diff --git a/src/Components/Endpoints/src/DependencyInjection/ServerComponentSerializer.cs b/src/Components/Endpoints/src/DependencyInjection/ServerComponentSerializer.cs index 7fa6d460da26..39b6e137a290 100644 --- a/src/Components/Endpoints/src/DependencyInjection/ServerComponentSerializer.cs +++ b/src/Components/Endpoints/src/DependencyInjection/ServerComponentSerializer.cs @@ -18,10 +18,10 @@ public ServerComponentSerializer(IDataProtectionProvider dataProtectionProvider) .CreateProtector(ServerComponentSerializationSettings.DataProtectionProviderPurpose) .ToTimeLimitedDataProtector(); - public ServerComponentMarker SerializeInvocation(ServerComponentInvocationSequence invocationId, Type type, ParameterView parameters, bool prerendered) + public ServerComponentMarker SerializeInvocation(ServerComponentInvocationSequence invocationId, Type type, ParameterView parameters, string key, bool prerendered) { var (sequence, serverComponent) = CreateSerializedServerComponent(invocationId, type, parameters); - return prerendered ? ServerComponentMarker.Prerendered(sequence, serverComponent) : ServerComponentMarker.NonPrerendered(sequence, serverComponent); + return prerendered ? ServerComponentMarker.Prerendered(sequence, serverComponent, key) : ServerComponentMarker.NonPrerendered(sequence, serverComponent, key); } private (int sequence, string payload) CreateSerializedServerComponent( diff --git a/src/Components/Endpoints/src/DependencyInjection/WebAssemblyComponentSerializer.cs b/src/Components/Endpoints/src/DependencyInjection/WebAssemblyComponentSerializer.cs index 3ed0e22f752a..e8b8e2a0d145 100644 --- a/src/Components/Endpoints/src/DependencyInjection/WebAssemblyComponentSerializer.cs +++ b/src/Components/Endpoints/src/DependencyInjection/WebAssemblyComponentSerializer.cs @@ -8,7 +8,7 @@ namespace Microsoft.AspNetCore.Components.Endpoints; // See the details of the component serialization protocol in WebAssemblyComponentDeserializer.cs on the Components solution. internal sealed class WebAssemblyComponentSerializer { - public static WebAssemblyComponentMarker SerializeInvocation(Type type, ParameterView parameters, bool prerendered) + public static WebAssemblyComponentMarker SerializeInvocation(Type type, ParameterView parameters, string? key, bool prerendered) { var assembly = type.Assembly.GetName().Name ?? throw new InvalidOperationException("Cannot prerender components from assemblies with a null name"); var typeFullName = type.FullName ?? throw new InvalidOperationException("Cannot prerender component types with a null name"); @@ -19,8 +19,8 @@ public static WebAssemblyComponentMarker SerializeInvocation(Type type, Paramete var serializedDefinitions = Convert.ToBase64String(JsonSerializer.SerializeToUtf8Bytes(definitions, WebAssemblyComponentSerializationSettings.JsonSerializationOptions)); var serializedValues = Convert.ToBase64String(JsonSerializer.SerializeToUtf8Bytes(values, WebAssemblyComponentSerializationSettings.JsonSerializationOptions)); - return prerendered ? WebAssemblyComponentMarker.Prerendered(assembly, typeFullName, serializedDefinitions, serializedValues) : - WebAssemblyComponentMarker.NonPrerendered(assembly, typeFullName, serializedDefinitions, serializedValues); + return prerendered ? WebAssemblyComponentMarker.Prerendered(assembly, typeFullName, serializedDefinitions, serializedValues, key) : + WebAssemblyComponentMarker.NonPrerendered(assembly, typeFullName, serializedDefinitions, serializedValues, key); } internal static void AppendPreamble(TextWriter writer, WebAssemblyComponentMarker record) diff --git a/src/Components/Endpoints/src/Rendering/EndpointHtmlRenderer.Streaming.cs b/src/Components/Endpoints/src/Rendering/EndpointHtmlRenderer.Streaming.cs index 6301b123cdc4..4316b745b691 100644 --- a/src/Components/Endpoints/src/Rendering/EndpointHtmlRenderer.Streaming.cs +++ b/src/Components/Endpoints/src/Rendering/EndpointHtmlRenderer.Streaming.cs @@ -185,7 +185,14 @@ private static void HandleNavigationAfterResponseStarted(TextWriter writer, stri protected override void WriteComponentHtml(int componentId, TextWriter output) => WriteComponentHtml(componentId, output, allowBoundaryMarkers: true); - private void WriteComponentHtml(int componentId, TextWriter output, bool allowBoundaryMarkers) + protected override void RenderChildComponent(TextWriter output, ref RenderTreeFrame componentFrame) + { + var componentId = componentFrame.ComponentId; + var sequenceAndKey = new SequenceAndKey(componentFrame.Sequence, componentFrame.ComponentKey); + WriteComponentHtml(componentId, output, allowBoundaryMarkers: true, sequenceAndKey); + } + + private void WriteComponentHtml(int componentId, TextWriter output, bool allowBoundaryMarkers, SequenceAndKey sequenceAndKey = default) { _visitedComponentIdsInCurrentStreamingBatch?.Add(componentId); @@ -198,9 +205,8 @@ private void WriteComponentHtml(int componentId, TextWriter output, bool allowBo // It may be better to use a custom element like [prerendered] // so it's easier for the JS code to react automatically whenever this gets inserted or updated during // streaming SSR or progressively-enhanced navigation. - var (serverMarker, webAssemblyMarker) = componentState.Component is SSRRenderModeBoundary boundary - ? boundary.ToMarkers(_httpContext) + ? boundary.ToMarkers(_httpContext, sequenceAndKey.Sequence, sequenceAndKey.Key) : default; if (serverMarker.HasValue) @@ -246,4 +252,5 @@ private void WriteComponentHtml(int componentId, TextWriter output, bool allowBo } private readonly record struct ComponentIdAndDepth(int ComponentId, int Depth); + private readonly record struct SequenceAndKey(int Sequence, object? Key); } diff --git a/src/Components/Endpoints/src/Rendering/SSRRenderModeBoundary.cs b/src/Components/Endpoints/src/Rendering/SSRRenderModeBoundary.cs index 26e639d856ce..aae553da694c 100644 --- a/src/Components/Endpoints/src/Rendering/SSRRenderModeBoundary.cs +++ b/src/Components/Endpoints/src/Rendering/SSRRenderModeBoundary.cs @@ -1,6 +1,10 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +using System.Collections.Concurrent; +using System.Globalization; +using System.Security.Cryptography; +using System.Text; using Microsoft.AspNetCore.Components.Rendering; using Microsoft.AspNetCore.Components.Web; using Microsoft.AspNetCore.Http; @@ -14,11 +18,14 @@ namespace Microsoft.AspNetCore.Components.Endpoints; /// internal class SSRRenderModeBoundary : IComponent { + private static readonly ConcurrentDictionary _componentTypeNameHashCache = new(); + private readonly Type _componentType; private readonly IComponentRenderMode _renderMode; private readonly bool _prerender; private RenderHandle _renderHandle; private IReadOnlyDictionary? _latestParameters; + private string? _markerKey; public SSRRenderModeBoundary(Type componentType, IComponentRenderMode renderMode) { @@ -92,8 +99,12 @@ private void Prerender(RenderTreeBuilder builder) builder.CloseComponent(); } - public (ServerComponentMarker?, WebAssemblyComponentMarker?) ToMarkers(HttpContext httpContext) + public (ServerComponentMarker?, WebAssemblyComponentMarker?) ToMarkers(HttpContext httpContext, int sequence, object? key) { + // We expect that the '@key' and sequence number shouldn't change for a given component instance, + // so we lazily compute the marker key once. + _markerKey ??= GenerateMarkerKey(sequence, key); + var parameters = _latestParameters is null ? ParameterView.Empty : ParameterView.FromDictionary((IDictionary)_latestParameters); @@ -106,15 +117,41 @@ private void Prerender(RenderTreeBuilder builder) var serverComponentSerializer = httpContext.RequestServices.GetRequiredService(); var invocationId = EndpointHtmlRenderer.GetOrCreateInvocationId(httpContext); - serverMarker = serverComponentSerializer.SerializeInvocation(invocationId, _componentType, parameters, _prerender); + serverMarker = serverComponentSerializer.SerializeInvocation(invocationId, _componentType, parameters, _markerKey, _prerender); } WebAssemblyComponentMarker? webAssemblyMarker = null; if (_renderMode is WebAssemblyRenderMode or AutoRenderMode) { - webAssemblyMarker = WebAssemblyComponentSerializer.SerializeInvocation(_componentType, parameters, _prerender); + webAssemblyMarker = WebAssemblyComponentSerializer.SerializeInvocation(_componentType, parameters, _markerKey, _prerender); } return (serverMarker, webAssemblyMarker); } + + private string GenerateMarkerKey(int sequence, object? key) + { + var componentTypeNameHash = _componentTypeNameHashCache.GetOrAdd(_componentType, ComputeComponentTypeNameHash); + return $"{componentTypeNameHash}:{sequence}:{(key as IFormattable)?.ToString(null, CultureInfo.InvariantCulture)}"; + } + + private static string ComputeComponentTypeNameHash(Type componentType) + { + if (componentType.FullName is not { } typeName) + { + throw new InvalidOperationException($"An invalid component type was used in {nameof(SSRRenderModeBoundary)}."); + } + + var typeNameLength = typeName.Length; + var typeNameBytes = typeNameLength < 1024 + ? stackalloc byte[typeNameLength] + : new byte[typeNameLength]; + + Encoding.UTF8.GetBytes(typeName, typeNameBytes); + + Span typeNameHashBytes = stackalloc byte[SHA1.HashSizeInBytes]; + SHA1.HashData(typeNameBytes, typeNameHashBytes); + + return Convert.ToHexString(typeNameHashBytes); + } } diff --git a/src/Components/Server/src/Circuits/CircuitFactory.cs b/src/Components/Server/src/Circuits/CircuitFactory.cs index 08bcc72673d1..7fce7503f35b 100644 --- a/src/Components/Server/src/Circuits/CircuitFactory.cs +++ b/src/Components/Server/src/Circuits/CircuitFactory.cs @@ -64,12 +64,14 @@ public async ValueTask CreateCircuitHostAsync( var appLifetime = scope.ServiceProvider.GetRequiredService(); await appLifetime.RestoreStateAsync(store); + var serverComponentDeserializer = scope.ServiceProvider.GetRequiredService(); var jsComponentInterop = new CircuitJSComponentInterop(_options); var renderer = new RemoteRenderer( scope.ServiceProvider, _loggerFactory, _options, client, + serverComponentDeserializer, _loggerFactory.CreateLogger(), jsRuntime, jsComponentInterop); diff --git a/src/Components/Server/src/Circuits/IServerComponentDeserializer.cs b/src/Components/Server/src/Circuits/IServerComponentDeserializer.cs index d51fdf8e090e..70a6d25ade9f 100644 --- a/src/Components/Server/src/Circuits/IServerComponentDeserializer.cs +++ b/src/Components/Server/src/Circuits/IServerComponentDeserializer.cs @@ -1,6 +1,8 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +using System.Diagnostics.CodeAnalysis; + namespace Microsoft.AspNetCore.Components.Server; internal interface IServerComponentDeserializer @@ -8,4 +10,6 @@ internal interface IServerComponentDeserializer bool TryDeserializeComponentDescriptorCollection( string serializedComponentRecords, out List descriptors); + + bool TryDeserializeSingleComponentDescriptor(ServerComponentMarker record, [NotNullWhen(true)] out ComponentDescriptor? result); } diff --git a/src/Components/Server/src/Circuits/RemoteRenderer.cs b/src/Components/Server/src/Circuits/RemoteRenderer.cs index 7afb72deec82..240aafe3fee1 100644 --- a/src/Components/Server/src/Circuits/RemoteRenderer.cs +++ b/src/Components/Server/src/Circuits/RemoteRenderer.cs @@ -3,7 +3,9 @@ using System.Collections.Concurrent; using System.Diagnostics.CodeAnalysis; +using System.Globalization; using System.Linq; +using System.Text.Json; using Microsoft.AspNetCore.Components.RenderTree; using Microsoft.AspNetCore.Components.Web; using Microsoft.AspNetCore.SignalR; @@ -21,6 +23,7 @@ internal partial class RemoteRenderer : WebRenderer private readonly CircuitClientProxy _client; private readonly CircuitOptions _options; + private readonly IServerComponentDeserializer _serverComponentDeserializer; private readonly ILogger _logger; internal readonly ConcurrentQueue _unacknowledgedRenderBatches = new ConcurrentQueue(); private long _nextRenderId = 1; @@ -39,6 +42,7 @@ public RemoteRenderer( ILoggerFactory loggerFactory, CircuitOptions options, CircuitClientProxy client, + IServerComponentDeserializer serverComponentDeserializer, ILogger logger, RemoteJSRuntime jsRuntime, CircuitJSComponentInterop jsComponentInterop) @@ -46,6 +50,7 @@ public RemoteRenderer( { _client = client; _options = options; + _serverComponentDeserializer = serverComponentDeserializer; _logger = logger; ElementReferenceContext = jsRuntime.ElementReferenceContext; @@ -59,12 +64,90 @@ public Task AddComponentAsync(Type componentType, ParameterView parameters, stri return RenderRootComponentAsync(componentId, parameters); } + protected override int GetWebRendererId() => (int)WebRendererId.Server; + protected override void AttachRootComponentToBrowser(int componentId, string domElementSelector) { var attachComponentTask = _client.SendAsync("JS.AttachComponent", componentId, domElementSelector); _ = CaptureAsyncExceptions(attachComponentTask); } + protected override void UpdateRootComponents(string operationsJson) + { + var operations = JsonSerializer.Deserialize>>( + operationsJson, + ServerComponentSerializationSettings.JsonSerializationOptions); + + foreach (var operation in operations) + { + switch (operation.Type) + { + case RootComponentOperationType.Add: + AddRootComponent(operation); + break; + case RootComponentOperationType.Update: + UpdateRootComponent(operation); + break; + case RootComponentOperationType.Remove: + RemoveRootComponent(operation); + break; + } + } + + return; + + void AddRootComponent(RootComponentOperation operation) + { + if (operation.SelectorId is not { } selectorId) + { + Log.InvalidRootComponentOperation(_logger, operation.Type, message: "Missing selector ID."); + return; + } + + if (!_serverComponentDeserializer.TryDeserializeSingleComponentDescriptor(operation.Marker, out var descriptor)) + { + throw new InvalidOperationException("Failed to deserialize a component descriptor when adding a new root component."); + } + + _ = AddComponentAsync(descriptor.ComponentType, descriptor.Parameters, selectorId.ToString(CultureInfo.InvariantCulture)); + } + + void UpdateRootComponent(RootComponentOperation operation) + { + if (operation.ComponentId is not { } componentId) + { + Log.InvalidRootComponentOperation(_logger, operation.Type, message: "Missing component ID."); + return; + } + + var componentState = GetComponentState(componentId); + + if (!_serverComponentDeserializer.TryDeserializeSingleComponentDescriptor(operation.Marker, out var descriptor)) + { + throw new InvalidOperationException("Failed to deserialize a component descriptor when updating an existing root component."); + } + + if (descriptor.ComponentType != componentState.Component.GetType()) + { + Log.InvalidRootComponentOperation(_logger, operation.Type, message: "Component type mismatch."); + return; + } + + _ = RenderRootComponentAsync(componentId, descriptor.Parameters); + } + + void RemoveRootComponent(RootComponentOperation operation) + { + if (operation.ComponentId is not { } componentId) + { + Log.InvalidRootComponentOperation(_logger, operation.Type, message: "Missing component ID."); + return; + } + + this.RemoveRootComponent(componentId); + } + } + protected override void ProcessPendingRender() { if (_unacknowledgedRenderBatches.Count >= _options.MaxBufferedUnacknowledgedRenderBatches) @@ -388,6 +471,9 @@ public static void CompletingBatchWithoutError(ILogger logger, long batchId, Tim [LoggerMessage(107, LogLevel.Debug, "The queue of unacknowledged render batches is full.", EventName = "FullUnacknowledgedRenderBatchesQueue")] public static partial void FullUnacknowledgedRenderBatchesQueue(ILogger logger); + + [LoggerMessage(108, LogLevel.Debug, "The root component operation of type '{OperationType}' was invalid: {Message}", EventName = "InvalidRootComponentOperation")] + public static partial void InvalidRootComponentOperation(ILogger logger, RootComponentOperationType operationType, string message); } } diff --git a/src/Components/Server/src/Circuits/ServerComponentDeserializer.cs b/src/Components/Server/src/Circuits/ServerComponentDeserializer.cs index dc0d63f53b8f..3e070d548a74 100644 --- a/src/Components/Server/src/Circuits/ServerComponentDeserializer.cs +++ b/src/Components/Server/src/Circuits/ServerComponentDeserializer.cs @@ -1,6 +1,7 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +using System.Diagnostics.CodeAnalysis; using System.Text; using System.Text.Json; using Microsoft.AspNetCore.DataProtection; @@ -60,6 +61,13 @@ internal sealed partial class ServerComponentDeserializer : IServerComponentDese private readonly RootComponentTypeCache _rootComponentTypeCache; private readonly ComponentParameterDeserializer _parametersDeserializer; + // The following fields are only used in TryDeserializeSingleComponentDescriptor. + // The TryDeserializeComponentDescriptorCollection method uses a stateless + // approach to efficiently detect invalid component records. + private readonly HashSet _expiredInvocationIds = new(); + private readonly HashSet _seenSequenceNumbersForCurrentInvocation = new(); + private Guid? _currentInvocationId; + public ServerComponentDeserializer( IDataProtectionProvider dataProtectionProvider, ILogger logger, @@ -91,16 +99,9 @@ public bool TryDeserializeComponentDescriptorCollection(string serializedCompone var previousInstance = new ServerComponent(); foreach (var marker in markers) { - if (marker.Type != ServerComponentMarker.ServerMarkerType) - { - Log.InvalidMarkerType(_logger, marker.Type); - descriptors.Clear(); - return false; - } - - if (marker.Descriptor == null) + if (!IsWellFormedServerComponent(marker)) { - Log.MissingMarkerDescriptor(_logger); + // The client sent us a marker with missing or obviously incorrect info. descriptors.Clear(); return false; } @@ -147,6 +148,75 @@ public bool TryDeserializeComponentDescriptorCollection(string serializedCompone return true; } + public bool TryDeserializeSingleComponentDescriptor(ServerComponentMarker record, [NotNullWhen(true)] out ComponentDescriptor? result) + { + result = default; + + if (!IsWellFormedServerComponent(record)) + { + // The client sent us a marker with missing or obviously incorrect info. + return false; + } + + var (descriptor, serverComponent) = DeserializeServerComponent(record); + if (descriptor is null) + { + // We failed to deserialize the component descriptor for some reason. + return false; + } + + // We're seeing a different invocation ID than we did the last time we processed a component. + // There are two possibilities: + // [1] A new invocation has started, in which case we should stop accepting components from the previous one. + // [2] The client is attempting to use an already-expired invocation ID. We should reject the component in + // this case because we only want to accept components from the current invocation. + if (serverComponent.InvocationId != _currentInvocationId) + { + if (_expiredInvocationIds.Contains(serverComponent.InvocationId)) + { + Log.ExpiredInvocationId(_logger, serverComponent.InvocationId.ToString("N")); + return false; + } + + if (_currentInvocationId.HasValue) + { + _expiredInvocationIds.Add(_currentInvocationId.Value); + } + + _currentInvocationId = serverComponent.InvocationId; + _seenSequenceNumbersForCurrentInvocation.Clear(); + } + + // We've already seen this sequence number for this invocation. We fail to avoid processing the same + // component twice. + if (_seenSequenceNumbersForCurrentInvocation.Contains(serverComponent.Sequence)) + { + Log.ReusedDescriptorSequence(_logger, serverComponent.Sequence, serverComponent.InvocationId.ToString("N")); + return false; + } + + _seenSequenceNumbersForCurrentInvocation.Add(serverComponent.Sequence); + result = descriptor; + return true; + } + + private bool IsWellFormedServerComponent(ServerComponentMarker record) + { + if (record.Type != ServerComponentMarker.ServerMarkerType) + { + Log.InvalidMarkerType(_logger, record.Type); + return false; + } + + if (record.Descriptor == null) + { + Log.MissingMarkerDescriptor(_logger); + return false; + } + + return true; + } + private (ComponentDescriptor, ServerComponent) DeserializeServerComponent(ServerComponentMarker record) { string unprotected; @@ -225,5 +295,11 @@ private static partial class Log [LoggerMessage(8, LogLevel.Debug, "The descriptor sequence '{sequence}' is an invalid start sequence.", EventName = "DescriptorSequenceMustStartAtZero")] public static partial void DescriptorSequenceMustStartAtZero(ILogger logger, int sequence); + + [LoggerMessage(9, LogLevel.Debug, "The descriptor invocationId '{invocationId}' has expired.", EventName = "ExpiredInvocationId")] + public static partial void ExpiredInvocationId(ILogger logger, string invocationId); + + [LoggerMessage(10, LogLevel.Debug, "The descriptor with sequence '{sequence}' was already used for the current invocationId '{invocationId}'.", EventName = "ReusedDescriptorSequence")] + public static partial void ReusedDescriptorSequence(ILogger logger, int sequence, string invocationId); } } diff --git a/src/Components/Server/src/Microsoft.AspNetCore.Components.Server.csproj b/src/Components/Server/src/Microsoft.AspNetCore.Components.Server.csproj index b8e3ce92ee76..013c6affc0d6 100644 --- a/src/Components/Server/src/Microsoft.AspNetCore.Components.Server.csproj +++ b/src/Components/Server/src/Microsoft.AspNetCore.Components.Server.csproj @@ -59,8 +59,11 @@ + + + diff --git a/src/Components/Server/test/Circuits/CircuitHostTest.cs b/src/Components/Server/test/Circuits/CircuitHostTest.cs index d41485e5a1b0..268411896769 100644 --- a/src/Components/Server/test/Circuits/CircuitHostTest.cs +++ b/src/Components/Server/test/Circuits/CircuitHostTest.cs @@ -1,6 +1,7 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +using System.Diagnostics.CodeAnalysis; using System.Reflection; using Microsoft.AspNetCore.DataProtection; using Microsoft.AspNetCore.SignalR; @@ -441,6 +442,7 @@ public TestRemoteRenderer(IServiceProvider serviceProvider, IClientProxy client) NullLoggerFactory.Instance, new CircuitOptions(), new CircuitClientProxy(client, "connection"), + new TestServerComponentDeserializer(), NullLogger.Instance, CreateJSRuntime(new CircuitOptions()), new CircuitJSComponentInterop(new CircuitOptions())) @@ -569,4 +571,19 @@ public async ValueTask DisposeAsync() } } } + + private class TestServerComponentDeserializer : IServerComponentDeserializer + { + public bool TryDeserializeComponentDescriptorCollection(string serializedComponentRecords, out List descriptors) + { + descriptors = default; + return true; + } + + public bool TryDeserializeSingleComponentDescriptor(ServerComponentMarker record, [NotNullWhen(true)] out ComponentDescriptor result) + { + result = default; + return true; + } + } } diff --git a/src/Components/Server/test/Circuits/ComponentHubTest.cs b/src/Components/Server/test/Circuits/ComponentHubTest.cs index ba2084047143..274080dae1a8 100644 --- a/src/Components/Server/test/Circuits/ComponentHubTest.cs +++ b/src/Components/Server/test/Circuits/ComponentHubTest.cs @@ -1,6 +1,7 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +using System.Diagnostics.CodeAnalysis; using System.Security.Claims; using System.Text.RegularExpressions; using Microsoft.AspNetCore.Components.Server.Circuits; @@ -168,6 +169,12 @@ public bool TryDeserializeComponentDescriptorCollection(string serializedCompone descriptors = default; return true; } + + public bool TryDeserializeSingleComponentDescriptor(ServerComponentMarker record, [NotNullWhen(true)] out ComponentDescriptor result) + { + result = default; + return true; + } } private class TestCircuitFactory : ICircuitFactory diff --git a/src/Components/Server/test/Circuits/RemoteRendererTest.cs b/src/Components/Server/test/Circuits/RemoteRendererTest.cs index 0392add99ccc..b2ae972e4b18 100644 --- a/src/Components/Server/test/Circuits/RemoteRendererTest.cs +++ b/src/Components/Server/test/Circuits/RemoteRendererTest.cs @@ -2,8 +2,12 @@ // The .NET Foundation licenses this file to you under the MIT license. using System.Diagnostics; +using System.Text.Json; +using Microsoft.AspNetCore.Components.Endpoints; +using Microsoft.AspNetCore.Components.Rendering; using Microsoft.AspNetCore.Components.Server; using Microsoft.AspNetCore.Components.Server.Circuits; +using Microsoft.AspNetCore.DataProtection; using Microsoft.AspNetCore.SignalR; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; @@ -20,6 +24,9 @@ public class RemoteRendererTest // failures. private static readonly TimeSpan Timeout = Debugger.IsAttached ? System.Threading.Timeout.InfiniteTimeSpan : TimeSpan.FromSeconds(10); + private readonly IDataProtectionProvider _ephemeralDataProtectionProvider = new EphemeralDataProtectionProvider(); + private readonly ServerComponentInvocationSequence _invocationSequence = new(); + [Fact] public void WritesAreBufferedWhenTheClientIsOffline() { @@ -419,6 +426,239 @@ await renderer.Dispatcher.InvokeAsync(() => renderer.RenderComponentAsync + { + Type = RootComponentOperationType.Add, + SelectorId = 1, + Marker = CreateMarker(typeof(DynamicallyAddedComponent), new() + { + [nameof(DynamicallyAddedComponent.Message)] = expectedMessage, + }), + }; + var operationsJson = JsonSerializer.Serialize( + new[] { operation }, + ServerComponentSerializationSettings.JsonSerializationOptions); + + // Act + await renderer.Dispatcher.InvokeAsync(() => renderer.UpdateRootComponents(operationsJson)); + var componentState = renderer.GetComponentState(0); + + // Assert + var component = Assert.IsType(componentState.Component); + Assert.Equal(expectedMessage, component.Message); + } + + [Fact] + public async Task UpdateRootComponents_DoesNotAddNewRootComponent_WhenSelectorIdIsMissing() + { + // Arrange + var serviceProvider = CreateServiceProvider(); + var renderer = GetRemoteRenderer(serviceProvider); + var operation = new RootComponentOperation + { + Type = RootComponentOperationType.Add, + Marker = CreateMarker(typeof(DynamicallyAddedComponent)), + }; + var operationsJson = JsonSerializer.Serialize( + new[] { operation }, + ServerComponentSerializationSettings.JsonSerializationOptions); + + // Act + await renderer.Dispatcher.InvokeAsync(() => renderer.UpdateRootComponents(operationsJson)); + renderer.UpdateRootComponents(operationsJson); + + // Assert + var ex = Assert.Throws(() => renderer.GetComponentState(0)); + Assert.StartsWith("The renderer does not have a component with ID", ex.Message); + } + + [Fact] + public async Task UpdateRootComponents_Throws_WhenAddingComponentFromInvalidDescriptor() + { + // Arrange + var serviceProvider = CreateServiceProvider(); + var renderer = GetRemoteRenderer(serviceProvider); + var operation = new RootComponentOperation + { + Type = RootComponentOperationType.Add, + SelectorId = 1, + Marker = new ServerComponentMarker() + { + Descriptor = "some random text", + }, + }; + var operationsJson = JsonSerializer.Serialize( + new[] { operation }, + ServerComponentSerializationSettings.JsonSerializationOptions); + + // Act + var task = renderer.Dispatcher.InvokeAsync(() => renderer.UpdateRootComponents(operationsJson)); + + // Assert + var ex = await Assert.ThrowsAsync(async () => await task); + Assert.StartsWith("Failed to deserialize a component descriptor when adding", ex.Message); + } + + [Fact] + public async Task UpdateRootComponents_CanUpdateExistingRootComponent() + { + // Arrange + var serviceProvider = CreateServiceProvider(); + var renderer = GetRemoteRenderer(serviceProvider); + var component = new DynamicallyAddedComponent() + { + Message = "Existing message", + }; + var expectedMessage = "Updated message"; + var componentId = renderer.AssignRootComponentId(component); + var operation = new RootComponentOperation + { + Type = RootComponentOperationType.Update, + ComponentId = componentId, + Marker = CreateMarker(typeof(DynamicallyAddedComponent), new() + { + [nameof(DynamicallyAddedComponent.Message)] = expectedMessage, + }), + }; + var operationsJson = JsonSerializer.Serialize( + new[] { operation }, + ServerComponentSerializationSettings.JsonSerializationOptions); + + // Act + await renderer.Dispatcher.InvokeAsync(() => renderer.UpdateRootComponents(operationsJson)); + + // Assert + Assert.Equal(expectedMessage, component.Message); + } + + [Fact] + public async Task UpdateRootComponents_DoesNotUpdateExistingRootComponent_WhenComponentIdIsMissing() + { + // Arrange + var serviceProvider = CreateServiceProvider(); + var renderer = GetRemoteRenderer(serviceProvider); + var expectedMessage = "Existing message"; + var component = new DynamicallyAddedComponent() + { + Message = expectedMessage, + }; + var componentId = renderer.AssignRootComponentId(component); + var operation = new RootComponentOperation + { + Type = RootComponentOperationType.Update, + Marker = CreateMarker(typeof(DynamicallyAddedComponent), new() + { + [nameof(DynamicallyAddedComponent.Message)] = "Some other message", + }), + }; + var operationsJson = JsonSerializer.Serialize( + new[] { operation }, + ServerComponentSerializationSettings.JsonSerializationOptions); + + // Act + await renderer.Dispatcher.InvokeAsync(() => renderer.UpdateRootComponents(operationsJson)); + + // Assert + Assert.Equal(expectedMessage, component.Message); + } + + [Fact] + public async Task UpdateRootComponents_DoesNotUpdateExistingRootComponent_WhenDescriptorComponentTypeDoesNotMatchRootComponentType() + { + // Arrange + var serviceProvider = CreateServiceProvider(); + var renderer = GetRemoteRenderer(serviceProvider); + var expectedMessage = "Existing message"; + var component1 = new DynamicallyAddedComponent() + { + Message = expectedMessage, + }; + var component2 = new TestComponent(); + var component1Id = renderer.AssignRootComponentId(component1); + var component2Id = renderer.AssignRootComponentId(component2); + var operation = new RootComponentOperation + { + Type = RootComponentOperationType.Update, + ComponentId = component1Id, + Marker = CreateMarker(typeof(TestComponent) /* Note the incorrect component type */, new() + { + [nameof(DynamicallyAddedComponent.Message)] = "Updated message", + }), + }; + var operationsJson = JsonSerializer.Serialize( + new[] { operation }, + ServerComponentSerializationSettings.JsonSerializationOptions); + + // Act + await renderer.Dispatcher.InvokeAsync(() => renderer.UpdateRootComponents(operationsJson)); + + // Assert + Assert.Equal(expectedMessage, component1.Message); + } + + [Fact] + public async Task UpdateRootComponents_Throws_WhenUpdatingComponentFromInvalidDescriptor() + { + // Arrange + var serviceProvider = CreateServiceProvider(); + var renderer = GetRemoteRenderer(serviceProvider); + var component = new DynamicallyAddedComponent() + { + Message = "Existing message", + }; + var componentId = renderer.AssignRootComponentId(component); + var operation = new RootComponentOperation + { + Type = RootComponentOperationType.Update, + ComponentId = componentId, + Marker = new() + { + Descriptor = "some random text", + }, + }; + var operationsJson = JsonSerializer.Serialize( + new[] { operation }, + ServerComponentSerializationSettings.JsonSerializationOptions); + + // Act + var task = renderer.Dispatcher.InvokeAsync(() => renderer.UpdateRootComponents(operationsJson)); + + // Assert + var ex = await Assert.ThrowsAsync(async () => await task); + Assert.StartsWith("Failed to deserialize a component descriptor when updating", ex.Message); + } + + [Fact] + public async Task UpdateRootComponents_CanRemoveExistingRootComponent() + { + // Arrange + var serviceProvider = CreateServiceProvider(); + var renderer = GetRemoteRenderer(serviceProvider); + var component = new DynamicallyAddedComponent(); + var componentId = renderer.AssignRootComponentId(component); + var operation = new RootComponentOperation + { + Type = RootComponentOperationType.Remove, + ComponentId = componentId, + }; + var operationsJson = JsonSerializer.Serialize( + new[] { operation }, + ServerComponentSerializationSettings.JsonSerializationOptions); + + // Act + await renderer.Dispatcher.InvokeAsync(() => renderer.UpdateRootComponents(operationsJson)); + + // Assert + await component.WaitForDisposeAsync().WaitAsync(Timeout); // Will timeout and throw if not disposed + } + private IServiceProvider CreateServiceProvider() { var serviceCollection = new ServiceCollection(); @@ -428,18 +668,38 @@ private IServiceProvider CreateServiceProvider() private TestRemoteRenderer GetRemoteRenderer(IServiceProvider serviceProvider, CircuitClientProxy circuitClient = null) { + var serverComponentDeserializer = new ServerComponentDeserializer( + _ephemeralDataProtectionProvider, + NullLogger.Instance, + new RootComponentTypeCache(), + new ComponentParameterDeserializer( + NullLogger.Instance, + new ComponentParametersTypeCache())); + return new TestRemoteRenderer( serviceProvider, NullLoggerFactory.Instance, new CircuitOptions(), circuitClient ?? new CircuitClientProxy(), + serverComponentDeserializer, NullLogger.Instance); } + private ServerComponentMarker CreateMarker(Type type, Dictionary parameters = null) + { + var serializer = new ServerComponentSerializer(_ephemeralDataProtectionProvider); + return serializer.SerializeInvocation( + _invocationSequence, + type, + parameters is null ? ParameterView.Empty : ParameterView.FromDictionary(parameters), + null, + false); + } + private class TestRemoteRenderer : RemoteRenderer { - public TestRemoteRenderer(IServiceProvider serviceProvider, ILoggerFactory loggerFactory, CircuitOptions options, CircuitClientProxy client, ILogger logger) - : base(serviceProvider, loggerFactory, options, client, logger, CreateJSRuntime(options), new CircuitJSComponentInterop(options)) + public TestRemoteRenderer(IServiceProvider serviceProvider, ILoggerFactory loggerFactory, CircuitOptions options, CircuitClientProxy client, IServerComponentDeserializer serverComponentDeserializer, ILogger logger) + : base(serviceProvider, loggerFactory, options, client, serverComponentDeserializer, logger, CreateJSRuntime(options), new CircuitJSComponentInterop(options)) { } @@ -450,6 +710,20 @@ public async Task RenderComponentAsync(ParameterView initialParamete await RenderRootComponentAsync(componentId, initialParameters); } + protected override void AttachRootComponentToBrowser(int componentId, string domElementSelector) + { + } + + public new void UpdateRootComponents(string operationsJson) + { + base.UpdateRootComponents(operationsJson); + } + + public new ComponentState GetComponentState(int componentId) + { + return base.GetComponentState(componentId); + } + private static RemoteJSRuntime CreateJSRuntime(CircuitOptions options) => new RemoteJSRuntime(Options.Create(options), Options.Create(new HubOptions()), null); } @@ -536,4 +810,48 @@ public void TriggerRender() Component.TriggerRender(); } } + + private class DynamicallyAddedComponent : IComponent, IDisposable + { + private readonly TaskCompletionSource _disposeTcs = new(); + private RenderHandle _renderHandle; + + [Parameter] + public string Message { get; set; } = "Default message"; + + private void Render(RenderTreeBuilder builder) + { + builder.AddContent(0, Message); + } + + public void Attach(RenderHandle renderHandle) + { + _renderHandle = renderHandle; + } + + public Task SetParametersAsync(ParameterView parameters) + { + if (parameters.TryGetValue(nameof(Message), out var message)) + { + Message = message; + } + + TriggerRender(); + return Task.CompletedTask; + } + + public void TriggerRender() + { + var task = _renderHandle.Dispatcher.InvokeAsync(() => _renderHandle.Render(Render)); + Assert.True(task.IsCompletedSuccessfully); + } + + public Task WaitForDisposeAsync() + => _disposeTcs.Task; + + public void Dispose() + { + _disposeTcs.SetResult(); + } + } } diff --git a/src/Components/Server/test/Circuits/ServerComponentDeserializerTest.cs b/src/Components/Server/test/Circuits/ServerComponentDeserializerTest.cs index 0957f67358cc..07550a582fcd 100644 --- a/src/Components/Server/test/Circuits/ServerComponentDeserializerTest.cs +++ b/src/Components/Server/test/Circuits/ServerComponentDeserializerTest.cs @@ -12,7 +12,7 @@ public class ServerComponentDeserializerTest { private readonly IDataProtectionProvider _ephemeralDataProtectionProvider; private readonly ITimeLimitedDataProtector _protector; - private readonly ServerComponentInvocationSequence _invocationSequence = new ServerComponentInvocationSequence(); + private ServerComponentInvocationSequence _invocationSequence = new(); public ServerComponentDeserializerTest() { @@ -303,6 +303,97 @@ public void DoesNotParseMarkersWithInvalidDescriptorPayloads() Assert.Empty(descriptors); } + [Fact] + public void TryDeserializeSingleComponentDescriptor_CanParseSingleMarker() + { + // Arrange + var markers = CreateMarkers(typeof(TestComponent)); + var serverComponentDeserializer = CreateServerComponentDeserializer(); + + // Act & assert + Assert.True(serverComponentDeserializer.TryDeserializeSingleComponentDescriptor(markers[0], out var descriptor)); + Assert.Equal(typeof(TestComponent).FullName, descriptor.ComponentType.FullName); + Assert.Equal(0, descriptor.Sequence); + } + + [Fact] + public void TryDeserializeSingleComponentDescriptor_CanParseMultipleMarkersWithAndWithoutParameters() + { + // Arrange + var markers = CreateMarkers( + (typeof(TestComponent), new Dictionary { ["First"] = "Value" }), + (typeof(TestComponent), null)); + var serverComponentDeserializer = CreateServerComponentDeserializer(); + + // Act & assert + Assert.True(serverComponentDeserializer.TryDeserializeSingleComponentDescriptor(markers[0], out var firstDescriptor)); + Assert.True(serverComponentDeserializer.TryDeserializeSingleComponentDescriptor(markers[1], out var secondDescriptor)); + + Assert.Equal(typeof(TestComponent).FullName, firstDescriptor.ComponentType.FullName); + Assert.Equal(0, firstDescriptor.Sequence); + var firstParameters = firstDescriptor.Parameters.ToDictionary(); + Assert.Single(firstParameters); + Assert.Contains("First", firstParameters.Keys); + Assert.Equal("Value", firstParameters["First"]); + + Assert.Equal(typeof(TestComponent).FullName, secondDescriptor.ComponentType.FullName); + Assert.Equal(1, secondDescriptor.Sequence); + Assert.Empty(secondDescriptor.Parameters.ToDictionary()); + } + + [Fact] + public void TryDeserializeSingleComponentDescriptor_AllowsParsingMarkersOutOfOrder() + { + // Arrange + var markers = CreateMarkers(typeof(TestComponent), typeof(TestComponent)); + var serverComponentDeserializer = CreateServerComponentDeserializer(); + + // Act & assert + Assert.True(serverComponentDeserializer.TryDeserializeSingleComponentDescriptor(markers[1], out _)); + Assert.True(serverComponentDeserializer.TryDeserializeSingleComponentDescriptor(markers[0], out _)); + } + + [Fact] + public void TryDeserializeSingleComponentDescriptor_AllowsParsingMarkersFromMultipleInvocations() + { + // Arrange + var firstInvocationMarkers = CreateMarkers(typeof(TestComponent)); + StartNewInvocation(); + var secondInvocationMarkers = CreateMarkers(typeof(TestComponent)); + var serverComponentDeserializer = CreateServerComponentDeserializer(); + + // Act & assert + Assert.True(serverComponentDeserializer.TryDeserializeSingleComponentDescriptor(firstInvocationMarkers[0], out _)); + Assert.True(serverComponentDeserializer.TryDeserializeSingleComponentDescriptor(secondInvocationMarkers[0], out _)); + } + + [Fact] + public void TryDeserializeSingleComponentDescriptor_DoesNotParseTheSameMarkerTwice() + { + // Arrange + var markers = CreateMarkers(typeof(TestComponent)); + var serverComponentDeserializer = CreateServerComponentDeserializer(); + + // Act & assert + Assert.True(serverComponentDeserializer.TryDeserializeSingleComponentDescriptor(markers[0], out _)); + Assert.False(serverComponentDeserializer.TryDeserializeSingleComponentDescriptor(markers[0], out _)); + } + + [Fact] + public void TryDeserializeSingleComponentDescriptor_DoesNotParseMarkerFromOldInvocation() + { + // Arrange + var firstInvocationMarkers = CreateMarkers(typeof(TestComponent), typeof(TestComponent)); + StartNewInvocation(); + var secondInvocationMarkers = CreateMarkers(typeof(TestComponent)); + var serverComponentDeserializer = CreateServerComponentDeserializer(); + + // Act & assert + Assert.True(serverComponentDeserializer.TryDeserializeSingleComponentDescriptor(firstInvocationMarkers[0], out _)); + Assert.True(serverComponentDeserializer.TryDeserializeSingleComponentDescriptor(secondInvocationMarkers[0], out _)); + Assert.False(serverComponentDeserializer.TryDeserializeSingleComponentDescriptor(firstInvocationMarkers[0], out _)); + } + private string SerializeComponent(string assembly, string type) => JsonSerializer.Serialize( new ServerComponent(0, assembly, type, Array.Empty(), Array.Empty(), Guid.NewGuid()), @@ -326,7 +417,7 @@ private ServerComponentMarker[] CreateMarkers(params Type[] types) var markers = new ServerComponentMarker[types.Length]; for (var i = 0; i < types.Length; i++) { - markers[i] = serializer.SerializeInvocation(_invocationSequence, types[i], ParameterView.Empty, false); + markers[i] = serializer.SerializeInvocation(_invocationSequence, types[i], ParameterView.Empty, null, false); } return markers; @@ -343,6 +434,7 @@ private ServerComponentMarker[] CreateMarkers(params (Type, Dictionary throw new NotImplementedException(); diff --git a/src/Components/Server/test/Circuits/TestCircuitHost.cs b/src/Components/Server/test/Circuits/TestCircuitHost.cs index edfb90a417b5..c0b09cb45189 100644 --- a/src/Components/Server/test/Circuits/TestCircuitHost.cs +++ b/src/Components/Server/test/Circuits/TestCircuitHost.cs @@ -34,6 +34,7 @@ public static CircuitHost Create( serviceProvider .Setup(services => services.GetService(typeof(IJSRuntime))) .Returns(jsRuntime); + var serverComponentDeserializer = Mock.Of(); if (remoteRenderer == null) { @@ -42,6 +43,7 @@ public static CircuitHost Create( NullLoggerFactory.Instance, new CircuitOptions(), clientProxy, + serverComponentDeserializer, NullLogger.Instance, jsRuntime, new CircuitJSComponentInterop(new CircuitOptions())); diff --git a/src/Components/Shared/src/RootComponentOperation.cs b/src/Components/Shared/src/RootComponentOperation.cs new file mode 100644 index 000000000000..164552717aa7 --- /dev/null +++ b/src/Components/Shared/src/RootComponentOperation.cs @@ -0,0 +1,22 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +namespace Microsoft.AspNetCore.Components; + +internal sealed class RootComponentOperation +{ + // Represents the type of root component operation to perform. + public RootComponentOperationType Type { get; set; } + + // When adding a root component, this is the selector ID + // to round-trip back to the client so it knows which DOM + // element the component should be attached to. + public int? SelectorId { get; set; } + + // The ID of the component to use during an update or remove + // operation. + public int? ComponentId { get; set; } + + // The type of the marker that was initially rendered to the page. + public TMarker? Marker { get; set; } +} diff --git a/src/Components/Shared/src/RootComponentOperationType.cs b/src/Components/Shared/src/RootComponentOperationType.cs new file mode 100644 index 000000000000..e3335c6d8afa --- /dev/null +++ b/src/Components/Shared/src/RootComponentOperationType.cs @@ -0,0 +1,14 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +using System.Text.Json.Serialization; + +namespace Microsoft.AspNetCore.Components; + +[JsonConverter(typeof(JsonStringEnumConverter))] +internal enum RootComponentOperationType +{ + Add, + Update, + Remove, +} diff --git a/src/Components/Shared/src/WebRendererId.cs b/src/Components/Shared/src/WebRendererId.cs new file mode 100644 index 000000000000..c92e4e142462 --- /dev/null +++ b/src/Components/Shared/src/WebRendererId.cs @@ -0,0 +1,14 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +namespace Microsoft.AspNetCore.Components; + +// Represents the renderer ID for a web renderer. +// This should be kept in sync with WebRendererId.ts. +internal enum WebRendererId +{ + Default = 0, + Server = 1, + WebAssembly = 2, + WebView = 3, +} diff --git a/src/Components/Web.JS/dist/Release/blazor.server.js b/src/Components/Web.JS/dist/Release/blazor.server.js index 61f83fea2527..cd960364200f 100644 --- a/src/Components/Web.JS/dist/Release/blazor.server.js +++ b/src/Components/Web.JS/dist/Release/blazor.server.js @@ -1 +1 @@ -(()=>{var e={778:()=>{},77:()=>{},203:()=>{},200:()=>{},628:()=>{},321:()=>{}},t={};function n(o){var r=t[o];if(void 0!==r)return r.exports;var i=t[o]={exports:{}};return e[o](i,i.exports,n),i.exports}n.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(e){if("object"==typeof window)return window}}(),(()=>{"use strict";var e,t,o;!function(e){const t=[],n="__jsObjectId",o="__dotNetObject",r="__byte[]",i="__dotNetStream",s="__jsStreamReferenceLength";let a,c;class l{constructor(e){this._jsObject=e,this._cachedFunctions=new Map}findFunction(e){const t=this._cachedFunctions.get(e);if(t)return t;let n,o=this._jsObject;if(e.split(".").forEach((t=>{if(!(t in o))throw new Error(`Could not find '${e}' ('${t}' was undefined).`);n=o,o=o[t]})),o instanceof Function)return o=o.bind(n),this._cachedFunctions.set(e,o),o;throw new Error(`The value '${e}' is not a function.`)}getWrappedObject(){return this._jsObject}}const h={0:new l(window)};h[0]._cachedFunctions.set("import",(e=>("string"==typeof e&&e.startsWith("./")&&(e=new URL(e.substr(2),document.baseURI).toString()),import(e))));let d,u=1;function p(e){t.push(e)}function f(e){if(e&&"object"==typeof e){h[u]=new l(e);const t={[n]:u};return u++,t}throw new Error(`Cannot create a JSObjectReference from the value '${e}'.`)}function g(e){let t=-1;if(e instanceof ArrayBuffer&&(e=new Uint8Array(e)),e instanceof Blob)t=e.size;else{if(!(e.buffer instanceof ArrayBuffer))throw new Error("Supplied value is not a typed array or blob.");if(void 0===e.byteLength)throw new Error(`Cannot create a JSStreamReference from the value '${e}' as it doesn't have a byteLength.`);t=e.byteLength}const o={[s]:t};try{const t=f(e);o[n]=t[n]}catch(t){throw new Error(`Cannot create a JSStreamReference from the value '${e}'.`)}return o}function m(e,n){c=e;const o=n?JSON.parse(n,((e,n)=>t.reduce(((t,n)=>n(e,t)),n))):null;return c=void 0,o}function y(){if(void 0===a)throw new Error("No call dispatcher has been set.");if(null===a)throw new Error("There are multiple .NET runtimes present, so a default dispatcher could not be resolved. Use DotNetObject to invoke .NET instance methods.");return a}e.attachDispatcher=function(e){const t=new v(e);return void 0===a?a=t:a&&(a=null),t},e.attachReviver=p,e.invokeMethod=function(e,t,...n){return y().invokeDotNetStaticMethod(e,t,...n)},e.invokeMethodAsync=function(e,t,...n){return y().invokeDotNetStaticMethodAsync(e,t,...n)},e.createJSObjectReference=f,e.createJSStreamReference=g,e.disposeJSObjectReference=function(e){const t=e&&e[n];"number"==typeof t&&_(t)},function(e){e[e.Default=0]="Default",e[e.JSObjectReference=1]="JSObjectReference",e[e.JSStreamReference=2]="JSStreamReference",e[e.JSVoidResult=3]="JSVoidResult"}(d=e.JSCallResultType||(e.JSCallResultType={}));class v{constructor(e){this._dotNetCallDispatcher=e,this._byteArraysToBeRevived=new Map,this._pendingDotNetToJSStreams=new Map,this._pendingAsyncCalls={},this._nextAsyncCallId=1}getDotNetCallDispatcher(){return this._dotNetCallDispatcher}invokeJSFromDotNet(e,t,n,o){const r=m(this,t),i=I(b(e,o)(...r||[]),n);return null==i?null:T(this,i)}beginInvokeJSFromDotNet(e,t,n,o,r){const i=new Promise((e=>{const o=m(this,n);e(b(t,r)(...o||[]))}));e&&i.then((t=>T(this,[e,!0,I(t,o)]))).then((t=>this._dotNetCallDispatcher.endInvokeJSFromDotNet(e,!0,t)),(t=>this._dotNetCallDispatcher.endInvokeJSFromDotNet(e,!1,JSON.stringify([e,!1,w(t)]))))}endInvokeDotNetFromJS(e,t,n){const o=t?m(this,n):new Error(n);this.completePendingCall(parseInt(e,10),t,o)}invokeDotNetStaticMethod(e,t,...n){return this.invokeDotNetMethod(e,t,null,n)}invokeDotNetStaticMethodAsync(e,t,...n){return this.invokeDotNetMethodAsync(e,t,null,n)}invokeDotNetMethod(e,t,n,o){if(this._dotNetCallDispatcher.invokeDotNetFromJS){const r=T(this,o),i=this._dotNetCallDispatcher.invokeDotNetFromJS(e,t,n,r);return i?m(this,i):null}throw new Error("The current dispatcher does not support synchronous calls from JS to .NET. Use invokeDotNetMethodAsync instead.")}invokeDotNetMethodAsync(e,t,n,o){if(e&&n)throw new Error(`For instance method calls, assemblyName should be null. Received '${e}'.`);const r=this._nextAsyncCallId++,i=new Promise(((e,t)=>{this._pendingAsyncCalls[r]={resolve:e,reject:t}}));try{const i=T(this,o);this._dotNetCallDispatcher.beginInvokeDotNetFromJS(r,e,t,n,i)}catch(e){this.completePendingCall(r,!1,e)}return i}receiveByteArray(e,t){this._byteArraysToBeRevived.set(e,t)}processByteArray(e){const t=this._byteArraysToBeRevived.get(e);return t?(this._byteArraysToBeRevived.delete(e),t):null}supplyDotNetStream(e,t){if(this._pendingDotNetToJSStreams.has(e)){const n=this._pendingDotNetToJSStreams.get(e);this._pendingDotNetToJSStreams.delete(e),n.resolve(t)}else{const n=new C;n.resolve(t),this._pendingDotNetToJSStreams.set(e,n)}}getDotNetStreamPromise(e){let t;if(this._pendingDotNetToJSStreams.has(e))t=this._pendingDotNetToJSStreams.get(e).streamPromise,this._pendingDotNetToJSStreams.delete(e);else{const n=new C;this._pendingDotNetToJSStreams.set(e,n),t=n.streamPromise}return t}completePendingCall(e,t,n){if(!this._pendingAsyncCalls.hasOwnProperty(e))throw new Error(`There is no pending async call with ID ${e}.`);const o=this._pendingAsyncCalls[e];delete this._pendingAsyncCalls[e],t?o.resolve(n):o.reject(n)}}function w(e){return e instanceof Error?`${e.message}\n${e.stack}`:e?e.toString():"null"}function b(e,t){const n=h[t];if(n)return n.findFunction(e);throw new Error(`JS object instance with ID ${t} does not exist (has it been disposed?).`)}function _(e){delete h[e]}e.findJSFunction=b,e.disposeJSObjectReferenceById=_;class E{constructor(e,t){this._id=e,this._callDispatcher=t}invokeMethod(e,...t){return this._callDispatcher.invokeDotNetMethod(null,e,this._id,t)}invokeMethodAsync(e,...t){return this._callDispatcher.invokeDotNetMethodAsync(null,e,this._id,t)}dispose(){this._callDispatcher.invokeDotNetMethodAsync(null,"__Dispose",this._id,null).catch((e=>console.error(e)))}serializeAsArg(){return{[o]:this._id}}}e.DotNetObject=E,p((function(e,t){if(t&&"object"==typeof t){if(t.hasOwnProperty(o))return new E(t[o],c);if(t.hasOwnProperty(n)){const e=t[n],o=h[e];if(o)return o.getWrappedObject();throw new Error(`JS object instance with Id '${e}' does not exist. It may have been disposed.`)}if(t.hasOwnProperty(r)){const e=t[r],n=c.processByteArray(e);if(void 0===n)throw new Error(`Byte array index '${e}' does not exist.`);return n}if(t.hasOwnProperty(i)){const e=t[i],n=c.getDotNetStreamPromise(e);return new S(n)}}return t}));class S{constructor(e){this._streamPromise=e}stream(){return this._streamPromise}async arrayBuffer(){return new Response(await this.stream()).arrayBuffer()}}class C{constructor(){this.streamPromise=new Promise(((e,t)=>{this.resolve=e,this.reject=t}))}}function I(e,t){switch(t){case d.Default:return e;case d.JSObjectReference:return f(e);case d.JSStreamReference:return g(e);case d.JSVoidResult:return null;default:throw new Error(`Invalid JS call result type '${t}'.`)}}let k=0;function T(e,t){k=0,c=e;const n=JSON.stringify(t,D);return c=void 0,n}function D(e,t){if(t instanceof E)return t.serializeAsArg();if(t instanceof Uint8Array){c.getDotNetCallDispatcher().sendByteArray(k,t);const e={[r]:k};return k++,e}return t}}(e||(e={})),function(e){e[e.prependFrame=1]="prependFrame",e[e.removeFrame=2]="removeFrame",e[e.setAttribute=3]="setAttribute",e[e.removeAttribute=4]="removeAttribute",e[e.updateText=5]="updateText",e[e.stepIn=6]="stepIn",e[e.stepOut=7]="stepOut",e[e.updateMarkup=8]="updateMarkup",e[e.permutationListEntry=9]="permutationListEntry",e[e.permutationListEnd=10]="permutationListEnd"}(t||(t={})),function(e){e[e.element=1]="element",e[e.text=2]="text",e[e.attribute=3]="attribute",e[e.component=4]="component",e[e.region=5]="region",e[e.elementReferenceCapture=6]="elementReferenceCapture",e[e.markup=8]="markup",e[e.namedEvent=10]="namedEvent"}(o||(o={}));class r{constructor(e,t){this.componentId=e,this.fieldValue=t}static fromEvent(e,t){const n=t.target;if(n instanceof Element){const t=function(e){return e instanceof HTMLInputElement?e.type&&"checkbox"===e.type.toLowerCase()?{value:e.checked}:{value:e.value}:e instanceof HTMLSelectElement||e instanceof HTMLTextAreaElement?{value:e.value}:null}(n);if(t)return new r(e,t.value)}return null}}const i=new Map,s=new Map,a=[];function c(e){return i.get(e)}function l(e){const t=i.get(e);return(null==t?void 0:t.browserEventName)||e}function h(e,t){e.forEach((e=>i.set(e,t)))}function d(e){const t=[];for(let n=0;ne.selected)).map((e=>e.value))}}{const e=function(e){return!!e&&"INPUT"===e.tagName&&"checkbox"===e.getAttribute("type")}(t);return{value:e?!!t.checked:t.value}}}}),h(["copy","cut","paste"],{createEventArgs:e=>({type:e.type})}),h(["drag","dragend","dragenter","dragleave","dragover","dragstart","drop"],{createEventArgs:e=>{return{...u(t=e),dataTransfer:t.dataTransfer?{dropEffect:t.dataTransfer.dropEffect,effectAllowed:t.dataTransfer.effectAllowed,files:Array.from(t.dataTransfer.files).map((e=>e.name)),items:Array.from(t.dataTransfer.items).map((e=>({kind:e.kind,type:e.type}))),types:t.dataTransfer.types}:null};var t}}),h(["focus","blur","focusin","focusout"],{createEventArgs:e=>({type:e.type})}),h(["keydown","keyup","keypress"],{createEventArgs:e=>{return{key:(t=e).key,code:t.code,location:t.location,repeat:t.repeat,ctrlKey:t.ctrlKey,shiftKey:t.shiftKey,altKey:t.altKey,metaKey:t.metaKey,type:t.type};var t}}),h(["contextmenu","click","mouseover","mouseout","mousemove","mousedown","mouseup","mouseleave","mouseenter","dblclick"],{createEventArgs:e=>u(e)}),h(["error"],{createEventArgs:e=>{return{message:(t=e).message,filename:t.filename,lineno:t.lineno,colno:t.colno,type:t.type};var t}}),h(["loadstart","timeout","abort","load","loadend","progress"],{createEventArgs:e=>{return{lengthComputable:(t=e).lengthComputable,loaded:t.loaded,total:t.total,type:t.type};var t}}),h(["touchcancel","touchend","touchmove","touchenter","touchleave","touchstart"],{createEventArgs:e=>{return{detail:(t=e).detail,touches:d(t.touches),targetTouches:d(t.targetTouches),changedTouches:d(t.changedTouches),ctrlKey:t.ctrlKey,shiftKey:t.shiftKey,altKey:t.altKey,metaKey:t.metaKey,type:t.type};var t}}),h(["gotpointercapture","lostpointercapture","pointercancel","pointerdown","pointerenter","pointerleave","pointermove","pointerout","pointerover","pointerup"],{createEventArgs:e=>{return{...u(t=e),pointerId:t.pointerId,width:t.width,height:t.height,pressure:t.pressure,tiltX:t.tiltX,tiltY:t.tiltY,pointerType:t.pointerType,isPrimary:t.isPrimary};var t}}),h(["wheel","mousewheel"],{createEventArgs:e=>{return{...u(t=e),deltaX:t.deltaX,deltaY:t.deltaY,deltaZ:t.deltaZ,deltaMode:t.deltaMode};var t}}),h(["toggle"],{createEventArgs:()=>({})});const p=["date","datetime-local","month","time","week"],f=new Map;let g,m,y=0;const v={async add(e,t,n){if(!n)throw new Error("initialParameters must be an object, even if empty.");const o="__bl-dynamic-root:"+(++y).toString();f.set(o,e);const r=await _().invokeMethodAsync("AddRootComponent",t,o),i=new b(r,m[t]);return await i.setParameters(n),i}};class w{invoke(e){return this._callback(e)}setCallback(t){this._selfJSObjectReference||(this._selfJSObjectReference=e.createJSObjectReference(this)),this._callback=t}getJSObjectReference(){return this._selfJSObjectReference}dispose(){this._selfJSObjectReference&&e.disposeJSObjectReference(this._selfJSObjectReference)}}class b{constructor(e,t){this._jsEventCallbackWrappers=new Map,this._componentId=e;for(const e of t)"eventcallback"===e.type&&this._jsEventCallbackWrappers.set(e.name.toLowerCase(),new w)}setParameters(e){const t={},n=Object.entries(e||{}),o=n.length;for(const[e,o]of n){const n=this._jsEventCallbackWrappers.get(e.toLowerCase());n&&o?(n.setCallback(o),t[e]=n.getJSObjectReference()):t[e]=o}return _().invokeMethodAsync("SetRootComponentParameters",this._componentId,o,t)}async dispose(){if(null!==this._componentId){await _().invokeMethodAsync("RemoveRootComponent",this._componentId),this._componentId=null;for(const e of this._jsEventCallbackWrappers.values())e.dispose()}}}function _(){if(!g)throw new Error("Dynamic root components have not been enabled in this application.");return g}const E=[];let S;const C=new Promise((e=>{S=e}));function I(e,t,n){return T(e,t.eventHandlerId,(()=>k(e).invokeMethodAsync("DispatchEventAsync",t,n)))}function k(e){const t=E[e];if(!t)throw new Error(`No interop methods are registered for renderer ${e}`);return t}let T=(e,t,n)=>n();const D=U(["abort","blur","canplay","canplaythrough","change","cuechange","durationchange","emptied","ended","error","focus","load","loadeddata","loadedmetadata","loadend","loadstart","mouseenter","mouseleave","pointerenter","pointerleave","pause","play","playing","progress","ratechange","reset","scroll","seeked","seeking","stalled","submit","suspend","timeupdate","toggle","unload","volumechange","waiting","DOMNodeInsertedIntoDocument","DOMNodeRemovedFromDocument"]),x={submit:!0},R=U(["click","dblclick","mousedown","mousemove","mouseup"]);class P{constructor(e){this.browserRendererId=e,this.afterClickCallbacks=[];const t=++P.nextEventDelegatorId;this.eventsCollectionKey=`_blazorEvents_${t}`,this.eventInfoStore=new A(this.onGlobalEvent.bind(this))}setListener(e,t,n,o){const r=this.getEventHandlerInfosForElement(e,!0),i=r.getHandler(t);if(i)this.eventInfoStore.update(i.eventHandlerId,n);else{const i={element:e,eventName:t,eventHandlerId:n,renderingComponentId:o};this.eventInfoStore.add(i),r.setHandler(t,i)}}getHandler(e){return this.eventInfoStore.get(e)}removeListener(e){const t=this.eventInfoStore.remove(e);if(t){const e=t.element,n=this.getEventHandlerInfosForElement(e,!1);n&&n.removeHandler(t.eventName)}}notifyAfterClick(e){this.afterClickCallbacks.push(e),this.eventInfoStore.addGlobalListener("click")}setStopPropagation(e,t,n){this.getEventHandlerInfosForElement(e,!0).stopPropagation(t,n)}setPreventDefault(e,t,n){this.getEventHandlerInfosForElement(e,!0).preventDefault(t,n)}onGlobalEvent(e){if(!(e.target instanceof Element))return;this.dispatchGlobalEventToAllElements(e.type,e);const t=(n=e.type,s.get(n));var n;t&&t.forEach((t=>this.dispatchGlobalEventToAllElements(t,e))),"click"===e.type&&this.afterClickCallbacks.forEach((t=>t(e)))}dispatchGlobalEventToAllElements(e,t){const n=t.composedPath();let o=n.shift(),i=null,s=!1;const a=Object.prototype.hasOwnProperty.call(D,e);let l=!1;for(;o;){const u=o,p=this.getEventHandlerInfosForElement(u,!1);if(p){const n=p.getHandler(e);if(n&&(h=u,d=t.type,!((h instanceof HTMLButtonElement||h instanceof HTMLInputElement||h instanceof HTMLTextAreaElement||h instanceof HTMLSelectElement)&&Object.prototype.hasOwnProperty.call(R,d)&&h.disabled))){if(!s){const n=c(e);i=(null==n?void 0:n.createEventArgs)?n.createEventArgs(t):{},s=!0}Object.prototype.hasOwnProperty.call(x,t.type)&&t.preventDefault(),I(this.browserRendererId,{eventHandlerId:n.eventHandlerId,eventName:e,eventFieldInfo:r.fromEvent(n.renderingComponentId,t)},i)}p.stopPropagation(e)&&(l=!0),p.preventDefault(e)&&t.preventDefault()}o=a||l?void 0:n.shift()}var h,d}getEventHandlerInfosForElement(e,t){return Object.prototype.hasOwnProperty.call(e,this.eventsCollectionKey)?e[this.eventsCollectionKey]:t?e[this.eventsCollectionKey]=new N:null}}P.nextEventDelegatorId=0;class A{constructor(e){this.globalListener=e,this.infosByEventHandlerId={},this.countByEventName={},a.push(this.handleEventNameAliasAdded.bind(this))}add(e){if(this.infosByEventHandlerId[e.eventHandlerId])throw new Error(`Event ${e.eventHandlerId} is already tracked`);this.infosByEventHandlerId[e.eventHandlerId]=e,this.addGlobalListener(e.eventName)}get(e){return this.infosByEventHandlerId[e]}addGlobalListener(e){if(e=l(e),Object.prototype.hasOwnProperty.call(this.countByEventName,e))this.countByEventName[e]++;else{this.countByEventName[e]=1;const t=Object.prototype.hasOwnProperty.call(D,e);document.addEventListener(e,this.globalListener,t)}}update(e,t){if(Object.prototype.hasOwnProperty.call(this.infosByEventHandlerId,t))throw new Error(`Event ${t} is already tracked`);const n=this.infosByEventHandlerId[e];delete this.infosByEventHandlerId[e],n.eventHandlerId=t,this.infosByEventHandlerId[t]=n}remove(e){const t=this.infosByEventHandlerId[e];if(t){delete this.infosByEventHandlerId[e];const n=l(t.eventName);0==--this.countByEventName[n]&&(delete this.countByEventName[n],document.removeEventListener(n,this.globalListener))}return t}handleEventNameAliasAdded(e,t){if(Object.prototype.hasOwnProperty.call(this.countByEventName,e)){const n=this.countByEventName[e];delete this.countByEventName[e],document.removeEventListener(e,this.globalListener),this.addGlobalListener(t),this.countByEventName[t]+=n-1}}}class N{constructor(){this.handlers={},this.preventDefaultFlags=null,this.stopPropagationFlags=null}getHandler(e){return Object.prototype.hasOwnProperty.call(this.handlers,e)?this.handlers[e]:null}setHandler(e,t){this.handlers[e]=t}removeHandler(e){delete this.handlers[e]}preventDefault(e,t){return void 0!==t&&(this.preventDefaultFlags=this.preventDefaultFlags||{},this.preventDefaultFlags[e]=t),!!this.preventDefaultFlags&&this.preventDefaultFlags[e]}stopPropagation(e,t){return void 0!==t&&(this.stopPropagationFlags=this.stopPropagationFlags||{},this.stopPropagationFlags[e]=t),!!this.stopPropagationFlags&&this.stopPropagationFlags[e]}}function U(e){const t={};return e.forEach((e=>{t[e]=!0})),t}const M=G("_blazorLogicalChildren"),L=G("_blazorLogicalParent"),$=G("_blazorLogicalEnd");function B(e,t){if(e.childNodes.length>0&&!t)throw new Error("New logical elements must start empty, or allowExistingContents must be true");return M in e||(e[M]=[]),e}function O(e,t){const n=document.createComment("!");return F(n,e,t),n}function F(e,t,n){const o=e;if(e instanceof Comment&&J(o)&&J(o).length>0)throw new Error("Not implemented: inserting non-empty logical container");if(j(o))throw new Error("Not implemented: moving existing logical children");const r=J(t);if(n0;)H(n,0)}const o=n;o.parentNode.removeChild(o)}function j(e){return e[L]||null}function W(e,t){return J(e)[t]}function z(e){const t=K(e);return"http://www.w3.org/2000/svg"===t.namespaceURI&&"foreignObject"!==t.tagName}function J(e){return e[M]}function q(e,t){const n=J(e);t.forEach((e=>{e.moveRangeStart=n[e.fromSiblingIndex],e.moveRangeEnd=Y(e.moveRangeStart)})),t.forEach((t=>{const o=document.createComment("marker");t.moveToBeforeMarker=o;const r=n[t.toSiblingIndex+1];r?r.parentNode.insertBefore(o,r):X(o,e)})),t.forEach((e=>{const t=e.moveToBeforeMarker,n=t.parentNode,o=e.moveRangeStart,r=e.moveRangeEnd;let i=o;for(;i;){const e=i.nextSibling;if(n.insertBefore(i,t),i===r)break;i=e}n.removeChild(t)})),t.forEach((e=>{n[e.toSiblingIndex]=e.moveRangeStart}))}function K(e){if(e instanceof Element||e instanceof DocumentFragment)return e;if(e instanceof Comment)return e.parentNode;throw new Error("Not a valid logical element")}function V(e){const t=J(j(e));return t[Array.prototype.indexOf.call(t,e)+1]||null}function X(e,t){if(t instanceof Element||t instanceof DocumentFragment)t.appendChild(e);else{if(!(t instanceof Comment))throw new Error(`Cannot append node because the parent is not a valid logical element. Parent: ${t}`);{const n=V(t);n?n.parentNode.insertBefore(e,n):X(e,j(t))}}}function Y(e){if(e instanceof Element||e instanceof DocumentFragment)return e;const t=V(e);if(t)return t.previousSibling;{const t=j(e);return t instanceof Element||t instanceof DocumentFragment?t.lastChild:Y(t)}}function G(e){return"function"==typeof Symbol?Symbol():e}function Q(e){return`_bl_${e}`}const Z="__internalId";e.attachReviver(((e,t)=>t&&"object"==typeof t&&Object.prototype.hasOwnProperty.call(t,Z)&&"string"==typeof t[Z]?function(e){const t=`[${Q(e)}]`;return document.querySelector(t)}(t[Z]):t));const ee="_blazorDeferredValue";function te(e){return"select-multiple"===e.type}function ne(e,t){e.value=t||""}function oe(e,t){e instanceof HTMLSelectElement?te(e)?function(e,t){t||(t=[]);for(let n=0;n{fe&&function(e,t){if(0!==e.button||function(e){return e.ctrlKey||e.shiftKey||e.altKey||e.metaKey}(e))return;if(e.defaultPrevented)return;const n=function(e){const t=!window._blazorDisableComposedPath&&e.composedPath&&e.composedPath();if(t){for(let e=0;edocument.baseURI,getLocationHref:()=>location.href,scrollToElement:Te};function Te(e){const t=document.getElementById(e);return!!t&&(t.scrollIntoView(),!0)}function De(e,t,n=!1){const o=me(e);!t.forceLoad&&ge(o)?xe(o,!1,t.replaceHistoryEntry,t.historyEntryState,n):function(e,t){if(location.href===e){const t=e+"?";history.replaceState(null,"",t),location.replace(e)}else t?location.replace(e):location.href=e}(e,t.replaceHistoryEntry)}async function xe(e,t,n,o=void 0,r=!1){if(Ae(),function(e){const t=e.indexOf("#");return t>-1&&location.href.replace(location.hash,"")===e.substring(0,t)}(e))!function(e,t,n){Re(e,t,n);const o=e.indexOf("#");o!==e.length-1&&Te(e.substring(o+1))}(e,n,o);else{if(!r&&we&&!await Ne(e,o,t))return;pe=!0,Re(e,n,o),await Ue(t)}}function Re(e,t,n=void 0){t?history.replaceState({userState:n,_index:be},"",e):(be++,history.pushState({userState:n,_index:be},"",e))}function Pe(e){return new Promise((t=>{const n=Ce;Ce=()=>{Ce=n,t()},history.go(e)}))}function Ae(){Ie&&(Ie(!1),Ie=null)}function Ne(e,t,n){return new Promise((o=>{Ae(),Se?(_e++,Ie=o,Se(_e,e,t,n)):o(!1)}))}async function Ue(e){var t;Ee&&await Ee(location.href,null===(t=history.state)||void 0===t?void 0:t.userState,e)}async function Me(e){var t,n;Ce&&await Ce(e),be=null!==(n=null===(t=history.state)||void 0===t?void 0:t._index)&&void 0!==n?n:0}const Le={focus:function(e,t){if(e instanceof HTMLElement)e.focus({preventScroll:t});else{if(!(e instanceof SVGElement))throw new Error("Unable to focus an invalid element.");if(!e.hasAttribute("tabindex"))throw new Error("Unable to focus an SVG element that does not have a tabindex.");e.focus({preventScroll:t})}},focusBySelector:function(e,t){const n=document.querySelector(e);n&&(n.hasAttribute("tabindex")||(n.tabIndex=-1),n.focus({preventScroll:!0}))}},$e={init:function(e,t,n,o=50){const r=Oe(t);(r||document.documentElement).style.overflowAnchor="none";const i=document.createRange();h(n.parentElement)&&(t.style.display="table-row",n.style.display="table-row");const s=new IntersectionObserver((function(o){o.forEach((o=>{var r;if(!o.isIntersecting)return;i.setStartAfter(t),i.setEndBefore(n);const s=i.getBoundingClientRect().height,a=null===(r=o.rootBounds)||void 0===r?void 0:r.height;o.target===t?e.invokeMethodAsync("OnSpacerBeforeVisible",o.intersectionRect.top-o.boundingClientRect.top,s,a):o.target===n&&n.offsetHeight>0&&e.invokeMethodAsync("OnSpacerAfterVisible",o.boundingClientRect.bottom-o.intersectionRect.bottom,s,a)}))}),{root:r,rootMargin:`${o}px`});s.observe(t),s.observe(n);const a=l(t),c=l(n);function l(e){const t={attributes:!0},n=new MutationObserver(((n,o)=>{h(e.parentElement)&&(o.disconnect(),e.style.display="table-row",o.observe(e,t)),s.unobserve(e),s.observe(e)}));return n.observe(e,t),n}function h(e){return null!==e&&(e instanceof HTMLTableElement&&""===e.style.display||"table"===e.style.display||e instanceof HTMLTableSectionElement&&""===e.style.display||"table-row-group"===e.style.display)}Be[e._id]={intersectionObserver:s,mutationObserverBefore:a,mutationObserverAfter:c}},dispose:function(e){const t=Be[e._id];t&&(t.intersectionObserver.disconnect(),t.mutationObserverBefore.disconnect(),t.mutationObserverAfter.disconnect(),e.dispose(),delete Be[e._id])}},Be={};function Oe(e){return e&&e!==document.body&&e!==document.documentElement?"visible"!==getComputedStyle(e).overflowY?e:Oe(e.parentElement):null}const Fe={getAndRemoveExistingTitle:function(){var e;const t=document.head?document.head.getElementsByTagName("title"):[];if(0===t.length)return null;let n=null;for(let o=t.length-1;o>=0;o--){const r=t[o],i=r.previousSibling;i instanceof Comment&&null!==j(i)||(null===n&&(n=r.textContent),null===(e=r.parentNode)||void 0===e||e.removeChild(r))}return n}},He={init:function(e,t){t._blazorInputFileNextFileId=0,t.addEventListener("click",(function(){t.value=""})),t.addEventListener("change",(function(){t._blazorFilesById={};const n=Array.prototype.map.call(t.files,(function(e){const n={id:++t._blazorInputFileNextFileId,lastModified:new Date(e.lastModified).toISOString(),name:e.name,size:e.size,contentType:e.type,readPromise:void 0,arrayBuffer:void 0,blob:e};return t._blazorFilesById[n.id]=n,n}));e.invokeMethodAsync("NotifyChange",n)}))},toImageFile:async function(e,t,n,o,r){const i=je(e,t),s=await new Promise((function(e){const t=new Image;t.onload=function(){URL.revokeObjectURL(t.src),e(t)},t.onerror=function(){t.onerror=null,URL.revokeObjectURL(t.src)},t.src=URL.createObjectURL(i.blob)})),a=await new Promise((function(e){var t;const i=Math.min(1,o/s.width),a=Math.min(1,r/s.height),c=Math.min(i,a),l=document.createElement("canvas");l.width=Math.round(s.width*c),l.height=Math.round(s.height*c),null===(t=l.getContext("2d"))||void 0===t||t.drawImage(s,0,0,l.width,l.height),l.toBlob(e,n)})),c={id:++e._blazorInputFileNextFileId,lastModified:i.lastModified,name:i.name,size:(null==a?void 0:a.size)||0,contentType:n,blob:a||i.blob};return e._blazorFilesById[c.id]=c,c},readFileData:async function(e,t){return je(e,t).blob}};function je(e,t){const n=e._blazorFilesById[t];if(!n)throw new Error(`There is no file with ID ${t}. The file list may have changed. See https://aka.ms/aspnet/blazor-input-file-multiple-selections.`);return n}const We=new Set,ze={enableNavigationPrompt:function(e){0===We.size&&window.addEventListener("beforeunload",Je),We.add(e)},disableNavigationPrompt:function(e){We.delete(e),0===We.size&&window.removeEventListener("beforeunload",Je)}};function Je(e){e.preventDefault(),e.returnValue=!0}async function qe(e,t,n){return e instanceof Blob?await async function(e,t,n){const o=e.slice(t,t+n),r=await o.arrayBuffer();return new Uint8Array(r)}(e,t,n):function(e,t,n){return new Uint8Array(e.buffer,e.byteOffset+t,n)}(e,t,n)}new Map;const Ke={navigateTo:function(e,t,n=!1){De(e,t instanceof Object?t:{forceLoad:t,replaceHistoryEntry:n})},registerCustomEventType:function(e,t){if(!t)throw new Error("The options parameter is required.");if(i.has(e))throw new Error(`The event '${e}' is already registered.`);if(t.browserEventName){const n=s.get(t.browserEventName);n?n.push(e):s.set(t.browserEventName,[e]),a.forEach((n=>n(e,t.browserEventName)))}i.set(e,t)},rootComponents:v,_internal:{navigationManager:ke,domWrapper:Le,Virtualize:$e,PageTitle:Fe,InputFile:He,NavigationLock:ze,getJSDataStreamChunk:qe,attachWebRendererInterop:function(t,n,o){const r=E.length;return E.push(t),Object.keys(n).length>0&&function(t,n,o){if(g)throw new Error("Dynamic root components have already been enabled.");g=t,m=n;for(const[t,r]of Object.entries(o)){const o=e.findJSFunction(t,0);for(const e of r)o(e,n[e])}}(k(r),n,o),S(),r}}};window.Blazor=Ke;const Ve=[0,2e3,1e4,3e4,null];class Xe{constructor(e){this._retryDelays=void 0!==e?[...e,null]:Ve}nextRetryDelayInMilliseconds(e){return this._retryDelays[e.previousRetryCount]}}class Ye{}Ye.Authorization="Authorization",Ye.Cookie="Cookie";class Ge{constructor(e,t,n){this.statusCode=e,this.statusText=t,this.content=n}}class Qe{get(e,t){return this.send({...t,method:"GET",url:e})}post(e,t){return this.send({...t,method:"POST",url:e})}delete(e,t){return this.send({...t,method:"DELETE",url:e})}getCookieString(e){return""}}class Ze extends Qe{constructor(e,t){super(),this._innerClient=e,this._accessTokenFactory=t}async send(e){let t=!0;this._accessTokenFactory&&(!this._accessToken||e.url&&e.url.indexOf("/negotiate?")>0)&&(t=!1,this._accessToken=await this._accessTokenFactory()),this._setAuthorizationHeader(e);const n=await this._innerClient.send(e);return t&&401===n.statusCode&&this._accessTokenFactory?(this._accessToken=await this._accessTokenFactory(),this._setAuthorizationHeader(e),await this._innerClient.send(e)):n}_setAuthorizationHeader(e){e.headers||(e.headers={}),this._accessToken?e.headers[Ye.Authorization]=`Bearer ${this._accessToken}`:this._accessTokenFactory&&e.headers[Ye.Authorization]&&delete e.headers[Ye.Authorization]}getCookieString(e){return this._innerClient.getCookieString(e)}}class et extends Error{constructor(e,t){const n=new.target.prototype;super(`${e}: Status code '${t}'`),this.statusCode=t,this.__proto__=n}}class tt extends Error{constructor(e="A timeout occurred."){const t=new.target.prototype;super(e),this.__proto__=t}}class nt extends Error{constructor(e="An abort occurred."){const t=new.target.prototype;super(e),this.__proto__=t}}class ot extends Error{constructor(e,t){const n=new.target.prototype;super(e),this.transport=t,this.errorType="UnsupportedTransportError",this.__proto__=n}}class rt extends Error{constructor(e,t){const n=new.target.prototype;super(e),this.transport=t,this.errorType="DisabledTransportError",this.__proto__=n}}class it extends Error{constructor(e,t){const n=new.target.prototype;super(e),this.transport=t,this.errorType="FailedToStartTransportError",this.__proto__=n}}class st extends Error{constructor(e){const t=new.target.prototype;super(e),this.errorType="FailedToNegotiateWithServerError",this.__proto__=t}}class at extends Error{constructor(e,t){const n=new.target.prototype;super(e),this.innerErrors=t,this.__proto__=n}}var ct;!function(e){e[e.Trace=0]="Trace",e[e.Debug=1]="Debug",e[e.Information=2]="Information",e[e.Warning=3]="Warning",e[e.Error=4]="Error",e[e.Critical=5]="Critical",e[e.None=6]="None"}(ct||(ct={}));class lt{constructor(){}log(e,t){}}lt.instance=new lt;const ht="0.0.0-DEV_BUILD";class dt{static isRequired(e,t){if(null==e)throw new Error(`The '${t}' argument is required.`)}static isNotEmpty(e,t){if(!e||e.match(/^\s*$/))throw new Error(`The '${t}' argument should not be empty.`)}static isIn(e,t,n){if(!(e in t))throw new Error(`Unknown ${n} value: ${e}.`)}}class ut{static get isBrowser(){return!ut.isNode&&"object"==typeof window&&"object"==typeof window.document}static get isWebWorker(){return!ut.isNode&&"object"==typeof self&&"importScripts"in self}static get isReactNative(){return!ut.isNode&&"object"==typeof window&&void 0===window.document}static get isNode(){return"undefined"!=typeof process&&process.release&&"node"===process.release.name}}function pt(e,t){let n="";return ft(e)?(n=`Binary data of length ${e.byteLength}`,t&&(n+=`. Content: '${function(e){const t=new Uint8Array(e);let n="";return t.forEach((e=>{n+=`0x${e<16?"0":""}${e.toString(16)} `})),n.substr(0,n.length-1)}(e)}'`)):"string"==typeof e&&(n=`String data of length ${e.length}`,t&&(n+=`. Content: '${e}'`)),n}function ft(e){return e&&"undefined"!=typeof ArrayBuffer&&(e instanceof ArrayBuffer||e.constructor&&"ArrayBuffer"===e.constructor.name)}async function gt(e,t,n,o,r,i){const s={},[a,c]=vt();s[a]=c,e.log(ct.Trace,`(${t} transport) sending data. ${pt(r,i.logMessageContent)}.`);const l=ft(r)?"arraybuffer":"text",h=await n.post(o,{content:r,headers:{...s,...i.headers},responseType:l,timeout:i.timeout,withCredentials:i.withCredentials});e.log(ct.Trace,`(${t} transport) request complete. Response status: ${h.statusCode}.`)}class mt{constructor(e,t){this._subject=e,this._observer=t}dispose(){const e=this._subject.observers.indexOf(this._observer);e>-1&&this._subject.observers.splice(e,1),0===this._subject.observers.length&&this._subject.cancelCallback&&this._subject.cancelCallback().catch((e=>{}))}}class yt{constructor(e){this._minLevel=e,this.out=console}log(e,t){if(e>=this._minLevel){const n=`[${(new Date).toISOString()}] ${ct[e]}: ${t}`;switch(e){case ct.Critical:case ct.Error:this.out.error(n);break;case ct.Warning:this.out.warn(n);break;case ct.Information:this.out.info(n);break;default:this.out.log(n)}}}}function vt(){let e="X-SignalR-User-Agent";return ut.isNode&&(e="User-Agent"),[e,wt(ht,bt(),ut.isNode?"NodeJS":"Browser",_t())]}function wt(e,t,n,o){let r="Microsoft SignalR/";const i=e.split(".");return r+=`${i[0]}.${i[1]}`,r+=` (${e}; `,r+=t&&""!==t?`${t}; `:"Unknown OS; ",r+=`${n}`,r+=o?`; ${o}`:"; Unknown Runtime Version",r+=")",r}function bt(){if(!ut.isNode)return"";switch(process.platform){case"win32":return"Windows NT";case"darwin":return"macOS";case"linux":return"Linux";default:return process.platform}}function _t(){if(ut.isNode)return process.versions.node}function Et(e){return e.stack?e.stack:e.message?e.message:`${e}`}class St extends Qe{constructor(e){super(),this._logger=e;const t={_fetchType:void 0,_jar:void 0};var o;o=t,"undefined"==typeof fetch&&(o._jar=new(n(628).CookieJar),"undefined"==typeof fetch?o._fetchType=n(200):o._fetchType=fetch,o._fetchType=n(203)(o._fetchType,o._jar),1)?(this._fetchType=t._fetchType,this._jar=t._jar):this._fetchType=fetch.bind(function(){if("undefined"!=typeof globalThis)return globalThis;if("undefined"!=typeof self)return self;if("undefined"!=typeof window)return window;if(void 0!==n.g)return n.g;throw new Error("could not find global")}()),this._abortControllerType=AbortController;const r={_abortControllerType:this._abortControllerType};(function(e){return"undefined"==typeof AbortController&&(e._abortControllerType=n(778),!0)})(r)&&(this._abortControllerType=r._abortControllerType)}async send(e){if(e.abortSignal&&e.abortSignal.aborted)throw new nt;if(!e.method)throw new Error("No method defined.");if(!e.url)throw new Error("No url defined.");const t=new this._abortControllerType;let n;e.abortSignal&&(e.abortSignal.onabort=()=>{t.abort(),n=new nt});let o,r=null;if(e.timeout){const o=e.timeout;r=setTimeout((()=>{t.abort(),this._logger.log(ct.Warning,"Timeout from HTTP request."),n=new tt}),o)}""===e.content&&(e.content=void 0),e.content&&(e.headers=e.headers||{},ft(e.content)?e.headers["Content-Type"]="application/octet-stream":e.headers["Content-Type"]="text/plain;charset=UTF-8");try{o=await this._fetchType(e.url,{body:e.content,cache:"no-cache",credentials:!0===e.withCredentials?"include":"same-origin",headers:{"X-Requested-With":"XMLHttpRequest",...e.headers},method:e.method,mode:"cors",redirect:"follow",signal:t.signal})}catch(e){if(n)throw n;throw this._logger.log(ct.Warning,`Error from HTTP request. ${e}.`),e}finally{r&&clearTimeout(r),e.abortSignal&&(e.abortSignal.onabort=null)}if(!o.ok){const e=await Ct(o,"text");throw new et(e||o.statusText,o.status)}const i=Ct(o,e.responseType),s=await i;return new Ge(o.status,o.statusText,s)}getCookieString(e){return""}}function Ct(e,t){let n;switch(t){case"arraybuffer":n=e.arrayBuffer();break;case"text":default:n=e.text();break;case"blob":case"document":case"json":throw new Error(`${t} is not supported.`)}return n}class It extends Qe{constructor(e){super(),this._logger=e}send(e){return e.abortSignal&&e.abortSignal.aborted?Promise.reject(new nt):e.method?e.url?new Promise(((t,n)=>{const o=new XMLHttpRequest;o.open(e.method,e.url,!0),o.withCredentials=void 0===e.withCredentials||e.withCredentials,o.setRequestHeader("X-Requested-With","XMLHttpRequest"),""===e.content&&(e.content=void 0),e.content&&(ft(e.content)?o.setRequestHeader("Content-Type","application/octet-stream"):o.setRequestHeader("Content-Type","text/plain;charset=UTF-8"));const r=e.headers;r&&Object.keys(r).forEach((e=>{o.setRequestHeader(e,r[e])})),e.responseType&&(o.responseType=e.responseType),e.abortSignal&&(e.abortSignal.onabort=()=>{o.abort(),n(new nt)}),e.timeout&&(o.timeout=e.timeout),o.onload=()=>{e.abortSignal&&(e.abortSignal.onabort=null),o.status>=200&&o.status<300?t(new Ge(o.status,o.statusText,o.response||o.responseText)):n(new et(o.response||o.responseText||o.statusText,o.status))},o.onerror=()=>{this._logger.log(ct.Warning,`Error from HTTP request. ${o.status}: ${o.statusText}.`),n(new et(o.statusText,o.status))},o.ontimeout=()=>{this._logger.log(ct.Warning,"Timeout from HTTP request."),n(new tt)},o.send(e.content)})):Promise.reject(new Error("No url defined.")):Promise.reject(new Error("No method defined."))}}class kt extends Qe{constructor(e){if(super(),"undefined"!=typeof fetch)this._httpClient=new St(e);else{if("undefined"==typeof XMLHttpRequest)throw new Error("No usable HttpClient found.");this._httpClient=new It(e)}}send(e){return e.abortSignal&&e.abortSignal.aborted?Promise.reject(new nt):e.method?e.url?this._httpClient.send(e):Promise.reject(new Error("No url defined.")):Promise.reject(new Error("No method defined."))}getCookieString(e){return this._httpClient.getCookieString(e)}}var Tt,Dt,xt,Rt;!function(e){e[e.None=0]="None",e[e.WebSockets=1]="WebSockets",e[e.ServerSentEvents=2]="ServerSentEvents",e[e.LongPolling=4]="LongPolling"}(Tt||(Tt={})),function(e){e[e.Text=1]="Text",e[e.Binary=2]="Binary"}(Dt||(Dt={}));class Pt{constructor(){this._isAborted=!1,this.onabort=null}abort(){this._isAborted||(this._isAborted=!0,this.onabort&&this.onabort())}get signal(){return this}get aborted(){return this._isAborted}}class At{get pollAborted(){return this._pollAbort.aborted}constructor(e,t,n){this._httpClient=e,this._logger=t,this._pollAbort=new Pt,this._options=n,this._running=!1,this.onreceive=null,this.onclose=null}async connect(e,t){if(dt.isRequired(e,"url"),dt.isRequired(t,"transferFormat"),dt.isIn(t,Dt,"transferFormat"),this._url=e,this._logger.log(ct.Trace,"(LongPolling transport) Connecting."),t===Dt.Binary&&"undefined"!=typeof XMLHttpRequest&&"string"!=typeof(new XMLHttpRequest).responseType)throw new Error("Binary protocols over XmlHttpRequest not implementing advanced features are not supported.");const[n,o]=vt(),r={[n]:o,...this._options.headers},i={abortSignal:this._pollAbort.signal,headers:r,timeout:1e5,withCredentials:this._options.withCredentials};t===Dt.Binary&&(i.responseType="arraybuffer");const s=`${e}&_=${Date.now()}`;this._logger.log(ct.Trace,`(LongPolling transport) polling: ${s}.`);const a=await this._httpClient.get(s,i);200!==a.statusCode?(this._logger.log(ct.Error,`(LongPolling transport) Unexpected response code: ${a.statusCode}.`),this._closeError=new et(a.statusText||"",a.statusCode),this._running=!1):this._running=!0,this._receiving=this._poll(this._url,i)}async _poll(e,t){try{for(;this._running;)try{const n=`${e}&_=${Date.now()}`;this._logger.log(ct.Trace,`(LongPolling transport) polling: ${n}.`);const o=await this._httpClient.get(n,t);204===o.statusCode?(this._logger.log(ct.Information,"(LongPolling transport) Poll terminated by server."),this._running=!1):200!==o.statusCode?(this._logger.log(ct.Error,`(LongPolling transport) Unexpected response code: ${o.statusCode}.`),this._closeError=new et(o.statusText||"",o.statusCode),this._running=!1):o.content?(this._logger.log(ct.Trace,`(LongPolling transport) data received. ${pt(o.content,this._options.logMessageContent)}.`),this.onreceive&&this.onreceive(o.content)):this._logger.log(ct.Trace,"(LongPolling transport) Poll timed out, reissuing.")}catch(e){this._running?e instanceof tt?this._logger.log(ct.Trace,"(LongPolling transport) Poll timed out, reissuing."):(this._closeError=e,this._running=!1):this._logger.log(ct.Trace,`(LongPolling transport) Poll errored after shutdown: ${e.message}`)}}finally{this._logger.log(ct.Trace,"(LongPolling transport) Polling complete."),this.pollAborted||this._raiseOnClose()}}async send(e){return this._running?gt(this._logger,"LongPolling",this._httpClient,this._url,e,this._options):Promise.reject(new Error("Cannot send until the transport is connected"))}async stop(){this._logger.log(ct.Trace,"(LongPolling transport) Stopping polling."),this._running=!1,this._pollAbort.abort();try{await this._receiving,this._logger.log(ct.Trace,`(LongPolling transport) sending DELETE request to ${this._url}.`);const e={},[t,n]=vt();e[t]=n;const o={headers:{...e,...this._options.headers},timeout:this._options.timeout,withCredentials:this._options.withCredentials};let r;try{await this._httpClient.delete(this._url,o)}catch(e){r=e}r?r instanceof et&&(404===r.statusCode?this._logger.log(ct.Trace,"(LongPolling transport) A 404 response was returned from sending a DELETE request."):this._logger.log(ct.Trace,`(LongPolling transport) Error sending a DELETE request: ${r}`)):this._logger.log(ct.Trace,"(LongPolling transport) DELETE request accepted.")}finally{this._logger.log(ct.Trace,"(LongPolling transport) Stop finished."),this._raiseOnClose()}}_raiseOnClose(){if(this.onclose){let e="(LongPolling transport) Firing onclose event.";this._closeError&&(e+=" Error: "+this._closeError),this._logger.log(ct.Trace,e),this.onclose(this._closeError)}}}class Nt{constructor(e,t,n,o){this._httpClient=e,this._accessToken=t,this._logger=n,this._options=o,this.onreceive=null,this.onclose=null}async connect(e,t){return dt.isRequired(e,"url"),dt.isRequired(t,"transferFormat"),dt.isIn(t,Dt,"transferFormat"),this._logger.log(ct.Trace,"(SSE transport) Connecting."),this._url=e,this._accessToken&&(e+=(e.indexOf("?")<0?"?":"&")+`access_token=${encodeURIComponent(this._accessToken)}`),new Promise(((n,o)=>{let r,i=!1;if(t===Dt.Text){if(ut.isBrowser||ut.isWebWorker)r=new this._options.EventSource(e,{withCredentials:this._options.withCredentials});else{const t=this._httpClient.getCookieString(e),n={};n.Cookie=t;const[o,i]=vt();n[o]=i,r=new this._options.EventSource(e,{withCredentials:this._options.withCredentials,headers:{...n,...this._options.headers}})}try{r.onmessage=e=>{if(this.onreceive)try{this._logger.log(ct.Trace,`(SSE transport) data received. ${pt(e.data,this._options.logMessageContent)}.`),this.onreceive(e.data)}catch(e){return void this._close(e)}},r.onerror=e=>{i?this._close():o(new Error("EventSource failed to connect. The connection could not be found on the server, either the connection ID is not present on the server, or a proxy is refusing/buffering the connection. If you have multiple servers check that sticky sessions are enabled."))},r.onopen=()=>{this._logger.log(ct.Information,`SSE connected to ${this._url}`),this._eventSource=r,i=!0,n()}}catch(e){return void o(e)}}else o(new Error("The Server-Sent Events transport only supports the 'Text' transfer format"))}))}async send(e){return this._eventSource?gt(this._logger,"SSE",this._httpClient,this._url,e,this._options):Promise.reject(new Error("Cannot send until the transport is connected"))}stop(){return this._close(),Promise.resolve()}_close(e){this._eventSource&&(this._eventSource.close(),this._eventSource=void 0,this.onclose&&this.onclose(e))}}class Ut{constructor(e,t,n,o,r,i){this._logger=n,this._accessTokenFactory=t,this._logMessageContent=o,this._webSocketConstructor=r,this._httpClient=e,this.onreceive=null,this.onclose=null,this._headers=i}async connect(e,t){let n;return dt.isRequired(e,"url"),dt.isRequired(t,"transferFormat"),dt.isIn(t,Dt,"transferFormat"),this._logger.log(ct.Trace,"(WebSockets transport) Connecting."),this._accessTokenFactory&&(n=await this._accessTokenFactory()),new Promise(((o,r)=>{let i;e=e.replace(/^http/,"ws");const s=this._httpClient.getCookieString(e);let a=!1;if(ut.isReactNative){const t={},[o,r]=vt();t[o]=r,n&&(t[Ye.Authorization]=`Bearer ${n}`),s&&(t[Ye.Cookie]=s),i=new this._webSocketConstructor(e,void 0,{headers:{...t,...this._headers}})}else n&&(e+=(e.indexOf("?")<0?"?":"&")+`access_token=${encodeURIComponent(n)}`);i||(i=new this._webSocketConstructor(e)),t===Dt.Binary&&(i.binaryType="arraybuffer"),i.onopen=t=>{this._logger.log(ct.Information,`WebSocket connected to ${e}.`),this._webSocket=i,a=!0,o()},i.onerror=e=>{let t=null;t="undefined"!=typeof ErrorEvent&&e instanceof ErrorEvent?e.error:"There was an error with the transport",this._logger.log(ct.Information,`(WebSockets transport) ${t}.`)},i.onmessage=e=>{if(this._logger.log(ct.Trace,`(WebSockets transport) data received. ${pt(e.data,this._logMessageContent)}.`),this.onreceive)try{this.onreceive(e.data)}catch(e){return void this._close(e)}},i.onclose=e=>{if(a)this._close(e);else{let t=null;t="undefined"!=typeof ErrorEvent&&e instanceof ErrorEvent?e.error:"WebSocket failed to connect. The connection could not be found on the server, either the endpoint may not be a SignalR endpoint, the connection ID is not present on the server, or there is a proxy blocking WebSockets. If you have multiple servers check that sticky sessions are enabled.",r(new Error(t))}}}))}send(e){return this._webSocket&&this._webSocket.readyState===this._webSocketConstructor.OPEN?(this._logger.log(ct.Trace,`(WebSockets transport) sending data. ${pt(e,this._logMessageContent)}.`),this._webSocket.send(e),Promise.resolve()):Promise.reject("WebSocket is not in the OPEN state")}stop(){return this._webSocket&&this._close(void 0),Promise.resolve()}_close(e){this._webSocket&&(this._webSocket.onclose=()=>{},this._webSocket.onmessage=()=>{},this._webSocket.onerror=()=>{},this._webSocket.close(),this._webSocket=void 0),this._logger.log(ct.Trace,"(WebSockets transport) socket closed."),this.onclose&&(!this._isCloseEvent(e)||!1!==e.wasClean&&1e3===e.code?e instanceof Error?this.onclose(e):this.onclose():this.onclose(new Error(`WebSocket closed with status code: ${e.code} (${e.reason||"no reason given"}).`)))}_isCloseEvent(e){return e&&"boolean"==typeof e.wasClean&&"number"==typeof e.code}}class Mt{constructor(e,t={}){var n;if(this._stopPromiseResolver=()=>{},this.features={},this._negotiateVersion=1,dt.isRequired(e,"url"),this._logger=void 0===(n=t.logger)?new yt(ct.Information):null===n?lt.instance:void 0!==n.log?n:new yt(n),this.baseUrl=this._resolveUrl(e),(t=t||{}).logMessageContent=void 0!==t.logMessageContent&&t.logMessageContent,"boolean"!=typeof t.withCredentials&&void 0!==t.withCredentials)throw new Error("withCredentials option was not a 'boolean' or 'undefined' value");t.withCredentials=void 0===t.withCredentials||t.withCredentials,t.timeout=void 0===t.timeout?1e5:t.timeout,"undefined"==typeof WebSocket||t.WebSocket||(t.WebSocket=WebSocket),"undefined"==typeof EventSource||t.EventSource||(t.EventSource=EventSource),this._httpClient=new Ze(t.httpClient||new kt(this._logger),t.accessTokenFactory),this._connectionState="Disconnected",this._connectionStarted=!1,this._options=t,this.onreceive=null,this.onclose=null}async start(e){if(e=e||Dt.Binary,dt.isIn(e,Dt,"transferFormat"),this._logger.log(ct.Debug,`Starting connection with transfer format '${Dt[e]}'.`),"Disconnected"!==this._connectionState)return Promise.reject(new Error("Cannot start an HttpConnection that is not in the 'Disconnected' state."));if(this._connectionState="Connecting",this._startInternalPromise=this._startInternal(e),await this._startInternalPromise,"Disconnecting"===this._connectionState){const e="Failed to start the HttpConnection before stop() was called.";return this._logger.log(ct.Error,e),await this._stopPromise,Promise.reject(new nt(e))}if("Connected"!==this._connectionState){const e="HttpConnection.startInternal completed gracefully but didn't enter the connection into the connected state!";return this._logger.log(ct.Error,e),Promise.reject(new nt(e))}this._connectionStarted=!0}send(e){return"Connected"!==this._connectionState?Promise.reject(new Error("Cannot send data if the connection is not in the 'Connected' State.")):(this._sendQueue||(this._sendQueue=new Lt(this.transport)),this._sendQueue.send(e))}async stop(e){return"Disconnected"===this._connectionState?(this._logger.log(ct.Debug,`Call to HttpConnection.stop(${e}) ignored because the connection is already in the disconnected state.`),Promise.resolve()):"Disconnecting"===this._connectionState?(this._logger.log(ct.Debug,`Call to HttpConnection.stop(${e}) ignored because the connection is already in the disconnecting state.`),this._stopPromise):(this._connectionState="Disconnecting",this._stopPromise=new Promise((e=>{this._stopPromiseResolver=e})),await this._stopInternal(e),void await this._stopPromise)}async _stopInternal(e){this._stopError=e;try{await this._startInternalPromise}catch(e){}if(this.transport){try{await this.transport.stop()}catch(e){this._logger.log(ct.Error,`HttpConnection.transport.stop() threw error '${e}'.`),this._stopConnection()}this.transport=void 0}else this._logger.log(ct.Debug,"HttpConnection.transport is undefined in HttpConnection.stop() because start() failed.")}async _startInternal(e){let t=this.baseUrl;this._accessTokenFactory=this._options.accessTokenFactory,this._httpClient._accessTokenFactory=this._accessTokenFactory;try{if(this._options.skipNegotiation){if(this._options.transport!==Tt.WebSockets)throw new Error("Negotiation can only be skipped when using the WebSocket transport directly.");this.transport=this._constructTransport(Tt.WebSockets),await this._startTransport(t,e)}else{let n=null,o=0;do{if(n=await this._getNegotiationResponse(t),"Disconnecting"===this._connectionState||"Disconnected"===this._connectionState)throw new nt("The connection was stopped during negotiation.");if(n.error)throw new Error(n.error);if(n.ProtocolVersion)throw new Error("Detected a connection attempt to an ASP.NET SignalR Server. This client only supports connecting to an ASP.NET Core SignalR Server. See https://aka.ms/signalr-core-differences for details.");if(n.url&&(t=n.url),n.accessToken){const e=n.accessToken;this._accessTokenFactory=()=>e,this._httpClient._accessToken=e,this._httpClient._accessTokenFactory=void 0}o++}while(n.url&&o<100);if(100===o&&n.url)throw new Error("Negotiate redirection limit exceeded.");await this._createTransport(t,this._options.transport,n,e)}this.transport instanceof At&&(this.features.inherentKeepAlive=!0),"Connecting"===this._connectionState&&(this._logger.log(ct.Debug,"The HttpConnection connected successfully."),this._connectionState="Connected")}catch(e){return this._logger.log(ct.Error,"Failed to start the connection: "+e),this._connectionState="Disconnected",this.transport=void 0,this._stopPromiseResolver(),Promise.reject(e)}}async _getNegotiationResponse(e){const t={},[n,o]=vt();t[n]=o;const r=this._resolveNegotiateUrl(e);this._logger.log(ct.Debug,`Sending negotiation request: ${r}.`);try{const e=await this._httpClient.post(r,{content:"",headers:{...t,...this._options.headers},timeout:this._options.timeout,withCredentials:this._options.withCredentials});if(200!==e.statusCode)return Promise.reject(new Error(`Unexpected status code returned from negotiate '${e.statusCode}'`));const n=JSON.parse(e.content);return(!n.negotiateVersion||n.negotiateVersion<1)&&(n.connectionToken=n.connectionId),n}catch(e){let t="Failed to complete negotiation with the server: "+e;return e instanceof et&&404===e.statusCode&&(t+=" Either this is not a SignalR endpoint or there is a proxy blocking the connection."),this._logger.log(ct.Error,t),Promise.reject(new st(t))}}_createConnectUrl(e,t){return t?e+(-1===e.indexOf("?")?"?":"&")+`id=${t}`:e}async _createTransport(e,t,n,o){let r=this._createConnectUrl(e,n.connectionToken);if(this._isITransport(t))return this._logger.log(ct.Debug,"Connection was provided an instance of ITransport, using that directly."),this.transport=t,await this._startTransport(r,o),void(this.connectionId=n.connectionId);const i=[],s=n.availableTransports||[];let a=n;for(const n of s){const s=this._resolveTransportOrError(n,t,o);if(s instanceof Error)i.push(`${n.transport} failed:`),i.push(s);else if(this._isITransport(s)){if(this.transport=s,!a){try{a=await this._getNegotiationResponse(e)}catch(e){return Promise.reject(e)}r=this._createConnectUrl(e,a.connectionToken)}try{return await this._startTransport(r,o),void(this.connectionId=a.connectionId)}catch(e){if(this._logger.log(ct.Error,`Failed to start the transport '${n.transport}': ${e}`),a=void 0,i.push(new it(`${n.transport} failed: ${e}`,Tt[n.transport])),"Connecting"!==this._connectionState){const e="Failed to select transport before stop() was called.";return this._logger.log(ct.Debug,e),Promise.reject(new nt(e))}}}}return i.length>0?Promise.reject(new at(`Unable to connect to the server with any of the available transports. ${i.join(" ")}`,i)):Promise.reject(new Error("None of the transports supported by the client are supported by the server."))}_constructTransport(e){switch(e){case Tt.WebSockets:if(!this._options.WebSocket)throw new Error("'WebSocket' is not supported in your environment.");return new Ut(this._httpClient,this._accessTokenFactory,this._logger,this._options.logMessageContent,this._options.WebSocket,this._options.headers||{});case Tt.ServerSentEvents:if(!this._options.EventSource)throw new Error("'EventSource' is not supported in your environment.");return new Nt(this._httpClient,this._httpClient._accessToken,this._logger,this._options);case Tt.LongPolling:return new At(this._httpClient,this._logger,this._options);default:throw new Error(`Unknown transport: ${e}.`)}}_startTransport(e,t){return this.transport.onreceive=this.onreceive,this.transport.onclose=e=>this._stopConnection(e),this.transport.connect(e,t)}_resolveTransportOrError(e,t,n){const o=Tt[e.transport];if(null==o)return this._logger.log(ct.Debug,`Skipping transport '${e.transport}' because it is not supported by this client.`),new Error(`Skipping transport '${e.transport}' because it is not supported by this client.`);if(!function(e,t){return!e||0!=(t&e)}(t,o))return this._logger.log(ct.Debug,`Skipping transport '${Tt[o]}' because it was disabled by the client.`),new rt(`'${Tt[o]}' is disabled by the client.`,o);if(!(e.transferFormats.map((e=>Dt[e])).indexOf(n)>=0))return this._logger.log(ct.Debug,`Skipping transport '${Tt[o]}' because it does not support the requested transfer format '${Dt[n]}'.`),new Error(`'${Tt[o]}' does not support ${Dt[n]}.`);if(o===Tt.WebSockets&&!this._options.WebSocket||o===Tt.ServerSentEvents&&!this._options.EventSource)return this._logger.log(ct.Debug,`Skipping transport '${Tt[o]}' because it is not supported in your environment.'`),new ot(`'${Tt[o]}' is not supported in your environment.`,o);this._logger.log(ct.Debug,`Selecting transport '${Tt[o]}'.`);try{return this._constructTransport(o)}catch(e){return e}}_isITransport(e){return e&&"object"==typeof e&&"connect"in e}_stopConnection(e){if(this._logger.log(ct.Debug,`HttpConnection.stopConnection(${e}) called while in state ${this._connectionState}.`),this.transport=void 0,e=this._stopError||e,this._stopError=void 0,"Disconnected"!==this._connectionState){if("Connecting"===this._connectionState)throw this._logger.log(ct.Warning,`Call to HttpConnection.stopConnection(${e}) was ignored because the connection is still in the connecting state.`),new Error(`HttpConnection.stopConnection(${e}) was called while the connection is still in the connecting state.`);if("Disconnecting"===this._connectionState&&this._stopPromiseResolver(),e?this._logger.log(ct.Error,`Connection disconnected with error '${e}'.`):this._logger.log(ct.Information,"Connection disconnected."),this._sendQueue&&(this._sendQueue.stop().catch((e=>{this._logger.log(ct.Error,`TransportSendQueue.stop() threw error '${e}'.`)})),this._sendQueue=void 0),this.connectionId=void 0,this._connectionState="Disconnected",this._connectionStarted){this._connectionStarted=!1;try{this.onclose&&this.onclose(e)}catch(t){this._logger.log(ct.Error,`HttpConnection.onclose(${e}) threw error '${t}'.`)}}}else this._logger.log(ct.Debug,`Call to HttpConnection.stopConnection(${e}) was ignored because the connection is already in the disconnected state.`)}_resolveUrl(e){if(0===e.lastIndexOf("https://",0)||0===e.lastIndexOf("http://",0))return e;if(!ut.isBrowser)throw new Error(`Cannot resolve '${e}'.`);const t=window.document.createElement("a");return t.href=e,this._logger.log(ct.Information,`Normalizing '${e}' to '${t.href}'.`),t.href}_resolveNegotiateUrl(e){const t=e.indexOf("?");let n=e.substring(0,-1===t?e.length:t);return"/"!==n[n.length-1]&&(n+="/"),n+="negotiate",n+=-1===t?"":e.substring(t),-1===n.indexOf("negotiateVersion")&&(n+=-1===t?"?":"&",n+="negotiateVersion="+this._negotiateVersion),n}}class Lt{constructor(e){this._transport=e,this._buffer=[],this._executing=!0,this._sendBufferedData=new $t,this._transportResult=new $t,this._sendLoopPromise=this._sendLoop()}send(e){return this._bufferData(e),this._transportResult||(this._transportResult=new $t),this._transportResult.promise}stop(){return this._executing=!1,this._sendBufferedData.resolve(),this._sendLoopPromise}_bufferData(e){if(this._buffer.length&&typeof this._buffer[0]!=typeof e)throw new Error(`Expected data to be of type ${typeof this._buffer} but was of type ${typeof e}`);this._buffer.push(e),this._sendBufferedData.resolve()}async _sendLoop(){for(;;){if(await this._sendBufferedData.promise,!this._executing){this._transportResult&&this._transportResult.reject("Connection stopped.");break}this._sendBufferedData=new $t;const e=this._transportResult;this._transportResult=void 0;const t="string"==typeof this._buffer[0]?this._buffer.join(""):Lt._concatBuffers(this._buffer);this._buffer.length=0;try{await this._transport.send(t),e.resolve()}catch(t){e.reject(t)}}}static _concatBuffers(e){const t=e.map((e=>e.byteLength)).reduce(((e,t)=>e+t)),n=new Uint8Array(t);let o=0;for(const t of e)n.set(new Uint8Array(t),o),o+=t.byteLength;return n.buffer}}class $t{constructor(){this.promise=new Promise(((e,t)=>[this._resolver,this._rejecter]=[e,t]))}resolve(){this._resolver()}reject(e){this._rejecter(e)}}class Bt{static write(e){return`${e}${Bt.RecordSeparator}`}static parse(e){if(e[e.length-1]!==Bt.RecordSeparator)throw new Error("Message is incomplete.");const t=e.split(Bt.RecordSeparator);return t.pop(),t}}Bt.RecordSeparatorCode=30,Bt.RecordSeparator=String.fromCharCode(Bt.RecordSeparatorCode);class Ot{writeHandshakeRequest(e){return Bt.write(JSON.stringify(e))}parseHandshakeResponse(e){let t,n;if(ft(e)){const o=new Uint8Array(e),r=o.indexOf(Bt.RecordSeparatorCode);if(-1===r)throw new Error("Message is incomplete.");const i=r+1;t=String.fromCharCode.apply(null,Array.prototype.slice.call(o.slice(0,i))),n=o.byteLength>i?o.slice(i).buffer:null}else{const o=e,r=o.indexOf(Bt.RecordSeparator);if(-1===r)throw new Error("Message is incomplete.");const i=r+1;t=o.substring(0,i),n=o.length>i?o.substring(i):null}const o=Bt.parse(t),r=JSON.parse(o[0]);if(r.type)throw new Error("Expected a handshake response from the server.");return[n,r]}}!function(e){e[e.Invocation=1]="Invocation",e[e.StreamItem=2]="StreamItem",e[e.Completion=3]="Completion",e[e.StreamInvocation=4]="StreamInvocation",e[e.CancelInvocation=5]="CancelInvocation",e[e.Ping=6]="Ping",e[e.Close=7]="Close"}(xt||(xt={}));class Ft{constructor(){this.observers=[]}next(e){for(const t of this.observers)t.next(e)}error(e){for(const t of this.observers)t.error&&t.error(e)}complete(){for(const e of this.observers)e.complete&&e.complete()}subscribe(e){return this.observers.push(e),new mt(this,e)}}!function(e){e.Disconnected="Disconnected",e.Connecting="Connecting",e.Connected="Connected",e.Disconnecting="Disconnecting",e.Reconnecting="Reconnecting"}(Rt||(Rt={}));class Ht{static create(e,t,n,o,r,i){return new Ht(e,t,n,o,r,i)}constructor(e,t,n,o,r,i){this._nextKeepAlive=0,this._freezeEventListener=()=>{this._logger.log(ct.Warning,"The page is being frozen, this will likely lead to the connection being closed and messages being lost. For more information see the docs at https://learn.microsoft.com/aspnet/core/signalr/javascript-client#bsleep")},dt.isRequired(e,"connection"),dt.isRequired(t,"logger"),dt.isRequired(n,"protocol"),this.serverTimeoutInMilliseconds=null!=r?r:3e4,this.keepAliveIntervalInMilliseconds=null!=i?i:15e3,this._logger=t,this._protocol=n,this.connection=e,this._reconnectPolicy=o,this._handshakeProtocol=new Ot,this.connection.onreceive=e=>this._processIncomingData(e),this.connection.onclose=e=>this._connectionClosed(e),this._callbacks={},this._methods={},this._closedCallbacks=[],this._reconnectingCallbacks=[],this._reconnectedCallbacks=[],this._invocationId=0,this._receivedHandshakeResponse=!1,this._connectionState=Rt.Disconnected,this._connectionStarted=!1,this._cachedPingMessage=this._protocol.writeMessage({type:xt.Ping})}get state(){return this._connectionState}get connectionId(){return this.connection&&this.connection.connectionId||null}get baseUrl(){return this.connection.baseUrl||""}set baseUrl(e){if(this._connectionState!==Rt.Disconnected&&this._connectionState!==Rt.Reconnecting)throw new Error("The HubConnection must be in the Disconnected or Reconnecting state to change the url.");if(!e)throw new Error("The HubConnection url must be a valid url.");this.connection.baseUrl=e}start(){return this._startPromise=this._startWithStateTransitions(),this._startPromise}async _startWithStateTransitions(){if(this._connectionState!==Rt.Disconnected)return Promise.reject(new Error("Cannot start a HubConnection that is not in the 'Disconnected' state."));this._connectionState=Rt.Connecting,this._logger.log(ct.Debug,"Starting HubConnection.");try{await this._startInternal(),ut.isBrowser&&window.document.addEventListener("freeze",this._freezeEventListener),this._connectionState=Rt.Connected,this._connectionStarted=!0,this._logger.log(ct.Debug,"HubConnection connected successfully.")}catch(e){return this._connectionState=Rt.Disconnected,this._logger.log(ct.Debug,`HubConnection failed to start successfully because of error '${e}'.`),Promise.reject(e)}}async _startInternal(){this._stopDuringStartError=void 0,this._receivedHandshakeResponse=!1;const e=new Promise(((e,t)=>{this._handshakeResolver=e,this._handshakeRejecter=t}));await this.connection.start(this._protocol.transferFormat);try{const t={protocol:this._protocol.name,version:this._protocol.version};if(this._logger.log(ct.Debug,"Sending handshake request."),await this._sendMessage(this._handshakeProtocol.writeHandshakeRequest(t)),this._logger.log(ct.Information,`Using HubProtocol '${this._protocol.name}'.`),this._cleanupTimeout(),this._resetTimeoutPeriod(),this._resetKeepAliveInterval(),await e,this._stopDuringStartError)throw this._stopDuringStartError;this.connection.features.inherentKeepAlive||await this._sendMessage(this._cachedPingMessage)}catch(e){throw this._logger.log(ct.Debug,`Hub handshake failed with error '${e}' during start(). Stopping HubConnection.`),this._cleanupTimeout(),this._cleanupPingTimer(),await this.connection.stop(e),e}}async stop(){const e=this._startPromise;this._stopPromise=this._stopInternal(),await this._stopPromise;try{await e}catch(e){}}_stopInternal(e){if(this._connectionState===Rt.Disconnected)return this._logger.log(ct.Debug,`Call to HubConnection.stop(${e}) ignored because it is already in the disconnected state.`),Promise.resolve();if(this._connectionState===Rt.Disconnecting)return this._logger.log(ct.Debug,`Call to HttpConnection.stop(${e}) ignored because the connection is already in the disconnecting state.`),this._stopPromise;const t=this._connectionState;return this._connectionState=Rt.Disconnecting,this._logger.log(ct.Debug,"Stopping HubConnection."),this._reconnectDelayHandle?(this._logger.log(ct.Debug,"Connection stopped during reconnect delay. Done reconnecting."),clearTimeout(this._reconnectDelayHandle),this._reconnectDelayHandle=void 0,this._completeClose(),Promise.resolve()):(t===Rt.Connected&&this._sendCloseMessage(),this._cleanupTimeout(),this._cleanupPingTimer(),this._stopDuringStartError=e||new nt("The connection was stopped before the hub handshake could complete."),this.connection.stop(e))}async _sendCloseMessage(){try{await this._sendWithProtocol(this._createCloseMessage())}catch{}}stream(e,...t){const[n,o]=this._replaceStreamingParams(t),r=this._createStreamInvocation(e,t,o);let i;const s=new Ft;return s.cancelCallback=()=>{const e=this._createCancelInvocation(r.invocationId);return delete this._callbacks[r.invocationId],i.then((()=>this._sendWithProtocol(e)))},this._callbacks[r.invocationId]=(e,t)=>{t?s.error(t):e&&(e.type===xt.Completion?e.error?s.error(new Error(e.error)):s.complete():s.next(e.item))},i=this._sendWithProtocol(r).catch((e=>{s.error(e),delete this._callbacks[r.invocationId]})),this._launchStreams(n,i),s}_sendMessage(e){return this._resetKeepAliveInterval(),this.connection.send(e)}_sendWithProtocol(e){return this._sendMessage(this._protocol.writeMessage(e))}send(e,...t){const[n,o]=this._replaceStreamingParams(t),r=this._sendWithProtocol(this._createInvocation(e,t,!0,o));return this._launchStreams(n,r),r}invoke(e,...t){const[n,o]=this._replaceStreamingParams(t),r=this._createInvocation(e,t,!1,o);return new Promise(((e,t)=>{this._callbacks[r.invocationId]=(n,o)=>{o?t(o):n&&(n.type===xt.Completion?n.error?t(new Error(n.error)):e(n.result):t(new Error(`Unexpected message type: ${n.type}`)))};const o=this._sendWithProtocol(r).catch((e=>{t(e),delete this._callbacks[r.invocationId]}));this._launchStreams(n,o)}))}on(e,t){e&&t&&(e=e.toLowerCase(),this._methods[e]||(this._methods[e]=[]),-1===this._methods[e].indexOf(t)&&this._methods[e].push(t))}off(e,t){if(!e)return;e=e.toLowerCase();const n=this._methods[e];if(n)if(t){const o=n.indexOf(t);-1!==o&&(n.splice(o,1),0===n.length&&delete this._methods[e])}else delete this._methods[e]}onclose(e){e&&this._closedCallbacks.push(e)}onreconnecting(e){e&&this._reconnectingCallbacks.push(e)}onreconnected(e){e&&this._reconnectedCallbacks.push(e)}_processIncomingData(e){if(this._cleanupTimeout(),this._receivedHandshakeResponse||(e=this._processHandshakeResponse(e),this._receivedHandshakeResponse=!0),e){const t=this._protocol.parseMessages(e,this._logger);for(const e of t)switch(e.type){case xt.Invocation:this._invokeClientMethod(e);break;case xt.StreamItem:case xt.Completion:{const t=this._callbacks[e.invocationId];if(t){e.type===xt.Completion&&delete this._callbacks[e.invocationId];try{t(e)}catch(e){this._logger.log(ct.Error,`Stream callback threw error: ${Et(e)}`)}}break}case xt.Ping:break;case xt.Close:{this._logger.log(ct.Information,"Close message received from server.");const t=e.error?new Error("Server returned an error on close: "+e.error):void 0;!0===e.allowReconnect?this.connection.stop(t):this._stopPromise=this._stopInternal(t);break}default:this._logger.log(ct.Warning,`Invalid message type: ${e.type}.`)}}this._resetTimeoutPeriod()}_processHandshakeResponse(e){let t,n;try{[n,t]=this._handshakeProtocol.parseHandshakeResponse(e)}catch(e){const t="Error parsing handshake response: "+e;this._logger.log(ct.Error,t);const n=new Error(t);throw this._handshakeRejecter(n),n}if(t.error){const e="Server returned handshake error: "+t.error;this._logger.log(ct.Error,e);const n=new Error(e);throw this._handshakeRejecter(n),n}return this._logger.log(ct.Debug,"Server handshake complete."),this._handshakeResolver(),n}_resetKeepAliveInterval(){this.connection.features.inherentKeepAlive||(this._nextKeepAlive=(new Date).getTime()+this.keepAliveIntervalInMilliseconds,this._cleanupPingTimer())}_resetTimeoutPeriod(){if(!(this.connection.features&&this.connection.features.inherentKeepAlive||(this._timeoutHandle=setTimeout((()=>this.serverTimeout()),this.serverTimeoutInMilliseconds),void 0!==this._pingServerHandle))){let e=this._nextKeepAlive-(new Date).getTime();e<0&&(e=0),this._pingServerHandle=setTimeout((async()=>{if(this._connectionState===Rt.Connected)try{await this._sendMessage(this._cachedPingMessage)}catch{this._cleanupPingTimer()}}),e)}}serverTimeout(){this.connection.stop(new Error("Server timeout elapsed without receiving a message from the server."))}async _invokeClientMethod(e){const t=e.target.toLowerCase(),n=this._methods[t];if(!n)return this._logger.log(ct.Warning,`No client method with the name '${t}' found.`),void(e.invocationId&&(this._logger.log(ct.Warning,`No result given for '${t}' method and invocation ID '${e.invocationId}'.`),await this._sendWithProtocol(this._createCompletionMessage(e.invocationId,"Client didn't provide a result.",null))));const o=n.slice(),r=!!e.invocationId;let i,s,a;for(const n of o)try{const o=i;i=await n.apply(this,e.arguments),r&&i&&o&&(this._logger.log(ct.Error,`Multiple results provided for '${t}'. Sending error to server.`),a=this._createCompletionMessage(e.invocationId,"Client provided multiple results.",null)),s=void 0}catch(e){s=e,this._logger.log(ct.Error,`A callback for the method '${t}' threw error '${e}'.`)}a?await this._sendWithProtocol(a):r?(s?a=this._createCompletionMessage(e.invocationId,`${s}`,null):void 0!==i?a=this._createCompletionMessage(e.invocationId,null,i):(this._logger.log(ct.Warning,`No result given for '${t}' method and invocation ID '${e.invocationId}'.`),a=this._createCompletionMessage(e.invocationId,"Client didn't provide a result.",null)),await this._sendWithProtocol(a)):i&&this._logger.log(ct.Error,`Result given for '${t}' method but server is not expecting a result.`)}_connectionClosed(e){this._logger.log(ct.Debug,`HubConnection.connectionClosed(${e}) called while in state ${this._connectionState}.`),this._stopDuringStartError=this._stopDuringStartError||e||new nt("The underlying connection was closed before the hub handshake could complete."),this._handshakeResolver&&this._handshakeResolver(),this._cancelCallbacksWithError(e||new Error("Invocation canceled due to the underlying connection being closed.")),this._cleanupTimeout(),this._cleanupPingTimer(),this._connectionState===Rt.Disconnecting?this._completeClose(e):this._connectionState===Rt.Connected&&this._reconnectPolicy?this._reconnect(e):this._connectionState===Rt.Connected&&this._completeClose(e)}_completeClose(e){if(this._connectionStarted){this._connectionState=Rt.Disconnected,this._connectionStarted=!1,ut.isBrowser&&window.document.removeEventListener("freeze",this._freezeEventListener);try{this._closedCallbacks.forEach((t=>t.apply(this,[e])))}catch(t){this._logger.log(ct.Error,`An onclose callback called with error '${e}' threw error '${t}'.`)}}}async _reconnect(e){const t=Date.now();let n=0,o=void 0!==e?e:new Error("Attempting to reconnect due to a unknown error."),r=this._getNextRetryDelay(n++,0,o);if(null===r)return this._logger.log(ct.Debug,"Connection not reconnecting because the IRetryPolicy returned null on the first reconnect attempt."),void this._completeClose(e);if(this._connectionState=Rt.Reconnecting,e?this._logger.log(ct.Information,`Connection reconnecting because of error '${e}'.`):this._logger.log(ct.Information,"Connection reconnecting."),0!==this._reconnectingCallbacks.length){try{this._reconnectingCallbacks.forEach((t=>t.apply(this,[e])))}catch(t){this._logger.log(ct.Error,`An onreconnecting callback called with error '${e}' threw error '${t}'.`)}if(this._connectionState!==Rt.Reconnecting)return void this._logger.log(ct.Debug,"Connection left the reconnecting state in onreconnecting callback. Done reconnecting.")}for(;null!==r;){if(this._logger.log(ct.Information,`Reconnect attempt number ${n} will start in ${r} ms.`),await new Promise((e=>{this._reconnectDelayHandle=setTimeout(e,r)})),this._reconnectDelayHandle=void 0,this._connectionState!==Rt.Reconnecting)return void this._logger.log(ct.Debug,"Connection left the reconnecting state during reconnect delay. Done reconnecting.");try{if(await this._startInternal(),this._connectionState=Rt.Connected,this._logger.log(ct.Information,"HubConnection reconnected successfully."),0!==this._reconnectedCallbacks.length)try{this._reconnectedCallbacks.forEach((e=>e.apply(this,[this.connection.connectionId])))}catch(e){this._logger.log(ct.Error,`An onreconnected callback called with connectionId '${this.connection.connectionId}; threw error '${e}'.`)}return}catch(e){if(this._logger.log(ct.Information,`Reconnect attempt failed because of error '${e}'.`),this._connectionState!==Rt.Reconnecting)return this._logger.log(ct.Debug,`Connection moved to the '${this._connectionState}' from the reconnecting state during reconnect attempt. Done reconnecting.`),void(this._connectionState===Rt.Disconnecting&&this._completeClose());o=e instanceof Error?e:new Error(e.toString()),r=this._getNextRetryDelay(n++,Date.now()-t,o)}}this._logger.log(ct.Information,`Reconnect retries have been exhausted after ${Date.now()-t} ms and ${n} failed attempts. Connection disconnecting.`),this._completeClose()}_getNextRetryDelay(e,t,n){try{return this._reconnectPolicy.nextRetryDelayInMilliseconds({elapsedMilliseconds:t,previousRetryCount:e,retryReason:n})}catch(n){return this._logger.log(ct.Error,`IRetryPolicy.nextRetryDelayInMilliseconds(${e}, ${t}) threw error '${n}'.`),null}}_cancelCallbacksWithError(e){const t=this._callbacks;this._callbacks={},Object.keys(t).forEach((n=>{const o=t[n];try{o(null,e)}catch(t){this._logger.log(ct.Error,`Stream 'error' callback called with '${e}' threw error: ${Et(t)}`)}}))}_cleanupPingTimer(){this._pingServerHandle&&(clearTimeout(this._pingServerHandle),this._pingServerHandle=void 0)}_cleanupTimeout(){this._timeoutHandle&&clearTimeout(this._timeoutHandle)}_createInvocation(e,t,n,o){if(n)return 0!==o.length?{arguments:t,streamIds:o,target:e,type:xt.Invocation}:{arguments:t,target:e,type:xt.Invocation};{const n=this._invocationId;return this._invocationId++,0!==o.length?{arguments:t,invocationId:n.toString(),streamIds:o,target:e,type:xt.Invocation}:{arguments:t,invocationId:n.toString(),target:e,type:xt.Invocation}}}_launchStreams(e,t){if(0!==e.length){t||(t=Promise.resolve());for(const n in e)e[n].subscribe({complete:()=>{t=t.then((()=>this._sendWithProtocol(this._createCompletionMessage(n))))},error:e=>{let o;o=e instanceof Error?e.message:e&&e.toString?e.toString():"Unknown error",t=t.then((()=>this._sendWithProtocol(this._createCompletionMessage(n,o))))},next:e=>{t=t.then((()=>this._sendWithProtocol(this._createStreamItemMessage(n,e))))}})}}_replaceStreamingParams(e){const t=[],n=[];for(let o=0;o=55296&&r<=56319&&o65535&&(h-=65536,i.push(h>>>10&1023|55296),h=56320|1023&h),i.push(h)}else i.push(a);i.length>=4096&&(s+=String.fromCharCode.apply(String,i),i.length=0)}return i.length>0&&(s+=String.fromCharCode.apply(String,i)),s}var on,rn=Gt?new TextDecoder:null,sn=Gt?"undefined"!=typeof process&&"force"!==(null===(Kt=null===process||void 0===process?void 0:process.env)||void 0===Kt?void 0:Kt.TEXT_DECODER)?200:0:Vt,an=function(e,t){this.type=e,this.data=t},cn=(on=function(e,t){return on=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=t[n])},on(e,t)},function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");function n(){this.constructor=e}on(e,t),e.prototype=null===t?Object.create(t):(n.prototype=t.prototype,new n)}),ln=function(e){function t(n){var o=e.call(this,n)||this,r=Object.create(t.prototype);return Object.setPrototypeOf(o,r),Object.defineProperty(o,"name",{configurable:!0,enumerable:!1,value:t.name}),o}return cn(t,e),t}(Error),hn={type:-1,encode:function(e){var t,n,o,r;return e instanceof Date?function(e){var t,n=e.sec,o=e.nsec;if(n>=0&&o>=0&&n<=17179869183){if(0===o&&n<=4294967295){var r=new Uint8Array(4);return(t=new DataView(r.buffer)).setUint32(0,n),r}var i=n/4294967296,s=4294967295&n;return r=new Uint8Array(8),(t=new DataView(r.buffer)).setUint32(0,o<<2|3&i),t.setUint32(4,s),r}return r=new Uint8Array(12),(t=new DataView(r.buffer)).setUint32(0,o),Xt(t,4,n),r}((o=1e6*((t=e.getTime())-1e3*(n=Math.floor(t/1e3))),{sec:n+(r=Math.floor(o/1e9)),nsec:o-1e9*r})):null},decode:function(e){var t=function(e){var t=new DataView(e.buffer,e.byteOffset,e.byteLength);switch(e.byteLength){case 4:return{sec:t.getUint32(0),nsec:0};case 8:var n=t.getUint32(0);return{sec:4294967296*(3&n)+t.getUint32(4),nsec:n>>>2};case 12:return{sec:Yt(t,4),nsec:t.getUint32(0)};default:throw new ln("Unrecognized data size for timestamp (expected 4, 8, or 12): ".concat(e.length))}}(e);return new Date(1e3*t.sec+t.nsec/1e6)}},dn=function(){function e(){this.builtInEncoders=[],this.builtInDecoders=[],this.encoders=[],this.decoders=[],this.register(hn)}return e.prototype.register=function(e){var t=e.type,n=e.encode,o=e.decode;if(t>=0)this.encoders[t]=n,this.decoders[t]=o;else{var r=1+t;this.builtInEncoders[r]=n,this.builtInDecoders[r]=o}},e.prototype.tryToEncode=function(e,t){for(var n=0;nthis.maxDepth)throw new Error("Too deep objects in depth ".concat(t));null==e?this.encodeNil():"boolean"==typeof e?this.encodeBoolean(e):"number"==typeof e?this.encodeNumber(e):"string"==typeof e?this.encodeString(e):this.encodeObject(e,t)},e.prototype.ensureBufferSizeToWrite=function(e){var t=this.pos+e;this.view.byteLength=0?e<128?this.writeU8(e):e<256?(this.writeU8(204),this.writeU8(e)):e<65536?(this.writeU8(205),this.writeU16(e)):e<4294967296?(this.writeU8(206),this.writeU32(e)):(this.writeU8(207),this.writeU64(e)):e>=-32?this.writeU8(224|e+32):e>=-128?(this.writeU8(208),this.writeI8(e)):e>=-32768?(this.writeU8(209),this.writeI16(e)):e>=-2147483648?(this.writeU8(210),this.writeI32(e)):(this.writeU8(211),this.writeI64(e)):this.forceFloat32?(this.writeU8(202),this.writeF32(e)):(this.writeU8(203),this.writeF64(e))},e.prototype.writeStringHeader=function(e){if(e<32)this.writeU8(160+e);else if(e<256)this.writeU8(217),this.writeU8(e);else if(e<65536)this.writeU8(218),this.writeU16(e);else{if(!(e<4294967296))throw new Error("Too long string: ".concat(e," bytes in UTF-8"));this.writeU8(219),this.writeU32(e)}},e.prototype.encodeString=function(e){if(e.length>en){var t=Qt(e);this.ensureBufferSizeToWrite(5+t),this.writeStringHeader(t),tn(e,this.bytes,this.pos),this.pos+=t}else t=Qt(e),this.ensureBufferSizeToWrite(5+t),this.writeStringHeader(t),function(e,t,n){for(var o=e.length,r=n,i=0;i>6&31|192;else{if(s>=55296&&s<=56319&&i>12&15|224,t[r++]=s>>6&63|128):(t[r++]=s>>18&7|240,t[r++]=s>>12&63|128,t[r++]=s>>6&63|128)}t[r++]=63&s|128}else t[r++]=s}}(e,this.bytes,this.pos),this.pos+=t},e.prototype.encodeObject=function(e,t){var n=this.extensionCodec.tryToEncode(e,this.context);if(null!=n)this.encodeExtension(n);else if(Array.isArray(e))this.encodeArray(e,t);else if(ArrayBuffer.isView(e))this.encodeBinary(e);else{if("object"!=typeof e)throw new Error("Unrecognized object: ".concat(Object.prototype.toString.apply(e)));this.encodeMap(e,t)}},e.prototype.encodeBinary=function(e){var t=e.byteLength;if(t<256)this.writeU8(196),this.writeU8(t);else if(t<65536)this.writeU8(197),this.writeU16(t);else{if(!(t<4294967296))throw new Error("Too large binary: ".concat(t));this.writeU8(198),this.writeU32(t)}var n=un(e);this.writeU8a(n)},e.prototype.encodeArray=function(e,t){var n=e.length;if(n<16)this.writeU8(144+n);else if(n<65536)this.writeU8(220),this.writeU16(n);else{if(!(n<4294967296))throw new Error("Too large array: ".concat(n));this.writeU8(221),this.writeU32(n)}for(var o=0,r=e;o0&&e<=this.maxKeyLength},e.prototype.find=function(e,t,n){e:for(var o=0,r=this.caches[n-1];o=this.maxLengthPerKey?n[Math.random()*n.length|0]=o:n.push(o)},e.prototype.decode=function(e,t,n){var o=this.find(e,t,n);if(null!=o)return this.hit++,o;this.miss++;var r=nn(e,t,n),i=Uint8Array.prototype.slice.call(e,t,t+n);return this.store(i,r),r},e}(),mn=function(e,t){var n,o,r,i,s={label:0,sent:function(){if(1&r[0])throw r[1];return r[1]},trys:[],ops:[]};return i={next:a(0),throw:a(1),return:a(2)},"function"==typeof Symbol&&(i[Symbol.iterator]=function(){return this}),i;function a(i){return function(a){return function(i){if(n)throw new TypeError("Generator is already executing.");for(;s;)try{if(n=1,o&&(r=2&i[0]?o.return:i[0]?o.throw||((r=o.return)&&r.call(o),0):o.next)&&!(r=r.call(o,i[1])).done)return r;switch(o=0,r&&(i=[2&i[0],r.value]),i[0]){case 0:case 1:r=i;break;case 4:return s.label++,{value:i[1],done:!1};case 5:s.label++,o=i[1],i=[0];continue;case 7:i=s.ops.pop(),s.trys.pop();continue;default:if(!((r=(r=s.trys).length>0&&r[r.length-1])||6!==i[0]&&2!==i[0])){s=0;continue}if(3===i[0]&&(!r||i[1]>r[0]&&i[1]=e},e.prototype.createExtraByteError=function(e){var t=this.view,n=this.pos;return new RangeError("Extra ".concat(t.byteLength-n," of ").concat(t.byteLength," byte(s) found at buffer[").concat(e,"]"))},e.prototype.decode=function(e){this.reinitializeState(),this.setBuffer(e);var t=this.doDecodeSync();if(this.hasRemaining(1))throw this.createExtraByteError(this.pos);return t},e.prototype.decodeMulti=function(e){return mn(this,(function(t){switch(t.label){case 0:this.reinitializeState(),this.setBuffer(e),t.label=1;case 1:return this.hasRemaining(1)?[4,this.doDecodeSync()]:[3,3];case 2:return t.sent(),[3,1];case 3:return[2]}}))},e.prototype.decodeAsync=function(e){var t,n,o,r,i,s,a;return i=this,void 0,a=function(){var i,s,a,c,l,h,d,u;return mn(this,(function(p){switch(p.label){case 0:i=!1,p.label=1;case 1:p.trys.push([1,6,7,12]),t=yn(e),p.label=2;case 2:return[4,t.next()];case 3:if((n=p.sent()).done)return[3,5];if(a=n.value,i)throw this.createExtraByteError(this.totalPos);this.appendBuffer(a);try{s=this.doDecodeSync(),i=!0}catch(e){if(!(e instanceof _n))throw e}this.totalPos+=this.pos,p.label=4;case 4:return[3,2];case 5:return[3,12];case 6:return c=p.sent(),o={error:c},[3,12];case 7:return p.trys.push([7,,10,11]),n&&!n.done&&(r=t.return)?[4,r.call(t)]:[3,9];case 8:p.sent(),p.label=9;case 9:return[3,11];case 10:if(o)throw o.error;return[7];case 11:return[7];case 12:if(i){if(this.hasRemaining(1))throw this.createExtraByteError(this.totalPos);return[2,s]}throw h=(l=this).headByte,d=l.pos,u=l.totalPos,new RangeError("Insufficient data in parsing ".concat(fn(h)," at ").concat(u," (").concat(d," in the current buffer)"))}}))},new((s=void 0)||(s=Promise))((function(e,t){function n(e){try{r(a.next(e))}catch(e){t(e)}}function o(e){try{r(a.throw(e))}catch(e){t(e)}}function r(t){var r;t.done?e(t.value):(r=t.value,r instanceof s?r:new s((function(e){e(r)}))).then(n,o)}r((a=a.apply(i,[])).next())}))},e.prototype.decodeArrayStream=function(e){return this.decodeMultiAsync(e,!0)},e.prototype.decodeStream=function(e){return this.decodeMultiAsync(e,!1)},e.prototype.decodeMultiAsync=function(e,t){return function(n,o,r){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var i,s=function(){var n,o,r,i,s,a,c,l,h;return mn(this,(function(d){switch(d.label){case 0:n=t,o=-1,d.label=1;case 1:d.trys.push([1,13,14,19]),r=yn(e),d.label=2;case 2:return[4,vn(r.next())];case 3:if((i=d.sent()).done)return[3,12];if(s=i.value,t&&0===o)throw this.createExtraByteError(this.totalPos);this.appendBuffer(s),n&&(o=this.readArraySize(),n=!1,this.complete()),d.label=4;case 4:d.trys.push([4,9,,10]),d.label=5;case 5:return[4,vn(this.doDecodeSync())];case 6:return[4,d.sent()];case 7:return d.sent(),0==--o?[3,8]:[3,5];case 8:return[3,10];case 9:if(!((a=d.sent())instanceof _n))throw a;return[3,10];case 10:this.totalPos+=this.pos,d.label=11;case 11:return[3,2];case 12:return[3,19];case 13:return c=d.sent(),l={error:c},[3,19];case 14:return d.trys.push([14,,17,18]),i&&!i.done&&(h=r.return)?[4,vn(h.call(r))]:[3,16];case 15:d.sent(),d.label=16;case 16:return[3,18];case 17:if(l)throw l.error;return[7];case 18:return[7];case 19:return[2]}}))}.apply(n,o||[]),a=[];return i={},c("next"),c("throw"),c("return"),i[Symbol.asyncIterator]=function(){return this},i;function c(e){s[e]&&(i[e]=function(t){return new Promise((function(n,o){a.push([e,t,n,o])>1||l(e,t)}))})}function l(e,t){try{(n=s[e](t)).value instanceof vn?Promise.resolve(n.value.v).then(h,d):u(a[0][2],n)}catch(e){u(a[0][3],e)}var n}function h(e){l("next",e)}function d(e){l("throw",e)}function u(e,t){e(t),a.shift(),a.length&&l(a[0][0],a[0][1])}}(this,arguments)},e.prototype.doDecodeSync=function(){e:for(;;){var e=this.readHeadByte(),t=void 0;if(e>=224)t=e-256;else if(e<192)if(e<128)t=e;else if(e<144){if(0!=(o=e-128)){this.pushMapState(o),this.complete();continue e}t={}}else if(e<160){if(0!=(o=e-144)){this.pushArrayState(o),this.complete();continue e}t=[]}else{var n=e-160;t=this.decodeUtf8String(n,0)}else if(192===e)t=null;else if(194===e)t=!1;else if(195===e)t=!0;else if(202===e)t=this.readF32();else if(203===e)t=this.readF64();else if(204===e)t=this.readU8();else if(205===e)t=this.readU16();else if(206===e)t=this.readU32();else if(207===e)t=this.readU64();else if(208===e)t=this.readI8();else if(209===e)t=this.readI16();else if(210===e)t=this.readI32();else if(211===e)t=this.readI64();else if(217===e)n=this.lookU8(),t=this.decodeUtf8String(n,1);else if(218===e)n=this.lookU16(),t=this.decodeUtf8String(n,2);else if(219===e)n=this.lookU32(),t=this.decodeUtf8String(n,4);else if(220===e){if(0!==(o=this.readU16())){this.pushArrayState(o),this.complete();continue e}t=[]}else if(221===e){if(0!==(o=this.readU32())){this.pushArrayState(o),this.complete();continue e}t=[]}else if(222===e){if(0!==(o=this.readU16())){this.pushMapState(o),this.complete();continue e}t={}}else if(223===e){if(0!==(o=this.readU32())){this.pushMapState(o),this.complete();continue e}t={}}else if(196===e){var o=this.lookU8();t=this.decodeBinary(o,1)}else if(197===e)o=this.lookU16(),t=this.decodeBinary(o,2);else if(198===e)o=this.lookU32(),t=this.decodeBinary(o,4);else if(212===e)t=this.decodeExtension(1,0);else if(213===e)t=this.decodeExtension(2,0);else if(214===e)t=this.decodeExtension(4,0);else if(215===e)t=this.decodeExtension(8,0);else if(216===e)t=this.decodeExtension(16,0);else if(199===e)o=this.lookU8(),t=this.decodeExtension(o,1);else if(200===e)o=this.lookU16(),t=this.decodeExtension(o,2);else{if(201!==e)throw new ln("Unrecognized type byte: ".concat(fn(e)));o=this.lookU32(),t=this.decodeExtension(o,4)}this.complete();for(var r=this.stack;r.length>0;){var i=r[r.length-1];if(0===i.type){if(i.array[i.position]=t,i.position++,i.position!==i.size)continue e;r.pop(),t=i.array}else{if(1===i.type){if("string"!=(s=typeof t)&&"number"!==s)throw new ln("The type of key must be string or number but "+typeof t);if("__proto__"===t)throw new ln("The key __proto__ is not allowed");i.key=t,i.type=2;continue e}if(i.map[i.key]=t,i.readCount++,i.readCount!==i.size){i.key=null,i.type=1;continue e}r.pop(),t=i.map}}return t}var s},e.prototype.readHeadByte=function(){return-1===this.headByte&&(this.headByte=this.readU8()),this.headByte},e.prototype.complete=function(){this.headByte=-1},e.prototype.readArraySize=function(){var e=this.readHeadByte();switch(e){case 220:return this.readU16();case 221:return this.readU32();default:if(e<160)return e-144;throw new ln("Unrecognized array type byte: ".concat(fn(e)))}},e.prototype.pushMapState=function(e){if(e>this.maxMapLength)throw new ln("Max length exceeded: map length (".concat(e,") > maxMapLengthLength (").concat(this.maxMapLength,")"));this.stack.push({type:1,size:e,key:null,readCount:0,map:{}})},e.prototype.pushArrayState=function(e){if(e>this.maxArrayLength)throw new ln("Max length exceeded: array length (".concat(e,") > maxArrayLength (").concat(this.maxArrayLength,")"));this.stack.push({type:0,size:e,array:new Array(e),position:0})},e.prototype.decodeUtf8String=function(e,t){var n;if(e>this.maxStrLength)throw new ln("Max length exceeded: UTF-8 byte length (".concat(e,") > maxStrLength (").concat(this.maxStrLength,")"));if(this.bytes.byteLengthsn?function(e,t,n){var o=e.subarray(t,t+n);return rn.decode(o)}(this.bytes,r,e):nn(this.bytes,r,e),this.pos+=t+e,o},e.prototype.stateIsMapKey=function(){return this.stack.length>0&&1===this.stack[this.stack.length-1].type},e.prototype.decodeBinary=function(e,t){if(e>this.maxBinLength)throw new ln("Max length exceeded: bin length (".concat(e,") > maxBinLength (").concat(this.maxBinLength,")"));if(!this.hasRemaining(e+t))throw En;var n=this.pos+t,o=this.bytes.subarray(n,n+e);return this.pos+=t+e,o},e.prototype.decodeExtension=function(e,t){if(e>this.maxExtLength)throw new ln("Max length exceeded: ext length (".concat(e,") > maxExtLength (").concat(this.maxExtLength,")"));var n=this.view.getInt8(this.pos+t),o=this.decodeBinary(e,t+1);return this.extensionCodec.decode(o,n,this.context)},e.prototype.lookU8=function(){return this.view.getUint8(this.pos)},e.prototype.lookU16=function(){return this.view.getUint16(this.pos)},e.prototype.lookU32=function(){return this.view.getUint32(this.pos)},e.prototype.readU8=function(){var e=this.view.getUint8(this.pos);return this.pos++,e},e.prototype.readI8=function(){var e=this.view.getInt8(this.pos);return this.pos++,e},e.prototype.readU16=function(){var e=this.view.getUint16(this.pos);return this.pos+=2,e},e.prototype.readI16=function(){var e=this.view.getInt16(this.pos);return this.pos+=2,e},e.prototype.readU32=function(){var e=this.view.getUint32(this.pos);return this.pos+=4,e},e.prototype.readI32=function(){var e=this.view.getInt32(this.pos);return this.pos+=4,e},e.prototype.readU64=function(){var e,t,n=(e=this.view,t=this.pos,4294967296*e.getUint32(t)+e.getUint32(t+4));return this.pos+=8,n},e.prototype.readI64=function(){var e=Yt(this.view,this.pos);return this.pos+=8,e},e.prototype.readF32=function(){var e=this.view.getFloat32(this.pos);return this.pos+=4,e},e.prototype.readF64=function(){var e=this.view.getFloat64(this.pos);return this.pos+=8,e},e}();class In{static write(e){let t=e.byteLength||e.length;const n=[];do{let e=127&t;t>>=7,t>0&&(e|=128),n.push(e)}while(t>0);t=e.byteLength||e.length;const o=new Uint8Array(n.length+t);return o.set(n,0),o.set(e,n.length),o.buffer}static parse(e){const t=[],n=new Uint8Array(e),o=[0,7,14,21,28];for(let r=0;r7)throw new Error("Messages bigger than 2GB are not supported.");if(!(n.byteLength>=r+s+a))throw new Error("Incomplete message.");t.push(n.slice?n.slice(r+s,r+s+a):n.subarray(r+s,r+s+a)),r=r+s+a}return t}}const kn=new Uint8Array([145,xt.Ping]);class Tn{constructor(e){this.name="messagepack",this.version=1,this.transferFormat=Dt.Binary,this._errorResult=1,this._voidResult=2,this._nonVoidResult=3,e=e||{},this._encoder=new pn(e.extensionCodec,e.context,e.maxDepth,e.initialBufferSize,e.sortKeys,e.forceFloat32,e.ignoreUndefined,e.forceIntegerToFloat),this._decoder=new Cn(e.extensionCodec,e.context,e.maxStrLength,e.maxBinLength,e.maxArrayLength,e.maxMapLength,e.maxExtLength)}parseMessages(e,t){if(!(n=e)||"undefined"==typeof ArrayBuffer||!(n instanceof ArrayBuffer||n.constructor&&"ArrayBuffer"===n.constructor.name))throw new Error("Invalid input for MessagePack hub protocol. Expected an ArrayBuffer.");var n;null===t&&(t=lt.instance);const o=In.parse(e),r=[];for(const e of o){const n=this._parseMessage(e,t);n&&r.push(n)}return r}writeMessage(e){switch(e.type){case xt.Invocation:return this._writeInvocation(e);case xt.StreamInvocation:return this._writeStreamInvocation(e);case xt.StreamItem:return this._writeStreamItem(e);case xt.Completion:return this._writeCompletion(e);case xt.Ping:return In.write(kn);case xt.CancelInvocation:return this._writeCancelInvocation(e);case xt.Close:return this._writeClose();default:throw new Error("Invalid message type.")}}_parseMessage(e,t){if(0===e.length)throw new Error("Invalid payload.");const n=this._decoder.decode(e);if(0===n.length||!(n instanceof Array))throw new Error("Invalid payload.");const o=n[0];switch(o){case xt.Invocation:return this._createInvocationMessage(this._readHeaders(n),n);case xt.StreamItem:return this._createStreamItemMessage(this._readHeaders(n),n);case xt.Completion:return this._createCompletionMessage(this._readHeaders(n),n);case xt.Ping:return this._createPingMessage(n);case xt.Close:return this._createCloseMessage(n);default:return t.log(ct.Information,"Unknown message type '"+o+"' ignored."),null}}_createCloseMessage(e){if(e.length<2)throw new Error("Invalid payload for Close message.");return{allowReconnect:e.length>=3?e[2]:void 0,error:e[1],type:xt.Close}}_createPingMessage(e){if(e.length<1)throw new Error("Invalid payload for Ping message.");return{type:xt.Ping}}_createInvocationMessage(e,t){if(t.length<5)throw new Error("Invalid payload for Invocation message.");const n=t[2];return n?{arguments:t[4],headers:e,invocationId:n,streamIds:[],target:t[3],type:xt.Invocation}:{arguments:t[4],headers:e,streamIds:[],target:t[3],type:xt.Invocation}}_createStreamItemMessage(e,t){if(t.length<4)throw new Error("Invalid payload for StreamItem message.");return{headers:e,invocationId:t[2],item:t[3],type:xt.StreamItem}}_createCompletionMessage(e,t){if(t.length<4)throw new Error("Invalid payload for Completion message.");const n=t[3];if(n!==this._voidResult&&t.length<5)throw new Error("Invalid payload for Completion message.");let o,r;switch(n){case this._errorResult:o=t[4];break;case this._nonVoidResult:r=t[4]}return{error:o,headers:e,invocationId:t[2],result:r,type:xt.Completion}}_writeInvocation(e){let t;return t=e.streamIds?this._encoder.encode([xt.Invocation,e.headers||{},e.invocationId||null,e.target,e.arguments,e.streamIds]):this._encoder.encode([xt.Invocation,e.headers||{},e.invocationId||null,e.target,e.arguments]),In.write(t.slice())}_writeStreamInvocation(e){let t;return t=e.streamIds?this._encoder.encode([xt.StreamInvocation,e.headers||{},e.invocationId,e.target,e.arguments,e.streamIds]):this._encoder.encode([xt.StreamInvocation,e.headers||{},e.invocationId,e.target,e.arguments]),In.write(t.slice())}_writeStreamItem(e){const t=this._encoder.encode([xt.StreamItem,e.headers||{},e.invocationId,e.item]);return In.write(t.slice())}_writeCompletion(e){const t=e.error?this._errorResult:void 0!==e.result?this._nonVoidResult:this._voidResult;let n;switch(t){case this._errorResult:n=this._encoder.encode([xt.Completion,e.headers||{},e.invocationId,t,e.error]);break;case this._voidResult:n=this._encoder.encode([xt.Completion,e.headers||{},e.invocationId,t]);break;case this._nonVoidResult:n=this._encoder.encode([xt.Completion,e.headers||{},e.invocationId,t,e.result])}return In.write(n.slice())}_writeCancelInvocation(e){const t=this._encoder.encode([xt.CancelInvocation,e.headers||{},e.invocationId]);return In.write(t.slice())}_writeClose(){const e=this._encoder.encode([xt.Close,null]);return In.write(e.slice())}_readHeaders(e){const t=e[1];if("object"!=typeof t)throw new Error("Invalid headers.");return t}}let Dn=!1;function xn(){const e=document.querySelector("#blazor-error-ui");e&&(e.style.display="block"),Dn||(Dn=!0,document.querySelectorAll("#blazor-error-ui .reload").forEach((e=>{e.onclick=function(e){location.reload(),e.preventDefault()}})),document.querySelectorAll("#blazor-error-ui .dismiss").forEach((e=>{e.onclick=function(e){const t=document.querySelector("#blazor-error-ui");t&&(t.style.display="none"),e.preventDefault()}})))}const Rn="function"==typeof TextDecoder?new TextDecoder("utf-8"):null,Pn=Rn?Rn.decode.bind(Rn):function(e){let t=0;const n=e.length,o=[],r=[];for(;t65535&&(r-=65536,o.push(r>>>10&1023|55296),r=56320|1023&r),o.push(r)}o.length>1024&&(r.push(String.fromCharCode.apply(null,o)),o.length=0)}return r.push(String.fromCharCode.apply(null,o)),r.join("")},An=Math.pow(2,32),Nn=Math.pow(2,21)-1;function Un(e,t){return e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24}function Mn(e,t){return e[t]+(e[t+1]<<8)+(e[t+2]<<16)+(e[t+3]<<24>>>0)}function Ln(e,t){const n=Mn(e,t+4);if(n>Nn)throw new Error(`Cannot read uint64 with high order part ${n}, because the result would exceed Number.MAX_SAFE_INTEGER.`);return n*An+Mn(e,t)}class $n{constructor(e){this.batchData=e;const t=new Hn(e);this.arrayRangeReader=new jn(e),this.arrayBuilderSegmentReader=new Wn(e),this.diffReader=new Bn(e),this.editReader=new On(e,t),this.frameReader=new Fn(e,t)}updatedComponents(){return Un(this.batchData,this.batchData.length-20)}referenceFrames(){return Un(this.batchData,this.batchData.length-16)}disposedComponentIds(){return Un(this.batchData,this.batchData.length-12)}disposedEventHandlerIds(){return Un(this.batchData,this.batchData.length-8)}updatedComponentsEntry(e,t){const n=e+4*t;return Un(this.batchData,n)}referenceFramesEntry(e,t){return e+20*t}disposedComponentIdsEntry(e,t){const n=e+4*t;return Un(this.batchData,n)}disposedEventHandlerIdsEntry(e,t){const n=e+8*t;return Ln(this.batchData,n)}}class Bn{constructor(e){this.batchDataUint8=e}componentId(e){return Un(this.batchDataUint8,e)}edits(e){return e+4}editsEntry(e,t){return e+16*t}}class On{constructor(e,t){this.batchDataUint8=e,this.stringReader=t}editType(e){return Un(this.batchDataUint8,e)}siblingIndex(e){return Un(this.batchDataUint8,e+4)}newTreeIndex(e){return Un(this.batchDataUint8,e+8)}moveToSiblingIndex(e){return Un(this.batchDataUint8,e+8)}removedAttributeName(e){const t=Un(this.batchDataUint8,e+12);return this.stringReader.readString(t)}}class Fn{constructor(e,t){this.batchDataUint8=e,this.stringReader=t}frameType(e){return Un(this.batchDataUint8,e)}subtreeLength(e){return Un(this.batchDataUint8,e+4)}elementReferenceCaptureId(e){const t=Un(this.batchDataUint8,e+4);return this.stringReader.readString(t)}componentId(e){return Un(this.batchDataUint8,e+8)}elementName(e){const t=Un(this.batchDataUint8,e+8);return this.stringReader.readString(t)}textContent(e){const t=Un(this.batchDataUint8,e+4);return this.stringReader.readString(t)}markupContent(e){const t=Un(this.batchDataUint8,e+4);return this.stringReader.readString(t)}attributeName(e){const t=Un(this.batchDataUint8,e+4);return this.stringReader.readString(t)}attributeValue(e){const t=Un(this.batchDataUint8,e+8);return this.stringReader.readString(t)}attributeEventHandlerId(e){return Ln(this.batchDataUint8,e+12)}}class Hn{constructor(e){this.batchDataUint8=e,this.stringTableStartIndex=Un(e,e.length-4)}readString(e){if(-1===e)return null;{const n=Un(this.batchDataUint8,this.stringTableStartIndex+4*e),o=function(e,t){let n=0,o=0;for(let r=0;r<4;r++){const i=e[t+r];if(n|=(127&i)<this.nextBatchId)return this.fatalError?(this.logger.log(zn.Debug,`Received a new batch ${e} but errored out on a previous batch ${this.nextBatchId-1}`),void await n.send("OnRenderCompleted",this.nextBatchId-1,this.fatalError.toString())):void this.logger.log(zn.Debug,`Waiting for batch ${this.nextBatchId}. Batch ${e} not processed.`);try{this.nextBatchId++,this.logger.log(zn.Debug,`Applying batch ${e}.`),function(e,t){const n=de[e];if(!n)throw new Error(`There is no browser renderer with ID ${e}.`);const o=t.arrayRangeReader,r=t.updatedComponents(),i=o.values(r),s=o.count(r),a=t.referenceFrames(),c=o.values(a),l=t.diffReader;for(let e=0;e=this.minLevel){const n=`[${(new Date).toISOString()}] ${zn[e]}: ${t}`;switch(e){case zn.Critical:case zn.Error:console.error(n);break;case zn.Warning:console.warn(n);break;case zn.Information:console.info(n);break;default:console.log(n)}}}}class Vn{constructor(e,t){this.circuitId=void 0,this.components=e,this.applicationState=t}reconnect(e){if(!this.circuitId)throw new Error("Circuit host not initialized.");return e.state!==Rt.Connected?Promise.resolve(!1):e.invoke("ConnectCircuit",this.circuitId)}initialize(e){if(this.circuitId)throw new Error(`Circuit host '${this.circuitId}' already initialized.`);this.circuitId=e}async startCircuit(e){if(e.state!==Rt.Connected)return!1;const t=await e.invoke("StartCircuit",ke.getBaseURI(),ke.getLocationHref(),JSON.stringify(this.components.map((e=>e.toRecord()))),this.applicationState||"");return!!t&&(this.initialize(t),!0)}resolveElement(e){const t=function(e){const t=f.get(e);if(t)return f.delete(e),t}(e);if(t)return B(t,!0);const n=Number.parseInt(e);if(!Number.isNaN(n))return function(e,t){if(!e.parentNode)throw new Error(`Comment not connected to the DOM ${e.textContent}`);const n=e.parentNode,o=B(n,!0),r=J(o);return Array.from(n.childNodes).forEach((e=>r.push(e))),e[L]=o,t&&(e[$]=t,B(t)),B(e)}(this.components[n].start,this.components[n].end);throw new Error(`Invalid sequence number or identifier '${e}'.`)}}const Xn={configureSignalR:e=>{},logLevel:zn.Warning,reconnectionOptions:{maxRetries:8,retryIntervalMilliseconds:2e4,dialogId:"components-reconnect-modal"}};class Yn{constructor(e,t,n,o){this.maxRetries=t,this.document=n,this.logger=o,this.addedToDom=!1,this.modal=this.document.createElement("div"),this.modal.id=e,this.maxRetries=t,this.modal.style.cssText=["position: fixed","top: 0","right: 0","bottom: 0","left: 0","z-index: 1050","display: none","overflow: hidden","background-color: #fff","opacity: 0.8","text-align: center","font-weight: bold","transition: visibility 0s linear 500ms"].join(";"),this.message=this.document.createElement("h5"),this.message.style.cssText="margin-top: 20px",this.button=this.document.createElement("button"),this.button.style.cssText="margin:5px auto 5px",this.button.textContent="Retry";const r=this.document.createElement("a");r.addEventListener("click",(()=>location.reload())),r.textContent="reload",this.reloadParagraph=this.document.createElement("p"),this.reloadParagraph.textContent="Alternatively, ",this.reloadParagraph.appendChild(r),this.modal.appendChild(this.message),this.modal.appendChild(this.button),this.modal.appendChild(this.reloadParagraph),this.loader=this.getLoader(),this.message.after(this.loader),this.button.addEventListener("click",(async()=>{this.show();try{await Ke.reconnect()||this.rejected()}catch(e){this.logger.log(zn.Error,e),this.failed()}}))}show(){this.addedToDom||(this.addedToDom=!0,this.document.body.appendChild(this.modal)),this.modal.style.display="block",this.loader.style.display="inline-block",this.button.style.display="none",this.reloadParagraph.style.display="none",this.message.textContent="Attempting to reconnect to the server...",this.modal.style.visibility="hidden",setTimeout((()=>{this.modal.style.visibility="visible"}),0)}update(e){this.message.textContent=`Attempting to reconnect to the server: ${e} of ${this.maxRetries}`}hide(){this.modal.style.display="none"}failed(){this.button.style.display="block",this.reloadParagraph.style.display="none",this.loader.style.display="none";const e=this.document.createTextNode("Reconnection failed. Try "),t=this.document.createElement("a");t.textContent="reloading",t.setAttribute("href",""),t.addEventListener("click",(()=>location.reload()));const n=this.document.createTextNode(" the page if you're unable to reconnect.");this.message.replaceChildren(e,t,n)}rejected(){this.button.style.display="none",this.reloadParagraph.style.display="none",this.loader.style.display="none";const e=this.document.createTextNode("Could not reconnect to the server. "),t=this.document.createElement("a");t.textContent="Reload",t.setAttribute("href",""),t.addEventListener("click",(()=>location.reload()));const n=this.document.createTextNode(" the page to restore functionality.");this.message.replaceChildren(e,t,n)}getLoader(){const e=this.document.createElement("div");return e.style.cssText=["border: 0.3em solid #f3f3f3","border-top: 0.3em solid #3498db","border-radius: 50%","width: 2em","height: 2em","display: inline-block"].join(";"),e.animate([{transform:"rotate(0deg)"},{transform:"rotate(360deg)"}],{duration:2e3,iterations:1/0}),e}}class Gn{constructor(e,t,n){this.dialog=e,this.maxRetries=t,this.document=n,this.document=n;const o=this.document.getElementById(Gn.MaxRetriesId);o&&(o.innerText=this.maxRetries.toString())}show(){this.removeClasses(),this.dialog.classList.add(Gn.ShowClassName)}update(e){const t=this.document.getElementById(Gn.CurrentAttemptId);t&&(t.innerText=e.toString())}hide(){this.removeClasses(),this.dialog.classList.add(Gn.HideClassName)}failed(){this.removeClasses(),this.dialog.classList.add(Gn.FailedClassName)}rejected(){this.removeClasses(),this.dialog.classList.add(Gn.RejectedClassName)}removeClasses(){this.dialog.classList.remove(Gn.ShowClassName,Gn.HideClassName,Gn.FailedClassName,Gn.RejectedClassName)}}Gn.ShowClassName="components-reconnect-show",Gn.HideClassName="components-reconnect-hide",Gn.FailedClassName="components-reconnect-failed",Gn.RejectedClassName="components-reconnect-rejected",Gn.MaxRetriesId="components-reconnect-max-retries",Gn.CurrentAttemptId="components-reconnect-current-attempt";class Qn{constructor(e,t,n){this._currentReconnectionProcess=null,this._logger=e,this._reconnectionDisplay=t,this._reconnectCallback=n||Ke.reconnect}onConnectionDown(e,t){if(!this._reconnectionDisplay){const t=document.getElementById(e.dialogId);this._reconnectionDisplay=t?new Gn(t,e.maxRetries,document):new Yn(e.dialogId,e.maxRetries,document,this._logger)}this._currentReconnectionProcess||(this._currentReconnectionProcess=new Zn(e,this._logger,this._reconnectCallback,this._reconnectionDisplay))}onConnectionUp(){this._currentReconnectionProcess&&(this._currentReconnectionProcess.dispose(),this._currentReconnectionProcess=null)}}class Zn{constructor(e,t,n,o){this.logger=t,this.reconnectCallback=n,this.isDisposed=!1,this.reconnectDisplay=o,this.reconnectDisplay.show(),this.attemptPeriodicReconnection(e)}dispose(){this.isDisposed=!0,this.reconnectDisplay.hide()}async attemptPeriodicReconnection(e){for(let t=0;tZn.MaximumFirstRetryInterval?Zn.MaximumFirstRetryInterval:e.retryIntervalMilliseconds;if(await this.delay(n),this.isDisposed)break;try{return await this.reconnectCallback()?void 0:void this.reconnectDisplay.rejected()}catch(e){this.logger.log(zn.Error,e)}}this.reconnectDisplay.failed()}delay(e){return new Promise((t=>setTimeout(t,e)))}}Zn.MaximumFirstRetryInterval=3e3;const eo=/^\s*Blazor-Component-State:(?[a-zA-Z0-9+/=]+)$/;function to(e){var t;if(e.nodeType===Node.COMMENT_NODE){const n=e.textContent||"",o=eo.exec(n),r=o&&o.groups&&o.groups.state;return r&&(null===(t=e.parentNode)||void 0===t||t.removeChild(e)),r}if(!e.hasChildNodes())return;const n=e.childNodes;for(let e=0;e.*)$/);function ro(e,t){const n=e.currentElement;if(n&&n.nodeType===Node.COMMENT_NODE&&n.textContent){const o=oo.exec(n.textContent),r=o&&o.groups&&o.groups.descriptor;if(!r)return;!function(e){if(e.parentNode instanceof Document)throw new Error("Root components cannot be marked as interactive. The element must be rendered statically so that scripts are not evaluated multiple times.")}(n);try{const o=function(e){const t=JSON.parse(e),{type:n}=t;if("server"!==n&&"webassembly"!==n)throw new Error(`Invalid component type '${n}'.`);return t}(r);switch(t){case"webassembly":return function(e,t,n){const{type:o,assembly:r,typeName:i,parameterDefinitions:s,parameterValues:a,prerenderId:c}=e,l=c?io(c,n):void 0;if(c&&!l)throw new Error(`Could not find an end component comment for '${t}'.`);if("webassembly"===o){if(!r)throw new Error("assembly must be defined when using a descriptor.");if(!i)throw new Error("typeName must be defined when using a descriptor.");return{type:o,assembly:r,typeName:i,parameterDefinitions:s&&atob(s),parameterValues:a&&atob(a),start:t,prerenderId:c,end:l}}}(o,n,e);case"server":return function(e,t,n){const{type:o,descriptor:r,sequence:i,prerenderId:s}=e,a=s?io(s,n):void 0;if(s&&!a)throw new Error(`Could not find an end component comment for '${t}'.`);if("server"===o){if(!r)throw new Error("descriptor must be defined when using a descriptor.");if(void 0===i)throw new Error("sequence must be defined when using a descriptor.");if(!Number.isInteger(i))throw new Error(`Error parsing the sequence '${i}' for component '${JSON.stringify(e)}'`);return{type:o,sequence:i,descriptor:r,start:t,prerenderId:s,end:a}}}(o,n,e)}}catch(e){throw new Error(`Found malformed component comment at ${n.textContent}`)}}}function io(e,t){for(;t.next()&&t.currentElement;){const n=t.currentElement;if(n.nodeType!==Node.COMMENT_NODE)continue;if(!n.textContent)continue;const o=oo.exec(n.textContent),r=o&&o[1];if(r)return so(r,e),n}}function so(e,t){const n=JSON.parse(e);if(1!==Object.keys(n).length)throw new Error(`Invalid end of component comment: '${e}'`);const o=n.prerenderId;if(!o)throw new Error(`End of component comment must have a value for the prerendered property: '${e}'`);if(o!==t)throw new Error(`End of component comment prerendered property must match the start comment prerender id: '${t}', '${o}'`)}class ao{constructor(e){this.childNodes=e,this.currentIndex=-1,this.length=e.length}next(){return this.currentIndex++,this.currentIndexasync function(e,n){const o=function(e){const t=document.baseURI;return t.endsWith("/")?`${t}${e}`:`${t}/${e}`}(n),r=await import(o);if(void 0===r)return;const{beforeStart:i,afterStarted:s}=r;return s&&e.afterStartedCallbacks.push(s),i?i(...t):void 0}(this,e))))}async invokeAfterStartedCallbacks(e){await C,await Promise.all(this.afterStartedCallbacks.map((t=>t(e))))}}let uo,po,fo,go=!1;async function mo(t,n){const o=function(e){const t={...Xn,...e};return e&&e.reconnectionOptions&&(t.reconnectionOptions={...Xn.reconnectionOptions,...e.reconnectionOptions}),t}(t),r=await async function(e){const t=await fetch("_blazor/initializers",{method:"GET",credentials:"include",cache:"no-cache"}),n=await t.json(),o=new ho;return await o.importInitializersAsync(n,[e]),o}(o),i=new Kn(o.logLevel);Ke.reconnect=async e=>{if(go)return!1;const t=e||await yo(o,i,po);return await po.reconnect(t)?(o.reconnectionHandler.onConnectionUp(),!0):(i.log(zn.Information,"Reconnection attempt to the circuit was rejected by the server. This may indicate that the associated state is no longer available on the server."),!1)},Ke.defaultReconnectionHandler=new Qn(i),o.reconnectionHandler=o.reconnectionHandler||Ke.defaultReconnectionHandler,i.log(zn.Information,"Starting up Blazor server-side application.");const s=to(document);po=new Vn(n||[],s||""),Ke._internal.navigationManager.listenForNavigationEvents(((e,t,n)=>uo.send("OnLocationChanged",e,t,n)),((e,t,n,o)=>uo.send("OnLocationChanging",e,t,n,o))),Ke._internal.forceCloseConnection=()=>uo.stop(),Ke._internal.sendJSDataStream=(e,t,n)=>function(e,t,n,o){setTimeout((async()=>{let r=5,i=(new Date).valueOf();try{const s=t instanceof Blob?t.size:t.byteLength;let a=0,c=0;for(;a1)await e.send("ReceiveJSDataChunk",n,c,h,null);else{if(!await e.invoke("ReceiveJSDataChunk",n,c,h,null))break;const t=(new Date).valueOf(),o=t-i;i=t,r=Math.max(1,Math.round(500/Math.max(1,o)))}a+=l,c++}}catch(t){await e.send("ReceiveJSDataChunk",n,-1,null,t.toString())}}),0)}(uo,e,t,n),fo=e.attachDispatcher({beginInvokeDotNetFromJS:(e,t,n,o,r)=>{uo.send("BeginInvokeDotNetFromJS",e?e.toString():null,t,n,o||0,r)},endInvokeJSFromDotNet:(e,t,n)=>{uo.send("EndInvokeJSFromDotNet",e,t,n)},sendByteArray:(e,t)=>{uo.send("ReceiveByteArray",e,t)}});const a=await yo(o,i,po);if(!await po.startCircuit(a))return void i.log(zn.Error,"Failed to start the circuit.");let c=!1;const l=()=>{if(!c){const e=new FormData,t=po.circuitId;e.append("circuitId",t),c=navigator.sendBeacon("_blazor/disconnect",e)}};Ke.disconnect=l,window.addEventListener("unload",l,{capture:!1,once:!0}),i.log(zn.Information,"Blazor server-side application started."),r.invokeAfterStartedCallbacks(Ke)}async function yo(e,t,n){var o,r;const i=new Tn;i.name="blazorpack";const s=(new zt).withUrl("_blazor").withHubProtocol(i);e.configureSignalR(s);const a=s.build();a.on("JS.AttachComponent",((e,t)=>function(e,t,n,o){let r=de[0];r||(r=new ce(0),de[0]=r),r.attachRootComponentToLogicalElement(n,t,!1)}(0,n.resolveElement(t),e))),a.on("JS.BeginInvokeJS",fo.beginInvokeJSFromDotNet.bind(fo)),a.on("JS.EndInvokeDotNet",fo.endInvokeDotNetFromJS.bind(fo)),a.on("JS.ReceiveByteArray",fo.receiveByteArray.bind(fo)),a.on("JS.BeginTransmitStream",(e=>{const t=new ReadableStream({start(t){a.stream("SendDotNetStreamToJS",e).subscribe({next:e=>t.enqueue(e),complete:()=>t.close(),error:e=>t.error(e)})}});fo.supplyDotNetStream(e,t)}));const c=Jn.getOrCreate(t);a.on("JS.RenderBatch",((e,n)=>{t.log(zn.Debug,`Received render batch with id ${e} and ${n.byteLength} bytes.`),c.processBatch(e,n,a)})),a.on("JS.EndLocationChanging",Ke._internal.navigationManager.endLocationChanging),a.onclose((t=>!go&&e.reconnectionHandler.onConnectionDown(e.reconnectionOptions,t))),a.on("JS.Error",(e=>{go=!0,vo(a,e,t),xn()}));try{await a.start(),uo=a}catch(e){if(vo(a,e,t),"FailedToNegotiateWithServerError"===e.errorType)throw e;xn(),e.innerErrors&&(e.innerErrors.some((e=>"UnsupportedTransportError"===e.errorType&&e.transport===Tt.WebSockets))?t.log(zn.Error,"Unable to connect, please ensure you are using an updated browser that supports WebSockets."):e.innerErrors.some((e=>"FailedToStartTransportError"===e.errorType&&e.transport===Tt.WebSockets))?t.log(zn.Error,"Unable to connect, please ensure WebSockets are available. A VPN or proxy may be blocking the connection."):e.innerErrors.some((e=>"DisabledTransportError"===e.errorType&&e.transport===Tt.LongPolling))&&t.log(zn.Error,"Unable to initiate a SignalR connection to the server. This might be because the server is not configured to support WebSockets. For additional details, visit https://aka.ms/blazor-server-websockets-error."))}return(null===(r=null===(o=a.connection)||void 0===o?void 0:o.features)||void 0===r?void 0:r.inherentKeepAlive)&&t.log(zn.Warning,"Failed to connect via WebSockets, using the Long Polling fallback transport. This may be due to a VPN or proxy blocking the connection. To troubleshoot this, visit https://aka.ms/blazor-server-using-fallback-long-polling."),a}function vo(e,t,n){n.log(zn.Error,t),e&&e.stop()}let wo=!1;function bo(e){if(wo)throw new Error("Blazor has already started.");return wo=!0,mo(e,function(e,t){return function(e){const t=no(e,"server"),n=[];for(let e=0;ee.sequence-t.sequence))}(e)}(document))}Ke.start=bo,window.DotNet=e,document&&document.currentScript&&"false"!==document.currentScript.getAttribute("autostart")&&bo()})()})(); \ No newline at end of file +(()=>{var e={778:()=>{},77:()=>{},203:()=>{},200:()=>{},628:()=>{},321:()=>{}},t={};function n(o){var r=t[o];if(void 0!==r)return r.exports;var s=t[o]={exports:{}};return e[o](s,s.exports,n),s.exports}n.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(e){if("object"==typeof window)return window}}(),(()=>{"use strict";var e,t,o;!function(e){const t=[],n="__jsObjectId",o="__dotNetObject",r="__byte[]",s="__dotNetStream",i="__jsStreamReferenceLength";let a,c;class l{constructor(e){this._jsObject=e,this._cachedFunctions=new Map}findFunction(e){const t=this._cachedFunctions.get(e);if(t)return t;let n,o=this._jsObject;if(e.split(".").forEach((t=>{if(!(t in o))throw new Error(`Could not find '${e}' ('${t}' was undefined).`);n=o,o=o[t]})),o instanceof Function)return o=o.bind(n),this._cachedFunctions.set(e,o),o;throw new Error(`The value '${e}' is not a function.`)}getWrappedObject(){return this._jsObject}}const h={0:new l(window)};h[0]._cachedFunctions.set("import",(e=>("string"==typeof e&&e.startsWith("./")&&(e=new URL(e.substr(2),document.baseURI).toString()),import(e))));let d,u=1;function p(e){t.push(e)}function f(e){if(e&&"object"==typeof e){h[u]=new l(e);const t={[n]:u};return u++,t}throw new Error(`Cannot create a JSObjectReference from the value '${e}'.`)}function g(e){let t=-1;if(e instanceof ArrayBuffer&&(e=new Uint8Array(e)),e instanceof Blob)t=e.size;else{if(!(e.buffer instanceof ArrayBuffer))throw new Error("Supplied value is not a typed array or blob.");if(void 0===e.byteLength)throw new Error(`Cannot create a JSStreamReference from the value '${e}' as it doesn't have a byteLength.`);t=e.byteLength}const o={[i]:t};try{const t=f(e);o[n]=t[n]}catch(t){throw new Error(`Cannot create a JSStreamReference from the value '${e}'.`)}return o}function m(e,n){c=e;const o=n?JSON.parse(n,((e,n)=>t.reduce(((t,n)=>n(e,t)),n))):null;return c=void 0,o}function y(){if(void 0===a)throw new Error("No call dispatcher has been set.");if(null===a)throw new Error("There are multiple .NET runtimes present, so a default dispatcher could not be resolved. Use DotNetObject to invoke .NET instance methods.");return a}e.attachDispatcher=function(e){const t=new v(e);return void 0===a?a=t:a&&(a=null),t},e.attachReviver=p,e.invokeMethod=function(e,t,...n){return y().invokeDotNetStaticMethod(e,t,...n)},e.invokeMethodAsync=function(e,t,...n){return y().invokeDotNetStaticMethodAsync(e,t,...n)},e.createJSObjectReference=f,e.createJSStreamReference=g,e.disposeJSObjectReference=function(e){const t=e&&e[n];"number"==typeof t&&_(t)},function(e){e[e.Default=0]="Default",e[e.JSObjectReference=1]="JSObjectReference",e[e.JSStreamReference=2]="JSStreamReference",e[e.JSVoidResult=3]="JSVoidResult"}(d=e.JSCallResultType||(e.JSCallResultType={}));class v{constructor(e){this._dotNetCallDispatcher=e,this._byteArraysToBeRevived=new Map,this._pendingDotNetToJSStreams=new Map,this._pendingAsyncCalls={},this._nextAsyncCallId=1}getDotNetCallDispatcher(){return this._dotNetCallDispatcher}invokeJSFromDotNet(e,t,n,o){const r=m(this,t),s=I(b(e,o)(...r||[]),n);return null==s?null:T(this,s)}beginInvokeJSFromDotNet(e,t,n,o,r){const s=new Promise((e=>{const o=m(this,n);e(b(t,r)(...o||[]))}));e&&s.then((t=>T(this,[e,!0,I(t,o)]))).then((t=>this._dotNetCallDispatcher.endInvokeJSFromDotNet(e,!0,t)),(t=>this._dotNetCallDispatcher.endInvokeJSFromDotNet(e,!1,JSON.stringify([e,!1,w(t)]))))}endInvokeDotNetFromJS(e,t,n){const o=t?m(this,n):new Error(n);this.completePendingCall(parseInt(e,10),t,o)}invokeDotNetStaticMethod(e,t,...n){return this.invokeDotNetMethod(e,t,null,n)}invokeDotNetStaticMethodAsync(e,t,...n){return this.invokeDotNetMethodAsync(e,t,null,n)}invokeDotNetMethod(e,t,n,o){if(this._dotNetCallDispatcher.invokeDotNetFromJS){const r=T(this,o),s=this._dotNetCallDispatcher.invokeDotNetFromJS(e,t,n,r);return s?m(this,s):null}throw new Error("The current dispatcher does not support synchronous calls from JS to .NET. Use invokeDotNetMethodAsync instead.")}invokeDotNetMethodAsync(e,t,n,o){if(e&&n)throw new Error(`For instance method calls, assemblyName should be null. Received '${e}'.`);const r=this._nextAsyncCallId++,s=new Promise(((e,t)=>{this._pendingAsyncCalls[r]={resolve:e,reject:t}}));try{const s=T(this,o);this._dotNetCallDispatcher.beginInvokeDotNetFromJS(r,e,t,n,s)}catch(e){this.completePendingCall(r,!1,e)}return s}receiveByteArray(e,t){this._byteArraysToBeRevived.set(e,t)}processByteArray(e){const t=this._byteArraysToBeRevived.get(e);return t?(this._byteArraysToBeRevived.delete(e),t):null}supplyDotNetStream(e,t){if(this._pendingDotNetToJSStreams.has(e)){const n=this._pendingDotNetToJSStreams.get(e);this._pendingDotNetToJSStreams.delete(e),n.resolve(t)}else{const n=new S;n.resolve(t),this._pendingDotNetToJSStreams.set(e,n)}}getDotNetStreamPromise(e){let t;if(this._pendingDotNetToJSStreams.has(e))t=this._pendingDotNetToJSStreams.get(e).streamPromise,this._pendingDotNetToJSStreams.delete(e);else{const n=new S;this._pendingDotNetToJSStreams.set(e,n),t=n.streamPromise}return t}completePendingCall(e,t,n){if(!this._pendingAsyncCalls.hasOwnProperty(e))throw new Error(`There is no pending async call with ID ${e}.`);const o=this._pendingAsyncCalls[e];delete this._pendingAsyncCalls[e],t?o.resolve(n):o.reject(n)}}function w(e){return e instanceof Error?`${e.message}\n${e.stack}`:e?e.toString():"null"}function b(e,t){const n=h[t];if(n)return n.findFunction(e);throw new Error(`JS object instance with ID ${t} does not exist (has it been disposed?).`)}function _(e){delete h[e]}e.findJSFunction=b,e.disposeJSObjectReferenceById=_;class E{constructor(e,t){this._id=e,this._callDispatcher=t}invokeMethod(e,...t){return this._callDispatcher.invokeDotNetMethod(null,e,this._id,t)}invokeMethodAsync(e,...t){return this._callDispatcher.invokeDotNetMethodAsync(null,e,this._id,t)}dispose(){this._callDispatcher.invokeDotNetMethodAsync(null,"__Dispose",this._id,null).catch((e=>console.error(e)))}serializeAsArg(){return{[o]:this._id}}}e.DotNetObject=E,p((function(e,t){if(t&&"object"==typeof t){if(t.hasOwnProperty(o))return new E(t[o],c);if(t.hasOwnProperty(n)){const e=t[n],o=h[e];if(o)return o.getWrappedObject();throw new Error(`JS object instance with Id '${e}' does not exist. It may have been disposed.`)}if(t.hasOwnProperty(r)){const e=t[r],n=c.processByteArray(e);if(void 0===n)throw new Error(`Byte array index '${e}' does not exist.`);return n}if(t.hasOwnProperty(s)){const e=t[s],n=c.getDotNetStreamPromise(e);return new C(n)}}return t}));class C{constructor(e){this._streamPromise=e}stream(){return this._streamPromise}async arrayBuffer(){return new Response(await this.stream()).arrayBuffer()}}class S{constructor(){this.streamPromise=new Promise(((e,t)=>{this.resolve=e,this.reject=t}))}}function I(e,t){switch(t){case d.Default:return e;case d.JSObjectReference:return f(e);case d.JSStreamReference:return g(e);case d.JSVoidResult:return null;default:throw new Error(`Invalid JS call result type '${t}'.`)}}let k=0;function T(e,t){k=0,c=e;const n=JSON.stringify(t,D);return c=void 0,n}function D(e,t){if(t instanceof E)return t.serializeAsArg();if(t instanceof Uint8Array){c.getDotNetCallDispatcher().sendByteArray(k,t);const e={[r]:k};return k++,e}return t}}(e||(e={})),function(e){e[e.prependFrame=1]="prependFrame",e[e.removeFrame=2]="removeFrame",e[e.setAttribute=3]="setAttribute",e[e.removeAttribute=4]="removeAttribute",e[e.updateText=5]="updateText",e[e.stepIn=6]="stepIn",e[e.stepOut=7]="stepOut",e[e.updateMarkup=8]="updateMarkup",e[e.permutationListEntry=9]="permutationListEntry",e[e.permutationListEnd=10]="permutationListEnd"}(t||(t={})),function(e){e[e.element=1]="element",e[e.text=2]="text",e[e.attribute=3]="attribute",e[e.component=4]="component",e[e.region=5]="region",e[e.elementReferenceCapture=6]="elementReferenceCapture",e[e.markup=8]="markup",e[e.namedEvent=10]="namedEvent"}(o||(o={}));class r{constructor(e,t){this.componentId=e,this.fieldValue=t}static fromEvent(e,t){const n=t.target;if(n instanceof Element){const t=function(e){return e instanceof HTMLInputElement?e.type&&"checkbox"===e.type.toLowerCase()?{value:e.checked}:{value:e.value}:e instanceof HTMLSelectElement||e instanceof HTMLTextAreaElement?{value:e.value}:null}(n);if(t)return new r(e,t.value)}return null}}const s=new Map,i=new Map,a=[];function c(e){return s.get(e)}function l(e){const t=s.get(e);return(null==t?void 0:t.browserEventName)||e}function h(e,t){e.forEach((e=>s.set(e,t)))}function d(e){const t=[];for(let n=0;ne.selected)).map((e=>e.value))}}{const e=function(e){return!!e&&"INPUT"===e.tagName&&"checkbox"===e.getAttribute("type")}(t);return{value:e?!!t.checked:t.value}}}}),h(["copy","cut","paste"],{createEventArgs:e=>({type:e.type})}),h(["drag","dragend","dragenter","dragleave","dragover","dragstart","drop"],{createEventArgs:e=>{return{...u(t=e),dataTransfer:t.dataTransfer?{dropEffect:t.dataTransfer.dropEffect,effectAllowed:t.dataTransfer.effectAllowed,files:Array.from(t.dataTransfer.files).map((e=>e.name)),items:Array.from(t.dataTransfer.items).map((e=>({kind:e.kind,type:e.type}))),types:t.dataTransfer.types}:null};var t}}),h(["focus","blur","focusin","focusout"],{createEventArgs:e=>({type:e.type})}),h(["keydown","keyup","keypress"],{createEventArgs:e=>{return{key:(t=e).key,code:t.code,location:t.location,repeat:t.repeat,ctrlKey:t.ctrlKey,shiftKey:t.shiftKey,altKey:t.altKey,metaKey:t.metaKey,type:t.type};var t}}),h(["contextmenu","click","mouseover","mouseout","mousemove","mousedown","mouseup","mouseleave","mouseenter","dblclick"],{createEventArgs:e=>u(e)}),h(["error"],{createEventArgs:e=>{return{message:(t=e).message,filename:t.filename,lineno:t.lineno,colno:t.colno,type:t.type};var t}}),h(["loadstart","timeout","abort","load","loadend","progress"],{createEventArgs:e=>{return{lengthComputable:(t=e).lengthComputable,loaded:t.loaded,total:t.total,type:t.type};var t}}),h(["touchcancel","touchend","touchmove","touchenter","touchleave","touchstart"],{createEventArgs:e=>{return{detail:(t=e).detail,touches:d(t.touches),targetTouches:d(t.targetTouches),changedTouches:d(t.changedTouches),ctrlKey:t.ctrlKey,shiftKey:t.shiftKey,altKey:t.altKey,metaKey:t.metaKey,type:t.type};var t}}),h(["gotpointercapture","lostpointercapture","pointercancel","pointerdown","pointerenter","pointerleave","pointermove","pointerout","pointerover","pointerup"],{createEventArgs:e=>{return{...u(t=e),pointerId:t.pointerId,width:t.width,height:t.height,pressure:t.pressure,tiltX:t.tiltX,tiltY:t.tiltY,pointerType:t.pointerType,isPrimary:t.isPrimary};var t}}),h(["wheel","mousewheel"],{createEventArgs:e=>{return{...u(t=e),deltaX:t.deltaX,deltaY:t.deltaY,deltaZ:t.deltaZ,deltaMode:t.deltaMode};var t}}),h(["toggle"],{createEventArgs:()=>({})});const p=["date","datetime-local","month","time","week"],f=new Map;let g,m,y=0;const v={async add(e,t,n){if(!n)throw new Error("initialParameters must be an object, even if empty.");const o="__bl-dynamic-root:"+(++y).toString();f.set(o,e);const r=await _().invokeMethodAsync("AddRootComponent",t,o),s=new b(r,m[t]);return await s.setParameters(n),s}};class w{invoke(e){return this._callback(e)}setCallback(t){this._selfJSObjectReference||(this._selfJSObjectReference=e.createJSObjectReference(this)),this._callback=t}getJSObjectReference(){return this._selfJSObjectReference}dispose(){this._selfJSObjectReference&&e.disposeJSObjectReference(this._selfJSObjectReference)}}class b{constructor(e,t){this._jsEventCallbackWrappers=new Map,this._componentId=e;for(const e of t)"eventcallback"===e.type&&this._jsEventCallbackWrappers.set(e.name.toLowerCase(),new w)}setParameters(e){const t={},n=Object.entries(e||{}),o=n.length;for(const[e,o]of n){const n=this._jsEventCallbackWrappers.get(e.toLowerCase());n&&o?(n.setCallback(o),t[e]=n.getJSObjectReference()):t[e]=o}return _().invokeMethodAsync("SetRootComponentParameters",this._componentId,o,t)}async dispose(){if(null!==this._componentId){await _().invokeMethodAsync("RemoveRootComponent",this._componentId),this._componentId=null;for(const e of this._jsEventCallbackWrappers.values())e.dispose()}}}function _(){if(!g)throw new Error("Dynamic root components have not been enabled in this application.");return g}const E=new Map,C=new Map,S=new Map;let I;const k=new Promise((e=>{I=e}));function T(e,t,n){return x(e,t.eventHandlerId,(()=>D(e).invokeMethodAsync("DispatchEventAsync",t,n)))}function D(e){const t=E.get(e);if(!t)throw new Error(`No interop methods are registered for renderer ${e}`);return t}let x=(e,t,n)=>n();const R=M(["abort","blur","canplay","canplaythrough","change","cuechange","durationchange","emptied","ended","error","focus","load","loadeddata","loadedmetadata","loadend","loadstart","mouseenter","mouseleave","pointerenter","pointerleave","pause","play","playing","progress","ratechange","reset","scroll","seeked","seeking","stalled","submit","suspend","timeupdate","toggle","unload","volumechange","waiting","DOMNodeInsertedIntoDocument","DOMNodeRemovedFromDocument"]),A={submit:!0},N=M(["click","dblclick","mousedown","mousemove","mouseup"]);class P{constructor(e){this.browserRendererId=e,this.afterClickCallbacks=[];const t=++P.nextEventDelegatorId;this.eventsCollectionKey=`_blazorEvents_${t}`,this.eventInfoStore=new U(this.onGlobalEvent.bind(this))}setListener(e,t,n,o){const r=this.getEventHandlerInfosForElement(e,!0),s=r.getHandler(t);if(s)this.eventInfoStore.update(s.eventHandlerId,n);else{const s={element:e,eventName:t,eventHandlerId:n,renderingComponentId:o};this.eventInfoStore.add(s),r.setHandler(t,s)}}getHandler(e){return this.eventInfoStore.get(e)}removeListener(e){const t=this.eventInfoStore.remove(e);if(t){const e=t.element,n=this.getEventHandlerInfosForElement(e,!1);n&&n.removeHandler(t.eventName)}}notifyAfterClick(e){this.afterClickCallbacks.push(e),this.eventInfoStore.addGlobalListener("click")}setStopPropagation(e,t,n){this.getEventHandlerInfosForElement(e,!0).stopPropagation(t,n)}setPreventDefault(e,t,n){this.getEventHandlerInfosForElement(e,!0).preventDefault(t,n)}onGlobalEvent(e){if(!(e.target instanceof Element))return;this.dispatchGlobalEventToAllElements(e.type,e);const t=(n=e.type,i.get(n));var n;t&&t.forEach((t=>this.dispatchGlobalEventToAllElements(t,e))),"click"===e.type&&this.afterClickCallbacks.forEach((t=>t(e)))}dispatchGlobalEventToAllElements(e,t){const n=t.composedPath();let o=n.shift(),s=null,i=!1;const a=Object.prototype.hasOwnProperty.call(R,e);let l=!1;for(;o;){const u=o,p=this.getEventHandlerInfosForElement(u,!1);if(p){const n=p.getHandler(e);if(n&&(h=u,d=t.type,!((h instanceof HTMLButtonElement||h instanceof HTMLInputElement||h instanceof HTMLTextAreaElement||h instanceof HTMLSelectElement)&&Object.prototype.hasOwnProperty.call(N,d)&&h.disabled))){if(!i){const n=c(e);s=(null==n?void 0:n.createEventArgs)?n.createEventArgs(t):{},i=!0}Object.prototype.hasOwnProperty.call(A,t.type)&&t.preventDefault(),T(this.browserRendererId,{eventHandlerId:n.eventHandlerId,eventName:e,eventFieldInfo:r.fromEvent(n.renderingComponentId,t)},s)}p.stopPropagation(e)&&(l=!0),p.preventDefault(e)&&t.preventDefault()}o=a||l?void 0:n.shift()}var h,d}getEventHandlerInfosForElement(e,t){return Object.prototype.hasOwnProperty.call(e,this.eventsCollectionKey)?e[this.eventsCollectionKey]:t?e[this.eventsCollectionKey]=new B:null}}P.nextEventDelegatorId=0;class U{constructor(e){this.globalListener=e,this.infosByEventHandlerId={},this.countByEventName={},a.push(this.handleEventNameAliasAdded.bind(this))}add(e){if(this.infosByEventHandlerId[e.eventHandlerId])throw new Error(`Event ${e.eventHandlerId} is already tracked`);this.infosByEventHandlerId[e.eventHandlerId]=e,this.addGlobalListener(e.eventName)}get(e){return this.infosByEventHandlerId[e]}addGlobalListener(e){if(e=l(e),Object.prototype.hasOwnProperty.call(this.countByEventName,e))this.countByEventName[e]++;else{this.countByEventName[e]=1;const t=Object.prototype.hasOwnProperty.call(R,e);document.addEventListener(e,this.globalListener,t)}}update(e,t){if(Object.prototype.hasOwnProperty.call(this.infosByEventHandlerId,t))throw new Error(`Event ${t} is already tracked`);const n=this.infosByEventHandlerId[e];delete this.infosByEventHandlerId[e],n.eventHandlerId=t,this.infosByEventHandlerId[t]=n}remove(e){const t=this.infosByEventHandlerId[e];if(t){delete this.infosByEventHandlerId[e];const n=l(t.eventName);0==--this.countByEventName[n]&&(delete this.countByEventName[n],document.removeEventListener(n,this.globalListener))}return t}handleEventNameAliasAdded(e,t){if(Object.prototype.hasOwnProperty.call(this.countByEventName,e)){const n=this.countByEventName[e];delete this.countByEventName[e],document.removeEventListener(e,this.globalListener),this.addGlobalListener(t),this.countByEventName[t]+=n-1}}}class B{constructor(){this.handlers={},this.preventDefaultFlags=null,this.stopPropagationFlags=null}getHandler(e){return Object.prototype.hasOwnProperty.call(this.handlers,e)?this.handlers[e]:null}setHandler(e,t){this.handlers[e]=t}removeHandler(e){delete this.handlers[e]}preventDefault(e,t){return void 0!==t&&(this.preventDefaultFlags=this.preventDefaultFlags||{},this.preventDefaultFlags[e]=t),!!this.preventDefaultFlags&&this.preventDefaultFlags[e]}stopPropagation(e,t){return void 0!==t&&(this.stopPropagationFlags=this.stopPropagationFlags||{},this.stopPropagationFlags[e]=t),!!this.stopPropagationFlags&&this.stopPropagationFlags[e]}}function M(e){const t={};return e.forEach((e=>{t[e]=!0})),t}const $=Symbol(),L=Symbol(),O=Symbol();function F(e,t){if($ in e)return e;const n=[];if(e.childNodes.length>0){if(!t)throw new Error("New logical elements must start empty, or allowExistingContents must be true");e.childNodes.forEach((t=>{const o=F(t,!0);o[L]=e,n.push(o)}))}return e[$]=n,e}function H(e){const t=V(e);for(;t.length;)z(e,0)}function j(e,t){const n=document.createComment("!");return W(n,e,t),n}function W(e,t,n){const o=e;let r=e;if($ in e){const t=Z(o);if(t!==e){const n=new Range;n.setStartBefore(e),n.setEndAfter(t),r=n.extractContents()}}const s=J(o);if(s){const e=V(s),t=Array.prototype.indexOf.call(e,o);e.splice(t,1),delete o[L]}const i=V(t);if(n0;)z(n,0)}const o=n;o.parentNode.removeChild(o)}function J(e){return e[L]||null}function q(e,t){return V(e)[t]}function K(e){const t=G(e);return"http://www.w3.org/2000/svg"===t.namespaceURI&&"foreignObject"!==t.tagName}function V(e){return e[$]}function X(e){const t=V(J(e));return t[Array.prototype.indexOf.call(t,e)+1]||null}function Y(e,t){const n=V(e);t.forEach((e=>{e.moveRangeStart=n[e.fromSiblingIndex],e.moveRangeEnd=Z(e.moveRangeStart)})),t.forEach((t=>{const o=document.createComment("marker");t.moveToBeforeMarker=o;const r=n[t.toSiblingIndex+1];r?r.parentNode.insertBefore(o,r):Q(o,e)})),t.forEach((e=>{const t=e.moveToBeforeMarker,n=t.parentNode,o=e.moveRangeStart,r=e.moveRangeEnd;let s=o;for(;s;){const e=s.nextSibling;if(n.insertBefore(s,t),s===r)break;s=e}n.removeChild(t)})),t.forEach((e=>{n[e.toSiblingIndex]=e.moveRangeStart}))}function G(e){if(e instanceof Element||e instanceof DocumentFragment)return e;if(e instanceof Comment)return e.parentNode;throw new Error("Not a valid logical element")}function Q(e,t){if(t instanceof Element||t instanceof DocumentFragment)t.appendChild(e);else{if(!(t instanceof Comment))throw new Error(`Cannot append node because the parent is not a valid logical element. Parent: ${t}`);{const n=X(t);n?n.parentNode.insertBefore(e,n):Q(e,J(t))}}}function Z(e){if(e instanceof Element||e instanceof DocumentFragment)return e;const t=X(e);if(t)return t.previousSibling;{const t=J(e);return t instanceof Element||t instanceof DocumentFragment?t.lastChild:Z(t)}}function ee(e){return`_bl_${e}`}const te="__internalId";e.attachReviver(((e,t)=>t&&"object"==typeof t&&Object.prototype.hasOwnProperty.call(t,te)&&"string"==typeof t[te]?function(e){const t=`[${ee(e)}]`;return document.querySelector(t)}(t[te]):t));const ne="_blazorDeferredValue";function oe(e){return"select-multiple"===e.type}function re(e,t){e.value=t||""}function se(e,t){e instanceof HTMLSelectElement?oe(e)?function(e,t){t||(t=[]);for(let n=0;n{ve&&function(e,t){if(0!==e.button||function(e){return e.ctrlKey||e.shiftKey||e.altKey||e.metaKey}(e))return;if(e.defaultPrevented)return;const n=function(e){const t=!window._blazorDisableComposedPath&&e.composedPath&&e.composedPath();if(t){for(let e=0;edocument.baseURI,getLocationHref:()=>location.href,scrollToElement:Ae};function Ae(e){const t=document.getElementById(e);return!!t&&(t.scrollIntoView(),!0)}function Ne(e,t,n=!1){const o=be(e);!t.forceLoad&&we(o)?Pe(o,!1,t.replaceHistoryEntry,t.historyEntryState,n):function(e,t){if(location.href===e){const t=e+"?";history.replaceState(null,"",t),location.replace(e)}else t?location.replace(e):location.href=e}(e,t.replaceHistoryEntry)}async function Pe(e,t,n,o=void 0,r=!1){if(Me(),function(e){const t=e.indexOf("#");return t>-1&&location.href.replace(location.hash,"")===e.substring(0,t)}(e))!function(e,t,n){Ue(e,t,n);const o=e.indexOf("#");o!==e.length-1&&Ae(e.substring(o+1))}(e,n,o);else{if(!r&&Ce&&!await $e(e,o,t))return;ye=!0,Ue(e,n,o),await Le(t)}}function Ue(e,t,n=void 0){t?history.replaceState({userState:n,_index:Se},"",e):(Se++,history.pushState({userState:n,_index:Se},"",e))}function Be(e){return new Promise((t=>{const n=De;De=()=>{De=n,t()},history.go(e)}))}function Me(){xe&&(xe(!1),xe=null)}function $e(e,t,n){return new Promise((o=>{Me(),Te?(Ie++,xe=o,Te(Ie,e,t,n)):o(!1)}))}async function Le(e){var t;ke&&await ke(location.href,null===(t=history.state)||void 0===t?void 0:t.userState,e)}async function Oe(e){var t,n;De&&await De(e),Se=null!==(n=null===(t=history.state)||void 0===t?void 0:t._index)&&void 0!==n?n:0}const Fe={focus:function(e,t){if(e instanceof HTMLElement)e.focus({preventScroll:t});else{if(!(e instanceof SVGElement))throw new Error("Unable to focus an invalid element.");if(!e.hasAttribute("tabindex"))throw new Error("Unable to focus an SVG element that does not have a tabindex.");e.focus({preventScroll:t})}},focusBySelector:function(e,t){const n=document.querySelector(e);n&&(n.hasAttribute("tabindex")||(n.tabIndex=-1),n.focus({preventScroll:!0}))}},He={init:function(e,t,n,o=50){const r=We(t);(r||document.documentElement).style.overflowAnchor="none";const s=document.createRange();h(n.parentElement)&&(t.style.display="table-row",n.style.display="table-row");const i=new IntersectionObserver((function(o){o.forEach((o=>{var r;if(!o.isIntersecting)return;s.setStartAfter(t),s.setEndBefore(n);const i=s.getBoundingClientRect().height,a=null===(r=o.rootBounds)||void 0===r?void 0:r.height;o.target===t?e.invokeMethodAsync("OnSpacerBeforeVisible",o.intersectionRect.top-o.boundingClientRect.top,i,a):o.target===n&&n.offsetHeight>0&&e.invokeMethodAsync("OnSpacerAfterVisible",o.boundingClientRect.bottom-o.intersectionRect.bottom,i,a)}))}),{root:r,rootMargin:`${o}px`});i.observe(t),i.observe(n);const a=l(t),c=l(n);function l(e){const t={attributes:!0},n=new MutationObserver(((n,o)=>{h(e.parentElement)&&(o.disconnect(),e.style.display="table-row",o.observe(e,t)),i.unobserve(e),i.observe(e)}));return n.observe(e,t),n}function h(e){return null!==e&&(e instanceof HTMLTableElement&&""===e.style.display||"table"===e.style.display||e instanceof HTMLTableSectionElement&&""===e.style.display||"table-row-group"===e.style.display)}je[e._id]={intersectionObserver:i,mutationObserverBefore:a,mutationObserverAfter:c}},dispose:function(e){const t=je[e._id];t&&(t.intersectionObserver.disconnect(),t.mutationObserverBefore.disconnect(),t.mutationObserverAfter.disconnect(),e.dispose(),delete je[e._id])}},je={};function We(e){return e&&e!==document.body&&e!==document.documentElement?"visible"!==getComputedStyle(e).overflowY?e:We(e.parentElement):null}const ze={getAndRemoveExistingTitle:function(){var e;const t=document.head?document.head.getElementsByTagName("title"):[];if(0===t.length)return null;let n=null;for(let o=t.length-1;o>=0;o--){const r=t[o],s=r.previousSibling;s instanceof Comment&&null!==J(s)||(null===n&&(n=r.textContent),null===(e=r.parentNode)||void 0===e||e.removeChild(r))}return n}},Je={init:function(e,t){t._blazorInputFileNextFileId=0,t.addEventListener("click",(function(){t.value=""})),t.addEventListener("change",(function(){t._blazorFilesById={};const n=Array.prototype.map.call(t.files,(function(e){const n={id:++t._blazorInputFileNextFileId,lastModified:new Date(e.lastModified).toISOString(),name:e.name,size:e.size,contentType:e.type,readPromise:void 0,arrayBuffer:void 0,blob:e};return t._blazorFilesById[n.id]=n,n}));e.invokeMethodAsync("NotifyChange",n)}))},toImageFile:async function(e,t,n,o,r){const s=qe(e,t),i=await new Promise((function(e){const t=new Image;t.onload=function(){URL.revokeObjectURL(t.src),e(t)},t.onerror=function(){t.onerror=null,URL.revokeObjectURL(t.src)},t.src=URL.createObjectURL(s.blob)})),a=await new Promise((function(e){var t;const s=Math.min(1,o/i.width),a=Math.min(1,r/i.height),c=Math.min(s,a),l=document.createElement("canvas");l.width=Math.round(i.width*c),l.height=Math.round(i.height*c),null===(t=l.getContext("2d"))||void 0===t||t.drawImage(i,0,0,l.width,l.height),l.toBlob(e,n)})),c={id:++e._blazorInputFileNextFileId,lastModified:s.lastModified,name:s.name,size:(null==a?void 0:a.size)||0,contentType:n,blob:a||s.blob};return e._blazorFilesById[c.id]=c,c},readFileData:async function(e,t){return qe(e,t).blob}};function qe(e,t){const n=e._blazorFilesById[t];if(!n)throw new Error(`There is no file with ID ${t}. The file list may have changed. See https://aka.ms/aspnet/blazor-input-file-multiple-selections.`);return n}const Ke=new Set,Ve={enableNavigationPrompt:function(e){0===Ke.size&&window.addEventListener("beforeunload",Xe),Ke.add(e)},disableNavigationPrompt:function(e){Ke.delete(e),0===Ke.size&&window.removeEventListener("beforeunload",Xe)}};function Xe(e){e.preventDefault(),e.returnValue=!0}async function Ye(e,t,n){return e instanceof Blob?await async function(e,t,n){const o=e.slice(t,t+n),r=await o.arrayBuffer();return new Uint8Array(r)}(e,t,n):function(e,t,n){return new Uint8Array(e.buffer,e.byteOffset+t,n)}(e,t,n)}new Map;const Ge={navigateTo:function(e,t,n=!1){Ne(e,t instanceof Object?t:{forceLoad:t,replaceHistoryEntry:n})},registerCustomEventType:function(e,t){if(!t)throw new Error("The options parameter is required.");if(s.has(e))throw new Error(`The event '${e}' is already registered.`);if(t.browserEventName){const n=i.get(t.browserEventName);n?n.push(e):i.set(t.browserEventName,[e]),a.forEach((n=>n(e,t.browserEventName)))}s.set(e,t)},rootComponents:v,_internal:{navigationManager:Re,domWrapper:Fe,Virtualize:He,PageTitle:ze,InputFile:Je,NavigationLock:Ve,getJSDataStreamChunk:Ye,attachWebRendererInterop:function(t,n,o,r){if(E.has(t))throw new Error(`Interop methods are already registered for renderer ${t}`);E.set(t,n),Object.keys(o).length>0&&function(t,n,o){if(g)throw new Error("Dynamic root components have already been enabled.");g=t,m=n;for(const[t,r]of Object.entries(o)){const o=e.findJSFunction(t,0);for(const e of r)o(e,n[e])}}(D(t),o,r),I(),function(e){const t=C.get(e);t&&(C.delete(e),S.delete(e),t())}(t)}}};window.Blazor=Ge;const Qe=[0,2e3,1e4,3e4,null];class Ze{constructor(e){this._retryDelays=void 0!==e?[...e,null]:Qe}nextRetryDelayInMilliseconds(e){return this._retryDelays[e.previousRetryCount]}}class et{}et.Authorization="Authorization",et.Cookie="Cookie";class tt{constructor(e,t,n){this.statusCode=e,this.statusText=t,this.content=n}}class nt{get(e,t){return this.send({...t,method:"GET",url:e})}post(e,t){return this.send({...t,method:"POST",url:e})}delete(e,t){return this.send({...t,method:"DELETE",url:e})}getCookieString(e){return""}}class ot extends nt{constructor(e,t){super(),this._innerClient=e,this._accessTokenFactory=t}async send(e){let t=!0;this._accessTokenFactory&&(!this._accessToken||e.url&&e.url.indexOf("/negotiate?")>0)&&(t=!1,this._accessToken=await this._accessTokenFactory()),this._setAuthorizationHeader(e);const n=await this._innerClient.send(e);return t&&401===n.statusCode&&this._accessTokenFactory?(this._accessToken=await this._accessTokenFactory(),this._setAuthorizationHeader(e),await this._innerClient.send(e)):n}_setAuthorizationHeader(e){e.headers||(e.headers={}),this._accessToken?e.headers[et.Authorization]=`Bearer ${this._accessToken}`:this._accessTokenFactory&&e.headers[et.Authorization]&&delete e.headers[et.Authorization]}getCookieString(e){return this._innerClient.getCookieString(e)}}class rt extends Error{constructor(e,t){const n=new.target.prototype;super(`${e}: Status code '${t}'`),this.statusCode=t,this.__proto__=n}}class st extends Error{constructor(e="A timeout occurred."){const t=new.target.prototype;super(e),this.__proto__=t}}class it extends Error{constructor(e="An abort occurred."){const t=new.target.prototype;super(e),this.__proto__=t}}class at extends Error{constructor(e,t){const n=new.target.prototype;super(e),this.transport=t,this.errorType="UnsupportedTransportError",this.__proto__=n}}class ct extends Error{constructor(e,t){const n=new.target.prototype;super(e),this.transport=t,this.errorType="DisabledTransportError",this.__proto__=n}}class lt extends Error{constructor(e,t){const n=new.target.prototype;super(e),this.transport=t,this.errorType="FailedToStartTransportError",this.__proto__=n}}class ht extends Error{constructor(e){const t=new.target.prototype;super(e),this.errorType="FailedToNegotiateWithServerError",this.__proto__=t}}class dt extends Error{constructor(e,t){const n=new.target.prototype;super(e),this.innerErrors=t,this.__proto__=n}}var ut;!function(e){e[e.Trace=0]="Trace",e[e.Debug=1]="Debug",e[e.Information=2]="Information",e[e.Warning=3]="Warning",e[e.Error=4]="Error",e[e.Critical=5]="Critical",e[e.None=6]="None"}(ut||(ut={}));class pt{constructor(){}log(e,t){}}pt.instance=new pt;const ft="0.0.0-DEV_BUILD";class gt{static isRequired(e,t){if(null==e)throw new Error(`The '${t}' argument is required.`)}static isNotEmpty(e,t){if(!e||e.match(/^\s*$/))throw new Error(`The '${t}' argument should not be empty.`)}static isIn(e,t,n){if(!(e in t))throw new Error(`Unknown ${n} value: ${e}.`)}}class mt{static get isBrowser(){return!mt.isNode&&"object"==typeof window&&"object"==typeof window.document}static get isWebWorker(){return!mt.isNode&&"object"==typeof self&&"importScripts"in self}static get isReactNative(){return!mt.isNode&&"object"==typeof window&&void 0===window.document}static get isNode(){return"undefined"!=typeof process&&process.release&&"node"===process.release.name}}function yt(e,t){let n="";return vt(e)?(n=`Binary data of length ${e.byteLength}`,t&&(n+=`. Content: '${function(e){const t=new Uint8Array(e);let n="";return t.forEach((e=>{n+=`0x${e<16?"0":""}${e.toString(16)} `})),n.substr(0,n.length-1)}(e)}'`)):"string"==typeof e&&(n=`String data of length ${e.length}`,t&&(n+=`. Content: '${e}'`)),n}function vt(e){return e&&"undefined"!=typeof ArrayBuffer&&(e instanceof ArrayBuffer||e.constructor&&"ArrayBuffer"===e.constructor.name)}async function wt(e,t,n,o,r,s){const i={},[a,c]=Et();i[a]=c,e.log(ut.Trace,`(${t} transport) sending data. ${yt(r,s.logMessageContent)}.`);const l=vt(r)?"arraybuffer":"text",h=await n.post(o,{content:r,headers:{...i,...s.headers},responseType:l,timeout:s.timeout,withCredentials:s.withCredentials});e.log(ut.Trace,`(${t} transport) request complete. Response status: ${h.statusCode}.`)}class bt{constructor(e,t){this._subject=e,this._observer=t}dispose(){const e=this._subject.observers.indexOf(this._observer);e>-1&&this._subject.observers.splice(e,1),0===this._subject.observers.length&&this._subject.cancelCallback&&this._subject.cancelCallback().catch((e=>{}))}}class _t{constructor(e){this._minLevel=e,this.out=console}log(e,t){if(e>=this._minLevel){const n=`[${(new Date).toISOString()}] ${ut[e]}: ${t}`;switch(e){case ut.Critical:case ut.Error:this.out.error(n);break;case ut.Warning:this.out.warn(n);break;case ut.Information:this.out.info(n);break;default:this.out.log(n)}}}}function Et(){let e="X-SignalR-User-Agent";return mt.isNode&&(e="User-Agent"),[e,Ct(ft,St(),mt.isNode?"NodeJS":"Browser",It())]}function Ct(e,t,n,o){let r="Microsoft SignalR/";const s=e.split(".");return r+=`${s[0]}.${s[1]}`,r+=` (${e}; `,r+=t&&""!==t?`${t}; `:"Unknown OS; ",r+=`${n}`,r+=o?`; ${o}`:"; Unknown Runtime Version",r+=")",r}function St(){if(!mt.isNode)return"";switch(process.platform){case"win32":return"Windows NT";case"darwin":return"macOS";case"linux":return"Linux";default:return process.platform}}function It(){if(mt.isNode)return process.versions.node}function kt(e){return e.stack?e.stack:e.message?e.message:`${e}`}class Tt extends nt{constructor(e){super(),this._logger=e;const t={_fetchType:void 0,_jar:void 0};var o;o=t,"undefined"==typeof fetch&&(o._jar=new(n(628).CookieJar),"undefined"==typeof fetch?o._fetchType=n(200):o._fetchType=fetch,o._fetchType=n(203)(o._fetchType,o._jar),1)?(this._fetchType=t._fetchType,this._jar=t._jar):this._fetchType=fetch.bind(function(){if("undefined"!=typeof globalThis)return globalThis;if("undefined"!=typeof self)return self;if("undefined"!=typeof window)return window;if(void 0!==n.g)return n.g;throw new Error("could not find global")}()),this._abortControllerType=AbortController;const r={_abortControllerType:this._abortControllerType};(function(e){return"undefined"==typeof AbortController&&(e._abortControllerType=n(778),!0)})(r)&&(this._abortControllerType=r._abortControllerType)}async send(e){if(e.abortSignal&&e.abortSignal.aborted)throw new it;if(!e.method)throw new Error("No method defined.");if(!e.url)throw new Error("No url defined.");const t=new this._abortControllerType;let n;e.abortSignal&&(e.abortSignal.onabort=()=>{t.abort(),n=new it});let o,r=null;if(e.timeout){const o=e.timeout;r=setTimeout((()=>{t.abort(),this._logger.log(ut.Warning,"Timeout from HTTP request."),n=new st}),o)}""===e.content&&(e.content=void 0),e.content&&(e.headers=e.headers||{},vt(e.content)?e.headers["Content-Type"]="application/octet-stream":e.headers["Content-Type"]="text/plain;charset=UTF-8");try{o=await this._fetchType(e.url,{body:e.content,cache:"no-cache",credentials:!0===e.withCredentials?"include":"same-origin",headers:{"X-Requested-With":"XMLHttpRequest",...e.headers},method:e.method,mode:"cors",redirect:"follow",signal:t.signal})}catch(e){if(n)throw n;throw this._logger.log(ut.Warning,`Error from HTTP request. ${e}.`),e}finally{r&&clearTimeout(r),e.abortSignal&&(e.abortSignal.onabort=null)}if(!o.ok){const e=await Dt(o,"text");throw new rt(e||o.statusText,o.status)}const s=Dt(o,e.responseType),i=await s;return new tt(o.status,o.statusText,i)}getCookieString(e){return""}}function Dt(e,t){let n;switch(t){case"arraybuffer":n=e.arrayBuffer();break;case"text":default:n=e.text();break;case"blob":case"document":case"json":throw new Error(`${t} is not supported.`)}return n}class xt extends nt{constructor(e){super(),this._logger=e}send(e){return e.abortSignal&&e.abortSignal.aborted?Promise.reject(new it):e.method?e.url?new Promise(((t,n)=>{const o=new XMLHttpRequest;o.open(e.method,e.url,!0),o.withCredentials=void 0===e.withCredentials||e.withCredentials,o.setRequestHeader("X-Requested-With","XMLHttpRequest"),""===e.content&&(e.content=void 0),e.content&&(vt(e.content)?o.setRequestHeader("Content-Type","application/octet-stream"):o.setRequestHeader("Content-Type","text/plain;charset=UTF-8"));const r=e.headers;r&&Object.keys(r).forEach((e=>{o.setRequestHeader(e,r[e])})),e.responseType&&(o.responseType=e.responseType),e.abortSignal&&(e.abortSignal.onabort=()=>{o.abort(),n(new it)}),e.timeout&&(o.timeout=e.timeout),o.onload=()=>{e.abortSignal&&(e.abortSignal.onabort=null),o.status>=200&&o.status<300?t(new tt(o.status,o.statusText,o.response||o.responseText)):n(new rt(o.response||o.responseText||o.statusText,o.status))},o.onerror=()=>{this._logger.log(ut.Warning,`Error from HTTP request. ${o.status}: ${o.statusText}.`),n(new rt(o.statusText,o.status))},o.ontimeout=()=>{this._logger.log(ut.Warning,"Timeout from HTTP request."),n(new st)},o.send(e.content)})):Promise.reject(new Error("No url defined.")):Promise.reject(new Error("No method defined."))}}class Rt extends nt{constructor(e){if(super(),"undefined"!=typeof fetch)this._httpClient=new Tt(e);else{if("undefined"==typeof XMLHttpRequest)throw new Error("No usable HttpClient found.");this._httpClient=new xt(e)}}send(e){return e.abortSignal&&e.abortSignal.aborted?Promise.reject(new it):e.method?e.url?this._httpClient.send(e):Promise.reject(new Error("No url defined.")):Promise.reject(new Error("No method defined."))}getCookieString(e){return this._httpClient.getCookieString(e)}}var At,Nt,Pt,Ut;!function(e){e[e.None=0]="None",e[e.WebSockets=1]="WebSockets",e[e.ServerSentEvents=2]="ServerSentEvents",e[e.LongPolling=4]="LongPolling"}(At||(At={})),function(e){e[e.Text=1]="Text",e[e.Binary=2]="Binary"}(Nt||(Nt={}));class Bt{constructor(){this._isAborted=!1,this.onabort=null}abort(){this._isAborted||(this._isAborted=!0,this.onabort&&this.onabort())}get signal(){return this}get aborted(){return this._isAborted}}class Mt{get pollAborted(){return this._pollAbort.aborted}constructor(e,t,n){this._httpClient=e,this._logger=t,this._pollAbort=new Bt,this._options=n,this._running=!1,this.onreceive=null,this.onclose=null}async connect(e,t){if(gt.isRequired(e,"url"),gt.isRequired(t,"transferFormat"),gt.isIn(t,Nt,"transferFormat"),this._url=e,this._logger.log(ut.Trace,"(LongPolling transport) Connecting."),t===Nt.Binary&&"undefined"!=typeof XMLHttpRequest&&"string"!=typeof(new XMLHttpRequest).responseType)throw new Error("Binary protocols over XmlHttpRequest not implementing advanced features are not supported.");const[n,o]=Et(),r={[n]:o,...this._options.headers},s={abortSignal:this._pollAbort.signal,headers:r,timeout:1e5,withCredentials:this._options.withCredentials};t===Nt.Binary&&(s.responseType="arraybuffer");const i=`${e}&_=${Date.now()}`;this._logger.log(ut.Trace,`(LongPolling transport) polling: ${i}.`);const a=await this._httpClient.get(i,s);200!==a.statusCode?(this._logger.log(ut.Error,`(LongPolling transport) Unexpected response code: ${a.statusCode}.`),this._closeError=new rt(a.statusText||"",a.statusCode),this._running=!1):this._running=!0,this._receiving=this._poll(this._url,s)}async _poll(e,t){try{for(;this._running;)try{const n=`${e}&_=${Date.now()}`;this._logger.log(ut.Trace,`(LongPolling transport) polling: ${n}.`);const o=await this._httpClient.get(n,t);204===o.statusCode?(this._logger.log(ut.Information,"(LongPolling transport) Poll terminated by server."),this._running=!1):200!==o.statusCode?(this._logger.log(ut.Error,`(LongPolling transport) Unexpected response code: ${o.statusCode}.`),this._closeError=new rt(o.statusText||"",o.statusCode),this._running=!1):o.content?(this._logger.log(ut.Trace,`(LongPolling transport) data received. ${yt(o.content,this._options.logMessageContent)}.`),this.onreceive&&this.onreceive(o.content)):this._logger.log(ut.Trace,"(LongPolling transport) Poll timed out, reissuing.")}catch(e){this._running?e instanceof st?this._logger.log(ut.Trace,"(LongPolling transport) Poll timed out, reissuing."):(this._closeError=e,this._running=!1):this._logger.log(ut.Trace,`(LongPolling transport) Poll errored after shutdown: ${e.message}`)}}finally{this._logger.log(ut.Trace,"(LongPolling transport) Polling complete."),this.pollAborted||this._raiseOnClose()}}async send(e){return this._running?wt(this._logger,"LongPolling",this._httpClient,this._url,e,this._options):Promise.reject(new Error("Cannot send until the transport is connected"))}async stop(){this._logger.log(ut.Trace,"(LongPolling transport) Stopping polling."),this._running=!1,this._pollAbort.abort();try{await this._receiving,this._logger.log(ut.Trace,`(LongPolling transport) sending DELETE request to ${this._url}.`);const e={},[t,n]=Et();e[t]=n;const o={headers:{...e,...this._options.headers},timeout:this._options.timeout,withCredentials:this._options.withCredentials};let r;try{await this._httpClient.delete(this._url,o)}catch(e){r=e}r?r instanceof rt&&(404===r.statusCode?this._logger.log(ut.Trace,"(LongPolling transport) A 404 response was returned from sending a DELETE request."):this._logger.log(ut.Trace,`(LongPolling transport) Error sending a DELETE request: ${r}`)):this._logger.log(ut.Trace,"(LongPolling transport) DELETE request accepted.")}finally{this._logger.log(ut.Trace,"(LongPolling transport) Stop finished."),this._raiseOnClose()}}_raiseOnClose(){if(this.onclose){let e="(LongPolling transport) Firing onclose event.";this._closeError&&(e+=" Error: "+this._closeError),this._logger.log(ut.Trace,e),this.onclose(this._closeError)}}}class $t{constructor(e,t,n,o){this._httpClient=e,this._accessToken=t,this._logger=n,this._options=o,this.onreceive=null,this.onclose=null}async connect(e,t){return gt.isRequired(e,"url"),gt.isRequired(t,"transferFormat"),gt.isIn(t,Nt,"transferFormat"),this._logger.log(ut.Trace,"(SSE transport) Connecting."),this._url=e,this._accessToken&&(e+=(e.indexOf("?")<0?"?":"&")+`access_token=${encodeURIComponent(this._accessToken)}`),new Promise(((n,o)=>{let r,s=!1;if(t===Nt.Text){if(mt.isBrowser||mt.isWebWorker)r=new this._options.EventSource(e,{withCredentials:this._options.withCredentials});else{const t=this._httpClient.getCookieString(e),n={};n.Cookie=t;const[o,s]=Et();n[o]=s,r=new this._options.EventSource(e,{withCredentials:this._options.withCredentials,headers:{...n,...this._options.headers}})}try{r.onmessage=e=>{if(this.onreceive)try{this._logger.log(ut.Trace,`(SSE transport) data received. ${yt(e.data,this._options.logMessageContent)}.`),this.onreceive(e.data)}catch(e){return void this._close(e)}},r.onerror=e=>{s?this._close():o(new Error("EventSource failed to connect. The connection could not be found on the server, either the connection ID is not present on the server, or a proxy is refusing/buffering the connection. If you have multiple servers check that sticky sessions are enabled."))},r.onopen=()=>{this._logger.log(ut.Information,`SSE connected to ${this._url}`),this._eventSource=r,s=!0,n()}}catch(e){return void o(e)}}else o(new Error("The Server-Sent Events transport only supports the 'Text' transfer format"))}))}async send(e){return this._eventSource?wt(this._logger,"SSE",this._httpClient,this._url,e,this._options):Promise.reject(new Error("Cannot send until the transport is connected"))}stop(){return this._close(),Promise.resolve()}_close(e){this._eventSource&&(this._eventSource.close(),this._eventSource=void 0,this.onclose&&this.onclose(e))}}class Lt{constructor(e,t,n,o,r,s){this._logger=n,this._accessTokenFactory=t,this._logMessageContent=o,this._webSocketConstructor=r,this._httpClient=e,this.onreceive=null,this.onclose=null,this._headers=s}async connect(e,t){let n;return gt.isRequired(e,"url"),gt.isRequired(t,"transferFormat"),gt.isIn(t,Nt,"transferFormat"),this._logger.log(ut.Trace,"(WebSockets transport) Connecting."),this._accessTokenFactory&&(n=await this._accessTokenFactory()),new Promise(((o,r)=>{let s;e=e.replace(/^http/,"ws");const i=this._httpClient.getCookieString(e);let a=!1;if(mt.isReactNative){const t={},[o,r]=Et();t[o]=r,n&&(t[et.Authorization]=`Bearer ${n}`),i&&(t[et.Cookie]=i),s=new this._webSocketConstructor(e,void 0,{headers:{...t,...this._headers}})}else n&&(e+=(e.indexOf("?")<0?"?":"&")+`access_token=${encodeURIComponent(n)}`);s||(s=new this._webSocketConstructor(e)),t===Nt.Binary&&(s.binaryType="arraybuffer"),s.onopen=t=>{this._logger.log(ut.Information,`WebSocket connected to ${e}.`),this._webSocket=s,a=!0,o()},s.onerror=e=>{let t=null;t="undefined"!=typeof ErrorEvent&&e instanceof ErrorEvent?e.error:"There was an error with the transport",this._logger.log(ut.Information,`(WebSockets transport) ${t}.`)},s.onmessage=e=>{if(this._logger.log(ut.Trace,`(WebSockets transport) data received. ${yt(e.data,this._logMessageContent)}.`),this.onreceive)try{this.onreceive(e.data)}catch(e){return void this._close(e)}},s.onclose=e=>{if(a)this._close(e);else{let t=null;t="undefined"!=typeof ErrorEvent&&e instanceof ErrorEvent?e.error:"WebSocket failed to connect. The connection could not be found on the server, either the endpoint may not be a SignalR endpoint, the connection ID is not present on the server, or there is a proxy blocking WebSockets. If you have multiple servers check that sticky sessions are enabled.",r(new Error(t))}}}))}send(e){return this._webSocket&&this._webSocket.readyState===this._webSocketConstructor.OPEN?(this._logger.log(ut.Trace,`(WebSockets transport) sending data. ${yt(e,this._logMessageContent)}.`),this._webSocket.send(e),Promise.resolve()):Promise.reject("WebSocket is not in the OPEN state")}stop(){return this._webSocket&&this._close(void 0),Promise.resolve()}_close(e){this._webSocket&&(this._webSocket.onclose=()=>{},this._webSocket.onmessage=()=>{},this._webSocket.onerror=()=>{},this._webSocket.close(),this._webSocket=void 0),this._logger.log(ut.Trace,"(WebSockets transport) socket closed."),this.onclose&&(!this._isCloseEvent(e)||!1!==e.wasClean&&1e3===e.code?e instanceof Error?this.onclose(e):this.onclose():this.onclose(new Error(`WebSocket closed with status code: ${e.code} (${e.reason||"no reason given"}).`)))}_isCloseEvent(e){return e&&"boolean"==typeof e.wasClean&&"number"==typeof e.code}}class Ot{constructor(e,t={}){var n;if(this._stopPromiseResolver=()=>{},this.features={},this._negotiateVersion=1,gt.isRequired(e,"url"),this._logger=void 0===(n=t.logger)?new _t(ut.Information):null===n?pt.instance:void 0!==n.log?n:new _t(n),this.baseUrl=this._resolveUrl(e),(t=t||{}).logMessageContent=void 0!==t.logMessageContent&&t.logMessageContent,"boolean"!=typeof t.withCredentials&&void 0!==t.withCredentials)throw new Error("withCredentials option was not a 'boolean' or 'undefined' value");t.withCredentials=void 0===t.withCredentials||t.withCredentials,t.timeout=void 0===t.timeout?1e5:t.timeout,"undefined"==typeof WebSocket||t.WebSocket||(t.WebSocket=WebSocket),"undefined"==typeof EventSource||t.EventSource||(t.EventSource=EventSource),this._httpClient=new ot(t.httpClient||new Rt(this._logger),t.accessTokenFactory),this._connectionState="Disconnected",this._connectionStarted=!1,this._options=t,this.onreceive=null,this.onclose=null}async start(e){if(e=e||Nt.Binary,gt.isIn(e,Nt,"transferFormat"),this._logger.log(ut.Debug,`Starting connection with transfer format '${Nt[e]}'.`),"Disconnected"!==this._connectionState)return Promise.reject(new Error("Cannot start an HttpConnection that is not in the 'Disconnected' state."));if(this._connectionState="Connecting",this._startInternalPromise=this._startInternal(e),await this._startInternalPromise,"Disconnecting"===this._connectionState){const e="Failed to start the HttpConnection before stop() was called.";return this._logger.log(ut.Error,e),await this._stopPromise,Promise.reject(new it(e))}if("Connected"!==this._connectionState){const e="HttpConnection.startInternal completed gracefully but didn't enter the connection into the connected state!";return this._logger.log(ut.Error,e),Promise.reject(new it(e))}this._connectionStarted=!0}send(e){return"Connected"!==this._connectionState?Promise.reject(new Error("Cannot send data if the connection is not in the 'Connected' State.")):(this._sendQueue||(this._sendQueue=new Ft(this.transport)),this._sendQueue.send(e))}async stop(e){return"Disconnected"===this._connectionState?(this._logger.log(ut.Debug,`Call to HttpConnection.stop(${e}) ignored because the connection is already in the disconnected state.`),Promise.resolve()):"Disconnecting"===this._connectionState?(this._logger.log(ut.Debug,`Call to HttpConnection.stop(${e}) ignored because the connection is already in the disconnecting state.`),this._stopPromise):(this._connectionState="Disconnecting",this._stopPromise=new Promise((e=>{this._stopPromiseResolver=e})),await this._stopInternal(e),void await this._stopPromise)}async _stopInternal(e){this._stopError=e;try{await this._startInternalPromise}catch(e){}if(this.transport){try{await this.transport.stop()}catch(e){this._logger.log(ut.Error,`HttpConnection.transport.stop() threw error '${e}'.`),this._stopConnection()}this.transport=void 0}else this._logger.log(ut.Debug,"HttpConnection.transport is undefined in HttpConnection.stop() because start() failed.")}async _startInternal(e){let t=this.baseUrl;this._accessTokenFactory=this._options.accessTokenFactory,this._httpClient._accessTokenFactory=this._accessTokenFactory;try{if(this._options.skipNegotiation){if(this._options.transport!==At.WebSockets)throw new Error("Negotiation can only be skipped when using the WebSocket transport directly.");this.transport=this._constructTransport(At.WebSockets),await this._startTransport(t,e)}else{let n=null,o=0;do{if(n=await this._getNegotiationResponse(t),"Disconnecting"===this._connectionState||"Disconnected"===this._connectionState)throw new it("The connection was stopped during negotiation.");if(n.error)throw new Error(n.error);if(n.ProtocolVersion)throw new Error("Detected a connection attempt to an ASP.NET SignalR Server. This client only supports connecting to an ASP.NET Core SignalR Server. See https://aka.ms/signalr-core-differences for details.");if(n.url&&(t=n.url),n.accessToken){const e=n.accessToken;this._accessTokenFactory=()=>e,this._httpClient._accessToken=e,this._httpClient._accessTokenFactory=void 0}o++}while(n.url&&o<100);if(100===o&&n.url)throw new Error("Negotiate redirection limit exceeded.");await this._createTransport(t,this._options.transport,n,e)}this.transport instanceof Mt&&(this.features.inherentKeepAlive=!0),"Connecting"===this._connectionState&&(this._logger.log(ut.Debug,"The HttpConnection connected successfully."),this._connectionState="Connected")}catch(e){return this._logger.log(ut.Error,"Failed to start the connection: "+e),this._connectionState="Disconnected",this.transport=void 0,this._stopPromiseResolver(),Promise.reject(e)}}async _getNegotiationResponse(e){const t={},[n,o]=Et();t[n]=o;const r=this._resolveNegotiateUrl(e);this._logger.log(ut.Debug,`Sending negotiation request: ${r}.`);try{const e=await this._httpClient.post(r,{content:"",headers:{...t,...this._options.headers},timeout:this._options.timeout,withCredentials:this._options.withCredentials});if(200!==e.statusCode)return Promise.reject(new Error(`Unexpected status code returned from negotiate '${e.statusCode}'`));const n=JSON.parse(e.content);return(!n.negotiateVersion||n.negotiateVersion<1)&&(n.connectionToken=n.connectionId),n}catch(e){let t="Failed to complete negotiation with the server: "+e;return e instanceof rt&&404===e.statusCode&&(t+=" Either this is not a SignalR endpoint or there is a proxy blocking the connection."),this._logger.log(ut.Error,t),Promise.reject(new ht(t))}}_createConnectUrl(e,t){return t?e+(-1===e.indexOf("?")?"?":"&")+`id=${t}`:e}async _createTransport(e,t,n,o){let r=this._createConnectUrl(e,n.connectionToken);if(this._isITransport(t))return this._logger.log(ut.Debug,"Connection was provided an instance of ITransport, using that directly."),this.transport=t,await this._startTransport(r,o),void(this.connectionId=n.connectionId);const s=[],i=n.availableTransports||[];let a=n;for(const n of i){const i=this._resolveTransportOrError(n,t,o);if(i instanceof Error)s.push(`${n.transport} failed:`),s.push(i);else if(this._isITransport(i)){if(this.transport=i,!a){try{a=await this._getNegotiationResponse(e)}catch(e){return Promise.reject(e)}r=this._createConnectUrl(e,a.connectionToken)}try{return await this._startTransport(r,o),void(this.connectionId=a.connectionId)}catch(e){if(this._logger.log(ut.Error,`Failed to start the transport '${n.transport}': ${e}`),a=void 0,s.push(new lt(`${n.transport} failed: ${e}`,At[n.transport])),"Connecting"!==this._connectionState){const e="Failed to select transport before stop() was called.";return this._logger.log(ut.Debug,e),Promise.reject(new it(e))}}}}return s.length>0?Promise.reject(new dt(`Unable to connect to the server with any of the available transports. ${s.join(" ")}`,s)):Promise.reject(new Error("None of the transports supported by the client are supported by the server."))}_constructTransport(e){switch(e){case At.WebSockets:if(!this._options.WebSocket)throw new Error("'WebSocket' is not supported in your environment.");return new Lt(this._httpClient,this._accessTokenFactory,this._logger,this._options.logMessageContent,this._options.WebSocket,this._options.headers||{});case At.ServerSentEvents:if(!this._options.EventSource)throw new Error("'EventSource' is not supported in your environment.");return new $t(this._httpClient,this._httpClient._accessToken,this._logger,this._options);case At.LongPolling:return new Mt(this._httpClient,this._logger,this._options);default:throw new Error(`Unknown transport: ${e}.`)}}_startTransport(e,t){return this.transport.onreceive=this.onreceive,this.transport.onclose=e=>this._stopConnection(e),this.transport.connect(e,t)}_resolveTransportOrError(e,t,n){const o=At[e.transport];if(null==o)return this._logger.log(ut.Debug,`Skipping transport '${e.transport}' because it is not supported by this client.`),new Error(`Skipping transport '${e.transport}' because it is not supported by this client.`);if(!function(e,t){return!e||0!=(t&e)}(t,o))return this._logger.log(ut.Debug,`Skipping transport '${At[o]}' because it was disabled by the client.`),new ct(`'${At[o]}' is disabled by the client.`,o);if(!(e.transferFormats.map((e=>Nt[e])).indexOf(n)>=0))return this._logger.log(ut.Debug,`Skipping transport '${At[o]}' because it does not support the requested transfer format '${Nt[n]}'.`),new Error(`'${At[o]}' does not support ${Nt[n]}.`);if(o===At.WebSockets&&!this._options.WebSocket||o===At.ServerSentEvents&&!this._options.EventSource)return this._logger.log(ut.Debug,`Skipping transport '${At[o]}' because it is not supported in your environment.'`),new at(`'${At[o]}' is not supported in your environment.`,o);this._logger.log(ut.Debug,`Selecting transport '${At[o]}'.`);try{return this._constructTransport(o)}catch(e){return e}}_isITransport(e){return e&&"object"==typeof e&&"connect"in e}_stopConnection(e){if(this._logger.log(ut.Debug,`HttpConnection.stopConnection(${e}) called while in state ${this._connectionState}.`),this.transport=void 0,e=this._stopError||e,this._stopError=void 0,"Disconnected"!==this._connectionState){if("Connecting"===this._connectionState)throw this._logger.log(ut.Warning,`Call to HttpConnection.stopConnection(${e}) was ignored because the connection is still in the connecting state.`),new Error(`HttpConnection.stopConnection(${e}) was called while the connection is still in the connecting state.`);if("Disconnecting"===this._connectionState&&this._stopPromiseResolver(),e?this._logger.log(ut.Error,`Connection disconnected with error '${e}'.`):this._logger.log(ut.Information,"Connection disconnected."),this._sendQueue&&(this._sendQueue.stop().catch((e=>{this._logger.log(ut.Error,`TransportSendQueue.stop() threw error '${e}'.`)})),this._sendQueue=void 0),this.connectionId=void 0,this._connectionState="Disconnected",this._connectionStarted){this._connectionStarted=!1;try{this.onclose&&this.onclose(e)}catch(t){this._logger.log(ut.Error,`HttpConnection.onclose(${e}) threw error '${t}'.`)}}}else this._logger.log(ut.Debug,`Call to HttpConnection.stopConnection(${e}) was ignored because the connection is already in the disconnected state.`)}_resolveUrl(e){if(0===e.lastIndexOf("https://",0)||0===e.lastIndexOf("http://",0))return e;if(!mt.isBrowser)throw new Error(`Cannot resolve '${e}'.`);const t=window.document.createElement("a");return t.href=e,this._logger.log(ut.Information,`Normalizing '${e}' to '${t.href}'.`),t.href}_resolveNegotiateUrl(e){const t=e.indexOf("?");let n=e.substring(0,-1===t?e.length:t);return"/"!==n[n.length-1]&&(n+="/"),n+="negotiate",n+=-1===t?"":e.substring(t),-1===n.indexOf("negotiateVersion")&&(n+=-1===t?"?":"&",n+="negotiateVersion="+this._negotiateVersion),n}}class Ft{constructor(e){this._transport=e,this._buffer=[],this._executing=!0,this._sendBufferedData=new Ht,this._transportResult=new Ht,this._sendLoopPromise=this._sendLoop()}send(e){return this._bufferData(e),this._transportResult||(this._transportResult=new Ht),this._transportResult.promise}stop(){return this._executing=!1,this._sendBufferedData.resolve(),this._sendLoopPromise}_bufferData(e){if(this._buffer.length&&typeof this._buffer[0]!=typeof e)throw new Error(`Expected data to be of type ${typeof this._buffer} but was of type ${typeof e}`);this._buffer.push(e),this._sendBufferedData.resolve()}async _sendLoop(){for(;;){if(await this._sendBufferedData.promise,!this._executing){this._transportResult&&this._transportResult.reject("Connection stopped.");break}this._sendBufferedData=new Ht;const e=this._transportResult;this._transportResult=void 0;const t="string"==typeof this._buffer[0]?this._buffer.join(""):Ft._concatBuffers(this._buffer);this._buffer.length=0;try{await this._transport.send(t),e.resolve()}catch(t){e.reject(t)}}}static _concatBuffers(e){const t=e.map((e=>e.byteLength)).reduce(((e,t)=>e+t)),n=new Uint8Array(t);let o=0;for(const t of e)n.set(new Uint8Array(t),o),o+=t.byteLength;return n.buffer}}class Ht{constructor(){this.promise=new Promise(((e,t)=>[this._resolver,this._rejecter]=[e,t]))}resolve(){this._resolver()}reject(e){this._rejecter(e)}}class jt{static write(e){return`${e}${jt.RecordSeparator}`}static parse(e){if(e[e.length-1]!==jt.RecordSeparator)throw new Error("Message is incomplete.");const t=e.split(jt.RecordSeparator);return t.pop(),t}}jt.RecordSeparatorCode=30,jt.RecordSeparator=String.fromCharCode(jt.RecordSeparatorCode);class Wt{writeHandshakeRequest(e){return jt.write(JSON.stringify(e))}parseHandshakeResponse(e){let t,n;if(vt(e)){const o=new Uint8Array(e),r=o.indexOf(jt.RecordSeparatorCode);if(-1===r)throw new Error("Message is incomplete.");const s=r+1;t=String.fromCharCode.apply(null,Array.prototype.slice.call(o.slice(0,s))),n=o.byteLength>s?o.slice(s).buffer:null}else{const o=e,r=o.indexOf(jt.RecordSeparator);if(-1===r)throw new Error("Message is incomplete.");const s=r+1;t=o.substring(0,s),n=o.length>s?o.substring(s):null}const o=jt.parse(t),r=JSON.parse(o[0]);if(r.type)throw new Error("Expected a handshake response from the server.");return[n,r]}}!function(e){e[e.Invocation=1]="Invocation",e[e.StreamItem=2]="StreamItem",e[e.Completion=3]="Completion",e[e.StreamInvocation=4]="StreamInvocation",e[e.CancelInvocation=5]="CancelInvocation",e[e.Ping=6]="Ping",e[e.Close=7]="Close"}(Pt||(Pt={}));class zt{constructor(){this.observers=[]}next(e){for(const t of this.observers)t.next(e)}error(e){for(const t of this.observers)t.error&&t.error(e)}complete(){for(const e of this.observers)e.complete&&e.complete()}subscribe(e){return this.observers.push(e),new bt(this,e)}}!function(e){e.Disconnected="Disconnected",e.Connecting="Connecting",e.Connected="Connected",e.Disconnecting="Disconnecting",e.Reconnecting="Reconnecting"}(Ut||(Ut={}));class Jt{static create(e,t,n,o,r,s){return new Jt(e,t,n,o,r,s)}constructor(e,t,n,o,r,s){this._nextKeepAlive=0,this._freezeEventListener=()=>{this._logger.log(ut.Warning,"The page is being frozen, this will likely lead to the connection being closed and messages being lost. For more information see the docs at https://learn.microsoft.com/aspnet/core/signalr/javascript-client#bsleep")},gt.isRequired(e,"connection"),gt.isRequired(t,"logger"),gt.isRequired(n,"protocol"),this.serverTimeoutInMilliseconds=null!=r?r:3e4,this.keepAliveIntervalInMilliseconds=null!=s?s:15e3,this._logger=t,this._protocol=n,this.connection=e,this._reconnectPolicy=o,this._handshakeProtocol=new Wt,this.connection.onreceive=e=>this._processIncomingData(e),this.connection.onclose=e=>this._connectionClosed(e),this._callbacks={},this._methods={},this._closedCallbacks=[],this._reconnectingCallbacks=[],this._reconnectedCallbacks=[],this._invocationId=0,this._receivedHandshakeResponse=!1,this._connectionState=Ut.Disconnected,this._connectionStarted=!1,this._cachedPingMessage=this._protocol.writeMessage({type:Pt.Ping})}get state(){return this._connectionState}get connectionId(){return this.connection&&this.connection.connectionId||null}get baseUrl(){return this.connection.baseUrl||""}set baseUrl(e){if(this._connectionState!==Ut.Disconnected&&this._connectionState!==Ut.Reconnecting)throw new Error("The HubConnection must be in the Disconnected or Reconnecting state to change the url.");if(!e)throw new Error("The HubConnection url must be a valid url.");this.connection.baseUrl=e}start(){return this._startPromise=this._startWithStateTransitions(),this._startPromise}async _startWithStateTransitions(){if(this._connectionState!==Ut.Disconnected)return Promise.reject(new Error("Cannot start a HubConnection that is not in the 'Disconnected' state."));this._connectionState=Ut.Connecting,this._logger.log(ut.Debug,"Starting HubConnection.");try{await this._startInternal(),mt.isBrowser&&window.document.addEventListener("freeze",this._freezeEventListener),this._connectionState=Ut.Connected,this._connectionStarted=!0,this._logger.log(ut.Debug,"HubConnection connected successfully.")}catch(e){return this._connectionState=Ut.Disconnected,this._logger.log(ut.Debug,`HubConnection failed to start successfully because of error '${e}'.`),Promise.reject(e)}}async _startInternal(){this._stopDuringStartError=void 0,this._receivedHandshakeResponse=!1;const e=new Promise(((e,t)=>{this._handshakeResolver=e,this._handshakeRejecter=t}));await this.connection.start(this._protocol.transferFormat);try{const t={protocol:this._protocol.name,version:this._protocol.version};if(this._logger.log(ut.Debug,"Sending handshake request."),await this._sendMessage(this._handshakeProtocol.writeHandshakeRequest(t)),this._logger.log(ut.Information,`Using HubProtocol '${this._protocol.name}'.`),this._cleanupTimeout(),this._resetTimeoutPeriod(),this._resetKeepAliveInterval(),await e,this._stopDuringStartError)throw this._stopDuringStartError;this.connection.features.inherentKeepAlive||await this._sendMessage(this._cachedPingMessage)}catch(e){throw this._logger.log(ut.Debug,`Hub handshake failed with error '${e}' during start(). Stopping HubConnection.`),this._cleanupTimeout(),this._cleanupPingTimer(),await this.connection.stop(e),e}}async stop(){const e=this._startPromise;this._stopPromise=this._stopInternal(),await this._stopPromise;try{await e}catch(e){}}_stopInternal(e){if(this._connectionState===Ut.Disconnected)return this._logger.log(ut.Debug,`Call to HubConnection.stop(${e}) ignored because it is already in the disconnected state.`),Promise.resolve();if(this._connectionState===Ut.Disconnecting)return this._logger.log(ut.Debug,`Call to HttpConnection.stop(${e}) ignored because the connection is already in the disconnecting state.`),this._stopPromise;const t=this._connectionState;return this._connectionState=Ut.Disconnecting,this._logger.log(ut.Debug,"Stopping HubConnection."),this._reconnectDelayHandle?(this._logger.log(ut.Debug,"Connection stopped during reconnect delay. Done reconnecting."),clearTimeout(this._reconnectDelayHandle),this._reconnectDelayHandle=void 0,this._completeClose(),Promise.resolve()):(t===Ut.Connected&&this._sendCloseMessage(),this._cleanupTimeout(),this._cleanupPingTimer(),this._stopDuringStartError=e||new it("The connection was stopped before the hub handshake could complete."),this.connection.stop(e))}async _sendCloseMessage(){try{await this._sendWithProtocol(this._createCloseMessage())}catch{}}stream(e,...t){const[n,o]=this._replaceStreamingParams(t),r=this._createStreamInvocation(e,t,o);let s;const i=new zt;return i.cancelCallback=()=>{const e=this._createCancelInvocation(r.invocationId);return delete this._callbacks[r.invocationId],s.then((()=>this._sendWithProtocol(e)))},this._callbacks[r.invocationId]=(e,t)=>{t?i.error(t):e&&(e.type===Pt.Completion?e.error?i.error(new Error(e.error)):i.complete():i.next(e.item))},s=this._sendWithProtocol(r).catch((e=>{i.error(e),delete this._callbacks[r.invocationId]})),this._launchStreams(n,s),i}_sendMessage(e){return this._resetKeepAliveInterval(),this.connection.send(e)}_sendWithProtocol(e){return this._sendMessage(this._protocol.writeMessage(e))}send(e,...t){const[n,o]=this._replaceStreamingParams(t),r=this._sendWithProtocol(this._createInvocation(e,t,!0,o));return this._launchStreams(n,r),r}invoke(e,...t){const[n,o]=this._replaceStreamingParams(t),r=this._createInvocation(e,t,!1,o);return new Promise(((e,t)=>{this._callbacks[r.invocationId]=(n,o)=>{o?t(o):n&&(n.type===Pt.Completion?n.error?t(new Error(n.error)):e(n.result):t(new Error(`Unexpected message type: ${n.type}`)))};const o=this._sendWithProtocol(r).catch((e=>{t(e),delete this._callbacks[r.invocationId]}));this._launchStreams(n,o)}))}on(e,t){e&&t&&(e=e.toLowerCase(),this._methods[e]||(this._methods[e]=[]),-1===this._methods[e].indexOf(t)&&this._methods[e].push(t))}off(e,t){if(!e)return;e=e.toLowerCase();const n=this._methods[e];if(n)if(t){const o=n.indexOf(t);-1!==o&&(n.splice(o,1),0===n.length&&delete this._methods[e])}else delete this._methods[e]}onclose(e){e&&this._closedCallbacks.push(e)}onreconnecting(e){e&&this._reconnectingCallbacks.push(e)}onreconnected(e){e&&this._reconnectedCallbacks.push(e)}_processIncomingData(e){if(this._cleanupTimeout(),this._receivedHandshakeResponse||(e=this._processHandshakeResponse(e),this._receivedHandshakeResponse=!0),e){const t=this._protocol.parseMessages(e,this._logger);for(const e of t)switch(e.type){case Pt.Invocation:this._invokeClientMethod(e);break;case Pt.StreamItem:case Pt.Completion:{const t=this._callbacks[e.invocationId];if(t){e.type===Pt.Completion&&delete this._callbacks[e.invocationId];try{t(e)}catch(e){this._logger.log(ut.Error,`Stream callback threw error: ${kt(e)}`)}}break}case Pt.Ping:break;case Pt.Close:{this._logger.log(ut.Information,"Close message received from server.");const t=e.error?new Error("Server returned an error on close: "+e.error):void 0;!0===e.allowReconnect?this.connection.stop(t):this._stopPromise=this._stopInternal(t);break}default:this._logger.log(ut.Warning,`Invalid message type: ${e.type}.`)}}this._resetTimeoutPeriod()}_processHandshakeResponse(e){let t,n;try{[n,t]=this._handshakeProtocol.parseHandshakeResponse(e)}catch(e){const t="Error parsing handshake response: "+e;this._logger.log(ut.Error,t);const n=new Error(t);throw this._handshakeRejecter(n),n}if(t.error){const e="Server returned handshake error: "+t.error;this._logger.log(ut.Error,e);const n=new Error(e);throw this._handshakeRejecter(n),n}return this._logger.log(ut.Debug,"Server handshake complete."),this._handshakeResolver(),n}_resetKeepAliveInterval(){this.connection.features.inherentKeepAlive||(this._nextKeepAlive=(new Date).getTime()+this.keepAliveIntervalInMilliseconds,this._cleanupPingTimer())}_resetTimeoutPeriod(){if(!(this.connection.features&&this.connection.features.inherentKeepAlive||(this._timeoutHandle=setTimeout((()=>this.serverTimeout()),this.serverTimeoutInMilliseconds),void 0!==this._pingServerHandle))){let e=this._nextKeepAlive-(new Date).getTime();e<0&&(e=0),this._pingServerHandle=setTimeout((async()=>{if(this._connectionState===Ut.Connected)try{await this._sendMessage(this._cachedPingMessage)}catch{this._cleanupPingTimer()}}),e)}}serverTimeout(){this.connection.stop(new Error("Server timeout elapsed without receiving a message from the server."))}async _invokeClientMethod(e){const t=e.target.toLowerCase(),n=this._methods[t];if(!n)return this._logger.log(ut.Warning,`No client method with the name '${t}' found.`),void(e.invocationId&&(this._logger.log(ut.Warning,`No result given for '${t}' method and invocation ID '${e.invocationId}'.`),await this._sendWithProtocol(this._createCompletionMessage(e.invocationId,"Client didn't provide a result.",null))));const o=n.slice(),r=!!e.invocationId;let s,i,a;for(const n of o)try{const o=s;s=await n.apply(this,e.arguments),r&&s&&o&&(this._logger.log(ut.Error,`Multiple results provided for '${t}'. Sending error to server.`),a=this._createCompletionMessage(e.invocationId,"Client provided multiple results.",null)),i=void 0}catch(e){i=e,this._logger.log(ut.Error,`A callback for the method '${t}' threw error '${e}'.`)}a?await this._sendWithProtocol(a):r?(i?a=this._createCompletionMessage(e.invocationId,`${i}`,null):void 0!==s?a=this._createCompletionMessage(e.invocationId,null,s):(this._logger.log(ut.Warning,`No result given for '${t}' method and invocation ID '${e.invocationId}'.`),a=this._createCompletionMessage(e.invocationId,"Client didn't provide a result.",null)),await this._sendWithProtocol(a)):s&&this._logger.log(ut.Error,`Result given for '${t}' method but server is not expecting a result.`)}_connectionClosed(e){this._logger.log(ut.Debug,`HubConnection.connectionClosed(${e}) called while in state ${this._connectionState}.`),this._stopDuringStartError=this._stopDuringStartError||e||new it("The underlying connection was closed before the hub handshake could complete."),this._handshakeResolver&&this._handshakeResolver(),this._cancelCallbacksWithError(e||new Error("Invocation canceled due to the underlying connection being closed.")),this._cleanupTimeout(),this._cleanupPingTimer(),this._connectionState===Ut.Disconnecting?this._completeClose(e):this._connectionState===Ut.Connected&&this._reconnectPolicy?this._reconnect(e):this._connectionState===Ut.Connected&&this._completeClose(e)}_completeClose(e){if(this._connectionStarted){this._connectionState=Ut.Disconnected,this._connectionStarted=!1,mt.isBrowser&&window.document.removeEventListener("freeze",this._freezeEventListener);try{this._closedCallbacks.forEach((t=>t.apply(this,[e])))}catch(t){this._logger.log(ut.Error,`An onclose callback called with error '${e}' threw error '${t}'.`)}}}async _reconnect(e){const t=Date.now();let n=0,o=void 0!==e?e:new Error("Attempting to reconnect due to a unknown error."),r=this._getNextRetryDelay(n++,0,o);if(null===r)return this._logger.log(ut.Debug,"Connection not reconnecting because the IRetryPolicy returned null on the first reconnect attempt."),void this._completeClose(e);if(this._connectionState=Ut.Reconnecting,e?this._logger.log(ut.Information,`Connection reconnecting because of error '${e}'.`):this._logger.log(ut.Information,"Connection reconnecting."),0!==this._reconnectingCallbacks.length){try{this._reconnectingCallbacks.forEach((t=>t.apply(this,[e])))}catch(t){this._logger.log(ut.Error,`An onreconnecting callback called with error '${e}' threw error '${t}'.`)}if(this._connectionState!==Ut.Reconnecting)return void this._logger.log(ut.Debug,"Connection left the reconnecting state in onreconnecting callback. Done reconnecting.")}for(;null!==r;){if(this._logger.log(ut.Information,`Reconnect attempt number ${n} will start in ${r} ms.`),await new Promise((e=>{this._reconnectDelayHandle=setTimeout(e,r)})),this._reconnectDelayHandle=void 0,this._connectionState!==Ut.Reconnecting)return void this._logger.log(ut.Debug,"Connection left the reconnecting state during reconnect delay. Done reconnecting.");try{if(await this._startInternal(),this._connectionState=Ut.Connected,this._logger.log(ut.Information,"HubConnection reconnected successfully."),0!==this._reconnectedCallbacks.length)try{this._reconnectedCallbacks.forEach((e=>e.apply(this,[this.connection.connectionId])))}catch(e){this._logger.log(ut.Error,`An onreconnected callback called with connectionId '${this.connection.connectionId}; threw error '${e}'.`)}return}catch(e){if(this._logger.log(ut.Information,`Reconnect attempt failed because of error '${e}'.`),this._connectionState!==Ut.Reconnecting)return this._logger.log(ut.Debug,`Connection moved to the '${this._connectionState}' from the reconnecting state during reconnect attempt. Done reconnecting.`),void(this._connectionState===Ut.Disconnecting&&this._completeClose());o=e instanceof Error?e:new Error(e.toString()),r=this._getNextRetryDelay(n++,Date.now()-t,o)}}this._logger.log(ut.Information,`Reconnect retries have been exhausted after ${Date.now()-t} ms and ${n} failed attempts. Connection disconnecting.`),this._completeClose()}_getNextRetryDelay(e,t,n){try{return this._reconnectPolicy.nextRetryDelayInMilliseconds({elapsedMilliseconds:t,previousRetryCount:e,retryReason:n})}catch(n){return this._logger.log(ut.Error,`IRetryPolicy.nextRetryDelayInMilliseconds(${e}, ${t}) threw error '${n}'.`),null}}_cancelCallbacksWithError(e){const t=this._callbacks;this._callbacks={},Object.keys(t).forEach((n=>{const o=t[n];try{o(null,e)}catch(t){this._logger.log(ut.Error,`Stream 'error' callback called with '${e}' threw error: ${kt(t)}`)}}))}_cleanupPingTimer(){this._pingServerHandle&&(clearTimeout(this._pingServerHandle),this._pingServerHandle=void 0)}_cleanupTimeout(){this._timeoutHandle&&clearTimeout(this._timeoutHandle)}_createInvocation(e,t,n,o){if(n)return 0!==o.length?{arguments:t,streamIds:o,target:e,type:Pt.Invocation}:{arguments:t,target:e,type:Pt.Invocation};{const n=this._invocationId;return this._invocationId++,0!==o.length?{arguments:t,invocationId:n.toString(),streamIds:o,target:e,type:Pt.Invocation}:{arguments:t,invocationId:n.toString(),target:e,type:Pt.Invocation}}}_launchStreams(e,t){if(0!==e.length){t||(t=Promise.resolve());for(const n in e)e[n].subscribe({complete:()=>{t=t.then((()=>this._sendWithProtocol(this._createCompletionMessage(n))))},error:e=>{let o;o=e instanceof Error?e.message:e&&e.toString?e.toString():"Unknown error",t=t.then((()=>this._sendWithProtocol(this._createCompletionMessage(n,o))))},next:e=>{t=t.then((()=>this._sendWithProtocol(this._createStreamItemMessage(n,e))))}})}}_replaceStreamingParams(e){const t=[],n=[];for(let o=0;o=55296&&r<=56319&&o65535&&(h-=65536,s.push(h>>>10&1023|55296),h=56320|1023&h),s.push(h)}else s.push(a);s.length>=4096&&(i+=String.fromCharCode.apply(String,s),s.length=0)}return s.length>0&&(i+=String.fromCharCode.apply(String,s)),i}var cn,ln=tn?new TextDecoder:null,hn=tn?"undefined"!=typeof process&&"force"!==(null===(Gt=null===process||void 0===process?void 0:process.env)||void 0===Gt?void 0:Gt.TEXT_DECODER)?200:0:Qt,dn=function(e,t){this.type=e,this.data=t},un=(cn=function(e,t){return cn=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=t[n])},cn(e,t)},function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");function n(){this.constructor=e}cn(e,t),e.prototype=null===t?Object.create(t):(n.prototype=t.prototype,new n)}),pn=function(e){function t(n){var o=e.call(this,n)||this,r=Object.create(t.prototype);return Object.setPrototypeOf(o,r),Object.defineProperty(o,"name",{configurable:!0,enumerable:!1,value:t.name}),o}return un(t,e),t}(Error),fn={type:-1,encode:function(e){var t,n,o,r;return e instanceof Date?function(e){var t,n=e.sec,o=e.nsec;if(n>=0&&o>=0&&n<=17179869183){if(0===o&&n<=4294967295){var r=new Uint8Array(4);return(t=new DataView(r.buffer)).setUint32(0,n),r}var s=n/4294967296,i=4294967295&n;return r=new Uint8Array(8),(t=new DataView(r.buffer)).setUint32(0,o<<2|3&s),t.setUint32(4,i),r}return r=new Uint8Array(12),(t=new DataView(r.buffer)).setUint32(0,o),Zt(t,4,n),r}((o=1e6*((t=e.getTime())-1e3*(n=Math.floor(t/1e3))),{sec:n+(r=Math.floor(o/1e9)),nsec:o-1e9*r})):null},decode:function(e){var t=function(e){var t=new DataView(e.buffer,e.byteOffset,e.byteLength);switch(e.byteLength){case 4:return{sec:t.getUint32(0),nsec:0};case 8:var n=t.getUint32(0);return{sec:4294967296*(3&n)+t.getUint32(4),nsec:n>>>2};case 12:return{sec:en(t,4),nsec:t.getUint32(0)};default:throw new pn("Unrecognized data size for timestamp (expected 4, 8, or 12): ".concat(e.length))}}(e);return new Date(1e3*t.sec+t.nsec/1e6)}},gn=function(){function e(){this.builtInEncoders=[],this.builtInDecoders=[],this.encoders=[],this.decoders=[],this.register(fn)}return e.prototype.register=function(e){var t=e.type,n=e.encode,o=e.decode;if(t>=0)this.encoders[t]=n,this.decoders[t]=o;else{var r=1+t;this.builtInEncoders[r]=n,this.builtInDecoders[r]=o}},e.prototype.tryToEncode=function(e,t){for(var n=0;nthis.maxDepth)throw new Error("Too deep objects in depth ".concat(t));null==e?this.encodeNil():"boolean"==typeof e?this.encodeBoolean(e):"number"==typeof e?this.encodeNumber(e):"string"==typeof e?this.encodeString(e):this.encodeObject(e,t)},e.prototype.ensureBufferSizeToWrite=function(e){var t=this.pos+e;this.view.byteLength=0?e<128?this.writeU8(e):e<256?(this.writeU8(204),this.writeU8(e)):e<65536?(this.writeU8(205),this.writeU16(e)):e<4294967296?(this.writeU8(206),this.writeU32(e)):(this.writeU8(207),this.writeU64(e)):e>=-32?this.writeU8(224|e+32):e>=-128?(this.writeU8(208),this.writeI8(e)):e>=-32768?(this.writeU8(209),this.writeI16(e)):e>=-2147483648?(this.writeU8(210),this.writeI32(e)):(this.writeU8(211),this.writeI64(e)):this.forceFloat32?(this.writeU8(202),this.writeF32(e)):(this.writeU8(203),this.writeF64(e))},e.prototype.writeStringHeader=function(e){if(e<32)this.writeU8(160+e);else if(e<256)this.writeU8(217),this.writeU8(e);else if(e<65536)this.writeU8(218),this.writeU16(e);else{if(!(e<4294967296))throw new Error("Too long string: ".concat(e," bytes in UTF-8"));this.writeU8(219),this.writeU32(e)}},e.prototype.encodeString=function(e){if(e.length>rn){var t=nn(e);this.ensureBufferSizeToWrite(5+t),this.writeStringHeader(t),sn(e,this.bytes,this.pos),this.pos+=t}else t=nn(e),this.ensureBufferSizeToWrite(5+t),this.writeStringHeader(t),function(e,t,n){for(var o=e.length,r=n,s=0;s>6&31|192;else{if(i>=55296&&i<=56319&&s>12&15|224,t[r++]=i>>6&63|128):(t[r++]=i>>18&7|240,t[r++]=i>>12&63|128,t[r++]=i>>6&63|128)}t[r++]=63&i|128}else t[r++]=i}}(e,this.bytes,this.pos),this.pos+=t},e.prototype.encodeObject=function(e,t){var n=this.extensionCodec.tryToEncode(e,this.context);if(null!=n)this.encodeExtension(n);else if(Array.isArray(e))this.encodeArray(e,t);else if(ArrayBuffer.isView(e))this.encodeBinary(e);else{if("object"!=typeof e)throw new Error("Unrecognized object: ".concat(Object.prototype.toString.apply(e)));this.encodeMap(e,t)}},e.prototype.encodeBinary=function(e){var t=e.byteLength;if(t<256)this.writeU8(196),this.writeU8(t);else if(t<65536)this.writeU8(197),this.writeU16(t);else{if(!(t<4294967296))throw new Error("Too large binary: ".concat(t));this.writeU8(198),this.writeU32(t)}var n=mn(e);this.writeU8a(n)},e.prototype.encodeArray=function(e,t){var n=e.length;if(n<16)this.writeU8(144+n);else if(n<65536)this.writeU8(220),this.writeU16(n);else{if(!(n<4294967296))throw new Error("Too large array: ".concat(n));this.writeU8(221),this.writeU32(n)}for(var o=0,r=e;o0&&e<=this.maxKeyLength},e.prototype.find=function(e,t,n){e:for(var o=0,r=this.caches[n-1];o=this.maxLengthPerKey?n[Math.random()*n.length|0]=o:n.push(o)},e.prototype.decode=function(e,t,n){var o=this.find(e,t,n);if(null!=o)return this.hit++,o;this.miss++;var r=an(e,t,n),s=Uint8Array.prototype.slice.call(e,t,t+n);return this.store(s,r),r},e}(),bn=function(e,t){var n,o,r,s,i={label:0,sent:function(){if(1&r[0])throw r[1];return r[1]},trys:[],ops:[]};return s={next:a(0),throw:a(1),return:a(2)},"function"==typeof Symbol&&(s[Symbol.iterator]=function(){return this}),s;function a(s){return function(a){return function(s){if(n)throw new TypeError("Generator is already executing.");for(;i;)try{if(n=1,o&&(r=2&s[0]?o.return:s[0]?o.throw||((r=o.return)&&r.call(o),0):o.next)&&!(r=r.call(o,s[1])).done)return r;switch(o=0,r&&(s=[2&s[0],r.value]),s[0]){case 0:case 1:r=s;break;case 4:return i.label++,{value:s[1],done:!1};case 5:i.label++,o=s[1],s=[0];continue;case 7:s=i.ops.pop(),i.trys.pop();continue;default:if(!((r=(r=i.trys).length>0&&r[r.length-1])||6!==s[0]&&2!==s[0])){i=0;continue}if(3===s[0]&&(!r||s[1]>r[0]&&s[1]=e},e.prototype.createExtraByteError=function(e){var t=this.view,n=this.pos;return new RangeError("Extra ".concat(t.byteLength-n," of ").concat(t.byteLength," byte(s) found at buffer[").concat(e,"]"))},e.prototype.decode=function(e){this.reinitializeState(),this.setBuffer(e);var t=this.doDecodeSync();if(this.hasRemaining(1))throw this.createExtraByteError(this.pos);return t},e.prototype.decodeMulti=function(e){return bn(this,(function(t){switch(t.label){case 0:this.reinitializeState(),this.setBuffer(e),t.label=1;case 1:return this.hasRemaining(1)?[4,this.doDecodeSync()]:[3,3];case 2:return t.sent(),[3,1];case 3:return[2]}}))},e.prototype.decodeAsync=function(e){var t,n,o,r,s,i,a;return s=this,void 0,a=function(){var s,i,a,c,l,h,d,u;return bn(this,(function(p){switch(p.label){case 0:s=!1,p.label=1;case 1:p.trys.push([1,6,7,12]),t=_n(e),p.label=2;case 2:return[4,t.next()];case 3:if((n=p.sent()).done)return[3,5];if(a=n.value,s)throw this.createExtraByteError(this.totalPos);this.appendBuffer(a);try{i=this.doDecodeSync(),s=!0}catch(e){if(!(e instanceof In))throw e}this.totalPos+=this.pos,p.label=4;case 4:return[3,2];case 5:return[3,12];case 6:return c=p.sent(),o={error:c},[3,12];case 7:return p.trys.push([7,,10,11]),n&&!n.done&&(r=t.return)?[4,r.call(t)]:[3,9];case 8:p.sent(),p.label=9;case 9:return[3,11];case 10:if(o)throw o.error;return[7];case 11:return[7];case 12:if(s){if(this.hasRemaining(1))throw this.createExtraByteError(this.totalPos);return[2,i]}throw h=(l=this).headByte,d=l.pos,u=l.totalPos,new RangeError("Insufficient data in parsing ".concat(vn(h)," at ").concat(u," (").concat(d," in the current buffer)"))}}))},new((i=void 0)||(i=Promise))((function(e,t){function n(e){try{r(a.next(e))}catch(e){t(e)}}function o(e){try{r(a.throw(e))}catch(e){t(e)}}function r(t){var r;t.done?e(t.value):(r=t.value,r instanceof i?r:new i((function(e){e(r)}))).then(n,o)}r((a=a.apply(s,[])).next())}))},e.prototype.decodeArrayStream=function(e){return this.decodeMultiAsync(e,!0)},e.prototype.decodeStream=function(e){return this.decodeMultiAsync(e,!1)},e.prototype.decodeMultiAsync=function(e,t){return function(n,o,r){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var s,i=function(){var n,o,r,s,i,a,c,l,h;return bn(this,(function(d){switch(d.label){case 0:n=t,o=-1,d.label=1;case 1:d.trys.push([1,13,14,19]),r=_n(e),d.label=2;case 2:return[4,En(r.next())];case 3:if((s=d.sent()).done)return[3,12];if(i=s.value,t&&0===o)throw this.createExtraByteError(this.totalPos);this.appendBuffer(i),n&&(o=this.readArraySize(),n=!1,this.complete()),d.label=4;case 4:d.trys.push([4,9,,10]),d.label=5;case 5:return[4,En(this.doDecodeSync())];case 6:return[4,d.sent()];case 7:return d.sent(),0==--o?[3,8]:[3,5];case 8:return[3,10];case 9:if(!((a=d.sent())instanceof In))throw a;return[3,10];case 10:this.totalPos+=this.pos,d.label=11;case 11:return[3,2];case 12:return[3,19];case 13:return c=d.sent(),l={error:c},[3,19];case 14:return d.trys.push([14,,17,18]),s&&!s.done&&(h=r.return)?[4,En(h.call(r))]:[3,16];case 15:d.sent(),d.label=16;case 16:return[3,18];case 17:if(l)throw l.error;return[7];case 18:return[7];case 19:return[2]}}))}.apply(n,o||[]),a=[];return s={},c("next"),c("throw"),c("return"),s[Symbol.asyncIterator]=function(){return this},s;function c(e){i[e]&&(s[e]=function(t){return new Promise((function(n,o){a.push([e,t,n,o])>1||l(e,t)}))})}function l(e,t){try{(n=i[e](t)).value instanceof En?Promise.resolve(n.value.v).then(h,d):u(a[0][2],n)}catch(e){u(a[0][3],e)}var n}function h(e){l("next",e)}function d(e){l("throw",e)}function u(e,t){e(t),a.shift(),a.length&&l(a[0][0],a[0][1])}}(this,arguments)},e.prototype.doDecodeSync=function(){e:for(;;){var e=this.readHeadByte(),t=void 0;if(e>=224)t=e-256;else if(e<192)if(e<128)t=e;else if(e<144){if(0!=(o=e-128)){this.pushMapState(o),this.complete();continue e}t={}}else if(e<160){if(0!=(o=e-144)){this.pushArrayState(o),this.complete();continue e}t=[]}else{var n=e-160;t=this.decodeUtf8String(n,0)}else if(192===e)t=null;else if(194===e)t=!1;else if(195===e)t=!0;else if(202===e)t=this.readF32();else if(203===e)t=this.readF64();else if(204===e)t=this.readU8();else if(205===e)t=this.readU16();else if(206===e)t=this.readU32();else if(207===e)t=this.readU64();else if(208===e)t=this.readI8();else if(209===e)t=this.readI16();else if(210===e)t=this.readI32();else if(211===e)t=this.readI64();else if(217===e)n=this.lookU8(),t=this.decodeUtf8String(n,1);else if(218===e)n=this.lookU16(),t=this.decodeUtf8String(n,2);else if(219===e)n=this.lookU32(),t=this.decodeUtf8String(n,4);else if(220===e){if(0!==(o=this.readU16())){this.pushArrayState(o),this.complete();continue e}t=[]}else if(221===e){if(0!==(o=this.readU32())){this.pushArrayState(o),this.complete();continue e}t=[]}else if(222===e){if(0!==(o=this.readU16())){this.pushMapState(o),this.complete();continue e}t={}}else if(223===e){if(0!==(o=this.readU32())){this.pushMapState(o),this.complete();continue e}t={}}else if(196===e){var o=this.lookU8();t=this.decodeBinary(o,1)}else if(197===e)o=this.lookU16(),t=this.decodeBinary(o,2);else if(198===e)o=this.lookU32(),t=this.decodeBinary(o,4);else if(212===e)t=this.decodeExtension(1,0);else if(213===e)t=this.decodeExtension(2,0);else if(214===e)t=this.decodeExtension(4,0);else if(215===e)t=this.decodeExtension(8,0);else if(216===e)t=this.decodeExtension(16,0);else if(199===e)o=this.lookU8(),t=this.decodeExtension(o,1);else if(200===e)o=this.lookU16(),t=this.decodeExtension(o,2);else{if(201!==e)throw new pn("Unrecognized type byte: ".concat(vn(e)));o=this.lookU32(),t=this.decodeExtension(o,4)}this.complete();for(var r=this.stack;r.length>0;){var s=r[r.length-1];if(0===s.type){if(s.array[s.position]=t,s.position++,s.position!==s.size)continue e;r.pop(),t=s.array}else{if(1===s.type){if("string"!=(i=typeof t)&&"number"!==i)throw new pn("The type of key must be string or number but "+typeof t);if("__proto__"===t)throw new pn("The key __proto__ is not allowed");s.key=t,s.type=2;continue e}if(s.map[s.key]=t,s.readCount++,s.readCount!==s.size){s.key=null,s.type=1;continue e}r.pop(),t=s.map}}return t}var i},e.prototype.readHeadByte=function(){return-1===this.headByte&&(this.headByte=this.readU8()),this.headByte},e.prototype.complete=function(){this.headByte=-1},e.prototype.readArraySize=function(){var e=this.readHeadByte();switch(e){case 220:return this.readU16();case 221:return this.readU32();default:if(e<160)return e-144;throw new pn("Unrecognized array type byte: ".concat(vn(e)))}},e.prototype.pushMapState=function(e){if(e>this.maxMapLength)throw new pn("Max length exceeded: map length (".concat(e,") > maxMapLengthLength (").concat(this.maxMapLength,")"));this.stack.push({type:1,size:e,key:null,readCount:0,map:{}})},e.prototype.pushArrayState=function(e){if(e>this.maxArrayLength)throw new pn("Max length exceeded: array length (".concat(e,") > maxArrayLength (").concat(this.maxArrayLength,")"));this.stack.push({type:0,size:e,array:new Array(e),position:0})},e.prototype.decodeUtf8String=function(e,t){var n;if(e>this.maxStrLength)throw new pn("Max length exceeded: UTF-8 byte length (".concat(e,") > maxStrLength (").concat(this.maxStrLength,")"));if(this.bytes.byteLengthhn?function(e,t,n){var o=e.subarray(t,t+n);return ln.decode(o)}(this.bytes,r,e):an(this.bytes,r,e),this.pos+=t+e,o},e.prototype.stateIsMapKey=function(){return this.stack.length>0&&1===this.stack[this.stack.length-1].type},e.prototype.decodeBinary=function(e,t){if(e>this.maxBinLength)throw new pn("Max length exceeded: bin length (".concat(e,") > maxBinLength (").concat(this.maxBinLength,")"));if(!this.hasRemaining(e+t))throw kn;var n=this.pos+t,o=this.bytes.subarray(n,n+e);return this.pos+=t+e,o},e.prototype.decodeExtension=function(e,t){if(e>this.maxExtLength)throw new pn("Max length exceeded: ext length (".concat(e,") > maxExtLength (").concat(this.maxExtLength,")"));var n=this.view.getInt8(this.pos+t),o=this.decodeBinary(e,t+1);return this.extensionCodec.decode(o,n,this.context)},e.prototype.lookU8=function(){return this.view.getUint8(this.pos)},e.prototype.lookU16=function(){return this.view.getUint16(this.pos)},e.prototype.lookU32=function(){return this.view.getUint32(this.pos)},e.prototype.readU8=function(){var e=this.view.getUint8(this.pos);return this.pos++,e},e.prototype.readI8=function(){var e=this.view.getInt8(this.pos);return this.pos++,e},e.prototype.readU16=function(){var e=this.view.getUint16(this.pos);return this.pos+=2,e},e.prototype.readI16=function(){var e=this.view.getInt16(this.pos);return this.pos+=2,e},e.prototype.readU32=function(){var e=this.view.getUint32(this.pos);return this.pos+=4,e},e.prototype.readI32=function(){var e=this.view.getInt32(this.pos);return this.pos+=4,e},e.prototype.readU64=function(){var e,t,n=(e=this.view,t=this.pos,4294967296*e.getUint32(t)+e.getUint32(t+4));return this.pos+=8,n},e.prototype.readI64=function(){var e=en(this.view,this.pos);return this.pos+=8,e},e.prototype.readF32=function(){var e=this.view.getFloat32(this.pos);return this.pos+=4,e},e.prototype.readF64=function(){var e=this.view.getFloat64(this.pos);return this.pos+=8,e},e}();class xn{static write(e){let t=e.byteLength||e.length;const n=[];do{let e=127&t;t>>=7,t>0&&(e|=128),n.push(e)}while(t>0);t=e.byteLength||e.length;const o=new Uint8Array(n.length+t);return o.set(n,0),o.set(e,n.length),o.buffer}static parse(e){const t=[],n=new Uint8Array(e),o=[0,7,14,21,28];for(let r=0;r7)throw new Error("Messages bigger than 2GB are not supported.");if(!(n.byteLength>=r+i+a))throw new Error("Incomplete message.");t.push(n.slice?n.slice(r+i,r+i+a):n.subarray(r+i,r+i+a)),r=r+i+a}return t}}const Rn=new Uint8Array([145,Pt.Ping]);class An{constructor(e){this.name="messagepack",this.version=1,this.transferFormat=Nt.Binary,this._errorResult=1,this._voidResult=2,this._nonVoidResult=3,e=e||{},this._encoder=new yn(e.extensionCodec,e.context,e.maxDepth,e.initialBufferSize,e.sortKeys,e.forceFloat32,e.ignoreUndefined,e.forceIntegerToFloat),this._decoder=new Dn(e.extensionCodec,e.context,e.maxStrLength,e.maxBinLength,e.maxArrayLength,e.maxMapLength,e.maxExtLength)}parseMessages(e,t){if(!(n=e)||"undefined"==typeof ArrayBuffer||!(n instanceof ArrayBuffer||n.constructor&&"ArrayBuffer"===n.constructor.name))throw new Error("Invalid input for MessagePack hub protocol. Expected an ArrayBuffer.");var n;null===t&&(t=pt.instance);const o=xn.parse(e),r=[];for(const e of o){const n=this._parseMessage(e,t);n&&r.push(n)}return r}writeMessage(e){switch(e.type){case Pt.Invocation:return this._writeInvocation(e);case Pt.StreamInvocation:return this._writeStreamInvocation(e);case Pt.StreamItem:return this._writeStreamItem(e);case Pt.Completion:return this._writeCompletion(e);case Pt.Ping:return xn.write(Rn);case Pt.CancelInvocation:return this._writeCancelInvocation(e);case Pt.Close:return this._writeClose();default:throw new Error("Invalid message type.")}}_parseMessage(e,t){if(0===e.length)throw new Error("Invalid payload.");const n=this._decoder.decode(e);if(0===n.length||!(n instanceof Array))throw new Error("Invalid payload.");const o=n[0];switch(o){case Pt.Invocation:return this._createInvocationMessage(this._readHeaders(n),n);case Pt.StreamItem:return this._createStreamItemMessage(this._readHeaders(n),n);case Pt.Completion:return this._createCompletionMessage(this._readHeaders(n),n);case Pt.Ping:return this._createPingMessage(n);case Pt.Close:return this._createCloseMessage(n);default:return t.log(ut.Information,"Unknown message type '"+o+"' ignored."),null}}_createCloseMessage(e){if(e.length<2)throw new Error("Invalid payload for Close message.");return{allowReconnect:e.length>=3?e[2]:void 0,error:e[1],type:Pt.Close}}_createPingMessage(e){if(e.length<1)throw new Error("Invalid payload for Ping message.");return{type:Pt.Ping}}_createInvocationMessage(e,t){if(t.length<5)throw new Error("Invalid payload for Invocation message.");const n=t[2];return n?{arguments:t[4],headers:e,invocationId:n,streamIds:[],target:t[3],type:Pt.Invocation}:{arguments:t[4],headers:e,streamIds:[],target:t[3],type:Pt.Invocation}}_createStreamItemMessage(e,t){if(t.length<4)throw new Error("Invalid payload for StreamItem message.");return{headers:e,invocationId:t[2],item:t[3],type:Pt.StreamItem}}_createCompletionMessage(e,t){if(t.length<4)throw new Error("Invalid payload for Completion message.");const n=t[3];if(n!==this._voidResult&&t.length<5)throw new Error("Invalid payload for Completion message.");let o,r;switch(n){case this._errorResult:o=t[4];break;case this._nonVoidResult:r=t[4]}return{error:o,headers:e,invocationId:t[2],result:r,type:Pt.Completion}}_writeInvocation(e){let t;return t=e.streamIds?this._encoder.encode([Pt.Invocation,e.headers||{},e.invocationId||null,e.target,e.arguments,e.streamIds]):this._encoder.encode([Pt.Invocation,e.headers||{},e.invocationId||null,e.target,e.arguments]),xn.write(t.slice())}_writeStreamInvocation(e){let t;return t=e.streamIds?this._encoder.encode([Pt.StreamInvocation,e.headers||{},e.invocationId,e.target,e.arguments,e.streamIds]):this._encoder.encode([Pt.StreamInvocation,e.headers||{},e.invocationId,e.target,e.arguments]),xn.write(t.slice())}_writeStreamItem(e){const t=this._encoder.encode([Pt.StreamItem,e.headers||{},e.invocationId,e.item]);return xn.write(t.slice())}_writeCompletion(e){const t=e.error?this._errorResult:void 0!==e.result?this._nonVoidResult:this._voidResult;let n;switch(t){case this._errorResult:n=this._encoder.encode([Pt.Completion,e.headers||{},e.invocationId,t,e.error]);break;case this._voidResult:n=this._encoder.encode([Pt.Completion,e.headers||{},e.invocationId,t]);break;case this._nonVoidResult:n=this._encoder.encode([Pt.Completion,e.headers||{},e.invocationId,t,e.result])}return xn.write(n.slice())}_writeCancelInvocation(e){const t=this._encoder.encode([Pt.CancelInvocation,e.headers||{},e.invocationId]);return xn.write(t.slice())}_writeClose(){const e=this._encoder.encode([Pt.Close,null]);return xn.write(e.slice())}_readHeaders(e){const t=e[1];if("object"!=typeof t)throw new Error("Invalid headers.");return t}}let Nn=!1;function Pn(){const e=document.querySelector("#blazor-error-ui");e&&(e.style.display="block"),Nn||(Nn=!0,document.querySelectorAll("#blazor-error-ui .reload").forEach((e=>{e.onclick=function(e){location.reload(),e.preventDefault()}})),document.querySelectorAll("#blazor-error-ui .dismiss").forEach((e=>{e.onclick=function(e){const t=document.querySelector("#blazor-error-ui");t&&(t.style.display="none"),e.preventDefault()}})))}const Un="function"==typeof TextDecoder?new TextDecoder("utf-8"):null,Bn=Un?Un.decode.bind(Un):function(e){let t=0;const n=e.length,o=[],r=[];for(;t65535&&(r-=65536,o.push(r>>>10&1023|55296),r=56320|1023&r),o.push(r)}o.length>1024&&(r.push(String.fromCharCode.apply(null,o)),o.length=0)}return r.push(String.fromCharCode.apply(null,o)),r.join("")},Mn=Math.pow(2,32),$n=Math.pow(2,21)-1;function Ln(e,t){return e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24}function On(e,t){return e[t]+(e[t+1]<<8)+(e[t+2]<<16)+(e[t+3]<<24>>>0)}function Fn(e,t){const n=On(e,t+4);if(n>$n)throw new Error(`Cannot read uint64 with high order part ${n}, because the result would exceed Number.MAX_SAFE_INTEGER.`);return n*Mn+On(e,t)}class Hn{constructor(e){this.batchData=e;const t=new Jn(e);this.arrayRangeReader=new qn(e),this.arrayBuilderSegmentReader=new Kn(e),this.diffReader=new jn(e),this.editReader=new Wn(e,t),this.frameReader=new zn(e,t)}updatedComponents(){return Ln(this.batchData,this.batchData.length-20)}referenceFrames(){return Ln(this.batchData,this.batchData.length-16)}disposedComponentIds(){return Ln(this.batchData,this.batchData.length-12)}disposedEventHandlerIds(){return Ln(this.batchData,this.batchData.length-8)}updatedComponentsEntry(e,t){const n=e+4*t;return Ln(this.batchData,n)}referenceFramesEntry(e,t){return e+20*t}disposedComponentIdsEntry(e,t){const n=e+4*t;return Ln(this.batchData,n)}disposedEventHandlerIdsEntry(e,t){const n=e+8*t;return Fn(this.batchData,n)}}class jn{constructor(e){this.batchDataUint8=e}componentId(e){return Ln(this.batchDataUint8,e)}edits(e){return e+4}editsEntry(e,t){return e+16*t}}class Wn{constructor(e,t){this.batchDataUint8=e,this.stringReader=t}editType(e){return Ln(this.batchDataUint8,e)}siblingIndex(e){return Ln(this.batchDataUint8,e+4)}newTreeIndex(e){return Ln(this.batchDataUint8,e+8)}moveToSiblingIndex(e){return Ln(this.batchDataUint8,e+8)}removedAttributeName(e){const t=Ln(this.batchDataUint8,e+12);return this.stringReader.readString(t)}}class zn{constructor(e,t){this.batchDataUint8=e,this.stringReader=t}frameType(e){return Ln(this.batchDataUint8,e)}subtreeLength(e){return Ln(this.batchDataUint8,e+4)}elementReferenceCaptureId(e){const t=Ln(this.batchDataUint8,e+4);return this.stringReader.readString(t)}componentId(e){return Ln(this.batchDataUint8,e+8)}elementName(e){const t=Ln(this.batchDataUint8,e+8);return this.stringReader.readString(t)}textContent(e){const t=Ln(this.batchDataUint8,e+4);return this.stringReader.readString(t)}markupContent(e){const t=Ln(this.batchDataUint8,e+4);return this.stringReader.readString(t)}attributeName(e){const t=Ln(this.batchDataUint8,e+4);return this.stringReader.readString(t)}attributeValue(e){const t=Ln(this.batchDataUint8,e+8);return this.stringReader.readString(t)}attributeEventHandlerId(e){return Fn(this.batchDataUint8,e+12)}}class Jn{constructor(e){this.batchDataUint8=e,this.stringTableStartIndex=Ln(e,e.length-4)}readString(e){if(-1===e)return null;{const n=Ln(this.batchDataUint8,this.stringTableStartIndex+4*e),o=function(e,t){let n=0,o=0;for(let r=0;r<4;r++){const s=e[t+r];if(n|=(127&s)<this.nextBatchId)return this.fatalError?(this.logger.log(Vn.Debug,`Received a new batch ${e} but errored out on a previous batch ${this.nextBatchId-1}`),void await n.send("OnRenderCompleted",this.nextBatchId-1,this.fatalError.toString())):void this.logger.log(Vn.Debug,`Waiting for batch ${this.nextBatchId}. Batch ${e} not processed.`);try{this.nextBatchId++,this.logger.log(Vn.Debug,`Applying batch ${e}.`),function(e,t){const n=ge[e];if(!n)throw new Error(`There is no browser renderer with ID ${e}.`);const o=t.arrayRangeReader,r=t.updatedComponents(),s=o.values(r),i=o.count(r),a=t.referenceFrames(),c=o.values(a),l=t.diffReader;for(let e=0;e=this.minLevel){const n=`[${(new Date).toISOString()}] ${Vn[e]}: ${t}`;switch(e){case Vn.Critical:case Vn.Error:console.error(n);break;case Vn.Warning:console.warn(n);break;case Vn.Information:console.info(n);break;default:console.log(n)}}}}class Zn{constructor(e){this._browserRendererId=e,this._registeredDescriptors=new Set,this._descriptorsToResolveById={},this._lastUpdatedIdByDescriptor=new Map,this._componentIdsByDescriptor=new Map}registerComponentDescriptor(e){this._registeredDescriptors.add(e)}unregisterComponentDescriptor(e){this._registeredDescriptors.delete(e)}async handleUpdatedRootComponents(e){await this.handleUpdatedRootComponentsCore(this._registeredDescriptors,e)}async handleUpdatedRootComponentsCore(e,t){if(n=this._browserRendererId,!E.has(n))return;var n;const o=[];for(const n of e)if(eo(n)){if(!this.doesComponentNeedUpdate(n))continue;if(!this.hasComponentEverBeenUpdated(n)){t&&(this.markComponentAsUpdated(n),this.markComponentAsPendingResolution(n),o.push({type:"add",selectorId:n.id,marker:n.toRecord()}));continue}const e=this.getInteractiveComponentId(n);if(void 0!==e){this.markComponentAsUpdated(n),o.push({type:"update",componentId:e,marker:n.toRecord()});continue}}else{this.unregisterComponentDescriptor(n);const e=this.getInteractiveComponentId(n);if(void 0!==e){o.push({type:"remove",componentId:e});continue}}if(!o.length)return;const r=JSON.stringify(o);await function(e,t){return D(e).invokeMethodAsync("UpdateRootComponents",t)}(this._browserRendererId,r)}resolveRootComponent(e,t){const n=this.resolveComponentById(e);if(!n)throw new Error(`Could not resolve a root component for descriptor with ID '${e}'.`);if(void 0!==this.getInteractiveComponentId(n))throw new Error("Cannot resolve a root component for the same descriptor multiple times.");return this.setInteractiveComponentId(n,t),this.handleUpdatedRootComponentsCore([n],!1),n}doesComponentNeedUpdate(e){return this._lastUpdatedIdByDescriptor.get(e)!==e.id}markComponentAsUpdated(e){this._lastUpdatedIdByDescriptor.set(e,e.id)}markComponentAsPendingResolution(e){this._descriptorsToResolveById[e.id]=e}resolveComponentById(e){const t=this._descriptorsToResolveById[e];return delete this._descriptorsToResolveById[e],t}hasComponentEverBeenUpdated(e){return this._lastUpdatedIdByDescriptor.has(e)}getInteractiveComponentId(e){return this._componentIdsByDescriptor.get(e)}setInteractiveComponentId(e,t){this._componentIdsByDescriptor.set(e,t)}}function eo(e){return document.contains(e.start)}class to{constructor(e,t){this.circuitId=void 0,this.applicationState=t,this.components=e}reconnect(e){if(!this.circuitId)throw new Error("Circuit host not initialized.");return e.state!==Ut.Connected?Promise.resolve(!1):e.invoke("ConnectCircuit",this.circuitId)}initialize(e){if(this.circuitId)throw new Error(`Circuit host '${this.circuitId}' already initialized.`);this.circuitId=e}async startCircuit(e){if(e.state!==Ut.Connected)return!1;const t=this.components instanceof Zn?"[]":JSON.stringify(this.components.map((e=>e.toRecord()))),n=await e.invoke("StartCircuit",Re.getBaseURI(),Re.getLocationHref(),t,this.applicationState||"");return!!n&&(this.initialize(n),!0)}resolveElement(e,t){const n=function(e){const t=f.get(e);if(t)return f.delete(e),t}(e);if(n)return F(n,!0);const o=Number.parseInt(e);if(!Number.isNaN(o))return function(e){const{start:t,end:n}=e,o=t[O];if(o){if(o!==e)throw new Error("The start component comment was already associated with another component descriptor.");return t}const r=t.parentNode;if(!r)throw new Error(`Comment not connected to the DOM ${t.textContent}`);const s=F(r,!0),i=V(s);t[L]=s,t[O]=e;const a=F(t);if(n){const e=V(a),o=Array.prototype.indexOf.call(i,a)+1;let r=null;for(;r!==n;){const n=i.splice(o,1)[0];if(!n)throw new Error("Could not find the end component comment in the parent logical node list");n[L]=t,e.push(n),r=n}}return a}(this.components instanceof Zn?this.components.resolveRootComponent(o,t):this.components[o]);throw new Error(`Invalid sequence number or identifier '${e}'.`)}}const no={configureSignalR:e=>{},logLevel:Vn.Warning,reconnectionOptions:{maxRetries:8,retryIntervalMilliseconds:2e4,dialogId:"components-reconnect-modal"}};class oo{constructor(e,t,n,o){this.maxRetries=t,this.document=n,this.logger=o,this.addedToDom=!1,this.modal=this.document.createElement("div"),this.modal.id=e,this.maxRetries=t,this.modal.style.cssText=["position: fixed","top: 0","right: 0","bottom: 0","left: 0","z-index: 1050","display: none","overflow: hidden","background-color: #fff","opacity: 0.8","text-align: center","font-weight: bold","transition: visibility 0s linear 500ms"].join(";"),this.message=this.document.createElement("h5"),this.message.style.cssText="margin-top: 20px",this.button=this.document.createElement("button"),this.button.style.cssText="margin:5px auto 5px",this.button.textContent="Retry";const r=this.document.createElement("a");r.addEventListener("click",(()=>location.reload())),r.textContent="reload",this.reloadParagraph=this.document.createElement("p"),this.reloadParagraph.textContent="Alternatively, ",this.reloadParagraph.appendChild(r),this.modal.appendChild(this.message),this.modal.appendChild(this.button),this.modal.appendChild(this.reloadParagraph),this.loader=this.getLoader(),this.message.after(this.loader),this.button.addEventListener("click",(async()=>{this.show();try{await Ge.reconnect()||this.rejected()}catch(e){this.logger.log(Vn.Error,e),this.failed()}}))}show(){this.addedToDom||(this.addedToDom=!0,this.document.body.appendChild(this.modal)),this.modal.style.display="block",this.loader.style.display="inline-block",this.button.style.display="none",this.reloadParagraph.style.display="none",this.message.textContent="Attempting to reconnect to the server...",this.modal.style.visibility="hidden",setTimeout((()=>{this.modal.style.visibility="visible"}),0)}update(e){this.message.textContent=`Attempting to reconnect to the server: ${e} of ${this.maxRetries}`}hide(){this.modal.style.display="none"}failed(){this.button.style.display="block",this.reloadParagraph.style.display="none",this.loader.style.display="none";const e=this.document.createTextNode("Reconnection failed. Try "),t=this.document.createElement("a");t.textContent="reloading",t.setAttribute("href",""),t.addEventListener("click",(()=>location.reload()));const n=this.document.createTextNode(" the page if you're unable to reconnect.");this.message.replaceChildren(e,t,n)}rejected(){this.button.style.display="none",this.reloadParagraph.style.display="none",this.loader.style.display="none";const e=this.document.createTextNode("Could not reconnect to the server. "),t=this.document.createElement("a");t.textContent="Reload",t.setAttribute("href",""),t.addEventListener("click",(()=>location.reload()));const n=this.document.createTextNode(" the page to restore functionality.");this.message.replaceChildren(e,t,n)}getLoader(){const e=this.document.createElement("div");return e.style.cssText=["border: 0.3em solid #f3f3f3","border-top: 0.3em solid #3498db","border-radius: 50%","width: 2em","height: 2em","display: inline-block"].join(";"),e.animate([{transform:"rotate(0deg)"},{transform:"rotate(360deg)"}],{duration:2e3,iterations:1/0}),e}}class ro{constructor(e,t,n){this.dialog=e,this.maxRetries=t,this.document=n,this.document=n;const o=this.document.getElementById(ro.MaxRetriesId);o&&(o.innerText=this.maxRetries.toString())}show(){this.removeClasses(),this.dialog.classList.add(ro.ShowClassName)}update(e){const t=this.document.getElementById(ro.CurrentAttemptId);t&&(t.innerText=e.toString())}hide(){this.removeClasses(),this.dialog.classList.add(ro.HideClassName)}failed(){this.removeClasses(),this.dialog.classList.add(ro.FailedClassName)}rejected(){this.removeClasses(),this.dialog.classList.add(ro.RejectedClassName)}removeClasses(){this.dialog.classList.remove(ro.ShowClassName,ro.HideClassName,ro.FailedClassName,ro.RejectedClassName)}}ro.ShowClassName="components-reconnect-show",ro.HideClassName="components-reconnect-hide",ro.FailedClassName="components-reconnect-failed",ro.RejectedClassName="components-reconnect-rejected",ro.MaxRetriesId="components-reconnect-max-retries",ro.CurrentAttemptId="components-reconnect-current-attempt";class so{constructor(e,t,n){this._currentReconnectionProcess=null,this._logger=e,this._reconnectionDisplay=t,this._reconnectCallback=n||Ge.reconnect}onConnectionDown(e,t){if(!this._reconnectionDisplay){const t=document.getElementById(e.dialogId);this._reconnectionDisplay=t?new ro(t,e.maxRetries,document):new oo(e.dialogId,e.maxRetries,document,this._logger)}this._currentReconnectionProcess||(this._currentReconnectionProcess=new io(e,this._logger,this._reconnectCallback,this._reconnectionDisplay))}onConnectionUp(){this._currentReconnectionProcess&&(this._currentReconnectionProcess.dispose(),this._currentReconnectionProcess=null)}}class io{constructor(e,t,n,o){this.logger=t,this.reconnectCallback=n,this.isDisposed=!1,this.reconnectDisplay=o,this.reconnectDisplay.show(),this.attemptPeriodicReconnection(e)}dispose(){this.isDisposed=!0,this.reconnectDisplay.hide()}async attemptPeriodicReconnection(e){for(let t=0;tio.MaximumFirstRetryInterval?io.MaximumFirstRetryInterval:e.retryIntervalMilliseconds;if(await this.delay(n),this.isDisposed)break;try{return await this.reconnectCallback()?void 0:void this.reconnectDisplay.rejected()}catch(e){this.logger.log(Vn.Error,e)}}this.reconnectDisplay.failed()}delay(e){return new Promise((t=>setTimeout(t,e)))}}io.MaximumFirstRetryInterval=3e3;const ao=/^\s*Blazor-Component-State:(?[a-zA-Z0-9+/=]+)$/;function co(e){var t;if(e.nodeType===Node.COMMENT_NODE){const n=e.textContent||"",o=ao.exec(n),r=o&&o.groups&&o.groups.state;return r&&(null===(t=e.parentNode)||void 0===t||t.removeChild(e)),r}if(!e.hasChildNodes())return;const n=e.childNodes;for(let e=0;e.*)$/);function uo(e,t){const n=e.currentElement;if(n&&n.nodeType===Node.COMMENT_NODE&&n.textContent){const o=ho.exec(n.textContent),r=o&&o.groups&&o.groups.descriptor;if(!r)return;!function(e){if(e.parentNode instanceof Document)throw new Error("Root components cannot be marked as interactive. The element must be rendered statically so that scripts are not evaluated multiple times.")}(n);try{const o=function(e){const t=JSON.parse(e),{type:n}=t;if("server"!==n&&"webassembly"!==n)throw new Error(`Invalid component type '${n}'.`);return t}(r);switch(t){case"webassembly":return function(e,t,n){const{type:o,assembly:r,typeName:s,parameterDefinitions:i,parameterValues:a,prerenderId:c,key:l}=e,h=c?po(c,n):void 0;if(c&&!h)throw new Error(`Could not find an end component comment for '${t}'.`);if("webassembly"===o){if(!r)throw new Error("assembly must be defined when using a descriptor.");if(!s)throw new Error("typeName must be defined when using a descriptor.");return{type:o,assembly:r,typeName:s,parameterDefinitions:i&&atob(i),parameterValues:a&&atob(a),start:t,prerenderId:c,end:h,key:l}}}(o,n,e);case"server":return function(e,t,n){const{type:o,descriptor:r,sequence:s,prerenderId:i,key:a}=e,c=i?po(i,n):void 0;if(i&&!c)throw new Error(`Could not find an end component comment for '${t}'.`);if("server"===o){if(!r)throw new Error("descriptor must be defined when using a descriptor.");if(void 0===s)throw new Error("sequence must be defined when using a descriptor.");if(!Number.isInteger(s))throw new Error(`Error parsing the sequence '${s}' for component '${JSON.stringify(e)}'`);return{type:o,sequence:s,descriptor:r,start:t,prerenderId:i,end:c,key:a}}}(o,n,e)}}catch(e){throw new Error(`Found malformed component comment at ${n.textContent}`)}}}function po(e,t){for(;t.next()&&t.currentElement;){const n=t.currentElement;if(n.nodeType!==Node.COMMENT_NODE)continue;if(!n.textContent)continue;const o=ho.exec(n.textContent),r=o&&o[1];if(r)return fo(r,e),n}}function fo(e,t){const n=JSON.parse(e);if(1!==Object.keys(n).length)throw new Error(`Invalid end of component comment: '${e}'`);const o=n.prerenderId;if(!o)throw new Error(`End of component comment must have a value for the prerendered property: '${e}'`);if(o!==t)throw new Error(`End of component comment prerendered property must match the start comment prerender id: '${t}', '${o}'`)}class go{constructor(e){this.childNodes=e,this.currentIndex=-1,this.length=e.length}next(){return this.currentIndex++,this.currentIndexasync function(e,n){const o=function(e){const t=document.baseURI;return t.endsWith("/")?`${t}${e}`:`${t}/${e}`}(n),r=await import(o);if(void 0===r)return;const{beforeStart:s,afterStarted:i}=r;return i&&e.afterStartedCallbacks.push(i),s?s(...t):void 0}(this,e))))}async invokeAfterStartedCallbacks(e){await k,await Promise.all(this.afterStartedCallbacks.map((t=>t(e))))}}let wo,bo,_o,Eo=!1;async function Co(t,n){const o=function(e){const t={...no,...e};return e&&e.reconnectionOptions&&(t.reconnectionOptions={...no.reconnectionOptions,...e.reconnectionOptions}),t}(t),r=await async function(e){const t=await fetch("_blazor/initializers",{method:"GET",credentials:"include",cache:"no-cache"}),n=await t.json(),o=new vo;return await o.importInitializersAsync(n,[e]),o}(o),s=new Qn(o.logLevel);Ge.reconnect=async e=>{if(Eo)return!1;const t=e||await So(o,s,bo);return await bo.reconnect(t)?(o.reconnectionHandler.onConnectionUp(),!0):(s.log(Vn.Information,"Reconnection attempt to the circuit was rejected by the server. This may indicate that the associated state is no longer available on the server."),!1)},Ge.defaultReconnectionHandler=new so(s),o.reconnectionHandler=o.reconnectionHandler||Ge.defaultReconnectionHandler,s.log(Vn.Information,"Starting up Blazor server-side application.");const i=co(document);bo=new to(n||[],i||""),Ge._internal.navigationManager.listenForNavigationEvents(((e,t,n)=>wo.send("OnLocationChanged",e,t,n)),((e,t,n,o)=>wo.send("OnLocationChanging",e,t,n,o))),Ge._internal.forceCloseConnection=()=>wo.stop(),Ge._internal.sendJSDataStream=(e,t,n)=>function(e,t,n,o){setTimeout((async()=>{let r=5,s=(new Date).valueOf();try{const i=t instanceof Blob?t.size:t.byteLength;let a=0,c=0;for(;a1)await e.send("ReceiveJSDataChunk",n,c,h,null);else{if(!await e.invoke("ReceiveJSDataChunk",n,c,h,null))break;const t=(new Date).valueOf(),o=t-s;s=t,r=Math.max(1,Math.round(500/Math.max(1,o)))}a+=l,c++}}catch(t){await e.send("ReceiveJSDataChunk",n,-1,null,t.toString())}}),0)}(wo,e,t,n),_o=e.attachDispatcher({beginInvokeDotNetFromJS:(e,t,n,o,r)=>{wo.send("BeginInvokeDotNetFromJS",e?e.toString():null,t,n,o||0,r)},endInvokeJSFromDotNet:(e,t,n)=>{wo.send("EndInvokeJSFromDotNet",e,t,n)},sendByteArray:(e,t)=>{wo.send("ReceiveByteArray",e,t)}});const a=await So(o,s,bo);if(!await bo.startCircuit(a))return void s.log(Vn.Error,"Failed to start the circuit.");let c=!1;const l=()=>{if(!c){const e=new FormData,t=bo.circuitId;e.append("circuitId",t),c=navigator.sendBeacon("_blazor/disconnect",e)}};Ge.disconnect=l,window.addEventListener("unload",l,{capture:!1,once:!0}),s.log(Vn.Information,"Blazor server-side application started."),r.invokeAfterStartedCallbacks(Ge)}async function So(e,t,n){var o,r;const s=new An;s.name="blazorpack";const i=(new Vt).withUrl("_blazor").withHubProtocol(s);e.configureSignalR(i);const a=i.build();a.on("JS.AttachComponent",((e,t)=>function(e,t,n,o){let r=ge[e];r||(r=new de(e),ge[e]=r),r.attachRootComponentToLogicalElement(n,t,!1)}(Xn.Server,n.resolveElement(t,e),e))),a.on("JS.BeginInvokeJS",_o.beginInvokeJSFromDotNet.bind(_o)),a.on("JS.EndInvokeDotNet",_o.endInvokeDotNetFromJS.bind(_o)),a.on("JS.ReceiveByteArray",_o.receiveByteArray.bind(_o)),a.on("JS.BeginTransmitStream",(e=>{const t=new ReadableStream({start(t){a.stream("SendDotNetStreamToJS",e).subscribe({next:e=>t.enqueue(e),complete:()=>t.close(),error:e=>t.error(e)})}});_o.supplyDotNetStream(e,t)}));const c=Yn.getOrCreate(t);a.on("JS.RenderBatch",((e,n)=>{t.log(Vn.Debug,`Received render batch with id ${e} and ${n.byteLength} bytes.`),c.processBatch(e,n,a)})),a.on("JS.EndLocationChanging",Ge._internal.navigationManager.endLocationChanging),a.onclose((t=>!Eo&&e.reconnectionHandler.onConnectionDown(e.reconnectionOptions,t))),a.on("JS.Error",(e=>{Eo=!0,Io(a,e,t),Pn()}));try{await a.start(),wo=a}catch(e){if(Io(a,e,t),"FailedToNegotiateWithServerError"===e.errorType)throw e;Pn(),e.innerErrors&&(e.innerErrors.some((e=>"UnsupportedTransportError"===e.errorType&&e.transport===At.WebSockets))?t.log(Vn.Error,"Unable to connect, please ensure you are using an updated browser that supports WebSockets."):e.innerErrors.some((e=>"FailedToStartTransportError"===e.errorType&&e.transport===At.WebSockets))?t.log(Vn.Error,"Unable to connect, please ensure WebSockets are available. A VPN or proxy may be blocking the connection."):e.innerErrors.some((e=>"DisabledTransportError"===e.errorType&&e.transport===At.LongPolling))&&t.log(Vn.Error,"Unable to initiate a SignalR connection to the server. This might be because the server is not configured to support WebSockets. For additional details, visit https://aka.ms/blazor-server-websockets-error."))}return(null===(r=null===(o=a.connection)||void 0===o?void 0:o.features)||void 0===r?void 0:r.inherentKeepAlive)&&t.log(Vn.Warning,"Failed to connect via WebSockets, using the Long Polling fallback transport. This may be due to a VPN or proxy blocking the connection. To troubleshoot this, visit https://aka.ms/blazor-server-using-fallback-long-polling."),a}function Io(e,t,n){n.log(Vn.Error,t),e&&e.stop()}let ko=!1;function To(e){if(ko)throw new Error("Blazor has already started.");return ko=!0,Co(e,function(e){const t=lo(e,"server"),n=[];for(let e=0;ee.sequence-t.sequence))}(document))}Ge.start=To,window.DotNet=e,document&&document.currentScript&&"false"!==document.currentScript.getAttribute("autostart")&&To()})()})(); \ No newline at end of file diff --git a/src/Components/Web.JS/dist/Release/blazor.web.js b/src/Components/Web.JS/dist/Release/blazor.web.js index 0e832151fc1c..50a7036dc40d 100644 --- a/src/Components/Web.JS/dist/Release/blazor.web.js +++ b/src/Components/Web.JS/dist/Release/blazor.web.js @@ -1 +1 @@ -(()=>{var e={778:()=>{},77:()=>{},203:()=>{},200:()=>{},628:()=>{},321:()=>{}},t={};function n(r){var o=t[r];if(void 0!==o)return o.exports;var i=t[r]={exports:{}};return e[r](i,i.exports,n),i.exports}n.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(e){if("object"==typeof window)return window}}(),(()=>{"use strict";var e,t,r;!function(e){const t=[],n="__jsObjectId",r="__dotNetObject",o="__byte[]",i="__dotNetStream",s="__jsStreamReferenceLength";let a,c;class l{constructor(e){this._jsObject=e,this._cachedFunctions=new Map}findFunction(e){const t=this._cachedFunctions.get(e);if(t)return t;let n,r=this._jsObject;if(e.split(".").forEach((t=>{if(!(t in r))throw new Error(`Could not find '${e}' ('${t}' was undefined).`);n=r,r=r[t]})),r instanceof Function)return r=r.bind(n),this._cachedFunctions.set(e,r),r;throw new Error(`The value '${e}' is not a function.`)}getWrappedObject(){return this._jsObject}}const h={0:new l(window)};h[0]._cachedFunctions.set("import",(e=>("string"==typeof e&&e.startsWith("./")&&(e=new URL(e.substr(2),document.baseURI).toString()),import(e))));let d,u=1;function p(e){t.push(e)}function f(e){if(e&&"object"==typeof e){h[u]=new l(e);const t={[n]:u};return u++,t}throw new Error(`Cannot create a JSObjectReference from the value '${e}'.`)}function g(e){let t=-1;if(e instanceof ArrayBuffer&&(e=new Uint8Array(e)),e instanceof Blob)t=e.size;else{if(!(e.buffer instanceof ArrayBuffer))throw new Error("Supplied value is not a typed array or blob.");if(void 0===e.byteLength)throw new Error(`Cannot create a JSStreamReference from the value '${e}' as it doesn't have a byteLength.`);t=e.byteLength}const r={[s]:t};try{const t=f(e);r[n]=t[n]}catch(t){throw new Error(`Cannot create a JSStreamReference from the value '${e}'.`)}return r}function m(e,n){c=e;const r=n?JSON.parse(n,((e,n)=>t.reduce(((t,n)=>n(e,t)),n))):null;return c=void 0,r}function y(){if(void 0===a)throw new Error("No call dispatcher has been set.");if(null===a)throw new Error("There are multiple .NET runtimes present, so a default dispatcher could not be resolved. Use DotNetObject to invoke .NET instance methods.");return a}e.attachDispatcher=function(e){const t=new w(e);return void 0===a?a=t:a&&(a=null),t},e.attachReviver=p,e.invokeMethod=function(e,t,...n){return y().invokeDotNetStaticMethod(e,t,...n)},e.invokeMethodAsync=function(e,t,...n){return y().invokeDotNetStaticMethodAsync(e,t,...n)},e.createJSObjectReference=f,e.createJSStreamReference=g,e.disposeJSObjectReference=function(e){const t=e&&e[n];"number"==typeof t&&_(t)},function(e){e[e.Default=0]="Default",e[e.JSObjectReference=1]="JSObjectReference",e[e.JSStreamReference=2]="JSStreamReference",e[e.JSVoidResult=3]="JSVoidResult"}(d=e.JSCallResultType||(e.JSCallResultType={}));class w{constructor(e){this._dotNetCallDispatcher=e,this._byteArraysToBeRevived=new Map,this._pendingDotNetToJSStreams=new Map,this._pendingAsyncCalls={},this._nextAsyncCallId=1}getDotNetCallDispatcher(){return this._dotNetCallDispatcher}invokeJSFromDotNet(e,t,n,r){const o=m(this,t),i=I(b(e,r)(...o||[]),n);return null==i?null:T(this,i)}beginInvokeJSFromDotNet(e,t,n,r,o){const i=new Promise((e=>{const r=m(this,n);e(b(t,o)(...r||[]))}));e&&i.then((t=>T(this,[e,!0,I(t,r)]))).then((t=>this._dotNetCallDispatcher.endInvokeJSFromDotNet(e,!0,t)),(t=>this._dotNetCallDispatcher.endInvokeJSFromDotNet(e,!1,JSON.stringify([e,!1,v(t)]))))}endInvokeDotNetFromJS(e,t,n){const r=t?m(this,n):new Error(n);this.completePendingCall(parseInt(e,10),t,r)}invokeDotNetStaticMethod(e,t,...n){return this.invokeDotNetMethod(e,t,null,n)}invokeDotNetStaticMethodAsync(e,t,...n){return this.invokeDotNetMethodAsync(e,t,null,n)}invokeDotNetMethod(e,t,n,r){if(this._dotNetCallDispatcher.invokeDotNetFromJS){const o=T(this,r),i=this._dotNetCallDispatcher.invokeDotNetFromJS(e,t,n,o);return i?m(this,i):null}throw new Error("The current dispatcher does not support synchronous calls from JS to .NET. Use invokeDotNetMethodAsync instead.")}invokeDotNetMethodAsync(e,t,n,r){if(e&&n)throw new Error(`For instance method calls, assemblyName should be null. Received '${e}'.`);const o=this._nextAsyncCallId++,i=new Promise(((e,t)=>{this._pendingAsyncCalls[o]={resolve:e,reject:t}}));try{const i=T(this,r);this._dotNetCallDispatcher.beginInvokeDotNetFromJS(o,e,t,n,i)}catch(e){this.completePendingCall(o,!1,e)}return i}receiveByteArray(e,t){this._byteArraysToBeRevived.set(e,t)}processByteArray(e){const t=this._byteArraysToBeRevived.get(e);return t?(this._byteArraysToBeRevived.delete(e),t):null}supplyDotNetStream(e,t){if(this._pendingDotNetToJSStreams.has(e)){const n=this._pendingDotNetToJSStreams.get(e);this._pendingDotNetToJSStreams.delete(e),n.resolve(t)}else{const n=new C;n.resolve(t),this._pendingDotNetToJSStreams.set(e,n)}}getDotNetStreamPromise(e){let t;if(this._pendingDotNetToJSStreams.has(e))t=this._pendingDotNetToJSStreams.get(e).streamPromise,this._pendingDotNetToJSStreams.delete(e);else{const n=new C;this._pendingDotNetToJSStreams.set(e,n),t=n.streamPromise}return t}completePendingCall(e,t,n){if(!this._pendingAsyncCalls.hasOwnProperty(e))throw new Error(`There is no pending async call with ID ${e}.`);const r=this._pendingAsyncCalls[e];delete this._pendingAsyncCalls[e],t?r.resolve(n):r.reject(n)}}function v(e){return e instanceof Error?`${e.message}\n${e.stack}`:e?e.toString():"null"}function b(e,t){const n=h[t];if(n)return n.findFunction(e);throw new Error(`JS object instance with ID ${t} does not exist (has it been disposed?).`)}function _(e){delete h[e]}e.findJSFunction=b,e.disposeJSObjectReferenceById=_;class E{constructor(e,t){this._id=e,this._callDispatcher=t}invokeMethod(e,...t){return this._callDispatcher.invokeDotNetMethod(null,e,this._id,t)}invokeMethodAsync(e,...t){return this._callDispatcher.invokeDotNetMethodAsync(null,e,this._id,t)}dispose(){this._callDispatcher.invokeDotNetMethodAsync(null,"__Dispose",this._id,null).catch((e=>console.error(e)))}serializeAsArg(){return{[r]:this._id}}}e.DotNetObject=E,p((function(e,t){if(t&&"object"==typeof t){if(t.hasOwnProperty(r))return new E(t[r],c);if(t.hasOwnProperty(n)){const e=t[n],r=h[e];if(r)return r.getWrappedObject();throw new Error(`JS object instance with Id '${e}' does not exist. It may have been disposed.`)}if(t.hasOwnProperty(o)){const e=t[o],n=c.processByteArray(e);if(void 0===n)throw new Error(`Byte array index '${e}' does not exist.`);return n}if(t.hasOwnProperty(i)){const e=t[i],n=c.getDotNetStreamPromise(e);return new S(n)}}return t}));class S{constructor(e){this._streamPromise=e}stream(){return this._streamPromise}async arrayBuffer(){return new Response(await this.stream()).arrayBuffer()}}class C{constructor(){this.streamPromise=new Promise(((e,t)=>{this.resolve=e,this.reject=t}))}}function I(e,t){switch(t){case d.Default:return e;case d.JSObjectReference:return f(e);case d.JSStreamReference:return g(e);case d.JSVoidResult:return null;default:throw new Error(`Invalid JS call result type '${t}'.`)}}let k=0;function T(e,t){k=0,c=e;const n=JSON.stringify(t,x);return c=void 0,n}function x(e,t){if(t instanceof E)return t.serializeAsArg();if(t instanceof Uint8Array){c.getDotNetCallDispatcher().sendByteArray(k,t);const e={[o]:k};return k++,e}return t}}(e||(e={})),function(e){e[e.prependFrame=1]="prependFrame",e[e.removeFrame=2]="removeFrame",e[e.setAttribute=3]="setAttribute",e[e.removeAttribute=4]="removeAttribute",e[e.updateText=5]="updateText",e[e.stepIn=6]="stepIn",e[e.stepOut=7]="stepOut",e[e.updateMarkup=8]="updateMarkup",e[e.permutationListEntry=9]="permutationListEntry",e[e.permutationListEnd=10]="permutationListEnd"}(t||(t={})),function(e){e[e.element=1]="element",e[e.text=2]="text",e[e.attribute=3]="attribute",e[e.component=4]="component",e[e.region=5]="region",e[e.elementReferenceCapture=6]="elementReferenceCapture",e[e.markup=8]="markup",e[e.namedEvent=10]="namedEvent"}(r||(r={}));class o{constructor(e,t){this.componentId=e,this.fieldValue=t}static fromEvent(e,t){const n=t.target;if(n instanceof Element){const t=function(e){return e instanceof HTMLInputElement?e.type&&"checkbox"===e.type.toLowerCase()?{value:e.checked}:{value:e.value}:e instanceof HTMLSelectElement||e instanceof HTMLTextAreaElement?{value:e.value}:null}(n);if(t)return new o(e,t.value)}return null}}const i=new Map,s=new Map,a=[];function c(e){return i.get(e)}function l(e){const t=i.get(e);return(null==t?void 0:t.browserEventName)||e}function h(e,t){e.forEach((e=>i.set(e,t)))}function d(e){const t=[];for(let n=0;ne.selected)).map((e=>e.value))}}{const e=function(e){return!!e&&"INPUT"===e.tagName&&"checkbox"===e.getAttribute("type")}(t);return{value:e?!!t.checked:t.value}}}}),h(["copy","cut","paste"],{createEventArgs:e=>({type:e.type})}),h(["drag","dragend","dragenter","dragleave","dragover","dragstart","drop"],{createEventArgs:e=>{return{...u(t=e),dataTransfer:t.dataTransfer?{dropEffect:t.dataTransfer.dropEffect,effectAllowed:t.dataTransfer.effectAllowed,files:Array.from(t.dataTransfer.files).map((e=>e.name)),items:Array.from(t.dataTransfer.items).map((e=>({kind:e.kind,type:e.type}))),types:t.dataTransfer.types}:null};var t}}),h(["focus","blur","focusin","focusout"],{createEventArgs:e=>({type:e.type})}),h(["keydown","keyup","keypress"],{createEventArgs:e=>{return{key:(t=e).key,code:t.code,location:t.location,repeat:t.repeat,ctrlKey:t.ctrlKey,shiftKey:t.shiftKey,altKey:t.altKey,metaKey:t.metaKey,type:t.type};var t}}),h(["contextmenu","click","mouseover","mouseout","mousemove","mousedown","mouseup","mouseleave","mouseenter","dblclick"],{createEventArgs:e=>u(e)}),h(["error"],{createEventArgs:e=>{return{message:(t=e).message,filename:t.filename,lineno:t.lineno,colno:t.colno,type:t.type};var t}}),h(["loadstart","timeout","abort","load","loadend","progress"],{createEventArgs:e=>{return{lengthComputable:(t=e).lengthComputable,loaded:t.loaded,total:t.total,type:t.type};var t}}),h(["touchcancel","touchend","touchmove","touchenter","touchleave","touchstart"],{createEventArgs:e=>{return{detail:(t=e).detail,touches:d(t.touches),targetTouches:d(t.targetTouches),changedTouches:d(t.changedTouches),ctrlKey:t.ctrlKey,shiftKey:t.shiftKey,altKey:t.altKey,metaKey:t.metaKey,type:t.type};var t}}),h(["gotpointercapture","lostpointercapture","pointercancel","pointerdown","pointerenter","pointerleave","pointermove","pointerout","pointerover","pointerup"],{createEventArgs:e=>{return{...u(t=e),pointerId:t.pointerId,width:t.width,height:t.height,pressure:t.pressure,tiltX:t.tiltX,tiltY:t.tiltY,pointerType:t.pointerType,isPrimary:t.isPrimary};var t}}),h(["wheel","mousewheel"],{createEventArgs:e=>{return{...u(t=e),deltaX:t.deltaX,deltaY:t.deltaY,deltaZ:t.deltaZ,deltaMode:t.deltaMode};var t}}),h(["toggle"],{createEventArgs:()=>({})});const p=["date","datetime-local","month","time","week"],f=new Map;let g,m,y=0;const w={async add(e,t,n){if(!n)throw new Error("initialParameters must be an object, even if empty.");const r="__bl-dynamic-root:"+(++y).toString();f.set(r,e);const o=await E().invokeMethodAsync("AddRootComponent",t,r),i=new _(o,m[t]);return await i.setParameters(n),i}};function v(e){const t=f.get(e);if(t)return f.delete(e),t}class b{invoke(e){return this._callback(e)}setCallback(t){this._selfJSObjectReference||(this._selfJSObjectReference=e.createJSObjectReference(this)),this._callback=t}getJSObjectReference(){return this._selfJSObjectReference}dispose(){this._selfJSObjectReference&&e.disposeJSObjectReference(this._selfJSObjectReference)}}class _{constructor(e,t){this._jsEventCallbackWrappers=new Map,this._componentId=e;for(const e of t)"eventcallback"===e.type&&this._jsEventCallbackWrappers.set(e.name.toLowerCase(),new b)}setParameters(e){const t={},n=Object.entries(e||{}),r=n.length;for(const[e,r]of n){const n=this._jsEventCallbackWrappers.get(e.toLowerCase());n&&r?(n.setCallback(r),t[e]=n.getJSObjectReference()):t[e]=r}return E().invokeMethodAsync("SetRootComponentParameters",this._componentId,r,t)}async dispose(){if(null!==this._componentId){await E().invokeMethodAsync("RemoveRootComponent",this._componentId),this._componentId=null;for(const e of this._jsEventCallbackWrappers.values())e.dispose()}}}function E(){if(!g)throw new Error("Dynamic root components have not been enabled in this application.");return g}const S=[];let C;const I=new Promise((e=>{C=e}));function k(e,t,n){return x(e,t.eventHandlerId,(()=>T(e).invokeMethodAsync("DispatchEventAsync",t,n)))}function T(e){const t=S[e];if(!t)throw new Error(`No interop methods are registered for renderer ${e}`);return t}let x=(e,t,n)=>n();const D=M(["abort","blur","canplay","canplaythrough","change","cuechange","durationchange","emptied","ended","error","focus","load","loadeddata","loadedmetadata","loadend","loadstart","mouseenter","mouseleave","pointerenter","pointerleave","pause","play","playing","progress","ratechange","reset","scroll","seeked","seeking","stalled","submit","suspend","timeupdate","toggle","unload","volumechange","waiting","DOMNodeInsertedIntoDocument","DOMNodeRemovedFromDocument"]),N={submit:!0},A=M(["click","dblclick","mousedown","mousemove","mouseup"]);class R{constructor(e){this.browserRendererId=e,this.afterClickCallbacks=[];const t=++R.nextEventDelegatorId;this.eventsCollectionKey=`_blazorEvents_${t}`,this.eventInfoStore=new P(this.onGlobalEvent.bind(this))}setListener(e,t,n,r){const o=this.getEventHandlerInfosForElement(e,!0),i=o.getHandler(t);if(i)this.eventInfoStore.update(i.eventHandlerId,n);else{const i={element:e,eventName:t,eventHandlerId:n,renderingComponentId:r};this.eventInfoStore.add(i),o.setHandler(t,i)}}getHandler(e){return this.eventInfoStore.get(e)}removeListener(e){const t=this.eventInfoStore.remove(e);if(t){const e=t.element,n=this.getEventHandlerInfosForElement(e,!1);n&&n.removeHandler(t.eventName)}}notifyAfterClick(e){this.afterClickCallbacks.push(e),this.eventInfoStore.addGlobalListener("click")}setStopPropagation(e,t,n){this.getEventHandlerInfosForElement(e,!0).stopPropagation(t,n)}setPreventDefault(e,t,n){this.getEventHandlerInfosForElement(e,!0).preventDefault(t,n)}onGlobalEvent(e){if(!(e.target instanceof Element))return;this.dispatchGlobalEventToAllElements(e.type,e);const t=(n=e.type,s.get(n));var n;t&&t.forEach((t=>this.dispatchGlobalEventToAllElements(t,e))),"click"===e.type&&this.afterClickCallbacks.forEach((t=>t(e)))}dispatchGlobalEventToAllElements(e,t){const n=t.composedPath();let r=n.shift(),i=null,s=!1;const a=Object.prototype.hasOwnProperty.call(D,e);let l=!1;for(;r;){const u=r,p=this.getEventHandlerInfosForElement(u,!1);if(p){const n=p.getHandler(e);if(n&&(h=u,d=t.type,!((h instanceof HTMLButtonElement||h instanceof HTMLInputElement||h instanceof HTMLTextAreaElement||h instanceof HTMLSelectElement)&&Object.prototype.hasOwnProperty.call(A,d)&&h.disabled))){if(!s){const n=c(e);i=(null==n?void 0:n.createEventArgs)?n.createEventArgs(t):{},s=!0}Object.prototype.hasOwnProperty.call(N,t.type)&&t.preventDefault(),k(this.browserRendererId,{eventHandlerId:n.eventHandlerId,eventName:e,eventFieldInfo:o.fromEvent(n.renderingComponentId,t)},i)}p.stopPropagation(e)&&(l=!0),p.preventDefault(e)&&t.preventDefault()}r=a||l?void 0:n.shift()}var h,d}getEventHandlerInfosForElement(e,t){return Object.prototype.hasOwnProperty.call(e,this.eventsCollectionKey)?e[this.eventsCollectionKey]:t?e[this.eventsCollectionKey]=new U:null}}R.nextEventDelegatorId=0;class P{constructor(e){this.globalListener=e,this.infosByEventHandlerId={},this.countByEventName={},a.push(this.handleEventNameAliasAdded.bind(this))}add(e){if(this.infosByEventHandlerId[e.eventHandlerId])throw new Error(`Event ${e.eventHandlerId} is already tracked`);this.infosByEventHandlerId[e.eventHandlerId]=e,this.addGlobalListener(e.eventName)}get(e){return this.infosByEventHandlerId[e]}addGlobalListener(e){if(e=l(e),Object.prototype.hasOwnProperty.call(this.countByEventName,e))this.countByEventName[e]++;else{this.countByEventName[e]=1;const t=Object.prototype.hasOwnProperty.call(D,e);document.addEventListener(e,this.globalListener,t)}}update(e,t){if(Object.prototype.hasOwnProperty.call(this.infosByEventHandlerId,t))throw new Error(`Event ${t} is already tracked`);const n=this.infosByEventHandlerId[e];delete this.infosByEventHandlerId[e],n.eventHandlerId=t,this.infosByEventHandlerId[t]=n}remove(e){const t=this.infosByEventHandlerId[e];if(t){delete this.infosByEventHandlerId[e];const n=l(t.eventName);0==--this.countByEventName[n]&&(delete this.countByEventName[n],document.removeEventListener(n,this.globalListener))}return t}handleEventNameAliasAdded(e,t){if(Object.prototype.hasOwnProperty.call(this.countByEventName,e)){const n=this.countByEventName[e];delete this.countByEventName[e],document.removeEventListener(e,this.globalListener),this.addGlobalListener(t),this.countByEventName[t]+=n-1}}}class U{constructor(){this.handlers={},this.preventDefaultFlags=null,this.stopPropagationFlags=null}getHandler(e){return Object.prototype.hasOwnProperty.call(this.handlers,e)?this.handlers[e]:null}setHandler(e,t){this.handlers[e]=t}removeHandler(e){delete this.handlers[e]}preventDefault(e,t){return void 0!==t&&(this.preventDefaultFlags=this.preventDefaultFlags||{},this.preventDefaultFlags[e]=t),!!this.preventDefaultFlags&&this.preventDefaultFlags[e]}stopPropagation(e,t){return void 0!==t&&(this.stopPropagationFlags=this.stopPropagationFlags||{},this.stopPropagationFlags[e]=t),!!this.stopPropagationFlags&&this.stopPropagationFlags[e]}}function M(e){const t={};return e.forEach((e=>{t[e]=!0})),t}const L=Z("_blazorLogicalChildren"),B=Z("_blazorLogicalParent"),O=Z("_blazorLogicalEnd");function F(e,t){if(!e.parentNode)throw new Error(`Comment not connected to the DOM ${e.textContent}`);const n=e.parentNode,r=$(n,!0),o=K(r);return Array.from(n.childNodes).forEach((e=>o.push(e))),e[B]=r,t&&(e[O]=t,$(t)),$(e)}function $(e,t){if(e.childNodes.length>0&&!t)throw new Error("New logical elements must start empty, or allowExistingContents must be true");return L in e||(e[L]=[]),e}function H(e,t){const n=document.createComment("!");return j(n,e,t),n}function j(e,t,n){const r=e;if(e instanceof Comment&&K(r)&&K(r).length>0)throw new Error("Not implemented: inserting non-empty logical container");if(z(r))throw new Error("Not implemented: moving existing logical children");const o=K(t);if(n0;)W(n,0)}const r=n;r.parentNode.removeChild(r)}function z(e){return e[B]||null}function J(e,t){return K(e)[t]}function q(e){const t=X(e);return"http://www.w3.org/2000/svg"===t.namespaceURI&&"foreignObject"!==t.tagName}function K(e){return e[L]}function V(e,t){const n=K(e);t.forEach((e=>{e.moveRangeStart=n[e.fromSiblingIndex],e.moveRangeEnd=Q(e.moveRangeStart)})),t.forEach((t=>{const r=document.createComment("marker");t.moveToBeforeMarker=r;const o=n[t.toSiblingIndex+1];o?o.parentNode.insertBefore(r,o):Y(r,e)})),t.forEach((e=>{const t=e.moveToBeforeMarker,n=t.parentNode,r=e.moveRangeStart,o=e.moveRangeEnd;let i=r;for(;i;){const e=i.nextSibling;if(n.insertBefore(i,t),i===o)break;i=e}n.removeChild(t)})),t.forEach((e=>{n[e.toSiblingIndex]=e.moveRangeStart}))}function X(e){if(e instanceof Element||e instanceof DocumentFragment)return e;if(e instanceof Comment)return e.parentNode;throw new Error("Not a valid logical element")}function G(e){const t=K(z(e));return t[Array.prototype.indexOf.call(t,e)+1]||null}function Y(e,t){if(t instanceof Element||t instanceof DocumentFragment)t.appendChild(e);else{if(!(t instanceof Comment))throw new Error(`Cannot append node because the parent is not a valid logical element. Parent: ${t}`);{const n=G(t);n?n.parentNode.insertBefore(e,n):Y(e,z(t))}}}function Q(e){if(e instanceof Element||e instanceof DocumentFragment)return e;const t=G(e);if(t)return t.previousSibling;{const t=z(e);return t instanceof Element||t instanceof DocumentFragment?t.lastChild:Q(t)}}function Z(e){return"function"==typeof Symbol?Symbol():e}function ee(e){return`_bl_${e}`}const te="__internalId";e.attachReviver(((e,t)=>t&&"object"==typeof t&&Object.prototype.hasOwnProperty.call(t,te)&&"string"==typeof t[te]?function(e){const t=`[${ee(e)}]`;return document.querySelector(t)}(t[te]):t));const ne="_blazorDeferredValue";function re(e){e instanceof HTMLOptionElement?ae(e):ne in e&&se(e,e[ne])}function oe(e){return"select-multiple"===e.type}function ie(e,t){e.value=t||""}function se(e,t){e instanceof HTMLSelectElement?oe(e)?function(e,t){t||(t=[]);for(let n=0;n{Ce()&&be(e,(e=>{Le(e,!0,!1)}))}))}attachRootComponentToLogicalElement(e,t,n){this.attachComponentToElement(e,t),this.rootComponentIds.add(e),n||(he[e]=t)}updateComponent(e,t,n,r){var o;const i=this.childComponentLocations[t];if(!i)throw new Error(`No element is currently associated with component ${t}`);const s=he[t];if(s){const e=function(e){return e[O]||null}(s);delete he[t],e?function(e,t){const n=z(e);if(!n)throw new Error("Can't clear between nodes. The start node does not have a logical parent.");const r=K(n),o=r.indexOf(e)+1,i=r.indexOf(t);for(let e=o;e<=i;e++)W(n,o);e.textContent="!"}(s,e):function(e){let t;for(;t=e.firstChild;)e.removeChild(t)}(s)}const a=null===(o=X(i))||void 0===o?void 0:o.getRootNode(),c=a&&a.activeElement;this.applyEdits(e,t,i,0,n,r),c instanceof HTMLElement&&a&&a.activeElement!==c&&c.focus()}disposeComponent(e){this.rootComponentIds.delete(e)&&function(e){const t=K(e);for(;t.length;)W(e,0)}(this.childComponentLocations[e]),delete this.childComponentLocations[e]}disposeEventHandler(e){this.eventDelegator.removeListener(e)}attachComponentToElement(e,t){this.childComponentLocations[e]=t}applyEdits(e,n,r,o,i,s){let a,c=0,l=o;const h=e.arrayBuilderSegmentReader,d=e.editReader,u=e.frameReader,p=h.values(i),f=h.offset(i),g=f+h.count(i);for(let i=f;idocument.baseURI,getLocationHref:()=>location.href,scrollToElement:Ue};function Ue(e){const t=document.getElementById(e);return!!t&&(t.scrollIntoView(),!0)}function Me(e,t,n=!1){const r=Ee(e);!t.forceLoad&&_e(r)?Le(r,!1,t.replaceHistoryEntry,t.historyEntryState,n):function(e,t){if(location.href===e){const t=e+"?";history.replaceState(null,"",t),location.replace(e)}else t?location.replace(e):location.href=e}(e,t.replaceHistoryEntry)}async function Le(e,t,n,r=void 0,o=!1){if(Fe(),function(e){const t=e.indexOf("#");return t>-1&&location.href.replace(location.hash,"")===e.substring(0,t)}(e))!function(e,t,n){Be(e,t,n);const r=e.indexOf("#");r!==e.length-1&&Ue(e.substring(r+1))}(e,n,r);else{if(!o&&ke&&!await $e(e,r,t))return;ge=!0,Be(e,n,r),await He(t)}}function Be(e,t,n=void 0){t?history.replaceState({userState:n,_index:Te},"",e):(Te++,history.pushState({userState:n,_index:Te},"",e))}function Oe(e){return new Promise((t=>{const n=Ae;Ae=()=>{Ae=n,t()},history.go(e)}))}function Fe(){Re&&(Re(!1),Re=null)}function $e(e,t,n){return new Promise((r=>{Fe(),Ne?(xe++,Re=r,Ne(xe,e,t,n)):r(!1)}))}async function He(e){var t;De&&await De(location.href,null===(t=history.state)||void 0===t?void 0:t.userState,e)}async function je(e){var t,n;Ae&&await Ae(e),Te=null!==(n=null===(t=history.state)||void 0===t?void 0:t._index)&&void 0!==n?n:0}const We={focus:function(e,t){if(e instanceof HTMLElement)e.focus({preventScroll:t});else{if(!(e instanceof SVGElement))throw new Error("Unable to focus an invalid element.");if(!e.hasAttribute("tabindex"))throw new Error("Unable to focus an SVG element that does not have a tabindex.");e.focus({preventScroll:t})}},focusBySelector:function(e,t){const n=document.querySelector(e);n&&(n.hasAttribute("tabindex")||(n.tabIndex=-1),n.focus({preventScroll:!0}))}},ze={init:function(e,t,n,r=50){const o=qe(t);(o||document.documentElement).style.overflowAnchor="none";const i=document.createRange();h(n.parentElement)&&(t.style.display="table-row",n.style.display="table-row");const s=new IntersectionObserver((function(r){r.forEach((r=>{var o;if(!r.isIntersecting)return;i.setStartAfter(t),i.setEndBefore(n);const s=i.getBoundingClientRect().height,a=null===(o=r.rootBounds)||void 0===o?void 0:o.height;r.target===t?e.invokeMethodAsync("OnSpacerBeforeVisible",r.intersectionRect.top-r.boundingClientRect.top,s,a):r.target===n&&n.offsetHeight>0&&e.invokeMethodAsync("OnSpacerAfterVisible",r.boundingClientRect.bottom-r.intersectionRect.bottom,s,a)}))}),{root:o,rootMargin:`${r}px`});s.observe(t),s.observe(n);const a=l(t),c=l(n);function l(e){const t={attributes:!0},n=new MutationObserver(((n,r)=>{h(e.parentElement)&&(r.disconnect(),e.style.display="table-row",r.observe(e,t)),s.unobserve(e),s.observe(e)}));return n.observe(e,t),n}function h(e){return null!==e&&(e instanceof HTMLTableElement&&""===e.style.display||"table"===e.style.display||e instanceof HTMLTableSectionElement&&""===e.style.display||"table-row-group"===e.style.display)}Je[e._id]={intersectionObserver:s,mutationObserverBefore:a,mutationObserverAfter:c}},dispose:function(e){const t=Je[e._id];t&&(t.intersectionObserver.disconnect(),t.mutationObserverBefore.disconnect(),t.mutationObserverAfter.disconnect(),e.dispose(),delete Je[e._id])}},Je={};function qe(e){return e&&e!==document.body&&e!==document.documentElement?"visible"!==getComputedStyle(e).overflowY?e:qe(e.parentElement):null}const Ke={getAndRemoveExistingTitle:function(){var e;const t=document.head?document.head.getElementsByTagName("title"):[];if(0===t.length)return null;let n=null;for(let r=t.length-1;r>=0;r--){const o=t[r],i=o.previousSibling;i instanceof Comment&&null!==z(i)||(null===n&&(n=o.textContent),null===(e=o.parentNode)||void 0===e||e.removeChild(o))}return n}},Ve={init:function(e,t){t._blazorInputFileNextFileId=0,t.addEventListener("click",(function(){t.value=""})),t.addEventListener("change",(function(){t._blazorFilesById={};const n=Array.prototype.map.call(t.files,(function(e){const n={id:++t._blazorInputFileNextFileId,lastModified:new Date(e.lastModified).toISOString(),name:e.name,size:e.size,contentType:e.type,readPromise:void 0,arrayBuffer:void 0,blob:e};return t._blazorFilesById[n.id]=n,n}));e.invokeMethodAsync("NotifyChange",n)}))},toImageFile:async function(e,t,n,r,o){const i=Xe(e,t),s=await new Promise((function(e){const t=new Image;t.onload=function(){URL.revokeObjectURL(t.src),e(t)},t.onerror=function(){t.onerror=null,URL.revokeObjectURL(t.src)},t.src=URL.createObjectURL(i.blob)})),a=await new Promise((function(e){var t;const i=Math.min(1,r/s.width),a=Math.min(1,o/s.height),c=Math.min(i,a),l=document.createElement("canvas");l.width=Math.round(s.width*c),l.height=Math.round(s.height*c),null===(t=l.getContext("2d"))||void 0===t||t.drawImage(s,0,0,l.width,l.height),l.toBlob(e,n)})),c={id:++e._blazorInputFileNextFileId,lastModified:i.lastModified,name:i.name,size:(null==a?void 0:a.size)||0,contentType:n,blob:a||i.blob};return e._blazorFilesById[c.id]=c,c},readFileData:async function(e,t){return Xe(e,t).blob}};function Xe(e,t){const n=e._blazorFilesById[t];if(!n)throw new Error(`There is no file with ID ${t}. The file list may have changed. See https://aka.ms/aspnet/blazor-input-file-multiple-selections.`);return n}const Ge=new Set,Ye={enableNavigationPrompt:function(e){0===Ge.size&&window.addEventListener("beforeunload",Qe),Ge.add(e)},disableNavigationPrompt:function(e){Ge.delete(e),0===Ge.size&&window.removeEventListener("beforeunload",Qe)}};function Qe(e){e.preventDefault(),e.returnValue=!0}async function Ze(e,t,n){return e instanceof Blob?await async function(e,t,n){const r=e.slice(t,t+n),o=await r.arrayBuffer();return new Uint8Array(o)}(e,t,n):function(e,t,n){return new Uint8Array(e.buffer,e.byteOffset+t,n)}(e,t,n)}const et=new Map,tt={navigateTo:function(e,t,n=!1){Me(e,t instanceof Object?t:{forceLoad:t,replaceHistoryEntry:n})},registerCustomEventType:function(e,t){if(!t)throw new Error("The options parameter is required.");if(i.has(e))throw new Error(`The event '${e}' is already registered.`);if(t.browserEventName){const n=s.get(t.browserEventName);n?n.push(e):s.set(t.browserEventName,[e]),a.forEach((n=>n(e,t.browserEventName)))}i.set(e,t)},rootComponents:w,_internal:{navigationManager:Pe,domWrapper:We,Virtualize:ze,PageTitle:Ke,InputFile:Ve,NavigationLock:Ye,getJSDataStreamChunk:Ze,attachWebRendererInterop:function(t,n,r){const o=S.length;return S.push(t),Object.keys(n).length>0&&function(t,n,r){if(g)throw new Error("Dynamic root components have already been enabled.");g=t,m=n;for(const[t,o]of Object.entries(r)){const r=e.findJSFunction(t,0);for(const e of o)r(e,n[e])}}(T(o),n,r),C(),o}}};window.Blazor=tt;const nt=[0,2e3,1e4,3e4,null];class rt{constructor(e){this._retryDelays=void 0!==e?[...e,null]:nt}nextRetryDelayInMilliseconds(e){return this._retryDelays[e.previousRetryCount]}}class ot{}ot.Authorization="Authorization",ot.Cookie="Cookie";class it{constructor(e,t,n){this.statusCode=e,this.statusText=t,this.content=n}}class st{get(e,t){return this.send({...t,method:"GET",url:e})}post(e,t){return this.send({...t,method:"POST",url:e})}delete(e,t){return this.send({...t,method:"DELETE",url:e})}getCookieString(e){return""}}class at extends st{constructor(e,t){super(),this._innerClient=e,this._accessTokenFactory=t}async send(e){let t=!0;this._accessTokenFactory&&(!this._accessToken||e.url&&e.url.indexOf("/negotiate?")>0)&&(t=!1,this._accessToken=await this._accessTokenFactory()),this._setAuthorizationHeader(e);const n=await this._innerClient.send(e);return t&&401===n.statusCode&&this._accessTokenFactory?(this._accessToken=await this._accessTokenFactory(),this._setAuthorizationHeader(e),await this._innerClient.send(e)):n}_setAuthorizationHeader(e){e.headers||(e.headers={}),this._accessToken?e.headers[ot.Authorization]=`Bearer ${this._accessToken}`:this._accessTokenFactory&&e.headers[ot.Authorization]&&delete e.headers[ot.Authorization]}getCookieString(e){return this._innerClient.getCookieString(e)}}class ct extends Error{constructor(e,t){const n=new.target.prototype;super(`${e}: Status code '${t}'`),this.statusCode=t,this.__proto__=n}}class lt extends Error{constructor(e="A timeout occurred."){const t=new.target.prototype;super(e),this.__proto__=t}}class ht extends Error{constructor(e="An abort occurred."){const t=new.target.prototype;super(e),this.__proto__=t}}class dt extends Error{constructor(e,t){const n=new.target.prototype;super(e),this.transport=t,this.errorType="UnsupportedTransportError",this.__proto__=n}}class ut extends Error{constructor(e,t){const n=new.target.prototype;super(e),this.transport=t,this.errorType="DisabledTransportError",this.__proto__=n}}class pt extends Error{constructor(e,t){const n=new.target.prototype;super(e),this.transport=t,this.errorType="FailedToStartTransportError",this.__proto__=n}}class ft extends Error{constructor(e){const t=new.target.prototype;super(e),this.errorType="FailedToNegotiateWithServerError",this.__proto__=t}}class gt extends Error{constructor(e,t){const n=new.target.prototype;super(e),this.innerErrors=t,this.__proto__=n}}var mt;!function(e){e[e.Trace=0]="Trace",e[e.Debug=1]="Debug",e[e.Information=2]="Information",e[e.Warning=3]="Warning",e[e.Error=4]="Error",e[e.Critical=5]="Critical",e[e.None=6]="None"}(mt||(mt={}));class yt{constructor(){}log(e,t){}}yt.instance=new yt;const wt="0.0.0-DEV_BUILD";class vt{static isRequired(e,t){if(null==e)throw new Error(`The '${t}' argument is required.`)}static isNotEmpty(e,t){if(!e||e.match(/^\s*$/))throw new Error(`The '${t}' argument should not be empty.`)}static isIn(e,t,n){if(!(e in t))throw new Error(`Unknown ${n} value: ${e}.`)}}class bt{static get isBrowser(){return!bt.isNode&&"object"==typeof window&&"object"==typeof window.document}static get isWebWorker(){return!bt.isNode&&"object"==typeof self&&"importScripts"in self}static get isReactNative(){return!bt.isNode&&"object"==typeof window&&void 0===window.document}static get isNode(){return"undefined"!=typeof process&&process.release&&"node"===process.release.name}}function _t(e,t){let n="";return Et(e)?(n=`Binary data of length ${e.byteLength}`,t&&(n+=`. Content: '${function(e){const t=new Uint8Array(e);let n="";return t.forEach((e=>{n+=`0x${e<16?"0":""}${e.toString(16)} `})),n.substr(0,n.length-1)}(e)}'`)):"string"==typeof e&&(n=`String data of length ${e.length}`,t&&(n+=`. Content: '${e}'`)),n}function Et(e){return e&&"undefined"!=typeof ArrayBuffer&&(e instanceof ArrayBuffer||e.constructor&&"ArrayBuffer"===e.constructor.name)}async function St(e,t,n,r,o,i){const s={},[a,c]=kt();s[a]=c,e.log(mt.Trace,`(${t} transport) sending data. ${_t(o,i.logMessageContent)}.`);const l=Et(o)?"arraybuffer":"text",h=await n.post(r,{content:o,headers:{...s,...i.headers},responseType:l,timeout:i.timeout,withCredentials:i.withCredentials});e.log(mt.Trace,`(${t} transport) request complete. Response status: ${h.statusCode}.`)}class Ct{constructor(e,t){this._subject=e,this._observer=t}dispose(){const e=this._subject.observers.indexOf(this._observer);e>-1&&this._subject.observers.splice(e,1),0===this._subject.observers.length&&this._subject.cancelCallback&&this._subject.cancelCallback().catch((e=>{}))}}class It{constructor(e){this._minLevel=e,this.out=console}log(e,t){if(e>=this._minLevel){const n=`[${(new Date).toISOString()}] ${mt[e]}: ${t}`;switch(e){case mt.Critical:case mt.Error:this.out.error(n);break;case mt.Warning:this.out.warn(n);break;case mt.Information:this.out.info(n);break;default:this.out.log(n)}}}}function kt(){let e="X-SignalR-User-Agent";return bt.isNode&&(e="User-Agent"),[e,Tt(wt,xt(),bt.isNode?"NodeJS":"Browser",Dt())]}function Tt(e,t,n,r){let o="Microsoft SignalR/";const i=e.split(".");return o+=`${i[0]}.${i[1]}`,o+=` (${e}; `,o+=t&&""!==t?`${t}; `:"Unknown OS; ",o+=`${n}`,o+=r?`; ${r}`:"; Unknown Runtime Version",o+=")",o}function xt(){if(!bt.isNode)return"";switch(process.platform){case"win32":return"Windows NT";case"darwin":return"macOS";case"linux":return"Linux";default:return process.platform}}function Dt(){if(bt.isNode)return process.versions.node}function Nt(e){return e.stack?e.stack:e.message?e.message:`${e}`}class At extends st{constructor(e){super(),this._logger=e;const t={_fetchType:void 0,_jar:void 0};var r;r=t,"undefined"==typeof fetch&&(r._jar=new(n(628).CookieJar),"undefined"==typeof fetch?r._fetchType=n(200):r._fetchType=fetch,r._fetchType=n(203)(r._fetchType,r._jar),1)?(this._fetchType=t._fetchType,this._jar=t._jar):this._fetchType=fetch.bind(function(){if("undefined"!=typeof globalThis)return globalThis;if("undefined"!=typeof self)return self;if("undefined"!=typeof window)return window;if(void 0!==n.g)return n.g;throw new Error("could not find global")}()),this._abortControllerType=AbortController;const o={_abortControllerType:this._abortControllerType};(function(e){return"undefined"==typeof AbortController&&(e._abortControllerType=n(778),!0)})(o)&&(this._abortControllerType=o._abortControllerType)}async send(e){if(e.abortSignal&&e.abortSignal.aborted)throw new ht;if(!e.method)throw new Error("No method defined.");if(!e.url)throw new Error("No url defined.");const t=new this._abortControllerType;let n;e.abortSignal&&(e.abortSignal.onabort=()=>{t.abort(),n=new ht});let r,o=null;if(e.timeout){const r=e.timeout;o=setTimeout((()=>{t.abort(),this._logger.log(mt.Warning,"Timeout from HTTP request."),n=new lt}),r)}""===e.content&&(e.content=void 0),e.content&&(e.headers=e.headers||{},Et(e.content)?e.headers["Content-Type"]="application/octet-stream":e.headers["Content-Type"]="text/plain;charset=UTF-8");try{r=await this._fetchType(e.url,{body:e.content,cache:"no-cache",credentials:!0===e.withCredentials?"include":"same-origin",headers:{"X-Requested-With":"XMLHttpRequest",...e.headers},method:e.method,mode:"cors",redirect:"follow",signal:t.signal})}catch(e){if(n)throw n;throw this._logger.log(mt.Warning,`Error from HTTP request. ${e}.`),e}finally{o&&clearTimeout(o),e.abortSignal&&(e.abortSignal.onabort=null)}if(!r.ok){const e=await Rt(r,"text");throw new ct(e||r.statusText,r.status)}const i=Rt(r,e.responseType),s=await i;return new it(r.status,r.statusText,s)}getCookieString(e){return""}}function Rt(e,t){let n;switch(t){case"arraybuffer":n=e.arrayBuffer();break;case"text":default:n=e.text();break;case"blob":case"document":case"json":throw new Error(`${t} is not supported.`)}return n}class Pt extends st{constructor(e){super(),this._logger=e}send(e){return e.abortSignal&&e.abortSignal.aborted?Promise.reject(new ht):e.method?e.url?new Promise(((t,n)=>{const r=new XMLHttpRequest;r.open(e.method,e.url,!0),r.withCredentials=void 0===e.withCredentials||e.withCredentials,r.setRequestHeader("X-Requested-With","XMLHttpRequest"),""===e.content&&(e.content=void 0),e.content&&(Et(e.content)?r.setRequestHeader("Content-Type","application/octet-stream"):r.setRequestHeader("Content-Type","text/plain;charset=UTF-8"));const o=e.headers;o&&Object.keys(o).forEach((e=>{r.setRequestHeader(e,o[e])})),e.responseType&&(r.responseType=e.responseType),e.abortSignal&&(e.abortSignal.onabort=()=>{r.abort(),n(new ht)}),e.timeout&&(r.timeout=e.timeout),r.onload=()=>{e.abortSignal&&(e.abortSignal.onabort=null),r.status>=200&&r.status<300?t(new it(r.status,r.statusText,r.response||r.responseText)):n(new ct(r.response||r.responseText||r.statusText,r.status))},r.onerror=()=>{this._logger.log(mt.Warning,`Error from HTTP request. ${r.status}: ${r.statusText}.`),n(new ct(r.statusText,r.status))},r.ontimeout=()=>{this._logger.log(mt.Warning,"Timeout from HTTP request."),n(new lt)},r.send(e.content)})):Promise.reject(new Error("No url defined.")):Promise.reject(new Error("No method defined."))}}class Ut extends st{constructor(e){if(super(),"undefined"!=typeof fetch)this._httpClient=new At(e);else{if("undefined"==typeof XMLHttpRequest)throw new Error("No usable HttpClient found.");this._httpClient=new Pt(e)}}send(e){return e.abortSignal&&e.abortSignal.aborted?Promise.reject(new ht):e.method?e.url?this._httpClient.send(e):Promise.reject(new Error("No url defined.")):Promise.reject(new Error("No method defined."))}getCookieString(e){return this._httpClient.getCookieString(e)}}var Mt,Lt,Bt,Ot;!function(e){e[e.None=0]="None",e[e.WebSockets=1]="WebSockets",e[e.ServerSentEvents=2]="ServerSentEvents",e[e.LongPolling=4]="LongPolling"}(Mt||(Mt={})),function(e){e[e.Text=1]="Text",e[e.Binary=2]="Binary"}(Lt||(Lt={}));class Ft{constructor(){this._isAborted=!1,this.onabort=null}abort(){this._isAborted||(this._isAborted=!0,this.onabort&&this.onabort())}get signal(){return this}get aborted(){return this._isAborted}}class $t{get pollAborted(){return this._pollAbort.aborted}constructor(e,t,n){this._httpClient=e,this._logger=t,this._pollAbort=new Ft,this._options=n,this._running=!1,this.onreceive=null,this.onclose=null}async connect(e,t){if(vt.isRequired(e,"url"),vt.isRequired(t,"transferFormat"),vt.isIn(t,Lt,"transferFormat"),this._url=e,this._logger.log(mt.Trace,"(LongPolling transport) Connecting."),t===Lt.Binary&&"undefined"!=typeof XMLHttpRequest&&"string"!=typeof(new XMLHttpRequest).responseType)throw new Error("Binary protocols over XmlHttpRequest not implementing advanced features are not supported.");const[n,r]=kt(),o={[n]:r,...this._options.headers},i={abortSignal:this._pollAbort.signal,headers:o,timeout:1e5,withCredentials:this._options.withCredentials};t===Lt.Binary&&(i.responseType="arraybuffer");const s=`${e}&_=${Date.now()}`;this._logger.log(mt.Trace,`(LongPolling transport) polling: ${s}.`);const a=await this._httpClient.get(s,i);200!==a.statusCode?(this._logger.log(mt.Error,`(LongPolling transport) Unexpected response code: ${a.statusCode}.`),this._closeError=new ct(a.statusText||"",a.statusCode),this._running=!1):this._running=!0,this._receiving=this._poll(this._url,i)}async _poll(e,t){try{for(;this._running;)try{const n=`${e}&_=${Date.now()}`;this._logger.log(mt.Trace,`(LongPolling transport) polling: ${n}.`);const r=await this._httpClient.get(n,t);204===r.statusCode?(this._logger.log(mt.Information,"(LongPolling transport) Poll terminated by server."),this._running=!1):200!==r.statusCode?(this._logger.log(mt.Error,`(LongPolling transport) Unexpected response code: ${r.statusCode}.`),this._closeError=new ct(r.statusText||"",r.statusCode),this._running=!1):r.content?(this._logger.log(mt.Trace,`(LongPolling transport) data received. ${_t(r.content,this._options.logMessageContent)}.`),this.onreceive&&this.onreceive(r.content)):this._logger.log(mt.Trace,"(LongPolling transport) Poll timed out, reissuing.")}catch(e){this._running?e instanceof lt?this._logger.log(mt.Trace,"(LongPolling transport) Poll timed out, reissuing."):(this._closeError=e,this._running=!1):this._logger.log(mt.Trace,`(LongPolling transport) Poll errored after shutdown: ${e.message}`)}}finally{this._logger.log(mt.Trace,"(LongPolling transport) Polling complete."),this.pollAborted||this._raiseOnClose()}}async send(e){return this._running?St(this._logger,"LongPolling",this._httpClient,this._url,e,this._options):Promise.reject(new Error("Cannot send until the transport is connected"))}async stop(){this._logger.log(mt.Trace,"(LongPolling transport) Stopping polling."),this._running=!1,this._pollAbort.abort();try{await this._receiving,this._logger.log(mt.Trace,`(LongPolling transport) sending DELETE request to ${this._url}.`);const e={},[t,n]=kt();e[t]=n;const r={headers:{...e,...this._options.headers},timeout:this._options.timeout,withCredentials:this._options.withCredentials};let o;try{await this._httpClient.delete(this._url,r)}catch(e){o=e}o?o instanceof ct&&(404===o.statusCode?this._logger.log(mt.Trace,"(LongPolling transport) A 404 response was returned from sending a DELETE request."):this._logger.log(mt.Trace,`(LongPolling transport) Error sending a DELETE request: ${o}`)):this._logger.log(mt.Trace,"(LongPolling transport) DELETE request accepted.")}finally{this._logger.log(mt.Trace,"(LongPolling transport) Stop finished."),this._raiseOnClose()}}_raiseOnClose(){if(this.onclose){let e="(LongPolling transport) Firing onclose event.";this._closeError&&(e+=" Error: "+this._closeError),this._logger.log(mt.Trace,e),this.onclose(this._closeError)}}}class Ht{constructor(e,t,n,r){this._httpClient=e,this._accessToken=t,this._logger=n,this._options=r,this.onreceive=null,this.onclose=null}async connect(e,t){return vt.isRequired(e,"url"),vt.isRequired(t,"transferFormat"),vt.isIn(t,Lt,"transferFormat"),this._logger.log(mt.Trace,"(SSE transport) Connecting."),this._url=e,this._accessToken&&(e+=(e.indexOf("?")<0?"?":"&")+`access_token=${encodeURIComponent(this._accessToken)}`),new Promise(((n,r)=>{let o,i=!1;if(t===Lt.Text){if(bt.isBrowser||bt.isWebWorker)o=new this._options.EventSource(e,{withCredentials:this._options.withCredentials});else{const t=this._httpClient.getCookieString(e),n={};n.Cookie=t;const[r,i]=kt();n[r]=i,o=new this._options.EventSource(e,{withCredentials:this._options.withCredentials,headers:{...n,...this._options.headers}})}try{o.onmessage=e=>{if(this.onreceive)try{this._logger.log(mt.Trace,`(SSE transport) data received. ${_t(e.data,this._options.logMessageContent)}.`),this.onreceive(e.data)}catch(e){return void this._close(e)}},o.onerror=e=>{i?this._close():r(new Error("EventSource failed to connect. The connection could not be found on the server, either the connection ID is not present on the server, or a proxy is refusing/buffering the connection. If you have multiple servers check that sticky sessions are enabled."))},o.onopen=()=>{this._logger.log(mt.Information,`SSE connected to ${this._url}`),this._eventSource=o,i=!0,n()}}catch(e){return void r(e)}}else r(new Error("The Server-Sent Events transport only supports the 'Text' transfer format"))}))}async send(e){return this._eventSource?St(this._logger,"SSE",this._httpClient,this._url,e,this._options):Promise.reject(new Error("Cannot send until the transport is connected"))}stop(){return this._close(),Promise.resolve()}_close(e){this._eventSource&&(this._eventSource.close(),this._eventSource=void 0,this.onclose&&this.onclose(e))}}class jt{constructor(e,t,n,r,o,i){this._logger=n,this._accessTokenFactory=t,this._logMessageContent=r,this._webSocketConstructor=o,this._httpClient=e,this.onreceive=null,this.onclose=null,this._headers=i}async connect(e,t){let n;return vt.isRequired(e,"url"),vt.isRequired(t,"transferFormat"),vt.isIn(t,Lt,"transferFormat"),this._logger.log(mt.Trace,"(WebSockets transport) Connecting."),this._accessTokenFactory&&(n=await this._accessTokenFactory()),new Promise(((r,o)=>{let i;e=e.replace(/^http/,"ws");const s=this._httpClient.getCookieString(e);let a=!1;if(bt.isReactNative){const t={},[r,o]=kt();t[r]=o,n&&(t[ot.Authorization]=`Bearer ${n}`),s&&(t[ot.Cookie]=s),i=new this._webSocketConstructor(e,void 0,{headers:{...t,...this._headers}})}else n&&(e+=(e.indexOf("?")<0?"?":"&")+`access_token=${encodeURIComponent(n)}`);i||(i=new this._webSocketConstructor(e)),t===Lt.Binary&&(i.binaryType="arraybuffer"),i.onopen=t=>{this._logger.log(mt.Information,`WebSocket connected to ${e}.`),this._webSocket=i,a=!0,r()},i.onerror=e=>{let t=null;t="undefined"!=typeof ErrorEvent&&e instanceof ErrorEvent?e.error:"There was an error with the transport",this._logger.log(mt.Information,`(WebSockets transport) ${t}.`)},i.onmessage=e=>{if(this._logger.log(mt.Trace,`(WebSockets transport) data received. ${_t(e.data,this._logMessageContent)}.`),this.onreceive)try{this.onreceive(e.data)}catch(e){return void this._close(e)}},i.onclose=e=>{if(a)this._close(e);else{let t=null;t="undefined"!=typeof ErrorEvent&&e instanceof ErrorEvent?e.error:"WebSocket failed to connect. The connection could not be found on the server, either the endpoint may not be a SignalR endpoint, the connection ID is not present on the server, or there is a proxy blocking WebSockets. If you have multiple servers check that sticky sessions are enabled.",o(new Error(t))}}}))}send(e){return this._webSocket&&this._webSocket.readyState===this._webSocketConstructor.OPEN?(this._logger.log(mt.Trace,`(WebSockets transport) sending data. ${_t(e,this._logMessageContent)}.`),this._webSocket.send(e),Promise.resolve()):Promise.reject("WebSocket is not in the OPEN state")}stop(){return this._webSocket&&this._close(void 0),Promise.resolve()}_close(e){this._webSocket&&(this._webSocket.onclose=()=>{},this._webSocket.onmessage=()=>{},this._webSocket.onerror=()=>{},this._webSocket.close(),this._webSocket=void 0),this._logger.log(mt.Trace,"(WebSockets transport) socket closed."),this.onclose&&(!this._isCloseEvent(e)||!1!==e.wasClean&&1e3===e.code?e instanceof Error?this.onclose(e):this.onclose():this.onclose(new Error(`WebSocket closed with status code: ${e.code} (${e.reason||"no reason given"}).`)))}_isCloseEvent(e){return e&&"boolean"==typeof e.wasClean&&"number"==typeof e.code}}class Wt{constructor(e,t={}){var n;if(this._stopPromiseResolver=()=>{},this.features={},this._negotiateVersion=1,vt.isRequired(e,"url"),this._logger=void 0===(n=t.logger)?new It(mt.Information):null===n?yt.instance:void 0!==n.log?n:new It(n),this.baseUrl=this._resolveUrl(e),(t=t||{}).logMessageContent=void 0!==t.logMessageContent&&t.logMessageContent,"boolean"!=typeof t.withCredentials&&void 0!==t.withCredentials)throw new Error("withCredentials option was not a 'boolean' or 'undefined' value");t.withCredentials=void 0===t.withCredentials||t.withCredentials,t.timeout=void 0===t.timeout?1e5:t.timeout,"undefined"==typeof WebSocket||t.WebSocket||(t.WebSocket=WebSocket),"undefined"==typeof EventSource||t.EventSource||(t.EventSource=EventSource),this._httpClient=new at(t.httpClient||new Ut(this._logger),t.accessTokenFactory),this._connectionState="Disconnected",this._connectionStarted=!1,this._options=t,this.onreceive=null,this.onclose=null}async start(e){if(e=e||Lt.Binary,vt.isIn(e,Lt,"transferFormat"),this._logger.log(mt.Debug,`Starting connection with transfer format '${Lt[e]}'.`),"Disconnected"!==this._connectionState)return Promise.reject(new Error("Cannot start an HttpConnection that is not in the 'Disconnected' state."));if(this._connectionState="Connecting",this._startInternalPromise=this._startInternal(e),await this._startInternalPromise,"Disconnecting"===this._connectionState){const e="Failed to start the HttpConnection before stop() was called.";return this._logger.log(mt.Error,e),await this._stopPromise,Promise.reject(new ht(e))}if("Connected"!==this._connectionState){const e="HttpConnection.startInternal completed gracefully but didn't enter the connection into the connected state!";return this._logger.log(mt.Error,e),Promise.reject(new ht(e))}this._connectionStarted=!0}send(e){return"Connected"!==this._connectionState?Promise.reject(new Error("Cannot send data if the connection is not in the 'Connected' State.")):(this._sendQueue||(this._sendQueue=new zt(this.transport)),this._sendQueue.send(e))}async stop(e){return"Disconnected"===this._connectionState?(this._logger.log(mt.Debug,`Call to HttpConnection.stop(${e}) ignored because the connection is already in the disconnected state.`),Promise.resolve()):"Disconnecting"===this._connectionState?(this._logger.log(mt.Debug,`Call to HttpConnection.stop(${e}) ignored because the connection is already in the disconnecting state.`),this._stopPromise):(this._connectionState="Disconnecting",this._stopPromise=new Promise((e=>{this._stopPromiseResolver=e})),await this._stopInternal(e),void await this._stopPromise)}async _stopInternal(e){this._stopError=e;try{await this._startInternalPromise}catch(e){}if(this.transport){try{await this.transport.stop()}catch(e){this._logger.log(mt.Error,`HttpConnection.transport.stop() threw error '${e}'.`),this._stopConnection()}this.transport=void 0}else this._logger.log(mt.Debug,"HttpConnection.transport is undefined in HttpConnection.stop() because start() failed.")}async _startInternal(e){let t=this.baseUrl;this._accessTokenFactory=this._options.accessTokenFactory,this._httpClient._accessTokenFactory=this._accessTokenFactory;try{if(this._options.skipNegotiation){if(this._options.transport!==Mt.WebSockets)throw new Error("Negotiation can only be skipped when using the WebSocket transport directly.");this.transport=this._constructTransport(Mt.WebSockets),await this._startTransport(t,e)}else{let n=null,r=0;do{if(n=await this._getNegotiationResponse(t),"Disconnecting"===this._connectionState||"Disconnected"===this._connectionState)throw new ht("The connection was stopped during negotiation.");if(n.error)throw new Error(n.error);if(n.ProtocolVersion)throw new Error("Detected a connection attempt to an ASP.NET SignalR Server. This client only supports connecting to an ASP.NET Core SignalR Server. See https://aka.ms/signalr-core-differences for details.");if(n.url&&(t=n.url),n.accessToken){const e=n.accessToken;this._accessTokenFactory=()=>e,this._httpClient._accessToken=e,this._httpClient._accessTokenFactory=void 0}r++}while(n.url&&r<100);if(100===r&&n.url)throw new Error("Negotiate redirection limit exceeded.");await this._createTransport(t,this._options.transport,n,e)}this.transport instanceof $t&&(this.features.inherentKeepAlive=!0),"Connecting"===this._connectionState&&(this._logger.log(mt.Debug,"The HttpConnection connected successfully."),this._connectionState="Connected")}catch(e){return this._logger.log(mt.Error,"Failed to start the connection: "+e),this._connectionState="Disconnected",this.transport=void 0,this._stopPromiseResolver(),Promise.reject(e)}}async _getNegotiationResponse(e){const t={},[n,r]=kt();t[n]=r;const o=this._resolveNegotiateUrl(e);this._logger.log(mt.Debug,`Sending negotiation request: ${o}.`);try{const e=await this._httpClient.post(o,{content:"",headers:{...t,...this._options.headers},timeout:this._options.timeout,withCredentials:this._options.withCredentials});if(200!==e.statusCode)return Promise.reject(new Error(`Unexpected status code returned from negotiate '${e.statusCode}'`));const n=JSON.parse(e.content);return(!n.negotiateVersion||n.negotiateVersion<1)&&(n.connectionToken=n.connectionId),n}catch(e){let t="Failed to complete negotiation with the server: "+e;return e instanceof ct&&404===e.statusCode&&(t+=" Either this is not a SignalR endpoint or there is a proxy blocking the connection."),this._logger.log(mt.Error,t),Promise.reject(new ft(t))}}_createConnectUrl(e,t){return t?e+(-1===e.indexOf("?")?"?":"&")+`id=${t}`:e}async _createTransport(e,t,n,r){let o=this._createConnectUrl(e,n.connectionToken);if(this._isITransport(t))return this._logger.log(mt.Debug,"Connection was provided an instance of ITransport, using that directly."),this.transport=t,await this._startTransport(o,r),void(this.connectionId=n.connectionId);const i=[],s=n.availableTransports||[];let a=n;for(const n of s){const s=this._resolveTransportOrError(n,t,r);if(s instanceof Error)i.push(`${n.transport} failed:`),i.push(s);else if(this._isITransport(s)){if(this.transport=s,!a){try{a=await this._getNegotiationResponse(e)}catch(e){return Promise.reject(e)}o=this._createConnectUrl(e,a.connectionToken)}try{return await this._startTransport(o,r),void(this.connectionId=a.connectionId)}catch(e){if(this._logger.log(mt.Error,`Failed to start the transport '${n.transport}': ${e}`),a=void 0,i.push(new pt(`${n.transport} failed: ${e}`,Mt[n.transport])),"Connecting"!==this._connectionState){const e="Failed to select transport before stop() was called.";return this._logger.log(mt.Debug,e),Promise.reject(new ht(e))}}}}return i.length>0?Promise.reject(new gt(`Unable to connect to the server with any of the available transports. ${i.join(" ")}`,i)):Promise.reject(new Error("None of the transports supported by the client are supported by the server."))}_constructTransport(e){switch(e){case Mt.WebSockets:if(!this._options.WebSocket)throw new Error("'WebSocket' is not supported in your environment.");return new jt(this._httpClient,this._accessTokenFactory,this._logger,this._options.logMessageContent,this._options.WebSocket,this._options.headers||{});case Mt.ServerSentEvents:if(!this._options.EventSource)throw new Error("'EventSource' is not supported in your environment.");return new Ht(this._httpClient,this._httpClient._accessToken,this._logger,this._options);case Mt.LongPolling:return new $t(this._httpClient,this._logger,this._options);default:throw new Error(`Unknown transport: ${e}.`)}}_startTransport(e,t){return this.transport.onreceive=this.onreceive,this.transport.onclose=e=>this._stopConnection(e),this.transport.connect(e,t)}_resolveTransportOrError(e,t,n){const r=Mt[e.transport];if(null==r)return this._logger.log(mt.Debug,`Skipping transport '${e.transport}' because it is not supported by this client.`),new Error(`Skipping transport '${e.transport}' because it is not supported by this client.`);if(!function(e,t){return!e||0!=(t&e)}(t,r))return this._logger.log(mt.Debug,`Skipping transport '${Mt[r]}' because it was disabled by the client.`),new ut(`'${Mt[r]}' is disabled by the client.`,r);if(!(e.transferFormats.map((e=>Lt[e])).indexOf(n)>=0))return this._logger.log(mt.Debug,`Skipping transport '${Mt[r]}' because it does not support the requested transfer format '${Lt[n]}'.`),new Error(`'${Mt[r]}' does not support ${Lt[n]}.`);if(r===Mt.WebSockets&&!this._options.WebSocket||r===Mt.ServerSentEvents&&!this._options.EventSource)return this._logger.log(mt.Debug,`Skipping transport '${Mt[r]}' because it is not supported in your environment.'`),new dt(`'${Mt[r]}' is not supported in your environment.`,r);this._logger.log(mt.Debug,`Selecting transport '${Mt[r]}'.`);try{return this._constructTransport(r)}catch(e){return e}}_isITransport(e){return e&&"object"==typeof e&&"connect"in e}_stopConnection(e){if(this._logger.log(mt.Debug,`HttpConnection.stopConnection(${e}) called while in state ${this._connectionState}.`),this.transport=void 0,e=this._stopError||e,this._stopError=void 0,"Disconnected"!==this._connectionState){if("Connecting"===this._connectionState)throw this._logger.log(mt.Warning,`Call to HttpConnection.stopConnection(${e}) was ignored because the connection is still in the connecting state.`),new Error(`HttpConnection.stopConnection(${e}) was called while the connection is still in the connecting state.`);if("Disconnecting"===this._connectionState&&this._stopPromiseResolver(),e?this._logger.log(mt.Error,`Connection disconnected with error '${e}'.`):this._logger.log(mt.Information,"Connection disconnected."),this._sendQueue&&(this._sendQueue.stop().catch((e=>{this._logger.log(mt.Error,`TransportSendQueue.stop() threw error '${e}'.`)})),this._sendQueue=void 0),this.connectionId=void 0,this._connectionState="Disconnected",this._connectionStarted){this._connectionStarted=!1;try{this.onclose&&this.onclose(e)}catch(t){this._logger.log(mt.Error,`HttpConnection.onclose(${e}) threw error '${t}'.`)}}}else this._logger.log(mt.Debug,`Call to HttpConnection.stopConnection(${e}) was ignored because the connection is already in the disconnected state.`)}_resolveUrl(e){if(0===e.lastIndexOf("https://",0)||0===e.lastIndexOf("http://",0))return e;if(!bt.isBrowser)throw new Error(`Cannot resolve '${e}'.`);const t=window.document.createElement("a");return t.href=e,this._logger.log(mt.Information,`Normalizing '${e}' to '${t.href}'.`),t.href}_resolveNegotiateUrl(e){const t=e.indexOf("?");let n=e.substring(0,-1===t?e.length:t);return"/"!==n[n.length-1]&&(n+="/"),n+="negotiate",n+=-1===t?"":e.substring(t),-1===n.indexOf("negotiateVersion")&&(n+=-1===t?"?":"&",n+="negotiateVersion="+this._negotiateVersion),n}}class zt{constructor(e){this._transport=e,this._buffer=[],this._executing=!0,this._sendBufferedData=new Jt,this._transportResult=new Jt,this._sendLoopPromise=this._sendLoop()}send(e){return this._bufferData(e),this._transportResult||(this._transportResult=new Jt),this._transportResult.promise}stop(){return this._executing=!1,this._sendBufferedData.resolve(),this._sendLoopPromise}_bufferData(e){if(this._buffer.length&&typeof this._buffer[0]!=typeof e)throw new Error(`Expected data to be of type ${typeof this._buffer} but was of type ${typeof e}`);this._buffer.push(e),this._sendBufferedData.resolve()}async _sendLoop(){for(;;){if(await this._sendBufferedData.promise,!this._executing){this._transportResult&&this._transportResult.reject("Connection stopped.");break}this._sendBufferedData=new Jt;const e=this._transportResult;this._transportResult=void 0;const t="string"==typeof this._buffer[0]?this._buffer.join(""):zt._concatBuffers(this._buffer);this._buffer.length=0;try{await this._transport.send(t),e.resolve()}catch(t){e.reject(t)}}}static _concatBuffers(e){const t=e.map((e=>e.byteLength)).reduce(((e,t)=>e+t)),n=new Uint8Array(t);let r=0;for(const t of e)n.set(new Uint8Array(t),r),r+=t.byteLength;return n.buffer}}class Jt{constructor(){this.promise=new Promise(((e,t)=>[this._resolver,this._rejecter]=[e,t]))}resolve(){this._resolver()}reject(e){this._rejecter(e)}}class qt{static write(e){return`${e}${qt.RecordSeparator}`}static parse(e){if(e[e.length-1]!==qt.RecordSeparator)throw new Error("Message is incomplete.");const t=e.split(qt.RecordSeparator);return t.pop(),t}}qt.RecordSeparatorCode=30,qt.RecordSeparator=String.fromCharCode(qt.RecordSeparatorCode);class Kt{writeHandshakeRequest(e){return qt.write(JSON.stringify(e))}parseHandshakeResponse(e){let t,n;if(Et(e)){const r=new Uint8Array(e),o=r.indexOf(qt.RecordSeparatorCode);if(-1===o)throw new Error("Message is incomplete.");const i=o+1;t=String.fromCharCode.apply(null,Array.prototype.slice.call(r.slice(0,i))),n=r.byteLength>i?r.slice(i).buffer:null}else{const r=e,o=r.indexOf(qt.RecordSeparator);if(-1===o)throw new Error("Message is incomplete.");const i=o+1;t=r.substring(0,i),n=r.length>i?r.substring(i):null}const r=qt.parse(t),o=JSON.parse(r[0]);if(o.type)throw new Error("Expected a handshake response from the server.");return[n,o]}}!function(e){e[e.Invocation=1]="Invocation",e[e.StreamItem=2]="StreamItem",e[e.Completion=3]="Completion",e[e.StreamInvocation=4]="StreamInvocation",e[e.CancelInvocation=5]="CancelInvocation",e[e.Ping=6]="Ping",e[e.Close=7]="Close"}(Bt||(Bt={}));class Vt{constructor(){this.observers=[]}next(e){for(const t of this.observers)t.next(e)}error(e){for(const t of this.observers)t.error&&t.error(e)}complete(){for(const e of this.observers)e.complete&&e.complete()}subscribe(e){return this.observers.push(e),new Ct(this,e)}}!function(e){e.Disconnected="Disconnected",e.Connecting="Connecting",e.Connected="Connected",e.Disconnecting="Disconnecting",e.Reconnecting="Reconnecting"}(Ot||(Ot={}));class Xt{static create(e,t,n,r,o,i){return new Xt(e,t,n,r,o,i)}constructor(e,t,n,r,o,i){this._nextKeepAlive=0,this._freezeEventListener=()=>{this._logger.log(mt.Warning,"The page is being frozen, this will likely lead to the connection being closed and messages being lost. For more information see the docs at https://learn.microsoft.com/aspnet/core/signalr/javascript-client#bsleep")},vt.isRequired(e,"connection"),vt.isRequired(t,"logger"),vt.isRequired(n,"protocol"),this.serverTimeoutInMilliseconds=null!=o?o:3e4,this.keepAliveIntervalInMilliseconds=null!=i?i:15e3,this._logger=t,this._protocol=n,this.connection=e,this._reconnectPolicy=r,this._handshakeProtocol=new Kt,this.connection.onreceive=e=>this._processIncomingData(e),this.connection.onclose=e=>this._connectionClosed(e),this._callbacks={},this._methods={},this._closedCallbacks=[],this._reconnectingCallbacks=[],this._reconnectedCallbacks=[],this._invocationId=0,this._receivedHandshakeResponse=!1,this._connectionState=Ot.Disconnected,this._connectionStarted=!1,this._cachedPingMessage=this._protocol.writeMessage({type:Bt.Ping})}get state(){return this._connectionState}get connectionId(){return this.connection&&this.connection.connectionId||null}get baseUrl(){return this.connection.baseUrl||""}set baseUrl(e){if(this._connectionState!==Ot.Disconnected&&this._connectionState!==Ot.Reconnecting)throw new Error("The HubConnection must be in the Disconnected or Reconnecting state to change the url.");if(!e)throw new Error("The HubConnection url must be a valid url.");this.connection.baseUrl=e}start(){return this._startPromise=this._startWithStateTransitions(),this._startPromise}async _startWithStateTransitions(){if(this._connectionState!==Ot.Disconnected)return Promise.reject(new Error("Cannot start a HubConnection that is not in the 'Disconnected' state."));this._connectionState=Ot.Connecting,this._logger.log(mt.Debug,"Starting HubConnection.");try{await this._startInternal(),bt.isBrowser&&window.document.addEventListener("freeze",this._freezeEventListener),this._connectionState=Ot.Connected,this._connectionStarted=!0,this._logger.log(mt.Debug,"HubConnection connected successfully.")}catch(e){return this._connectionState=Ot.Disconnected,this._logger.log(mt.Debug,`HubConnection failed to start successfully because of error '${e}'.`),Promise.reject(e)}}async _startInternal(){this._stopDuringStartError=void 0,this._receivedHandshakeResponse=!1;const e=new Promise(((e,t)=>{this._handshakeResolver=e,this._handshakeRejecter=t}));await this.connection.start(this._protocol.transferFormat);try{const t={protocol:this._protocol.name,version:this._protocol.version};if(this._logger.log(mt.Debug,"Sending handshake request."),await this._sendMessage(this._handshakeProtocol.writeHandshakeRequest(t)),this._logger.log(mt.Information,`Using HubProtocol '${this._protocol.name}'.`),this._cleanupTimeout(),this._resetTimeoutPeriod(),this._resetKeepAliveInterval(),await e,this._stopDuringStartError)throw this._stopDuringStartError;this.connection.features.inherentKeepAlive||await this._sendMessage(this._cachedPingMessage)}catch(e){throw this._logger.log(mt.Debug,`Hub handshake failed with error '${e}' during start(). Stopping HubConnection.`),this._cleanupTimeout(),this._cleanupPingTimer(),await this.connection.stop(e),e}}async stop(){const e=this._startPromise;this._stopPromise=this._stopInternal(),await this._stopPromise;try{await e}catch(e){}}_stopInternal(e){if(this._connectionState===Ot.Disconnected)return this._logger.log(mt.Debug,`Call to HubConnection.stop(${e}) ignored because it is already in the disconnected state.`),Promise.resolve();if(this._connectionState===Ot.Disconnecting)return this._logger.log(mt.Debug,`Call to HttpConnection.stop(${e}) ignored because the connection is already in the disconnecting state.`),this._stopPromise;const t=this._connectionState;return this._connectionState=Ot.Disconnecting,this._logger.log(mt.Debug,"Stopping HubConnection."),this._reconnectDelayHandle?(this._logger.log(mt.Debug,"Connection stopped during reconnect delay. Done reconnecting."),clearTimeout(this._reconnectDelayHandle),this._reconnectDelayHandle=void 0,this._completeClose(),Promise.resolve()):(t===Ot.Connected&&this._sendCloseMessage(),this._cleanupTimeout(),this._cleanupPingTimer(),this._stopDuringStartError=e||new ht("The connection was stopped before the hub handshake could complete."),this.connection.stop(e))}async _sendCloseMessage(){try{await this._sendWithProtocol(this._createCloseMessage())}catch{}}stream(e,...t){const[n,r]=this._replaceStreamingParams(t),o=this._createStreamInvocation(e,t,r);let i;const s=new Vt;return s.cancelCallback=()=>{const e=this._createCancelInvocation(o.invocationId);return delete this._callbacks[o.invocationId],i.then((()=>this._sendWithProtocol(e)))},this._callbacks[o.invocationId]=(e,t)=>{t?s.error(t):e&&(e.type===Bt.Completion?e.error?s.error(new Error(e.error)):s.complete():s.next(e.item))},i=this._sendWithProtocol(o).catch((e=>{s.error(e),delete this._callbacks[o.invocationId]})),this._launchStreams(n,i),s}_sendMessage(e){return this._resetKeepAliveInterval(),this.connection.send(e)}_sendWithProtocol(e){return this._sendMessage(this._protocol.writeMessage(e))}send(e,...t){const[n,r]=this._replaceStreamingParams(t),o=this._sendWithProtocol(this._createInvocation(e,t,!0,r));return this._launchStreams(n,o),o}invoke(e,...t){const[n,r]=this._replaceStreamingParams(t),o=this._createInvocation(e,t,!1,r);return new Promise(((e,t)=>{this._callbacks[o.invocationId]=(n,r)=>{r?t(r):n&&(n.type===Bt.Completion?n.error?t(new Error(n.error)):e(n.result):t(new Error(`Unexpected message type: ${n.type}`)))};const r=this._sendWithProtocol(o).catch((e=>{t(e),delete this._callbacks[o.invocationId]}));this._launchStreams(n,r)}))}on(e,t){e&&t&&(e=e.toLowerCase(),this._methods[e]||(this._methods[e]=[]),-1===this._methods[e].indexOf(t)&&this._methods[e].push(t))}off(e,t){if(!e)return;e=e.toLowerCase();const n=this._methods[e];if(n)if(t){const r=n.indexOf(t);-1!==r&&(n.splice(r,1),0===n.length&&delete this._methods[e])}else delete this._methods[e]}onclose(e){e&&this._closedCallbacks.push(e)}onreconnecting(e){e&&this._reconnectingCallbacks.push(e)}onreconnected(e){e&&this._reconnectedCallbacks.push(e)}_processIncomingData(e){if(this._cleanupTimeout(),this._receivedHandshakeResponse||(e=this._processHandshakeResponse(e),this._receivedHandshakeResponse=!0),e){const t=this._protocol.parseMessages(e,this._logger);for(const e of t)switch(e.type){case Bt.Invocation:this._invokeClientMethod(e);break;case Bt.StreamItem:case Bt.Completion:{const t=this._callbacks[e.invocationId];if(t){e.type===Bt.Completion&&delete this._callbacks[e.invocationId];try{t(e)}catch(e){this._logger.log(mt.Error,`Stream callback threw error: ${Nt(e)}`)}}break}case Bt.Ping:break;case Bt.Close:{this._logger.log(mt.Information,"Close message received from server.");const t=e.error?new Error("Server returned an error on close: "+e.error):void 0;!0===e.allowReconnect?this.connection.stop(t):this._stopPromise=this._stopInternal(t);break}default:this._logger.log(mt.Warning,`Invalid message type: ${e.type}.`)}}this._resetTimeoutPeriod()}_processHandshakeResponse(e){let t,n;try{[n,t]=this._handshakeProtocol.parseHandshakeResponse(e)}catch(e){const t="Error parsing handshake response: "+e;this._logger.log(mt.Error,t);const n=new Error(t);throw this._handshakeRejecter(n),n}if(t.error){const e="Server returned handshake error: "+t.error;this._logger.log(mt.Error,e);const n=new Error(e);throw this._handshakeRejecter(n),n}return this._logger.log(mt.Debug,"Server handshake complete."),this._handshakeResolver(),n}_resetKeepAliveInterval(){this.connection.features.inherentKeepAlive||(this._nextKeepAlive=(new Date).getTime()+this.keepAliveIntervalInMilliseconds,this._cleanupPingTimer())}_resetTimeoutPeriod(){if(!(this.connection.features&&this.connection.features.inherentKeepAlive||(this._timeoutHandle=setTimeout((()=>this.serverTimeout()),this.serverTimeoutInMilliseconds),void 0!==this._pingServerHandle))){let e=this._nextKeepAlive-(new Date).getTime();e<0&&(e=0),this._pingServerHandle=setTimeout((async()=>{if(this._connectionState===Ot.Connected)try{await this._sendMessage(this._cachedPingMessage)}catch{this._cleanupPingTimer()}}),e)}}serverTimeout(){this.connection.stop(new Error("Server timeout elapsed without receiving a message from the server."))}async _invokeClientMethod(e){const t=e.target.toLowerCase(),n=this._methods[t];if(!n)return this._logger.log(mt.Warning,`No client method with the name '${t}' found.`),void(e.invocationId&&(this._logger.log(mt.Warning,`No result given for '${t}' method and invocation ID '${e.invocationId}'.`),await this._sendWithProtocol(this._createCompletionMessage(e.invocationId,"Client didn't provide a result.",null))));const r=n.slice(),o=!!e.invocationId;let i,s,a;for(const n of r)try{const r=i;i=await n.apply(this,e.arguments),o&&i&&r&&(this._logger.log(mt.Error,`Multiple results provided for '${t}'. Sending error to server.`),a=this._createCompletionMessage(e.invocationId,"Client provided multiple results.",null)),s=void 0}catch(e){s=e,this._logger.log(mt.Error,`A callback for the method '${t}' threw error '${e}'.`)}a?await this._sendWithProtocol(a):o?(s?a=this._createCompletionMessage(e.invocationId,`${s}`,null):void 0!==i?a=this._createCompletionMessage(e.invocationId,null,i):(this._logger.log(mt.Warning,`No result given for '${t}' method and invocation ID '${e.invocationId}'.`),a=this._createCompletionMessage(e.invocationId,"Client didn't provide a result.",null)),await this._sendWithProtocol(a)):i&&this._logger.log(mt.Error,`Result given for '${t}' method but server is not expecting a result.`)}_connectionClosed(e){this._logger.log(mt.Debug,`HubConnection.connectionClosed(${e}) called while in state ${this._connectionState}.`),this._stopDuringStartError=this._stopDuringStartError||e||new ht("The underlying connection was closed before the hub handshake could complete."),this._handshakeResolver&&this._handshakeResolver(),this._cancelCallbacksWithError(e||new Error("Invocation canceled due to the underlying connection being closed.")),this._cleanupTimeout(),this._cleanupPingTimer(),this._connectionState===Ot.Disconnecting?this._completeClose(e):this._connectionState===Ot.Connected&&this._reconnectPolicy?this._reconnect(e):this._connectionState===Ot.Connected&&this._completeClose(e)}_completeClose(e){if(this._connectionStarted){this._connectionState=Ot.Disconnected,this._connectionStarted=!1,bt.isBrowser&&window.document.removeEventListener("freeze",this._freezeEventListener);try{this._closedCallbacks.forEach((t=>t.apply(this,[e])))}catch(t){this._logger.log(mt.Error,`An onclose callback called with error '${e}' threw error '${t}'.`)}}}async _reconnect(e){const t=Date.now();let n=0,r=void 0!==e?e:new Error("Attempting to reconnect due to a unknown error."),o=this._getNextRetryDelay(n++,0,r);if(null===o)return this._logger.log(mt.Debug,"Connection not reconnecting because the IRetryPolicy returned null on the first reconnect attempt."),void this._completeClose(e);if(this._connectionState=Ot.Reconnecting,e?this._logger.log(mt.Information,`Connection reconnecting because of error '${e}'.`):this._logger.log(mt.Information,"Connection reconnecting."),0!==this._reconnectingCallbacks.length){try{this._reconnectingCallbacks.forEach((t=>t.apply(this,[e])))}catch(t){this._logger.log(mt.Error,`An onreconnecting callback called with error '${e}' threw error '${t}'.`)}if(this._connectionState!==Ot.Reconnecting)return void this._logger.log(mt.Debug,"Connection left the reconnecting state in onreconnecting callback. Done reconnecting.")}for(;null!==o;){if(this._logger.log(mt.Information,`Reconnect attempt number ${n} will start in ${o} ms.`),await new Promise((e=>{this._reconnectDelayHandle=setTimeout(e,o)})),this._reconnectDelayHandle=void 0,this._connectionState!==Ot.Reconnecting)return void this._logger.log(mt.Debug,"Connection left the reconnecting state during reconnect delay. Done reconnecting.");try{if(await this._startInternal(),this._connectionState=Ot.Connected,this._logger.log(mt.Information,"HubConnection reconnected successfully."),0!==this._reconnectedCallbacks.length)try{this._reconnectedCallbacks.forEach((e=>e.apply(this,[this.connection.connectionId])))}catch(e){this._logger.log(mt.Error,`An onreconnected callback called with connectionId '${this.connection.connectionId}; threw error '${e}'.`)}return}catch(e){if(this._logger.log(mt.Information,`Reconnect attempt failed because of error '${e}'.`),this._connectionState!==Ot.Reconnecting)return this._logger.log(mt.Debug,`Connection moved to the '${this._connectionState}' from the reconnecting state during reconnect attempt. Done reconnecting.`),void(this._connectionState===Ot.Disconnecting&&this._completeClose());r=e instanceof Error?e:new Error(e.toString()),o=this._getNextRetryDelay(n++,Date.now()-t,r)}}this._logger.log(mt.Information,`Reconnect retries have been exhausted after ${Date.now()-t} ms and ${n} failed attempts. Connection disconnecting.`),this._completeClose()}_getNextRetryDelay(e,t,n){try{return this._reconnectPolicy.nextRetryDelayInMilliseconds({elapsedMilliseconds:t,previousRetryCount:e,retryReason:n})}catch(n){return this._logger.log(mt.Error,`IRetryPolicy.nextRetryDelayInMilliseconds(${e}, ${t}) threw error '${n}'.`),null}}_cancelCallbacksWithError(e){const t=this._callbacks;this._callbacks={},Object.keys(t).forEach((n=>{const r=t[n];try{r(null,e)}catch(t){this._logger.log(mt.Error,`Stream 'error' callback called with '${e}' threw error: ${Nt(t)}`)}}))}_cleanupPingTimer(){this._pingServerHandle&&(clearTimeout(this._pingServerHandle),this._pingServerHandle=void 0)}_cleanupTimeout(){this._timeoutHandle&&clearTimeout(this._timeoutHandle)}_createInvocation(e,t,n,r){if(n)return 0!==r.length?{arguments:t,streamIds:r,target:e,type:Bt.Invocation}:{arguments:t,target:e,type:Bt.Invocation};{const n=this._invocationId;return this._invocationId++,0!==r.length?{arguments:t,invocationId:n.toString(),streamIds:r,target:e,type:Bt.Invocation}:{arguments:t,invocationId:n.toString(),target:e,type:Bt.Invocation}}}_launchStreams(e,t){if(0!==e.length){t||(t=Promise.resolve());for(const n in e)e[n].subscribe({complete:()=>{t=t.then((()=>this._sendWithProtocol(this._createCompletionMessage(n))))},error:e=>{let r;r=e instanceof Error?e.message:e&&e.toString?e.toString():"Unknown error",t=t.then((()=>this._sendWithProtocol(this._createCompletionMessage(n,r))))},next:e=>{t=t.then((()=>this._sendWithProtocol(this._createStreamItemMessage(n,e))))}})}}_replaceStreamingParams(e){const t=[],n=[];for(let r=0;r=55296&&o<=56319&&r65535&&(h-=65536,i.push(h>>>10&1023|55296),h=56320|1023&h),i.push(h)}else i.push(a);i.length>=4096&&(s+=String.fromCharCode.apply(String,i),i.length=0)}return i.length>0&&(s+=String.fromCharCode.apply(String,i)),s}var un,pn=sn?new TextDecoder:null,fn=sn?"undefined"!=typeof process&&"force"!==(null===(tn=null===process||void 0===process?void 0:process.env)||void 0===tn?void 0:tn.TEXT_DECODER)?200:0:nn,gn=function(e,t){this.type=e,this.data=t},mn=(un=function(e,t){return un=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=t[n])},un(e,t)},function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");function n(){this.constructor=e}un(e,t),e.prototype=null===t?Object.create(t):(n.prototype=t.prototype,new n)}),yn=function(e){function t(n){var r=e.call(this,n)||this,o=Object.create(t.prototype);return Object.setPrototypeOf(r,o),Object.defineProperty(r,"name",{configurable:!0,enumerable:!1,value:t.name}),r}return mn(t,e),t}(Error),wn={type:-1,encode:function(e){var t,n,r,o;return e instanceof Date?function(e){var t,n=e.sec,r=e.nsec;if(n>=0&&r>=0&&n<=17179869183){if(0===r&&n<=4294967295){var o=new Uint8Array(4);return(t=new DataView(o.buffer)).setUint32(0,n),o}var i=n/4294967296,s=4294967295&n;return o=new Uint8Array(8),(t=new DataView(o.buffer)).setUint32(0,r<<2|3&i),t.setUint32(4,s),o}return o=new Uint8Array(12),(t=new DataView(o.buffer)).setUint32(0,r),rn(t,4,n),o}((r=1e6*((t=e.getTime())-1e3*(n=Math.floor(t/1e3))),{sec:n+(o=Math.floor(r/1e9)),nsec:r-1e9*o})):null},decode:function(e){var t=function(e){var t=new DataView(e.buffer,e.byteOffset,e.byteLength);switch(e.byteLength){case 4:return{sec:t.getUint32(0),nsec:0};case 8:var n=t.getUint32(0);return{sec:4294967296*(3&n)+t.getUint32(4),nsec:n>>>2};case 12:return{sec:on(t,4),nsec:t.getUint32(0)};default:throw new yn("Unrecognized data size for timestamp (expected 4, 8, or 12): ".concat(e.length))}}(e);return new Date(1e3*t.sec+t.nsec/1e6)}},vn=function(){function e(){this.builtInEncoders=[],this.builtInDecoders=[],this.encoders=[],this.decoders=[],this.register(wn)}return e.prototype.register=function(e){var t=e.type,n=e.encode,r=e.decode;if(t>=0)this.encoders[t]=n,this.decoders[t]=r;else{var o=1+t;this.builtInEncoders[o]=n,this.builtInDecoders[o]=r}},e.prototype.tryToEncode=function(e,t){for(var n=0;nthis.maxDepth)throw new Error("Too deep objects in depth ".concat(t));null==e?this.encodeNil():"boolean"==typeof e?this.encodeBoolean(e):"number"==typeof e?this.encodeNumber(e):"string"==typeof e?this.encodeString(e):this.encodeObject(e,t)},e.prototype.ensureBufferSizeToWrite=function(e){var t=this.pos+e;this.view.byteLength=0?e<128?this.writeU8(e):e<256?(this.writeU8(204),this.writeU8(e)):e<65536?(this.writeU8(205),this.writeU16(e)):e<4294967296?(this.writeU8(206),this.writeU32(e)):(this.writeU8(207),this.writeU64(e)):e>=-32?this.writeU8(224|e+32):e>=-128?(this.writeU8(208),this.writeI8(e)):e>=-32768?(this.writeU8(209),this.writeI16(e)):e>=-2147483648?(this.writeU8(210),this.writeI32(e)):(this.writeU8(211),this.writeI64(e)):this.forceFloat32?(this.writeU8(202),this.writeF32(e)):(this.writeU8(203),this.writeF64(e))},e.prototype.writeStringHeader=function(e){if(e<32)this.writeU8(160+e);else if(e<256)this.writeU8(217),this.writeU8(e);else if(e<65536)this.writeU8(218),this.writeU16(e);else{if(!(e<4294967296))throw new Error("Too long string: ".concat(e," bytes in UTF-8"));this.writeU8(219),this.writeU32(e)}},e.prototype.encodeString=function(e){if(e.length>ln){var t=an(e);this.ensureBufferSizeToWrite(5+t),this.writeStringHeader(t),hn(e,this.bytes,this.pos),this.pos+=t}else t=an(e),this.ensureBufferSizeToWrite(5+t),this.writeStringHeader(t),function(e,t,n){for(var r=e.length,o=n,i=0;i>6&31|192;else{if(s>=55296&&s<=56319&&i>12&15|224,t[o++]=s>>6&63|128):(t[o++]=s>>18&7|240,t[o++]=s>>12&63|128,t[o++]=s>>6&63|128)}t[o++]=63&s|128}else t[o++]=s}}(e,this.bytes,this.pos),this.pos+=t},e.prototype.encodeObject=function(e,t){var n=this.extensionCodec.tryToEncode(e,this.context);if(null!=n)this.encodeExtension(n);else if(Array.isArray(e))this.encodeArray(e,t);else if(ArrayBuffer.isView(e))this.encodeBinary(e);else{if("object"!=typeof e)throw new Error("Unrecognized object: ".concat(Object.prototype.toString.apply(e)));this.encodeMap(e,t)}},e.prototype.encodeBinary=function(e){var t=e.byteLength;if(t<256)this.writeU8(196),this.writeU8(t);else if(t<65536)this.writeU8(197),this.writeU16(t);else{if(!(t<4294967296))throw new Error("Too large binary: ".concat(t));this.writeU8(198),this.writeU32(t)}var n=bn(e);this.writeU8a(n)},e.prototype.encodeArray=function(e,t){var n=e.length;if(n<16)this.writeU8(144+n);else if(n<65536)this.writeU8(220),this.writeU16(n);else{if(!(n<4294967296))throw new Error("Too large array: ".concat(n));this.writeU8(221),this.writeU32(n)}for(var r=0,o=e;r0&&e<=this.maxKeyLength},e.prototype.find=function(e,t,n){e:for(var r=0,o=this.caches[n-1];r=this.maxLengthPerKey?n[Math.random()*n.length|0]=r:n.push(r)},e.prototype.decode=function(e,t,n){var r=this.find(e,t,n);if(null!=r)return this.hit++,r;this.miss++;var o=dn(e,t,n),i=Uint8Array.prototype.slice.call(e,t,t+n);return this.store(i,o),o},e}(),Cn=function(e,t){var n,r,o,i,s={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]};return i={next:a(0),throw:a(1),return:a(2)},"function"==typeof Symbol&&(i[Symbol.iterator]=function(){return this}),i;function a(i){return function(a){return function(i){if(n)throw new TypeError("Generator is already executing.");for(;s;)try{if(n=1,r&&(o=2&i[0]?r.return:i[0]?r.throw||((o=r.return)&&o.call(r),0):r.next)&&!(o=o.call(r,i[1])).done)return o;switch(r=0,o&&(i=[2&i[0],o.value]),i[0]){case 0:case 1:o=i;break;case 4:return s.label++,{value:i[1],done:!1};case 5:s.label++,r=i[1],i=[0];continue;case 7:i=s.ops.pop(),s.trys.pop();continue;default:if(!((o=(o=s.trys).length>0&&o[o.length-1])||6!==i[0]&&2!==i[0])){s=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]=e},e.prototype.createExtraByteError=function(e){var t=this.view,n=this.pos;return new RangeError("Extra ".concat(t.byteLength-n," of ").concat(t.byteLength," byte(s) found at buffer[").concat(e,"]"))},e.prototype.decode=function(e){this.reinitializeState(),this.setBuffer(e);var t=this.doDecodeSync();if(this.hasRemaining(1))throw this.createExtraByteError(this.pos);return t},e.prototype.decodeMulti=function(e){return Cn(this,(function(t){switch(t.label){case 0:this.reinitializeState(),this.setBuffer(e),t.label=1;case 1:return this.hasRemaining(1)?[4,this.doDecodeSync()]:[3,3];case 2:return t.sent(),[3,1];case 3:return[2]}}))},e.prototype.decodeAsync=function(e){var t,n,r,o,i,s,a;return i=this,void 0,a=function(){var i,s,a,c,l,h,d,u;return Cn(this,(function(p){switch(p.label){case 0:i=!1,p.label=1;case 1:p.trys.push([1,6,7,12]),t=In(e),p.label=2;case 2:return[4,t.next()];case 3:if((n=p.sent()).done)return[3,5];if(a=n.value,i)throw this.createExtraByteError(this.totalPos);this.appendBuffer(a);try{s=this.doDecodeSync(),i=!0}catch(e){if(!(e instanceof Dn))throw e}this.totalPos+=this.pos,p.label=4;case 4:return[3,2];case 5:return[3,12];case 6:return c=p.sent(),r={error:c},[3,12];case 7:return p.trys.push([7,,10,11]),n&&!n.done&&(o=t.return)?[4,o.call(t)]:[3,9];case 8:p.sent(),p.label=9;case 9:return[3,11];case 10:if(r)throw r.error;return[7];case 11:return[7];case 12:if(i){if(this.hasRemaining(1))throw this.createExtraByteError(this.totalPos);return[2,s]}throw h=(l=this).headByte,d=l.pos,u=l.totalPos,new RangeError("Insufficient data in parsing ".concat(En(h)," at ").concat(u," (").concat(d," in the current buffer)"))}}))},new((s=void 0)||(s=Promise))((function(e,t){function n(e){try{o(a.next(e))}catch(e){t(e)}}function r(e){try{o(a.throw(e))}catch(e){t(e)}}function o(t){var o;t.done?e(t.value):(o=t.value,o instanceof s?o:new s((function(e){e(o)}))).then(n,r)}o((a=a.apply(i,[])).next())}))},e.prototype.decodeArrayStream=function(e){return this.decodeMultiAsync(e,!0)},e.prototype.decodeStream=function(e){return this.decodeMultiAsync(e,!1)},e.prototype.decodeMultiAsync=function(e,t){return function(n,r,o){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var i,s=function(){var n,r,o,i,s,a,c,l,h;return Cn(this,(function(d){switch(d.label){case 0:n=t,r=-1,d.label=1;case 1:d.trys.push([1,13,14,19]),o=In(e),d.label=2;case 2:return[4,kn(o.next())];case 3:if((i=d.sent()).done)return[3,12];if(s=i.value,t&&0===r)throw this.createExtraByteError(this.totalPos);this.appendBuffer(s),n&&(r=this.readArraySize(),n=!1,this.complete()),d.label=4;case 4:d.trys.push([4,9,,10]),d.label=5;case 5:return[4,kn(this.doDecodeSync())];case 6:return[4,d.sent()];case 7:return d.sent(),0==--r?[3,8]:[3,5];case 8:return[3,10];case 9:if(!((a=d.sent())instanceof Dn))throw a;return[3,10];case 10:this.totalPos+=this.pos,d.label=11;case 11:return[3,2];case 12:return[3,19];case 13:return c=d.sent(),l={error:c},[3,19];case 14:return d.trys.push([14,,17,18]),i&&!i.done&&(h=o.return)?[4,kn(h.call(o))]:[3,16];case 15:d.sent(),d.label=16;case 16:return[3,18];case 17:if(l)throw l.error;return[7];case 18:return[7];case 19:return[2]}}))}.apply(n,r||[]),a=[];return i={},c("next"),c("throw"),c("return"),i[Symbol.asyncIterator]=function(){return this},i;function c(e){s[e]&&(i[e]=function(t){return new Promise((function(n,r){a.push([e,t,n,r])>1||l(e,t)}))})}function l(e,t){try{(n=s[e](t)).value instanceof kn?Promise.resolve(n.value.v).then(h,d):u(a[0][2],n)}catch(e){u(a[0][3],e)}var n}function h(e){l("next",e)}function d(e){l("throw",e)}function u(e,t){e(t),a.shift(),a.length&&l(a[0][0],a[0][1])}}(this,arguments)},e.prototype.doDecodeSync=function(){e:for(;;){var e=this.readHeadByte(),t=void 0;if(e>=224)t=e-256;else if(e<192)if(e<128)t=e;else if(e<144){if(0!=(r=e-128)){this.pushMapState(r),this.complete();continue e}t={}}else if(e<160){if(0!=(r=e-144)){this.pushArrayState(r),this.complete();continue e}t=[]}else{var n=e-160;t=this.decodeUtf8String(n,0)}else if(192===e)t=null;else if(194===e)t=!1;else if(195===e)t=!0;else if(202===e)t=this.readF32();else if(203===e)t=this.readF64();else if(204===e)t=this.readU8();else if(205===e)t=this.readU16();else if(206===e)t=this.readU32();else if(207===e)t=this.readU64();else if(208===e)t=this.readI8();else if(209===e)t=this.readI16();else if(210===e)t=this.readI32();else if(211===e)t=this.readI64();else if(217===e)n=this.lookU8(),t=this.decodeUtf8String(n,1);else if(218===e)n=this.lookU16(),t=this.decodeUtf8String(n,2);else if(219===e)n=this.lookU32(),t=this.decodeUtf8String(n,4);else if(220===e){if(0!==(r=this.readU16())){this.pushArrayState(r),this.complete();continue e}t=[]}else if(221===e){if(0!==(r=this.readU32())){this.pushArrayState(r),this.complete();continue e}t=[]}else if(222===e){if(0!==(r=this.readU16())){this.pushMapState(r),this.complete();continue e}t={}}else if(223===e){if(0!==(r=this.readU32())){this.pushMapState(r),this.complete();continue e}t={}}else if(196===e){var r=this.lookU8();t=this.decodeBinary(r,1)}else if(197===e)r=this.lookU16(),t=this.decodeBinary(r,2);else if(198===e)r=this.lookU32(),t=this.decodeBinary(r,4);else if(212===e)t=this.decodeExtension(1,0);else if(213===e)t=this.decodeExtension(2,0);else if(214===e)t=this.decodeExtension(4,0);else if(215===e)t=this.decodeExtension(8,0);else if(216===e)t=this.decodeExtension(16,0);else if(199===e)r=this.lookU8(),t=this.decodeExtension(r,1);else if(200===e)r=this.lookU16(),t=this.decodeExtension(r,2);else{if(201!==e)throw new yn("Unrecognized type byte: ".concat(En(e)));r=this.lookU32(),t=this.decodeExtension(r,4)}this.complete();for(var o=this.stack;o.length>0;){var i=o[o.length-1];if(0===i.type){if(i.array[i.position]=t,i.position++,i.position!==i.size)continue e;o.pop(),t=i.array}else{if(1===i.type){if("string"!=(s=typeof t)&&"number"!==s)throw new yn("The type of key must be string or number but "+typeof t);if("__proto__"===t)throw new yn("The key __proto__ is not allowed");i.key=t,i.type=2;continue e}if(i.map[i.key]=t,i.readCount++,i.readCount!==i.size){i.key=null,i.type=1;continue e}o.pop(),t=i.map}}return t}var s},e.prototype.readHeadByte=function(){return-1===this.headByte&&(this.headByte=this.readU8()),this.headByte},e.prototype.complete=function(){this.headByte=-1},e.prototype.readArraySize=function(){var e=this.readHeadByte();switch(e){case 220:return this.readU16();case 221:return this.readU32();default:if(e<160)return e-144;throw new yn("Unrecognized array type byte: ".concat(En(e)))}},e.prototype.pushMapState=function(e){if(e>this.maxMapLength)throw new yn("Max length exceeded: map length (".concat(e,") > maxMapLengthLength (").concat(this.maxMapLength,")"));this.stack.push({type:1,size:e,key:null,readCount:0,map:{}})},e.prototype.pushArrayState=function(e){if(e>this.maxArrayLength)throw new yn("Max length exceeded: array length (".concat(e,") > maxArrayLength (").concat(this.maxArrayLength,")"));this.stack.push({type:0,size:e,array:new Array(e),position:0})},e.prototype.decodeUtf8String=function(e,t){var n;if(e>this.maxStrLength)throw new yn("Max length exceeded: UTF-8 byte length (".concat(e,") > maxStrLength (").concat(this.maxStrLength,")"));if(this.bytes.byteLengthfn?function(e,t,n){var r=e.subarray(t,t+n);return pn.decode(r)}(this.bytes,o,e):dn(this.bytes,o,e),this.pos+=t+e,r},e.prototype.stateIsMapKey=function(){return this.stack.length>0&&1===this.stack[this.stack.length-1].type},e.prototype.decodeBinary=function(e,t){if(e>this.maxBinLength)throw new yn("Max length exceeded: bin length (".concat(e,") > maxBinLength (").concat(this.maxBinLength,")"));if(!this.hasRemaining(e+t))throw Nn;var n=this.pos+t,r=this.bytes.subarray(n,n+e);return this.pos+=t+e,r},e.prototype.decodeExtension=function(e,t){if(e>this.maxExtLength)throw new yn("Max length exceeded: ext length (".concat(e,") > maxExtLength (").concat(this.maxExtLength,")"));var n=this.view.getInt8(this.pos+t),r=this.decodeBinary(e,t+1);return this.extensionCodec.decode(r,n,this.context)},e.prototype.lookU8=function(){return this.view.getUint8(this.pos)},e.prototype.lookU16=function(){return this.view.getUint16(this.pos)},e.prototype.lookU32=function(){return this.view.getUint32(this.pos)},e.prototype.readU8=function(){var e=this.view.getUint8(this.pos);return this.pos++,e},e.prototype.readI8=function(){var e=this.view.getInt8(this.pos);return this.pos++,e},e.prototype.readU16=function(){var e=this.view.getUint16(this.pos);return this.pos+=2,e},e.prototype.readI16=function(){var e=this.view.getInt16(this.pos);return this.pos+=2,e},e.prototype.readU32=function(){var e=this.view.getUint32(this.pos);return this.pos+=4,e},e.prototype.readI32=function(){var e=this.view.getInt32(this.pos);return this.pos+=4,e},e.prototype.readU64=function(){var e,t,n=(e=this.view,t=this.pos,4294967296*e.getUint32(t)+e.getUint32(t+4));return this.pos+=8,n},e.prototype.readI64=function(){var e=on(this.view,this.pos);return this.pos+=8,e},e.prototype.readF32=function(){var e=this.view.getFloat32(this.pos);return this.pos+=4,e},e.prototype.readF64=function(){var e=this.view.getFloat64(this.pos);return this.pos+=8,e},e}();class Pn{static write(e){let t=e.byteLength||e.length;const n=[];do{let e=127&t;t>>=7,t>0&&(e|=128),n.push(e)}while(t>0);t=e.byteLength||e.length;const r=new Uint8Array(n.length+t);return r.set(n,0),r.set(e,n.length),r.buffer}static parse(e){const t=[],n=new Uint8Array(e),r=[0,7,14,21,28];for(let o=0;o7)throw new Error("Messages bigger than 2GB are not supported.");if(!(n.byteLength>=o+s+a))throw new Error("Incomplete message.");t.push(n.slice?n.slice(o+s,o+s+a):n.subarray(o+s,o+s+a)),o=o+s+a}return t}}const Un=new Uint8Array([145,Bt.Ping]);class Mn{constructor(e){this.name="messagepack",this.version=1,this.transferFormat=Lt.Binary,this._errorResult=1,this._voidResult=2,this._nonVoidResult=3,e=e||{},this._encoder=new _n(e.extensionCodec,e.context,e.maxDepth,e.initialBufferSize,e.sortKeys,e.forceFloat32,e.ignoreUndefined,e.forceIntegerToFloat),this._decoder=new Rn(e.extensionCodec,e.context,e.maxStrLength,e.maxBinLength,e.maxArrayLength,e.maxMapLength,e.maxExtLength)}parseMessages(e,t){if(!(n=e)||"undefined"==typeof ArrayBuffer||!(n instanceof ArrayBuffer||n.constructor&&"ArrayBuffer"===n.constructor.name))throw new Error("Invalid input for MessagePack hub protocol. Expected an ArrayBuffer.");var n;null===t&&(t=yt.instance);const r=Pn.parse(e),o=[];for(const e of r){const n=this._parseMessage(e,t);n&&o.push(n)}return o}writeMessage(e){switch(e.type){case Bt.Invocation:return this._writeInvocation(e);case Bt.StreamInvocation:return this._writeStreamInvocation(e);case Bt.StreamItem:return this._writeStreamItem(e);case Bt.Completion:return this._writeCompletion(e);case Bt.Ping:return Pn.write(Un);case Bt.CancelInvocation:return this._writeCancelInvocation(e);case Bt.Close:return this._writeClose();default:throw new Error("Invalid message type.")}}_parseMessage(e,t){if(0===e.length)throw new Error("Invalid payload.");const n=this._decoder.decode(e);if(0===n.length||!(n instanceof Array))throw new Error("Invalid payload.");const r=n[0];switch(r){case Bt.Invocation:return this._createInvocationMessage(this._readHeaders(n),n);case Bt.StreamItem:return this._createStreamItemMessage(this._readHeaders(n),n);case Bt.Completion:return this._createCompletionMessage(this._readHeaders(n),n);case Bt.Ping:return this._createPingMessage(n);case Bt.Close:return this._createCloseMessage(n);default:return t.log(mt.Information,"Unknown message type '"+r+"' ignored."),null}}_createCloseMessage(e){if(e.length<2)throw new Error("Invalid payload for Close message.");return{allowReconnect:e.length>=3?e[2]:void 0,error:e[1],type:Bt.Close}}_createPingMessage(e){if(e.length<1)throw new Error("Invalid payload for Ping message.");return{type:Bt.Ping}}_createInvocationMessage(e,t){if(t.length<5)throw new Error("Invalid payload for Invocation message.");const n=t[2];return n?{arguments:t[4],headers:e,invocationId:n,streamIds:[],target:t[3],type:Bt.Invocation}:{arguments:t[4],headers:e,streamIds:[],target:t[3],type:Bt.Invocation}}_createStreamItemMessage(e,t){if(t.length<4)throw new Error("Invalid payload for StreamItem message.");return{headers:e,invocationId:t[2],item:t[3],type:Bt.StreamItem}}_createCompletionMessage(e,t){if(t.length<4)throw new Error("Invalid payload for Completion message.");const n=t[3];if(n!==this._voidResult&&t.length<5)throw new Error("Invalid payload for Completion message.");let r,o;switch(n){case this._errorResult:r=t[4];break;case this._nonVoidResult:o=t[4]}return{error:r,headers:e,invocationId:t[2],result:o,type:Bt.Completion}}_writeInvocation(e){let t;return t=e.streamIds?this._encoder.encode([Bt.Invocation,e.headers||{},e.invocationId||null,e.target,e.arguments,e.streamIds]):this._encoder.encode([Bt.Invocation,e.headers||{},e.invocationId||null,e.target,e.arguments]),Pn.write(t.slice())}_writeStreamInvocation(e){let t;return t=e.streamIds?this._encoder.encode([Bt.StreamInvocation,e.headers||{},e.invocationId,e.target,e.arguments,e.streamIds]):this._encoder.encode([Bt.StreamInvocation,e.headers||{},e.invocationId,e.target,e.arguments]),Pn.write(t.slice())}_writeStreamItem(e){const t=this._encoder.encode([Bt.StreamItem,e.headers||{},e.invocationId,e.item]);return Pn.write(t.slice())}_writeCompletion(e){const t=e.error?this._errorResult:void 0!==e.result?this._nonVoidResult:this._voidResult;let n;switch(t){case this._errorResult:n=this._encoder.encode([Bt.Completion,e.headers||{},e.invocationId,t,e.error]);break;case this._voidResult:n=this._encoder.encode([Bt.Completion,e.headers||{},e.invocationId,t]);break;case this._nonVoidResult:n=this._encoder.encode([Bt.Completion,e.headers||{},e.invocationId,t,e.result])}return Pn.write(n.slice())}_writeCancelInvocation(e){const t=this._encoder.encode([Bt.CancelInvocation,e.headers||{},e.invocationId]);return Pn.write(t.slice())}_writeClose(){const e=this._encoder.encode([Bt.Close,null]);return Pn.write(e.slice())}_readHeaders(e){const t=e[1];if("object"!=typeof t)throw new Error("Invalid headers.");return t}}let Ln=!1;function Bn(){const e=document.querySelector("#blazor-error-ui");e&&(e.style.display="block"),Ln||(Ln=!0,document.querySelectorAll("#blazor-error-ui .reload").forEach((e=>{e.onclick=function(e){location.reload(),e.preventDefault()}})),document.querySelectorAll("#blazor-error-ui .dismiss").forEach((e=>{e.onclick=function(e){const t=document.querySelector("#blazor-error-ui");t&&(t.style.display="none"),e.preventDefault()}})))}const On="function"==typeof TextDecoder?new TextDecoder("utf-8"):null,Fn=On?On.decode.bind(On):function(e){let t=0;const n=e.length,r=[],o=[];for(;t65535&&(o-=65536,r.push(o>>>10&1023|55296),o=56320|1023&o),r.push(o)}r.length>1024&&(o.push(String.fromCharCode.apply(null,r)),r.length=0)}return o.push(String.fromCharCode.apply(null,r)),o.join("")},$n=Math.pow(2,32),Hn=Math.pow(2,21)-1;function jn(e,t){return e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24}function Wn(e,t){return e[t]+(e[t+1]<<8)+(e[t+2]<<16)+(e[t+3]<<24>>>0)}function zn(e,t){const n=Wn(e,t+4);if(n>Hn)throw new Error(`Cannot read uint64 with high order part ${n}, because the result would exceed Number.MAX_SAFE_INTEGER.`);return n*$n+Wn(e,t)}class Jn{constructor(e){this.batchData=e;const t=new Xn(e);this.arrayRangeReader=new Gn(e),this.arrayBuilderSegmentReader=new Yn(e),this.diffReader=new qn(e),this.editReader=new Kn(e,t),this.frameReader=new Vn(e,t)}updatedComponents(){return jn(this.batchData,this.batchData.length-20)}referenceFrames(){return jn(this.batchData,this.batchData.length-16)}disposedComponentIds(){return jn(this.batchData,this.batchData.length-12)}disposedEventHandlerIds(){return jn(this.batchData,this.batchData.length-8)}updatedComponentsEntry(e,t){const n=e+4*t;return jn(this.batchData,n)}referenceFramesEntry(e,t){return e+20*t}disposedComponentIdsEntry(e,t){const n=e+4*t;return jn(this.batchData,n)}disposedEventHandlerIdsEntry(e,t){const n=e+8*t;return zn(this.batchData,n)}}class qn{constructor(e){this.batchDataUint8=e}componentId(e){return jn(this.batchDataUint8,e)}edits(e){return e+4}editsEntry(e,t){return e+16*t}}class Kn{constructor(e,t){this.batchDataUint8=e,this.stringReader=t}editType(e){return jn(this.batchDataUint8,e)}siblingIndex(e){return jn(this.batchDataUint8,e+4)}newTreeIndex(e){return jn(this.batchDataUint8,e+8)}moveToSiblingIndex(e){return jn(this.batchDataUint8,e+8)}removedAttributeName(e){const t=jn(this.batchDataUint8,e+12);return this.stringReader.readString(t)}}class Vn{constructor(e,t){this.batchDataUint8=e,this.stringReader=t}frameType(e){return jn(this.batchDataUint8,e)}subtreeLength(e){return jn(this.batchDataUint8,e+4)}elementReferenceCaptureId(e){const t=jn(this.batchDataUint8,e+4);return this.stringReader.readString(t)}componentId(e){return jn(this.batchDataUint8,e+8)}elementName(e){const t=jn(this.batchDataUint8,e+8);return this.stringReader.readString(t)}textContent(e){const t=jn(this.batchDataUint8,e+4);return this.stringReader.readString(t)}markupContent(e){const t=jn(this.batchDataUint8,e+4);return this.stringReader.readString(t)}attributeName(e){const t=jn(this.batchDataUint8,e+4);return this.stringReader.readString(t)}attributeValue(e){const t=jn(this.batchDataUint8,e+8);return this.stringReader.readString(t)}attributeEventHandlerId(e){return zn(this.batchDataUint8,e+12)}}class Xn{constructor(e){this.batchDataUint8=e,this.stringTableStartIndex=jn(e,e.length-4)}readString(e){if(-1===e)return null;{const n=jn(this.batchDataUint8,this.stringTableStartIndex+4*e),r=function(e,t){let n=0,r=0;for(let o=0;o<4;o++){const i=e[t+o];if(n|=(127&i)<this.nextBatchId)return this.fatalError?(this.logger.log(Qn.Debug,`Received a new batch ${e} but errored out on a previous batch ${this.nextBatchId-1}`),void await n.send("OnRenderCompleted",this.nextBatchId-1,this.fatalError.toString())):void this.logger.log(Qn.Debug,`Waiting for batch ${this.nextBatchId}. Batch ${e} not processed.`);try{this.nextBatchId++,this.logger.log(Qn.Debug,`Applying batch ${e}.`),ye(this.browserRendererId,new Jn(t)),await this.completeBatch(n,e)}catch(t){throw this.fatalError=t.toString(),this.logger.log(Qn.Error,`There was an error applying batch ${e}.`),n.send("OnRenderCompleted",e,t.toString()),t}}getLastBatchid(){return this.nextBatchId-1}async completeBatch(e,t){try{await e.send("OnRenderCompleted",t,null)}catch{this.logger.log(Qn.Warning,`Failed to deliver completion notification for render '${t}'.`)}}}class er{log(e,t){}}er.instance=new er;class tr{constructor(e){this.minLevel=e}log(e,t){if(e>=this.minLevel){const n=`[${(new Date).toISOString()}] ${Qn[e]}: ${t}`;switch(e){case Qn.Critical:case Qn.Error:console.error(n);break;case Qn.Warning:console.warn(n);break;case Qn.Information:console.info(n);break;default:console.log(n)}}}}class nr{constructor(e,t){this.circuitId=void 0,this.components=e,this.applicationState=t}reconnect(e){if(!this.circuitId)throw new Error("Circuit host not initialized.");return e.state!==Ot.Connected?Promise.resolve(!1):e.invoke("ConnectCircuit",this.circuitId)}initialize(e){if(this.circuitId)throw new Error(`Circuit host '${this.circuitId}' already initialized.`);this.circuitId=e}async startCircuit(e){if(e.state!==Ot.Connected)return!1;const t=await e.invoke("StartCircuit",Pe.getBaseURI(),Pe.getLocationHref(),JSON.stringify(this.components.map((e=>e.toRecord()))),this.applicationState||"");return!!t&&(this.initialize(t),!0)}resolveElement(e){const t=v(e);if(t)return $(t,!0);const n=Number.parseInt(e);if(!Number.isNaN(n))return F(this.components[n].start,this.components[n].end);throw new Error(`Invalid sequence number or identifier '${e}'.`)}}const rr={configureSignalR:e=>{},logLevel:Qn.Warning,reconnectionOptions:{maxRetries:8,retryIntervalMilliseconds:2e4,dialogId:"components-reconnect-modal"}};class or{constructor(e,t,n,r){this.maxRetries=t,this.document=n,this.logger=r,this.addedToDom=!1,this.modal=this.document.createElement("div"),this.modal.id=e,this.maxRetries=t,this.modal.style.cssText=["position: fixed","top: 0","right: 0","bottom: 0","left: 0","z-index: 1050","display: none","overflow: hidden","background-color: #fff","opacity: 0.8","text-align: center","font-weight: bold","transition: visibility 0s linear 500ms"].join(";"),this.message=this.document.createElement("h5"),this.message.style.cssText="margin-top: 20px",this.button=this.document.createElement("button"),this.button.style.cssText="margin:5px auto 5px",this.button.textContent="Retry";const o=this.document.createElement("a");o.addEventListener("click",(()=>location.reload())),o.textContent="reload",this.reloadParagraph=this.document.createElement("p"),this.reloadParagraph.textContent="Alternatively, ",this.reloadParagraph.appendChild(o),this.modal.appendChild(this.message),this.modal.appendChild(this.button),this.modal.appendChild(this.reloadParagraph),this.loader=this.getLoader(),this.message.after(this.loader),this.button.addEventListener("click",(async()=>{this.show();try{await tt.reconnect()||this.rejected()}catch(e){this.logger.log(Qn.Error,e),this.failed()}}))}show(){this.addedToDom||(this.addedToDom=!0,this.document.body.appendChild(this.modal)),this.modal.style.display="block",this.loader.style.display="inline-block",this.button.style.display="none",this.reloadParagraph.style.display="none",this.message.textContent="Attempting to reconnect to the server...",this.modal.style.visibility="hidden",setTimeout((()=>{this.modal.style.visibility="visible"}),0)}update(e){this.message.textContent=`Attempting to reconnect to the server: ${e} of ${this.maxRetries}`}hide(){this.modal.style.display="none"}failed(){this.button.style.display="block",this.reloadParagraph.style.display="none",this.loader.style.display="none";const e=this.document.createTextNode("Reconnection failed. Try "),t=this.document.createElement("a");t.textContent="reloading",t.setAttribute("href",""),t.addEventListener("click",(()=>location.reload()));const n=this.document.createTextNode(" the page if you're unable to reconnect.");this.message.replaceChildren(e,t,n)}rejected(){this.button.style.display="none",this.reloadParagraph.style.display="none",this.loader.style.display="none";const e=this.document.createTextNode("Could not reconnect to the server. "),t=this.document.createElement("a");t.textContent="Reload",t.setAttribute("href",""),t.addEventListener("click",(()=>location.reload()));const n=this.document.createTextNode(" the page to restore functionality.");this.message.replaceChildren(e,t,n)}getLoader(){const e=this.document.createElement("div");return e.style.cssText=["border: 0.3em solid #f3f3f3","border-top: 0.3em solid #3498db","border-radius: 50%","width: 2em","height: 2em","display: inline-block"].join(";"),e.animate([{transform:"rotate(0deg)"},{transform:"rotate(360deg)"}],{duration:2e3,iterations:1/0}),e}}class ir{constructor(e,t,n){this.dialog=e,this.maxRetries=t,this.document=n,this.document=n;const r=this.document.getElementById(ir.MaxRetriesId);r&&(r.innerText=this.maxRetries.toString())}show(){this.removeClasses(),this.dialog.classList.add(ir.ShowClassName)}update(e){const t=this.document.getElementById(ir.CurrentAttemptId);t&&(t.innerText=e.toString())}hide(){this.removeClasses(),this.dialog.classList.add(ir.HideClassName)}failed(){this.removeClasses(),this.dialog.classList.add(ir.FailedClassName)}rejected(){this.removeClasses(),this.dialog.classList.add(ir.RejectedClassName)}removeClasses(){this.dialog.classList.remove(ir.ShowClassName,ir.HideClassName,ir.FailedClassName,ir.RejectedClassName)}}ir.ShowClassName="components-reconnect-show",ir.HideClassName="components-reconnect-hide",ir.FailedClassName="components-reconnect-failed",ir.RejectedClassName="components-reconnect-rejected",ir.MaxRetriesId="components-reconnect-max-retries",ir.CurrentAttemptId="components-reconnect-current-attempt";class sr{constructor(e,t,n){this._currentReconnectionProcess=null,this._logger=e,this._reconnectionDisplay=t,this._reconnectCallback=n||tt.reconnect}onConnectionDown(e,t){if(!this._reconnectionDisplay){const t=document.getElementById(e.dialogId);this._reconnectionDisplay=t?new ir(t,e.maxRetries,document):new or(e.dialogId,e.maxRetries,document,this._logger)}this._currentReconnectionProcess||(this._currentReconnectionProcess=new ar(e,this._logger,this._reconnectCallback,this._reconnectionDisplay))}onConnectionUp(){this._currentReconnectionProcess&&(this._currentReconnectionProcess.dispose(),this._currentReconnectionProcess=null)}}class ar{constructor(e,t,n,r){this.logger=t,this.reconnectCallback=n,this.isDisposed=!1,this.reconnectDisplay=r,this.reconnectDisplay.show(),this.attemptPeriodicReconnection(e)}dispose(){this.isDisposed=!0,this.reconnectDisplay.hide()}async attemptPeriodicReconnection(e){for(let t=0;tar.MaximumFirstRetryInterval?ar.MaximumFirstRetryInterval:e.retryIntervalMilliseconds;if(await this.delay(n),this.isDisposed)break;try{return await this.reconnectCallback()?void 0:void this.reconnectDisplay.rejected()}catch(e){this.logger.log(Qn.Error,e)}}this.reconnectDisplay.failed()}delay(e){return new Promise((t=>setTimeout(t,e)))}}function cr(e,t){switch(t){case"webassembly":return function(e){const t=dr(e,"webassembly"),n=[];for(let e=0;ee.id-t.id))}(e);case"server":return function(e){const t=dr(e,"server"),n=[];for(let e=0;ee.sequence-t.sequence))}(e)}}ar.MaximumFirstRetryInterval=3e3;const lr=/^\s*Blazor-Component-State:(?[a-zA-Z0-9+/=]+)$/;function hr(e){var t;if(e.nodeType===Node.COMMENT_NODE){const n=e.textContent||"",r=lr.exec(n),o=r&&r.groups&&r.groups.state;return o&&(null===(t=e.parentNode)||void 0===t||t.removeChild(e)),o}if(!e.hasChildNodes())return;const n=e.childNodes;for(let e=0;e.*)$/);function pr(e,t){const n=e.currentElement;if(n&&n.nodeType===Node.COMMENT_NODE&&n.textContent){const r=ur.exec(n.textContent),o=r&&r.groups&&r.groups.descriptor;if(!o)return;!function(e){if(e.parentNode instanceof Document)throw new Error("Root components cannot be marked as interactive. The element must be rendered statically so that scripts are not evaluated multiple times.")}(n);try{const r=function(e){const t=JSON.parse(e),{type:n}=t;if("server"!==n&&"webassembly"!==n)throw new Error(`Invalid component type '${n}'.`);return t}(o);switch(t){case"webassembly":return function(e,t,n){const{type:r,assembly:o,typeName:i,parameterDefinitions:s,parameterValues:a,prerenderId:c}=e,l=c?fr(c,n):void 0;if(c&&!l)throw new Error(`Could not find an end component comment for '${t}'.`);if("webassembly"===r){if(!o)throw new Error("assembly must be defined when using a descriptor.");if(!i)throw new Error("typeName must be defined when using a descriptor.");return{type:r,assembly:o,typeName:i,parameterDefinitions:s&&atob(s),parameterValues:a&&atob(a),start:t,prerenderId:c,end:l}}}(r,n,e);case"server":return function(e,t,n){const{type:r,descriptor:o,sequence:i,prerenderId:s}=e,a=s?fr(s,n):void 0;if(s&&!a)throw new Error(`Could not find an end component comment for '${t}'.`);if("server"===r){if(!o)throw new Error("descriptor must be defined when using a descriptor.");if(void 0===i)throw new Error("sequence must be defined when using a descriptor.");if(!Number.isInteger(i))throw new Error(`Error parsing the sequence '${i}' for component '${JSON.stringify(e)}'`);return{type:r,sequence:i,descriptor:o,start:t,prerenderId:s,end:a}}}(r,n,e)}}catch(e){throw new Error(`Found malformed component comment at ${n.textContent}`)}}}function fr(e,t){for(;t.next()&&t.currentElement;){const n=t.currentElement;if(n.nodeType!==Node.COMMENT_NODE)continue;if(!n.textContent)continue;const r=ur.exec(n.textContent),o=r&&r[1];if(o)return gr(o,e),n}}function gr(e,t){const n=JSON.parse(e);if(1!==Object.keys(n).length)throw new Error(`Invalid end of component comment: '${e}'`);const r=n.prerenderId;if(!r)throw new Error(`End of component comment must have a value for the prerendered property: '${e}'`);if(r!==t)throw new Error(`End of component comment prerendered property must match the start comment prerender id: '${t}', '${r}'`)}class mr{constructor(e){this.childNodes=e,this.currentIndex=-1,this.length=e.length}next(){return this.currentIndex++,this.currentIndexasync function(e,n){const r=function(e){const t=document.baseURI;return t.endsWith("/")?`${t}${e}`:`${t}/${e}`}(n),o=await import(r);if(void 0===o)return;const{beforeStart:i,afterStarted:s}=o;return s&&e.afterStartedCallbacks.push(s),i?i(...t):void 0}(this,e))))}async invokeAfterStartedCallbacks(e){await I,await Promise.all(this.afterStartedCallbacks.map((t=>t(e))))}}let br,_r,Er,Sr,Cr=!1;async function Ir(e,t,n){var r,o;const i=new Mn;i.name="blazorpack";const s=(new Qt).withUrl("_blazor").withHubProtocol(i);e.configureSignalR(s);const a=s.build();a.on("JS.AttachComponent",((e,t)=>me(0,n.resolveElement(t),e,!1))),a.on("JS.BeginInvokeJS",Er.beginInvokeJSFromDotNet.bind(Er)),a.on("JS.EndInvokeDotNet",Er.endInvokeDotNetFromJS.bind(Er)),a.on("JS.ReceiveByteArray",Er.receiveByteArray.bind(Er)),a.on("JS.BeginTransmitStream",(e=>{const t=new ReadableStream({start(t){a.stream("SendDotNetStreamToJS",e).subscribe({next:e=>t.enqueue(e),complete:()=>t.close(),error:e=>t.error(e)})}});Er.supplyDotNetStream(e,t)}));const c=Zn.getOrCreate(t);a.on("JS.RenderBatch",((e,n)=>{t.log(Qn.Debug,`Received render batch with id ${e} and ${n.byteLength} bytes.`),c.processBatch(e,n,a)})),a.on("JS.EndLocationChanging",tt._internal.navigationManager.endLocationChanging),a.onclose((t=>!Cr&&e.reconnectionHandler.onConnectionDown(e.reconnectionOptions,t))),a.on("JS.Error",(e=>{Cr=!0,kr(a,e,t),Bn()}));try{await a.start(),br=a}catch(e){if(kr(a,e,t),"FailedToNegotiateWithServerError"===e.errorType)throw e;Bn(),e.innerErrors&&(e.innerErrors.some((e=>"UnsupportedTransportError"===e.errorType&&e.transport===Mt.WebSockets))?t.log(Qn.Error,"Unable to connect, please ensure you are using an updated browser that supports WebSockets."):e.innerErrors.some((e=>"FailedToStartTransportError"===e.errorType&&e.transport===Mt.WebSockets))?t.log(Qn.Error,"Unable to connect, please ensure WebSockets are available. A VPN or proxy may be blocking the connection."):e.innerErrors.some((e=>"DisabledTransportError"===e.errorType&&e.transport===Mt.LongPolling))&&t.log(Qn.Error,"Unable to initiate a SignalR connection to the server. This might be because the server is not configured to support WebSockets. For additional details, visit https://aka.ms/blazor-server-websockets-error."))}return(null===(o=null===(r=a.connection)||void 0===r?void 0:r.features)||void 0===o?void 0:o.inherentKeepAlive)&&t.log(Qn.Warning,"Failed to connect via WebSockets, using the Long Polling fallback transport. This may be due to a VPN or proxy blocking the connection. To troubleshoot this, visit https://aka.ms/blazor-server-using-fallback-long-polling."),a}function kr(e,t,n){n.log(Qn.Error,t),e&&e.stop()}function Tr(e){return Sr=e,Sr}var xr,Dr;const Nr=navigator,Ar=Nr.userAgentData&&Nr.userAgentData.brands,Rr=Ar&&Ar.length>0?Ar.some((e=>"Google Chrome"===e.brand||"Microsoft Edge"===e.brand||"Chromium"===e.brand)):window.chrome,Pr=null!==(Dr=null===(xr=Nr.userAgentData)||void 0===xr?void 0:xr.platform)&&void 0!==Dr?Dr:navigator.platform;let Ur,Mr,Lr,Br,Or,Fr,$r=!1,Hr=!1;function jr(){return($r||Hr)&&(Rr||navigator.userAgent.includes("Firefox"))}const Wr=Math.pow(2,32),zr=Math.pow(2,21)-1;let Jr=null,qr="Production";function Kr(e){return Mr.getI32(e)}const Vr={start:function(t){return async function(t){const n={},{dotnet:r}=await async function(e){if("undefined"==typeof WebAssembly||!WebAssembly.validate)throw new Error("This browser does not support WebAssembly.");const t=await async function(e,t){const n=void 0!==e?e("manifest","blazor.boot.json","_framework/blazor.boot.json",""):i("_framework/blazor.boot.json");let r;r=n?"string"==typeof n?await i(n):await n:await i("_framework/blazor.boot.json"),qr=t||r.headers.get("Blazor-Environment")||"Production";const o=await r.json();return o.modifiableAssemblies=r.headers.get("DOTNET-MODIFIABLE-ASSEMBLIES"),o.aspnetCoreBrowserTools=r.headers.get("ASPNETCORE-BROWSER-TOOLS"),o;function i(e){return fetch(e,{method:"GET",credentials:"include",cache:"no-cache"})}}(e.loadBootResource,e.environment),n=Object.keys(t.resources.runtime).filter((e=>e.startsWith("dotnet.")&&e.endsWith(".js")))[0],r=t.resources.runtime[n];let o=`_framework/${n}`;if(e.loadBootResource){const t="dotnetjs",i=e.loadBootResource(t,n,o,r);if("string"==typeof i)o=i;else if(i)throw new Error(`For a ${t} resource, custom loaders must supply a URI string.`)}if(t.cacheBootResources){const e=document.createElement("link");e.rel="modulepreload",e.href=o,e.crossOrigin="anonymous",e.integrity=r,document.head.appendChild(e)}const i=new URL(o,document.baseURI).toString();return await import(i)}(t),o=function(e,t){const n={maxParallelDownloads:1e6,enableDownloadRetry:!1,applicationEnvironment:qr},r={...window.Module||{},onConfigLoaded:async n=>{n.environmentVariables||(n.environmentVariables={}),0===n.icuDataMode&&(n.environmentVariables.__BLAZOR_SHARDED_ICU="1"),n.aspnetCoreBrowserTools&&(n.environmentVariables.__ASPNETCORE_BROWSER_TOOLS=n.aspnetCoreBrowserTools),tt._internal.getApplicationEnvironment=()=>n.applicationEnvironment,t.jsInitializer=await async function(e,t){const n=e.resources.libraryInitializers,r=new vr;return n&&await r.importInitializersAsync(Object.keys(n),[t,e.resources.extensions]),r}(n,e)},onDownloadResourceProgress:Xr,config:n,disableDotnet6Compatibility:!1,print:Yr,printErr:Qr};return r}(t,n);r.withStartupOptions(t).withModuleConfig(o),Fr=await r.create();const{MONO:i,BINDING:s,Module:a,setModuleImports:c,INTERNAL:l}=Fr;Lr=a,Ur=s,Mr=i,Or=l;const h=Or.resourceLoader;n.resourceLoader=h,function(e){$r=!!e.bootConfig.resources.pdb,Hr=e.bootConfig.debugBuild;const t=Pr.match(/^Mac/i)?"Cmd":"Alt";jr()&&console.info(`Debugging hotkey: Shift+${t}+D (when application has focus)`),document.addEventListener("keydown",(e=>{e.shiftKey&&(e.metaKey||e.altKey)&&"KeyD"===e.code&&(Hr||$r?navigator.userAgent.includes("Firefox")?async function(){const e=await fetch(`_framework/debug?url=${encodeURIComponent(location.href)}&isFirefox=true`);200!==e.status&&console.warn(await e.text())}():Rr?function(){const e=document.createElement("a");e.href=`_framework/debug?url=${encodeURIComponent(location.href)}`,e.target="_blank",e.rel="noopener noreferrer",e.click()}():console.error("Currently, only Microsoft Edge (80+), Google Chrome, or Chromium, are supported for debugging."):console.error("Cannot start debugging, because the application was not compiled with debugging enabled."))}))}(h),tt._internal.dotNetCriticalError=Qr,tt._internal.loadLazyAssembly=e=>async function(e,t){const n=e.bootConfig.resources,r=n.lazyAssembly;if(!r)throw new Error("No assemblies have been marked as lazy-loadable. Use the 'BlazorWebAssemblyLazyLoad' item group in your project file to enable lazy loading an assembly.");if(!r.hasOwnProperty(t))throw new Error(`${t} must be marked with 'BlazorWebAssemblyLazyLoad' item group in your project file to allow lazy-loading.`);const o=t,i=function(e,t){const n=e.lastIndexOf(".");if(n<0)throw new Error(`No extension to replace in '${e}'`);return e.substr(0,n)+".pdb"}(t),s=jr()&&n.pdb&&r.hasOwnProperty(i),a=e.loadResource(o,`_framework/${o}`,r[o],"assembly").response.then((e=>e.arrayBuffer()));if(s){const t=await e.loadResource(i,`_framework/${i}`,r[i],"pdb").response.then((e=>e.arrayBuffer())),[n,o]=await Promise.all([a,t]);return{dll:new Uint8Array(n),pdb:new Uint8Array(o)}}{const e=await a;return{dll:new Uint8Array(e),pdb:null}}}(Or.resourceLoader,e),tt._internal.loadSatelliteAssemblies=(e,t)=>async function(e,t,n){const r=e.bootConfig.resources.satelliteResources;r&&await Promise.all(t.filter((e=>r.hasOwnProperty(e))).map((t=>e.loadResources(r[t],(e=>`_framework/${e}`),"assembly"))).reduce(((e,t)=>e.concat(t)),new Array).map((async e=>{const t=await e.response,r=await t.arrayBuffer(),o={dll:new Uint8Array(r)};n(o)})))}(h,e,t),c("blazor-internal",{Blazor:{_internal:tt._internal}});const d=await Fr.getAssemblyExports("Microsoft.AspNetCore.Components.WebAssembly");return Object.assign(tt._internal,{dotNetExports:{...d.Microsoft.AspNetCore.Components.WebAssembly.Services.DefaultWebAssemblyJSRuntime}}),Br=e.attachDispatcher({beginInvokeDotNetFromJS:(e,t,n,r,o)=>{if(eo(),!r&&!t)throw new Error("Either assemblyName or dotNetObjectId must have a non null value.");const i=r?r.toString():t;tt._internal.dotNetExports.BeginInvokeDotNet(e?e.toString():null,i,n,o)},endInvokeJSFromDotNet:(e,t,n)=>{tt._internal.dotNetExports.EndInvokeJS(n)},sendByteArray:(e,t)=>{tt._internal.dotNetExports.ReceiveByteArrayFromJS(e,t)},invokeDotNetFromJS:(e,t,n,r)=>(eo(),tt._internal.dotNetExports.InvokeDotNet(e||null,t,null!=n?n:0,r))}),n}(t)},callEntryPoint:async function(e){try{await Fr.runMain(e,[])}catch(e){console.error(e),Bn()}},toUint8Array:function(e){const t=Zr(e),n=Kr(t),r=new Uint8Array(n);return r.set(Lr.HEAPU8.subarray(t+4,t+4+n)),r},getArrayLength:function(e){return Kr(Zr(e))},getArrayEntryPtr:function(e,t,n){return Zr(e)+4+t*n},getObjectFieldsBaseAddress:function(e){return e+8},readInt16Field:function(e,t){return n=e+(t||0),Mr.getI16(n);var n},readInt32Field:function(e,t){return Kr(e+(t||0))},readUint64Field:function(e,t){return function(e){const t=e>>2,n=Lr.HEAPU32[t+1];if(n>zr)throw new Error(`Cannot read uint64 with high order part ${n}, because the result would exceed Number.MAX_SAFE_INTEGER.`);return n*Wr+Lr.HEAPU32[t]}(e+(t||0))},readFloatField:function(e,t){return n=e+(t||0),Mr.getF32(n);var n},readObjectField:function(e,t){return Kr(e+(t||0))},readStringField:function(e,t,n){const r=Kr(e+(t||0));if(0===r)return null;if(n){const e=Ur.unbox_mono_obj(r);return"boolean"==typeof e?e?"":null:e}return Ur.conv_string(r)},readStructField:function(e,t){return e+(t||0)},beginHeapLock:function(){return eo(),Jr=to.create(),Jr},invokeWhenHeapUnlocked:function(e){Jr?Jr.enqueuePostReleaseAction(e):e()}};function Xr(e,t){const n=e/t*100;document.documentElement.style.setProperty("--blazor-load-percentage",`${n}%`),document.documentElement.style.setProperty("--blazor-load-percentage-text",`"${Math.floor(n)}%"`)}const Gr=["DEBUGGING ENABLED"],Yr=e=>Gr.indexOf(e)<0&&console.log(e),Qr=e=>{console.error(e||"(null)"),Bn()};function Zr(e){return e+12}function eo(){if(Jr)throw new Error("Assertion failed - heap is currently locked")}class to{enqueuePostReleaseAction(e){this.postReleaseActions||(this.postReleaseActions=[]),this.postReleaseActions.push(e)}release(){var e;if(Jr!==this)throw new Error("Trying to release a lock which isn't current");for(Or.mono_wasm_gc_unlock(),Jr=null;null===(e=this.postReleaseActions)||void 0===e?void 0:e.length;)this.postReleaseActions.shift()(),eo()}static create(){return Or.mono_wasm_gc_lock(),new to}}class no{constructor(e){this.batchAddress=e,this.arrayRangeReader=ro,this.arrayBuilderSegmentReader=oo,this.diffReader=io,this.editReader=so,this.frameReader=ao}updatedComponents(){return Sr.readStructField(this.batchAddress,0)}referenceFrames(){return Sr.readStructField(this.batchAddress,ro.structLength)}disposedComponentIds(){return Sr.readStructField(this.batchAddress,2*ro.structLength)}disposedEventHandlerIds(){return Sr.readStructField(this.batchAddress,3*ro.structLength)}updatedComponentsEntry(e,t){return co(e,t,io.structLength)}referenceFramesEntry(e,t){return co(e,t,ao.structLength)}disposedComponentIdsEntry(e,t){const n=co(e,t,4);return Sr.readInt32Field(n)}disposedEventHandlerIdsEntry(e,t){const n=co(e,t,8);return Sr.readUint64Field(n)}}const ro={structLength:8,values:e=>Sr.readObjectField(e,0),count:e=>Sr.readInt32Field(e,4)},oo={structLength:12,values:e=>{const t=Sr.readObjectField(e,0),n=Sr.getObjectFieldsBaseAddress(t);return Sr.readObjectField(n,0)},offset:e=>Sr.readInt32Field(e,4),count:e=>Sr.readInt32Field(e,8)},io={structLength:4+oo.structLength,componentId:e=>Sr.readInt32Field(e,0),edits:e=>Sr.readStructField(e,4),editsEntry:(e,t)=>co(e,t,so.structLength)},so={structLength:20,editType:e=>Sr.readInt32Field(e,0),siblingIndex:e=>Sr.readInt32Field(e,4),newTreeIndex:e=>Sr.readInt32Field(e,8),moveToSiblingIndex:e=>Sr.readInt32Field(e,8),removedAttributeName:e=>Sr.readStringField(e,16)},ao={structLength:36,frameType:e=>Sr.readInt16Field(e,4),subtreeLength:e=>Sr.readInt32Field(e,8),elementReferenceCaptureId:e=>Sr.readStringField(e,16),componentId:e=>Sr.readInt32Field(e,12),elementName:e=>Sr.readStringField(e,16),textContent:e=>Sr.readStringField(e,16),markupContent:e=>Sr.readStringField(e,16),attributeName:e=>Sr.readStringField(e,16),attributeValue:e=>Sr.readStringField(e,24,!0),attributeEventHandlerId:e=>Sr.readUint64Field(e,8)};function co(e,t,n){return Sr.getArrayEntryPtr(e,t,n)}class lo{constructor(e){this.preregisteredComponents=e;const t={};for(let n=0;n=n&&s>=r&&o(e.item(i),t.item(s))===yo.None;)i--,s--,a++;return a}(e,t,r,r,n),i=function(e){var t;const n=[];let r=e.length-1,o=(null===(t=e[r])||void 0===t?void 0:t.length)-1;for(;r>0||o>0;){const t=0===r?wo.Insert:0===o?wo.Delete:e[r][o];switch(n.unshift(t),t){case wo.Keep:case wo.Update:r--,o--;break;case wo.Insert:o--;break;case wo.Delete:r--}}return n}(function(e,t,n){const r=[],o=[],i=e.length,s=t.length;if(0===i&&0===s)return[];for(let e=0;e<=i;e++)(r[e]=Array(s+1))[0]=e,o[e]=Array(s+1);const a=r[0];for(let e=1;e<=s;e++)a[e]=e;for(let a=1;a<=i;a++)for(let i=1;i<=s;i++){const s=n(e.item(a-1),t.item(i-1)),c=r[a-1][i]+1,l=r[a][i-1]+1;let h;switch(s){case yo.None:h=r[a-1][i-1];break;case yo.Some:h=r[a-1][i-1]+1;break;case yo.Infinite:h=Number.MAX_VALUE}h{};function To(){document.removeEventListener("click",xo),document.removeEventListener("submit",No),window.removeEventListener("popstate",Do)}function xo(e){Ce()||be(e,(e=>{history.pushState(null,"",e),Ao(e)}))}function Do(e){Ce()||Ao(location.href)}function No(e){if(Ce()||e.defaultPrevented)return;const t=e.target;if(t instanceof HTMLFormElement){e.preventDefault();const n=new URL(t.action),r={method:t.method},o=new FormData(t),i=e.submitter;i&&i.name&&o.append(i.name,i.value),"get"===r.method?n.search=new URLSearchParams(o).toString():r.body=o,Ao(n.toString(),r)}}async function Ao(e,t){null==Io||Io.abort(),Io=new AbortController;const n=Io.signal,r=fetch(e,Object.assign({signal:n,headers:{"blazor-enhanced-nav":"on"}},t));if(await async function(e,t,n,r){let o;try{o=await e;const t=o.headers.get("blazor-enhanced-nav-redirect-location");if(t)return void location.replace(t);if(!o.body)return void n(o,"");const r=o.headers.get("ssr-framing");if(!r){const e=await o.text();return void n(o,e)}let i=!0;await o.body.pipeThrough(new TextDecoderStream).pipeThrough(function(e){let t="";return new TransformStream({transform(n,r){if(t+=n,t.indexOf(e,t.length-n.length-e.length)>=0){const n=t.split(e);n.slice(0,-1).forEach((e=>r.enqueue(e))),t=n[n.length-1]}},flush(e){e.enqueue(t)}})}(`\x3c!--${r}--\x3e`)).pipeTo(new WritableStream({write(e){i?(i=!1,n(o,e)):(e=>{const t=document.createRange().createContextualFragment(e);for(;t.firstChild;)document.body.appendChild(t.firstChild)})(e)}}))}catch(e){if("AbortError"===e.name&&t.aborted)return;throw e}}(r,n,((n,r)=>{n.redirected&&(history.replaceState(null,"",n.url),e=n.url);const o=n.headers.get("content-type");if((null==o?void 0:o.startsWith("text/html"))&&r){const e=(new DOMParser).parseFromString(r,"text/html");bo(document,e)}else(null==o?void 0:o.startsWith("text/"))&&r?Ro(r):(n.status<200||n.status>=300)&&!r?Ro(`Error: ${n.status} ${n.statusText}`):(null==t?void 0:t.method)&&"get"!==t.method?Ro(`Error: ${t.method} request to ${e} returned non-HTML content of type ${o||"unspecified"}.`):(history.replaceState(null,"",e+"?"),location.replace(e))})),!n.aborted){ko();const t=e.indexOf("#");if(t>=0){const n=e.substring(t+1),r=document.getElementById(n);null==r||r.scrollIntoView()}}}function Ro(e){document.documentElement.textContent=e;const t=document.documentElement.style;t.fontFamily="consolas, monospace",t.whiteSpace="pre-wrap",t.padding="1rem"}let Po=!0;class Uo extends HTMLElement{connectedCallback(){var e;null===(e=this.parentNode)||void 0===e||e.removeChild(this);const t=this.attachShadow({mode:"open"}),n=document.createElement("slot");t.appendChild(n),n.addEventListener("slotchange",(e=>{this.childNodes.forEach((e=>{if(e instanceof HTMLTemplateElement){const t=e.getAttribute("blazor-component-id");if(t)!function(e,t){const n=function(e){const t=`bl:${e}`,n=document.createNodeIterator(document,NodeFilter.SHOW_COMMENT);let r=null;for(;(r=n.nextNode())&&r.textContent!==t;);if(!r)return null;const o=`/bl:${e}`;let i=null;for(;(i=n.nextNode())&&i.textContent!==o;);return i?{startMarker:r,endMarker:i}:null}(e);if(n)if(Po)bo({startExclusive:n.startMarker,endExclusive:n.endMarker},t);else{const{startMarker:e,endMarker:r}=n,o=new Range;for(o.setStart(e,e.textContent.length),o.setEnd(r,0),o.deleteContents();t.childNodes[0];)r.parentNode.insertBefore(t.childNodes[0],r)}}(t,e.content);else switch(e.getAttribute("type")){case"redirection":const t=e.content.textContent;_e(t)?(history.replaceState(null,"",t),Ao(t)):location.replace(t);break;case"error":Ro(e.content.textContent||"Error")}}}))}))}}let Mo,Lo=!1;async function Bo(e){var t;if(Lo)throw new Error("Blazor has already started.");Lo=!0,Mo=e,function(e){(null==e?void 0:e.disableDomPreservation)&&(Po=!1),customElements.define("blazor-ssr",Uo)}(null==e?void 0:e.ssr),(null===(t=null==e?void 0:e.ssr)||void 0===t?void 0:t.disableDomPreservation)||(ko=Oo,document.addEventListener("click",xo),document.addEventListener("submit",No),window.addEventListener("popstate",Do)),await Oo()}async function Oo(){const t=cr(document,"server"),n=cr(document,"webassembly");t.length&&(To(),await async function(t,n){const r=function(e){const t={...rr,...e};return e&&e.reconnectionOptions&&(t.reconnectionOptions={...rr.reconnectionOptions,...e.reconnectionOptions}),t}(t),o=await async function(e){const t=await fetch("_blazor/initializers",{method:"GET",credentials:"include",cache:"no-cache"}),n=await t.json(),r=new vr;return await r.importInitializersAsync(n,[e]),r}(r),i=new tr(r.logLevel);tt.reconnect=async e=>{if(Cr)return!1;const t=e||await Ir(r,i,_r);return await _r.reconnect(t)?(r.reconnectionHandler.onConnectionUp(),!0):(i.log(Qn.Information,"Reconnection attempt to the circuit was rejected by the server. This may indicate that the associated state is no longer available on the server."),!1)},tt.defaultReconnectionHandler=new sr(i),r.reconnectionHandler=r.reconnectionHandler||tt.defaultReconnectionHandler,i.log(Qn.Information,"Starting up Blazor server-side application.");const s=hr(document);_r=new nr(n||[],s||""),tt._internal.navigationManager.listenForNavigationEvents(((e,t,n)=>br.send("OnLocationChanged",e,t,n)),((e,t,n,r)=>br.send("OnLocationChanging",e,t,n,r))),tt._internal.forceCloseConnection=()=>br.stop(),tt._internal.sendJSDataStream=(e,t,n)=>function(e,t,n,r){setTimeout((async()=>{let o=5,i=(new Date).valueOf();try{const s=t instanceof Blob?t.size:t.byteLength;let a=0,c=0;for(;a1)await e.send("ReceiveJSDataChunk",n,c,h,null);else{if(!await e.invoke("ReceiveJSDataChunk",n,c,h,null))break;const t=(new Date).valueOf(),r=t-i;i=t,o=Math.max(1,Math.round(500/Math.max(1,r)))}a+=l,c++}}catch(t){await e.send("ReceiveJSDataChunk",n,-1,null,t.toString())}}),0)}(br,e,t,n),Er=e.attachDispatcher({beginInvokeDotNetFromJS:(e,t,n,r,o)=>{br.send("BeginInvokeDotNetFromJS",e?e.toString():null,t,n,r||0,o)},endInvokeJSFromDotNet:(e,t,n)=>{br.send("EndInvokeJSFromDotNet",e,t,n)},sendByteArray:(e,t)=>{br.send("ReceiveByteArray",e,t)}});const a=await Ir(r,i,_r);if(!await _r.startCircuit(a))return void i.log(Qn.Error,"Failed to start the circuit.");let c=!1;const l=()=>{if(!c){const e=new FormData,t=_r.circuitId;e.append("circuitId",t),c=navigator.sendBeacon("_blazor/disconnect",e)}};tt.disconnect=l,window.addEventListener("unload",l,{capture:!1,once:!0}),i.log(Qn.Information,"Blazor server-side application started."),o.invokeAfterStartedCallbacks(tt)}(null==Mo?void 0:Mo.circuit,t)),n.length&&(To(),await async function(e,t){(function(){if(window.parent!==window&&!window.opener&&window.frameElement){const e=window.sessionStorage&&window.sessionStorage["Microsoft.AspNetCore.Components.WebAssembly.Authentication.CachedAuthSettings"],t=e&&JSON.parse(e);return t&&t.redirect_uri&&location.href.startsWith(t.redirect_uri)}return!1})()&&await new Promise((()=>{})),function(e){const t=x;x=(e,n,r)=>{((e,t,n)=>{const r=function(e){return fe[e]}(e);r.eventDelegator.getHandler(t)&&Vr.invokeWhenHeapUnlocked(n)})(e,n,(()=>t(e,n,r)))}}(),tt._internal.applyHotReload=(e,t,n,r)=>{Br.invokeDotNetStaticMethod("Microsoft.AspNetCore.Components.WebAssembly","ApplyHotReloadDelta",e,t,n,r)},tt._internal.getApplyUpdateCapabilities=()=>Br.invokeDotNetStaticMethod("Microsoft.AspNetCore.Components.WebAssembly","GetApplyUpdateCapabilities"),tt._internal.invokeJSFromDotNet=ho,tt._internal.invokeJSJson=uo,tt._internal.endInvokeDotNetFromJS=po,tt._internal.receiveWebAssemblyDotNetDataStream=fo,tt._internal.receiveByteArray=go;const n=Tr(Vr);tt.platform=n,tt._internal.renderBatch=(e,t)=>{const n=Vr.beginHeapLock();try{ye(e,new no(t))}finally{n.release()}},tt._internal.navigationManager.listenForNavigationEvents((async(e,t,n)=>{await Br.invokeDotNetStaticMethodAsync("Microsoft.AspNetCore.Components.WebAssembly","NotifyLocationChanged",e,t,n)}),(async(e,t,n,r)=>{const o=await Br.invokeDotNetStaticMethodAsync("Microsoft.AspNetCore.Components.WebAssembly","NotifyLocationChangingAsync",t,n,r);tt._internal.navigationManager.endLocationChanging(e,o)}));const r=new lo(t||[]);let o,i;tt._internal.registeredComponents={getRegisteredComponentsCount:()=>r.getCount(),getId:e=>r.getId(e),getAssembly:e=>r.getAssembly(e),getTypeName:e=>r.getTypeName(e),getParameterDefinitions:e=>r.getParameterDefinitions(e)||"",getParameterValues:e=>r.getParameterValues(e)||""},tt._internal.getPersistedState=()=>hr(document)||"",tt._internal.attachRootComponentToElement=(e,t,n)=>{const o=r.resolveRegisteredElement(e);o?me(n,o,t,!1):function(e,t,n){const r="::before";let o=!1;if(e.endsWith("::after"))e=e.slice(0,-7),o=!0;else if(e.endsWith(r))throw new Error(`The '${r}' selector is not supported.`);const i=v(e)||document.querySelector(e);if(!i)throw new Error(`Could not find any element matching selector '${e}'.`);me(n||0,$(i,!0),t,o)}(e,t,n)};try{const t=await n.start(null!=e?e:{});o=t.resourceLoader,i=t.jsInitializer}catch(e){throw new Error(`Failed to start platform. Reason: ${e}`)}n.callEntryPoint(o.bootConfig.entryAssembly),i.invokeAfterStartedCallbacks(tt)}(null==Mo?void 0:Mo.webAssembly,n))}tt.start=Bo,window.DotNet=e,document&&document.currentScript&&"false"!==document.currentScript.getAttribute("autostart")&&Bo()})()})(); \ No newline at end of file +(()=>{var e={778:()=>{},77:()=>{},203:()=>{},200:()=>{},628:()=>{},321:()=>{}},t={};function n(r){var o=t[r];if(void 0!==o)return o.exports;var s=t[r]={exports:{}};return e[r](s,s.exports,n),s.exports}n.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(e){if("object"==typeof window)return window}}(),(()=>{"use strict";var e,t,r;!function(e){const t=[],n="__jsObjectId",r="__dotNetObject",o="__byte[]",s="__dotNetStream",i="__jsStreamReferenceLength";let a,c;class l{constructor(e){this._jsObject=e,this._cachedFunctions=new Map}findFunction(e){const t=this._cachedFunctions.get(e);if(t)return t;let n,r=this._jsObject;if(e.split(".").forEach((t=>{if(!(t in r))throw new Error(`Could not find '${e}' ('${t}' was undefined).`);n=r,r=r[t]})),r instanceof Function)return r=r.bind(n),this._cachedFunctions.set(e,r),r;throw new Error(`The value '${e}' is not a function.`)}getWrappedObject(){return this._jsObject}}const h={0:new l(window)};h[0]._cachedFunctions.set("import",(e=>("string"==typeof e&&e.startsWith("./")&&(e=new URL(e.substr(2),document.baseURI).toString()),import(e))));let d,u=1;function p(e){t.push(e)}function f(e){if(e&&"object"==typeof e){h[u]=new l(e);const t={[n]:u};return u++,t}throw new Error(`Cannot create a JSObjectReference from the value '${e}'.`)}function g(e){let t=-1;if(e instanceof ArrayBuffer&&(e=new Uint8Array(e)),e instanceof Blob)t=e.size;else{if(!(e.buffer instanceof ArrayBuffer))throw new Error("Supplied value is not a typed array or blob.");if(void 0===e.byteLength)throw new Error(`Cannot create a JSStreamReference from the value '${e}' as it doesn't have a byteLength.`);t=e.byteLength}const r={[i]:t};try{const t=f(e);r[n]=t[n]}catch(t){throw new Error(`Cannot create a JSStreamReference from the value '${e}'.`)}return r}function m(e,n){c=e;const r=n?JSON.parse(n,((e,n)=>t.reduce(((t,n)=>n(e,t)),n))):null;return c=void 0,r}function y(){if(void 0===a)throw new Error("No call dispatcher has been set.");if(null===a)throw new Error("There are multiple .NET runtimes present, so a default dispatcher could not be resolved. Use DotNetObject to invoke .NET instance methods.");return a}e.attachDispatcher=function(e){const t=new v(e);return void 0===a?a=t:a&&(a=null),t},e.attachReviver=p,e.invokeMethod=function(e,t,...n){return y().invokeDotNetStaticMethod(e,t,...n)},e.invokeMethodAsync=function(e,t,...n){return y().invokeDotNetStaticMethodAsync(e,t,...n)},e.createJSObjectReference=f,e.createJSStreamReference=g,e.disposeJSObjectReference=function(e){const t=e&&e[n];"number"==typeof t&&_(t)},function(e){e[e.Default=0]="Default",e[e.JSObjectReference=1]="JSObjectReference",e[e.JSStreamReference=2]="JSStreamReference",e[e.JSVoidResult=3]="JSVoidResult"}(d=e.JSCallResultType||(e.JSCallResultType={}));class v{constructor(e){this._dotNetCallDispatcher=e,this._byteArraysToBeRevived=new Map,this._pendingDotNetToJSStreams=new Map,this._pendingAsyncCalls={},this._nextAsyncCallId=1}getDotNetCallDispatcher(){return this._dotNetCallDispatcher}invokeJSFromDotNet(e,t,n,r){const o=m(this,t),s=I(b(e,r)(...o||[]),n);return null==s?null:T(this,s)}beginInvokeJSFromDotNet(e,t,n,r,o){const s=new Promise((e=>{const r=m(this,n);e(b(t,o)(...r||[]))}));e&&s.then((t=>T(this,[e,!0,I(t,r)]))).then((t=>this._dotNetCallDispatcher.endInvokeJSFromDotNet(e,!0,t)),(t=>this._dotNetCallDispatcher.endInvokeJSFromDotNet(e,!1,JSON.stringify([e,!1,w(t)]))))}endInvokeDotNetFromJS(e,t,n){const r=t?m(this,n):new Error(n);this.completePendingCall(parseInt(e,10),t,r)}invokeDotNetStaticMethod(e,t,...n){return this.invokeDotNetMethod(e,t,null,n)}invokeDotNetStaticMethodAsync(e,t,...n){return this.invokeDotNetMethodAsync(e,t,null,n)}invokeDotNetMethod(e,t,n,r){if(this._dotNetCallDispatcher.invokeDotNetFromJS){const o=T(this,r),s=this._dotNetCallDispatcher.invokeDotNetFromJS(e,t,n,o);return s?m(this,s):null}throw new Error("The current dispatcher does not support synchronous calls from JS to .NET. Use invokeDotNetMethodAsync instead.")}invokeDotNetMethodAsync(e,t,n,r){if(e&&n)throw new Error(`For instance method calls, assemblyName should be null. Received '${e}'.`);const o=this._nextAsyncCallId++,s=new Promise(((e,t)=>{this._pendingAsyncCalls[o]={resolve:e,reject:t}}));try{const s=T(this,r);this._dotNetCallDispatcher.beginInvokeDotNetFromJS(o,e,t,n,s)}catch(e){this.completePendingCall(o,!1,e)}return s}receiveByteArray(e,t){this._byteArraysToBeRevived.set(e,t)}processByteArray(e){const t=this._byteArraysToBeRevived.get(e);return t?(this._byteArraysToBeRevived.delete(e),t):null}supplyDotNetStream(e,t){if(this._pendingDotNetToJSStreams.has(e)){const n=this._pendingDotNetToJSStreams.get(e);this._pendingDotNetToJSStreams.delete(e),n.resolve(t)}else{const n=new S;n.resolve(t),this._pendingDotNetToJSStreams.set(e,n)}}getDotNetStreamPromise(e){let t;if(this._pendingDotNetToJSStreams.has(e))t=this._pendingDotNetToJSStreams.get(e).streamPromise,this._pendingDotNetToJSStreams.delete(e);else{const n=new S;this._pendingDotNetToJSStreams.set(e,n),t=n.streamPromise}return t}completePendingCall(e,t,n){if(!this._pendingAsyncCalls.hasOwnProperty(e))throw new Error(`There is no pending async call with ID ${e}.`);const r=this._pendingAsyncCalls[e];delete this._pendingAsyncCalls[e],t?r.resolve(n):r.reject(n)}}function w(e){return e instanceof Error?`${e.message}\n${e.stack}`:e?e.toString():"null"}function b(e,t){const n=h[t];if(n)return n.findFunction(e);throw new Error(`JS object instance with ID ${t} does not exist (has it been disposed?).`)}function _(e){delete h[e]}e.findJSFunction=b,e.disposeJSObjectReferenceById=_;class E{constructor(e,t){this._id=e,this._callDispatcher=t}invokeMethod(e,...t){return this._callDispatcher.invokeDotNetMethod(null,e,this._id,t)}invokeMethodAsync(e,...t){return this._callDispatcher.invokeDotNetMethodAsync(null,e,this._id,t)}dispose(){this._callDispatcher.invokeDotNetMethodAsync(null,"__Dispose",this._id,null).catch((e=>console.error(e)))}serializeAsArg(){return{[r]:this._id}}}e.DotNetObject=E,p((function(e,t){if(t&&"object"==typeof t){if(t.hasOwnProperty(r))return new E(t[r],c);if(t.hasOwnProperty(n)){const e=t[n],r=h[e];if(r)return r.getWrappedObject();throw new Error(`JS object instance with Id '${e}' does not exist. It may have been disposed.`)}if(t.hasOwnProperty(o)){const e=t[o],n=c.processByteArray(e);if(void 0===n)throw new Error(`Byte array index '${e}' does not exist.`);return n}if(t.hasOwnProperty(s)){const e=t[s],n=c.getDotNetStreamPromise(e);return new C(n)}}return t}));class C{constructor(e){this._streamPromise=e}stream(){return this._streamPromise}async arrayBuffer(){return new Response(await this.stream()).arrayBuffer()}}class S{constructor(){this.streamPromise=new Promise(((e,t)=>{this.resolve=e,this.reject=t}))}}function I(e,t){switch(t){case d.Default:return e;case d.JSObjectReference:return f(e);case d.JSStreamReference:return g(e);case d.JSVoidResult:return null;default:throw new Error(`Invalid JS call result type '${t}'.`)}}let k=0;function T(e,t){k=0,c=e;const n=JSON.stringify(t,D);return c=void 0,n}function D(e,t){if(t instanceof E)return t.serializeAsArg();if(t instanceof Uint8Array){c.getDotNetCallDispatcher().sendByteArray(k,t);const e={[o]:k};return k++,e}return t}}(e||(e={})),function(e){e[e.prependFrame=1]="prependFrame",e[e.removeFrame=2]="removeFrame",e[e.setAttribute=3]="setAttribute",e[e.removeAttribute=4]="removeAttribute",e[e.updateText=5]="updateText",e[e.stepIn=6]="stepIn",e[e.stepOut=7]="stepOut",e[e.updateMarkup=8]="updateMarkup",e[e.permutationListEntry=9]="permutationListEntry",e[e.permutationListEnd=10]="permutationListEnd"}(t||(t={})),function(e){e[e.element=1]="element",e[e.text=2]="text",e[e.attribute=3]="attribute",e[e.component=4]="component",e[e.region=5]="region",e[e.elementReferenceCapture=6]="elementReferenceCapture",e[e.markup=8]="markup",e[e.namedEvent=10]="namedEvent"}(r||(r={}));class o{constructor(e,t){this.componentId=e,this.fieldValue=t}static fromEvent(e,t){const n=t.target;if(n instanceof Element){const t=function(e){return e instanceof HTMLInputElement?e.type&&"checkbox"===e.type.toLowerCase()?{value:e.checked}:{value:e.value}:e instanceof HTMLSelectElement||e instanceof HTMLTextAreaElement?{value:e.value}:null}(n);if(t)return new o(e,t.value)}return null}}const s=new Map,i=new Map,a=[];function c(e){return s.get(e)}function l(e){const t=s.get(e);return(null==t?void 0:t.browserEventName)||e}function h(e,t){e.forEach((e=>s.set(e,t)))}function d(e){const t=[];for(let n=0;ne.selected)).map((e=>e.value))}}{const e=function(e){return!!e&&"INPUT"===e.tagName&&"checkbox"===e.getAttribute("type")}(t);return{value:e?!!t.checked:t.value}}}}),h(["copy","cut","paste"],{createEventArgs:e=>({type:e.type})}),h(["drag","dragend","dragenter","dragleave","dragover","dragstart","drop"],{createEventArgs:e=>{return{...u(t=e),dataTransfer:t.dataTransfer?{dropEffect:t.dataTransfer.dropEffect,effectAllowed:t.dataTransfer.effectAllowed,files:Array.from(t.dataTransfer.files).map((e=>e.name)),items:Array.from(t.dataTransfer.items).map((e=>({kind:e.kind,type:e.type}))),types:t.dataTransfer.types}:null};var t}}),h(["focus","blur","focusin","focusout"],{createEventArgs:e=>({type:e.type})}),h(["keydown","keyup","keypress"],{createEventArgs:e=>{return{key:(t=e).key,code:t.code,location:t.location,repeat:t.repeat,ctrlKey:t.ctrlKey,shiftKey:t.shiftKey,altKey:t.altKey,metaKey:t.metaKey,type:t.type};var t}}),h(["contextmenu","click","mouseover","mouseout","mousemove","mousedown","mouseup","mouseleave","mouseenter","dblclick"],{createEventArgs:e=>u(e)}),h(["error"],{createEventArgs:e=>{return{message:(t=e).message,filename:t.filename,lineno:t.lineno,colno:t.colno,type:t.type};var t}}),h(["loadstart","timeout","abort","load","loadend","progress"],{createEventArgs:e=>{return{lengthComputable:(t=e).lengthComputable,loaded:t.loaded,total:t.total,type:t.type};var t}}),h(["touchcancel","touchend","touchmove","touchenter","touchleave","touchstart"],{createEventArgs:e=>{return{detail:(t=e).detail,touches:d(t.touches),targetTouches:d(t.targetTouches),changedTouches:d(t.changedTouches),ctrlKey:t.ctrlKey,shiftKey:t.shiftKey,altKey:t.altKey,metaKey:t.metaKey,type:t.type};var t}}),h(["gotpointercapture","lostpointercapture","pointercancel","pointerdown","pointerenter","pointerleave","pointermove","pointerout","pointerover","pointerup"],{createEventArgs:e=>{return{...u(t=e),pointerId:t.pointerId,width:t.width,height:t.height,pressure:t.pressure,tiltX:t.tiltX,tiltY:t.tiltY,pointerType:t.pointerType,isPrimary:t.isPrimary};var t}}),h(["wheel","mousewheel"],{createEventArgs:e=>{return{...u(t=e),deltaX:t.deltaX,deltaY:t.deltaY,deltaZ:t.deltaZ,deltaMode:t.deltaMode};var t}}),h(["toggle"],{createEventArgs:()=>({})});const p=["date","datetime-local","month","time","week"],f=new Map;let g,m,y=0;const v={async add(e,t,n){if(!n)throw new Error("initialParameters must be an object, even if empty.");const r="__bl-dynamic-root:"+(++y).toString();f.set(r,e);const o=await E().invokeMethodAsync("AddRootComponent",t,r),s=new _(o,m[t]);return await s.setParameters(n),s}};function w(e){const t=f.get(e);if(t)return f.delete(e),t}class b{invoke(e){return this._callback(e)}setCallback(t){this._selfJSObjectReference||(this._selfJSObjectReference=e.createJSObjectReference(this)),this._callback=t}getJSObjectReference(){return this._selfJSObjectReference}dispose(){this._selfJSObjectReference&&e.disposeJSObjectReference(this._selfJSObjectReference)}}class _{constructor(e,t){this._jsEventCallbackWrappers=new Map,this._componentId=e;for(const e of t)"eventcallback"===e.type&&this._jsEventCallbackWrappers.set(e.name.toLowerCase(),new b)}setParameters(e){const t={},n=Object.entries(e||{}),r=n.length;for(const[e,r]of n){const n=this._jsEventCallbackWrappers.get(e.toLowerCase());n&&r?(n.setCallback(r),t[e]=n.getJSObjectReference()):t[e]=r}return E().invokeMethodAsync("SetRootComponentParameters",this._componentId,r,t)}async dispose(){if(null!==this._componentId){await E().invokeMethodAsync("RemoveRootComponent",this._componentId),this._componentId=null;for(const e of this._jsEventCallbackWrappers.values())e.dispose()}}}function E(){if(!g)throw new Error("Dynamic root components have not been enabled in this application.");return g}const C=new Map,S=new Map,I=new Map;let k;const T=new Promise((e=>{k=e}));function D(e){return C.has(e)}function x(e){if(D(e))return Promise.resolve();let t=I.get(e);return t||(t=new Promise((t=>{S.set(e,t)})),I.set(e,t)),t}function N(e,t,n){return A(e,t.eventHandlerId,(()=>R(e).invokeMethodAsync("DispatchEventAsync",t,n)))}function R(e){const t=C.get(e);if(!t)throw new Error(`No interop methods are registered for renderer ${e}`);return t}let A=(e,t,n)=>n();const U=F(["abort","blur","canplay","canplaythrough","change","cuechange","durationchange","emptied","ended","error","focus","load","loadeddata","loadedmetadata","loadend","loadstart","mouseenter","mouseleave","pointerenter","pointerleave","pause","play","playing","progress","ratechange","reset","scroll","seeked","seeking","stalled","submit","suspend","timeupdate","toggle","unload","volumechange","waiting","DOMNodeInsertedIntoDocument","DOMNodeRemovedFromDocument"]),P={submit:!0},M=F(["click","dblclick","mousedown","mousemove","mouseup"]);class L{constructor(e){this.browserRendererId=e,this.afterClickCallbacks=[];const t=++L.nextEventDelegatorId;this.eventsCollectionKey=`_blazorEvents_${t}`,this.eventInfoStore=new B(this.onGlobalEvent.bind(this))}setListener(e,t,n,r){const o=this.getEventHandlerInfosForElement(e,!0),s=o.getHandler(t);if(s)this.eventInfoStore.update(s.eventHandlerId,n);else{const s={element:e,eventName:t,eventHandlerId:n,renderingComponentId:r};this.eventInfoStore.add(s),o.setHandler(t,s)}}getHandler(e){return this.eventInfoStore.get(e)}removeListener(e){const t=this.eventInfoStore.remove(e);if(t){const e=t.element,n=this.getEventHandlerInfosForElement(e,!1);n&&n.removeHandler(t.eventName)}}notifyAfterClick(e){this.afterClickCallbacks.push(e),this.eventInfoStore.addGlobalListener("click")}setStopPropagation(e,t,n){this.getEventHandlerInfosForElement(e,!0).stopPropagation(t,n)}setPreventDefault(e,t,n){this.getEventHandlerInfosForElement(e,!0).preventDefault(t,n)}onGlobalEvent(e){if(!(e.target instanceof Element))return;this.dispatchGlobalEventToAllElements(e.type,e);const t=(n=e.type,i.get(n));var n;t&&t.forEach((t=>this.dispatchGlobalEventToAllElements(t,e))),"click"===e.type&&this.afterClickCallbacks.forEach((t=>t(e)))}dispatchGlobalEventToAllElements(e,t){const n=t.composedPath();let r=n.shift(),s=null,i=!1;const a=Object.prototype.hasOwnProperty.call(U,e);let l=!1;for(;r;){const u=r,p=this.getEventHandlerInfosForElement(u,!1);if(p){const n=p.getHandler(e);if(n&&(h=u,d=t.type,!((h instanceof HTMLButtonElement||h instanceof HTMLInputElement||h instanceof HTMLTextAreaElement||h instanceof HTMLSelectElement)&&Object.prototype.hasOwnProperty.call(M,d)&&h.disabled))){if(!i){const n=c(e);s=(null==n?void 0:n.createEventArgs)?n.createEventArgs(t):{},i=!0}Object.prototype.hasOwnProperty.call(P,t.type)&&t.preventDefault(),N(this.browserRendererId,{eventHandlerId:n.eventHandlerId,eventName:e,eventFieldInfo:o.fromEvent(n.renderingComponentId,t)},s)}p.stopPropagation(e)&&(l=!0),p.preventDefault(e)&&t.preventDefault()}r=a||l?void 0:n.shift()}var h,d}getEventHandlerInfosForElement(e,t){return Object.prototype.hasOwnProperty.call(e,this.eventsCollectionKey)?e[this.eventsCollectionKey]:t?e[this.eventsCollectionKey]=new O:null}}L.nextEventDelegatorId=0;class B{constructor(e){this.globalListener=e,this.infosByEventHandlerId={},this.countByEventName={},a.push(this.handleEventNameAliasAdded.bind(this))}add(e){if(this.infosByEventHandlerId[e.eventHandlerId])throw new Error(`Event ${e.eventHandlerId} is already tracked`);this.infosByEventHandlerId[e.eventHandlerId]=e,this.addGlobalListener(e.eventName)}get(e){return this.infosByEventHandlerId[e]}addGlobalListener(e){if(e=l(e),Object.prototype.hasOwnProperty.call(this.countByEventName,e))this.countByEventName[e]++;else{this.countByEventName[e]=1;const t=Object.prototype.hasOwnProperty.call(U,e);document.addEventListener(e,this.globalListener,t)}}update(e,t){if(Object.prototype.hasOwnProperty.call(this.infosByEventHandlerId,t))throw new Error(`Event ${t} is already tracked`);const n=this.infosByEventHandlerId[e];delete this.infosByEventHandlerId[e],n.eventHandlerId=t,this.infosByEventHandlerId[t]=n}remove(e){const t=this.infosByEventHandlerId[e];if(t){delete this.infosByEventHandlerId[e];const n=l(t.eventName);0==--this.countByEventName[n]&&(delete this.countByEventName[n],document.removeEventListener(n,this.globalListener))}return t}handleEventNameAliasAdded(e,t){if(Object.prototype.hasOwnProperty.call(this.countByEventName,e)){const n=this.countByEventName[e];delete this.countByEventName[e],document.removeEventListener(e,this.globalListener),this.addGlobalListener(t),this.countByEventName[t]+=n-1}}}class O{constructor(){this.handlers={},this.preventDefaultFlags=null,this.stopPropagationFlags=null}getHandler(e){return Object.prototype.hasOwnProperty.call(this.handlers,e)?this.handlers[e]:null}setHandler(e,t){this.handlers[e]=t}removeHandler(e){delete this.handlers[e]}preventDefault(e,t){return void 0!==t&&(this.preventDefaultFlags=this.preventDefaultFlags||{},this.preventDefaultFlags[e]=t),!!this.preventDefaultFlags&&this.preventDefaultFlags[e]}stopPropagation(e,t){return void 0!==t&&(this.stopPropagationFlags=this.stopPropagationFlags||{},this.stopPropagationFlags[e]=t),!!this.stopPropagationFlags&&this.stopPropagationFlags[e]}}function F(e){const t={};return e.forEach((e=>{t[e]=!0})),t}const $=Symbol(),H=Symbol(),j=Symbol();function W(e){const{start:t,end:n}=e,r=t[j];if(r){if(r!==e)throw new Error("The start component comment was already associated with another component descriptor.");return t}const o=t.parentNode;if(!o)throw new Error(`Comment not connected to the DOM ${t.textContent}`);const s=J(o,!0),i=Z(s);t[H]=s,t[j]=e;const a=J(t);if(n){const e=Z(a),r=Array.prototype.indexOf.call(i,a)+1;let o=null;for(;o!==n;){const n=i.splice(r,1)[0];if(!n)throw new Error("Could not find the end component comment in the parent logical node list");n[H]=t,e.push(n),o=n}}return a}function J(e,t){if($ in e)return e;const n=[];if(e.childNodes.length>0){if(!t)throw new Error("New logical elements must start empty, or allowExistingContents must be true");e.childNodes.forEach((t=>{const r=J(t,!0);r[H]=e,n.push(r)}))}return e[$]=n,e}function z(e){const t=Z(e);for(;t.length;)K(e,0)}function q(e,t){const n=document.createComment("!");return V(n,e,t),n}function V(e,t,n){const r=e;let o=e;if(te(e)){const t=se(r);if(t!==e){const n=new Range;n.setStartBefore(e),n.setEndAfter(t),o=n.extractContents()}}const s=X(r);if(s){const e=Z(s),t=Array.prototype.indexOf.call(e,r);e.splice(t,1),delete r[H]}const i=Z(t);if(n0;)K(n,0)}const r=n;r.parentNode.removeChild(r)}function X(e){return e[H]||null}function G(e,t){return Z(e)[t]}function Y(e){return e[j]||null}function Q(e){const t=re(e);return"http://www.w3.org/2000/svg"===t.namespaceURI&&"foreignObject"!==t.tagName}function Z(e){return e[$]}function ee(e){const t=Z(X(e));return t[Array.prototype.indexOf.call(t,e)+1]||null}function te(e){return $ in e}function ne(e,t){const n=Z(e);t.forEach((e=>{e.moveRangeStart=n[e.fromSiblingIndex],e.moveRangeEnd=se(e.moveRangeStart)})),t.forEach((t=>{const r=document.createComment("marker");t.moveToBeforeMarker=r;const o=n[t.toSiblingIndex+1];o?o.parentNode.insertBefore(r,o):oe(r,e)})),t.forEach((e=>{const t=e.moveToBeforeMarker,n=t.parentNode,r=e.moveRangeStart,o=e.moveRangeEnd;let s=r;for(;s;){const e=s.nextSibling;if(n.insertBefore(s,t),s===o)break;s=e}n.removeChild(t)})),t.forEach((e=>{n[e.toSiblingIndex]=e.moveRangeStart}))}function re(e){if(e instanceof Element||e instanceof DocumentFragment)return e;if(e instanceof Comment)return e.parentNode;throw new Error("Not a valid logical element")}function oe(e,t){if(t instanceof Element||t instanceof DocumentFragment)t.appendChild(e);else{if(!(t instanceof Comment))throw new Error(`Cannot append node because the parent is not a valid logical element. Parent: ${t}`);{const n=ee(t);n?n.parentNode.insertBefore(e,n):oe(e,X(t))}}}function se(e){if(e instanceof Element||e instanceof DocumentFragment)return e;const t=ee(e);if(t)return t.previousSibling;{const t=X(e);return t instanceof Element||t instanceof DocumentFragment?t.lastChild:se(t)}}function ie(e){return`_bl_${e}`}const ae="__internalId";e.attachReviver(((e,t)=>t&&"object"==typeof t&&Object.prototype.hasOwnProperty.call(t,ae)&&"string"==typeof t[ae]?function(e){const t=`[${ie(e)}]`;return document.querySelector(t)}(t[ae]):t));const ce="_blazorDeferredValue";function le(e){e instanceof HTMLOptionElement?pe(e):ce in e&&ue(e,e[ce])}function he(e){return"select-multiple"===e.type}function de(e,t){e.value=t||""}function ue(e,t){e instanceof HTMLSelectElement?he(e)?function(e,t){t||(t=[]);for(let n=0;n{Ue()&&xe(e,(e=>{ze(e,!0,!1)}))}))}attachRootComponentToLogicalElement(e,t,n){if(be(t))throw new Error(`Root component '${e}' could not be attached because its target element is already associated with a root component`);we(t,!0),this.attachComponentToElement(e,t),this.rootComponentIds.add(e),n||(me[e]=t)}updateComponent(e,t,n,r){var o;const s=this.childComponentLocations[t];if(!s)throw new Error(`No element is currently associated with component ${t}`);const i=me[t];i&&(delete me[t],z(i),i instanceof Comment&&(i.textContent="!"));const a=null===(o=re(s))||void 0===o?void 0:o.getRootNode(),c=a&&a.activeElement;this.applyEdits(e,t,s,0,n,r),c instanceof HTMLElement&&a&&a.activeElement!==c&&c.focus()}disposeComponent(e){if(this.rootComponentIds.delete(e)){const t=this.childComponentLocations[e];we(t,!1),z(t)}delete this.childComponentLocations[e]}disposeEventHandler(e){this.eventDelegator.removeListener(e)}attachComponentToElement(e,t){this.childComponentLocations[e]=t}applyEdits(e,n,r,o,s,i){let a,c=0,l=o;const h=e.arrayBuilderSegmentReader,d=e.editReader,u=e.frameReader,p=h.values(s),f=h.offset(s),g=f+h.count(s);for(let s=f;sdocument.baseURI,getLocationHref:()=>location.href,scrollToElement:We};function We(e){const t=document.getElementById(e);return!!t&&(t.scrollIntoView(),!0)}function Je(e,t,n=!1){const r=Re(e);!t.forceLoad&&Ne(r)?ze(r,!1,t.replaceHistoryEntry,t.historyEntryState,n):function(e,t){if(location.href===e){const t=e+"?";history.replaceState(null,"",t),location.replace(e)}else t?location.replace(e):location.href=e}(e,t.replaceHistoryEntry)}async function ze(e,t,n,r=void 0,o=!1){if(Ke(),function(e){const t=e.indexOf("#");return t>-1&&location.href.replace(location.hash,"")===e.substring(0,t)}(e))!function(e,t,n){qe(e,t,n);const r=e.indexOf("#");r!==e.length-1&&We(e.substring(r+1))}(e,n,r);else{if(!o&&Me&&!await Xe(e,r,t))return;Se=!0,qe(e,n,r),await Ge(t)}}function qe(e,t,n=void 0){t?history.replaceState({userState:n,_index:Le},"",e):(Le++,history.pushState({userState:n,_index:Le},"",e))}function Ve(e){return new Promise((t=>{const n=$e;$e=()=>{$e=n,t()},history.go(e)}))}function Ke(){He&&(He(!1),He=null)}function Xe(e,t,n){return new Promise((r=>{Ke(),Fe?(Be++,He=r,Fe(Be,e,t,n)):r(!1)}))}async function Ge(e){var t;Oe&&await Oe(location.href,null===(t=history.state)||void 0===t?void 0:t.userState,e)}async function Ye(e){var t,n;$e&&await $e(e),Le=null!==(n=null===(t=history.state)||void 0===t?void 0:t._index)&&void 0!==n?n:0}const Qe={focus:function(e,t){if(e instanceof HTMLElement)e.focus({preventScroll:t});else{if(!(e instanceof SVGElement))throw new Error("Unable to focus an invalid element.");if(!e.hasAttribute("tabindex"))throw new Error("Unable to focus an SVG element that does not have a tabindex.");e.focus({preventScroll:t})}},focusBySelector:function(e,t){const n=document.querySelector(e);n&&(n.hasAttribute("tabindex")||(n.tabIndex=-1),n.focus({preventScroll:!0}))}},Ze={init:function(e,t,n,r=50){const o=tt(t);(o||document.documentElement).style.overflowAnchor="none";const s=document.createRange();h(n.parentElement)&&(t.style.display="table-row",n.style.display="table-row");const i=new IntersectionObserver((function(r){r.forEach((r=>{var o;if(!r.isIntersecting)return;s.setStartAfter(t),s.setEndBefore(n);const i=s.getBoundingClientRect().height,a=null===(o=r.rootBounds)||void 0===o?void 0:o.height;r.target===t?e.invokeMethodAsync("OnSpacerBeforeVisible",r.intersectionRect.top-r.boundingClientRect.top,i,a):r.target===n&&n.offsetHeight>0&&e.invokeMethodAsync("OnSpacerAfterVisible",r.boundingClientRect.bottom-r.intersectionRect.bottom,i,a)}))}),{root:o,rootMargin:`${r}px`});i.observe(t),i.observe(n);const a=l(t),c=l(n);function l(e){const t={attributes:!0},n=new MutationObserver(((n,r)=>{h(e.parentElement)&&(r.disconnect(),e.style.display="table-row",r.observe(e,t)),i.unobserve(e),i.observe(e)}));return n.observe(e,t),n}function h(e){return null!==e&&(e instanceof HTMLTableElement&&""===e.style.display||"table"===e.style.display||e instanceof HTMLTableSectionElement&&""===e.style.display||"table-row-group"===e.style.display)}et[e._id]={intersectionObserver:i,mutationObserverBefore:a,mutationObserverAfter:c}},dispose:function(e){const t=et[e._id];t&&(t.intersectionObserver.disconnect(),t.mutationObserverBefore.disconnect(),t.mutationObserverAfter.disconnect(),e.dispose(),delete et[e._id])}},et={};function tt(e){return e&&e!==document.body&&e!==document.documentElement?"visible"!==getComputedStyle(e).overflowY?e:tt(e.parentElement):null}const nt={getAndRemoveExistingTitle:function(){var e;const t=document.head?document.head.getElementsByTagName("title"):[];if(0===t.length)return null;let n=null;for(let r=t.length-1;r>=0;r--){const o=t[r],s=o.previousSibling;s instanceof Comment&&null!==X(s)||(null===n&&(n=o.textContent),null===(e=o.parentNode)||void 0===e||e.removeChild(o))}return n}},rt={init:function(e,t){t._blazorInputFileNextFileId=0,t.addEventListener("click",(function(){t.value=""})),t.addEventListener("change",(function(){t._blazorFilesById={};const n=Array.prototype.map.call(t.files,(function(e){const n={id:++t._blazorInputFileNextFileId,lastModified:new Date(e.lastModified).toISOString(),name:e.name,size:e.size,contentType:e.type,readPromise:void 0,arrayBuffer:void 0,blob:e};return t._blazorFilesById[n.id]=n,n}));e.invokeMethodAsync("NotifyChange",n)}))},toImageFile:async function(e,t,n,r,o){const s=ot(e,t),i=await new Promise((function(e){const t=new Image;t.onload=function(){URL.revokeObjectURL(t.src),e(t)},t.onerror=function(){t.onerror=null,URL.revokeObjectURL(t.src)},t.src=URL.createObjectURL(s.blob)})),a=await new Promise((function(e){var t;const s=Math.min(1,r/i.width),a=Math.min(1,o/i.height),c=Math.min(s,a),l=document.createElement("canvas");l.width=Math.round(i.width*c),l.height=Math.round(i.height*c),null===(t=l.getContext("2d"))||void 0===t||t.drawImage(i,0,0,l.width,l.height),l.toBlob(e,n)})),c={id:++e._blazorInputFileNextFileId,lastModified:s.lastModified,name:s.name,size:(null==a?void 0:a.size)||0,contentType:n,blob:a||s.blob};return e._blazorFilesById[c.id]=c,c},readFileData:async function(e,t){return ot(e,t).blob}};function ot(e,t){const n=e._blazorFilesById[t];if(!n)throw new Error(`There is no file with ID ${t}. The file list may have changed. See https://aka.ms/aspnet/blazor-input-file-multiple-selections.`);return n}const st=new Set,it={enableNavigationPrompt:function(e){0===st.size&&window.addEventListener("beforeunload",at),st.add(e)},disableNavigationPrompt:function(e){st.delete(e),0===st.size&&window.removeEventListener("beforeunload",at)}};function at(e){e.preventDefault(),e.returnValue=!0}async function ct(e,t,n){return e instanceof Blob?await async function(e,t,n){const r=e.slice(t,t+n),o=await r.arrayBuffer();return new Uint8Array(o)}(e,t,n):function(e,t,n){return new Uint8Array(e.buffer,e.byteOffset+t,n)}(e,t,n)}const lt=new Map,ht={navigateTo:function(e,t,n=!1){Je(e,t instanceof Object?t:{forceLoad:t,replaceHistoryEntry:n})},registerCustomEventType:function(e,t){if(!t)throw new Error("The options parameter is required.");if(s.has(e))throw new Error(`The event '${e}' is already registered.`);if(t.browserEventName){const n=i.get(t.browserEventName);n?n.push(e):i.set(t.browserEventName,[e]),a.forEach((n=>n(e,t.browserEventName)))}s.set(e,t)},rootComponents:v,_internal:{navigationManager:je,domWrapper:Qe,Virtualize:Ze,PageTitle:nt,InputFile:rt,NavigationLock:it,getJSDataStreamChunk:ct,attachWebRendererInterop:function(t,n,r,o){if(C.has(t))throw new Error(`Interop methods are already registered for renderer ${t}`);C.set(t,n),Object.keys(r).length>0&&function(t,n,r){if(g)throw new Error("Dynamic root components have already been enabled.");g=t,m=n;for(const[t,o]of Object.entries(r)){const r=e.findJSFunction(t,0);for(const e of o)r(e,n[e])}}(R(t),r,o),k(),function(e){const t=S.get(e);t&&(S.delete(e),I.delete(e),t())}(t)}}};window.Blazor=ht;const dt=[0,2e3,1e4,3e4,null];class ut{constructor(e){this._retryDelays=void 0!==e?[...e,null]:dt}nextRetryDelayInMilliseconds(e){return this._retryDelays[e.previousRetryCount]}}class pt{}pt.Authorization="Authorization",pt.Cookie="Cookie";class ft{constructor(e,t,n){this.statusCode=e,this.statusText=t,this.content=n}}class gt{get(e,t){return this.send({...t,method:"GET",url:e})}post(e,t){return this.send({...t,method:"POST",url:e})}delete(e,t){return this.send({...t,method:"DELETE",url:e})}getCookieString(e){return""}}class mt extends gt{constructor(e,t){super(),this._innerClient=e,this._accessTokenFactory=t}async send(e){let t=!0;this._accessTokenFactory&&(!this._accessToken||e.url&&e.url.indexOf("/negotiate?")>0)&&(t=!1,this._accessToken=await this._accessTokenFactory()),this._setAuthorizationHeader(e);const n=await this._innerClient.send(e);return t&&401===n.statusCode&&this._accessTokenFactory?(this._accessToken=await this._accessTokenFactory(),this._setAuthorizationHeader(e),await this._innerClient.send(e)):n}_setAuthorizationHeader(e){e.headers||(e.headers={}),this._accessToken?e.headers[pt.Authorization]=`Bearer ${this._accessToken}`:this._accessTokenFactory&&e.headers[pt.Authorization]&&delete e.headers[pt.Authorization]}getCookieString(e){return this._innerClient.getCookieString(e)}}class yt extends Error{constructor(e,t){const n=new.target.prototype;super(`${e}: Status code '${t}'`),this.statusCode=t,this.__proto__=n}}class vt extends Error{constructor(e="A timeout occurred."){const t=new.target.prototype;super(e),this.__proto__=t}}class wt extends Error{constructor(e="An abort occurred."){const t=new.target.prototype;super(e),this.__proto__=t}}class bt extends Error{constructor(e,t){const n=new.target.prototype;super(e),this.transport=t,this.errorType="UnsupportedTransportError",this.__proto__=n}}class _t extends Error{constructor(e,t){const n=new.target.prototype;super(e),this.transport=t,this.errorType="DisabledTransportError",this.__proto__=n}}class Et extends Error{constructor(e,t){const n=new.target.prototype;super(e),this.transport=t,this.errorType="FailedToStartTransportError",this.__proto__=n}}class Ct extends Error{constructor(e){const t=new.target.prototype;super(e),this.errorType="FailedToNegotiateWithServerError",this.__proto__=t}}class St extends Error{constructor(e,t){const n=new.target.prototype;super(e),this.innerErrors=t,this.__proto__=n}}var It;!function(e){e[e.Trace=0]="Trace",e[e.Debug=1]="Debug",e[e.Information=2]="Information",e[e.Warning=3]="Warning",e[e.Error=4]="Error",e[e.Critical=5]="Critical",e[e.None=6]="None"}(It||(It={}));class kt{constructor(){}log(e,t){}}kt.instance=new kt;const Tt="0.0.0-DEV_BUILD";class Dt{static isRequired(e,t){if(null==e)throw new Error(`The '${t}' argument is required.`)}static isNotEmpty(e,t){if(!e||e.match(/^\s*$/))throw new Error(`The '${t}' argument should not be empty.`)}static isIn(e,t,n){if(!(e in t))throw new Error(`Unknown ${n} value: ${e}.`)}}class xt{static get isBrowser(){return!xt.isNode&&"object"==typeof window&&"object"==typeof window.document}static get isWebWorker(){return!xt.isNode&&"object"==typeof self&&"importScripts"in self}static get isReactNative(){return!xt.isNode&&"object"==typeof window&&void 0===window.document}static get isNode(){return"undefined"!=typeof process&&process.release&&"node"===process.release.name}}function Nt(e,t){let n="";return Rt(e)?(n=`Binary data of length ${e.byteLength}`,t&&(n+=`. Content: '${function(e){const t=new Uint8Array(e);let n="";return t.forEach((e=>{n+=`0x${e<16?"0":""}${e.toString(16)} `})),n.substr(0,n.length-1)}(e)}'`)):"string"==typeof e&&(n=`String data of length ${e.length}`,t&&(n+=`. Content: '${e}'`)),n}function Rt(e){return e&&"undefined"!=typeof ArrayBuffer&&(e instanceof ArrayBuffer||e.constructor&&"ArrayBuffer"===e.constructor.name)}async function At(e,t,n,r,o,s){const i={},[a,c]=Mt();i[a]=c,e.log(It.Trace,`(${t} transport) sending data. ${Nt(o,s.logMessageContent)}.`);const l=Rt(o)?"arraybuffer":"text",h=await n.post(r,{content:o,headers:{...i,...s.headers},responseType:l,timeout:s.timeout,withCredentials:s.withCredentials});e.log(It.Trace,`(${t} transport) request complete. Response status: ${h.statusCode}.`)}class Ut{constructor(e,t){this._subject=e,this._observer=t}dispose(){const e=this._subject.observers.indexOf(this._observer);e>-1&&this._subject.observers.splice(e,1),0===this._subject.observers.length&&this._subject.cancelCallback&&this._subject.cancelCallback().catch((e=>{}))}}class Pt{constructor(e){this._minLevel=e,this.out=console}log(e,t){if(e>=this._minLevel){const n=`[${(new Date).toISOString()}] ${It[e]}: ${t}`;switch(e){case It.Critical:case It.Error:this.out.error(n);break;case It.Warning:this.out.warn(n);break;case It.Information:this.out.info(n);break;default:this.out.log(n)}}}}function Mt(){let e="X-SignalR-User-Agent";return xt.isNode&&(e="User-Agent"),[e,Lt(Tt,Bt(),xt.isNode?"NodeJS":"Browser",Ot())]}function Lt(e,t,n,r){let o="Microsoft SignalR/";const s=e.split(".");return o+=`${s[0]}.${s[1]}`,o+=` (${e}; `,o+=t&&""!==t?`${t}; `:"Unknown OS; ",o+=`${n}`,o+=r?`; ${r}`:"; Unknown Runtime Version",o+=")",o}function Bt(){if(!xt.isNode)return"";switch(process.platform){case"win32":return"Windows NT";case"darwin":return"macOS";case"linux":return"Linux";default:return process.platform}}function Ot(){if(xt.isNode)return process.versions.node}function Ft(e){return e.stack?e.stack:e.message?e.message:`${e}`}class $t extends gt{constructor(e){super(),this._logger=e;const t={_fetchType:void 0,_jar:void 0};var r;r=t,"undefined"==typeof fetch&&(r._jar=new(n(628).CookieJar),"undefined"==typeof fetch?r._fetchType=n(200):r._fetchType=fetch,r._fetchType=n(203)(r._fetchType,r._jar),1)?(this._fetchType=t._fetchType,this._jar=t._jar):this._fetchType=fetch.bind(function(){if("undefined"!=typeof globalThis)return globalThis;if("undefined"!=typeof self)return self;if("undefined"!=typeof window)return window;if(void 0!==n.g)return n.g;throw new Error("could not find global")}()),this._abortControllerType=AbortController;const o={_abortControllerType:this._abortControllerType};(function(e){return"undefined"==typeof AbortController&&(e._abortControllerType=n(778),!0)})(o)&&(this._abortControllerType=o._abortControllerType)}async send(e){if(e.abortSignal&&e.abortSignal.aborted)throw new wt;if(!e.method)throw new Error("No method defined.");if(!e.url)throw new Error("No url defined.");const t=new this._abortControllerType;let n;e.abortSignal&&(e.abortSignal.onabort=()=>{t.abort(),n=new wt});let r,o=null;if(e.timeout){const r=e.timeout;o=setTimeout((()=>{t.abort(),this._logger.log(It.Warning,"Timeout from HTTP request."),n=new vt}),r)}""===e.content&&(e.content=void 0),e.content&&(e.headers=e.headers||{},Rt(e.content)?e.headers["Content-Type"]="application/octet-stream":e.headers["Content-Type"]="text/plain;charset=UTF-8");try{r=await this._fetchType(e.url,{body:e.content,cache:"no-cache",credentials:!0===e.withCredentials?"include":"same-origin",headers:{"X-Requested-With":"XMLHttpRequest",...e.headers},method:e.method,mode:"cors",redirect:"follow",signal:t.signal})}catch(e){if(n)throw n;throw this._logger.log(It.Warning,`Error from HTTP request. ${e}.`),e}finally{o&&clearTimeout(o),e.abortSignal&&(e.abortSignal.onabort=null)}if(!r.ok){const e=await Ht(r,"text");throw new yt(e||r.statusText,r.status)}const s=Ht(r,e.responseType),i=await s;return new ft(r.status,r.statusText,i)}getCookieString(e){return""}}function Ht(e,t){let n;switch(t){case"arraybuffer":n=e.arrayBuffer();break;case"text":default:n=e.text();break;case"blob":case"document":case"json":throw new Error(`${t} is not supported.`)}return n}class jt extends gt{constructor(e){super(),this._logger=e}send(e){return e.abortSignal&&e.abortSignal.aborted?Promise.reject(new wt):e.method?e.url?new Promise(((t,n)=>{const r=new XMLHttpRequest;r.open(e.method,e.url,!0),r.withCredentials=void 0===e.withCredentials||e.withCredentials,r.setRequestHeader("X-Requested-With","XMLHttpRequest"),""===e.content&&(e.content=void 0),e.content&&(Rt(e.content)?r.setRequestHeader("Content-Type","application/octet-stream"):r.setRequestHeader("Content-Type","text/plain;charset=UTF-8"));const o=e.headers;o&&Object.keys(o).forEach((e=>{r.setRequestHeader(e,o[e])})),e.responseType&&(r.responseType=e.responseType),e.abortSignal&&(e.abortSignal.onabort=()=>{r.abort(),n(new wt)}),e.timeout&&(r.timeout=e.timeout),r.onload=()=>{e.abortSignal&&(e.abortSignal.onabort=null),r.status>=200&&r.status<300?t(new ft(r.status,r.statusText,r.response||r.responseText)):n(new yt(r.response||r.responseText||r.statusText,r.status))},r.onerror=()=>{this._logger.log(It.Warning,`Error from HTTP request. ${r.status}: ${r.statusText}.`),n(new yt(r.statusText,r.status))},r.ontimeout=()=>{this._logger.log(It.Warning,"Timeout from HTTP request."),n(new vt)},r.send(e.content)})):Promise.reject(new Error("No url defined.")):Promise.reject(new Error("No method defined."))}}class Wt extends gt{constructor(e){if(super(),"undefined"!=typeof fetch)this._httpClient=new $t(e);else{if("undefined"==typeof XMLHttpRequest)throw new Error("No usable HttpClient found.");this._httpClient=new jt(e)}}send(e){return e.abortSignal&&e.abortSignal.aborted?Promise.reject(new wt):e.method?e.url?this._httpClient.send(e):Promise.reject(new Error("No url defined.")):Promise.reject(new Error("No method defined."))}getCookieString(e){return this._httpClient.getCookieString(e)}}var Jt,zt,qt,Vt;!function(e){e[e.None=0]="None",e[e.WebSockets=1]="WebSockets",e[e.ServerSentEvents=2]="ServerSentEvents",e[e.LongPolling=4]="LongPolling"}(Jt||(Jt={})),function(e){e[e.Text=1]="Text",e[e.Binary=2]="Binary"}(zt||(zt={}));class Kt{constructor(){this._isAborted=!1,this.onabort=null}abort(){this._isAborted||(this._isAborted=!0,this.onabort&&this.onabort())}get signal(){return this}get aborted(){return this._isAborted}}class Xt{get pollAborted(){return this._pollAbort.aborted}constructor(e,t,n){this._httpClient=e,this._logger=t,this._pollAbort=new Kt,this._options=n,this._running=!1,this.onreceive=null,this.onclose=null}async connect(e,t){if(Dt.isRequired(e,"url"),Dt.isRequired(t,"transferFormat"),Dt.isIn(t,zt,"transferFormat"),this._url=e,this._logger.log(It.Trace,"(LongPolling transport) Connecting."),t===zt.Binary&&"undefined"!=typeof XMLHttpRequest&&"string"!=typeof(new XMLHttpRequest).responseType)throw new Error("Binary protocols over XmlHttpRequest not implementing advanced features are not supported.");const[n,r]=Mt(),o={[n]:r,...this._options.headers},s={abortSignal:this._pollAbort.signal,headers:o,timeout:1e5,withCredentials:this._options.withCredentials};t===zt.Binary&&(s.responseType="arraybuffer");const i=`${e}&_=${Date.now()}`;this._logger.log(It.Trace,`(LongPolling transport) polling: ${i}.`);const a=await this._httpClient.get(i,s);200!==a.statusCode?(this._logger.log(It.Error,`(LongPolling transport) Unexpected response code: ${a.statusCode}.`),this._closeError=new yt(a.statusText||"",a.statusCode),this._running=!1):this._running=!0,this._receiving=this._poll(this._url,s)}async _poll(e,t){try{for(;this._running;)try{const n=`${e}&_=${Date.now()}`;this._logger.log(It.Trace,`(LongPolling transport) polling: ${n}.`);const r=await this._httpClient.get(n,t);204===r.statusCode?(this._logger.log(It.Information,"(LongPolling transport) Poll terminated by server."),this._running=!1):200!==r.statusCode?(this._logger.log(It.Error,`(LongPolling transport) Unexpected response code: ${r.statusCode}.`),this._closeError=new yt(r.statusText||"",r.statusCode),this._running=!1):r.content?(this._logger.log(It.Trace,`(LongPolling transport) data received. ${Nt(r.content,this._options.logMessageContent)}.`),this.onreceive&&this.onreceive(r.content)):this._logger.log(It.Trace,"(LongPolling transport) Poll timed out, reissuing.")}catch(e){this._running?e instanceof vt?this._logger.log(It.Trace,"(LongPolling transport) Poll timed out, reissuing."):(this._closeError=e,this._running=!1):this._logger.log(It.Trace,`(LongPolling transport) Poll errored after shutdown: ${e.message}`)}}finally{this._logger.log(It.Trace,"(LongPolling transport) Polling complete."),this.pollAborted||this._raiseOnClose()}}async send(e){return this._running?At(this._logger,"LongPolling",this._httpClient,this._url,e,this._options):Promise.reject(new Error("Cannot send until the transport is connected"))}async stop(){this._logger.log(It.Trace,"(LongPolling transport) Stopping polling."),this._running=!1,this._pollAbort.abort();try{await this._receiving,this._logger.log(It.Trace,`(LongPolling transport) sending DELETE request to ${this._url}.`);const e={},[t,n]=Mt();e[t]=n;const r={headers:{...e,...this._options.headers},timeout:this._options.timeout,withCredentials:this._options.withCredentials};let o;try{await this._httpClient.delete(this._url,r)}catch(e){o=e}o?o instanceof yt&&(404===o.statusCode?this._logger.log(It.Trace,"(LongPolling transport) A 404 response was returned from sending a DELETE request."):this._logger.log(It.Trace,`(LongPolling transport) Error sending a DELETE request: ${o}`)):this._logger.log(It.Trace,"(LongPolling transport) DELETE request accepted.")}finally{this._logger.log(It.Trace,"(LongPolling transport) Stop finished."),this._raiseOnClose()}}_raiseOnClose(){if(this.onclose){let e="(LongPolling transport) Firing onclose event.";this._closeError&&(e+=" Error: "+this._closeError),this._logger.log(It.Trace,e),this.onclose(this._closeError)}}}class Gt{constructor(e,t,n,r){this._httpClient=e,this._accessToken=t,this._logger=n,this._options=r,this.onreceive=null,this.onclose=null}async connect(e,t){return Dt.isRequired(e,"url"),Dt.isRequired(t,"transferFormat"),Dt.isIn(t,zt,"transferFormat"),this._logger.log(It.Trace,"(SSE transport) Connecting."),this._url=e,this._accessToken&&(e+=(e.indexOf("?")<0?"?":"&")+`access_token=${encodeURIComponent(this._accessToken)}`),new Promise(((n,r)=>{let o,s=!1;if(t===zt.Text){if(xt.isBrowser||xt.isWebWorker)o=new this._options.EventSource(e,{withCredentials:this._options.withCredentials});else{const t=this._httpClient.getCookieString(e),n={};n.Cookie=t;const[r,s]=Mt();n[r]=s,o=new this._options.EventSource(e,{withCredentials:this._options.withCredentials,headers:{...n,...this._options.headers}})}try{o.onmessage=e=>{if(this.onreceive)try{this._logger.log(It.Trace,`(SSE transport) data received. ${Nt(e.data,this._options.logMessageContent)}.`),this.onreceive(e.data)}catch(e){return void this._close(e)}},o.onerror=e=>{s?this._close():r(new Error("EventSource failed to connect. The connection could not be found on the server, either the connection ID is not present on the server, or a proxy is refusing/buffering the connection. If you have multiple servers check that sticky sessions are enabled."))},o.onopen=()=>{this._logger.log(It.Information,`SSE connected to ${this._url}`),this._eventSource=o,s=!0,n()}}catch(e){return void r(e)}}else r(new Error("The Server-Sent Events transport only supports the 'Text' transfer format"))}))}async send(e){return this._eventSource?At(this._logger,"SSE",this._httpClient,this._url,e,this._options):Promise.reject(new Error("Cannot send until the transport is connected"))}stop(){return this._close(),Promise.resolve()}_close(e){this._eventSource&&(this._eventSource.close(),this._eventSource=void 0,this.onclose&&this.onclose(e))}}class Yt{constructor(e,t,n,r,o,s){this._logger=n,this._accessTokenFactory=t,this._logMessageContent=r,this._webSocketConstructor=o,this._httpClient=e,this.onreceive=null,this.onclose=null,this._headers=s}async connect(e,t){let n;return Dt.isRequired(e,"url"),Dt.isRequired(t,"transferFormat"),Dt.isIn(t,zt,"transferFormat"),this._logger.log(It.Trace,"(WebSockets transport) Connecting."),this._accessTokenFactory&&(n=await this._accessTokenFactory()),new Promise(((r,o)=>{let s;e=e.replace(/^http/,"ws");const i=this._httpClient.getCookieString(e);let a=!1;if(xt.isReactNative){const t={},[r,o]=Mt();t[r]=o,n&&(t[pt.Authorization]=`Bearer ${n}`),i&&(t[pt.Cookie]=i),s=new this._webSocketConstructor(e,void 0,{headers:{...t,...this._headers}})}else n&&(e+=(e.indexOf("?")<0?"?":"&")+`access_token=${encodeURIComponent(n)}`);s||(s=new this._webSocketConstructor(e)),t===zt.Binary&&(s.binaryType="arraybuffer"),s.onopen=t=>{this._logger.log(It.Information,`WebSocket connected to ${e}.`),this._webSocket=s,a=!0,r()},s.onerror=e=>{let t=null;t="undefined"!=typeof ErrorEvent&&e instanceof ErrorEvent?e.error:"There was an error with the transport",this._logger.log(It.Information,`(WebSockets transport) ${t}.`)},s.onmessage=e=>{if(this._logger.log(It.Trace,`(WebSockets transport) data received. ${Nt(e.data,this._logMessageContent)}.`),this.onreceive)try{this.onreceive(e.data)}catch(e){return void this._close(e)}},s.onclose=e=>{if(a)this._close(e);else{let t=null;t="undefined"!=typeof ErrorEvent&&e instanceof ErrorEvent?e.error:"WebSocket failed to connect. The connection could not be found on the server, either the endpoint may not be a SignalR endpoint, the connection ID is not present on the server, or there is a proxy blocking WebSockets. If you have multiple servers check that sticky sessions are enabled.",o(new Error(t))}}}))}send(e){return this._webSocket&&this._webSocket.readyState===this._webSocketConstructor.OPEN?(this._logger.log(It.Trace,`(WebSockets transport) sending data. ${Nt(e,this._logMessageContent)}.`),this._webSocket.send(e),Promise.resolve()):Promise.reject("WebSocket is not in the OPEN state")}stop(){return this._webSocket&&this._close(void 0),Promise.resolve()}_close(e){this._webSocket&&(this._webSocket.onclose=()=>{},this._webSocket.onmessage=()=>{},this._webSocket.onerror=()=>{},this._webSocket.close(),this._webSocket=void 0),this._logger.log(It.Trace,"(WebSockets transport) socket closed."),this.onclose&&(!this._isCloseEvent(e)||!1!==e.wasClean&&1e3===e.code?e instanceof Error?this.onclose(e):this.onclose():this.onclose(new Error(`WebSocket closed with status code: ${e.code} (${e.reason||"no reason given"}).`)))}_isCloseEvent(e){return e&&"boolean"==typeof e.wasClean&&"number"==typeof e.code}}class Qt{constructor(e,t={}){var n;if(this._stopPromiseResolver=()=>{},this.features={},this._negotiateVersion=1,Dt.isRequired(e,"url"),this._logger=void 0===(n=t.logger)?new Pt(It.Information):null===n?kt.instance:void 0!==n.log?n:new Pt(n),this.baseUrl=this._resolveUrl(e),(t=t||{}).logMessageContent=void 0!==t.logMessageContent&&t.logMessageContent,"boolean"!=typeof t.withCredentials&&void 0!==t.withCredentials)throw new Error("withCredentials option was not a 'boolean' or 'undefined' value");t.withCredentials=void 0===t.withCredentials||t.withCredentials,t.timeout=void 0===t.timeout?1e5:t.timeout,"undefined"==typeof WebSocket||t.WebSocket||(t.WebSocket=WebSocket),"undefined"==typeof EventSource||t.EventSource||(t.EventSource=EventSource),this._httpClient=new mt(t.httpClient||new Wt(this._logger),t.accessTokenFactory),this._connectionState="Disconnected",this._connectionStarted=!1,this._options=t,this.onreceive=null,this.onclose=null}async start(e){if(e=e||zt.Binary,Dt.isIn(e,zt,"transferFormat"),this._logger.log(It.Debug,`Starting connection with transfer format '${zt[e]}'.`),"Disconnected"!==this._connectionState)return Promise.reject(new Error("Cannot start an HttpConnection that is not in the 'Disconnected' state."));if(this._connectionState="Connecting",this._startInternalPromise=this._startInternal(e),await this._startInternalPromise,"Disconnecting"===this._connectionState){const e="Failed to start the HttpConnection before stop() was called.";return this._logger.log(It.Error,e),await this._stopPromise,Promise.reject(new wt(e))}if("Connected"!==this._connectionState){const e="HttpConnection.startInternal completed gracefully but didn't enter the connection into the connected state!";return this._logger.log(It.Error,e),Promise.reject(new wt(e))}this._connectionStarted=!0}send(e){return"Connected"!==this._connectionState?Promise.reject(new Error("Cannot send data if the connection is not in the 'Connected' State.")):(this._sendQueue||(this._sendQueue=new Zt(this.transport)),this._sendQueue.send(e))}async stop(e){return"Disconnected"===this._connectionState?(this._logger.log(It.Debug,`Call to HttpConnection.stop(${e}) ignored because the connection is already in the disconnected state.`),Promise.resolve()):"Disconnecting"===this._connectionState?(this._logger.log(It.Debug,`Call to HttpConnection.stop(${e}) ignored because the connection is already in the disconnecting state.`),this._stopPromise):(this._connectionState="Disconnecting",this._stopPromise=new Promise((e=>{this._stopPromiseResolver=e})),await this._stopInternal(e),void await this._stopPromise)}async _stopInternal(e){this._stopError=e;try{await this._startInternalPromise}catch(e){}if(this.transport){try{await this.transport.stop()}catch(e){this._logger.log(It.Error,`HttpConnection.transport.stop() threw error '${e}'.`),this._stopConnection()}this.transport=void 0}else this._logger.log(It.Debug,"HttpConnection.transport is undefined in HttpConnection.stop() because start() failed.")}async _startInternal(e){let t=this.baseUrl;this._accessTokenFactory=this._options.accessTokenFactory,this._httpClient._accessTokenFactory=this._accessTokenFactory;try{if(this._options.skipNegotiation){if(this._options.transport!==Jt.WebSockets)throw new Error("Negotiation can only be skipped when using the WebSocket transport directly.");this.transport=this._constructTransport(Jt.WebSockets),await this._startTransport(t,e)}else{let n=null,r=0;do{if(n=await this._getNegotiationResponse(t),"Disconnecting"===this._connectionState||"Disconnected"===this._connectionState)throw new wt("The connection was stopped during negotiation.");if(n.error)throw new Error(n.error);if(n.ProtocolVersion)throw new Error("Detected a connection attempt to an ASP.NET SignalR Server. This client only supports connecting to an ASP.NET Core SignalR Server. See https://aka.ms/signalr-core-differences for details.");if(n.url&&(t=n.url),n.accessToken){const e=n.accessToken;this._accessTokenFactory=()=>e,this._httpClient._accessToken=e,this._httpClient._accessTokenFactory=void 0}r++}while(n.url&&r<100);if(100===r&&n.url)throw new Error("Negotiate redirection limit exceeded.");await this._createTransport(t,this._options.transport,n,e)}this.transport instanceof Xt&&(this.features.inherentKeepAlive=!0),"Connecting"===this._connectionState&&(this._logger.log(It.Debug,"The HttpConnection connected successfully."),this._connectionState="Connected")}catch(e){return this._logger.log(It.Error,"Failed to start the connection: "+e),this._connectionState="Disconnected",this.transport=void 0,this._stopPromiseResolver(),Promise.reject(e)}}async _getNegotiationResponse(e){const t={},[n,r]=Mt();t[n]=r;const o=this._resolveNegotiateUrl(e);this._logger.log(It.Debug,`Sending negotiation request: ${o}.`);try{const e=await this._httpClient.post(o,{content:"",headers:{...t,...this._options.headers},timeout:this._options.timeout,withCredentials:this._options.withCredentials});if(200!==e.statusCode)return Promise.reject(new Error(`Unexpected status code returned from negotiate '${e.statusCode}'`));const n=JSON.parse(e.content);return(!n.negotiateVersion||n.negotiateVersion<1)&&(n.connectionToken=n.connectionId),n}catch(e){let t="Failed to complete negotiation with the server: "+e;return e instanceof yt&&404===e.statusCode&&(t+=" Either this is not a SignalR endpoint or there is a proxy blocking the connection."),this._logger.log(It.Error,t),Promise.reject(new Ct(t))}}_createConnectUrl(e,t){return t?e+(-1===e.indexOf("?")?"?":"&")+`id=${t}`:e}async _createTransport(e,t,n,r){let o=this._createConnectUrl(e,n.connectionToken);if(this._isITransport(t))return this._logger.log(It.Debug,"Connection was provided an instance of ITransport, using that directly."),this.transport=t,await this._startTransport(o,r),void(this.connectionId=n.connectionId);const s=[],i=n.availableTransports||[];let a=n;for(const n of i){const i=this._resolveTransportOrError(n,t,r);if(i instanceof Error)s.push(`${n.transport} failed:`),s.push(i);else if(this._isITransport(i)){if(this.transport=i,!a){try{a=await this._getNegotiationResponse(e)}catch(e){return Promise.reject(e)}o=this._createConnectUrl(e,a.connectionToken)}try{return await this._startTransport(o,r),void(this.connectionId=a.connectionId)}catch(e){if(this._logger.log(It.Error,`Failed to start the transport '${n.transport}': ${e}`),a=void 0,s.push(new Et(`${n.transport} failed: ${e}`,Jt[n.transport])),"Connecting"!==this._connectionState){const e="Failed to select transport before stop() was called.";return this._logger.log(It.Debug,e),Promise.reject(new wt(e))}}}}return s.length>0?Promise.reject(new St(`Unable to connect to the server with any of the available transports. ${s.join(" ")}`,s)):Promise.reject(new Error("None of the transports supported by the client are supported by the server."))}_constructTransport(e){switch(e){case Jt.WebSockets:if(!this._options.WebSocket)throw new Error("'WebSocket' is not supported in your environment.");return new Yt(this._httpClient,this._accessTokenFactory,this._logger,this._options.logMessageContent,this._options.WebSocket,this._options.headers||{});case Jt.ServerSentEvents:if(!this._options.EventSource)throw new Error("'EventSource' is not supported in your environment.");return new Gt(this._httpClient,this._httpClient._accessToken,this._logger,this._options);case Jt.LongPolling:return new Xt(this._httpClient,this._logger,this._options);default:throw new Error(`Unknown transport: ${e}.`)}}_startTransport(e,t){return this.transport.onreceive=this.onreceive,this.transport.onclose=e=>this._stopConnection(e),this.transport.connect(e,t)}_resolveTransportOrError(e,t,n){const r=Jt[e.transport];if(null==r)return this._logger.log(It.Debug,`Skipping transport '${e.transport}' because it is not supported by this client.`),new Error(`Skipping transport '${e.transport}' because it is not supported by this client.`);if(!function(e,t){return!e||0!=(t&e)}(t,r))return this._logger.log(It.Debug,`Skipping transport '${Jt[r]}' because it was disabled by the client.`),new _t(`'${Jt[r]}' is disabled by the client.`,r);if(!(e.transferFormats.map((e=>zt[e])).indexOf(n)>=0))return this._logger.log(It.Debug,`Skipping transport '${Jt[r]}' because it does not support the requested transfer format '${zt[n]}'.`),new Error(`'${Jt[r]}' does not support ${zt[n]}.`);if(r===Jt.WebSockets&&!this._options.WebSocket||r===Jt.ServerSentEvents&&!this._options.EventSource)return this._logger.log(It.Debug,`Skipping transport '${Jt[r]}' because it is not supported in your environment.'`),new bt(`'${Jt[r]}' is not supported in your environment.`,r);this._logger.log(It.Debug,`Selecting transport '${Jt[r]}'.`);try{return this._constructTransport(r)}catch(e){return e}}_isITransport(e){return e&&"object"==typeof e&&"connect"in e}_stopConnection(e){if(this._logger.log(It.Debug,`HttpConnection.stopConnection(${e}) called while in state ${this._connectionState}.`),this.transport=void 0,e=this._stopError||e,this._stopError=void 0,"Disconnected"!==this._connectionState){if("Connecting"===this._connectionState)throw this._logger.log(It.Warning,`Call to HttpConnection.stopConnection(${e}) was ignored because the connection is still in the connecting state.`),new Error(`HttpConnection.stopConnection(${e}) was called while the connection is still in the connecting state.`);if("Disconnecting"===this._connectionState&&this._stopPromiseResolver(),e?this._logger.log(It.Error,`Connection disconnected with error '${e}'.`):this._logger.log(It.Information,"Connection disconnected."),this._sendQueue&&(this._sendQueue.stop().catch((e=>{this._logger.log(It.Error,`TransportSendQueue.stop() threw error '${e}'.`)})),this._sendQueue=void 0),this.connectionId=void 0,this._connectionState="Disconnected",this._connectionStarted){this._connectionStarted=!1;try{this.onclose&&this.onclose(e)}catch(t){this._logger.log(It.Error,`HttpConnection.onclose(${e}) threw error '${t}'.`)}}}else this._logger.log(It.Debug,`Call to HttpConnection.stopConnection(${e}) was ignored because the connection is already in the disconnected state.`)}_resolveUrl(e){if(0===e.lastIndexOf("https://",0)||0===e.lastIndexOf("http://",0))return e;if(!xt.isBrowser)throw new Error(`Cannot resolve '${e}'.`);const t=window.document.createElement("a");return t.href=e,this._logger.log(It.Information,`Normalizing '${e}' to '${t.href}'.`),t.href}_resolveNegotiateUrl(e){const t=e.indexOf("?");let n=e.substring(0,-1===t?e.length:t);return"/"!==n[n.length-1]&&(n+="/"),n+="negotiate",n+=-1===t?"":e.substring(t),-1===n.indexOf("negotiateVersion")&&(n+=-1===t?"?":"&",n+="negotiateVersion="+this._negotiateVersion),n}}class Zt{constructor(e){this._transport=e,this._buffer=[],this._executing=!0,this._sendBufferedData=new en,this._transportResult=new en,this._sendLoopPromise=this._sendLoop()}send(e){return this._bufferData(e),this._transportResult||(this._transportResult=new en),this._transportResult.promise}stop(){return this._executing=!1,this._sendBufferedData.resolve(),this._sendLoopPromise}_bufferData(e){if(this._buffer.length&&typeof this._buffer[0]!=typeof e)throw new Error(`Expected data to be of type ${typeof this._buffer} but was of type ${typeof e}`);this._buffer.push(e),this._sendBufferedData.resolve()}async _sendLoop(){for(;;){if(await this._sendBufferedData.promise,!this._executing){this._transportResult&&this._transportResult.reject("Connection stopped.");break}this._sendBufferedData=new en;const e=this._transportResult;this._transportResult=void 0;const t="string"==typeof this._buffer[0]?this._buffer.join(""):Zt._concatBuffers(this._buffer);this._buffer.length=0;try{await this._transport.send(t),e.resolve()}catch(t){e.reject(t)}}}static _concatBuffers(e){const t=e.map((e=>e.byteLength)).reduce(((e,t)=>e+t)),n=new Uint8Array(t);let r=0;for(const t of e)n.set(new Uint8Array(t),r),r+=t.byteLength;return n.buffer}}class en{constructor(){this.promise=new Promise(((e,t)=>[this._resolver,this._rejecter]=[e,t]))}resolve(){this._resolver()}reject(e){this._rejecter(e)}}class tn{static write(e){return`${e}${tn.RecordSeparator}`}static parse(e){if(e[e.length-1]!==tn.RecordSeparator)throw new Error("Message is incomplete.");const t=e.split(tn.RecordSeparator);return t.pop(),t}}tn.RecordSeparatorCode=30,tn.RecordSeparator=String.fromCharCode(tn.RecordSeparatorCode);class nn{writeHandshakeRequest(e){return tn.write(JSON.stringify(e))}parseHandshakeResponse(e){let t,n;if(Rt(e)){const r=new Uint8Array(e),o=r.indexOf(tn.RecordSeparatorCode);if(-1===o)throw new Error("Message is incomplete.");const s=o+1;t=String.fromCharCode.apply(null,Array.prototype.slice.call(r.slice(0,s))),n=r.byteLength>s?r.slice(s).buffer:null}else{const r=e,o=r.indexOf(tn.RecordSeparator);if(-1===o)throw new Error("Message is incomplete.");const s=o+1;t=r.substring(0,s),n=r.length>s?r.substring(s):null}const r=tn.parse(t),o=JSON.parse(r[0]);if(o.type)throw new Error("Expected a handshake response from the server.");return[n,o]}}!function(e){e[e.Invocation=1]="Invocation",e[e.StreamItem=2]="StreamItem",e[e.Completion=3]="Completion",e[e.StreamInvocation=4]="StreamInvocation",e[e.CancelInvocation=5]="CancelInvocation",e[e.Ping=6]="Ping",e[e.Close=7]="Close"}(qt||(qt={}));class rn{constructor(){this.observers=[]}next(e){for(const t of this.observers)t.next(e)}error(e){for(const t of this.observers)t.error&&t.error(e)}complete(){for(const e of this.observers)e.complete&&e.complete()}subscribe(e){return this.observers.push(e),new Ut(this,e)}}!function(e){e.Disconnected="Disconnected",e.Connecting="Connecting",e.Connected="Connected",e.Disconnecting="Disconnecting",e.Reconnecting="Reconnecting"}(Vt||(Vt={}));class on{static create(e,t,n,r,o,s){return new on(e,t,n,r,o,s)}constructor(e,t,n,r,o,s){this._nextKeepAlive=0,this._freezeEventListener=()=>{this._logger.log(It.Warning,"The page is being frozen, this will likely lead to the connection being closed and messages being lost. For more information see the docs at https://learn.microsoft.com/aspnet/core/signalr/javascript-client#bsleep")},Dt.isRequired(e,"connection"),Dt.isRequired(t,"logger"),Dt.isRequired(n,"protocol"),this.serverTimeoutInMilliseconds=null!=o?o:3e4,this.keepAliveIntervalInMilliseconds=null!=s?s:15e3,this._logger=t,this._protocol=n,this.connection=e,this._reconnectPolicy=r,this._handshakeProtocol=new nn,this.connection.onreceive=e=>this._processIncomingData(e),this.connection.onclose=e=>this._connectionClosed(e),this._callbacks={},this._methods={},this._closedCallbacks=[],this._reconnectingCallbacks=[],this._reconnectedCallbacks=[],this._invocationId=0,this._receivedHandshakeResponse=!1,this._connectionState=Vt.Disconnected,this._connectionStarted=!1,this._cachedPingMessage=this._protocol.writeMessage({type:qt.Ping})}get state(){return this._connectionState}get connectionId(){return this.connection&&this.connection.connectionId||null}get baseUrl(){return this.connection.baseUrl||""}set baseUrl(e){if(this._connectionState!==Vt.Disconnected&&this._connectionState!==Vt.Reconnecting)throw new Error("The HubConnection must be in the Disconnected or Reconnecting state to change the url.");if(!e)throw new Error("The HubConnection url must be a valid url.");this.connection.baseUrl=e}start(){return this._startPromise=this._startWithStateTransitions(),this._startPromise}async _startWithStateTransitions(){if(this._connectionState!==Vt.Disconnected)return Promise.reject(new Error("Cannot start a HubConnection that is not in the 'Disconnected' state."));this._connectionState=Vt.Connecting,this._logger.log(It.Debug,"Starting HubConnection.");try{await this._startInternal(),xt.isBrowser&&window.document.addEventListener("freeze",this._freezeEventListener),this._connectionState=Vt.Connected,this._connectionStarted=!0,this._logger.log(It.Debug,"HubConnection connected successfully.")}catch(e){return this._connectionState=Vt.Disconnected,this._logger.log(It.Debug,`HubConnection failed to start successfully because of error '${e}'.`),Promise.reject(e)}}async _startInternal(){this._stopDuringStartError=void 0,this._receivedHandshakeResponse=!1;const e=new Promise(((e,t)=>{this._handshakeResolver=e,this._handshakeRejecter=t}));await this.connection.start(this._protocol.transferFormat);try{const t={protocol:this._protocol.name,version:this._protocol.version};if(this._logger.log(It.Debug,"Sending handshake request."),await this._sendMessage(this._handshakeProtocol.writeHandshakeRequest(t)),this._logger.log(It.Information,`Using HubProtocol '${this._protocol.name}'.`),this._cleanupTimeout(),this._resetTimeoutPeriod(),this._resetKeepAliveInterval(),await e,this._stopDuringStartError)throw this._stopDuringStartError;this.connection.features.inherentKeepAlive||await this._sendMessage(this._cachedPingMessage)}catch(e){throw this._logger.log(It.Debug,`Hub handshake failed with error '${e}' during start(). Stopping HubConnection.`),this._cleanupTimeout(),this._cleanupPingTimer(),await this.connection.stop(e),e}}async stop(){const e=this._startPromise;this._stopPromise=this._stopInternal(),await this._stopPromise;try{await e}catch(e){}}_stopInternal(e){if(this._connectionState===Vt.Disconnected)return this._logger.log(It.Debug,`Call to HubConnection.stop(${e}) ignored because it is already in the disconnected state.`),Promise.resolve();if(this._connectionState===Vt.Disconnecting)return this._logger.log(It.Debug,`Call to HttpConnection.stop(${e}) ignored because the connection is already in the disconnecting state.`),this._stopPromise;const t=this._connectionState;return this._connectionState=Vt.Disconnecting,this._logger.log(It.Debug,"Stopping HubConnection."),this._reconnectDelayHandle?(this._logger.log(It.Debug,"Connection stopped during reconnect delay. Done reconnecting."),clearTimeout(this._reconnectDelayHandle),this._reconnectDelayHandle=void 0,this._completeClose(),Promise.resolve()):(t===Vt.Connected&&this._sendCloseMessage(),this._cleanupTimeout(),this._cleanupPingTimer(),this._stopDuringStartError=e||new wt("The connection was stopped before the hub handshake could complete."),this.connection.stop(e))}async _sendCloseMessage(){try{await this._sendWithProtocol(this._createCloseMessage())}catch{}}stream(e,...t){const[n,r]=this._replaceStreamingParams(t),o=this._createStreamInvocation(e,t,r);let s;const i=new rn;return i.cancelCallback=()=>{const e=this._createCancelInvocation(o.invocationId);return delete this._callbacks[o.invocationId],s.then((()=>this._sendWithProtocol(e)))},this._callbacks[o.invocationId]=(e,t)=>{t?i.error(t):e&&(e.type===qt.Completion?e.error?i.error(new Error(e.error)):i.complete():i.next(e.item))},s=this._sendWithProtocol(o).catch((e=>{i.error(e),delete this._callbacks[o.invocationId]})),this._launchStreams(n,s),i}_sendMessage(e){return this._resetKeepAliveInterval(),this.connection.send(e)}_sendWithProtocol(e){return this._sendMessage(this._protocol.writeMessage(e))}send(e,...t){const[n,r]=this._replaceStreamingParams(t),o=this._sendWithProtocol(this._createInvocation(e,t,!0,r));return this._launchStreams(n,o),o}invoke(e,...t){const[n,r]=this._replaceStreamingParams(t),o=this._createInvocation(e,t,!1,r);return new Promise(((e,t)=>{this._callbacks[o.invocationId]=(n,r)=>{r?t(r):n&&(n.type===qt.Completion?n.error?t(new Error(n.error)):e(n.result):t(new Error(`Unexpected message type: ${n.type}`)))};const r=this._sendWithProtocol(o).catch((e=>{t(e),delete this._callbacks[o.invocationId]}));this._launchStreams(n,r)}))}on(e,t){e&&t&&(e=e.toLowerCase(),this._methods[e]||(this._methods[e]=[]),-1===this._methods[e].indexOf(t)&&this._methods[e].push(t))}off(e,t){if(!e)return;e=e.toLowerCase();const n=this._methods[e];if(n)if(t){const r=n.indexOf(t);-1!==r&&(n.splice(r,1),0===n.length&&delete this._methods[e])}else delete this._methods[e]}onclose(e){e&&this._closedCallbacks.push(e)}onreconnecting(e){e&&this._reconnectingCallbacks.push(e)}onreconnected(e){e&&this._reconnectedCallbacks.push(e)}_processIncomingData(e){if(this._cleanupTimeout(),this._receivedHandshakeResponse||(e=this._processHandshakeResponse(e),this._receivedHandshakeResponse=!0),e){const t=this._protocol.parseMessages(e,this._logger);for(const e of t)switch(e.type){case qt.Invocation:this._invokeClientMethod(e);break;case qt.StreamItem:case qt.Completion:{const t=this._callbacks[e.invocationId];if(t){e.type===qt.Completion&&delete this._callbacks[e.invocationId];try{t(e)}catch(e){this._logger.log(It.Error,`Stream callback threw error: ${Ft(e)}`)}}break}case qt.Ping:break;case qt.Close:{this._logger.log(It.Information,"Close message received from server.");const t=e.error?new Error("Server returned an error on close: "+e.error):void 0;!0===e.allowReconnect?this.connection.stop(t):this._stopPromise=this._stopInternal(t);break}default:this._logger.log(It.Warning,`Invalid message type: ${e.type}.`)}}this._resetTimeoutPeriod()}_processHandshakeResponse(e){let t,n;try{[n,t]=this._handshakeProtocol.parseHandshakeResponse(e)}catch(e){const t="Error parsing handshake response: "+e;this._logger.log(It.Error,t);const n=new Error(t);throw this._handshakeRejecter(n),n}if(t.error){const e="Server returned handshake error: "+t.error;this._logger.log(It.Error,e);const n=new Error(e);throw this._handshakeRejecter(n),n}return this._logger.log(It.Debug,"Server handshake complete."),this._handshakeResolver(),n}_resetKeepAliveInterval(){this.connection.features.inherentKeepAlive||(this._nextKeepAlive=(new Date).getTime()+this.keepAliveIntervalInMilliseconds,this._cleanupPingTimer())}_resetTimeoutPeriod(){if(!(this.connection.features&&this.connection.features.inherentKeepAlive||(this._timeoutHandle=setTimeout((()=>this.serverTimeout()),this.serverTimeoutInMilliseconds),void 0!==this._pingServerHandle))){let e=this._nextKeepAlive-(new Date).getTime();e<0&&(e=0),this._pingServerHandle=setTimeout((async()=>{if(this._connectionState===Vt.Connected)try{await this._sendMessage(this._cachedPingMessage)}catch{this._cleanupPingTimer()}}),e)}}serverTimeout(){this.connection.stop(new Error("Server timeout elapsed without receiving a message from the server."))}async _invokeClientMethod(e){const t=e.target.toLowerCase(),n=this._methods[t];if(!n)return this._logger.log(It.Warning,`No client method with the name '${t}' found.`),void(e.invocationId&&(this._logger.log(It.Warning,`No result given for '${t}' method and invocation ID '${e.invocationId}'.`),await this._sendWithProtocol(this._createCompletionMessage(e.invocationId,"Client didn't provide a result.",null))));const r=n.slice(),o=!!e.invocationId;let s,i,a;for(const n of r)try{const r=s;s=await n.apply(this,e.arguments),o&&s&&r&&(this._logger.log(It.Error,`Multiple results provided for '${t}'. Sending error to server.`),a=this._createCompletionMessage(e.invocationId,"Client provided multiple results.",null)),i=void 0}catch(e){i=e,this._logger.log(It.Error,`A callback for the method '${t}' threw error '${e}'.`)}a?await this._sendWithProtocol(a):o?(i?a=this._createCompletionMessage(e.invocationId,`${i}`,null):void 0!==s?a=this._createCompletionMessage(e.invocationId,null,s):(this._logger.log(It.Warning,`No result given for '${t}' method and invocation ID '${e.invocationId}'.`),a=this._createCompletionMessage(e.invocationId,"Client didn't provide a result.",null)),await this._sendWithProtocol(a)):s&&this._logger.log(It.Error,`Result given for '${t}' method but server is not expecting a result.`)}_connectionClosed(e){this._logger.log(It.Debug,`HubConnection.connectionClosed(${e}) called while in state ${this._connectionState}.`),this._stopDuringStartError=this._stopDuringStartError||e||new wt("The underlying connection was closed before the hub handshake could complete."),this._handshakeResolver&&this._handshakeResolver(),this._cancelCallbacksWithError(e||new Error("Invocation canceled due to the underlying connection being closed.")),this._cleanupTimeout(),this._cleanupPingTimer(),this._connectionState===Vt.Disconnecting?this._completeClose(e):this._connectionState===Vt.Connected&&this._reconnectPolicy?this._reconnect(e):this._connectionState===Vt.Connected&&this._completeClose(e)}_completeClose(e){if(this._connectionStarted){this._connectionState=Vt.Disconnected,this._connectionStarted=!1,xt.isBrowser&&window.document.removeEventListener("freeze",this._freezeEventListener);try{this._closedCallbacks.forEach((t=>t.apply(this,[e])))}catch(t){this._logger.log(It.Error,`An onclose callback called with error '${e}' threw error '${t}'.`)}}}async _reconnect(e){const t=Date.now();let n=0,r=void 0!==e?e:new Error("Attempting to reconnect due to a unknown error."),o=this._getNextRetryDelay(n++,0,r);if(null===o)return this._logger.log(It.Debug,"Connection not reconnecting because the IRetryPolicy returned null on the first reconnect attempt."),void this._completeClose(e);if(this._connectionState=Vt.Reconnecting,e?this._logger.log(It.Information,`Connection reconnecting because of error '${e}'.`):this._logger.log(It.Information,"Connection reconnecting."),0!==this._reconnectingCallbacks.length){try{this._reconnectingCallbacks.forEach((t=>t.apply(this,[e])))}catch(t){this._logger.log(It.Error,`An onreconnecting callback called with error '${e}' threw error '${t}'.`)}if(this._connectionState!==Vt.Reconnecting)return void this._logger.log(It.Debug,"Connection left the reconnecting state in onreconnecting callback. Done reconnecting.")}for(;null!==o;){if(this._logger.log(It.Information,`Reconnect attempt number ${n} will start in ${o} ms.`),await new Promise((e=>{this._reconnectDelayHandle=setTimeout(e,o)})),this._reconnectDelayHandle=void 0,this._connectionState!==Vt.Reconnecting)return void this._logger.log(It.Debug,"Connection left the reconnecting state during reconnect delay. Done reconnecting.");try{if(await this._startInternal(),this._connectionState=Vt.Connected,this._logger.log(It.Information,"HubConnection reconnected successfully."),0!==this._reconnectedCallbacks.length)try{this._reconnectedCallbacks.forEach((e=>e.apply(this,[this.connection.connectionId])))}catch(e){this._logger.log(It.Error,`An onreconnected callback called with connectionId '${this.connection.connectionId}; threw error '${e}'.`)}return}catch(e){if(this._logger.log(It.Information,`Reconnect attempt failed because of error '${e}'.`),this._connectionState!==Vt.Reconnecting)return this._logger.log(It.Debug,`Connection moved to the '${this._connectionState}' from the reconnecting state during reconnect attempt. Done reconnecting.`),void(this._connectionState===Vt.Disconnecting&&this._completeClose());r=e instanceof Error?e:new Error(e.toString()),o=this._getNextRetryDelay(n++,Date.now()-t,r)}}this._logger.log(It.Information,`Reconnect retries have been exhausted after ${Date.now()-t} ms and ${n} failed attempts. Connection disconnecting.`),this._completeClose()}_getNextRetryDelay(e,t,n){try{return this._reconnectPolicy.nextRetryDelayInMilliseconds({elapsedMilliseconds:t,previousRetryCount:e,retryReason:n})}catch(n){return this._logger.log(It.Error,`IRetryPolicy.nextRetryDelayInMilliseconds(${e}, ${t}) threw error '${n}'.`),null}}_cancelCallbacksWithError(e){const t=this._callbacks;this._callbacks={},Object.keys(t).forEach((n=>{const r=t[n];try{r(null,e)}catch(t){this._logger.log(It.Error,`Stream 'error' callback called with '${e}' threw error: ${Ft(t)}`)}}))}_cleanupPingTimer(){this._pingServerHandle&&(clearTimeout(this._pingServerHandle),this._pingServerHandle=void 0)}_cleanupTimeout(){this._timeoutHandle&&clearTimeout(this._timeoutHandle)}_createInvocation(e,t,n,r){if(n)return 0!==r.length?{arguments:t,streamIds:r,target:e,type:qt.Invocation}:{arguments:t,target:e,type:qt.Invocation};{const n=this._invocationId;return this._invocationId++,0!==r.length?{arguments:t,invocationId:n.toString(),streamIds:r,target:e,type:qt.Invocation}:{arguments:t,invocationId:n.toString(),target:e,type:qt.Invocation}}}_launchStreams(e,t){if(0!==e.length){t||(t=Promise.resolve());for(const n in e)e[n].subscribe({complete:()=>{t=t.then((()=>this._sendWithProtocol(this._createCompletionMessage(n))))},error:e=>{let r;r=e instanceof Error?e.message:e&&e.toString?e.toString():"Unknown error",t=t.then((()=>this._sendWithProtocol(this._createCompletionMessage(n,r))))},next:e=>{t=t.then((()=>this._sendWithProtocol(this._createStreamItemMessage(n,e))))}})}}_replaceStreamingParams(e){const t=[],n=[];for(let r=0;r=55296&&o<=56319&&r65535&&(h-=65536,s.push(h>>>10&1023|55296),h=56320|1023&h),s.push(h)}else s.push(a);s.length>=4096&&(i+=String.fromCharCode.apply(String,s),s.length=0)}return s.length>0&&(i+=String.fromCharCode.apply(String,s)),i}var _n,En=gn?new TextDecoder:null,Cn=gn?"undefined"!=typeof process&&"force"!==(null===(dn=null===process||void 0===process?void 0:process.env)||void 0===dn?void 0:dn.TEXT_DECODER)?200:0:un,Sn=function(e,t){this.type=e,this.data=t},In=(_n=function(e,t){return _n=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=t[n])},_n(e,t)},function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");function n(){this.constructor=e}_n(e,t),e.prototype=null===t?Object.create(t):(n.prototype=t.prototype,new n)}),kn=function(e){function t(n){var r=e.call(this,n)||this,o=Object.create(t.prototype);return Object.setPrototypeOf(r,o),Object.defineProperty(r,"name",{configurable:!0,enumerable:!1,value:t.name}),r}return In(t,e),t}(Error),Tn={type:-1,encode:function(e){var t,n,r,o;return e instanceof Date?function(e){var t,n=e.sec,r=e.nsec;if(n>=0&&r>=0&&n<=17179869183){if(0===r&&n<=4294967295){var o=new Uint8Array(4);return(t=new DataView(o.buffer)).setUint32(0,n),o}var s=n/4294967296,i=4294967295&n;return o=new Uint8Array(8),(t=new DataView(o.buffer)).setUint32(0,r<<2|3&s),t.setUint32(4,i),o}return o=new Uint8Array(12),(t=new DataView(o.buffer)).setUint32(0,r),pn(t,4,n),o}((r=1e6*((t=e.getTime())-1e3*(n=Math.floor(t/1e3))),{sec:n+(o=Math.floor(r/1e9)),nsec:r-1e9*o})):null},decode:function(e){var t=function(e){var t=new DataView(e.buffer,e.byteOffset,e.byteLength);switch(e.byteLength){case 4:return{sec:t.getUint32(0),nsec:0};case 8:var n=t.getUint32(0);return{sec:4294967296*(3&n)+t.getUint32(4),nsec:n>>>2};case 12:return{sec:fn(t,4),nsec:t.getUint32(0)};default:throw new kn("Unrecognized data size for timestamp (expected 4, 8, or 12): ".concat(e.length))}}(e);return new Date(1e3*t.sec+t.nsec/1e6)}},Dn=function(){function e(){this.builtInEncoders=[],this.builtInDecoders=[],this.encoders=[],this.decoders=[],this.register(Tn)}return e.prototype.register=function(e){var t=e.type,n=e.encode,r=e.decode;if(t>=0)this.encoders[t]=n,this.decoders[t]=r;else{var o=1+t;this.builtInEncoders[o]=n,this.builtInDecoders[o]=r}},e.prototype.tryToEncode=function(e,t){for(var n=0;nthis.maxDepth)throw new Error("Too deep objects in depth ".concat(t));null==e?this.encodeNil():"boolean"==typeof e?this.encodeBoolean(e):"number"==typeof e?this.encodeNumber(e):"string"==typeof e?this.encodeString(e):this.encodeObject(e,t)},e.prototype.ensureBufferSizeToWrite=function(e){var t=this.pos+e;this.view.byteLength=0?e<128?this.writeU8(e):e<256?(this.writeU8(204),this.writeU8(e)):e<65536?(this.writeU8(205),this.writeU16(e)):e<4294967296?(this.writeU8(206),this.writeU32(e)):(this.writeU8(207),this.writeU64(e)):e>=-32?this.writeU8(224|e+32):e>=-128?(this.writeU8(208),this.writeI8(e)):e>=-32768?(this.writeU8(209),this.writeI16(e)):e>=-2147483648?(this.writeU8(210),this.writeI32(e)):(this.writeU8(211),this.writeI64(e)):this.forceFloat32?(this.writeU8(202),this.writeF32(e)):(this.writeU8(203),this.writeF64(e))},e.prototype.writeStringHeader=function(e){if(e<32)this.writeU8(160+e);else if(e<256)this.writeU8(217),this.writeU8(e);else if(e<65536)this.writeU8(218),this.writeU16(e);else{if(!(e<4294967296))throw new Error("Too long string: ".concat(e," bytes in UTF-8"));this.writeU8(219),this.writeU32(e)}},e.prototype.encodeString=function(e){if(e.length>vn){var t=mn(e);this.ensureBufferSizeToWrite(5+t),this.writeStringHeader(t),wn(e,this.bytes,this.pos),this.pos+=t}else t=mn(e),this.ensureBufferSizeToWrite(5+t),this.writeStringHeader(t),function(e,t,n){for(var r=e.length,o=n,s=0;s>6&31|192;else{if(i>=55296&&i<=56319&&s>12&15|224,t[o++]=i>>6&63|128):(t[o++]=i>>18&7|240,t[o++]=i>>12&63|128,t[o++]=i>>6&63|128)}t[o++]=63&i|128}else t[o++]=i}}(e,this.bytes,this.pos),this.pos+=t},e.prototype.encodeObject=function(e,t){var n=this.extensionCodec.tryToEncode(e,this.context);if(null!=n)this.encodeExtension(n);else if(Array.isArray(e))this.encodeArray(e,t);else if(ArrayBuffer.isView(e))this.encodeBinary(e);else{if("object"!=typeof e)throw new Error("Unrecognized object: ".concat(Object.prototype.toString.apply(e)));this.encodeMap(e,t)}},e.prototype.encodeBinary=function(e){var t=e.byteLength;if(t<256)this.writeU8(196),this.writeU8(t);else if(t<65536)this.writeU8(197),this.writeU16(t);else{if(!(t<4294967296))throw new Error("Too large binary: ".concat(t));this.writeU8(198),this.writeU32(t)}var n=xn(e);this.writeU8a(n)},e.prototype.encodeArray=function(e,t){var n=e.length;if(n<16)this.writeU8(144+n);else if(n<65536)this.writeU8(220),this.writeU16(n);else{if(!(n<4294967296))throw new Error("Too large array: ".concat(n));this.writeU8(221),this.writeU32(n)}for(var r=0,o=e;r0&&e<=this.maxKeyLength},e.prototype.find=function(e,t,n){e:for(var r=0,o=this.caches[n-1];r=this.maxLengthPerKey?n[Math.random()*n.length|0]=r:n.push(r)},e.prototype.decode=function(e,t,n){var r=this.find(e,t,n);if(null!=r)return this.hit++,r;this.miss++;var o=bn(e,t,n),s=Uint8Array.prototype.slice.call(e,t,t+n);return this.store(s,o),o},e}(),Un=function(e,t){var n,r,o,s,i={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]};return s={next:a(0),throw:a(1),return:a(2)},"function"==typeof Symbol&&(s[Symbol.iterator]=function(){return this}),s;function a(s){return function(a){return function(s){if(n)throw new TypeError("Generator is already executing.");for(;i;)try{if(n=1,r&&(o=2&s[0]?r.return:s[0]?r.throw||((o=r.return)&&o.call(r),0):r.next)&&!(o=o.call(r,s[1])).done)return o;switch(r=0,o&&(s=[2&s[0],o.value]),s[0]){case 0:case 1:o=s;break;case 4:return i.label++,{value:s[1],done:!1};case 5:i.label++,r=s[1],s=[0];continue;case 7:s=i.ops.pop(),i.trys.pop();continue;default:if(!((o=(o=i.trys).length>0&&o[o.length-1])||6!==s[0]&&2!==s[0])){i=0;continue}if(3===s[0]&&(!o||s[1]>o[0]&&s[1]=e},e.prototype.createExtraByteError=function(e){var t=this.view,n=this.pos;return new RangeError("Extra ".concat(t.byteLength-n," of ").concat(t.byteLength," byte(s) found at buffer[").concat(e,"]"))},e.prototype.decode=function(e){this.reinitializeState(),this.setBuffer(e);var t=this.doDecodeSync();if(this.hasRemaining(1))throw this.createExtraByteError(this.pos);return t},e.prototype.decodeMulti=function(e){return Un(this,(function(t){switch(t.label){case 0:this.reinitializeState(),this.setBuffer(e),t.label=1;case 1:return this.hasRemaining(1)?[4,this.doDecodeSync()]:[3,3];case 2:return t.sent(),[3,1];case 3:return[2]}}))},e.prototype.decodeAsync=function(e){var t,n,r,o,s,i,a;return s=this,void 0,a=function(){var s,i,a,c,l,h,d,u;return Un(this,(function(p){switch(p.label){case 0:s=!1,p.label=1;case 1:p.trys.push([1,6,7,12]),t=Pn(e),p.label=2;case 2:return[4,t.next()];case 3:if((n=p.sent()).done)return[3,5];if(a=n.value,s)throw this.createExtraByteError(this.totalPos);this.appendBuffer(a);try{i=this.doDecodeSync(),s=!0}catch(e){if(!(e instanceof On))throw e}this.totalPos+=this.pos,p.label=4;case 4:return[3,2];case 5:return[3,12];case 6:return c=p.sent(),r={error:c},[3,12];case 7:return p.trys.push([7,,10,11]),n&&!n.done&&(o=t.return)?[4,o.call(t)]:[3,9];case 8:p.sent(),p.label=9;case 9:return[3,11];case 10:if(r)throw r.error;return[7];case 11:return[7];case 12:if(s){if(this.hasRemaining(1))throw this.createExtraByteError(this.totalPos);return[2,i]}throw h=(l=this).headByte,d=l.pos,u=l.totalPos,new RangeError("Insufficient data in parsing ".concat(Rn(h)," at ").concat(u," (").concat(d," in the current buffer)"))}}))},new((i=void 0)||(i=Promise))((function(e,t){function n(e){try{o(a.next(e))}catch(e){t(e)}}function r(e){try{o(a.throw(e))}catch(e){t(e)}}function o(t){var o;t.done?e(t.value):(o=t.value,o instanceof i?o:new i((function(e){e(o)}))).then(n,r)}o((a=a.apply(s,[])).next())}))},e.prototype.decodeArrayStream=function(e){return this.decodeMultiAsync(e,!0)},e.prototype.decodeStream=function(e){return this.decodeMultiAsync(e,!1)},e.prototype.decodeMultiAsync=function(e,t){return function(n,r,o){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var s,i=function(){var n,r,o,s,i,a,c,l,h;return Un(this,(function(d){switch(d.label){case 0:n=t,r=-1,d.label=1;case 1:d.trys.push([1,13,14,19]),o=Pn(e),d.label=2;case 2:return[4,Mn(o.next())];case 3:if((s=d.sent()).done)return[3,12];if(i=s.value,t&&0===r)throw this.createExtraByteError(this.totalPos);this.appendBuffer(i),n&&(r=this.readArraySize(),n=!1,this.complete()),d.label=4;case 4:d.trys.push([4,9,,10]),d.label=5;case 5:return[4,Mn(this.doDecodeSync())];case 6:return[4,d.sent()];case 7:return d.sent(),0==--r?[3,8]:[3,5];case 8:return[3,10];case 9:if(!((a=d.sent())instanceof On))throw a;return[3,10];case 10:this.totalPos+=this.pos,d.label=11;case 11:return[3,2];case 12:return[3,19];case 13:return c=d.sent(),l={error:c},[3,19];case 14:return d.trys.push([14,,17,18]),s&&!s.done&&(h=o.return)?[4,Mn(h.call(o))]:[3,16];case 15:d.sent(),d.label=16;case 16:return[3,18];case 17:if(l)throw l.error;return[7];case 18:return[7];case 19:return[2]}}))}.apply(n,r||[]),a=[];return s={},c("next"),c("throw"),c("return"),s[Symbol.asyncIterator]=function(){return this},s;function c(e){i[e]&&(s[e]=function(t){return new Promise((function(n,r){a.push([e,t,n,r])>1||l(e,t)}))})}function l(e,t){try{(n=i[e](t)).value instanceof Mn?Promise.resolve(n.value.v).then(h,d):u(a[0][2],n)}catch(e){u(a[0][3],e)}var n}function h(e){l("next",e)}function d(e){l("throw",e)}function u(e,t){e(t),a.shift(),a.length&&l(a[0][0],a[0][1])}}(this,arguments)},e.prototype.doDecodeSync=function(){e:for(;;){var e=this.readHeadByte(),t=void 0;if(e>=224)t=e-256;else if(e<192)if(e<128)t=e;else if(e<144){if(0!=(r=e-128)){this.pushMapState(r),this.complete();continue e}t={}}else if(e<160){if(0!=(r=e-144)){this.pushArrayState(r),this.complete();continue e}t=[]}else{var n=e-160;t=this.decodeUtf8String(n,0)}else if(192===e)t=null;else if(194===e)t=!1;else if(195===e)t=!0;else if(202===e)t=this.readF32();else if(203===e)t=this.readF64();else if(204===e)t=this.readU8();else if(205===e)t=this.readU16();else if(206===e)t=this.readU32();else if(207===e)t=this.readU64();else if(208===e)t=this.readI8();else if(209===e)t=this.readI16();else if(210===e)t=this.readI32();else if(211===e)t=this.readI64();else if(217===e)n=this.lookU8(),t=this.decodeUtf8String(n,1);else if(218===e)n=this.lookU16(),t=this.decodeUtf8String(n,2);else if(219===e)n=this.lookU32(),t=this.decodeUtf8String(n,4);else if(220===e){if(0!==(r=this.readU16())){this.pushArrayState(r),this.complete();continue e}t=[]}else if(221===e){if(0!==(r=this.readU32())){this.pushArrayState(r),this.complete();continue e}t=[]}else if(222===e){if(0!==(r=this.readU16())){this.pushMapState(r),this.complete();continue e}t={}}else if(223===e){if(0!==(r=this.readU32())){this.pushMapState(r),this.complete();continue e}t={}}else if(196===e){var r=this.lookU8();t=this.decodeBinary(r,1)}else if(197===e)r=this.lookU16(),t=this.decodeBinary(r,2);else if(198===e)r=this.lookU32(),t=this.decodeBinary(r,4);else if(212===e)t=this.decodeExtension(1,0);else if(213===e)t=this.decodeExtension(2,0);else if(214===e)t=this.decodeExtension(4,0);else if(215===e)t=this.decodeExtension(8,0);else if(216===e)t=this.decodeExtension(16,0);else if(199===e)r=this.lookU8(),t=this.decodeExtension(r,1);else if(200===e)r=this.lookU16(),t=this.decodeExtension(r,2);else{if(201!==e)throw new kn("Unrecognized type byte: ".concat(Rn(e)));r=this.lookU32(),t=this.decodeExtension(r,4)}this.complete();for(var o=this.stack;o.length>0;){var s=o[o.length-1];if(0===s.type){if(s.array[s.position]=t,s.position++,s.position!==s.size)continue e;o.pop(),t=s.array}else{if(1===s.type){if("string"!=(i=typeof t)&&"number"!==i)throw new kn("The type of key must be string or number but "+typeof t);if("__proto__"===t)throw new kn("The key __proto__ is not allowed");s.key=t,s.type=2;continue e}if(s.map[s.key]=t,s.readCount++,s.readCount!==s.size){s.key=null,s.type=1;continue e}o.pop(),t=s.map}}return t}var i},e.prototype.readHeadByte=function(){return-1===this.headByte&&(this.headByte=this.readU8()),this.headByte},e.prototype.complete=function(){this.headByte=-1},e.prototype.readArraySize=function(){var e=this.readHeadByte();switch(e){case 220:return this.readU16();case 221:return this.readU32();default:if(e<160)return e-144;throw new kn("Unrecognized array type byte: ".concat(Rn(e)))}},e.prototype.pushMapState=function(e){if(e>this.maxMapLength)throw new kn("Max length exceeded: map length (".concat(e,") > maxMapLengthLength (").concat(this.maxMapLength,")"));this.stack.push({type:1,size:e,key:null,readCount:0,map:{}})},e.prototype.pushArrayState=function(e){if(e>this.maxArrayLength)throw new kn("Max length exceeded: array length (".concat(e,") > maxArrayLength (").concat(this.maxArrayLength,")"));this.stack.push({type:0,size:e,array:new Array(e),position:0})},e.prototype.decodeUtf8String=function(e,t){var n;if(e>this.maxStrLength)throw new kn("Max length exceeded: UTF-8 byte length (".concat(e,") > maxStrLength (").concat(this.maxStrLength,")"));if(this.bytes.byteLengthCn?function(e,t,n){var r=e.subarray(t,t+n);return En.decode(r)}(this.bytes,o,e):bn(this.bytes,o,e),this.pos+=t+e,r},e.prototype.stateIsMapKey=function(){return this.stack.length>0&&1===this.stack[this.stack.length-1].type},e.prototype.decodeBinary=function(e,t){if(e>this.maxBinLength)throw new kn("Max length exceeded: bin length (".concat(e,") > maxBinLength (").concat(this.maxBinLength,")"));if(!this.hasRemaining(e+t))throw Fn;var n=this.pos+t,r=this.bytes.subarray(n,n+e);return this.pos+=t+e,r},e.prototype.decodeExtension=function(e,t){if(e>this.maxExtLength)throw new kn("Max length exceeded: ext length (".concat(e,") > maxExtLength (").concat(this.maxExtLength,")"));var n=this.view.getInt8(this.pos+t),r=this.decodeBinary(e,t+1);return this.extensionCodec.decode(r,n,this.context)},e.prototype.lookU8=function(){return this.view.getUint8(this.pos)},e.prototype.lookU16=function(){return this.view.getUint16(this.pos)},e.prototype.lookU32=function(){return this.view.getUint32(this.pos)},e.prototype.readU8=function(){var e=this.view.getUint8(this.pos);return this.pos++,e},e.prototype.readI8=function(){var e=this.view.getInt8(this.pos);return this.pos++,e},e.prototype.readU16=function(){var e=this.view.getUint16(this.pos);return this.pos+=2,e},e.prototype.readI16=function(){var e=this.view.getInt16(this.pos);return this.pos+=2,e},e.prototype.readU32=function(){var e=this.view.getUint32(this.pos);return this.pos+=4,e},e.prototype.readI32=function(){var e=this.view.getInt32(this.pos);return this.pos+=4,e},e.prototype.readU64=function(){var e,t,n=(e=this.view,t=this.pos,4294967296*e.getUint32(t)+e.getUint32(t+4));return this.pos+=8,n},e.prototype.readI64=function(){var e=fn(this.view,this.pos);return this.pos+=8,e},e.prototype.readF32=function(){var e=this.view.getFloat32(this.pos);return this.pos+=4,e},e.prototype.readF64=function(){var e=this.view.getFloat64(this.pos);return this.pos+=8,e},e}();class jn{static write(e){let t=e.byteLength||e.length;const n=[];do{let e=127&t;t>>=7,t>0&&(e|=128),n.push(e)}while(t>0);t=e.byteLength||e.length;const r=new Uint8Array(n.length+t);return r.set(n,0),r.set(e,n.length),r.buffer}static parse(e){const t=[],n=new Uint8Array(e),r=[0,7,14,21,28];for(let o=0;o7)throw new Error("Messages bigger than 2GB are not supported.");if(!(n.byteLength>=o+i+a))throw new Error("Incomplete message.");t.push(n.slice?n.slice(o+i,o+i+a):n.subarray(o+i,o+i+a)),o=o+i+a}return t}}const Wn=new Uint8Array([145,qt.Ping]);class Jn{constructor(e){this.name="messagepack",this.version=1,this.transferFormat=zt.Binary,this._errorResult=1,this._voidResult=2,this._nonVoidResult=3,e=e||{},this._encoder=new Nn(e.extensionCodec,e.context,e.maxDepth,e.initialBufferSize,e.sortKeys,e.forceFloat32,e.ignoreUndefined,e.forceIntegerToFloat),this._decoder=new Hn(e.extensionCodec,e.context,e.maxStrLength,e.maxBinLength,e.maxArrayLength,e.maxMapLength,e.maxExtLength)}parseMessages(e,t){if(!(n=e)||"undefined"==typeof ArrayBuffer||!(n instanceof ArrayBuffer||n.constructor&&"ArrayBuffer"===n.constructor.name))throw new Error("Invalid input for MessagePack hub protocol. Expected an ArrayBuffer.");var n;null===t&&(t=kt.instance);const r=jn.parse(e),o=[];for(const e of r){const n=this._parseMessage(e,t);n&&o.push(n)}return o}writeMessage(e){switch(e.type){case qt.Invocation:return this._writeInvocation(e);case qt.StreamInvocation:return this._writeStreamInvocation(e);case qt.StreamItem:return this._writeStreamItem(e);case qt.Completion:return this._writeCompletion(e);case qt.Ping:return jn.write(Wn);case qt.CancelInvocation:return this._writeCancelInvocation(e);case qt.Close:return this._writeClose();default:throw new Error("Invalid message type.")}}_parseMessage(e,t){if(0===e.length)throw new Error("Invalid payload.");const n=this._decoder.decode(e);if(0===n.length||!(n instanceof Array))throw new Error("Invalid payload.");const r=n[0];switch(r){case qt.Invocation:return this._createInvocationMessage(this._readHeaders(n),n);case qt.StreamItem:return this._createStreamItemMessage(this._readHeaders(n),n);case qt.Completion:return this._createCompletionMessage(this._readHeaders(n),n);case qt.Ping:return this._createPingMessage(n);case qt.Close:return this._createCloseMessage(n);default:return t.log(It.Information,"Unknown message type '"+r+"' ignored."),null}}_createCloseMessage(e){if(e.length<2)throw new Error("Invalid payload for Close message.");return{allowReconnect:e.length>=3?e[2]:void 0,error:e[1],type:qt.Close}}_createPingMessage(e){if(e.length<1)throw new Error("Invalid payload for Ping message.");return{type:qt.Ping}}_createInvocationMessage(e,t){if(t.length<5)throw new Error("Invalid payload for Invocation message.");const n=t[2];return n?{arguments:t[4],headers:e,invocationId:n,streamIds:[],target:t[3],type:qt.Invocation}:{arguments:t[4],headers:e,streamIds:[],target:t[3],type:qt.Invocation}}_createStreamItemMessage(e,t){if(t.length<4)throw new Error("Invalid payload for StreamItem message.");return{headers:e,invocationId:t[2],item:t[3],type:qt.StreamItem}}_createCompletionMessage(e,t){if(t.length<4)throw new Error("Invalid payload for Completion message.");const n=t[3];if(n!==this._voidResult&&t.length<5)throw new Error("Invalid payload for Completion message.");let r,o;switch(n){case this._errorResult:r=t[4];break;case this._nonVoidResult:o=t[4]}return{error:r,headers:e,invocationId:t[2],result:o,type:qt.Completion}}_writeInvocation(e){let t;return t=e.streamIds?this._encoder.encode([qt.Invocation,e.headers||{},e.invocationId||null,e.target,e.arguments,e.streamIds]):this._encoder.encode([qt.Invocation,e.headers||{},e.invocationId||null,e.target,e.arguments]),jn.write(t.slice())}_writeStreamInvocation(e){let t;return t=e.streamIds?this._encoder.encode([qt.StreamInvocation,e.headers||{},e.invocationId,e.target,e.arguments,e.streamIds]):this._encoder.encode([qt.StreamInvocation,e.headers||{},e.invocationId,e.target,e.arguments]),jn.write(t.slice())}_writeStreamItem(e){const t=this._encoder.encode([qt.StreamItem,e.headers||{},e.invocationId,e.item]);return jn.write(t.slice())}_writeCompletion(e){const t=e.error?this._errorResult:void 0!==e.result?this._nonVoidResult:this._voidResult;let n;switch(t){case this._errorResult:n=this._encoder.encode([qt.Completion,e.headers||{},e.invocationId,t,e.error]);break;case this._voidResult:n=this._encoder.encode([qt.Completion,e.headers||{},e.invocationId,t]);break;case this._nonVoidResult:n=this._encoder.encode([qt.Completion,e.headers||{},e.invocationId,t,e.result])}return jn.write(n.slice())}_writeCancelInvocation(e){const t=this._encoder.encode([qt.CancelInvocation,e.headers||{},e.invocationId]);return jn.write(t.slice())}_writeClose(){const e=this._encoder.encode([qt.Close,null]);return jn.write(e.slice())}_readHeaders(e){const t=e[1];if("object"!=typeof t)throw new Error("Invalid headers.");return t}}let zn=!1;function qn(){const e=document.querySelector("#blazor-error-ui");e&&(e.style.display="block"),zn||(zn=!0,document.querySelectorAll("#blazor-error-ui .reload").forEach((e=>{e.onclick=function(e){location.reload(),e.preventDefault()}})),document.querySelectorAll("#blazor-error-ui .dismiss").forEach((e=>{e.onclick=function(e){const t=document.querySelector("#blazor-error-ui");t&&(t.style.display="none"),e.preventDefault()}})))}const Vn="function"==typeof TextDecoder?new TextDecoder("utf-8"):null,Kn=Vn?Vn.decode.bind(Vn):function(e){let t=0;const n=e.length,r=[],o=[];for(;t65535&&(o-=65536,r.push(o>>>10&1023|55296),o=56320|1023&o),r.push(o)}r.length>1024&&(o.push(String.fromCharCode.apply(null,r)),r.length=0)}return o.push(String.fromCharCode.apply(null,r)),o.join("")},Xn=Math.pow(2,32),Gn=Math.pow(2,21)-1;function Yn(e,t){return e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24}function Qn(e,t){return e[t]+(e[t+1]<<8)+(e[t+2]<<16)+(e[t+3]<<24>>>0)}function Zn(e,t){const n=Qn(e,t+4);if(n>Gn)throw new Error(`Cannot read uint64 with high order part ${n}, because the result would exceed Number.MAX_SAFE_INTEGER.`);return n*Xn+Qn(e,t)}class er{constructor(e){this.batchData=e;const t=new or(e);this.arrayRangeReader=new sr(e),this.arrayBuilderSegmentReader=new ir(e),this.diffReader=new tr(e),this.editReader=new nr(e,t),this.frameReader=new rr(e,t)}updatedComponents(){return Yn(this.batchData,this.batchData.length-20)}referenceFrames(){return Yn(this.batchData,this.batchData.length-16)}disposedComponentIds(){return Yn(this.batchData,this.batchData.length-12)}disposedEventHandlerIds(){return Yn(this.batchData,this.batchData.length-8)}updatedComponentsEntry(e,t){const n=e+4*t;return Yn(this.batchData,n)}referenceFramesEntry(e,t){return e+20*t}disposedComponentIdsEntry(e,t){const n=e+4*t;return Yn(this.batchData,n)}disposedEventHandlerIdsEntry(e,t){const n=e+8*t;return Zn(this.batchData,n)}}class tr{constructor(e){this.batchDataUint8=e}componentId(e){return Yn(this.batchDataUint8,e)}edits(e){return e+4}editsEntry(e,t){return e+16*t}}class nr{constructor(e,t){this.batchDataUint8=e,this.stringReader=t}editType(e){return Yn(this.batchDataUint8,e)}siblingIndex(e){return Yn(this.batchDataUint8,e+4)}newTreeIndex(e){return Yn(this.batchDataUint8,e+8)}moveToSiblingIndex(e){return Yn(this.batchDataUint8,e+8)}removedAttributeName(e){const t=Yn(this.batchDataUint8,e+12);return this.stringReader.readString(t)}}class rr{constructor(e,t){this.batchDataUint8=e,this.stringReader=t}frameType(e){return Yn(this.batchDataUint8,e)}subtreeLength(e){return Yn(this.batchDataUint8,e+4)}elementReferenceCaptureId(e){const t=Yn(this.batchDataUint8,e+4);return this.stringReader.readString(t)}componentId(e){return Yn(this.batchDataUint8,e+8)}elementName(e){const t=Yn(this.batchDataUint8,e+8);return this.stringReader.readString(t)}textContent(e){const t=Yn(this.batchDataUint8,e+4);return this.stringReader.readString(t)}markupContent(e){const t=Yn(this.batchDataUint8,e+4);return this.stringReader.readString(t)}attributeName(e){const t=Yn(this.batchDataUint8,e+4);return this.stringReader.readString(t)}attributeValue(e){const t=Yn(this.batchDataUint8,e+8);return this.stringReader.readString(t)}attributeEventHandlerId(e){return Zn(this.batchDataUint8,e+12)}}class or{constructor(e){this.batchDataUint8=e,this.stringTableStartIndex=Yn(e,e.length-4)}readString(e){if(-1===e)return null;{const n=Yn(this.batchDataUint8,this.stringTableStartIndex+4*e),r=function(e,t){let n=0,r=0;for(let o=0;o<4;o++){const s=e[t+o];if(n|=(127&s)<this.nextBatchId)return this.fatalError?(this.logger.log(ar.Debug,`Received a new batch ${e} but errored out on a previous batch ${this.nextBatchId-1}`),void await n.send("OnRenderCompleted",this.nextBatchId-1,this.fatalError.toString())):void this.logger.log(ar.Debug,`Waiting for batch ${this.nextBatchId}. Batch ${e} not processed.`);try{this.nextBatchId++,this.logger.log(ar.Debug,`Applying batch ${e}.`),ke(cr.Server,new er(t)),await this.completeBatch(n,e)}catch(t){throw this.fatalError=t.toString(),this.logger.log(ar.Error,`There was an error applying batch ${e}.`),n.send("OnRenderCompleted",e,t.toString()),t}}getLastBatchid(){return this.nextBatchId-1}async completeBatch(e,t){try{await e.send("OnRenderCompleted",t,null)}catch{this.logger.log(ar.Warning,`Failed to deliver completion notification for render '${t}'.`)}}}class hr{log(e,t){}}hr.instance=new hr;class dr{constructor(e){this.minLevel=e}log(e,t){if(e>=this.minLevel){const n=`[${(new Date).toISOString()}] ${ar[e]}: ${t}`;switch(e){case ar.Critical:case ar.Error:console.error(n);break;case ar.Warning:console.warn(n);break;case ar.Information:console.info(n);break;default:console.log(n)}}}}class ur{constructor(e){this._browserRendererId=e,this._registeredDescriptors=new Set,this._descriptorsToResolveById={},this._lastUpdatedIdByDescriptor=new Map,this._componentIdsByDescriptor=new Map}registerComponentDescriptor(e){this._registeredDescriptors.add(e)}unregisterComponentDescriptor(e){this._registeredDescriptors.delete(e)}async handleUpdatedRootComponents(e){await this.handleUpdatedRootComponentsCore(this._registeredDescriptors,e)}async handleUpdatedRootComponentsCore(e,t){if(!D(this._browserRendererId))return;const n=[];for(const r of e)if(pr(r)){if(!this.doesComponentNeedUpdate(r))continue;if(!this.hasComponentEverBeenUpdated(r)){t&&(this.markComponentAsUpdated(r),this.markComponentAsPendingResolution(r),n.push({type:"add",selectorId:r.id,marker:r.toRecord()}));continue}const e=this.getInteractiveComponentId(r);if(void 0!==e){this.markComponentAsUpdated(r),n.push({type:"update",componentId:e,marker:r.toRecord()});continue}}else{this.unregisterComponentDescriptor(r);const e=this.getInteractiveComponentId(r);if(void 0!==e){n.push({type:"remove",componentId:e});continue}}if(!n.length)return;const r=JSON.stringify(n);await function(e,t){return R(e).invokeMethodAsync("UpdateRootComponents",t)}(this._browserRendererId,r)}resolveRootComponent(e,t){const n=this.resolveComponentById(e);if(!n)throw new Error(`Could not resolve a root component for descriptor with ID '${e}'.`);if(void 0!==this.getInteractiveComponentId(n))throw new Error("Cannot resolve a root component for the same descriptor multiple times.");return this.setInteractiveComponentId(n,t),this.handleUpdatedRootComponentsCore([n],!1),n}doesComponentNeedUpdate(e){return this._lastUpdatedIdByDescriptor.get(e)!==e.id}markComponentAsUpdated(e){this._lastUpdatedIdByDescriptor.set(e,e.id)}markComponentAsPendingResolution(e){this._descriptorsToResolveById[e.id]=e}resolveComponentById(e){const t=this._descriptorsToResolveById[e];return delete this._descriptorsToResolveById[e],t}hasComponentEverBeenUpdated(e){return this._lastUpdatedIdByDescriptor.has(e)}getInteractiveComponentId(e){return this._componentIdsByDescriptor.get(e)}setInteractiveComponentId(e,t){this._componentIdsByDescriptor.set(e,t)}}function pr(e){return document.contains(e.start)}class fr{constructor(e,t){this.circuitId=void 0,this.applicationState=t,this.components=e}reconnect(e){if(!this.circuitId)throw new Error("Circuit host not initialized.");return e.state!==Vt.Connected?Promise.resolve(!1):e.invoke("ConnectCircuit",this.circuitId)}initialize(e){if(this.circuitId)throw new Error(`Circuit host '${this.circuitId}' already initialized.`);this.circuitId=e}async startCircuit(e){if(e.state!==Vt.Connected)return!1;const t=this.components instanceof ur?"[]":JSON.stringify(this.components.map((e=>e.toRecord()))),n=await e.invoke("StartCircuit",je.getBaseURI(),je.getLocationHref(),t,this.applicationState||"");return!!n&&(this.initialize(n),!0)}resolveElement(e,t){const n=w(e);if(n)return J(n,!0);const r=Number.parseInt(e);if(!Number.isNaN(r))return W(this.components instanceof ur?this.components.resolveRootComponent(r,t):this.components[r]);throw new Error(`Invalid sequence number or identifier '${e}'.`)}}const gr={configureSignalR:e=>{},logLevel:ar.Warning,reconnectionOptions:{maxRetries:8,retryIntervalMilliseconds:2e4,dialogId:"components-reconnect-modal"}};class mr{constructor(e,t,n,r){this.maxRetries=t,this.document=n,this.logger=r,this.addedToDom=!1,this.modal=this.document.createElement("div"),this.modal.id=e,this.maxRetries=t,this.modal.style.cssText=["position: fixed","top: 0","right: 0","bottom: 0","left: 0","z-index: 1050","display: none","overflow: hidden","background-color: #fff","opacity: 0.8","text-align: center","font-weight: bold","transition: visibility 0s linear 500ms"].join(";"),this.message=this.document.createElement("h5"),this.message.style.cssText="margin-top: 20px",this.button=this.document.createElement("button"),this.button.style.cssText="margin:5px auto 5px",this.button.textContent="Retry";const o=this.document.createElement("a");o.addEventListener("click",(()=>location.reload())),o.textContent="reload",this.reloadParagraph=this.document.createElement("p"),this.reloadParagraph.textContent="Alternatively, ",this.reloadParagraph.appendChild(o),this.modal.appendChild(this.message),this.modal.appendChild(this.button),this.modal.appendChild(this.reloadParagraph),this.loader=this.getLoader(),this.message.after(this.loader),this.button.addEventListener("click",(async()=>{this.show();try{await ht.reconnect()||this.rejected()}catch(e){this.logger.log(ar.Error,e),this.failed()}}))}show(){this.addedToDom||(this.addedToDom=!0,this.document.body.appendChild(this.modal)),this.modal.style.display="block",this.loader.style.display="inline-block",this.button.style.display="none",this.reloadParagraph.style.display="none",this.message.textContent="Attempting to reconnect to the server...",this.modal.style.visibility="hidden",setTimeout((()=>{this.modal.style.visibility="visible"}),0)}update(e){this.message.textContent=`Attempting to reconnect to the server: ${e} of ${this.maxRetries}`}hide(){this.modal.style.display="none"}failed(){this.button.style.display="block",this.reloadParagraph.style.display="none",this.loader.style.display="none";const e=this.document.createTextNode("Reconnection failed. Try "),t=this.document.createElement("a");t.textContent="reloading",t.setAttribute("href",""),t.addEventListener("click",(()=>location.reload()));const n=this.document.createTextNode(" the page if you're unable to reconnect.");this.message.replaceChildren(e,t,n)}rejected(){this.button.style.display="none",this.reloadParagraph.style.display="none",this.loader.style.display="none";const e=this.document.createTextNode("Could not reconnect to the server. "),t=this.document.createElement("a");t.textContent="Reload",t.setAttribute("href",""),t.addEventListener("click",(()=>location.reload()));const n=this.document.createTextNode(" the page to restore functionality.");this.message.replaceChildren(e,t,n)}getLoader(){const e=this.document.createElement("div");return e.style.cssText=["border: 0.3em solid #f3f3f3","border-top: 0.3em solid #3498db","border-radius: 50%","width: 2em","height: 2em","display: inline-block"].join(";"),e.animate([{transform:"rotate(0deg)"},{transform:"rotate(360deg)"}],{duration:2e3,iterations:1/0}),e}}class yr{constructor(e,t,n){this.dialog=e,this.maxRetries=t,this.document=n,this.document=n;const r=this.document.getElementById(yr.MaxRetriesId);r&&(r.innerText=this.maxRetries.toString())}show(){this.removeClasses(),this.dialog.classList.add(yr.ShowClassName)}update(e){const t=this.document.getElementById(yr.CurrentAttemptId);t&&(t.innerText=e.toString())}hide(){this.removeClasses(),this.dialog.classList.add(yr.HideClassName)}failed(){this.removeClasses(),this.dialog.classList.add(yr.FailedClassName)}rejected(){this.removeClasses(),this.dialog.classList.add(yr.RejectedClassName)}removeClasses(){this.dialog.classList.remove(yr.ShowClassName,yr.HideClassName,yr.FailedClassName,yr.RejectedClassName)}}yr.ShowClassName="components-reconnect-show",yr.HideClassName="components-reconnect-hide",yr.FailedClassName="components-reconnect-failed",yr.RejectedClassName="components-reconnect-rejected",yr.MaxRetriesId="components-reconnect-max-retries",yr.CurrentAttemptId="components-reconnect-current-attempt";class vr{constructor(e,t,n){this._currentReconnectionProcess=null,this._logger=e,this._reconnectionDisplay=t,this._reconnectCallback=n||ht.reconnect}onConnectionDown(e,t){if(!this._reconnectionDisplay){const t=document.getElementById(e.dialogId);this._reconnectionDisplay=t?new yr(t,e.maxRetries,document):new mr(e.dialogId,e.maxRetries,document,this._logger)}this._currentReconnectionProcess||(this._currentReconnectionProcess=new wr(e,this._logger,this._reconnectCallback,this._reconnectionDisplay))}onConnectionUp(){this._currentReconnectionProcess&&(this._currentReconnectionProcess.dispose(),this._currentReconnectionProcess=null)}}class wr{constructor(e,t,n,r){this.logger=t,this.reconnectCallback=n,this.isDisposed=!1,this.reconnectDisplay=r,this.reconnectDisplay.show(),this.attemptPeriodicReconnection(e)}dispose(){this.isDisposed=!0,this.reconnectDisplay.hide()}async attemptPeriodicReconnection(e){for(let t=0;twr.MaximumFirstRetryInterval?wr.MaximumFirstRetryInterval:e.retryIntervalMilliseconds;if(await this.delay(n),this.isDisposed)break;try{return await this.reconnectCallback()?void 0:void this.reconnectDisplay.rejected()}catch(e){this.logger.log(ar.Error,e)}}this.reconnectDisplay.failed()}delay(e){return new Promise((t=>setTimeout(t,e)))}}function br(e,t){switch(t){case"webassembly":return function(e){const t=Cr(e,"webassembly"),n=[];for(let e=0;ee.id-t.id))}(e);case"server":return function(e){const t=Cr(e,"server"),n=[];for(let e=0;ee.sequence-t.sequence))}(e)}}wr.MaximumFirstRetryInterval=3e3;const _r=/^\s*Blazor-Component-State:(?[a-zA-Z0-9+/=]+)$/;function Er(e){var t;if(e.nodeType===Node.COMMENT_NODE){const n=e.textContent||"",r=_r.exec(n),o=r&&r.groups&&r.groups.state;return o&&(null===(t=e.parentNode)||void 0===t||t.removeChild(e)),o}if(!e.hasChildNodes())return;const n=e.childNodes;for(let e=0;e.*)$/);function Ir(e,t){const n=e.currentElement;if(n&&n.nodeType===Node.COMMENT_NODE&&n.textContent){const r=Sr.exec(n.textContent),o=r&&r.groups&&r.groups.descriptor;if(!o)return;!function(e){if(e.parentNode instanceof Document)throw new Error("Root components cannot be marked as interactive. The element must be rendered statically so that scripts are not evaluated multiple times.")}(n);try{const r=function(e){const t=JSON.parse(e),{type:n}=t;if("server"!==n&&"webassembly"!==n)throw new Error(`Invalid component type '${n}'.`);return t}(o);switch(t){case"webassembly":return function(e,t,n){const{type:r,assembly:o,typeName:s,parameterDefinitions:i,parameterValues:a,prerenderId:c,key:l}=e,h=c?kr(c,n):void 0;if(c&&!h)throw new Error(`Could not find an end component comment for '${t}'.`);if("webassembly"===r){if(!o)throw new Error("assembly must be defined when using a descriptor.");if(!s)throw new Error("typeName must be defined when using a descriptor.");return{type:r,assembly:o,typeName:s,parameterDefinitions:i&&atob(i),parameterValues:a&&atob(a),start:t,prerenderId:c,end:h,key:l}}}(r,n,e);case"server":return function(e,t,n){const{type:r,descriptor:o,sequence:s,prerenderId:i,key:a}=e,c=i?kr(i,n):void 0;if(i&&!c)throw new Error(`Could not find an end component comment for '${t}'.`);if("server"===r){if(!o)throw new Error("descriptor must be defined when using a descriptor.");if(void 0===s)throw new Error("sequence must be defined when using a descriptor.");if(!Number.isInteger(s))throw new Error(`Error parsing the sequence '${s}' for component '${JSON.stringify(e)}'`);return{type:r,sequence:s,descriptor:o,start:t,prerenderId:i,end:c,key:a}}}(r,n,e)}}catch(e){throw new Error(`Found malformed component comment at ${n.textContent}`)}}}function kr(e,t){for(;t.next()&&t.currentElement;){const n=t.currentElement;if(n.nodeType!==Node.COMMENT_NODE)continue;if(!n.textContent)continue;const r=Sr.exec(n.textContent),o=r&&r[1];if(o)return Tr(o,e),n}}function Tr(e,t){const n=JSON.parse(e);if(1!==Object.keys(n).length)throw new Error(`Invalid end of component comment: '${e}'`);const r=n.prerenderId;if(!r)throw new Error(`End of component comment must have a value for the prerendered property: '${e}'`);if(r!==t)throw new Error(`End of component comment prerendered property must match the start comment prerender id: '${t}', '${r}'`)}class Dr{constructor(e){this.childNodes=e,this.currentIndex=-1,this.length=e.length}next(){return this.currentIndex++,this.currentIndexasync function(e,n){const r=function(e){const t=document.baseURI;return t.endsWith("/")?`${t}${e}`:`${t}/${e}`}(n),o=await import(r);if(void 0===o)return;const{beforeStart:s,afterStarted:i}=o;return i&&e.afterStartedCallbacks.push(i),s?s(...t):void 0}(this,e))))}async invokeAfterStartedCallbacks(e){await T,await Promise.all(this.afterStartedCallbacks.map((t=>t(e))))}}let Ar,Ur,Pr,Mr,Lr=!1;async function Br(e,t,n){var r,o;const s=new Jn;s.name="blazorpack";const i=(new cn).withUrl("_blazor").withHubProtocol(s);e.configureSignalR(i);const a=i.build();a.on("JS.AttachComponent",((e,t)=>Ie(cr.Server,n.resolveElement(t,e),e,!1))),a.on("JS.BeginInvokeJS",Pr.beginInvokeJSFromDotNet.bind(Pr)),a.on("JS.EndInvokeDotNet",Pr.endInvokeDotNetFromJS.bind(Pr)),a.on("JS.ReceiveByteArray",Pr.receiveByteArray.bind(Pr)),a.on("JS.BeginTransmitStream",(e=>{const t=new ReadableStream({start(t){a.stream("SendDotNetStreamToJS",e).subscribe({next:e=>t.enqueue(e),complete:()=>t.close(),error:e=>t.error(e)})}});Pr.supplyDotNetStream(e,t)}));const c=lr.getOrCreate(t);a.on("JS.RenderBatch",((e,n)=>{t.log(ar.Debug,`Received render batch with id ${e} and ${n.byteLength} bytes.`),c.processBatch(e,n,a)})),a.on("JS.EndLocationChanging",ht._internal.navigationManager.endLocationChanging),a.onclose((t=>!Lr&&e.reconnectionHandler.onConnectionDown(e.reconnectionOptions,t))),a.on("JS.Error",(e=>{Lr=!0,Or(a,e,t),qn()}));try{await a.start(),Ar=a}catch(e){if(Or(a,e,t),"FailedToNegotiateWithServerError"===e.errorType)throw e;qn(),e.innerErrors&&(e.innerErrors.some((e=>"UnsupportedTransportError"===e.errorType&&e.transport===Jt.WebSockets))?t.log(ar.Error,"Unable to connect, please ensure you are using an updated browser that supports WebSockets."):e.innerErrors.some((e=>"FailedToStartTransportError"===e.errorType&&e.transport===Jt.WebSockets))?t.log(ar.Error,"Unable to connect, please ensure WebSockets are available. A VPN or proxy may be blocking the connection."):e.innerErrors.some((e=>"DisabledTransportError"===e.errorType&&e.transport===Jt.LongPolling))&&t.log(ar.Error,"Unable to initiate a SignalR connection to the server. This might be because the server is not configured to support WebSockets. For additional details, visit https://aka.ms/blazor-server-websockets-error."))}return(null===(o=null===(r=a.connection)||void 0===r?void 0:r.features)||void 0===o?void 0:o.inherentKeepAlive)&&t.log(ar.Warning,"Failed to connect via WebSockets, using the Long Polling fallback transport. This may be due to a VPN or proxy blocking the connection. To troubleshoot this, visit https://aka.ms/blazor-server-using-fallback-long-polling."),a}function Or(e,t,n){n.log(ar.Error,t),e&&e.stop()}function Fr(e){return Mr=e,Mr}var $r,Hr;const jr=navigator,Wr=jr.userAgentData&&jr.userAgentData.brands,Jr=Wr&&Wr.length>0?Wr.some((e=>"Google Chrome"===e.brand||"Microsoft Edge"===e.brand||"Chromium"===e.brand)):window.chrome,zr=null!==(Hr=null===($r=jr.userAgentData)||void 0===$r?void 0:$r.platform)&&void 0!==Hr?Hr:navigator.platform;function qr(e){return 0!==e.debugLevel&&(Jr||navigator.userAgent.includes("Firefox"))}let Vr,Kr,Xr,Gr,Yr,Qr;const Zr=Math.pow(2,32),eo=Math.pow(2,21)-1;let to=null;function no(e){return Kr.getI32(e)}const ro={start:function(t){return async function(t){const{dotnet:n}=await async function(e){if("undefined"==typeof WebAssembly||!WebAssembly.validate)throw new Error("This browser does not support WebAssembly.");let t="_framework/dotnet.js";if(e.loadBootResource){const n="dotnetjs",r=e.loadBootResource(n,"dotnet.js",t,"");if("string"==typeof r)t=r;else if(r)throw new Error(`For a ${n} resource, custom loaders must supply a URI string.`)}const n=new URL(t,document.baseURI).toString();return await import(n)}(t),r=function(e){const t={maxParallelDownloads:1e6,enableDownloadRetry:!1,applicationEnvironment:e.environment},n={...window.Module||{},onConfigLoaded:async(t,{invokeLibraryInitializers:n})=>{var r,o;t.environmentVariables||(t.environmentVariables={}),"sharded"===t.globalizationMode&&(t.environmentVariables.__BLAZOR_SHARDED_ICU="1"),ht._internal.getApplicationEnvironment=()=>t.applicationEnvironment;const s=[e,null!==(o=null===(r=t.resources)||void 0===r?void 0:r.extensions)&&void 0!==o?o:{}];await n("beforeStart",s)},onDownloadResourceProgress:oo,config:t,disableDotnet6Compatibility:!1,out:io,err:ao};return n}(t);n.withStartupOptions(t).withModuleConfig(r),Qr=await n.create();const{MONO:o,BINDING:s,Module:i,setModuleImports:a,INTERNAL:c,getConfig:l,invokeLibraryInitializers:h}=Qr;Xr=i,Vr=s,Kr=o,Yr=c,function(e){const t=zr.match(/^Mac/i)?"Cmd":"Alt";qr(e)&&console.info(`Debugging hotkey: Shift+${t}+D (when application has focus)`),document.addEventListener("keydown",(t=>{t.shiftKey&&(t.metaKey||t.altKey)&&"KeyD"===t.code&&(qr(e)?navigator.userAgent.includes("Firefox")?async function(){const e=await fetch(`_framework/debug?url=${encodeURIComponent(location.href)}&isFirefox=true`);200!==e.status&&console.warn(await e.text())}():Jr?function(){const e=document.createElement("a");e.href=`_framework/debug?url=${encodeURIComponent(location.href)}`,e.target="_blank",e.rel="noopener noreferrer",e.click()}():console.error("Currently, only Microsoft Edge (80+), Google Chrome, or Chromium, are supported for debugging."):console.error("Cannot start debugging, because the application was not compiled with debugging enabled."))}))}(l()),ht._internal.dotNetCriticalError=ao,a("blazor-internal",{Blazor:{_internal:ht._internal}});const d=await Qr.getAssemblyExports("Microsoft.AspNetCore.Components.WebAssembly");return Object.assign(ht._internal,{dotNetExports:{...d.Microsoft.AspNetCore.Components.WebAssembly.Services.DefaultWebAssemblyJSRuntime}}),Gr=e.attachDispatcher({beginInvokeDotNetFromJS:(e,t,n,r,o)=>{if(lo(),!r&&!t)throw new Error("Either assemblyName or dotNetObjectId must have a non null value.");const s=r?r.toString():t;ht._internal.dotNetExports.BeginInvokeDotNet(e?e.toString():null,s,n,o)},endInvokeJSFromDotNet:(e,t,n)=>{ht._internal.dotNetExports.EndInvokeJS(n)},sendByteArray:(e,t)=>{ht._internal.dotNetExports.ReceiveByteArrayFromJS(e,t)},invokeDotNetFromJS:(e,t,n,r)=>(lo(),ht._internal.dotNetExports.InvokeDotNet(e||null,t,null!=n?n:0,r))}),{invokeLibraryInitializers:h}}(t)},callEntryPoint:async function(){try{await Qr.runMain(Qr.getConfig().mainAssemblyName,[])}catch(e){console.error(e),qn()}},toUint8Array:function(e){const t=co(e),n=no(t),r=new Uint8Array(n);return r.set(Xr.HEAPU8.subarray(t+4,t+4+n)),r},getArrayLength:function(e){return no(co(e))},getArrayEntryPtr:function(e,t,n){return co(e)+4+t*n},getObjectFieldsBaseAddress:function(e){return e+8},readInt16Field:function(e,t){return n=e+(t||0),Kr.getI16(n);var n},readInt32Field:function(e,t){return no(e+(t||0))},readUint64Field:function(e,t){return function(e){const t=e>>2,n=Xr.HEAPU32[t+1];if(n>eo)throw new Error(`Cannot read uint64 with high order part ${n}, because the result would exceed Number.MAX_SAFE_INTEGER.`);return n*Zr+Xr.HEAPU32[t]}(e+(t||0))},readFloatField:function(e,t){return n=e+(t||0),Kr.getF32(n);var n},readObjectField:function(e,t){return no(e+(t||0))},readStringField:function(e,t,n){const r=no(e+(t||0));if(0===r)return null;if(n){const e=Vr.unbox_mono_obj(r);return"boolean"==typeof e?e?"":null:e}return Vr.conv_string(r)},readStructField:function(e,t){return e+(t||0)},beginHeapLock:function(){return lo(),to=ho.create(),to},invokeWhenHeapUnlocked:function(e){to?to.enqueuePostReleaseAction(e):e()}};function oo(e,t){const n=e/t*100;document.documentElement.style.setProperty("--blazor-load-percentage",`${n}%`),document.documentElement.style.setProperty("--blazor-load-percentage-text",`"${Math.floor(n)}%"`)}const so=["DEBUGGING ENABLED"],io=e=>so.indexOf(e)<0&&console.log(e),ao=e=>{console.error(e||"(null)"),qn()};function co(e){return e+12}function lo(){if(to)throw new Error("Assertion failed - heap is currently locked")}class ho{enqueuePostReleaseAction(e){this.postReleaseActions||(this.postReleaseActions=[]),this.postReleaseActions.push(e)}release(){var e;if(to!==this)throw new Error("Trying to release a lock which isn't current");for(Yr.mono_wasm_gc_unlock(),to=null;null===(e=this.postReleaseActions)||void 0===e?void 0:e.length;)this.postReleaseActions.shift()(),lo()}static create(){return Yr.mono_wasm_gc_lock(),new ho}}class uo{constructor(e){this.batchAddress=e,this.arrayRangeReader=po,this.arrayBuilderSegmentReader=fo,this.diffReader=go,this.editReader=mo,this.frameReader=yo}updatedComponents(){return Mr.readStructField(this.batchAddress,0)}referenceFrames(){return Mr.readStructField(this.batchAddress,po.structLength)}disposedComponentIds(){return Mr.readStructField(this.batchAddress,2*po.structLength)}disposedEventHandlerIds(){return Mr.readStructField(this.batchAddress,3*po.structLength)}updatedComponentsEntry(e,t){return vo(e,t,go.structLength)}referenceFramesEntry(e,t){return vo(e,t,yo.structLength)}disposedComponentIdsEntry(e,t){const n=vo(e,t,4);return Mr.readInt32Field(n)}disposedEventHandlerIdsEntry(e,t){const n=vo(e,t,8);return Mr.readUint64Field(n)}}const po={structLength:8,values:e=>Mr.readObjectField(e,0),count:e=>Mr.readInt32Field(e,4)},fo={structLength:12,values:e=>{const t=Mr.readObjectField(e,0),n=Mr.getObjectFieldsBaseAddress(t);return Mr.readObjectField(n,0)},offset:e=>Mr.readInt32Field(e,4),count:e=>Mr.readInt32Field(e,8)},go={structLength:4+fo.structLength,componentId:e=>Mr.readInt32Field(e,0),edits:e=>Mr.readStructField(e,4),editsEntry:(e,t)=>vo(e,t,mo.structLength)},mo={structLength:20,editType:e=>Mr.readInt32Field(e,0),siblingIndex:e=>Mr.readInt32Field(e,4),newTreeIndex:e=>Mr.readInt32Field(e,8),moveToSiblingIndex:e=>Mr.readInt32Field(e,8),removedAttributeName:e=>Mr.readStringField(e,16)},yo={structLength:36,frameType:e=>Mr.readInt16Field(e,4),subtreeLength:e=>Mr.readInt32Field(e,8),elementReferenceCaptureId:e=>Mr.readStringField(e,16),componentId:e=>Mr.readInt32Field(e,12),elementName:e=>Mr.readStringField(e,16),textContent:e=>Mr.readStringField(e,16),markupContent:e=>Mr.readStringField(e,16),attributeName:e=>Mr.readStringField(e,16),attributeValue:e=>Mr.readStringField(e,24,!0),attributeEventHandlerId:e=>Mr.readUint64Field(e,8)};function vo(e,t,n){return Mr.getArrayEntryPtr(e,t,n)}class wo{constructor(e){if(this.componentsById={},e instanceof ur)this.preregisteredComponents=[],this.rootComponentManager=e;else{this.preregisteredComponents=e;for(let t=0;t=n&&i>=r&&o(e.item(s),t.item(i))===ko.None;)s--,i--,a++;return a}(e,t,r,r,n),s=function(e){var t;const n=[];let r=e.length-1,o=(null===(t=e[r])||void 0===t?void 0:t.length)-1;for(;r>0||o>0;){const t=0===r?To.Insert:0===o?To.Delete:e[r][o];switch(n.unshift(t),t){case To.Keep:case To.Update:r--,o--;break;case To.Insert:o--;break;case To.Delete:r--}}return n}(function(e,t,n){const r=[],o=[],s=e.length,i=t.length;if(0===s&&0===i)return[];for(let e=0;e<=s;e++)(r[e]=Array(i+1))[0]=e,o[e]=Array(i+1);const a=r[0];for(let e=1;e<=i;e++)a[e]=e;for(let a=1;a<=s;a++)for(let s=1;s<=i;s++){const i=n(e.item(a-1),t.item(s-1)),c=r[a-1][s]+1,l=r[a][s-1]+1;let h;switch(i){case ko.None:h=r[a-1][s-1];break;case ko.Some:h=r[a-1][s-1]+1;break;case ko.Infinite:h=Number.MAX_VALUE}h{history.pushState(null,"",e),Ko(e)}))}function qo(e){Ue()||Ko(location.href)}function Vo(e){if(Ue()||e.defaultPrevented)return;const t=e.target;if(t instanceof HTMLFormElement){e.preventDefault();const n=new URL(t.action),r={method:t.method},o=new FormData(t),s=e.submitter;s&&s.name&&o.append(s.name,s.value),"get"===r.method?n.search=new URLSearchParams(o).toString():r.body=o,Ko(n.toString(),r)}}async function Ko(e,t){Ro=!0,null==xo||xo.abort(),xo=new AbortController;const n=xo.signal,r=fetch(e,Object.assign({signal:n,headers:{"blazor-enhanced-nav":"on"}},t));if(await async function(e,t,n,r){let o;try{o=await e;const t=o.headers.get("blazor-enhanced-nav-redirect-location");if(t)return void location.replace(t);if(!o.body)return void n(o,"");const r=o.headers.get("ssr-framing");if(!r){const e=await o.text();return void n(o,e)}let s=!0;await o.body.pipeThrough(new TextDecoderStream).pipeThrough(function(e){let t="";return new TransformStream({transform(n,r){if(t+=n,t.indexOf(e,t.length-n.length-e.length)>=0){const n=t.split(e);n.slice(0,-1).forEach((e=>r.enqueue(e))),t=n[n.length-1]}},flush(e){e.enqueue(t)}})}(`\x3c!--${r}--\x3e`)).pipeTo(new WritableStream({write(e){s?(s=!1,n(o,e)):(e=>{const t=document.createRange().createContextualFragment(e);for(;t.firstChild;)document.body.appendChild(t.firstChild)})(e)}}))}catch(e){if("AbortError"===e.name&&t.aborted)return;throw e}}(r,n,((n,r)=>{n.redirected&&(history.replaceState(null,"",n.url),e=n.url);const o=n.headers.get("content-type");if((null==o?void 0:o.startsWith("text/html"))&&r){const e=(new DOMParser).parseFromString(r,"text/html");Uo(document,e),No.documentUpdated()}else(null==o?void 0:o.startsWith("text/"))&&r?Xo(r):(n.status<200||n.status>=300)&&!r?Xo(`Error: ${n.status} ${n.statusText}`):(null==t?void 0:t.method)&&"get"!==t.method?Xo(`Error: ${t.method} request to ${e} returned non-HTML content of type ${o||"unspecified"}.`):(history.replaceState(null,"",e+"?"),location.replace(e))})),!n.aborted){const t=e.indexOf("#");if(t>=0){const n=e.substring(t+1),r=document.getElementById(n);null==r||r.scrollIntoView()}Ro=!1,No.documentUpdated()}}function Xo(e){document.documentElement.textContent=e;const t=document.documentElement.style;t.fontFamily="consolas, monospace",t.whiteSpace="pre-wrap",t.padding="1rem"}let Go,Yo=!0;class Qo extends HTMLElement{connectedCallback(){var e;null===(e=this.parentNode)||void 0===e||e.removeChild(this);const t=this.attachShadow({mode:"open"}),n=document.createElement("slot");t.appendChild(n),n.addEventListener("slotchange",(e=>{this.childNodes.forEach((e=>{if(e instanceof HTMLTemplateElement){const t=e.getAttribute("blazor-component-id");if(t)!function(e,t){const n=function(e){const t=`bl:${e}`,n=document.createNodeIterator(document,NodeFilter.SHOW_COMMENT);let r=null;for(;(r=n.nextNode())&&r.textContent!==t;);if(!r)return null;const o=`/bl:${e}`;let s=null;for(;(s=n.nextNode())&&s.textContent!==o;);return s?{startMarker:r,endMarker:s}:null}(e);if(n){const{startMarker:e,endMarker:r}=n;if(Yo)Uo({startExclusive:e,endExclusive:r},t);else{const n=r.parentNode,o=new Range;for(o.setStart(e,e.textContent.length),o.setEnd(r,0),o.deleteContents();t.childNodes[0];)n.insertBefore(t.childNodes[0],r)}Go.documentUpdated()}}(t,e.content);else switch(e.getAttribute("type")){case"redirection":const t=e.content.textContent;Ne(t)?(history.replaceState(null,"",t),Ko(t)):location.replace(t);break;case"error":Xo(e.content.textContent||"Error")}}}))}))}}let Zo,es=!1;const ts=new ur(cr.Server),ns=new ur(cr.WebAssembly);function rs(e){var t;if(es)throw new Error("Blazor has already started.");es=!0,Zo=e;const n={documentUpdated:ss};return Ao={registerComponentDescriptor:os},function(e,t){Go=t,(null==e?void 0:e.disableDomPreservation)&&(Yo=!1),customElements.define("blazor-ssr",Qo)}(null==e?void 0:e.ssr,n),(null===(t=null==e?void 0:e.ssr)||void 0===t?void 0:t.disableDomPreservation)||Jo(n),function(e){const t=Fo(document);for(const e of t)null==Ao||Ao.registerComponentDescriptor(e)}(),Promise.resolve()}function os(t){switch(t.type){case"server":!async function(){is||(is=!0,await async function(t,n){const r=function(e){const t={...gr,...e};return e&&e.reconnectionOptions&&(t.reconnectionOptions={...gr.reconnectionOptions,...e.reconnectionOptions}),t}(t),o=await async function(e){const t=await fetch("_blazor/initializers",{method:"GET",credentials:"include",cache:"no-cache"}),n=await t.json(),r=new Rr;return await r.importInitializersAsync(n,[e]),r}(r),s=new dr(r.logLevel);ht.reconnect=async e=>{if(Lr)return!1;const t=e||await Br(r,s,Ur);return await Ur.reconnect(t)?(r.reconnectionHandler.onConnectionUp(),!0):(s.log(ar.Information,"Reconnection attempt to the circuit was rejected by the server. This may indicate that the associated state is no longer available on the server."),!1)},ht.defaultReconnectionHandler=new vr(s),r.reconnectionHandler=r.reconnectionHandler||ht.defaultReconnectionHandler,s.log(ar.Information,"Starting up Blazor server-side application.");const i=Er(document);Ur=new fr(n||[],i||""),ht._internal.navigationManager.listenForNavigationEvents(((e,t,n)=>Ar.send("OnLocationChanged",e,t,n)),((e,t,n,r)=>Ar.send("OnLocationChanging",e,t,n,r))),ht._internal.forceCloseConnection=()=>Ar.stop(),ht._internal.sendJSDataStream=(e,t,n)=>function(e,t,n,r){setTimeout((async()=>{let o=5,s=(new Date).valueOf();try{const i=t instanceof Blob?t.size:t.byteLength;let a=0,c=0;for(;a1)await e.send("ReceiveJSDataChunk",n,c,h,null);else{if(!await e.invoke("ReceiveJSDataChunk",n,c,h,null))break;const t=(new Date).valueOf(),r=t-s;s=t,o=Math.max(1,Math.round(500/Math.max(1,r)))}a+=l,c++}}catch(t){await e.send("ReceiveJSDataChunk",n,-1,null,t.toString())}}),0)}(Ar,e,t,n),Pr=e.attachDispatcher({beginInvokeDotNetFromJS:(e,t,n,r,o)=>{Ar.send("BeginInvokeDotNetFromJS",e?e.toString():null,t,n,r||0,o)},endInvokeJSFromDotNet:(e,t,n)=>{Ar.send("EndInvokeJSFromDotNet",e,t,n)},sendByteArray:(e,t)=>{Ar.send("ReceiveByteArray",e,t)}});const a=await Br(r,s,Ur);if(!await Ur.startCircuit(a))return void s.log(ar.Error,"Failed to start the circuit.");let c=!1;const l=()=>{if(!c){const e=new FormData,t=Ur.circuitId;e.append("circuitId",t),c=navigator.sendBeacon("_blazor/disconnect",e)}};ht.disconnect=l,window.addEventListener("unload",l,{capture:!1,once:!0}),s.log(ar.Information,"Blazor server-side application started."),o.invokeAfterStartedCallbacks(ht)}(null==Zo?void 0:Zo.circuit,ts),await x(cr.Server),ss())}(),ts.registerComponentDescriptor(t);break;case"webassembly":!async function(){as||(as=!0,await async function(e,t){(function(){if(window.parent!==window&&!window.opener&&window.frameElement){const e=window.sessionStorage&&window.sessionStorage["Microsoft.AspNetCore.Components.WebAssembly.Authentication.CachedAuthSettings"],t=e&&JSON.parse(e);return t&&t.redirect_uri&&location.href.startsWith(t.redirect_uri)}return!1})()&&await new Promise((()=>{})),function(e){const t=A;A=(e,n,r)=>{((e,t,n)=>{const r=function(e){return Ce[e]}(e);r.eventDelegator.getHandler(t)&&ro.invokeWhenHeapUnlocked(n)})(e,n,(()=>t(e,n,r)))}}(),ht._internal.applyHotReload=(e,t,n,r)=>{Gr.invokeDotNetStaticMethod("Microsoft.AspNetCore.Components.WebAssembly","ApplyHotReloadDelta",e,t,n,r)},ht._internal.getApplyUpdateCapabilities=()=>Gr.invokeDotNetStaticMethod("Microsoft.AspNetCore.Components.WebAssembly","GetApplyUpdateCapabilities"),ht._internal.invokeJSFromDotNet=bo,ht._internal.invokeJSJson=_o,ht._internal.endInvokeDotNetFromJS=Eo,ht._internal.receiveWebAssemblyDotNetDataStream=Co,ht._internal.receiveByteArray=So;const n=Fr(ro);ht.platform=n,ht._internal.renderBatch=(e,t)=>{const n=ro.beginHeapLock();try{ke(e,new uo(t))}finally{n.release()}},ht._internal.navigationManager.listenForNavigationEvents((async(e,t,n)=>{await Gr.invokeDotNetStaticMethodAsync("Microsoft.AspNetCore.Components.WebAssembly","NotifyLocationChanged",e,t,n)}),(async(e,t,n,r)=>{const o=await Gr.invokeDotNetStaticMethodAsync("Microsoft.AspNetCore.Components.WebAssembly","NotifyLocationChangingAsync",t,n,r);ht._internal.navigationManager.endLocationChanging(e,o)}));const r=new wo(t||[]);let o;ht._internal.registeredComponents={getRegisteredComponentsCount:()=>r.getCount(),getId:e=>r.getId(e),getAssembly:e=>r.getAssembly(e),getTypeName:e=>r.getTypeName(e),getParameterDefinitions:e=>r.getParameterDefinitions(e)||"",getParameterValues:e=>r.getParameterValues(e)||""},ht._internal.getPersistedState=()=>Er(document)||"",ht._internal.attachRootComponentToElement=(e,t,n)=>{const o=r.resolveRegisteredElement(e,t);o?Ie(n,o,t,!1):function(e,t,n){const r="::before";let o=!1;if(e.endsWith("::after"))e=e.slice(0,-7),o=!0;else if(e.endsWith(r))throw new Error(`The '${r}' selector is not supported.`);const s=w(e)||document.querySelector(e);if(!s)throw new Error(`Could not find any element matching selector '${e}'.`);Ie(n||0,J(s,!0),t,o)}(e,t,n)};try{o=await n.start(null!=e?e:{})}catch(e){throw new Error(`Failed to start platform. Reason: ${e}`)}n.callEntryPoint(),o.invokeLibraryInitializers("afterStarted",[ht])}(null==Zo?void 0:Zo.webAssembly,ns),await x(cr.WebAssembly),ss())}(),ns.registerComponentDescriptor(t)}}function ss(){const e=!Ro;ts.handleUpdatedRootComponents(e),ns.handleUpdatedRootComponents(e)}let is=!1,as=!1;ht.start=rs,window.DotNet=e,document&&document.currentScript&&"false"!==document.currentScript.getAttribute("autostart")&&rs()})()})(); \ No newline at end of file diff --git a/src/Components/Web.JS/dist/Release/blazor.webview.js b/src/Components/Web.JS/dist/Release/blazor.webview.js index b7296ac3d88f..b673948085a0 100644 --- a/src/Components/Web.JS/dist/Release/blazor.webview.js +++ b/src/Components/Web.JS/dist/Release/blazor.webview.js @@ -1 +1 @@ -(()=>{"use strict";var e,t,n,r={d:(e,t)=>{for(var n in t)r.o(t,n)&&!r.o(e,n)&&Object.defineProperty(e,n,{enumerable:!0,get:t[n]})},o:(e,t)=>Object.prototype.hasOwnProperty.call(e,t)};r.d({},{e:()=>Et}),function(e){const t=[],n="__jsObjectId",r="__dotNetObject",o="__byte[]",a="__dotNetStream",i="__jsStreamReferenceLength";let s,c;class l{constructor(e){this._jsObject=e,this._cachedFunctions=new Map}findFunction(e){const t=this._cachedFunctions.get(e);if(t)return t;let n,r=this._jsObject;if(e.split(".").forEach((t=>{if(!(t in r))throw new Error(`Could not find '${e}' ('${t}' was undefined).`);n=r,r=r[t]})),r instanceof Function)return r=r.bind(n),this._cachedFunctions.set(e,r),r;throw new Error(`The value '${e}' is not a function.`)}getWrappedObject(){return this._jsObject}}const u={0:new l(window)};u[0]._cachedFunctions.set("import",(e=>("string"==typeof e&&e.startsWith("./")&&(e=new URL(e.substr(2),document.baseURI).toString()),import(e))));let d,h=1;function f(e){t.push(e)}function p(e){if(e&&"object"==typeof e){u[h]=new l(e);const t={[n]:h};return h++,t}throw new Error(`Cannot create a JSObjectReference from the value '${e}'.`)}function m(e){let t=-1;if(e instanceof ArrayBuffer&&(e=new Uint8Array(e)),e instanceof Blob)t=e.size;else{if(!(e.buffer instanceof ArrayBuffer))throw new Error("Supplied value is not a typed array or blob.");if(void 0===e.byteLength)throw new Error(`Cannot create a JSStreamReference from the value '${e}' as it doesn't have a byteLength.`);t=e.byteLength}const r={[i]:t};try{const t=p(e);r[n]=t[n]}catch(t){throw new Error(`Cannot create a JSStreamReference from the value '${e}'.`)}return r}function v(e,n){c=e;const r=n?JSON.parse(n,((e,n)=>t.reduce(((t,n)=>n(e,t)),n))):null;return c=void 0,r}function g(){if(void 0===s)throw new Error("No call dispatcher has been set.");if(null===s)throw new Error("There are multiple .NET runtimes present, so a default dispatcher could not be resolved. Use DotNetObject to invoke .NET instance methods.");return s}e.attachDispatcher=function(e){const t=new b(e);return void 0===s?s=t:s&&(s=null),t},e.attachReviver=f,e.invokeMethod=function(e,t,...n){return g().invokeDotNetStaticMethod(e,t,...n)},e.invokeMethodAsync=function(e,t,...n){return g().invokeDotNetStaticMethodAsync(e,t,...n)},e.createJSObjectReference=p,e.createJSStreamReference=m,e.disposeJSObjectReference=function(e){const t=e&&e[n];"number"==typeof t&&E(t)},function(e){e[e.Default=0]="Default",e[e.JSObjectReference=1]="JSObjectReference",e[e.JSStreamReference=2]="JSStreamReference",e[e.JSVoidResult=3]="JSVoidResult"}(d=e.JSCallResultType||(e.JSCallResultType={}));class b{constructor(e){this._dotNetCallDispatcher=e,this._byteArraysToBeRevived=new Map,this._pendingDotNetToJSStreams=new Map,this._pendingAsyncCalls={},this._nextAsyncCallId=1}getDotNetCallDispatcher(){return this._dotNetCallDispatcher}invokeJSFromDotNet(e,t,n,r){const o=v(this,t),a=C(w(e,r)(...o||[]),n);return null==a?null:A(this,a)}beginInvokeJSFromDotNet(e,t,n,r,o){const a=new Promise((e=>{const r=v(this,n);e(w(t,o)(...r||[]))}));e&&a.then((t=>A(this,[e,!0,C(t,r)]))).then((t=>this._dotNetCallDispatcher.endInvokeJSFromDotNet(e,!0,t)),(t=>this._dotNetCallDispatcher.endInvokeJSFromDotNet(e,!1,JSON.stringify([e,!1,y(t)]))))}endInvokeDotNetFromJS(e,t,n){const r=t?v(this,n):new Error(n);this.completePendingCall(parseInt(e,10),t,r)}invokeDotNetStaticMethod(e,t,...n){return this.invokeDotNetMethod(e,t,null,n)}invokeDotNetStaticMethodAsync(e,t,...n){return this.invokeDotNetMethodAsync(e,t,null,n)}invokeDotNetMethod(e,t,n,r){if(this._dotNetCallDispatcher.invokeDotNetFromJS){const o=A(this,r),a=this._dotNetCallDispatcher.invokeDotNetFromJS(e,t,n,o);return a?v(this,a):null}throw new Error("The current dispatcher does not support synchronous calls from JS to .NET. Use invokeDotNetMethodAsync instead.")}invokeDotNetMethodAsync(e,t,n,r){if(e&&n)throw new Error(`For instance method calls, assemblyName should be null. Received '${e}'.`);const o=this._nextAsyncCallId++,a=new Promise(((e,t)=>{this._pendingAsyncCalls[o]={resolve:e,reject:t}}));try{const a=A(this,r);this._dotNetCallDispatcher.beginInvokeDotNetFromJS(o,e,t,n,a)}catch(e){this.completePendingCall(o,!1,e)}return a}receiveByteArray(e,t){this._byteArraysToBeRevived.set(e,t)}processByteArray(e){const t=this._byteArraysToBeRevived.get(e);return t?(this._byteArraysToBeRevived.delete(e),t):null}supplyDotNetStream(e,t){if(this._pendingDotNetToJSStreams.has(e)){const n=this._pendingDotNetToJSStreams.get(e);this._pendingDotNetToJSStreams.delete(e),n.resolve(t)}else{const n=new D;n.resolve(t),this._pendingDotNetToJSStreams.set(e,n)}}getDotNetStreamPromise(e){let t;if(this._pendingDotNetToJSStreams.has(e))t=this._pendingDotNetToJSStreams.get(e).streamPromise,this._pendingDotNetToJSStreams.delete(e);else{const n=new D;this._pendingDotNetToJSStreams.set(e,n),t=n.streamPromise}return t}completePendingCall(e,t,n){if(!this._pendingAsyncCalls.hasOwnProperty(e))throw new Error(`There is no pending async call with ID ${e}.`);const r=this._pendingAsyncCalls[e];delete this._pendingAsyncCalls[e],t?r.resolve(n):r.reject(n)}}function y(e){return e instanceof Error?`${e.message}\n${e.stack}`:e?e.toString():"null"}function w(e,t){const n=u[t];if(n)return n.findFunction(e);throw new Error(`JS object instance with ID ${t} does not exist (has it been disposed?).`)}function E(e){delete u[e]}e.findJSFunction=w,e.disposeJSObjectReferenceById=E;class S{constructor(e,t){this._id=e,this._callDispatcher=t}invokeMethod(e,...t){return this._callDispatcher.invokeDotNetMethod(null,e,this._id,t)}invokeMethodAsync(e,...t){return this._callDispatcher.invokeDotNetMethodAsync(null,e,this._id,t)}dispose(){this._callDispatcher.invokeDotNetMethodAsync(null,"__Dispose",this._id,null).catch((e=>console.error(e)))}serializeAsArg(){return{[r]:this._id}}}e.DotNetObject=S,f((function(e,t){if(t&&"object"==typeof t){if(t.hasOwnProperty(r))return new S(t[r],c);if(t.hasOwnProperty(n)){const e=t[n],r=u[e];if(r)return r.getWrappedObject();throw new Error(`JS object instance with Id '${e}' does not exist. It may have been disposed.`)}if(t.hasOwnProperty(o)){const e=t[o],n=c.processByteArray(e);if(void 0===n)throw new Error(`Byte array index '${e}' does not exist.`);return n}if(t.hasOwnProperty(a)){const e=t[a],n=c.getDotNetStreamPromise(e);return new I(n)}}return t}));class I{constructor(e){this._streamPromise=e}stream(){return this._streamPromise}async arrayBuffer(){return new Response(await this.stream()).arrayBuffer()}}class D{constructor(){this.streamPromise=new Promise(((e,t)=>{this.resolve=e,this.reject=t}))}}function C(e,t){switch(t){case d.Default:return e;case d.JSObjectReference:return p(e);case d.JSStreamReference:return m(e);case d.JSVoidResult:return null;default:throw new Error(`Invalid JS call result type '${t}'.`)}}let N=0;function A(e,t){N=0,c=e;const n=JSON.stringify(t,k);return c=void 0,n}function k(e,t){if(t instanceof S)return t.serializeAsArg();if(t instanceof Uint8Array){c.getDotNetCallDispatcher().sendByteArray(N,t);const e={[o]:N};return N++,e}return t}}(e||(e={})),function(e){e[e.prependFrame=1]="prependFrame",e[e.removeFrame=2]="removeFrame",e[e.setAttribute=3]="setAttribute",e[e.removeAttribute=4]="removeAttribute",e[e.updateText=5]="updateText",e[e.stepIn=6]="stepIn",e[e.stepOut=7]="stepOut",e[e.updateMarkup=8]="updateMarkup",e[e.permutationListEntry=9]="permutationListEntry",e[e.permutationListEnd=10]="permutationListEnd"}(t||(t={})),function(e){e[e.element=1]="element",e[e.text=2]="text",e[e.attribute=3]="attribute",e[e.component=4]="component",e[e.region=5]="region",e[e.elementReferenceCapture=6]="elementReferenceCapture",e[e.markup=8]="markup",e[e.namedEvent=10]="namedEvent"}(n||(n={}));class o{constructor(e,t){this.componentId=e,this.fieldValue=t}static fromEvent(e,t){const n=t.target;if(n instanceof Element){const t=function(e){return e instanceof HTMLInputElement?e.type&&"checkbox"===e.type.toLowerCase()?{value:e.checked}:{value:e.value}:e instanceof HTMLSelectElement||e instanceof HTMLTextAreaElement?{value:e.value}:null}(n);if(t)return new o(e,t.value)}return null}}const a=new Map,i=new Map,s=[];function c(e){return a.get(e)}function l(e){const t=a.get(e);return(null==t?void 0:t.browserEventName)||e}function u(e,t){e.forEach((e=>a.set(e,t)))}function d(e){const t=[];for(let n=0;ne.selected)).map((e=>e.value))}}{const e=function(e){return!!e&&"INPUT"===e.tagName&&"checkbox"===e.getAttribute("type")}(t);return{value:e?!!t.checked:t.value}}}}),u(["copy","cut","paste"],{createEventArgs:e=>({type:e.type})}),u(["drag","dragend","dragenter","dragleave","dragover","dragstart","drop"],{createEventArgs:e=>{return{...h(t=e),dataTransfer:t.dataTransfer?{dropEffect:t.dataTransfer.dropEffect,effectAllowed:t.dataTransfer.effectAllowed,files:Array.from(t.dataTransfer.files).map((e=>e.name)),items:Array.from(t.dataTransfer.items).map((e=>({kind:e.kind,type:e.type}))),types:t.dataTransfer.types}:null};var t}}),u(["focus","blur","focusin","focusout"],{createEventArgs:e=>({type:e.type})}),u(["keydown","keyup","keypress"],{createEventArgs:e=>{return{key:(t=e).key,code:t.code,location:t.location,repeat:t.repeat,ctrlKey:t.ctrlKey,shiftKey:t.shiftKey,altKey:t.altKey,metaKey:t.metaKey,type:t.type};var t}}),u(["contextmenu","click","mouseover","mouseout","mousemove","mousedown","mouseup","mouseleave","mouseenter","dblclick"],{createEventArgs:e=>h(e)}),u(["error"],{createEventArgs:e=>{return{message:(t=e).message,filename:t.filename,lineno:t.lineno,colno:t.colno,type:t.type};var t}}),u(["loadstart","timeout","abort","load","loadend","progress"],{createEventArgs:e=>{return{lengthComputable:(t=e).lengthComputable,loaded:t.loaded,total:t.total,type:t.type};var t}}),u(["touchcancel","touchend","touchmove","touchenter","touchleave","touchstart"],{createEventArgs:e=>{return{detail:(t=e).detail,touches:d(t.touches),targetTouches:d(t.targetTouches),changedTouches:d(t.changedTouches),ctrlKey:t.ctrlKey,shiftKey:t.shiftKey,altKey:t.altKey,metaKey:t.metaKey,type:t.type};var t}}),u(["gotpointercapture","lostpointercapture","pointercancel","pointerdown","pointerenter","pointerleave","pointermove","pointerout","pointerover","pointerup"],{createEventArgs:e=>{return{...h(t=e),pointerId:t.pointerId,width:t.width,height:t.height,pressure:t.pressure,tiltX:t.tiltX,tiltY:t.tiltY,pointerType:t.pointerType,isPrimary:t.isPrimary};var t}}),u(["wheel","mousewheel"],{createEventArgs:e=>{return{...h(t=e),deltaX:t.deltaX,deltaY:t.deltaY,deltaZ:t.deltaZ,deltaMode:t.deltaMode};var t}}),u(["toggle"],{createEventArgs:()=>({})});const f=["date","datetime-local","month","time","week"],p=new Map;let m,v,g=0;const b={async add(e,t,n){if(!n)throw new Error("initialParameters must be an object, even if empty.");const r="__bl-dynamic-root:"+(++g).toString();p.set(r,e);const o=await E().invokeMethodAsync("AddRootComponent",t,r),a=new w(o,v[t]);return await a.setParameters(n),a}};class y{invoke(e){return this._callback(e)}setCallback(t){this._selfJSObjectReference||(this._selfJSObjectReference=e.createJSObjectReference(this)),this._callback=t}getJSObjectReference(){return this._selfJSObjectReference}dispose(){this._selfJSObjectReference&&e.disposeJSObjectReference(this._selfJSObjectReference)}}class w{constructor(e,t){this._jsEventCallbackWrappers=new Map,this._componentId=e;for(const e of t)"eventcallback"===e.type&&this._jsEventCallbackWrappers.set(e.name.toLowerCase(),new y)}setParameters(e){const t={},n=Object.entries(e||{}),r=n.length;for(const[e,r]of n){const n=this._jsEventCallbackWrappers.get(e.toLowerCase());n&&r?(n.setCallback(r),t[e]=n.getJSObjectReference()):t[e]=r}return E().invokeMethodAsync("SetRootComponentParameters",this._componentId,r,t)}async dispose(){if(null!==this._componentId){await E().invokeMethodAsync("RemoveRootComponent",this._componentId),this._componentId=null;for(const e of this._jsEventCallbackWrappers.values())e.dispose()}}}function E(){if(!m)throw new Error("Dynamic root components have not been enabled in this application.");return m}const S=[];let I;const D=new Promise((e=>{I=e}));function C(e,t,n){return A(e,t.eventHandlerId,(()=>N(e).invokeMethodAsync("DispatchEventAsync",t,n)))}function N(e){const t=S[e];if(!t)throw new Error(`No interop methods are registered for renderer ${e}`);return t}let A=(e,t,n)=>n();const k=x(["abort","blur","canplay","canplaythrough","change","cuechange","durationchange","emptied","ended","error","focus","load","loadeddata","loadedmetadata","loadend","loadstart","mouseenter","mouseleave","pointerenter","pointerleave","pause","play","playing","progress","ratechange","reset","scroll","seeked","seeking","stalled","submit","suspend","timeupdate","toggle","unload","volumechange","waiting","DOMNodeInsertedIntoDocument","DOMNodeRemovedFromDocument"]),T={submit:!0},R=x(["click","dblclick","mousedown","mousemove","mouseup"]);class _{constructor(e){this.browserRendererId=e,this.afterClickCallbacks=[];const t=++_.nextEventDelegatorId;this.eventsCollectionKey=`_blazorEvents_${t}`,this.eventInfoStore=new O(this.onGlobalEvent.bind(this))}setListener(e,t,n,r){const o=this.getEventHandlerInfosForElement(e,!0),a=o.getHandler(t);if(a)this.eventInfoStore.update(a.eventHandlerId,n);else{const a={element:e,eventName:t,eventHandlerId:n,renderingComponentId:r};this.eventInfoStore.add(a),o.setHandler(t,a)}}getHandler(e){return this.eventInfoStore.get(e)}removeListener(e){const t=this.eventInfoStore.remove(e);if(t){const e=t.element,n=this.getEventHandlerInfosForElement(e,!1);n&&n.removeHandler(t.eventName)}}notifyAfterClick(e){this.afterClickCallbacks.push(e),this.eventInfoStore.addGlobalListener("click")}setStopPropagation(e,t,n){this.getEventHandlerInfosForElement(e,!0).stopPropagation(t,n)}setPreventDefault(e,t,n){this.getEventHandlerInfosForElement(e,!0).preventDefault(t,n)}onGlobalEvent(e){if(!(e.target instanceof Element))return;this.dispatchGlobalEventToAllElements(e.type,e);const t=(n=e.type,i.get(n));var n;t&&t.forEach((t=>this.dispatchGlobalEventToAllElements(t,e))),"click"===e.type&&this.afterClickCallbacks.forEach((t=>t(e)))}dispatchGlobalEventToAllElements(e,t){const n=t.composedPath();let r=n.shift(),a=null,i=!1;const s=Object.prototype.hasOwnProperty.call(k,e);let l=!1;for(;r;){const h=r,f=this.getEventHandlerInfosForElement(h,!1);if(f){const n=f.getHandler(e);if(n&&(u=h,d=t.type,!((u instanceof HTMLButtonElement||u instanceof HTMLInputElement||u instanceof HTMLTextAreaElement||u instanceof HTMLSelectElement)&&Object.prototype.hasOwnProperty.call(R,d)&&u.disabled))){if(!i){const n=c(e);a=(null==n?void 0:n.createEventArgs)?n.createEventArgs(t):{},i=!0}Object.prototype.hasOwnProperty.call(T,t.type)&&t.preventDefault(),C(this.browserRendererId,{eventHandlerId:n.eventHandlerId,eventName:e,eventFieldInfo:o.fromEvent(n.renderingComponentId,t)},a)}f.stopPropagation(e)&&(l=!0),f.preventDefault(e)&&t.preventDefault()}r=s||l?void 0:n.shift()}var u,d}getEventHandlerInfosForElement(e,t){return Object.prototype.hasOwnProperty.call(e,this.eventsCollectionKey)?e[this.eventsCollectionKey]:t?e[this.eventsCollectionKey]=new L:null}}_.nextEventDelegatorId=0;class O{constructor(e){this.globalListener=e,this.infosByEventHandlerId={},this.countByEventName={},s.push(this.handleEventNameAliasAdded.bind(this))}add(e){if(this.infosByEventHandlerId[e.eventHandlerId])throw new Error(`Event ${e.eventHandlerId} is already tracked`);this.infosByEventHandlerId[e.eventHandlerId]=e,this.addGlobalListener(e.eventName)}get(e){return this.infosByEventHandlerId[e]}addGlobalListener(e){if(e=l(e),Object.prototype.hasOwnProperty.call(this.countByEventName,e))this.countByEventName[e]++;else{this.countByEventName[e]=1;const t=Object.prototype.hasOwnProperty.call(k,e);document.addEventListener(e,this.globalListener,t)}}update(e,t){if(Object.prototype.hasOwnProperty.call(this.infosByEventHandlerId,t))throw new Error(`Event ${t} is already tracked`);const n=this.infosByEventHandlerId[e];delete this.infosByEventHandlerId[e],n.eventHandlerId=t,this.infosByEventHandlerId[t]=n}remove(e){const t=this.infosByEventHandlerId[e];if(t){delete this.infosByEventHandlerId[e];const n=l(t.eventName);0==--this.countByEventName[n]&&(delete this.countByEventName[n],document.removeEventListener(n,this.globalListener))}return t}handleEventNameAliasAdded(e,t){if(Object.prototype.hasOwnProperty.call(this.countByEventName,e)){const n=this.countByEventName[e];delete this.countByEventName[e],document.removeEventListener(e,this.globalListener),this.addGlobalListener(t),this.countByEventName[t]+=n-1}}}class L{constructor(){this.handlers={},this.preventDefaultFlags=null,this.stopPropagationFlags=null}getHandler(e){return Object.prototype.hasOwnProperty.call(this.handlers,e)?this.handlers[e]:null}setHandler(e,t){this.handlers[e]=t}removeHandler(e){delete this.handlers[e]}preventDefault(e,t){return void 0!==t&&(this.preventDefaultFlags=this.preventDefaultFlags||{},this.preventDefaultFlags[e]=t),!!this.preventDefaultFlags&&this.preventDefaultFlags[e]}stopPropagation(e,t){return void 0!==t&&(this.stopPropagationFlags=this.stopPropagationFlags||{},this.stopPropagationFlags[e]=t),!!this.stopPropagationFlags&&this.stopPropagationFlags[e]}}function x(e){const t={};return e.forEach((e=>{t[e]=!0})),t}const F=q("_blazorLogicalChildren"),P=q("_blazorLogicalParent"),M=q("_blazorLogicalEnd");function B(e,t){if(e.childNodes.length>0&&!t)throw new Error("New logical elements must start empty, or allowExistingContents must be true");return F in e||(e[F]=[]),e}function j(e,t){const n=document.createComment("!");return H(n,e,t),n}function H(e,t,n){const r=e;if(e instanceof Comment&&K(r)&&K(r).length>0)throw new Error("Not implemented: inserting non-empty logical container");if(U(r))throw new Error("Not implemented: moving existing logical children");const o=K(t);if(n0;)J(n,0)}const r=n;r.parentNode.removeChild(r)}function U(e){return e[P]||null}function $(e,t){return K(e)[t]}function z(e){const t=W(e);return"http://www.w3.org/2000/svg"===t.namespaceURI&&"foreignObject"!==t.tagName}function K(e){return e[F]}function X(e,t){const n=K(e);t.forEach((e=>{e.moveRangeStart=n[e.fromSiblingIndex],e.moveRangeEnd=G(e.moveRangeStart)})),t.forEach((t=>{const r=document.createComment("marker");t.moveToBeforeMarker=r;const o=n[t.toSiblingIndex+1];o?o.parentNode.insertBefore(r,o):V(r,e)})),t.forEach((e=>{const t=e.moveToBeforeMarker,n=t.parentNode,r=e.moveRangeStart,o=e.moveRangeEnd;let a=r;for(;a;){const e=a.nextSibling;if(n.insertBefore(a,t),a===o)break;a=e}n.removeChild(t)})),t.forEach((e=>{n[e.toSiblingIndex]=e.moveRangeStart}))}function W(e){if(e instanceof Element||e instanceof DocumentFragment)return e;if(e instanceof Comment)return e.parentNode;throw new Error("Not a valid logical element")}function Y(e){const t=K(U(e));return t[Array.prototype.indexOf.call(t,e)+1]||null}function V(e,t){if(t instanceof Element||t instanceof DocumentFragment)t.appendChild(e);else{if(!(t instanceof Comment))throw new Error(`Cannot append node because the parent is not a valid logical element. Parent: ${t}`);{const n=Y(t);n?n.parentNode.insertBefore(e,n):V(e,U(t))}}}function G(e){if(e instanceof Element||e instanceof DocumentFragment)return e;const t=Y(e);if(t)return t.previousSibling;{const t=U(e);return t instanceof Element||t instanceof DocumentFragment?t.lastChild:G(t)}}function q(e){return"function"==typeof Symbol?Symbol():e}function Z(e){return`_bl_${e}`}const Q="__internalId";e.attachReviver(((e,t)=>t&&"object"==typeof t&&Object.prototype.hasOwnProperty.call(t,Q)&&"string"==typeof t[Q]?function(e){const t=`[${Z(e)}]`;return document.querySelector(t)}(t[Q]):t));const ee="_blazorDeferredValue";function te(e){return"select-multiple"===e.type}function ne(e,t){e.value=t||""}function re(e,t){e instanceof HTMLSelectElement?te(e)?function(e,t){t||(t=[]);for(let n=0;n{pe&&function(e,t){if(0!==e.button||function(e){return e.ctrlKey||e.shiftKey||e.altKey||e.metaKey}(e))return;if(e.defaultPrevented)return;const n=function(e){const t=!window._blazorDisableComposedPath&&e.composedPath&&e.composedPath();if(t){for(let e=0;edocument.baseURI,getLocationHref:()=>location.href,scrollToElement:Ae};function Ae(e){const t=document.getElementById(e);return!!t&&(t.scrollIntoView(),!0)}function ke(e,t,n=!1){const r=ve(e);!t.forceLoad&&me(r)?Te(r,!1,t.replaceHistoryEntry,t.historyEntryState,n):function(e,t){if(location.href===e){const t=e+"?";history.replaceState(null,"",t),location.replace(e)}else t?location.replace(e):location.href=e}(e,t.replaceHistoryEntry)}async function Te(e,t,n,r=void 0,o=!1){if(Oe(),function(e){const t=e.indexOf("#");return t>-1&&location.href.replace(location.hash,"")===e.substring(0,t)}(e))!function(e,t,n){Re(e,t,n);const r=e.indexOf("#");r!==e.length-1&&Ae(e.substring(r+1))}(e,n,r);else{if(!o&&ye&&!await Le(e,r,t))return;fe=!0,Re(e,n,r),await xe(t)}}function Re(e,t,n=void 0){t?history.replaceState({userState:n,_index:we},"",e):(we++,history.pushState({userState:n,_index:we},"",e))}function _e(e){return new Promise((t=>{const n=De;De=()=>{De=n,t()},history.go(e)}))}function Oe(){Ce&&(Ce(!1),Ce=null)}function Le(e,t,n){return new Promise((r=>{Oe(),Ie?(Ee++,Ce=r,Ie(Ee,e,t,n)):r(!1)}))}async function xe(e){var t;Se&&await Se(location.href,null===(t=history.state)||void 0===t?void 0:t.userState,e)}async function Fe(e){var t,n;De&&await De(e),we=null!==(n=null===(t=history.state)||void 0===t?void 0:t._index)&&void 0!==n?n:0}const Pe={focus:function(e,t){if(e instanceof HTMLElement)e.focus({preventScroll:t});else{if(!(e instanceof SVGElement))throw new Error("Unable to focus an invalid element.");if(!e.hasAttribute("tabindex"))throw new Error("Unable to focus an SVG element that does not have a tabindex.");e.focus({preventScroll:t})}},focusBySelector:function(e,t){const n=document.querySelector(e);n&&(n.hasAttribute("tabindex")||(n.tabIndex=-1),n.focus({preventScroll:!0}))}},Me={init:function(e,t,n,r=50){const o=je(t);(o||document.documentElement).style.overflowAnchor="none";const a=document.createRange();u(n.parentElement)&&(t.style.display="table-row",n.style.display="table-row");const i=new IntersectionObserver((function(r){r.forEach((r=>{var o;if(!r.isIntersecting)return;a.setStartAfter(t),a.setEndBefore(n);const i=a.getBoundingClientRect().height,s=null===(o=r.rootBounds)||void 0===o?void 0:o.height;r.target===t?e.invokeMethodAsync("OnSpacerBeforeVisible",r.intersectionRect.top-r.boundingClientRect.top,i,s):r.target===n&&n.offsetHeight>0&&e.invokeMethodAsync("OnSpacerAfterVisible",r.boundingClientRect.bottom-r.intersectionRect.bottom,i,s)}))}),{root:o,rootMargin:`${r}px`});i.observe(t),i.observe(n);const s=l(t),c=l(n);function l(e){const t={attributes:!0},n=new MutationObserver(((n,r)=>{u(e.parentElement)&&(r.disconnect(),e.style.display="table-row",r.observe(e,t)),i.unobserve(e),i.observe(e)}));return n.observe(e,t),n}function u(e){return null!==e&&(e instanceof HTMLTableElement&&""===e.style.display||"table"===e.style.display||e instanceof HTMLTableSectionElement&&""===e.style.display||"table-row-group"===e.style.display)}Be[e._id]={intersectionObserver:i,mutationObserverBefore:s,mutationObserverAfter:c}},dispose:function(e){const t=Be[e._id];t&&(t.intersectionObserver.disconnect(),t.mutationObserverBefore.disconnect(),t.mutationObserverAfter.disconnect(),e.dispose(),delete Be[e._id])}},Be={};function je(e){return e&&e!==document.body&&e!==document.documentElement?"visible"!==getComputedStyle(e).overflowY?e:je(e.parentElement):null}const He={getAndRemoveExistingTitle:function(){var e;const t=document.head?document.head.getElementsByTagName("title"):[];if(0===t.length)return null;let n=null;for(let r=t.length-1;r>=0;r--){const o=t[r],a=o.previousSibling;a instanceof Comment&&null!==U(a)||(null===n&&(n=o.textContent),null===(e=o.parentNode)||void 0===e||e.removeChild(o))}return n}},Je={init:function(e,t){t._blazorInputFileNextFileId=0,t.addEventListener("click",(function(){t.value=""})),t.addEventListener("change",(function(){t._blazorFilesById={};const n=Array.prototype.map.call(t.files,(function(e){const n={id:++t._blazorInputFileNextFileId,lastModified:new Date(e.lastModified).toISOString(),name:e.name,size:e.size,contentType:e.type,readPromise:void 0,arrayBuffer:void 0,blob:e};return t._blazorFilesById[n.id]=n,n}));e.invokeMethodAsync("NotifyChange",n)}))},toImageFile:async function(e,t,n,r,o){const a=Ue(e,t),i=await new Promise((function(e){const t=new Image;t.onload=function(){URL.revokeObjectURL(t.src),e(t)},t.onerror=function(){t.onerror=null,URL.revokeObjectURL(t.src)},t.src=URL.createObjectURL(a.blob)})),s=await new Promise((function(e){var t;const a=Math.min(1,r/i.width),s=Math.min(1,o/i.height),c=Math.min(a,s),l=document.createElement("canvas");l.width=Math.round(i.width*c),l.height=Math.round(i.height*c),null===(t=l.getContext("2d"))||void 0===t||t.drawImage(i,0,0,l.width,l.height),l.toBlob(e,n)})),c={id:++e._blazorInputFileNextFileId,lastModified:a.lastModified,name:a.name,size:(null==s?void 0:s.size)||0,contentType:n,blob:s||a.blob};return e._blazorFilesById[c.id]=c,c},readFileData:async function(e,t){return Ue(e,t).blob}};function Ue(e,t){const n=e._blazorFilesById[t];if(!n)throw new Error(`There is no file with ID ${t}. The file list may have changed. See https://aka.ms/aspnet/blazor-input-file-multiple-selections.`);return n}const $e=new Set,ze={enableNavigationPrompt:function(e){0===$e.size&&window.addEventListener("beforeunload",Ke),$e.add(e)},disableNavigationPrompt:function(e){$e.delete(e),0===$e.size&&window.removeEventListener("beforeunload",Ke)}};function Ke(e){e.preventDefault(),e.returnValue=!0}const Xe=new Map,We={navigateTo:function(e,t,n=!1){ke(e,t instanceof Object?t:{forceLoad:t,replaceHistoryEntry:n})},registerCustomEventType:function(e,t){if(!t)throw new Error("The options parameter is required.");if(a.has(e))throw new Error(`The event '${e}' is already registered.`);if(t.browserEventName){const n=i.get(t.browserEventName);n?n.push(e):i.set(t.browserEventName,[e]),s.forEach((n=>n(e,t.browserEventName)))}a.set(e,t)},rootComponents:b,_internal:{navigationManager:Ne,domWrapper:Pe,Virtualize:Me,PageTitle:He,InputFile:Je,NavigationLock:ze,getJSDataStreamChunk:async function(e,t,n){return e instanceof Blob?await async function(e,t,n){const r=e.slice(t,t+n),o=await r.arrayBuffer();return new Uint8Array(o)}(e,t,n):function(e,t,n){return new Uint8Array(e.buffer,e.byteOffset+t,n)}(e,t,n)},attachWebRendererInterop:function(t,n,r){const o=S.length;return S.push(t),Object.keys(n).length>0&&function(t,n,r){if(m)throw new Error("Dynamic root components have already been enabled.");m=t,v=n;for(const[t,o]of Object.entries(r)){const r=e.findJSFunction(t,0);for(const e of o)r(e,n[e])}}(N(o),n,r),I(),o}}};window.Blazor=We;let Ye=!1;const Ve="function"==typeof TextDecoder?new TextDecoder("utf-8"):null,Ge=Ve?Ve.decode.bind(Ve):function(e){let t=0;const n=e.length,r=[],o=[];for(;t65535&&(o-=65536,r.push(o>>>10&1023|55296),o=56320|1023&o),r.push(o)}r.length>1024&&(o.push(String.fromCharCode.apply(null,r)),r.length=0)}return o.push(String.fromCharCode.apply(null,r)),o.join("")},qe=Math.pow(2,32),Ze=Math.pow(2,21)-1;function Qe(e,t){return e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24}function et(e,t){return e[t]+(e[t+1]<<8)+(e[t+2]<<16)+(e[t+3]<<24>>>0)}function tt(e,t){const n=et(e,t+4);if(n>Ze)throw new Error(`Cannot read uint64 with high order part ${n}, because the result would exceed Number.MAX_SAFE_INTEGER.`);return n*qe+et(e,t)}class nt{constructor(e){this.batchData=e;const t=new it(e);this.arrayRangeReader=new st(e),this.arrayBuilderSegmentReader=new ct(e),this.diffReader=new rt(e),this.editReader=new ot(e,t),this.frameReader=new at(e,t)}updatedComponents(){return Qe(this.batchData,this.batchData.length-20)}referenceFrames(){return Qe(this.batchData,this.batchData.length-16)}disposedComponentIds(){return Qe(this.batchData,this.batchData.length-12)}disposedEventHandlerIds(){return Qe(this.batchData,this.batchData.length-8)}updatedComponentsEntry(e,t){const n=e+4*t;return Qe(this.batchData,n)}referenceFramesEntry(e,t){return e+20*t}disposedComponentIdsEntry(e,t){const n=e+4*t;return Qe(this.batchData,n)}disposedEventHandlerIdsEntry(e,t){const n=e+8*t;return tt(this.batchData,n)}}class rt{constructor(e){this.batchDataUint8=e}componentId(e){return Qe(this.batchDataUint8,e)}edits(e){return e+4}editsEntry(e,t){return e+16*t}}class ot{constructor(e,t){this.batchDataUint8=e,this.stringReader=t}editType(e){return Qe(this.batchDataUint8,e)}siblingIndex(e){return Qe(this.batchDataUint8,e+4)}newTreeIndex(e){return Qe(this.batchDataUint8,e+8)}moveToSiblingIndex(e){return Qe(this.batchDataUint8,e+8)}removedAttributeName(e){const t=Qe(this.batchDataUint8,e+12);return this.stringReader.readString(t)}}class at{constructor(e,t){this.batchDataUint8=e,this.stringReader=t}frameType(e){return Qe(this.batchDataUint8,e)}subtreeLength(e){return Qe(this.batchDataUint8,e+4)}elementReferenceCaptureId(e){const t=Qe(this.batchDataUint8,e+4);return this.stringReader.readString(t)}componentId(e){return Qe(this.batchDataUint8,e+8)}elementName(e){const t=Qe(this.batchDataUint8,e+8);return this.stringReader.readString(t)}textContent(e){const t=Qe(this.batchDataUint8,e+4);return this.stringReader.readString(t)}markupContent(e){const t=Qe(this.batchDataUint8,e+4);return this.stringReader.readString(t)}attributeName(e){const t=Qe(this.batchDataUint8,e+4);return this.stringReader.readString(t)}attributeValue(e){const t=Qe(this.batchDataUint8,e+8);return this.stringReader.readString(t)}attributeEventHandlerId(e){return tt(this.batchDataUint8,e+12)}}class it{constructor(e){this.batchDataUint8=e,this.stringTableStartIndex=Qe(e,e.length-4)}readString(e){if(-1===e)return null;{const n=Qe(this.batchDataUint8,this.stringTableStartIndex+4*e),r=function(e,t){let n=0,r=0;for(let o=0;o<4;o++){const a=e[t+o];if(n|=(127&a)<async function(e,n){const r=function(e){const t=document.baseURI;return t.endsWith("/")?`${t}${e}`:`${t}/${e}`}(n),o=await import(r);if(void 0===o)return;const{beforeStart:a,afterStarted:i}=o;return i&&e.afterStartedCallbacks.push(i),a?a(...t):void 0}(this,e))))}async invokeAfterStartedCallbacks(e){await D,await Promise.all(this.afterStartedCallbacks.map((t=>t(e))))}}let Et,St=!1;async function It(){if(St)throw new Error("Blazor has already started.");St=!0,Et=e.attachDispatcher({beginInvokeDotNetFromJS:ht,endInvokeJSFromDotNet:ft,sendByteArray:pt});const t=await async function(){const e=await fetch("_framework/blazor.modules.json",{method:"GET",credentials:"include",cache:"no-cache"}),t=await e.json(),n=new wt;return await n.importInitializersAsync(t,[]),n}();(function(){const e={AttachToDocument:(e,t)=>{!function(e,t,n){const r="::before";let o=!1;if(e.endsWith("::after"))e=e.slice(0,-7),o=!0;else if(e.endsWith(r))throw new Error(`The '${r}' selector is not supported.`);const a=function(e){const t=p.get(e);if(t)return p.delete(e),t}(e)||document.querySelector(e);if(!a)throw new Error(`Could not find any element matching selector '${e}'.`);!function(e,t,n,r){let o=de[0];o||(o=new ce(0),de[0]=o),o.attachRootComponentToLogicalElement(n,t,r)}(0,B(a,!0),t,o)}(t,e)},RenderBatch:(e,t)=>{try{const n=yt(t);(function(e,t){const n=de[0];if(!n)throw new Error("There is no browser renderer with ID 0.");const r=t.arrayRangeReader,o=t.updatedComponents(),a=r.values(o),i=r.count(o),s=t.referenceFrames(),c=r.values(s),l=t.diffReader;for(let e=0;e{ut=!0,console.error(`${e}\n${t}`),function(){const e=document.querySelector("#blazor-error-ui");e&&(e.style.display="block"),Ye||(Ye=!0,document.querySelectorAll("#blazor-error-ui .reload").forEach((e=>{e.onclick=function(e){location.reload(),e.preventDefault()}})),document.querySelectorAll("#blazor-error-ui .dismiss").forEach((e=>{e.onclick=function(e){const t=document.querySelector("#blazor-error-ui");t&&(t.style.display="none"),e.preventDefault()}})))}()},BeginInvokeJS:Et.beginInvokeJSFromDotNet.bind(Et),EndInvokeDotNet:Et.endInvokeDotNetFromJS.bind(Et),SendByteArrayToJS:bt,Navigate:Ne.navigateTo,SetHasLocationChangingListeners:Ne.setHasLocationChangingListeners,EndLocationChanging:Ne.endLocationChanging};window.external.receiveMessage((t=>{const n=function(e){if(ut||!e||!e.startsWith(lt))return null;const t=e.substring(lt.length),[n,...r]=JSON.parse(t);return{messageType:n,args:r}}(t);if(n){if(!Object.prototype.hasOwnProperty.call(e,n.messageType))throw new Error(`Unsupported IPC message type '${n.messageType}'`);e[n.messageType].apply(null,n.args)}}))})(),We._internal.receiveWebViewDotNetDataStream=Dt,Ne.enableNavigationInterception(),Ne.listenForNavigationEvents(mt,vt),gt("AttachPage",Ne.getBaseURI(),Ne.getLocationHref()),await t.invokeAfterStartedCallbacks(We)}function Dt(e,t,n,r){!function(e,t,n,r,o){let a=Xe.get(t);if(!a){const n=new ReadableStream({start(e){Xe.set(t,e),a=e}});e.supplyDotNetStream(t,n)}o?(a.error(o),Xe.delete(t)):0===r?(a.close(),Xe.delete(t)):a.enqueue(n.length===r?n:n.subarray(0,r))}(Et,e,t,n,r)}We.start=It,window.DotNet=e,document&&document.currentScript&&"false"!==document.currentScript.getAttribute("autostart")&&It()})(); \ No newline at end of file +(()=>{"use strict";var e,t,n,r={d:(e,t)=>{for(var n in t)r.o(t,n)&&!r.o(e,n)&&Object.defineProperty(e,n,{enumerable:!0,get:t[n]})},o:(e,t)=>Object.prototype.hasOwnProperty.call(e,t)};r.d({},{e:()=>Dt}),function(e){const t=[],n="__jsObjectId",r="__dotNetObject",o="__byte[]",a="__dotNetStream",s="__jsStreamReferenceLength";let i,c;class l{constructor(e){this._jsObject=e,this._cachedFunctions=new Map}findFunction(e){const t=this._cachedFunctions.get(e);if(t)return t;let n,r=this._jsObject;if(e.split(".").forEach((t=>{if(!(t in r))throw new Error(`Could not find '${e}' ('${t}' was undefined).`);n=r,r=r[t]})),r instanceof Function)return r=r.bind(n),this._cachedFunctions.set(e,r),r;throw new Error(`The value '${e}' is not a function.`)}getWrappedObject(){return this._jsObject}}const u={0:new l(window)};u[0]._cachedFunctions.set("import",(e=>("string"==typeof e&&e.startsWith("./")&&(e=new URL(e.substr(2),document.baseURI).toString()),import(e))));let d,h=1;function f(e){t.push(e)}function p(e){if(e&&"object"==typeof e){u[h]=new l(e);const t={[n]:h};return h++,t}throw new Error(`Cannot create a JSObjectReference from the value '${e}'.`)}function m(e){let t=-1;if(e instanceof ArrayBuffer&&(e=new Uint8Array(e)),e instanceof Blob)t=e.size;else{if(!(e.buffer instanceof ArrayBuffer))throw new Error("Supplied value is not a typed array or blob.");if(void 0===e.byteLength)throw new Error(`Cannot create a JSStreamReference from the value '${e}' as it doesn't have a byteLength.`);t=e.byteLength}const r={[s]:t};try{const t=p(e);r[n]=t[n]}catch(t){throw new Error(`Cannot create a JSStreamReference from the value '${e}'.`)}return r}function v(e,n){c=e;const r=n?JSON.parse(n,((e,n)=>t.reduce(((t,n)=>n(e,t)),n))):null;return c=void 0,r}function g(){if(void 0===i)throw new Error("No call dispatcher has been set.");if(null===i)throw new Error("There are multiple .NET runtimes present, so a default dispatcher could not be resolved. Use DotNetObject to invoke .NET instance methods.");return i}e.attachDispatcher=function(e){const t=new b(e);return void 0===i?i=t:i&&(i=null),t},e.attachReviver=f,e.invokeMethod=function(e,t,...n){return g().invokeDotNetStaticMethod(e,t,...n)},e.invokeMethodAsync=function(e,t,...n){return g().invokeDotNetStaticMethodAsync(e,t,...n)},e.createJSObjectReference=p,e.createJSStreamReference=m,e.disposeJSObjectReference=function(e){const t=e&&e[n];"number"==typeof t&&E(t)},function(e){e[e.Default=0]="Default",e[e.JSObjectReference=1]="JSObjectReference",e[e.JSStreamReference=2]="JSStreamReference",e[e.JSVoidResult=3]="JSVoidResult"}(d=e.JSCallResultType||(e.JSCallResultType={}));class b{constructor(e){this._dotNetCallDispatcher=e,this._byteArraysToBeRevived=new Map,this._pendingDotNetToJSStreams=new Map,this._pendingAsyncCalls={},this._nextAsyncCallId=1}getDotNetCallDispatcher(){return this._dotNetCallDispatcher}invokeJSFromDotNet(e,t,n,r){const o=v(this,t),a=C(w(e,r)(...o||[]),n);return null==a?null:N(this,a)}beginInvokeJSFromDotNet(e,t,n,r,o){const a=new Promise((e=>{const r=v(this,n);e(w(t,o)(...r||[]))}));e&&a.then((t=>N(this,[e,!0,C(t,r)]))).then((t=>this._dotNetCallDispatcher.endInvokeJSFromDotNet(e,!0,t)),(t=>this._dotNetCallDispatcher.endInvokeJSFromDotNet(e,!1,JSON.stringify([e,!1,y(t)]))))}endInvokeDotNetFromJS(e,t,n){const r=t?v(this,n):new Error(n);this.completePendingCall(parseInt(e,10),t,r)}invokeDotNetStaticMethod(e,t,...n){return this.invokeDotNetMethod(e,t,null,n)}invokeDotNetStaticMethodAsync(e,t,...n){return this.invokeDotNetMethodAsync(e,t,null,n)}invokeDotNetMethod(e,t,n,r){if(this._dotNetCallDispatcher.invokeDotNetFromJS){const o=N(this,r),a=this._dotNetCallDispatcher.invokeDotNetFromJS(e,t,n,o);return a?v(this,a):null}throw new Error("The current dispatcher does not support synchronous calls from JS to .NET. Use invokeDotNetMethodAsync instead.")}invokeDotNetMethodAsync(e,t,n,r){if(e&&n)throw new Error(`For instance method calls, assemblyName should be null. Received '${e}'.`);const o=this._nextAsyncCallId++,a=new Promise(((e,t)=>{this._pendingAsyncCalls[o]={resolve:e,reject:t}}));try{const a=N(this,r);this._dotNetCallDispatcher.beginInvokeDotNetFromJS(o,e,t,n,a)}catch(e){this.completePendingCall(o,!1,e)}return a}receiveByteArray(e,t){this._byteArraysToBeRevived.set(e,t)}processByteArray(e){const t=this._byteArraysToBeRevived.get(e);return t?(this._byteArraysToBeRevived.delete(e),t):null}supplyDotNetStream(e,t){if(this._pendingDotNetToJSStreams.has(e)){const n=this._pendingDotNetToJSStreams.get(e);this._pendingDotNetToJSStreams.delete(e),n.resolve(t)}else{const n=new D;n.resolve(t),this._pendingDotNetToJSStreams.set(e,n)}}getDotNetStreamPromise(e){let t;if(this._pendingDotNetToJSStreams.has(e))t=this._pendingDotNetToJSStreams.get(e).streamPromise,this._pendingDotNetToJSStreams.delete(e);else{const n=new D;this._pendingDotNetToJSStreams.set(e,n),t=n.streamPromise}return t}completePendingCall(e,t,n){if(!this._pendingAsyncCalls.hasOwnProperty(e))throw new Error(`There is no pending async call with ID ${e}.`);const r=this._pendingAsyncCalls[e];delete this._pendingAsyncCalls[e],t?r.resolve(n):r.reject(n)}}function y(e){return e instanceof Error?`${e.message}\n${e.stack}`:e?e.toString():"null"}function w(e,t){const n=u[t];if(n)return n.findFunction(e);throw new Error(`JS object instance with ID ${t} does not exist (has it been disposed?).`)}function E(e){delete u[e]}e.findJSFunction=w,e.disposeJSObjectReferenceById=E;class S{constructor(e,t){this._id=e,this._callDispatcher=t}invokeMethod(e,...t){return this._callDispatcher.invokeDotNetMethod(null,e,this._id,t)}invokeMethodAsync(e,...t){return this._callDispatcher.invokeDotNetMethodAsync(null,e,this._id,t)}dispose(){this._callDispatcher.invokeDotNetMethodAsync(null,"__Dispose",this._id,null).catch((e=>console.error(e)))}serializeAsArg(){return{[r]:this._id}}}e.DotNetObject=S,f((function(e,t){if(t&&"object"==typeof t){if(t.hasOwnProperty(r))return new S(t[r],c);if(t.hasOwnProperty(n)){const e=t[n],r=u[e];if(r)return r.getWrappedObject();throw new Error(`JS object instance with Id '${e}' does not exist. It may have been disposed.`)}if(t.hasOwnProperty(o)){const e=t[o],n=c.processByteArray(e);if(void 0===n)throw new Error(`Byte array index '${e}' does not exist.`);return n}if(t.hasOwnProperty(a)){const e=t[a],n=c.getDotNetStreamPromise(e);return new I(n)}}return t}));class I{constructor(e){this._streamPromise=e}stream(){return this._streamPromise}async arrayBuffer(){return new Response(await this.stream()).arrayBuffer()}}class D{constructor(){this.streamPromise=new Promise(((e,t)=>{this.resolve=e,this.reject=t}))}}function C(e,t){switch(t){case d.Default:return e;case d.JSObjectReference:return p(e);case d.JSStreamReference:return m(e);case d.JSVoidResult:return null;default:throw new Error(`Invalid JS call result type '${t}'.`)}}let A=0;function N(e,t){A=0,c=e;const n=JSON.stringify(t,k);return c=void 0,n}function k(e,t){if(t instanceof S)return t.serializeAsArg();if(t instanceof Uint8Array){c.getDotNetCallDispatcher().sendByteArray(A,t);const e={[o]:A};return A++,e}return t}}(e||(e={})),function(e){e[e.prependFrame=1]="prependFrame",e[e.removeFrame=2]="removeFrame",e[e.setAttribute=3]="setAttribute",e[e.removeAttribute=4]="removeAttribute",e[e.updateText=5]="updateText",e[e.stepIn=6]="stepIn",e[e.stepOut=7]="stepOut",e[e.updateMarkup=8]="updateMarkup",e[e.permutationListEntry=9]="permutationListEntry",e[e.permutationListEnd=10]="permutationListEnd"}(t||(t={})),function(e){e[e.element=1]="element",e[e.text=2]="text",e[e.attribute=3]="attribute",e[e.component=4]="component",e[e.region=5]="region",e[e.elementReferenceCapture=6]="elementReferenceCapture",e[e.markup=8]="markup",e[e.namedEvent=10]="namedEvent"}(n||(n={}));class o{constructor(e,t){this.componentId=e,this.fieldValue=t}static fromEvent(e,t){const n=t.target;if(n instanceof Element){const t=function(e){return e instanceof HTMLInputElement?e.type&&"checkbox"===e.type.toLowerCase()?{value:e.checked}:{value:e.value}:e instanceof HTMLSelectElement||e instanceof HTMLTextAreaElement?{value:e.value}:null}(n);if(t)return new o(e,t.value)}return null}}const a=new Map,s=new Map,i=[];function c(e){return a.get(e)}function l(e){const t=a.get(e);return(null==t?void 0:t.browserEventName)||e}function u(e,t){e.forEach((e=>a.set(e,t)))}function d(e){const t=[];for(let n=0;ne.selected)).map((e=>e.value))}}{const e=function(e){return!!e&&"INPUT"===e.tagName&&"checkbox"===e.getAttribute("type")}(t);return{value:e?!!t.checked:t.value}}}}),u(["copy","cut","paste"],{createEventArgs:e=>({type:e.type})}),u(["drag","dragend","dragenter","dragleave","dragover","dragstart","drop"],{createEventArgs:e=>{return{...h(t=e),dataTransfer:t.dataTransfer?{dropEffect:t.dataTransfer.dropEffect,effectAllowed:t.dataTransfer.effectAllowed,files:Array.from(t.dataTransfer.files).map((e=>e.name)),items:Array.from(t.dataTransfer.items).map((e=>({kind:e.kind,type:e.type}))),types:t.dataTransfer.types}:null};var t}}),u(["focus","blur","focusin","focusout"],{createEventArgs:e=>({type:e.type})}),u(["keydown","keyup","keypress"],{createEventArgs:e=>{return{key:(t=e).key,code:t.code,location:t.location,repeat:t.repeat,ctrlKey:t.ctrlKey,shiftKey:t.shiftKey,altKey:t.altKey,metaKey:t.metaKey,type:t.type};var t}}),u(["contextmenu","click","mouseover","mouseout","mousemove","mousedown","mouseup","mouseleave","mouseenter","dblclick"],{createEventArgs:e=>h(e)}),u(["error"],{createEventArgs:e=>{return{message:(t=e).message,filename:t.filename,lineno:t.lineno,colno:t.colno,type:t.type};var t}}),u(["loadstart","timeout","abort","load","loadend","progress"],{createEventArgs:e=>{return{lengthComputable:(t=e).lengthComputable,loaded:t.loaded,total:t.total,type:t.type};var t}}),u(["touchcancel","touchend","touchmove","touchenter","touchleave","touchstart"],{createEventArgs:e=>{return{detail:(t=e).detail,touches:d(t.touches),targetTouches:d(t.targetTouches),changedTouches:d(t.changedTouches),ctrlKey:t.ctrlKey,shiftKey:t.shiftKey,altKey:t.altKey,metaKey:t.metaKey,type:t.type};var t}}),u(["gotpointercapture","lostpointercapture","pointercancel","pointerdown","pointerenter","pointerleave","pointermove","pointerout","pointerover","pointerup"],{createEventArgs:e=>{return{...h(t=e),pointerId:t.pointerId,width:t.width,height:t.height,pressure:t.pressure,tiltX:t.tiltX,tiltY:t.tiltY,pointerType:t.pointerType,isPrimary:t.isPrimary};var t}}),u(["wheel","mousewheel"],{createEventArgs:e=>{return{...h(t=e),deltaX:t.deltaX,deltaY:t.deltaY,deltaZ:t.deltaZ,deltaMode:t.deltaMode};var t}}),u(["toggle"],{createEventArgs:()=>({})});const f=["date","datetime-local","month","time","week"],p=new Map;let m,v,g=0;const b={async add(e,t,n){if(!n)throw new Error("initialParameters must be an object, even if empty.");const r="__bl-dynamic-root:"+(++g).toString();p.set(r,e);const o=await E().invokeMethodAsync("AddRootComponent",t,r),a=new w(o,v[t]);return await a.setParameters(n),a}};class y{invoke(e){return this._callback(e)}setCallback(t){this._selfJSObjectReference||(this._selfJSObjectReference=e.createJSObjectReference(this)),this._callback=t}getJSObjectReference(){return this._selfJSObjectReference}dispose(){this._selfJSObjectReference&&e.disposeJSObjectReference(this._selfJSObjectReference)}}class w{constructor(e,t){this._jsEventCallbackWrappers=new Map,this._componentId=e;for(const e of t)"eventcallback"===e.type&&this._jsEventCallbackWrappers.set(e.name.toLowerCase(),new y)}setParameters(e){const t={},n=Object.entries(e||{}),r=n.length;for(const[e,r]of n){const n=this._jsEventCallbackWrappers.get(e.toLowerCase());n&&r?(n.setCallback(r),t[e]=n.getJSObjectReference()):t[e]=r}return E().invokeMethodAsync("SetRootComponentParameters",this._componentId,r,t)}async dispose(){if(null!==this._componentId){await E().invokeMethodAsync("RemoveRootComponent",this._componentId),this._componentId=null;for(const e of this._jsEventCallbackWrappers.values())e.dispose()}}}function E(){if(!m)throw new Error("Dynamic root components have not been enabled in this application.");return m}const S=new Map,I=new Map,D=new Map;let C;const A=new Promise((e=>{C=e}));function N(e,t,n){return T(e,t.eventHandlerId,(()=>k(e).invokeMethodAsync("DispatchEventAsync",t,n)))}function k(e){const t=S.get(e);if(!t)throw new Error(`No interop methods are registered for renderer ${e}`);return t}let T=(e,t,n)=>n();const R=M(["abort","blur","canplay","canplaythrough","change","cuechange","durationchange","emptied","ended","error","focus","load","loadeddata","loadedmetadata","loadend","loadstart","mouseenter","mouseleave","pointerenter","pointerleave","pause","play","playing","progress","ratechange","reset","scroll","seeked","seeking","stalled","submit","suspend","timeupdate","toggle","unload","volumechange","waiting","DOMNodeInsertedIntoDocument","DOMNodeRemovedFromDocument"]),_={submit:!0},O=M(["click","dblclick","mousedown","mousemove","mouseup"]);class x{constructor(e){this.browserRendererId=e,this.afterClickCallbacks=[];const t=++x.nextEventDelegatorId;this.eventsCollectionKey=`_blazorEvents_${t}`,this.eventInfoStore=new L(this.onGlobalEvent.bind(this))}setListener(e,t,n,r){const o=this.getEventHandlerInfosForElement(e,!0),a=o.getHandler(t);if(a)this.eventInfoStore.update(a.eventHandlerId,n);else{const a={element:e,eventName:t,eventHandlerId:n,renderingComponentId:r};this.eventInfoStore.add(a),o.setHandler(t,a)}}getHandler(e){return this.eventInfoStore.get(e)}removeListener(e){const t=this.eventInfoStore.remove(e);if(t){const e=t.element,n=this.getEventHandlerInfosForElement(e,!1);n&&n.removeHandler(t.eventName)}}notifyAfterClick(e){this.afterClickCallbacks.push(e),this.eventInfoStore.addGlobalListener("click")}setStopPropagation(e,t,n){this.getEventHandlerInfosForElement(e,!0).stopPropagation(t,n)}setPreventDefault(e,t,n){this.getEventHandlerInfosForElement(e,!0).preventDefault(t,n)}onGlobalEvent(e){if(!(e.target instanceof Element))return;this.dispatchGlobalEventToAllElements(e.type,e);const t=(n=e.type,s.get(n));var n;t&&t.forEach((t=>this.dispatchGlobalEventToAllElements(t,e))),"click"===e.type&&this.afterClickCallbacks.forEach((t=>t(e)))}dispatchGlobalEventToAllElements(e,t){const n=t.composedPath();let r=n.shift(),a=null,s=!1;const i=Object.prototype.hasOwnProperty.call(R,e);let l=!1;for(;r;){const h=r,f=this.getEventHandlerInfosForElement(h,!1);if(f){const n=f.getHandler(e);if(n&&(u=h,d=t.type,!((u instanceof HTMLButtonElement||u instanceof HTMLInputElement||u instanceof HTMLTextAreaElement||u instanceof HTMLSelectElement)&&Object.prototype.hasOwnProperty.call(O,d)&&u.disabled))){if(!s){const n=c(e);a=(null==n?void 0:n.createEventArgs)?n.createEventArgs(t):{},s=!0}Object.prototype.hasOwnProperty.call(_,t.type)&&t.preventDefault(),N(this.browserRendererId,{eventHandlerId:n.eventHandlerId,eventName:e,eventFieldInfo:o.fromEvent(n.renderingComponentId,t)},a)}f.stopPropagation(e)&&(l=!0),f.preventDefault(e)&&t.preventDefault()}r=i||l?void 0:n.shift()}var u,d}getEventHandlerInfosForElement(e,t){return Object.prototype.hasOwnProperty.call(e,this.eventsCollectionKey)?e[this.eventsCollectionKey]:t?e[this.eventsCollectionKey]=new F:null}}x.nextEventDelegatorId=0;class L{constructor(e){this.globalListener=e,this.infosByEventHandlerId={},this.countByEventName={},i.push(this.handleEventNameAliasAdded.bind(this))}add(e){if(this.infosByEventHandlerId[e.eventHandlerId])throw new Error(`Event ${e.eventHandlerId} is already tracked`);this.infosByEventHandlerId[e.eventHandlerId]=e,this.addGlobalListener(e.eventName)}get(e){return this.infosByEventHandlerId[e]}addGlobalListener(e){if(e=l(e),Object.prototype.hasOwnProperty.call(this.countByEventName,e))this.countByEventName[e]++;else{this.countByEventName[e]=1;const t=Object.prototype.hasOwnProperty.call(R,e);document.addEventListener(e,this.globalListener,t)}}update(e,t){if(Object.prototype.hasOwnProperty.call(this.infosByEventHandlerId,t))throw new Error(`Event ${t} is already tracked`);const n=this.infosByEventHandlerId[e];delete this.infosByEventHandlerId[e],n.eventHandlerId=t,this.infosByEventHandlerId[t]=n}remove(e){const t=this.infosByEventHandlerId[e];if(t){delete this.infosByEventHandlerId[e];const n=l(t.eventName);0==--this.countByEventName[n]&&(delete this.countByEventName[n],document.removeEventListener(n,this.globalListener))}return t}handleEventNameAliasAdded(e,t){if(Object.prototype.hasOwnProperty.call(this.countByEventName,e)){const n=this.countByEventName[e];delete this.countByEventName[e],document.removeEventListener(e,this.globalListener),this.addGlobalListener(t),this.countByEventName[t]+=n-1}}}class F{constructor(){this.handlers={},this.preventDefaultFlags=null,this.stopPropagationFlags=null}getHandler(e){return Object.prototype.hasOwnProperty.call(this.handlers,e)?this.handlers[e]:null}setHandler(e,t){this.handlers[e]=t}removeHandler(e){delete this.handlers[e]}preventDefault(e,t){return void 0!==t&&(this.preventDefaultFlags=this.preventDefaultFlags||{},this.preventDefaultFlags[e]=t),!!this.preventDefaultFlags&&this.preventDefaultFlags[e]}stopPropagation(e,t){return void 0!==t&&(this.stopPropagationFlags=this.stopPropagationFlags||{},this.stopPropagationFlags[e]=t),!!this.stopPropagationFlags&&this.stopPropagationFlags[e]}}function M(e){const t={};return e.forEach((e=>{t[e]=!0})),t}const P=Symbol(),B=Symbol();function j(e,t){if(P in e)return e;const n=[];if(e.childNodes.length>0){if(!t)throw new Error("New logical elements must start empty, or allowExistingContents must be true");e.childNodes.forEach((t=>{const r=j(t,!0);r[B]=e,n.push(r)}))}return e[P]=n,e}function H(e){const t=W(e);for(;t.length;)$(e,0)}function J(e,t){const n=document.createComment("!");return U(n,e,t),n}function U(e,t,n){const r=e;let o=e;if(P in e){const t=Z(r);if(t!==e){const n=new Range;n.setStartBefore(e),n.setEndAfter(t),o=n.extractContents()}}const a=z(r);if(a){const e=W(a),t=Array.prototype.indexOf.call(e,r);e.splice(t,1),delete r[B]}const s=W(t);if(n0;)$(n,0)}const r=n;r.parentNode.removeChild(r)}function z(e){return e[B]||null}function K(e,t){return W(e)[t]}function X(e){const t=G(e);return"http://www.w3.org/2000/svg"===t.namespaceURI&&"foreignObject"!==t.tagName}function W(e){return e[P]}function Y(e){const t=W(z(e));return t[Array.prototype.indexOf.call(t,e)+1]||null}function V(e,t){const n=W(e);t.forEach((e=>{e.moveRangeStart=n[e.fromSiblingIndex],e.moveRangeEnd=Z(e.moveRangeStart)})),t.forEach((t=>{const r=document.createComment("marker");t.moveToBeforeMarker=r;const o=n[t.toSiblingIndex+1];o?o.parentNode.insertBefore(r,o):q(r,e)})),t.forEach((e=>{const t=e.moveToBeforeMarker,n=t.parentNode,r=e.moveRangeStart,o=e.moveRangeEnd;let a=r;for(;a;){const e=a.nextSibling;if(n.insertBefore(a,t),a===o)break;a=e}n.removeChild(t)})),t.forEach((e=>{n[e.toSiblingIndex]=e.moveRangeStart}))}function G(e){if(e instanceof Element||e instanceof DocumentFragment)return e;if(e instanceof Comment)return e.parentNode;throw new Error("Not a valid logical element")}function q(e,t){if(t instanceof Element||t instanceof DocumentFragment)t.appendChild(e);else{if(!(t instanceof Comment))throw new Error(`Cannot append node because the parent is not a valid logical element. Parent: ${t}`);{const n=Y(t);n?n.parentNode.insertBefore(e,n):q(e,z(t))}}}function Z(e){if(e instanceof Element||e instanceof DocumentFragment)return e;const t=Y(e);if(t)return t.previousSibling;{const t=z(e);return t instanceof Element||t instanceof DocumentFragment?t.lastChild:Z(t)}}function Q(e){return`_bl_${e}`}Symbol();const ee="__internalId";e.attachReviver(((e,t)=>t&&"object"==typeof t&&Object.prototype.hasOwnProperty.call(t,ee)&&"string"==typeof t[ee]?function(e){const t=`[${Q(e)}]`;return document.querySelector(t)}(t[ee]):t));const te="_blazorDeferredValue";function ne(e){return"select-multiple"===e.type}function re(e,t){e.value=t||""}function oe(e,t){e instanceof HTMLSelectElement?ne(e)?function(e,t){t||(t=[]);for(let n=0;n{ge&&function(e,t){if(0!==e.button||function(e){return e.ctrlKey||e.shiftKey||e.altKey||e.metaKey}(e))return;if(e.defaultPrevented)return;const n=function(e){const t=!window._blazorDisableComposedPath&&e.composedPath&&e.composedPath();if(t){for(let e=0;edocument.baseURI,getLocationHref:()=>location.href,scrollToElement:Re};function Re(e){const t=document.getElementById(e);return!!t&&(t.scrollIntoView(),!0)}function _e(e,t,n=!1){const r=ye(e);!t.forceLoad&&be(r)?Oe(r,!1,t.replaceHistoryEntry,t.historyEntryState,n):function(e,t){if(location.href===e){const t=e+"?";history.replaceState(null,"",t),location.replace(e)}else t?location.replace(e):location.href=e}(e,t.replaceHistoryEntry)}async function Oe(e,t,n,r=void 0,o=!1){if(Fe(),function(e){const t=e.indexOf("#");return t>-1&&location.href.replace(location.hash,"")===e.substring(0,t)}(e))!function(e,t,n){xe(e,t,n);const r=e.indexOf("#");r!==e.length-1&&Re(e.substring(r+1))}(e,n,r);else{if(!o&&Se&&!await Me(e,r,t))return;ve=!0,xe(e,n,r),await Pe(t)}}function xe(e,t,n=void 0){t?history.replaceState({userState:n,_index:Ie},"",e):(Ie++,history.pushState({userState:n,_index:Ie},"",e))}function Le(e){return new Promise((t=>{const n=Ne;Ne=()=>{Ne=n,t()},history.go(e)}))}function Fe(){ke&&(ke(!1),ke=null)}function Me(e,t,n){return new Promise((r=>{Fe(),Ae?(De++,ke=r,Ae(De,e,t,n)):r(!1)}))}async function Pe(e){var t;Ce&&await Ce(location.href,null===(t=history.state)||void 0===t?void 0:t.userState,e)}async function Be(e){var t,n;Ne&&await Ne(e),Ie=null!==(n=null===(t=history.state)||void 0===t?void 0:t._index)&&void 0!==n?n:0}const je={focus:function(e,t){if(e instanceof HTMLElement)e.focus({preventScroll:t});else{if(!(e instanceof SVGElement))throw new Error("Unable to focus an invalid element.");if(!e.hasAttribute("tabindex"))throw new Error("Unable to focus an SVG element that does not have a tabindex.");e.focus({preventScroll:t})}},focusBySelector:function(e,t){const n=document.querySelector(e);n&&(n.hasAttribute("tabindex")||(n.tabIndex=-1),n.focus({preventScroll:!0}))}},He={init:function(e,t,n,r=50){const o=Ue(t);(o||document.documentElement).style.overflowAnchor="none";const a=document.createRange();u(n.parentElement)&&(t.style.display="table-row",n.style.display="table-row");const s=new IntersectionObserver((function(r){r.forEach((r=>{var o;if(!r.isIntersecting)return;a.setStartAfter(t),a.setEndBefore(n);const s=a.getBoundingClientRect().height,i=null===(o=r.rootBounds)||void 0===o?void 0:o.height;r.target===t?e.invokeMethodAsync("OnSpacerBeforeVisible",r.intersectionRect.top-r.boundingClientRect.top,s,i):r.target===n&&n.offsetHeight>0&&e.invokeMethodAsync("OnSpacerAfterVisible",r.boundingClientRect.bottom-r.intersectionRect.bottom,s,i)}))}),{root:o,rootMargin:`${r}px`});s.observe(t),s.observe(n);const i=l(t),c=l(n);function l(e){const t={attributes:!0},n=new MutationObserver(((n,r)=>{u(e.parentElement)&&(r.disconnect(),e.style.display="table-row",r.observe(e,t)),s.unobserve(e),s.observe(e)}));return n.observe(e,t),n}function u(e){return null!==e&&(e instanceof HTMLTableElement&&""===e.style.display||"table"===e.style.display||e instanceof HTMLTableSectionElement&&""===e.style.display||"table-row-group"===e.style.display)}Je[e._id]={intersectionObserver:s,mutationObserverBefore:i,mutationObserverAfter:c}},dispose:function(e){const t=Je[e._id];t&&(t.intersectionObserver.disconnect(),t.mutationObserverBefore.disconnect(),t.mutationObserverAfter.disconnect(),e.dispose(),delete Je[e._id])}},Je={};function Ue(e){return e&&e!==document.body&&e!==document.documentElement?"visible"!==getComputedStyle(e).overflowY?e:Ue(e.parentElement):null}const $e={getAndRemoveExistingTitle:function(){var e;const t=document.head?document.head.getElementsByTagName("title"):[];if(0===t.length)return null;let n=null;for(let r=t.length-1;r>=0;r--){const o=t[r],a=o.previousSibling;a instanceof Comment&&null!==z(a)||(null===n&&(n=o.textContent),null===(e=o.parentNode)||void 0===e||e.removeChild(o))}return n}},ze={init:function(e,t){t._blazorInputFileNextFileId=0,t.addEventListener("click",(function(){t.value=""})),t.addEventListener("change",(function(){t._blazorFilesById={};const n=Array.prototype.map.call(t.files,(function(e){const n={id:++t._blazorInputFileNextFileId,lastModified:new Date(e.lastModified).toISOString(),name:e.name,size:e.size,contentType:e.type,readPromise:void 0,arrayBuffer:void 0,blob:e};return t._blazorFilesById[n.id]=n,n}));e.invokeMethodAsync("NotifyChange",n)}))},toImageFile:async function(e,t,n,r,o){const a=Ke(e,t),s=await new Promise((function(e){const t=new Image;t.onload=function(){URL.revokeObjectURL(t.src),e(t)},t.onerror=function(){t.onerror=null,URL.revokeObjectURL(t.src)},t.src=URL.createObjectURL(a.blob)})),i=await new Promise((function(e){var t;const a=Math.min(1,r/s.width),i=Math.min(1,o/s.height),c=Math.min(a,i),l=document.createElement("canvas");l.width=Math.round(s.width*c),l.height=Math.round(s.height*c),null===(t=l.getContext("2d"))||void 0===t||t.drawImage(s,0,0,l.width,l.height),l.toBlob(e,n)})),c={id:++e._blazorInputFileNextFileId,lastModified:a.lastModified,name:a.name,size:(null==i?void 0:i.size)||0,contentType:n,blob:i||a.blob};return e._blazorFilesById[c.id]=c,c},readFileData:async function(e,t){return Ke(e,t).blob}};function Ke(e,t){const n=e._blazorFilesById[t];if(!n)throw new Error(`There is no file with ID ${t}. The file list may have changed. See https://aka.ms/aspnet/blazor-input-file-multiple-selections.`);return n}const Xe=new Set,We={enableNavigationPrompt:function(e){0===Xe.size&&window.addEventListener("beforeunload",Ye),Xe.add(e)},disableNavigationPrompt:function(e){Xe.delete(e),0===Xe.size&&window.removeEventListener("beforeunload",Ye)}};function Ye(e){e.preventDefault(),e.returnValue=!0}const Ve=new Map,Ge={navigateTo:function(e,t,n=!1){_e(e,t instanceof Object?t:{forceLoad:t,replaceHistoryEntry:n})},registerCustomEventType:function(e,t){if(!t)throw new Error("The options parameter is required.");if(a.has(e))throw new Error(`The event '${e}' is already registered.`);if(t.browserEventName){const n=s.get(t.browserEventName);n?n.push(e):s.set(t.browserEventName,[e]),i.forEach((n=>n(e,t.browserEventName)))}a.set(e,t)},rootComponents:b,_internal:{navigationManager:Te,domWrapper:je,Virtualize:He,PageTitle:$e,InputFile:ze,NavigationLock:We,getJSDataStreamChunk:async function(e,t,n){return e instanceof Blob?await async function(e,t,n){const r=e.slice(t,t+n),o=await r.arrayBuffer();return new Uint8Array(o)}(e,t,n):function(e,t,n){return new Uint8Array(e.buffer,e.byteOffset+t,n)}(e,t,n)},attachWebRendererInterop:function(t,n,r,o){if(S.has(t))throw new Error(`Interop methods are already registered for renderer ${t}`);S.set(t,n),Object.keys(r).length>0&&function(t,n,r){if(m)throw new Error("Dynamic root components have already been enabled.");m=t,v=n;for(const[t,o]of Object.entries(r)){const r=e.findJSFunction(t,0);for(const e of o)r(e,n[e])}}(k(t),r,o),C(),function(e){const t=I.get(e);t&&(I.delete(e),D.delete(e),t())}(t)}}};window.Blazor=Ge;let qe=!1;const Ze="function"==typeof TextDecoder?new TextDecoder("utf-8"):null,Qe=Ze?Ze.decode.bind(Ze):function(e){let t=0;const n=e.length,r=[],o=[];for(;t65535&&(o-=65536,r.push(o>>>10&1023|55296),o=56320|1023&o),r.push(o)}r.length>1024&&(o.push(String.fromCharCode.apply(null,r)),r.length=0)}return o.push(String.fromCharCode.apply(null,r)),o.join("")},et=Math.pow(2,32),tt=Math.pow(2,21)-1;function nt(e,t){return e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24}function rt(e,t){return e[t]+(e[t+1]<<8)+(e[t+2]<<16)+(e[t+3]<<24>>>0)}function ot(e,t){const n=rt(e,t+4);if(n>tt)throw new Error(`Cannot read uint64 with high order part ${n}, because the result would exceed Number.MAX_SAFE_INTEGER.`);return n*et+rt(e,t)}class at{constructor(e){this.batchData=e;const t=new lt(e);this.arrayRangeReader=new ut(e),this.arrayBuilderSegmentReader=new dt(e),this.diffReader=new st(e),this.editReader=new it(e,t),this.frameReader=new ct(e,t)}updatedComponents(){return nt(this.batchData,this.batchData.length-20)}referenceFrames(){return nt(this.batchData,this.batchData.length-16)}disposedComponentIds(){return nt(this.batchData,this.batchData.length-12)}disposedEventHandlerIds(){return nt(this.batchData,this.batchData.length-8)}updatedComponentsEntry(e,t){const n=e+4*t;return nt(this.batchData,n)}referenceFramesEntry(e,t){return e+20*t}disposedComponentIdsEntry(e,t){const n=e+4*t;return nt(this.batchData,n)}disposedEventHandlerIdsEntry(e,t){const n=e+8*t;return ot(this.batchData,n)}}class st{constructor(e){this.batchDataUint8=e}componentId(e){return nt(this.batchDataUint8,e)}edits(e){return e+4}editsEntry(e,t){return e+16*t}}class it{constructor(e,t){this.batchDataUint8=e,this.stringReader=t}editType(e){return nt(this.batchDataUint8,e)}siblingIndex(e){return nt(this.batchDataUint8,e+4)}newTreeIndex(e){return nt(this.batchDataUint8,e+8)}moveToSiblingIndex(e){return nt(this.batchDataUint8,e+8)}removedAttributeName(e){const t=nt(this.batchDataUint8,e+12);return this.stringReader.readString(t)}}class ct{constructor(e,t){this.batchDataUint8=e,this.stringReader=t}frameType(e){return nt(this.batchDataUint8,e)}subtreeLength(e){return nt(this.batchDataUint8,e+4)}elementReferenceCaptureId(e){const t=nt(this.batchDataUint8,e+4);return this.stringReader.readString(t)}componentId(e){return nt(this.batchDataUint8,e+8)}elementName(e){const t=nt(this.batchDataUint8,e+8);return this.stringReader.readString(t)}textContent(e){const t=nt(this.batchDataUint8,e+4);return this.stringReader.readString(t)}markupContent(e){const t=nt(this.batchDataUint8,e+4);return this.stringReader.readString(t)}attributeName(e){const t=nt(this.batchDataUint8,e+4);return this.stringReader.readString(t)}attributeValue(e){const t=nt(this.batchDataUint8,e+8);return this.stringReader.readString(t)}attributeEventHandlerId(e){return ot(this.batchDataUint8,e+12)}}class lt{constructor(e){this.batchDataUint8=e,this.stringTableStartIndex=nt(e,e.length-4)}readString(e){if(-1===e)return null;{const n=nt(this.batchDataUint8,this.stringTableStartIndex+4*e),r=function(e,t){let n=0,r=0;for(let o=0;o<4;o++){const a=e[t+o];if(n|=(127&a)<async function(e,n){const r=function(e){const t=document.baseURI;return t.endsWith("/")?`${t}${e}`:`${t}/${e}`}(n),o=await import(r);if(void 0===o)return;const{beforeStart:a,afterStarted:s}=o;return s&&e.afterStartedCallbacks.push(s),a?a(...t):void 0}(this,e))))}async invokeAfterStartedCallbacks(e){await A,await Promise.all(this.afterStartedCallbacks.map((t=>t(e))))}}let Dt,Ct=!1;async function At(){if(Ct)throw new Error("Blazor has already started.");Ct=!0,Dt=e.attachDispatcher({beginInvokeDotNetFromJS:mt,endInvokeJSFromDotNet:vt,sendByteArray:gt});const t=await async function(){const e=await fetch("_framework/blazor.modules.json",{method:"GET",credentials:"include",cache:"no-cache"}),t=await e.json(),n=new It;return await n.importInitializersAsync(t,[]),n}();(function(){const e={AttachToDocument:(e,t)=>{!function(e,t,n){const r="::before";let o=!1;if(e.endsWith("::after"))e=e.slice(0,-7),o=!0;else if(e.endsWith(r))throw new Error(`The '${r}' selector is not supported.`);const a=function(e){const t=p.get(e);if(t)return p.delete(e),t}(e)||document.querySelector(e);if(!a)throw new Error(`Could not find any element matching selector '${e}'.`);!function(e,t,n,r){let o=pe[0];o||(o=new ue(0),pe[0]=o),o.attachRootComponentToLogicalElement(n,t,r)}(0,j(a,!0),t,o)}(t,e)},RenderBatch:(e,t)=>{try{const n=St(t);(function(e,t){const n=pe[0];if(!n)throw new Error("There is no browser renderer with ID 0.");const r=t.arrayRangeReader,o=t.updatedComponents(),a=r.values(o),s=r.count(o),i=t.referenceFrames(),c=r.values(i),l=t.diffReader;for(let e=0;e{ft=!0,console.error(`${e}\n${t}`),function(){const e=document.querySelector("#blazor-error-ui");e&&(e.style.display="block"),qe||(qe=!0,document.querySelectorAll("#blazor-error-ui .reload").forEach((e=>{e.onclick=function(e){location.reload(),e.preventDefault()}})),document.querySelectorAll("#blazor-error-ui .dismiss").forEach((e=>{e.onclick=function(e){const t=document.querySelector("#blazor-error-ui");t&&(t.style.display="none"),e.preventDefault()}})))}()},BeginInvokeJS:Dt.beginInvokeJSFromDotNet.bind(Dt),EndInvokeDotNet:Dt.endInvokeDotNetFromJS.bind(Dt),SendByteArrayToJS:Et,Navigate:Te.navigateTo,SetHasLocationChangingListeners:Te.setHasLocationChangingListeners,EndLocationChanging:Te.endLocationChanging};window.external.receiveMessage((t=>{const n=function(e){if(ft||!e||!e.startsWith(ht))return null;const t=e.substring(ht.length),[n,...r]=JSON.parse(t);return{messageType:n,args:r}}(t);if(n){if(!Object.prototype.hasOwnProperty.call(e,n.messageType))throw new Error(`Unsupported IPC message type '${n.messageType}'`);e[n.messageType].apply(null,n.args)}}))})(),Ge._internal.receiveWebViewDotNetDataStream=Nt,Te.enableNavigationInterception(),Te.listenForNavigationEvents(bt,yt),wt("AttachPage",Te.getBaseURI(),Te.getLocationHref()),await t.invokeAfterStartedCallbacks(Ge)}function Nt(e,t,n,r){!function(e,t,n,r,o){let a=Ve.get(t);if(!a){const n=new ReadableStream({start(e){Ve.set(t,e),a=e}});e.supplyDotNetStream(t,n)}o?(a.error(o),Ve.delete(t)):0===r?(a.close(),Ve.delete(t)):a.enqueue(n.length===r?n:n.subarray(0,r))}(Dt,e,t,n,r)}Ge.start=At,window.DotNet=e,document&&document.currentScript&&"false"!==document.currentScript.getAttribute("autostart")&&At()})(); \ No newline at end of file diff --git a/src/Components/Web.JS/src/Boot.Server.Common.ts b/src/Components/Web.JS/src/Boot.Server.Common.ts index a21c383f13db..185e171db532 100644 --- a/src/Components/Web.JS/src/Boot.Server.Common.ts +++ b/src/Components/Web.JS/src/Boot.Server.Common.ts @@ -16,13 +16,15 @@ import { attachRootComponentToLogicalElement } from './Rendering/Renderer'; import { discoverPersistedState, ServerComponentDescriptor } from './Services/ComponentDescriptorDiscovery'; import { sendJSDataStream } from './Platform/Circuits/CircuitStreamingInterop'; import { fetchAndInvokeInitializers } from './JSInitializers/JSInitializers.Server'; +import { WebRendererId } from './Rendering/WebRendererId'; +import { RootComponentManager } from './Services/RootComponentManager'; let renderingFailed = false; let connection: HubConnection; let circuit: CircuitDescriptor; let dispatcher: DotNet.ICallDispatcher; -export async function startCircuit(userOptions?: Partial, components?: ServerComponentDescriptor[]): Promise { +export async function startCircuit(userOptions?: Partial, components?: ServerComponentDescriptor[] | RootComponentManager): Promise { // Establish options to be used const options = resolveOptions(userOptions); const jsInitializer = await fetchAndInvokeInitializers(options); @@ -113,7 +115,7 @@ async function initializeConnection(options: CircuitStartOptions, logger: Logger const newConnection = connectionBuilder.build(); - newConnection.on('JS.AttachComponent', (componentId, selector) => attachRootComponentToLogicalElement(0, circuit.resolveElement(selector), componentId, false)); + newConnection.on('JS.AttachComponent', (componentId, selector) => attachRootComponentToLogicalElement(WebRendererId.Server, circuit.resolveElement(selector, componentId), componentId, false)); newConnection.on('JS.BeginInvokeJS', dispatcher.beginInvokeJSFromDotNet.bind(dispatcher)); newConnection.on('JS.EndInvokeDotNet', dispatcher.endInvokeDotNetFromJS.bind(dispatcher)); newConnection.on('JS.ReceiveByteArray', dispatcher.receiveByteArray.bind(dispatcher)); diff --git a/src/Components/Web.JS/src/Boot.Web.ts b/src/Components/Web.JS/src/Boot.Web.ts index 072ff0bfac89..dfcb7407f303 100644 --- a/src/Components/Web.JS/src/Boot.Web.ts +++ b/src/Components/Web.JS/src/Boot.Web.ts @@ -15,50 +15,88 @@ import { shouldAutoStart } from './BootCommon'; import { Blazor } from './GlobalExports'; import { WebStartOptions } from './Platform/WebStartOptions'; import { attachStreamingRenderingListener } from './Rendering/StreamingRendering'; -import { attachProgressivelyEnhancedNavigationListener, detachProgressivelyEnhancedNavigationListener } from './Services/NavigationEnhancement'; +import { NavigationEnhancementCallbacks, attachProgressivelyEnhancedNavigationListener, isPerformingEnhancedPageLoad } from './Services/NavigationEnhancement'; import { WebAssemblyComponentDescriptor } from './Services/ComponentDescriptorDiscovery'; -import { ServerComponentDescriptor, discoverComponents } from './Services/ComponentDescriptorDiscovery'; +import { ServerComponentDescriptor } from './Services/ComponentDescriptorDiscovery'; +import { RootComponentManager } from './Services/RootComponentManager'; +import { WebRendererId } from './Rendering/WebRendererId'; +import { DescriptorHandler, attachComponentDescriptorHandler, registerAllComponentDescriptors } from './Rendering/DomMerging/DomSync'; +import { waitForRendererAttached } from './Rendering/WebRendererInteropMethods'; let started = false; let webStartOptions: Partial | undefined; -async function boot(options?: Partial): Promise { +const circuitRootComponents = new RootComponentManager(WebRendererId.Server); +const webAssemblyRootComponents = new RootComponentManager(WebRendererId.WebAssembly); + +function boot(options?: Partial) : Promise { if (started) { throw new Error('Blazor has already started.'); } started = true; webStartOptions = options; - attachStreamingRenderingListener(options?.ssr); + const navigationEnhancementCallbacks: NavigationEnhancementCallbacks = { + documentUpdated: handleUpdatedComponentDescriptors, + }; + + const descriptorHandler: DescriptorHandler = { + registerComponentDescriptor, + }; + + attachComponentDescriptorHandler(descriptorHandler); + attachStreamingRenderingListener(options?.ssr, navigationEnhancementCallbacks); if (!options?.ssr?.disableDomPreservation) { - attachProgressivelyEnhancedNavigationListener(activateInteractiveComponents); + attachProgressivelyEnhancedNavigationListener(navigationEnhancementCallbacks); } - await activateInteractiveComponents(); + registerAllComponentDescriptors(document); + + return Promise.resolve(); } -async function activateInteractiveComponents() { - const serverComponents = discoverComponents(document, 'server') as ServerComponentDescriptor[]; - const webAssemblyComponents = discoverComponents(document, 'webassembly') as WebAssemblyComponentDescriptor[]; +function registerComponentDescriptor(descriptor: ServerComponentDescriptor | WebAssemblyComponentDescriptor) { + switch (descriptor.type) { + case 'server': + startCircuitIfNotStarted(); + circuitRootComponents.registerComponentDescriptor(descriptor); + break; + case 'webassembly': + startWebAssemblyIfNotStarted(); + webAssemblyRootComponents.registerComponentDescriptor(descriptor); + break; + } +} - if (serverComponents.length) { - // TEMPORARY until https://github.com/dotnet/aspnetcore/issues/48763 is implemented - // As soon we we see you have interactive components, we'll stop doing enhanced nav even if you don't have an interactive router - // This is because, otherwise, we would need a way to add new interactive root components to an existing circuit and that's #48763 - detachProgressivelyEnhancedNavigationListener(); +function handleUpdatedComponentDescriptors() { + const shouldAddNewRootComponents = !isPerformingEnhancedPageLoad(); + circuitRootComponents.handleUpdatedRootComponents(shouldAddNewRootComponents); + webAssemblyRootComponents.handleUpdatedRootComponents(shouldAddNewRootComponents); +} - await startCircuit(webStartOptions?.circuit, serverComponents); +let circuitStarted = false; +async function startCircuitIfNotStarted() { + if (circuitStarted) { + return; } - if (webAssemblyComponents.length) { - // TEMPORARY until https://github.com/dotnet/aspnetcore/issues/48763 is implemented - // As soon we we see you have interactive components, we'll stop doing enhanced nav even if you don't have an interactive router - // This is because, otherwise, we would need a way to add new interactive root components to an existing WebAssembly runtime and that's #48763 - detachProgressivelyEnhancedNavigationListener(); + circuitStarted = true; + await startCircuit(webStartOptions?.circuit, circuitRootComponents); + await waitForRendererAttached(WebRendererId.Server); + handleUpdatedComponentDescriptors(); +} - await startWebAssembly(webStartOptions?.webAssembly, webAssemblyComponents); +let webAssemblyStarted = false; +async function startWebAssemblyIfNotStarted() { + if (webAssemblyStarted) { + return; } + + webAssemblyStarted = true; + await startWebAssembly(webStartOptions?.webAssembly, webAssemblyRootComponents); + await waitForRendererAttached(WebRendererId.WebAssembly); + handleUpdatedComponentDescriptors(); } Blazor.start = boot; diff --git a/src/Components/Web.JS/src/Boot.WebAssembly.Common.ts b/src/Components/Web.JS/src/Boot.WebAssembly.Common.ts index 895f52ff6724..7c95984d8960 100644 --- a/src/Components/Web.JS/src/Boot.WebAssembly.Common.ts +++ b/src/Components/Web.JS/src/Boot.WebAssembly.Common.ts @@ -15,8 +15,9 @@ import { JSInitializer } from './JSInitializers/JSInitializers'; import { WebAssemblyComponentDescriptor, discoverPersistedState } from './Services/ComponentDescriptorDiscovery'; import { receiveDotNetDataStream } from './StreamingInterop'; import { WebAssemblyComponentAttacher } from './Platform/WebAssemblyComponentAttacher'; +import { RootComponentManager } from './Services/RootComponentManager'; -export async function startWebAssembly(options?: Partial, components?: WebAssemblyComponentDescriptor[]): Promise { +export async function startWebAssembly(options?: Partial, components?: WebAssemblyComponentDescriptor[] | RootComponentManager): Promise { if (inAuthRedirectIframe()) { // eslint-disable-next-line @typescript-eslint/no-empty-function await new Promise(() => { }); // See inAuthRedirectIframe for explanation @@ -98,7 +99,7 @@ export async function startWebAssembly(options?: Partial discoverPersistedState(document) || ''; Blazor._internal.attachRootComponentToElement = (selector, componentId, rendererId: any) => { - const element = componentAttacher.resolveRegisteredElement(selector); + const element = componentAttacher.resolveRegisteredElement(selector, componentId); if (!element) { attachRootComponentToElement(selector, componentId, rendererId); } else { diff --git a/src/Components/Web.JS/src/JSInitializers/JSInitializers.ts b/src/Components/Web.JS/src/JSInitializers/JSInitializers.ts index 7cd81e392b4d..41e8ee37c057 100644 --- a/src/Components/Web.JS/src/JSInitializers/JSInitializers.ts +++ b/src/Components/Web.JS/src/JSInitializers/JSInitializers.ts @@ -2,7 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. import { Blazor } from '../GlobalExports'; -import { rendererAttached } from '../Rendering/WebRendererInteropMethods'; +import { firstRendererAttached } from '../Rendering/WebRendererInteropMethods'; type BeforeBlazorStartedCallback = (...args: unknown[]) => Promise; export type AfterBlazorStartedCallback = (blazor: typeof Blazor) => Promise; @@ -41,7 +41,7 @@ export class JSInitializer { } async invokeAfterStartedCallbacks(blazor: typeof Blazor): Promise { - await rendererAttached; + await firstRendererAttached; await Promise.all(this.afterStartedCallbacks.map(callback => callback(blazor))); } } diff --git a/src/Components/Web.JS/src/Platform/Circuits/CircuitManager.ts b/src/Components/Web.JS/src/Platform/Circuits/CircuitManager.ts index 9dd52c0f59db..e04dca6adb91 100644 --- a/src/Components/Web.JS/src/Platform/Circuits/CircuitManager.ts +++ b/src/Components/Web.JS/src/Platform/Circuits/CircuitManager.ts @@ -6,18 +6,19 @@ import { toLogicalRootCommentElement, LogicalElement, toLogicalElement } from '. import { ServerComponentDescriptor } from '../../Services/ComponentDescriptorDiscovery'; import { HubConnectionState } from '@microsoft/signalr'; import { getAndRemovePendingRootComponentContainer } from '../../Rendering/JSRootComponents'; +import { RootComponentManager } from '../../Services/RootComponentManager'; export class CircuitDescriptor { public circuitId?: string; - public components: ServerComponentDescriptor[]; + public components: ServerComponentDescriptor[] | RootComponentManager; public applicationState: string; - public constructor(components: ServerComponentDescriptor[], appState: string) { + public constructor(components: ServerComponentDescriptor[] | RootComponentManager, appState: string) { this.circuitId = undefined; - this.components = components; this.applicationState = appState; + this.components = components; } public reconnect(reconnection: signalR.HubConnection): Promise { @@ -43,11 +44,16 @@ export class CircuitDescriptor { if (connection.state !== HubConnectionState.Connected) { return false; } + + const componentsJson = this.components instanceof RootComponentManager + ? '[]' + : JSON.stringify(this.components.map(c => c.toRecord())); + const result = await connection.invoke( 'StartCircuit', navigationManagerFunctions.getBaseURI(), navigationManagerFunctions.getLocationHref(), - JSON.stringify(this.components.map(c => c.toRecord())), + componentsJson, this.applicationState || '' ); @@ -59,7 +65,7 @@ export class CircuitDescriptor { } } - public resolveElement(sequenceOrIdentifier: string): LogicalElement { + public resolveElement(sequenceOrIdentifier: string, componentId: number): LogicalElement { // It may be a root component added by JS const jsAddedComponentContainer = getAndRemovePendingRootComponentContainer(sequenceOrIdentifier); if (jsAddedComponentContainer) { @@ -69,7 +75,10 @@ export class CircuitDescriptor { // ... or it may be a root component added by .NET const parsedSequence = Number.parseInt(sequenceOrIdentifier); if (!Number.isNaN(parsedSequence)) { - return toLogicalRootCommentElement(this.components[parsedSequence].start as Comment, this.components[parsedSequence].end as Comment); + const descriptor = this.components instanceof RootComponentManager + ? this.components.resolveRootComponent(parsedSequence, componentId) + : this.components[parsedSequence]; + return toLogicalRootCommentElement(descriptor); } throw new Error(`Invalid sequence number or identifier '${sequenceOrIdentifier}'.`); diff --git a/src/Components/Web.JS/src/Platform/Circuits/RenderQueue.ts b/src/Components/Web.JS/src/Platform/Circuits/RenderQueue.ts index 165b2e0d1508..e5973d634b51 100644 --- a/src/Components/Web.JS/src/Platform/Circuits/RenderQueue.ts +++ b/src/Components/Web.JS/src/Platform/Circuits/RenderQueue.ts @@ -5,6 +5,7 @@ import { renderBatch } from '../../Rendering/Renderer'; import { OutOfProcessRenderBatch } from '../../Rendering/RenderBatch/OutOfProcessRenderBatch'; import { Logger, LogLevel } from '../Logging/Logger'; import { HubConnection } from '@microsoft/signalr'; +import { WebRendererId } from '../../Rendering/WebRendererId'; export class RenderQueue { private static instance: RenderQueue; @@ -13,18 +14,15 @@ export class RenderQueue { private fatalError?: string; - public browserRendererId: number; - public logger: Logger; - public constructor(browserRendererId: number, logger: Logger) { - this.browserRendererId = browserRendererId; + public constructor(logger: Logger) { this.logger = logger; } public static getOrCreate(logger: Logger): RenderQueue { if (!RenderQueue.instance) { - RenderQueue.instance = new RenderQueue(0, logger); + RenderQueue.instance = new RenderQueue(logger); } return this.instance; @@ -54,7 +52,7 @@ export class RenderQueue { try { this.nextBatchId++; this.logger.log(LogLevel.Debug, `Applying batch ${receivedBatchId}.`); - renderBatch(this.browserRendererId, new OutOfProcessRenderBatch(batchData)); + renderBatch(WebRendererId.Server, new OutOfProcessRenderBatch(batchData)); await this.completeBatch(connection, receivedBatchId); } catch (error) { this.fatalError = (error as Error).toString(); diff --git a/src/Components/Web.JS/src/Platform/WebAssemblyComponentAttacher.ts b/src/Components/Web.JS/src/Platform/WebAssemblyComponentAttacher.ts index 9c6fcabc47a9..093c62ecfba0 100644 --- a/src/Components/Web.JS/src/Platform/WebAssemblyComponentAttacher.ts +++ b/src/Components/Web.JS/src/Platform/WebAssemblyComponentAttacher.ts @@ -3,26 +3,34 @@ import { LogicalElement, toLogicalRootCommentElement } from '../Rendering/LogicalElements'; import { WebAssemblyComponentDescriptor } from '../Services/ComponentDescriptorDiscovery'; +import { RootComponentManager } from '../Services/RootComponentManager'; export class WebAssemblyComponentAttacher { public preregisteredComponents: WebAssemblyComponentDescriptor[]; private componentsById: { [index: number]: WebAssemblyComponentDescriptor }; - public constructor(components: WebAssemblyComponentDescriptor[]) { - this.preregisteredComponents = components; - const componentsById = {}; - for (let index = 0; index < components.length; index++) { - const component = components[index]; - componentsById[component.id] = component; + private rootComponentManager?: RootComponentManager; + + public constructor(components: WebAssemblyComponentDescriptor[] | RootComponentManager) { + this.componentsById = {}; + if (components instanceof RootComponentManager) { + this.preregisteredComponents = []; + this.rootComponentManager = components; + } else { + this.preregisteredComponents = components; + for (let index = 0; index < components.length; index++) { + const component = components[index]; + this.componentsById[component.id] = component; + } } - this.componentsById = componentsById; } - public resolveRegisteredElement(id: string): LogicalElement | undefined { + public resolveRegisteredElement(id: string, componentId: number): LogicalElement | undefined { const parsedId = Number.parseInt(id); if (!Number.isNaN(parsedId)) { - return toLogicalRootCommentElement(this.componentsById[parsedId].start as Comment, this.componentsById[parsedId].end as Comment); + const component = this.rootComponentManager?.resolveRootComponent(parsedId, componentId) || this.componentsById[parsedId]; + return toLogicalRootCommentElement(component); } else { return undefined; } diff --git a/src/Components/Web.JS/src/Rendering/BrowserRenderer.ts b/src/Components/Web.JS/src/Rendering/BrowserRenderer.ts index 9b0bf156a12e..74a14d4a38af 100644 --- a/src/Components/Web.JS/src/Rendering/BrowserRenderer.ts +++ b/src/Components/Web.JS/src/Rendering/BrowserRenderer.ts @@ -3,7 +3,7 @@ import { RenderBatch, ArrayBuilderSegment, RenderTreeEdit, RenderTreeFrame, EditType, FrameType, ArrayValues } from './RenderBatch/RenderBatch'; import { EventDelegator } from './Events/EventDelegator'; -import { LogicalElement, PermutationListEntry, toLogicalElement, insertLogicalChild, removeLogicalChild, getLogicalParent, getLogicalChild, createAndInsertLogicalContainer, isSvgElement, getLogicalChildrenArray, getLogicalSiblingEnd, permuteLogicalChildren, getClosestDomElement, emptyLogicalElement } from './LogicalElements'; +import { LogicalElement, PermutationListEntry, toLogicalElement, insertLogicalChild, removeLogicalChild, getLogicalParent, getLogicalChild, createAndInsertLogicalContainer, isSvgElement, permuteLogicalChildren, getClosestDomElement, emptyLogicalElement } from './LogicalElements'; import { applyCaptureIdToElement } from './ElementReferenceCapture'; import { attachToEventDelegator as attachNavigationManagerToEventDelegator } from '../Services/NavigationManager'; import { applyAnyDeferredValue, tryApplySpecialProperty } from './DomSpecialPropertyUtil'; @@ -13,6 +13,7 @@ const elementsToClearOnRootComponentRender: { [componentId: number]: LogicalElem const internalAttributeNamePrefix = '__internal_'; const eventPreventDefaultAttributeNamePrefix = 'preventDefault_'; const eventStopPropagationAttributeNamePrefix = 'stopPropagation_'; +const interactiveRootComponentPropname = Symbol(); export class BrowserRenderer { public eventDelegator: EventDelegator; @@ -31,6 +32,11 @@ export class BrowserRenderer { } public attachRootComponentToLogicalElement(componentId: number, element: LogicalElement, appendContent: boolean): void { + if (isInteractiveRootComponentElement(element)) { + throw new Error(`Root component '${componentId}' could not be attached because its target element is already associated with a root component`); + } + + markAsInteractiveRootComponentElement(element, true); this.attachComponentToElement(componentId, element); this.rootComponentIds.add(componentId); @@ -50,13 +56,13 @@ export class BrowserRenderer { // On the first render for each root component, clear any existing content (e.g., prerendered) const rootElementToClear = elementsToClearOnRootComponentRender[componentId]; if (rootElementToClear) { - const rootElementToClearEnd = getLogicalSiblingEnd(rootElementToClear); delete elementsToClearOnRootComponentRender[componentId]; + emptyLogicalElement(rootElementToClear); - if (!rootElementToClearEnd) { - clearElement(rootElementToClear as unknown as Element); - } else { - clearBetween(rootElementToClear as unknown as Node, rootElementToClearEnd as unknown as Comment); + if (rootElementToClear instanceof Comment) { + // We sanitize start comments by removing all the information from it now that we don't need it anymore + // as it adds noise to the DOM. + rootElementToClear.textContent = '!'; } } @@ -76,7 +82,9 @@ export class BrowserRenderer { // When disposing a root component, the container element won't be removed from the DOM (because there's // no parent to remove that child), so we empty it to restore it to the state it was in before the root // component was added. - emptyLogicalElement(this.childComponentLocations[componentId]); + const logicalElement = this.childComponentLocations[componentId]; + markAsInteractiveRootComponentElement(logicalElement, false); + emptyLogicalElement(logicalElement); } delete this.childComponentLocations[componentId]; @@ -357,6 +365,14 @@ export class BrowserRenderer { } } +function markAsInteractiveRootComponentElement(element: LogicalElement, isInteractive: boolean) { + element[interactiveRootComponentPropname] = isInteractive; +} + +export function isInteractiveRootComponentElement(element: LogicalElement): boolean | undefined { + return element[interactiveRootComponentPropname]; +} + export interface ComponentDescriptor { start: Node; end: Node; @@ -387,32 +403,6 @@ function countDescendantFrames(batch: RenderBatch, frame: RenderTreeFrame): numb } } -function clearElement(element: Element) { - let childNode: Node | null; - while ((childNode = element.firstChild)) { - element.removeChild(childNode); - } -} - -function clearBetween(start: Node, end: Node): void { - const logicalParent = getLogicalParent(start as unknown as LogicalElement); - if (!logicalParent) { - throw new Error("Can't clear between nodes. The start node does not have a logical parent."); - } - const children = getLogicalChildrenArray(logicalParent); - const removeStart = children.indexOf(start as unknown as LogicalElement) + 1; - const endIndex = children.indexOf(end as unknown as LogicalElement); - - // We remove the end component comment from the DOM as we don't need it after this point. - for (let i = removeStart; i <= endIndex; i++) { - removeLogicalChild(logicalParent, removeStart); - } - - // We sanitize the start comment by removing all the information from it now that we don't need it anymore - // as it adds noise to the DOM. - start.textContent = '!'; -} - function stripOnPrefix(attributeName: string) { if (attributeName.startsWith('on')) { return attributeName.substring(2); diff --git a/src/Components/Web.JS/src/Rendering/DomMerging/DomSync.ts b/src/Components/Web.JS/src/Rendering/DomMerging/DomSync.ts index bc607f8e3773..94b23b36cad9 100644 --- a/src/Components/Web.JS/src/Rendering/DomMerging/DomSync.ts +++ b/src/Components/Web.JS/src/Rendering/DomMerging/DomSync.ts @@ -1,38 +1,102 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +import { ComponentDescriptor, ServerComponentDescriptor, WebAssemblyComponentDescriptor, discoverComponents } from '../../Services/ComponentDescriptorDiscovery'; +import { isInteractiveRootComponentElement } from '../BrowserRenderer'; import { applyAnyDeferredValue } from '../DomSpecialPropertyUtil'; +import { LogicalElement, getLogicalChildrenArray, getLogicalNextSibling, getLogicalParent, getLogicalRootDescriptor, insertLogicalChild, insertLogicalChildBefore, isLogicalElement, toLogicalElement, toLogicalRootCommentElement } from '../LogicalElements'; import { synchronizeAttributes } from './AttributeSync'; import { UpdateCost, ItemList, Operation, computeEditScript } from './EditScript'; -export function synchronizeDomContent(destination: CommentBoundedRange | Node, newContent: Node) { - let destinationParent: Node; - let nextDestinationNode: Node | null; - let originalNodesForDiff: ItemList; +let descriptorHandler: DescriptorHandler | null = null; + +export interface DescriptorHandler { + registerComponentDescriptor(descriptor: ComponentDescriptor): void; +} + +export function attachComponentDescriptorHandler(handler: DescriptorHandler) { + descriptorHandler = handler; +} + +export function registerAllComponentDescriptors(root: Node) { + const descriptors = upgradeComponentCommentsToLogicalRootComments(root); - // Figure out how to interpret the 'destination' parameter, since it can come in two very different forms + for (const descriptor of descriptors) { + descriptorHandler?.registerComponentDescriptor(descriptor); + } +} + +export { preprocessAndSynchronizeDomContent as synchronizeDomContent }; + +function preprocessAndSynchronizeDomContent(destination: CommentBoundedRange | Node, newContent: Node) { + // Start by recursively identifying component markers in the new content + // and converting them into logical elements so they correctly participate + // in logical element synchronization + upgradeComponentCommentsToLogicalRootComments(newContent); + + // Then, synchronize the preprocessed DOM content + synchronizeDomContentCore(destination, newContent); +} + +function synchronizeDomContentCore(destination: CommentBoundedRange | Node, newContent: Node) { + // Determine the destination's parent node, i.e., the node containing the children + // we intend to synchronize. This might sometimes be a logical parent. + let destinationParent: Node; if (destination instanceof Node) { destinationParent = destination; - nextDestinationNode = destination.firstChild; - originalNodesForDiff = destination.childNodes; } else { - destinationParent = destination.startExclusive.parentNode!; - nextDestinationNode = destination.startExclusive.nextSibling; - originalNodesForDiff = new SiblingSubsetNodeList(destination); + destinationParent = + getLogicalParent(destination.startExclusive as unknown as LogicalElement) as unknown as Node ?? + destination.startExclusive.parentNode!; + } + + // If only one out of the destination and new content is a logical element, we normalize + // the other to also be a logical element + const isSynchronizingLogicalElements = isLogicalElement(destinationParent) || isLogicalElement(newContent); + if (isSynchronizingLogicalElements) { + toLogicalElement(destinationParent, /* allowExistingContents */ true); + toLogicalElement(newContent, /* allowExistingContents */ true); + } + + // Create abstract lists of child nodes + let originalNodesForDiff: ItemList; + let newNodesForDiff: ItemList; + if (isSynchronizingLogicalElements) { + originalNodesForDiff = new LogicalElementNodeList(destinationParent as unknown as LogicalElement); + newNodesForDiff = new LogicalElementNodeList(newContent as unknown as LogicalElement); + } else { + originalNodesForDiff = destinationParent.childNodes; + newNodesForDiff = newContent.childNodes; + } + + // If the destination is a comment bounded range, limit the node list to a subset defined + // by that range + if (!(destination instanceof Node)) { + originalNodesForDiff = new SiblingSubsetNodeList(originalNodesForDiff, destination); } // Run the diff const editScript = computeEditScript( originalNodesForDiff, - newContent.childNodes, - domNodeComparer); + newNodesForDiff, + domNodeComparer + ); + + let destinationWalker: EditWalker; + let sourceWalker: EditWalker; + if (isSynchronizingLogicalElements) { + destinationWalker = new LogicalElementEditWalker(originalNodesForDiff.item(0) as unknown as LogicalElement); + sourceWalker = new LogicalElementEditWalker(newNodesForDiff.item(0) as unknown as LogicalElement); + } else { + destinationWalker = new DomNodeEditWalker(originalNodesForDiff.item(0)!); + sourceWalker = new DomNodeEditWalker(newNodesForDiff.item(0)!); + } // Handle any common leading items - let nextNewContentNode = newContent.firstChild; // Could be null for (let i = 0; i < editScript.skipCount; i++) { - treatAsMatch(nextDestinationNode!, nextNewContentNode!); - nextDestinationNode = nextDestinationNode!.nextSibling!; - nextNewContentNode = nextNewContentNode!.nextSibling; + treatAsMatch(destinationWalker.current, sourceWalker.current); + destinationWalker.advance(); + sourceWalker.advance(); } // Handle any edited region @@ -43,26 +107,30 @@ export function synchronizeDomContent(destination: CommentBoundedRange | Node, n for (let editIndex = 0; editIndex < editsLength; editIndex++) { const operation = edits[editIndex]; switch (operation) { - case Operation.Keep: - treatAsMatch(nextDestinationNode!, nextNewContentNode!); - nextDestinationNode = nextDestinationNode!.nextSibling; - nextNewContentNode = nextNewContentNode!.nextSibling; + case Operation.Keep: { + treatAsMatch(destinationWalker.current, sourceWalker.current); + destinationWalker.advance(); + sourceWalker.advance(); break; - case Operation.Update: - treatAsSubstitution(nextDestinationNode!, nextNewContentNode!); - nextDestinationNode = nextDestinationNode!.nextSibling; - nextNewContentNode = nextNewContentNode!.nextSibling; + } + case Operation.Update: { + treatAsSubstitution(destinationWalker.current, sourceWalker.current); + destinationWalker.advance(); + sourceWalker.advance(); break; - case Operation.Delete: - const nodeToRemove = nextDestinationNode!; - nextDestinationNode = nodeToRemove.nextSibling; - destinationParent.removeChild(nodeToRemove); + } + case Operation.Delete: { + const nodeToRemove = destinationWalker.current; + destinationWalker.advance(); + treatAsDeletion(nodeToRemove, destinationParent); break; - case Operation.Insert: - const nodeToInsert = nextNewContentNode!; - nextNewContentNode = nodeToInsert.nextSibling; - destinationParent.insertBefore(nodeToInsert, nextDestinationNode); + } + case Operation.Insert: { + const nodeToInsert = sourceWalker.current; + sourceWalker.advance(); + treatAsInsertion(nodeToInsert, destinationWalker.current, destinationParent); break; + } default: throw new Error(`Unexpected operation: '${operation}'`); } @@ -71,12 +139,12 @@ export function synchronizeDomContent(destination: CommentBoundedRange | Node, n // Handle any common trailing items // These can only exist if there were some edits, otherwise everything would be in the set of common leading items const endAtNodeExclOrNull = destination instanceof Node ? null : destination.endExclusive; - while (nextDestinationNode !== endAtNodeExclOrNull) { - treatAsMatch(nextDestinationNode!, nextNewContentNode!); - nextDestinationNode = nextDestinationNode!.nextSibling; - nextNewContentNode = nextNewContentNode!.nextSibling; + while (destinationWalker.current !== endAtNodeExclOrNull) { + treatAsMatch(destinationWalker.current, sourceWalker.current); + destinationWalker.advance(); + sourceWalker.advance(); } - if (nextNewContentNode) { + if (sourceWalker.current) { // Should never be possible, as it would imply a bug in the edit script calculation, or possibly an unsupported // scenario like a DOM mutation observer modifying the destination nodes while we are working on them throw new Error('Updating the DOM failed because the sets of trailing nodes had inconsistent lengths.'); @@ -87,13 +155,36 @@ export function synchronizeDomContent(destination: CommentBoundedRange | Node, n function treatAsMatch(destination: Node, source: Node) { switch (destination.nodeType) { case Node.TEXT_NODE: - case Node.COMMENT_NODE: break; - case Node.ELEMENT_NODE: + case Node.COMMENT_NODE: { + const destinationAsLogicalElement = destination as unknown as LogicalElement; + const sourceAsLogicalElement = source as unknown as LogicalElement; + const destinationRootDescriptor = getLogicalRootDescriptor(destinationAsLogicalElement); + const sourceRootDescriptor = getLogicalRootDescriptor(sourceAsLogicalElement); + + if (!destinationRootDescriptor !== !sourceRootDescriptor) { + throw new Error('Not supported: merging component comment nodes with non-component comment nodes'); + } + + if (destinationRootDescriptor) { + // Update the existing descriptor with hte new descriptor's data + destinationRootDescriptor.update(sourceRootDescriptor); + + const isDestinationInteractive = isInteractiveRootComponentElement(destinationAsLogicalElement); + if (isDestinationInteractive) { + // Don't sync DOM content for already-interactive components becuase their content is managed + // by the renderer. + } else { + synchronizeDomContentCore(destination, source); + } + } + break; + } + case Node.ELEMENT_NODE: { const editableElementValue = getEditableElementValue(source as Element); synchronizeAttributes(destination as Element, source as Element); applyAnyDeferredValue(destination as Element); - synchronizeDomContent(destination as Element, source as Element); + synchronizeDomContentCore(destination as Element, source as Element); // This is a much simpler alternative to the deferred-value-assignment logic we use in interactive rendering. // Because this sync algorithm goes depth-first, we know all the attributes and descendants are fully in sync @@ -103,6 +194,7 @@ function treatAsMatch(destination: Node, source: Node) { ensureEditableValueSynchronized(destination as Element, editableElementValue); } break; + } case Node.DOCUMENT_TYPE_NODE: // See comment below about doctype nodes. We leave them alone. break; @@ -122,17 +214,72 @@ function treatAsSubstitution(destination: Node, source: Node) { } } +function treatAsDeletion(nodeToDelete: Node, parentNode: Node) { + if (isLogicalElement(parentNode)) { + // It's not safe to call 'removeLogicalChild' here because it recursively removes + // logical descendants from their parents, and that can potentially interfere with + // renderer-managed DOM. Instead, we insert the logical element into a new document + // fragment, which allows the renderer to continue applying render batches until + // related components get disposed. + const docFrag = toLogicalElement(document.createDocumentFragment()); + insertLogicalChild(nodeToDelete, docFrag, 0); + } else { + parentNode.removeChild(nodeToDelete); + } +} + +function treatAsInsertion(nodeToInsert: Node, nextNode: Node | null, parentNode: Node) { + if (isLogicalElement(parentNode)) { + insertLogicalChildBefore(nodeToInsert, parentNode as unknown as LogicalElement, nextNode as unknown as LogicalElement); + } else { + // If the parent node is not a logical element, that means + // the node we're inserting is either a root logical element, or not a logical + // element at all. In either case, it's safe to treat the node we're inserting + // as a single node because root logical nodes cannot be component comments. + parentNode.insertBefore(nodeToInsert, nextNode); + } + + // Find and register descriptors in new content + const iterator = document.createNodeIterator(nodeToInsert, NodeFilter.SHOW_COMMENT); + while (iterator.nextNode()) { + const logicalRootDescriptor = getLogicalRootDescriptor(iterator.referenceNode as unknown as LogicalElement); + if (logicalRootDescriptor) { + descriptorHandler?.registerComponentDescriptor(logicalRootDescriptor); + } + } +} + function domNodeComparer(a: Node, b: Node): UpdateCost { if (a.nodeType !== b.nodeType) { return UpdateCost.Infinite; } + if (isLogicalElement(a) !== isLogicalElement(b)) { + // We cannot merge logical elements with non-logical elements. + return UpdateCost.Infinite; + } + switch (a.nodeType) { case Node.TEXT_NODE: - case Node.COMMENT_NODE: - // We're willing to update text and comment nodes in place, but treat the update operation as being + // We're willing to update text nodes in place, but treat the update operation as being // as costly as an insertion or deletion return a.textContent === b.textContent ? UpdateCost.None : UpdateCost.Some; + case Node.COMMENT_NODE: { + const rootDescriptorA = getLogicalRootDescriptor(a as unknown as LogicalElement); + const rootDescriptorB = getLogicalRootDescriptor(b as unknown as LogicalElement); + + if (rootDescriptorA || rootDescriptorB) { + // If either node represents a root component comment, they must both be components of with matching keys. + // We will update a component with a non-component or a component with a different key. + return rootDescriptorA && rootDescriptorB && rootDescriptorA.matches(rootDescriptorB) + ? UpdateCost.None + : UpdateCost.Infinite; + } else { + // We're willing to update non-component comment nodes in place, but treat the update operation as being + // as costly as an insertion or deletion + return a.textContent === b.textContent ? UpdateCost.None : UpdateCost.Some; + } + } case Node.ELEMENT_NODE: // For elements, we're only doing a shallow comparison and don't know if attributes/descendants are different. // We never 'update' one element type into another. We regard the update cost for same-type elements as zero because @@ -152,6 +299,33 @@ function domNodeComparer(a: Node, b: Node): UpdateCost { } } +function upgradeComponentCommentsToLogicalRootComments(root: Node): ComponentDescriptor[] { + const serverDescriptors = discoverComponents(root, 'server') as ServerComponentDescriptor[]; + const webAssemblyDescriptors = discoverComponents(root, 'webassembly') as WebAssemblyComponentDescriptor[]; + const allDescriptors: ComponentDescriptor[] = []; + + for (const descriptor of [...serverDescriptors, ...webAssemblyDescriptors]) { + const existingDescriptor = getLogicalRootDescriptor(descriptor.start as unknown as LogicalElement); + if (existingDescriptor) { + allDescriptors.push(existingDescriptor); + } else { + toLogicalRootCommentElement(descriptor); + + // Since we've already parsed the payloads from the start and end comments, + // we sanitize them to reduce noise in the DOM. + const { start, end } = descriptor; + start.textContent = 'bl-root'; + if (end) { + end.textContent = '/bl-root'; + } + + allDescriptors.push(descriptor); + } + } + + return allDescriptors; +} + function ensureEditableValueSynchronized(destination: Element, value: any) { if (destination instanceof HTMLTextAreaElement && destination.value !== value) { destination.value = value as string; @@ -183,8 +357,46 @@ export interface CommentBoundedRange { endExclusive: Comment, } +interface EditWalker { + current: Node; + advance(): void; +} + +class DomNodeEditWalker implements EditWalker { + current: Node; + + constructor(startNode: Node) { + this.current = startNode; + } + + advance() { + if (!this.current) { + throw new Error('Cannot advance beyond the end of the sibling array'); + } + + this.current = this.current.nextSibling!; + } +} + +class LogicalElementEditWalker implements EditWalker { + current: Node; + + constructor(startNode: LogicalElement) { + this.current = startNode as unknown as Node; + } + + advance() { + if (!this.current) { + throw new Error('Cannot advance beyond the end of the logical children array'); + } + + const nextSibling = getLogicalNextSibling(this.current as unknown as LogicalElement); + this.current = nextSibling as unknown as Node; + } +} + class SiblingSubsetNodeList implements ItemList { - private readonly siblings: NodeList; + private readonly siblings: ItemList; private readonly startIndex: number; private readonly endIndexExcl: number; @@ -200,14 +412,34 @@ class SiblingSubsetNodeList implements ItemList { } } - constructor(range: CommentBoundedRange) { - if (!range.startExclusive.parentNode || range.startExclusive.parentNode !== range.endExclusive.parentNode) { - throw new Error('Invalid CommentBoundedRange. The start and end markers have no common parent.'); - } - - this.siblings = range.startExclusive.parentNode!.childNodes; + constructor(childNodes: ItemList, range: CommentBoundedRange) { + this.siblings = childNodes; this.startIndex = Array.prototype.indexOf.call(this.siblings, range.startExclusive) + 1; this.endIndexExcl = Array.prototype.indexOf.call(this.siblings, range.endExclusive); this.length = this.endIndexExcl - this.startIndex; } } + +class LogicalElementNodeList implements ItemList { + readonly length: number; + + constructor(element: LogicalElement) { + const childNodes = getLogicalChildrenArray(element); + this.length = childNodes.length; + + // This is done for compatibility with Array.prototype.indexOf, which expects an array-like object + Object.assign(this, childNodes); + } + + [index: number]: Node; + + item(index: number): Node | null { + return this[index] as unknown as Node; + } + + forEach(callbackfn: (value: Node, key: number, parent: ItemList) => void, thisArg?: any): void { + for (let i = 0; i < this.length; i++) { + callbackfn.call(thisArg, this.item(i)!, i, this); + } + } +} diff --git a/src/Components/Web.JS/src/Rendering/LogicalElements.ts b/src/Components/Web.JS/src/Rendering/LogicalElements.ts index f5b897ac9beb..30b7357ba666 100644 --- a/src/Components/Web.JS/src/Rendering/LogicalElements.ts +++ b/src/Components/Web.JS/src/Rendering/LogicalElements.ts @@ -1,6 +1,8 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +import { ServerComponentDescriptor, WebAssemblyComponentDescriptor } from '../Services/ComponentDescriptorDiscovery'; + /* A LogicalElement plays the same role as an Element instance from the point of view of the API consumer. Inserting and removing logical elements updates the browser DOM just the same. @@ -28,11 +30,11 @@ - Whenever a logical child is added or removed, we update the parent's array of logical children */ -const logicalChildrenPropname = createSymbolOrFallback('_blazorLogicalChildren'); -const logicalParentPropname = createSymbolOrFallback('_blazorLogicalParent'); -const logicalEndSiblingPropname = createSymbolOrFallback('_blazorLogicalEnd'); +const logicalChildrenPropname = Symbol(); +const logicalParentPropname = Symbol(); +const logicalRootDescriptorPropname = Symbol(); -export function toLogicalRootCommentElement(start: Comment, end: Comment): LogicalElement { +export function toLogicalRootCommentElement(descriptor: ServerComponentDescriptor | WebAssemblyComponentDescriptor): LogicalElement { // Now that we support start/end comments as component delimiters we are going to be setting up // adding the components rendered output as siblings of the start/end tags (between). // For that to work, we need to appropriately configure the parent element to be a logical element @@ -49,36 +51,71 @@ export function toLogicalRootCommentElement(start: Comment, end: Comment): Logic // |- *div // |- *component // |- *footer - if (!start.parentNode) { - throw new Error(`Comment not connected to the DOM ${start.textContent}`); + const { start, end } = descriptor; + const existingDescriptor = start[logicalRootDescriptorPropname]; + if (existingDescriptor) { + if (existingDescriptor !== descriptor) { + throw new Error('The start component comment was already associated with another component descriptor.'); + } + return start as unknown as LogicalElement; } const parent = start.parentNode; + if (!parent) { + throw new Error(`Comment not connected to the DOM ${start.textContent}`); + } + const parentLogicalElement = toLogicalElement(parent, /* allow existing contents */ true); const children = getLogicalChildrenArray(parentLogicalElement); - Array.from(parent.childNodes).forEach(n => children.push(n as unknown as LogicalElement)); start[logicalParentPropname] = parentLogicalElement; - // We might not have an end comment in the case of non-prerendered components. + start[logicalRootDescriptorPropname] = descriptor; + const startLogicalElement = toLogicalElement(start); + if (end) { - start[logicalEndSiblingPropname] = end; - toLogicalElement(end); + // We need to make each element between the start and end comments a logical child + // of the start node. + const rootCommentChildren = getLogicalChildrenArray(startLogicalElement); + const startNextChildIndex = Array.prototype.indexOf.call(children, startLogicalElement) + 1; + let lastMovedChild: LogicalElement | null = null; + + while (lastMovedChild !== end as unknown as LogicalElement) { + const childToMove = children.splice(startNextChildIndex, 1)[0]; + if (!childToMove) { + throw new Error('Could not find the end component comment in the parent logical node list'); + } + childToMove[logicalParentPropname] = start; + rootCommentChildren.push(childToMove); + lastMovedChild = childToMove; + } } - return toLogicalElement(start); + + return startLogicalElement; } export function toLogicalElement(element: Node, allowExistingContents?: boolean): LogicalElement { - // Normally it's good to assert that the element has started empty, because that's the usual - // situation and we probably have a bug if it's not. But for the element that contain prerendered - // root components, we want to let them keep their content until we replace it. - if (element.childNodes.length > 0 && !allowExistingContents) { - throw new Error('New logical elements must start empty, or allowExistingContents must be true'); + if (logicalChildrenPropname in element) { // If it's already a logical element, leave it alone + return element as unknown as LogicalElement; } - if (!(logicalChildrenPropname in element)) { // If it's already a logical element, leave it alone - element[logicalChildrenPropname] = []; + const childrenArray: LogicalElement[] = []; + + if (element.childNodes.length > 0) { + // Normally it's good to assert that the element has started empty, because that's the usual + // situation and we probably have a bug if it's not. But for the elements that contain prerendered + // root components, we want to let them keep their content until we replace it. + if (!allowExistingContents) { + throw new Error('New logical elements must start empty, or allowExistingContents must be true'); + } + + element.childNodes.forEach(child => { + const childLogicalElement = toLogicalElement(child, /* allowExistingContents */ true); + childLogicalElement[logicalParentPropname] = element; + childrenArray.push(childLogicalElement); + }); } + element[logicalChildrenPropname] = childrenArray; return element as unknown as LogicalElement; } @@ -95,37 +132,55 @@ export function createAndInsertLogicalContainer(parent: LogicalElement, childInd return containerElement as unknown as LogicalElement; } +export function insertLogicalChildBefore(child: Node, parent: LogicalElement, before: LogicalElement | null): void { + const childrenArray = getLogicalChildrenArray(parent); + let childIndex: number; + if (before) { + childIndex = Array.prototype.indexOf.call(childrenArray, before); + if (childIndex < 0) { + throw new Error('Could not find logical element in the parent logical node list'); + } + } else { + childIndex = childrenArray.length; + } + insertLogicalChild(child, parent, childIndex); +} + export function insertLogicalChild(child: Node, parent: LogicalElement, childIndex: number): void { const childAsLogicalElement = child as unknown as LogicalElement; - if (child instanceof Comment) { - const existingGrandchildren = getLogicalChildrenArray(childAsLogicalElement); - if (existingGrandchildren && getLogicalChildrenArray(childAsLogicalElement).length > 0) { - // There's nothing to stop us implementing support for this scenario, and it's not difficult - // (after inserting 'child' itself, also iterate through its logical children and physically - // put them as following-siblings in the DOM). However there's no scenario that requires it - // presently, so if we did implement it there'd be no good way to have tests for it. - throw new Error('Not implemented: inserting non-empty logical container'); + + // If the child is a component comment with logical siblings, its siblings also + // need to be inserted into the parent node + let nodeToInsert = child; + if (isLogicalElement(child)) { + const lastNodeToInsert = findLastDomNodeInRange(childAsLogicalElement); + if (lastNodeToInsert !== child) { + const range = new Range(); + range.setStartBefore(child); + range.setEndAfter(lastNodeToInsert); + nodeToInsert = range.extractContents(); } } - if (getLogicalParent(childAsLogicalElement)) { - // Likewise, we could easily support this scenario too (in this 'if' block, just splice - // out 'child' from the logical children array of its previous logical parent by using - // Array.prototype.indexOf to determine its previous sibling index). - // But again, since there's not currently any scenario that would use it, we would not - // have any test coverage for such an implementation. - throw new Error('Not implemented: moving existing logical children'); + // If the node we're inserting already has a logical parent, + // remove it from its sibling array + const existingLogicalParent = getLogicalParent(childAsLogicalElement); + if (existingLogicalParent) { + const existingSiblingArray = getLogicalChildrenArray(existingLogicalParent); + const existingChildIndex = Array.prototype.indexOf.call(existingSiblingArray, childAsLogicalElement); + existingSiblingArray.splice(existingChildIndex, 1); + delete childAsLogicalElement[logicalParentPropname]; } const newSiblings = getLogicalChildrenArray(parent); if (childIndex < newSiblings.length) { // Insert const nextSibling = newSiblings[childIndex] as any as Node; - nextSibling.parentNode!.insertBefore(child, nextSibling); + nextSibling.parentNode!.insertBefore(nodeToInsert, nextSibling); newSiblings.splice(childIndex, 0, childAsLogicalElement); } else { // Append - appendDomNode(child, parent); + appendDomNode(nodeToInsert, parent); newSiblings.push(childAsLogicalElement); } @@ -158,14 +213,14 @@ export function getLogicalParent(element: LogicalElement): LogicalElement | null return (element[logicalParentPropname] as LogicalElement) || null; } -export function getLogicalSiblingEnd(element: LogicalElement): LogicalElement | null { - return (element[logicalEndSiblingPropname] as LogicalElement) || null; -} - export function getLogicalChild(parent: LogicalElement, childIndex: number): LogicalElement { return getLogicalChildrenArray(parent)[childIndex]; } +export function getLogicalRootDescriptor(element: LogicalElement): ServerComponentDescriptor | WebAssemblyComponentDescriptor { + return element[logicalRootDescriptorPropname] || null; +} + // SVG elements support `foreignObject` children that can hold arbitrary HTML. // For these scenarios, the parent SVG and `foreignObject` elements should // be rendered under the SVG namespace, while the HTML content should be rendered @@ -184,6 +239,16 @@ export function getLogicalChildrenArray(element: LogicalElement): LogicalElement return element[logicalChildrenPropname] as LogicalElement[]; } +export function getLogicalNextSibling(element: LogicalElement): LogicalElement | null { + const siblings = getLogicalChildrenArray(getLogicalParent(element)!); + const siblingIndex = Array.prototype.indexOf.call(siblings, element); + return siblings[siblingIndex + 1] || null; +} + +export function isLogicalElement(element: Node): boolean { + return logicalChildrenPropname in element; +} + export function permuteLogicalChildren(parent: LogicalElement, permutationList: PermutationListEntry[]): void { // The permutationList must represent a valid permutation, i.e., the list of 'from' indices // is distinct, and the list of 'to' indices is a permutation of it. The algorithm here @@ -260,12 +325,6 @@ interface PermutationListEntryWithTrackingData extends PermutationListEntry { moveToBeforeMarker?: Node, } -function getLogicalNextSibling(element: LogicalElement): LogicalElement | null { - const siblings = getLogicalChildrenArray(getLogicalParent(element)!); - const siblingIndex = Array.prototype.indexOf.call(siblings, element); - return siblings[siblingIndex + 1] || null; -} - function appendDomNode(child: Node, parent: LogicalElement) { // This function only puts 'child' into the DOM in the right place relative to 'parent' // It does not update the logical children array of anything @@ -289,7 +348,7 @@ function appendDomNode(child: Node, parent: LogicalElement) { // Returns the final node (in depth-first evaluation order) that is a descendant of the logical element. // As such, the entire subtree is between 'element' and 'findLastDomNodeInRange(element)' inclusive. -function findLastDomNodeInRange(element: LogicalElement) { +function findLastDomNodeInRange(element: LogicalElement): Node { if (element instanceof Element || element instanceof DocumentFragment) { return element; } @@ -297,20 +356,16 @@ function findLastDomNodeInRange(element: LogicalElement) { const nextSibling = getLogicalNextSibling(element); if (nextSibling) { // Simple case: not the last logical sibling, so take the node before the next sibling - return (nextSibling as any as Node).previousSibling; + return (nextSibling as any as Node).previousSibling!; } else { // Harder case: there's no logical next-sibling, so recurse upwards until we find // a logical ancestor that does have one, or a physical element const logicalParent = getLogicalParent(element)!; return logicalParent instanceof Element || logicalParent instanceof DocumentFragment - ? logicalParent.lastChild + ? logicalParent.lastChild! : findLastDomNodeInRange(logicalParent); } } -function createSymbolOrFallback(fallback: string): symbol | string { - return typeof Symbol === 'function' ? Symbol() : fallback; -} - // Nominal type to represent a logical element without needing to allocate any object for instances export interface LogicalElement { LogicalElement__DO_NOT_IMPLEMENT: any } diff --git a/src/Components/Web.JS/src/Rendering/StreamingRendering.ts b/src/Components/Web.JS/src/Rendering/StreamingRendering.ts index c804cfc80625..05e29c232d97 100644 --- a/src/Components/Web.JS/src/Rendering/StreamingRendering.ts +++ b/src/Components/Web.JS/src/Rendering/StreamingRendering.ts @@ -1,14 +1,17 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -import { SsrStartOptions } from "../Platform/SsrStartOptions"; -import { performEnhancedPageLoad, replaceDocumentWithPlainText } from "../Services/NavigationEnhancement"; -import { isWithinBaseUriSpace } from "../Services/NavigationUtils"; -import { synchronizeDomContent } from "./DomMerging/DomSync"; +import { SsrStartOptions } from '../Platform/SsrStartOptions'; +import { NavigationEnhancementCallbacks, performEnhancedPageLoad, replaceDocumentWithPlainText } from '../Services/NavigationEnhancement'; +import { isWithinBaseUriSpace } from '../Services/NavigationUtils'; +import { synchronizeDomContent } from './DomMerging/DomSync'; let enableDomPreservation = true; +let navigationEnhancementCallbacks: NavigationEnhancementCallbacks; + +export function attachStreamingRenderingListener(options: SsrStartOptions | undefined, callbacks: NavigationEnhancementCallbacks) { + navigationEnhancementCallbacks = callbacks; -export function attachStreamingRenderingListener(options: SsrStartOptions | undefined) { if (options?.disableDomPreservation) { enableDomPreservation = false; } @@ -64,20 +67,23 @@ class BlazorStreamingUpdate extends HTMLElement { function insertStreamingContentIntoDocument(componentIdAsString: string, docFrag: DocumentFragment): void { const markers = findStreamingMarkers(componentIdAsString); if (markers) { + const { startMarker, endMarker } = markers; if (enableDomPreservation) { - synchronizeDomContent({ startExclusive: markers.startMarker, endExclusive: markers.endMarker }, docFrag); + synchronizeDomContent({ startExclusive: startMarker, endExclusive: endMarker }, docFrag); } else { // In this mode we completely delete the old content before inserting the new content - const { startMarker, endMarker } = markers; + const destinationRoot = endMarker.parentNode!; const existingContent = new Range(); existingContent.setStart(startMarker, startMarker.textContent!.length); existingContent.setEnd(endMarker, 0); existingContent.deleteContents(); while (docFrag.childNodes[0]) { - endMarker.parentNode!.insertBefore(docFrag.childNodes[0], endMarker); + destinationRoot.insertBefore(docFrag.childNodes[0], endMarker); } } + + navigationEnhancementCallbacks.documentUpdated(); } } diff --git a/src/Components/Web.JS/src/Rendering/WebRendererId.ts b/src/Components/Web.JS/src/Rendering/WebRendererId.ts new file mode 100644 index 000000000000..bf0c35fef594 --- /dev/null +++ b/src/Components/Web.JS/src/Rendering/WebRendererId.ts @@ -0,0 +1,10 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +// These IDs need to be kept in sync with RendererId.cs +export enum WebRendererId { + Default = 0, + Server = 1, + WebAssembly = 2, + WebView = 3, +} diff --git a/src/Components/Web.JS/src/Rendering/WebRendererInteropMethods.ts b/src/Components/Web.JS/src/Rendering/WebRendererInteropMethods.ts index 91d7ffd64cb0..e50a3513dee5 100644 --- a/src/Components/Web.JS/src/Rendering/WebRendererInteropMethods.ts +++ b/src/Components/Web.JS/src/Rendering/WebRendererInteropMethods.ts @@ -5,29 +5,64 @@ import { DotNet } from '@microsoft/dotnet-js-interop'; import { EventDescriptor } from './Events/EventDelegator'; import { enableJSRootComponents, JSComponentParametersByIdentifier, JSComponentIdentifiersByInitializer } from './JSRootComponents'; -const interopMethodsByRendererId: DotNet.DotNetObject[] = []; +const interopMethodsByRenderer = new Map(); +const resolveAttachedPromiseByRenderer = new Map void>(); +const attachedPromisesByRenderer = new Map>(); -let resolveRendererAttached : () => void; +let resolveFirstRendererAttached : () => void; -export const rendererAttached = new Promise((resolve) => { - resolveRendererAttached = resolve; +export const firstRendererAttached = new Promise((resolve) => { + resolveFirstRendererAttached = resolve; }); export function attachWebRendererInterop( + rendererId: number, interopMethods: DotNet.DotNetObject, jsComponentParameters: JSComponentParametersByIdentifier, jsComponentInitializers: JSComponentIdentifiersByInitializer, -): number { - const rendererId = interopMethodsByRendererId.length; - interopMethodsByRendererId.push(interopMethods); +): void { + if (interopMethodsByRenderer.has(rendererId)) { + throw new Error(`Interop methods are already registered for renderer ${rendererId}`); + } + + interopMethodsByRenderer.set(rendererId, interopMethods); if (Object.keys(jsComponentParameters).length > 0) { const manager = getInteropMethods(rendererId); enableJSRootComponents(manager, jsComponentParameters, jsComponentInitializers); } - resolveRendererAttached(); - return rendererId; + resolveFirstRendererAttached(); + resolveRendererAttached(rendererId); +} + +export function isRendererAttached(browserRendererId: number): boolean { + return interopMethodsByRenderer.has(browserRendererId); +} + +export function waitForRendererAttached(browserRendererId: number): Promise { + if (isRendererAttached(browserRendererId)) { + return Promise.resolve(); + } + + let attachedPromise = attachedPromisesByRenderer.get(browserRendererId); + if (!attachedPromise) { + attachedPromise = new Promise((resolve) => { + resolveAttachedPromiseByRenderer.set(browserRendererId, resolve); + }); + attachedPromisesByRenderer.set(browserRendererId, attachedPromise); + } + + return attachedPromise; +} + +function resolveRendererAttached(browserRendererId: number): void { + const resolveRendererAttached = resolveAttachedPromiseByRenderer.get(browserRendererId); + if (resolveRendererAttached) { + resolveAttachedPromiseByRenderer.delete(browserRendererId); + attachedPromisesByRenderer.delete(browserRendererId); + resolveRendererAttached(); + } } export function dispatchEvent(browserRendererId: number, eventDescriptor: EventDescriptor, eventArgs: any): void { @@ -37,8 +72,13 @@ export function dispatchEvent(browserRendererId: number, eventDescriptor: EventD }); } +export function updateRootComponents(browserRendererId: number, operationsJson: string): Promise { + const interopMethods = getInteropMethods(browserRendererId); + return interopMethods.invokeMethodAsync('UpdateRootComponents', operationsJson); +} + function getInteropMethods(rendererId: number): DotNet.DotNetObject { - const interopMethods = interopMethodsByRendererId[rendererId]; + const interopMethods = interopMethodsByRenderer.get(rendererId); if (!interopMethods) { throw new Error(`No interop methods are registered for renderer ${rendererId}`); } diff --git a/src/Components/Web.JS/src/Services/ComponentDescriptorDiscovery.ts b/src/Components/Web.JS/src/Services/ComponentDescriptorDiscovery.ts index 5e53f5ac57d1..f4a86c02644a 100644 --- a/src/Components/Web.JS/src/Services/ComponentDescriptorDiscovery.ts +++ b/src/Components/Web.JS/src/Services/ComponentDescriptorDiscovery.ts @@ -1,17 +1,17 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -export function discoverComponents(document: Document, type: 'webassembly' | 'server'): ServerComponentDescriptor[] | WebAssemblyComponentDescriptor[] { - switch (type){ +export function discoverComponents(root: Node, type: 'webassembly' | 'server'): ServerComponentDescriptor[] | WebAssemblyComponentDescriptor[] { + switch (type) { case 'webassembly': - return discoverWebAssemblyComponents(document); + return discoverWebAssemblyComponents(root); case 'server': - return discoverServerComponents(document); + return discoverServerComponents(root); } } -function discoverServerComponents(document: Document): ServerComponentDescriptor[] { - const componentComments = resolveComponentComments(document, 'server') as ServerComponentComment[]; +function discoverServerComponents(root: Node): ServerComponentDescriptor[] { + const componentComments = resolveComponentComments(root, 'server') as ServerComponentComment[]; const discoveredComponents: ServerComponentDescriptor[] = []; for (let i = 0; i < componentComments.length; i++) { const componentComment = componentComments[i]; @@ -21,6 +21,7 @@ function discoverServerComponents(document: Document): ServerComponentDescriptor componentComment.end, componentComment.sequence, componentComment.descriptor, + componentComment.key ); discoveredComponents.push(entry); @@ -58,8 +59,8 @@ export function discoverPersistedState(node: Node): string | null | undefined { return; } -function discoverWebAssemblyComponents(document: Document): WebAssemblyComponentDescriptor[] { - const componentComments = resolveComponentComments(document, 'webassembly') as WebAssemblyComponentDescriptor[]; +function discoverWebAssemblyComponents(node: Node): WebAssemblyComponentDescriptor[] { + const componentComments = resolveComponentComments(node, 'webassembly') as WebAssemblyComponentDescriptor[]; const discoveredComponents: WebAssemblyComponentDescriptor[] = []; for (let i = 0; i < componentComments.length; i++) { const componentComment = componentComments[i]; @@ -71,6 +72,7 @@ function discoverWebAssemblyComponents(document: Document): WebAssemblyComponent componentComment.typeName, componentComment.parameterDefinitions, componentComment.parameterValues, + componentComment.key ); discoveredComponents.push(entry); @@ -88,9 +90,10 @@ interface ServerComponentComment { type: 'server'; sequence: number; descriptor: string; - start: Node; - end?: Node; + start: Comment; + end?: Comment; prerenderId?: string; + key?: string; } interface WebAssemblyComponentComment { @@ -100,22 +103,19 @@ interface WebAssemblyComponentComment { parameterDefinitions?: string; parameterValues?: string; prerenderId?: string; - start: Node; - end?: Node; + start: Comment; + end?: Comment; + key?: string; } function resolveComponentComments(node: Node, type: 'webassembly' | 'server'): ComponentComment[] { - if (!node.hasChildNodes()) { - return []; - } - const result: ComponentComment[] = []; const childNodeIterator = new ComponentCommentIterator(node.childNodes); while (childNodeIterator.next() && childNodeIterator.currentElement) { const componentComment = getComponentComment(childNodeIterator, type); if (componentComment) { result.push(componentComment); - } else { + } else if (childNodeIterator.currentElement.hasChildNodes()) { const childResults = resolveComponentComments(childNodeIterator.currentElement, type); for (let j = 0; j < childResults.length; j++) { const childResult = childResults[j]; @@ -145,9 +145,9 @@ function getComponentComment(commentNodeIterator: ComponentCommentIterator, type const componentComment = parseCommentPayload(json); switch (type) { case 'webassembly': - return createWebAssemblyComponentComment(componentComment as WebAssemblyComponentComment, candidateStart, commentNodeIterator); + return createWebAssemblyComponentComment(componentComment as WebAssemblyComponentComment, candidateStart as Comment, commentNodeIterator); case 'server': - return createServerComponentComment(componentComment as ServerComponentComment, candidateStart, commentNodeIterator); + return createServerComponentComment(componentComment as ServerComponentComment, candidateStart as Comment, commentNodeIterator); } } catch (error) { throw new Error(`Found malformed component comment at ${candidateStart.textContent}`); @@ -174,8 +174,8 @@ function assertNotDirectlyOnDocument(marker: Node) { } } -function createServerComponentComment(payload: ServerComponentComment, start: Node, iterator: ComponentCommentIterator): ServerComponentComment | undefined { - const { type, descriptor, sequence, prerenderId } = payload; +function createServerComponentComment(payload: ServerComponentComment, start: Comment, iterator: ComponentCommentIterator): ServerComponentComment | undefined { + const { type, descriptor, sequence, prerenderId, key } = payload; // Regardless of whether this comment matches the type we're looking for (i.e., 'server'), we still need to move the iterator // on to its end position since we don't want to recurse into unrelated prerendered components, nor do we want to get confused @@ -208,11 +208,12 @@ function createServerComponentComment(payload: ServerComponentComment, start: No start, prerenderId, end, + key, }; } -function createWebAssemblyComponentComment(payload: WebAssemblyComponentComment, start: Node, iterator: ComponentCommentIterator): WebAssemblyComponentComment | undefined { - const { type, assembly, typeName, parameterDefinitions, parameterValues, prerenderId } = payload; +function createWebAssemblyComponentComment(payload: WebAssemblyComponentComment, start: Comment, iterator: ComponentCommentIterator): WebAssemblyComponentComment | undefined { + const { type, assembly, typeName, parameterDefinitions, parameterValues, prerenderId, key } = payload; // Regardless of whether this comment matches the type we're looking for (i.e., 'webassembly'), we still need to move the iterator // on to its end position since we don't want to recurse into unrelated prerendered components, nor do we want to get confused @@ -247,10 +248,11 @@ function createWebAssemblyComponentComment(payload: WebAssemblyComponentComment, start, prerenderId, end, + key, }; } -function getComponentEndComment(prerenderedId: string, iterator: ComponentCommentIterator): ChildNode | undefined { +function getComponentEndComment(prerenderedId: string, iterator: ComponentCommentIterator): Comment | undefined { while (iterator.next() && iterator.currentElement) { const node = iterator.currentElement; if (node.nodeType !== Node.COMMENT_NODE) { @@ -268,7 +270,7 @@ function getComponentEndComment(prerenderedId: string, iterator: ComponentCommen validateEndComponentPayload(json, prerenderedId); - return node; + return node as Comment; } return undefined; @@ -316,34 +318,72 @@ class ComponentCommentIterator { } } -interface ServerComponentMarker { - type: string; +export type ComponentMarker = ServerComponentMarker | WebAssemblyComponentMarker; + +type ServerComponentMarker = { + type: 'server'; sequence: number; descriptor: string; } +type WebAssemblyComponentMarker = { + type: 'webassembly'; + typeName: string; + assembly: string; + parameterDefinitions?: string; + parameterValues?: string; +} + +export type ComponentDescriptor = ServerComponentDescriptor | WebAssemblyComponentDescriptor; + export class ServerComponentDescriptor { - public type: string; + private static globalId = 1; + + public type: 'server'; + + public start: Comment; - public start: Node; + public end?: Comment; - public end?: Node; + public id: number; public sequence: number; public descriptor: string; - public constructor(type: string, start: Node, end: Node | undefined, sequence: number, descriptor: string) { + public key?: string; + + public constructor(type: 'server', start: Comment, end: Comment | undefined, sequence: number, descriptor: string, key: string | undefined) { + this.id = ServerComponentDescriptor.globalId++; this.type = type; this.start = start; this.end = end; this.sequence = sequence; this.descriptor = descriptor; + this.key = key; + } + + public matches(other: ComponentDescriptor): other is ServerComponentDescriptor { + return this.key === other.key && this.type === other.type; + } + + public update(other: ComponentDescriptor) { + if (!this.matches(other)) { + throw new Error(`Cannot merge mismatching component descriptors:\n${JSON.stringify(this)}\nand\n${JSON.stringify(other)}`); + } + + this.end = other.end; + this.sequence = other.sequence; + this.descriptor = other.descriptor; + this.id = other.id; } public toRecord(): ServerComponentMarker { - const result = { type: this.type, sequence: this.sequence, descriptor: this.descriptor }; - return result; + return { + type: this.type, + sequence: this.sequence, + descriptor: this.descriptor, + }; } } @@ -362,11 +402,13 @@ export class WebAssemblyComponentDescriptor { public id: number; - public start: Node; + public start: Comment; + + public end?: Comment; - public end?: Node; + public key?: string; - public constructor(type: 'webassembly', start: Node, end: Node | undefined, assembly: string, typeName: string, parameterDefinitions?: string, parameterValues?: string) { + public constructor(type: 'webassembly', start: Comment, end: Comment | undefined, assembly: string, typeName: string, parameterDefinitions?: string, parameterValues?: string, key?: string) { this.id = WebAssemblyComponentDescriptor.globalId++; this.type = type; this.assembly = assembly; @@ -375,5 +417,30 @@ export class WebAssemblyComponentDescriptor { this.parameterValues = parameterValues; this.start = start; this.end = end; + this.key = key; + } + + public matches(other: ComponentDescriptor): other is WebAssemblyComponentDescriptor { + return this.key === other.key && this.type === other.type && this.typeName === other.typeName && this.assembly === other.assembly; + } + + public update(other: ComponentDescriptor) { + if (!this.matches(other)) { + throw new Error(`Cannot merge mismatching component descriptors:\n${JSON.stringify(this)}\nand\n${JSON.stringify(other)}`); + } + + this.parameterDefinitions = other.parameterDefinitions; + this.parameterValues = other.parameterValues; + this.id = other.id; + } + + public toRecord(): WebAssemblyComponentMarker { + return { + type: this.type, + typeName: this.typeName, + assembly: this.assembly, + parameterDefinitions: this.parameterDefinitions, + parameterValues: this.parameterValues, + }; } } diff --git a/src/Components/Web.JS/src/Services/NavigationEnhancement.ts b/src/Components/Web.JS/src/Services/NavigationEnhancement.ts index 5faf12e1b51b..8d5453a16e61 100644 --- a/src/Components/Web.JS/src/Services/NavigationEnhancement.ts +++ b/src/Components/Web.JS/src/Services/NavigationEnhancement.ts @@ -1,3 +1,6 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + import { synchronizeDomContent } from '../Rendering/DomMerging/DomSync'; import { handleClickForNavigationInterception, hasInteractiveRouter } from './NavigationUtils'; @@ -29,10 +32,19 @@ different bundles that only contain minimal content. */ let currentEnhancedNavigationAbortController: AbortController | null; -let onDocumentUpdatedCallback: Function = () => {}; +let navigationEnhancementCallbacks: NavigationEnhancementCallbacks; +let performingEnhancedPageLoad: boolean; + +export interface NavigationEnhancementCallbacks { + documentUpdated: () => void; +} + +export function isPerformingEnhancedPageLoad() { + return performingEnhancedPageLoad; +} -export function attachProgressivelyEnhancedNavigationListener(onDocumentUpdated: Function) { - onDocumentUpdatedCallback = onDocumentUpdated; +export function attachProgressivelyEnhancedNavigationListener(callbacks: NavigationEnhancementCallbacks) { + navigationEnhancementCallbacks = callbacks; document.addEventListener('click', onDocumentClick); document.addEventListener('submit', onDocumentSubmit); window.addEventListener('popstate', onPopState); @@ -98,6 +110,8 @@ function onDocumentSubmit(event: SubmitEvent) { } export async function performEnhancedPageLoad(internalDestinationHref: string, fetchOptions?: RequestInit) { + performingEnhancedPageLoad = true; + // First, stop any preceding enhanced page load currentEnhancedNavigationAbortController?.abort(); @@ -122,6 +136,7 @@ export async function performEnhancedPageLoad(internalDestinationHref: string, f // For HTML responses, regardless of the status code, display it const parsedHtml = new DOMParser().parseFromString(initialContent, 'text/html'); synchronizeDomContent(document, parsedHtml); + navigationEnhancementCallbacks.documentUpdated(); } else if (responseContentType?.startsWith('text/') && initialContent) { // For any other text-based content, we'll just display it, because that's what // would happen if this was a non-enhanced request. @@ -153,13 +168,6 @@ export async function performEnhancedPageLoad(internalDestinationHref: string, f }); if (!abortSignal.aborted) { - // TEMPORARY until https://github.com/dotnet/aspnetcore/issues/48763 is implemented - // We should really be doing this on the `onInitialDocument` callback *and* inside the custom element logic - // so we can add interactive components immediately on each update. Until #48763 is implemented, the stopgap implementation - // is just to do it when the enhanced nav process completes entirely, and then if we do add any interactive components, we - // disable enhanced nav completely. - onDocumentUpdatedCallback(); - // The whole response including any streaming SSR is now finished, and it was not aborted (no other navigation // has since started). So finally, recreate the native "scroll to hash" behavior. const hashPosition = internalDestinationHref.indexOf('#'); @@ -168,6 +176,9 @@ export async function performEnhancedPageLoad(internalDestinationHref: string, f const targetElem = document.getElementById(hash); targetElem?.scrollIntoView(); } + + performingEnhancedPageLoad = false; + navigationEnhancementCallbacks.documentUpdated(); } } diff --git a/src/Components/Web.JS/src/Services/NavigationUtils.ts b/src/Components/Web.JS/src/Services/NavigationUtils.ts index d736ae434d70..1ebcd2f7aee6 100644 --- a/src/Components/Web.JS/src/Services/NavigationUtils.ts +++ b/src/Components/Web.JS/src/Services/NavigationUtils.ts @@ -1,3 +1,6 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + let hasInteractiveRouterValue = false; /** diff --git a/src/Components/Web.JS/src/Services/RootComponentManager.ts b/src/Components/Web.JS/src/Services/RootComponentManager.ts new file mode 100644 index 000000000000..634a59dc5b74 --- /dev/null +++ b/src/Components/Web.JS/src/Services/RootComponentManager.ts @@ -0,0 +1,167 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +import { ComponentDescriptor, ComponentMarker } from './ComponentDescriptorDiscovery'; +import { isRendererAttached, updateRootComponents } from '../Rendering/WebRendererInteropMethods'; + +type RootComponentOperation = RootComponentAddOperation | RootComponentUpdateOperation | RootComponentRemoveOperation; + +type RootComponentAddOperation = { + type: 'add'; + selectorId: number; + marker: ComponentMarker; +}; + +type RootComponentUpdateOperation = { + type: 'update'; + componentId: number; + marker: ComponentMarker; +}; + +type RootComponentRemoveOperation = { + type: 'remove'; + componentId: number; +}; + +export class RootComponentManager { + private readonly _registeredDescriptors = new Set(); + + private readonly _descriptorsToResolveById: { [id: number]: ComponentDescriptor } = {}; + + private readonly _lastUpdatedIdByDescriptor = new Map(); + + private readonly _componentIdsByDescriptor = new Map(); + + constructor(private readonly _browserRendererId: number) { } + + public registerComponentDescriptor(descriptor: ComponentDescriptor) { + this._registeredDescriptors.add(descriptor); + } + + private unregisterComponentDescriptor(descriptor: ComponentDescriptor) { + this._registeredDescriptors.delete(descriptor); + } + + public async handleUpdatedRootComponents(addNewRootComponents: boolean) { + await this.handleUpdatedRootComponentsCore(this._registeredDescriptors, addNewRootComponents); + } + + private async handleUpdatedRootComponentsCore(descriptors: Iterable, addNewRootComponents: boolean) { + if (!isRendererAttached(this._browserRendererId)) { + // There's no attached renderer to update interactive root components, so we'll no-op. + // An alternative would be to asynchronously wait for the renderer to attach before + // continuing, but that might happen at an inconvenient point in the future. For example, + // 'addNewRootComponents' might have been specified as 'true', but this method could + // continue execution at a time when the caller would have preferred it to be 'false'. + return; + } + + const operations: RootComponentOperation[] = []; + + for (const descriptor of descriptors) { + if (isDescriptorInDocument(descriptor)) { + if (!this.doesComponentNeedUpdate(descriptor)) { + // The descriptor has not changed. + continue; + } + + if (!this.hasComponentEverBeenUpdated(descriptor)) { + if (addNewRootComponents) { + // This is the first time we're seeing this marker. + this.markComponentAsUpdated(descriptor); + this.markComponentAsPendingResolution(descriptor); + operations.push({ type: 'add', selectorId: descriptor.id, marker: descriptor.toRecord() }); + } + continue; + } + + const componentId = this.getInteractiveComponentId(descriptor); + if (componentId !== undefined) { + // The component has become interactive, so we'll update its parameters. + this.markComponentAsUpdated(descriptor); + operations.push({ type: 'update', componentId, marker: descriptor.toRecord() }); + continue; + } + + // We have started to add the component, but it has not become interactive yet. + // We'll wait until we have a component ID to work with before sending parameter + // updates. + } else { + this.unregisterComponentDescriptor(descriptor); + + const componentId = this.getInteractiveComponentId(descriptor); + if (componentId !== undefined) { + // We have an interactive component for this marker, so we'll remove it. + operations.push({ type: 'remove', componentId }); + continue; + } + + // If we make it here, that means we either: + // 1. Haven't started to make the component interactive, in which case we have no further action to take. + // 2. Have started to make the component interactive, but it hasn't become interactive yet. In this case, + // we'll wait to remove the component until after we have a component ID to provide. + } + } + + if (!operations.length) { + return; + } + + const operationsJson = JSON.stringify(operations); + await updateRootComponents(this._browserRendererId, operationsJson); + } + + public resolveRootComponent(resolutionId: number, componentId: number): ComponentDescriptor { + const descriptor = this.resolveComponentById(resolutionId); + if (!descriptor) { + throw new Error(`Could not resolve a root component for descriptor with ID '${resolutionId}'.`); + } + + if (this.getInteractiveComponentId(descriptor) !== undefined) { + throw new Error('Cannot resolve a root component for the same descriptor multiple times.'); + } + + this.setInteractiveComponentId(descriptor, componentId); + + // The descriptor may have changed since the last call to handleUpdatedRootComponentsCore(). + // We'll update this single descriptor so that the component receives the most up-to-date parameters + // or gets removed if it no longer exists on the page. + this.handleUpdatedRootComponentsCore([descriptor], false); + + return descriptor; + } + + private doesComponentNeedUpdate(descriptor: ComponentDescriptor) { + return this._lastUpdatedIdByDescriptor.get(descriptor) !== descriptor.id; + } + + private markComponentAsUpdated(descriptor: ComponentDescriptor) { + this._lastUpdatedIdByDescriptor.set(descriptor, descriptor.id); + } + + private markComponentAsPendingResolution(descriptor: ComponentDescriptor) { + this._descriptorsToResolveById[descriptor.id] = descriptor; + } + + private resolveComponentById(id: number): ComponentDescriptor | undefined { + const result = this._descriptorsToResolveById[id]; + delete this._descriptorsToResolveById[id]; + return result; + } + + private hasComponentEverBeenUpdated(descriptor: ComponentDescriptor) { + return this._lastUpdatedIdByDescriptor.has(descriptor); + } + + private getInteractiveComponentId(descriptor: ComponentDescriptor): number | undefined { + return this._componentIdsByDescriptor.get(descriptor); + } + + private setInteractiveComponentId(descriptor: ComponentDescriptor, componentId: number): void { + this._componentIdsByDescriptor.set(descriptor, componentId); + } +} + +function isDescriptorInDocument(descriptor: ComponentDescriptor): boolean { + return document.contains(descriptor.start); +} diff --git a/src/Components/Web/src/HtmlRendering/StaticHtmlRenderer.HtmlWriting.cs b/src/Components/Web/src/HtmlRendering/StaticHtmlRenderer.HtmlWriting.cs index c285ec4b759d..7a475f70563d 100644 --- a/src/Components/Web/src/HtmlRendering/StaticHtmlRenderer.HtmlWriting.cs +++ b/src/Components/Web/src/HtmlRendering/StaticHtmlRenderer.HtmlWriting.cs @@ -39,6 +39,16 @@ protected internal virtual void WriteComponentHtml(int componentId, TextWriter o RenderFrames(componentId, output, frames, 0, frames.Count); } + /// + /// Renders the specified component frame as HTML to the output. + /// + /// The output destination. + /// The representing the component to be rendered. + protected virtual void RenderChildComponent(TextWriter output, ref RenderTreeFrame componentFrame) + { + WriteComponentHtml(componentFrame.ComponentId, output); + } + private int RenderFrames(int componentId, TextWriter output, ArrayRange frames, int position, int maxElements) { var nextPosition = position; @@ -306,7 +316,7 @@ private int RenderChildComponent(TextWriter output, ArrayRange { ref var frame = ref frames.Array[position]; - WriteComponentHtml(frame.ComponentId, output); + RenderChildComponent(output, ref frame); return position + frame.ComponentSubtreeLength; } diff --git a/src/Components/Web/src/PublicAPI.Unshipped.txt b/src/Components/Web/src/PublicAPI.Unshipped.txt index 3215ee46ed2b..341bc7e08f50 100644 --- a/src/Components/Web/src/PublicAPI.Unshipped.txt +++ b/src/Components/Web/src/PublicAPI.Unshipped.txt @@ -62,7 +62,6 @@ Microsoft.AspNetCore.Components.HtmlRendering.Infrastructure.StaticHtmlRenderer. Microsoft.AspNetCore.Components.HtmlRendering.Infrastructure.StaticHtmlRenderer.BeginRenderingComponent(System.Type! componentType, Microsoft.AspNetCore.Components.ParameterView initialParameters) -> Microsoft.AspNetCore.Components.Web.HtmlRendering.HtmlRootComponent Microsoft.AspNetCore.Components.HtmlRendering.Infrastructure.StaticHtmlRenderer.StaticHtmlRenderer(System.IServiceProvider! serviceProvider, Microsoft.Extensions.Logging.ILoggerFactory! loggerFactory) -> void Microsoft.AspNetCore.Components.HtmlRendering.Infrastructure.StaticHtmlRenderer.TryCreateScopeQualifiedEventName(int componentId, string! assignedEventName, out string? scopeQualifiedEventName) -> bool -Microsoft.AspNetCore.Components.RenderTree.WebRenderer.WaitUntilAttachedAsync() -> System.Threading.Tasks.Task! Microsoft.AspNetCore.Components.SupplyParameterFromFormAttribute Microsoft.AspNetCore.Components.SupplyParameterFromFormAttribute.Handler.get -> string? Microsoft.AspNetCore.Components.SupplyParameterFromFormAttribute.Handler.set -> void @@ -121,6 +120,9 @@ static Microsoft.AspNetCore.Components.Forms.Mapping.SupplyParameterFromFormServ static Microsoft.AspNetCore.Components.Web.RenderMode.Auto.get -> Microsoft.AspNetCore.Components.Web.AutoRenderMode! static Microsoft.AspNetCore.Components.Web.RenderMode.Server.get -> Microsoft.AspNetCore.Components.Web.ServerRenderMode! static Microsoft.AspNetCore.Components.Web.RenderMode.WebAssembly.get -> Microsoft.AspNetCore.Components.Web.WebAssemblyRenderMode! +virtual Microsoft.AspNetCore.Components.HtmlRendering.Infrastructure.StaticHtmlRenderer.RenderChildComponent(System.IO.TextWriter! output, ref Microsoft.AspNetCore.Components.RenderTree.RenderTreeFrame componentFrame) -> void virtual Microsoft.AspNetCore.Components.HtmlRendering.Infrastructure.StaticHtmlRenderer.WriteComponentHtml(int componentId, System.IO.TextWriter! output) -> void +virtual Microsoft.AspNetCore.Components.RenderTree.WebRenderer.GetWebRendererId() -> int +virtual Microsoft.AspNetCore.Components.RenderTree.WebRenderer.UpdateRootComponents(string! operationsJson) -> void Microsoft.AspNetCore.Components.Web.Virtualization.Virtualize.EmptyContent.get -> Microsoft.AspNetCore.Components.RenderFragment? Microsoft.AspNetCore.Components.Web.Virtualization.Virtualize.EmptyContent.set -> void diff --git a/src/Components/Web/src/WebRenderer.cs b/src/Components/Web/src/WebRenderer.cs index 240b207c4e83..9430f331069a 100644 --- a/src/Components/Web/src/WebRenderer.cs +++ b/src/Components/Web/src/WebRenderer.cs @@ -18,7 +18,7 @@ namespace Microsoft.AspNetCore.Components.RenderTree; public abstract class WebRenderer : Renderer { private readonly DotNetObjectReference _interopMethodsReference; - private readonly Task _attachTask; + private readonly int _rendererId; /// /// Constructs an instance of . @@ -36,48 +36,40 @@ public WebRenderer( { _interopMethodsReference = DotNetObjectReference.Create( new WebRendererInteropMethods(this, jsonOptions, jsComponentInterop)); + _rendererId = GetWebRendererId(); // Supply a DotNetObjectReference to JS that it can use to call us back for events etc. jsComponentInterop.AttachToRenderer(this); var jsRuntime = serviceProvider.GetRequiredService(); - _attachTask = jsRuntime.InvokeAsync( + jsRuntime.InvokeVoidAsync( "Blazor._internal.attachWebRendererInterop", + _rendererId, _interopMethodsReference, jsComponentInterop.Configuration.JSComponentParametersByIdentifier, - jsComponentInterop.Configuration.JSComponentIdentifiersByInitializer) - .AsTask(); + jsComponentInterop.Configuration.JSComponentIdentifiersByInitializer).Preserve(); } /// /// Gets the identifier for the renderer. /// - /// - /// Accessing before the renderer is attached will throw an . Call - /// to wait until the renderer gets attached to the browser. - /// protected int RendererId { - get - { - if (!_attachTask.IsCompletedSuccessfully) - { - throw new InvalidOperationException($"'{nameof(RendererId)}' does not have a value until {nameof(WaitUntilAttachedAsync)} completes successfully."); - } - - return _attachTask.Result; - } + get => _rendererId; - [Obsolete($"The renderer ID gets assigned automatically upon construction.")] + [Obsolete($"The renderer ID can be assigned by overriding '{nameof(GetWebRendererId)}'.")] init { /* No-op */ } } /// - /// Waits until the renderer is attached to the browser. The renderer must be attached before - /// renders can be processed. + /// Allocates an identifier for the renderer. /// - /// - public Task WaitUntilAttachedAsync() - => _attachTask; + protected virtual int GetWebRendererId() + { + // We return '0' by default, which is reserved so that classes deriving from this + // type don't need to worry about allocating an ID unless they're using multiple renderers. + // As soon as multiple renderers are used, this needs to return a unique identifier. + return 0; + } /// /// Instantiates a root component and attaches it to the browser within the specified element. @@ -93,6 +85,14 @@ protected internal int AddRootComponent([DynamicallyAccessedMembers(Component)] return componentId; } + /// + /// Performs the specified operations on the renderer's root components. + /// + /// A JSON-serialized list of operations to perform on the renderer's root components. + protected virtual void UpdateRootComponents(string operationsJson) + { + } + /// /// Called by the framework to give a location for the specified root component in the browser DOM. /// @@ -123,6 +123,7 @@ internal sealed class WebRendererInteropMethods private readonly JSComponentInterop _jsComponentInterop; [DynamicDependency(nameof(DispatchEventAsync))] + [DynamicDependency(nameof(UpdateRootComponents))] public WebRendererInteropMethods(WebRenderer renderer, JsonSerializerOptions jsonOptions, JSComponentInterop jsComponentInterop) { _renderer = renderer; @@ -140,6 +141,10 @@ public Task DispatchEventAsync(JsonElement eventDescriptor, JsonElement eventArg webEventData.EventArgs); } + [JSInvokable] + public void UpdateRootComponents(string operationsJson) + => _renderer.UpdateRootComponents(operationsJson); + [JSInvokable] // Linker preserves this if you call RootComponents.Add public int AddRootComponent(string identifier, string domElementSelector) => _jsComponentInterop.AddRootComponent(identifier, domElementSelector); diff --git a/src/Components/WebAssembly/WebAssembly/src/Hosting/WebAssemblyHost.cs b/src/Components/WebAssembly/WebAssembly/src/Hosting/WebAssemblyHost.cs index 78af496244cc..fdc1ffbf5638 100644 --- a/src/Components/WebAssembly/WebAssembly/src/Hosting/WebAssemblyHost.cs +++ b/src/Components/WebAssembly/WebAssembly/src/Hosting/WebAssemblyHost.cs @@ -147,9 +147,7 @@ internal async Task RunAsyncCore(CancellationToken cancellationToken, WebAssembl { var loggerFactory = Services.GetRequiredService(); var jsComponentInterop = new JSComponentInterop(_rootComponents.JSComponents); - _renderer = new WebAssemblyRenderer(Services, loggerFactory, jsComponentInterop); - await _renderer.WaitUntilAttachedAsync(); WebAssemblyNavigationManager.Instance.CreateLogger(loggerFactory); diff --git a/src/Components/WebAssembly/WebAssembly/src/Hosting/WebAssemblyHostBuilder.cs b/src/Components/WebAssembly/WebAssembly/src/Hosting/WebAssemblyHostBuilder.cs index 1088029a3542..761c256db2c4 100644 --- a/src/Components/WebAssembly/WebAssembly/src/Hosting/WebAssemblyHostBuilder.cs +++ b/src/Components/WebAssembly/WebAssembly/src/Hosting/WebAssemblyHostBuilder.cs @@ -107,13 +107,20 @@ private void InitializeRegisteredRootComponents(IInternalJSImportMethods jsMetho var typeName = jsMethods.RegisteredComponents_GetTypeName(id); var serializedParameterDefinitions = jsMethods.RegisteredComponents_GetParameterDefinitions(id); var serializedParameterValues = jsMethods.RegisteredComponents_GetParameterValues(id); - registeredComponents[i] = new WebAssemblyComponentMarker(WebAssemblyComponentMarker.ClientMarkerType, assembly, typeName, serializedParameterDefinitions, serializedParameterValues, id.ToString(CultureInfo.InvariantCulture)); + registeredComponents[i] = new WebAssemblyComponentMarker( + WebAssemblyComponentMarker.ClientMarkerType, + assembly, + typeName, + serializedParameterDefinitions, + serializedParameterValues, + key: null, + id.ToString(CultureInfo.InvariantCulture)); } + _rootComponentCache = new RootComponentTypeCache(); var componentDeserializer = WebAssemblyComponentParameterDeserializer.Instance; foreach (var registeredComponent in registeredComponents) { - _rootComponentCache = new RootComponentTypeCache(); var componentType = _rootComponentCache.GetRootComponent(registeredComponent.Assembly!, registeredComponent.TypeName!); if (componentType is null) { @@ -253,6 +260,7 @@ internal void InitializeDefaultServices() Services.AddSingleton(WebAssemblyNavigationInterception.Instance); Services.AddSingleton(WebAssemblyScrollToLocationHash.Instance); Services.AddSingleton(new LazyAssemblyLoader(DefaultWebAssemblyJSRuntime.Instance)); + Services.AddSingleton(_ => _rootComponentCache ?? new()); Services.AddSingleton(); Services.AddSingleton(sp => sp.GetRequiredService().State); Services.AddSingleton(); diff --git a/src/Components/WebAssembly/WebAssembly/src/Microsoft.AspNetCore.Components.WebAssembly.csproj b/src/Components/WebAssembly/WebAssembly/src/Microsoft.AspNetCore.Components.WebAssembly.csproj index ea7753c90d81..f42214bede04 100644 --- a/src/Components/WebAssembly/WebAssembly/src/Microsoft.AspNetCore.Components.WebAssembly.csproj +++ b/src/Components/WebAssembly/WebAssembly/src/Microsoft.AspNetCore.Components.WebAssembly.csproj @@ -36,7 +36,10 @@ + + + diff --git a/src/Components/WebAssembly/WebAssembly/src/Rendering/WebAssemblyRenderer.cs b/src/Components/WebAssembly/WebAssembly/src/Rendering/WebAssemblyRenderer.cs index f5234edc5f92..254dafecbc44 100644 --- a/src/Components/WebAssembly/WebAssembly/src/Rendering/WebAssemblyRenderer.cs +++ b/src/Components/WebAssembly/WebAssembly/src/Rendering/WebAssemblyRenderer.cs @@ -2,13 +2,16 @@ // The .NET Foundation licenses this file to you under the MIT license. using System.Diagnostics.CodeAnalysis; +using System.Globalization; using System.Runtime.CompilerServices; using System.Runtime.InteropServices.JavaScript; +using System.Text.Json; using Microsoft.AspNetCore.Components.RenderTree; using Microsoft.AspNetCore.Components.Web; using Microsoft.AspNetCore.Components.Web.Infrastructure; using Microsoft.AspNetCore.Components.WebAssembly.Hosting; using Microsoft.AspNetCore.Components.WebAssembly.Services; +using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Microsoft.JSInterop; using static Microsoft.AspNetCore.Internal.LinkerFlags; @@ -21,11 +24,13 @@ namespace Microsoft.AspNetCore.Components.WebAssembly.Rendering; /// internal sealed partial class WebAssemblyRenderer : WebRenderer { + private readonly RootComponentTypeCache _rootComponentCache; private readonly ILogger _logger; public WebAssemblyRenderer(IServiceProvider serviceProvider, ILoggerFactory loggerFactory, JSComponentInterop jsComponentInterop) : base(serviceProvider, loggerFactory, DefaultWebAssemblyJSRuntime.Instance.ReadJsonSerializerOptions(), jsComponentInterop) { + _rootComponentCache = serviceProvider.GetRequiredService(); _logger = loggerFactory.CreateLogger(); ElementReferenceContext = DefaultWebAssemblyJSRuntime.Instance.ElementReferenceContext; @@ -39,6 +44,8 @@ public Task AddComponentAsync([DynamicallyAccessedMembers(Component)] Type compo return RenderRootComponentAsync(componentId, parameters); } + protected override int GetWebRendererId() => (int)WebRendererId.WebAssembly; + protected override void AttachRootComponentToBrowser(int componentId, string domElementSelector) { DefaultWebAssemblyJSRuntime.Instance.InvokeVoid( @@ -48,6 +55,81 @@ protected override void AttachRootComponentToBrowser(int componentId, string dom RendererId); } + [DynamicDependency(JsonSerialized, typeof(RootComponentOperation))] + [UnconditionalSuppressMessage("Trimming", "IL2026", Justification = "The correct members will be preserved by the above DynamicDependency")] + protected override void UpdateRootComponents(string operationsJson) + { + var operations = JsonSerializer.Deserialize>>( + operationsJson, + WebAssemblyComponentSerializationSettings.JsonSerializationOptions)!; + + foreach (var operation in operations) + { + switch (operation.Type) + { + case RootComponentOperationType.Add: + AddRootComponent(operation); + break; + case RootComponentOperationType.Update: + UpdateRootComponent(operation); + break; + case RootComponentOperationType.Remove: + RemoveRootComponent(operation); + break; + } + } + + return; + + [UnconditionalSuppressMessage("Trimming", "IL2072", Justification = "Root components are expected to be defined in assemblies that do not get trimmed.")] + void AddRootComponent(RootComponentOperation operation) + { + if (operation.SelectorId is not { } selectorId) + { + throw new InvalidOperationException($"The component operation of type '{operation.Type}' requires a '{nameof(operation.SelectorId)}' to be specified."); + } + + var marker = operation.Marker; + var componentType = _rootComponentCache.GetRootComponent(marker.Assembly!, marker.TypeName!) + ?? throw new InvalidOperationException($"Root component type '{marker.TypeName}' could not be found in the assembly '{marker.Assembly}'."); + + var parameters = DeserializeComponentParameters(marker); + _ = AddComponentAsync(componentType, parameters, selectorId.ToString(CultureInfo.InvariantCulture)); + } + + void UpdateRootComponent(RootComponentOperation operation) + { + if (operation.ComponentId is not { } componentId) + { + throw new InvalidOperationException($"The component operation of type '{operation.Type}' requires a '{nameof(operation.ComponentId)}' to be specified."); + } + + var marker = operation.Marker; + var parameters = DeserializeComponentParameters(marker); + _ = RenderRootComponentAsync(componentId, parameters); + } + + void RemoveRootComponent(RootComponentOperation operation) + { + if (operation.ComponentId is not { } componentId) + { + throw new InvalidOperationException($"The component operation of type '{operation.Type}' requires a '{nameof(operation.ComponentId)}' to be specified."); + } + + this.RemoveRootComponent(componentId); + } + + static ParameterView DeserializeComponentParameters(WebAssemblyComponentMarker marker) + { + var definitions = WebAssemblyComponentParameterDeserializer.GetParameterDefinitions(marker.ParameterDefinitions!); + var values = WebAssemblyComponentParameterDeserializer.GetParameterValues(marker.ParameterValues!); + var componentDeserializer = WebAssemblyComponentParameterDeserializer.Instance; + var parameters = componentDeserializer.DeserializeParameters(definitions, values); + + return parameters; + } + } + /// protected override void Dispose(bool disposing) { diff --git a/src/Components/WebView/WebView/src/Microsoft.AspNetCore.Components.WebView.csproj b/src/Components/WebView/WebView/src/Microsoft.AspNetCore.Components.WebView.csproj index 762431c770c3..5d9fc8dad81e 100644 --- a/src/Components/WebView/WebView/src/Microsoft.AspNetCore.Components.WebView.csproj +++ b/src/Components/WebView/WebView/src/Microsoft.AspNetCore.Components.WebView.csproj @@ -30,6 +30,7 @@ + diff --git a/src/Components/WebView/WebView/src/Services/WebViewRenderer.cs b/src/Components/WebView/WebView/src/Services/WebViewRenderer.cs index dfe3f8ba6f40..1284df8ebd74 100644 --- a/src/Components/WebView/WebView/src/Services/WebViewRenderer.cs +++ b/src/Components/WebView/WebView/src/Services/WebViewRenderer.cs @@ -31,6 +31,8 @@ public WebViewRenderer( public override Dispatcher Dispatcher => _dispatcher; + protected override int GetWebRendererId() => (int)WebRendererId.WebView; + protected override void HandleException(Exception exception) { // Notify the JS code so it can show the in-app UI diff --git a/src/Components/test/E2ETest/ServerRenderingTests/InteractivityTest.cs b/src/Components/test/E2ETest/ServerRenderingTests/InteractivityTest.cs index 53ab3d6e672f..0fc8760ebb47 100644 --- a/src/Components/test/E2ETest/ServerRenderingTests/InteractivityTest.cs +++ b/src/Components/test/E2ETest/ServerRenderingTests/InteractivityTest.cs @@ -179,6 +179,257 @@ public void CanUseCallSiteRenderMode_ServerAndWebAssembly(bool prerender) Browser.Equal("10", () => countServerElem.Text); } + private const string AddServerId = "add-server-counter-link"; + private const string AddServerPrerenderedId = "add-server-counter-prerendered-link"; + private const string AddWebAssemblyId = "add-webassembly-counter-link"; + private const string AddWebAssemblyPrerenderedId = "add-webassembly-counter-prerendered-link"; + + public static readonly TheoryData AddCounterLinkSequences = new() + { + // One component + new[] { AddServerPrerenderedId }, + new[] { AddWebAssemblyPrerenderedId }, + + // Multiple components, mixing all combinations of Server/WebAssembly and prerendered/non-prerendered + new[] { AddServerPrerenderedId, AddWebAssemblyId, AddWebAssemblyPrerenderedId, AddServerId }, + }; + + [Theory] + [InlineData(AddServerId)] + [InlineData(AddServerPrerenderedId)] + [InlineData(AddWebAssemblyId)] + [InlineData(AddWebAssemblyPrerenderedId)] + public void DynamicallyAddedSsrComponent_CanBecomeInteractive_AfterEnhancedNavigation(string addCounterLinkId) + { + Navigate($"{ServerPathBase}/streaming-interactivity"); + + Browser.Equal("Not streaming", () => Browser.FindElement(By.Id("status")).Text); + + Browser.Click(By.Id(addCounterLinkId)); + Browser.Equal("True", () => Browser.FindElement(By.Id("is-interactive-0")).Text); + + Browser.Click(By.Id("increment-0")); + Browser.Equal("1", () => Browser.FindElement(By.Id("count-0")).Text); + + AssertBrowserLogDoesNotContainErrors(); + } + + [Theory] + [MemberData(nameof(AddCounterLinkSequences))] + public void MultipleDynamicallyAddedSsrComponents_CanBecomeInteractive_AfterEnhancedNavigation(string[] addCounterLinkIds) + { + Navigate($"{ServerPathBase}/streaming-interactivity"); + + Browser.Equal("Not streaming", () => Browser.FindElement(By.Id("status")).Text); + + for (var i = 0; i < addCounterLinkIds.Length; i++) + { + Browser.Click(By.Id(addCounterLinkIds[i])); + Browser.Equal("True", () => Browser.FindElement(By.Id($"is-interactive-{i}")).Text); + + Browser.Click(By.Id($"increment-{i}")); + Browser.Equal("1", () => Browser.FindElement(By.Id($"count-{i}")).Text); + } + + AssertBrowserLogDoesNotContainErrors(); + } + + [Theory] + [MemberData(nameof(AddCounterLinkSequences))] + public void DynamicallyAddedSsrComponents_CanBecomeInteractive_AfterStreamingRenderingCompletes(string[] addCounterLinkIds) + { + Navigate($"{ServerPathBase}/streaming-interactivity"); + + Browser.Equal("Not streaming", () => Browser.FindElement(By.Id("status")).Text); + Browser.Click(By.Id("start-streaming-link")); + Browser.Equal("Streaming", () => Browser.FindElement(By.Id("status")).Text); + + for (var i = 0; i < addCounterLinkIds.Length; i++) + { + Browser.Click(By.Id(addCounterLinkIds[i])); + + // To verify that components use the most up-to-date parameters when they become interactive, we + // perform SSR updates with new parameter values. + // The first counter will have an increment amount of 1, the second 2, etc. + for (var j = 0; j < i; j++) + { + Browser.Click(By.Id($"update-counter-link-{i}")); + } + + if (addCounterLinkIds[i].Contains("prerendered")) + { + Browser.Equal("False", () => Browser.FindElement(By.Id($"is-interactive-{i}")).Text); + Browser.Click(By.Id($"increment-{i}")); + Browser.Equal("0", () => Browser.FindElement(By.Id($"count-{i}")).Text); + } + else + { + // Non-prerendered components won't produce any output until they become interactive. + // We verify this by ensuring that the "action links" exist on the page, + // but the interactive component does not. + Browser.Exists(By.Id($"remove-counter-link-{i}")); + Browser.DoesNotExist(By.Id($"is-interactive-{i}")); + } + } + + Browser.Click(By.Id("stop-streaming-link")); + + for (var i = 0; i < addCounterLinkIds.Length; i++) + { + Browser.Equal("True", () => Browser.FindElement(By.Id($"is-interactive-{i}")).Text); + + Browser.Click(By.Id($"increment-{i}")); + Browser.Equal($"{i + 1}", () => Browser.FindElement(By.Id($"count-{i}")).Text); + } + + AssertBrowserLogDoesNotContainErrors(); + } + + [Theory] + [MemberData(nameof(AddCounterLinkSequences))] + public void InteractiveRootComponents_CanReceiveSsrParameterUpdates_FromEnhancedNavigation(string[] addCounterLinkIds) + { + Navigate($"{ServerPathBase}/streaming-interactivity"); + + Browser.Equal("Not streaming", () => Browser.FindElement(By.Id("status")).Text); + + for (var i = 0; i < addCounterLinkIds.Length; i++) + { + Browser.Click(By.Id(addCounterLinkIds[i])); + Browser.Equal("True", () => Browser.FindElement(By.Id($"is-interactive-{i}")).Text); + + Browser.Click(By.Id($"increment-{i}")); + Browser.Equal("1", () => Browser.FindElement(By.Id($"count-{i}")).Text); + + Browser.Click(By.Id($"update-counter-link-{i}")); + Browser.Equal("2", () => Browser.FindElement(By.Id($"increment-amount-{i}")).Text); + + Browser.Click(By.Id($"increment-{i}")); + Browser.Equal("3", () => Browser.FindElement(By.Id($"count-{i}")).Text); + } + + AssertBrowserLogDoesNotContainErrors(); + } + + [Theory] + [MemberData(nameof(AddCounterLinkSequences))] + public void InteractiveRootComponents_CanReceiveSsrParameterUpdates_FromStreamingRenderingUpdate(string[] addCounterLinkIds) + { + Navigate($"{ServerPathBase}/streaming-interactivity"); + + Browser.Equal("Not streaming", () => Browser.FindElement(By.Id("status")).Text); + + // Components don't become interactive during streaming rendering, so we need to + // add then via enhanced navigation first + for (var i = 0; i < addCounterLinkIds.Length; i++) + { + Browser.Click(By.Id(addCounterLinkIds[i])); + Browser.Equal("True", () => Browser.FindElement(By.Id($"is-interactive-{i}")).Text); + } + + Browser.Click(By.Id("start-streaming-link")); + Browser.Equal("Streaming", () => Browser.FindElement(By.Id("status")).Text); + + for (var i = 0; i < addCounterLinkIds.Length; i++) + { + Browser.Click(By.Id($"increment-{i}")); + Browser.Equal("1", () => Browser.FindElement(By.Id($"count-{i}")).Text); + + Browser.Click(By.Id($"update-counter-link-{i}")); + Browser.Equal("2", () => Browser.FindElement(By.Id($"increment-amount-{i}")).Text); + + Browser.Click(By.Id($"increment-{i}")); + Browser.Equal("3", () => Browser.FindElement(By.Id($"count-{i}")).Text); + } + + Browser.Click(By.Id("stop-streaming-link")); + + AssertBrowserLogDoesNotContainErrors(); + } + + [Theory] + [MemberData(nameof(AddCounterLinkSequences))] + public void InteractiveRootComponents_CanGetDisposed_FromEnhancedNavigation(string[] addCounterLinkIds) + { + Navigate($"{ServerPathBase}/streaming-interactivity"); + + Browser.Equal("Not streaming", () => Browser.FindElement(By.Id("status")).Text); + + for (var i = 0; i < addCounterLinkIds.Length; i++) + { + Browser.Click(By.Id(addCounterLinkIds[i])); + Browser.Equal("True", () => Browser.FindElement(By.Id($"is-interactive-{i}")).Text); + } + + for (var i = 0; i < addCounterLinkIds.Length; i++) + { + Browser.Click(By.Id($"remove-counter-link-{i}")); + Browser.DoesNotExist(By.Id($"remove-counter-link-{i}")); + AssertBrowserLogContainsMessage($"Counter {i} was disposed"); + } + + AssertBrowserLogDoesNotContainErrors(); + } + + [Theory] + [MemberData(nameof(AddCounterLinkSequences))] + public void InteractiveRootComponents_CanGetDisposed_FromStreamingRenderingUpdate(string[] addCounterLinkIds) + { + Navigate($"{ServerPathBase}/streaming-interactivity"); + + Browser.Equal("Not streaming", () => Browser.FindElement(By.Id("status")).Text); + + // Components don't become interactive during streaming rendering, so we need to + // add then via enhanced navigation first + for (var i = 0; i < addCounterLinkIds.Length; i++) + { + Browser.Click(By.Id(addCounterLinkIds[i])); + Browser.Equal("True", () => Browser.FindElement(By.Id($"is-interactive-{i}")).Text); + } + + Browser.Click(By.Id("start-streaming-link")); + Browser.Equal("Streaming", () => Browser.FindElement(By.Id("status")).Text); + + for (var i = 0; i < addCounterLinkIds.Length; i++) + { + Browser.Click(By.Id($"remove-counter-link-{i}")); + Browser.DoesNotExist(By.Id($"remove-counter-link-{i}")); + AssertBrowserLogContainsMessage($"Counter {i} was disposed"); + } + + Browser.Click(By.Id("stop-streaming-link")); + + AssertBrowserLogDoesNotContainErrors(); + } + + [Theory] + [MemberData(nameof(AddCounterLinkSequences))] + public void DynamicallyAddedSsrComponents_CanGetRemoved_BeforeStreamingRenderingCompletes(string[] addCounterLinkIds) + { + Navigate($"{ServerPathBase}/streaming-interactivity"); + + Browser.Equal("Not streaming", () => Browser.FindElement(By.Id("status")).Text); + Browser.Click(By.Id("start-streaming-link")); + Browser.Equal("Streaming", () => Browser.FindElement(By.Id("status")).Text); + + for (var i = 0; i < addCounterLinkIds.Length; i++) + { + Browser.Click(By.Id(addCounterLinkIds[i])); + Browser.Exists(By.Id($"remove-counter-link-{i}")); + } + + Browser.Click(By.Id($"remove-counter-link-0")); + + Browser.Click(By.Id("stop-streaming-link")); + + for (var i = 1; i < addCounterLinkIds.Length; i++) + { + Browser.Equal("True", () => Browser.FindElement(By.Id($"is-interactive-{i}")).Text); + } + + AssertBrowserLogDoesNotContainErrors(); + } + private string InteractiveCallsiteUrl(bool prerender, int? serverIncrement = default, int? webAssemblyIncrement = default) { var result = $"{ServerPathBase}/interactive-callsite?suppress-autostart&prerender={prerender}"; @@ -195,4 +446,19 @@ private string InteractiveCallsiteUrl(bool prerender, int? serverIncrement = def return result; } + + private void AssertBrowserLogContainsMessage(string message) + { + Browser.True(() => + { + var entries = Browser.Manage().Logs.GetLog(LogType.Browser); + return entries.Any(entry => entry.Message.Contains(message)); + }); + } + + private void AssertBrowserLogDoesNotContainErrors() + { + var entries = Browser.Manage().Logs.GetLog(LogType.Browser); + Assert.DoesNotContain(entries, entry => entry.Level == LogLevel.Severe); + } } diff --git a/src/Components/test/E2ETest/Tests/JSRootComponentsTest.cs b/src/Components/test/E2ETest/Tests/JSRootComponentsTest.cs index a3000e3f1748..c94a9bc98284 100644 --- a/src/Components/test/E2ETest/Tests/JSRootComponentsTest.cs +++ b/src/Components/test/E2ETest/Tests/JSRootComponentsTest.cs @@ -87,16 +87,6 @@ public void CanAddAndRemoveMultipleRootComponentsToTheSameElement() AssertGlobalErrorState(false); } - [Fact] - public void CannotAddMultipleRootComponentsToTheSameElementAtTheSameTime() - { - // Try adding a second without removing the first - app.FindElement(By.Id("add-root-component-inside-blazor")).Click(); - app.FindElement(By.Id("add-root-component-inside-blazor")).Click(); - - AssertGlobalErrorState(true); - } - [Fact] public void CanUpdateParameters() { diff --git a/src/Components/test/testassets/Components.TestServer/RazorComponentEndpointsStartup.cs b/src/Components/test/testassets/Components.TestServer/RazorComponentEndpointsStartup.cs index 84ac8ef47690..e47406f284a7 100644 --- a/src/Components/test/testassets/Components.TestServer/RazorComponentEndpointsStartup.cs +++ b/src/Components/test/testassets/Components.TestServer/RazorComponentEndpointsStartup.cs @@ -5,6 +5,7 @@ using System.Security.Claims; using Components.TestServer.RazorComponents; using Components.TestServer.RazorComponents.Pages.Forms; +using Components.TestServer.RazorComponents.Pages.StreamingRendering; using Components.TestServer.Services; namespace TestServer; @@ -63,6 +64,7 @@ public void Configure(IApplicationBuilder app, IWebHostEnvironment env) NotEnabledStreamingRenderingComponent.MapEndpoints(endpoints); StreamingRenderingForm.MapEndpoints(endpoints); + InteractiveStreamingRenderingComponent.MapEndpoints(endpoints); MapEnhancedNavigationEndpoints(endpoints); }); diff --git a/src/Components/test/testassets/Components.TestServer/RazorComponents/Components/InteractiveStreamingRenderingComponent.razor b/src/Components/test/testassets/Components.TestServer/RazorComponents/Components/InteractiveStreamingRenderingComponent.razor new file mode 100644 index 000000000000..92eed0e8ded1 --- /dev/null +++ b/src/Components/test/testassets/Components.TestServer/RazorComponents/Components/InteractiveStreamingRenderingComponent.razor @@ -0,0 +1,228 @@ +@using System.Threading.Channels; +@using System.Text.Json; +@using System.Collections.Immutable; +@using Microsoft.AspNetCore.Mvc; +@using TestContentPackage; + +

Current status:

+ +

+ @if (_isStreaming) + { + Streaming + } + else + { + Not streaming + } +

+ +@if (_isStreaming) +{ +

+ All counter action links will work via streaming update. Interactivity will not start for + newly-added components until you click the "Stop streaming" link below. +

+

+ When running this page manually, you should open each link in a background tab so you can see the streaming updates in real time. +

+ Stop streaming +} +else +{ +

+ All counter action links will work via enhanced navigation. Interactivity will start immediately + for newly-added components. +

+

+ When running this page manually, you can click the links normally and the page will refresh after each action. +

+ Start streaming +} + +
+ @foreach (var counter in _state.Counters) + { +
+ + + +
+ + @GetActionLink($"remove-counter-link-{counter.Id}", "Remove", _state.WithRemovedCounter(counter)) + | + @GetActionLink($"update-counter-link-{counter.Id}", "Change increment amount", _state.WithUpdatedCounter(counter)) + } +
+ +
+ +
+ Add new counter: +
+ + @GetActionLink("add-server-counter-prerendered-link", "Add Server counter", _state.WithAddedCounter(RenderModeId.ServerPrerendered)) + | + @GetActionLink("add-server-counter-link", "(non-prerendered)", _state.WithAddedCounter(RenderModeId.ServerNonPrerendered)) +
+ + @GetActionLink("add-webassembly-counter-prerendered-link", "Add WebAssembly counter", _state.WithAddedCounter(RenderModeId.WebAssemblyPrerendered)) + | + @GetActionLink("add-webassembly-counter-link", "(non-prerendered)", _state.WithAddedCounter(RenderModeId.WebAssemblyNonPrerendered)) +
+ + @GetActionLink("add-auto-counter-link", "Add Auto mode counter", _state.WithAddedCounter(RenderModeId.AutoPrerendered)) + | + @GetActionLink("add-auto-counter-non-prerendered-link", "(non-prerendered)", _state.WithAddedCounter(RenderModeId.AutoNonPrerendered)) +
+ +@code { + + static Channel StreamingStateChannel; + + ComponentState _state = new(ImmutableArray.Empty, NextCounterId: 0); + bool _isStreaming = false; + + [SupplyParameterFromQuery] + public string? InitialState { get; set; } + + [SupplyParameterFromQuery] + public bool ShouldStream { get; set; } + + protected override async Task OnInitializedAsync() + { + if (InitialState is not null) + { + _state = ReadStateFromJson(InitialState); + } + + if (ShouldStream) + { + _isStreaming = true; + + StreamingStateChannel = Channel.CreateUnbounded(); + + await foreach (var state in StreamingStateChannel.Reader.ReadAllAsync()) + { + _state = state; + StateHasChanged(); + } + } + + _isStreaming = false; + } + + public static void MapEndpoints(IEndpointRouteBuilder endpoints) + { + endpoints.MapGet("streaming-interactivity/update-state", ([FromQuery(Name = "state")] string stateJson) => + { + var state = ReadStateFromJson(stateJson); + StreamingStateChannel.Writer.TryWrite(state); + return "Updated state"; + }); + + endpoints.MapGet("streaming-interactivity/end-response", () => + { + StreamingStateChannel.Writer.Complete(); + return "Response ended"; + }); + } + + private RenderFragment GetActionLink(string id, string text, ComponentState state) + { + if (_isStreaming) + { + var url = GetStreamingUrl(state); + return @@text; + } + else + { + var url = GetEnhancedNavigationUrl(state, shouldStream: false); + return @@text; + } + } + + private static ComponentState ReadStateFromJson(string stateJson) + { + return JsonSerializer.Deserialize(stateJson) + ?? throw new InvalidOperationException($"Could not parse state from JSON value '{stateJson}'"); + } + + private static string GetEscapedStateJson(ComponentState state) + { + var stateJson = JsonSerializer.Serialize(state); + var escapedStateJson = Uri.EscapeDataString(stateJson); + return escapedStateJson; + } + + private static string GetStreamingUrl(ComponentState state) + { + var stateJson = GetEscapedStateJson(state); + return $"streaming-interactivity/update-state?state={stateJson}"; + } + + private static string GetEnhancedNavigationUrl(ComponentState state, bool shouldStream) + { + var stateJson = GetEscapedStateJson(state); + return $"streaming-interactivity?{nameof(InitialState)}={stateJson}&{nameof(ShouldStream)}={shouldStream}"; + } + + private static IComponentRenderMode GetRenderMode(RenderModeId renderMode) + { + return renderMode switch + { + RenderModeId.ServerPrerendered => RenderMode.Server, + RenderModeId.ServerNonPrerendered => new ServerRenderMode(false), + RenderModeId.WebAssemblyPrerendered => RenderMode.WebAssembly, + RenderModeId.WebAssemblyNonPrerendered => new WebAssemblyRenderMode(false), + RenderModeId.AutoPrerendered => RenderMode.Auto, + RenderModeId.AutoNonPrerendered => new AutoRenderMode(false), + _ => throw new InvalidOperationException($"Unknown render mode: {renderMode}"), + }; + } + + private enum RenderModeId + { + ServerPrerendered = 0, + ServerNonPrerendered = 1, + WebAssemblyPrerendered = 2, + WebAssemblyNonPrerendered = 3, + AutoPrerendered = 4, + AutoNonPrerendered = 5, + } + + private record struct CounterInfo(int Id, int IncrementAmount, RenderModeId RenderModeId); + + private record ComponentState(ImmutableArray Counters, int NextCounterId) + { + public ComponentState WithAddedCounter(RenderModeId renderMode) + { + return this with + { + Counters = Counters.Add(new(NextCounterId, IncrementAmount: 1, renderMode)), + NextCounterId = NextCounterId + 1, + }; + } + + public ComponentState WithUpdatedCounter(in CounterInfo counter) + { + return this with + { + Counters = Counters.Replace(counter, counter with { IncrementAmount = counter.IncrementAmount + 1 }), + }; + } + + public ComponentState WithRemovedCounter(in CounterInfo counter) + { + return this with + { + Counters = Counters.Remove(counter), + }; + } + } +} diff --git a/src/Components/test/testassets/Components.TestServer/RazorComponents/Pages/Auth/InteractiveAuthenticationState.razor b/src/Components/test/testassets/Components.TestServer/RazorComponents/Pages/Auth/InteractiveAuthenticationState.razor index 77199f976abb..c4383dc6eb4e 100644 --- a/src/Components/test/testassets/Components.TestServer/RazorComponents/Pages/Auth/InteractiveAuthenticationState.razor +++ b/src/Components/test/testassets/Components.TestServer/RazorComponents/Pages/Auth/InteractiveAuthenticationState.razor @@ -13,8 +13,8 @@
-Log in | -Log out +Log in | +Log out @code { bool _interactive = false; diff --git a/src/Components/test/testassets/Components.TestServer/RazorComponents/Pages/StreamingRendering/StreamingWithInteractivity.razor b/src/Components/test/testassets/Components.TestServer/RazorComponents/Pages/StreamingRendering/StreamingWithInteractivity.razor new file mode 100644 index 000000000000..464998782a15 --- /dev/null +++ b/src/Components/test/testassets/Components.TestServer/RazorComponents/Pages/StreamingRendering/StreamingWithInteractivity.razor @@ -0,0 +1,7 @@ +@page "/streaming-interactivity" + +@attribute [StreamRendering(true)] + +

Streaming Rendering with Interactivity

+ + diff --git a/src/Components/test/testassets/Components.TestServer/RazorComponents/Shared/EnhancedNavLayout.razor b/src/Components/test/testassets/Components.TestServer/RazorComponents/Shared/EnhancedNavLayout.razor index b1e0a8cc13ef..542f7e56841b 100644 --- a/src/Components/test/testassets/Components.TestServer/RazorComponents/Shared/EnhancedNavLayout.razor +++ b/src/Components/test/testassets/Components.TestServer/RazorComponents/Shared/EnhancedNavLayout.razor @@ -2,6 +2,7 @@