From 1d32e1eb44364561b701ad0cc9a03ffbe1384bf4 Mon Sep 17 00:00:00 2001 From: Tanay Parikh Date: Thu, 10 Jun 2021 11:27:11 -0700 Subject: [PATCH 01/37] Streaming Interop (WIP) --- .../BlazorPack/BlazorPackHubProtocolWorker.cs | 7 + .../Server/src/Circuits/RemoteJSDataStream.cs | 169 ++++++++++++++++++ .../Server/src/Circuits/RemoteJSRuntime.cs | 6 + src/Components/Server/src/ComponentHub.cs | 7 +- .../Web.JS/dist/Release/blazor.server.js | 2 +- .../Web.JS/dist/Release/blazor.webview.js | 2 +- src/Components/Web.JS/src/Boot.Server.ts | 60 +++++++ src/Components/Web.JS/src/GlobalExports.ts | 3 +- src/Components/Web.JS/src/InputFile.ts | 4 +- src/Components/Web/src/Forms/InputFile.cs | 6 +- .../Web/src/Forms/InputFile/BrowserFile.cs | 2 +- .../InputFile/RemoteBrowserFileStream.cs | 115 +++--------- ...bAssemblyJSObjectReferenceJsonConverter.cs | 2 +- .../src/src/Microsoft.JSInterop.ts | 9 +- .../src/IJSDataReference.cs | 30 ++++ .../src/Implementation/JSDataReference.cs | 49 +++++ .../src/Implementation/JSObjectReference.cs | 4 + .../JSObjectReferenceJsonWorker.cs | 21 ++- .../JSDataReferenceJsonConverter.cs | 40 +++++ .../JSObjectReferenceJsonConverter.cs | 2 +- .../Microsoft.JSInterop/src/JSRuntime.cs | 22 ++- .../src/PublicAPI.Unshipped.txt | 9 +- .../JSInterop/JSCallResultTypeHelper.cs | 3 +- .../Core/src/Internal/DefaultHubDispatcher.cs | 4 +- 24 files changed, 459 insertions(+), 119 deletions(-) create mode 100644 src/Components/Server/src/Circuits/RemoteJSDataStream.cs create mode 100644 src/JSInterop/Microsoft.JSInterop/src/IJSDataReference.cs create mode 100644 src/JSInterop/Microsoft.JSInterop/src/Implementation/JSDataReference.cs create mode 100644 src/JSInterop/Microsoft.JSInterop/src/Infrastructure/JSDataReferenceJsonConverter.cs diff --git a/src/Components/Server/src/BlazorPack/BlazorPackHubProtocolWorker.cs b/src/Components/Server/src/BlazorPack/BlazorPackHubProtocolWorker.cs index 10c9ccd8acd1..d2d907c5bd85 100644 --- a/src/Components/Server/src/BlazorPack/BlazorPackHubProtocolWorker.cs +++ b/src/Components/Server/src/BlazorPack/BlazorPackHubProtocolWorker.cs @@ -35,6 +35,13 @@ protected override object DeserializeObject(ref MessagePackReader reader, Type t { return reader.ReadSingle(); } + else if (type == typeof(ReadOnlySequence)) + { + // This is how I think it should work, but sometimes the memory seems to get corrupted. + // The "await foreach (var chunk in subject)" code in RemoteJSDataStream sometimes gets + // chunks with negative lengths. So, this is not actually used in this proof-of-concept + return reader.ReadBytes() ?? null; + } else if (type == typeof(byte[])) { var bytes = reader.ReadBytes(); diff --git a/src/Components/Server/src/Circuits/RemoteJSDataStream.cs b/src/Components/Server/src/Circuits/RemoteJSDataStream.cs new file mode 100644 index 000000000000..f84c65bba73b --- /dev/null +++ b/src/Components/Server/src/Circuits/RemoteJSDataStream.cs @@ -0,0 +1,169 @@ +// Copyright (c) .NET Foundation. All rights reserved. +// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. + +using System; +using System.Buffers; +using System.Collections.Generic; +using System.IO; +using System.IO.Pipelines; +using System.Threading; +using System.Threading.Tasks; +using Microsoft.JSInterop; + +namespace Microsoft.AspNetCore.Components.Server.Circuits +{ + internal class RemoteJSDataStream : Stream + { + // Concerns with static `Instances`? Malicious actor could hijack another user's + // stream by (improbably) guessing the GUID. Maybe we put this in the JSRuntime for curcuit isolation? + private readonly static Dictionary Instances = new(); + + private readonly Guid _streamId; + private readonly long _totalLength; + private readonly CancellationToken _cancellationToken; + private readonly Stream _pipeReaderStream; + private readonly Pipe _pipe; + private long _bytesRead; + + public static Task SupplyData(string streamId, ReadOnlySequence chunk, string error) + { + if (!Instances.TryGetValue(Guid.Parse(streamId), out var instance)) + { + throw new InvalidOperationException("There is no data stream with the given identifier. It may have already been disposed."); + } + + return instance.SupplyData(chunk, error); + } + + public static async Task CreateRemoteJSDataStreamAsync( + JSRuntime runtime, + IJSDataReference jsDataReference, + long totalLength, + long maxBufferSize, + CancellationToken cancellationToken = default) + { + var streamId = Guid.NewGuid(); + var remoteJSDataStream = new RemoteJSDataStream(streamId, totalLength, maxBufferSize, cancellationToken); + await runtime.InvokeVoidAsync("Blazor._internal.sendJSDataStream", jsDataReference, streamId); + return remoteJSDataStream; + } + + private RemoteJSDataStream(Guid streamId, long totalLength, long maxBufferSize, CancellationToken cancellationToken) + { + _streamId = streamId; + _totalLength = totalLength; + _cancellationToken = cancellationToken; + + Instances.Add(_streamId, this); + + _pipe = new Pipe(new PipeOptions(pauseWriterThreshold: maxBufferSize, resumeWriterThreshold: maxBufferSize)); + _pipeReaderStream = _pipe.Reader.AsStream(); + } + + // TODO: Surely this should be IAsyncEnumerable> so we can pass through the + // data without having to copy it into a temporary buffer. But trying this gives strange errors - + // sometimes the "chunk" variable below has a negative length, even though the logic in BlazorPackHubProtocolWorker + // never returns a corrupted item as far as I can tell. + private async Task SupplyData(ReadOnlySequence chunk, string error) + { + if (chunk.Length < 0) + { + throw new InvalidOperationException($"The incoming data chunk cannot be negative."); + } + + try + { + if (!string.IsNullOrEmpty(error)) + { + throw new InvalidOperationException($"An error occurred while reading the remote stream: {error}"); + } + + if (chunk.Length == 0) + { + throw new InvalidOperationException($"The incoming data chunk cannot be empty."); + } + + _bytesRead += chunk.Length; + + if (_bytesRead > _totalLength) + { + throw new InvalidOperationException($"The incoming data stream declared a length {_totalLength}, but {_bytesRead} bytes were read."); + } + + // Enforce 1 MB max chunk size. + const int maxChunkLength = 1024 * 1024; + if (chunk.Length > maxChunkLength) + { + throw new InvalidOperationException($"The incoming stream chunk of length {chunk.Length} exceeds the limit of {maxChunkLength}."); + } + + CopyToPipeWriter(chunk, _pipe.Writer); + _pipe.Writer.Advance((int)chunk.Length); + await _pipe.Writer.FlushAsync(_cancellationToken); + + if (_bytesRead == _totalLength) + { + await _pipe.Writer.CompleteAsync(); + } + } + catch (Exception e) + { + await _pipe.Writer.CompleteAsync(e); + return; + } + } + + private static void CopyToPipeWriter(ReadOnlySequence chunk, PipeWriter writer) + { + var pipeBuffer = writer.GetSpan((int)chunk.Length); + chunk.CopyTo(pipeBuffer); + } + + public override bool CanRead => true; + + public override bool CanSeek => false; + + public override bool CanWrite => false; + + public override long Length => _pipeReaderStream.Length; + + public override long Position + { + get => _pipeReaderStream.Position; + set => throw new NotSupportedException(); + } + + public override void Flush() + => throw new NotSupportedException(); + + public override int Read(byte[] buffer, int offset, int count) + => throw new NotSupportedException("Synchronous reads are not supported."); + + public override long Seek(long offset, SeekOrigin origin) + => throw new NotSupportedException(); + + public override void SetLength(long value) + => throw new NotSupportedException(); + + public override void Write(byte[] buffer, int offset, int count) + => throw new NotSupportedException(); + + public override async Task ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) + { + return await _pipeReaderStream.ReadAsync(buffer.AsMemory(offset, count), cancellationToken); + } + + public override async ValueTask ReadAsync(Memory buffer, CancellationToken cancellationToken = default) + { + return await _pipeReaderStream.ReadAsync(buffer, cancellationToken); + } + + protected override void Dispose(bool disposing) + { + if (disposing) + { + Instances.Remove(_streamId); + } + } + } +} diff --git a/src/Components/Server/src/Circuits/RemoteJSRuntime.cs b/src/Components/Server/src/Circuits/RemoteJSRuntime.cs index bce6fcfe78a8..d57d31ae6c5a 100644 --- a/src/Components/Server/src/Circuits/RemoteJSRuntime.cs +++ b/src/Components/Server/src/Circuits/RemoteJSRuntime.cs @@ -2,7 +2,10 @@ // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; +using System.IO; using System.Text.Json; +using System.Threading; +using System.Threading.Tasks; using Microsoft.AspNetCore.SignalR; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; @@ -140,6 +143,9 @@ public void MarkPermanentlyDisconnected() _clientProxy = null; } + protected override async Task ReadJSDataAsStreamAsync(IJSDataReference jsDataReference, long totalLength, long maxBufferSize, CancellationToken cancellationToken) + => await RemoteJSDataStream.CreateRemoteJSDataStreamAsync(this, jsDataReference, totalLength, maxBufferSize, cancellationToken); + public static class Log { private static readonly Action _beginInvokeJS = diff --git a/src/Components/Server/src/ComponentHub.cs b/src/Components/Server/src/ComponentHub.cs index 9887345da19d..3bf3a8613a5f 100644 --- a/src/Components/Server/src/ComponentHub.cs +++ b/src/Components/Server/src/ComponentHub.cs @@ -2,6 +2,7 @@ // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; +using System.Buffers; using System.Runtime.CompilerServices; using System.Threading.Tasks; using Microsoft.AspNetCore.Components.Server.Circuits; @@ -36,7 +37,7 @@ namespace Microsoft.AspNetCore.Components.Server // in error cases. internal sealed class ComponentHub : Hub { - private static readonly object CircuitKey = new object(); + private static readonly object CircuitKey = new(); private readonly IServerComponentDeserializer _serverComponentSerializer; private readonly IDataProtectionProvider _dataProtectionProvider; private readonly ICircuitFactory _circuitFactory; @@ -246,6 +247,10 @@ public async ValueTask OnRenderCompleted(long renderId, string errorMessageOrNul _ = circuitHost.OnRenderCompletedAsync(renderId, errorMessageOrNull); } + [System.Diagnostics.CodeAnalysis.SuppressMessage("Performance", "CA1822:Mark members as static", Justification = "HubReflectionHelper.GetHubMethods is configured to only pickup Instance methods.")] + public Task SupplyJSDataChunk(string streamId, ReadOnlySequence chunk, string error) + => RemoteJSDataStream.SupplyData(streamId, chunk, error); + public async ValueTask OnLocationChanged(string uri, bool intercepted) { var circuitHost = await GetActiveCircuitAsync(); diff --git a/src/Components/Web.JS/dist/Release/blazor.server.js b/src/Components/Web.JS/dist/Release/blazor.server.js index 3a1eb7be8f28..b5b3211f8503 100644 --- a/src/Components/Web.JS/dist/Release/blazor.server.js +++ b/src/Components/Web.JS/dist/Release/blazor.server.js @@ -1 +1 @@ -(()=>{"use strict";var e,t,n;!function(e){window.DotNet=e;const t=[];class n{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 r="__jsObjectId",o={},i={0:new n(window)};i[0]._cachedFunctions.set("import",(e=>("string"==typeof e&&e.startsWith("./")&&(e=document.baseURI+e.substr(2)),import(e))));let s,a=1,c=1,l=null;function h(e){t.push(e)}function u(e){if(e&&"object"==typeof e){i[c]=new n(e);const t={[r]:c};return c++,t}throw new Error(`Cannot create a JSObjectReference from the value '${e}'.`)}function d(e){return e?JSON.parse(e,((e,n)=>t.reduce(((t,n)=>n(e,t)),n))):null}function p(e,t,n,r){const o=g();if(o.invokeDotNetFromJS){const i=JSON.stringify(r,E),s=o.invokeDotNetFromJS(e,t,n,i);return s?d(s):null}throw new Error("The current dispatcher does not support synchronous calls from JS to .NET. Use invokeMethodAsync instead.")}function f(e,t,n,r){if(e&&n)throw new Error(`For instance method calls, assemblyName should be null. Received '${e}'.`);const i=a++,s=new Promise(((e,t)=>{o[i]={resolve:e,reject:t}}));try{const o=JSON.stringify(r,E);g().beginInvokeDotNetFromJS(i,e,t,n,o)}catch(e){m(i,!1,e)}return s}function g(){if(null!==l)return l;throw new Error("No .NET call dispatcher has been set.")}function m(e,t,n){if(!o.hasOwnProperty(e))throw new Error(`There is no pending async call with ID ${e}.`);const r=o[e];delete o[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){let n=i[t];if(n)return n.findFunction(e);throw new Error(`JS object instance with ID ${t} does not exist (has it been disposed?).`)}function v(e){delete i[e]}e.attachDispatcher=function(e){l=e},e.attachReviver=h,e.invokeMethod=function(e,t,...n){return p(e,t,null,n)},e.invokeMethodAsync=function(e,t,...n){return f(e,t,null,n)},e.createJSObjectReference=u,e.disposeJSObjectReference=function(e){const t=e&&e.__jsObjectId;"number"==typeof t&&v(t)},function(e){e[e.Default=0]="Default",e[e.JSObjectReference=1]="JSObjectReference"}(s=e.JSCallResultType||(e.JSCallResultType={})),e.jsCallDispatcher={findJSFunction:w,disposeJSObjectReferenceById:v,invokeJSFromDotNet:(e,t,n,r)=>{const o=_(w(e,r).apply(null,d(t)),n);return null==o?null:JSON.stringify(o,E)},beginInvokeJSFromDotNet:(e,t,n,r,o)=>{const i=new Promise((e=>{e(w(t,o).apply(null,d(n)))}));e&&i.then((t=>g().endInvokeJSFromDotNet(e,!0,JSON.stringify([e,!0,_(t,r)],E))),(t=>g().endInvokeJSFromDotNet(e,!1,JSON.stringify([e,!1,y(t)]))))},endInvokeDotNetFromJS:(e,t,n)=>{const r=t?d(n):new Error(n);m(parseInt(e),t,r)}};class b{constructor(e){this._id=e}invokeMethod(e,...t){return p(null,e,this._id,t)}invokeMethodAsync(e,...t){return f(null,e,this._id,t)}dispose(){f(null,"__Dispose",this._id,null).catch((e=>console.error(e)))}serializeAsArg(){return{__dotNetObject:this._id}}}function _(e,t){switch(t){case s.Default:return e;case s.JSObjectReference:return u(e);default:throw new Error(`Invalid JS call result type '${t}'.`)}}function E(e,t){return t instanceof b?t.serializeAsArg():t}h((function(e,t){return t&&"object"==typeof t&&t.hasOwnProperty("__dotNetObject")?new b(t.__dotNetObject):t})),h((function(e,t){if(t&&"object"==typeof t&&t.hasOwnProperty(r)){const e=t.__jsObjectId,n=i[e];if(n)return n.getWrappedObject();throw new Error(`JS object instance with ID ${e} does not exist (has it been disposed?).`)}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"}(n||(n={}));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}}let o;function i(e,t){if(!o)throw new Error("eventDispatcher not initialized. Call 'setEventDispatcher' to configure it.");o(e,t)}const s=new Map,a=new Map,c={createEventArgs:()=>({})},l=[];function h(e){return s.get(e)}function u(e){const t=s.get(e);return(null==t?void 0:t.browserEventName)||e}function d(e,t){e.forEach((e=>s.set(e,t)))}function p(e){const t=[];for(let n=0;n{return{...f(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}}),d(["focus","blur","focusin","focusout"],c),d(["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};var t}}),d(["contextmenu","click","mouseover","mouseout","mousemove","mousedown","mouseup","dblclick"],{createEventArgs:e=>f(e)}),d(["error"],{createEventArgs:e=>{return{message:(t=e).message,filename:t.filename,lineno:t.lineno,colno:t.colno};var t}}),d(["loadstart","timeout","abort","load","loadend","progress"],{createEventArgs:e=>{return{lengthComputable:(t=e).lengthComputable,loaded:t.loaded,total:t.total};var t}}),d(["touchcancel","touchend","touchmove","touchenter","touchleave","touchstart"],{createEventArgs:e=>{return{detail:(t=e).detail,touches:p(t.touches),targetTouches:p(t.targetTouches),changedTouches:p(t.changedTouches),ctrlKey:t.ctrlKey,shiftKey:t.shiftKey,altKey:t.altKey,metaKey:t.metaKey,type:t.type};var t}}),d(["gotpointercapture","lostpointercapture","pointercancel","pointerdown","pointerenter","pointerleave","pointermove","pointerout","pointerover","pointerup"],{createEventArgs:e=>{return{...f(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}}),d(["wheel","mousewheel"],{createEventArgs:e=>{return{...f(t=e),deltaX:t.deltaX,deltaY:t.deltaY,deltaZ:t.deltaZ,deltaMode:t.deltaMode};var t}}),d(["toggle"],c);const g=["date","datetime-local","month","time","week"],m=E(["abort","blur","change","error","focus","load","loadend","loadstart","mouseenter","mouseleave","progress","reset","scroll","submit","unload","toggle","DOMNodeInsertedIntoDocument","DOMNodeRemovedFromDocument"]),y={submit:!0},w=E(["click","dblclick","mousedown","mousemove","mouseup"]);class v{constructor(e){this.browserRendererId=e,this.afterClickCallbacks=[];const t=++v.nextEventDelegatorId;this.eventsCollectionKey=`_blazorEvents_${t}`,this.eventInfoStore=new b(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,a.get(n));var n;t&&t.forEach((t=>this.dispatchGlobalEventToAllElements(t,e))),"click"===e.type&&this.afterClickCallbacks.forEach((t=>t(e)))}dispatchGlobalEventToAllElements(e,t){let n=t.target,o=null,s=!1;const a=m.hasOwnProperty(e);let c=!1;for(;n;){const d=this.getEventHandlerInfosForElement(n,!1);if(d){const a=d.getHandler(e);if(a&&(l=n,u=t.type,!((l instanceof HTMLButtonElement||l instanceof HTMLInputElement||l instanceof HTMLTextAreaElement||l instanceof HTMLSelectElement)&&w.hasOwnProperty(u)&&l.disabled))){if(!s){const n=h(e);o=(null==n?void 0:n.createEventArgs)?n.createEventArgs(t):{},s=!0}y.hasOwnProperty(t.type)&&t.preventDefault(),i({browserRendererId:this.browserRendererId,eventHandlerId:a.eventHandlerId,eventName:e,eventFieldInfo:r.fromEvent(a.renderingComponentId,t)},o)}d.stopPropagation(e)&&(c=!0),d.preventDefault(e)&&t.preventDefault()}n=a||c?null:n.parentElement}var l,u}getEventHandlerInfosForElement(e,t){return e.hasOwnProperty(this.eventsCollectionKey)?e[this.eventsCollectionKey]:t?e[this.eventsCollectionKey]=new _:null}}v.nextEventDelegatorId=0;class b{constructor(e){this.globalListener=e,this.infosByEventHandlerId={},this.countByEventName={},l.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=u(e),this.countByEventName.hasOwnProperty(e))this.countByEventName[e]++;else{this.countByEventName[e]=1;const t=m.hasOwnProperty(e);document.addEventListener(e,this.globalListener,t)}}update(e,t){if(this.infosByEventHandlerId.hasOwnProperty(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=u(t.eventName);0==--this.countByEventName[n]&&(delete this.countByEventName[n],document.removeEventListener(n,this.globalListener))}return t}handleEventNameAliasAdded(e,t){if(this.countByEventName.hasOwnProperty(e)){const n=this.countByEventName[e];delete this.countByEventName[e],document.removeEventListener(e,this.globalListener),this.addGlobalListener(t),this.countByEventName[t]+=n-1}}}class _{constructor(){this.handlers={},this.preventDefaultFlags=null,this.stopPropagationFlags=null}getHandler(e){return this.handlers.hasOwnProperty(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 E(e){const t={};return e.forEach((e=>{t[e]=!0})),t}const S=H("_blazorLogicalChildren"),C=H("_blazorLogicalParent"),I=H("_blazorLogicalEnd");function k(e,t){if(e.childNodes.length>0&&!t)throw new Error("New logical elements must start empty, or allowExistingContents must be true");return S in e||(e[S]=[]),e}function T(e,t){const n=document.createComment("!");return x(n,e,t),n}function x(e,t,n){const r=e;if(e instanceof Comment&&A(r)&&A(r).length>0)throw new Error("Not implemented: inserting non-empty logical container");if(R(r))throw new Error("Not implemented: moving existing logical children");const o=A(t);if(n0;)D(n,0)}const r=n;r.parentNode.removeChild(r)}function R(e){return e[C]||null}function P(e,t){return A(e)[t]}function U(e){var t=$(e);return"http://www.w3.org/2000/svg"===t.namespaceURI&&"foreignObject"!==t.tagName}function A(e){return e[S]}function N(e,t){const n=A(e);t.forEach((e=>{e.moveRangeStart=n[e.fromSiblingIndex],e.moveRangeEnd=L(e.moveRangeStart)})),t.forEach((t=>{const r=t.moveToBeforeMarker=document.createComment("marker"),o=n[t.toSiblingIndex+1];o?o.parentNode.insertBefore(r,o):M(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 $(e){if(e instanceof Element)return e;if(e instanceof Comment)return e.parentNode;throw new Error("Not a valid logical element")}function B(e){const t=A(R(e));return t[Array.prototype.indexOf.call(t,e)+1]||null}function M(e,t){if(t instanceof Element)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=B(t);n?n.parentNode.insertBefore(e,n):M(e,R(t))}}}function L(e){if(e instanceof Element)return e;const t=B(e);if(t)return t.previousSibling;{const t=R(e);return t instanceof Element?t.lastChild:L(t)}}function H(e){return"function"==typeof Symbol?Symbol():e}function F(e){return`_bl_${e}`}e.attachReviver(((e,t)=>t&&"object"==typeof t&&t.hasOwnProperty("__internalId")&&"string"==typeof t.__internalId?function(e){const t=`[${F(e)}]`;return document.querySelector(t)}(t.__internalId):t));const O="_blazorSelectValue",j=document.createElement("template"),W=document.createElementNS("http://www.w3.org/2000/svg","g"),z={},q="__internal_",J="preventDefault_",K="stopPropagation_";class V{constructor(e){this.childComponentLocations={},this.eventDelegator=new v(e),this.eventDelegator.notifyAfterClick((e=>{if(!ee)return;if(0!==e.button||function(e){return e.ctrlKey||e.shiftKey||e.altKey||e.metaKey}(e))return;if(e.defaultPrevented)return;const t=function(e){const t=!window._blazorDisableComposedPath&&e.composedPath&&e.composedPath();if(t){for(let e=0;ese(!1))))},enableNavigationInterception:function(){ee=!0},navigateTo:oe,getBaseURI:()=>document.baseURI,getLocationHref:()=>location.href};function oe(e,t,n=!1){const r=ce(e);if(!t&&he(r))ie(r,!1,n);else if(t&&location.href===e){const t=e+"?";history.replaceState(null,"",t),location.replace(e)}else n?history.replaceState(null,"",r):location.href=e}function ie(e,t,n=!1){Z=!0,n?history.replaceState(null,"",e):history.pushState(null,"",e),se(t)}async function se(e){ne&&await ne(location.href,e)}let ae;function ce(e){return ae=ae||document.createElement("a"),ae.href=e,ae.href}function le(e,t){return e?e.tagName===t?e:le(e.parentElement,t):null}function he(e){const t=(n=document.baseURI).substr(0,n.lastIndexOf("/")+1);var n;return e.startsWith(t)}const ue={init:function(e,t,n,r=50){const o=pe(t);(o||document.documentElement).style.overflowAnchor="none";const i=new IntersectionObserver((function(r){r.forEach((r=>{var o;if(!r.isIntersecting)return;const i=t.getBoundingClientRect(),s=n.getBoundingClientRect().top-i.bottom,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`});i.observe(t),i.observe(n);const s=c(t),a=c(n);function c(e){const t=new MutationObserver((()=>{i.unobserve(e),i.observe(e)}));return t.observe(e,{attributes:!0}),t}de[e._id]={intersectionObserver:i,mutationObserverBefore:s,mutationObserverAfter:a}},dispose:function(e){const t=de[e._id];t&&(t.intersectionObserver.disconnect(),t.mutationObserverBefore.disconnect(),t.mutationObserverAfter.disconnect(),e.dispose(),delete de[e._id])}},de={};function pe(e){return e?"visible"!==getComputedStyle(e).overflowY?e:pe(e.parentElement):null}const fe={navigateTo:oe,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=a.get(t.browserEventName);n?n.push(e):a.set(t.browserEventName,[e]),l.forEach((n=>n(e,t.browserEventName)))}s.set(e,t)},_internal:{navigationManager:re,domWrapper:{focus:function(e,t){if(!(e instanceof HTMLElement))throw new Error("Unable to focus an invalid element.");e.focus({preventScroll:t})}},Virtualize:ue}};window.Blazor=fe;const ge=[0,2e3,1e4,3e4,null];class me{constructor(e){this._retryDelays=void 0!==e?[...e,null]:ge}nextRetryDelayInMilliseconds(e){return this._retryDelays[e.previousRetryCount]}}class ye extends Error{constructor(e,t){const n=new.target.prototype;super(`${e}: Status code '${t}'`),this.statusCode=t,this.__proto__=n}}class we extends Error{constructor(e="A timeout occurred."){const t=new.target.prototype;super(e),this.__proto__=t}}class ve extends Error{constructor(e="An abort occurred."){const t=new.target.prototype;super(e),this.__proto__=t}}class be{constructor(e,t,n){this.statusCode=e,this.statusText=t,this.content=n}}class _e{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""}}var Ee,Se,Ce,Ie,ke;!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"}(Ee||(Ee={}));class Te extends _e{constructor(e){if(super(),this._logger=e,"undefined"==typeof fetch){const e=require;this._jar=new(e("tough-cookie").CookieJar),this._fetchType=e("node-fetch"),this._fetchType=e("fetch-cookie")(this._fetchType,this._jar),this._abortControllerType=e("abort-controller")}else this._fetchType=fetch.bind(self),this._abortControllerType=AbortController}async send(e){if(e.abortSignal&&e.abortSignal.aborted)throw new ve;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 ve});let r,o=null;if(e.timeout){const r=e.timeout;o=setTimeout((()=>{t.abort(),this._logger.log(Ee.Warning,"Timeout from HTTP request."),n=new we}),r)}try{r=await this._fetchType(e.url,{body:e.content,cache:"no-cache",credentials:!0===e.withCredentials?"include":"same-origin",headers:{"Content-Type":"text/plain;charset=UTF-8","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(Ee.Warning,`Error from HTTP request. ${e}.`),e}finally{o&&clearTimeout(o),e.abortSignal&&(e.abortSignal.onabort=null)}if(!r.ok){const e=await xe(r,"text");throw new ye(e||r.statusText,r.status)}const i=xe(r,e.responseType),s=await i;return new be(r.status,r.statusText,s)}getCookieString(e){return""}}function xe(e,t){let n;switch(t){case"arraybuffer":n=e.arrayBuffer();break;case"text":n=e.text();break;case"blob":case"document":case"json":throw new Error(`${t} is not supported.`);default:n=e.text()}return n}class De extends _e{constructor(e){super(),this._logger=e}send(e){return e.abortSignal&&e.abortSignal.aborted?Promise.reject(new ve):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"),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 ve)}),e.timeout&&(r.timeout=e.timeout),r.onload=()=>{e.abortSignal&&(e.abortSignal.onabort=null),r.status>=200&&r.status<300?t(new be(r.status,r.statusText,r.response||r.responseText)):n(new ye(r.response||r.responseText||r.statusText,r.status))},r.onerror=()=>{this._logger.log(Ee.Warning,`Error from HTTP request. ${r.status}: ${r.statusText}.`),n(new ye(r.statusText,r.status))},r.ontimeout=()=>{this._logger.log(Ee.Warning,"Timeout from HTTP request."),n(new we)},r.send(e.content||"")})):Promise.reject(new Error("No url defined.")):Promise.reject(new Error("No method defined."))}}class Re extends _e{constructor(e){if(super(),"undefined"!=typeof fetch)this._httpClient=new Te(e);else{if("undefined"==typeof XMLHttpRequest)throw new Error("No usable HttpClient found.");this._httpClient=new De(e)}}send(e){return e.abortSignal&&e.abortSignal.aborted?Promise.reject(new ve):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)}}class Pe{}Pe.Authorization="Authorization",Pe.Cookie="Cookie",function(e){e[e.None=0]="None",e[e.WebSockets=1]="WebSockets",e[e.ServerSentEvents=2]="ServerSentEvents",e[e.LongPolling=4]="LongPolling"}(Se||(Se={})),function(e){e[e.Text=1]="Text",e[e.Binary=2]="Binary"}(Ce||(Ce={}));class Ue{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 Ae{constructor(){}log(e,t){}}Ae.instance=new Ae;class Ne{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 $e{static get isBrowser(){return"object"==typeof window}static get isWebWorker(){return"object"==typeof self&&"importScripts"in self}static get isNode(){return!this.isBrowser&&!this.isWebWorker}}function Be(e,t){let n="";return Me(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 Me(e){return e&&"undefined"!=typeof ArrayBuffer&&(e instanceof ArrayBuffer||e.constructor&&"ArrayBuffer"===e.constructor.name)}async function Le(e,t,n,r,o,i,s,a,c){let l={};if(o){const e=await o();e&&(l={Authorization:`Bearer ${e}`})}const[h,u]=Oe();l[h]=u,e.log(Ee.Trace,`(${t} transport) sending data. ${Be(i,s)}.`);const d=Me(i)?"arraybuffer":"text",p=await n.post(r,{content:i,headers:{...l,...c},responseType:d,withCredentials:a});e.log(Ee.Trace,`(${t} transport) request complete. Response status: ${p.statusCode}.`)}class He{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 Fe{constructor(e){this._minLevel=e,this.out=console}log(e,t){if(e>=this._minLevel){const n=`[${(new Date).toISOString()}] ${Ee[e]}: ${t}`;switch(e){case Ee.Critical:case Ee.Error:this.out.error(n);break;case Ee.Warning:this.out.warn(n);break;case Ee.Information:this.out.info(n);break;default:this.out.log(n)}}}}function Oe(){let e="X-SignalR-User-Agent";return $e.isNode&&(e="User-Agent"),[e,je("0.0.0-DEV_BUILD",We(),$e.isNode?"NodeJS":"Browser",ze())]}function je(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 We(){if(!$e.isNode)return"";switch(process.platform){case"win32":return"Windows NT";case"darwin":return"macOS";case"linux":return"Linux";default:return process.platform}}function ze(){if($e.isNode)return process.versions.node}class qe{constructor(e,t,n,r,o,i){this._httpClient=e,this._accessTokenFactory=t,this._logger=n,this._pollAbort=new Ue,this._logMessageContent=r,this._withCredentials=o,this._headers=i,this._running=!1,this.onreceive=null,this.onclose=null}get pollAborted(){return this._pollAbort.aborted}async connect(e,t){if(Ne.isRequired(e,"url"),Ne.isRequired(t,"transferFormat"),Ne.isIn(t,Ce,"transferFormat"),this._url=e,this._logger.log(Ee.Trace,"(LongPolling transport) Connecting."),t===Ce.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]=Oe(),o={[n]:r,...this._headers},i={abortSignal:this._pollAbort.signal,headers:o,timeout:1e5,withCredentials:this._withCredentials};t===Ce.Binary&&(i.responseType="arraybuffer");const s=await this._getAccessToken();this._updateHeaderToken(i,s);const a=`${e}&_=${Date.now()}`;this._logger.log(Ee.Trace,`(LongPolling transport) polling: ${a}.`);const c=await this._httpClient.get(a,i);200!==c.statusCode?(this._logger.log(Ee.Error,`(LongPolling transport) Unexpected response code: ${c.statusCode}.`),this._closeError=new ye(c.statusText||"",c.statusCode),this._running=!1):this._running=!0,this._receiving=this._poll(this._url,i)}async _getAccessToken(){return this._accessTokenFactory?await this._accessTokenFactory():null}_updateHeaderToken(e,t){e.headers||(e.headers={}),t?e.headers[Pe.Authorization]=`Bearer ${t}`:e.headers[Pe.Authorization]&&delete e.headers[Pe.Authorization]}async _poll(e,t){try{for(;this._running;){const n=await this._getAccessToken();this._updateHeaderToken(t,n);try{const n=`${e}&_=${Date.now()}`;this._logger.log(Ee.Trace,`(LongPolling transport) polling: ${n}.`);const r=await this._httpClient.get(n,t);204===r.statusCode?(this._logger.log(Ee.Information,"(LongPolling transport) Poll terminated by server."),this._running=!1):200!==r.statusCode?(this._logger.log(Ee.Error,`(LongPolling transport) Unexpected response code: ${r.statusCode}.`),this._closeError=new ye(r.statusText||"",r.statusCode),this._running=!1):r.content?(this._logger.log(Ee.Trace,`(LongPolling transport) data received. ${Be(r.content,this._logMessageContent)}.`),this.onreceive&&this.onreceive(r.content)):this._logger.log(Ee.Trace,"(LongPolling transport) Poll timed out, reissuing.")}catch(e){this._running?e instanceof we?this._logger.log(Ee.Trace,"(LongPolling transport) Poll timed out, reissuing."):(this._closeError=e,this._running=!1):this._logger.log(Ee.Trace,`(LongPolling transport) Poll errored after shutdown: ${e.message}`)}}}finally{this._logger.log(Ee.Trace,"(LongPolling transport) Polling complete."),this.pollAborted||this._raiseOnClose()}}async send(e){return this._running?Le(this._logger,"LongPolling",this._httpClient,this._url,this._accessTokenFactory,e,this._logMessageContent,this._withCredentials,this._headers):Promise.reject(new Error("Cannot send until the transport is connected"))}async stop(){this._logger.log(Ee.Trace,"(LongPolling transport) Stopping polling."),this._running=!1,this._pollAbort.abort();try{await this._receiving,this._logger.log(Ee.Trace,`(LongPolling transport) sending DELETE request to ${this._url}.`);const e={},[t,n]=Oe();e[t]=n;const r={headers:{...e,...this._headers},withCredentials:this._withCredentials},o=await this._getAccessToken();this._updateHeaderToken(r,o),await this._httpClient.delete(this._url,r),this._logger.log(Ee.Trace,"(LongPolling transport) DELETE request sent.")}finally{this._logger.log(Ee.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(Ee.Trace,e),this.onclose(this._closeError)}}}class Je{constructor(e,t,n,r,o,i,s){this._httpClient=e,this._accessTokenFactory=t,this._logger=n,this._logMessageContent=r,this._withCredentials=i,this._eventSourceConstructor=o,this._headers=s,this.onreceive=null,this.onclose=null}async connect(e,t){if(Ne.isRequired(e,"url"),Ne.isRequired(t,"transferFormat"),Ne.isIn(t,Ce,"transferFormat"),this._logger.log(Ee.Trace,"(SSE transport) Connecting."),this._url=e,this._accessTokenFactory){const t=await this._accessTokenFactory();t&&(e+=(e.indexOf("?")<0?"?":"&")+`access_token=${encodeURIComponent(t)}`)}return new Promise(((n,r)=>{let o,i=!1;if(t===Ce.Text){if($e.isBrowser||$e.isWebWorker)o=new this._eventSourceConstructor(e,{withCredentials:this._withCredentials});else{const t=this._httpClient.getCookieString(e),n={};n.Cookie=t;const[r,i]=Oe();n[r]=i,o=new this._eventSourceConstructor(e,{withCredentials:this._withCredentials,headers:{...n,...this._headers}})}try{o.onmessage=e=>{if(this.onreceive)try{this._logger.log(Ee.Trace,`(SSE transport) data received. ${Be(e.data,this._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(Ee.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?Le(this._logger,"SSE",this._httpClient,this._url,this._accessTokenFactory,e,this._logMessageContent,this._withCredentials,this._headers):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 Ke{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){if(Ne.isRequired(e,"url"),Ne.isRequired(t,"transferFormat"),Ne.isIn(t,Ce,"transferFormat"),this._logger.log(Ee.Trace,"(WebSockets transport) Connecting."),this._accessTokenFactory){const t=await this._accessTokenFactory();t&&(e+=(e.indexOf("?")<0?"?":"&")+`access_token=${encodeURIComponent(t)}`)}return new Promise(((n,r)=>{let o;e=e.replace(/^http/,"ws"),this._httpClient.getCookieString(e);let i=!1;o||(o=new this._webSocketConstructor(e)),t===Ce.Binary&&(o.binaryType="arraybuffer"),o.onopen=t=>{this._logger.log(Ee.Information,`WebSocket connected to ${e}.`),this._webSocket=o,i=!0,n()},o.onerror=e=>{let t=null;t="undefined"!=typeof ErrorEvent&&e instanceof ErrorEvent?e.error:"There was an error with the transport",this._logger.log(Ee.Information,`(WebSockets transport) ${t}.`)},o.onmessage=e=>{if(this._logger.log(Ee.Trace,`(WebSockets transport) data received. ${Be(e.data,this._logMessageContent)}.`),this.onreceive)try{this.onreceive(e.data)}catch(e){return void this._close(e)}},o.onclose=e=>{if(i)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(Ee.Trace,`(WebSockets transport) sending data. ${Be(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(Ee.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 Ve{constructor(e,t={}){var n;if(this._stopPromiseResolver=()=>{},this.features={},this._negotiateVersion=1,Ne.isRequired(e,"url"),this._logger=void 0===(n=t.logger)?new Fe(Ee.Information):null===n?Ae.instance:void 0!==n.log?n:new Fe(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,"undefined"==typeof WebSocket||t.WebSocket||(t.WebSocket=WebSocket),"undefined"==typeof EventSource||t.EventSource||(t.EventSource=EventSource),this._httpClient=t.httpClient||new Re(this._logger),this._connectionState="Disconnected",this._connectionStarted=!1,this._options=t,this.onreceive=null,this.onclose=null}async start(e){if(e=e||Ce.Binary,Ne.isIn(e,Ce,"transferFormat"),this._logger.log(Ee.Debug,`Starting connection with transfer format '${Ce[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(Ee.Error,e),await this._stopPromise,Promise.reject(new Error(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(Ee.Error,e),Promise.reject(new Error(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 Xe(this.transport)),this._sendQueue.send(e))}async stop(e){return"Disconnected"===this._connectionState?(this._logger.log(Ee.Debug,`Call to HttpConnection.stop(${e}) ignored because the connection is already in the disconnected state.`),Promise.resolve()):"Disconnecting"===this._connectionState?(this._logger.log(Ee.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(Ee.Error,`HttpConnection.transport.stop() threw error '${e}'.`),this._stopConnection()}this.transport=void 0}else this._logger.log(Ee.Debug,"HttpConnection.transport is undefined in HttpConnection.stop() because start() failed.")}async _startInternal(e){let t=this.baseUrl;this._accessTokenFactory=this._options.accessTokenFactory;try{if(this._options.skipNegotiation){if(this._options.transport!==Se.WebSockets)throw new Error("Negotiation can only be skipped when using the WebSocket transport directly.");this.transport=this._constructTransport(Se.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 Error("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}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 qe&&(this.features.inherentKeepAlive=!0),"Connecting"===this._connectionState&&(this._logger.log(Ee.Debug,"The HttpConnection connected successfully."),this._connectionState="Connected")}catch(e){return this._logger.log(Ee.Error,"Failed to start the connection: "+e),this._connectionState="Disconnected",this.transport=void 0,this._stopPromiseResolver(),Promise.reject(e)}}async _getNegotiationResponse(e){const t={};if(this._accessTokenFactory){const e=await this._accessTokenFactory();e&&(t[Pe.Authorization]=`Bearer ${e}`)}const[n,r]=Oe();t[n]=r;const o=this._resolveNegotiateUrl(e);this._logger.log(Ee.Debug,`Sending negotiation request: ${o}.`);try{const e=await this._httpClient.post(o,{content:"",headers:{...t,...this._options.headers},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 ye&&404===e.statusCode&&(t+=" Either this is not a SignalR endpoint or there is a proxy blocking the connection."),this._logger.log(Ee.Error,t),Promise.reject(new Error(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(Ee.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: ${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(Ee.Error,`Failed to start the transport '${n.transport}': ${e}`),a=void 0,i.push(`${n.transport} failed: ${e}`),"Connecting"!==this._connectionState){const e="Failed to select transport before stop() was called.";return this._logger.log(Ee.Debug,e),Promise.reject(new Error(e))}}}}return i.length>0?Promise.reject(new Error(`Unable to connect to the server with any of the available transports. ${i.join(" ")}`)):Promise.reject(new Error("None of the transports supported by the client are supported by the server."))}_constructTransport(e){switch(e){case Se.WebSockets:if(!this._options.WebSocket)throw new Error("'WebSocket' is not supported in your environment.");return new Ke(this._httpClient,this._accessTokenFactory,this._logger,this._options.logMessageContent||!1,this._options.WebSocket,this._options.headers||{});case Se.ServerSentEvents:if(!this._options.EventSource)throw new Error("'EventSource' is not supported in your environment.");return new Je(this._httpClient,this._accessTokenFactory,this._logger,this._options.logMessageContent||!1,this._options.EventSource,this._options.withCredentials,this._options.headers||{});case Se.LongPolling:return new qe(this._httpClient,this._accessTokenFactory,this._logger,this._options.logMessageContent||!1,this._options.withCredentials,this._options.headers||{});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=Se[e.transport];if(null==r)return this._logger.log(Ee.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(Ee.Debug,`Skipping transport '${Se[r]}' because it was disabled by the client.`),new Error(`'${Se[r]}' is disabled by the client.`);if(!(e.transferFormats.map((e=>Ce[e])).indexOf(n)>=0))return this._logger.log(Ee.Debug,`Skipping transport '${Se[r]}' because it does not support the requested transfer format '${Ce[n]}'.`),new Error(`'${Se[r]}' does not support ${Ce[n]}.`);if(r===Se.WebSockets&&!this._options.WebSocket||r===Se.ServerSentEvents&&!this._options.EventSource)return this._logger.log(Ee.Debug,`Skipping transport '${Se[r]}' because it is not supported in your environment.'`),new Error(`'${Se[r]}' is not supported in your environment.`);this._logger.log(Ee.Debug,`Selecting transport '${Se[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(Ee.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(Ee.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(Ee.Error,`Connection disconnected with error '${e}'.`):this._logger.log(Ee.Information,"Connection disconnected."),this._sendQueue&&(this._sendQueue.stop().catch((e=>{this._logger.log(Ee.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(Ee.Error,`HttpConnection.onclose(${e}) threw error '${t}'.`)}}}else this._logger.log(Ee.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(!$e.isBrowser||!window.document)throw new Error(`Cannot resolve '${e}'.`);const t=window.document.createElement("a");return t.href=e,this._logger.log(Ee.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 Xe{constructor(e){this._transport=e,this._buffer=[],this._executing=!0,this._sendBufferedData=new Ye,this._transportResult=new Ye,this._sendLoopPromise=this._sendLoop()}send(e){return this._bufferData(e),this._transportResult||(this._transportResult=new Ye),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 Ye;const e=this._transportResult;this._transportResult=void 0;const t="string"==typeof this._buffer[0]?this._buffer.join(""):Xe._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 Ye{constructor(){this.promise=new Promise(((e,t)=>[this._resolver,this._rejecter]=[e,t]))}resolve(){this._resolver()}reject(e){this._rejecter(e)}}class Ge{static write(e){return`${e}${Ge.RecordSeparator}`}static parse(e){if(e[e.length-1]!==Ge.RecordSeparator)throw new Error("Message is incomplete.");const t=e.split(Ge.RecordSeparator);return t.pop(),t}}Ge.RecordSeparatorCode=30,Ge.RecordSeparator=String.fromCharCode(Ge.RecordSeparatorCode);class Qe{writeHandshakeRequest(e){return Ge.write(JSON.stringify(e))}parseHandshakeResponse(e){let t,n;if(Me(e)){const r=new Uint8Array(e),o=r.indexOf(Ge.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(Ge.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=Ge.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"}(Ie||(Ie={}));class Ze{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 He(this,e)}}!function(e){e.Disconnected="Disconnected",e.Connecting="Connecting",e.Connected="Connected",e.Disconnecting="Disconnecting",e.Reconnecting="Reconnecting"}(ke||(ke={}));class et{constructor(e,t,n,r){this._nextKeepAlive=0,Ne.isRequired(e,"connection"),Ne.isRequired(t,"logger"),Ne.isRequired(n,"protocol"),this.serverTimeoutInMilliseconds=3e4,this.keepAliveIntervalInMilliseconds=15e3,this._logger=t,this._protocol=n,this.connection=e,this._reconnectPolicy=r,this._handshakeProtocol=new Qe,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=ke.Disconnected,this._connectionStarted=!1,this._cachedPingMessage=this._protocol.writeMessage({type:Ie.Ping})}static create(e,t,n,r){return new et(e,t,n,r)}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!==ke.Disconnected&&this._connectionState!==ke.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!==ke.Disconnected)return Promise.reject(new Error("Cannot start a HubConnection that is not in the 'Disconnected' state."));this._connectionState=ke.Connecting,this._logger.log(Ee.Debug,"Starting HubConnection.");try{await this._startInternal(),this._connectionState=ke.Connected,this._connectionStarted=!0,this._logger.log(Ee.Debug,"HubConnection connected successfully.")}catch(e){return this._connectionState=ke.Disconnected,this._logger.log(Ee.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(Ee.Debug,"Sending handshake request."),await this._sendMessage(this._handshakeProtocol.writeHandshakeRequest(t)),this._logger.log(Ee.Information,`Using HubProtocol '${this._protocol.name}'.`),this._cleanupTimeout(),this._resetTimeoutPeriod(),this._resetKeepAliveInterval(),await e,this._stopDuringStartError)throw this._stopDuringStartError}catch(e){throw this._logger.log(Ee.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){return this._connectionState===ke.Disconnected?(this._logger.log(Ee.Debug,`Call to HubConnection.stop(${e}) ignored because it is already in the disconnected state.`),Promise.resolve()):this._connectionState===ke.Disconnecting?(this._logger.log(Ee.Debug,`Call to HttpConnection.stop(${e}) ignored because the connection is already in the disconnecting state.`),this._stopPromise):(this._connectionState=ke.Disconnecting,this._logger.log(Ee.Debug,"Stopping HubConnection."),this._reconnectDelayHandle?(this._logger.log(Ee.Debug,"Connection stopped during reconnect delay. Done reconnecting."),clearTimeout(this._reconnectDelayHandle),this._reconnectDelayHandle=void 0,this._completeClose(),Promise.resolve()):(this._cleanupTimeout(),this._cleanupPingTimer(),this._stopDuringStartError=e||new Error("The connection was stopped before the hub handshake could complete."),this.connection.stop(e)))}stream(e,...t){const[n,r]=this._replaceStreamingParams(t),o=this._createStreamInvocation(e,t,r);let i;const s=new Ze;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===Ie.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===Ie.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 Ie.Invocation:this._invokeClientMethod(e);break;case Ie.StreamItem:case Ie.Completion:{const t=this._callbacks[e.invocationId];t&&(e.type===Ie.Completion&&delete this._callbacks[e.invocationId],t(e));break}case Ie.Ping:break;case Ie.Close:{this._logger.log(Ee.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(Ee.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(Ee.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(Ee.Error,e);const n=new Error(e);throw this._handshakeRejecter(n),n}return this._logger.log(Ee.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===ke.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."))}_invokeClientMethod(e){const t=this._methods[e.target.toLowerCase()];if(t){try{t.forEach((t=>t.apply(this,e.arguments)))}catch(t){this._logger.log(Ee.Error,`A callback for the method ${e.target.toLowerCase()} threw error '${t}'.`)}if(e.invocationId){const e="Server requested a response, which is not supported in this version of the client.";this._logger.log(Ee.Error,e),this._stopPromise=this._stopInternal(new Error(e))}}else this._logger.log(Ee.Warning,`No client method with the name '${e.target}' found.`)}_connectionClosed(e){this._logger.log(Ee.Debug,`HubConnection.connectionClosed(${e}) called while in state ${this._connectionState}.`),this._stopDuringStartError=this._stopDuringStartError||e||new Error("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===ke.Disconnecting?this._completeClose(e):this._connectionState===ke.Connected&&this._reconnectPolicy?this._reconnect(e):this._connectionState===ke.Connected&&this._completeClose(e)}_completeClose(e){if(this._connectionStarted){this._connectionState=ke.Disconnected,this._connectionStarted=!1;try{this._closedCallbacks.forEach((t=>t.apply(this,[e])))}catch(t){this._logger.log(Ee.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(Ee.Debug,"Connection not reconnecting because the IRetryPolicy returned null on the first reconnect attempt."),void this._completeClose(e);if(this._connectionState=ke.Reconnecting,e?this._logger.log(Ee.Information,`Connection reconnecting because of error '${e}'.`):this._logger.log(Ee.Information,"Connection reconnecting."),0!==this._reconnectingCallbacks.length){try{this._reconnectingCallbacks.forEach((t=>t.apply(this,[e])))}catch(t){this._logger.log(Ee.Error,`An onreconnecting callback called with error '${e}' threw error '${t}'.`)}if(this._connectionState!==ke.Reconnecting)return void this._logger.log(Ee.Debug,"Connection left the reconnecting state in onreconnecting callback. Done reconnecting.")}for(;null!==o;){if(this._logger.log(Ee.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!==ke.Reconnecting)return void this._logger.log(Ee.Debug,"Connection left the reconnecting state during reconnect delay. Done reconnecting.");try{if(await this._startInternal(),this._connectionState=ke.Connected,this._logger.log(Ee.Information,"HubConnection reconnected successfully."),0!==this._reconnectedCallbacks.length)try{this._reconnectedCallbacks.forEach((e=>e.apply(this,[this.connection.connectionId])))}catch(e){this._logger.log(Ee.Error,`An onreconnected callback called with connectionId '${this.connection.connectionId}; threw error '${e}'.`)}return}catch(e){if(this._logger.log(Ee.Information,`Reconnect attempt failed because of error '${e}'.`),this._connectionState!==ke.Reconnecting)return this._logger.log(Ee.Debug,`Connection moved to the '${this._connectionState}' from the reconnecting state during reconnect attempt. Done reconnecting.`),void(this._connectionState===ke.Disconnecting&&this._completeClose());r=e instanceof Error?e:new Error(e.toString()),o=this._getNextRetryDelay(n++,Date.now()-t,r)}}this._logger.log(Ee.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(Ee.Error,`IRetryPolicy.nextRetryDelayInMilliseconds(${e}, ${t}) threw error '${n}'.`),null}}_cancelCallbacksWithError(e){const t=this._callbacks;this._callbacks={},Object.keys(t).forEach((n=>{(0,t[n])(null,e)}))}_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:Ie.Invocation}:{arguments:t,target:e,type:Ie.Invocation};{const n=this._invocationId;return this._invocationId++,0!==r.length?{arguments:t,invocationId:n.toString(),streamIds:r,target:e,type:Ie.Invocation}:{arguments:t,invocationId:n.toString(),target:e,type:Ie.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 ut=ot?new TextDecoder:null,dt=ot?"undefined"!=typeof process&&"force"!==process.env.TEXT_DECODER?200:0:it,pt=function(e,t){this.type=e,this.data=t};function ft(e,t,n){var r=Math.floor(n/4294967296),o=n;e.setUint32(t,r),e.setUint32(t+4,o)}function gt(e,t){return 4294967296*e.getInt32(t)+e.getUint32(t+4)}var mt={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),ft(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:gt(t,4),nsec:t.getUint32(0)};default:throw new Error("Unrecognized data size for timestamp: "+e.length)}}(e);return new Date(1e3*t.sec+t.nsec/1e6)}},yt=function(){function e(){this.builtInEncoders=[],this.builtInDecoders=[],this.encoders=[],this.decoders=[],this.register(mt)}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 "+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: "+e+" bytes in UTF-8");this.writeU8(219),this.writeU32(e)}},e.prototype.encodeString=function(e){if(e.length>ct){var t=st(e);this.ensureBufferSizeToWrite(5+t),this.writeStringHeader(t),lt(e,this.bytes,this.pos),this.pos+=t}else t=st(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: "+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: "+t);this.writeU8(198),this.writeU32(t)}var n=wt(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: "+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=ht(e,t,n),i=Uint8Array.prototype.slice.call(e,t,t+n);return this.store(i,o),o},e}(),St=(_t=function(e,t){return(_t=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])})(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}_t(e,t),e.prototype=null===t?Object.create(t):(n.prototype=t.prototype,new n)}),Ct=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]1||a(e,t)}))})}function a(e,t){try{(n=o[e](t)).value instanceof kt?Promise.resolve(n.value.v).then(c,l):h(i[0][2],n)}catch(e){h(i[0][3],e)}var n}function c(e){a("next",e)}function l(e){a("throw",e)}function h(e,t){e(t),i.shift(),i.length&&a(i[0][0],i[0][1])}},xt=new DataView(new ArrayBuffer(0)),Dt=new Uint8Array(xt.buffer),Rt=function(){try{xt.getInt8(0)}catch(e){return e.constructor}throw new Error("never reached")}(),Pt=new Rt("Insufficient data"),Ut=4294967295,At=new Et,Nt=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 St(t,e),t}(Error),$t=function(){function e(e,t,n,r,o,i,s,a){void 0===e&&(e=yt.defaultCodec),void 0===t&&(t=void 0),void 0===n&&(n=Ut),void 0===r&&(r=Ut),void 0===o&&(o=Ut),void 0===i&&(i=Ut),void 0===s&&(s=Ut),void 0===a&&(a=At),this.extensionCodec=e,this.context=t,this.maxStrLength=n,this.maxBinLength=r,this.maxArrayLength=o,this.maxMapLength=i,this.maxExtLength=s,this.keyDecoder=a,this.totalPos=0,this.pos=0,this.view=xt,this.bytes=Dt,this.headByte=-1,this.stack=[]}return e.prototype.reinitializeState=function(){this.totalPos=0,this.headByte=-1,this.stack.length=0},e.prototype.setBuffer=function(e){this.bytes=wt(e),this.view=function(e){if(e instanceof ArrayBuffer)return new DataView(e);var t=wt(e);return new DataView(t.buffer,t.byteOffset,t.byteLength)}(this.bytes),this.pos=0},e.prototype.appendBuffer=function(e){if(-1!==this.headByte||this.hasRemaining()){var t=this.bytes.subarray(this.pos),n=wt(e),r=new Uint8Array(t.length+n.length);r.set(t),r.set(n,t.length),this.setBuffer(r)}else this.setBuffer(e)},e.prototype.hasRemaining=function(e){return void 0===e&&(e=1),this.view.byteLength-this.pos>=e},e.prototype.createExtraByteError=function(e){var t=this.view,n=this.pos;return new RangeError("Extra "+(t.byteLength-n)+" of "+t.byteLength+" byte(s) found at buffer["+e+"]")},e.prototype.decode=function(e){this.reinitializeState(),this.setBuffer(e);var t=this.doDecodeSync();if(this.hasRemaining())throw this.createExtraByteError(this.pos);return t},e.prototype.decodeMulti=function(e){return Ct(this,(function(t){switch(t.label){case 0:this.reinitializeState(),this.setBuffer(e),t.label=1;case 1:return this.hasRemaining()?[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,u,d;return Ct(this,(function(p){switch(p.label){case 0:i=!1,p.label=1;case 1:p.trys.push([1,6,7,12]),t=It(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 Rt))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())throw this.createExtraByteError(this.totalPos);return[2,s]}throw h=(l=this).headByte,u=l.pos,d=l.totalPos,new RangeError("Insufficient data in parsing "+bt(h)+" at "+d+" ("+u+" 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 Tt(this,arguments,(function(){var n,r,o,i,s,a,c,l,h;return Ct(this,(function(u){switch(u.label){case 0:n=t,r=-1,u.label=1;case 1:u.trys.push([1,13,14,19]),o=It(e),u.label=2;case 2:return[4,kt(o.next())];case 3:if((i=u.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()),u.label=4;case 4:u.trys.push([4,9,,10]),u.label=5;case 5:return[4,kt(this.doDecodeSync())];case 6:return[4,u.sent()];case 7:return u.sent(),0==--r?[3,8]:[3,5];case 8:return[3,10];case 9:if(!((a=u.sent())instanceof Rt))throw a;return[3,10];case 10:this.totalPos+=this.pos,u.label=11;case 11:return[3,2];case 12:return[3,19];case 13:return c=u.sent(),l={error:c},[3,19];case 14:return u.trys.push([14,,17,18]),i&&!i.done&&(h=o.return)?[4,kt(h.call(o))]:[3,16];case 15:u.sent(),u.label=16;case 16:return[3,18];case 17:if(l)throw l.error;return[7];case 18:return[7];case 19:return[2]}}))}))},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 Nt("Unrecognized type byte: "+bt(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 Nt("The type of key must be string or number but "+typeof t);if("__proto__"===t)throw new Nt("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 Nt("Unrecognized array type byte: "+bt(e))}},e.prototype.pushMapState=function(e){if(e>this.maxMapLength)throw new Nt("Max length exceeded: map length ("+e+") > maxMapLengthLength ("+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 Nt("Max length exceeded: array length ("+e+") > maxArrayLength ("+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 Nt("Max length exceeded: UTF-8 byte length ("+e+") > maxStrLength ("+this.maxStrLength+")");if(this.bytes.byteLengthdt?function(e,t,n){var r=e.subarray(t,t+n);return ut.decode(r)}(this.bytes,o,e):ht(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 Nt("Max length exceeded: bin length ("+e+") > maxBinLength ("+this.maxBinLength+")");if(!this.hasRemaining(e+t))throw Pt;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 Nt("Max length exceeded: ext length ("+e+") > maxExtLength ("+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=gt(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 Bt{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 Mt=new Uint8Array([145,Ie.Ping]);class Lt{constructor(e){this.name="messagepack",this.version=1,this.transferFormat=Ce.Binary,this._errorResult=1,this._voidResult=2,this._nonVoidResult=3,e=e||{},this._encoder=new vt(e.extensionCodec,e.context,e.maxDepth,e.initialBufferSize,e.sortKeys,e.forceFloat32,e.ignoreUndefined,e.forceIntegerToFloat),this._decoder=new $t(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=Ae.instance);const r=Bt.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 Ie.Invocation:return this._writeInvocation(e);case Ie.StreamInvocation:return this._writeStreamInvocation(e);case Ie.StreamItem:return this._writeStreamItem(e);case Ie.Completion:return this._writeCompletion(e);case Ie.Ping:return Bt.write(Mt);case Ie.CancelInvocation:return this._writeCancelInvocation(e);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 Ie.Invocation:return this._createInvocationMessage(this._readHeaders(n),n);case Ie.StreamItem:return this._createStreamItemMessage(this._readHeaders(n),n);case Ie.Completion:return this._createCompletionMessage(this._readHeaders(n),n);case Ie.Ping:return this._createPingMessage(n);case Ie.Close:return this._createCloseMessage(n);default:return t.log(Ee.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:Ie.Close}}_createPingMessage(e){if(e.length<1)throw new Error("Invalid payload for Ping message.");return{type:Ie.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:Ie.Invocation}:{arguments:t[4],headers:e,streamIds:[],target:t[3],type:Ie.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:Ie.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:Ie.Completion}}_writeInvocation(e){let t;return t=e.streamIds?this._encoder.encode([Ie.Invocation,e.headers||{},e.invocationId||null,e.target,e.arguments,e.streamIds]):this._encoder.encode([Ie.Invocation,e.headers||{},e.invocationId||null,e.target,e.arguments]),Bt.write(t.slice())}_writeStreamInvocation(e){let t;return t=e.streamIds?this._encoder.encode([Ie.StreamInvocation,e.headers||{},e.invocationId,e.target,e.arguments,e.streamIds]):this._encoder.encode([Ie.StreamInvocation,e.headers||{},e.invocationId,e.target,e.arguments]),Bt.write(t.slice())}_writeStreamItem(e){const t=this._encoder.encode([Ie.StreamItem,e.headers||{},e.invocationId,e.item]);return Bt.write(t.slice())}_writeCompletion(e){const t=e.error?this._errorResult:e.result?this._nonVoidResult:this._voidResult;let n;switch(t){case this._errorResult:n=this._encoder.encode([Ie.Completion,e.headers||{},e.invocationId,t,e.error]);break;case this._voidResult:n=this._encoder.encode([Ie.Completion,e.headers||{},e.invocationId,t]);break;case this._nonVoidResult:n=this._encoder.encode([Ie.Completion,e.headers||{},e.invocationId,t,e.result])}return Bt.write(n.slice())}_writeCancelInvocation(e){const t=this._encoder.encode([Ie.CancelInvocation,e.headers||{},e.invocationId]);return Bt.write(t.slice())}_readHeaders(e){const t=e[1];if("object"!=typeof t)throw new Error("Invalid headers.");return t}}let Ht=!1;const Ft="function"==typeof TextDecoder?new TextDecoder("utf-8"):null,Ot=Ft?Ft.decode.bind(Ft):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("")},jt=Math.pow(2,32),Wt=Math.pow(2,21)-1;function zt(e,t){return e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24}function qt(e,t){return e[t]+(e[t+1]<<8)+(e[t+2]<<16)+(e[t+3]<<24>>>0)}function Jt(e,t){const n=qt(e,t+4);if(n>Wt)throw new Error(`Cannot read uint64 with high order part ${n}, because the result would exceed Number.MAX_SAFE_INTEGER.`);return n*jt+qt(e,t)}class Kt{constructor(e){this.batchData=e;const t=new Gt(e);this.arrayRangeReader=new Qt(e),this.arrayBuilderSegmentReader=new Zt(e),this.diffReader=new Vt(e),this.editReader=new Xt(e,t),this.frameReader=new Yt(e,t)}updatedComponents(){return zt(this.batchData,this.batchData.length-20)}referenceFrames(){return zt(this.batchData,this.batchData.length-16)}disposedComponentIds(){return zt(this.batchData,this.batchData.length-12)}disposedEventHandlerIds(){return zt(this.batchData,this.batchData.length-8)}updatedComponentsEntry(e,t){const n=e+4*t;return zt(this.batchData,n)}referenceFramesEntry(e,t){return e+20*t}disposedComponentIdsEntry(e,t){const n=e+4*t;return zt(this.batchData,n)}disposedEventHandlerIdsEntry(e,t){const n=e+8*t;return Jt(this.batchData,n)}}class Vt{constructor(e){this.batchDataUint8=e}componentId(e){return zt(this.batchDataUint8,e)}edits(e){return e+4}editsEntry(e,t){return e+16*t}}class Xt{constructor(e,t){this.batchDataUint8=e,this.stringReader=t}editType(e){return zt(this.batchDataUint8,e)}siblingIndex(e){return zt(this.batchDataUint8,e+4)}newTreeIndex(e){return zt(this.batchDataUint8,e+8)}moveToSiblingIndex(e){return zt(this.batchDataUint8,e+8)}removedAttributeName(e){const t=zt(this.batchDataUint8,e+12);return this.stringReader.readString(t)}}class Yt{constructor(e,t){this.batchDataUint8=e,this.stringReader=t}frameType(e){return zt(this.batchDataUint8,e)}subtreeLength(e){return zt(this.batchDataUint8,e+4)}elementReferenceCaptureId(e){const t=zt(this.batchDataUint8,e+4);return this.stringReader.readString(t)}componentId(e){return zt(this.batchDataUint8,e+8)}elementName(e){const t=zt(this.batchDataUint8,e+8);return this.stringReader.readString(t)}textContent(e){const t=zt(this.batchDataUint8,e+4);return this.stringReader.readString(t)}markupContent(e){const t=zt(this.batchDataUint8,e+4);return this.stringReader.readString(t)}attributeName(e){const t=zt(this.batchDataUint8,e+4);return this.stringReader.readString(t)}attributeValue(e){const t=zt(this.batchDataUint8,e+8);return this.stringReader.readString(t)}attributeEventHandlerId(e){return Jt(this.batchDataUint8,e+12)}}class Gt{constructor(e){this.batchDataUint8=e,this.stringTableStartIndex=zt(e,e.length-4)}readString(e){if(-1===e)return null;{const n=zt(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(en.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(en.Debug,`Waiting for batch ${this.nextBatchId}. Batch ${e} not processed.`);try{this.nextBatchId++,this.logger.log(en.Debug,`Applying batch ${e}.`),function(e,t){const n=Q[e];if(!n)throw new Error(`There is no browser renderer with ID ${e}.`);const r=t.arrayRangeReader,o=t.updatedComponents(),i=r.values(o),s=r.count(o),a=t.referenceFrames(),c=r.values(a),l=t.diffReader;for(let e=0;e=this.minLevel){const n=`[${(new Date).toISOString()}] ${en[e]}: ${t}`;switch(e){case en.Critical:case en.Error:console.error(n);break;case en.Warning:console.warn(n);break;case en.Information:console.info(n);break;default:console.log(n)}}}}class on{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!==ke.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!==ke.Connected)return!1;const t=await e.invoke("StartCircuit",re.getBaseURI(),re.getLocationHref(),JSON.stringify(this.components.map((e=>e.toRecord()))),this.applicationState||"");return!!t&&(this.initialize(t),!0)}resolveElement(e){const t=Number.parseInt(e);if(Number.isNaN(t))throw new Error(`Invalid sequence number '${e}'.`);return function(e,t){if(!e.parentNode)throw new Error(`Comment not connected to the DOM ${e.textContent}`);const n=e.parentNode,r=k(n,!0),o=A(r);return Array.from(n.childNodes).forEach((e=>o.push(e))),e[C]=r,t&&(e[I]=t,k(t)),k(e)}(this.components[t].start,this.components[t].end)}}const sn={configureSignalR:e=>{},logLevel:en.Warning,reconnectionOptions:{maxRetries:8,retryIntervalMilliseconds:2e4,dialogId:"components-reconnect-modal"}};class an{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.modal.innerHTML='

Alternatively, reload

',this.message=this.modal.querySelector("h5"),this.button=this.modal.querySelector("button"),this.reloadParagraph=this.modal.querySelector("p"),this.loader=this.getLoader(),this.message.after(this.loader),this.button.addEventListener("click",(async()=>{this.show();try{await(null==fe?void 0:fe.reconnect)()||this.rejected()}catch(e){this.logger.log(en.Error,e),this.failed()}})),this.reloadParagraph.querySelector("a").addEventListener("click",(()=>location.reload()))}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",this.message.innerHTML="Reconnection failed. Try reloading the page if you're unable to reconnect.",this.message.querySelector("a").addEventListener("click",(()=>location.reload()))}rejected(){this.button.style.display="none",this.reloadParagraph.style.display="none",this.loader.style.display="none",this.message.innerHTML="Could not reconnect to the server. Reload the page to restore functionality.",this.message.querySelector("a").addEventListener("click",(()=>location.reload()))}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 cn{constructor(e,t,n){this.dialog=e,this.maxRetries=t,this.document=n,this.document=n;const r=this.document.getElementById(cn.MaxRetriesId);r&&(r.innerText=this.maxRetries.toString())}show(){this.removeClasses(),this.dialog.classList.add(cn.ShowClassName)}update(e){const t=this.document.getElementById(cn.CurrentAttemptId);t&&(t.innerText=e.toString())}hide(){this.removeClasses(),this.dialog.classList.add(cn.HideClassName)}failed(){this.removeClasses(),this.dialog.classList.add(cn.FailedClassName)}rejected(){this.removeClasses(),this.dialog.classList.add(cn.RejectedClassName)}removeClasses(){this.dialog.classList.remove(cn.ShowClassName,cn.HideClassName,cn.FailedClassName,cn.RejectedClassName)}}cn.ShowClassName="components-reconnect-show",cn.HideClassName="components-reconnect-hide",cn.FailedClassName="components-reconnect-failed",cn.RejectedClassName="components-reconnect-rejected",cn.MaxRetriesId="components-reconnect-max-retries",cn.CurrentAttemptId="components-reconnect-current-attempt";class ln{constructor(e,t,n){this._currentReconnectionProcess=null,this._logger=e,this._reconnectionDisplay=t,this._reconnectCallback=n||(()=>fe.reconnect())}onConnectionDown(e,t){if(!this._reconnectionDisplay){const t=document.getElementById(e.dialogId);this._reconnectionDisplay=t?new cn(t,e.maxRetries,document):new an(e.dialogId,e.maxRetries,document,this._logger)}this._currentReconnectionProcess||(this._currentReconnectionProcess=new hn(e,this._logger,this._reconnectCallback,this._reconnectionDisplay))}onConnectionUp(){this._currentReconnectionProcess&&(this._currentReconnectionProcess.dispose(),this._currentReconnectionProcess=null)}}class hn{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;thn.MaximumFirstRetryInterval?hn.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(en.Error,e)}}this.reconnectDisplay.failed()}delay(e){return new Promise((t=>setTimeout(t,e)))}}hn.MaximumFirstRetryInterval=3e3;const un=/^\s*Blazor-Component-State:(?[a-zA-Z0-9\+\/=]+)$/;function dn(e){var t;if(e.nodeType===Node.COMMENT_NODE){const n=e.textContent||"",r=un.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 gn(e,t){const n=e.currentElement;if(n&&n.nodeType===Node.COMMENT_NODE&&n.textContent){const r=fn.exec(n.textContent),o=r&&r.groups&&r.groups.descriptor;if(!o)return;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;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.");if(c){const e=mn(c,n);if(!e)throw new Error(`Could not find an end component comment for '${t}'`);return{type:r,assembly:o,typeName:i,parameterDefinitions:s&&atob(s),parameterValues:a&&atob(a),start:t,prerenderId:c,end:e}}return{type:r,assembly:o,typeName:i,parameterDefinitions:s&&atob(s),parameterValues:a&&atob(a),start:t}}}(r,n,e);case"server":return function(e,t,n){const{type:r,descriptor:o,sequence:i,prerenderId:s}=e;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)}'`);if(s){const e=mn(s,n);if(!e)throw new Error(`Could not find an end component comment for '${t}'`);return{type:r,sequence:i,descriptor:o,start:t,prerenderId:s,end:e}}return{type:r,sequence:i,descriptor:o,start:t}}}(r,n,e)}}catch(e){throw new Error(`Found malformed component comment at ${n.textContent}`)}}}function mn(e,t){for(;t.next()&&t.currentElement;){const n=t.currentElement;if(n.nodeType!==Node.COMMENT_NODE)continue;if(!n.textContent)continue;const r=fn.exec(n.textContent),o=r&&r[1];if(o)return yn(o,e),n}}function yn(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 wn{constructor(e){this.childNodes=e,this.currentIndex=-1,this.length=e.length}next(){return this.currentIndex++,this.currentIndexe.sequence-t.sequence))}(e)}(document),o=dn(document),i=new on(r,o||""),s=await Tn(t,n,i);if(!await i.startCircuit(s))return void n.log(en.Error,"Failed to start the circuit.");let a=!1;const c=()=>{if(!a){const e=new FormData,t=i.circuitId;e.append("circuitId",t),a=navigator.sendBeacon("_blazor/disconnect",e)}};fe.disconnect=c,window.addEventListener("unload",c,{capture:!1,once:!0}),fe.reconnect=async e=>{if(Cn)return!1;const r=e||await Tn(t,n,i);return await i.reconnect(r)?(t.reconnectionHandler.onConnectionUp(),!0):(n.log(en.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)},n.log(en.Information,"Blazor server-side application started.")}async function Tn(t,n,r){const i=new Lt;i.name="blazorpack";const s=(new rt).withUrl("_blazor").withHubProtocol(i);t.configureSignalR(s);const a=s.build();o=(e,t)=>{a.send("DispatchBrowserEvent",JSON.stringify(e),JSON.stringify(t))},fe._internal.navigationManager.listenForNavigationEvents(((e,t)=>a.send("OnLocationChanged",e,t))),a.on("JS.AttachComponent",((e,t)=>function(e,t,n){let r=Q[0];r||(r=Q[0]=new V(0)),r.attachRootComponentToLogicalElement(n,t)}(0,r.resolveElement(t),e))),a.on("JS.BeginInvokeJS",e.jsCallDispatcher.beginInvokeJSFromDotNet),a.on("JS.EndInvokeDotNet",e.jsCallDispatcher.endInvokeDotNetFromJS);const c=tn.getOrCreate(n);a.on("JS.RenderBatch",((e,t)=>{n.log(en.Debug,`Received render batch with id ${e} and ${t.byteLength} bytes.`),c.processBatch(e,t,a)})),a.onclose((e=>!Cn&&t.reconnectionHandler.onConnectionDown(t.reconnectionOptions,e))),a.on("JS.Error",(e=>{Cn=!0,xn(a,e,n),async function(){let e=document.querySelector("#blazor-error-ui");e&&(e.style.display="block"),Ht||(Ht=!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()}})))}()})),fe._internal.forceCloseConnection=()=>a.stop();try{await a.start()}catch(e){xn(a,e,n)}return e.attachDispatcher({beginInvokeDotNetFromJS:(e,t,n,r,o)=>{a.send("BeginInvokeDotNetFromJS",e?e.toString():null,t,n,r||0,o)},endInvokeJSFromDotNet:(e,t,n)=>{a.send("EndInvokeJSFromDotNet",e,t,n)}}),a}function xn(e,t,n){n.log(en.Error,t),e&&e.stop()}fe.start=kn,document&&document.currentScript&&"false"!==document.currentScript.getAttribute("autostart")&&kn()})(); +(()=>{"use strict";var e,t,n;!function(e){window.DotNet=e;const t=[],n=new Map;class r{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 o="__jsObjectId",i={},s={0:new r(window)};s[0]._cachedFunctions.set("import",(e=>("string"==typeof e&&e.startsWith("./")&&(e=document.baseURI+e.substr(2)),import(e))));let a,c=1,l=1,h=null;function u(e){t.push(e)}function d(e){if(e&&"object"==typeof e){s[l]=new r(e);let t={[o]:l};return e.buffer instanceof ArrayBuffer&&void 0!==e.byteLength&&(t.__jsDataReferenceLength=e.byteLength),l++,t}throw new Error(`Cannot create a JSObjectReference from the value '${e}'.`)}function p(e){return e?JSON.parse(e,((e,n)=>t.reduce(((t,n)=>n(e,t)),n))):null}function f(e,t,n,r){const o=m();if(o.invokeDotNetFromJS){const i=I(r),s=o.invokeDotNetFromJS(e,t,n,i);return s?p(s):null}throw new Error("The current dispatcher does not support synchronous calls from JS to .NET. Use invokeMethodAsync instead.")}function g(e,t,n,r){if(e&&n)throw new Error(`For instance method calls, assemblyName should be null. Received '${e}'.`);const o=c++,s=new Promise(((e,t)=>{i[o]={resolve:e,reject:t}}));try{const i=I(r);m().beginInvokeDotNetFromJS(o,e,t,n,i)}catch(e){y(o,!1,e)}return s}function m(){if(null!==h)return h;throw new Error("No .NET call dispatcher has been set.")}function y(e,t,n){if(!i.hasOwnProperty(e))throw new Error(`There is no pending async call with ID ${e}.`);const r=i[e];delete i[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 v(e,t){let n=s[t];if(n)return n.findFunction(e);throw new Error(`JS object instance with ID ${t} does not exist (has it been disposed?).`)}function b(e){delete s[e]}e.attachDispatcher=function(e){h=e},e.attachReviver=u,e.invokeMethod=function(e,t,...n){return f(e,t,null,n)},e.invokeMethodAsync=function(e,t,...n){return g(e,t,null,n)},e.createJSObjectReference=d,e.disposeJSObjectReference=function(e){const t=e&&e.__jsObjectId;"number"==typeof t&&b(t)},function(e){e[e.Default=0]="Default",e[e.JSObjectReference=1]="JSObjectReference"}(a=e.JSCallResultType||(e.JSCallResultType={})),e.jsCallDispatcher={findJSFunction:v,disposeJSObjectReferenceById:b,invokeJSFromDotNet:(e,t,n,r)=>{const o=S(v(e,r).apply(null,p(t)),n);return null==o?null:I(o)},beginInvokeJSFromDotNet:(e,t,n,r,o)=>{const i=new Promise((e=>{e(v(t,o).apply(null,p(n)))}));e&&i.then((t=>m().endInvokeJSFromDotNet(e,!0,I([e,!0,S(t,r)]))),(t=>m().endInvokeJSFromDotNet(e,!1,JSON.stringify([e,!1,w(t)]))))},endInvokeDotNetFromJS:(e,t,n)=>{const r=t?p(n):new Error(n);y(parseInt(e),t,r)},receiveByteArray:(e,t)=>{n.set(e,t)}};class _{constructor(e){this._id=e}invokeMethod(e,...t){return f(null,e,this._id,t)}invokeMethodAsync(e,...t){return g(null,e,this._id,t)}dispose(){g(null,"__Dispose",this._id,null).catch((e=>console.error(e)))}serializeAsArg(){return{__dotNetObject:this._id}}}const E="__byte[]";function S(e,t){switch(t){case a.Default:return e;case a.JSObjectReference:return d(e);default:throw new Error(`Invalid JS call result type '${t}'.`)}}u((function(e,t){if(t&&"object"==typeof t){if(t.hasOwnProperty("__dotNetObject"))return new _(t.__dotNetObject);if(t.hasOwnProperty(o)){const e=t.__jsObjectId,n=s[e];if(n)return n.getWrappedObject();throw new Error(`JS object instance with Id '${e}' does not exist. It may have been disposed.`)}if(t.hasOwnProperty(E)){const e=t["__byte[]"],r=n.get(e);if(void 0===r)throw new Error(`Byte array index '${e}' does not exist.`);return r}}return t}));let C=0;function I(e){return C=0,JSON.stringify(e,k)}function k(e,t){if(t instanceof _)return t.serializeAsArg();if(t instanceof Uint8Array){h.sendByteArray(C,t);const e={[E]:C};return C++,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"}(n||(n={}));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}}let o;function i(e,t){if(!o)throw new Error("eventDispatcher not initialized. Call 'setEventDispatcher' to configure it.");o(e,t)}const s=new Map,a=new Map,c={createEventArgs:()=>({})},l=[];function h(e){return s.get(e)}function u(e){const t=s.get(e);return(null==t?void 0:t.browserEventName)||e}function d(e,t){e.forEach((e=>s.set(e,t)))}function p(e){const t=[];for(let n=0;n{return{...f(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}}),d(["focus","blur","focusin","focusout"],c),d(["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};var t}}),d(["contextmenu","click","mouseover","mouseout","mousemove","mousedown","mouseup","dblclick"],{createEventArgs:e=>f(e)}),d(["error"],{createEventArgs:e=>{return{message:(t=e).message,filename:t.filename,lineno:t.lineno,colno:t.colno};var t}}),d(["loadstart","timeout","abort","load","loadend","progress"],{createEventArgs:e=>{return{lengthComputable:(t=e).lengthComputable,loaded:t.loaded,total:t.total};var t}}),d(["touchcancel","touchend","touchmove","touchenter","touchleave","touchstart"],{createEventArgs:e=>{return{detail:(t=e).detail,touches:p(t.touches),targetTouches:p(t.targetTouches),changedTouches:p(t.changedTouches),ctrlKey:t.ctrlKey,shiftKey:t.shiftKey,altKey:t.altKey,metaKey:t.metaKey,type:t.type};var t}}),d(["gotpointercapture","lostpointercapture","pointercancel","pointerdown","pointerenter","pointerleave","pointermove","pointerout","pointerover","pointerup"],{createEventArgs:e=>{return{...f(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}}),d(["wheel","mousewheel"],{createEventArgs:e=>{return{...f(t=e),deltaX:t.deltaX,deltaY:t.deltaY,deltaZ:t.deltaZ,deltaMode:t.deltaMode};var t}}),d(["toggle"],c);const g=["date","datetime-local","month","time","week"],m=E(["abort","blur","change","error","focus","load","loadend","loadstart","mouseenter","mouseleave","progress","reset","scroll","submit","unload","toggle","DOMNodeInsertedIntoDocument","DOMNodeRemovedFromDocument"]),y={submit:!0},w=E(["click","dblclick","mousedown","mousemove","mouseup"]);class v{constructor(e){this.browserRendererId=e,this.afterClickCallbacks=[];const t=++v.nextEventDelegatorId;this.eventsCollectionKey=`_blazorEvents_${t}`,this.eventInfoStore=new b(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,a.get(n));var n;t&&t.forEach((t=>this.dispatchGlobalEventToAllElements(t,e))),"click"===e.type&&this.afterClickCallbacks.forEach((t=>t(e)))}dispatchGlobalEventToAllElements(e,t){let n=t.target,o=null,s=!1;const a=m.hasOwnProperty(e);let c=!1;for(;n;){const d=this.getEventHandlerInfosForElement(n,!1);if(d){const a=d.getHandler(e);if(a&&(l=n,u=t.type,!((l instanceof HTMLButtonElement||l instanceof HTMLInputElement||l instanceof HTMLTextAreaElement||l instanceof HTMLSelectElement)&&w.hasOwnProperty(u)&&l.disabled))){if(!s){const n=h(e);o=(null==n?void 0:n.createEventArgs)?n.createEventArgs(t):{},s=!0}y.hasOwnProperty(t.type)&&t.preventDefault(),i({browserRendererId:this.browserRendererId,eventHandlerId:a.eventHandlerId,eventName:e,eventFieldInfo:r.fromEvent(a.renderingComponentId,t)},o)}d.stopPropagation(e)&&(c=!0),d.preventDefault(e)&&t.preventDefault()}n=a||c?null:n.parentElement}var l,u}getEventHandlerInfosForElement(e,t){return e.hasOwnProperty(this.eventsCollectionKey)?e[this.eventsCollectionKey]:t?e[this.eventsCollectionKey]=new _:null}}v.nextEventDelegatorId=0;class b{constructor(e){this.globalListener=e,this.infosByEventHandlerId={},this.countByEventName={},l.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=u(e),this.countByEventName.hasOwnProperty(e))this.countByEventName[e]++;else{this.countByEventName[e]=1;const t=m.hasOwnProperty(e);document.addEventListener(e,this.globalListener,t)}}update(e,t){if(this.infosByEventHandlerId.hasOwnProperty(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=u(t.eventName);0==--this.countByEventName[n]&&(delete this.countByEventName[n],document.removeEventListener(n,this.globalListener))}return t}handleEventNameAliasAdded(e,t){if(this.countByEventName.hasOwnProperty(e)){const n=this.countByEventName[e];delete this.countByEventName[e],document.removeEventListener(e,this.globalListener),this.addGlobalListener(t),this.countByEventName[t]+=n-1}}}class _{constructor(){this.handlers={},this.preventDefaultFlags=null,this.stopPropagationFlags=null}getHandler(e){return this.handlers.hasOwnProperty(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 E(e){const t={};return e.forEach((e=>{t[e]=!0})),t}const S=H("_blazorLogicalChildren"),C=H("_blazorLogicalParent"),I=H("_blazorLogicalEnd");function k(e,t){if(e.childNodes.length>0&&!t)throw new Error("New logical elements must start empty, or allowExistingContents must be true");return S in e||(e[S]=[]),e}function T(e,t){const n=document.createComment("!");return x(n,e,t),n}function x(e,t,n){const r=e;if(e instanceof Comment&&A(r)&&A(r).length>0)throw new Error("Not implemented: inserting non-empty logical container");if(R(r))throw new Error("Not implemented: moving existing logical children");const o=A(t);if(n0;)D(n,0)}const r=n;r.parentNode.removeChild(r)}function R(e){return e[C]||null}function P(e,t){return A(e)[t]}function U(e){var t=B(e);return"http://www.w3.org/2000/svg"===t.namespaceURI&&"foreignObject"!==t.tagName}function A(e){return e[S]}function N(e,t){const n=A(e);t.forEach((e=>{e.moveRangeStart=n[e.fromSiblingIndex],e.moveRangeEnd=M(e.moveRangeStart)})),t.forEach((t=>{const r=t.moveToBeforeMarker=document.createComment("marker"),o=n[t.toSiblingIndex+1];o?o.parentNode.insertBefore(r,o):L(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 B(e){if(e instanceof Element)return e;if(e instanceof Comment)return e.parentNode;throw new Error("Not a valid logical element")}function $(e){const t=A(R(e));return t[Array.prototype.indexOf.call(t,e)+1]||null}function L(e,t){if(t instanceof Element)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=$(t);n?n.parentNode.insertBefore(e,n):L(e,R(t))}}}function M(e){if(e instanceof Element)return e;const t=$(e);if(t)return t.previousSibling;{const t=R(e);return t instanceof Element?t.lastChild:M(t)}}function H(e){return"function"==typeof Symbol?Symbol():e}function O(e){return`_bl_${e}`}e.attachReviver(((e,t)=>t&&"object"==typeof t&&t.hasOwnProperty("__internalId")&&"string"==typeof t.__internalId?function(e){const t=`[${O(e)}]`;return document.querySelector(t)}(t.__internalId):t));const F="_blazorSelectValue",j=document.createElement("template"),W=document.createElementNS("http://www.w3.org/2000/svg","g"),z={},q="__internal_",J="preventDefault_",K="stopPropagation_";class V{constructor(e){this.childComponentLocations={},this.eventDelegator=new v(e),this.eventDelegator.notifyAfterClick((e=>{if(!ee)return;if(0!==e.button||function(e){return e.ctrlKey||e.shiftKey||e.altKey||e.metaKey}(e))return;if(e.defaultPrevented)return;const t=function(e){const t=!window._blazorDisableComposedPath&&e.composedPath&&e.composedPath();if(t){for(let e=0;ese(!1))))},enableNavigationInterception:function(){ee=!0},navigateTo:oe,getBaseURI:()=>document.baseURI,getLocationHref:()=>location.href};function oe(e,t,n=!1){const r=ce(e);if(!t&&he(r))ie(r,!1,n);else if(t&&location.href===e){const t=e+"?";history.replaceState(null,"",t),location.replace(e)}else n?history.replaceState(null,"",r):location.href=e}function ie(e,t,n=!1){Z=!0,n?history.replaceState(null,"",e):history.pushState(null,"",e),se(t)}async function se(e){ne&&await ne(location.href,e)}let ae;function ce(e){return ae=ae||document.createElement("a"),ae.href=e,ae.href}function le(e,t){return e?e.tagName===t?e:le(e.parentElement,t):null}function he(e){const t=(n=document.baseURI).substr(0,n.lastIndexOf("/")+1);var n;return e.startsWith(t)}const ue={init:function(e,t,n,r=50){const o=pe(t);(o||document.documentElement).style.overflowAnchor="none";const i=new IntersectionObserver((function(r){r.forEach((r=>{var o;if(!r.isIntersecting)return;const i=t.getBoundingClientRect(),s=n.getBoundingClientRect().top-i.bottom,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`});i.observe(t),i.observe(n);const s=c(t),a=c(n);function c(e){const t=new MutationObserver((()=>{i.unobserve(e),i.observe(e)}));return t.observe(e,{attributes:!0}),t}de[e._id]={intersectionObserver:i,mutationObserverBefore:s,mutationObserverAfter:a}},dispose:function(e){const t=de[e._id];t&&(t.intersectionObserver.disconnect(),t.mutationObserverBefore.disconnect(),t.mutationObserverAfter.disconnect(),e.dispose(),delete de[e._id])}},de={};function pe(e){return e?"visible"!==getComputedStyle(e).overflowY?e:pe(e.parentElement):null}const fe={navigateTo:oe,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=a.get(t.browserEventName);n?n.push(e):a.set(t.browserEventName,[e]),l.forEach((n=>n(e,t.browserEventName)))}s.set(e,t)},_internal:{navigationManager:re,domWrapper:{focus:function(e,t){if(!(e instanceof HTMLElement))throw new Error("Unable to focus an invalid element.");e.focus({preventScroll:t})}},Virtualize:ue}};window.Blazor=fe;const ge=[0,2e3,1e4,3e4,null];class me{constructor(e){this._retryDelays=void 0!==e?[...e,null]:ge}nextRetryDelayInMilliseconds(e){return this._retryDelays[e.previousRetryCount]}}class ye extends Error{constructor(e,t){const n=new.target.prototype;super(`${e}: Status code '${t}'`),this.statusCode=t,this.__proto__=n}}class we extends Error{constructor(e="A timeout occurred."){const t=new.target.prototype;super(e),this.__proto__=t}}class ve extends Error{constructor(e="An abort occurred."){const t=new.target.prototype;super(e),this.__proto__=t}}class be{constructor(e,t,n){this.statusCode=e,this.statusText=t,this.content=n}}class _e{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""}}var Ee,Se,Ce,Ie,ke;!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"}(Ee||(Ee={}));class Te extends _e{constructor(e){if(super(),this._logger=e,"undefined"==typeof fetch){const e=require;this._jar=new(e("tough-cookie").CookieJar),this._fetchType=e("node-fetch"),this._fetchType=e("fetch-cookie")(this._fetchType,this._jar),this._abortControllerType=e("abort-controller")}else this._fetchType=fetch.bind(self),this._abortControllerType=AbortController}async send(e){if(e.abortSignal&&e.abortSignal.aborted)throw new ve;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 ve});let r,o=null;if(e.timeout){const r=e.timeout;o=setTimeout((()=>{t.abort(),this._logger.log(Ee.Warning,"Timeout from HTTP request."),n=new we}),r)}try{r=await this._fetchType(e.url,{body:e.content,cache:"no-cache",credentials:!0===e.withCredentials?"include":"same-origin",headers:{"Content-Type":"text/plain;charset=UTF-8","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(Ee.Warning,`Error from HTTP request. ${e}.`),e}finally{o&&clearTimeout(o),e.abortSignal&&(e.abortSignal.onabort=null)}if(!r.ok){const e=await xe(r,"text");throw new ye(e||r.statusText,r.status)}const i=xe(r,e.responseType),s=await i;return new be(r.status,r.statusText,s)}getCookieString(e){return""}}function xe(e,t){let n;switch(t){case"arraybuffer":n=e.arrayBuffer();break;case"text":n=e.text();break;case"blob":case"document":case"json":throw new Error(`${t} is not supported.`);default:n=e.text()}return n}class De extends _e{constructor(e){super(),this._logger=e}send(e){return e.abortSignal&&e.abortSignal.aborted?Promise.reject(new ve):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"),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 ve)}),e.timeout&&(r.timeout=e.timeout),r.onload=()=>{e.abortSignal&&(e.abortSignal.onabort=null),r.status>=200&&r.status<300?t(new be(r.status,r.statusText,r.response||r.responseText)):n(new ye(r.response||r.responseText||r.statusText,r.status))},r.onerror=()=>{this._logger.log(Ee.Warning,`Error from HTTP request. ${r.status}: ${r.statusText}.`),n(new ye(r.statusText,r.status))},r.ontimeout=()=>{this._logger.log(Ee.Warning,"Timeout from HTTP request."),n(new we)},r.send(e.content||"")})):Promise.reject(new Error("No url defined.")):Promise.reject(new Error("No method defined."))}}class Re extends _e{constructor(e){if(super(),"undefined"!=typeof fetch)this._httpClient=new Te(e);else{if("undefined"==typeof XMLHttpRequest)throw new Error("No usable HttpClient found.");this._httpClient=new De(e)}}send(e){return e.abortSignal&&e.abortSignal.aborted?Promise.reject(new ve):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)}}class Pe{}Pe.Authorization="Authorization",Pe.Cookie="Cookie",function(e){e[e.None=0]="None",e[e.WebSockets=1]="WebSockets",e[e.ServerSentEvents=2]="ServerSentEvents",e[e.LongPolling=4]="LongPolling"}(Se||(Se={})),function(e){e[e.Text=1]="Text",e[e.Binary=2]="Binary"}(Ce||(Ce={}));class Ue{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 Ae{constructor(){}log(e,t){}}Ae.instance=new Ae;class Ne{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 Be{static get isBrowser(){return"object"==typeof window}static get isWebWorker(){return"object"==typeof self&&"importScripts"in self}static get isNode(){return!this.isBrowser&&!this.isWebWorker}}function $e(e,t){let n="";return Le(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 Le(e){return e&&"undefined"!=typeof ArrayBuffer&&(e instanceof ArrayBuffer||e.constructor&&"ArrayBuffer"===e.constructor.name)}async function Me(e,t,n,r,o,i,s,a,c){let l={};if(o){const e=await o();e&&(l={Authorization:`Bearer ${e}`})}const[h,u]=Fe();l[h]=u,e.log(Ee.Trace,`(${t} transport) sending data. ${$e(i,s)}.`);const d=Le(i)?"arraybuffer":"text",p=await n.post(r,{content:i,headers:{...l,...c},responseType:d,withCredentials:a});e.log(Ee.Trace,`(${t} transport) request complete. Response status: ${p.statusCode}.`)}class He{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 Oe{constructor(e){this._minLevel=e,this.out=console}log(e,t){if(e>=this._minLevel){const n=`[${(new Date).toISOString()}] ${Ee[e]}: ${t}`;switch(e){case Ee.Critical:case Ee.Error:this.out.error(n);break;case Ee.Warning:this.out.warn(n);break;case Ee.Information:this.out.info(n);break;default:this.out.log(n)}}}}function Fe(){let e="X-SignalR-User-Agent";return Be.isNode&&(e="User-Agent"),[e,je("0.0.0-DEV_BUILD",We(),Be.isNode?"NodeJS":"Browser",ze())]}function je(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 We(){if(!Be.isNode)return"";switch(process.platform){case"win32":return"Windows NT";case"darwin":return"macOS";case"linux":return"Linux";default:return process.platform}}function ze(){if(Be.isNode)return process.versions.node}class qe{constructor(e,t,n,r,o,i){this._httpClient=e,this._accessTokenFactory=t,this._logger=n,this._pollAbort=new Ue,this._logMessageContent=r,this._withCredentials=o,this._headers=i,this._running=!1,this.onreceive=null,this.onclose=null}get pollAborted(){return this._pollAbort.aborted}async connect(e,t){if(Ne.isRequired(e,"url"),Ne.isRequired(t,"transferFormat"),Ne.isIn(t,Ce,"transferFormat"),this._url=e,this._logger.log(Ee.Trace,"(LongPolling transport) Connecting."),t===Ce.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]=Fe(),o={[n]:r,...this._headers},i={abortSignal:this._pollAbort.signal,headers:o,timeout:1e5,withCredentials:this._withCredentials};t===Ce.Binary&&(i.responseType="arraybuffer");const s=await this._getAccessToken();this._updateHeaderToken(i,s);const a=`${e}&_=${Date.now()}`;this._logger.log(Ee.Trace,`(LongPolling transport) polling: ${a}.`);const c=await this._httpClient.get(a,i);200!==c.statusCode?(this._logger.log(Ee.Error,`(LongPolling transport) Unexpected response code: ${c.statusCode}.`),this._closeError=new ye(c.statusText||"",c.statusCode),this._running=!1):this._running=!0,this._receiving=this._poll(this._url,i)}async _getAccessToken(){return this._accessTokenFactory?await this._accessTokenFactory():null}_updateHeaderToken(e,t){e.headers||(e.headers={}),t?e.headers[Pe.Authorization]=`Bearer ${t}`:e.headers[Pe.Authorization]&&delete e.headers[Pe.Authorization]}async _poll(e,t){try{for(;this._running;){const n=await this._getAccessToken();this._updateHeaderToken(t,n);try{const n=`${e}&_=${Date.now()}`;this._logger.log(Ee.Trace,`(LongPolling transport) polling: ${n}.`);const r=await this._httpClient.get(n,t);204===r.statusCode?(this._logger.log(Ee.Information,"(LongPolling transport) Poll terminated by server."),this._running=!1):200!==r.statusCode?(this._logger.log(Ee.Error,`(LongPolling transport) Unexpected response code: ${r.statusCode}.`),this._closeError=new ye(r.statusText||"",r.statusCode),this._running=!1):r.content?(this._logger.log(Ee.Trace,`(LongPolling transport) data received. ${$e(r.content,this._logMessageContent)}.`),this.onreceive&&this.onreceive(r.content)):this._logger.log(Ee.Trace,"(LongPolling transport) Poll timed out, reissuing.")}catch(e){this._running?e instanceof we?this._logger.log(Ee.Trace,"(LongPolling transport) Poll timed out, reissuing."):(this._closeError=e,this._running=!1):this._logger.log(Ee.Trace,`(LongPolling transport) Poll errored after shutdown: ${e.message}`)}}}finally{this._logger.log(Ee.Trace,"(LongPolling transport) Polling complete."),this.pollAborted||this._raiseOnClose()}}async send(e){return this._running?Me(this._logger,"LongPolling",this._httpClient,this._url,this._accessTokenFactory,e,this._logMessageContent,this._withCredentials,this._headers):Promise.reject(new Error("Cannot send until the transport is connected"))}async stop(){this._logger.log(Ee.Trace,"(LongPolling transport) Stopping polling."),this._running=!1,this._pollAbort.abort();try{await this._receiving,this._logger.log(Ee.Trace,`(LongPolling transport) sending DELETE request to ${this._url}.`);const e={},[t,n]=Fe();e[t]=n;const r={headers:{...e,...this._headers},withCredentials:this._withCredentials},o=await this._getAccessToken();this._updateHeaderToken(r,o),await this._httpClient.delete(this._url,r),this._logger.log(Ee.Trace,"(LongPolling transport) DELETE request sent.")}finally{this._logger.log(Ee.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(Ee.Trace,e),this.onclose(this._closeError)}}}class Je{constructor(e,t,n,r,o,i,s){this._httpClient=e,this._accessTokenFactory=t,this._logger=n,this._logMessageContent=r,this._withCredentials=i,this._eventSourceConstructor=o,this._headers=s,this.onreceive=null,this.onclose=null}async connect(e,t){if(Ne.isRequired(e,"url"),Ne.isRequired(t,"transferFormat"),Ne.isIn(t,Ce,"transferFormat"),this._logger.log(Ee.Trace,"(SSE transport) Connecting."),this._url=e,this._accessTokenFactory){const t=await this._accessTokenFactory();t&&(e+=(e.indexOf("?")<0?"?":"&")+`access_token=${encodeURIComponent(t)}`)}return new Promise(((n,r)=>{let o,i=!1;if(t===Ce.Text){if(Be.isBrowser||Be.isWebWorker)o=new this._eventSourceConstructor(e,{withCredentials:this._withCredentials});else{const t=this._httpClient.getCookieString(e),n={};n.Cookie=t;const[r,i]=Fe();n[r]=i,o=new this._eventSourceConstructor(e,{withCredentials:this._withCredentials,headers:{...n,...this._headers}})}try{o.onmessage=e=>{if(this.onreceive)try{this._logger.log(Ee.Trace,`(SSE transport) data received. ${$e(e.data,this._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(Ee.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?Me(this._logger,"SSE",this._httpClient,this._url,this._accessTokenFactory,e,this._logMessageContent,this._withCredentials,this._headers):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 Ke{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){if(Ne.isRequired(e,"url"),Ne.isRequired(t,"transferFormat"),Ne.isIn(t,Ce,"transferFormat"),this._logger.log(Ee.Trace,"(WebSockets transport) Connecting."),this._accessTokenFactory){const t=await this._accessTokenFactory();t&&(e+=(e.indexOf("?")<0?"?":"&")+`access_token=${encodeURIComponent(t)}`)}return new Promise(((n,r)=>{let o;e=e.replace(/^http/,"ws"),this._httpClient.getCookieString(e);let i=!1;o||(o=new this._webSocketConstructor(e)),t===Ce.Binary&&(o.binaryType="arraybuffer"),o.onopen=t=>{this._logger.log(Ee.Information,`WebSocket connected to ${e}.`),this._webSocket=o,i=!0,n()},o.onerror=e=>{let t=null;t="undefined"!=typeof ErrorEvent&&e instanceof ErrorEvent?e.error:"There was an error with the transport",this._logger.log(Ee.Information,`(WebSockets transport) ${t}.`)},o.onmessage=e=>{if(this._logger.log(Ee.Trace,`(WebSockets transport) data received. ${$e(e.data,this._logMessageContent)}.`),this.onreceive)try{this.onreceive(e.data)}catch(e){return void this._close(e)}},o.onclose=e=>{if(i)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(Ee.Trace,`(WebSockets transport) sending data. ${$e(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(Ee.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 Ve{constructor(e,t={}){var n;if(this._stopPromiseResolver=()=>{},this.features={},this._negotiateVersion=1,Ne.isRequired(e,"url"),this._logger=void 0===(n=t.logger)?new Oe(Ee.Information):null===n?Ae.instance:void 0!==n.log?n:new Oe(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,"undefined"==typeof WebSocket||t.WebSocket||(t.WebSocket=WebSocket),"undefined"==typeof EventSource||t.EventSource||(t.EventSource=EventSource),this._httpClient=t.httpClient||new Re(this._logger),this._connectionState="Disconnected",this._connectionStarted=!1,this._options=t,this.onreceive=null,this.onclose=null}async start(e){if(e=e||Ce.Binary,Ne.isIn(e,Ce,"transferFormat"),this._logger.log(Ee.Debug,`Starting connection with transfer format '${Ce[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(Ee.Error,e),await this._stopPromise,Promise.reject(new Error(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(Ee.Error,e),Promise.reject(new Error(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 Xe(this.transport)),this._sendQueue.send(e))}async stop(e){return"Disconnected"===this._connectionState?(this._logger.log(Ee.Debug,`Call to HttpConnection.stop(${e}) ignored because the connection is already in the disconnected state.`),Promise.resolve()):"Disconnecting"===this._connectionState?(this._logger.log(Ee.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(Ee.Error,`HttpConnection.transport.stop() threw error '${e}'.`),this._stopConnection()}this.transport=void 0}else this._logger.log(Ee.Debug,"HttpConnection.transport is undefined in HttpConnection.stop() because start() failed.")}async _startInternal(e){let t=this.baseUrl;this._accessTokenFactory=this._options.accessTokenFactory;try{if(this._options.skipNegotiation){if(this._options.transport!==Se.WebSockets)throw new Error("Negotiation can only be skipped when using the WebSocket transport directly.");this.transport=this._constructTransport(Se.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 Error("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}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 qe&&(this.features.inherentKeepAlive=!0),"Connecting"===this._connectionState&&(this._logger.log(Ee.Debug,"The HttpConnection connected successfully."),this._connectionState="Connected")}catch(e){return this._logger.log(Ee.Error,"Failed to start the connection: "+e),this._connectionState="Disconnected",this.transport=void 0,this._stopPromiseResolver(),Promise.reject(e)}}async _getNegotiationResponse(e){const t={};if(this._accessTokenFactory){const e=await this._accessTokenFactory();e&&(t[Pe.Authorization]=`Bearer ${e}`)}const[n,r]=Fe();t[n]=r;const o=this._resolveNegotiateUrl(e);this._logger.log(Ee.Debug,`Sending negotiation request: ${o}.`);try{const e=await this._httpClient.post(o,{content:"",headers:{...t,...this._options.headers},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 ye&&404===e.statusCode&&(t+=" Either this is not a SignalR endpoint or there is a proxy blocking the connection."),this._logger.log(Ee.Error,t),Promise.reject(new Error(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(Ee.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: ${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(Ee.Error,`Failed to start the transport '${n.transport}': ${e}`),a=void 0,i.push(`${n.transport} failed: ${e}`),"Connecting"!==this._connectionState){const e="Failed to select transport before stop() was called.";return this._logger.log(Ee.Debug,e),Promise.reject(new Error(e))}}}}return i.length>0?Promise.reject(new Error(`Unable to connect to the server with any of the available transports. ${i.join(" ")}`)):Promise.reject(new Error("None of the transports supported by the client are supported by the server."))}_constructTransport(e){switch(e){case Se.WebSockets:if(!this._options.WebSocket)throw new Error("'WebSocket' is not supported in your environment.");return new Ke(this._httpClient,this._accessTokenFactory,this._logger,this._options.logMessageContent||!1,this._options.WebSocket,this._options.headers||{});case Se.ServerSentEvents:if(!this._options.EventSource)throw new Error("'EventSource' is not supported in your environment.");return new Je(this._httpClient,this._accessTokenFactory,this._logger,this._options.logMessageContent||!1,this._options.EventSource,this._options.withCredentials,this._options.headers||{});case Se.LongPolling:return new qe(this._httpClient,this._accessTokenFactory,this._logger,this._options.logMessageContent||!1,this._options.withCredentials,this._options.headers||{});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=Se[e.transport];if(null==r)return this._logger.log(Ee.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(Ee.Debug,`Skipping transport '${Se[r]}' because it was disabled by the client.`),new Error(`'${Se[r]}' is disabled by the client.`);if(!(e.transferFormats.map((e=>Ce[e])).indexOf(n)>=0))return this._logger.log(Ee.Debug,`Skipping transport '${Se[r]}' because it does not support the requested transfer format '${Ce[n]}'.`),new Error(`'${Se[r]}' does not support ${Ce[n]}.`);if(r===Se.WebSockets&&!this._options.WebSocket||r===Se.ServerSentEvents&&!this._options.EventSource)return this._logger.log(Ee.Debug,`Skipping transport '${Se[r]}' because it is not supported in your environment.'`),new Error(`'${Se[r]}' is not supported in your environment.`);this._logger.log(Ee.Debug,`Selecting transport '${Se[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(Ee.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(Ee.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(Ee.Error,`Connection disconnected with error '${e}'.`):this._logger.log(Ee.Information,"Connection disconnected."),this._sendQueue&&(this._sendQueue.stop().catch((e=>{this._logger.log(Ee.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(Ee.Error,`HttpConnection.onclose(${e}) threw error '${t}'.`)}}}else this._logger.log(Ee.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(!Be.isBrowser||!window.document)throw new Error(`Cannot resolve '${e}'.`);const t=window.document.createElement("a");return t.href=e,this._logger.log(Ee.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 Xe{constructor(e){this._transport=e,this._buffer=[],this._executing=!0,this._sendBufferedData=new Ye,this._transportResult=new Ye,this._sendLoopPromise=this._sendLoop()}send(e){return this._bufferData(e),this._transportResult||(this._transportResult=new Ye),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 Ye;const e=this._transportResult;this._transportResult=void 0;const t="string"==typeof this._buffer[0]?this._buffer.join(""):Xe._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 Ye{constructor(){this.promise=new Promise(((e,t)=>[this._resolver,this._rejecter]=[e,t]))}resolve(){this._resolver()}reject(e){this._rejecter(e)}}class Ge{static write(e){return`${e}${Ge.RecordSeparator}`}static parse(e){if(e[e.length-1]!==Ge.RecordSeparator)throw new Error("Message is incomplete.");const t=e.split(Ge.RecordSeparator);return t.pop(),t}}Ge.RecordSeparatorCode=30,Ge.RecordSeparator=String.fromCharCode(Ge.RecordSeparatorCode);class Qe{writeHandshakeRequest(e){return Ge.write(JSON.stringify(e))}parseHandshakeResponse(e){let t,n;if(Le(e)){const r=new Uint8Array(e),o=r.indexOf(Ge.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(Ge.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=Ge.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"}(Ie||(Ie={}));class Ze{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 He(this,e)}}!function(e){e.Disconnected="Disconnected",e.Connecting="Connecting",e.Connected="Connected",e.Disconnecting="Disconnecting",e.Reconnecting="Reconnecting"}(ke||(ke={}));class et{constructor(e,t,n,r){this._nextKeepAlive=0,Ne.isRequired(e,"connection"),Ne.isRequired(t,"logger"),Ne.isRequired(n,"protocol"),this.serverTimeoutInMilliseconds=3e4,this.keepAliveIntervalInMilliseconds=15e3,this._logger=t,this._protocol=n,this.connection=e,this._reconnectPolicy=r,this._handshakeProtocol=new Qe,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=ke.Disconnected,this._connectionStarted=!1,this._cachedPingMessage=this._protocol.writeMessage({type:Ie.Ping})}static create(e,t,n,r){return new et(e,t,n,r)}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!==ke.Disconnected&&this._connectionState!==ke.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!==ke.Disconnected)return Promise.reject(new Error("Cannot start a HubConnection that is not in the 'Disconnected' state."));this._connectionState=ke.Connecting,this._logger.log(Ee.Debug,"Starting HubConnection.");try{await this._startInternal(),this._connectionState=ke.Connected,this._connectionStarted=!0,this._logger.log(Ee.Debug,"HubConnection connected successfully.")}catch(e){return this._connectionState=ke.Disconnected,this._logger.log(Ee.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(Ee.Debug,"Sending handshake request."),await this._sendMessage(this._handshakeProtocol.writeHandshakeRequest(t)),this._logger.log(Ee.Information,`Using HubProtocol '${this._protocol.name}'.`),this._cleanupTimeout(),this._resetTimeoutPeriod(),this._resetKeepAliveInterval(),await e,this._stopDuringStartError)throw this._stopDuringStartError}catch(e){throw this._logger.log(Ee.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){return this._connectionState===ke.Disconnected?(this._logger.log(Ee.Debug,`Call to HubConnection.stop(${e}) ignored because it is already in the disconnected state.`),Promise.resolve()):this._connectionState===ke.Disconnecting?(this._logger.log(Ee.Debug,`Call to HttpConnection.stop(${e}) ignored because the connection is already in the disconnecting state.`),this._stopPromise):(this._connectionState=ke.Disconnecting,this._logger.log(Ee.Debug,"Stopping HubConnection."),this._reconnectDelayHandle?(this._logger.log(Ee.Debug,"Connection stopped during reconnect delay. Done reconnecting."),clearTimeout(this._reconnectDelayHandle),this._reconnectDelayHandle=void 0,this._completeClose(),Promise.resolve()):(this._cleanupTimeout(),this._cleanupPingTimer(),this._stopDuringStartError=e||new Error("The connection was stopped before the hub handshake could complete."),this.connection.stop(e)))}stream(e,...t){const[n,r]=this._replaceStreamingParams(t),o=this._createStreamInvocation(e,t,r);let i;const s=new Ze;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===Ie.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===Ie.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 Ie.Invocation:this._invokeClientMethod(e);break;case Ie.StreamItem:case Ie.Completion:{const t=this._callbacks[e.invocationId];t&&(e.type===Ie.Completion&&delete this._callbacks[e.invocationId],t(e));break}case Ie.Ping:break;case Ie.Close:{this._logger.log(Ee.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(Ee.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(Ee.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(Ee.Error,e);const n=new Error(e);throw this._handshakeRejecter(n),n}return this._logger.log(Ee.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===ke.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."))}_invokeClientMethod(e){const t=this._methods[e.target.toLowerCase()];if(t){try{t.forEach((t=>t.apply(this,e.arguments)))}catch(t){this._logger.log(Ee.Error,`A callback for the method ${e.target.toLowerCase()} threw error '${t}'.`)}if(e.invocationId){const e="Server requested a response, which is not supported in this version of the client.";this._logger.log(Ee.Error,e),this._stopPromise=this._stopInternal(new Error(e))}}else this._logger.log(Ee.Warning,`No client method with the name '${e.target}' found.`)}_connectionClosed(e){this._logger.log(Ee.Debug,`HubConnection.connectionClosed(${e}) called while in state ${this._connectionState}.`),this._stopDuringStartError=this._stopDuringStartError||e||new Error("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===ke.Disconnecting?this._completeClose(e):this._connectionState===ke.Connected&&this._reconnectPolicy?this._reconnect(e):this._connectionState===ke.Connected&&this._completeClose(e)}_completeClose(e){if(this._connectionStarted){this._connectionState=ke.Disconnected,this._connectionStarted=!1;try{this._closedCallbacks.forEach((t=>t.apply(this,[e])))}catch(t){this._logger.log(Ee.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(Ee.Debug,"Connection not reconnecting because the IRetryPolicy returned null on the first reconnect attempt."),void this._completeClose(e);if(this._connectionState=ke.Reconnecting,e?this._logger.log(Ee.Information,`Connection reconnecting because of error '${e}'.`):this._logger.log(Ee.Information,"Connection reconnecting."),0!==this._reconnectingCallbacks.length){try{this._reconnectingCallbacks.forEach((t=>t.apply(this,[e])))}catch(t){this._logger.log(Ee.Error,`An onreconnecting callback called with error '${e}' threw error '${t}'.`)}if(this._connectionState!==ke.Reconnecting)return void this._logger.log(Ee.Debug,"Connection left the reconnecting state in onreconnecting callback. Done reconnecting.")}for(;null!==o;){if(this._logger.log(Ee.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!==ke.Reconnecting)return void this._logger.log(Ee.Debug,"Connection left the reconnecting state during reconnect delay. Done reconnecting.");try{if(await this._startInternal(),this._connectionState=ke.Connected,this._logger.log(Ee.Information,"HubConnection reconnected successfully."),0!==this._reconnectedCallbacks.length)try{this._reconnectedCallbacks.forEach((e=>e.apply(this,[this.connection.connectionId])))}catch(e){this._logger.log(Ee.Error,`An onreconnected callback called with connectionId '${this.connection.connectionId}; threw error '${e}'.`)}return}catch(e){if(this._logger.log(Ee.Information,`Reconnect attempt failed because of error '${e}'.`),this._connectionState!==ke.Reconnecting)return this._logger.log(Ee.Debug,`Connection moved to the '${this._connectionState}' from the reconnecting state during reconnect attempt. Done reconnecting.`),void(this._connectionState===ke.Disconnecting&&this._completeClose());r=e instanceof Error?e:new Error(e.toString()),o=this._getNextRetryDelay(n++,Date.now()-t,r)}}this._logger.log(Ee.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(Ee.Error,`IRetryPolicy.nextRetryDelayInMilliseconds(${e}, ${t}) threw error '${n}'.`),null}}_cancelCallbacksWithError(e){const t=this._callbacks;this._callbacks={},Object.keys(t).forEach((n=>{(0,t[n])(null,e)}))}_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:Ie.Invocation}:{arguments:t,target:e,type:Ie.Invocation};{const n=this._invocationId;return this._invocationId++,0!==r.length?{arguments:t,invocationId:n.toString(),streamIds:r,target:e,type:Ie.Invocation}:{arguments:t,invocationId:n.toString(),target:e,type:Ie.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 ut=ot?new TextDecoder:null,dt=ot?"undefined"!=typeof process&&"force"!==process.env.TEXT_DECODER?200:0:it,pt=function(e,t){this.type=e,this.data=t};function ft(e,t,n){var r=Math.floor(n/4294967296),o=n;e.setUint32(t,r),e.setUint32(t+4,o)}function gt(e,t){return 4294967296*e.getInt32(t)+e.getUint32(t+4)}var mt={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),ft(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:gt(t,4),nsec:t.getUint32(0)};default:throw new Error("Unrecognized data size for timestamp: "+e.length)}}(e);return new Date(1e3*t.sec+t.nsec/1e6)}},yt=function(){function e(){this.builtInEncoders=[],this.builtInDecoders=[],this.encoders=[],this.decoders=[],this.register(mt)}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 "+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: "+e+" bytes in UTF-8");this.writeU8(219),this.writeU32(e)}},e.prototype.encodeString=function(e){if(e.length>ct){var t=st(e);this.ensureBufferSizeToWrite(5+t),this.writeStringHeader(t),lt(e,this.bytes,this.pos),this.pos+=t}else t=st(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: "+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: "+t);this.writeU8(198),this.writeU32(t)}var n=wt(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: "+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=ht(e,t,n),i=Uint8Array.prototype.slice.call(e,t,t+n);return this.store(i,o),o},e}(),St=(_t=function(e,t){return(_t=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])})(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}_t(e,t),e.prototype=null===t?Object.create(t):(n.prototype=t.prototype,new n)}),Ct=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]1||a(e,t)}))})}function a(e,t){try{(n=o[e](t)).value instanceof kt?Promise.resolve(n.value.v).then(c,l):h(i[0][2],n)}catch(e){h(i[0][3],e)}var n}function c(e){a("next",e)}function l(e){a("throw",e)}function h(e,t){e(t),i.shift(),i.length&&a(i[0][0],i[0][1])}},xt=new DataView(new ArrayBuffer(0)),Dt=new Uint8Array(xt.buffer),Rt=function(){try{xt.getInt8(0)}catch(e){return e.constructor}throw new Error("never reached")}(),Pt=new Rt("Insufficient data"),Ut=4294967295,At=new Et,Nt=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 St(t,e),t}(Error),Bt=function(){function e(e,t,n,r,o,i,s,a){void 0===e&&(e=yt.defaultCodec),void 0===t&&(t=void 0),void 0===n&&(n=Ut),void 0===r&&(r=Ut),void 0===o&&(o=Ut),void 0===i&&(i=Ut),void 0===s&&(s=Ut),void 0===a&&(a=At),this.extensionCodec=e,this.context=t,this.maxStrLength=n,this.maxBinLength=r,this.maxArrayLength=o,this.maxMapLength=i,this.maxExtLength=s,this.keyDecoder=a,this.totalPos=0,this.pos=0,this.view=xt,this.bytes=Dt,this.headByte=-1,this.stack=[]}return e.prototype.reinitializeState=function(){this.totalPos=0,this.headByte=-1,this.stack.length=0},e.prototype.setBuffer=function(e){this.bytes=wt(e),this.view=function(e){if(e instanceof ArrayBuffer)return new DataView(e);var t=wt(e);return new DataView(t.buffer,t.byteOffset,t.byteLength)}(this.bytes),this.pos=0},e.prototype.appendBuffer=function(e){if(-1!==this.headByte||this.hasRemaining()){var t=this.bytes.subarray(this.pos),n=wt(e),r=new Uint8Array(t.length+n.length);r.set(t),r.set(n,t.length),this.setBuffer(r)}else this.setBuffer(e)},e.prototype.hasRemaining=function(e){return void 0===e&&(e=1),this.view.byteLength-this.pos>=e},e.prototype.createExtraByteError=function(e){var t=this.view,n=this.pos;return new RangeError("Extra "+(t.byteLength-n)+" of "+t.byteLength+" byte(s) found at buffer["+e+"]")},e.prototype.decode=function(e){this.reinitializeState(),this.setBuffer(e);var t=this.doDecodeSync();if(this.hasRemaining())throw this.createExtraByteError(this.pos);return t},e.prototype.decodeMulti=function(e){return Ct(this,(function(t){switch(t.label){case 0:this.reinitializeState(),this.setBuffer(e),t.label=1;case 1:return this.hasRemaining()?[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,u,d;return Ct(this,(function(p){switch(p.label){case 0:i=!1,p.label=1;case 1:p.trys.push([1,6,7,12]),t=It(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 Rt))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())throw this.createExtraByteError(this.totalPos);return[2,s]}throw h=(l=this).headByte,u=l.pos,d=l.totalPos,new RangeError("Insufficient data in parsing "+bt(h)+" at "+d+" ("+u+" 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 Tt(this,arguments,(function(){var n,r,o,i,s,a,c,l,h;return Ct(this,(function(u){switch(u.label){case 0:n=t,r=-1,u.label=1;case 1:u.trys.push([1,13,14,19]),o=It(e),u.label=2;case 2:return[4,kt(o.next())];case 3:if((i=u.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()),u.label=4;case 4:u.trys.push([4,9,,10]),u.label=5;case 5:return[4,kt(this.doDecodeSync())];case 6:return[4,u.sent()];case 7:return u.sent(),0==--r?[3,8]:[3,5];case 8:return[3,10];case 9:if(!((a=u.sent())instanceof Rt))throw a;return[3,10];case 10:this.totalPos+=this.pos,u.label=11;case 11:return[3,2];case 12:return[3,19];case 13:return c=u.sent(),l={error:c},[3,19];case 14:return u.trys.push([14,,17,18]),i&&!i.done&&(h=o.return)?[4,kt(h.call(o))]:[3,16];case 15:u.sent(),u.label=16;case 16:return[3,18];case 17:if(l)throw l.error;return[7];case 18:return[7];case 19:return[2]}}))}))},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 Nt("Unrecognized type byte: "+bt(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 Nt("The type of key must be string or number but "+typeof t);if("__proto__"===t)throw new Nt("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 Nt("Unrecognized array type byte: "+bt(e))}},e.prototype.pushMapState=function(e){if(e>this.maxMapLength)throw new Nt("Max length exceeded: map length ("+e+") > maxMapLengthLength ("+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 Nt("Max length exceeded: array length ("+e+") > maxArrayLength ("+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 Nt("Max length exceeded: UTF-8 byte length ("+e+") > maxStrLength ("+this.maxStrLength+")");if(this.bytes.byteLengthdt?function(e,t,n){var r=e.subarray(t,t+n);return ut.decode(r)}(this.bytes,o,e):ht(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 Nt("Max length exceeded: bin length ("+e+") > maxBinLength ("+this.maxBinLength+")");if(!this.hasRemaining(e+t))throw Pt;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 Nt("Max length exceeded: ext length ("+e+") > maxExtLength ("+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=gt(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 $t{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 Lt=new Uint8Array([145,Ie.Ping]);class Mt{constructor(e){this.name="messagepack",this.version=1,this.transferFormat=Ce.Binary,this._errorResult=1,this._voidResult=2,this._nonVoidResult=3,e=e||{},this._encoder=new vt(e.extensionCodec,e.context,e.maxDepth,e.initialBufferSize,e.sortKeys,e.forceFloat32,e.ignoreUndefined,e.forceIntegerToFloat),this._decoder=new Bt(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=Ae.instance);const r=$t.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 Ie.Invocation:return this._writeInvocation(e);case Ie.StreamInvocation:return this._writeStreamInvocation(e);case Ie.StreamItem:return this._writeStreamItem(e);case Ie.Completion:return this._writeCompletion(e);case Ie.Ping:return $t.write(Lt);case Ie.CancelInvocation:return this._writeCancelInvocation(e);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 Ie.Invocation:return this._createInvocationMessage(this._readHeaders(n),n);case Ie.StreamItem:return this._createStreamItemMessage(this._readHeaders(n),n);case Ie.Completion:return this._createCompletionMessage(this._readHeaders(n),n);case Ie.Ping:return this._createPingMessage(n);case Ie.Close:return this._createCloseMessage(n);default:return t.log(Ee.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:Ie.Close}}_createPingMessage(e){if(e.length<1)throw new Error("Invalid payload for Ping message.");return{type:Ie.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:Ie.Invocation}:{arguments:t[4],headers:e,streamIds:[],target:t[3],type:Ie.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:Ie.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:Ie.Completion}}_writeInvocation(e){let t;return t=e.streamIds?this._encoder.encode([Ie.Invocation,e.headers||{},e.invocationId||null,e.target,e.arguments,e.streamIds]):this._encoder.encode([Ie.Invocation,e.headers||{},e.invocationId||null,e.target,e.arguments]),$t.write(t.slice())}_writeStreamInvocation(e){let t;return t=e.streamIds?this._encoder.encode([Ie.StreamInvocation,e.headers||{},e.invocationId,e.target,e.arguments,e.streamIds]):this._encoder.encode([Ie.StreamInvocation,e.headers||{},e.invocationId,e.target,e.arguments]),$t.write(t.slice())}_writeStreamItem(e){const t=this._encoder.encode([Ie.StreamItem,e.headers||{},e.invocationId,e.item]);return $t.write(t.slice())}_writeCompletion(e){const t=e.error?this._errorResult:e.result?this._nonVoidResult:this._voidResult;let n;switch(t){case this._errorResult:n=this._encoder.encode([Ie.Completion,e.headers||{},e.invocationId,t,e.error]);break;case this._voidResult:n=this._encoder.encode([Ie.Completion,e.headers||{},e.invocationId,t]);break;case this._nonVoidResult:n=this._encoder.encode([Ie.Completion,e.headers||{},e.invocationId,t,e.result])}return $t.write(n.slice())}_writeCancelInvocation(e){const t=this._encoder.encode([Ie.CancelInvocation,e.headers||{},e.invocationId]);return $t.write(t.slice())}_readHeaders(e){const t=e[1];if("object"!=typeof t)throw new Error("Invalid headers.");return t}}let Ht=!1;const Ot="function"==typeof TextDecoder?new TextDecoder("utf-8"):null,Ft=Ot?Ot.decode.bind(Ot):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("")},jt=Math.pow(2,32),Wt=Math.pow(2,21)-1;function zt(e,t){return e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24}function qt(e,t){return e[t]+(e[t+1]<<8)+(e[t+2]<<16)+(e[t+3]<<24>>>0)}function Jt(e,t){const n=qt(e,t+4);if(n>Wt)throw new Error(`Cannot read uint64 with high order part ${n}, because the result would exceed Number.MAX_SAFE_INTEGER.`);return n*jt+qt(e,t)}class Kt{constructor(e){this.batchData=e;const t=new Gt(e);this.arrayRangeReader=new Qt(e),this.arrayBuilderSegmentReader=new Zt(e),this.diffReader=new Vt(e),this.editReader=new Xt(e,t),this.frameReader=new Yt(e,t)}updatedComponents(){return zt(this.batchData,this.batchData.length-20)}referenceFrames(){return zt(this.batchData,this.batchData.length-16)}disposedComponentIds(){return zt(this.batchData,this.batchData.length-12)}disposedEventHandlerIds(){return zt(this.batchData,this.batchData.length-8)}updatedComponentsEntry(e,t){const n=e+4*t;return zt(this.batchData,n)}referenceFramesEntry(e,t){return e+20*t}disposedComponentIdsEntry(e,t){const n=e+4*t;return zt(this.batchData,n)}disposedEventHandlerIdsEntry(e,t){const n=e+8*t;return Jt(this.batchData,n)}}class Vt{constructor(e){this.batchDataUint8=e}componentId(e){return zt(this.batchDataUint8,e)}edits(e){return e+4}editsEntry(e,t){return e+16*t}}class Xt{constructor(e,t){this.batchDataUint8=e,this.stringReader=t}editType(e){return zt(this.batchDataUint8,e)}siblingIndex(e){return zt(this.batchDataUint8,e+4)}newTreeIndex(e){return zt(this.batchDataUint8,e+8)}moveToSiblingIndex(e){return zt(this.batchDataUint8,e+8)}removedAttributeName(e){const t=zt(this.batchDataUint8,e+12);return this.stringReader.readString(t)}}class Yt{constructor(e,t){this.batchDataUint8=e,this.stringReader=t}frameType(e){return zt(this.batchDataUint8,e)}subtreeLength(e){return zt(this.batchDataUint8,e+4)}elementReferenceCaptureId(e){const t=zt(this.batchDataUint8,e+4);return this.stringReader.readString(t)}componentId(e){return zt(this.batchDataUint8,e+8)}elementName(e){const t=zt(this.batchDataUint8,e+8);return this.stringReader.readString(t)}textContent(e){const t=zt(this.batchDataUint8,e+4);return this.stringReader.readString(t)}markupContent(e){const t=zt(this.batchDataUint8,e+4);return this.stringReader.readString(t)}attributeName(e){const t=zt(this.batchDataUint8,e+4);return this.stringReader.readString(t)}attributeValue(e){const t=zt(this.batchDataUint8,e+8);return this.stringReader.readString(t)}attributeEventHandlerId(e){return Jt(this.batchDataUint8,e+12)}}class Gt{constructor(e){this.batchDataUint8=e,this.stringTableStartIndex=zt(e,e.length-4)}readString(e){if(-1===e)return null;{const n=zt(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(en.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(en.Debug,`Waiting for batch ${this.nextBatchId}. Batch ${e} not processed.`);try{this.nextBatchId++,this.logger.log(en.Debug,`Applying batch ${e}.`),function(e,t){const n=Q[e];if(!n)throw new Error(`There is no browser renderer with ID ${e}.`);const r=t.arrayRangeReader,o=t.updatedComponents(),i=r.values(o),s=r.count(o),a=t.referenceFrames(),c=r.values(a),l=t.diffReader;for(let e=0;e=this.minLevel){const n=`[${(new Date).toISOString()}] ${en[e]}: ${t}`;switch(e){case en.Critical:case en.Error:console.error(n);break;case en.Warning:console.warn(n);break;case en.Information:console.info(n);break;default:console.log(n)}}}}class on{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!==ke.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!==ke.Connected)return!1;const t=await e.invoke("StartCircuit",re.getBaseURI(),re.getLocationHref(),JSON.stringify(this.components.map((e=>e.toRecord()))),this.applicationState||"");return!!t&&(this.initialize(t),!0)}resolveElement(e){const t=Number.parseInt(e);if(Number.isNaN(t))throw new Error(`Invalid sequence number '${e}'.`);return function(e,t){if(!e.parentNode)throw new Error(`Comment not connected to the DOM ${e.textContent}`);const n=e.parentNode,r=k(n,!0),o=A(r);return Array.from(n.childNodes).forEach((e=>o.push(e))),e[C]=r,t&&(e[I]=t,k(t)),k(e)}(this.components[t].start,this.components[t].end)}}const sn={configureSignalR:e=>{},logLevel:en.Warning,reconnectionOptions:{maxRetries:8,retryIntervalMilliseconds:2e4,dialogId:"components-reconnect-modal"}};class an{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.modal.innerHTML='

Alternatively, reload

',this.message=this.modal.querySelector("h5"),this.button=this.modal.querySelector("button"),this.reloadParagraph=this.modal.querySelector("p"),this.loader=this.getLoader(),this.message.after(this.loader),this.button.addEventListener("click",(async()=>{this.show();try{await(null==fe?void 0:fe.reconnect)()||this.rejected()}catch(e){this.logger.log(en.Error,e),this.failed()}})),this.reloadParagraph.querySelector("a").addEventListener("click",(()=>location.reload()))}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",this.message.innerHTML="Reconnection failed. Try reloading the page if you're unable to reconnect.",this.message.querySelector("a").addEventListener("click",(()=>location.reload()))}rejected(){this.button.style.display="none",this.reloadParagraph.style.display="none",this.loader.style.display="none",this.message.innerHTML="Could not reconnect to the server. Reload the page to restore functionality.",this.message.querySelector("a").addEventListener("click",(()=>location.reload()))}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 cn{constructor(e,t,n){this.dialog=e,this.maxRetries=t,this.document=n,this.document=n;const r=this.document.getElementById(cn.MaxRetriesId);r&&(r.innerText=this.maxRetries.toString())}show(){this.removeClasses(),this.dialog.classList.add(cn.ShowClassName)}update(e){const t=this.document.getElementById(cn.CurrentAttemptId);t&&(t.innerText=e.toString())}hide(){this.removeClasses(),this.dialog.classList.add(cn.HideClassName)}failed(){this.removeClasses(),this.dialog.classList.add(cn.FailedClassName)}rejected(){this.removeClasses(),this.dialog.classList.add(cn.RejectedClassName)}removeClasses(){this.dialog.classList.remove(cn.ShowClassName,cn.HideClassName,cn.FailedClassName,cn.RejectedClassName)}}cn.ShowClassName="components-reconnect-show",cn.HideClassName="components-reconnect-hide",cn.FailedClassName="components-reconnect-failed",cn.RejectedClassName="components-reconnect-rejected",cn.MaxRetriesId="components-reconnect-max-retries",cn.CurrentAttemptId="components-reconnect-current-attempt";class ln{constructor(e,t,n){this._currentReconnectionProcess=null,this._logger=e,this._reconnectionDisplay=t,this._reconnectCallback=n||(()=>fe.reconnect())}onConnectionDown(e,t){if(!this._reconnectionDisplay){const t=document.getElementById(e.dialogId);this._reconnectionDisplay=t?new cn(t,e.maxRetries,document):new an(e.dialogId,e.maxRetries,document,this._logger)}this._currentReconnectionProcess||(this._currentReconnectionProcess=new hn(e,this._logger,this._reconnectCallback,this._reconnectionDisplay))}onConnectionUp(){this._currentReconnectionProcess&&(this._currentReconnectionProcess.dispose(),this._currentReconnectionProcess=null)}}class hn{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;thn.MaximumFirstRetryInterval?hn.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(en.Error,e)}}this.reconnectDisplay.failed()}delay(e){return new Promise((t=>setTimeout(t,e)))}}hn.MaximumFirstRetryInterval=3e3;const un=/^\s*Blazor-Component-State:(?[a-zA-Z0-9\+\/=]+)$/;function dn(e){var t;if(e.nodeType===Node.COMMENT_NODE){const n=e.textContent||"",r=un.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 gn(e,t){const n=e.currentElement;if(n&&n.nodeType===Node.COMMENT_NODE&&n.textContent){const r=fn.exec(n.textContent),o=r&&r.groups&&r.groups.descriptor;if(!o)return;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;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.");if(c){const e=mn(c,n);if(!e)throw new Error(`Could not find an end component comment for '${t}'`);return{type:r,assembly:o,typeName:i,parameterDefinitions:s&&atob(s),parameterValues:a&&atob(a),start:t,prerenderId:c,end:e}}return{type:r,assembly:o,typeName:i,parameterDefinitions:s&&atob(s),parameterValues:a&&atob(a),start:t}}}(r,n,e);case"server":return function(e,t,n){const{type:r,descriptor:o,sequence:i,prerenderId:s}=e;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)}'`);if(s){const e=mn(s,n);if(!e)throw new Error(`Could not find an end component comment for '${t}'`);return{type:r,sequence:i,descriptor:o,start:t,prerenderId:s,end:e}}return{type:r,sequence:i,descriptor:o,start:t}}}(r,n,e)}}catch(e){throw new Error(`Found malformed component comment at ${n.textContent}`)}}}function mn(e,t){for(;t.next()&&t.currentElement;){const n=t.currentElement;if(n.nodeType!==Node.COMMENT_NODE)continue;if(!n.textContent)continue;const r=fn.exec(n.textContent),o=r&&r[1];if(o)return yn(o,e),n}}function yn(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 wn{constructor(e){this.childNodes=e,this.currentIndex=-1,this.length=e.length}next(){return this.currentIndex++,this.currentIndexe.sequence-t.sequence))}(e)}(document),o=dn(document),i=new on(r,o||""),s=await Tn(t,n,i);if(!await i.startCircuit(s))return void n.log(en.Error,"Failed to start the circuit.");let a=!1;const c=()=>{if(!a){const e=new FormData,t=i.circuitId;e.append("circuitId",t),a=navigator.sendBeacon("_blazor/disconnect",e)}};fe.disconnect=c,window.addEventListener("unload",c,{capture:!1,once:!0}),fe.reconnect=async e=>{if(Cn)return!1;const r=e||await Tn(t,n,i);return await i.reconnect(r)?(t.reconnectionHandler.onConnectionUp(),!0):(n.log(en.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)},n.log(en.Information,"Blazor server-side application started.")}async function Tn(t,n,r){const i=new Mt;i.name="blazorpack";const s=(new rt).withUrl("_blazor").withHubProtocol(i);t.configureSignalR(s);const a=s.build();o=(e,t)=>{a.send("DispatchBrowserEvent",JSON.stringify(e),JSON.stringify(t))},fe._internal.navigationManager.listenForNavigationEvents(((e,t)=>a.send("OnLocationChanged",e,t))),a.on("JS.AttachComponent",((e,t)=>function(e,t,n){let r=Q[0];r||(r=Q[0]=new V(0)),r.attachRootComponentToLogicalElement(n,t)}(0,r.resolveElement(t),e))),a.on("JS.BeginInvokeJS",e.jsCallDispatcher.beginInvokeJSFromDotNet),a.on("JS.EndInvokeDotNet",e.jsCallDispatcher.endInvokeDotNetFromJS),a.on("JS.ReceiveByteArray",e.jsCallDispatcher.receiveByteArray);const c=tn.getOrCreate(n);a.on("JS.RenderBatch",((e,t)=>{n.log(en.Debug,`Received render batch with id ${e} and ${t.byteLength} bytes.`),c.processBatch(e,t,a)})),a.onclose((e=>!Cn&&t.reconnectionHandler.onConnectionDown(t.reconnectionOptions,e))),a.on("JS.Error",(e=>{Cn=!0,xn(a,e,n),async function(){let e=document.querySelector("#blazor-error-ui");e&&(e.style.display="block"),Ht||(Ht=!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()}})))}()})),fe._internal.forceCloseConnection=()=>a.stop(),fe._internal.sendJSDataStream=async(e,t)=>{setTimeout((async()=>{let n=5,r=(new Date).valueOf();try{const o=31744;let i=0;for(;i1)await a.send("SupplyJSDataChunk",t,c,null);else{await a.invoke("SupplyJSDataChunk",t,c,null);const e=(new Date).valueOf(),o=e-r;r=e,n=Math.max(1,Math.round(500/o))}i+=s}}catch(e){await a.send("SupplyJSDataChunk",t,null,e.toString())}}),0)};try{await a.start()}catch(e){xn(a,e,n)}return e.attachDispatcher({beginInvokeDotNetFromJS:(e,t,n,r,o)=>{a.send("BeginInvokeDotNetFromJS",e?e.toString():null,t,n,r||0,o)},endInvokeJSFromDotNet:(e,t,n)=>{a.send("EndInvokeJSFromDotNet",e,t,n)},sendByteArray:(e,t)=>{a.send("ReceiveByteArray",e,t)}}),a}function xn(e,t,n){n.log(en.Error,t),e&&e.stop()}fe.start=kn,document&&document.currentScript&&"false"!==document.currentScript.getAttribute("autostart")&&kn()})(); \ 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 617d9a3600c8..905f06991b58 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;!function(e){window.DotNet=e;const t=[],n=new Map;class r{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 o="__jsObjectId",a={},i={0:new r(window)};i[0]._cachedFunctions.set("import",(e=>("string"==typeof e&&e.startsWith("./")&&(e=document.baseURI+e.substr(2)),import(e))));let s,c=1,l=1,u=null;function d(e){t.push(e)}function h(e){if(e&&"object"==typeof e){i[l]=new r(e);const t={[o]:l};return l++,t}throw new Error(`Cannot create a JSObjectReference from the value '${e}'.`)}function f(e){return e?JSON.parse(e,((e,n)=>t.reduce(((t,n)=>n(e,t)),n))):null}function p(e,t,n,r){const o=v();if(o.invokeDotNetFromJS){const a=D(r),i=o.invokeDotNetFromJS(e,t,n,a);return i?f(i):null}throw new Error("The current dispatcher does not support synchronous calls from JS to .NET. Use invokeMethodAsync instead.")}function m(e,t,n,r){if(e&&n)throw new Error(`For instance method calls, assemblyName should be null. Received '${e}'.`);const o=c++,i=new Promise(((e,t)=>{a[o]={resolve:e,reject:t}}));try{const a=D(r);v().beginInvokeDotNetFromJS(o,e,t,n,a)}catch(e){g(o,!1,e)}return i}function v(){if(null!==u)return u;throw new Error("No .NET call dispatcher has been set.")}function g(e,t,n){if(!a.hasOwnProperty(e))throw new Error(`There is no pending async call with ID ${e}.`);const r=a[e];delete a[e],t?r.resolve(n):r.reject(n)}function b(e){return e instanceof Error?`${e.message}\n${e.stack}`:e?e.toString():"null"}function y(e,t){let n=i[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 i[e]}e.attachDispatcher=function(e){u=e},e.attachReviver=d,e.invokeMethod=function(e,t,...n){return p(e,t,null,n)},e.invokeMethodAsync=function(e,t,...n){return m(e,t,null,n)},e.createJSObjectReference=h,e.disposeJSObjectReference=function(e){const t=e&&e.__jsObjectId;"number"==typeof t&&E(t)},function(e){e[e.Default=0]="Default",e[e.JSObjectReference=1]="JSObjectReference"}(s=e.JSCallResultType||(e.JSCallResultType={})),e.jsCallDispatcher={findJSFunction:y,disposeJSObjectReferenceById:E,invokeJSFromDotNet:(e,t,n,r)=>{const o=S(y(e,r).apply(null,f(t)),n);return null==o?null:D(o)},beginInvokeJSFromDotNet:(e,t,n,r,o)=>{const a=new Promise((e=>{e(y(t,o).apply(null,f(n)))}));e&&a.then((t=>v().endInvokeJSFromDotNet(e,!0,D([e,!0,S(t,r)]))),(t=>v().endInvokeJSFromDotNet(e,!1,JSON.stringify([e,!1,b(t)]))))},endInvokeDotNetFromJS:(e,t,n)=>{const r=t?f(n):new Error(n);g(parseInt(e),t,r)},receiveByteArray:(e,t)=>{n.set(e,t)}};class w{constructor(e){this._id=e}invokeMethod(e,...t){return p(null,e,this._id,t)}invokeMethodAsync(e,...t){return m(null,e,this._id,t)}dispose(){m(null,"__Dispose",this._id,null).catch((e=>console.error(e)))}serializeAsArg(){return{__dotNetObject:this._id}}}const I="__byte[]";function S(e,t){switch(t){case s.Default:return e;case s.JSObjectReference:return h(e);default:throw new Error(`Invalid JS call result type '${t}'.`)}}d((function(e,t){if(t&&"object"==typeof t){if(t.hasOwnProperty("__dotNetObject"))return new w(t.__dotNetObject);if(t.hasOwnProperty(o)){const e=t.__jsObjectId,n=i[e];if(n)return n.getWrappedObject();throw new Error(`JS object instance with Id '${e}' does not exist. It may have been disposed.`)}if(t.hasOwnProperty(I)){const e=t["__byte[]"],r=n.get(e);if(void 0===r)throw new Error(`Byte array index '${e}' does not exist.`);return r}}return t}));let C=0;function D(e){return C=0,JSON.stringify(e,A)}function A(e,t){if(t instanceof w)return t.serializeAsArg();if(t instanceof Uint8Array){u.sendByteArray(C,t);const e={[I]:C};return C++,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"}(n||(n={}));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}}let o;function a(e,t){if(!o)throw new Error("eventDispatcher not initialized. Call 'setEventDispatcher' to configure it.");o(e,t)}const i=new Map,s=new Map,c={createEventArgs:()=>({})},l=[];function u(e){return i.get(e)}function d(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 f(e){const t=[];for(let n=0;n{return{...p(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"],c),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};var t}}),h(["contextmenu","click","mouseover","mouseout","mousemove","mousedown","mouseup","dblclick"],{createEventArgs:e=>p(e)}),h(["error"],{createEventArgs:e=>{return{message:(t=e).message,filename:t.filename,lineno:t.lineno,colno:t.colno};var t}}),h(["loadstart","timeout","abort","load","loadend","progress"],{createEventArgs:e=>{return{lengthComputable:(t=e).lengthComputable,loaded:t.loaded,total:t.total};var t}}),h(["touchcancel","touchend","touchmove","touchenter","touchleave","touchstart"],{createEventArgs:e=>{return{detail:(t=e).detail,touches:f(t.touches),targetTouches:f(t.targetTouches),changedTouches:f(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{...p(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{...p(t=e),deltaX:t.deltaX,deltaY:t.deltaY,deltaZ:t.deltaZ,deltaMode:t.deltaMode};var t}}),h(["toggle"],c);const m=["date","datetime-local","month","time","week"],v=I(["abort","blur","change","error","focus","load","loadend","loadstart","mouseenter","mouseleave","progress","reset","scroll","submit","unload","toggle","DOMNodeInsertedIntoDocument","DOMNodeRemovedFromDocument"]),g={submit:!0},b=I(["click","dblclick","mousedown","mousemove","mouseup"]);class y{constructor(e){this.browserRendererId=e,this.afterClickCallbacks=[];const t=++y.nextEventDelegatorId;this.eventsCollectionKey=`_blazorEvents_${t}`,this.eventInfoStore=new E(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){let n=t.target,o=null,i=!1;const s=v.hasOwnProperty(e);let c=!1;for(;n;){const h=this.getEventHandlerInfosForElement(n,!1);if(h){const s=h.getHandler(e);if(s&&(l=n,d=t.type,!((l instanceof HTMLButtonElement||l instanceof HTMLInputElement||l instanceof HTMLTextAreaElement||l instanceof HTMLSelectElement)&&b.hasOwnProperty(d)&&l.disabled))){if(!i){const n=u(e);o=(null==n?void 0:n.createEventArgs)?n.createEventArgs(t):{},i=!0}g.hasOwnProperty(t.type)&&t.preventDefault(),a({browserRendererId:this.browserRendererId,eventHandlerId:s.eventHandlerId,eventName:e,eventFieldInfo:r.fromEvent(s.renderingComponentId,t)},o)}h.stopPropagation(e)&&(c=!0),h.preventDefault(e)&&t.preventDefault()}n=s||c?null:n.parentElement}var l,d}getEventHandlerInfosForElement(e,t){return e.hasOwnProperty(this.eventsCollectionKey)?e[this.eventsCollectionKey]:t?e[this.eventsCollectionKey]=new w:null}}y.nextEventDelegatorId=0;class E{constructor(e){this.globalListener=e,this.infosByEventHandlerId={},this.countByEventName={},l.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=d(e),this.countByEventName.hasOwnProperty(e))this.countByEventName[e]++;else{this.countByEventName[e]=1;const t=v.hasOwnProperty(e);document.addEventListener(e,this.globalListener,t)}}update(e,t){if(this.infosByEventHandlerId.hasOwnProperty(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=d(t.eventName);0==--this.countByEventName[n]&&(delete this.countByEventName[n],document.removeEventListener(n,this.globalListener))}return t}handleEventNameAliasAdded(e,t){if(this.countByEventName.hasOwnProperty(e)){const n=this.countByEventName[e];delete this.countByEventName[e],document.removeEventListener(e,this.globalListener),this.addGlobalListener(t),this.countByEventName[t]+=n-1}}}class w{constructor(){this.handlers={},this.preventDefaultFlags=null,this.stopPropagationFlags=null}getHandler(e){return this.handlers.hasOwnProperty(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 I(e){const t={};return e.forEach((e=>{t[e]=!0})),t}const S=M("_blazorLogicalChildren"),C=M("_blazorLogicalParent"),D=M("_blazorLogicalEnd");function A(e,t){if(e.childNodes.length>0&&!t)throw new Error("New logical elements must start empty, or allowExistingContents must be true");return S in e||(e[S]=[]),e}function T(e,t){const n=document.createComment("!");return N(n,e,t),n}function N(e,t,n){const r=e;if(e instanceof Comment&&O(r)&&O(r).length>0)throw new Error("Not implemented: inserting non-empty logical container");if(R(r))throw new Error("Not implemented: moving existing logical children");const o=O(t);if(n0;)k(n,0)}const r=n;r.parentNode.removeChild(r)}function R(e){return e[C]||null}function F(e,t){return O(e)[t]}function _(e){var t=P(e);return"http://www.w3.org/2000/svg"===t.namespaceURI&&"foreignObject"!==t.tagName}function O(e){return e[S]}function x(e,t){const n=O(e);t.forEach((e=>{e.moveRangeStart=n[e.fromSiblingIndex],e.moveRangeEnd=H(e.moveRangeStart)})),t.forEach((t=>{const r=t.moveToBeforeMarker=document.createComment("marker"),o=n[t.toSiblingIndex+1];o?o.parentNode.insertBefore(r,o):L(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 P(e){if(e instanceof Element)return e;if(e instanceof Comment)return e.parentNode;throw new Error("Not a valid logical element")}function B(e){const t=O(R(e));return t[Array.prototype.indexOf.call(t,e)+1]||null}function L(e,t){if(t instanceof Element)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=B(t);n?n.parentNode.insertBefore(e,n):L(e,R(t))}}}function H(e){if(e instanceof Element)return e;const t=B(e);if(t)return t.previousSibling;{const t=R(e);return t instanceof Element?t.lastChild:H(t)}}function M(e){return"function"==typeof Symbol?Symbol():e}function U(e){return`_bl_${e}`}e.attachReviver(((e,t)=>t&&"object"==typeof t&&t.hasOwnProperty("__internalId")&&"string"==typeof t.__internalId?function(e){const t=`[${U(e)}]`;return document.querySelector(t)}(t.__internalId):t));const j="_blazorSelectValue",J=document.createElement("template"),$=document.createElementNS("http://www.w3.org/2000/svg","g"),K={},z="__internal_",V="preventDefault_",X="stopPropagation_";class Y{constructor(e){this.childComponentLocations={},this.eventDelegator=new y(e),this.eventDelegator.notifyAfterClick((e=>{if(!ee)return;if(0!==e.button||function(e){return e.ctrlKey||e.shiftKey||e.altKey||e.metaKey}(e))return;if(e.defaultPrevented)return;const t=function(e){const t=!window._blazorDisableComposedPath&&e.composedPath&&e.composedPath();if(t){for(let e=0;eie(!1))))},enableNavigationInterception:function(){ee=!0},navigateTo:oe,getBaseURI:()=>document.baseURI,getLocationHref:()=>location.href};function oe(e,t,n=!1){const r=ce(e);if(!t&&ue(r))ae(r,!1,n);else if(t&&location.href===e){const t=e+"?";history.replaceState(null,"",t),location.replace(e)}else n?history.replaceState(null,"",r):location.href=e}function ae(e,t,n=!1){Q=!0,n?history.replaceState(null,"",e):history.pushState(null,"",e),ie(t)}async function ie(e){ne&&await ne(location.href,e)}let se;function ce(e){return se=se||document.createElement("a"),se.href=e,se.href}function le(e,t){return e?e.tagName===t?e:le(e.parentElement,t):null}function ue(e){const t=(n=document.baseURI).substr(0,n.lastIndexOf("/")+1);var n;return e.startsWith(t)}const de={init:function(e,t,n,r=50){const o=fe(t);(o||document.documentElement).style.overflowAnchor="none";const a=new IntersectionObserver((function(r){r.forEach((r=>{var o;if(!r.isIntersecting)return;const a=t.getBoundingClientRect(),i=n.getBoundingClientRect().top-a.bottom,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`});a.observe(t),a.observe(n);const i=c(t),s=c(n);function c(e){const t=new MutationObserver((()=>{a.unobserve(e),a.observe(e)}));return t.observe(e,{attributes:!0}),t}he[e._id]={intersectionObserver:a,mutationObserverBefore:i,mutationObserverAfter:s}},dispose:function(e){const t=he[e._id];t&&(t.intersectionObserver.disconnect(),t.mutationObserverBefore.disconnect(),t.mutationObserverAfter.disconnect(),e.dispose(),delete he[e._id])}},he={};function fe(e){return e?"visible"!==getComputedStyle(e).overflowY?e:fe(e.parentElement):null}const pe={navigateTo:oe,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]),l.forEach((n=>n(e,t.browserEventName)))}i.set(e,t)},_internal:{navigationManager:re,domWrapper:{focus:function(e,t){if(!(e instanceof HTMLElement))throw new Error("Unable to focus an invalid element.");e.focus({preventScroll:t})}},Virtualize:de}};window.Blazor=pe;let me=!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("")},be=Math.pow(2,32),ye=Math.pow(2,21)-1;function Ee(e,t){return e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24}function we(e,t){return e[t]+(e[t+1]<<8)+(e[t+2]<<16)+(e[t+3]<<24>>>0)}function Ie(e,t){const n=we(e,t+4);if(n>ye)throw new Error(`Cannot read uint64 with high order part ${n}, because the result would exceed Number.MAX_SAFE_INTEGER.`);return n*be+we(e,t)}class Se{constructor(e){this.batchData=e;const t=new Te(e);this.arrayRangeReader=new Ne(e),this.arrayBuilderSegmentReader=new ke(e),this.diffReader=new Ce(e),this.editReader=new De(e,t),this.frameReader=new Ae(e,t)}updatedComponents(){return Ee(this.batchData,this.batchData.length-20)}referenceFrames(){return Ee(this.batchData,this.batchData.length-16)}disposedComponentIds(){return Ee(this.batchData,this.batchData.length-12)}disposedEventHandlerIds(){return Ee(this.batchData,this.batchData.length-8)}updatedComponentsEntry(e,t){const n=e+4*t;return Ee(this.batchData,n)}referenceFramesEntry(e,t){return e+20*t}disposedComponentIdsEntry(e,t){const n=e+4*t;return Ee(this.batchData,n)}disposedEventHandlerIdsEntry(e,t){const n=e+8*t;return Ie(this.batchData,n)}}class Ce{constructor(e){this.batchDataUint8=e}componentId(e){return Ee(this.batchDataUint8,e)}edits(e){return e+4}editsEntry(e,t){return e+16*t}}class De{constructor(e,t){this.batchDataUint8=e,this.stringReader=t}editType(e){return Ee(this.batchDataUint8,e)}siblingIndex(e){return Ee(this.batchDataUint8,e+4)}newTreeIndex(e){return Ee(this.batchDataUint8,e+8)}moveToSiblingIndex(e){return Ee(this.batchDataUint8,e+8)}removedAttributeName(e){const t=Ee(this.batchDataUint8,e+12);return this.stringReader.readString(t)}}class Ae{constructor(e,t){this.batchDataUint8=e,this.stringReader=t}frameType(e){return Ee(this.batchDataUint8,e)}subtreeLength(e){return Ee(this.batchDataUint8,e+4)}elementReferenceCaptureId(e){const t=Ee(this.batchDataUint8,e+4);return this.stringReader.readString(t)}componentId(e){return Ee(this.batchDataUint8,e+8)}elementName(e){const t=Ee(this.batchDataUint8,e+8);return this.stringReader.readString(t)}textContent(e){const t=Ee(this.batchDataUint8,e+4);return this.stringReader.readString(t)}markupContent(e){const t=Ee(this.batchDataUint8,e+4);return this.stringReader.readString(t)}attributeName(e){const t=Ee(this.batchDataUint8,e+4);return this.stringReader.readString(t)}attributeValue(e){const t=Ee(this.batchDataUint8,e+8);return this.stringReader.readString(t)}attributeEventHandlerId(e){return Ie(this.batchDataUint8,e+12)}}class Te{constructor(e){this.batchDataUint8=e,this.stringTableStartIndex=Ee(e,e.length-4)}readString(e){if(-1===e)return null;{const n=Ee(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)<{!function(e,t,n){const r=document.querySelector(e);if(!r)throw new Error(`Could not find any element matching selector '${e}'.`);!function(e,t,n){let r=Z[0];r||(r=Z[0]=new Y(0)),r.attachRootComponentToLogicalElement(n,t)}(0,A(r,!0),t)}(t,e)},RenderBatch:(e,t)=>{try{const n=Me(t);(function(e,t){const n=Z[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{Fe=!0,console.error(`${e}\n${t}`),async function(){let e=document.querySelector("#blazor-error-ui");e&&(e.style.display="block"),me||(me=!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:e.jsCallDispatcher.beginInvokeJSFromDotNet,EndInvokeDotNet:e.jsCallDispatcher.endInvokeDotNetFromJS,SendByteArrayToJS:He,Navigate:re.navigateTo};window.external.receiveMessage((e=>{const n=function(e){if(Fe||!e||!e.startsWith(Re))return null;const t=e.substring(Re.length),[n,...r]=JSON.parse(t);return{messageType:n,args:r}}(e);if(n){if(!t.hasOwnProperty(n.messageType))throw new Error(`Unsupported IPC message type '${n.messageType}'`);t[n.messageType].apply(null,n.args)}}))}(),e.attachDispatcher({beginInvokeDotNetFromJS:Oe,endInvokeJSFromDotNet:xe,sendByteArray:Pe}),pe._internal.InputFile=Ue,re.enableNavigationInterception(),re.listenForNavigationEvents(Be),Le("AttachPage",re.getBaseURI(),re.getLocationHref())}o=function(e,t){Le("DispatchBrowserEvent",e,t)},pe.start=Ke,document&&document.currentScript&&"false"!==document.currentScript.getAttribute("autostart")&&Ke()})(); \ No newline at end of file +(()=>{"use strict";var e,t,n;!function(e){window.DotNet=e;const t=[],n=new Map;class r{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 o="__jsObjectId",a={},i={0:new r(window)};i[0]._cachedFunctions.set("import",(e=>("string"==typeof e&&e.startsWith("./")&&(e=document.baseURI+e.substr(2)),import(e))));let s,c=1,l=1,u=null;function d(e){t.push(e)}function h(e){if(e&&"object"==typeof e){i[l]=new r(e);let t={[o]:l};return e.buffer instanceof ArrayBuffer&&void 0!==e.byteLength&&(t.__jsDataReferenceLength=e.byteLength),l++,t}throw new Error(`Cannot create a JSObjectReference from the value '${e}'.`)}function f(e){return e?JSON.parse(e,((e,n)=>t.reduce(((t,n)=>n(e,t)),n))):null}function p(e,t,n,r){const o=v();if(o.invokeDotNetFromJS){const a=C(r),i=o.invokeDotNetFromJS(e,t,n,a);return i?f(i):null}throw new Error("The current dispatcher does not support synchronous calls from JS to .NET. Use invokeMethodAsync instead.")}function m(e,t,n,r){if(e&&n)throw new Error(`For instance method calls, assemblyName should be null. Received '${e}'.`);const o=c++,i=new Promise(((e,t)=>{a[o]={resolve:e,reject:t}}));try{const a=C(r);v().beginInvokeDotNetFromJS(o,e,t,n,a)}catch(e){g(o,!1,e)}return i}function v(){if(null!==u)return u;throw new Error("No .NET call dispatcher has been set.")}function g(e,t,n){if(!a.hasOwnProperty(e))throw new Error(`There is no pending async call with ID ${e}.`);const r=a[e];delete a[e],t?r.resolve(n):r.reject(n)}function b(e){return e instanceof Error?`${e.message}\n${e.stack}`:e?e.toString():"null"}function y(e,t){let n=i[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 i[e]}e.attachDispatcher=function(e){u=e},e.attachReviver=d,e.invokeMethod=function(e,t,...n){return p(e,t,null,n)},e.invokeMethodAsync=function(e,t,...n){return m(e,t,null,n)},e.createJSObjectReference=h,e.disposeJSObjectReference=function(e){const t=e&&e.__jsObjectId;"number"==typeof t&&E(t)},function(e){e[e.Default=0]="Default",e[e.JSObjectReference=1]="JSObjectReference"}(s=e.JSCallResultType||(e.JSCallResultType={})),e.jsCallDispatcher={findJSFunction:y,disposeJSObjectReferenceById:E,invokeJSFromDotNet:(e,t,n,r)=>{const o=S(y(e,r).apply(null,f(t)),n);return null==o?null:C(o)},beginInvokeJSFromDotNet:(e,t,n,r,o)=>{const a=new Promise((e=>{e(y(t,o).apply(null,f(n)))}));e&&a.then((t=>v().endInvokeJSFromDotNet(e,!0,C([e,!0,S(t,r)]))),(t=>v().endInvokeJSFromDotNet(e,!1,JSON.stringify([e,!1,b(t)]))))},endInvokeDotNetFromJS:(e,t,n)=>{const r=t?f(n):new Error(n);g(parseInt(e),t,r)},receiveByteArray:(e,t)=>{n.set(e,t)}};class w{constructor(e){this._id=e}invokeMethod(e,...t){return p(null,e,this._id,t)}invokeMethodAsync(e,...t){return m(null,e,this._id,t)}dispose(){m(null,"__Dispose",this._id,null).catch((e=>console.error(e)))}serializeAsArg(){return{__dotNetObject:this._id}}}const I="__byte[]";function S(e,t){switch(t){case s.Default:return e;case s.JSObjectReference:return h(e);default:throw new Error(`Invalid JS call result type '${t}'.`)}}d((function(e,t){if(t&&"object"==typeof t){if(t.hasOwnProperty("__dotNetObject"))return new w(t.__dotNetObject);if(t.hasOwnProperty(o)){const e=t.__jsObjectId,n=i[e];if(n)return n.getWrappedObject();throw new Error(`JS object instance with Id '${e}' does not exist. It may have been disposed.`)}if(t.hasOwnProperty(I)){const e=t["__byte[]"],r=n.get(e);if(void 0===r)throw new Error(`Byte array index '${e}' does not exist.`);return r}}return t}));let D=0;function C(e){return D=0,JSON.stringify(e,A)}function A(e,t){if(t instanceof w)return t.serializeAsArg();if(t instanceof Uint8Array){u.sendByteArray(D,t);const e={[I]:D};return D++,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"}(n||(n={}));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}}let o;function a(e,t){if(!o)throw new Error("eventDispatcher not initialized. Call 'setEventDispatcher' to configure it.");o(e,t)}const i=new Map,s=new Map,c={createEventArgs:()=>({})},l=[];function u(e){return i.get(e)}function d(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 f(e){const t=[];for(let n=0;n{return{...p(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"],c),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};var t}}),h(["contextmenu","click","mouseover","mouseout","mousemove","mousedown","mouseup","dblclick"],{createEventArgs:e=>p(e)}),h(["error"],{createEventArgs:e=>{return{message:(t=e).message,filename:t.filename,lineno:t.lineno,colno:t.colno};var t}}),h(["loadstart","timeout","abort","load","loadend","progress"],{createEventArgs:e=>{return{lengthComputable:(t=e).lengthComputable,loaded:t.loaded,total:t.total};var t}}),h(["touchcancel","touchend","touchmove","touchenter","touchleave","touchstart"],{createEventArgs:e=>{return{detail:(t=e).detail,touches:f(t.touches),targetTouches:f(t.targetTouches),changedTouches:f(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{...p(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{...p(t=e),deltaX:t.deltaX,deltaY:t.deltaY,deltaZ:t.deltaZ,deltaMode:t.deltaMode};var t}}),h(["toggle"],c);const m=["date","datetime-local","month","time","week"],v=I(["abort","blur","change","error","focus","load","loadend","loadstart","mouseenter","mouseleave","progress","reset","scroll","submit","unload","toggle","DOMNodeInsertedIntoDocument","DOMNodeRemovedFromDocument"]),g={submit:!0},b=I(["click","dblclick","mousedown","mousemove","mouseup"]);class y{constructor(e){this.browserRendererId=e,this.afterClickCallbacks=[];const t=++y.nextEventDelegatorId;this.eventsCollectionKey=`_blazorEvents_${t}`,this.eventInfoStore=new E(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){let n=t.target,o=null,i=!1;const s=v.hasOwnProperty(e);let c=!1;for(;n;){const h=this.getEventHandlerInfosForElement(n,!1);if(h){const s=h.getHandler(e);if(s&&(l=n,d=t.type,!((l instanceof HTMLButtonElement||l instanceof HTMLInputElement||l instanceof HTMLTextAreaElement||l instanceof HTMLSelectElement)&&b.hasOwnProperty(d)&&l.disabled))){if(!i){const n=u(e);o=(null==n?void 0:n.createEventArgs)?n.createEventArgs(t):{},i=!0}g.hasOwnProperty(t.type)&&t.preventDefault(),a({browserRendererId:this.browserRendererId,eventHandlerId:s.eventHandlerId,eventName:e,eventFieldInfo:r.fromEvent(s.renderingComponentId,t)},o)}h.stopPropagation(e)&&(c=!0),h.preventDefault(e)&&t.preventDefault()}n=s||c?null:n.parentElement}var l,d}getEventHandlerInfosForElement(e,t){return e.hasOwnProperty(this.eventsCollectionKey)?e[this.eventsCollectionKey]:t?e[this.eventsCollectionKey]=new w:null}}y.nextEventDelegatorId=0;class E{constructor(e){this.globalListener=e,this.infosByEventHandlerId={},this.countByEventName={},l.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=d(e),this.countByEventName.hasOwnProperty(e))this.countByEventName[e]++;else{this.countByEventName[e]=1;const t=v.hasOwnProperty(e);document.addEventListener(e,this.globalListener,t)}}update(e,t){if(this.infosByEventHandlerId.hasOwnProperty(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=d(t.eventName);0==--this.countByEventName[n]&&(delete this.countByEventName[n],document.removeEventListener(n,this.globalListener))}return t}handleEventNameAliasAdded(e,t){if(this.countByEventName.hasOwnProperty(e)){const n=this.countByEventName[e];delete this.countByEventName[e],document.removeEventListener(e,this.globalListener),this.addGlobalListener(t),this.countByEventName[t]+=n-1}}}class w{constructor(){this.handlers={},this.preventDefaultFlags=null,this.stopPropagationFlags=null}getHandler(e){return this.handlers.hasOwnProperty(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 I(e){const t={};return e.forEach((e=>{t[e]=!0})),t}const S=M("_blazorLogicalChildren"),D=M("_blazorLogicalParent"),C=M("_blazorLogicalEnd");function A(e,t){if(e.childNodes.length>0&&!t)throw new Error("New logical elements must start empty, or allowExistingContents must be true");return S in e||(e[S]=[]),e}function T(e,t){const n=document.createComment("!");return N(n,e,t),n}function N(e,t,n){const r=e;if(e instanceof Comment&&O(r)&&O(r).length>0)throw new Error("Not implemented: inserting non-empty logical container");if(R(r))throw new Error("Not implemented: moving existing logical children");const o=O(t);if(n0;)k(n,0)}const r=n;r.parentNode.removeChild(r)}function R(e){return e[D]||null}function F(e,t){return O(e)[t]}function _(e){var t=P(e);return"http://www.w3.org/2000/svg"===t.namespaceURI&&"foreignObject"!==t.tagName}function O(e){return e[S]}function x(e,t){const n=O(e);t.forEach((e=>{e.moveRangeStart=n[e.fromSiblingIndex],e.moveRangeEnd=H(e.moveRangeStart)})),t.forEach((t=>{const r=t.moveToBeforeMarker=document.createComment("marker"),o=n[t.toSiblingIndex+1];o?o.parentNode.insertBefore(r,o):B(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 P(e){if(e instanceof Element)return e;if(e instanceof Comment)return e.parentNode;throw new Error("Not a valid logical element")}function L(e){const t=O(R(e));return t[Array.prototype.indexOf.call(t,e)+1]||null}function B(e,t){if(t instanceof Element)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=L(t);n?n.parentNode.insertBefore(e,n):B(e,R(t))}}}function H(e){if(e instanceof Element)return e;const t=L(e);if(t)return t.previousSibling;{const t=R(e);return t instanceof Element?t.lastChild:H(t)}}function M(e){return"function"==typeof Symbol?Symbol():e}function U(e){return`_bl_${e}`}e.attachReviver(((e,t)=>t&&"object"==typeof t&&t.hasOwnProperty("__internalId")&&"string"==typeof t.__internalId?function(e){const t=`[${U(e)}]`;return document.querySelector(t)}(t.__internalId):t));const j="_blazorSelectValue",J=document.createElement("template"),$=document.createElementNS("http://www.w3.org/2000/svg","g"),K={},z="__internal_",V="preventDefault_",X="stopPropagation_";class Y{constructor(e){this.childComponentLocations={},this.eventDelegator=new y(e),this.eventDelegator.notifyAfterClick((e=>{if(!ee)return;if(0!==e.button||function(e){return e.ctrlKey||e.shiftKey||e.altKey||e.metaKey}(e))return;if(e.defaultPrevented)return;const t=function(e){const t=!window._blazorDisableComposedPath&&e.composedPath&&e.composedPath();if(t){for(let e=0;eie(!1))))},enableNavigationInterception:function(){ee=!0},navigateTo:oe,getBaseURI:()=>document.baseURI,getLocationHref:()=>location.href};function oe(e,t,n=!1){const r=ce(e);if(!t&&ue(r))ae(r,!1,n);else if(t&&location.href===e){const t=e+"?";history.replaceState(null,"",t),location.replace(e)}else n?history.replaceState(null,"",r):location.href=e}function ae(e,t,n=!1){Q=!0,n?history.replaceState(null,"",e):history.pushState(null,"",e),ie(t)}async function ie(e){ne&&await ne(location.href,e)}let se;function ce(e){return se=se||document.createElement("a"),se.href=e,se.href}function le(e,t){return e?e.tagName===t?e:le(e.parentElement,t):null}function ue(e){const t=(n=document.baseURI).substr(0,n.lastIndexOf("/")+1);var n;return e.startsWith(t)}const de={init:function(e,t,n,r=50){const o=fe(t);(o||document.documentElement).style.overflowAnchor="none";const a=new IntersectionObserver((function(r){r.forEach((r=>{var o;if(!r.isIntersecting)return;const a=t.getBoundingClientRect(),i=n.getBoundingClientRect().top-a.bottom,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`});a.observe(t),a.observe(n);const i=c(t),s=c(n);function c(e){const t=new MutationObserver((()=>{a.unobserve(e),a.observe(e)}));return t.observe(e,{attributes:!0}),t}he[e._id]={intersectionObserver:a,mutationObserverBefore:i,mutationObserverAfter:s}},dispose:function(e){const t=he[e._id];t&&(t.intersectionObserver.disconnect(),t.mutationObserverBefore.disconnect(),t.mutationObserverAfter.disconnect(),e.dispose(),delete he[e._id])}},he={};function fe(e){return e?"visible"!==getComputedStyle(e).overflowY?e:fe(e.parentElement):null}const pe={navigateTo:oe,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]),l.forEach((n=>n(e,t.browserEventName)))}i.set(e,t)},_internal:{navigationManager:re,domWrapper:{focus:function(e,t){if(!(e instanceof HTMLElement))throw new Error("Unable to focus an invalid element.");e.focus({preventScroll:t})}},Virtualize:de}};window.Blazor=pe;let me=!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("")},be=Math.pow(2,32),ye=Math.pow(2,21)-1;function Ee(e,t){return e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24}function we(e,t){return e[t]+(e[t+1]<<8)+(e[t+2]<<16)+(e[t+3]<<24>>>0)}function Ie(e,t){const n=we(e,t+4);if(n>ye)throw new Error(`Cannot read uint64 with high order part ${n}, because the result would exceed Number.MAX_SAFE_INTEGER.`);return n*be+we(e,t)}class Se{constructor(e){this.batchData=e;const t=new Te(e);this.arrayRangeReader=new Ne(e),this.arrayBuilderSegmentReader=new ke(e),this.diffReader=new De(e),this.editReader=new Ce(e,t),this.frameReader=new Ae(e,t)}updatedComponents(){return Ee(this.batchData,this.batchData.length-20)}referenceFrames(){return Ee(this.batchData,this.batchData.length-16)}disposedComponentIds(){return Ee(this.batchData,this.batchData.length-12)}disposedEventHandlerIds(){return Ee(this.batchData,this.batchData.length-8)}updatedComponentsEntry(e,t){const n=e+4*t;return Ee(this.batchData,n)}referenceFramesEntry(e,t){return e+20*t}disposedComponentIdsEntry(e,t){const n=e+4*t;return Ee(this.batchData,n)}disposedEventHandlerIdsEntry(e,t){const n=e+8*t;return Ie(this.batchData,n)}}class De{constructor(e){this.batchDataUint8=e}componentId(e){return Ee(this.batchDataUint8,e)}edits(e){return e+4}editsEntry(e,t){return e+16*t}}class Ce{constructor(e,t){this.batchDataUint8=e,this.stringReader=t}editType(e){return Ee(this.batchDataUint8,e)}siblingIndex(e){return Ee(this.batchDataUint8,e+4)}newTreeIndex(e){return Ee(this.batchDataUint8,e+8)}moveToSiblingIndex(e){return Ee(this.batchDataUint8,e+8)}removedAttributeName(e){const t=Ee(this.batchDataUint8,e+12);return this.stringReader.readString(t)}}class Ae{constructor(e,t){this.batchDataUint8=e,this.stringReader=t}frameType(e){return Ee(this.batchDataUint8,e)}subtreeLength(e){return Ee(this.batchDataUint8,e+4)}elementReferenceCaptureId(e){const t=Ee(this.batchDataUint8,e+4);return this.stringReader.readString(t)}componentId(e){return Ee(this.batchDataUint8,e+8)}elementName(e){const t=Ee(this.batchDataUint8,e+8);return this.stringReader.readString(t)}textContent(e){const t=Ee(this.batchDataUint8,e+4);return this.stringReader.readString(t)}markupContent(e){const t=Ee(this.batchDataUint8,e+4);return this.stringReader.readString(t)}attributeName(e){const t=Ee(this.batchDataUint8,e+4);return this.stringReader.readString(t)}attributeValue(e){const t=Ee(this.batchDataUint8,e+8);return this.stringReader.readString(t)}attributeEventHandlerId(e){return Ie(this.batchDataUint8,e+12)}}class Te{constructor(e){this.batchDataUint8=e,this.stringTableStartIndex=Ee(e,e.length-4)}readString(e){if(-1===e)return null;{const n=Ee(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)<{!function(e,t,n){const r=document.querySelector(e);if(!r)throw new Error(`Could not find any element matching selector '${e}'.`);!function(e,t,n){let r=Z[0];r||(r=Z[0]=new Y(0)),r.attachRootComponentToLogicalElement(n,t)}(0,A(r,!0),t)}(t,e)},RenderBatch:(e,t)=>{try{const n=Me(t);(function(e,t){const n=Z[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{Fe=!0,console.error(`${e}\n${t}`),async function(){let e=document.querySelector("#blazor-error-ui");e&&(e.style.display="block"),me||(me=!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:e.jsCallDispatcher.beginInvokeJSFromDotNet,EndInvokeDotNet:e.jsCallDispatcher.endInvokeDotNetFromJS,SendByteArrayToJS:He,Navigate:re.navigateTo};window.external.receiveMessage((e=>{const n=function(e){if(Fe||!e||!e.startsWith(Re))return null;const t=e.substring(Re.length),[n,...r]=JSON.parse(t);return{messageType:n,args:r}}(e);if(n){if(!t.hasOwnProperty(n.messageType))throw new Error(`Unsupported IPC message type '${n.messageType}'`);t[n.messageType].apply(null,n.args)}}))}(),e.attachDispatcher({beginInvokeDotNetFromJS:Oe,endInvokeJSFromDotNet:xe,sendByteArray:Pe}),pe._internal.InputFile=Ue,re.enableNavigationInterception(),re.listenForNavigationEvents(Le),Be("AttachPage",re.getBaseURI(),re.getLocationHref())}o=function(e,t){Be("DispatchBrowserEvent",e,t)},pe.start=Ke,document&&document.currentScript&&"false"!==document.currentScript.getAttribute("autostart")&&Ke()})(); \ No newline at end of file diff --git a/src/Components/Web.JS/src/Boot.Server.ts b/src/Components/Web.JS/src/Boot.Server.ts index d559adc400a4..bc76ab80d029 100644 --- a/src/Components/Web.JS/src/Boot.Server.ts +++ b/src/Components/Web.JS/src/Boot.Server.ts @@ -122,6 +122,66 @@ async function initializeConnection(options: CircuitStartOptions, logger: Logger Blazor._internal.forceCloseConnection = () => connection.stop(); + Blazor._internal.sendJSDataStream = async (data: ArrayBufferView, streamId: string) => { + // Run the rest in the background, without delaying the completion of the call to sendJSDataStream + // otherwise we'll deadlock (.NET can't begin reading until this completes, but it won't complete + // because nobody's reading the pipe) + setTimeout(async () => { + const maxMillisecondsBetweenAcks = 500; + let numChunksUntilNextAck = 5; + let lastAckTime = new Date().valueOf(); + try { + const chunkSize = 31*1024; // TODO: Should this somehow auto-match the SignalR max message size, minus some overhead? + let position = 0; + while (position < data.byteLength) { + // TODO: Doesn't the JS side receive any backpressure indication? We're just pushing it all here. + // TODO: What about cancellation? If the .NET-side JSDataStream gets disposed, then ideally we'd + // receive a message telling us to stop processing the stream with that streamId, and would + // stop sending the data. + const nextChunkSize = Math.min(chunkSize, data.byteLength - position); + console.log(`Sending a chunk of length ${nextChunkSize}`); + const nextChunkData = new Uint8Array(data.buffer, data.byteOffset + position, nextChunkSize); + + + numChunksUntilNextAck--; + if (numChunksUntilNextAck > 1) { + // Most of the time just send and buffer within the network layer + await connection.send('SupplyJSDataChunk', streamId, nextChunkData, null); + } else { + // But regularly, wait for an ACK, so other events can be interleaved + // The use of "invoke" (not "send") here is what prevents the JS side from queuing up chunks + // faster than the .NET side can receive them. It means that if there are other user interactions + // while the transfer is in progress, they would get inserted in the middle, so it would be + // possible to navigate away or cancel without first waiting for all the remaining chunks. + await connection.invoke('SupplyJSDataChunk', streamId, nextChunkData, null); + + // Estimate the number of chunks we should send before the next ack to achieve the desired + // interactivity rate + const timeNow = new Date().valueOf(); + const msSinceAck = timeNow - lastAckTime; + lastAckTime = timeNow; + numChunksUntilNextAck = Math.max(1, Math.round(maxMillisecondsBetweenAcks / msSinceAck)); + } + + position += nextChunkSize; + + // Somehow we need to delay sending the next item until the actual network transfer for the preceding + // one completed. Otherwise we'll just queue them all up instantly, which is too problematic because + // it prevents all other user interactions while the transfer is in progress. For example, this makes + // it impossible to have a "cancel" button. We need to give priority to all other events, which would + // be achievable if we didn't dispatch the next chunk until the previous one finished, because then + // any other events would already be queued. + // + // One way to do this would be *not* using SignalR streaming at all, but rather having a "pull" + // model like the existing . It would be slower, but the .NET side could request each + // chunk in turn once it's received the last one. That would also give cancellation for free. + } + } catch (error) { + await connection.send('SupplyJSDataChunk', streamId, null, error.toString()); + } + }, 0); + }; + try { await connection.start(); } catch (ex) { diff --git a/src/Components/Web.JS/src/GlobalExports.ts b/src/Components/Web.JS/src/GlobalExports.ts index b2cf1bf0d762..0b163cbdd792 100644 --- a/src/Components/Web.JS/src/GlobalExports.ts +++ b/src/Components/Web.JS/src/GlobalExports.ts @@ -48,7 +48,8 @@ interface IBlazor { getLazyAssemblies?: any dotNetCriticalError?: any getSatelliteAssemblies?: any, - applyHotReload?: (id: string, metadataDelta: string, ilDelta: string) => void + applyHotReload?: (id: string, metadataDelta: string, ilDelta: string) => void, + sendJSDataStream?: (data: any, streamId: string) => void, } } diff --git a/src/Components/Web.JS/src/InputFile.ts b/src/Components/Web.JS/src/InputFile.ts index 0a29237b664e..8a69fd4e8d97 100644 --- a/src/Components/Web.JS/src/InputFile.ts +++ b/src/Components/Web.JS/src/InputFile.ts @@ -101,9 +101,9 @@ async function ensureArrayBufferReadyForSharedMemoryInterop(elem: InputElement, getFileById(elem, fileId).arrayBuffer = arrayBuffer; } -async function readFileData(elem: InputElement, fileId: number, startOffset: number, count: number): Promise { +async function readFileData(elem: InputElement, fileId: number): Promise { const arrayBuffer = await getArrayBufferFromFileAsync(elem, fileId); - return new Uint8Array(arrayBuffer, startOffset, count); + return new Uint8Array(arrayBuffer); } export function getFileById(elem: InputElement, fileId: number): BrowserFile { diff --git a/src/Components/Web/src/Forms/InputFile.cs b/src/Components/Web/src/Forms/InputFile.cs index 92b3f5162af3..637366cfa6db 100644 --- a/src/Components/Web/src/Forms/InputFile.cs +++ b/src/Components/Web/src/Forms/InputFile.cs @@ -81,10 +81,10 @@ protected override void BuildRenderTree(RenderTreeBuilder builder) builder.CloseElement(); } - internal Stream OpenReadStream(BrowserFile file, CancellationToken cancellationToken) + internal Stream OpenReadStream(BrowserFile file, long maxAllowedSize, CancellationToken cancellationToken) => _jsUnmarshalledRuntime != null ? - (Stream)new SharedBrowserFileStream(JSRuntime, _jsUnmarshalledRuntime, _inputFileElement, file) : - new RemoteBrowserFileStream(JSRuntime, _inputFileElement, file, Options.Value, cancellationToken); + new SharedBrowserFileStream(JSRuntime, _jsUnmarshalledRuntime, _inputFileElement, file) : + new RemoteBrowserFileStream(JSRuntime, _inputFileElement, file, Options.Value, maxAllowedSize, cancellationToken); internal async ValueTask ConvertToImageFileAsync(BrowserFile file, string format, int maxWidth, int maxHeight) { diff --git a/src/Components/Web/src/Forms/InputFile/BrowserFile.cs b/src/Components/Web/src/Forms/InputFile/BrowserFile.cs index 09b7a54283fc..92f62cabd9ce 100644 --- a/src/Components/Web/src/Forms/InputFile/BrowserFile.cs +++ b/src/Components/Web/src/Forms/InputFile/BrowserFile.cs @@ -44,7 +44,7 @@ public Stream OpenReadStream(long maxAllowedSize = 512000, CancellationToken can throw new IOException($"Supplied file with size {Size} bytes exceeds the maximum of {maxAllowedSize} bytes."); } - return Owner.OpenReadStream(this, cancellationToken); + return Owner.OpenReadStream(this, maxAllowedSize, cancellationToken); } } } diff --git a/src/Components/Web/src/Forms/InputFile/RemoteBrowserFileStream.cs b/src/Components/Web/src/Forms/InputFile/RemoteBrowserFileStream.cs index 2616ecef0ca6..bd726531ae74 100644 --- a/src/Components/Web/src/Forms/InputFile/RemoteBrowserFileStream.cs +++ b/src/Components/Web/src/Forms/InputFile/RemoteBrowserFileStream.cs @@ -2,9 +2,7 @@ // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; -using System.Buffers; -using System.IO.Pipelines; -using System.Text.Json; +using System.IO; using System.Threading; using System.Threading.Tasks; using Microsoft.JSInterop; @@ -15,118 +13,46 @@ internal class RemoteBrowserFileStream : BrowserFileStream { private readonly IJSRuntime _jsRuntime; private readonly ElementReference _inputFileElement; - private readonly int _maxSegmentSize; - private readonly PipeReader _pipeReader; - private readonly CancellationTokenSource _fillBufferCts; - private readonly TimeSpan _segmentFetchTimeout; + private readonly long _maxAllowedSize; + private readonly CancellationTokenSource _openRedStreamCts; + private readonly Task OpenReadStreamTask; - private bool _isReadingCompleted; private bool _isDisposed; + private CancellationTokenSource? _copyFileDataCts; public RemoteBrowserFileStream( IJSRuntime jsRuntime, ElementReference inputFileElement, BrowserFile file, RemoteBrowserFileStreamOptions options, + long maxAllowedSize, CancellationToken cancellationToken) : base(file) { _jsRuntime = jsRuntime; _inputFileElement = inputFileElement; - _maxSegmentSize = options.MaxSegmentSize; - _segmentFetchTimeout = options.SegmentFetchTimeout; + _maxAllowedSize = maxAllowedSize; + _openRedStreamCts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); - var pipe = new Pipe(new PipeOptions(pauseWriterThreshold: options.MaxBufferSize, resumeWriterThreshold: options.MaxBufferSize)); - _pipeReader = pipe.Reader; - _fillBufferCts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); - - _ = FillBuffer(pipe.Writer, _fillBufferCts.Token); + OpenReadStreamTask = OpenReadStreamAsync(options, _openRedStreamCts.Token); } - private async Task FillBuffer(PipeWriter writer, CancellationToken cancellationToken) + private async Task OpenReadStreamAsync(RemoteBrowserFileStreamOptions options, CancellationToken cancellationToken) { - long offset = 0; - - while (offset < File.Size) - { - var pipeBuffer = writer.GetMemory(_maxSegmentSize); - var segmentSize = (int)Math.Min(_maxSegmentSize, File.Size - offset); - - try - { - using var readSegmentCts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); - readSegmentCts.CancelAfter(_segmentFetchTimeout); - - var bytes = await _jsRuntime.InvokeAsync( - InputFileInterop.ReadFileData, - readSegmentCts.Token, - _inputFileElement, - File.Id, - offset, - segmentSize); - - if (bytes is null || bytes.Length != segmentSize) - { - throw new InvalidOperationException( - $"A segment with size {bytes?.Length ?? 0} bytes was received, but {segmentSize} bytes were expected."); - } + var dataReference = await _jsRuntime.InvokeAsync( + InputFileInterop.ReadFileData, + cancellationToken, + _inputFileElement, + File.Id); - bytes.CopyTo(pipeBuffer); - writer.Advance(segmentSize); - offset += segmentSize; - - var result = await writer.FlushAsync(cancellationToken); - - if (result.IsCompleted) - { - break; - } - } - catch (Exception e) - { - await writer.CompleteAsync(e); - return; - } - } - - await writer.CompleteAsync(); + return await dataReference.OpenReadStreamAsync(_maxAllowedSize, options.MaxBufferSize, cancellationToken); } protected override async ValueTask CopyFileDataIntoBuffer(long sourceOffset, Memory destination, CancellationToken cancellationToken) { - if (_isReadingCompleted) - { - return 0; - } - - int totalBytesCopied = 0; - - while (destination.Length > 0) - { - var result = await _pipeReader.ReadAsync(cancellationToken); - var bytesToCopy = (int)Math.Min(result.Buffer.Length, destination.Length); - - if (bytesToCopy == 0) - { - if (result.IsCompleted) - { - _isReadingCompleted = true; - await _pipeReader.CompleteAsync(); - } - - break; - } - - var slice = result.Buffer.Slice(0, bytesToCopy); - slice.CopyTo(destination.Span); - - _pipeReader.AdvanceTo(slice.End); - - totalBytesCopied += bytesToCopy; - destination = destination.Slice(bytesToCopy); - } - - return totalBytesCopied; + var stream = await OpenReadStreamTask; + _copyFileDataCts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); + return await stream.ReadAsync(destination, _copyFileDataCts.Token); } protected override void Dispose(bool disposing) @@ -136,7 +62,8 @@ protected override void Dispose(bool disposing) return; } - _fillBufferCts.Cancel(); + _openRedStreamCts.Cancel(); + _copyFileDataCts?.Cancel(); _isDisposed = true; diff --git a/src/Components/WebAssembly/JSInterop/src/WebAssemblyJSObjectReferenceJsonConverter.cs b/src/Components/WebAssembly/JSInterop/src/WebAssemblyJSObjectReferenceJsonConverter.cs index 5b2f12f54bed..04fe3972da4f 100644 --- a/src/Components/WebAssembly/JSInterop/src/WebAssemblyJSObjectReferenceJsonConverter.cs +++ b/src/Components/WebAssembly/JSInterop/src/WebAssemblyJSObjectReferenceJsonConverter.cs @@ -27,7 +27,7 @@ public override bool CanConvert(Type typeToConvert) public override IJSObjectReference? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { - var id = JSObjectReferenceJsonWorker.ReadJSObjectReferenceIdentifier(ref reader); + var (id, _) = JSObjectReferenceJsonWorker.ReadJSObjectReferenceIdentifier(ref reader); return new WebAssemblyJSObjectReference(_jsRuntime, id); } diff --git a/src/JSInterop/Microsoft.JSInterop.JS/src/src/Microsoft.JSInterop.ts b/src/JSInterop/Microsoft.JSInterop.JS/src/src/Microsoft.JSInterop.ts index c45b09fb70fd..901402a0daec 100644 --- a/src/JSInterop/Microsoft.JSInterop.JS/src/src/Microsoft.JSInterop.ts +++ b/src/JSInterop/Microsoft.JSInterop.JS/src/src/Microsoft.JSInterop.ts @@ -49,6 +49,7 @@ export module DotNet { } const jsObjectIdKey = "__jsObjectId"; + const jsDataReferenceLengthKey = "__jsDataReferenceLength"; const pendingAsyncCalls: { [id: number]: PendingAsyncCall } = {}; const windowJSObjectId = 0; @@ -126,10 +127,16 @@ export module DotNet { if (jsObject && typeof jsObject === 'object') { cachedJSObjectsById[nextJsObjectId] = new JSObject(jsObject); - const result = { + let result: any = { [jsObjectIdKey]: nextJsObjectId }; + // Check if this is an ArrayBufferView, and if so also provide the length of + // the buffer to be used for the JSDataReference. + if (jsObject.buffer instanceof ArrayBuffer && jsObject.byteLength !== undefined) { + result[jsDataReferenceLengthKey] = jsObject.byteLength; + } + nextJsObjectId++; return result; diff --git a/src/JSInterop/Microsoft.JSInterop/src/IJSDataReference.cs b/src/JSInterop/Microsoft.JSInterop/src/IJSDataReference.cs new file mode 100644 index 000000000000..d98133e9d84f --- /dev/null +++ b/src/JSInterop/Microsoft.JSInterop/src/IJSDataReference.cs @@ -0,0 +1,30 @@ +// Copyright (c) .NET Foundation. All rights reserved. +// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. + +using System; +using System.IO; +using System.Threading; +using System.Threading.Tasks; + +namespace Microsoft.JSInterop +{ + /// + /// Represents a reference to JavaScript data to be consumed through a stream. + /// + public interface IJSDataReference : IAsyncDisposable + { + /// + /// Length of the stream provided by JS. + /// + public long Length { get; } + + /// + /// Initiatializes a with the for the current data reference. + /// + /// Maximum number of bytes permitted to be read from JS. + /// Amount of bytes to buffer before flushing. + /// for cancelling read. + /// Stream which can provide data associated with the current data reference. + public Task OpenReadStreamAsync(long maxAllowedSize = 512000, long maxBufferSize = 100 * 1024, CancellationToken cancellationToken = default); + } +} diff --git a/src/JSInterop/Microsoft.JSInterop/src/Implementation/JSDataReference.cs b/src/JSInterop/Microsoft.JSInterop/src/Implementation/JSDataReference.cs new file mode 100644 index 000000000000..e20126714e17 --- /dev/null +++ b/src/JSInterop/Microsoft.JSInterop/src/Implementation/JSDataReference.cs @@ -0,0 +1,49 @@ +// Copyright (c) .NET Foundation. All rights reserved. +// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. + +using System; +using System.IO; +using System.Threading; +using System.Threading.Tasks; + +namespace Microsoft.JSInterop.Implementation +{ + /// + /// Implements functionality for . + /// + public class JSDataReference : JSObjectReference, IJSDataReference + { + private readonly JSRuntime _jsRuntime; + + /// + public long Length { get; private set; } + + /// + /// Inititializes a new instance. + /// + /// The used for invoking JS interop calls. + /// The unique identifier. + /// The length of the data stream coming from JS represented by this data reference. + protected internal JSDataReference(JSRuntime jsRuntime, long id, long totalLength) : base(jsRuntime, id) + { + if (totalLength <= 0) + { + throw new InvalidOperationException($"The incoming data stream of length {totalLength} cannot be empty."); + } + + _jsRuntime = jsRuntime; + Length = totalLength; + } + + /// + async Task IJSDataReference.OpenReadStreamAsync(long maxLength, long maxBufferSize, CancellationToken cancellationToken) + { + if (Length > maxLength) + { + throw new InvalidOperationException($"The incoming data stream of length {Length} exceeds the maximum length {maxLength}."); + } + + return await _jsRuntime.ReadJSDataAsStreamAsync(this, Length, maxBufferSize, cancellationToken); + } + } +} diff --git a/src/JSInterop/Microsoft.JSInterop/src/Implementation/JSObjectReference.cs b/src/JSInterop/Microsoft.JSInterop/src/Implementation/JSObjectReference.cs index f4736c049d9e..483311290457 100644 --- a/src/JSInterop/Microsoft.JSInterop/src/Implementation/JSObjectReference.cs +++ b/src/JSInterop/Microsoft.JSInterop/src/Implementation/JSObjectReference.cs @@ -3,6 +3,8 @@ using System; using System.Diagnostics.CodeAnalysis; +using System.IO; +using System.IO.Pipelines; using System.Threading; using System.Threading.Tasks; using static Microsoft.AspNetCore.Internal.LinkerFlags; @@ -12,6 +14,8 @@ namespace Microsoft.JSInterop.Implementation /// /// Implements functionality for . /// + // Note that the same concrete implementation can represent either an object or a data reference. Developers + // work in terms of the interfaces which indicate the set of method it's useful to call. public class JSObjectReference : IJSObjectReference { private readonly JSRuntime _jsRuntime; diff --git a/src/JSInterop/Microsoft.JSInterop/src/Implementation/JSObjectReferenceJsonWorker.cs b/src/JSInterop/Microsoft.JSInterop/src/Implementation/JSObjectReferenceJsonWorker.cs index c22f60a17056..40bc520053aa 100644 --- a/src/JSInterop/Microsoft.JSInterop/src/Implementation/JSObjectReferenceJsonWorker.cs +++ b/src/JSInterop/Microsoft.JSInterop/src/Implementation/JSObjectReferenceJsonWorker.cs @@ -6,33 +6,40 @@ namespace Microsoft.JSInterop.Implementation { /// - /// Used by JsonConverters to read or write a IJSObjectReference instance. + /// Used by JsonConverters to read or write a or instance. /// /// This type is part of ASP.NET Core's internal infrastructure and is not recommended for use by external code. /// /// public static class JSObjectReferenceJsonWorker { - private static readonly JsonEncodedText _idKey = JsonEncodedText.Encode("__jsObjectId"); + private static readonly JsonEncodedText _jsObjectIdKey = JsonEncodedText.Encode("__jsObjectId"); + private static readonly JsonEncodedText _jsDataReferenceLengthKey = JsonEncodedText.Encode("__jsDataReferenceLength"); /// /// Reads the id for a instance. /// /// The /// - public static long ReadJSObjectReferenceIdentifier(ref Utf8JsonReader reader) + public static (long, long) ReadJSObjectReferenceIdentifier(ref Utf8JsonReader reader) { long id = -1; + long length = -1; while (reader.Read() && reader.TokenType != JsonTokenType.EndObject) { if (reader.TokenType == JsonTokenType.PropertyName) { - if (id == -1 && reader.ValueTextEquals(_idKey.EncodedUtf8Bytes)) + if (id == -1 && reader.ValueTextEquals(_jsObjectIdKey.EncodedUtf8Bytes)) { reader.Read(); id = reader.GetInt64(); } + else if (length == -1 && reader.ValueTextEquals(_jsDataReferenceLengthKey.EncodedUtf8Bytes)) + { + reader.Read(); + length = reader.GetInt64(); + } else { throw new JsonException($"Unexcepted JSON property {reader.GetString()}."); @@ -46,10 +53,10 @@ public static long ReadJSObjectReferenceIdentifier(ref Utf8JsonReader reader) if (id == -1) { - throw new JsonException($"Required property {_idKey} not found."); + throw new JsonException($"Required property {_jsObjectIdKey} not found."); } - return id; + return (id, length); } /// @@ -60,7 +67,7 @@ public static long ReadJSObjectReferenceIdentifier(ref Utf8JsonReader reader) public static void WriteJSObjectReference(Utf8JsonWriter writer, JSObjectReference objectReference) { writer.WriteStartObject(); - writer.WriteNumber(_idKey, objectReference.Id); + writer.WriteNumber(_jsObjectIdKey, objectReference.Id); writer.WriteEndObject(); } } diff --git a/src/JSInterop/Microsoft.JSInterop/src/Infrastructure/JSDataReferenceJsonConverter.cs b/src/JSInterop/Microsoft.JSInterop/src/Infrastructure/JSDataReferenceJsonConverter.cs new file mode 100644 index 000000000000..f4a85ede9e13 --- /dev/null +++ b/src/JSInterop/Microsoft.JSInterop/src/Infrastructure/JSDataReferenceJsonConverter.cs @@ -0,0 +1,40 @@ +// Copyright (c) .NET Foundation. All rights reserved. +// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. + +using System; +using System.Text.Json; +using System.Text.Json.Serialization; +using Microsoft.JSInterop.Implementation; + +namespace Microsoft.JSInterop.Infrastructure +{ + internal sealed class JSDataReferenceJsonConverter : JsonConverter + { + private readonly JSRuntime _jsRuntime; + + public JSDataReferenceJsonConverter(JSRuntime jsRuntime) + { + _jsRuntime = jsRuntime; + } + + public override bool CanConvert(Type typeToConvert) + => typeToConvert == typeof(IJSDataReference) || typeToConvert == typeof(JSDataReference); + + public override IJSDataReference? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + var (id, length) = JSObjectReferenceJsonWorker.ReadJSObjectReferenceIdentifier(ref reader); + + if (length == -1) + { + throw new JsonException($"Required property __jsDataReferenceLength not found."); + } + + return new JSDataReference(_jsRuntime, id, length); + } + + public override void Write(Utf8JsonWriter writer, IJSDataReference value, JsonSerializerOptions options) + { + JSObjectReferenceJsonWorker.WriteJSObjectReference(writer, (JSDataReference)value); + } + } +} diff --git a/src/JSInterop/Microsoft.JSInterop/src/Infrastructure/JSObjectReferenceJsonConverter.cs b/src/JSInterop/Microsoft.JSInterop/src/Infrastructure/JSObjectReferenceJsonConverter.cs index 037c3e8ea8c8..39fabae778ce 100644 --- a/src/JSInterop/Microsoft.JSInterop/src/Infrastructure/JSObjectReferenceJsonConverter.cs +++ b/src/JSInterop/Microsoft.JSInterop/src/Infrastructure/JSObjectReferenceJsonConverter.cs @@ -22,7 +22,7 @@ public override bool CanConvert(Type typeToConvert) public override IJSObjectReference? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { - var id = JSObjectReferenceJsonWorker.ReadJSObjectReferenceIdentifier(ref reader); + var (id, _) = JSObjectReferenceJsonWorker.ReadJSObjectReferenceIdentifier(ref reader); return new JSObjectReference(_jsRuntime, id); } diff --git a/src/JSInterop/Microsoft.JSInterop/src/JSRuntime.cs b/src/JSInterop/Microsoft.JSInterop/src/JSRuntime.cs index d78bc15d3a5f..44a3e3b59b04 100644 --- a/src/JSInterop/Microsoft.JSInterop/src/JSRuntime.cs +++ b/src/JSInterop/Microsoft.JSInterop/src/JSRuntime.cs @@ -5,6 +5,7 @@ using System.Collections.Concurrent; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; +using System.IO; using System.Text.Json; using System.Threading; using System.Threading.Tasks; @@ -40,7 +41,8 @@ protected JSRuntime() { new DotNetObjectReferenceJsonConverterFactory(this), new JSObjectReferenceJsonConverter(this), - new ByteArrayJsonConverter(this) + new JSDataReferenceJsonConverter(this), + new ByteArrayJsonConverter(this), } }; } @@ -208,6 +210,24 @@ protected internal virtual void ReceiveByteArray(int id, byte[] data) ByteArraysToBeRevived.Append(data); } + /// + /// Provides a for the data reference represented by . + /// + /// to produce a data stream for. + /// Expected length of the incoming data stream. + /// Amount of bytes to buffer before flushing. + /// for cancelling read. + /// + protected internal virtual Task ReadJSDataAsStreamAsync(IJSDataReference jsDataReference, long totalLength, long maxBufferSize, CancellationToken cancellationToken) + { + // The reason it's virtual and not abstract is just for back-compat + + // JSRuntime subclasses should override this method, and implement their own system for returning a Stream + // representing the contents of the IJSObjectReference (whose value on the JS side will be an ArrayBufferLike). + // The transport mechanism will be completely different between, say, Server and WebAssembly. + throw new NotSupportedException("The current JavaScript runtime does not support reading data streams."); + } + [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2072:RequiresUnreferencedCode", Justification = "We enforce trimmer attributes for JSON deserialized types on InvokeAsync.")] internal void EndInvokeJS(long taskId, bool succeeded, ref Utf8JsonReader jsonReader) { diff --git a/src/JSInterop/Microsoft.JSInterop/src/PublicAPI.Unshipped.txt b/src/JSInterop/Microsoft.JSInterop/src/PublicAPI.Unshipped.txt index d68c6101dc40..d05462b5257c 100644 --- a/src/JSInterop/Microsoft.JSInterop/src/PublicAPI.Unshipped.txt +++ b/src/JSInterop/Microsoft.JSInterop/src/PublicAPI.Unshipped.txt @@ -1,8 +1,14 @@ #nullable enable +Microsoft.JSInterop.IJSDataReference +Microsoft.JSInterop.IJSDataReference.Length.get -> long +Microsoft.JSInterop.IJSDataReference.OpenReadStreamAsync(long maxAllowedSize = 512000, long maxBufferSize = 102400, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task! +Microsoft.JSInterop.Implementation.JSDataReference +Microsoft.JSInterop.Implementation.JSDataReference.JSDataReference(Microsoft.JSInterop.JSRuntime! jsRuntime, long id, long totalLength) -> void +Microsoft.JSInterop.Implementation.JSDataReference.Length.get -> long Microsoft.JSInterop.Implementation.JSObjectReferenceJsonWorker Microsoft.JSInterop.Infrastructure.DotNetInvocationResult.ResultJson.get -> string? Microsoft.JSInterop.JSRuntime.Dispose() -> void -static Microsoft.JSInterop.Implementation.JSObjectReferenceJsonWorker.ReadJSObjectReferenceIdentifier(ref System.Text.Json.Utf8JsonReader reader) -> long +static Microsoft.JSInterop.Implementation.JSObjectReferenceJsonWorker.ReadJSObjectReferenceIdentifier(ref System.Text.Json.Utf8JsonReader reader) -> (long, long) static Microsoft.JSInterop.Implementation.JSObjectReferenceJsonWorker.WriteJSObjectReference(System.Text.Json.Utf8JsonWriter! writer, Microsoft.JSInterop.Implementation.JSObjectReference! objectReference) -> void *REMOVED*Microsoft.JSInterop.Infrastructure.DotNetInvocationResult.DotNetInvocationResult(System.Exception! exception, string? errorKind) -> void *REMOVED*Microsoft.JSInterop.Infrastructure.DotNetInvocationResult.DotNetInvocationResult(object? result) -> void @@ -30,6 +36,7 @@ static Microsoft.JSInterop.JSRuntimeExtensions.InvokeVoidAsync(this Microsoft.JS static Microsoft.JSInterop.JSRuntimeExtensions.InvokeVoidAsync(this Microsoft.JSInterop.IJSRuntime! jsRuntime, string! identifier, System.TimeSpan timeout, params object?[]? args) -> System.Threading.Tasks.ValueTask *REMOVED*static Microsoft.JSInterop.JSRuntimeExtensions.InvokeVoidAsync(this Microsoft.JSInterop.IJSRuntime! jsRuntime, string! identifier, params object![]! args) -> System.Threading.Tasks.ValueTask static Microsoft.JSInterop.JSRuntimeExtensions.InvokeVoidAsync(this Microsoft.JSInterop.IJSRuntime! jsRuntime, string! identifier, params object?[]? args) -> System.Threading.Tasks.ValueTask +virtual Microsoft.JSInterop.JSRuntime.ReadJSDataAsStreamAsync(Microsoft.JSInterop.IJSDataReference! jsDataReference, long totalLength, long maxBufferSize, System.Threading.CancellationToken cancellationToken) -> System.Threading.Tasks.Task! virtual Microsoft.JSInterop.JSRuntime.ReceiveByteArray(int id, byte[]! data) -> void virtual Microsoft.JSInterop.JSRuntime.SendByteArray(int id, byte[]! data) -> void Microsoft.JSInterop.JSDisconnectedException diff --git a/src/Shared/JSInterop/JSCallResultTypeHelper.cs b/src/Shared/JSInterop/JSCallResultTypeHelper.cs index 8bf1a547fc1b..1a924aebc6e0 100644 --- a/src/Shared/JSInterop/JSCallResultTypeHelper.cs +++ b/src/Shared/JSInterop/JSCallResultTypeHelper.cs @@ -15,7 +15,8 @@ public static JSCallResultType FromGeneric() if (typeof(TResult).Assembly == _currentAssembly && (typeof(TResult) == typeof(IJSObjectReference) || typeof(TResult) == typeof(IJSInProcessObjectReference) - || typeof(TResult) == typeof(IJSUnmarshalledObjectReference))) + || typeof(TResult) == typeof(IJSUnmarshalledObjectReference) + || typeof(TResult) == typeof(IJSDataReference))) { return JSCallResultType.JSObjectReference; } diff --git a/src/SignalR/server/Core/src/Internal/DefaultHubDispatcher.cs b/src/SignalR/server/Core/src/Internal/DefaultHubDispatcher.cs index 1b355bea3a6e..c58deacc52fe 100644 --- a/src/SignalR/server/Core/src/Internal/DefaultHubDispatcher.cs +++ b/src/SignalR/server/Core/src/Internal/DefaultHubDispatcher.cs @@ -22,7 +22,7 @@ namespace Microsoft.AspNetCore.SignalR.Internal { internal partial class DefaultHubDispatcher : HubDispatcher where THub : Hub { - private readonly Dictionary _methods = new Dictionary(StringComparer.OrdinalIgnoreCase); + private readonly Dictionary _methods = new(StringComparer.OrdinalIgnoreCase); private readonly IServiceScopeFactory _serviceScopeFactory; private readonly IHubContext _hubContext; private readonly ILogger> _logger; @@ -248,7 +248,7 @@ private Task ProcessInvocation(HubConnectionContext connection, } else { - bool isStreamCall = descriptor.StreamingParameters != null; + var isStreamCall = descriptor.StreamingParameters != null; if (connection.ActiveInvocationLimit != null && !isStreamCall && !isStreamResponse) { return connection.ActiveInvocationLimit.RunAsync(state => From 66dbaf5f23e409b3369d58b845182069da851369 Mon Sep 17 00:00:00 2001 From: Tanay Parikh Date: Fri, 11 Jun 2021 10:35:17 -0700 Subject: [PATCH 02/37] Cancel JS Data Stream (with clearTimeout) --- .../Server/src/Circuits/RemoteJSDataStream.cs | 31 +++++++++++++---- .../Web.JS/dist/Release/blazor.server.js | 2 +- src/Components/Web.JS/src/Boot.Server.ts | 34 +++++++++++++++---- src/Components/Web.JS/src/GlobalExports.ts | 1 + 4 files changed, 55 insertions(+), 13 deletions(-) diff --git a/src/Components/Server/src/Circuits/RemoteJSDataStream.cs b/src/Components/Server/src/Circuits/RemoteJSDataStream.cs index f84c65bba73b..043f7d85d076 100644 --- a/src/Components/Server/src/Circuits/RemoteJSDataStream.cs +++ b/src/Components/Server/src/Circuits/RemoteJSDataStream.cs @@ -17,7 +17,8 @@ internal class RemoteJSDataStream : Stream // Concerns with static `Instances`? Malicious actor could hijack another user's // stream by (improbably) guessing the GUID. Maybe we put this in the JSRuntime for curcuit isolation? private readonly static Dictionary Instances = new(); - + private readonly JSRuntime _runtime; + private readonly IJSDataReference _jsDataReference; private readonly Guid _streamId; private readonly long _totalLength; private readonly CancellationToken _cancellationToken; @@ -29,7 +30,9 @@ public static Task SupplyData(string streamId, ReadOnlySequence chunk, str { if (!Instances.TryGetValue(Guid.Parse(streamId), out var instance)) { - throw new InvalidOperationException("There is no data stream with the given identifier. It may have already been disposed."); + // There is no data stream with the given identifier. It may have already been disposed. + // We return silently as we still expect a couple of SupplyData calls after disposal IFF the RemoteJSDataStream was cancelled. + return Task.CompletedTask; } return instance.SupplyData(chunk, error); @@ -43,13 +46,21 @@ public static async Task CreateRemoteJSDataStreamAsync( CancellationToken cancellationToken = default) { var streamId = Guid.NewGuid(); - var remoteJSDataStream = new RemoteJSDataStream(streamId, totalLength, maxBufferSize, cancellationToken); + var remoteJSDataStream = new RemoteJSDataStream(runtime, jsDataReference, streamId, totalLength, maxBufferSize, cancellationToken); await runtime.InvokeVoidAsync("Blazor._internal.sendJSDataStream", jsDataReference, streamId); return remoteJSDataStream; } - private RemoteJSDataStream(Guid streamId, long totalLength, long maxBufferSize, CancellationToken cancellationToken) + private RemoteJSDataStream( + JSRuntime runtime, + IJSDataReference jsDataReference, + Guid streamId, + long totalLength, + long maxBufferSize, + CancellationToken cancellationToken) { + _runtime = runtime; + _jsDataReference = jsDataReference; _streamId = streamId; _totalLength = totalLength; _cancellationToken = cancellationToken; @@ -150,16 +161,24 @@ public override void Write(byte[] buffer, int offset, int count) public override async Task ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) { - return await _pipeReaderStream.ReadAsync(buffer.AsMemory(offset, count), cancellationToken); + var linkedCts = CancellationTokenSource.CreateLinkedTokenSource(_cancellationToken, cancellationToken); + return await _pipeReaderStream.ReadAsync(buffer.AsMemory(offset, count), linkedCts.Token); } public override async ValueTask ReadAsync(Memory buffer, CancellationToken cancellationToken = default) { - return await _pipeReaderStream.ReadAsync(buffer, cancellationToken); + var linkedCts = CancellationTokenSource.CreateLinkedTokenSource(_cancellationToken, cancellationToken); + return await _pipeReaderStream.ReadAsync(buffer, linkedCts.Token); } protected override void Dispose(bool disposing) { + // Fire & forget a notification to the JSRuntime to stop sending additional chunks. + if (_cancellationToken.IsCancellationRequested) + { + _ = Task.Run(() => _runtime.InvokeVoidAsync("Blazor._internal.cancelJSDataStream", _streamId)); + } + if (disposing) { Instances.Remove(_streamId); diff --git a/src/Components/Web.JS/dist/Release/blazor.server.js b/src/Components/Web.JS/dist/Release/blazor.server.js index b5b3211f8503..086da8e45893 100644 --- a/src/Components/Web.JS/dist/Release/blazor.server.js +++ b/src/Components/Web.JS/dist/Release/blazor.server.js @@ -1 +1 @@ -(()=>{"use strict";var e,t,n;!function(e){window.DotNet=e;const t=[],n=new Map;class r{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 o="__jsObjectId",i={},s={0:new r(window)};s[0]._cachedFunctions.set("import",(e=>("string"==typeof e&&e.startsWith("./")&&(e=document.baseURI+e.substr(2)),import(e))));let a,c=1,l=1,h=null;function u(e){t.push(e)}function d(e){if(e&&"object"==typeof e){s[l]=new r(e);let t={[o]:l};return e.buffer instanceof ArrayBuffer&&void 0!==e.byteLength&&(t.__jsDataReferenceLength=e.byteLength),l++,t}throw new Error(`Cannot create a JSObjectReference from the value '${e}'.`)}function p(e){return e?JSON.parse(e,((e,n)=>t.reduce(((t,n)=>n(e,t)),n))):null}function f(e,t,n,r){const o=m();if(o.invokeDotNetFromJS){const i=I(r),s=o.invokeDotNetFromJS(e,t,n,i);return s?p(s):null}throw new Error("The current dispatcher does not support synchronous calls from JS to .NET. Use invokeMethodAsync instead.")}function g(e,t,n,r){if(e&&n)throw new Error(`For instance method calls, assemblyName should be null. Received '${e}'.`);const o=c++,s=new Promise(((e,t)=>{i[o]={resolve:e,reject:t}}));try{const i=I(r);m().beginInvokeDotNetFromJS(o,e,t,n,i)}catch(e){y(o,!1,e)}return s}function m(){if(null!==h)return h;throw new Error("No .NET call dispatcher has been set.")}function y(e,t,n){if(!i.hasOwnProperty(e))throw new Error(`There is no pending async call with ID ${e}.`);const r=i[e];delete i[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 v(e,t){let n=s[t];if(n)return n.findFunction(e);throw new Error(`JS object instance with ID ${t} does not exist (has it been disposed?).`)}function b(e){delete s[e]}e.attachDispatcher=function(e){h=e},e.attachReviver=u,e.invokeMethod=function(e,t,...n){return f(e,t,null,n)},e.invokeMethodAsync=function(e,t,...n){return g(e,t,null,n)},e.createJSObjectReference=d,e.disposeJSObjectReference=function(e){const t=e&&e.__jsObjectId;"number"==typeof t&&b(t)},function(e){e[e.Default=0]="Default",e[e.JSObjectReference=1]="JSObjectReference"}(a=e.JSCallResultType||(e.JSCallResultType={})),e.jsCallDispatcher={findJSFunction:v,disposeJSObjectReferenceById:b,invokeJSFromDotNet:(e,t,n,r)=>{const o=S(v(e,r).apply(null,p(t)),n);return null==o?null:I(o)},beginInvokeJSFromDotNet:(e,t,n,r,o)=>{const i=new Promise((e=>{e(v(t,o).apply(null,p(n)))}));e&&i.then((t=>m().endInvokeJSFromDotNet(e,!0,I([e,!0,S(t,r)]))),(t=>m().endInvokeJSFromDotNet(e,!1,JSON.stringify([e,!1,w(t)]))))},endInvokeDotNetFromJS:(e,t,n)=>{const r=t?p(n):new Error(n);y(parseInt(e),t,r)},receiveByteArray:(e,t)=>{n.set(e,t)}};class _{constructor(e){this._id=e}invokeMethod(e,...t){return f(null,e,this._id,t)}invokeMethodAsync(e,...t){return g(null,e,this._id,t)}dispose(){g(null,"__Dispose",this._id,null).catch((e=>console.error(e)))}serializeAsArg(){return{__dotNetObject:this._id}}}const E="__byte[]";function S(e,t){switch(t){case a.Default:return e;case a.JSObjectReference:return d(e);default:throw new Error(`Invalid JS call result type '${t}'.`)}}u((function(e,t){if(t&&"object"==typeof t){if(t.hasOwnProperty("__dotNetObject"))return new _(t.__dotNetObject);if(t.hasOwnProperty(o)){const e=t.__jsObjectId,n=s[e];if(n)return n.getWrappedObject();throw new Error(`JS object instance with Id '${e}' does not exist. It may have been disposed.`)}if(t.hasOwnProperty(E)){const e=t["__byte[]"],r=n.get(e);if(void 0===r)throw new Error(`Byte array index '${e}' does not exist.`);return r}}return t}));let C=0;function I(e){return C=0,JSON.stringify(e,k)}function k(e,t){if(t instanceof _)return t.serializeAsArg();if(t instanceof Uint8Array){h.sendByteArray(C,t);const e={[E]:C};return C++,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"}(n||(n={}));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}}let o;function i(e,t){if(!o)throw new Error("eventDispatcher not initialized. Call 'setEventDispatcher' to configure it.");o(e,t)}const s=new Map,a=new Map,c={createEventArgs:()=>({})},l=[];function h(e){return s.get(e)}function u(e){const t=s.get(e);return(null==t?void 0:t.browserEventName)||e}function d(e,t){e.forEach((e=>s.set(e,t)))}function p(e){const t=[];for(let n=0;n{return{...f(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}}),d(["focus","blur","focusin","focusout"],c),d(["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};var t}}),d(["contextmenu","click","mouseover","mouseout","mousemove","mousedown","mouseup","dblclick"],{createEventArgs:e=>f(e)}),d(["error"],{createEventArgs:e=>{return{message:(t=e).message,filename:t.filename,lineno:t.lineno,colno:t.colno};var t}}),d(["loadstart","timeout","abort","load","loadend","progress"],{createEventArgs:e=>{return{lengthComputable:(t=e).lengthComputable,loaded:t.loaded,total:t.total};var t}}),d(["touchcancel","touchend","touchmove","touchenter","touchleave","touchstart"],{createEventArgs:e=>{return{detail:(t=e).detail,touches:p(t.touches),targetTouches:p(t.targetTouches),changedTouches:p(t.changedTouches),ctrlKey:t.ctrlKey,shiftKey:t.shiftKey,altKey:t.altKey,metaKey:t.metaKey,type:t.type};var t}}),d(["gotpointercapture","lostpointercapture","pointercancel","pointerdown","pointerenter","pointerleave","pointermove","pointerout","pointerover","pointerup"],{createEventArgs:e=>{return{...f(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}}),d(["wheel","mousewheel"],{createEventArgs:e=>{return{...f(t=e),deltaX:t.deltaX,deltaY:t.deltaY,deltaZ:t.deltaZ,deltaMode:t.deltaMode};var t}}),d(["toggle"],c);const g=["date","datetime-local","month","time","week"],m=E(["abort","blur","change","error","focus","load","loadend","loadstart","mouseenter","mouseleave","progress","reset","scroll","submit","unload","toggle","DOMNodeInsertedIntoDocument","DOMNodeRemovedFromDocument"]),y={submit:!0},w=E(["click","dblclick","mousedown","mousemove","mouseup"]);class v{constructor(e){this.browserRendererId=e,this.afterClickCallbacks=[];const t=++v.nextEventDelegatorId;this.eventsCollectionKey=`_blazorEvents_${t}`,this.eventInfoStore=new b(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,a.get(n));var n;t&&t.forEach((t=>this.dispatchGlobalEventToAllElements(t,e))),"click"===e.type&&this.afterClickCallbacks.forEach((t=>t(e)))}dispatchGlobalEventToAllElements(e,t){let n=t.target,o=null,s=!1;const a=m.hasOwnProperty(e);let c=!1;for(;n;){const d=this.getEventHandlerInfosForElement(n,!1);if(d){const a=d.getHandler(e);if(a&&(l=n,u=t.type,!((l instanceof HTMLButtonElement||l instanceof HTMLInputElement||l instanceof HTMLTextAreaElement||l instanceof HTMLSelectElement)&&w.hasOwnProperty(u)&&l.disabled))){if(!s){const n=h(e);o=(null==n?void 0:n.createEventArgs)?n.createEventArgs(t):{},s=!0}y.hasOwnProperty(t.type)&&t.preventDefault(),i({browserRendererId:this.browserRendererId,eventHandlerId:a.eventHandlerId,eventName:e,eventFieldInfo:r.fromEvent(a.renderingComponentId,t)},o)}d.stopPropagation(e)&&(c=!0),d.preventDefault(e)&&t.preventDefault()}n=a||c?null:n.parentElement}var l,u}getEventHandlerInfosForElement(e,t){return e.hasOwnProperty(this.eventsCollectionKey)?e[this.eventsCollectionKey]:t?e[this.eventsCollectionKey]=new _:null}}v.nextEventDelegatorId=0;class b{constructor(e){this.globalListener=e,this.infosByEventHandlerId={},this.countByEventName={},l.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=u(e),this.countByEventName.hasOwnProperty(e))this.countByEventName[e]++;else{this.countByEventName[e]=1;const t=m.hasOwnProperty(e);document.addEventListener(e,this.globalListener,t)}}update(e,t){if(this.infosByEventHandlerId.hasOwnProperty(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=u(t.eventName);0==--this.countByEventName[n]&&(delete this.countByEventName[n],document.removeEventListener(n,this.globalListener))}return t}handleEventNameAliasAdded(e,t){if(this.countByEventName.hasOwnProperty(e)){const n=this.countByEventName[e];delete this.countByEventName[e],document.removeEventListener(e,this.globalListener),this.addGlobalListener(t),this.countByEventName[t]+=n-1}}}class _{constructor(){this.handlers={},this.preventDefaultFlags=null,this.stopPropagationFlags=null}getHandler(e){return this.handlers.hasOwnProperty(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 E(e){const t={};return e.forEach((e=>{t[e]=!0})),t}const S=H("_blazorLogicalChildren"),C=H("_blazorLogicalParent"),I=H("_blazorLogicalEnd");function k(e,t){if(e.childNodes.length>0&&!t)throw new Error("New logical elements must start empty, or allowExistingContents must be true");return S in e||(e[S]=[]),e}function T(e,t){const n=document.createComment("!");return x(n,e,t),n}function x(e,t,n){const r=e;if(e instanceof Comment&&A(r)&&A(r).length>0)throw new Error("Not implemented: inserting non-empty logical container");if(R(r))throw new Error("Not implemented: moving existing logical children");const o=A(t);if(n0;)D(n,0)}const r=n;r.parentNode.removeChild(r)}function R(e){return e[C]||null}function P(e,t){return A(e)[t]}function U(e){var t=B(e);return"http://www.w3.org/2000/svg"===t.namespaceURI&&"foreignObject"!==t.tagName}function A(e){return e[S]}function N(e,t){const n=A(e);t.forEach((e=>{e.moveRangeStart=n[e.fromSiblingIndex],e.moveRangeEnd=M(e.moveRangeStart)})),t.forEach((t=>{const r=t.moveToBeforeMarker=document.createComment("marker"),o=n[t.toSiblingIndex+1];o?o.parentNode.insertBefore(r,o):L(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 B(e){if(e instanceof Element)return e;if(e instanceof Comment)return e.parentNode;throw new Error("Not a valid logical element")}function $(e){const t=A(R(e));return t[Array.prototype.indexOf.call(t,e)+1]||null}function L(e,t){if(t instanceof Element)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=$(t);n?n.parentNode.insertBefore(e,n):L(e,R(t))}}}function M(e){if(e instanceof Element)return e;const t=$(e);if(t)return t.previousSibling;{const t=R(e);return t instanceof Element?t.lastChild:M(t)}}function H(e){return"function"==typeof Symbol?Symbol():e}function O(e){return`_bl_${e}`}e.attachReviver(((e,t)=>t&&"object"==typeof t&&t.hasOwnProperty("__internalId")&&"string"==typeof t.__internalId?function(e){const t=`[${O(e)}]`;return document.querySelector(t)}(t.__internalId):t));const F="_blazorSelectValue",j=document.createElement("template"),W=document.createElementNS("http://www.w3.org/2000/svg","g"),z={},q="__internal_",J="preventDefault_",K="stopPropagation_";class V{constructor(e){this.childComponentLocations={},this.eventDelegator=new v(e),this.eventDelegator.notifyAfterClick((e=>{if(!ee)return;if(0!==e.button||function(e){return e.ctrlKey||e.shiftKey||e.altKey||e.metaKey}(e))return;if(e.defaultPrevented)return;const t=function(e){const t=!window._blazorDisableComposedPath&&e.composedPath&&e.composedPath();if(t){for(let e=0;ese(!1))))},enableNavigationInterception:function(){ee=!0},navigateTo:oe,getBaseURI:()=>document.baseURI,getLocationHref:()=>location.href};function oe(e,t,n=!1){const r=ce(e);if(!t&&he(r))ie(r,!1,n);else if(t&&location.href===e){const t=e+"?";history.replaceState(null,"",t),location.replace(e)}else n?history.replaceState(null,"",r):location.href=e}function ie(e,t,n=!1){Z=!0,n?history.replaceState(null,"",e):history.pushState(null,"",e),se(t)}async function se(e){ne&&await ne(location.href,e)}let ae;function ce(e){return ae=ae||document.createElement("a"),ae.href=e,ae.href}function le(e,t){return e?e.tagName===t?e:le(e.parentElement,t):null}function he(e){const t=(n=document.baseURI).substr(0,n.lastIndexOf("/")+1);var n;return e.startsWith(t)}const ue={init:function(e,t,n,r=50){const o=pe(t);(o||document.documentElement).style.overflowAnchor="none";const i=new IntersectionObserver((function(r){r.forEach((r=>{var o;if(!r.isIntersecting)return;const i=t.getBoundingClientRect(),s=n.getBoundingClientRect().top-i.bottom,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`});i.observe(t),i.observe(n);const s=c(t),a=c(n);function c(e){const t=new MutationObserver((()=>{i.unobserve(e),i.observe(e)}));return t.observe(e,{attributes:!0}),t}de[e._id]={intersectionObserver:i,mutationObserverBefore:s,mutationObserverAfter:a}},dispose:function(e){const t=de[e._id];t&&(t.intersectionObserver.disconnect(),t.mutationObserverBefore.disconnect(),t.mutationObserverAfter.disconnect(),e.dispose(),delete de[e._id])}},de={};function pe(e){return e?"visible"!==getComputedStyle(e).overflowY?e:pe(e.parentElement):null}const fe={navigateTo:oe,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=a.get(t.browserEventName);n?n.push(e):a.set(t.browserEventName,[e]),l.forEach((n=>n(e,t.browserEventName)))}s.set(e,t)},_internal:{navigationManager:re,domWrapper:{focus:function(e,t){if(!(e instanceof HTMLElement))throw new Error("Unable to focus an invalid element.");e.focus({preventScroll:t})}},Virtualize:ue}};window.Blazor=fe;const ge=[0,2e3,1e4,3e4,null];class me{constructor(e){this._retryDelays=void 0!==e?[...e,null]:ge}nextRetryDelayInMilliseconds(e){return this._retryDelays[e.previousRetryCount]}}class ye extends Error{constructor(e,t){const n=new.target.prototype;super(`${e}: Status code '${t}'`),this.statusCode=t,this.__proto__=n}}class we extends Error{constructor(e="A timeout occurred."){const t=new.target.prototype;super(e),this.__proto__=t}}class ve extends Error{constructor(e="An abort occurred."){const t=new.target.prototype;super(e),this.__proto__=t}}class be{constructor(e,t,n){this.statusCode=e,this.statusText=t,this.content=n}}class _e{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""}}var Ee,Se,Ce,Ie,ke;!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"}(Ee||(Ee={}));class Te extends _e{constructor(e){if(super(),this._logger=e,"undefined"==typeof fetch){const e=require;this._jar=new(e("tough-cookie").CookieJar),this._fetchType=e("node-fetch"),this._fetchType=e("fetch-cookie")(this._fetchType,this._jar),this._abortControllerType=e("abort-controller")}else this._fetchType=fetch.bind(self),this._abortControllerType=AbortController}async send(e){if(e.abortSignal&&e.abortSignal.aborted)throw new ve;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 ve});let r,o=null;if(e.timeout){const r=e.timeout;o=setTimeout((()=>{t.abort(),this._logger.log(Ee.Warning,"Timeout from HTTP request."),n=new we}),r)}try{r=await this._fetchType(e.url,{body:e.content,cache:"no-cache",credentials:!0===e.withCredentials?"include":"same-origin",headers:{"Content-Type":"text/plain;charset=UTF-8","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(Ee.Warning,`Error from HTTP request. ${e}.`),e}finally{o&&clearTimeout(o),e.abortSignal&&(e.abortSignal.onabort=null)}if(!r.ok){const e=await xe(r,"text");throw new ye(e||r.statusText,r.status)}const i=xe(r,e.responseType),s=await i;return new be(r.status,r.statusText,s)}getCookieString(e){return""}}function xe(e,t){let n;switch(t){case"arraybuffer":n=e.arrayBuffer();break;case"text":n=e.text();break;case"blob":case"document":case"json":throw new Error(`${t} is not supported.`);default:n=e.text()}return n}class De extends _e{constructor(e){super(),this._logger=e}send(e){return e.abortSignal&&e.abortSignal.aborted?Promise.reject(new ve):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"),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 ve)}),e.timeout&&(r.timeout=e.timeout),r.onload=()=>{e.abortSignal&&(e.abortSignal.onabort=null),r.status>=200&&r.status<300?t(new be(r.status,r.statusText,r.response||r.responseText)):n(new ye(r.response||r.responseText||r.statusText,r.status))},r.onerror=()=>{this._logger.log(Ee.Warning,`Error from HTTP request. ${r.status}: ${r.statusText}.`),n(new ye(r.statusText,r.status))},r.ontimeout=()=>{this._logger.log(Ee.Warning,"Timeout from HTTP request."),n(new we)},r.send(e.content||"")})):Promise.reject(new Error("No url defined.")):Promise.reject(new Error("No method defined."))}}class Re extends _e{constructor(e){if(super(),"undefined"!=typeof fetch)this._httpClient=new Te(e);else{if("undefined"==typeof XMLHttpRequest)throw new Error("No usable HttpClient found.");this._httpClient=new De(e)}}send(e){return e.abortSignal&&e.abortSignal.aborted?Promise.reject(new ve):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)}}class Pe{}Pe.Authorization="Authorization",Pe.Cookie="Cookie",function(e){e[e.None=0]="None",e[e.WebSockets=1]="WebSockets",e[e.ServerSentEvents=2]="ServerSentEvents",e[e.LongPolling=4]="LongPolling"}(Se||(Se={})),function(e){e[e.Text=1]="Text",e[e.Binary=2]="Binary"}(Ce||(Ce={}));class Ue{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 Ae{constructor(){}log(e,t){}}Ae.instance=new Ae;class Ne{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 Be{static get isBrowser(){return"object"==typeof window}static get isWebWorker(){return"object"==typeof self&&"importScripts"in self}static get isNode(){return!this.isBrowser&&!this.isWebWorker}}function $e(e,t){let n="";return Le(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 Le(e){return e&&"undefined"!=typeof ArrayBuffer&&(e instanceof ArrayBuffer||e.constructor&&"ArrayBuffer"===e.constructor.name)}async function Me(e,t,n,r,o,i,s,a,c){let l={};if(o){const e=await o();e&&(l={Authorization:`Bearer ${e}`})}const[h,u]=Fe();l[h]=u,e.log(Ee.Trace,`(${t} transport) sending data. ${$e(i,s)}.`);const d=Le(i)?"arraybuffer":"text",p=await n.post(r,{content:i,headers:{...l,...c},responseType:d,withCredentials:a});e.log(Ee.Trace,`(${t} transport) request complete. Response status: ${p.statusCode}.`)}class He{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 Oe{constructor(e){this._minLevel=e,this.out=console}log(e,t){if(e>=this._minLevel){const n=`[${(new Date).toISOString()}] ${Ee[e]}: ${t}`;switch(e){case Ee.Critical:case Ee.Error:this.out.error(n);break;case Ee.Warning:this.out.warn(n);break;case Ee.Information:this.out.info(n);break;default:this.out.log(n)}}}}function Fe(){let e="X-SignalR-User-Agent";return Be.isNode&&(e="User-Agent"),[e,je("0.0.0-DEV_BUILD",We(),Be.isNode?"NodeJS":"Browser",ze())]}function je(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 We(){if(!Be.isNode)return"";switch(process.platform){case"win32":return"Windows NT";case"darwin":return"macOS";case"linux":return"Linux";default:return process.platform}}function ze(){if(Be.isNode)return process.versions.node}class qe{constructor(e,t,n,r,o,i){this._httpClient=e,this._accessTokenFactory=t,this._logger=n,this._pollAbort=new Ue,this._logMessageContent=r,this._withCredentials=o,this._headers=i,this._running=!1,this.onreceive=null,this.onclose=null}get pollAborted(){return this._pollAbort.aborted}async connect(e,t){if(Ne.isRequired(e,"url"),Ne.isRequired(t,"transferFormat"),Ne.isIn(t,Ce,"transferFormat"),this._url=e,this._logger.log(Ee.Trace,"(LongPolling transport) Connecting."),t===Ce.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]=Fe(),o={[n]:r,...this._headers},i={abortSignal:this._pollAbort.signal,headers:o,timeout:1e5,withCredentials:this._withCredentials};t===Ce.Binary&&(i.responseType="arraybuffer");const s=await this._getAccessToken();this._updateHeaderToken(i,s);const a=`${e}&_=${Date.now()}`;this._logger.log(Ee.Trace,`(LongPolling transport) polling: ${a}.`);const c=await this._httpClient.get(a,i);200!==c.statusCode?(this._logger.log(Ee.Error,`(LongPolling transport) Unexpected response code: ${c.statusCode}.`),this._closeError=new ye(c.statusText||"",c.statusCode),this._running=!1):this._running=!0,this._receiving=this._poll(this._url,i)}async _getAccessToken(){return this._accessTokenFactory?await this._accessTokenFactory():null}_updateHeaderToken(e,t){e.headers||(e.headers={}),t?e.headers[Pe.Authorization]=`Bearer ${t}`:e.headers[Pe.Authorization]&&delete e.headers[Pe.Authorization]}async _poll(e,t){try{for(;this._running;){const n=await this._getAccessToken();this._updateHeaderToken(t,n);try{const n=`${e}&_=${Date.now()}`;this._logger.log(Ee.Trace,`(LongPolling transport) polling: ${n}.`);const r=await this._httpClient.get(n,t);204===r.statusCode?(this._logger.log(Ee.Information,"(LongPolling transport) Poll terminated by server."),this._running=!1):200!==r.statusCode?(this._logger.log(Ee.Error,`(LongPolling transport) Unexpected response code: ${r.statusCode}.`),this._closeError=new ye(r.statusText||"",r.statusCode),this._running=!1):r.content?(this._logger.log(Ee.Trace,`(LongPolling transport) data received. ${$e(r.content,this._logMessageContent)}.`),this.onreceive&&this.onreceive(r.content)):this._logger.log(Ee.Trace,"(LongPolling transport) Poll timed out, reissuing.")}catch(e){this._running?e instanceof we?this._logger.log(Ee.Trace,"(LongPolling transport) Poll timed out, reissuing."):(this._closeError=e,this._running=!1):this._logger.log(Ee.Trace,`(LongPolling transport) Poll errored after shutdown: ${e.message}`)}}}finally{this._logger.log(Ee.Trace,"(LongPolling transport) Polling complete."),this.pollAborted||this._raiseOnClose()}}async send(e){return this._running?Me(this._logger,"LongPolling",this._httpClient,this._url,this._accessTokenFactory,e,this._logMessageContent,this._withCredentials,this._headers):Promise.reject(new Error("Cannot send until the transport is connected"))}async stop(){this._logger.log(Ee.Trace,"(LongPolling transport) Stopping polling."),this._running=!1,this._pollAbort.abort();try{await this._receiving,this._logger.log(Ee.Trace,`(LongPolling transport) sending DELETE request to ${this._url}.`);const e={},[t,n]=Fe();e[t]=n;const r={headers:{...e,...this._headers},withCredentials:this._withCredentials},o=await this._getAccessToken();this._updateHeaderToken(r,o),await this._httpClient.delete(this._url,r),this._logger.log(Ee.Trace,"(LongPolling transport) DELETE request sent.")}finally{this._logger.log(Ee.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(Ee.Trace,e),this.onclose(this._closeError)}}}class Je{constructor(e,t,n,r,o,i,s){this._httpClient=e,this._accessTokenFactory=t,this._logger=n,this._logMessageContent=r,this._withCredentials=i,this._eventSourceConstructor=o,this._headers=s,this.onreceive=null,this.onclose=null}async connect(e,t){if(Ne.isRequired(e,"url"),Ne.isRequired(t,"transferFormat"),Ne.isIn(t,Ce,"transferFormat"),this._logger.log(Ee.Trace,"(SSE transport) Connecting."),this._url=e,this._accessTokenFactory){const t=await this._accessTokenFactory();t&&(e+=(e.indexOf("?")<0?"?":"&")+`access_token=${encodeURIComponent(t)}`)}return new Promise(((n,r)=>{let o,i=!1;if(t===Ce.Text){if(Be.isBrowser||Be.isWebWorker)o=new this._eventSourceConstructor(e,{withCredentials:this._withCredentials});else{const t=this._httpClient.getCookieString(e),n={};n.Cookie=t;const[r,i]=Fe();n[r]=i,o=new this._eventSourceConstructor(e,{withCredentials:this._withCredentials,headers:{...n,...this._headers}})}try{o.onmessage=e=>{if(this.onreceive)try{this._logger.log(Ee.Trace,`(SSE transport) data received. ${$e(e.data,this._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(Ee.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?Me(this._logger,"SSE",this._httpClient,this._url,this._accessTokenFactory,e,this._logMessageContent,this._withCredentials,this._headers):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 Ke{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){if(Ne.isRequired(e,"url"),Ne.isRequired(t,"transferFormat"),Ne.isIn(t,Ce,"transferFormat"),this._logger.log(Ee.Trace,"(WebSockets transport) Connecting."),this._accessTokenFactory){const t=await this._accessTokenFactory();t&&(e+=(e.indexOf("?")<0?"?":"&")+`access_token=${encodeURIComponent(t)}`)}return new Promise(((n,r)=>{let o;e=e.replace(/^http/,"ws"),this._httpClient.getCookieString(e);let i=!1;o||(o=new this._webSocketConstructor(e)),t===Ce.Binary&&(o.binaryType="arraybuffer"),o.onopen=t=>{this._logger.log(Ee.Information,`WebSocket connected to ${e}.`),this._webSocket=o,i=!0,n()},o.onerror=e=>{let t=null;t="undefined"!=typeof ErrorEvent&&e instanceof ErrorEvent?e.error:"There was an error with the transport",this._logger.log(Ee.Information,`(WebSockets transport) ${t}.`)},o.onmessage=e=>{if(this._logger.log(Ee.Trace,`(WebSockets transport) data received. ${$e(e.data,this._logMessageContent)}.`),this.onreceive)try{this.onreceive(e.data)}catch(e){return void this._close(e)}},o.onclose=e=>{if(i)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(Ee.Trace,`(WebSockets transport) sending data. ${$e(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(Ee.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 Ve{constructor(e,t={}){var n;if(this._stopPromiseResolver=()=>{},this.features={},this._negotiateVersion=1,Ne.isRequired(e,"url"),this._logger=void 0===(n=t.logger)?new Oe(Ee.Information):null===n?Ae.instance:void 0!==n.log?n:new Oe(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,"undefined"==typeof WebSocket||t.WebSocket||(t.WebSocket=WebSocket),"undefined"==typeof EventSource||t.EventSource||(t.EventSource=EventSource),this._httpClient=t.httpClient||new Re(this._logger),this._connectionState="Disconnected",this._connectionStarted=!1,this._options=t,this.onreceive=null,this.onclose=null}async start(e){if(e=e||Ce.Binary,Ne.isIn(e,Ce,"transferFormat"),this._logger.log(Ee.Debug,`Starting connection with transfer format '${Ce[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(Ee.Error,e),await this._stopPromise,Promise.reject(new Error(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(Ee.Error,e),Promise.reject(new Error(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 Xe(this.transport)),this._sendQueue.send(e))}async stop(e){return"Disconnected"===this._connectionState?(this._logger.log(Ee.Debug,`Call to HttpConnection.stop(${e}) ignored because the connection is already in the disconnected state.`),Promise.resolve()):"Disconnecting"===this._connectionState?(this._logger.log(Ee.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(Ee.Error,`HttpConnection.transport.stop() threw error '${e}'.`),this._stopConnection()}this.transport=void 0}else this._logger.log(Ee.Debug,"HttpConnection.transport is undefined in HttpConnection.stop() because start() failed.")}async _startInternal(e){let t=this.baseUrl;this._accessTokenFactory=this._options.accessTokenFactory;try{if(this._options.skipNegotiation){if(this._options.transport!==Se.WebSockets)throw new Error("Negotiation can only be skipped when using the WebSocket transport directly.");this.transport=this._constructTransport(Se.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 Error("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}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 qe&&(this.features.inherentKeepAlive=!0),"Connecting"===this._connectionState&&(this._logger.log(Ee.Debug,"The HttpConnection connected successfully."),this._connectionState="Connected")}catch(e){return this._logger.log(Ee.Error,"Failed to start the connection: "+e),this._connectionState="Disconnected",this.transport=void 0,this._stopPromiseResolver(),Promise.reject(e)}}async _getNegotiationResponse(e){const t={};if(this._accessTokenFactory){const e=await this._accessTokenFactory();e&&(t[Pe.Authorization]=`Bearer ${e}`)}const[n,r]=Fe();t[n]=r;const o=this._resolveNegotiateUrl(e);this._logger.log(Ee.Debug,`Sending negotiation request: ${o}.`);try{const e=await this._httpClient.post(o,{content:"",headers:{...t,...this._options.headers},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 ye&&404===e.statusCode&&(t+=" Either this is not a SignalR endpoint or there is a proxy blocking the connection."),this._logger.log(Ee.Error,t),Promise.reject(new Error(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(Ee.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: ${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(Ee.Error,`Failed to start the transport '${n.transport}': ${e}`),a=void 0,i.push(`${n.transport} failed: ${e}`),"Connecting"!==this._connectionState){const e="Failed to select transport before stop() was called.";return this._logger.log(Ee.Debug,e),Promise.reject(new Error(e))}}}}return i.length>0?Promise.reject(new Error(`Unable to connect to the server with any of the available transports. ${i.join(" ")}`)):Promise.reject(new Error("None of the transports supported by the client are supported by the server."))}_constructTransport(e){switch(e){case Se.WebSockets:if(!this._options.WebSocket)throw new Error("'WebSocket' is not supported in your environment.");return new Ke(this._httpClient,this._accessTokenFactory,this._logger,this._options.logMessageContent||!1,this._options.WebSocket,this._options.headers||{});case Se.ServerSentEvents:if(!this._options.EventSource)throw new Error("'EventSource' is not supported in your environment.");return new Je(this._httpClient,this._accessTokenFactory,this._logger,this._options.logMessageContent||!1,this._options.EventSource,this._options.withCredentials,this._options.headers||{});case Se.LongPolling:return new qe(this._httpClient,this._accessTokenFactory,this._logger,this._options.logMessageContent||!1,this._options.withCredentials,this._options.headers||{});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=Se[e.transport];if(null==r)return this._logger.log(Ee.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(Ee.Debug,`Skipping transport '${Se[r]}' because it was disabled by the client.`),new Error(`'${Se[r]}' is disabled by the client.`);if(!(e.transferFormats.map((e=>Ce[e])).indexOf(n)>=0))return this._logger.log(Ee.Debug,`Skipping transport '${Se[r]}' because it does not support the requested transfer format '${Ce[n]}'.`),new Error(`'${Se[r]}' does not support ${Ce[n]}.`);if(r===Se.WebSockets&&!this._options.WebSocket||r===Se.ServerSentEvents&&!this._options.EventSource)return this._logger.log(Ee.Debug,`Skipping transport '${Se[r]}' because it is not supported in your environment.'`),new Error(`'${Se[r]}' is not supported in your environment.`);this._logger.log(Ee.Debug,`Selecting transport '${Se[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(Ee.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(Ee.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(Ee.Error,`Connection disconnected with error '${e}'.`):this._logger.log(Ee.Information,"Connection disconnected."),this._sendQueue&&(this._sendQueue.stop().catch((e=>{this._logger.log(Ee.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(Ee.Error,`HttpConnection.onclose(${e}) threw error '${t}'.`)}}}else this._logger.log(Ee.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(!Be.isBrowser||!window.document)throw new Error(`Cannot resolve '${e}'.`);const t=window.document.createElement("a");return t.href=e,this._logger.log(Ee.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 Xe{constructor(e){this._transport=e,this._buffer=[],this._executing=!0,this._sendBufferedData=new Ye,this._transportResult=new Ye,this._sendLoopPromise=this._sendLoop()}send(e){return this._bufferData(e),this._transportResult||(this._transportResult=new Ye),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 Ye;const e=this._transportResult;this._transportResult=void 0;const t="string"==typeof this._buffer[0]?this._buffer.join(""):Xe._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 Ye{constructor(){this.promise=new Promise(((e,t)=>[this._resolver,this._rejecter]=[e,t]))}resolve(){this._resolver()}reject(e){this._rejecter(e)}}class Ge{static write(e){return`${e}${Ge.RecordSeparator}`}static parse(e){if(e[e.length-1]!==Ge.RecordSeparator)throw new Error("Message is incomplete.");const t=e.split(Ge.RecordSeparator);return t.pop(),t}}Ge.RecordSeparatorCode=30,Ge.RecordSeparator=String.fromCharCode(Ge.RecordSeparatorCode);class Qe{writeHandshakeRequest(e){return Ge.write(JSON.stringify(e))}parseHandshakeResponse(e){let t,n;if(Le(e)){const r=new Uint8Array(e),o=r.indexOf(Ge.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(Ge.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=Ge.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"}(Ie||(Ie={}));class Ze{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 He(this,e)}}!function(e){e.Disconnected="Disconnected",e.Connecting="Connecting",e.Connected="Connected",e.Disconnecting="Disconnecting",e.Reconnecting="Reconnecting"}(ke||(ke={}));class et{constructor(e,t,n,r){this._nextKeepAlive=0,Ne.isRequired(e,"connection"),Ne.isRequired(t,"logger"),Ne.isRequired(n,"protocol"),this.serverTimeoutInMilliseconds=3e4,this.keepAliveIntervalInMilliseconds=15e3,this._logger=t,this._protocol=n,this.connection=e,this._reconnectPolicy=r,this._handshakeProtocol=new Qe,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=ke.Disconnected,this._connectionStarted=!1,this._cachedPingMessage=this._protocol.writeMessage({type:Ie.Ping})}static create(e,t,n,r){return new et(e,t,n,r)}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!==ke.Disconnected&&this._connectionState!==ke.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!==ke.Disconnected)return Promise.reject(new Error("Cannot start a HubConnection that is not in the 'Disconnected' state."));this._connectionState=ke.Connecting,this._logger.log(Ee.Debug,"Starting HubConnection.");try{await this._startInternal(),this._connectionState=ke.Connected,this._connectionStarted=!0,this._logger.log(Ee.Debug,"HubConnection connected successfully.")}catch(e){return this._connectionState=ke.Disconnected,this._logger.log(Ee.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(Ee.Debug,"Sending handshake request."),await this._sendMessage(this._handshakeProtocol.writeHandshakeRequest(t)),this._logger.log(Ee.Information,`Using HubProtocol '${this._protocol.name}'.`),this._cleanupTimeout(),this._resetTimeoutPeriod(),this._resetKeepAliveInterval(),await e,this._stopDuringStartError)throw this._stopDuringStartError}catch(e){throw this._logger.log(Ee.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){return this._connectionState===ke.Disconnected?(this._logger.log(Ee.Debug,`Call to HubConnection.stop(${e}) ignored because it is already in the disconnected state.`),Promise.resolve()):this._connectionState===ke.Disconnecting?(this._logger.log(Ee.Debug,`Call to HttpConnection.stop(${e}) ignored because the connection is already in the disconnecting state.`),this._stopPromise):(this._connectionState=ke.Disconnecting,this._logger.log(Ee.Debug,"Stopping HubConnection."),this._reconnectDelayHandle?(this._logger.log(Ee.Debug,"Connection stopped during reconnect delay. Done reconnecting."),clearTimeout(this._reconnectDelayHandle),this._reconnectDelayHandle=void 0,this._completeClose(),Promise.resolve()):(this._cleanupTimeout(),this._cleanupPingTimer(),this._stopDuringStartError=e||new Error("The connection was stopped before the hub handshake could complete."),this.connection.stop(e)))}stream(e,...t){const[n,r]=this._replaceStreamingParams(t),o=this._createStreamInvocation(e,t,r);let i;const s=new Ze;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===Ie.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===Ie.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 Ie.Invocation:this._invokeClientMethod(e);break;case Ie.StreamItem:case Ie.Completion:{const t=this._callbacks[e.invocationId];t&&(e.type===Ie.Completion&&delete this._callbacks[e.invocationId],t(e));break}case Ie.Ping:break;case Ie.Close:{this._logger.log(Ee.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(Ee.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(Ee.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(Ee.Error,e);const n=new Error(e);throw this._handshakeRejecter(n),n}return this._logger.log(Ee.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===ke.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."))}_invokeClientMethod(e){const t=this._methods[e.target.toLowerCase()];if(t){try{t.forEach((t=>t.apply(this,e.arguments)))}catch(t){this._logger.log(Ee.Error,`A callback for the method ${e.target.toLowerCase()} threw error '${t}'.`)}if(e.invocationId){const e="Server requested a response, which is not supported in this version of the client.";this._logger.log(Ee.Error,e),this._stopPromise=this._stopInternal(new Error(e))}}else this._logger.log(Ee.Warning,`No client method with the name '${e.target}' found.`)}_connectionClosed(e){this._logger.log(Ee.Debug,`HubConnection.connectionClosed(${e}) called while in state ${this._connectionState}.`),this._stopDuringStartError=this._stopDuringStartError||e||new Error("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===ke.Disconnecting?this._completeClose(e):this._connectionState===ke.Connected&&this._reconnectPolicy?this._reconnect(e):this._connectionState===ke.Connected&&this._completeClose(e)}_completeClose(e){if(this._connectionStarted){this._connectionState=ke.Disconnected,this._connectionStarted=!1;try{this._closedCallbacks.forEach((t=>t.apply(this,[e])))}catch(t){this._logger.log(Ee.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(Ee.Debug,"Connection not reconnecting because the IRetryPolicy returned null on the first reconnect attempt."),void this._completeClose(e);if(this._connectionState=ke.Reconnecting,e?this._logger.log(Ee.Information,`Connection reconnecting because of error '${e}'.`):this._logger.log(Ee.Information,"Connection reconnecting."),0!==this._reconnectingCallbacks.length){try{this._reconnectingCallbacks.forEach((t=>t.apply(this,[e])))}catch(t){this._logger.log(Ee.Error,`An onreconnecting callback called with error '${e}' threw error '${t}'.`)}if(this._connectionState!==ke.Reconnecting)return void this._logger.log(Ee.Debug,"Connection left the reconnecting state in onreconnecting callback. Done reconnecting.")}for(;null!==o;){if(this._logger.log(Ee.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!==ke.Reconnecting)return void this._logger.log(Ee.Debug,"Connection left the reconnecting state during reconnect delay. Done reconnecting.");try{if(await this._startInternal(),this._connectionState=ke.Connected,this._logger.log(Ee.Information,"HubConnection reconnected successfully."),0!==this._reconnectedCallbacks.length)try{this._reconnectedCallbacks.forEach((e=>e.apply(this,[this.connection.connectionId])))}catch(e){this._logger.log(Ee.Error,`An onreconnected callback called with connectionId '${this.connection.connectionId}; threw error '${e}'.`)}return}catch(e){if(this._logger.log(Ee.Information,`Reconnect attempt failed because of error '${e}'.`),this._connectionState!==ke.Reconnecting)return this._logger.log(Ee.Debug,`Connection moved to the '${this._connectionState}' from the reconnecting state during reconnect attempt. Done reconnecting.`),void(this._connectionState===ke.Disconnecting&&this._completeClose());r=e instanceof Error?e:new Error(e.toString()),o=this._getNextRetryDelay(n++,Date.now()-t,r)}}this._logger.log(Ee.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(Ee.Error,`IRetryPolicy.nextRetryDelayInMilliseconds(${e}, ${t}) threw error '${n}'.`),null}}_cancelCallbacksWithError(e){const t=this._callbacks;this._callbacks={},Object.keys(t).forEach((n=>{(0,t[n])(null,e)}))}_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:Ie.Invocation}:{arguments:t,target:e,type:Ie.Invocation};{const n=this._invocationId;return this._invocationId++,0!==r.length?{arguments:t,invocationId:n.toString(),streamIds:r,target:e,type:Ie.Invocation}:{arguments:t,invocationId:n.toString(),target:e,type:Ie.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 ut=ot?new TextDecoder:null,dt=ot?"undefined"!=typeof process&&"force"!==process.env.TEXT_DECODER?200:0:it,pt=function(e,t){this.type=e,this.data=t};function ft(e,t,n){var r=Math.floor(n/4294967296),o=n;e.setUint32(t,r),e.setUint32(t+4,o)}function gt(e,t){return 4294967296*e.getInt32(t)+e.getUint32(t+4)}var mt={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),ft(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:gt(t,4),nsec:t.getUint32(0)};default:throw new Error("Unrecognized data size for timestamp: "+e.length)}}(e);return new Date(1e3*t.sec+t.nsec/1e6)}},yt=function(){function e(){this.builtInEncoders=[],this.builtInDecoders=[],this.encoders=[],this.decoders=[],this.register(mt)}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 "+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: "+e+" bytes in UTF-8");this.writeU8(219),this.writeU32(e)}},e.prototype.encodeString=function(e){if(e.length>ct){var t=st(e);this.ensureBufferSizeToWrite(5+t),this.writeStringHeader(t),lt(e,this.bytes,this.pos),this.pos+=t}else t=st(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: "+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: "+t);this.writeU8(198),this.writeU32(t)}var n=wt(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: "+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=ht(e,t,n),i=Uint8Array.prototype.slice.call(e,t,t+n);return this.store(i,o),o},e}(),St=(_t=function(e,t){return(_t=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])})(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}_t(e,t),e.prototype=null===t?Object.create(t):(n.prototype=t.prototype,new n)}),Ct=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]1||a(e,t)}))})}function a(e,t){try{(n=o[e](t)).value instanceof kt?Promise.resolve(n.value.v).then(c,l):h(i[0][2],n)}catch(e){h(i[0][3],e)}var n}function c(e){a("next",e)}function l(e){a("throw",e)}function h(e,t){e(t),i.shift(),i.length&&a(i[0][0],i[0][1])}},xt=new DataView(new ArrayBuffer(0)),Dt=new Uint8Array(xt.buffer),Rt=function(){try{xt.getInt8(0)}catch(e){return e.constructor}throw new Error("never reached")}(),Pt=new Rt("Insufficient data"),Ut=4294967295,At=new Et,Nt=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 St(t,e),t}(Error),Bt=function(){function e(e,t,n,r,o,i,s,a){void 0===e&&(e=yt.defaultCodec),void 0===t&&(t=void 0),void 0===n&&(n=Ut),void 0===r&&(r=Ut),void 0===o&&(o=Ut),void 0===i&&(i=Ut),void 0===s&&(s=Ut),void 0===a&&(a=At),this.extensionCodec=e,this.context=t,this.maxStrLength=n,this.maxBinLength=r,this.maxArrayLength=o,this.maxMapLength=i,this.maxExtLength=s,this.keyDecoder=a,this.totalPos=0,this.pos=0,this.view=xt,this.bytes=Dt,this.headByte=-1,this.stack=[]}return e.prototype.reinitializeState=function(){this.totalPos=0,this.headByte=-1,this.stack.length=0},e.prototype.setBuffer=function(e){this.bytes=wt(e),this.view=function(e){if(e instanceof ArrayBuffer)return new DataView(e);var t=wt(e);return new DataView(t.buffer,t.byteOffset,t.byteLength)}(this.bytes),this.pos=0},e.prototype.appendBuffer=function(e){if(-1!==this.headByte||this.hasRemaining()){var t=this.bytes.subarray(this.pos),n=wt(e),r=new Uint8Array(t.length+n.length);r.set(t),r.set(n,t.length),this.setBuffer(r)}else this.setBuffer(e)},e.prototype.hasRemaining=function(e){return void 0===e&&(e=1),this.view.byteLength-this.pos>=e},e.prototype.createExtraByteError=function(e){var t=this.view,n=this.pos;return new RangeError("Extra "+(t.byteLength-n)+" of "+t.byteLength+" byte(s) found at buffer["+e+"]")},e.prototype.decode=function(e){this.reinitializeState(),this.setBuffer(e);var t=this.doDecodeSync();if(this.hasRemaining())throw this.createExtraByteError(this.pos);return t},e.prototype.decodeMulti=function(e){return Ct(this,(function(t){switch(t.label){case 0:this.reinitializeState(),this.setBuffer(e),t.label=1;case 1:return this.hasRemaining()?[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,u,d;return Ct(this,(function(p){switch(p.label){case 0:i=!1,p.label=1;case 1:p.trys.push([1,6,7,12]),t=It(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 Rt))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())throw this.createExtraByteError(this.totalPos);return[2,s]}throw h=(l=this).headByte,u=l.pos,d=l.totalPos,new RangeError("Insufficient data in parsing "+bt(h)+" at "+d+" ("+u+" 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 Tt(this,arguments,(function(){var n,r,o,i,s,a,c,l,h;return Ct(this,(function(u){switch(u.label){case 0:n=t,r=-1,u.label=1;case 1:u.trys.push([1,13,14,19]),o=It(e),u.label=2;case 2:return[4,kt(o.next())];case 3:if((i=u.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()),u.label=4;case 4:u.trys.push([4,9,,10]),u.label=5;case 5:return[4,kt(this.doDecodeSync())];case 6:return[4,u.sent()];case 7:return u.sent(),0==--r?[3,8]:[3,5];case 8:return[3,10];case 9:if(!((a=u.sent())instanceof Rt))throw a;return[3,10];case 10:this.totalPos+=this.pos,u.label=11;case 11:return[3,2];case 12:return[3,19];case 13:return c=u.sent(),l={error:c},[3,19];case 14:return u.trys.push([14,,17,18]),i&&!i.done&&(h=o.return)?[4,kt(h.call(o))]:[3,16];case 15:u.sent(),u.label=16;case 16:return[3,18];case 17:if(l)throw l.error;return[7];case 18:return[7];case 19:return[2]}}))}))},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 Nt("Unrecognized type byte: "+bt(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 Nt("The type of key must be string or number but "+typeof t);if("__proto__"===t)throw new Nt("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 Nt("Unrecognized array type byte: "+bt(e))}},e.prototype.pushMapState=function(e){if(e>this.maxMapLength)throw new Nt("Max length exceeded: map length ("+e+") > maxMapLengthLength ("+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 Nt("Max length exceeded: array length ("+e+") > maxArrayLength ("+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 Nt("Max length exceeded: UTF-8 byte length ("+e+") > maxStrLength ("+this.maxStrLength+")");if(this.bytes.byteLengthdt?function(e,t,n){var r=e.subarray(t,t+n);return ut.decode(r)}(this.bytes,o,e):ht(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 Nt("Max length exceeded: bin length ("+e+") > maxBinLength ("+this.maxBinLength+")");if(!this.hasRemaining(e+t))throw Pt;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 Nt("Max length exceeded: ext length ("+e+") > maxExtLength ("+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=gt(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 $t{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 Lt=new Uint8Array([145,Ie.Ping]);class Mt{constructor(e){this.name="messagepack",this.version=1,this.transferFormat=Ce.Binary,this._errorResult=1,this._voidResult=2,this._nonVoidResult=3,e=e||{},this._encoder=new vt(e.extensionCodec,e.context,e.maxDepth,e.initialBufferSize,e.sortKeys,e.forceFloat32,e.ignoreUndefined,e.forceIntegerToFloat),this._decoder=new Bt(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=Ae.instance);const r=$t.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 Ie.Invocation:return this._writeInvocation(e);case Ie.StreamInvocation:return this._writeStreamInvocation(e);case Ie.StreamItem:return this._writeStreamItem(e);case Ie.Completion:return this._writeCompletion(e);case Ie.Ping:return $t.write(Lt);case Ie.CancelInvocation:return this._writeCancelInvocation(e);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 Ie.Invocation:return this._createInvocationMessage(this._readHeaders(n),n);case Ie.StreamItem:return this._createStreamItemMessage(this._readHeaders(n),n);case Ie.Completion:return this._createCompletionMessage(this._readHeaders(n),n);case Ie.Ping:return this._createPingMessage(n);case Ie.Close:return this._createCloseMessage(n);default:return t.log(Ee.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:Ie.Close}}_createPingMessage(e){if(e.length<1)throw new Error("Invalid payload for Ping message.");return{type:Ie.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:Ie.Invocation}:{arguments:t[4],headers:e,streamIds:[],target:t[3],type:Ie.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:Ie.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:Ie.Completion}}_writeInvocation(e){let t;return t=e.streamIds?this._encoder.encode([Ie.Invocation,e.headers||{},e.invocationId||null,e.target,e.arguments,e.streamIds]):this._encoder.encode([Ie.Invocation,e.headers||{},e.invocationId||null,e.target,e.arguments]),$t.write(t.slice())}_writeStreamInvocation(e){let t;return t=e.streamIds?this._encoder.encode([Ie.StreamInvocation,e.headers||{},e.invocationId,e.target,e.arguments,e.streamIds]):this._encoder.encode([Ie.StreamInvocation,e.headers||{},e.invocationId,e.target,e.arguments]),$t.write(t.slice())}_writeStreamItem(e){const t=this._encoder.encode([Ie.StreamItem,e.headers||{},e.invocationId,e.item]);return $t.write(t.slice())}_writeCompletion(e){const t=e.error?this._errorResult:e.result?this._nonVoidResult:this._voidResult;let n;switch(t){case this._errorResult:n=this._encoder.encode([Ie.Completion,e.headers||{},e.invocationId,t,e.error]);break;case this._voidResult:n=this._encoder.encode([Ie.Completion,e.headers||{},e.invocationId,t]);break;case this._nonVoidResult:n=this._encoder.encode([Ie.Completion,e.headers||{},e.invocationId,t,e.result])}return $t.write(n.slice())}_writeCancelInvocation(e){const t=this._encoder.encode([Ie.CancelInvocation,e.headers||{},e.invocationId]);return $t.write(t.slice())}_readHeaders(e){const t=e[1];if("object"!=typeof t)throw new Error("Invalid headers.");return t}}let Ht=!1;const Ot="function"==typeof TextDecoder?new TextDecoder("utf-8"):null,Ft=Ot?Ot.decode.bind(Ot):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("")},jt=Math.pow(2,32),Wt=Math.pow(2,21)-1;function zt(e,t){return e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24}function qt(e,t){return e[t]+(e[t+1]<<8)+(e[t+2]<<16)+(e[t+3]<<24>>>0)}function Jt(e,t){const n=qt(e,t+4);if(n>Wt)throw new Error(`Cannot read uint64 with high order part ${n}, because the result would exceed Number.MAX_SAFE_INTEGER.`);return n*jt+qt(e,t)}class Kt{constructor(e){this.batchData=e;const t=new Gt(e);this.arrayRangeReader=new Qt(e),this.arrayBuilderSegmentReader=new Zt(e),this.diffReader=new Vt(e),this.editReader=new Xt(e,t),this.frameReader=new Yt(e,t)}updatedComponents(){return zt(this.batchData,this.batchData.length-20)}referenceFrames(){return zt(this.batchData,this.batchData.length-16)}disposedComponentIds(){return zt(this.batchData,this.batchData.length-12)}disposedEventHandlerIds(){return zt(this.batchData,this.batchData.length-8)}updatedComponentsEntry(e,t){const n=e+4*t;return zt(this.batchData,n)}referenceFramesEntry(e,t){return e+20*t}disposedComponentIdsEntry(e,t){const n=e+4*t;return zt(this.batchData,n)}disposedEventHandlerIdsEntry(e,t){const n=e+8*t;return Jt(this.batchData,n)}}class Vt{constructor(e){this.batchDataUint8=e}componentId(e){return zt(this.batchDataUint8,e)}edits(e){return e+4}editsEntry(e,t){return e+16*t}}class Xt{constructor(e,t){this.batchDataUint8=e,this.stringReader=t}editType(e){return zt(this.batchDataUint8,e)}siblingIndex(e){return zt(this.batchDataUint8,e+4)}newTreeIndex(e){return zt(this.batchDataUint8,e+8)}moveToSiblingIndex(e){return zt(this.batchDataUint8,e+8)}removedAttributeName(e){const t=zt(this.batchDataUint8,e+12);return this.stringReader.readString(t)}}class Yt{constructor(e,t){this.batchDataUint8=e,this.stringReader=t}frameType(e){return zt(this.batchDataUint8,e)}subtreeLength(e){return zt(this.batchDataUint8,e+4)}elementReferenceCaptureId(e){const t=zt(this.batchDataUint8,e+4);return this.stringReader.readString(t)}componentId(e){return zt(this.batchDataUint8,e+8)}elementName(e){const t=zt(this.batchDataUint8,e+8);return this.stringReader.readString(t)}textContent(e){const t=zt(this.batchDataUint8,e+4);return this.stringReader.readString(t)}markupContent(e){const t=zt(this.batchDataUint8,e+4);return this.stringReader.readString(t)}attributeName(e){const t=zt(this.batchDataUint8,e+4);return this.stringReader.readString(t)}attributeValue(e){const t=zt(this.batchDataUint8,e+8);return this.stringReader.readString(t)}attributeEventHandlerId(e){return Jt(this.batchDataUint8,e+12)}}class Gt{constructor(e){this.batchDataUint8=e,this.stringTableStartIndex=zt(e,e.length-4)}readString(e){if(-1===e)return null;{const n=zt(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(en.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(en.Debug,`Waiting for batch ${this.nextBatchId}. Batch ${e} not processed.`);try{this.nextBatchId++,this.logger.log(en.Debug,`Applying batch ${e}.`),function(e,t){const n=Q[e];if(!n)throw new Error(`There is no browser renderer with ID ${e}.`);const r=t.arrayRangeReader,o=t.updatedComponents(),i=r.values(o),s=r.count(o),a=t.referenceFrames(),c=r.values(a),l=t.diffReader;for(let e=0;e=this.minLevel){const n=`[${(new Date).toISOString()}] ${en[e]}: ${t}`;switch(e){case en.Critical:case en.Error:console.error(n);break;case en.Warning:console.warn(n);break;case en.Information:console.info(n);break;default:console.log(n)}}}}class on{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!==ke.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!==ke.Connected)return!1;const t=await e.invoke("StartCircuit",re.getBaseURI(),re.getLocationHref(),JSON.stringify(this.components.map((e=>e.toRecord()))),this.applicationState||"");return!!t&&(this.initialize(t),!0)}resolveElement(e){const t=Number.parseInt(e);if(Number.isNaN(t))throw new Error(`Invalid sequence number '${e}'.`);return function(e,t){if(!e.parentNode)throw new Error(`Comment not connected to the DOM ${e.textContent}`);const n=e.parentNode,r=k(n,!0),o=A(r);return Array.from(n.childNodes).forEach((e=>o.push(e))),e[C]=r,t&&(e[I]=t,k(t)),k(e)}(this.components[t].start,this.components[t].end)}}const sn={configureSignalR:e=>{},logLevel:en.Warning,reconnectionOptions:{maxRetries:8,retryIntervalMilliseconds:2e4,dialogId:"components-reconnect-modal"}};class an{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.modal.innerHTML='

Alternatively, reload

',this.message=this.modal.querySelector("h5"),this.button=this.modal.querySelector("button"),this.reloadParagraph=this.modal.querySelector("p"),this.loader=this.getLoader(),this.message.after(this.loader),this.button.addEventListener("click",(async()=>{this.show();try{await(null==fe?void 0:fe.reconnect)()||this.rejected()}catch(e){this.logger.log(en.Error,e),this.failed()}})),this.reloadParagraph.querySelector("a").addEventListener("click",(()=>location.reload()))}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",this.message.innerHTML="Reconnection failed. Try reloading the page if you're unable to reconnect.",this.message.querySelector("a").addEventListener("click",(()=>location.reload()))}rejected(){this.button.style.display="none",this.reloadParagraph.style.display="none",this.loader.style.display="none",this.message.innerHTML="Could not reconnect to the server. Reload the page to restore functionality.",this.message.querySelector("a").addEventListener("click",(()=>location.reload()))}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 cn{constructor(e,t,n){this.dialog=e,this.maxRetries=t,this.document=n,this.document=n;const r=this.document.getElementById(cn.MaxRetriesId);r&&(r.innerText=this.maxRetries.toString())}show(){this.removeClasses(),this.dialog.classList.add(cn.ShowClassName)}update(e){const t=this.document.getElementById(cn.CurrentAttemptId);t&&(t.innerText=e.toString())}hide(){this.removeClasses(),this.dialog.classList.add(cn.HideClassName)}failed(){this.removeClasses(),this.dialog.classList.add(cn.FailedClassName)}rejected(){this.removeClasses(),this.dialog.classList.add(cn.RejectedClassName)}removeClasses(){this.dialog.classList.remove(cn.ShowClassName,cn.HideClassName,cn.FailedClassName,cn.RejectedClassName)}}cn.ShowClassName="components-reconnect-show",cn.HideClassName="components-reconnect-hide",cn.FailedClassName="components-reconnect-failed",cn.RejectedClassName="components-reconnect-rejected",cn.MaxRetriesId="components-reconnect-max-retries",cn.CurrentAttemptId="components-reconnect-current-attempt";class ln{constructor(e,t,n){this._currentReconnectionProcess=null,this._logger=e,this._reconnectionDisplay=t,this._reconnectCallback=n||(()=>fe.reconnect())}onConnectionDown(e,t){if(!this._reconnectionDisplay){const t=document.getElementById(e.dialogId);this._reconnectionDisplay=t?new cn(t,e.maxRetries,document):new an(e.dialogId,e.maxRetries,document,this._logger)}this._currentReconnectionProcess||(this._currentReconnectionProcess=new hn(e,this._logger,this._reconnectCallback,this._reconnectionDisplay))}onConnectionUp(){this._currentReconnectionProcess&&(this._currentReconnectionProcess.dispose(),this._currentReconnectionProcess=null)}}class hn{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;thn.MaximumFirstRetryInterval?hn.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(en.Error,e)}}this.reconnectDisplay.failed()}delay(e){return new Promise((t=>setTimeout(t,e)))}}hn.MaximumFirstRetryInterval=3e3;const un=/^\s*Blazor-Component-State:(?[a-zA-Z0-9\+\/=]+)$/;function dn(e){var t;if(e.nodeType===Node.COMMENT_NODE){const n=e.textContent||"",r=un.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 gn(e,t){const n=e.currentElement;if(n&&n.nodeType===Node.COMMENT_NODE&&n.textContent){const r=fn.exec(n.textContent),o=r&&r.groups&&r.groups.descriptor;if(!o)return;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;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.");if(c){const e=mn(c,n);if(!e)throw new Error(`Could not find an end component comment for '${t}'`);return{type:r,assembly:o,typeName:i,parameterDefinitions:s&&atob(s),parameterValues:a&&atob(a),start:t,prerenderId:c,end:e}}return{type:r,assembly:o,typeName:i,parameterDefinitions:s&&atob(s),parameterValues:a&&atob(a),start:t}}}(r,n,e);case"server":return function(e,t,n){const{type:r,descriptor:o,sequence:i,prerenderId:s}=e;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)}'`);if(s){const e=mn(s,n);if(!e)throw new Error(`Could not find an end component comment for '${t}'`);return{type:r,sequence:i,descriptor:o,start:t,prerenderId:s,end:e}}return{type:r,sequence:i,descriptor:o,start:t}}}(r,n,e)}}catch(e){throw new Error(`Found malformed component comment at ${n.textContent}`)}}}function mn(e,t){for(;t.next()&&t.currentElement;){const n=t.currentElement;if(n.nodeType!==Node.COMMENT_NODE)continue;if(!n.textContent)continue;const r=fn.exec(n.textContent),o=r&&r[1];if(o)return yn(o,e),n}}function yn(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 wn{constructor(e){this.childNodes=e,this.currentIndex=-1,this.length=e.length}next(){return this.currentIndex++,this.currentIndexe.sequence-t.sequence))}(e)}(document),o=dn(document),i=new on(r,o||""),s=await Tn(t,n,i);if(!await i.startCircuit(s))return void n.log(en.Error,"Failed to start the circuit.");let a=!1;const c=()=>{if(!a){const e=new FormData,t=i.circuitId;e.append("circuitId",t),a=navigator.sendBeacon("_blazor/disconnect",e)}};fe.disconnect=c,window.addEventListener("unload",c,{capture:!1,once:!0}),fe.reconnect=async e=>{if(Cn)return!1;const r=e||await Tn(t,n,i);return await i.reconnect(r)?(t.reconnectionHandler.onConnectionUp(),!0):(n.log(en.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)},n.log(en.Information,"Blazor server-side application started.")}async function Tn(t,n,r){const i=new Mt;i.name="blazorpack";const s=(new rt).withUrl("_blazor").withHubProtocol(i);t.configureSignalR(s);const a=s.build();o=(e,t)=>{a.send("DispatchBrowserEvent",JSON.stringify(e),JSON.stringify(t))},fe._internal.navigationManager.listenForNavigationEvents(((e,t)=>a.send("OnLocationChanged",e,t))),a.on("JS.AttachComponent",((e,t)=>function(e,t,n){let r=Q[0];r||(r=Q[0]=new V(0)),r.attachRootComponentToLogicalElement(n,t)}(0,r.resolveElement(t),e))),a.on("JS.BeginInvokeJS",e.jsCallDispatcher.beginInvokeJSFromDotNet),a.on("JS.EndInvokeDotNet",e.jsCallDispatcher.endInvokeDotNetFromJS),a.on("JS.ReceiveByteArray",e.jsCallDispatcher.receiveByteArray);const c=tn.getOrCreate(n);a.on("JS.RenderBatch",((e,t)=>{n.log(en.Debug,`Received render batch with id ${e} and ${t.byteLength} bytes.`),c.processBatch(e,t,a)})),a.onclose((e=>!Cn&&t.reconnectionHandler.onConnectionDown(t.reconnectionOptions,e))),a.on("JS.Error",(e=>{Cn=!0,xn(a,e,n),async function(){let e=document.querySelector("#blazor-error-ui");e&&(e.style.display="block"),Ht||(Ht=!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()}})))}()})),fe._internal.forceCloseConnection=()=>a.stop(),fe._internal.sendJSDataStream=async(e,t)=>{setTimeout((async()=>{let n=5,r=(new Date).valueOf();try{const o=31744;let i=0;for(;i1)await a.send("SupplyJSDataChunk",t,c,null);else{await a.invoke("SupplyJSDataChunk",t,c,null);const e=(new Date).valueOf(),o=e-r;r=e,n=Math.max(1,Math.round(500/o))}i+=s}}catch(e){await a.send("SupplyJSDataChunk",t,null,e.toString())}}),0)};try{await a.start()}catch(e){xn(a,e,n)}return e.attachDispatcher({beginInvokeDotNetFromJS:(e,t,n,r,o)=>{a.send("BeginInvokeDotNetFromJS",e?e.toString():null,t,n,r||0,o)},endInvokeJSFromDotNet:(e,t,n)=>{a.send("EndInvokeJSFromDotNet",e,t,n)},sendByteArray:(e,t)=>{a.send("ReceiveByteArray",e,t)}}),a}function xn(e,t,n){n.log(en.Error,t),e&&e.stop()}fe.start=kn,document&&document.currentScript&&"false"!==document.currentScript.getAttribute("autostart")&&kn()})(); \ No newline at end of file +(()=>{"use strict";var e,t,n;!function(e){window.DotNet=e;const t=[],n=new Map;class r{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 o="__jsObjectId",i={},s={0:new r(window)};s[0]._cachedFunctions.set("import",(e=>("string"==typeof e&&e.startsWith("./")&&(e=document.baseURI+e.substr(2)),import(e))));let a,c=1,l=1,h=null;function u(e){t.push(e)}function d(e){if(e&&"object"==typeof e){s[l]=new r(e);let t={[o]:l};return e.buffer instanceof ArrayBuffer&&void 0!==e.byteLength&&(t.__jsDataReferenceLength=e.byteLength),l++,t}throw new Error(`Cannot create a JSObjectReference from the value '${e}'.`)}function p(e){return e?JSON.parse(e,((e,n)=>t.reduce(((t,n)=>n(e,t)),n))):null}function f(e,t,n,r){const o=m();if(o.invokeDotNetFromJS){const i=I(r),s=o.invokeDotNetFromJS(e,t,n,i);return s?p(s):null}throw new Error("The current dispatcher does not support synchronous calls from JS to .NET. Use invokeMethodAsync instead.")}function g(e,t,n,r){if(e&&n)throw new Error(`For instance method calls, assemblyName should be null. Received '${e}'.`);const o=c++,s=new Promise(((e,t)=>{i[o]={resolve:e,reject:t}}));try{const i=I(r);m().beginInvokeDotNetFromJS(o,e,t,n,i)}catch(e){y(o,!1,e)}return s}function m(){if(null!==h)return h;throw new Error("No .NET call dispatcher has been set.")}function y(e,t,n){if(!i.hasOwnProperty(e))throw new Error(`There is no pending async call with ID ${e}.`);const r=i[e];delete i[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 v(e,t){let n=s[t];if(n)return n.findFunction(e);throw new Error(`JS object instance with ID ${t} does not exist (has it been disposed?).`)}function b(e){delete s[e]}e.attachDispatcher=function(e){h=e},e.attachReviver=u,e.invokeMethod=function(e,t,...n){return f(e,t,null,n)},e.invokeMethodAsync=function(e,t,...n){return g(e,t,null,n)},e.createJSObjectReference=d,e.disposeJSObjectReference=function(e){const t=e&&e.__jsObjectId;"number"==typeof t&&b(t)},function(e){e[e.Default=0]="Default",e[e.JSObjectReference=1]="JSObjectReference"}(a=e.JSCallResultType||(e.JSCallResultType={})),e.jsCallDispatcher={findJSFunction:v,disposeJSObjectReferenceById:b,invokeJSFromDotNet:(e,t,n,r)=>{const o=S(v(e,r).apply(null,p(t)),n);return null==o?null:I(o)},beginInvokeJSFromDotNet:(e,t,n,r,o)=>{const i=new Promise((e=>{e(v(t,o).apply(null,p(n)))}));e&&i.then((t=>m().endInvokeJSFromDotNet(e,!0,I([e,!0,S(t,r)]))),(t=>m().endInvokeJSFromDotNet(e,!1,JSON.stringify([e,!1,w(t)]))))},endInvokeDotNetFromJS:(e,t,n)=>{const r=t?p(n):new Error(n);y(parseInt(e),t,r)},receiveByteArray:(e,t)=>{n.set(e,t)}};class _{constructor(e){this._id=e}invokeMethod(e,...t){return f(null,e,this._id,t)}invokeMethodAsync(e,...t){return g(null,e,this._id,t)}dispose(){g(null,"__Dispose",this._id,null).catch((e=>console.error(e)))}serializeAsArg(){return{__dotNetObject:this._id}}}const E="__byte[]";function S(e,t){switch(t){case a.Default:return e;case a.JSObjectReference:return d(e);default:throw new Error(`Invalid JS call result type '${t}'.`)}}u((function(e,t){if(t&&"object"==typeof t){if(t.hasOwnProperty("__dotNetObject"))return new _(t.__dotNetObject);if(t.hasOwnProperty(o)){const e=t.__jsObjectId,n=s[e];if(n)return n.getWrappedObject();throw new Error(`JS object instance with Id '${e}' does not exist. It may have been disposed.`)}if(t.hasOwnProperty(E)){const e=t["__byte[]"],r=n.get(e);if(void 0===r)throw new Error(`Byte array index '${e}' does not exist.`);return r}}return t}));let C=0;function I(e){return C=0,JSON.stringify(e,k)}function k(e,t){if(t instanceof _)return t.serializeAsArg();if(t instanceof Uint8Array){h.sendByteArray(C,t);const e={[E]:C};return C++,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"}(n||(n={}));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}}let o;function i(e,t){if(!o)throw new Error("eventDispatcher not initialized. Call 'setEventDispatcher' to configure it.");o(e,t)}const s=new Map,a=new Map,c={createEventArgs:()=>({})},l=[];function h(e){return s.get(e)}function u(e){const t=s.get(e);return(null==t?void 0:t.browserEventName)||e}function d(e,t){e.forEach((e=>s.set(e,t)))}function p(e){const t=[];for(let n=0;n{return{...f(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}}),d(["focus","blur","focusin","focusout"],c),d(["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};var t}}),d(["contextmenu","click","mouseover","mouseout","mousemove","mousedown","mouseup","dblclick"],{createEventArgs:e=>f(e)}),d(["error"],{createEventArgs:e=>{return{message:(t=e).message,filename:t.filename,lineno:t.lineno,colno:t.colno};var t}}),d(["loadstart","timeout","abort","load","loadend","progress"],{createEventArgs:e=>{return{lengthComputable:(t=e).lengthComputable,loaded:t.loaded,total:t.total};var t}}),d(["touchcancel","touchend","touchmove","touchenter","touchleave","touchstart"],{createEventArgs:e=>{return{detail:(t=e).detail,touches:p(t.touches),targetTouches:p(t.targetTouches),changedTouches:p(t.changedTouches),ctrlKey:t.ctrlKey,shiftKey:t.shiftKey,altKey:t.altKey,metaKey:t.metaKey,type:t.type};var t}}),d(["gotpointercapture","lostpointercapture","pointercancel","pointerdown","pointerenter","pointerleave","pointermove","pointerout","pointerover","pointerup"],{createEventArgs:e=>{return{...f(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}}),d(["wheel","mousewheel"],{createEventArgs:e=>{return{...f(t=e),deltaX:t.deltaX,deltaY:t.deltaY,deltaZ:t.deltaZ,deltaMode:t.deltaMode};var t}}),d(["toggle"],c);const g=["date","datetime-local","month","time","week"],m=E(["abort","blur","change","error","focus","load","loadend","loadstart","mouseenter","mouseleave","progress","reset","scroll","submit","unload","toggle","DOMNodeInsertedIntoDocument","DOMNodeRemovedFromDocument"]),y={submit:!0},w=E(["click","dblclick","mousedown","mousemove","mouseup"]);class v{constructor(e){this.browserRendererId=e,this.afterClickCallbacks=[];const t=++v.nextEventDelegatorId;this.eventsCollectionKey=`_blazorEvents_${t}`,this.eventInfoStore=new b(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,a.get(n));var n;t&&t.forEach((t=>this.dispatchGlobalEventToAllElements(t,e))),"click"===e.type&&this.afterClickCallbacks.forEach((t=>t(e)))}dispatchGlobalEventToAllElements(e,t){let n=t.target,o=null,s=!1;const a=m.hasOwnProperty(e);let c=!1;for(;n;){const d=this.getEventHandlerInfosForElement(n,!1);if(d){const a=d.getHandler(e);if(a&&(l=n,u=t.type,!((l instanceof HTMLButtonElement||l instanceof HTMLInputElement||l instanceof HTMLTextAreaElement||l instanceof HTMLSelectElement)&&w.hasOwnProperty(u)&&l.disabled))){if(!s){const n=h(e);o=(null==n?void 0:n.createEventArgs)?n.createEventArgs(t):{},s=!0}y.hasOwnProperty(t.type)&&t.preventDefault(),i({browserRendererId:this.browserRendererId,eventHandlerId:a.eventHandlerId,eventName:e,eventFieldInfo:r.fromEvent(a.renderingComponentId,t)},o)}d.stopPropagation(e)&&(c=!0),d.preventDefault(e)&&t.preventDefault()}n=a||c?null:n.parentElement}var l,u}getEventHandlerInfosForElement(e,t){return e.hasOwnProperty(this.eventsCollectionKey)?e[this.eventsCollectionKey]:t?e[this.eventsCollectionKey]=new _:null}}v.nextEventDelegatorId=0;class b{constructor(e){this.globalListener=e,this.infosByEventHandlerId={},this.countByEventName={},l.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=u(e),this.countByEventName.hasOwnProperty(e))this.countByEventName[e]++;else{this.countByEventName[e]=1;const t=m.hasOwnProperty(e);document.addEventListener(e,this.globalListener,t)}}update(e,t){if(this.infosByEventHandlerId.hasOwnProperty(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=u(t.eventName);0==--this.countByEventName[n]&&(delete this.countByEventName[n],document.removeEventListener(n,this.globalListener))}return t}handleEventNameAliasAdded(e,t){if(this.countByEventName.hasOwnProperty(e)){const n=this.countByEventName[e];delete this.countByEventName[e],document.removeEventListener(e,this.globalListener),this.addGlobalListener(t),this.countByEventName[t]+=n-1}}}class _{constructor(){this.handlers={},this.preventDefaultFlags=null,this.stopPropagationFlags=null}getHandler(e){return this.handlers.hasOwnProperty(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 E(e){const t={};return e.forEach((e=>{t[e]=!0})),t}const S=H("_blazorLogicalChildren"),C=H("_blazorLogicalParent"),I=H("_blazorLogicalEnd");function k(e,t){if(e.childNodes.length>0&&!t)throw new Error("New logical elements must start empty, or allowExistingContents must be true");return S in e||(e[S]=[]),e}function T(e,t){const n=document.createComment("!");return D(n,e,t),n}function D(e,t,n){const r=e;if(e instanceof Comment&&A(r)&&A(r).length>0)throw new Error("Not implemented: inserting non-empty logical container");if(R(r))throw new Error("Not implemented: moving existing logical children");const o=A(t);if(n0;)x(n,0)}const r=n;r.parentNode.removeChild(r)}function R(e){return e[C]||null}function P(e,t){return A(e)[t]}function U(e){var t=B(e);return"http://www.w3.org/2000/svg"===t.namespaceURI&&"foreignObject"!==t.tagName}function A(e){return e[S]}function N(e,t){const n=A(e);t.forEach((e=>{e.moveRangeStart=n[e.fromSiblingIndex],e.moveRangeEnd=L(e.moveRangeStart)})),t.forEach((t=>{const r=t.moveToBeforeMarker=document.createComment("marker"),o=n[t.toSiblingIndex+1];o?o.parentNode.insertBefore(r,o):M(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 B(e){if(e instanceof Element)return e;if(e instanceof Comment)return e.parentNode;throw new Error("Not a valid logical element")}function $(e){const t=A(R(e));return t[Array.prototype.indexOf.call(t,e)+1]||null}function M(e,t){if(t instanceof Element)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=$(t);n?n.parentNode.insertBefore(e,n):M(e,R(t))}}}function L(e){if(e instanceof Element)return e;const t=$(e);if(t)return t.previousSibling;{const t=R(e);return t instanceof Element?t.lastChild:L(t)}}function H(e){return"function"==typeof Symbol?Symbol():e}function O(e){return`_bl_${e}`}e.attachReviver(((e,t)=>t&&"object"==typeof t&&t.hasOwnProperty("__internalId")&&"string"==typeof t.__internalId?function(e){const t=`[${O(e)}]`;return document.querySelector(t)}(t.__internalId):t));const F="_blazorSelectValue",j=document.createElement("template"),W=document.createElementNS("http://www.w3.org/2000/svg","g"),z={},q="__internal_",J="preventDefault_",K="stopPropagation_";class V{constructor(e){this.childComponentLocations={},this.eventDelegator=new v(e),this.eventDelegator.notifyAfterClick((e=>{if(!ee)return;if(0!==e.button||function(e){return e.ctrlKey||e.shiftKey||e.altKey||e.metaKey}(e))return;if(e.defaultPrevented)return;const t=function(e){const t=!window._blazorDisableComposedPath&&e.composedPath&&e.composedPath();if(t){for(let e=0;ese(!1))))},enableNavigationInterception:function(){ee=!0},navigateTo:oe,getBaseURI:()=>document.baseURI,getLocationHref:()=>location.href};function oe(e,t,n=!1){const r=ce(e);if(!t&&he(r))ie(r,!1,n);else if(t&&location.href===e){const t=e+"?";history.replaceState(null,"",t),location.replace(e)}else n?history.replaceState(null,"",r):location.href=e}function ie(e,t,n=!1){Z=!0,n?history.replaceState(null,"",e):history.pushState(null,"",e),se(t)}async function se(e){ne&&await ne(location.href,e)}let ae;function ce(e){return ae=ae||document.createElement("a"),ae.href=e,ae.href}function le(e,t){return e?e.tagName===t?e:le(e.parentElement,t):null}function he(e){const t=(n=document.baseURI).substr(0,n.lastIndexOf("/")+1);var n;return e.startsWith(t)}const ue={init:function(e,t,n,r=50){const o=pe(t);(o||document.documentElement).style.overflowAnchor="none";const i=new IntersectionObserver((function(r){r.forEach((r=>{var o;if(!r.isIntersecting)return;const i=t.getBoundingClientRect(),s=n.getBoundingClientRect().top-i.bottom,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`});i.observe(t),i.observe(n);const s=c(t),a=c(n);function c(e){const t=new MutationObserver((()=>{i.unobserve(e),i.observe(e)}));return t.observe(e,{attributes:!0}),t}de[e._id]={intersectionObserver:i,mutationObserverBefore:s,mutationObserverAfter:a}},dispose:function(e){const t=de[e._id];t&&(t.intersectionObserver.disconnect(),t.mutationObserverBefore.disconnect(),t.mutationObserverAfter.disconnect(),e.dispose(),delete de[e._id])}},de={};function pe(e){return e?"visible"!==getComputedStyle(e).overflowY?e:pe(e.parentElement):null}const fe={navigateTo:oe,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=a.get(t.browserEventName);n?n.push(e):a.set(t.browserEventName,[e]),l.forEach((n=>n(e,t.browserEventName)))}s.set(e,t)},_internal:{navigationManager:re,domWrapper:{focus:function(e,t){if(!(e instanceof HTMLElement))throw new Error("Unable to focus an invalid element.");e.focus({preventScroll:t})}},Virtualize:ue}};window.Blazor=fe;const ge=[0,2e3,1e4,3e4,null];class me{constructor(e){this._retryDelays=void 0!==e?[...e,null]:ge}nextRetryDelayInMilliseconds(e){return this._retryDelays[e.previousRetryCount]}}class ye extends Error{constructor(e,t){const n=new.target.prototype;super(`${e}: Status code '${t}'`),this.statusCode=t,this.__proto__=n}}class we extends Error{constructor(e="A timeout occurred."){const t=new.target.prototype;super(e),this.__proto__=t}}class ve extends Error{constructor(e="An abort occurred."){const t=new.target.prototype;super(e),this.__proto__=t}}class be{constructor(e,t,n){this.statusCode=e,this.statusText=t,this.content=n}}class _e{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""}}var Ee,Se,Ce,Ie,ke;!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"}(Ee||(Ee={}));class Te extends _e{constructor(e){if(super(),this._logger=e,"undefined"==typeof fetch){const e=require;this._jar=new(e("tough-cookie").CookieJar),this._fetchType=e("node-fetch"),this._fetchType=e("fetch-cookie")(this._fetchType,this._jar),this._abortControllerType=e("abort-controller")}else this._fetchType=fetch.bind(self),this._abortControllerType=AbortController}async send(e){if(e.abortSignal&&e.abortSignal.aborted)throw new ve;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 ve});let r,o=null;if(e.timeout){const r=e.timeout;o=setTimeout((()=>{t.abort(),this._logger.log(Ee.Warning,"Timeout from HTTP request."),n=new we}),r)}try{r=await this._fetchType(e.url,{body:e.content,cache:"no-cache",credentials:!0===e.withCredentials?"include":"same-origin",headers:{"Content-Type":"text/plain;charset=UTF-8","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(Ee.Warning,`Error from HTTP request. ${e}.`),e}finally{o&&clearTimeout(o),e.abortSignal&&(e.abortSignal.onabort=null)}if(!r.ok){const e=await De(r,"text");throw new ye(e||r.statusText,r.status)}const i=De(r,e.responseType),s=await i;return new be(r.status,r.statusText,s)}getCookieString(e){return""}}function De(e,t){let n;switch(t){case"arraybuffer":n=e.arrayBuffer();break;case"text":n=e.text();break;case"blob":case"document":case"json":throw new Error(`${t} is not supported.`);default:n=e.text()}return n}class xe extends _e{constructor(e){super(),this._logger=e}send(e){return e.abortSignal&&e.abortSignal.aborted?Promise.reject(new ve):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"),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 ve)}),e.timeout&&(r.timeout=e.timeout),r.onload=()=>{e.abortSignal&&(e.abortSignal.onabort=null),r.status>=200&&r.status<300?t(new be(r.status,r.statusText,r.response||r.responseText)):n(new ye(r.response||r.responseText||r.statusText,r.status))},r.onerror=()=>{this._logger.log(Ee.Warning,`Error from HTTP request. ${r.status}: ${r.statusText}.`),n(new ye(r.statusText,r.status))},r.ontimeout=()=>{this._logger.log(Ee.Warning,"Timeout from HTTP request."),n(new we)},r.send(e.content||"")})):Promise.reject(new Error("No url defined.")):Promise.reject(new Error("No method defined."))}}class Re extends _e{constructor(e){if(super(),"undefined"!=typeof fetch)this._httpClient=new Te(e);else{if("undefined"==typeof XMLHttpRequest)throw new Error("No usable HttpClient found.");this._httpClient=new xe(e)}}send(e){return e.abortSignal&&e.abortSignal.aborted?Promise.reject(new ve):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)}}class Pe{}Pe.Authorization="Authorization",Pe.Cookie="Cookie",function(e){e[e.None=0]="None",e[e.WebSockets=1]="WebSockets",e[e.ServerSentEvents=2]="ServerSentEvents",e[e.LongPolling=4]="LongPolling"}(Se||(Se={})),function(e){e[e.Text=1]="Text",e[e.Binary=2]="Binary"}(Ce||(Ce={}));class Ue{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 Ae{constructor(){}log(e,t){}}Ae.instance=new Ae;class Ne{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 Be{static get isBrowser(){return"object"==typeof window}static get isWebWorker(){return"object"==typeof self&&"importScripts"in self}static get isNode(){return!this.isBrowser&&!this.isWebWorker}}function $e(e,t){let n="";return Me(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 Me(e){return e&&"undefined"!=typeof ArrayBuffer&&(e instanceof ArrayBuffer||e.constructor&&"ArrayBuffer"===e.constructor.name)}async function Le(e,t,n,r,o,i,s,a,c){let l={};if(o){const e=await o();e&&(l={Authorization:`Bearer ${e}`})}const[h,u]=Fe();l[h]=u,e.log(Ee.Trace,`(${t} transport) sending data. ${$e(i,s)}.`);const d=Me(i)?"arraybuffer":"text",p=await n.post(r,{content:i,headers:{...l,...c},responseType:d,withCredentials:a});e.log(Ee.Trace,`(${t} transport) request complete. Response status: ${p.statusCode}.`)}class He{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 Oe{constructor(e){this._minLevel=e,this.out=console}log(e,t){if(e>=this._minLevel){const n=`[${(new Date).toISOString()}] ${Ee[e]}: ${t}`;switch(e){case Ee.Critical:case Ee.Error:this.out.error(n);break;case Ee.Warning:this.out.warn(n);break;case Ee.Information:this.out.info(n);break;default:this.out.log(n)}}}}function Fe(){let e="X-SignalR-User-Agent";return Be.isNode&&(e="User-Agent"),[e,je("0.0.0-DEV_BUILD",We(),Be.isNode?"NodeJS":"Browser",ze())]}function je(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 We(){if(!Be.isNode)return"";switch(process.platform){case"win32":return"Windows NT";case"darwin":return"macOS";case"linux":return"Linux";default:return process.platform}}function ze(){if(Be.isNode)return process.versions.node}class qe{constructor(e,t,n,r,o,i){this._httpClient=e,this._accessTokenFactory=t,this._logger=n,this._pollAbort=new Ue,this._logMessageContent=r,this._withCredentials=o,this._headers=i,this._running=!1,this.onreceive=null,this.onclose=null}get pollAborted(){return this._pollAbort.aborted}async connect(e,t){if(Ne.isRequired(e,"url"),Ne.isRequired(t,"transferFormat"),Ne.isIn(t,Ce,"transferFormat"),this._url=e,this._logger.log(Ee.Trace,"(LongPolling transport) Connecting."),t===Ce.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]=Fe(),o={[n]:r,...this._headers},i={abortSignal:this._pollAbort.signal,headers:o,timeout:1e5,withCredentials:this._withCredentials};t===Ce.Binary&&(i.responseType="arraybuffer");const s=await this._getAccessToken();this._updateHeaderToken(i,s);const a=`${e}&_=${Date.now()}`;this._logger.log(Ee.Trace,`(LongPolling transport) polling: ${a}.`);const c=await this._httpClient.get(a,i);200!==c.statusCode?(this._logger.log(Ee.Error,`(LongPolling transport) Unexpected response code: ${c.statusCode}.`),this._closeError=new ye(c.statusText||"",c.statusCode),this._running=!1):this._running=!0,this._receiving=this._poll(this._url,i)}async _getAccessToken(){return this._accessTokenFactory?await this._accessTokenFactory():null}_updateHeaderToken(e,t){e.headers||(e.headers={}),t?e.headers[Pe.Authorization]=`Bearer ${t}`:e.headers[Pe.Authorization]&&delete e.headers[Pe.Authorization]}async _poll(e,t){try{for(;this._running;){const n=await this._getAccessToken();this._updateHeaderToken(t,n);try{const n=`${e}&_=${Date.now()}`;this._logger.log(Ee.Trace,`(LongPolling transport) polling: ${n}.`);const r=await this._httpClient.get(n,t);204===r.statusCode?(this._logger.log(Ee.Information,"(LongPolling transport) Poll terminated by server."),this._running=!1):200!==r.statusCode?(this._logger.log(Ee.Error,`(LongPolling transport) Unexpected response code: ${r.statusCode}.`),this._closeError=new ye(r.statusText||"",r.statusCode),this._running=!1):r.content?(this._logger.log(Ee.Trace,`(LongPolling transport) data received. ${$e(r.content,this._logMessageContent)}.`),this.onreceive&&this.onreceive(r.content)):this._logger.log(Ee.Trace,"(LongPolling transport) Poll timed out, reissuing.")}catch(e){this._running?e instanceof we?this._logger.log(Ee.Trace,"(LongPolling transport) Poll timed out, reissuing."):(this._closeError=e,this._running=!1):this._logger.log(Ee.Trace,`(LongPolling transport) Poll errored after shutdown: ${e.message}`)}}}finally{this._logger.log(Ee.Trace,"(LongPolling transport) Polling complete."),this.pollAborted||this._raiseOnClose()}}async send(e){return this._running?Le(this._logger,"LongPolling",this._httpClient,this._url,this._accessTokenFactory,e,this._logMessageContent,this._withCredentials,this._headers):Promise.reject(new Error("Cannot send until the transport is connected"))}async stop(){this._logger.log(Ee.Trace,"(LongPolling transport) Stopping polling."),this._running=!1,this._pollAbort.abort();try{await this._receiving,this._logger.log(Ee.Trace,`(LongPolling transport) sending DELETE request to ${this._url}.`);const e={},[t,n]=Fe();e[t]=n;const r={headers:{...e,...this._headers},withCredentials:this._withCredentials},o=await this._getAccessToken();this._updateHeaderToken(r,o),await this._httpClient.delete(this._url,r),this._logger.log(Ee.Trace,"(LongPolling transport) DELETE request sent.")}finally{this._logger.log(Ee.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(Ee.Trace,e),this.onclose(this._closeError)}}}class Je{constructor(e,t,n,r,o,i,s){this._httpClient=e,this._accessTokenFactory=t,this._logger=n,this._logMessageContent=r,this._withCredentials=i,this._eventSourceConstructor=o,this._headers=s,this.onreceive=null,this.onclose=null}async connect(e,t){if(Ne.isRequired(e,"url"),Ne.isRequired(t,"transferFormat"),Ne.isIn(t,Ce,"transferFormat"),this._logger.log(Ee.Trace,"(SSE transport) Connecting."),this._url=e,this._accessTokenFactory){const t=await this._accessTokenFactory();t&&(e+=(e.indexOf("?")<0?"?":"&")+`access_token=${encodeURIComponent(t)}`)}return new Promise(((n,r)=>{let o,i=!1;if(t===Ce.Text){if(Be.isBrowser||Be.isWebWorker)o=new this._eventSourceConstructor(e,{withCredentials:this._withCredentials});else{const t=this._httpClient.getCookieString(e),n={};n.Cookie=t;const[r,i]=Fe();n[r]=i,o=new this._eventSourceConstructor(e,{withCredentials:this._withCredentials,headers:{...n,...this._headers}})}try{o.onmessage=e=>{if(this.onreceive)try{this._logger.log(Ee.Trace,`(SSE transport) data received. ${$e(e.data,this._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(Ee.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?Le(this._logger,"SSE",this._httpClient,this._url,this._accessTokenFactory,e,this._logMessageContent,this._withCredentials,this._headers):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 Ke{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){if(Ne.isRequired(e,"url"),Ne.isRequired(t,"transferFormat"),Ne.isIn(t,Ce,"transferFormat"),this._logger.log(Ee.Trace,"(WebSockets transport) Connecting."),this._accessTokenFactory){const t=await this._accessTokenFactory();t&&(e+=(e.indexOf("?")<0?"?":"&")+`access_token=${encodeURIComponent(t)}`)}return new Promise(((n,r)=>{let o;e=e.replace(/^http/,"ws"),this._httpClient.getCookieString(e);let i=!1;o||(o=new this._webSocketConstructor(e)),t===Ce.Binary&&(o.binaryType="arraybuffer"),o.onopen=t=>{this._logger.log(Ee.Information,`WebSocket connected to ${e}.`),this._webSocket=o,i=!0,n()},o.onerror=e=>{let t=null;t="undefined"!=typeof ErrorEvent&&e instanceof ErrorEvent?e.error:"There was an error with the transport",this._logger.log(Ee.Information,`(WebSockets transport) ${t}.`)},o.onmessage=e=>{if(this._logger.log(Ee.Trace,`(WebSockets transport) data received. ${$e(e.data,this._logMessageContent)}.`),this.onreceive)try{this.onreceive(e.data)}catch(e){return void this._close(e)}},o.onclose=e=>{if(i)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(Ee.Trace,`(WebSockets transport) sending data. ${$e(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(Ee.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 Ve{constructor(e,t={}){var n;if(this._stopPromiseResolver=()=>{},this.features={},this._negotiateVersion=1,Ne.isRequired(e,"url"),this._logger=void 0===(n=t.logger)?new Oe(Ee.Information):null===n?Ae.instance:void 0!==n.log?n:new Oe(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,"undefined"==typeof WebSocket||t.WebSocket||(t.WebSocket=WebSocket),"undefined"==typeof EventSource||t.EventSource||(t.EventSource=EventSource),this._httpClient=t.httpClient||new Re(this._logger),this._connectionState="Disconnected",this._connectionStarted=!1,this._options=t,this.onreceive=null,this.onclose=null}async start(e){if(e=e||Ce.Binary,Ne.isIn(e,Ce,"transferFormat"),this._logger.log(Ee.Debug,`Starting connection with transfer format '${Ce[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(Ee.Error,e),await this._stopPromise,Promise.reject(new Error(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(Ee.Error,e),Promise.reject(new Error(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 Xe(this.transport)),this._sendQueue.send(e))}async stop(e){return"Disconnected"===this._connectionState?(this._logger.log(Ee.Debug,`Call to HttpConnection.stop(${e}) ignored because the connection is already in the disconnected state.`),Promise.resolve()):"Disconnecting"===this._connectionState?(this._logger.log(Ee.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(Ee.Error,`HttpConnection.transport.stop() threw error '${e}'.`),this._stopConnection()}this.transport=void 0}else this._logger.log(Ee.Debug,"HttpConnection.transport is undefined in HttpConnection.stop() because start() failed.")}async _startInternal(e){let t=this.baseUrl;this._accessTokenFactory=this._options.accessTokenFactory;try{if(this._options.skipNegotiation){if(this._options.transport!==Se.WebSockets)throw new Error("Negotiation can only be skipped when using the WebSocket transport directly.");this.transport=this._constructTransport(Se.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 Error("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}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 qe&&(this.features.inherentKeepAlive=!0),"Connecting"===this._connectionState&&(this._logger.log(Ee.Debug,"The HttpConnection connected successfully."),this._connectionState="Connected")}catch(e){return this._logger.log(Ee.Error,"Failed to start the connection: "+e),this._connectionState="Disconnected",this.transport=void 0,this._stopPromiseResolver(),Promise.reject(e)}}async _getNegotiationResponse(e){const t={};if(this._accessTokenFactory){const e=await this._accessTokenFactory();e&&(t[Pe.Authorization]=`Bearer ${e}`)}const[n,r]=Fe();t[n]=r;const o=this._resolveNegotiateUrl(e);this._logger.log(Ee.Debug,`Sending negotiation request: ${o}.`);try{const e=await this._httpClient.post(o,{content:"",headers:{...t,...this._options.headers},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 ye&&404===e.statusCode&&(t+=" Either this is not a SignalR endpoint or there is a proxy blocking the connection."),this._logger.log(Ee.Error,t),Promise.reject(new Error(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(Ee.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: ${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(Ee.Error,`Failed to start the transport '${n.transport}': ${e}`),a=void 0,i.push(`${n.transport} failed: ${e}`),"Connecting"!==this._connectionState){const e="Failed to select transport before stop() was called.";return this._logger.log(Ee.Debug,e),Promise.reject(new Error(e))}}}}return i.length>0?Promise.reject(new Error(`Unable to connect to the server with any of the available transports. ${i.join(" ")}`)):Promise.reject(new Error("None of the transports supported by the client are supported by the server."))}_constructTransport(e){switch(e){case Se.WebSockets:if(!this._options.WebSocket)throw new Error("'WebSocket' is not supported in your environment.");return new Ke(this._httpClient,this._accessTokenFactory,this._logger,this._options.logMessageContent||!1,this._options.WebSocket,this._options.headers||{});case Se.ServerSentEvents:if(!this._options.EventSource)throw new Error("'EventSource' is not supported in your environment.");return new Je(this._httpClient,this._accessTokenFactory,this._logger,this._options.logMessageContent||!1,this._options.EventSource,this._options.withCredentials,this._options.headers||{});case Se.LongPolling:return new qe(this._httpClient,this._accessTokenFactory,this._logger,this._options.logMessageContent||!1,this._options.withCredentials,this._options.headers||{});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=Se[e.transport];if(null==r)return this._logger.log(Ee.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(Ee.Debug,`Skipping transport '${Se[r]}' because it was disabled by the client.`),new Error(`'${Se[r]}' is disabled by the client.`);if(!(e.transferFormats.map((e=>Ce[e])).indexOf(n)>=0))return this._logger.log(Ee.Debug,`Skipping transport '${Se[r]}' because it does not support the requested transfer format '${Ce[n]}'.`),new Error(`'${Se[r]}' does not support ${Ce[n]}.`);if(r===Se.WebSockets&&!this._options.WebSocket||r===Se.ServerSentEvents&&!this._options.EventSource)return this._logger.log(Ee.Debug,`Skipping transport '${Se[r]}' because it is not supported in your environment.'`),new Error(`'${Se[r]}' is not supported in your environment.`);this._logger.log(Ee.Debug,`Selecting transport '${Se[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(Ee.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(Ee.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(Ee.Error,`Connection disconnected with error '${e}'.`):this._logger.log(Ee.Information,"Connection disconnected."),this._sendQueue&&(this._sendQueue.stop().catch((e=>{this._logger.log(Ee.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(Ee.Error,`HttpConnection.onclose(${e}) threw error '${t}'.`)}}}else this._logger.log(Ee.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(!Be.isBrowser||!window.document)throw new Error(`Cannot resolve '${e}'.`);const t=window.document.createElement("a");return t.href=e,this._logger.log(Ee.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 Xe{constructor(e){this._transport=e,this._buffer=[],this._executing=!0,this._sendBufferedData=new Ye,this._transportResult=new Ye,this._sendLoopPromise=this._sendLoop()}send(e){return this._bufferData(e),this._transportResult||(this._transportResult=new Ye),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 Ye;const e=this._transportResult;this._transportResult=void 0;const t="string"==typeof this._buffer[0]?this._buffer.join(""):Xe._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 Ye{constructor(){this.promise=new Promise(((e,t)=>[this._resolver,this._rejecter]=[e,t]))}resolve(){this._resolver()}reject(e){this._rejecter(e)}}class Ge{static write(e){return`${e}${Ge.RecordSeparator}`}static parse(e){if(e[e.length-1]!==Ge.RecordSeparator)throw new Error("Message is incomplete.");const t=e.split(Ge.RecordSeparator);return t.pop(),t}}Ge.RecordSeparatorCode=30,Ge.RecordSeparator=String.fromCharCode(Ge.RecordSeparatorCode);class Qe{writeHandshakeRequest(e){return Ge.write(JSON.stringify(e))}parseHandshakeResponse(e){let t,n;if(Me(e)){const r=new Uint8Array(e),o=r.indexOf(Ge.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(Ge.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=Ge.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"}(Ie||(Ie={}));class Ze{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 He(this,e)}}!function(e){e.Disconnected="Disconnected",e.Connecting="Connecting",e.Connected="Connected",e.Disconnecting="Disconnecting",e.Reconnecting="Reconnecting"}(ke||(ke={}));class et{constructor(e,t,n,r){this._nextKeepAlive=0,Ne.isRequired(e,"connection"),Ne.isRequired(t,"logger"),Ne.isRequired(n,"protocol"),this.serverTimeoutInMilliseconds=3e4,this.keepAliveIntervalInMilliseconds=15e3,this._logger=t,this._protocol=n,this.connection=e,this._reconnectPolicy=r,this._handshakeProtocol=new Qe,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=ke.Disconnected,this._connectionStarted=!1,this._cachedPingMessage=this._protocol.writeMessage({type:Ie.Ping})}static create(e,t,n,r){return new et(e,t,n,r)}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!==ke.Disconnected&&this._connectionState!==ke.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!==ke.Disconnected)return Promise.reject(new Error("Cannot start a HubConnection that is not in the 'Disconnected' state."));this._connectionState=ke.Connecting,this._logger.log(Ee.Debug,"Starting HubConnection.");try{await this._startInternal(),this._connectionState=ke.Connected,this._connectionStarted=!0,this._logger.log(Ee.Debug,"HubConnection connected successfully.")}catch(e){return this._connectionState=ke.Disconnected,this._logger.log(Ee.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(Ee.Debug,"Sending handshake request."),await this._sendMessage(this._handshakeProtocol.writeHandshakeRequest(t)),this._logger.log(Ee.Information,`Using HubProtocol '${this._protocol.name}'.`),this._cleanupTimeout(),this._resetTimeoutPeriod(),this._resetKeepAliveInterval(),await e,this._stopDuringStartError)throw this._stopDuringStartError}catch(e){throw this._logger.log(Ee.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){return this._connectionState===ke.Disconnected?(this._logger.log(Ee.Debug,`Call to HubConnection.stop(${e}) ignored because it is already in the disconnected state.`),Promise.resolve()):this._connectionState===ke.Disconnecting?(this._logger.log(Ee.Debug,`Call to HttpConnection.stop(${e}) ignored because the connection is already in the disconnecting state.`),this._stopPromise):(this._connectionState=ke.Disconnecting,this._logger.log(Ee.Debug,"Stopping HubConnection."),this._reconnectDelayHandle?(this._logger.log(Ee.Debug,"Connection stopped during reconnect delay. Done reconnecting."),clearTimeout(this._reconnectDelayHandle),this._reconnectDelayHandle=void 0,this._completeClose(),Promise.resolve()):(this._cleanupTimeout(),this._cleanupPingTimer(),this._stopDuringStartError=e||new Error("The connection was stopped before the hub handshake could complete."),this.connection.stop(e)))}stream(e,...t){const[n,r]=this._replaceStreamingParams(t),o=this._createStreamInvocation(e,t,r);let i;const s=new Ze;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===Ie.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===Ie.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 Ie.Invocation:this._invokeClientMethod(e);break;case Ie.StreamItem:case Ie.Completion:{const t=this._callbacks[e.invocationId];t&&(e.type===Ie.Completion&&delete this._callbacks[e.invocationId],t(e));break}case Ie.Ping:break;case Ie.Close:{this._logger.log(Ee.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(Ee.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(Ee.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(Ee.Error,e);const n=new Error(e);throw this._handshakeRejecter(n),n}return this._logger.log(Ee.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===ke.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."))}_invokeClientMethod(e){const t=this._methods[e.target.toLowerCase()];if(t){try{t.forEach((t=>t.apply(this,e.arguments)))}catch(t){this._logger.log(Ee.Error,`A callback for the method ${e.target.toLowerCase()} threw error '${t}'.`)}if(e.invocationId){const e="Server requested a response, which is not supported in this version of the client.";this._logger.log(Ee.Error,e),this._stopPromise=this._stopInternal(new Error(e))}}else this._logger.log(Ee.Warning,`No client method with the name '${e.target}' found.`)}_connectionClosed(e){this._logger.log(Ee.Debug,`HubConnection.connectionClosed(${e}) called while in state ${this._connectionState}.`),this._stopDuringStartError=this._stopDuringStartError||e||new Error("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===ke.Disconnecting?this._completeClose(e):this._connectionState===ke.Connected&&this._reconnectPolicy?this._reconnect(e):this._connectionState===ke.Connected&&this._completeClose(e)}_completeClose(e){if(this._connectionStarted){this._connectionState=ke.Disconnected,this._connectionStarted=!1;try{this._closedCallbacks.forEach((t=>t.apply(this,[e])))}catch(t){this._logger.log(Ee.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(Ee.Debug,"Connection not reconnecting because the IRetryPolicy returned null on the first reconnect attempt."),void this._completeClose(e);if(this._connectionState=ke.Reconnecting,e?this._logger.log(Ee.Information,`Connection reconnecting because of error '${e}'.`):this._logger.log(Ee.Information,"Connection reconnecting."),0!==this._reconnectingCallbacks.length){try{this._reconnectingCallbacks.forEach((t=>t.apply(this,[e])))}catch(t){this._logger.log(Ee.Error,`An onreconnecting callback called with error '${e}' threw error '${t}'.`)}if(this._connectionState!==ke.Reconnecting)return void this._logger.log(Ee.Debug,"Connection left the reconnecting state in onreconnecting callback. Done reconnecting.")}for(;null!==o;){if(this._logger.log(Ee.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!==ke.Reconnecting)return void this._logger.log(Ee.Debug,"Connection left the reconnecting state during reconnect delay. Done reconnecting.");try{if(await this._startInternal(),this._connectionState=ke.Connected,this._logger.log(Ee.Information,"HubConnection reconnected successfully."),0!==this._reconnectedCallbacks.length)try{this._reconnectedCallbacks.forEach((e=>e.apply(this,[this.connection.connectionId])))}catch(e){this._logger.log(Ee.Error,`An onreconnected callback called with connectionId '${this.connection.connectionId}; threw error '${e}'.`)}return}catch(e){if(this._logger.log(Ee.Information,`Reconnect attempt failed because of error '${e}'.`),this._connectionState!==ke.Reconnecting)return this._logger.log(Ee.Debug,`Connection moved to the '${this._connectionState}' from the reconnecting state during reconnect attempt. Done reconnecting.`),void(this._connectionState===ke.Disconnecting&&this._completeClose());r=e instanceof Error?e:new Error(e.toString()),o=this._getNextRetryDelay(n++,Date.now()-t,r)}}this._logger.log(Ee.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(Ee.Error,`IRetryPolicy.nextRetryDelayInMilliseconds(${e}, ${t}) threw error '${n}'.`),null}}_cancelCallbacksWithError(e){const t=this._callbacks;this._callbacks={},Object.keys(t).forEach((n=>{(0,t[n])(null,e)}))}_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:Ie.Invocation}:{arguments:t,target:e,type:Ie.Invocation};{const n=this._invocationId;return this._invocationId++,0!==r.length?{arguments:t,invocationId:n.toString(),streamIds:r,target:e,type:Ie.Invocation}:{arguments:t,invocationId:n.toString(),target:e,type:Ie.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 ut=ot?new TextDecoder:null,dt=ot?"undefined"!=typeof process&&"force"!==process.env.TEXT_DECODER?200:0:it,pt=function(e,t){this.type=e,this.data=t};function ft(e,t,n){var r=Math.floor(n/4294967296),o=n;e.setUint32(t,r),e.setUint32(t+4,o)}function gt(e,t){return 4294967296*e.getInt32(t)+e.getUint32(t+4)}var mt={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),ft(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:gt(t,4),nsec:t.getUint32(0)};default:throw new Error("Unrecognized data size for timestamp: "+e.length)}}(e);return new Date(1e3*t.sec+t.nsec/1e6)}},yt=function(){function e(){this.builtInEncoders=[],this.builtInDecoders=[],this.encoders=[],this.decoders=[],this.register(mt)}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 "+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: "+e+" bytes in UTF-8");this.writeU8(219),this.writeU32(e)}},e.prototype.encodeString=function(e){if(e.length>ct){var t=st(e);this.ensureBufferSizeToWrite(5+t),this.writeStringHeader(t),lt(e,this.bytes,this.pos),this.pos+=t}else t=st(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: "+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: "+t);this.writeU8(198),this.writeU32(t)}var n=wt(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: "+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=ht(e,t,n),i=Uint8Array.prototype.slice.call(e,t,t+n);return this.store(i,o),o},e}(),St=(_t=function(e,t){return(_t=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])})(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}_t(e,t),e.prototype=null===t?Object.create(t):(n.prototype=t.prototype,new n)}),Ct=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]1||a(e,t)}))})}function a(e,t){try{(n=o[e](t)).value instanceof kt?Promise.resolve(n.value.v).then(c,l):h(i[0][2],n)}catch(e){h(i[0][3],e)}var n}function c(e){a("next",e)}function l(e){a("throw",e)}function h(e,t){e(t),i.shift(),i.length&&a(i[0][0],i[0][1])}},Dt=new DataView(new ArrayBuffer(0)),xt=new Uint8Array(Dt.buffer),Rt=function(){try{Dt.getInt8(0)}catch(e){return e.constructor}throw new Error("never reached")}(),Pt=new Rt("Insufficient data"),Ut=4294967295,At=new Et,Nt=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 St(t,e),t}(Error),Bt=function(){function e(e,t,n,r,o,i,s,a){void 0===e&&(e=yt.defaultCodec),void 0===t&&(t=void 0),void 0===n&&(n=Ut),void 0===r&&(r=Ut),void 0===o&&(o=Ut),void 0===i&&(i=Ut),void 0===s&&(s=Ut),void 0===a&&(a=At),this.extensionCodec=e,this.context=t,this.maxStrLength=n,this.maxBinLength=r,this.maxArrayLength=o,this.maxMapLength=i,this.maxExtLength=s,this.keyDecoder=a,this.totalPos=0,this.pos=0,this.view=Dt,this.bytes=xt,this.headByte=-1,this.stack=[]}return e.prototype.reinitializeState=function(){this.totalPos=0,this.headByte=-1,this.stack.length=0},e.prototype.setBuffer=function(e){this.bytes=wt(e),this.view=function(e){if(e instanceof ArrayBuffer)return new DataView(e);var t=wt(e);return new DataView(t.buffer,t.byteOffset,t.byteLength)}(this.bytes),this.pos=0},e.prototype.appendBuffer=function(e){if(-1!==this.headByte||this.hasRemaining()){var t=this.bytes.subarray(this.pos),n=wt(e),r=new Uint8Array(t.length+n.length);r.set(t),r.set(n,t.length),this.setBuffer(r)}else this.setBuffer(e)},e.prototype.hasRemaining=function(e){return void 0===e&&(e=1),this.view.byteLength-this.pos>=e},e.prototype.createExtraByteError=function(e){var t=this.view,n=this.pos;return new RangeError("Extra "+(t.byteLength-n)+" of "+t.byteLength+" byte(s) found at buffer["+e+"]")},e.prototype.decode=function(e){this.reinitializeState(),this.setBuffer(e);var t=this.doDecodeSync();if(this.hasRemaining())throw this.createExtraByteError(this.pos);return t},e.prototype.decodeMulti=function(e){return Ct(this,(function(t){switch(t.label){case 0:this.reinitializeState(),this.setBuffer(e),t.label=1;case 1:return this.hasRemaining()?[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,u,d;return Ct(this,(function(p){switch(p.label){case 0:i=!1,p.label=1;case 1:p.trys.push([1,6,7,12]),t=It(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 Rt))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())throw this.createExtraByteError(this.totalPos);return[2,s]}throw h=(l=this).headByte,u=l.pos,d=l.totalPos,new RangeError("Insufficient data in parsing "+bt(h)+" at "+d+" ("+u+" 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 Tt(this,arguments,(function(){var n,r,o,i,s,a,c,l,h;return Ct(this,(function(u){switch(u.label){case 0:n=t,r=-1,u.label=1;case 1:u.trys.push([1,13,14,19]),o=It(e),u.label=2;case 2:return[4,kt(o.next())];case 3:if((i=u.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()),u.label=4;case 4:u.trys.push([4,9,,10]),u.label=5;case 5:return[4,kt(this.doDecodeSync())];case 6:return[4,u.sent()];case 7:return u.sent(),0==--r?[3,8]:[3,5];case 8:return[3,10];case 9:if(!((a=u.sent())instanceof Rt))throw a;return[3,10];case 10:this.totalPos+=this.pos,u.label=11;case 11:return[3,2];case 12:return[3,19];case 13:return c=u.sent(),l={error:c},[3,19];case 14:return u.trys.push([14,,17,18]),i&&!i.done&&(h=o.return)?[4,kt(h.call(o))]:[3,16];case 15:u.sent(),u.label=16;case 16:return[3,18];case 17:if(l)throw l.error;return[7];case 18:return[7];case 19:return[2]}}))}))},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 Nt("Unrecognized type byte: "+bt(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 Nt("The type of key must be string or number but "+typeof t);if("__proto__"===t)throw new Nt("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 Nt("Unrecognized array type byte: "+bt(e))}},e.prototype.pushMapState=function(e){if(e>this.maxMapLength)throw new Nt("Max length exceeded: map length ("+e+") > maxMapLengthLength ("+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 Nt("Max length exceeded: array length ("+e+") > maxArrayLength ("+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 Nt("Max length exceeded: UTF-8 byte length ("+e+") > maxStrLength ("+this.maxStrLength+")");if(this.bytes.byteLengthdt?function(e,t,n){var r=e.subarray(t,t+n);return ut.decode(r)}(this.bytes,o,e):ht(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 Nt("Max length exceeded: bin length ("+e+") > maxBinLength ("+this.maxBinLength+")");if(!this.hasRemaining(e+t))throw Pt;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 Nt("Max length exceeded: ext length ("+e+") > maxExtLength ("+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=gt(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 $t{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 Mt=new Uint8Array([145,Ie.Ping]);class Lt{constructor(e){this.name="messagepack",this.version=1,this.transferFormat=Ce.Binary,this._errorResult=1,this._voidResult=2,this._nonVoidResult=3,e=e||{},this._encoder=new vt(e.extensionCodec,e.context,e.maxDepth,e.initialBufferSize,e.sortKeys,e.forceFloat32,e.ignoreUndefined,e.forceIntegerToFloat),this._decoder=new Bt(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=Ae.instance);const r=$t.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 Ie.Invocation:return this._writeInvocation(e);case Ie.StreamInvocation:return this._writeStreamInvocation(e);case Ie.StreamItem:return this._writeStreamItem(e);case Ie.Completion:return this._writeCompletion(e);case Ie.Ping:return $t.write(Mt);case Ie.CancelInvocation:return this._writeCancelInvocation(e);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 Ie.Invocation:return this._createInvocationMessage(this._readHeaders(n),n);case Ie.StreamItem:return this._createStreamItemMessage(this._readHeaders(n),n);case Ie.Completion:return this._createCompletionMessage(this._readHeaders(n),n);case Ie.Ping:return this._createPingMessage(n);case Ie.Close:return this._createCloseMessage(n);default:return t.log(Ee.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:Ie.Close}}_createPingMessage(e){if(e.length<1)throw new Error("Invalid payload for Ping message.");return{type:Ie.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:Ie.Invocation}:{arguments:t[4],headers:e,streamIds:[],target:t[3],type:Ie.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:Ie.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:Ie.Completion}}_writeInvocation(e){let t;return t=e.streamIds?this._encoder.encode([Ie.Invocation,e.headers||{},e.invocationId||null,e.target,e.arguments,e.streamIds]):this._encoder.encode([Ie.Invocation,e.headers||{},e.invocationId||null,e.target,e.arguments]),$t.write(t.slice())}_writeStreamInvocation(e){let t;return t=e.streamIds?this._encoder.encode([Ie.StreamInvocation,e.headers||{},e.invocationId,e.target,e.arguments,e.streamIds]):this._encoder.encode([Ie.StreamInvocation,e.headers||{},e.invocationId,e.target,e.arguments]),$t.write(t.slice())}_writeStreamItem(e){const t=this._encoder.encode([Ie.StreamItem,e.headers||{},e.invocationId,e.item]);return $t.write(t.slice())}_writeCompletion(e){const t=e.error?this._errorResult:e.result?this._nonVoidResult:this._voidResult;let n;switch(t){case this._errorResult:n=this._encoder.encode([Ie.Completion,e.headers||{},e.invocationId,t,e.error]);break;case this._voidResult:n=this._encoder.encode([Ie.Completion,e.headers||{},e.invocationId,t]);break;case this._nonVoidResult:n=this._encoder.encode([Ie.Completion,e.headers||{},e.invocationId,t,e.result])}return $t.write(n.slice())}_writeCancelInvocation(e){const t=this._encoder.encode([Ie.CancelInvocation,e.headers||{},e.invocationId]);return $t.write(t.slice())}_readHeaders(e){const t=e[1];if("object"!=typeof t)throw new Error("Invalid headers.");return t}}let Ht=!1;const Ot="function"==typeof TextDecoder?new TextDecoder("utf-8"):null,Ft=Ot?Ot.decode.bind(Ot):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("")},jt=Math.pow(2,32),Wt=Math.pow(2,21)-1;function zt(e,t){return e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24}function qt(e,t){return e[t]+(e[t+1]<<8)+(e[t+2]<<16)+(e[t+3]<<24>>>0)}function Jt(e,t){const n=qt(e,t+4);if(n>Wt)throw new Error(`Cannot read uint64 with high order part ${n}, because the result would exceed Number.MAX_SAFE_INTEGER.`);return n*jt+qt(e,t)}class Kt{constructor(e){this.batchData=e;const t=new Gt(e);this.arrayRangeReader=new Qt(e),this.arrayBuilderSegmentReader=new Zt(e),this.diffReader=new Vt(e),this.editReader=new Xt(e,t),this.frameReader=new Yt(e,t)}updatedComponents(){return zt(this.batchData,this.batchData.length-20)}referenceFrames(){return zt(this.batchData,this.batchData.length-16)}disposedComponentIds(){return zt(this.batchData,this.batchData.length-12)}disposedEventHandlerIds(){return zt(this.batchData,this.batchData.length-8)}updatedComponentsEntry(e,t){const n=e+4*t;return zt(this.batchData,n)}referenceFramesEntry(e,t){return e+20*t}disposedComponentIdsEntry(e,t){const n=e+4*t;return zt(this.batchData,n)}disposedEventHandlerIdsEntry(e,t){const n=e+8*t;return Jt(this.batchData,n)}}class Vt{constructor(e){this.batchDataUint8=e}componentId(e){return zt(this.batchDataUint8,e)}edits(e){return e+4}editsEntry(e,t){return e+16*t}}class Xt{constructor(e,t){this.batchDataUint8=e,this.stringReader=t}editType(e){return zt(this.batchDataUint8,e)}siblingIndex(e){return zt(this.batchDataUint8,e+4)}newTreeIndex(e){return zt(this.batchDataUint8,e+8)}moveToSiblingIndex(e){return zt(this.batchDataUint8,e+8)}removedAttributeName(e){const t=zt(this.batchDataUint8,e+12);return this.stringReader.readString(t)}}class Yt{constructor(e,t){this.batchDataUint8=e,this.stringReader=t}frameType(e){return zt(this.batchDataUint8,e)}subtreeLength(e){return zt(this.batchDataUint8,e+4)}elementReferenceCaptureId(e){const t=zt(this.batchDataUint8,e+4);return this.stringReader.readString(t)}componentId(e){return zt(this.batchDataUint8,e+8)}elementName(e){const t=zt(this.batchDataUint8,e+8);return this.stringReader.readString(t)}textContent(e){const t=zt(this.batchDataUint8,e+4);return this.stringReader.readString(t)}markupContent(e){const t=zt(this.batchDataUint8,e+4);return this.stringReader.readString(t)}attributeName(e){const t=zt(this.batchDataUint8,e+4);return this.stringReader.readString(t)}attributeValue(e){const t=zt(this.batchDataUint8,e+8);return this.stringReader.readString(t)}attributeEventHandlerId(e){return Jt(this.batchDataUint8,e+12)}}class Gt{constructor(e){this.batchDataUint8=e,this.stringTableStartIndex=zt(e,e.length-4)}readString(e){if(-1===e)return null;{const n=zt(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(en.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(en.Debug,`Waiting for batch ${this.nextBatchId}. Batch ${e} not processed.`);try{this.nextBatchId++,this.logger.log(en.Debug,`Applying batch ${e}.`),function(e,t){const n=Q[e];if(!n)throw new Error(`There is no browser renderer with ID ${e}.`);const r=t.arrayRangeReader,o=t.updatedComponents(),i=r.values(o),s=r.count(o),a=t.referenceFrames(),c=r.values(a),l=t.diffReader;for(let e=0;e=this.minLevel){const n=`[${(new Date).toISOString()}] ${en[e]}: ${t}`;switch(e){case en.Critical:case en.Error:console.error(n);break;case en.Warning:console.warn(n);break;case en.Information:console.info(n);break;default:console.log(n)}}}}class on{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!==ke.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!==ke.Connected)return!1;const t=await e.invoke("StartCircuit",re.getBaseURI(),re.getLocationHref(),JSON.stringify(this.components.map((e=>e.toRecord()))),this.applicationState||"");return!!t&&(this.initialize(t),!0)}resolveElement(e){const t=Number.parseInt(e);if(Number.isNaN(t))throw new Error(`Invalid sequence number '${e}'.`);return function(e,t){if(!e.parentNode)throw new Error(`Comment not connected to the DOM ${e.textContent}`);const n=e.parentNode,r=k(n,!0),o=A(r);return Array.from(n.childNodes).forEach((e=>o.push(e))),e[C]=r,t&&(e[I]=t,k(t)),k(e)}(this.components[t].start,this.components[t].end)}}const sn={configureSignalR:e=>{},logLevel:en.Warning,reconnectionOptions:{maxRetries:8,retryIntervalMilliseconds:2e4,dialogId:"components-reconnect-modal"}};class an{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.modal.innerHTML='

Alternatively, reload

',this.message=this.modal.querySelector("h5"),this.button=this.modal.querySelector("button"),this.reloadParagraph=this.modal.querySelector("p"),this.loader=this.getLoader(),this.message.after(this.loader),this.button.addEventListener("click",(async()=>{this.show();try{await(null==fe?void 0:fe.reconnect)()||this.rejected()}catch(e){this.logger.log(en.Error,e),this.failed()}})),this.reloadParagraph.querySelector("a").addEventListener("click",(()=>location.reload()))}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",this.message.innerHTML="Reconnection failed. Try reloading the page if you're unable to reconnect.",this.message.querySelector("a").addEventListener("click",(()=>location.reload()))}rejected(){this.button.style.display="none",this.reloadParagraph.style.display="none",this.loader.style.display="none",this.message.innerHTML="Could not reconnect to the server. Reload the page to restore functionality.",this.message.querySelector("a").addEventListener("click",(()=>location.reload()))}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 cn{constructor(e,t,n){this.dialog=e,this.maxRetries=t,this.document=n,this.document=n;const r=this.document.getElementById(cn.MaxRetriesId);r&&(r.innerText=this.maxRetries.toString())}show(){this.removeClasses(),this.dialog.classList.add(cn.ShowClassName)}update(e){const t=this.document.getElementById(cn.CurrentAttemptId);t&&(t.innerText=e.toString())}hide(){this.removeClasses(),this.dialog.classList.add(cn.HideClassName)}failed(){this.removeClasses(),this.dialog.classList.add(cn.FailedClassName)}rejected(){this.removeClasses(),this.dialog.classList.add(cn.RejectedClassName)}removeClasses(){this.dialog.classList.remove(cn.ShowClassName,cn.HideClassName,cn.FailedClassName,cn.RejectedClassName)}}cn.ShowClassName="components-reconnect-show",cn.HideClassName="components-reconnect-hide",cn.FailedClassName="components-reconnect-failed",cn.RejectedClassName="components-reconnect-rejected",cn.MaxRetriesId="components-reconnect-max-retries",cn.CurrentAttemptId="components-reconnect-current-attempt";class ln{constructor(e,t,n){this._currentReconnectionProcess=null,this._logger=e,this._reconnectionDisplay=t,this._reconnectCallback=n||(()=>fe.reconnect())}onConnectionDown(e,t){if(!this._reconnectionDisplay){const t=document.getElementById(e.dialogId);this._reconnectionDisplay=t?new cn(t,e.maxRetries,document):new an(e.dialogId,e.maxRetries,document,this._logger)}this._currentReconnectionProcess||(this._currentReconnectionProcess=new hn(e,this._logger,this._reconnectCallback,this._reconnectionDisplay))}onConnectionUp(){this._currentReconnectionProcess&&(this._currentReconnectionProcess.dispose(),this._currentReconnectionProcess=null)}}class hn{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;thn.MaximumFirstRetryInterval?hn.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(en.Error,e)}}this.reconnectDisplay.failed()}delay(e){return new Promise((t=>setTimeout(t,e)))}}hn.MaximumFirstRetryInterval=3e3;const un=/^\s*Blazor-Component-State:(?[a-zA-Z0-9\+\/=]+)$/;function dn(e){var t;if(e.nodeType===Node.COMMENT_NODE){const n=e.textContent||"",r=un.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 gn(e,t){const n=e.currentElement;if(n&&n.nodeType===Node.COMMENT_NODE&&n.textContent){const r=fn.exec(n.textContent),o=r&&r.groups&&r.groups.descriptor;if(!o)return;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;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.");if(c){const e=mn(c,n);if(!e)throw new Error(`Could not find an end component comment for '${t}'`);return{type:r,assembly:o,typeName:i,parameterDefinitions:s&&atob(s),parameterValues:a&&atob(a),start:t,prerenderId:c,end:e}}return{type:r,assembly:o,typeName:i,parameterDefinitions:s&&atob(s),parameterValues:a&&atob(a),start:t}}}(r,n,e);case"server":return function(e,t,n){const{type:r,descriptor:o,sequence:i,prerenderId:s}=e;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)}'`);if(s){const e=mn(s,n);if(!e)throw new Error(`Could not find an end component comment for '${t}'`);return{type:r,sequence:i,descriptor:o,start:t,prerenderId:s,end:e}}return{type:r,sequence:i,descriptor:o,start:t}}}(r,n,e)}}catch(e){throw new Error(`Found malformed component comment at ${n.textContent}`)}}}function mn(e,t){for(;t.next()&&t.currentElement;){const n=t.currentElement;if(n.nodeType!==Node.COMMENT_NODE)continue;if(!n.textContent)continue;const r=fn.exec(n.textContent),o=r&&r[1];if(o)return yn(o,e),n}}function yn(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 wn{constructor(e){this.childNodes=e,this.currentIndex=-1,this.length=e.length}next(){return this.currentIndex++,this.currentIndexe.sequence-t.sequence))}(e)}(document),o=dn(document),i=new on(r,o||""),s=await Tn(t,n,i);if(!await i.startCircuit(s))return void n.log(en.Error,"Failed to start the circuit.");let a=!1;const c=()=>{if(!a){const e=new FormData,t=i.circuitId;e.append("circuitId",t),a=navigator.sendBeacon("_blazor/disconnect",e)}};fe.disconnect=c,window.addEventListener("unload",c,{capture:!1,once:!0}),fe.reconnect=async e=>{if(Cn)return!1;const r=e||await Tn(t,n,i);return await i.reconnect(r)?(t.reconnectionHandler.onConnectionUp(),!0):(n.log(en.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)},n.log(en.Information,"Blazor server-side application started.")}async function Tn(t,n,r){const i=new Lt;i.name="blazorpack";const s=(new rt).withUrl("_blazor").withHubProtocol(i);t.configureSignalR(s);const a=s.build();o=(e,t)=>{a.send("DispatchBrowserEvent",JSON.stringify(e),JSON.stringify(t))},fe._internal.navigationManager.listenForNavigationEvents(((e,t)=>a.send("OnLocationChanged",e,t))),a.on("JS.AttachComponent",((e,t)=>function(e,t,n){let r=Q[0];r||(r=Q[0]=new V(0)),r.attachRootComponentToLogicalElement(n,t)}(0,r.resolveElement(t),e))),a.on("JS.BeginInvokeJS",e.jsCallDispatcher.beginInvokeJSFromDotNet),a.on("JS.EndInvokeDotNet",e.jsCallDispatcher.endInvokeDotNetFromJS),a.on("JS.ReceiveByteArray",e.jsCallDispatcher.receiveByteArray);const c=tn.getOrCreate(n);a.on("JS.RenderBatch",((e,t)=>{n.log(en.Debug,`Received render batch with id ${e} and ${t.byteLength} bytes.`),c.processBatch(e,t,a)})),a.onclose((e=>!Cn&&t.reconnectionHandler.onConnectionDown(t.reconnectionOptions,e))),a.on("JS.Error",(e=>{Cn=!0,Dn(a,e,n),async function(){let e=document.querySelector("#blazor-error-ui");e&&(e.style.display="block"),Ht||(Ht=!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()}})))}()})),fe._internal.forceCloseConnection=()=>a.stop();const l=new Map;fe._internal.sendJSDataStream=async(e,t)=>{const n=setTimeout((async()=>{let n=5,r=(new Date).valueOf();try{const o=31744;let i=0;for(;i1)await a.send("SupplyJSDataChunk",t,c,null);else{if(void 0===l.get(t))break;await a.invoke("SupplyJSDataChunk",t,c,null);const e=(new Date).valueOf(),o=e-r;r=e,n=Math.max(1,Math.round(500/o))}i+=s}}catch(e){await a.send("SupplyJSDataChunk",t,null,e.toString())}finally{l.delete(t)}}),0);l.set(t,n)},fe._internal.cancelJSDataStream=async e=>{const t=l.get(e);void 0!==t&&(clearTimeout(t),l.delete(e))};try{await a.start()}catch(e){Dn(a,e,n)}return e.attachDispatcher({beginInvokeDotNetFromJS:(e,t,n,r,o)=>{a.send("BeginInvokeDotNetFromJS",e?e.toString():null,t,n,r||0,o)},endInvokeJSFromDotNet:(e,t,n)=>{a.send("EndInvokeJSFromDotNet",e,t,n)},sendByteArray:(e,t)=>{a.send("ReceiveByteArray",e,t)}}),a}function Dn(e,t,n){n.log(en.Error,t),e&&e.stop()}fe.start=kn,document&&document.currentScript&&"false"!==document.currentScript.getAttribute("autostart")&&kn()})(); \ No newline at end of file diff --git a/src/Components/Web.JS/src/Boot.Server.ts b/src/Components/Web.JS/src/Boot.Server.ts index bc76ab80d029..53cd89e043a1 100644 --- a/src/Components/Web.JS/src/Boot.Server.ts +++ b/src/Components/Web.JS/src/Boot.Server.ts @@ -122,11 +122,12 @@ async function initializeConnection(options: CircuitStartOptions, logger: Logger Blazor._internal.forceCloseConnection = () => connection.stop(); + const activeJSDataStreams = new Map(); Blazor._internal.sendJSDataStream = async (data: ArrayBufferView, streamId: string) => { // Run the rest in the background, without delaying the completion of the call to sendJSDataStream // otherwise we'll deadlock (.NET can't begin reading until this completes, but it won't complete // because nobody's reading the pipe) - setTimeout(async () => { + const handle = setTimeout(async () => { const maxMillisecondsBetweenAcks = 500; let numChunksUntilNextAck = 5; let lastAckTime = new Date().valueOf(); @@ -135,19 +136,22 @@ async function initializeConnection(options: CircuitStartOptions, logger: Logger let position = 0; while (position < data.byteLength) { // TODO: Doesn't the JS side receive any backpressure indication? We're just pushing it all here. - // TODO: What about cancellation? If the .NET-side JSDataStream gets disposed, then ideally we'd - // receive a message telling us to stop processing the stream with that streamId, and would - // stop sending the data. const nextChunkSize = Math.min(chunkSize, data.byteLength - position); console.log(`Sending a chunk of length ${nextChunkSize}`); const nextChunkData = new Uint8Array(data.buffer, data.byteOffset + position, nextChunkSize); - numChunksUntilNextAck--; if (numChunksUntilNextAck > 1) { // Most of the time just send and buffer within the network layer await connection.send('SupplyJSDataChunk', streamId, nextChunkData, null); } else { + // Check to see if the stream has been cancelled from .NET + // We do this check everytime we wait for an ACK to avoid this additional + // overhead on every single chunk. + if (activeJSDataStreams.get(streamId) === undefined) { + break; + } + // But regularly, wait for an ACK, so other events can be interleaved // The use of "invoke" (not "send") here is what prevents the JS side from queuing up chunks // faster than the .NET side can receive them. It means that if there are other user interactions @@ -165,7 +169,7 @@ async function initializeConnection(options: CircuitStartOptions, logger: Logger position += nextChunkSize; - // Somehow we need to delay sending the next item until the actual network transfer for the preceding + // TODO: Somehow we need to delay sending the next item until the actual network transfer for the preceding // one completed. Otherwise we'll just queue them all up instantly, which is too problematic because // it prevents all other user interactions while the transfer is in progress. For example, this makes // it impossible to have a "cancel" button. We need to give priority to all other events, which would @@ -178,10 +182,28 @@ async function initializeConnection(options: CircuitStartOptions, logger: Logger } } catch (error) { await connection.send('SupplyJSDataChunk', streamId, null, error.toString()); + } finally { + activeJSDataStreams.delete(streamId); } }, 0); + + // Note: need to convert to generic/number to avoid automatic type cast to NodeJS.Timeout + activeJSDataStreams.set(streamId, handle as any as number); }; + Blazor._internal.cancelJSDataStream = async (streamId: string) => { + const handle = activeJSDataStreams.get(streamId); + + if (handle === undefined) { + return; + } + + // Note clearing the timeout only cancels the function from running IF it hasn't started yet. + clearTimeout(handle); + + activeJSDataStreams.delete(streamId); + } + try { await connection.start(); } catch (ex) { diff --git a/src/Components/Web.JS/src/GlobalExports.ts b/src/Components/Web.JS/src/GlobalExports.ts index 0b163cbdd792..fbf4bd44e869 100644 --- a/src/Components/Web.JS/src/GlobalExports.ts +++ b/src/Components/Web.JS/src/GlobalExports.ts @@ -50,6 +50,7 @@ interface IBlazor { getSatelliteAssemblies?: any, applyHotReload?: (id: string, metadataDelta: string, ilDelta: string) => void, sendJSDataStream?: (data: any, streamId: string) => void, + cancelJSDataStream?: (streamId: string) => void, } } From 2509ce5aa87da9be048b370260099c52b3cc2b1a Mon Sep 17 00:00:00 2001 From: Tanay Parikh Date: Fri, 11 Jun 2021 10:46:47 -0700 Subject: [PATCH 03/37] Cancel without clearTimeout --- .../Web.JS/dist/Release/blazor.server.js | 2 +- src/Components/Web.JS/src/Boot.Server.ts | 26 +++++++------------ 2 files changed, 11 insertions(+), 17 deletions(-) diff --git a/src/Components/Web.JS/dist/Release/blazor.server.js b/src/Components/Web.JS/dist/Release/blazor.server.js index 086da8e45893..2ed735764cfe 100644 --- a/src/Components/Web.JS/dist/Release/blazor.server.js +++ b/src/Components/Web.JS/dist/Release/blazor.server.js @@ -1 +1 @@ -(()=>{"use strict";var e,t,n;!function(e){window.DotNet=e;const t=[],n=new Map;class r{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 o="__jsObjectId",i={},s={0:new r(window)};s[0]._cachedFunctions.set("import",(e=>("string"==typeof e&&e.startsWith("./")&&(e=document.baseURI+e.substr(2)),import(e))));let a,c=1,l=1,h=null;function u(e){t.push(e)}function d(e){if(e&&"object"==typeof e){s[l]=new r(e);let t={[o]:l};return e.buffer instanceof ArrayBuffer&&void 0!==e.byteLength&&(t.__jsDataReferenceLength=e.byteLength),l++,t}throw new Error(`Cannot create a JSObjectReference from the value '${e}'.`)}function p(e){return e?JSON.parse(e,((e,n)=>t.reduce(((t,n)=>n(e,t)),n))):null}function f(e,t,n,r){const o=m();if(o.invokeDotNetFromJS){const i=I(r),s=o.invokeDotNetFromJS(e,t,n,i);return s?p(s):null}throw new Error("The current dispatcher does not support synchronous calls from JS to .NET. Use invokeMethodAsync instead.")}function g(e,t,n,r){if(e&&n)throw new Error(`For instance method calls, assemblyName should be null. Received '${e}'.`);const o=c++,s=new Promise(((e,t)=>{i[o]={resolve:e,reject:t}}));try{const i=I(r);m().beginInvokeDotNetFromJS(o,e,t,n,i)}catch(e){y(o,!1,e)}return s}function m(){if(null!==h)return h;throw new Error("No .NET call dispatcher has been set.")}function y(e,t,n){if(!i.hasOwnProperty(e))throw new Error(`There is no pending async call with ID ${e}.`);const r=i[e];delete i[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 v(e,t){let n=s[t];if(n)return n.findFunction(e);throw new Error(`JS object instance with ID ${t} does not exist (has it been disposed?).`)}function b(e){delete s[e]}e.attachDispatcher=function(e){h=e},e.attachReviver=u,e.invokeMethod=function(e,t,...n){return f(e,t,null,n)},e.invokeMethodAsync=function(e,t,...n){return g(e,t,null,n)},e.createJSObjectReference=d,e.disposeJSObjectReference=function(e){const t=e&&e.__jsObjectId;"number"==typeof t&&b(t)},function(e){e[e.Default=0]="Default",e[e.JSObjectReference=1]="JSObjectReference"}(a=e.JSCallResultType||(e.JSCallResultType={})),e.jsCallDispatcher={findJSFunction:v,disposeJSObjectReferenceById:b,invokeJSFromDotNet:(e,t,n,r)=>{const o=S(v(e,r).apply(null,p(t)),n);return null==o?null:I(o)},beginInvokeJSFromDotNet:(e,t,n,r,o)=>{const i=new Promise((e=>{e(v(t,o).apply(null,p(n)))}));e&&i.then((t=>m().endInvokeJSFromDotNet(e,!0,I([e,!0,S(t,r)]))),(t=>m().endInvokeJSFromDotNet(e,!1,JSON.stringify([e,!1,w(t)]))))},endInvokeDotNetFromJS:(e,t,n)=>{const r=t?p(n):new Error(n);y(parseInt(e),t,r)},receiveByteArray:(e,t)=>{n.set(e,t)}};class _{constructor(e){this._id=e}invokeMethod(e,...t){return f(null,e,this._id,t)}invokeMethodAsync(e,...t){return g(null,e,this._id,t)}dispose(){g(null,"__Dispose",this._id,null).catch((e=>console.error(e)))}serializeAsArg(){return{__dotNetObject:this._id}}}const E="__byte[]";function S(e,t){switch(t){case a.Default:return e;case a.JSObjectReference:return d(e);default:throw new Error(`Invalid JS call result type '${t}'.`)}}u((function(e,t){if(t&&"object"==typeof t){if(t.hasOwnProperty("__dotNetObject"))return new _(t.__dotNetObject);if(t.hasOwnProperty(o)){const e=t.__jsObjectId,n=s[e];if(n)return n.getWrappedObject();throw new Error(`JS object instance with Id '${e}' does not exist. It may have been disposed.`)}if(t.hasOwnProperty(E)){const e=t["__byte[]"],r=n.get(e);if(void 0===r)throw new Error(`Byte array index '${e}' does not exist.`);return r}}return t}));let C=0;function I(e){return C=0,JSON.stringify(e,k)}function k(e,t){if(t instanceof _)return t.serializeAsArg();if(t instanceof Uint8Array){h.sendByteArray(C,t);const e={[E]:C};return C++,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"}(n||(n={}));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}}let o;function i(e,t){if(!o)throw new Error("eventDispatcher not initialized. Call 'setEventDispatcher' to configure it.");o(e,t)}const s=new Map,a=new Map,c={createEventArgs:()=>({})},l=[];function h(e){return s.get(e)}function u(e){const t=s.get(e);return(null==t?void 0:t.browserEventName)||e}function d(e,t){e.forEach((e=>s.set(e,t)))}function p(e){const t=[];for(let n=0;n{return{...f(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}}),d(["focus","blur","focusin","focusout"],c),d(["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};var t}}),d(["contextmenu","click","mouseover","mouseout","mousemove","mousedown","mouseup","dblclick"],{createEventArgs:e=>f(e)}),d(["error"],{createEventArgs:e=>{return{message:(t=e).message,filename:t.filename,lineno:t.lineno,colno:t.colno};var t}}),d(["loadstart","timeout","abort","load","loadend","progress"],{createEventArgs:e=>{return{lengthComputable:(t=e).lengthComputable,loaded:t.loaded,total:t.total};var t}}),d(["touchcancel","touchend","touchmove","touchenter","touchleave","touchstart"],{createEventArgs:e=>{return{detail:(t=e).detail,touches:p(t.touches),targetTouches:p(t.targetTouches),changedTouches:p(t.changedTouches),ctrlKey:t.ctrlKey,shiftKey:t.shiftKey,altKey:t.altKey,metaKey:t.metaKey,type:t.type};var t}}),d(["gotpointercapture","lostpointercapture","pointercancel","pointerdown","pointerenter","pointerleave","pointermove","pointerout","pointerover","pointerup"],{createEventArgs:e=>{return{...f(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}}),d(["wheel","mousewheel"],{createEventArgs:e=>{return{...f(t=e),deltaX:t.deltaX,deltaY:t.deltaY,deltaZ:t.deltaZ,deltaMode:t.deltaMode};var t}}),d(["toggle"],c);const g=["date","datetime-local","month","time","week"],m=E(["abort","blur","change","error","focus","load","loadend","loadstart","mouseenter","mouseleave","progress","reset","scroll","submit","unload","toggle","DOMNodeInsertedIntoDocument","DOMNodeRemovedFromDocument"]),y={submit:!0},w=E(["click","dblclick","mousedown","mousemove","mouseup"]);class v{constructor(e){this.browserRendererId=e,this.afterClickCallbacks=[];const t=++v.nextEventDelegatorId;this.eventsCollectionKey=`_blazorEvents_${t}`,this.eventInfoStore=new b(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,a.get(n));var n;t&&t.forEach((t=>this.dispatchGlobalEventToAllElements(t,e))),"click"===e.type&&this.afterClickCallbacks.forEach((t=>t(e)))}dispatchGlobalEventToAllElements(e,t){let n=t.target,o=null,s=!1;const a=m.hasOwnProperty(e);let c=!1;for(;n;){const d=this.getEventHandlerInfosForElement(n,!1);if(d){const a=d.getHandler(e);if(a&&(l=n,u=t.type,!((l instanceof HTMLButtonElement||l instanceof HTMLInputElement||l instanceof HTMLTextAreaElement||l instanceof HTMLSelectElement)&&w.hasOwnProperty(u)&&l.disabled))){if(!s){const n=h(e);o=(null==n?void 0:n.createEventArgs)?n.createEventArgs(t):{},s=!0}y.hasOwnProperty(t.type)&&t.preventDefault(),i({browserRendererId:this.browserRendererId,eventHandlerId:a.eventHandlerId,eventName:e,eventFieldInfo:r.fromEvent(a.renderingComponentId,t)},o)}d.stopPropagation(e)&&(c=!0),d.preventDefault(e)&&t.preventDefault()}n=a||c?null:n.parentElement}var l,u}getEventHandlerInfosForElement(e,t){return e.hasOwnProperty(this.eventsCollectionKey)?e[this.eventsCollectionKey]:t?e[this.eventsCollectionKey]=new _:null}}v.nextEventDelegatorId=0;class b{constructor(e){this.globalListener=e,this.infosByEventHandlerId={},this.countByEventName={},l.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=u(e),this.countByEventName.hasOwnProperty(e))this.countByEventName[e]++;else{this.countByEventName[e]=1;const t=m.hasOwnProperty(e);document.addEventListener(e,this.globalListener,t)}}update(e,t){if(this.infosByEventHandlerId.hasOwnProperty(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=u(t.eventName);0==--this.countByEventName[n]&&(delete this.countByEventName[n],document.removeEventListener(n,this.globalListener))}return t}handleEventNameAliasAdded(e,t){if(this.countByEventName.hasOwnProperty(e)){const n=this.countByEventName[e];delete this.countByEventName[e],document.removeEventListener(e,this.globalListener),this.addGlobalListener(t),this.countByEventName[t]+=n-1}}}class _{constructor(){this.handlers={},this.preventDefaultFlags=null,this.stopPropagationFlags=null}getHandler(e){return this.handlers.hasOwnProperty(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 E(e){const t={};return e.forEach((e=>{t[e]=!0})),t}const S=H("_blazorLogicalChildren"),C=H("_blazorLogicalParent"),I=H("_blazorLogicalEnd");function k(e,t){if(e.childNodes.length>0&&!t)throw new Error("New logical elements must start empty, or allowExistingContents must be true");return S in e||(e[S]=[]),e}function T(e,t){const n=document.createComment("!");return D(n,e,t),n}function D(e,t,n){const r=e;if(e instanceof Comment&&A(r)&&A(r).length>0)throw new Error("Not implemented: inserting non-empty logical container");if(R(r))throw new Error("Not implemented: moving existing logical children");const o=A(t);if(n0;)x(n,0)}const r=n;r.parentNode.removeChild(r)}function R(e){return e[C]||null}function P(e,t){return A(e)[t]}function U(e){var t=B(e);return"http://www.w3.org/2000/svg"===t.namespaceURI&&"foreignObject"!==t.tagName}function A(e){return e[S]}function N(e,t){const n=A(e);t.forEach((e=>{e.moveRangeStart=n[e.fromSiblingIndex],e.moveRangeEnd=L(e.moveRangeStart)})),t.forEach((t=>{const r=t.moveToBeforeMarker=document.createComment("marker"),o=n[t.toSiblingIndex+1];o?o.parentNode.insertBefore(r,o):M(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 B(e){if(e instanceof Element)return e;if(e instanceof Comment)return e.parentNode;throw new Error("Not a valid logical element")}function $(e){const t=A(R(e));return t[Array.prototype.indexOf.call(t,e)+1]||null}function M(e,t){if(t instanceof Element)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=$(t);n?n.parentNode.insertBefore(e,n):M(e,R(t))}}}function L(e){if(e instanceof Element)return e;const t=$(e);if(t)return t.previousSibling;{const t=R(e);return t instanceof Element?t.lastChild:L(t)}}function H(e){return"function"==typeof Symbol?Symbol():e}function O(e){return`_bl_${e}`}e.attachReviver(((e,t)=>t&&"object"==typeof t&&t.hasOwnProperty("__internalId")&&"string"==typeof t.__internalId?function(e){const t=`[${O(e)}]`;return document.querySelector(t)}(t.__internalId):t));const F="_blazorSelectValue",j=document.createElement("template"),W=document.createElementNS("http://www.w3.org/2000/svg","g"),z={},q="__internal_",J="preventDefault_",K="stopPropagation_";class V{constructor(e){this.childComponentLocations={},this.eventDelegator=new v(e),this.eventDelegator.notifyAfterClick((e=>{if(!ee)return;if(0!==e.button||function(e){return e.ctrlKey||e.shiftKey||e.altKey||e.metaKey}(e))return;if(e.defaultPrevented)return;const t=function(e){const t=!window._blazorDisableComposedPath&&e.composedPath&&e.composedPath();if(t){for(let e=0;ese(!1))))},enableNavigationInterception:function(){ee=!0},navigateTo:oe,getBaseURI:()=>document.baseURI,getLocationHref:()=>location.href};function oe(e,t,n=!1){const r=ce(e);if(!t&&he(r))ie(r,!1,n);else if(t&&location.href===e){const t=e+"?";history.replaceState(null,"",t),location.replace(e)}else n?history.replaceState(null,"",r):location.href=e}function ie(e,t,n=!1){Z=!0,n?history.replaceState(null,"",e):history.pushState(null,"",e),se(t)}async function se(e){ne&&await ne(location.href,e)}let ae;function ce(e){return ae=ae||document.createElement("a"),ae.href=e,ae.href}function le(e,t){return e?e.tagName===t?e:le(e.parentElement,t):null}function he(e){const t=(n=document.baseURI).substr(0,n.lastIndexOf("/")+1);var n;return e.startsWith(t)}const ue={init:function(e,t,n,r=50){const o=pe(t);(o||document.documentElement).style.overflowAnchor="none";const i=new IntersectionObserver((function(r){r.forEach((r=>{var o;if(!r.isIntersecting)return;const i=t.getBoundingClientRect(),s=n.getBoundingClientRect().top-i.bottom,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`});i.observe(t),i.observe(n);const s=c(t),a=c(n);function c(e){const t=new MutationObserver((()=>{i.unobserve(e),i.observe(e)}));return t.observe(e,{attributes:!0}),t}de[e._id]={intersectionObserver:i,mutationObserverBefore:s,mutationObserverAfter:a}},dispose:function(e){const t=de[e._id];t&&(t.intersectionObserver.disconnect(),t.mutationObserverBefore.disconnect(),t.mutationObserverAfter.disconnect(),e.dispose(),delete de[e._id])}},de={};function pe(e){return e?"visible"!==getComputedStyle(e).overflowY?e:pe(e.parentElement):null}const fe={navigateTo:oe,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=a.get(t.browserEventName);n?n.push(e):a.set(t.browserEventName,[e]),l.forEach((n=>n(e,t.browserEventName)))}s.set(e,t)},_internal:{navigationManager:re,domWrapper:{focus:function(e,t){if(!(e instanceof HTMLElement))throw new Error("Unable to focus an invalid element.");e.focus({preventScroll:t})}},Virtualize:ue}};window.Blazor=fe;const ge=[0,2e3,1e4,3e4,null];class me{constructor(e){this._retryDelays=void 0!==e?[...e,null]:ge}nextRetryDelayInMilliseconds(e){return this._retryDelays[e.previousRetryCount]}}class ye extends Error{constructor(e,t){const n=new.target.prototype;super(`${e}: Status code '${t}'`),this.statusCode=t,this.__proto__=n}}class we extends Error{constructor(e="A timeout occurred."){const t=new.target.prototype;super(e),this.__proto__=t}}class ve extends Error{constructor(e="An abort occurred."){const t=new.target.prototype;super(e),this.__proto__=t}}class be{constructor(e,t,n){this.statusCode=e,this.statusText=t,this.content=n}}class _e{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""}}var Ee,Se,Ce,Ie,ke;!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"}(Ee||(Ee={}));class Te extends _e{constructor(e){if(super(),this._logger=e,"undefined"==typeof fetch){const e=require;this._jar=new(e("tough-cookie").CookieJar),this._fetchType=e("node-fetch"),this._fetchType=e("fetch-cookie")(this._fetchType,this._jar),this._abortControllerType=e("abort-controller")}else this._fetchType=fetch.bind(self),this._abortControllerType=AbortController}async send(e){if(e.abortSignal&&e.abortSignal.aborted)throw new ve;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 ve});let r,o=null;if(e.timeout){const r=e.timeout;o=setTimeout((()=>{t.abort(),this._logger.log(Ee.Warning,"Timeout from HTTP request."),n=new we}),r)}try{r=await this._fetchType(e.url,{body:e.content,cache:"no-cache",credentials:!0===e.withCredentials?"include":"same-origin",headers:{"Content-Type":"text/plain;charset=UTF-8","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(Ee.Warning,`Error from HTTP request. ${e}.`),e}finally{o&&clearTimeout(o),e.abortSignal&&(e.abortSignal.onabort=null)}if(!r.ok){const e=await De(r,"text");throw new ye(e||r.statusText,r.status)}const i=De(r,e.responseType),s=await i;return new be(r.status,r.statusText,s)}getCookieString(e){return""}}function De(e,t){let n;switch(t){case"arraybuffer":n=e.arrayBuffer();break;case"text":n=e.text();break;case"blob":case"document":case"json":throw new Error(`${t} is not supported.`);default:n=e.text()}return n}class xe extends _e{constructor(e){super(),this._logger=e}send(e){return e.abortSignal&&e.abortSignal.aborted?Promise.reject(new ve):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"),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 ve)}),e.timeout&&(r.timeout=e.timeout),r.onload=()=>{e.abortSignal&&(e.abortSignal.onabort=null),r.status>=200&&r.status<300?t(new be(r.status,r.statusText,r.response||r.responseText)):n(new ye(r.response||r.responseText||r.statusText,r.status))},r.onerror=()=>{this._logger.log(Ee.Warning,`Error from HTTP request. ${r.status}: ${r.statusText}.`),n(new ye(r.statusText,r.status))},r.ontimeout=()=>{this._logger.log(Ee.Warning,"Timeout from HTTP request."),n(new we)},r.send(e.content||"")})):Promise.reject(new Error("No url defined.")):Promise.reject(new Error("No method defined."))}}class Re extends _e{constructor(e){if(super(),"undefined"!=typeof fetch)this._httpClient=new Te(e);else{if("undefined"==typeof XMLHttpRequest)throw new Error("No usable HttpClient found.");this._httpClient=new xe(e)}}send(e){return e.abortSignal&&e.abortSignal.aborted?Promise.reject(new ve):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)}}class Pe{}Pe.Authorization="Authorization",Pe.Cookie="Cookie",function(e){e[e.None=0]="None",e[e.WebSockets=1]="WebSockets",e[e.ServerSentEvents=2]="ServerSentEvents",e[e.LongPolling=4]="LongPolling"}(Se||(Se={})),function(e){e[e.Text=1]="Text",e[e.Binary=2]="Binary"}(Ce||(Ce={}));class Ue{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 Ae{constructor(){}log(e,t){}}Ae.instance=new Ae;class Ne{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 Be{static get isBrowser(){return"object"==typeof window}static get isWebWorker(){return"object"==typeof self&&"importScripts"in self}static get isNode(){return!this.isBrowser&&!this.isWebWorker}}function $e(e,t){let n="";return Me(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 Me(e){return e&&"undefined"!=typeof ArrayBuffer&&(e instanceof ArrayBuffer||e.constructor&&"ArrayBuffer"===e.constructor.name)}async function Le(e,t,n,r,o,i,s,a,c){let l={};if(o){const e=await o();e&&(l={Authorization:`Bearer ${e}`})}const[h,u]=Fe();l[h]=u,e.log(Ee.Trace,`(${t} transport) sending data. ${$e(i,s)}.`);const d=Me(i)?"arraybuffer":"text",p=await n.post(r,{content:i,headers:{...l,...c},responseType:d,withCredentials:a});e.log(Ee.Trace,`(${t} transport) request complete. Response status: ${p.statusCode}.`)}class He{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 Oe{constructor(e){this._minLevel=e,this.out=console}log(e,t){if(e>=this._minLevel){const n=`[${(new Date).toISOString()}] ${Ee[e]}: ${t}`;switch(e){case Ee.Critical:case Ee.Error:this.out.error(n);break;case Ee.Warning:this.out.warn(n);break;case Ee.Information:this.out.info(n);break;default:this.out.log(n)}}}}function Fe(){let e="X-SignalR-User-Agent";return Be.isNode&&(e="User-Agent"),[e,je("0.0.0-DEV_BUILD",We(),Be.isNode?"NodeJS":"Browser",ze())]}function je(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 We(){if(!Be.isNode)return"";switch(process.platform){case"win32":return"Windows NT";case"darwin":return"macOS";case"linux":return"Linux";default:return process.platform}}function ze(){if(Be.isNode)return process.versions.node}class qe{constructor(e,t,n,r,o,i){this._httpClient=e,this._accessTokenFactory=t,this._logger=n,this._pollAbort=new Ue,this._logMessageContent=r,this._withCredentials=o,this._headers=i,this._running=!1,this.onreceive=null,this.onclose=null}get pollAborted(){return this._pollAbort.aborted}async connect(e,t){if(Ne.isRequired(e,"url"),Ne.isRequired(t,"transferFormat"),Ne.isIn(t,Ce,"transferFormat"),this._url=e,this._logger.log(Ee.Trace,"(LongPolling transport) Connecting."),t===Ce.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]=Fe(),o={[n]:r,...this._headers},i={abortSignal:this._pollAbort.signal,headers:o,timeout:1e5,withCredentials:this._withCredentials};t===Ce.Binary&&(i.responseType="arraybuffer");const s=await this._getAccessToken();this._updateHeaderToken(i,s);const a=`${e}&_=${Date.now()}`;this._logger.log(Ee.Trace,`(LongPolling transport) polling: ${a}.`);const c=await this._httpClient.get(a,i);200!==c.statusCode?(this._logger.log(Ee.Error,`(LongPolling transport) Unexpected response code: ${c.statusCode}.`),this._closeError=new ye(c.statusText||"",c.statusCode),this._running=!1):this._running=!0,this._receiving=this._poll(this._url,i)}async _getAccessToken(){return this._accessTokenFactory?await this._accessTokenFactory():null}_updateHeaderToken(e,t){e.headers||(e.headers={}),t?e.headers[Pe.Authorization]=`Bearer ${t}`:e.headers[Pe.Authorization]&&delete e.headers[Pe.Authorization]}async _poll(e,t){try{for(;this._running;){const n=await this._getAccessToken();this._updateHeaderToken(t,n);try{const n=`${e}&_=${Date.now()}`;this._logger.log(Ee.Trace,`(LongPolling transport) polling: ${n}.`);const r=await this._httpClient.get(n,t);204===r.statusCode?(this._logger.log(Ee.Information,"(LongPolling transport) Poll terminated by server."),this._running=!1):200!==r.statusCode?(this._logger.log(Ee.Error,`(LongPolling transport) Unexpected response code: ${r.statusCode}.`),this._closeError=new ye(r.statusText||"",r.statusCode),this._running=!1):r.content?(this._logger.log(Ee.Trace,`(LongPolling transport) data received. ${$e(r.content,this._logMessageContent)}.`),this.onreceive&&this.onreceive(r.content)):this._logger.log(Ee.Trace,"(LongPolling transport) Poll timed out, reissuing.")}catch(e){this._running?e instanceof we?this._logger.log(Ee.Trace,"(LongPolling transport) Poll timed out, reissuing."):(this._closeError=e,this._running=!1):this._logger.log(Ee.Trace,`(LongPolling transport) Poll errored after shutdown: ${e.message}`)}}}finally{this._logger.log(Ee.Trace,"(LongPolling transport) Polling complete."),this.pollAborted||this._raiseOnClose()}}async send(e){return this._running?Le(this._logger,"LongPolling",this._httpClient,this._url,this._accessTokenFactory,e,this._logMessageContent,this._withCredentials,this._headers):Promise.reject(new Error("Cannot send until the transport is connected"))}async stop(){this._logger.log(Ee.Trace,"(LongPolling transport) Stopping polling."),this._running=!1,this._pollAbort.abort();try{await this._receiving,this._logger.log(Ee.Trace,`(LongPolling transport) sending DELETE request to ${this._url}.`);const e={},[t,n]=Fe();e[t]=n;const r={headers:{...e,...this._headers},withCredentials:this._withCredentials},o=await this._getAccessToken();this._updateHeaderToken(r,o),await this._httpClient.delete(this._url,r),this._logger.log(Ee.Trace,"(LongPolling transport) DELETE request sent.")}finally{this._logger.log(Ee.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(Ee.Trace,e),this.onclose(this._closeError)}}}class Je{constructor(e,t,n,r,o,i,s){this._httpClient=e,this._accessTokenFactory=t,this._logger=n,this._logMessageContent=r,this._withCredentials=i,this._eventSourceConstructor=o,this._headers=s,this.onreceive=null,this.onclose=null}async connect(e,t){if(Ne.isRequired(e,"url"),Ne.isRequired(t,"transferFormat"),Ne.isIn(t,Ce,"transferFormat"),this._logger.log(Ee.Trace,"(SSE transport) Connecting."),this._url=e,this._accessTokenFactory){const t=await this._accessTokenFactory();t&&(e+=(e.indexOf("?")<0?"?":"&")+`access_token=${encodeURIComponent(t)}`)}return new Promise(((n,r)=>{let o,i=!1;if(t===Ce.Text){if(Be.isBrowser||Be.isWebWorker)o=new this._eventSourceConstructor(e,{withCredentials:this._withCredentials});else{const t=this._httpClient.getCookieString(e),n={};n.Cookie=t;const[r,i]=Fe();n[r]=i,o=new this._eventSourceConstructor(e,{withCredentials:this._withCredentials,headers:{...n,...this._headers}})}try{o.onmessage=e=>{if(this.onreceive)try{this._logger.log(Ee.Trace,`(SSE transport) data received. ${$e(e.data,this._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(Ee.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?Le(this._logger,"SSE",this._httpClient,this._url,this._accessTokenFactory,e,this._logMessageContent,this._withCredentials,this._headers):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 Ke{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){if(Ne.isRequired(e,"url"),Ne.isRequired(t,"transferFormat"),Ne.isIn(t,Ce,"transferFormat"),this._logger.log(Ee.Trace,"(WebSockets transport) Connecting."),this._accessTokenFactory){const t=await this._accessTokenFactory();t&&(e+=(e.indexOf("?")<0?"?":"&")+`access_token=${encodeURIComponent(t)}`)}return new Promise(((n,r)=>{let o;e=e.replace(/^http/,"ws"),this._httpClient.getCookieString(e);let i=!1;o||(o=new this._webSocketConstructor(e)),t===Ce.Binary&&(o.binaryType="arraybuffer"),o.onopen=t=>{this._logger.log(Ee.Information,`WebSocket connected to ${e}.`),this._webSocket=o,i=!0,n()},o.onerror=e=>{let t=null;t="undefined"!=typeof ErrorEvent&&e instanceof ErrorEvent?e.error:"There was an error with the transport",this._logger.log(Ee.Information,`(WebSockets transport) ${t}.`)},o.onmessage=e=>{if(this._logger.log(Ee.Trace,`(WebSockets transport) data received. ${$e(e.data,this._logMessageContent)}.`),this.onreceive)try{this.onreceive(e.data)}catch(e){return void this._close(e)}},o.onclose=e=>{if(i)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(Ee.Trace,`(WebSockets transport) sending data. ${$e(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(Ee.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 Ve{constructor(e,t={}){var n;if(this._stopPromiseResolver=()=>{},this.features={},this._negotiateVersion=1,Ne.isRequired(e,"url"),this._logger=void 0===(n=t.logger)?new Oe(Ee.Information):null===n?Ae.instance:void 0!==n.log?n:new Oe(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,"undefined"==typeof WebSocket||t.WebSocket||(t.WebSocket=WebSocket),"undefined"==typeof EventSource||t.EventSource||(t.EventSource=EventSource),this._httpClient=t.httpClient||new Re(this._logger),this._connectionState="Disconnected",this._connectionStarted=!1,this._options=t,this.onreceive=null,this.onclose=null}async start(e){if(e=e||Ce.Binary,Ne.isIn(e,Ce,"transferFormat"),this._logger.log(Ee.Debug,`Starting connection with transfer format '${Ce[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(Ee.Error,e),await this._stopPromise,Promise.reject(new Error(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(Ee.Error,e),Promise.reject(new Error(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 Xe(this.transport)),this._sendQueue.send(e))}async stop(e){return"Disconnected"===this._connectionState?(this._logger.log(Ee.Debug,`Call to HttpConnection.stop(${e}) ignored because the connection is already in the disconnected state.`),Promise.resolve()):"Disconnecting"===this._connectionState?(this._logger.log(Ee.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(Ee.Error,`HttpConnection.transport.stop() threw error '${e}'.`),this._stopConnection()}this.transport=void 0}else this._logger.log(Ee.Debug,"HttpConnection.transport is undefined in HttpConnection.stop() because start() failed.")}async _startInternal(e){let t=this.baseUrl;this._accessTokenFactory=this._options.accessTokenFactory;try{if(this._options.skipNegotiation){if(this._options.transport!==Se.WebSockets)throw new Error("Negotiation can only be skipped when using the WebSocket transport directly.");this.transport=this._constructTransport(Se.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 Error("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}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 qe&&(this.features.inherentKeepAlive=!0),"Connecting"===this._connectionState&&(this._logger.log(Ee.Debug,"The HttpConnection connected successfully."),this._connectionState="Connected")}catch(e){return this._logger.log(Ee.Error,"Failed to start the connection: "+e),this._connectionState="Disconnected",this.transport=void 0,this._stopPromiseResolver(),Promise.reject(e)}}async _getNegotiationResponse(e){const t={};if(this._accessTokenFactory){const e=await this._accessTokenFactory();e&&(t[Pe.Authorization]=`Bearer ${e}`)}const[n,r]=Fe();t[n]=r;const o=this._resolveNegotiateUrl(e);this._logger.log(Ee.Debug,`Sending negotiation request: ${o}.`);try{const e=await this._httpClient.post(o,{content:"",headers:{...t,...this._options.headers},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 ye&&404===e.statusCode&&(t+=" Either this is not a SignalR endpoint or there is a proxy blocking the connection."),this._logger.log(Ee.Error,t),Promise.reject(new Error(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(Ee.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: ${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(Ee.Error,`Failed to start the transport '${n.transport}': ${e}`),a=void 0,i.push(`${n.transport} failed: ${e}`),"Connecting"!==this._connectionState){const e="Failed to select transport before stop() was called.";return this._logger.log(Ee.Debug,e),Promise.reject(new Error(e))}}}}return i.length>0?Promise.reject(new Error(`Unable to connect to the server with any of the available transports. ${i.join(" ")}`)):Promise.reject(new Error("None of the transports supported by the client are supported by the server."))}_constructTransport(e){switch(e){case Se.WebSockets:if(!this._options.WebSocket)throw new Error("'WebSocket' is not supported in your environment.");return new Ke(this._httpClient,this._accessTokenFactory,this._logger,this._options.logMessageContent||!1,this._options.WebSocket,this._options.headers||{});case Se.ServerSentEvents:if(!this._options.EventSource)throw new Error("'EventSource' is not supported in your environment.");return new Je(this._httpClient,this._accessTokenFactory,this._logger,this._options.logMessageContent||!1,this._options.EventSource,this._options.withCredentials,this._options.headers||{});case Se.LongPolling:return new qe(this._httpClient,this._accessTokenFactory,this._logger,this._options.logMessageContent||!1,this._options.withCredentials,this._options.headers||{});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=Se[e.transport];if(null==r)return this._logger.log(Ee.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(Ee.Debug,`Skipping transport '${Se[r]}' because it was disabled by the client.`),new Error(`'${Se[r]}' is disabled by the client.`);if(!(e.transferFormats.map((e=>Ce[e])).indexOf(n)>=0))return this._logger.log(Ee.Debug,`Skipping transport '${Se[r]}' because it does not support the requested transfer format '${Ce[n]}'.`),new Error(`'${Se[r]}' does not support ${Ce[n]}.`);if(r===Se.WebSockets&&!this._options.WebSocket||r===Se.ServerSentEvents&&!this._options.EventSource)return this._logger.log(Ee.Debug,`Skipping transport '${Se[r]}' because it is not supported in your environment.'`),new Error(`'${Se[r]}' is not supported in your environment.`);this._logger.log(Ee.Debug,`Selecting transport '${Se[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(Ee.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(Ee.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(Ee.Error,`Connection disconnected with error '${e}'.`):this._logger.log(Ee.Information,"Connection disconnected."),this._sendQueue&&(this._sendQueue.stop().catch((e=>{this._logger.log(Ee.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(Ee.Error,`HttpConnection.onclose(${e}) threw error '${t}'.`)}}}else this._logger.log(Ee.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(!Be.isBrowser||!window.document)throw new Error(`Cannot resolve '${e}'.`);const t=window.document.createElement("a");return t.href=e,this._logger.log(Ee.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 Xe{constructor(e){this._transport=e,this._buffer=[],this._executing=!0,this._sendBufferedData=new Ye,this._transportResult=new Ye,this._sendLoopPromise=this._sendLoop()}send(e){return this._bufferData(e),this._transportResult||(this._transportResult=new Ye),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 Ye;const e=this._transportResult;this._transportResult=void 0;const t="string"==typeof this._buffer[0]?this._buffer.join(""):Xe._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 Ye{constructor(){this.promise=new Promise(((e,t)=>[this._resolver,this._rejecter]=[e,t]))}resolve(){this._resolver()}reject(e){this._rejecter(e)}}class Ge{static write(e){return`${e}${Ge.RecordSeparator}`}static parse(e){if(e[e.length-1]!==Ge.RecordSeparator)throw new Error("Message is incomplete.");const t=e.split(Ge.RecordSeparator);return t.pop(),t}}Ge.RecordSeparatorCode=30,Ge.RecordSeparator=String.fromCharCode(Ge.RecordSeparatorCode);class Qe{writeHandshakeRequest(e){return Ge.write(JSON.stringify(e))}parseHandshakeResponse(e){let t,n;if(Me(e)){const r=new Uint8Array(e),o=r.indexOf(Ge.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(Ge.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=Ge.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"}(Ie||(Ie={}));class Ze{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 He(this,e)}}!function(e){e.Disconnected="Disconnected",e.Connecting="Connecting",e.Connected="Connected",e.Disconnecting="Disconnecting",e.Reconnecting="Reconnecting"}(ke||(ke={}));class et{constructor(e,t,n,r){this._nextKeepAlive=0,Ne.isRequired(e,"connection"),Ne.isRequired(t,"logger"),Ne.isRequired(n,"protocol"),this.serverTimeoutInMilliseconds=3e4,this.keepAliveIntervalInMilliseconds=15e3,this._logger=t,this._protocol=n,this.connection=e,this._reconnectPolicy=r,this._handshakeProtocol=new Qe,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=ke.Disconnected,this._connectionStarted=!1,this._cachedPingMessage=this._protocol.writeMessage({type:Ie.Ping})}static create(e,t,n,r){return new et(e,t,n,r)}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!==ke.Disconnected&&this._connectionState!==ke.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!==ke.Disconnected)return Promise.reject(new Error("Cannot start a HubConnection that is not in the 'Disconnected' state."));this._connectionState=ke.Connecting,this._logger.log(Ee.Debug,"Starting HubConnection.");try{await this._startInternal(),this._connectionState=ke.Connected,this._connectionStarted=!0,this._logger.log(Ee.Debug,"HubConnection connected successfully.")}catch(e){return this._connectionState=ke.Disconnected,this._logger.log(Ee.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(Ee.Debug,"Sending handshake request."),await this._sendMessage(this._handshakeProtocol.writeHandshakeRequest(t)),this._logger.log(Ee.Information,`Using HubProtocol '${this._protocol.name}'.`),this._cleanupTimeout(),this._resetTimeoutPeriod(),this._resetKeepAliveInterval(),await e,this._stopDuringStartError)throw this._stopDuringStartError}catch(e){throw this._logger.log(Ee.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){return this._connectionState===ke.Disconnected?(this._logger.log(Ee.Debug,`Call to HubConnection.stop(${e}) ignored because it is already in the disconnected state.`),Promise.resolve()):this._connectionState===ke.Disconnecting?(this._logger.log(Ee.Debug,`Call to HttpConnection.stop(${e}) ignored because the connection is already in the disconnecting state.`),this._stopPromise):(this._connectionState=ke.Disconnecting,this._logger.log(Ee.Debug,"Stopping HubConnection."),this._reconnectDelayHandle?(this._logger.log(Ee.Debug,"Connection stopped during reconnect delay. Done reconnecting."),clearTimeout(this._reconnectDelayHandle),this._reconnectDelayHandle=void 0,this._completeClose(),Promise.resolve()):(this._cleanupTimeout(),this._cleanupPingTimer(),this._stopDuringStartError=e||new Error("The connection was stopped before the hub handshake could complete."),this.connection.stop(e)))}stream(e,...t){const[n,r]=this._replaceStreamingParams(t),o=this._createStreamInvocation(e,t,r);let i;const s=new Ze;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===Ie.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===Ie.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 Ie.Invocation:this._invokeClientMethod(e);break;case Ie.StreamItem:case Ie.Completion:{const t=this._callbacks[e.invocationId];t&&(e.type===Ie.Completion&&delete this._callbacks[e.invocationId],t(e));break}case Ie.Ping:break;case Ie.Close:{this._logger.log(Ee.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(Ee.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(Ee.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(Ee.Error,e);const n=new Error(e);throw this._handshakeRejecter(n),n}return this._logger.log(Ee.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===ke.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."))}_invokeClientMethod(e){const t=this._methods[e.target.toLowerCase()];if(t){try{t.forEach((t=>t.apply(this,e.arguments)))}catch(t){this._logger.log(Ee.Error,`A callback for the method ${e.target.toLowerCase()} threw error '${t}'.`)}if(e.invocationId){const e="Server requested a response, which is not supported in this version of the client.";this._logger.log(Ee.Error,e),this._stopPromise=this._stopInternal(new Error(e))}}else this._logger.log(Ee.Warning,`No client method with the name '${e.target}' found.`)}_connectionClosed(e){this._logger.log(Ee.Debug,`HubConnection.connectionClosed(${e}) called while in state ${this._connectionState}.`),this._stopDuringStartError=this._stopDuringStartError||e||new Error("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===ke.Disconnecting?this._completeClose(e):this._connectionState===ke.Connected&&this._reconnectPolicy?this._reconnect(e):this._connectionState===ke.Connected&&this._completeClose(e)}_completeClose(e){if(this._connectionStarted){this._connectionState=ke.Disconnected,this._connectionStarted=!1;try{this._closedCallbacks.forEach((t=>t.apply(this,[e])))}catch(t){this._logger.log(Ee.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(Ee.Debug,"Connection not reconnecting because the IRetryPolicy returned null on the first reconnect attempt."),void this._completeClose(e);if(this._connectionState=ke.Reconnecting,e?this._logger.log(Ee.Information,`Connection reconnecting because of error '${e}'.`):this._logger.log(Ee.Information,"Connection reconnecting."),0!==this._reconnectingCallbacks.length){try{this._reconnectingCallbacks.forEach((t=>t.apply(this,[e])))}catch(t){this._logger.log(Ee.Error,`An onreconnecting callback called with error '${e}' threw error '${t}'.`)}if(this._connectionState!==ke.Reconnecting)return void this._logger.log(Ee.Debug,"Connection left the reconnecting state in onreconnecting callback. Done reconnecting.")}for(;null!==o;){if(this._logger.log(Ee.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!==ke.Reconnecting)return void this._logger.log(Ee.Debug,"Connection left the reconnecting state during reconnect delay. Done reconnecting.");try{if(await this._startInternal(),this._connectionState=ke.Connected,this._logger.log(Ee.Information,"HubConnection reconnected successfully."),0!==this._reconnectedCallbacks.length)try{this._reconnectedCallbacks.forEach((e=>e.apply(this,[this.connection.connectionId])))}catch(e){this._logger.log(Ee.Error,`An onreconnected callback called with connectionId '${this.connection.connectionId}; threw error '${e}'.`)}return}catch(e){if(this._logger.log(Ee.Information,`Reconnect attempt failed because of error '${e}'.`),this._connectionState!==ke.Reconnecting)return this._logger.log(Ee.Debug,`Connection moved to the '${this._connectionState}' from the reconnecting state during reconnect attempt. Done reconnecting.`),void(this._connectionState===ke.Disconnecting&&this._completeClose());r=e instanceof Error?e:new Error(e.toString()),o=this._getNextRetryDelay(n++,Date.now()-t,r)}}this._logger.log(Ee.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(Ee.Error,`IRetryPolicy.nextRetryDelayInMilliseconds(${e}, ${t}) threw error '${n}'.`),null}}_cancelCallbacksWithError(e){const t=this._callbacks;this._callbacks={},Object.keys(t).forEach((n=>{(0,t[n])(null,e)}))}_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:Ie.Invocation}:{arguments:t,target:e,type:Ie.Invocation};{const n=this._invocationId;return this._invocationId++,0!==r.length?{arguments:t,invocationId:n.toString(),streamIds:r,target:e,type:Ie.Invocation}:{arguments:t,invocationId:n.toString(),target:e,type:Ie.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 ut=ot?new TextDecoder:null,dt=ot?"undefined"!=typeof process&&"force"!==process.env.TEXT_DECODER?200:0:it,pt=function(e,t){this.type=e,this.data=t};function ft(e,t,n){var r=Math.floor(n/4294967296),o=n;e.setUint32(t,r),e.setUint32(t+4,o)}function gt(e,t){return 4294967296*e.getInt32(t)+e.getUint32(t+4)}var mt={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),ft(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:gt(t,4),nsec:t.getUint32(0)};default:throw new Error("Unrecognized data size for timestamp: "+e.length)}}(e);return new Date(1e3*t.sec+t.nsec/1e6)}},yt=function(){function e(){this.builtInEncoders=[],this.builtInDecoders=[],this.encoders=[],this.decoders=[],this.register(mt)}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 "+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: "+e+" bytes in UTF-8");this.writeU8(219),this.writeU32(e)}},e.prototype.encodeString=function(e){if(e.length>ct){var t=st(e);this.ensureBufferSizeToWrite(5+t),this.writeStringHeader(t),lt(e,this.bytes,this.pos),this.pos+=t}else t=st(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: "+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: "+t);this.writeU8(198),this.writeU32(t)}var n=wt(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: "+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=ht(e,t,n),i=Uint8Array.prototype.slice.call(e,t,t+n);return this.store(i,o),o},e}(),St=(_t=function(e,t){return(_t=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])})(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}_t(e,t),e.prototype=null===t?Object.create(t):(n.prototype=t.prototype,new n)}),Ct=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]1||a(e,t)}))})}function a(e,t){try{(n=o[e](t)).value instanceof kt?Promise.resolve(n.value.v).then(c,l):h(i[0][2],n)}catch(e){h(i[0][3],e)}var n}function c(e){a("next",e)}function l(e){a("throw",e)}function h(e,t){e(t),i.shift(),i.length&&a(i[0][0],i[0][1])}},Dt=new DataView(new ArrayBuffer(0)),xt=new Uint8Array(Dt.buffer),Rt=function(){try{Dt.getInt8(0)}catch(e){return e.constructor}throw new Error("never reached")}(),Pt=new Rt("Insufficient data"),Ut=4294967295,At=new Et,Nt=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 St(t,e),t}(Error),Bt=function(){function e(e,t,n,r,o,i,s,a){void 0===e&&(e=yt.defaultCodec),void 0===t&&(t=void 0),void 0===n&&(n=Ut),void 0===r&&(r=Ut),void 0===o&&(o=Ut),void 0===i&&(i=Ut),void 0===s&&(s=Ut),void 0===a&&(a=At),this.extensionCodec=e,this.context=t,this.maxStrLength=n,this.maxBinLength=r,this.maxArrayLength=o,this.maxMapLength=i,this.maxExtLength=s,this.keyDecoder=a,this.totalPos=0,this.pos=0,this.view=Dt,this.bytes=xt,this.headByte=-1,this.stack=[]}return e.prototype.reinitializeState=function(){this.totalPos=0,this.headByte=-1,this.stack.length=0},e.prototype.setBuffer=function(e){this.bytes=wt(e),this.view=function(e){if(e instanceof ArrayBuffer)return new DataView(e);var t=wt(e);return new DataView(t.buffer,t.byteOffset,t.byteLength)}(this.bytes),this.pos=0},e.prototype.appendBuffer=function(e){if(-1!==this.headByte||this.hasRemaining()){var t=this.bytes.subarray(this.pos),n=wt(e),r=new Uint8Array(t.length+n.length);r.set(t),r.set(n,t.length),this.setBuffer(r)}else this.setBuffer(e)},e.prototype.hasRemaining=function(e){return void 0===e&&(e=1),this.view.byteLength-this.pos>=e},e.prototype.createExtraByteError=function(e){var t=this.view,n=this.pos;return new RangeError("Extra "+(t.byteLength-n)+" of "+t.byteLength+" byte(s) found at buffer["+e+"]")},e.prototype.decode=function(e){this.reinitializeState(),this.setBuffer(e);var t=this.doDecodeSync();if(this.hasRemaining())throw this.createExtraByteError(this.pos);return t},e.prototype.decodeMulti=function(e){return Ct(this,(function(t){switch(t.label){case 0:this.reinitializeState(),this.setBuffer(e),t.label=1;case 1:return this.hasRemaining()?[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,u,d;return Ct(this,(function(p){switch(p.label){case 0:i=!1,p.label=1;case 1:p.trys.push([1,6,7,12]),t=It(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 Rt))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())throw this.createExtraByteError(this.totalPos);return[2,s]}throw h=(l=this).headByte,u=l.pos,d=l.totalPos,new RangeError("Insufficient data in parsing "+bt(h)+" at "+d+" ("+u+" 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 Tt(this,arguments,(function(){var n,r,o,i,s,a,c,l,h;return Ct(this,(function(u){switch(u.label){case 0:n=t,r=-1,u.label=1;case 1:u.trys.push([1,13,14,19]),o=It(e),u.label=2;case 2:return[4,kt(o.next())];case 3:if((i=u.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()),u.label=4;case 4:u.trys.push([4,9,,10]),u.label=5;case 5:return[4,kt(this.doDecodeSync())];case 6:return[4,u.sent()];case 7:return u.sent(),0==--r?[3,8]:[3,5];case 8:return[3,10];case 9:if(!((a=u.sent())instanceof Rt))throw a;return[3,10];case 10:this.totalPos+=this.pos,u.label=11;case 11:return[3,2];case 12:return[3,19];case 13:return c=u.sent(),l={error:c},[3,19];case 14:return u.trys.push([14,,17,18]),i&&!i.done&&(h=o.return)?[4,kt(h.call(o))]:[3,16];case 15:u.sent(),u.label=16;case 16:return[3,18];case 17:if(l)throw l.error;return[7];case 18:return[7];case 19:return[2]}}))}))},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 Nt("Unrecognized type byte: "+bt(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 Nt("The type of key must be string or number but "+typeof t);if("__proto__"===t)throw new Nt("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 Nt("Unrecognized array type byte: "+bt(e))}},e.prototype.pushMapState=function(e){if(e>this.maxMapLength)throw new Nt("Max length exceeded: map length ("+e+") > maxMapLengthLength ("+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 Nt("Max length exceeded: array length ("+e+") > maxArrayLength ("+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 Nt("Max length exceeded: UTF-8 byte length ("+e+") > maxStrLength ("+this.maxStrLength+")");if(this.bytes.byteLengthdt?function(e,t,n){var r=e.subarray(t,t+n);return ut.decode(r)}(this.bytes,o,e):ht(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 Nt("Max length exceeded: bin length ("+e+") > maxBinLength ("+this.maxBinLength+")");if(!this.hasRemaining(e+t))throw Pt;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 Nt("Max length exceeded: ext length ("+e+") > maxExtLength ("+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=gt(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 $t{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 Mt=new Uint8Array([145,Ie.Ping]);class Lt{constructor(e){this.name="messagepack",this.version=1,this.transferFormat=Ce.Binary,this._errorResult=1,this._voidResult=2,this._nonVoidResult=3,e=e||{},this._encoder=new vt(e.extensionCodec,e.context,e.maxDepth,e.initialBufferSize,e.sortKeys,e.forceFloat32,e.ignoreUndefined,e.forceIntegerToFloat),this._decoder=new Bt(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=Ae.instance);const r=$t.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 Ie.Invocation:return this._writeInvocation(e);case Ie.StreamInvocation:return this._writeStreamInvocation(e);case Ie.StreamItem:return this._writeStreamItem(e);case Ie.Completion:return this._writeCompletion(e);case Ie.Ping:return $t.write(Mt);case Ie.CancelInvocation:return this._writeCancelInvocation(e);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 Ie.Invocation:return this._createInvocationMessage(this._readHeaders(n),n);case Ie.StreamItem:return this._createStreamItemMessage(this._readHeaders(n),n);case Ie.Completion:return this._createCompletionMessage(this._readHeaders(n),n);case Ie.Ping:return this._createPingMessage(n);case Ie.Close:return this._createCloseMessage(n);default:return t.log(Ee.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:Ie.Close}}_createPingMessage(e){if(e.length<1)throw new Error("Invalid payload for Ping message.");return{type:Ie.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:Ie.Invocation}:{arguments:t[4],headers:e,streamIds:[],target:t[3],type:Ie.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:Ie.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:Ie.Completion}}_writeInvocation(e){let t;return t=e.streamIds?this._encoder.encode([Ie.Invocation,e.headers||{},e.invocationId||null,e.target,e.arguments,e.streamIds]):this._encoder.encode([Ie.Invocation,e.headers||{},e.invocationId||null,e.target,e.arguments]),$t.write(t.slice())}_writeStreamInvocation(e){let t;return t=e.streamIds?this._encoder.encode([Ie.StreamInvocation,e.headers||{},e.invocationId,e.target,e.arguments,e.streamIds]):this._encoder.encode([Ie.StreamInvocation,e.headers||{},e.invocationId,e.target,e.arguments]),$t.write(t.slice())}_writeStreamItem(e){const t=this._encoder.encode([Ie.StreamItem,e.headers||{},e.invocationId,e.item]);return $t.write(t.slice())}_writeCompletion(e){const t=e.error?this._errorResult:e.result?this._nonVoidResult:this._voidResult;let n;switch(t){case this._errorResult:n=this._encoder.encode([Ie.Completion,e.headers||{},e.invocationId,t,e.error]);break;case this._voidResult:n=this._encoder.encode([Ie.Completion,e.headers||{},e.invocationId,t]);break;case this._nonVoidResult:n=this._encoder.encode([Ie.Completion,e.headers||{},e.invocationId,t,e.result])}return $t.write(n.slice())}_writeCancelInvocation(e){const t=this._encoder.encode([Ie.CancelInvocation,e.headers||{},e.invocationId]);return $t.write(t.slice())}_readHeaders(e){const t=e[1];if("object"!=typeof t)throw new Error("Invalid headers.");return t}}let Ht=!1;const Ot="function"==typeof TextDecoder?new TextDecoder("utf-8"):null,Ft=Ot?Ot.decode.bind(Ot):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("")},jt=Math.pow(2,32),Wt=Math.pow(2,21)-1;function zt(e,t){return e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24}function qt(e,t){return e[t]+(e[t+1]<<8)+(e[t+2]<<16)+(e[t+3]<<24>>>0)}function Jt(e,t){const n=qt(e,t+4);if(n>Wt)throw new Error(`Cannot read uint64 with high order part ${n}, because the result would exceed Number.MAX_SAFE_INTEGER.`);return n*jt+qt(e,t)}class Kt{constructor(e){this.batchData=e;const t=new Gt(e);this.arrayRangeReader=new Qt(e),this.arrayBuilderSegmentReader=new Zt(e),this.diffReader=new Vt(e),this.editReader=new Xt(e,t),this.frameReader=new Yt(e,t)}updatedComponents(){return zt(this.batchData,this.batchData.length-20)}referenceFrames(){return zt(this.batchData,this.batchData.length-16)}disposedComponentIds(){return zt(this.batchData,this.batchData.length-12)}disposedEventHandlerIds(){return zt(this.batchData,this.batchData.length-8)}updatedComponentsEntry(e,t){const n=e+4*t;return zt(this.batchData,n)}referenceFramesEntry(e,t){return e+20*t}disposedComponentIdsEntry(e,t){const n=e+4*t;return zt(this.batchData,n)}disposedEventHandlerIdsEntry(e,t){const n=e+8*t;return Jt(this.batchData,n)}}class Vt{constructor(e){this.batchDataUint8=e}componentId(e){return zt(this.batchDataUint8,e)}edits(e){return e+4}editsEntry(e,t){return e+16*t}}class Xt{constructor(e,t){this.batchDataUint8=e,this.stringReader=t}editType(e){return zt(this.batchDataUint8,e)}siblingIndex(e){return zt(this.batchDataUint8,e+4)}newTreeIndex(e){return zt(this.batchDataUint8,e+8)}moveToSiblingIndex(e){return zt(this.batchDataUint8,e+8)}removedAttributeName(e){const t=zt(this.batchDataUint8,e+12);return this.stringReader.readString(t)}}class Yt{constructor(e,t){this.batchDataUint8=e,this.stringReader=t}frameType(e){return zt(this.batchDataUint8,e)}subtreeLength(e){return zt(this.batchDataUint8,e+4)}elementReferenceCaptureId(e){const t=zt(this.batchDataUint8,e+4);return this.stringReader.readString(t)}componentId(e){return zt(this.batchDataUint8,e+8)}elementName(e){const t=zt(this.batchDataUint8,e+8);return this.stringReader.readString(t)}textContent(e){const t=zt(this.batchDataUint8,e+4);return this.stringReader.readString(t)}markupContent(e){const t=zt(this.batchDataUint8,e+4);return this.stringReader.readString(t)}attributeName(e){const t=zt(this.batchDataUint8,e+4);return this.stringReader.readString(t)}attributeValue(e){const t=zt(this.batchDataUint8,e+8);return this.stringReader.readString(t)}attributeEventHandlerId(e){return Jt(this.batchDataUint8,e+12)}}class Gt{constructor(e){this.batchDataUint8=e,this.stringTableStartIndex=zt(e,e.length-4)}readString(e){if(-1===e)return null;{const n=zt(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(en.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(en.Debug,`Waiting for batch ${this.nextBatchId}. Batch ${e} not processed.`);try{this.nextBatchId++,this.logger.log(en.Debug,`Applying batch ${e}.`),function(e,t){const n=Q[e];if(!n)throw new Error(`There is no browser renderer with ID ${e}.`);const r=t.arrayRangeReader,o=t.updatedComponents(),i=r.values(o),s=r.count(o),a=t.referenceFrames(),c=r.values(a),l=t.diffReader;for(let e=0;e=this.minLevel){const n=`[${(new Date).toISOString()}] ${en[e]}: ${t}`;switch(e){case en.Critical:case en.Error:console.error(n);break;case en.Warning:console.warn(n);break;case en.Information:console.info(n);break;default:console.log(n)}}}}class on{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!==ke.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!==ke.Connected)return!1;const t=await e.invoke("StartCircuit",re.getBaseURI(),re.getLocationHref(),JSON.stringify(this.components.map((e=>e.toRecord()))),this.applicationState||"");return!!t&&(this.initialize(t),!0)}resolveElement(e){const t=Number.parseInt(e);if(Number.isNaN(t))throw new Error(`Invalid sequence number '${e}'.`);return function(e,t){if(!e.parentNode)throw new Error(`Comment not connected to the DOM ${e.textContent}`);const n=e.parentNode,r=k(n,!0),o=A(r);return Array.from(n.childNodes).forEach((e=>o.push(e))),e[C]=r,t&&(e[I]=t,k(t)),k(e)}(this.components[t].start,this.components[t].end)}}const sn={configureSignalR:e=>{},logLevel:en.Warning,reconnectionOptions:{maxRetries:8,retryIntervalMilliseconds:2e4,dialogId:"components-reconnect-modal"}};class an{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.modal.innerHTML='

Alternatively, reload

',this.message=this.modal.querySelector("h5"),this.button=this.modal.querySelector("button"),this.reloadParagraph=this.modal.querySelector("p"),this.loader=this.getLoader(),this.message.after(this.loader),this.button.addEventListener("click",(async()=>{this.show();try{await(null==fe?void 0:fe.reconnect)()||this.rejected()}catch(e){this.logger.log(en.Error,e),this.failed()}})),this.reloadParagraph.querySelector("a").addEventListener("click",(()=>location.reload()))}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",this.message.innerHTML="Reconnection failed. Try reloading the page if you're unable to reconnect.",this.message.querySelector("a").addEventListener("click",(()=>location.reload()))}rejected(){this.button.style.display="none",this.reloadParagraph.style.display="none",this.loader.style.display="none",this.message.innerHTML="Could not reconnect to the server. Reload the page to restore functionality.",this.message.querySelector("a").addEventListener("click",(()=>location.reload()))}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 cn{constructor(e,t,n){this.dialog=e,this.maxRetries=t,this.document=n,this.document=n;const r=this.document.getElementById(cn.MaxRetriesId);r&&(r.innerText=this.maxRetries.toString())}show(){this.removeClasses(),this.dialog.classList.add(cn.ShowClassName)}update(e){const t=this.document.getElementById(cn.CurrentAttemptId);t&&(t.innerText=e.toString())}hide(){this.removeClasses(),this.dialog.classList.add(cn.HideClassName)}failed(){this.removeClasses(),this.dialog.classList.add(cn.FailedClassName)}rejected(){this.removeClasses(),this.dialog.classList.add(cn.RejectedClassName)}removeClasses(){this.dialog.classList.remove(cn.ShowClassName,cn.HideClassName,cn.FailedClassName,cn.RejectedClassName)}}cn.ShowClassName="components-reconnect-show",cn.HideClassName="components-reconnect-hide",cn.FailedClassName="components-reconnect-failed",cn.RejectedClassName="components-reconnect-rejected",cn.MaxRetriesId="components-reconnect-max-retries",cn.CurrentAttemptId="components-reconnect-current-attempt";class ln{constructor(e,t,n){this._currentReconnectionProcess=null,this._logger=e,this._reconnectionDisplay=t,this._reconnectCallback=n||(()=>fe.reconnect())}onConnectionDown(e,t){if(!this._reconnectionDisplay){const t=document.getElementById(e.dialogId);this._reconnectionDisplay=t?new cn(t,e.maxRetries,document):new an(e.dialogId,e.maxRetries,document,this._logger)}this._currentReconnectionProcess||(this._currentReconnectionProcess=new hn(e,this._logger,this._reconnectCallback,this._reconnectionDisplay))}onConnectionUp(){this._currentReconnectionProcess&&(this._currentReconnectionProcess.dispose(),this._currentReconnectionProcess=null)}}class hn{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;thn.MaximumFirstRetryInterval?hn.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(en.Error,e)}}this.reconnectDisplay.failed()}delay(e){return new Promise((t=>setTimeout(t,e)))}}hn.MaximumFirstRetryInterval=3e3;const un=/^\s*Blazor-Component-State:(?[a-zA-Z0-9\+\/=]+)$/;function dn(e){var t;if(e.nodeType===Node.COMMENT_NODE){const n=e.textContent||"",r=un.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 gn(e,t){const n=e.currentElement;if(n&&n.nodeType===Node.COMMENT_NODE&&n.textContent){const r=fn.exec(n.textContent),o=r&&r.groups&&r.groups.descriptor;if(!o)return;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;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.");if(c){const e=mn(c,n);if(!e)throw new Error(`Could not find an end component comment for '${t}'`);return{type:r,assembly:o,typeName:i,parameterDefinitions:s&&atob(s),parameterValues:a&&atob(a),start:t,prerenderId:c,end:e}}return{type:r,assembly:o,typeName:i,parameterDefinitions:s&&atob(s),parameterValues:a&&atob(a),start:t}}}(r,n,e);case"server":return function(e,t,n){const{type:r,descriptor:o,sequence:i,prerenderId:s}=e;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)}'`);if(s){const e=mn(s,n);if(!e)throw new Error(`Could not find an end component comment for '${t}'`);return{type:r,sequence:i,descriptor:o,start:t,prerenderId:s,end:e}}return{type:r,sequence:i,descriptor:o,start:t}}}(r,n,e)}}catch(e){throw new Error(`Found malformed component comment at ${n.textContent}`)}}}function mn(e,t){for(;t.next()&&t.currentElement;){const n=t.currentElement;if(n.nodeType!==Node.COMMENT_NODE)continue;if(!n.textContent)continue;const r=fn.exec(n.textContent),o=r&&r[1];if(o)return yn(o,e),n}}function yn(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 wn{constructor(e){this.childNodes=e,this.currentIndex=-1,this.length=e.length}next(){return this.currentIndex++,this.currentIndexe.sequence-t.sequence))}(e)}(document),o=dn(document),i=new on(r,o||""),s=await Tn(t,n,i);if(!await i.startCircuit(s))return void n.log(en.Error,"Failed to start the circuit.");let a=!1;const c=()=>{if(!a){const e=new FormData,t=i.circuitId;e.append("circuitId",t),a=navigator.sendBeacon("_blazor/disconnect",e)}};fe.disconnect=c,window.addEventListener("unload",c,{capture:!1,once:!0}),fe.reconnect=async e=>{if(Cn)return!1;const r=e||await Tn(t,n,i);return await i.reconnect(r)?(t.reconnectionHandler.onConnectionUp(),!0):(n.log(en.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)},n.log(en.Information,"Blazor server-side application started.")}async function Tn(t,n,r){const i=new Lt;i.name="blazorpack";const s=(new rt).withUrl("_blazor").withHubProtocol(i);t.configureSignalR(s);const a=s.build();o=(e,t)=>{a.send("DispatchBrowserEvent",JSON.stringify(e),JSON.stringify(t))},fe._internal.navigationManager.listenForNavigationEvents(((e,t)=>a.send("OnLocationChanged",e,t))),a.on("JS.AttachComponent",((e,t)=>function(e,t,n){let r=Q[0];r||(r=Q[0]=new V(0)),r.attachRootComponentToLogicalElement(n,t)}(0,r.resolveElement(t),e))),a.on("JS.BeginInvokeJS",e.jsCallDispatcher.beginInvokeJSFromDotNet),a.on("JS.EndInvokeDotNet",e.jsCallDispatcher.endInvokeDotNetFromJS),a.on("JS.ReceiveByteArray",e.jsCallDispatcher.receiveByteArray);const c=tn.getOrCreate(n);a.on("JS.RenderBatch",((e,t)=>{n.log(en.Debug,`Received render batch with id ${e} and ${t.byteLength} bytes.`),c.processBatch(e,t,a)})),a.onclose((e=>!Cn&&t.reconnectionHandler.onConnectionDown(t.reconnectionOptions,e))),a.on("JS.Error",(e=>{Cn=!0,Dn(a,e,n),async function(){let e=document.querySelector("#blazor-error-ui");e&&(e.style.display="block"),Ht||(Ht=!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()}})))}()})),fe._internal.forceCloseConnection=()=>a.stop();const l=new Map;fe._internal.sendJSDataStream=async(e,t)=>{const n=setTimeout((async()=>{let n=5,r=(new Date).valueOf();try{const o=31744;let i=0;for(;i1)await a.send("SupplyJSDataChunk",t,c,null);else{if(void 0===l.get(t))break;await a.invoke("SupplyJSDataChunk",t,c,null);const e=(new Date).valueOf(),o=e-r;r=e,n=Math.max(1,Math.round(500/o))}i+=s}}catch(e){await a.send("SupplyJSDataChunk",t,null,e.toString())}finally{l.delete(t)}}),0);l.set(t,n)},fe._internal.cancelJSDataStream=async e=>{const t=l.get(e);void 0!==t&&(clearTimeout(t),l.delete(e))};try{await a.start()}catch(e){Dn(a,e,n)}return e.attachDispatcher({beginInvokeDotNetFromJS:(e,t,n,r,o)=>{a.send("BeginInvokeDotNetFromJS",e?e.toString():null,t,n,r||0,o)},endInvokeJSFromDotNet:(e,t,n)=>{a.send("EndInvokeJSFromDotNet",e,t,n)},sendByteArray:(e,t)=>{a.send("ReceiveByteArray",e,t)}}),a}function Dn(e,t,n){n.log(en.Error,t),e&&e.stop()}fe.start=kn,document&&document.currentScript&&"false"!==document.currentScript.getAttribute("autostart")&&kn()})(); \ No newline at end of file +(()=>{"use strict";var e,t,n;!function(e){window.DotNet=e;const t=[],n=new Map;class r{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 o="__jsObjectId",i={},s={0:new r(window)};s[0]._cachedFunctions.set("import",(e=>("string"==typeof e&&e.startsWith("./")&&(e=document.baseURI+e.substr(2)),import(e))));let a,c=1,l=1,h=null;function u(e){t.push(e)}function d(e){if(e&&"object"==typeof e){s[l]=new r(e);let t={[o]:l};return e.buffer instanceof ArrayBuffer&&void 0!==e.byteLength&&(t.__jsDataReferenceLength=e.byteLength),l++,t}throw new Error(`Cannot create a JSObjectReference from the value '${e}'.`)}function p(e){return e?JSON.parse(e,((e,n)=>t.reduce(((t,n)=>n(e,t)),n))):null}function f(e,t,n,r){const o=m();if(o.invokeDotNetFromJS){const i=I(r),s=o.invokeDotNetFromJS(e,t,n,i);return s?p(s):null}throw new Error("The current dispatcher does not support synchronous calls from JS to .NET. Use invokeMethodAsync instead.")}function g(e,t,n,r){if(e&&n)throw new Error(`For instance method calls, assemblyName should be null. Received '${e}'.`);const o=c++,s=new Promise(((e,t)=>{i[o]={resolve:e,reject:t}}));try{const i=I(r);m().beginInvokeDotNetFromJS(o,e,t,n,i)}catch(e){y(o,!1,e)}return s}function m(){if(null!==h)return h;throw new Error("No .NET call dispatcher has been set.")}function y(e,t,n){if(!i.hasOwnProperty(e))throw new Error(`There is no pending async call with ID ${e}.`);const r=i[e];delete i[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 v(e,t){let n=s[t];if(n)return n.findFunction(e);throw new Error(`JS object instance with ID ${t} does not exist (has it been disposed?).`)}function b(e){delete s[e]}e.attachDispatcher=function(e){h=e},e.attachReviver=u,e.invokeMethod=function(e,t,...n){return f(e,t,null,n)},e.invokeMethodAsync=function(e,t,...n){return g(e,t,null,n)},e.createJSObjectReference=d,e.disposeJSObjectReference=function(e){const t=e&&e.__jsObjectId;"number"==typeof t&&b(t)},function(e){e[e.Default=0]="Default",e[e.JSObjectReference=1]="JSObjectReference"}(a=e.JSCallResultType||(e.JSCallResultType={})),e.jsCallDispatcher={findJSFunction:v,disposeJSObjectReferenceById:b,invokeJSFromDotNet:(e,t,n,r)=>{const o=S(v(e,r).apply(null,p(t)),n);return null==o?null:I(o)},beginInvokeJSFromDotNet:(e,t,n,r,o)=>{const i=new Promise((e=>{e(v(t,o).apply(null,p(n)))}));e&&i.then((t=>m().endInvokeJSFromDotNet(e,!0,I([e,!0,S(t,r)]))),(t=>m().endInvokeJSFromDotNet(e,!1,JSON.stringify([e,!1,w(t)]))))},endInvokeDotNetFromJS:(e,t,n)=>{const r=t?p(n):new Error(n);y(parseInt(e),t,r)},receiveByteArray:(e,t)=>{n.set(e,t)}};class _{constructor(e){this._id=e}invokeMethod(e,...t){return f(null,e,this._id,t)}invokeMethodAsync(e,...t){return g(null,e,this._id,t)}dispose(){g(null,"__Dispose",this._id,null).catch((e=>console.error(e)))}serializeAsArg(){return{__dotNetObject:this._id}}}const E="__byte[]";function S(e,t){switch(t){case a.Default:return e;case a.JSObjectReference:return d(e);default:throw new Error(`Invalid JS call result type '${t}'.`)}}u((function(e,t){if(t&&"object"==typeof t){if(t.hasOwnProperty("__dotNetObject"))return new _(t.__dotNetObject);if(t.hasOwnProperty(o)){const e=t.__jsObjectId,n=s[e];if(n)return n.getWrappedObject();throw new Error(`JS object instance with Id '${e}' does not exist. It may have been disposed.`)}if(t.hasOwnProperty(E)){const e=t["__byte[]"],r=n.get(e);if(void 0===r)throw new Error(`Byte array index '${e}' does not exist.`);return r}}return t}));let C=0;function I(e){return C=0,JSON.stringify(e,k)}function k(e,t){if(t instanceof _)return t.serializeAsArg();if(t instanceof Uint8Array){h.sendByteArray(C,t);const e={[E]:C};return C++,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"}(n||(n={}));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}}let o;function i(e,t){if(!o)throw new Error("eventDispatcher not initialized. Call 'setEventDispatcher' to configure it.");o(e,t)}const s=new Map,a=new Map,c={createEventArgs:()=>({})},l=[];function h(e){return s.get(e)}function u(e){const t=s.get(e);return(null==t?void 0:t.browserEventName)||e}function d(e,t){e.forEach((e=>s.set(e,t)))}function p(e){const t=[];for(let n=0;n{return{...f(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}}),d(["focus","blur","focusin","focusout"],c),d(["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};var t}}),d(["contextmenu","click","mouseover","mouseout","mousemove","mousedown","mouseup","dblclick"],{createEventArgs:e=>f(e)}),d(["error"],{createEventArgs:e=>{return{message:(t=e).message,filename:t.filename,lineno:t.lineno,colno:t.colno};var t}}),d(["loadstart","timeout","abort","load","loadend","progress"],{createEventArgs:e=>{return{lengthComputable:(t=e).lengthComputable,loaded:t.loaded,total:t.total};var t}}),d(["touchcancel","touchend","touchmove","touchenter","touchleave","touchstart"],{createEventArgs:e=>{return{detail:(t=e).detail,touches:p(t.touches),targetTouches:p(t.targetTouches),changedTouches:p(t.changedTouches),ctrlKey:t.ctrlKey,shiftKey:t.shiftKey,altKey:t.altKey,metaKey:t.metaKey,type:t.type};var t}}),d(["gotpointercapture","lostpointercapture","pointercancel","pointerdown","pointerenter","pointerleave","pointermove","pointerout","pointerover","pointerup"],{createEventArgs:e=>{return{...f(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}}),d(["wheel","mousewheel"],{createEventArgs:e=>{return{...f(t=e),deltaX:t.deltaX,deltaY:t.deltaY,deltaZ:t.deltaZ,deltaMode:t.deltaMode};var t}}),d(["toggle"],c);const g=["date","datetime-local","month","time","week"],m=E(["abort","blur","change","error","focus","load","loadend","loadstart","mouseenter","mouseleave","progress","reset","scroll","submit","unload","toggle","DOMNodeInsertedIntoDocument","DOMNodeRemovedFromDocument"]),y={submit:!0},w=E(["click","dblclick","mousedown","mousemove","mouseup"]);class v{constructor(e){this.browserRendererId=e,this.afterClickCallbacks=[];const t=++v.nextEventDelegatorId;this.eventsCollectionKey=`_blazorEvents_${t}`,this.eventInfoStore=new b(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,a.get(n));var n;t&&t.forEach((t=>this.dispatchGlobalEventToAllElements(t,e))),"click"===e.type&&this.afterClickCallbacks.forEach((t=>t(e)))}dispatchGlobalEventToAllElements(e,t){let n=t.target,o=null,s=!1;const a=m.hasOwnProperty(e);let c=!1;for(;n;){const d=this.getEventHandlerInfosForElement(n,!1);if(d){const a=d.getHandler(e);if(a&&(l=n,u=t.type,!((l instanceof HTMLButtonElement||l instanceof HTMLInputElement||l instanceof HTMLTextAreaElement||l instanceof HTMLSelectElement)&&w.hasOwnProperty(u)&&l.disabled))){if(!s){const n=h(e);o=(null==n?void 0:n.createEventArgs)?n.createEventArgs(t):{},s=!0}y.hasOwnProperty(t.type)&&t.preventDefault(),i({browserRendererId:this.browserRendererId,eventHandlerId:a.eventHandlerId,eventName:e,eventFieldInfo:r.fromEvent(a.renderingComponentId,t)},o)}d.stopPropagation(e)&&(c=!0),d.preventDefault(e)&&t.preventDefault()}n=a||c?null:n.parentElement}var l,u}getEventHandlerInfosForElement(e,t){return e.hasOwnProperty(this.eventsCollectionKey)?e[this.eventsCollectionKey]:t?e[this.eventsCollectionKey]=new _:null}}v.nextEventDelegatorId=0;class b{constructor(e){this.globalListener=e,this.infosByEventHandlerId={},this.countByEventName={},l.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=u(e),this.countByEventName.hasOwnProperty(e))this.countByEventName[e]++;else{this.countByEventName[e]=1;const t=m.hasOwnProperty(e);document.addEventListener(e,this.globalListener,t)}}update(e,t){if(this.infosByEventHandlerId.hasOwnProperty(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=u(t.eventName);0==--this.countByEventName[n]&&(delete this.countByEventName[n],document.removeEventListener(n,this.globalListener))}return t}handleEventNameAliasAdded(e,t){if(this.countByEventName.hasOwnProperty(e)){const n=this.countByEventName[e];delete this.countByEventName[e],document.removeEventListener(e,this.globalListener),this.addGlobalListener(t),this.countByEventName[t]+=n-1}}}class _{constructor(){this.handlers={},this.preventDefaultFlags=null,this.stopPropagationFlags=null}getHandler(e){return this.handlers.hasOwnProperty(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 E(e){const t={};return e.forEach((e=>{t[e]=!0})),t}const S=H("_blazorLogicalChildren"),C=H("_blazorLogicalParent"),I=H("_blazorLogicalEnd");function k(e,t){if(e.childNodes.length>0&&!t)throw new Error("New logical elements must start empty, or allowExistingContents must be true");return S in e||(e[S]=[]),e}function T(e,t){const n=document.createComment("!");return D(n,e,t),n}function D(e,t,n){const r=e;if(e instanceof Comment&&A(r)&&A(r).length>0)throw new Error("Not implemented: inserting non-empty logical container");if(R(r))throw new Error("Not implemented: moving existing logical children");const o=A(t);if(n0;)x(n,0)}const r=n;r.parentNode.removeChild(r)}function R(e){return e[C]||null}function P(e,t){return A(e)[t]}function U(e){var t=B(e);return"http://www.w3.org/2000/svg"===t.namespaceURI&&"foreignObject"!==t.tagName}function A(e){return e[S]}function N(e,t){const n=A(e);t.forEach((e=>{e.moveRangeStart=n[e.fromSiblingIndex],e.moveRangeEnd=M(e.moveRangeStart)})),t.forEach((t=>{const r=t.moveToBeforeMarker=document.createComment("marker"),o=n[t.toSiblingIndex+1];o?o.parentNode.insertBefore(r,o):L(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 B(e){if(e instanceof Element)return e;if(e instanceof Comment)return e.parentNode;throw new Error("Not a valid logical element")}function $(e){const t=A(R(e));return t[Array.prototype.indexOf.call(t,e)+1]||null}function L(e,t){if(t instanceof Element)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=$(t);n?n.parentNode.insertBefore(e,n):L(e,R(t))}}}function M(e){if(e instanceof Element)return e;const t=$(e);if(t)return t.previousSibling;{const t=R(e);return t instanceof Element?t.lastChild:M(t)}}function H(e){return"function"==typeof Symbol?Symbol():e}function O(e){return`_bl_${e}`}e.attachReviver(((e,t)=>t&&"object"==typeof t&&t.hasOwnProperty("__internalId")&&"string"==typeof t.__internalId?function(e){const t=`[${O(e)}]`;return document.querySelector(t)}(t.__internalId):t));const F="_blazorSelectValue",j=document.createElement("template"),W=document.createElementNS("http://www.w3.org/2000/svg","g"),z={},q="__internal_",J="preventDefault_",K="stopPropagation_";class V{constructor(e){this.childComponentLocations={},this.eventDelegator=new v(e),this.eventDelegator.notifyAfterClick((e=>{if(!ee)return;if(0!==e.button||function(e){return e.ctrlKey||e.shiftKey||e.altKey||e.metaKey}(e))return;if(e.defaultPrevented)return;const t=function(e){const t=!window._blazorDisableComposedPath&&e.composedPath&&e.composedPath();if(t){for(let e=0;ese(!1))))},enableNavigationInterception:function(){ee=!0},navigateTo:oe,getBaseURI:()=>document.baseURI,getLocationHref:()=>location.href};function oe(e,t,n=!1){const r=ce(e);if(!t&&he(r))ie(r,!1,n);else if(t&&location.href===e){const t=e+"?";history.replaceState(null,"",t),location.replace(e)}else n?history.replaceState(null,"",r):location.href=e}function ie(e,t,n=!1){Z=!0,n?history.replaceState(null,"",e):history.pushState(null,"",e),se(t)}async function se(e){ne&&await ne(location.href,e)}let ae;function ce(e){return ae=ae||document.createElement("a"),ae.href=e,ae.href}function le(e,t){return e?e.tagName===t?e:le(e.parentElement,t):null}function he(e){const t=(n=document.baseURI).substr(0,n.lastIndexOf("/")+1);var n;return e.startsWith(t)}const ue={init:function(e,t,n,r=50){const o=pe(t);(o||document.documentElement).style.overflowAnchor="none";const i=new IntersectionObserver((function(r){r.forEach((r=>{var o;if(!r.isIntersecting)return;const i=t.getBoundingClientRect(),s=n.getBoundingClientRect().top-i.bottom,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`});i.observe(t),i.observe(n);const s=c(t),a=c(n);function c(e){const t=new MutationObserver((()=>{i.unobserve(e),i.observe(e)}));return t.observe(e,{attributes:!0}),t}de[e._id]={intersectionObserver:i,mutationObserverBefore:s,mutationObserverAfter:a}},dispose:function(e){const t=de[e._id];t&&(t.intersectionObserver.disconnect(),t.mutationObserverBefore.disconnect(),t.mutationObserverAfter.disconnect(),e.dispose(),delete de[e._id])}},de={};function pe(e){return e?"visible"!==getComputedStyle(e).overflowY?e:pe(e.parentElement):null}const fe={navigateTo:oe,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=a.get(t.browserEventName);n?n.push(e):a.set(t.browserEventName,[e]),l.forEach((n=>n(e,t.browserEventName)))}s.set(e,t)},_internal:{navigationManager:re,domWrapper:{focus:function(e,t){if(!(e instanceof HTMLElement))throw new Error("Unable to focus an invalid element.");e.focus({preventScroll:t})}},Virtualize:ue}};window.Blazor=fe;const ge=[0,2e3,1e4,3e4,null];class me{constructor(e){this._retryDelays=void 0!==e?[...e,null]:ge}nextRetryDelayInMilliseconds(e){return this._retryDelays[e.previousRetryCount]}}class ye extends Error{constructor(e,t){const n=new.target.prototype;super(`${e}: Status code '${t}'`),this.statusCode=t,this.__proto__=n}}class we extends Error{constructor(e="A timeout occurred."){const t=new.target.prototype;super(e),this.__proto__=t}}class ve extends Error{constructor(e="An abort occurred."){const t=new.target.prototype;super(e),this.__proto__=t}}class be{constructor(e,t,n){this.statusCode=e,this.statusText=t,this.content=n}}class _e{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""}}var Ee,Se,Ce,Ie,ke;!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"}(Ee||(Ee={}));class Te extends _e{constructor(e){if(super(),this._logger=e,"undefined"==typeof fetch){const e=require;this._jar=new(e("tough-cookie").CookieJar),this._fetchType=e("node-fetch"),this._fetchType=e("fetch-cookie")(this._fetchType,this._jar),this._abortControllerType=e("abort-controller")}else this._fetchType=fetch.bind(self),this._abortControllerType=AbortController}async send(e){if(e.abortSignal&&e.abortSignal.aborted)throw new ve;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 ve});let r,o=null;if(e.timeout){const r=e.timeout;o=setTimeout((()=>{t.abort(),this._logger.log(Ee.Warning,"Timeout from HTTP request."),n=new we}),r)}try{r=await this._fetchType(e.url,{body:e.content,cache:"no-cache",credentials:!0===e.withCredentials?"include":"same-origin",headers:{"Content-Type":"text/plain;charset=UTF-8","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(Ee.Warning,`Error from HTTP request. ${e}.`),e}finally{o&&clearTimeout(o),e.abortSignal&&(e.abortSignal.onabort=null)}if(!r.ok){const e=await De(r,"text");throw new ye(e||r.statusText,r.status)}const i=De(r,e.responseType),s=await i;return new be(r.status,r.statusText,s)}getCookieString(e){return""}}function De(e,t){let n;switch(t){case"arraybuffer":n=e.arrayBuffer();break;case"text":n=e.text();break;case"blob":case"document":case"json":throw new Error(`${t} is not supported.`);default:n=e.text()}return n}class xe extends _e{constructor(e){super(),this._logger=e}send(e){return e.abortSignal&&e.abortSignal.aborted?Promise.reject(new ve):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"),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 ve)}),e.timeout&&(r.timeout=e.timeout),r.onload=()=>{e.abortSignal&&(e.abortSignal.onabort=null),r.status>=200&&r.status<300?t(new be(r.status,r.statusText,r.response||r.responseText)):n(new ye(r.response||r.responseText||r.statusText,r.status))},r.onerror=()=>{this._logger.log(Ee.Warning,`Error from HTTP request. ${r.status}: ${r.statusText}.`),n(new ye(r.statusText,r.status))},r.ontimeout=()=>{this._logger.log(Ee.Warning,"Timeout from HTTP request."),n(new we)},r.send(e.content||"")})):Promise.reject(new Error("No url defined.")):Promise.reject(new Error("No method defined."))}}class Re extends _e{constructor(e){if(super(),"undefined"!=typeof fetch)this._httpClient=new Te(e);else{if("undefined"==typeof XMLHttpRequest)throw new Error("No usable HttpClient found.");this._httpClient=new xe(e)}}send(e){return e.abortSignal&&e.abortSignal.aborted?Promise.reject(new ve):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)}}class Pe{}Pe.Authorization="Authorization",Pe.Cookie="Cookie",function(e){e[e.None=0]="None",e[e.WebSockets=1]="WebSockets",e[e.ServerSentEvents=2]="ServerSentEvents",e[e.LongPolling=4]="LongPolling"}(Se||(Se={})),function(e){e[e.Text=1]="Text",e[e.Binary=2]="Binary"}(Ce||(Ce={}));class Ue{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 Ae{constructor(){}log(e,t){}}Ae.instance=new Ae;class Ne{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 Be{static get isBrowser(){return"object"==typeof window}static get isWebWorker(){return"object"==typeof self&&"importScripts"in self}static get isNode(){return!this.isBrowser&&!this.isWebWorker}}function $e(e,t){let n="";return Le(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 Le(e){return e&&"undefined"!=typeof ArrayBuffer&&(e instanceof ArrayBuffer||e.constructor&&"ArrayBuffer"===e.constructor.name)}async function Me(e,t,n,r,o,i,s,a,c){let l={};if(o){const e=await o();e&&(l={Authorization:`Bearer ${e}`})}const[h,u]=Fe();l[h]=u,e.log(Ee.Trace,`(${t} transport) sending data. ${$e(i,s)}.`);const d=Le(i)?"arraybuffer":"text",p=await n.post(r,{content:i,headers:{...l,...c},responseType:d,withCredentials:a});e.log(Ee.Trace,`(${t} transport) request complete. Response status: ${p.statusCode}.`)}class He{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 Oe{constructor(e){this._minLevel=e,this.out=console}log(e,t){if(e>=this._minLevel){const n=`[${(new Date).toISOString()}] ${Ee[e]}: ${t}`;switch(e){case Ee.Critical:case Ee.Error:this.out.error(n);break;case Ee.Warning:this.out.warn(n);break;case Ee.Information:this.out.info(n);break;default:this.out.log(n)}}}}function Fe(){let e="X-SignalR-User-Agent";return Be.isNode&&(e="User-Agent"),[e,je("0.0.0-DEV_BUILD",We(),Be.isNode?"NodeJS":"Browser",ze())]}function je(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 We(){if(!Be.isNode)return"";switch(process.platform){case"win32":return"Windows NT";case"darwin":return"macOS";case"linux":return"Linux";default:return process.platform}}function ze(){if(Be.isNode)return process.versions.node}class qe{constructor(e,t,n,r,o,i){this._httpClient=e,this._accessTokenFactory=t,this._logger=n,this._pollAbort=new Ue,this._logMessageContent=r,this._withCredentials=o,this._headers=i,this._running=!1,this.onreceive=null,this.onclose=null}get pollAborted(){return this._pollAbort.aborted}async connect(e,t){if(Ne.isRequired(e,"url"),Ne.isRequired(t,"transferFormat"),Ne.isIn(t,Ce,"transferFormat"),this._url=e,this._logger.log(Ee.Trace,"(LongPolling transport) Connecting."),t===Ce.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]=Fe(),o={[n]:r,...this._headers},i={abortSignal:this._pollAbort.signal,headers:o,timeout:1e5,withCredentials:this._withCredentials};t===Ce.Binary&&(i.responseType="arraybuffer");const s=await this._getAccessToken();this._updateHeaderToken(i,s);const a=`${e}&_=${Date.now()}`;this._logger.log(Ee.Trace,`(LongPolling transport) polling: ${a}.`);const c=await this._httpClient.get(a,i);200!==c.statusCode?(this._logger.log(Ee.Error,`(LongPolling transport) Unexpected response code: ${c.statusCode}.`),this._closeError=new ye(c.statusText||"",c.statusCode),this._running=!1):this._running=!0,this._receiving=this._poll(this._url,i)}async _getAccessToken(){return this._accessTokenFactory?await this._accessTokenFactory():null}_updateHeaderToken(e,t){e.headers||(e.headers={}),t?e.headers[Pe.Authorization]=`Bearer ${t}`:e.headers[Pe.Authorization]&&delete e.headers[Pe.Authorization]}async _poll(e,t){try{for(;this._running;){const n=await this._getAccessToken();this._updateHeaderToken(t,n);try{const n=`${e}&_=${Date.now()}`;this._logger.log(Ee.Trace,`(LongPolling transport) polling: ${n}.`);const r=await this._httpClient.get(n,t);204===r.statusCode?(this._logger.log(Ee.Information,"(LongPolling transport) Poll terminated by server."),this._running=!1):200!==r.statusCode?(this._logger.log(Ee.Error,`(LongPolling transport) Unexpected response code: ${r.statusCode}.`),this._closeError=new ye(r.statusText||"",r.statusCode),this._running=!1):r.content?(this._logger.log(Ee.Trace,`(LongPolling transport) data received. ${$e(r.content,this._logMessageContent)}.`),this.onreceive&&this.onreceive(r.content)):this._logger.log(Ee.Trace,"(LongPolling transport) Poll timed out, reissuing.")}catch(e){this._running?e instanceof we?this._logger.log(Ee.Trace,"(LongPolling transport) Poll timed out, reissuing."):(this._closeError=e,this._running=!1):this._logger.log(Ee.Trace,`(LongPolling transport) Poll errored after shutdown: ${e.message}`)}}}finally{this._logger.log(Ee.Trace,"(LongPolling transport) Polling complete."),this.pollAborted||this._raiseOnClose()}}async send(e){return this._running?Me(this._logger,"LongPolling",this._httpClient,this._url,this._accessTokenFactory,e,this._logMessageContent,this._withCredentials,this._headers):Promise.reject(new Error("Cannot send until the transport is connected"))}async stop(){this._logger.log(Ee.Trace,"(LongPolling transport) Stopping polling."),this._running=!1,this._pollAbort.abort();try{await this._receiving,this._logger.log(Ee.Trace,`(LongPolling transport) sending DELETE request to ${this._url}.`);const e={},[t,n]=Fe();e[t]=n;const r={headers:{...e,...this._headers},withCredentials:this._withCredentials},o=await this._getAccessToken();this._updateHeaderToken(r,o),await this._httpClient.delete(this._url,r),this._logger.log(Ee.Trace,"(LongPolling transport) DELETE request sent.")}finally{this._logger.log(Ee.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(Ee.Trace,e),this.onclose(this._closeError)}}}class Je{constructor(e,t,n,r,o,i,s){this._httpClient=e,this._accessTokenFactory=t,this._logger=n,this._logMessageContent=r,this._withCredentials=i,this._eventSourceConstructor=o,this._headers=s,this.onreceive=null,this.onclose=null}async connect(e,t){if(Ne.isRequired(e,"url"),Ne.isRequired(t,"transferFormat"),Ne.isIn(t,Ce,"transferFormat"),this._logger.log(Ee.Trace,"(SSE transport) Connecting."),this._url=e,this._accessTokenFactory){const t=await this._accessTokenFactory();t&&(e+=(e.indexOf("?")<0?"?":"&")+`access_token=${encodeURIComponent(t)}`)}return new Promise(((n,r)=>{let o,i=!1;if(t===Ce.Text){if(Be.isBrowser||Be.isWebWorker)o=new this._eventSourceConstructor(e,{withCredentials:this._withCredentials});else{const t=this._httpClient.getCookieString(e),n={};n.Cookie=t;const[r,i]=Fe();n[r]=i,o=new this._eventSourceConstructor(e,{withCredentials:this._withCredentials,headers:{...n,...this._headers}})}try{o.onmessage=e=>{if(this.onreceive)try{this._logger.log(Ee.Trace,`(SSE transport) data received. ${$e(e.data,this._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(Ee.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?Me(this._logger,"SSE",this._httpClient,this._url,this._accessTokenFactory,e,this._logMessageContent,this._withCredentials,this._headers):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 Ke{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){if(Ne.isRequired(e,"url"),Ne.isRequired(t,"transferFormat"),Ne.isIn(t,Ce,"transferFormat"),this._logger.log(Ee.Trace,"(WebSockets transport) Connecting."),this._accessTokenFactory){const t=await this._accessTokenFactory();t&&(e+=(e.indexOf("?")<0?"?":"&")+`access_token=${encodeURIComponent(t)}`)}return new Promise(((n,r)=>{let o;e=e.replace(/^http/,"ws"),this._httpClient.getCookieString(e);let i=!1;o||(o=new this._webSocketConstructor(e)),t===Ce.Binary&&(o.binaryType="arraybuffer"),o.onopen=t=>{this._logger.log(Ee.Information,`WebSocket connected to ${e}.`),this._webSocket=o,i=!0,n()},o.onerror=e=>{let t=null;t="undefined"!=typeof ErrorEvent&&e instanceof ErrorEvent?e.error:"There was an error with the transport",this._logger.log(Ee.Information,`(WebSockets transport) ${t}.`)},o.onmessage=e=>{if(this._logger.log(Ee.Trace,`(WebSockets transport) data received. ${$e(e.data,this._logMessageContent)}.`),this.onreceive)try{this.onreceive(e.data)}catch(e){return void this._close(e)}},o.onclose=e=>{if(i)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(Ee.Trace,`(WebSockets transport) sending data. ${$e(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(Ee.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 Ve{constructor(e,t={}){var n;if(this._stopPromiseResolver=()=>{},this.features={},this._negotiateVersion=1,Ne.isRequired(e,"url"),this._logger=void 0===(n=t.logger)?new Oe(Ee.Information):null===n?Ae.instance:void 0!==n.log?n:new Oe(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,"undefined"==typeof WebSocket||t.WebSocket||(t.WebSocket=WebSocket),"undefined"==typeof EventSource||t.EventSource||(t.EventSource=EventSource),this._httpClient=t.httpClient||new Re(this._logger),this._connectionState="Disconnected",this._connectionStarted=!1,this._options=t,this.onreceive=null,this.onclose=null}async start(e){if(e=e||Ce.Binary,Ne.isIn(e,Ce,"transferFormat"),this._logger.log(Ee.Debug,`Starting connection with transfer format '${Ce[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(Ee.Error,e),await this._stopPromise,Promise.reject(new Error(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(Ee.Error,e),Promise.reject(new Error(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 Xe(this.transport)),this._sendQueue.send(e))}async stop(e){return"Disconnected"===this._connectionState?(this._logger.log(Ee.Debug,`Call to HttpConnection.stop(${e}) ignored because the connection is already in the disconnected state.`),Promise.resolve()):"Disconnecting"===this._connectionState?(this._logger.log(Ee.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(Ee.Error,`HttpConnection.transport.stop() threw error '${e}'.`),this._stopConnection()}this.transport=void 0}else this._logger.log(Ee.Debug,"HttpConnection.transport is undefined in HttpConnection.stop() because start() failed.")}async _startInternal(e){let t=this.baseUrl;this._accessTokenFactory=this._options.accessTokenFactory;try{if(this._options.skipNegotiation){if(this._options.transport!==Se.WebSockets)throw new Error("Negotiation can only be skipped when using the WebSocket transport directly.");this.transport=this._constructTransport(Se.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 Error("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}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 qe&&(this.features.inherentKeepAlive=!0),"Connecting"===this._connectionState&&(this._logger.log(Ee.Debug,"The HttpConnection connected successfully."),this._connectionState="Connected")}catch(e){return this._logger.log(Ee.Error,"Failed to start the connection: "+e),this._connectionState="Disconnected",this.transport=void 0,this._stopPromiseResolver(),Promise.reject(e)}}async _getNegotiationResponse(e){const t={};if(this._accessTokenFactory){const e=await this._accessTokenFactory();e&&(t[Pe.Authorization]=`Bearer ${e}`)}const[n,r]=Fe();t[n]=r;const o=this._resolveNegotiateUrl(e);this._logger.log(Ee.Debug,`Sending negotiation request: ${o}.`);try{const e=await this._httpClient.post(o,{content:"",headers:{...t,...this._options.headers},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 ye&&404===e.statusCode&&(t+=" Either this is not a SignalR endpoint or there is a proxy blocking the connection."),this._logger.log(Ee.Error,t),Promise.reject(new Error(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(Ee.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: ${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(Ee.Error,`Failed to start the transport '${n.transport}': ${e}`),a=void 0,i.push(`${n.transport} failed: ${e}`),"Connecting"!==this._connectionState){const e="Failed to select transport before stop() was called.";return this._logger.log(Ee.Debug,e),Promise.reject(new Error(e))}}}}return i.length>0?Promise.reject(new Error(`Unable to connect to the server with any of the available transports. ${i.join(" ")}`)):Promise.reject(new Error("None of the transports supported by the client are supported by the server."))}_constructTransport(e){switch(e){case Se.WebSockets:if(!this._options.WebSocket)throw new Error("'WebSocket' is not supported in your environment.");return new Ke(this._httpClient,this._accessTokenFactory,this._logger,this._options.logMessageContent||!1,this._options.WebSocket,this._options.headers||{});case Se.ServerSentEvents:if(!this._options.EventSource)throw new Error("'EventSource' is not supported in your environment.");return new Je(this._httpClient,this._accessTokenFactory,this._logger,this._options.logMessageContent||!1,this._options.EventSource,this._options.withCredentials,this._options.headers||{});case Se.LongPolling:return new qe(this._httpClient,this._accessTokenFactory,this._logger,this._options.logMessageContent||!1,this._options.withCredentials,this._options.headers||{});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=Se[e.transport];if(null==r)return this._logger.log(Ee.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(Ee.Debug,`Skipping transport '${Se[r]}' because it was disabled by the client.`),new Error(`'${Se[r]}' is disabled by the client.`);if(!(e.transferFormats.map((e=>Ce[e])).indexOf(n)>=0))return this._logger.log(Ee.Debug,`Skipping transport '${Se[r]}' because it does not support the requested transfer format '${Ce[n]}'.`),new Error(`'${Se[r]}' does not support ${Ce[n]}.`);if(r===Se.WebSockets&&!this._options.WebSocket||r===Se.ServerSentEvents&&!this._options.EventSource)return this._logger.log(Ee.Debug,`Skipping transport '${Se[r]}' because it is not supported in your environment.'`),new Error(`'${Se[r]}' is not supported in your environment.`);this._logger.log(Ee.Debug,`Selecting transport '${Se[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(Ee.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(Ee.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(Ee.Error,`Connection disconnected with error '${e}'.`):this._logger.log(Ee.Information,"Connection disconnected."),this._sendQueue&&(this._sendQueue.stop().catch((e=>{this._logger.log(Ee.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(Ee.Error,`HttpConnection.onclose(${e}) threw error '${t}'.`)}}}else this._logger.log(Ee.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(!Be.isBrowser||!window.document)throw new Error(`Cannot resolve '${e}'.`);const t=window.document.createElement("a");return t.href=e,this._logger.log(Ee.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 Xe{constructor(e){this._transport=e,this._buffer=[],this._executing=!0,this._sendBufferedData=new Ye,this._transportResult=new Ye,this._sendLoopPromise=this._sendLoop()}send(e){return this._bufferData(e),this._transportResult||(this._transportResult=new Ye),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 Ye;const e=this._transportResult;this._transportResult=void 0;const t="string"==typeof this._buffer[0]?this._buffer.join(""):Xe._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 Ye{constructor(){this.promise=new Promise(((e,t)=>[this._resolver,this._rejecter]=[e,t]))}resolve(){this._resolver()}reject(e){this._rejecter(e)}}class Ge{static write(e){return`${e}${Ge.RecordSeparator}`}static parse(e){if(e[e.length-1]!==Ge.RecordSeparator)throw new Error("Message is incomplete.");const t=e.split(Ge.RecordSeparator);return t.pop(),t}}Ge.RecordSeparatorCode=30,Ge.RecordSeparator=String.fromCharCode(Ge.RecordSeparatorCode);class Qe{writeHandshakeRequest(e){return Ge.write(JSON.stringify(e))}parseHandshakeResponse(e){let t,n;if(Le(e)){const r=new Uint8Array(e),o=r.indexOf(Ge.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(Ge.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=Ge.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"}(Ie||(Ie={}));class Ze{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 He(this,e)}}!function(e){e.Disconnected="Disconnected",e.Connecting="Connecting",e.Connected="Connected",e.Disconnecting="Disconnecting",e.Reconnecting="Reconnecting"}(ke||(ke={}));class et{constructor(e,t,n,r){this._nextKeepAlive=0,Ne.isRequired(e,"connection"),Ne.isRequired(t,"logger"),Ne.isRequired(n,"protocol"),this.serverTimeoutInMilliseconds=3e4,this.keepAliveIntervalInMilliseconds=15e3,this._logger=t,this._protocol=n,this.connection=e,this._reconnectPolicy=r,this._handshakeProtocol=new Qe,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=ke.Disconnected,this._connectionStarted=!1,this._cachedPingMessage=this._protocol.writeMessage({type:Ie.Ping})}static create(e,t,n,r){return new et(e,t,n,r)}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!==ke.Disconnected&&this._connectionState!==ke.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!==ke.Disconnected)return Promise.reject(new Error("Cannot start a HubConnection that is not in the 'Disconnected' state."));this._connectionState=ke.Connecting,this._logger.log(Ee.Debug,"Starting HubConnection.");try{await this._startInternal(),this._connectionState=ke.Connected,this._connectionStarted=!0,this._logger.log(Ee.Debug,"HubConnection connected successfully.")}catch(e){return this._connectionState=ke.Disconnected,this._logger.log(Ee.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(Ee.Debug,"Sending handshake request."),await this._sendMessage(this._handshakeProtocol.writeHandshakeRequest(t)),this._logger.log(Ee.Information,`Using HubProtocol '${this._protocol.name}'.`),this._cleanupTimeout(),this._resetTimeoutPeriod(),this._resetKeepAliveInterval(),await e,this._stopDuringStartError)throw this._stopDuringStartError}catch(e){throw this._logger.log(Ee.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){return this._connectionState===ke.Disconnected?(this._logger.log(Ee.Debug,`Call to HubConnection.stop(${e}) ignored because it is already in the disconnected state.`),Promise.resolve()):this._connectionState===ke.Disconnecting?(this._logger.log(Ee.Debug,`Call to HttpConnection.stop(${e}) ignored because the connection is already in the disconnecting state.`),this._stopPromise):(this._connectionState=ke.Disconnecting,this._logger.log(Ee.Debug,"Stopping HubConnection."),this._reconnectDelayHandle?(this._logger.log(Ee.Debug,"Connection stopped during reconnect delay. Done reconnecting."),clearTimeout(this._reconnectDelayHandle),this._reconnectDelayHandle=void 0,this._completeClose(),Promise.resolve()):(this._cleanupTimeout(),this._cleanupPingTimer(),this._stopDuringStartError=e||new Error("The connection was stopped before the hub handshake could complete."),this.connection.stop(e)))}stream(e,...t){const[n,r]=this._replaceStreamingParams(t),o=this._createStreamInvocation(e,t,r);let i;const s=new Ze;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===Ie.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===Ie.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 Ie.Invocation:this._invokeClientMethod(e);break;case Ie.StreamItem:case Ie.Completion:{const t=this._callbacks[e.invocationId];t&&(e.type===Ie.Completion&&delete this._callbacks[e.invocationId],t(e));break}case Ie.Ping:break;case Ie.Close:{this._logger.log(Ee.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(Ee.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(Ee.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(Ee.Error,e);const n=new Error(e);throw this._handshakeRejecter(n),n}return this._logger.log(Ee.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===ke.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."))}_invokeClientMethod(e){const t=this._methods[e.target.toLowerCase()];if(t){try{t.forEach((t=>t.apply(this,e.arguments)))}catch(t){this._logger.log(Ee.Error,`A callback for the method ${e.target.toLowerCase()} threw error '${t}'.`)}if(e.invocationId){const e="Server requested a response, which is not supported in this version of the client.";this._logger.log(Ee.Error,e),this._stopPromise=this._stopInternal(new Error(e))}}else this._logger.log(Ee.Warning,`No client method with the name '${e.target}' found.`)}_connectionClosed(e){this._logger.log(Ee.Debug,`HubConnection.connectionClosed(${e}) called while in state ${this._connectionState}.`),this._stopDuringStartError=this._stopDuringStartError||e||new Error("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===ke.Disconnecting?this._completeClose(e):this._connectionState===ke.Connected&&this._reconnectPolicy?this._reconnect(e):this._connectionState===ke.Connected&&this._completeClose(e)}_completeClose(e){if(this._connectionStarted){this._connectionState=ke.Disconnected,this._connectionStarted=!1;try{this._closedCallbacks.forEach((t=>t.apply(this,[e])))}catch(t){this._logger.log(Ee.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(Ee.Debug,"Connection not reconnecting because the IRetryPolicy returned null on the first reconnect attempt."),void this._completeClose(e);if(this._connectionState=ke.Reconnecting,e?this._logger.log(Ee.Information,`Connection reconnecting because of error '${e}'.`):this._logger.log(Ee.Information,"Connection reconnecting."),0!==this._reconnectingCallbacks.length){try{this._reconnectingCallbacks.forEach((t=>t.apply(this,[e])))}catch(t){this._logger.log(Ee.Error,`An onreconnecting callback called with error '${e}' threw error '${t}'.`)}if(this._connectionState!==ke.Reconnecting)return void this._logger.log(Ee.Debug,"Connection left the reconnecting state in onreconnecting callback. Done reconnecting.")}for(;null!==o;){if(this._logger.log(Ee.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!==ke.Reconnecting)return void this._logger.log(Ee.Debug,"Connection left the reconnecting state during reconnect delay. Done reconnecting.");try{if(await this._startInternal(),this._connectionState=ke.Connected,this._logger.log(Ee.Information,"HubConnection reconnected successfully."),0!==this._reconnectedCallbacks.length)try{this._reconnectedCallbacks.forEach((e=>e.apply(this,[this.connection.connectionId])))}catch(e){this._logger.log(Ee.Error,`An onreconnected callback called with connectionId '${this.connection.connectionId}; threw error '${e}'.`)}return}catch(e){if(this._logger.log(Ee.Information,`Reconnect attempt failed because of error '${e}'.`),this._connectionState!==ke.Reconnecting)return this._logger.log(Ee.Debug,`Connection moved to the '${this._connectionState}' from the reconnecting state during reconnect attempt. Done reconnecting.`),void(this._connectionState===ke.Disconnecting&&this._completeClose());r=e instanceof Error?e:new Error(e.toString()),o=this._getNextRetryDelay(n++,Date.now()-t,r)}}this._logger.log(Ee.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(Ee.Error,`IRetryPolicy.nextRetryDelayInMilliseconds(${e}, ${t}) threw error '${n}'.`),null}}_cancelCallbacksWithError(e){const t=this._callbacks;this._callbacks={},Object.keys(t).forEach((n=>{(0,t[n])(null,e)}))}_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:Ie.Invocation}:{arguments:t,target:e,type:Ie.Invocation};{const n=this._invocationId;return this._invocationId++,0!==r.length?{arguments:t,invocationId:n.toString(),streamIds:r,target:e,type:Ie.Invocation}:{arguments:t,invocationId:n.toString(),target:e,type:Ie.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 ut=ot?new TextDecoder:null,dt=ot?"undefined"!=typeof process&&"force"!==process.env.TEXT_DECODER?200:0:it,pt=function(e,t){this.type=e,this.data=t};function ft(e,t,n){var r=Math.floor(n/4294967296),o=n;e.setUint32(t,r),e.setUint32(t+4,o)}function gt(e,t){return 4294967296*e.getInt32(t)+e.getUint32(t+4)}var mt={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),ft(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:gt(t,4),nsec:t.getUint32(0)};default:throw new Error("Unrecognized data size for timestamp: "+e.length)}}(e);return new Date(1e3*t.sec+t.nsec/1e6)}},yt=function(){function e(){this.builtInEncoders=[],this.builtInDecoders=[],this.encoders=[],this.decoders=[],this.register(mt)}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 "+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: "+e+" bytes in UTF-8");this.writeU8(219),this.writeU32(e)}},e.prototype.encodeString=function(e){if(e.length>ct){var t=st(e);this.ensureBufferSizeToWrite(5+t),this.writeStringHeader(t),lt(e,this.bytes,this.pos),this.pos+=t}else t=st(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: "+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: "+t);this.writeU8(198),this.writeU32(t)}var n=wt(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: "+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=ht(e,t,n),i=Uint8Array.prototype.slice.call(e,t,t+n);return this.store(i,o),o},e}(),St=(_t=function(e,t){return(_t=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])})(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}_t(e,t),e.prototype=null===t?Object.create(t):(n.prototype=t.prototype,new n)}),Ct=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]1||a(e,t)}))})}function a(e,t){try{(n=o[e](t)).value instanceof kt?Promise.resolve(n.value.v).then(c,l):h(i[0][2],n)}catch(e){h(i[0][3],e)}var n}function c(e){a("next",e)}function l(e){a("throw",e)}function h(e,t){e(t),i.shift(),i.length&&a(i[0][0],i[0][1])}},Dt=new DataView(new ArrayBuffer(0)),xt=new Uint8Array(Dt.buffer),Rt=function(){try{Dt.getInt8(0)}catch(e){return e.constructor}throw new Error("never reached")}(),Pt=new Rt("Insufficient data"),Ut=4294967295,At=new Et,Nt=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 St(t,e),t}(Error),Bt=function(){function e(e,t,n,r,o,i,s,a){void 0===e&&(e=yt.defaultCodec),void 0===t&&(t=void 0),void 0===n&&(n=Ut),void 0===r&&(r=Ut),void 0===o&&(o=Ut),void 0===i&&(i=Ut),void 0===s&&(s=Ut),void 0===a&&(a=At),this.extensionCodec=e,this.context=t,this.maxStrLength=n,this.maxBinLength=r,this.maxArrayLength=o,this.maxMapLength=i,this.maxExtLength=s,this.keyDecoder=a,this.totalPos=0,this.pos=0,this.view=Dt,this.bytes=xt,this.headByte=-1,this.stack=[]}return e.prototype.reinitializeState=function(){this.totalPos=0,this.headByte=-1,this.stack.length=0},e.prototype.setBuffer=function(e){this.bytes=wt(e),this.view=function(e){if(e instanceof ArrayBuffer)return new DataView(e);var t=wt(e);return new DataView(t.buffer,t.byteOffset,t.byteLength)}(this.bytes),this.pos=0},e.prototype.appendBuffer=function(e){if(-1!==this.headByte||this.hasRemaining()){var t=this.bytes.subarray(this.pos),n=wt(e),r=new Uint8Array(t.length+n.length);r.set(t),r.set(n,t.length),this.setBuffer(r)}else this.setBuffer(e)},e.prototype.hasRemaining=function(e){return void 0===e&&(e=1),this.view.byteLength-this.pos>=e},e.prototype.createExtraByteError=function(e){var t=this.view,n=this.pos;return new RangeError("Extra "+(t.byteLength-n)+" of "+t.byteLength+" byte(s) found at buffer["+e+"]")},e.prototype.decode=function(e){this.reinitializeState(),this.setBuffer(e);var t=this.doDecodeSync();if(this.hasRemaining())throw this.createExtraByteError(this.pos);return t},e.prototype.decodeMulti=function(e){return Ct(this,(function(t){switch(t.label){case 0:this.reinitializeState(),this.setBuffer(e),t.label=1;case 1:return this.hasRemaining()?[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,u,d;return Ct(this,(function(p){switch(p.label){case 0:i=!1,p.label=1;case 1:p.trys.push([1,6,7,12]),t=It(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 Rt))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())throw this.createExtraByteError(this.totalPos);return[2,s]}throw h=(l=this).headByte,u=l.pos,d=l.totalPos,new RangeError("Insufficient data in parsing "+bt(h)+" at "+d+" ("+u+" 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 Tt(this,arguments,(function(){var n,r,o,i,s,a,c,l,h;return Ct(this,(function(u){switch(u.label){case 0:n=t,r=-1,u.label=1;case 1:u.trys.push([1,13,14,19]),o=It(e),u.label=2;case 2:return[4,kt(o.next())];case 3:if((i=u.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()),u.label=4;case 4:u.trys.push([4,9,,10]),u.label=5;case 5:return[4,kt(this.doDecodeSync())];case 6:return[4,u.sent()];case 7:return u.sent(),0==--r?[3,8]:[3,5];case 8:return[3,10];case 9:if(!((a=u.sent())instanceof Rt))throw a;return[3,10];case 10:this.totalPos+=this.pos,u.label=11;case 11:return[3,2];case 12:return[3,19];case 13:return c=u.sent(),l={error:c},[3,19];case 14:return u.trys.push([14,,17,18]),i&&!i.done&&(h=o.return)?[4,kt(h.call(o))]:[3,16];case 15:u.sent(),u.label=16;case 16:return[3,18];case 17:if(l)throw l.error;return[7];case 18:return[7];case 19:return[2]}}))}))},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 Nt("Unrecognized type byte: "+bt(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 Nt("The type of key must be string or number but "+typeof t);if("__proto__"===t)throw new Nt("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 Nt("Unrecognized array type byte: "+bt(e))}},e.prototype.pushMapState=function(e){if(e>this.maxMapLength)throw new Nt("Max length exceeded: map length ("+e+") > maxMapLengthLength ("+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 Nt("Max length exceeded: array length ("+e+") > maxArrayLength ("+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 Nt("Max length exceeded: UTF-8 byte length ("+e+") > maxStrLength ("+this.maxStrLength+")");if(this.bytes.byteLengthdt?function(e,t,n){var r=e.subarray(t,t+n);return ut.decode(r)}(this.bytes,o,e):ht(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 Nt("Max length exceeded: bin length ("+e+") > maxBinLength ("+this.maxBinLength+")");if(!this.hasRemaining(e+t))throw Pt;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 Nt("Max length exceeded: ext length ("+e+") > maxExtLength ("+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=gt(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 $t{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 Lt=new Uint8Array([145,Ie.Ping]);class Mt{constructor(e){this.name="messagepack",this.version=1,this.transferFormat=Ce.Binary,this._errorResult=1,this._voidResult=2,this._nonVoidResult=3,e=e||{},this._encoder=new vt(e.extensionCodec,e.context,e.maxDepth,e.initialBufferSize,e.sortKeys,e.forceFloat32,e.ignoreUndefined,e.forceIntegerToFloat),this._decoder=new Bt(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=Ae.instance);const r=$t.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 Ie.Invocation:return this._writeInvocation(e);case Ie.StreamInvocation:return this._writeStreamInvocation(e);case Ie.StreamItem:return this._writeStreamItem(e);case Ie.Completion:return this._writeCompletion(e);case Ie.Ping:return $t.write(Lt);case Ie.CancelInvocation:return this._writeCancelInvocation(e);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 Ie.Invocation:return this._createInvocationMessage(this._readHeaders(n),n);case Ie.StreamItem:return this._createStreamItemMessage(this._readHeaders(n),n);case Ie.Completion:return this._createCompletionMessage(this._readHeaders(n),n);case Ie.Ping:return this._createPingMessage(n);case Ie.Close:return this._createCloseMessage(n);default:return t.log(Ee.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:Ie.Close}}_createPingMessage(e){if(e.length<1)throw new Error("Invalid payload for Ping message.");return{type:Ie.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:Ie.Invocation}:{arguments:t[4],headers:e,streamIds:[],target:t[3],type:Ie.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:Ie.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:Ie.Completion}}_writeInvocation(e){let t;return t=e.streamIds?this._encoder.encode([Ie.Invocation,e.headers||{},e.invocationId||null,e.target,e.arguments,e.streamIds]):this._encoder.encode([Ie.Invocation,e.headers||{},e.invocationId||null,e.target,e.arguments]),$t.write(t.slice())}_writeStreamInvocation(e){let t;return t=e.streamIds?this._encoder.encode([Ie.StreamInvocation,e.headers||{},e.invocationId,e.target,e.arguments,e.streamIds]):this._encoder.encode([Ie.StreamInvocation,e.headers||{},e.invocationId,e.target,e.arguments]),$t.write(t.slice())}_writeStreamItem(e){const t=this._encoder.encode([Ie.StreamItem,e.headers||{},e.invocationId,e.item]);return $t.write(t.slice())}_writeCompletion(e){const t=e.error?this._errorResult:e.result?this._nonVoidResult:this._voidResult;let n;switch(t){case this._errorResult:n=this._encoder.encode([Ie.Completion,e.headers||{},e.invocationId,t,e.error]);break;case this._voidResult:n=this._encoder.encode([Ie.Completion,e.headers||{},e.invocationId,t]);break;case this._nonVoidResult:n=this._encoder.encode([Ie.Completion,e.headers||{},e.invocationId,t,e.result])}return $t.write(n.slice())}_writeCancelInvocation(e){const t=this._encoder.encode([Ie.CancelInvocation,e.headers||{},e.invocationId]);return $t.write(t.slice())}_readHeaders(e){const t=e[1];if("object"!=typeof t)throw new Error("Invalid headers.");return t}}let Ht=!1;const Ot="function"==typeof TextDecoder?new TextDecoder("utf-8"):null,Ft=Ot?Ot.decode.bind(Ot):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("")},jt=Math.pow(2,32),Wt=Math.pow(2,21)-1;function zt(e,t){return e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24}function qt(e,t){return e[t]+(e[t+1]<<8)+(e[t+2]<<16)+(e[t+3]<<24>>>0)}function Jt(e,t){const n=qt(e,t+4);if(n>Wt)throw new Error(`Cannot read uint64 with high order part ${n}, because the result would exceed Number.MAX_SAFE_INTEGER.`);return n*jt+qt(e,t)}class Kt{constructor(e){this.batchData=e;const t=new Gt(e);this.arrayRangeReader=new Qt(e),this.arrayBuilderSegmentReader=new Zt(e),this.diffReader=new Vt(e),this.editReader=new Xt(e,t),this.frameReader=new Yt(e,t)}updatedComponents(){return zt(this.batchData,this.batchData.length-20)}referenceFrames(){return zt(this.batchData,this.batchData.length-16)}disposedComponentIds(){return zt(this.batchData,this.batchData.length-12)}disposedEventHandlerIds(){return zt(this.batchData,this.batchData.length-8)}updatedComponentsEntry(e,t){const n=e+4*t;return zt(this.batchData,n)}referenceFramesEntry(e,t){return e+20*t}disposedComponentIdsEntry(e,t){const n=e+4*t;return zt(this.batchData,n)}disposedEventHandlerIdsEntry(e,t){const n=e+8*t;return Jt(this.batchData,n)}}class Vt{constructor(e){this.batchDataUint8=e}componentId(e){return zt(this.batchDataUint8,e)}edits(e){return e+4}editsEntry(e,t){return e+16*t}}class Xt{constructor(e,t){this.batchDataUint8=e,this.stringReader=t}editType(e){return zt(this.batchDataUint8,e)}siblingIndex(e){return zt(this.batchDataUint8,e+4)}newTreeIndex(e){return zt(this.batchDataUint8,e+8)}moveToSiblingIndex(e){return zt(this.batchDataUint8,e+8)}removedAttributeName(e){const t=zt(this.batchDataUint8,e+12);return this.stringReader.readString(t)}}class Yt{constructor(e,t){this.batchDataUint8=e,this.stringReader=t}frameType(e){return zt(this.batchDataUint8,e)}subtreeLength(e){return zt(this.batchDataUint8,e+4)}elementReferenceCaptureId(e){const t=zt(this.batchDataUint8,e+4);return this.stringReader.readString(t)}componentId(e){return zt(this.batchDataUint8,e+8)}elementName(e){const t=zt(this.batchDataUint8,e+8);return this.stringReader.readString(t)}textContent(e){const t=zt(this.batchDataUint8,e+4);return this.stringReader.readString(t)}markupContent(e){const t=zt(this.batchDataUint8,e+4);return this.stringReader.readString(t)}attributeName(e){const t=zt(this.batchDataUint8,e+4);return this.stringReader.readString(t)}attributeValue(e){const t=zt(this.batchDataUint8,e+8);return this.stringReader.readString(t)}attributeEventHandlerId(e){return Jt(this.batchDataUint8,e+12)}}class Gt{constructor(e){this.batchDataUint8=e,this.stringTableStartIndex=zt(e,e.length-4)}readString(e){if(-1===e)return null;{const n=zt(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(en.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(en.Debug,`Waiting for batch ${this.nextBatchId}. Batch ${e} not processed.`);try{this.nextBatchId++,this.logger.log(en.Debug,`Applying batch ${e}.`),function(e,t){const n=Q[e];if(!n)throw new Error(`There is no browser renderer with ID ${e}.`);const r=t.arrayRangeReader,o=t.updatedComponents(),i=r.values(o),s=r.count(o),a=t.referenceFrames(),c=r.values(a),l=t.diffReader;for(let e=0;e=this.minLevel){const n=`[${(new Date).toISOString()}] ${en[e]}: ${t}`;switch(e){case en.Critical:case en.Error:console.error(n);break;case en.Warning:console.warn(n);break;case en.Information:console.info(n);break;default:console.log(n)}}}}class on{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!==ke.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!==ke.Connected)return!1;const t=await e.invoke("StartCircuit",re.getBaseURI(),re.getLocationHref(),JSON.stringify(this.components.map((e=>e.toRecord()))),this.applicationState||"");return!!t&&(this.initialize(t),!0)}resolveElement(e){const t=Number.parseInt(e);if(Number.isNaN(t))throw new Error(`Invalid sequence number '${e}'.`);return function(e,t){if(!e.parentNode)throw new Error(`Comment not connected to the DOM ${e.textContent}`);const n=e.parentNode,r=k(n,!0),o=A(r);return Array.from(n.childNodes).forEach((e=>o.push(e))),e[C]=r,t&&(e[I]=t,k(t)),k(e)}(this.components[t].start,this.components[t].end)}}const sn={configureSignalR:e=>{},logLevel:en.Warning,reconnectionOptions:{maxRetries:8,retryIntervalMilliseconds:2e4,dialogId:"components-reconnect-modal"}};class an{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.modal.innerHTML='

Alternatively, reload

',this.message=this.modal.querySelector("h5"),this.button=this.modal.querySelector("button"),this.reloadParagraph=this.modal.querySelector("p"),this.loader=this.getLoader(),this.message.after(this.loader),this.button.addEventListener("click",(async()=>{this.show();try{await(null==fe?void 0:fe.reconnect)()||this.rejected()}catch(e){this.logger.log(en.Error,e),this.failed()}})),this.reloadParagraph.querySelector("a").addEventListener("click",(()=>location.reload()))}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",this.message.innerHTML="Reconnection failed. Try reloading the page if you're unable to reconnect.",this.message.querySelector("a").addEventListener("click",(()=>location.reload()))}rejected(){this.button.style.display="none",this.reloadParagraph.style.display="none",this.loader.style.display="none",this.message.innerHTML="Could not reconnect to the server. Reload the page to restore functionality.",this.message.querySelector("a").addEventListener("click",(()=>location.reload()))}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 cn{constructor(e,t,n){this.dialog=e,this.maxRetries=t,this.document=n,this.document=n;const r=this.document.getElementById(cn.MaxRetriesId);r&&(r.innerText=this.maxRetries.toString())}show(){this.removeClasses(),this.dialog.classList.add(cn.ShowClassName)}update(e){const t=this.document.getElementById(cn.CurrentAttemptId);t&&(t.innerText=e.toString())}hide(){this.removeClasses(),this.dialog.classList.add(cn.HideClassName)}failed(){this.removeClasses(),this.dialog.classList.add(cn.FailedClassName)}rejected(){this.removeClasses(),this.dialog.classList.add(cn.RejectedClassName)}removeClasses(){this.dialog.classList.remove(cn.ShowClassName,cn.HideClassName,cn.FailedClassName,cn.RejectedClassName)}}cn.ShowClassName="components-reconnect-show",cn.HideClassName="components-reconnect-hide",cn.FailedClassName="components-reconnect-failed",cn.RejectedClassName="components-reconnect-rejected",cn.MaxRetriesId="components-reconnect-max-retries",cn.CurrentAttemptId="components-reconnect-current-attempt";class ln{constructor(e,t,n){this._currentReconnectionProcess=null,this._logger=e,this._reconnectionDisplay=t,this._reconnectCallback=n||(()=>fe.reconnect())}onConnectionDown(e,t){if(!this._reconnectionDisplay){const t=document.getElementById(e.dialogId);this._reconnectionDisplay=t?new cn(t,e.maxRetries,document):new an(e.dialogId,e.maxRetries,document,this._logger)}this._currentReconnectionProcess||(this._currentReconnectionProcess=new hn(e,this._logger,this._reconnectCallback,this._reconnectionDisplay))}onConnectionUp(){this._currentReconnectionProcess&&(this._currentReconnectionProcess.dispose(),this._currentReconnectionProcess=null)}}class hn{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;thn.MaximumFirstRetryInterval?hn.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(en.Error,e)}}this.reconnectDisplay.failed()}delay(e){return new Promise((t=>setTimeout(t,e)))}}hn.MaximumFirstRetryInterval=3e3;const un=/^\s*Blazor-Component-State:(?[a-zA-Z0-9\+\/=]+)$/;function dn(e){var t;if(e.nodeType===Node.COMMENT_NODE){const n=e.textContent||"",r=un.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 gn(e,t){const n=e.currentElement;if(n&&n.nodeType===Node.COMMENT_NODE&&n.textContent){const r=fn.exec(n.textContent),o=r&&r.groups&&r.groups.descriptor;if(!o)return;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;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.");if(c){const e=mn(c,n);if(!e)throw new Error(`Could not find an end component comment for '${t}'`);return{type:r,assembly:o,typeName:i,parameterDefinitions:s&&atob(s),parameterValues:a&&atob(a),start:t,prerenderId:c,end:e}}return{type:r,assembly:o,typeName:i,parameterDefinitions:s&&atob(s),parameterValues:a&&atob(a),start:t}}}(r,n,e);case"server":return function(e,t,n){const{type:r,descriptor:o,sequence:i,prerenderId:s}=e;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)}'`);if(s){const e=mn(s,n);if(!e)throw new Error(`Could not find an end component comment for '${t}'`);return{type:r,sequence:i,descriptor:o,start:t,prerenderId:s,end:e}}return{type:r,sequence:i,descriptor:o,start:t}}}(r,n,e)}}catch(e){throw new Error(`Found malformed component comment at ${n.textContent}`)}}}function mn(e,t){for(;t.next()&&t.currentElement;){const n=t.currentElement;if(n.nodeType!==Node.COMMENT_NODE)continue;if(!n.textContent)continue;const r=fn.exec(n.textContent),o=r&&r[1];if(o)return yn(o,e),n}}function yn(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 wn{constructor(e){this.childNodes=e,this.currentIndex=-1,this.length=e.length}next(){return this.currentIndex++,this.currentIndexe.sequence-t.sequence))}(e)}(document),o=dn(document),i=new on(r,o||""),s=await Tn(t,n,i);if(!await i.startCircuit(s))return void n.log(en.Error,"Failed to start the circuit.");let a=!1;const c=()=>{if(!a){const e=new FormData,t=i.circuitId;e.append("circuitId",t),a=navigator.sendBeacon("_blazor/disconnect",e)}};fe.disconnect=c,window.addEventListener("unload",c,{capture:!1,once:!0}),fe.reconnect=async e=>{if(Cn)return!1;const r=e||await Tn(t,n,i);return await i.reconnect(r)?(t.reconnectionHandler.onConnectionUp(),!0):(n.log(en.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)},n.log(en.Information,"Blazor server-side application started.")}async function Tn(t,n,r){const i=new Mt;i.name="blazorpack";const s=(new rt).withUrl("_blazor").withHubProtocol(i);t.configureSignalR(s);const a=s.build();o=(e,t)=>{a.send("DispatchBrowserEvent",JSON.stringify(e),JSON.stringify(t))},fe._internal.navigationManager.listenForNavigationEvents(((e,t)=>a.send("OnLocationChanged",e,t))),a.on("JS.AttachComponent",((e,t)=>function(e,t,n){let r=Q[0];r||(r=Q[0]=new V(0)),r.attachRootComponentToLogicalElement(n,t)}(0,r.resolveElement(t),e))),a.on("JS.BeginInvokeJS",e.jsCallDispatcher.beginInvokeJSFromDotNet),a.on("JS.EndInvokeDotNet",e.jsCallDispatcher.endInvokeDotNetFromJS),a.on("JS.ReceiveByteArray",e.jsCallDispatcher.receiveByteArray);const c=tn.getOrCreate(n);a.on("JS.RenderBatch",((e,t)=>{n.log(en.Debug,`Received render batch with id ${e} and ${t.byteLength} bytes.`),c.processBatch(e,t,a)})),a.onclose((e=>!Cn&&t.reconnectionHandler.onConnectionDown(t.reconnectionOptions,e))),a.on("JS.Error",(e=>{Cn=!0,Dn(a,e,n),async function(){let e=document.querySelector("#blazor-error-ui");e&&(e.style.display="block"),Ht||(Ht=!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()}})))}()})),fe._internal.forceCloseConnection=()=>a.stop();const l=new Set;fe._internal.sendJSDataStream=async(e,t)=>{l.add(t),setTimeout((async()=>{let n=5,r=(new Date).valueOf();try{const o=31744;let i=0;for(;i1)await a.send("SupplyJSDataChunk",t,c,null);else{if(!l.has(t))break;await a.invoke("SupplyJSDataChunk",t,c,null);const e=(new Date).valueOf(),o=e-r;r=e,n=Math.max(1,Math.round(500/o))}i+=s}}catch(e){await a.send("SupplyJSDataChunk",t,null,e.toString())}finally{l.delete(t)}}),0)},fe._internal.cancelJSDataStream=async e=>{l.delete(e)};try{await a.start()}catch(e){Dn(a,e,n)}return e.attachDispatcher({beginInvokeDotNetFromJS:(e,t,n,r,o)=>{a.send("BeginInvokeDotNetFromJS",e?e.toString():null,t,n,r||0,o)},endInvokeJSFromDotNet:(e,t,n)=>{a.send("EndInvokeJSFromDotNet",e,t,n)},sendByteArray:(e,t)=>{a.send("ReceiveByteArray",e,t)}}),a}function Dn(e,t,n){n.log(en.Error,t),e&&e.stop()}fe.start=kn,document&&document.currentScript&&"false"!==document.currentScript.getAttribute("autostart")&&kn()})(); \ No newline at end of file diff --git a/src/Components/Web.JS/src/Boot.Server.ts b/src/Components/Web.JS/src/Boot.Server.ts index 53cd89e043a1..2ed588a52a37 100644 --- a/src/Components/Web.JS/src/Boot.Server.ts +++ b/src/Components/Web.JS/src/Boot.Server.ts @@ -122,12 +122,16 @@ async function initializeConnection(options: CircuitStartOptions, logger: Logger Blazor._internal.forceCloseConnection = () => connection.stop(); - const activeJSDataStreams = new Map(); + const activeJSDataStreams = new Set(); Blazor._internal.sendJSDataStream = async (data: ArrayBufferView, streamId: string) => { + // First, add the current stream to the active streams. This ensures + // we'll be able to handle any (immediate) stream cancellation requests. + activeJSDataStreams.add(streamId); + // Run the rest in the background, without delaying the completion of the call to sendJSDataStream // otherwise we'll deadlock (.NET can't begin reading until this completes, but it won't complete // because nobody's reading the pipe) - const handle = setTimeout(async () => { + setTimeout(async () => { const maxMillisecondsBetweenAcks = 500; let numChunksUntilNextAck = 5; let lastAckTime = new Date().valueOf(); @@ -147,8 +151,10 @@ async function initializeConnection(options: CircuitStartOptions, logger: Logger } else { // Check to see if the stream has been cancelled from .NET // We do this check everytime we wait for an ACK to avoid this additional - // overhead on every single chunk. - if (activeJSDataStreams.get(streamId) === undefined) { + // overhead on every single chunk. This means we'll still send a couple + // of SupplyJSDataChunk requests after cancellation (which will be ignored by .NET). + // If preferred, this check can be done on every chunk to avoid the lingering SupplyJSDataChunk calls. + if (!activeJSDataStreams.has(streamId)) { break; } @@ -186,21 +192,9 @@ async function initializeConnection(options: CircuitStartOptions, logger: Logger activeJSDataStreams.delete(streamId); } }, 0); - - // Note: need to convert to generic/number to avoid automatic type cast to NodeJS.Timeout - activeJSDataStreams.set(streamId, handle as any as number); }; Blazor._internal.cancelJSDataStream = async (streamId: string) => { - const handle = activeJSDataStreams.get(streamId); - - if (handle === undefined) { - return; - } - - // Note clearing the timeout only cancels the function from running IF it hasn't started yet. - clearTimeout(handle); - activeJSDataStreams.delete(streamId); } From 50bcb3195b3287cc897cd3f916f65f69e79481a8 Mon Sep 17 00:00:00 2001 From: Tanay Parikh Date: Fri, 11 Jun 2021 12:40:15 -0700 Subject: [PATCH 04/37] Determine chunk size based on SignalR limit --- .../Server/src/Circuits/RemoteJSDataStream.cs | 12 +++++----- .../Server/src/Circuits/RemoteJSRuntime.cs | 2 +- .../Web.JS/dist/Release/blazor.server.js | 2 +- src/Components/Web.JS/src/Boot.Server.ts | 24 ++++++++----------- src/Components/Web.JS/src/GlobalExports.ts | 2 +- 5 files changed, 19 insertions(+), 23 deletions(-) diff --git a/src/Components/Server/src/Circuits/RemoteJSDataStream.cs b/src/Components/Server/src/Circuits/RemoteJSDataStream.cs index 043f7d85d076..f62372cd6325 100644 --- a/src/Components/Server/src/Circuits/RemoteJSDataStream.cs +++ b/src/Components/Server/src/Circuits/RemoteJSDataStream.cs @@ -15,10 +15,11 @@ namespace Microsoft.AspNetCore.Components.Server.Circuits internal class RemoteJSDataStream : Stream { // Concerns with static `Instances`? Malicious actor could hijack another user's - // stream by (improbably) guessing the GUID. Maybe we put this in the JSRuntime for curcuit isolation? + // stream by (improbably) guessing the GUID. + // Maybe we put this in the JSRuntime for curcuit isolation? Would increate overhead as + // we'd have to go through CircuitHost, DotNetDispatcher and so on. private readonly static Dictionary Instances = new(); private readonly JSRuntime _runtime; - private readonly IJSDataReference _jsDataReference; private readonly Guid _streamId; private readonly long _totalLength; private readonly CancellationToken _cancellationToken; @@ -43,24 +44,23 @@ public static async Task CreateRemoteJSDataStreamAsync( IJSDataReference jsDataReference, long totalLength, long maxBufferSize, + long maximumIncomingBytes, CancellationToken cancellationToken = default) { var streamId = Guid.NewGuid(); - var remoteJSDataStream = new RemoteJSDataStream(runtime, jsDataReference, streamId, totalLength, maxBufferSize, cancellationToken); - await runtime.InvokeVoidAsync("Blazor._internal.sendJSDataStream", jsDataReference, streamId); + var remoteJSDataStream = new RemoteJSDataStream(runtime, streamId, totalLength, maxBufferSize, cancellationToken); + await runtime.InvokeVoidAsync("Blazor._internal.sendJSDataStream", jsDataReference, streamId, maximumIncomingBytes); return remoteJSDataStream; } private RemoteJSDataStream( JSRuntime runtime, - IJSDataReference jsDataReference, Guid streamId, long totalLength, long maxBufferSize, CancellationToken cancellationToken) { _runtime = runtime; - _jsDataReference = jsDataReference; _streamId = streamId; _totalLength = totalLength; _cancellationToken = cancellationToken; diff --git a/src/Components/Server/src/Circuits/RemoteJSRuntime.cs b/src/Components/Server/src/Circuits/RemoteJSRuntime.cs index d57d31ae6c5a..c6de1ff4776d 100644 --- a/src/Components/Server/src/Circuits/RemoteJSRuntime.cs +++ b/src/Components/Server/src/Circuits/RemoteJSRuntime.cs @@ -144,7 +144,7 @@ public void MarkPermanentlyDisconnected() } protected override async Task ReadJSDataAsStreamAsync(IJSDataReference jsDataReference, long totalLength, long maxBufferSize, CancellationToken cancellationToken) - => await RemoteJSDataStream.CreateRemoteJSDataStreamAsync(this, jsDataReference, totalLength, maxBufferSize, cancellationToken); + => await RemoteJSDataStream.CreateRemoteJSDataStreamAsync(this, jsDataReference, totalLength, maxBufferSize, _maximumIncomingBytes, cancellationToken); public static class Log { diff --git a/src/Components/Web.JS/dist/Release/blazor.server.js b/src/Components/Web.JS/dist/Release/blazor.server.js index 2ed735764cfe..45d2f72d33c9 100644 --- a/src/Components/Web.JS/dist/Release/blazor.server.js +++ b/src/Components/Web.JS/dist/Release/blazor.server.js @@ -1 +1 @@ -(()=>{"use strict";var e,t,n;!function(e){window.DotNet=e;const t=[],n=new Map;class r{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 o="__jsObjectId",i={},s={0:new r(window)};s[0]._cachedFunctions.set("import",(e=>("string"==typeof e&&e.startsWith("./")&&(e=document.baseURI+e.substr(2)),import(e))));let a,c=1,l=1,h=null;function u(e){t.push(e)}function d(e){if(e&&"object"==typeof e){s[l]=new r(e);let t={[o]:l};return e.buffer instanceof ArrayBuffer&&void 0!==e.byteLength&&(t.__jsDataReferenceLength=e.byteLength),l++,t}throw new Error(`Cannot create a JSObjectReference from the value '${e}'.`)}function p(e){return e?JSON.parse(e,((e,n)=>t.reduce(((t,n)=>n(e,t)),n))):null}function f(e,t,n,r){const o=m();if(o.invokeDotNetFromJS){const i=I(r),s=o.invokeDotNetFromJS(e,t,n,i);return s?p(s):null}throw new Error("The current dispatcher does not support synchronous calls from JS to .NET. Use invokeMethodAsync instead.")}function g(e,t,n,r){if(e&&n)throw new Error(`For instance method calls, assemblyName should be null. Received '${e}'.`);const o=c++,s=new Promise(((e,t)=>{i[o]={resolve:e,reject:t}}));try{const i=I(r);m().beginInvokeDotNetFromJS(o,e,t,n,i)}catch(e){y(o,!1,e)}return s}function m(){if(null!==h)return h;throw new Error("No .NET call dispatcher has been set.")}function y(e,t,n){if(!i.hasOwnProperty(e))throw new Error(`There is no pending async call with ID ${e}.`);const r=i[e];delete i[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 v(e,t){let n=s[t];if(n)return n.findFunction(e);throw new Error(`JS object instance with ID ${t} does not exist (has it been disposed?).`)}function b(e){delete s[e]}e.attachDispatcher=function(e){h=e},e.attachReviver=u,e.invokeMethod=function(e,t,...n){return f(e,t,null,n)},e.invokeMethodAsync=function(e,t,...n){return g(e,t,null,n)},e.createJSObjectReference=d,e.disposeJSObjectReference=function(e){const t=e&&e.__jsObjectId;"number"==typeof t&&b(t)},function(e){e[e.Default=0]="Default",e[e.JSObjectReference=1]="JSObjectReference"}(a=e.JSCallResultType||(e.JSCallResultType={})),e.jsCallDispatcher={findJSFunction:v,disposeJSObjectReferenceById:b,invokeJSFromDotNet:(e,t,n,r)=>{const o=S(v(e,r).apply(null,p(t)),n);return null==o?null:I(o)},beginInvokeJSFromDotNet:(e,t,n,r,o)=>{const i=new Promise((e=>{e(v(t,o).apply(null,p(n)))}));e&&i.then((t=>m().endInvokeJSFromDotNet(e,!0,I([e,!0,S(t,r)]))),(t=>m().endInvokeJSFromDotNet(e,!1,JSON.stringify([e,!1,w(t)]))))},endInvokeDotNetFromJS:(e,t,n)=>{const r=t?p(n):new Error(n);y(parseInt(e),t,r)},receiveByteArray:(e,t)=>{n.set(e,t)}};class _{constructor(e){this._id=e}invokeMethod(e,...t){return f(null,e,this._id,t)}invokeMethodAsync(e,...t){return g(null,e,this._id,t)}dispose(){g(null,"__Dispose",this._id,null).catch((e=>console.error(e)))}serializeAsArg(){return{__dotNetObject:this._id}}}const E="__byte[]";function S(e,t){switch(t){case a.Default:return e;case a.JSObjectReference:return d(e);default:throw new Error(`Invalid JS call result type '${t}'.`)}}u((function(e,t){if(t&&"object"==typeof t){if(t.hasOwnProperty("__dotNetObject"))return new _(t.__dotNetObject);if(t.hasOwnProperty(o)){const e=t.__jsObjectId,n=s[e];if(n)return n.getWrappedObject();throw new Error(`JS object instance with Id '${e}' does not exist. It may have been disposed.`)}if(t.hasOwnProperty(E)){const e=t["__byte[]"],r=n.get(e);if(void 0===r)throw new Error(`Byte array index '${e}' does not exist.`);return r}}return t}));let C=0;function I(e){return C=0,JSON.stringify(e,k)}function k(e,t){if(t instanceof _)return t.serializeAsArg();if(t instanceof Uint8Array){h.sendByteArray(C,t);const e={[E]:C};return C++,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"}(n||(n={}));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}}let o;function i(e,t){if(!o)throw new Error("eventDispatcher not initialized. Call 'setEventDispatcher' to configure it.");o(e,t)}const s=new Map,a=new Map,c={createEventArgs:()=>({})},l=[];function h(e){return s.get(e)}function u(e){const t=s.get(e);return(null==t?void 0:t.browserEventName)||e}function d(e,t){e.forEach((e=>s.set(e,t)))}function p(e){const t=[];for(let n=0;n{return{...f(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}}),d(["focus","blur","focusin","focusout"],c),d(["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};var t}}),d(["contextmenu","click","mouseover","mouseout","mousemove","mousedown","mouseup","dblclick"],{createEventArgs:e=>f(e)}),d(["error"],{createEventArgs:e=>{return{message:(t=e).message,filename:t.filename,lineno:t.lineno,colno:t.colno};var t}}),d(["loadstart","timeout","abort","load","loadend","progress"],{createEventArgs:e=>{return{lengthComputable:(t=e).lengthComputable,loaded:t.loaded,total:t.total};var t}}),d(["touchcancel","touchend","touchmove","touchenter","touchleave","touchstart"],{createEventArgs:e=>{return{detail:(t=e).detail,touches:p(t.touches),targetTouches:p(t.targetTouches),changedTouches:p(t.changedTouches),ctrlKey:t.ctrlKey,shiftKey:t.shiftKey,altKey:t.altKey,metaKey:t.metaKey,type:t.type};var t}}),d(["gotpointercapture","lostpointercapture","pointercancel","pointerdown","pointerenter","pointerleave","pointermove","pointerout","pointerover","pointerup"],{createEventArgs:e=>{return{...f(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}}),d(["wheel","mousewheel"],{createEventArgs:e=>{return{...f(t=e),deltaX:t.deltaX,deltaY:t.deltaY,deltaZ:t.deltaZ,deltaMode:t.deltaMode};var t}}),d(["toggle"],c);const g=["date","datetime-local","month","time","week"],m=E(["abort","blur","change","error","focus","load","loadend","loadstart","mouseenter","mouseleave","progress","reset","scroll","submit","unload","toggle","DOMNodeInsertedIntoDocument","DOMNodeRemovedFromDocument"]),y={submit:!0},w=E(["click","dblclick","mousedown","mousemove","mouseup"]);class v{constructor(e){this.browserRendererId=e,this.afterClickCallbacks=[];const t=++v.nextEventDelegatorId;this.eventsCollectionKey=`_blazorEvents_${t}`,this.eventInfoStore=new b(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,a.get(n));var n;t&&t.forEach((t=>this.dispatchGlobalEventToAllElements(t,e))),"click"===e.type&&this.afterClickCallbacks.forEach((t=>t(e)))}dispatchGlobalEventToAllElements(e,t){let n=t.target,o=null,s=!1;const a=m.hasOwnProperty(e);let c=!1;for(;n;){const d=this.getEventHandlerInfosForElement(n,!1);if(d){const a=d.getHandler(e);if(a&&(l=n,u=t.type,!((l instanceof HTMLButtonElement||l instanceof HTMLInputElement||l instanceof HTMLTextAreaElement||l instanceof HTMLSelectElement)&&w.hasOwnProperty(u)&&l.disabled))){if(!s){const n=h(e);o=(null==n?void 0:n.createEventArgs)?n.createEventArgs(t):{},s=!0}y.hasOwnProperty(t.type)&&t.preventDefault(),i({browserRendererId:this.browserRendererId,eventHandlerId:a.eventHandlerId,eventName:e,eventFieldInfo:r.fromEvent(a.renderingComponentId,t)},o)}d.stopPropagation(e)&&(c=!0),d.preventDefault(e)&&t.preventDefault()}n=a||c?null:n.parentElement}var l,u}getEventHandlerInfosForElement(e,t){return e.hasOwnProperty(this.eventsCollectionKey)?e[this.eventsCollectionKey]:t?e[this.eventsCollectionKey]=new _:null}}v.nextEventDelegatorId=0;class b{constructor(e){this.globalListener=e,this.infosByEventHandlerId={},this.countByEventName={},l.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=u(e),this.countByEventName.hasOwnProperty(e))this.countByEventName[e]++;else{this.countByEventName[e]=1;const t=m.hasOwnProperty(e);document.addEventListener(e,this.globalListener,t)}}update(e,t){if(this.infosByEventHandlerId.hasOwnProperty(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=u(t.eventName);0==--this.countByEventName[n]&&(delete this.countByEventName[n],document.removeEventListener(n,this.globalListener))}return t}handleEventNameAliasAdded(e,t){if(this.countByEventName.hasOwnProperty(e)){const n=this.countByEventName[e];delete this.countByEventName[e],document.removeEventListener(e,this.globalListener),this.addGlobalListener(t),this.countByEventName[t]+=n-1}}}class _{constructor(){this.handlers={},this.preventDefaultFlags=null,this.stopPropagationFlags=null}getHandler(e){return this.handlers.hasOwnProperty(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 E(e){const t={};return e.forEach((e=>{t[e]=!0})),t}const S=H("_blazorLogicalChildren"),C=H("_blazorLogicalParent"),I=H("_blazorLogicalEnd");function k(e,t){if(e.childNodes.length>0&&!t)throw new Error("New logical elements must start empty, or allowExistingContents must be true");return S in e||(e[S]=[]),e}function T(e,t){const n=document.createComment("!");return D(n,e,t),n}function D(e,t,n){const r=e;if(e instanceof Comment&&A(r)&&A(r).length>0)throw new Error("Not implemented: inserting non-empty logical container");if(R(r))throw new Error("Not implemented: moving existing logical children");const o=A(t);if(n0;)x(n,0)}const r=n;r.parentNode.removeChild(r)}function R(e){return e[C]||null}function P(e,t){return A(e)[t]}function U(e){var t=B(e);return"http://www.w3.org/2000/svg"===t.namespaceURI&&"foreignObject"!==t.tagName}function A(e){return e[S]}function N(e,t){const n=A(e);t.forEach((e=>{e.moveRangeStart=n[e.fromSiblingIndex],e.moveRangeEnd=M(e.moveRangeStart)})),t.forEach((t=>{const r=t.moveToBeforeMarker=document.createComment("marker"),o=n[t.toSiblingIndex+1];o?o.parentNode.insertBefore(r,o):L(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 B(e){if(e instanceof Element)return e;if(e instanceof Comment)return e.parentNode;throw new Error("Not a valid logical element")}function $(e){const t=A(R(e));return t[Array.prototype.indexOf.call(t,e)+1]||null}function L(e,t){if(t instanceof Element)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=$(t);n?n.parentNode.insertBefore(e,n):L(e,R(t))}}}function M(e){if(e instanceof Element)return e;const t=$(e);if(t)return t.previousSibling;{const t=R(e);return t instanceof Element?t.lastChild:M(t)}}function H(e){return"function"==typeof Symbol?Symbol():e}function O(e){return`_bl_${e}`}e.attachReviver(((e,t)=>t&&"object"==typeof t&&t.hasOwnProperty("__internalId")&&"string"==typeof t.__internalId?function(e){const t=`[${O(e)}]`;return document.querySelector(t)}(t.__internalId):t));const F="_blazorSelectValue",j=document.createElement("template"),W=document.createElementNS("http://www.w3.org/2000/svg","g"),z={},q="__internal_",J="preventDefault_",K="stopPropagation_";class V{constructor(e){this.childComponentLocations={},this.eventDelegator=new v(e),this.eventDelegator.notifyAfterClick((e=>{if(!ee)return;if(0!==e.button||function(e){return e.ctrlKey||e.shiftKey||e.altKey||e.metaKey}(e))return;if(e.defaultPrevented)return;const t=function(e){const t=!window._blazorDisableComposedPath&&e.composedPath&&e.composedPath();if(t){for(let e=0;ese(!1))))},enableNavigationInterception:function(){ee=!0},navigateTo:oe,getBaseURI:()=>document.baseURI,getLocationHref:()=>location.href};function oe(e,t,n=!1){const r=ce(e);if(!t&&he(r))ie(r,!1,n);else if(t&&location.href===e){const t=e+"?";history.replaceState(null,"",t),location.replace(e)}else n?history.replaceState(null,"",r):location.href=e}function ie(e,t,n=!1){Z=!0,n?history.replaceState(null,"",e):history.pushState(null,"",e),se(t)}async function se(e){ne&&await ne(location.href,e)}let ae;function ce(e){return ae=ae||document.createElement("a"),ae.href=e,ae.href}function le(e,t){return e?e.tagName===t?e:le(e.parentElement,t):null}function he(e){const t=(n=document.baseURI).substr(0,n.lastIndexOf("/")+1);var n;return e.startsWith(t)}const ue={init:function(e,t,n,r=50){const o=pe(t);(o||document.documentElement).style.overflowAnchor="none";const i=new IntersectionObserver((function(r){r.forEach((r=>{var o;if(!r.isIntersecting)return;const i=t.getBoundingClientRect(),s=n.getBoundingClientRect().top-i.bottom,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`});i.observe(t),i.observe(n);const s=c(t),a=c(n);function c(e){const t=new MutationObserver((()=>{i.unobserve(e),i.observe(e)}));return t.observe(e,{attributes:!0}),t}de[e._id]={intersectionObserver:i,mutationObserverBefore:s,mutationObserverAfter:a}},dispose:function(e){const t=de[e._id];t&&(t.intersectionObserver.disconnect(),t.mutationObserverBefore.disconnect(),t.mutationObserverAfter.disconnect(),e.dispose(),delete de[e._id])}},de={};function pe(e){return e?"visible"!==getComputedStyle(e).overflowY?e:pe(e.parentElement):null}const fe={navigateTo:oe,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=a.get(t.browserEventName);n?n.push(e):a.set(t.browserEventName,[e]),l.forEach((n=>n(e,t.browserEventName)))}s.set(e,t)},_internal:{navigationManager:re,domWrapper:{focus:function(e,t){if(!(e instanceof HTMLElement))throw new Error("Unable to focus an invalid element.");e.focus({preventScroll:t})}},Virtualize:ue}};window.Blazor=fe;const ge=[0,2e3,1e4,3e4,null];class me{constructor(e){this._retryDelays=void 0!==e?[...e,null]:ge}nextRetryDelayInMilliseconds(e){return this._retryDelays[e.previousRetryCount]}}class ye extends Error{constructor(e,t){const n=new.target.prototype;super(`${e}: Status code '${t}'`),this.statusCode=t,this.__proto__=n}}class we extends Error{constructor(e="A timeout occurred."){const t=new.target.prototype;super(e),this.__proto__=t}}class ve extends Error{constructor(e="An abort occurred."){const t=new.target.prototype;super(e),this.__proto__=t}}class be{constructor(e,t,n){this.statusCode=e,this.statusText=t,this.content=n}}class _e{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""}}var Ee,Se,Ce,Ie,ke;!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"}(Ee||(Ee={}));class Te extends _e{constructor(e){if(super(),this._logger=e,"undefined"==typeof fetch){const e=require;this._jar=new(e("tough-cookie").CookieJar),this._fetchType=e("node-fetch"),this._fetchType=e("fetch-cookie")(this._fetchType,this._jar),this._abortControllerType=e("abort-controller")}else this._fetchType=fetch.bind(self),this._abortControllerType=AbortController}async send(e){if(e.abortSignal&&e.abortSignal.aborted)throw new ve;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 ve});let r,o=null;if(e.timeout){const r=e.timeout;o=setTimeout((()=>{t.abort(),this._logger.log(Ee.Warning,"Timeout from HTTP request."),n=new we}),r)}try{r=await this._fetchType(e.url,{body:e.content,cache:"no-cache",credentials:!0===e.withCredentials?"include":"same-origin",headers:{"Content-Type":"text/plain;charset=UTF-8","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(Ee.Warning,`Error from HTTP request. ${e}.`),e}finally{o&&clearTimeout(o),e.abortSignal&&(e.abortSignal.onabort=null)}if(!r.ok){const e=await De(r,"text");throw new ye(e||r.statusText,r.status)}const i=De(r,e.responseType),s=await i;return new be(r.status,r.statusText,s)}getCookieString(e){return""}}function De(e,t){let n;switch(t){case"arraybuffer":n=e.arrayBuffer();break;case"text":n=e.text();break;case"blob":case"document":case"json":throw new Error(`${t} is not supported.`);default:n=e.text()}return n}class xe extends _e{constructor(e){super(),this._logger=e}send(e){return e.abortSignal&&e.abortSignal.aborted?Promise.reject(new ve):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"),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 ve)}),e.timeout&&(r.timeout=e.timeout),r.onload=()=>{e.abortSignal&&(e.abortSignal.onabort=null),r.status>=200&&r.status<300?t(new be(r.status,r.statusText,r.response||r.responseText)):n(new ye(r.response||r.responseText||r.statusText,r.status))},r.onerror=()=>{this._logger.log(Ee.Warning,`Error from HTTP request. ${r.status}: ${r.statusText}.`),n(new ye(r.statusText,r.status))},r.ontimeout=()=>{this._logger.log(Ee.Warning,"Timeout from HTTP request."),n(new we)},r.send(e.content||"")})):Promise.reject(new Error("No url defined.")):Promise.reject(new Error("No method defined."))}}class Re extends _e{constructor(e){if(super(),"undefined"!=typeof fetch)this._httpClient=new Te(e);else{if("undefined"==typeof XMLHttpRequest)throw new Error("No usable HttpClient found.");this._httpClient=new xe(e)}}send(e){return e.abortSignal&&e.abortSignal.aborted?Promise.reject(new ve):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)}}class Pe{}Pe.Authorization="Authorization",Pe.Cookie="Cookie",function(e){e[e.None=0]="None",e[e.WebSockets=1]="WebSockets",e[e.ServerSentEvents=2]="ServerSentEvents",e[e.LongPolling=4]="LongPolling"}(Se||(Se={})),function(e){e[e.Text=1]="Text",e[e.Binary=2]="Binary"}(Ce||(Ce={}));class Ue{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 Ae{constructor(){}log(e,t){}}Ae.instance=new Ae;class Ne{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 Be{static get isBrowser(){return"object"==typeof window}static get isWebWorker(){return"object"==typeof self&&"importScripts"in self}static get isNode(){return!this.isBrowser&&!this.isWebWorker}}function $e(e,t){let n="";return Le(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 Le(e){return e&&"undefined"!=typeof ArrayBuffer&&(e instanceof ArrayBuffer||e.constructor&&"ArrayBuffer"===e.constructor.name)}async function Me(e,t,n,r,o,i,s,a,c){let l={};if(o){const e=await o();e&&(l={Authorization:`Bearer ${e}`})}const[h,u]=Fe();l[h]=u,e.log(Ee.Trace,`(${t} transport) sending data. ${$e(i,s)}.`);const d=Le(i)?"arraybuffer":"text",p=await n.post(r,{content:i,headers:{...l,...c},responseType:d,withCredentials:a});e.log(Ee.Trace,`(${t} transport) request complete. Response status: ${p.statusCode}.`)}class He{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 Oe{constructor(e){this._minLevel=e,this.out=console}log(e,t){if(e>=this._minLevel){const n=`[${(new Date).toISOString()}] ${Ee[e]}: ${t}`;switch(e){case Ee.Critical:case Ee.Error:this.out.error(n);break;case Ee.Warning:this.out.warn(n);break;case Ee.Information:this.out.info(n);break;default:this.out.log(n)}}}}function Fe(){let e="X-SignalR-User-Agent";return Be.isNode&&(e="User-Agent"),[e,je("0.0.0-DEV_BUILD",We(),Be.isNode?"NodeJS":"Browser",ze())]}function je(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 We(){if(!Be.isNode)return"";switch(process.platform){case"win32":return"Windows NT";case"darwin":return"macOS";case"linux":return"Linux";default:return process.platform}}function ze(){if(Be.isNode)return process.versions.node}class qe{constructor(e,t,n,r,o,i){this._httpClient=e,this._accessTokenFactory=t,this._logger=n,this._pollAbort=new Ue,this._logMessageContent=r,this._withCredentials=o,this._headers=i,this._running=!1,this.onreceive=null,this.onclose=null}get pollAborted(){return this._pollAbort.aborted}async connect(e,t){if(Ne.isRequired(e,"url"),Ne.isRequired(t,"transferFormat"),Ne.isIn(t,Ce,"transferFormat"),this._url=e,this._logger.log(Ee.Trace,"(LongPolling transport) Connecting."),t===Ce.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]=Fe(),o={[n]:r,...this._headers},i={abortSignal:this._pollAbort.signal,headers:o,timeout:1e5,withCredentials:this._withCredentials};t===Ce.Binary&&(i.responseType="arraybuffer");const s=await this._getAccessToken();this._updateHeaderToken(i,s);const a=`${e}&_=${Date.now()}`;this._logger.log(Ee.Trace,`(LongPolling transport) polling: ${a}.`);const c=await this._httpClient.get(a,i);200!==c.statusCode?(this._logger.log(Ee.Error,`(LongPolling transport) Unexpected response code: ${c.statusCode}.`),this._closeError=new ye(c.statusText||"",c.statusCode),this._running=!1):this._running=!0,this._receiving=this._poll(this._url,i)}async _getAccessToken(){return this._accessTokenFactory?await this._accessTokenFactory():null}_updateHeaderToken(e,t){e.headers||(e.headers={}),t?e.headers[Pe.Authorization]=`Bearer ${t}`:e.headers[Pe.Authorization]&&delete e.headers[Pe.Authorization]}async _poll(e,t){try{for(;this._running;){const n=await this._getAccessToken();this._updateHeaderToken(t,n);try{const n=`${e}&_=${Date.now()}`;this._logger.log(Ee.Trace,`(LongPolling transport) polling: ${n}.`);const r=await this._httpClient.get(n,t);204===r.statusCode?(this._logger.log(Ee.Information,"(LongPolling transport) Poll terminated by server."),this._running=!1):200!==r.statusCode?(this._logger.log(Ee.Error,`(LongPolling transport) Unexpected response code: ${r.statusCode}.`),this._closeError=new ye(r.statusText||"",r.statusCode),this._running=!1):r.content?(this._logger.log(Ee.Trace,`(LongPolling transport) data received. ${$e(r.content,this._logMessageContent)}.`),this.onreceive&&this.onreceive(r.content)):this._logger.log(Ee.Trace,"(LongPolling transport) Poll timed out, reissuing.")}catch(e){this._running?e instanceof we?this._logger.log(Ee.Trace,"(LongPolling transport) Poll timed out, reissuing."):(this._closeError=e,this._running=!1):this._logger.log(Ee.Trace,`(LongPolling transport) Poll errored after shutdown: ${e.message}`)}}}finally{this._logger.log(Ee.Trace,"(LongPolling transport) Polling complete."),this.pollAborted||this._raiseOnClose()}}async send(e){return this._running?Me(this._logger,"LongPolling",this._httpClient,this._url,this._accessTokenFactory,e,this._logMessageContent,this._withCredentials,this._headers):Promise.reject(new Error("Cannot send until the transport is connected"))}async stop(){this._logger.log(Ee.Trace,"(LongPolling transport) Stopping polling."),this._running=!1,this._pollAbort.abort();try{await this._receiving,this._logger.log(Ee.Trace,`(LongPolling transport) sending DELETE request to ${this._url}.`);const e={},[t,n]=Fe();e[t]=n;const r={headers:{...e,...this._headers},withCredentials:this._withCredentials},o=await this._getAccessToken();this._updateHeaderToken(r,o),await this._httpClient.delete(this._url,r),this._logger.log(Ee.Trace,"(LongPolling transport) DELETE request sent.")}finally{this._logger.log(Ee.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(Ee.Trace,e),this.onclose(this._closeError)}}}class Je{constructor(e,t,n,r,o,i,s){this._httpClient=e,this._accessTokenFactory=t,this._logger=n,this._logMessageContent=r,this._withCredentials=i,this._eventSourceConstructor=o,this._headers=s,this.onreceive=null,this.onclose=null}async connect(e,t){if(Ne.isRequired(e,"url"),Ne.isRequired(t,"transferFormat"),Ne.isIn(t,Ce,"transferFormat"),this._logger.log(Ee.Trace,"(SSE transport) Connecting."),this._url=e,this._accessTokenFactory){const t=await this._accessTokenFactory();t&&(e+=(e.indexOf("?")<0?"?":"&")+`access_token=${encodeURIComponent(t)}`)}return new Promise(((n,r)=>{let o,i=!1;if(t===Ce.Text){if(Be.isBrowser||Be.isWebWorker)o=new this._eventSourceConstructor(e,{withCredentials:this._withCredentials});else{const t=this._httpClient.getCookieString(e),n={};n.Cookie=t;const[r,i]=Fe();n[r]=i,o=new this._eventSourceConstructor(e,{withCredentials:this._withCredentials,headers:{...n,...this._headers}})}try{o.onmessage=e=>{if(this.onreceive)try{this._logger.log(Ee.Trace,`(SSE transport) data received. ${$e(e.data,this._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(Ee.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?Me(this._logger,"SSE",this._httpClient,this._url,this._accessTokenFactory,e,this._logMessageContent,this._withCredentials,this._headers):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 Ke{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){if(Ne.isRequired(e,"url"),Ne.isRequired(t,"transferFormat"),Ne.isIn(t,Ce,"transferFormat"),this._logger.log(Ee.Trace,"(WebSockets transport) Connecting."),this._accessTokenFactory){const t=await this._accessTokenFactory();t&&(e+=(e.indexOf("?")<0?"?":"&")+`access_token=${encodeURIComponent(t)}`)}return new Promise(((n,r)=>{let o;e=e.replace(/^http/,"ws"),this._httpClient.getCookieString(e);let i=!1;o||(o=new this._webSocketConstructor(e)),t===Ce.Binary&&(o.binaryType="arraybuffer"),o.onopen=t=>{this._logger.log(Ee.Information,`WebSocket connected to ${e}.`),this._webSocket=o,i=!0,n()},o.onerror=e=>{let t=null;t="undefined"!=typeof ErrorEvent&&e instanceof ErrorEvent?e.error:"There was an error with the transport",this._logger.log(Ee.Information,`(WebSockets transport) ${t}.`)},o.onmessage=e=>{if(this._logger.log(Ee.Trace,`(WebSockets transport) data received. ${$e(e.data,this._logMessageContent)}.`),this.onreceive)try{this.onreceive(e.data)}catch(e){return void this._close(e)}},o.onclose=e=>{if(i)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(Ee.Trace,`(WebSockets transport) sending data. ${$e(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(Ee.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 Ve{constructor(e,t={}){var n;if(this._stopPromiseResolver=()=>{},this.features={},this._negotiateVersion=1,Ne.isRequired(e,"url"),this._logger=void 0===(n=t.logger)?new Oe(Ee.Information):null===n?Ae.instance:void 0!==n.log?n:new Oe(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,"undefined"==typeof WebSocket||t.WebSocket||(t.WebSocket=WebSocket),"undefined"==typeof EventSource||t.EventSource||(t.EventSource=EventSource),this._httpClient=t.httpClient||new Re(this._logger),this._connectionState="Disconnected",this._connectionStarted=!1,this._options=t,this.onreceive=null,this.onclose=null}async start(e){if(e=e||Ce.Binary,Ne.isIn(e,Ce,"transferFormat"),this._logger.log(Ee.Debug,`Starting connection with transfer format '${Ce[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(Ee.Error,e),await this._stopPromise,Promise.reject(new Error(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(Ee.Error,e),Promise.reject(new Error(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 Xe(this.transport)),this._sendQueue.send(e))}async stop(e){return"Disconnected"===this._connectionState?(this._logger.log(Ee.Debug,`Call to HttpConnection.stop(${e}) ignored because the connection is already in the disconnected state.`),Promise.resolve()):"Disconnecting"===this._connectionState?(this._logger.log(Ee.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(Ee.Error,`HttpConnection.transport.stop() threw error '${e}'.`),this._stopConnection()}this.transport=void 0}else this._logger.log(Ee.Debug,"HttpConnection.transport is undefined in HttpConnection.stop() because start() failed.")}async _startInternal(e){let t=this.baseUrl;this._accessTokenFactory=this._options.accessTokenFactory;try{if(this._options.skipNegotiation){if(this._options.transport!==Se.WebSockets)throw new Error("Negotiation can only be skipped when using the WebSocket transport directly.");this.transport=this._constructTransport(Se.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 Error("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}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 qe&&(this.features.inherentKeepAlive=!0),"Connecting"===this._connectionState&&(this._logger.log(Ee.Debug,"The HttpConnection connected successfully."),this._connectionState="Connected")}catch(e){return this._logger.log(Ee.Error,"Failed to start the connection: "+e),this._connectionState="Disconnected",this.transport=void 0,this._stopPromiseResolver(),Promise.reject(e)}}async _getNegotiationResponse(e){const t={};if(this._accessTokenFactory){const e=await this._accessTokenFactory();e&&(t[Pe.Authorization]=`Bearer ${e}`)}const[n,r]=Fe();t[n]=r;const o=this._resolveNegotiateUrl(e);this._logger.log(Ee.Debug,`Sending negotiation request: ${o}.`);try{const e=await this._httpClient.post(o,{content:"",headers:{...t,...this._options.headers},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 ye&&404===e.statusCode&&(t+=" Either this is not a SignalR endpoint or there is a proxy blocking the connection."),this._logger.log(Ee.Error,t),Promise.reject(new Error(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(Ee.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: ${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(Ee.Error,`Failed to start the transport '${n.transport}': ${e}`),a=void 0,i.push(`${n.transport} failed: ${e}`),"Connecting"!==this._connectionState){const e="Failed to select transport before stop() was called.";return this._logger.log(Ee.Debug,e),Promise.reject(new Error(e))}}}}return i.length>0?Promise.reject(new Error(`Unable to connect to the server with any of the available transports. ${i.join(" ")}`)):Promise.reject(new Error("None of the transports supported by the client are supported by the server."))}_constructTransport(e){switch(e){case Se.WebSockets:if(!this._options.WebSocket)throw new Error("'WebSocket' is not supported in your environment.");return new Ke(this._httpClient,this._accessTokenFactory,this._logger,this._options.logMessageContent||!1,this._options.WebSocket,this._options.headers||{});case Se.ServerSentEvents:if(!this._options.EventSource)throw new Error("'EventSource' is not supported in your environment.");return new Je(this._httpClient,this._accessTokenFactory,this._logger,this._options.logMessageContent||!1,this._options.EventSource,this._options.withCredentials,this._options.headers||{});case Se.LongPolling:return new qe(this._httpClient,this._accessTokenFactory,this._logger,this._options.logMessageContent||!1,this._options.withCredentials,this._options.headers||{});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=Se[e.transport];if(null==r)return this._logger.log(Ee.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(Ee.Debug,`Skipping transport '${Se[r]}' because it was disabled by the client.`),new Error(`'${Se[r]}' is disabled by the client.`);if(!(e.transferFormats.map((e=>Ce[e])).indexOf(n)>=0))return this._logger.log(Ee.Debug,`Skipping transport '${Se[r]}' because it does not support the requested transfer format '${Ce[n]}'.`),new Error(`'${Se[r]}' does not support ${Ce[n]}.`);if(r===Se.WebSockets&&!this._options.WebSocket||r===Se.ServerSentEvents&&!this._options.EventSource)return this._logger.log(Ee.Debug,`Skipping transport '${Se[r]}' because it is not supported in your environment.'`),new Error(`'${Se[r]}' is not supported in your environment.`);this._logger.log(Ee.Debug,`Selecting transport '${Se[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(Ee.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(Ee.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(Ee.Error,`Connection disconnected with error '${e}'.`):this._logger.log(Ee.Information,"Connection disconnected."),this._sendQueue&&(this._sendQueue.stop().catch((e=>{this._logger.log(Ee.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(Ee.Error,`HttpConnection.onclose(${e}) threw error '${t}'.`)}}}else this._logger.log(Ee.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(!Be.isBrowser||!window.document)throw new Error(`Cannot resolve '${e}'.`);const t=window.document.createElement("a");return t.href=e,this._logger.log(Ee.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 Xe{constructor(e){this._transport=e,this._buffer=[],this._executing=!0,this._sendBufferedData=new Ye,this._transportResult=new Ye,this._sendLoopPromise=this._sendLoop()}send(e){return this._bufferData(e),this._transportResult||(this._transportResult=new Ye),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 Ye;const e=this._transportResult;this._transportResult=void 0;const t="string"==typeof this._buffer[0]?this._buffer.join(""):Xe._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 Ye{constructor(){this.promise=new Promise(((e,t)=>[this._resolver,this._rejecter]=[e,t]))}resolve(){this._resolver()}reject(e){this._rejecter(e)}}class Ge{static write(e){return`${e}${Ge.RecordSeparator}`}static parse(e){if(e[e.length-1]!==Ge.RecordSeparator)throw new Error("Message is incomplete.");const t=e.split(Ge.RecordSeparator);return t.pop(),t}}Ge.RecordSeparatorCode=30,Ge.RecordSeparator=String.fromCharCode(Ge.RecordSeparatorCode);class Qe{writeHandshakeRequest(e){return Ge.write(JSON.stringify(e))}parseHandshakeResponse(e){let t,n;if(Le(e)){const r=new Uint8Array(e),o=r.indexOf(Ge.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(Ge.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=Ge.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"}(Ie||(Ie={}));class Ze{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 He(this,e)}}!function(e){e.Disconnected="Disconnected",e.Connecting="Connecting",e.Connected="Connected",e.Disconnecting="Disconnecting",e.Reconnecting="Reconnecting"}(ke||(ke={}));class et{constructor(e,t,n,r){this._nextKeepAlive=0,Ne.isRequired(e,"connection"),Ne.isRequired(t,"logger"),Ne.isRequired(n,"protocol"),this.serverTimeoutInMilliseconds=3e4,this.keepAliveIntervalInMilliseconds=15e3,this._logger=t,this._protocol=n,this.connection=e,this._reconnectPolicy=r,this._handshakeProtocol=new Qe,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=ke.Disconnected,this._connectionStarted=!1,this._cachedPingMessage=this._protocol.writeMessage({type:Ie.Ping})}static create(e,t,n,r){return new et(e,t,n,r)}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!==ke.Disconnected&&this._connectionState!==ke.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!==ke.Disconnected)return Promise.reject(new Error("Cannot start a HubConnection that is not in the 'Disconnected' state."));this._connectionState=ke.Connecting,this._logger.log(Ee.Debug,"Starting HubConnection.");try{await this._startInternal(),this._connectionState=ke.Connected,this._connectionStarted=!0,this._logger.log(Ee.Debug,"HubConnection connected successfully.")}catch(e){return this._connectionState=ke.Disconnected,this._logger.log(Ee.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(Ee.Debug,"Sending handshake request."),await this._sendMessage(this._handshakeProtocol.writeHandshakeRequest(t)),this._logger.log(Ee.Information,`Using HubProtocol '${this._protocol.name}'.`),this._cleanupTimeout(),this._resetTimeoutPeriod(),this._resetKeepAliveInterval(),await e,this._stopDuringStartError)throw this._stopDuringStartError}catch(e){throw this._logger.log(Ee.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){return this._connectionState===ke.Disconnected?(this._logger.log(Ee.Debug,`Call to HubConnection.stop(${e}) ignored because it is already in the disconnected state.`),Promise.resolve()):this._connectionState===ke.Disconnecting?(this._logger.log(Ee.Debug,`Call to HttpConnection.stop(${e}) ignored because the connection is already in the disconnecting state.`),this._stopPromise):(this._connectionState=ke.Disconnecting,this._logger.log(Ee.Debug,"Stopping HubConnection."),this._reconnectDelayHandle?(this._logger.log(Ee.Debug,"Connection stopped during reconnect delay. Done reconnecting."),clearTimeout(this._reconnectDelayHandle),this._reconnectDelayHandle=void 0,this._completeClose(),Promise.resolve()):(this._cleanupTimeout(),this._cleanupPingTimer(),this._stopDuringStartError=e||new Error("The connection was stopped before the hub handshake could complete."),this.connection.stop(e)))}stream(e,...t){const[n,r]=this._replaceStreamingParams(t),o=this._createStreamInvocation(e,t,r);let i;const s=new Ze;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===Ie.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===Ie.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 Ie.Invocation:this._invokeClientMethod(e);break;case Ie.StreamItem:case Ie.Completion:{const t=this._callbacks[e.invocationId];t&&(e.type===Ie.Completion&&delete this._callbacks[e.invocationId],t(e));break}case Ie.Ping:break;case Ie.Close:{this._logger.log(Ee.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(Ee.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(Ee.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(Ee.Error,e);const n=new Error(e);throw this._handshakeRejecter(n),n}return this._logger.log(Ee.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===ke.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."))}_invokeClientMethod(e){const t=this._methods[e.target.toLowerCase()];if(t){try{t.forEach((t=>t.apply(this,e.arguments)))}catch(t){this._logger.log(Ee.Error,`A callback for the method ${e.target.toLowerCase()} threw error '${t}'.`)}if(e.invocationId){const e="Server requested a response, which is not supported in this version of the client.";this._logger.log(Ee.Error,e),this._stopPromise=this._stopInternal(new Error(e))}}else this._logger.log(Ee.Warning,`No client method with the name '${e.target}' found.`)}_connectionClosed(e){this._logger.log(Ee.Debug,`HubConnection.connectionClosed(${e}) called while in state ${this._connectionState}.`),this._stopDuringStartError=this._stopDuringStartError||e||new Error("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===ke.Disconnecting?this._completeClose(e):this._connectionState===ke.Connected&&this._reconnectPolicy?this._reconnect(e):this._connectionState===ke.Connected&&this._completeClose(e)}_completeClose(e){if(this._connectionStarted){this._connectionState=ke.Disconnected,this._connectionStarted=!1;try{this._closedCallbacks.forEach((t=>t.apply(this,[e])))}catch(t){this._logger.log(Ee.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(Ee.Debug,"Connection not reconnecting because the IRetryPolicy returned null on the first reconnect attempt."),void this._completeClose(e);if(this._connectionState=ke.Reconnecting,e?this._logger.log(Ee.Information,`Connection reconnecting because of error '${e}'.`):this._logger.log(Ee.Information,"Connection reconnecting."),0!==this._reconnectingCallbacks.length){try{this._reconnectingCallbacks.forEach((t=>t.apply(this,[e])))}catch(t){this._logger.log(Ee.Error,`An onreconnecting callback called with error '${e}' threw error '${t}'.`)}if(this._connectionState!==ke.Reconnecting)return void this._logger.log(Ee.Debug,"Connection left the reconnecting state in onreconnecting callback. Done reconnecting.")}for(;null!==o;){if(this._logger.log(Ee.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!==ke.Reconnecting)return void this._logger.log(Ee.Debug,"Connection left the reconnecting state during reconnect delay. Done reconnecting.");try{if(await this._startInternal(),this._connectionState=ke.Connected,this._logger.log(Ee.Information,"HubConnection reconnected successfully."),0!==this._reconnectedCallbacks.length)try{this._reconnectedCallbacks.forEach((e=>e.apply(this,[this.connection.connectionId])))}catch(e){this._logger.log(Ee.Error,`An onreconnected callback called with connectionId '${this.connection.connectionId}; threw error '${e}'.`)}return}catch(e){if(this._logger.log(Ee.Information,`Reconnect attempt failed because of error '${e}'.`),this._connectionState!==ke.Reconnecting)return this._logger.log(Ee.Debug,`Connection moved to the '${this._connectionState}' from the reconnecting state during reconnect attempt. Done reconnecting.`),void(this._connectionState===ke.Disconnecting&&this._completeClose());r=e instanceof Error?e:new Error(e.toString()),o=this._getNextRetryDelay(n++,Date.now()-t,r)}}this._logger.log(Ee.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(Ee.Error,`IRetryPolicy.nextRetryDelayInMilliseconds(${e}, ${t}) threw error '${n}'.`),null}}_cancelCallbacksWithError(e){const t=this._callbacks;this._callbacks={},Object.keys(t).forEach((n=>{(0,t[n])(null,e)}))}_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:Ie.Invocation}:{arguments:t,target:e,type:Ie.Invocation};{const n=this._invocationId;return this._invocationId++,0!==r.length?{arguments:t,invocationId:n.toString(),streamIds:r,target:e,type:Ie.Invocation}:{arguments:t,invocationId:n.toString(),target:e,type:Ie.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 ut=ot?new TextDecoder:null,dt=ot?"undefined"!=typeof process&&"force"!==process.env.TEXT_DECODER?200:0:it,pt=function(e,t){this.type=e,this.data=t};function ft(e,t,n){var r=Math.floor(n/4294967296),o=n;e.setUint32(t,r),e.setUint32(t+4,o)}function gt(e,t){return 4294967296*e.getInt32(t)+e.getUint32(t+4)}var mt={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),ft(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:gt(t,4),nsec:t.getUint32(0)};default:throw new Error("Unrecognized data size for timestamp: "+e.length)}}(e);return new Date(1e3*t.sec+t.nsec/1e6)}},yt=function(){function e(){this.builtInEncoders=[],this.builtInDecoders=[],this.encoders=[],this.decoders=[],this.register(mt)}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 "+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: "+e+" bytes in UTF-8");this.writeU8(219),this.writeU32(e)}},e.prototype.encodeString=function(e){if(e.length>ct){var t=st(e);this.ensureBufferSizeToWrite(5+t),this.writeStringHeader(t),lt(e,this.bytes,this.pos),this.pos+=t}else t=st(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: "+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: "+t);this.writeU8(198),this.writeU32(t)}var n=wt(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: "+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=ht(e,t,n),i=Uint8Array.prototype.slice.call(e,t,t+n);return this.store(i,o),o},e}(),St=(_t=function(e,t){return(_t=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])})(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}_t(e,t),e.prototype=null===t?Object.create(t):(n.prototype=t.prototype,new n)}),Ct=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]1||a(e,t)}))})}function a(e,t){try{(n=o[e](t)).value instanceof kt?Promise.resolve(n.value.v).then(c,l):h(i[0][2],n)}catch(e){h(i[0][3],e)}var n}function c(e){a("next",e)}function l(e){a("throw",e)}function h(e,t){e(t),i.shift(),i.length&&a(i[0][0],i[0][1])}},Dt=new DataView(new ArrayBuffer(0)),xt=new Uint8Array(Dt.buffer),Rt=function(){try{Dt.getInt8(0)}catch(e){return e.constructor}throw new Error("never reached")}(),Pt=new Rt("Insufficient data"),Ut=4294967295,At=new Et,Nt=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 St(t,e),t}(Error),Bt=function(){function e(e,t,n,r,o,i,s,a){void 0===e&&(e=yt.defaultCodec),void 0===t&&(t=void 0),void 0===n&&(n=Ut),void 0===r&&(r=Ut),void 0===o&&(o=Ut),void 0===i&&(i=Ut),void 0===s&&(s=Ut),void 0===a&&(a=At),this.extensionCodec=e,this.context=t,this.maxStrLength=n,this.maxBinLength=r,this.maxArrayLength=o,this.maxMapLength=i,this.maxExtLength=s,this.keyDecoder=a,this.totalPos=0,this.pos=0,this.view=Dt,this.bytes=xt,this.headByte=-1,this.stack=[]}return e.prototype.reinitializeState=function(){this.totalPos=0,this.headByte=-1,this.stack.length=0},e.prototype.setBuffer=function(e){this.bytes=wt(e),this.view=function(e){if(e instanceof ArrayBuffer)return new DataView(e);var t=wt(e);return new DataView(t.buffer,t.byteOffset,t.byteLength)}(this.bytes),this.pos=0},e.prototype.appendBuffer=function(e){if(-1!==this.headByte||this.hasRemaining()){var t=this.bytes.subarray(this.pos),n=wt(e),r=new Uint8Array(t.length+n.length);r.set(t),r.set(n,t.length),this.setBuffer(r)}else this.setBuffer(e)},e.prototype.hasRemaining=function(e){return void 0===e&&(e=1),this.view.byteLength-this.pos>=e},e.prototype.createExtraByteError=function(e){var t=this.view,n=this.pos;return new RangeError("Extra "+(t.byteLength-n)+" of "+t.byteLength+" byte(s) found at buffer["+e+"]")},e.prototype.decode=function(e){this.reinitializeState(),this.setBuffer(e);var t=this.doDecodeSync();if(this.hasRemaining())throw this.createExtraByteError(this.pos);return t},e.prototype.decodeMulti=function(e){return Ct(this,(function(t){switch(t.label){case 0:this.reinitializeState(),this.setBuffer(e),t.label=1;case 1:return this.hasRemaining()?[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,u,d;return Ct(this,(function(p){switch(p.label){case 0:i=!1,p.label=1;case 1:p.trys.push([1,6,7,12]),t=It(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 Rt))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())throw this.createExtraByteError(this.totalPos);return[2,s]}throw h=(l=this).headByte,u=l.pos,d=l.totalPos,new RangeError("Insufficient data in parsing "+bt(h)+" at "+d+" ("+u+" 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 Tt(this,arguments,(function(){var n,r,o,i,s,a,c,l,h;return Ct(this,(function(u){switch(u.label){case 0:n=t,r=-1,u.label=1;case 1:u.trys.push([1,13,14,19]),o=It(e),u.label=2;case 2:return[4,kt(o.next())];case 3:if((i=u.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()),u.label=4;case 4:u.trys.push([4,9,,10]),u.label=5;case 5:return[4,kt(this.doDecodeSync())];case 6:return[4,u.sent()];case 7:return u.sent(),0==--r?[3,8]:[3,5];case 8:return[3,10];case 9:if(!((a=u.sent())instanceof Rt))throw a;return[3,10];case 10:this.totalPos+=this.pos,u.label=11;case 11:return[3,2];case 12:return[3,19];case 13:return c=u.sent(),l={error:c},[3,19];case 14:return u.trys.push([14,,17,18]),i&&!i.done&&(h=o.return)?[4,kt(h.call(o))]:[3,16];case 15:u.sent(),u.label=16;case 16:return[3,18];case 17:if(l)throw l.error;return[7];case 18:return[7];case 19:return[2]}}))}))},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 Nt("Unrecognized type byte: "+bt(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 Nt("The type of key must be string or number but "+typeof t);if("__proto__"===t)throw new Nt("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 Nt("Unrecognized array type byte: "+bt(e))}},e.prototype.pushMapState=function(e){if(e>this.maxMapLength)throw new Nt("Max length exceeded: map length ("+e+") > maxMapLengthLength ("+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 Nt("Max length exceeded: array length ("+e+") > maxArrayLength ("+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 Nt("Max length exceeded: UTF-8 byte length ("+e+") > maxStrLength ("+this.maxStrLength+")");if(this.bytes.byteLengthdt?function(e,t,n){var r=e.subarray(t,t+n);return ut.decode(r)}(this.bytes,o,e):ht(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 Nt("Max length exceeded: bin length ("+e+") > maxBinLength ("+this.maxBinLength+")");if(!this.hasRemaining(e+t))throw Pt;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 Nt("Max length exceeded: ext length ("+e+") > maxExtLength ("+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=gt(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 $t{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 Lt=new Uint8Array([145,Ie.Ping]);class Mt{constructor(e){this.name="messagepack",this.version=1,this.transferFormat=Ce.Binary,this._errorResult=1,this._voidResult=2,this._nonVoidResult=3,e=e||{},this._encoder=new vt(e.extensionCodec,e.context,e.maxDepth,e.initialBufferSize,e.sortKeys,e.forceFloat32,e.ignoreUndefined,e.forceIntegerToFloat),this._decoder=new Bt(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=Ae.instance);const r=$t.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 Ie.Invocation:return this._writeInvocation(e);case Ie.StreamInvocation:return this._writeStreamInvocation(e);case Ie.StreamItem:return this._writeStreamItem(e);case Ie.Completion:return this._writeCompletion(e);case Ie.Ping:return $t.write(Lt);case Ie.CancelInvocation:return this._writeCancelInvocation(e);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 Ie.Invocation:return this._createInvocationMessage(this._readHeaders(n),n);case Ie.StreamItem:return this._createStreamItemMessage(this._readHeaders(n),n);case Ie.Completion:return this._createCompletionMessage(this._readHeaders(n),n);case Ie.Ping:return this._createPingMessage(n);case Ie.Close:return this._createCloseMessage(n);default:return t.log(Ee.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:Ie.Close}}_createPingMessage(e){if(e.length<1)throw new Error("Invalid payload for Ping message.");return{type:Ie.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:Ie.Invocation}:{arguments:t[4],headers:e,streamIds:[],target:t[3],type:Ie.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:Ie.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:Ie.Completion}}_writeInvocation(e){let t;return t=e.streamIds?this._encoder.encode([Ie.Invocation,e.headers||{},e.invocationId||null,e.target,e.arguments,e.streamIds]):this._encoder.encode([Ie.Invocation,e.headers||{},e.invocationId||null,e.target,e.arguments]),$t.write(t.slice())}_writeStreamInvocation(e){let t;return t=e.streamIds?this._encoder.encode([Ie.StreamInvocation,e.headers||{},e.invocationId,e.target,e.arguments,e.streamIds]):this._encoder.encode([Ie.StreamInvocation,e.headers||{},e.invocationId,e.target,e.arguments]),$t.write(t.slice())}_writeStreamItem(e){const t=this._encoder.encode([Ie.StreamItem,e.headers||{},e.invocationId,e.item]);return $t.write(t.slice())}_writeCompletion(e){const t=e.error?this._errorResult:e.result?this._nonVoidResult:this._voidResult;let n;switch(t){case this._errorResult:n=this._encoder.encode([Ie.Completion,e.headers||{},e.invocationId,t,e.error]);break;case this._voidResult:n=this._encoder.encode([Ie.Completion,e.headers||{},e.invocationId,t]);break;case this._nonVoidResult:n=this._encoder.encode([Ie.Completion,e.headers||{},e.invocationId,t,e.result])}return $t.write(n.slice())}_writeCancelInvocation(e){const t=this._encoder.encode([Ie.CancelInvocation,e.headers||{},e.invocationId]);return $t.write(t.slice())}_readHeaders(e){const t=e[1];if("object"!=typeof t)throw new Error("Invalid headers.");return t}}let Ht=!1;const Ot="function"==typeof TextDecoder?new TextDecoder("utf-8"):null,Ft=Ot?Ot.decode.bind(Ot):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("")},jt=Math.pow(2,32),Wt=Math.pow(2,21)-1;function zt(e,t){return e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24}function qt(e,t){return e[t]+(e[t+1]<<8)+(e[t+2]<<16)+(e[t+3]<<24>>>0)}function Jt(e,t){const n=qt(e,t+4);if(n>Wt)throw new Error(`Cannot read uint64 with high order part ${n}, because the result would exceed Number.MAX_SAFE_INTEGER.`);return n*jt+qt(e,t)}class Kt{constructor(e){this.batchData=e;const t=new Gt(e);this.arrayRangeReader=new Qt(e),this.arrayBuilderSegmentReader=new Zt(e),this.diffReader=new Vt(e),this.editReader=new Xt(e,t),this.frameReader=new Yt(e,t)}updatedComponents(){return zt(this.batchData,this.batchData.length-20)}referenceFrames(){return zt(this.batchData,this.batchData.length-16)}disposedComponentIds(){return zt(this.batchData,this.batchData.length-12)}disposedEventHandlerIds(){return zt(this.batchData,this.batchData.length-8)}updatedComponentsEntry(e,t){const n=e+4*t;return zt(this.batchData,n)}referenceFramesEntry(e,t){return e+20*t}disposedComponentIdsEntry(e,t){const n=e+4*t;return zt(this.batchData,n)}disposedEventHandlerIdsEntry(e,t){const n=e+8*t;return Jt(this.batchData,n)}}class Vt{constructor(e){this.batchDataUint8=e}componentId(e){return zt(this.batchDataUint8,e)}edits(e){return e+4}editsEntry(e,t){return e+16*t}}class Xt{constructor(e,t){this.batchDataUint8=e,this.stringReader=t}editType(e){return zt(this.batchDataUint8,e)}siblingIndex(e){return zt(this.batchDataUint8,e+4)}newTreeIndex(e){return zt(this.batchDataUint8,e+8)}moveToSiblingIndex(e){return zt(this.batchDataUint8,e+8)}removedAttributeName(e){const t=zt(this.batchDataUint8,e+12);return this.stringReader.readString(t)}}class Yt{constructor(e,t){this.batchDataUint8=e,this.stringReader=t}frameType(e){return zt(this.batchDataUint8,e)}subtreeLength(e){return zt(this.batchDataUint8,e+4)}elementReferenceCaptureId(e){const t=zt(this.batchDataUint8,e+4);return this.stringReader.readString(t)}componentId(e){return zt(this.batchDataUint8,e+8)}elementName(e){const t=zt(this.batchDataUint8,e+8);return this.stringReader.readString(t)}textContent(e){const t=zt(this.batchDataUint8,e+4);return this.stringReader.readString(t)}markupContent(e){const t=zt(this.batchDataUint8,e+4);return this.stringReader.readString(t)}attributeName(e){const t=zt(this.batchDataUint8,e+4);return this.stringReader.readString(t)}attributeValue(e){const t=zt(this.batchDataUint8,e+8);return this.stringReader.readString(t)}attributeEventHandlerId(e){return Jt(this.batchDataUint8,e+12)}}class Gt{constructor(e){this.batchDataUint8=e,this.stringTableStartIndex=zt(e,e.length-4)}readString(e){if(-1===e)return null;{const n=zt(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(en.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(en.Debug,`Waiting for batch ${this.nextBatchId}. Batch ${e} not processed.`);try{this.nextBatchId++,this.logger.log(en.Debug,`Applying batch ${e}.`),function(e,t){const n=Q[e];if(!n)throw new Error(`There is no browser renderer with ID ${e}.`);const r=t.arrayRangeReader,o=t.updatedComponents(),i=r.values(o),s=r.count(o),a=t.referenceFrames(),c=r.values(a),l=t.diffReader;for(let e=0;e=this.minLevel){const n=`[${(new Date).toISOString()}] ${en[e]}: ${t}`;switch(e){case en.Critical:case en.Error:console.error(n);break;case en.Warning:console.warn(n);break;case en.Information:console.info(n);break;default:console.log(n)}}}}class on{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!==ke.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!==ke.Connected)return!1;const t=await e.invoke("StartCircuit",re.getBaseURI(),re.getLocationHref(),JSON.stringify(this.components.map((e=>e.toRecord()))),this.applicationState||"");return!!t&&(this.initialize(t),!0)}resolveElement(e){const t=Number.parseInt(e);if(Number.isNaN(t))throw new Error(`Invalid sequence number '${e}'.`);return function(e,t){if(!e.parentNode)throw new Error(`Comment not connected to the DOM ${e.textContent}`);const n=e.parentNode,r=k(n,!0),o=A(r);return Array.from(n.childNodes).forEach((e=>o.push(e))),e[C]=r,t&&(e[I]=t,k(t)),k(e)}(this.components[t].start,this.components[t].end)}}const sn={configureSignalR:e=>{},logLevel:en.Warning,reconnectionOptions:{maxRetries:8,retryIntervalMilliseconds:2e4,dialogId:"components-reconnect-modal"}};class an{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.modal.innerHTML='

Alternatively, reload

',this.message=this.modal.querySelector("h5"),this.button=this.modal.querySelector("button"),this.reloadParagraph=this.modal.querySelector("p"),this.loader=this.getLoader(),this.message.after(this.loader),this.button.addEventListener("click",(async()=>{this.show();try{await(null==fe?void 0:fe.reconnect)()||this.rejected()}catch(e){this.logger.log(en.Error,e),this.failed()}})),this.reloadParagraph.querySelector("a").addEventListener("click",(()=>location.reload()))}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",this.message.innerHTML="Reconnection failed. Try reloading the page if you're unable to reconnect.",this.message.querySelector("a").addEventListener("click",(()=>location.reload()))}rejected(){this.button.style.display="none",this.reloadParagraph.style.display="none",this.loader.style.display="none",this.message.innerHTML="Could not reconnect to the server. Reload the page to restore functionality.",this.message.querySelector("a").addEventListener("click",(()=>location.reload()))}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 cn{constructor(e,t,n){this.dialog=e,this.maxRetries=t,this.document=n,this.document=n;const r=this.document.getElementById(cn.MaxRetriesId);r&&(r.innerText=this.maxRetries.toString())}show(){this.removeClasses(),this.dialog.classList.add(cn.ShowClassName)}update(e){const t=this.document.getElementById(cn.CurrentAttemptId);t&&(t.innerText=e.toString())}hide(){this.removeClasses(),this.dialog.classList.add(cn.HideClassName)}failed(){this.removeClasses(),this.dialog.classList.add(cn.FailedClassName)}rejected(){this.removeClasses(),this.dialog.classList.add(cn.RejectedClassName)}removeClasses(){this.dialog.classList.remove(cn.ShowClassName,cn.HideClassName,cn.FailedClassName,cn.RejectedClassName)}}cn.ShowClassName="components-reconnect-show",cn.HideClassName="components-reconnect-hide",cn.FailedClassName="components-reconnect-failed",cn.RejectedClassName="components-reconnect-rejected",cn.MaxRetriesId="components-reconnect-max-retries",cn.CurrentAttemptId="components-reconnect-current-attempt";class ln{constructor(e,t,n){this._currentReconnectionProcess=null,this._logger=e,this._reconnectionDisplay=t,this._reconnectCallback=n||(()=>fe.reconnect())}onConnectionDown(e,t){if(!this._reconnectionDisplay){const t=document.getElementById(e.dialogId);this._reconnectionDisplay=t?new cn(t,e.maxRetries,document):new an(e.dialogId,e.maxRetries,document,this._logger)}this._currentReconnectionProcess||(this._currentReconnectionProcess=new hn(e,this._logger,this._reconnectCallback,this._reconnectionDisplay))}onConnectionUp(){this._currentReconnectionProcess&&(this._currentReconnectionProcess.dispose(),this._currentReconnectionProcess=null)}}class hn{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;thn.MaximumFirstRetryInterval?hn.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(en.Error,e)}}this.reconnectDisplay.failed()}delay(e){return new Promise((t=>setTimeout(t,e)))}}hn.MaximumFirstRetryInterval=3e3;const un=/^\s*Blazor-Component-State:(?[a-zA-Z0-9\+\/=]+)$/;function dn(e){var t;if(e.nodeType===Node.COMMENT_NODE){const n=e.textContent||"",r=un.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 gn(e,t){const n=e.currentElement;if(n&&n.nodeType===Node.COMMENT_NODE&&n.textContent){const r=fn.exec(n.textContent),o=r&&r.groups&&r.groups.descriptor;if(!o)return;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;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.");if(c){const e=mn(c,n);if(!e)throw new Error(`Could not find an end component comment for '${t}'`);return{type:r,assembly:o,typeName:i,parameterDefinitions:s&&atob(s),parameterValues:a&&atob(a),start:t,prerenderId:c,end:e}}return{type:r,assembly:o,typeName:i,parameterDefinitions:s&&atob(s),parameterValues:a&&atob(a),start:t}}}(r,n,e);case"server":return function(e,t,n){const{type:r,descriptor:o,sequence:i,prerenderId:s}=e;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)}'`);if(s){const e=mn(s,n);if(!e)throw new Error(`Could not find an end component comment for '${t}'`);return{type:r,sequence:i,descriptor:o,start:t,prerenderId:s,end:e}}return{type:r,sequence:i,descriptor:o,start:t}}}(r,n,e)}}catch(e){throw new Error(`Found malformed component comment at ${n.textContent}`)}}}function mn(e,t){for(;t.next()&&t.currentElement;){const n=t.currentElement;if(n.nodeType!==Node.COMMENT_NODE)continue;if(!n.textContent)continue;const r=fn.exec(n.textContent),o=r&&r[1];if(o)return yn(o,e),n}}function yn(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 wn{constructor(e){this.childNodes=e,this.currentIndex=-1,this.length=e.length}next(){return this.currentIndex++,this.currentIndexe.sequence-t.sequence))}(e)}(document),o=dn(document),i=new on(r,o||""),s=await Tn(t,n,i);if(!await i.startCircuit(s))return void n.log(en.Error,"Failed to start the circuit.");let a=!1;const c=()=>{if(!a){const e=new FormData,t=i.circuitId;e.append("circuitId",t),a=navigator.sendBeacon("_blazor/disconnect",e)}};fe.disconnect=c,window.addEventListener("unload",c,{capture:!1,once:!0}),fe.reconnect=async e=>{if(Cn)return!1;const r=e||await Tn(t,n,i);return await i.reconnect(r)?(t.reconnectionHandler.onConnectionUp(),!0):(n.log(en.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)},n.log(en.Information,"Blazor server-side application started.")}async function Tn(t,n,r){const i=new Mt;i.name="blazorpack";const s=(new rt).withUrl("_blazor").withHubProtocol(i);t.configureSignalR(s);const a=s.build();o=(e,t)=>{a.send("DispatchBrowserEvent",JSON.stringify(e),JSON.stringify(t))},fe._internal.navigationManager.listenForNavigationEvents(((e,t)=>a.send("OnLocationChanged",e,t))),a.on("JS.AttachComponent",((e,t)=>function(e,t,n){let r=Q[0];r||(r=Q[0]=new V(0)),r.attachRootComponentToLogicalElement(n,t)}(0,r.resolveElement(t),e))),a.on("JS.BeginInvokeJS",e.jsCallDispatcher.beginInvokeJSFromDotNet),a.on("JS.EndInvokeDotNet",e.jsCallDispatcher.endInvokeDotNetFromJS),a.on("JS.ReceiveByteArray",e.jsCallDispatcher.receiveByteArray);const c=tn.getOrCreate(n);a.on("JS.RenderBatch",((e,t)=>{n.log(en.Debug,`Received render batch with id ${e} and ${t.byteLength} bytes.`),c.processBatch(e,t,a)})),a.onclose((e=>!Cn&&t.reconnectionHandler.onConnectionDown(t.reconnectionOptions,e))),a.on("JS.Error",(e=>{Cn=!0,Dn(a,e,n),async function(){let e=document.querySelector("#blazor-error-ui");e&&(e.style.display="block"),Ht||(Ht=!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()}})))}()})),fe._internal.forceCloseConnection=()=>a.stop();const l=new Set;fe._internal.sendJSDataStream=async(e,t)=>{l.add(t),setTimeout((async()=>{let n=5,r=(new Date).valueOf();try{const o=31744;let i=0;for(;i1)await a.send("SupplyJSDataChunk",t,c,null);else{if(!l.has(t))break;await a.invoke("SupplyJSDataChunk",t,c,null);const e=(new Date).valueOf(),o=e-r;r=e,n=Math.max(1,Math.round(500/o))}i+=s}}catch(e){await a.send("SupplyJSDataChunk",t,null,e.toString())}finally{l.delete(t)}}),0)},fe._internal.cancelJSDataStream=async e=>{l.delete(e)};try{await a.start()}catch(e){Dn(a,e,n)}return e.attachDispatcher({beginInvokeDotNetFromJS:(e,t,n,r,o)=>{a.send("BeginInvokeDotNetFromJS",e?e.toString():null,t,n,r||0,o)},endInvokeJSFromDotNet:(e,t,n)=>{a.send("EndInvokeJSFromDotNet",e,t,n)},sendByteArray:(e,t)=>{a.send("ReceiveByteArray",e,t)}}),a}function Dn(e,t,n){n.log(en.Error,t),e&&e.stop()}fe.start=kn,document&&document.currentScript&&"false"!==document.currentScript.getAttribute("autostart")&&kn()})(); \ No newline at end of file +(()=>{"use strict";var e,t,n;!function(e){window.DotNet=e;const t=[],n=new Map;class r{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 o="__jsObjectId",i={},s={0:new r(window)};s[0]._cachedFunctions.set("import",(e=>("string"==typeof e&&e.startsWith("./")&&(e=document.baseURI+e.substr(2)),import(e))));let a,c=1,l=1,h=null;function u(e){t.push(e)}function d(e){if(e&&"object"==typeof e){s[l]=new r(e);let t={[o]:l};return e.buffer instanceof ArrayBuffer&&void 0!==e.byteLength&&(t.__jsDataReferenceLength=e.byteLength),l++,t}throw new Error(`Cannot create a JSObjectReference from the value '${e}'.`)}function p(e){return e?JSON.parse(e,((e,n)=>t.reduce(((t,n)=>n(e,t)),n))):null}function f(e,t,n,r){const o=m();if(o.invokeDotNetFromJS){const i=I(r),s=o.invokeDotNetFromJS(e,t,n,i);return s?p(s):null}throw new Error("The current dispatcher does not support synchronous calls from JS to .NET. Use invokeMethodAsync instead.")}function g(e,t,n,r){if(e&&n)throw new Error(`For instance method calls, assemblyName should be null. Received '${e}'.`);const o=c++,s=new Promise(((e,t)=>{i[o]={resolve:e,reject:t}}));try{const i=I(r);m().beginInvokeDotNetFromJS(o,e,t,n,i)}catch(e){y(o,!1,e)}return s}function m(){if(null!==h)return h;throw new Error("No .NET call dispatcher has been set.")}function y(e,t,n){if(!i.hasOwnProperty(e))throw new Error(`There is no pending async call with ID ${e}.`);const r=i[e];delete i[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 v(e,t){let n=s[t];if(n)return n.findFunction(e);throw new Error(`JS object instance with ID ${t} does not exist (has it been disposed?).`)}function b(e){delete s[e]}e.attachDispatcher=function(e){h=e},e.attachReviver=u,e.invokeMethod=function(e,t,...n){return f(e,t,null,n)},e.invokeMethodAsync=function(e,t,...n){return g(e,t,null,n)},e.createJSObjectReference=d,e.disposeJSObjectReference=function(e){const t=e&&e.__jsObjectId;"number"==typeof t&&b(t)},function(e){e[e.Default=0]="Default",e[e.JSObjectReference=1]="JSObjectReference"}(a=e.JSCallResultType||(e.JSCallResultType={})),e.jsCallDispatcher={findJSFunction:v,disposeJSObjectReferenceById:b,invokeJSFromDotNet:(e,t,n,r)=>{const o=S(v(e,r).apply(null,p(t)),n);return null==o?null:I(o)},beginInvokeJSFromDotNet:(e,t,n,r,o)=>{const i=new Promise((e=>{e(v(t,o).apply(null,p(n)))}));e&&i.then((t=>m().endInvokeJSFromDotNet(e,!0,I([e,!0,S(t,r)]))),(t=>m().endInvokeJSFromDotNet(e,!1,JSON.stringify([e,!1,w(t)]))))},endInvokeDotNetFromJS:(e,t,n)=>{const r=t?p(n):new Error(n);y(parseInt(e),t,r)},receiveByteArray:(e,t)=>{n.set(e,t)}};class _{constructor(e){this._id=e}invokeMethod(e,...t){return f(null,e,this._id,t)}invokeMethodAsync(e,...t){return g(null,e,this._id,t)}dispose(){g(null,"__Dispose",this._id,null).catch((e=>console.error(e)))}serializeAsArg(){return{__dotNetObject:this._id}}}const E="__byte[]";function S(e,t){switch(t){case a.Default:return e;case a.JSObjectReference:return d(e);default:throw new Error(`Invalid JS call result type '${t}'.`)}}u((function(e,t){if(t&&"object"==typeof t){if(t.hasOwnProperty("__dotNetObject"))return new _(t.__dotNetObject);if(t.hasOwnProperty(o)){const e=t.__jsObjectId,n=s[e];if(n)return n.getWrappedObject();throw new Error(`JS object instance with Id '${e}' does not exist. It may have been disposed.`)}if(t.hasOwnProperty(E)){const e=t["__byte[]"],r=n.get(e);if(void 0===r)throw new Error(`Byte array index '${e}' does not exist.`);return r}}return t}));let C=0;function I(e){return C=0,JSON.stringify(e,k)}function k(e,t){if(t instanceof _)return t.serializeAsArg();if(t instanceof Uint8Array){h.sendByteArray(C,t);const e={[E]:C};return C++,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"}(n||(n={}));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}}let o;function i(e,t){if(!o)throw new Error("eventDispatcher not initialized. Call 'setEventDispatcher' to configure it.");o(e,t)}const s=new Map,a=new Map,c={createEventArgs:()=>({})},l=[];function h(e){return s.get(e)}function u(e){const t=s.get(e);return(null==t?void 0:t.browserEventName)||e}function d(e,t){e.forEach((e=>s.set(e,t)))}function p(e){const t=[];for(let n=0;n{return{...f(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}}),d(["focus","blur","focusin","focusout"],c),d(["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};var t}}),d(["contextmenu","click","mouseover","mouseout","mousemove","mousedown","mouseup","dblclick"],{createEventArgs:e=>f(e)}),d(["error"],{createEventArgs:e=>{return{message:(t=e).message,filename:t.filename,lineno:t.lineno,colno:t.colno};var t}}),d(["loadstart","timeout","abort","load","loadend","progress"],{createEventArgs:e=>{return{lengthComputable:(t=e).lengthComputable,loaded:t.loaded,total:t.total};var t}}),d(["touchcancel","touchend","touchmove","touchenter","touchleave","touchstart"],{createEventArgs:e=>{return{detail:(t=e).detail,touches:p(t.touches),targetTouches:p(t.targetTouches),changedTouches:p(t.changedTouches),ctrlKey:t.ctrlKey,shiftKey:t.shiftKey,altKey:t.altKey,metaKey:t.metaKey,type:t.type};var t}}),d(["gotpointercapture","lostpointercapture","pointercancel","pointerdown","pointerenter","pointerleave","pointermove","pointerout","pointerover","pointerup"],{createEventArgs:e=>{return{...f(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}}),d(["wheel","mousewheel"],{createEventArgs:e=>{return{...f(t=e),deltaX:t.deltaX,deltaY:t.deltaY,deltaZ:t.deltaZ,deltaMode:t.deltaMode};var t}}),d(["toggle"],c);const g=["date","datetime-local","month","time","week"],m=E(["abort","blur","change","error","focus","load","loadend","loadstart","mouseenter","mouseleave","progress","reset","scroll","submit","unload","toggle","DOMNodeInsertedIntoDocument","DOMNodeRemovedFromDocument"]),y={submit:!0},w=E(["click","dblclick","mousedown","mousemove","mouseup"]);class v{constructor(e){this.browserRendererId=e,this.afterClickCallbacks=[];const t=++v.nextEventDelegatorId;this.eventsCollectionKey=`_blazorEvents_${t}`,this.eventInfoStore=new b(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,a.get(n));var n;t&&t.forEach((t=>this.dispatchGlobalEventToAllElements(t,e))),"click"===e.type&&this.afterClickCallbacks.forEach((t=>t(e)))}dispatchGlobalEventToAllElements(e,t){let n=t.target,o=null,s=!1;const a=m.hasOwnProperty(e);let c=!1;for(;n;){const d=this.getEventHandlerInfosForElement(n,!1);if(d){const a=d.getHandler(e);if(a&&(l=n,u=t.type,!((l instanceof HTMLButtonElement||l instanceof HTMLInputElement||l instanceof HTMLTextAreaElement||l instanceof HTMLSelectElement)&&w.hasOwnProperty(u)&&l.disabled))){if(!s){const n=h(e);o=(null==n?void 0:n.createEventArgs)?n.createEventArgs(t):{},s=!0}y.hasOwnProperty(t.type)&&t.preventDefault(),i({browserRendererId:this.browserRendererId,eventHandlerId:a.eventHandlerId,eventName:e,eventFieldInfo:r.fromEvent(a.renderingComponentId,t)},o)}d.stopPropagation(e)&&(c=!0),d.preventDefault(e)&&t.preventDefault()}n=a||c?null:n.parentElement}var l,u}getEventHandlerInfosForElement(e,t){return e.hasOwnProperty(this.eventsCollectionKey)?e[this.eventsCollectionKey]:t?e[this.eventsCollectionKey]=new _:null}}v.nextEventDelegatorId=0;class b{constructor(e){this.globalListener=e,this.infosByEventHandlerId={},this.countByEventName={},l.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=u(e),this.countByEventName.hasOwnProperty(e))this.countByEventName[e]++;else{this.countByEventName[e]=1;const t=m.hasOwnProperty(e);document.addEventListener(e,this.globalListener,t)}}update(e,t){if(this.infosByEventHandlerId.hasOwnProperty(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=u(t.eventName);0==--this.countByEventName[n]&&(delete this.countByEventName[n],document.removeEventListener(n,this.globalListener))}return t}handleEventNameAliasAdded(e,t){if(this.countByEventName.hasOwnProperty(e)){const n=this.countByEventName[e];delete this.countByEventName[e],document.removeEventListener(e,this.globalListener),this.addGlobalListener(t),this.countByEventName[t]+=n-1}}}class _{constructor(){this.handlers={},this.preventDefaultFlags=null,this.stopPropagationFlags=null}getHandler(e){return this.handlers.hasOwnProperty(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 E(e){const t={};return e.forEach((e=>{t[e]=!0})),t}const S=H("_blazorLogicalChildren"),C=H("_blazorLogicalParent"),I=H("_blazorLogicalEnd");function k(e,t){if(e.childNodes.length>0&&!t)throw new Error("New logical elements must start empty, or allowExistingContents must be true");return S in e||(e[S]=[]),e}function T(e,t){const n=document.createComment("!");return D(n,e,t),n}function D(e,t,n){const r=e;if(e instanceof Comment&&A(r)&&A(r).length>0)throw new Error("Not implemented: inserting non-empty logical container");if(R(r))throw new Error("Not implemented: moving existing logical children");const o=A(t);if(n0;)x(n,0)}const r=n;r.parentNode.removeChild(r)}function R(e){return e[C]||null}function P(e,t){return A(e)[t]}function U(e){var t=B(e);return"http://www.w3.org/2000/svg"===t.namespaceURI&&"foreignObject"!==t.tagName}function A(e){return e[S]}function N(e,t){const n=A(e);t.forEach((e=>{e.moveRangeStart=n[e.fromSiblingIndex],e.moveRangeEnd=M(e.moveRangeStart)})),t.forEach((t=>{const r=t.moveToBeforeMarker=document.createComment("marker"),o=n[t.toSiblingIndex+1];o?o.parentNode.insertBefore(r,o):L(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 B(e){if(e instanceof Element)return e;if(e instanceof Comment)return e.parentNode;throw new Error("Not a valid logical element")}function $(e){const t=A(R(e));return t[Array.prototype.indexOf.call(t,e)+1]||null}function L(e,t){if(t instanceof Element)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=$(t);n?n.parentNode.insertBefore(e,n):L(e,R(t))}}}function M(e){if(e instanceof Element)return e;const t=$(e);if(t)return t.previousSibling;{const t=R(e);return t instanceof Element?t.lastChild:M(t)}}function H(e){return"function"==typeof Symbol?Symbol():e}function O(e){return`_bl_${e}`}e.attachReviver(((e,t)=>t&&"object"==typeof t&&t.hasOwnProperty("__internalId")&&"string"==typeof t.__internalId?function(e){const t=`[${O(e)}]`;return document.querySelector(t)}(t.__internalId):t));const F="_blazorSelectValue",j=document.createElement("template"),W=document.createElementNS("http://www.w3.org/2000/svg","g"),z={},q="__internal_",J="preventDefault_",K="stopPropagation_";class V{constructor(e){this.childComponentLocations={},this.eventDelegator=new v(e),this.eventDelegator.notifyAfterClick((e=>{if(!ee)return;if(0!==e.button||function(e){return e.ctrlKey||e.shiftKey||e.altKey||e.metaKey}(e))return;if(e.defaultPrevented)return;const t=function(e){const t=!window._blazorDisableComposedPath&&e.composedPath&&e.composedPath();if(t){for(let e=0;ese(!1))))},enableNavigationInterception:function(){ee=!0},navigateTo:oe,getBaseURI:()=>document.baseURI,getLocationHref:()=>location.href};function oe(e,t,n=!1){const r=ce(e);if(!t&&he(r))ie(r,!1,n);else if(t&&location.href===e){const t=e+"?";history.replaceState(null,"",t),location.replace(e)}else n?history.replaceState(null,"",r):location.href=e}function ie(e,t,n=!1){Z=!0,n?history.replaceState(null,"",e):history.pushState(null,"",e),se(t)}async function se(e){ne&&await ne(location.href,e)}let ae;function ce(e){return ae=ae||document.createElement("a"),ae.href=e,ae.href}function le(e,t){return e?e.tagName===t?e:le(e.parentElement,t):null}function he(e){const t=(n=document.baseURI).substr(0,n.lastIndexOf("/")+1);var n;return e.startsWith(t)}const ue={init:function(e,t,n,r=50){const o=pe(t);(o||document.documentElement).style.overflowAnchor="none";const i=new IntersectionObserver((function(r){r.forEach((r=>{var o;if(!r.isIntersecting)return;const i=t.getBoundingClientRect(),s=n.getBoundingClientRect().top-i.bottom,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`});i.observe(t),i.observe(n);const s=c(t),a=c(n);function c(e){const t=new MutationObserver((()=>{i.unobserve(e),i.observe(e)}));return t.observe(e,{attributes:!0}),t}de[e._id]={intersectionObserver:i,mutationObserverBefore:s,mutationObserverAfter:a}},dispose:function(e){const t=de[e._id];t&&(t.intersectionObserver.disconnect(),t.mutationObserverBefore.disconnect(),t.mutationObserverAfter.disconnect(),e.dispose(),delete de[e._id])}},de={};function pe(e){return e?"visible"!==getComputedStyle(e).overflowY?e:pe(e.parentElement):null}const fe={navigateTo:oe,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=a.get(t.browserEventName);n?n.push(e):a.set(t.browserEventName,[e]),l.forEach((n=>n(e,t.browserEventName)))}s.set(e,t)},_internal:{navigationManager:re,domWrapper:{focus:function(e,t){if(!(e instanceof HTMLElement))throw new Error("Unable to focus an invalid element.");e.focus({preventScroll:t})}},Virtualize:ue}};window.Blazor=fe;const ge=[0,2e3,1e4,3e4,null];class me{constructor(e){this._retryDelays=void 0!==e?[...e,null]:ge}nextRetryDelayInMilliseconds(e){return this._retryDelays[e.previousRetryCount]}}class ye extends Error{constructor(e,t){const n=new.target.prototype;super(`${e}: Status code '${t}'`),this.statusCode=t,this.__proto__=n}}class we extends Error{constructor(e="A timeout occurred."){const t=new.target.prototype;super(e),this.__proto__=t}}class ve extends Error{constructor(e="An abort occurred."){const t=new.target.prototype;super(e),this.__proto__=t}}class be{constructor(e,t,n){this.statusCode=e,this.statusText=t,this.content=n}}class _e{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""}}var Ee,Se,Ce,Ie,ke;!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"}(Ee||(Ee={}));class Te extends _e{constructor(e){if(super(),this._logger=e,"undefined"==typeof fetch){const e=require;this._jar=new(e("tough-cookie").CookieJar),this._fetchType=e("node-fetch"),this._fetchType=e("fetch-cookie")(this._fetchType,this._jar),this._abortControllerType=e("abort-controller")}else this._fetchType=fetch.bind(self),this._abortControllerType=AbortController}async send(e){if(e.abortSignal&&e.abortSignal.aborted)throw new ve;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 ve});let r,o=null;if(e.timeout){const r=e.timeout;o=setTimeout((()=>{t.abort(),this._logger.log(Ee.Warning,"Timeout from HTTP request."),n=new we}),r)}try{r=await this._fetchType(e.url,{body:e.content,cache:"no-cache",credentials:!0===e.withCredentials?"include":"same-origin",headers:{"Content-Type":"text/plain;charset=UTF-8","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(Ee.Warning,`Error from HTTP request. ${e}.`),e}finally{o&&clearTimeout(o),e.abortSignal&&(e.abortSignal.onabort=null)}if(!r.ok){const e=await De(r,"text");throw new ye(e||r.statusText,r.status)}const i=De(r,e.responseType),s=await i;return new be(r.status,r.statusText,s)}getCookieString(e){return""}}function De(e,t){let n;switch(t){case"arraybuffer":n=e.arrayBuffer();break;case"text":n=e.text();break;case"blob":case"document":case"json":throw new Error(`${t} is not supported.`);default:n=e.text()}return n}class xe extends _e{constructor(e){super(),this._logger=e}send(e){return e.abortSignal&&e.abortSignal.aborted?Promise.reject(new ve):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"),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 ve)}),e.timeout&&(r.timeout=e.timeout),r.onload=()=>{e.abortSignal&&(e.abortSignal.onabort=null),r.status>=200&&r.status<300?t(new be(r.status,r.statusText,r.response||r.responseText)):n(new ye(r.response||r.responseText||r.statusText,r.status))},r.onerror=()=>{this._logger.log(Ee.Warning,`Error from HTTP request. ${r.status}: ${r.statusText}.`),n(new ye(r.statusText,r.status))},r.ontimeout=()=>{this._logger.log(Ee.Warning,"Timeout from HTTP request."),n(new we)},r.send(e.content||"")})):Promise.reject(new Error("No url defined.")):Promise.reject(new Error("No method defined."))}}class Re extends _e{constructor(e){if(super(),"undefined"!=typeof fetch)this._httpClient=new Te(e);else{if("undefined"==typeof XMLHttpRequest)throw new Error("No usable HttpClient found.");this._httpClient=new xe(e)}}send(e){return e.abortSignal&&e.abortSignal.aborted?Promise.reject(new ve):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)}}class Pe{}Pe.Authorization="Authorization",Pe.Cookie="Cookie",function(e){e[e.None=0]="None",e[e.WebSockets=1]="WebSockets",e[e.ServerSentEvents=2]="ServerSentEvents",e[e.LongPolling=4]="LongPolling"}(Se||(Se={})),function(e){e[e.Text=1]="Text",e[e.Binary=2]="Binary"}(Ce||(Ce={}));class Ue{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 Ae{constructor(){}log(e,t){}}Ae.instance=new Ae;class Ne{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 Be{static get isBrowser(){return"object"==typeof window}static get isWebWorker(){return"object"==typeof self&&"importScripts"in self}static get isNode(){return!this.isBrowser&&!this.isWebWorker}}function $e(e,t){let n="";return Le(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 Le(e){return e&&"undefined"!=typeof ArrayBuffer&&(e instanceof ArrayBuffer||e.constructor&&"ArrayBuffer"===e.constructor.name)}async function Me(e,t,n,r,o,i,s,a,c){let l={};if(o){const e=await o();e&&(l={Authorization:`Bearer ${e}`})}const[h,u]=Fe();l[h]=u,e.log(Ee.Trace,`(${t} transport) sending data. ${$e(i,s)}.`);const d=Le(i)?"arraybuffer":"text",p=await n.post(r,{content:i,headers:{...l,...c},responseType:d,withCredentials:a});e.log(Ee.Trace,`(${t} transport) request complete. Response status: ${p.statusCode}.`)}class He{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 Oe{constructor(e){this._minLevel=e,this.out=console}log(e,t){if(e>=this._minLevel){const n=`[${(new Date).toISOString()}] ${Ee[e]}: ${t}`;switch(e){case Ee.Critical:case Ee.Error:this.out.error(n);break;case Ee.Warning:this.out.warn(n);break;case Ee.Information:this.out.info(n);break;default:this.out.log(n)}}}}function Fe(){let e="X-SignalR-User-Agent";return Be.isNode&&(e="User-Agent"),[e,je("0.0.0-DEV_BUILD",We(),Be.isNode?"NodeJS":"Browser",ze())]}function je(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 We(){if(!Be.isNode)return"";switch(process.platform){case"win32":return"Windows NT";case"darwin":return"macOS";case"linux":return"Linux";default:return process.platform}}function ze(){if(Be.isNode)return process.versions.node}class qe{constructor(e,t,n,r,o,i){this._httpClient=e,this._accessTokenFactory=t,this._logger=n,this._pollAbort=new Ue,this._logMessageContent=r,this._withCredentials=o,this._headers=i,this._running=!1,this.onreceive=null,this.onclose=null}get pollAborted(){return this._pollAbort.aborted}async connect(e,t){if(Ne.isRequired(e,"url"),Ne.isRequired(t,"transferFormat"),Ne.isIn(t,Ce,"transferFormat"),this._url=e,this._logger.log(Ee.Trace,"(LongPolling transport) Connecting."),t===Ce.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]=Fe(),o={[n]:r,...this._headers},i={abortSignal:this._pollAbort.signal,headers:o,timeout:1e5,withCredentials:this._withCredentials};t===Ce.Binary&&(i.responseType="arraybuffer");const s=await this._getAccessToken();this._updateHeaderToken(i,s);const a=`${e}&_=${Date.now()}`;this._logger.log(Ee.Trace,`(LongPolling transport) polling: ${a}.`);const c=await this._httpClient.get(a,i);200!==c.statusCode?(this._logger.log(Ee.Error,`(LongPolling transport) Unexpected response code: ${c.statusCode}.`),this._closeError=new ye(c.statusText||"",c.statusCode),this._running=!1):this._running=!0,this._receiving=this._poll(this._url,i)}async _getAccessToken(){return this._accessTokenFactory?await this._accessTokenFactory():null}_updateHeaderToken(e,t){e.headers||(e.headers={}),t?e.headers[Pe.Authorization]=`Bearer ${t}`:e.headers[Pe.Authorization]&&delete e.headers[Pe.Authorization]}async _poll(e,t){try{for(;this._running;){const n=await this._getAccessToken();this._updateHeaderToken(t,n);try{const n=`${e}&_=${Date.now()}`;this._logger.log(Ee.Trace,`(LongPolling transport) polling: ${n}.`);const r=await this._httpClient.get(n,t);204===r.statusCode?(this._logger.log(Ee.Information,"(LongPolling transport) Poll terminated by server."),this._running=!1):200!==r.statusCode?(this._logger.log(Ee.Error,`(LongPolling transport) Unexpected response code: ${r.statusCode}.`),this._closeError=new ye(r.statusText||"",r.statusCode),this._running=!1):r.content?(this._logger.log(Ee.Trace,`(LongPolling transport) data received. ${$e(r.content,this._logMessageContent)}.`),this.onreceive&&this.onreceive(r.content)):this._logger.log(Ee.Trace,"(LongPolling transport) Poll timed out, reissuing.")}catch(e){this._running?e instanceof we?this._logger.log(Ee.Trace,"(LongPolling transport) Poll timed out, reissuing."):(this._closeError=e,this._running=!1):this._logger.log(Ee.Trace,`(LongPolling transport) Poll errored after shutdown: ${e.message}`)}}}finally{this._logger.log(Ee.Trace,"(LongPolling transport) Polling complete."),this.pollAborted||this._raiseOnClose()}}async send(e){return this._running?Me(this._logger,"LongPolling",this._httpClient,this._url,this._accessTokenFactory,e,this._logMessageContent,this._withCredentials,this._headers):Promise.reject(new Error("Cannot send until the transport is connected"))}async stop(){this._logger.log(Ee.Trace,"(LongPolling transport) Stopping polling."),this._running=!1,this._pollAbort.abort();try{await this._receiving,this._logger.log(Ee.Trace,`(LongPolling transport) sending DELETE request to ${this._url}.`);const e={},[t,n]=Fe();e[t]=n;const r={headers:{...e,...this._headers},withCredentials:this._withCredentials},o=await this._getAccessToken();this._updateHeaderToken(r,o),await this._httpClient.delete(this._url,r),this._logger.log(Ee.Trace,"(LongPolling transport) DELETE request sent.")}finally{this._logger.log(Ee.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(Ee.Trace,e),this.onclose(this._closeError)}}}class Je{constructor(e,t,n,r,o,i,s){this._httpClient=e,this._accessTokenFactory=t,this._logger=n,this._logMessageContent=r,this._withCredentials=i,this._eventSourceConstructor=o,this._headers=s,this.onreceive=null,this.onclose=null}async connect(e,t){if(Ne.isRequired(e,"url"),Ne.isRequired(t,"transferFormat"),Ne.isIn(t,Ce,"transferFormat"),this._logger.log(Ee.Trace,"(SSE transport) Connecting."),this._url=e,this._accessTokenFactory){const t=await this._accessTokenFactory();t&&(e+=(e.indexOf("?")<0?"?":"&")+`access_token=${encodeURIComponent(t)}`)}return new Promise(((n,r)=>{let o,i=!1;if(t===Ce.Text){if(Be.isBrowser||Be.isWebWorker)o=new this._eventSourceConstructor(e,{withCredentials:this._withCredentials});else{const t=this._httpClient.getCookieString(e),n={};n.Cookie=t;const[r,i]=Fe();n[r]=i,o=new this._eventSourceConstructor(e,{withCredentials:this._withCredentials,headers:{...n,...this._headers}})}try{o.onmessage=e=>{if(this.onreceive)try{this._logger.log(Ee.Trace,`(SSE transport) data received. ${$e(e.data,this._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(Ee.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?Me(this._logger,"SSE",this._httpClient,this._url,this._accessTokenFactory,e,this._logMessageContent,this._withCredentials,this._headers):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 Ke{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){if(Ne.isRequired(e,"url"),Ne.isRequired(t,"transferFormat"),Ne.isIn(t,Ce,"transferFormat"),this._logger.log(Ee.Trace,"(WebSockets transport) Connecting."),this._accessTokenFactory){const t=await this._accessTokenFactory();t&&(e+=(e.indexOf("?")<0?"?":"&")+`access_token=${encodeURIComponent(t)}`)}return new Promise(((n,r)=>{let o;e=e.replace(/^http/,"ws"),this._httpClient.getCookieString(e);let i=!1;o||(o=new this._webSocketConstructor(e)),t===Ce.Binary&&(o.binaryType="arraybuffer"),o.onopen=t=>{this._logger.log(Ee.Information,`WebSocket connected to ${e}.`),this._webSocket=o,i=!0,n()},o.onerror=e=>{let t=null;t="undefined"!=typeof ErrorEvent&&e instanceof ErrorEvent?e.error:"There was an error with the transport",this._logger.log(Ee.Information,`(WebSockets transport) ${t}.`)},o.onmessage=e=>{if(this._logger.log(Ee.Trace,`(WebSockets transport) data received. ${$e(e.data,this._logMessageContent)}.`),this.onreceive)try{this.onreceive(e.data)}catch(e){return void this._close(e)}},o.onclose=e=>{if(i)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(Ee.Trace,`(WebSockets transport) sending data. ${$e(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(Ee.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 Ve{constructor(e,t={}){var n;if(this._stopPromiseResolver=()=>{},this.features={},this._negotiateVersion=1,Ne.isRequired(e,"url"),this._logger=void 0===(n=t.logger)?new Oe(Ee.Information):null===n?Ae.instance:void 0!==n.log?n:new Oe(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,"undefined"==typeof WebSocket||t.WebSocket||(t.WebSocket=WebSocket),"undefined"==typeof EventSource||t.EventSource||(t.EventSource=EventSource),this._httpClient=t.httpClient||new Re(this._logger),this._connectionState="Disconnected",this._connectionStarted=!1,this._options=t,this.onreceive=null,this.onclose=null}async start(e){if(e=e||Ce.Binary,Ne.isIn(e,Ce,"transferFormat"),this._logger.log(Ee.Debug,`Starting connection with transfer format '${Ce[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(Ee.Error,e),await this._stopPromise,Promise.reject(new Error(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(Ee.Error,e),Promise.reject(new Error(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 Xe(this.transport)),this._sendQueue.send(e))}async stop(e){return"Disconnected"===this._connectionState?(this._logger.log(Ee.Debug,`Call to HttpConnection.stop(${e}) ignored because the connection is already in the disconnected state.`),Promise.resolve()):"Disconnecting"===this._connectionState?(this._logger.log(Ee.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(Ee.Error,`HttpConnection.transport.stop() threw error '${e}'.`),this._stopConnection()}this.transport=void 0}else this._logger.log(Ee.Debug,"HttpConnection.transport is undefined in HttpConnection.stop() because start() failed.")}async _startInternal(e){let t=this.baseUrl;this._accessTokenFactory=this._options.accessTokenFactory;try{if(this._options.skipNegotiation){if(this._options.transport!==Se.WebSockets)throw new Error("Negotiation can only be skipped when using the WebSocket transport directly.");this.transport=this._constructTransport(Se.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 Error("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}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 qe&&(this.features.inherentKeepAlive=!0),"Connecting"===this._connectionState&&(this._logger.log(Ee.Debug,"The HttpConnection connected successfully."),this._connectionState="Connected")}catch(e){return this._logger.log(Ee.Error,"Failed to start the connection: "+e),this._connectionState="Disconnected",this.transport=void 0,this._stopPromiseResolver(),Promise.reject(e)}}async _getNegotiationResponse(e){const t={};if(this._accessTokenFactory){const e=await this._accessTokenFactory();e&&(t[Pe.Authorization]=`Bearer ${e}`)}const[n,r]=Fe();t[n]=r;const o=this._resolveNegotiateUrl(e);this._logger.log(Ee.Debug,`Sending negotiation request: ${o}.`);try{const e=await this._httpClient.post(o,{content:"",headers:{...t,...this._options.headers},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 ye&&404===e.statusCode&&(t+=" Either this is not a SignalR endpoint or there is a proxy blocking the connection."),this._logger.log(Ee.Error,t),Promise.reject(new Error(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(Ee.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: ${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(Ee.Error,`Failed to start the transport '${n.transport}': ${e}`),a=void 0,i.push(`${n.transport} failed: ${e}`),"Connecting"!==this._connectionState){const e="Failed to select transport before stop() was called.";return this._logger.log(Ee.Debug,e),Promise.reject(new Error(e))}}}}return i.length>0?Promise.reject(new Error(`Unable to connect to the server with any of the available transports. ${i.join(" ")}`)):Promise.reject(new Error("None of the transports supported by the client are supported by the server."))}_constructTransport(e){switch(e){case Se.WebSockets:if(!this._options.WebSocket)throw new Error("'WebSocket' is not supported in your environment.");return new Ke(this._httpClient,this._accessTokenFactory,this._logger,this._options.logMessageContent||!1,this._options.WebSocket,this._options.headers||{});case Se.ServerSentEvents:if(!this._options.EventSource)throw new Error("'EventSource' is not supported in your environment.");return new Je(this._httpClient,this._accessTokenFactory,this._logger,this._options.logMessageContent||!1,this._options.EventSource,this._options.withCredentials,this._options.headers||{});case Se.LongPolling:return new qe(this._httpClient,this._accessTokenFactory,this._logger,this._options.logMessageContent||!1,this._options.withCredentials,this._options.headers||{});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=Se[e.transport];if(null==r)return this._logger.log(Ee.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(Ee.Debug,`Skipping transport '${Se[r]}' because it was disabled by the client.`),new Error(`'${Se[r]}' is disabled by the client.`);if(!(e.transferFormats.map((e=>Ce[e])).indexOf(n)>=0))return this._logger.log(Ee.Debug,`Skipping transport '${Se[r]}' because it does not support the requested transfer format '${Ce[n]}'.`),new Error(`'${Se[r]}' does not support ${Ce[n]}.`);if(r===Se.WebSockets&&!this._options.WebSocket||r===Se.ServerSentEvents&&!this._options.EventSource)return this._logger.log(Ee.Debug,`Skipping transport '${Se[r]}' because it is not supported in your environment.'`),new Error(`'${Se[r]}' is not supported in your environment.`);this._logger.log(Ee.Debug,`Selecting transport '${Se[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(Ee.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(Ee.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(Ee.Error,`Connection disconnected with error '${e}'.`):this._logger.log(Ee.Information,"Connection disconnected."),this._sendQueue&&(this._sendQueue.stop().catch((e=>{this._logger.log(Ee.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(Ee.Error,`HttpConnection.onclose(${e}) threw error '${t}'.`)}}}else this._logger.log(Ee.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(!Be.isBrowser||!window.document)throw new Error(`Cannot resolve '${e}'.`);const t=window.document.createElement("a");return t.href=e,this._logger.log(Ee.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 Xe{constructor(e){this._transport=e,this._buffer=[],this._executing=!0,this._sendBufferedData=new Ye,this._transportResult=new Ye,this._sendLoopPromise=this._sendLoop()}send(e){return this._bufferData(e),this._transportResult||(this._transportResult=new Ye),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 Ye;const e=this._transportResult;this._transportResult=void 0;const t="string"==typeof this._buffer[0]?this._buffer.join(""):Xe._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 Ye{constructor(){this.promise=new Promise(((e,t)=>[this._resolver,this._rejecter]=[e,t]))}resolve(){this._resolver()}reject(e){this._rejecter(e)}}class Ge{static write(e){return`${e}${Ge.RecordSeparator}`}static parse(e){if(e[e.length-1]!==Ge.RecordSeparator)throw new Error("Message is incomplete.");const t=e.split(Ge.RecordSeparator);return t.pop(),t}}Ge.RecordSeparatorCode=30,Ge.RecordSeparator=String.fromCharCode(Ge.RecordSeparatorCode);class Qe{writeHandshakeRequest(e){return Ge.write(JSON.stringify(e))}parseHandshakeResponse(e){let t,n;if(Le(e)){const r=new Uint8Array(e),o=r.indexOf(Ge.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(Ge.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=Ge.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"}(Ie||(Ie={}));class Ze{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 He(this,e)}}!function(e){e.Disconnected="Disconnected",e.Connecting="Connecting",e.Connected="Connected",e.Disconnecting="Disconnecting",e.Reconnecting="Reconnecting"}(ke||(ke={}));class et{constructor(e,t,n,r){this._nextKeepAlive=0,Ne.isRequired(e,"connection"),Ne.isRequired(t,"logger"),Ne.isRequired(n,"protocol"),this.serverTimeoutInMilliseconds=3e4,this.keepAliveIntervalInMilliseconds=15e3,this._logger=t,this._protocol=n,this.connection=e,this._reconnectPolicy=r,this._handshakeProtocol=new Qe,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=ke.Disconnected,this._connectionStarted=!1,this._cachedPingMessage=this._protocol.writeMessage({type:Ie.Ping})}static create(e,t,n,r){return new et(e,t,n,r)}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!==ke.Disconnected&&this._connectionState!==ke.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!==ke.Disconnected)return Promise.reject(new Error("Cannot start a HubConnection that is not in the 'Disconnected' state."));this._connectionState=ke.Connecting,this._logger.log(Ee.Debug,"Starting HubConnection.");try{await this._startInternal(),this._connectionState=ke.Connected,this._connectionStarted=!0,this._logger.log(Ee.Debug,"HubConnection connected successfully.")}catch(e){return this._connectionState=ke.Disconnected,this._logger.log(Ee.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(Ee.Debug,"Sending handshake request."),await this._sendMessage(this._handshakeProtocol.writeHandshakeRequest(t)),this._logger.log(Ee.Information,`Using HubProtocol '${this._protocol.name}'.`),this._cleanupTimeout(),this._resetTimeoutPeriod(),this._resetKeepAliveInterval(),await e,this._stopDuringStartError)throw this._stopDuringStartError}catch(e){throw this._logger.log(Ee.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){return this._connectionState===ke.Disconnected?(this._logger.log(Ee.Debug,`Call to HubConnection.stop(${e}) ignored because it is already in the disconnected state.`),Promise.resolve()):this._connectionState===ke.Disconnecting?(this._logger.log(Ee.Debug,`Call to HttpConnection.stop(${e}) ignored because the connection is already in the disconnecting state.`),this._stopPromise):(this._connectionState=ke.Disconnecting,this._logger.log(Ee.Debug,"Stopping HubConnection."),this._reconnectDelayHandle?(this._logger.log(Ee.Debug,"Connection stopped during reconnect delay. Done reconnecting."),clearTimeout(this._reconnectDelayHandle),this._reconnectDelayHandle=void 0,this._completeClose(),Promise.resolve()):(this._cleanupTimeout(),this._cleanupPingTimer(),this._stopDuringStartError=e||new Error("The connection was stopped before the hub handshake could complete."),this.connection.stop(e)))}stream(e,...t){const[n,r]=this._replaceStreamingParams(t),o=this._createStreamInvocation(e,t,r);let i;const s=new Ze;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===Ie.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===Ie.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 Ie.Invocation:this._invokeClientMethod(e);break;case Ie.StreamItem:case Ie.Completion:{const t=this._callbacks[e.invocationId];t&&(e.type===Ie.Completion&&delete this._callbacks[e.invocationId],t(e));break}case Ie.Ping:break;case Ie.Close:{this._logger.log(Ee.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(Ee.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(Ee.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(Ee.Error,e);const n=new Error(e);throw this._handshakeRejecter(n),n}return this._logger.log(Ee.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===ke.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."))}_invokeClientMethod(e){const t=this._methods[e.target.toLowerCase()];if(t){try{t.forEach((t=>t.apply(this,e.arguments)))}catch(t){this._logger.log(Ee.Error,`A callback for the method ${e.target.toLowerCase()} threw error '${t}'.`)}if(e.invocationId){const e="Server requested a response, which is not supported in this version of the client.";this._logger.log(Ee.Error,e),this._stopPromise=this._stopInternal(new Error(e))}}else this._logger.log(Ee.Warning,`No client method with the name '${e.target}' found.`)}_connectionClosed(e){this._logger.log(Ee.Debug,`HubConnection.connectionClosed(${e}) called while in state ${this._connectionState}.`),this._stopDuringStartError=this._stopDuringStartError||e||new Error("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===ke.Disconnecting?this._completeClose(e):this._connectionState===ke.Connected&&this._reconnectPolicy?this._reconnect(e):this._connectionState===ke.Connected&&this._completeClose(e)}_completeClose(e){if(this._connectionStarted){this._connectionState=ke.Disconnected,this._connectionStarted=!1;try{this._closedCallbacks.forEach((t=>t.apply(this,[e])))}catch(t){this._logger.log(Ee.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(Ee.Debug,"Connection not reconnecting because the IRetryPolicy returned null on the first reconnect attempt."),void this._completeClose(e);if(this._connectionState=ke.Reconnecting,e?this._logger.log(Ee.Information,`Connection reconnecting because of error '${e}'.`):this._logger.log(Ee.Information,"Connection reconnecting."),0!==this._reconnectingCallbacks.length){try{this._reconnectingCallbacks.forEach((t=>t.apply(this,[e])))}catch(t){this._logger.log(Ee.Error,`An onreconnecting callback called with error '${e}' threw error '${t}'.`)}if(this._connectionState!==ke.Reconnecting)return void this._logger.log(Ee.Debug,"Connection left the reconnecting state in onreconnecting callback. Done reconnecting.")}for(;null!==o;){if(this._logger.log(Ee.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!==ke.Reconnecting)return void this._logger.log(Ee.Debug,"Connection left the reconnecting state during reconnect delay. Done reconnecting.");try{if(await this._startInternal(),this._connectionState=ke.Connected,this._logger.log(Ee.Information,"HubConnection reconnected successfully."),0!==this._reconnectedCallbacks.length)try{this._reconnectedCallbacks.forEach((e=>e.apply(this,[this.connection.connectionId])))}catch(e){this._logger.log(Ee.Error,`An onreconnected callback called with connectionId '${this.connection.connectionId}; threw error '${e}'.`)}return}catch(e){if(this._logger.log(Ee.Information,`Reconnect attempt failed because of error '${e}'.`),this._connectionState!==ke.Reconnecting)return this._logger.log(Ee.Debug,`Connection moved to the '${this._connectionState}' from the reconnecting state during reconnect attempt. Done reconnecting.`),void(this._connectionState===ke.Disconnecting&&this._completeClose());r=e instanceof Error?e:new Error(e.toString()),o=this._getNextRetryDelay(n++,Date.now()-t,r)}}this._logger.log(Ee.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(Ee.Error,`IRetryPolicy.nextRetryDelayInMilliseconds(${e}, ${t}) threw error '${n}'.`),null}}_cancelCallbacksWithError(e){const t=this._callbacks;this._callbacks={},Object.keys(t).forEach((n=>{(0,t[n])(null,e)}))}_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:Ie.Invocation}:{arguments:t,target:e,type:Ie.Invocation};{const n=this._invocationId;return this._invocationId++,0!==r.length?{arguments:t,invocationId:n.toString(),streamIds:r,target:e,type:Ie.Invocation}:{arguments:t,invocationId:n.toString(),target:e,type:Ie.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 ut=ot?new TextDecoder:null,dt=ot?"undefined"!=typeof process&&"force"!==process.env.TEXT_DECODER?200:0:it,pt=function(e,t){this.type=e,this.data=t};function ft(e,t,n){var r=Math.floor(n/4294967296),o=n;e.setUint32(t,r),e.setUint32(t+4,o)}function gt(e,t){return 4294967296*e.getInt32(t)+e.getUint32(t+4)}var mt={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),ft(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:gt(t,4),nsec:t.getUint32(0)};default:throw new Error("Unrecognized data size for timestamp: "+e.length)}}(e);return new Date(1e3*t.sec+t.nsec/1e6)}},yt=function(){function e(){this.builtInEncoders=[],this.builtInDecoders=[],this.encoders=[],this.decoders=[],this.register(mt)}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 "+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: "+e+" bytes in UTF-8");this.writeU8(219),this.writeU32(e)}},e.prototype.encodeString=function(e){if(e.length>ct){var t=st(e);this.ensureBufferSizeToWrite(5+t),this.writeStringHeader(t),lt(e,this.bytes,this.pos),this.pos+=t}else t=st(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: "+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: "+t);this.writeU8(198),this.writeU32(t)}var n=wt(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: "+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=ht(e,t,n),i=Uint8Array.prototype.slice.call(e,t,t+n);return this.store(i,o),o},e}(),St=(_t=function(e,t){return(_t=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])})(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}_t(e,t),e.prototype=null===t?Object.create(t):(n.prototype=t.prototype,new n)}),Ct=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]1||a(e,t)}))})}function a(e,t){try{(n=o[e](t)).value instanceof kt?Promise.resolve(n.value.v).then(c,l):h(i[0][2],n)}catch(e){h(i[0][3],e)}var n}function c(e){a("next",e)}function l(e){a("throw",e)}function h(e,t){e(t),i.shift(),i.length&&a(i[0][0],i[0][1])}},Dt=new DataView(new ArrayBuffer(0)),xt=new Uint8Array(Dt.buffer),Rt=function(){try{Dt.getInt8(0)}catch(e){return e.constructor}throw new Error("never reached")}(),Pt=new Rt("Insufficient data"),Ut=4294967295,At=new Et,Nt=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 St(t,e),t}(Error),Bt=function(){function e(e,t,n,r,o,i,s,a){void 0===e&&(e=yt.defaultCodec),void 0===t&&(t=void 0),void 0===n&&(n=Ut),void 0===r&&(r=Ut),void 0===o&&(o=Ut),void 0===i&&(i=Ut),void 0===s&&(s=Ut),void 0===a&&(a=At),this.extensionCodec=e,this.context=t,this.maxStrLength=n,this.maxBinLength=r,this.maxArrayLength=o,this.maxMapLength=i,this.maxExtLength=s,this.keyDecoder=a,this.totalPos=0,this.pos=0,this.view=Dt,this.bytes=xt,this.headByte=-1,this.stack=[]}return e.prototype.reinitializeState=function(){this.totalPos=0,this.headByte=-1,this.stack.length=0},e.prototype.setBuffer=function(e){this.bytes=wt(e),this.view=function(e){if(e instanceof ArrayBuffer)return new DataView(e);var t=wt(e);return new DataView(t.buffer,t.byteOffset,t.byteLength)}(this.bytes),this.pos=0},e.prototype.appendBuffer=function(e){if(-1!==this.headByte||this.hasRemaining()){var t=this.bytes.subarray(this.pos),n=wt(e),r=new Uint8Array(t.length+n.length);r.set(t),r.set(n,t.length),this.setBuffer(r)}else this.setBuffer(e)},e.prototype.hasRemaining=function(e){return void 0===e&&(e=1),this.view.byteLength-this.pos>=e},e.prototype.createExtraByteError=function(e){var t=this.view,n=this.pos;return new RangeError("Extra "+(t.byteLength-n)+" of "+t.byteLength+" byte(s) found at buffer["+e+"]")},e.prototype.decode=function(e){this.reinitializeState(),this.setBuffer(e);var t=this.doDecodeSync();if(this.hasRemaining())throw this.createExtraByteError(this.pos);return t},e.prototype.decodeMulti=function(e){return Ct(this,(function(t){switch(t.label){case 0:this.reinitializeState(),this.setBuffer(e),t.label=1;case 1:return this.hasRemaining()?[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,u,d;return Ct(this,(function(p){switch(p.label){case 0:i=!1,p.label=1;case 1:p.trys.push([1,6,7,12]),t=It(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 Rt))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())throw this.createExtraByteError(this.totalPos);return[2,s]}throw h=(l=this).headByte,u=l.pos,d=l.totalPos,new RangeError("Insufficient data in parsing "+bt(h)+" at "+d+" ("+u+" 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 Tt(this,arguments,(function(){var n,r,o,i,s,a,c,l,h;return Ct(this,(function(u){switch(u.label){case 0:n=t,r=-1,u.label=1;case 1:u.trys.push([1,13,14,19]),o=It(e),u.label=2;case 2:return[4,kt(o.next())];case 3:if((i=u.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()),u.label=4;case 4:u.trys.push([4,9,,10]),u.label=5;case 5:return[4,kt(this.doDecodeSync())];case 6:return[4,u.sent()];case 7:return u.sent(),0==--r?[3,8]:[3,5];case 8:return[3,10];case 9:if(!((a=u.sent())instanceof Rt))throw a;return[3,10];case 10:this.totalPos+=this.pos,u.label=11;case 11:return[3,2];case 12:return[3,19];case 13:return c=u.sent(),l={error:c},[3,19];case 14:return u.trys.push([14,,17,18]),i&&!i.done&&(h=o.return)?[4,kt(h.call(o))]:[3,16];case 15:u.sent(),u.label=16;case 16:return[3,18];case 17:if(l)throw l.error;return[7];case 18:return[7];case 19:return[2]}}))}))},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 Nt("Unrecognized type byte: "+bt(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 Nt("The type of key must be string or number but "+typeof t);if("__proto__"===t)throw new Nt("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 Nt("Unrecognized array type byte: "+bt(e))}},e.prototype.pushMapState=function(e){if(e>this.maxMapLength)throw new Nt("Max length exceeded: map length ("+e+") > maxMapLengthLength ("+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 Nt("Max length exceeded: array length ("+e+") > maxArrayLength ("+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 Nt("Max length exceeded: UTF-8 byte length ("+e+") > maxStrLength ("+this.maxStrLength+")");if(this.bytes.byteLengthdt?function(e,t,n){var r=e.subarray(t,t+n);return ut.decode(r)}(this.bytes,o,e):ht(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 Nt("Max length exceeded: bin length ("+e+") > maxBinLength ("+this.maxBinLength+")");if(!this.hasRemaining(e+t))throw Pt;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 Nt("Max length exceeded: ext length ("+e+") > maxExtLength ("+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=gt(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 $t{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 Lt=new Uint8Array([145,Ie.Ping]);class Mt{constructor(e){this.name="messagepack",this.version=1,this.transferFormat=Ce.Binary,this._errorResult=1,this._voidResult=2,this._nonVoidResult=3,e=e||{},this._encoder=new vt(e.extensionCodec,e.context,e.maxDepth,e.initialBufferSize,e.sortKeys,e.forceFloat32,e.ignoreUndefined,e.forceIntegerToFloat),this._decoder=new Bt(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=Ae.instance);const r=$t.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 Ie.Invocation:return this._writeInvocation(e);case Ie.StreamInvocation:return this._writeStreamInvocation(e);case Ie.StreamItem:return this._writeStreamItem(e);case Ie.Completion:return this._writeCompletion(e);case Ie.Ping:return $t.write(Lt);case Ie.CancelInvocation:return this._writeCancelInvocation(e);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 Ie.Invocation:return this._createInvocationMessage(this._readHeaders(n),n);case Ie.StreamItem:return this._createStreamItemMessage(this._readHeaders(n),n);case Ie.Completion:return this._createCompletionMessage(this._readHeaders(n),n);case Ie.Ping:return this._createPingMessage(n);case Ie.Close:return this._createCloseMessage(n);default:return t.log(Ee.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:Ie.Close}}_createPingMessage(e){if(e.length<1)throw new Error("Invalid payload for Ping message.");return{type:Ie.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:Ie.Invocation}:{arguments:t[4],headers:e,streamIds:[],target:t[3],type:Ie.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:Ie.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:Ie.Completion}}_writeInvocation(e){let t;return t=e.streamIds?this._encoder.encode([Ie.Invocation,e.headers||{},e.invocationId||null,e.target,e.arguments,e.streamIds]):this._encoder.encode([Ie.Invocation,e.headers||{},e.invocationId||null,e.target,e.arguments]),$t.write(t.slice())}_writeStreamInvocation(e){let t;return t=e.streamIds?this._encoder.encode([Ie.StreamInvocation,e.headers||{},e.invocationId,e.target,e.arguments,e.streamIds]):this._encoder.encode([Ie.StreamInvocation,e.headers||{},e.invocationId,e.target,e.arguments]),$t.write(t.slice())}_writeStreamItem(e){const t=this._encoder.encode([Ie.StreamItem,e.headers||{},e.invocationId,e.item]);return $t.write(t.slice())}_writeCompletion(e){const t=e.error?this._errorResult:e.result?this._nonVoidResult:this._voidResult;let n;switch(t){case this._errorResult:n=this._encoder.encode([Ie.Completion,e.headers||{},e.invocationId,t,e.error]);break;case this._voidResult:n=this._encoder.encode([Ie.Completion,e.headers||{},e.invocationId,t]);break;case this._nonVoidResult:n=this._encoder.encode([Ie.Completion,e.headers||{},e.invocationId,t,e.result])}return $t.write(n.slice())}_writeCancelInvocation(e){const t=this._encoder.encode([Ie.CancelInvocation,e.headers||{},e.invocationId]);return $t.write(t.slice())}_readHeaders(e){const t=e[1];if("object"!=typeof t)throw new Error("Invalid headers.");return t}}let Ht=!1;const Ot="function"==typeof TextDecoder?new TextDecoder("utf-8"):null,Ft=Ot?Ot.decode.bind(Ot):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("")},jt=Math.pow(2,32),Wt=Math.pow(2,21)-1;function zt(e,t){return e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24}function qt(e,t){return e[t]+(e[t+1]<<8)+(e[t+2]<<16)+(e[t+3]<<24>>>0)}function Jt(e,t){const n=qt(e,t+4);if(n>Wt)throw new Error(`Cannot read uint64 with high order part ${n}, because the result would exceed Number.MAX_SAFE_INTEGER.`);return n*jt+qt(e,t)}class Kt{constructor(e){this.batchData=e;const t=new Gt(e);this.arrayRangeReader=new Qt(e),this.arrayBuilderSegmentReader=new Zt(e),this.diffReader=new Vt(e),this.editReader=new Xt(e,t),this.frameReader=new Yt(e,t)}updatedComponents(){return zt(this.batchData,this.batchData.length-20)}referenceFrames(){return zt(this.batchData,this.batchData.length-16)}disposedComponentIds(){return zt(this.batchData,this.batchData.length-12)}disposedEventHandlerIds(){return zt(this.batchData,this.batchData.length-8)}updatedComponentsEntry(e,t){const n=e+4*t;return zt(this.batchData,n)}referenceFramesEntry(e,t){return e+20*t}disposedComponentIdsEntry(e,t){const n=e+4*t;return zt(this.batchData,n)}disposedEventHandlerIdsEntry(e,t){const n=e+8*t;return Jt(this.batchData,n)}}class Vt{constructor(e){this.batchDataUint8=e}componentId(e){return zt(this.batchDataUint8,e)}edits(e){return e+4}editsEntry(e,t){return e+16*t}}class Xt{constructor(e,t){this.batchDataUint8=e,this.stringReader=t}editType(e){return zt(this.batchDataUint8,e)}siblingIndex(e){return zt(this.batchDataUint8,e+4)}newTreeIndex(e){return zt(this.batchDataUint8,e+8)}moveToSiblingIndex(e){return zt(this.batchDataUint8,e+8)}removedAttributeName(e){const t=zt(this.batchDataUint8,e+12);return this.stringReader.readString(t)}}class Yt{constructor(e,t){this.batchDataUint8=e,this.stringReader=t}frameType(e){return zt(this.batchDataUint8,e)}subtreeLength(e){return zt(this.batchDataUint8,e+4)}elementReferenceCaptureId(e){const t=zt(this.batchDataUint8,e+4);return this.stringReader.readString(t)}componentId(e){return zt(this.batchDataUint8,e+8)}elementName(e){const t=zt(this.batchDataUint8,e+8);return this.stringReader.readString(t)}textContent(e){const t=zt(this.batchDataUint8,e+4);return this.stringReader.readString(t)}markupContent(e){const t=zt(this.batchDataUint8,e+4);return this.stringReader.readString(t)}attributeName(e){const t=zt(this.batchDataUint8,e+4);return this.stringReader.readString(t)}attributeValue(e){const t=zt(this.batchDataUint8,e+8);return this.stringReader.readString(t)}attributeEventHandlerId(e){return Jt(this.batchDataUint8,e+12)}}class Gt{constructor(e){this.batchDataUint8=e,this.stringTableStartIndex=zt(e,e.length-4)}readString(e){if(-1===e)return null;{const n=zt(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(en.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(en.Debug,`Waiting for batch ${this.nextBatchId}. Batch ${e} not processed.`);try{this.nextBatchId++,this.logger.log(en.Debug,`Applying batch ${e}.`),function(e,t){const n=Q[e];if(!n)throw new Error(`There is no browser renderer with ID ${e}.`);const r=t.arrayRangeReader,o=t.updatedComponents(),i=r.values(o),s=r.count(o),a=t.referenceFrames(),c=r.values(a),l=t.diffReader;for(let e=0;e=this.minLevel){const n=`[${(new Date).toISOString()}] ${en[e]}: ${t}`;switch(e){case en.Critical:case en.Error:console.error(n);break;case en.Warning:console.warn(n);break;case en.Information:console.info(n);break;default:console.log(n)}}}}class on{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!==ke.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!==ke.Connected)return!1;const t=await e.invoke("StartCircuit",re.getBaseURI(),re.getLocationHref(),JSON.stringify(this.components.map((e=>e.toRecord()))),this.applicationState||"");return!!t&&(this.initialize(t),!0)}resolveElement(e){const t=Number.parseInt(e);if(Number.isNaN(t))throw new Error(`Invalid sequence number '${e}'.`);return function(e,t){if(!e.parentNode)throw new Error(`Comment not connected to the DOM ${e.textContent}`);const n=e.parentNode,r=k(n,!0),o=A(r);return Array.from(n.childNodes).forEach((e=>o.push(e))),e[C]=r,t&&(e[I]=t,k(t)),k(e)}(this.components[t].start,this.components[t].end)}}const sn={configureSignalR:e=>{},logLevel:en.Warning,reconnectionOptions:{maxRetries:8,retryIntervalMilliseconds:2e4,dialogId:"components-reconnect-modal"}};class an{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.modal.innerHTML='

Alternatively, reload

',this.message=this.modal.querySelector("h5"),this.button=this.modal.querySelector("button"),this.reloadParagraph=this.modal.querySelector("p"),this.loader=this.getLoader(),this.message.after(this.loader),this.button.addEventListener("click",(async()=>{this.show();try{await(null==fe?void 0:fe.reconnect)()||this.rejected()}catch(e){this.logger.log(en.Error,e),this.failed()}})),this.reloadParagraph.querySelector("a").addEventListener("click",(()=>location.reload()))}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",this.message.innerHTML="Reconnection failed. Try reloading the page if you're unable to reconnect.",this.message.querySelector("a").addEventListener("click",(()=>location.reload()))}rejected(){this.button.style.display="none",this.reloadParagraph.style.display="none",this.loader.style.display="none",this.message.innerHTML="Could not reconnect to the server. Reload the page to restore functionality.",this.message.querySelector("a").addEventListener("click",(()=>location.reload()))}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 cn{constructor(e,t,n){this.dialog=e,this.maxRetries=t,this.document=n,this.document=n;const r=this.document.getElementById(cn.MaxRetriesId);r&&(r.innerText=this.maxRetries.toString())}show(){this.removeClasses(),this.dialog.classList.add(cn.ShowClassName)}update(e){const t=this.document.getElementById(cn.CurrentAttemptId);t&&(t.innerText=e.toString())}hide(){this.removeClasses(),this.dialog.classList.add(cn.HideClassName)}failed(){this.removeClasses(),this.dialog.classList.add(cn.FailedClassName)}rejected(){this.removeClasses(),this.dialog.classList.add(cn.RejectedClassName)}removeClasses(){this.dialog.classList.remove(cn.ShowClassName,cn.HideClassName,cn.FailedClassName,cn.RejectedClassName)}}cn.ShowClassName="components-reconnect-show",cn.HideClassName="components-reconnect-hide",cn.FailedClassName="components-reconnect-failed",cn.RejectedClassName="components-reconnect-rejected",cn.MaxRetriesId="components-reconnect-max-retries",cn.CurrentAttemptId="components-reconnect-current-attempt";class ln{constructor(e,t,n){this._currentReconnectionProcess=null,this._logger=e,this._reconnectionDisplay=t,this._reconnectCallback=n||(()=>fe.reconnect())}onConnectionDown(e,t){if(!this._reconnectionDisplay){const t=document.getElementById(e.dialogId);this._reconnectionDisplay=t?new cn(t,e.maxRetries,document):new an(e.dialogId,e.maxRetries,document,this._logger)}this._currentReconnectionProcess||(this._currentReconnectionProcess=new hn(e,this._logger,this._reconnectCallback,this._reconnectionDisplay))}onConnectionUp(){this._currentReconnectionProcess&&(this._currentReconnectionProcess.dispose(),this._currentReconnectionProcess=null)}}class hn{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;thn.MaximumFirstRetryInterval?hn.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(en.Error,e)}}this.reconnectDisplay.failed()}delay(e){return new Promise((t=>setTimeout(t,e)))}}hn.MaximumFirstRetryInterval=3e3;const un=/^\s*Blazor-Component-State:(?[a-zA-Z0-9\+\/=]+)$/;function dn(e){var t;if(e.nodeType===Node.COMMENT_NODE){const n=e.textContent||"",r=un.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 gn(e,t){const n=e.currentElement;if(n&&n.nodeType===Node.COMMENT_NODE&&n.textContent){const r=fn.exec(n.textContent),o=r&&r.groups&&r.groups.descriptor;if(!o)return;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;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.");if(c){const e=mn(c,n);if(!e)throw new Error(`Could not find an end component comment for '${t}'`);return{type:r,assembly:o,typeName:i,parameterDefinitions:s&&atob(s),parameterValues:a&&atob(a),start:t,prerenderId:c,end:e}}return{type:r,assembly:o,typeName:i,parameterDefinitions:s&&atob(s),parameterValues:a&&atob(a),start:t}}}(r,n,e);case"server":return function(e,t,n){const{type:r,descriptor:o,sequence:i,prerenderId:s}=e;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)}'`);if(s){const e=mn(s,n);if(!e)throw new Error(`Could not find an end component comment for '${t}'`);return{type:r,sequence:i,descriptor:o,start:t,prerenderId:s,end:e}}return{type:r,sequence:i,descriptor:o,start:t}}}(r,n,e)}}catch(e){throw new Error(`Found malformed component comment at ${n.textContent}`)}}}function mn(e,t){for(;t.next()&&t.currentElement;){const n=t.currentElement;if(n.nodeType!==Node.COMMENT_NODE)continue;if(!n.textContent)continue;const r=fn.exec(n.textContent),o=r&&r[1];if(o)return yn(o,e),n}}function yn(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 wn{constructor(e){this.childNodes=e,this.currentIndex=-1,this.length=e.length}next(){return this.currentIndex++,this.currentIndexe.sequence-t.sequence))}(e)}(document),o=dn(document),i=new on(r,o||""),s=await Tn(t,n,i);if(!await i.startCircuit(s))return void n.log(en.Error,"Failed to start the circuit.");let a=!1;const c=()=>{if(!a){const e=new FormData,t=i.circuitId;e.append("circuitId",t),a=navigator.sendBeacon("_blazor/disconnect",e)}};fe.disconnect=c,window.addEventListener("unload",c,{capture:!1,once:!0}),fe.reconnect=async e=>{if(Cn)return!1;const r=e||await Tn(t,n,i);return await i.reconnect(r)?(t.reconnectionHandler.onConnectionUp(),!0):(n.log(en.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)},n.log(en.Information,"Blazor server-side application started.")}async function Tn(t,n,r){const i=new Mt;i.name="blazorpack";const s=(new rt).withUrl("_blazor").withHubProtocol(i);t.configureSignalR(s);const a=s.build();o=(e,t)=>{a.send("DispatchBrowserEvent",JSON.stringify(e),JSON.stringify(t))},fe._internal.navigationManager.listenForNavigationEvents(((e,t)=>a.send("OnLocationChanged",e,t))),a.on("JS.AttachComponent",((e,t)=>function(e,t,n){let r=Q[0];r||(r=Q[0]=new V(0)),r.attachRootComponentToLogicalElement(n,t)}(0,r.resolveElement(t),e))),a.on("JS.BeginInvokeJS",e.jsCallDispatcher.beginInvokeJSFromDotNet),a.on("JS.EndInvokeDotNet",e.jsCallDispatcher.endInvokeDotNetFromJS),a.on("JS.ReceiveByteArray",e.jsCallDispatcher.receiveByteArray);const c=tn.getOrCreate(n);a.on("JS.RenderBatch",((e,t)=>{n.log(en.Debug,`Received render batch with id ${e} and ${t.byteLength} bytes.`),c.processBatch(e,t,a)})),a.onclose((e=>!Cn&&t.reconnectionHandler.onConnectionDown(t.reconnectionOptions,e))),a.on("JS.Error",(e=>{Cn=!0,Dn(a,e,n),async function(){let e=document.querySelector("#blazor-error-ui");e&&(e.style.display="block"),Ht||(Ht=!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()}})))}()})),fe._internal.forceCloseConnection=()=>a.stop();const l=new Set;fe._internal.sendJSDataStream=async(e,t,n)=>{l.add(t),setTimeout((async()=>{let r=5,o=(new Date).valueOf();try{const i=n-512;if(i<=0)throw new Error("The chunk size must be greater than 0.");let s=0;for(;s1)await a.send("SupplyJSDataChunk",t,c,null);else{if(!l.has(t))break;await a.invoke("SupplyJSDataChunk",t,c,null);const e=(new Date).valueOf(),n=e-o;o=e,r=Math.max(1,Math.round(500/n))}s+=n}}catch(e){await a.send("SupplyJSDataChunk",t,null,e.toString())}finally{l.delete(t)}}),0)},fe._internal.cancelJSDataStream=async e=>{l.delete(e)};try{await a.start()}catch(e){Dn(a,e,n)}return e.attachDispatcher({beginInvokeDotNetFromJS:(e,t,n,r,o)=>{a.send("BeginInvokeDotNetFromJS",e?e.toString():null,t,n,r||0,o)},endInvokeJSFromDotNet:(e,t,n)=>{a.send("EndInvokeJSFromDotNet",e,t,n)},sendByteArray:(e,t)=>{a.send("ReceiveByteArray",e,t)}}),a}function Dn(e,t,n){n.log(en.Error,t),e&&e.stop()}fe.start=kn,document&&document.currentScript&&"false"!==document.currentScript.getAttribute("autostart")&&kn()})(); \ No newline at end of file diff --git a/src/Components/Web.JS/src/Boot.Server.ts b/src/Components/Web.JS/src/Boot.Server.ts index 2ed588a52a37..a97d5a77e5d7 100644 --- a/src/Components/Web.JS/src/Boot.Server.ts +++ b/src/Components/Web.JS/src/Boot.Server.ts @@ -123,7 +123,7 @@ async function initializeConnection(options: CircuitStartOptions, logger: Logger Blazor._internal.forceCloseConnection = () => connection.stop(); const activeJSDataStreams = new Set(); - Blazor._internal.sendJSDataStream = async (data: ArrayBufferView, streamId: string) => { + Blazor._internal.sendJSDataStream = async (data: ArrayBufferView, streamId: string, maximumIncomingBytes: number) => { // First, add the current stream to the active streams. This ensures // we'll be able to handle any (immediate) stream cancellation requests. activeJSDataStreams.add(streamId); @@ -136,10 +136,17 @@ async function initializeConnection(options: CircuitStartOptions, logger: Logger let numChunksUntilNextAck = 5; let lastAckTime = new Date().valueOf(); try { - const chunkSize = 31*1024; // TODO: Should this somehow auto-match the SignalR max message size, minus some overhead? + // Chunk Size is the max SignalR message size less 512 bytes assumed overhead. + const chunkSize = maximumIncomingBytes - 512; + if (chunkSize <= 0) { + throw new Error('The chunk size must be greater than 0.') + } + let position = 0; + + // Note: The server-side `StreamBufferCapacity` option (defaults to 10) can be configured to limit how many + // stream items from the client (per stream) will be stored before reading any more stream items (thus applying backpressure). while (position < data.byteLength) { - // TODO: Doesn't the JS side receive any backpressure indication? We're just pushing it all here. const nextChunkSize = Math.min(chunkSize, data.byteLength - position); console.log(`Sending a chunk of length ${nextChunkSize}`); const nextChunkData = new Uint8Array(data.buffer, data.byteOffset + position, nextChunkSize); @@ -174,17 +181,6 @@ async function initializeConnection(options: CircuitStartOptions, logger: Logger } position += nextChunkSize; - - // TODO: Somehow we need to delay sending the next item until the actual network transfer for the preceding - // one completed. Otherwise we'll just queue them all up instantly, which is too problematic because - // it prevents all other user interactions while the transfer is in progress. For example, this makes - // it impossible to have a "cancel" button. We need to give priority to all other events, which would - // be achievable if we didn't dispatch the next chunk until the previous one finished, because then - // any other events would already be queued. - // - // One way to do this would be *not* using SignalR streaming at all, but rather having a "pull" - // model like the existing . It would be slower, but the .NET side could request each - // chunk in turn once it's received the last one. That would also give cancellation for free. } } catch (error) { await connection.send('SupplyJSDataChunk', streamId, null, error.toString()); diff --git a/src/Components/Web.JS/src/GlobalExports.ts b/src/Components/Web.JS/src/GlobalExports.ts index fbf4bd44e869..004a09ce635e 100644 --- a/src/Components/Web.JS/src/GlobalExports.ts +++ b/src/Components/Web.JS/src/GlobalExports.ts @@ -49,7 +49,7 @@ interface IBlazor { dotNetCriticalError?: any getSatelliteAssemblies?: any, applyHotReload?: (id: string, metadataDelta: string, ilDelta: string) => void, - sendJSDataStream?: (data: any, streamId: string) => void, + sendJSDataStream?: (data: any, streamId: string, maximumIncomingBytes: number) => void, cancelJSDataStream?: (streamId: string) => void, } } From 5b691058c51d8c1928128a18483e0f46668edaa4 Mon Sep 17 00:00:00 2001 From: Tanay Parikh Date: Fri, 11 Jun 2021 12:40:30 -0700 Subject: [PATCH 05/37] Add DeserializedJSObjectReferenceValues --- ...bAssemblyJSObjectReferenceJsonConverter.cs | 4 +-- .../JSObjectReferenceJsonWorker.cs | 33 ++++++++++++++----- .../JSDataReferenceJsonConverter.cs | 6 ++-- .../JSObjectReferenceJsonConverter.cs | 4 +-- .../src/PublicAPI.Unshipped.txt | 6 +++- 5 files changed, 37 insertions(+), 16 deletions(-) diff --git a/src/Components/WebAssembly/JSInterop/src/WebAssemblyJSObjectReferenceJsonConverter.cs b/src/Components/WebAssembly/JSInterop/src/WebAssemblyJSObjectReferenceJsonConverter.cs index 04fe3972da4f..9afc2eaadea2 100644 --- a/src/Components/WebAssembly/JSInterop/src/WebAssemblyJSObjectReferenceJsonConverter.cs +++ b/src/Components/WebAssembly/JSInterop/src/WebAssemblyJSObjectReferenceJsonConverter.cs @@ -27,8 +27,8 @@ public override bool CanConvert(Type typeToConvert) public override IJSObjectReference? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { - var (id, _) = JSObjectReferenceJsonWorker.ReadJSObjectReferenceIdentifier(ref reader); - return new WebAssemblyJSObjectReference(_jsRuntime, id); + var deserializedValues = JSObjectReferenceJsonWorker.ReadJSObjectReference(ref reader); + return new WebAssemblyJSObjectReference(_jsRuntime, deserializedValues.Id); } public override void Write(Utf8JsonWriter writer, IJSObjectReference value, JsonSerializerOptions options) diff --git a/src/JSInterop/Microsoft.JSInterop/src/Implementation/JSObjectReferenceJsonWorker.cs b/src/JSInterop/Microsoft.JSInterop/src/Implementation/JSObjectReferenceJsonWorker.cs index 40bc520053aa..92ca7eab6e18 100644 --- a/src/JSInterop/Microsoft.JSInterop/src/Implementation/JSObjectReferenceJsonWorker.cs +++ b/src/JSInterop/Microsoft.JSInterop/src/Implementation/JSObjectReferenceJsonWorker.cs @@ -1,6 +1,7 @@ // Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. +using System; using System.Text.Json; namespace Microsoft.JSInterop.Implementation @@ -20,22 +21,22 @@ public static class JSObjectReferenceJsonWorker /// Reads the id for a instance. ///
/// The - /// - public static (long, long) ReadJSObjectReferenceIdentifier(ref Utf8JsonReader reader) + /// The deserialized id and length for the . + public static DeserializedJSObjectReferenceValues ReadJSObjectReference(ref Utf8JsonReader reader) { - long id = -1; - long length = -1; + long? id = null; + long? length = null; while (reader.Read() && reader.TokenType != JsonTokenType.EndObject) { if (reader.TokenType == JsonTokenType.PropertyName) { - if (id == -1 && reader.ValueTextEquals(_jsObjectIdKey.EncodedUtf8Bytes)) + if (id is null && reader.ValueTextEquals(_jsObjectIdKey.EncodedUtf8Bytes)) { reader.Read(); id = reader.GetInt64(); } - else if (length == -1 && reader.ValueTextEquals(_jsDataReferenceLengthKey.EncodedUtf8Bytes)) + else if (length is null && reader.ValueTextEquals(_jsDataReferenceLengthKey.EncodedUtf8Bytes)) { reader.Read(); length = reader.GetInt64(); @@ -51,12 +52,12 @@ public static (long, long) ReadJSObjectReferenceIdentifier(ref Utf8JsonReader re } } - if (id == -1) + if (!id.HasValue) { throw new JsonException($"Required property {_jsObjectIdKey} not found."); } - return (id, length); + return new DeserializedJSObjectReferenceValues() { Id = id.Value, Length = length }; } /// @@ -71,4 +72,20 @@ public static void WriteJSObjectReference(Utf8JsonWriter writer, JSObjectReferen writer.WriteEndObject(); } } + + /// + /// Contains the JSObjectReference.Id and Length that was deserialized + /// + public struct DeserializedJSObjectReferenceValues + { + /// + /// Can be used for the + /// + public long Id; + + /// + /// Can be used for the + /// + public long? Length; + } } diff --git a/src/JSInterop/Microsoft.JSInterop/src/Infrastructure/JSDataReferenceJsonConverter.cs b/src/JSInterop/Microsoft.JSInterop/src/Infrastructure/JSDataReferenceJsonConverter.cs index f4a85ede9e13..892a3aaac4e0 100644 --- a/src/JSInterop/Microsoft.JSInterop/src/Infrastructure/JSDataReferenceJsonConverter.cs +++ b/src/JSInterop/Microsoft.JSInterop/src/Infrastructure/JSDataReferenceJsonConverter.cs @@ -22,14 +22,14 @@ public override bool CanConvert(Type typeToConvert) public override IJSDataReference? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { - var (id, length) = JSObjectReferenceJsonWorker.ReadJSObjectReferenceIdentifier(ref reader); + var deserializedValues = JSObjectReferenceJsonWorker.ReadJSObjectReference(ref reader); - if (length == -1) + if (!deserializedValues.Length.HasValue) { throw new JsonException($"Required property __jsDataReferenceLength not found."); } - return new JSDataReference(_jsRuntime, id, length); + return new JSDataReference(_jsRuntime, deserializedValues.Id, deserializedValues.Length.Value); } public override void Write(Utf8JsonWriter writer, IJSDataReference value, JsonSerializerOptions options) diff --git a/src/JSInterop/Microsoft.JSInterop/src/Infrastructure/JSObjectReferenceJsonConverter.cs b/src/JSInterop/Microsoft.JSInterop/src/Infrastructure/JSObjectReferenceJsonConverter.cs index 39fabae778ce..bdd4df7c5f0d 100644 --- a/src/JSInterop/Microsoft.JSInterop/src/Infrastructure/JSObjectReferenceJsonConverter.cs +++ b/src/JSInterop/Microsoft.JSInterop/src/Infrastructure/JSObjectReferenceJsonConverter.cs @@ -22,8 +22,8 @@ public override bool CanConvert(Type typeToConvert) public override IJSObjectReference? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { - var (id, _) = JSObjectReferenceJsonWorker.ReadJSObjectReferenceIdentifier(ref reader); - return new JSObjectReference(_jsRuntime, id); + var deserializedValues = JSObjectReferenceJsonWorker.ReadJSObjectReference(ref reader); + return new JSObjectReference(_jsRuntime, deserializedValues.Id); } public override void Write(Utf8JsonWriter writer, IJSObjectReference value, JsonSerializerOptions options) diff --git a/src/JSInterop/Microsoft.JSInterop/src/PublicAPI.Unshipped.txt b/src/JSInterop/Microsoft.JSInterop/src/PublicAPI.Unshipped.txt index d05462b5257c..1b10329e7ce7 100644 --- a/src/JSInterop/Microsoft.JSInterop/src/PublicAPI.Unshipped.txt +++ b/src/JSInterop/Microsoft.JSInterop/src/PublicAPI.Unshipped.txt @@ -2,13 +2,17 @@ Microsoft.JSInterop.IJSDataReference Microsoft.JSInterop.IJSDataReference.Length.get -> long Microsoft.JSInterop.IJSDataReference.OpenReadStreamAsync(long maxAllowedSize = 512000, long maxBufferSize = 102400, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task! +Microsoft.JSInterop.Implementation.DeserializedJSObjectReferenceValues +Microsoft.JSInterop.Implementation.DeserializedJSObjectReferenceValues.DeserializedJSObjectReferenceValues() -> void +Microsoft.JSInterop.Implementation.DeserializedJSObjectReferenceValues.Id -> long +Microsoft.JSInterop.Implementation.DeserializedJSObjectReferenceValues.Length -> long? Microsoft.JSInterop.Implementation.JSDataReference Microsoft.JSInterop.Implementation.JSDataReference.JSDataReference(Microsoft.JSInterop.JSRuntime! jsRuntime, long id, long totalLength) -> void Microsoft.JSInterop.Implementation.JSDataReference.Length.get -> long Microsoft.JSInterop.Implementation.JSObjectReferenceJsonWorker Microsoft.JSInterop.Infrastructure.DotNetInvocationResult.ResultJson.get -> string? Microsoft.JSInterop.JSRuntime.Dispose() -> void -static Microsoft.JSInterop.Implementation.JSObjectReferenceJsonWorker.ReadJSObjectReferenceIdentifier(ref System.Text.Json.Utf8JsonReader reader) -> (long, long) +static Microsoft.JSInterop.Implementation.JSObjectReferenceJsonWorker.ReadJSObjectReference(ref System.Text.Json.Utf8JsonReader reader) -> Microsoft.JSInterop.Implementation.DeserializedJSObjectReferenceValues static Microsoft.JSInterop.Implementation.JSObjectReferenceJsonWorker.WriteJSObjectReference(System.Text.Json.Utf8JsonWriter! writer, Microsoft.JSInterop.Implementation.JSObjectReference! objectReference) -> void *REMOVED*Microsoft.JSInterop.Infrastructure.DotNetInvocationResult.DotNetInvocationResult(System.Exception! exception, string? errorKind) -> void *REMOVED*Microsoft.JSInterop.Infrastructure.DotNetInvocationResult.DotNetInvocationResult(object? result) -> void From 519f854600b256ca078fc413b3c0daa901da231d Mon Sep 17 00:00:00 2001 From: Tanay Parikh Date: Fri, 11 Jun 2021 15:46:23 -0700 Subject: [PATCH 06/37] Update JSObjectReference.cs --- .../src/Implementation/JSObjectReference.cs | 4 ---- 1 file changed, 4 deletions(-) diff --git a/src/JSInterop/Microsoft.JSInterop/src/Implementation/JSObjectReference.cs b/src/JSInterop/Microsoft.JSInterop/src/Implementation/JSObjectReference.cs index 483311290457..f4736c049d9e 100644 --- a/src/JSInterop/Microsoft.JSInterop/src/Implementation/JSObjectReference.cs +++ b/src/JSInterop/Microsoft.JSInterop/src/Implementation/JSObjectReference.cs @@ -3,8 +3,6 @@ using System; using System.Diagnostics.CodeAnalysis; -using System.IO; -using System.IO.Pipelines; using System.Threading; using System.Threading.Tasks; using static Microsoft.AspNetCore.Internal.LinkerFlags; @@ -14,8 +12,6 @@ namespace Microsoft.JSInterop.Implementation /// /// Implements functionality for . /// - // Note that the same concrete implementation can represent either an object or a data reference. Developers - // work in terms of the interfaces which indicate the set of method it's useful to call. public class JSObjectReference : IJSObjectReference { private readonly JSRuntime _jsRuntime; From b35027b9445fee982aad310c437a2d0572102a9e Mon Sep 17 00:00:00 2001 From: Tanay Parikh Date: Fri, 11 Jun 2021 16:06:16 -0700 Subject: [PATCH 07/37] Move RemoteJSDataStream Instances to RemoteJSRuntime --- .../Server/src/Circuits/CircuitHost.cs | 30 +++++++++++++++++++ .../Server/src/Circuits/RemoteJSDataStream.cs | 19 +++++------- .../Server/src/Circuits/RemoteJSRuntime.cs | 3 ++ src/Components/Server/src/ComponentHub.cs | 15 +++++++--- 4 files changed, 51 insertions(+), 16 deletions(-) diff --git a/src/Components/Server/src/Circuits/CircuitHost.cs b/src/Components/Server/src/Circuits/CircuitHost.cs index 7deecfbefb5a..68e566db57f5 100644 --- a/src/Components/Server/src/Circuits/CircuitHost.cs +++ b/src/Components/Server/src/Circuits/CircuitHost.cs @@ -2,6 +2,7 @@ // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; +using System.Buffers; using System.Collections.Generic; using System.Globalization; using System.Security.Claims; @@ -415,6 +416,27 @@ await Renderer.Dispatcher.InvokeAsync(() => } } + // SupplyJSDataChunk is used in a fire-and-forget context, so it's responsible for its own + // error handling. + internal async Task SupplyJSDataChunk(string streamId, ReadOnlySequence chunk, string error) + { + AssertInitialized(); + AssertNotDisposed(); + + try + { + await RemoteJSDataStream.SupplyData(JSRuntime, streamId, chunk, error); + } + catch (Exception ex) + { + // An error completing JS interop means that the user sent invalid data, a well-behaved + // client won't do this. + Log.SupplyJSDataChunkException(_logger, streamId, ex); + await TryNotifyClientErrorAsync(Client, GetClientErrorMessage(ex, "Invalid chunk supplied to stream.")); + UnhandledException?.Invoke(this, new UnhandledExceptionEventArgs(ex, isTerminating: false)); + } + } + // DispatchEvent is used in a fire-and-forget context, so it's responsible for its own // error handling. public async Task DispatchEvent(string eventDescriptorJson, string eventArgsJson) @@ -638,6 +660,7 @@ private static class Log private static readonly Action _endInvokeJSSucceeded; private static readonly Action _receiveByteArraySuccess; private static readonly Action _receiveByteArrayException; + private static readonly Action _supplyJSDataChunkException; private static readonly Action _dispatchEventFailedToParseEventData; private static readonly Action _dispatchEventFailedToDispatchEvent; private static readonly Action _locationChange; @@ -682,6 +705,7 @@ private static class EventIds public static readonly EventId OnRenderCompletedFailed = new EventId(212, "OnRenderCompletedFailed"); public static readonly EventId ReceiveByteArraySucceeded = new EventId(213, "ReceiveByteArraySucceeded"); public static readonly EventId ReceiveByteArrayException = new EventId(214, "ReceiveByteArrayException"); + public static readonly EventId SupplyJSDataChunkException = new EventId(215, "SupplyJSDataChunkException"); } static Log() @@ -811,6 +835,11 @@ static Log() EventIds.ReceiveByteArrayException, "The ReceiveByteArray call with id '{id}' failed."); + _supplyJSDataChunkException = LoggerMessage.Define( + LogLevel.Debug, + EventIds.SupplyJSDataChunkException, + "The SupplyJSDataChunk call with stream id '{streamId}' failed."); + _dispatchEventFailedToParseEventData = LoggerMessage.Define( LogLevel.Debug, EventIds.DispatchEventFailedToParseEventData, @@ -875,6 +904,7 @@ public static void CircuitHandlerFailed(ILogger logger, CircuitHandler handler, public static void EndInvokeJSSucceeded(ILogger logger, long asyncCall) => _endInvokeJSSucceeded(logger, asyncCall, null); internal static void ReceiveByteArraySuccess(ILogger logger, long id) => _receiveByteArraySuccess(logger, id, null); internal static void ReceiveByteArrayException(ILogger logger, long id, Exception ex) => _receiveByteArrayException(logger, id, ex); + internal static void SupplyJSDataChunkException(ILogger logger, string streamId, Exception ex) => _supplyJSDataChunkException(logger, streamId, ex); public static void DispatchEventFailedToParseEventData(ILogger logger, Exception ex) => _dispatchEventFailedToParseEventData(logger, ex); public static void DispatchEventFailedToDispatchEvent(ILogger logger, string eventHandlerId, Exception ex) => _dispatchEventFailedToDispatchEvent(logger, eventHandlerId ?? "", ex); diff --git a/src/Components/Server/src/Circuits/RemoteJSDataStream.cs b/src/Components/Server/src/Circuits/RemoteJSDataStream.cs index f62372cd6325..ac9cbfc03425 100644 --- a/src/Components/Server/src/Circuits/RemoteJSDataStream.cs +++ b/src/Components/Server/src/Circuits/RemoteJSDataStream.cs @@ -14,12 +14,7 @@ namespace Microsoft.AspNetCore.Components.Server.Circuits { internal class RemoteJSDataStream : Stream { - // Concerns with static `Instances`? Malicious actor could hijack another user's - // stream by (improbably) guessing the GUID. - // Maybe we put this in the JSRuntime for curcuit isolation? Would increate overhead as - // we'd have to go through CircuitHost, DotNetDispatcher and so on. - private readonly static Dictionary Instances = new(); - private readonly JSRuntime _runtime; + private readonly RemoteJSRuntime _runtime; private readonly Guid _streamId; private readonly long _totalLength; private readonly CancellationToken _cancellationToken; @@ -27,9 +22,9 @@ internal class RemoteJSDataStream : Stream private readonly Pipe _pipe; private long _bytesRead; - public static Task SupplyData(string streamId, ReadOnlySequence chunk, string error) + public static Task SupplyData(RemoteJSRuntime runtime, string streamId, ReadOnlySequence chunk, string error) { - if (!Instances.TryGetValue(Guid.Parse(streamId), out var instance)) + if (!runtime.RemoteJSDataStreamInstances.TryGetValue(Guid.Parse(streamId), out var instance)) { // There is no data stream with the given identifier. It may have already been disposed. // We return silently as we still expect a couple of SupplyData calls after disposal IFF the RemoteJSDataStream was cancelled. @@ -40,7 +35,7 @@ public static Task SupplyData(string streamId, ReadOnlySequence chunk, str } public static async Task CreateRemoteJSDataStreamAsync( - JSRuntime runtime, + RemoteJSRuntime runtime, IJSDataReference jsDataReference, long totalLength, long maxBufferSize, @@ -54,7 +49,7 @@ public static async Task CreateRemoteJSDataStreamAsync( } private RemoteJSDataStream( - JSRuntime runtime, + RemoteJSRuntime runtime, Guid streamId, long totalLength, long maxBufferSize, @@ -65,7 +60,7 @@ private RemoteJSDataStream( _totalLength = totalLength; _cancellationToken = cancellationToken; - Instances.Add(_streamId, this); + _runtime.RemoteJSDataStreamInstances.Add(_streamId, this); _pipe = new Pipe(new PipeOptions(pauseWriterThreshold: maxBufferSize, resumeWriterThreshold: maxBufferSize)); _pipeReaderStream = _pipe.Reader.AsStream(); @@ -181,7 +176,7 @@ protected override void Dispose(bool disposing) if (disposing) { - Instances.Remove(_streamId); + _runtime.RemoteJSDataStreamInstances.Remove(_streamId); } } } diff --git a/src/Components/Server/src/Circuits/RemoteJSRuntime.cs b/src/Components/Server/src/Circuits/RemoteJSRuntime.cs index c6de1ff4776d..13bbb5bb62ef 100644 --- a/src/Components/Server/src/Circuits/RemoteJSRuntime.cs +++ b/src/Components/Server/src/Circuits/RemoteJSRuntime.cs @@ -2,6 +2,7 @@ // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; +using System.Collections.Generic; using System.IO; using System.Text.Json; using System.Threading; @@ -23,6 +24,8 @@ internal class RemoteJSRuntime : JSRuntime private readonly long _maximumIncomingBytes; private int _byteArraysToBeRevivedTotalBytes; + internal readonly Dictionary RemoteJSDataStreamInstances = new(); + public ElementReferenceContext ElementReferenceContext { get; } public bool IsInitialized => _clientProxy is not null; diff --git a/src/Components/Server/src/ComponentHub.cs b/src/Components/Server/src/ComponentHub.cs index 3bf3a8613a5f..f7d636be3434 100644 --- a/src/Components/Server/src/ComponentHub.cs +++ b/src/Components/Server/src/ComponentHub.cs @@ -224,6 +224,17 @@ public async ValueTask ReceiveByteArray(int id, byte[] data) await circuitHost.ReceiveByteArray(id, data); } + public async Task SupplyJSDataChunk(string streamId, ReadOnlySequence chunk, string error) + { + var circuitHost = await GetActiveCircuitAsync(); + if (circuitHost == null) + { + return; + } + + await circuitHost.SupplyJSDataChunk(streamId, chunk, error); + } + public async ValueTask DispatchBrowserEvent(string eventDescriptor, string eventArgs) { var circuitHost = await GetActiveCircuitAsync(); @@ -247,10 +258,6 @@ public async ValueTask OnRenderCompleted(long renderId, string errorMessageOrNul _ = circuitHost.OnRenderCompletedAsync(renderId, errorMessageOrNull); } - [System.Diagnostics.CodeAnalysis.SuppressMessage("Performance", "CA1822:Mark members as static", Justification = "HubReflectionHelper.GetHubMethods is configured to only pickup Instance methods.")] - public Task SupplyJSDataChunk(string streamId, ReadOnlySequence chunk, string error) - => RemoteJSDataStream.SupplyData(streamId, chunk, error); - public async ValueTask OnLocationChanged(string uri, bool intercepted) { var circuitHost = await GetActiveCircuitAsync(); From 46f4ddfca8fb5449ead9489327555d89ddac276f Mon Sep 17 00:00:00 2001 From: Tanay Parikh Date: Fri, 11 Jun 2021 16:20:17 -0700 Subject: [PATCH 08/37] Cancel using SupplyJSDataChunk --- .../Server/src/Circuits/CircuitHost.cs | 5 ++-- .../Server/src/Circuits/RemoteJSDataStream.cs | 16 ++++------- src/Components/Server/src/ComponentHub.cs | 6 ++--- .../Web.JS/dist/Release/blazor.server.js | 2 +- src/Components/Web.JS/src/Boot.Server.ts | 27 +++++-------------- src/Components/Web.JS/src/GlobalExports.ts | 1 - 6 files changed, 18 insertions(+), 39 deletions(-) diff --git a/src/Components/Server/src/Circuits/CircuitHost.cs b/src/Components/Server/src/Circuits/CircuitHost.cs index 68e566db57f5..31cebbf973e3 100644 --- a/src/Components/Server/src/Circuits/CircuitHost.cs +++ b/src/Components/Server/src/Circuits/CircuitHost.cs @@ -418,14 +418,14 @@ await Renderer.Dispatcher.InvokeAsync(() => // SupplyJSDataChunk is used in a fire-and-forget context, so it's responsible for its own // error handling. - internal async Task SupplyJSDataChunk(string streamId, ReadOnlySequence chunk, string error) + internal async Task SupplyJSDataChunk(string streamId, ReadOnlySequence chunk, string error) { AssertInitialized(); AssertNotDisposed(); try { - await RemoteJSDataStream.SupplyData(JSRuntime, streamId, chunk, error); + return await RemoteJSDataStream.SupplyData(JSRuntime, streamId, chunk, error); } catch (Exception ex) { @@ -434,6 +434,7 @@ internal async Task SupplyJSDataChunk(string streamId, ReadOnlySequence ch Log.SupplyJSDataChunkException(_logger, streamId, ex); await TryNotifyClientErrorAsync(Client, GetClientErrorMessage(ex, "Invalid chunk supplied to stream.")); UnhandledException?.Invoke(this, new UnhandledExceptionEventArgs(ex, isTerminating: false)); + return false; } } diff --git a/src/Components/Server/src/Circuits/RemoteJSDataStream.cs b/src/Components/Server/src/Circuits/RemoteJSDataStream.cs index ac9cbfc03425..0c8490762b36 100644 --- a/src/Components/Server/src/Circuits/RemoteJSDataStream.cs +++ b/src/Components/Server/src/Circuits/RemoteJSDataStream.cs @@ -3,7 +3,6 @@ using System; using System.Buffers; -using System.Collections.Generic; using System.IO; using System.IO.Pipelines; using System.Threading; @@ -22,16 +21,17 @@ internal class RemoteJSDataStream : Stream private readonly Pipe _pipe; private long _bytesRead; - public static Task SupplyData(RemoteJSRuntime runtime, string streamId, ReadOnlySequence chunk, string error) + public static async Task SupplyData(RemoteJSRuntime runtime, string streamId, ReadOnlySequence chunk, string error) { if (!runtime.RemoteJSDataStreamInstances.TryGetValue(Guid.Parse(streamId), out var instance)) { // There is no data stream with the given identifier. It may have already been disposed. - // We return silently as we still expect a couple of SupplyData calls after disposal IFF the RemoteJSDataStream was cancelled. - return Task.CompletedTask; + // We notify JS that the stream has been cancelled/disposed. + return false; } - return instance.SupplyData(chunk, error); + await instance.SupplyData(chunk, error); + return true; } public static async Task CreateRemoteJSDataStreamAsync( @@ -168,12 +168,6 @@ public override async ValueTask ReadAsync(Memory buffer, Cancellation protected override void Dispose(bool disposing) { - // Fire & forget a notification to the JSRuntime to stop sending additional chunks. - if (_cancellationToken.IsCancellationRequested) - { - _ = Task.Run(() => _runtime.InvokeVoidAsync("Blazor._internal.cancelJSDataStream", _streamId)); - } - if (disposing) { _runtime.RemoteJSDataStreamInstances.Remove(_streamId); diff --git a/src/Components/Server/src/ComponentHub.cs b/src/Components/Server/src/ComponentHub.cs index f7d636be3434..a32f71fb0a5f 100644 --- a/src/Components/Server/src/ComponentHub.cs +++ b/src/Components/Server/src/ComponentHub.cs @@ -224,15 +224,15 @@ public async ValueTask ReceiveByteArray(int id, byte[] data) await circuitHost.ReceiveByteArray(id, data); } - public async Task SupplyJSDataChunk(string streamId, ReadOnlySequence chunk, string error) + public async Task SupplyJSDataChunk(string streamId, ReadOnlySequence chunk, string error) { var circuitHost = await GetActiveCircuitAsync(); if (circuitHost == null) { - return; + return false; } - await circuitHost.SupplyJSDataChunk(streamId, chunk, error); + return await circuitHost.SupplyJSDataChunk(streamId, chunk, error); } public async ValueTask DispatchBrowserEvent(string eventDescriptor, string eventArgs) diff --git a/src/Components/Web.JS/dist/Release/blazor.server.js b/src/Components/Web.JS/dist/Release/blazor.server.js index 45d2f72d33c9..91816a7857b7 100644 --- a/src/Components/Web.JS/dist/Release/blazor.server.js +++ b/src/Components/Web.JS/dist/Release/blazor.server.js @@ -1 +1 @@ -(()=>{"use strict";var e,t,n;!function(e){window.DotNet=e;const t=[],n=new Map;class r{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 o="__jsObjectId",i={},s={0:new r(window)};s[0]._cachedFunctions.set("import",(e=>("string"==typeof e&&e.startsWith("./")&&(e=document.baseURI+e.substr(2)),import(e))));let a,c=1,l=1,h=null;function u(e){t.push(e)}function d(e){if(e&&"object"==typeof e){s[l]=new r(e);let t={[o]:l};return e.buffer instanceof ArrayBuffer&&void 0!==e.byteLength&&(t.__jsDataReferenceLength=e.byteLength),l++,t}throw new Error(`Cannot create a JSObjectReference from the value '${e}'.`)}function p(e){return e?JSON.parse(e,((e,n)=>t.reduce(((t,n)=>n(e,t)),n))):null}function f(e,t,n,r){const o=m();if(o.invokeDotNetFromJS){const i=I(r),s=o.invokeDotNetFromJS(e,t,n,i);return s?p(s):null}throw new Error("The current dispatcher does not support synchronous calls from JS to .NET. Use invokeMethodAsync instead.")}function g(e,t,n,r){if(e&&n)throw new Error(`For instance method calls, assemblyName should be null. Received '${e}'.`);const o=c++,s=new Promise(((e,t)=>{i[o]={resolve:e,reject:t}}));try{const i=I(r);m().beginInvokeDotNetFromJS(o,e,t,n,i)}catch(e){y(o,!1,e)}return s}function m(){if(null!==h)return h;throw new Error("No .NET call dispatcher has been set.")}function y(e,t,n){if(!i.hasOwnProperty(e))throw new Error(`There is no pending async call with ID ${e}.`);const r=i[e];delete i[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 v(e,t){let n=s[t];if(n)return n.findFunction(e);throw new Error(`JS object instance with ID ${t} does not exist (has it been disposed?).`)}function b(e){delete s[e]}e.attachDispatcher=function(e){h=e},e.attachReviver=u,e.invokeMethod=function(e,t,...n){return f(e,t,null,n)},e.invokeMethodAsync=function(e,t,...n){return g(e,t,null,n)},e.createJSObjectReference=d,e.disposeJSObjectReference=function(e){const t=e&&e.__jsObjectId;"number"==typeof t&&b(t)},function(e){e[e.Default=0]="Default",e[e.JSObjectReference=1]="JSObjectReference"}(a=e.JSCallResultType||(e.JSCallResultType={})),e.jsCallDispatcher={findJSFunction:v,disposeJSObjectReferenceById:b,invokeJSFromDotNet:(e,t,n,r)=>{const o=S(v(e,r).apply(null,p(t)),n);return null==o?null:I(o)},beginInvokeJSFromDotNet:(e,t,n,r,o)=>{const i=new Promise((e=>{e(v(t,o).apply(null,p(n)))}));e&&i.then((t=>m().endInvokeJSFromDotNet(e,!0,I([e,!0,S(t,r)]))),(t=>m().endInvokeJSFromDotNet(e,!1,JSON.stringify([e,!1,w(t)]))))},endInvokeDotNetFromJS:(e,t,n)=>{const r=t?p(n):new Error(n);y(parseInt(e),t,r)},receiveByteArray:(e,t)=>{n.set(e,t)}};class _{constructor(e){this._id=e}invokeMethod(e,...t){return f(null,e,this._id,t)}invokeMethodAsync(e,...t){return g(null,e,this._id,t)}dispose(){g(null,"__Dispose",this._id,null).catch((e=>console.error(e)))}serializeAsArg(){return{__dotNetObject:this._id}}}const E="__byte[]";function S(e,t){switch(t){case a.Default:return e;case a.JSObjectReference:return d(e);default:throw new Error(`Invalid JS call result type '${t}'.`)}}u((function(e,t){if(t&&"object"==typeof t){if(t.hasOwnProperty("__dotNetObject"))return new _(t.__dotNetObject);if(t.hasOwnProperty(o)){const e=t.__jsObjectId,n=s[e];if(n)return n.getWrappedObject();throw new Error(`JS object instance with Id '${e}' does not exist. It may have been disposed.`)}if(t.hasOwnProperty(E)){const e=t["__byte[]"],r=n.get(e);if(void 0===r)throw new Error(`Byte array index '${e}' does not exist.`);return r}}return t}));let C=0;function I(e){return C=0,JSON.stringify(e,k)}function k(e,t){if(t instanceof _)return t.serializeAsArg();if(t instanceof Uint8Array){h.sendByteArray(C,t);const e={[E]:C};return C++,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"}(n||(n={}));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}}let o;function i(e,t){if(!o)throw new Error("eventDispatcher not initialized. Call 'setEventDispatcher' to configure it.");o(e,t)}const s=new Map,a=new Map,c={createEventArgs:()=>({})},l=[];function h(e){return s.get(e)}function u(e){const t=s.get(e);return(null==t?void 0:t.browserEventName)||e}function d(e,t){e.forEach((e=>s.set(e,t)))}function p(e){const t=[];for(let n=0;n{return{...f(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}}),d(["focus","blur","focusin","focusout"],c),d(["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};var t}}),d(["contextmenu","click","mouseover","mouseout","mousemove","mousedown","mouseup","dblclick"],{createEventArgs:e=>f(e)}),d(["error"],{createEventArgs:e=>{return{message:(t=e).message,filename:t.filename,lineno:t.lineno,colno:t.colno};var t}}),d(["loadstart","timeout","abort","load","loadend","progress"],{createEventArgs:e=>{return{lengthComputable:(t=e).lengthComputable,loaded:t.loaded,total:t.total};var t}}),d(["touchcancel","touchend","touchmove","touchenter","touchleave","touchstart"],{createEventArgs:e=>{return{detail:(t=e).detail,touches:p(t.touches),targetTouches:p(t.targetTouches),changedTouches:p(t.changedTouches),ctrlKey:t.ctrlKey,shiftKey:t.shiftKey,altKey:t.altKey,metaKey:t.metaKey,type:t.type};var t}}),d(["gotpointercapture","lostpointercapture","pointercancel","pointerdown","pointerenter","pointerleave","pointermove","pointerout","pointerover","pointerup"],{createEventArgs:e=>{return{...f(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}}),d(["wheel","mousewheel"],{createEventArgs:e=>{return{...f(t=e),deltaX:t.deltaX,deltaY:t.deltaY,deltaZ:t.deltaZ,deltaMode:t.deltaMode};var t}}),d(["toggle"],c);const g=["date","datetime-local","month","time","week"],m=E(["abort","blur","change","error","focus","load","loadend","loadstart","mouseenter","mouseleave","progress","reset","scroll","submit","unload","toggle","DOMNodeInsertedIntoDocument","DOMNodeRemovedFromDocument"]),y={submit:!0},w=E(["click","dblclick","mousedown","mousemove","mouseup"]);class v{constructor(e){this.browserRendererId=e,this.afterClickCallbacks=[];const t=++v.nextEventDelegatorId;this.eventsCollectionKey=`_blazorEvents_${t}`,this.eventInfoStore=new b(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,a.get(n));var n;t&&t.forEach((t=>this.dispatchGlobalEventToAllElements(t,e))),"click"===e.type&&this.afterClickCallbacks.forEach((t=>t(e)))}dispatchGlobalEventToAllElements(e,t){let n=t.target,o=null,s=!1;const a=m.hasOwnProperty(e);let c=!1;for(;n;){const d=this.getEventHandlerInfosForElement(n,!1);if(d){const a=d.getHandler(e);if(a&&(l=n,u=t.type,!((l instanceof HTMLButtonElement||l instanceof HTMLInputElement||l instanceof HTMLTextAreaElement||l instanceof HTMLSelectElement)&&w.hasOwnProperty(u)&&l.disabled))){if(!s){const n=h(e);o=(null==n?void 0:n.createEventArgs)?n.createEventArgs(t):{},s=!0}y.hasOwnProperty(t.type)&&t.preventDefault(),i({browserRendererId:this.browserRendererId,eventHandlerId:a.eventHandlerId,eventName:e,eventFieldInfo:r.fromEvent(a.renderingComponentId,t)},o)}d.stopPropagation(e)&&(c=!0),d.preventDefault(e)&&t.preventDefault()}n=a||c?null:n.parentElement}var l,u}getEventHandlerInfosForElement(e,t){return e.hasOwnProperty(this.eventsCollectionKey)?e[this.eventsCollectionKey]:t?e[this.eventsCollectionKey]=new _:null}}v.nextEventDelegatorId=0;class b{constructor(e){this.globalListener=e,this.infosByEventHandlerId={},this.countByEventName={},l.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=u(e),this.countByEventName.hasOwnProperty(e))this.countByEventName[e]++;else{this.countByEventName[e]=1;const t=m.hasOwnProperty(e);document.addEventListener(e,this.globalListener,t)}}update(e,t){if(this.infosByEventHandlerId.hasOwnProperty(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=u(t.eventName);0==--this.countByEventName[n]&&(delete this.countByEventName[n],document.removeEventListener(n,this.globalListener))}return t}handleEventNameAliasAdded(e,t){if(this.countByEventName.hasOwnProperty(e)){const n=this.countByEventName[e];delete this.countByEventName[e],document.removeEventListener(e,this.globalListener),this.addGlobalListener(t),this.countByEventName[t]+=n-1}}}class _{constructor(){this.handlers={},this.preventDefaultFlags=null,this.stopPropagationFlags=null}getHandler(e){return this.handlers.hasOwnProperty(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 E(e){const t={};return e.forEach((e=>{t[e]=!0})),t}const S=H("_blazorLogicalChildren"),C=H("_blazorLogicalParent"),I=H("_blazorLogicalEnd");function k(e,t){if(e.childNodes.length>0&&!t)throw new Error("New logical elements must start empty, or allowExistingContents must be true");return S in e||(e[S]=[]),e}function T(e,t){const n=document.createComment("!");return D(n,e,t),n}function D(e,t,n){const r=e;if(e instanceof Comment&&A(r)&&A(r).length>0)throw new Error("Not implemented: inserting non-empty logical container");if(R(r))throw new Error("Not implemented: moving existing logical children");const o=A(t);if(n0;)x(n,0)}const r=n;r.parentNode.removeChild(r)}function R(e){return e[C]||null}function P(e,t){return A(e)[t]}function U(e){var t=B(e);return"http://www.w3.org/2000/svg"===t.namespaceURI&&"foreignObject"!==t.tagName}function A(e){return e[S]}function N(e,t){const n=A(e);t.forEach((e=>{e.moveRangeStart=n[e.fromSiblingIndex],e.moveRangeEnd=M(e.moveRangeStart)})),t.forEach((t=>{const r=t.moveToBeforeMarker=document.createComment("marker"),o=n[t.toSiblingIndex+1];o?o.parentNode.insertBefore(r,o):L(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 B(e){if(e instanceof Element)return e;if(e instanceof Comment)return e.parentNode;throw new Error("Not a valid logical element")}function $(e){const t=A(R(e));return t[Array.prototype.indexOf.call(t,e)+1]||null}function L(e,t){if(t instanceof Element)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=$(t);n?n.parentNode.insertBefore(e,n):L(e,R(t))}}}function M(e){if(e instanceof Element)return e;const t=$(e);if(t)return t.previousSibling;{const t=R(e);return t instanceof Element?t.lastChild:M(t)}}function H(e){return"function"==typeof Symbol?Symbol():e}function O(e){return`_bl_${e}`}e.attachReviver(((e,t)=>t&&"object"==typeof t&&t.hasOwnProperty("__internalId")&&"string"==typeof t.__internalId?function(e){const t=`[${O(e)}]`;return document.querySelector(t)}(t.__internalId):t));const F="_blazorSelectValue",j=document.createElement("template"),W=document.createElementNS("http://www.w3.org/2000/svg","g"),z={},q="__internal_",J="preventDefault_",K="stopPropagation_";class V{constructor(e){this.childComponentLocations={},this.eventDelegator=new v(e),this.eventDelegator.notifyAfterClick((e=>{if(!ee)return;if(0!==e.button||function(e){return e.ctrlKey||e.shiftKey||e.altKey||e.metaKey}(e))return;if(e.defaultPrevented)return;const t=function(e){const t=!window._blazorDisableComposedPath&&e.composedPath&&e.composedPath();if(t){for(let e=0;ese(!1))))},enableNavigationInterception:function(){ee=!0},navigateTo:oe,getBaseURI:()=>document.baseURI,getLocationHref:()=>location.href};function oe(e,t,n=!1){const r=ce(e);if(!t&&he(r))ie(r,!1,n);else if(t&&location.href===e){const t=e+"?";history.replaceState(null,"",t),location.replace(e)}else n?history.replaceState(null,"",r):location.href=e}function ie(e,t,n=!1){Z=!0,n?history.replaceState(null,"",e):history.pushState(null,"",e),se(t)}async function se(e){ne&&await ne(location.href,e)}let ae;function ce(e){return ae=ae||document.createElement("a"),ae.href=e,ae.href}function le(e,t){return e?e.tagName===t?e:le(e.parentElement,t):null}function he(e){const t=(n=document.baseURI).substr(0,n.lastIndexOf("/")+1);var n;return e.startsWith(t)}const ue={init:function(e,t,n,r=50){const o=pe(t);(o||document.documentElement).style.overflowAnchor="none";const i=new IntersectionObserver((function(r){r.forEach((r=>{var o;if(!r.isIntersecting)return;const i=t.getBoundingClientRect(),s=n.getBoundingClientRect().top-i.bottom,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`});i.observe(t),i.observe(n);const s=c(t),a=c(n);function c(e){const t=new MutationObserver((()=>{i.unobserve(e),i.observe(e)}));return t.observe(e,{attributes:!0}),t}de[e._id]={intersectionObserver:i,mutationObserverBefore:s,mutationObserverAfter:a}},dispose:function(e){const t=de[e._id];t&&(t.intersectionObserver.disconnect(),t.mutationObserverBefore.disconnect(),t.mutationObserverAfter.disconnect(),e.dispose(),delete de[e._id])}},de={};function pe(e){return e?"visible"!==getComputedStyle(e).overflowY?e:pe(e.parentElement):null}const fe={navigateTo:oe,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=a.get(t.browserEventName);n?n.push(e):a.set(t.browserEventName,[e]),l.forEach((n=>n(e,t.browserEventName)))}s.set(e,t)},_internal:{navigationManager:re,domWrapper:{focus:function(e,t){if(!(e instanceof HTMLElement))throw new Error("Unable to focus an invalid element.");e.focus({preventScroll:t})}},Virtualize:ue}};window.Blazor=fe;const ge=[0,2e3,1e4,3e4,null];class me{constructor(e){this._retryDelays=void 0!==e?[...e,null]:ge}nextRetryDelayInMilliseconds(e){return this._retryDelays[e.previousRetryCount]}}class ye extends Error{constructor(e,t){const n=new.target.prototype;super(`${e}: Status code '${t}'`),this.statusCode=t,this.__proto__=n}}class we extends Error{constructor(e="A timeout occurred."){const t=new.target.prototype;super(e),this.__proto__=t}}class ve extends Error{constructor(e="An abort occurred."){const t=new.target.prototype;super(e),this.__proto__=t}}class be{constructor(e,t,n){this.statusCode=e,this.statusText=t,this.content=n}}class _e{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""}}var Ee,Se,Ce,Ie,ke;!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"}(Ee||(Ee={}));class Te extends _e{constructor(e){if(super(),this._logger=e,"undefined"==typeof fetch){const e=require;this._jar=new(e("tough-cookie").CookieJar),this._fetchType=e("node-fetch"),this._fetchType=e("fetch-cookie")(this._fetchType,this._jar),this._abortControllerType=e("abort-controller")}else this._fetchType=fetch.bind(self),this._abortControllerType=AbortController}async send(e){if(e.abortSignal&&e.abortSignal.aborted)throw new ve;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 ve});let r,o=null;if(e.timeout){const r=e.timeout;o=setTimeout((()=>{t.abort(),this._logger.log(Ee.Warning,"Timeout from HTTP request."),n=new we}),r)}try{r=await this._fetchType(e.url,{body:e.content,cache:"no-cache",credentials:!0===e.withCredentials?"include":"same-origin",headers:{"Content-Type":"text/plain;charset=UTF-8","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(Ee.Warning,`Error from HTTP request. ${e}.`),e}finally{o&&clearTimeout(o),e.abortSignal&&(e.abortSignal.onabort=null)}if(!r.ok){const e=await De(r,"text");throw new ye(e||r.statusText,r.status)}const i=De(r,e.responseType),s=await i;return new be(r.status,r.statusText,s)}getCookieString(e){return""}}function De(e,t){let n;switch(t){case"arraybuffer":n=e.arrayBuffer();break;case"text":n=e.text();break;case"blob":case"document":case"json":throw new Error(`${t} is not supported.`);default:n=e.text()}return n}class xe extends _e{constructor(e){super(),this._logger=e}send(e){return e.abortSignal&&e.abortSignal.aborted?Promise.reject(new ve):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"),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 ve)}),e.timeout&&(r.timeout=e.timeout),r.onload=()=>{e.abortSignal&&(e.abortSignal.onabort=null),r.status>=200&&r.status<300?t(new be(r.status,r.statusText,r.response||r.responseText)):n(new ye(r.response||r.responseText||r.statusText,r.status))},r.onerror=()=>{this._logger.log(Ee.Warning,`Error from HTTP request. ${r.status}: ${r.statusText}.`),n(new ye(r.statusText,r.status))},r.ontimeout=()=>{this._logger.log(Ee.Warning,"Timeout from HTTP request."),n(new we)},r.send(e.content||"")})):Promise.reject(new Error("No url defined.")):Promise.reject(new Error("No method defined."))}}class Re extends _e{constructor(e){if(super(),"undefined"!=typeof fetch)this._httpClient=new Te(e);else{if("undefined"==typeof XMLHttpRequest)throw new Error("No usable HttpClient found.");this._httpClient=new xe(e)}}send(e){return e.abortSignal&&e.abortSignal.aborted?Promise.reject(new ve):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)}}class Pe{}Pe.Authorization="Authorization",Pe.Cookie="Cookie",function(e){e[e.None=0]="None",e[e.WebSockets=1]="WebSockets",e[e.ServerSentEvents=2]="ServerSentEvents",e[e.LongPolling=4]="LongPolling"}(Se||(Se={})),function(e){e[e.Text=1]="Text",e[e.Binary=2]="Binary"}(Ce||(Ce={}));class Ue{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 Ae{constructor(){}log(e,t){}}Ae.instance=new Ae;class Ne{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 Be{static get isBrowser(){return"object"==typeof window}static get isWebWorker(){return"object"==typeof self&&"importScripts"in self}static get isNode(){return!this.isBrowser&&!this.isWebWorker}}function $e(e,t){let n="";return Le(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 Le(e){return e&&"undefined"!=typeof ArrayBuffer&&(e instanceof ArrayBuffer||e.constructor&&"ArrayBuffer"===e.constructor.name)}async function Me(e,t,n,r,o,i,s,a,c){let l={};if(o){const e=await o();e&&(l={Authorization:`Bearer ${e}`})}const[h,u]=Fe();l[h]=u,e.log(Ee.Trace,`(${t} transport) sending data. ${$e(i,s)}.`);const d=Le(i)?"arraybuffer":"text",p=await n.post(r,{content:i,headers:{...l,...c},responseType:d,withCredentials:a});e.log(Ee.Trace,`(${t} transport) request complete. Response status: ${p.statusCode}.`)}class He{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 Oe{constructor(e){this._minLevel=e,this.out=console}log(e,t){if(e>=this._minLevel){const n=`[${(new Date).toISOString()}] ${Ee[e]}: ${t}`;switch(e){case Ee.Critical:case Ee.Error:this.out.error(n);break;case Ee.Warning:this.out.warn(n);break;case Ee.Information:this.out.info(n);break;default:this.out.log(n)}}}}function Fe(){let e="X-SignalR-User-Agent";return Be.isNode&&(e="User-Agent"),[e,je("0.0.0-DEV_BUILD",We(),Be.isNode?"NodeJS":"Browser",ze())]}function je(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 We(){if(!Be.isNode)return"";switch(process.platform){case"win32":return"Windows NT";case"darwin":return"macOS";case"linux":return"Linux";default:return process.platform}}function ze(){if(Be.isNode)return process.versions.node}class qe{constructor(e,t,n,r,o,i){this._httpClient=e,this._accessTokenFactory=t,this._logger=n,this._pollAbort=new Ue,this._logMessageContent=r,this._withCredentials=o,this._headers=i,this._running=!1,this.onreceive=null,this.onclose=null}get pollAborted(){return this._pollAbort.aborted}async connect(e,t){if(Ne.isRequired(e,"url"),Ne.isRequired(t,"transferFormat"),Ne.isIn(t,Ce,"transferFormat"),this._url=e,this._logger.log(Ee.Trace,"(LongPolling transport) Connecting."),t===Ce.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]=Fe(),o={[n]:r,...this._headers},i={abortSignal:this._pollAbort.signal,headers:o,timeout:1e5,withCredentials:this._withCredentials};t===Ce.Binary&&(i.responseType="arraybuffer");const s=await this._getAccessToken();this._updateHeaderToken(i,s);const a=`${e}&_=${Date.now()}`;this._logger.log(Ee.Trace,`(LongPolling transport) polling: ${a}.`);const c=await this._httpClient.get(a,i);200!==c.statusCode?(this._logger.log(Ee.Error,`(LongPolling transport) Unexpected response code: ${c.statusCode}.`),this._closeError=new ye(c.statusText||"",c.statusCode),this._running=!1):this._running=!0,this._receiving=this._poll(this._url,i)}async _getAccessToken(){return this._accessTokenFactory?await this._accessTokenFactory():null}_updateHeaderToken(e,t){e.headers||(e.headers={}),t?e.headers[Pe.Authorization]=`Bearer ${t}`:e.headers[Pe.Authorization]&&delete e.headers[Pe.Authorization]}async _poll(e,t){try{for(;this._running;){const n=await this._getAccessToken();this._updateHeaderToken(t,n);try{const n=`${e}&_=${Date.now()}`;this._logger.log(Ee.Trace,`(LongPolling transport) polling: ${n}.`);const r=await this._httpClient.get(n,t);204===r.statusCode?(this._logger.log(Ee.Information,"(LongPolling transport) Poll terminated by server."),this._running=!1):200!==r.statusCode?(this._logger.log(Ee.Error,`(LongPolling transport) Unexpected response code: ${r.statusCode}.`),this._closeError=new ye(r.statusText||"",r.statusCode),this._running=!1):r.content?(this._logger.log(Ee.Trace,`(LongPolling transport) data received. ${$e(r.content,this._logMessageContent)}.`),this.onreceive&&this.onreceive(r.content)):this._logger.log(Ee.Trace,"(LongPolling transport) Poll timed out, reissuing.")}catch(e){this._running?e instanceof we?this._logger.log(Ee.Trace,"(LongPolling transport) Poll timed out, reissuing."):(this._closeError=e,this._running=!1):this._logger.log(Ee.Trace,`(LongPolling transport) Poll errored after shutdown: ${e.message}`)}}}finally{this._logger.log(Ee.Trace,"(LongPolling transport) Polling complete."),this.pollAborted||this._raiseOnClose()}}async send(e){return this._running?Me(this._logger,"LongPolling",this._httpClient,this._url,this._accessTokenFactory,e,this._logMessageContent,this._withCredentials,this._headers):Promise.reject(new Error("Cannot send until the transport is connected"))}async stop(){this._logger.log(Ee.Trace,"(LongPolling transport) Stopping polling."),this._running=!1,this._pollAbort.abort();try{await this._receiving,this._logger.log(Ee.Trace,`(LongPolling transport) sending DELETE request to ${this._url}.`);const e={},[t,n]=Fe();e[t]=n;const r={headers:{...e,...this._headers},withCredentials:this._withCredentials},o=await this._getAccessToken();this._updateHeaderToken(r,o),await this._httpClient.delete(this._url,r),this._logger.log(Ee.Trace,"(LongPolling transport) DELETE request sent.")}finally{this._logger.log(Ee.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(Ee.Trace,e),this.onclose(this._closeError)}}}class Je{constructor(e,t,n,r,o,i,s){this._httpClient=e,this._accessTokenFactory=t,this._logger=n,this._logMessageContent=r,this._withCredentials=i,this._eventSourceConstructor=o,this._headers=s,this.onreceive=null,this.onclose=null}async connect(e,t){if(Ne.isRequired(e,"url"),Ne.isRequired(t,"transferFormat"),Ne.isIn(t,Ce,"transferFormat"),this._logger.log(Ee.Trace,"(SSE transport) Connecting."),this._url=e,this._accessTokenFactory){const t=await this._accessTokenFactory();t&&(e+=(e.indexOf("?")<0?"?":"&")+`access_token=${encodeURIComponent(t)}`)}return new Promise(((n,r)=>{let o,i=!1;if(t===Ce.Text){if(Be.isBrowser||Be.isWebWorker)o=new this._eventSourceConstructor(e,{withCredentials:this._withCredentials});else{const t=this._httpClient.getCookieString(e),n={};n.Cookie=t;const[r,i]=Fe();n[r]=i,o=new this._eventSourceConstructor(e,{withCredentials:this._withCredentials,headers:{...n,...this._headers}})}try{o.onmessage=e=>{if(this.onreceive)try{this._logger.log(Ee.Trace,`(SSE transport) data received. ${$e(e.data,this._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(Ee.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?Me(this._logger,"SSE",this._httpClient,this._url,this._accessTokenFactory,e,this._logMessageContent,this._withCredentials,this._headers):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 Ke{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){if(Ne.isRequired(e,"url"),Ne.isRequired(t,"transferFormat"),Ne.isIn(t,Ce,"transferFormat"),this._logger.log(Ee.Trace,"(WebSockets transport) Connecting."),this._accessTokenFactory){const t=await this._accessTokenFactory();t&&(e+=(e.indexOf("?")<0?"?":"&")+`access_token=${encodeURIComponent(t)}`)}return new Promise(((n,r)=>{let o;e=e.replace(/^http/,"ws"),this._httpClient.getCookieString(e);let i=!1;o||(o=new this._webSocketConstructor(e)),t===Ce.Binary&&(o.binaryType="arraybuffer"),o.onopen=t=>{this._logger.log(Ee.Information,`WebSocket connected to ${e}.`),this._webSocket=o,i=!0,n()},o.onerror=e=>{let t=null;t="undefined"!=typeof ErrorEvent&&e instanceof ErrorEvent?e.error:"There was an error with the transport",this._logger.log(Ee.Information,`(WebSockets transport) ${t}.`)},o.onmessage=e=>{if(this._logger.log(Ee.Trace,`(WebSockets transport) data received. ${$e(e.data,this._logMessageContent)}.`),this.onreceive)try{this.onreceive(e.data)}catch(e){return void this._close(e)}},o.onclose=e=>{if(i)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(Ee.Trace,`(WebSockets transport) sending data. ${$e(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(Ee.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 Ve{constructor(e,t={}){var n;if(this._stopPromiseResolver=()=>{},this.features={},this._negotiateVersion=1,Ne.isRequired(e,"url"),this._logger=void 0===(n=t.logger)?new Oe(Ee.Information):null===n?Ae.instance:void 0!==n.log?n:new Oe(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,"undefined"==typeof WebSocket||t.WebSocket||(t.WebSocket=WebSocket),"undefined"==typeof EventSource||t.EventSource||(t.EventSource=EventSource),this._httpClient=t.httpClient||new Re(this._logger),this._connectionState="Disconnected",this._connectionStarted=!1,this._options=t,this.onreceive=null,this.onclose=null}async start(e){if(e=e||Ce.Binary,Ne.isIn(e,Ce,"transferFormat"),this._logger.log(Ee.Debug,`Starting connection with transfer format '${Ce[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(Ee.Error,e),await this._stopPromise,Promise.reject(new Error(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(Ee.Error,e),Promise.reject(new Error(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 Xe(this.transport)),this._sendQueue.send(e))}async stop(e){return"Disconnected"===this._connectionState?(this._logger.log(Ee.Debug,`Call to HttpConnection.stop(${e}) ignored because the connection is already in the disconnected state.`),Promise.resolve()):"Disconnecting"===this._connectionState?(this._logger.log(Ee.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(Ee.Error,`HttpConnection.transport.stop() threw error '${e}'.`),this._stopConnection()}this.transport=void 0}else this._logger.log(Ee.Debug,"HttpConnection.transport is undefined in HttpConnection.stop() because start() failed.")}async _startInternal(e){let t=this.baseUrl;this._accessTokenFactory=this._options.accessTokenFactory;try{if(this._options.skipNegotiation){if(this._options.transport!==Se.WebSockets)throw new Error("Negotiation can only be skipped when using the WebSocket transport directly.");this.transport=this._constructTransport(Se.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 Error("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}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 qe&&(this.features.inherentKeepAlive=!0),"Connecting"===this._connectionState&&(this._logger.log(Ee.Debug,"The HttpConnection connected successfully."),this._connectionState="Connected")}catch(e){return this._logger.log(Ee.Error,"Failed to start the connection: "+e),this._connectionState="Disconnected",this.transport=void 0,this._stopPromiseResolver(),Promise.reject(e)}}async _getNegotiationResponse(e){const t={};if(this._accessTokenFactory){const e=await this._accessTokenFactory();e&&(t[Pe.Authorization]=`Bearer ${e}`)}const[n,r]=Fe();t[n]=r;const o=this._resolveNegotiateUrl(e);this._logger.log(Ee.Debug,`Sending negotiation request: ${o}.`);try{const e=await this._httpClient.post(o,{content:"",headers:{...t,...this._options.headers},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 ye&&404===e.statusCode&&(t+=" Either this is not a SignalR endpoint or there is a proxy blocking the connection."),this._logger.log(Ee.Error,t),Promise.reject(new Error(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(Ee.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: ${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(Ee.Error,`Failed to start the transport '${n.transport}': ${e}`),a=void 0,i.push(`${n.transport} failed: ${e}`),"Connecting"!==this._connectionState){const e="Failed to select transport before stop() was called.";return this._logger.log(Ee.Debug,e),Promise.reject(new Error(e))}}}}return i.length>0?Promise.reject(new Error(`Unable to connect to the server with any of the available transports. ${i.join(" ")}`)):Promise.reject(new Error("None of the transports supported by the client are supported by the server."))}_constructTransport(e){switch(e){case Se.WebSockets:if(!this._options.WebSocket)throw new Error("'WebSocket' is not supported in your environment.");return new Ke(this._httpClient,this._accessTokenFactory,this._logger,this._options.logMessageContent||!1,this._options.WebSocket,this._options.headers||{});case Se.ServerSentEvents:if(!this._options.EventSource)throw new Error("'EventSource' is not supported in your environment.");return new Je(this._httpClient,this._accessTokenFactory,this._logger,this._options.logMessageContent||!1,this._options.EventSource,this._options.withCredentials,this._options.headers||{});case Se.LongPolling:return new qe(this._httpClient,this._accessTokenFactory,this._logger,this._options.logMessageContent||!1,this._options.withCredentials,this._options.headers||{});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=Se[e.transport];if(null==r)return this._logger.log(Ee.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(Ee.Debug,`Skipping transport '${Se[r]}' because it was disabled by the client.`),new Error(`'${Se[r]}' is disabled by the client.`);if(!(e.transferFormats.map((e=>Ce[e])).indexOf(n)>=0))return this._logger.log(Ee.Debug,`Skipping transport '${Se[r]}' because it does not support the requested transfer format '${Ce[n]}'.`),new Error(`'${Se[r]}' does not support ${Ce[n]}.`);if(r===Se.WebSockets&&!this._options.WebSocket||r===Se.ServerSentEvents&&!this._options.EventSource)return this._logger.log(Ee.Debug,`Skipping transport '${Se[r]}' because it is not supported in your environment.'`),new Error(`'${Se[r]}' is not supported in your environment.`);this._logger.log(Ee.Debug,`Selecting transport '${Se[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(Ee.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(Ee.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(Ee.Error,`Connection disconnected with error '${e}'.`):this._logger.log(Ee.Information,"Connection disconnected."),this._sendQueue&&(this._sendQueue.stop().catch((e=>{this._logger.log(Ee.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(Ee.Error,`HttpConnection.onclose(${e}) threw error '${t}'.`)}}}else this._logger.log(Ee.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(!Be.isBrowser||!window.document)throw new Error(`Cannot resolve '${e}'.`);const t=window.document.createElement("a");return t.href=e,this._logger.log(Ee.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 Xe{constructor(e){this._transport=e,this._buffer=[],this._executing=!0,this._sendBufferedData=new Ye,this._transportResult=new Ye,this._sendLoopPromise=this._sendLoop()}send(e){return this._bufferData(e),this._transportResult||(this._transportResult=new Ye),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 Ye;const e=this._transportResult;this._transportResult=void 0;const t="string"==typeof this._buffer[0]?this._buffer.join(""):Xe._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 Ye{constructor(){this.promise=new Promise(((e,t)=>[this._resolver,this._rejecter]=[e,t]))}resolve(){this._resolver()}reject(e){this._rejecter(e)}}class Ge{static write(e){return`${e}${Ge.RecordSeparator}`}static parse(e){if(e[e.length-1]!==Ge.RecordSeparator)throw new Error("Message is incomplete.");const t=e.split(Ge.RecordSeparator);return t.pop(),t}}Ge.RecordSeparatorCode=30,Ge.RecordSeparator=String.fromCharCode(Ge.RecordSeparatorCode);class Qe{writeHandshakeRequest(e){return Ge.write(JSON.stringify(e))}parseHandshakeResponse(e){let t,n;if(Le(e)){const r=new Uint8Array(e),o=r.indexOf(Ge.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(Ge.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=Ge.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"}(Ie||(Ie={}));class Ze{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 He(this,e)}}!function(e){e.Disconnected="Disconnected",e.Connecting="Connecting",e.Connected="Connected",e.Disconnecting="Disconnecting",e.Reconnecting="Reconnecting"}(ke||(ke={}));class et{constructor(e,t,n,r){this._nextKeepAlive=0,Ne.isRequired(e,"connection"),Ne.isRequired(t,"logger"),Ne.isRequired(n,"protocol"),this.serverTimeoutInMilliseconds=3e4,this.keepAliveIntervalInMilliseconds=15e3,this._logger=t,this._protocol=n,this.connection=e,this._reconnectPolicy=r,this._handshakeProtocol=new Qe,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=ke.Disconnected,this._connectionStarted=!1,this._cachedPingMessage=this._protocol.writeMessage({type:Ie.Ping})}static create(e,t,n,r){return new et(e,t,n,r)}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!==ke.Disconnected&&this._connectionState!==ke.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!==ke.Disconnected)return Promise.reject(new Error("Cannot start a HubConnection that is not in the 'Disconnected' state."));this._connectionState=ke.Connecting,this._logger.log(Ee.Debug,"Starting HubConnection.");try{await this._startInternal(),this._connectionState=ke.Connected,this._connectionStarted=!0,this._logger.log(Ee.Debug,"HubConnection connected successfully.")}catch(e){return this._connectionState=ke.Disconnected,this._logger.log(Ee.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(Ee.Debug,"Sending handshake request."),await this._sendMessage(this._handshakeProtocol.writeHandshakeRequest(t)),this._logger.log(Ee.Information,`Using HubProtocol '${this._protocol.name}'.`),this._cleanupTimeout(),this._resetTimeoutPeriod(),this._resetKeepAliveInterval(),await e,this._stopDuringStartError)throw this._stopDuringStartError}catch(e){throw this._logger.log(Ee.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){return this._connectionState===ke.Disconnected?(this._logger.log(Ee.Debug,`Call to HubConnection.stop(${e}) ignored because it is already in the disconnected state.`),Promise.resolve()):this._connectionState===ke.Disconnecting?(this._logger.log(Ee.Debug,`Call to HttpConnection.stop(${e}) ignored because the connection is already in the disconnecting state.`),this._stopPromise):(this._connectionState=ke.Disconnecting,this._logger.log(Ee.Debug,"Stopping HubConnection."),this._reconnectDelayHandle?(this._logger.log(Ee.Debug,"Connection stopped during reconnect delay. Done reconnecting."),clearTimeout(this._reconnectDelayHandle),this._reconnectDelayHandle=void 0,this._completeClose(),Promise.resolve()):(this._cleanupTimeout(),this._cleanupPingTimer(),this._stopDuringStartError=e||new Error("The connection was stopped before the hub handshake could complete."),this.connection.stop(e)))}stream(e,...t){const[n,r]=this._replaceStreamingParams(t),o=this._createStreamInvocation(e,t,r);let i;const s=new Ze;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===Ie.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===Ie.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 Ie.Invocation:this._invokeClientMethod(e);break;case Ie.StreamItem:case Ie.Completion:{const t=this._callbacks[e.invocationId];t&&(e.type===Ie.Completion&&delete this._callbacks[e.invocationId],t(e));break}case Ie.Ping:break;case Ie.Close:{this._logger.log(Ee.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(Ee.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(Ee.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(Ee.Error,e);const n=new Error(e);throw this._handshakeRejecter(n),n}return this._logger.log(Ee.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===ke.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."))}_invokeClientMethod(e){const t=this._methods[e.target.toLowerCase()];if(t){try{t.forEach((t=>t.apply(this,e.arguments)))}catch(t){this._logger.log(Ee.Error,`A callback for the method ${e.target.toLowerCase()} threw error '${t}'.`)}if(e.invocationId){const e="Server requested a response, which is not supported in this version of the client.";this._logger.log(Ee.Error,e),this._stopPromise=this._stopInternal(new Error(e))}}else this._logger.log(Ee.Warning,`No client method with the name '${e.target}' found.`)}_connectionClosed(e){this._logger.log(Ee.Debug,`HubConnection.connectionClosed(${e}) called while in state ${this._connectionState}.`),this._stopDuringStartError=this._stopDuringStartError||e||new Error("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===ke.Disconnecting?this._completeClose(e):this._connectionState===ke.Connected&&this._reconnectPolicy?this._reconnect(e):this._connectionState===ke.Connected&&this._completeClose(e)}_completeClose(e){if(this._connectionStarted){this._connectionState=ke.Disconnected,this._connectionStarted=!1;try{this._closedCallbacks.forEach((t=>t.apply(this,[e])))}catch(t){this._logger.log(Ee.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(Ee.Debug,"Connection not reconnecting because the IRetryPolicy returned null on the first reconnect attempt."),void this._completeClose(e);if(this._connectionState=ke.Reconnecting,e?this._logger.log(Ee.Information,`Connection reconnecting because of error '${e}'.`):this._logger.log(Ee.Information,"Connection reconnecting."),0!==this._reconnectingCallbacks.length){try{this._reconnectingCallbacks.forEach((t=>t.apply(this,[e])))}catch(t){this._logger.log(Ee.Error,`An onreconnecting callback called with error '${e}' threw error '${t}'.`)}if(this._connectionState!==ke.Reconnecting)return void this._logger.log(Ee.Debug,"Connection left the reconnecting state in onreconnecting callback. Done reconnecting.")}for(;null!==o;){if(this._logger.log(Ee.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!==ke.Reconnecting)return void this._logger.log(Ee.Debug,"Connection left the reconnecting state during reconnect delay. Done reconnecting.");try{if(await this._startInternal(),this._connectionState=ke.Connected,this._logger.log(Ee.Information,"HubConnection reconnected successfully."),0!==this._reconnectedCallbacks.length)try{this._reconnectedCallbacks.forEach((e=>e.apply(this,[this.connection.connectionId])))}catch(e){this._logger.log(Ee.Error,`An onreconnected callback called with connectionId '${this.connection.connectionId}; threw error '${e}'.`)}return}catch(e){if(this._logger.log(Ee.Information,`Reconnect attempt failed because of error '${e}'.`),this._connectionState!==ke.Reconnecting)return this._logger.log(Ee.Debug,`Connection moved to the '${this._connectionState}' from the reconnecting state during reconnect attempt. Done reconnecting.`),void(this._connectionState===ke.Disconnecting&&this._completeClose());r=e instanceof Error?e:new Error(e.toString()),o=this._getNextRetryDelay(n++,Date.now()-t,r)}}this._logger.log(Ee.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(Ee.Error,`IRetryPolicy.nextRetryDelayInMilliseconds(${e}, ${t}) threw error '${n}'.`),null}}_cancelCallbacksWithError(e){const t=this._callbacks;this._callbacks={},Object.keys(t).forEach((n=>{(0,t[n])(null,e)}))}_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:Ie.Invocation}:{arguments:t,target:e,type:Ie.Invocation};{const n=this._invocationId;return this._invocationId++,0!==r.length?{arguments:t,invocationId:n.toString(),streamIds:r,target:e,type:Ie.Invocation}:{arguments:t,invocationId:n.toString(),target:e,type:Ie.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 ut=ot?new TextDecoder:null,dt=ot?"undefined"!=typeof process&&"force"!==process.env.TEXT_DECODER?200:0:it,pt=function(e,t){this.type=e,this.data=t};function ft(e,t,n){var r=Math.floor(n/4294967296),o=n;e.setUint32(t,r),e.setUint32(t+4,o)}function gt(e,t){return 4294967296*e.getInt32(t)+e.getUint32(t+4)}var mt={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),ft(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:gt(t,4),nsec:t.getUint32(0)};default:throw new Error("Unrecognized data size for timestamp: "+e.length)}}(e);return new Date(1e3*t.sec+t.nsec/1e6)}},yt=function(){function e(){this.builtInEncoders=[],this.builtInDecoders=[],this.encoders=[],this.decoders=[],this.register(mt)}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 "+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: "+e+" bytes in UTF-8");this.writeU8(219),this.writeU32(e)}},e.prototype.encodeString=function(e){if(e.length>ct){var t=st(e);this.ensureBufferSizeToWrite(5+t),this.writeStringHeader(t),lt(e,this.bytes,this.pos),this.pos+=t}else t=st(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: "+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: "+t);this.writeU8(198),this.writeU32(t)}var n=wt(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: "+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=ht(e,t,n),i=Uint8Array.prototype.slice.call(e,t,t+n);return this.store(i,o),o},e}(),St=(_t=function(e,t){return(_t=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])})(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}_t(e,t),e.prototype=null===t?Object.create(t):(n.prototype=t.prototype,new n)}),Ct=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]1||a(e,t)}))})}function a(e,t){try{(n=o[e](t)).value instanceof kt?Promise.resolve(n.value.v).then(c,l):h(i[0][2],n)}catch(e){h(i[0][3],e)}var n}function c(e){a("next",e)}function l(e){a("throw",e)}function h(e,t){e(t),i.shift(),i.length&&a(i[0][0],i[0][1])}},Dt=new DataView(new ArrayBuffer(0)),xt=new Uint8Array(Dt.buffer),Rt=function(){try{Dt.getInt8(0)}catch(e){return e.constructor}throw new Error("never reached")}(),Pt=new Rt("Insufficient data"),Ut=4294967295,At=new Et,Nt=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 St(t,e),t}(Error),Bt=function(){function e(e,t,n,r,o,i,s,a){void 0===e&&(e=yt.defaultCodec),void 0===t&&(t=void 0),void 0===n&&(n=Ut),void 0===r&&(r=Ut),void 0===o&&(o=Ut),void 0===i&&(i=Ut),void 0===s&&(s=Ut),void 0===a&&(a=At),this.extensionCodec=e,this.context=t,this.maxStrLength=n,this.maxBinLength=r,this.maxArrayLength=o,this.maxMapLength=i,this.maxExtLength=s,this.keyDecoder=a,this.totalPos=0,this.pos=0,this.view=Dt,this.bytes=xt,this.headByte=-1,this.stack=[]}return e.prototype.reinitializeState=function(){this.totalPos=0,this.headByte=-1,this.stack.length=0},e.prototype.setBuffer=function(e){this.bytes=wt(e),this.view=function(e){if(e instanceof ArrayBuffer)return new DataView(e);var t=wt(e);return new DataView(t.buffer,t.byteOffset,t.byteLength)}(this.bytes),this.pos=0},e.prototype.appendBuffer=function(e){if(-1!==this.headByte||this.hasRemaining()){var t=this.bytes.subarray(this.pos),n=wt(e),r=new Uint8Array(t.length+n.length);r.set(t),r.set(n,t.length),this.setBuffer(r)}else this.setBuffer(e)},e.prototype.hasRemaining=function(e){return void 0===e&&(e=1),this.view.byteLength-this.pos>=e},e.prototype.createExtraByteError=function(e){var t=this.view,n=this.pos;return new RangeError("Extra "+(t.byteLength-n)+" of "+t.byteLength+" byte(s) found at buffer["+e+"]")},e.prototype.decode=function(e){this.reinitializeState(),this.setBuffer(e);var t=this.doDecodeSync();if(this.hasRemaining())throw this.createExtraByteError(this.pos);return t},e.prototype.decodeMulti=function(e){return Ct(this,(function(t){switch(t.label){case 0:this.reinitializeState(),this.setBuffer(e),t.label=1;case 1:return this.hasRemaining()?[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,u,d;return Ct(this,(function(p){switch(p.label){case 0:i=!1,p.label=1;case 1:p.trys.push([1,6,7,12]),t=It(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 Rt))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())throw this.createExtraByteError(this.totalPos);return[2,s]}throw h=(l=this).headByte,u=l.pos,d=l.totalPos,new RangeError("Insufficient data in parsing "+bt(h)+" at "+d+" ("+u+" 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 Tt(this,arguments,(function(){var n,r,o,i,s,a,c,l,h;return Ct(this,(function(u){switch(u.label){case 0:n=t,r=-1,u.label=1;case 1:u.trys.push([1,13,14,19]),o=It(e),u.label=2;case 2:return[4,kt(o.next())];case 3:if((i=u.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()),u.label=4;case 4:u.trys.push([4,9,,10]),u.label=5;case 5:return[4,kt(this.doDecodeSync())];case 6:return[4,u.sent()];case 7:return u.sent(),0==--r?[3,8]:[3,5];case 8:return[3,10];case 9:if(!((a=u.sent())instanceof Rt))throw a;return[3,10];case 10:this.totalPos+=this.pos,u.label=11;case 11:return[3,2];case 12:return[3,19];case 13:return c=u.sent(),l={error:c},[3,19];case 14:return u.trys.push([14,,17,18]),i&&!i.done&&(h=o.return)?[4,kt(h.call(o))]:[3,16];case 15:u.sent(),u.label=16;case 16:return[3,18];case 17:if(l)throw l.error;return[7];case 18:return[7];case 19:return[2]}}))}))},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 Nt("Unrecognized type byte: "+bt(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 Nt("The type of key must be string or number but "+typeof t);if("__proto__"===t)throw new Nt("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 Nt("Unrecognized array type byte: "+bt(e))}},e.prototype.pushMapState=function(e){if(e>this.maxMapLength)throw new Nt("Max length exceeded: map length ("+e+") > maxMapLengthLength ("+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 Nt("Max length exceeded: array length ("+e+") > maxArrayLength ("+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 Nt("Max length exceeded: UTF-8 byte length ("+e+") > maxStrLength ("+this.maxStrLength+")");if(this.bytes.byteLengthdt?function(e,t,n){var r=e.subarray(t,t+n);return ut.decode(r)}(this.bytes,o,e):ht(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 Nt("Max length exceeded: bin length ("+e+") > maxBinLength ("+this.maxBinLength+")");if(!this.hasRemaining(e+t))throw Pt;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 Nt("Max length exceeded: ext length ("+e+") > maxExtLength ("+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=gt(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 $t{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 Lt=new Uint8Array([145,Ie.Ping]);class Mt{constructor(e){this.name="messagepack",this.version=1,this.transferFormat=Ce.Binary,this._errorResult=1,this._voidResult=2,this._nonVoidResult=3,e=e||{},this._encoder=new vt(e.extensionCodec,e.context,e.maxDepth,e.initialBufferSize,e.sortKeys,e.forceFloat32,e.ignoreUndefined,e.forceIntegerToFloat),this._decoder=new Bt(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=Ae.instance);const r=$t.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 Ie.Invocation:return this._writeInvocation(e);case Ie.StreamInvocation:return this._writeStreamInvocation(e);case Ie.StreamItem:return this._writeStreamItem(e);case Ie.Completion:return this._writeCompletion(e);case Ie.Ping:return $t.write(Lt);case Ie.CancelInvocation:return this._writeCancelInvocation(e);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 Ie.Invocation:return this._createInvocationMessage(this._readHeaders(n),n);case Ie.StreamItem:return this._createStreamItemMessage(this._readHeaders(n),n);case Ie.Completion:return this._createCompletionMessage(this._readHeaders(n),n);case Ie.Ping:return this._createPingMessage(n);case Ie.Close:return this._createCloseMessage(n);default:return t.log(Ee.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:Ie.Close}}_createPingMessage(e){if(e.length<1)throw new Error("Invalid payload for Ping message.");return{type:Ie.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:Ie.Invocation}:{arguments:t[4],headers:e,streamIds:[],target:t[3],type:Ie.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:Ie.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:Ie.Completion}}_writeInvocation(e){let t;return t=e.streamIds?this._encoder.encode([Ie.Invocation,e.headers||{},e.invocationId||null,e.target,e.arguments,e.streamIds]):this._encoder.encode([Ie.Invocation,e.headers||{},e.invocationId||null,e.target,e.arguments]),$t.write(t.slice())}_writeStreamInvocation(e){let t;return t=e.streamIds?this._encoder.encode([Ie.StreamInvocation,e.headers||{},e.invocationId,e.target,e.arguments,e.streamIds]):this._encoder.encode([Ie.StreamInvocation,e.headers||{},e.invocationId,e.target,e.arguments]),$t.write(t.slice())}_writeStreamItem(e){const t=this._encoder.encode([Ie.StreamItem,e.headers||{},e.invocationId,e.item]);return $t.write(t.slice())}_writeCompletion(e){const t=e.error?this._errorResult:e.result?this._nonVoidResult:this._voidResult;let n;switch(t){case this._errorResult:n=this._encoder.encode([Ie.Completion,e.headers||{},e.invocationId,t,e.error]);break;case this._voidResult:n=this._encoder.encode([Ie.Completion,e.headers||{},e.invocationId,t]);break;case this._nonVoidResult:n=this._encoder.encode([Ie.Completion,e.headers||{},e.invocationId,t,e.result])}return $t.write(n.slice())}_writeCancelInvocation(e){const t=this._encoder.encode([Ie.CancelInvocation,e.headers||{},e.invocationId]);return $t.write(t.slice())}_readHeaders(e){const t=e[1];if("object"!=typeof t)throw new Error("Invalid headers.");return t}}let Ht=!1;const Ot="function"==typeof TextDecoder?new TextDecoder("utf-8"):null,Ft=Ot?Ot.decode.bind(Ot):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("")},jt=Math.pow(2,32),Wt=Math.pow(2,21)-1;function zt(e,t){return e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24}function qt(e,t){return e[t]+(e[t+1]<<8)+(e[t+2]<<16)+(e[t+3]<<24>>>0)}function Jt(e,t){const n=qt(e,t+4);if(n>Wt)throw new Error(`Cannot read uint64 with high order part ${n}, because the result would exceed Number.MAX_SAFE_INTEGER.`);return n*jt+qt(e,t)}class Kt{constructor(e){this.batchData=e;const t=new Gt(e);this.arrayRangeReader=new Qt(e),this.arrayBuilderSegmentReader=new Zt(e),this.diffReader=new Vt(e),this.editReader=new Xt(e,t),this.frameReader=new Yt(e,t)}updatedComponents(){return zt(this.batchData,this.batchData.length-20)}referenceFrames(){return zt(this.batchData,this.batchData.length-16)}disposedComponentIds(){return zt(this.batchData,this.batchData.length-12)}disposedEventHandlerIds(){return zt(this.batchData,this.batchData.length-8)}updatedComponentsEntry(e,t){const n=e+4*t;return zt(this.batchData,n)}referenceFramesEntry(e,t){return e+20*t}disposedComponentIdsEntry(e,t){const n=e+4*t;return zt(this.batchData,n)}disposedEventHandlerIdsEntry(e,t){const n=e+8*t;return Jt(this.batchData,n)}}class Vt{constructor(e){this.batchDataUint8=e}componentId(e){return zt(this.batchDataUint8,e)}edits(e){return e+4}editsEntry(e,t){return e+16*t}}class Xt{constructor(e,t){this.batchDataUint8=e,this.stringReader=t}editType(e){return zt(this.batchDataUint8,e)}siblingIndex(e){return zt(this.batchDataUint8,e+4)}newTreeIndex(e){return zt(this.batchDataUint8,e+8)}moveToSiblingIndex(e){return zt(this.batchDataUint8,e+8)}removedAttributeName(e){const t=zt(this.batchDataUint8,e+12);return this.stringReader.readString(t)}}class Yt{constructor(e,t){this.batchDataUint8=e,this.stringReader=t}frameType(e){return zt(this.batchDataUint8,e)}subtreeLength(e){return zt(this.batchDataUint8,e+4)}elementReferenceCaptureId(e){const t=zt(this.batchDataUint8,e+4);return this.stringReader.readString(t)}componentId(e){return zt(this.batchDataUint8,e+8)}elementName(e){const t=zt(this.batchDataUint8,e+8);return this.stringReader.readString(t)}textContent(e){const t=zt(this.batchDataUint8,e+4);return this.stringReader.readString(t)}markupContent(e){const t=zt(this.batchDataUint8,e+4);return this.stringReader.readString(t)}attributeName(e){const t=zt(this.batchDataUint8,e+4);return this.stringReader.readString(t)}attributeValue(e){const t=zt(this.batchDataUint8,e+8);return this.stringReader.readString(t)}attributeEventHandlerId(e){return Jt(this.batchDataUint8,e+12)}}class Gt{constructor(e){this.batchDataUint8=e,this.stringTableStartIndex=zt(e,e.length-4)}readString(e){if(-1===e)return null;{const n=zt(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(en.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(en.Debug,`Waiting for batch ${this.nextBatchId}. Batch ${e} not processed.`);try{this.nextBatchId++,this.logger.log(en.Debug,`Applying batch ${e}.`),function(e,t){const n=Q[e];if(!n)throw new Error(`There is no browser renderer with ID ${e}.`);const r=t.arrayRangeReader,o=t.updatedComponents(),i=r.values(o),s=r.count(o),a=t.referenceFrames(),c=r.values(a),l=t.diffReader;for(let e=0;e=this.minLevel){const n=`[${(new Date).toISOString()}] ${en[e]}: ${t}`;switch(e){case en.Critical:case en.Error:console.error(n);break;case en.Warning:console.warn(n);break;case en.Information:console.info(n);break;default:console.log(n)}}}}class on{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!==ke.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!==ke.Connected)return!1;const t=await e.invoke("StartCircuit",re.getBaseURI(),re.getLocationHref(),JSON.stringify(this.components.map((e=>e.toRecord()))),this.applicationState||"");return!!t&&(this.initialize(t),!0)}resolveElement(e){const t=Number.parseInt(e);if(Number.isNaN(t))throw new Error(`Invalid sequence number '${e}'.`);return function(e,t){if(!e.parentNode)throw new Error(`Comment not connected to the DOM ${e.textContent}`);const n=e.parentNode,r=k(n,!0),o=A(r);return Array.from(n.childNodes).forEach((e=>o.push(e))),e[C]=r,t&&(e[I]=t,k(t)),k(e)}(this.components[t].start,this.components[t].end)}}const sn={configureSignalR:e=>{},logLevel:en.Warning,reconnectionOptions:{maxRetries:8,retryIntervalMilliseconds:2e4,dialogId:"components-reconnect-modal"}};class an{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.modal.innerHTML='

Alternatively, reload

',this.message=this.modal.querySelector("h5"),this.button=this.modal.querySelector("button"),this.reloadParagraph=this.modal.querySelector("p"),this.loader=this.getLoader(),this.message.after(this.loader),this.button.addEventListener("click",(async()=>{this.show();try{await(null==fe?void 0:fe.reconnect)()||this.rejected()}catch(e){this.logger.log(en.Error,e),this.failed()}})),this.reloadParagraph.querySelector("a").addEventListener("click",(()=>location.reload()))}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",this.message.innerHTML="Reconnection failed. Try reloading the page if you're unable to reconnect.",this.message.querySelector("a").addEventListener("click",(()=>location.reload()))}rejected(){this.button.style.display="none",this.reloadParagraph.style.display="none",this.loader.style.display="none",this.message.innerHTML="Could not reconnect to the server. Reload the page to restore functionality.",this.message.querySelector("a").addEventListener("click",(()=>location.reload()))}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 cn{constructor(e,t,n){this.dialog=e,this.maxRetries=t,this.document=n,this.document=n;const r=this.document.getElementById(cn.MaxRetriesId);r&&(r.innerText=this.maxRetries.toString())}show(){this.removeClasses(),this.dialog.classList.add(cn.ShowClassName)}update(e){const t=this.document.getElementById(cn.CurrentAttemptId);t&&(t.innerText=e.toString())}hide(){this.removeClasses(),this.dialog.classList.add(cn.HideClassName)}failed(){this.removeClasses(),this.dialog.classList.add(cn.FailedClassName)}rejected(){this.removeClasses(),this.dialog.classList.add(cn.RejectedClassName)}removeClasses(){this.dialog.classList.remove(cn.ShowClassName,cn.HideClassName,cn.FailedClassName,cn.RejectedClassName)}}cn.ShowClassName="components-reconnect-show",cn.HideClassName="components-reconnect-hide",cn.FailedClassName="components-reconnect-failed",cn.RejectedClassName="components-reconnect-rejected",cn.MaxRetriesId="components-reconnect-max-retries",cn.CurrentAttemptId="components-reconnect-current-attempt";class ln{constructor(e,t,n){this._currentReconnectionProcess=null,this._logger=e,this._reconnectionDisplay=t,this._reconnectCallback=n||(()=>fe.reconnect())}onConnectionDown(e,t){if(!this._reconnectionDisplay){const t=document.getElementById(e.dialogId);this._reconnectionDisplay=t?new cn(t,e.maxRetries,document):new an(e.dialogId,e.maxRetries,document,this._logger)}this._currentReconnectionProcess||(this._currentReconnectionProcess=new hn(e,this._logger,this._reconnectCallback,this._reconnectionDisplay))}onConnectionUp(){this._currentReconnectionProcess&&(this._currentReconnectionProcess.dispose(),this._currentReconnectionProcess=null)}}class hn{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;thn.MaximumFirstRetryInterval?hn.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(en.Error,e)}}this.reconnectDisplay.failed()}delay(e){return new Promise((t=>setTimeout(t,e)))}}hn.MaximumFirstRetryInterval=3e3;const un=/^\s*Blazor-Component-State:(?[a-zA-Z0-9\+\/=]+)$/;function dn(e){var t;if(e.nodeType===Node.COMMENT_NODE){const n=e.textContent||"",r=un.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 gn(e,t){const n=e.currentElement;if(n&&n.nodeType===Node.COMMENT_NODE&&n.textContent){const r=fn.exec(n.textContent),o=r&&r.groups&&r.groups.descriptor;if(!o)return;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;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.");if(c){const e=mn(c,n);if(!e)throw new Error(`Could not find an end component comment for '${t}'`);return{type:r,assembly:o,typeName:i,parameterDefinitions:s&&atob(s),parameterValues:a&&atob(a),start:t,prerenderId:c,end:e}}return{type:r,assembly:o,typeName:i,parameterDefinitions:s&&atob(s),parameterValues:a&&atob(a),start:t}}}(r,n,e);case"server":return function(e,t,n){const{type:r,descriptor:o,sequence:i,prerenderId:s}=e;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)}'`);if(s){const e=mn(s,n);if(!e)throw new Error(`Could not find an end component comment for '${t}'`);return{type:r,sequence:i,descriptor:o,start:t,prerenderId:s,end:e}}return{type:r,sequence:i,descriptor:o,start:t}}}(r,n,e)}}catch(e){throw new Error(`Found malformed component comment at ${n.textContent}`)}}}function mn(e,t){for(;t.next()&&t.currentElement;){const n=t.currentElement;if(n.nodeType!==Node.COMMENT_NODE)continue;if(!n.textContent)continue;const r=fn.exec(n.textContent),o=r&&r[1];if(o)return yn(o,e),n}}function yn(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 wn{constructor(e){this.childNodes=e,this.currentIndex=-1,this.length=e.length}next(){return this.currentIndex++,this.currentIndexe.sequence-t.sequence))}(e)}(document),o=dn(document),i=new on(r,o||""),s=await Tn(t,n,i);if(!await i.startCircuit(s))return void n.log(en.Error,"Failed to start the circuit.");let a=!1;const c=()=>{if(!a){const e=new FormData,t=i.circuitId;e.append("circuitId",t),a=navigator.sendBeacon("_blazor/disconnect",e)}};fe.disconnect=c,window.addEventListener("unload",c,{capture:!1,once:!0}),fe.reconnect=async e=>{if(Cn)return!1;const r=e||await Tn(t,n,i);return await i.reconnect(r)?(t.reconnectionHandler.onConnectionUp(),!0):(n.log(en.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)},n.log(en.Information,"Blazor server-side application started.")}async function Tn(t,n,r){const i=new Mt;i.name="blazorpack";const s=(new rt).withUrl("_blazor").withHubProtocol(i);t.configureSignalR(s);const a=s.build();o=(e,t)=>{a.send("DispatchBrowserEvent",JSON.stringify(e),JSON.stringify(t))},fe._internal.navigationManager.listenForNavigationEvents(((e,t)=>a.send("OnLocationChanged",e,t))),a.on("JS.AttachComponent",((e,t)=>function(e,t,n){let r=Q[0];r||(r=Q[0]=new V(0)),r.attachRootComponentToLogicalElement(n,t)}(0,r.resolveElement(t),e))),a.on("JS.BeginInvokeJS",e.jsCallDispatcher.beginInvokeJSFromDotNet),a.on("JS.EndInvokeDotNet",e.jsCallDispatcher.endInvokeDotNetFromJS),a.on("JS.ReceiveByteArray",e.jsCallDispatcher.receiveByteArray);const c=tn.getOrCreate(n);a.on("JS.RenderBatch",((e,t)=>{n.log(en.Debug,`Received render batch with id ${e} and ${t.byteLength} bytes.`),c.processBatch(e,t,a)})),a.onclose((e=>!Cn&&t.reconnectionHandler.onConnectionDown(t.reconnectionOptions,e))),a.on("JS.Error",(e=>{Cn=!0,Dn(a,e,n),async function(){let e=document.querySelector("#blazor-error-ui");e&&(e.style.display="block"),Ht||(Ht=!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()}})))}()})),fe._internal.forceCloseConnection=()=>a.stop();const l=new Set;fe._internal.sendJSDataStream=async(e,t,n)=>{l.add(t),setTimeout((async()=>{let r=5,o=(new Date).valueOf();try{const i=n-512;if(i<=0)throw new Error("The chunk size must be greater than 0.");let s=0;for(;s1)await a.send("SupplyJSDataChunk",t,c,null);else{if(!l.has(t))break;await a.invoke("SupplyJSDataChunk",t,c,null);const e=(new Date).valueOf(),n=e-o;o=e,r=Math.max(1,Math.round(500/n))}s+=n}}catch(e){await a.send("SupplyJSDataChunk",t,null,e.toString())}finally{l.delete(t)}}),0)},fe._internal.cancelJSDataStream=async e=>{l.delete(e)};try{await a.start()}catch(e){Dn(a,e,n)}return e.attachDispatcher({beginInvokeDotNetFromJS:(e,t,n,r,o)=>{a.send("BeginInvokeDotNetFromJS",e?e.toString():null,t,n,r||0,o)},endInvokeJSFromDotNet:(e,t,n)=>{a.send("EndInvokeJSFromDotNet",e,t,n)},sendByteArray:(e,t)=>{a.send("ReceiveByteArray",e,t)}}),a}function Dn(e,t,n){n.log(en.Error,t),e&&e.stop()}fe.start=kn,document&&document.currentScript&&"false"!==document.currentScript.getAttribute("autostart")&&kn()})(); \ No newline at end of file +(()=>{"use strict";var e,t,n;!function(e){window.DotNet=e;const t=[],n=new Map;class r{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 o="__jsObjectId",i={},s={0:new r(window)};s[0]._cachedFunctions.set("import",(e=>("string"==typeof e&&e.startsWith("./")&&(e=document.baseURI+e.substr(2)),import(e))));let a,c=1,l=1,h=null;function u(e){t.push(e)}function d(e){if(e&&"object"==typeof e){s[l]=new r(e);let t={[o]:l};return e.buffer instanceof ArrayBuffer&&void 0!==e.byteLength&&(t.__jsDataReferenceLength=e.byteLength),l++,t}throw new Error(`Cannot create a JSObjectReference from the value '${e}'.`)}function p(e){return e?JSON.parse(e,((e,n)=>t.reduce(((t,n)=>n(e,t)),n))):null}function f(e,t,n,r){const o=m();if(o.invokeDotNetFromJS){const i=I(r),s=o.invokeDotNetFromJS(e,t,n,i);return s?p(s):null}throw new Error("The current dispatcher does not support synchronous calls from JS to .NET. Use invokeMethodAsync instead.")}function g(e,t,n,r){if(e&&n)throw new Error(`For instance method calls, assemblyName should be null. Received '${e}'.`);const o=c++,s=new Promise(((e,t)=>{i[o]={resolve:e,reject:t}}));try{const i=I(r);m().beginInvokeDotNetFromJS(o,e,t,n,i)}catch(e){y(o,!1,e)}return s}function m(){if(null!==h)return h;throw new Error("No .NET call dispatcher has been set.")}function y(e,t,n){if(!i.hasOwnProperty(e))throw new Error(`There is no pending async call with ID ${e}.`);const r=i[e];delete i[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 v(e,t){let n=s[t];if(n)return n.findFunction(e);throw new Error(`JS object instance with ID ${t} does not exist (has it been disposed?).`)}function b(e){delete s[e]}e.attachDispatcher=function(e){h=e},e.attachReviver=u,e.invokeMethod=function(e,t,...n){return f(e,t,null,n)},e.invokeMethodAsync=function(e,t,...n){return g(e,t,null,n)},e.createJSObjectReference=d,e.disposeJSObjectReference=function(e){const t=e&&e.__jsObjectId;"number"==typeof t&&b(t)},function(e){e[e.Default=0]="Default",e[e.JSObjectReference=1]="JSObjectReference"}(a=e.JSCallResultType||(e.JSCallResultType={})),e.jsCallDispatcher={findJSFunction:v,disposeJSObjectReferenceById:b,invokeJSFromDotNet:(e,t,n,r)=>{const o=S(v(e,r).apply(null,p(t)),n);return null==o?null:I(o)},beginInvokeJSFromDotNet:(e,t,n,r,o)=>{const i=new Promise((e=>{e(v(t,o).apply(null,p(n)))}));e&&i.then((t=>m().endInvokeJSFromDotNet(e,!0,I([e,!0,S(t,r)]))),(t=>m().endInvokeJSFromDotNet(e,!1,JSON.stringify([e,!1,w(t)]))))},endInvokeDotNetFromJS:(e,t,n)=>{const r=t?p(n):new Error(n);y(parseInt(e),t,r)},receiveByteArray:(e,t)=>{n.set(e,t)}};class _{constructor(e){this._id=e}invokeMethod(e,...t){return f(null,e,this._id,t)}invokeMethodAsync(e,...t){return g(null,e,this._id,t)}dispose(){g(null,"__Dispose",this._id,null).catch((e=>console.error(e)))}serializeAsArg(){return{__dotNetObject:this._id}}}const E="__byte[]";function S(e,t){switch(t){case a.Default:return e;case a.JSObjectReference:return d(e);default:throw new Error(`Invalid JS call result type '${t}'.`)}}u((function(e,t){if(t&&"object"==typeof t){if(t.hasOwnProperty("__dotNetObject"))return new _(t.__dotNetObject);if(t.hasOwnProperty(o)){const e=t.__jsObjectId,n=s[e];if(n)return n.getWrappedObject();throw new Error(`JS object instance with Id '${e}' does not exist. It may have been disposed.`)}if(t.hasOwnProperty(E)){const e=t["__byte[]"],r=n.get(e);if(void 0===r)throw new Error(`Byte array index '${e}' does not exist.`);return r}}return t}));let C=0;function I(e){return C=0,JSON.stringify(e,k)}function k(e,t){if(t instanceof _)return t.serializeAsArg();if(t instanceof Uint8Array){h.sendByteArray(C,t);const e={[E]:C};return C++,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"}(n||(n={}));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}}let o;function i(e,t){if(!o)throw new Error("eventDispatcher not initialized. Call 'setEventDispatcher' to configure it.");o(e,t)}const s=new Map,a=new Map,c={createEventArgs:()=>({})},l=[];function h(e){return s.get(e)}function u(e){const t=s.get(e);return(null==t?void 0:t.browserEventName)||e}function d(e,t){e.forEach((e=>s.set(e,t)))}function p(e){const t=[];for(let n=0;n{return{...f(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}}),d(["focus","blur","focusin","focusout"],c),d(["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};var t}}),d(["contextmenu","click","mouseover","mouseout","mousemove","mousedown","mouseup","dblclick"],{createEventArgs:e=>f(e)}),d(["error"],{createEventArgs:e=>{return{message:(t=e).message,filename:t.filename,lineno:t.lineno,colno:t.colno};var t}}),d(["loadstart","timeout","abort","load","loadend","progress"],{createEventArgs:e=>{return{lengthComputable:(t=e).lengthComputable,loaded:t.loaded,total:t.total};var t}}),d(["touchcancel","touchend","touchmove","touchenter","touchleave","touchstart"],{createEventArgs:e=>{return{detail:(t=e).detail,touches:p(t.touches),targetTouches:p(t.targetTouches),changedTouches:p(t.changedTouches),ctrlKey:t.ctrlKey,shiftKey:t.shiftKey,altKey:t.altKey,metaKey:t.metaKey,type:t.type};var t}}),d(["gotpointercapture","lostpointercapture","pointercancel","pointerdown","pointerenter","pointerleave","pointermove","pointerout","pointerover","pointerup"],{createEventArgs:e=>{return{...f(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}}),d(["wheel","mousewheel"],{createEventArgs:e=>{return{...f(t=e),deltaX:t.deltaX,deltaY:t.deltaY,deltaZ:t.deltaZ,deltaMode:t.deltaMode};var t}}),d(["toggle"],c);const g=["date","datetime-local","month","time","week"],m=E(["abort","blur","change","error","focus","load","loadend","loadstart","mouseenter","mouseleave","progress","reset","scroll","submit","unload","toggle","DOMNodeInsertedIntoDocument","DOMNodeRemovedFromDocument"]),y={submit:!0},w=E(["click","dblclick","mousedown","mousemove","mouseup"]);class v{constructor(e){this.browserRendererId=e,this.afterClickCallbacks=[];const t=++v.nextEventDelegatorId;this.eventsCollectionKey=`_blazorEvents_${t}`,this.eventInfoStore=new b(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,a.get(n));var n;t&&t.forEach((t=>this.dispatchGlobalEventToAllElements(t,e))),"click"===e.type&&this.afterClickCallbacks.forEach((t=>t(e)))}dispatchGlobalEventToAllElements(e,t){let n=t.target,o=null,s=!1;const a=m.hasOwnProperty(e);let c=!1;for(;n;){const d=this.getEventHandlerInfosForElement(n,!1);if(d){const a=d.getHandler(e);if(a&&(l=n,u=t.type,!((l instanceof HTMLButtonElement||l instanceof HTMLInputElement||l instanceof HTMLTextAreaElement||l instanceof HTMLSelectElement)&&w.hasOwnProperty(u)&&l.disabled))){if(!s){const n=h(e);o=(null==n?void 0:n.createEventArgs)?n.createEventArgs(t):{},s=!0}y.hasOwnProperty(t.type)&&t.preventDefault(),i({browserRendererId:this.browserRendererId,eventHandlerId:a.eventHandlerId,eventName:e,eventFieldInfo:r.fromEvent(a.renderingComponentId,t)},o)}d.stopPropagation(e)&&(c=!0),d.preventDefault(e)&&t.preventDefault()}n=a||c?null:n.parentElement}var l,u}getEventHandlerInfosForElement(e,t){return e.hasOwnProperty(this.eventsCollectionKey)?e[this.eventsCollectionKey]:t?e[this.eventsCollectionKey]=new _:null}}v.nextEventDelegatorId=0;class b{constructor(e){this.globalListener=e,this.infosByEventHandlerId={},this.countByEventName={},l.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=u(e),this.countByEventName.hasOwnProperty(e))this.countByEventName[e]++;else{this.countByEventName[e]=1;const t=m.hasOwnProperty(e);document.addEventListener(e,this.globalListener,t)}}update(e,t){if(this.infosByEventHandlerId.hasOwnProperty(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=u(t.eventName);0==--this.countByEventName[n]&&(delete this.countByEventName[n],document.removeEventListener(n,this.globalListener))}return t}handleEventNameAliasAdded(e,t){if(this.countByEventName.hasOwnProperty(e)){const n=this.countByEventName[e];delete this.countByEventName[e],document.removeEventListener(e,this.globalListener),this.addGlobalListener(t),this.countByEventName[t]+=n-1}}}class _{constructor(){this.handlers={},this.preventDefaultFlags=null,this.stopPropagationFlags=null}getHandler(e){return this.handlers.hasOwnProperty(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 E(e){const t={};return e.forEach((e=>{t[e]=!0})),t}const S=H("_blazorLogicalChildren"),C=H("_blazorLogicalParent"),I=H("_blazorLogicalEnd");function k(e,t){if(e.childNodes.length>0&&!t)throw new Error("New logical elements must start empty, or allowExistingContents must be true");return S in e||(e[S]=[]),e}function T(e,t){const n=document.createComment("!");return x(n,e,t),n}function x(e,t,n){const r=e;if(e instanceof Comment&&A(r)&&A(r).length>0)throw new Error("Not implemented: inserting non-empty logical container");if(R(r))throw new Error("Not implemented: moving existing logical children");const o=A(t);if(n0;)D(n,0)}const r=n;r.parentNode.removeChild(r)}function R(e){return e[C]||null}function P(e,t){return A(e)[t]}function U(e){var t=B(e);return"http://www.w3.org/2000/svg"===t.namespaceURI&&"foreignObject"!==t.tagName}function A(e){return e[S]}function N(e,t){const n=A(e);t.forEach((e=>{e.moveRangeStart=n[e.fromSiblingIndex],e.moveRangeEnd=M(e.moveRangeStart)})),t.forEach((t=>{const r=t.moveToBeforeMarker=document.createComment("marker"),o=n[t.toSiblingIndex+1];o?o.parentNode.insertBefore(r,o):L(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 B(e){if(e instanceof Element)return e;if(e instanceof Comment)return e.parentNode;throw new Error("Not a valid logical element")}function $(e){const t=A(R(e));return t[Array.prototype.indexOf.call(t,e)+1]||null}function L(e,t){if(t instanceof Element)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=$(t);n?n.parentNode.insertBefore(e,n):L(e,R(t))}}}function M(e){if(e instanceof Element)return e;const t=$(e);if(t)return t.previousSibling;{const t=R(e);return t instanceof Element?t.lastChild:M(t)}}function H(e){return"function"==typeof Symbol?Symbol():e}function O(e){return`_bl_${e}`}e.attachReviver(((e,t)=>t&&"object"==typeof t&&t.hasOwnProperty("__internalId")&&"string"==typeof t.__internalId?function(e){const t=`[${O(e)}]`;return document.querySelector(t)}(t.__internalId):t));const F="_blazorSelectValue",j=document.createElement("template"),W=document.createElementNS("http://www.w3.org/2000/svg","g"),z={},q="__internal_",J="preventDefault_",K="stopPropagation_";class V{constructor(e){this.childComponentLocations={},this.eventDelegator=new v(e),this.eventDelegator.notifyAfterClick((e=>{if(!ee)return;if(0!==e.button||function(e){return e.ctrlKey||e.shiftKey||e.altKey||e.metaKey}(e))return;if(e.defaultPrevented)return;const t=function(e){const t=!window._blazorDisableComposedPath&&e.composedPath&&e.composedPath();if(t){for(let e=0;ese(!1))))},enableNavigationInterception:function(){ee=!0},navigateTo:oe,getBaseURI:()=>document.baseURI,getLocationHref:()=>location.href};function oe(e,t,n=!1){const r=ce(e);if(!t&&he(r))ie(r,!1,n);else if(t&&location.href===e){const t=e+"?";history.replaceState(null,"",t),location.replace(e)}else n?history.replaceState(null,"",r):location.href=e}function ie(e,t,n=!1){Z=!0,n?history.replaceState(null,"",e):history.pushState(null,"",e),se(t)}async function se(e){ne&&await ne(location.href,e)}let ae;function ce(e){return ae=ae||document.createElement("a"),ae.href=e,ae.href}function le(e,t){return e?e.tagName===t?e:le(e.parentElement,t):null}function he(e){const t=(n=document.baseURI).substr(0,n.lastIndexOf("/")+1);var n;return e.startsWith(t)}const ue={init:function(e,t,n,r=50){const o=pe(t);(o||document.documentElement).style.overflowAnchor="none";const i=new IntersectionObserver((function(r){r.forEach((r=>{var o;if(!r.isIntersecting)return;const i=t.getBoundingClientRect(),s=n.getBoundingClientRect().top-i.bottom,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`});i.observe(t),i.observe(n);const s=c(t),a=c(n);function c(e){const t=new MutationObserver((()=>{i.unobserve(e),i.observe(e)}));return t.observe(e,{attributes:!0}),t}de[e._id]={intersectionObserver:i,mutationObserverBefore:s,mutationObserverAfter:a}},dispose:function(e){const t=de[e._id];t&&(t.intersectionObserver.disconnect(),t.mutationObserverBefore.disconnect(),t.mutationObserverAfter.disconnect(),e.dispose(),delete de[e._id])}},de={};function pe(e){return e?"visible"!==getComputedStyle(e).overflowY?e:pe(e.parentElement):null}const fe={navigateTo:oe,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=a.get(t.browserEventName);n?n.push(e):a.set(t.browserEventName,[e]),l.forEach((n=>n(e,t.browserEventName)))}s.set(e,t)},_internal:{navigationManager:re,domWrapper:{focus:function(e,t){if(!(e instanceof HTMLElement))throw new Error("Unable to focus an invalid element.");e.focus({preventScroll:t})}},Virtualize:ue}};window.Blazor=fe;const ge=[0,2e3,1e4,3e4,null];class me{constructor(e){this._retryDelays=void 0!==e?[...e,null]:ge}nextRetryDelayInMilliseconds(e){return this._retryDelays[e.previousRetryCount]}}class ye extends Error{constructor(e,t){const n=new.target.prototype;super(`${e}: Status code '${t}'`),this.statusCode=t,this.__proto__=n}}class we extends Error{constructor(e="A timeout occurred."){const t=new.target.prototype;super(e),this.__proto__=t}}class ve extends Error{constructor(e="An abort occurred."){const t=new.target.prototype;super(e),this.__proto__=t}}class be{constructor(e,t,n){this.statusCode=e,this.statusText=t,this.content=n}}class _e{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""}}var Ee,Se,Ce,Ie,ke;!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"}(Ee||(Ee={}));class Te extends _e{constructor(e){if(super(),this._logger=e,"undefined"==typeof fetch){const e=require;this._jar=new(e("tough-cookie").CookieJar),this._fetchType=e("node-fetch"),this._fetchType=e("fetch-cookie")(this._fetchType,this._jar),this._abortControllerType=e("abort-controller")}else this._fetchType=fetch.bind(self),this._abortControllerType=AbortController}async send(e){if(e.abortSignal&&e.abortSignal.aborted)throw new ve;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 ve});let r,o=null;if(e.timeout){const r=e.timeout;o=setTimeout((()=>{t.abort(),this._logger.log(Ee.Warning,"Timeout from HTTP request."),n=new we}),r)}try{r=await this._fetchType(e.url,{body:e.content,cache:"no-cache",credentials:!0===e.withCredentials?"include":"same-origin",headers:{"Content-Type":"text/plain;charset=UTF-8","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(Ee.Warning,`Error from HTTP request. ${e}.`),e}finally{o&&clearTimeout(o),e.abortSignal&&(e.abortSignal.onabort=null)}if(!r.ok){const e=await xe(r,"text");throw new ye(e||r.statusText,r.status)}const i=xe(r,e.responseType),s=await i;return new be(r.status,r.statusText,s)}getCookieString(e){return""}}function xe(e,t){let n;switch(t){case"arraybuffer":n=e.arrayBuffer();break;case"text":n=e.text();break;case"blob":case"document":case"json":throw new Error(`${t} is not supported.`);default:n=e.text()}return n}class De extends _e{constructor(e){super(),this._logger=e}send(e){return e.abortSignal&&e.abortSignal.aborted?Promise.reject(new ve):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"),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 ve)}),e.timeout&&(r.timeout=e.timeout),r.onload=()=>{e.abortSignal&&(e.abortSignal.onabort=null),r.status>=200&&r.status<300?t(new be(r.status,r.statusText,r.response||r.responseText)):n(new ye(r.response||r.responseText||r.statusText,r.status))},r.onerror=()=>{this._logger.log(Ee.Warning,`Error from HTTP request. ${r.status}: ${r.statusText}.`),n(new ye(r.statusText,r.status))},r.ontimeout=()=>{this._logger.log(Ee.Warning,"Timeout from HTTP request."),n(new we)},r.send(e.content||"")})):Promise.reject(new Error("No url defined.")):Promise.reject(new Error("No method defined."))}}class Re extends _e{constructor(e){if(super(),"undefined"!=typeof fetch)this._httpClient=new Te(e);else{if("undefined"==typeof XMLHttpRequest)throw new Error("No usable HttpClient found.");this._httpClient=new De(e)}}send(e){return e.abortSignal&&e.abortSignal.aborted?Promise.reject(new ve):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)}}class Pe{}Pe.Authorization="Authorization",Pe.Cookie="Cookie",function(e){e[e.None=0]="None",e[e.WebSockets=1]="WebSockets",e[e.ServerSentEvents=2]="ServerSentEvents",e[e.LongPolling=4]="LongPolling"}(Se||(Se={})),function(e){e[e.Text=1]="Text",e[e.Binary=2]="Binary"}(Ce||(Ce={}));class Ue{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 Ae{constructor(){}log(e,t){}}Ae.instance=new Ae;class Ne{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 Be{static get isBrowser(){return"object"==typeof window}static get isWebWorker(){return"object"==typeof self&&"importScripts"in self}static get isNode(){return!this.isBrowser&&!this.isWebWorker}}function $e(e,t){let n="";return Le(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 Le(e){return e&&"undefined"!=typeof ArrayBuffer&&(e instanceof ArrayBuffer||e.constructor&&"ArrayBuffer"===e.constructor.name)}async function Me(e,t,n,r,o,i,s,a,c){let l={};if(o){const e=await o();e&&(l={Authorization:`Bearer ${e}`})}const[h,u]=Fe();l[h]=u,e.log(Ee.Trace,`(${t} transport) sending data. ${$e(i,s)}.`);const d=Le(i)?"arraybuffer":"text",p=await n.post(r,{content:i,headers:{...l,...c},responseType:d,withCredentials:a});e.log(Ee.Trace,`(${t} transport) request complete. Response status: ${p.statusCode}.`)}class He{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 Oe{constructor(e){this._minLevel=e,this.out=console}log(e,t){if(e>=this._minLevel){const n=`[${(new Date).toISOString()}] ${Ee[e]}: ${t}`;switch(e){case Ee.Critical:case Ee.Error:this.out.error(n);break;case Ee.Warning:this.out.warn(n);break;case Ee.Information:this.out.info(n);break;default:this.out.log(n)}}}}function Fe(){let e="X-SignalR-User-Agent";return Be.isNode&&(e="User-Agent"),[e,je("0.0.0-DEV_BUILD",We(),Be.isNode?"NodeJS":"Browser",ze())]}function je(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 We(){if(!Be.isNode)return"";switch(process.platform){case"win32":return"Windows NT";case"darwin":return"macOS";case"linux":return"Linux";default:return process.platform}}function ze(){if(Be.isNode)return process.versions.node}class qe{constructor(e,t,n,r,o,i){this._httpClient=e,this._accessTokenFactory=t,this._logger=n,this._pollAbort=new Ue,this._logMessageContent=r,this._withCredentials=o,this._headers=i,this._running=!1,this.onreceive=null,this.onclose=null}get pollAborted(){return this._pollAbort.aborted}async connect(e,t){if(Ne.isRequired(e,"url"),Ne.isRequired(t,"transferFormat"),Ne.isIn(t,Ce,"transferFormat"),this._url=e,this._logger.log(Ee.Trace,"(LongPolling transport) Connecting."),t===Ce.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]=Fe(),o={[n]:r,...this._headers},i={abortSignal:this._pollAbort.signal,headers:o,timeout:1e5,withCredentials:this._withCredentials};t===Ce.Binary&&(i.responseType="arraybuffer");const s=await this._getAccessToken();this._updateHeaderToken(i,s);const a=`${e}&_=${Date.now()}`;this._logger.log(Ee.Trace,`(LongPolling transport) polling: ${a}.`);const c=await this._httpClient.get(a,i);200!==c.statusCode?(this._logger.log(Ee.Error,`(LongPolling transport) Unexpected response code: ${c.statusCode}.`),this._closeError=new ye(c.statusText||"",c.statusCode),this._running=!1):this._running=!0,this._receiving=this._poll(this._url,i)}async _getAccessToken(){return this._accessTokenFactory?await this._accessTokenFactory():null}_updateHeaderToken(e,t){e.headers||(e.headers={}),t?e.headers[Pe.Authorization]=`Bearer ${t}`:e.headers[Pe.Authorization]&&delete e.headers[Pe.Authorization]}async _poll(e,t){try{for(;this._running;){const n=await this._getAccessToken();this._updateHeaderToken(t,n);try{const n=`${e}&_=${Date.now()}`;this._logger.log(Ee.Trace,`(LongPolling transport) polling: ${n}.`);const r=await this._httpClient.get(n,t);204===r.statusCode?(this._logger.log(Ee.Information,"(LongPolling transport) Poll terminated by server."),this._running=!1):200!==r.statusCode?(this._logger.log(Ee.Error,`(LongPolling transport) Unexpected response code: ${r.statusCode}.`),this._closeError=new ye(r.statusText||"",r.statusCode),this._running=!1):r.content?(this._logger.log(Ee.Trace,`(LongPolling transport) data received. ${$e(r.content,this._logMessageContent)}.`),this.onreceive&&this.onreceive(r.content)):this._logger.log(Ee.Trace,"(LongPolling transport) Poll timed out, reissuing.")}catch(e){this._running?e instanceof we?this._logger.log(Ee.Trace,"(LongPolling transport) Poll timed out, reissuing."):(this._closeError=e,this._running=!1):this._logger.log(Ee.Trace,`(LongPolling transport) Poll errored after shutdown: ${e.message}`)}}}finally{this._logger.log(Ee.Trace,"(LongPolling transport) Polling complete."),this.pollAborted||this._raiseOnClose()}}async send(e){return this._running?Me(this._logger,"LongPolling",this._httpClient,this._url,this._accessTokenFactory,e,this._logMessageContent,this._withCredentials,this._headers):Promise.reject(new Error("Cannot send until the transport is connected"))}async stop(){this._logger.log(Ee.Trace,"(LongPolling transport) Stopping polling."),this._running=!1,this._pollAbort.abort();try{await this._receiving,this._logger.log(Ee.Trace,`(LongPolling transport) sending DELETE request to ${this._url}.`);const e={},[t,n]=Fe();e[t]=n;const r={headers:{...e,...this._headers},withCredentials:this._withCredentials},o=await this._getAccessToken();this._updateHeaderToken(r,o),await this._httpClient.delete(this._url,r),this._logger.log(Ee.Trace,"(LongPolling transport) DELETE request sent.")}finally{this._logger.log(Ee.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(Ee.Trace,e),this.onclose(this._closeError)}}}class Je{constructor(e,t,n,r,o,i,s){this._httpClient=e,this._accessTokenFactory=t,this._logger=n,this._logMessageContent=r,this._withCredentials=i,this._eventSourceConstructor=o,this._headers=s,this.onreceive=null,this.onclose=null}async connect(e,t){if(Ne.isRequired(e,"url"),Ne.isRequired(t,"transferFormat"),Ne.isIn(t,Ce,"transferFormat"),this._logger.log(Ee.Trace,"(SSE transport) Connecting."),this._url=e,this._accessTokenFactory){const t=await this._accessTokenFactory();t&&(e+=(e.indexOf("?")<0?"?":"&")+`access_token=${encodeURIComponent(t)}`)}return new Promise(((n,r)=>{let o,i=!1;if(t===Ce.Text){if(Be.isBrowser||Be.isWebWorker)o=new this._eventSourceConstructor(e,{withCredentials:this._withCredentials});else{const t=this._httpClient.getCookieString(e),n={};n.Cookie=t;const[r,i]=Fe();n[r]=i,o=new this._eventSourceConstructor(e,{withCredentials:this._withCredentials,headers:{...n,...this._headers}})}try{o.onmessage=e=>{if(this.onreceive)try{this._logger.log(Ee.Trace,`(SSE transport) data received. ${$e(e.data,this._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(Ee.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?Me(this._logger,"SSE",this._httpClient,this._url,this._accessTokenFactory,e,this._logMessageContent,this._withCredentials,this._headers):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 Ke{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){if(Ne.isRequired(e,"url"),Ne.isRequired(t,"transferFormat"),Ne.isIn(t,Ce,"transferFormat"),this._logger.log(Ee.Trace,"(WebSockets transport) Connecting."),this._accessTokenFactory){const t=await this._accessTokenFactory();t&&(e+=(e.indexOf("?")<0?"?":"&")+`access_token=${encodeURIComponent(t)}`)}return new Promise(((n,r)=>{let o;e=e.replace(/^http/,"ws"),this._httpClient.getCookieString(e);let i=!1;o||(o=new this._webSocketConstructor(e)),t===Ce.Binary&&(o.binaryType="arraybuffer"),o.onopen=t=>{this._logger.log(Ee.Information,`WebSocket connected to ${e}.`),this._webSocket=o,i=!0,n()},o.onerror=e=>{let t=null;t="undefined"!=typeof ErrorEvent&&e instanceof ErrorEvent?e.error:"There was an error with the transport",this._logger.log(Ee.Information,`(WebSockets transport) ${t}.`)},o.onmessage=e=>{if(this._logger.log(Ee.Trace,`(WebSockets transport) data received. ${$e(e.data,this._logMessageContent)}.`),this.onreceive)try{this.onreceive(e.data)}catch(e){return void this._close(e)}},o.onclose=e=>{if(i)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(Ee.Trace,`(WebSockets transport) sending data. ${$e(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(Ee.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 Ve{constructor(e,t={}){var n;if(this._stopPromiseResolver=()=>{},this.features={},this._negotiateVersion=1,Ne.isRequired(e,"url"),this._logger=void 0===(n=t.logger)?new Oe(Ee.Information):null===n?Ae.instance:void 0!==n.log?n:new Oe(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,"undefined"==typeof WebSocket||t.WebSocket||(t.WebSocket=WebSocket),"undefined"==typeof EventSource||t.EventSource||(t.EventSource=EventSource),this._httpClient=t.httpClient||new Re(this._logger),this._connectionState="Disconnected",this._connectionStarted=!1,this._options=t,this.onreceive=null,this.onclose=null}async start(e){if(e=e||Ce.Binary,Ne.isIn(e,Ce,"transferFormat"),this._logger.log(Ee.Debug,`Starting connection with transfer format '${Ce[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(Ee.Error,e),await this._stopPromise,Promise.reject(new Error(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(Ee.Error,e),Promise.reject(new Error(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 Xe(this.transport)),this._sendQueue.send(e))}async stop(e){return"Disconnected"===this._connectionState?(this._logger.log(Ee.Debug,`Call to HttpConnection.stop(${e}) ignored because the connection is already in the disconnected state.`),Promise.resolve()):"Disconnecting"===this._connectionState?(this._logger.log(Ee.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(Ee.Error,`HttpConnection.transport.stop() threw error '${e}'.`),this._stopConnection()}this.transport=void 0}else this._logger.log(Ee.Debug,"HttpConnection.transport is undefined in HttpConnection.stop() because start() failed.")}async _startInternal(e){let t=this.baseUrl;this._accessTokenFactory=this._options.accessTokenFactory;try{if(this._options.skipNegotiation){if(this._options.transport!==Se.WebSockets)throw new Error("Negotiation can only be skipped when using the WebSocket transport directly.");this.transport=this._constructTransport(Se.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 Error("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}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 qe&&(this.features.inherentKeepAlive=!0),"Connecting"===this._connectionState&&(this._logger.log(Ee.Debug,"The HttpConnection connected successfully."),this._connectionState="Connected")}catch(e){return this._logger.log(Ee.Error,"Failed to start the connection: "+e),this._connectionState="Disconnected",this.transport=void 0,this._stopPromiseResolver(),Promise.reject(e)}}async _getNegotiationResponse(e){const t={};if(this._accessTokenFactory){const e=await this._accessTokenFactory();e&&(t[Pe.Authorization]=`Bearer ${e}`)}const[n,r]=Fe();t[n]=r;const o=this._resolveNegotiateUrl(e);this._logger.log(Ee.Debug,`Sending negotiation request: ${o}.`);try{const e=await this._httpClient.post(o,{content:"",headers:{...t,...this._options.headers},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 ye&&404===e.statusCode&&(t+=" Either this is not a SignalR endpoint or there is a proxy blocking the connection."),this._logger.log(Ee.Error,t),Promise.reject(new Error(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(Ee.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: ${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(Ee.Error,`Failed to start the transport '${n.transport}': ${e}`),a=void 0,i.push(`${n.transport} failed: ${e}`),"Connecting"!==this._connectionState){const e="Failed to select transport before stop() was called.";return this._logger.log(Ee.Debug,e),Promise.reject(new Error(e))}}}}return i.length>0?Promise.reject(new Error(`Unable to connect to the server with any of the available transports. ${i.join(" ")}`)):Promise.reject(new Error("None of the transports supported by the client are supported by the server."))}_constructTransport(e){switch(e){case Se.WebSockets:if(!this._options.WebSocket)throw new Error("'WebSocket' is not supported in your environment.");return new Ke(this._httpClient,this._accessTokenFactory,this._logger,this._options.logMessageContent||!1,this._options.WebSocket,this._options.headers||{});case Se.ServerSentEvents:if(!this._options.EventSource)throw new Error("'EventSource' is not supported in your environment.");return new Je(this._httpClient,this._accessTokenFactory,this._logger,this._options.logMessageContent||!1,this._options.EventSource,this._options.withCredentials,this._options.headers||{});case Se.LongPolling:return new qe(this._httpClient,this._accessTokenFactory,this._logger,this._options.logMessageContent||!1,this._options.withCredentials,this._options.headers||{});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=Se[e.transport];if(null==r)return this._logger.log(Ee.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(Ee.Debug,`Skipping transport '${Se[r]}' because it was disabled by the client.`),new Error(`'${Se[r]}' is disabled by the client.`);if(!(e.transferFormats.map((e=>Ce[e])).indexOf(n)>=0))return this._logger.log(Ee.Debug,`Skipping transport '${Se[r]}' because it does not support the requested transfer format '${Ce[n]}'.`),new Error(`'${Se[r]}' does not support ${Ce[n]}.`);if(r===Se.WebSockets&&!this._options.WebSocket||r===Se.ServerSentEvents&&!this._options.EventSource)return this._logger.log(Ee.Debug,`Skipping transport '${Se[r]}' because it is not supported in your environment.'`),new Error(`'${Se[r]}' is not supported in your environment.`);this._logger.log(Ee.Debug,`Selecting transport '${Se[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(Ee.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(Ee.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(Ee.Error,`Connection disconnected with error '${e}'.`):this._logger.log(Ee.Information,"Connection disconnected."),this._sendQueue&&(this._sendQueue.stop().catch((e=>{this._logger.log(Ee.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(Ee.Error,`HttpConnection.onclose(${e}) threw error '${t}'.`)}}}else this._logger.log(Ee.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(!Be.isBrowser||!window.document)throw new Error(`Cannot resolve '${e}'.`);const t=window.document.createElement("a");return t.href=e,this._logger.log(Ee.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 Xe{constructor(e){this._transport=e,this._buffer=[],this._executing=!0,this._sendBufferedData=new Ye,this._transportResult=new Ye,this._sendLoopPromise=this._sendLoop()}send(e){return this._bufferData(e),this._transportResult||(this._transportResult=new Ye),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 Ye;const e=this._transportResult;this._transportResult=void 0;const t="string"==typeof this._buffer[0]?this._buffer.join(""):Xe._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 Ye{constructor(){this.promise=new Promise(((e,t)=>[this._resolver,this._rejecter]=[e,t]))}resolve(){this._resolver()}reject(e){this._rejecter(e)}}class Ge{static write(e){return`${e}${Ge.RecordSeparator}`}static parse(e){if(e[e.length-1]!==Ge.RecordSeparator)throw new Error("Message is incomplete.");const t=e.split(Ge.RecordSeparator);return t.pop(),t}}Ge.RecordSeparatorCode=30,Ge.RecordSeparator=String.fromCharCode(Ge.RecordSeparatorCode);class Qe{writeHandshakeRequest(e){return Ge.write(JSON.stringify(e))}parseHandshakeResponse(e){let t,n;if(Le(e)){const r=new Uint8Array(e),o=r.indexOf(Ge.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(Ge.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=Ge.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"}(Ie||(Ie={}));class Ze{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 He(this,e)}}!function(e){e.Disconnected="Disconnected",e.Connecting="Connecting",e.Connected="Connected",e.Disconnecting="Disconnecting",e.Reconnecting="Reconnecting"}(ke||(ke={}));class et{constructor(e,t,n,r){this._nextKeepAlive=0,Ne.isRequired(e,"connection"),Ne.isRequired(t,"logger"),Ne.isRequired(n,"protocol"),this.serverTimeoutInMilliseconds=3e4,this.keepAliveIntervalInMilliseconds=15e3,this._logger=t,this._protocol=n,this.connection=e,this._reconnectPolicy=r,this._handshakeProtocol=new Qe,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=ke.Disconnected,this._connectionStarted=!1,this._cachedPingMessage=this._protocol.writeMessage({type:Ie.Ping})}static create(e,t,n,r){return new et(e,t,n,r)}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!==ke.Disconnected&&this._connectionState!==ke.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!==ke.Disconnected)return Promise.reject(new Error("Cannot start a HubConnection that is not in the 'Disconnected' state."));this._connectionState=ke.Connecting,this._logger.log(Ee.Debug,"Starting HubConnection.");try{await this._startInternal(),this._connectionState=ke.Connected,this._connectionStarted=!0,this._logger.log(Ee.Debug,"HubConnection connected successfully.")}catch(e){return this._connectionState=ke.Disconnected,this._logger.log(Ee.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(Ee.Debug,"Sending handshake request."),await this._sendMessage(this._handshakeProtocol.writeHandshakeRequest(t)),this._logger.log(Ee.Information,`Using HubProtocol '${this._protocol.name}'.`),this._cleanupTimeout(),this._resetTimeoutPeriod(),this._resetKeepAliveInterval(),await e,this._stopDuringStartError)throw this._stopDuringStartError}catch(e){throw this._logger.log(Ee.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){return this._connectionState===ke.Disconnected?(this._logger.log(Ee.Debug,`Call to HubConnection.stop(${e}) ignored because it is already in the disconnected state.`),Promise.resolve()):this._connectionState===ke.Disconnecting?(this._logger.log(Ee.Debug,`Call to HttpConnection.stop(${e}) ignored because the connection is already in the disconnecting state.`),this._stopPromise):(this._connectionState=ke.Disconnecting,this._logger.log(Ee.Debug,"Stopping HubConnection."),this._reconnectDelayHandle?(this._logger.log(Ee.Debug,"Connection stopped during reconnect delay. Done reconnecting."),clearTimeout(this._reconnectDelayHandle),this._reconnectDelayHandle=void 0,this._completeClose(),Promise.resolve()):(this._cleanupTimeout(),this._cleanupPingTimer(),this._stopDuringStartError=e||new Error("The connection was stopped before the hub handshake could complete."),this.connection.stop(e)))}stream(e,...t){const[n,r]=this._replaceStreamingParams(t),o=this._createStreamInvocation(e,t,r);let i;const s=new Ze;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===Ie.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===Ie.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 Ie.Invocation:this._invokeClientMethod(e);break;case Ie.StreamItem:case Ie.Completion:{const t=this._callbacks[e.invocationId];t&&(e.type===Ie.Completion&&delete this._callbacks[e.invocationId],t(e));break}case Ie.Ping:break;case Ie.Close:{this._logger.log(Ee.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(Ee.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(Ee.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(Ee.Error,e);const n=new Error(e);throw this._handshakeRejecter(n),n}return this._logger.log(Ee.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===ke.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."))}_invokeClientMethod(e){const t=this._methods[e.target.toLowerCase()];if(t){try{t.forEach((t=>t.apply(this,e.arguments)))}catch(t){this._logger.log(Ee.Error,`A callback for the method ${e.target.toLowerCase()} threw error '${t}'.`)}if(e.invocationId){const e="Server requested a response, which is not supported in this version of the client.";this._logger.log(Ee.Error,e),this._stopPromise=this._stopInternal(new Error(e))}}else this._logger.log(Ee.Warning,`No client method with the name '${e.target}' found.`)}_connectionClosed(e){this._logger.log(Ee.Debug,`HubConnection.connectionClosed(${e}) called while in state ${this._connectionState}.`),this._stopDuringStartError=this._stopDuringStartError||e||new Error("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===ke.Disconnecting?this._completeClose(e):this._connectionState===ke.Connected&&this._reconnectPolicy?this._reconnect(e):this._connectionState===ke.Connected&&this._completeClose(e)}_completeClose(e){if(this._connectionStarted){this._connectionState=ke.Disconnected,this._connectionStarted=!1;try{this._closedCallbacks.forEach((t=>t.apply(this,[e])))}catch(t){this._logger.log(Ee.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(Ee.Debug,"Connection not reconnecting because the IRetryPolicy returned null on the first reconnect attempt."),void this._completeClose(e);if(this._connectionState=ke.Reconnecting,e?this._logger.log(Ee.Information,`Connection reconnecting because of error '${e}'.`):this._logger.log(Ee.Information,"Connection reconnecting."),0!==this._reconnectingCallbacks.length){try{this._reconnectingCallbacks.forEach((t=>t.apply(this,[e])))}catch(t){this._logger.log(Ee.Error,`An onreconnecting callback called with error '${e}' threw error '${t}'.`)}if(this._connectionState!==ke.Reconnecting)return void this._logger.log(Ee.Debug,"Connection left the reconnecting state in onreconnecting callback. Done reconnecting.")}for(;null!==o;){if(this._logger.log(Ee.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!==ke.Reconnecting)return void this._logger.log(Ee.Debug,"Connection left the reconnecting state during reconnect delay. Done reconnecting.");try{if(await this._startInternal(),this._connectionState=ke.Connected,this._logger.log(Ee.Information,"HubConnection reconnected successfully."),0!==this._reconnectedCallbacks.length)try{this._reconnectedCallbacks.forEach((e=>e.apply(this,[this.connection.connectionId])))}catch(e){this._logger.log(Ee.Error,`An onreconnected callback called with connectionId '${this.connection.connectionId}; threw error '${e}'.`)}return}catch(e){if(this._logger.log(Ee.Information,`Reconnect attempt failed because of error '${e}'.`),this._connectionState!==ke.Reconnecting)return this._logger.log(Ee.Debug,`Connection moved to the '${this._connectionState}' from the reconnecting state during reconnect attempt. Done reconnecting.`),void(this._connectionState===ke.Disconnecting&&this._completeClose());r=e instanceof Error?e:new Error(e.toString()),o=this._getNextRetryDelay(n++,Date.now()-t,r)}}this._logger.log(Ee.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(Ee.Error,`IRetryPolicy.nextRetryDelayInMilliseconds(${e}, ${t}) threw error '${n}'.`),null}}_cancelCallbacksWithError(e){const t=this._callbacks;this._callbacks={},Object.keys(t).forEach((n=>{(0,t[n])(null,e)}))}_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:Ie.Invocation}:{arguments:t,target:e,type:Ie.Invocation};{const n=this._invocationId;return this._invocationId++,0!==r.length?{arguments:t,invocationId:n.toString(),streamIds:r,target:e,type:Ie.Invocation}:{arguments:t,invocationId:n.toString(),target:e,type:Ie.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 ut=ot?new TextDecoder:null,dt=ot?"undefined"!=typeof process&&"force"!==process.env.TEXT_DECODER?200:0:it,pt=function(e,t){this.type=e,this.data=t};function ft(e,t,n){var r=Math.floor(n/4294967296),o=n;e.setUint32(t,r),e.setUint32(t+4,o)}function gt(e,t){return 4294967296*e.getInt32(t)+e.getUint32(t+4)}var mt={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),ft(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:gt(t,4),nsec:t.getUint32(0)};default:throw new Error("Unrecognized data size for timestamp: "+e.length)}}(e);return new Date(1e3*t.sec+t.nsec/1e6)}},yt=function(){function e(){this.builtInEncoders=[],this.builtInDecoders=[],this.encoders=[],this.decoders=[],this.register(mt)}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 "+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: "+e+" bytes in UTF-8");this.writeU8(219),this.writeU32(e)}},e.prototype.encodeString=function(e){if(e.length>ct){var t=st(e);this.ensureBufferSizeToWrite(5+t),this.writeStringHeader(t),lt(e,this.bytes,this.pos),this.pos+=t}else t=st(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: "+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: "+t);this.writeU8(198),this.writeU32(t)}var n=wt(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: "+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=ht(e,t,n),i=Uint8Array.prototype.slice.call(e,t,t+n);return this.store(i,o),o},e}(),St=(_t=function(e,t){return(_t=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])})(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}_t(e,t),e.prototype=null===t?Object.create(t):(n.prototype=t.prototype,new n)}),Ct=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]1||a(e,t)}))})}function a(e,t){try{(n=o[e](t)).value instanceof kt?Promise.resolve(n.value.v).then(c,l):h(i[0][2],n)}catch(e){h(i[0][3],e)}var n}function c(e){a("next",e)}function l(e){a("throw",e)}function h(e,t){e(t),i.shift(),i.length&&a(i[0][0],i[0][1])}},xt=new DataView(new ArrayBuffer(0)),Dt=new Uint8Array(xt.buffer),Rt=function(){try{xt.getInt8(0)}catch(e){return e.constructor}throw new Error("never reached")}(),Pt=new Rt("Insufficient data"),Ut=4294967295,At=new Et,Nt=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 St(t,e),t}(Error),Bt=function(){function e(e,t,n,r,o,i,s,a){void 0===e&&(e=yt.defaultCodec),void 0===t&&(t=void 0),void 0===n&&(n=Ut),void 0===r&&(r=Ut),void 0===o&&(o=Ut),void 0===i&&(i=Ut),void 0===s&&(s=Ut),void 0===a&&(a=At),this.extensionCodec=e,this.context=t,this.maxStrLength=n,this.maxBinLength=r,this.maxArrayLength=o,this.maxMapLength=i,this.maxExtLength=s,this.keyDecoder=a,this.totalPos=0,this.pos=0,this.view=xt,this.bytes=Dt,this.headByte=-1,this.stack=[]}return e.prototype.reinitializeState=function(){this.totalPos=0,this.headByte=-1,this.stack.length=0},e.prototype.setBuffer=function(e){this.bytes=wt(e),this.view=function(e){if(e instanceof ArrayBuffer)return new DataView(e);var t=wt(e);return new DataView(t.buffer,t.byteOffset,t.byteLength)}(this.bytes),this.pos=0},e.prototype.appendBuffer=function(e){if(-1!==this.headByte||this.hasRemaining()){var t=this.bytes.subarray(this.pos),n=wt(e),r=new Uint8Array(t.length+n.length);r.set(t),r.set(n,t.length),this.setBuffer(r)}else this.setBuffer(e)},e.prototype.hasRemaining=function(e){return void 0===e&&(e=1),this.view.byteLength-this.pos>=e},e.prototype.createExtraByteError=function(e){var t=this.view,n=this.pos;return new RangeError("Extra "+(t.byteLength-n)+" of "+t.byteLength+" byte(s) found at buffer["+e+"]")},e.prototype.decode=function(e){this.reinitializeState(),this.setBuffer(e);var t=this.doDecodeSync();if(this.hasRemaining())throw this.createExtraByteError(this.pos);return t},e.prototype.decodeMulti=function(e){return Ct(this,(function(t){switch(t.label){case 0:this.reinitializeState(),this.setBuffer(e),t.label=1;case 1:return this.hasRemaining()?[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,u,d;return Ct(this,(function(p){switch(p.label){case 0:i=!1,p.label=1;case 1:p.trys.push([1,6,7,12]),t=It(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 Rt))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())throw this.createExtraByteError(this.totalPos);return[2,s]}throw h=(l=this).headByte,u=l.pos,d=l.totalPos,new RangeError("Insufficient data in parsing "+bt(h)+" at "+d+" ("+u+" 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 Tt(this,arguments,(function(){var n,r,o,i,s,a,c,l,h;return Ct(this,(function(u){switch(u.label){case 0:n=t,r=-1,u.label=1;case 1:u.trys.push([1,13,14,19]),o=It(e),u.label=2;case 2:return[4,kt(o.next())];case 3:if((i=u.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()),u.label=4;case 4:u.trys.push([4,9,,10]),u.label=5;case 5:return[4,kt(this.doDecodeSync())];case 6:return[4,u.sent()];case 7:return u.sent(),0==--r?[3,8]:[3,5];case 8:return[3,10];case 9:if(!((a=u.sent())instanceof Rt))throw a;return[3,10];case 10:this.totalPos+=this.pos,u.label=11;case 11:return[3,2];case 12:return[3,19];case 13:return c=u.sent(),l={error:c},[3,19];case 14:return u.trys.push([14,,17,18]),i&&!i.done&&(h=o.return)?[4,kt(h.call(o))]:[3,16];case 15:u.sent(),u.label=16;case 16:return[3,18];case 17:if(l)throw l.error;return[7];case 18:return[7];case 19:return[2]}}))}))},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 Nt("Unrecognized type byte: "+bt(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 Nt("The type of key must be string or number but "+typeof t);if("__proto__"===t)throw new Nt("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 Nt("Unrecognized array type byte: "+bt(e))}},e.prototype.pushMapState=function(e){if(e>this.maxMapLength)throw new Nt("Max length exceeded: map length ("+e+") > maxMapLengthLength ("+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 Nt("Max length exceeded: array length ("+e+") > maxArrayLength ("+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 Nt("Max length exceeded: UTF-8 byte length ("+e+") > maxStrLength ("+this.maxStrLength+")");if(this.bytes.byteLengthdt?function(e,t,n){var r=e.subarray(t,t+n);return ut.decode(r)}(this.bytes,o,e):ht(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 Nt("Max length exceeded: bin length ("+e+") > maxBinLength ("+this.maxBinLength+")");if(!this.hasRemaining(e+t))throw Pt;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 Nt("Max length exceeded: ext length ("+e+") > maxExtLength ("+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=gt(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 $t{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 Lt=new Uint8Array([145,Ie.Ping]);class Mt{constructor(e){this.name="messagepack",this.version=1,this.transferFormat=Ce.Binary,this._errorResult=1,this._voidResult=2,this._nonVoidResult=3,e=e||{},this._encoder=new vt(e.extensionCodec,e.context,e.maxDepth,e.initialBufferSize,e.sortKeys,e.forceFloat32,e.ignoreUndefined,e.forceIntegerToFloat),this._decoder=new Bt(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=Ae.instance);const r=$t.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 Ie.Invocation:return this._writeInvocation(e);case Ie.StreamInvocation:return this._writeStreamInvocation(e);case Ie.StreamItem:return this._writeStreamItem(e);case Ie.Completion:return this._writeCompletion(e);case Ie.Ping:return $t.write(Lt);case Ie.CancelInvocation:return this._writeCancelInvocation(e);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 Ie.Invocation:return this._createInvocationMessage(this._readHeaders(n),n);case Ie.StreamItem:return this._createStreamItemMessage(this._readHeaders(n),n);case Ie.Completion:return this._createCompletionMessage(this._readHeaders(n),n);case Ie.Ping:return this._createPingMessage(n);case Ie.Close:return this._createCloseMessage(n);default:return t.log(Ee.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:Ie.Close}}_createPingMessage(e){if(e.length<1)throw new Error("Invalid payload for Ping message.");return{type:Ie.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:Ie.Invocation}:{arguments:t[4],headers:e,streamIds:[],target:t[3],type:Ie.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:Ie.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:Ie.Completion}}_writeInvocation(e){let t;return t=e.streamIds?this._encoder.encode([Ie.Invocation,e.headers||{},e.invocationId||null,e.target,e.arguments,e.streamIds]):this._encoder.encode([Ie.Invocation,e.headers||{},e.invocationId||null,e.target,e.arguments]),$t.write(t.slice())}_writeStreamInvocation(e){let t;return t=e.streamIds?this._encoder.encode([Ie.StreamInvocation,e.headers||{},e.invocationId,e.target,e.arguments,e.streamIds]):this._encoder.encode([Ie.StreamInvocation,e.headers||{},e.invocationId,e.target,e.arguments]),$t.write(t.slice())}_writeStreamItem(e){const t=this._encoder.encode([Ie.StreamItem,e.headers||{},e.invocationId,e.item]);return $t.write(t.slice())}_writeCompletion(e){const t=e.error?this._errorResult:e.result?this._nonVoidResult:this._voidResult;let n;switch(t){case this._errorResult:n=this._encoder.encode([Ie.Completion,e.headers||{},e.invocationId,t,e.error]);break;case this._voidResult:n=this._encoder.encode([Ie.Completion,e.headers||{},e.invocationId,t]);break;case this._nonVoidResult:n=this._encoder.encode([Ie.Completion,e.headers||{},e.invocationId,t,e.result])}return $t.write(n.slice())}_writeCancelInvocation(e){const t=this._encoder.encode([Ie.CancelInvocation,e.headers||{},e.invocationId]);return $t.write(t.slice())}_readHeaders(e){const t=e[1];if("object"!=typeof t)throw new Error("Invalid headers.");return t}}let Ht=!1;const Ot="function"==typeof TextDecoder?new TextDecoder("utf-8"):null,Ft=Ot?Ot.decode.bind(Ot):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("")},jt=Math.pow(2,32),Wt=Math.pow(2,21)-1;function zt(e,t){return e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24}function qt(e,t){return e[t]+(e[t+1]<<8)+(e[t+2]<<16)+(e[t+3]<<24>>>0)}function Jt(e,t){const n=qt(e,t+4);if(n>Wt)throw new Error(`Cannot read uint64 with high order part ${n}, because the result would exceed Number.MAX_SAFE_INTEGER.`);return n*jt+qt(e,t)}class Kt{constructor(e){this.batchData=e;const t=new Gt(e);this.arrayRangeReader=new Qt(e),this.arrayBuilderSegmentReader=new Zt(e),this.diffReader=new Vt(e),this.editReader=new Xt(e,t),this.frameReader=new Yt(e,t)}updatedComponents(){return zt(this.batchData,this.batchData.length-20)}referenceFrames(){return zt(this.batchData,this.batchData.length-16)}disposedComponentIds(){return zt(this.batchData,this.batchData.length-12)}disposedEventHandlerIds(){return zt(this.batchData,this.batchData.length-8)}updatedComponentsEntry(e,t){const n=e+4*t;return zt(this.batchData,n)}referenceFramesEntry(e,t){return e+20*t}disposedComponentIdsEntry(e,t){const n=e+4*t;return zt(this.batchData,n)}disposedEventHandlerIdsEntry(e,t){const n=e+8*t;return Jt(this.batchData,n)}}class Vt{constructor(e){this.batchDataUint8=e}componentId(e){return zt(this.batchDataUint8,e)}edits(e){return e+4}editsEntry(e,t){return e+16*t}}class Xt{constructor(e,t){this.batchDataUint8=e,this.stringReader=t}editType(e){return zt(this.batchDataUint8,e)}siblingIndex(e){return zt(this.batchDataUint8,e+4)}newTreeIndex(e){return zt(this.batchDataUint8,e+8)}moveToSiblingIndex(e){return zt(this.batchDataUint8,e+8)}removedAttributeName(e){const t=zt(this.batchDataUint8,e+12);return this.stringReader.readString(t)}}class Yt{constructor(e,t){this.batchDataUint8=e,this.stringReader=t}frameType(e){return zt(this.batchDataUint8,e)}subtreeLength(e){return zt(this.batchDataUint8,e+4)}elementReferenceCaptureId(e){const t=zt(this.batchDataUint8,e+4);return this.stringReader.readString(t)}componentId(e){return zt(this.batchDataUint8,e+8)}elementName(e){const t=zt(this.batchDataUint8,e+8);return this.stringReader.readString(t)}textContent(e){const t=zt(this.batchDataUint8,e+4);return this.stringReader.readString(t)}markupContent(e){const t=zt(this.batchDataUint8,e+4);return this.stringReader.readString(t)}attributeName(e){const t=zt(this.batchDataUint8,e+4);return this.stringReader.readString(t)}attributeValue(e){const t=zt(this.batchDataUint8,e+8);return this.stringReader.readString(t)}attributeEventHandlerId(e){return Jt(this.batchDataUint8,e+12)}}class Gt{constructor(e){this.batchDataUint8=e,this.stringTableStartIndex=zt(e,e.length-4)}readString(e){if(-1===e)return null;{const n=zt(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(en.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(en.Debug,`Waiting for batch ${this.nextBatchId}. Batch ${e} not processed.`);try{this.nextBatchId++,this.logger.log(en.Debug,`Applying batch ${e}.`),function(e,t){const n=Q[e];if(!n)throw new Error(`There is no browser renderer with ID ${e}.`);const r=t.arrayRangeReader,o=t.updatedComponents(),i=r.values(o),s=r.count(o),a=t.referenceFrames(),c=r.values(a),l=t.diffReader;for(let e=0;e=this.minLevel){const n=`[${(new Date).toISOString()}] ${en[e]}: ${t}`;switch(e){case en.Critical:case en.Error:console.error(n);break;case en.Warning:console.warn(n);break;case en.Information:console.info(n);break;default:console.log(n)}}}}class on{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!==ke.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!==ke.Connected)return!1;const t=await e.invoke("StartCircuit",re.getBaseURI(),re.getLocationHref(),JSON.stringify(this.components.map((e=>e.toRecord()))),this.applicationState||"");return!!t&&(this.initialize(t),!0)}resolveElement(e){const t=Number.parseInt(e);if(Number.isNaN(t))throw new Error(`Invalid sequence number '${e}'.`);return function(e,t){if(!e.parentNode)throw new Error(`Comment not connected to the DOM ${e.textContent}`);const n=e.parentNode,r=k(n,!0),o=A(r);return Array.from(n.childNodes).forEach((e=>o.push(e))),e[C]=r,t&&(e[I]=t,k(t)),k(e)}(this.components[t].start,this.components[t].end)}}const sn={configureSignalR:e=>{},logLevel:en.Warning,reconnectionOptions:{maxRetries:8,retryIntervalMilliseconds:2e4,dialogId:"components-reconnect-modal"}};class an{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.modal.innerHTML='

Alternatively, reload

',this.message=this.modal.querySelector("h5"),this.button=this.modal.querySelector("button"),this.reloadParagraph=this.modal.querySelector("p"),this.loader=this.getLoader(),this.message.after(this.loader),this.button.addEventListener("click",(async()=>{this.show();try{await(null==fe?void 0:fe.reconnect)()||this.rejected()}catch(e){this.logger.log(en.Error,e),this.failed()}})),this.reloadParagraph.querySelector("a").addEventListener("click",(()=>location.reload()))}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",this.message.innerHTML="Reconnection failed. Try reloading the page if you're unable to reconnect.",this.message.querySelector("a").addEventListener("click",(()=>location.reload()))}rejected(){this.button.style.display="none",this.reloadParagraph.style.display="none",this.loader.style.display="none",this.message.innerHTML="Could not reconnect to the server. Reload the page to restore functionality.",this.message.querySelector("a").addEventListener("click",(()=>location.reload()))}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 cn{constructor(e,t,n){this.dialog=e,this.maxRetries=t,this.document=n,this.document=n;const r=this.document.getElementById(cn.MaxRetriesId);r&&(r.innerText=this.maxRetries.toString())}show(){this.removeClasses(),this.dialog.classList.add(cn.ShowClassName)}update(e){const t=this.document.getElementById(cn.CurrentAttemptId);t&&(t.innerText=e.toString())}hide(){this.removeClasses(),this.dialog.classList.add(cn.HideClassName)}failed(){this.removeClasses(),this.dialog.classList.add(cn.FailedClassName)}rejected(){this.removeClasses(),this.dialog.classList.add(cn.RejectedClassName)}removeClasses(){this.dialog.classList.remove(cn.ShowClassName,cn.HideClassName,cn.FailedClassName,cn.RejectedClassName)}}cn.ShowClassName="components-reconnect-show",cn.HideClassName="components-reconnect-hide",cn.FailedClassName="components-reconnect-failed",cn.RejectedClassName="components-reconnect-rejected",cn.MaxRetriesId="components-reconnect-max-retries",cn.CurrentAttemptId="components-reconnect-current-attempt";class ln{constructor(e,t,n){this._currentReconnectionProcess=null,this._logger=e,this._reconnectionDisplay=t,this._reconnectCallback=n||(()=>fe.reconnect())}onConnectionDown(e,t){if(!this._reconnectionDisplay){const t=document.getElementById(e.dialogId);this._reconnectionDisplay=t?new cn(t,e.maxRetries,document):new an(e.dialogId,e.maxRetries,document,this._logger)}this._currentReconnectionProcess||(this._currentReconnectionProcess=new hn(e,this._logger,this._reconnectCallback,this._reconnectionDisplay))}onConnectionUp(){this._currentReconnectionProcess&&(this._currentReconnectionProcess.dispose(),this._currentReconnectionProcess=null)}}class hn{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;thn.MaximumFirstRetryInterval?hn.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(en.Error,e)}}this.reconnectDisplay.failed()}delay(e){return new Promise((t=>setTimeout(t,e)))}}hn.MaximumFirstRetryInterval=3e3;const un=/^\s*Blazor-Component-State:(?[a-zA-Z0-9\+\/=]+)$/;function dn(e){var t;if(e.nodeType===Node.COMMENT_NODE){const n=e.textContent||"",r=un.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 gn(e,t){const n=e.currentElement;if(n&&n.nodeType===Node.COMMENT_NODE&&n.textContent){const r=fn.exec(n.textContent),o=r&&r.groups&&r.groups.descriptor;if(!o)return;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;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.");if(c){const e=mn(c,n);if(!e)throw new Error(`Could not find an end component comment for '${t}'`);return{type:r,assembly:o,typeName:i,parameterDefinitions:s&&atob(s),parameterValues:a&&atob(a),start:t,prerenderId:c,end:e}}return{type:r,assembly:o,typeName:i,parameterDefinitions:s&&atob(s),parameterValues:a&&atob(a),start:t}}}(r,n,e);case"server":return function(e,t,n){const{type:r,descriptor:o,sequence:i,prerenderId:s}=e;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)}'`);if(s){const e=mn(s,n);if(!e)throw new Error(`Could not find an end component comment for '${t}'`);return{type:r,sequence:i,descriptor:o,start:t,prerenderId:s,end:e}}return{type:r,sequence:i,descriptor:o,start:t}}}(r,n,e)}}catch(e){throw new Error(`Found malformed component comment at ${n.textContent}`)}}}function mn(e,t){for(;t.next()&&t.currentElement;){const n=t.currentElement;if(n.nodeType!==Node.COMMENT_NODE)continue;if(!n.textContent)continue;const r=fn.exec(n.textContent),o=r&&r[1];if(o)return yn(o,e),n}}function yn(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 wn{constructor(e){this.childNodes=e,this.currentIndex=-1,this.length=e.length}next(){return this.currentIndex++,this.currentIndexe.sequence-t.sequence))}(e)}(document),o=dn(document),i=new on(r,o||""),s=await Tn(t,n,i);if(!await i.startCircuit(s))return void n.log(en.Error,"Failed to start the circuit.");let a=!1;const c=()=>{if(!a){const e=new FormData,t=i.circuitId;e.append("circuitId",t),a=navigator.sendBeacon("_blazor/disconnect",e)}};fe.disconnect=c,window.addEventListener("unload",c,{capture:!1,once:!0}),fe.reconnect=async e=>{if(Cn)return!1;const r=e||await Tn(t,n,i);return await i.reconnect(r)?(t.reconnectionHandler.onConnectionUp(),!0):(n.log(en.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)},n.log(en.Information,"Blazor server-side application started.")}async function Tn(t,n,r){const i=new Mt;i.name="blazorpack";const s=(new rt).withUrl("_blazor").withHubProtocol(i);t.configureSignalR(s);const a=s.build();o=(e,t)=>{a.send("DispatchBrowserEvent",JSON.stringify(e),JSON.stringify(t))},fe._internal.navigationManager.listenForNavigationEvents(((e,t)=>a.send("OnLocationChanged",e,t))),a.on("JS.AttachComponent",((e,t)=>function(e,t,n){let r=Q[0];r||(r=Q[0]=new V(0)),r.attachRootComponentToLogicalElement(n,t)}(0,r.resolveElement(t),e))),a.on("JS.BeginInvokeJS",e.jsCallDispatcher.beginInvokeJSFromDotNet),a.on("JS.EndInvokeDotNet",e.jsCallDispatcher.endInvokeDotNetFromJS),a.on("JS.ReceiveByteArray",e.jsCallDispatcher.receiveByteArray);const c=tn.getOrCreate(n);a.on("JS.RenderBatch",((e,t)=>{n.log(en.Debug,`Received render batch with id ${e} and ${t.byteLength} bytes.`),c.processBatch(e,t,a)})),a.onclose((e=>!Cn&&t.reconnectionHandler.onConnectionDown(t.reconnectionOptions,e))),a.on("JS.Error",(e=>{Cn=!0,xn(a,e,n),async function(){let e=document.querySelector("#blazor-error-ui");e&&(e.style.display="block"),Ht||(Ht=!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()}})))}()})),fe._internal.forceCloseConnection=()=>a.stop(),fe._internal.sendJSDataStream=async(e,t,n)=>{setTimeout((async()=>{let r=5,o=(new Date).valueOf();try{const i=n-512;if(i<=0)throw new Error("The chunk size must be greater than 0.");let s=0;for(;s1)await a.send("SupplyJSDataChunk",t,c,null);else{if(!await a.invoke("SupplyJSDataChunk",t,c,null))break;const e=(new Date).valueOf(),n=e-o;o=e,r=Math.max(1,Math.round(500/n))}s+=n}}catch(e){await a.send("SupplyJSDataChunk",t,null,e.toString())}}),0)};try{await a.start()}catch(e){xn(a,e,n)}return e.attachDispatcher({beginInvokeDotNetFromJS:(e,t,n,r,o)=>{a.send("BeginInvokeDotNetFromJS",e?e.toString():null,t,n,r||0,o)},endInvokeJSFromDotNet:(e,t,n)=>{a.send("EndInvokeJSFromDotNet",e,t,n)},sendByteArray:(e,t)=>{a.send("ReceiveByteArray",e,t)}}),a}function xn(e,t,n){n.log(en.Error,t),e&&e.stop()}fe.start=kn,document&&document.currentScript&&"false"!==document.currentScript.getAttribute("autostart")&&kn()})(); \ No newline at end of file diff --git a/src/Components/Web.JS/src/Boot.Server.ts b/src/Components/Web.JS/src/Boot.Server.ts index a97d5a77e5d7..52d8c739d1a5 100644 --- a/src/Components/Web.JS/src/Boot.Server.ts +++ b/src/Components/Web.JS/src/Boot.Server.ts @@ -122,12 +122,7 @@ async function initializeConnection(options: CircuitStartOptions, logger: Logger Blazor._internal.forceCloseConnection = () => connection.stop(); - const activeJSDataStreams = new Set(); Blazor._internal.sendJSDataStream = async (data: ArrayBufferView, streamId: string, maximumIncomingBytes: number) => { - // First, add the current stream to the active streams. This ensures - // we'll be able to handle any (immediate) stream cancellation requests. - activeJSDataStreams.add(streamId); - // Run the rest in the background, without delaying the completion of the call to sendJSDataStream // otherwise we'll deadlock (.NET can't begin reading until this completes, but it won't complete // because nobody's reading the pipe) @@ -156,21 +151,17 @@ async function initializeConnection(options: CircuitStartOptions, logger: Logger // Most of the time just send and buffer within the network layer await connection.send('SupplyJSDataChunk', streamId, nextChunkData, null); } else { - // Check to see if the stream has been cancelled from .NET - // We do this check everytime we wait for an ACK to avoid this additional - // overhead on every single chunk. This means we'll still send a couple - // of SupplyJSDataChunk requests after cancellation (which will be ignored by .NET). - // If preferred, this check can be done on every chunk to avoid the lingering SupplyJSDataChunk calls. - if (!activeJSDataStreams.has(streamId)) { - break; - } - // But regularly, wait for an ACK, so other events can be interleaved // The use of "invoke" (not "send") here is what prevents the JS side from queuing up chunks // faster than the .NET side can receive them. It means that if there are other user interactions // while the transfer is in progress, they would get inserted in the middle, so it would be // possible to navigate away or cancel without first waiting for all the remaining chunks. - await connection.invoke('SupplyJSDataChunk', streamId, nextChunkData, null); + const streamIsAlive = await connection.invoke('SupplyJSDataChunk', streamId, nextChunkData, null); + + // Checks to see if we should continue streaming or if the stream has been cancelled/disposed. + if (!streamIsAlive) { + break; + } // Estimate the number of chunks we should send before the next ack to achieve the desired // interactivity rate @@ -184,16 +175,10 @@ async function initializeConnection(options: CircuitStartOptions, logger: Logger } } catch (error) { await connection.send('SupplyJSDataChunk', streamId, null, error.toString()); - } finally { - activeJSDataStreams.delete(streamId); } }, 0); }; - Blazor._internal.cancelJSDataStream = async (streamId: string) => { - activeJSDataStreams.delete(streamId); - } - try { await connection.start(); } catch (ex) { diff --git a/src/Components/Web.JS/src/GlobalExports.ts b/src/Components/Web.JS/src/GlobalExports.ts index 004a09ce635e..c5b04890ec48 100644 --- a/src/Components/Web.JS/src/GlobalExports.ts +++ b/src/Components/Web.JS/src/GlobalExports.ts @@ -50,7 +50,6 @@ interface IBlazor { getSatelliteAssemblies?: any, applyHotReload?: (id: string, metadataDelta: string, ilDelta: string) => void, sendJSDataStream?: (data: any, streamId: string, maximumIncomingBytes: number) => void, - cancelJSDataStream?: (streamId: string) => void, } } From e1635e69c848ac98905840f13530160cac672401 Mon Sep 17 00:00:00 2001 From: Tanay Parikh Date: Fri, 11 Jun 2021 16:37:36 -0700 Subject: [PATCH 09/37] Update blazor.server.js --- src/Components/Web.JS/dist/Release/blazor.server.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Components/Web.JS/dist/Release/blazor.server.js b/src/Components/Web.JS/dist/Release/blazor.server.js index 0ff753e17a64..91816a7857b7 100644 --- a/src/Components/Web.JS/dist/Release/blazor.server.js +++ b/src/Components/Web.JS/dist/Release/blazor.server.js @@ -1 +1 @@ -(()=>{"use strict";var e,t,n;!function(e){window.DotNet=e;const t=[],n=new Map;class r{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 o="__jsObjectId",i={},s={0:new r(window)};s[0]._cachedFunctions.set("import",(e=>("string"==typeof e&&e.startsWith("./")&&(e=document.baseURI+e.substr(2)),import(e))));let a,c=1,l=1,h=null;function u(e){t.push(e)}function d(e){if(e&&"object"==typeof e){s[l]=new r(e);const t={[o]:l};return l++,t}throw new Error(`Cannot create a JSObjectReference from the value '${e}'.`)}function p(e){return e?JSON.parse(e,((e,n)=>t.reduce(((t,n)=>n(e,t)),n))):null}function f(e,t,n,r){const o=m();if(o.invokeDotNetFromJS){const i=I(r),s=o.invokeDotNetFromJS(e,t,n,i);return s?p(s):null}throw new Error("The current dispatcher does not support synchronous calls from JS to .NET. Use invokeMethodAsync instead.")}function g(e,t,n,r){if(e&&n)throw new Error(`For instance method calls, assemblyName should be null. Received '${e}'.`);const o=c++,s=new Promise(((e,t)=>{i[o]={resolve:e,reject:t}}));try{const i=I(r);m().beginInvokeDotNetFromJS(o,e,t,n,i)}catch(e){y(o,!1,e)}return s}function m(){if(null!==h)return h;throw new Error("No .NET call dispatcher has been set.")}function y(e,t,n){if(!i.hasOwnProperty(e))throw new Error(`There is no pending async call with ID ${e}.`);const r=i[e];delete i[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 v(e,t){let n=s[t];if(n)return n.findFunction(e);throw new Error(`JS object instance with ID ${t} does not exist (has it been disposed?).`)}function b(e){delete s[e]}e.attachDispatcher=function(e){h=e},e.attachReviver=u,e.invokeMethod=function(e,t,...n){return f(e,t,null,n)},e.invokeMethodAsync=function(e,t,...n){return g(e,t,null,n)},e.createJSObjectReference=d,e.disposeJSObjectReference=function(e){const t=e&&e.__jsObjectId;"number"==typeof t&&b(t)},function(e){e[e.Default=0]="Default",e[e.JSObjectReference=1]="JSObjectReference"}(a=e.JSCallResultType||(e.JSCallResultType={})),e.jsCallDispatcher={findJSFunction:v,disposeJSObjectReferenceById:b,invokeJSFromDotNet:(e,t,n,r)=>{const o=S(v(e,r).apply(null,p(t)),n);return null==o?null:I(o)},beginInvokeJSFromDotNet:(e,t,n,r,o)=>{const i=new Promise((e=>{e(v(t,o).apply(null,p(n)))}));e&&i.then((t=>m().endInvokeJSFromDotNet(e,!0,I([e,!0,S(t,r)]))),(t=>m().endInvokeJSFromDotNet(e,!1,JSON.stringify([e,!1,w(t)]))))},endInvokeDotNetFromJS:(e,t,n)=>{const r=t?p(n):new Error(n);y(parseInt(e),t,r)},receiveByteArray:(e,t)=>{n.set(e,t)}};class _{constructor(e){this._id=e}invokeMethod(e,...t){return f(null,e,this._id,t)}invokeMethodAsync(e,...t){return g(null,e,this._id,t)}dispose(){g(null,"__Dispose",this._id,null).catch((e=>console.error(e)))}serializeAsArg(){return{__dotNetObject:this._id}}}const E="__byte[]";function S(e,t){switch(t){case a.Default:return e;case a.JSObjectReference:return d(e);default:throw new Error(`Invalid JS call result type '${t}'.`)}}u((function(e,t){if(t&&"object"==typeof t){if(t.hasOwnProperty("__dotNetObject"))return new _(t.__dotNetObject);if(t.hasOwnProperty(o)){const e=t.__jsObjectId,n=s[e];if(n)return n.getWrappedObject();throw new Error(`JS object instance with Id '${e}' does not exist. It may have been disposed.`)}if(t.hasOwnProperty(E)){const e=t["__byte[]"],r=n.get(e);if(void 0===r)throw new Error(`Byte array index '${e}' does not exist.`);return r}}return t}));let C=0;function I(e){return C=0,JSON.stringify(e,k)}function k(e,t){if(t instanceof _)return t.serializeAsArg();if(t instanceof Uint8Array){h.sendByteArray(C,t);const e={[E]:C};return C++,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"}(n||(n={}));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}}let o;function i(e,t){if(!o)throw new Error("eventDispatcher not initialized. Call 'setEventDispatcher' to configure it.");o(e,t)}const s=new Map,a=new Map,c={createEventArgs:()=>({})},l=[];function h(e){return s.get(e)}function u(e){const t=s.get(e);return(null==t?void 0:t.browserEventName)||e}function d(e,t){e.forEach((e=>s.set(e,t)))}function p(e){const t=[];for(let n=0;n{return{...f(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}}),d(["focus","blur","focusin","focusout"],c),d(["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};var t}}),d(["contextmenu","click","mouseover","mouseout","mousemove","mousedown","mouseup","dblclick"],{createEventArgs:e=>f(e)}),d(["error"],{createEventArgs:e=>{return{message:(t=e).message,filename:t.filename,lineno:t.lineno,colno:t.colno};var t}}),d(["loadstart","timeout","abort","load","loadend","progress"],{createEventArgs:e=>{return{lengthComputable:(t=e).lengthComputable,loaded:t.loaded,total:t.total};var t}}),d(["touchcancel","touchend","touchmove","touchenter","touchleave","touchstart"],{createEventArgs:e=>{return{detail:(t=e).detail,touches:p(t.touches),targetTouches:p(t.targetTouches),changedTouches:p(t.changedTouches),ctrlKey:t.ctrlKey,shiftKey:t.shiftKey,altKey:t.altKey,metaKey:t.metaKey,type:t.type};var t}}),d(["gotpointercapture","lostpointercapture","pointercancel","pointerdown","pointerenter","pointerleave","pointermove","pointerout","pointerover","pointerup"],{createEventArgs:e=>{return{...f(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}}),d(["wheel","mousewheel"],{createEventArgs:e=>{return{...f(t=e),deltaX:t.deltaX,deltaY:t.deltaY,deltaZ:t.deltaZ,deltaMode:t.deltaMode};var t}}),d(["toggle"],c);const g=["date","datetime-local","month","time","week"],m=E(["abort","blur","change","error","focus","load","loadend","loadstart","mouseenter","mouseleave","progress","reset","scroll","submit","unload","toggle","DOMNodeInsertedIntoDocument","DOMNodeRemovedFromDocument"]),y={submit:!0},w=E(["click","dblclick","mousedown","mousemove","mouseup"]);class v{constructor(e){this.browserRendererId=e,this.afterClickCallbacks=[];const t=++v.nextEventDelegatorId;this.eventsCollectionKey=`_blazorEvents_${t}`,this.eventInfoStore=new b(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,a.get(n));var n;t&&t.forEach((t=>this.dispatchGlobalEventToAllElements(t,e))),"click"===e.type&&this.afterClickCallbacks.forEach((t=>t(e)))}dispatchGlobalEventToAllElements(e,t){let n=t.target,o=null,s=!1;const a=m.hasOwnProperty(e);let c=!1;for(;n;){const d=this.getEventHandlerInfosForElement(n,!1);if(d){const a=d.getHandler(e);if(a&&(l=n,u=t.type,!((l instanceof HTMLButtonElement||l instanceof HTMLInputElement||l instanceof HTMLTextAreaElement||l instanceof HTMLSelectElement)&&w.hasOwnProperty(u)&&l.disabled))){if(!s){const n=h(e);o=(null==n?void 0:n.createEventArgs)?n.createEventArgs(t):{},s=!0}y.hasOwnProperty(t.type)&&t.preventDefault(),i({browserRendererId:this.browserRendererId,eventHandlerId:a.eventHandlerId,eventName:e,eventFieldInfo:r.fromEvent(a.renderingComponentId,t)},o)}d.stopPropagation(e)&&(c=!0),d.preventDefault(e)&&t.preventDefault()}n=a||c?null:n.parentElement}var l,u}getEventHandlerInfosForElement(e,t){return e.hasOwnProperty(this.eventsCollectionKey)?e[this.eventsCollectionKey]:t?e[this.eventsCollectionKey]=new _:null}}v.nextEventDelegatorId=0;class b{constructor(e){this.globalListener=e,this.infosByEventHandlerId={},this.countByEventName={},l.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=u(e),this.countByEventName.hasOwnProperty(e))this.countByEventName[e]++;else{this.countByEventName[e]=1;const t=m.hasOwnProperty(e);document.addEventListener(e,this.globalListener,t)}}update(e,t){if(this.infosByEventHandlerId.hasOwnProperty(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=u(t.eventName);0==--this.countByEventName[n]&&(delete this.countByEventName[n],document.removeEventListener(n,this.globalListener))}return t}handleEventNameAliasAdded(e,t){if(this.countByEventName.hasOwnProperty(e)){const n=this.countByEventName[e];delete this.countByEventName[e],document.removeEventListener(e,this.globalListener),this.addGlobalListener(t),this.countByEventName[t]+=n-1}}}class _{constructor(){this.handlers={},this.preventDefaultFlags=null,this.stopPropagationFlags=null}getHandler(e){return this.handlers.hasOwnProperty(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 E(e){const t={};return e.forEach((e=>{t[e]=!0})),t}const S=H("_blazorLogicalChildren"),C=H("_blazorLogicalParent"),I=H("_blazorLogicalEnd");function k(e,t){if(e.childNodes.length>0&&!t)throw new Error("New logical elements must start empty, or allowExistingContents must be true");return S in e||(e[S]=[]),e}function T(e,t){const n=document.createComment("!");return x(n,e,t),n}function x(e,t,n){const r=e;if(e instanceof Comment&&A(r)&&A(r).length>0)throw new Error("Not implemented: inserting non-empty logical container");if(R(r))throw new Error("Not implemented: moving existing logical children");const o=A(t);if(n0;)D(n,0)}const r=n;r.parentNode.removeChild(r)}function R(e){return e[C]||null}function P(e,t){return A(e)[t]}function U(e){var t=B(e);return"http://www.w3.org/2000/svg"===t.namespaceURI&&"foreignObject"!==t.tagName}function A(e){return e[S]}function N(e,t){const n=A(e);t.forEach((e=>{e.moveRangeStart=n[e.fromSiblingIndex],e.moveRangeEnd=L(e.moveRangeStart)})),t.forEach((t=>{const r=t.moveToBeforeMarker=document.createComment("marker"),o=n[t.toSiblingIndex+1];o?o.parentNode.insertBefore(r,o):M(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 B(e){if(e instanceof Element)return e;if(e instanceof Comment)return e.parentNode;throw new Error("Not a valid logical element")}function $(e){const t=A(R(e));return t[Array.prototype.indexOf.call(t,e)+1]||null}function M(e,t){if(t instanceof Element)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=$(t);n?n.parentNode.insertBefore(e,n):M(e,R(t))}}}function L(e){if(e instanceof Element)return e;const t=$(e);if(t)return t.previousSibling;{const t=R(e);return t instanceof Element?t.lastChild:L(t)}}function H(e){return"function"==typeof Symbol?Symbol():e}function F(e){return`_bl_${e}`}e.attachReviver(((e,t)=>t&&"object"==typeof t&&t.hasOwnProperty("__internalId")&&"string"==typeof t.__internalId?function(e){const t=`[${F(e)}]`;return document.querySelector(t)}(t.__internalId):t));const O="_blazorSelectValue",j=document.createElement("template"),W=document.createElementNS("http://www.w3.org/2000/svg","g"),z={},q="__internal_",J="preventDefault_",K="stopPropagation_";class V{constructor(e){this.childComponentLocations={},this.eventDelegator=new v(e),this.eventDelegator.notifyAfterClick((e=>{if(!ee)return;if(0!==e.button||function(e){return e.ctrlKey||e.shiftKey||e.altKey||e.metaKey}(e))return;if(e.defaultPrevented)return;const t=function(e){const t=!window._blazorDisableComposedPath&&e.composedPath&&e.composedPath();if(t){for(let e=0;ese(!1))))},enableNavigationInterception:function(){ee=!0},navigateTo:oe,getBaseURI:()=>document.baseURI,getLocationHref:()=>location.href};function oe(e,t,n=!1){const r=ce(e);if(!t&&he(r))ie(r,!1,n);else if(t&&location.href===e){const t=e+"?";history.replaceState(null,"",t),location.replace(e)}else n?history.replaceState(null,"",r):location.href=e}function ie(e,t,n=!1){Z=!0,n?history.replaceState(null,"",e):history.pushState(null,"",e),se(t)}async function se(e){ne&&await ne(location.href,e)}let ae;function ce(e){return ae=ae||document.createElement("a"),ae.href=e,ae.href}function le(e,t){return e?e.tagName===t?e:le(e.parentElement,t):null}function he(e){const t=(n=document.baseURI).substr(0,n.lastIndexOf("/")+1);var n;return e.startsWith(t)}const ue={init:function(e,t,n,r=50){const o=pe(t);(o||document.documentElement).style.overflowAnchor="none";const i=new IntersectionObserver((function(r){r.forEach((r=>{var o;if(!r.isIntersecting)return;const i=t.getBoundingClientRect(),s=n.getBoundingClientRect().top-i.bottom,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`});i.observe(t),i.observe(n);const s=c(t),a=c(n);function c(e){const t=new MutationObserver((()=>{i.unobserve(e),i.observe(e)}));return t.observe(e,{attributes:!0}),t}de[e._id]={intersectionObserver:i,mutationObserverBefore:s,mutationObserverAfter:a}},dispose:function(e){const t=de[e._id];t&&(t.intersectionObserver.disconnect(),t.mutationObserverBefore.disconnect(),t.mutationObserverAfter.disconnect(),e.dispose(),delete de[e._id])}},de={};function pe(e){return e?"visible"!==getComputedStyle(e).overflowY?e:pe(e.parentElement):null}const fe={navigateTo:oe,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=a.get(t.browserEventName);n?n.push(e):a.set(t.browserEventName,[e]),l.forEach((n=>n(e,t.browserEventName)))}s.set(e,t)},_internal:{navigationManager:re,domWrapper:{focus:function(e,t){if(!(e instanceof HTMLElement))throw new Error("Unable to focus an invalid element.");e.focus({preventScroll:t})}},Virtualize:ue}};window.Blazor=fe;const ge=[0,2e3,1e4,3e4,null];class me{constructor(e){this._retryDelays=void 0!==e?[...e,null]:ge}nextRetryDelayInMilliseconds(e){return this._retryDelays[e.previousRetryCount]}}class ye extends Error{constructor(e,t){const n=new.target.prototype;super(`${e}: Status code '${t}'`),this.statusCode=t,this.__proto__=n}}class we extends Error{constructor(e="A timeout occurred."){const t=new.target.prototype;super(e),this.__proto__=t}}class ve extends Error{constructor(e="An abort occurred."){const t=new.target.prototype;super(e),this.__proto__=t}}class be{constructor(e,t,n){this.statusCode=e,this.statusText=t,this.content=n}}class _e{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""}}var Ee,Se,Ce,Ie,ke;!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"}(Ee||(Ee={}));class Te extends _e{constructor(e){if(super(),this._logger=e,"undefined"==typeof fetch){const e=require;this._jar=new(e("tough-cookie").CookieJar),this._fetchType=e("node-fetch"),this._fetchType=e("fetch-cookie")(this._fetchType,this._jar),this._abortControllerType=e("abort-controller")}else this._fetchType=fetch.bind(self),this._abortControllerType=AbortController}async send(e){if(e.abortSignal&&e.abortSignal.aborted)throw new ve;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 ve});let r,o=null;if(e.timeout){const r=e.timeout;o=setTimeout((()=>{t.abort(),this._logger.log(Ee.Warning,"Timeout from HTTP request."),n=new we}),r)}try{r=await this._fetchType(e.url,{body:e.content,cache:"no-cache",credentials:!0===e.withCredentials?"include":"same-origin",headers:{"Content-Type":"text/plain;charset=UTF-8","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(Ee.Warning,`Error from HTTP request. ${e}.`),e}finally{o&&clearTimeout(o),e.abortSignal&&(e.abortSignal.onabort=null)}if(!r.ok){const e=await xe(r,"text");throw new ye(e||r.statusText,r.status)}const i=xe(r,e.responseType),s=await i;return new be(r.status,r.statusText,s)}getCookieString(e){return""}}function xe(e,t){let n;switch(t){case"arraybuffer":n=e.arrayBuffer();break;case"text":n=e.text();break;case"blob":case"document":case"json":throw new Error(`${t} is not supported.`);default:n=e.text()}return n}class De extends _e{constructor(e){super(),this._logger=e}send(e){return e.abortSignal&&e.abortSignal.aborted?Promise.reject(new ve):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"),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 ve)}),e.timeout&&(r.timeout=e.timeout),r.onload=()=>{e.abortSignal&&(e.abortSignal.onabort=null),r.status>=200&&r.status<300?t(new be(r.status,r.statusText,r.response||r.responseText)):n(new ye(r.response||r.responseText||r.statusText,r.status))},r.onerror=()=>{this._logger.log(Ee.Warning,`Error from HTTP request. ${r.status}: ${r.statusText}.`),n(new ye(r.statusText,r.status))},r.ontimeout=()=>{this._logger.log(Ee.Warning,"Timeout from HTTP request."),n(new we)},r.send(e.content||"")})):Promise.reject(new Error("No url defined.")):Promise.reject(new Error("No method defined."))}}class Re extends _e{constructor(e){if(super(),"undefined"!=typeof fetch)this._httpClient=new Te(e);else{if("undefined"==typeof XMLHttpRequest)throw new Error("No usable HttpClient found.");this._httpClient=new De(e)}}send(e){return e.abortSignal&&e.abortSignal.aborted?Promise.reject(new ve):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)}}class Pe{}Pe.Authorization="Authorization",Pe.Cookie="Cookie",function(e){e[e.None=0]="None",e[e.WebSockets=1]="WebSockets",e[e.ServerSentEvents=2]="ServerSentEvents",e[e.LongPolling=4]="LongPolling"}(Se||(Se={})),function(e){e[e.Text=1]="Text",e[e.Binary=2]="Binary"}(Ce||(Ce={}));class Ue{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 Ae{constructor(){}log(e,t){}}Ae.instance=new Ae;class Ne{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 Be{static get isBrowser(){return"object"==typeof window}static get isWebWorker(){return"object"==typeof self&&"importScripts"in self}static get isNode(){return!this.isBrowser&&!this.isWebWorker}}function $e(e,t){let n="";return Me(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 Me(e){return e&&"undefined"!=typeof ArrayBuffer&&(e instanceof ArrayBuffer||e.constructor&&"ArrayBuffer"===e.constructor.name)}async function Le(e,t,n,r,o,i,s,a,c){let l={};if(o){const e=await o();e&&(l={Authorization:`Bearer ${e}`})}const[h,u]=Oe();l[h]=u,e.log(Ee.Trace,`(${t} transport) sending data. ${$e(i,s)}.`);const d=Me(i)?"arraybuffer":"text",p=await n.post(r,{content:i,headers:{...l,...c},responseType:d,withCredentials:a});e.log(Ee.Trace,`(${t} transport) request complete. Response status: ${p.statusCode}.`)}class He{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 Fe{constructor(e){this._minLevel=e,this.out=console}log(e,t){if(e>=this._minLevel){const n=`[${(new Date).toISOString()}] ${Ee[e]}: ${t}`;switch(e){case Ee.Critical:case Ee.Error:this.out.error(n);break;case Ee.Warning:this.out.warn(n);break;case Ee.Information:this.out.info(n);break;default:this.out.log(n)}}}}function Oe(){let e="X-SignalR-User-Agent";return Be.isNode&&(e="User-Agent"),[e,je("0.0.0-DEV_BUILD",We(),Be.isNode?"NodeJS":"Browser",ze())]}function je(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 We(){if(!Be.isNode)return"";switch(process.platform){case"win32":return"Windows NT";case"darwin":return"macOS";case"linux":return"Linux";default:return process.platform}}function ze(){if(Be.isNode)return process.versions.node}class qe{constructor(e,t,n,r,o,i){this._httpClient=e,this._accessTokenFactory=t,this._logger=n,this._pollAbort=new Ue,this._logMessageContent=r,this._withCredentials=o,this._headers=i,this._running=!1,this.onreceive=null,this.onclose=null}get pollAborted(){return this._pollAbort.aborted}async connect(e,t){if(Ne.isRequired(e,"url"),Ne.isRequired(t,"transferFormat"),Ne.isIn(t,Ce,"transferFormat"),this._url=e,this._logger.log(Ee.Trace,"(LongPolling transport) Connecting."),t===Ce.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]=Oe(),o={[n]:r,...this._headers},i={abortSignal:this._pollAbort.signal,headers:o,timeout:1e5,withCredentials:this._withCredentials};t===Ce.Binary&&(i.responseType="arraybuffer");const s=await this._getAccessToken();this._updateHeaderToken(i,s);const a=`${e}&_=${Date.now()}`;this._logger.log(Ee.Trace,`(LongPolling transport) polling: ${a}.`);const c=await this._httpClient.get(a,i);200!==c.statusCode?(this._logger.log(Ee.Error,`(LongPolling transport) Unexpected response code: ${c.statusCode}.`),this._closeError=new ye(c.statusText||"",c.statusCode),this._running=!1):this._running=!0,this._receiving=this._poll(this._url,i)}async _getAccessToken(){return this._accessTokenFactory?await this._accessTokenFactory():null}_updateHeaderToken(e,t){e.headers||(e.headers={}),t?e.headers[Pe.Authorization]=`Bearer ${t}`:e.headers[Pe.Authorization]&&delete e.headers[Pe.Authorization]}async _poll(e,t){try{for(;this._running;){const n=await this._getAccessToken();this._updateHeaderToken(t,n);try{const n=`${e}&_=${Date.now()}`;this._logger.log(Ee.Trace,`(LongPolling transport) polling: ${n}.`);const r=await this._httpClient.get(n,t);204===r.statusCode?(this._logger.log(Ee.Information,"(LongPolling transport) Poll terminated by server."),this._running=!1):200!==r.statusCode?(this._logger.log(Ee.Error,`(LongPolling transport) Unexpected response code: ${r.statusCode}.`),this._closeError=new ye(r.statusText||"",r.statusCode),this._running=!1):r.content?(this._logger.log(Ee.Trace,`(LongPolling transport) data received. ${$e(r.content,this._logMessageContent)}.`),this.onreceive&&this.onreceive(r.content)):this._logger.log(Ee.Trace,"(LongPolling transport) Poll timed out, reissuing.")}catch(e){this._running?e instanceof we?this._logger.log(Ee.Trace,"(LongPolling transport) Poll timed out, reissuing."):(this._closeError=e,this._running=!1):this._logger.log(Ee.Trace,`(LongPolling transport) Poll errored after shutdown: ${e.message}`)}}}finally{this._logger.log(Ee.Trace,"(LongPolling transport) Polling complete."),this.pollAborted||this._raiseOnClose()}}async send(e){return this._running?Le(this._logger,"LongPolling",this._httpClient,this._url,this._accessTokenFactory,e,this._logMessageContent,this._withCredentials,this._headers):Promise.reject(new Error("Cannot send until the transport is connected"))}async stop(){this._logger.log(Ee.Trace,"(LongPolling transport) Stopping polling."),this._running=!1,this._pollAbort.abort();try{await this._receiving,this._logger.log(Ee.Trace,`(LongPolling transport) sending DELETE request to ${this._url}.`);const e={},[t,n]=Oe();e[t]=n;const r={headers:{...e,...this._headers},withCredentials:this._withCredentials},o=await this._getAccessToken();this._updateHeaderToken(r,o),await this._httpClient.delete(this._url,r),this._logger.log(Ee.Trace,"(LongPolling transport) DELETE request sent.")}finally{this._logger.log(Ee.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(Ee.Trace,e),this.onclose(this._closeError)}}}class Je{constructor(e,t,n,r,o,i,s){this._httpClient=e,this._accessTokenFactory=t,this._logger=n,this._logMessageContent=r,this._withCredentials=i,this._eventSourceConstructor=o,this._headers=s,this.onreceive=null,this.onclose=null}async connect(e,t){if(Ne.isRequired(e,"url"),Ne.isRequired(t,"transferFormat"),Ne.isIn(t,Ce,"transferFormat"),this._logger.log(Ee.Trace,"(SSE transport) Connecting."),this._url=e,this._accessTokenFactory){const t=await this._accessTokenFactory();t&&(e+=(e.indexOf("?")<0?"?":"&")+`access_token=${encodeURIComponent(t)}`)}return new Promise(((n,r)=>{let o,i=!1;if(t===Ce.Text){if(Be.isBrowser||Be.isWebWorker)o=new this._eventSourceConstructor(e,{withCredentials:this._withCredentials});else{const t=this._httpClient.getCookieString(e),n={};n.Cookie=t;const[r,i]=Oe();n[r]=i,o=new this._eventSourceConstructor(e,{withCredentials:this._withCredentials,headers:{...n,...this._headers}})}try{o.onmessage=e=>{if(this.onreceive)try{this._logger.log(Ee.Trace,`(SSE transport) data received. ${$e(e.data,this._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(Ee.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?Le(this._logger,"SSE",this._httpClient,this._url,this._accessTokenFactory,e,this._logMessageContent,this._withCredentials,this._headers):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 Ke{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){if(Ne.isRequired(e,"url"),Ne.isRequired(t,"transferFormat"),Ne.isIn(t,Ce,"transferFormat"),this._logger.log(Ee.Trace,"(WebSockets transport) Connecting."),this._accessTokenFactory){const t=await this._accessTokenFactory();t&&(e+=(e.indexOf("?")<0?"?":"&")+`access_token=${encodeURIComponent(t)}`)}return new Promise(((n,r)=>{let o;e=e.replace(/^http/,"ws"),this._httpClient.getCookieString(e);let i=!1;o||(o=new this._webSocketConstructor(e)),t===Ce.Binary&&(o.binaryType="arraybuffer"),o.onopen=t=>{this._logger.log(Ee.Information,`WebSocket connected to ${e}.`),this._webSocket=o,i=!0,n()},o.onerror=e=>{let t=null;t="undefined"!=typeof ErrorEvent&&e instanceof ErrorEvent?e.error:"There was an error with the transport",this._logger.log(Ee.Information,`(WebSockets transport) ${t}.`)},o.onmessage=e=>{if(this._logger.log(Ee.Trace,`(WebSockets transport) data received. ${$e(e.data,this._logMessageContent)}.`),this.onreceive)try{this.onreceive(e.data)}catch(e){return void this._close(e)}},o.onclose=e=>{if(i)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(Ee.Trace,`(WebSockets transport) sending data. ${$e(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(Ee.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 Ve{constructor(e,t={}){var n;if(this._stopPromiseResolver=()=>{},this.features={},this._negotiateVersion=1,Ne.isRequired(e,"url"),this._logger=void 0===(n=t.logger)?new Fe(Ee.Information):null===n?Ae.instance:void 0!==n.log?n:new Fe(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,"undefined"==typeof WebSocket||t.WebSocket||(t.WebSocket=WebSocket),"undefined"==typeof EventSource||t.EventSource||(t.EventSource=EventSource),this._httpClient=t.httpClient||new Re(this._logger),this._connectionState="Disconnected",this._connectionStarted=!1,this._options=t,this.onreceive=null,this.onclose=null}async start(e){if(e=e||Ce.Binary,Ne.isIn(e,Ce,"transferFormat"),this._logger.log(Ee.Debug,`Starting connection with transfer format '${Ce[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(Ee.Error,e),await this._stopPromise,Promise.reject(new Error(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(Ee.Error,e),Promise.reject(new Error(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 Xe(this.transport)),this._sendQueue.send(e))}async stop(e){return"Disconnected"===this._connectionState?(this._logger.log(Ee.Debug,`Call to HttpConnection.stop(${e}) ignored because the connection is already in the disconnected state.`),Promise.resolve()):"Disconnecting"===this._connectionState?(this._logger.log(Ee.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(Ee.Error,`HttpConnection.transport.stop() threw error '${e}'.`),this._stopConnection()}this.transport=void 0}else this._logger.log(Ee.Debug,"HttpConnection.transport is undefined in HttpConnection.stop() because start() failed.")}async _startInternal(e){let t=this.baseUrl;this._accessTokenFactory=this._options.accessTokenFactory;try{if(this._options.skipNegotiation){if(this._options.transport!==Se.WebSockets)throw new Error("Negotiation can only be skipped when using the WebSocket transport directly.");this.transport=this._constructTransport(Se.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 Error("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}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 qe&&(this.features.inherentKeepAlive=!0),"Connecting"===this._connectionState&&(this._logger.log(Ee.Debug,"The HttpConnection connected successfully."),this._connectionState="Connected")}catch(e){return this._logger.log(Ee.Error,"Failed to start the connection: "+e),this._connectionState="Disconnected",this.transport=void 0,this._stopPromiseResolver(),Promise.reject(e)}}async _getNegotiationResponse(e){const t={};if(this._accessTokenFactory){const e=await this._accessTokenFactory();e&&(t[Pe.Authorization]=`Bearer ${e}`)}const[n,r]=Oe();t[n]=r;const o=this._resolveNegotiateUrl(e);this._logger.log(Ee.Debug,`Sending negotiation request: ${o}.`);try{const e=await this._httpClient.post(o,{content:"",headers:{...t,...this._options.headers},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 ye&&404===e.statusCode&&(t+=" Either this is not a SignalR endpoint or there is a proxy blocking the connection."),this._logger.log(Ee.Error,t),Promise.reject(new Error(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(Ee.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: ${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(Ee.Error,`Failed to start the transport '${n.transport}': ${e}`),a=void 0,i.push(`${n.transport} failed: ${e}`),"Connecting"!==this._connectionState){const e="Failed to select transport before stop() was called.";return this._logger.log(Ee.Debug,e),Promise.reject(new Error(e))}}}}return i.length>0?Promise.reject(new Error(`Unable to connect to the server with any of the available transports. ${i.join(" ")}`)):Promise.reject(new Error("None of the transports supported by the client are supported by the server."))}_constructTransport(e){switch(e){case Se.WebSockets:if(!this._options.WebSocket)throw new Error("'WebSocket' is not supported in your environment.");return new Ke(this._httpClient,this._accessTokenFactory,this._logger,this._options.logMessageContent||!1,this._options.WebSocket,this._options.headers||{});case Se.ServerSentEvents:if(!this._options.EventSource)throw new Error("'EventSource' is not supported in your environment.");return new Je(this._httpClient,this._accessTokenFactory,this._logger,this._options.logMessageContent||!1,this._options.EventSource,this._options.withCredentials,this._options.headers||{});case Se.LongPolling:return new qe(this._httpClient,this._accessTokenFactory,this._logger,this._options.logMessageContent||!1,this._options.withCredentials,this._options.headers||{});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=Se[e.transport];if(null==r)return this._logger.log(Ee.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(Ee.Debug,`Skipping transport '${Se[r]}' because it was disabled by the client.`),new Error(`'${Se[r]}' is disabled by the client.`);if(!(e.transferFormats.map((e=>Ce[e])).indexOf(n)>=0))return this._logger.log(Ee.Debug,`Skipping transport '${Se[r]}' because it does not support the requested transfer format '${Ce[n]}'.`),new Error(`'${Se[r]}' does not support ${Ce[n]}.`);if(r===Se.WebSockets&&!this._options.WebSocket||r===Se.ServerSentEvents&&!this._options.EventSource)return this._logger.log(Ee.Debug,`Skipping transport '${Se[r]}' because it is not supported in your environment.'`),new Error(`'${Se[r]}' is not supported in your environment.`);this._logger.log(Ee.Debug,`Selecting transport '${Se[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(Ee.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(Ee.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(Ee.Error,`Connection disconnected with error '${e}'.`):this._logger.log(Ee.Information,"Connection disconnected."),this._sendQueue&&(this._sendQueue.stop().catch((e=>{this._logger.log(Ee.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(Ee.Error,`HttpConnection.onclose(${e}) threw error '${t}'.`)}}}else this._logger.log(Ee.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(!Be.isBrowser||!window.document)throw new Error(`Cannot resolve '${e}'.`);const t=window.document.createElement("a");return t.href=e,this._logger.log(Ee.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 Xe{constructor(e){this._transport=e,this._buffer=[],this._executing=!0,this._sendBufferedData=new Ye,this._transportResult=new Ye,this._sendLoopPromise=this._sendLoop()}send(e){return this._bufferData(e),this._transportResult||(this._transportResult=new Ye),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 Ye;const e=this._transportResult;this._transportResult=void 0;const t="string"==typeof this._buffer[0]?this._buffer.join(""):Xe._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 Ye{constructor(){this.promise=new Promise(((e,t)=>[this._resolver,this._rejecter]=[e,t]))}resolve(){this._resolver()}reject(e){this._rejecter(e)}}class Ge{static write(e){return`${e}${Ge.RecordSeparator}`}static parse(e){if(e[e.length-1]!==Ge.RecordSeparator)throw new Error("Message is incomplete.");const t=e.split(Ge.RecordSeparator);return t.pop(),t}}Ge.RecordSeparatorCode=30,Ge.RecordSeparator=String.fromCharCode(Ge.RecordSeparatorCode);class Qe{writeHandshakeRequest(e){return Ge.write(JSON.stringify(e))}parseHandshakeResponse(e){let t,n;if(Me(e)){const r=new Uint8Array(e),o=r.indexOf(Ge.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(Ge.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=Ge.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"}(Ie||(Ie={}));class Ze{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 He(this,e)}}!function(e){e.Disconnected="Disconnected",e.Connecting="Connecting",e.Connected="Connected",e.Disconnecting="Disconnecting",e.Reconnecting="Reconnecting"}(ke||(ke={}));class et{constructor(e,t,n,r){this._nextKeepAlive=0,Ne.isRequired(e,"connection"),Ne.isRequired(t,"logger"),Ne.isRequired(n,"protocol"),this.serverTimeoutInMilliseconds=3e4,this.keepAliveIntervalInMilliseconds=15e3,this._logger=t,this._protocol=n,this.connection=e,this._reconnectPolicy=r,this._handshakeProtocol=new Qe,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=ke.Disconnected,this._connectionStarted=!1,this._cachedPingMessage=this._protocol.writeMessage({type:Ie.Ping})}static create(e,t,n,r){return new et(e,t,n,r)}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!==ke.Disconnected&&this._connectionState!==ke.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!==ke.Disconnected)return Promise.reject(new Error("Cannot start a HubConnection that is not in the 'Disconnected' state."));this._connectionState=ke.Connecting,this._logger.log(Ee.Debug,"Starting HubConnection.");try{await this._startInternal(),this._connectionState=ke.Connected,this._connectionStarted=!0,this._logger.log(Ee.Debug,"HubConnection connected successfully.")}catch(e){return this._connectionState=ke.Disconnected,this._logger.log(Ee.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(Ee.Debug,"Sending handshake request."),await this._sendMessage(this._handshakeProtocol.writeHandshakeRequest(t)),this._logger.log(Ee.Information,`Using HubProtocol '${this._protocol.name}'.`),this._cleanupTimeout(),this._resetTimeoutPeriod(),this._resetKeepAliveInterval(),await e,this._stopDuringStartError)throw this._stopDuringStartError}catch(e){throw this._logger.log(Ee.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){return this._connectionState===ke.Disconnected?(this._logger.log(Ee.Debug,`Call to HubConnection.stop(${e}) ignored because it is already in the disconnected state.`),Promise.resolve()):this._connectionState===ke.Disconnecting?(this._logger.log(Ee.Debug,`Call to HttpConnection.stop(${e}) ignored because the connection is already in the disconnecting state.`),this._stopPromise):(this._connectionState=ke.Disconnecting,this._logger.log(Ee.Debug,"Stopping HubConnection."),this._reconnectDelayHandle?(this._logger.log(Ee.Debug,"Connection stopped during reconnect delay. Done reconnecting."),clearTimeout(this._reconnectDelayHandle),this._reconnectDelayHandle=void 0,this._completeClose(),Promise.resolve()):(this._cleanupTimeout(),this._cleanupPingTimer(),this._stopDuringStartError=e||new Error("The connection was stopped before the hub handshake could complete."),this.connection.stop(e)))}stream(e,...t){const[n,r]=this._replaceStreamingParams(t),o=this._createStreamInvocation(e,t,r);let i;const s=new Ze;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===Ie.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===Ie.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 Ie.Invocation:this._invokeClientMethod(e);break;case Ie.StreamItem:case Ie.Completion:{const t=this._callbacks[e.invocationId];t&&(e.type===Ie.Completion&&delete this._callbacks[e.invocationId],t(e));break}case Ie.Ping:break;case Ie.Close:{this._logger.log(Ee.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(Ee.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(Ee.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(Ee.Error,e);const n=new Error(e);throw this._handshakeRejecter(n),n}return this._logger.log(Ee.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===ke.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."))}_invokeClientMethod(e){const t=this._methods[e.target.toLowerCase()];if(t){try{t.forEach((t=>t.apply(this,e.arguments)))}catch(t){this._logger.log(Ee.Error,`A callback for the method ${e.target.toLowerCase()} threw error '${t}'.`)}if(e.invocationId){const e="Server requested a response, which is not supported in this version of the client.";this._logger.log(Ee.Error,e),this._stopPromise=this._stopInternal(new Error(e))}}else this._logger.log(Ee.Warning,`No client method with the name '${e.target}' found.`)}_connectionClosed(e){this._logger.log(Ee.Debug,`HubConnection.connectionClosed(${e}) called while in state ${this._connectionState}.`),this._stopDuringStartError=this._stopDuringStartError||e||new Error("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===ke.Disconnecting?this._completeClose(e):this._connectionState===ke.Connected&&this._reconnectPolicy?this._reconnect(e):this._connectionState===ke.Connected&&this._completeClose(e)}_completeClose(e){if(this._connectionStarted){this._connectionState=ke.Disconnected,this._connectionStarted=!1;try{this._closedCallbacks.forEach((t=>t.apply(this,[e])))}catch(t){this._logger.log(Ee.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(Ee.Debug,"Connection not reconnecting because the IRetryPolicy returned null on the first reconnect attempt."),void this._completeClose(e);if(this._connectionState=ke.Reconnecting,e?this._logger.log(Ee.Information,`Connection reconnecting because of error '${e}'.`):this._logger.log(Ee.Information,"Connection reconnecting."),0!==this._reconnectingCallbacks.length){try{this._reconnectingCallbacks.forEach((t=>t.apply(this,[e])))}catch(t){this._logger.log(Ee.Error,`An onreconnecting callback called with error '${e}' threw error '${t}'.`)}if(this._connectionState!==ke.Reconnecting)return void this._logger.log(Ee.Debug,"Connection left the reconnecting state in onreconnecting callback. Done reconnecting.")}for(;null!==o;){if(this._logger.log(Ee.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!==ke.Reconnecting)return void this._logger.log(Ee.Debug,"Connection left the reconnecting state during reconnect delay. Done reconnecting.");try{if(await this._startInternal(),this._connectionState=ke.Connected,this._logger.log(Ee.Information,"HubConnection reconnected successfully."),0!==this._reconnectedCallbacks.length)try{this._reconnectedCallbacks.forEach((e=>e.apply(this,[this.connection.connectionId])))}catch(e){this._logger.log(Ee.Error,`An onreconnected callback called with connectionId '${this.connection.connectionId}; threw error '${e}'.`)}return}catch(e){if(this._logger.log(Ee.Information,`Reconnect attempt failed because of error '${e}'.`),this._connectionState!==ke.Reconnecting)return this._logger.log(Ee.Debug,`Connection moved to the '${this._connectionState}' from the reconnecting state during reconnect attempt. Done reconnecting.`),void(this._connectionState===ke.Disconnecting&&this._completeClose());r=e instanceof Error?e:new Error(e.toString()),o=this._getNextRetryDelay(n++,Date.now()-t,r)}}this._logger.log(Ee.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(Ee.Error,`IRetryPolicy.nextRetryDelayInMilliseconds(${e}, ${t}) threw error '${n}'.`),null}}_cancelCallbacksWithError(e){const t=this._callbacks;this._callbacks={},Object.keys(t).forEach((n=>{(0,t[n])(null,e)}))}_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:Ie.Invocation}:{arguments:t,target:e,type:Ie.Invocation};{const n=this._invocationId;return this._invocationId++,0!==r.length?{arguments:t,invocationId:n.toString(),streamIds:r,target:e,type:Ie.Invocation}:{arguments:t,invocationId:n.toString(),target:e,type:Ie.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 ut=ot?new TextDecoder:null,dt=ot?"undefined"!=typeof process&&"force"!==process.env.TEXT_DECODER?200:0:it,pt=function(e,t){this.type=e,this.data=t};function ft(e,t,n){var r=Math.floor(n/4294967296),o=n;e.setUint32(t,r),e.setUint32(t+4,o)}function gt(e,t){return 4294967296*e.getInt32(t)+e.getUint32(t+4)}var mt={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),ft(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:gt(t,4),nsec:t.getUint32(0)};default:throw new Error("Unrecognized data size for timestamp: "+e.length)}}(e);return new Date(1e3*t.sec+t.nsec/1e6)}},yt=function(){function e(){this.builtInEncoders=[],this.builtInDecoders=[],this.encoders=[],this.decoders=[],this.register(mt)}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 "+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: "+e+" bytes in UTF-8");this.writeU8(219),this.writeU32(e)}},e.prototype.encodeString=function(e){if(e.length>ct){var t=st(e);this.ensureBufferSizeToWrite(5+t),this.writeStringHeader(t),lt(e,this.bytes,this.pos),this.pos+=t}else t=st(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: "+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: "+t);this.writeU8(198),this.writeU32(t)}var n=wt(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: "+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=ht(e,t,n),i=Uint8Array.prototype.slice.call(e,t,t+n);return this.store(i,o),o},e}(),St=(_t=function(e,t){return(_t=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])})(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}_t(e,t),e.prototype=null===t?Object.create(t):(n.prototype=t.prototype,new n)}),Ct=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]1||a(e,t)}))})}function a(e,t){try{(n=o[e](t)).value instanceof kt?Promise.resolve(n.value.v).then(c,l):h(i[0][2],n)}catch(e){h(i[0][3],e)}var n}function c(e){a("next",e)}function l(e){a("throw",e)}function h(e,t){e(t),i.shift(),i.length&&a(i[0][0],i[0][1])}},xt=new DataView(new ArrayBuffer(0)),Dt=new Uint8Array(xt.buffer),Rt=function(){try{xt.getInt8(0)}catch(e){return e.constructor}throw new Error("never reached")}(),Pt=new Rt("Insufficient data"),Ut=4294967295,At=new Et,Nt=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 St(t,e),t}(Error),Bt=function(){function e(e,t,n,r,o,i,s,a){void 0===e&&(e=yt.defaultCodec),void 0===t&&(t=void 0),void 0===n&&(n=Ut),void 0===r&&(r=Ut),void 0===o&&(o=Ut),void 0===i&&(i=Ut),void 0===s&&(s=Ut),void 0===a&&(a=At),this.extensionCodec=e,this.context=t,this.maxStrLength=n,this.maxBinLength=r,this.maxArrayLength=o,this.maxMapLength=i,this.maxExtLength=s,this.keyDecoder=a,this.totalPos=0,this.pos=0,this.view=xt,this.bytes=Dt,this.headByte=-1,this.stack=[]}return e.prototype.reinitializeState=function(){this.totalPos=0,this.headByte=-1,this.stack.length=0},e.prototype.setBuffer=function(e){this.bytes=wt(e),this.view=function(e){if(e instanceof ArrayBuffer)return new DataView(e);var t=wt(e);return new DataView(t.buffer,t.byteOffset,t.byteLength)}(this.bytes),this.pos=0},e.prototype.appendBuffer=function(e){if(-1!==this.headByte||this.hasRemaining()){var t=this.bytes.subarray(this.pos),n=wt(e),r=new Uint8Array(t.length+n.length);r.set(t),r.set(n,t.length),this.setBuffer(r)}else this.setBuffer(e)},e.prototype.hasRemaining=function(e){return void 0===e&&(e=1),this.view.byteLength-this.pos>=e},e.prototype.createExtraByteError=function(e){var t=this.view,n=this.pos;return new RangeError("Extra "+(t.byteLength-n)+" of "+t.byteLength+" byte(s) found at buffer["+e+"]")},e.prototype.decode=function(e){this.reinitializeState(),this.setBuffer(e);var t=this.doDecodeSync();if(this.hasRemaining())throw this.createExtraByteError(this.pos);return t},e.prototype.decodeMulti=function(e){return Ct(this,(function(t){switch(t.label){case 0:this.reinitializeState(),this.setBuffer(e),t.label=1;case 1:return this.hasRemaining()?[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,u,d;return Ct(this,(function(p){switch(p.label){case 0:i=!1,p.label=1;case 1:p.trys.push([1,6,7,12]),t=It(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 Rt))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())throw this.createExtraByteError(this.totalPos);return[2,s]}throw h=(l=this).headByte,u=l.pos,d=l.totalPos,new RangeError("Insufficient data in parsing "+bt(h)+" at "+d+" ("+u+" 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 Tt(this,arguments,(function(){var n,r,o,i,s,a,c,l,h;return Ct(this,(function(u){switch(u.label){case 0:n=t,r=-1,u.label=1;case 1:u.trys.push([1,13,14,19]),o=It(e),u.label=2;case 2:return[4,kt(o.next())];case 3:if((i=u.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()),u.label=4;case 4:u.trys.push([4,9,,10]),u.label=5;case 5:return[4,kt(this.doDecodeSync())];case 6:return[4,u.sent()];case 7:return u.sent(),0==--r?[3,8]:[3,5];case 8:return[3,10];case 9:if(!((a=u.sent())instanceof Rt))throw a;return[3,10];case 10:this.totalPos+=this.pos,u.label=11;case 11:return[3,2];case 12:return[3,19];case 13:return c=u.sent(),l={error:c},[3,19];case 14:return u.trys.push([14,,17,18]),i&&!i.done&&(h=o.return)?[4,kt(h.call(o))]:[3,16];case 15:u.sent(),u.label=16;case 16:return[3,18];case 17:if(l)throw l.error;return[7];case 18:return[7];case 19:return[2]}}))}))},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 Nt("Unrecognized type byte: "+bt(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 Nt("The type of key must be string or number but "+typeof t);if("__proto__"===t)throw new Nt("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 Nt("Unrecognized array type byte: "+bt(e))}},e.prototype.pushMapState=function(e){if(e>this.maxMapLength)throw new Nt("Max length exceeded: map length ("+e+") > maxMapLengthLength ("+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 Nt("Max length exceeded: array length ("+e+") > maxArrayLength ("+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 Nt("Max length exceeded: UTF-8 byte length ("+e+") > maxStrLength ("+this.maxStrLength+")");if(this.bytes.byteLengthdt?function(e,t,n){var r=e.subarray(t,t+n);return ut.decode(r)}(this.bytes,o,e):ht(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 Nt("Max length exceeded: bin length ("+e+") > maxBinLength ("+this.maxBinLength+")");if(!this.hasRemaining(e+t))throw Pt;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 Nt("Max length exceeded: ext length ("+e+") > maxExtLength ("+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=gt(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 $t{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 Mt=new Uint8Array([145,Ie.Ping]);class Lt{constructor(e){this.name="messagepack",this.version=1,this.transferFormat=Ce.Binary,this._errorResult=1,this._voidResult=2,this._nonVoidResult=3,e=e||{},this._encoder=new vt(e.extensionCodec,e.context,e.maxDepth,e.initialBufferSize,e.sortKeys,e.forceFloat32,e.ignoreUndefined,e.forceIntegerToFloat),this._decoder=new Bt(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=Ae.instance);const r=$t.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 Ie.Invocation:return this._writeInvocation(e);case Ie.StreamInvocation:return this._writeStreamInvocation(e);case Ie.StreamItem:return this._writeStreamItem(e);case Ie.Completion:return this._writeCompletion(e);case Ie.Ping:return $t.write(Mt);case Ie.CancelInvocation:return this._writeCancelInvocation(e);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 Ie.Invocation:return this._createInvocationMessage(this._readHeaders(n),n);case Ie.StreamItem:return this._createStreamItemMessage(this._readHeaders(n),n);case Ie.Completion:return this._createCompletionMessage(this._readHeaders(n),n);case Ie.Ping:return this._createPingMessage(n);case Ie.Close:return this._createCloseMessage(n);default:return t.log(Ee.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:Ie.Close}}_createPingMessage(e){if(e.length<1)throw new Error("Invalid payload for Ping message.");return{type:Ie.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:Ie.Invocation}:{arguments:t[4],headers:e,streamIds:[],target:t[3],type:Ie.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:Ie.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:Ie.Completion}}_writeInvocation(e){let t;return t=e.streamIds?this._encoder.encode([Ie.Invocation,e.headers||{},e.invocationId||null,e.target,e.arguments,e.streamIds]):this._encoder.encode([Ie.Invocation,e.headers||{},e.invocationId||null,e.target,e.arguments]),$t.write(t.slice())}_writeStreamInvocation(e){let t;return t=e.streamIds?this._encoder.encode([Ie.StreamInvocation,e.headers||{},e.invocationId,e.target,e.arguments,e.streamIds]):this._encoder.encode([Ie.StreamInvocation,e.headers||{},e.invocationId,e.target,e.arguments]),$t.write(t.slice())}_writeStreamItem(e){const t=this._encoder.encode([Ie.StreamItem,e.headers||{},e.invocationId,e.item]);return $t.write(t.slice())}_writeCompletion(e){const t=e.error?this._errorResult:e.result?this._nonVoidResult:this._voidResult;let n;switch(t){case this._errorResult:n=this._encoder.encode([Ie.Completion,e.headers||{},e.invocationId,t,e.error]);break;case this._voidResult:n=this._encoder.encode([Ie.Completion,e.headers||{},e.invocationId,t]);break;case this._nonVoidResult:n=this._encoder.encode([Ie.Completion,e.headers||{},e.invocationId,t,e.result])}return $t.write(n.slice())}_writeCancelInvocation(e){const t=this._encoder.encode([Ie.CancelInvocation,e.headers||{},e.invocationId]);return $t.write(t.slice())}_readHeaders(e){const t=e[1];if("object"!=typeof t)throw new Error("Invalid headers.");return t}}let Ht=!1;const Ft="function"==typeof TextDecoder?new TextDecoder("utf-8"):null,Ot=Ft?Ft.decode.bind(Ft):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("")},jt=Math.pow(2,32),Wt=Math.pow(2,21)-1;function zt(e,t){return e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24}function qt(e,t){return e[t]+(e[t+1]<<8)+(e[t+2]<<16)+(e[t+3]<<24>>>0)}function Jt(e,t){const n=qt(e,t+4);if(n>Wt)throw new Error(`Cannot read uint64 with high order part ${n}, because the result would exceed Number.MAX_SAFE_INTEGER.`);return n*jt+qt(e,t)}class Kt{constructor(e){this.batchData=e;const t=new Gt(e);this.arrayRangeReader=new Qt(e),this.arrayBuilderSegmentReader=new Zt(e),this.diffReader=new Vt(e),this.editReader=new Xt(e,t),this.frameReader=new Yt(e,t)}updatedComponents(){return zt(this.batchData,this.batchData.length-20)}referenceFrames(){return zt(this.batchData,this.batchData.length-16)}disposedComponentIds(){return zt(this.batchData,this.batchData.length-12)}disposedEventHandlerIds(){return zt(this.batchData,this.batchData.length-8)}updatedComponentsEntry(e,t){const n=e+4*t;return zt(this.batchData,n)}referenceFramesEntry(e,t){return e+20*t}disposedComponentIdsEntry(e,t){const n=e+4*t;return zt(this.batchData,n)}disposedEventHandlerIdsEntry(e,t){const n=e+8*t;return Jt(this.batchData,n)}}class Vt{constructor(e){this.batchDataUint8=e}componentId(e){return zt(this.batchDataUint8,e)}edits(e){return e+4}editsEntry(e,t){return e+16*t}}class Xt{constructor(e,t){this.batchDataUint8=e,this.stringReader=t}editType(e){return zt(this.batchDataUint8,e)}siblingIndex(e){return zt(this.batchDataUint8,e+4)}newTreeIndex(e){return zt(this.batchDataUint8,e+8)}moveToSiblingIndex(e){return zt(this.batchDataUint8,e+8)}removedAttributeName(e){const t=zt(this.batchDataUint8,e+12);return this.stringReader.readString(t)}}class Yt{constructor(e,t){this.batchDataUint8=e,this.stringReader=t}frameType(e){return zt(this.batchDataUint8,e)}subtreeLength(e){return zt(this.batchDataUint8,e+4)}elementReferenceCaptureId(e){const t=zt(this.batchDataUint8,e+4);return this.stringReader.readString(t)}componentId(e){return zt(this.batchDataUint8,e+8)}elementName(e){const t=zt(this.batchDataUint8,e+8);return this.stringReader.readString(t)}textContent(e){const t=zt(this.batchDataUint8,e+4);return this.stringReader.readString(t)}markupContent(e){const t=zt(this.batchDataUint8,e+4);return this.stringReader.readString(t)}attributeName(e){const t=zt(this.batchDataUint8,e+4);return this.stringReader.readString(t)}attributeValue(e){const t=zt(this.batchDataUint8,e+8);return this.stringReader.readString(t)}attributeEventHandlerId(e){return Jt(this.batchDataUint8,e+12)}}class Gt{constructor(e){this.batchDataUint8=e,this.stringTableStartIndex=zt(e,e.length-4)}readString(e){if(-1===e)return null;{const n=zt(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(en.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(en.Debug,`Waiting for batch ${this.nextBatchId}. Batch ${e} not processed.`);try{this.nextBatchId++,this.logger.log(en.Debug,`Applying batch ${e}.`),function(e,t){const n=Q[e];if(!n)throw new Error(`There is no browser renderer with ID ${e}.`);const r=t.arrayRangeReader,o=t.updatedComponents(),i=r.values(o),s=r.count(o),a=t.referenceFrames(),c=r.values(a),l=t.diffReader;for(let e=0;e=this.minLevel){const n=`[${(new Date).toISOString()}] ${en[e]}: ${t}`;switch(e){case en.Critical:case en.Error:console.error(n);break;case en.Warning:console.warn(n);break;case en.Information:console.info(n);break;default:console.log(n)}}}}class on{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!==ke.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!==ke.Connected)return!1;const t=await e.invoke("StartCircuit",re.getBaseURI(),re.getLocationHref(),JSON.stringify(this.components.map((e=>e.toRecord()))),this.applicationState||"");return!!t&&(this.initialize(t),!0)}resolveElement(e){const t=Number.parseInt(e);if(Number.isNaN(t))throw new Error(`Invalid sequence number '${e}'.`);return function(e,t){if(!e.parentNode)throw new Error(`Comment not connected to the DOM ${e.textContent}`);const n=e.parentNode,r=k(n,!0),o=A(r);return Array.from(n.childNodes).forEach((e=>o.push(e))),e[C]=r,t&&(e[I]=t,k(t)),k(e)}(this.components[t].start,this.components[t].end)}}const sn={configureSignalR:e=>{},logLevel:en.Warning,reconnectionOptions:{maxRetries:8,retryIntervalMilliseconds:2e4,dialogId:"components-reconnect-modal"}};class an{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.modal.innerHTML='

Alternatively, reload

',this.message=this.modal.querySelector("h5"),this.button=this.modal.querySelector("button"),this.reloadParagraph=this.modal.querySelector("p"),this.loader=this.getLoader(),this.message.after(this.loader),this.button.addEventListener("click",(async()=>{this.show();try{await(null==fe?void 0:fe.reconnect)()||this.rejected()}catch(e){this.logger.log(en.Error,e),this.failed()}})),this.reloadParagraph.querySelector("a").addEventListener("click",(()=>location.reload()))}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",this.message.innerHTML="Reconnection failed. Try reloading the page if you're unable to reconnect.",this.message.querySelector("a").addEventListener("click",(()=>location.reload()))}rejected(){this.button.style.display="none",this.reloadParagraph.style.display="none",this.loader.style.display="none",this.message.innerHTML="Could not reconnect to the server. Reload the page to restore functionality.",this.message.querySelector("a").addEventListener("click",(()=>location.reload()))}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 cn{constructor(e,t,n){this.dialog=e,this.maxRetries=t,this.document=n,this.document=n;const r=this.document.getElementById(cn.MaxRetriesId);r&&(r.innerText=this.maxRetries.toString())}show(){this.removeClasses(),this.dialog.classList.add(cn.ShowClassName)}update(e){const t=this.document.getElementById(cn.CurrentAttemptId);t&&(t.innerText=e.toString())}hide(){this.removeClasses(),this.dialog.classList.add(cn.HideClassName)}failed(){this.removeClasses(),this.dialog.classList.add(cn.FailedClassName)}rejected(){this.removeClasses(),this.dialog.classList.add(cn.RejectedClassName)}removeClasses(){this.dialog.classList.remove(cn.ShowClassName,cn.HideClassName,cn.FailedClassName,cn.RejectedClassName)}}cn.ShowClassName="components-reconnect-show",cn.HideClassName="components-reconnect-hide",cn.FailedClassName="components-reconnect-failed",cn.RejectedClassName="components-reconnect-rejected",cn.MaxRetriesId="components-reconnect-max-retries",cn.CurrentAttemptId="components-reconnect-current-attempt";class ln{constructor(e,t,n){this._currentReconnectionProcess=null,this._logger=e,this._reconnectionDisplay=t,this._reconnectCallback=n||(()=>fe.reconnect())}onConnectionDown(e,t){if(!this._reconnectionDisplay){const t=document.getElementById(e.dialogId);this._reconnectionDisplay=t?new cn(t,e.maxRetries,document):new an(e.dialogId,e.maxRetries,document,this._logger)}this._currentReconnectionProcess||(this._currentReconnectionProcess=new hn(e,this._logger,this._reconnectCallback,this._reconnectionDisplay))}onConnectionUp(){this._currentReconnectionProcess&&(this._currentReconnectionProcess.dispose(),this._currentReconnectionProcess=null)}}class hn{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;thn.MaximumFirstRetryInterval?hn.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(en.Error,e)}}this.reconnectDisplay.failed()}delay(e){return new Promise((t=>setTimeout(t,e)))}}hn.MaximumFirstRetryInterval=3e3;const un=/^\s*Blazor-Component-State:(?[a-zA-Z0-9\+\/=]+)$/;function dn(e){var t;if(e.nodeType===Node.COMMENT_NODE){const n=e.textContent||"",r=un.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 gn(e,t){const n=e.currentElement;if(n&&n.nodeType===Node.COMMENT_NODE&&n.textContent){const r=fn.exec(n.textContent),o=r&&r.groups&&r.groups.descriptor;if(!o)return;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;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.");if(c){const e=mn(c,n);if(!e)throw new Error(`Could not find an end component comment for '${t}'`);return{type:r,assembly:o,typeName:i,parameterDefinitions:s&&atob(s),parameterValues:a&&atob(a),start:t,prerenderId:c,end:e}}return{type:r,assembly:o,typeName:i,parameterDefinitions:s&&atob(s),parameterValues:a&&atob(a),start:t}}}(r,n,e);case"server":return function(e,t,n){const{type:r,descriptor:o,sequence:i,prerenderId:s}=e;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)}'`);if(s){const e=mn(s,n);if(!e)throw new Error(`Could not find an end component comment for '${t}'`);return{type:r,sequence:i,descriptor:o,start:t,prerenderId:s,end:e}}return{type:r,sequence:i,descriptor:o,start:t}}}(r,n,e)}}catch(e){throw new Error(`Found malformed component comment at ${n.textContent}`)}}}function mn(e,t){for(;t.next()&&t.currentElement;){const n=t.currentElement;if(n.nodeType!==Node.COMMENT_NODE)continue;if(!n.textContent)continue;const r=fn.exec(n.textContent),o=r&&r[1];if(o)return yn(o,e),n}}function yn(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 wn{constructor(e){this.childNodes=e,this.currentIndex=-1,this.length=e.length}next(){return this.currentIndex++,this.currentIndexe.sequence-t.sequence))}(e)}(document),o=dn(document),i=new on(r,o||""),s=await Tn(t,n,i);if(!await i.startCircuit(s))return void n.log(en.Error,"Failed to start the circuit.");let a=!1;const c=()=>{if(!a){const e=new FormData,t=i.circuitId;e.append("circuitId",t),a=navigator.sendBeacon("_blazor/disconnect",e)}};fe.disconnect=c,window.addEventListener("unload",c,{capture:!1,once:!0}),fe.reconnect=async e=>{if(Cn)return!1;const r=e||await Tn(t,n,i);return await i.reconnect(r)?(t.reconnectionHandler.onConnectionUp(),!0):(n.log(en.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)},n.log(en.Information,"Blazor server-side application started.")}async function Tn(t,n,r){const i=new Lt;i.name="blazorpack";const s=(new rt).withUrl("_blazor").withHubProtocol(i);t.configureSignalR(s);const a=s.build();o=(e,t)=>{a.send("DispatchBrowserEvent",JSON.stringify(e),JSON.stringify(t))},fe._internal.navigationManager.listenForNavigationEvents(((e,t)=>a.send("OnLocationChanged",e,t))),a.on("JS.AttachComponent",((e,t)=>function(e,t,n){let r=Q[0];r||(r=Q[0]=new V(0)),r.attachRootComponentToLogicalElement(n,t)}(0,r.resolveElement(t),e))),a.on("JS.BeginInvokeJS",e.jsCallDispatcher.beginInvokeJSFromDotNet),a.on("JS.EndInvokeDotNet",e.jsCallDispatcher.endInvokeDotNetFromJS),a.on("JS.ReceiveByteArray",e.jsCallDispatcher.receiveByteArray);const c=tn.getOrCreate(n);a.on("JS.RenderBatch",((e,t)=>{n.log(en.Debug,`Received render batch with id ${e} and ${t.byteLength} bytes.`),c.processBatch(e,t,a)})),a.onclose((e=>!Cn&&t.reconnectionHandler.onConnectionDown(t.reconnectionOptions,e))),a.on("JS.Error",(e=>{Cn=!0,xn(a,e,n),async function(){let e=document.querySelector("#blazor-error-ui");e&&(e.style.display="block"),Ht||(Ht=!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()}})))}()})),fe._internal.forceCloseConnection=()=>a.stop();try{await a.start()}catch(e){xn(a,e,n)}return e.attachDispatcher({beginInvokeDotNetFromJS:(e,t,n,r,o)=>{a.send("BeginInvokeDotNetFromJS",e?e.toString():null,t,n,r||0,o)},endInvokeJSFromDotNet:(e,t,n)=>{a.send("EndInvokeJSFromDotNet",e,t,n)},sendByteArray:(e,t)=>{a.send("ReceiveByteArray",e,t)}}),a}function xn(e,t,n){n.log(en.Error,t),e&&e.stop()}fe.start=kn,document&&document.currentScript&&"false"!==document.currentScript.getAttribute("autostart")&&kn()})(); \ No newline at end of file +(()=>{"use strict";var e,t,n;!function(e){window.DotNet=e;const t=[],n=new Map;class r{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 o="__jsObjectId",i={},s={0:new r(window)};s[0]._cachedFunctions.set("import",(e=>("string"==typeof e&&e.startsWith("./")&&(e=document.baseURI+e.substr(2)),import(e))));let a,c=1,l=1,h=null;function u(e){t.push(e)}function d(e){if(e&&"object"==typeof e){s[l]=new r(e);let t={[o]:l};return e.buffer instanceof ArrayBuffer&&void 0!==e.byteLength&&(t.__jsDataReferenceLength=e.byteLength),l++,t}throw new Error(`Cannot create a JSObjectReference from the value '${e}'.`)}function p(e){return e?JSON.parse(e,((e,n)=>t.reduce(((t,n)=>n(e,t)),n))):null}function f(e,t,n,r){const o=m();if(o.invokeDotNetFromJS){const i=I(r),s=o.invokeDotNetFromJS(e,t,n,i);return s?p(s):null}throw new Error("The current dispatcher does not support synchronous calls from JS to .NET. Use invokeMethodAsync instead.")}function g(e,t,n,r){if(e&&n)throw new Error(`For instance method calls, assemblyName should be null. Received '${e}'.`);const o=c++,s=new Promise(((e,t)=>{i[o]={resolve:e,reject:t}}));try{const i=I(r);m().beginInvokeDotNetFromJS(o,e,t,n,i)}catch(e){y(o,!1,e)}return s}function m(){if(null!==h)return h;throw new Error("No .NET call dispatcher has been set.")}function y(e,t,n){if(!i.hasOwnProperty(e))throw new Error(`There is no pending async call with ID ${e}.`);const r=i[e];delete i[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 v(e,t){let n=s[t];if(n)return n.findFunction(e);throw new Error(`JS object instance with ID ${t} does not exist (has it been disposed?).`)}function b(e){delete s[e]}e.attachDispatcher=function(e){h=e},e.attachReviver=u,e.invokeMethod=function(e,t,...n){return f(e,t,null,n)},e.invokeMethodAsync=function(e,t,...n){return g(e,t,null,n)},e.createJSObjectReference=d,e.disposeJSObjectReference=function(e){const t=e&&e.__jsObjectId;"number"==typeof t&&b(t)},function(e){e[e.Default=0]="Default",e[e.JSObjectReference=1]="JSObjectReference"}(a=e.JSCallResultType||(e.JSCallResultType={})),e.jsCallDispatcher={findJSFunction:v,disposeJSObjectReferenceById:b,invokeJSFromDotNet:(e,t,n,r)=>{const o=S(v(e,r).apply(null,p(t)),n);return null==o?null:I(o)},beginInvokeJSFromDotNet:(e,t,n,r,o)=>{const i=new Promise((e=>{e(v(t,o).apply(null,p(n)))}));e&&i.then((t=>m().endInvokeJSFromDotNet(e,!0,I([e,!0,S(t,r)]))),(t=>m().endInvokeJSFromDotNet(e,!1,JSON.stringify([e,!1,w(t)]))))},endInvokeDotNetFromJS:(e,t,n)=>{const r=t?p(n):new Error(n);y(parseInt(e),t,r)},receiveByteArray:(e,t)=>{n.set(e,t)}};class _{constructor(e){this._id=e}invokeMethod(e,...t){return f(null,e,this._id,t)}invokeMethodAsync(e,...t){return g(null,e,this._id,t)}dispose(){g(null,"__Dispose",this._id,null).catch((e=>console.error(e)))}serializeAsArg(){return{__dotNetObject:this._id}}}const E="__byte[]";function S(e,t){switch(t){case a.Default:return e;case a.JSObjectReference:return d(e);default:throw new Error(`Invalid JS call result type '${t}'.`)}}u((function(e,t){if(t&&"object"==typeof t){if(t.hasOwnProperty("__dotNetObject"))return new _(t.__dotNetObject);if(t.hasOwnProperty(o)){const e=t.__jsObjectId,n=s[e];if(n)return n.getWrappedObject();throw new Error(`JS object instance with Id '${e}' does not exist. It may have been disposed.`)}if(t.hasOwnProperty(E)){const e=t["__byte[]"],r=n.get(e);if(void 0===r)throw new Error(`Byte array index '${e}' does not exist.`);return r}}return t}));let C=0;function I(e){return C=0,JSON.stringify(e,k)}function k(e,t){if(t instanceof _)return t.serializeAsArg();if(t instanceof Uint8Array){h.sendByteArray(C,t);const e={[E]:C};return C++,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"}(n||(n={}));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}}let o;function i(e,t){if(!o)throw new Error("eventDispatcher not initialized. Call 'setEventDispatcher' to configure it.");o(e,t)}const s=new Map,a=new Map,c={createEventArgs:()=>({})},l=[];function h(e){return s.get(e)}function u(e){const t=s.get(e);return(null==t?void 0:t.browserEventName)||e}function d(e,t){e.forEach((e=>s.set(e,t)))}function p(e){const t=[];for(let n=0;n{return{...f(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}}),d(["focus","blur","focusin","focusout"],c),d(["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};var t}}),d(["contextmenu","click","mouseover","mouseout","mousemove","mousedown","mouseup","dblclick"],{createEventArgs:e=>f(e)}),d(["error"],{createEventArgs:e=>{return{message:(t=e).message,filename:t.filename,lineno:t.lineno,colno:t.colno};var t}}),d(["loadstart","timeout","abort","load","loadend","progress"],{createEventArgs:e=>{return{lengthComputable:(t=e).lengthComputable,loaded:t.loaded,total:t.total};var t}}),d(["touchcancel","touchend","touchmove","touchenter","touchleave","touchstart"],{createEventArgs:e=>{return{detail:(t=e).detail,touches:p(t.touches),targetTouches:p(t.targetTouches),changedTouches:p(t.changedTouches),ctrlKey:t.ctrlKey,shiftKey:t.shiftKey,altKey:t.altKey,metaKey:t.metaKey,type:t.type};var t}}),d(["gotpointercapture","lostpointercapture","pointercancel","pointerdown","pointerenter","pointerleave","pointermove","pointerout","pointerover","pointerup"],{createEventArgs:e=>{return{...f(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}}),d(["wheel","mousewheel"],{createEventArgs:e=>{return{...f(t=e),deltaX:t.deltaX,deltaY:t.deltaY,deltaZ:t.deltaZ,deltaMode:t.deltaMode};var t}}),d(["toggle"],c);const g=["date","datetime-local","month","time","week"],m=E(["abort","blur","change","error","focus","load","loadend","loadstart","mouseenter","mouseleave","progress","reset","scroll","submit","unload","toggle","DOMNodeInsertedIntoDocument","DOMNodeRemovedFromDocument"]),y={submit:!0},w=E(["click","dblclick","mousedown","mousemove","mouseup"]);class v{constructor(e){this.browserRendererId=e,this.afterClickCallbacks=[];const t=++v.nextEventDelegatorId;this.eventsCollectionKey=`_blazorEvents_${t}`,this.eventInfoStore=new b(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,a.get(n));var n;t&&t.forEach((t=>this.dispatchGlobalEventToAllElements(t,e))),"click"===e.type&&this.afterClickCallbacks.forEach((t=>t(e)))}dispatchGlobalEventToAllElements(e,t){let n=t.target,o=null,s=!1;const a=m.hasOwnProperty(e);let c=!1;for(;n;){const d=this.getEventHandlerInfosForElement(n,!1);if(d){const a=d.getHandler(e);if(a&&(l=n,u=t.type,!((l instanceof HTMLButtonElement||l instanceof HTMLInputElement||l instanceof HTMLTextAreaElement||l instanceof HTMLSelectElement)&&w.hasOwnProperty(u)&&l.disabled))){if(!s){const n=h(e);o=(null==n?void 0:n.createEventArgs)?n.createEventArgs(t):{},s=!0}y.hasOwnProperty(t.type)&&t.preventDefault(),i({browserRendererId:this.browserRendererId,eventHandlerId:a.eventHandlerId,eventName:e,eventFieldInfo:r.fromEvent(a.renderingComponentId,t)},o)}d.stopPropagation(e)&&(c=!0),d.preventDefault(e)&&t.preventDefault()}n=a||c?null:n.parentElement}var l,u}getEventHandlerInfosForElement(e,t){return e.hasOwnProperty(this.eventsCollectionKey)?e[this.eventsCollectionKey]:t?e[this.eventsCollectionKey]=new _:null}}v.nextEventDelegatorId=0;class b{constructor(e){this.globalListener=e,this.infosByEventHandlerId={},this.countByEventName={},l.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=u(e),this.countByEventName.hasOwnProperty(e))this.countByEventName[e]++;else{this.countByEventName[e]=1;const t=m.hasOwnProperty(e);document.addEventListener(e,this.globalListener,t)}}update(e,t){if(this.infosByEventHandlerId.hasOwnProperty(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=u(t.eventName);0==--this.countByEventName[n]&&(delete this.countByEventName[n],document.removeEventListener(n,this.globalListener))}return t}handleEventNameAliasAdded(e,t){if(this.countByEventName.hasOwnProperty(e)){const n=this.countByEventName[e];delete this.countByEventName[e],document.removeEventListener(e,this.globalListener),this.addGlobalListener(t),this.countByEventName[t]+=n-1}}}class _{constructor(){this.handlers={},this.preventDefaultFlags=null,this.stopPropagationFlags=null}getHandler(e){return this.handlers.hasOwnProperty(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 E(e){const t={};return e.forEach((e=>{t[e]=!0})),t}const S=H("_blazorLogicalChildren"),C=H("_blazorLogicalParent"),I=H("_blazorLogicalEnd");function k(e,t){if(e.childNodes.length>0&&!t)throw new Error("New logical elements must start empty, or allowExistingContents must be true");return S in e||(e[S]=[]),e}function T(e,t){const n=document.createComment("!");return x(n,e,t),n}function x(e,t,n){const r=e;if(e instanceof Comment&&A(r)&&A(r).length>0)throw new Error("Not implemented: inserting non-empty logical container");if(R(r))throw new Error("Not implemented: moving existing logical children");const o=A(t);if(n0;)D(n,0)}const r=n;r.parentNode.removeChild(r)}function R(e){return e[C]||null}function P(e,t){return A(e)[t]}function U(e){var t=B(e);return"http://www.w3.org/2000/svg"===t.namespaceURI&&"foreignObject"!==t.tagName}function A(e){return e[S]}function N(e,t){const n=A(e);t.forEach((e=>{e.moveRangeStart=n[e.fromSiblingIndex],e.moveRangeEnd=M(e.moveRangeStart)})),t.forEach((t=>{const r=t.moveToBeforeMarker=document.createComment("marker"),o=n[t.toSiblingIndex+1];o?o.parentNode.insertBefore(r,o):L(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 B(e){if(e instanceof Element)return e;if(e instanceof Comment)return e.parentNode;throw new Error("Not a valid logical element")}function $(e){const t=A(R(e));return t[Array.prototype.indexOf.call(t,e)+1]||null}function L(e,t){if(t instanceof Element)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=$(t);n?n.parentNode.insertBefore(e,n):L(e,R(t))}}}function M(e){if(e instanceof Element)return e;const t=$(e);if(t)return t.previousSibling;{const t=R(e);return t instanceof Element?t.lastChild:M(t)}}function H(e){return"function"==typeof Symbol?Symbol():e}function O(e){return`_bl_${e}`}e.attachReviver(((e,t)=>t&&"object"==typeof t&&t.hasOwnProperty("__internalId")&&"string"==typeof t.__internalId?function(e){const t=`[${O(e)}]`;return document.querySelector(t)}(t.__internalId):t));const F="_blazorSelectValue",j=document.createElement("template"),W=document.createElementNS("http://www.w3.org/2000/svg","g"),z={},q="__internal_",J="preventDefault_",K="stopPropagation_";class V{constructor(e){this.childComponentLocations={},this.eventDelegator=new v(e),this.eventDelegator.notifyAfterClick((e=>{if(!ee)return;if(0!==e.button||function(e){return e.ctrlKey||e.shiftKey||e.altKey||e.metaKey}(e))return;if(e.defaultPrevented)return;const t=function(e){const t=!window._blazorDisableComposedPath&&e.composedPath&&e.composedPath();if(t){for(let e=0;ese(!1))))},enableNavigationInterception:function(){ee=!0},navigateTo:oe,getBaseURI:()=>document.baseURI,getLocationHref:()=>location.href};function oe(e,t,n=!1){const r=ce(e);if(!t&&he(r))ie(r,!1,n);else if(t&&location.href===e){const t=e+"?";history.replaceState(null,"",t),location.replace(e)}else n?history.replaceState(null,"",r):location.href=e}function ie(e,t,n=!1){Z=!0,n?history.replaceState(null,"",e):history.pushState(null,"",e),se(t)}async function se(e){ne&&await ne(location.href,e)}let ae;function ce(e){return ae=ae||document.createElement("a"),ae.href=e,ae.href}function le(e,t){return e?e.tagName===t?e:le(e.parentElement,t):null}function he(e){const t=(n=document.baseURI).substr(0,n.lastIndexOf("/")+1);var n;return e.startsWith(t)}const ue={init:function(e,t,n,r=50){const o=pe(t);(o||document.documentElement).style.overflowAnchor="none";const i=new IntersectionObserver((function(r){r.forEach((r=>{var o;if(!r.isIntersecting)return;const i=t.getBoundingClientRect(),s=n.getBoundingClientRect().top-i.bottom,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`});i.observe(t),i.observe(n);const s=c(t),a=c(n);function c(e){const t=new MutationObserver((()=>{i.unobserve(e),i.observe(e)}));return t.observe(e,{attributes:!0}),t}de[e._id]={intersectionObserver:i,mutationObserverBefore:s,mutationObserverAfter:a}},dispose:function(e){const t=de[e._id];t&&(t.intersectionObserver.disconnect(),t.mutationObserverBefore.disconnect(),t.mutationObserverAfter.disconnect(),e.dispose(),delete de[e._id])}},de={};function pe(e){return e?"visible"!==getComputedStyle(e).overflowY?e:pe(e.parentElement):null}const fe={navigateTo:oe,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=a.get(t.browserEventName);n?n.push(e):a.set(t.browserEventName,[e]),l.forEach((n=>n(e,t.browserEventName)))}s.set(e,t)},_internal:{navigationManager:re,domWrapper:{focus:function(e,t){if(!(e instanceof HTMLElement))throw new Error("Unable to focus an invalid element.");e.focus({preventScroll:t})}},Virtualize:ue}};window.Blazor=fe;const ge=[0,2e3,1e4,3e4,null];class me{constructor(e){this._retryDelays=void 0!==e?[...e,null]:ge}nextRetryDelayInMilliseconds(e){return this._retryDelays[e.previousRetryCount]}}class ye extends Error{constructor(e,t){const n=new.target.prototype;super(`${e}: Status code '${t}'`),this.statusCode=t,this.__proto__=n}}class we extends Error{constructor(e="A timeout occurred."){const t=new.target.prototype;super(e),this.__proto__=t}}class ve extends Error{constructor(e="An abort occurred."){const t=new.target.prototype;super(e),this.__proto__=t}}class be{constructor(e,t,n){this.statusCode=e,this.statusText=t,this.content=n}}class _e{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""}}var Ee,Se,Ce,Ie,ke;!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"}(Ee||(Ee={}));class Te extends _e{constructor(e){if(super(),this._logger=e,"undefined"==typeof fetch){const e=require;this._jar=new(e("tough-cookie").CookieJar),this._fetchType=e("node-fetch"),this._fetchType=e("fetch-cookie")(this._fetchType,this._jar),this._abortControllerType=e("abort-controller")}else this._fetchType=fetch.bind(self),this._abortControllerType=AbortController}async send(e){if(e.abortSignal&&e.abortSignal.aborted)throw new ve;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 ve});let r,o=null;if(e.timeout){const r=e.timeout;o=setTimeout((()=>{t.abort(),this._logger.log(Ee.Warning,"Timeout from HTTP request."),n=new we}),r)}try{r=await this._fetchType(e.url,{body:e.content,cache:"no-cache",credentials:!0===e.withCredentials?"include":"same-origin",headers:{"Content-Type":"text/plain;charset=UTF-8","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(Ee.Warning,`Error from HTTP request. ${e}.`),e}finally{o&&clearTimeout(o),e.abortSignal&&(e.abortSignal.onabort=null)}if(!r.ok){const e=await xe(r,"text");throw new ye(e||r.statusText,r.status)}const i=xe(r,e.responseType),s=await i;return new be(r.status,r.statusText,s)}getCookieString(e){return""}}function xe(e,t){let n;switch(t){case"arraybuffer":n=e.arrayBuffer();break;case"text":n=e.text();break;case"blob":case"document":case"json":throw new Error(`${t} is not supported.`);default:n=e.text()}return n}class De extends _e{constructor(e){super(),this._logger=e}send(e){return e.abortSignal&&e.abortSignal.aborted?Promise.reject(new ve):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"),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 ve)}),e.timeout&&(r.timeout=e.timeout),r.onload=()=>{e.abortSignal&&(e.abortSignal.onabort=null),r.status>=200&&r.status<300?t(new be(r.status,r.statusText,r.response||r.responseText)):n(new ye(r.response||r.responseText||r.statusText,r.status))},r.onerror=()=>{this._logger.log(Ee.Warning,`Error from HTTP request. ${r.status}: ${r.statusText}.`),n(new ye(r.statusText,r.status))},r.ontimeout=()=>{this._logger.log(Ee.Warning,"Timeout from HTTP request."),n(new we)},r.send(e.content||"")})):Promise.reject(new Error("No url defined.")):Promise.reject(new Error("No method defined."))}}class Re extends _e{constructor(e){if(super(),"undefined"!=typeof fetch)this._httpClient=new Te(e);else{if("undefined"==typeof XMLHttpRequest)throw new Error("No usable HttpClient found.");this._httpClient=new De(e)}}send(e){return e.abortSignal&&e.abortSignal.aborted?Promise.reject(new ve):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)}}class Pe{}Pe.Authorization="Authorization",Pe.Cookie="Cookie",function(e){e[e.None=0]="None",e[e.WebSockets=1]="WebSockets",e[e.ServerSentEvents=2]="ServerSentEvents",e[e.LongPolling=4]="LongPolling"}(Se||(Se={})),function(e){e[e.Text=1]="Text",e[e.Binary=2]="Binary"}(Ce||(Ce={}));class Ue{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 Ae{constructor(){}log(e,t){}}Ae.instance=new Ae;class Ne{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 Be{static get isBrowser(){return"object"==typeof window}static get isWebWorker(){return"object"==typeof self&&"importScripts"in self}static get isNode(){return!this.isBrowser&&!this.isWebWorker}}function $e(e,t){let n="";return Le(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 Le(e){return e&&"undefined"!=typeof ArrayBuffer&&(e instanceof ArrayBuffer||e.constructor&&"ArrayBuffer"===e.constructor.name)}async function Me(e,t,n,r,o,i,s,a,c){let l={};if(o){const e=await o();e&&(l={Authorization:`Bearer ${e}`})}const[h,u]=Fe();l[h]=u,e.log(Ee.Trace,`(${t} transport) sending data. ${$e(i,s)}.`);const d=Le(i)?"arraybuffer":"text",p=await n.post(r,{content:i,headers:{...l,...c},responseType:d,withCredentials:a});e.log(Ee.Trace,`(${t} transport) request complete. Response status: ${p.statusCode}.`)}class He{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 Oe{constructor(e){this._minLevel=e,this.out=console}log(e,t){if(e>=this._minLevel){const n=`[${(new Date).toISOString()}] ${Ee[e]}: ${t}`;switch(e){case Ee.Critical:case Ee.Error:this.out.error(n);break;case Ee.Warning:this.out.warn(n);break;case Ee.Information:this.out.info(n);break;default:this.out.log(n)}}}}function Fe(){let e="X-SignalR-User-Agent";return Be.isNode&&(e="User-Agent"),[e,je("0.0.0-DEV_BUILD",We(),Be.isNode?"NodeJS":"Browser",ze())]}function je(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 We(){if(!Be.isNode)return"";switch(process.platform){case"win32":return"Windows NT";case"darwin":return"macOS";case"linux":return"Linux";default:return process.platform}}function ze(){if(Be.isNode)return process.versions.node}class qe{constructor(e,t,n,r,o,i){this._httpClient=e,this._accessTokenFactory=t,this._logger=n,this._pollAbort=new Ue,this._logMessageContent=r,this._withCredentials=o,this._headers=i,this._running=!1,this.onreceive=null,this.onclose=null}get pollAborted(){return this._pollAbort.aborted}async connect(e,t){if(Ne.isRequired(e,"url"),Ne.isRequired(t,"transferFormat"),Ne.isIn(t,Ce,"transferFormat"),this._url=e,this._logger.log(Ee.Trace,"(LongPolling transport) Connecting."),t===Ce.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]=Fe(),o={[n]:r,...this._headers},i={abortSignal:this._pollAbort.signal,headers:o,timeout:1e5,withCredentials:this._withCredentials};t===Ce.Binary&&(i.responseType="arraybuffer");const s=await this._getAccessToken();this._updateHeaderToken(i,s);const a=`${e}&_=${Date.now()}`;this._logger.log(Ee.Trace,`(LongPolling transport) polling: ${a}.`);const c=await this._httpClient.get(a,i);200!==c.statusCode?(this._logger.log(Ee.Error,`(LongPolling transport) Unexpected response code: ${c.statusCode}.`),this._closeError=new ye(c.statusText||"",c.statusCode),this._running=!1):this._running=!0,this._receiving=this._poll(this._url,i)}async _getAccessToken(){return this._accessTokenFactory?await this._accessTokenFactory():null}_updateHeaderToken(e,t){e.headers||(e.headers={}),t?e.headers[Pe.Authorization]=`Bearer ${t}`:e.headers[Pe.Authorization]&&delete e.headers[Pe.Authorization]}async _poll(e,t){try{for(;this._running;){const n=await this._getAccessToken();this._updateHeaderToken(t,n);try{const n=`${e}&_=${Date.now()}`;this._logger.log(Ee.Trace,`(LongPolling transport) polling: ${n}.`);const r=await this._httpClient.get(n,t);204===r.statusCode?(this._logger.log(Ee.Information,"(LongPolling transport) Poll terminated by server."),this._running=!1):200!==r.statusCode?(this._logger.log(Ee.Error,`(LongPolling transport) Unexpected response code: ${r.statusCode}.`),this._closeError=new ye(r.statusText||"",r.statusCode),this._running=!1):r.content?(this._logger.log(Ee.Trace,`(LongPolling transport) data received. ${$e(r.content,this._logMessageContent)}.`),this.onreceive&&this.onreceive(r.content)):this._logger.log(Ee.Trace,"(LongPolling transport) Poll timed out, reissuing.")}catch(e){this._running?e instanceof we?this._logger.log(Ee.Trace,"(LongPolling transport) Poll timed out, reissuing."):(this._closeError=e,this._running=!1):this._logger.log(Ee.Trace,`(LongPolling transport) Poll errored after shutdown: ${e.message}`)}}}finally{this._logger.log(Ee.Trace,"(LongPolling transport) Polling complete."),this.pollAborted||this._raiseOnClose()}}async send(e){return this._running?Me(this._logger,"LongPolling",this._httpClient,this._url,this._accessTokenFactory,e,this._logMessageContent,this._withCredentials,this._headers):Promise.reject(new Error("Cannot send until the transport is connected"))}async stop(){this._logger.log(Ee.Trace,"(LongPolling transport) Stopping polling."),this._running=!1,this._pollAbort.abort();try{await this._receiving,this._logger.log(Ee.Trace,`(LongPolling transport) sending DELETE request to ${this._url}.`);const e={},[t,n]=Fe();e[t]=n;const r={headers:{...e,...this._headers},withCredentials:this._withCredentials},o=await this._getAccessToken();this._updateHeaderToken(r,o),await this._httpClient.delete(this._url,r),this._logger.log(Ee.Trace,"(LongPolling transport) DELETE request sent.")}finally{this._logger.log(Ee.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(Ee.Trace,e),this.onclose(this._closeError)}}}class Je{constructor(e,t,n,r,o,i,s){this._httpClient=e,this._accessTokenFactory=t,this._logger=n,this._logMessageContent=r,this._withCredentials=i,this._eventSourceConstructor=o,this._headers=s,this.onreceive=null,this.onclose=null}async connect(e,t){if(Ne.isRequired(e,"url"),Ne.isRequired(t,"transferFormat"),Ne.isIn(t,Ce,"transferFormat"),this._logger.log(Ee.Trace,"(SSE transport) Connecting."),this._url=e,this._accessTokenFactory){const t=await this._accessTokenFactory();t&&(e+=(e.indexOf("?")<0?"?":"&")+`access_token=${encodeURIComponent(t)}`)}return new Promise(((n,r)=>{let o,i=!1;if(t===Ce.Text){if(Be.isBrowser||Be.isWebWorker)o=new this._eventSourceConstructor(e,{withCredentials:this._withCredentials});else{const t=this._httpClient.getCookieString(e),n={};n.Cookie=t;const[r,i]=Fe();n[r]=i,o=new this._eventSourceConstructor(e,{withCredentials:this._withCredentials,headers:{...n,...this._headers}})}try{o.onmessage=e=>{if(this.onreceive)try{this._logger.log(Ee.Trace,`(SSE transport) data received. ${$e(e.data,this._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(Ee.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?Me(this._logger,"SSE",this._httpClient,this._url,this._accessTokenFactory,e,this._logMessageContent,this._withCredentials,this._headers):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 Ke{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){if(Ne.isRequired(e,"url"),Ne.isRequired(t,"transferFormat"),Ne.isIn(t,Ce,"transferFormat"),this._logger.log(Ee.Trace,"(WebSockets transport) Connecting."),this._accessTokenFactory){const t=await this._accessTokenFactory();t&&(e+=(e.indexOf("?")<0?"?":"&")+`access_token=${encodeURIComponent(t)}`)}return new Promise(((n,r)=>{let o;e=e.replace(/^http/,"ws"),this._httpClient.getCookieString(e);let i=!1;o||(o=new this._webSocketConstructor(e)),t===Ce.Binary&&(o.binaryType="arraybuffer"),o.onopen=t=>{this._logger.log(Ee.Information,`WebSocket connected to ${e}.`),this._webSocket=o,i=!0,n()},o.onerror=e=>{let t=null;t="undefined"!=typeof ErrorEvent&&e instanceof ErrorEvent?e.error:"There was an error with the transport",this._logger.log(Ee.Information,`(WebSockets transport) ${t}.`)},o.onmessage=e=>{if(this._logger.log(Ee.Trace,`(WebSockets transport) data received. ${$e(e.data,this._logMessageContent)}.`),this.onreceive)try{this.onreceive(e.data)}catch(e){return void this._close(e)}},o.onclose=e=>{if(i)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(Ee.Trace,`(WebSockets transport) sending data. ${$e(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(Ee.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 Ve{constructor(e,t={}){var n;if(this._stopPromiseResolver=()=>{},this.features={},this._negotiateVersion=1,Ne.isRequired(e,"url"),this._logger=void 0===(n=t.logger)?new Oe(Ee.Information):null===n?Ae.instance:void 0!==n.log?n:new Oe(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,"undefined"==typeof WebSocket||t.WebSocket||(t.WebSocket=WebSocket),"undefined"==typeof EventSource||t.EventSource||(t.EventSource=EventSource),this._httpClient=t.httpClient||new Re(this._logger),this._connectionState="Disconnected",this._connectionStarted=!1,this._options=t,this.onreceive=null,this.onclose=null}async start(e){if(e=e||Ce.Binary,Ne.isIn(e,Ce,"transferFormat"),this._logger.log(Ee.Debug,`Starting connection with transfer format '${Ce[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(Ee.Error,e),await this._stopPromise,Promise.reject(new Error(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(Ee.Error,e),Promise.reject(new Error(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 Xe(this.transport)),this._sendQueue.send(e))}async stop(e){return"Disconnected"===this._connectionState?(this._logger.log(Ee.Debug,`Call to HttpConnection.stop(${e}) ignored because the connection is already in the disconnected state.`),Promise.resolve()):"Disconnecting"===this._connectionState?(this._logger.log(Ee.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(Ee.Error,`HttpConnection.transport.stop() threw error '${e}'.`),this._stopConnection()}this.transport=void 0}else this._logger.log(Ee.Debug,"HttpConnection.transport is undefined in HttpConnection.stop() because start() failed.")}async _startInternal(e){let t=this.baseUrl;this._accessTokenFactory=this._options.accessTokenFactory;try{if(this._options.skipNegotiation){if(this._options.transport!==Se.WebSockets)throw new Error("Negotiation can only be skipped when using the WebSocket transport directly.");this.transport=this._constructTransport(Se.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 Error("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}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 qe&&(this.features.inherentKeepAlive=!0),"Connecting"===this._connectionState&&(this._logger.log(Ee.Debug,"The HttpConnection connected successfully."),this._connectionState="Connected")}catch(e){return this._logger.log(Ee.Error,"Failed to start the connection: "+e),this._connectionState="Disconnected",this.transport=void 0,this._stopPromiseResolver(),Promise.reject(e)}}async _getNegotiationResponse(e){const t={};if(this._accessTokenFactory){const e=await this._accessTokenFactory();e&&(t[Pe.Authorization]=`Bearer ${e}`)}const[n,r]=Fe();t[n]=r;const o=this._resolveNegotiateUrl(e);this._logger.log(Ee.Debug,`Sending negotiation request: ${o}.`);try{const e=await this._httpClient.post(o,{content:"",headers:{...t,...this._options.headers},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 ye&&404===e.statusCode&&(t+=" Either this is not a SignalR endpoint or there is a proxy blocking the connection."),this._logger.log(Ee.Error,t),Promise.reject(new Error(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(Ee.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: ${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(Ee.Error,`Failed to start the transport '${n.transport}': ${e}`),a=void 0,i.push(`${n.transport} failed: ${e}`),"Connecting"!==this._connectionState){const e="Failed to select transport before stop() was called.";return this._logger.log(Ee.Debug,e),Promise.reject(new Error(e))}}}}return i.length>0?Promise.reject(new Error(`Unable to connect to the server with any of the available transports. ${i.join(" ")}`)):Promise.reject(new Error("None of the transports supported by the client are supported by the server."))}_constructTransport(e){switch(e){case Se.WebSockets:if(!this._options.WebSocket)throw new Error("'WebSocket' is not supported in your environment.");return new Ke(this._httpClient,this._accessTokenFactory,this._logger,this._options.logMessageContent||!1,this._options.WebSocket,this._options.headers||{});case Se.ServerSentEvents:if(!this._options.EventSource)throw new Error("'EventSource' is not supported in your environment.");return new Je(this._httpClient,this._accessTokenFactory,this._logger,this._options.logMessageContent||!1,this._options.EventSource,this._options.withCredentials,this._options.headers||{});case Se.LongPolling:return new qe(this._httpClient,this._accessTokenFactory,this._logger,this._options.logMessageContent||!1,this._options.withCredentials,this._options.headers||{});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=Se[e.transport];if(null==r)return this._logger.log(Ee.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(Ee.Debug,`Skipping transport '${Se[r]}' because it was disabled by the client.`),new Error(`'${Se[r]}' is disabled by the client.`);if(!(e.transferFormats.map((e=>Ce[e])).indexOf(n)>=0))return this._logger.log(Ee.Debug,`Skipping transport '${Se[r]}' because it does not support the requested transfer format '${Ce[n]}'.`),new Error(`'${Se[r]}' does not support ${Ce[n]}.`);if(r===Se.WebSockets&&!this._options.WebSocket||r===Se.ServerSentEvents&&!this._options.EventSource)return this._logger.log(Ee.Debug,`Skipping transport '${Se[r]}' because it is not supported in your environment.'`),new Error(`'${Se[r]}' is not supported in your environment.`);this._logger.log(Ee.Debug,`Selecting transport '${Se[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(Ee.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(Ee.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(Ee.Error,`Connection disconnected with error '${e}'.`):this._logger.log(Ee.Information,"Connection disconnected."),this._sendQueue&&(this._sendQueue.stop().catch((e=>{this._logger.log(Ee.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(Ee.Error,`HttpConnection.onclose(${e}) threw error '${t}'.`)}}}else this._logger.log(Ee.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(!Be.isBrowser||!window.document)throw new Error(`Cannot resolve '${e}'.`);const t=window.document.createElement("a");return t.href=e,this._logger.log(Ee.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 Xe{constructor(e){this._transport=e,this._buffer=[],this._executing=!0,this._sendBufferedData=new Ye,this._transportResult=new Ye,this._sendLoopPromise=this._sendLoop()}send(e){return this._bufferData(e),this._transportResult||(this._transportResult=new Ye),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 Ye;const e=this._transportResult;this._transportResult=void 0;const t="string"==typeof this._buffer[0]?this._buffer.join(""):Xe._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 Ye{constructor(){this.promise=new Promise(((e,t)=>[this._resolver,this._rejecter]=[e,t]))}resolve(){this._resolver()}reject(e){this._rejecter(e)}}class Ge{static write(e){return`${e}${Ge.RecordSeparator}`}static parse(e){if(e[e.length-1]!==Ge.RecordSeparator)throw new Error("Message is incomplete.");const t=e.split(Ge.RecordSeparator);return t.pop(),t}}Ge.RecordSeparatorCode=30,Ge.RecordSeparator=String.fromCharCode(Ge.RecordSeparatorCode);class Qe{writeHandshakeRequest(e){return Ge.write(JSON.stringify(e))}parseHandshakeResponse(e){let t,n;if(Le(e)){const r=new Uint8Array(e),o=r.indexOf(Ge.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(Ge.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=Ge.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"}(Ie||(Ie={}));class Ze{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 He(this,e)}}!function(e){e.Disconnected="Disconnected",e.Connecting="Connecting",e.Connected="Connected",e.Disconnecting="Disconnecting",e.Reconnecting="Reconnecting"}(ke||(ke={}));class et{constructor(e,t,n,r){this._nextKeepAlive=0,Ne.isRequired(e,"connection"),Ne.isRequired(t,"logger"),Ne.isRequired(n,"protocol"),this.serverTimeoutInMilliseconds=3e4,this.keepAliveIntervalInMilliseconds=15e3,this._logger=t,this._protocol=n,this.connection=e,this._reconnectPolicy=r,this._handshakeProtocol=new Qe,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=ke.Disconnected,this._connectionStarted=!1,this._cachedPingMessage=this._protocol.writeMessage({type:Ie.Ping})}static create(e,t,n,r){return new et(e,t,n,r)}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!==ke.Disconnected&&this._connectionState!==ke.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!==ke.Disconnected)return Promise.reject(new Error("Cannot start a HubConnection that is not in the 'Disconnected' state."));this._connectionState=ke.Connecting,this._logger.log(Ee.Debug,"Starting HubConnection.");try{await this._startInternal(),this._connectionState=ke.Connected,this._connectionStarted=!0,this._logger.log(Ee.Debug,"HubConnection connected successfully.")}catch(e){return this._connectionState=ke.Disconnected,this._logger.log(Ee.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(Ee.Debug,"Sending handshake request."),await this._sendMessage(this._handshakeProtocol.writeHandshakeRequest(t)),this._logger.log(Ee.Information,`Using HubProtocol '${this._protocol.name}'.`),this._cleanupTimeout(),this._resetTimeoutPeriod(),this._resetKeepAliveInterval(),await e,this._stopDuringStartError)throw this._stopDuringStartError}catch(e){throw this._logger.log(Ee.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){return this._connectionState===ke.Disconnected?(this._logger.log(Ee.Debug,`Call to HubConnection.stop(${e}) ignored because it is already in the disconnected state.`),Promise.resolve()):this._connectionState===ke.Disconnecting?(this._logger.log(Ee.Debug,`Call to HttpConnection.stop(${e}) ignored because the connection is already in the disconnecting state.`),this._stopPromise):(this._connectionState=ke.Disconnecting,this._logger.log(Ee.Debug,"Stopping HubConnection."),this._reconnectDelayHandle?(this._logger.log(Ee.Debug,"Connection stopped during reconnect delay. Done reconnecting."),clearTimeout(this._reconnectDelayHandle),this._reconnectDelayHandle=void 0,this._completeClose(),Promise.resolve()):(this._cleanupTimeout(),this._cleanupPingTimer(),this._stopDuringStartError=e||new Error("The connection was stopped before the hub handshake could complete."),this.connection.stop(e)))}stream(e,...t){const[n,r]=this._replaceStreamingParams(t),o=this._createStreamInvocation(e,t,r);let i;const s=new Ze;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===Ie.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===Ie.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 Ie.Invocation:this._invokeClientMethod(e);break;case Ie.StreamItem:case Ie.Completion:{const t=this._callbacks[e.invocationId];t&&(e.type===Ie.Completion&&delete this._callbacks[e.invocationId],t(e));break}case Ie.Ping:break;case Ie.Close:{this._logger.log(Ee.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(Ee.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(Ee.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(Ee.Error,e);const n=new Error(e);throw this._handshakeRejecter(n),n}return this._logger.log(Ee.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===ke.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."))}_invokeClientMethod(e){const t=this._methods[e.target.toLowerCase()];if(t){try{t.forEach((t=>t.apply(this,e.arguments)))}catch(t){this._logger.log(Ee.Error,`A callback for the method ${e.target.toLowerCase()} threw error '${t}'.`)}if(e.invocationId){const e="Server requested a response, which is not supported in this version of the client.";this._logger.log(Ee.Error,e),this._stopPromise=this._stopInternal(new Error(e))}}else this._logger.log(Ee.Warning,`No client method with the name '${e.target}' found.`)}_connectionClosed(e){this._logger.log(Ee.Debug,`HubConnection.connectionClosed(${e}) called while in state ${this._connectionState}.`),this._stopDuringStartError=this._stopDuringStartError||e||new Error("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===ke.Disconnecting?this._completeClose(e):this._connectionState===ke.Connected&&this._reconnectPolicy?this._reconnect(e):this._connectionState===ke.Connected&&this._completeClose(e)}_completeClose(e){if(this._connectionStarted){this._connectionState=ke.Disconnected,this._connectionStarted=!1;try{this._closedCallbacks.forEach((t=>t.apply(this,[e])))}catch(t){this._logger.log(Ee.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(Ee.Debug,"Connection not reconnecting because the IRetryPolicy returned null on the first reconnect attempt."),void this._completeClose(e);if(this._connectionState=ke.Reconnecting,e?this._logger.log(Ee.Information,`Connection reconnecting because of error '${e}'.`):this._logger.log(Ee.Information,"Connection reconnecting."),0!==this._reconnectingCallbacks.length){try{this._reconnectingCallbacks.forEach((t=>t.apply(this,[e])))}catch(t){this._logger.log(Ee.Error,`An onreconnecting callback called with error '${e}' threw error '${t}'.`)}if(this._connectionState!==ke.Reconnecting)return void this._logger.log(Ee.Debug,"Connection left the reconnecting state in onreconnecting callback. Done reconnecting.")}for(;null!==o;){if(this._logger.log(Ee.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!==ke.Reconnecting)return void this._logger.log(Ee.Debug,"Connection left the reconnecting state during reconnect delay. Done reconnecting.");try{if(await this._startInternal(),this._connectionState=ke.Connected,this._logger.log(Ee.Information,"HubConnection reconnected successfully."),0!==this._reconnectedCallbacks.length)try{this._reconnectedCallbacks.forEach((e=>e.apply(this,[this.connection.connectionId])))}catch(e){this._logger.log(Ee.Error,`An onreconnected callback called with connectionId '${this.connection.connectionId}; threw error '${e}'.`)}return}catch(e){if(this._logger.log(Ee.Information,`Reconnect attempt failed because of error '${e}'.`),this._connectionState!==ke.Reconnecting)return this._logger.log(Ee.Debug,`Connection moved to the '${this._connectionState}' from the reconnecting state during reconnect attempt. Done reconnecting.`),void(this._connectionState===ke.Disconnecting&&this._completeClose());r=e instanceof Error?e:new Error(e.toString()),o=this._getNextRetryDelay(n++,Date.now()-t,r)}}this._logger.log(Ee.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(Ee.Error,`IRetryPolicy.nextRetryDelayInMilliseconds(${e}, ${t}) threw error '${n}'.`),null}}_cancelCallbacksWithError(e){const t=this._callbacks;this._callbacks={},Object.keys(t).forEach((n=>{(0,t[n])(null,e)}))}_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:Ie.Invocation}:{arguments:t,target:e,type:Ie.Invocation};{const n=this._invocationId;return this._invocationId++,0!==r.length?{arguments:t,invocationId:n.toString(),streamIds:r,target:e,type:Ie.Invocation}:{arguments:t,invocationId:n.toString(),target:e,type:Ie.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 ut=ot?new TextDecoder:null,dt=ot?"undefined"!=typeof process&&"force"!==process.env.TEXT_DECODER?200:0:it,pt=function(e,t){this.type=e,this.data=t};function ft(e,t,n){var r=Math.floor(n/4294967296),o=n;e.setUint32(t,r),e.setUint32(t+4,o)}function gt(e,t){return 4294967296*e.getInt32(t)+e.getUint32(t+4)}var mt={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),ft(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:gt(t,4),nsec:t.getUint32(0)};default:throw new Error("Unrecognized data size for timestamp: "+e.length)}}(e);return new Date(1e3*t.sec+t.nsec/1e6)}},yt=function(){function e(){this.builtInEncoders=[],this.builtInDecoders=[],this.encoders=[],this.decoders=[],this.register(mt)}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 "+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: "+e+" bytes in UTF-8");this.writeU8(219),this.writeU32(e)}},e.prototype.encodeString=function(e){if(e.length>ct){var t=st(e);this.ensureBufferSizeToWrite(5+t),this.writeStringHeader(t),lt(e,this.bytes,this.pos),this.pos+=t}else t=st(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: "+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: "+t);this.writeU8(198),this.writeU32(t)}var n=wt(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: "+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=ht(e,t,n),i=Uint8Array.prototype.slice.call(e,t,t+n);return this.store(i,o),o},e}(),St=(_t=function(e,t){return(_t=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])})(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}_t(e,t),e.prototype=null===t?Object.create(t):(n.prototype=t.prototype,new n)}),Ct=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]1||a(e,t)}))})}function a(e,t){try{(n=o[e](t)).value instanceof kt?Promise.resolve(n.value.v).then(c,l):h(i[0][2],n)}catch(e){h(i[0][3],e)}var n}function c(e){a("next",e)}function l(e){a("throw",e)}function h(e,t){e(t),i.shift(),i.length&&a(i[0][0],i[0][1])}},xt=new DataView(new ArrayBuffer(0)),Dt=new Uint8Array(xt.buffer),Rt=function(){try{xt.getInt8(0)}catch(e){return e.constructor}throw new Error("never reached")}(),Pt=new Rt("Insufficient data"),Ut=4294967295,At=new Et,Nt=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 St(t,e),t}(Error),Bt=function(){function e(e,t,n,r,o,i,s,a){void 0===e&&(e=yt.defaultCodec),void 0===t&&(t=void 0),void 0===n&&(n=Ut),void 0===r&&(r=Ut),void 0===o&&(o=Ut),void 0===i&&(i=Ut),void 0===s&&(s=Ut),void 0===a&&(a=At),this.extensionCodec=e,this.context=t,this.maxStrLength=n,this.maxBinLength=r,this.maxArrayLength=o,this.maxMapLength=i,this.maxExtLength=s,this.keyDecoder=a,this.totalPos=0,this.pos=0,this.view=xt,this.bytes=Dt,this.headByte=-1,this.stack=[]}return e.prototype.reinitializeState=function(){this.totalPos=0,this.headByte=-1,this.stack.length=0},e.prototype.setBuffer=function(e){this.bytes=wt(e),this.view=function(e){if(e instanceof ArrayBuffer)return new DataView(e);var t=wt(e);return new DataView(t.buffer,t.byteOffset,t.byteLength)}(this.bytes),this.pos=0},e.prototype.appendBuffer=function(e){if(-1!==this.headByte||this.hasRemaining()){var t=this.bytes.subarray(this.pos),n=wt(e),r=new Uint8Array(t.length+n.length);r.set(t),r.set(n,t.length),this.setBuffer(r)}else this.setBuffer(e)},e.prototype.hasRemaining=function(e){return void 0===e&&(e=1),this.view.byteLength-this.pos>=e},e.prototype.createExtraByteError=function(e){var t=this.view,n=this.pos;return new RangeError("Extra "+(t.byteLength-n)+" of "+t.byteLength+" byte(s) found at buffer["+e+"]")},e.prototype.decode=function(e){this.reinitializeState(),this.setBuffer(e);var t=this.doDecodeSync();if(this.hasRemaining())throw this.createExtraByteError(this.pos);return t},e.prototype.decodeMulti=function(e){return Ct(this,(function(t){switch(t.label){case 0:this.reinitializeState(),this.setBuffer(e),t.label=1;case 1:return this.hasRemaining()?[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,u,d;return Ct(this,(function(p){switch(p.label){case 0:i=!1,p.label=1;case 1:p.trys.push([1,6,7,12]),t=It(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 Rt))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())throw this.createExtraByteError(this.totalPos);return[2,s]}throw h=(l=this).headByte,u=l.pos,d=l.totalPos,new RangeError("Insufficient data in parsing "+bt(h)+" at "+d+" ("+u+" 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 Tt(this,arguments,(function(){var n,r,o,i,s,a,c,l,h;return Ct(this,(function(u){switch(u.label){case 0:n=t,r=-1,u.label=1;case 1:u.trys.push([1,13,14,19]),o=It(e),u.label=2;case 2:return[4,kt(o.next())];case 3:if((i=u.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()),u.label=4;case 4:u.trys.push([4,9,,10]),u.label=5;case 5:return[4,kt(this.doDecodeSync())];case 6:return[4,u.sent()];case 7:return u.sent(),0==--r?[3,8]:[3,5];case 8:return[3,10];case 9:if(!((a=u.sent())instanceof Rt))throw a;return[3,10];case 10:this.totalPos+=this.pos,u.label=11;case 11:return[3,2];case 12:return[3,19];case 13:return c=u.sent(),l={error:c},[3,19];case 14:return u.trys.push([14,,17,18]),i&&!i.done&&(h=o.return)?[4,kt(h.call(o))]:[3,16];case 15:u.sent(),u.label=16;case 16:return[3,18];case 17:if(l)throw l.error;return[7];case 18:return[7];case 19:return[2]}}))}))},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 Nt("Unrecognized type byte: "+bt(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 Nt("The type of key must be string or number but "+typeof t);if("__proto__"===t)throw new Nt("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 Nt("Unrecognized array type byte: "+bt(e))}},e.prototype.pushMapState=function(e){if(e>this.maxMapLength)throw new Nt("Max length exceeded: map length ("+e+") > maxMapLengthLength ("+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 Nt("Max length exceeded: array length ("+e+") > maxArrayLength ("+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 Nt("Max length exceeded: UTF-8 byte length ("+e+") > maxStrLength ("+this.maxStrLength+")");if(this.bytes.byteLengthdt?function(e,t,n){var r=e.subarray(t,t+n);return ut.decode(r)}(this.bytes,o,e):ht(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 Nt("Max length exceeded: bin length ("+e+") > maxBinLength ("+this.maxBinLength+")");if(!this.hasRemaining(e+t))throw Pt;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 Nt("Max length exceeded: ext length ("+e+") > maxExtLength ("+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=gt(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 $t{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 Lt=new Uint8Array([145,Ie.Ping]);class Mt{constructor(e){this.name="messagepack",this.version=1,this.transferFormat=Ce.Binary,this._errorResult=1,this._voidResult=2,this._nonVoidResult=3,e=e||{},this._encoder=new vt(e.extensionCodec,e.context,e.maxDepth,e.initialBufferSize,e.sortKeys,e.forceFloat32,e.ignoreUndefined,e.forceIntegerToFloat),this._decoder=new Bt(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=Ae.instance);const r=$t.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 Ie.Invocation:return this._writeInvocation(e);case Ie.StreamInvocation:return this._writeStreamInvocation(e);case Ie.StreamItem:return this._writeStreamItem(e);case Ie.Completion:return this._writeCompletion(e);case Ie.Ping:return $t.write(Lt);case Ie.CancelInvocation:return this._writeCancelInvocation(e);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 Ie.Invocation:return this._createInvocationMessage(this._readHeaders(n),n);case Ie.StreamItem:return this._createStreamItemMessage(this._readHeaders(n),n);case Ie.Completion:return this._createCompletionMessage(this._readHeaders(n),n);case Ie.Ping:return this._createPingMessage(n);case Ie.Close:return this._createCloseMessage(n);default:return t.log(Ee.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:Ie.Close}}_createPingMessage(e){if(e.length<1)throw new Error("Invalid payload for Ping message.");return{type:Ie.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:Ie.Invocation}:{arguments:t[4],headers:e,streamIds:[],target:t[3],type:Ie.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:Ie.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:Ie.Completion}}_writeInvocation(e){let t;return t=e.streamIds?this._encoder.encode([Ie.Invocation,e.headers||{},e.invocationId||null,e.target,e.arguments,e.streamIds]):this._encoder.encode([Ie.Invocation,e.headers||{},e.invocationId||null,e.target,e.arguments]),$t.write(t.slice())}_writeStreamInvocation(e){let t;return t=e.streamIds?this._encoder.encode([Ie.StreamInvocation,e.headers||{},e.invocationId,e.target,e.arguments,e.streamIds]):this._encoder.encode([Ie.StreamInvocation,e.headers||{},e.invocationId,e.target,e.arguments]),$t.write(t.slice())}_writeStreamItem(e){const t=this._encoder.encode([Ie.StreamItem,e.headers||{},e.invocationId,e.item]);return $t.write(t.slice())}_writeCompletion(e){const t=e.error?this._errorResult:e.result?this._nonVoidResult:this._voidResult;let n;switch(t){case this._errorResult:n=this._encoder.encode([Ie.Completion,e.headers||{},e.invocationId,t,e.error]);break;case this._voidResult:n=this._encoder.encode([Ie.Completion,e.headers||{},e.invocationId,t]);break;case this._nonVoidResult:n=this._encoder.encode([Ie.Completion,e.headers||{},e.invocationId,t,e.result])}return $t.write(n.slice())}_writeCancelInvocation(e){const t=this._encoder.encode([Ie.CancelInvocation,e.headers||{},e.invocationId]);return $t.write(t.slice())}_readHeaders(e){const t=e[1];if("object"!=typeof t)throw new Error("Invalid headers.");return t}}let Ht=!1;const Ot="function"==typeof TextDecoder?new TextDecoder("utf-8"):null,Ft=Ot?Ot.decode.bind(Ot):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("")},jt=Math.pow(2,32),Wt=Math.pow(2,21)-1;function zt(e,t){return e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24}function qt(e,t){return e[t]+(e[t+1]<<8)+(e[t+2]<<16)+(e[t+3]<<24>>>0)}function Jt(e,t){const n=qt(e,t+4);if(n>Wt)throw new Error(`Cannot read uint64 with high order part ${n}, because the result would exceed Number.MAX_SAFE_INTEGER.`);return n*jt+qt(e,t)}class Kt{constructor(e){this.batchData=e;const t=new Gt(e);this.arrayRangeReader=new Qt(e),this.arrayBuilderSegmentReader=new Zt(e),this.diffReader=new Vt(e),this.editReader=new Xt(e,t),this.frameReader=new Yt(e,t)}updatedComponents(){return zt(this.batchData,this.batchData.length-20)}referenceFrames(){return zt(this.batchData,this.batchData.length-16)}disposedComponentIds(){return zt(this.batchData,this.batchData.length-12)}disposedEventHandlerIds(){return zt(this.batchData,this.batchData.length-8)}updatedComponentsEntry(e,t){const n=e+4*t;return zt(this.batchData,n)}referenceFramesEntry(e,t){return e+20*t}disposedComponentIdsEntry(e,t){const n=e+4*t;return zt(this.batchData,n)}disposedEventHandlerIdsEntry(e,t){const n=e+8*t;return Jt(this.batchData,n)}}class Vt{constructor(e){this.batchDataUint8=e}componentId(e){return zt(this.batchDataUint8,e)}edits(e){return e+4}editsEntry(e,t){return e+16*t}}class Xt{constructor(e,t){this.batchDataUint8=e,this.stringReader=t}editType(e){return zt(this.batchDataUint8,e)}siblingIndex(e){return zt(this.batchDataUint8,e+4)}newTreeIndex(e){return zt(this.batchDataUint8,e+8)}moveToSiblingIndex(e){return zt(this.batchDataUint8,e+8)}removedAttributeName(e){const t=zt(this.batchDataUint8,e+12);return this.stringReader.readString(t)}}class Yt{constructor(e,t){this.batchDataUint8=e,this.stringReader=t}frameType(e){return zt(this.batchDataUint8,e)}subtreeLength(e){return zt(this.batchDataUint8,e+4)}elementReferenceCaptureId(e){const t=zt(this.batchDataUint8,e+4);return this.stringReader.readString(t)}componentId(e){return zt(this.batchDataUint8,e+8)}elementName(e){const t=zt(this.batchDataUint8,e+8);return this.stringReader.readString(t)}textContent(e){const t=zt(this.batchDataUint8,e+4);return this.stringReader.readString(t)}markupContent(e){const t=zt(this.batchDataUint8,e+4);return this.stringReader.readString(t)}attributeName(e){const t=zt(this.batchDataUint8,e+4);return this.stringReader.readString(t)}attributeValue(e){const t=zt(this.batchDataUint8,e+8);return this.stringReader.readString(t)}attributeEventHandlerId(e){return Jt(this.batchDataUint8,e+12)}}class Gt{constructor(e){this.batchDataUint8=e,this.stringTableStartIndex=zt(e,e.length-4)}readString(e){if(-1===e)return null;{const n=zt(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(en.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(en.Debug,`Waiting for batch ${this.nextBatchId}. Batch ${e} not processed.`);try{this.nextBatchId++,this.logger.log(en.Debug,`Applying batch ${e}.`),function(e,t){const n=Q[e];if(!n)throw new Error(`There is no browser renderer with ID ${e}.`);const r=t.arrayRangeReader,o=t.updatedComponents(),i=r.values(o),s=r.count(o),a=t.referenceFrames(),c=r.values(a),l=t.diffReader;for(let e=0;e=this.minLevel){const n=`[${(new Date).toISOString()}] ${en[e]}: ${t}`;switch(e){case en.Critical:case en.Error:console.error(n);break;case en.Warning:console.warn(n);break;case en.Information:console.info(n);break;default:console.log(n)}}}}class on{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!==ke.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!==ke.Connected)return!1;const t=await e.invoke("StartCircuit",re.getBaseURI(),re.getLocationHref(),JSON.stringify(this.components.map((e=>e.toRecord()))),this.applicationState||"");return!!t&&(this.initialize(t),!0)}resolveElement(e){const t=Number.parseInt(e);if(Number.isNaN(t))throw new Error(`Invalid sequence number '${e}'.`);return function(e,t){if(!e.parentNode)throw new Error(`Comment not connected to the DOM ${e.textContent}`);const n=e.parentNode,r=k(n,!0),o=A(r);return Array.from(n.childNodes).forEach((e=>o.push(e))),e[C]=r,t&&(e[I]=t,k(t)),k(e)}(this.components[t].start,this.components[t].end)}}const sn={configureSignalR:e=>{},logLevel:en.Warning,reconnectionOptions:{maxRetries:8,retryIntervalMilliseconds:2e4,dialogId:"components-reconnect-modal"}};class an{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.modal.innerHTML='

Alternatively, reload

',this.message=this.modal.querySelector("h5"),this.button=this.modal.querySelector("button"),this.reloadParagraph=this.modal.querySelector("p"),this.loader=this.getLoader(),this.message.after(this.loader),this.button.addEventListener("click",(async()=>{this.show();try{await(null==fe?void 0:fe.reconnect)()||this.rejected()}catch(e){this.logger.log(en.Error,e),this.failed()}})),this.reloadParagraph.querySelector("a").addEventListener("click",(()=>location.reload()))}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",this.message.innerHTML="Reconnection failed. Try reloading the page if you're unable to reconnect.",this.message.querySelector("a").addEventListener("click",(()=>location.reload()))}rejected(){this.button.style.display="none",this.reloadParagraph.style.display="none",this.loader.style.display="none",this.message.innerHTML="Could not reconnect to the server. Reload the page to restore functionality.",this.message.querySelector("a").addEventListener("click",(()=>location.reload()))}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 cn{constructor(e,t,n){this.dialog=e,this.maxRetries=t,this.document=n,this.document=n;const r=this.document.getElementById(cn.MaxRetriesId);r&&(r.innerText=this.maxRetries.toString())}show(){this.removeClasses(),this.dialog.classList.add(cn.ShowClassName)}update(e){const t=this.document.getElementById(cn.CurrentAttemptId);t&&(t.innerText=e.toString())}hide(){this.removeClasses(),this.dialog.classList.add(cn.HideClassName)}failed(){this.removeClasses(),this.dialog.classList.add(cn.FailedClassName)}rejected(){this.removeClasses(),this.dialog.classList.add(cn.RejectedClassName)}removeClasses(){this.dialog.classList.remove(cn.ShowClassName,cn.HideClassName,cn.FailedClassName,cn.RejectedClassName)}}cn.ShowClassName="components-reconnect-show",cn.HideClassName="components-reconnect-hide",cn.FailedClassName="components-reconnect-failed",cn.RejectedClassName="components-reconnect-rejected",cn.MaxRetriesId="components-reconnect-max-retries",cn.CurrentAttemptId="components-reconnect-current-attempt";class ln{constructor(e,t,n){this._currentReconnectionProcess=null,this._logger=e,this._reconnectionDisplay=t,this._reconnectCallback=n||(()=>fe.reconnect())}onConnectionDown(e,t){if(!this._reconnectionDisplay){const t=document.getElementById(e.dialogId);this._reconnectionDisplay=t?new cn(t,e.maxRetries,document):new an(e.dialogId,e.maxRetries,document,this._logger)}this._currentReconnectionProcess||(this._currentReconnectionProcess=new hn(e,this._logger,this._reconnectCallback,this._reconnectionDisplay))}onConnectionUp(){this._currentReconnectionProcess&&(this._currentReconnectionProcess.dispose(),this._currentReconnectionProcess=null)}}class hn{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;thn.MaximumFirstRetryInterval?hn.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(en.Error,e)}}this.reconnectDisplay.failed()}delay(e){return new Promise((t=>setTimeout(t,e)))}}hn.MaximumFirstRetryInterval=3e3;const un=/^\s*Blazor-Component-State:(?[a-zA-Z0-9\+\/=]+)$/;function dn(e){var t;if(e.nodeType===Node.COMMENT_NODE){const n=e.textContent||"",r=un.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 gn(e,t){const n=e.currentElement;if(n&&n.nodeType===Node.COMMENT_NODE&&n.textContent){const r=fn.exec(n.textContent),o=r&&r.groups&&r.groups.descriptor;if(!o)return;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;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.");if(c){const e=mn(c,n);if(!e)throw new Error(`Could not find an end component comment for '${t}'`);return{type:r,assembly:o,typeName:i,parameterDefinitions:s&&atob(s),parameterValues:a&&atob(a),start:t,prerenderId:c,end:e}}return{type:r,assembly:o,typeName:i,parameterDefinitions:s&&atob(s),parameterValues:a&&atob(a),start:t}}}(r,n,e);case"server":return function(e,t,n){const{type:r,descriptor:o,sequence:i,prerenderId:s}=e;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)}'`);if(s){const e=mn(s,n);if(!e)throw new Error(`Could not find an end component comment for '${t}'`);return{type:r,sequence:i,descriptor:o,start:t,prerenderId:s,end:e}}return{type:r,sequence:i,descriptor:o,start:t}}}(r,n,e)}}catch(e){throw new Error(`Found malformed component comment at ${n.textContent}`)}}}function mn(e,t){for(;t.next()&&t.currentElement;){const n=t.currentElement;if(n.nodeType!==Node.COMMENT_NODE)continue;if(!n.textContent)continue;const r=fn.exec(n.textContent),o=r&&r[1];if(o)return yn(o,e),n}}function yn(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 wn{constructor(e){this.childNodes=e,this.currentIndex=-1,this.length=e.length}next(){return this.currentIndex++,this.currentIndexe.sequence-t.sequence))}(e)}(document),o=dn(document),i=new on(r,o||""),s=await Tn(t,n,i);if(!await i.startCircuit(s))return void n.log(en.Error,"Failed to start the circuit.");let a=!1;const c=()=>{if(!a){const e=new FormData,t=i.circuitId;e.append("circuitId",t),a=navigator.sendBeacon("_blazor/disconnect",e)}};fe.disconnect=c,window.addEventListener("unload",c,{capture:!1,once:!0}),fe.reconnect=async e=>{if(Cn)return!1;const r=e||await Tn(t,n,i);return await i.reconnect(r)?(t.reconnectionHandler.onConnectionUp(),!0):(n.log(en.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)},n.log(en.Information,"Blazor server-side application started.")}async function Tn(t,n,r){const i=new Mt;i.name="blazorpack";const s=(new rt).withUrl("_blazor").withHubProtocol(i);t.configureSignalR(s);const a=s.build();o=(e,t)=>{a.send("DispatchBrowserEvent",JSON.stringify(e),JSON.stringify(t))},fe._internal.navigationManager.listenForNavigationEvents(((e,t)=>a.send("OnLocationChanged",e,t))),a.on("JS.AttachComponent",((e,t)=>function(e,t,n){let r=Q[0];r||(r=Q[0]=new V(0)),r.attachRootComponentToLogicalElement(n,t)}(0,r.resolveElement(t),e))),a.on("JS.BeginInvokeJS",e.jsCallDispatcher.beginInvokeJSFromDotNet),a.on("JS.EndInvokeDotNet",e.jsCallDispatcher.endInvokeDotNetFromJS),a.on("JS.ReceiveByteArray",e.jsCallDispatcher.receiveByteArray);const c=tn.getOrCreate(n);a.on("JS.RenderBatch",((e,t)=>{n.log(en.Debug,`Received render batch with id ${e} and ${t.byteLength} bytes.`),c.processBatch(e,t,a)})),a.onclose((e=>!Cn&&t.reconnectionHandler.onConnectionDown(t.reconnectionOptions,e))),a.on("JS.Error",(e=>{Cn=!0,xn(a,e,n),async function(){let e=document.querySelector("#blazor-error-ui");e&&(e.style.display="block"),Ht||(Ht=!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()}})))}()})),fe._internal.forceCloseConnection=()=>a.stop(),fe._internal.sendJSDataStream=async(e,t,n)=>{setTimeout((async()=>{let r=5,o=(new Date).valueOf();try{const i=n-512;if(i<=0)throw new Error("The chunk size must be greater than 0.");let s=0;for(;s1)await a.send("SupplyJSDataChunk",t,c,null);else{if(!await a.invoke("SupplyJSDataChunk",t,c,null))break;const e=(new Date).valueOf(),n=e-o;o=e,r=Math.max(1,Math.round(500/n))}s+=n}}catch(e){await a.send("SupplyJSDataChunk",t,null,e.toString())}}),0)};try{await a.start()}catch(e){xn(a,e,n)}return e.attachDispatcher({beginInvokeDotNetFromJS:(e,t,n,r,o)=>{a.send("BeginInvokeDotNetFromJS",e?e.toString():null,t,n,r||0,o)},endInvokeJSFromDotNet:(e,t,n)=>{a.send("EndInvokeJSFromDotNet",e,t,n)},sendByteArray:(e,t)=>{a.send("ReceiveByteArray",e,t)}}),a}function xn(e,t,n){n.log(en.Error,t),e&&e.stop()}fe.start=kn,document&&document.currentScript&&"false"!==document.currentScript.getAttribute("autostart")&&kn()})(); \ No newline at end of file From c97360c4a5b4c07cc2083d75ed543f49919cf564 Mon Sep 17 00:00:00 2001 From: Tanay Parikh Date: Mon, 14 Jun 2021 11:18:47 -0700 Subject: [PATCH 10/37] PR Feedback --- .../BlazorPack/BlazorPackHubProtocolWorker.cs | 7 ------- .../Server/src/Circuits/CircuitHost.cs | 18 ++++++++--------- .../Server/src/Circuits/RemoteJSDataStream.cs | 20 ++++--------------- src/Components/Server/src/ComponentHub.cs | 4 ++-- src/Components/Web.JS/src/Boot.Server.ts | 6 +++--- .../src/IJSDataReference.cs | 4 ++-- 6 files changed, 20 insertions(+), 39 deletions(-) diff --git a/src/Components/Server/src/BlazorPack/BlazorPackHubProtocolWorker.cs b/src/Components/Server/src/BlazorPack/BlazorPackHubProtocolWorker.cs index d2d907c5bd85..10c9ccd8acd1 100644 --- a/src/Components/Server/src/BlazorPack/BlazorPackHubProtocolWorker.cs +++ b/src/Components/Server/src/BlazorPack/BlazorPackHubProtocolWorker.cs @@ -35,13 +35,6 @@ protected override object DeserializeObject(ref MessagePackReader reader, Type t { return reader.ReadSingle(); } - else if (type == typeof(ReadOnlySequence)) - { - // This is how I think it should work, but sometimes the memory seems to get corrupted. - // The "await foreach (var chunk in subject)" code in RemoteJSDataStream sometimes gets - // chunks with negative lengths. So, this is not actually used in this proof-of-concept - return reader.ReadBytes() ?? null; - } else if (type == typeof(byte[])) { var bytes = reader.ReadBytes(); diff --git a/src/Components/Server/src/Circuits/CircuitHost.cs b/src/Components/Server/src/Circuits/CircuitHost.cs index 31cebbf973e3..be0d4d030992 100644 --- a/src/Components/Server/src/Circuits/CircuitHost.cs +++ b/src/Components/Server/src/Circuits/CircuitHost.cs @@ -416,9 +416,9 @@ await Renderer.Dispatcher.InvokeAsync(() => } } - // SupplyJSDataChunk is used in a fire-and-forget context, so it's responsible for its own + // ReceiveJSDataChunk is used in a fire-and-forget context, so it's responsible for its own // error handling. - internal async Task SupplyJSDataChunk(string streamId, ReadOnlySequence chunk, string error) + internal async Task ReceiveJSDataChunk(string streamId, ReadOnlySequence chunk, string error) { AssertInitialized(); AssertNotDisposed(); @@ -431,7 +431,7 @@ internal async Task SupplyJSDataChunk(string streamId, ReadOnlySequence _endInvokeJSSucceeded; private static readonly Action _receiveByteArraySuccess; private static readonly Action _receiveByteArrayException; - private static readonly Action _supplyJSDataChunkException; + private static readonly Action _receiveJSDataChunkException; private static readonly Action _dispatchEventFailedToParseEventData; private static readonly Action _dispatchEventFailedToDispatchEvent; private static readonly Action _locationChange; @@ -706,7 +706,7 @@ private static class EventIds public static readonly EventId OnRenderCompletedFailed = new EventId(212, "OnRenderCompletedFailed"); public static readonly EventId ReceiveByteArraySucceeded = new EventId(213, "ReceiveByteArraySucceeded"); public static readonly EventId ReceiveByteArrayException = new EventId(214, "ReceiveByteArrayException"); - public static readonly EventId SupplyJSDataChunkException = new EventId(215, "SupplyJSDataChunkException"); + public static readonly EventId ReceiveJSDataChunkException = new EventId(215, "ReceiveJSDataChunkException"); } static Log() @@ -836,10 +836,10 @@ static Log() EventIds.ReceiveByteArrayException, "The ReceiveByteArray call with id '{id}' failed."); - _supplyJSDataChunkException = LoggerMessage.Define( + _receiveJSDataChunkException = LoggerMessage.Define( LogLevel.Debug, - EventIds.SupplyJSDataChunkException, - "The SupplyJSDataChunk call with stream id '{streamId}' failed."); + EventIds.ReceiveJSDataChunkException, + "The ReceiveJSDataChunk call with stream id '{streamId}' failed."); _dispatchEventFailedToParseEventData = LoggerMessage.Define( LogLevel.Debug, @@ -905,7 +905,7 @@ public static void CircuitHandlerFailed(ILogger logger, CircuitHandler handler, public static void EndInvokeJSSucceeded(ILogger logger, long asyncCall) => _endInvokeJSSucceeded(logger, asyncCall, null); internal static void ReceiveByteArraySuccess(ILogger logger, long id) => _receiveByteArraySuccess(logger, id, null); internal static void ReceiveByteArrayException(ILogger logger, long id, Exception ex) => _receiveByteArrayException(logger, id, ex); - internal static void SupplyJSDataChunkException(ILogger logger, string streamId, Exception ex) => _supplyJSDataChunkException(logger, streamId, ex); + internal static void ReceiveJSDataChunkException(ILogger logger, string streamId, Exception ex) => _receiveJSDataChunkException(logger, streamId, ex); public static void DispatchEventFailedToParseEventData(ILogger logger, Exception ex) => _dispatchEventFailedToParseEventData(logger, ex); public static void DispatchEventFailedToDispatchEvent(ILogger logger, string eventHandlerId, Exception ex) => _dispatchEventFailedToDispatchEvent(logger, eventHandlerId ?? "", ex); diff --git a/src/Components/Server/src/Circuits/RemoteJSDataStream.cs b/src/Components/Server/src/Circuits/RemoteJSDataStream.cs index 0c8490762b36..804eedcaac44 100644 --- a/src/Components/Server/src/Circuits/RemoteJSDataStream.cs +++ b/src/Components/Server/src/Circuits/RemoteJSDataStream.cs @@ -66,17 +66,12 @@ private RemoteJSDataStream( _pipeReaderStream = _pipe.Reader.AsStream(); } - // TODO: Surely this should be IAsyncEnumerable> so we can pass through the - // data without having to copy it into a temporary buffer. But trying this gives strange errors - - // sometimes the "chunk" variable below has a negative length, even though the logic in BlazorPackHubProtocolWorker - // never returns a corrupted item as far as I can tell. + // Ideally we'd have IAsyncEnumerable> here so we can pass through the + // data without having to copy it into a temporary buffer in BlazorPackHubProtocolWorker. But trying + // this gives strange errors; sometimes the "chunk" variable below has a negative length, even though + // the logic never returns a corrupted item as far as I can tell. private async Task SupplyData(ReadOnlySequence chunk, string error) { - if (chunk.Length < 0) - { - throw new InvalidOperationException($"The incoming data chunk cannot be negative."); - } - try { if (!string.IsNullOrEmpty(error)) @@ -96,13 +91,6 @@ private async Task SupplyData(ReadOnlySequence chunk, string error) throw new InvalidOperationException($"The incoming data stream declared a length {_totalLength}, but {_bytesRead} bytes were read."); } - // Enforce 1 MB max chunk size. - const int maxChunkLength = 1024 * 1024; - if (chunk.Length > maxChunkLength) - { - throw new InvalidOperationException($"The incoming stream chunk of length {chunk.Length} exceeds the limit of {maxChunkLength}."); - } - CopyToPipeWriter(chunk, _pipe.Writer); _pipe.Writer.Advance((int)chunk.Length); await _pipe.Writer.FlushAsync(_cancellationToken); diff --git a/src/Components/Server/src/ComponentHub.cs b/src/Components/Server/src/ComponentHub.cs index a32f71fb0a5f..920289d578b1 100644 --- a/src/Components/Server/src/ComponentHub.cs +++ b/src/Components/Server/src/ComponentHub.cs @@ -224,7 +224,7 @@ public async ValueTask ReceiveByteArray(int id, byte[] data) await circuitHost.ReceiveByteArray(id, data); } - public async Task SupplyJSDataChunk(string streamId, ReadOnlySequence chunk, string error) + public async Task ReceiveJSDataChunk(string streamId, ReadOnlySequence chunk, string error) { var circuitHost = await GetActiveCircuitAsync(); if (circuitHost == null) @@ -232,7 +232,7 @@ public async Task SupplyJSDataChunk(string streamId, ReadOnlySequence 1) { // Most of the time just send and buffer within the network layer - await connection.send('SupplyJSDataChunk', streamId, nextChunkData, null); + await connection.send('ReceiveJSDataChunk', streamId, nextChunkData, null); } else { // But regularly, wait for an ACK, so other events can be interleaved // The use of "invoke" (not "send") here is what prevents the JS side from queuing up chunks // faster than the .NET side can receive them. It means that if there are other user interactions // while the transfer is in progress, they would get inserted in the middle, so it would be // possible to navigate away or cancel without first waiting for all the remaining chunks. - const streamIsAlive = await connection.invoke('SupplyJSDataChunk', streamId, nextChunkData, null); + const streamIsAlive = await connection.invoke('ReceiveJSDataChunk', streamId, nextChunkData, null); // Checks to see if we should continue streaming or if the stream has been cancelled/disposed. if (!streamIsAlive) { @@ -174,7 +174,7 @@ async function initializeConnection(options: CircuitStartOptions, logger: Logger position += nextChunkSize; } } catch (error) { - await connection.send('SupplyJSDataChunk', streamId, null, error.toString()); + await connection.send('ReceiveJSDataChunk', streamId, null, error.toString()); } }, 0); }; diff --git a/src/JSInterop/Microsoft.JSInterop/src/IJSDataReference.cs b/src/JSInterop/Microsoft.JSInterop/src/IJSDataReference.cs index d98133e9d84f..c12f6fab23b6 100644 --- a/src/JSInterop/Microsoft.JSInterop/src/IJSDataReference.cs +++ b/src/JSInterop/Microsoft.JSInterop/src/IJSDataReference.cs @@ -14,14 +14,14 @@ namespace Microsoft.JSInterop public interface IJSDataReference : IAsyncDisposable { /// - /// Length of the stream provided by JS. + /// Length of the stream provided by JavaScript. /// public long Length { get; } /// /// Initiatializes a with the for the current data reference. /// - /// Maximum number of bytes permitted to be read from JS. + /// Maximum number of bytes permitted to be read from JavaScript. /// Amount of bytes to buffer before flushing. /// for cancelling read. /// Stream which can provide data associated with the current data reference. From b266fbafa86d983695e322b712b228eddbb90cc3 Mon Sep 17 00:00:00 2001 From: Tanay Parikh Date: Mon, 14 Jun 2021 11:19:57 -0700 Subject: [PATCH 11/37] JSCallResultType JSDataReference --- .../Web.JS/dist/Release/blazor.server.js | 2 +- .../Web.JS/dist/Release/blazor.webview.js | 2 +- src/Components/Web.JS/src/Boot.WebAssembly.ts | 1 + ...bAssemblyJSObjectReferenceJsonConverter.cs | 4 +- .../JSInterop/src/WebAssemblyJSRuntime.cs | 1 + .../src/src/Microsoft.JSInterop.ts | 43 +++++++++++++++---- .../JSObjectReferenceJsonWorker.cs | 39 ++++------------- .../JSDataReferenceJsonConverter.cs | 41 ++++++++++++++++-- .../JSObjectReferenceJsonConverter.cs | 4 +- .../src/JSCallResultType.cs | 5 +++ .../src/PublicAPI.Unshipped.txt | 3 +- 11 files changed, 95 insertions(+), 50 deletions(-) diff --git a/src/Components/Web.JS/dist/Release/blazor.server.js b/src/Components/Web.JS/dist/Release/blazor.server.js index 1cfb992eb305..2fc7959e9ae8 100644 --- a/src/Components/Web.JS/dist/Release/blazor.server.js +++ b/src/Components/Web.JS/dist/Release/blazor.server.js @@ -1 +1 @@ -(()=>{"use strict";var e,t,n;!function(e){window.DotNet=e;const t=[],n=new Map;class r{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 o="__jsObjectId",i={},s={0:new r(window)};s[0]._cachedFunctions.set("import",(e=>("string"==typeof e&&e.startsWith("./")&&(e=document.baseURI+e.substr(2)),import(e))));let a,c=1,l=1,h=null;function u(e){t.push(e)}function d(e){if(e&&"object"==typeof e){s[l]=new r(e);const t={[o]:l};return l++,t}throw new Error(`Cannot create a JSObjectReference from the value '${e}'.`)}function p(e){return e?JSON.parse(e,((e,n)=>t.reduce(((t,n)=>n(e,t)),n))):null}function f(e,t,n,r){const o=m();if(o.invokeDotNetFromJS){const i=I(r),s=o.invokeDotNetFromJS(e,t,n,i);return s?p(s):null}throw new Error("The current dispatcher does not support synchronous calls from JS to .NET. Use invokeMethodAsync instead.")}function g(e,t,n,r){if(e&&n)throw new Error(`For instance method calls, assemblyName should be null. Received '${e}'.`);const o=c++,s=new Promise(((e,t)=>{i[o]={resolve:e,reject:t}}));try{const i=I(r);m().beginInvokeDotNetFromJS(o,e,t,n,i)}catch(e){y(o,!1,e)}return s}function m(){if(null!==h)return h;throw new Error("No .NET call dispatcher has been set.")}function y(e,t,n){if(!i.hasOwnProperty(e))throw new Error(`There is no pending async call with ID ${e}.`);const r=i[e];delete i[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 v(e,t){let n=s[t];if(n)return n.findFunction(e);throw new Error(`JS object instance with ID ${t} does not exist (has it been disposed?).`)}function b(e){delete s[e]}e.attachDispatcher=function(e){h=e},e.attachReviver=u,e.invokeMethod=function(e,t,...n){return f(e,t,null,n)},e.invokeMethodAsync=function(e,t,...n){return g(e,t,null,n)},e.createJSObjectReference=d,e.disposeJSObjectReference=function(e){const t=e&&e.__jsObjectId;"number"==typeof t&&b(t)},function(e){e[e.Default=0]="Default",e[e.JSObjectReference=1]="JSObjectReference"}(a=e.JSCallResultType||(e.JSCallResultType={})),e.jsCallDispatcher={findJSFunction:v,disposeJSObjectReferenceById:b,invokeJSFromDotNet:(e,t,n,r)=>{const o=S(v(e,r).apply(null,p(t)),n);return null==o?null:I(o)},beginInvokeJSFromDotNet:(e,t,n,r,o)=>{const i=new Promise((e=>{e(v(t,o).apply(null,p(n)))}));e&&i.then((t=>m().endInvokeJSFromDotNet(e,!0,I([e,!0,S(t,r)]))),(t=>m().endInvokeJSFromDotNet(e,!1,JSON.stringify([e,!1,w(t)]))))},endInvokeDotNetFromJS:(e,t,n)=>{const r=t?p(n):new Error(n);y(parseInt(e),t,r)},receiveByteArray:(e,t)=>{n.set(e,t)}};class _{constructor(e){this._id=e}invokeMethod(e,...t){return f(null,e,this._id,t)}invokeMethodAsync(e,...t){return g(null,e,this._id,t)}dispose(){g(null,"__Dispose",this._id,null).catch((e=>console.error(e)))}serializeAsArg(){return{__dotNetObject:this._id}}}const E="__byte[]";function S(e,t){switch(t){case a.Default:return e;case a.JSObjectReference:return d(e);default:throw new Error(`Invalid JS call result type '${t}'.`)}}u((function(e,t){if(t&&"object"==typeof t){if(t.hasOwnProperty("__dotNetObject"))return new _(t.__dotNetObject);if(t.hasOwnProperty(o)){const e=t.__jsObjectId,n=s[e];if(n)return n.getWrappedObject();throw new Error(`JS object instance with Id '${e}' does not exist. It may have been disposed.`)}if(t.hasOwnProperty(E)){const e=t["__byte[]"],r=n.get(e);if(void 0===r)throw new Error(`Byte array index '${e}' does not exist.`);return r}}return t}));let C=0;function I(e){return C=0,JSON.stringify(e,k)}function k(e,t){if(t instanceof _)return t.serializeAsArg();if(t instanceof Uint8Array){h.sendByteArray(C,t);const e={[E]:C};return C++,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"}(n||(n={}));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}}let o;function i(e,t){if(!o)throw new Error("eventDispatcher not initialized. Call 'setEventDispatcher' to configure it.");o(e,t)}const s=new Map,a=new Map,c={createEventArgs:()=>({})},l=[];function h(e){return s.get(e)}function u(e){const t=s.get(e);return(null==t?void 0:t.browserEventName)||e}function d(e,t){e.forEach((e=>s.set(e,t)))}function p(e){const t=[];for(let n=0;n{return{...f(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}}),d(["focus","blur","focusin","focusout"],c),d(["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};var t}}),d(["contextmenu","click","mouseover","mouseout","mousemove","mousedown","mouseup","dblclick"],{createEventArgs:e=>f(e)}),d(["error"],{createEventArgs:e=>{return{message:(t=e).message,filename:t.filename,lineno:t.lineno,colno:t.colno};var t}}),d(["loadstart","timeout","abort","load","loadend","progress"],{createEventArgs:e=>{return{lengthComputable:(t=e).lengthComputable,loaded:t.loaded,total:t.total};var t}}),d(["touchcancel","touchend","touchmove","touchenter","touchleave","touchstart"],{createEventArgs:e=>{return{detail:(t=e).detail,touches:p(t.touches),targetTouches:p(t.targetTouches),changedTouches:p(t.changedTouches),ctrlKey:t.ctrlKey,shiftKey:t.shiftKey,altKey:t.altKey,metaKey:t.metaKey,type:t.type};var t}}),d(["gotpointercapture","lostpointercapture","pointercancel","pointerdown","pointerenter","pointerleave","pointermove","pointerout","pointerover","pointerup"],{createEventArgs:e=>{return{...f(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}}),d(["wheel","mousewheel"],{createEventArgs:e=>{return{...f(t=e),deltaX:t.deltaX,deltaY:t.deltaY,deltaZ:t.deltaZ,deltaMode:t.deltaMode};var t}}),d(["toggle"],c);const g=["date","datetime-local","month","time","week"],m=E(["abort","blur","change","error","focus","load","loadend","loadstart","mouseenter","mouseleave","progress","reset","scroll","submit","unload","toggle","DOMNodeInsertedIntoDocument","DOMNodeRemovedFromDocument"]),y={submit:!0},w=E(["click","dblclick","mousedown","mousemove","mouseup"]);class v{constructor(e){this.browserRendererId=e,this.afterClickCallbacks=[];const t=++v.nextEventDelegatorId;this.eventsCollectionKey=`_blazorEvents_${t}`,this.eventInfoStore=new b(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,a.get(n));var n;t&&t.forEach((t=>this.dispatchGlobalEventToAllElements(t,e))),"click"===e.type&&this.afterClickCallbacks.forEach((t=>t(e)))}dispatchGlobalEventToAllElements(e,t){let n=t.target,o=null,s=!1;const a=m.hasOwnProperty(e);let c=!1;for(;n;){const d=this.getEventHandlerInfosForElement(n,!1);if(d){const a=d.getHandler(e);if(a&&(l=n,u=t.type,!((l instanceof HTMLButtonElement||l instanceof HTMLInputElement||l instanceof HTMLTextAreaElement||l instanceof HTMLSelectElement)&&w.hasOwnProperty(u)&&l.disabled))){if(!s){const n=h(e);o=(null==n?void 0:n.createEventArgs)?n.createEventArgs(t):{},s=!0}y.hasOwnProperty(t.type)&&t.preventDefault(),i({browserRendererId:this.browserRendererId,eventHandlerId:a.eventHandlerId,eventName:e,eventFieldInfo:r.fromEvent(a.renderingComponentId,t)},o)}d.stopPropagation(e)&&(c=!0),d.preventDefault(e)&&t.preventDefault()}n=a||c?null:n.parentElement}var l,u}getEventHandlerInfosForElement(e,t){return e.hasOwnProperty(this.eventsCollectionKey)?e[this.eventsCollectionKey]:t?e[this.eventsCollectionKey]=new _:null}}v.nextEventDelegatorId=0;class b{constructor(e){this.globalListener=e,this.infosByEventHandlerId={},this.countByEventName={},l.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=u(e),this.countByEventName.hasOwnProperty(e))this.countByEventName[e]++;else{this.countByEventName[e]=1;const t=m.hasOwnProperty(e);document.addEventListener(e,this.globalListener,t)}}update(e,t){if(this.infosByEventHandlerId.hasOwnProperty(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=u(t.eventName);0==--this.countByEventName[n]&&(delete this.countByEventName[n],document.removeEventListener(n,this.globalListener))}return t}handleEventNameAliasAdded(e,t){if(this.countByEventName.hasOwnProperty(e)){const n=this.countByEventName[e];delete this.countByEventName[e],document.removeEventListener(e,this.globalListener),this.addGlobalListener(t),this.countByEventName[t]+=n-1}}}class _{constructor(){this.handlers={},this.preventDefaultFlags=null,this.stopPropagationFlags=null}getHandler(e){return this.handlers.hasOwnProperty(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 E(e){const t={};return e.forEach((e=>{t[e]=!0})),t}const S=H("_blazorLogicalChildren"),C=H("_blazorLogicalParent"),I=H("_blazorLogicalEnd");function k(e,t){if(e.childNodes.length>0&&!t)throw new Error("New logical elements must start empty, or allowExistingContents must be true");return S in e||(e[S]=[]),e}function T(e,t){const n=document.createComment("!");return x(n,e,t),n}function x(e,t,n){const r=e;if(e instanceof Comment&&A(r)&&A(r).length>0)throw new Error("Not implemented: inserting non-empty logical container");if(R(r))throw new Error("Not implemented: moving existing logical children");const o=A(t);if(n0;)D(n,0)}const r=n;r.parentNode.removeChild(r)}function R(e){return e[C]||null}function P(e,t){return A(e)[t]}function U(e){var t=B(e);return"http://www.w3.org/2000/svg"===t.namespaceURI&&"foreignObject"!==t.tagName}function A(e){return e[S]}function N(e,t){const n=A(e);t.forEach((e=>{e.moveRangeStart=n[e.fromSiblingIndex],e.moveRangeEnd=M(e.moveRangeStart)})),t.forEach((t=>{const r=t.moveToBeforeMarker=document.createComment("marker"),o=n[t.toSiblingIndex+1];o?o.parentNode.insertBefore(r,o):L(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 B(e){if(e instanceof Element)return e;if(e instanceof Comment)return e.parentNode;throw new Error("Not a valid logical element")}function $(e){const t=A(R(e));return t[Array.prototype.indexOf.call(t,e)+1]||null}function L(e,t){if(t instanceof Element)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=$(t);n?n.parentNode.insertBefore(e,n):L(e,R(t))}}}function M(e){if(e instanceof Element)return e;const t=$(e);if(t)return t.previousSibling;{const t=R(e);return t instanceof Element?t.lastChild:M(t)}}function H(e){return"function"==typeof Symbol?Symbol():e}function F(e){return`_bl_${e}`}e.attachReviver(((e,t)=>t&&"object"==typeof t&&t.hasOwnProperty("__internalId")&&"string"==typeof t.__internalId?function(e){const t=`[${F(e)}]`;return document.querySelector(t)}(t.__internalId):t));const O="_blazorSelectValue",j=document.createElement("template"),W=document.createElementNS("http://www.w3.org/2000/svg","g"),z={},q="__internal_",J="preventDefault_",K="stopPropagation_";class V{constructor(e){this.childComponentLocations={},this.eventDelegator=new v(e),this.eventDelegator.notifyAfterClick((e=>{if(!ee)return;if(0!==e.button||function(e){return e.ctrlKey||e.shiftKey||e.altKey||e.metaKey}(e))return;if(e.defaultPrevented)return;const t=function(e){const t=!window._blazorDisableComposedPath&&e.composedPath&&e.composedPath();if(t){for(let e=0;ese(!1))))},enableNavigationInterception:function(){ee=!0},navigateTo:oe,getBaseURI:()=>document.baseURI,getLocationHref:()=>location.href};function oe(e,t,n=!1){const r=ce(e);if(!t&&he(r))ie(r,!1,n);else if(t&&location.href===e){const t=e+"?";history.replaceState(null,"",t),location.replace(e)}else n?history.replaceState(null,"",r):location.href=e}function ie(e,t,n=!1){Z=!0,n?history.replaceState(null,"",e):history.pushState(null,"",e),se(t)}async function se(e){ne&&await ne(location.href,e)}let ae;function ce(e){return ae=ae||document.createElement("a"),ae.href=e,ae.href}function le(e,t){return e?e.tagName===t?e:le(e.parentElement,t):null}function he(e){const t=(n=document.baseURI).substr(0,n.lastIndexOf("/")+1);var n;return e.startsWith(t)}const ue={init:function(e,t,n,r=50){const o=pe(t);(o||document.documentElement).style.overflowAnchor="none";const i=new IntersectionObserver((function(r){r.forEach((r=>{var o;if(!r.isIntersecting)return;const i=t.getBoundingClientRect(),s=n.getBoundingClientRect().top-i.bottom,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`});i.observe(t),i.observe(n);const s=c(t),a=c(n);function c(e){const t=new MutationObserver((()=>{i.unobserve(e),i.observe(e)}));return t.observe(e,{attributes:!0}),t}de[e._id]={intersectionObserver:i,mutationObserverBefore:s,mutationObserverAfter:a}},dispose:function(e){const t=de[e._id];t&&(t.intersectionObserver.disconnect(),t.mutationObserverBefore.disconnect(),t.mutationObserverAfter.disconnect(),e.dispose(),delete de[e._id])}},de={};function pe(e){return e?"visible"!==getComputedStyle(e).overflowY?e:pe(e.parentElement):null}const fe={navigateTo:oe,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=a.get(t.browserEventName);n?n.push(e):a.set(t.browserEventName,[e]),l.forEach((n=>n(e,t.browserEventName)))}s.set(e,t)},_internal:{navigationManager:re,domWrapper:{focus:function(e,t){if(!(e instanceof HTMLElement))throw new Error("Unable to focus an invalid element.");e.focus({preventScroll:t})},focusBySelector:function(e){const t=document.querySelector(e);t&&(t.hasAttribute("tabindex")||(t.tabIndex=-1),t.focus())}},Virtualize:ue}};window.Blazor=fe;const ge=[0,2e3,1e4,3e4,null];class me{constructor(e){this._retryDelays=void 0!==e?[...e,null]:ge}nextRetryDelayInMilliseconds(e){return this._retryDelays[e.previousRetryCount]}}class ye extends Error{constructor(e,t){const n=new.target.prototype;super(`${e}: Status code '${t}'`),this.statusCode=t,this.__proto__=n}}class we extends Error{constructor(e="A timeout occurred."){const t=new.target.prototype;super(e),this.__proto__=t}}class ve extends Error{constructor(e="An abort occurred."){const t=new.target.prototype;super(e),this.__proto__=t}}class be{constructor(e,t,n){this.statusCode=e,this.statusText=t,this.content=n}}class _e{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""}}var Ee,Se,Ce,Ie,ke;!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"}(Ee||(Ee={}));class Te extends _e{constructor(e){if(super(),this._logger=e,"undefined"==typeof fetch){const e=require;this._jar=new(e("tough-cookie").CookieJar),this._fetchType=e("node-fetch"),this._fetchType=e("fetch-cookie")(this._fetchType,this._jar),this._abortControllerType=e("abort-controller")}else this._fetchType=fetch.bind(self),this._abortControllerType=AbortController}async send(e){if(e.abortSignal&&e.abortSignal.aborted)throw new ve;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 ve});let r,o=null;if(e.timeout){const r=e.timeout;o=setTimeout((()=>{t.abort(),this._logger.log(Ee.Warning,"Timeout from HTTP request."),n=new we}),r)}try{r=await this._fetchType(e.url,{body:e.content,cache:"no-cache",credentials:!0===e.withCredentials?"include":"same-origin",headers:{"Content-Type":"text/plain;charset=UTF-8","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(Ee.Warning,`Error from HTTP request. ${e}.`),e}finally{o&&clearTimeout(o),e.abortSignal&&(e.abortSignal.onabort=null)}if(!r.ok){const e=await xe(r,"text");throw new ye(e||r.statusText,r.status)}const i=xe(r,e.responseType),s=await i;return new be(r.status,r.statusText,s)}getCookieString(e){return""}}function xe(e,t){let n;switch(t){case"arraybuffer":n=e.arrayBuffer();break;case"text":n=e.text();break;case"blob":case"document":case"json":throw new Error(`${t} is not supported.`);default:n=e.text()}return n}class De extends _e{constructor(e){super(),this._logger=e}send(e){return e.abortSignal&&e.abortSignal.aborted?Promise.reject(new ve):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"),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 ve)}),e.timeout&&(r.timeout=e.timeout),r.onload=()=>{e.abortSignal&&(e.abortSignal.onabort=null),r.status>=200&&r.status<300?t(new be(r.status,r.statusText,r.response||r.responseText)):n(new ye(r.response||r.responseText||r.statusText,r.status))},r.onerror=()=>{this._logger.log(Ee.Warning,`Error from HTTP request. ${r.status}: ${r.statusText}.`),n(new ye(r.statusText,r.status))},r.ontimeout=()=>{this._logger.log(Ee.Warning,"Timeout from HTTP request."),n(new we)},r.send(e.content||"")})):Promise.reject(new Error("No url defined.")):Promise.reject(new Error("No method defined."))}}class Re extends _e{constructor(e){if(super(),"undefined"!=typeof fetch)this._httpClient=new Te(e);else{if("undefined"==typeof XMLHttpRequest)throw new Error("No usable HttpClient found.");this._httpClient=new De(e)}}send(e){return e.abortSignal&&e.abortSignal.aborted?Promise.reject(new ve):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)}}class Pe{}Pe.Authorization="Authorization",Pe.Cookie="Cookie",function(e){e[e.None=0]="None",e[e.WebSockets=1]="WebSockets",e[e.ServerSentEvents=2]="ServerSentEvents",e[e.LongPolling=4]="LongPolling"}(Se||(Se={})),function(e){e[e.Text=1]="Text",e[e.Binary=2]="Binary"}(Ce||(Ce={}));class Ue{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 Ae{constructor(){}log(e,t){}}Ae.instance=new Ae;class Ne{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 Be{static get isBrowser(){return"object"==typeof window}static get isWebWorker(){return"object"==typeof self&&"importScripts"in self}static get isNode(){return!this.isBrowser&&!this.isWebWorker}}function $e(e,t){let n="";return Le(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 Le(e){return e&&"undefined"!=typeof ArrayBuffer&&(e instanceof ArrayBuffer||e.constructor&&"ArrayBuffer"===e.constructor.name)}async function Me(e,t,n,r,o,i,s,a,c){let l={};if(o){const e=await o();e&&(l={Authorization:`Bearer ${e}`})}const[h,u]=Oe();l[h]=u,e.log(Ee.Trace,`(${t} transport) sending data. ${$e(i,s)}.`);const d=Le(i)?"arraybuffer":"text",p=await n.post(r,{content:i,headers:{...l,...c},responseType:d,withCredentials:a});e.log(Ee.Trace,`(${t} transport) request complete. Response status: ${p.statusCode}.`)}class He{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 Fe{constructor(e){this._minLevel=e,this.out=console}log(e,t){if(e>=this._minLevel){const n=`[${(new Date).toISOString()}] ${Ee[e]}: ${t}`;switch(e){case Ee.Critical:case Ee.Error:this.out.error(n);break;case Ee.Warning:this.out.warn(n);break;case Ee.Information:this.out.info(n);break;default:this.out.log(n)}}}}function Oe(){let e="X-SignalR-User-Agent";return Be.isNode&&(e="User-Agent"),[e,je("0.0.0-DEV_BUILD",We(),Be.isNode?"NodeJS":"Browser",ze())]}function je(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 We(){if(!Be.isNode)return"";switch(process.platform){case"win32":return"Windows NT";case"darwin":return"macOS";case"linux":return"Linux";default:return process.platform}}function ze(){if(Be.isNode)return process.versions.node}class qe{constructor(e,t,n,r,o,i){this._httpClient=e,this._accessTokenFactory=t,this._logger=n,this._pollAbort=new Ue,this._logMessageContent=r,this._withCredentials=o,this._headers=i,this._running=!1,this.onreceive=null,this.onclose=null}get pollAborted(){return this._pollAbort.aborted}async connect(e,t){if(Ne.isRequired(e,"url"),Ne.isRequired(t,"transferFormat"),Ne.isIn(t,Ce,"transferFormat"),this._url=e,this._logger.log(Ee.Trace,"(LongPolling transport) Connecting."),t===Ce.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]=Oe(),o={[n]:r,...this._headers},i={abortSignal:this._pollAbort.signal,headers:o,timeout:1e5,withCredentials:this._withCredentials};t===Ce.Binary&&(i.responseType="arraybuffer");const s=await this._getAccessToken();this._updateHeaderToken(i,s);const a=`${e}&_=${Date.now()}`;this._logger.log(Ee.Trace,`(LongPolling transport) polling: ${a}.`);const c=await this._httpClient.get(a,i);200!==c.statusCode?(this._logger.log(Ee.Error,`(LongPolling transport) Unexpected response code: ${c.statusCode}.`),this._closeError=new ye(c.statusText||"",c.statusCode),this._running=!1):this._running=!0,this._receiving=this._poll(this._url,i)}async _getAccessToken(){return this._accessTokenFactory?await this._accessTokenFactory():null}_updateHeaderToken(e,t){e.headers||(e.headers={}),t?e.headers[Pe.Authorization]=`Bearer ${t}`:e.headers[Pe.Authorization]&&delete e.headers[Pe.Authorization]}async _poll(e,t){try{for(;this._running;){const n=await this._getAccessToken();this._updateHeaderToken(t,n);try{const n=`${e}&_=${Date.now()}`;this._logger.log(Ee.Trace,`(LongPolling transport) polling: ${n}.`);const r=await this._httpClient.get(n,t);204===r.statusCode?(this._logger.log(Ee.Information,"(LongPolling transport) Poll terminated by server."),this._running=!1):200!==r.statusCode?(this._logger.log(Ee.Error,`(LongPolling transport) Unexpected response code: ${r.statusCode}.`),this._closeError=new ye(r.statusText||"",r.statusCode),this._running=!1):r.content?(this._logger.log(Ee.Trace,`(LongPolling transport) data received. ${$e(r.content,this._logMessageContent)}.`),this.onreceive&&this.onreceive(r.content)):this._logger.log(Ee.Trace,"(LongPolling transport) Poll timed out, reissuing.")}catch(e){this._running?e instanceof we?this._logger.log(Ee.Trace,"(LongPolling transport) Poll timed out, reissuing."):(this._closeError=e,this._running=!1):this._logger.log(Ee.Trace,`(LongPolling transport) Poll errored after shutdown: ${e.message}`)}}}finally{this._logger.log(Ee.Trace,"(LongPolling transport) Polling complete."),this.pollAborted||this._raiseOnClose()}}async send(e){return this._running?Me(this._logger,"LongPolling",this._httpClient,this._url,this._accessTokenFactory,e,this._logMessageContent,this._withCredentials,this._headers):Promise.reject(new Error("Cannot send until the transport is connected"))}async stop(){this._logger.log(Ee.Trace,"(LongPolling transport) Stopping polling."),this._running=!1,this._pollAbort.abort();try{await this._receiving,this._logger.log(Ee.Trace,`(LongPolling transport) sending DELETE request to ${this._url}.`);const e={},[t,n]=Oe();e[t]=n;const r={headers:{...e,...this._headers},withCredentials:this._withCredentials},o=await this._getAccessToken();this._updateHeaderToken(r,o),await this._httpClient.delete(this._url,r),this._logger.log(Ee.Trace,"(LongPolling transport) DELETE request sent.")}finally{this._logger.log(Ee.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(Ee.Trace,e),this.onclose(this._closeError)}}}class Je{constructor(e,t,n,r,o,i,s){this._httpClient=e,this._accessTokenFactory=t,this._logger=n,this._logMessageContent=r,this._withCredentials=i,this._eventSourceConstructor=o,this._headers=s,this.onreceive=null,this.onclose=null}async connect(e,t){if(Ne.isRequired(e,"url"),Ne.isRequired(t,"transferFormat"),Ne.isIn(t,Ce,"transferFormat"),this._logger.log(Ee.Trace,"(SSE transport) Connecting."),this._url=e,this._accessTokenFactory){const t=await this._accessTokenFactory();t&&(e+=(e.indexOf("?")<0?"?":"&")+`access_token=${encodeURIComponent(t)}`)}return new Promise(((n,r)=>{let o,i=!1;if(t===Ce.Text){if(Be.isBrowser||Be.isWebWorker)o=new this._eventSourceConstructor(e,{withCredentials:this._withCredentials});else{const t=this._httpClient.getCookieString(e),n={};n.Cookie=t;const[r,i]=Oe();n[r]=i,o=new this._eventSourceConstructor(e,{withCredentials:this._withCredentials,headers:{...n,...this._headers}})}try{o.onmessage=e=>{if(this.onreceive)try{this._logger.log(Ee.Trace,`(SSE transport) data received. ${$e(e.data,this._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(Ee.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?Me(this._logger,"SSE",this._httpClient,this._url,this._accessTokenFactory,e,this._logMessageContent,this._withCredentials,this._headers):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 Ke{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){if(Ne.isRequired(e,"url"),Ne.isRequired(t,"transferFormat"),Ne.isIn(t,Ce,"transferFormat"),this._logger.log(Ee.Trace,"(WebSockets transport) Connecting."),this._accessTokenFactory){const t=await this._accessTokenFactory();t&&(e+=(e.indexOf("?")<0?"?":"&")+`access_token=${encodeURIComponent(t)}`)}return new Promise(((n,r)=>{let o;e=e.replace(/^http/,"ws"),this._httpClient.getCookieString(e);let i=!1;o||(o=new this._webSocketConstructor(e)),t===Ce.Binary&&(o.binaryType="arraybuffer"),o.onopen=t=>{this._logger.log(Ee.Information,`WebSocket connected to ${e}.`),this._webSocket=o,i=!0,n()},o.onerror=e=>{let t=null;t="undefined"!=typeof ErrorEvent&&e instanceof ErrorEvent?e.error:"There was an error with the transport",this._logger.log(Ee.Information,`(WebSockets transport) ${t}.`)},o.onmessage=e=>{if(this._logger.log(Ee.Trace,`(WebSockets transport) data received. ${$e(e.data,this._logMessageContent)}.`),this.onreceive)try{this.onreceive(e.data)}catch(e){return void this._close(e)}},o.onclose=e=>{if(i)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(Ee.Trace,`(WebSockets transport) sending data. ${$e(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(Ee.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 Ve{constructor(e,t={}){var n;if(this._stopPromiseResolver=()=>{},this.features={},this._negotiateVersion=1,Ne.isRequired(e,"url"),this._logger=void 0===(n=t.logger)?new Fe(Ee.Information):null===n?Ae.instance:void 0!==n.log?n:new Fe(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,"undefined"==typeof WebSocket||t.WebSocket||(t.WebSocket=WebSocket),"undefined"==typeof EventSource||t.EventSource||(t.EventSource=EventSource),this._httpClient=t.httpClient||new Re(this._logger),this._connectionState="Disconnected",this._connectionStarted=!1,this._options=t,this.onreceive=null,this.onclose=null}async start(e){if(e=e||Ce.Binary,Ne.isIn(e,Ce,"transferFormat"),this._logger.log(Ee.Debug,`Starting connection with transfer format '${Ce[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(Ee.Error,e),await this._stopPromise,Promise.reject(new Error(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(Ee.Error,e),Promise.reject(new Error(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 Xe(this.transport)),this._sendQueue.send(e))}async stop(e){return"Disconnected"===this._connectionState?(this._logger.log(Ee.Debug,`Call to HttpConnection.stop(${e}) ignored because the connection is already in the disconnected state.`),Promise.resolve()):"Disconnecting"===this._connectionState?(this._logger.log(Ee.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(Ee.Error,`HttpConnection.transport.stop() threw error '${e}'.`),this._stopConnection()}this.transport=void 0}else this._logger.log(Ee.Debug,"HttpConnection.transport is undefined in HttpConnection.stop() because start() failed.")}async _startInternal(e){let t=this.baseUrl;this._accessTokenFactory=this._options.accessTokenFactory;try{if(this._options.skipNegotiation){if(this._options.transport!==Se.WebSockets)throw new Error("Negotiation can only be skipped when using the WebSocket transport directly.");this.transport=this._constructTransport(Se.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 Error("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}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 qe&&(this.features.inherentKeepAlive=!0),"Connecting"===this._connectionState&&(this._logger.log(Ee.Debug,"The HttpConnection connected successfully."),this._connectionState="Connected")}catch(e){return this._logger.log(Ee.Error,"Failed to start the connection: "+e),this._connectionState="Disconnected",this.transport=void 0,this._stopPromiseResolver(),Promise.reject(e)}}async _getNegotiationResponse(e){const t={};if(this._accessTokenFactory){const e=await this._accessTokenFactory();e&&(t[Pe.Authorization]=`Bearer ${e}`)}const[n,r]=Oe();t[n]=r;const o=this._resolveNegotiateUrl(e);this._logger.log(Ee.Debug,`Sending negotiation request: ${o}.`);try{const e=await this._httpClient.post(o,{content:"",headers:{...t,...this._options.headers},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 ye&&404===e.statusCode&&(t+=" Either this is not a SignalR endpoint or there is a proxy blocking the connection."),this._logger.log(Ee.Error,t),Promise.reject(new Error(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(Ee.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: ${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(Ee.Error,`Failed to start the transport '${n.transport}': ${e}`),a=void 0,i.push(`${n.transport} failed: ${e}`),"Connecting"!==this._connectionState){const e="Failed to select transport before stop() was called.";return this._logger.log(Ee.Debug,e),Promise.reject(new Error(e))}}}}return i.length>0?Promise.reject(new Error(`Unable to connect to the server with any of the available transports. ${i.join(" ")}`)):Promise.reject(new Error("None of the transports supported by the client are supported by the server."))}_constructTransport(e){switch(e){case Se.WebSockets:if(!this._options.WebSocket)throw new Error("'WebSocket' is not supported in your environment.");return new Ke(this._httpClient,this._accessTokenFactory,this._logger,this._options.logMessageContent||!1,this._options.WebSocket,this._options.headers||{});case Se.ServerSentEvents:if(!this._options.EventSource)throw new Error("'EventSource' is not supported in your environment.");return new Je(this._httpClient,this._accessTokenFactory,this._logger,this._options.logMessageContent||!1,this._options.EventSource,this._options.withCredentials,this._options.headers||{});case Se.LongPolling:return new qe(this._httpClient,this._accessTokenFactory,this._logger,this._options.logMessageContent||!1,this._options.withCredentials,this._options.headers||{});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=Se[e.transport];if(null==r)return this._logger.log(Ee.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(Ee.Debug,`Skipping transport '${Se[r]}' because it was disabled by the client.`),new Error(`'${Se[r]}' is disabled by the client.`);if(!(e.transferFormats.map((e=>Ce[e])).indexOf(n)>=0))return this._logger.log(Ee.Debug,`Skipping transport '${Se[r]}' because it does not support the requested transfer format '${Ce[n]}'.`),new Error(`'${Se[r]}' does not support ${Ce[n]}.`);if(r===Se.WebSockets&&!this._options.WebSocket||r===Se.ServerSentEvents&&!this._options.EventSource)return this._logger.log(Ee.Debug,`Skipping transport '${Se[r]}' because it is not supported in your environment.'`),new Error(`'${Se[r]}' is not supported in your environment.`);this._logger.log(Ee.Debug,`Selecting transport '${Se[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(Ee.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(Ee.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(Ee.Error,`Connection disconnected with error '${e}'.`):this._logger.log(Ee.Information,"Connection disconnected."),this._sendQueue&&(this._sendQueue.stop().catch((e=>{this._logger.log(Ee.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(Ee.Error,`HttpConnection.onclose(${e}) threw error '${t}'.`)}}}else this._logger.log(Ee.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(!Be.isBrowser||!window.document)throw new Error(`Cannot resolve '${e}'.`);const t=window.document.createElement("a");return t.href=e,this._logger.log(Ee.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 Xe{constructor(e){this._transport=e,this._buffer=[],this._executing=!0,this._sendBufferedData=new Ye,this._transportResult=new Ye,this._sendLoopPromise=this._sendLoop()}send(e){return this._bufferData(e),this._transportResult||(this._transportResult=new Ye),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 Ye;const e=this._transportResult;this._transportResult=void 0;const t="string"==typeof this._buffer[0]?this._buffer.join(""):Xe._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 Ye{constructor(){this.promise=new Promise(((e,t)=>[this._resolver,this._rejecter]=[e,t]))}resolve(){this._resolver()}reject(e){this._rejecter(e)}}class Ge{static write(e){return`${e}${Ge.RecordSeparator}`}static parse(e){if(e[e.length-1]!==Ge.RecordSeparator)throw new Error("Message is incomplete.");const t=e.split(Ge.RecordSeparator);return t.pop(),t}}Ge.RecordSeparatorCode=30,Ge.RecordSeparator=String.fromCharCode(Ge.RecordSeparatorCode);class Qe{writeHandshakeRequest(e){return Ge.write(JSON.stringify(e))}parseHandshakeResponse(e){let t,n;if(Le(e)){const r=new Uint8Array(e),o=r.indexOf(Ge.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(Ge.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=Ge.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"}(Ie||(Ie={}));class Ze{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 He(this,e)}}!function(e){e.Disconnected="Disconnected",e.Connecting="Connecting",e.Connected="Connected",e.Disconnecting="Disconnecting",e.Reconnecting="Reconnecting"}(ke||(ke={}));class et{constructor(e,t,n,r){this._nextKeepAlive=0,Ne.isRequired(e,"connection"),Ne.isRequired(t,"logger"),Ne.isRequired(n,"protocol"),this.serverTimeoutInMilliseconds=3e4,this.keepAliveIntervalInMilliseconds=15e3,this._logger=t,this._protocol=n,this.connection=e,this._reconnectPolicy=r,this._handshakeProtocol=new Qe,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=ke.Disconnected,this._connectionStarted=!1,this._cachedPingMessage=this._protocol.writeMessage({type:Ie.Ping})}static create(e,t,n,r){return new et(e,t,n,r)}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!==ke.Disconnected&&this._connectionState!==ke.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!==ke.Disconnected)return Promise.reject(new Error("Cannot start a HubConnection that is not in the 'Disconnected' state."));this._connectionState=ke.Connecting,this._logger.log(Ee.Debug,"Starting HubConnection.");try{await this._startInternal(),this._connectionState=ke.Connected,this._connectionStarted=!0,this._logger.log(Ee.Debug,"HubConnection connected successfully.")}catch(e){return this._connectionState=ke.Disconnected,this._logger.log(Ee.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(Ee.Debug,"Sending handshake request."),await this._sendMessage(this._handshakeProtocol.writeHandshakeRequest(t)),this._logger.log(Ee.Information,`Using HubProtocol '${this._protocol.name}'.`),this._cleanupTimeout(),this._resetTimeoutPeriod(),this._resetKeepAliveInterval(),await e,this._stopDuringStartError)throw this._stopDuringStartError}catch(e){throw this._logger.log(Ee.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){return this._connectionState===ke.Disconnected?(this._logger.log(Ee.Debug,`Call to HubConnection.stop(${e}) ignored because it is already in the disconnected state.`),Promise.resolve()):this._connectionState===ke.Disconnecting?(this._logger.log(Ee.Debug,`Call to HttpConnection.stop(${e}) ignored because the connection is already in the disconnecting state.`),this._stopPromise):(this._connectionState=ke.Disconnecting,this._logger.log(Ee.Debug,"Stopping HubConnection."),this._reconnectDelayHandle?(this._logger.log(Ee.Debug,"Connection stopped during reconnect delay. Done reconnecting."),clearTimeout(this._reconnectDelayHandle),this._reconnectDelayHandle=void 0,this._completeClose(),Promise.resolve()):(this._cleanupTimeout(),this._cleanupPingTimer(),this._stopDuringStartError=e||new Error("The connection was stopped before the hub handshake could complete."),this.connection.stop(e)))}stream(e,...t){const[n,r]=this._replaceStreamingParams(t),o=this._createStreamInvocation(e,t,r);let i;const s=new Ze;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===Ie.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===Ie.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 Ie.Invocation:this._invokeClientMethod(e);break;case Ie.StreamItem:case Ie.Completion:{const t=this._callbacks[e.invocationId];t&&(e.type===Ie.Completion&&delete this._callbacks[e.invocationId],t(e));break}case Ie.Ping:break;case Ie.Close:{this._logger.log(Ee.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(Ee.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(Ee.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(Ee.Error,e);const n=new Error(e);throw this._handshakeRejecter(n),n}return this._logger.log(Ee.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===ke.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."))}_invokeClientMethod(e){const t=this._methods[e.target.toLowerCase()];if(t){try{t.forEach((t=>t.apply(this,e.arguments)))}catch(t){this._logger.log(Ee.Error,`A callback for the method ${e.target.toLowerCase()} threw error '${t}'.`)}if(e.invocationId){const e="Server requested a response, which is not supported in this version of the client.";this._logger.log(Ee.Error,e),this._stopPromise=this._stopInternal(new Error(e))}}else this._logger.log(Ee.Warning,`No client method with the name '${e.target}' found.`)}_connectionClosed(e){this._logger.log(Ee.Debug,`HubConnection.connectionClosed(${e}) called while in state ${this._connectionState}.`),this._stopDuringStartError=this._stopDuringStartError||e||new Error("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===ke.Disconnecting?this._completeClose(e):this._connectionState===ke.Connected&&this._reconnectPolicy?this._reconnect(e):this._connectionState===ke.Connected&&this._completeClose(e)}_completeClose(e){if(this._connectionStarted){this._connectionState=ke.Disconnected,this._connectionStarted=!1;try{this._closedCallbacks.forEach((t=>t.apply(this,[e])))}catch(t){this._logger.log(Ee.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(Ee.Debug,"Connection not reconnecting because the IRetryPolicy returned null on the first reconnect attempt."),void this._completeClose(e);if(this._connectionState=ke.Reconnecting,e?this._logger.log(Ee.Information,`Connection reconnecting because of error '${e}'.`):this._logger.log(Ee.Information,"Connection reconnecting."),0!==this._reconnectingCallbacks.length){try{this._reconnectingCallbacks.forEach((t=>t.apply(this,[e])))}catch(t){this._logger.log(Ee.Error,`An onreconnecting callback called with error '${e}' threw error '${t}'.`)}if(this._connectionState!==ke.Reconnecting)return void this._logger.log(Ee.Debug,"Connection left the reconnecting state in onreconnecting callback. Done reconnecting.")}for(;null!==o;){if(this._logger.log(Ee.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!==ke.Reconnecting)return void this._logger.log(Ee.Debug,"Connection left the reconnecting state during reconnect delay. Done reconnecting.");try{if(await this._startInternal(),this._connectionState=ke.Connected,this._logger.log(Ee.Information,"HubConnection reconnected successfully."),0!==this._reconnectedCallbacks.length)try{this._reconnectedCallbacks.forEach((e=>e.apply(this,[this.connection.connectionId])))}catch(e){this._logger.log(Ee.Error,`An onreconnected callback called with connectionId '${this.connection.connectionId}; threw error '${e}'.`)}return}catch(e){if(this._logger.log(Ee.Information,`Reconnect attempt failed because of error '${e}'.`),this._connectionState!==ke.Reconnecting)return this._logger.log(Ee.Debug,`Connection moved to the '${this._connectionState}' from the reconnecting state during reconnect attempt. Done reconnecting.`),void(this._connectionState===ke.Disconnecting&&this._completeClose());r=e instanceof Error?e:new Error(e.toString()),o=this._getNextRetryDelay(n++,Date.now()-t,r)}}this._logger.log(Ee.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(Ee.Error,`IRetryPolicy.nextRetryDelayInMilliseconds(${e}, ${t}) threw error '${n}'.`),null}}_cancelCallbacksWithError(e){const t=this._callbacks;this._callbacks={},Object.keys(t).forEach((n=>{(0,t[n])(null,e)}))}_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:Ie.Invocation}:{arguments:t,target:e,type:Ie.Invocation};{const n=this._invocationId;return this._invocationId++,0!==r.length?{arguments:t,invocationId:n.toString(),streamIds:r,target:e,type:Ie.Invocation}:{arguments:t,invocationId:n.toString(),target:e,type:Ie.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 ut=ot?new TextDecoder:null,dt=ot?"undefined"!=typeof process&&"force"!==process.env.TEXT_DECODER?200:0:it,pt=function(e,t){this.type=e,this.data=t};function ft(e,t,n){var r=Math.floor(n/4294967296),o=n;e.setUint32(t,r),e.setUint32(t+4,o)}function gt(e,t){return 4294967296*e.getInt32(t)+e.getUint32(t+4)}var mt={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),ft(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:gt(t,4),nsec:t.getUint32(0)};default:throw new Error("Unrecognized data size for timestamp: "+e.length)}}(e);return new Date(1e3*t.sec+t.nsec/1e6)}},yt=function(){function e(){this.builtInEncoders=[],this.builtInDecoders=[],this.encoders=[],this.decoders=[],this.register(mt)}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 "+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: "+e+" bytes in UTF-8");this.writeU8(219),this.writeU32(e)}},e.prototype.encodeString=function(e){if(e.length>ct){var t=st(e);this.ensureBufferSizeToWrite(5+t),this.writeStringHeader(t),lt(e,this.bytes,this.pos),this.pos+=t}else t=st(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: "+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: "+t);this.writeU8(198),this.writeU32(t)}var n=wt(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: "+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=ht(e,t,n),i=Uint8Array.prototype.slice.call(e,t,t+n);return this.store(i,o),o},e}(),Tt=(_t=function(e,t){return(_t=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])})(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}_t(e,t),e.prototype=null===t?Object.create(t):(n.prototype=t.prototype,new n)}),xt=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]1||a(e,t)}))})}function a(e,t){try{(n=o[e](t)).value instanceof Rt?Promise.resolve(n.value.v).then(c,l):h(i[0][2],n)}catch(e){h(i[0][3],e)}var n}function c(e){a("next",e)}function l(e){a("throw",e)}function h(e,t){e(t),i.shift(),i.length&&a(i[0][0],i[0][1])}},Ut=new DataView(new ArrayBuffer(0)),At=new Uint8Array(Ut.buffer),Nt=function(){try{Ut.getInt8(0)}catch(e){return e.constructor}throw new Error("never reached")}(),Bt=new Nt("Insufficient data"),$t=4294967295,Lt=new kt,Mt=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 Tt(t,e),t}(Error),Ht=function(){function e(e,t,n,r,o,i,s,a){void 0===e&&(e=yt.defaultCodec),void 0===t&&(t=void 0),void 0===n&&(n=$t),void 0===r&&(r=$t),void 0===o&&(o=$t),void 0===i&&(i=$t),void 0===s&&(s=$t),void 0===a&&(a=Lt),this.extensionCodec=e,this.context=t,this.maxStrLength=n,this.maxBinLength=r,this.maxArrayLength=o,this.maxMapLength=i,this.maxExtLength=s,this.keyDecoder=a,this.totalPos=0,this.pos=0,this.view=Ut,this.bytes=At,this.headByte=-1,this.stack=[]}return e.prototype.reinitializeState=function(){this.totalPos=0,this.headByte=-1,this.stack.length=0},e.prototype.setBuffer=function(e){this.bytes=wt(e),this.view=function(e){if(e instanceof ArrayBuffer)return new DataView(e);var t=wt(e);return new DataView(t.buffer,t.byteOffset,t.byteLength)}(this.bytes),this.pos=0},e.prototype.appendBuffer=function(e){if(-1!==this.headByte||this.hasRemaining()){var t=this.bytes.subarray(this.pos),n=wt(e),r=new Uint8Array(t.length+n.length);r.set(t),r.set(n,t.length),this.setBuffer(r)}else this.setBuffer(e)},e.prototype.hasRemaining=function(e){return void 0===e&&(e=1),this.view.byteLength-this.pos>=e},e.prototype.createExtraByteError=function(e){var t=this.view,n=this.pos;return new RangeError("Extra "+(t.byteLength-n)+" of "+t.byteLength+" byte(s) found at buffer["+e+"]")},e.prototype.decode=function(e){this.reinitializeState(),this.setBuffer(e);var t=this.doDecodeSync();if(this.hasRemaining())throw this.createExtraByteError(this.pos);return t},e.prototype.decodeMulti=function(e){return xt(this,(function(t){switch(t.label){case 0:this.reinitializeState(),this.setBuffer(e),t.label=1;case 1:return this.hasRemaining()?[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,u,d;return xt(this,(function(p){switch(p.label){case 0:i=!1,p.label=1;case 1:p.trys.push([1,6,7,12]),t=Dt(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 Nt))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())throw this.createExtraByteError(this.totalPos);return[2,s]}throw h=(l=this).headByte,u=l.pos,d=l.totalPos,new RangeError("Insufficient data in parsing "+bt(h)+" at "+d+" ("+u+" 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 Pt(this,arguments,(function(){var n,r,o,i,s,a,c,l,h;return xt(this,(function(u){switch(u.label){case 0:n=t,r=-1,u.label=1;case 1:u.trys.push([1,13,14,19]),o=Dt(e),u.label=2;case 2:return[4,Rt(o.next())];case 3:if((i=u.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()),u.label=4;case 4:u.trys.push([4,9,,10]),u.label=5;case 5:return[4,Rt(this.doDecodeSync())];case 6:return[4,u.sent()];case 7:return u.sent(),0==--r?[3,8]:[3,5];case 8:return[3,10];case 9:if(!((a=u.sent())instanceof Nt))throw a;return[3,10];case 10:this.totalPos+=this.pos,u.label=11;case 11:return[3,2];case 12:return[3,19];case 13:return c=u.sent(),l={error:c},[3,19];case 14:return u.trys.push([14,,17,18]),i&&!i.done&&(h=o.return)?[4,Rt(h.call(o))]:[3,16];case 15:u.sent(),u.label=16;case 16:return[3,18];case 17:if(l)throw l.error;return[7];case 18:return[7];case 19:return[2]}}))}))},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 Mt("Unrecognized type byte: "+bt(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 Mt("The type of key must be string or number but "+typeof t);if("__proto__"===t)throw new Mt("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 Mt("Unrecognized array type byte: "+bt(e))}},e.prototype.pushMapState=function(e){if(e>this.maxMapLength)throw new Mt("Max length exceeded: map length ("+e+") > maxMapLengthLength ("+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 Mt("Max length exceeded: array length ("+e+") > maxArrayLength ("+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 Mt("Max length exceeded: UTF-8 byte length ("+e+") > maxStrLength ("+this.maxStrLength+")");if(this.bytes.byteLengthdt?function(e,t,n){var r=e.subarray(t,t+n);return ut.decode(r)}(this.bytes,o,e):ht(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 Mt("Max length exceeded: bin length ("+e+") > maxBinLength ("+this.maxBinLength+")");if(!this.hasRemaining(e+t))throw Bt;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 Mt("Max length exceeded: ext length ("+e+") > maxExtLength ("+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=gt(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}();!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"}(Et||(Et={})),function(e){e[e.None=0]="None",e[e.WebSockets=1]="WebSockets",e[e.ServerSentEvents=2]="ServerSentEvents",e[e.LongPolling=4]="LongPolling"}(St||(St={})),function(e){e[e.Text=1]="Text",e[e.Binary=2]="Binary"}(Ct||(Ct={}));class Ft{constructor(){}log(e,t){}}Ft.instance=new Ft,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 Ot{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 jt=new Uint8Array([145,Et.Ping]);class Wt{constructor(e){this.name="messagepack",this.version=1,this.transferFormat=Ct.Binary,this._errorResult=1,this._voidResult=2,this._nonVoidResult=3,e=e||{},this._encoder=new vt(e.extensionCodec,e.context,e.maxDepth,e.initialBufferSize,e.sortKeys,e.forceFloat32,e.ignoreUndefined,e.forceIntegerToFloat),this._decoder=new Ht(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=Ft.instance);const r=Ot.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 Et.Invocation:return this._writeInvocation(e);case Et.StreamInvocation:return this._writeStreamInvocation(e);case Et.StreamItem:return this._writeStreamItem(e);case Et.Completion:return this._writeCompletion(e);case Et.Ping:return Ot.write(jt);case Et.CancelInvocation:return this._writeCancelInvocation(e);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 Et.Invocation:return this._createInvocationMessage(this._readHeaders(n),n);case Et.StreamItem:return this._createStreamItemMessage(this._readHeaders(n),n);case Et.Completion:return this._createCompletionMessage(this._readHeaders(n),n);case Et.Ping:return this._createPingMessage(n);case Et.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:Et.Close}}_createPingMessage(e){if(e.length<1)throw new Error("Invalid payload for Ping message.");return{type:Et.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:Et.Invocation}:{arguments:t[4],headers:e,streamIds:[],target:t[3],type:Et.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:Et.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:Et.Completion}}_writeInvocation(e){let t;return t=e.streamIds?this._encoder.encode([Et.Invocation,e.headers||{},e.invocationId||null,e.target,e.arguments,e.streamIds]):this._encoder.encode([Et.Invocation,e.headers||{},e.invocationId||null,e.target,e.arguments]),Ot.write(t.slice())}_writeStreamInvocation(e){let t;return t=e.streamIds?this._encoder.encode([Et.StreamInvocation,e.headers||{},e.invocationId,e.target,e.arguments,e.streamIds]):this._encoder.encode([Et.StreamInvocation,e.headers||{},e.invocationId,e.target,e.arguments]),Ot.write(t.slice())}_writeStreamItem(e){const t=this._encoder.encode([Et.StreamItem,e.headers||{},e.invocationId,e.item]);return Ot.write(t.slice())}_writeCompletion(e){const t=e.error?this._errorResult:e.result?this._nonVoidResult:this._voidResult;let n;switch(t){case this._errorResult:n=this._encoder.encode([Et.Completion,e.headers||{},e.invocationId,t,e.error]);break;case this._voidResult:n=this._encoder.encode([Et.Completion,e.headers||{},e.invocationId,t]);break;case this._nonVoidResult:n=this._encoder.encode([Et.Completion,e.headers||{},e.invocationId,t,e.result])}return Ot.write(n.slice())}_writeCancelInvocation(e){const t=this._encoder.encode([Et.CancelInvocation,e.headers||{},e.invocationId]);return Ot.write(t.slice())}_readHeaders(e){const t=e[1];if("object"!=typeof t)throw new Error("Invalid headers.");return t}}let zt=!1;const qt="function"==typeof TextDecoder?new TextDecoder("utf-8"):null,Jt=qt?qt.decode.bind(qt):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("")},Kt=Math.pow(2,32),Vt=Math.pow(2,21)-1;function Xt(e,t){return e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24}function Yt(e,t){return e[t]+(e[t+1]<<8)+(e[t+2]<<16)+(e[t+3]<<24>>>0)}function Gt(e,t){const n=Yt(e,t+4);if(n>Vt)throw new Error(`Cannot read uint64 with high order part ${n}, because the result would exceed Number.MAX_SAFE_INTEGER.`);return n*Kt+Yt(e,t)}class Qt{constructor(e){this.batchData=e;const t=new nn(e);this.arrayRangeReader=new rn(e),this.arrayBuilderSegmentReader=new on(e),this.diffReader=new Zt(e),this.editReader=new en(e,t),this.frameReader=new tn(e,t)}updatedComponents(){return Xt(this.batchData,this.batchData.length-20)}referenceFrames(){return Xt(this.batchData,this.batchData.length-16)}disposedComponentIds(){return Xt(this.batchData,this.batchData.length-12)}disposedEventHandlerIds(){return Xt(this.batchData,this.batchData.length-8)}updatedComponentsEntry(e,t){const n=e+4*t;return Xt(this.batchData,n)}referenceFramesEntry(e,t){return e+20*t}disposedComponentIdsEntry(e,t){const n=e+4*t;return Xt(this.batchData,n)}disposedEventHandlerIdsEntry(e,t){const n=e+8*t;return Gt(this.batchData,n)}}class Zt{constructor(e){this.batchDataUint8=e}componentId(e){return Xt(this.batchDataUint8,e)}edits(e){return e+4}editsEntry(e,t){return e+16*t}}class en{constructor(e,t){this.batchDataUint8=e,this.stringReader=t}editType(e){return Xt(this.batchDataUint8,e)}siblingIndex(e){return Xt(this.batchDataUint8,e+4)}newTreeIndex(e){return Xt(this.batchDataUint8,e+8)}moveToSiblingIndex(e){return Xt(this.batchDataUint8,e+8)}removedAttributeName(e){const t=Xt(this.batchDataUint8,e+12);return this.stringReader.readString(t)}}class tn{constructor(e,t){this.batchDataUint8=e,this.stringReader=t}frameType(e){return Xt(this.batchDataUint8,e)}subtreeLength(e){return Xt(this.batchDataUint8,e+4)}elementReferenceCaptureId(e){const t=Xt(this.batchDataUint8,e+4);return this.stringReader.readString(t)}componentId(e){return Xt(this.batchDataUint8,e+8)}elementName(e){const t=Xt(this.batchDataUint8,e+8);return this.stringReader.readString(t)}textContent(e){const t=Xt(this.batchDataUint8,e+4);return this.stringReader.readString(t)}markupContent(e){const t=Xt(this.batchDataUint8,e+4);return this.stringReader.readString(t)}attributeName(e){const t=Xt(this.batchDataUint8,e+4);return this.stringReader.readString(t)}attributeValue(e){const t=Xt(this.batchDataUint8,e+8);return this.stringReader.readString(t)}attributeEventHandlerId(e){return Gt(this.batchDataUint8,e+12)}}class nn{constructor(e){this.batchDataUint8=e,this.stringTableStartIndex=Xt(e,e.length-4)}readString(e){if(-1===e)return null;{const n=Xt(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(sn.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(sn.Debug,`Waiting for batch ${this.nextBatchId}. Batch ${e} not processed.`);try{this.nextBatchId++,this.logger.log(sn.Debug,`Applying batch ${e}.`),function(e,t){const n=Q[e];if(!n)throw new Error(`There is no browser renderer with ID ${e}.`);const r=t.arrayRangeReader,o=t.updatedComponents(),i=r.values(o),s=r.count(o),a=t.referenceFrames(),c=r.values(a),l=t.diffReader;for(let e=0;e=this.minLevel){const n=`[${(new Date).toISOString()}] ${sn[e]}: ${t}`;switch(e){case sn.Critical:case sn.Error:console.error(n);break;case sn.Warning:console.warn(n);break;case sn.Information:console.info(n);break;default:console.log(n)}}}}class hn{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!==ke.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!==ke.Connected)return!1;const t=await e.invoke("StartCircuit",re.getBaseURI(),re.getLocationHref(),JSON.stringify(this.components.map((e=>e.toRecord()))),this.applicationState||"");return!!t&&(this.initialize(t),!0)}resolveElement(e){const t=Number.parseInt(e);if(Number.isNaN(t))throw new Error(`Invalid sequence number '${e}'.`);return function(e,t){if(!e.parentNode)throw new Error(`Comment not connected to the DOM ${e.textContent}`);const n=e.parentNode,r=k(n,!0),o=A(r);return Array.from(n.childNodes).forEach((e=>o.push(e))),e[C]=r,t&&(e[I]=t,k(t)),k(e)}(this.components[t].start,this.components[t].end)}}const un={configureSignalR:e=>{},logLevel:sn.Warning,reconnectionOptions:{maxRetries:8,retryIntervalMilliseconds:2e4,dialogId:"components-reconnect-modal"}};class dn{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.modal.innerHTML='

Alternatively, reload

',this.message=this.modal.querySelector("h5"),this.button=this.modal.querySelector("button"),this.reloadParagraph=this.modal.querySelector("p"),this.loader=this.getLoader(),this.message.after(this.loader),this.button.addEventListener("click",(async()=>{this.show();try{await(null==fe?void 0:fe.reconnect)()||this.rejected()}catch(e){this.logger.log(sn.Error,e),this.failed()}})),this.reloadParagraph.querySelector("a").addEventListener("click",(()=>location.reload()))}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",this.message.innerHTML="Reconnection failed. Try reloading the page if you're unable to reconnect.",this.message.querySelector("a").addEventListener("click",(()=>location.reload()))}rejected(){this.button.style.display="none",this.reloadParagraph.style.display="none",this.loader.style.display="none",this.message.innerHTML="Could not reconnect to the server. Reload the page to restore functionality.",this.message.querySelector("a").addEventListener("click",(()=>location.reload()))}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 pn{constructor(e,t,n){this.dialog=e,this.maxRetries=t,this.document=n,this.document=n;const r=this.document.getElementById(pn.MaxRetriesId);r&&(r.innerText=this.maxRetries.toString())}show(){this.removeClasses(),this.dialog.classList.add(pn.ShowClassName)}update(e){const t=this.document.getElementById(pn.CurrentAttemptId);t&&(t.innerText=e.toString())}hide(){this.removeClasses(),this.dialog.classList.add(pn.HideClassName)}failed(){this.removeClasses(),this.dialog.classList.add(pn.FailedClassName)}rejected(){this.removeClasses(),this.dialog.classList.add(pn.RejectedClassName)}removeClasses(){this.dialog.classList.remove(pn.ShowClassName,pn.HideClassName,pn.FailedClassName,pn.RejectedClassName)}}pn.ShowClassName="components-reconnect-show",pn.HideClassName="components-reconnect-hide",pn.FailedClassName="components-reconnect-failed",pn.RejectedClassName="components-reconnect-rejected",pn.MaxRetriesId="components-reconnect-max-retries",pn.CurrentAttemptId="components-reconnect-current-attempt";class fn{constructor(e,t,n){this._currentReconnectionProcess=null,this._logger=e,this._reconnectionDisplay=t,this._reconnectCallback=n||(()=>fe.reconnect())}onConnectionDown(e,t){if(!this._reconnectionDisplay){const t=document.getElementById(e.dialogId);this._reconnectionDisplay=t?new pn(t,e.maxRetries,document):new dn(e.dialogId,e.maxRetries,document,this._logger)}this._currentReconnectionProcess||(this._currentReconnectionProcess=new gn(e,this._logger,this._reconnectCallback,this._reconnectionDisplay))}onConnectionUp(){this._currentReconnectionProcess&&(this._currentReconnectionProcess.dispose(),this._currentReconnectionProcess=null)}}class gn{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;tgn.MaximumFirstRetryInterval?gn.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(sn.Error,e)}}this.reconnectDisplay.failed()}delay(e){return new Promise((t=>setTimeout(t,e)))}}gn.MaximumFirstRetryInterval=3e3;const mn=/^\s*Blazor-Component-State:(?[a-zA-Z0-9\+\/=]+)$/;function yn(e){var t;if(e.nodeType===Node.COMMENT_NODE){const n=e.textContent||"",r=mn.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 bn(e,t){const n=e.currentElement;if(n&&n.nodeType===Node.COMMENT_NODE&&n.textContent){const r=vn.exec(n.textContent),o=r&&r.groups&&r.groups.descriptor;if(!o)return;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;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.");if(c){const e=_n(c,n);if(!e)throw new Error(`Could not find an end component comment for '${t}'`);return{type:r,assembly:o,typeName:i,parameterDefinitions:s&&atob(s),parameterValues:a&&atob(a),start:t,prerenderId:c,end:e}}return{type:r,assembly:o,typeName:i,parameterDefinitions:s&&atob(s),parameterValues:a&&atob(a),start:t}}}(r,n,e);case"server":return function(e,t,n){const{type:r,descriptor:o,sequence:i,prerenderId:s}=e;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)}'`);if(s){const e=_n(s,n);if(!e)throw new Error(`Could not find an end component comment for '${t}'`);return{type:r,sequence:i,descriptor:o,start:t,prerenderId:s,end:e}}return{type:r,sequence:i,descriptor:o,start:t}}}(r,n,e)}}catch(e){throw new Error(`Found malformed component comment at ${n.textContent}`)}}}function _n(e,t){for(;t.next()&&t.currentElement;){const n=t.currentElement;if(n.nodeType!==Node.COMMENT_NODE)continue;if(!n.textContent)continue;const r=vn.exec(n.textContent),o=r&&r[1];if(o)return En(o,e),n}}function En(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 Sn{constructor(e){this.childNodes=e,this.currentIndex=-1,this.length=e.length}next(){return this.currentIndex++,this.currentIndexe.sequence-t.sequence))}(e)}(document),o=yn(document),i=new hn(r,o||""),s=await Un(t,n,i);if(!await i.startCircuit(s))return void n.log(sn.Error,"Failed to start the circuit.");let a=!1;const c=()=>{if(!a){const e=new FormData,t=i.circuitId;e.append("circuitId",t),a=navigator.sendBeacon("_blazor/disconnect",e)}};fe.disconnect=c,window.addEventListener("unload",c,{capture:!1,once:!0}),fe.reconnect=async e=>{if(Dn)return!1;const r=e||await Un(t,n,i);return await i.reconnect(r)?(t.reconnectionHandler.onConnectionUp(),!0):(n.log(sn.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)},n.log(sn.Information,"Blazor server-side application started.")}async function Un(t,n,r){const i=new Wt;i.name="blazorpack";const s=(new rt).withUrl("_blazor").withHubProtocol(i);t.configureSignalR(s);const a=s.build();o=(e,t)=>{a.send("DispatchBrowserEvent",JSON.stringify(e),JSON.stringify(t))},fe._internal.navigationManager.listenForNavigationEvents(((e,t)=>a.send("OnLocationChanged",e,t))),a.on("JS.AttachComponent",((e,t)=>function(e,t,n){let r=Q[0];r||(r=Q[0]=new V(0)),r.attachRootComponentToLogicalElement(n,t)}(0,r.resolveElement(t),e))),a.on("JS.BeginInvokeJS",e.jsCallDispatcher.beginInvokeJSFromDotNet),a.on("JS.EndInvokeDotNet",e.jsCallDispatcher.endInvokeDotNetFromJS),a.on("JS.ReceiveByteArray",e.jsCallDispatcher.receiveByteArray);const c=an.getOrCreate(n);a.on("JS.RenderBatch",((e,t)=>{n.log(sn.Debug,`Received render batch with id ${e} and ${t.byteLength} bytes.`),c.processBatch(e,t,a)})),a.onclose((e=>!Dn&&t.reconnectionHandler.onConnectionDown(t.reconnectionOptions,e))),a.on("JS.Error",(e=>{Dn=!0,An(a,e,n),async function(){let e=document.querySelector("#blazor-error-ui");e&&(e.style.display="block"),zt||(zt=!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()}})))}()})),fe._internal.forceCloseConnection=()=>a.stop();try{await a.start()}catch(e){An(a,e,n)}return e.attachDispatcher({beginInvokeDotNetFromJS:(e,t,n,r,o)=>{a.send("BeginInvokeDotNetFromJS",e?e.toString():null,t,n,r||0,o)},endInvokeJSFromDotNet:(e,t,n)=>{a.send("EndInvokeJSFromDotNet",e,t,n)},sendByteArray:(e,t)=>{a.send("ReceiveByteArray",e,t)}}),a}function An(e,t,n){n.log(sn.Error,t),e&&e.stop()}fe.start=Pn,document&&document.currentScript&&"false"!==document.currentScript.getAttribute("autostart")&&Pn()})(); \ No newline at end of file +(()=>{"use strict";var e,t,n;!function(e){window.DotNet=e;const t=[],n=new Map;class r{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 o="__jsObjectId",i={},s={0:new r(window)};s[0]._cachedFunctions.set("import",(e=>("string"==typeof e&&e.startsWith("./")&&(e=document.baseURI+e.substr(2)),import(e))));let a,c=1,l=1,h=null;function u(e){t.push(e)}function d(e){if(e&&"object"==typeof e){s[l]=new r(e);const t={[o]:l};return l++,t}throw new Error(`Cannot create a JSObjectReference from the value '${e}'.`)}function p(e){if(!(e.buffer instanceof ArrayBuffer))throw new Error(`Cannot create a JSDataReference from the value '${e}' as it is not a valid ArrayBuffer.`);if(void 0===e.byteLength)throw new Error(`Cannot create a JSDataReference from the value '${e}' as it doesn't have a byteLength.`);const t={__jsDataReferenceLength:e.byteLength};try{const n=d(e);t.__jsObjectId=n.__jsObjectId}catch{throw new Error(`Cannot create a JSDataReference from the value '${e}'.`)}return t}function f(e){return e?JSON.parse(e,((e,n)=>t.reduce(((t,n)=>n(e,t)),n))):null}function g(e,t,n,r){const o=y();if(o.invokeDotNetFromJS){const i=k(r),s=o.invokeDotNetFromJS(e,t,n,i);return s?f(s):null}throw new Error("The current dispatcher does not support synchronous calls from JS to .NET. Use invokeMethodAsync instead.")}function m(e,t,n,r){if(e&&n)throw new Error(`For instance method calls, assemblyName should be null. Received '${e}'.`);const o=c++,s=new Promise(((e,t)=>{i[o]={resolve:e,reject:t}}));try{const i=k(r);y().beginInvokeDotNetFromJS(o,e,t,n,i)}catch(e){w(o,!1,e)}return s}function y(){if(null!==h)return h;throw new Error("No .NET call dispatcher has been set.")}function w(e,t,n){if(!i.hasOwnProperty(e))throw new Error(`There is no pending async call with ID ${e}.`);const r=i[e];delete i[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){let n=s[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 s[e]}e.attachDispatcher=function(e){h=e},e.attachReviver=u,e.invokeMethod=function(e,t,...n){return g(e,t,null,n)},e.invokeMethodAsync=function(e,t,...n){return m(e,t,null,n)},e.createJSObjectReference=d,e.createJSDataReference=p,e.disposeJSObjectReference=function(e){const t=e&&e.__jsObjectId;"number"==typeof t&&_(t)},function(e){e[e.Default=0]="Default",e[e.JSObjectReference=1]="JSObjectReference",e[e.JSDataReference=2]="JSDataReference"}(a=e.JSCallResultType||(e.JSCallResultType={})),e.jsCallDispatcher={findJSFunction:b,disposeJSObjectReferenceById:_,invokeJSFromDotNet:(e,t,n,r)=>{const o=C(b(e,r).apply(null,f(t)),n);return null==o?null:k(o)},beginInvokeJSFromDotNet:(e,t,n,r,o)=>{const i=new Promise((e=>{e(b(t,o).apply(null,f(n)))}));e&&i.then((t=>y().endInvokeJSFromDotNet(e,!0,k([e,!0,C(t,r)]))),(t=>y().endInvokeJSFromDotNet(e,!1,JSON.stringify([e,!1,v(t)]))))},endInvokeDotNetFromJS:(e,t,n)=>{const r=t?f(n):new Error(n);w(parseInt(e),t,r)},receiveByteArray:(e,t)=>{n.set(e,t)}};class E{constructor(e){this._id=e}invokeMethod(e,...t){return g(null,e,this._id,t)}invokeMethodAsync(e,...t){return m(null,e,this._id,t)}dispose(){m(null,"__Dispose",this._id,null).catch((e=>console.error(e)))}serializeAsArg(){return{__dotNetObject:this._id}}}const S="__byte[]";function C(e,t){switch(t){case a.Default:return e;case a.JSObjectReference:return d(e);case a.JSDataReference:return p(e);default:throw new Error(`Invalid JS call result type '${t}'.`)}}u((function(e,t){if(t&&"object"==typeof t){if(t.hasOwnProperty("__dotNetObject"))return new E(t.__dotNetObject);if(t.hasOwnProperty(o)){const e=t.__jsObjectId,n=s[e];if(n)return n.getWrappedObject();throw new Error(`JS object instance with Id '${e}' does not exist. It may have been disposed.`)}if(t.hasOwnProperty(S)){const e=t["__byte[]"],r=n.get(e);if(void 0===r)throw new Error(`Byte array index '${e}' does not exist.`);return r}}return t}));let I=0;function k(e){return I=0,JSON.stringify(e,T)}function T(e,t){if(t instanceof E)return t.serializeAsArg();if(t instanceof Uint8Array){h.sendByteArray(I,t);const e={[S]:I};return I++,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"}(n||(n={}));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}}let o;function i(e,t){if(!o)throw new Error("eventDispatcher not initialized. Call 'setEventDispatcher' to configure it.");o(e,t)}const s=new Map,a=new Map,c={createEventArgs:()=>({})},l=[];function h(e){return s.get(e)}function u(e){const t=s.get(e);return(null==t?void 0:t.browserEventName)||e}function d(e,t){e.forEach((e=>s.set(e,t)))}function p(e){const t=[];for(let n=0;n{return{...f(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}}),d(["focus","blur","focusin","focusout"],c),d(["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};var t}}),d(["contextmenu","click","mouseover","mouseout","mousemove","mousedown","mouseup","dblclick"],{createEventArgs:e=>f(e)}),d(["error"],{createEventArgs:e=>{return{message:(t=e).message,filename:t.filename,lineno:t.lineno,colno:t.colno};var t}}),d(["loadstart","timeout","abort","load","loadend","progress"],{createEventArgs:e=>{return{lengthComputable:(t=e).lengthComputable,loaded:t.loaded,total:t.total};var t}}),d(["touchcancel","touchend","touchmove","touchenter","touchleave","touchstart"],{createEventArgs:e=>{return{detail:(t=e).detail,touches:p(t.touches),targetTouches:p(t.targetTouches),changedTouches:p(t.changedTouches),ctrlKey:t.ctrlKey,shiftKey:t.shiftKey,altKey:t.altKey,metaKey:t.metaKey,type:t.type};var t}}),d(["gotpointercapture","lostpointercapture","pointercancel","pointerdown","pointerenter","pointerleave","pointermove","pointerout","pointerover","pointerup"],{createEventArgs:e=>{return{...f(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}}),d(["wheel","mousewheel"],{createEventArgs:e=>{return{...f(t=e),deltaX:t.deltaX,deltaY:t.deltaY,deltaZ:t.deltaZ,deltaMode:t.deltaMode};var t}}),d(["toggle"],c);const g=["date","datetime-local","month","time","week"],m=E(["abort","blur","change","error","focus","load","loadend","loadstart","mouseenter","mouseleave","progress","reset","scroll","submit","unload","toggle","DOMNodeInsertedIntoDocument","DOMNodeRemovedFromDocument"]),y={submit:!0},w=E(["click","dblclick","mousedown","mousemove","mouseup"]);class v{constructor(e){this.browserRendererId=e,this.afterClickCallbacks=[];const t=++v.nextEventDelegatorId;this.eventsCollectionKey=`_blazorEvents_${t}`,this.eventInfoStore=new b(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,a.get(n));var n;t&&t.forEach((t=>this.dispatchGlobalEventToAllElements(t,e))),"click"===e.type&&this.afterClickCallbacks.forEach((t=>t(e)))}dispatchGlobalEventToAllElements(e,t){let n=t.target,o=null,s=!1;const a=m.hasOwnProperty(e);let c=!1;for(;n;){const d=this.getEventHandlerInfosForElement(n,!1);if(d){const a=d.getHandler(e);if(a&&(l=n,u=t.type,!((l instanceof HTMLButtonElement||l instanceof HTMLInputElement||l instanceof HTMLTextAreaElement||l instanceof HTMLSelectElement)&&w.hasOwnProperty(u)&&l.disabled))){if(!s){const n=h(e);o=(null==n?void 0:n.createEventArgs)?n.createEventArgs(t):{},s=!0}y.hasOwnProperty(t.type)&&t.preventDefault(),i({browserRendererId:this.browserRendererId,eventHandlerId:a.eventHandlerId,eventName:e,eventFieldInfo:r.fromEvent(a.renderingComponentId,t)},o)}d.stopPropagation(e)&&(c=!0),d.preventDefault(e)&&t.preventDefault()}n=a||c?null:n.parentElement}var l,u}getEventHandlerInfosForElement(e,t){return e.hasOwnProperty(this.eventsCollectionKey)?e[this.eventsCollectionKey]:t?e[this.eventsCollectionKey]=new _:null}}v.nextEventDelegatorId=0;class b{constructor(e){this.globalListener=e,this.infosByEventHandlerId={},this.countByEventName={},l.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=u(e),this.countByEventName.hasOwnProperty(e))this.countByEventName[e]++;else{this.countByEventName[e]=1;const t=m.hasOwnProperty(e);document.addEventListener(e,this.globalListener,t)}}update(e,t){if(this.infosByEventHandlerId.hasOwnProperty(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=u(t.eventName);0==--this.countByEventName[n]&&(delete this.countByEventName[n],document.removeEventListener(n,this.globalListener))}return t}handleEventNameAliasAdded(e,t){if(this.countByEventName.hasOwnProperty(e)){const n=this.countByEventName[e];delete this.countByEventName[e],document.removeEventListener(e,this.globalListener),this.addGlobalListener(t),this.countByEventName[t]+=n-1}}}class _{constructor(){this.handlers={},this.preventDefaultFlags=null,this.stopPropagationFlags=null}getHandler(e){return this.handlers.hasOwnProperty(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 E(e){const t={};return e.forEach((e=>{t[e]=!0})),t}const S=O("_blazorLogicalChildren"),C=O("_blazorLogicalParent"),I=O("_blazorLogicalEnd");function k(e,t){if(e.childNodes.length>0&&!t)throw new Error("New logical elements must start empty, or allowExistingContents must be true");return S in e||(e[S]=[]),e}function T(e,t){const n=document.createComment("!");return D(n,e,t),n}function D(e,t,n){const r=e;if(e instanceof Comment&&A(r)&&A(r).length>0)throw new Error("Not implemented: inserting non-empty logical container");if(R(r))throw new Error("Not implemented: moving existing logical children");const o=A(t);if(n0;)x(n,0)}const r=n;r.parentNode.removeChild(r)}function R(e){return e[C]||null}function P(e,t){return A(e)[t]}function U(e){var t=B(e);return"http://www.w3.org/2000/svg"===t.namespaceURI&&"foreignObject"!==t.tagName}function A(e){return e[S]}function N(e,t){const n=A(e);t.forEach((e=>{e.moveRangeStart=n[e.fromSiblingIndex],e.moveRangeEnd=M(e.moveRangeStart)})),t.forEach((t=>{const r=t.moveToBeforeMarker=document.createComment("marker"),o=n[t.toSiblingIndex+1];o?o.parentNode.insertBefore(r,o):L(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 B(e){if(e instanceof Element)return e;if(e instanceof Comment)return e.parentNode;throw new Error("Not a valid logical element")}function $(e){const t=A(R(e));return t[Array.prototype.indexOf.call(t,e)+1]||null}function L(e,t){if(t instanceof Element)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=$(t);n?n.parentNode.insertBefore(e,n):L(e,R(t))}}}function M(e){if(e instanceof Element)return e;const t=$(e);if(t)return t.previousSibling;{const t=R(e);return t instanceof Element?t.lastChild:M(t)}}function O(e){return"function"==typeof Symbol?Symbol():e}function H(e){return`_bl_${e}`}e.attachReviver(((e,t)=>t&&"object"==typeof t&&t.hasOwnProperty("__internalId")&&"string"==typeof t.__internalId?function(e){const t=`[${H(e)}]`;return document.querySelector(t)}(t.__internalId):t));const F="_blazorSelectValue",j=document.createElement("template"),W=document.createElementNS("http://www.w3.org/2000/svg","g"),z={},q="__internal_",J="preventDefault_",K="stopPropagation_";class V{constructor(e){this.childComponentLocations={},this.eventDelegator=new v(e),this.eventDelegator.notifyAfterClick((e=>{if(!ee)return;if(0!==e.button||function(e){return e.ctrlKey||e.shiftKey||e.altKey||e.metaKey}(e))return;if(e.defaultPrevented)return;const t=function(e){const t=!window._blazorDisableComposedPath&&e.composedPath&&e.composedPath();if(t){for(let e=0;ese(!1))))},enableNavigationInterception:function(){ee=!0},navigateTo:oe,getBaseURI:()=>document.baseURI,getLocationHref:()=>location.href};function oe(e,t,n=!1){const r=ce(e);if(!t&&he(r))ie(r,!1,n);else if(t&&location.href===e){const t=e+"?";history.replaceState(null,"",t),location.replace(e)}else n?history.replaceState(null,"",r):location.href=e}function ie(e,t,n=!1){Z=!0,n?history.replaceState(null,"",e):history.pushState(null,"",e),se(t)}async function se(e){ne&&await ne(location.href,e)}let ae;function ce(e){return ae=ae||document.createElement("a"),ae.href=e,ae.href}function le(e,t){return e?e.tagName===t?e:le(e.parentElement,t):null}function he(e){const t=(n=document.baseURI).substr(0,n.lastIndexOf("/")+1);var n;return e.startsWith(t)}const ue={init:function(e,t,n,r=50){const o=pe(t);(o||document.documentElement).style.overflowAnchor="none";const i=new IntersectionObserver((function(r){r.forEach((r=>{var o;if(!r.isIntersecting)return;const i=t.getBoundingClientRect(),s=n.getBoundingClientRect().top-i.bottom,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`});i.observe(t),i.observe(n);const s=c(t),a=c(n);function c(e){const t=new MutationObserver((()=>{i.unobserve(e),i.observe(e)}));return t.observe(e,{attributes:!0}),t}de[e._id]={intersectionObserver:i,mutationObserverBefore:s,mutationObserverAfter:a}},dispose:function(e){const t=de[e._id];t&&(t.intersectionObserver.disconnect(),t.mutationObserverBefore.disconnect(),t.mutationObserverAfter.disconnect(),e.dispose(),delete de[e._id])}},de={};function pe(e){return e?"visible"!==getComputedStyle(e).overflowY?e:pe(e.parentElement):null}const fe={navigateTo:oe,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=a.get(t.browserEventName);n?n.push(e):a.set(t.browserEventName,[e]),l.forEach((n=>n(e,t.browserEventName)))}s.set(e,t)},_internal:{navigationManager:re,domWrapper:{focus:function(e,t){if(!(e instanceof HTMLElement))throw new Error("Unable to focus an invalid element.");e.focus({preventScroll:t})},focusBySelector:function(e){const t=document.querySelector(e);t&&(t.hasAttribute("tabindex")||(t.tabIndex=-1),t.focus())}},Virtualize:ue}};window.Blazor=fe;const ge=[0,2e3,1e4,3e4,null];class me{constructor(e){this._retryDelays=void 0!==e?[...e,null]:ge}nextRetryDelayInMilliseconds(e){return this._retryDelays[e.previousRetryCount]}}class ye extends Error{constructor(e,t){const n=new.target.prototype;super(`${e}: Status code '${t}'`),this.statusCode=t,this.__proto__=n}}class we extends Error{constructor(e="A timeout occurred."){const t=new.target.prototype;super(e),this.__proto__=t}}class ve extends Error{constructor(e="An abort occurred."){const t=new.target.prototype;super(e),this.__proto__=t}}class be{constructor(e,t,n){this.statusCode=e,this.statusText=t,this.content=n}}class _e{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""}}var Ee,Se,Ce,Ie,ke;!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"}(Ee||(Ee={}));class Te extends _e{constructor(e){if(super(),this._logger=e,"undefined"==typeof fetch){const e=require;this._jar=new(e("tough-cookie").CookieJar),this._fetchType=e("node-fetch"),this._fetchType=e("fetch-cookie")(this._fetchType,this._jar),this._abortControllerType=e("abort-controller")}else this._fetchType=fetch.bind(self),this._abortControllerType=AbortController}async send(e){if(e.abortSignal&&e.abortSignal.aborted)throw new ve;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 ve});let r,o=null;if(e.timeout){const r=e.timeout;o=setTimeout((()=>{t.abort(),this._logger.log(Ee.Warning,"Timeout from HTTP request."),n=new we}),r)}try{r=await this._fetchType(e.url,{body:e.content,cache:"no-cache",credentials:!0===e.withCredentials?"include":"same-origin",headers:{"Content-Type":"text/plain;charset=UTF-8","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(Ee.Warning,`Error from HTTP request. ${e}.`),e}finally{o&&clearTimeout(o),e.abortSignal&&(e.abortSignal.onabort=null)}if(!r.ok){const e=await De(r,"text");throw new ye(e||r.statusText,r.status)}const i=De(r,e.responseType),s=await i;return new be(r.status,r.statusText,s)}getCookieString(e){return""}}function De(e,t){let n;switch(t){case"arraybuffer":n=e.arrayBuffer();break;case"text":n=e.text();break;case"blob":case"document":case"json":throw new Error(`${t} is not supported.`);default:n=e.text()}return n}class xe extends _e{constructor(e){super(),this._logger=e}send(e){return e.abortSignal&&e.abortSignal.aborted?Promise.reject(new ve):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"),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 ve)}),e.timeout&&(r.timeout=e.timeout),r.onload=()=>{e.abortSignal&&(e.abortSignal.onabort=null),r.status>=200&&r.status<300?t(new be(r.status,r.statusText,r.response||r.responseText)):n(new ye(r.response||r.responseText||r.statusText,r.status))},r.onerror=()=>{this._logger.log(Ee.Warning,`Error from HTTP request. ${r.status}: ${r.statusText}.`),n(new ye(r.statusText,r.status))},r.ontimeout=()=>{this._logger.log(Ee.Warning,"Timeout from HTTP request."),n(new we)},r.send(e.content||"")})):Promise.reject(new Error("No url defined.")):Promise.reject(new Error("No method defined."))}}class Re extends _e{constructor(e){if(super(),"undefined"!=typeof fetch)this._httpClient=new Te(e);else{if("undefined"==typeof XMLHttpRequest)throw new Error("No usable HttpClient found.");this._httpClient=new xe(e)}}send(e){return e.abortSignal&&e.abortSignal.aborted?Promise.reject(new ve):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)}}class Pe{}Pe.Authorization="Authorization",Pe.Cookie="Cookie",function(e){e[e.None=0]="None",e[e.WebSockets=1]="WebSockets",e[e.ServerSentEvents=2]="ServerSentEvents",e[e.LongPolling=4]="LongPolling"}(Se||(Se={})),function(e){e[e.Text=1]="Text",e[e.Binary=2]="Binary"}(Ce||(Ce={}));class Ue{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 Ae{constructor(){}log(e,t){}}Ae.instance=new Ae;class Ne{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 Be{static get isBrowser(){return"object"==typeof window}static get isWebWorker(){return"object"==typeof self&&"importScripts"in self}static get isNode(){return!this.isBrowser&&!this.isWebWorker}}function $e(e,t){let n="";return Le(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 Le(e){return e&&"undefined"!=typeof ArrayBuffer&&(e instanceof ArrayBuffer||e.constructor&&"ArrayBuffer"===e.constructor.name)}async function Me(e,t,n,r,o,i,s,a,c){let l={};if(o){const e=await o();e&&(l={Authorization:`Bearer ${e}`})}const[h,u]=Fe();l[h]=u,e.log(Ee.Trace,`(${t} transport) sending data. ${$e(i,s)}.`);const d=Le(i)?"arraybuffer":"text",p=await n.post(r,{content:i,headers:{...l,...c},responseType:d,withCredentials:a});e.log(Ee.Trace,`(${t} transport) request complete. Response status: ${p.statusCode}.`)}class Oe{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 He{constructor(e){this._minLevel=e,this.out=console}log(e,t){if(e>=this._minLevel){const n=`[${(new Date).toISOString()}] ${Ee[e]}: ${t}`;switch(e){case Ee.Critical:case Ee.Error:this.out.error(n);break;case Ee.Warning:this.out.warn(n);break;case Ee.Information:this.out.info(n);break;default:this.out.log(n)}}}}function Fe(){let e="X-SignalR-User-Agent";return Be.isNode&&(e="User-Agent"),[e,je("0.0.0-DEV_BUILD",We(),Be.isNode?"NodeJS":"Browser",ze())]}function je(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 We(){if(!Be.isNode)return"";switch(process.platform){case"win32":return"Windows NT";case"darwin":return"macOS";case"linux":return"Linux";default:return process.platform}}function ze(){if(Be.isNode)return process.versions.node}class qe{constructor(e,t,n,r,o,i){this._httpClient=e,this._accessTokenFactory=t,this._logger=n,this._pollAbort=new Ue,this._logMessageContent=r,this._withCredentials=o,this._headers=i,this._running=!1,this.onreceive=null,this.onclose=null}get pollAborted(){return this._pollAbort.aborted}async connect(e,t){if(Ne.isRequired(e,"url"),Ne.isRequired(t,"transferFormat"),Ne.isIn(t,Ce,"transferFormat"),this._url=e,this._logger.log(Ee.Trace,"(LongPolling transport) Connecting."),t===Ce.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]=Fe(),o={[n]:r,...this._headers},i={abortSignal:this._pollAbort.signal,headers:o,timeout:1e5,withCredentials:this._withCredentials};t===Ce.Binary&&(i.responseType="arraybuffer");const s=await this._getAccessToken();this._updateHeaderToken(i,s);const a=`${e}&_=${Date.now()}`;this._logger.log(Ee.Trace,`(LongPolling transport) polling: ${a}.`);const c=await this._httpClient.get(a,i);200!==c.statusCode?(this._logger.log(Ee.Error,`(LongPolling transport) Unexpected response code: ${c.statusCode}.`),this._closeError=new ye(c.statusText||"",c.statusCode),this._running=!1):this._running=!0,this._receiving=this._poll(this._url,i)}async _getAccessToken(){return this._accessTokenFactory?await this._accessTokenFactory():null}_updateHeaderToken(e,t){e.headers||(e.headers={}),t?e.headers[Pe.Authorization]=`Bearer ${t}`:e.headers[Pe.Authorization]&&delete e.headers[Pe.Authorization]}async _poll(e,t){try{for(;this._running;){const n=await this._getAccessToken();this._updateHeaderToken(t,n);try{const n=`${e}&_=${Date.now()}`;this._logger.log(Ee.Trace,`(LongPolling transport) polling: ${n}.`);const r=await this._httpClient.get(n,t);204===r.statusCode?(this._logger.log(Ee.Information,"(LongPolling transport) Poll terminated by server."),this._running=!1):200!==r.statusCode?(this._logger.log(Ee.Error,`(LongPolling transport) Unexpected response code: ${r.statusCode}.`),this._closeError=new ye(r.statusText||"",r.statusCode),this._running=!1):r.content?(this._logger.log(Ee.Trace,`(LongPolling transport) data received. ${$e(r.content,this._logMessageContent)}.`),this.onreceive&&this.onreceive(r.content)):this._logger.log(Ee.Trace,"(LongPolling transport) Poll timed out, reissuing.")}catch(e){this._running?e instanceof we?this._logger.log(Ee.Trace,"(LongPolling transport) Poll timed out, reissuing."):(this._closeError=e,this._running=!1):this._logger.log(Ee.Trace,`(LongPolling transport) Poll errored after shutdown: ${e.message}`)}}}finally{this._logger.log(Ee.Trace,"(LongPolling transport) Polling complete."),this.pollAborted||this._raiseOnClose()}}async send(e){return this._running?Me(this._logger,"LongPolling",this._httpClient,this._url,this._accessTokenFactory,e,this._logMessageContent,this._withCredentials,this._headers):Promise.reject(new Error("Cannot send until the transport is connected"))}async stop(){this._logger.log(Ee.Trace,"(LongPolling transport) Stopping polling."),this._running=!1,this._pollAbort.abort();try{await this._receiving,this._logger.log(Ee.Trace,`(LongPolling transport) sending DELETE request to ${this._url}.`);const e={},[t,n]=Fe();e[t]=n;const r={headers:{...e,...this._headers},withCredentials:this._withCredentials},o=await this._getAccessToken();this._updateHeaderToken(r,o),await this._httpClient.delete(this._url,r),this._logger.log(Ee.Trace,"(LongPolling transport) DELETE request sent.")}finally{this._logger.log(Ee.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(Ee.Trace,e),this.onclose(this._closeError)}}}class Je{constructor(e,t,n,r,o,i,s){this._httpClient=e,this._accessTokenFactory=t,this._logger=n,this._logMessageContent=r,this._withCredentials=i,this._eventSourceConstructor=o,this._headers=s,this.onreceive=null,this.onclose=null}async connect(e,t){if(Ne.isRequired(e,"url"),Ne.isRequired(t,"transferFormat"),Ne.isIn(t,Ce,"transferFormat"),this._logger.log(Ee.Trace,"(SSE transport) Connecting."),this._url=e,this._accessTokenFactory){const t=await this._accessTokenFactory();t&&(e+=(e.indexOf("?")<0?"?":"&")+`access_token=${encodeURIComponent(t)}`)}return new Promise(((n,r)=>{let o,i=!1;if(t===Ce.Text){if(Be.isBrowser||Be.isWebWorker)o=new this._eventSourceConstructor(e,{withCredentials:this._withCredentials});else{const t=this._httpClient.getCookieString(e),n={};n.Cookie=t;const[r,i]=Fe();n[r]=i,o=new this._eventSourceConstructor(e,{withCredentials:this._withCredentials,headers:{...n,...this._headers}})}try{o.onmessage=e=>{if(this.onreceive)try{this._logger.log(Ee.Trace,`(SSE transport) data received. ${$e(e.data,this._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(Ee.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?Me(this._logger,"SSE",this._httpClient,this._url,this._accessTokenFactory,e,this._logMessageContent,this._withCredentials,this._headers):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 Ke{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){if(Ne.isRequired(e,"url"),Ne.isRequired(t,"transferFormat"),Ne.isIn(t,Ce,"transferFormat"),this._logger.log(Ee.Trace,"(WebSockets transport) Connecting."),this._accessTokenFactory){const t=await this._accessTokenFactory();t&&(e+=(e.indexOf("?")<0?"?":"&")+`access_token=${encodeURIComponent(t)}`)}return new Promise(((n,r)=>{let o;e=e.replace(/^http/,"ws"),this._httpClient.getCookieString(e);let i=!1;o||(o=new this._webSocketConstructor(e)),t===Ce.Binary&&(o.binaryType="arraybuffer"),o.onopen=t=>{this._logger.log(Ee.Information,`WebSocket connected to ${e}.`),this._webSocket=o,i=!0,n()},o.onerror=e=>{let t=null;t="undefined"!=typeof ErrorEvent&&e instanceof ErrorEvent?e.error:"There was an error with the transport",this._logger.log(Ee.Information,`(WebSockets transport) ${t}.`)},o.onmessage=e=>{if(this._logger.log(Ee.Trace,`(WebSockets transport) data received. ${$e(e.data,this._logMessageContent)}.`),this.onreceive)try{this.onreceive(e.data)}catch(e){return void this._close(e)}},o.onclose=e=>{if(i)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(Ee.Trace,`(WebSockets transport) sending data. ${$e(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(Ee.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 Ve{constructor(e,t={}){var n;if(this._stopPromiseResolver=()=>{},this.features={},this._negotiateVersion=1,Ne.isRequired(e,"url"),this._logger=void 0===(n=t.logger)?new He(Ee.Information):null===n?Ae.instance:void 0!==n.log?n:new He(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,"undefined"==typeof WebSocket||t.WebSocket||(t.WebSocket=WebSocket),"undefined"==typeof EventSource||t.EventSource||(t.EventSource=EventSource),this._httpClient=t.httpClient||new Re(this._logger),this._connectionState="Disconnected",this._connectionStarted=!1,this._options=t,this.onreceive=null,this.onclose=null}async start(e){if(e=e||Ce.Binary,Ne.isIn(e,Ce,"transferFormat"),this._logger.log(Ee.Debug,`Starting connection with transfer format '${Ce[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(Ee.Error,e),await this._stopPromise,Promise.reject(new Error(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(Ee.Error,e),Promise.reject(new Error(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 Xe(this.transport)),this._sendQueue.send(e))}async stop(e){return"Disconnected"===this._connectionState?(this._logger.log(Ee.Debug,`Call to HttpConnection.stop(${e}) ignored because the connection is already in the disconnected state.`),Promise.resolve()):"Disconnecting"===this._connectionState?(this._logger.log(Ee.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(Ee.Error,`HttpConnection.transport.stop() threw error '${e}'.`),this._stopConnection()}this.transport=void 0}else this._logger.log(Ee.Debug,"HttpConnection.transport is undefined in HttpConnection.stop() because start() failed.")}async _startInternal(e){let t=this.baseUrl;this._accessTokenFactory=this._options.accessTokenFactory;try{if(this._options.skipNegotiation){if(this._options.transport!==Se.WebSockets)throw new Error("Negotiation can only be skipped when using the WebSocket transport directly.");this.transport=this._constructTransport(Se.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 Error("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}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 qe&&(this.features.inherentKeepAlive=!0),"Connecting"===this._connectionState&&(this._logger.log(Ee.Debug,"The HttpConnection connected successfully."),this._connectionState="Connected")}catch(e){return this._logger.log(Ee.Error,"Failed to start the connection: "+e),this._connectionState="Disconnected",this.transport=void 0,this._stopPromiseResolver(),Promise.reject(e)}}async _getNegotiationResponse(e){const t={};if(this._accessTokenFactory){const e=await this._accessTokenFactory();e&&(t[Pe.Authorization]=`Bearer ${e}`)}const[n,r]=Fe();t[n]=r;const o=this._resolveNegotiateUrl(e);this._logger.log(Ee.Debug,`Sending negotiation request: ${o}.`);try{const e=await this._httpClient.post(o,{content:"",headers:{...t,...this._options.headers},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 ye&&404===e.statusCode&&(t+=" Either this is not a SignalR endpoint or there is a proxy blocking the connection."),this._logger.log(Ee.Error,t),Promise.reject(new Error(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(Ee.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: ${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(Ee.Error,`Failed to start the transport '${n.transport}': ${e}`),a=void 0,i.push(`${n.transport} failed: ${e}`),"Connecting"!==this._connectionState){const e="Failed to select transport before stop() was called.";return this._logger.log(Ee.Debug,e),Promise.reject(new Error(e))}}}}return i.length>0?Promise.reject(new Error(`Unable to connect to the server with any of the available transports. ${i.join(" ")}`)):Promise.reject(new Error("None of the transports supported by the client are supported by the server."))}_constructTransport(e){switch(e){case Se.WebSockets:if(!this._options.WebSocket)throw new Error("'WebSocket' is not supported in your environment.");return new Ke(this._httpClient,this._accessTokenFactory,this._logger,this._options.logMessageContent||!1,this._options.WebSocket,this._options.headers||{});case Se.ServerSentEvents:if(!this._options.EventSource)throw new Error("'EventSource' is not supported in your environment.");return new Je(this._httpClient,this._accessTokenFactory,this._logger,this._options.logMessageContent||!1,this._options.EventSource,this._options.withCredentials,this._options.headers||{});case Se.LongPolling:return new qe(this._httpClient,this._accessTokenFactory,this._logger,this._options.logMessageContent||!1,this._options.withCredentials,this._options.headers||{});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=Se[e.transport];if(null==r)return this._logger.log(Ee.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(Ee.Debug,`Skipping transport '${Se[r]}' because it was disabled by the client.`),new Error(`'${Se[r]}' is disabled by the client.`);if(!(e.transferFormats.map((e=>Ce[e])).indexOf(n)>=0))return this._logger.log(Ee.Debug,`Skipping transport '${Se[r]}' because it does not support the requested transfer format '${Ce[n]}'.`),new Error(`'${Se[r]}' does not support ${Ce[n]}.`);if(r===Se.WebSockets&&!this._options.WebSocket||r===Se.ServerSentEvents&&!this._options.EventSource)return this._logger.log(Ee.Debug,`Skipping transport '${Se[r]}' because it is not supported in your environment.'`),new Error(`'${Se[r]}' is not supported in your environment.`);this._logger.log(Ee.Debug,`Selecting transport '${Se[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(Ee.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(Ee.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(Ee.Error,`Connection disconnected with error '${e}'.`):this._logger.log(Ee.Information,"Connection disconnected."),this._sendQueue&&(this._sendQueue.stop().catch((e=>{this._logger.log(Ee.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(Ee.Error,`HttpConnection.onclose(${e}) threw error '${t}'.`)}}}else this._logger.log(Ee.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(!Be.isBrowser||!window.document)throw new Error(`Cannot resolve '${e}'.`);const t=window.document.createElement("a");return t.href=e,this._logger.log(Ee.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 Xe{constructor(e){this._transport=e,this._buffer=[],this._executing=!0,this._sendBufferedData=new Ye,this._transportResult=new Ye,this._sendLoopPromise=this._sendLoop()}send(e){return this._bufferData(e),this._transportResult||(this._transportResult=new Ye),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 Ye;const e=this._transportResult;this._transportResult=void 0;const t="string"==typeof this._buffer[0]?this._buffer.join(""):Xe._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 Ye{constructor(){this.promise=new Promise(((e,t)=>[this._resolver,this._rejecter]=[e,t]))}resolve(){this._resolver()}reject(e){this._rejecter(e)}}class Ge{static write(e){return`${e}${Ge.RecordSeparator}`}static parse(e){if(e[e.length-1]!==Ge.RecordSeparator)throw new Error("Message is incomplete.");const t=e.split(Ge.RecordSeparator);return t.pop(),t}}Ge.RecordSeparatorCode=30,Ge.RecordSeparator=String.fromCharCode(Ge.RecordSeparatorCode);class Qe{writeHandshakeRequest(e){return Ge.write(JSON.stringify(e))}parseHandshakeResponse(e){let t,n;if(Le(e)){const r=new Uint8Array(e),o=r.indexOf(Ge.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(Ge.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=Ge.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"}(Ie||(Ie={}));class Ze{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 Oe(this,e)}}!function(e){e.Disconnected="Disconnected",e.Connecting="Connecting",e.Connected="Connected",e.Disconnecting="Disconnecting",e.Reconnecting="Reconnecting"}(ke||(ke={}));class et{constructor(e,t,n,r){this._nextKeepAlive=0,Ne.isRequired(e,"connection"),Ne.isRequired(t,"logger"),Ne.isRequired(n,"protocol"),this.serverTimeoutInMilliseconds=3e4,this.keepAliveIntervalInMilliseconds=15e3,this._logger=t,this._protocol=n,this.connection=e,this._reconnectPolicy=r,this._handshakeProtocol=new Qe,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=ke.Disconnected,this._connectionStarted=!1,this._cachedPingMessage=this._protocol.writeMessage({type:Ie.Ping})}static create(e,t,n,r){return new et(e,t,n,r)}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!==ke.Disconnected&&this._connectionState!==ke.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!==ke.Disconnected)return Promise.reject(new Error("Cannot start a HubConnection that is not in the 'Disconnected' state."));this._connectionState=ke.Connecting,this._logger.log(Ee.Debug,"Starting HubConnection.");try{await this._startInternal(),this._connectionState=ke.Connected,this._connectionStarted=!0,this._logger.log(Ee.Debug,"HubConnection connected successfully.")}catch(e){return this._connectionState=ke.Disconnected,this._logger.log(Ee.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(Ee.Debug,"Sending handshake request."),await this._sendMessage(this._handshakeProtocol.writeHandshakeRequest(t)),this._logger.log(Ee.Information,`Using HubProtocol '${this._protocol.name}'.`),this._cleanupTimeout(),this._resetTimeoutPeriod(),this._resetKeepAliveInterval(),await e,this._stopDuringStartError)throw this._stopDuringStartError}catch(e){throw this._logger.log(Ee.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){return this._connectionState===ke.Disconnected?(this._logger.log(Ee.Debug,`Call to HubConnection.stop(${e}) ignored because it is already in the disconnected state.`),Promise.resolve()):this._connectionState===ke.Disconnecting?(this._logger.log(Ee.Debug,`Call to HttpConnection.stop(${e}) ignored because the connection is already in the disconnecting state.`),this._stopPromise):(this._connectionState=ke.Disconnecting,this._logger.log(Ee.Debug,"Stopping HubConnection."),this._reconnectDelayHandle?(this._logger.log(Ee.Debug,"Connection stopped during reconnect delay. Done reconnecting."),clearTimeout(this._reconnectDelayHandle),this._reconnectDelayHandle=void 0,this._completeClose(),Promise.resolve()):(this._cleanupTimeout(),this._cleanupPingTimer(),this._stopDuringStartError=e||new Error("The connection was stopped before the hub handshake could complete."),this.connection.stop(e)))}stream(e,...t){const[n,r]=this._replaceStreamingParams(t),o=this._createStreamInvocation(e,t,r);let i;const s=new Ze;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===Ie.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===Ie.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 Ie.Invocation:this._invokeClientMethod(e);break;case Ie.StreamItem:case Ie.Completion:{const t=this._callbacks[e.invocationId];t&&(e.type===Ie.Completion&&delete this._callbacks[e.invocationId],t(e));break}case Ie.Ping:break;case Ie.Close:{this._logger.log(Ee.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(Ee.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(Ee.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(Ee.Error,e);const n=new Error(e);throw this._handshakeRejecter(n),n}return this._logger.log(Ee.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===ke.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."))}_invokeClientMethod(e){const t=this._methods[e.target.toLowerCase()];if(t){try{t.forEach((t=>t.apply(this,e.arguments)))}catch(t){this._logger.log(Ee.Error,`A callback for the method ${e.target.toLowerCase()} threw error '${t}'.`)}if(e.invocationId){const e="Server requested a response, which is not supported in this version of the client.";this._logger.log(Ee.Error,e),this._stopPromise=this._stopInternal(new Error(e))}}else this._logger.log(Ee.Warning,`No client method with the name '${e.target}' found.`)}_connectionClosed(e){this._logger.log(Ee.Debug,`HubConnection.connectionClosed(${e}) called while in state ${this._connectionState}.`),this._stopDuringStartError=this._stopDuringStartError||e||new Error("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===ke.Disconnecting?this._completeClose(e):this._connectionState===ke.Connected&&this._reconnectPolicy?this._reconnect(e):this._connectionState===ke.Connected&&this._completeClose(e)}_completeClose(e){if(this._connectionStarted){this._connectionState=ke.Disconnected,this._connectionStarted=!1;try{this._closedCallbacks.forEach((t=>t.apply(this,[e])))}catch(t){this._logger.log(Ee.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(Ee.Debug,"Connection not reconnecting because the IRetryPolicy returned null on the first reconnect attempt."),void this._completeClose(e);if(this._connectionState=ke.Reconnecting,e?this._logger.log(Ee.Information,`Connection reconnecting because of error '${e}'.`):this._logger.log(Ee.Information,"Connection reconnecting."),0!==this._reconnectingCallbacks.length){try{this._reconnectingCallbacks.forEach((t=>t.apply(this,[e])))}catch(t){this._logger.log(Ee.Error,`An onreconnecting callback called with error '${e}' threw error '${t}'.`)}if(this._connectionState!==ke.Reconnecting)return void this._logger.log(Ee.Debug,"Connection left the reconnecting state in onreconnecting callback. Done reconnecting.")}for(;null!==o;){if(this._logger.log(Ee.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!==ke.Reconnecting)return void this._logger.log(Ee.Debug,"Connection left the reconnecting state during reconnect delay. Done reconnecting.");try{if(await this._startInternal(),this._connectionState=ke.Connected,this._logger.log(Ee.Information,"HubConnection reconnected successfully."),0!==this._reconnectedCallbacks.length)try{this._reconnectedCallbacks.forEach((e=>e.apply(this,[this.connection.connectionId])))}catch(e){this._logger.log(Ee.Error,`An onreconnected callback called with connectionId '${this.connection.connectionId}; threw error '${e}'.`)}return}catch(e){if(this._logger.log(Ee.Information,`Reconnect attempt failed because of error '${e}'.`),this._connectionState!==ke.Reconnecting)return this._logger.log(Ee.Debug,`Connection moved to the '${this._connectionState}' from the reconnecting state during reconnect attempt. Done reconnecting.`),void(this._connectionState===ke.Disconnecting&&this._completeClose());r=e instanceof Error?e:new Error(e.toString()),o=this._getNextRetryDelay(n++,Date.now()-t,r)}}this._logger.log(Ee.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(Ee.Error,`IRetryPolicy.nextRetryDelayInMilliseconds(${e}, ${t}) threw error '${n}'.`),null}}_cancelCallbacksWithError(e){const t=this._callbacks;this._callbacks={},Object.keys(t).forEach((n=>{(0,t[n])(null,e)}))}_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:Ie.Invocation}:{arguments:t,target:e,type:Ie.Invocation};{const n=this._invocationId;return this._invocationId++,0!==r.length?{arguments:t,invocationId:n.toString(),streamIds:r,target:e,type:Ie.Invocation}:{arguments:t,invocationId:n.toString(),target:e,type:Ie.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 ut=ot?new TextDecoder:null,dt=ot?"undefined"!=typeof process&&"force"!==process.env.TEXT_DECODER?200:0:it,pt=function(e,t){this.type=e,this.data=t};function ft(e,t,n){var r=Math.floor(n/4294967296),o=n;e.setUint32(t,r),e.setUint32(t+4,o)}function gt(e,t){return 4294967296*e.getInt32(t)+e.getUint32(t+4)}var mt={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),ft(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:gt(t,4),nsec:t.getUint32(0)};default:throw new Error("Unrecognized data size for timestamp: "+e.length)}}(e);return new Date(1e3*t.sec+t.nsec/1e6)}},yt=function(){function e(){this.builtInEncoders=[],this.builtInDecoders=[],this.encoders=[],this.decoders=[],this.register(mt)}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 "+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: "+e+" bytes in UTF-8");this.writeU8(219),this.writeU32(e)}},e.prototype.encodeString=function(e){if(e.length>ct){var t=st(e);this.ensureBufferSizeToWrite(5+t),this.writeStringHeader(t),lt(e,this.bytes,this.pos),this.pos+=t}else t=st(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: "+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: "+t);this.writeU8(198),this.writeU32(t)}var n=wt(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: "+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=ht(e,t,n),i=Uint8Array.prototype.slice.call(e,t,t+n);return this.store(i,o),o},e}(),St=(_t=function(e,t){return(_t=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])})(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}_t(e,t),e.prototype=null===t?Object.create(t):(n.prototype=t.prototype,new n)}),Ct=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]1||a(e,t)}))})}function a(e,t){try{(n=o[e](t)).value instanceof kt?Promise.resolve(n.value.v).then(c,l):h(i[0][2],n)}catch(e){h(i[0][3],e)}var n}function c(e){a("next",e)}function l(e){a("throw",e)}function h(e,t){e(t),i.shift(),i.length&&a(i[0][0],i[0][1])}},Dt=new DataView(new ArrayBuffer(0)),xt=new Uint8Array(Dt.buffer),Rt=function(){try{Dt.getInt8(0)}catch(e){return e.constructor}throw new Error("never reached")}(),Pt=new Rt("Insufficient data"),Ut=4294967295,At=new Et,Nt=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 St(t,e),t}(Error),Bt=function(){function e(e,t,n,r,o,i,s,a){void 0===e&&(e=yt.defaultCodec),void 0===t&&(t=void 0),void 0===n&&(n=Ut),void 0===r&&(r=Ut),void 0===o&&(o=Ut),void 0===i&&(i=Ut),void 0===s&&(s=Ut),void 0===a&&(a=At),this.extensionCodec=e,this.context=t,this.maxStrLength=n,this.maxBinLength=r,this.maxArrayLength=o,this.maxMapLength=i,this.maxExtLength=s,this.keyDecoder=a,this.totalPos=0,this.pos=0,this.view=Dt,this.bytes=xt,this.headByte=-1,this.stack=[]}return e.prototype.reinitializeState=function(){this.totalPos=0,this.headByte=-1,this.stack.length=0},e.prototype.setBuffer=function(e){this.bytes=wt(e),this.view=function(e){if(e instanceof ArrayBuffer)return new DataView(e);var t=wt(e);return new DataView(t.buffer,t.byteOffset,t.byteLength)}(this.bytes),this.pos=0},e.prototype.appendBuffer=function(e){if(-1!==this.headByte||this.hasRemaining()){var t=this.bytes.subarray(this.pos),n=wt(e),r=new Uint8Array(t.length+n.length);r.set(t),r.set(n,t.length),this.setBuffer(r)}else this.setBuffer(e)},e.prototype.hasRemaining=function(e){return void 0===e&&(e=1),this.view.byteLength-this.pos>=e},e.prototype.createExtraByteError=function(e){var t=this.view,n=this.pos;return new RangeError("Extra "+(t.byteLength-n)+" of "+t.byteLength+" byte(s) found at buffer["+e+"]")},e.prototype.decode=function(e){this.reinitializeState(),this.setBuffer(e);var t=this.doDecodeSync();if(this.hasRemaining())throw this.createExtraByteError(this.pos);return t},e.prototype.decodeMulti=function(e){return Ct(this,(function(t){switch(t.label){case 0:this.reinitializeState(),this.setBuffer(e),t.label=1;case 1:return this.hasRemaining()?[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,u,d;return Ct(this,(function(p){switch(p.label){case 0:i=!1,p.label=1;case 1:p.trys.push([1,6,7,12]),t=It(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 Rt))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())throw this.createExtraByteError(this.totalPos);return[2,s]}throw h=(l=this).headByte,u=l.pos,d=l.totalPos,new RangeError("Insufficient data in parsing "+bt(h)+" at "+d+" ("+u+" 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 Tt(this,arguments,(function(){var n,r,o,i,s,a,c,l,h;return Ct(this,(function(u){switch(u.label){case 0:n=t,r=-1,u.label=1;case 1:u.trys.push([1,13,14,19]),o=It(e),u.label=2;case 2:return[4,kt(o.next())];case 3:if((i=u.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()),u.label=4;case 4:u.trys.push([4,9,,10]),u.label=5;case 5:return[4,kt(this.doDecodeSync())];case 6:return[4,u.sent()];case 7:return u.sent(),0==--r?[3,8]:[3,5];case 8:return[3,10];case 9:if(!((a=u.sent())instanceof Rt))throw a;return[3,10];case 10:this.totalPos+=this.pos,u.label=11;case 11:return[3,2];case 12:return[3,19];case 13:return c=u.sent(),l={error:c},[3,19];case 14:return u.trys.push([14,,17,18]),i&&!i.done&&(h=o.return)?[4,kt(h.call(o))]:[3,16];case 15:u.sent(),u.label=16;case 16:return[3,18];case 17:if(l)throw l.error;return[7];case 18:return[7];case 19:return[2]}}))}))},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 Nt("Unrecognized type byte: "+bt(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 Nt("The type of key must be string or number but "+typeof t);if("__proto__"===t)throw new Nt("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 Nt("Unrecognized array type byte: "+bt(e))}},e.prototype.pushMapState=function(e){if(e>this.maxMapLength)throw new Nt("Max length exceeded: map length ("+e+") > maxMapLengthLength ("+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 Nt("Max length exceeded: array length ("+e+") > maxArrayLength ("+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 Nt("Max length exceeded: UTF-8 byte length ("+e+") > maxStrLength ("+this.maxStrLength+")");if(this.bytes.byteLengthdt?function(e,t,n){var r=e.subarray(t,t+n);return ut.decode(r)}(this.bytes,o,e):ht(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 Nt("Max length exceeded: bin length ("+e+") > maxBinLength ("+this.maxBinLength+")");if(!this.hasRemaining(e+t))throw Pt;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 Nt("Max length exceeded: ext length ("+e+") > maxExtLength ("+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=gt(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 $t{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 Lt=new Uint8Array([145,Ie.Ping]);class Mt{constructor(e){this.name="messagepack",this.version=1,this.transferFormat=Ce.Binary,this._errorResult=1,this._voidResult=2,this._nonVoidResult=3,e=e||{},this._encoder=new vt(e.extensionCodec,e.context,e.maxDepth,e.initialBufferSize,e.sortKeys,e.forceFloat32,e.ignoreUndefined,e.forceIntegerToFloat),this._decoder=new Bt(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=Ae.instance);const r=$t.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 Ie.Invocation:return this._writeInvocation(e);case Ie.StreamInvocation:return this._writeStreamInvocation(e);case Ie.StreamItem:return this._writeStreamItem(e);case Ie.Completion:return this._writeCompletion(e);case Ie.Ping:return $t.write(Lt);case Ie.CancelInvocation:return this._writeCancelInvocation(e);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 Ie.Invocation:return this._createInvocationMessage(this._readHeaders(n),n);case Ie.StreamItem:return this._createStreamItemMessage(this._readHeaders(n),n);case Ie.Completion:return this._createCompletionMessage(this._readHeaders(n),n);case Ie.Ping:return this._createPingMessage(n);case Ie.Close:return this._createCloseMessage(n);default:return t.log(Ee.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:Ie.Close}}_createPingMessage(e){if(e.length<1)throw new Error("Invalid payload for Ping message.");return{type:Ie.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:Ie.Invocation}:{arguments:t[4],headers:e,streamIds:[],target:t[3],type:Ie.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:Ie.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:Ie.Completion}}_writeInvocation(e){let t;return t=e.streamIds?this._encoder.encode([Ie.Invocation,e.headers||{},e.invocationId||null,e.target,e.arguments,e.streamIds]):this._encoder.encode([Ie.Invocation,e.headers||{},e.invocationId||null,e.target,e.arguments]),$t.write(t.slice())}_writeStreamInvocation(e){let t;return t=e.streamIds?this._encoder.encode([Ie.StreamInvocation,e.headers||{},e.invocationId,e.target,e.arguments,e.streamIds]):this._encoder.encode([Ie.StreamInvocation,e.headers||{},e.invocationId,e.target,e.arguments]),$t.write(t.slice())}_writeStreamItem(e){const t=this._encoder.encode([Ie.StreamItem,e.headers||{},e.invocationId,e.item]);return $t.write(t.slice())}_writeCompletion(e){const t=e.error?this._errorResult:e.result?this._nonVoidResult:this._voidResult;let n;switch(t){case this._errorResult:n=this._encoder.encode([Ie.Completion,e.headers||{},e.invocationId,t,e.error]);break;case this._voidResult:n=this._encoder.encode([Ie.Completion,e.headers||{},e.invocationId,t]);break;case this._nonVoidResult:n=this._encoder.encode([Ie.Completion,e.headers||{},e.invocationId,t,e.result])}return $t.write(n.slice())}_writeCancelInvocation(e){const t=this._encoder.encode([Ie.CancelInvocation,e.headers||{},e.invocationId]);return $t.write(t.slice())}_readHeaders(e){const t=e[1];if("object"!=typeof t)throw new Error("Invalid headers.");return t}}let Ot=!1;const Ht="function"==typeof TextDecoder?new TextDecoder("utf-8"):null,Ft=Ht?Ht.decode.bind(Ht):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("")},jt=Math.pow(2,32),Wt=Math.pow(2,21)-1;function zt(e,t){return e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24}function qt(e,t){return e[t]+(e[t+1]<<8)+(e[t+2]<<16)+(e[t+3]<<24>>>0)}function Jt(e,t){const n=qt(e,t+4);if(n>Wt)throw new Error(`Cannot read uint64 with high order part ${n}, because the result would exceed Number.MAX_SAFE_INTEGER.`);return n*jt+qt(e,t)}class Kt{constructor(e){this.batchData=e;const t=new Gt(e);this.arrayRangeReader=new Qt(e),this.arrayBuilderSegmentReader=new Zt(e),this.diffReader=new Vt(e),this.editReader=new Xt(e,t),this.frameReader=new Yt(e,t)}updatedComponents(){return zt(this.batchData,this.batchData.length-20)}referenceFrames(){return zt(this.batchData,this.batchData.length-16)}disposedComponentIds(){return zt(this.batchData,this.batchData.length-12)}disposedEventHandlerIds(){return zt(this.batchData,this.batchData.length-8)}updatedComponentsEntry(e,t){const n=e+4*t;return zt(this.batchData,n)}referenceFramesEntry(e,t){return e+20*t}disposedComponentIdsEntry(e,t){const n=e+4*t;return zt(this.batchData,n)}disposedEventHandlerIdsEntry(e,t){const n=e+8*t;return Jt(this.batchData,n)}}class Vt{constructor(e){this.batchDataUint8=e}componentId(e){return zt(this.batchDataUint8,e)}edits(e){return e+4}editsEntry(e,t){return e+16*t}}class Xt{constructor(e,t){this.batchDataUint8=e,this.stringReader=t}editType(e){return zt(this.batchDataUint8,e)}siblingIndex(e){return zt(this.batchDataUint8,e+4)}newTreeIndex(e){return zt(this.batchDataUint8,e+8)}moveToSiblingIndex(e){return zt(this.batchDataUint8,e+8)}removedAttributeName(e){const t=zt(this.batchDataUint8,e+12);return this.stringReader.readString(t)}}class Yt{constructor(e,t){this.batchDataUint8=e,this.stringReader=t}frameType(e){return zt(this.batchDataUint8,e)}subtreeLength(e){return zt(this.batchDataUint8,e+4)}elementReferenceCaptureId(e){const t=zt(this.batchDataUint8,e+4);return this.stringReader.readString(t)}componentId(e){return zt(this.batchDataUint8,e+8)}elementName(e){const t=zt(this.batchDataUint8,e+8);return this.stringReader.readString(t)}textContent(e){const t=zt(this.batchDataUint8,e+4);return this.stringReader.readString(t)}markupContent(e){const t=zt(this.batchDataUint8,e+4);return this.stringReader.readString(t)}attributeName(e){const t=zt(this.batchDataUint8,e+4);return this.stringReader.readString(t)}attributeValue(e){const t=zt(this.batchDataUint8,e+8);return this.stringReader.readString(t)}attributeEventHandlerId(e){return Jt(this.batchDataUint8,e+12)}}class Gt{constructor(e){this.batchDataUint8=e,this.stringTableStartIndex=zt(e,e.length-4)}readString(e){if(-1===e)return null;{const n=zt(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(en.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(en.Debug,`Waiting for batch ${this.nextBatchId}. Batch ${e} not processed.`);try{this.nextBatchId++,this.logger.log(en.Debug,`Applying batch ${e}.`),function(e,t){const n=Q[e];if(!n)throw new Error(`There is no browser renderer with ID ${e}.`);const r=t.arrayRangeReader,o=t.updatedComponents(),i=r.values(o),s=r.count(o),a=t.referenceFrames(),c=r.values(a),l=t.diffReader;for(let e=0;e=this.minLevel){const n=`[${(new Date).toISOString()}] ${en[e]}: ${t}`;switch(e){case en.Critical:case en.Error:console.error(n);break;case en.Warning:console.warn(n);break;case en.Information:console.info(n);break;default:console.log(n)}}}}class on{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!==ke.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!==ke.Connected)return!1;const t=await e.invoke("StartCircuit",re.getBaseURI(),re.getLocationHref(),JSON.stringify(this.components.map((e=>e.toRecord()))),this.applicationState||"");return!!t&&(this.initialize(t),!0)}resolveElement(e){const t=Number.parseInt(e);if(Number.isNaN(t))throw new Error(`Invalid sequence number '${e}'.`);return function(e,t){if(!e.parentNode)throw new Error(`Comment not connected to the DOM ${e.textContent}`);const n=e.parentNode,r=k(n,!0),o=A(r);return Array.from(n.childNodes).forEach((e=>o.push(e))),e[C]=r,t&&(e[I]=t,k(t)),k(e)}(this.components[t].start,this.components[t].end)}}const sn={configureSignalR:e=>{},logLevel:en.Warning,reconnectionOptions:{maxRetries:8,retryIntervalMilliseconds:2e4,dialogId:"components-reconnect-modal"}};class an{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.modal.innerHTML='

Alternatively, reload

',this.message=this.modal.querySelector("h5"),this.button=this.modal.querySelector("button"),this.reloadParagraph=this.modal.querySelector("p"),this.loader=this.getLoader(),this.message.after(this.loader),this.button.addEventListener("click",(async()=>{this.show();try{await(null==fe?void 0:fe.reconnect)()||this.rejected()}catch(e){this.logger.log(en.Error,e),this.failed()}})),this.reloadParagraph.querySelector("a").addEventListener("click",(()=>location.reload()))}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",this.message.innerHTML="Reconnection failed. Try reloading the page if you're unable to reconnect.",this.message.querySelector("a").addEventListener("click",(()=>location.reload()))}rejected(){this.button.style.display="none",this.reloadParagraph.style.display="none",this.loader.style.display="none",this.message.innerHTML="Could not reconnect to the server. Reload the page to restore functionality.",this.message.querySelector("a").addEventListener("click",(()=>location.reload()))}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 cn{constructor(e,t,n){this.dialog=e,this.maxRetries=t,this.document=n,this.document=n;const r=this.document.getElementById(cn.MaxRetriesId);r&&(r.innerText=this.maxRetries.toString())}show(){this.removeClasses(),this.dialog.classList.add(cn.ShowClassName)}update(e){const t=this.document.getElementById(cn.CurrentAttemptId);t&&(t.innerText=e.toString())}hide(){this.removeClasses(),this.dialog.classList.add(cn.HideClassName)}failed(){this.removeClasses(),this.dialog.classList.add(cn.FailedClassName)}rejected(){this.removeClasses(),this.dialog.classList.add(cn.RejectedClassName)}removeClasses(){this.dialog.classList.remove(cn.ShowClassName,cn.HideClassName,cn.FailedClassName,cn.RejectedClassName)}}cn.ShowClassName="components-reconnect-show",cn.HideClassName="components-reconnect-hide",cn.FailedClassName="components-reconnect-failed",cn.RejectedClassName="components-reconnect-rejected",cn.MaxRetriesId="components-reconnect-max-retries",cn.CurrentAttemptId="components-reconnect-current-attempt";class ln{constructor(e,t,n){this._currentReconnectionProcess=null,this._logger=e,this._reconnectionDisplay=t,this._reconnectCallback=n||(()=>fe.reconnect())}onConnectionDown(e,t){if(!this._reconnectionDisplay){const t=document.getElementById(e.dialogId);this._reconnectionDisplay=t?new cn(t,e.maxRetries,document):new an(e.dialogId,e.maxRetries,document,this._logger)}this._currentReconnectionProcess||(this._currentReconnectionProcess=new hn(e,this._logger,this._reconnectCallback,this._reconnectionDisplay))}onConnectionUp(){this._currentReconnectionProcess&&(this._currentReconnectionProcess.dispose(),this._currentReconnectionProcess=null)}}class hn{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;thn.MaximumFirstRetryInterval?hn.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(en.Error,e)}}this.reconnectDisplay.failed()}delay(e){return new Promise((t=>setTimeout(t,e)))}}hn.MaximumFirstRetryInterval=3e3;const un=/^\s*Blazor-Component-State:(?[a-zA-Z0-9\+\/=]+)$/;function dn(e){var t;if(e.nodeType===Node.COMMENT_NODE){const n=e.textContent||"",r=un.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 gn(e,t){const n=e.currentElement;if(n&&n.nodeType===Node.COMMENT_NODE&&n.textContent){const r=fn.exec(n.textContent),o=r&&r.groups&&r.groups.descriptor;if(!o)return;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;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.");if(c){const e=mn(c,n);if(!e)throw new Error(`Could not find an end component comment for '${t}'`);return{type:r,assembly:o,typeName:i,parameterDefinitions:s&&atob(s),parameterValues:a&&atob(a),start:t,prerenderId:c,end:e}}return{type:r,assembly:o,typeName:i,parameterDefinitions:s&&atob(s),parameterValues:a&&atob(a),start:t}}}(r,n,e);case"server":return function(e,t,n){const{type:r,descriptor:o,sequence:i,prerenderId:s}=e;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)}'`);if(s){const e=mn(s,n);if(!e)throw new Error(`Could not find an end component comment for '${t}'`);return{type:r,sequence:i,descriptor:o,start:t,prerenderId:s,end:e}}return{type:r,sequence:i,descriptor:o,start:t}}}(r,n,e)}}catch(e){throw new Error(`Found malformed component comment at ${n.textContent}`)}}}function mn(e,t){for(;t.next()&&t.currentElement;){const n=t.currentElement;if(n.nodeType!==Node.COMMENT_NODE)continue;if(!n.textContent)continue;const r=fn.exec(n.textContent),o=r&&r[1];if(o)return yn(o,e),n}}function yn(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 wn{constructor(e){this.childNodes=e,this.currentIndex=-1,this.length=e.length}next(){return this.currentIndex++,this.currentIndexe.sequence-t.sequence))}(e)}(document),o=dn(document),i=new on(r,o||""),s=await Tn(t,n,i);if(!await i.startCircuit(s))return void n.log(en.Error,"Failed to start the circuit.");let a=!1;const c=()=>{if(!a){const e=new FormData,t=i.circuitId;e.append("circuitId",t),a=navigator.sendBeacon("_blazor/disconnect",e)}};fe.disconnect=c,window.addEventListener("unload",c,{capture:!1,once:!0}),fe.reconnect=async e=>{if(Cn)return!1;const r=e||await Tn(t,n,i);return await i.reconnect(r)?(t.reconnectionHandler.onConnectionUp(),!0):(n.log(en.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)},n.log(en.Information,"Blazor server-side application started.")}async function Tn(t,n,r){const i=new Mt;i.name="blazorpack";const s=(new rt).withUrl("_blazor").withHubProtocol(i);t.configureSignalR(s);const a=s.build();o=(e,t)=>{a.send("DispatchBrowserEvent",JSON.stringify(e),JSON.stringify(t))},fe._internal.navigationManager.listenForNavigationEvents(((e,t)=>a.send("OnLocationChanged",e,t))),a.on("JS.AttachComponent",((e,t)=>function(e,t,n){let r=Q[0];r||(r=Q[0]=new V(0)),r.attachRootComponentToLogicalElement(n,t)}(0,r.resolveElement(t),e))),a.on("JS.BeginInvokeJS",e.jsCallDispatcher.beginInvokeJSFromDotNet),a.on("JS.EndInvokeDotNet",e.jsCallDispatcher.endInvokeDotNetFromJS),a.on("JS.ReceiveByteArray",e.jsCallDispatcher.receiveByteArray);const c=tn.getOrCreate(n);a.on("JS.RenderBatch",((e,t)=>{n.log(en.Debug,`Received render batch with id ${e} and ${t.byteLength} bytes.`),c.processBatch(e,t,a)})),a.onclose((e=>!Cn&&t.reconnectionHandler.onConnectionDown(t.reconnectionOptions,e))),a.on("JS.Error",(e=>{Cn=!0,Dn(a,e,n),async function(){let e=document.querySelector("#blazor-error-ui");e&&(e.style.display="block"),Ot||(Ot=!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()}})))}()})),fe._internal.forceCloseConnection=()=>a.stop(),fe._internal.sendJSDataStream=async(e,t,n)=>{setTimeout((async()=>{let r=5,o=(new Date).valueOf();try{const i=n-512;if(i<=0)throw new Error("The chunk size must be greater than 0.");let s=0;for(;s1)await a.send("ReceiveJSDataChunk",t,c,null);else{if(!await a.invoke("ReceiveJSDataChunk",t,c,null))break;const e=(new Date).valueOf(),n=e-o;o=e,r=Math.max(1,Math.round(500/n))}s+=n}}catch(e){await a.send("ReceiveJSDataChunk",t,null,e.toString())}}),0)};try{await a.start()}catch(e){Dn(a,e,n)}return e.attachDispatcher({beginInvokeDotNetFromJS:(e,t,n,r,o)=>{a.send("BeginInvokeDotNetFromJS",e?e.toString():null,t,n,r||0,o)},endInvokeJSFromDotNet:(e,t,n)=>{a.send("EndInvokeJSFromDotNet",e,t,n)},sendByteArray:(e,t)=>{a.send("ReceiveByteArray",e,t)}}),a}function Dn(e,t,n){n.log(en.Error,t),e&&e.stop()}fe.start=kn,document&&document.currentScript&&"false"!==document.currentScript.getAttribute("autostart")&&kn()})(); \ 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 a4fff15d158e..6b6f47ef9ca0 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;!function(e){window.DotNet=e;const t=[],n=new Map;class r{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 o="__jsObjectId",a={},i={0:new r(window)};i[0]._cachedFunctions.set("import",(e=>("string"==typeof e&&e.startsWith("./")&&(e=document.baseURI+e.substr(2)),import(e))));let s,c=1,l=1,u=null;function d(e){t.push(e)}function h(e){if(e&&"object"==typeof e){i[l]=new r(e);const t={[o]:l};return l++,t}throw new Error(`Cannot create a JSObjectReference from the value '${e}'.`)}function f(e){return e?JSON.parse(e,((e,n)=>t.reduce(((t,n)=>n(e,t)),n))):null}function m(e,t,n,r){const o=v();if(o.invokeDotNetFromJS){const a=D(r),i=o.invokeDotNetFromJS(e,t,n,a);return i?f(i):null}throw new Error("The current dispatcher does not support synchronous calls from JS to .NET. Use invokeMethodAsync instead.")}function p(e,t,n,r){if(e&&n)throw new Error(`For instance method calls, assemblyName should be null. Received '${e}'.`);const o=c++,i=new Promise(((e,t)=>{a[o]={resolve:e,reject:t}}));try{const a=D(r);v().beginInvokeDotNetFromJS(o,e,t,n,a)}catch(e){g(o,!1,e)}return i}function v(){if(null!==u)return u;throw new Error("No .NET call dispatcher has been set.")}function g(e,t,n){if(!a.hasOwnProperty(e))throw new Error(`There is no pending async call with ID ${e}.`);const r=a[e];delete a[e],t?r.resolve(n):r.reject(n)}function b(e){return e instanceof Error?`${e.message}\n${e.stack}`:e?e.toString():"null"}function y(e,t){let n=i[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 i[e]}e.attachDispatcher=function(e){u=e},e.attachReviver=d,e.invokeMethod=function(e,t,...n){return m(e,t,null,n)},e.invokeMethodAsync=function(e,t,...n){return p(e,t,null,n)},e.createJSObjectReference=h,e.disposeJSObjectReference=function(e){const t=e&&e.__jsObjectId;"number"==typeof t&&E(t)},function(e){e[e.Default=0]="Default",e[e.JSObjectReference=1]="JSObjectReference"}(s=e.JSCallResultType||(e.JSCallResultType={})),e.jsCallDispatcher={findJSFunction:y,disposeJSObjectReferenceById:E,invokeJSFromDotNet:(e,t,n,r)=>{const o=S(y(e,r).apply(null,f(t)),n);return null==o?null:D(o)},beginInvokeJSFromDotNet:(e,t,n,r,o)=>{const a=new Promise((e=>{e(y(t,o).apply(null,f(n)))}));e&&a.then((t=>v().endInvokeJSFromDotNet(e,!0,D([e,!0,S(t,r)]))),(t=>v().endInvokeJSFromDotNet(e,!1,JSON.stringify([e,!1,b(t)]))))},endInvokeDotNetFromJS:(e,t,n)=>{const r=t?f(n):new Error(n);g(parseInt(e),t,r)},receiveByteArray:(e,t)=>{n.set(e,t)}};class w{constructor(e){this._id=e}invokeMethod(e,...t){return m(null,e,this._id,t)}invokeMethodAsync(e,...t){return p(null,e,this._id,t)}dispose(){p(null,"__Dispose",this._id,null).catch((e=>console.error(e)))}serializeAsArg(){return{__dotNetObject:this._id}}}const I="__byte[]";function S(e,t){switch(t){case s.Default:return e;case s.JSObjectReference:return h(e);default:throw new Error(`Invalid JS call result type '${t}'.`)}}d((function(e,t){if(t&&"object"==typeof t){if(t.hasOwnProperty("__dotNetObject"))return new w(t.__dotNetObject);if(t.hasOwnProperty(o)){const e=t.__jsObjectId,n=i[e];if(n)return n.getWrappedObject();throw new Error(`JS object instance with Id '${e}' does not exist. It may have been disposed.`)}if(t.hasOwnProperty(I)){const e=t["__byte[]"],r=n.get(e);if(void 0===r)throw new Error(`Byte array index '${e}' does not exist.`);return r}}return t}));let C=0;function D(e){return C=0,JSON.stringify(e,A)}function A(e,t){if(t instanceof w)return t.serializeAsArg();if(t instanceof Uint8Array){u.sendByteArray(C,t);const e={[I]:C};return C++,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"}(n||(n={}));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}}let o;function a(e,t){if(!o)throw new Error("eventDispatcher not initialized. Call 'setEventDispatcher' to configure it.");o(e,t)}const i=new Map,s=new Map,c={createEventArgs:()=>({})},l=[];function u(e){return i.get(e)}function d(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 f(e){const t=[];for(let n=0;n{return{...m(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"],c),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};var t}}),h(["contextmenu","click","mouseover","mouseout","mousemove","mousedown","mouseup","dblclick"],{createEventArgs:e=>m(e)}),h(["error"],{createEventArgs:e=>{return{message:(t=e).message,filename:t.filename,lineno:t.lineno,colno:t.colno};var t}}),h(["loadstart","timeout","abort","load","loadend","progress"],{createEventArgs:e=>{return{lengthComputable:(t=e).lengthComputable,loaded:t.loaded,total:t.total};var t}}),h(["touchcancel","touchend","touchmove","touchenter","touchleave","touchstart"],{createEventArgs:e=>{return{detail:(t=e).detail,touches:f(t.touches),targetTouches:f(t.targetTouches),changedTouches:f(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{...m(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{...m(t=e),deltaX:t.deltaX,deltaY:t.deltaY,deltaZ:t.deltaZ,deltaMode:t.deltaMode};var t}}),h(["toggle"],c);const p=["date","datetime-local","month","time","week"],v=I(["abort","blur","change","error","focus","load","loadend","loadstart","mouseenter","mouseleave","progress","reset","scroll","submit","unload","toggle","DOMNodeInsertedIntoDocument","DOMNodeRemovedFromDocument"]),g={submit:!0},b=I(["click","dblclick","mousedown","mousemove","mouseup"]);class y{constructor(e){this.browserRendererId=e,this.afterClickCallbacks=[];const t=++y.nextEventDelegatorId;this.eventsCollectionKey=`_blazorEvents_${t}`,this.eventInfoStore=new E(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){let n=t.target,o=null,i=!1;const s=v.hasOwnProperty(e);let c=!1;for(;n;){const h=this.getEventHandlerInfosForElement(n,!1);if(h){const s=h.getHandler(e);if(s&&(l=n,d=t.type,!((l instanceof HTMLButtonElement||l instanceof HTMLInputElement||l instanceof HTMLTextAreaElement||l instanceof HTMLSelectElement)&&b.hasOwnProperty(d)&&l.disabled))){if(!i){const n=u(e);o=(null==n?void 0:n.createEventArgs)?n.createEventArgs(t):{},i=!0}g.hasOwnProperty(t.type)&&t.preventDefault(),a({browserRendererId:this.browserRendererId,eventHandlerId:s.eventHandlerId,eventName:e,eventFieldInfo:r.fromEvent(s.renderingComponentId,t)},o)}h.stopPropagation(e)&&(c=!0),h.preventDefault(e)&&t.preventDefault()}n=s||c?null:n.parentElement}var l,d}getEventHandlerInfosForElement(e,t){return e.hasOwnProperty(this.eventsCollectionKey)?e[this.eventsCollectionKey]:t?e[this.eventsCollectionKey]=new w:null}}y.nextEventDelegatorId=0;class E{constructor(e){this.globalListener=e,this.infosByEventHandlerId={},this.countByEventName={},l.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=d(e),this.countByEventName.hasOwnProperty(e))this.countByEventName[e]++;else{this.countByEventName[e]=1;const t=v.hasOwnProperty(e);document.addEventListener(e,this.globalListener,t)}}update(e,t){if(this.infosByEventHandlerId.hasOwnProperty(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=d(t.eventName);0==--this.countByEventName[n]&&(delete this.countByEventName[n],document.removeEventListener(n,this.globalListener))}return t}handleEventNameAliasAdded(e,t){if(this.countByEventName.hasOwnProperty(e)){const n=this.countByEventName[e];delete this.countByEventName[e],document.removeEventListener(e,this.globalListener),this.addGlobalListener(t),this.countByEventName[t]+=n-1}}}class w{constructor(){this.handlers={},this.preventDefaultFlags=null,this.stopPropagationFlags=null}getHandler(e){return this.handlers.hasOwnProperty(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 I(e){const t={};return e.forEach((e=>{t[e]=!0})),t}const S=M("_blazorLogicalChildren"),C=M("_blazorLogicalParent"),D=M("_blazorLogicalEnd");function A(e,t){if(e.childNodes.length>0&&!t)throw new Error("New logical elements must start empty, or allowExistingContents must be true");return S in e||(e[S]=[]),e}function T(e,t){const n=document.createComment("!");return N(n,e,t),n}function N(e,t,n){const r=e;if(e instanceof Comment&&x(r)&&x(r).length>0)throw new Error("Not implemented: inserting non-empty logical container");if(R(r))throw new Error("Not implemented: moving existing logical children");const o=x(t);if(n0;)k(n,0)}const r=n;r.parentNode.removeChild(r)}function R(e){return e[C]||null}function F(e,t){return x(e)[t]}function _(e){var t=P(e);return"http://www.w3.org/2000/svg"===t.namespaceURI&&"foreignObject"!==t.tagName}function x(e){return e[S]}function O(e,t){const n=x(e);t.forEach((e=>{e.moveRangeStart=n[e.fromSiblingIndex],e.moveRangeEnd=H(e.moveRangeStart)})),t.forEach((t=>{const r=t.moveToBeforeMarker=document.createComment("marker"),o=n[t.toSiblingIndex+1];o?o.parentNode.insertBefore(r,o):L(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 P(e){if(e instanceof Element)return e;if(e instanceof Comment)return e.parentNode;throw new Error("Not a valid logical element")}function B(e){const t=x(R(e));return t[Array.prototype.indexOf.call(t,e)+1]||null}function L(e,t){if(t instanceof Element)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=B(t);n?n.parentNode.insertBefore(e,n):L(e,R(t))}}}function H(e){if(e instanceof Element)return e;const t=B(e);if(t)return t.previousSibling;{const t=R(e);return t instanceof Element?t.lastChild:H(t)}}function M(e){return"function"==typeof Symbol?Symbol():e}function U(e){return`_bl_${e}`}e.attachReviver(((e,t)=>t&&"object"==typeof t&&t.hasOwnProperty("__internalId")&&"string"==typeof t.__internalId?function(e){const t=`[${U(e)}]`;return document.querySelector(t)}(t.__internalId):t));const j="_blazorSelectValue",J=document.createElement("template"),$=document.createElementNS("http://www.w3.org/2000/svg","g"),K={},z="__internal_",V="preventDefault_",X="stopPropagation_";class Y{constructor(e){this.childComponentLocations={},this.eventDelegator=new y(e),this.eventDelegator.notifyAfterClick((e=>{if(!ee)return;if(0!==e.button||function(e){return e.ctrlKey||e.shiftKey||e.altKey||e.metaKey}(e))return;if(e.defaultPrevented)return;const t=function(e){const t=!window._blazorDisableComposedPath&&e.composedPath&&e.composedPath();if(t){for(let e=0;eie(!1))))},enableNavigationInterception:function(){ee=!0},navigateTo:oe,getBaseURI:()=>document.baseURI,getLocationHref:()=>location.href};function oe(e,t,n=!1){const r=ce(e);if(!t&&ue(r))ae(r,!1,n);else if(t&&location.href===e){const t=e+"?";history.replaceState(null,"",t),location.replace(e)}else n?history.replaceState(null,"",r):location.href=e}function ae(e,t,n=!1){Q=!0,n?history.replaceState(null,"",e):history.pushState(null,"",e),ie(t)}async function ie(e){ne&&await ne(location.href,e)}let se;function ce(e){return se=se||document.createElement("a"),se.href=e,se.href}function le(e,t){return e?e.tagName===t?e:le(e.parentElement,t):null}function ue(e){const t=(n=document.baseURI).substr(0,n.lastIndexOf("/")+1);var n;return e.startsWith(t)}const de={init:function(e,t,n,r=50){const o=fe(t);(o||document.documentElement).style.overflowAnchor="none";const a=new IntersectionObserver((function(r){r.forEach((r=>{var o;if(!r.isIntersecting)return;const a=t.getBoundingClientRect(),i=n.getBoundingClientRect().top-a.bottom,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`});a.observe(t),a.observe(n);const i=c(t),s=c(n);function c(e){const t=new MutationObserver((()=>{a.unobserve(e),a.observe(e)}));return t.observe(e,{attributes:!0}),t}he[e._id]={intersectionObserver:a,mutationObserverBefore:i,mutationObserverAfter:s}},dispose:function(e){const t=he[e._id];t&&(t.intersectionObserver.disconnect(),t.mutationObserverBefore.disconnect(),t.mutationObserverAfter.disconnect(),e.dispose(),delete he[e._id])}},he={};function fe(e){return e?"visible"!==getComputedStyle(e).overflowY?e:fe(e.parentElement):null}const me={navigateTo:oe,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]),l.forEach((n=>n(e,t.browserEventName)))}i.set(e,t)},_internal:{navigationManager:re,domWrapper:{focus:function(e,t){if(!(e instanceof HTMLElement))throw new Error("Unable to focus an invalid element.");e.focus({preventScroll:t})},focusBySelector:function(e){const t=document.querySelector(e);t&&(t.hasAttribute("tabindex")||(t.tabIndex=-1),t.focus())}},Virtualize:de}};window.Blazor=me;let pe=!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("")},be=Math.pow(2,32),ye=Math.pow(2,21)-1;function Ee(e,t){return e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24}function we(e,t){return e[t]+(e[t+1]<<8)+(e[t+2]<<16)+(e[t+3]<<24>>>0)}function Ie(e,t){const n=we(e,t+4);if(n>ye)throw new Error(`Cannot read uint64 with high order part ${n}, because the result would exceed Number.MAX_SAFE_INTEGER.`);return n*be+we(e,t)}class Se{constructor(e){this.batchData=e;const t=new Te(e);this.arrayRangeReader=new Ne(e),this.arrayBuilderSegmentReader=new ke(e),this.diffReader=new Ce(e),this.editReader=new De(e,t),this.frameReader=new Ae(e,t)}updatedComponents(){return Ee(this.batchData,this.batchData.length-20)}referenceFrames(){return Ee(this.batchData,this.batchData.length-16)}disposedComponentIds(){return Ee(this.batchData,this.batchData.length-12)}disposedEventHandlerIds(){return Ee(this.batchData,this.batchData.length-8)}updatedComponentsEntry(e,t){const n=e+4*t;return Ee(this.batchData,n)}referenceFramesEntry(e,t){return e+20*t}disposedComponentIdsEntry(e,t){const n=e+4*t;return Ee(this.batchData,n)}disposedEventHandlerIdsEntry(e,t){const n=e+8*t;return Ie(this.batchData,n)}}class Ce{constructor(e){this.batchDataUint8=e}componentId(e){return Ee(this.batchDataUint8,e)}edits(e){return e+4}editsEntry(e,t){return e+16*t}}class De{constructor(e,t){this.batchDataUint8=e,this.stringReader=t}editType(e){return Ee(this.batchDataUint8,e)}siblingIndex(e){return Ee(this.batchDataUint8,e+4)}newTreeIndex(e){return Ee(this.batchDataUint8,e+8)}moveToSiblingIndex(e){return Ee(this.batchDataUint8,e+8)}removedAttributeName(e){const t=Ee(this.batchDataUint8,e+12);return this.stringReader.readString(t)}}class Ae{constructor(e,t){this.batchDataUint8=e,this.stringReader=t}frameType(e){return Ee(this.batchDataUint8,e)}subtreeLength(e){return Ee(this.batchDataUint8,e+4)}elementReferenceCaptureId(e){const t=Ee(this.batchDataUint8,e+4);return this.stringReader.readString(t)}componentId(e){return Ee(this.batchDataUint8,e+8)}elementName(e){const t=Ee(this.batchDataUint8,e+8);return this.stringReader.readString(t)}textContent(e){const t=Ee(this.batchDataUint8,e+4);return this.stringReader.readString(t)}markupContent(e){const t=Ee(this.batchDataUint8,e+4);return this.stringReader.readString(t)}attributeName(e){const t=Ee(this.batchDataUint8,e+4);return this.stringReader.readString(t)}attributeValue(e){const t=Ee(this.batchDataUint8,e+8);return this.stringReader.readString(t)}attributeEventHandlerId(e){return Ie(this.batchDataUint8,e+12)}}class Te{constructor(e){this.batchDataUint8=e,this.stringTableStartIndex=Ee(e,e.length-4)}readString(e){if(-1===e)return null;{const n=Ee(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)<{!function(e,t,n){const r=document.querySelector(e);if(!r)throw new Error(`Could not find any element matching selector '${e}'.`);!function(e,t,n){let r=Z[0];r||(r=Z[0]=new Y(0)),r.attachRootComponentToLogicalElement(n,t)}(0,A(r,!0),t)}(t,e)},RenderBatch:(e,t)=>{try{const n=Me(t);(function(e,t){const n=Z[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{Fe=!0,console.error(`${e}\n${t}`),async function(){let e=document.querySelector("#blazor-error-ui");e&&(e.style.display="block"),pe||(pe=!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:e.jsCallDispatcher.beginInvokeJSFromDotNet,EndInvokeDotNet:e.jsCallDispatcher.endInvokeDotNetFromJS,SendByteArrayToJS:He,Navigate:re.navigateTo};window.external.receiveMessage((e=>{const n=function(e){if(Fe||!e||!e.startsWith(Re))return null;const t=e.substring(Re.length),[n,...r]=JSON.parse(t);return{messageType:n,args:r}}(e);if(n){if(!t.hasOwnProperty(n.messageType))throw new Error(`Unsupported IPC message type '${n.messageType}'`);t[n.messageType].apply(null,n.args)}}))}(),e.attachDispatcher({beginInvokeDotNetFromJS:xe,endInvokeJSFromDotNet:Oe,sendByteArray:Pe}),me._internal.InputFile=Ue,re.enableNavigationInterception(),re.listenForNavigationEvents(Be),Le("AttachPage",re.getBaseURI(),re.getLocationHref())}o=function(e,t){Le("DispatchBrowserEvent",e,t)},me.start=Ke,document&&document.currentScript&&"false"!==document.currentScript.getAttribute("autostart")&&Ke()})(); \ No newline at end of file +(()=>{"use strict";var e,t,n;!function(e){window.DotNet=e;const t=[],n=new Map;class r{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 o="__jsObjectId",a={},i={0:new r(window)};i[0]._cachedFunctions.set("import",(e=>("string"==typeof e&&e.startsWith("./")&&(e=document.baseURI+e.substr(2)),import(e))));let s,c=1,l=1,u=null;function d(e){t.push(e)}function h(e){if(e&&"object"==typeof e){i[l]=new r(e);const t={[o]:l};return l++,t}throw new Error(`Cannot create a JSObjectReference from the value '${e}'.`)}function f(e){if(!(e.buffer instanceof ArrayBuffer))throw new Error(`Cannot create a JSDataReference from the value '${e}' as it is not a valid ArrayBuffer.`);if(void 0===e.byteLength)throw new Error(`Cannot create a JSDataReference from the value '${e}' as it doesn't have a byteLength.`);const t={__jsDataReferenceLength:e.byteLength};try{const n=h(e);t.__jsObjectId=n.__jsObjectId}catch{throw new Error(`Cannot create a JSDataReference from the value '${e}'.`)}return t}function m(e){return e?JSON.parse(e,((e,n)=>t.reduce(((t,n)=>n(e,t)),n))):null}function p(e,t,n,r){const o=g();if(o.invokeDotNetFromJS){const a=A(r),i=o.invokeDotNetFromJS(e,t,n,a);return i?m(i):null}throw new Error("The current dispatcher does not support synchronous calls from JS to .NET. Use invokeMethodAsync instead.")}function v(e,t,n,r){if(e&&n)throw new Error(`For instance method calls, assemblyName should be null. Received '${e}'.`);const o=c++,i=new Promise(((e,t)=>{a[o]={resolve:e,reject:t}}));try{const a=A(r);g().beginInvokeDotNetFromJS(o,e,t,n,a)}catch(e){b(o,!1,e)}return i}function g(){if(null!==u)return u;throw new Error("No .NET call dispatcher has been set.")}function b(e,t,n){if(!a.hasOwnProperty(e))throw new Error(`There is no pending async call with ID ${e}.`);const r=a[e];delete a[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){let n=i[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 i[e]}e.attachDispatcher=function(e){u=e},e.attachReviver=d,e.invokeMethod=function(e,t,...n){return p(e,t,null,n)},e.invokeMethodAsync=function(e,t,...n){return v(e,t,null,n)},e.createJSObjectReference=h,e.createJSDataReference=f,e.disposeJSObjectReference=function(e){const t=e&&e.__jsObjectId;"number"==typeof t&&E(t)},function(e){e[e.Default=0]="Default",e[e.JSObjectReference=1]="JSObjectReference",e[e.JSDataReference=2]="JSDataReference"}(s=e.JSCallResultType||(e.JSCallResultType={})),e.jsCallDispatcher={findJSFunction:w,disposeJSObjectReferenceById:E,invokeJSFromDotNet:(e,t,n,r)=>{const o=D(w(e,r).apply(null,m(t)),n);return null==o?null:A(o)},beginInvokeJSFromDotNet:(e,t,n,r,o)=>{const a=new Promise((e=>{e(w(t,o).apply(null,m(n)))}));e&&a.then((t=>g().endInvokeJSFromDotNet(e,!0,A([e,!0,D(t,r)]))),(t=>g().endInvokeJSFromDotNet(e,!1,JSON.stringify([e,!1,y(t)]))))},endInvokeDotNetFromJS:(e,t,n)=>{const r=t?m(n):new Error(n);b(parseInt(e),t,r)},receiveByteArray:(e,t)=>{n.set(e,t)}};class I{constructor(e){this._id=e}invokeMethod(e,...t){return p(null,e,this._id,t)}invokeMethodAsync(e,...t){return v(null,e,this._id,t)}dispose(){v(null,"__Dispose",this._id,null).catch((e=>console.error(e)))}serializeAsArg(){return{__dotNetObject:this._id}}}const S="__byte[]";function D(e,t){switch(t){case s.Default:return e;case s.JSObjectReference:return h(e);case s.JSDataReference:return f(e);default:throw new Error(`Invalid JS call result type '${t}'.`)}}d((function(e,t){if(t&&"object"==typeof t){if(t.hasOwnProperty("__dotNetObject"))return new I(t.__dotNetObject);if(t.hasOwnProperty(o)){const e=t.__jsObjectId,n=i[e];if(n)return n.getWrappedObject();throw new Error(`JS object instance with Id '${e}' does not exist. It may have been disposed.`)}if(t.hasOwnProperty(S)){const e=t["__byte[]"],r=n.get(e);if(void 0===r)throw new Error(`Byte array index '${e}' does not exist.`);return r}}return t}));let C=0;function A(e){return C=0,JSON.stringify(e,T)}function T(e,t){if(t instanceof I)return t.serializeAsArg();if(t instanceof Uint8Array){u.sendByteArray(C,t);const e={[S]:C};return C++,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"}(n||(n={}));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}}let o;function a(e,t){if(!o)throw new Error("eventDispatcher not initialized. Call 'setEventDispatcher' to configure it.");o(e,t)}const i=new Map,s=new Map,c={createEventArgs:()=>({})},l=[];function u(e){return i.get(e)}function d(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 f(e){const t=[];for(let n=0;n{return{...m(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"],c),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};var t}}),h(["contextmenu","click","mouseover","mouseout","mousemove","mousedown","mouseup","dblclick"],{createEventArgs:e=>m(e)}),h(["error"],{createEventArgs:e=>{return{message:(t=e).message,filename:t.filename,lineno:t.lineno,colno:t.colno};var t}}),h(["loadstart","timeout","abort","load","loadend","progress"],{createEventArgs:e=>{return{lengthComputable:(t=e).lengthComputable,loaded:t.loaded,total:t.total};var t}}),h(["touchcancel","touchend","touchmove","touchenter","touchleave","touchstart"],{createEventArgs:e=>{return{detail:(t=e).detail,touches:f(t.touches),targetTouches:f(t.targetTouches),changedTouches:f(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{...m(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{...m(t=e),deltaX:t.deltaX,deltaY:t.deltaY,deltaZ:t.deltaZ,deltaMode:t.deltaMode};var t}}),h(["toggle"],c);const p=["date","datetime-local","month","time","week"],v=I(["abort","blur","change","error","focus","load","loadend","loadstart","mouseenter","mouseleave","progress","reset","scroll","submit","unload","toggle","DOMNodeInsertedIntoDocument","DOMNodeRemovedFromDocument"]),g={submit:!0},b=I(["click","dblclick","mousedown","mousemove","mouseup"]);class y{constructor(e){this.browserRendererId=e,this.afterClickCallbacks=[];const t=++y.nextEventDelegatorId;this.eventsCollectionKey=`_blazorEvents_${t}`,this.eventInfoStore=new w(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){let n=t.target,o=null,i=!1;const s=v.hasOwnProperty(e);let c=!1;for(;n;){const h=this.getEventHandlerInfosForElement(n,!1);if(h){const s=h.getHandler(e);if(s&&(l=n,d=t.type,!((l instanceof HTMLButtonElement||l instanceof HTMLInputElement||l instanceof HTMLTextAreaElement||l instanceof HTMLSelectElement)&&b.hasOwnProperty(d)&&l.disabled))){if(!i){const n=u(e);o=(null==n?void 0:n.createEventArgs)?n.createEventArgs(t):{},i=!0}g.hasOwnProperty(t.type)&&t.preventDefault(),a({browserRendererId:this.browserRendererId,eventHandlerId:s.eventHandlerId,eventName:e,eventFieldInfo:r.fromEvent(s.renderingComponentId,t)},o)}h.stopPropagation(e)&&(c=!0),h.preventDefault(e)&&t.preventDefault()}n=s||c?null:n.parentElement}var l,d}getEventHandlerInfosForElement(e,t){return e.hasOwnProperty(this.eventsCollectionKey)?e[this.eventsCollectionKey]:t?e[this.eventsCollectionKey]=new E:null}}y.nextEventDelegatorId=0;class w{constructor(e){this.globalListener=e,this.infosByEventHandlerId={},this.countByEventName={},l.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=d(e),this.countByEventName.hasOwnProperty(e))this.countByEventName[e]++;else{this.countByEventName[e]=1;const t=v.hasOwnProperty(e);document.addEventListener(e,this.globalListener,t)}}update(e,t){if(this.infosByEventHandlerId.hasOwnProperty(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=d(t.eventName);0==--this.countByEventName[n]&&(delete this.countByEventName[n],document.removeEventListener(n,this.globalListener))}return t}handleEventNameAliasAdded(e,t){if(this.countByEventName.hasOwnProperty(e)){const n=this.countByEventName[e];delete this.countByEventName[e],document.removeEventListener(e,this.globalListener),this.addGlobalListener(t),this.countByEventName[t]+=n-1}}}class E{constructor(){this.handlers={},this.preventDefaultFlags=null,this.stopPropagationFlags=null}getHandler(e){return this.handlers.hasOwnProperty(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 I(e){const t={};return e.forEach((e=>{t[e]=!0})),t}const S=M("_blazorLogicalChildren"),D=M("_blazorLogicalParent"),C=M("_blazorLogicalEnd");function A(e,t){if(e.childNodes.length>0&&!t)throw new Error("New logical elements must start empty, or allowExistingContents must be true");return S in e||(e[S]=[]),e}function T(e,t){const n=document.createComment("!");return N(n,e,t),n}function N(e,t,n){const r=e;if(e instanceof Comment&&O(r)&&O(r).length>0)throw new Error("Not implemented: inserting non-empty logical container");if(k(r))throw new Error("Not implemented: moving existing logical children");const o=O(t);if(n0;)R(n,0)}const r=n;r.parentNode.removeChild(r)}function k(e){return e[D]||null}function F(e,t){return O(e)[t]}function _(e){var t=B(e);return"http://www.w3.org/2000/svg"===t.namespaceURI&&"foreignObject"!==t.tagName}function O(e){return e[S]}function x(e,t){const n=O(e);t.forEach((e=>{e.moveRangeStart=n[e.fromSiblingIndex],e.moveRangeEnd=H(e.moveRangeStart)})),t.forEach((t=>{const r=t.moveToBeforeMarker=document.createComment("marker"),o=n[t.toSiblingIndex+1];o?o.parentNode.insertBefore(r,o):P(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 B(e){if(e instanceof Element)return e;if(e instanceof Comment)return e.parentNode;throw new Error("Not a valid logical element")}function L(e){const t=O(k(e));return t[Array.prototype.indexOf.call(t,e)+1]||null}function P(e,t){if(t instanceof Element)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=L(t);n?n.parentNode.insertBefore(e,n):P(e,k(t))}}}function H(e){if(e instanceof Element)return e;const t=L(e);if(t)return t.previousSibling;{const t=k(e);return t instanceof Element?t.lastChild:H(t)}}function M(e){return"function"==typeof Symbol?Symbol():e}function U(e){return`_bl_${e}`}e.attachReviver(((e,t)=>t&&"object"==typeof t&&t.hasOwnProperty("__internalId")&&"string"==typeof t.__internalId?function(e){const t=`[${U(e)}]`;return document.querySelector(t)}(t.__internalId):t));const j="_blazorSelectValue",J=document.createElement("template"),$=document.createElementNS("http://www.w3.org/2000/svg","g"),K={},z="__internal_",V="preventDefault_",X="stopPropagation_";class Y{constructor(e){this.childComponentLocations={},this.eventDelegator=new y(e),this.eventDelegator.notifyAfterClick((e=>{if(!ee)return;if(0!==e.button||function(e){return e.ctrlKey||e.shiftKey||e.altKey||e.metaKey}(e))return;if(e.defaultPrevented)return;const t=function(e){const t=!window._blazorDisableComposedPath&&e.composedPath&&e.composedPath();if(t){for(let e=0;eie(!1))))},enableNavigationInterception:function(){ee=!0},navigateTo:oe,getBaseURI:()=>document.baseURI,getLocationHref:()=>location.href};function oe(e,t,n=!1){const r=ce(e);if(!t&&ue(r))ae(r,!1,n);else if(t&&location.href===e){const t=e+"?";history.replaceState(null,"",t),location.replace(e)}else n?history.replaceState(null,"",r):location.href=e}function ae(e,t,n=!1){Q=!0,n?history.replaceState(null,"",e):history.pushState(null,"",e),ie(t)}async function ie(e){ne&&await ne(location.href,e)}let se;function ce(e){return se=se||document.createElement("a"),se.href=e,se.href}function le(e,t){return e?e.tagName===t?e:le(e.parentElement,t):null}function ue(e){const t=(n=document.baseURI).substr(0,n.lastIndexOf("/")+1);var n;return e.startsWith(t)}const de={init:function(e,t,n,r=50){const o=fe(t);(o||document.documentElement).style.overflowAnchor="none";const a=new IntersectionObserver((function(r){r.forEach((r=>{var o;if(!r.isIntersecting)return;const a=t.getBoundingClientRect(),i=n.getBoundingClientRect().top-a.bottom,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`});a.observe(t),a.observe(n);const i=c(t),s=c(n);function c(e){const t=new MutationObserver((()=>{a.unobserve(e),a.observe(e)}));return t.observe(e,{attributes:!0}),t}he[e._id]={intersectionObserver:a,mutationObserverBefore:i,mutationObserverAfter:s}},dispose:function(e){const t=he[e._id];t&&(t.intersectionObserver.disconnect(),t.mutationObserverBefore.disconnect(),t.mutationObserverAfter.disconnect(),e.dispose(),delete he[e._id])}},he={};function fe(e){return e?"visible"!==getComputedStyle(e).overflowY?e:fe(e.parentElement):null}const me={navigateTo:oe,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]),l.forEach((n=>n(e,t.browserEventName)))}i.set(e,t)},_internal:{navigationManager:re,domWrapper:{focus:function(e,t){if(!(e instanceof HTMLElement))throw new Error("Unable to focus an invalid element.");e.focus({preventScroll:t})},focusBySelector:function(e){const t=document.querySelector(e);t&&(t.hasAttribute("tabindex")||(t.tabIndex=-1),t.focus())}},Virtualize:de}};window.Blazor=me;let pe=!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("")},be=Math.pow(2,32),ye=Math.pow(2,21)-1;function we(e,t){return e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24}function Ee(e,t){return e[t]+(e[t+1]<<8)+(e[t+2]<<16)+(e[t+3]<<24>>>0)}function Ie(e,t){const n=Ee(e,t+4);if(n>ye)throw new Error(`Cannot read uint64 with high order part ${n}, because the result would exceed Number.MAX_SAFE_INTEGER.`);return n*be+Ee(e,t)}class Se{constructor(e){this.batchData=e;const t=new Te(e);this.arrayRangeReader=new Ne(e),this.arrayBuilderSegmentReader=new Re(e),this.diffReader=new De(e),this.editReader=new Ce(e,t),this.frameReader=new Ae(e,t)}updatedComponents(){return we(this.batchData,this.batchData.length-20)}referenceFrames(){return we(this.batchData,this.batchData.length-16)}disposedComponentIds(){return we(this.batchData,this.batchData.length-12)}disposedEventHandlerIds(){return we(this.batchData,this.batchData.length-8)}updatedComponentsEntry(e,t){const n=e+4*t;return we(this.batchData,n)}referenceFramesEntry(e,t){return e+20*t}disposedComponentIdsEntry(e,t){const n=e+4*t;return we(this.batchData,n)}disposedEventHandlerIdsEntry(e,t){const n=e+8*t;return Ie(this.batchData,n)}}class De{constructor(e){this.batchDataUint8=e}componentId(e){return we(this.batchDataUint8,e)}edits(e){return e+4}editsEntry(e,t){return e+16*t}}class Ce{constructor(e,t){this.batchDataUint8=e,this.stringReader=t}editType(e){return we(this.batchDataUint8,e)}siblingIndex(e){return we(this.batchDataUint8,e+4)}newTreeIndex(e){return we(this.batchDataUint8,e+8)}moveToSiblingIndex(e){return we(this.batchDataUint8,e+8)}removedAttributeName(e){const t=we(this.batchDataUint8,e+12);return this.stringReader.readString(t)}}class Ae{constructor(e,t){this.batchDataUint8=e,this.stringReader=t}frameType(e){return we(this.batchDataUint8,e)}subtreeLength(e){return we(this.batchDataUint8,e+4)}elementReferenceCaptureId(e){const t=we(this.batchDataUint8,e+4);return this.stringReader.readString(t)}componentId(e){return we(this.batchDataUint8,e+8)}elementName(e){const t=we(this.batchDataUint8,e+8);return this.stringReader.readString(t)}textContent(e){const t=we(this.batchDataUint8,e+4);return this.stringReader.readString(t)}markupContent(e){const t=we(this.batchDataUint8,e+4);return this.stringReader.readString(t)}attributeName(e){const t=we(this.batchDataUint8,e+4);return this.stringReader.readString(t)}attributeValue(e){const t=we(this.batchDataUint8,e+8);return this.stringReader.readString(t)}attributeEventHandlerId(e){return Ie(this.batchDataUint8,e+12)}}class Te{constructor(e){this.batchDataUint8=e,this.stringTableStartIndex=we(e,e.length-4)}readString(e){if(-1===e)return null;{const n=we(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)<{!function(e,t,n){const r=document.querySelector(e);if(!r)throw new Error(`Could not find any element matching selector '${e}'.`);!function(e,t,n){let r=Z[0];r||(r=Z[0]=new Y(0)),r.attachRootComponentToLogicalElement(n,t)}(0,A(r,!0),t)}(t,e)},RenderBatch:(e,t)=>{try{const n=Me(t);(function(e,t){const n=Z[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{Fe=!0,console.error(`${e}\n${t}`),async function(){let e=document.querySelector("#blazor-error-ui");e&&(e.style.display="block"),pe||(pe=!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:e.jsCallDispatcher.beginInvokeJSFromDotNet,EndInvokeDotNet:e.jsCallDispatcher.endInvokeDotNetFromJS,SendByteArrayToJS:He,Navigate:re.navigateTo};window.external.receiveMessage((e=>{const n=function(e){if(Fe||!e||!e.startsWith(ke))return null;const t=e.substring(ke.length),[n,...r]=JSON.parse(t);return{messageType:n,args:r}}(e);if(n){if(!t.hasOwnProperty(n.messageType))throw new Error(`Unsupported IPC message type '${n.messageType}'`);t[n.messageType].apply(null,n.args)}}))}(),e.attachDispatcher({beginInvokeDotNetFromJS:Oe,endInvokeJSFromDotNet:xe,sendByteArray:Be}),me._internal.InputFile=Ue,re.enableNavigationInterception(),re.listenForNavigationEvents(Le),Pe("AttachPage",re.getBaseURI(),re.getLocationHref())}o=function(e,t){Pe("DispatchBrowserEvent",e,t)},me.start=Ke,document&&document.currentScript&&"false"!==document.currentScript.getAttribute("autostart")&&Ke()})(); \ No newline at end of file diff --git a/src/Components/Web.JS/src/Boot.WebAssembly.ts b/src/Components/Web.JS/src/Boot.WebAssembly.ts index 821641093887..32e5df81b66e 100644 --- a/src/Components/Web.JS/src/Boot.WebAssembly.ts +++ b/src/Components/Web.JS/src/Boot.WebAssembly.ts @@ -151,6 +151,7 @@ function invokeJSFromDotNet(callInfo: Pointer, arg0: any, arg1: any, arg2: any): return result; case DotNet.JSCallResultType.JSObjectReference: return DotNet.createJSObjectReference(result).__jsObjectId; + case DotNet.JSCallResultType.JSDataReference: default: throw new Error(`Invalid JS call result type '${resultType}'.`); } diff --git a/src/Components/WebAssembly/JSInterop/src/WebAssemblyJSObjectReferenceJsonConverter.cs b/src/Components/WebAssembly/JSInterop/src/WebAssemblyJSObjectReferenceJsonConverter.cs index 9afc2eaadea2..5b2f12f54bed 100644 --- a/src/Components/WebAssembly/JSInterop/src/WebAssemblyJSObjectReferenceJsonConverter.cs +++ b/src/Components/WebAssembly/JSInterop/src/WebAssemblyJSObjectReferenceJsonConverter.cs @@ -27,8 +27,8 @@ public override bool CanConvert(Type typeToConvert) public override IJSObjectReference? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { - var deserializedValues = JSObjectReferenceJsonWorker.ReadJSObjectReference(ref reader); - return new WebAssemblyJSObjectReference(_jsRuntime, deserializedValues.Id); + var id = JSObjectReferenceJsonWorker.ReadJSObjectReferenceIdentifier(ref reader); + return new WebAssemblyJSObjectReference(_jsRuntime, id); } public override void Write(Utf8JsonWriter writer, IJSObjectReference value, JsonSerializerOptions options) diff --git a/src/Components/WebAssembly/JSInterop/src/WebAssemblyJSRuntime.cs b/src/Components/WebAssembly/JSInterop/src/WebAssemblyJSRuntime.cs index f35d9335ca79..942a916d5a5f 100644 --- a/src/Components/WebAssembly/JSInterop/src/WebAssemblyJSRuntime.cs +++ b/src/Components/WebAssembly/JSInterop/src/WebAssemblyJSRuntime.cs @@ -101,6 +101,7 @@ internal TResult InvokeUnmarshalled(string identifier, T0 a return exception != null ? throw new JSException(exception) : (TResult)(object)new WebAssemblyJSObjectReference(this, id); + case JSCallResultType.JSDataReference: default: throw new InvalidOperationException($"Invalid result type '{resultType}'."); } diff --git a/src/JSInterop/Microsoft.JSInterop.JS/src/src/Microsoft.JSInterop.ts b/src/JSInterop/Microsoft.JSInterop.JS/src/src/Microsoft.JSInterop.ts index 901402a0daec..39c07927b8d9 100644 --- a/src/JSInterop/Microsoft.JSInterop.JS/src/src/Microsoft.JSInterop.ts +++ b/src/JSInterop/Microsoft.JSInterop.JS/src/src/Microsoft.JSInterop.ts @@ -127,16 +127,10 @@ export module DotNet { if (jsObject && typeof jsObject === 'object') { cachedJSObjectsById[nextJsObjectId] = new JSObject(jsObject); - let result: any = { + const result = { [jsObjectIdKey]: nextJsObjectId }; - // Check if this is an ArrayBufferView, and if so also provide the length of - // the buffer to be used for the JSDataReference. - if (jsObject.buffer instanceof ArrayBuffer && jsObject.byteLength !== undefined) { - result[jsDataReferenceLengthKey] = jsObject.byteLength; - } - nextJsObjectId++; return result; @@ -145,6 +139,36 @@ export module DotNet { } } + /** + * Creates a JavaScript data reference that can be passed to .NET via interop calls. + * + * @param jsObject The JavaScript Object used to create the JavaScript data reference. + * @returns The JavaScript data reference (this will be the same instance as the given object). + * @throws Error if the given value is not an Object or doesn't have a valid byteLength. + */ + export function createJSDataReference(jsObject: any): any { + // Check if this is an ArrayBufferView, and if it has a valid byteLength for transfer + // using a JSDataReference. + if (!(jsObject.buffer instanceof ArrayBuffer)) { + throw new Error(`Cannot create a JSDataReference from the value '${jsObject}' as it is not a valid ArrayBuffer.`); + } else if (jsObject.byteLength === undefined) { + throw new Error(`Cannot create a JSDataReference from the value '${jsObject}' as it doesn't have a byteLength.`); + } + + const result: any = { + [jsDataReferenceLengthKey]: jsObject.byteLength, + } + + try { + const jsObjectReference = createJSObjectReference(jsObject); + result[jsObjectIdKey] = jsObjectReference[jsObjectIdKey]; + } catch { + throw new Error(`Cannot create a JSDataReference from the value '${jsObject}'.`); + } + + return result; + } + /** * Disposes the given JavaScript object reference. * @@ -238,7 +262,8 @@ export module DotNet { */ export enum JSCallResultType { Default = 0, - JSObjectReference = 1 + JSObjectReference = 1, + JSDataReference = 2, } /** @@ -453,6 +478,8 @@ export module DotNet { return returnValue; case JSCallResultType.JSObjectReference: return createJSObjectReference(returnValue); + case JSCallResultType.JSDataReference: + return createJSDataReference(returnValue); default: throw new Error(`Invalid JS call result type '${resultType}'.`); } diff --git a/src/JSInterop/Microsoft.JSInterop/src/Implementation/JSObjectReferenceJsonWorker.cs b/src/JSInterop/Microsoft.JSInterop/src/Implementation/JSObjectReferenceJsonWorker.cs index 92ca7eab6e18..352d64618543 100644 --- a/src/JSInterop/Microsoft.JSInterop/src/Implementation/JSObjectReferenceJsonWorker.cs +++ b/src/JSInterop/Microsoft.JSInterop/src/Implementation/JSObjectReferenceJsonWorker.cs @@ -7,40 +7,33 @@ namespace Microsoft.JSInterop.Implementation { /// - /// Used by JsonConverters to read or write a or instance. + /// Used by JsonConverters to read or write a instance. /// /// This type is part of ASP.NET Core's internal infrastructure and is not recommended for use by external code. /// /// public static class JSObjectReferenceJsonWorker { - private static readonly JsonEncodedText _jsObjectIdKey = JsonEncodedText.Encode("__jsObjectId"); - private static readonly JsonEncodedText _jsDataReferenceLengthKey = JsonEncodedText.Encode("__jsDataReferenceLength"); + internal static readonly JsonEncodedText JSObjectIdKey = JsonEncodedText.Encode("__jsObjectId"); /// /// Reads the id for a instance. /// /// The - /// The deserialized id and length for the . - public static DeserializedJSObjectReferenceValues ReadJSObjectReference(ref Utf8JsonReader reader) + /// The deserialized id for the . + public static long ReadJSObjectReferenceIdentifier(ref Utf8JsonReader reader) { long? id = null; - long? length = null; while (reader.Read() && reader.TokenType != JsonTokenType.EndObject) { if (reader.TokenType == JsonTokenType.PropertyName) { - if (id is null && reader.ValueTextEquals(_jsObjectIdKey.EncodedUtf8Bytes)) + if (id is null && reader.ValueTextEquals(JSObjectIdKey.EncodedUtf8Bytes)) { reader.Read(); id = reader.GetInt64(); } - else if (length is null && reader.ValueTextEquals(_jsDataReferenceLengthKey.EncodedUtf8Bytes)) - { - reader.Read(); - length = reader.GetInt64(); - } else { throw new JsonException($"Unexcepted JSON property {reader.GetString()}."); @@ -54,10 +47,10 @@ public static DeserializedJSObjectReferenceValues ReadJSObjectReference(ref Utf8 if (!id.HasValue) { - throw new JsonException($"Required property {_jsObjectIdKey} not found."); + throw new JsonException($"Required property {JSObjectIdKey} not found."); } - return new DeserializedJSObjectReferenceValues() { Id = id.Value, Length = length }; + return id.Value; } /// @@ -68,24 +61,8 @@ public static DeserializedJSObjectReferenceValues ReadJSObjectReference(ref Utf8 public static void WriteJSObjectReference(Utf8JsonWriter writer, JSObjectReference objectReference) { writer.WriteStartObject(); - writer.WriteNumber(_jsObjectIdKey, objectReference.Id); + writer.WriteNumber(JSObjectIdKey, objectReference.Id); writer.WriteEndObject(); } } - - /// - /// Contains the JSObjectReference.Id and Length that was deserialized - /// - public struct DeserializedJSObjectReferenceValues - { - /// - /// Can be used for the - /// - public long Id; - - /// - /// Can be used for the - /// - public long? Length; - } } diff --git a/src/JSInterop/Microsoft.JSInterop/src/Infrastructure/JSDataReferenceJsonConverter.cs b/src/JSInterop/Microsoft.JSInterop/src/Infrastructure/JSDataReferenceJsonConverter.cs index 892a3aaac4e0..3f31a5b34b5a 100644 --- a/src/JSInterop/Microsoft.JSInterop/src/Infrastructure/JSDataReferenceJsonConverter.cs +++ b/src/JSInterop/Microsoft.JSInterop/src/Infrastructure/JSDataReferenceJsonConverter.cs @@ -10,6 +10,8 @@ namespace Microsoft.JSInterop.Infrastructure { internal sealed class JSDataReferenceJsonConverter : JsonConverter { + private static readonly JsonEncodedText _jsDataReferenceLengthKey = JsonEncodedText.Encode("__jsDataReferenceLength"); + private readonly JSRuntime _jsRuntime; public JSDataReferenceJsonConverter(JSRuntime jsRuntime) @@ -22,14 +24,45 @@ public override bool CanConvert(Type typeToConvert) public override IJSDataReference? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { - var deserializedValues = JSObjectReferenceJsonWorker.ReadJSObjectReference(ref reader); + long? id = null; + long? length = null; + + while (reader.Read() && reader.TokenType != JsonTokenType.EndObject) + { + if (reader.TokenType == JsonTokenType.PropertyName) + { + if (id is null && reader.ValueTextEquals(JSObjectReferenceJsonWorker.JSObjectIdKey.EncodedUtf8Bytes)) + { + reader.Read(); + id = reader.GetInt64(); + } + else if (length is null && reader.ValueTextEquals(_jsDataReferenceLengthKey.EncodedUtf8Bytes)) + { + reader.Read(); + length = reader.GetInt64(); + } + else + { + throw new JsonException($"Unexcepted JSON property {reader.GetString()}."); + } + } + else + { + throw new JsonException($"Unexcepted JSON token {reader.TokenType}"); + } + } + + if (!id.HasValue) + { + throw new JsonException($"Required property {JSObjectReferenceJsonWorker.JSObjectIdKey} not found."); + } - if (!deserializedValues.Length.HasValue) + if (!length.HasValue) { - throw new JsonException($"Required property __jsDataReferenceLength not found."); + throw new JsonException($"Required property {_jsDataReferenceLengthKey} not found."); } - return new JSDataReference(_jsRuntime, deserializedValues.Id, deserializedValues.Length.Value); + return new JSDataReference(_jsRuntime, id.Value, length.Value); } public override void Write(Utf8JsonWriter writer, IJSDataReference value, JsonSerializerOptions options) diff --git a/src/JSInterop/Microsoft.JSInterop/src/Infrastructure/JSObjectReferenceJsonConverter.cs b/src/JSInterop/Microsoft.JSInterop/src/Infrastructure/JSObjectReferenceJsonConverter.cs index bdd4df7c5f0d..037c3e8ea8c8 100644 --- a/src/JSInterop/Microsoft.JSInterop/src/Infrastructure/JSObjectReferenceJsonConverter.cs +++ b/src/JSInterop/Microsoft.JSInterop/src/Infrastructure/JSObjectReferenceJsonConverter.cs @@ -22,8 +22,8 @@ public override bool CanConvert(Type typeToConvert) public override IJSObjectReference? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { - var deserializedValues = JSObjectReferenceJsonWorker.ReadJSObjectReference(ref reader); - return new JSObjectReference(_jsRuntime, deserializedValues.Id); + var id = JSObjectReferenceJsonWorker.ReadJSObjectReferenceIdentifier(ref reader); + return new JSObjectReference(_jsRuntime, id); } public override void Write(Utf8JsonWriter writer, IJSObjectReference value, JsonSerializerOptions options) diff --git a/src/JSInterop/Microsoft.JSInterop/src/JSCallResultType.cs b/src/JSInterop/Microsoft.JSInterop/src/JSCallResultType.cs index 1268113dc71f..9ff8ee3d9e9c 100644 --- a/src/JSInterop/Microsoft.JSInterop/src/JSCallResultType.cs +++ b/src/JSInterop/Microsoft.JSInterop/src/JSCallResultType.cs @@ -17,5 +17,10 @@ public enum JSCallResultType : int /// Indicates that the returned value is to be treated as a JS object reference. /// JSObjectReference = 1, + + /// + /// Indicates that the returned value is to be treated as a JS data reference. + /// + JSDataReference = 2, } } diff --git a/src/JSInterop/Microsoft.JSInterop/src/PublicAPI.Unshipped.txt b/src/JSInterop/Microsoft.JSInterop/src/PublicAPI.Unshipped.txt index 1b10329e7ce7..9b4c466bb290 100644 --- a/src/JSInterop/Microsoft.JSInterop/src/PublicAPI.Unshipped.txt +++ b/src/JSInterop/Microsoft.JSInterop/src/PublicAPI.Unshipped.txt @@ -11,8 +11,9 @@ Microsoft.JSInterop.Implementation.JSDataReference.JSDataReference(Microsoft.JSI Microsoft.JSInterop.Implementation.JSDataReference.Length.get -> long Microsoft.JSInterop.Implementation.JSObjectReferenceJsonWorker Microsoft.JSInterop.Infrastructure.DotNetInvocationResult.ResultJson.get -> string? +Microsoft.JSInterop.JSCallResultType.JSDataReference = 2 -> Microsoft.JSInterop.JSCallResultType Microsoft.JSInterop.JSRuntime.Dispose() -> void -static Microsoft.JSInterop.Implementation.JSObjectReferenceJsonWorker.ReadJSObjectReference(ref System.Text.Json.Utf8JsonReader reader) -> Microsoft.JSInterop.Implementation.DeserializedJSObjectReferenceValues +static Microsoft.JSInterop.Implementation.JSObjectReferenceJsonWorker.ReadJSObjectReferenceIdentifier(ref System.Text.Json.Utf8JsonReader reader) -> long static Microsoft.JSInterop.Implementation.JSObjectReferenceJsonWorker.WriteJSObjectReference(System.Text.Json.Utf8JsonWriter! writer, Microsoft.JSInterop.Implementation.JSObjectReference! objectReference) -> void *REMOVED*Microsoft.JSInterop.Infrastructure.DotNetInvocationResult.DotNetInvocationResult(System.Exception! exception, string? errorKind) -> void *REMOVED*Microsoft.JSInterop.Infrastructure.DotNetInvocationResult.DotNetInvocationResult(object? result) -> void From 7133bd64493c97d4fd96975da0427a5cedd5f5e3 Mon Sep 17 00:00:00 2001 From: Tanay Parikh Date: Mon, 14 Jun 2021 11:26:34 -0700 Subject: [PATCH 12/37] Update PublicAPI.Unshipped.txt --- src/JSInterop/Microsoft.JSInterop/src/PublicAPI.Unshipped.txt | 4 ---- 1 file changed, 4 deletions(-) diff --git a/src/JSInterop/Microsoft.JSInterop/src/PublicAPI.Unshipped.txt b/src/JSInterop/Microsoft.JSInterop/src/PublicAPI.Unshipped.txt index 9b4c466bb290..d479efc1804b 100644 --- a/src/JSInterop/Microsoft.JSInterop/src/PublicAPI.Unshipped.txt +++ b/src/JSInterop/Microsoft.JSInterop/src/PublicAPI.Unshipped.txt @@ -2,10 +2,6 @@ Microsoft.JSInterop.IJSDataReference Microsoft.JSInterop.IJSDataReference.Length.get -> long Microsoft.JSInterop.IJSDataReference.OpenReadStreamAsync(long maxAllowedSize = 512000, long maxBufferSize = 102400, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task! -Microsoft.JSInterop.Implementation.DeserializedJSObjectReferenceValues -Microsoft.JSInterop.Implementation.DeserializedJSObjectReferenceValues.DeserializedJSObjectReferenceValues() -> void -Microsoft.JSInterop.Implementation.DeserializedJSObjectReferenceValues.Id -> long -Microsoft.JSInterop.Implementation.DeserializedJSObjectReferenceValues.Length -> long? Microsoft.JSInterop.Implementation.JSDataReference Microsoft.JSInterop.Implementation.JSDataReference.JSDataReference(Microsoft.JSInterop.JSRuntime! jsRuntime, long id, long totalLength) -> void Microsoft.JSInterop.Implementation.JSDataReference.Length.get -> long From e3956fef6ae3dc64d3774a1e9e1c5a508915bef2 Mon Sep 17 00:00:00 2001 From: Tanay Parikh Date: Mon, 14 Jun 2021 12:07:59 -0700 Subject: [PATCH 13/37] PR Feedback Continued --- src/Components/Server/src/Circuits/CircuitHost.cs | 4 ++-- src/Components/Server/src/Circuits/RemoteJSDataStream.cs | 8 ++++---- src/Components/Server/src/Circuits/RemoteJSRuntime.cs | 1 - src/Components/Server/src/ComponentHub.cs | 2 +- src/Shared/JSInterop/JSCallResultTypeHelper.cs | 8 ++++++-- 5 files changed, 13 insertions(+), 10 deletions(-) diff --git a/src/Components/Server/src/Circuits/CircuitHost.cs b/src/Components/Server/src/Circuits/CircuitHost.cs index be0d4d030992..5a375336c56c 100644 --- a/src/Components/Server/src/Circuits/CircuitHost.cs +++ b/src/Components/Server/src/Circuits/CircuitHost.cs @@ -418,14 +418,14 @@ await Renderer.Dispatcher.InvokeAsync(() => // ReceiveJSDataChunk is used in a fire-and-forget context, so it's responsible for its own // error handling. - internal async Task ReceiveJSDataChunk(string streamId, ReadOnlySequence chunk, string error) + internal async Task ReceiveJSDataChunk(string streamId, byte[] chunk, string error) { AssertInitialized(); AssertNotDisposed(); try { - return await RemoteJSDataStream.SupplyData(JSRuntime, streamId, chunk, error); + return await RemoteJSDataStream.ReceiveData(JSRuntime, streamId, chunk, error); } catch (Exception ex) { diff --git a/src/Components/Server/src/Circuits/RemoteJSDataStream.cs b/src/Components/Server/src/Circuits/RemoteJSDataStream.cs index 804eedcaac44..f1c1783a4eb0 100644 --- a/src/Components/Server/src/Circuits/RemoteJSDataStream.cs +++ b/src/Components/Server/src/Circuits/RemoteJSDataStream.cs @@ -21,7 +21,7 @@ internal class RemoteJSDataStream : Stream private readonly Pipe _pipe; private long _bytesRead; - public static async Task SupplyData(RemoteJSRuntime runtime, string streamId, ReadOnlySequence chunk, string error) + public static async Task ReceiveData(RemoteJSRuntime runtime, string streamId, byte[] chunk, string error) { if (!runtime.RemoteJSDataStreamInstances.TryGetValue(Guid.Parse(streamId), out var instance)) { @@ -30,7 +30,7 @@ public static async Task SupplyData(RemoteJSRuntime runtime, string stream return false; } - await instance.SupplyData(chunk, error); + await instance.ReceiveData(chunk, error); return true; } @@ -70,7 +70,7 @@ private RemoteJSDataStream( // data without having to copy it into a temporary buffer in BlazorPackHubProtocolWorker. But trying // this gives strange errors; sometimes the "chunk" variable below has a negative length, even though // the logic never returns a corrupted item as far as I can tell. - private async Task SupplyData(ReadOnlySequence chunk, string error) + private async Task ReceiveData(byte[] chunk, string error) { try { @@ -107,7 +107,7 @@ private async Task SupplyData(ReadOnlySequence chunk, string error) } } - private static void CopyToPipeWriter(ReadOnlySequence chunk, PipeWriter writer) + private static void CopyToPipeWriter(byte[] chunk, PipeWriter writer) { var pipeBuffer = writer.GetSpan((int)chunk.Length); chunk.CopyTo(pipeBuffer); diff --git a/src/Components/Server/src/Circuits/RemoteJSRuntime.cs b/src/Components/Server/src/Circuits/RemoteJSRuntime.cs index 13bbb5bb62ef..3974f7c442ce 100644 --- a/src/Components/Server/src/Circuits/RemoteJSRuntime.cs +++ b/src/Components/Server/src/Circuits/RemoteJSRuntime.cs @@ -207,7 +207,6 @@ internal static void InvokeDotNetMethodSuccess(ILogger logger, { _invokeInstanceDotNetMethodSuccess(logger, invocationInfo.MethodIdentifier, invocationInfo.DotNetObjectId, invocationInfo.CallId, null); } - } } } diff --git a/src/Components/Server/src/ComponentHub.cs b/src/Components/Server/src/ComponentHub.cs index 920289d578b1..8ff823d721be 100644 --- a/src/Components/Server/src/ComponentHub.cs +++ b/src/Components/Server/src/ComponentHub.cs @@ -224,7 +224,7 @@ public async ValueTask ReceiveByteArray(int id, byte[] data) await circuitHost.ReceiveByteArray(id, data); } - public async Task ReceiveJSDataChunk(string streamId, ReadOnlySequence chunk, string error) + public async Task ReceiveJSDataChunk(string streamId, byte[] chunk, string error) { var circuitHost = await GetActiveCircuitAsync(); if (circuitHost == null) diff --git a/src/Shared/JSInterop/JSCallResultTypeHelper.cs b/src/Shared/JSInterop/JSCallResultTypeHelper.cs index 1a924aebc6e0..4d491a5a629a 100644 --- a/src/Shared/JSInterop/JSCallResultTypeHelper.cs +++ b/src/Shared/JSInterop/JSCallResultTypeHelper.cs @@ -15,11 +15,15 @@ public static JSCallResultType FromGeneric() if (typeof(TResult).Assembly == _currentAssembly && (typeof(TResult) == typeof(IJSObjectReference) || typeof(TResult) == typeof(IJSInProcessObjectReference) - || typeof(TResult) == typeof(IJSUnmarshalledObjectReference) - || typeof(TResult) == typeof(IJSDataReference))) + || typeof(TResult) == typeof(IJSUnmarshalledObjectReference))) { return JSCallResultType.JSObjectReference; } + else if (typeof(TResult).Assembly == _currentAssembly + && typeof(TResult) == typeof(IJSDataReference)) + { + return JSCallResultType.JSDataReference; + } else { return JSCallResultType.Default; From 639b34f844ef2aa6535b155700f1f820f7b2a567 Mon Sep 17 00:00:00 2001 From: Tanay Parikh Date: Mon, 14 Jun 2021 14:54:03 -0700 Subject: [PATCH 14/37] Unit Tests --- .../Server/src/Circuits/RemoteJSDataStream.cs | 16 +- .../test/Circuits/RemoteJSDataStreamTest.cs | 147 ++++++++++++++++++ .../JSDataReferenceJsonConverterTest.cs | 123 +++++++++++++++ .../Microsoft.JSInterop/test/JSRuntimeTest.cs | 15 ++ 4 files changed, 296 insertions(+), 5 deletions(-) create mode 100644 src/Components/Server/test/Circuits/RemoteJSDataStreamTest.cs create mode 100644 src/JSInterop/Microsoft.JSInterop/test/Infrastructure/JSDataReferenceJsonConverterTest.cs diff --git a/src/Components/Server/src/Circuits/RemoteJSDataStream.cs b/src/Components/Server/src/Circuits/RemoteJSDataStream.cs index f1c1783a4eb0..75ee89cdc9f1 100644 --- a/src/Components/Server/src/Circuits/RemoteJSDataStream.cs +++ b/src/Components/Server/src/Circuits/RemoteJSDataStream.cs @@ -23,15 +23,19 @@ internal class RemoteJSDataStream : Stream public static async Task ReceiveData(RemoteJSRuntime runtime, string streamId, byte[] chunk, string error) { - if (!runtime.RemoteJSDataStreamInstances.TryGetValue(Guid.Parse(streamId), out var instance)) + if (!Guid.TryParse(streamId, out var guid)) + { + throw new ArgumentException("The streamId is not recognized."); + } + + if (!runtime.RemoteJSDataStreamInstances.TryGetValue(guid, out var instance)) { // There is no data stream with the given identifier. It may have already been disposed. // We notify JS that the stream has been cancelled/disposed. return false; } - await instance.ReceiveData(chunk, error); - return true; + return await instance.ReceiveData(chunk, error); } public static async Task CreateRemoteJSDataStreamAsync( @@ -70,7 +74,7 @@ private RemoteJSDataStream( // data without having to copy it into a temporary buffer in BlazorPackHubProtocolWorker. But trying // this gives strange errors; sometimes the "chunk" variable below has a negative length, even though // the logic never returns a corrupted item as far as I can tell. - private async Task ReceiveData(byte[] chunk, string error) + private async Task ReceiveData(byte[] chunk, string error) { try { @@ -99,11 +103,13 @@ private async Task ReceiveData(byte[] chunk, string error) { await _pipe.Writer.CompleteAsync(); } + + return true; } catch (Exception e) { await _pipe.Writer.CompleteAsync(e); - return; + return false; } } diff --git a/src/Components/Server/test/Circuits/RemoteJSDataStreamTest.cs b/src/Components/Server/test/Circuits/RemoteJSDataStreamTest.cs new file mode 100644 index 000000000000..6f666f940b13 --- /dev/null +++ b/src/Components/Server/test/Circuits/RemoteJSDataStreamTest.cs @@ -0,0 +1,147 @@ +// Copyright (c) .NET Foundation. All rights reserved. +// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. + +using System; +using System.Linq; +using System.Threading.Tasks; +using Microsoft.AspNetCore.SignalR; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Options; +using Microsoft.JSInterop; +using Moq; +using Xunit; + +namespace Microsoft.AspNetCore.Components.Server.Circuits +{ + public class RemoteJSDataStreamTest + { + private static readonly TestRemoteJSRuntime _jsRuntime = new(Options.Create(new CircuitOptions()), Options.Create(new HubOptions()), Mock.Of>()); + + [Fact] + public async void CreateRemoteJSDataStreamAsync_CreatesStream() + { + // Arrange + var jsDataReference = Mock.Of(); + + // Act + var remoteJSDataStream = await RemoteJSDataStream.CreateRemoteJSDataStreamAsync(_jsRuntime, jsDataReference, totalLength: 100, maxBufferSize: 50, maximumIncomingBytes: 10_000); + + // Assert + Assert.NotNull(remoteJSDataStream); + } + + [Fact] + public async void ReceiveData_InvalidGuid() + { + // Arrange + var chunk = new byte[] { 3, 5, 6, 7 }; + + // Act + var exception = await Assert.ThrowsAsync(async() => await RemoteJSDataStream.ReceiveData(_jsRuntime, streamId: "invalid-guid", chunk, error: null)); + + // Assert + Assert.Equal("The streamId is not recognized.", exception.Message); + } + + [Fact] + public async void ReceiveData_DoesNotFindStream() + { + // Arrange + var chunk = new byte[] { 3, 5, 6, 7 }; + var unrecognizedGuid = Guid.NewGuid(); + + // Act + var success = await RemoteJSDataStream.ReceiveData(_jsRuntime, streamId: unrecognizedGuid.ToString(), chunk, error: null); + + // Assert + Assert.False(success); + } + + [Fact] + public async void ReceiveData_SuccessReadsBackStream() + { + // Arrange + var jsRuntime = new TestRemoteJSRuntime(Options.Create(new CircuitOptions()), Options.Create(new HubOptions()), Mock.Of>()); + var remoteJSDataStream = await CreateRemoteJSDataStreamAsync(jsRuntime); + var streamId = GetStreamId(remoteJSDataStream, jsRuntime); + var chunk = new byte[] { 3, 5, 7 }; + + // Act + var success = await RemoteJSDataStream.ReceiveData(jsRuntime, streamId, chunk, error: null); + + // Assert + Assert.True(success); + } + + [Fact] + public async void ReceiveData_WithError() + { + // Arrange + var jsRuntime = new TestRemoteJSRuntime(Options.Create(new CircuitOptions()), Options.Create(new HubOptions()), Mock.Of>()); + var remoteJSDataStream = await CreateRemoteJSDataStreamAsync(jsRuntime); + var streamId = GetStreamId(remoteJSDataStream, jsRuntime); + + // Act + var success = await RemoteJSDataStream.ReceiveData(jsRuntime, streamId, chunk: null, error: "some error"); + + // Assert + Assert.False(success); + } + + [Fact] + public async void ReceiveData_WithZeroLengthChunk() + { + // Arrange + var jsRuntime = new TestRemoteJSRuntime(Options.Create(new CircuitOptions()), Options.Create(new HubOptions()), Mock.Of>()); + var remoteJSDataStream = await CreateRemoteJSDataStreamAsync(jsRuntime); + var streamId = GetStreamId(remoteJSDataStream, jsRuntime); + var chunk = Array.Empty(); + + // Act + var success = await RemoteJSDataStream.ReceiveData(jsRuntime, streamId, chunk, error: null); + + // Assert + Assert.False(success); + } + + [Fact] + public async void ReceiveData_ProvidedWithMoreBytesThanRemaining() + { + // Arrange + var jsRuntime = new TestRemoteJSRuntime(Options.Create(new CircuitOptions()), Options.Create(new HubOptions()), Mock.Of>()); + var jsDataReference = Mock.Of(); + var remoteJSDataStream = await RemoteJSDataStream.CreateRemoteJSDataStreamAsync(jsRuntime, jsDataReference, totalLength: 100, maxBufferSize: 50, maximumIncomingBytes: 10_000); + var streamId = GetStreamId(remoteJSDataStream, jsRuntime); + var chunk = new byte[110]; // 100 byte totalLength for stream + + // Act + var success = await RemoteJSDataStream.ReceiveData(jsRuntime, streamId, chunk, error: null); + + // Assert + Assert.False(success); + } + + private static async Task CreateRemoteJSDataStreamAsync(TestRemoteJSRuntime jsRuntime = null) + { + var jsDataReference = Mock.Of(); + var remoteJSDataStream = await RemoteJSDataStream.CreateRemoteJSDataStreamAsync(jsRuntime ?? _jsRuntime, jsDataReference, totalLength: 100, maxBufferSize: 50, maximumIncomingBytes: 10_000); + return remoteJSDataStream; + } + + private static string GetStreamId(RemoteJSDataStream stream, RemoteJSRuntime runtime) => + runtime.RemoteJSDataStreamInstances.FirstOrDefault(kvp => kvp.Value == stream).Key.ToString(); + + class TestRemoteJSRuntime : RemoteJSRuntime, IJSRuntime + { + public TestRemoteJSRuntime(IOptions circuitOptions, IOptions hubOptions, ILogger logger) : base(circuitOptions, hubOptions, logger) + { + } + + new public ValueTask InvokeAsync(string identifier, object[] args) + { + Assert.Equal("Blazor._internal.sendJSDataStream", identifier); + return ValueTask.FromResult(default); + } + } + } +} diff --git a/src/JSInterop/Microsoft.JSInterop/test/Infrastructure/JSDataReferenceJsonConverterTest.cs b/src/JSInterop/Microsoft.JSInterop/test/Infrastructure/JSDataReferenceJsonConverterTest.cs new file mode 100644 index 000000000000..f3ad82207792 --- /dev/null +++ b/src/JSInterop/Microsoft.JSInterop/test/Infrastructure/JSDataReferenceJsonConverterTest.cs @@ -0,0 +1,123 @@ +// Copyright (c) .NET Foundation. All rights reserved. +// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. + +using System; +using System.Text.Json; +using Microsoft.JSInterop.Implementation; +using Xunit; + +namespace Microsoft.JSInterop.Infrastructure +{ + public class JSDataReferenceJsonConverterTest + { + private readonly JSRuntime JSRuntime = new TestJSRuntime(); + private readonly JsonSerializerOptions JsonSerializerOptions; + + public JSDataReferenceJsonConverterTest() + { + JsonSerializerOptions = JSRuntime.JsonSerializerOptions; + JsonSerializerOptions.Converters.Add(new JSDataReferenceJsonConverter(JSRuntime)); + } + + [Fact] + public void Read_Throws_IfJsonIsMissingJSObjectIdProperty() + { + // Arrange + var json = "{}"; + + // Act & Assert + var ex = Assert.Throws(() => JsonSerializer.Deserialize(json, JsonSerializerOptions)); + Assert.Equal("Required property __jsObjectId not found.", ex.Message); + } + + [Fact] + public void Read_Throws_IfJsonContainsUnknownContent() + { + // Arrange + var json = "{\"foo\":2}"; + + // Act & Assert + var ex = Assert.Throws(() => JsonSerializer.Deserialize(json, JsonSerializerOptions)); + Assert.Equal("Unexcepted JSON property foo.", ex.Message); + } + + [Fact] + public void Read_Throws_IfJsonIsIncomplete() + { + // Arrange + var json = $"{{\"__jsObjectId\":5"; + + // Act & Assert + var ex = Record.Exception(() => JsonSerializer.Deserialize(json, JsonSerializerOptions)); + Assert.IsAssignableFrom(ex); + } + + [Fact] + public void Read_Throws_IfJSObjectIdAppearsMultipleTimes() + { + // Arrange + var json = $"{{\"__jsObjectId\":3,\"__jsObjectId\":7}}"; + + // Act & Assert + var ex = Record.Exception(() => JsonSerializer.Deserialize(json, JsonSerializerOptions)); + Assert.IsAssignableFrom(ex); + } + + [Fact] + public void Read_Throws_IfLengthNotProvided() + { + // Arrange + var expectedId = 3; + var json = $"{{\"__jsObjectId\":{expectedId}}}"; + + // Act & Assert + var ex = Assert.Throws(() => JsonSerializer.Deserialize(json, JsonSerializerOptions)); + Assert.Equal("Required property __jsDataReferenceLength not found.", ex.Message); + } + + [Fact] + public void Read_ReadsJson_IJSDataReference() + { + // Arrange + var expectedId = 3; + var expectedLength = 5; + var json = $"{{\"__jsObjectId\":{expectedId}, \"__jsDataReferenceLength\":{expectedLength}}}"; + + // Act + var deserialized = (JSDataReference)JsonSerializer.Deserialize(json, JsonSerializerOptions)!; + + // Assert + Assert.Equal(expectedId, deserialized?.Id); + Assert.Equal(expectedLength, deserialized?.Length); + } + + [Fact] + public void Read_ReadsJson_IJSDataReferenceReverseOrder() + { + // Arrange + var expectedId = 3; + var expectedLength = 5; + var json = $"{{\"__jsDataReferenceLength\":{expectedLength}, \"__jsObjectId\":{expectedId}}}"; + + // Act + var deserialized = (JSDataReference)JsonSerializer.Deserialize(json, JsonSerializerOptions)!; + + // Assert + Assert.Equal(expectedId, deserialized?.Id); + Assert.Equal(expectedLength, deserialized?.Length); + } + + [Fact] + public void Write_WritesValidJson() + { + // Arrange + var jsObjectRef = new JSDataReference(JSRuntime, 7, 10); + + // Act + var json = JsonSerializer.Serialize((IJSDataReference)jsObjectRef, JsonSerializerOptions); + + // Assert + Assert.Equal($"{{\"__jsObjectId\":{jsObjectRef.Id}}}", json); + } + } +} diff --git a/src/JSInterop/Microsoft.JSInterop/test/JSRuntimeTest.cs b/src/JSInterop/Microsoft.JSInterop/test/JSRuntimeTest.cs index d77241e970b8..e81c88b94803 100644 --- a/src/JSInterop/Microsoft.JSInterop/test/JSRuntimeTest.cs +++ b/src/JSInterop/Microsoft.JSInterop/test/JSRuntimeTest.cs @@ -9,6 +9,7 @@ using System.Text.Json; using System.Threading; using System.Threading.Tasks; +using Microsoft.JSInterop.Implementation; using Microsoft.JSInterop.Infrastructure; using Xunit; @@ -395,6 +396,20 @@ public void ReceiveByteArray_ThrowsExceptionIfUnexpectedId() Assert.Equal("Element id '7' cannot be added to the byte arrays to be revived with length '2'.", ex.Message); } + [Fact] + public async void ReadJSDataAsStreamAsync_ThrowsNotSupportedException() + { + // Arrange + var runtime = new TestJSRuntime(); + var dataReference = new JSDataReference(runtime, 10, 10); + + // Act + var exception = await Assert.ThrowsAsync(async () => await runtime.ReadJSDataAsStreamAsync(dataReference, 10, 10, CancellationToken.None)); + + // Assert + Assert.Equal("The current JavaScript runtime does not support reading data streams.", exception.Message); + } + private class JSError { public DotNetInvocationInfo InvocationInfo { get; set; } From 7f893127109e58742c02887dccba75a09c1aceae Mon Sep 17 00:00:00 2001 From: Tanay Parikh Date: Mon, 14 Jun 2021 15:26:57 -0700 Subject: [PATCH 15/37] @pranavkm feedback --- .../Server/src/Circuits/RemoteJSDataStream.cs | 15 ++++++++------- src/Components/Server/src/ComponentHub.cs | 2 +- .../Microsoft.JSInterop/src/IJSDataReference.cs | 12 ++++++------ .../src/Implementation/JSDataReference.cs | 12 ++++++------ .../src/PublicAPI.Unshipped.txt | 3 +-- 5 files changed, 22 insertions(+), 22 deletions(-) diff --git a/src/Components/Server/src/Circuits/RemoteJSDataStream.cs b/src/Components/Server/src/Circuits/RemoteJSDataStream.cs index 75ee89cdc9f1..e5bd2f1ed078 100644 --- a/src/Components/Server/src/Circuits/RemoteJSDataStream.cs +++ b/src/Components/Server/src/Circuits/RemoteJSDataStream.cs @@ -11,12 +11,12 @@ namespace Microsoft.AspNetCore.Components.Server.Circuits { - internal class RemoteJSDataStream : Stream + internal sealed class RemoteJSDataStream : Stream { private readonly RemoteJSRuntime _runtime; private readonly Guid _streamId; private readonly long _totalLength; - private readonly CancellationToken _cancellationToken; + private readonly CancellationToken _streamCancellationToken; private readonly Stream _pipeReaderStream; private readonly Pipe _pipe; private long _bytesRead; @@ -38,7 +38,7 @@ public static async Task ReceiveData(RemoteJSRuntime runtime, string strea return await instance.ReceiveData(chunk, error); } - public static async Task CreateRemoteJSDataStreamAsync( + public static async ValueTask CreateRemoteJSDataStreamAsync( RemoteJSRuntime runtime, IJSDataReference jsDataReference, long totalLength, @@ -62,7 +62,7 @@ private RemoteJSDataStream( _runtime = runtime; _streamId = streamId; _totalLength = totalLength; - _cancellationToken = cancellationToken; + _streamCancellationToken = cancellationToken; _runtime.RemoteJSDataStreamInstances.Add(_streamId, this); @@ -97,7 +97,7 @@ private async Task ReceiveData(byte[] chunk, string error) CopyToPipeWriter(chunk, _pipe.Writer); _pipe.Writer.Advance((int)chunk.Length); - await _pipe.Writer.FlushAsync(_cancellationToken); + await _pipe.Writer.FlushAsync(_streamCancellationToken); if (_bytesRead == _totalLength) { @@ -109,6 +109,7 @@ private async Task ReceiveData(byte[] chunk, string error) catch (Exception e) { await _pipe.Writer.CompleteAsync(e); + Dispose(true); return false; } } @@ -150,13 +151,13 @@ public override void Write(byte[] buffer, int offset, int count) public override async Task ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) { - var linkedCts = CancellationTokenSource.CreateLinkedTokenSource(_cancellationToken, cancellationToken); + var linkedCts = CancellationTokenSource.CreateLinkedTokenSource(_streamCancellationToken, cancellationToken); return await _pipeReaderStream.ReadAsync(buffer.AsMemory(offset, count), linkedCts.Token); } public override async ValueTask ReadAsync(Memory buffer, CancellationToken cancellationToken = default) { - var linkedCts = CancellationTokenSource.CreateLinkedTokenSource(_cancellationToken, cancellationToken); + var linkedCts = CancellationTokenSource.CreateLinkedTokenSource(_streamCancellationToken, cancellationToken); return await _pipeReaderStream.ReadAsync(buffer, linkedCts.Token); } diff --git a/src/Components/Server/src/ComponentHub.cs b/src/Components/Server/src/ComponentHub.cs index 8ff823d721be..15273a422bb9 100644 --- a/src/Components/Server/src/ComponentHub.cs +++ b/src/Components/Server/src/ComponentHub.cs @@ -224,7 +224,7 @@ public async ValueTask ReceiveByteArray(int id, byte[] data) await circuitHost.ReceiveByteArray(id, data); } - public async Task ReceiveJSDataChunk(string streamId, byte[] chunk, string error) + public async ValueTask ReceiveJSDataChunk(string streamId, byte[] chunk, string error) { var circuitHost = await GetActiveCircuitAsync(); if (circuitHost == null) diff --git a/src/JSInterop/Microsoft.JSInterop/src/IJSDataReference.cs b/src/JSInterop/Microsoft.JSInterop/src/IJSDataReference.cs index c12f6fab23b6..9149aec3b368 100644 --- a/src/JSInterop/Microsoft.JSInterop/src/IJSDataReference.cs +++ b/src/JSInterop/Microsoft.JSInterop/src/IJSDataReference.cs @@ -9,22 +9,22 @@ namespace Microsoft.JSInterop { /// - /// Represents a reference to JavaScript data to be consumed through a stream. + /// Represents a reference to JavaScript data to be consumed through a . /// public interface IJSDataReference : IAsyncDisposable { /// - /// Length of the stream provided by JavaScript. + /// Length of the provided by JavaScript. /// public long Length { get; } /// - /// Initiatializes a with the for the current data reference. + /// Opens a with the for the current data reference. /// /// Maximum number of bytes permitted to be read from JavaScript. - /// Amount of bytes to buffer before flushing. + /// Maximum number of bytes that are allowed to be buffered. /// for cancelling read. - /// Stream which can provide data associated with the current data reference. - public Task OpenReadStreamAsync(long maxAllowedSize = 512000, long maxBufferSize = 100 * 1024, CancellationToken cancellationToken = default); + /// which can provide data associated with the current data reference. + ValueTask OpenReadStreamAsync(long maxAllowedSize = 512000, long maxBufferSize = 100 * 1024, CancellationToken cancellationToken = default); } } diff --git a/src/JSInterop/Microsoft.JSInterop/src/Implementation/JSDataReference.cs b/src/JSInterop/Microsoft.JSInterop/src/Implementation/JSDataReference.cs index e20126714e17..5446ad3b2677 100644 --- a/src/JSInterop/Microsoft.JSInterop/src/Implementation/JSDataReference.cs +++ b/src/JSInterop/Microsoft.JSInterop/src/Implementation/JSDataReference.cs @@ -11,12 +11,12 @@ namespace Microsoft.JSInterop.Implementation /// /// Implements functionality for . /// - public class JSDataReference : JSObjectReference, IJSDataReference + public sealed class JSDataReference : JSObjectReference, IJSDataReference { private readonly JSRuntime _jsRuntime; /// - public long Length { get; private set; } + public long Length { get; } /// /// Inititializes a new instance. @@ -24,11 +24,11 @@ public class JSDataReference : JSObjectReference, IJSDataReference /// The used for invoking JS interop calls. /// The unique identifier. /// The length of the data stream coming from JS represented by this data reference. - protected internal JSDataReference(JSRuntime jsRuntime, long id, long totalLength) : base(jsRuntime, id) + internal JSDataReference(JSRuntime jsRuntime, long id, long totalLength) : base(jsRuntime, id) { if (totalLength <= 0) { - throw new InvalidOperationException($"The incoming data stream of length {totalLength} cannot be empty."); + throw new ArgumentOutOfRangeException(nameof(totalLength), totalLength, "Length must be a positive value."); } _jsRuntime = jsRuntime; @@ -36,11 +36,11 @@ protected internal JSDataReference(JSRuntime jsRuntime, long id, long totalLengt } /// - async Task IJSDataReference.OpenReadStreamAsync(long maxLength, long maxBufferSize, CancellationToken cancellationToken) + async ValueTask IJSDataReference.OpenReadStreamAsync(long maxLength, long maxBufferSize, CancellationToken cancellationToken) { if (Length > maxLength) { - throw new InvalidOperationException($"The incoming data stream of length {Length} exceeds the maximum length {maxLength}."); + throw new ArgumentOutOfRangeException(nameof(maxLength), $"The incoming data stream of length {Length} exceeds the maximum length {maxLength}."); } return await _jsRuntime.ReadJSDataAsStreamAsync(this, Length, maxBufferSize, cancellationToken); diff --git a/src/JSInterop/Microsoft.JSInterop/src/PublicAPI.Unshipped.txt b/src/JSInterop/Microsoft.JSInterop/src/PublicAPI.Unshipped.txt index d479efc1804b..2c7982196320 100644 --- a/src/JSInterop/Microsoft.JSInterop/src/PublicAPI.Unshipped.txt +++ b/src/JSInterop/Microsoft.JSInterop/src/PublicAPI.Unshipped.txt @@ -1,9 +1,8 @@ #nullable enable Microsoft.JSInterop.IJSDataReference Microsoft.JSInterop.IJSDataReference.Length.get -> long -Microsoft.JSInterop.IJSDataReference.OpenReadStreamAsync(long maxAllowedSize = 512000, long maxBufferSize = 102400, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task! +Microsoft.JSInterop.IJSDataReference.OpenReadStreamAsync(long maxAllowedSize = 512000, long maxBufferSize = 102400, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask Microsoft.JSInterop.Implementation.JSDataReference -Microsoft.JSInterop.Implementation.JSDataReference.JSDataReference(Microsoft.JSInterop.JSRuntime! jsRuntime, long id, long totalLength) -> void Microsoft.JSInterop.Implementation.JSDataReference.Length.get -> long Microsoft.JSInterop.Implementation.JSObjectReferenceJsonWorker Microsoft.JSInterop.Infrastructure.DotNetInvocationResult.ResultJson.get -> string? From 115d9356e1ca8e60882032710576784d8ae85df8 Mon Sep 17 00:00:00 2001 From: Tanay Parikh Date: Mon, 14 Jun 2021 15:46:56 -0700 Subject: [PATCH 16/37] @BrennanConroy PR Feedback --- .../Server/src/Circuits/CircuitHost.cs | 8 +++--- .../Server/src/Circuits/RemoteJSDataStream.cs | 27 +++++-------------- .../Server/src/Circuits/RemoteJSRuntime.cs | 3 ++- src/Components/Server/src/ComponentHub.cs | 2 +- .../test/Circuits/RemoteJSDataStreamTest.cs | 21 +++------------ 5 files changed, 18 insertions(+), 43 deletions(-) diff --git a/src/Components/Server/src/Circuits/CircuitHost.cs b/src/Components/Server/src/Circuits/CircuitHost.cs index 5a375336c56c..c5ceabd055b1 100644 --- a/src/Components/Server/src/Circuits/CircuitHost.cs +++ b/src/Components/Server/src/Circuits/CircuitHost.cs @@ -418,7 +418,7 @@ await Renderer.Dispatcher.InvokeAsync(() => // ReceiveJSDataChunk is used in a fire-and-forget context, so it's responsible for its own // error handling. - internal async Task ReceiveJSDataChunk(string streamId, byte[] chunk, string error) + internal async Task ReceiveJSDataChunk(long streamId, byte[] chunk, string error) { AssertInitialized(); AssertNotDisposed(); @@ -661,7 +661,7 @@ private static class Log private static readonly Action _endInvokeJSSucceeded; private static readonly Action _receiveByteArraySuccess; private static readonly Action _receiveByteArrayException; - private static readonly Action _receiveJSDataChunkException; + private static readonly Action _receiveJSDataChunkException; private static readonly Action _dispatchEventFailedToParseEventData; private static readonly Action _dispatchEventFailedToDispatchEvent; private static readonly Action _locationChange; @@ -836,7 +836,7 @@ static Log() EventIds.ReceiveByteArrayException, "The ReceiveByteArray call with id '{id}' failed."); - _receiveJSDataChunkException = LoggerMessage.Define( + _receiveJSDataChunkException = LoggerMessage.Define( LogLevel.Debug, EventIds.ReceiveJSDataChunkException, "The ReceiveJSDataChunk call with stream id '{streamId}' failed."); @@ -905,7 +905,7 @@ public static void CircuitHandlerFailed(ILogger logger, CircuitHandler handler, public static void EndInvokeJSSucceeded(ILogger logger, long asyncCall) => _endInvokeJSSucceeded(logger, asyncCall, null); internal static void ReceiveByteArraySuccess(ILogger logger, long id) => _receiveByteArraySuccess(logger, id, null); internal static void ReceiveByteArrayException(ILogger logger, long id, Exception ex) => _receiveByteArrayException(logger, id, ex); - internal static void ReceiveJSDataChunkException(ILogger logger, string streamId, Exception ex) => _receiveJSDataChunkException(logger, streamId, ex); + internal static void ReceiveJSDataChunkException(ILogger logger, long streamId, Exception ex) => _receiveJSDataChunkException(logger, streamId, ex); public static void DispatchEventFailedToParseEventData(ILogger logger, Exception ex) => _dispatchEventFailedToParseEventData(logger, ex); public static void DispatchEventFailedToDispatchEvent(ILogger logger, string eventHandlerId, Exception ex) => _dispatchEventFailedToDispatchEvent(logger, eventHandlerId ?? "", ex); diff --git a/src/Components/Server/src/Circuits/RemoteJSDataStream.cs b/src/Components/Server/src/Circuits/RemoteJSDataStream.cs index e5bd2f1ed078..ce3fe6378ceb 100644 --- a/src/Components/Server/src/Circuits/RemoteJSDataStream.cs +++ b/src/Components/Server/src/Circuits/RemoteJSDataStream.cs @@ -14,21 +14,16 @@ namespace Microsoft.AspNetCore.Components.Server.Circuits internal sealed class RemoteJSDataStream : Stream { private readonly RemoteJSRuntime _runtime; - private readonly Guid _streamId; + private readonly long _streamId; private readonly long _totalLength; private readonly CancellationToken _streamCancellationToken; private readonly Stream _pipeReaderStream; private readonly Pipe _pipe; private long _bytesRead; - public static async Task ReceiveData(RemoteJSRuntime runtime, string streamId, byte[] chunk, string error) + public static async Task ReceiveData(RemoteJSRuntime runtime, long streamId, byte[] chunk, string error) { - if (!Guid.TryParse(streamId, out var guid)) - { - throw new ArgumentException("The streamId is not recognized."); - } - - if (!runtime.RemoteJSDataStreamInstances.TryGetValue(guid, out var instance)) + if (!runtime.RemoteJSDataStreamInstances.TryGetValue(streamId, out var instance)) { // There is no data stream with the given identifier. It may have already been disposed. // We notify JS that the stream has been cancelled/disposed. @@ -46,7 +41,7 @@ public static async ValueTask CreateRemoteJSDataStreamAsync( long maximumIncomingBytes, CancellationToken cancellationToken = default) { - var streamId = Guid.NewGuid(); + var streamId = runtime.RemoteJSDataStreamNextInstanceId++; var remoteJSDataStream = new RemoteJSDataStream(runtime, streamId, totalLength, maxBufferSize, cancellationToken); await runtime.InvokeVoidAsync("Blazor._internal.sendJSDataStream", jsDataReference, streamId, maximumIncomingBytes); return remoteJSDataStream; @@ -54,7 +49,7 @@ public static async ValueTask CreateRemoteJSDataStreamAsync( private RemoteJSDataStream( RemoteJSRuntime runtime, - Guid streamId, + long streamId, long totalLength, long maxBufferSize, CancellationToken cancellationToken) @@ -66,7 +61,7 @@ private RemoteJSDataStream( _runtime.RemoteJSDataStreamInstances.Add(_streamId, this); - _pipe = new Pipe(new PipeOptions(pauseWriterThreshold: maxBufferSize, resumeWriterThreshold: maxBufferSize)); + _pipe = new Pipe(new PipeOptions(pauseWriterThreshold: maxBufferSize, resumeWriterThreshold: maxBufferSize / 2)); _pipeReaderStream = _pipe.Reader.AsStream(); } @@ -95,9 +90,7 @@ private async Task ReceiveData(byte[] chunk, string error) throw new InvalidOperationException($"The incoming data stream declared a length {_totalLength}, but {_bytesRead} bytes were read."); } - CopyToPipeWriter(chunk, _pipe.Writer); - _pipe.Writer.Advance((int)chunk.Length); - await _pipe.Writer.FlushAsync(_streamCancellationToken); + await _pipe.Writer.WriteAsync(chunk, _streamCancellationToken); if (_bytesRead == _totalLength) { @@ -114,12 +107,6 @@ private async Task ReceiveData(byte[] chunk, string error) } } - private static void CopyToPipeWriter(byte[] chunk, PipeWriter writer) - { - var pipeBuffer = writer.GetSpan((int)chunk.Length); - chunk.CopyTo(pipeBuffer); - } - public override bool CanRead => true; public override bool CanSeek => false; diff --git a/src/Components/Server/src/Circuits/RemoteJSRuntime.cs b/src/Components/Server/src/Circuits/RemoteJSRuntime.cs index 3974f7c442ce..7ead84b3e506 100644 --- a/src/Components/Server/src/Circuits/RemoteJSRuntime.cs +++ b/src/Components/Server/src/Circuits/RemoteJSRuntime.cs @@ -24,7 +24,8 @@ internal class RemoteJSRuntime : JSRuntime private readonly long _maximumIncomingBytes; private int _byteArraysToBeRevivedTotalBytes; - internal readonly Dictionary RemoteJSDataStreamInstances = new(); + internal int RemoteJSDataStreamNextInstanceId; + internal readonly Dictionary RemoteJSDataStreamInstances = new(); public ElementReferenceContext ElementReferenceContext { get; } diff --git a/src/Components/Server/src/ComponentHub.cs b/src/Components/Server/src/ComponentHub.cs index 15273a422bb9..650bc762932f 100644 --- a/src/Components/Server/src/ComponentHub.cs +++ b/src/Components/Server/src/ComponentHub.cs @@ -224,7 +224,7 @@ public async ValueTask ReceiveByteArray(int id, byte[] data) await circuitHost.ReceiveByteArray(id, data); } - public async ValueTask ReceiveJSDataChunk(string streamId, byte[] chunk, string error) + public async ValueTask ReceiveJSDataChunk(long streamId, byte[] chunk, string error) { var circuitHost = await GetActiveCircuitAsync(); if (circuitHost == null) diff --git a/src/Components/Server/test/Circuits/RemoteJSDataStreamTest.cs b/src/Components/Server/test/Circuits/RemoteJSDataStreamTest.cs index 6f666f940b13..140cf0b6db89 100644 --- a/src/Components/Server/test/Circuits/RemoteJSDataStreamTest.cs +++ b/src/Components/Server/test/Circuits/RemoteJSDataStreamTest.cs @@ -30,28 +30,15 @@ public async void CreateRemoteJSDataStreamAsync_CreatesStream() Assert.NotNull(remoteJSDataStream); } - [Fact] - public async void ReceiveData_InvalidGuid() - { - // Arrange - var chunk = new byte[] { 3, 5, 6, 7 }; - - // Act - var exception = await Assert.ThrowsAsync(async() => await RemoteJSDataStream.ReceiveData(_jsRuntime, streamId: "invalid-guid", chunk, error: null)); - - // Assert - Assert.Equal("The streamId is not recognized.", exception.Message); - } - [Fact] public async void ReceiveData_DoesNotFindStream() { // Arrange var chunk = new byte[] { 3, 5, 6, 7 }; - var unrecognizedGuid = Guid.NewGuid(); + var unrecognizedGuid = 10; // Act - var success = await RemoteJSDataStream.ReceiveData(_jsRuntime, streamId: unrecognizedGuid.ToString(), chunk, error: null); + var success = await RemoteJSDataStream.ReceiveData(_jsRuntime, streamId: unrecognizedGuid, chunk, error: null); // Assert Assert.False(success); @@ -128,8 +115,8 @@ private static async Task CreateRemoteJSDataStreamAsync(Test return remoteJSDataStream; } - private static string GetStreamId(RemoteJSDataStream stream, RemoteJSRuntime runtime) => - runtime.RemoteJSDataStreamInstances.FirstOrDefault(kvp => kvp.Value == stream).Key.ToString(); + private static long GetStreamId(RemoteJSDataStream stream, RemoteJSRuntime runtime) => + runtime.RemoteJSDataStreamInstances.FirstOrDefault(kvp => kvp.Value == stream).Key; class TestRemoteJSRuntime : RemoteJSRuntime, IJSRuntime { From 1e01c626310ca98bfc47cb015a0e5f822a4feaea Mon Sep 17 00:00:00 2001 From: Tanay Parikh Date: Mon, 14 Jun 2021 16:38:29 -0700 Subject: [PATCH 17/37] E2E JS To .NET Interop Test --- src/Components/test/E2ETest/Tests/InputFileTest.cs | 1 - src/Components/test/E2ETest/Tests/InteropTest.cs | 1 + .../test/testassets/BasicTestApp/InteropComponent.razor | 6 ++++++ .../testassets/BasicTestApp/wwwroot/js/jsinteroptests.js | 8 ++++++++ 4 files changed, 15 insertions(+), 1 deletion(-) diff --git a/src/Components/test/E2ETest/Tests/InputFileTest.cs b/src/Components/test/E2ETest/Tests/InputFileTest.cs index 8073c0dddb5e..c39d785c4c9e 100644 --- a/src/Components/test/E2ETest/Tests/InputFileTest.cs +++ b/src/Components/test/E2ETest/Tests/InputFileTest.cs @@ -16,7 +16,6 @@ using OpenQA.Selenium.Support.Extensions; using Xunit; using Xunit.Abstractions; -using System.Threading.Tasks; namespace Microsoft.AspNetCore.Components.E2ETest.Tests { diff --git a/src/Components/test/E2ETest/Tests/InteropTest.cs b/src/Components/test/E2ETest/Tests/InteropTest.cs index ee091576caeb..1bb3c9febab4 100644 --- a/src/Components/test/E2ETest/Tests/InteropTest.cs +++ b/src/Components/test/E2ETest/Tests/InteropTest.cs @@ -63,6 +63,7 @@ public void CanInvokeDotNetMethods() ["roundTripByteArrayWrapperObjectAsyncFromJS"] = @"{""strVal"":""Some string"",""byteArrayVal"":{""0"":1,""1"":5,""2"":7,""3"":17,""4"":200,""5"":138},""intVal"":42}", ["roundTripByteArrayAsyncFromDotNet"] = @"1,5,7,15,35,200", ["roundTripByteArrayWrapperObjectAsyncFromDotNet"] = @"StrVal: Some String, IntVal: 100000, ByteArrayVal: 1,5,7,15,35,200", + ["jsToDotNetStreamAsync"] = @"1,5,7,15,35,200", ["AsyncThrowSyncException"] = @"""System.InvalidOperationException: Threw a sync exception!", ["AsyncThrowAsyncException"] = @"""System.InvalidOperationException: Threw an async exception!", ["SyncExceptionFromAsyncMethod"] = "Function threw a sync exception!", diff --git a/src/Components/test/testassets/BasicTestApp/InteropComponent.razor b/src/Components/test/testassets/BasicTestApp/InteropComponent.razor index b80b32ccccb6..15283b0b25c8 100644 --- a/src/Components/test/testassets/BasicTestApp/InteropComponent.razor +++ b/src/Components/test/testassets/BasicTestApp/InteropComponent.razor @@ -175,6 +175,12 @@ ReturnValues["roundTripByteArrayWrapperObjectFromDotNet"] = ((IJSInProcessRuntime)JSRuntime).Invoke("roundTripByteArrayWrapperObject", byteArrayWrapperObject).ToString(); } + var dataReference = await JSRuntime.InvokeAsync("jsToDotNetStreamAsync"); + using var stream = await dataReference.OpenReadStreamAsync(); + var jsToDotNetStreamAsyncResult = new byte[6]; + stream.CopyTo(jsToDotNetStreamAsyncResult, 0, jsToDotNetStreamAsyncResult.Length); + ReturnValues["jsToDotNetStreamAsync"] = string.Join(",", (jsToDotNetStreamAsyncResult.ToArray()); + Invocations = invocations; DoneWithInterop = true; } diff --git a/src/Components/test/testassets/BasicTestApp/wwwroot/js/jsinteroptests.js b/src/Components/test/testassets/BasicTestApp/wwwroot/js/jsinteroptests.js index 9d1fdbd2ed66..f43e601dbd53 100644 --- a/src/Components/test/testassets/BasicTestApp/wwwroot/js/jsinteroptests.js +++ b/src/Components/test/testassets/BasicTestApp/wwwroot/js/jsinteroptests.js @@ -260,6 +260,14 @@ function roundTripByteArrayWrapperObject(byteArrayWrapperObject) { return byteArrayWrapperObject; } +function jsToDotNetStreamAsync() { + return new Promise((resolve, reject) => { + setTimeout(function () { + resolve(new Uint8Array([1, 5, 7, 15, 35, 200])); + }, 100); + }); +} + function roundTripByteArrayWrapperObjectAsync(byteArrayWrapperObject) { return new Promise((resolve, reject) => { setTimeout(function () { From 6a931ad537d44620cdf0ac40795c830edf835d04 Mon Sep 17 00:00:00 2001 From: Tanay Parikh Date: Mon, 14 Jun 2021 16:42:16 -0700 Subject: [PATCH 18/37] Update blazor.server.js --- src/Components/Web.JS/dist/Release/blazor.server.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Components/Web.JS/dist/Release/blazor.server.js b/src/Components/Web.JS/dist/Release/blazor.server.js index 9168593b9217..2fc7959e9ae8 100644 --- a/src/Components/Web.JS/dist/Release/blazor.server.js +++ b/src/Components/Web.JS/dist/Release/blazor.server.js @@ -1 +1 @@ -(()=>{"use strict";var e,t,n;!function(e){window.DotNet=e;const t=[],n=new Map;class r{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 o="__jsObjectId",i={},s={0:new r(window)};s[0]._cachedFunctions.set("import",(e=>("string"==typeof e&&e.startsWith("./")&&(e=document.baseURI+e.substr(2)),import(e))));let a,c=1,l=1,h=null;function u(e){t.push(e)}function d(e){if(e&&"object"==typeof e){s[l]=new r(e);const t={[o]:l};return l++,t}throw new Error(`Cannot create a JSObjectReference from the value '${e}'.`)}function p(e){return e?JSON.parse(e,((e,n)=>t.reduce(((t,n)=>n(e,t)),n))):null}function f(e,t,n,r){const o=m();if(o.invokeDotNetFromJS){const i=I(r),s=o.invokeDotNetFromJS(e,t,n,i);return s?p(s):null}throw new Error("The current dispatcher does not support synchronous calls from JS to .NET. Use invokeMethodAsync instead.")}function g(e,t,n,r){if(e&&n)throw new Error(`For instance method calls, assemblyName should be null. Received '${e}'.`);const o=c++,s=new Promise(((e,t)=>{i[o]={resolve:e,reject:t}}));try{const i=I(r);m().beginInvokeDotNetFromJS(o,e,t,n,i)}catch(e){y(o,!1,e)}return s}function m(){if(null!==h)return h;throw new Error("No .NET call dispatcher has been set.")}function y(e,t,n){if(!i.hasOwnProperty(e))throw new Error(`There is no pending async call with ID ${e}.`);const r=i[e];delete i[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 v(e,t){let n=s[t];if(n)return n.findFunction(e);throw new Error(`JS object instance with ID ${t} does not exist (has it been disposed?).`)}function b(e){delete s[e]}e.attachDispatcher=function(e){h=e},e.attachReviver=u,e.invokeMethod=function(e,t,...n){return f(e,t,null,n)},e.invokeMethodAsync=function(e,t,...n){return g(e,t,null,n)},e.createJSObjectReference=d,e.disposeJSObjectReference=function(e){const t=e&&e.__jsObjectId;"number"==typeof t&&b(t)},function(e){e[e.Default=0]="Default",e[e.JSObjectReference=1]="JSObjectReference"}(a=e.JSCallResultType||(e.JSCallResultType={})),e.jsCallDispatcher={findJSFunction:v,disposeJSObjectReferenceById:b,invokeJSFromDotNet:(e,t,n,r)=>{const o=S(v(e,r).apply(null,p(t)),n);return null==o?null:I(o)},beginInvokeJSFromDotNet:(e,t,n,r,o)=>{const i=new Promise((e=>{e(v(t,o).apply(null,p(n)))}));e&&i.then((t=>m().endInvokeJSFromDotNet(e,!0,I([e,!0,S(t,r)]))),(t=>m().endInvokeJSFromDotNet(e,!1,JSON.stringify([e,!1,w(t)]))))},endInvokeDotNetFromJS:(e,t,n)=>{const r=t?p(n):new Error(n);y(parseInt(e),t,r)},receiveByteArray:(e,t)=>{n.set(e,t)}};class _{constructor(e){this._id=e}invokeMethod(e,...t){return f(null,e,this._id,t)}invokeMethodAsync(e,...t){return g(null,e,this._id,t)}dispose(){g(null,"__Dispose",this._id,null).catch((e=>console.error(e)))}serializeAsArg(){return{__dotNetObject:this._id}}}const E="__byte[]";function S(e,t){switch(t){case a.Default:return e;case a.JSObjectReference:return d(e);default:throw new Error(`Invalid JS call result type '${t}'.`)}}u((function(e,t){if(t&&"object"==typeof t){if(t.hasOwnProperty("__dotNetObject"))return new _(t.__dotNetObject);if(t.hasOwnProperty(o)){const e=t.__jsObjectId,n=s[e];if(n)return n.getWrappedObject();throw new Error(`JS object instance with Id '${e}' does not exist. It may have been disposed.`)}if(t.hasOwnProperty(E)){const e=t["__byte[]"],r=n.get(e);if(void 0===r)throw new Error(`Byte array index '${e}' does not exist.`);return r}}return t}));let C=0;function I(e){return C=0,JSON.stringify(e,k)}function k(e,t){if(t instanceof _)return t.serializeAsArg();if(t instanceof Uint8Array){h.sendByteArray(C,t);const e={[E]:C};return C++,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"}(n||(n={}));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}}let o;function i(e,t){if(!o)throw new Error("eventDispatcher not initialized. Call 'setEventDispatcher' to configure it.");o(e,t)}const s=new Map,a=new Map,c={createEventArgs:()=>({})},l=[];function h(e){return s.get(e)}function u(e){const t=s.get(e);return(null==t?void 0:t.browserEventName)||e}function d(e,t){e.forEach((e=>s.set(e,t)))}function p(e){const t=[];for(let n=0;n{return{...f(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}}),d(["focus","blur","focusin","focusout"],c),d(["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};var t}}),d(["contextmenu","click","mouseover","mouseout","mousemove","mousedown","mouseup","dblclick"],{createEventArgs:e=>f(e)}),d(["error"],{createEventArgs:e=>{return{message:(t=e).message,filename:t.filename,lineno:t.lineno,colno:t.colno};var t}}),d(["loadstart","timeout","abort","load","loadend","progress"],{createEventArgs:e=>{return{lengthComputable:(t=e).lengthComputable,loaded:t.loaded,total:t.total};var t}}),d(["touchcancel","touchend","touchmove","touchenter","touchleave","touchstart"],{createEventArgs:e=>{return{detail:(t=e).detail,touches:p(t.touches),targetTouches:p(t.targetTouches),changedTouches:p(t.changedTouches),ctrlKey:t.ctrlKey,shiftKey:t.shiftKey,altKey:t.altKey,metaKey:t.metaKey,type:t.type};var t}}),d(["gotpointercapture","lostpointercapture","pointercancel","pointerdown","pointerenter","pointerleave","pointermove","pointerout","pointerover","pointerup"],{createEventArgs:e=>{return{...f(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}}),d(["wheel","mousewheel"],{createEventArgs:e=>{return{...f(t=e),deltaX:t.deltaX,deltaY:t.deltaY,deltaZ:t.deltaZ,deltaMode:t.deltaMode};var t}}),d(["toggle"],c);const g=["date","datetime-local","month","time","week"],m=E(["abort","blur","change","error","focus","load","loadend","loadstart","mouseenter","mouseleave","progress","reset","scroll","submit","unload","toggle","DOMNodeInsertedIntoDocument","DOMNodeRemovedFromDocument"]),y={submit:!0},w=E(["click","dblclick","mousedown","mousemove","mouseup"]);class v{constructor(e){this.browserRendererId=e,this.afterClickCallbacks=[];const t=++v.nextEventDelegatorId;this.eventsCollectionKey=`_blazorEvents_${t}`,this.eventInfoStore=new b(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,a.get(n));var n;t&&t.forEach((t=>this.dispatchGlobalEventToAllElements(t,e))),"click"===e.type&&this.afterClickCallbacks.forEach((t=>t(e)))}dispatchGlobalEventToAllElements(e,t){let n=t.target,o=null,s=!1;const a=m.hasOwnProperty(e);let c=!1;for(;n;){const d=this.getEventHandlerInfosForElement(n,!1);if(d){const a=d.getHandler(e);if(a&&(l=n,u=t.type,!((l instanceof HTMLButtonElement||l instanceof HTMLInputElement||l instanceof HTMLTextAreaElement||l instanceof HTMLSelectElement)&&w.hasOwnProperty(u)&&l.disabled))){if(!s){const n=h(e);o=(null==n?void 0:n.createEventArgs)?n.createEventArgs(t):{},s=!0}y.hasOwnProperty(t.type)&&t.preventDefault(),i({browserRendererId:this.browserRendererId,eventHandlerId:a.eventHandlerId,eventName:e,eventFieldInfo:r.fromEvent(a.renderingComponentId,t)},o)}d.stopPropagation(e)&&(c=!0),d.preventDefault(e)&&t.preventDefault()}n=a||c?null:n.parentElement}var l,u}getEventHandlerInfosForElement(e,t){return e.hasOwnProperty(this.eventsCollectionKey)?e[this.eventsCollectionKey]:t?e[this.eventsCollectionKey]=new _:null}}v.nextEventDelegatorId=0;class b{constructor(e){this.globalListener=e,this.infosByEventHandlerId={},this.countByEventName={},l.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=u(e),this.countByEventName.hasOwnProperty(e))this.countByEventName[e]++;else{this.countByEventName[e]=1;const t=m.hasOwnProperty(e);document.addEventListener(e,this.globalListener,t)}}update(e,t){if(this.infosByEventHandlerId.hasOwnProperty(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=u(t.eventName);0==--this.countByEventName[n]&&(delete this.countByEventName[n],document.removeEventListener(n,this.globalListener))}return t}handleEventNameAliasAdded(e,t){if(this.countByEventName.hasOwnProperty(e)){const n=this.countByEventName[e];delete this.countByEventName[e],document.removeEventListener(e,this.globalListener),this.addGlobalListener(t),this.countByEventName[t]+=n-1}}}class _{constructor(){this.handlers={},this.preventDefaultFlags=null,this.stopPropagationFlags=null}getHandler(e){return this.handlers.hasOwnProperty(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 E(e){const t={};return e.forEach((e=>{t[e]=!0})),t}const S=H("_blazorLogicalChildren"),C=H("_blazorLogicalParent"),I=H("_blazorLogicalEnd");function k(e,t){if(e.childNodes.length>0&&!t)throw new Error("New logical elements must start empty, or allowExistingContents must be true");return S in e||(e[S]=[]),e}function T(e,t){const n=document.createComment("!");return x(n,e,t),n}function x(e,t,n){const r=e;if(e instanceof Comment&&A(r)&&A(r).length>0)throw new Error("Not implemented: inserting non-empty logical container");if(R(r))throw new Error("Not implemented: moving existing logical children");const o=A(t);if(n0;)D(n,0)}const r=n;r.parentNode.removeChild(r)}function R(e){return e[C]||null}function P(e,t){return A(e)[t]}function U(e){var t=B(e);return"http://www.w3.org/2000/svg"===t.namespaceURI&&"foreignObject"!==t.tagName}function A(e){return e[S]}function N(e,t){const n=A(e);t.forEach((e=>{e.moveRangeStart=n[e.fromSiblingIndex],e.moveRangeEnd=L(e.moveRangeStart)})),t.forEach((t=>{const r=t.moveToBeforeMarker=document.createComment("marker"),o=n[t.toSiblingIndex+1];o?o.parentNode.insertBefore(r,o):M(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 B(e){if(e instanceof Element)return e;if(e instanceof Comment)return e.parentNode;throw new Error("Not a valid logical element")}function $(e){const t=A(R(e));return t[Array.prototype.indexOf.call(t,e)+1]||null}function M(e,t){if(t instanceof Element)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=$(t);n?n.parentNode.insertBefore(e,n):M(e,R(t))}}}function L(e){if(e instanceof Element)return e;const t=$(e);if(t)return t.previousSibling;{const t=R(e);return t instanceof Element?t.lastChild:L(t)}}function H(e){return"function"==typeof Symbol?Symbol():e}function F(e){return`_bl_${e}`}e.attachReviver(((e,t)=>t&&"object"==typeof t&&t.hasOwnProperty("__internalId")&&"string"==typeof t.__internalId?function(e){const t=`[${F(e)}]`;return document.querySelector(t)}(t.__internalId):t));const O="_blazorSelectValue",j=document.createElement("template"),W=document.createElementNS("http://www.w3.org/2000/svg","g"),z={},q="__internal_",J="preventDefault_",K="stopPropagation_";class V{constructor(e){this.childComponentLocations={},this.eventDelegator=new v(e),this.eventDelegator.notifyAfterClick((e=>{if(!ee)return;if(0!==e.button||function(e){return e.ctrlKey||e.shiftKey||e.altKey||e.metaKey}(e))return;if(e.defaultPrevented)return;const t=function(e){const t=!window._blazorDisableComposedPath&&e.composedPath&&e.composedPath();if(t){for(let e=0;ese(!1))))},enableNavigationInterception:function(){ee=!0},navigateTo:oe,getBaseURI:()=>document.baseURI,getLocationHref:()=>location.href};function oe(e,t,n=!1){const r=ce(e);if(!t&&he(r))ie(r,!1,n);else if(t&&location.href===e){const t=e+"?";history.replaceState(null,"",t),location.replace(e)}else n?history.replaceState(null,"",r):location.href=e}function ie(e,t,n=!1){Z=!0,n?history.replaceState(null,"",e):history.pushState(null,"",e),se(t)}async function se(e){ne&&await ne(location.href,e)}let ae;function ce(e){return ae=ae||document.createElement("a"),ae.href=e,ae.href}function le(e,t){return e?e.tagName===t?e:le(e.parentElement,t):null}function he(e){const t=(n=document.baseURI).substr(0,n.lastIndexOf("/")+1);var n;return e.startsWith(t)}const ue={init:function(e,t,n,r=50){const o=pe(t);(o||document.documentElement).style.overflowAnchor="none";const i=new IntersectionObserver((function(r){r.forEach((r=>{var o;if(!r.isIntersecting)return;const i=t.getBoundingClientRect(),s=n.getBoundingClientRect().top-i.bottom,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`});i.observe(t),i.observe(n);const s=c(t),a=c(n);function c(e){const t=new MutationObserver((()=>{i.unobserve(e),i.observe(e)}));return t.observe(e,{attributes:!0}),t}de[e._id]={intersectionObserver:i,mutationObserverBefore:s,mutationObserverAfter:a}},dispose:function(e){const t=de[e._id];t&&(t.intersectionObserver.disconnect(),t.mutationObserverBefore.disconnect(),t.mutationObserverAfter.disconnect(),e.dispose(),delete de[e._id])}},de={};function pe(e){return e?"visible"!==getComputedStyle(e).overflowY?e:pe(e.parentElement):null}const fe={navigateTo:oe,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=a.get(t.browserEventName);n?n.push(e):a.set(t.browserEventName,[e]),l.forEach((n=>n(e,t.browserEventName)))}s.set(e,t)},_internal:{navigationManager:re,domWrapper:{focus:function(e,t){if(!(e instanceof HTMLElement))throw new Error("Unable to focus an invalid element.");e.focus({preventScroll:t})},focusBySelector:function(e){const t=document.querySelector(e);t&&(t.hasAttribute("tabindex")||(t.tabIndex=-1),t.focus())}},Virtualize:ue}};window.Blazor=fe;const ge=[0,2e3,1e4,3e4,null];class me{constructor(e){this._retryDelays=void 0!==e?[...e,null]:ge}nextRetryDelayInMilliseconds(e){return this._retryDelays[e.previousRetryCount]}}class ye extends Error{constructor(e,t){const n=new.target.prototype;super(`${e}: Status code '${t}'`),this.statusCode=t,this.__proto__=n}}class we extends Error{constructor(e="A timeout occurred."){const t=new.target.prototype;super(e),this.__proto__=t}}class ve extends Error{constructor(e="An abort occurred."){const t=new.target.prototype;super(e),this.__proto__=t}}class be{constructor(e,t,n){this.statusCode=e,this.statusText=t,this.content=n}}class _e{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""}}var Ee,Se,Ce,Ie,ke;!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"}(Ee||(Ee={}));class Te extends _e{constructor(e){if(super(),this._logger=e,"undefined"==typeof fetch){const e=require;this._jar=new(e("tough-cookie").CookieJar),this._fetchType=e("node-fetch"),this._fetchType=e("fetch-cookie")(this._fetchType,this._jar),this._abortControllerType=e("abort-controller")}else this._fetchType=fetch.bind(self),this._abortControllerType=AbortController}async send(e){if(e.abortSignal&&e.abortSignal.aborted)throw new ve;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 ve});let r,o=null;if(e.timeout){const r=e.timeout;o=setTimeout((()=>{t.abort(),this._logger.log(Ee.Warning,"Timeout from HTTP request."),n=new we}),r)}try{r=await this._fetchType(e.url,{body:e.content,cache:"no-cache",credentials:!0===e.withCredentials?"include":"same-origin",headers:{"Content-Type":"text/plain;charset=UTF-8","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(Ee.Warning,`Error from HTTP request. ${e}.`),e}finally{o&&clearTimeout(o),e.abortSignal&&(e.abortSignal.onabort=null)}if(!r.ok){const e=await xe(r,"text");throw new ye(e||r.statusText,r.status)}const i=xe(r,e.responseType),s=await i;return new be(r.status,r.statusText,s)}getCookieString(e){return""}}function xe(e,t){let n;switch(t){case"arraybuffer":n=e.arrayBuffer();break;case"text":n=e.text();break;case"blob":case"document":case"json":throw new Error(`${t} is not supported.`);default:n=e.text()}return n}class De extends _e{constructor(e){super(),this._logger=e}send(e){return e.abortSignal&&e.abortSignal.aborted?Promise.reject(new ve):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"),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 ve)}),e.timeout&&(r.timeout=e.timeout),r.onload=()=>{e.abortSignal&&(e.abortSignal.onabort=null),r.status>=200&&r.status<300?t(new be(r.status,r.statusText,r.response||r.responseText)):n(new ye(r.response||r.responseText||r.statusText,r.status))},r.onerror=()=>{this._logger.log(Ee.Warning,`Error from HTTP request. ${r.status}: ${r.statusText}.`),n(new ye(r.statusText,r.status))},r.ontimeout=()=>{this._logger.log(Ee.Warning,"Timeout from HTTP request."),n(new we)},r.send(e.content||"")})):Promise.reject(new Error("No url defined.")):Promise.reject(new Error("No method defined."))}}class Re extends _e{constructor(e){if(super(),"undefined"!=typeof fetch)this._httpClient=new Te(e);else{if("undefined"==typeof XMLHttpRequest)throw new Error("No usable HttpClient found.");this._httpClient=new De(e)}}send(e){return e.abortSignal&&e.abortSignal.aborted?Promise.reject(new ve):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)}}class Pe{}Pe.Authorization="Authorization",Pe.Cookie="Cookie",function(e){e[e.None=0]="None",e[e.WebSockets=1]="WebSockets",e[e.ServerSentEvents=2]="ServerSentEvents",e[e.LongPolling=4]="LongPolling"}(Se||(Se={})),function(e){e[e.Text=1]="Text",e[e.Binary=2]="Binary"}(Ce||(Ce={}));class Ue{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 Ae{constructor(){}log(e,t){}}Ae.instance=new Ae;class Ne{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 Be{static get isBrowser(){return"object"==typeof window}static get isWebWorker(){return"object"==typeof self&&"importScripts"in self}static get isNode(){return!this.isBrowser&&!this.isWebWorker}}function $e(e,t){let n="";return Me(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 Me(e){return e&&"undefined"!=typeof ArrayBuffer&&(e instanceof ArrayBuffer||e.constructor&&"ArrayBuffer"===e.constructor.name)}async function Le(e,t,n,r,o,i,s,a,c){let l={};if(o){const e=await o();e&&(l={Authorization:`Bearer ${e}`})}const[h,u]=Oe();l[h]=u,e.log(Ee.Trace,`(${t} transport) sending data. ${$e(i,s)}.`);const d=Me(i)?"arraybuffer":"text",p=await n.post(r,{content:i,headers:{...l,...c},responseType:d,withCredentials:a});e.log(Ee.Trace,`(${t} transport) request complete. Response status: ${p.statusCode}.`)}class He{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 Fe{constructor(e){this._minLevel=e,this.out=console}log(e,t){if(e>=this._minLevel){const n=`[${(new Date).toISOString()}] ${Ee[e]}: ${t}`;switch(e){case Ee.Critical:case Ee.Error:this.out.error(n);break;case Ee.Warning:this.out.warn(n);break;case Ee.Information:this.out.info(n);break;default:this.out.log(n)}}}}function Oe(){let e="X-SignalR-User-Agent";return Be.isNode&&(e="User-Agent"),[e,je("0.0.0-DEV_BUILD",We(),Be.isNode?"NodeJS":"Browser",ze())]}function je(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 We(){if(!Be.isNode)return"";switch(process.platform){case"win32":return"Windows NT";case"darwin":return"macOS";case"linux":return"Linux";default:return process.platform}}function ze(){if(Be.isNode)return process.versions.node}class qe{constructor(e,t,n,r,o,i){this._httpClient=e,this._accessTokenFactory=t,this._logger=n,this._pollAbort=new Ue,this._logMessageContent=r,this._withCredentials=o,this._headers=i,this._running=!1,this.onreceive=null,this.onclose=null}get pollAborted(){return this._pollAbort.aborted}async connect(e,t){if(Ne.isRequired(e,"url"),Ne.isRequired(t,"transferFormat"),Ne.isIn(t,Ce,"transferFormat"),this._url=e,this._logger.log(Ee.Trace,"(LongPolling transport) Connecting."),t===Ce.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]=Oe(),o={[n]:r,...this._headers},i={abortSignal:this._pollAbort.signal,headers:o,timeout:1e5,withCredentials:this._withCredentials};t===Ce.Binary&&(i.responseType="arraybuffer");const s=await this._getAccessToken();this._updateHeaderToken(i,s);const a=`${e}&_=${Date.now()}`;this._logger.log(Ee.Trace,`(LongPolling transport) polling: ${a}.`);const c=await this._httpClient.get(a,i);200!==c.statusCode?(this._logger.log(Ee.Error,`(LongPolling transport) Unexpected response code: ${c.statusCode}.`),this._closeError=new ye(c.statusText||"",c.statusCode),this._running=!1):this._running=!0,this._receiving=this._poll(this._url,i)}async _getAccessToken(){return this._accessTokenFactory?await this._accessTokenFactory():null}_updateHeaderToken(e,t){e.headers||(e.headers={}),t?e.headers[Pe.Authorization]=`Bearer ${t}`:e.headers[Pe.Authorization]&&delete e.headers[Pe.Authorization]}async _poll(e,t){try{for(;this._running;){const n=await this._getAccessToken();this._updateHeaderToken(t,n);try{const n=`${e}&_=${Date.now()}`;this._logger.log(Ee.Trace,`(LongPolling transport) polling: ${n}.`);const r=await this._httpClient.get(n,t);204===r.statusCode?(this._logger.log(Ee.Information,"(LongPolling transport) Poll terminated by server."),this._running=!1):200!==r.statusCode?(this._logger.log(Ee.Error,`(LongPolling transport) Unexpected response code: ${r.statusCode}.`),this._closeError=new ye(r.statusText||"",r.statusCode),this._running=!1):r.content?(this._logger.log(Ee.Trace,`(LongPolling transport) data received. ${$e(r.content,this._logMessageContent)}.`),this.onreceive&&this.onreceive(r.content)):this._logger.log(Ee.Trace,"(LongPolling transport) Poll timed out, reissuing.")}catch(e){this._running?e instanceof we?this._logger.log(Ee.Trace,"(LongPolling transport) Poll timed out, reissuing."):(this._closeError=e,this._running=!1):this._logger.log(Ee.Trace,`(LongPolling transport) Poll errored after shutdown: ${e.message}`)}}}finally{this._logger.log(Ee.Trace,"(LongPolling transport) Polling complete."),this.pollAborted||this._raiseOnClose()}}async send(e){return this._running?Le(this._logger,"LongPolling",this._httpClient,this._url,this._accessTokenFactory,e,this._logMessageContent,this._withCredentials,this._headers):Promise.reject(new Error("Cannot send until the transport is connected"))}async stop(){this._logger.log(Ee.Trace,"(LongPolling transport) Stopping polling."),this._running=!1,this._pollAbort.abort();try{await this._receiving,this._logger.log(Ee.Trace,`(LongPolling transport) sending DELETE request to ${this._url}.`);const e={},[t,n]=Oe();e[t]=n;const r={headers:{...e,...this._headers},withCredentials:this._withCredentials},o=await this._getAccessToken();this._updateHeaderToken(r,o),await this._httpClient.delete(this._url,r),this._logger.log(Ee.Trace,"(LongPolling transport) DELETE request sent.")}finally{this._logger.log(Ee.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(Ee.Trace,e),this.onclose(this._closeError)}}}class Je{constructor(e,t,n,r,o,i,s){this._httpClient=e,this._accessTokenFactory=t,this._logger=n,this._logMessageContent=r,this._withCredentials=i,this._eventSourceConstructor=o,this._headers=s,this.onreceive=null,this.onclose=null}async connect(e,t){if(Ne.isRequired(e,"url"),Ne.isRequired(t,"transferFormat"),Ne.isIn(t,Ce,"transferFormat"),this._logger.log(Ee.Trace,"(SSE transport) Connecting."),this._url=e,this._accessTokenFactory){const t=await this._accessTokenFactory();t&&(e+=(e.indexOf("?")<0?"?":"&")+`access_token=${encodeURIComponent(t)}`)}return new Promise(((n,r)=>{let o,i=!1;if(t===Ce.Text){if(Be.isBrowser||Be.isWebWorker)o=new this._eventSourceConstructor(e,{withCredentials:this._withCredentials});else{const t=this._httpClient.getCookieString(e),n={};n.Cookie=t;const[r,i]=Oe();n[r]=i,o=new this._eventSourceConstructor(e,{withCredentials:this._withCredentials,headers:{...n,...this._headers}})}try{o.onmessage=e=>{if(this.onreceive)try{this._logger.log(Ee.Trace,`(SSE transport) data received. ${$e(e.data,this._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(Ee.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?Le(this._logger,"SSE",this._httpClient,this._url,this._accessTokenFactory,e,this._logMessageContent,this._withCredentials,this._headers):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 Ke{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){if(Ne.isRequired(e,"url"),Ne.isRequired(t,"transferFormat"),Ne.isIn(t,Ce,"transferFormat"),this._logger.log(Ee.Trace,"(WebSockets transport) Connecting."),this._accessTokenFactory){const t=await this._accessTokenFactory();t&&(e+=(e.indexOf("?")<0?"?":"&")+`access_token=${encodeURIComponent(t)}`)}return new Promise(((n,r)=>{let o;e=e.replace(/^http/,"ws"),this._httpClient.getCookieString(e);let i=!1;o||(o=new this._webSocketConstructor(e)),t===Ce.Binary&&(o.binaryType="arraybuffer"),o.onopen=t=>{this._logger.log(Ee.Information,`WebSocket connected to ${e}.`),this._webSocket=o,i=!0,n()},o.onerror=e=>{let t=null;t="undefined"!=typeof ErrorEvent&&e instanceof ErrorEvent?e.error:"There was an error with the transport",this._logger.log(Ee.Information,`(WebSockets transport) ${t}.`)},o.onmessage=e=>{if(this._logger.log(Ee.Trace,`(WebSockets transport) data received. ${$e(e.data,this._logMessageContent)}.`),this.onreceive)try{this.onreceive(e.data)}catch(e){return void this._close(e)}},o.onclose=e=>{if(i)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(Ee.Trace,`(WebSockets transport) sending data. ${$e(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(Ee.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 Ve{constructor(e,t={}){var n;if(this._stopPromiseResolver=()=>{},this.features={},this._negotiateVersion=1,Ne.isRequired(e,"url"),this._logger=void 0===(n=t.logger)?new Fe(Ee.Information):null===n?Ae.instance:void 0!==n.log?n:new Fe(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,"undefined"==typeof WebSocket||t.WebSocket||(t.WebSocket=WebSocket),"undefined"==typeof EventSource||t.EventSource||(t.EventSource=EventSource),this._httpClient=t.httpClient||new Re(this._logger),this._connectionState="Disconnected",this._connectionStarted=!1,this._options=t,this.onreceive=null,this.onclose=null}async start(e){if(e=e||Ce.Binary,Ne.isIn(e,Ce,"transferFormat"),this._logger.log(Ee.Debug,`Starting connection with transfer format '${Ce[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(Ee.Error,e),await this._stopPromise,Promise.reject(new Error(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(Ee.Error,e),Promise.reject(new Error(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 Xe(this.transport)),this._sendQueue.send(e))}async stop(e){return"Disconnected"===this._connectionState?(this._logger.log(Ee.Debug,`Call to HttpConnection.stop(${e}) ignored because the connection is already in the disconnected state.`),Promise.resolve()):"Disconnecting"===this._connectionState?(this._logger.log(Ee.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(Ee.Error,`HttpConnection.transport.stop() threw error '${e}'.`),this._stopConnection()}this.transport=void 0}else this._logger.log(Ee.Debug,"HttpConnection.transport is undefined in HttpConnection.stop() because start() failed.")}async _startInternal(e){let t=this.baseUrl;this._accessTokenFactory=this._options.accessTokenFactory;try{if(this._options.skipNegotiation){if(this._options.transport!==Se.WebSockets)throw new Error("Negotiation can only be skipped when using the WebSocket transport directly.");this.transport=this._constructTransport(Se.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 Error("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}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 qe&&(this.features.inherentKeepAlive=!0),"Connecting"===this._connectionState&&(this._logger.log(Ee.Debug,"The HttpConnection connected successfully."),this._connectionState="Connected")}catch(e){return this._logger.log(Ee.Error,"Failed to start the connection: "+e),this._connectionState="Disconnected",this.transport=void 0,this._stopPromiseResolver(),Promise.reject(e)}}async _getNegotiationResponse(e){const t={};if(this._accessTokenFactory){const e=await this._accessTokenFactory();e&&(t[Pe.Authorization]=`Bearer ${e}`)}const[n,r]=Oe();t[n]=r;const o=this._resolveNegotiateUrl(e);this._logger.log(Ee.Debug,`Sending negotiation request: ${o}.`);try{const e=await this._httpClient.post(o,{content:"",headers:{...t,...this._options.headers},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 ye&&404===e.statusCode&&(t+=" Either this is not a SignalR endpoint or there is a proxy blocking the connection."),this._logger.log(Ee.Error,t),Promise.reject(new Error(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(Ee.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: ${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(Ee.Error,`Failed to start the transport '${n.transport}': ${e}`),a=void 0,i.push(`${n.transport} failed: ${e}`),"Connecting"!==this._connectionState){const e="Failed to select transport before stop() was called.";return this._logger.log(Ee.Debug,e),Promise.reject(new Error(e))}}}}return i.length>0?Promise.reject(new Error(`Unable to connect to the server with any of the available transports. ${i.join(" ")}`)):Promise.reject(new Error("None of the transports supported by the client are supported by the server."))}_constructTransport(e){switch(e){case Se.WebSockets:if(!this._options.WebSocket)throw new Error("'WebSocket' is not supported in your environment.");return new Ke(this._httpClient,this._accessTokenFactory,this._logger,this._options.logMessageContent||!1,this._options.WebSocket,this._options.headers||{});case Se.ServerSentEvents:if(!this._options.EventSource)throw new Error("'EventSource' is not supported in your environment.");return new Je(this._httpClient,this._accessTokenFactory,this._logger,this._options.logMessageContent||!1,this._options.EventSource,this._options.withCredentials,this._options.headers||{});case Se.LongPolling:return new qe(this._httpClient,this._accessTokenFactory,this._logger,this._options.logMessageContent||!1,this._options.withCredentials,this._options.headers||{});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=Se[e.transport];if(null==r)return this._logger.log(Ee.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(Ee.Debug,`Skipping transport '${Se[r]}' because it was disabled by the client.`),new Error(`'${Se[r]}' is disabled by the client.`);if(!(e.transferFormats.map((e=>Ce[e])).indexOf(n)>=0))return this._logger.log(Ee.Debug,`Skipping transport '${Se[r]}' because it does not support the requested transfer format '${Ce[n]}'.`),new Error(`'${Se[r]}' does not support ${Ce[n]}.`);if(r===Se.WebSockets&&!this._options.WebSocket||r===Se.ServerSentEvents&&!this._options.EventSource)return this._logger.log(Ee.Debug,`Skipping transport '${Se[r]}' because it is not supported in your environment.'`),new Error(`'${Se[r]}' is not supported in your environment.`);this._logger.log(Ee.Debug,`Selecting transport '${Se[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(Ee.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(Ee.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(Ee.Error,`Connection disconnected with error '${e}'.`):this._logger.log(Ee.Information,"Connection disconnected."),this._sendQueue&&(this._sendQueue.stop().catch((e=>{this._logger.log(Ee.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(Ee.Error,`HttpConnection.onclose(${e}) threw error '${t}'.`)}}}else this._logger.log(Ee.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(!Be.isBrowser||!window.document)throw new Error(`Cannot resolve '${e}'.`);const t=window.document.createElement("a");return t.href=e,this._logger.log(Ee.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 Xe{constructor(e){this._transport=e,this._buffer=[],this._executing=!0,this._sendBufferedData=new Ye,this._transportResult=new Ye,this._sendLoopPromise=this._sendLoop()}send(e){return this._bufferData(e),this._transportResult||(this._transportResult=new Ye),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 Ye;const e=this._transportResult;this._transportResult=void 0;const t="string"==typeof this._buffer[0]?this._buffer.join(""):Xe._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 Ye{constructor(){this.promise=new Promise(((e,t)=>[this._resolver,this._rejecter]=[e,t]))}resolve(){this._resolver()}reject(e){this._rejecter(e)}}class Ge{static write(e){return`${e}${Ge.RecordSeparator}`}static parse(e){if(e[e.length-1]!==Ge.RecordSeparator)throw new Error("Message is incomplete.");const t=e.split(Ge.RecordSeparator);return t.pop(),t}}Ge.RecordSeparatorCode=30,Ge.RecordSeparator=String.fromCharCode(Ge.RecordSeparatorCode);class Qe{writeHandshakeRequest(e){return Ge.write(JSON.stringify(e))}parseHandshakeResponse(e){let t,n;if(Me(e)){const r=new Uint8Array(e),o=r.indexOf(Ge.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(Ge.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=Ge.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"}(Ie||(Ie={}));class Ze{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 He(this,e)}}!function(e){e.Disconnected="Disconnected",e.Connecting="Connecting",e.Connected="Connected",e.Disconnecting="Disconnecting",e.Reconnecting="Reconnecting"}(ke||(ke={}));class et{constructor(e,t,n,r){this._nextKeepAlive=0,Ne.isRequired(e,"connection"),Ne.isRequired(t,"logger"),Ne.isRequired(n,"protocol"),this.serverTimeoutInMilliseconds=3e4,this.keepAliveIntervalInMilliseconds=15e3,this._logger=t,this._protocol=n,this.connection=e,this._reconnectPolicy=r,this._handshakeProtocol=new Qe,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=ke.Disconnected,this._connectionStarted=!1,this._cachedPingMessage=this._protocol.writeMessage({type:Ie.Ping})}static create(e,t,n,r){return new et(e,t,n,r)}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!==ke.Disconnected&&this._connectionState!==ke.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!==ke.Disconnected)return Promise.reject(new Error("Cannot start a HubConnection that is not in the 'Disconnected' state."));this._connectionState=ke.Connecting,this._logger.log(Ee.Debug,"Starting HubConnection.");try{await this._startInternal(),this._connectionState=ke.Connected,this._connectionStarted=!0,this._logger.log(Ee.Debug,"HubConnection connected successfully.")}catch(e){return this._connectionState=ke.Disconnected,this._logger.log(Ee.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(Ee.Debug,"Sending handshake request."),await this._sendMessage(this._handshakeProtocol.writeHandshakeRequest(t)),this._logger.log(Ee.Information,`Using HubProtocol '${this._protocol.name}'.`),this._cleanupTimeout(),this._resetTimeoutPeriod(),this._resetKeepAliveInterval(),await e,this._stopDuringStartError)throw this._stopDuringStartError}catch(e){throw this._logger.log(Ee.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){return this._connectionState===ke.Disconnected?(this._logger.log(Ee.Debug,`Call to HubConnection.stop(${e}) ignored because it is already in the disconnected state.`),Promise.resolve()):this._connectionState===ke.Disconnecting?(this._logger.log(Ee.Debug,`Call to HttpConnection.stop(${e}) ignored because the connection is already in the disconnecting state.`),this._stopPromise):(this._connectionState=ke.Disconnecting,this._logger.log(Ee.Debug,"Stopping HubConnection."),this._reconnectDelayHandle?(this._logger.log(Ee.Debug,"Connection stopped during reconnect delay. Done reconnecting."),clearTimeout(this._reconnectDelayHandle),this._reconnectDelayHandle=void 0,this._completeClose(),Promise.resolve()):(this._cleanupTimeout(),this._cleanupPingTimer(),this._stopDuringStartError=e||new Error("The connection was stopped before the hub handshake could complete."),this.connection.stop(e)))}stream(e,...t){const[n,r]=this._replaceStreamingParams(t),o=this._createStreamInvocation(e,t,r);let i;const s=new Ze;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===Ie.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===Ie.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 Ie.Invocation:this._invokeClientMethod(e);break;case Ie.StreamItem:case Ie.Completion:{const t=this._callbacks[e.invocationId];t&&(e.type===Ie.Completion&&delete this._callbacks[e.invocationId],t(e));break}case Ie.Ping:break;case Ie.Close:{this._logger.log(Ee.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(Ee.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(Ee.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(Ee.Error,e);const n=new Error(e);throw this._handshakeRejecter(n),n}return this._logger.log(Ee.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===ke.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."))}_invokeClientMethod(e){const t=this._methods[e.target.toLowerCase()];if(t){try{t.forEach((t=>t.apply(this,e.arguments)))}catch(t){this._logger.log(Ee.Error,`A callback for the method ${e.target.toLowerCase()} threw error '${t}'.`)}if(e.invocationId){const e="Server requested a response, which is not supported in this version of the client.";this._logger.log(Ee.Error,e),this._stopPromise=this._stopInternal(new Error(e))}}else this._logger.log(Ee.Warning,`No client method with the name '${e.target}' found.`)}_connectionClosed(e){this._logger.log(Ee.Debug,`HubConnection.connectionClosed(${e}) called while in state ${this._connectionState}.`),this._stopDuringStartError=this._stopDuringStartError||e||new Error("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===ke.Disconnecting?this._completeClose(e):this._connectionState===ke.Connected&&this._reconnectPolicy?this._reconnect(e):this._connectionState===ke.Connected&&this._completeClose(e)}_completeClose(e){if(this._connectionStarted){this._connectionState=ke.Disconnected,this._connectionStarted=!1;try{this._closedCallbacks.forEach((t=>t.apply(this,[e])))}catch(t){this._logger.log(Ee.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(Ee.Debug,"Connection not reconnecting because the IRetryPolicy returned null on the first reconnect attempt."),void this._completeClose(e);if(this._connectionState=ke.Reconnecting,e?this._logger.log(Ee.Information,`Connection reconnecting because of error '${e}'.`):this._logger.log(Ee.Information,"Connection reconnecting."),0!==this._reconnectingCallbacks.length){try{this._reconnectingCallbacks.forEach((t=>t.apply(this,[e])))}catch(t){this._logger.log(Ee.Error,`An onreconnecting callback called with error '${e}' threw error '${t}'.`)}if(this._connectionState!==ke.Reconnecting)return void this._logger.log(Ee.Debug,"Connection left the reconnecting state in onreconnecting callback. Done reconnecting.")}for(;null!==o;){if(this._logger.log(Ee.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!==ke.Reconnecting)return void this._logger.log(Ee.Debug,"Connection left the reconnecting state during reconnect delay. Done reconnecting.");try{if(await this._startInternal(),this._connectionState=ke.Connected,this._logger.log(Ee.Information,"HubConnection reconnected successfully."),0!==this._reconnectedCallbacks.length)try{this._reconnectedCallbacks.forEach((e=>e.apply(this,[this.connection.connectionId])))}catch(e){this._logger.log(Ee.Error,`An onreconnected callback called with connectionId '${this.connection.connectionId}; threw error '${e}'.`)}return}catch(e){if(this._logger.log(Ee.Information,`Reconnect attempt failed because of error '${e}'.`),this._connectionState!==ke.Reconnecting)return this._logger.log(Ee.Debug,`Connection moved to the '${this._connectionState}' from the reconnecting state during reconnect attempt. Done reconnecting.`),void(this._connectionState===ke.Disconnecting&&this._completeClose());r=e instanceof Error?e:new Error(e.toString()),o=this._getNextRetryDelay(n++,Date.now()-t,r)}}this._logger.log(Ee.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(Ee.Error,`IRetryPolicy.nextRetryDelayInMilliseconds(${e}, ${t}) threw error '${n}'.`),null}}_cancelCallbacksWithError(e){const t=this._callbacks;this._callbacks={},Object.keys(t).forEach((n=>{(0,t[n])(null,e)}))}_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:Ie.Invocation}:{arguments:t,target:e,type:Ie.Invocation};{const n=this._invocationId;return this._invocationId++,0!==r.length?{arguments:t,invocationId:n.toString(),streamIds:r,target:e,type:Ie.Invocation}:{arguments:t,invocationId:n.toString(),target:e,type:Ie.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 ut=ot?new TextDecoder:null,dt=ot?"undefined"!=typeof process&&"force"!==process.env.TEXT_DECODER?200:0:it,pt=function(e,t){this.type=e,this.data=t};function ft(e,t,n){var r=Math.floor(n/4294967296),o=n;e.setUint32(t,r),e.setUint32(t+4,o)}function gt(e,t){return 4294967296*e.getInt32(t)+e.getUint32(t+4)}var mt={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),ft(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:gt(t,4),nsec:t.getUint32(0)};default:throw new Error("Unrecognized data size for timestamp: "+e.length)}}(e);return new Date(1e3*t.sec+t.nsec/1e6)}},yt=function(){function e(){this.builtInEncoders=[],this.builtInDecoders=[],this.encoders=[],this.decoders=[],this.register(mt)}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 "+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: "+e+" bytes in UTF-8");this.writeU8(219),this.writeU32(e)}},e.prototype.encodeString=function(e){if(e.length>ct){var t=st(e);this.ensureBufferSizeToWrite(5+t),this.writeStringHeader(t),lt(e,this.bytes,this.pos),this.pos+=t}else t=st(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: "+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: "+t);this.writeU8(198),this.writeU32(t)}var n=wt(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: "+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=ht(e,t,n),i=Uint8Array.prototype.slice.call(e,t,t+n);return this.store(i,o),o},e}(),St=(_t=function(e,t){return(_t=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])})(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}_t(e,t),e.prototype=null===t?Object.create(t):(n.prototype=t.prototype,new n)}),Ct=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]1||a(e,t)}))})}function a(e,t){try{(n=o[e](t)).value instanceof kt?Promise.resolve(n.value.v).then(c,l):h(i[0][2],n)}catch(e){h(i[0][3],e)}var n}function c(e){a("next",e)}function l(e){a("throw",e)}function h(e,t){e(t),i.shift(),i.length&&a(i[0][0],i[0][1])}},xt=new DataView(new ArrayBuffer(0)),Dt=new Uint8Array(xt.buffer),Rt=function(){try{xt.getInt8(0)}catch(e){return e.constructor}throw new Error("never reached")}(),Pt=new Rt("Insufficient data"),Ut=4294967295,At=new Et,Nt=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 St(t,e),t}(Error),Bt=function(){function e(e,t,n,r,o,i,s,a){void 0===e&&(e=yt.defaultCodec),void 0===t&&(t=void 0),void 0===n&&(n=Ut),void 0===r&&(r=Ut),void 0===o&&(o=Ut),void 0===i&&(i=Ut),void 0===s&&(s=Ut),void 0===a&&(a=At),this.extensionCodec=e,this.context=t,this.maxStrLength=n,this.maxBinLength=r,this.maxArrayLength=o,this.maxMapLength=i,this.maxExtLength=s,this.keyDecoder=a,this.totalPos=0,this.pos=0,this.view=xt,this.bytes=Dt,this.headByte=-1,this.stack=[]}return e.prototype.reinitializeState=function(){this.totalPos=0,this.headByte=-1,this.stack.length=0},e.prototype.setBuffer=function(e){this.bytes=wt(e),this.view=function(e){if(e instanceof ArrayBuffer)return new DataView(e);var t=wt(e);return new DataView(t.buffer,t.byteOffset,t.byteLength)}(this.bytes),this.pos=0},e.prototype.appendBuffer=function(e){if(-1!==this.headByte||this.hasRemaining()){var t=this.bytes.subarray(this.pos),n=wt(e),r=new Uint8Array(t.length+n.length);r.set(t),r.set(n,t.length),this.setBuffer(r)}else this.setBuffer(e)},e.prototype.hasRemaining=function(e){return void 0===e&&(e=1),this.view.byteLength-this.pos>=e},e.prototype.createExtraByteError=function(e){var t=this.view,n=this.pos;return new RangeError("Extra "+(t.byteLength-n)+" of "+t.byteLength+" byte(s) found at buffer["+e+"]")},e.prototype.decode=function(e){this.reinitializeState(),this.setBuffer(e);var t=this.doDecodeSync();if(this.hasRemaining())throw this.createExtraByteError(this.pos);return t},e.prototype.decodeMulti=function(e){return Ct(this,(function(t){switch(t.label){case 0:this.reinitializeState(),this.setBuffer(e),t.label=1;case 1:return this.hasRemaining()?[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,u,d;return Ct(this,(function(p){switch(p.label){case 0:i=!1,p.label=1;case 1:p.trys.push([1,6,7,12]),t=It(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 Rt))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())throw this.createExtraByteError(this.totalPos);return[2,s]}throw h=(l=this).headByte,u=l.pos,d=l.totalPos,new RangeError("Insufficient data in parsing "+bt(h)+" at "+d+" ("+u+" 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 Tt(this,arguments,(function(){var n,r,o,i,s,a,c,l,h;return Ct(this,(function(u){switch(u.label){case 0:n=t,r=-1,u.label=1;case 1:u.trys.push([1,13,14,19]),o=It(e),u.label=2;case 2:return[4,kt(o.next())];case 3:if((i=u.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()),u.label=4;case 4:u.trys.push([4,9,,10]),u.label=5;case 5:return[4,kt(this.doDecodeSync())];case 6:return[4,u.sent()];case 7:return u.sent(),0==--r?[3,8]:[3,5];case 8:return[3,10];case 9:if(!((a=u.sent())instanceof Rt))throw a;return[3,10];case 10:this.totalPos+=this.pos,u.label=11;case 11:return[3,2];case 12:return[3,19];case 13:return c=u.sent(),l={error:c},[3,19];case 14:return u.trys.push([14,,17,18]),i&&!i.done&&(h=o.return)?[4,kt(h.call(o))]:[3,16];case 15:u.sent(),u.label=16;case 16:return[3,18];case 17:if(l)throw l.error;return[7];case 18:return[7];case 19:return[2]}}))}))},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 Nt("Unrecognized type byte: "+bt(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 Nt("The type of key must be string or number but "+typeof t);if("__proto__"===t)throw new Nt("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 Nt("Unrecognized array type byte: "+bt(e))}},e.prototype.pushMapState=function(e){if(e>this.maxMapLength)throw new Nt("Max length exceeded: map length ("+e+") > maxMapLengthLength ("+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 Nt("Max length exceeded: array length ("+e+") > maxArrayLength ("+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 Nt("Max length exceeded: UTF-8 byte length ("+e+") > maxStrLength ("+this.maxStrLength+")");if(this.bytes.byteLengthdt?function(e,t,n){var r=e.subarray(t,t+n);return ut.decode(r)}(this.bytes,o,e):ht(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 Nt("Max length exceeded: bin length ("+e+") > maxBinLength ("+this.maxBinLength+")");if(!this.hasRemaining(e+t))throw Pt;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 Nt("Max length exceeded: ext length ("+e+") > maxExtLength ("+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=gt(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 $t{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 Mt=new Uint8Array([145,Ie.Ping]);class Lt{constructor(e){this.name="messagepack",this.version=1,this.transferFormat=Ce.Binary,this._errorResult=1,this._voidResult=2,this._nonVoidResult=3,e=e||{},this._encoder=new vt(e.extensionCodec,e.context,e.maxDepth,e.initialBufferSize,e.sortKeys,e.forceFloat32,e.ignoreUndefined,e.forceIntegerToFloat),this._decoder=new Bt(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=Ae.instance);const r=$t.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 Ie.Invocation:return this._writeInvocation(e);case Ie.StreamInvocation:return this._writeStreamInvocation(e);case Ie.StreamItem:return this._writeStreamItem(e);case Ie.Completion:return this._writeCompletion(e);case Ie.Ping:return $t.write(Mt);case Ie.CancelInvocation:return this._writeCancelInvocation(e);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 Ie.Invocation:return this._createInvocationMessage(this._readHeaders(n),n);case Ie.StreamItem:return this._createStreamItemMessage(this._readHeaders(n),n);case Ie.Completion:return this._createCompletionMessage(this._readHeaders(n),n);case Ie.Ping:return this._createPingMessage(n);case Ie.Close:return this._createCloseMessage(n);default:return t.log(Ee.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:Ie.Close}}_createPingMessage(e){if(e.length<1)throw new Error("Invalid payload for Ping message.");return{type:Ie.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:Ie.Invocation}:{arguments:t[4],headers:e,streamIds:[],target:t[3],type:Ie.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:Ie.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:Ie.Completion}}_writeInvocation(e){let t;return t=e.streamIds?this._encoder.encode([Ie.Invocation,e.headers||{},e.invocationId||null,e.target,e.arguments,e.streamIds]):this._encoder.encode([Ie.Invocation,e.headers||{},e.invocationId||null,e.target,e.arguments]),$t.write(t.slice())}_writeStreamInvocation(e){let t;return t=e.streamIds?this._encoder.encode([Ie.StreamInvocation,e.headers||{},e.invocationId,e.target,e.arguments,e.streamIds]):this._encoder.encode([Ie.StreamInvocation,e.headers||{},e.invocationId,e.target,e.arguments]),$t.write(t.slice())}_writeStreamItem(e){const t=this._encoder.encode([Ie.StreamItem,e.headers||{},e.invocationId,e.item]);return $t.write(t.slice())}_writeCompletion(e){const t=e.error?this._errorResult:e.result?this._nonVoidResult:this._voidResult;let n;switch(t){case this._errorResult:n=this._encoder.encode([Ie.Completion,e.headers||{},e.invocationId,t,e.error]);break;case this._voidResult:n=this._encoder.encode([Ie.Completion,e.headers||{},e.invocationId,t]);break;case this._nonVoidResult:n=this._encoder.encode([Ie.Completion,e.headers||{},e.invocationId,t,e.result])}return $t.write(n.slice())}_writeCancelInvocation(e){const t=this._encoder.encode([Ie.CancelInvocation,e.headers||{},e.invocationId]);return $t.write(t.slice())}_readHeaders(e){const t=e[1];if("object"!=typeof t)throw new Error("Invalid headers.");return t}}let Ht=!1;const Ft="function"==typeof TextDecoder?new TextDecoder("utf-8"):null,Ot=Ft?Ft.decode.bind(Ft):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("")},jt=Math.pow(2,32),Wt=Math.pow(2,21)-1;function zt(e,t){return e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24}function qt(e,t){return e[t]+(e[t+1]<<8)+(e[t+2]<<16)+(e[t+3]<<24>>>0)}function Jt(e,t){const n=qt(e,t+4);if(n>Wt)throw new Error(`Cannot read uint64 with high order part ${n}, because the result would exceed Number.MAX_SAFE_INTEGER.`);return n*jt+qt(e,t)}class Kt{constructor(e){this.batchData=e;const t=new Gt(e);this.arrayRangeReader=new Qt(e),this.arrayBuilderSegmentReader=new Zt(e),this.diffReader=new Vt(e),this.editReader=new Xt(e,t),this.frameReader=new Yt(e,t)}updatedComponents(){return zt(this.batchData,this.batchData.length-20)}referenceFrames(){return zt(this.batchData,this.batchData.length-16)}disposedComponentIds(){return zt(this.batchData,this.batchData.length-12)}disposedEventHandlerIds(){return zt(this.batchData,this.batchData.length-8)}updatedComponentsEntry(e,t){const n=e+4*t;return zt(this.batchData,n)}referenceFramesEntry(e,t){return e+20*t}disposedComponentIdsEntry(e,t){const n=e+4*t;return zt(this.batchData,n)}disposedEventHandlerIdsEntry(e,t){const n=e+8*t;return Jt(this.batchData,n)}}class Vt{constructor(e){this.batchDataUint8=e}componentId(e){return zt(this.batchDataUint8,e)}edits(e){return e+4}editsEntry(e,t){return e+16*t}}class Xt{constructor(e,t){this.batchDataUint8=e,this.stringReader=t}editType(e){return zt(this.batchDataUint8,e)}siblingIndex(e){return zt(this.batchDataUint8,e+4)}newTreeIndex(e){return zt(this.batchDataUint8,e+8)}moveToSiblingIndex(e){return zt(this.batchDataUint8,e+8)}removedAttributeName(e){const t=zt(this.batchDataUint8,e+12);return this.stringReader.readString(t)}}class Yt{constructor(e,t){this.batchDataUint8=e,this.stringReader=t}frameType(e){return zt(this.batchDataUint8,e)}subtreeLength(e){return zt(this.batchDataUint8,e+4)}elementReferenceCaptureId(e){const t=zt(this.batchDataUint8,e+4);return this.stringReader.readString(t)}componentId(e){return zt(this.batchDataUint8,e+8)}elementName(e){const t=zt(this.batchDataUint8,e+8);return this.stringReader.readString(t)}textContent(e){const t=zt(this.batchDataUint8,e+4);return this.stringReader.readString(t)}markupContent(e){const t=zt(this.batchDataUint8,e+4);return this.stringReader.readString(t)}attributeName(e){const t=zt(this.batchDataUint8,e+4);return this.stringReader.readString(t)}attributeValue(e){const t=zt(this.batchDataUint8,e+8);return this.stringReader.readString(t)}attributeEventHandlerId(e){return Jt(this.batchDataUint8,e+12)}}class Gt{constructor(e){this.batchDataUint8=e,this.stringTableStartIndex=zt(e,e.length-4)}readString(e){if(-1===e)return null;{const n=zt(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(en.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(en.Debug,`Waiting for batch ${this.nextBatchId}. Batch ${e} not processed.`);try{this.nextBatchId++,this.logger.log(en.Debug,`Applying batch ${e}.`),function(e,t){const n=Q[e];if(!n)throw new Error(`There is no browser renderer with ID ${e}.`);const r=t.arrayRangeReader,o=t.updatedComponents(),i=r.values(o),s=r.count(o),a=t.referenceFrames(),c=r.values(a),l=t.diffReader;for(let e=0;e=this.minLevel){const n=`[${(new Date).toISOString()}] ${en[e]}: ${t}`;switch(e){case en.Critical:case en.Error:console.error(n);break;case en.Warning:console.warn(n);break;case en.Information:console.info(n);break;default:console.log(n)}}}}class on{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!==ke.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!==ke.Connected)return!1;const t=await e.invoke("StartCircuit",re.getBaseURI(),re.getLocationHref(),JSON.stringify(this.components.map((e=>e.toRecord()))),this.applicationState||"");return!!t&&(this.initialize(t),!0)}resolveElement(e){const t=Number.parseInt(e);if(Number.isNaN(t))throw new Error(`Invalid sequence number '${e}'.`);return function(e,t){if(!e.parentNode)throw new Error(`Comment not connected to the DOM ${e.textContent}`);const n=e.parentNode,r=k(n,!0),o=A(r);return Array.from(n.childNodes).forEach((e=>o.push(e))),e[C]=r,t&&(e[I]=t,k(t)),k(e)}(this.components[t].start,this.components[t].end)}}const sn={configureSignalR:e=>{},logLevel:en.Warning,reconnectionOptions:{maxRetries:8,retryIntervalMilliseconds:2e4,dialogId:"components-reconnect-modal"}};class an{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.modal.innerHTML='

Alternatively, reload

',this.message=this.modal.querySelector("h5"),this.button=this.modal.querySelector("button"),this.reloadParagraph=this.modal.querySelector("p"),this.loader=this.getLoader(),this.message.after(this.loader),this.button.addEventListener("click",(async()=>{this.show();try{await(null==fe?void 0:fe.reconnect)()||this.rejected()}catch(e){this.logger.log(en.Error,e),this.failed()}})),this.reloadParagraph.querySelector("a").addEventListener("click",(()=>location.reload()))}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",this.message.innerHTML="Reconnection failed. Try reloading the page if you're unable to reconnect.",this.message.querySelector("a").addEventListener("click",(()=>location.reload()))}rejected(){this.button.style.display="none",this.reloadParagraph.style.display="none",this.loader.style.display="none",this.message.innerHTML="Could not reconnect to the server. Reload the page to restore functionality.",this.message.querySelector("a").addEventListener("click",(()=>location.reload()))}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 cn{constructor(e,t,n){this.dialog=e,this.maxRetries=t,this.document=n,this.document=n;const r=this.document.getElementById(cn.MaxRetriesId);r&&(r.innerText=this.maxRetries.toString())}show(){this.removeClasses(),this.dialog.classList.add(cn.ShowClassName)}update(e){const t=this.document.getElementById(cn.CurrentAttemptId);t&&(t.innerText=e.toString())}hide(){this.removeClasses(),this.dialog.classList.add(cn.HideClassName)}failed(){this.removeClasses(),this.dialog.classList.add(cn.FailedClassName)}rejected(){this.removeClasses(),this.dialog.classList.add(cn.RejectedClassName)}removeClasses(){this.dialog.classList.remove(cn.ShowClassName,cn.HideClassName,cn.FailedClassName,cn.RejectedClassName)}}cn.ShowClassName="components-reconnect-show",cn.HideClassName="components-reconnect-hide",cn.FailedClassName="components-reconnect-failed",cn.RejectedClassName="components-reconnect-rejected",cn.MaxRetriesId="components-reconnect-max-retries",cn.CurrentAttemptId="components-reconnect-current-attempt";class ln{constructor(e,t,n){this._currentReconnectionProcess=null,this._logger=e,this._reconnectionDisplay=t,this._reconnectCallback=n||(()=>fe.reconnect())}onConnectionDown(e,t){if(!this._reconnectionDisplay){const t=document.getElementById(e.dialogId);this._reconnectionDisplay=t?new cn(t,e.maxRetries,document):new an(e.dialogId,e.maxRetries,document,this._logger)}this._currentReconnectionProcess||(this._currentReconnectionProcess=new hn(e,this._logger,this._reconnectCallback,this._reconnectionDisplay))}onConnectionUp(){this._currentReconnectionProcess&&(this._currentReconnectionProcess.dispose(),this._currentReconnectionProcess=null)}}class hn{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;thn.MaximumFirstRetryInterval?hn.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(en.Error,e)}}this.reconnectDisplay.failed()}delay(e){return new Promise((t=>setTimeout(t,e)))}}hn.MaximumFirstRetryInterval=3e3;const un=/^\s*Blazor-Component-State:(?[a-zA-Z0-9\+\/=]+)$/;function dn(e){var t;if(e.nodeType===Node.COMMENT_NODE){const n=e.textContent||"",r=un.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 gn(e,t){const n=e.currentElement;if(n&&n.nodeType===Node.COMMENT_NODE&&n.textContent){const r=fn.exec(n.textContent),o=r&&r.groups&&r.groups.descriptor;if(!o)return;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;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.");if(c){const e=mn(c,n);if(!e)throw new Error(`Could not find an end component comment for '${t}'`);return{type:r,assembly:o,typeName:i,parameterDefinitions:s&&atob(s),parameterValues:a&&atob(a),start:t,prerenderId:c,end:e}}return{type:r,assembly:o,typeName:i,parameterDefinitions:s&&atob(s),parameterValues:a&&atob(a),start:t}}}(r,n,e);case"server":return function(e,t,n){const{type:r,descriptor:o,sequence:i,prerenderId:s}=e;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)}'`);if(s){const e=mn(s,n);if(!e)throw new Error(`Could not find an end component comment for '${t}'`);return{type:r,sequence:i,descriptor:o,start:t,prerenderId:s,end:e}}return{type:r,sequence:i,descriptor:o,start:t}}}(r,n,e)}}catch(e){throw new Error(`Found malformed component comment at ${n.textContent}`)}}}function mn(e,t){for(;t.next()&&t.currentElement;){const n=t.currentElement;if(n.nodeType!==Node.COMMENT_NODE)continue;if(!n.textContent)continue;const r=fn.exec(n.textContent),o=r&&r[1];if(o)return yn(o,e),n}}function yn(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 wn{constructor(e){this.childNodes=e,this.currentIndex=-1,this.length=e.length}next(){return this.currentIndex++,this.currentIndexe.sequence-t.sequence))}(e)}(document),o=dn(document),i=new on(r,o||""),s=await Tn(t,n,i);if(!await i.startCircuit(s))return void n.log(en.Error,"Failed to start the circuit.");let a=!1;const c=()=>{if(!a){const e=new FormData,t=i.circuitId;e.append("circuitId",t),a=navigator.sendBeacon("_blazor/disconnect",e)}};fe.disconnect=c,window.addEventListener("unload",c,{capture:!1,once:!0}),fe.reconnect=async e=>{if(Cn)return!1;const r=e||await Tn(t,n,i);return await i.reconnect(r)?(t.reconnectionHandler.onConnectionUp(),!0):(n.log(en.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)},n.log(en.Information,"Blazor server-side application started.")}async function Tn(t,n,r){const i=new Lt;i.name="blazorpack";const s=(new rt).withUrl("_blazor").withHubProtocol(i);t.configureSignalR(s);const a=s.build();o=(e,t)=>{a.send("DispatchBrowserEvent",JSON.stringify(e),JSON.stringify(t))},fe._internal.navigationManager.listenForNavigationEvents(((e,t)=>a.send("OnLocationChanged",e,t))),a.on("JS.AttachComponent",((e,t)=>function(e,t,n){let r=Q[0];r||(r=Q[0]=new V(0)),r.attachRootComponentToLogicalElement(n,t)}(0,r.resolveElement(t),e))),a.on("JS.BeginInvokeJS",e.jsCallDispatcher.beginInvokeJSFromDotNet),a.on("JS.EndInvokeDotNet",e.jsCallDispatcher.endInvokeDotNetFromJS),a.on("JS.ReceiveByteArray",e.jsCallDispatcher.receiveByteArray);const c=tn.getOrCreate(n);a.on("JS.RenderBatch",((e,t)=>{n.log(en.Debug,`Received render batch with id ${e} and ${t.byteLength} bytes.`),c.processBatch(e,t,a)})),a.onclose((e=>!Cn&&t.reconnectionHandler.onConnectionDown(t.reconnectionOptions,e))),a.on("JS.Error",(e=>{Cn=!0,xn(a,e,n),async function(){let e=document.querySelector("#blazor-error-ui");e&&(e.style.display="block"),Ht||(Ht=!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()}})))}()})),fe._internal.forceCloseConnection=()=>a.stop();try{await a.start()}catch(e){xn(a,e,n)}return e.attachDispatcher({beginInvokeDotNetFromJS:(e,t,n,r,o)=>{a.send("BeginInvokeDotNetFromJS",e?e.toString():null,t,n,r||0,o)},endInvokeJSFromDotNet:(e,t,n)=>{a.send("EndInvokeJSFromDotNet",e,t,n)},sendByteArray:(e,t)=>{a.send("ReceiveByteArray",e,t)}}),a}function xn(e,t,n){n.log(en.Error,t),e&&e.stop()}fe.start=kn,document&&document.currentScript&&"false"!==document.currentScript.getAttribute("autostart")&&kn()})(); \ No newline at end of file +(()=>{"use strict";var e,t,n;!function(e){window.DotNet=e;const t=[],n=new Map;class r{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 o="__jsObjectId",i={},s={0:new r(window)};s[0]._cachedFunctions.set("import",(e=>("string"==typeof e&&e.startsWith("./")&&(e=document.baseURI+e.substr(2)),import(e))));let a,c=1,l=1,h=null;function u(e){t.push(e)}function d(e){if(e&&"object"==typeof e){s[l]=new r(e);const t={[o]:l};return l++,t}throw new Error(`Cannot create a JSObjectReference from the value '${e}'.`)}function p(e){if(!(e.buffer instanceof ArrayBuffer))throw new Error(`Cannot create a JSDataReference from the value '${e}' as it is not a valid ArrayBuffer.`);if(void 0===e.byteLength)throw new Error(`Cannot create a JSDataReference from the value '${e}' as it doesn't have a byteLength.`);const t={__jsDataReferenceLength:e.byteLength};try{const n=d(e);t.__jsObjectId=n.__jsObjectId}catch{throw new Error(`Cannot create a JSDataReference from the value '${e}'.`)}return t}function f(e){return e?JSON.parse(e,((e,n)=>t.reduce(((t,n)=>n(e,t)),n))):null}function g(e,t,n,r){const o=y();if(o.invokeDotNetFromJS){const i=k(r),s=o.invokeDotNetFromJS(e,t,n,i);return s?f(s):null}throw new Error("The current dispatcher does not support synchronous calls from JS to .NET. Use invokeMethodAsync instead.")}function m(e,t,n,r){if(e&&n)throw new Error(`For instance method calls, assemblyName should be null. Received '${e}'.`);const o=c++,s=new Promise(((e,t)=>{i[o]={resolve:e,reject:t}}));try{const i=k(r);y().beginInvokeDotNetFromJS(o,e,t,n,i)}catch(e){w(o,!1,e)}return s}function y(){if(null!==h)return h;throw new Error("No .NET call dispatcher has been set.")}function w(e,t,n){if(!i.hasOwnProperty(e))throw new Error(`There is no pending async call with ID ${e}.`);const r=i[e];delete i[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){let n=s[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 s[e]}e.attachDispatcher=function(e){h=e},e.attachReviver=u,e.invokeMethod=function(e,t,...n){return g(e,t,null,n)},e.invokeMethodAsync=function(e,t,...n){return m(e,t,null,n)},e.createJSObjectReference=d,e.createJSDataReference=p,e.disposeJSObjectReference=function(e){const t=e&&e.__jsObjectId;"number"==typeof t&&_(t)},function(e){e[e.Default=0]="Default",e[e.JSObjectReference=1]="JSObjectReference",e[e.JSDataReference=2]="JSDataReference"}(a=e.JSCallResultType||(e.JSCallResultType={})),e.jsCallDispatcher={findJSFunction:b,disposeJSObjectReferenceById:_,invokeJSFromDotNet:(e,t,n,r)=>{const o=C(b(e,r).apply(null,f(t)),n);return null==o?null:k(o)},beginInvokeJSFromDotNet:(e,t,n,r,o)=>{const i=new Promise((e=>{e(b(t,o).apply(null,f(n)))}));e&&i.then((t=>y().endInvokeJSFromDotNet(e,!0,k([e,!0,C(t,r)]))),(t=>y().endInvokeJSFromDotNet(e,!1,JSON.stringify([e,!1,v(t)]))))},endInvokeDotNetFromJS:(e,t,n)=>{const r=t?f(n):new Error(n);w(parseInt(e),t,r)},receiveByteArray:(e,t)=>{n.set(e,t)}};class E{constructor(e){this._id=e}invokeMethod(e,...t){return g(null,e,this._id,t)}invokeMethodAsync(e,...t){return m(null,e,this._id,t)}dispose(){m(null,"__Dispose",this._id,null).catch((e=>console.error(e)))}serializeAsArg(){return{__dotNetObject:this._id}}}const S="__byte[]";function C(e,t){switch(t){case a.Default:return e;case a.JSObjectReference:return d(e);case a.JSDataReference:return p(e);default:throw new Error(`Invalid JS call result type '${t}'.`)}}u((function(e,t){if(t&&"object"==typeof t){if(t.hasOwnProperty("__dotNetObject"))return new E(t.__dotNetObject);if(t.hasOwnProperty(o)){const e=t.__jsObjectId,n=s[e];if(n)return n.getWrappedObject();throw new Error(`JS object instance with Id '${e}' does not exist. It may have been disposed.`)}if(t.hasOwnProperty(S)){const e=t["__byte[]"],r=n.get(e);if(void 0===r)throw new Error(`Byte array index '${e}' does not exist.`);return r}}return t}));let I=0;function k(e){return I=0,JSON.stringify(e,T)}function T(e,t){if(t instanceof E)return t.serializeAsArg();if(t instanceof Uint8Array){h.sendByteArray(I,t);const e={[S]:I};return I++,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"}(n||(n={}));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}}let o;function i(e,t){if(!o)throw new Error("eventDispatcher not initialized. Call 'setEventDispatcher' to configure it.");o(e,t)}const s=new Map,a=new Map,c={createEventArgs:()=>({})},l=[];function h(e){return s.get(e)}function u(e){const t=s.get(e);return(null==t?void 0:t.browserEventName)||e}function d(e,t){e.forEach((e=>s.set(e,t)))}function p(e){const t=[];for(let n=0;n{return{...f(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}}),d(["focus","blur","focusin","focusout"],c),d(["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};var t}}),d(["contextmenu","click","mouseover","mouseout","mousemove","mousedown","mouseup","dblclick"],{createEventArgs:e=>f(e)}),d(["error"],{createEventArgs:e=>{return{message:(t=e).message,filename:t.filename,lineno:t.lineno,colno:t.colno};var t}}),d(["loadstart","timeout","abort","load","loadend","progress"],{createEventArgs:e=>{return{lengthComputable:(t=e).lengthComputable,loaded:t.loaded,total:t.total};var t}}),d(["touchcancel","touchend","touchmove","touchenter","touchleave","touchstart"],{createEventArgs:e=>{return{detail:(t=e).detail,touches:p(t.touches),targetTouches:p(t.targetTouches),changedTouches:p(t.changedTouches),ctrlKey:t.ctrlKey,shiftKey:t.shiftKey,altKey:t.altKey,metaKey:t.metaKey,type:t.type};var t}}),d(["gotpointercapture","lostpointercapture","pointercancel","pointerdown","pointerenter","pointerleave","pointermove","pointerout","pointerover","pointerup"],{createEventArgs:e=>{return{...f(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}}),d(["wheel","mousewheel"],{createEventArgs:e=>{return{...f(t=e),deltaX:t.deltaX,deltaY:t.deltaY,deltaZ:t.deltaZ,deltaMode:t.deltaMode};var t}}),d(["toggle"],c);const g=["date","datetime-local","month","time","week"],m=E(["abort","blur","change","error","focus","load","loadend","loadstart","mouseenter","mouseleave","progress","reset","scroll","submit","unload","toggle","DOMNodeInsertedIntoDocument","DOMNodeRemovedFromDocument"]),y={submit:!0},w=E(["click","dblclick","mousedown","mousemove","mouseup"]);class v{constructor(e){this.browserRendererId=e,this.afterClickCallbacks=[];const t=++v.nextEventDelegatorId;this.eventsCollectionKey=`_blazorEvents_${t}`,this.eventInfoStore=new b(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,a.get(n));var n;t&&t.forEach((t=>this.dispatchGlobalEventToAllElements(t,e))),"click"===e.type&&this.afterClickCallbacks.forEach((t=>t(e)))}dispatchGlobalEventToAllElements(e,t){let n=t.target,o=null,s=!1;const a=m.hasOwnProperty(e);let c=!1;for(;n;){const d=this.getEventHandlerInfosForElement(n,!1);if(d){const a=d.getHandler(e);if(a&&(l=n,u=t.type,!((l instanceof HTMLButtonElement||l instanceof HTMLInputElement||l instanceof HTMLTextAreaElement||l instanceof HTMLSelectElement)&&w.hasOwnProperty(u)&&l.disabled))){if(!s){const n=h(e);o=(null==n?void 0:n.createEventArgs)?n.createEventArgs(t):{},s=!0}y.hasOwnProperty(t.type)&&t.preventDefault(),i({browserRendererId:this.browserRendererId,eventHandlerId:a.eventHandlerId,eventName:e,eventFieldInfo:r.fromEvent(a.renderingComponentId,t)},o)}d.stopPropagation(e)&&(c=!0),d.preventDefault(e)&&t.preventDefault()}n=a||c?null:n.parentElement}var l,u}getEventHandlerInfosForElement(e,t){return e.hasOwnProperty(this.eventsCollectionKey)?e[this.eventsCollectionKey]:t?e[this.eventsCollectionKey]=new _:null}}v.nextEventDelegatorId=0;class b{constructor(e){this.globalListener=e,this.infosByEventHandlerId={},this.countByEventName={},l.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=u(e),this.countByEventName.hasOwnProperty(e))this.countByEventName[e]++;else{this.countByEventName[e]=1;const t=m.hasOwnProperty(e);document.addEventListener(e,this.globalListener,t)}}update(e,t){if(this.infosByEventHandlerId.hasOwnProperty(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=u(t.eventName);0==--this.countByEventName[n]&&(delete this.countByEventName[n],document.removeEventListener(n,this.globalListener))}return t}handleEventNameAliasAdded(e,t){if(this.countByEventName.hasOwnProperty(e)){const n=this.countByEventName[e];delete this.countByEventName[e],document.removeEventListener(e,this.globalListener),this.addGlobalListener(t),this.countByEventName[t]+=n-1}}}class _{constructor(){this.handlers={},this.preventDefaultFlags=null,this.stopPropagationFlags=null}getHandler(e){return this.handlers.hasOwnProperty(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 E(e){const t={};return e.forEach((e=>{t[e]=!0})),t}const S=O("_blazorLogicalChildren"),C=O("_blazorLogicalParent"),I=O("_blazorLogicalEnd");function k(e,t){if(e.childNodes.length>0&&!t)throw new Error("New logical elements must start empty, or allowExistingContents must be true");return S in e||(e[S]=[]),e}function T(e,t){const n=document.createComment("!");return D(n,e,t),n}function D(e,t,n){const r=e;if(e instanceof Comment&&A(r)&&A(r).length>0)throw new Error("Not implemented: inserting non-empty logical container");if(R(r))throw new Error("Not implemented: moving existing logical children");const o=A(t);if(n0;)x(n,0)}const r=n;r.parentNode.removeChild(r)}function R(e){return e[C]||null}function P(e,t){return A(e)[t]}function U(e){var t=B(e);return"http://www.w3.org/2000/svg"===t.namespaceURI&&"foreignObject"!==t.tagName}function A(e){return e[S]}function N(e,t){const n=A(e);t.forEach((e=>{e.moveRangeStart=n[e.fromSiblingIndex],e.moveRangeEnd=M(e.moveRangeStart)})),t.forEach((t=>{const r=t.moveToBeforeMarker=document.createComment("marker"),o=n[t.toSiblingIndex+1];o?o.parentNode.insertBefore(r,o):L(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 B(e){if(e instanceof Element)return e;if(e instanceof Comment)return e.parentNode;throw new Error("Not a valid logical element")}function $(e){const t=A(R(e));return t[Array.prototype.indexOf.call(t,e)+1]||null}function L(e,t){if(t instanceof Element)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=$(t);n?n.parentNode.insertBefore(e,n):L(e,R(t))}}}function M(e){if(e instanceof Element)return e;const t=$(e);if(t)return t.previousSibling;{const t=R(e);return t instanceof Element?t.lastChild:M(t)}}function O(e){return"function"==typeof Symbol?Symbol():e}function H(e){return`_bl_${e}`}e.attachReviver(((e,t)=>t&&"object"==typeof t&&t.hasOwnProperty("__internalId")&&"string"==typeof t.__internalId?function(e){const t=`[${H(e)}]`;return document.querySelector(t)}(t.__internalId):t));const F="_blazorSelectValue",j=document.createElement("template"),W=document.createElementNS("http://www.w3.org/2000/svg","g"),z={},q="__internal_",J="preventDefault_",K="stopPropagation_";class V{constructor(e){this.childComponentLocations={},this.eventDelegator=new v(e),this.eventDelegator.notifyAfterClick((e=>{if(!ee)return;if(0!==e.button||function(e){return e.ctrlKey||e.shiftKey||e.altKey||e.metaKey}(e))return;if(e.defaultPrevented)return;const t=function(e){const t=!window._blazorDisableComposedPath&&e.composedPath&&e.composedPath();if(t){for(let e=0;ese(!1))))},enableNavigationInterception:function(){ee=!0},navigateTo:oe,getBaseURI:()=>document.baseURI,getLocationHref:()=>location.href};function oe(e,t,n=!1){const r=ce(e);if(!t&&he(r))ie(r,!1,n);else if(t&&location.href===e){const t=e+"?";history.replaceState(null,"",t),location.replace(e)}else n?history.replaceState(null,"",r):location.href=e}function ie(e,t,n=!1){Z=!0,n?history.replaceState(null,"",e):history.pushState(null,"",e),se(t)}async function se(e){ne&&await ne(location.href,e)}let ae;function ce(e){return ae=ae||document.createElement("a"),ae.href=e,ae.href}function le(e,t){return e?e.tagName===t?e:le(e.parentElement,t):null}function he(e){const t=(n=document.baseURI).substr(0,n.lastIndexOf("/")+1);var n;return e.startsWith(t)}const ue={init:function(e,t,n,r=50){const o=pe(t);(o||document.documentElement).style.overflowAnchor="none";const i=new IntersectionObserver((function(r){r.forEach((r=>{var o;if(!r.isIntersecting)return;const i=t.getBoundingClientRect(),s=n.getBoundingClientRect().top-i.bottom,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`});i.observe(t),i.observe(n);const s=c(t),a=c(n);function c(e){const t=new MutationObserver((()=>{i.unobserve(e),i.observe(e)}));return t.observe(e,{attributes:!0}),t}de[e._id]={intersectionObserver:i,mutationObserverBefore:s,mutationObserverAfter:a}},dispose:function(e){const t=de[e._id];t&&(t.intersectionObserver.disconnect(),t.mutationObserverBefore.disconnect(),t.mutationObserverAfter.disconnect(),e.dispose(),delete de[e._id])}},de={};function pe(e){return e?"visible"!==getComputedStyle(e).overflowY?e:pe(e.parentElement):null}const fe={navigateTo:oe,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=a.get(t.browserEventName);n?n.push(e):a.set(t.browserEventName,[e]),l.forEach((n=>n(e,t.browserEventName)))}s.set(e,t)},_internal:{navigationManager:re,domWrapper:{focus:function(e,t){if(!(e instanceof HTMLElement))throw new Error("Unable to focus an invalid element.");e.focus({preventScroll:t})},focusBySelector:function(e){const t=document.querySelector(e);t&&(t.hasAttribute("tabindex")||(t.tabIndex=-1),t.focus())}},Virtualize:ue}};window.Blazor=fe;const ge=[0,2e3,1e4,3e4,null];class me{constructor(e){this._retryDelays=void 0!==e?[...e,null]:ge}nextRetryDelayInMilliseconds(e){return this._retryDelays[e.previousRetryCount]}}class ye extends Error{constructor(e,t){const n=new.target.prototype;super(`${e}: Status code '${t}'`),this.statusCode=t,this.__proto__=n}}class we extends Error{constructor(e="A timeout occurred."){const t=new.target.prototype;super(e),this.__proto__=t}}class ve extends Error{constructor(e="An abort occurred."){const t=new.target.prototype;super(e),this.__proto__=t}}class be{constructor(e,t,n){this.statusCode=e,this.statusText=t,this.content=n}}class _e{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""}}var Ee,Se,Ce,Ie,ke;!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"}(Ee||(Ee={}));class Te extends _e{constructor(e){if(super(),this._logger=e,"undefined"==typeof fetch){const e=require;this._jar=new(e("tough-cookie").CookieJar),this._fetchType=e("node-fetch"),this._fetchType=e("fetch-cookie")(this._fetchType,this._jar),this._abortControllerType=e("abort-controller")}else this._fetchType=fetch.bind(self),this._abortControllerType=AbortController}async send(e){if(e.abortSignal&&e.abortSignal.aborted)throw new ve;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 ve});let r,o=null;if(e.timeout){const r=e.timeout;o=setTimeout((()=>{t.abort(),this._logger.log(Ee.Warning,"Timeout from HTTP request."),n=new we}),r)}try{r=await this._fetchType(e.url,{body:e.content,cache:"no-cache",credentials:!0===e.withCredentials?"include":"same-origin",headers:{"Content-Type":"text/plain;charset=UTF-8","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(Ee.Warning,`Error from HTTP request. ${e}.`),e}finally{o&&clearTimeout(o),e.abortSignal&&(e.abortSignal.onabort=null)}if(!r.ok){const e=await De(r,"text");throw new ye(e||r.statusText,r.status)}const i=De(r,e.responseType),s=await i;return new be(r.status,r.statusText,s)}getCookieString(e){return""}}function De(e,t){let n;switch(t){case"arraybuffer":n=e.arrayBuffer();break;case"text":n=e.text();break;case"blob":case"document":case"json":throw new Error(`${t} is not supported.`);default:n=e.text()}return n}class xe extends _e{constructor(e){super(),this._logger=e}send(e){return e.abortSignal&&e.abortSignal.aborted?Promise.reject(new ve):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"),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 ve)}),e.timeout&&(r.timeout=e.timeout),r.onload=()=>{e.abortSignal&&(e.abortSignal.onabort=null),r.status>=200&&r.status<300?t(new be(r.status,r.statusText,r.response||r.responseText)):n(new ye(r.response||r.responseText||r.statusText,r.status))},r.onerror=()=>{this._logger.log(Ee.Warning,`Error from HTTP request. ${r.status}: ${r.statusText}.`),n(new ye(r.statusText,r.status))},r.ontimeout=()=>{this._logger.log(Ee.Warning,"Timeout from HTTP request."),n(new we)},r.send(e.content||"")})):Promise.reject(new Error("No url defined.")):Promise.reject(new Error("No method defined."))}}class Re extends _e{constructor(e){if(super(),"undefined"!=typeof fetch)this._httpClient=new Te(e);else{if("undefined"==typeof XMLHttpRequest)throw new Error("No usable HttpClient found.");this._httpClient=new xe(e)}}send(e){return e.abortSignal&&e.abortSignal.aborted?Promise.reject(new ve):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)}}class Pe{}Pe.Authorization="Authorization",Pe.Cookie="Cookie",function(e){e[e.None=0]="None",e[e.WebSockets=1]="WebSockets",e[e.ServerSentEvents=2]="ServerSentEvents",e[e.LongPolling=4]="LongPolling"}(Se||(Se={})),function(e){e[e.Text=1]="Text",e[e.Binary=2]="Binary"}(Ce||(Ce={}));class Ue{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 Ae{constructor(){}log(e,t){}}Ae.instance=new Ae;class Ne{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 Be{static get isBrowser(){return"object"==typeof window}static get isWebWorker(){return"object"==typeof self&&"importScripts"in self}static get isNode(){return!this.isBrowser&&!this.isWebWorker}}function $e(e,t){let n="";return Le(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 Le(e){return e&&"undefined"!=typeof ArrayBuffer&&(e instanceof ArrayBuffer||e.constructor&&"ArrayBuffer"===e.constructor.name)}async function Me(e,t,n,r,o,i,s,a,c){let l={};if(o){const e=await o();e&&(l={Authorization:`Bearer ${e}`})}const[h,u]=Fe();l[h]=u,e.log(Ee.Trace,`(${t} transport) sending data. ${$e(i,s)}.`);const d=Le(i)?"arraybuffer":"text",p=await n.post(r,{content:i,headers:{...l,...c},responseType:d,withCredentials:a});e.log(Ee.Trace,`(${t} transport) request complete. Response status: ${p.statusCode}.`)}class Oe{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 He{constructor(e){this._minLevel=e,this.out=console}log(e,t){if(e>=this._minLevel){const n=`[${(new Date).toISOString()}] ${Ee[e]}: ${t}`;switch(e){case Ee.Critical:case Ee.Error:this.out.error(n);break;case Ee.Warning:this.out.warn(n);break;case Ee.Information:this.out.info(n);break;default:this.out.log(n)}}}}function Fe(){let e="X-SignalR-User-Agent";return Be.isNode&&(e="User-Agent"),[e,je("0.0.0-DEV_BUILD",We(),Be.isNode?"NodeJS":"Browser",ze())]}function je(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 We(){if(!Be.isNode)return"";switch(process.platform){case"win32":return"Windows NT";case"darwin":return"macOS";case"linux":return"Linux";default:return process.platform}}function ze(){if(Be.isNode)return process.versions.node}class qe{constructor(e,t,n,r,o,i){this._httpClient=e,this._accessTokenFactory=t,this._logger=n,this._pollAbort=new Ue,this._logMessageContent=r,this._withCredentials=o,this._headers=i,this._running=!1,this.onreceive=null,this.onclose=null}get pollAborted(){return this._pollAbort.aborted}async connect(e,t){if(Ne.isRequired(e,"url"),Ne.isRequired(t,"transferFormat"),Ne.isIn(t,Ce,"transferFormat"),this._url=e,this._logger.log(Ee.Trace,"(LongPolling transport) Connecting."),t===Ce.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]=Fe(),o={[n]:r,...this._headers},i={abortSignal:this._pollAbort.signal,headers:o,timeout:1e5,withCredentials:this._withCredentials};t===Ce.Binary&&(i.responseType="arraybuffer");const s=await this._getAccessToken();this._updateHeaderToken(i,s);const a=`${e}&_=${Date.now()}`;this._logger.log(Ee.Trace,`(LongPolling transport) polling: ${a}.`);const c=await this._httpClient.get(a,i);200!==c.statusCode?(this._logger.log(Ee.Error,`(LongPolling transport) Unexpected response code: ${c.statusCode}.`),this._closeError=new ye(c.statusText||"",c.statusCode),this._running=!1):this._running=!0,this._receiving=this._poll(this._url,i)}async _getAccessToken(){return this._accessTokenFactory?await this._accessTokenFactory():null}_updateHeaderToken(e,t){e.headers||(e.headers={}),t?e.headers[Pe.Authorization]=`Bearer ${t}`:e.headers[Pe.Authorization]&&delete e.headers[Pe.Authorization]}async _poll(e,t){try{for(;this._running;){const n=await this._getAccessToken();this._updateHeaderToken(t,n);try{const n=`${e}&_=${Date.now()}`;this._logger.log(Ee.Trace,`(LongPolling transport) polling: ${n}.`);const r=await this._httpClient.get(n,t);204===r.statusCode?(this._logger.log(Ee.Information,"(LongPolling transport) Poll terminated by server."),this._running=!1):200!==r.statusCode?(this._logger.log(Ee.Error,`(LongPolling transport) Unexpected response code: ${r.statusCode}.`),this._closeError=new ye(r.statusText||"",r.statusCode),this._running=!1):r.content?(this._logger.log(Ee.Trace,`(LongPolling transport) data received. ${$e(r.content,this._logMessageContent)}.`),this.onreceive&&this.onreceive(r.content)):this._logger.log(Ee.Trace,"(LongPolling transport) Poll timed out, reissuing.")}catch(e){this._running?e instanceof we?this._logger.log(Ee.Trace,"(LongPolling transport) Poll timed out, reissuing."):(this._closeError=e,this._running=!1):this._logger.log(Ee.Trace,`(LongPolling transport) Poll errored after shutdown: ${e.message}`)}}}finally{this._logger.log(Ee.Trace,"(LongPolling transport) Polling complete."),this.pollAborted||this._raiseOnClose()}}async send(e){return this._running?Me(this._logger,"LongPolling",this._httpClient,this._url,this._accessTokenFactory,e,this._logMessageContent,this._withCredentials,this._headers):Promise.reject(new Error("Cannot send until the transport is connected"))}async stop(){this._logger.log(Ee.Trace,"(LongPolling transport) Stopping polling."),this._running=!1,this._pollAbort.abort();try{await this._receiving,this._logger.log(Ee.Trace,`(LongPolling transport) sending DELETE request to ${this._url}.`);const e={},[t,n]=Fe();e[t]=n;const r={headers:{...e,...this._headers},withCredentials:this._withCredentials},o=await this._getAccessToken();this._updateHeaderToken(r,o),await this._httpClient.delete(this._url,r),this._logger.log(Ee.Trace,"(LongPolling transport) DELETE request sent.")}finally{this._logger.log(Ee.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(Ee.Trace,e),this.onclose(this._closeError)}}}class Je{constructor(e,t,n,r,o,i,s){this._httpClient=e,this._accessTokenFactory=t,this._logger=n,this._logMessageContent=r,this._withCredentials=i,this._eventSourceConstructor=o,this._headers=s,this.onreceive=null,this.onclose=null}async connect(e,t){if(Ne.isRequired(e,"url"),Ne.isRequired(t,"transferFormat"),Ne.isIn(t,Ce,"transferFormat"),this._logger.log(Ee.Trace,"(SSE transport) Connecting."),this._url=e,this._accessTokenFactory){const t=await this._accessTokenFactory();t&&(e+=(e.indexOf("?")<0?"?":"&")+`access_token=${encodeURIComponent(t)}`)}return new Promise(((n,r)=>{let o,i=!1;if(t===Ce.Text){if(Be.isBrowser||Be.isWebWorker)o=new this._eventSourceConstructor(e,{withCredentials:this._withCredentials});else{const t=this._httpClient.getCookieString(e),n={};n.Cookie=t;const[r,i]=Fe();n[r]=i,o=new this._eventSourceConstructor(e,{withCredentials:this._withCredentials,headers:{...n,...this._headers}})}try{o.onmessage=e=>{if(this.onreceive)try{this._logger.log(Ee.Trace,`(SSE transport) data received. ${$e(e.data,this._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(Ee.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?Me(this._logger,"SSE",this._httpClient,this._url,this._accessTokenFactory,e,this._logMessageContent,this._withCredentials,this._headers):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 Ke{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){if(Ne.isRequired(e,"url"),Ne.isRequired(t,"transferFormat"),Ne.isIn(t,Ce,"transferFormat"),this._logger.log(Ee.Trace,"(WebSockets transport) Connecting."),this._accessTokenFactory){const t=await this._accessTokenFactory();t&&(e+=(e.indexOf("?")<0?"?":"&")+`access_token=${encodeURIComponent(t)}`)}return new Promise(((n,r)=>{let o;e=e.replace(/^http/,"ws"),this._httpClient.getCookieString(e);let i=!1;o||(o=new this._webSocketConstructor(e)),t===Ce.Binary&&(o.binaryType="arraybuffer"),o.onopen=t=>{this._logger.log(Ee.Information,`WebSocket connected to ${e}.`),this._webSocket=o,i=!0,n()},o.onerror=e=>{let t=null;t="undefined"!=typeof ErrorEvent&&e instanceof ErrorEvent?e.error:"There was an error with the transport",this._logger.log(Ee.Information,`(WebSockets transport) ${t}.`)},o.onmessage=e=>{if(this._logger.log(Ee.Trace,`(WebSockets transport) data received. ${$e(e.data,this._logMessageContent)}.`),this.onreceive)try{this.onreceive(e.data)}catch(e){return void this._close(e)}},o.onclose=e=>{if(i)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(Ee.Trace,`(WebSockets transport) sending data. ${$e(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(Ee.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 Ve{constructor(e,t={}){var n;if(this._stopPromiseResolver=()=>{},this.features={},this._negotiateVersion=1,Ne.isRequired(e,"url"),this._logger=void 0===(n=t.logger)?new He(Ee.Information):null===n?Ae.instance:void 0!==n.log?n:new He(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,"undefined"==typeof WebSocket||t.WebSocket||(t.WebSocket=WebSocket),"undefined"==typeof EventSource||t.EventSource||(t.EventSource=EventSource),this._httpClient=t.httpClient||new Re(this._logger),this._connectionState="Disconnected",this._connectionStarted=!1,this._options=t,this.onreceive=null,this.onclose=null}async start(e){if(e=e||Ce.Binary,Ne.isIn(e,Ce,"transferFormat"),this._logger.log(Ee.Debug,`Starting connection with transfer format '${Ce[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(Ee.Error,e),await this._stopPromise,Promise.reject(new Error(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(Ee.Error,e),Promise.reject(new Error(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 Xe(this.transport)),this._sendQueue.send(e))}async stop(e){return"Disconnected"===this._connectionState?(this._logger.log(Ee.Debug,`Call to HttpConnection.stop(${e}) ignored because the connection is already in the disconnected state.`),Promise.resolve()):"Disconnecting"===this._connectionState?(this._logger.log(Ee.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(Ee.Error,`HttpConnection.transport.stop() threw error '${e}'.`),this._stopConnection()}this.transport=void 0}else this._logger.log(Ee.Debug,"HttpConnection.transport is undefined in HttpConnection.stop() because start() failed.")}async _startInternal(e){let t=this.baseUrl;this._accessTokenFactory=this._options.accessTokenFactory;try{if(this._options.skipNegotiation){if(this._options.transport!==Se.WebSockets)throw new Error("Negotiation can only be skipped when using the WebSocket transport directly.");this.transport=this._constructTransport(Se.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 Error("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}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 qe&&(this.features.inherentKeepAlive=!0),"Connecting"===this._connectionState&&(this._logger.log(Ee.Debug,"The HttpConnection connected successfully."),this._connectionState="Connected")}catch(e){return this._logger.log(Ee.Error,"Failed to start the connection: "+e),this._connectionState="Disconnected",this.transport=void 0,this._stopPromiseResolver(),Promise.reject(e)}}async _getNegotiationResponse(e){const t={};if(this._accessTokenFactory){const e=await this._accessTokenFactory();e&&(t[Pe.Authorization]=`Bearer ${e}`)}const[n,r]=Fe();t[n]=r;const o=this._resolveNegotiateUrl(e);this._logger.log(Ee.Debug,`Sending negotiation request: ${o}.`);try{const e=await this._httpClient.post(o,{content:"",headers:{...t,...this._options.headers},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 ye&&404===e.statusCode&&(t+=" Either this is not a SignalR endpoint or there is a proxy blocking the connection."),this._logger.log(Ee.Error,t),Promise.reject(new Error(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(Ee.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: ${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(Ee.Error,`Failed to start the transport '${n.transport}': ${e}`),a=void 0,i.push(`${n.transport} failed: ${e}`),"Connecting"!==this._connectionState){const e="Failed to select transport before stop() was called.";return this._logger.log(Ee.Debug,e),Promise.reject(new Error(e))}}}}return i.length>0?Promise.reject(new Error(`Unable to connect to the server with any of the available transports. ${i.join(" ")}`)):Promise.reject(new Error("None of the transports supported by the client are supported by the server."))}_constructTransport(e){switch(e){case Se.WebSockets:if(!this._options.WebSocket)throw new Error("'WebSocket' is not supported in your environment.");return new Ke(this._httpClient,this._accessTokenFactory,this._logger,this._options.logMessageContent||!1,this._options.WebSocket,this._options.headers||{});case Se.ServerSentEvents:if(!this._options.EventSource)throw new Error("'EventSource' is not supported in your environment.");return new Je(this._httpClient,this._accessTokenFactory,this._logger,this._options.logMessageContent||!1,this._options.EventSource,this._options.withCredentials,this._options.headers||{});case Se.LongPolling:return new qe(this._httpClient,this._accessTokenFactory,this._logger,this._options.logMessageContent||!1,this._options.withCredentials,this._options.headers||{});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=Se[e.transport];if(null==r)return this._logger.log(Ee.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(Ee.Debug,`Skipping transport '${Se[r]}' because it was disabled by the client.`),new Error(`'${Se[r]}' is disabled by the client.`);if(!(e.transferFormats.map((e=>Ce[e])).indexOf(n)>=0))return this._logger.log(Ee.Debug,`Skipping transport '${Se[r]}' because it does not support the requested transfer format '${Ce[n]}'.`),new Error(`'${Se[r]}' does not support ${Ce[n]}.`);if(r===Se.WebSockets&&!this._options.WebSocket||r===Se.ServerSentEvents&&!this._options.EventSource)return this._logger.log(Ee.Debug,`Skipping transport '${Se[r]}' because it is not supported in your environment.'`),new Error(`'${Se[r]}' is not supported in your environment.`);this._logger.log(Ee.Debug,`Selecting transport '${Se[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(Ee.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(Ee.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(Ee.Error,`Connection disconnected with error '${e}'.`):this._logger.log(Ee.Information,"Connection disconnected."),this._sendQueue&&(this._sendQueue.stop().catch((e=>{this._logger.log(Ee.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(Ee.Error,`HttpConnection.onclose(${e}) threw error '${t}'.`)}}}else this._logger.log(Ee.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(!Be.isBrowser||!window.document)throw new Error(`Cannot resolve '${e}'.`);const t=window.document.createElement("a");return t.href=e,this._logger.log(Ee.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 Xe{constructor(e){this._transport=e,this._buffer=[],this._executing=!0,this._sendBufferedData=new Ye,this._transportResult=new Ye,this._sendLoopPromise=this._sendLoop()}send(e){return this._bufferData(e),this._transportResult||(this._transportResult=new Ye),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 Ye;const e=this._transportResult;this._transportResult=void 0;const t="string"==typeof this._buffer[0]?this._buffer.join(""):Xe._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 Ye{constructor(){this.promise=new Promise(((e,t)=>[this._resolver,this._rejecter]=[e,t]))}resolve(){this._resolver()}reject(e){this._rejecter(e)}}class Ge{static write(e){return`${e}${Ge.RecordSeparator}`}static parse(e){if(e[e.length-1]!==Ge.RecordSeparator)throw new Error("Message is incomplete.");const t=e.split(Ge.RecordSeparator);return t.pop(),t}}Ge.RecordSeparatorCode=30,Ge.RecordSeparator=String.fromCharCode(Ge.RecordSeparatorCode);class Qe{writeHandshakeRequest(e){return Ge.write(JSON.stringify(e))}parseHandshakeResponse(e){let t,n;if(Le(e)){const r=new Uint8Array(e),o=r.indexOf(Ge.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(Ge.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=Ge.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"}(Ie||(Ie={}));class Ze{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 Oe(this,e)}}!function(e){e.Disconnected="Disconnected",e.Connecting="Connecting",e.Connected="Connected",e.Disconnecting="Disconnecting",e.Reconnecting="Reconnecting"}(ke||(ke={}));class et{constructor(e,t,n,r){this._nextKeepAlive=0,Ne.isRequired(e,"connection"),Ne.isRequired(t,"logger"),Ne.isRequired(n,"protocol"),this.serverTimeoutInMilliseconds=3e4,this.keepAliveIntervalInMilliseconds=15e3,this._logger=t,this._protocol=n,this.connection=e,this._reconnectPolicy=r,this._handshakeProtocol=new Qe,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=ke.Disconnected,this._connectionStarted=!1,this._cachedPingMessage=this._protocol.writeMessage({type:Ie.Ping})}static create(e,t,n,r){return new et(e,t,n,r)}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!==ke.Disconnected&&this._connectionState!==ke.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!==ke.Disconnected)return Promise.reject(new Error("Cannot start a HubConnection that is not in the 'Disconnected' state."));this._connectionState=ke.Connecting,this._logger.log(Ee.Debug,"Starting HubConnection.");try{await this._startInternal(),this._connectionState=ke.Connected,this._connectionStarted=!0,this._logger.log(Ee.Debug,"HubConnection connected successfully.")}catch(e){return this._connectionState=ke.Disconnected,this._logger.log(Ee.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(Ee.Debug,"Sending handshake request."),await this._sendMessage(this._handshakeProtocol.writeHandshakeRequest(t)),this._logger.log(Ee.Information,`Using HubProtocol '${this._protocol.name}'.`),this._cleanupTimeout(),this._resetTimeoutPeriod(),this._resetKeepAliveInterval(),await e,this._stopDuringStartError)throw this._stopDuringStartError}catch(e){throw this._logger.log(Ee.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){return this._connectionState===ke.Disconnected?(this._logger.log(Ee.Debug,`Call to HubConnection.stop(${e}) ignored because it is already in the disconnected state.`),Promise.resolve()):this._connectionState===ke.Disconnecting?(this._logger.log(Ee.Debug,`Call to HttpConnection.stop(${e}) ignored because the connection is already in the disconnecting state.`),this._stopPromise):(this._connectionState=ke.Disconnecting,this._logger.log(Ee.Debug,"Stopping HubConnection."),this._reconnectDelayHandle?(this._logger.log(Ee.Debug,"Connection stopped during reconnect delay. Done reconnecting."),clearTimeout(this._reconnectDelayHandle),this._reconnectDelayHandle=void 0,this._completeClose(),Promise.resolve()):(this._cleanupTimeout(),this._cleanupPingTimer(),this._stopDuringStartError=e||new Error("The connection was stopped before the hub handshake could complete."),this.connection.stop(e)))}stream(e,...t){const[n,r]=this._replaceStreamingParams(t),o=this._createStreamInvocation(e,t,r);let i;const s=new Ze;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===Ie.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===Ie.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 Ie.Invocation:this._invokeClientMethod(e);break;case Ie.StreamItem:case Ie.Completion:{const t=this._callbacks[e.invocationId];t&&(e.type===Ie.Completion&&delete this._callbacks[e.invocationId],t(e));break}case Ie.Ping:break;case Ie.Close:{this._logger.log(Ee.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(Ee.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(Ee.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(Ee.Error,e);const n=new Error(e);throw this._handshakeRejecter(n),n}return this._logger.log(Ee.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===ke.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."))}_invokeClientMethod(e){const t=this._methods[e.target.toLowerCase()];if(t){try{t.forEach((t=>t.apply(this,e.arguments)))}catch(t){this._logger.log(Ee.Error,`A callback for the method ${e.target.toLowerCase()} threw error '${t}'.`)}if(e.invocationId){const e="Server requested a response, which is not supported in this version of the client.";this._logger.log(Ee.Error,e),this._stopPromise=this._stopInternal(new Error(e))}}else this._logger.log(Ee.Warning,`No client method with the name '${e.target}' found.`)}_connectionClosed(e){this._logger.log(Ee.Debug,`HubConnection.connectionClosed(${e}) called while in state ${this._connectionState}.`),this._stopDuringStartError=this._stopDuringStartError||e||new Error("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===ke.Disconnecting?this._completeClose(e):this._connectionState===ke.Connected&&this._reconnectPolicy?this._reconnect(e):this._connectionState===ke.Connected&&this._completeClose(e)}_completeClose(e){if(this._connectionStarted){this._connectionState=ke.Disconnected,this._connectionStarted=!1;try{this._closedCallbacks.forEach((t=>t.apply(this,[e])))}catch(t){this._logger.log(Ee.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(Ee.Debug,"Connection not reconnecting because the IRetryPolicy returned null on the first reconnect attempt."),void this._completeClose(e);if(this._connectionState=ke.Reconnecting,e?this._logger.log(Ee.Information,`Connection reconnecting because of error '${e}'.`):this._logger.log(Ee.Information,"Connection reconnecting."),0!==this._reconnectingCallbacks.length){try{this._reconnectingCallbacks.forEach((t=>t.apply(this,[e])))}catch(t){this._logger.log(Ee.Error,`An onreconnecting callback called with error '${e}' threw error '${t}'.`)}if(this._connectionState!==ke.Reconnecting)return void this._logger.log(Ee.Debug,"Connection left the reconnecting state in onreconnecting callback. Done reconnecting.")}for(;null!==o;){if(this._logger.log(Ee.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!==ke.Reconnecting)return void this._logger.log(Ee.Debug,"Connection left the reconnecting state during reconnect delay. Done reconnecting.");try{if(await this._startInternal(),this._connectionState=ke.Connected,this._logger.log(Ee.Information,"HubConnection reconnected successfully."),0!==this._reconnectedCallbacks.length)try{this._reconnectedCallbacks.forEach((e=>e.apply(this,[this.connection.connectionId])))}catch(e){this._logger.log(Ee.Error,`An onreconnected callback called with connectionId '${this.connection.connectionId}; threw error '${e}'.`)}return}catch(e){if(this._logger.log(Ee.Information,`Reconnect attempt failed because of error '${e}'.`),this._connectionState!==ke.Reconnecting)return this._logger.log(Ee.Debug,`Connection moved to the '${this._connectionState}' from the reconnecting state during reconnect attempt. Done reconnecting.`),void(this._connectionState===ke.Disconnecting&&this._completeClose());r=e instanceof Error?e:new Error(e.toString()),o=this._getNextRetryDelay(n++,Date.now()-t,r)}}this._logger.log(Ee.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(Ee.Error,`IRetryPolicy.nextRetryDelayInMilliseconds(${e}, ${t}) threw error '${n}'.`),null}}_cancelCallbacksWithError(e){const t=this._callbacks;this._callbacks={},Object.keys(t).forEach((n=>{(0,t[n])(null,e)}))}_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:Ie.Invocation}:{arguments:t,target:e,type:Ie.Invocation};{const n=this._invocationId;return this._invocationId++,0!==r.length?{arguments:t,invocationId:n.toString(),streamIds:r,target:e,type:Ie.Invocation}:{arguments:t,invocationId:n.toString(),target:e,type:Ie.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 ut=ot?new TextDecoder:null,dt=ot?"undefined"!=typeof process&&"force"!==process.env.TEXT_DECODER?200:0:it,pt=function(e,t){this.type=e,this.data=t};function ft(e,t,n){var r=Math.floor(n/4294967296),o=n;e.setUint32(t,r),e.setUint32(t+4,o)}function gt(e,t){return 4294967296*e.getInt32(t)+e.getUint32(t+4)}var mt={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),ft(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:gt(t,4),nsec:t.getUint32(0)};default:throw new Error("Unrecognized data size for timestamp: "+e.length)}}(e);return new Date(1e3*t.sec+t.nsec/1e6)}},yt=function(){function e(){this.builtInEncoders=[],this.builtInDecoders=[],this.encoders=[],this.decoders=[],this.register(mt)}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 "+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: "+e+" bytes in UTF-8");this.writeU8(219),this.writeU32(e)}},e.prototype.encodeString=function(e){if(e.length>ct){var t=st(e);this.ensureBufferSizeToWrite(5+t),this.writeStringHeader(t),lt(e,this.bytes,this.pos),this.pos+=t}else t=st(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: "+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: "+t);this.writeU8(198),this.writeU32(t)}var n=wt(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: "+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=ht(e,t,n),i=Uint8Array.prototype.slice.call(e,t,t+n);return this.store(i,o),o},e}(),St=(_t=function(e,t){return(_t=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])})(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}_t(e,t),e.prototype=null===t?Object.create(t):(n.prototype=t.prototype,new n)}),Ct=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]1||a(e,t)}))})}function a(e,t){try{(n=o[e](t)).value instanceof kt?Promise.resolve(n.value.v).then(c,l):h(i[0][2],n)}catch(e){h(i[0][3],e)}var n}function c(e){a("next",e)}function l(e){a("throw",e)}function h(e,t){e(t),i.shift(),i.length&&a(i[0][0],i[0][1])}},Dt=new DataView(new ArrayBuffer(0)),xt=new Uint8Array(Dt.buffer),Rt=function(){try{Dt.getInt8(0)}catch(e){return e.constructor}throw new Error("never reached")}(),Pt=new Rt("Insufficient data"),Ut=4294967295,At=new Et,Nt=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 St(t,e),t}(Error),Bt=function(){function e(e,t,n,r,o,i,s,a){void 0===e&&(e=yt.defaultCodec),void 0===t&&(t=void 0),void 0===n&&(n=Ut),void 0===r&&(r=Ut),void 0===o&&(o=Ut),void 0===i&&(i=Ut),void 0===s&&(s=Ut),void 0===a&&(a=At),this.extensionCodec=e,this.context=t,this.maxStrLength=n,this.maxBinLength=r,this.maxArrayLength=o,this.maxMapLength=i,this.maxExtLength=s,this.keyDecoder=a,this.totalPos=0,this.pos=0,this.view=Dt,this.bytes=xt,this.headByte=-1,this.stack=[]}return e.prototype.reinitializeState=function(){this.totalPos=0,this.headByte=-1,this.stack.length=0},e.prototype.setBuffer=function(e){this.bytes=wt(e),this.view=function(e){if(e instanceof ArrayBuffer)return new DataView(e);var t=wt(e);return new DataView(t.buffer,t.byteOffset,t.byteLength)}(this.bytes),this.pos=0},e.prototype.appendBuffer=function(e){if(-1!==this.headByte||this.hasRemaining()){var t=this.bytes.subarray(this.pos),n=wt(e),r=new Uint8Array(t.length+n.length);r.set(t),r.set(n,t.length),this.setBuffer(r)}else this.setBuffer(e)},e.prototype.hasRemaining=function(e){return void 0===e&&(e=1),this.view.byteLength-this.pos>=e},e.prototype.createExtraByteError=function(e){var t=this.view,n=this.pos;return new RangeError("Extra "+(t.byteLength-n)+" of "+t.byteLength+" byte(s) found at buffer["+e+"]")},e.prototype.decode=function(e){this.reinitializeState(),this.setBuffer(e);var t=this.doDecodeSync();if(this.hasRemaining())throw this.createExtraByteError(this.pos);return t},e.prototype.decodeMulti=function(e){return Ct(this,(function(t){switch(t.label){case 0:this.reinitializeState(),this.setBuffer(e),t.label=1;case 1:return this.hasRemaining()?[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,u,d;return Ct(this,(function(p){switch(p.label){case 0:i=!1,p.label=1;case 1:p.trys.push([1,6,7,12]),t=It(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 Rt))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())throw this.createExtraByteError(this.totalPos);return[2,s]}throw h=(l=this).headByte,u=l.pos,d=l.totalPos,new RangeError("Insufficient data in parsing "+bt(h)+" at "+d+" ("+u+" 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 Tt(this,arguments,(function(){var n,r,o,i,s,a,c,l,h;return Ct(this,(function(u){switch(u.label){case 0:n=t,r=-1,u.label=1;case 1:u.trys.push([1,13,14,19]),o=It(e),u.label=2;case 2:return[4,kt(o.next())];case 3:if((i=u.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()),u.label=4;case 4:u.trys.push([4,9,,10]),u.label=5;case 5:return[4,kt(this.doDecodeSync())];case 6:return[4,u.sent()];case 7:return u.sent(),0==--r?[3,8]:[3,5];case 8:return[3,10];case 9:if(!((a=u.sent())instanceof Rt))throw a;return[3,10];case 10:this.totalPos+=this.pos,u.label=11;case 11:return[3,2];case 12:return[3,19];case 13:return c=u.sent(),l={error:c},[3,19];case 14:return u.trys.push([14,,17,18]),i&&!i.done&&(h=o.return)?[4,kt(h.call(o))]:[3,16];case 15:u.sent(),u.label=16;case 16:return[3,18];case 17:if(l)throw l.error;return[7];case 18:return[7];case 19:return[2]}}))}))},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 Nt("Unrecognized type byte: "+bt(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 Nt("The type of key must be string or number but "+typeof t);if("__proto__"===t)throw new Nt("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 Nt("Unrecognized array type byte: "+bt(e))}},e.prototype.pushMapState=function(e){if(e>this.maxMapLength)throw new Nt("Max length exceeded: map length ("+e+") > maxMapLengthLength ("+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 Nt("Max length exceeded: array length ("+e+") > maxArrayLength ("+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 Nt("Max length exceeded: UTF-8 byte length ("+e+") > maxStrLength ("+this.maxStrLength+")");if(this.bytes.byteLengthdt?function(e,t,n){var r=e.subarray(t,t+n);return ut.decode(r)}(this.bytes,o,e):ht(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 Nt("Max length exceeded: bin length ("+e+") > maxBinLength ("+this.maxBinLength+")");if(!this.hasRemaining(e+t))throw Pt;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 Nt("Max length exceeded: ext length ("+e+") > maxExtLength ("+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=gt(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 $t{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 Lt=new Uint8Array([145,Ie.Ping]);class Mt{constructor(e){this.name="messagepack",this.version=1,this.transferFormat=Ce.Binary,this._errorResult=1,this._voidResult=2,this._nonVoidResult=3,e=e||{},this._encoder=new vt(e.extensionCodec,e.context,e.maxDepth,e.initialBufferSize,e.sortKeys,e.forceFloat32,e.ignoreUndefined,e.forceIntegerToFloat),this._decoder=new Bt(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=Ae.instance);const r=$t.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 Ie.Invocation:return this._writeInvocation(e);case Ie.StreamInvocation:return this._writeStreamInvocation(e);case Ie.StreamItem:return this._writeStreamItem(e);case Ie.Completion:return this._writeCompletion(e);case Ie.Ping:return $t.write(Lt);case Ie.CancelInvocation:return this._writeCancelInvocation(e);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 Ie.Invocation:return this._createInvocationMessage(this._readHeaders(n),n);case Ie.StreamItem:return this._createStreamItemMessage(this._readHeaders(n),n);case Ie.Completion:return this._createCompletionMessage(this._readHeaders(n),n);case Ie.Ping:return this._createPingMessage(n);case Ie.Close:return this._createCloseMessage(n);default:return t.log(Ee.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:Ie.Close}}_createPingMessage(e){if(e.length<1)throw new Error("Invalid payload for Ping message.");return{type:Ie.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:Ie.Invocation}:{arguments:t[4],headers:e,streamIds:[],target:t[3],type:Ie.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:Ie.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:Ie.Completion}}_writeInvocation(e){let t;return t=e.streamIds?this._encoder.encode([Ie.Invocation,e.headers||{},e.invocationId||null,e.target,e.arguments,e.streamIds]):this._encoder.encode([Ie.Invocation,e.headers||{},e.invocationId||null,e.target,e.arguments]),$t.write(t.slice())}_writeStreamInvocation(e){let t;return t=e.streamIds?this._encoder.encode([Ie.StreamInvocation,e.headers||{},e.invocationId,e.target,e.arguments,e.streamIds]):this._encoder.encode([Ie.StreamInvocation,e.headers||{},e.invocationId,e.target,e.arguments]),$t.write(t.slice())}_writeStreamItem(e){const t=this._encoder.encode([Ie.StreamItem,e.headers||{},e.invocationId,e.item]);return $t.write(t.slice())}_writeCompletion(e){const t=e.error?this._errorResult:e.result?this._nonVoidResult:this._voidResult;let n;switch(t){case this._errorResult:n=this._encoder.encode([Ie.Completion,e.headers||{},e.invocationId,t,e.error]);break;case this._voidResult:n=this._encoder.encode([Ie.Completion,e.headers||{},e.invocationId,t]);break;case this._nonVoidResult:n=this._encoder.encode([Ie.Completion,e.headers||{},e.invocationId,t,e.result])}return $t.write(n.slice())}_writeCancelInvocation(e){const t=this._encoder.encode([Ie.CancelInvocation,e.headers||{},e.invocationId]);return $t.write(t.slice())}_readHeaders(e){const t=e[1];if("object"!=typeof t)throw new Error("Invalid headers.");return t}}let Ot=!1;const Ht="function"==typeof TextDecoder?new TextDecoder("utf-8"):null,Ft=Ht?Ht.decode.bind(Ht):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("")},jt=Math.pow(2,32),Wt=Math.pow(2,21)-1;function zt(e,t){return e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24}function qt(e,t){return e[t]+(e[t+1]<<8)+(e[t+2]<<16)+(e[t+3]<<24>>>0)}function Jt(e,t){const n=qt(e,t+4);if(n>Wt)throw new Error(`Cannot read uint64 with high order part ${n}, because the result would exceed Number.MAX_SAFE_INTEGER.`);return n*jt+qt(e,t)}class Kt{constructor(e){this.batchData=e;const t=new Gt(e);this.arrayRangeReader=new Qt(e),this.arrayBuilderSegmentReader=new Zt(e),this.diffReader=new Vt(e),this.editReader=new Xt(e,t),this.frameReader=new Yt(e,t)}updatedComponents(){return zt(this.batchData,this.batchData.length-20)}referenceFrames(){return zt(this.batchData,this.batchData.length-16)}disposedComponentIds(){return zt(this.batchData,this.batchData.length-12)}disposedEventHandlerIds(){return zt(this.batchData,this.batchData.length-8)}updatedComponentsEntry(e,t){const n=e+4*t;return zt(this.batchData,n)}referenceFramesEntry(e,t){return e+20*t}disposedComponentIdsEntry(e,t){const n=e+4*t;return zt(this.batchData,n)}disposedEventHandlerIdsEntry(e,t){const n=e+8*t;return Jt(this.batchData,n)}}class Vt{constructor(e){this.batchDataUint8=e}componentId(e){return zt(this.batchDataUint8,e)}edits(e){return e+4}editsEntry(e,t){return e+16*t}}class Xt{constructor(e,t){this.batchDataUint8=e,this.stringReader=t}editType(e){return zt(this.batchDataUint8,e)}siblingIndex(e){return zt(this.batchDataUint8,e+4)}newTreeIndex(e){return zt(this.batchDataUint8,e+8)}moveToSiblingIndex(e){return zt(this.batchDataUint8,e+8)}removedAttributeName(e){const t=zt(this.batchDataUint8,e+12);return this.stringReader.readString(t)}}class Yt{constructor(e,t){this.batchDataUint8=e,this.stringReader=t}frameType(e){return zt(this.batchDataUint8,e)}subtreeLength(e){return zt(this.batchDataUint8,e+4)}elementReferenceCaptureId(e){const t=zt(this.batchDataUint8,e+4);return this.stringReader.readString(t)}componentId(e){return zt(this.batchDataUint8,e+8)}elementName(e){const t=zt(this.batchDataUint8,e+8);return this.stringReader.readString(t)}textContent(e){const t=zt(this.batchDataUint8,e+4);return this.stringReader.readString(t)}markupContent(e){const t=zt(this.batchDataUint8,e+4);return this.stringReader.readString(t)}attributeName(e){const t=zt(this.batchDataUint8,e+4);return this.stringReader.readString(t)}attributeValue(e){const t=zt(this.batchDataUint8,e+8);return this.stringReader.readString(t)}attributeEventHandlerId(e){return Jt(this.batchDataUint8,e+12)}}class Gt{constructor(e){this.batchDataUint8=e,this.stringTableStartIndex=zt(e,e.length-4)}readString(e){if(-1===e)return null;{const n=zt(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(en.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(en.Debug,`Waiting for batch ${this.nextBatchId}. Batch ${e} not processed.`);try{this.nextBatchId++,this.logger.log(en.Debug,`Applying batch ${e}.`),function(e,t){const n=Q[e];if(!n)throw new Error(`There is no browser renderer with ID ${e}.`);const r=t.arrayRangeReader,o=t.updatedComponents(),i=r.values(o),s=r.count(o),a=t.referenceFrames(),c=r.values(a),l=t.diffReader;for(let e=0;e=this.minLevel){const n=`[${(new Date).toISOString()}] ${en[e]}: ${t}`;switch(e){case en.Critical:case en.Error:console.error(n);break;case en.Warning:console.warn(n);break;case en.Information:console.info(n);break;default:console.log(n)}}}}class on{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!==ke.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!==ke.Connected)return!1;const t=await e.invoke("StartCircuit",re.getBaseURI(),re.getLocationHref(),JSON.stringify(this.components.map((e=>e.toRecord()))),this.applicationState||"");return!!t&&(this.initialize(t),!0)}resolveElement(e){const t=Number.parseInt(e);if(Number.isNaN(t))throw new Error(`Invalid sequence number '${e}'.`);return function(e,t){if(!e.parentNode)throw new Error(`Comment not connected to the DOM ${e.textContent}`);const n=e.parentNode,r=k(n,!0),o=A(r);return Array.from(n.childNodes).forEach((e=>o.push(e))),e[C]=r,t&&(e[I]=t,k(t)),k(e)}(this.components[t].start,this.components[t].end)}}const sn={configureSignalR:e=>{},logLevel:en.Warning,reconnectionOptions:{maxRetries:8,retryIntervalMilliseconds:2e4,dialogId:"components-reconnect-modal"}};class an{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.modal.innerHTML='

Alternatively, reload

',this.message=this.modal.querySelector("h5"),this.button=this.modal.querySelector("button"),this.reloadParagraph=this.modal.querySelector("p"),this.loader=this.getLoader(),this.message.after(this.loader),this.button.addEventListener("click",(async()=>{this.show();try{await(null==fe?void 0:fe.reconnect)()||this.rejected()}catch(e){this.logger.log(en.Error,e),this.failed()}})),this.reloadParagraph.querySelector("a").addEventListener("click",(()=>location.reload()))}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",this.message.innerHTML="Reconnection failed. Try reloading the page if you're unable to reconnect.",this.message.querySelector("a").addEventListener("click",(()=>location.reload()))}rejected(){this.button.style.display="none",this.reloadParagraph.style.display="none",this.loader.style.display="none",this.message.innerHTML="Could not reconnect to the server. Reload the page to restore functionality.",this.message.querySelector("a").addEventListener("click",(()=>location.reload()))}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 cn{constructor(e,t,n){this.dialog=e,this.maxRetries=t,this.document=n,this.document=n;const r=this.document.getElementById(cn.MaxRetriesId);r&&(r.innerText=this.maxRetries.toString())}show(){this.removeClasses(),this.dialog.classList.add(cn.ShowClassName)}update(e){const t=this.document.getElementById(cn.CurrentAttemptId);t&&(t.innerText=e.toString())}hide(){this.removeClasses(),this.dialog.classList.add(cn.HideClassName)}failed(){this.removeClasses(),this.dialog.classList.add(cn.FailedClassName)}rejected(){this.removeClasses(),this.dialog.classList.add(cn.RejectedClassName)}removeClasses(){this.dialog.classList.remove(cn.ShowClassName,cn.HideClassName,cn.FailedClassName,cn.RejectedClassName)}}cn.ShowClassName="components-reconnect-show",cn.HideClassName="components-reconnect-hide",cn.FailedClassName="components-reconnect-failed",cn.RejectedClassName="components-reconnect-rejected",cn.MaxRetriesId="components-reconnect-max-retries",cn.CurrentAttemptId="components-reconnect-current-attempt";class ln{constructor(e,t,n){this._currentReconnectionProcess=null,this._logger=e,this._reconnectionDisplay=t,this._reconnectCallback=n||(()=>fe.reconnect())}onConnectionDown(e,t){if(!this._reconnectionDisplay){const t=document.getElementById(e.dialogId);this._reconnectionDisplay=t?new cn(t,e.maxRetries,document):new an(e.dialogId,e.maxRetries,document,this._logger)}this._currentReconnectionProcess||(this._currentReconnectionProcess=new hn(e,this._logger,this._reconnectCallback,this._reconnectionDisplay))}onConnectionUp(){this._currentReconnectionProcess&&(this._currentReconnectionProcess.dispose(),this._currentReconnectionProcess=null)}}class hn{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;thn.MaximumFirstRetryInterval?hn.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(en.Error,e)}}this.reconnectDisplay.failed()}delay(e){return new Promise((t=>setTimeout(t,e)))}}hn.MaximumFirstRetryInterval=3e3;const un=/^\s*Blazor-Component-State:(?[a-zA-Z0-9\+\/=]+)$/;function dn(e){var t;if(e.nodeType===Node.COMMENT_NODE){const n=e.textContent||"",r=un.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 gn(e,t){const n=e.currentElement;if(n&&n.nodeType===Node.COMMENT_NODE&&n.textContent){const r=fn.exec(n.textContent),o=r&&r.groups&&r.groups.descriptor;if(!o)return;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;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.");if(c){const e=mn(c,n);if(!e)throw new Error(`Could not find an end component comment for '${t}'`);return{type:r,assembly:o,typeName:i,parameterDefinitions:s&&atob(s),parameterValues:a&&atob(a),start:t,prerenderId:c,end:e}}return{type:r,assembly:o,typeName:i,parameterDefinitions:s&&atob(s),parameterValues:a&&atob(a),start:t}}}(r,n,e);case"server":return function(e,t,n){const{type:r,descriptor:o,sequence:i,prerenderId:s}=e;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)}'`);if(s){const e=mn(s,n);if(!e)throw new Error(`Could not find an end component comment for '${t}'`);return{type:r,sequence:i,descriptor:o,start:t,prerenderId:s,end:e}}return{type:r,sequence:i,descriptor:o,start:t}}}(r,n,e)}}catch(e){throw new Error(`Found malformed component comment at ${n.textContent}`)}}}function mn(e,t){for(;t.next()&&t.currentElement;){const n=t.currentElement;if(n.nodeType!==Node.COMMENT_NODE)continue;if(!n.textContent)continue;const r=fn.exec(n.textContent),o=r&&r[1];if(o)return yn(o,e),n}}function yn(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 wn{constructor(e){this.childNodes=e,this.currentIndex=-1,this.length=e.length}next(){return this.currentIndex++,this.currentIndexe.sequence-t.sequence))}(e)}(document),o=dn(document),i=new on(r,o||""),s=await Tn(t,n,i);if(!await i.startCircuit(s))return void n.log(en.Error,"Failed to start the circuit.");let a=!1;const c=()=>{if(!a){const e=new FormData,t=i.circuitId;e.append("circuitId",t),a=navigator.sendBeacon("_blazor/disconnect",e)}};fe.disconnect=c,window.addEventListener("unload",c,{capture:!1,once:!0}),fe.reconnect=async e=>{if(Cn)return!1;const r=e||await Tn(t,n,i);return await i.reconnect(r)?(t.reconnectionHandler.onConnectionUp(),!0):(n.log(en.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)},n.log(en.Information,"Blazor server-side application started.")}async function Tn(t,n,r){const i=new Mt;i.name="blazorpack";const s=(new rt).withUrl("_blazor").withHubProtocol(i);t.configureSignalR(s);const a=s.build();o=(e,t)=>{a.send("DispatchBrowserEvent",JSON.stringify(e),JSON.stringify(t))},fe._internal.navigationManager.listenForNavigationEvents(((e,t)=>a.send("OnLocationChanged",e,t))),a.on("JS.AttachComponent",((e,t)=>function(e,t,n){let r=Q[0];r||(r=Q[0]=new V(0)),r.attachRootComponentToLogicalElement(n,t)}(0,r.resolveElement(t),e))),a.on("JS.BeginInvokeJS",e.jsCallDispatcher.beginInvokeJSFromDotNet),a.on("JS.EndInvokeDotNet",e.jsCallDispatcher.endInvokeDotNetFromJS),a.on("JS.ReceiveByteArray",e.jsCallDispatcher.receiveByteArray);const c=tn.getOrCreate(n);a.on("JS.RenderBatch",((e,t)=>{n.log(en.Debug,`Received render batch with id ${e} and ${t.byteLength} bytes.`),c.processBatch(e,t,a)})),a.onclose((e=>!Cn&&t.reconnectionHandler.onConnectionDown(t.reconnectionOptions,e))),a.on("JS.Error",(e=>{Cn=!0,Dn(a,e,n),async function(){let e=document.querySelector("#blazor-error-ui");e&&(e.style.display="block"),Ot||(Ot=!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()}})))}()})),fe._internal.forceCloseConnection=()=>a.stop(),fe._internal.sendJSDataStream=async(e,t,n)=>{setTimeout((async()=>{let r=5,o=(new Date).valueOf();try{const i=n-512;if(i<=0)throw new Error("The chunk size must be greater than 0.");let s=0;for(;s1)await a.send("ReceiveJSDataChunk",t,c,null);else{if(!await a.invoke("ReceiveJSDataChunk",t,c,null))break;const e=(new Date).valueOf(),n=e-o;o=e,r=Math.max(1,Math.round(500/n))}s+=n}}catch(e){await a.send("ReceiveJSDataChunk",t,null,e.toString())}}),0)};try{await a.start()}catch(e){Dn(a,e,n)}return e.attachDispatcher({beginInvokeDotNetFromJS:(e,t,n,r,o)=>{a.send("BeginInvokeDotNetFromJS",e?e.toString():null,t,n,r||0,o)},endInvokeJSFromDotNet:(e,t,n)=>{a.send("EndInvokeJSFromDotNet",e,t,n)},sendByteArray:(e,t)=>{a.send("ReceiveByteArray",e,t)}}),a}function Dn(e,t,n){n.log(en.Error,t),e&&e.stop()}fe.start=kn,document&&document.currentScript&&"false"!==document.currentScript.getAttribute("autostart")&&kn()})(); \ No newline at end of file From e7999971b009c549302e603e18609c4e1d588558 Mon Sep 17 00:00:00 2001 From: Tanay Parikh Date: Mon, 14 Jun 2021 16:59:03 -0700 Subject: [PATCH 19/37] Update InteropComponent.razor --- .../BasicTestApp/InteropComponent.razor | 20 ++++++++++++++----- 1 file changed, 15 insertions(+), 5 deletions(-) diff --git a/src/Components/test/testassets/BasicTestApp/InteropComponent.razor b/src/Components/test/testassets/BasicTestApp/InteropComponent.razor index 15283b0b25c8..998171734fa5 100644 --- a/src/Components/test/testassets/BasicTestApp/InteropComponent.razor +++ b/src/Components/test/testassets/BasicTestApp/InteropComponent.razor @@ -175,11 +175,21 @@ ReturnValues["roundTripByteArrayWrapperObjectFromDotNet"] = ((IJSInProcessRuntime)JSRuntime).Invoke("roundTripByteArrayWrapperObject", byteArrayWrapperObject).ToString(); } - var dataReference = await JSRuntime.InvokeAsync("jsToDotNetStreamAsync"); - using var stream = await dataReference.OpenReadStreamAsync(); - var jsToDotNetStreamAsyncResult = new byte[6]; - stream.CopyTo(jsToDotNetStreamAsyncResult, 0, jsToDotNetStreamAsyncResult.Length); - ReturnValues["jsToDotNetStreamAsync"] = string.Join(",", (jsToDotNetStreamAsyncResult.ToArray()); + // Only run this test for Blazor Server + if (shouldSupportSyncInterop) + { + // Set the result to the expected value in the WASM case to ensure + // missing this test case doesn't result in test failure. + ReturnValues["jsToDotNetStreamAsync"] = "1,5,7,15,35,200"; + } + else + { + var dataReference = await JSRuntime.InvokeAsync("jsToDotNetStreamAsync"); + using var stream = await dataReference.OpenReadStreamAsync(); + using var memoryStream = new System.IO.MemoryStream(); + await stream.CopyToAsync(memoryStream); + ReturnValues["jsToDotNetStreamAsync"] = string.Join(",", (memoryStream.ToArray())); + } Invocations = invocations; DoneWithInterop = true; From 9296a366391a5ebc1dc35b9bffa73145961759f1 Mon Sep 17 00:00:00 2001 From: Tanay Parikh Date: Mon, 14 Jun 2021 17:06:58 -0700 Subject: [PATCH 20/37] Make LinkedCTS More Efficient --- .../Server/src/Circuits/RemoteJSDataStream.cs | 20 +++++++++++++++---- 1 file changed, 16 insertions(+), 4 deletions(-) diff --git a/src/Components/Server/src/Circuits/RemoteJSDataStream.cs b/src/Components/Server/src/Circuits/RemoteJSDataStream.cs index ce3fe6378ceb..6976fc509aba 100644 --- a/src/Components/Server/src/Circuits/RemoteJSDataStream.cs +++ b/src/Components/Server/src/Circuits/RemoteJSDataStream.cs @@ -138,14 +138,26 @@ public override void Write(byte[] buffer, int offset, int count) public override async Task ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) { - var linkedCts = CancellationTokenSource.CreateLinkedTokenSource(_streamCancellationToken, cancellationToken); - return await _pipeReaderStream.ReadAsync(buffer.AsMemory(offset, count), linkedCts.Token); + return await _pipeReaderStream.ReadAsync(buffer.AsMemory(offset, count), GetLinkedCancellationToken(cancellationToken)); } public override async ValueTask ReadAsync(Memory buffer, CancellationToken cancellationToken = default) { - var linkedCts = CancellationTokenSource.CreateLinkedTokenSource(_streamCancellationToken, cancellationToken); - return await _pipeReaderStream.ReadAsync(buffer, linkedCts.Token); + return await _pipeReaderStream.ReadAsync(buffer, GetLinkedCancellationToken(cancellationToken)); + } + + private CancellationToken GetLinkedCancellationToken(CancellationToken readCancellationToken) + { + if (readCancellationToken.CanBeCanceled && _streamCancellationToken.CanBeCanceled) + { + return CancellationTokenSource.CreateLinkedTokenSource(_streamCancellationToken, readCancellationToken).Token; + } + else if (readCancellationToken.CanBeCanceled) + { + return readCancellationToken; + } + + return _streamCancellationToken; } protected override void Dispose(bool disposing) From e07686d9b01dc55c5d26b5a5db54140348898d1c Mon Sep 17 00:00:00 2001 From: Tanay Parikh Date: Mon, 14 Jun 2021 17:14:16 -0700 Subject: [PATCH 21/37] Update RemoteJSDataStream.cs --- .../Server/src/Circuits/RemoteJSDataStream.cs | 18 ++++++++++-------- 1 file changed, 10 insertions(+), 8 deletions(-) diff --git a/src/Components/Server/src/Circuits/RemoteJSDataStream.cs b/src/Components/Server/src/Circuits/RemoteJSDataStream.cs index 6976fc509aba..0196767bd745 100644 --- a/src/Components/Server/src/Circuits/RemoteJSDataStream.cs +++ b/src/Components/Server/src/Circuits/RemoteJSDataStream.cs @@ -138,26 +138,28 @@ public override void Write(byte[] buffer, int offset, int count) public override async Task ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) { - return await _pipeReaderStream.ReadAsync(buffer.AsMemory(offset, count), GetLinkedCancellationToken(cancellationToken)); + var linkedCancellationToken = GetLinkedCancellationToken(_streamCancellationToken, cancellationToken); + return await _pipeReaderStream.ReadAsync(buffer.AsMemory(offset, count), linkedCancellationToken); } public override async ValueTask ReadAsync(Memory buffer, CancellationToken cancellationToken = default) { - return await _pipeReaderStream.ReadAsync(buffer, GetLinkedCancellationToken(cancellationToken)); + var linkedCancellationToken = GetLinkedCancellationToken(_streamCancellationToken, cancellationToken); + return await _pipeReaderStream.ReadAsync(buffer, linkedCancellationToken); } - private CancellationToken GetLinkedCancellationToken(CancellationToken readCancellationToken) + private static CancellationToken GetLinkedCancellationToken(CancellationToken a, CancellationToken b) { - if (readCancellationToken.CanBeCanceled && _streamCancellationToken.CanBeCanceled) + if (a.CanBeCanceled && b.CanBeCanceled) { - return CancellationTokenSource.CreateLinkedTokenSource(_streamCancellationToken, readCancellationToken).Token; + return CancellationTokenSource.CreateLinkedTokenSource(a, b).Token; } - else if (readCancellationToken.CanBeCanceled) + else if (a.CanBeCanceled) { - return readCancellationToken; + return a; } - return _streamCancellationToken; + return b; } protected override void Dispose(bool disposing) From 12f7b89f983a26df1f6c593a83fc583b7bf10190 Mon Sep 17 00:00:00 2001 From: Tanay Parikh Date: Thu, 17 Jun 2021 11:50:39 -0700 Subject: [PATCH 22/37] Revert SignalR Changes --- src/SignalR/server/Core/src/Internal/DefaultHubDispatcher.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/SignalR/server/Core/src/Internal/DefaultHubDispatcher.cs b/src/SignalR/server/Core/src/Internal/DefaultHubDispatcher.cs index c58deacc52fe..1b355bea3a6e 100644 --- a/src/SignalR/server/Core/src/Internal/DefaultHubDispatcher.cs +++ b/src/SignalR/server/Core/src/Internal/DefaultHubDispatcher.cs @@ -22,7 +22,7 @@ namespace Microsoft.AspNetCore.SignalR.Internal { internal partial class DefaultHubDispatcher : HubDispatcher where THub : Hub { - private readonly Dictionary _methods = new(StringComparer.OrdinalIgnoreCase); + private readonly Dictionary _methods = new Dictionary(StringComparer.OrdinalIgnoreCase); private readonly IServiceScopeFactory _serviceScopeFactory; private readonly IHubContext _hubContext; private readonly ILogger> _logger; @@ -248,7 +248,7 @@ private Task ProcessInvocation(HubConnectionContext connection, } else { - var isStreamCall = descriptor.StreamingParameters != null; + bool isStreamCall = descriptor.StreamingParameters != null; if (connection.ActiveInvocationLimit != null && !isStreamCall && !isStreamResponse) { return connection.ActiveInvocationLimit.RunAsync(state => From e37413beae5f4ddc1ca0bb22f1e43c02bcbecd53 Mon Sep 17 00:00:00 2001 From: Tanay Parikh Date: Thu, 17 Jun 2021 16:00:08 -0700 Subject: [PATCH 23/37] PR Feedback --- .../Server/src/Circuits/RemoteJSDataStream.cs | 2 +- src/Components/Server/src/ComponentHub.cs | 2 +- .../Web.JS/dist/Release/blazor.server.js | 2 +- src/Components/Web.JS/src/Boot.Server.ts | 3 +- .../test/E2ETest/Tests/InteropTest.cs | 2 +- .../BasicTestApp/InteropComponent.razor | 30 +++++++++++++--- .../InteropTest/JSDataReferenceInterop.cs | 35 +++++++++++++++++++ .../BasicTestApp/wwwroot/js/jsinteroptests.js | 3 +- .../Microsoft.JSInterop/src/JSRuntime.cs | 2 +- .../JSInterop/JSCallResultTypeHelper.cs | 3 +- 10 files changed, 69 insertions(+), 15 deletions(-) create mode 100644 src/Components/test/testassets/BasicTestApp/InteropTest/JSDataReferenceInterop.cs diff --git a/src/Components/Server/src/Circuits/RemoteJSDataStream.cs b/src/Components/Server/src/Circuits/RemoteJSDataStream.cs index 0196767bd745..cfde4041a58c 100644 --- a/src/Components/Server/src/Circuits/RemoteJSDataStream.cs +++ b/src/Components/Server/src/Circuits/RemoteJSDataStream.cs @@ -113,7 +113,7 @@ private async Task ReceiveData(byte[] chunk, string error) public override bool CanWrite => false; - public override long Length => _pipeReaderStream.Length; + public override long Length => _totalLength; public override long Position { diff --git a/src/Components/Server/src/ComponentHub.cs b/src/Components/Server/src/ComponentHub.cs index 650bc762932f..d55c1036c905 100644 --- a/src/Components/Server/src/ComponentHub.cs +++ b/src/Components/Server/src/ComponentHub.cs @@ -221,7 +221,7 @@ public async ValueTask ReceiveByteArray(int id, byte[] data) return; } - await circuitHost.ReceiveByteArray(id, data); + _ = circuitHost.ReceiveByteArray(id, data); } public async ValueTask ReceiveJSDataChunk(long streamId, byte[] chunk, string error) diff --git a/src/Components/Web.JS/dist/Release/blazor.server.js b/src/Components/Web.JS/dist/Release/blazor.server.js index 2fc7959e9ae8..73def9442e00 100644 --- a/src/Components/Web.JS/dist/Release/blazor.server.js +++ b/src/Components/Web.JS/dist/Release/blazor.server.js @@ -1 +1 @@ -(()=>{"use strict";var e,t,n;!function(e){window.DotNet=e;const t=[],n=new Map;class r{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 o="__jsObjectId",i={},s={0:new r(window)};s[0]._cachedFunctions.set("import",(e=>("string"==typeof e&&e.startsWith("./")&&(e=document.baseURI+e.substr(2)),import(e))));let a,c=1,l=1,h=null;function u(e){t.push(e)}function d(e){if(e&&"object"==typeof e){s[l]=new r(e);const t={[o]:l};return l++,t}throw new Error(`Cannot create a JSObjectReference from the value '${e}'.`)}function p(e){if(!(e.buffer instanceof ArrayBuffer))throw new Error(`Cannot create a JSDataReference from the value '${e}' as it is not a valid ArrayBuffer.`);if(void 0===e.byteLength)throw new Error(`Cannot create a JSDataReference from the value '${e}' as it doesn't have a byteLength.`);const t={__jsDataReferenceLength:e.byteLength};try{const n=d(e);t.__jsObjectId=n.__jsObjectId}catch{throw new Error(`Cannot create a JSDataReference from the value '${e}'.`)}return t}function f(e){return e?JSON.parse(e,((e,n)=>t.reduce(((t,n)=>n(e,t)),n))):null}function g(e,t,n,r){const o=y();if(o.invokeDotNetFromJS){const i=k(r),s=o.invokeDotNetFromJS(e,t,n,i);return s?f(s):null}throw new Error("The current dispatcher does not support synchronous calls from JS to .NET. Use invokeMethodAsync instead.")}function m(e,t,n,r){if(e&&n)throw new Error(`For instance method calls, assemblyName should be null. Received '${e}'.`);const o=c++,s=new Promise(((e,t)=>{i[o]={resolve:e,reject:t}}));try{const i=k(r);y().beginInvokeDotNetFromJS(o,e,t,n,i)}catch(e){w(o,!1,e)}return s}function y(){if(null!==h)return h;throw new Error("No .NET call dispatcher has been set.")}function w(e,t,n){if(!i.hasOwnProperty(e))throw new Error(`There is no pending async call with ID ${e}.`);const r=i[e];delete i[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){let n=s[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 s[e]}e.attachDispatcher=function(e){h=e},e.attachReviver=u,e.invokeMethod=function(e,t,...n){return g(e,t,null,n)},e.invokeMethodAsync=function(e,t,...n){return m(e,t,null,n)},e.createJSObjectReference=d,e.createJSDataReference=p,e.disposeJSObjectReference=function(e){const t=e&&e.__jsObjectId;"number"==typeof t&&_(t)},function(e){e[e.Default=0]="Default",e[e.JSObjectReference=1]="JSObjectReference",e[e.JSDataReference=2]="JSDataReference"}(a=e.JSCallResultType||(e.JSCallResultType={})),e.jsCallDispatcher={findJSFunction:b,disposeJSObjectReferenceById:_,invokeJSFromDotNet:(e,t,n,r)=>{const o=C(b(e,r).apply(null,f(t)),n);return null==o?null:k(o)},beginInvokeJSFromDotNet:(e,t,n,r,o)=>{const i=new Promise((e=>{e(b(t,o).apply(null,f(n)))}));e&&i.then((t=>y().endInvokeJSFromDotNet(e,!0,k([e,!0,C(t,r)]))),(t=>y().endInvokeJSFromDotNet(e,!1,JSON.stringify([e,!1,v(t)]))))},endInvokeDotNetFromJS:(e,t,n)=>{const r=t?f(n):new Error(n);w(parseInt(e),t,r)},receiveByteArray:(e,t)=>{n.set(e,t)}};class E{constructor(e){this._id=e}invokeMethod(e,...t){return g(null,e,this._id,t)}invokeMethodAsync(e,...t){return m(null,e,this._id,t)}dispose(){m(null,"__Dispose",this._id,null).catch((e=>console.error(e)))}serializeAsArg(){return{__dotNetObject:this._id}}}const S="__byte[]";function C(e,t){switch(t){case a.Default:return e;case a.JSObjectReference:return d(e);case a.JSDataReference:return p(e);default:throw new Error(`Invalid JS call result type '${t}'.`)}}u((function(e,t){if(t&&"object"==typeof t){if(t.hasOwnProperty("__dotNetObject"))return new E(t.__dotNetObject);if(t.hasOwnProperty(o)){const e=t.__jsObjectId,n=s[e];if(n)return n.getWrappedObject();throw new Error(`JS object instance with Id '${e}' does not exist. It may have been disposed.`)}if(t.hasOwnProperty(S)){const e=t["__byte[]"],r=n.get(e);if(void 0===r)throw new Error(`Byte array index '${e}' does not exist.`);return r}}return t}));let I=0;function k(e){return I=0,JSON.stringify(e,T)}function T(e,t){if(t instanceof E)return t.serializeAsArg();if(t instanceof Uint8Array){h.sendByteArray(I,t);const e={[S]:I};return I++,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"}(n||(n={}));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}}let o;function i(e,t){if(!o)throw new Error("eventDispatcher not initialized. Call 'setEventDispatcher' to configure it.");o(e,t)}const s=new Map,a=new Map,c={createEventArgs:()=>({})},l=[];function h(e){return s.get(e)}function u(e){const t=s.get(e);return(null==t?void 0:t.browserEventName)||e}function d(e,t){e.forEach((e=>s.set(e,t)))}function p(e){const t=[];for(let n=0;n{return{...f(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}}),d(["focus","blur","focusin","focusout"],c),d(["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};var t}}),d(["contextmenu","click","mouseover","mouseout","mousemove","mousedown","mouseup","dblclick"],{createEventArgs:e=>f(e)}),d(["error"],{createEventArgs:e=>{return{message:(t=e).message,filename:t.filename,lineno:t.lineno,colno:t.colno};var t}}),d(["loadstart","timeout","abort","load","loadend","progress"],{createEventArgs:e=>{return{lengthComputable:(t=e).lengthComputable,loaded:t.loaded,total:t.total};var t}}),d(["touchcancel","touchend","touchmove","touchenter","touchleave","touchstart"],{createEventArgs:e=>{return{detail:(t=e).detail,touches:p(t.touches),targetTouches:p(t.targetTouches),changedTouches:p(t.changedTouches),ctrlKey:t.ctrlKey,shiftKey:t.shiftKey,altKey:t.altKey,metaKey:t.metaKey,type:t.type};var t}}),d(["gotpointercapture","lostpointercapture","pointercancel","pointerdown","pointerenter","pointerleave","pointermove","pointerout","pointerover","pointerup"],{createEventArgs:e=>{return{...f(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}}),d(["wheel","mousewheel"],{createEventArgs:e=>{return{...f(t=e),deltaX:t.deltaX,deltaY:t.deltaY,deltaZ:t.deltaZ,deltaMode:t.deltaMode};var t}}),d(["toggle"],c);const g=["date","datetime-local","month","time","week"],m=E(["abort","blur","change","error","focus","load","loadend","loadstart","mouseenter","mouseleave","progress","reset","scroll","submit","unload","toggle","DOMNodeInsertedIntoDocument","DOMNodeRemovedFromDocument"]),y={submit:!0},w=E(["click","dblclick","mousedown","mousemove","mouseup"]);class v{constructor(e){this.browserRendererId=e,this.afterClickCallbacks=[];const t=++v.nextEventDelegatorId;this.eventsCollectionKey=`_blazorEvents_${t}`,this.eventInfoStore=new b(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,a.get(n));var n;t&&t.forEach((t=>this.dispatchGlobalEventToAllElements(t,e))),"click"===e.type&&this.afterClickCallbacks.forEach((t=>t(e)))}dispatchGlobalEventToAllElements(e,t){let n=t.target,o=null,s=!1;const a=m.hasOwnProperty(e);let c=!1;for(;n;){const d=this.getEventHandlerInfosForElement(n,!1);if(d){const a=d.getHandler(e);if(a&&(l=n,u=t.type,!((l instanceof HTMLButtonElement||l instanceof HTMLInputElement||l instanceof HTMLTextAreaElement||l instanceof HTMLSelectElement)&&w.hasOwnProperty(u)&&l.disabled))){if(!s){const n=h(e);o=(null==n?void 0:n.createEventArgs)?n.createEventArgs(t):{},s=!0}y.hasOwnProperty(t.type)&&t.preventDefault(),i({browserRendererId:this.browserRendererId,eventHandlerId:a.eventHandlerId,eventName:e,eventFieldInfo:r.fromEvent(a.renderingComponentId,t)},o)}d.stopPropagation(e)&&(c=!0),d.preventDefault(e)&&t.preventDefault()}n=a||c?null:n.parentElement}var l,u}getEventHandlerInfosForElement(e,t){return e.hasOwnProperty(this.eventsCollectionKey)?e[this.eventsCollectionKey]:t?e[this.eventsCollectionKey]=new _:null}}v.nextEventDelegatorId=0;class b{constructor(e){this.globalListener=e,this.infosByEventHandlerId={},this.countByEventName={},l.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=u(e),this.countByEventName.hasOwnProperty(e))this.countByEventName[e]++;else{this.countByEventName[e]=1;const t=m.hasOwnProperty(e);document.addEventListener(e,this.globalListener,t)}}update(e,t){if(this.infosByEventHandlerId.hasOwnProperty(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=u(t.eventName);0==--this.countByEventName[n]&&(delete this.countByEventName[n],document.removeEventListener(n,this.globalListener))}return t}handleEventNameAliasAdded(e,t){if(this.countByEventName.hasOwnProperty(e)){const n=this.countByEventName[e];delete this.countByEventName[e],document.removeEventListener(e,this.globalListener),this.addGlobalListener(t),this.countByEventName[t]+=n-1}}}class _{constructor(){this.handlers={},this.preventDefaultFlags=null,this.stopPropagationFlags=null}getHandler(e){return this.handlers.hasOwnProperty(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 E(e){const t={};return e.forEach((e=>{t[e]=!0})),t}const S=O("_blazorLogicalChildren"),C=O("_blazorLogicalParent"),I=O("_blazorLogicalEnd");function k(e,t){if(e.childNodes.length>0&&!t)throw new Error("New logical elements must start empty, or allowExistingContents must be true");return S in e||(e[S]=[]),e}function T(e,t){const n=document.createComment("!");return D(n,e,t),n}function D(e,t,n){const r=e;if(e instanceof Comment&&A(r)&&A(r).length>0)throw new Error("Not implemented: inserting non-empty logical container");if(R(r))throw new Error("Not implemented: moving existing logical children");const o=A(t);if(n0;)x(n,0)}const r=n;r.parentNode.removeChild(r)}function R(e){return e[C]||null}function P(e,t){return A(e)[t]}function U(e){var t=B(e);return"http://www.w3.org/2000/svg"===t.namespaceURI&&"foreignObject"!==t.tagName}function A(e){return e[S]}function N(e,t){const n=A(e);t.forEach((e=>{e.moveRangeStart=n[e.fromSiblingIndex],e.moveRangeEnd=M(e.moveRangeStart)})),t.forEach((t=>{const r=t.moveToBeforeMarker=document.createComment("marker"),o=n[t.toSiblingIndex+1];o?o.parentNode.insertBefore(r,o):L(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 B(e){if(e instanceof Element)return e;if(e instanceof Comment)return e.parentNode;throw new Error("Not a valid logical element")}function $(e){const t=A(R(e));return t[Array.prototype.indexOf.call(t,e)+1]||null}function L(e,t){if(t instanceof Element)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=$(t);n?n.parentNode.insertBefore(e,n):L(e,R(t))}}}function M(e){if(e instanceof Element)return e;const t=$(e);if(t)return t.previousSibling;{const t=R(e);return t instanceof Element?t.lastChild:M(t)}}function O(e){return"function"==typeof Symbol?Symbol():e}function H(e){return`_bl_${e}`}e.attachReviver(((e,t)=>t&&"object"==typeof t&&t.hasOwnProperty("__internalId")&&"string"==typeof t.__internalId?function(e){const t=`[${H(e)}]`;return document.querySelector(t)}(t.__internalId):t));const F="_blazorSelectValue",j=document.createElement("template"),W=document.createElementNS("http://www.w3.org/2000/svg","g"),z={},q="__internal_",J="preventDefault_",K="stopPropagation_";class V{constructor(e){this.childComponentLocations={},this.eventDelegator=new v(e),this.eventDelegator.notifyAfterClick((e=>{if(!ee)return;if(0!==e.button||function(e){return e.ctrlKey||e.shiftKey||e.altKey||e.metaKey}(e))return;if(e.defaultPrevented)return;const t=function(e){const t=!window._blazorDisableComposedPath&&e.composedPath&&e.composedPath();if(t){for(let e=0;ese(!1))))},enableNavigationInterception:function(){ee=!0},navigateTo:oe,getBaseURI:()=>document.baseURI,getLocationHref:()=>location.href};function oe(e,t,n=!1){const r=ce(e);if(!t&&he(r))ie(r,!1,n);else if(t&&location.href===e){const t=e+"?";history.replaceState(null,"",t),location.replace(e)}else n?history.replaceState(null,"",r):location.href=e}function ie(e,t,n=!1){Z=!0,n?history.replaceState(null,"",e):history.pushState(null,"",e),se(t)}async function se(e){ne&&await ne(location.href,e)}let ae;function ce(e){return ae=ae||document.createElement("a"),ae.href=e,ae.href}function le(e,t){return e?e.tagName===t?e:le(e.parentElement,t):null}function he(e){const t=(n=document.baseURI).substr(0,n.lastIndexOf("/")+1);var n;return e.startsWith(t)}const ue={init:function(e,t,n,r=50){const o=pe(t);(o||document.documentElement).style.overflowAnchor="none";const i=new IntersectionObserver((function(r){r.forEach((r=>{var o;if(!r.isIntersecting)return;const i=t.getBoundingClientRect(),s=n.getBoundingClientRect().top-i.bottom,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`});i.observe(t),i.observe(n);const s=c(t),a=c(n);function c(e){const t=new MutationObserver((()=>{i.unobserve(e),i.observe(e)}));return t.observe(e,{attributes:!0}),t}de[e._id]={intersectionObserver:i,mutationObserverBefore:s,mutationObserverAfter:a}},dispose:function(e){const t=de[e._id];t&&(t.intersectionObserver.disconnect(),t.mutationObserverBefore.disconnect(),t.mutationObserverAfter.disconnect(),e.dispose(),delete de[e._id])}},de={};function pe(e){return e?"visible"!==getComputedStyle(e).overflowY?e:pe(e.parentElement):null}const fe={navigateTo:oe,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=a.get(t.browserEventName);n?n.push(e):a.set(t.browserEventName,[e]),l.forEach((n=>n(e,t.browserEventName)))}s.set(e,t)},_internal:{navigationManager:re,domWrapper:{focus:function(e,t){if(!(e instanceof HTMLElement))throw new Error("Unable to focus an invalid element.");e.focus({preventScroll:t})},focusBySelector:function(e){const t=document.querySelector(e);t&&(t.hasAttribute("tabindex")||(t.tabIndex=-1),t.focus())}},Virtualize:ue}};window.Blazor=fe;const ge=[0,2e3,1e4,3e4,null];class me{constructor(e){this._retryDelays=void 0!==e?[...e,null]:ge}nextRetryDelayInMilliseconds(e){return this._retryDelays[e.previousRetryCount]}}class ye extends Error{constructor(e,t){const n=new.target.prototype;super(`${e}: Status code '${t}'`),this.statusCode=t,this.__proto__=n}}class we extends Error{constructor(e="A timeout occurred."){const t=new.target.prototype;super(e),this.__proto__=t}}class ve extends Error{constructor(e="An abort occurred."){const t=new.target.prototype;super(e),this.__proto__=t}}class be{constructor(e,t,n){this.statusCode=e,this.statusText=t,this.content=n}}class _e{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""}}var Ee,Se,Ce,Ie,ke;!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"}(Ee||(Ee={}));class Te extends _e{constructor(e){if(super(),this._logger=e,"undefined"==typeof fetch){const e=require;this._jar=new(e("tough-cookie").CookieJar),this._fetchType=e("node-fetch"),this._fetchType=e("fetch-cookie")(this._fetchType,this._jar),this._abortControllerType=e("abort-controller")}else this._fetchType=fetch.bind(self),this._abortControllerType=AbortController}async send(e){if(e.abortSignal&&e.abortSignal.aborted)throw new ve;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 ve});let r,o=null;if(e.timeout){const r=e.timeout;o=setTimeout((()=>{t.abort(),this._logger.log(Ee.Warning,"Timeout from HTTP request."),n=new we}),r)}try{r=await this._fetchType(e.url,{body:e.content,cache:"no-cache",credentials:!0===e.withCredentials?"include":"same-origin",headers:{"Content-Type":"text/plain;charset=UTF-8","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(Ee.Warning,`Error from HTTP request. ${e}.`),e}finally{o&&clearTimeout(o),e.abortSignal&&(e.abortSignal.onabort=null)}if(!r.ok){const e=await De(r,"text");throw new ye(e||r.statusText,r.status)}const i=De(r,e.responseType),s=await i;return new be(r.status,r.statusText,s)}getCookieString(e){return""}}function De(e,t){let n;switch(t){case"arraybuffer":n=e.arrayBuffer();break;case"text":n=e.text();break;case"blob":case"document":case"json":throw new Error(`${t} is not supported.`);default:n=e.text()}return n}class xe extends _e{constructor(e){super(),this._logger=e}send(e){return e.abortSignal&&e.abortSignal.aborted?Promise.reject(new ve):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"),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 ve)}),e.timeout&&(r.timeout=e.timeout),r.onload=()=>{e.abortSignal&&(e.abortSignal.onabort=null),r.status>=200&&r.status<300?t(new be(r.status,r.statusText,r.response||r.responseText)):n(new ye(r.response||r.responseText||r.statusText,r.status))},r.onerror=()=>{this._logger.log(Ee.Warning,`Error from HTTP request. ${r.status}: ${r.statusText}.`),n(new ye(r.statusText,r.status))},r.ontimeout=()=>{this._logger.log(Ee.Warning,"Timeout from HTTP request."),n(new we)},r.send(e.content||"")})):Promise.reject(new Error("No url defined.")):Promise.reject(new Error("No method defined."))}}class Re extends _e{constructor(e){if(super(),"undefined"!=typeof fetch)this._httpClient=new Te(e);else{if("undefined"==typeof XMLHttpRequest)throw new Error("No usable HttpClient found.");this._httpClient=new xe(e)}}send(e){return e.abortSignal&&e.abortSignal.aborted?Promise.reject(new ve):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)}}class Pe{}Pe.Authorization="Authorization",Pe.Cookie="Cookie",function(e){e[e.None=0]="None",e[e.WebSockets=1]="WebSockets",e[e.ServerSentEvents=2]="ServerSentEvents",e[e.LongPolling=4]="LongPolling"}(Se||(Se={})),function(e){e[e.Text=1]="Text",e[e.Binary=2]="Binary"}(Ce||(Ce={}));class Ue{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 Ae{constructor(){}log(e,t){}}Ae.instance=new Ae;class Ne{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 Be{static get isBrowser(){return"object"==typeof window}static get isWebWorker(){return"object"==typeof self&&"importScripts"in self}static get isNode(){return!this.isBrowser&&!this.isWebWorker}}function $e(e,t){let n="";return Le(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 Le(e){return e&&"undefined"!=typeof ArrayBuffer&&(e instanceof ArrayBuffer||e.constructor&&"ArrayBuffer"===e.constructor.name)}async function Me(e,t,n,r,o,i,s,a,c){let l={};if(o){const e=await o();e&&(l={Authorization:`Bearer ${e}`})}const[h,u]=Fe();l[h]=u,e.log(Ee.Trace,`(${t} transport) sending data. ${$e(i,s)}.`);const d=Le(i)?"arraybuffer":"text",p=await n.post(r,{content:i,headers:{...l,...c},responseType:d,withCredentials:a});e.log(Ee.Trace,`(${t} transport) request complete. Response status: ${p.statusCode}.`)}class Oe{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 He{constructor(e){this._minLevel=e,this.out=console}log(e,t){if(e>=this._minLevel){const n=`[${(new Date).toISOString()}] ${Ee[e]}: ${t}`;switch(e){case Ee.Critical:case Ee.Error:this.out.error(n);break;case Ee.Warning:this.out.warn(n);break;case Ee.Information:this.out.info(n);break;default:this.out.log(n)}}}}function Fe(){let e="X-SignalR-User-Agent";return Be.isNode&&(e="User-Agent"),[e,je("0.0.0-DEV_BUILD",We(),Be.isNode?"NodeJS":"Browser",ze())]}function je(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 We(){if(!Be.isNode)return"";switch(process.platform){case"win32":return"Windows NT";case"darwin":return"macOS";case"linux":return"Linux";default:return process.platform}}function ze(){if(Be.isNode)return process.versions.node}class qe{constructor(e,t,n,r,o,i){this._httpClient=e,this._accessTokenFactory=t,this._logger=n,this._pollAbort=new Ue,this._logMessageContent=r,this._withCredentials=o,this._headers=i,this._running=!1,this.onreceive=null,this.onclose=null}get pollAborted(){return this._pollAbort.aborted}async connect(e,t){if(Ne.isRequired(e,"url"),Ne.isRequired(t,"transferFormat"),Ne.isIn(t,Ce,"transferFormat"),this._url=e,this._logger.log(Ee.Trace,"(LongPolling transport) Connecting."),t===Ce.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]=Fe(),o={[n]:r,...this._headers},i={abortSignal:this._pollAbort.signal,headers:o,timeout:1e5,withCredentials:this._withCredentials};t===Ce.Binary&&(i.responseType="arraybuffer");const s=await this._getAccessToken();this._updateHeaderToken(i,s);const a=`${e}&_=${Date.now()}`;this._logger.log(Ee.Trace,`(LongPolling transport) polling: ${a}.`);const c=await this._httpClient.get(a,i);200!==c.statusCode?(this._logger.log(Ee.Error,`(LongPolling transport) Unexpected response code: ${c.statusCode}.`),this._closeError=new ye(c.statusText||"",c.statusCode),this._running=!1):this._running=!0,this._receiving=this._poll(this._url,i)}async _getAccessToken(){return this._accessTokenFactory?await this._accessTokenFactory():null}_updateHeaderToken(e,t){e.headers||(e.headers={}),t?e.headers[Pe.Authorization]=`Bearer ${t}`:e.headers[Pe.Authorization]&&delete e.headers[Pe.Authorization]}async _poll(e,t){try{for(;this._running;){const n=await this._getAccessToken();this._updateHeaderToken(t,n);try{const n=`${e}&_=${Date.now()}`;this._logger.log(Ee.Trace,`(LongPolling transport) polling: ${n}.`);const r=await this._httpClient.get(n,t);204===r.statusCode?(this._logger.log(Ee.Information,"(LongPolling transport) Poll terminated by server."),this._running=!1):200!==r.statusCode?(this._logger.log(Ee.Error,`(LongPolling transport) Unexpected response code: ${r.statusCode}.`),this._closeError=new ye(r.statusText||"",r.statusCode),this._running=!1):r.content?(this._logger.log(Ee.Trace,`(LongPolling transport) data received. ${$e(r.content,this._logMessageContent)}.`),this.onreceive&&this.onreceive(r.content)):this._logger.log(Ee.Trace,"(LongPolling transport) Poll timed out, reissuing.")}catch(e){this._running?e instanceof we?this._logger.log(Ee.Trace,"(LongPolling transport) Poll timed out, reissuing."):(this._closeError=e,this._running=!1):this._logger.log(Ee.Trace,`(LongPolling transport) Poll errored after shutdown: ${e.message}`)}}}finally{this._logger.log(Ee.Trace,"(LongPolling transport) Polling complete."),this.pollAborted||this._raiseOnClose()}}async send(e){return this._running?Me(this._logger,"LongPolling",this._httpClient,this._url,this._accessTokenFactory,e,this._logMessageContent,this._withCredentials,this._headers):Promise.reject(new Error("Cannot send until the transport is connected"))}async stop(){this._logger.log(Ee.Trace,"(LongPolling transport) Stopping polling."),this._running=!1,this._pollAbort.abort();try{await this._receiving,this._logger.log(Ee.Trace,`(LongPolling transport) sending DELETE request to ${this._url}.`);const e={},[t,n]=Fe();e[t]=n;const r={headers:{...e,...this._headers},withCredentials:this._withCredentials},o=await this._getAccessToken();this._updateHeaderToken(r,o),await this._httpClient.delete(this._url,r),this._logger.log(Ee.Trace,"(LongPolling transport) DELETE request sent.")}finally{this._logger.log(Ee.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(Ee.Trace,e),this.onclose(this._closeError)}}}class Je{constructor(e,t,n,r,o,i,s){this._httpClient=e,this._accessTokenFactory=t,this._logger=n,this._logMessageContent=r,this._withCredentials=i,this._eventSourceConstructor=o,this._headers=s,this.onreceive=null,this.onclose=null}async connect(e,t){if(Ne.isRequired(e,"url"),Ne.isRequired(t,"transferFormat"),Ne.isIn(t,Ce,"transferFormat"),this._logger.log(Ee.Trace,"(SSE transport) Connecting."),this._url=e,this._accessTokenFactory){const t=await this._accessTokenFactory();t&&(e+=(e.indexOf("?")<0?"?":"&")+`access_token=${encodeURIComponent(t)}`)}return new Promise(((n,r)=>{let o,i=!1;if(t===Ce.Text){if(Be.isBrowser||Be.isWebWorker)o=new this._eventSourceConstructor(e,{withCredentials:this._withCredentials});else{const t=this._httpClient.getCookieString(e),n={};n.Cookie=t;const[r,i]=Fe();n[r]=i,o=new this._eventSourceConstructor(e,{withCredentials:this._withCredentials,headers:{...n,...this._headers}})}try{o.onmessage=e=>{if(this.onreceive)try{this._logger.log(Ee.Trace,`(SSE transport) data received. ${$e(e.data,this._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(Ee.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?Me(this._logger,"SSE",this._httpClient,this._url,this._accessTokenFactory,e,this._logMessageContent,this._withCredentials,this._headers):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 Ke{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){if(Ne.isRequired(e,"url"),Ne.isRequired(t,"transferFormat"),Ne.isIn(t,Ce,"transferFormat"),this._logger.log(Ee.Trace,"(WebSockets transport) Connecting."),this._accessTokenFactory){const t=await this._accessTokenFactory();t&&(e+=(e.indexOf("?")<0?"?":"&")+`access_token=${encodeURIComponent(t)}`)}return new Promise(((n,r)=>{let o;e=e.replace(/^http/,"ws"),this._httpClient.getCookieString(e);let i=!1;o||(o=new this._webSocketConstructor(e)),t===Ce.Binary&&(o.binaryType="arraybuffer"),o.onopen=t=>{this._logger.log(Ee.Information,`WebSocket connected to ${e}.`),this._webSocket=o,i=!0,n()},o.onerror=e=>{let t=null;t="undefined"!=typeof ErrorEvent&&e instanceof ErrorEvent?e.error:"There was an error with the transport",this._logger.log(Ee.Information,`(WebSockets transport) ${t}.`)},o.onmessage=e=>{if(this._logger.log(Ee.Trace,`(WebSockets transport) data received. ${$e(e.data,this._logMessageContent)}.`),this.onreceive)try{this.onreceive(e.data)}catch(e){return void this._close(e)}},o.onclose=e=>{if(i)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(Ee.Trace,`(WebSockets transport) sending data. ${$e(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(Ee.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 Ve{constructor(e,t={}){var n;if(this._stopPromiseResolver=()=>{},this.features={},this._negotiateVersion=1,Ne.isRequired(e,"url"),this._logger=void 0===(n=t.logger)?new He(Ee.Information):null===n?Ae.instance:void 0!==n.log?n:new He(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,"undefined"==typeof WebSocket||t.WebSocket||(t.WebSocket=WebSocket),"undefined"==typeof EventSource||t.EventSource||(t.EventSource=EventSource),this._httpClient=t.httpClient||new Re(this._logger),this._connectionState="Disconnected",this._connectionStarted=!1,this._options=t,this.onreceive=null,this.onclose=null}async start(e){if(e=e||Ce.Binary,Ne.isIn(e,Ce,"transferFormat"),this._logger.log(Ee.Debug,`Starting connection with transfer format '${Ce[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(Ee.Error,e),await this._stopPromise,Promise.reject(new Error(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(Ee.Error,e),Promise.reject(new Error(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 Xe(this.transport)),this._sendQueue.send(e))}async stop(e){return"Disconnected"===this._connectionState?(this._logger.log(Ee.Debug,`Call to HttpConnection.stop(${e}) ignored because the connection is already in the disconnected state.`),Promise.resolve()):"Disconnecting"===this._connectionState?(this._logger.log(Ee.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(Ee.Error,`HttpConnection.transport.stop() threw error '${e}'.`),this._stopConnection()}this.transport=void 0}else this._logger.log(Ee.Debug,"HttpConnection.transport is undefined in HttpConnection.stop() because start() failed.")}async _startInternal(e){let t=this.baseUrl;this._accessTokenFactory=this._options.accessTokenFactory;try{if(this._options.skipNegotiation){if(this._options.transport!==Se.WebSockets)throw new Error("Negotiation can only be skipped when using the WebSocket transport directly.");this.transport=this._constructTransport(Se.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 Error("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}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 qe&&(this.features.inherentKeepAlive=!0),"Connecting"===this._connectionState&&(this._logger.log(Ee.Debug,"The HttpConnection connected successfully."),this._connectionState="Connected")}catch(e){return this._logger.log(Ee.Error,"Failed to start the connection: "+e),this._connectionState="Disconnected",this.transport=void 0,this._stopPromiseResolver(),Promise.reject(e)}}async _getNegotiationResponse(e){const t={};if(this._accessTokenFactory){const e=await this._accessTokenFactory();e&&(t[Pe.Authorization]=`Bearer ${e}`)}const[n,r]=Fe();t[n]=r;const o=this._resolveNegotiateUrl(e);this._logger.log(Ee.Debug,`Sending negotiation request: ${o}.`);try{const e=await this._httpClient.post(o,{content:"",headers:{...t,...this._options.headers},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 ye&&404===e.statusCode&&(t+=" Either this is not a SignalR endpoint or there is a proxy blocking the connection."),this._logger.log(Ee.Error,t),Promise.reject(new Error(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(Ee.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: ${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(Ee.Error,`Failed to start the transport '${n.transport}': ${e}`),a=void 0,i.push(`${n.transport} failed: ${e}`),"Connecting"!==this._connectionState){const e="Failed to select transport before stop() was called.";return this._logger.log(Ee.Debug,e),Promise.reject(new Error(e))}}}}return i.length>0?Promise.reject(new Error(`Unable to connect to the server with any of the available transports. ${i.join(" ")}`)):Promise.reject(new Error("None of the transports supported by the client are supported by the server."))}_constructTransport(e){switch(e){case Se.WebSockets:if(!this._options.WebSocket)throw new Error("'WebSocket' is not supported in your environment.");return new Ke(this._httpClient,this._accessTokenFactory,this._logger,this._options.logMessageContent||!1,this._options.WebSocket,this._options.headers||{});case Se.ServerSentEvents:if(!this._options.EventSource)throw new Error("'EventSource' is not supported in your environment.");return new Je(this._httpClient,this._accessTokenFactory,this._logger,this._options.logMessageContent||!1,this._options.EventSource,this._options.withCredentials,this._options.headers||{});case Se.LongPolling:return new qe(this._httpClient,this._accessTokenFactory,this._logger,this._options.logMessageContent||!1,this._options.withCredentials,this._options.headers||{});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=Se[e.transport];if(null==r)return this._logger.log(Ee.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(Ee.Debug,`Skipping transport '${Se[r]}' because it was disabled by the client.`),new Error(`'${Se[r]}' is disabled by the client.`);if(!(e.transferFormats.map((e=>Ce[e])).indexOf(n)>=0))return this._logger.log(Ee.Debug,`Skipping transport '${Se[r]}' because it does not support the requested transfer format '${Ce[n]}'.`),new Error(`'${Se[r]}' does not support ${Ce[n]}.`);if(r===Se.WebSockets&&!this._options.WebSocket||r===Se.ServerSentEvents&&!this._options.EventSource)return this._logger.log(Ee.Debug,`Skipping transport '${Se[r]}' because it is not supported in your environment.'`),new Error(`'${Se[r]}' is not supported in your environment.`);this._logger.log(Ee.Debug,`Selecting transport '${Se[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(Ee.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(Ee.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(Ee.Error,`Connection disconnected with error '${e}'.`):this._logger.log(Ee.Information,"Connection disconnected."),this._sendQueue&&(this._sendQueue.stop().catch((e=>{this._logger.log(Ee.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(Ee.Error,`HttpConnection.onclose(${e}) threw error '${t}'.`)}}}else this._logger.log(Ee.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(!Be.isBrowser||!window.document)throw new Error(`Cannot resolve '${e}'.`);const t=window.document.createElement("a");return t.href=e,this._logger.log(Ee.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 Xe{constructor(e){this._transport=e,this._buffer=[],this._executing=!0,this._sendBufferedData=new Ye,this._transportResult=new Ye,this._sendLoopPromise=this._sendLoop()}send(e){return this._bufferData(e),this._transportResult||(this._transportResult=new Ye),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 Ye;const e=this._transportResult;this._transportResult=void 0;const t="string"==typeof this._buffer[0]?this._buffer.join(""):Xe._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 Ye{constructor(){this.promise=new Promise(((e,t)=>[this._resolver,this._rejecter]=[e,t]))}resolve(){this._resolver()}reject(e){this._rejecter(e)}}class Ge{static write(e){return`${e}${Ge.RecordSeparator}`}static parse(e){if(e[e.length-1]!==Ge.RecordSeparator)throw new Error("Message is incomplete.");const t=e.split(Ge.RecordSeparator);return t.pop(),t}}Ge.RecordSeparatorCode=30,Ge.RecordSeparator=String.fromCharCode(Ge.RecordSeparatorCode);class Qe{writeHandshakeRequest(e){return Ge.write(JSON.stringify(e))}parseHandshakeResponse(e){let t,n;if(Le(e)){const r=new Uint8Array(e),o=r.indexOf(Ge.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(Ge.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=Ge.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"}(Ie||(Ie={}));class Ze{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 Oe(this,e)}}!function(e){e.Disconnected="Disconnected",e.Connecting="Connecting",e.Connected="Connected",e.Disconnecting="Disconnecting",e.Reconnecting="Reconnecting"}(ke||(ke={}));class et{constructor(e,t,n,r){this._nextKeepAlive=0,Ne.isRequired(e,"connection"),Ne.isRequired(t,"logger"),Ne.isRequired(n,"protocol"),this.serverTimeoutInMilliseconds=3e4,this.keepAliveIntervalInMilliseconds=15e3,this._logger=t,this._protocol=n,this.connection=e,this._reconnectPolicy=r,this._handshakeProtocol=new Qe,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=ke.Disconnected,this._connectionStarted=!1,this._cachedPingMessage=this._protocol.writeMessage({type:Ie.Ping})}static create(e,t,n,r){return new et(e,t,n,r)}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!==ke.Disconnected&&this._connectionState!==ke.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!==ke.Disconnected)return Promise.reject(new Error("Cannot start a HubConnection that is not in the 'Disconnected' state."));this._connectionState=ke.Connecting,this._logger.log(Ee.Debug,"Starting HubConnection.");try{await this._startInternal(),this._connectionState=ke.Connected,this._connectionStarted=!0,this._logger.log(Ee.Debug,"HubConnection connected successfully.")}catch(e){return this._connectionState=ke.Disconnected,this._logger.log(Ee.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(Ee.Debug,"Sending handshake request."),await this._sendMessage(this._handshakeProtocol.writeHandshakeRequest(t)),this._logger.log(Ee.Information,`Using HubProtocol '${this._protocol.name}'.`),this._cleanupTimeout(),this._resetTimeoutPeriod(),this._resetKeepAliveInterval(),await e,this._stopDuringStartError)throw this._stopDuringStartError}catch(e){throw this._logger.log(Ee.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){return this._connectionState===ke.Disconnected?(this._logger.log(Ee.Debug,`Call to HubConnection.stop(${e}) ignored because it is already in the disconnected state.`),Promise.resolve()):this._connectionState===ke.Disconnecting?(this._logger.log(Ee.Debug,`Call to HttpConnection.stop(${e}) ignored because the connection is already in the disconnecting state.`),this._stopPromise):(this._connectionState=ke.Disconnecting,this._logger.log(Ee.Debug,"Stopping HubConnection."),this._reconnectDelayHandle?(this._logger.log(Ee.Debug,"Connection stopped during reconnect delay. Done reconnecting."),clearTimeout(this._reconnectDelayHandle),this._reconnectDelayHandle=void 0,this._completeClose(),Promise.resolve()):(this._cleanupTimeout(),this._cleanupPingTimer(),this._stopDuringStartError=e||new Error("The connection was stopped before the hub handshake could complete."),this.connection.stop(e)))}stream(e,...t){const[n,r]=this._replaceStreamingParams(t),o=this._createStreamInvocation(e,t,r);let i;const s=new Ze;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===Ie.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===Ie.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 Ie.Invocation:this._invokeClientMethod(e);break;case Ie.StreamItem:case Ie.Completion:{const t=this._callbacks[e.invocationId];t&&(e.type===Ie.Completion&&delete this._callbacks[e.invocationId],t(e));break}case Ie.Ping:break;case Ie.Close:{this._logger.log(Ee.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(Ee.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(Ee.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(Ee.Error,e);const n=new Error(e);throw this._handshakeRejecter(n),n}return this._logger.log(Ee.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===ke.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."))}_invokeClientMethod(e){const t=this._methods[e.target.toLowerCase()];if(t){try{t.forEach((t=>t.apply(this,e.arguments)))}catch(t){this._logger.log(Ee.Error,`A callback for the method ${e.target.toLowerCase()} threw error '${t}'.`)}if(e.invocationId){const e="Server requested a response, which is not supported in this version of the client.";this._logger.log(Ee.Error,e),this._stopPromise=this._stopInternal(new Error(e))}}else this._logger.log(Ee.Warning,`No client method with the name '${e.target}' found.`)}_connectionClosed(e){this._logger.log(Ee.Debug,`HubConnection.connectionClosed(${e}) called while in state ${this._connectionState}.`),this._stopDuringStartError=this._stopDuringStartError||e||new Error("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===ke.Disconnecting?this._completeClose(e):this._connectionState===ke.Connected&&this._reconnectPolicy?this._reconnect(e):this._connectionState===ke.Connected&&this._completeClose(e)}_completeClose(e){if(this._connectionStarted){this._connectionState=ke.Disconnected,this._connectionStarted=!1;try{this._closedCallbacks.forEach((t=>t.apply(this,[e])))}catch(t){this._logger.log(Ee.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(Ee.Debug,"Connection not reconnecting because the IRetryPolicy returned null on the first reconnect attempt."),void this._completeClose(e);if(this._connectionState=ke.Reconnecting,e?this._logger.log(Ee.Information,`Connection reconnecting because of error '${e}'.`):this._logger.log(Ee.Information,"Connection reconnecting."),0!==this._reconnectingCallbacks.length){try{this._reconnectingCallbacks.forEach((t=>t.apply(this,[e])))}catch(t){this._logger.log(Ee.Error,`An onreconnecting callback called with error '${e}' threw error '${t}'.`)}if(this._connectionState!==ke.Reconnecting)return void this._logger.log(Ee.Debug,"Connection left the reconnecting state in onreconnecting callback. Done reconnecting.")}for(;null!==o;){if(this._logger.log(Ee.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!==ke.Reconnecting)return void this._logger.log(Ee.Debug,"Connection left the reconnecting state during reconnect delay. Done reconnecting.");try{if(await this._startInternal(),this._connectionState=ke.Connected,this._logger.log(Ee.Information,"HubConnection reconnected successfully."),0!==this._reconnectedCallbacks.length)try{this._reconnectedCallbacks.forEach((e=>e.apply(this,[this.connection.connectionId])))}catch(e){this._logger.log(Ee.Error,`An onreconnected callback called with connectionId '${this.connection.connectionId}; threw error '${e}'.`)}return}catch(e){if(this._logger.log(Ee.Information,`Reconnect attempt failed because of error '${e}'.`),this._connectionState!==ke.Reconnecting)return this._logger.log(Ee.Debug,`Connection moved to the '${this._connectionState}' from the reconnecting state during reconnect attempt. Done reconnecting.`),void(this._connectionState===ke.Disconnecting&&this._completeClose());r=e instanceof Error?e:new Error(e.toString()),o=this._getNextRetryDelay(n++,Date.now()-t,r)}}this._logger.log(Ee.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(Ee.Error,`IRetryPolicy.nextRetryDelayInMilliseconds(${e}, ${t}) threw error '${n}'.`),null}}_cancelCallbacksWithError(e){const t=this._callbacks;this._callbacks={},Object.keys(t).forEach((n=>{(0,t[n])(null,e)}))}_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:Ie.Invocation}:{arguments:t,target:e,type:Ie.Invocation};{const n=this._invocationId;return this._invocationId++,0!==r.length?{arguments:t,invocationId:n.toString(),streamIds:r,target:e,type:Ie.Invocation}:{arguments:t,invocationId:n.toString(),target:e,type:Ie.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 ut=ot?new TextDecoder:null,dt=ot?"undefined"!=typeof process&&"force"!==process.env.TEXT_DECODER?200:0:it,pt=function(e,t){this.type=e,this.data=t};function ft(e,t,n){var r=Math.floor(n/4294967296),o=n;e.setUint32(t,r),e.setUint32(t+4,o)}function gt(e,t){return 4294967296*e.getInt32(t)+e.getUint32(t+4)}var mt={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),ft(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:gt(t,4),nsec:t.getUint32(0)};default:throw new Error("Unrecognized data size for timestamp: "+e.length)}}(e);return new Date(1e3*t.sec+t.nsec/1e6)}},yt=function(){function e(){this.builtInEncoders=[],this.builtInDecoders=[],this.encoders=[],this.decoders=[],this.register(mt)}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 "+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: "+e+" bytes in UTF-8");this.writeU8(219),this.writeU32(e)}},e.prototype.encodeString=function(e){if(e.length>ct){var t=st(e);this.ensureBufferSizeToWrite(5+t),this.writeStringHeader(t),lt(e,this.bytes,this.pos),this.pos+=t}else t=st(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: "+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: "+t);this.writeU8(198),this.writeU32(t)}var n=wt(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: "+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=ht(e,t,n),i=Uint8Array.prototype.slice.call(e,t,t+n);return this.store(i,o),o},e}(),St=(_t=function(e,t){return(_t=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])})(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}_t(e,t),e.prototype=null===t?Object.create(t):(n.prototype=t.prototype,new n)}),Ct=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]1||a(e,t)}))})}function a(e,t){try{(n=o[e](t)).value instanceof kt?Promise.resolve(n.value.v).then(c,l):h(i[0][2],n)}catch(e){h(i[0][3],e)}var n}function c(e){a("next",e)}function l(e){a("throw",e)}function h(e,t){e(t),i.shift(),i.length&&a(i[0][0],i[0][1])}},Dt=new DataView(new ArrayBuffer(0)),xt=new Uint8Array(Dt.buffer),Rt=function(){try{Dt.getInt8(0)}catch(e){return e.constructor}throw new Error("never reached")}(),Pt=new Rt("Insufficient data"),Ut=4294967295,At=new Et,Nt=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 St(t,e),t}(Error),Bt=function(){function e(e,t,n,r,o,i,s,a){void 0===e&&(e=yt.defaultCodec),void 0===t&&(t=void 0),void 0===n&&(n=Ut),void 0===r&&(r=Ut),void 0===o&&(o=Ut),void 0===i&&(i=Ut),void 0===s&&(s=Ut),void 0===a&&(a=At),this.extensionCodec=e,this.context=t,this.maxStrLength=n,this.maxBinLength=r,this.maxArrayLength=o,this.maxMapLength=i,this.maxExtLength=s,this.keyDecoder=a,this.totalPos=0,this.pos=0,this.view=Dt,this.bytes=xt,this.headByte=-1,this.stack=[]}return e.prototype.reinitializeState=function(){this.totalPos=0,this.headByte=-1,this.stack.length=0},e.prototype.setBuffer=function(e){this.bytes=wt(e),this.view=function(e){if(e instanceof ArrayBuffer)return new DataView(e);var t=wt(e);return new DataView(t.buffer,t.byteOffset,t.byteLength)}(this.bytes),this.pos=0},e.prototype.appendBuffer=function(e){if(-1!==this.headByte||this.hasRemaining()){var t=this.bytes.subarray(this.pos),n=wt(e),r=new Uint8Array(t.length+n.length);r.set(t),r.set(n,t.length),this.setBuffer(r)}else this.setBuffer(e)},e.prototype.hasRemaining=function(e){return void 0===e&&(e=1),this.view.byteLength-this.pos>=e},e.prototype.createExtraByteError=function(e){var t=this.view,n=this.pos;return new RangeError("Extra "+(t.byteLength-n)+" of "+t.byteLength+" byte(s) found at buffer["+e+"]")},e.prototype.decode=function(e){this.reinitializeState(),this.setBuffer(e);var t=this.doDecodeSync();if(this.hasRemaining())throw this.createExtraByteError(this.pos);return t},e.prototype.decodeMulti=function(e){return Ct(this,(function(t){switch(t.label){case 0:this.reinitializeState(),this.setBuffer(e),t.label=1;case 1:return this.hasRemaining()?[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,u,d;return Ct(this,(function(p){switch(p.label){case 0:i=!1,p.label=1;case 1:p.trys.push([1,6,7,12]),t=It(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 Rt))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())throw this.createExtraByteError(this.totalPos);return[2,s]}throw h=(l=this).headByte,u=l.pos,d=l.totalPos,new RangeError("Insufficient data in parsing "+bt(h)+" at "+d+" ("+u+" 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 Tt(this,arguments,(function(){var n,r,o,i,s,a,c,l,h;return Ct(this,(function(u){switch(u.label){case 0:n=t,r=-1,u.label=1;case 1:u.trys.push([1,13,14,19]),o=It(e),u.label=2;case 2:return[4,kt(o.next())];case 3:if((i=u.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()),u.label=4;case 4:u.trys.push([4,9,,10]),u.label=5;case 5:return[4,kt(this.doDecodeSync())];case 6:return[4,u.sent()];case 7:return u.sent(),0==--r?[3,8]:[3,5];case 8:return[3,10];case 9:if(!((a=u.sent())instanceof Rt))throw a;return[3,10];case 10:this.totalPos+=this.pos,u.label=11;case 11:return[3,2];case 12:return[3,19];case 13:return c=u.sent(),l={error:c},[3,19];case 14:return u.trys.push([14,,17,18]),i&&!i.done&&(h=o.return)?[4,kt(h.call(o))]:[3,16];case 15:u.sent(),u.label=16;case 16:return[3,18];case 17:if(l)throw l.error;return[7];case 18:return[7];case 19:return[2]}}))}))},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 Nt("Unrecognized type byte: "+bt(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 Nt("The type of key must be string or number but "+typeof t);if("__proto__"===t)throw new Nt("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 Nt("Unrecognized array type byte: "+bt(e))}},e.prototype.pushMapState=function(e){if(e>this.maxMapLength)throw new Nt("Max length exceeded: map length ("+e+") > maxMapLengthLength ("+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 Nt("Max length exceeded: array length ("+e+") > maxArrayLength ("+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 Nt("Max length exceeded: UTF-8 byte length ("+e+") > maxStrLength ("+this.maxStrLength+")");if(this.bytes.byteLengthdt?function(e,t,n){var r=e.subarray(t,t+n);return ut.decode(r)}(this.bytes,o,e):ht(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 Nt("Max length exceeded: bin length ("+e+") > maxBinLength ("+this.maxBinLength+")");if(!this.hasRemaining(e+t))throw Pt;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 Nt("Max length exceeded: ext length ("+e+") > maxExtLength ("+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=gt(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 $t{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 Lt=new Uint8Array([145,Ie.Ping]);class Mt{constructor(e){this.name="messagepack",this.version=1,this.transferFormat=Ce.Binary,this._errorResult=1,this._voidResult=2,this._nonVoidResult=3,e=e||{},this._encoder=new vt(e.extensionCodec,e.context,e.maxDepth,e.initialBufferSize,e.sortKeys,e.forceFloat32,e.ignoreUndefined,e.forceIntegerToFloat),this._decoder=new Bt(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=Ae.instance);const r=$t.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 Ie.Invocation:return this._writeInvocation(e);case Ie.StreamInvocation:return this._writeStreamInvocation(e);case Ie.StreamItem:return this._writeStreamItem(e);case Ie.Completion:return this._writeCompletion(e);case Ie.Ping:return $t.write(Lt);case Ie.CancelInvocation:return this._writeCancelInvocation(e);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 Ie.Invocation:return this._createInvocationMessage(this._readHeaders(n),n);case Ie.StreamItem:return this._createStreamItemMessage(this._readHeaders(n),n);case Ie.Completion:return this._createCompletionMessage(this._readHeaders(n),n);case Ie.Ping:return this._createPingMessage(n);case Ie.Close:return this._createCloseMessage(n);default:return t.log(Ee.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:Ie.Close}}_createPingMessage(e){if(e.length<1)throw new Error("Invalid payload for Ping message.");return{type:Ie.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:Ie.Invocation}:{arguments:t[4],headers:e,streamIds:[],target:t[3],type:Ie.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:Ie.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:Ie.Completion}}_writeInvocation(e){let t;return t=e.streamIds?this._encoder.encode([Ie.Invocation,e.headers||{},e.invocationId||null,e.target,e.arguments,e.streamIds]):this._encoder.encode([Ie.Invocation,e.headers||{},e.invocationId||null,e.target,e.arguments]),$t.write(t.slice())}_writeStreamInvocation(e){let t;return t=e.streamIds?this._encoder.encode([Ie.StreamInvocation,e.headers||{},e.invocationId,e.target,e.arguments,e.streamIds]):this._encoder.encode([Ie.StreamInvocation,e.headers||{},e.invocationId,e.target,e.arguments]),$t.write(t.slice())}_writeStreamItem(e){const t=this._encoder.encode([Ie.StreamItem,e.headers||{},e.invocationId,e.item]);return $t.write(t.slice())}_writeCompletion(e){const t=e.error?this._errorResult:e.result?this._nonVoidResult:this._voidResult;let n;switch(t){case this._errorResult:n=this._encoder.encode([Ie.Completion,e.headers||{},e.invocationId,t,e.error]);break;case this._voidResult:n=this._encoder.encode([Ie.Completion,e.headers||{},e.invocationId,t]);break;case this._nonVoidResult:n=this._encoder.encode([Ie.Completion,e.headers||{},e.invocationId,t,e.result])}return $t.write(n.slice())}_writeCancelInvocation(e){const t=this._encoder.encode([Ie.CancelInvocation,e.headers||{},e.invocationId]);return $t.write(t.slice())}_readHeaders(e){const t=e[1];if("object"!=typeof t)throw new Error("Invalid headers.");return t}}let Ot=!1;const Ht="function"==typeof TextDecoder?new TextDecoder("utf-8"):null,Ft=Ht?Ht.decode.bind(Ht):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("")},jt=Math.pow(2,32),Wt=Math.pow(2,21)-1;function zt(e,t){return e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24}function qt(e,t){return e[t]+(e[t+1]<<8)+(e[t+2]<<16)+(e[t+3]<<24>>>0)}function Jt(e,t){const n=qt(e,t+4);if(n>Wt)throw new Error(`Cannot read uint64 with high order part ${n}, because the result would exceed Number.MAX_SAFE_INTEGER.`);return n*jt+qt(e,t)}class Kt{constructor(e){this.batchData=e;const t=new Gt(e);this.arrayRangeReader=new Qt(e),this.arrayBuilderSegmentReader=new Zt(e),this.diffReader=new Vt(e),this.editReader=new Xt(e,t),this.frameReader=new Yt(e,t)}updatedComponents(){return zt(this.batchData,this.batchData.length-20)}referenceFrames(){return zt(this.batchData,this.batchData.length-16)}disposedComponentIds(){return zt(this.batchData,this.batchData.length-12)}disposedEventHandlerIds(){return zt(this.batchData,this.batchData.length-8)}updatedComponentsEntry(e,t){const n=e+4*t;return zt(this.batchData,n)}referenceFramesEntry(e,t){return e+20*t}disposedComponentIdsEntry(e,t){const n=e+4*t;return zt(this.batchData,n)}disposedEventHandlerIdsEntry(e,t){const n=e+8*t;return Jt(this.batchData,n)}}class Vt{constructor(e){this.batchDataUint8=e}componentId(e){return zt(this.batchDataUint8,e)}edits(e){return e+4}editsEntry(e,t){return e+16*t}}class Xt{constructor(e,t){this.batchDataUint8=e,this.stringReader=t}editType(e){return zt(this.batchDataUint8,e)}siblingIndex(e){return zt(this.batchDataUint8,e+4)}newTreeIndex(e){return zt(this.batchDataUint8,e+8)}moveToSiblingIndex(e){return zt(this.batchDataUint8,e+8)}removedAttributeName(e){const t=zt(this.batchDataUint8,e+12);return this.stringReader.readString(t)}}class Yt{constructor(e,t){this.batchDataUint8=e,this.stringReader=t}frameType(e){return zt(this.batchDataUint8,e)}subtreeLength(e){return zt(this.batchDataUint8,e+4)}elementReferenceCaptureId(e){const t=zt(this.batchDataUint8,e+4);return this.stringReader.readString(t)}componentId(e){return zt(this.batchDataUint8,e+8)}elementName(e){const t=zt(this.batchDataUint8,e+8);return this.stringReader.readString(t)}textContent(e){const t=zt(this.batchDataUint8,e+4);return this.stringReader.readString(t)}markupContent(e){const t=zt(this.batchDataUint8,e+4);return this.stringReader.readString(t)}attributeName(e){const t=zt(this.batchDataUint8,e+4);return this.stringReader.readString(t)}attributeValue(e){const t=zt(this.batchDataUint8,e+8);return this.stringReader.readString(t)}attributeEventHandlerId(e){return Jt(this.batchDataUint8,e+12)}}class Gt{constructor(e){this.batchDataUint8=e,this.stringTableStartIndex=zt(e,e.length-4)}readString(e){if(-1===e)return null;{const n=zt(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(en.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(en.Debug,`Waiting for batch ${this.nextBatchId}. Batch ${e} not processed.`);try{this.nextBatchId++,this.logger.log(en.Debug,`Applying batch ${e}.`),function(e,t){const n=Q[e];if(!n)throw new Error(`There is no browser renderer with ID ${e}.`);const r=t.arrayRangeReader,o=t.updatedComponents(),i=r.values(o),s=r.count(o),a=t.referenceFrames(),c=r.values(a),l=t.diffReader;for(let e=0;e=this.minLevel){const n=`[${(new Date).toISOString()}] ${en[e]}: ${t}`;switch(e){case en.Critical:case en.Error:console.error(n);break;case en.Warning:console.warn(n);break;case en.Information:console.info(n);break;default:console.log(n)}}}}class on{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!==ke.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!==ke.Connected)return!1;const t=await e.invoke("StartCircuit",re.getBaseURI(),re.getLocationHref(),JSON.stringify(this.components.map((e=>e.toRecord()))),this.applicationState||"");return!!t&&(this.initialize(t),!0)}resolveElement(e){const t=Number.parseInt(e);if(Number.isNaN(t))throw new Error(`Invalid sequence number '${e}'.`);return function(e,t){if(!e.parentNode)throw new Error(`Comment not connected to the DOM ${e.textContent}`);const n=e.parentNode,r=k(n,!0),o=A(r);return Array.from(n.childNodes).forEach((e=>o.push(e))),e[C]=r,t&&(e[I]=t,k(t)),k(e)}(this.components[t].start,this.components[t].end)}}const sn={configureSignalR:e=>{},logLevel:en.Warning,reconnectionOptions:{maxRetries:8,retryIntervalMilliseconds:2e4,dialogId:"components-reconnect-modal"}};class an{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.modal.innerHTML='

Alternatively, reload

',this.message=this.modal.querySelector("h5"),this.button=this.modal.querySelector("button"),this.reloadParagraph=this.modal.querySelector("p"),this.loader=this.getLoader(),this.message.after(this.loader),this.button.addEventListener("click",(async()=>{this.show();try{await(null==fe?void 0:fe.reconnect)()||this.rejected()}catch(e){this.logger.log(en.Error,e),this.failed()}})),this.reloadParagraph.querySelector("a").addEventListener("click",(()=>location.reload()))}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",this.message.innerHTML="Reconnection failed. Try reloading the page if you're unable to reconnect.",this.message.querySelector("a").addEventListener("click",(()=>location.reload()))}rejected(){this.button.style.display="none",this.reloadParagraph.style.display="none",this.loader.style.display="none",this.message.innerHTML="Could not reconnect to the server. Reload the page to restore functionality.",this.message.querySelector("a").addEventListener("click",(()=>location.reload()))}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 cn{constructor(e,t,n){this.dialog=e,this.maxRetries=t,this.document=n,this.document=n;const r=this.document.getElementById(cn.MaxRetriesId);r&&(r.innerText=this.maxRetries.toString())}show(){this.removeClasses(),this.dialog.classList.add(cn.ShowClassName)}update(e){const t=this.document.getElementById(cn.CurrentAttemptId);t&&(t.innerText=e.toString())}hide(){this.removeClasses(),this.dialog.classList.add(cn.HideClassName)}failed(){this.removeClasses(),this.dialog.classList.add(cn.FailedClassName)}rejected(){this.removeClasses(),this.dialog.classList.add(cn.RejectedClassName)}removeClasses(){this.dialog.classList.remove(cn.ShowClassName,cn.HideClassName,cn.FailedClassName,cn.RejectedClassName)}}cn.ShowClassName="components-reconnect-show",cn.HideClassName="components-reconnect-hide",cn.FailedClassName="components-reconnect-failed",cn.RejectedClassName="components-reconnect-rejected",cn.MaxRetriesId="components-reconnect-max-retries",cn.CurrentAttemptId="components-reconnect-current-attempt";class ln{constructor(e,t,n){this._currentReconnectionProcess=null,this._logger=e,this._reconnectionDisplay=t,this._reconnectCallback=n||(()=>fe.reconnect())}onConnectionDown(e,t){if(!this._reconnectionDisplay){const t=document.getElementById(e.dialogId);this._reconnectionDisplay=t?new cn(t,e.maxRetries,document):new an(e.dialogId,e.maxRetries,document,this._logger)}this._currentReconnectionProcess||(this._currentReconnectionProcess=new hn(e,this._logger,this._reconnectCallback,this._reconnectionDisplay))}onConnectionUp(){this._currentReconnectionProcess&&(this._currentReconnectionProcess.dispose(),this._currentReconnectionProcess=null)}}class hn{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;thn.MaximumFirstRetryInterval?hn.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(en.Error,e)}}this.reconnectDisplay.failed()}delay(e){return new Promise((t=>setTimeout(t,e)))}}hn.MaximumFirstRetryInterval=3e3;const un=/^\s*Blazor-Component-State:(?[a-zA-Z0-9\+\/=]+)$/;function dn(e){var t;if(e.nodeType===Node.COMMENT_NODE){const n=e.textContent||"",r=un.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 gn(e,t){const n=e.currentElement;if(n&&n.nodeType===Node.COMMENT_NODE&&n.textContent){const r=fn.exec(n.textContent),o=r&&r.groups&&r.groups.descriptor;if(!o)return;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;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.");if(c){const e=mn(c,n);if(!e)throw new Error(`Could not find an end component comment for '${t}'`);return{type:r,assembly:o,typeName:i,parameterDefinitions:s&&atob(s),parameterValues:a&&atob(a),start:t,prerenderId:c,end:e}}return{type:r,assembly:o,typeName:i,parameterDefinitions:s&&atob(s),parameterValues:a&&atob(a),start:t}}}(r,n,e);case"server":return function(e,t,n){const{type:r,descriptor:o,sequence:i,prerenderId:s}=e;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)}'`);if(s){const e=mn(s,n);if(!e)throw new Error(`Could not find an end component comment for '${t}'`);return{type:r,sequence:i,descriptor:o,start:t,prerenderId:s,end:e}}return{type:r,sequence:i,descriptor:o,start:t}}}(r,n,e)}}catch(e){throw new Error(`Found malformed component comment at ${n.textContent}`)}}}function mn(e,t){for(;t.next()&&t.currentElement;){const n=t.currentElement;if(n.nodeType!==Node.COMMENT_NODE)continue;if(!n.textContent)continue;const r=fn.exec(n.textContent),o=r&&r[1];if(o)return yn(o,e),n}}function yn(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 wn{constructor(e){this.childNodes=e,this.currentIndex=-1,this.length=e.length}next(){return this.currentIndex++,this.currentIndexe.sequence-t.sequence))}(e)}(document),o=dn(document),i=new on(r,o||""),s=await Tn(t,n,i);if(!await i.startCircuit(s))return void n.log(en.Error,"Failed to start the circuit.");let a=!1;const c=()=>{if(!a){const e=new FormData,t=i.circuitId;e.append("circuitId",t),a=navigator.sendBeacon("_blazor/disconnect",e)}};fe.disconnect=c,window.addEventListener("unload",c,{capture:!1,once:!0}),fe.reconnect=async e=>{if(Cn)return!1;const r=e||await Tn(t,n,i);return await i.reconnect(r)?(t.reconnectionHandler.onConnectionUp(),!0):(n.log(en.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)},n.log(en.Information,"Blazor server-side application started.")}async function Tn(t,n,r){const i=new Mt;i.name="blazorpack";const s=(new rt).withUrl("_blazor").withHubProtocol(i);t.configureSignalR(s);const a=s.build();o=(e,t)=>{a.send("DispatchBrowserEvent",JSON.stringify(e),JSON.stringify(t))},fe._internal.navigationManager.listenForNavigationEvents(((e,t)=>a.send("OnLocationChanged",e,t))),a.on("JS.AttachComponent",((e,t)=>function(e,t,n){let r=Q[0];r||(r=Q[0]=new V(0)),r.attachRootComponentToLogicalElement(n,t)}(0,r.resolveElement(t),e))),a.on("JS.BeginInvokeJS",e.jsCallDispatcher.beginInvokeJSFromDotNet),a.on("JS.EndInvokeDotNet",e.jsCallDispatcher.endInvokeDotNetFromJS),a.on("JS.ReceiveByteArray",e.jsCallDispatcher.receiveByteArray);const c=tn.getOrCreate(n);a.on("JS.RenderBatch",((e,t)=>{n.log(en.Debug,`Received render batch with id ${e} and ${t.byteLength} bytes.`),c.processBatch(e,t,a)})),a.onclose((e=>!Cn&&t.reconnectionHandler.onConnectionDown(t.reconnectionOptions,e))),a.on("JS.Error",(e=>{Cn=!0,Dn(a,e,n),async function(){let e=document.querySelector("#blazor-error-ui");e&&(e.style.display="block"),Ot||(Ot=!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()}})))}()})),fe._internal.forceCloseConnection=()=>a.stop(),fe._internal.sendJSDataStream=async(e,t,n)=>{setTimeout((async()=>{let r=5,o=(new Date).valueOf();try{const i=n-512;if(i<=0)throw new Error("The chunk size must be greater than 0.");let s=0;for(;s1)await a.send("ReceiveJSDataChunk",t,c,null);else{if(!await a.invoke("ReceiveJSDataChunk",t,c,null))break;const e=(new Date).valueOf(),n=e-o;o=e,r=Math.max(1,Math.round(500/n))}s+=n}}catch(e){await a.send("ReceiveJSDataChunk",t,null,e.toString())}}),0)};try{await a.start()}catch(e){Dn(a,e,n)}return e.attachDispatcher({beginInvokeDotNetFromJS:(e,t,n,r,o)=>{a.send("BeginInvokeDotNetFromJS",e?e.toString():null,t,n,r||0,o)},endInvokeJSFromDotNet:(e,t,n)=>{a.send("EndInvokeJSFromDotNet",e,t,n)},sendByteArray:(e,t)=>{a.send("ReceiveByteArray",e,t)}}),a}function Dn(e,t,n){n.log(en.Error,t),e&&e.stop()}fe.start=kn,document&&document.currentScript&&"false"!==document.currentScript.getAttribute("autostart")&&kn()})(); \ No newline at end of file +(()=>{"use strict";var e,t,n;!function(e){window.DotNet=e;const t=[],n=new Map;class r{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 o="__jsObjectId",i={},s={0:new r(window)};s[0]._cachedFunctions.set("import",(e=>("string"==typeof e&&e.startsWith("./")&&(e=document.baseURI+e.substr(2)),import(e))));let a,c=1,l=1,h=null;function u(e){t.push(e)}function d(e){if(e&&"object"==typeof e){s[l]=new r(e);const t={[o]:l};return l++,t}throw new Error(`Cannot create a JSObjectReference from the value '${e}'.`)}function p(e){if(!(e.buffer instanceof ArrayBuffer))throw new Error(`Cannot create a JSDataReference from the value '${e}' as it is not a valid ArrayBuffer.`);if(void 0===e.byteLength)throw new Error(`Cannot create a JSDataReference from the value '${e}' as it doesn't have a byteLength.`);const t={__jsDataReferenceLength:e.byteLength};try{const n=d(e);t.__jsObjectId=n.__jsObjectId}catch{throw new Error(`Cannot create a JSDataReference from the value '${e}'.`)}return t}function f(e){return e?JSON.parse(e,((e,n)=>t.reduce(((t,n)=>n(e,t)),n))):null}function g(e,t,n,r){const o=y();if(o.invokeDotNetFromJS){const i=k(r),s=o.invokeDotNetFromJS(e,t,n,i);return s?f(s):null}throw new Error("The current dispatcher does not support synchronous calls from JS to .NET. Use invokeMethodAsync instead.")}function m(e,t,n,r){if(e&&n)throw new Error(`For instance method calls, assemblyName should be null. Received '${e}'.`);const o=c++,s=new Promise(((e,t)=>{i[o]={resolve:e,reject:t}}));try{const i=k(r);y().beginInvokeDotNetFromJS(o,e,t,n,i)}catch(e){w(o,!1,e)}return s}function y(){if(null!==h)return h;throw new Error("No .NET call dispatcher has been set.")}function w(e,t,n){if(!i.hasOwnProperty(e))throw new Error(`There is no pending async call with ID ${e}.`);const r=i[e];delete i[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){let n=s[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 s[e]}e.attachDispatcher=function(e){h=e},e.attachReviver=u,e.invokeMethod=function(e,t,...n){return g(e,t,null,n)},e.invokeMethodAsync=function(e,t,...n){return m(e,t,null,n)},e.createJSObjectReference=d,e.createJSDataReference=p,e.disposeJSObjectReference=function(e){const t=e&&e.__jsObjectId;"number"==typeof t&&_(t)},function(e){e[e.Default=0]="Default",e[e.JSObjectReference=1]="JSObjectReference",e[e.JSDataReference=2]="JSDataReference"}(a=e.JSCallResultType||(e.JSCallResultType={})),e.jsCallDispatcher={findJSFunction:b,disposeJSObjectReferenceById:_,invokeJSFromDotNet:(e,t,n,r)=>{const o=C(b(e,r).apply(null,f(t)),n);return null==o?null:k(o)},beginInvokeJSFromDotNet:(e,t,n,r,o)=>{const i=new Promise((e=>{e(b(t,o).apply(null,f(n)))}));e&&i.then((t=>y().endInvokeJSFromDotNet(e,!0,k([e,!0,C(t,r)]))),(t=>y().endInvokeJSFromDotNet(e,!1,JSON.stringify([e,!1,v(t)]))))},endInvokeDotNetFromJS:(e,t,n)=>{const r=t?f(n):new Error(n);w(parseInt(e),t,r)},receiveByteArray:(e,t)=>{n.set(e,t)}};class E{constructor(e){this._id=e}invokeMethod(e,...t){return g(null,e,this._id,t)}invokeMethodAsync(e,...t){return m(null,e,this._id,t)}dispose(){m(null,"__Dispose",this._id,null).catch((e=>console.error(e)))}serializeAsArg(){return{__dotNetObject:this._id}}}const S="__byte[]";function C(e,t){switch(t){case a.Default:return e;case a.JSObjectReference:return d(e);case a.JSDataReference:return p(e);default:throw new Error(`Invalid JS call result type '${t}'.`)}}u((function(e,t){if(t&&"object"==typeof t){if(t.hasOwnProperty("__dotNetObject"))return new E(t.__dotNetObject);if(t.hasOwnProperty(o)){const e=t.__jsObjectId,n=s[e];if(n)return n.getWrappedObject();throw new Error(`JS object instance with Id '${e}' does not exist. It may have been disposed.`)}if(t.hasOwnProperty(S)){const e=t["__byte[]"],r=n.get(e);if(void 0===r)throw new Error(`Byte array index '${e}' does not exist.`);return r}}return t}));let I=0;function k(e){return I=0,JSON.stringify(e,T)}function T(e,t){if(t instanceof E)return t.serializeAsArg();if(t instanceof Uint8Array){h.sendByteArray(I,t);const e={[S]:I};return I++,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"}(n||(n={}));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}}let o;function i(e,t){if(!o)throw new Error("eventDispatcher not initialized. Call 'setEventDispatcher' to configure it.");o(e,t)}const s=new Map,a=new Map,c={createEventArgs:()=>({})},l=[];function h(e){return s.get(e)}function u(e){const t=s.get(e);return(null==t?void 0:t.browserEventName)||e}function d(e,t){e.forEach((e=>s.set(e,t)))}function p(e){const t=[];for(let n=0;n{return{...f(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}}),d(["focus","blur","focusin","focusout"],c),d(["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};var t}}),d(["contextmenu","click","mouseover","mouseout","mousemove","mousedown","mouseup","dblclick"],{createEventArgs:e=>f(e)}),d(["error"],{createEventArgs:e=>{return{message:(t=e).message,filename:t.filename,lineno:t.lineno,colno:t.colno};var t}}),d(["loadstart","timeout","abort","load","loadend","progress"],{createEventArgs:e=>{return{lengthComputable:(t=e).lengthComputable,loaded:t.loaded,total:t.total};var t}}),d(["touchcancel","touchend","touchmove","touchenter","touchleave","touchstart"],{createEventArgs:e=>{return{detail:(t=e).detail,touches:p(t.touches),targetTouches:p(t.targetTouches),changedTouches:p(t.changedTouches),ctrlKey:t.ctrlKey,shiftKey:t.shiftKey,altKey:t.altKey,metaKey:t.metaKey,type:t.type};var t}}),d(["gotpointercapture","lostpointercapture","pointercancel","pointerdown","pointerenter","pointerleave","pointermove","pointerout","pointerover","pointerup"],{createEventArgs:e=>{return{...f(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}}),d(["wheel","mousewheel"],{createEventArgs:e=>{return{...f(t=e),deltaX:t.deltaX,deltaY:t.deltaY,deltaZ:t.deltaZ,deltaMode:t.deltaMode};var t}}),d(["toggle"],c);const g=["date","datetime-local","month","time","week"],m=E(["abort","blur","change","error","focus","load","loadend","loadstart","mouseenter","mouseleave","progress","reset","scroll","submit","unload","toggle","DOMNodeInsertedIntoDocument","DOMNodeRemovedFromDocument"]),y={submit:!0},w=E(["click","dblclick","mousedown","mousemove","mouseup"]);class v{constructor(e){this.browserRendererId=e,this.afterClickCallbacks=[];const t=++v.nextEventDelegatorId;this.eventsCollectionKey=`_blazorEvents_${t}`,this.eventInfoStore=new b(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,a.get(n));var n;t&&t.forEach((t=>this.dispatchGlobalEventToAllElements(t,e))),"click"===e.type&&this.afterClickCallbacks.forEach((t=>t(e)))}dispatchGlobalEventToAllElements(e,t){let n=t.target,o=null,s=!1;const a=m.hasOwnProperty(e);let c=!1;for(;n;){const d=this.getEventHandlerInfosForElement(n,!1);if(d){const a=d.getHandler(e);if(a&&(l=n,u=t.type,!((l instanceof HTMLButtonElement||l instanceof HTMLInputElement||l instanceof HTMLTextAreaElement||l instanceof HTMLSelectElement)&&w.hasOwnProperty(u)&&l.disabled))){if(!s){const n=h(e);o=(null==n?void 0:n.createEventArgs)?n.createEventArgs(t):{},s=!0}y.hasOwnProperty(t.type)&&t.preventDefault(),i({browserRendererId:this.browserRendererId,eventHandlerId:a.eventHandlerId,eventName:e,eventFieldInfo:r.fromEvent(a.renderingComponentId,t)},o)}d.stopPropagation(e)&&(c=!0),d.preventDefault(e)&&t.preventDefault()}n=a||c?null:n.parentElement}var l,u}getEventHandlerInfosForElement(e,t){return e.hasOwnProperty(this.eventsCollectionKey)?e[this.eventsCollectionKey]:t?e[this.eventsCollectionKey]=new _:null}}v.nextEventDelegatorId=0;class b{constructor(e){this.globalListener=e,this.infosByEventHandlerId={},this.countByEventName={},l.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=u(e),this.countByEventName.hasOwnProperty(e))this.countByEventName[e]++;else{this.countByEventName[e]=1;const t=m.hasOwnProperty(e);document.addEventListener(e,this.globalListener,t)}}update(e,t){if(this.infosByEventHandlerId.hasOwnProperty(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=u(t.eventName);0==--this.countByEventName[n]&&(delete this.countByEventName[n],document.removeEventListener(n,this.globalListener))}return t}handleEventNameAliasAdded(e,t){if(this.countByEventName.hasOwnProperty(e)){const n=this.countByEventName[e];delete this.countByEventName[e],document.removeEventListener(e,this.globalListener),this.addGlobalListener(t),this.countByEventName[t]+=n-1}}}class _{constructor(){this.handlers={},this.preventDefaultFlags=null,this.stopPropagationFlags=null}getHandler(e){return this.handlers.hasOwnProperty(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 E(e){const t={};return e.forEach((e=>{t[e]=!0})),t}const S=O("_blazorLogicalChildren"),C=O("_blazorLogicalParent"),I=O("_blazorLogicalEnd");function k(e,t){if(e.childNodes.length>0&&!t)throw new Error("New logical elements must start empty, or allowExistingContents must be true");return S in e||(e[S]=[]),e}function T(e,t){const n=document.createComment("!");return D(n,e,t),n}function D(e,t,n){const r=e;if(e instanceof Comment&&A(r)&&A(r).length>0)throw new Error("Not implemented: inserting non-empty logical container");if(R(r))throw new Error("Not implemented: moving existing logical children");const o=A(t);if(n0;)x(n,0)}const r=n;r.parentNode.removeChild(r)}function R(e){return e[C]||null}function P(e,t){return A(e)[t]}function U(e){var t=B(e);return"http://www.w3.org/2000/svg"===t.namespaceURI&&"foreignObject"!==t.tagName}function A(e){return e[S]}function N(e,t){const n=A(e);t.forEach((e=>{e.moveRangeStart=n[e.fromSiblingIndex],e.moveRangeEnd=M(e.moveRangeStart)})),t.forEach((t=>{const r=t.moveToBeforeMarker=document.createComment("marker"),o=n[t.toSiblingIndex+1];o?o.parentNode.insertBefore(r,o):L(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 B(e){if(e instanceof Element)return e;if(e instanceof Comment)return e.parentNode;throw new Error("Not a valid logical element")}function $(e){const t=A(R(e));return t[Array.prototype.indexOf.call(t,e)+1]||null}function L(e,t){if(t instanceof Element)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=$(t);n?n.parentNode.insertBefore(e,n):L(e,R(t))}}}function M(e){if(e instanceof Element)return e;const t=$(e);if(t)return t.previousSibling;{const t=R(e);return t instanceof Element?t.lastChild:M(t)}}function O(e){return"function"==typeof Symbol?Symbol():e}function H(e){return`_bl_${e}`}e.attachReviver(((e,t)=>t&&"object"==typeof t&&t.hasOwnProperty("__internalId")&&"string"==typeof t.__internalId?function(e){const t=`[${H(e)}]`;return document.querySelector(t)}(t.__internalId):t));const F="_blazorSelectValue",j=document.createElement("template"),W=document.createElementNS("http://www.w3.org/2000/svg","g"),z={},q="__internal_",J="preventDefault_",K="stopPropagation_";class V{constructor(e){this.childComponentLocations={},this.eventDelegator=new v(e),this.eventDelegator.notifyAfterClick((e=>{if(!ee)return;if(0!==e.button||function(e){return e.ctrlKey||e.shiftKey||e.altKey||e.metaKey}(e))return;if(e.defaultPrevented)return;const t=function(e){const t=!window._blazorDisableComposedPath&&e.composedPath&&e.composedPath();if(t){for(let e=0;ese(!1))))},enableNavigationInterception:function(){ee=!0},navigateTo:oe,getBaseURI:()=>document.baseURI,getLocationHref:()=>location.href};function oe(e,t,n=!1){const r=ce(e);if(!t&&he(r))ie(r,!1,n);else if(t&&location.href===e){const t=e+"?";history.replaceState(null,"",t),location.replace(e)}else n?history.replaceState(null,"",r):location.href=e}function ie(e,t,n=!1){Z=!0,n?history.replaceState(null,"",e):history.pushState(null,"",e),se(t)}async function se(e){ne&&await ne(location.href,e)}let ae;function ce(e){return ae=ae||document.createElement("a"),ae.href=e,ae.href}function le(e,t){return e?e.tagName===t?e:le(e.parentElement,t):null}function he(e){const t=(n=document.baseURI).substr(0,n.lastIndexOf("/")+1);var n;return e.startsWith(t)}const ue={init:function(e,t,n,r=50){const o=pe(t);(o||document.documentElement).style.overflowAnchor="none";const i=new IntersectionObserver((function(r){r.forEach((r=>{var o;if(!r.isIntersecting)return;const i=t.getBoundingClientRect(),s=n.getBoundingClientRect().top-i.bottom,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`});i.observe(t),i.observe(n);const s=c(t),a=c(n);function c(e){const t=new MutationObserver((()=>{i.unobserve(e),i.observe(e)}));return t.observe(e,{attributes:!0}),t}de[e._id]={intersectionObserver:i,mutationObserverBefore:s,mutationObserverAfter:a}},dispose:function(e){const t=de[e._id];t&&(t.intersectionObserver.disconnect(),t.mutationObserverBefore.disconnect(),t.mutationObserverAfter.disconnect(),e.dispose(),delete de[e._id])}},de={};function pe(e){return e?"visible"!==getComputedStyle(e).overflowY?e:pe(e.parentElement):null}const fe={navigateTo:oe,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=a.get(t.browserEventName);n?n.push(e):a.set(t.browserEventName,[e]),l.forEach((n=>n(e,t.browserEventName)))}s.set(e,t)},_internal:{navigationManager:re,domWrapper:{focus:function(e,t){if(!(e instanceof HTMLElement))throw new Error("Unable to focus an invalid element.");e.focus({preventScroll:t})},focusBySelector:function(e){const t=document.querySelector(e);t&&(t.hasAttribute("tabindex")||(t.tabIndex=-1),t.focus())}},Virtualize:ue}};window.Blazor=fe;const ge=[0,2e3,1e4,3e4,null];class me{constructor(e){this._retryDelays=void 0!==e?[...e,null]:ge}nextRetryDelayInMilliseconds(e){return this._retryDelays[e.previousRetryCount]}}class ye extends Error{constructor(e,t){const n=new.target.prototype;super(`${e}: Status code '${t}'`),this.statusCode=t,this.__proto__=n}}class we extends Error{constructor(e="A timeout occurred."){const t=new.target.prototype;super(e),this.__proto__=t}}class ve extends Error{constructor(e="An abort occurred."){const t=new.target.prototype;super(e),this.__proto__=t}}class be{constructor(e,t,n){this.statusCode=e,this.statusText=t,this.content=n}}class _e{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""}}var Ee,Se,Ce,Ie,ke;!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"}(Ee||(Ee={}));class Te extends _e{constructor(e){if(super(),this._logger=e,"undefined"==typeof fetch){const e=require;this._jar=new(e("tough-cookie").CookieJar),this._fetchType=e("node-fetch"),this._fetchType=e("fetch-cookie")(this._fetchType,this._jar),this._abortControllerType=e("abort-controller")}else this._fetchType=fetch.bind(self),this._abortControllerType=AbortController}async send(e){if(e.abortSignal&&e.abortSignal.aborted)throw new ve;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 ve});let r,o=null;if(e.timeout){const r=e.timeout;o=setTimeout((()=>{t.abort(),this._logger.log(Ee.Warning,"Timeout from HTTP request."),n=new we}),r)}try{r=await this._fetchType(e.url,{body:e.content,cache:"no-cache",credentials:!0===e.withCredentials?"include":"same-origin",headers:{"Content-Type":"text/plain;charset=UTF-8","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(Ee.Warning,`Error from HTTP request. ${e}.`),e}finally{o&&clearTimeout(o),e.abortSignal&&(e.abortSignal.onabort=null)}if(!r.ok){const e=await De(r,"text");throw new ye(e||r.statusText,r.status)}const i=De(r,e.responseType),s=await i;return new be(r.status,r.statusText,s)}getCookieString(e){return""}}function De(e,t){let n;switch(t){case"arraybuffer":n=e.arrayBuffer();break;case"text":n=e.text();break;case"blob":case"document":case"json":throw new Error(`${t} is not supported.`);default:n=e.text()}return n}class xe extends _e{constructor(e){super(),this._logger=e}send(e){return e.abortSignal&&e.abortSignal.aborted?Promise.reject(new ve):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"),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 ve)}),e.timeout&&(r.timeout=e.timeout),r.onload=()=>{e.abortSignal&&(e.abortSignal.onabort=null),r.status>=200&&r.status<300?t(new be(r.status,r.statusText,r.response||r.responseText)):n(new ye(r.response||r.responseText||r.statusText,r.status))},r.onerror=()=>{this._logger.log(Ee.Warning,`Error from HTTP request. ${r.status}: ${r.statusText}.`),n(new ye(r.statusText,r.status))},r.ontimeout=()=>{this._logger.log(Ee.Warning,"Timeout from HTTP request."),n(new we)},r.send(e.content||"")})):Promise.reject(new Error("No url defined.")):Promise.reject(new Error("No method defined."))}}class Re extends _e{constructor(e){if(super(),"undefined"!=typeof fetch)this._httpClient=new Te(e);else{if("undefined"==typeof XMLHttpRequest)throw new Error("No usable HttpClient found.");this._httpClient=new xe(e)}}send(e){return e.abortSignal&&e.abortSignal.aborted?Promise.reject(new ve):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)}}class Pe{}Pe.Authorization="Authorization",Pe.Cookie="Cookie",function(e){e[e.None=0]="None",e[e.WebSockets=1]="WebSockets",e[e.ServerSentEvents=2]="ServerSentEvents",e[e.LongPolling=4]="LongPolling"}(Se||(Se={})),function(e){e[e.Text=1]="Text",e[e.Binary=2]="Binary"}(Ce||(Ce={}));class Ue{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 Ae{constructor(){}log(e,t){}}Ae.instance=new Ae;class Ne{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 Be{static get isBrowser(){return"object"==typeof window}static get isWebWorker(){return"object"==typeof self&&"importScripts"in self}static get isNode(){return!this.isBrowser&&!this.isWebWorker}}function $e(e,t){let n="";return Le(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 Le(e){return e&&"undefined"!=typeof ArrayBuffer&&(e instanceof ArrayBuffer||e.constructor&&"ArrayBuffer"===e.constructor.name)}async function Me(e,t,n,r,o,i,s,a,c){let l={};if(o){const e=await o();e&&(l={Authorization:`Bearer ${e}`})}const[h,u]=Fe();l[h]=u,e.log(Ee.Trace,`(${t} transport) sending data. ${$e(i,s)}.`);const d=Le(i)?"arraybuffer":"text",p=await n.post(r,{content:i,headers:{...l,...c},responseType:d,withCredentials:a});e.log(Ee.Trace,`(${t} transport) request complete. Response status: ${p.statusCode}.`)}class Oe{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 He{constructor(e){this._minLevel=e,this.out=console}log(e,t){if(e>=this._minLevel){const n=`[${(new Date).toISOString()}] ${Ee[e]}: ${t}`;switch(e){case Ee.Critical:case Ee.Error:this.out.error(n);break;case Ee.Warning:this.out.warn(n);break;case Ee.Information:this.out.info(n);break;default:this.out.log(n)}}}}function Fe(){let e="X-SignalR-User-Agent";return Be.isNode&&(e="User-Agent"),[e,je("0.0.0-DEV_BUILD",We(),Be.isNode?"NodeJS":"Browser",ze())]}function je(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 We(){if(!Be.isNode)return"";switch(process.platform){case"win32":return"Windows NT";case"darwin":return"macOS";case"linux":return"Linux";default:return process.platform}}function ze(){if(Be.isNode)return process.versions.node}class qe{constructor(e,t,n,r,o,i){this._httpClient=e,this._accessTokenFactory=t,this._logger=n,this._pollAbort=new Ue,this._logMessageContent=r,this._withCredentials=o,this._headers=i,this._running=!1,this.onreceive=null,this.onclose=null}get pollAborted(){return this._pollAbort.aborted}async connect(e,t){if(Ne.isRequired(e,"url"),Ne.isRequired(t,"transferFormat"),Ne.isIn(t,Ce,"transferFormat"),this._url=e,this._logger.log(Ee.Trace,"(LongPolling transport) Connecting."),t===Ce.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]=Fe(),o={[n]:r,...this._headers},i={abortSignal:this._pollAbort.signal,headers:o,timeout:1e5,withCredentials:this._withCredentials};t===Ce.Binary&&(i.responseType="arraybuffer");const s=await this._getAccessToken();this._updateHeaderToken(i,s);const a=`${e}&_=${Date.now()}`;this._logger.log(Ee.Trace,`(LongPolling transport) polling: ${a}.`);const c=await this._httpClient.get(a,i);200!==c.statusCode?(this._logger.log(Ee.Error,`(LongPolling transport) Unexpected response code: ${c.statusCode}.`),this._closeError=new ye(c.statusText||"",c.statusCode),this._running=!1):this._running=!0,this._receiving=this._poll(this._url,i)}async _getAccessToken(){return this._accessTokenFactory?await this._accessTokenFactory():null}_updateHeaderToken(e,t){e.headers||(e.headers={}),t?e.headers[Pe.Authorization]=`Bearer ${t}`:e.headers[Pe.Authorization]&&delete e.headers[Pe.Authorization]}async _poll(e,t){try{for(;this._running;){const n=await this._getAccessToken();this._updateHeaderToken(t,n);try{const n=`${e}&_=${Date.now()}`;this._logger.log(Ee.Trace,`(LongPolling transport) polling: ${n}.`);const r=await this._httpClient.get(n,t);204===r.statusCode?(this._logger.log(Ee.Information,"(LongPolling transport) Poll terminated by server."),this._running=!1):200!==r.statusCode?(this._logger.log(Ee.Error,`(LongPolling transport) Unexpected response code: ${r.statusCode}.`),this._closeError=new ye(r.statusText||"",r.statusCode),this._running=!1):r.content?(this._logger.log(Ee.Trace,`(LongPolling transport) data received. ${$e(r.content,this._logMessageContent)}.`),this.onreceive&&this.onreceive(r.content)):this._logger.log(Ee.Trace,"(LongPolling transport) Poll timed out, reissuing.")}catch(e){this._running?e instanceof we?this._logger.log(Ee.Trace,"(LongPolling transport) Poll timed out, reissuing."):(this._closeError=e,this._running=!1):this._logger.log(Ee.Trace,`(LongPolling transport) Poll errored after shutdown: ${e.message}`)}}}finally{this._logger.log(Ee.Trace,"(LongPolling transport) Polling complete."),this.pollAborted||this._raiseOnClose()}}async send(e){return this._running?Me(this._logger,"LongPolling",this._httpClient,this._url,this._accessTokenFactory,e,this._logMessageContent,this._withCredentials,this._headers):Promise.reject(new Error("Cannot send until the transport is connected"))}async stop(){this._logger.log(Ee.Trace,"(LongPolling transport) Stopping polling."),this._running=!1,this._pollAbort.abort();try{await this._receiving,this._logger.log(Ee.Trace,`(LongPolling transport) sending DELETE request to ${this._url}.`);const e={},[t,n]=Fe();e[t]=n;const r={headers:{...e,...this._headers},withCredentials:this._withCredentials},o=await this._getAccessToken();this._updateHeaderToken(r,o),await this._httpClient.delete(this._url,r),this._logger.log(Ee.Trace,"(LongPolling transport) DELETE request sent.")}finally{this._logger.log(Ee.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(Ee.Trace,e),this.onclose(this._closeError)}}}class Je{constructor(e,t,n,r,o,i,s){this._httpClient=e,this._accessTokenFactory=t,this._logger=n,this._logMessageContent=r,this._withCredentials=i,this._eventSourceConstructor=o,this._headers=s,this.onreceive=null,this.onclose=null}async connect(e,t){if(Ne.isRequired(e,"url"),Ne.isRequired(t,"transferFormat"),Ne.isIn(t,Ce,"transferFormat"),this._logger.log(Ee.Trace,"(SSE transport) Connecting."),this._url=e,this._accessTokenFactory){const t=await this._accessTokenFactory();t&&(e+=(e.indexOf("?")<0?"?":"&")+`access_token=${encodeURIComponent(t)}`)}return new Promise(((n,r)=>{let o,i=!1;if(t===Ce.Text){if(Be.isBrowser||Be.isWebWorker)o=new this._eventSourceConstructor(e,{withCredentials:this._withCredentials});else{const t=this._httpClient.getCookieString(e),n={};n.Cookie=t;const[r,i]=Fe();n[r]=i,o=new this._eventSourceConstructor(e,{withCredentials:this._withCredentials,headers:{...n,...this._headers}})}try{o.onmessage=e=>{if(this.onreceive)try{this._logger.log(Ee.Trace,`(SSE transport) data received. ${$e(e.data,this._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(Ee.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?Me(this._logger,"SSE",this._httpClient,this._url,this._accessTokenFactory,e,this._logMessageContent,this._withCredentials,this._headers):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 Ke{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){if(Ne.isRequired(e,"url"),Ne.isRequired(t,"transferFormat"),Ne.isIn(t,Ce,"transferFormat"),this._logger.log(Ee.Trace,"(WebSockets transport) Connecting."),this._accessTokenFactory){const t=await this._accessTokenFactory();t&&(e+=(e.indexOf("?")<0?"?":"&")+`access_token=${encodeURIComponent(t)}`)}return new Promise(((n,r)=>{let o;e=e.replace(/^http/,"ws"),this._httpClient.getCookieString(e);let i=!1;o||(o=new this._webSocketConstructor(e)),t===Ce.Binary&&(o.binaryType="arraybuffer"),o.onopen=t=>{this._logger.log(Ee.Information,`WebSocket connected to ${e}.`),this._webSocket=o,i=!0,n()},o.onerror=e=>{let t=null;t="undefined"!=typeof ErrorEvent&&e instanceof ErrorEvent?e.error:"There was an error with the transport",this._logger.log(Ee.Information,`(WebSockets transport) ${t}.`)},o.onmessage=e=>{if(this._logger.log(Ee.Trace,`(WebSockets transport) data received. ${$e(e.data,this._logMessageContent)}.`),this.onreceive)try{this.onreceive(e.data)}catch(e){return void this._close(e)}},o.onclose=e=>{if(i)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(Ee.Trace,`(WebSockets transport) sending data. ${$e(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(Ee.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 Ve{constructor(e,t={}){var n;if(this._stopPromiseResolver=()=>{},this.features={},this._negotiateVersion=1,Ne.isRequired(e,"url"),this._logger=void 0===(n=t.logger)?new He(Ee.Information):null===n?Ae.instance:void 0!==n.log?n:new He(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,"undefined"==typeof WebSocket||t.WebSocket||(t.WebSocket=WebSocket),"undefined"==typeof EventSource||t.EventSource||(t.EventSource=EventSource),this._httpClient=t.httpClient||new Re(this._logger),this._connectionState="Disconnected",this._connectionStarted=!1,this._options=t,this.onreceive=null,this.onclose=null}async start(e){if(e=e||Ce.Binary,Ne.isIn(e,Ce,"transferFormat"),this._logger.log(Ee.Debug,`Starting connection with transfer format '${Ce[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(Ee.Error,e),await this._stopPromise,Promise.reject(new Error(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(Ee.Error,e),Promise.reject(new Error(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 Xe(this.transport)),this._sendQueue.send(e))}async stop(e){return"Disconnected"===this._connectionState?(this._logger.log(Ee.Debug,`Call to HttpConnection.stop(${e}) ignored because the connection is already in the disconnected state.`),Promise.resolve()):"Disconnecting"===this._connectionState?(this._logger.log(Ee.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(Ee.Error,`HttpConnection.transport.stop() threw error '${e}'.`),this._stopConnection()}this.transport=void 0}else this._logger.log(Ee.Debug,"HttpConnection.transport is undefined in HttpConnection.stop() because start() failed.")}async _startInternal(e){let t=this.baseUrl;this._accessTokenFactory=this._options.accessTokenFactory;try{if(this._options.skipNegotiation){if(this._options.transport!==Se.WebSockets)throw new Error("Negotiation can only be skipped when using the WebSocket transport directly.");this.transport=this._constructTransport(Se.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 Error("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}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 qe&&(this.features.inherentKeepAlive=!0),"Connecting"===this._connectionState&&(this._logger.log(Ee.Debug,"The HttpConnection connected successfully."),this._connectionState="Connected")}catch(e){return this._logger.log(Ee.Error,"Failed to start the connection: "+e),this._connectionState="Disconnected",this.transport=void 0,this._stopPromiseResolver(),Promise.reject(e)}}async _getNegotiationResponse(e){const t={};if(this._accessTokenFactory){const e=await this._accessTokenFactory();e&&(t[Pe.Authorization]=`Bearer ${e}`)}const[n,r]=Fe();t[n]=r;const o=this._resolveNegotiateUrl(e);this._logger.log(Ee.Debug,`Sending negotiation request: ${o}.`);try{const e=await this._httpClient.post(o,{content:"",headers:{...t,...this._options.headers},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 ye&&404===e.statusCode&&(t+=" Either this is not a SignalR endpoint or there is a proxy blocking the connection."),this._logger.log(Ee.Error,t),Promise.reject(new Error(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(Ee.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: ${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(Ee.Error,`Failed to start the transport '${n.transport}': ${e}`),a=void 0,i.push(`${n.transport} failed: ${e}`),"Connecting"!==this._connectionState){const e="Failed to select transport before stop() was called.";return this._logger.log(Ee.Debug,e),Promise.reject(new Error(e))}}}}return i.length>0?Promise.reject(new Error(`Unable to connect to the server with any of the available transports. ${i.join(" ")}`)):Promise.reject(new Error("None of the transports supported by the client are supported by the server."))}_constructTransport(e){switch(e){case Se.WebSockets:if(!this._options.WebSocket)throw new Error("'WebSocket' is not supported in your environment.");return new Ke(this._httpClient,this._accessTokenFactory,this._logger,this._options.logMessageContent||!1,this._options.WebSocket,this._options.headers||{});case Se.ServerSentEvents:if(!this._options.EventSource)throw new Error("'EventSource' is not supported in your environment.");return new Je(this._httpClient,this._accessTokenFactory,this._logger,this._options.logMessageContent||!1,this._options.EventSource,this._options.withCredentials,this._options.headers||{});case Se.LongPolling:return new qe(this._httpClient,this._accessTokenFactory,this._logger,this._options.logMessageContent||!1,this._options.withCredentials,this._options.headers||{});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=Se[e.transport];if(null==r)return this._logger.log(Ee.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(Ee.Debug,`Skipping transport '${Se[r]}' because it was disabled by the client.`),new Error(`'${Se[r]}' is disabled by the client.`);if(!(e.transferFormats.map((e=>Ce[e])).indexOf(n)>=0))return this._logger.log(Ee.Debug,`Skipping transport '${Se[r]}' because it does not support the requested transfer format '${Ce[n]}'.`),new Error(`'${Se[r]}' does not support ${Ce[n]}.`);if(r===Se.WebSockets&&!this._options.WebSocket||r===Se.ServerSentEvents&&!this._options.EventSource)return this._logger.log(Ee.Debug,`Skipping transport '${Se[r]}' because it is not supported in your environment.'`),new Error(`'${Se[r]}' is not supported in your environment.`);this._logger.log(Ee.Debug,`Selecting transport '${Se[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(Ee.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(Ee.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(Ee.Error,`Connection disconnected with error '${e}'.`):this._logger.log(Ee.Information,"Connection disconnected."),this._sendQueue&&(this._sendQueue.stop().catch((e=>{this._logger.log(Ee.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(Ee.Error,`HttpConnection.onclose(${e}) threw error '${t}'.`)}}}else this._logger.log(Ee.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(!Be.isBrowser||!window.document)throw new Error(`Cannot resolve '${e}'.`);const t=window.document.createElement("a");return t.href=e,this._logger.log(Ee.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 Xe{constructor(e){this._transport=e,this._buffer=[],this._executing=!0,this._sendBufferedData=new Ye,this._transportResult=new Ye,this._sendLoopPromise=this._sendLoop()}send(e){return this._bufferData(e),this._transportResult||(this._transportResult=new Ye),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 Ye;const e=this._transportResult;this._transportResult=void 0;const t="string"==typeof this._buffer[0]?this._buffer.join(""):Xe._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 Ye{constructor(){this.promise=new Promise(((e,t)=>[this._resolver,this._rejecter]=[e,t]))}resolve(){this._resolver()}reject(e){this._rejecter(e)}}class Ge{static write(e){return`${e}${Ge.RecordSeparator}`}static parse(e){if(e[e.length-1]!==Ge.RecordSeparator)throw new Error("Message is incomplete.");const t=e.split(Ge.RecordSeparator);return t.pop(),t}}Ge.RecordSeparatorCode=30,Ge.RecordSeparator=String.fromCharCode(Ge.RecordSeparatorCode);class Qe{writeHandshakeRequest(e){return Ge.write(JSON.stringify(e))}parseHandshakeResponse(e){let t,n;if(Le(e)){const r=new Uint8Array(e),o=r.indexOf(Ge.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(Ge.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=Ge.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"}(Ie||(Ie={}));class Ze{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 Oe(this,e)}}!function(e){e.Disconnected="Disconnected",e.Connecting="Connecting",e.Connected="Connected",e.Disconnecting="Disconnecting",e.Reconnecting="Reconnecting"}(ke||(ke={}));class et{constructor(e,t,n,r){this._nextKeepAlive=0,Ne.isRequired(e,"connection"),Ne.isRequired(t,"logger"),Ne.isRequired(n,"protocol"),this.serverTimeoutInMilliseconds=3e4,this.keepAliveIntervalInMilliseconds=15e3,this._logger=t,this._protocol=n,this.connection=e,this._reconnectPolicy=r,this._handshakeProtocol=new Qe,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=ke.Disconnected,this._connectionStarted=!1,this._cachedPingMessage=this._protocol.writeMessage({type:Ie.Ping})}static create(e,t,n,r){return new et(e,t,n,r)}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!==ke.Disconnected&&this._connectionState!==ke.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!==ke.Disconnected)return Promise.reject(new Error("Cannot start a HubConnection that is not in the 'Disconnected' state."));this._connectionState=ke.Connecting,this._logger.log(Ee.Debug,"Starting HubConnection.");try{await this._startInternal(),this._connectionState=ke.Connected,this._connectionStarted=!0,this._logger.log(Ee.Debug,"HubConnection connected successfully.")}catch(e){return this._connectionState=ke.Disconnected,this._logger.log(Ee.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(Ee.Debug,"Sending handshake request."),await this._sendMessage(this._handshakeProtocol.writeHandshakeRequest(t)),this._logger.log(Ee.Information,`Using HubProtocol '${this._protocol.name}'.`),this._cleanupTimeout(),this._resetTimeoutPeriod(),this._resetKeepAliveInterval(),await e,this._stopDuringStartError)throw this._stopDuringStartError}catch(e){throw this._logger.log(Ee.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){return this._connectionState===ke.Disconnected?(this._logger.log(Ee.Debug,`Call to HubConnection.stop(${e}) ignored because it is already in the disconnected state.`),Promise.resolve()):this._connectionState===ke.Disconnecting?(this._logger.log(Ee.Debug,`Call to HttpConnection.stop(${e}) ignored because the connection is already in the disconnecting state.`),this._stopPromise):(this._connectionState=ke.Disconnecting,this._logger.log(Ee.Debug,"Stopping HubConnection."),this._reconnectDelayHandle?(this._logger.log(Ee.Debug,"Connection stopped during reconnect delay. Done reconnecting."),clearTimeout(this._reconnectDelayHandle),this._reconnectDelayHandle=void 0,this._completeClose(),Promise.resolve()):(this._cleanupTimeout(),this._cleanupPingTimer(),this._stopDuringStartError=e||new Error("The connection was stopped before the hub handshake could complete."),this.connection.stop(e)))}stream(e,...t){const[n,r]=this._replaceStreamingParams(t),o=this._createStreamInvocation(e,t,r);let i;const s=new Ze;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===Ie.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===Ie.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 Ie.Invocation:this._invokeClientMethod(e);break;case Ie.StreamItem:case Ie.Completion:{const t=this._callbacks[e.invocationId];t&&(e.type===Ie.Completion&&delete this._callbacks[e.invocationId],t(e));break}case Ie.Ping:break;case Ie.Close:{this._logger.log(Ee.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(Ee.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(Ee.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(Ee.Error,e);const n=new Error(e);throw this._handshakeRejecter(n),n}return this._logger.log(Ee.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===ke.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."))}_invokeClientMethod(e){const t=this._methods[e.target.toLowerCase()];if(t){try{t.forEach((t=>t.apply(this,e.arguments)))}catch(t){this._logger.log(Ee.Error,`A callback for the method ${e.target.toLowerCase()} threw error '${t}'.`)}if(e.invocationId){const e="Server requested a response, which is not supported in this version of the client.";this._logger.log(Ee.Error,e),this._stopPromise=this._stopInternal(new Error(e))}}else this._logger.log(Ee.Warning,`No client method with the name '${e.target}' found.`)}_connectionClosed(e){this._logger.log(Ee.Debug,`HubConnection.connectionClosed(${e}) called while in state ${this._connectionState}.`),this._stopDuringStartError=this._stopDuringStartError||e||new Error("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===ke.Disconnecting?this._completeClose(e):this._connectionState===ke.Connected&&this._reconnectPolicy?this._reconnect(e):this._connectionState===ke.Connected&&this._completeClose(e)}_completeClose(e){if(this._connectionStarted){this._connectionState=ke.Disconnected,this._connectionStarted=!1;try{this._closedCallbacks.forEach((t=>t.apply(this,[e])))}catch(t){this._logger.log(Ee.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(Ee.Debug,"Connection not reconnecting because the IRetryPolicy returned null on the first reconnect attempt."),void this._completeClose(e);if(this._connectionState=ke.Reconnecting,e?this._logger.log(Ee.Information,`Connection reconnecting because of error '${e}'.`):this._logger.log(Ee.Information,"Connection reconnecting."),0!==this._reconnectingCallbacks.length){try{this._reconnectingCallbacks.forEach((t=>t.apply(this,[e])))}catch(t){this._logger.log(Ee.Error,`An onreconnecting callback called with error '${e}' threw error '${t}'.`)}if(this._connectionState!==ke.Reconnecting)return void this._logger.log(Ee.Debug,"Connection left the reconnecting state in onreconnecting callback. Done reconnecting.")}for(;null!==o;){if(this._logger.log(Ee.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!==ke.Reconnecting)return void this._logger.log(Ee.Debug,"Connection left the reconnecting state during reconnect delay. Done reconnecting.");try{if(await this._startInternal(),this._connectionState=ke.Connected,this._logger.log(Ee.Information,"HubConnection reconnected successfully."),0!==this._reconnectedCallbacks.length)try{this._reconnectedCallbacks.forEach((e=>e.apply(this,[this.connection.connectionId])))}catch(e){this._logger.log(Ee.Error,`An onreconnected callback called with connectionId '${this.connection.connectionId}; threw error '${e}'.`)}return}catch(e){if(this._logger.log(Ee.Information,`Reconnect attempt failed because of error '${e}'.`),this._connectionState!==ke.Reconnecting)return this._logger.log(Ee.Debug,`Connection moved to the '${this._connectionState}' from the reconnecting state during reconnect attempt. Done reconnecting.`),void(this._connectionState===ke.Disconnecting&&this._completeClose());r=e instanceof Error?e:new Error(e.toString()),o=this._getNextRetryDelay(n++,Date.now()-t,r)}}this._logger.log(Ee.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(Ee.Error,`IRetryPolicy.nextRetryDelayInMilliseconds(${e}, ${t}) threw error '${n}'.`),null}}_cancelCallbacksWithError(e){const t=this._callbacks;this._callbacks={},Object.keys(t).forEach((n=>{(0,t[n])(null,e)}))}_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:Ie.Invocation}:{arguments:t,target:e,type:Ie.Invocation};{const n=this._invocationId;return this._invocationId++,0!==r.length?{arguments:t,invocationId:n.toString(),streamIds:r,target:e,type:Ie.Invocation}:{arguments:t,invocationId:n.toString(),target:e,type:Ie.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 ut=ot?new TextDecoder:null,dt=ot?"undefined"!=typeof process&&"force"!==process.env.TEXT_DECODER?200:0:it,pt=function(e,t){this.type=e,this.data=t};function ft(e,t,n){var r=Math.floor(n/4294967296),o=n;e.setUint32(t,r),e.setUint32(t+4,o)}function gt(e,t){return 4294967296*e.getInt32(t)+e.getUint32(t+4)}var mt={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),ft(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:gt(t,4),nsec:t.getUint32(0)};default:throw new Error("Unrecognized data size for timestamp: "+e.length)}}(e);return new Date(1e3*t.sec+t.nsec/1e6)}},yt=function(){function e(){this.builtInEncoders=[],this.builtInDecoders=[],this.encoders=[],this.decoders=[],this.register(mt)}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 "+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: "+e+" bytes in UTF-8");this.writeU8(219),this.writeU32(e)}},e.prototype.encodeString=function(e){if(e.length>ct){var t=st(e);this.ensureBufferSizeToWrite(5+t),this.writeStringHeader(t),lt(e,this.bytes,this.pos),this.pos+=t}else t=st(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: "+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: "+t);this.writeU8(198),this.writeU32(t)}var n=wt(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: "+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=ht(e,t,n),i=Uint8Array.prototype.slice.call(e,t,t+n);return this.store(i,o),o},e}(),St=(_t=function(e,t){return(_t=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])})(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}_t(e,t),e.prototype=null===t?Object.create(t):(n.prototype=t.prototype,new n)}),Ct=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]1||a(e,t)}))})}function a(e,t){try{(n=o[e](t)).value instanceof kt?Promise.resolve(n.value.v).then(c,l):h(i[0][2],n)}catch(e){h(i[0][3],e)}var n}function c(e){a("next",e)}function l(e){a("throw",e)}function h(e,t){e(t),i.shift(),i.length&&a(i[0][0],i[0][1])}},Dt=new DataView(new ArrayBuffer(0)),xt=new Uint8Array(Dt.buffer),Rt=function(){try{Dt.getInt8(0)}catch(e){return e.constructor}throw new Error("never reached")}(),Pt=new Rt("Insufficient data"),Ut=4294967295,At=new Et,Nt=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 St(t,e),t}(Error),Bt=function(){function e(e,t,n,r,o,i,s,a){void 0===e&&(e=yt.defaultCodec),void 0===t&&(t=void 0),void 0===n&&(n=Ut),void 0===r&&(r=Ut),void 0===o&&(o=Ut),void 0===i&&(i=Ut),void 0===s&&(s=Ut),void 0===a&&(a=At),this.extensionCodec=e,this.context=t,this.maxStrLength=n,this.maxBinLength=r,this.maxArrayLength=o,this.maxMapLength=i,this.maxExtLength=s,this.keyDecoder=a,this.totalPos=0,this.pos=0,this.view=Dt,this.bytes=xt,this.headByte=-1,this.stack=[]}return e.prototype.reinitializeState=function(){this.totalPos=0,this.headByte=-1,this.stack.length=0},e.prototype.setBuffer=function(e){this.bytes=wt(e),this.view=function(e){if(e instanceof ArrayBuffer)return new DataView(e);var t=wt(e);return new DataView(t.buffer,t.byteOffset,t.byteLength)}(this.bytes),this.pos=0},e.prototype.appendBuffer=function(e){if(-1!==this.headByte||this.hasRemaining()){var t=this.bytes.subarray(this.pos),n=wt(e),r=new Uint8Array(t.length+n.length);r.set(t),r.set(n,t.length),this.setBuffer(r)}else this.setBuffer(e)},e.prototype.hasRemaining=function(e){return void 0===e&&(e=1),this.view.byteLength-this.pos>=e},e.prototype.createExtraByteError=function(e){var t=this.view,n=this.pos;return new RangeError("Extra "+(t.byteLength-n)+" of "+t.byteLength+" byte(s) found at buffer["+e+"]")},e.prototype.decode=function(e){this.reinitializeState(),this.setBuffer(e);var t=this.doDecodeSync();if(this.hasRemaining())throw this.createExtraByteError(this.pos);return t},e.prototype.decodeMulti=function(e){return Ct(this,(function(t){switch(t.label){case 0:this.reinitializeState(),this.setBuffer(e),t.label=1;case 1:return this.hasRemaining()?[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,u,d;return Ct(this,(function(p){switch(p.label){case 0:i=!1,p.label=1;case 1:p.trys.push([1,6,7,12]),t=It(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 Rt))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())throw this.createExtraByteError(this.totalPos);return[2,s]}throw h=(l=this).headByte,u=l.pos,d=l.totalPos,new RangeError("Insufficient data in parsing "+bt(h)+" at "+d+" ("+u+" 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 Tt(this,arguments,(function(){var n,r,o,i,s,a,c,l,h;return Ct(this,(function(u){switch(u.label){case 0:n=t,r=-1,u.label=1;case 1:u.trys.push([1,13,14,19]),o=It(e),u.label=2;case 2:return[4,kt(o.next())];case 3:if((i=u.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()),u.label=4;case 4:u.trys.push([4,9,,10]),u.label=5;case 5:return[4,kt(this.doDecodeSync())];case 6:return[4,u.sent()];case 7:return u.sent(),0==--r?[3,8]:[3,5];case 8:return[3,10];case 9:if(!((a=u.sent())instanceof Rt))throw a;return[3,10];case 10:this.totalPos+=this.pos,u.label=11;case 11:return[3,2];case 12:return[3,19];case 13:return c=u.sent(),l={error:c},[3,19];case 14:return u.trys.push([14,,17,18]),i&&!i.done&&(h=o.return)?[4,kt(h.call(o))]:[3,16];case 15:u.sent(),u.label=16;case 16:return[3,18];case 17:if(l)throw l.error;return[7];case 18:return[7];case 19:return[2]}}))}))},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 Nt("Unrecognized type byte: "+bt(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 Nt("The type of key must be string or number but "+typeof t);if("__proto__"===t)throw new Nt("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 Nt("Unrecognized array type byte: "+bt(e))}},e.prototype.pushMapState=function(e){if(e>this.maxMapLength)throw new Nt("Max length exceeded: map length ("+e+") > maxMapLengthLength ("+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 Nt("Max length exceeded: array length ("+e+") > maxArrayLength ("+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 Nt("Max length exceeded: UTF-8 byte length ("+e+") > maxStrLength ("+this.maxStrLength+")");if(this.bytes.byteLengthdt?function(e,t,n){var r=e.subarray(t,t+n);return ut.decode(r)}(this.bytes,o,e):ht(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 Nt("Max length exceeded: bin length ("+e+") > maxBinLength ("+this.maxBinLength+")");if(!this.hasRemaining(e+t))throw Pt;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 Nt("Max length exceeded: ext length ("+e+") > maxExtLength ("+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=gt(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 $t{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 Lt=new Uint8Array([145,Ie.Ping]);class Mt{constructor(e){this.name="messagepack",this.version=1,this.transferFormat=Ce.Binary,this._errorResult=1,this._voidResult=2,this._nonVoidResult=3,e=e||{},this._encoder=new vt(e.extensionCodec,e.context,e.maxDepth,e.initialBufferSize,e.sortKeys,e.forceFloat32,e.ignoreUndefined,e.forceIntegerToFloat),this._decoder=new Bt(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=Ae.instance);const r=$t.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 Ie.Invocation:return this._writeInvocation(e);case Ie.StreamInvocation:return this._writeStreamInvocation(e);case Ie.StreamItem:return this._writeStreamItem(e);case Ie.Completion:return this._writeCompletion(e);case Ie.Ping:return $t.write(Lt);case Ie.CancelInvocation:return this._writeCancelInvocation(e);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 Ie.Invocation:return this._createInvocationMessage(this._readHeaders(n),n);case Ie.StreamItem:return this._createStreamItemMessage(this._readHeaders(n),n);case Ie.Completion:return this._createCompletionMessage(this._readHeaders(n),n);case Ie.Ping:return this._createPingMessage(n);case Ie.Close:return this._createCloseMessage(n);default:return t.log(Ee.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:Ie.Close}}_createPingMessage(e){if(e.length<1)throw new Error("Invalid payload for Ping message.");return{type:Ie.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:Ie.Invocation}:{arguments:t[4],headers:e,streamIds:[],target:t[3],type:Ie.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:Ie.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:Ie.Completion}}_writeInvocation(e){let t;return t=e.streamIds?this._encoder.encode([Ie.Invocation,e.headers||{},e.invocationId||null,e.target,e.arguments,e.streamIds]):this._encoder.encode([Ie.Invocation,e.headers||{},e.invocationId||null,e.target,e.arguments]),$t.write(t.slice())}_writeStreamInvocation(e){let t;return t=e.streamIds?this._encoder.encode([Ie.StreamInvocation,e.headers||{},e.invocationId,e.target,e.arguments,e.streamIds]):this._encoder.encode([Ie.StreamInvocation,e.headers||{},e.invocationId,e.target,e.arguments]),$t.write(t.slice())}_writeStreamItem(e){const t=this._encoder.encode([Ie.StreamItem,e.headers||{},e.invocationId,e.item]);return $t.write(t.slice())}_writeCompletion(e){const t=e.error?this._errorResult:e.result?this._nonVoidResult:this._voidResult;let n;switch(t){case this._errorResult:n=this._encoder.encode([Ie.Completion,e.headers||{},e.invocationId,t,e.error]);break;case this._voidResult:n=this._encoder.encode([Ie.Completion,e.headers||{},e.invocationId,t]);break;case this._nonVoidResult:n=this._encoder.encode([Ie.Completion,e.headers||{},e.invocationId,t,e.result])}return $t.write(n.slice())}_writeCancelInvocation(e){const t=this._encoder.encode([Ie.CancelInvocation,e.headers||{},e.invocationId]);return $t.write(t.slice())}_readHeaders(e){const t=e[1];if("object"!=typeof t)throw new Error("Invalid headers.");return t}}let Ot=!1;const Ht="function"==typeof TextDecoder?new TextDecoder("utf-8"):null,Ft=Ht?Ht.decode.bind(Ht):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("")},jt=Math.pow(2,32),Wt=Math.pow(2,21)-1;function zt(e,t){return e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24}function qt(e,t){return e[t]+(e[t+1]<<8)+(e[t+2]<<16)+(e[t+3]<<24>>>0)}function Jt(e,t){const n=qt(e,t+4);if(n>Wt)throw new Error(`Cannot read uint64 with high order part ${n}, because the result would exceed Number.MAX_SAFE_INTEGER.`);return n*jt+qt(e,t)}class Kt{constructor(e){this.batchData=e;const t=new Gt(e);this.arrayRangeReader=new Qt(e),this.arrayBuilderSegmentReader=new Zt(e),this.diffReader=new Vt(e),this.editReader=new Xt(e,t),this.frameReader=new Yt(e,t)}updatedComponents(){return zt(this.batchData,this.batchData.length-20)}referenceFrames(){return zt(this.batchData,this.batchData.length-16)}disposedComponentIds(){return zt(this.batchData,this.batchData.length-12)}disposedEventHandlerIds(){return zt(this.batchData,this.batchData.length-8)}updatedComponentsEntry(e,t){const n=e+4*t;return zt(this.batchData,n)}referenceFramesEntry(e,t){return e+20*t}disposedComponentIdsEntry(e,t){const n=e+4*t;return zt(this.batchData,n)}disposedEventHandlerIdsEntry(e,t){const n=e+8*t;return Jt(this.batchData,n)}}class Vt{constructor(e){this.batchDataUint8=e}componentId(e){return zt(this.batchDataUint8,e)}edits(e){return e+4}editsEntry(e,t){return e+16*t}}class Xt{constructor(e,t){this.batchDataUint8=e,this.stringReader=t}editType(e){return zt(this.batchDataUint8,e)}siblingIndex(e){return zt(this.batchDataUint8,e+4)}newTreeIndex(e){return zt(this.batchDataUint8,e+8)}moveToSiblingIndex(e){return zt(this.batchDataUint8,e+8)}removedAttributeName(e){const t=zt(this.batchDataUint8,e+12);return this.stringReader.readString(t)}}class Yt{constructor(e,t){this.batchDataUint8=e,this.stringReader=t}frameType(e){return zt(this.batchDataUint8,e)}subtreeLength(e){return zt(this.batchDataUint8,e+4)}elementReferenceCaptureId(e){const t=zt(this.batchDataUint8,e+4);return this.stringReader.readString(t)}componentId(e){return zt(this.batchDataUint8,e+8)}elementName(e){const t=zt(this.batchDataUint8,e+8);return this.stringReader.readString(t)}textContent(e){const t=zt(this.batchDataUint8,e+4);return this.stringReader.readString(t)}markupContent(e){const t=zt(this.batchDataUint8,e+4);return this.stringReader.readString(t)}attributeName(e){const t=zt(this.batchDataUint8,e+4);return this.stringReader.readString(t)}attributeValue(e){const t=zt(this.batchDataUint8,e+8);return this.stringReader.readString(t)}attributeEventHandlerId(e){return Jt(this.batchDataUint8,e+12)}}class Gt{constructor(e){this.batchDataUint8=e,this.stringTableStartIndex=zt(e,e.length-4)}readString(e){if(-1===e)return null;{const n=zt(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(en.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(en.Debug,`Waiting for batch ${this.nextBatchId}. Batch ${e} not processed.`);try{this.nextBatchId++,this.logger.log(en.Debug,`Applying batch ${e}.`),function(e,t){const n=Q[e];if(!n)throw new Error(`There is no browser renderer with ID ${e}.`);const r=t.arrayRangeReader,o=t.updatedComponents(),i=r.values(o),s=r.count(o),a=t.referenceFrames(),c=r.values(a),l=t.diffReader;for(let e=0;e=this.minLevel){const n=`[${(new Date).toISOString()}] ${en[e]}: ${t}`;switch(e){case en.Critical:case en.Error:console.error(n);break;case en.Warning:console.warn(n);break;case en.Information:console.info(n);break;default:console.log(n)}}}}class on{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!==ke.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!==ke.Connected)return!1;const t=await e.invoke("StartCircuit",re.getBaseURI(),re.getLocationHref(),JSON.stringify(this.components.map((e=>e.toRecord()))),this.applicationState||"");return!!t&&(this.initialize(t),!0)}resolveElement(e){const t=Number.parseInt(e);if(Number.isNaN(t))throw new Error(`Invalid sequence number '${e}'.`);return function(e,t){if(!e.parentNode)throw new Error(`Comment not connected to the DOM ${e.textContent}`);const n=e.parentNode,r=k(n,!0),o=A(r);return Array.from(n.childNodes).forEach((e=>o.push(e))),e[C]=r,t&&(e[I]=t,k(t)),k(e)}(this.components[t].start,this.components[t].end)}}const sn={configureSignalR:e=>{},logLevel:en.Warning,reconnectionOptions:{maxRetries:8,retryIntervalMilliseconds:2e4,dialogId:"components-reconnect-modal"}};class an{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.modal.innerHTML='

Alternatively, reload

',this.message=this.modal.querySelector("h5"),this.button=this.modal.querySelector("button"),this.reloadParagraph=this.modal.querySelector("p"),this.loader=this.getLoader(),this.message.after(this.loader),this.button.addEventListener("click",(async()=>{this.show();try{await(null==fe?void 0:fe.reconnect)()||this.rejected()}catch(e){this.logger.log(en.Error,e),this.failed()}})),this.reloadParagraph.querySelector("a").addEventListener("click",(()=>location.reload()))}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",this.message.innerHTML="Reconnection failed. Try reloading the page if you're unable to reconnect.",this.message.querySelector("a").addEventListener("click",(()=>location.reload()))}rejected(){this.button.style.display="none",this.reloadParagraph.style.display="none",this.loader.style.display="none",this.message.innerHTML="Could not reconnect to the server. Reload the page to restore functionality.",this.message.querySelector("a").addEventListener("click",(()=>location.reload()))}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 cn{constructor(e,t,n){this.dialog=e,this.maxRetries=t,this.document=n,this.document=n;const r=this.document.getElementById(cn.MaxRetriesId);r&&(r.innerText=this.maxRetries.toString())}show(){this.removeClasses(),this.dialog.classList.add(cn.ShowClassName)}update(e){const t=this.document.getElementById(cn.CurrentAttemptId);t&&(t.innerText=e.toString())}hide(){this.removeClasses(),this.dialog.classList.add(cn.HideClassName)}failed(){this.removeClasses(),this.dialog.classList.add(cn.FailedClassName)}rejected(){this.removeClasses(),this.dialog.classList.add(cn.RejectedClassName)}removeClasses(){this.dialog.classList.remove(cn.ShowClassName,cn.HideClassName,cn.FailedClassName,cn.RejectedClassName)}}cn.ShowClassName="components-reconnect-show",cn.HideClassName="components-reconnect-hide",cn.FailedClassName="components-reconnect-failed",cn.RejectedClassName="components-reconnect-rejected",cn.MaxRetriesId="components-reconnect-max-retries",cn.CurrentAttemptId="components-reconnect-current-attempt";class ln{constructor(e,t,n){this._currentReconnectionProcess=null,this._logger=e,this._reconnectionDisplay=t,this._reconnectCallback=n||(()=>fe.reconnect())}onConnectionDown(e,t){if(!this._reconnectionDisplay){const t=document.getElementById(e.dialogId);this._reconnectionDisplay=t?new cn(t,e.maxRetries,document):new an(e.dialogId,e.maxRetries,document,this._logger)}this._currentReconnectionProcess||(this._currentReconnectionProcess=new hn(e,this._logger,this._reconnectCallback,this._reconnectionDisplay))}onConnectionUp(){this._currentReconnectionProcess&&(this._currentReconnectionProcess.dispose(),this._currentReconnectionProcess=null)}}class hn{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;thn.MaximumFirstRetryInterval?hn.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(en.Error,e)}}this.reconnectDisplay.failed()}delay(e){return new Promise((t=>setTimeout(t,e)))}}hn.MaximumFirstRetryInterval=3e3;const un=/^\s*Blazor-Component-State:(?[a-zA-Z0-9\+\/=]+)$/;function dn(e){var t;if(e.nodeType===Node.COMMENT_NODE){const n=e.textContent||"",r=un.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 gn(e,t){const n=e.currentElement;if(n&&n.nodeType===Node.COMMENT_NODE&&n.textContent){const r=fn.exec(n.textContent),o=r&&r.groups&&r.groups.descriptor;if(!o)return;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;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.");if(c){const e=mn(c,n);if(!e)throw new Error(`Could not find an end component comment for '${t}'`);return{type:r,assembly:o,typeName:i,parameterDefinitions:s&&atob(s),parameterValues:a&&atob(a),start:t,prerenderId:c,end:e}}return{type:r,assembly:o,typeName:i,parameterDefinitions:s&&atob(s),parameterValues:a&&atob(a),start:t}}}(r,n,e);case"server":return function(e,t,n){const{type:r,descriptor:o,sequence:i,prerenderId:s}=e;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)}'`);if(s){const e=mn(s,n);if(!e)throw new Error(`Could not find an end component comment for '${t}'`);return{type:r,sequence:i,descriptor:o,start:t,prerenderId:s,end:e}}return{type:r,sequence:i,descriptor:o,start:t}}}(r,n,e)}}catch(e){throw new Error(`Found malformed component comment at ${n.textContent}`)}}}function mn(e,t){for(;t.next()&&t.currentElement;){const n=t.currentElement;if(n.nodeType!==Node.COMMENT_NODE)continue;if(!n.textContent)continue;const r=fn.exec(n.textContent),o=r&&r[1];if(o)return yn(o,e),n}}function yn(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 wn{constructor(e){this.childNodes=e,this.currentIndex=-1,this.length=e.length}next(){return this.currentIndex++,this.currentIndexe.sequence-t.sequence))}(e)}(document),o=dn(document),i=new on(r,o||""),s=await Tn(t,n,i);if(!await i.startCircuit(s))return void n.log(en.Error,"Failed to start the circuit.");let a=!1;const c=()=>{if(!a){const e=new FormData,t=i.circuitId;e.append("circuitId",t),a=navigator.sendBeacon("_blazor/disconnect",e)}};fe.disconnect=c,window.addEventListener("unload",c,{capture:!1,once:!0}),fe.reconnect=async e=>{if(Cn)return!1;const r=e||await Tn(t,n,i);return await i.reconnect(r)?(t.reconnectionHandler.onConnectionUp(),!0):(n.log(en.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)},n.log(en.Information,"Blazor server-side application started.")}async function Tn(t,n,r){const i=new Mt;i.name="blazorpack";const s=(new rt).withUrl("_blazor").withHubProtocol(i);t.configureSignalR(s);const a=s.build();o=(e,t)=>{a.send("DispatchBrowserEvent",JSON.stringify(e),JSON.stringify(t))},fe._internal.navigationManager.listenForNavigationEvents(((e,t)=>a.send("OnLocationChanged",e,t))),a.on("JS.AttachComponent",((e,t)=>function(e,t,n){let r=Q[0];r||(r=Q[0]=new V(0)),r.attachRootComponentToLogicalElement(n,t)}(0,r.resolveElement(t),e))),a.on("JS.BeginInvokeJS",e.jsCallDispatcher.beginInvokeJSFromDotNet),a.on("JS.EndInvokeDotNet",e.jsCallDispatcher.endInvokeDotNetFromJS),a.on("JS.ReceiveByteArray",e.jsCallDispatcher.receiveByteArray);const c=tn.getOrCreate(n);a.on("JS.RenderBatch",((e,t)=>{n.log(en.Debug,`Received render batch with id ${e} and ${t.byteLength} bytes.`),c.processBatch(e,t,a)})),a.onclose((e=>!Cn&&t.reconnectionHandler.onConnectionDown(t.reconnectionOptions,e))),a.on("JS.Error",(e=>{Cn=!0,Dn(a,e,n),async function(){let e=document.querySelector("#blazor-error-ui");e&&(e.style.display="block"),Ot||(Ot=!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()}})))}()})),fe._internal.forceCloseConnection=()=>a.stop(),fe._internal.sendJSDataStream=(e,t,n)=>{setTimeout((async()=>{let r=5,o=(new Date).valueOf();try{const i=n-512;if(i<=0)throw new Error("The chunk size must be greater than 0.");let s=0;for(;s1)await a.send("ReceiveJSDataChunk",t,c,null);else{if(!await a.invoke("ReceiveJSDataChunk",t,c,null))break;const e=(new Date).valueOf(),n=e-o;o=e,r=Math.max(1,Math.round(500/n))}s+=n}}catch(e){await a.send("ReceiveJSDataChunk",t,null,e.toString())}}),0)};try{await a.start()}catch(e){Dn(a,e,n)}return e.attachDispatcher({beginInvokeDotNetFromJS:(e,t,n,r,o)=>{a.send("BeginInvokeDotNetFromJS",e?e.toString():null,t,n,r||0,o)},endInvokeJSFromDotNet:(e,t,n)=>{a.send("EndInvokeJSFromDotNet",e,t,n)},sendByteArray:(e,t)=>{a.send("ReceiveByteArray",e,t)}}),a}function Dn(e,t,n){n.log(en.Error,t),e&&e.stop()}fe.start=kn,document&&document.currentScript&&"false"!==document.currentScript.getAttribute("autostart")&&kn()})(); \ No newline at end of file diff --git a/src/Components/Web.JS/src/Boot.Server.ts b/src/Components/Web.JS/src/Boot.Server.ts index a4de8a4ae8de..23725e7e58bd 100644 --- a/src/Components/Web.JS/src/Boot.Server.ts +++ b/src/Components/Web.JS/src/Boot.Server.ts @@ -122,7 +122,7 @@ async function initializeConnection(options: CircuitStartOptions, logger: Logger Blazor._internal.forceCloseConnection = () => connection.stop(); - Blazor._internal.sendJSDataStream = async (data: ArrayBufferView, streamId: string, maximumIncomingBytes: number) => { + Blazor._internal.sendJSDataStream = (data: ArrayBufferView, streamId: string, maximumIncomingBytes: number) => { // Run the rest in the background, without delaying the completion of the call to sendJSDataStream // otherwise we'll deadlock (.NET can't begin reading until this completes, but it won't complete // because nobody's reading the pipe) @@ -143,7 +143,6 @@ async function initializeConnection(options: CircuitStartOptions, logger: Logger // stream items from the client (per stream) will be stored before reading any more stream items (thus applying backpressure). while (position < data.byteLength) { const nextChunkSize = Math.min(chunkSize, data.byteLength - position); - console.log(`Sending a chunk of length ${nextChunkSize}`); const nextChunkData = new Uint8Array(data.buffer, data.byteOffset + position, nextChunkSize); numChunksUntilNextAck--; diff --git a/src/Components/test/E2ETest/Tests/InteropTest.cs b/src/Components/test/E2ETest/Tests/InteropTest.cs index 1bb3c9febab4..fb0da802cc18 100644 --- a/src/Components/test/E2ETest/Tests/InteropTest.cs +++ b/src/Components/test/E2ETest/Tests/InteropTest.cs @@ -63,7 +63,7 @@ public void CanInvokeDotNetMethods() ["roundTripByteArrayWrapperObjectAsyncFromJS"] = @"{""strVal"":""Some string"",""byteArrayVal"":{""0"":1,""1"":5,""2"":7,""3"":17,""4"":200,""5"":138},""intVal"":42}", ["roundTripByteArrayAsyncFromDotNet"] = @"1,5,7,15,35,200", ["roundTripByteArrayWrapperObjectAsyncFromDotNet"] = @"StrVal: Some String, IntVal: 100000, ByteArrayVal: 1,5,7,15,35,200", - ["jsToDotNetStreamAsync"] = @"1,5,7,15,35,200", + ["jsToDotNetStreamAsync"] = "Success", ["AsyncThrowSyncException"] = @"""System.InvalidOperationException: Threw a sync exception!", ["AsyncThrowAsyncException"] = @"""System.InvalidOperationException: Threw an async exception!", ["SyncExceptionFromAsyncMethod"] = "Function threw a sync exception!", diff --git a/src/Components/test/testassets/BasicTestApp/InteropComponent.razor b/src/Components/test/testassets/BasicTestApp/InteropComponent.razor index 998171734fa5..c4e552dcce35 100644 --- a/src/Components/test/testassets/BasicTestApp/InteropComponent.razor +++ b/src/Components/test/testassets/BasicTestApp/InteropComponent.razor @@ -2,6 +2,7 @@ @using BasicTestApp.InteropTest @using System.Runtime.InteropServices @using System.Text.Json +@using System.IO @inject IJSRuntime JSRuntime @@ -175,20 +176,39 @@ ReturnValues["roundTripByteArrayWrapperObjectFromDotNet"] = ((IJSInProcessRuntime)JSRuntime).Invoke("roundTripByteArrayWrapperObject", byteArrayWrapperObject).ToString(); } - // Only run this test for Blazor Server + // Streaming interop tests need to be run only for Blazor server + // As such, we set the result of `jsToDotNetStreamAsync` to the expected result for WASM if (shouldSupportSyncInterop) { - // Set the result to the expected value in the WASM case to ensure - // missing this test case doesn't result in test failure. - ReturnValues["jsToDotNetStreamAsync"] = "1,5,7,15,35,200"; + // In the WASM case, setting the result to the expected result ensures the missing test case doesn't result in test failure. + ReturnValues["jsToDotNetStreamAsync"] = "Success"; } else { + // Proceed to run the actual blazor server streaming interop tests var dataReference = await JSRuntime.InvokeAsync("jsToDotNetStreamAsync"); using var stream = await dataReference.OpenReadStreamAsync(); using var memoryStream = new System.IO.MemoryStream(); await stream.CopyToAsync(memoryStream); - ReturnValues["jsToDotNetStreamAsync"] = string.Join(",", (memoryStream.ToArray())); + var buffer = memoryStream.ToArray(); + + for (var i = 0; i < buffer.Length; i++) + { + var expectedValue = i % 256; + if (buffer[i] != expectedValue) + { + ReturnValues["jsToDotNetStreamAsync"] = $"Failure at index {i}."; + break; + } + } + + if (buffer.Length != 100_000) + { + ReturnValues["jsToDotNetStreamAsync"] = $"Failure, got a stream of length {buffer.Length}, expected a length of 50,000."; + } + + // Mark the test as successful if we haven't already set a failure above + ReturnValues.TryAdd("jsToDotNetStreamAsync", "Success"); } Invocations = invocations; diff --git a/src/Components/test/testassets/BasicTestApp/InteropTest/JSDataReferenceInterop.cs b/src/Components/test/testassets/BasicTestApp/InteropTest/JSDataReferenceInterop.cs new file mode 100644 index 000000000000..d959ad470eb5 --- /dev/null +++ b/src/Components/test/testassets/BasicTestApp/InteropTest/JSDataReferenceInterop.cs @@ -0,0 +1,35 @@ +// Copyright (c) .NET Foundation. All rights reserved. +// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. + +using System.Threading.Tasks; +using Microsoft.JSInterop; + +namespace BasicTestApp.InteropTest +{ + public class JSDataReferenceInterop + { + [JSInvokable] + public static Task RoundTripJSDataReferenceAsync(IJSDataReference jsDataReference) + { + return Task.FromResult(jsDataReference); + } + + [JSInvokable] + public static Task RoundTripJSDataReferenceWrapperObjectAsync(JSDataReferenceWrapper jsDataReferenceWrapper) + { + return Task.FromResult(jsDataReferenceWrapper); + } + + public class JSDataReferenceWrapper + { + public string StrVal { get; set; } + public IJSDataReference JSDataReferenceVal { get; set; } + public int IntVal { get; set; } + + public override string ToString() + { + return $"StrVal: {StrVal}, IntVal: {IntVal}, JSDataReferenceVal: {string.Join(',', JSDataReferenceVal)}"; + } + } + } +} diff --git a/src/Components/test/testassets/BasicTestApp/wwwroot/js/jsinteroptests.js b/src/Components/test/testassets/BasicTestApp/wwwroot/js/jsinteroptests.js index f43e601dbd53..e31c7826d84b 100644 --- a/src/Components/test/testassets/BasicTestApp/wwwroot/js/jsinteroptests.js +++ b/src/Components/test/testassets/BasicTestApp/wwwroot/js/jsinteroptests.js @@ -263,7 +263,8 @@ function roundTripByteArrayWrapperObject(byteArrayWrapperObject) { function jsToDotNetStreamAsync() { return new Promise((resolve, reject) => { setTimeout(function () { - resolve(new Uint8Array([1, 5, 7, 15, 35, 200])); + const largeArray = Array.from({ length: 100000 }).map((_, index) => index % 256); + resolve(new Uint8Array(largeArray)); }, 100); }); } diff --git a/src/JSInterop/Microsoft.JSInterop/src/JSRuntime.cs b/src/JSInterop/Microsoft.JSInterop/src/JSRuntime.cs index 44a3e3b59b04..affcd36d208a 100644 --- a/src/JSInterop/Microsoft.JSInterop/src/JSRuntime.cs +++ b/src/JSInterop/Microsoft.JSInterop/src/JSRuntime.cs @@ -217,7 +217,7 @@ protected internal virtual void ReceiveByteArray(int id, byte[] data) /// Expected length of the incoming data stream. /// Amount of bytes to buffer before flushing. /// for cancelling read. - /// + /// for the data reference represented by . protected internal virtual Task ReadJSDataAsStreamAsync(IJSDataReference jsDataReference, long totalLength, long maxBufferSize, CancellationToken cancellationToken) { // The reason it's virtual and not abstract is just for back-compat diff --git a/src/Shared/JSInterop/JSCallResultTypeHelper.cs b/src/Shared/JSInterop/JSCallResultTypeHelper.cs index 4d491a5a629a..bd3be2d13d5c 100644 --- a/src/Shared/JSInterop/JSCallResultTypeHelper.cs +++ b/src/Shared/JSInterop/JSCallResultTypeHelper.cs @@ -19,8 +19,7 @@ public static JSCallResultType FromGeneric() { return JSCallResultType.JSObjectReference; } - else if (typeof(TResult).Assembly == _currentAssembly - && typeof(TResult) == typeof(IJSDataReference)) + else if (typeof(TResult).Assembly == _currentAssembly && typeof(TResult) == typeof(IJSDataReference)) { return JSCallResultType.JSDataReference; } From eafd3f8a4c5f7f729e35a388ee6e7f4238c79d61 Mon Sep 17 00:00:00 2001 From: Tanay Parikh Date: Fri, 18 Jun 2021 14:20:49 -0700 Subject: [PATCH 24/37] E2E tests --- .../Web.JS/dist/Release/blazor.server.js | 2 +- .../Web.JS/dist/Release/blazor.webview.js | 2 +- .../test/E2ETest/Tests/InteropTest.cs | 5 +- .../BasicTestApp/InteropComponent.razor | 65 +++++++++++++------ .../InteropTest/JSDataReferenceInterop.cs | 54 ++++++++++++--- .../BasicTestApp/wwwroot/js/jsinteroptests.js | 27 +++++++- .../src/src/Microsoft.JSInterop.ts | 18 ++--- 7 files changed, 131 insertions(+), 42 deletions(-) diff --git a/src/Components/Web.JS/dist/Release/blazor.server.js b/src/Components/Web.JS/dist/Release/blazor.server.js index 73def9442e00..efc409f8ce4b 100644 --- a/src/Components/Web.JS/dist/Release/blazor.server.js +++ b/src/Components/Web.JS/dist/Release/blazor.server.js @@ -1 +1 @@ -(()=>{"use strict";var e,t,n;!function(e){window.DotNet=e;const t=[],n=new Map;class r{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 o="__jsObjectId",i={},s={0:new r(window)};s[0]._cachedFunctions.set("import",(e=>("string"==typeof e&&e.startsWith("./")&&(e=document.baseURI+e.substr(2)),import(e))));let a,c=1,l=1,h=null;function u(e){t.push(e)}function d(e){if(e&&"object"==typeof e){s[l]=new r(e);const t={[o]:l};return l++,t}throw new Error(`Cannot create a JSObjectReference from the value '${e}'.`)}function p(e){if(!(e.buffer instanceof ArrayBuffer))throw new Error(`Cannot create a JSDataReference from the value '${e}' as it is not a valid ArrayBuffer.`);if(void 0===e.byteLength)throw new Error(`Cannot create a JSDataReference from the value '${e}' as it doesn't have a byteLength.`);const t={__jsDataReferenceLength:e.byteLength};try{const n=d(e);t.__jsObjectId=n.__jsObjectId}catch{throw new Error(`Cannot create a JSDataReference from the value '${e}'.`)}return t}function f(e){return e?JSON.parse(e,((e,n)=>t.reduce(((t,n)=>n(e,t)),n))):null}function g(e,t,n,r){const o=y();if(o.invokeDotNetFromJS){const i=k(r),s=o.invokeDotNetFromJS(e,t,n,i);return s?f(s):null}throw new Error("The current dispatcher does not support synchronous calls from JS to .NET. Use invokeMethodAsync instead.")}function m(e,t,n,r){if(e&&n)throw new Error(`For instance method calls, assemblyName should be null. Received '${e}'.`);const o=c++,s=new Promise(((e,t)=>{i[o]={resolve:e,reject:t}}));try{const i=k(r);y().beginInvokeDotNetFromJS(o,e,t,n,i)}catch(e){w(o,!1,e)}return s}function y(){if(null!==h)return h;throw new Error("No .NET call dispatcher has been set.")}function w(e,t,n){if(!i.hasOwnProperty(e))throw new Error(`There is no pending async call with ID ${e}.`);const r=i[e];delete i[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){let n=s[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 s[e]}e.attachDispatcher=function(e){h=e},e.attachReviver=u,e.invokeMethod=function(e,t,...n){return g(e,t,null,n)},e.invokeMethodAsync=function(e,t,...n){return m(e,t,null,n)},e.createJSObjectReference=d,e.createJSDataReference=p,e.disposeJSObjectReference=function(e){const t=e&&e.__jsObjectId;"number"==typeof t&&_(t)},function(e){e[e.Default=0]="Default",e[e.JSObjectReference=1]="JSObjectReference",e[e.JSDataReference=2]="JSDataReference"}(a=e.JSCallResultType||(e.JSCallResultType={})),e.jsCallDispatcher={findJSFunction:b,disposeJSObjectReferenceById:_,invokeJSFromDotNet:(e,t,n,r)=>{const o=C(b(e,r).apply(null,f(t)),n);return null==o?null:k(o)},beginInvokeJSFromDotNet:(e,t,n,r,o)=>{const i=new Promise((e=>{e(b(t,o).apply(null,f(n)))}));e&&i.then((t=>y().endInvokeJSFromDotNet(e,!0,k([e,!0,C(t,r)]))),(t=>y().endInvokeJSFromDotNet(e,!1,JSON.stringify([e,!1,v(t)]))))},endInvokeDotNetFromJS:(e,t,n)=>{const r=t?f(n):new Error(n);w(parseInt(e),t,r)},receiveByteArray:(e,t)=>{n.set(e,t)}};class E{constructor(e){this._id=e}invokeMethod(e,...t){return g(null,e,this._id,t)}invokeMethodAsync(e,...t){return m(null,e,this._id,t)}dispose(){m(null,"__Dispose",this._id,null).catch((e=>console.error(e)))}serializeAsArg(){return{__dotNetObject:this._id}}}const S="__byte[]";function C(e,t){switch(t){case a.Default:return e;case a.JSObjectReference:return d(e);case a.JSDataReference:return p(e);default:throw new Error(`Invalid JS call result type '${t}'.`)}}u((function(e,t){if(t&&"object"==typeof t){if(t.hasOwnProperty("__dotNetObject"))return new E(t.__dotNetObject);if(t.hasOwnProperty(o)){const e=t.__jsObjectId,n=s[e];if(n)return n.getWrappedObject();throw new Error(`JS object instance with Id '${e}' does not exist. It may have been disposed.`)}if(t.hasOwnProperty(S)){const e=t["__byte[]"],r=n.get(e);if(void 0===r)throw new Error(`Byte array index '${e}' does not exist.`);return r}}return t}));let I=0;function k(e){return I=0,JSON.stringify(e,T)}function T(e,t){if(t instanceof E)return t.serializeAsArg();if(t instanceof Uint8Array){h.sendByteArray(I,t);const e={[S]:I};return I++,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"}(n||(n={}));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}}let o;function i(e,t){if(!o)throw new Error("eventDispatcher not initialized. Call 'setEventDispatcher' to configure it.");o(e,t)}const s=new Map,a=new Map,c={createEventArgs:()=>({})},l=[];function h(e){return s.get(e)}function u(e){const t=s.get(e);return(null==t?void 0:t.browserEventName)||e}function d(e,t){e.forEach((e=>s.set(e,t)))}function p(e){const t=[];for(let n=0;n{return{...f(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}}),d(["focus","blur","focusin","focusout"],c),d(["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};var t}}),d(["contextmenu","click","mouseover","mouseout","mousemove","mousedown","mouseup","dblclick"],{createEventArgs:e=>f(e)}),d(["error"],{createEventArgs:e=>{return{message:(t=e).message,filename:t.filename,lineno:t.lineno,colno:t.colno};var t}}),d(["loadstart","timeout","abort","load","loadend","progress"],{createEventArgs:e=>{return{lengthComputable:(t=e).lengthComputable,loaded:t.loaded,total:t.total};var t}}),d(["touchcancel","touchend","touchmove","touchenter","touchleave","touchstart"],{createEventArgs:e=>{return{detail:(t=e).detail,touches:p(t.touches),targetTouches:p(t.targetTouches),changedTouches:p(t.changedTouches),ctrlKey:t.ctrlKey,shiftKey:t.shiftKey,altKey:t.altKey,metaKey:t.metaKey,type:t.type};var t}}),d(["gotpointercapture","lostpointercapture","pointercancel","pointerdown","pointerenter","pointerleave","pointermove","pointerout","pointerover","pointerup"],{createEventArgs:e=>{return{...f(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}}),d(["wheel","mousewheel"],{createEventArgs:e=>{return{...f(t=e),deltaX:t.deltaX,deltaY:t.deltaY,deltaZ:t.deltaZ,deltaMode:t.deltaMode};var t}}),d(["toggle"],c);const g=["date","datetime-local","month","time","week"],m=E(["abort","blur","change","error","focus","load","loadend","loadstart","mouseenter","mouseleave","progress","reset","scroll","submit","unload","toggle","DOMNodeInsertedIntoDocument","DOMNodeRemovedFromDocument"]),y={submit:!0},w=E(["click","dblclick","mousedown","mousemove","mouseup"]);class v{constructor(e){this.browserRendererId=e,this.afterClickCallbacks=[];const t=++v.nextEventDelegatorId;this.eventsCollectionKey=`_blazorEvents_${t}`,this.eventInfoStore=new b(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,a.get(n));var n;t&&t.forEach((t=>this.dispatchGlobalEventToAllElements(t,e))),"click"===e.type&&this.afterClickCallbacks.forEach((t=>t(e)))}dispatchGlobalEventToAllElements(e,t){let n=t.target,o=null,s=!1;const a=m.hasOwnProperty(e);let c=!1;for(;n;){const d=this.getEventHandlerInfosForElement(n,!1);if(d){const a=d.getHandler(e);if(a&&(l=n,u=t.type,!((l instanceof HTMLButtonElement||l instanceof HTMLInputElement||l instanceof HTMLTextAreaElement||l instanceof HTMLSelectElement)&&w.hasOwnProperty(u)&&l.disabled))){if(!s){const n=h(e);o=(null==n?void 0:n.createEventArgs)?n.createEventArgs(t):{},s=!0}y.hasOwnProperty(t.type)&&t.preventDefault(),i({browserRendererId:this.browserRendererId,eventHandlerId:a.eventHandlerId,eventName:e,eventFieldInfo:r.fromEvent(a.renderingComponentId,t)},o)}d.stopPropagation(e)&&(c=!0),d.preventDefault(e)&&t.preventDefault()}n=a||c?null:n.parentElement}var l,u}getEventHandlerInfosForElement(e,t){return e.hasOwnProperty(this.eventsCollectionKey)?e[this.eventsCollectionKey]:t?e[this.eventsCollectionKey]=new _:null}}v.nextEventDelegatorId=0;class b{constructor(e){this.globalListener=e,this.infosByEventHandlerId={},this.countByEventName={},l.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=u(e),this.countByEventName.hasOwnProperty(e))this.countByEventName[e]++;else{this.countByEventName[e]=1;const t=m.hasOwnProperty(e);document.addEventListener(e,this.globalListener,t)}}update(e,t){if(this.infosByEventHandlerId.hasOwnProperty(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=u(t.eventName);0==--this.countByEventName[n]&&(delete this.countByEventName[n],document.removeEventListener(n,this.globalListener))}return t}handleEventNameAliasAdded(e,t){if(this.countByEventName.hasOwnProperty(e)){const n=this.countByEventName[e];delete this.countByEventName[e],document.removeEventListener(e,this.globalListener),this.addGlobalListener(t),this.countByEventName[t]+=n-1}}}class _{constructor(){this.handlers={},this.preventDefaultFlags=null,this.stopPropagationFlags=null}getHandler(e){return this.handlers.hasOwnProperty(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 E(e){const t={};return e.forEach((e=>{t[e]=!0})),t}const S=O("_blazorLogicalChildren"),C=O("_blazorLogicalParent"),I=O("_blazorLogicalEnd");function k(e,t){if(e.childNodes.length>0&&!t)throw new Error("New logical elements must start empty, or allowExistingContents must be true");return S in e||(e[S]=[]),e}function T(e,t){const n=document.createComment("!");return D(n,e,t),n}function D(e,t,n){const r=e;if(e instanceof Comment&&A(r)&&A(r).length>0)throw new Error("Not implemented: inserting non-empty logical container");if(R(r))throw new Error("Not implemented: moving existing logical children");const o=A(t);if(n0;)x(n,0)}const r=n;r.parentNode.removeChild(r)}function R(e){return e[C]||null}function P(e,t){return A(e)[t]}function U(e){var t=B(e);return"http://www.w3.org/2000/svg"===t.namespaceURI&&"foreignObject"!==t.tagName}function A(e){return e[S]}function N(e,t){const n=A(e);t.forEach((e=>{e.moveRangeStart=n[e.fromSiblingIndex],e.moveRangeEnd=M(e.moveRangeStart)})),t.forEach((t=>{const r=t.moveToBeforeMarker=document.createComment("marker"),o=n[t.toSiblingIndex+1];o?o.parentNode.insertBefore(r,o):L(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 B(e){if(e instanceof Element)return e;if(e instanceof Comment)return e.parentNode;throw new Error("Not a valid logical element")}function $(e){const t=A(R(e));return t[Array.prototype.indexOf.call(t,e)+1]||null}function L(e,t){if(t instanceof Element)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=$(t);n?n.parentNode.insertBefore(e,n):L(e,R(t))}}}function M(e){if(e instanceof Element)return e;const t=$(e);if(t)return t.previousSibling;{const t=R(e);return t instanceof Element?t.lastChild:M(t)}}function O(e){return"function"==typeof Symbol?Symbol():e}function H(e){return`_bl_${e}`}e.attachReviver(((e,t)=>t&&"object"==typeof t&&t.hasOwnProperty("__internalId")&&"string"==typeof t.__internalId?function(e){const t=`[${H(e)}]`;return document.querySelector(t)}(t.__internalId):t));const F="_blazorSelectValue",j=document.createElement("template"),W=document.createElementNS("http://www.w3.org/2000/svg","g"),z={},q="__internal_",J="preventDefault_",K="stopPropagation_";class V{constructor(e){this.childComponentLocations={},this.eventDelegator=new v(e),this.eventDelegator.notifyAfterClick((e=>{if(!ee)return;if(0!==e.button||function(e){return e.ctrlKey||e.shiftKey||e.altKey||e.metaKey}(e))return;if(e.defaultPrevented)return;const t=function(e){const t=!window._blazorDisableComposedPath&&e.composedPath&&e.composedPath();if(t){for(let e=0;ese(!1))))},enableNavigationInterception:function(){ee=!0},navigateTo:oe,getBaseURI:()=>document.baseURI,getLocationHref:()=>location.href};function oe(e,t,n=!1){const r=ce(e);if(!t&&he(r))ie(r,!1,n);else if(t&&location.href===e){const t=e+"?";history.replaceState(null,"",t),location.replace(e)}else n?history.replaceState(null,"",r):location.href=e}function ie(e,t,n=!1){Z=!0,n?history.replaceState(null,"",e):history.pushState(null,"",e),se(t)}async function se(e){ne&&await ne(location.href,e)}let ae;function ce(e){return ae=ae||document.createElement("a"),ae.href=e,ae.href}function le(e,t){return e?e.tagName===t?e:le(e.parentElement,t):null}function he(e){const t=(n=document.baseURI).substr(0,n.lastIndexOf("/")+1);var n;return e.startsWith(t)}const ue={init:function(e,t,n,r=50){const o=pe(t);(o||document.documentElement).style.overflowAnchor="none";const i=new IntersectionObserver((function(r){r.forEach((r=>{var o;if(!r.isIntersecting)return;const i=t.getBoundingClientRect(),s=n.getBoundingClientRect().top-i.bottom,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`});i.observe(t),i.observe(n);const s=c(t),a=c(n);function c(e){const t=new MutationObserver((()=>{i.unobserve(e),i.observe(e)}));return t.observe(e,{attributes:!0}),t}de[e._id]={intersectionObserver:i,mutationObserverBefore:s,mutationObserverAfter:a}},dispose:function(e){const t=de[e._id];t&&(t.intersectionObserver.disconnect(),t.mutationObserverBefore.disconnect(),t.mutationObserverAfter.disconnect(),e.dispose(),delete de[e._id])}},de={};function pe(e){return e?"visible"!==getComputedStyle(e).overflowY?e:pe(e.parentElement):null}const fe={navigateTo:oe,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=a.get(t.browserEventName);n?n.push(e):a.set(t.browserEventName,[e]),l.forEach((n=>n(e,t.browserEventName)))}s.set(e,t)},_internal:{navigationManager:re,domWrapper:{focus:function(e,t){if(!(e instanceof HTMLElement))throw new Error("Unable to focus an invalid element.");e.focus({preventScroll:t})},focusBySelector:function(e){const t=document.querySelector(e);t&&(t.hasAttribute("tabindex")||(t.tabIndex=-1),t.focus())}},Virtualize:ue}};window.Blazor=fe;const ge=[0,2e3,1e4,3e4,null];class me{constructor(e){this._retryDelays=void 0!==e?[...e,null]:ge}nextRetryDelayInMilliseconds(e){return this._retryDelays[e.previousRetryCount]}}class ye extends Error{constructor(e,t){const n=new.target.prototype;super(`${e}: Status code '${t}'`),this.statusCode=t,this.__proto__=n}}class we extends Error{constructor(e="A timeout occurred."){const t=new.target.prototype;super(e),this.__proto__=t}}class ve extends Error{constructor(e="An abort occurred."){const t=new.target.prototype;super(e),this.__proto__=t}}class be{constructor(e,t,n){this.statusCode=e,this.statusText=t,this.content=n}}class _e{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""}}var Ee,Se,Ce,Ie,ke;!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"}(Ee||(Ee={}));class Te extends _e{constructor(e){if(super(),this._logger=e,"undefined"==typeof fetch){const e=require;this._jar=new(e("tough-cookie").CookieJar),this._fetchType=e("node-fetch"),this._fetchType=e("fetch-cookie")(this._fetchType,this._jar),this._abortControllerType=e("abort-controller")}else this._fetchType=fetch.bind(self),this._abortControllerType=AbortController}async send(e){if(e.abortSignal&&e.abortSignal.aborted)throw new ve;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 ve});let r,o=null;if(e.timeout){const r=e.timeout;o=setTimeout((()=>{t.abort(),this._logger.log(Ee.Warning,"Timeout from HTTP request."),n=new we}),r)}try{r=await this._fetchType(e.url,{body:e.content,cache:"no-cache",credentials:!0===e.withCredentials?"include":"same-origin",headers:{"Content-Type":"text/plain;charset=UTF-8","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(Ee.Warning,`Error from HTTP request. ${e}.`),e}finally{o&&clearTimeout(o),e.abortSignal&&(e.abortSignal.onabort=null)}if(!r.ok){const e=await De(r,"text");throw new ye(e||r.statusText,r.status)}const i=De(r,e.responseType),s=await i;return new be(r.status,r.statusText,s)}getCookieString(e){return""}}function De(e,t){let n;switch(t){case"arraybuffer":n=e.arrayBuffer();break;case"text":n=e.text();break;case"blob":case"document":case"json":throw new Error(`${t} is not supported.`);default:n=e.text()}return n}class xe extends _e{constructor(e){super(),this._logger=e}send(e){return e.abortSignal&&e.abortSignal.aborted?Promise.reject(new ve):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"),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 ve)}),e.timeout&&(r.timeout=e.timeout),r.onload=()=>{e.abortSignal&&(e.abortSignal.onabort=null),r.status>=200&&r.status<300?t(new be(r.status,r.statusText,r.response||r.responseText)):n(new ye(r.response||r.responseText||r.statusText,r.status))},r.onerror=()=>{this._logger.log(Ee.Warning,`Error from HTTP request. ${r.status}: ${r.statusText}.`),n(new ye(r.statusText,r.status))},r.ontimeout=()=>{this._logger.log(Ee.Warning,"Timeout from HTTP request."),n(new we)},r.send(e.content||"")})):Promise.reject(new Error("No url defined.")):Promise.reject(new Error("No method defined."))}}class Re extends _e{constructor(e){if(super(),"undefined"!=typeof fetch)this._httpClient=new Te(e);else{if("undefined"==typeof XMLHttpRequest)throw new Error("No usable HttpClient found.");this._httpClient=new xe(e)}}send(e){return e.abortSignal&&e.abortSignal.aborted?Promise.reject(new ve):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)}}class Pe{}Pe.Authorization="Authorization",Pe.Cookie="Cookie",function(e){e[e.None=0]="None",e[e.WebSockets=1]="WebSockets",e[e.ServerSentEvents=2]="ServerSentEvents",e[e.LongPolling=4]="LongPolling"}(Se||(Se={})),function(e){e[e.Text=1]="Text",e[e.Binary=2]="Binary"}(Ce||(Ce={}));class Ue{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 Ae{constructor(){}log(e,t){}}Ae.instance=new Ae;class Ne{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 Be{static get isBrowser(){return"object"==typeof window}static get isWebWorker(){return"object"==typeof self&&"importScripts"in self}static get isNode(){return!this.isBrowser&&!this.isWebWorker}}function $e(e,t){let n="";return Le(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 Le(e){return e&&"undefined"!=typeof ArrayBuffer&&(e instanceof ArrayBuffer||e.constructor&&"ArrayBuffer"===e.constructor.name)}async function Me(e,t,n,r,o,i,s,a,c){let l={};if(o){const e=await o();e&&(l={Authorization:`Bearer ${e}`})}const[h,u]=Fe();l[h]=u,e.log(Ee.Trace,`(${t} transport) sending data. ${$e(i,s)}.`);const d=Le(i)?"arraybuffer":"text",p=await n.post(r,{content:i,headers:{...l,...c},responseType:d,withCredentials:a});e.log(Ee.Trace,`(${t} transport) request complete. Response status: ${p.statusCode}.`)}class Oe{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 He{constructor(e){this._minLevel=e,this.out=console}log(e,t){if(e>=this._minLevel){const n=`[${(new Date).toISOString()}] ${Ee[e]}: ${t}`;switch(e){case Ee.Critical:case Ee.Error:this.out.error(n);break;case Ee.Warning:this.out.warn(n);break;case Ee.Information:this.out.info(n);break;default:this.out.log(n)}}}}function Fe(){let e="X-SignalR-User-Agent";return Be.isNode&&(e="User-Agent"),[e,je("0.0.0-DEV_BUILD",We(),Be.isNode?"NodeJS":"Browser",ze())]}function je(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 We(){if(!Be.isNode)return"";switch(process.platform){case"win32":return"Windows NT";case"darwin":return"macOS";case"linux":return"Linux";default:return process.platform}}function ze(){if(Be.isNode)return process.versions.node}class qe{constructor(e,t,n,r,o,i){this._httpClient=e,this._accessTokenFactory=t,this._logger=n,this._pollAbort=new Ue,this._logMessageContent=r,this._withCredentials=o,this._headers=i,this._running=!1,this.onreceive=null,this.onclose=null}get pollAborted(){return this._pollAbort.aborted}async connect(e,t){if(Ne.isRequired(e,"url"),Ne.isRequired(t,"transferFormat"),Ne.isIn(t,Ce,"transferFormat"),this._url=e,this._logger.log(Ee.Trace,"(LongPolling transport) Connecting."),t===Ce.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]=Fe(),o={[n]:r,...this._headers},i={abortSignal:this._pollAbort.signal,headers:o,timeout:1e5,withCredentials:this._withCredentials};t===Ce.Binary&&(i.responseType="arraybuffer");const s=await this._getAccessToken();this._updateHeaderToken(i,s);const a=`${e}&_=${Date.now()}`;this._logger.log(Ee.Trace,`(LongPolling transport) polling: ${a}.`);const c=await this._httpClient.get(a,i);200!==c.statusCode?(this._logger.log(Ee.Error,`(LongPolling transport) Unexpected response code: ${c.statusCode}.`),this._closeError=new ye(c.statusText||"",c.statusCode),this._running=!1):this._running=!0,this._receiving=this._poll(this._url,i)}async _getAccessToken(){return this._accessTokenFactory?await this._accessTokenFactory():null}_updateHeaderToken(e,t){e.headers||(e.headers={}),t?e.headers[Pe.Authorization]=`Bearer ${t}`:e.headers[Pe.Authorization]&&delete e.headers[Pe.Authorization]}async _poll(e,t){try{for(;this._running;){const n=await this._getAccessToken();this._updateHeaderToken(t,n);try{const n=`${e}&_=${Date.now()}`;this._logger.log(Ee.Trace,`(LongPolling transport) polling: ${n}.`);const r=await this._httpClient.get(n,t);204===r.statusCode?(this._logger.log(Ee.Information,"(LongPolling transport) Poll terminated by server."),this._running=!1):200!==r.statusCode?(this._logger.log(Ee.Error,`(LongPolling transport) Unexpected response code: ${r.statusCode}.`),this._closeError=new ye(r.statusText||"",r.statusCode),this._running=!1):r.content?(this._logger.log(Ee.Trace,`(LongPolling transport) data received. ${$e(r.content,this._logMessageContent)}.`),this.onreceive&&this.onreceive(r.content)):this._logger.log(Ee.Trace,"(LongPolling transport) Poll timed out, reissuing.")}catch(e){this._running?e instanceof we?this._logger.log(Ee.Trace,"(LongPolling transport) Poll timed out, reissuing."):(this._closeError=e,this._running=!1):this._logger.log(Ee.Trace,`(LongPolling transport) Poll errored after shutdown: ${e.message}`)}}}finally{this._logger.log(Ee.Trace,"(LongPolling transport) Polling complete."),this.pollAborted||this._raiseOnClose()}}async send(e){return this._running?Me(this._logger,"LongPolling",this._httpClient,this._url,this._accessTokenFactory,e,this._logMessageContent,this._withCredentials,this._headers):Promise.reject(new Error("Cannot send until the transport is connected"))}async stop(){this._logger.log(Ee.Trace,"(LongPolling transport) Stopping polling."),this._running=!1,this._pollAbort.abort();try{await this._receiving,this._logger.log(Ee.Trace,`(LongPolling transport) sending DELETE request to ${this._url}.`);const e={},[t,n]=Fe();e[t]=n;const r={headers:{...e,...this._headers},withCredentials:this._withCredentials},o=await this._getAccessToken();this._updateHeaderToken(r,o),await this._httpClient.delete(this._url,r),this._logger.log(Ee.Trace,"(LongPolling transport) DELETE request sent.")}finally{this._logger.log(Ee.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(Ee.Trace,e),this.onclose(this._closeError)}}}class Je{constructor(e,t,n,r,o,i,s){this._httpClient=e,this._accessTokenFactory=t,this._logger=n,this._logMessageContent=r,this._withCredentials=i,this._eventSourceConstructor=o,this._headers=s,this.onreceive=null,this.onclose=null}async connect(e,t){if(Ne.isRequired(e,"url"),Ne.isRequired(t,"transferFormat"),Ne.isIn(t,Ce,"transferFormat"),this._logger.log(Ee.Trace,"(SSE transport) Connecting."),this._url=e,this._accessTokenFactory){const t=await this._accessTokenFactory();t&&(e+=(e.indexOf("?")<0?"?":"&")+`access_token=${encodeURIComponent(t)}`)}return new Promise(((n,r)=>{let o,i=!1;if(t===Ce.Text){if(Be.isBrowser||Be.isWebWorker)o=new this._eventSourceConstructor(e,{withCredentials:this._withCredentials});else{const t=this._httpClient.getCookieString(e),n={};n.Cookie=t;const[r,i]=Fe();n[r]=i,o=new this._eventSourceConstructor(e,{withCredentials:this._withCredentials,headers:{...n,...this._headers}})}try{o.onmessage=e=>{if(this.onreceive)try{this._logger.log(Ee.Trace,`(SSE transport) data received. ${$e(e.data,this._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(Ee.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?Me(this._logger,"SSE",this._httpClient,this._url,this._accessTokenFactory,e,this._logMessageContent,this._withCredentials,this._headers):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 Ke{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){if(Ne.isRequired(e,"url"),Ne.isRequired(t,"transferFormat"),Ne.isIn(t,Ce,"transferFormat"),this._logger.log(Ee.Trace,"(WebSockets transport) Connecting."),this._accessTokenFactory){const t=await this._accessTokenFactory();t&&(e+=(e.indexOf("?")<0?"?":"&")+`access_token=${encodeURIComponent(t)}`)}return new Promise(((n,r)=>{let o;e=e.replace(/^http/,"ws"),this._httpClient.getCookieString(e);let i=!1;o||(o=new this._webSocketConstructor(e)),t===Ce.Binary&&(o.binaryType="arraybuffer"),o.onopen=t=>{this._logger.log(Ee.Information,`WebSocket connected to ${e}.`),this._webSocket=o,i=!0,n()},o.onerror=e=>{let t=null;t="undefined"!=typeof ErrorEvent&&e instanceof ErrorEvent?e.error:"There was an error with the transport",this._logger.log(Ee.Information,`(WebSockets transport) ${t}.`)},o.onmessage=e=>{if(this._logger.log(Ee.Trace,`(WebSockets transport) data received. ${$e(e.data,this._logMessageContent)}.`),this.onreceive)try{this.onreceive(e.data)}catch(e){return void this._close(e)}},o.onclose=e=>{if(i)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(Ee.Trace,`(WebSockets transport) sending data. ${$e(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(Ee.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 Ve{constructor(e,t={}){var n;if(this._stopPromiseResolver=()=>{},this.features={},this._negotiateVersion=1,Ne.isRequired(e,"url"),this._logger=void 0===(n=t.logger)?new He(Ee.Information):null===n?Ae.instance:void 0!==n.log?n:new He(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,"undefined"==typeof WebSocket||t.WebSocket||(t.WebSocket=WebSocket),"undefined"==typeof EventSource||t.EventSource||(t.EventSource=EventSource),this._httpClient=t.httpClient||new Re(this._logger),this._connectionState="Disconnected",this._connectionStarted=!1,this._options=t,this.onreceive=null,this.onclose=null}async start(e){if(e=e||Ce.Binary,Ne.isIn(e,Ce,"transferFormat"),this._logger.log(Ee.Debug,`Starting connection with transfer format '${Ce[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(Ee.Error,e),await this._stopPromise,Promise.reject(new Error(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(Ee.Error,e),Promise.reject(new Error(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 Xe(this.transport)),this._sendQueue.send(e))}async stop(e){return"Disconnected"===this._connectionState?(this._logger.log(Ee.Debug,`Call to HttpConnection.stop(${e}) ignored because the connection is already in the disconnected state.`),Promise.resolve()):"Disconnecting"===this._connectionState?(this._logger.log(Ee.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(Ee.Error,`HttpConnection.transport.stop() threw error '${e}'.`),this._stopConnection()}this.transport=void 0}else this._logger.log(Ee.Debug,"HttpConnection.transport is undefined in HttpConnection.stop() because start() failed.")}async _startInternal(e){let t=this.baseUrl;this._accessTokenFactory=this._options.accessTokenFactory;try{if(this._options.skipNegotiation){if(this._options.transport!==Se.WebSockets)throw new Error("Negotiation can only be skipped when using the WebSocket transport directly.");this.transport=this._constructTransport(Se.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 Error("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}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 qe&&(this.features.inherentKeepAlive=!0),"Connecting"===this._connectionState&&(this._logger.log(Ee.Debug,"The HttpConnection connected successfully."),this._connectionState="Connected")}catch(e){return this._logger.log(Ee.Error,"Failed to start the connection: "+e),this._connectionState="Disconnected",this.transport=void 0,this._stopPromiseResolver(),Promise.reject(e)}}async _getNegotiationResponse(e){const t={};if(this._accessTokenFactory){const e=await this._accessTokenFactory();e&&(t[Pe.Authorization]=`Bearer ${e}`)}const[n,r]=Fe();t[n]=r;const o=this._resolveNegotiateUrl(e);this._logger.log(Ee.Debug,`Sending negotiation request: ${o}.`);try{const e=await this._httpClient.post(o,{content:"",headers:{...t,...this._options.headers},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 ye&&404===e.statusCode&&(t+=" Either this is not a SignalR endpoint or there is a proxy blocking the connection."),this._logger.log(Ee.Error,t),Promise.reject(new Error(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(Ee.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: ${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(Ee.Error,`Failed to start the transport '${n.transport}': ${e}`),a=void 0,i.push(`${n.transport} failed: ${e}`),"Connecting"!==this._connectionState){const e="Failed to select transport before stop() was called.";return this._logger.log(Ee.Debug,e),Promise.reject(new Error(e))}}}}return i.length>0?Promise.reject(new Error(`Unable to connect to the server with any of the available transports. ${i.join(" ")}`)):Promise.reject(new Error("None of the transports supported by the client are supported by the server."))}_constructTransport(e){switch(e){case Se.WebSockets:if(!this._options.WebSocket)throw new Error("'WebSocket' is not supported in your environment.");return new Ke(this._httpClient,this._accessTokenFactory,this._logger,this._options.logMessageContent||!1,this._options.WebSocket,this._options.headers||{});case Se.ServerSentEvents:if(!this._options.EventSource)throw new Error("'EventSource' is not supported in your environment.");return new Je(this._httpClient,this._accessTokenFactory,this._logger,this._options.logMessageContent||!1,this._options.EventSource,this._options.withCredentials,this._options.headers||{});case Se.LongPolling:return new qe(this._httpClient,this._accessTokenFactory,this._logger,this._options.logMessageContent||!1,this._options.withCredentials,this._options.headers||{});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=Se[e.transport];if(null==r)return this._logger.log(Ee.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(Ee.Debug,`Skipping transport '${Se[r]}' because it was disabled by the client.`),new Error(`'${Se[r]}' is disabled by the client.`);if(!(e.transferFormats.map((e=>Ce[e])).indexOf(n)>=0))return this._logger.log(Ee.Debug,`Skipping transport '${Se[r]}' because it does not support the requested transfer format '${Ce[n]}'.`),new Error(`'${Se[r]}' does not support ${Ce[n]}.`);if(r===Se.WebSockets&&!this._options.WebSocket||r===Se.ServerSentEvents&&!this._options.EventSource)return this._logger.log(Ee.Debug,`Skipping transport '${Se[r]}' because it is not supported in your environment.'`),new Error(`'${Se[r]}' is not supported in your environment.`);this._logger.log(Ee.Debug,`Selecting transport '${Se[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(Ee.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(Ee.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(Ee.Error,`Connection disconnected with error '${e}'.`):this._logger.log(Ee.Information,"Connection disconnected."),this._sendQueue&&(this._sendQueue.stop().catch((e=>{this._logger.log(Ee.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(Ee.Error,`HttpConnection.onclose(${e}) threw error '${t}'.`)}}}else this._logger.log(Ee.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(!Be.isBrowser||!window.document)throw new Error(`Cannot resolve '${e}'.`);const t=window.document.createElement("a");return t.href=e,this._logger.log(Ee.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 Xe{constructor(e){this._transport=e,this._buffer=[],this._executing=!0,this._sendBufferedData=new Ye,this._transportResult=new Ye,this._sendLoopPromise=this._sendLoop()}send(e){return this._bufferData(e),this._transportResult||(this._transportResult=new Ye),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 Ye;const e=this._transportResult;this._transportResult=void 0;const t="string"==typeof this._buffer[0]?this._buffer.join(""):Xe._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 Ye{constructor(){this.promise=new Promise(((e,t)=>[this._resolver,this._rejecter]=[e,t]))}resolve(){this._resolver()}reject(e){this._rejecter(e)}}class Ge{static write(e){return`${e}${Ge.RecordSeparator}`}static parse(e){if(e[e.length-1]!==Ge.RecordSeparator)throw new Error("Message is incomplete.");const t=e.split(Ge.RecordSeparator);return t.pop(),t}}Ge.RecordSeparatorCode=30,Ge.RecordSeparator=String.fromCharCode(Ge.RecordSeparatorCode);class Qe{writeHandshakeRequest(e){return Ge.write(JSON.stringify(e))}parseHandshakeResponse(e){let t,n;if(Le(e)){const r=new Uint8Array(e),o=r.indexOf(Ge.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(Ge.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=Ge.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"}(Ie||(Ie={}));class Ze{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 Oe(this,e)}}!function(e){e.Disconnected="Disconnected",e.Connecting="Connecting",e.Connected="Connected",e.Disconnecting="Disconnecting",e.Reconnecting="Reconnecting"}(ke||(ke={}));class et{constructor(e,t,n,r){this._nextKeepAlive=0,Ne.isRequired(e,"connection"),Ne.isRequired(t,"logger"),Ne.isRequired(n,"protocol"),this.serverTimeoutInMilliseconds=3e4,this.keepAliveIntervalInMilliseconds=15e3,this._logger=t,this._protocol=n,this.connection=e,this._reconnectPolicy=r,this._handshakeProtocol=new Qe,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=ke.Disconnected,this._connectionStarted=!1,this._cachedPingMessage=this._protocol.writeMessage({type:Ie.Ping})}static create(e,t,n,r){return new et(e,t,n,r)}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!==ke.Disconnected&&this._connectionState!==ke.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!==ke.Disconnected)return Promise.reject(new Error("Cannot start a HubConnection that is not in the 'Disconnected' state."));this._connectionState=ke.Connecting,this._logger.log(Ee.Debug,"Starting HubConnection.");try{await this._startInternal(),this._connectionState=ke.Connected,this._connectionStarted=!0,this._logger.log(Ee.Debug,"HubConnection connected successfully.")}catch(e){return this._connectionState=ke.Disconnected,this._logger.log(Ee.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(Ee.Debug,"Sending handshake request."),await this._sendMessage(this._handshakeProtocol.writeHandshakeRequest(t)),this._logger.log(Ee.Information,`Using HubProtocol '${this._protocol.name}'.`),this._cleanupTimeout(),this._resetTimeoutPeriod(),this._resetKeepAliveInterval(),await e,this._stopDuringStartError)throw this._stopDuringStartError}catch(e){throw this._logger.log(Ee.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){return this._connectionState===ke.Disconnected?(this._logger.log(Ee.Debug,`Call to HubConnection.stop(${e}) ignored because it is already in the disconnected state.`),Promise.resolve()):this._connectionState===ke.Disconnecting?(this._logger.log(Ee.Debug,`Call to HttpConnection.stop(${e}) ignored because the connection is already in the disconnecting state.`),this._stopPromise):(this._connectionState=ke.Disconnecting,this._logger.log(Ee.Debug,"Stopping HubConnection."),this._reconnectDelayHandle?(this._logger.log(Ee.Debug,"Connection stopped during reconnect delay. Done reconnecting."),clearTimeout(this._reconnectDelayHandle),this._reconnectDelayHandle=void 0,this._completeClose(),Promise.resolve()):(this._cleanupTimeout(),this._cleanupPingTimer(),this._stopDuringStartError=e||new Error("The connection was stopped before the hub handshake could complete."),this.connection.stop(e)))}stream(e,...t){const[n,r]=this._replaceStreamingParams(t),o=this._createStreamInvocation(e,t,r);let i;const s=new Ze;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===Ie.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===Ie.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 Ie.Invocation:this._invokeClientMethod(e);break;case Ie.StreamItem:case Ie.Completion:{const t=this._callbacks[e.invocationId];t&&(e.type===Ie.Completion&&delete this._callbacks[e.invocationId],t(e));break}case Ie.Ping:break;case Ie.Close:{this._logger.log(Ee.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(Ee.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(Ee.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(Ee.Error,e);const n=new Error(e);throw this._handshakeRejecter(n),n}return this._logger.log(Ee.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===ke.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."))}_invokeClientMethod(e){const t=this._methods[e.target.toLowerCase()];if(t){try{t.forEach((t=>t.apply(this,e.arguments)))}catch(t){this._logger.log(Ee.Error,`A callback for the method ${e.target.toLowerCase()} threw error '${t}'.`)}if(e.invocationId){const e="Server requested a response, which is not supported in this version of the client.";this._logger.log(Ee.Error,e),this._stopPromise=this._stopInternal(new Error(e))}}else this._logger.log(Ee.Warning,`No client method with the name '${e.target}' found.`)}_connectionClosed(e){this._logger.log(Ee.Debug,`HubConnection.connectionClosed(${e}) called while in state ${this._connectionState}.`),this._stopDuringStartError=this._stopDuringStartError||e||new Error("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===ke.Disconnecting?this._completeClose(e):this._connectionState===ke.Connected&&this._reconnectPolicy?this._reconnect(e):this._connectionState===ke.Connected&&this._completeClose(e)}_completeClose(e){if(this._connectionStarted){this._connectionState=ke.Disconnected,this._connectionStarted=!1;try{this._closedCallbacks.forEach((t=>t.apply(this,[e])))}catch(t){this._logger.log(Ee.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(Ee.Debug,"Connection not reconnecting because the IRetryPolicy returned null on the first reconnect attempt."),void this._completeClose(e);if(this._connectionState=ke.Reconnecting,e?this._logger.log(Ee.Information,`Connection reconnecting because of error '${e}'.`):this._logger.log(Ee.Information,"Connection reconnecting."),0!==this._reconnectingCallbacks.length){try{this._reconnectingCallbacks.forEach((t=>t.apply(this,[e])))}catch(t){this._logger.log(Ee.Error,`An onreconnecting callback called with error '${e}' threw error '${t}'.`)}if(this._connectionState!==ke.Reconnecting)return void this._logger.log(Ee.Debug,"Connection left the reconnecting state in onreconnecting callback. Done reconnecting.")}for(;null!==o;){if(this._logger.log(Ee.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!==ke.Reconnecting)return void this._logger.log(Ee.Debug,"Connection left the reconnecting state during reconnect delay. Done reconnecting.");try{if(await this._startInternal(),this._connectionState=ke.Connected,this._logger.log(Ee.Information,"HubConnection reconnected successfully."),0!==this._reconnectedCallbacks.length)try{this._reconnectedCallbacks.forEach((e=>e.apply(this,[this.connection.connectionId])))}catch(e){this._logger.log(Ee.Error,`An onreconnected callback called with connectionId '${this.connection.connectionId}; threw error '${e}'.`)}return}catch(e){if(this._logger.log(Ee.Information,`Reconnect attempt failed because of error '${e}'.`),this._connectionState!==ke.Reconnecting)return this._logger.log(Ee.Debug,`Connection moved to the '${this._connectionState}' from the reconnecting state during reconnect attempt. Done reconnecting.`),void(this._connectionState===ke.Disconnecting&&this._completeClose());r=e instanceof Error?e:new Error(e.toString()),o=this._getNextRetryDelay(n++,Date.now()-t,r)}}this._logger.log(Ee.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(Ee.Error,`IRetryPolicy.nextRetryDelayInMilliseconds(${e}, ${t}) threw error '${n}'.`),null}}_cancelCallbacksWithError(e){const t=this._callbacks;this._callbacks={},Object.keys(t).forEach((n=>{(0,t[n])(null,e)}))}_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:Ie.Invocation}:{arguments:t,target:e,type:Ie.Invocation};{const n=this._invocationId;return this._invocationId++,0!==r.length?{arguments:t,invocationId:n.toString(),streamIds:r,target:e,type:Ie.Invocation}:{arguments:t,invocationId:n.toString(),target:e,type:Ie.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 ut=ot?new TextDecoder:null,dt=ot?"undefined"!=typeof process&&"force"!==process.env.TEXT_DECODER?200:0:it,pt=function(e,t){this.type=e,this.data=t};function ft(e,t,n){var r=Math.floor(n/4294967296),o=n;e.setUint32(t,r),e.setUint32(t+4,o)}function gt(e,t){return 4294967296*e.getInt32(t)+e.getUint32(t+4)}var mt={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),ft(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:gt(t,4),nsec:t.getUint32(0)};default:throw new Error("Unrecognized data size for timestamp: "+e.length)}}(e);return new Date(1e3*t.sec+t.nsec/1e6)}},yt=function(){function e(){this.builtInEncoders=[],this.builtInDecoders=[],this.encoders=[],this.decoders=[],this.register(mt)}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 "+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: "+e+" bytes in UTF-8");this.writeU8(219),this.writeU32(e)}},e.prototype.encodeString=function(e){if(e.length>ct){var t=st(e);this.ensureBufferSizeToWrite(5+t),this.writeStringHeader(t),lt(e,this.bytes,this.pos),this.pos+=t}else t=st(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: "+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: "+t);this.writeU8(198),this.writeU32(t)}var n=wt(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: "+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=ht(e,t,n),i=Uint8Array.prototype.slice.call(e,t,t+n);return this.store(i,o),o},e}(),St=(_t=function(e,t){return(_t=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])})(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}_t(e,t),e.prototype=null===t?Object.create(t):(n.prototype=t.prototype,new n)}),Ct=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]1||a(e,t)}))})}function a(e,t){try{(n=o[e](t)).value instanceof kt?Promise.resolve(n.value.v).then(c,l):h(i[0][2],n)}catch(e){h(i[0][3],e)}var n}function c(e){a("next",e)}function l(e){a("throw",e)}function h(e,t){e(t),i.shift(),i.length&&a(i[0][0],i[0][1])}},Dt=new DataView(new ArrayBuffer(0)),xt=new Uint8Array(Dt.buffer),Rt=function(){try{Dt.getInt8(0)}catch(e){return e.constructor}throw new Error("never reached")}(),Pt=new Rt("Insufficient data"),Ut=4294967295,At=new Et,Nt=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 St(t,e),t}(Error),Bt=function(){function e(e,t,n,r,o,i,s,a){void 0===e&&(e=yt.defaultCodec),void 0===t&&(t=void 0),void 0===n&&(n=Ut),void 0===r&&(r=Ut),void 0===o&&(o=Ut),void 0===i&&(i=Ut),void 0===s&&(s=Ut),void 0===a&&(a=At),this.extensionCodec=e,this.context=t,this.maxStrLength=n,this.maxBinLength=r,this.maxArrayLength=o,this.maxMapLength=i,this.maxExtLength=s,this.keyDecoder=a,this.totalPos=0,this.pos=0,this.view=Dt,this.bytes=xt,this.headByte=-1,this.stack=[]}return e.prototype.reinitializeState=function(){this.totalPos=0,this.headByte=-1,this.stack.length=0},e.prototype.setBuffer=function(e){this.bytes=wt(e),this.view=function(e){if(e instanceof ArrayBuffer)return new DataView(e);var t=wt(e);return new DataView(t.buffer,t.byteOffset,t.byteLength)}(this.bytes),this.pos=0},e.prototype.appendBuffer=function(e){if(-1!==this.headByte||this.hasRemaining()){var t=this.bytes.subarray(this.pos),n=wt(e),r=new Uint8Array(t.length+n.length);r.set(t),r.set(n,t.length),this.setBuffer(r)}else this.setBuffer(e)},e.prototype.hasRemaining=function(e){return void 0===e&&(e=1),this.view.byteLength-this.pos>=e},e.prototype.createExtraByteError=function(e){var t=this.view,n=this.pos;return new RangeError("Extra "+(t.byteLength-n)+" of "+t.byteLength+" byte(s) found at buffer["+e+"]")},e.prototype.decode=function(e){this.reinitializeState(),this.setBuffer(e);var t=this.doDecodeSync();if(this.hasRemaining())throw this.createExtraByteError(this.pos);return t},e.prototype.decodeMulti=function(e){return Ct(this,(function(t){switch(t.label){case 0:this.reinitializeState(),this.setBuffer(e),t.label=1;case 1:return this.hasRemaining()?[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,u,d;return Ct(this,(function(p){switch(p.label){case 0:i=!1,p.label=1;case 1:p.trys.push([1,6,7,12]),t=It(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 Rt))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())throw this.createExtraByteError(this.totalPos);return[2,s]}throw h=(l=this).headByte,u=l.pos,d=l.totalPos,new RangeError("Insufficient data in parsing "+bt(h)+" at "+d+" ("+u+" 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 Tt(this,arguments,(function(){var n,r,o,i,s,a,c,l,h;return Ct(this,(function(u){switch(u.label){case 0:n=t,r=-1,u.label=1;case 1:u.trys.push([1,13,14,19]),o=It(e),u.label=2;case 2:return[4,kt(o.next())];case 3:if((i=u.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()),u.label=4;case 4:u.trys.push([4,9,,10]),u.label=5;case 5:return[4,kt(this.doDecodeSync())];case 6:return[4,u.sent()];case 7:return u.sent(),0==--r?[3,8]:[3,5];case 8:return[3,10];case 9:if(!((a=u.sent())instanceof Rt))throw a;return[3,10];case 10:this.totalPos+=this.pos,u.label=11;case 11:return[3,2];case 12:return[3,19];case 13:return c=u.sent(),l={error:c},[3,19];case 14:return u.trys.push([14,,17,18]),i&&!i.done&&(h=o.return)?[4,kt(h.call(o))]:[3,16];case 15:u.sent(),u.label=16;case 16:return[3,18];case 17:if(l)throw l.error;return[7];case 18:return[7];case 19:return[2]}}))}))},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 Nt("Unrecognized type byte: "+bt(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 Nt("The type of key must be string or number but "+typeof t);if("__proto__"===t)throw new Nt("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 Nt("Unrecognized array type byte: "+bt(e))}},e.prototype.pushMapState=function(e){if(e>this.maxMapLength)throw new Nt("Max length exceeded: map length ("+e+") > maxMapLengthLength ("+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 Nt("Max length exceeded: array length ("+e+") > maxArrayLength ("+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 Nt("Max length exceeded: UTF-8 byte length ("+e+") > maxStrLength ("+this.maxStrLength+")");if(this.bytes.byteLengthdt?function(e,t,n){var r=e.subarray(t,t+n);return ut.decode(r)}(this.bytes,o,e):ht(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 Nt("Max length exceeded: bin length ("+e+") > maxBinLength ("+this.maxBinLength+")");if(!this.hasRemaining(e+t))throw Pt;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 Nt("Max length exceeded: ext length ("+e+") > maxExtLength ("+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=gt(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 $t{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 Lt=new Uint8Array([145,Ie.Ping]);class Mt{constructor(e){this.name="messagepack",this.version=1,this.transferFormat=Ce.Binary,this._errorResult=1,this._voidResult=2,this._nonVoidResult=3,e=e||{},this._encoder=new vt(e.extensionCodec,e.context,e.maxDepth,e.initialBufferSize,e.sortKeys,e.forceFloat32,e.ignoreUndefined,e.forceIntegerToFloat),this._decoder=new Bt(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=Ae.instance);const r=$t.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 Ie.Invocation:return this._writeInvocation(e);case Ie.StreamInvocation:return this._writeStreamInvocation(e);case Ie.StreamItem:return this._writeStreamItem(e);case Ie.Completion:return this._writeCompletion(e);case Ie.Ping:return $t.write(Lt);case Ie.CancelInvocation:return this._writeCancelInvocation(e);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 Ie.Invocation:return this._createInvocationMessage(this._readHeaders(n),n);case Ie.StreamItem:return this._createStreamItemMessage(this._readHeaders(n),n);case Ie.Completion:return this._createCompletionMessage(this._readHeaders(n),n);case Ie.Ping:return this._createPingMessage(n);case Ie.Close:return this._createCloseMessage(n);default:return t.log(Ee.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:Ie.Close}}_createPingMessage(e){if(e.length<1)throw new Error("Invalid payload for Ping message.");return{type:Ie.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:Ie.Invocation}:{arguments:t[4],headers:e,streamIds:[],target:t[3],type:Ie.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:Ie.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:Ie.Completion}}_writeInvocation(e){let t;return t=e.streamIds?this._encoder.encode([Ie.Invocation,e.headers||{},e.invocationId||null,e.target,e.arguments,e.streamIds]):this._encoder.encode([Ie.Invocation,e.headers||{},e.invocationId||null,e.target,e.arguments]),$t.write(t.slice())}_writeStreamInvocation(e){let t;return t=e.streamIds?this._encoder.encode([Ie.StreamInvocation,e.headers||{},e.invocationId,e.target,e.arguments,e.streamIds]):this._encoder.encode([Ie.StreamInvocation,e.headers||{},e.invocationId,e.target,e.arguments]),$t.write(t.slice())}_writeStreamItem(e){const t=this._encoder.encode([Ie.StreamItem,e.headers||{},e.invocationId,e.item]);return $t.write(t.slice())}_writeCompletion(e){const t=e.error?this._errorResult:e.result?this._nonVoidResult:this._voidResult;let n;switch(t){case this._errorResult:n=this._encoder.encode([Ie.Completion,e.headers||{},e.invocationId,t,e.error]);break;case this._voidResult:n=this._encoder.encode([Ie.Completion,e.headers||{},e.invocationId,t]);break;case this._nonVoidResult:n=this._encoder.encode([Ie.Completion,e.headers||{},e.invocationId,t,e.result])}return $t.write(n.slice())}_writeCancelInvocation(e){const t=this._encoder.encode([Ie.CancelInvocation,e.headers||{},e.invocationId]);return $t.write(t.slice())}_readHeaders(e){const t=e[1];if("object"!=typeof t)throw new Error("Invalid headers.");return t}}let Ot=!1;const Ht="function"==typeof TextDecoder?new TextDecoder("utf-8"):null,Ft=Ht?Ht.decode.bind(Ht):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("")},jt=Math.pow(2,32),Wt=Math.pow(2,21)-1;function zt(e,t){return e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24}function qt(e,t){return e[t]+(e[t+1]<<8)+(e[t+2]<<16)+(e[t+3]<<24>>>0)}function Jt(e,t){const n=qt(e,t+4);if(n>Wt)throw new Error(`Cannot read uint64 with high order part ${n}, because the result would exceed Number.MAX_SAFE_INTEGER.`);return n*jt+qt(e,t)}class Kt{constructor(e){this.batchData=e;const t=new Gt(e);this.arrayRangeReader=new Qt(e),this.arrayBuilderSegmentReader=new Zt(e),this.diffReader=new Vt(e),this.editReader=new Xt(e,t),this.frameReader=new Yt(e,t)}updatedComponents(){return zt(this.batchData,this.batchData.length-20)}referenceFrames(){return zt(this.batchData,this.batchData.length-16)}disposedComponentIds(){return zt(this.batchData,this.batchData.length-12)}disposedEventHandlerIds(){return zt(this.batchData,this.batchData.length-8)}updatedComponentsEntry(e,t){const n=e+4*t;return zt(this.batchData,n)}referenceFramesEntry(e,t){return e+20*t}disposedComponentIdsEntry(e,t){const n=e+4*t;return zt(this.batchData,n)}disposedEventHandlerIdsEntry(e,t){const n=e+8*t;return Jt(this.batchData,n)}}class Vt{constructor(e){this.batchDataUint8=e}componentId(e){return zt(this.batchDataUint8,e)}edits(e){return e+4}editsEntry(e,t){return e+16*t}}class Xt{constructor(e,t){this.batchDataUint8=e,this.stringReader=t}editType(e){return zt(this.batchDataUint8,e)}siblingIndex(e){return zt(this.batchDataUint8,e+4)}newTreeIndex(e){return zt(this.batchDataUint8,e+8)}moveToSiblingIndex(e){return zt(this.batchDataUint8,e+8)}removedAttributeName(e){const t=zt(this.batchDataUint8,e+12);return this.stringReader.readString(t)}}class Yt{constructor(e,t){this.batchDataUint8=e,this.stringReader=t}frameType(e){return zt(this.batchDataUint8,e)}subtreeLength(e){return zt(this.batchDataUint8,e+4)}elementReferenceCaptureId(e){const t=zt(this.batchDataUint8,e+4);return this.stringReader.readString(t)}componentId(e){return zt(this.batchDataUint8,e+8)}elementName(e){const t=zt(this.batchDataUint8,e+8);return this.stringReader.readString(t)}textContent(e){const t=zt(this.batchDataUint8,e+4);return this.stringReader.readString(t)}markupContent(e){const t=zt(this.batchDataUint8,e+4);return this.stringReader.readString(t)}attributeName(e){const t=zt(this.batchDataUint8,e+4);return this.stringReader.readString(t)}attributeValue(e){const t=zt(this.batchDataUint8,e+8);return this.stringReader.readString(t)}attributeEventHandlerId(e){return Jt(this.batchDataUint8,e+12)}}class Gt{constructor(e){this.batchDataUint8=e,this.stringTableStartIndex=zt(e,e.length-4)}readString(e){if(-1===e)return null;{const n=zt(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(en.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(en.Debug,`Waiting for batch ${this.nextBatchId}. Batch ${e} not processed.`);try{this.nextBatchId++,this.logger.log(en.Debug,`Applying batch ${e}.`),function(e,t){const n=Q[e];if(!n)throw new Error(`There is no browser renderer with ID ${e}.`);const r=t.arrayRangeReader,o=t.updatedComponents(),i=r.values(o),s=r.count(o),a=t.referenceFrames(),c=r.values(a),l=t.diffReader;for(let e=0;e=this.minLevel){const n=`[${(new Date).toISOString()}] ${en[e]}: ${t}`;switch(e){case en.Critical:case en.Error:console.error(n);break;case en.Warning:console.warn(n);break;case en.Information:console.info(n);break;default:console.log(n)}}}}class on{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!==ke.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!==ke.Connected)return!1;const t=await e.invoke("StartCircuit",re.getBaseURI(),re.getLocationHref(),JSON.stringify(this.components.map((e=>e.toRecord()))),this.applicationState||"");return!!t&&(this.initialize(t),!0)}resolveElement(e){const t=Number.parseInt(e);if(Number.isNaN(t))throw new Error(`Invalid sequence number '${e}'.`);return function(e,t){if(!e.parentNode)throw new Error(`Comment not connected to the DOM ${e.textContent}`);const n=e.parentNode,r=k(n,!0),o=A(r);return Array.from(n.childNodes).forEach((e=>o.push(e))),e[C]=r,t&&(e[I]=t,k(t)),k(e)}(this.components[t].start,this.components[t].end)}}const sn={configureSignalR:e=>{},logLevel:en.Warning,reconnectionOptions:{maxRetries:8,retryIntervalMilliseconds:2e4,dialogId:"components-reconnect-modal"}};class an{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.modal.innerHTML='

Alternatively, reload

',this.message=this.modal.querySelector("h5"),this.button=this.modal.querySelector("button"),this.reloadParagraph=this.modal.querySelector("p"),this.loader=this.getLoader(),this.message.after(this.loader),this.button.addEventListener("click",(async()=>{this.show();try{await(null==fe?void 0:fe.reconnect)()||this.rejected()}catch(e){this.logger.log(en.Error,e),this.failed()}})),this.reloadParagraph.querySelector("a").addEventListener("click",(()=>location.reload()))}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",this.message.innerHTML="Reconnection failed. Try reloading the page if you're unable to reconnect.",this.message.querySelector("a").addEventListener("click",(()=>location.reload()))}rejected(){this.button.style.display="none",this.reloadParagraph.style.display="none",this.loader.style.display="none",this.message.innerHTML="Could not reconnect to the server. Reload the page to restore functionality.",this.message.querySelector("a").addEventListener("click",(()=>location.reload()))}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 cn{constructor(e,t,n){this.dialog=e,this.maxRetries=t,this.document=n,this.document=n;const r=this.document.getElementById(cn.MaxRetriesId);r&&(r.innerText=this.maxRetries.toString())}show(){this.removeClasses(),this.dialog.classList.add(cn.ShowClassName)}update(e){const t=this.document.getElementById(cn.CurrentAttemptId);t&&(t.innerText=e.toString())}hide(){this.removeClasses(),this.dialog.classList.add(cn.HideClassName)}failed(){this.removeClasses(),this.dialog.classList.add(cn.FailedClassName)}rejected(){this.removeClasses(),this.dialog.classList.add(cn.RejectedClassName)}removeClasses(){this.dialog.classList.remove(cn.ShowClassName,cn.HideClassName,cn.FailedClassName,cn.RejectedClassName)}}cn.ShowClassName="components-reconnect-show",cn.HideClassName="components-reconnect-hide",cn.FailedClassName="components-reconnect-failed",cn.RejectedClassName="components-reconnect-rejected",cn.MaxRetriesId="components-reconnect-max-retries",cn.CurrentAttemptId="components-reconnect-current-attempt";class ln{constructor(e,t,n){this._currentReconnectionProcess=null,this._logger=e,this._reconnectionDisplay=t,this._reconnectCallback=n||(()=>fe.reconnect())}onConnectionDown(e,t){if(!this._reconnectionDisplay){const t=document.getElementById(e.dialogId);this._reconnectionDisplay=t?new cn(t,e.maxRetries,document):new an(e.dialogId,e.maxRetries,document,this._logger)}this._currentReconnectionProcess||(this._currentReconnectionProcess=new hn(e,this._logger,this._reconnectCallback,this._reconnectionDisplay))}onConnectionUp(){this._currentReconnectionProcess&&(this._currentReconnectionProcess.dispose(),this._currentReconnectionProcess=null)}}class hn{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;thn.MaximumFirstRetryInterval?hn.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(en.Error,e)}}this.reconnectDisplay.failed()}delay(e){return new Promise((t=>setTimeout(t,e)))}}hn.MaximumFirstRetryInterval=3e3;const un=/^\s*Blazor-Component-State:(?[a-zA-Z0-9\+\/=]+)$/;function dn(e){var t;if(e.nodeType===Node.COMMENT_NODE){const n=e.textContent||"",r=un.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 gn(e,t){const n=e.currentElement;if(n&&n.nodeType===Node.COMMENT_NODE&&n.textContent){const r=fn.exec(n.textContent),o=r&&r.groups&&r.groups.descriptor;if(!o)return;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;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.");if(c){const e=mn(c,n);if(!e)throw new Error(`Could not find an end component comment for '${t}'`);return{type:r,assembly:o,typeName:i,parameterDefinitions:s&&atob(s),parameterValues:a&&atob(a),start:t,prerenderId:c,end:e}}return{type:r,assembly:o,typeName:i,parameterDefinitions:s&&atob(s),parameterValues:a&&atob(a),start:t}}}(r,n,e);case"server":return function(e,t,n){const{type:r,descriptor:o,sequence:i,prerenderId:s}=e;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)}'`);if(s){const e=mn(s,n);if(!e)throw new Error(`Could not find an end component comment for '${t}'`);return{type:r,sequence:i,descriptor:o,start:t,prerenderId:s,end:e}}return{type:r,sequence:i,descriptor:o,start:t}}}(r,n,e)}}catch(e){throw new Error(`Found malformed component comment at ${n.textContent}`)}}}function mn(e,t){for(;t.next()&&t.currentElement;){const n=t.currentElement;if(n.nodeType!==Node.COMMENT_NODE)continue;if(!n.textContent)continue;const r=fn.exec(n.textContent),o=r&&r[1];if(o)return yn(o,e),n}}function yn(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 wn{constructor(e){this.childNodes=e,this.currentIndex=-1,this.length=e.length}next(){return this.currentIndex++,this.currentIndexe.sequence-t.sequence))}(e)}(document),o=dn(document),i=new on(r,o||""),s=await Tn(t,n,i);if(!await i.startCircuit(s))return void n.log(en.Error,"Failed to start the circuit.");let a=!1;const c=()=>{if(!a){const e=new FormData,t=i.circuitId;e.append("circuitId",t),a=navigator.sendBeacon("_blazor/disconnect",e)}};fe.disconnect=c,window.addEventListener("unload",c,{capture:!1,once:!0}),fe.reconnect=async e=>{if(Cn)return!1;const r=e||await Tn(t,n,i);return await i.reconnect(r)?(t.reconnectionHandler.onConnectionUp(),!0):(n.log(en.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)},n.log(en.Information,"Blazor server-side application started.")}async function Tn(t,n,r){const i=new Mt;i.name="blazorpack";const s=(new rt).withUrl("_blazor").withHubProtocol(i);t.configureSignalR(s);const a=s.build();o=(e,t)=>{a.send("DispatchBrowserEvent",JSON.stringify(e),JSON.stringify(t))},fe._internal.navigationManager.listenForNavigationEvents(((e,t)=>a.send("OnLocationChanged",e,t))),a.on("JS.AttachComponent",((e,t)=>function(e,t,n){let r=Q[0];r||(r=Q[0]=new V(0)),r.attachRootComponentToLogicalElement(n,t)}(0,r.resolveElement(t),e))),a.on("JS.BeginInvokeJS",e.jsCallDispatcher.beginInvokeJSFromDotNet),a.on("JS.EndInvokeDotNet",e.jsCallDispatcher.endInvokeDotNetFromJS),a.on("JS.ReceiveByteArray",e.jsCallDispatcher.receiveByteArray);const c=tn.getOrCreate(n);a.on("JS.RenderBatch",((e,t)=>{n.log(en.Debug,`Received render batch with id ${e} and ${t.byteLength} bytes.`),c.processBatch(e,t,a)})),a.onclose((e=>!Cn&&t.reconnectionHandler.onConnectionDown(t.reconnectionOptions,e))),a.on("JS.Error",(e=>{Cn=!0,Dn(a,e,n),async function(){let e=document.querySelector("#blazor-error-ui");e&&(e.style.display="block"),Ot||(Ot=!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()}})))}()})),fe._internal.forceCloseConnection=()=>a.stop(),fe._internal.sendJSDataStream=(e,t,n)=>{setTimeout((async()=>{let r=5,o=(new Date).valueOf();try{const i=n-512;if(i<=0)throw new Error("The chunk size must be greater than 0.");let s=0;for(;s1)await a.send("ReceiveJSDataChunk",t,c,null);else{if(!await a.invoke("ReceiveJSDataChunk",t,c,null))break;const e=(new Date).valueOf(),n=e-o;o=e,r=Math.max(1,Math.round(500/n))}s+=n}}catch(e){await a.send("ReceiveJSDataChunk",t,null,e.toString())}}),0)};try{await a.start()}catch(e){Dn(a,e,n)}return e.attachDispatcher({beginInvokeDotNetFromJS:(e,t,n,r,o)=>{a.send("BeginInvokeDotNetFromJS",e?e.toString():null,t,n,r||0,o)},endInvokeJSFromDotNet:(e,t,n)=>{a.send("EndInvokeJSFromDotNet",e,t,n)},sendByteArray:(e,t)=>{a.send("ReceiveByteArray",e,t)}}),a}function Dn(e,t,n){n.log(en.Error,t),e&&e.stop()}fe.start=kn,document&&document.currentScript&&"false"!==document.currentScript.getAttribute("autostart")&&kn()})(); \ No newline at end of file +(()=>{"use strict";var e,t,n;!function(e){window.DotNet=e;const t=[],n=new Map;class r{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 o="__jsObjectId",i={},s={0:new r(window)};s[0]._cachedFunctions.set("import",(e=>("string"==typeof e&&e.startsWith("./")&&(e=document.baseURI+e.substr(2)),import(e))));let a,c=1,l=1,h=null;function u(e){t.push(e)}function d(e){if(e&&"object"==typeof e){s[l]=new r(e);const t={[o]:l};return l++,t}throw new Error(`Cannot create a JSObjectReference from the value '${e}'.`)}function p(e){if(!(e.buffer instanceof ArrayBuffer))throw new Error(`Cannot create a JSDataReference from the value '${e}' as it is not a valid ArrayBuffer.`);if(void 0===e.byteLength)throw new Error(`Cannot create a JSDataReference from the value '${e}' as it doesn't have a byteLength.`);const t={__jsDataReferenceLength:e.byteLength};try{const n=d(e);t.__jsObjectId=n.__jsObjectId}catch{throw new Error(`Cannot create a JSStreamReference from the value '${e}'.`)}return t}function f(e){return e?JSON.parse(e,((e,n)=>t.reduce(((t,n)=>n(e,t)),n))):null}function g(e,t,n,r){const o=y();if(o.invokeDotNetFromJS){const i=k(r),s=o.invokeDotNetFromJS(e,t,n,i);return s?f(s):null}throw new Error("The current dispatcher does not support synchronous calls from JS to .NET. Use invokeMethodAsync instead.")}function m(e,t,n,r){if(e&&n)throw new Error(`For instance method calls, assemblyName should be null. Received '${e}'.`);const o=c++,s=new Promise(((e,t)=>{i[o]={resolve:e,reject:t}}));try{const i=k(r);y().beginInvokeDotNetFromJS(o,e,t,n,i)}catch(e){w(o,!1,e)}return s}function y(){if(null!==h)return h;throw new Error("No .NET call dispatcher has been set.")}function w(e,t,n){if(!i.hasOwnProperty(e))throw new Error(`There is no pending async call with ID ${e}.`);const r=i[e];delete i[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){let n=s[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 s[e]}e.attachDispatcher=function(e){h=e},e.attachReviver=u,e.invokeMethod=function(e,t,...n){return g(e,t,null,n)},e.invokeMethodAsync=function(e,t,...n){return m(e,t,null,n)},e.createJSObjectReference=d,e.createJSDataReference=p,e.disposeJSObjectReference=function(e){const t=e&&e.__jsObjectId;"number"==typeof t&&_(t)},function(e){e[e.Default=0]="Default",e[e.JSObjectReference=1]="JSObjectReference",e[e.JSDataReference=2]="JSDataReference"}(a=e.JSCallResultType||(e.JSCallResultType={})),e.jsCallDispatcher={findJSFunction:b,disposeJSObjectReferenceById:_,invokeJSFromDotNet:(e,t,n,r)=>{const o=C(b(e,r).apply(null,f(t)),n);return null==o?null:k(o)},beginInvokeJSFromDotNet:(e,t,n,r,o)=>{const i=new Promise((e=>{e(b(t,o).apply(null,f(n)))}));e&&i.then((t=>y().endInvokeJSFromDotNet(e,!0,k([e,!0,C(t,r)]))),(t=>y().endInvokeJSFromDotNet(e,!1,JSON.stringify([e,!1,v(t)]))))},endInvokeDotNetFromJS:(e,t,n)=>{const r=t?f(n):new Error(n);w(parseInt(e),t,r)},receiveByteArray:(e,t)=>{n.set(e,t)}};class E{constructor(e){this._id=e}invokeMethod(e,...t){return g(null,e,this._id,t)}invokeMethodAsync(e,...t){return m(null,e,this._id,t)}dispose(){m(null,"__Dispose",this._id,null).catch((e=>console.error(e)))}serializeAsArg(){return{__dotNetObject:this._id}}}const S="__byte[]";function C(e,t){switch(t){case a.Default:return e;case a.JSObjectReference:return d(e);case a.JSDataReference:return p(e);default:throw new Error(`Invalid JS call result type '${t}'.`)}}u((function(e,t){if(t&&"object"==typeof t){if(t.hasOwnProperty("__dotNetObject"))return new E(t.__dotNetObject);if(t.hasOwnProperty(o)){const e=t.__jsObjectId,n=s[e];if(n)return n.getWrappedObject();throw new Error(`JS object instance with Id '${e}' does not exist. It may have been disposed.`)}if(t.hasOwnProperty(S)){const e=t["__byte[]"],r=n.get(e);if(void 0===r)throw new Error(`Byte array index '${e}' does not exist.`);return r}}return t}));let I=0;function k(e){return I=0,JSON.stringify(e,T)}function T(e,t){if(t instanceof E)return t.serializeAsArg();if(t instanceof Uint8Array){h.sendByteArray(I,t);const e={[S]:I};return I++,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"}(n||(n={}));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}}let o;function i(e,t){if(!o)throw new Error("eventDispatcher not initialized. Call 'setEventDispatcher' to configure it.");o(e,t)}const s=new Map,a=new Map,c={createEventArgs:()=>({})},l=[];function h(e){return s.get(e)}function u(e){const t=s.get(e);return(null==t?void 0:t.browserEventName)||e}function d(e,t){e.forEach((e=>s.set(e,t)))}function p(e){const t=[];for(let n=0;n{return{...f(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}}),d(["focus","blur","focusin","focusout"],c),d(["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};var t}}),d(["contextmenu","click","mouseover","mouseout","mousemove","mousedown","mouseup","dblclick"],{createEventArgs:e=>f(e)}),d(["error"],{createEventArgs:e=>{return{message:(t=e).message,filename:t.filename,lineno:t.lineno,colno:t.colno};var t}}),d(["loadstart","timeout","abort","load","loadend","progress"],{createEventArgs:e=>{return{lengthComputable:(t=e).lengthComputable,loaded:t.loaded,total:t.total};var t}}),d(["touchcancel","touchend","touchmove","touchenter","touchleave","touchstart"],{createEventArgs:e=>{return{detail:(t=e).detail,touches:p(t.touches),targetTouches:p(t.targetTouches),changedTouches:p(t.changedTouches),ctrlKey:t.ctrlKey,shiftKey:t.shiftKey,altKey:t.altKey,metaKey:t.metaKey,type:t.type};var t}}),d(["gotpointercapture","lostpointercapture","pointercancel","pointerdown","pointerenter","pointerleave","pointermove","pointerout","pointerover","pointerup"],{createEventArgs:e=>{return{...f(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}}),d(["wheel","mousewheel"],{createEventArgs:e=>{return{...f(t=e),deltaX:t.deltaX,deltaY:t.deltaY,deltaZ:t.deltaZ,deltaMode:t.deltaMode};var t}}),d(["toggle"],c);const g=["date","datetime-local","month","time","week"],m=E(["abort","blur","change","error","focus","load","loadend","loadstart","mouseenter","mouseleave","progress","reset","scroll","submit","unload","toggle","DOMNodeInsertedIntoDocument","DOMNodeRemovedFromDocument"]),y={submit:!0},w=E(["click","dblclick","mousedown","mousemove","mouseup"]);class v{constructor(e){this.browserRendererId=e,this.afterClickCallbacks=[];const t=++v.nextEventDelegatorId;this.eventsCollectionKey=`_blazorEvents_${t}`,this.eventInfoStore=new b(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,a.get(n));var n;t&&t.forEach((t=>this.dispatchGlobalEventToAllElements(t,e))),"click"===e.type&&this.afterClickCallbacks.forEach((t=>t(e)))}dispatchGlobalEventToAllElements(e,t){let n=t.target,o=null,s=!1;const a=m.hasOwnProperty(e);let c=!1;for(;n;){const d=this.getEventHandlerInfosForElement(n,!1);if(d){const a=d.getHandler(e);if(a&&(l=n,u=t.type,!((l instanceof HTMLButtonElement||l instanceof HTMLInputElement||l instanceof HTMLTextAreaElement||l instanceof HTMLSelectElement)&&w.hasOwnProperty(u)&&l.disabled))){if(!s){const n=h(e);o=(null==n?void 0:n.createEventArgs)?n.createEventArgs(t):{},s=!0}y.hasOwnProperty(t.type)&&t.preventDefault(),i({browserRendererId:this.browserRendererId,eventHandlerId:a.eventHandlerId,eventName:e,eventFieldInfo:r.fromEvent(a.renderingComponentId,t)},o)}d.stopPropagation(e)&&(c=!0),d.preventDefault(e)&&t.preventDefault()}n=a||c?null:n.parentElement}var l,u}getEventHandlerInfosForElement(e,t){return e.hasOwnProperty(this.eventsCollectionKey)?e[this.eventsCollectionKey]:t?e[this.eventsCollectionKey]=new _:null}}v.nextEventDelegatorId=0;class b{constructor(e){this.globalListener=e,this.infosByEventHandlerId={},this.countByEventName={},l.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=u(e),this.countByEventName.hasOwnProperty(e))this.countByEventName[e]++;else{this.countByEventName[e]=1;const t=m.hasOwnProperty(e);document.addEventListener(e,this.globalListener,t)}}update(e,t){if(this.infosByEventHandlerId.hasOwnProperty(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=u(t.eventName);0==--this.countByEventName[n]&&(delete this.countByEventName[n],document.removeEventListener(n,this.globalListener))}return t}handleEventNameAliasAdded(e,t){if(this.countByEventName.hasOwnProperty(e)){const n=this.countByEventName[e];delete this.countByEventName[e],document.removeEventListener(e,this.globalListener),this.addGlobalListener(t),this.countByEventName[t]+=n-1}}}class _{constructor(){this.handlers={},this.preventDefaultFlags=null,this.stopPropagationFlags=null}getHandler(e){return this.handlers.hasOwnProperty(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 E(e){const t={};return e.forEach((e=>{t[e]=!0})),t}const S=O("_blazorLogicalChildren"),C=O("_blazorLogicalParent"),I=O("_blazorLogicalEnd");function k(e,t){if(e.childNodes.length>0&&!t)throw new Error("New logical elements must start empty, or allowExistingContents must be true");return S in e||(e[S]=[]),e}function T(e,t){const n=document.createComment("!");return D(n,e,t),n}function D(e,t,n){const r=e;if(e instanceof Comment&&A(r)&&A(r).length>0)throw new Error("Not implemented: inserting non-empty logical container");if(R(r))throw new Error("Not implemented: moving existing logical children");const o=A(t);if(n0;)x(n,0)}const r=n;r.parentNode.removeChild(r)}function R(e){return e[C]||null}function P(e,t){return A(e)[t]}function U(e){var t=B(e);return"http://www.w3.org/2000/svg"===t.namespaceURI&&"foreignObject"!==t.tagName}function A(e){return e[S]}function N(e,t){const n=A(e);t.forEach((e=>{e.moveRangeStart=n[e.fromSiblingIndex],e.moveRangeEnd=M(e.moveRangeStart)})),t.forEach((t=>{const r=t.moveToBeforeMarker=document.createComment("marker"),o=n[t.toSiblingIndex+1];o?o.parentNode.insertBefore(r,o):L(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 B(e){if(e instanceof Element)return e;if(e instanceof Comment)return e.parentNode;throw new Error("Not a valid logical element")}function $(e){const t=A(R(e));return t[Array.prototype.indexOf.call(t,e)+1]||null}function L(e,t){if(t instanceof Element)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=$(t);n?n.parentNode.insertBefore(e,n):L(e,R(t))}}}function M(e){if(e instanceof Element)return e;const t=$(e);if(t)return t.previousSibling;{const t=R(e);return t instanceof Element?t.lastChild:M(t)}}function O(e){return"function"==typeof Symbol?Symbol():e}function H(e){return`_bl_${e}`}e.attachReviver(((e,t)=>t&&"object"==typeof t&&t.hasOwnProperty("__internalId")&&"string"==typeof t.__internalId?function(e){const t=`[${H(e)}]`;return document.querySelector(t)}(t.__internalId):t));const F="_blazorSelectValue",j=document.createElement("template"),W=document.createElementNS("http://www.w3.org/2000/svg","g"),z={},q="__internal_",J="preventDefault_",K="stopPropagation_";class V{constructor(e){this.childComponentLocations={},this.eventDelegator=new v(e),this.eventDelegator.notifyAfterClick((e=>{if(!ee)return;if(0!==e.button||function(e){return e.ctrlKey||e.shiftKey||e.altKey||e.metaKey}(e))return;if(e.defaultPrevented)return;const t=function(e){const t=!window._blazorDisableComposedPath&&e.composedPath&&e.composedPath();if(t){for(let e=0;ese(!1))))},enableNavigationInterception:function(){ee=!0},navigateTo:oe,getBaseURI:()=>document.baseURI,getLocationHref:()=>location.href};function oe(e,t,n=!1){const r=ce(e);if(!t&&he(r))ie(r,!1,n);else if(t&&location.href===e){const t=e+"?";history.replaceState(null,"",t),location.replace(e)}else n?history.replaceState(null,"",r):location.href=e}function ie(e,t,n=!1){Z=!0,n?history.replaceState(null,"",e):history.pushState(null,"",e),se(t)}async function se(e){ne&&await ne(location.href,e)}let ae;function ce(e){return ae=ae||document.createElement("a"),ae.href=e,ae.href}function le(e,t){return e?e.tagName===t?e:le(e.parentElement,t):null}function he(e){const t=(n=document.baseURI).substr(0,n.lastIndexOf("/")+1);var n;return e.startsWith(t)}const ue={init:function(e,t,n,r=50){const o=pe(t);(o||document.documentElement).style.overflowAnchor="none";const i=new IntersectionObserver((function(r){r.forEach((r=>{var o;if(!r.isIntersecting)return;const i=t.getBoundingClientRect(),s=n.getBoundingClientRect().top-i.bottom,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`});i.observe(t),i.observe(n);const s=c(t),a=c(n);function c(e){const t=new MutationObserver((()=>{i.unobserve(e),i.observe(e)}));return t.observe(e,{attributes:!0}),t}de[e._id]={intersectionObserver:i,mutationObserverBefore:s,mutationObserverAfter:a}},dispose:function(e){const t=de[e._id];t&&(t.intersectionObserver.disconnect(),t.mutationObserverBefore.disconnect(),t.mutationObserverAfter.disconnect(),e.dispose(),delete de[e._id])}},de={};function pe(e){return e?"visible"!==getComputedStyle(e).overflowY?e:pe(e.parentElement):null}const fe={navigateTo:oe,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=a.get(t.browserEventName);n?n.push(e):a.set(t.browserEventName,[e]),l.forEach((n=>n(e,t.browserEventName)))}s.set(e,t)},_internal:{navigationManager:re,domWrapper:{focus:function(e,t){if(!(e instanceof HTMLElement))throw new Error("Unable to focus an invalid element.");e.focus({preventScroll:t})},focusBySelector:function(e){const t=document.querySelector(e);t&&(t.hasAttribute("tabindex")||(t.tabIndex=-1),t.focus())}},Virtualize:ue}};window.Blazor=fe;const ge=[0,2e3,1e4,3e4,null];class me{constructor(e){this._retryDelays=void 0!==e?[...e,null]:ge}nextRetryDelayInMilliseconds(e){return this._retryDelays[e.previousRetryCount]}}class ye extends Error{constructor(e,t){const n=new.target.prototype;super(`${e}: Status code '${t}'`),this.statusCode=t,this.__proto__=n}}class we extends Error{constructor(e="A timeout occurred."){const t=new.target.prototype;super(e),this.__proto__=t}}class ve extends Error{constructor(e="An abort occurred."){const t=new.target.prototype;super(e),this.__proto__=t}}class be{constructor(e,t,n){this.statusCode=e,this.statusText=t,this.content=n}}class _e{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""}}var Ee,Se,Ce,Ie,ke;!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"}(Ee||(Ee={}));class Te extends _e{constructor(e){if(super(),this._logger=e,"undefined"==typeof fetch){const e=require;this._jar=new(e("tough-cookie").CookieJar),this._fetchType=e("node-fetch"),this._fetchType=e("fetch-cookie")(this._fetchType,this._jar),this._abortControllerType=e("abort-controller")}else this._fetchType=fetch.bind(self),this._abortControllerType=AbortController}async send(e){if(e.abortSignal&&e.abortSignal.aborted)throw new ve;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 ve});let r,o=null;if(e.timeout){const r=e.timeout;o=setTimeout((()=>{t.abort(),this._logger.log(Ee.Warning,"Timeout from HTTP request."),n=new we}),r)}try{r=await this._fetchType(e.url,{body:e.content,cache:"no-cache",credentials:!0===e.withCredentials?"include":"same-origin",headers:{"Content-Type":"text/plain;charset=UTF-8","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(Ee.Warning,`Error from HTTP request. ${e}.`),e}finally{o&&clearTimeout(o),e.abortSignal&&(e.abortSignal.onabort=null)}if(!r.ok){const e=await De(r,"text");throw new ye(e||r.statusText,r.status)}const i=De(r,e.responseType),s=await i;return new be(r.status,r.statusText,s)}getCookieString(e){return""}}function De(e,t){let n;switch(t){case"arraybuffer":n=e.arrayBuffer();break;case"text":n=e.text();break;case"blob":case"document":case"json":throw new Error(`${t} is not supported.`);default:n=e.text()}return n}class xe extends _e{constructor(e){super(),this._logger=e}send(e){return e.abortSignal&&e.abortSignal.aborted?Promise.reject(new ve):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"),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 ve)}),e.timeout&&(r.timeout=e.timeout),r.onload=()=>{e.abortSignal&&(e.abortSignal.onabort=null),r.status>=200&&r.status<300?t(new be(r.status,r.statusText,r.response||r.responseText)):n(new ye(r.response||r.responseText||r.statusText,r.status))},r.onerror=()=>{this._logger.log(Ee.Warning,`Error from HTTP request. ${r.status}: ${r.statusText}.`),n(new ye(r.statusText,r.status))},r.ontimeout=()=>{this._logger.log(Ee.Warning,"Timeout from HTTP request."),n(new we)},r.send(e.content||"")})):Promise.reject(new Error("No url defined.")):Promise.reject(new Error("No method defined."))}}class Re extends _e{constructor(e){if(super(),"undefined"!=typeof fetch)this._httpClient=new Te(e);else{if("undefined"==typeof XMLHttpRequest)throw new Error("No usable HttpClient found.");this._httpClient=new xe(e)}}send(e){return e.abortSignal&&e.abortSignal.aborted?Promise.reject(new ve):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)}}class Pe{}Pe.Authorization="Authorization",Pe.Cookie="Cookie",function(e){e[e.None=0]="None",e[e.WebSockets=1]="WebSockets",e[e.ServerSentEvents=2]="ServerSentEvents",e[e.LongPolling=4]="LongPolling"}(Se||(Se={})),function(e){e[e.Text=1]="Text",e[e.Binary=2]="Binary"}(Ce||(Ce={}));class Ue{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 Ae{constructor(){}log(e,t){}}Ae.instance=new Ae;class Ne{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 Be{static get isBrowser(){return"object"==typeof window}static get isWebWorker(){return"object"==typeof self&&"importScripts"in self}static get isNode(){return!this.isBrowser&&!this.isWebWorker}}function $e(e,t){let n="";return Le(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 Le(e){return e&&"undefined"!=typeof ArrayBuffer&&(e instanceof ArrayBuffer||e.constructor&&"ArrayBuffer"===e.constructor.name)}async function Me(e,t,n,r,o,i,s,a,c){let l={};if(o){const e=await o();e&&(l={Authorization:`Bearer ${e}`})}const[h,u]=Fe();l[h]=u,e.log(Ee.Trace,`(${t} transport) sending data. ${$e(i,s)}.`);const d=Le(i)?"arraybuffer":"text",p=await n.post(r,{content:i,headers:{...l,...c},responseType:d,withCredentials:a});e.log(Ee.Trace,`(${t} transport) request complete. Response status: ${p.statusCode}.`)}class Oe{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 He{constructor(e){this._minLevel=e,this.out=console}log(e,t){if(e>=this._minLevel){const n=`[${(new Date).toISOString()}] ${Ee[e]}: ${t}`;switch(e){case Ee.Critical:case Ee.Error:this.out.error(n);break;case Ee.Warning:this.out.warn(n);break;case Ee.Information:this.out.info(n);break;default:this.out.log(n)}}}}function Fe(){let e="X-SignalR-User-Agent";return Be.isNode&&(e="User-Agent"),[e,je("0.0.0-DEV_BUILD",We(),Be.isNode?"NodeJS":"Browser",ze())]}function je(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 We(){if(!Be.isNode)return"";switch(process.platform){case"win32":return"Windows NT";case"darwin":return"macOS";case"linux":return"Linux";default:return process.platform}}function ze(){if(Be.isNode)return process.versions.node}class qe{constructor(e,t,n,r,o,i){this._httpClient=e,this._accessTokenFactory=t,this._logger=n,this._pollAbort=new Ue,this._logMessageContent=r,this._withCredentials=o,this._headers=i,this._running=!1,this.onreceive=null,this.onclose=null}get pollAborted(){return this._pollAbort.aborted}async connect(e,t){if(Ne.isRequired(e,"url"),Ne.isRequired(t,"transferFormat"),Ne.isIn(t,Ce,"transferFormat"),this._url=e,this._logger.log(Ee.Trace,"(LongPolling transport) Connecting."),t===Ce.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]=Fe(),o={[n]:r,...this._headers},i={abortSignal:this._pollAbort.signal,headers:o,timeout:1e5,withCredentials:this._withCredentials};t===Ce.Binary&&(i.responseType="arraybuffer");const s=await this._getAccessToken();this._updateHeaderToken(i,s);const a=`${e}&_=${Date.now()}`;this._logger.log(Ee.Trace,`(LongPolling transport) polling: ${a}.`);const c=await this._httpClient.get(a,i);200!==c.statusCode?(this._logger.log(Ee.Error,`(LongPolling transport) Unexpected response code: ${c.statusCode}.`),this._closeError=new ye(c.statusText||"",c.statusCode),this._running=!1):this._running=!0,this._receiving=this._poll(this._url,i)}async _getAccessToken(){return this._accessTokenFactory?await this._accessTokenFactory():null}_updateHeaderToken(e,t){e.headers||(e.headers={}),t?e.headers[Pe.Authorization]=`Bearer ${t}`:e.headers[Pe.Authorization]&&delete e.headers[Pe.Authorization]}async _poll(e,t){try{for(;this._running;){const n=await this._getAccessToken();this._updateHeaderToken(t,n);try{const n=`${e}&_=${Date.now()}`;this._logger.log(Ee.Trace,`(LongPolling transport) polling: ${n}.`);const r=await this._httpClient.get(n,t);204===r.statusCode?(this._logger.log(Ee.Information,"(LongPolling transport) Poll terminated by server."),this._running=!1):200!==r.statusCode?(this._logger.log(Ee.Error,`(LongPolling transport) Unexpected response code: ${r.statusCode}.`),this._closeError=new ye(r.statusText||"",r.statusCode),this._running=!1):r.content?(this._logger.log(Ee.Trace,`(LongPolling transport) data received. ${$e(r.content,this._logMessageContent)}.`),this.onreceive&&this.onreceive(r.content)):this._logger.log(Ee.Trace,"(LongPolling transport) Poll timed out, reissuing.")}catch(e){this._running?e instanceof we?this._logger.log(Ee.Trace,"(LongPolling transport) Poll timed out, reissuing."):(this._closeError=e,this._running=!1):this._logger.log(Ee.Trace,`(LongPolling transport) Poll errored after shutdown: ${e.message}`)}}}finally{this._logger.log(Ee.Trace,"(LongPolling transport) Polling complete."),this.pollAborted||this._raiseOnClose()}}async send(e){return this._running?Me(this._logger,"LongPolling",this._httpClient,this._url,this._accessTokenFactory,e,this._logMessageContent,this._withCredentials,this._headers):Promise.reject(new Error("Cannot send until the transport is connected"))}async stop(){this._logger.log(Ee.Trace,"(LongPolling transport) Stopping polling."),this._running=!1,this._pollAbort.abort();try{await this._receiving,this._logger.log(Ee.Trace,`(LongPolling transport) sending DELETE request to ${this._url}.`);const e={},[t,n]=Fe();e[t]=n;const r={headers:{...e,...this._headers},withCredentials:this._withCredentials},o=await this._getAccessToken();this._updateHeaderToken(r,o),await this._httpClient.delete(this._url,r),this._logger.log(Ee.Trace,"(LongPolling transport) DELETE request sent.")}finally{this._logger.log(Ee.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(Ee.Trace,e),this.onclose(this._closeError)}}}class Je{constructor(e,t,n,r,o,i,s){this._httpClient=e,this._accessTokenFactory=t,this._logger=n,this._logMessageContent=r,this._withCredentials=i,this._eventSourceConstructor=o,this._headers=s,this.onreceive=null,this.onclose=null}async connect(e,t){if(Ne.isRequired(e,"url"),Ne.isRequired(t,"transferFormat"),Ne.isIn(t,Ce,"transferFormat"),this._logger.log(Ee.Trace,"(SSE transport) Connecting."),this._url=e,this._accessTokenFactory){const t=await this._accessTokenFactory();t&&(e+=(e.indexOf("?")<0?"?":"&")+`access_token=${encodeURIComponent(t)}`)}return new Promise(((n,r)=>{let o,i=!1;if(t===Ce.Text){if(Be.isBrowser||Be.isWebWorker)o=new this._eventSourceConstructor(e,{withCredentials:this._withCredentials});else{const t=this._httpClient.getCookieString(e),n={};n.Cookie=t;const[r,i]=Fe();n[r]=i,o=new this._eventSourceConstructor(e,{withCredentials:this._withCredentials,headers:{...n,...this._headers}})}try{o.onmessage=e=>{if(this.onreceive)try{this._logger.log(Ee.Trace,`(SSE transport) data received. ${$e(e.data,this._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(Ee.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?Me(this._logger,"SSE",this._httpClient,this._url,this._accessTokenFactory,e,this._logMessageContent,this._withCredentials,this._headers):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 Ke{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){if(Ne.isRequired(e,"url"),Ne.isRequired(t,"transferFormat"),Ne.isIn(t,Ce,"transferFormat"),this._logger.log(Ee.Trace,"(WebSockets transport) Connecting."),this._accessTokenFactory){const t=await this._accessTokenFactory();t&&(e+=(e.indexOf("?")<0?"?":"&")+`access_token=${encodeURIComponent(t)}`)}return new Promise(((n,r)=>{let o;e=e.replace(/^http/,"ws"),this._httpClient.getCookieString(e);let i=!1;o||(o=new this._webSocketConstructor(e)),t===Ce.Binary&&(o.binaryType="arraybuffer"),o.onopen=t=>{this._logger.log(Ee.Information,`WebSocket connected to ${e}.`),this._webSocket=o,i=!0,n()},o.onerror=e=>{let t=null;t="undefined"!=typeof ErrorEvent&&e instanceof ErrorEvent?e.error:"There was an error with the transport",this._logger.log(Ee.Information,`(WebSockets transport) ${t}.`)},o.onmessage=e=>{if(this._logger.log(Ee.Trace,`(WebSockets transport) data received. ${$e(e.data,this._logMessageContent)}.`),this.onreceive)try{this.onreceive(e.data)}catch(e){return void this._close(e)}},o.onclose=e=>{if(i)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(Ee.Trace,`(WebSockets transport) sending data. ${$e(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(Ee.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 Ve{constructor(e,t={}){var n;if(this._stopPromiseResolver=()=>{},this.features={},this._negotiateVersion=1,Ne.isRequired(e,"url"),this._logger=void 0===(n=t.logger)?new He(Ee.Information):null===n?Ae.instance:void 0!==n.log?n:new He(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,"undefined"==typeof WebSocket||t.WebSocket||(t.WebSocket=WebSocket),"undefined"==typeof EventSource||t.EventSource||(t.EventSource=EventSource),this._httpClient=t.httpClient||new Re(this._logger),this._connectionState="Disconnected",this._connectionStarted=!1,this._options=t,this.onreceive=null,this.onclose=null}async start(e){if(e=e||Ce.Binary,Ne.isIn(e,Ce,"transferFormat"),this._logger.log(Ee.Debug,`Starting connection with transfer format '${Ce[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(Ee.Error,e),await this._stopPromise,Promise.reject(new Error(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(Ee.Error,e),Promise.reject(new Error(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 Xe(this.transport)),this._sendQueue.send(e))}async stop(e){return"Disconnected"===this._connectionState?(this._logger.log(Ee.Debug,`Call to HttpConnection.stop(${e}) ignored because the connection is already in the disconnected state.`),Promise.resolve()):"Disconnecting"===this._connectionState?(this._logger.log(Ee.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(Ee.Error,`HttpConnection.transport.stop() threw error '${e}'.`),this._stopConnection()}this.transport=void 0}else this._logger.log(Ee.Debug,"HttpConnection.transport is undefined in HttpConnection.stop() because start() failed.")}async _startInternal(e){let t=this.baseUrl;this._accessTokenFactory=this._options.accessTokenFactory;try{if(this._options.skipNegotiation){if(this._options.transport!==Se.WebSockets)throw new Error("Negotiation can only be skipped when using the WebSocket transport directly.");this.transport=this._constructTransport(Se.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 Error("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}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 qe&&(this.features.inherentKeepAlive=!0),"Connecting"===this._connectionState&&(this._logger.log(Ee.Debug,"The HttpConnection connected successfully."),this._connectionState="Connected")}catch(e){return this._logger.log(Ee.Error,"Failed to start the connection: "+e),this._connectionState="Disconnected",this.transport=void 0,this._stopPromiseResolver(),Promise.reject(e)}}async _getNegotiationResponse(e){const t={};if(this._accessTokenFactory){const e=await this._accessTokenFactory();e&&(t[Pe.Authorization]=`Bearer ${e}`)}const[n,r]=Fe();t[n]=r;const o=this._resolveNegotiateUrl(e);this._logger.log(Ee.Debug,`Sending negotiation request: ${o}.`);try{const e=await this._httpClient.post(o,{content:"",headers:{...t,...this._options.headers},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 ye&&404===e.statusCode&&(t+=" Either this is not a SignalR endpoint or there is a proxy blocking the connection."),this._logger.log(Ee.Error,t),Promise.reject(new Error(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(Ee.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: ${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(Ee.Error,`Failed to start the transport '${n.transport}': ${e}`),a=void 0,i.push(`${n.transport} failed: ${e}`),"Connecting"!==this._connectionState){const e="Failed to select transport before stop() was called.";return this._logger.log(Ee.Debug,e),Promise.reject(new Error(e))}}}}return i.length>0?Promise.reject(new Error(`Unable to connect to the server with any of the available transports. ${i.join(" ")}`)):Promise.reject(new Error("None of the transports supported by the client are supported by the server."))}_constructTransport(e){switch(e){case Se.WebSockets:if(!this._options.WebSocket)throw new Error("'WebSocket' is not supported in your environment.");return new Ke(this._httpClient,this._accessTokenFactory,this._logger,this._options.logMessageContent||!1,this._options.WebSocket,this._options.headers||{});case Se.ServerSentEvents:if(!this._options.EventSource)throw new Error("'EventSource' is not supported in your environment.");return new Je(this._httpClient,this._accessTokenFactory,this._logger,this._options.logMessageContent||!1,this._options.EventSource,this._options.withCredentials,this._options.headers||{});case Se.LongPolling:return new qe(this._httpClient,this._accessTokenFactory,this._logger,this._options.logMessageContent||!1,this._options.withCredentials,this._options.headers||{});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=Se[e.transport];if(null==r)return this._logger.log(Ee.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(Ee.Debug,`Skipping transport '${Se[r]}' because it was disabled by the client.`),new Error(`'${Se[r]}' is disabled by the client.`);if(!(e.transferFormats.map((e=>Ce[e])).indexOf(n)>=0))return this._logger.log(Ee.Debug,`Skipping transport '${Se[r]}' because it does not support the requested transfer format '${Ce[n]}'.`),new Error(`'${Se[r]}' does not support ${Ce[n]}.`);if(r===Se.WebSockets&&!this._options.WebSocket||r===Se.ServerSentEvents&&!this._options.EventSource)return this._logger.log(Ee.Debug,`Skipping transport '${Se[r]}' because it is not supported in your environment.'`),new Error(`'${Se[r]}' is not supported in your environment.`);this._logger.log(Ee.Debug,`Selecting transport '${Se[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(Ee.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(Ee.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(Ee.Error,`Connection disconnected with error '${e}'.`):this._logger.log(Ee.Information,"Connection disconnected."),this._sendQueue&&(this._sendQueue.stop().catch((e=>{this._logger.log(Ee.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(Ee.Error,`HttpConnection.onclose(${e}) threw error '${t}'.`)}}}else this._logger.log(Ee.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(!Be.isBrowser||!window.document)throw new Error(`Cannot resolve '${e}'.`);const t=window.document.createElement("a");return t.href=e,this._logger.log(Ee.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 Xe{constructor(e){this._transport=e,this._buffer=[],this._executing=!0,this._sendBufferedData=new Ye,this._transportResult=new Ye,this._sendLoopPromise=this._sendLoop()}send(e){return this._bufferData(e),this._transportResult||(this._transportResult=new Ye),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 Ye;const e=this._transportResult;this._transportResult=void 0;const t="string"==typeof this._buffer[0]?this._buffer.join(""):Xe._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 Ye{constructor(){this.promise=new Promise(((e,t)=>[this._resolver,this._rejecter]=[e,t]))}resolve(){this._resolver()}reject(e){this._rejecter(e)}}class Ge{static write(e){return`${e}${Ge.RecordSeparator}`}static parse(e){if(e[e.length-1]!==Ge.RecordSeparator)throw new Error("Message is incomplete.");const t=e.split(Ge.RecordSeparator);return t.pop(),t}}Ge.RecordSeparatorCode=30,Ge.RecordSeparator=String.fromCharCode(Ge.RecordSeparatorCode);class Qe{writeHandshakeRequest(e){return Ge.write(JSON.stringify(e))}parseHandshakeResponse(e){let t,n;if(Le(e)){const r=new Uint8Array(e),o=r.indexOf(Ge.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(Ge.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=Ge.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"}(Ie||(Ie={}));class Ze{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 Oe(this,e)}}!function(e){e.Disconnected="Disconnected",e.Connecting="Connecting",e.Connected="Connected",e.Disconnecting="Disconnecting",e.Reconnecting="Reconnecting"}(ke||(ke={}));class et{constructor(e,t,n,r){this._nextKeepAlive=0,Ne.isRequired(e,"connection"),Ne.isRequired(t,"logger"),Ne.isRequired(n,"protocol"),this.serverTimeoutInMilliseconds=3e4,this.keepAliveIntervalInMilliseconds=15e3,this._logger=t,this._protocol=n,this.connection=e,this._reconnectPolicy=r,this._handshakeProtocol=new Qe,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=ke.Disconnected,this._connectionStarted=!1,this._cachedPingMessage=this._protocol.writeMessage({type:Ie.Ping})}static create(e,t,n,r){return new et(e,t,n,r)}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!==ke.Disconnected&&this._connectionState!==ke.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!==ke.Disconnected)return Promise.reject(new Error("Cannot start a HubConnection that is not in the 'Disconnected' state."));this._connectionState=ke.Connecting,this._logger.log(Ee.Debug,"Starting HubConnection.");try{await this._startInternal(),this._connectionState=ke.Connected,this._connectionStarted=!0,this._logger.log(Ee.Debug,"HubConnection connected successfully.")}catch(e){return this._connectionState=ke.Disconnected,this._logger.log(Ee.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(Ee.Debug,"Sending handshake request."),await this._sendMessage(this._handshakeProtocol.writeHandshakeRequest(t)),this._logger.log(Ee.Information,`Using HubProtocol '${this._protocol.name}'.`),this._cleanupTimeout(),this._resetTimeoutPeriod(),this._resetKeepAliveInterval(),await e,this._stopDuringStartError)throw this._stopDuringStartError}catch(e){throw this._logger.log(Ee.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){return this._connectionState===ke.Disconnected?(this._logger.log(Ee.Debug,`Call to HubConnection.stop(${e}) ignored because it is already in the disconnected state.`),Promise.resolve()):this._connectionState===ke.Disconnecting?(this._logger.log(Ee.Debug,`Call to HttpConnection.stop(${e}) ignored because the connection is already in the disconnecting state.`),this._stopPromise):(this._connectionState=ke.Disconnecting,this._logger.log(Ee.Debug,"Stopping HubConnection."),this._reconnectDelayHandle?(this._logger.log(Ee.Debug,"Connection stopped during reconnect delay. Done reconnecting."),clearTimeout(this._reconnectDelayHandle),this._reconnectDelayHandle=void 0,this._completeClose(),Promise.resolve()):(this._cleanupTimeout(),this._cleanupPingTimer(),this._stopDuringStartError=e||new Error("The connection was stopped before the hub handshake could complete."),this.connection.stop(e)))}stream(e,...t){const[n,r]=this._replaceStreamingParams(t),o=this._createStreamInvocation(e,t,r);let i;const s=new Ze;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===Ie.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===Ie.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 Ie.Invocation:this._invokeClientMethod(e);break;case Ie.StreamItem:case Ie.Completion:{const t=this._callbacks[e.invocationId];t&&(e.type===Ie.Completion&&delete this._callbacks[e.invocationId],t(e));break}case Ie.Ping:break;case Ie.Close:{this._logger.log(Ee.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(Ee.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(Ee.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(Ee.Error,e);const n=new Error(e);throw this._handshakeRejecter(n),n}return this._logger.log(Ee.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===ke.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."))}_invokeClientMethod(e){const t=this._methods[e.target.toLowerCase()];if(t){try{t.forEach((t=>t.apply(this,e.arguments)))}catch(t){this._logger.log(Ee.Error,`A callback for the method ${e.target.toLowerCase()} threw error '${t}'.`)}if(e.invocationId){const e="Server requested a response, which is not supported in this version of the client.";this._logger.log(Ee.Error,e),this._stopPromise=this._stopInternal(new Error(e))}}else this._logger.log(Ee.Warning,`No client method with the name '${e.target}' found.`)}_connectionClosed(e){this._logger.log(Ee.Debug,`HubConnection.connectionClosed(${e}) called while in state ${this._connectionState}.`),this._stopDuringStartError=this._stopDuringStartError||e||new Error("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===ke.Disconnecting?this._completeClose(e):this._connectionState===ke.Connected&&this._reconnectPolicy?this._reconnect(e):this._connectionState===ke.Connected&&this._completeClose(e)}_completeClose(e){if(this._connectionStarted){this._connectionState=ke.Disconnected,this._connectionStarted=!1;try{this._closedCallbacks.forEach((t=>t.apply(this,[e])))}catch(t){this._logger.log(Ee.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(Ee.Debug,"Connection not reconnecting because the IRetryPolicy returned null on the first reconnect attempt."),void this._completeClose(e);if(this._connectionState=ke.Reconnecting,e?this._logger.log(Ee.Information,`Connection reconnecting because of error '${e}'.`):this._logger.log(Ee.Information,"Connection reconnecting."),0!==this._reconnectingCallbacks.length){try{this._reconnectingCallbacks.forEach((t=>t.apply(this,[e])))}catch(t){this._logger.log(Ee.Error,`An onreconnecting callback called with error '${e}' threw error '${t}'.`)}if(this._connectionState!==ke.Reconnecting)return void this._logger.log(Ee.Debug,"Connection left the reconnecting state in onreconnecting callback. Done reconnecting.")}for(;null!==o;){if(this._logger.log(Ee.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!==ke.Reconnecting)return void this._logger.log(Ee.Debug,"Connection left the reconnecting state during reconnect delay. Done reconnecting.");try{if(await this._startInternal(),this._connectionState=ke.Connected,this._logger.log(Ee.Information,"HubConnection reconnected successfully."),0!==this._reconnectedCallbacks.length)try{this._reconnectedCallbacks.forEach((e=>e.apply(this,[this.connection.connectionId])))}catch(e){this._logger.log(Ee.Error,`An onreconnected callback called with connectionId '${this.connection.connectionId}; threw error '${e}'.`)}return}catch(e){if(this._logger.log(Ee.Information,`Reconnect attempt failed because of error '${e}'.`),this._connectionState!==ke.Reconnecting)return this._logger.log(Ee.Debug,`Connection moved to the '${this._connectionState}' from the reconnecting state during reconnect attempt. Done reconnecting.`),void(this._connectionState===ke.Disconnecting&&this._completeClose());r=e instanceof Error?e:new Error(e.toString()),o=this._getNextRetryDelay(n++,Date.now()-t,r)}}this._logger.log(Ee.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(Ee.Error,`IRetryPolicy.nextRetryDelayInMilliseconds(${e}, ${t}) threw error '${n}'.`),null}}_cancelCallbacksWithError(e){const t=this._callbacks;this._callbacks={},Object.keys(t).forEach((n=>{(0,t[n])(null,e)}))}_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:Ie.Invocation}:{arguments:t,target:e,type:Ie.Invocation};{const n=this._invocationId;return this._invocationId++,0!==r.length?{arguments:t,invocationId:n.toString(),streamIds:r,target:e,type:Ie.Invocation}:{arguments:t,invocationId:n.toString(),target:e,type:Ie.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 ut=ot?new TextDecoder:null,dt=ot?"undefined"!=typeof process&&"force"!==process.env.TEXT_DECODER?200:0:it,pt=function(e,t){this.type=e,this.data=t};function ft(e,t,n){var r=Math.floor(n/4294967296),o=n;e.setUint32(t,r),e.setUint32(t+4,o)}function gt(e,t){return 4294967296*e.getInt32(t)+e.getUint32(t+4)}var mt={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),ft(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:gt(t,4),nsec:t.getUint32(0)};default:throw new Error("Unrecognized data size for timestamp: "+e.length)}}(e);return new Date(1e3*t.sec+t.nsec/1e6)}},yt=function(){function e(){this.builtInEncoders=[],this.builtInDecoders=[],this.encoders=[],this.decoders=[],this.register(mt)}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 "+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: "+e+" bytes in UTF-8");this.writeU8(219),this.writeU32(e)}},e.prototype.encodeString=function(e){if(e.length>ct){var t=st(e);this.ensureBufferSizeToWrite(5+t),this.writeStringHeader(t),lt(e,this.bytes,this.pos),this.pos+=t}else t=st(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: "+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: "+t);this.writeU8(198),this.writeU32(t)}var n=wt(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: "+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=ht(e,t,n),i=Uint8Array.prototype.slice.call(e,t,t+n);return this.store(i,o),o},e}(),St=(_t=function(e,t){return(_t=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])})(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}_t(e,t),e.prototype=null===t?Object.create(t):(n.prototype=t.prototype,new n)}),Ct=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]1||a(e,t)}))})}function a(e,t){try{(n=o[e](t)).value instanceof kt?Promise.resolve(n.value.v).then(c,l):h(i[0][2],n)}catch(e){h(i[0][3],e)}var n}function c(e){a("next",e)}function l(e){a("throw",e)}function h(e,t){e(t),i.shift(),i.length&&a(i[0][0],i[0][1])}},Dt=new DataView(new ArrayBuffer(0)),xt=new Uint8Array(Dt.buffer),Rt=function(){try{Dt.getInt8(0)}catch(e){return e.constructor}throw new Error("never reached")}(),Pt=new Rt("Insufficient data"),Ut=4294967295,At=new Et,Nt=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 St(t,e),t}(Error),Bt=function(){function e(e,t,n,r,o,i,s,a){void 0===e&&(e=yt.defaultCodec),void 0===t&&(t=void 0),void 0===n&&(n=Ut),void 0===r&&(r=Ut),void 0===o&&(o=Ut),void 0===i&&(i=Ut),void 0===s&&(s=Ut),void 0===a&&(a=At),this.extensionCodec=e,this.context=t,this.maxStrLength=n,this.maxBinLength=r,this.maxArrayLength=o,this.maxMapLength=i,this.maxExtLength=s,this.keyDecoder=a,this.totalPos=0,this.pos=0,this.view=Dt,this.bytes=xt,this.headByte=-1,this.stack=[]}return e.prototype.reinitializeState=function(){this.totalPos=0,this.headByte=-1,this.stack.length=0},e.prototype.setBuffer=function(e){this.bytes=wt(e),this.view=function(e){if(e instanceof ArrayBuffer)return new DataView(e);var t=wt(e);return new DataView(t.buffer,t.byteOffset,t.byteLength)}(this.bytes),this.pos=0},e.prototype.appendBuffer=function(e){if(-1!==this.headByte||this.hasRemaining()){var t=this.bytes.subarray(this.pos),n=wt(e),r=new Uint8Array(t.length+n.length);r.set(t),r.set(n,t.length),this.setBuffer(r)}else this.setBuffer(e)},e.prototype.hasRemaining=function(e){return void 0===e&&(e=1),this.view.byteLength-this.pos>=e},e.prototype.createExtraByteError=function(e){var t=this.view,n=this.pos;return new RangeError("Extra "+(t.byteLength-n)+" of "+t.byteLength+" byte(s) found at buffer["+e+"]")},e.prototype.decode=function(e){this.reinitializeState(),this.setBuffer(e);var t=this.doDecodeSync();if(this.hasRemaining())throw this.createExtraByteError(this.pos);return t},e.prototype.decodeMulti=function(e){return Ct(this,(function(t){switch(t.label){case 0:this.reinitializeState(),this.setBuffer(e),t.label=1;case 1:return this.hasRemaining()?[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,u,d;return Ct(this,(function(p){switch(p.label){case 0:i=!1,p.label=1;case 1:p.trys.push([1,6,7,12]),t=It(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 Rt))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())throw this.createExtraByteError(this.totalPos);return[2,s]}throw h=(l=this).headByte,u=l.pos,d=l.totalPos,new RangeError("Insufficient data in parsing "+bt(h)+" at "+d+" ("+u+" 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 Tt(this,arguments,(function(){var n,r,o,i,s,a,c,l,h;return Ct(this,(function(u){switch(u.label){case 0:n=t,r=-1,u.label=1;case 1:u.trys.push([1,13,14,19]),o=It(e),u.label=2;case 2:return[4,kt(o.next())];case 3:if((i=u.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()),u.label=4;case 4:u.trys.push([4,9,,10]),u.label=5;case 5:return[4,kt(this.doDecodeSync())];case 6:return[4,u.sent()];case 7:return u.sent(),0==--r?[3,8]:[3,5];case 8:return[3,10];case 9:if(!((a=u.sent())instanceof Rt))throw a;return[3,10];case 10:this.totalPos+=this.pos,u.label=11;case 11:return[3,2];case 12:return[3,19];case 13:return c=u.sent(),l={error:c},[3,19];case 14:return u.trys.push([14,,17,18]),i&&!i.done&&(h=o.return)?[4,kt(h.call(o))]:[3,16];case 15:u.sent(),u.label=16;case 16:return[3,18];case 17:if(l)throw l.error;return[7];case 18:return[7];case 19:return[2]}}))}))},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 Nt("Unrecognized type byte: "+bt(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 Nt("The type of key must be string or number but "+typeof t);if("__proto__"===t)throw new Nt("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 Nt("Unrecognized array type byte: "+bt(e))}},e.prototype.pushMapState=function(e){if(e>this.maxMapLength)throw new Nt("Max length exceeded: map length ("+e+") > maxMapLengthLength ("+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 Nt("Max length exceeded: array length ("+e+") > maxArrayLength ("+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 Nt("Max length exceeded: UTF-8 byte length ("+e+") > maxStrLength ("+this.maxStrLength+")");if(this.bytes.byteLengthdt?function(e,t,n){var r=e.subarray(t,t+n);return ut.decode(r)}(this.bytes,o,e):ht(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 Nt("Max length exceeded: bin length ("+e+") > maxBinLength ("+this.maxBinLength+")");if(!this.hasRemaining(e+t))throw Pt;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 Nt("Max length exceeded: ext length ("+e+") > maxExtLength ("+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=gt(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 $t{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 Lt=new Uint8Array([145,Ie.Ping]);class Mt{constructor(e){this.name="messagepack",this.version=1,this.transferFormat=Ce.Binary,this._errorResult=1,this._voidResult=2,this._nonVoidResult=3,e=e||{},this._encoder=new vt(e.extensionCodec,e.context,e.maxDepth,e.initialBufferSize,e.sortKeys,e.forceFloat32,e.ignoreUndefined,e.forceIntegerToFloat),this._decoder=new Bt(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=Ae.instance);const r=$t.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 Ie.Invocation:return this._writeInvocation(e);case Ie.StreamInvocation:return this._writeStreamInvocation(e);case Ie.StreamItem:return this._writeStreamItem(e);case Ie.Completion:return this._writeCompletion(e);case Ie.Ping:return $t.write(Lt);case Ie.CancelInvocation:return this._writeCancelInvocation(e);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 Ie.Invocation:return this._createInvocationMessage(this._readHeaders(n),n);case Ie.StreamItem:return this._createStreamItemMessage(this._readHeaders(n),n);case Ie.Completion:return this._createCompletionMessage(this._readHeaders(n),n);case Ie.Ping:return this._createPingMessage(n);case Ie.Close:return this._createCloseMessage(n);default:return t.log(Ee.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:Ie.Close}}_createPingMessage(e){if(e.length<1)throw new Error("Invalid payload for Ping message.");return{type:Ie.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:Ie.Invocation}:{arguments:t[4],headers:e,streamIds:[],target:t[3],type:Ie.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:Ie.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:Ie.Completion}}_writeInvocation(e){let t;return t=e.streamIds?this._encoder.encode([Ie.Invocation,e.headers||{},e.invocationId||null,e.target,e.arguments,e.streamIds]):this._encoder.encode([Ie.Invocation,e.headers||{},e.invocationId||null,e.target,e.arguments]),$t.write(t.slice())}_writeStreamInvocation(e){let t;return t=e.streamIds?this._encoder.encode([Ie.StreamInvocation,e.headers||{},e.invocationId,e.target,e.arguments,e.streamIds]):this._encoder.encode([Ie.StreamInvocation,e.headers||{},e.invocationId,e.target,e.arguments]),$t.write(t.slice())}_writeStreamItem(e){const t=this._encoder.encode([Ie.StreamItem,e.headers||{},e.invocationId,e.item]);return $t.write(t.slice())}_writeCompletion(e){const t=e.error?this._errorResult:e.result?this._nonVoidResult:this._voidResult;let n;switch(t){case this._errorResult:n=this._encoder.encode([Ie.Completion,e.headers||{},e.invocationId,t,e.error]);break;case this._voidResult:n=this._encoder.encode([Ie.Completion,e.headers||{},e.invocationId,t]);break;case this._nonVoidResult:n=this._encoder.encode([Ie.Completion,e.headers||{},e.invocationId,t,e.result])}return $t.write(n.slice())}_writeCancelInvocation(e){const t=this._encoder.encode([Ie.CancelInvocation,e.headers||{},e.invocationId]);return $t.write(t.slice())}_readHeaders(e){const t=e[1];if("object"!=typeof t)throw new Error("Invalid headers.");return t}}let Ot=!1;const Ht="function"==typeof TextDecoder?new TextDecoder("utf-8"):null,Ft=Ht?Ht.decode.bind(Ht):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("")},jt=Math.pow(2,32),Wt=Math.pow(2,21)-1;function zt(e,t){return e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24}function qt(e,t){return e[t]+(e[t+1]<<8)+(e[t+2]<<16)+(e[t+3]<<24>>>0)}function Jt(e,t){const n=qt(e,t+4);if(n>Wt)throw new Error(`Cannot read uint64 with high order part ${n}, because the result would exceed Number.MAX_SAFE_INTEGER.`);return n*jt+qt(e,t)}class Kt{constructor(e){this.batchData=e;const t=new Gt(e);this.arrayRangeReader=new Qt(e),this.arrayBuilderSegmentReader=new Zt(e),this.diffReader=new Vt(e),this.editReader=new Xt(e,t),this.frameReader=new Yt(e,t)}updatedComponents(){return zt(this.batchData,this.batchData.length-20)}referenceFrames(){return zt(this.batchData,this.batchData.length-16)}disposedComponentIds(){return zt(this.batchData,this.batchData.length-12)}disposedEventHandlerIds(){return zt(this.batchData,this.batchData.length-8)}updatedComponentsEntry(e,t){const n=e+4*t;return zt(this.batchData,n)}referenceFramesEntry(e,t){return e+20*t}disposedComponentIdsEntry(e,t){const n=e+4*t;return zt(this.batchData,n)}disposedEventHandlerIdsEntry(e,t){const n=e+8*t;return Jt(this.batchData,n)}}class Vt{constructor(e){this.batchDataUint8=e}componentId(e){return zt(this.batchDataUint8,e)}edits(e){return e+4}editsEntry(e,t){return e+16*t}}class Xt{constructor(e,t){this.batchDataUint8=e,this.stringReader=t}editType(e){return zt(this.batchDataUint8,e)}siblingIndex(e){return zt(this.batchDataUint8,e+4)}newTreeIndex(e){return zt(this.batchDataUint8,e+8)}moveToSiblingIndex(e){return zt(this.batchDataUint8,e+8)}removedAttributeName(e){const t=zt(this.batchDataUint8,e+12);return this.stringReader.readString(t)}}class Yt{constructor(e,t){this.batchDataUint8=e,this.stringReader=t}frameType(e){return zt(this.batchDataUint8,e)}subtreeLength(e){return zt(this.batchDataUint8,e+4)}elementReferenceCaptureId(e){const t=zt(this.batchDataUint8,e+4);return this.stringReader.readString(t)}componentId(e){return zt(this.batchDataUint8,e+8)}elementName(e){const t=zt(this.batchDataUint8,e+8);return this.stringReader.readString(t)}textContent(e){const t=zt(this.batchDataUint8,e+4);return this.stringReader.readString(t)}markupContent(e){const t=zt(this.batchDataUint8,e+4);return this.stringReader.readString(t)}attributeName(e){const t=zt(this.batchDataUint8,e+4);return this.stringReader.readString(t)}attributeValue(e){const t=zt(this.batchDataUint8,e+8);return this.stringReader.readString(t)}attributeEventHandlerId(e){return Jt(this.batchDataUint8,e+12)}}class Gt{constructor(e){this.batchDataUint8=e,this.stringTableStartIndex=zt(e,e.length-4)}readString(e){if(-1===e)return null;{const n=zt(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(en.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(en.Debug,`Waiting for batch ${this.nextBatchId}. Batch ${e} not processed.`);try{this.nextBatchId++,this.logger.log(en.Debug,`Applying batch ${e}.`),function(e,t){const n=Q[e];if(!n)throw new Error(`There is no browser renderer with ID ${e}.`);const r=t.arrayRangeReader,o=t.updatedComponents(),i=r.values(o),s=r.count(o),a=t.referenceFrames(),c=r.values(a),l=t.diffReader;for(let e=0;e=this.minLevel){const n=`[${(new Date).toISOString()}] ${en[e]}: ${t}`;switch(e){case en.Critical:case en.Error:console.error(n);break;case en.Warning:console.warn(n);break;case en.Information:console.info(n);break;default:console.log(n)}}}}class on{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!==ke.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!==ke.Connected)return!1;const t=await e.invoke("StartCircuit",re.getBaseURI(),re.getLocationHref(),JSON.stringify(this.components.map((e=>e.toRecord()))),this.applicationState||"");return!!t&&(this.initialize(t),!0)}resolveElement(e){const t=Number.parseInt(e);if(Number.isNaN(t))throw new Error(`Invalid sequence number '${e}'.`);return function(e,t){if(!e.parentNode)throw new Error(`Comment not connected to the DOM ${e.textContent}`);const n=e.parentNode,r=k(n,!0),o=A(r);return Array.from(n.childNodes).forEach((e=>o.push(e))),e[C]=r,t&&(e[I]=t,k(t)),k(e)}(this.components[t].start,this.components[t].end)}}const sn={configureSignalR:e=>{},logLevel:en.Warning,reconnectionOptions:{maxRetries:8,retryIntervalMilliseconds:2e4,dialogId:"components-reconnect-modal"}};class an{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.modal.innerHTML='

Alternatively, reload

',this.message=this.modal.querySelector("h5"),this.button=this.modal.querySelector("button"),this.reloadParagraph=this.modal.querySelector("p"),this.loader=this.getLoader(),this.message.after(this.loader),this.button.addEventListener("click",(async()=>{this.show();try{await(null==fe?void 0:fe.reconnect)()||this.rejected()}catch(e){this.logger.log(en.Error,e),this.failed()}})),this.reloadParagraph.querySelector("a").addEventListener("click",(()=>location.reload()))}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",this.message.innerHTML="Reconnection failed. Try reloading the page if you're unable to reconnect.",this.message.querySelector("a").addEventListener("click",(()=>location.reload()))}rejected(){this.button.style.display="none",this.reloadParagraph.style.display="none",this.loader.style.display="none",this.message.innerHTML="Could not reconnect to the server. Reload the page to restore functionality.",this.message.querySelector("a").addEventListener("click",(()=>location.reload()))}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 cn{constructor(e,t,n){this.dialog=e,this.maxRetries=t,this.document=n,this.document=n;const r=this.document.getElementById(cn.MaxRetriesId);r&&(r.innerText=this.maxRetries.toString())}show(){this.removeClasses(),this.dialog.classList.add(cn.ShowClassName)}update(e){const t=this.document.getElementById(cn.CurrentAttemptId);t&&(t.innerText=e.toString())}hide(){this.removeClasses(),this.dialog.classList.add(cn.HideClassName)}failed(){this.removeClasses(),this.dialog.classList.add(cn.FailedClassName)}rejected(){this.removeClasses(),this.dialog.classList.add(cn.RejectedClassName)}removeClasses(){this.dialog.classList.remove(cn.ShowClassName,cn.HideClassName,cn.FailedClassName,cn.RejectedClassName)}}cn.ShowClassName="components-reconnect-show",cn.HideClassName="components-reconnect-hide",cn.FailedClassName="components-reconnect-failed",cn.RejectedClassName="components-reconnect-rejected",cn.MaxRetriesId="components-reconnect-max-retries",cn.CurrentAttemptId="components-reconnect-current-attempt";class ln{constructor(e,t,n){this._currentReconnectionProcess=null,this._logger=e,this._reconnectionDisplay=t,this._reconnectCallback=n||(()=>fe.reconnect())}onConnectionDown(e,t){if(!this._reconnectionDisplay){const t=document.getElementById(e.dialogId);this._reconnectionDisplay=t?new cn(t,e.maxRetries,document):new an(e.dialogId,e.maxRetries,document,this._logger)}this._currentReconnectionProcess||(this._currentReconnectionProcess=new hn(e,this._logger,this._reconnectCallback,this._reconnectionDisplay))}onConnectionUp(){this._currentReconnectionProcess&&(this._currentReconnectionProcess.dispose(),this._currentReconnectionProcess=null)}}class hn{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;thn.MaximumFirstRetryInterval?hn.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(en.Error,e)}}this.reconnectDisplay.failed()}delay(e){return new Promise((t=>setTimeout(t,e)))}}hn.MaximumFirstRetryInterval=3e3;const un=/^\s*Blazor-Component-State:(?[a-zA-Z0-9\+\/=]+)$/;function dn(e){var t;if(e.nodeType===Node.COMMENT_NODE){const n=e.textContent||"",r=un.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 gn(e,t){const n=e.currentElement;if(n&&n.nodeType===Node.COMMENT_NODE&&n.textContent){const r=fn.exec(n.textContent),o=r&&r.groups&&r.groups.descriptor;if(!o)return;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;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.");if(c){const e=mn(c,n);if(!e)throw new Error(`Could not find an end component comment for '${t}'`);return{type:r,assembly:o,typeName:i,parameterDefinitions:s&&atob(s),parameterValues:a&&atob(a),start:t,prerenderId:c,end:e}}return{type:r,assembly:o,typeName:i,parameterDefinitions:s&&atob(s),parameterValues:a&&atob(a),start:t}}}(r,n,e);case"server":return function(e,t,n){const{type:r,descriptor:o,sequence:i,prerenderId:s}=e;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)}'`);if(s){const e=mn(s,n);if(!e)throw new Error(`Could not find an end component comment for '${t}'`);return{type:r,sequence:i,descriptor:o,start:t,prerenderId:s,end:e}}return{type:r,sequence:i,descriptor:o,start:t}}}(r,n,e)}}catch(e){throw new Error(`Found malformed component comment at ${n.textContent}`)}}}function mn(e,t){for(;t.next()&&t.currentElement;){const n=t.currentElement;if(n.nodeType!==Node.COMMENT_NODE)continue;if(!n.textContent)continue;const r=fn.exec(n.textContent),o=r&&r[1];if(o)return yn(o,e),n}}function yn(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 wn{constructor(e){this.childNodes=e,this.currentIndex=-1,this.length=e.length}next(){return this.currentIndex++,this.currentIndexe.sequence-t.sequence))}(e)}(document),o=dn(document),i=new on(r,o||""),s=await Tn(t,n,i);if(!await i.startCircuit(s))return void n.log(en.Error,"Failed to start the circuit.");let a=!1;const c=()=>{if(!a){const e=new FormData,t=i.circuitId;e.append("circuitId",t),a=navigator.sendBeacon("_blazor/disconnect",e)}};fe.disconnect=c,window.addEventListener("unload",c,{capture:!1,once:!0}),fe.reconnect=async e=>{if(Cn)return!1;const r=e||await Tn(t,n,i);return await i.reconnect(r)?(t.reconnectionHandler.onConnectionUp(),!0):(n.log(en.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)},n.log(en.Information,"Blazor server-side application started.")}async function Tn(t,n,r){const i=new Mt;i.name="blazorpack";const s=(new rt).withUrl("_blazor").withHubProtocol(i);t.configureSignalR(s);const a=s.build();o=(e,t)=>{a.send("DispatchBrowserEvent",JSON.stringify(e),JSON.stringify(t))},fe._internal.navigationManager.listenForNavigationEvents(((e,t)=>a.send("OnLocationChanged",e,t))),a.on("JS.AttachComponent",((e,t)=>function(e,t,n){let r=Q[0];r||(r=Q[0]=new V(0)),r.attachRootComponentToLogicalElement(n,t)}(0,r.resolveElement(t),e))),a.on("JS.BeginInvokeJS",e.jsCallDispatcher.beginInvokeJSFromDotNet),a.on("JS.EndInvokeDotNet",e.jsCallDispatcher.endInvokeDotNetFromJS),a.on("JS.ReceiveByteArray",e.jsCallDispatcher.receiveByteArray);const c=tn.getOrCreate(n);a.on("JS.RenderBatch",((e,t)=>{n.log(en.Debug,`Received render batch with id ${e} and ${t.byteLength} bytes.`),c.processBatch(e,t,a)})),a.onclose((e=>!Cn&&t.reconnectionHandler.onConnectionDown(t.reconnectionOptions,e))),a.on("JS.Error",(e=>{Cn=!0,Dn(a,e,n),async function(){let e=document.querySelector("#blazor-error-ui");e&&(e.style.display="block"),Ot||(Ot=!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()}})))}()})),fe._internal.forceCloseConnection=()=>a.stop(),fe._internal.sendJSDataStream=(e,t,n)=>{setTimeout((async()=>{let r=5,o=(new Date).valueOf();try{const i=n-512;if(i<=0)throw new Error("The chunk size must be greater than 0.");let s=0;for(;s1)await a.send("ReceiveJSDataChunk",t,c,null);else{if(!await a.invoke("ReceiveJSDataChunk",t,c,null))break;const e=(new Date).valueOf(),n=e-o;o=e,r=Math.max(1,Math.round(500/n))}s+=n}}catch(e){await a.send("ReceiveJSDataChunk",t,null,e.toString())}}),0)};try{await a.start()}catch(e){Dn(a,e,n)}return e.attachDispatcher({beginInvokeDotNetFromJS:(e,t,n,r,o)=>{a.send("BeginInvokeDotNetFromJS",e?e.toString():null,t,n,r||0,o)},endInvokeJSFromDotNet:(e,t,n)=>{a.send("EndInvokeJSFromDotNet",e,t,n)},sendByteArray:(e,t)=>{a.send("ReceiveByteArray",e,t)}}),a}function Dn(e,t,n){n.log(en.Error,t),e&&e.stop()}fe.start=kn,document&&document.currentScript&&"false"!==document.currentScript.getAttribute("autostart")&&kn()})(); \ 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 6b6f47ef9ca0..dde2003b4c93 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;!function(e){window.DotNet=e;const t=[],n=new Map;class r{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 o="__jsObjectId",a={},i={0:new r(window)};i[0]._cachedFunctions.set("import",(e=>("string"==typeof e&&e.startsWith("./")&&(e=document.baseURI+e.substr(2)),import(e))));let s,c=1,l=1,u=null;function d(e){t.push(e)}function h(e){if(e&&"object"==typeof e){i[l]=new r(e);const t={[o]:l};return l++,t}throw new Error(`Cannot create a JSObjectReference from the value '${e}'.`)}function f(e){if(!(e.buffer instanceof ArrayBuffer))throw new Error(`Cannot create a JSDataReference from the value '${e}' as it is not a valid ArrayBuffer.`);if(void 0===e.byteLength)throw new Error(`Cannot create a JSDataReference from the value '${e}' as it doesn't have a byteLength.`);const t={__jsDataReferenceLength:e.byteLength};try{const n=h(e);t.__jsObjectId=n.__jsObjectId}catch{throw new Error(`Cannot create a JSDataReference from the value '${e}'.`)}return t}function m(e){return e?JSON.parse(e,((e,n)=>t.reduce(((t,n)=>n(e,t)),n))):null}function p(e,t,n,r){const o=g();if(o.invokeDotNetFromJS){const a=A(r),i=o.invokeDotNetFromJS(e,t,n,a);return i?m(i):null}throw new Error("The current dispatcher does not support synchronous calls from JS to .NET. Use invokeMethodAsync instead.")}function v(e,t,n,r){if(e&&n)throw new Error(`For instance method calls, assemblyName should be null. Received '${e}'.`);const o=c++,i=new Promise(((e,t)=>{a[o]={resolve:e,reject:t}}));try{const a=A(r);g().beginInvokeDotNetFromJS(o,e,t,n,a)}catch(e){b(o,!1,e)}return i}function g(){if(null!==u)return u;throw new Error("No .NET call dispatcher has been set.")}function b(e,t,n){if(!a.hasOwnProperty(e))throw new Error(`There is no pending async call with ID ${e}.`);const r=a[e];delete a[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){let n=i[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 i[e]}e.attachDispatcher=function(e){u=e},e.attachReviver=d,e.invokeMethod=function(e,t,...n){return p(e,t,null,n)},e.invokeMethodAsync=function(e,t,...n){return v(e,t,null,n)},e.createJSObjectReference=h,e.createJSDataReference=f,e.disposeJSObjectReference=function(e){const t=e&&e.__jsObjectId;"number"==typeof t&&E(t)},function(e){e[e.Default=0]="Default",e[e.JSObjectReference=1]="JSObjectReference",e[e.JSDataReference=2]="JSDataReference"}(s=e.JSCallResultType||(e.JSCallResultType={})),e.jsCallDispatcher={findJSFunction:w,disposeJSObjectReferenceById:E,invokeJSFromDotNet:(e,t,n,r)=>{const o=D(w(e,r).apply(null,m(t)),n);return null==o?null:A(o)},beginInvokeJSFromDotNet:(e,t,n,r,o)=>{const a=new Promise((e=>{e(w(t,o).apply(null,m(n)))}));e&&a.then((t=>g().endInvokeJSFromDotNet(e,!0,A([e,!0,D(t,r)]))),(t=>g().endInvokeJSFromDotNet(e,!1,JSON.stringify([e,!1,y(t)]))))},endInvokeDotNetFromJS:(e,t,n)=>{const r=t?m(n):new Error(n);b(parseInt(e),t,r)},receiveByteArray:(e,t)=>{n.set(e,t)}};class I{constructor(e){this._id=e}invokeMethod(e,...t){return p(null,e,this._id,t)}invokeMethodAsync(e,...t){return v(null,e,this._id,t)}dispose(){v(null,"__Dispose",this._id,null).catch((e=>console.error(e)))}serializeAsArg(){return{__dotNetObject:this._id}}}const S="__byte[]";function D(e,t){switch(t){case s.Default:return e;case s.JSObjectReference:return h(e);case s.JSDataReference:return f(e);default:throw new Error(`Invalid JS call result type '${t}'.`)}}d((function(e,t){if(t&&"object"==typeof t){if(t.hasOwnProperty("__dotNetObject"))return new I(t.__dotNetObject);if(t.hasOwnProperty(o)){const e=t.__jsObjectId,n=i[e];if(n)return n.getWrappedObject();throw new Error(`JS object instance with Id '${e}' does not exist. It may have been disposed.`)}if(t.hasOwnProperty(S)){const e=t["__byte[]"],r=n.get(e);if(void 0===r)throw new Error(`Byte array index '${e}' does not exist.`);return r}}return t}));let C=0;function A(e){return C=0,JSON.stringify(e,T)}function T(e,t){if(t instanceof I)return t.serializeAsArg();if(t instanceof Uint8Array){u.sendByteArray(C,t);const e={[S]:C};return C++,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"}(n||(n={}));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}}let o;function a(e,t){if(!o)throw new Error("eventDispatcher not initialized. Call 'setEventDispatcher' to configure it.");o(e,t)}const i=new Map,s=new Map,c={createEventArgs:()=>({})},l=[];function u(e){return i.get(e)}function d(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 f(e){const t=[];for(let n=0;n{return{...m(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"],c),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};var t}}),h(["contextmenu","click","mouseover","mouseout","mousemove","mousedown","mouseup","dblclick"],{createEventArgs:e=>m(e)}),h(["error"],{createEventArgs:e=>{return{message:(t=e).message,filename:t.filename,lineno:t.lineno,colno:t.colno};var t}}),h(["loadstart","timeout","abort","load","loadend","progress"],{createEventArgs:e=>{return{lengthComputable:(t=e).lengthComputable,loaded:t.loaded,total:t.total};var t}}),h(["touchcancel","touchend","touchmove","touchenter","touchleave","touchstart"],{createEventArgs:e=>{return{detail:(t=e).detail,touches:f(t.touches),targetTouches:f(t.targetTouches),changedTouches:f(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{...m(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{...m(t=e),deltaX:t.deltaX,deltaY:t.deltaY,deltaZ:t.deltaZ,deltaMode:t.deltaMode};var t}}),h(["toggle"],c);const p=["date","datetime-local","month","time","week"],v=I(["abort","blur","change","error","focus","load","loadend","loadstart","mouseenter","mouseleave","progress","reset","scroll","submit","unload","toggle","DOMNodeInsertedIntoDocument","DOMNodeRemovedFromDocument"]),g={submit:!0},b=I(["click","dblclick","mousedown","mousemove","mouseup"]);class y{constructor(e){this.browserRendererId=e,this.afterClickCallbacks=[];const t=++y.nextEventDelegatorId;this.eventsCollectionKey=`_blazorEvents_${t}`,this.eventInfoStore=new w(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){let n=t.target,o=null,i=!1;const s=v.hasOwnProperty(e);let c=!1;for(;n;){const h=this.getEventHandlerInfosForElement(n,!1);if(h){const s=h.getHandler(e);if(s&&(l=n,d=t.type,!((l instanceof HTMLButtonElement||l instanceof HTMLInputElement||l instanceof HTMLTextAreaElement||l instanceof HTMLSelectElement)&&b.hasOwnProperty(d)&&l.disabled))){if(!i){const n=u(e);o=(null==n?void 0:n.createEventArgs)?n.createEventArgs(t):{},i=!0}g.hasOwnProperty(t.type)&&t.preventDefault(),a({browserRendererId:this.browserRendererId,eventHandlerId:s.eventHandlerId,eventName:e,eventFieldInfo:r.fromEvent(s.renderingComponentId,t)},o)}h.stopPropagation(e)&&(c=!0),h.preventDefault(e)&&t.preventDefault()}n=s||c?null:n.parentElement}var l,d}getEventHandlerInfosForElement(e,t){return e.hasOwnProperty(this.eventsCollectionKey)?e[this.eventsCollectionKey]:t?e[this.eventsCollectionKey]=new E:null}}y.nextEventDelegatorId=0;class w{constructor(e){this.globalListener=e,this.infosByEventHandlerId={},this.countByEventName={},l.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=d(e),this.countByEventName.hasOwnProperty(e))this.countByEventName[e]++;else{this.countByEventName[e]=1;const t=v.hasOwnProperty(e);document.addEventListener(e,this.globalListener,t)}}update(e,t){if(this.infosByEventHandlerId.hasOwnProperty(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=d(t.eventName);0==--this.countByEventName[n]&&(delete this.countByEventName[n],document.removeEventListener(n,this.globalListener))}return t}handleEventNameAliasAdded(e,t){if(this.countByEventName.hasOwnProperty(e)){const n=this.countByEventName[e];delete this.countByEventName[e],document.removeEventListener(e,this.globalListener),this.addGlobalListener(t),this.countByEventName[t]+=n-1}}}class E{constructor(){this.handlers={},this.preventDefaultFlags=null,this.stopPropagationFlags=null}getHandler(e){return this.handlers.hasOwnProperty(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 I(e){const t={};return e.forEach((e=>{t[e]=!0})),t}const S=M("_blazorLogicalChildren"),D=M("_blazorLogicalParent"),C=M("_blazorLogicalEnd");function A(e,t){if(e.childNodes.length>0&&!t)throw new Error("New logical elements must start empty, or allowExistingContents must be true");return S in e||(e[S]=[]),e}function T(e,t){const n=document.createComment("!");return N(n,e,t),n}function N(e,t,n){const r=e;if(e instanceof Comment&&O(r)&&O(r).length>0)throw new Error("Not implemented: inserting non-empty logical container");if(k(r))throw new Error("Not implemented: moving existing logical children");const o=O(t);if(n0;)R(n,0)}const r=n;r.parentNode.removeChild(r)}function k(e){return e[D]||null}function F(e,t){return O(e)[t]}function _(e){var t=B(e);return"http://www.w3.org/2000/svg"===t.namespaceURI&&"foreignObject"!==t.tagName}function O(e){return e[S]}function x(e,t){const n=O(e);t.forEach((e=>{e.moveRangeStart=n[e.fromSiblingIndex],e.moveRangeEnd=H(e.moveRangeStart)})),t.forEach((t=>{const r=t.moveToBeforeMarker=document.createComment("marker"),o=n[t.toSiblingIndex+1];o?o.parentNode.insertBefore(r,o):P(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 B(e){if(e instanceof Element)return e;if(e instanceof Comment)return e.parentNode;throw new Error("Not a valid logical element")}function L(e){const t=O(k(e));return t[Array.prototype.indexOf.call(t,e)+1]||null}function P(e,t){if(t instanceof Element)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=L(t);n?n.parentNode.insertBefore(e,n):P(e,k(t))}}}function H(e){if(e instanceof Element)return e;const t=L(e);if(t)return t.previousSibling;{const t=k(e);return t instanceof Element?t.lastChild:H(t)}}function M(e){return"function"==typeof Symbol?Symbol():e}function U(e){return`_bl_${e}`}e.attachReviver(((e,t)=>t&&"object"==typeof t&&t.hasOwnProperty("__internalId")&&"string"==typeof t.__internalId?function(e){const t=`[${U(e)}]`;return document.querySelector(t)}(t.__internalId):t));const j="_blazorSelectValue",J=document.createElement("template"),$=document.createElementNS("http://www.w3.org/2000/svg","g"),K={},z="__internal_",V="preventDefault_",X="stopPropagation_";class Y{constructor(e){this.childComponentLocations={},this.eventDelegator=new y(e),this.eventDelegator.notifyAfterClick((e=>{if(!ee)return;if(0!==e.button||function(e){return e.ctrlKey||e.shiftKey||e.altKey||e.metaKey}(e))return;if(e.defaultPrevented)return;const t=function(e){const t=!window._blazorDisableComposedPath&&e.composedPath&&e.composedPath();if(t){for(let e=0;eie(!1))))},enableNavigationInterception:function(){ee=!0},navigateTo:oe,getBaseURI:()=>document.baseURI,getLocationHref:()=>location.href};function oe(e,t,n=!1){const r=ce(e);if(!t&&ue(r))ae(r,!1,n);else if(t&&location.href===e){const t=e+"?";history.replaceState(null,"",t),location.replace(e)}else n?history.replaceState(null,"",r):location.href=e}function ae(e,t,n=!1){Q=!0,n?history.replaceState(null,"",e):history.pushState(null,"",e),ie(t)}async function ie(e){ne&&await ne(location.href,e)}let se;function ce(e){return se=se||document.createElement("a"),se.href=e,se.href}function le(e,t){return e?e.tagName===t?e:le(e.parentElement,t):null}function ue(e){const t=(n=document.baseURI).substr(0,n.lastIndexOf("/")+1);var n;return e.startsWith(t)}const de={init:function(e,t,n,r=50){const o=fe(t);(o||document.documentElement).style.overflowAnchor="none";const a=new IntersectionObserver((function(r){r.forEach((r=>{var o;if(!r.isIntersecting)return;const a=t.getBoundingClientRect(),i=n.getBoundingClientRect().top-a.bottom,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`});a.observe(t),a.observe(n);const i=c(t),s=c(n);function c(e){const t=new MutationObserver((()=>{a.unobserve(e),a.observe(e)}));return t.observe(e,{attributes:!0}),t}he[e._id]={intersectionObserver:a,mutationObserverBefore:i,mutationObserverAfter:s}},dispose:function(e){const t=he[e._id];t&&(t.intersectionObserver.disconnect(),t.mutationObserverBefore.disconnect(),t.mutationObserverAfter.disconnect(),e.dispose(),delete he[e._id])}},he={};function fe(e){return e?"visible"!==getComputedStyle(e).overflowY?e:fe(e.parentElement):null}const me={navigateTo:oe,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]),l.forEach((n=>n(e,t.browserEventName)))}i.set(e,t)},_internal:{navigationManager:re,domWrapper:{focus:function(e,t){if(!(e instanceof HTMLElement))throw new Error("Unable to focus an invalid element.");e.focus({preventScroll:t})},focusBySelector:function(e){const t=document.querySelector(e);t&&(t.hasAttribute("tabindex")||(t.tabIndex=-1),t.focus())}},Virtualize:de}};window.Blazor=me;let pe=!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("")},be=Math.pow(2,32),ye=Math.pow(2,21)-1;function we(e,t){return e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24}function Ee(e,t){return e[t]+(e[t+1]<<8)+(e[t+2]<<16)+(e[t+3]<<24>>>0)}function Ie(e,t){const n=Ee(e,t+4);if(n>ye)throw new Error(`Cannot read uint64 with high order part ${n}, because the result would exceed Number.MAX_SAFE_INTEGER.`);return n*be+Ee(e,t)}class Se{constructor(e){this.batchData=e;const t=new Te(e);this.arrayRangeReader=new Ne(e),this.arrayBuilderSegmentReader=new Re(e),this.diffReader=new De(e),this.editReader=new Ce(e,t),this.frameReader=new Ae(e,t)}updatedComponents(){return we(this.batchData,this.batchData.length-20)}referenceFrames(){return we(this.batchData,this.batchData.length-16)}disposedComponentIds(){return we(this.batchData,this.batchData.length-12)}disposedEventHandlerIds(){return we(this.batchData,this.batchData.length-8)}updatedComponentsEntry(e,t){const n=e+4*t;return we(this.batchData,n)}referenceFramesEntry(e,t){return e+20*t}disposedComponentIdsEntry(e,t){const n=e+4*t;return we(this.batchData,n)}disposedEventHandlerIdsEntry(e,t){const n=e+8*t;return Ie(this.batchData,n)}}class De{constructor(e){this.batchDataUint8=e}componentId(e){return we(this.batchDataUint8,e)}edits(e){return e+4}editsEntry(e,t){return e+16*t}}class Ce{constructor(e,t){this.batchDataUint8=e,this.stringReader=t}editType(e){return we(this.batchDataUint8,e)}siblingIndex(e){return we(this.batchDataUint8,e+4)}newTreeIndex(e){return we(this.batchDataUint8,e+8)}moveToSiblingIndex(e){return we(this.batchDataUint8,e+8)}removedAttributeName(e){const t=we(this.batchDataUint8,e+12);return this.stringReader.readString(t)}}class Ae{constructor(e,t){this.batchDataUint8=e,this.stringReader=t}frameType(e){return we(this.batchDataUint8,e)}subtreeLength(e){return we(this.batchDataUint8,e+4)}elementReferenceCaptureId(e){const t=we(this.batchDataUint8,e+4);return this.stringReader.readString(t)}componentId(e){return we(this.batchDataUint8,e+8)}elementName(e){const t=we(this.batchDataUint8,e+8);return this.stringReader.readString(t)}textContent(e){const t=we(this.batchDataUint8,e+4);return this.stringReader.readString(t)}markupContent(e){const t=we(this.batchDataUint8,e+4);return this.stringReader.readString(t)}attributeName(e){const t=we(this.batchDataUint8,e+4);return this.stringReader.readString(t)}attributeValue(e){const t=we(this.batchDataUint8,e+8);return this.stringReader.readString(t)}attributeEventHandlerId(e){return Ie(this.batchDataUint8,e+12)}}class Te{constructor(e){this.batchDataUint8=e,this.stringTableStartIndex=we(e,e.length-4)}readString(e){if(-1===e)return null;{const n=we(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)<{!function(e,t,n){const r=document.querySelector(e);if(!r)throw new Error(`Could not find any element matching selector '${e}'.`);!function(e,t,n){let r=Z[0];r||(r=Z[0]=new Y(0)),r.attachRootComponentToLogicalElement(n,t)}(0,A(r,!0),t)}(t,e)},RenderBatch:(e,t)=>{try{const n=Me(t);(function(e,t){const n=Z[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{Fe=!0,console.error(`${e}\n${t}`),async function(){let e=document.querySelector("#blazor-error-ui");e&&(e.style.display="block"),pe||(pe=!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:e.jsCallDispatcher.beginInvokeJSFromDotNet,EndInvokeDotNet:e.jsCallDispatcher.endInvokeDotNetFromJS,SendByteArrayToJS:He,Navigate:re.navigateTo};window.external.receiveMessage((e=>{const n=function(e){if(Fe||!e||!e.startsWith(ke))return null;const t=e.substring(ke.length),[n,...r]=JSON.parse(t);return{messageType:n,args:r}}(e);if(n){if(!t.hasOwnProperty(n.messageType))throw new Error(`Unsupported IPC message type '${n.messageType}'`);t[n.messageType].apply(null,n.args)}}))}(),e.attachDispatcher({beginInvokeDotNetFromJS:Oe,endInvokeJSFromDotNet:xe,sendByteArray:Be}),me._internal.InputFile=Ue,re.enableNavigationInterception(),re.listenForNavigationEvents(Le),Pe("AttachPage",re.getBaseURI(),re.getLocationHref())}o=function(e,t){Pe("DispatchBrowserEvent",e,t)},me.start=Ke,document&&document.currentScript&&"false"!==document.currentScript.getAttribute("autostart")&&Ke()})(); \ No newline at end of file +(()=>{"use strict";var e,t,n;!function(e){window.DotNet=e;const t=[],n=new Map;class r{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 o="__jsObjectId",a={},i={0:new r(window)};i[0]._cachedFunctions.set("import",(e=>("string"==typeof e&&e.startsWith("./")&&(e=document.baseURI+e.substr(2)),import(e))));let s,c=1,l=1,u=null;function d(e){t.push(e)}function h(e){if(e&&"object"==typeof e){i[l]=new r(e);const t={[o]:l};return l++,t}throw new Error(`Cannot create a JSObjectReference from the value '${e}'.`)}function f(e){if(!(e.buffer instanceof ArrayBuffer))throw new Error(`Cannot create a JSDataReference from the value '${e}' as it is not a valid ArrayBuffer.`);if(void 0===e.byteLength)throw new Error(`Cannot create a JSDataReference from the value '${e}' as it doesn't have a byteLength.`);const t={__jsDataReferenceLength:e.byteLength};try{const n=h(e);t.__jsObjectId=n.__jsObjectId}catch{throw new Error(`Cannot create a JSStreamReference from the value '${e}'.`)}return t}function m(e){return e?JSON.parse(e,((e,n)=>t.reduce(((t,n)=>n(e,t)),n))):null}function p(e,t,n,r){const o=g();if(o.invokeDotNetFromJS){const a=A(r),i=o.invokeDotNetFromJS(e,t,n,a);return i?m(i):null}throw new Error("The current dispatcher does not support synchronous calls from JS to .NET. Use invokeMethodAsync instead.")}function v(e,t,n,r){if(e&&n)throw new Error(`For instance method calls, assemblyName should be null. Received '${e}'.`);const o=c++,i=new Promise(((e,t)=>{a[o]={resolve:e,reject:t}}));try{const a=A(r);g().beginInvokeDotNetFromJS(o,e,t,n,a)}catch(e){b(o,!1,e)}return i}function g(){if(null!==u)return u;throw new Error("No .NET call dispatcher has been set.")}function b(e,t,n){if(!a.hasOwnProperty(e))throw new Error(`There is no pending async call with ID ${e}.`);const r=a[e];delete a[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){let n=i[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 i[e]}e.attachDispatcher=function(e){u=e},e.attachReviver=d,e.invokeMethod=function(e,t,...n){return p(e,t,null,n)},e.invokeMethodAsync=function(e,t,...n){return v(e,t,null,n)},e.createJSObjectReference=h,e.createJSDataReference=f,e.disposeJSObjectReference=function(e){const t=e&&e.__jsObjectId;"number"==typeof t&&E(t)},function(e){e[e.Default=0]="Default",e[e.JSObjectReference=1]="JSObjectReference",e[e.JSDataReference=2]="JSDataReference"}(s=e.JSCallResultType||(e.JSCallResultType={})),e.jsCallDispatcher={findJSFunction:w,disposeJSObjectReferenceById:E,invokeJSFromDotNet:(e,t,n,r)=>{const o=D(w(e,r).apply(null,m(t)),n);return null==o?null:A(o)},beginInvokeJSFromDotNet:(e,t,n,r,o)=>{const a=new Promise((e=>{e(w(t,o).apply(null,m(n)))}));e&&a.then((t=>g().endInvokeJSFromDotNet(e,!0,A([e,!0,D(t,r)]))),(t=>g().endInvokeJSFromDotNet(e,!1,JSON.stringify([e,!1,y(t)]))))},endInvokeDotNetFromJS:(e,t,n)=>{const r=t?m(n):new Error(n);b(parseInt(e),t,r)},receiveByteArray:(e,t)=>{n.set(e,t)}};class I{constructor(e){this._id=e}invokeMethod(e,...t){return p(null,e,this._id,t)}invokeMethodAsync(e,...t){return v(null,e,this._id,t)}dispose(){v(null,"__Dispose",this._id,null).catch((e=>console.error(e)))}serializeAsArg(){return{__dotNetObject:this._id}}}const S="__byte[]";function D(e,t){switch(t){case s.Default:return e;case s.JSObjectReference:return h(e);case s.JSDataReference:return f(e);default:throw new Error(`Invalid JS call result type '${t}'.`)}}d((function(e,t){if(t&&"object"==typeof t){if(t.hasOwnProperty("__dotNetObject"))return new I(t.__dotNetObject);if(t.hasOwnProperty(o)){const e=t.__jsObjectId,n=i[e];if(n)return n.getWrappedObject();throw new Error(`JS object instance with Id '${e}' does not exist. It may have been disposed.`)}if(t.hasOwnProperty(S)){const e=t["__byte[]"],r=n.get(e);if(void 0===r)throw new Error(`Byte array index '${e}' does not exist.`);return r}}return t}));let C=0;function A(e){return C=0,JSON.stringify(e,T)}function T(e,t){if(t instanceof I)return t.serializeAsArg();if(t instanceof Uint8Array){u.sendByteArray(C,t);const e={[S]:C};return C++,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"}(n||(n={}));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}}let o;function a(e,t){if(!o)throw new Error("eventDispatcher not initialized. Call 'setEventDispatcher' to configure it.");o(e,t)}const i=new Map,s=new Map,c={createEventArgs:()=>({})},l=[];function u(e){return i.get(e)}function d(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 f(e){const t=[];for(let n=0;n{return{...m(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"],c),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};var t}}),h(["contextmenu","click","mouseover","mouseout","mousemove","mousedown","mouseup","dblclick"],{createEventArgs:e=>m(e)}),h(["error"],{createEventArgs:e=>{return{message:(t=e).message,filename:t.filename,lineno:t.lineno,colno:t.colno};var t}}),h(["loadstart","timeout","abort","load","loadend","progress"],{createEventArgs:e=>{return{lengthComputable:(t=e).lengthComputable,loaded:t.loaded,total:t.total};var t}}),h(["touchcancel","touchend","touchmove","touchenter","touchleave","touchstart"],{createEventArgs:e=>{return{detail:(t=e).detail,touches:f(t.touches),targetTouches:f(t.targetTouches),changedTouches:f(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{...m(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{...m(t=e),deltaX:t.deltaX,deltaY:t.deltaY,deltaZ:t.deltaZ,deltaMode:t.deltaMode};var t}}),h(["toggle"],c);const p=["date","datetime-local","month","time","week"],v=I(["abort","blur","change","error","focus","load","loadend","loadstart","mouseenter","mouseleave","progress","reset","scroll","submit","unload","toggle","DOMNodeInsertedIntoDocument","DOMNodeRemovedFromDocument"]),g={submit:!0},b=I(["click","dblclick","mousedown","mousemove","mouseup"]);class y{constructor(e){this.browserRendererId=e,this.afterClickCallbacks=[];const t=++y.nextEventDelegatorId;this.eventsCollectionKey=`_blazorEvents_${t}`,this.eventInfoStore=new w(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){let n=t.target,o=null,i=!1;const s=v.hasOwnProperty(e);let c=!1;for(;n;){const h=this.getEventHandlerInfosForElement(n,!1);if(h){const s=h.getHandler(e);if(s&&(l=n,d=t.type,!((l instanceof HTMLButtonElement||l instanceof HTMLInputElement||l instanceof HTMLTextAreaElement||l instanceof HTMLSelectElement)&&b.hasOwnProperty(d)&&l.disabled))){if(!i){const n=u(e);o=(null==n?void 0:n.createEventArgs)?n.createEventArgs(t):{},i=!0}g.hasOwnProperty(t.type)&&t.preventDefault(),a({browserRendererId:this.browserRendererId,eventHandlerId:s.eventHandlerId,eventName:e,eventFieldInfo:r.fromEvent(s.renderingComponentId,t)},o)}h.stopPropagation(e)&&(c=!0),h.preventDefault(e)&&t.preventDefault()}n=s||c?null:n.parentElement}var l,d}getEventHandlerInfosForElement(e,t){return e.hasOwnProperty(this.eventsCollectionKey)?e[this.eventsCollectionKey]:t?e[this.eventsCollectionKey]=new E:null}}y.nextEventDelegatorId=0;class w{constructor(e){this.globalListener=e,this.infosByEventHandlerId={},this.countByEventName={},l.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=d(e),this.countByEventName.hasOwnProperty(e))this.countByEventName[e]++;else{this.countByEventName[e]=1;const t=v.hasOwnProperty(e);document.addEventListener(e,this.globalListener,t)}}update(e,t){if(this.infosByEventHandlerId.hasOwnProperty(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=d(t.eventName);0==--this.countByEventName[n]&&(delete this.countByEventName[n],document.removeEventListener(n,this.globalListener))}return t}handleEventNameAliasAdded(e,t){if(this.countByEventName.hasOwnProperty(e)){const n=this.countByEventName[e];delete this.countByEventName[e],document.removeEventListener(e,this.globalListener),this.addGlobalListener(t),this.countByEventName[t]+=n-1}}}class E{constructor(){this.handlers={},this.preventDefaultFlags=null,this.stopPropagationFlags=null}getHandler(e){return this.handlers.hasOwnProperty(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 I(e){const t={};return e.forEach((e=>{t[e]=!0})),t}const S=M("_blazorLogicalChildren"),D=M("_blazorLogicalParent"),C=M("_blazorLogicalEnd");function A(e,t){if(e.childNodes.length>0&&!t)throw new Error("New logical elements must start empty, or allowExistingContents must be true");return S in e||(e[S]=[]),e}function T(e,t){const n=document.createComment("!");return N(n,e,t),n}function N(e,t,n){const r=e;if(e instanceof Comment&&O(r)&&O(r).length>0)throw new Error("Not implemented: inserting non-empty logical container");if(k(r))throw new Error("Not implemented: moving existing logical children");const o=O(t);if(n0;)R(n,0)}const r=n;r.parentNode.removeChild(r)}function k(e){return e[D]||null}function F(e,t){return O(e)[t]}function _(e){var t=B(e);return"http://www.w3.org/2000/svg"===t.namespaceURI&&"foreignObject"!==t.tagName}function O(e){return e[S]}function x(e,t){const n=O(e);t.forEach((e=>{e.moveRangeStart=n[e.fromSiblingIndex],e.moveRangeEnd=H(e.moveRangeStart)})),t.forEach((t=>{const r=t.moveToBeforeMarker=document.createComment("marker"),o=n[t.toSiblingIndex+1];o?o.parentNode.insertBefore(r,o):P(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 B(e){if(e instanceof Element)return e;if(e instanceof Comment)return e.parentNode;throw new Error("Not a valid logical element")}function L(e){const t=O(k(e));return t[Array.prototype.indexOf.call(t,e)+1]||null}function P(e,t){if(t instanceof Element)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=L(t);n?n.parentNode.insertBefore(e,n):P(e,k(t))}}}function H(e){if(e instanceof Element)return e;const t=L(e);if(t)return t.previousSibling;{const t=k(e);return t instanceof Element?t.lastChild:H(t)}}function M(e){return"function"==typeof Symbol?Symbol():e}function U(e){return`_bl_${e}`}e.attachReviver(((e,t)=>t&&"object"==typeof t&&t.hasOwnProperty("__internalId")&&"string"==typeof t.__internalId?function(e){const t=`[${U(e)}]`;return document.querySelector(t)}(t.__internalId):t));const j="_blazorSelectValue",J=document.createElement("template"),$=document.createElementNS("http://www.w3.org/2000/svg","g"),K={},z="__internal_",V="preventDefault_",X="stopPropagation_";class Y{constructor(e){this.childComponentLocations={},this.eventDelegator=new y(e),this.eventDelegator.notifyAfterClick((e=>{if(!ee)return;if(0!==e.button||function(e){return e.ctrlKey||e.shiftKey||e.altKey||e.metaKey}(e))return;if(e.defaultPrevented)return;const t=function(e){const t=!window._blazorDisableComposedPath&&e.composedPath&&e.composedPath();if(t){for(let e=0;eie(!1))))},enableNavigationInterception:function(){ee=!0},navigateTo:oe,getBaseURI:()=>document.baseURI,getLocationHref:()=>location.href};function oe(e,t,n=!1){const r=ce(e);if(!t&&ue(r))ae(r,!1,n);else if(t&&location.href===e){const t=e+"?";history.replaceState(null,"",t),location.replace(e)}else n?history.replaceState(null,"",r):location.href=e}function ae(e,t,n=!1){Q=!0,n?history.replaceState(null,"",e):history.pushState(null,"",e),ie(t)}async function ie(e){ne&&await ne(location.href,e)}let se;function ce(e){return se=se||document.createElement("a"),se.href=e,se.href}function le(e,t){return e?e.tagName===t?e:le(e.parentElement,t):null}function ue(e){const t=(n=document.baseURI).substr(0,n.lastIndexOf("/")+1);var n;return e.startsWith(t)}const de={init:function(e,t,n,r=50){const o=fe(t);(o||document.documentElement).style.overflowAnchor="none";const a=new IntersectionObserver((function(r){r.forEach((r=>{var o;if(!r.isIntersecting)return;const a=t.getBoundingClientRect(),i=n.getBoundingClientRect().top-a.bottom,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`});a.observe(t),a.observe(n);const i=c(t),s=c(n);function c(e){const t=new MutationObserver((()=>{a.unobserve(e),a.observe(e)}));return t.observe(e,{attributes:!0}),t}he[e._id]={intersectionObserver:a,mutationObserverBefore:i,mutationObserverAfter:s}},dispose:function(e){const t=he[e._id];t&&(t.intersectionObserver.disconnect(),t.mutationObserverBefore.disconnect(),t.mutationObserverAfter.disconnect(),e.dispose(),delete he[e._id])}},he={};function fe(e){return e?"visible"!==getComputedStyle(e).overflowY?e:fe(e.parentElement):null}const me={navigateTo:oe,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]),l.forEach((n=>n(e,t.browserEventName)))}i.set(e,t)},_internal:{navigationManager:re,domWrapper:{focus:function(e,t){if(!(e instanceof HTMLElement))throw new Error("Unable to focus an invalid element.");e.focus({preventScroll:t})},focusBySelector:function(e){const t=document.querySelector(e);t&&(t.hasAttribute("tabindex")||(t.tabIndex=-1),t.focus())}},Virtualize:de}};window.Blazor=me;let pe=!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("")},be=Math.pow(2,32),ye=Math.pow(2,21)-1;function we(e,t){return e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24}function Ee(e,t){return e[t]+(e[t+1]<<8)+(e[t+2]<<16)+(e[t+3]<<24>>>0)}function Ie(e,t){const n=Ee(e,t+4);if(n>ye)throw new Error(`Cannot read uint64 with high order part ${n}, because the result would exceed Number.MAX_SAFE_INTEGER.`);return n*be+Ee(e,t)}class Se{constructor(e){this.batchData=e;const t=new Te(e);this.arrayRangeReader=new Ne(e),this.arrayBuilderSegmentReader=new Re(e),this.diffReader=new De(e),this.editReader=new Ce(e,t),this.frameReader=new Ae(e,t)}updatedComponents(){return we(this.batchData,this.batchData.length-20)}referenceFrames(){return we(this.batchData,this.batchData.length-16)}disposedComponentIds(){return we(this.batchData,this.batchData.length-12)}disposedEventHandlerIds(){return we(this.batchData,this.batchData.length-8)}updatedComponentsEntry(e,t){const n=e+4*t;return we(this.batchData,n)}referenceFramesEntry(e,t){return e+20*t}disposedComponentIdsEntry(e,t){const n=e+4*t;return we(this.batchData,n)}disposedEventHandlerIdsEntry(e,t){const n=e+8*t;return Ie(this.batchData,n)}}class De{constructor(e){this.batchDataUint8=e}componentId(e){return we(this.batchDataUint8,e)}edits(e){return e+4}editsEntry(e,t){return e+16*t}}class Ce{constructor(e,t){this.batchDataUint8=e,this.stringReader=t}editType(e){return we(this.batchDataUint8,e)}siblingIndex(e){return we(this.batchDataUint8,e+4)}newTreeIndex(e){return we(this.batchDataUint8,e+8)}moveToSiblingIndex(e){return we(this.batchDataUint8,e+8)}removedAttributeName(e){const t=we(this.batchDataUint8,e+12);return this.stringReader.readString(t)}}class Ae{constructor(e,t){this.batchDataUint8=e,this.stringReader=t}frameType(e){return we(this.batchDataUint8,e)}subtreeLength(e){return we(this.batchDataUint8,e+4)}elementReferenceCaptureId(e){const t=we(this.batchDataUint8,e+4);return this.stringReader.readString(t)}componentId(e){return we(this.batchDataUint8,e+8)}elementName(e){const t=we(this.batchDataUint8,e+8);return this.stringReader.readString(t)}textContent(e){const t=we(this.batchDataUint8,e+4);return this.stringReader.readString(t)}markupContent(e){const t=we(this.batchDataUint8,e+4);return this.stringReader.readString(t)}attributeName(e){const t=we(this.batchDataUint8,e+4);return this.stringReader.readString(t)}attributeValue(e){const t=we(this.batchDataUint8,e+8);return this.stringReader.readString(t)}attributeEventHandlerId(e){return Ie(this.batchDataUint8,e+12)}}class Te{constructor(e){this.batchDataUint8=e,this.stringTableStartIndex=we(e,e.length-4)}readString(e){if(-1===e)return null;{const n=we(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)<{!function(e,t,n){const r=document.querySelector(e);if(!r)throw new Error(`Could not find any element matching selector '${e}'.`);!function(e,t,n){let r=Z[0];r||(r=Z[0]=new Y(0)),r.attachRootComponentToLogicalElement(n,t)}(0,A(r,!0),t)}(t,e)},RenderBatch:(e,t)=>{try{const n=Me(t);(function(e,t){const n=Z[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{Fe=!0,console.error(`${e}\n${t}`),async function(){let e=document.querySelector("#blazor-error-ui");e&&(e.style.display="block"),pe||(pe=!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:e.jsCallDispatcher.beginInvokeJSFromDotNet,EndInvokeDotNet:e.jsCallDispatcher.endInvokeDotNetFromJS,SendByteArrayToJS:He,Navigate:re.navigateTo};window.external.receiveMessage((e=>{const n=function(e){if(Fe||!e||!e.startsWith(ke))return null;const t=e.substring(ke.length),[n,...r]=JSON.parse(t);return{messageType:n,args:r}}(e);if(n){if(!t.hasOwnProperty(n.messageType))throw new Error(`Unsupported IPC message type '${n.messageType}'`);t[n.messageType].apply(null,n.args)}}))}(),e.attachDispatcher({beginInvokeDotNetFromJS:Oe,endInvokeJSFromDotNet:xe,sendByteArray:Be}),me._internal.InputFile=Ue,re.enableNavigationInterception(),re.listenForNavigationEvents(Le),Pe("AttachPage",re.getBaseURI(),re.getLocationHref())}o=function(e,t){Pe("DispatchBrowserEvent",e,t)},me.start=Ke,document&&document.currentScript&&"false"!==document.currentScript.getAttribute("autostart")&&Ke()})(); \ No newline at end of file diff --git a/src/Components/test/E2ETest/Tests/InteropTest.cs b/src/Components/test/E2ETest/Tests/InteropTest.cs index fb0da802cc18..a9f1340db565 100644 --- a/src/Components/test/E2ETest/Tests/InteropTest.cs +++ b/src/Components/test/E2ETest/Tests/InteropTest.cs @@ -63,7 +63,10 @@ public void CanInvokeDotNetMethods() ["roundTripByteArrayWrapperObjectAsyncFromJS"] = @"{""strVal"":""Some string"",""byteArrayVal"":{""0"":1,""1"":5,""2"":7,""3"":17,""4"":200,""5"":138},""intVal"":42}", ["roundTripByteArrayAsyncFromDotNet"] = @"1,5,7,15,35,200", ["roundTripByteArrayWrapperObjectAsyncFromDotNet"] = @"StrVal: Some String, IntVal: 100000, ByteArrayVal: 1,5,7,15,35,200", - ["jsToDotNetStreamAsync"] = "Success", + ["jsToDotNetStreamReturnValueAsync"] = "Success", + ["jsToDotNetStreamWrapperObjectReturnValueAsync"] = "Success", + ["jsToDotNetStreamParameterAsync"] = @"""Success""", + ["jsToDotNetStreamWrapperObjectParameterAsync"] = @"""Success""", ["AsyncThrowSyncException"] = @"""System.InvalidOperationException: Threw a sync exception!", ["AsyncThrowAsyncException"] = @"""System.InvalidOperationException: Threw an async exception!", ["SyncExceptionFromAsyncMethod"] = "Function threw a sync exception!", diff --git a/src/Components/test/testassets/BasicTestApp/InteropComponent.razor b/src/Components/test/testassets/BasicTestApp/InteropComponent.razor index c4e552dcce35..78e48a17cda1 100644 --- a/src/Components/test/testassets/BasicTestApp/InteropComponent.razor +++ b/src/Components/test/testassets/BasicTestApp/InteropComponent.razor @@ -3,6 +3,7 @@ @using System.Runtime.InteropServices @using System.Text.Json @using System.IO +@using static BasicTestApp.InteropTest.JSDataReferenceInterop @inject IJSRuntime JSRuntime @@ -177,44 +178,68 @@ } // Streaming interop tests need to be run only for Blazor server - // As such, we set the result of `jsToDotNetStreamAsync` to the expected result for WASM + // As such, we set the results to the expected result for WASM if (shouldSupportSyncInterop) { // In the WASM case, setting the result to the expected result ensures the missing test case doesn't result in test failure. - ReturnValues["jsToDotNetStreamAsync"] = "Success"; + ReturnValues["jsToDotNetStreamReturnValueAsync"] = "Success"; + ReturnValues["jsToDotNetStreamWrapperObjectReturnValueAsync"] = "Success"; } else { // Proceed to run the actual blazor server streaming interop tests - var dataReference = await JSRuntime.InvokeAsync("jsToDotNetStreamAsync"); - using var stream = await dataReference.OpenReadStreamAsync(); - using var memoryStream = new System.IO.MemoryStream(); - await stream.CopyToAsync(memoryStream); - var buffer = memoryStream.ToArray(); - for (var i = 0; i < buffer.Length; i++) + // Test: jsToDotNetStreamReturnValueAsync + var dataReference = await JSRuntime.InvokeAsync("jsToDotNetStreamReturnValueAsync"); + using var dataReferenceStream = await dataReference.OpenReadStreamAsync(); + await ValidateStreamValuesAsync("jsToDotNetStreamReturnValueAsync", dataReferenceStream); + + // Test: jsToDotNetStreamWrapperObjectReturnValueAsync + var dataWrapperReference = await JSRuntime.InvokeAsync("jsToDotNetStreamWrapperObjectReturnValueAsync"); + if (dataWrapperReference.StrVal != "SomeStr") { - var expectedValue = i % 256; - if (buffer[i] != expectedValue) - { - ReturnValues["jsToDotNetStreamAsync"] = $"Failure at index {i}."; - break; - } + ReturnValues["jsToDotNetStreamWrapperObjectReturnValueAsync"] = $"StrVal did not match expected 'SomeStr', received {dataWrapperReference.StrVal}."; } - - if (buffer.Length != 100_000) + else if (dataWrapperReference.IntVal != 5) { - ReturnValues["jsToDotNetStreamAsync"] = $"Failure, got a stream of length {buffer.Length}, expected a length of 50,000."; + ReturnValues["jsToDotNetStreamWrapperObjectReturnValueAsync"] = $"IntVal did not match expected '5', received {dataWrapperReference.IntVal}."; + } + else + { + using var dataWrapperReferenceStream = await dataWrapperReference.JSDataReferenceVal.OpenReadStreamAsync(); + await ValidateStreamValuesAsync("jsToDotNetStreamWrapperObjectReturnValueAsync", dataWrapperReferenceStream); } - - // Mark the test as successful if we haven't already set a failure above - ReturnValues.TryAdd("jsToDotNetStreamAsync", "Success"); } Invocations = invocations; DoneWithInterop = true; } + private async Task ValidateStreamValuesAsync(string testName, Stream stream) + { + using var memoryStream = new System.IO.MemoryStream(); + await stream.CopyToAsync(memoryStream); + var buffer = memoryStream.ToArray(); + + for (var i = 0; i < buffer.Length; i++) + { + var expectedValue = i % 256; + if (buffer[i] != expectedValue) + { + ReturnValues[testName] = $"Failure at index {i}."; + break; + } + } + + if (buffer.Length != 100_000) + { + ReturnValues[testName] = $"Failure, got a stream of length {buffer.Length}, expected a length of 100,000."; + } + + // Mark the test as successful if we haven't already set a failure above + ReturnValues.TryAdd(testName, "Success"); + } + public void InvokeInProcessInterop() { var inProcRuntime = ((IJSInProcessRuntime)JSRuntime); diff --git a/src/Components/test/testassets/BasicTestApp/InteropTest/JSDataReferenceInterop.cs b/src/Components/test/testassets/BasicTestApp/InteropTest/JSDataReferenceInterop.cs index d959ad470eb5..ebe62fc8ffbf 100644 --- a/src/Components/test/testassets/BasicTestApp/InteropTest/JSDataReferenceInterop.cs +++ b/src/Components/test/testassets/BasicTestApp/InteropTest/JSDataReferenceInterop.cs @@ -1,6 +1,8 @@ // Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. +using System.IO; +using System.Text.Json.Serialization; using System.Threading.Tasks; using Microsoft.JSInterop; @@ -9,27 +11,61 @@ namespace BasicTestApp.InteropTest public class JSDataReferenceInterop { [JSInvokable] - public static Task RoundTripJSDataReferenceAsync(IJSDataReference jsDataReference) + public static async Task JSToDotNetStreamParameterAsync(IJSDataReference jsDataReference) { - return Task.FromResult(jsDataReference); + using var dataReferenceStream = await jsDataReference.OpenReadStreamAsync(); + return await ValidateStreamValuesAsync(dataReferenceStream); } [JSInvokable] - public static Task RoundTripJSDataReferenceWrapperObjectAsync(JSDataReferenceWrapper jsDataReferenceWrapper) + public static async Task JSToDotNetStreamWrapperObjectParameterAsync(JSDataReferenceWrapper jsDataReferenceWrapper) { - return Task.FromResult(jsDataReferenceWrapper); + if (jsDataReferenceWrapper.StrVal != "SomeStr") + { + return $"StrVal did not match expected 'SomeStr', received {jsDataReferenceWrapper.StrVal}."; + } + else if (jsDataReferenceWrapper.IntVal != 5) + { + return $"IntVal did not match expected '5', received {jsDataReferenceWrapper.IntVal}."; + } + else + { + using var dataWrapperReferenceStream = await jsDataReferenceWrapper.JSDataReferenceVal.OpenReadStreamAsync(); + return await ValidateStreamValuesAsync(dataWrapperReferenceStream); + } + } + + private static async Task ValidateStreamValuesAsync(Stream stream) + { + using var memoryStream = new MemoryStream(); + await stream.CopyToAsync(memoryStream); + var buffer = memoryStream.ToArray(); + + for (var i = 0; i < buffer.Length; i++) + { + var expectedValue = i % 256; + if (buffer[i] != expectedValue) + { + return $"Failure at index {i}."; + } + } + + if (buffer.Length != 100_000) + { + return $"Failure, got a stream of length {buffer.Length}, expected a length of 100,000."; + } + + return "Success"; } public class JSDataReferenceWrapper { public string StrVal { get; set; } + + [JsonPropertyName("jsDataReferenceVal")] public IJSDataReference JSDataReferenceVal { get; set; } - public int IntVal { get; set; } - public override string ToString() - { - return $"StrVal: {StrVal}, IntVal: {IntVal}, JSDataReferenceVal: {string.Join(',', JSDataReferenceVal)}"; - } + public int IntVal { get; set; } } } } diff --git a/src/Components/test/testassets/BasicTestApp/wwwroot/js/jsinteroptests.js b/src/Components/test/testassets/BasicTestApp/wwwroot/js/jsinteroptests.js index e31c7826d84b..9f87abc58d03 100644 --- a/src/Components/test/testassets/BasicTestApp/wwwroot/js/jsinteroptests.js +++ b/src/Components/test/testassets/BasicTestApp/wwwroot/js/jsinteroptests.js @@ -104,6 +104,19 @@ async function invokeDotNetInteropMethodsAsync(shouldSupportSyncInterop, dotNetO var returnedByteArrayWrapper = await DotNet.invokeMethodAsync(assemblyName, 'RoundTripByteArrayWrapperObjectAsync', byteArrayWrapper); results['roundTripByteArrayWrapperObjectAsyncFromJS'] = returnedByteArrayWrapper; + if (shouldSupportSyncInterop) { + results['jsToDotNetStreamParameterAsync'] = "Success"; + results['jsToDotNetStreamWrapperObjectParameterAsync'] = "Success"; + } else { + const largeArray = Array.from({ length: 100000 }).map((_, index) => index % 256); + const largeByteArray = new Uint8Array(largeArray); + const jsStreamReference = DotNet.createJSDataReference(largeByteArray); + results['jsToDotNetStreamParameterAsync'] = await DotNet.invokeMethodAsync(assemblyName, 'JSToDotNetStreamParameterAsync', jsStreamReference); + + var streamWrapper = { 'strVal': "SomeStr", 'jsDataReferenceVal': jsStreamReference, 'intVal': 5 }; + results['jsToDotNetStreamWrapperObjectParameterAsync'] = await DotNet.invokeMethodAsync(assemblyName, 'JSToDotNetStreamWrapperObjectParameterAsync', streamWrapper); + } + const instanceMethodAsync = await instanceMethodsTarget.invokeMethodAsync('InstanceMethodAsync', { stringValue: 'My string', dtoByRef: dotNetObjectByRef @@ -260,7 +273,7 @@ function roundTripByteArrayWrapperObject(byteArrayWrapperObject) { return byteArrayWrapperObject; } -function jsToDotNetStreamAsync() { +function jsToDotNetStreamReturnValueAsync() { return new Promise((resolve, reject) => { setTimeout(function () { const largeArray = Array.from({ length: 100000 }).map((_, index) => index % 256); @@ -269,6 +282,18 @@ function jsToDotNetStreamAsync() { }); } +function jsToDotNetStreamWrapperObjectReturnValueAsync() { + return new Promise((resolve, reject) => { + setTimeout(function () { + const largeArray = Array.from({ length: 100000 }).map((_, index) => index % 256); + const byteArray = new Uint8Array(largeArray); + const jsStreamReference = DotNet.createJSDataReference(byteArray); + const returnValue = { strVal: 'SomeStr', intVal: 5, jsDataReferenceVal: jsStreamReference } + resolve(returnValue); + }, 100); + }); +} + function roundTripByteArrayWrapperObjectAsync(byteArrayWrapperObject) { return new Promise((resolve, reject) => { setTimeout(function () { diff --git a/src/JSInterop/Microsoft.JSInterop.JS/src/src/Microsoft.JSInterop.ts b/src/JSInterop/Microsoft.JSInterop.JS/src/src/Microsoft.JSInterop.ts index 39c07927b8d9..8ea680a200a1 100644 --- a/src/JSInterop/Microsoft.JSInterop.JS/src/src/Microsoft.JSInterop.ts +++ b/src/JSInterop/Microsoft.JSInterop.JS/src/src/Microsoft.JSInterop.ts @@ -142,28 +142,28 @@ export module DotNet { /** * Creates a JavaScript data reference that can be passed to .NET via interop calls. * - * @param jsObject The JavaScript Object used to create the JavaScript data reference. + * @param arrayBufferView The ArrayBufferView used to create the JavaScript stream reference. * @returns The JavaScript data reference (this will be the same instance as the given object). * @throws Error if the given value is not an Object or doesn't have a valid byteLength. */ - export function createJSDataReference(jsObject: any): any { + export function createJSDataReference(arrayBufferView: ArrayBufferView | any): any { // Check if this is an ArrayBufferView, and if it has a valid byteLength for transfer // using a JSDataReference. - if (!(jsObject.buffer instanceof ArrayBuffer)) { - throw new Error(`Cannot create a JSDataReference from the value '${jsObject}' as it is not a valid ArrayBuffer.`); - } else if (jsObject.byteLength === undefined) { - throw new Error(`Cannot create a JSDataReference from the value '${jsObject}' as it doesn't have a byteLength.`); + if (!(arrayBufferView.buffer instanceof ArrayBuffer)) { + throw new Error(`Cannot create a JSDataReference from the value '${arrayBufferView}' as it is not a valid ArrayBuffer.`); + } else if (arrayBufferView.byteLength === undefined) { + throw new Error(`Cannot create a JSDataReference from the value '${arrayBufferView}' as it doesn't have a byteLength.`); } const result: any = { - [jsDataReferenceLengthKey]: jsObject.byteLength, + [jsDataReferenceLengthKey]: arrayBufferView.byteLength, } try { - const jsObjectReference = createJSObjectReference(jsObject); + const jsObjectReference = createJSObjectReference(arrayBufferView); result[jsObjectIdKey] = jsObjectReference[jsObjectIdKey]; } catch { - throw new Error(`Cannot create a JSDataReference from the value '${jsObject}'.`); + throw new Error(`Cannot create a JSStreamReference from the value '${arrayBufferView}'.`); } return result; From 903b16dc5a288551e6d634b0e67150a846dd1460 Mon Sep 17 00:00:00 2001 From: Tanay Parikh Date: Fri, 18 Jun 2021 16:44:19 -0700 Subject: [PATCH 25/37] JSDataReference->JSStreamReference --- .../Server/src/Circuits/RemoteJSDataStream.cs | 3 +- .../Server/src/Circuits/RemoteJSRuntime.cs | 4 +-- .../test/Circuits/RemoteJSDataStreamTest.cs | 14 ++++---- src/Components/Web.JS/src/Boot.WebAssembly.ts | 2 +- .../InputFile/RemoteBrowserFileStream.cs | 2 +- .../JSInterop/src/WebAssemblyJSRuntime.cs | 2 +- .../BasicTestApp/InteropComponent.razor | 8 ++--- ...Interop.cs => JSStreamReferenceInterop.cs} | 24 ++++++------- .../BasicTestApp/wwwroot/js/jsinteroptests.js | 8 ++--- .../src/src/Microsoft.JSInterop.ts | 18 +++++----- ...DataReference.cs => IJSStreamReference.cs} | 2 +- ...SDataReference.cs => JSStreamReference.cs} | 10 +++--- ...r.cs => JSStreamReferenceJsonConverter.cs} | 20 +++++------ .../src/JSCallResultType.cs | 2 +- .../Microsoft.JSInterop/src/JSRuntime.cs | 10 +++--- .../src/PublicAPI.Unshipped.txt | 14 ++++---- ... => JSStreamReferenceJsonConverterTest.cs} | 34 +++++++++---------- .../Microsoft.JSInterop/test/JSRuntimeTest.cs | 2 +- .../JSInterop/JSCallResultTypeHelper.cs | 4 +-- 19 files changed, 91 insertions(+), 92 deletions(-) rename src/Components/test/testassets/BasicTestApp/InteropTest/{JSDataReferenceInterop.cs => JSStreamReferenceInterop.cs} (69%) rename src/JSInterop/Microsoft.JSInterop/src/{IJSDataReference.cs => IJSStreamReference.cs} (95%) rename src/JSInterop/Microsoft.JSInterop/src/Implementation/{JSDataReference.cs => JSStreamReference.cs} (75%) rename src/JSInterop/Microsoft.JSInterop/src/Infrastructure/{JSDataReferenceJsonConverter.cs => JSStreamReferenceJsonConverter.cs} (69%) rename src/JSInterop/Microsoft.JSInterop/test/Infrastructure/{JSDataReferenceJsonConverterTest.cs => JSStreamReferenceJsonConverterTest.cs} (69%) diff --git a/src/Components/Server/src/Circuits/RemoteJSDataStream.cs b/src/Components/Server/src/Circuits/RemoteJSDataStream.cs index cfde4041a58c..ab3bf16c6635 100644 --- a/src/Components/Server/src/Circuits/RemoteJSDataStream.cs +++ b/src/Components/Server/src/Circuits/RemoteJSDataStream.cs @@ -2,7 +2,6 @@ // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; -using System.Buffers; using System.IO; using System.IO.Pipelines; using System.Threading; @@ -35,7 +34,7 @@ public static async Task ReceiveData(RemoteJSRuntime runtime, long streamI public static async ValueTask CreateRemoteJSDataStreamAsync( RemoteJSRuntime runtime, - IJSDataReference jsDataReference, + IJSStreamReference jsStreamReference, long totalLength, long maxBufferSize, long maximumIncomingBytes, diff --git a/src/Components/Server/src/Circuits/RemoteJSRuntime.cs b/src/Components/Server/src/Circuits/RemoteJSRuntime.cs index 0979826f6642..54157ddb1599 100644 --- a/src/Components/Server/src/Circuits/RemoteJSRuntime.cs +++ b/src/Components/Server/src/Circuits/RemoteJSRuntime.cs @@ -147,8 +147,8 @@ public void MarkPermanentlyDisconnected() _clientProxy = null; } - protected override async Task ReadJSDataAsStreamAsync(IJSDataReference jsDataReference, long totalLength, long maxBufferSize, CancellationToken cancellationToken) - => await RemoteJSDataStream.CreateRemoteJSDataStreamAsync(this, jsDataReference, totalLength, maxBufferSize, _maximumIncomingBytes, cancellationToken); + protected override async Task ReadJSDataAsStreamAsync(IJSStreamReference jsStreamReference, long totalLength, long maxBufferSize, CancellationToken cancellationToken) + => await RemoteJSDataStream.CreateRemoteJSDataStreamAsync(this, jsStreamReference, totalLength, maxBufferSize, _maximumIncomingBytes, cancellationToken); public static class Log { diff --git a/src/Components/Server/test/Circuits/RemoteJSDataStreamTest.cs b/src/Components/Server/test/Circuits/RemoteJSDataStreamTest.cs index 140cf0b6db89..1f6a89a66e69 100644 --- a/src/Components/Server/test/Circuits/RemoteJSDataStreamTest.cs +++ b/src/Components/Server/test/Circuits/RemoteJSDataStreamTest.cs @@ -21,10 +21,10 @@ public class RemoteJSDataStreamTest public async void CreateRemoteJSDataStreamAsync_CreatesStream() { // Arrange - var jsDataReference = Mock.Of(); + var jsStreamReference = Mock.Of(); // Act - var remoteJSDataStream = await RemoteJSDataStream.CreateRemoteJSDataStreamAsync(_jsRuntime, jsDataReference, totalLength: 100, maxBufferSize: 50, maximumIncomingBytes: 10_000); + var remoteJSDataStream = await RemoteJSDataStream.CreateRemoteJSDataStreamAsync(_jsRuntime, jsStreamReference, totalLength: 100, maxBufferSize: 50, maximumIncomingBytes: 10_000); // Assert Assert.NotNull(remoteJSDataStream); @@ -96,10 +96,10 @@ public async void ReceiveData_ProvidedWithMoreBytesThanRemaining() { // Arrange var jsRuntime = new TestRemoteJSRuntime(Options.Create(new CircuitOptions()), Options.Create(new HubOptions()), Mock.Of>()); - var jsDataReference = Mock.Of(); - var remoteJSDataStream = await RemoteJSDataStream.CreateRemoteJSDataStreamAsync(jsRuntime, jsDataReference, totalLength: 100, maxBufferSize: 50, maximumIncomingBytes: 10_000); + var jsStreamReference = Mock.Of(); + var remoteJSDataStream = await RemoteJSDataStream.CreateRemoteJSDataStreamAsync(jsRuntime, jsStreamReference, totalLength: 100, maxBufferSize: 50, maximumIncomingBytes: 10_000); var streamId = GetStreamId(remoteJSDataStream, jsRuntime); - var chunk = new byte[110]; // 100 byte totalLength for stream + var chunk = new byte[110]; // 100 byte totalLength for stream // Act var success = await RemoteJSDataStream.ReceiveData(jsRuntime, streamId, chunk, error: null); @@ -110,8 +110,8 @@ public async void ReceiveData_ProvidedWithMoreBytesThanRemaining() private static async Task CreateRemoteJSDataStreamAsync(TestRemoteJSRuntime jsRuntime = null) { - var jsDataReference = Mock.Of(); - var remoteJSDataStream = await RemoteJSDataStream.CreateRemoteJSDataStreamAsync(jsRuntime ?? _jsRuntime, jsDataReference, totalLength: 100, maxBufferSize: 50, maximumIncomingBytes: 10_000); + var jsStreamReference = Mock.Of(); + var remoteJSDataStream = await RemoteJSDataStream.CreateRemoteJSDataStreamAsync(jsRuntime ?? _jsRuntime, jsStreamReference, totalLength: 100, maxBufferSize: 50, maximumIncomingBytes: 10_000); return remoteJSDataStream; } diff --git a/src/Components/Web.JS/src/Boot.WebAssembly.ts b/src/Components/Web.JS/src/Boot.WebAssembly.ts index 0abdf3c4006c..cf153a4a4988 100644 --- a/src/Components/Web.JS/src/Boot.WebAssembly.ts +++ b/src/Components/Web.JS/src/Boot.WebAssembly.ts @@ -153,7 +153,7 @@ function invokeJSFromDotNet(callInfo: Pointer, arg0: any, arg1: any, arg2: any): return result; case DotNet.JSCallResultType.JSObjectReference: return DotNet.createJSObjectReference(result).__jsObjectId; - case DotNet.JSCallResultType.JSDataReference: + case DotNet.JSCallResultType.JSStreamReference: default: throw new Error(`Invalid JS call result type '${resultType}'.`); } diff --git a/src/Components/Web/src/Forms/InputFile/RemoteBrowserFileStream.cs b/src/Components/Web/src/Forms/InputFile/RemoteBrowserFileStream.cs index bd726531ae74..cb8b21714173 100644 --- a/src/Components/Web/src/Forms/InputFile/RemoteBrowserFileStream.cs +++ b/src/Components/Web/src/Forms/InputFile/RemoteBrowserFileStream.cs @@ -39,7 +39,7 @@ public RemoteBrowserFileStream( private async Task OpenReadStreamAsync(RemoteBrowserFileStreamOptions options, CancellationToken cancellationToken) { - var dataReference = await _jsRuntime.InvokeAsync( + var dataReference = await _jsRuntime.InvokeAsync( InputFileInterop.ReadFileData, cancellationToken, _inputFileElement, diff --git a/src/Components/WebAssembly/JSInterop/src/WebAssemblyJSRuntime.cs b/src/Components/WebAssembly/JSInterop/src/WebAssemblyJSRuntime.cs index 942a916d5a5f..06eaba3ff592 100644 --- a/src/Components/WebAssembly/JSInterop/src/WebAssemblyJSRuntime.cs +++ b/src/Components/WebAssembly/JSInterop/src/WebAssemblyJSRuntime.cs @@ -101,7 +101,7 @@ internal TResult InvokeUnmarshalled(string identifier, T0 a return exception != null ? throw new JSException(exception) : (TResult)(object)new WebAssemblyJSObjectReference(this, id); - case JSCallResultType.JSDataReference: + case JSCallResultType.JSStreamReference: default: throw new InvalidOperationException($"Invalid result type '{resultType}'."); } diff --git a/src/Components/test/testassets/BasicTestApp/InteropComponent.razor b/src/Components/test/testassets/BasicTestApp/InteropComponent.razor index 78e48a17cda1..c2aafa5f67ad 100644 --- a/src/Components/test/testassets/BasicTestApp/InteropComponent.razor +++ b/src/Components/test/testassets/BasicTestApp/InteropComponent.razor @@ -3,7 +3,7 @@ @using System.Runtime.InteropServices @using System.Text.Json @using System.IO -@using static BasicTestApp.InteropTest.JSDataReferenceInterop +@using static BasicTestApp.InteropTest.JSStreamReferenceInterop @inject IJSRuntime JSRuntime @@ -190,12 +190,12 @@ // Proceed to run the actual blazor server streaming interop tests // Test: jsToDotNetStreamReturnValueAsync - var dataReference = await JSRuntime.InvokeAsync("jsToDotNetStreamReturnValueAsync"); + var dataReference = await JSRuntime.InvokeAsync("jsToDotNetStreamReturnValueAsync"); using var dataReferenceStream = await dataReference.OpenReadStreamAsync(); await ValidateStreamValuesAsync("jsToDotNetStreamReturnValueAsync", dataReferenceStream); // Test: jsToDotNetStreamWrapperObjectReturnValueAsync - var dataWrapperReference = await JSRuntime.InvokeAsync("jsToDotNetStreamWrapperObjectReturnValueAsync"); + var dataWrapperReference = await JSRuntime.InvokeAsync("jsToDotNetStreamWrapperObjectReturnValueAsync"); if (dataWrapperReference.StrVal != "SomeStr") { ReturnValues["jsToDotNetStreamWrapperObjectReturnValueAsync"] = $"StrVal did not match expected 'SomeStr', received {dataWrapperReference.StrVal}."; @@ -206,7 +206,7 @@ } else { - using var dataWrapperReferenceStream = await dataWrapperReference.JSDataReferenceVal.OpenReadStreamAsync(); + using var dataWrapperReferenceStream = await dataWrapperReference.JSStreamReferenceVal.OpenReadStreamAsync(); await ValidateStreamValuesAsync("jsToDotNetStreamWrapperObjectReturnValueAsync", dataWrapperReferenceStream); } } diff --git a/src/Components/test/testassets/BasicTestApp/InteropTest/JSDataReferenceInterop.cs b/src/Components/test/testassets/BasicTestApp/InteropTest/JSStreamReferenceInterop.cs similarity index 69% rename from src/Components/test/testassets/BasicTestApp/InteropTest/JSDataReferenceInterop.cs rename to src/Components/test/testassets/BasicTestApp/InteropTest/JSStreamReferenceInterop.cs index ebe62fc8ffbf..c47a07557f09 100644 --- a/src/Components/test/testassets/BasicTestApp/InteropTest/JSDataReferenceInterop.cs +++ b/src/Components/test/testassets/BasicTestApp/InteropTest/JSStreamReferenceInterop.cs @@ -8,29 +8,29 @@ namespace BasicTestApp.InteropTest { - public class JSDataReferenceInterop + public class JSStreamReferenceInterop { [JSInvokable] - public static async Task JSToDotNetStreamParameterAsync(IJSDataReference jsDataReference) + public static async Task JSToDotNetStreamParameterAsync(IJSStreamReference jsStreamReference) { - using var dataReferenceStream = await jsDataReference.OpenReadStreamAsync(); + using var dataReferenceStream = await jsStreamReference.OpenReadStreamAsync(); return await ValidateStreamValuesAsync(dataReferenceStream); } [JSInvokable] - public static async Task JSToDotNetStreamWrapperObjectParameterAsync(JSDataReferenceWrapper jsDataReferenceWrapper) + public static async Task JSToDotNetStreamWrapperObjectParameterAsync(JSStreamReferenceWrapper jsStreamReferenceWrapper) { - if (jsDataReferenceWrapper.StrVal != "SomeStr") + if (jsStreamReferenceWrapper.StrVal != "SomeStr") { - return $"StrVal did not match expected 'SomeStr', received {jsDataReferenceWrapper.StrVal}."; + return $"StrVal did not match expected 'SomeStr', received {jsStreamReferenceWrapper.StrVal}."; } - else if (jsDataReferenceWrapper.IntVal != 5) + else if (jsStreamReferenceWrapper.IntVal != 5) { - return $"IntVal did not match expected '5', received {jsDataReferenceWrapper.IntVal}."; + return $"IntVal did not match expected '5', received {jsStreamReferenceWrapper.IntVal}."; } else { - using var dataWrapperReferenceStream = await jsDataReferenceWrapper.JSDataReferenceVal.OpenReadStreamAsync(); + using var dataWrapperReferenceStream = await jsStreamReferenceWrapper.JSStreamReferenceVal.OpenReadStreamAsync(); return await ValidateStreamValuesAsync(dataWrapperReferenceStream); } } @@ -58,12 +58,12 @@ private static async Task ValidateStreamValuesAsync(Stream stream) return "Success"; } - public class JSDataReferenceWrapper + public class JSStreamReferenceWrapper { public string StrVal { get; set; } - [JsonPropertyName("jsDataReferenceVal")] - public IJSDataReference JSDataReferenceVal { get; set; } + [JsonPropertyName("jsStreamReferenceVal")] + public IJSStreamReference JSStreamReferenceVal { get; set; } public int IntVal { get; set; } } diff --git a/src/Components/test/testassets/BasicTestApp/wwwroot/js/jsinteroptests.js b/src/Components/test/testassets/BasicTestApp/wwwroot/js/jsinteroptests.js index 9f87abc58d03..ec639e1026f0 100644 --- a/src/Components/test/testassets/BasicTestApp/wwwroot/js/jsinteroptests.js +++ b/src/Components/test/testassets/BasicTestApp/wwwroot/js/jsinteroptests.js @@ -110,10 +110,10 @@ async function invokeDotNetInteropMethodsAsync(shouldSupportSyncInterop, dotNetO } else { const largeArray = Array.from({ length: 100000 }).map((_, index) => index % 256); const largeByteArray = new Uint8Array(largeArray); - const jsStreamReference = DotNet.createJSDataReference(largeByteArray); + const jsStreamReference = DotNet.createJSStreamReference(largeByteArray); results['jsToDotNetStreamParameterAsync'] = await DotNet.invokeMethodAsync(assemblyName, 'JSToDotNetStreamParameterAsync', jsStreamReference); - var streamWrapper = { 'strVal': "SomeStr", 'jsDataReferenceVal': jsStreamReference, 'intVal': 5 }; + var streamWrapper = { 'strVal': "SomeStr", 'jsStreamReferenceVal': jsStreamReference, 'intVal': 5 }; results['jsToDotNetStreamWrapperObjectParameterAsync'] = await DotNet.invokeMethodAsync(assemblyName, 'JSToDotNetStreamWrapperObjectParameterAsync', streamWrapper); } @@ -287,8 +287,8 @@ function jsToDotNetStreamWrapperObjectReturnValueAsync() { setTimeout(function () { const largeArray = Array.from({ length: 100000 }).map((_, index) => index % 256); const byteArray = new Uint8Array(largeArray); - const jsStreamReference = DotNet.createJSDataReference(byteArray); - const returnValue = { strVal: 'SomeStr', intVal: 5, jsDataReferenceVal: jsStreamReference } + const jsStreamReference = DotNet.createJSStreamReference(byteArray); + const returnValue = { strVal: 'SomeStr', intVal: 5, jsStreamReferenceVal: jsStreamReference } resolve(returnValue); }, 100); }); diff --git a/src/JSInterop/Microsoft.JSInterop.JS/src/src/Microsoft.JSInterop.ts b/src/JSInterop/Microsoft.JSInterop.JS/src/src/Microsoft.JSInterop.ts index 8ea680a200a1..fa7530a84d45 100644 --- a/src/JSInterop/Microsoft.JSInterop.JS/src/src/Microsoft.JSInterop.ts +++ b/src/JSInterop/Microsoft.JSInterop.JS/src/src/Microsoft.JSInterop.ts @@ -49,7 +49,7 @@ export module DotNet { } const jsObjectIdKey = "__jsObjectId"; - const jsDataReferenceLengthKey = "__jsDataReferenceLength"; + const jsStreamReferenceLengthKey = "__jsStreamReferenceLength"; const pendingAsyncCalls: { [id: number]: PendingAsyncCall } = {}; const windowJSObjectId = 0; @@ -146,17 +146,17 @@ export module DotNet { * @returns The JavaScript data reference (this will be the same instance as the given object). * @throws Error if the given value is not an Object or doesn't have a valid byteLength. */ - export function createJSDataReference(arrayBufferView: ArrayBufferView | any): any { + export function createJSStreamReference(arrayBufferView: ArrayBufferView | any): any { // Check if this is an ArrayBufferView, and if it has a valid byteLength for transfer - // using a JSDataReference. + // using a JSStreamReference. if (!(arrayBufferView.buffer instanceof ArrayBuffer)) { - throw new Error(`Cannot create a JSDataReference from the value '${arrayBufferView}' as it is not a valid ArrayBuffer.`); + throw new Error(`Cannot create a JSStreamReference from the value '${arrayBufferView}' as it is not a valid ArrayBuffer.`); } else if (arrayBufferView.byteLength === undefined) { - throw new Error(`Cannot create a JSDataReference from the value '${arrayBufferView}' as it doesn't have a byteLength.`); + throw new Error(`Cannot create a JSStreamReference from the value '${arrayBufferView}' as it doesn't have a byteLength.`); } const result: any = { - [jsDataReferenceLengthKey]: arrayBufferView.byteLength, + [jsStreamReferenceLengthKey]: arrayBufferView.byteLength, } try { @@ -263,7 +263,7 @@ export module DotNet { export enum JSCallResultType { Default = 0, JSObjectReference = 1, - JSDataReference = 2, + JSStreamReference = 2, } /** @@ -478,8 +478,8 @@ export module DotNet { return returnValue; case JSCallResultType.JSObjectReference: return createJSObjectReference(returnValue); - case JSCallResultType.JSDataReference: - return createJSDataReference(returnValue); + case JSCallResultType.JSStreamReference: + return createJSStreamReference(returnValue); default: throw new Error(`Invalid JS call result type '${resultType}'.`); } diff --git a/src/JSInterop/Microsoft.JSInterop/src/IJSDataReference.cs b/src/JSInterop/Microsoft.JSInterop/src/IJSStreamReference.cs similarity index 95% rename from src/JSInterop/Microsoft.JSInterop/src/IJSDataReference.cs rename to src/JSInterop/Microsoft.JSInterop/src/IJSStreamReference.cs index 9149aec3b368..4cf01b5763f5 100644 --- a/src/JSInterop/Microsoft.JSInterop/src/IJSDataReference.cs +++ b/src/JSInterop/Microsoft.JSInterop/src/IJSStreamReference.cs @@ -11,7 +11,7 @@ namespace Microsoft.JSInterop /// /// Represents a reference to JavaScript data to be consumed through a . /// - public interface IJSDataReference : IAsyncDisposable + public interface IJSStreamReference : IAsyncDisposable { /// /// Length of the provided by JavaScript. diff --git a/src/JSInterop/Microsoft.JSInterop/src/Implementation/JSDataReference.cs b/src/JSInterop/Microsoft.JSInterop/src/Implementation/JSStreamReference.cs similarity index 75% rename from src/JSInterop/Microsoft.JSInterop/src/Implementation/JSDataReference.cs rename to src/JSInterop/Microsoft.JSInterop/src/Implementation/JSStreamReference.cs index 5446ad3b2677..269bcc9f87d8 100644 --- a/src/JSInterop/Microsoft.JSInterop/src/Implementation/JSDataReference.cs +++ b/src/JSInterop/Microsoft.JSInterop/src/Implementation/JSStreamReference.cs @@ -9,9 +9,9 @@ namespace Microsoft.JSInterop.Implementation { /// - /// Implements functionality for . + /// Implements functionality for . /// - public sealed class JSDataReference : JSObjectReference, IJSDataReference + public sealed class JSStreamReference : JSObjectReference, IJSStreamReference { private readonly JSRuntime _jsRuntime; @@ -19,12 +19,12 @@ public sealed class JSDataReference : JSObjectReference, IJSDataReference public long Length { get; } /// - /// Inititializes a new instance. + /// Inititializes a new instance. /// /// The used for invoking JS interop calls. /// The unique identifier. /// The length of the data stream coming from JS represented by this data reference. - internal JSDataReference(JSRuntime jsRuntime, long id, long totalLength) : base(jsRuntime, id) + internal JSStreamReference(JSRuntime jsRuntime, long id, long totalLength) : base(jsRuntime, id) { if (totalLength <= 0) { @@ -36,7 +36,7 @@ internal JSDataReference(JSRuntime jsRuntime, long id, long totalLength) : base( } /// - async ValueTask IJSDataReference.OpenReadStreamAsync(long maxLength, long maxBufferSize, CancellationToken cancellationToken) + async ValueTask IJSStreamReference.OpenReadStreamAsync(long maxLength, long maxBufferSize, CancellationToken cancellationToken) { if (Length > maxLength) { diff --git a/src/JSInterop/Microsoft.JSInterop/src/Infrastructure/JSDataReferenceJsonConverter.cs b/src/JSInterop/Microsoft.JSInterop/src/Infrastructure/JSStreamReferenceJsonConverter.cs similarity index 69% rename from src/JSInterop/Microsoft.JSInterop/src/Infrastructure/JSDataReferenceJsonConverter.cs rename to src/JSInterop/Microsoft.JSInterop/src/Infrastructure/JSStreamReferenceJsonConverter.cs index 3f31a5b34b5a..0f28bafdee70 100644 --- a/src/JSInterop/Microsoft.JSInterop/src/Infrastructure/JSDataReferenceJsonConverter.cs +++ b/src/JSInterop/Microsoft.JSInterop/src/Infrastructure/JSStreamReferenceJsonConverter.cs @@ -8,21 +8,21 @@ namespace Microsoft.JSInterop.Infrastructure { - internal sealed class JSDataReferenceJsonConverter : JsonConverter + internal sealed class JSStreamReferenceJsonConverter : JsonConverter { - private static readonly JsonEncodedText _jsDataReferenceLengthKey = JsonEncodedText.Encode("__jsDataReferenceLength"); + private static readonly JsonEncodedText _jsStreamReferenceLengthKey = JsonEncodedText.Encode("__jsStreamReferenceLength"); private readonly JSRuntime _jsRuntime; - public JSDataReferenceJsonConverter(JSRuntime jsRuntime) + public JSStreamReferenceJsonConverter(JSRuntime jsRuntime) { _jsRuntime = jsRuntime; } public override bool CanConvert(Type typeToConvert) - => typeToConvert == typeof(IJSDataReference) || typeToConvert == typeof(JSDataReference); + => typeToConvert == typeof(IJSStreamReference) || typeToConvert == typeof(JSStreamReference); - public override IJSDataReference? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + public override IJSStreamReference? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { long? id = null; long? length = null; @@ -36,7 +36,7 @@ public override bool CanConvert(Type typeToConvert) reader.Read(); id = reader.GetInt64(); } - else if (length is null && reader.ValueTextEquals(_jsDataReferenceLengthKey.EncodedUtf8Bytes)) + else if (length is null && reader.ValueTextEquals(_jsStreamReferenceLengthKey.EncodedUtf8Bytes)) { reader.Read(); length = reader.GetInt64(); @@ -59,15 +59,15 @@ public override bool CanConvert(Type typeToConvert) if (!length.HasValue) { - throw new JsonException($"Required property {_jsDataReferenceLengthKey} not found."); + throw new JsonException($"Required property {_jsStreamReferenceLengthKey} not found."); } - return new JSDataReference(_jsRuntime, id.Value, length.Value); + return new JSStreamReference(_jsRuntime, id.Value, length.Value); } - public override void Write(Utf8JsonWriter writer, IJSDataReference value, JsonSerializerOptions options) + public override void Write(Utf8JsonWriter writer, IJSStreamReference value, JsonSerializerOptions options) { - JSObjectReferenceJsonWorker.WriteJSObjectReference(writer, (JSDataReference)value); + JSObjectReferenceJsonWorker.WriteJSObjectReference(writer, (JSStreamReference)value); } } } diff --git a/src/JSInterop/Microsoft.JSInterop/src/JSCallResultType.cs b/src/JSInterop/Microsoft.JSInterop/src/JSCallResultType.cs index 9ff8ee3d9e9c..723d2b7f8644 100644 --- a/src/JSInterop/Microsoft.JSInterop/src/JSCallResultType.cs +++ b/src/JSInterop/Microsoft.JSInterop/src/JSCallResultType.cs @@ -21,6 +21,6 @@ public enum JSCallResultType : int /// /// Indicates that the returned value is to be treated as a JS data reference. /// - JSDataReference = 2, + JSStreamReference = 2, } } diff --git a/src/JSInterop/Microsoft.JSInterop/src/JSRuntime.cs b/src/JSInterop/Microsoft.JSInterop/src/JSRuntime.cs index affcd36d208a..389166ab9b40 100644 --- a/src/JSInterop/Microsoft.JSInterop/src/JSRuntime.cs +++ b/src/JSInterop/Microsoft.JSInterop/src/JSRuntime.cs @@ -41,7 +41,7 @@ protected JSRuntime() { new DotNetObjectReferenceJsonConverterFactory(this), new JSObjectReferenceJsonConverter(this), - new JSDataReferenceJsonConverter(this), + new JSStreamReferenceJsonConverter(this), new ByteArrayJsonConverter(this), } }; @@ -211,14 +211,14 @@ protected internal virtual void ReceiveByteArray(int id, byte[] data) } /// - /// Provides a for the data reference represented by . + /// Provides a for the data reference represented by . /// - /// to produce a data stream for. + /// to produce a data stream for. /// Expected length of the incoming data stream. /// Amount of bytes to buffer before flushing. /// for cancelling read. - /// for the data reference represented by . - protected internal virtual Task ReadJSDataAsStreamAsync(IJSDataReference jsDataReference, long totalLength, long maxBufferSize, CancellationToken cancellationToken) + /// for the data reference represented by . + protected internal virtual Task ReadJSDataAsStreamAsync(IJSStreamReference jsStreamReference, long totalLength, long maxBufferSize, CancellationToken cancellationToken) { // The reason it's virtual and not abstract is just for back-compat diff --git a/src/JSInterop/Microsoft.JSInterop/src/PublicAPI.Unshipped.txt b/src/JSInterop/Microsoft.JSInterop/src/PublicAPI.Unshipped.txt index 2c7982196320..e1e22df85d77 100644 --- a/src/JSInterop/Microsoft.JSInterop/src/PublicAPI.Unshipped.txt +++ b/src/JSInterop/Microsoft.JSInterop/src/PublicAPI.Unshipped.txt @@ -1,12 +1,12 @@ #nullable enable -Microsoft.JSInterop.IJSDataReference -Microsoft.JSInterop.IJSDataReference.Length.get -> long -Microsoft.JSInterop.IJSDataReference.OpenReadStreamAsync(long maxAllowedSize = 512000, long maxBufferSize = 102400, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask -Microsoft.JSInterop.Implementation.JSDataReference -Microsoft.JSInterop.Implementation.JSDataReference.Length.get -> long +Microsoft.JSInterop.IJSStreamReference +Microsoft.JSInterop.IJSStreamReference.Length.get -> long +Microsoft.JSInterop.IJSStreamReference.OpenReadStreamAsync(long maxAllowedSize = 512000, long maxBufferSize = 102400, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask +Microsoft.JSInterop.Implementation.JSStreamReference +Microsoft.JSInterop.Implementation.JSStreamReference.Length.get -> long Microsoft.JSInterop.Implementation.JSObjectReferenceJsonWorker Microsoft.JSInterop.Infrastructure.DotNetInvocationResult.ResultJson.get -> string? -Microsoft.JSInterop.JSCallResultType.JSDataReference = 2 -> Microsoft.JSInterop.JSCallResultType +Microsoft.JSInterop.JSCallResultType.JSStreamReference = 2 -> Microsoft.JSInterop.JSCallResultType Microsoft.JSInterop.JSRuntime.Dispose() -> void static Microsoft.JSInterop.Implementation.JSObjectReferenceJsonWorker.ReadJSObjectReferenceIdentifier(ref System.Text.Json.Utf8JsonReader reader) -> long static Microsoft.JSInterop.Implementation.JSObjectReferenceJsonWorker.WriteJSObjectReference(System.Text.Json.Utf8JsonWriter! writer, Microsoft.JSInterop.Implementation.JSObjectReference! objectReference) -> void @@ -36,7 +36,7 @@ static Microsoft.JSInterop.JSRuntimeExtensions.InvokeVoidAsync(this Microsoft.JS static Microsoft.JSInterop.JSRuntimeExtensions.InvokeVoidAsync(this Microsoft.JSInterop.IJSRuntime! jsRuntime, string! identifier, System.TimeSpan timeout, params object?[]? args) -> System.Threading.Tasks.ValueTask *REMOVED*static Microsoft.JSInterop.JSRuntimeExtensions.InvokeVoidAsync(this Microsoft.JSInterop.IJSRuntime! jsRuntime, string! identifier, params object![]! args) -> System.Threading.Tasks.ValueTask static Microsoft.JSInterop.JSRuntimeExtensions.InvokeVoidAsync(this Microsoft.JSInterop.IJSRuntime! jsRuntime, string! identifier, params object?[]? args) -> System.Threading.Tasks.ValueTask -virtual Microsoft.JSInterop.JSRuntime.ReadJSDataAsStreamAsync(Microsoft.JSInterop.IJSDataReference! jsDataReference, long totalLength, long maxBufferSize, System.Threading.CancellationToken cancellationToken) -> System.Threading.Tasks.Task! +virtual Microsoft.JSInterop.JSRuntime.ReadJSDataAsStreamAsync(Microsoft.JSInterop.IJSStreamReference! jsStreamReference, long totalLength, long maxBufferSize, System.Threading.CancellationToken cancellationToken) -> System.Threading.Tasks.Task! virtual Microsoft.JSInterop.JSRuntime.ReceiveByteArray(int id, byte[]! data) -> void virtual Microsoft.JSInterop.JSRuntime.SendByteArray(int id, byte[]! data) -> void Microsoft.JSInterop.JSDisconnectedException diff --git a/src/JSInterop/Microsoft.JSInterop/test/Infrastructure/JSDataReferenceJsonConverterTest.cs b/src/JSInterop/Microsoft.JSInterop/test/Infrastructure/JSStreamReferenceJsonConverterTest.cs similarity index 69% rename from src/JSInterop/Microsoft.JSInterop/test/Infrastructure/JSDataReferenceJsonConverterTest.cs rename to src/JSInterop/Microsoft.JSInterop/test/Infrastructure/JSStreamReferenceJsonConverterTest.cs index f3ad82207792..1b12dc4de9e4 100644 --- a/src/JSInterop/Microsoft.JSInterop/test/Infrastructure/JSDataReferenceJsonConverterTest.cs +++ b/src/JSInterop/Microsoft.JSInterop/test/Infrastructure/JSStreamReferenceJsonConverterTest.cs @@ -8,15 +8,15 @@ namespace Microsoft.JSInterop.Infrastructure { - public class JSDataReferenceJsonConverterTest + public class JSStreamReferenceJsonConverterTest { private readonly JSRuntime JSRuntime = new TestJSRuntime(); private readonly JsonSerializerOptions JsonSerializerOptions; - public JSDataReferenceJsonConverterTest() + public JSStreamReferenceJsonConverterTest() { JsonSerializerOptions = JSRuntime.JsonSerializerOptions; - JsonSerializerOptions.Converters.Add(new JSDataReferenceJsonConverter(JSRuntime)); + JsonSerializerOptions.Converters.Add(new JSStreamReferenceJsonConverter(JSRuntime)); } [Fact] @@ -26,7 +26,7 @@ public void Read_Throws_IfJsonIsMissingJSObjectIdProperty() var json = "{}"; // Act & Assert - var ex = Assert.Throws(() => JsonSerializer.Deserialize(json, JsonSerializerOptions)); + var ex = Assert.Throws(() => JsonSerializer.Deserialize(json, JsonSerializerOptions)); Assert.Equal("Required property __jsObjectId not found.", ex.Message); } @@ -37,7 +37,7 @@ public void Read_Throws_IfJsonContainsUnknownContent() var json = "{\"foo\":2}"; // Act & Assert - var ex = Assert.Throws(() => JsonSerializer.Deserialize(json, JsonSerializerOptions)); + var ex = Assert.Throws(() => JsonSerializer.Deserialize(json, JsonSerializerOptions)); Assert.Equal("Unexcepted JSON property foo.", ex.Message); } @@ -48,7 +48,7 @@ public void Read_Throws_IfJsonIsIncomplete() var json = $"{{\"__jsObjectId\":5"; // Act & Assert - var ex = Record.Exception(() => JsonSerializer.Deserialize(json, JsonSerializerOptions)); + var ex = Record.Exception(() => JsonSerializer.Deserialize(json, JsonSerializerOptions)); Assert.IsAssignableFrom(ex); } @@ -59,7 +59,7 @@ public void Read_Throws_IfJSObjectIdAppearsMultipleTimes() var json = $"{{\"__jsObjectId\":3,\"__jsObjectId\":7}}"; // Act & Assert - var ex = Record.Exception(() => JsonSerializer.Deserialize(json, JsonSerializerOptions)); + var ex = Record.Exception(() => JsonSerializer.Deserialize(json, JsonSerializerOptions)); Assert.IsAssignableFrom(ex); } @@ -71,20 +71,20 @@ public void Read_Throws_IfLengthNotProvided() var json = $"{{\"__jsObjectId\":{expectedId}}}"; // Act & Assert - var ex = Assert.Throws(() => JsonSerializer.Deserialize(json, JsonSerializerOptions)); - Assert.Equal("Required property __jsDataReferenceLength not found.", ex.Message); + var ex = Assert.Throws(() => JsonSerializer.Deserialize(json, JsonSerializerOptions)); + Assert.Equal("Required property __jsStreamReferenceLength not found.", ex.Message); } [Fact] - public void Read_ReadsJson_IJSDataReference() + public void Read_ReadsJson_IJSStreamReference() { // Arrange var expectedId = 3; var expectedLength = 5; - var json = $"{{\"__jsObjectId\":{expectedId}, \"__jsDataReferenceLength\":{expectedLength}}}"; + var json = $"{{\"__jsObjectId\":{expectedId}, \"__jsStreamReferenceLength\":{expectedLength}}}"; // Act - var deserialized = (JSDataReference)JsonSerializer.Deserialize(json, JsonSerializerOptions)!; + var deserialized = (JSStreamReference)JsonSerializer.Deserialize(json, JsonSerializerOptions)!; // Assert Assert.Equal(expectedId, deserialized?.Id); @@ -92,15 +92,15 @@ public void Read_ReadsJson_IJSDataReference() } [Fact] - public void Read_ReadsJson_IJSDataReferenceReverseOrder() + public void Read_ReadsJson_IJSStreamReferenceReverseOrder() { // Arrange var expectedId = 3; var expectedLength = 5; - var json = $"{{\"__jsDataReferenceLength\":{expectedLength}, \"__jsObjectId\":{expectedId}}}"; + var json = $"{{\"__jsStreamReferenceLength\":{expectedLength}, \"__jsObjectId\":{expectedId}}}"; // Act - var deserialized = (JSDataReference)JsonSerializer.Deserialize(json, JsonSerializerOptions)!; + var deserialized = (JSStreamReference)JsonSerializer.Deserialize(json, JsonSerializerOptions)!; // Assert Assert.Equal(expectedId, deserialized?.Id); @@ -111,10 +111,10 @@ public void Read_ReadsJson_IJSDataReferenceReverseOrder() public void Write_WritesValidJson() { // Arrange - var jsObjectRef = new JSDataReference(JSRuntime, 7, 10); + var jsObjectRef = new JSStreamReference(JSRuntime, 7, 10); // Act - var json = JsonSerializer.Serialize((IJSDataReference)jsObjectRef, JsonSerializerOptions); + var json = JsonSerializer.Serialize((IJSStreamReference)jsObjectRef, JsonSerializerOptions); // Assert Assert.Equal($"{{\"__jsObjectId\":{jsObjectRef.Id}}}", json); diff --git a/src/JSInterop/Microsoft.JSInterop/test/JSRuntimeTest.cs b/src/JSInterop/Microsoft.JSInterop/test/JSRuntimeTest.cs index e81c88b94803..f887055564ac 100644 --- a/src/JSInterop/Microsoft.JSInterop/test/JSRuntimeTest.cs +++ b/src/JSInterop/Microsoft.JSInterop/test/JSRuntimeTest.cs @@ -401,7 +401,7 @@ public async void ReadJSDataAsStreamAsync_ThrowsNotSupportedException() { // Arrange var runtime = new TestJSRuntime(); - var dataReference = new JSDataReference(runtime, 10, 10); + var dataReference = new JSStreamReference(runtime, 10, 10); // Act var exception = await Assert.ThrowsAsync(async () => await runtime.ReadJSDataAsStreamAsync(dataReference, 10, 10, CancellationToken.None)); diff --git a/src/Shared/JSInterop/JSCallResultTypeHelper.cs b/src/Shared/JSInterop/JSCallResultTypeHelper.cs index bd3be2d13d5c..591a01b07e62 100644 --- a/src/Shared/JSInterop/JSCallResultTypeHelper.cs +++ b/src/Shared/JSInterop/JSCallResultTypeHelper.cs @@ -19,9 +19,9 @@ public static JSCallResultType FromGeneric() { return JSCallResultType.JSObjectReference; } - else if (typeof(TResult).Assembly == _currentAssembly && typeof(TResult) == typeof(IJSDataReference)) + else if (typeof(TResult).Assembly == _currentAssembly && typeof(TResult) == typeof(IJSStreamReference)) { - return JSCallResultType.JSDataReference; + return JSCallResultType.JSStreamReference; } else { From 0bb3e6c60d1b7657f2895a03bbb53eeb81e349ba Mon Sep 17 00:00:00 2001 From: Tanay Parikh Date: Fri, 18 Jun 2021 17:40:01 -0700 Subject: [PATCH 26/37] PR Feedback --- .../Server/src/Circuits/RemoteJSDataStream.cs | 14 +++-- .../Web.JS/dist/Release/blazor.server.js | 2 +- .../Web.JS/dist/Release/blazor.webview.js | 2 +- src/Components/Web.JS/src/Boot.Server.ts | 57 +------------------ src/Components/Web.JS/src/GlobalExports.ts | 2 +- .../Circuits/CircuitStreamingInterop.ts | 51 +++++++++++++++++ .../InputFile/RemoteBrowserFileStream.cs | 8 +-- .../JSInterop/src/WebAssemblyJSRuntime.cs | 2 + 8 files changed, 71 insertions(+), 67 deletions(-) create mode 100644 src/Components/Web.JS/src/Platform/Circuits/CircuitStreamingInterop.ts diff --git a/src/Components/Server/src/Circuits/RemoteJSDataStream.cs b/src/Components/Server/src/Circuits/RemoteJSDataStream.cs index ab3bf16c6635..2ffecbd9ab26 100644 --- a/src/Components/Server/src/Circuits/RemoteJSDataStream.cs +++ b/src/Components/Server/src/Circuits/RemoteJSDataStream.cs @@ -40,9 +40,16 @@ public static async ValueTask CreateRemoteJSDataStreamAsync( long maximumIncomingBytes, CancellationToken cancellationToken = default) { + // Enforce minimum 1 kb SignalR message size as we budget 512 bytes + // overhead for the transfer, thus leaving at least 512 bytes for data + // transfer per chunk. + var chunkSize = maximumIncomingBytes > 1024 ? + maximumIncomingBytes - 512 : + throw new ArgumentException($"SignalR MaximumIncomingBytes must be at least 1 kb."); + var streamId = runtime.RemoteJSDataStreamNextInstanceId++; var remoteJSDataStream = new RemoteJSDataStream(runtime, streamId, totalLength, maxBufferSize, cancellationToken); - await runtime.InvokeVoidAsync("Blazor._internal.sendJSDataStream", jsDataReference, streamId, maximumIncomingBytes); + await runtime.InvokeVoidAsync("Blazor._internal.sendJSDataStream", jsStreamReference, streamId, chunkSize); return remoteJSDataStream; } @@ -64,10 +71,6 @@ private RemoteJSDataStream( _pipeReaderStream = _pipe.Reader.AsStream(); } - // Ideally we'd have IAsyncEnumerable> here so we can pass through the - // data without having to copy it into a temporary buffer in BlazorPackHubProtocolWorker. But trying - // this gives strange errors; sometimes the "chunk" variable below has a negative length, even though - // the logic never returns a corrupted item as far as I can tell. private async Task ReceiveData(byte[] chunk, string error) { try @@ -94,6 +97,7 @@ private async Task ReceiveData(byte[] chunk, string error) if (_bytesRead == _totalLength) { await _pipe.Writer.CompleteAsync(); + Dispose(true); } return true; diff --git a/src/Components/Web.JS/dist/Release/blazor.server.js b/src/Components/Web.JS/dist/Release/blazor.server.js index efc409f8ce4b..b8dbef524080 100644 --- a/src/Components/Web.JS/dist/Release/blazor.server.js +++ b/src/Components/Web.JS/dist/Release/blazor.server.js @@ -1 +1 @@ -(()=>{"use strict";var e,t,n;!function(e){window.DotNet=e;const t=[],n=new Map;class r{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 o="__jsObjectId",i={},s={0:new r(window)};s[0]._cachedFunctions.set("import",(e=>("string"==typeof e&&e.startsWith("./")&&(e=document.baseURI+e.substr(2)),import(e))));let a,c=1,l=1,h=null;function u(e){t.push(e)}function d(e){if(e&&"object"==typeof e){s[l]=new r(e);const t={[o]:l};return l++,t}throw new Error(`Cannot create a JSObjectReference from the value '${e}'.`)}function p(e){if(!(e.buffer instanceof ArrayBuffer))throw new Error(`Cannot create a JSDataReference from the value '${e}' as it is not a valid ArrayBuffer.`);if(void 0===e.byteLength)throw new Error(`Cannot create a JSDataReference from the value '${e}' as it doesn't have a byteLength.`);const t={__jsDataReferenceLength:e.byteLength};try{const n=d(e);t.__jsObjectId=n.__jsObjectId}catch{throw new Error(`Cannot create a JSStreamReference from the value '${e}'.`)}return t}function f(e){return e?JSON.parse(e,((e,n)=>t.reduce(((t,n)=>n(e,t)),n))):null}function g(e,t,n,r){const o=y();if(o.invokeDotNetFromJS){const i=k(r),s=o.invokeDotNetFromJS(e,t,n,i);return s?f(s):null}throw new Error("The current dispatcher does not support synchronous calls from JS to .NET. Use invokeMethodAsync instead.")}function m(e,t,n,r){if(e&&n)throw new Error(`For instance method calls, assemblyName should be null. Received '${e}'.`);const o=c++,s=new Promise(((e,t)=>{i[o]={resolve:e,reject:t}}));try{const i=k(r);y().beginInvokeDotNetFromJS(o,e,t,n,i)}catch(e){w(o,!1,e)}return s}function y(){if(null!==h)return h;throw new Error("No .NET call dispatcher has been set.")}function w(e,t,n){if(!i.hasOwnProperty(e))throw new Error(`There is no pending async call with ID ${e}.`);const r=i[e];delete i[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){let n=s[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 s[e]}e.attachDispatcher=function(e){h=e},e.attachReviver=u,e.invokeMethod=function(e,t,...n){return g(e,t,null,n)},e.invokeMethodAsync=function(e,t,...n){return m(e,t,null,n)},e.createJSObjectReference=d,e.createJSDataReference=p,e.disposeJSObjectReference=function(e){const t=e&&e.__jsObjectId;"number"==typeof t&&_(t)},function(e){e[e.Default=0]="Default",e[e.JSObjectReference=1]="JSObjectReference",e[e.JSDataReference=2]="JSDataReference"}(a=e.JSCallResultType||(e.JSCallResultType={})),e.jsCallDispatcher={findJSFunction:b,disposeJSObjectReferenceById:_,invokeJSFromDotNet:(e,t,n,r)=>{const o=C(b(e,r).apply(null,f(t)),n);return null==o?null:k(o)},beginInvokeJSFromDotNet:(e,t,n,r,o)=>{const i=new Promise((e=>{e(b(t,o).apply(null,f(n)))}));e&&i.then((t=>y().endInvokeJSFromDotNet(e,!0,k([e,!0,C(t,r)]))),(t=>y().endInvokeJSFromDotNet(e,!1,JSON.stringify([e,!1,v(t)]))))},endInvokeDotNetFromJS:(e,t,n)=>{const r=t?f(n):new Error(n);w(parseInt(e),t,r)},receiveByteArray:(e,t)=>{n.set(e,t)}};class E{constructor(e){this._id=e}invokeMethod(e,...t){return g(null,e,this._id,t)}invokeMethodAsync(e,...t){return m(null,e,this._id,t)}dispose(){m(null,"__Dispose",this._id,null).catch((e=>console.error(e)))}serializeAsArg(){return{__dotNetObject:this._id}}}const S="__byte[]";function C(e,t){switch(t){case a.Default:return e;case a.JSObjectReference:return d(e);case a.JSDataReference:return p(e);default:throw new Error(`Invalid JS call result type '${t}'.`)}}u((function(e,t){if(t&&"object"==typeof t){if(t.hasOwnProperty("__dotNetObject"))return new E(t.__dotNetObject);if(t.hasOwnProperty(o)){const e=t.__jsObjectId,n=s[e];if(n)return n.getWrappedObject();throw new Error(`JS object instance with Id '${e}' does not exist. It may have been disposed.`)}if(t.hasOwnProperty(S)){const e=t["__byte[]"],r=n.get(e);if(void 0===r)throw new Error(`Byte array index '${e}' does not exist.`);return r}}return t}));let I=0;function k(e){return I=0,JSON.stringify(e,T)}function T(e,t){if(t instanceof E)return t.serializeAsArg();if(t instanceof Uint8Array){h.sendByteArray(I,t);const e={[S]:I};return I++,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"}(n||(n={}));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}}let o;function i(e,t){if(!o)throw new Error("eventDispatcher not initialized. Call 'setEventDispatcher' to configure it.");o(e,t)}const s=new Map,a=new Map,c={createEventArgs:()=>({})},l=[];function h(e){return s.get(e)}function u(e){const t=s.get(e);return(null==t?void 0:t.browserEventName)||e}function d(e,t){e.forEach((e=>s.set(e,t)))}function p(e){const t=[];for(let n=0;n{return{...f(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}}),d(["focus","blur","focusin","focusout"],c),d(["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};var t}}),d(["contextmenu","click","mouseover","mouseout","mousemove","mousedown","mouseup","dblclick"],{createEventArgs:e=>f(e)}),d(["error"],{createEventArgs:e=>{return{message:(t=e).message,filename:t.filename,lineno:t.lineno,colno:t.colno};var t}}),d(["loadstart","timeout","abort","load","loadend","progress"],{createEventArgs:e=>{return{lengthComputable:(t=e).lengthComputable,loaded:t.loaded,total:t.total};var t}}),d(["touchcancel","touchend","touchmove","touchenter","touchleave","touchstart"],{createEventArgs:e=>{return{detail:(t=e).detail,touches:p(t.touches),targetTouches:p(t.targetTouches),changedTouches:p(t.changedTouches),ctrlKey:t.ctrlKey,shiftKey:t.shiftKey,altKey:t.altKey,metaKey:t.metaKey,type:t.type};var t}}),d(["gotpointercapture","lostpointercapture","pointercancel","pointerdown","pointerenter","pointerleave","pointermove","pointerout","pointerover","pointerup"],{createEventArgs:e=>{return{...f(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}}),d(["wheel","mousewheel"],{createEventArgs:e=>{return{...f(t=e),deltaX:t.deltaX,deltaY:t.deltaY,deltaZ:t.deltaZ,deltaMode:t.deltaMode};var t}}),d(["toggle"],c);const g=["date","datetime-local","month","time","week"],m=E(["abort","blur","change","error","focus","load","loadend","loadstart","mouseenter","mouseleave","progress","reset","scroll","submit","unload","toggle","DOMNodeInsertedIntoDocument","DOMNodeRemovedFromDocument"]),y={submit:!0},w=E(["click","dblclick","mousedown","mousemove","mouseup"]);class v{constructor(e){this.browserRendererId=e,this.afterClickCallbacks=[];const t=++v.nextEventDelegatorId;this.eventsCollectionKey=`_blazorEvents_${t}`,this.eventInfoStore=new b(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,a.get(n));var n;t&&t.forEach((t=>this.dispatchGlobalEventToAllElements(t,e))),"click"===e.type&&this.afterClickCallbacks.forEach((t=>t(e)))}dispatchGlobalEventToAllElements(e,t){let n=t.target,o=null,s=!1;const a=m.hasOwnProperty(e);let c=!1;for(;n;){const d=this.getEventHandlerInfosForElement(n,!1);if(d){const a=d.getHandler(e);if(a&&(l=n,u=t.type,!((l instanceof HTMLButtonElement||l instanceof HTMLInputElement||l instanceof HTMLTextAreaElement||l instanceof HTMLSelectElement)&&w.hasOwnProperty(u)&&l.disabled))){if(!s){const n=h(e);o=(null==n?void 0:n.createEventArgs)?n.createEventArgs(t):{},s=!0}y.hasOwnProperty(t.type)&&t.preventDefault(),i({browserRendererId:this.browserRendererId,eventHandlerId:a.eventHandlerId,eventName:e,eventFieldInfo:r.fromEvent(a.renderingComponentId,t)},o)}d.stopPropagation(e)&&(c=!0),d.preventDefault(e)&&t.preventDefault()}n=a||c?null:n.parentElement}var l,u}getEventHandlerInfosForElement(e,t){return e.hasOwnProperty(this.eventsCollectionKey)?e[this.eventsCollectionKey]:t?e[this.eventsCollectionKey]=new _:null}}v.nextEventDelegatorId=0;class b{constructor(e){this.globalListener=e,this.infosByEventHandlerId={},this.countByEventName={},l.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=u(e),this.countByEventName.hasOwnProperty(e))this.countByEventName[e]++;else{this.countByEventName[e]=1;const t=m.hasOwnProperty(e);document.addEventListener(e,this.globalListener,t)}}update(e,t){if(this.infosByEventHandlerId.hasOwnProperty(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=u(t.eventName);0==--this.countByEventName[n]&&(delete this.countByEventName[n],document.removeEventListener(n,this.globalListener))}return t}handleEventNameAliasAdded(e,t){if(this.countByEventName.hasOwnProperty(e)){const n=this.countByEventName[e];delete this.countByEventName[e],document.removeEventListener(e,this.globalListener),this.addGlobalListener(t),this.countByEventName[t]+=n-1}}}class _{constructor(){this.handlers={},this.preventDefaultFlags=null,this.stopPropagationFlags=null}getHandler(e){return this.handlers.hasOwnProperty(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 E(e){const t={};return e.forEach((e=>{t[e]=!0})),t}const S=O("_blazorLogicalChildren"),C=O("_blazorLogicalParent"),I=O("_blazorLogicalEnd");function k(e,t){if(e.childNodes.length>0&&!t)throw new Error("New logical elements must start empty, or allowExistingContents must be true");return S in e||(e[S]=[]),e}function T(e,t){const n=document.createComment("!");return D(n,e,t),n}function D(e,t,n){const r=e;if(e instanceof Comment&&A(r)&&A(r).length>0)throw new Error("Not implemented: inserting non-empty logical container");if(R(r))throw new Error("Not implemented: moving existing logical children");const o=A(t);if(n0;)x(n,0)}const r=n;r.parentNode.removeChild(r)}function R(e){return e[C]||null}function P(e,t){return A(e)[t]}function U(e){var t=B(e);return"http://www.w3.org/2000/svg"===t.namespaceURI&&"foreignObject"!==t.tagName}function A(e){return e[S]}function N(e,t){const n=A(e);t.forEach((e=>{e.moveRangeStart=n[e.fromSiblingIndex],e.moveRangeEnd=M(e.moveRangeStart)})),t.forEach((t=>{const r=t.moveToBeforeMarker=document.createComment("marker"),o=n[t.toSiblingIndex+1];o?o.parentNode.insertBefore(r,o):L(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 B(e){if(e instanceof Element)return e;if(e instanceof Comment)return e.parentNode;throw new Error("Not a valid logical element")}function $(e){const t=A(R(e));return t[Array.prototype.indexOf.call(t,e)+1]||null}function L(e,t){if(t instanceof Element)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=$(t);n?n.parentNode.insertBefore(e,n):L(e,R(t))}}}function M(e){if(e instanceof Element)return e;const t=$(e);if(t)return t.previousSibling;{const t=R(e);return t instanceof Element?t.lastChild:M(t)}}function O(e){return"function"==typeof Symbol?Symbol():e}function H(e){return`_bl_${e}`}e.attachReviver(((e,t)=>t&&"object"==typeof t&&t.hasOwnProperty("__internalId")&&"string"==typeof t.__internalId?function(e){const t=`[${H(e)}]`;return document.querySelector(t)}(t.__internalId):t));const F="_blazorSelectValue",j=document.createElement("template"),W=document.createElementNS("http://www.w3.org/2000/svg","g"),z={},q="__internal_",J="preventDefault_",K="stopPropagation_";class V{constructor(e){this.childComponentLocations={},this.eventDelegator=new v(e),this.eventDelegator.notifyAfterClick((e=>{if(!ee)return;if(0!==e.button||function(e){return e.ctrlKey||e.shiftKey||e.altKey||e.metaKey}(e))return;if(e.defaultPrevented)return;const t=function(e){const t=!window._blazorDisableComposedPath&&e.composedPath&&e.composedPath();if(t){for(let e=0;ese(!1))))},enableNavigationInterception:function(){ee=!0},navigateTo:oe,getBaseURI:()=>document.baseURI,getLocationHref:()=>location.href};function oe(e,t,n=!1){const r=ce(e);if(!t&&he(r))ie(r,!1,n);else if(t&&location.href===e){const t=e+"?";history.replaceState(null,"",t),location.replace(e)}else n?history.replaceState(null,"",r):location.href=e}function ie(e,t,n=!1){Z=!0,n?history.replaceState(null,"",e):history.pushState(null,"",e),se(t)}async function se(e){ne&&await ne(location.href,e)}let ae;function ce(e){return ae=ae||document.createElement("a"),ae.href=e,ae.href}function le(e,t){return e?e.tagName===t?e:le(e.parentElement,t):null}function he(e){const t=(n=document.baseURI).substr(0,n.lastIndexOf("/")+1);var n;return e.startsWith(t)}const ue={init:function(e,t,n,r=50){const o=pe(t);(o||document.documentElement).style.overflowAnchor="none";const i=new IntersectionObserver((function(r){r.forEach((r=>{var o;if(!r.isIntersecting)return;const i=t.getBoundingClientRect(),s=n.getBoundingClientRect().top-i.bottom,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`});i.observe(t),i.observe(n);const s=c(t),a=c(n);function c(e){const t=new MutationObserver((()=>{i.unobserve(e),i.observe(e)}));return t.observe(e,{attributes:!0}),t}de[e._id]={intersectionObserver:i,mutationObserverBefore:s,mutationObserverAfter:a}},dispose:function(e){const t=de[e._id];t&&(t.intersectionObserver.disconnect(),t.mutationObserverBefore.disconnect(),t.mutationObserverAfter.disconnect(),e.dispose(),delete de[e._id])}},de={};function pe(e){return e?"visible"!==getComputedStyle(e).overflowY?e:pe(e.parentElement):null}const fe={navigateTo:oe,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=a.get(t.browserEventName);n?n.push(e):a.set(t.browserEventName,[e]),l.forEach((n=>n(e,t.browserEventName)))}s.set(e,t)},_internal:{navigationManager:re,domWrapper:{focus:function(e,t){if(!(e instanceof HTMLElement))throw new Error("Unable to focus an invalid element.");e.focus({preventScroll:t})},focusBySelector:function(e){const t=document.querySelector(e);t&&(t.hasAttribute("tabindex")||(t.tabIndex=-1),t.focus())}},Virtualize:ue}};window.Blazor=fe;const ge=[0,2e3,1e4,3e4,null];class me{constructor(e){this._retryDelays=void 0!==e?[...e,null]:ge}nextRetryDelayInMilliseconds(e){return this._retryDelays[e.previousRetryCount]}}class ye extends Error{constructor(e,t){const n=new.target.prototype;super(`${e}: Status code '${t}'`),this.statusCode=t,this.__proto__=n}}class we extends Error{constructor(e="A timeout occurred."){const t=new.target.prototype;super(e),this.__proto__=t}}class ve extends Error{constructor(e="An abort occurred."){const t=new.target.prototype;super(e),this.__proto__=t}}class be{constructor(e,t,n){this.statusCode=e,this.statusText=t,this.content=n}}class _e{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""}}var Ee,Se,Ce,Ie,ke;!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"}(Ee||(Ee={}));class Te extends _e{constructor(e){if(super(),this._logger=e,"undefined"==typeof fetch){const e=require;this._jar=new(e("tough-cookie").CookieJar),this._fetchType=e("node-fetch"),this._fetchType=e("fetch-cookie")(this._fetchType,this._jar),this._abortControllerType=e("abort-controller")}else this._fetchType=fetch.bind(self),this._abortControllerType=AbortController}async send(e){if(e.abortSignal&&e.abortSignal.aborted)throw new ve;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 ve});let r,o=null;if(e.timeout){const r=e.timeout;o=setTimeout((()=>{t.abort(),this._logger.log(Ee.Warning,"Timeout from HTTP request."),n=new we}),r)}try{r=await this._fetchType(e.url,{body:e.content,cache:"no-cache",credentials:!0===e.withCredentials?"include":"same-origin",headers:{"Content-Type":"text/plain;charset=UTF-8","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(Ee.Warning,`Error from HTTP request. ${e}.`),e}finally{o&&clearTimeout(o),e.abortSignal&&(e.abortSignal.onabort=null)}if(!r.ok){const e=await De(r,"text");throw new ye(e||r.statusText,r.status)}const i=De(r,e.responseType),s=await i;return new be(r.status,r.statusText,s)}getCookieString(e){return""}}function De(e,t){let n;switch(t){case"arraybuffer":n=e.arrayBuffer();break;case"text":n=e.text();break;case"blob":case"document":case"json":throw new Error(`${t} is not supported.`);default:n=e.text()}return n}class xe extends _e{constructor(e){super(),this._logger=e}send(e){return e.abortSignal&&e.abortSignal.aborted?Promise.reject(new ve):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"),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 ve)}),e.timeout&&(r.timeout=e.timeout),r.onload=()=>{e.abortSignal&&(e.abortSignal.onabort=null),r.status>=200&&r.status<300?t(new be(r.status,r.statusText,r.response||r.responseText)):n(new ye(r.response||r.responseText||r.statusText,r.status))},r.onerror=()=>{this._logger.log(Ee.Warning,`Error from HTTP request. ${r.status}: ${r.statusText}.`),n(new ye(r.statusText,r.status))},r.ontimeout=()=>{this._logger.log(Ee.Warning,"Timeout from HTTP request."),n(new we)},r.send(e.content||"")})):Promise.reject(new Error("No url defined.")):Promise.reject(new Error("No method defined."))}}class Re extends _e{constructor(e){if(super(),"undefined"!=typeof fetch)this._httpClient=new Te(e);else{if("undefined"==typeof XMLHttpRequest)throw new Error("No usable HttpClient found.");this._httpClient=new xe(e)}}send(e){return e.abortSignal&&e.abortSignal.aborted?Promise.reject(new ve):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)}}class Pe{}Pe.Authorization="Authorization",Pe.Cookie="Cookie",function(e){e[e.None=0]="None",e[e.WebSockets=1]="WebSockets",e[e.ServerSentEvents=2]="ServerSentEvents",e[e.LongPolling=4]="LongPolling"}(Se||(Se={})),function(e){e[e.Text=1]="Text",e[e.Binary=2]="Binary"}(Ce||(Ce={}));class Ue{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 Ae{constructor(){}log(e,t){}}Ae.instance=new Ae;class Ne{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 Be{static get isBrowser(){return"object"==typeof window}static get isWebWorker(){return"object"==typeof self&&"importScripts"in self}static get isNode(){return!this.isBrowser&&!this.isWebWorker}}function $e(e,t){let n="";return Le(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 Le(e){return e&&"undefined"!=typeof ArrayBuffer&&(e instanceof ArrayBuffer||e.constructor&&"ArrayBuffer"===e.constructor.name)}async function Me(e,t,n,r,o,i,s,a,c){let l={};if(o){const e=await o();e&&(l={Authorization:`Bearer ${e}`})}const[h,u]=Fe();l[h]=u,e.log(Ee.Trace,`(${t} transport) sending data. ${$e(i,s)}.`);const d=Le(i)?"arraybuffer":"text",p=await n.post(r,{content:i,headers:{...l,...c},responseType:d,withCredentials:a});e.log(Ee.Trace,`(${t} transport) request complete. Response status: ${p.statusCode}.`)}class Oe{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 He{constructor(e){this._minLevel=e,this.out=console}log(e,t){if(e>=this._minLevel){const n=`[${(new Date).toISOString()}] ${Ee[e]}: ${t}`;switch(e){case Ee.Critical:case Ee.Error:this.out.error(n);break;case Ee.Warning:this.out.warn(n);break;case Ee.Information:this.out.info(n);break;default:this.out.log(n)}}}}function Fe(){let e="X-SignalR-User-Agent";return Be.isNode&&(e="User-Agent"),[e,je("0.0.0-DEV_BUILD",We(),Be.isNode?"NodeJS":"Browser",ze())]}function je(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 We(){if(!Be.isNode)return"";switch(process.platform){case"win32":return"Windows NT";case"darwin":return"macOS";case"linux":return"Linux";default:return process.platform}}function ze(){if(Be.isNode)return process.versions.node}class qe{constructor(e,t,n,r,o,i){this._httpClient=e,this._accessTokenFactory=t,this._logger=n,this._pollAbort=new Ue,this._logMessageContent=r,this._withCredentials=o,this._headers=i,this._running=!1,this.onreceive=null,this.onclose=null}get pollAborted(){return this._pollAbort.aborted}async connect(e,t){if(Ne.isRequired(e,"url"),Ne.isRequired(t,"transferFormat"),Ne.isIn(t,Ce,"transferFormat"),this._url=e,this._logger.log(Ee.Trace,"(LongPolling transport) Connecting."),t===Ce.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]=Fe(),o={[n]:r,...this._headers},i={abortSignal:this._pollAbort.signal,headers:o,timeout:1e5,withCredentials:this._withCredentials};t===Ce.Binary&&(i.responseType="arraybuffer");const s=await this._getAccessToken();this._updateHeaderToken(i,s);const a=`${e}&_=${Date.now()}`;this._logger.log(Ee.Trace,`(LongPolling transport) polling: ${a}.`);const c=await this._httpClient.get(a,i);200!==c.statusCode?(this._logger.log(Ee.Error,`(LongPolling transport) Unexpected response code: ${c.statusCode}.`),this._closeError=new ye(c.statusText||"",c.statusCode),this._running=!1):this._running=!0,this._receiving=this._poll(this._url,i)}async _getAccessToken(){return this._accessTokenFactory?await this._accessTokenFactory():null}_updateHeaderToken(e,t){e.headers||(e.headers={}),t?e.headers[Pe.Authorization]=`Bearer ${t}`:e.headers[Pe.Authorization]&&delete e.headers[Pe.Authorization]}async _poll(e,t){try{for(;this._running;){const n=await this._getAccessToken();this._updateHeaderToken(t,n);try{const n=`${e}&_=${Date.now()}`;this._logger.log(Ee.Trace,`(LongPolling transport) polling: ${n}.`);const r=await this._httpClient.get(n,t);204===r.statusCode?(this._logger.log(Ee.Information,"(LongPolling transport) Poll terminated by server."),this._running=!1):200!==r.statusCode?(this._logger.log(Ee.Error,`(LongPolling transport) Unexpected response code: ${r.statusCode}.`),this._closeError=new ye(r.statusText||"",r.statusCode),this._running=!1):r.content?(this._logger.log(Ee.Trace,`(LongPolling transport) data received. ${$e(r.content,this._logMessageContent)}.`),this.onreceive&&this.onreceive(r.content)):this._logger.log(Ee.Trace,"(LongPolling transport) Poll timed out, reissuing.")}catch(e){this._running?e instanceof we?this._logger.log(Ee.Trace,"(LongPolling transport) Poll timed out, reissuing."):(this._closeError=e,this._running=!1):this._logger.log(Ee.Trace,`(LongPolling transport) Poll errored after shutdown: ${e.message}`)}}}finally{this._logger.log(Ee.Trace,"(LongPolling transport) Polling complete."),this.pollAborted||this._raiseOnClose()}}async send(e){return this._running?Me(this._logger,"LongPolling",this._httpClient,this._url,this._accessTokenFactory,e,this._logMessageContent,this._withCredentials,this._headers):Promise.reject(new Error("Cannot send until the transport is connected"))}async stop(){this._logger.log(Ee.Trace,"(LongPolling transport) Stopping polling."),this._running=!1,this._pollAbort.abort();try{await this._receiving,this._logger.log(Ee.Trace,`(LongPolling transport) sending DELETE request to ${this._url}.`);const e={},[t,n]=Fe();e[t]=n;const r={headers:{...e,...this._headers},withCredentials:this._withCredentials},o=await this._getAccessToken();this._updateHeaderToken(r,o),await this._httpClient.delete(this._url,r),this._logger.log(Ee.Trace,"(LongPolling transport) DELETE request sent.")}finally{this._logger.log(Ee.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(Ee.Trace,e),this.onclose(this._closeError)}}}class Je{constructor(e,t,n,r,o,i,s){this._httpClient=e,this._accessTokenFactory=t,this._logger=n,this._logMessageContent=r,this._withCredentials=i,this._eventSourceConstructor=o,this._headers=s,this.onreceive=null,this.onclose=null}async connect(e,t){if(Ne.isRequired(e,"url"),Ne.isRequired(t,"transferFormat"),Ne.isIn(t,Ce,"transferFormat"),this._logger.log(Ee.Trace,"(SSE transport) Connecting."),this._url=e,this._accessTokenFactory){const t=await this._accessTokenFactory();t&&(e+=(e.indexOf("?")<0?"?":"&")+`access_token=${encodeURIComponent(t)}`)}return new Promise(((n,r)=>{let o,i=!1;if(t===Ce.Text){if(Be.isBrowser||Be.isWebWorker)o=new this._eventSourceConstructor(e,{withCredentials:this._withCredentials});else{const t=this._httpClient.getCookieString(e),n={};n.Cookie=t;const[r,i]=Fe();n[r]=i,o=new this._eventSourceConstructor(e,{withCredentials:this._withCredentials,headers:{...n,...this._headers}})}try{o.onmessage=e=>{if(this.onreceive)try{this._logger.log(Ee.Trace,`(SSE transport) data received. ${$e(e.data,this._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(Ee.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?Me(this._logger,"SSE",this._httpClient,this._url,this._accessTokenFactory,e,this._logMessageContent,this._withCredentials,this._headers):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 Ke{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){if(Ne.isRequired(e,"url"),Ne.isRequired(t,"transferFormat"),Ne.isIn(t,Ce,"transferFormat"),this._logger.log(Ee.Trace,"(WebSockets transport) Connecting."),this._accessTokenFactory){const t=await this._accessTokenFactory();t&&(e+=(e.indexOf("?")<0?"?":"&")+`access_token=${encodeURIComponent(t)}`)}return new Promise(((n,r)=>{let o;e=e.replace(/^http/,"ws"),this._httpClient.getCookieString(e);let i=!1;o||(o=new this._webSocketConstructor(e)),t===Ce.Binary&&(o.binaryType="arraybuffer"),o.onopen=t=>{this._logger.log(Ee.Information,`WebSocket connected to ${e}.`),this._webSocket=o,i=!0,n()},o.onerror=e=>{let t=null;t="undefined"!=typeof ErrorEvent&&e instanceof ErrorEvent?e.error:"There was an error with the transport",this._logger.log(Ee.Information,`(WebSockets transport) ${t}.`)},o.onmessage=e=>{if(this._logger.log(Ee.Trace,`(WebSockets transport) data received. ${$e(e.data,this._logMessageContent)}.`),this.onreceive)try{this.onreceive(e.data)}catch(e){return void this._close(e)}},o.onclose=e=>{if(i)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(Ee.Trace,`(WebSockets transport) sending data. ${$e(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(Ee.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 Ve{constructor(e,t={}){var n;if(this._stopPromiseResolver=()=>{},this.features={},this._negotiateVersion=1,Ne.isRequired(e,"url"),this._logger=void 0===(n=t.logger)?new He(Ee.Information):null===n?Ae.instance:void 0!==n.log?n:new He(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,"undefined"==typeof WebSocket||t.WebSocket||(t.WebSocket=WebSocket),"undefined"==typeof EventSource||t.EventSource||(t.EventSource=EventSource),this._httpClient=t.httpClient||new Re(this._logger),this._connectionState="Disconnected",this._connectionStarted=!1,this._options=t,this.onreceive=null,this.onclose=null}async start(e){if(e=e||Ce.Binary,Ne.isIn(e,Ce,"transferFormat"),this._logger.log(Ee.Debug,`Starting connection with transfer format '${Ce[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(Ee.Error,e),await this._stopPromise,Promise.reject(new Error(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(Ee.Error,e),Promise.reject(new Error(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 Xe(this.transport)),this._sendQueue.send(e))}async stop(e){return"Disconnected"===this._connectionState?(this._logger.log(Ee.Debug,`Call to HttpConnection.stop(${e}) ignored because the connection is already in the disconnected state.`),Promise.resolve()):"Disconnecting"===this._connectionState?(this._logger.log(Ee.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(Ee.Error,`HttpConnection.transport.stop() threw error '${e}'.`),this._stopConnection()}this.transport=void 0}else this._logger.log(Ee.Debug,"HttpConnection.transport is undefined in HttpConnection.stop() because start() failed.")}async _startInternal(e){let t=this.baseUrl;this._accessTokenFactory=this._options.accessTokenFactory;try{if(this._options.skipNegotiation){if(this._options.transport!==Se.WebSockets)throw new Error("Negotiation can only be skipped when using the WebSocket transport directly.");this.transport=this._constructTransport(Se.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 Error("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}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 qe&&(this.features.inherentKeepAlive=!0),"Connecting"===this._connectionState&&(this._logger.log(Ee.Debug,"The HttpConnection connected successfully."),this._connectionState="Connected")}catch(e){return this._logger.log(Ee.Error,"Failed to start the connection: "+e),this._connectionState="Disconnected",this.transport=void 0,this._stopPromiseResolver(),Promise.reject(e)}}async _getNegotiationResponse(e){const t={};if(this._accessTokenFactory){const e=await this._accessTokenFactory();e&&(t[Pe.Authorization]=`Bearer ${e}`)}const[n,r]=Fe();t[n]=r;const o=this._resolveNegotiateUrl(e);this._logger.log(Ee.Debug,`Sending negotiation request: ${o}.`);try{const e=await this._httpClient.post(o,{content:"",headers:{...t,...this._options.headers},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 ye&&404===e.statusCode&&(t+=" Either this is not a SignalR endpoint or there is a proxy blocking the connection."),this._logger.log(Ee.Error,t),Promise.reject(new Error(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(Ee.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: ${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(Ee.Error,`Failed to start the transport '${n.transport}': ${e}`),a=void 0,i.push(`${n.transport} failed: ${e}`),"Connecting"!==this._connectionState){const e="Failed to select transport before stop() was called.";return this._logger.log(Ee.Debug,e),Promise.reject(new Error(e))}}}}return i.length>0?Promise.reject(new Error(`Unable to connect to the server with any of the available transports. ${i.join(" ")}`)):Promise.reject(new Error("None of the transports supported by the client are supported by the server."))}_constructTransport(e){switch(e){case Se.WebSockets:if(!this._options.WebSocket)throw new Error("'WebSocket' is not supported in your environment.");return new Ke(this._httpClient,this._accessTokenFactory,this._logger,this._options.logMessageContent||!1,this._options.WebSocket,this._options.headers||{});case Se.ServerSentEvents:if(!this._options.EventSource)throw new Error("'EventSource' is not supported in your environment.");return new Je(this._httpClient,this._accessTokenFactory,this._logger,this._options.logMessageContent||!1,this._options.EventSource,this._options.withCredentials,this._options.headers||{});case Se.LongPolling:return new qe(this._httpClient,this._accessTokenFactory,this._logger,this._options.logMessageContent||!1,this._options.withCredentials,this._options.headers||{});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=Se[e.transport];if(null==r)return this._logger.log(Ee.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(Ee.Debug,`Skipping transport '${Se[r]}' because it was disabled by the client.`),new Error(`'${Se[r]}' is disabled by the client.`);if(!(e.transferFormats.map((e=>Ce[e])).indexOf(n)>=0))return this._logger.log(Ee.Debug,`Skipping transport '${Se[r]}' because it does not support the requested transfer format '${Ce[n]}'.`),new Error(`'${Se[r]}' does not support ${Ce[n]}.`);if(r===Se.WebSockets&&!this._options.WebSocket||r===Se.ServerSentEvents&&!this._options.EventSource)return this._logger.log(Ee.Debug,`Skipping transport '${Se[r]}' because it is not supported in your environment.'`),new Error(`'${Se[r]}' is not supported in your environment.`);this._logger.log(Ee.Debug,`Selecting transport '${Se[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(Ee.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(Ee.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(Ee.Error,`Connection disconnected with error '${e}'.`):this._logger.log(Ee.Information,"Connection disconnected."),this._sendQueue&&(this._sendQueue.stop().catch((e=>{this._logger.log(Ee.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(Ee.Error,`HttpConnection.onclose(${e}) threw error '${t}'.`)}}}else this._logger.log(Ee.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(!Be.isBrowser||!window.document)throw new Error(`Cannot resolve '${e}'.`);const t=window.document.createElement("a");return t.href=e,this._logger.log(Ee.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 Xe{constructor(e){this._transport=e,this._buffer=[],this._executing=!0,this._sendBufferedData=new Ye,this._transportResult=new Ye,this._sendLoopPromise=this._sendLoop()}send(e){return this._bufferData(e),this._transportResult||(this._transportResult=new Ye),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 Ye;const e=this._transportResult;this._transportResult=void 0;const t="string"==typeof this._buffer[0]?this._buffer.join(""):Xe._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 Ye{constructor(){this.promise=new Promise(((e,t)=>[this._resolver,this._rejecter]=[e,t]))}resolve(){this._resolver()}reject(e){this._rejecter(e)}}class Ge{static write(e){return`${e}${Ge.RecordSeparator}`}static parse(e){if(e[e.length-1]!==Ge.RecordSeparator)throw new Error("Message is incomplete.");const t=e.split(Ge.RecordSeparator);return t.pop(),t}}Ge.RecordSeparatorCode=30,Ge.RecordSeparator=String.fromCharCode(Ge.RecordSeparatorCode);class Qe{writeHandshakeRequest(e){return Ge.write(JSON.stringify(e))}parseHandshakeResponse(e){let t,n;if(Le(e)){const r=new Uint8Array(e),o=r.indexOf(Ge.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(Ge.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=Ge.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"}(Ie||(Ie={}));class Ze{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 Oe(this,e)}}!function(e){e.Disconnected="Disconnected",e.Connecting="Connecting",e.Connected="Connected",e.Disconnecting="Disconnecting",e.Reconnecting="Reconnecting"}(ke||(ke={}));class et{constructor(e,t,n,r){this._nextKeepAlive=0,Ne.isRequired(e,"connection"),Ne.isRequired(t,"logger"),Ne.isRequired(n,"protocol"),this.serverTimeoutInMilliseconds=3e4,this.keepAliveIntervalInMilliseconds=15e3,this._logger=t,this._protocol=n,this.connection=e,this._reconnectPolicy=r,this._handshakeProtocol=new Qe,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=ke.Disconnected,this._connectionStarted=!1,this._cachedPingMessage=this._protocol.writeMessage({type:Ie.Ping})}static create(e,t,n,r){return new et(e,t,n,r)}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!==ke.Disconnected&&this._connectionState!==ke.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!==ke.Disconnected)return Promise.reject(new Error("Cannot start a HubConnection that is not in the 'Disconnected' state."));this._connectionState=ke.Connecting,this._logger.log(Ee.Debug,"Starting HubConnection.");try{await this._startInternal(),this._connectionState=ke.Connected,this._connectionStarted=!0,this._logger.log(Ee.Debug,"HubConnection connected successfully.")}catch(e){return this._connectionState=ke.Disconnected,this._logger.log(Ee.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(Ee.Debug,"Sending handshake request."),await this._sendMessage(this._handshakeProtocol.writeHandshakeRequest(t)),this._logger.log(Ee.Information,`Using HubProtocol '${this._protocol.name}'.`),this._cleanupTimeout(),this._resetTimeoutPeriod(),this._resetKeepAliveInterval(),await e,this._stopDuringStartError)throw this._stopDuringStartError}catch(e){throw this._logger.log(Ee.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){return this._connectionState===ke.Disconnected?(this._logger.log(Ee.Debug,`Call to HubConnection.stop(${e}) ignored because it is already in the disconnected state.`),Promise.resolve()):this._connectionState===ke.Disconnecting?(this._logger.log(Ee.Debug,`Call to HttpConnection.stop(${e}) ignored because the connection is already in the disconnecting state.`),this._stopPromise):(this._connectionState=ke.Disconnecting,this._logger.log(Ee.Debug,"Stopping HubConnection."),this._reconnectDelayHandle?(this._logger.log(Ee.Debug,"Connection stopped during reconnect delay. Done reconnecting."),clearTimeout(this._reconnectDelayHandle),this._reconnectDelayHandle=void 0,this._completeClose(),Promise.resolve()):(this._cleanupTimeout(),this._cleanupPingTimer(),this._stopDuringStartError=e||new Error("The connection was stopped before the hub handshake could complete."),this.connection.stop(e)))}stream(e,...t){const[n,r]=this._replaceStreamingParams(t),o=this._createStreamInvocation(e,t,r);let i;const s=new Ze;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===Ie.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===Ie.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 Ie.Invocation:this._invokeClientMethod(e);break;case Ie.StreamItem:case Ie.Completion:{const t=this._callbacks[e.invocationId];t&&(e.type===Ie.Completion&&delete this._callbacks[e.invocationId],t(e));break}case Ie.Ping:break;case Ie.Close:{this._logger.log(Ee.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(Ee.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(Ee.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(Ee.Error,e);const n=new Error(e);throw this._handshakeRejecter(n),n}return this._logger.log(Ee.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===ke.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."))}_invokeClientMethod(e){const t=this._methods[e.target.toLowerCase()];if(t){try{t.forEach((t=>t.apply(this,e.arguments)))}catch(t){this._logger.log(Ee.Error,`A callback for the method ${e.target.toLowerCase()} threw error '${t}'.`)}if(e.invocationId){const e="Server requested a response, which is not supported in this version of the client.";this._logger.log(Ee.Error,e),this._stopPromise=this._stopInternal(new Error(e))}}else this._logger.log(Ee.Warning,`No client method with the name '${e.target}' found.`)}_connectionClosed(e){this._logger.log(Ee.Debug,`HubConnection.connectionClosed(${e}) called while in state ${this._connectionState}.`),this._stopDuringStartError=this._stopDuringStartError||e||new Error("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===ke.Disconnecting?this._completeClose(e):this._connectionState===ke.Connected&&this._reconnectPolicy?this._reconnect(e):this._connectionState===ke.Connected&&this._completeClose(e)}_completeClose(e){if(this._connectionStarted){this._connectionState=ke.Disconnected,this._connectionStarted=!1;try{this._closedCallbacks.forEach((t=>t.apply(this,[e])))}catch(t){this._logger.log(Ee.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(Ee.Debug,"Connection not reconnecting because the IRetryPolicy returned null on the first reconnect attempt."),void this._completeClose(e);if(this._connectionState=ke.Reconnecting,e?this._logger.log(Ee.Information,`Connection reconnecting because of error '${e}'.`):this._logger.log(Ee.Information,"Connection reconnecting."),0!==this._reconnectingCallbacks.length){try{this._reconnectingCallbacks.forEach((t=>t.apply(this,[e])))}catch(t){this._logger.log(Ee.Error,`An onreconnecting callback called with error '${e}' threw error '${t}'.`)}if(this._connectionState!==ke.Reconnecting)return void this._logger.log(Ee.Debug,"Connection left the reconnecting state in onreconnecting callback. Done reconnecting.")}for(;null!==o;){if(this._logger.log(Ee.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!==ke.Reconnecting)return void this._logger.log(Ee.Debug,"Connection left the reconnecting state during reconnect delay. Done reconnecting.");try{if(await this._startInternal(),this._connectionState=ke.Connected,this._logger.log(Ee.Information,"HubConnection reconnected successfully."),0!==this._reconnectedCallbacks.length)try{this._reconnectedCallbacks.forEach((e=>e.apply(this,[this.connection.connectionId])))}catch(e){this._logger.log(Ee.Error,`An onreconnected callback called with connectionId '${this.connection.connectionId}; threw error '${e}'.`)}return}catch(e){if(this._logger.log(Ee.Information,`Reconnect attempt failed because of error '${e}'.`),this._connectionState!==ke.Reconnecting)return this._logger.log(Ee.Debug,`Connection moved to the '${this._connectionState}' from the reconnecting state during reconnect attempt. Done reconnecting.`),void(this._connectionState===ke.Disconnecting&&this._completeClose());r=e instanceof Error?e:new Error(e.toString()),o=this._getNextRetryDelay(n++,Date.now()-t,r)}}this._logger.log(Ee.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(Ee.Error,`IRetryPolicy.nextRetryDelayInMilliseconds(${e}, ${t}) threw error '${n}'.`),null}}_cancelCallbacksWithError(e){const t=this._callbacks;this._callbacks={},Object.keys(t).forEach((n=>{(0,t[n])(null,e)}))}_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:Ie.Invocation}:{arguments:t,target:e,type:Ie.Invocation};{const n=this._invocationId;return this._invocationId++,0!==r.length?{arguments:t,invocationId:n.toString(),streamIds:r,target:e,type:Ie.Invocation}:{arguments:t,invocationId:n.toString(),target:e,type:Ie.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 ut=ot?new TextDecoder:null,dt=ot?"undefined"!=typeof process&&"force"!==process.env.TEXT_DECODER?200:0:it,pt=function(e,t){this.type=e,this.data=t};function ft(e,t,n){var r=Math.floor(n/4294967296),o=n;e.setUint32(t,r),e.setUint32(t+4,o)}function gt(e,t){return 4294967296*e.getInt32(t)+e.getUint32(t+4)}var mt={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),ft(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:gt(t,4),nsec:t.getUint32(0)};default:throw new Error("Unrecognized data size for timestamp: "+e.length)}}(e);return new Date(1e3*t.sec+t.nsec/1e6)}},yt=function(){function e(){this.builtInEncoders=[],this.builtInDecoders=[],this.encoders=[],this.decoders=[],this.register(mt)}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 "+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: "+e+" bytes in UTF-8");this.writeU8(219),this.writeU32(e)}},e.prototype.encodeString=function(e){if(e.length>ct){var t=st(e);this.ensureBufferSizeToWrite(5+t),this.writeStringHeader(t),lt(e,this.bytes,this.pos),this.pos+=t}else t=st(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: "+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: "+t);this.writeU8(198),this.writeU32(t)}var n=wt(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: "+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=ht(e,t,n),i=Uint8Array.prototype.slice.call(e,t,t+n);return this.store(i,o),o},e}(),St=(_t=function(e,t){return(_t=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])})(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}_t(e,t),e.prototype=null===t?Object.create(t):(n.prototype=t.prototype,new n)}),Ct=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]1||a(e,t)}))})}function a(e,t){try{(n=o[e](t)).value instanceof kt?Promise.resolve(n.value.v).then(c,l):h(i[0][2],n)}catch(e){h(i[0][3],e)}var n}function c(e){a("next",e)}function l(e){a("throw",e)}function h(e,t){e(t),i.shift(),i.length&&a(i[0][0],i[0][1])}},Dt=new DataView(new ArrayBuffer(0)),xt=new Uint8Array(Dt.buffer),Rt=function(){try{Dt.getInt8(0)}catch(e){return e.constructor}throw new Error("never reached")}(),Pt=new Rt("Insufficient data"),Ut=4294967295,At=new Et,Nt=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 St(t,e),t}(Error),Bt=function(){function e(e,t,n,r,o,i,s,a){void 0===e&&(e=yt.defaultCodec),void 0===t&&(t=void 0),void 0===n&&(n=Ut),void 0===r&&(r=Ut),void 0===o&&(o=Ut),void 0===i&&(i=Ut),void 0===s&&(s=Ut),void 0===a&&(a=At),this.extensionCodec=e,this.context=t,this.maxStrLength=n,this.maxBinLength=r,this.maxArrayLength=o,this.maxMapLength=i,this.maxExtLength=s,this.keyDecoder=a,this.totalPos=0,this.pos=0,this.view=Dt,this.bytes=xt,this.headByte=-1,this.stack=[]}return e.prototype.reinitializeState=function(){this.totalPos=0,this.headByte=-1,this.stack.length=0},e.prototype.setBuffer=function(e){this.bytes=wt(e),this.view=function(e){if(e instanceof ArrayBuffer)return new DataView(e);var t=wt(e);return new DataView(t.buffer,t.byteOffset,t.byteLength)}(this.bytes),this.pos=0},e.prototype.appendBuffer=function(e){if(-1!==this.headByte||this.hasRemaining()){var t=this.bytes.subarray(this.pos),n=wt(e),r=new Uint8Array(t.length+n.length);r.set(t),r.set(n,t.length),this.setBuffer(r)}else this.setBuffer(e)},e.prototype.hasRemaining=function(e){return void 0===e&&(e=1),this.view.byteLength-this.pos>=e},e.prototype.createExtraByteError=function(e){var t=this.view,n=this.pos;return new RangeError("Extra "+(t.byteLength-n)+" of "+t.byteLength+" byte(s) found at buffer["+e+"]")},e.prototype.decode=function(e){this.reinitializeState(),this.setBuffer(e);var t=this.doDecodeSync();if(this.hasRemaining())throw this.createExtraByteError(this.pos);return t},e.prototype.decodeMulti=function(e){return Ct(this,(function(t){switch(t.label){case 0:this.reinitializeState(),this.setBuffer(e),t.label=1;case 1:return this.hasRemaining()?[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,u,d;return Ct(this,(function(p){switch(p.label){case 0:i=!1,p.label=1;case 1:p.trys.push([1,6,7,12]),t=It(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 Rt))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())throw this.createExtraByteError(this.totalPos);return[2,s]}throw h=(l=this).headByte,u=l.pos,d=l.totalPos,new RangeError("Insufficient data in parsing "+bt(h)+" at "+d+" ("+u+" 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 Tt(this,arguments,(function(){var n,r,o,i,s,a,c,l,h;return Ct(this,(function(u){switch(u.label){case 0:n=t,r=-1,u.label=1;case 1:u.trys.push([1,13,14,19]),o=It(e),u.label=2;case 2:return[4,kt(o.next())];case 3:if((i=u.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()),u.label=4;case 4:u.trys.push([4,9,,10]),u.label=5;case 5:return[4,kt(this.doDecodeSync())];case 6:return[4,u.sent()];case 7:return u.sent(),0==--r?[3,8]:[3,5];case 8:return[3,10];case 9:if(!((a=u.sent())instanceof Rt))throw a;return[3,10];case 10:this.totalPos+=this.pos,u.label=11;case 11:return[3,2];case 12:return[3,19];case 13:return c=u.sent(),l={error:c},[3,19];case 14:return u.trys.push([14,,17,18]),i&&!i.done&&(h=o.return)?[4,kt(h.call(o))]:[3,16];case 15:u.sent(),u.label=16;case 16:return[3,18];case 17:if(l)throw l.error;return[7];case 18:return[7];case 19:return[2]}}))}))},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 Nt("Unrecognized type byte: "+bt(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 Nt("The type of key must be string or number but "+typeof t);if("__proto__"===t)throw new Nt("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 Nt("Unrecognized array type byte: "+bt(e))}},e.prototype.pushMapState=function(e){if(e>this.maxMapLength)throw new Nt("Max length exceeded: map length ("+e+") > maxMapLengthLength ("+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 Nt("Max length exceeded: array length ("+e+") > maxArrayLength ("+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 Nt("Max length exceeded: UTF-8 byte length ("+e+") > maxStrLength ("+this.maxStrLength+")");if(this.bytes.byteLengthdt?function(e,t,n){var r=e.subarray(t,t+n);return ut.decode(r)}(this.bytes,o,e):ht(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 Nt("Max length exceeded: bin length ("+e+") > maxBinLength ("+this.maxBinLength+")");if(!this.hasRemaining(e+t))throw Pt;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 Nt("Max length exceeded: ext length ("+e+") > maxExtLength ("+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=gt(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 $t{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 Lt=new Uint8Array([145,Ie.Ping]);class Mt{constructor(e){this.name="messagepack",this.version=1,this.transferFormat=Ce.Binary,this._errorResult=1,this._voidResult=2,this._nonVoidResult=3,e=e||{},this._encoder=new vt(e.extensionCodec,e.context,e.maxDepth,e.initialBufferSize,e.sortKeys,e.forceFloat32,e.ignoreUndefined,e.forceIntegerToFloat),this._decoder=new Bt(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=Ae.instance);const r=$t.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 Ie.Invocation:return this._writeInvocation(e);case Ie.StreamInvocation:return this._writeStreamInvocation(e);case Ie.StreamItem:return this._writeStreamItem(e);case Ie.Completion:return this._writeCompletion(e);case Ie.Ping:return $t.write(Lt);case Ie.CancelInvocation:return this._writeCancelInvocation(e);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 Ie.Invocation:return this._createInvocationMessage(this._readHeaders(n),n);case Ie.StreamItem:return this._createStreamItemMessage(this._readHeaders(n),n);case Ie.Completion:return this._createCompletionMessage(this._readHeaders(n),n);case Ie.Ping:return this._createPingMessage(n);case Ie.Close:return this._createCloseMessage(n);default:return t.log(Ee.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:Ie.Close}}_createPingMessage(e){if(e.length<1)throw new Error("Invalid payload for Ping message.");return{type:Ie.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:Ie.Invocation}:{arguments:t[4],headers:e,streamIds:[],target:t[3],type:Ie.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:Ie.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:Ie.Completion}}_writeInvocation(e){let t;return t=e.streamIds?this._encoder.encode([Ie.Invocation,e.headers||{},e.invocationId||null,e.target,e.arguments,e.streamIds]):this._encoder.encode([Ie.Invocation,e.headers||{},e.invocationId||null,e.target,e.arguments]),$t.write(t.slice())}_writeStreamInvocation(e){let t;return t=e.streamIds?this._encoder.encode([Ie.StreamInvocation,e.headers||{},e.invocationId,e.target,e.arguments,e.streamIds]):this._encoder.encode([Ie.StreamInvocation,e.headers||{},e.invocationId,e.target,e.arguments]),$t.write(t.slice())}_writeStreamItem(e){const t=this._encoder.encode([Ie.StreamItem,e.headers||{},e.invocationId,e.item]);return $t.write(t.slice())}_writeCompletion(e){const t=e.error?this._errorResult:e.result?this._nonVoidResult:this._voidResult;let n;switch(t){case this._errorResult:n=this._encoder.encode([Ie.Completion,e.headers||{},e.invocationId,t,e.error]);break;case this._voidResult:n=this._encoder.encode([Ie.Completion,e.headers||{},e.invocationId,t]);break;case this._nonVoidResult:n=this._encoder.encode([Ie.Completion,e.headers||{},e.invocationId,t,e.result])}return $t.write(n.slice())}_writeCancelInvocation(e){const t=this._encoder.encode([Ie.CancelInvocation,e.headers||{},e.invocationId]);return $t.write(t.slice())}_readHeaders(e){const t=e[1];if("object"!=typeof t)throw new Error("Invalid headers.");return t}}let Ot=!1;const Ht="function"==typeof TextDecoder?new TextDecoder("utf-8"):null,Ft=Ht?Ht.decode.bind(Ht):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("")},jt=Math.pow(2,32),Wt=Math.pow(2,21)-1;function zt(e,t){return e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24}function qt(e,t){return e[t]+(e[t+1]<<8)+(e[t+2]<<16)+(e[t+3]<<24>>>0)}function Jt(e,t){const n=qt(e,t+4);if(n>Wt)throw new Error(`Cannot read uint64 with high order part ${n}, because the result would exceed Number.MAX_SAFE_INTEGER.`);return n*jt+qt(e,t)}class Kt{constructor(e){this.batchData=e;const t=new Gt(e);this.arrayRangeReader=new Qt(e),this.arrayBuilderSegmentReader=new Zt(e),this.diffReader=new Vt(e),this.editReader=new Xt(e,t),this.frameReader=new Yt(e,t)}updatedComponents(){return zt(this.batchData,this.batchData.length-20)}referenceFrames(){return zt(this.batchData,this.batchData.length-16)}disposedComponentIds(){return zt(this.batchData,this.batchData.length-12)}disposedEventHandlerIds(){return zt(this.batchData,this.batchData.length-8)}updatedComponentsEntry(e,t){const n=e+4*t;return zt(this.batchData,n)}referenceFramesEntry(e,t){return e+20*t}disposedComponentIdsEntry(e,t){const n=e+4*t;return zt(this.batchData,n)}disposedEventHandlerIdsEntry(e,t){const n=e+8*t;return Jt(this.batchData,n)}}class Vt{constructor(e){this.batchDataUint8=e}componentId(e){return zt(this.batchDataUint8,e)}edits(e){return e+4}editsEntry(e,t){return e+16*t}}class Xt{constructor(e,t){this.batchDataUint8=e,this.stringReader=t}editType(e){return zt(this.batchDataUint8,e)}siblingIndex(e){return zt(this.batchDataUint8,e+4)}newTreeIndex(e){return zt(this.batchDataUint8,e+8)}moveToSiblingIndex(e){return zt(this.batchDataUint8,e+8)}removedAttributeName(e){const t=zt(this.batchDataUint8,e+12);return this.stringReader.readString(t)}}class Yt{constructor(e,t){this.batchDataUint8=e,this.stringReader=t}frameType(e){return zt(this.batchDataUint8,e)}subtreeLength(e){return zt(this.batchDataUint8,e+4)}elementReferenceCaptureId(e){const t=zt(this.batchDataUint8,e+4);return this.stringReader.readString(t)}componentId(e){return zt(this.batchDataUint8,e+8)}elementName(e){const t=zt(this.batchDataUint8,e+8);return this.stringReader.readString(t)}textContent(e){const t=zt(this.batchDataUint8,e+4);return this.stringReader.readString(t)}markupContent(e){const t=zt(this.batchDataUint8,e+4);return this.stringReader.readString(t)}attributeName(e){const t=zt(this.batchDataUint8,e+4);return this.stringReader.readString(t)}attributeValue(e){const t=zt(this.batchDataUint8,e+8);return this.stringReader.readString(t)}attributeEventHandlerId(e){return Jt(this.batchDataUint8,e+12)}}class Gt{constructor(e){this.batchDataUint8=e,this.stringTableStartIndex=zt(e,e.length-4)}readString(e){if(-1===e)return null;{const n=zt(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(en.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(en.Debug,`Waiting for batch ${this.nextBatchId}. Batch ${e} not processed.`);try{this.nextBatchId++,this.logger.log(en.Debug,`Applying batch ${e}.`),function(e,t){const n=Q[e];if(!n)throw new Error(`There is no browser renderer with ID ${e}.`);const r=t.arrayRangeReader,o=t.updatedComponents(),i=r.values(o),s=r.count(o),a=t.referenceFrames(),c=r.values(a),l=t.diffReader;for(let e=0;e=this.minLevel){const n=`[${(new Date).toISOString()}] ${en[e]}: ${t}`;switch(e){case en.Critical:case en.Error:console.error(n);break;case en.Warning:console.warn(n);break;case en.Information:console.info(n);break;default:console.log(n)}}}}class on{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!==ke.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!==ke.Connected)return!1;const t=await e.invoke("StartCircuit",re.getBaseURI(),re.getLocationHref(),JSON.stringify(this.components.map((e=>e.toRecord()))),this.applicationState||"");return!!t&&(this.initialize(t),!0)}resolveElement(e){const t=Number.parseInt(e);if(Number.isNaN(t))throw new Error(`Invalid sequence number '${e}'.`);return function(e,t){if(!e.parentNode)throw new Error(`Comment not connected to the DOM ${e.textContent}`);const n=e.parentNode,r=k(n,!0),o=A(r);return Array.from(n.childNodes).forEach((e=>o.push(e))),e[C]=r,t&&(e[I]=t,k(t)),k(e)}(this.components[t].start,this.components[t].end)}}const sn={configureSignalR:e=>{},logLevel:en.Warning,reconnectionOptions:{maxRetries:8,retryIntervalMilliseconds:2e4,dialogId:"components-reconnect-modal"}};class an{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.modal.innerHTML='

Alternatively, reload

',this.message=this.modal.querySelector("h5"),this.button=this.modal.querySelector("button"),this.reloadParagraph=this.modal.querySelector("p"),this.loader=this.getLoader(),this.message.after(this.loader),this.button.addEventListener("click",(async()=>{this.show();try{await(null==fe?void 0:fe.reconnect)()||this.rejected()}catch(e){this.logger.log(en.Error,e),this.failed()}})),this.reloadParagraph.querySelector("a").addEventListener("click",(()=>location.reload()))}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",this.message.innerHTML="Reconnection failed. Try reloading the page if you're unable to reconnect.",this.message.querySelector("a").addEventListener("click",(()=>location.reload()))}rejected(){this.button.style.display="none",this.reloadParagraph.style.display="none",this.loader.style.display="none",this.message.innerHTML="Could not reconnect to the server. Reload the page to restore functionality.",this.message.querySelector("a").addEventListener("click",(()=>location.reload()))}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 cn{constructor(e,t,n){this.dialog=e,this.maxRetries=t,this.document=n,this.document=n;const r=this.document.getElementById(cn.MaxRetriesId);r&&(r.innerText=this.maxRetries.toString())}show(){this.removeClasses(),this.dialog.classList.add(cn.ShowClassName)}update(e){const t=this.document.getElementById(cn.CurrentAttemptId);t&&(t.innerText=e.toString())}hide(){this.removeClasses(),this.dialog.classList.add(cn.HideClassName)}failed(){this.removeClasses(),this.dialog.classList.add(cn.FailedClassName)}rejected(){this.removeClasses(),this.dialog.classList.add(cn.RejectedClassName)}removeClasses(){this.dialog.classList.remove(cn.ShowClassName,cn.HideClassName,cn.FailedClassName,cn.RejectedClassName)}}cn.ShowClassName="components-reconnect-show",cn.HideClassName="components-reconnect-hide",cn.FailedClassName="components-reconnect-failed",cn.RejectedClassName="components-reconnect-rejected",cn.MaxRetriesId="components-reconnect-max-retries",cn.CurrentAttemptId="components-reconnect-current-attempt";class ln{constructor(e,t,n){this._currentReconnectionProcess=null,this._logger=e,this._reconnectionDisplay=t,this._reconnectCallback=n||(()=>fe.reconnect())}onConnectionDown(e,t){if(!this._reconnectionDisplay){const t=document.getElementById(e.dialogId);this._reconnectionDisplay=t?new cn(t,e.maxRetries,document):new an(e.dialogId,e.maxRetries,document,this._logger)}this._currentReconnectionProcess||(this._currentReconnectionProcess=new hn(e,this._logger,this._reconnectCallback,this._reconnectionDisplay))}onConnectionUp(){this._currentReconnectionProcess&&(this._currentReconnectionProcess.dispose(),this._currentReconnectionProcess=null)}}class hn{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;thn.MaximumFirstRetryInterval?hn.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(en.Error,e)}}this.reconnectDisplay.failed()}delay(e){return new Promise((t=>setTimeout(t,e)))}}hn.MaximumFirstRetryInterval=3e3;const un=/^\s*Blazor-Component-State:(?[a-zA-Z0-9\+\/=]+)$/;function dn(e){var t;if(e.nodeType===Node.COMMENT_NODE){const n=e.textContent||"",r=un.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 gn(e,t){const n=e.currentElement;if(n&&n.nodeType===Node.COMMENT_NODE&&n.textContent){const r=fn.exec(n.textContent),o=r&&r.groups&&r.groups.descriptor;if(!o)return;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;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.");if(c){const e=mn(c,n);if(!e)throw new Error(`Could not find an end component comment for '${t}'`);return{type:r,assembly:o,typeName:i,parameterDefinitions:s&&atob(s),parameterValues:a&&atob(a),start:t,prerenderId:c,end:e}}return{type:r,assembly:o,typeName:i,parameterDefinitions:s&&atob(s),parameterValues:a&&atob(a),start:t}}}(r,n,e);case"server":return function(e,t,n){const{type:r,descriptor:o,sequence:i,prerenderId:s}=e;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)}'`);if(s){const e=mn(s,n);if(!e)throw new Error(`Could not find an end component comment for '${t}'`);return{type:r,sequence:i,descriptor:o,start:t,prerenderId:s,end:e}}return{type:r,sequence:i,descriptor:o,start:t}}}(r,n,e)}}catch(e){throw new Error(`Found malformed component comment at ${n.textContent}`)}}}function mn(e,t){for(;t.next()&&t.currentElement;){const n=t.currentElement;if(n.nodeType!==Node.COMMENT_NODE)continue;if(!n.textContent)continue;const r=fn.exec(n.textContent),o=r&&r[1];if(o)return yn(o,e),n}}function yn(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 wn{constructor(e){this.childNodes=e,this.currentIndex=-1,this.length=e.length}next(){return this.currentIndex++,this.currentIndexe.sequence-t.sequence))}(e)}(document),o=dn(document),i=new on(r,o||""),s=await Tn(t,n,i);if(!await i.startCircuit(s))return void n.log(en.Error,"Failed to start the circuit.");let a=!1;const c=()=>{if(!a){const e=new FormData,t=i.circuitId;e.append("circuitId",t),a=navigator.sendBeacon("_blazor/disconnect",e)}};fe.disconnect=c,window.addEventListener("unload",c,{capture:!1,once:!0}),fe.reconnect=async e=>{if(Cn)return!1;const r=e||await Tn(t,n,i);return await i.reconnect(r)?(t.reconnectionHandler.onConnectionUp(),!0):(n.log(en.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)},n.log(en.Information,"Blazor server-side application started.")}async function Tn(t,n,r){const i=new Mt;i.name="blazorpack";const s=(new rt).withUrl("_blazor").withHubProtocol(i);t.configureSignalR(s);const a=s.build();o=(e,t)=>{a.send("DispatchBrowserEvent",JSON.stringify(e),JSON.stringify(t))},fe._internal.navigationManager.listenForNavigationEvents(((e,t)=>a.send("OnLocationChanged",e,t))),a.on("JS.AttachComponent",((e,t)=>function(e,t,n){let r=Q[0];r||(r=Q[0]=new V(0)),r.attachRootComponentToLogicalElement(n,t)}(0,r.resolveElement(t),e))),a.on("JS.BeginInvokeJS",e.jsCallDispatcher.beginInvokeJSFromDotNet),a.on("JS.EndInvokeDotNet",e.jsCallDispatcher.endInvokeDotNetFromJS),a.on("JS.ReceiveByteArray",e.jsCallDispatcher.receiveByteArray);const c=tn.getOrCreate(n);a.on("JS.RenderBatch",((e,t)=>{n.log(en.Debug,`Received render batch with id ${e} and ${t.byteLength} bytes.`),c.processBatch(e,t,a)})),a.onclose((e=>!Cn&&t.reconnectionHandler.onConnectionDown(t.reconnectionOptions,e))),a.on("JS.Error",(e=>{Cn=!0,Dn(a,e,n),async function(){let e=document.querySelector("#blazor-error-ui");e&&(e.style.display="block"),Ot||(Ot=!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()}})))}()})),fe._internal.forceCloseConnection=()=>a.stop(),fe._internal.sendJSDataStream=(e,t,n)=>{setTimeout((async()=>{let r=5,o=(new Date).valueOf();try{const i=n-512;if(i<=0)throw new Error("The chunk size must be greater than 0.");let s=0;for(;s1)await a.send("ReceiveJSDataChunk",t,c,null);else{if(!await a.invoke("ReceiveJSDataChunk",t,c,null))break;const e=(new Date).valueOf(),n=e-o;o=e,r=Math.max(1,Math.round(500/n))}s+=n}}catch(e){await a.send("ReceiveJSDataChunk",t,null,e.toString())}}),0)};try{await a.start()}catch(e){Dn(a,e,n)}return e.attachDispatcher({beginInvokeDotNetFromJS:(e,t,n,r,o)=>{a.send("BeginInvokeDotNetFromJS",e?e.toString():null,t,n,r||0,o)},endInvokeJSFromDotNet:(e,t,n)=>{a.send("EndInvokeJSFromDotNet",e,t,n)},sendByteArray:(e,t)=>{a.send("ReceiveByteArray",e,t)}}),a}function Dn(e,t,n){n.log(en.Error,t),e&&e.stop()}fe.start=kn,document&&document.currentScript&&"false"!==document.currentScript.getAttribute("autostart")&&kn()})(); \ No newline at end of file +(()=>{"use strict";var e,t,n;!function(e){window.DotNet=e;const t=[],n=new Map;class r{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 o="__jsObjectId",i={},s={0:new r(window)};s[0]._cachedFunctions.set("import",(e=>("string"==typeof e&&e.startsWith("./")&&(e=document.baseURI+e.substr(2)),import(e))));let a,c=1,l=1,h=null;function u(e){t.push(e)}function d(e){if(e&&"object"==typeof e){s[l]=new r(e);const t={[o]:l};return l++,t}throw new Error(`Cannot create a JSObjectReference from the value '${e}'.`)}function p(e){if(!(e.buffer instanceof ArrayBuffer))throw new Error(`Cannot create a JSStreamReference from the value '${e}' as it is not a valid ArrayBuffer.`);if(void 0===e.byteLength)throw new Error(`Cannot create a JSStreamReference from the value '${e}' as it doesn't have a byteLength.`);const t={__jsStreamReferenceLength:e.byteLength-5};try{const n=d(e);t.__jsObjectId=n.__jsObjectId}catch{throw new Error(`Cannot create a JSStreamReference from the value '${e}'.`)}return t}function f(e){return e?JSON.parse(e,((e,n)=>t.reduce(((t,n)=>n(e,t)),n))):null}function g(e,t,n,r){const o=y();if(o.invokeDotNetFromJS){const i=k(r),s=o.invokeDotNetFromJS(e,t,n,i);return s?f(s):null}throw new Error("The current dispatcher does not support synchronous calls from JS to .NET. Use invokeMethodAsync instead.")}function m(e,t,n,r){if(e&&n)throw new Error(`For instance method calls, assemblyName should be null. Received '${e}'.`);const o=c++,s=new Promise(((e,t)=>{i[o]={resolve:e,reject:t}}));try{const i=k(r);y().beginInvokeDotNetFromJS(o,e,t,n,i)}catch(e){w(o,!1,e)}return s}function y(){if(null!==h)return h;throw new Error("No .NET call dispatcher has been set.")}function w(e,t,n){if(!i.hasOwnProperty(e))throw new Error(`There is no pending async call with ID ${e}.`);const r=i[e];delete i[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){let n=s[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 s[e]}e.attachDispatcher=function(e){h=e},e.attachReviver=u,e.invokeMethod=function(e,t,...n){return g(e,t,null,n)},e.invokeMethodAsync=function(e,t,...n){return m(e,t,null,n)},e.createJSObjectReference=d,e.createJSStreamReference=p,e.disposeJSObjectReference=function(e){const t=e&&e.__jsObjectId;"number"==typeof t&&_(t)},function(e){e[e.Default=0]="Default",e[e.JSObjectReference=1]="JSObjectReference",e[e.JSStreamReference=2]="JSStreamReference"}(a=e.JSCallResultType||(e.JSCallResultType={})),e.jsCallDispatcher={findJSFunction:b,disposeJSObjectReferenceById:_,invokeJSFromDotNet:(e,t,n,r)=>{const o=C(b(e,r).apply(null,f(t)),n);return null==o?null:k(o)},beginInvokeJSFromDotNet:(e,t,n,r,o)=>{const i=new Promise((e=>{e(b(t,o).apply(null,f(n)))}));e&&i.then((t=>y().endInvokeJSFromDotNet(e,!0,k([e,!0,C(t,r)]))),(t=>y().endInvokeJSFromDotNet(e,!1,JSON.stringify([e,!1,v(t)]))))},endInvokeDotNetFromJS:(e,t,n)=>{const r=t?f(n):new Error(n);w(parseInt(e),t,r)},receiveByteArray:(e,t)=>{n.set(e,t)}};class E{constructor(e){this._id=e}invokeMethod(e,...t){return g(null,e,this._id,t)}invokeMethodAsync(e,...t){return m(null,e,this._id,t)}dispose(){m(null,"__Dispose",this._id,null).catch((e=>console.error(e)))}serializeAsArg(){return{__dotNetObject:this._id}}}const S="__byte[]";function C(e,t){switch(t){case a.Default:return e;case a.JSObjectReference:return d(e);case a.JSStreamReference:return p(e);default:throw new Error(`Invalid JS call result type '${t}'.`)}}u((function(e,t){if(t&&"object"==typeof t){if(t.hasOwnProperty("__dotNetObject"))return new E(t.__dotNetObject);if(t.hasOwnProperty(o)){const e=t.__jsObjectId,n=s[e];if(n)return n.getWrappedObject();throw new Error(`JS object instance with Id '${e}' does not exist. It may have been disposed.`)}if(t.hasOwnProperty(S)){const e=t["__byte[]"],r=n.get(e);if(void 0===r)throw new Error(`Byte array index '${e}' does not exist.`);return r}}return t}));let I=0;function k(e){return I=0,JSON.stringify(e,T)}function T(e,t){if(t instanceof E)return t.serializeAsArg();if(t instanceof Uint8Array){h.sendByteArray(I,t);const e={[S]:I};return I++,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"}(n||(n={}));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}}let o;function i(e,t){if(!o)throw new Error("eventDispatcher not initialized. Call 'setEventDispatcher' to configure it.");o(e,t)}const s=new Map,a=new Map,c={createEventArgs:()=>({})},l=[];function h(e){return s.get(e)}function u(e){const t=s.get(e);return(null==t?void 0:t.browserEventName)||e}function d(e,t){e.forEach((e=>s.set(e,t)))}function p(e){const t=[];for(let n=0;n{return{...f(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}}),d(["focus","blur","focusin","focusout"],c),d(["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};var t}}),d(["contextmenu","click","mouseover","mouseout","mousemove","mousedown","mouseup","dblclick"],{createEventArgs:e=>f(e)}),d(["error"],{createEventArgs:e=>{return{message:(t=e).message,filename:t.filename,lineno:t.lineno,colno:t.colno};var t}}),d(["loadstart","timeout","abort","load","loadend","progress"],{createEventArgs:e=>{return{lengthComputable:(t=e).lengthComputable,loaded:t.loaded,total:t.total};var t}}),d(["touchcancel","touchend","touchmove","touchenter","touchleave","touchstart"],{createEventArgs:e=>{return{detail:(t=e).detail,touches:p(t.touches),targetTouches:p(t.targetTouches),changedTouches:p(t.changedTouches),ctrlKey:t.ctrlKey,shiftKey:t.shiftKey,altKey:t.altKey,metaKey:t.metaKey,type:t.type};var t}}),d(["gotpointercapture","lostpointercapture","pointercancel","pointerdown","pointerenter","pointerleave","pointermove","pointerout","pointerover","pointerup"],{createEventArgs:e=>{return{...f(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}}),d(["wheel","mousewheel"],{createEventArgs:e=>{return{...f(t=e),deltaX:t.deltaX,deltaY:t.deltaY,deltaZ:t.deltaZ,deltaMode:t.deltaMode};var t}}),d(["toggle"],c);const g=["date","datetime-local","month","time","week"],m=E(["abort","blur","change","error","focus","load","loadend","loadstart","mouseenter","mouseleave","progress","reset","scroll","submit","unload","toggle","DOMNodeInsertedIntoDocument","DOMNodeRemovedFromDocument"]),y={submit:!0},w=E(["click","dblclick","mousedown","mousemove","mouseup"]);class v{constructor(e){this.browserRendererId=e,this.afterClickCallbacks=[];const t=++v.nextEventDelegatorId;this.eventsCollectionKey=`_blazorEvents_${t}`,this.eventInfoStore=new b(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,a.get(n));var n;t&&t.forEach((t=>this.dispatchGlobalEventToAllElements(t,e))),"click"===e.type&&this.afterClickCallbacks.forEach((t=>t(e)))}dispatchGlobalEventToAllElements(e,t){let n=t.target,o=null,s=!1;const a=m.hasOwnProperty(e);let c=!1;for(;n;){const d=this.getEventHandlerInfosForElement(n,!1);if(d){const a=d.getHandler(e);if(a&&(l=n,u=t.type,!((l instanceof HTMLButtonElement||l instanceof HTMLInputElement||l instanceof HTMLTextAreaElement||l instanceof HTMLSelectElement)&&w.hasOwnProperty(u)&&l.disabled))){if(!s){const n=h(e);o=(null==n?void 0:n.createEventArgs)?n.createEventArgs(t):{},s=!0}y.hasOwnProperty(t.type)&&t.preventDefault(),i({browserRendererId:this.browserRendererId,eventHandlerId:a.eventHandlerId,eventName:e,eventFieldInfo:r.fromEvent(a.renderingComponentId,t)},o)}d.stopPropagation(e)&&(c=!0),d.preventDefault(e)&&t.preventDefault()}n=a||c?null:n.parentElement}var l,u}getEventHandlerInfosForElement(e,t){return e.hasOwnProperty(this.eventsCollectionKey)?e[this.eventsCollectionKey]:t?e[this.eventsCollectionKey]=new _:null}}v.nextEventDelegatorId=0;class b{constructor(e){this.globalListener=e,this.infosByEventHandlerId={},this.countByEventName={},l.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=u(e),this.countByEventName.hasOwnProperty(e))this.countByEventName[e]++;else{this.countByEventName[e]=1;const t=m.hasOwnProperty(e);document.addEventListener(e,this.globalListener,t)}}update(e,t){if(this.infosByEventHandlerId.hasOwnProperty(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=u(t.eventName);0==--this.countByEventName[n]&&(delete this.countByEventName[n],document.removeEventListener(n,this.globalListener))}return t}handleEventNameAliasAdded(e,t){if(this.countByEventName.hasOwnProperty(e)){const n=this.countByEventName[e];delete this.countByEventName[e],document.removeEventListener(e,this.globalListener),this.addGlobalListener(t),this.countByEventName[t]+=n-1}}}class _{constructor(){this.handlers={},this.preventDefaultFlags=null,this.stopPropagationFlags=null}getHandler(e){return this.handlers.hasOwnProperty(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 E(e){const t={};return e.forEach((e=>{t[e]=!0})),t}const S=O("_blazorLogicalChildren"),C=O("_blazorLogicalParent"),I=O("_blazorLogicalEnd");function k(e,t){if(e.childNodes.length>0&&!t)throw new Error("New logical elements must start empty, or allowExistingContents must be true");return S in e||(e[S]=[]),e}function T(e,t){const n=document.createComment("!");return x(n,e,t),n}function x(e,t,n){const r=e;if(e instanceof Comment&&A(r)&&A(r).length>0)throw new Error("Not implemented: inserting non-empty logical container");if(R(r))throw new Error("Not implemented: moving existing logical children");const o=A(t);if(n0;)D(n,0)}const r=n;r.parentNode.removeChild(r)}function R(e){return e[C]||null}function P(e,t){return A(e)[t]}function U(e){var t=B(e);return"http://www.w3.org/2000/svg"===t.namespaceURI&&"foreignObject"!==t.tagName}function A(e){return e[S]}function N(e,t){const n=A(e);t.forEach((e=>{e.moveRangeStart=n[e.fromSiblingIndex],e.moveRangeEnd=M(e.moveRangeStart)})),t.forEach((t=>{const r=t.moveToBeforeMarker=document.createComment("marker"),o=n[t.toSiblingIndex+1];o?o.parentNode.insertBefore(r,o):L(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 B(e){if(e instanceof Element)return e;if(e instanceof Comment)return e.parentNode;throw new Error("Not a valid logical element")}function $(e){const t=A(R(e));return t[Array.prototype.indexOf.call(t,e)+1]||null}function L(e,t){if(t instanceof Element)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=$(t);n?n.parentNode.insertBefore(e,n):L(e,R(t))}}}function M(e){if(e instanceof Element)return e;const t=$(e);if(t)return t.previousSibling;{const t=R(e);return t instanceof Element?t.lastChild:M(t)}}function O(e){return"function"==typeof Symbol?Symbol():e}function H(e){return`_bl_${e}`}e.attachReviver(((e,t)=>t&&"object"==typeof t&&t.hasOwnProperty("__internalId")&&"string"==typeof t.__internalId?function(e){const t=`[${H(e)}]`;return document.querySelector(t)}(t.__internalId):t));const F="_blazorSelectValue",j=document.createElement("template"),W=document.createElementNS("http://www.w3.org/2000/svg","g"),z={},q="__internal_",J="preventDefault_",K="stopPropagation_";class V{constructor(e){this.childComponentLocations={},this.eventDelegator=new v(e),this.eventDelegator.notifyAfterClick((e=>{if(!ee)return;if(0!==e.button||function(e){return e.ctrlKey||e.shiftKey||e.altKey||e.metaKey}(e))return;if(e.defaultPrevented)return;const t=function(e){const t=!window._blazorDisableComposedPath&&e.composedPath&&e.composedPath();if(t){for(let e=0;ese(!1))))},enableNavigationInterception:function(){ee=!0},navigateTo:oe,getBaseURI:()=>document.baseURI,getLocationHref:()=>location.href};function oe(e,t,n=!1){const r=ce(e);if(!t&&he(r))ie(r,!1,n);else if(t&&location.href===e){const t=e+"?";history.replaceState(null,"",t),location.replace(e)}else n?history.replaceState(null,"",r):location.href=e}function ie(e,t,n=!1){Z=!0,n?history.replaceState(null,"",e):history.pushState(null,"",e),se(t)}async function se(e){ne&&await ne(location.href,e)}let ae;function ce(e){return ae=ae||document.createElement("a"),ae.href=e,ae.href}function le(e,t){return e?e.tagName===t?e:le(e.parentElement,t):null}function he(e){const t=(n=document.baseURI).substr(0,n.lastIndexOf("/")+1);var n;return e.startsWith(t)}const ue={init:function(e,t,n,r=50){const o=pe(t);(o||document.documentElement).style.overflowAnchor="none";const i=new IntersectionObserver((function(r){r.forEach((r=>{var o;if(!r.isIntersecting)return;const i=t.getBoundingClientRect(),s=n.getBoundingClientRect().top-i.bottom,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`});i.observe(t),i.observe(n);const s=c(t),a=c(n);function c(e){const t=new MutationObserver((()=>{i.unobserve(e),i.observe(e)}));return t.observe(e,{attributes:!0}),t}de[e._id]={intersectionObserver:i,mutationObserverBefore:s,mutationObserverAfter:a}},dispose:function(e){const t=de[e._id];t&&(t.intersectionObserver.disconnect(),t.mutationObserverBefore.disconnect(),t.mutationObserverAfter.disconnect(),e.dispose(),delete de[e._id])}},de={};function pe(e){return e?"visible"!==getComputedStyle(e).overflowY?e:pe(e.parentElement):null}const fe={navigateTo:oe,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=a.get(t.browserEventName);n?n.push(e):a.set(t.browserEventName,[e]),l.forEach((n=>n(e,t.browserEventName)))}s.set(e,t)},_internal:{navigationManager:re,domWrapper:{focus:function(e,t){if(!(e instanceof HTMLElement))throw new Error("Unable to focus an invalid element.");e.focus({preventScroll:t})},focusBySelector:function(e){const t=document.querySelector(e);t&&(t.hasAttribute("tabindex")||(t.tabIndex=-1),t.focus())}},Virtualize:ue}};window.Blazor=fe;const ge=[0,2e3,1e4,3e4,null];class me{constructor(e){this._retryDelays=void 0!==e?[...e,null]:ge}nextRetryDelayInMilliseconds(e){return this._retryDelays[e.previousRetryCount]}}class ye extends Error{constructor(e,t){const n=new.target.prototype;super(`${e}: Status code '${t}'`),this.statusCode=t,this.__proto__=n}}class we extends Error{constructor(e="A timeout occurred."){const t=new.target.prototype;super(e),this.__proto__=t}}class ve extends Error{constructor(e="An abort occurred."){const t=new.target.prototype;super(e),this.__proto__=t}}class be{constructor(e,t,n){this.statusCode=e,this.statusText=t,this.content=n}}class _e{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""}}var Ee,Se,Ce,Ie,ke;!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"}(Ee||(Ee={}));class Te extends _e{constructor(e){if(super(),this._logger=e,"undefined"==typeof fetch){const e=require;this._jar=new(e("tough-cookie").CookieJar),this._fetchType=e("node-fetch"),this._fetchType=e("fetch-cookie")(this._fetchType,this._jar),this._abortControllerType=e("abort-controller")}else this._fetchType=fetch.bind(self),this._abortControllerType=AbortController}async send(e){if(e.abortSignal&&e.abortSignal.aborted)throw new ve;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 ve});let r,o=null;if(e.timeout){const r=e.timeout;o=setTimeout((()=>{t.abort(),this._logger.log(Ee.Warning,"Timeout from HTTP request."),n=new we}),r)}try{r=await this._fetchType(e.url,{body:e.content,cache:"no-cache",credentials:!0===e.withCredentials?"include":"same-origin",headers:{"Content-Type":"text/plain;charset=UTF-8","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(Ee.Warning,`Error from HTTP request. ${e}.`),e}finally{o&&clearTimeout(o),e.abortSignal&&(e.abortSignal.onabort=null)}if(!r.ok){const e=await xe(r,"text");throw new ye(e||r.statusText,r.status)}const i=xe(r,e.responseType),s=await i;return new be(r.status,r.statusText,s)}getCookieString(e){return""}}function xe(e,t){let n;switch(t){case"arraybuffer":n=e.arrayBuffer();break;case"text":n=e.text();break;case"blob":case"document":case"json":throw new Error(`${t} is not supported.`);default:n=e.text()}return n}class De extends _e{constructor(e){super(),this._logger=e}send(e){return e.abortSignal&&e.abortSignal.aborted?Promise.reject(new ve):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"),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 ve)}),e.timeout&&(r.timeout=e.timeout),r.onload=()=>{e.abortSignal&&(e.abortSignal.onabort=null),r.status>=200&&r.status<300?t(new be(r.status,r.statusText,r.response||r.responseText)):n(new ye(r.response||r.responseText||r.statusText,r.status))},r.onerror=()=>{this._logger.log(Ee.Warning,`Error from HTTP request. ${r.status}: ${r.statusText}.`),n(new ye(r.statusText,r.status))},r.ontimeout=()=>{this._logger.log(Ee.Warning,"Timeout from HTTP request."),n(new we)},r.send(e.content||"")})):Promise.reject(new Error("No url defined.")):Promise.reject(new Error("No method defined."))}}class Re extends _e{constructor(e){if(super(),"undefined"!=typeof fetch)this._httpClient=new Te(e);else{if("undefined"==typeof XMLHttpRequest)throw new Error("No usable HttpClient found.");this._httpClient=new De(e)}}send(e){return e.abortSignal&&e.abortSignal.aborted?Promise.reject(new ve):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)}}class Pe{}Pe.Authorization="Authorization",Pe.Cookie="Cookie",function(e){e[e.None=0]="None",e[e.WebSockets=1]="WebSockets",e[e.ServerSentEvents=2]="ServerSentEvents",e[e.LongPolling=4]="LongPolling"}(Se||(Se={})),function(e){e[e.Text=1]="Text",e[e.Binary=2]="Binary"}(Ce||(Ce={}));class Ue{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 Ae{constructor(){}log(e,t){}}Ae.instance=new Ae;class Ne{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 Be{static get isBrowser(){return"object"==typeof window}static get isWebWorker(){return"object"==typeof self&&"importScripts"in self}static get isNode(){return!this.isBrowser&&!this.isWebWorker}}function $e(e,t){let n="";return Le(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 Le(e){return e&&"undefined"!=typeof ArrayBuffer&&(e instanceof ArrayBuffer||e.constructor&&"ArrayBuffer"===e.constructor.name)}async function Me(e,t,n,r,o,i,s,a,c){let l={};if(o){const e=await o();e&&(l={Authorization:`Bearer ${e}`})}const[h,u]=Fe();l[h]=u,e.log(Ee.Trace,`(${t} transport) sending data. ${$e(i,s)}.`);const d=Le(i)?"arraybuffer":"text",p=await n.post(r,{content:i,headers:{...l,...c},responseType:d,withCredentials:a});e.log(Ee.Trace,`(${t} transport) request complete. Response status: ${p.statusCode}.`)}class Oe{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 He{constructor(e){this._minLevel=e,this.out=console}log(e,t){if(e>=this._minLevel){const n=`[${(new Date).toISOString()}] ${Ee[e]}: ${t}`;switch(e){case Ee.Critical:case Ee.Error:this.out.error(n);break;case Ee.Warning:this.out.warn(n);break;case Ee.Information:this.out.info(n);break;default:this.out.log(n)}}}}function Fe(){let e="X-SignalR-User-Agent";return Be.isNode&&(e="User-Agent"),[e,je("0.0.0-DEV_BUILD",We(),Be.isNode?"NodeJS":"Browser",ze())]}function je(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 We(){if(!Be.isNode)return"";switch(process.platform){case"win32":return"Windows NT";case"darwin":return"macOS";case"linux":return"Linux";default:return process.platform}}function ze(){if(Be.isNode)return process.versions.node}class qe{constructor(e,t,n,r,o,i){this._httpClient=e,this._accessTokenFactory=t,this._logger=n,this._pollAbort=new Ue,this._logMessageContent=r,this._withCredentials=o,this._headers=i,this._running=!1,this.onreceive=null,this.onclose=null}get pollAborted(){return this._pollAbort.aborted}async connect(e,t){if(Ne.isRequired(e,"url"),Ne.isRequired(t,"transferFormat"),Ne.isIn(t,Ce,"transferFormat"),this._url=e,this._logger.log(Ee.Trace,"(LongPolling transport) Connecting."),t===Ce.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]=Fe(),o={[n]:r,...this._headers},i={abortSignal:this._pollAbort.signal,headers:o,timeout:1e5,withCredentials:this._withCredentials};t===Ce.Binary&&(i.responseType="arraybuffer");const s=await this._getAccessToken();this._updateHeaderToken(i,s);const a=`${e}&_=${Date.now()}`;this._logger.log(Ee.Trace,`(LongPolling transport) polling: ${a}.`);const c=await this._httpClient.get(a,i);200!==c.statusCode?(this._logger.log(Ee.Error,`(LongPolling transport) Unexpected response code: ${c.statusCode}.`),this._closeError=new ye(c.statusText||"",c.statusCode),this._running=!1):this._running=!0,this._receiving=this._poll(this._url,i)}async _getAccessToken(){return this._accessTokenFactory?await this._accessTokenFactory():null}_updateHeaderToken(e,t){e.headers||(e.headers={}),t?e.headers[Pe.Authorization]=`Bearer ${t}`:e.headers[Pe.Authorization]&&delete e.headers[Pe.Authorization]}async _poll(e,t){try{for(;this._running;){const n=await this._getAccessToken();this._updateHeaderToken(t,n);try{const n=`${e}&_=${Date.now()}`;this._logger.log(Ee.Trace,`(LongPolling transport) polling: ${n}.`);const r=await this._httpClient.get(n,t);204===r.statusCode?(this._logger.log(Ee.Information,"(LongPolling transport) Poll terminated by server."),this._running=!1):200!==r.statusCode?(this._logger.log(Ee.Error,`(LongPolling transport) Unexpected response code: ${r.statusCode}.`),this._closeError=new ye(r.statusText||"",r.statusCode),this._running=!1):r.content?(this._logger.log(Ee.Trace,`(LongPolling transport) data received. ${$e(r.content,this._logMessageContent)}.`),this.onreceive&&this.onreceive(r.content)):this._logger.log(Ee.Trace,"(LongPolling transport) Poll timed out, reissuing.")}catch(e){this._running?e instanceof we?this._logger.log(Ee.Trace,"(LongPolling transport) Poll timed out, reissuing."):(this._closeError=e,this._running=!1):this._logger.log(Ee.Trace,`(LongPolling transport) Poll errored after shutdown: ${e.message}`)}}}finally{this._logger.log(Ee.Trace,"(LongPolling transport) Polling complete."),this.pollAborted||this._raiseOnClose()}}async send(e){return this._running?Me(this._logger,"LongPolling",this._httpClient,this._url,this._accessTokenFactory,e,this._logMessageContent,this._withCredentials,this._headers):Promise.reject(new Error("Cannot send until the transport is connected"))}async stop(){this._logger.log(Ee.Trace,"(LongPolling transport) Stopping polling."),this._running=!1,this._pollAbort.abort();try{await this._receiving,this._logger.log(Ee.Trace,`(LongPolling transport) sending DELETE request to ${this._url}.`);const e={},[t,n]=Fe();e[t]=n;const r={headers:{...e,...this._headers},withCredentials:this._withCredentials},o=await this._getAccessToken();this._updateHeaderToken(r,o),await this._httpClient.delete(this._url,r),this._logger.log(Ee.Trace,"(LongPolling transport) DELETE request sent.")}finally{this._logger.log(Ee.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(Ee.Trace,e),this.onclose(this._closeError)}}}class Je{constructor(e,t,n,r,o,i,s){this._httpClient=e,this._accessTokenFactory=t,this._logger=n,this._logMessageContent=r,this._withCredentials=i,this._eventSourceConstructor=o,this._headers=s,this.onreceive=null,this.onclose=null}async connect(e,t){if(Ne.isRequired(e,"url"),Ne.isRequired(t,"transferFormat"),Ne.isIn(t,Ce,"transferFormat"),this._logger.log(Ee.Trace,"(SSE transport) Connecting."),this._url=e,this._accessTokenFactory){const t=await this._accessTokenFactory();t&&(e+=(e.indexOf("?")<0?"?":"&")+`access_token=${encodeURIComponent(t)}`)}return new Promise(((n,r)=>{let o,i=!1;if(t===Ce.Text){if(Be.isBrowser||Be.isWebWorker)o=new this._eventSourceConstructor(e,{withCredentials:this._withCredentials});else{const t=this._httpClient.getCookieString(e),n={};n.Cookie=t;const[r,i]=Fe();n[r]=i,o=new this._eventSourceConstructor(e,{withCredentials:this._withCredentials,headers:{...n,...this._headers}})}try{o.onmessage=e=>{if(this.onreceive)try{this._logger.log(Ee.Trace,`(SSE transport) data received. ${$e(e.data,this._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(Ee.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?Me(this._logger,"SSE",this._httpClient,this._url,this._accessTokenFactory,e,this._logMessageContent,this._withCredentials,this._headers):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 Ke{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){if(Ne.isRequired(e,"url"),Ne.isRequired(t,"transferFormat"),Ne.isIn(t,Ce,"transferFormat"),this._logger.log(Ee.Trace,"(WebSockets transport) Connecting."),this._accessTokenFactory){const t=await this._accessTokenFactory();t&&(e+=(e.indexOf("?")<0?"?":"&")+`access_token=${encodeURIComponent(t)}`)}return new Promise(((n,r)=>{let o;e=e.replace(/^http/,"ws"),this._httpClient.getCookieString(e);let i=!1;o||(o=new this._webSocketConstructor(e)),t===Ce.Binary&&(o.binaryType="arraybuffer"),o.onopen=t=>{this._logger.log(Ee.Information,`WebSocket connected to ${e}.`),this._webSocket=o,i=!0,n()},o.onerror=e=>{let t=null;t="undefined"!=typeof ErrorEvent&&e instanceof ErrorEvent?e.error:"There was an error with the transport",this._logger.log(Ee.Information,`(WebSockets transport) ${t}.`)},o.onmessage=e=>{if(this._logger.log(Ee.Trace,`(WebSockets transport) data received. ${$e(e.data,this._logMessageContent)}.`),this.onreceive)try{this.onreceive(e.data)}catch(e){return void this._close(e)}},o.onclose=e=>{if(i)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(Ee.Trace,`(WebSockets transport) sending data. ${$e(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(Ee.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 Ve{constructor(e,t={}){var n;if(this._stopPromiseResolver=()=>{},this.features={},this._negotiateVersion=1,Ne.isRequired(e,"url"),this._logger=void 0===(n=t.logger)?new He(Ee.Information):null===n?Ae.instance:void 0!==n.log?n:new He(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,"undefined"==typeof WebSocket||t.WebSocket||(t.WebSocket=WebSocket),"undefined"==typeof EventSource||t.EventSource||(t.EventSource=EventSource),this._httpClient=t.httpClient||new Re(this._logger),this._connectionState="Disconnected",this._connectionStarted=!1,this._options=t,this.onreceive=null,this.onclose=null}async start(e){if(e=e||Ce.Binary,Ne.isIn(e,Ce,"transferFormat"),this._logger.log(Ee.Debug,`Starting connection with transfer format '${Ce[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(Ee.Error,e),await this._stopPromise,Promise.reject(new Error(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(Ee.Error,e),Promise.reject(new Error(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 Xe(this.transport)),this._sendQueue.send(e))}async stop(e){return"Disconnected"===this._connectionState?(this._logger.log(Ee.Debug,`Call to HttpConnection.stop(${e}) ignored because the connection is already in the disconnected state.`),Promise.resolve()):"Disconnecting"===this._connectionState?(this._logger.log(Ee.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(Ee.Error,`HttpConnection.transport.stop() threw error '${e}'.`),this._stopConnection()}this.transport=void 0}else this._logger.log(Ee.Debug,"HttpConnection.transport is undefined in HttpConnection.stop() because start() failed.")}async _startInternal(e){let t=this.baseUrl;this._accessTokenFactory=this._options.accessTokenFactory;try{if(this._options.skipNegotiation){if(this._options.transport!==Se.WebSockets)throw new Error("Negotiation can only be skipped when using the WebSocket transport directly.");this.transport=this._constructTransport(Se.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 Error("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}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 qe&&(this.features.inherentKeepAlive=!0),"Connecting"===this._connectionState&&(this._logger.log(Ee.Debug,"The HttpConnection connected successfully."),this._connectionState="Connected")}catch(e){return this._logger.log(Ee.Error,"Failed to start the connection: "+e),this._connectionState="Disconnected",this.transport=void 0,this._stopPromiseResolver(),Promise.reject(e)}}async _getNegotiationResponse(e){const t={};if(this._accessTokenFactory){const e=await this._accessTokenFactory();e&&(t[Pe.Authorization]=`Bearer ${e}`)}const[n,r]=Fe();t[n]=r;const o=this._resolveNegotiateUrl(e);this._logger.log(Ee.Debug,`Sending negotiation request: ${o}.`);try{const e=await this._httpClient.post(o,{content:"",headers:{...t,...this._options.headers},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 ye&&404===e.statusCode&&(t+=" Either this is not a SignalR endpoint or there is a proxy blocking the connection."),this._logger.log(Ee.Error,t),Promise.reject(new Error(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(Ee.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: ${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(Ee.Error,`Failed to start the transport '${n.transport}': ${e}`),a=void 0,i.push(`${n.transport} failed: ${e}`),"Connecting"!==this._connectionState){const e="Failed to select transport before stop() was called.";return this._logger.log(Ee.Debug,e),Promise.reject(new Error(e))}}}}return i.length>0?Promise.reject(new Error(`Unable to connect to the server with any of the available transports. ${i.join(" ")}`)):Promise.reject(new Error("None of the transports supported by the client are supported by the server."))}_constructTransport(e){switch(e){case Se.WebSockets:if(!this._options.WebSocket)throw new Error("'WebSocket' is not supported in your environment.");return new Ke(this._httpClient,this._accessTokenFactory,this._logger,this._options.logMessageContent||!1,this._options.WebSocket,this._options.headers||{});case Se.ServerSentEvents:if(!this._options.EventSource)throw new Error("'EventSource' is not supported in your environment.");return new Je(this._httpClient,this._accessTokenFactory,this._logger,this._options.logMessageContent||!1,this._options.EventSource,this._options.withCredentials,this._options.headers||{});case Se.LongPolling:return new qe(this._httpClient,this._accessTokenFactory,this._logger,this._options.logMessageContent||!1,this._options.withCredentials,this._options.headers||{});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=Se[e.transport];if(null==r)return this._logger.log(Ee.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(Ee.Debug,`Skipping transport '${Se[r]}' because it was disabled by the client.`),new Error(`'${Se[r]}' is disabled by the client.`);if(!(e.transferFormats.map((e=>Ce[e])).indexOf(n)>=0))return this._logger.log(Ee.Debug,`Skipping transport '${Se[r]}' because it does not support the requested transfer format '${Ce[n]}'.`),new Error(`'${Se[r]}' does not support ${Ce[n]}.`);if(r===Se.WebSockets&&!this._options.WebSocket||r===Se.ServerSentEvents&&!this._options.EventSource)return this._logger.log(Ee.Debug,`Skipping transport '${Se[r]}' because it is not supported in your environment.'`),new Error(`'${Se[r]}' is not supported in your environment.`);this._logger.log(Ee.Debug,`Selecting transport '${Se[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(Ee.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(Ee.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(Ee.Error,`Connection disconnected with error '${e}'.`):this._logger.log(Ee.Information,"Connection disconnected."),this._sendQueue&&(this._sendQueue.stop().catch((e=>{this._logger.log(Ee.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(Ee.Error,`HttpConnection.onclose(${e}) threw error '${t}'.`)}}}else this._logger.log(Ee.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(!Be.isBrowser||!window.document)throw new Error(`Cannot resolve '${e}'.`);const t=window.document.createElement("a");return t.href=e,this._logger.log(Ee.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 Xe{constructor(e){this._transport=e,this._buffer=[],this._executing=!0,this._sendBufferedData=new Ye,this._transportResult=new Ye,this._sendLoopPromise=this._sendLoop()}send(e){return this._bufferData(e),this._transportResult||(this._transportResult=new Ye),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 Ye;const e=this._transportResult;this._transportResult=void 0;const t="string"==typeof this._buffer[0]?this._buffer.join(""):Xe._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 Ye{constructor(){this.promise=new Promise(((e,t)=>[this._resolver,this._rejecter]=[e,t]))}resolve(){this._resolver()}reject(e){this._rejecter(e)}}class Ge{static write(e){return`${e}${Ge.RecordSeparator}`}static parse(e){if(e[e.length-1]!==Ge.RecordSeparator)throw new Error("Message is incomplete.");const t=e.split(Ge.RecordSeparator);return t.pop(),t}}Ge.RecordSeparatorCode=30,Ge.RecordSeparator=String.fromCharCode(Ge.RecordSeparatorCode);class Qe{writeHandshakeRequest(e){return Ge.write(JSON.stringify(e))}parseHandshakeResponse(e){let t,n;if(Le(e)){const r=new Uint8Array(e),o=r.indexOf(Ge.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(Ge.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=Ge.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"}(Ie||(Ie={}));class Ze{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 Oe(this,e)}}!function(e){e.Disconnected="Disconnected",e.Connecting="Connecting",e.Connected="Connected",e.Disconnecting="Disconnecting",e.Reconnecting="Reconnecting"}(ke||(ke={}));class et{constructor(e,t,n,r){this._nextKeepAlive=0,Ne.isRequired(e,"connection"),Ne.isRequired(t,"logger"),Ne.isRequired(n,"protocol"),this.serverTimeoutInMilliseconds=3e4,this.keepAliveIntervalInMilliseconds=15e3,this._logger=t,this._protocol=n,this.connection=e,this._reconnectPolicy=r,this._handshakeProtocol=new Qe,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=ke.Disconnected,this._connectionStarted=!1,this._cachedPingMessage=this._protocol.writeMessage({type:Ie.Ping})}static create(e,t,n,r){return new et(e,t,n,r)}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!==ke.Disconnected&&this._connectionState!==ke.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!==ke.Disconnected)return Promise.reject(new Error("Cannot start a HubConnection that is not in the 'Disconnected' state."));this._connectionState=ke.Connecting,this._logger.log(Ee.Debug,"Starting HubConnection.");try{await this._startInternal(),this._connectionState=ke.Connected,this._connectionStarted=!0,this._logger.log(Ee.Debug,"HubConnection connected successfully.")}catch(e){return this._connectionState=ke.Disconnected,this._logger.log(Ee.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(Ee.Debug,"Sending handshake request."),await this._sendMessage(this._handshakeProtocol.writeHandshakeRequest(t)),this._logger.log(Ee.Information,`Using HubProtocol '${this._protocol.name}'.`),this._cleanupTimeout(),this._resetTimeoutPeriod(),this._resetKeepAliveInterval(),await e,this._stopDuringStartError)throw this._stopDuringStartError}catch(e){throw this._logger.log(Ee.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){return this._connectionState===ke.Disconnected?(this._logger.log(Ee.Debug,`Call to HubConnection.stop(${e}) ignored because it is already in the disconnected state.`),Promise.resolve()):this._connectionState===ke.Disconnecting?(this._logger.log(Ee.Debug,`Call to HttpConnection.stop(${e}) ignored because the connection is already in the disconnecting state.`),this._stopPromise):(this._connectionState=ke.Disconnecting,this._logger.log(Ee.Debug,"Stopping HubConnection."),this._reconnectDelayHandle?(this._logger.log(Ee.Debug,"Connection stopped during reconnect delay. Done reconnecting."),clearTimeout(this._reconnectDelayHandle),this._reconnectDelayHandle=void 0,this._completeClose(),Promise.resolve()):(this._cleanupTimeout(),this._cleanupPingTimer(),this._stopDuringStartError=e||new Error("The connection was stopped before the hub handshake could complete."),this.connection.stop(e)))}stream(e,...t){const[n,r]=this._replaceStreamingParams(t),o=this._createStreamInvocation(e,t,r);let i;const s=new Ze;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===Ie.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===Ie.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 Ie.Invocation:this._invokeClientMethod(e);break;case Ie.StreamItem:case Ie.Completion:{const t=this._callbacks[e.invocationId];t&&(e.type===Ie.Completion&&delete this._callbacks[e.invocationId],t(e));break}case Ie.Ping:break;case Ie.Close:{this._logger.log(Ee.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(Ee.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(Ee.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(Ee.Error,e);const n=new Error(e);throw this._handshakeRejecter(n),n}return this._logger.log(Ee.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===ke.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."))}_invokeClientMethod(e){const t=this._methods[e.target.toLowerCase()];if(t){try{t.forEach((t=>t.apply(this,e.arguments)))}catch(t){this._logger.log(Ee.Error,`A callback for the method ${e.target.toLowerCase()} threw error '${t}'.`)}if(e.invocationId){const e="Server requested a response, which is not supported in this version of the client.";this._logger.log(Ee.Error,e),this._stopPromise=this._stopInternal(new Error(e))}}else this._logger.log(Ee.Warning,`No client method with the name '${e.target}' found.`)}_connectionClosed(e){this._logger.log(Ee.Debug,`HubConnection.connectionClosed(${e}) called while in state ${this._connectionState}.`),this._stopDuringStartError=this._stopDuringStartError||e||new Error("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===ke.Disconnecting?this._completeClose(e):this._connectionState===ke.Connected&&this._reconnectPolicy?this._reconnect(e):this._connectionState===ke.Connected&&this._completeClose(e)}_completeClose(e){if(this._connectionStarted){this._connectionState=ke.Disconnected,this._connectionStarted=!1;try{this._closedCallbacks.forEach((t=>t.apply(this,[e])))}catch(t){this._logger.log(Ee.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(Ee.Debug,"Connection not reconnecting because the IRetryPolicy returned null on the first reconnect attempt."),void this._completeClose(e);if(this._connectionState=ke.Reconnecting,e?this._logger.log(Ee.Information,`Connection reconnecting because of error '${e}'.`):this._logger.log(Ee.Information,"Connection reconnecting."),0!==this._reconnectingCallbacks.length){try{this._reconnectingCallbacks.forEach((t=>t.apply(this,[e])))}catch(t){this._logger.log(Ee.Error,`An onreconnecting callback called with error '${e}' threw error '${t}'.`)}if(this._connectionState!==ke.Reconnecting)return void this._logger.log(Ee.Debug,"Connection left the reconnecting state in onreconnecting callback. Done reconnecting.")}for(;null!==o;){if(this._logger.log(Ee.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!==ke.Reconnecting)return void this._logger.log(Ee.Debug,"Connection left the reconnecting state during reconnect delay. Done reconnecting.");try{if(await this._startInternal(),this._connectionState=ke.Connected,this._logger.log(Ee.Information,"HubConnection reconnected successfully."),0!==this._reconnectedCallbacks.length)try{this._reconnectedCallbacks.forEach((e=>e.apply(this,[this.connection.connectionId])))}catch(e){this._logger.log(Ee.Error,`An onreconnected callback called with connectionId '${this.connection.connectionId}; threw error '${e}'.`)}return}catch(e){if(this._logger.log(Ee.Information,`Reconnect attempt failed because of error '${e}'.`),this._connectionState!==ke.Reconnecting)return this._logger.log(Ee.Debug,`Connection moved to the '${this._connectionState}' from the reconnecting state during reconnect attempt. Done reconnecting.`),void(this._connectionState===ke.Disconnecting&&this._completeClose());r=e instanceof Error?e:new Error(e.toString()),o=this._getNextRetryDelay(n++,Date.now()-t,r)}}this._logger.log(Ee.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(Ee.Error,`IRetryPolicy.nextRetryDelayInMilliseconds(${e}, ${t}) threw error '${n}'.`),null}}_cancelCallbacksWithError(e){const t=this._callbacks;this._callbacks={},Object.keys(t).forEach((n=>{(0,t[n])(null,e)}))}_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:Ie.Invocation}:{arguments:t,target:e,type:Ie.Invocation};{const n=this._invocationId;return this._invocationId++,0!==r.length?{arguments:t,invocationId:n.toString(),streamIds:r,target:e,type:Ie.Invocation}:{arguments:t,invocationId:n.toString(),target:e,type:Ie.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 ut=ot?new TextDecoder:null,dt=ot?"undefined"!=typeof process&&"force"!==process.env.TEXT_DECODER?200:0:it,pt=function(e,t){this.type=e,this.data=t};function ft(e,t,n){var r=Math.floor(n/4294967296),o=n;e.setUint32(t,r),e.setUint32(t+4,o)}function gt(e,t){return 4294967296*e.getInt32(t)+e.getUint32(t+4)}var mt={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),ft(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:gt(t,4),nsec:t.getUint32(0)};default:throw new Error("Unrecognized data size for timestamp: "+e.length)}}(e);return new Date(1e3*t.sec+t.nsec/1e6)}},yt=function(){function e(){this.builtInEncoders=[],this.builtInDecoders=[],this.encoders=[],this.decoders=[],this.register(mt)}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 "+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: "+e+" bytes in UTF-8");this.writeU8(219),this.writeU32(e)}},e.prototype.encodeString=function(e){if(e.length>ct){var t=st(e);this.ensureBufferSizeToWrite(5+t),this.writeStringHeader(t),lt(e,this.bytes,this.pos),this.pos+=t}else t=st(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: "+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: "+t);this.writeU8(198),this.writeU32(t)}var n=wt(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: "+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=ht(e,t,n),i=Uint8Array.prototype.slice.call(e,t,t+n);return this.store(i,o),o},e}(),St=(_t=function(e,t){return(_t=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])})(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}_t(e,t),e.prototype=null===t?Object.create(t):(n.prototype=t.prototype,new n)}),Ct=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]1||a(e,t)}))})}function a(e,t){try{(n=o[e](t)).value instanceof kt?Promise.resolve(n.value.v).then(c,l):h(i[0][2],n)}catch(e){h(i[0][3],e)}var n}function c(e){a("next",e)}function l(e){a("throw",e)}function h(e,t){e(t),i.shift(),i.length&&a(i[0][0],i[0][1])}},xt=new DataView(new ArrayBuffer(0)),Dt=new Uint8Array(xt.buffer),Rt=function(){try{xt.getInt8(0)}catch(e){return e.constructor}throw new Error("never reached")}(),Pt=new Rt("Insufficient data"),Ut=4294967295,At=new Et,Nt=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 St(t,e),t}(Error),Bt=function(){function e(e,t,n,r,o,i,s,a){void 0===e&&(e=yt.defaultCodec),void 0===t&&(t=void 0),void 0===n&&(n=Ut),void 0===r&&(r=Ut),void 0===o&&(o=Ut),void 0===i&&(i=Ut),void 0===s&&(s=Ut),void 0===a&&(a=At),this.extensionCodec=e,this.context=t,this.maxStrLength=n,this.maxBinLength=r,this.maxArrayLength=o,this.maxMapLength=i,this.maxExtLength=s,this.keyDecoder=a,this.totalPos=0,this.pos=0,this.view=xt,this.bytes=Dt,this.headByte=-1,this.stack=[]}return e.prototype.reinitializeState=function(){this.totalPos=0,this.headByte=-1,this.stack.length=0},e.prototype.setBuffer=function(e){this.bytes=wt(e),this.view=function(e){if(e instanceof ArrayBuffer)return new DataView(e);var t=wt(e);return new DataView(t.buffer,t.byteOffset,t.byteLength)}(this.bytes),this.pos=0},e.prototype.appendBuffer=function(e){if(-1!==this.headByte||this.hasRemaining()){var t=this.bytes.subarray(this.pos),n=wt(e),r=new Uint8Array(t.length+n.length);r.set(t),r.set(n,t.length),this.setBuffer(r)}else this.setBuffer(e)},e.prototype.hasRemaining=function(e){return void 0===e&&(e=1),this.view.byteLength-this.pos>=e},e.prototype.createExtraByteError=function(e){var t=this.view,n=this.pos;return new RangeError("Extra "+(t.byteLength-n)+" of "+t.byteLength+" byte(s) found at buffer["+e+"]")},e.prototype.decode=function(e){this.reinitializeState(),this.setBuffer(e);var t=this.doDecodeSync();if(this.hasRemaining())throw this.createExtraByteError(this.pos);return t},e.prototype.decodeMulti=function(e){return Ct(this,(function(t){switch(t.label){case 0:this.reinitializeState(),this.setBuffer(e),t.label=1;case 1:return this.hasRemaining()?[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,u,d;return Ct(this,(function(p){switch(p.label){case 0:i=!1,p.label=1;case 1:p.trys.push([1,6,7,12]),t=It(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 Rt))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())throw this.createExtraByteError(this.totalPos);return[2,s]}throw h=(l=this).headByte,u=l.pos,d=l.totalPos,new RangeError("Insufficient data in parsing "+bt(h)+" at "+d+" ("+u+" 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 Tt(this,arguments,(function(){var n,r,o,i,s,a,c,l,h;return Ct(this,(function(u){switch(u.label){case 0:n=t,r=-1,u.label=1;case 1:u.trys.push([1,13,14,19]),o=It(e),u.label=2;case 2:return[4,kt(o.next())];case 3:if((i=u.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()),u.label=4;case 4:u.trys.push([4,9,,10]),u.label=5;case 5:return[4,kt(this.doDecodeSync())];case 6:return[4,u.sent()];case 7:return u.sent(),0==--r?[3,8]:[3,5];case 8:return[3,10];case 9:if(!((a=u.sent())instanceof Rt))throw a;return[3,10];case 10:this.totalPos+=this.pos,u.label=11;case 11:return[3,2];case 12:return[3,19];case 13:return c=u.sent(),l={error:c},[3,19];case 14:return u.trys.push([14,,17,18]),i&&!i.done&&(h=o.return)?[4,kt(h.call(o))]:[3,16];case 15:u.sent(),u.label=16;case 16:return[3,18];case 17:if(l)throw l.error;return[7];case 18:return[7];case 19:return[2]}}))}))},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 Nt("Unrecognized type byte: "+bt(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 Nt("The type of key must be string or number but "+typeof t);if("__proto__"===t)throw new Nt("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 Nt("Unrecognized array type byte: "+bt(e))}},e.prototype.pushMapState=function(e){if(e>this.maxMapLength)throw new Nt("Max length exceeded: map length ("+e+") > maxMapLengthLength ("+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 Nt("Max length exceeded: array length ("+e+") > maxArrayLength ("+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 Nt("Max length exceeded: UTF-8 byte length ("+e+") > maxStrLength ("+this.maxStrLength+")");if(this.bytes.byteLengthdt?function(e,t,n){var r=e.subarray(t,t+n);return ut.decode(r)}(this.bytes,o,e):ht(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 Nt("Max length exceeded: bin length ("+e+") > maxBinLength ("+this.maxBinLength+")");if(!this.hasRemaining(e+t))throw Pt;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 Nt("Max length exceeded: ext length ("+e+") > maxExtLength ("+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=gt(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 $t{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 Lt=new Uint8Array([145,Ie.Ping]);class Mt{constructor(e){this.name="messagepack",this.version=1,this.transferFormat=Ce.Binary,this._errorResult=1,this._voidResult=2,this._nonVoidResult=3,e=e||{},this._encoder=new vt(e.extensionCodec,e.context,e.maxDepth,e.initialBufferSize,e.sortKeys,e.forceFloat32,e.ignoreUndefined,e.forceIntegerToFloat),this._decoder=new Bt(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=Ae.instance);const r=$t.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 Ie.Invocation:return this._writeInvocation(e);case Ie.StreamInvocation:return this._writeStreamInvocation(e);case Ie.StreamItem:return this._writeStreamItem(e);case Ie.Completion:return this._writeCompletion(e);case Ie.Ping:return $t.write(Lt);case Ie.CancelInvocation:return this._writeCancelInvocation(e);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 Ie.Invocation:return this._createInvocationMessage(this._readHeaders(n),n);case Ie.StreamItem:return this._createStreamItemMessage(this._readHeaders(n),n);case Ie.Completion:return this._createCompletionMessage(this._readHeaders(n),n);case Ie.Ping:return this._createPingMessage(n);case Ie.Close:return this._createCloseMessage(n);default:return t.log(Ee.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:Ie.Close}}_createPingMessage(e){if(e.length<1)throw new Error("Invalid payload for Ping message.");return{type:Ie.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:Ie.Invocation}:{arguments:t[4],headers:e,streamIds:[],target:t[3],type:Ie.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:Ie.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:Ie.Completion}}_writeInvocation(e){let t;return t=e.streamIds?this._encoder.encode([Ie.Invocation,e.headers||{},e.invocationId||null,e.target,e.arguments,e.streamIds]):this._encoder.encode([Ie.Invocation,e.headers||{},e.invocationId||null,e.target,e.arguments]),$t.write(t.slice())}_writeStreamInvocation(e){let t;return t=e.streamIds?this._encoder.encode([Ie.StreamInvocation,e.headers||{},e.invocationId,e.target,e.arguments,e.streamIds]):this._encoder.encode([Ie.StreamInvocation,e.headers||{},e.invocationId,e.target,e.arguments]),$t.write(t.slice())}_writeStreamItem(e){const t=this._encoder.encode([Ie.StreamItem,e.headers||{},e.invocationId,e.item]);return $t.write(t.slice())}_writeCompletion(e){const t=e.error?this._errorResult:e.result?this._nonVoidResult:this._voidResult;let n;switch(t){case this._errorResult:n=this._encoder.encode([Ie.Completion,e.headers||{},e.invocationId,t,e.error]);break;case this._voidResult:n=this._encoder.encode([Ie.Completion,e.headers||{},e.invocationId,t]);break;case this._nonVoidResult:n=this._encoder.encode([Ie.Completion,e.headers||{},e.invocationId,t,e.result])}return $t.write(n.slice())}_writeCancelInvocation(e){const t=this._encoder.encode([Ie.CancelInvocation,e.headers||{},e.invocationId]);return $t.write(t.slice())}_readHeaders(e){const t=e[1];if("object"!=typeof t)throw new Error("Invalid headers.");return t}}let Ot=!1;const Ht="function"==typeof TextDecoder?new TextDecoder("utf-8"):null,Ft=Ht?Ht.decode.bind(Ht):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("")},jt=Math.pow(2,32),Wt=Math.pow(2,21)-1;function zt(e,t){return e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24}function qt(e,t){return e[t]+(e[t+1]<<8)+(e[t+2]<<16)+(e[t+3]<<24>>>0)}function Jt(e,t){const n=qt(e,t+4);if(n>Wt)throw new Error(`Cannot read uint64 with high order part ${n}, because the result would exceed Number.MAX_SAFE_INTEGER.`);return n*jt+qt(e,t)}class Kt{constructor(e){this.batchData=e;const t=new Gt(e);this.arrayRangeReader=new Qt(e),this.arrayBuilderSegmentReader=new Zt(e),this.diffReader=new Vt(e),this.editReader=new Xt(e,t),this.frameReader=new Yt(e,t)}updatedComponents(){return zt(this.batchData,this.batchData.length-20)}referenceFrames(){return zt(this.batchData,this.batchData.length-16)}disposedComponentIds(){return zt(this.batchData,this.batchData.length-12)}disposedEventHandlerIds(){return zt(this.batchData,this.batchData.length-8)}updatedComponentsEntry(e,t){const n=e+4*t;return zt(this.batchData,n)}referenceFramesEntry(e,t){return e+20*t}disposedComponentIdsEntry(e,t){const n=e+4*t;return zt(this.batchData,n)}disposedEventHandlerIdsEntry(e,t){const n=e+8*t;return Jt(this.batchData,n)}}class Vt{constructor(e){this.batchDataUint8=e}componentId(e){return zt(this.batchDataUint8,e)}edits(e){return e+4}editsEntry(e,t){return e+16*t}}class Xt{constructor(e,t){this.batchDataUint8=e,this.stringReader=t}editType(e){return zt(this.batchDataUint8,e)}siblingIndex(e){return zt(this.batchDataUint8,e+4)}newTreeIndex(e){return zt(this.batchDataUint8,e+8)}moveToSiblingIndex(e){return zt(this.batchDataUint8,e+8)}removedAttributeName(e){const t=zt(this.batchDataUint8,e+12);return this.stringReader.readString(t)}}class Yt{constructor(e,t){this.batchDataUint8=e,this.stringReader=t}frameType(e){return zt(this.batchDataUint8,e)}subtreeLength(e){return zt(this.batchDataUint8,e+4)}elementReferenceCaptureId(e){const t=zt(this.batchDataUint8,e+4);return this.stringReader.readString(t)}componentId(e){return zt(this.batchDataUint8,e+8)}elementName(e){const t=zt(this.batchDataUint8,e+8);return this.stringReader.readString(t)}textContent(e){const t=zt(this.batchDataUint8,e+4);return this.stringReader.readString(t)}markupContent(e){const t=zt(this.batchDataUint8,e+4);return this.stringReader.readString(t)}attributeName(e){const t=zt(this.batchDataUint8,e+4);return this.stringReader.readString(t)}attributeValue(e){const t=zt(this.batchDataUint8,e+8);return this.stringReader.readString(t)}attributeEventHandlerId(e){return Jt(this.batchDataUint8,e+12)}}class Gt{constructor(e){this.batchDataUint8=e,this.stringTableStartIndex=zt(e,e.length-4)}readString(e){if(-1===e)return null;{const n=zt(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(en.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(en.Debug,`Waiting for batch ${this.nextBatchId}. Batch ${e} not processed.`);try{this.nextBatchId++,this.logger.log(en.Debug,`Applying batch ${e}.`),function(e,t){const n=Q[e];if(!n)throw new Error(`There is no browser renderer with ID ${e}.`);const r=t.arrayRangeReader,o=t.updatedComponents(),i=r.values(o),s=r.count(o),a=t.referenceFrames(),c=r.values(a),l=t.diffReader;for(let e=0;e=this.minLevel){const n=`[${(new Date).toISOString()}] ${en[e]}: ${t}`;switch(e){case en.Critical:case en.Error:console.error(n);break;case en.Warning:console.warn(n);break;case en.Information:console.info(n);break;default:console.log(n)}}}}class on{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!==ke.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!==ke.Connected)return!1;const t=await e.invoke("StartCircuit",re.getBaseURI(),re.getLocationHref(),JSON.stringify(this.components.map((e=>e.toRecord()))),this.applicationState||"");return!!t&&(this.initialize(t),!0)}resolveElement(e){const t=Number.parseInt(e);if(Number.isNaN(t))throw new Error(`Invalid sequence number '${e}'.`);return function(e,t){if(!e.parentNode)throw new Error(`Comment not connected to the DOM ${e.textContent}`);const n=e.parentNode,r=k(n,!0),o=A(r);return Array.from(n.childNodes).forEach((e=>o.push(e))),e[C]=r,t&&(e[I]=t,k(t)),k(e)}(this.components[t].start,this.components[t].end)}}const sn={configureSignalR:e=>{},logLevel:en.Warning,reconnectionOptions:{maxRetries:8,retryIntervalMilliseconds:2e4,dialogId:"components-reconnect-modal"}};class an{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.modal.innerHTML='

Alternatively, reload

',this.message=this.modal.querySelector("h5"),this.button=this.modal.querySelector("button"),this.reloadParagraph=this.modal.querySelector("p"),this.loader=this.getLoader(),this.message.after(this.loader),this.button.addEventListener("click",(async()=>{this.show();try{await(null==fe?void 0:fe.reconnect)()||this.rejected()}catch(e){this.logger.log(en.Error,e),this.failed()}})),this.reloadParagraph.querySelector("a").addEventListener("click",(()=>location.reload()))}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",this.message.innerHTML="Reconnection failed. Try reloading the page if you're unable to reconnect.",this.message.querySelector("a").addEventListener("click",(()=>location.reload()))}rejected(){this.button.style.display="none",this.reloadParagraph.style.display="none",this.loader.style.display="none",this.message.innerHTML="Could not reconnect to the server. Reload the page to restore functionality.",this.message.querySelector("a").addEventListener("click",(()=>location.reload()))}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 cn{constructor(e,t,n){this.dialog=e,this.maxRetries=t,this.document=n,this.document=n;const r=this.document.getElementById(cn.MaxRetriesId);r&&(r.innerText=this.maxRetries.toString())}show(){this.removeClasses(),this.dialog.classList.add(cn.ShowClassName)}update(e){const t=this.document.getElementById(cn.CurrentAttemptId);t&&(t.innerText=e.toString())}hide(){this.removeClasses(),this.dialog.classList.add(cn.HideClassName)}failed(){this.removeClasses(),this.dialog.classList.add(cn.FailedClassName)}rejected(){this.removeClasses(),this.dialog.classList.add(cn.RejectedClassName)}removeClasses(){this.dialog.classList.remove(cn.ShowClassName,cn.HideClassName,cn.FailedClassName,cn.RejectedClassName)}}cn.ShowClassName="components-reconnect-show",cn.HideClassName="components-reconnect-hide",cn.FailedClassName="components-reconnect-failed",cn.RejectedClassName="components-reconnect-rejected",cn.MaxRetriesId="components-reconnect-max-retries",cn.CurrentAttemptId="components-reconnect-current-attempt";class ln{constructor(e,t,n){this._currentReconnectionProcess=null,this._logger=e,this._reconnectionDisplay=t,this._reconnectCallback=n||(()=>fe.reconnect())}onConnectionDown(e,t){if(!this._reconnectionDisplay){const t=document.getElementById(e.dialogId);this._reconnectionDisplay=t?new cn(t,e.maxRetries,document):new an(e.dialogId,e.maxRetries,document,this._logger)}this._currentReconnectionProcess||(this._currentReconnectionProcess=new hn(e,this._logger,this._reconnectCallback,this._reconnectionDisplay))}onConnectionUp(){this._currentReconnectionProcess&&(this._currentReconnectionProcess.dispose(),this._currentReconnectionProcess=null)}}class hn{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;thn.MaximumFirstRetryInterval?hn.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(en.Error,e)}}this.reconnectDisplay.failed()}delay(e){return new Promise((t=>setTimeout(t,e)))}}hn.MaximumFirstRetryInterval=3e3;const un=/^\s*Blazor-Component-State:(?[a-zA-Z0-9\+\/=]+)$/;function dn(e){var t;if(e.nodeType===Node.COMMENT_NODE){const n=e.textContent||"",r=un.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 gn(e,t){const n=e.currentElement;if(n&&n.nodeType===Node.COMMENT_NODE&&n.textContent){const r=fn.exec(n.textContent),o=r&&r.groups&&r.groups.descriptor;if(!o)return;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;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.");if(c){const e=mn(c,n);if(!e)throw new Error(`Could not find an end component comment for '${t}'`);return{type:r,assembly:o,typeName:i,parameterDefinitions:s&&atob(s),parameterValues:a&&atob(a),start:t,prerenderId:c,end:e}}return{type:r,assembly:o,typeName:i,parameterDefinitions:s&&atob(s),parameterValues:a&&atob(a),start:t}}}(r,n,e);case"server":return function(e,t,n){const{type:r,descriptor:o,sequence:i,prerenderId:s}=e;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)}'`);if(s){const e=mn(s,n);if(!e)throw new Error(`Could not find an end component comment for '${t}'`);return{type:r,sequence:i,descriptor:o,start:t,prerenderId:s,end:e}}return{type:r,sequence:i,descriptor:o,start:t}}}(r,n,e)}}catch(e){throw new Error(`Found malformed component comment at ${n.textContent}`)}}}function mn(e,t){for(;t.next()&&t.currentElement;){const n=t.currentElement;if(n.nodeType!==Node.COMMENT_NODE)continue;if(!n.textContent)continue;const r=fn.exec(n.textContent),o=r&&r[1];if(o)return yn(o,e),n}}function yn(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 wn{constructor(e){this.childNodes=e,this.currentIndex=-1,this.length=e.length}next(){return this.currentIndex++,this.currentIndexe.sequence-t.sequence))}(e)}(document),o=dn(document),i=new on(r,o||""),s=await Tn(t,n,i);if(!await i.startCircuit(s))return void n.log(en.Error,"Failed to start the circuit.");let a=!1;const c=()=>{if(!a){const e=new FormData,t=i.circuitId;e.append("circuitId",t),a=navigator.sendBeacon("_blazor/disconnect",e)}};fe.disconnect=c,window.addEventListener("unload",c,{capture:!1,once:!0}),fe.reconnect=async e=>{if(Cn)return!1;const r=e||await Tn(t,n,i);return await i.reconnect(r)?(t.reconnectionHandler.onConnectionUp(),!0):(n.log(en.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)},n.log(en.Information,"Blazor server-side application started.")}async function Tn(t,n,r){const i=new Mt;i.name="blazorpack";const s=(new rt).withUrl("_blazor").withHubProtocol(i);t.configureSignalR(s);const a=s.build();o=(e,t)=>{a.send("DispatchBrowserEvent",JSON.stringify(e),JSON.stringify(t))},fe._internal.navigationManager.listenForNavigationEvents(((e,t)=>a.send("OnLocationChanged",e,t))),a.on("JS.AttachComponent",((e,t)=>function(e,t,n){let r=Q[0];r||(r=Q[0]=new V(0)),r.attachRootComponentToLogicalElement(n,t)}(0,r.resolveElement(t),e))),a.on("JS.BeginInvokeJS",e.jsCallDispatcher.beginInvokeJSFromDotNet),a.on("JS.EndInvokeDotNet",e.jsCallDispatcher.endInvokeDotNetFromJS),a.on("JS.ReceiveByteArray",e.jsCallDispatcher.receiveByteArray);const c=tn.getOrCreate(n);a.on("JS.RenderBatch",((e,t)=>{n.log(en.Debug,`Received render batch with id ${e} and ${t.byteLength} bytes.`),c.processBatch(e,t,a)})),a.onclose((e=>!Cn&&t.reconnectionHandler.onConnectionDown(t.reconnectionOptions,e))),a.on("JS.Error",(e=>{Cn=!0,xn(a,e,n),async function(){let e=document.querySelector("#blazor-error-ui");e&&(e.style.display="block"),Ot||(Ot=!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()}})))}()})),fe._internal.forceCloseConnection=()=>a.stop(),fe._internal.sendJSDataStream=(e,t,n)=>function(e,t,n,r){setTimeout((async()=>{let o=5,i=(new Date).valueOf();try{let s=0;for(;s1)await e.send("ReceiveJSDataChunk",n,c,null);else{if(!await e.invoke("ReceiveJSDataChunk",n,c,null))break;const t=(new Date).valueOf(),r=t-i;i=t,o=Math.max(1,Math.round(500/Math.max(1,r)))}s+=a}}catch(t){await e.send("ReceiveJSDataChunk",n,null,t.toString())}}),0)}(a,e,t,n);try{await a.start()}catch(e){xn(a,e,n)}return e.attachDispatcher({beginInvokeDotNetFromJS:(e,t,n,r,o)=>{a.send("BeginInvokeDotNetFromJS",e?e.toString():null,t,n,r||0,o)},endInvokeJSFromDotNet:(e,t,n)=>{a.send("EndInvokeJSFromDotNet",e,t,n)},sendByteArray:(e,t)=>{a.send("ReceiveByteArray",e,t)}}),a}function xn(e,t,n){n.log(en.Error,t),e&&e.stop()}fe.start=kn,document&&document.currentScript&&"false"!==document.currentScript.getAttribute("autostart")&&kn()})(); \ 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 dde2003b4c93..7ba8522cc3e8 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;!function(e){window.DotNet=e;const t=[],n=new Map;class r{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 o="__jsObjectId",a={},i={0:new r(window)};i[0]._cachedFunctions.set("import",(e=>("string"==typeof e&&e.startsWith("./")&&(e=document.baseURI+e.substr(2)),import(e))));let s,c=1,l=1,u=null;function d(e){t.push(e)}function h(e){if(e&&"object"==typeof e){i[l]=new r(e);const t={[o]:l};return l++,t}throw new Error(`Cannot create a JSObjectReference from the value '${e}'.`)}function f(e){if(!(e.buffer instanceof ArrayBuffer))throw new Error(`Cannot create a JSDataReference from the value '${e}' as it is not a valid ArrayBuffer.`);if(void 0===e.byteLength)throw new Error(`Cannot create a JSDataReference from the value '${e}' as it doesn't have a byteLength.`);const t={__jsDataReferenceLength:e.byteLength};try{const n=h(e);t.__jsObjectId=n.__jsObjectId}catch{throw new Error(`Cannot create a JSStreamReference from the value '${e}'.`)}return t}function m(e){return e?JSON.parse(e,((e,n)=>t.reduce(((t,n)=>n(e,t)),n))):null}function p(e,t,n,r){const o=g();if(o.invokeDotNetFromJS){const a=A(r),i=o.invokeDotNetFromJS(e,t,n,a);return i?m(i):null}throw new Error("The current dispatcher does not support synchronous calls from JS to .NET. Use invokeMethodAsync instead.")}function v(e,t,n,r){if(e&&n)throw new Error(`For instance method calls, assemblyName should be null. Received '${e}'.`);const o=c++,i=new Promise(((e,t)=>{a[o]={resolve:e,reject:t}}));try{const a=A(r);g().beginInvokeDotNetFromJS(o,e,t,n,a)}catch(e){b(o,!1,e)}return i}function g(){if(null!==u)return u;throw new Error("No .NET call dispatcher has been set.")}function b(e,t,n){if(!a.hasOwnProperty(e))throw new Error(`There is no pending async call with ID ${e}.`);const r=a[e];delete a[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){let n=i[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 i[e]}e.attachDispatcher=function(e){u=e},e.attachReviver=d,e.invokeMethod=function(e,t,...n){return p(e,t,null,n)},e.invokeMethodAsync=function(e,t,...n){return v(e,t,null,n)},e.createJSObjectReference=h,e.createJSDataReference=f,e.disposeJSObjectReference=function(e){const t=e&&e.__jsObjectId;"number"==typeof t&&E(t)},function(e){e[e.Default=0]="Default",e[e.JSObjectReference=1]="JSObjectReference",e[e.JSDataReference=2]="JSDataReference"}(s=e.JSCallResultType||(e.JSCallResultType={})),e.jsCallDispatcher={findJSFunction:w,disposeJSObjectReferenceById:E,invokeJSFromDotNet:(e,t,n,r)=>{const o=D(w(e,r).apply(null,m(t)),n);return null==o?null:A(o)},beginInvokeJSFromDotNet:(e,t,n,r,o)=>{const a=new Promise((e=>{e(w(t,o).apply(null,m(n)))}));e&&a.then((t=>g().endInvokeJSFromDotNet(e,!0,A([e,!0,D(t,r)]))),(t=>g().endInvokeJSFromDotNet(e,!1,JSON.stringify([e,!1,y(t)]))))},endInvokeDotNetFromJS:(e,t,n)=>{const r=t?m(n):new Error(n);b(parseInt(e),t,r)},receiveByteArray:(e,t)=>{n.set(e,t)}};class I{constructor(e){this._id=e}invokeMethod(e,...t){return p(null,e,this._id,t)}invokeMethodAsync(e,...t){return v(null,e,this._id,t)}dispose(){v(null,"__Dispose",this._id,null).catch((e=>console.error(e)))}serializeAsArg(){return{__dotNetObject:this._id}}}const S="__byte[]";function D(e,t){switch(t){case s.Default:return e;case s.JSObjectReference:return h(e);case s.JSDataReference:return f(e);default:throw new Error(`Invalid JS call result type '${t}'.`)}}d((function(e,t){if(t&&"object"==typeof t){if(t.hasOwnProperty("__dotNetObject"))return new I(t.__dotNetObject);if(t.hasOwnProperty(o)){const e=t.__jsObjectId,n=i[e];if(n)return n.getWrappedObject();throw new Error(`JS object instance with Id '${e}' does not exist. It may have been disposed.`)}if(t.hasOwnProperty(S)){const e=t["__byte[]"],r=n.get(e);if(void 0===r)throw new Error(`Byte array index '${e}' does not exist.`);return r}}return t}));let C=0;function A(e){return C=0,JSON.stringify(e,T)}function T(e,t){if(t instanceof I)return t.serializeAsArg();if(t instanceof Uint8Array){u.sendByteArray(C,t);const e={[S]:C};return C++,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"}(n||(n={}));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}}let o;function a(e,t){if(!o)throw new Error("eventDispatcher not initialized. Call 'setEventDispatcher' to configure it.");o(e,t)}const i=new Map,s=new Map,c={createEventArgs:()=>({})},l=[];function u(e){return i.get(e)}function d(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 f(e){const t=[];for(let n=0;n{return{...m(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"],c),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};var t}}),h(["contextmenu","click","mouseover","mouseout","mousemove","mousedown","mouseup","dblclick"],{createEventArgs:e=>m(e)}),h(["error"],{createEventArgs:e=>{return{message:(t=e).message,filename:t.filename,lineno:t.lineno,colno:t.colno};var t}}),h(["loadstart","timeout","abort","load","loadend","progress"],{createEventArgs:e=>{return{lengthComputable:(t=e).lengthComputable,loaded:t.loaded,total:t.total};var t}}),h(["touchcancel","touchend","touchmove","touchenter","touchleave","touchstart"],{createEventArgs:e=>{return{detail:(t=e).detail,touches:f(t.touches),targetTouches:f(t.targetTouches),changedTouches:f(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{...m(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{...m(t=e),deltaX:t.deltaX,deltaY:t.deltaY,deltaZ:t.deltaZ,deltaMode:t.deltaMode};var t}}),h(["toggle"],c);const p=["date","datetime-local","month","time","week"],v=I(["abort","blur","change","error","focus","load","loadend","loadstart","mouseenter","mouseleave","progress","reset","scroll","submit","unload","toggle","DOMNodeInsertedIntoDocument","DOMNodeRemovedFromDocument"]),g={submit:!0},b=I(["click","dblclick","mousedown","mousemove","mouseup"]);class y{constructor(e){this.browserRendererId=e,this.afterClickCallbacks=[];const t=++y.nextEventDelegatorId;this.eventsCollectionKey=`_blazorEvents_${t}`,this.eventInfoStore=new w(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){let n=t.target,o=null,i=!1;const s=v.hasOwnProperty(e);let c=!1;for(;n;){const h=this.getEventHandlerInfosForElement(n,!1);if(h){const s=h.getHandler(e);if(s&&(l=n,d=t.type,!((l instanceof HTMLButtonElement||l instanceof HTMLInputElement||l instanceof HTMLTextAreaElement||l instanceof HTMLSelectElement)&&b.hasOwnProperty(d)&&l.disabled))){if(!i){const n=u(e);o=(null==n?void 0:n.createEventArgs)?n.createEventArgs(t):{},i=!0}g.hasOwnProperty(t.type)&&t.preventDefault(),a({browserRendererId:this.browserRendererId,eventHandlerId:s.eventHandlerId,eventName:e,eventFieldInfo:r.fromEvent(s.renderingComponentId,t)},o)}h.stopPropagation(e)&&(c=!0),h.preventDefault(e)&&t.preventDefault()}n=s||c?null:n.parentElement}var l,d}getEventHandlerInfosForElement(e,t){return e.hasOwnProperty(this.eventsCollectionKey)?e[this.eventsCollectionKey]:t?e[this.eventsCollectionKey]=new E:null}}y.nextEventDelegatorId=0;class w{constructor(e){this.globalListener=e,this.infosByEventHandlerId={},this.countByEventName={},l.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=d(e),this.countByEventName.hasOwnProperty(e))this.countByEventName[e]++;else{this.countByEventName[e]=1;const t=v.hasOwnProperty(e);document.addEventListener(e,this.globalListener,t)}}update(e,t){if(this.infosByEventHandlerId.hasOwnProperty(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=d(t.eventName);0==--this.countByEventName[n]&&(delete this.countByEventName[n],document.removeEventListener(n,this.globalListener))}return t}handleEventNameAliasAdded(e,t){if(this.countByEventName.hasOwnProperty(e)){const n=this.countByEventName[e];delete this.countByEventName[e],document.removeEventListener(e,this.globalListener),this.addGlobalListener(t),this.countByEventName[t]+=n-1}}}class E{constructor(){this.handlers={},this.preventDefaultFlags=null,this.stopPropagationFlags=null}getHandler(e){return this.handlers.hasOwnProperty(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 I(e){const t={};return e.forEach((e=>{t[e]=!0})),t}const S=M("_blazorLogicalChildren"),D=M("_blazorLogicalParent"),C=M("_blazorLogicalEnd");function A(e,t){if(e.childNodes.length>0&&!t)throw new Error("New logical elements must start empty, or allowExistingContents must be true");return S in e||(e[S]=[]),e}function T(e,t){const n=document.createComment("!");return N(n,e,t),n}function N(e,t,n){const r=e;if(e instanceof Comment&&O(r)&&O(r).length>0)throw new Error("Not implemented: inserting non-empty logical container");if(k(r))throw new Error("Not implemented: moving existing logical children");const o=O(t);if(n0;)R(n,0)}const r=n;r.parentNode.removeChild(r)}function k(e){return e[D]||null}function F(e,t){return O(e)[t]}function _(e){var t=B(e);return"http://www.w3.org/2000/svg"===t.namespaceURI&&"foreignObject"!==t.tagName}function O(e){return e[S]}function x(e,t){const n=O(e);t.forEach((e=>{e.moveRangeStart=n[e.fromSiblingIndex],e.moveRangeEnd=H(e.moveRangeStart)})),t.forEach((t=>{const r=t.moveToBeforeMarker=document.createComment("marker"),o=n[t.toSiblingIndex+1];o?o.parentNode.insertBefore(r,o):P(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 B(e){if(e instanceof Element)return e;if(e instanceof Comment)return e.parentNode;throw new Error("Not a valid logical element")}function L(e){const t=O(k(e));return t[Array.prototype.indexOf.call(t,e)+1]||null}function P(e,t){if(t instanceof Element)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=L(t);n?n.parentNode.insertBefore(e,n):P(e,k(t))}}}function H(e){if(e instanceof Element)return e;const t=L(e);if(t)return t.previousSibling;{const t=k(e);return t instanceof Element?t.lastChild:H(t)}}function M(e){return"function"==typeof Symbol?Symbol():e}function U(e){return`_bl_${e}`}e.attachReviver(((e,t)=>t&&"object"==typeof t&&t.hasOwnProperty("__internalId")&&"string"==typeof t.__internalId?function(e){const t=`[${U(e)}]`;return document.querySelector(t)}(t.__internalId):t));const j="_blazorSelectValue",J=document.createElement("template"),$=document.createElementNS("http://www.w3.org/2000/svg","g"),K={},z="__internal_",V="preventDefault_",X="stopPropagation_";class Y{constructor(e){this.childComponentLocations={},this.eventDelegator=new y(e),this.eventDelegator.notifyAfterClick((e=>{if(!ee)return;if(0!==e.button||function(e){return e.ctrlKey||e.shiftKey||e.altKey||e.metaKey}(e))return;if(e.defaultPrevented)return;const t=function(e){const t=!window._blazorDisableComposedPath&&e.composedPath&&e.composedPath();if(t){for(let e=0;eie(!1))))},enableNavigationInterception:function(){ee=!0},navigateTo:oe,getBaseURI:()=>document.baseURI,getLocationHref:()=>location.href};function oe(e,t,n=!1){const r=ce(e);if(!t&&ue(r))ae(r,!1,n);else if(t&&location.href===e){const t=e+"?";history.replaceState(null,"",t),location.replace(e)}else n?history.replaceState(null,"",r):location.href=e}function ae(e,t,n=!1){Q=!0,n?history.replaceState(null,"",e):history.pushState(null,"",e),ie(t)}async function ie(e){ne&&await ne(location.href,e)}let se;function ce(e){return se=se||document.createElement("a"),se.href=e,se.href}function le(e,t){return e?e.tagName===t?e:le(e.parentElement,t):null}function ue(e){const t=(n=document.baseURI).substr(0,n.lastIndexOf("/")+1);var n;return e.startsWith(t)}const de={init:function(e,t,n,r=50){const o=fe(t);(o||document.documentElement).style.overflowAnchor="none";const a=new IntersectionObserver((function(r){r.forEach((r=>{var o;if(!r.isIntersecting)return;const a=t.getBoundingClientRect(),i=n.getBoundingClientRect().top-a.bottom,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`});a.observe(t),a.observe(n);const i=c(t),s=c(n);function c(e){const t=new MutationObserver((()=>{a.unobserve(e),a.observe(e)}));return t.observe(e,{attributes:!0}),t}he[e._id]={intersectionObserver:a,mutationObserverBefore:i,mutationObserverAfter:s}},dispose:function(e){const t=he[e._id];t&&(t.intersectionObserver.disconnect(),t.mutationObserverBefore.disconnect(),t.mutationObserverAfter.disconnect(),e.dispose(),delete he[e._id])}},he={};function fe(e){return e?"visible"!==getComputedStyle(e).overflowY?e:fe(e.parentElement):null}const me={navigateTo:oe,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]),l.forEach((n=>n(e,t.browserEventName)))}i.set(e,t)},_internal:{navigationManager:re,domWrapper:{focus:function(e,t){if(!(e instanceof HTMLElement))throw new Error("Unable to focus an invalid element.");e.focus({preventScroll:t})},focusBySelector:function(e){const t=document.querySelector(e);t&&(t.hasAttribute("tabindex")||(t.tabIndex=-1),t.focus())}},Virtualize:de}};window.Blazor=me;let pe=!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("")},be=Math.pow(2,32),ye=Math.pow(2,21)-1;function we(e,t){return e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24}function Ee(e,t){return e[t]+(e[t+1]<<8)+(e[t+2]<<16)+(e[t+3]<<24>>>0)}function Ie(e,t){const n=Ee(e,t+4);if(n>ye)throw new Error(`Cannot read uint64 with high order part ${n}, because the result would exceed Number.MAX_SAFE_INTEGER.`);return n*be+Ee(e,t)}class Se{constructor(e){this.batchData=e;const t=new Te(e);this.arrayRangeReader=new Ne(e),this.arrayBuilderSegmentReader=new Re(e),this.diffReader=new De(e),this.editReader=new Ce(e,t),this.frameReader=new Ae(e,t)}updatedComponents(){return we(this.batchData,this.batchData.length-20)}referenceFrames(){return we(this.batchData,this.batchData.length-16)}disposedComponentIds(){return we(this.batchData,this.batchData.length-12)}disposedEventHandlerIds(){return we(this.batchData,this.batchData.length-8)}updatedComponentsEntry(e,t){const n=e+4*t;return we(this.batchData,n)}referenceFramesEntry(e,t){return e+20*t}disposedComponentIdsEntry(e,t){const n=e+4*t;return we(this.batchData,n)}disposedEventHandlerIdsEntry(e,t){const n=e+8*t;return Ie(this.batchData,n)}}class De{constructor(e){this.batchDataUint8=e}componentId(e){return we(this.batchDataUint8,e)}edits(e){return e+4}editsEntry(e,t){return e+16*t}}class Ce{constructor(e,t){this.batchDataUint8=e,this.stringReader=t}editType(e){return we(this.batchDataUint8,e)}siblingIndex(e){return we(this.batchDataUint8,e+4)}newTreeIndex(e){return we(this.batchDataUint8,e+8)}moveToSiblingIndex(e){return we(this.batchDataUint8,e+8)}removedAttributeName(e){const t=we(this.batchDataUint8,e+12);return this.stringReader.readString(t)}}class Ae{constructor(e,t){this.batchDataUint8=e,this.stringReader=t}frameType(e){return we(this.batchDataUint8,e)}subtreeLength(e){return we(this.batchDataUint8,e+4)}elementReferenceCaptureId(e){const t=we(this.batchDataUint8,e+4);return this.stringReader.readString(t)}componentId(e){return we(this.batchDataUint8,e+8)}elementName(e){const t=we(this.batchDataUint8,e+8);return this.stringReader.readString(t)}textContent(e){const t=we(this.batchDataUint8,e+4);return this.stringReader.readString(t)}markupContent(e){const t=we(this.batchDataUint8,e+4);return this.stringReader.readString(t)}attributeName(e){const t=we(this.batchDataUint8,e+4);return this.stringReader.readString(t)}attributeValue(e){const t=we(this.batchDataUint8,e+8);return this.stringReader.readString(t)}attributeEventHandlerId(e){return Ie(this.batchDataUint8,e+12)}}class Te{constructor(e){this.batchDataUint8=e,this.stringTableStartIndex=we(e,e.length-4)}readString(e){if(-1===e)return null;{const n=we(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)<{!function(e,t,n){const r=document.querySelector(e);if(!r)throw new Error(`Could not find any element matching selector '${e}'.`);!function(e,t,n){let r=Z[0];r||(r=Z[0]=new Y(0)),r.attachRootComponentToLogicalElement(n,t)}(0,A(r,!0),t)}(t,e)},RenderBatch:(e,t)=>{try{const n=Me(t);(function(e,t){const n=Z[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{Fe=!0,console.error(`${e}\n${t}`),async function(){let e=document.querySelector("#blazor-error-ui");e&&(e.style.display="block"),pe||(pe=!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:e.jsCallDispatcher.beginInvokeJSFromDotNet,EndInvokeDotNet:e.jsCallDispatcher.endInvokeDotNetFromJS,SendByteArrayToJS:He,Navigate:re.navigateTo};window.external.receiveMessage((e=>{const n=function(e){if(Fe||!e||!e.startsWith(ke))return null;const t=e.substring(ke.length),[n,...r]=JSON.parse(t);return{messageType:n,args:r}}(e);if(n){if(!t.hasOwnProperty(n.messageType))throw new Error(`Unsupported IPC message type '${n.messageType}'`);t[n.messageType].apply(null,n.args)}}))}(),e.attachDispatcher({beginInvokeDotNetFromJS:Oe,endInvokeJSFromDotNet:xe,sendByteArray:Be}),me._internal.InputFile=Ue,re.enableNavigationInterception(),re.listenForNavigationEvents(Le),Pe("AttachPage",re.getBaseURI(),re.getLocationHref())}o=function(e,t){Pe("DispatchBrowserEvent",e,t)},me.start=Ke,document&&document.currentScript&&"false"!==document.currentScript.getAttribute("autostart")&&Ke()})(); \ No newline at end of file +(()=>{"use strict";var e,t,n;!function(e){window.DotNet=e;const t=[],n=new Map;class r{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 o="__jsObjectId",a={},i={0:new r(window)};i[0]._cachedFunctions.set("import",(e=>("string"==typeof e&&e.startsWith("./")&&(e=document.baseURI+e.substr(2)),import(e))));let s,c=1,l=1,u=null;function d(e){t.push(e)}function h(e){if(e&&"object"==typeof e){i[l]=new r(e);const t={[o]:l};return l++,t}throw new Error(`Cannot create a JSObjectReference from the value '${e}'.`)}function f(e){if(!(e.buffer instanceof ArrayBuffer))throw new Error(`Cannot create a JSStreamReference from the value '${e}' as it is not a valid ArrayBuffer.`);if(void 0===e.byteLength)throw new Error(`Cannot create a JSStreamReference from the value '${e}' as it doesn't have a byteLength.`);const t={__jsStreamReferenceLength:e.byteLength-5};try{const n=h(e);t.__jsObjectId=n.__jsObjectId}catch{throw new Error(`Cannot create a JSStreamReference from the value '${e}'.`)}return t}function m(e){return e?JSON.parse(e,((e,n)=>t.reduce(((t,n)=>n(e,t)),n))):null}function p(e,t,n,r){const o=g();if(o.invokeDotNetFromJS){const a=D(r),i=o.invokeDotNetFromJS(e,t,n,a);return i?m(i):null}throw new Error("The current dispatcher does not support synchronous calls from JS to .NET. Use invokeMethodAsync instead.")}function v(e,t,n,r){if(e&&n)throw new Error(`For instance method calls, assemblyName should be null. Received '${e}'.`);const o=c++,i=new Promise(((e,t)=>{a[o]={resolve:e,reject:t}}));try{const a=D(r);g().beginInvokeDotNetFromJS(o,e,t,n,a)}catch(e){b(o,!1,e)}return i}function g(){if(null!==u)return u;throw new Error("No .NET call dispatcher has been set.")}function b(e,t,n){if(!a.hasOwnProperty(e))throw new Error(`There is no pending async call with ID ${e}.`);const r=a[e];delete a[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){let n=i[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 i[e]}e.attachDispatcher=function(e){u=e},e.attachReviver=d,e.invokeMethod=function(e,t,...n){return p(e,t,null,n)},e.invokeMethodAsync=function(e,t,...n){return v(e,t,null,n)},e.createJSObjectReference=h,e.createJSStreamReference=f,e.disposeJSObjectReference=function(e){const t=e&&e.__jsObjectId;"number"==typeof t&&E(t)},function(e){e[e.Default=0]="Default",e[e.JSObjectReference=1]="JSObjectReference",e[e.JSStreamReference=2]="JSStreamReference"}(s=e.JSCallResultType||(e.JSCallResultType={})),e.jsCallDispatcher={findJSFunction:w,disposeJSObjectReferenceById:E,invokeJSFromDotNet:(e,t,n,r)=>{const o=C(w(e,r).apply(null,m(t)),n);return null==o?null:D(o)},beginInvokeJSFromDotNet:(e,t,n,r,o)=>{const a=new Promise((e=>{e(w(t,o).apply(null,m(n)))}));e&&a.then((t=>g().endInvokeJSFromDotNet(e,!0,D([e,!0,C(t,r)]))),(t=>g().endInvokeJSFromDotNet(e,!1,JSON.stringify([e,!1,y(t)]))))},endInvokeDotNetFromJS:(e,t,n)=>{const r=t?m(n):new Error(n);b(parseInt(e),t,r)},receiveByteArray:(e,t)=>{n.set(e,t)}};class I{constructor(e){this._id=e}invokeMethod(e,...t){return p(null,e,this._id,t)}invokeMethodAsync(e,...t){return v(null,e,this._id,t)}dispose(){v(null,"__Dispose",this._id,null).catch((e=>console.error(e)))}serializeAsArg(){return{__dotNetObject:this._id}}}const S="__byte[]";function C(e,t){switch(t){case s.Default:return e;case s.JSObjectReference:return h(e);case s.JSStreamReference:return f(e);default:throw new Error(`Invalid JS call result type '${t}'.`)}}d((function(e,t){if(t&&"object"==typeof t){if(t.hasOwnProperty("__dotNetObject"))return new I(t.__dotNetObject);if(t.hasOwnProperty(o)){const e=t.__jsObjectId,n=i[e];if(n)return n.getWrappedObject();throw new Error(`JS object instance with Id '${e}' does not exist. It may have been disposed.`)}if(t.hasOwnProperty(S)){const e=t["__byte[]"],r=n.get(e);if(void 0===r)throw new Error(`Byte array index '${e}' does not exist.`);return r}}return t}));let A=0;function D(e){return A=0,JSON.stringify(e,T)}function T(e,t){if(t instanceof I)return t.serializeAsArg();if(t instanceof Uint8Array){u.sendByteArray(A,t);const e={[S]: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"}(n||(n={}));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}}let o;function a(e,t){if(!o)throw new Error("eventDispatcher not initialized. Call 'setEventDispatcher' to configure it.");o(e,t)}const i=new Map,s=new Map,c={createEventArgs:()=>({})},l=[];function u(e){return i.get(e)}function d(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 f(e){const t=[];for(let n=0;n{return{...m(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"],c),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};var t}}),h(["contextmenu","click","mouseover","mouseout","mousemove","mousedown","mouseup","dblclick"],{createEventArgs:e=>m(e)}),h(["error"],{createEventArgs:e=>{return{message:(t=e).message,filename:t.filename,lineno:t.lineno,colno:t.colno};var t}}),h(["loadstart","timeout","abort","load","loadend","progress"],{createEventArgs:e=>{return{lengthComputable:(t=e).lengthComputable,loaded:t.loaded,total:t.total};var t}}),h(["touchcancel","touchend","touchmove","touchenter","touchleave","touchstart"],{createEventArgs:e=>{return{detail:(t=e).detail,touches:f(t.touches),targetTouches:f(t.targetTouches),changedTouches:f(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{...m(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{...m(t=e),deltaX:t.deltaX,deltaY:t.deltaY,deltaZ:t.deltaZ,deltaMode:t.deltaMode};var t}}),h(["toggle"],c);const p=["date","datetime-local","month","time","week"],v=I(["abort","blur","change","error","focus","load","loadend","loadstart","mouseenter","mouseleave","progress","reset","scroll","submit","unload","toggle","DOMNodeInsertedIntoDocument","DOMNodeRemovedFromDocument"]),g={submit:!0},b=I(["click","dblclick","mousedown","mousemove","mouseup"]);class y{constructor(e){this.browserRendererId=e,this.afterClickCallbacks=[];const t=++y.nextEventDelegatorId;this.eventsCollectionKey=`_blazorEvents_${t}`,this.eventInfoStore=new w(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){let n=t.target,o=null,i=!1;const s=v.hasOwnProperty(e);let c=!1;for(;n;){const h=this.getEventHandlerInfosForElement(n,!1);if(h){const s=h.getHandler(e);if(s&&(l=n,d=t.type,!((l instanceof HTMLButtonElement||l instanceof HTMLInputElement||l instanceof HTMLTextAreaElement||l instanceof HTMLSelectElement)&&b.hasOwnProperty(d)&&l.disabled))){if(!i){const n=u(e);o=(null==n?void 0:n.createEventArgs)?n.createEventArgs(t):{},i=!0}g.hasOwnProperty(t.type)&&t.preventDefault(),a({browserRendererId:this.browserRendererId,eventHandlerId:s.eventHandlerId,eventName:e,eventFieldInfo:r.fromEvent(s.renderingComponentId,t)},o)}h.stopPropagation(e)&&(c=!0),h.preventDefault(e)&&t.preventDefault()}n=s||c?null:n.parentElement}var l,d}getEventHandlerInfosForElement(e,t){return e.hasOwnProperty(this.eventsCollectionKey)?e[this.eventsCollectionKey]:t?e[this.eventsCollectionKey]=new E:null}}y.nextEventDelegatorId=0;class w{constructor(e){this.globalListener=e,this.infosByEventHandlerId={},this.countByEventName={},l.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=d(e),this.countByEventName.hasOwnProperty(e))this.countByEventName[e]++;else{this.countByEventName[e]=1;const t=v.hasOwnProperty(e);document.addEventListener(e,this.globalListener,t)}}update(e,t){if(this.infosByEventHandlerId.hasOwnProperty(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=d(t.eventName);0==--this.countByEventName[n]&&(delete this.countByEventName[n],document.removeEventListener(n,this.globalListener))}return t}handleEventNameAliasAdded(e,t){if(this.countByEventName.hasOwnProperty(e)){const n=this.countByEventName[e];delete this.countByEventName[e],document.removeEventListener(e,this.globalListener),this.addGlobalListener(t),this.countByEventName[t]+=n-1}}}class E{constructor(){this.handlers={},this.preventDefaultFlags=null,this.stopPropagationFlags=null}getHandler(e){return this.handlers.hasOwnProperty(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 I(e){const t={};return e.forEach((e=>{t[e]=!0})),t}const S=M("_blazorLogicalChildren"),C=M("_blazorLogicalParent"),A=M("_blazorLogicalEnd");function D(e,t){if(e.childNodes.length>0&&!t)throw new Error("New logical elements must start empty, or allowExistingContents must be true");return S in e||(e[S]=[]),e}function T(e,t){const n=document.createComment("!");return N(n,e,t),n}function N(e,t,n){const r=e;if(e instanceof Comment&&O(r)&&O(r).length>0)throw new Error("Not implemented: inserting non-empty logical container");if(k(r))throw new Error("Not implemented: moving existing logical children");const o=O(t);if(n0;)R(n,0)}const r=n;r.parentNode.removeChild(r)}function k(e){return e[C]||null}function F(e,t){return O(e)[t]}function _(e){var t=B(e);return"http://www.w3.org/2000/svg"===t.namespaceURI&&"foreignObject"!==t.tagName}function O(e){return e[S]}function x(e,t){const n=O(e);t.forEach((e=>{e.moveRangeStart=n[e.fromSiblingIndex],e.moveRangeEnd=H(e.moveRangeStart)})),t.forEach((t=>{const r=t.moveToBeforeMarker=document.createComment("marker"),o=n[t.toSiblingIndex+1];o?o.parentNode.insertBefore(r,o):P(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 B(e){if(e instanceof Element)return e;if(e instanceof Comment)return e.parentNode;throw new Error("Not a valid logical element")}function L(e){const t=O(k(e));return t[Array.prototype.indexOf.call(t,e)+1]||null}function P(e,t){if(t instanceof Element)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=L(t);n?n.parentNode.insertBefore(e,n):P(e,k(t))}}}function H(e){if(e instanceof Element)return e;const t=L(e);if(t)return t.previousSibling;{const t=k(e);return t instanceof Element?t.lastChild:H(t)}}function M(e){return"function"==typeof Symbol?Symbol():e}function U(e){return`_bl_${e}`}e.attachReviver(((e,t)=>t&&"object"==typeof t&&t.hasOwnProperty("__internalId")&&"string"==typeof t.__internalId?function(e){const t=`[${U(e)}]`;return document.querySelector(t)}(t.__internalId):t));const j="_blazorSelectValue",J=document.createElement("template"),$=document.createElementNS("http://www.w3.org/2000/svg","g"),K={},z="__internal_",V="preventDefault_",X="stopPropagation_";class Y{constructor(e){this.childComponentLocations={},this.eventDelegator=new y(e),this.eventDelegator.notifyAfterClick((e=>{if(!ee)return;if(0!==e.button||function(e){return e.ctrlKey||e.shiftKey||e.altKey||e.metaKey}(e))return;if(e.defaultPrevented)return;const t=function(e){const t=!window._blazorDisableComposedPath&&e.composedPath&&e.composedPath();if(t){for(let e=0;eie(!1))))},enableNavigationInterception:function(){ee=!0},navigateTo:oe,getBaseURI:()=>document.baseURI,getLocationHref:()=>location.href};function oe(e,t,n=!1){const r=ce(e);if(!t&&ue(r))ae(r,!1,n);else if(t&&location.href===e){const t=e+"?";history.replaceState(null,"",t),location.replace(e)}else n?history.replaceState(null,"",r):location.href=e}function ae(e,t,n=!1){Q=!0,n?history.replaceState(null,"",e):history.pushState(null,"",e),ie(t)}async function ie(e){ne&&await ne(location.href,e)}let se;function ce(e){return se=se||document.createElement("a"),se.href=e,se.href}function le(e,t){return e?e.tagName===t?e:le(e.parentElement,t):null}function ue(e){const t=(n=document.baseURI).substr(0,n.lastIndexOf("/")+1);var n;return e.startsWith(t)}const de={init:function(e,t,n,r=50){const o=fe(t);(o||document.documentElement).style.overflowAnchor="none";const a=new IntersectionObserver((function(r){r.forEach((r=>{var o;if(!r.isIntersecting)return;const a=t.getBoundingClientRect(),i=n.getBoundingClientRect().top-a.bottom,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`});a.observe(t),a.observe(n);const i=c(t),s=c(n);function c(e){const t=new MutationObserver((()=>{a.unobserve(e),a.observe(e)}));return t.observe(e,{attributes:!0}),t}he[e._id]={intersectionObserver:a,mutationObserverBefore:i,mutationObserverAfter:s}},dispose:function(e){const t=he[e._id];t&&(t.intersectionObserver.disconnect(),t.mutationObserverBefore.disconnect(),t.mutationObserverAfter.disconnect(),e.dispose(),delete he[e._id])}},he={};function fe(e){return e?"visible"!==getComputedStyle(e).overflowY?e:fe(e.parentElement):null}const me={navigateTo:oe,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]),l.forEach((n=>n(e,t.browserEventName)))}i.set(e,t)},_internal:{navigationManager:re,domWrapper:{focus:function(e,t){if(!(e instanceof HTMLElement))throw new Error("Unable to focus an invalid element.");e.focus({preventScroll:t})},focusBySelector:function(e){const t=document.querySelector(e);t&&(t.hasAttribute("tabindex")||(t.tabIndex=-1),t.focus())}},Virtualize:de}};window.Blazor=me;let pe=!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("")},be=Math.pow(2,32),ye=Math.pow(2,21)-1;function we(e,t){return e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24}function Ee(e,t){return e[t]+(e[t+1]<<8)+(e[t+2]<<16)+(e[t+3]<<24>>>0)}function Ie(e,t){const n=Ee(e,t+4);if(n>ye)throw new Error(`Cannot read uint64 with high order part ${n}, because the result would exceed Number.MAX_SAFE_INTEGER.`);return n*be+Ee(e,t)}class Se{constructor(e){this.batchData=e;const t=new Te(e);this.arrayRangeReader=new Ne(e),this.arrayBuilderSegmentReader=new Re(e),this.diffReader=new Ce(e),this.editReader=new Ae(e,t),this.frameReader=new De(e,t)}updatedComponents(){return we(this.batchData,this.batchData.length-20)}referenceFrames(){return we(this.batchData,this.batchData.length-16)}disposedComponentIds(){return we(this.batchData,this.batchData.length-12)}disposedEventHandlerIds(){return we(this.batchData,this.batchData.length-8)}updatedComponentsEntry(e,t){const n=e+4*t;return we(this.batchData,n)}referenceFramesEntry(e,t){return e+20*t}disposedComponentIdsEntry(e,t){const n=e+4*t;return we(this.batchData,n)}disposedEventHandlerIdsEntry(e,t){const n=e+8*t;return Ie(this.batchData,n)}}class Ce{constructor(e){this.batchDataUint8=e}componentId(e){return we(this.batchDataUint8,e)}edits(e){return e+4}editsEntry(e,t){return e+16*t}}class Ae{constructor(e,t){this.batchDataUint8=e,this.stringReader=t}editType(e){return we(this.batchDataUint8,e)}siblingIndex(e){return we(this.batchDataUint8,e+4)}newTreeIndex(e){return we(this.batchDataUint8,e+8)}moveToSiblingIndex(e){return we(this.batchDataUint8,e+8)}removedAttributeName(e){const t=we(this.batchDataUint8,e+12);return this.stringReader.readString(t)}}class De{constructor(e,t){this.batchDataUint8=e,this.stringReader=t}frameType(e){return we(this.batchDataUint8,e)}subtreeLength(e){return we(this.batchDataUint8,e+4)}elementReferenceCaptureId(e){const t=we(this.batchDataUint8,e+4);return this.stringReader.readString(t)}componentId(e){return we(this.batchDataUint8,e+8)}elementName(e){const t=we(this.batchDataUint8,e+8);return this.stringReader.readString(t)}textContent(e){const t=we(this.batchDataUint8,e+4);return this.stringReader.readString(t)}markupContent(e){const t=we(this.batchDataUint8,e+4);return this.stringReader.readString(t)}attributeName(e){const t=we(this.batchDataUint8,e+4);return this.stringReader.readString(t)}attributeValue(e){const t=we(this.batchDataUint8,e+8);return this.stringReader.readString(t)}attributeEventHandlerId(e){return Ie(this.batchDataUint8,e+12)}}class Te{constructor(e){this.batchDataUint8=e,this.stringTableStartIndex=we(e,e.length-4)}readString(e){if(-1===e)return null;{const n=we(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)<{!function(e,t,n){const r=document.querySelector(e);if(!r)throw new Error(`Could not find any element matching selector '${e}'.`);!function(e,t,n){let r=Z[0];r||(r=Z[0]=new Y(0)),r.attachRootComponentToLogicalElement(n,t)}(0,D(r,!0),t)}(t,e)},RenderBatch:(e,t)=>{try{const n=Me(t);(function(e,t){const n=Z[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{Fe=!0,console.error(`${e}\n${t}`),async function(){let e=document.querySelector("#blazor-error-ui");e&&(e.style.display="block"),pe||(pe=!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:e.jsCallDispatcher.beginInvokeJSFromDotNet,EndInvokeDotNet:e.jsCallDispatcher.endInvokeDotNetFromJS,SendByteArrayToJS:He,Navigate:re.navigateTo};window.external.receiveMessage((e=>{const n=function(e){if(Fe||!e||!e.startsWith(ke))return null;const t=e.substring(ke.length),[n,...r]=JSON.parse(t);return{messageType:n,args:r}}(e);if(n){if(!t.hasOwnProperty(n.messageType))throw new Error(`Unsupported IPC message type '${n.messageType}'`);t[n.messageType].apply(null,n.args)}}))}(),e.attachDispatcher({beginInvokeDotNetFromJS:Oe,endInvokeJSFromDotNet:xe,sendByteArray:Be}),me._internal.InputFile=Ue,re.enableNavigationInterception(),re.listenForNavigationEvents(Le),Pe("AttachPage",re.getBaseURI(),re.getLocationHref())}o=function(e,t){Pe("DispatchBrowserEvent",e,t)},me.start=Ke,document&&document.currentScript&&"false"!==document.currentScript.getAttribute("autostart")&&Ke()})(); \ No newline at end of file diff --git a/src/Components/Web.JS/src/Boot.Server.ts b/src/Components/Web.JS/src/Boot.Server.ts index 23725e7e58bd..c6744916f477 100644 --- a/src/Components/Web.JS/src/Boot.Server.ts +++ b/src/Components/Web.JS/src/Boot.Server.ts @@ -14,6 +14,7 @@ import { DefaultReconnectionHandler } from './Platform/Circuits/DefaultReconnect import { attachRootComponentToLogicalElement } from './Rendering/Renderer'; import { discoverComponents, discoverPersistedState, ServerComponentDescriptor } from './Services/ComponentDescriptorDiscovery'; import { InputFile } from './InputFile'; +import { sendJSDataStream } from './Platform/Circuits/CircuitStreamingInterop'; let renderingFailed = false; let started = false; @@ -122,61 +123,7 @@ async function initializeConnection(options: CircuitStartOptions, logger: Logger Blazor._internal.forceCloseConnection = () => connection.stop(); - Blazor._internal.sendJSDataStream = (data: ArrayBufferView, streamId: string, maximumIncomingBytes: number) => { - // Run the rest in the background, without delaying the completion of the call to sendJSDataStream - // otherwise we'll deadlock (.NET can't begin reading until this completes, but it won't complete - // because nobody's reading the pipe) - setTimeout(async () => { - const maxMillisecondsBetweenAcks = 500; - let numChunksUntilNextAck = 5; - let lastAckTime = new Date().valueOf(); - try { - // Chunk Size is the max SignalR message size less 512 bytes assumed overhead. - const chunkSize = maximumIncomingBytes - 512; - if (chunkSize <= 0) { - throw new Error('The chunk size must be greater than 0.') - } - - let position = 0; - - // Note: The server-side `StreamBufferCapacity` option (defaults to 10) can be configured to limit how many - // stream items from the client (per stream) will be stored before reading any more stream items (thus applying backpressure). - while (position < data.byteLength) { - const nextChunkSize = Math.min(chunkSize, data.byteLength - position); - const nextChunkData = new Uint8Array(data.buffer, data.byteOffset + position, nextChunkSize); - - numChunksUntilNextAck--; - if (numChunksUntilNextAck > 1) { - // Most of the time just send and buffer within the network layer - await connection.send('ReceiveJSDataChunk', streamId, nextChunkData, null); - } else { - // But regularly, wait for an ACK, so other events can be interleaved - // The use of "invoke" (not "send") here is what prevents the JS side from queuing up chunks - // faster than the .NET side can receive them. It means that if there are other user interactions - // while the transfer is in progress, they would get inserted in the middle, so it would be - // possible to navigate away or cancel without first waiting for all the remaining chunks. - const streamIsAlive = await connection.invoke('ReceiveJSDataChunk', streamId, nextChunkData, null); - - // Checks to see if we should continue streaming or if the stream has been cancelled/disposed. - if (!streamIsAlive) { - break; - } - - // Estimate the number of chunks we should send before the next ack to achieve the desired - // interactivity rate - const timeNow = new Date().valueOf(); - const msSinceAck = timeNow - lastAckTime; - lastAckTime = timeNow; - numChunksUntilNextAck = Math.max(1, Math.round(maxMillisecondsBetweenAcks / msSinceAck)); - } - - position += nextChunkSize; - } - } catch (error) { - await connection.send('ReceiveJSDataChunk', streamId, null, error.toString()); - } - }, 0); - }; + Blazor._internal.sendJSDataStream = (data: ArrayBufferView, streamId: string, chunkSize: number) => sendJSDataStream(connection, data, streamId, chunkSize); try { await connection.start(); diff --git a/src/Components/Web.JS/src/GlobalExports.ts b/src/Components/Web.JS/src/GlobalExports.ts index 6bcc70d0febe..756e3159665e 100644 --- a/src/Components/Web.JS/src/GlobalExports.ts +++ b/src/Components/Web.JS/src/GlobalExports.ts @@ -48,7 +48,7 @@ interface IBlazor { getLazyAssemblies?: any dotNetCriticalError?: any getSatelliteAssemblies?: any, - sendJSDataStream?: (data: any, streamId: string, maximumIncomingBytes: number) => void, + sendJSDataStream?: (data: any, streamId: string, chunkSize: number) => void, // APIs invoked by hot reload applyHotReload?: (id: string, metadataDelta: string, ilDelta: string) => void, diff --git a/src/Components/Web.JS/src/Platform/Circuits/CircuitStreamingInterop.ts b/src/Components/Web.JS/src/Platform/Circuits/CircuitStreamingInterop.ts new file mode 100644 index 000000000000..43d3ed02da8f --- /dev/null +++ b/src/Components/Web.JS/src/Platform/Circuits/CircuitStreamingInterop.ts @@ -0,0 +1,51 @@ +import { HubConnection } from '@microsoft/signalr'; + +export function sendJSDataStream(connection: HubConnection, data: ArrayBufferView, streamId: string, chunkSize: number) { + // Run the rest in the background, without delaying the completion of the call to sendJSDataStream + // otherwise we'll deadlock (.NET can't begin reading until this completes, but it won't complete + // because nobody's reading the pipe) + setTimeout(async () => { + const maxMillisecondsBetweenAcks = 500; + let numChunksUntilNextAck = 5; + let lastAckTime = new Date().valueOf(); + try { + let position = 0; + + // Note: The server-side `StreamBufferCapacity` option (defaults to 10) can be configured to limit how many + // stream items from the client (per stream) will be stored before reading any more stream items (thus applying backpressure). + while (position < data.byteLength) { + const nextChunkSize = Math.min(chunkSize, data.byteLength - position); + const nextChunkData = new Uint8Array(data.buffer, data.byteOffset + position, nextChunkSize); + + numChunksUntilNextAck--; + if (numChunksUntilNextAck > 1) { + // Most of the time just send and buffer within the network layer + await connection.send('ReceiveJSDataChunk', streamId, nextChunkData, null); + } else { + // But regularly, wait for an ACK, so other events can be interleaved + // The use of "invoke" (not "send") here is what prevents the JS side from queuing up chunks + // faster than the .NET side can receive them. It means that if there are other user interactions + // while the transfer is in progress, they would get inserted in the middle, so it would be + // possible to navigate away or cancel without first waiting for all the remaining chunks. + const streamIsAlive = await connection.invoke('ReceiveJSDataChunk', streamId, nextChunkData, null); + + // Checks to see if we should continue streaming or if the stream has been cancelled/disposed. + if (!streamIsAlive) { + break; + } + + // Estimate the number of chunks we should send before the next ack to achieve the desired + // interactivity rate. + const timeNow = new Date().valueOf(); + const msSinceAck = timeNow - lastAckTime; + lastAckTime = timeNow; + numChunksUntilNextAck = Math.max(1, Math.round(maxMillisecondsBetweenAcks / Math.max(1, msSinceAck))); + } + + position += nextChunkSize; + } + } catch (error) { + await connection.send('ReceiveJSDataChunk', streamId, null, error.toString()); + } + }, 0); +}; diff --git a/src/Components/Web/src/Forms/InputFile/RemoteBrowserFileStream.cs b/src/Components/Web/src/Forms/InputFile/RemoteBrowserFileStream.cs index cb8b21714173..ddbee6e770db 100644 --- a/src/Components/Web/src/Forms/InputFile/RemoteBrowserFileStream.cs +++ b/src/Components/Web/src/Forms/InputFile/RemoteBrowserFileStream.cs @@ -14,7 +14,7 @@ internal class RemoteBrowserFileStream : BrowserFileStream private readonly IJSRuntime _jsRuntime; private readonly ElementReference _inputFileElement; private readonly long _maxAllowedSize; - private readonly CancellationTokenSource _openRedStreamCts; + private readonly CancellationTokenSource _openReadStreamCts; private readonly Task OpenReadStreamTask; private bool _isDisposed; @@ -32,9 +32,9 @@ public RemoteBrowserFileStream( _jsRuntime = jsRuntime; _inputFileElement = inputFileElement; _maxAllowedSize = maxAllowedSize; - _openRedStreamCts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); + _openReadStreamCts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); - OpenReadStreamTask = OpenReadStreamAsync(options, _openRedStreamCts.Token); + OpenReadStreamTask = OpenReadStreamAsync(options, _openReadStreamCts.Token); } private async Task OpenReadStreamAsync(RemoteBrowserFileStreamOptions options, CancellationToken cancellationToken) @@ -62,7 +62,7 @@ protected override void Dispose(bool disposing) return; } - _openRedStreamCts.Cancel(); + _openReadStreamCts.Cancel(); _copyFileDataCts?.Cancel(); _isDisposed = true; diff --git a/src/Components/WebAssembly/JSInterop/src/WebAssemblyJSRuntime.cs b/src/Components/WebAssembly/JSInterop/src/WebAssemblyJSRuntime.cs index 06eaba3ff592..16d33ed9449b 100644 --- a/src/Components/WebAssembly/JSInterop/src/WebAssemblyJSRuntime.cs +++ b/src/Components/WebAssembly/JSInterop/src/WebAssemblyJSRuntime.cs @@ -102,6 +102,8 @@ internal TResult InvokeUnmarshalled(string identifier, T0 a ? throw new JSException(exception) : (TResult)(object)new WebAssemblyJSObjectReference(this, id); case JSCallResultType.JSStreamReference: + // WebAssembly streaming interop is not presently supported (TODO). Thus we shouldn't see + // a JSCallResultType.JSStreamReference. default: throw new InvalidOperationException($"Invalid result type '{resultType}'."); } From 381c53d2e2336cb6de71f22314f7e9f5af2511e4 Mon Sep 17 00:00:00 2001 From: Tanay Parikh Date: Mon, 21 Jun 2021 15:33:13 -0700 Subject: [PATCH 27/37] 1 Minutes Inactivity Timeout --- .../Server/src/Circuits/RemoteJSDataStream.cs | 38 ++++++-- .../test/Circuits/RemoteJSDataStreamTest.cs | 95 ++++++++++++++++--- 2 files changed, 112 insertions(+), 21 deletions(-) diff --git a/src/Components/Server/src/Circuits/RemoteJSDataStream.cs b/src/Components/Server/src/Circuits/RemoteJSDataStream.cs index 2ffecbd9ab26..a631795562fa 100644 --- a/src/Components/Server/src/Circuits/RemoteJSDataStream.cs +++ b/src/Components/Server/src/Circuits/RemoteJSDataStream.cs @@ -16,6 +16,7 @@ internal sealed class RemoteJSDataStream : Stream private readonly long _streamId; private readonly long _totalLength; private readonly CancellationToken _streamCancellationToken; + private readonly Timer _receiveDataTimer; private readonly Stream _pipeReaderStream; private readonly Pipe _pipe; private long _bytesRead; @@ -65,16 +66,29 @@ private RemoteJSDataStream( _totalLength = totalLength; _streamCancellationToken = cancellationToken; + // Dispose of the stream if a chunk isn't received within 1 minute. + _receiveDataTimer = new Timer(new TimerCallback(async (state) => { + var stream = state as RemoteJSDataStream; + var timeoutException = new TimeoutException("Did not receive any data in the alloted time."); + await stream.CompletePipeAndDisposeStream(timeoutException); + }), this, dueTime: ReceiveDataTimeout, period: Timeout.InfiniteTimeSpan); + _runtime.RemoteJSDataStreamInstances.Add(_streamId, this); _pipe = new Pipe(new PipeOptions(pauseWriterThreshold: maxBufferSize, resumeWriterThreshold: maxBufferSize / 2)); _pipeReaderStream = _pipe.Reader.AsStream(); } + // internal for testing + internal TimeSpan ReceiveDataTimeout { private get; set; } = TimeSpan.FromMinutes(1); + private async Task ReceiveData(byte[] chunk, string error) { try { + // Reset the timeout as a chunk has been received + _receiveDataTimer.Change(dueTime: ReceiveDataTimeout, period: Timeout.InfiniteTimeSpan); + if (!string.IsNullOrEmpty(error)) { throw new InvalidOperationException($"An error occurred while reading the remote stream: {error}"); @@ -82,30 +96,36 @@ private async Task ReceiveData(byte[] chunk, string error) if (chunk.Length == 0) { - throw new InvalidOperationException($"The incoming data chunk cannot be empty."); + throw new EndOfStreamException($"The incoming data chunk cannot be empty."); } _bytesRead += chunk.Length; if (_bytesRead > _totalLength) { - throw new InvalidOperationException($"The incoming data stream declared a length {_totalLength}, but {_bytesRead} bytes were read."); + throw new EndOfStreamException($"The incoming data stream declared a length {_totalLength}, but {_bytesRead} bytes were sent."); } await _pipe.Writer.WriteAsync(chunk, _streamCancellationToken); if (_bytesRead == _totalLength) { - await _pipe.Writer.CompleteAsync(); - Dispose(true); + await CompletePipeAndDisposeStream(); } return true; } catch (Exception e) { - await _pipe.Writer.CompleteAsync(e); - Dispose(true); + await CompletePipeAndDisposeStream(e); + + // Fatal exception, crush the circuit. A well behaved client + // should not result in this type of exception. + if (e is EndOfStreamException) + { + throw; + } + return false; } } @@ -165,6 +185,12 @@ private static CancellationToken GetLinkedCancellationToken(CancellationToken a, return b; } + internal async Task CompletePipeAndDisposeStream(Exception? ex = null) + { + await _pipe.Writer.CompleteAsync(ex); + Dispose(true); + } + protected override void Dispose(bool disposing) { if (disposing) diff --git a/src/Components/Server/test/Circuits/RemoteJSDataStreamTest.cs b/src/Components/Server/test/Circuits/RemoteJSDataStreamTest.cs index 1f6a89a66e69..7b880b97fa08 100644 --- a/src/Components/Server/test/Circuits/RemoteJSDataStreamTest.cs +++ b/src/Components/Server/test/Circuits/RemoteJSDataStreamTest.cs @@ -2,6 +2,7 @@ // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; +using System.IO; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.SignalR; @@ -51,13 +52,68 @@ public async void ReceiveData_SuccessReadsBackStream() var jsRuntime = new TestRemoteJSRuntime(Options.Create(new CircuitOptions()), Options.Create(new HubOptions()), Mock.Of>()); var remoteJSDataStream = await CreateRemoteJSDataStreamAsync(jsRuntime); var streamId = GetStreamId(remoteJSDataStream, jsRuntime); + var chunk = new byte[100]; + var random = new Random(); + random.NextBytes(chunk); + + var sendDataTask = Task.Run(async () => + { + // Act 1 + var success = await RemoteJSDataStream.ReceiveData(jsRuntime, streamId, chunk, error: null); + return success; + }); + + // Act & Assert 2 + using var memoryStream = new MemoryStream(); + await remoteJSDataStream.CopyToAsync(memoryStream); + Assert.Equal(chunk, memoryStream.ToArray()); + + // Act & Assert 3 + var sendDataCompleted = await sendDataTask; + Assert.True(sendDataCompleted); + } + + [Fact] + public async void ReceiveData_ReceiveDataTimeout_StreamDisposed() + { + // Arrange + var jsRuntime = new TestRemoteJSRuntime(Options.Create(new CircuitOptions()), Options.Create(new HubOptions()), Mock.Of>()); + var jsStreamReference = Mock.Of(); + var remoteJSDataStream = await RemoteJSDataStream.CreateRemoteJSDataStreamAsync(jsRuntime ?? _jsRuntime, jsStreamReference, totalLength: 9, maxBufferSize: 50, maximumIncomingBytes: 10_000); + var streamId = GetStreamId(remoteJSDataStream, jsRuntime); var chunk = new byte[] { 3, 5, 7 }; - // Act - var success = await RemoteJSDataStream.ReceiveData(jsRuntime, streamId, chunk, error: null); + // Set a 15 second timeout for testing + remoteJSDataStream.ReceiveDataTimeout = TimeSpan.FromSeconds(15); - // Assert - Assert.True(success); + var sendDataTask = Task.Run(async () => + { + // Act & Assert 1 + var success = await RemoteJSDataStream.ReceiveData(jsRuntime, streamId, chunk, error: null); + Assert.True(success); + + await Task.Delay(TimeSpan.FromSeconds(10)); + + // Act & Assert 2 + success = await RemoteJSDataStream.ReceiveData(jsRuntime, streamId, chunk, error: null); + Assert.True(success); + + await Task.Delay(TimeSpan.FromSeconds(20)); + + // Act & Assert 3 + success = await RemoteJSDataStream.ReceiveData(jsRuntime, streamId, chunk, error: null); + Assert.False(success); + return true; + }); + + // Act & Assert 4 + using var mem = new MemoryStream(); + var ex = await Assert.ThrowsAsync(async() => await remoteJSDataStream.CopyToAsync(mem)); + Assert.Equal("Did not receive any data in the alloted time.", ex.Message); + + // Act & Assert 5 + var sendDataCompleted = await sendDataTask; + Assert.True(sendDataCompleted); } [Fact] @@ -68,11 +124,14 @@ public async void ReceiveData_WithError() var remoteJSDataStream = await CreateRemoteJSDataStreamAsync(jsRuntime); var streamId = GetStreamId(remoteJSDataStream, jsRuntime); - // Act + // Act & Assert 1 var success = await RemoteJSDataStream.ReceiveData(jsRuntime, streamId, chunk: null, error: "some error"); - - // Assert Assert.False(success); + + // Act & Assert 2 + using var mem = new MemoryStream(); + var ex = await Assert.ThrowsAsync(async () => await remoteJSDataStream.CopyToAsync(mem)); + Assert.Equal("An error occurred while reading the remote stream: some error", ex.Message); } [Fact] @@ -84,11 +143,14 @@ public async void ReceiveData_WithZeroLengthChunk() var streamId = GetStreamId(remoteJSDataStream, jsRuntime); var chunk = Array.Empty(); - // Act - var success = await RemoteJSDataStream.ReceiveData(jsRuntime, streamId, chunk, error: null); + // Act & Assert 1 + var ex = await Assert.ThrowsAsync(async () => await RemoteJSDataStream.ReceiveData(jsRuntime, streamId, chunk, error: null)); + Assert.Equal("The incoming data chunk cannot be empty.", ex.Message); - // Assert - Assert.False(success); + // Act & Assert 2 + using var mem = new MemoryStream(); + ex = await Assert.ThrowsAsync(async () => await remoteJSDataStream.CopyToAsync(mem)); + Assert.Equal("The incoming data chunk cannot be empty.", ex.Message); } [Fact] @@ -101,11 +163,14 @@ public async void ReceiveData_ProvidedWithMoreBytesThanRemaining() var streamId = GetStreamId(remoteJSDataStream, jsRuntime); var chunk = new byte[110]; // 100 byte totalLength for stream - // Act - var success = await RemoteJSDataStream.ReceiveData(jsRuntime, streamId, chunk, error: null); + // Act & Assert 1 + var ex = await Assert.ThrowsAsync(async () => await RemoteJSDataStream.ReceiveData(jsRuntime, streamId, chunk, error: null)); + Assert.Equal("The incoming data stream declared a length 100, but 110 bytes were sent.", ex.Message); - // Assert - Assert.False(success); + // Act & Assert 2 + using var mem = new MemoryStream(); + ex = await Assert.ThrowsAsync(async () => await remoteJSDataStream.CopyToAsync(mem)); + Assert.Equal("The incoming data stream declared a length 100, but 110 bytes were sent.", ex.Message); } private static async Task CreateRemoteJSDataStreamAsync(TestRemoteJSRuntime jsRuntime = null) From 6e09532bf49eed0f404f3d95e83f49f28849b2cb Mon Sep 17 00:00:00 2001 From: Tanay Parikh Date: Mon, 21 Jun 2021 16:36:09 -0700 Subject: [PATCH 28/37] Integrate chunk sequence validation for SignalR Disconnect --- .../Server/src/Circuits/CircuitHost.cs | 4 +- .../Server/src/Circuits/RemoteJSDataStream.cs | 14 ++++-- src/Components/Server/src/ComponentHub.cs | 4 +- .../test/Circuits/RemoteJSDataStreamTest.cs | 45 +++++++++++++++---- .../Web.JS/dist/Release/blazor.server.js | 2 +- .../Web.JS/dist/Release/blazor.webview.js | 2 +- .../Circuits/CircuitStreamingInterop.ts | 8 ++-- 7 files changed, 59 insertions(+), 20 deletions(-) diff --git a/src/Components/Server/src/Circuits/CircuitHost.cs b/src/Components/Server/src/Circuits/CircuitHost.cs index 84f49de34769..f6b544d6f7e2 100644 --- a/src/Components/Server/src/Circuits/CircuitHost.cs +++ b/src/Components/Server/src/Circuits/CircuitHost.cs @@ -418,14 +418,14 @@ await Renderer.Dispatcher.InvokeAsync(() => // ReceiveJSDataChunk is used in a fire-and-forget context, so it's responsible for its own // error handling. - internal async Task ReceiveJSDataChunk(long streamId, byte[] chunk, string error) + internal async Task ReceiveJSDataChunk(long streamId, long chunkId, byte[] chunk, string error) { AssertInitialized(); AssertNotDisposed(); try { - return await RemoteJSDataStream.ReceiveData(JSRuntime, streamId, chunk, error); + return await RemoteJSDataStream.ReceiveData(JSRuntime, streamId, chunkId, chunk, error); } catch (Exception ex) { diff --git a/src/Components/Server/src/Circuits/RemoteJSDataStream.cs b/src/Components/Server/src/Circuits/RemoteJSDataStream.cs index a631795562fa..13d6451467ae 100644 --- a/src/Components/Server/src/Circuits/RemoteJSDataStream.cs +++ b/src/Components/Server/src/Circuits/RemoteJSDataStream.cs @@ -20,8 +20,9 @@ internal sealed class RemoteJSDataStream : Stream private readonly Stream _pipeReaderStream; private readonly Pipe _pipe; private long _bytesRead; + private long _expectedChunkId; - public static async Task ReceiveData(RemoteJSRuntime runtime, long streamId, byte[] chunk, string error) + public static async Task ReceiveData(RemoteJSRuntime runtime, long streamId, long chunkId, byte[] chunk, string error) { if (!runtime.RemoteJSDataStreamInstances.TryGetValue(streamId, out var instance)) { @@ -30,7 +31,7 @@ public static async Task ReceiveData(RemoteJSRuntime runtime, long streamI return false; } - return await instance.ReceiveData(chunk, error); + return await instance.ReceiveData(chunkId, chunk, error); } public static async ValueTask CreateRemoteJSDataStreamAsync( @@ -82,7 +83,7 @@ private RemoteJSDataStream( // internal for testing internal TimeSpan ReceiveDataTimeout { private get; set; } = TimeSpan.FromMinutes(1); - private async Task ReceiveData(byte[] chunk, string error) + private async Task ReceiveData(long chunkId, byte[] chunk, string error) { try { @@ -94,6 +95,13 @@ private async Task ReceiveData(byte[] chunk, string error) throw new InvalidOperationException($"An error occurred while reading the remote stream: {error}"); } + if (chunkId != _expectedChunkId) + { + throw new EndOfStreamException($"Out of sequence chunk received, expected {_expectedChunkId}, but received {chunkId}."); + } + + ++_expectedChunkId; + if (chunk.Length == 0) { throw new EndOfStreamException($"The incoming data chunk cannot be empty."); diff --git a/src/Components/Server/src/ComponentHub.cs b/src/Components/Server/src/ComponentHub.cs index d55c1036c905..01b65d9073db 100644 --- a/src/Components/Server/src/ComponentHub.cs +++ b/src/Components/Server/src/ComponentHub.cs @@ -224,7 +224,7 @@ public async ValueTask ReceiveByteArray(int id, byte[] data) _ = circuitHost.ReceiveByteArray(id, data); } - public async ValueTask ReceiveJSDataChunk(long streamId, byte[] chunk, string error) + public async ValueTask ReceiveJSDataChunk(long streamId, long chunkId, byte[] chunk, string error) { var circuitHost = await GetActiveCircuitAsync(); if (circuitHost == null) @@ -232,7 +232,7 @@ public async ValueTask ReceiveJSDataChunk(long streamId, byte[] chunk, str return false; } - return await circuitHost.ReceiveJSDataChunk(streamId, chunk, error); + return await circuitHost.ReceiveJSDataChunk(streamId, chunkId, chunk, error); } public async ValueTask DispatchBrowserEvent(string eventDescriptor, string eventArgs) diff --git a/src/Components/Server/test/Circuits/RemoteJSDataStreamTest.cs b/src/Components/Server/test/Circuits/RemoteJSDataStreamTest.cs index 7b880b97fa08..5b51150cf115 100644 --- a/src/Components/Server/test/Circuits/RemoteJSDataStreamTest.cs +++ b/src/Components/Server/test/Circuits/RemoteJSDataStreamTest.cs @@ -39,7 +39,7 @@ public async void ReceiveData_DoesNotFindStream() var unrecognizedGuid = 10; // Act - var success = await RemoteJSDataStream.ReceiveData(_jsRuntime, streamId: unrecognizedGuid, chunk, error: null); + var success = await RemoteJSDataStream.ReceiveData(_jsRuntime, streamId: unrecognizedGuid, chunkId: 0, chunk, error: null); // Assert Assert.False(success); @@ -59,7 +59,7 @@ public async void ReceiveData_SuccessReadsBackStream() var sendDataTask = Task.Run(async () => { // Act 1 - var success = await RemoteJSDataStream.ReceiveData(jsRuntime, streamId, chunk, error: null); + var success = await RemoteJSDataStream.ReceiveData(jsRuntime, streamId, chunkId: 0, chunk, error: null); return success; }); @@ -89,23 +89,28 @@ public async void ReceiveData_ReceiveDataTimeout_StreamDisposed() var sendDataTask = Task.Run(async () => { // Act & Assert 1 - var success = await RemoteJSDataStream.ReceiveData(jsRuntime, streamId, chunk, error: null); + var success = await RemoteJSDataStream.ReceiveData(jsRuntime, streamId, chunkId: 0, chunk, error: null); Assert.True(success); await Task.Delay(TimeSpan.FromSeconds(10)); // Act & Assert 2 - success = await RemoteJSDataStream.ReceiveData(jsRuntime, streamId, chunk, error: null); + success = await RemoteJSDataStream.ReceiveData(jsRuntime, streamId, chunkId: 1, chunk, error: null); Assert.True(success); await Task.Delay(TimeSpan.FromSeconds(20)); // Act & Assert 3 - success = await RemoteJSDataStream.ReceiveData(jsRuntime, streamId, chunk, error: null); + // Ensures stream is disposed after the timeout and any additional chunks aren't accepted + success = await RemoteJSDataStream.ReceiveData(jsRuntime, streamId, chunkId: 2, chunk, error: null); Assert.False(success); return true; }); + // Wait past the initial 15 second timeout to ensure it gets reset after + // a new data chunk is received. + await Task.Delay(TimeSpan.FromSeconds(20)); + // Act & Assert 4 using var mem = new MemoryStream(); var ex = await Assert.ThrowsAsync(async() => await remoteJSDataStream.CopyToAsync(mem)); @@ -125,7 +130,7 @@ public async void ReceiveData_WithError() var streamId = GetStreamId(remoteJSDataStream, jsRuntime); // Act & Assert 1 - var success = await RemoteJSDataStream.ReceiveData(jsRuntime, streamId, chunk: null, error: "some error"); + var success = await RemoteJSDataStream.ReceiveData(jsRuntime, streamId, chunkId: 0, chunk: null, error: "some error"); Assert.False(success); // Act & Assert 2 @@ -144,7 +149,7 @@ public async void ReceiveData_WithZeroLengthChunk() var chunk = Array.Empty(); // Act & Assert 1 - var ex = await Assert.ThrowsAsync(async () => await RemoteJSDataStream.ReceiveData(jsRuntime, streamId, chunk, error: null)); + var ex = await Assert.ThrowsAsync(async () => await RemoteJSDataStream.ReceiveData(jsRuntime, streamId, chunkId: 0, chunk, error: null)); Assert.Equal("The incoming data chunk cannot be empty.", ex.Message); // Act & Assert 2 @@ -164,7 +169,7 @@ public async void ReceiveData_ProvidedWithMoreBytesThanRemaining() var chunk = new byte[110]; // 100 byte totalLength for stream // Act & Assert 1 - var ex = await Assert.ThrowsAsync(async () => await RemoteJSDataStream.ReceiveData(jsRuntime, streamId, chunk, error: null)); + var ex = await Assert.ThrowsAsync(async () => await RemoteJSDataStream.ReceiveData(jsRuntime, streamId, chunkId: 0, chunk, error: null)); Assert.Equal("The incoming data stream declared a length 100, but 110 bytes were sent.", ex.Message); // Act & Assert 2 @@ -173,6 +178,30 @@ public async void ReceiveData_ProvidedWithMoreBytesThanRemaining() Assert.Equal("The incoming data stream declared a length 100, but 110 bytes were sent.", ex.Message); } + [Fact] + public async void ReceiveData_ProvidedWithOutOfOrderChunk_SimulatesSignalRDisconnect() + { + // Arrange + var jsRuntime = new TestRemoteJSRuntime(Options.Create(new CircuitOptions()), Options.Create(new HubOptions()), Mock.Of>()); + var jsStreamReference = Mock.Of(); + var remoteJSDataStream = await RemoteJSDataStream.CreateRemoteJSDataStreamAsync(jsRuntime, jsStreamReference, totalLength: 100, maxBufferSize: 50, maximumIncomingBytes: 10_000); + var streamId = GetStreamId(remoteJSDataStream, jsRuntime); + var chunk = new byte[5]; + + // Act & Assert 1 + for (var i = 0; i < 5; i++) + { + await RemoteJSDataStream.ReceiveData(jsRuntime, streamId, chunkId: i, chunk, error: null); + } + var ex = await Assert.ThrowsAsync(async () => await RemoteJSDataStream.ReceiveData(jsRuntime, streamId, chunkId: 7, chunk, error: null)); + Assert.Equal("Out of sequence chunk received, expected 5, but received 7.", ex.Message); + + // Act & Assert 2 + using var mem = new MemoryStream(); + ex = await Assert.ThrowsAsync(async () => await remoteJSDataStream.CopyToAsync(mem)); + Assert.Equal("Out of sequence chunk received, expected 5, but received 7.", ex.Message); + } + private static async Task CreateRemoteJSDataStreamAsync(TestRemoteJSRuntime jsRuntime = null) { var jsStreamReference = Mock.Of(); diff --git a/src/Components/Web.JS/dist/Release/blazor.server.js b/src/Components/Web.JS/dist/Release/blazor.server.js index b8dbef524080..43cd902449d1 100644 --- a/src/Components/Web.JS/dist/Release/blazor.server.js +++ b/src/Components/Web.JS/dist/Release/blazor.server.js @@ -1 +1 @@ -(()=>{"use strict";var e,t,n;!function(e){window.DotNet=e;const t=[],n=new Map;class r{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 o="__jsObjectId",i={},s={0:new r(window)};s[0]._cachedFunctions.set("import",(e=>("string"==typeof e&&e.startsWith("./")&&(e=document.baseURI+e.substr(2)),import(e))));let a,c=1,l=1,h=null;function u(e){t.push(e)}function d(e){if(e&&"object"==typeof e){s[l]=new r(e);const t={[o]:l};return l++,t}throw new Error(`Cannot create a JSObjectReference from the value '${e}'.`)}function p(e){if(!(e.buffer instanceof ArrayBuffer))throw new Error(`Cannot create a JSStreamReference from the value '${e}' as it is not a valid ArrayBuffer.`);if(void 0===e.byteLength)throw new Error(`Cannot create a JSStreamReference from the value '${e}' as it doesn't have a byteLength.`);const t={__jsStreamReferenceLength:e.byteLength-5};try{const n=d(e);t.__jsObjectId=n.__jsObjectId}catch{throw new Error(`Cannot create a JSStreamReference from the value '${e}'.`)}return t}function f(e){return e?JSON.parse(e,((e,n)=>t.reduce(((t,n)=>n(e,t)),n))):null}function g(e,t,n,r){const o=y();if(o.invokeDotNetFromJS){const i=k(r),s=o.invokeDotNetFromJS(e,t,n,i);return s?f(s):null}throw new Error("The current dispatcher does not support synchronous calls from JS to .NET. Use invokeMethodAsync instead.")}function m(e,t,n,r){if(e&&n)throw new Error(`For instance method calls, assemblyName should be null. Received '${e}'.`);const o=c++,s=new Promise(((e,t)=>{i[o]={resolve:e,reject:t}}));try{const i=k(r);y().beginInvokeDotNetFromJS(o,e,t,n,i)}catch(e){w(o,!1,e)}return s}function y(){if(null!==h)return h;throw new Error("No .NET call dispatcher has been set.")}function w(e,t,n){if(!i.hasOwnProperty(e))throw new Error(`There is no pending async call with ID ${e}.`);const r=i[e];delete i[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){let n=s[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 s[e]}e.attachDispatcher=function(e){h=e},e.attachReviver=u,e.invokeMethod=function(e,t,...n){return g(e,t,null,n)},e.invokeMethodAsync=function(e,t,...n){return m(e,t,null,n)},e.createJSObjectReference=d,e.createJSStreamReference=p,e.disposeJSObjectReference=function(e){const t=e&&e.__jsObjectId;"number"==typeof t&&_(t)},function(e){e[e.Default=0]="Default",e[e.JSObjectReference=1]="JSObjectReference",e[e.JSStreamReference=2]="JSStreamReference"}(a=e.JSCallResultType||(e.JSCallResultType={})),e.jsCallDispatcher={findJSFunction:b,disposeJSObjectReferenceById:_,invokeJSFromDotNet:(e,t,n,r)=>{const o=C(b(e,r).apply(null,f(t)),n);return null==o?null:k(o)},beginInvokeJSFromDotNet:(e,t,n,r,o)=>{const i=new Promise((e=>{e(b(t,o).apply(null,f(n)))}));e&&i.then((t=>y().endInvokeJSFromDotNet(e,!0,k([e,!0,C(t,r)]))),(t=>y().endInvokeJSFromDotNet(e,!1,JSON.stringify([e,!1,v(t)]))))},endInvokeDotNetFromJS:(e,t,n)=>{const r=t?f(n):new Error(n);w(parseInt(e),t,r)},receiveByteArray:(e,t)=>{n.set(e,t)}};class E{constructor(e){this._id=e}invokeMethod(e,...t){return g(null,e,this._id,t)}invokeMethodAsync(e,...t){return m(null,e,this._id,t)}dispose(){m(null,"__Dispose",this._id,null).catch((e=>console.error(e)))}serializeAsArg(){return{__dotNetObject:this._id}}}const S="__byte[]";function C(e,t){switch(t){case a.Default:return e;case a.JSObjectReference:return d(e);case a.JSStreamReference:return p(e);default:throw new Error(`Invalid JS call result type '${t}'.`)}}u((function(e,t){if(t&&"object"==typeof t){if(t.hasOwnProperty("__dotNetObject"))return new E(t.__dotNetObject);if(t.hasOwnProperty(o)){const e=t.__jsObjectId,n=s[e];if(n)return n.getWrappedObject();throw new Error(`JS object instance with Id '${e}' does not exist. It may have been disposed.`)}if(t.hasOwnProperty(S)){const e=t["__byte[]"],r=n.get(e);if(void 0===r)throw new Error(`Byte array index '${e}' does not exist.`);return r}}return t}));let I=0;function k(e){return I=0,JSON.stringify(e,T)}function T(e,t){if(t instanceof E)return t.serializeAsArg();if(t instanceof Uint8Array){h.sendByteArray(I,t);const e={[S]:I};return I++,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"}(n||(n={}));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}}let o;function i(e,t){if(!o)throw new Error("eventDispatcher not initialized. Call 'setEventDispatcher' to configure it.");o(e,t)}const s=new Map,a=new Map,c={createEventArgs:()=>({})},l=[];function h(e){return s.get(e)}function u(e){const t=s.get(e);return(null==t?void 0:t.browserEventName)||e}function d(e,t){e.forEach((e=>s.set(e,t)))}function p(e){const t=[];for(let n=0;n{return{...f(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}}),d(["focus","blur","focusin","focusout"],c),d(["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};var t}}),d(["contextmenu","click","mouseover","mouseout","mousemove","mousedown","mouseup","dblclick"],{createEventArgs:e=>f(e)}),d(["error"],{createEventArgs:e=>{return{message:(t=e).message,filename:t.filename,lineno:t.lineno,colno:t.colno};var t}}),d(["loadstart","timeout","abort","load","loadend","progress"],{createEventArgs:e=>{return{lengthComputable:(t=e).lengthComputable,loaded:t.loaded,total:t.total};var t}}),d(["touchcancel","touchend","touchmove","touchenter","touchleave","touchstart"],{createEventArgs:e=>{return{detail:(t=e).detail,touches:p(t.touches),targetTouches:p(t.targetTouches),changedTouches:p(t.changedTouches),ctrlKey:t.ctrlKey,shiftKey:t.shiftKey,altKey:t.altKey,metaKey:t.metaKey,type:t.type};var t}}),d(["gotpointercapture","lostpointercapture","pointercancel","pointerdown","pointerenter","pointerleave","pointermove","pointerout","pointerover","pointerup"],{createEventArgs:e=>{return{...f(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}}),d(["wheel","mousewheel"],{createEventArgs:e=>{return{...f(t=e),deltaX:t.deltaX,deltaY:t.deltaY,deltaZ:t.deltaZ,deltaMode:t.deltaMode};var t}}),d(["toggle"],c);const g=["date","datetime-local","month","time","week"],m=E(["abort","blur","change","error","focus","load","loadend","loadstart","mouseenter","mouseleave","progress","reset","scroll","submit","unload","toggle","DOMNodeInsertedIntoDocument","DOMNodeRemovedFromDocument"]),y={submit:!0},w=E(["click","dblclick","mousedown","mousemove","mouseup"]);class v{constructor(e){this.browserRendererId=e,this.afterClickCallbacks=[];const t=++v.nextEventDelegatorId;this.eventsCollectionKey=`_blazorEvents_${t}`,this.eventInfoStore=new b(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,a.get(n));var n;t&&t.forEach((t=>this.dispatchGlobalEventToAllElements(t,e))),"click"===e.type&&this.afterClickCallbacks.forEach((t=>t(e)))}dispatchGlobalEventToAllElements(e,t){let n=t.target,o=null,s=!1;const a=m.hasOwnProperty(e);let c=!1;for(;n;){const d=this.getEventHandlerInfosForElement(n,!1);if(d){const a=d.getHandler(e);if(a&&(l=n,u=t.type,!((l instanceof HTMLButtonElement||l instanceof HTMLInputElement||l instanceof HTMLTextAreaElement||l instanceof HTMLSelectElement)&&w.hasOwnProperty(u)&&l.disabled))){if(!s){const n=h(e);o=(null==n?void 0:n.createEventArgs)?n.createEventArgs(t):{},s=!0}y.hasOwnProperty(t.type)&&t.preventDefault(),i({browserRendererId:this.browserRendererId,eventHandlerId:a.eventHandlerId,eventName:e,eventFieldInfo:r.fromEvent(a.renderingComponentId,t)},o)}d.stopPropagation(e)&&(c=!0),d.preventDefault(e)&&t.preventDefault()}n=a||c?null:n.parentElement}var l,u}getEventHandlerInfosForElement(e,t){return e.hasOwnProperty(this.eventsCollectionKey)?e[this.eventsCollectionKey]:t?e[this.eventsCollectionKey]=new _:null}}v.nextEventDelegatorId=0;class b{constructor(e){this.globalListener=e,this.infosByEventHandlerId={},this.countByEventName={},l.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=u(e),this.countByEventName.hasOwnProperty(e))this.countByEventName[e]++;else{this.countByEventName[e]=1;const t=m.hasOwnProperty(e);document.addEventListener(e,this.globalListener,t)}}update(e,t){if(this.infosByEventHandlerId.hasOwnProperty(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=u(t.eventName);0==--this.countByEventName[n]&&(delete this.countByEventName[n],document.removeEventListener(n,this.globalListener))}return t}handleEventNameAliasAdded(e,t){if(this.countByEventName.hasOwnProperty(e)){const n=this.countByEventName[e];delete this.countByEventName[e],document.removeEventListener(e,this.globalListener),this.addGlobalListener(t),this.countByEventName[t]+=n-1}}}class _{constructor(){this.handlers={},this.preventDefaultFlags=null,this.stopPropagationFlags=null}getHandler(e){return this.handlers.hasOwnProperty(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 E(e){const t={};return e.forEach((e=>{t[e]=!0})),t}const S=O("_blazorLogicalChildren"),C=O("_blazorLogicalParent"),I=O("_blazorLogicalEnd");function k(e,t){if(e.childNodes.length>0&&!t)throw new Error("New logical elements must start empty, or allowExistingContents must be true");return S in e||(e[S]=[]),e}function T(e,t){const n=document.createComment("!");return x(n,e,t),n}function x(e,t,n){const r=e;if(e instanceof Comment&&A(r)&&A(r).length>0)throw new Error("Not implemented: inserting non-empty logical container");if(R(r))throw new Error("Not implemented: moving existing logical children");const o=A(t);if(n0;)D(n,0)}const r=n;r.parentNode.removeChild(r)}function R(e){return e[C]||null}function P(e,t){return A(e)[t]}function U(e){var t=B(e);return"http://www.w3.org/2000/svg"===t.namespaceURI&&"foreignObject"!==t.tagName}function A(e){return e[S]}function N(e,t){const n=A(e);t.forEach((e=>{e.moveRangeStart=n[e.fromSiblingIndex],e.moveRangeEnd=M(e.moveRangeStart)})),t.forEach((t=>{const r=t.moveToBeforeMarker=document.createComment("marker"),o=n[t.toSiblingIndex+1];o?o.parentNode.insertBefore(r,o):L(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 B(e){if(e instanceof Element)return e;if(e instanceof Comment)return e.parentNode;throw new Error("Not a valid logical element")}function $(e){const t=A(R(e));return t[Array.prototype.indexOf.call(t,e)+1]||null}function L(e,t){if(t instanceof Element)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=$(t);n?n.parentNode.insertBefore(e,n):L(e,R(t))}}}function M(e){if(e instanceof Element)return e;const t=$(e);if(t)return t.previousSibling;{const t=R(e);return t instanceof Element?t.lastChild:M(t)}}function O(e){return"function"==typeof Symbol?Symbol():e}function H(e){return`_bl_${e}`}e.attachReviver(((e,t)=>t&&"object"==typeof t&&t.hasOwnProperty("__internalId")&&"string"==typeof t.__internalId?function(e){const t=`[${H(e)}]`;return document.querySelector(t)}(t.__internalId):t));const F="_blazorSelectValue",j=document.createElement("template"),W=document.createElementNS("http://www.w3.org/2000/svg","g"),z={},q="__internal_",J="preventDefault_",K="stopPropagation_";class V{constructor(e){this.childComponentLocations={},this.eventDelegator=new v(e),this.eventDelegator.notifyAfterClick((e=>{if(!ee)return;if(0!==e.button||function(e){return e.ctrlKey||e.shiftKey||e.altKey||e.metaKey}(e))return;if(e.defaultPrevented)return;const t=function(e){const t=!window._blazorDisableComposedPath&&e.composedPath&&e.composedPath();if(t){for(let e=0;ese(!1))))},enableNavigationInterception:function(){ee=!0},navigateTo:oe,getBaseURI:()=>document.baseURI,getLocationHref:()=>location.href};function oe(e,t,n=!1){const r=ce(e);if(!t&&he(r))ie(r,!1,n);else if(t&&location.href===e){const t=e+"?";history.replaceState(null,"",t),location.replace(e)}else n?history.replaceState(null,"",r):location.href=e}function ie(e,t,n=!1){Z=!0,n?history.replaceState(null,"",e):history.pushState(null,"",e),se(t)}async function se(e){ne&&await ne(location.href,e)}let ae;function ce(e){return ae=ae||document.createElement("a"),ae.href=e,ae.href}function le(e,t){return e?e.tagName===t?e:le(e.parentElement,t):null}function he(e){const t=(n=document.baseURI).substr(0,n.lastIndexOf("/")+1);var n;return e.startsWith(t)}const ue={init:function(e,t,n,r=50){const o=pe(t);(o||document.documentElement).style.overflowAnchor="none";const i=new IntersectionObserver((function(r){r.forEach((r=>{var o;if(!r.isIntersecting)return;const i=t.getBoundingClientRect(),s=n.getBoundingClientRect().top-i.bottom,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`});i.observe(t),i.observe(n);const s=c(t),a=c(n);function c(e){const t=new MutationObserver((()=>{i.unobserve(e),i.observe(e)}));return t.observe(e,{attributes:!0}),t}de[e._id]={intersectionObserver:i,mutationObserverBefore:s,mutationObserverAfter:a}},dispose:function(e){const t=de[e._id];t&&(t.intersectionObserver.disconnect(),t.mutationObserverBefore.disconnect(),t.mutationObserverAfter.disconnect(),e.dispose(),delete de[e._id])}},de={};function pe(e){return e?"visible"!==getComputedStyle(e).overflowY?e:pe(e.parentElement):null}const fe={navigateTo:oe,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=a.get(t.browserEventName);n?n.push(e):a.set(t.browserEventName,[e]),l.forEach((n=>n(e,t.browserEventName)))}s.set(e,t)},_internal:{navigationManager:re,domWrapper:{focus:function(e,t){if(!(e instanceof HTMLElement))throw new Error("Unable to focus an invalid element.");e.focus({preventScroll:t})},focusBySelector:function(e){const t=document.querySelector(e);t&&(t.hasAttribute("tabindex")||(t.tabIndex=-1),t.focus())}},Virtualize:ue}};window.Blazor=fe;const ge=[0,2e3,1e4,3e4,null];class me{constructor(e){this._retryDelays=void 0!==e?[...e,null]:ge}nextRetryDelayInMilliseconds(e){return this._retryDelays[e.previousRetryCount]}}class ye extends Error{constructor(e,t){const n=new.target.prototype;super(`${e}: Status code '${t}'`),this.statusCode=t,this.__proto__=n}}class we extends Error{constructor(e="A timeout occurred."){const t=new.target.prototype;super(e),this.__proto__=t}}class ve extends Error{constructor(e="An abort occurred."){const t=new.target.prototype;super(e),this.__proto__=t}}class be{constructor(e,t,n){this.statusCode=e,this.statusText=t,this.content=n}}class _e{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""}}var Ee,Se,Ce,Ie,ke;!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"}(Ee||(Ee={}));class Te extends _e{constructor(e){if(super(),this._logger=e,"undefined"==typeof fetch){const e=require;this._jar=new(e("tough-cookie").CookieJar),this._fetchType=e("node-fetch"),this._fetchType=e("fetch-cookie")(this._fetchType,this._jar),this._abortControllerType=e("abort-controller")}else this._fetchType=fetch.bind(self),this._abortControllerType=AbortController}async send(e){if(e.abortSignal&&e.abortSignal.aborted)throw new ve;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 ve});let r,o=null;if(e.timeout){const r=e.timeout;o=setTimeout((()=>{t.abort(),this._logger.log(Ee.Warning,"Timeout from HTTP request."),n=new we}),r)}try{r=await this._fetchType(e.url,{body:e.content,cache:"no-cache",credentials:!0===e.withCredentials?"include":"same-origin",headers:{"Content-Type":"text/plain;charset=UTF-8","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(Ee.Warning,`Error from HTTP request. ${e}.`),e}finally{o&&clearTimeout(o),e.abortSignal&&(e.abortSignal.onabort=null)}if(!r.ok){const e=await xe(r,"text");throw new ye(e||r.statusText,r.status)}const i=xe(r,e.responseType),s=await i;return new be(r.status,r.statusText,s)}getCookieString(e){return""}}function xe(e,t){let n;switch(t){case"arraybuffer":n=e.arrayBuffer();break;case"text":n=e.text();break;case"blob":case"document":case"json":throw new Error(`${t} is not supported.`);default:n=e.text()}return n}class De extends _e{constructor(e){super(),this._logger=e}send(e){return e.abortSignal&&e.abortSignal.aborted?Promise.reject(new ve):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"),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 ve)}),e.timeout&&(r.timeout=e.timeout),r.onload=()=>{e.abortSignal&&(e.abortSignal.onabort=null),r.status>=200&&r.status<300?t(new be(r.status,r.statusText,r.response||r.responseText)):n(new ye(r.response||r.responseText||r.statusText,r.status))},r.onerror=()=>{this._logger.log(Ee.Warning,`Error from HTTP request. ${r.status}: ${r.statusText}.`),n(new ye(r.statusText,r.status))},r.ontimeout=()=>{this._logger.log(Ee.Warning,"Timeout from HTTP request."),n(new we)},r.send(e.content||"")})):Promise.reject(new Error("No url defined.")):Promise.reject(new Error("No method defined."))}}class Re extends _e{constructor(e){if(super(),"undefined"!=typeof fetch)this._httpClient=new Te(e);else{if("undefined"==typeof XMLHttpRequest)throw new Error("No usable HttpClient found.");this._httpClient=new De(e)}}send(e){return e.abortSignal&&e.abortSignal.aborted?Promise.reject(new ve):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)}}class Pe{}Pe.Authorization="Authorization",Pe.Cookie="Cookie",function(e){e[e.None=0]="None",e[e.WebSockets=1]="WebSockets",e[e.ServerSentEvents=2]="ServerSentEvents",e[e.LongPolling=4]="LongPolling"}(Se||(Se={})),function(e){e[e.Text=1]="Text",e[e.Binary=2]="Binary"}(Ce||(Ce={}));class Ue{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 Ae{constructor(){}log(e,t){}}Ae.instance=new Ae;class Ne{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 Be{static get isBrowser(){return"object"==typeof window}static get isWebWorker(){return"object"==typeof self&&"importScripts"in self}static get isNode(){return!this.isBrowser&&!this.isWebWorker}}function $e(e,t){let n="";return Le(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 Le(e){return e&&"undefined"!=typeof ArrayBuffer&&(e instanceof ArrayBuffer||e.constructor&&"ArrayBuffer"===e.constructor.name)}async function Me(e,t,n,r,o,i,s,a,c){let l={};if(o){const e=await o();e&&(l={Authorization:`Bearer ${e}`})}const[h,u]=Fe();l[h]=u,e.log(Ee.Trace,`(${t} transport) sending data. ${$e(i,s)}.`);const d=Le(i)?"arraybuffer":"text",p=await n.post(r,{content:i,headers:{...l,...c},responseType:d,withCredentials:a});e.log(Ee.Trace,`(${t} transport) request complete. Response status: ${p.statusCode}.`)}class Oe{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 He{constructor(e){this._minLevel=e,this.out=console}log(e,t){if(e>=this._minLevel){const n=`[${(new Date).toISOString()}] ${Ee[e]}: ${t}`;switch(e){case Ee.Critical:case Ee.Error:this.out.error(n);break;case Ee.Warning:this.out.warn(n);break;case Ee.Information:this.out.info(n);break;default:this.out.log(n)}}}}function Fe(){let e="X-SignalR-User-Agent";return Be.isNode&&(e="User-Agent"),[e,je("0.0.0-DEV_BUILD",We(),Be.isNode?"NodeJS":"Browser",ze())]}function je(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 We(){if(!Be.isNode)return"";switch(process.platform){case"win32":return"Windows NT";case"darwin":return"macOS";case"linux":return"Linux";default:return process.platform}}function ze(){if(Be.isNode)return process.versions.node}class qe{constructor(e,t,n,r,o,i){this._httpClient=e,this._accessTokenFactory=t,this._logger=n,this._pollAbort=new Ue,this._logMessageContent=r,this._withCredentials=o,this._headers=i,this._running=!1,this.onreceive=null,this.onclose=null}get pollAborted(){return this._pollAbort.aborted}async connect(e,t){if(Ne.isRequired(e,"url"),Ne.isRequired(t,"transferFormat"),Ne.isIn(t,Ce,"transferFormat"),this._url=e,this._logger.log(Ee.Trace,"(LongPolling transport) Connecting."),t===Ce.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]=Fe(),o={[n]:r,...this._headers},i={abortSignal:this._pollAbort.signal,headers:o,timeout:1e5,withCredentials:this._withCredentials};t===Ce.Binary&&(i.responseType="arraybuffer");const s=await this._getAccessToken();this._updateHeaderToken(i,s);const a=`${e}&_=${Date.now()}`;this._logger.log(Ee.Trace,`(LongPolling transport) polling: ${a}.`);const c=await this._httpClient.get(a,i);200!==c.statusCode?(this._logger.log(Ee.Error,`(LongPolling transport) Unexpected response code: ${c.statusCode}.`),this._closeError=new ye(c.statusText||"",c.statusCode),this._running=!1):this._running=!0,this._receiving=this._poll(this._url,i)}async _getAccessToken(){return this._accessTokenFactory?await this._accessTokenFactory():null}_updateHeaderToken(e,t){e.headers||(e.headers={}),t?e.headers[Pe.Authorization]=`Bearer ${t}`:e.headers[Pe.Authorization]&&delete e.headers[Pe.Authorization]}async _poll(e,t){try{for(;this._running;){const n=await this._getAccessToken();this._updateHeaderToken(t,n);try{const n=`${e}&_=${Date.now()}`;this._logger.log(Ee.Trace,`(LongPolling transport) polling: ${n}.`);const r=await this._httpClient.get(n,t);204===r.statusCode?(this._logger.log(Ee.Information,"(LongPolling transport) Poll terminated by server."),this._running=!1):200!==r.statusCode?(this._logger.log(Ee.Error,`(LongPolling transport) Unexpected response code: ${r.statusCode}.`),this._closeError=new ye(r.statusText||"",r.statusCode),this._running=!1):r.content?(this._logger.log(Ee.Trace,`(LongPolling transport) data received. ${$e(r.content,this._logMessageContent)}.`),this.onreceive&&this.onreceive(r.content)):this._logger.log(Ee.Trace,"(LongPolling transport) Poll timed out, reissuing.")}catch(e){this._running?e instanceof we?this._logger.log(Ee.Trace,"(LongPolling transport) Poll timed out, reissuing."):(this._closeError=e,this._running=!1):this._logger.log(Ee.Trace,`(LongPolling transport) Poll errored after shutdown: ${e.message}`)}}}finally{this._logger.log(Ee.Trace,"(LongPolling transport) Polling complete."),this.pollAborted||this._raiseOnClose()}}async send(e){return this._running?Me(this._logger,"LongPolling",this._httpClient,this._url,this._accessTokenFactory,e,this._logMessageContent,this._withCredentials,this._headers):Promise.reject(new Error("Cannot send until the transport is connected"))}async stop(){this._logger.log(Ee.Trace,"(LongPolling transport) Stopping polling."),this._running=!1,this._pollAbort.abort();try{await this._receiving,this._logger.log(Ee.Trace,`(LongPolling transport) sending DELETE request to ${this._url}.`);const e={},[t,n]=Fe();e[t]=n;const r={headers:{...e,...this._headers},withCredentials:this._withCredentials},o=await this._getAccessToken();this._updateHeaderToken(r,o),await this._httpClient.delete(this._url,r),this._logger.log(Ee.Trace,"(LongPolling transport) DELETE request sent.")}finally{this._logger.log(Ee.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(Ee.Trace,e),this.onclose(this._closeError)}}}class Je{constructor(e,t,n,r,o,i,s){this._httpClient=e,this._accessTokenFactory=t,this._logger=n,this._logMessageContent=r,this._withCredentials=i,this._eventSourceConstructor=o,this._headers=s,this.onreceive=null,this.onclose=null}async connect(e,t){if(Ne.isRequired(e,"url"),Ne.isRequired(t,"transferFormat"),Ne.isIn(t,Ce,"transferFormat"),this._logger.log(Ee.Trace,"(SSE transport) Connecting."),this._url=e,this._accessTokenFactory){const t=await this._accessTokenFactory();t&&(e+=(e.indexOf("?")<0?"?":"&")+`access_token=${encodeURIComponent(t)}`)}return new Promise(((n,r)=>{let o,i=!1;if(t===Ce.Text){if(Be.isBrowser||Be.isWebWorker)o=new this._eventSourceConstructor(e,{withCredentials:this._withCredentials});else{const t=this._httpClient.getCookieString(e),n={};n.Cookie=t;const[r,i]=Fe();n[r]=i,o=new this._eventSourceConstructor(e,{withCredentials:this._withCredentials,headers:{...n,...this._headers}})}try{o.onmessage=e=>{if(this.onreceive)try{this._logger.log(Ee.Trace,`(SSE transport) data received. ${$e(e.data,this._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(Ee.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?Me(this._logger,"SSE",this._httpClient,this._url,this._accessTokenFactory,e,this._logMessageContent,this._withCredentials,this._headers):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 Ke{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){if(Ne.isRequired(e,"url"),Ne.isRequired(t,"transferFormat"),Ne.isIn(t,Ce,"transferFormat"),this._logger.log(Ee.Trace,"(WebSockets transport) Connecting."),this._accessTokenFactory){const t=await this._accessTokenFactory();t&&(e+=(e.indexOf("?")<0?"?":"&")+`access_token=${encodeURIComponent(t)}`)}return new Promise(((n,r)=>{let o;e=e.replace(/^http/,"ws"),this._httpClient.getCookieString(e);let i=!1;o||(o=new this._webSocketConstructor(e)),t===Ce.Binary&&(o.binaryType="arraybuffer"),o.onopen=t=>{this._logger.log(Ee.Information,`WebSocket connected to ${e}.`),this._webSocket=o,i=!0,n()},o.onerror=e=>{let t=null;t="undefined"!=typeof ErrorEvent&&e instanceof ErrorEvent?e.error:"There was an error with the transport",this._logger.log(Ee.Information,`(WebSockets transport) ${t}.`)},o.onmessage=e=>{if(this._logger.log(Ee.Trace,`(WebSockets transport) data received. ${$e(e.data,this._logMessageContent)}.`),this.onreceive)try{this.onreceive(e.data)}catch(e){return void this._close(e)}},o.onclose=e=>{if(i)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(Ee.Trace,`(WebSockets transport) sending data. ${$e(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(Ee.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 Ve{constructor(e,t={}){var n;if(this._stopPromiseResolver=()=>{},this.features={},this._negotiateVersion=1,Ne.isRequired(e,"url"),this._logger=void 0===(n=t.logger)?new He(Ee.Information):null===n?Ae.instance:void 0!==n.log?n:new He(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,"undefined"==typeof WebSocket||t.WebSocket||(t.WebSocket=WebSocket),"undefined"==typeof EventSource||t.EventSource||(t.EventSource=EventSource),this._httpClient=t.httpClient||new Re(this._logger),this._connectionState="Disconnected",this._connectionStarted=!1,this._options=t,this.onreceive=null,this.onclose=null}async start(e){if(e=e||Ce.Binary,Ne.isIn(e,Ce,"transferFormat"),this._logger.log(Ee.Debug,`Starting connection with transfer format '${Ce[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(Ee.Error,e),await this._stopPromise,Promise.reject(new Error(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(Ee.Error,e),Promise.reject(new Error(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 Xe(this.transport)),this._sendQueue.send(e))}async stop(e){return"Disconnected"===this._connectionState?(this._logger.log(Ee.Debug,`Call to HttpConnection.stop(${e}) ignored because the connection is already in the disconnected state.`),Promise.resolve()):"Disconnecting"===this._connectionState?(this._logger.log(Ee.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(Ee.Error,`HttpConnection.transport.stop() threw error '${e}'.`),this._stopConnection()}this.transport=void 0}else this._logger.log(Ee.Debug,"HttpConnection.transport is undefined in HttpConnection.stop() because start() failed.")}async _startInternal(e){let t=this.baseUrl;this._accessTokenFactory=this._options.accessTokenFactory;try{if(this._options.skipNegotiation){if(this._options.transport!==Se.WebSockets)throw new Error("Negotiation can only be skipped when using the WebSocket transport directly.");this.transport=this._constructTransport(Se.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 Error("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}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 qe&&(this.features.inherentKeepAlive=!0),"Connecting"===this._connectionState&&(this._logger.log(Ee.Debug,"The HttpConnection connected successfully."),this._connectionState="Connected")}catch(e){return this._logger.log(Ee.Error,"Failed to start the connection: "+e),this._connectionState="Disconnected",this.transport=void 0,this._stopPromiseResolver(),Promise.reject(e)}}async _getNegotiationResponse(e){const t={};if(this._accessTokenFactory){const e=await this._accessTokenFactory();e&&(t[Pe.Authorization]=`Bearer ${e}`)}const[n,r]=Fe();t[n]=r;const o=this._resolveNegotiateUrl(e);this._logger.log(Ee.Debug,`Sending negotiation request: ${o}.`);try{const e=await this._httpClient.post(o,{content:"",headers:{...t,...this._options.headers},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 ye&&404===e.statusCode&&(t+=" Either this is not a SignalR endpoint or there is a proxy blocking the connection."),this._logger.log(Ee.Error,t),Promise.reject(new Error(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(Ee.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: ${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(Ee.Error,`Failed to start the transport '${n.transport}': ${e}`),a=void 0,i.push(`${n.transport} failed: ${e}`),"Connecting"!==this._connectionState){const e="Failed to select transport before stop() was called.";return this._logger.log(Ee.Debug,e),Promise.reject(new Error(e))}}}}return i.length>0?Promise.reject(new Error(`Unable to connect to the server with any of the available transports. ${i.join(" ")}`)):Promise.reject(new Error("None of the transports supported by the client are supported by the server."))}_constructTransport(e){switch(e){case Se.WebSockets:if(!this._options.WebSocket)throw new Error("'WebSocket' is not supported in your environment.");return new Ke(this._httpClient,this._accessTokenFactory,this._logger,this._options.logMessageContent||!1,this._options.WebSocket,this._options.headers||{});case Se.ServerSentEvents:if(!this._options.EventSource)throw new Error("'EventSource' is not supported in your environment.");return new Je(this._httpClient,this._accessTokenFactory,this._logger,this._options.logMessageContent||!1,this._options.EventSource,this._options.withCredentials,this._options.headers||{});case Se.LongPolling:return new qe(this._httpClient,this._accessTokenFactory,this._logger,this._options.logMessageContent||!1,this._options.withCredentials,this._options.headers||{});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=Se[e.transport];if(null==r)return this._logger.log(Ee.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(Ee.Debug,`Skipping transport '${Se[r]}' because it was disabled by the client.`),new Error(`'${Se[r]}' is disabled by the client.`);if(!(e.transferFormats.map((e=>Ce[e])).indexOf(n)>=0))return this._logger.log(Ee.Debug,`Skipping transport '${Se[r]}' because it does not support the requested transfer format '${Ce[n]}'.`),new Error(`'${Se[r]}' does not support ${Ce[n]}.`);if(r===Se.WebSockets&&!this._options.WebSocket||r===Se.ServerSentEvents&&!this._options.EventSource)return this._logger.log(Ee.Debug,`Skipping transport '${Se[r]}' because it is not supported in your environment.'`),new Error(`'${Se[r]}' is not supported in your environment.`);this._logger.log(Ee.Debug,`Selecting transport '${Se[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(Ee.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(Ee.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(Ee.Error,`Connection disconnected with error '${e}'.`):this._logger.log(Ee.Information,"Connection disconnected."),this._sendQueue&&(this._sendQueue.stop().catch((e=>{this._logger.log(Ee.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(Ee.Error,`HttpConnection.onclose(${e}) threw error '${t}'.`)}}}else this._logger.log(Ee.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(!Be.isBrowser||!window.document)throw new Error(`Cannot resolve '${e}'.`);const t=window.document.createElement("a");return t.href=e,this._logger.log(Ee.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 Xe{constructor(e){this._transport=e,this._buffer=[],this._executing=!0,this._sendBufferedData=new Ye,this._transportResult=new Ye,this._sendLoopPromise=this._sendLoop()}send(e){return this._bufferData(e),this._transportResult||(this._transportResult=new Ye),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 Ye;const e=this._transportResult;this._transportResult=void 0;const t="string"==typeof this._buffer[0]?this._buffer.join(""):Xe._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 Ye{constructor(){this.promise=new Promise(((e,t)=>[this._resolver,this._rejecter]=[e,t]))}resolve(){this._resolver()}reject(e){this._rejecter(e)}}class Ge{static write(e){return`${e}${Ge.RecordSeparator}`}static parse(e){if(e[e.length-1]!==Ge.RecordSeparator)throw new Error("Message is incomplete.");const t=e.split(Ge.RecordSeparator);return t.pop(),t}}Ge.RecordSeparatorCode=30,Ge.RecordSeparator=String.fromCharCode(Ge.RecordSeparatorCode);class Qe{writeHandshakeRequest(e){return Ge.write(JSON.stringify(e))}parseHandshakeResponse(e){let t,n;if(Le(e)){const r=new Uint8Array(e),o=r.indexOf(Ge.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(Ge.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=Ge.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"}(Ie||(Ie={}));class Ze{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 Oe(this,e)}}!function(e){e.Disconnected="Disconnected",e.Connecting="Connecting",e.Connected="Connected",e.Disconnecting="Disconnecting",e.Reconnecting="Reconnecting"}(ke||(ke={}));class et{constructor(e,t,n,r){this._nextKeepAlive=0,Ne.isRequired(e,"connection"),Ne.isRequired(t,"logger"),Ne.isRequired(n,"protocol"),this.serverTimeoutInMilliseconds=3e4,this.keepAliveIntervalInMilliseconds=15e3,this._logger=t,this._protocol=n,this.connection=e,this._reconnectPolicy=r,this._handshakeProtocol=new Qe,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=ke.Disconnected,this._connectionStarted=!1,this._cachedPingMessage=this._protocol.writeMessage({type:Ie.Ping})}static create(e,t,n,r){return new et(e,t,n,r)}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!==ke.Disconnected&&this._connectionState!==ke.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!==ke.Disconnected)return Promise.reject(new Error("Cannot start a HubConnection that is not in the 'Disconnected' state."));this._connectionState=ke.Connecting,this._logger.log(Ee.Debug,"Starting HubConnection.");try{await this._startInternal(),this._connectionState=ke.Connected,this._connectionStarted=!0,this._logger.log(Ee.Debug,"HubConnection connected successfully.")}catch(e){return this._connectionState=ke.Disconnected,this._logger.log(Ee.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(Ee.Debug,"Sending handshake request."),await this._sendMessage(this._handshakeProtocol.writeHandshakeRequest(t)),this._logger.log(Ee.Information,`Using HubProtocol '${this._protocol.name}'.`),this._cleanupTimeout(),this._resetTimeoutPeriod(),this._resetKeepAliveInterval(),await e,this._stopDuringStartError)throw this._stopDuringStartError}catch(e){throw this._logger.log(Ee.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){return this._connectionState===ke.Disconnected?(this._logger.log(Ee.Debug,`Call to HubConnection.stop(${e}) ignored because it is already in the disconnected state.`),Promise.resolve()):this._connectionState===ke.Disconnecting?(this._logger.log(Ee.Debug,`Call to HttpConnection.stop(${e}) ignored because the connection is already in the disconnecting state.`),this._stopPromise):(this._connectionState=ke.Disconnecting,this._logger.log(Ee.Debug,"Stopping HubConnection."),this._reconnectDelayHandle?(this._logger.log(Ee.Debug,"Connection stopped during reconnect delay. Done reconnecting."),clearTimeout(this._reconnectDelayHandle),this._reconnectDelayHandle=void 0,this._completeClose(),Promise.resolve()):(this._cleanupTimeout(),this._cleanupPingTimer(),this._stopDuringStartError=e||new Error("The connection was stopped before the hub handshake could complete."),this.connection.stop(e)))}stream(e,...t){const[n,r]=this._replaceStreamingParams(t),o=this._createStreamInvocation(e,t,r);let i;const s=new Ze;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===Ie.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===Ie.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 Ie.Invocation:this._invokeClientMethod(e);break;case Ie.StreamItem:case Ie.Completion:{const t=this._callbacks[e.invocationId];t&&(e.type===Ie.Completion&&delete this._callbacks[e.invocationId],t(e));break}case Ie.Ping:break;case Ie.Close:{this._logger.log(Ee.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(Ee.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(Ee.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(Ee.Error,e);const n=new Error(e);throw this._handshakeRejecter(n),n}return this._logger.log(Ee.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===ke.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."))}_invokeClientMethod(e){const t=this._methods[e.target.toLowerCase()];if(t){try{t.forEach((t=>t.apply(this,e.arguments)))}catch(t){this._logger.log(Ee.Error,`A callback for the method ${e.target.toLowerCase()} threw error '${t}'.`)}if(e.invocationId){const e="Server requested a response, which is not supported in this version of the client.";this._logger.log(Ee.Error,e),this._stopPromise=this._stopInternal(new Error(e))}}else this._logger.log(Ee.Warning,`No client method with the name '${e.target}' found.`)}_connectionClosed(e){this._logger.log(Ee.Debug,`HubConnection.connectionClosed(${e}) called while in state ${this._connectionState}.`),this._stopDuringStartError=this._stopDuringStartError||e||new Error("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===ke.Disconnecting?this._completeClose(e):this._connectionState===ke.Connected&&this._reconnectPolicy?this._reconnect(e):this._connectionState===ke.Connected&&this._completeClose(e)}_completeClose(e){if(this._connectionStarted){this._connectionState=ke.Disconnected,this._connectionStarted=!1;try{this._closedCallbacks.forEach((t=>t.apply(this,[e])))}catch(t){this._logger.log(Ee.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(Ee.Debug,"Connection not reconnecting because the IRetryPolicy returned null on the first reconnect attempt."),void this._completeClose(e);if(this._connectionState=ke.Reconnecting,e?this._logger.log(Ee.Information,`Connection reconnecting because of error '${e}'.`):this._logger.log(Ee.Information,"Connection reconnecting."),0!==this._reconnectingCallbacks.length){try{this._reconnectingCallbacks.forEach((t=>t.apply(this,[e])))}catch(t){this._logger.log(Ee.Error,`An onreconnecting callback called with error '${e}' threw error '${t}'.`)}if(this._connectionState!==ke.Reconnecting)return void this._logger.log(Ee.Debug,"Connection left the reconnecting state in onreconnecting callback. Done reconnecting.")}for(;null!==o;){if(this._logger.log(Ee.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!==ke.Reconnecting)return void this._logger.log(Ee.Debug,"Connection left the reconnecting state during reconnect delay. Done reconnecting.");try{if(await this._startInternal(),this._connectionState=ke.Connected,this._logger.log(Ee.Information,"HubConnection reconnected successfully."),0!==this._reconnectedCallbacks.length)try{this._reconnectedCallbacks.forEach((e=>e.apply(this,[this.connection.connectionId])))}catch(e){this._logger.log(Ee.Error,`An onreconnected callback called with connectionId '${this.connection.connectionId}; threw error '${e}'.`)}return}catch(e){if(this._logger.log(Ee.Information,`Reconnect attempt failed because of error '${e}'.`),this._connectionState!==ke.Reconnecting)return this._logger.log(Ee.Debug,`Connection moved to the '${this._connectionState}' from the reconnecting state during reconnect attempt. Done reconnecting.`),void(this._connectionState===ke.Disconnecting&&this._completeClose());r=e instanceof Error?e:new Error(e.toString()),o=this._getNextRetryDelay(n++,Date.now()-t,r)}}this._logger.log(Ee.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(Ee.Error,`IRetryPolicy.nextRetryDelayInMilliseconds(${e}, ${t}) threw error '${n}'.`),null}}_cancelCallbacksWithError(e){const t=this._callbacks;this._callbacks={},Object.keys(t).forEach((n=>{(0,t[n])(null,e)}))}_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:Ie.Invocation}:{arguments:t,target:e,type:Ie.Invocation};{const n=this._invocationId;return this._invocationId++,0!==r.length?{arguments:t,invocationId:n.toString(),streamIds:r,target:e,type:Ie.Invocation}:{arguments:t,invocationId:n.toString(),target:e,type:Ie.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 ut=ot?new TextDecoder:null,dt=ot?"undefined"!=typeof process&&"force"!==process.env.TEXT_DECODER?200:0:it,pt=function(e,t){this.type=e,this.data=t};function ft(e,t,n){var r=Math.floor(n/4294967296),o=n;e.setUint32(t,r),e.setUint32(t+4,o)}function gt(e,t){return 4294967296*e.getInt32(t)+e.getUint32(t+4)}var mt={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),ft(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:gt(t,4),nsec:t.getUint32(0)};default:throw new Error("Unrecognized data size for timestamp: "+e.length)}}(e);return new Date(1e3*t.sec+t.nsec/1e6)}},yt=function(){function e(){this.builtInEncoders=[],this.builtInDecoders=[],this.encoders=[],this.decoders=[],this.register(mt)}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 "+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: "+e+" bytes in UTF-8");this.writeU8(219),this.writeU32(e)}},e.prototype.encodeString=function(e){if(e.length>ct){var t=st(e);this.ensureBufferSizeToWrite(5+t),this.writeStringHeader(t),lt(e,this.bytes,this.pos),this.pos+=t}else t=st(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: "+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: "+t);this.writeU8(198),this.writeU32(t)}var n=wt(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: "+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=ht(e,t,n),i=Uint8Array.prototype.slice.call(e,t,t+n);return this.store(i,o),o},e}(),St=(_t=function(e,t){return(_t=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])})(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}_t(e,t),e.prototype=null===t?Object.create(t):(n.prototype=t.prototype,new n)}),Ct=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]1||a(e,t)}))})}function a(e,t){try{(n=o[e](t)).value instanceof kt?Promise.resolve(n.value.v).then(c,l):h(i[0][2],n)}catch(e){h(i[0][3],e)}var n}function c(e){a("next",e)}function l(e){a("throw",e)}function h(e,t){e(t),i.shift(),i.length&&a(i[0][0],i[0][1])}},xt=new DataView(new ArrayBuffer(0)),Dt=new Uint8Array(xt.buffer),Rt=function(){try{xt.getInt8(0)}catch(e){return e.constructor}throw new Error("never reached")}(),Pt=new Rt("Insufficient data"),Ut=4294967295,At=new Et,Nt=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 St(t,e),t}(Error),Bt=function(){function e(e,t,n,r,o,i,s,a){void 0===e&&(e=yt.defaultCodec),void 0===t&&(t=void 0),void 0===n&&(n=Ut),void 0===r&&(r=Ut),void 0===o&&(o=Ut),void 0===i&&(i=Ut),void 0===s&&(s=Ut),void 0===a&&(a=At),this.extensionCodec=e,this.context=t,this.maxStrLength=n,this.maxBinLength=r,this.maxArrayLength=o,this.maxMapLength=i,this.maxExtLength=s,this.keyDecoder=a,this.totalPos=0,this.pos=0,this.view=xt,this.bytes=Dt,this.headByte=-1,this.stack=[]}return e.prototype.reinitializeState=function(){this.totalPos=0,this.headByte=-1,this.stack.length=0},e.prototype.setBuffer=function(e){this.bytes=wt(e),this.view=function(e){if(e instanceof ArrayBuffer)return new DataView(e);var t=wt(e);return new DataView(t.buffer,t.byteOffset,t.byteLength)}(this.bytes),this.pos=0},e.prototype.appendBuffer=function(e){if(-1!==this.headByte||this.hasRemaining()){var t=this.bytes.subarray(this.pos),n=wt(e),r=new Uint8Array(t.length+n.length);r.set(t),r.set(n,t.length),this.setBuffer(r)}else this.setBuffer(e)},e.prototype.hasRemaining=function(e){return void 0===e&&(e=1),this.view.byteLength-this.pos>=e},e.prototype.createExtraByteError=function(e){var t=this.view,n=this.pos;return new RangeError("Extra "+(t.byteLength-n)+" of "+t.byteLength+" byte(s) found at buffer["+e+"]")},e.prototype.decode=function(e){this.reinitializeState(),this.setBuffer(e);var t=this.doDecodeSync();if(this.hasRemaining())throw this.createExtraByteError(this.pos);return t},e.prototype.decodeMulti=function(e){return Ct(this,(function(t){switch(t.label){case 0:this.reinitializeState(),this.setBuffer(e),t.label=1;case 1:return this.hasRemaining()?[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,u,d;return Ct(this,(function(p){switch(p.label){case 0:i=!1,p.label=1;case 1:p.trys.push([1,6,7,12]),t=It(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 Rt))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())throw this.createExtraByteError(this.totalPos);return[2,s]}throw h=(l=this).headByte,u=l.pos,d=l.totalPos,new RangeError("Insufficient data in parsing "+bt(h)+" at "+d+" ("+u+" 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 Tt(this,arguments,(function(){var n,r,o,i,s,a,c,l,h;return Ct(this,(function(u){switch(u.label){case 0:n=t,r=-1,u.label=1;case 1:u.trys.push([1,13,14,19]),o=It(e),u.label=2;case 2:return[4,kt(o.next())];case 3:if((i=u.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()),u.label=4;case 4:u.trys.push([4,9,,10]),u.label=5;case 5:return[4,kt(this.doDecodeSync())];case 6:return[4,u.sent()];case 7:return u.sent(),0==--r?[3,8]:[3,5];case 8:return[3,10];case 9:if(!((a=u.sent())instanceof Rt))throw a;return[3,10];case 10:this.totalPos+=this.pos,u.label=11;case 11:return[3,2];case 12:return[3,19];case 13:return c=u.sent(),l={error:c},[3,19];case 14:return u.trys.push([14,,17,18]),i&&!i.done&&(h=o.return)?[4,kt(h.call(o))]:[3,16];case 15:u.sent(),u.label=16;case 16:return[3,18];case 17:if(l)throw l.error;return[7];case 18:return[7];case 19:return[2]}}))}))},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 Nt("Unrecognized type byte: "+bt(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 Nt("The type of key must be string or number but "+typeof t);if("__proto__"===t)throw new Nt("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 Nt("Unrecognized array type byte: "+bt(e))}},e.prototype.pushMapState=function(e){if(e>this.maxMapLength)throw new Nt("Max length exceeded: map length ("+e+") > maxMapLengthLength ("+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 Nt("Max length exceeded: array length ("+e+") > maxArrayLength ("+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 Nt("Max length exceeded: UTF-8 byte length ("+e+") > maxStrLength ("+this.maxStrLength+")");if(this.bytes.byteLengthdt?function(e,t,n){var r=e.subarray(t,t+n);return ut.decode(r)}(this.bytes,o,e):ht(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 Nt("Max length exceeded: bin length ("+e+") > maxBinLength ("+this.maxBinLength+")");if(!this.hasRemaining(e+t))throw Pt;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 Nt("Max length exceeded: ext length ("+e+") > maxExtLength ("+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=gt(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 $t{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 Lt=new Uint8Array([145,Ie.Ping]);class Mt{constructor(e){this.name="messagepack",this.version=1,this.transferFormat=Ce.Binary,this._errorResult=1,this._voidResult=2,this._nonVoidResult=3,e=e||{},this._encoder=new vt(e.extensionCodec,e.context,e.maxDepth,e.initialBufferSize,e.sortKeys,e.forceFloat32,e.ignoreUndefined,e.forceIntegerToFloat),this._decoder=new Bt(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=Ae.instance);const r=$t.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 Ie.Invocation:return this._writeInvocation(e);case Ie.StreamInvocation:return this._writeStreamInvocation(e);case Ie.StreamItem:return this._writeStreamItem(e);case Ie.Completion:return this._writeCompletion(e);case Ie.Ping:return $t.write(Lt);case Ie.CancelInvocation:return this._writeCancelInvocation(e);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 Ie.Invocation:return this._createInvocationMessage(this._readHeaders(n),n);case Ie.StreamItem:return this._createStreamItemMessage(this._readHeaders(n),n);case Ie.Completion:return this._createCompletionMessage(this._readHeaders(n),n);case Ie.Ping:return this._createPingMessage(n);case Ie.Close:return this._createCloseMessage(n);default:return t.log(Ee.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:Ie.Close}}_createPingMessage(e){if(e.length<1)throw new Error("Invalid payload for Ping message.");return{type:Ie.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:Ie.Invocation}:{arguments:t[4],headers:e,streamIds:[],target:t[3],type:Ie.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:Ie.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:Ie.Completion}}_writeInvocation(e){let t;return t=e.streamIds?this._encoder.encode([Ie.Invocation,e.headers||{},e.invocationId||null,e.target,e.arguments,e.streamIds]):this._encoder.encode([Ie.Invocation,e.headers||{},e.invocationId||null,e.target,e.arguments]),$t.write(t.slice())}_writeStreamInvocation(e){let t;return t=e.streamIds?this._encoder.encode([Ie.StreamInvocation,e.headers||{},e.invocationId,e.target,e.arguments,e.streamIds]):this._encoder.encode([Ie.StreamInvocation,e.headers||{},e.invocationId,e.target,e.arguments]),$t.write(t.slice())}_writeStreamItem(e){const t=this._encoder.encode([Ie.StreamItem,e.headers||{},e.invocationId,e.item]);return $t.write(t.slice())}_writeCompletion(e){const t=e.error?this._errorResult:e.result?this._nonVoidResult:this._voidResult;let n;switch(t){case this._errorResult:n=this._encoder.encode([Ie.Completion,e.headers||{},e.invocationId,t,e.error]);break;case this._voidResult:n=this._encoder.encode([Ie.Completion,e.headers||{},e.invocationId,t]);break;case this._nonVoidResult:n=this._encoder.encode([Ie.Completion,e.headers||{},e.invocationId,t,e.result])}return $t.write(n.slice())}_writeCancelInvocation(e){const t=this._encoder.encode([Ie.CancelInvocation,e.headers||{},e.invocationId]);return $t.write(t.slice())}_readHeaders(e){const t=e[1];if("object"!=typeof t)throw new Error("Invalid headers.");return t}}let Ot=!1;const Ht="function"==typeof TextDecoder?new TextDecoder("utf-8"):null,Ft=Ht?Ht.decode.bind(Ht):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("")},jt=Math.pow(2,32),Wt=Math.pow(2,21)-1;function zt(e,t){return e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24}function qt(e,t){return e[t]+(e[t+1]<<8)+(e[t+2]<<16)+(e[t+3]<<24>>>0)}function Jt(e,t){const n=qt(e,t+4);if(n>Wt)throw new Error(`Cannot read uint64 with high order part ${n}, because the result would exceed Number.MAX_SAFE_INTEGER.`);return n*jt+qt(e,t)}class Kt{constructor(e){this.batchData=e;const t=new Gt(e);this.arrayRangeReader=new Qt(e),this.arrayBuilderSegmentReader=new Zt(e),this.diffReader=new Vt(e),this.editReader=new Xt(e,t),this.frameReader=new Yt(e,t)}updatedComponents(){return zt(this.batchData,this.batchData.length-20)}referenceFrames(){return zt(this.batchData,this.batchData.length-16)}disposedComponentIds(){return zt(this.batchData,this.batchData.length-12)}disposedEventHandlerIds(){return zt(this.batchData,this.batchData.length-8)}updatedComponentsEntry(e,t){const n=e+4*t;return zt(this.batchData,n)}referenceFramesEntry(e,t){return e+20*t}disposedComponentIdsEntry(e,t){const n=e+4*t;return zt(this.batchData,n)}disposedEventHandlerIdsEntry(e,t){const n=e+8*t;return Jt(this.batchData,n)}}class Vt{constructor(e){this.batchDataUint8=e}componentId(e){return zt(this.batchDataUint8,e)}edits(e){return e+4}editsEntry(e,t){return e+16*t}}class Xt{constructor(e,t){this.batchDataUint8=e,this.stringReader=t}editType(e){return zt(this.batchDataUint8,e)}siblingIndex(e){return zt(this.batchDataUint8,e+4)}newTreeIndex(e){return zt(this.batchDataUint8,e+8)}moveToSiblingIndex(e){return zt(this.batchDataUint8,e+8)}removedAttributeName(e){const t=zt(this.batchDataUint8,e+12);return this.stringReader.readString(t)}}class Yt{constructor(e,t){this.batchDataUint8=e,this.stringReader=t}frameType(e){return zt(this.batchDataUint8,e)}subtreeLength(e){return zt(this.batchDataUint8,e+4)}elementReferenceCaptureId(e){const t=zt(this.batchDataUint8,e+4);return this.stringReader.readString(t)}componentId(e){return zt(this.batchDataUint8,e+8)}elementName(e){const t=zt(this.batchDataUint8,e+8);return this.stringReader.readString(t)}textContent(e){const t=zt(this.batchDataUint8,e+4);return this.stringReader.readString(t)}markupContent(e){const t=zt(this.batchDataUint8,e+4);return this.stringReader.readString(t)}attributeName(e){const t=zt(this.batchDataUint8,e+4);return this.stringReader.readString(t)}attributeValue(e){const t=zt(this.batchDataUint8,e+8);return this.stringReader.readString(t)}attributeEventHandlerId(e){return Jt(this.batchDataUint8,e+12)}}class Gt{constructor(e){this.batchDataUint8=e,this.stringTableStartIndex=zt(e,e.length-4)}readString(e){if(-1===e)return null;{const n=zt(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(en.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(en.Debug,`Waiting for batch ${this.nextBatchId}. Batch ${e} not processed.`);try{this.nextBatchId++,this.logger.log(en.Debug,`Applying batch ${e}.`),function(e,t){const n=Q[e];if(!n)throw new Error(`There is no browser renderer with ID ${e}.`);const r=t.arrayRangeReader,o=t.updatedComponents(),i=r.values(o),s=r.count(o),a=t.referenceFrames(),c=r.values(a),l=t.diffReader;for(let e=0;e=this.minLevel){const n=`[${(new Date).toISOString()}] ${en[e]}: ${t}`;switch(e){case en.Critical:case en.Error:console.error(n);break;case en.Warning:console.warn(n);break;case en.Information:console.info(n);break;default:console.log(n)}}}}class on{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!==ke.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!==ke.Connected)return!1;const t=await e.invoke("StartCircuit",re.getBaseURI(),re.getLocationHref(),JSON.stringify(this.components.map((e=>e.toRecord()))),this.applicationState||"");return!!t&&(this.initialize(t),!0)}resolveElement(e){const t=Number.parseInt(e);if(Number.isNaN(t))throw new Error(`Invalid sequence number '${e}'.`);return function(e,t){if(!e.parentNode)throw new Error(`Comment not connected to the DOM ${e.textContent}`);const n=e.parentNode,r=k(n,!0),o=A(r);return Array.from(n.childNodes).forEach((e=>o.push(e))),e[C]=r,t&&(e[I]=t,k(t)),k(e)}(this.components[t].start,this.components[t].end)}}const sn={configureSignalR:e=>{},logLevel:en.Warning,reconnectionOptions:{maxRetries:8,retryIntervalMilliseconds:2e4,dialogId:"components-reconnect-modal"}};class an{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.modal.innerHTML='

Alternatively, reload

',this.message=this.modal.querySelector("h5"),this.button=this.modal.querySelector("button"),this.reloadParagraph=this.modal.querySelector("p"),this.loader=this.getLoader(),this.message.after(this.loader),this.button.addEventListener("click",(async()=>{this.show();try{await(null==fe?void 0:fe.reconnect)()||this.rejected()}catch(e){this.logger.log(en.Error,e),this.failed()}})),this.reloadParagraph.querySelector("a").addEventListener("click",(()=>location.reload()))}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",this.message.innerHTML="Reconnection failed. Try reloading the page if you're unable to reconnect.",this.message.querySelector("a").addEventListener("click",(()=>location.reload()))}rejected(){this.button.style.display="none",this.reloadParagraph.style.display="none",this.loader.style.display="none",this.message.innerHTML="Could not reconnect to the server. Reload the page to restore functionality.",this.message.querySelector("a").addEventListener("click",(()=>location.reload()))}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 cn{constructor(e,t,n){this.dialog=e,this.maxRetries=t,this.document=n,this.document=n;const r=this.document.getElementById(cn.MaxRetriesId);r&&(r.innerText=this.maxRetries.toString())}show(){this.removeClasses(),this.dialog.classList.add(cn.ShowClassName)}update(e){const t=this.document.getElementById(cn.CurrentAttemptId);t&&(t.innerText=e.toString())}hide(){this.removeClasses(),this.dialog.classList.add(cn.HideClassName)}failed(){this.removeClasses(),this.dialog.classList.add(cn.FailedClassName)}rejected(){this.removeClasses(),this.dialog.classList.add(cn.RejectedClassName)}removeClasses(){this.dialog.classList.remove(cn.ShowClassName,cn.HideClassName,cn.FailedClassName,cn.RejectedClassName)}}cn.ShowClassName="components-reconnect-show",cn.HideClassName="components-reconnect-hide",cn.FailedClassName="components-reconnect-failed",cn.RejectedClassName="components-reconnect-rejected",cn.MaxRetriesId="components-reconnect-max-retries",cn.CurrentAttemptId="components-reconnect-current-attempt";class ln{constructor(e,t,n){this._currentReconnectionProcess=null,this._logger=e,this._reconnectionDisplay=t,this._reconnectCallback=n||(()=>fe.reconnect())}onConnectionDown(e,t){if(!this._reconnectionDisplay){const t=document.getElementById(e.dialogId);this._reconnectionDisplay=t?new cn(t,e.maxRetries,document):new an(e.dialogId,e.maxRetries,document,this._logger)}this._currentReconnectionProcess||(this._currentReconnectionProcess=new hn(e,this._logger,this._reconnectCallback,this._reconnectionDisplay))}onConnectionUp(){this._currentReconnectionProcess&&(this._currentReconnectionProcess.dispose(),this._currentReconnectionProcess=null)}}class hn{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;thn.MaximumFirstRetryInterval?hn.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(en.Error,e)}}this.reconnectDisplay.failed()}delay(e){return new Promise((t=>setTimeout(t,e)))}}hn.MaximumFirstRetryInterval=3e3;const un=/^\s*Blazor-Component-State:(?[a-zA-Z0-9\+\/=]+)$/;function dn(e){var t;if(e.nodeType===Node.COMMENT_NODE){const n=e.textContent||"",r=un.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 gn(e,t){const n=e.currentElement;if(n&&n.nodeType===Node.COMMENT_NODE&&n.textContent){const r=fn.exec(n.textContent),o=r&&r.groups&&r.groups.descriptor;if(!o)return;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;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.");if(c){const e=mn(c,n);if(!e)throw new Error(`Could not find an end component comment for '${t}'`);return{type:r,assembly:o,typeName:i,parameterDefinitions:s&&atob(s),parameterValues:a&&atob(a),start:t,prerenderId:c,end:e}}return{type:r,assembly:o,typeName:i,parameterDefinitions:s&&atob(s),parameterValues:a&&atob(a),start:t}}}(r,n,e);case"server":return function(e,t,n){const{type:r,descriptor:o,sequence:i,prerenderId:s}=e;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)}'`);if(s){const e=mn(s,n);if(!e)throw new Error(`Could not find an end component comment for '${t}'`);return{type:r,sequence:i,descriptor:o,start:t,prerenderId:s,end:e}}return{type:r,sequence:i,descriptor:o,start:t}}}(r,n,e)}}catch(e){throw new Error(`Found malformed component comment at ${n.textContent}`)}}}function mn(e,t){for(;t.next()&&t.currentElement;){const n=t.currentElement;if(n.nodeType!==Node.COMMENT_NODE)continue;if(!n.textContent)continue;const r=fn.exec(n.textContent),o=r&&r[1];if(o)return yn(o,e),n}}function yn(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 wn{constructor(e){this.childNodes=e,this.currentIndex=-1,this.length=e.length}next(){return this.currentIndex++,this.currentIndexe.sequence-t.sequence))}(e)}(document),o=dn(document),i=new on(r,o||""),s=await Tn(t,n,i);if(!await i.startCircuit(s))return void n.log(en.Error,"Failed to start the circuit.");let a=!1;const c=()=>{if(!a){const e=new FormData,t=i.circuitId;e.append("circuitId",t),a=navigator.sendBeacon("_blazor/disconnect",e)}};fe.disconnect=c,window.addEventListener("unload",c,{capture:!1,once:!0}),fe.reconnect=async e=>{if(Cn)return!1;const r=e||await Tn(t,n,i);return await i.reconnect(r)?(t.reconnectionHandler.onConnectionUp(),!0):(n.log(en.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)},n.log(en.Information,"Blazor server-side application started.")}async function Tn(t,n,r){const i=new Mt;i.name="blazorpack";const s=(new rt).withUrl("_blazor").withHubProtocol(i);t.configureSignalR(s);const a=s.build();o=(e,t)=>{a.send("DispatchBrowserEvent",JSON.stringify(e),JSON.stringify(t))},fe._internal.navigationManager.listenForNavigationEvents(((e,t)=>a.send("OnLocationChanged",e,t))),a.on("JS.AttachComponent",((e,t)=>function(e,t,n){let r=Q[0];r||(r=Q[0]=new V(0)),r.attachRootComponentToLogicalElement(n,t)}(0,r.resolveElement(t),e))),a.on("JS.BeginInvokeJS",e.jsCallDispatcher.beginInvokeJSFromDotNet),a.on("JS.EndInvokeDotNet",e.jsCallDispatcher.endInvokeDotNetFromJS),a.on("JS.ReceiveByteArray",e.jsCallDispatcher.receiveByteArray);const c=tn.getOrCreate(n);a.on("JS.RenderBatch",((e,t)=>{n.log(en.Debug,`Received render batch with id ${e} and ${t.byteLength} bytes.`),c.processBatch(e,t,a)})),a.onclose((e=>!Cn&&t.reconnectionHandler.onConnectionDown(t.reconnectionOptions,e))),a.on("JS.Error",(e=>{Cn=!0,xn(a,e,n),async function(){let e=document.querySelector("#blazor-error-ui");e&&(e.style.display="block"),Ot||(Ot=!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()}})))}()})),fe._internal.forceCloseConnection=()=>a.stop(),fe._internal.sendJSDataStream=(e,t,n)=>function(e,t,n,r){setTimeout((async()=>{let o=5,i=(new Date).valueOf();try{let s=0;for(;s1)await e.send("ReceiveJSDataChunk",n,c,null);else{if(!await e.invoke("ReceiveJSDataChunk",n,c,null))break;const t=(new Date).valueOf(),r=t-i;i=t,o=Math.max(1,Math.round(500/Math.max(1,r)))}s+=a}}catch(t){await e.send("ReceiveJSDataChunk",n,null,t.toString())}}),0)}(a,e,t,n);try{await a.start()}catch(e){xn(a,e,n)}return e.attachDispatcher({beginInvokeDotNetFromJS:(e,t,n,r,o)=>{a.send("BeginInvokeDotNetFromJS",e?e.toString():null,t,n,r||0,o)},endInvokeJSFromDotNet:(e,t,n)=>{a.send("EndInvokeJSFromDotNet",e,t,n)},sendByteArray:(e,t)=>{a.send("ReceiveByteArray",e,t)}}),a}function xn(e,t,n){n.log(en.Error,t),e&&e.stop()}fe.start=kn,document&&document.currentScript&&"false"!==document.currentScript.getAttribute("autostart")&&kn()})(); \ No newline at end of file +(()=>{"use strict";var e,t,n;!function(e){window.DotNet=e;const t=[],n=new Map;class r{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 o="__jsObjectId",i={},s={0:new r(window)};s[0]._cachedFunctions.set("import",(e=>("string"==typeof e&&e.startsWith("./")&&(e=document.baseURI+e.substr(2)),import(e))));let a,c=1,l=1,h=null;function u(e){t.push(e)}function d(e){if(e&&"object"==typeof e){s[l]=new r(e);const t={[o]:l};return l++,t}throw new Error(`Cannot create a JSObjectReference from the value '${e}'.`)}function p(e){if(!(e.buffer instanceof ArrayBuffer))throw new Error(`Cannot create a JSStreamReference from the value '${e}' as it is not a valid ArrayBuffer.`);if(void 0===e.byteLength)throw new Error(`Cannot create a JSStreamReference from the value '${e}' as it doesn't have a byteLength.`);const t={__jsStreamReferenceLength:e.byteLength};try{const n=d(e);t.__jsObjectId=n.__jsObjectId}catch{throw new Error(`Cannot create a JSStreamReference from the value '${e}'.`)}return t}function f(e){return e?JSON.parse(e,((e,n)=>t.reduce(((t,n)=>n(e,t)),n))):null}function g(e,t,n,r){const o=y();if(o.invokeDotNetFromJS){const i=k(r),s=o.invokeDotNetFromJS(e,t,n,i);return s?f(s):null}throw new Error("The current dispatcher does not support synchronous calls from JS to .NET. Use invokeMethodAsync instead.")}function m(e,t,n,r){if(e&&n)throw new Error(`For instance method calls, assemblyName should be null. Received '${e}'.`);const o=c++,s=new Promise(((e,t)=>{i[o]={resolve:e,reject:t}}));try{const i=k(r);y().beginInvokeDotNetFromJS(o,e,t,n,i)}catch(e){w(o,!1,e)}return s}function y(){if(null!==h)return h;throw new Error("No .NET call dispatcher has been set.")}function w(e,t,n){if(!i.hasOwnProperty(e))throw new Error(`There is no pending async call with ID ${e}.`);const r=i[e];delete i[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){let n=s[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 s[e]}e.attachDispatcher=function(e){h=e},e.attachReviver=u,e.invokeMethod=function(e,t,...n){return g(e,t,null,n)},e.invokeMethodAsync=function(e,t,...n){return m(e,t,null,n)},e.createJSObjectReference=d,e.createJSStreamReference=p,e.disposeJSObjectReference=function(e){const t=e&&e.__jsObjectId;"number"==typeof t&&_(t)},function(e){e[e.Default=0]="Default",e[e.JSObjectReference=1]="JSObjectReference",e[e.JSStreamReference=2]="JSStreamReference"}(a=e.JSCallResultType||(e.JSCallResultType={})),e.jsCallDispatcher={findJSFunction:b,disposeJSObjectReferenceById:_,invokeJSFromDotNet:(e,t,n,r)=>{const o=C(b(e,r).apply(null,f(t)),n);return null==o?null:k(o)},beginInvokeJSFromDotNet:(e,t,n,r,o)=>{const i=new Promise((e=>{e(b(t,o).apply(null,f(n)))}));e&&i.then((t=>y().endInvokeJSFromDotNet(e,!0,k([e,!0,C(t,r)]))),(t=>y().endInvokeJSFromDotNet(e,!1,JSON.stringify([e,!1,v(t)]))))},endInvokeDotNetFromJS:(e,t,n)=>{const r=t?f(n):new Error(n);w(parseInt(e),t,r)},receiveByteArray:(e,t)=>{n.set(e,t)}};class E{constructor(e){this._id=e}invokeMethod(e,...t){return g(null,e,this._id,t)}invokeMethodAsync(e,...t){return m(null,e,this._id,t)}dispose(){m(null,"__Dispose",this._id,null).catch((e=>console.error(e)))}serializeAsArg(){return{__dotNetObject:this._id}}}const S="__byte[]";function C(e,t){switch(t){case a.Default:return e;case a.JSObjectReference:return d(e);case a.JSStreamReference:return p(e);default:throw new Error(`Invalid JS call result type '${t}'.`)}}u((function(e,t){if(t&&"object"==typeof t){if(t.hasOwnProperty("__dotNetObject"))return new E(t.__dotNetObject);if(t.hasOwnProperty(o)){const e=t.__jsObjectId,n=s[e];if(n)return n.getWrappedObject();throw new Error(`JS object instance with Id '${e}' does not exist. It may have been disposed.`)}if(t.hasOwnProperty(S)){const e=t["__byte[]"],r=n.get(e);if(void 0===r)throw new Error(`Byte array index '${e}' does not exist.`);return r}}return t}));let I=0;function k(e){return I=0,JSON.stringify(e,T)}function T(e,t){if(t instanceof E)return t.serializeAsArg();if(t instanceof Uint8Array){h.sendByteArray(I,t);const e={[S]:I};return I++,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"}(n||(n={}));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}}let o;function i(e,t){if(!o)throw new Error("eventDispatcher not initialized. Call 'setEventDispatcher' to configure it.");o(e,t)}const s=new Map,a=new Map,c={createEventArgs:()=>({})},l=[];function h(e){return s.get(e)}function u(e){const t=s.get(e);return(null==t?void 0:t.browserEventName)||e}function d(e,t){e.forEach((e=>s.set(e,t)))}function p(e){const t=[];for(let n=0;n{return{...f(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}}),d(["focus","blur","focusin","focusout"],c),d(["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};var t}}),d(["contextmenu","click","mouseover","mouseout","mousemove","mousedown","mouseup","dblclick"],{createEventArgs:e=>f(e)}),d(["error"],{createEventArgs:e=>{return{message:(t=e).message,filename:t.filename,lineno:t.lineno,colno:t.colno};var t}}),d(["loadstart","timeout","abort","load","loadend","progress"],{createEventArgs:e=>{return{lengthComputable:(t=e).lengthComputable,loaded:t.loaded,total:t.total};var t}}),d(["touchcancel","touchend","touchmove","touchenter","touchleave","touchstart"],{createEventArgs:e=>{return{detail:(t=e).detail,touches:p(t.touches),targetTouches:p(t.targetTouches),changedTouches:p(t.changedTouches),ctrlKey:t.ctrlKey,shiftKey:t.shiftKey,altKey:t.altKey,metaKey:t.metaKey,type:t.type};var t}}),d(["gotpointercapture","lostpointercapture","pointercancel","pointerdown","pointerenter","pointerleave","pointermove","pointerout","pointerover","pointerup"],{createEventArgs:e=>{return{...f(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}}),d(["wheel","mousewheel"],{createEventArgs:e=>{return{...f(t=e),deltaX:t.deltaX,deltaY:t.deltaY,deltaZ:t.deltaZ,deltaMode:t.deltaMode};var t}}),d(["toggle"],c);const g=["date","datetime-local","month","time","week"],m=E(["abort","blur","change","error","focus","load","loadend","loadstart","mouseenter","mouseleave","progress","reset","scroll","submit","unload","toggle","DOMNodeInsertedIntoDocument","DOMNodeRemovedFromDocument"]),y={submit:!0},w=E(["click","dblclick","mousedown","mousemove","mouseup"]);class v{constructor(e){this.browserRendererId=e,this.afterClickCallbacks=[];const t=++v.nextEventDelegatorId;this.eventsCollectionKey=`_blazorEvents_${t}`,this.eventInfoStore=new b(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,a.get(n));var n;t&&t.forEach((t=>this.dispatchGlobalEventToAllElements(t,e))),"click"===e.type&&this.afterClickCallbacks.forEach((t=>t(e)))}dispatchGlobalEventToAllElements(e,t){let n=t.target,o=null,s=!1;const a=m.hasOwnProperty(e);let c=!1;for(;n;){const d=this.getEventHandlerInfosForElement(n,!1);if(d){const a=d.getHandler(e);if(a&&(l=n,u=t.type,!((l instanceof HTMLButtonElement||l instanceof HTMLInputElement||l instanceof HTMLTextAreaElement||l instanceof HTMLSelectElement)&&w.hasOwnProperty(u)&&l.disabled))){if(!s){const n=h(e);o=(null==n?void 0:n.createEventArgs)?n.createEventArgs(t):{},s=!0}y.hasOwnProperty(t.type)&&t.preventDefault(),i({browserRendererId:this.browserRendererId,eventHandlerId:a.eventHandlerId,eventName:e,eventFieldInfo:r.fromEvent(a.renderingComponentId,t)},o)}d.stopPropagation(e)&&(c=!0),d.preventDefault(e)&&t.preventDefault()}n=a||c?null:n.parentElement}var l,u}getEventHandlerInfosForElement(e,t){return e.hasOwnProperty(this.eventsCollectionKey)?e[this.eventsCollectionKey]:t?e[this.eventsCollectionKey]=new _:null}}v.nextEventDelegatorId=0;class b{constructor(e){this.globalListener=e,this.infosByEventHandlerId={},this.countByEventName={},l.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=u(e),this.countByEventName.hasOwnProperty(e))this.countByEventName[e]++;else{this.countByEventName[e]=1;const t=m.hasOwnProperty(e);document.addEventListener(e,this.globalListener,t)}}update(e,t){if(this.infosByEventHandlerId.hasOwnProperty(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=u(t.eventName);0==--this.countByEventName[n]&&(delete this.countByEventName[n],document.removeEventListener(n,this.globalListener))}return t}handleEventNameAliasAdded(e,t){if(this.countByEventName.hasOwnProperty(e)){const n=this.countByEventName[e];delete this.countByEventName[e],document.removeEventListener(e,this.globalListener),this.addGlobalListener(t),this.countByEventName[t]+=n-1}}}class _{constructor(){this.handlers={},this.preventDefaultFlags=null,this.stopPropagationFlags=null}getHandler(e){return this.handlers.hasOwnProperty(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 E(e){const t={};return e.forEach((e=>{t[e]=!0})),t}const S=O("_blazorLogicalChildren"),C=O("_blazorLogicalParent"),I=O("_blazorLogicalEnd");function k(e,t){if(e.childNodes.length>0&&!t)throw new Error("New logical elements must start empty, or allowExistingContents must be true");return S in e||(e[S]=[]),e}function T(e,t){const n=document.createComment("!");return x(n,e,t),n}function x(e,t,n){const r=e;if(e instanceof Comment&&A(r)&&A(r).length>0)throw new Error("Not implemented: inserting non-empty logical container");if(R(r))throw new Error("Not implemented: moving existing logical children");const o=A(t);if(n0;)D(n,0)}const r=n;r.parentNode.removeChild(r)}function R(e){return e[C]||null}function P(e,t){return A(e)[t]}function U(e){var t=B(e);return"http://www.w3.org/2000/svg"===t.namespaceURI&&"foreignObject"!==t.tagName}function A(e){return e[S]}function N(e,t){const n=A(e);t.forEach((e=>{e.moveRangeStart=n[e.fromSiblingIndex],e.moveRangeEnd=M(e.moveRangeStart)})),t.forEach((t=>{const r=t.moveToBeforeMarker=document.createComment("marker"),o=n[t.toSiblingIndex+1];o?o.parentNode.insertBefore(r,o):L(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 B(e){if(e instanceof Element)return e;if(e instanceof Comment)return e.parentNode;throw new Error("Not a valid logical element")}function $(e){const t=A(R(e));return t[Array.prototype.indexOf.call(t,e)+1]||null}function L(e,t){if(t instanceof Element)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=$(t);n?n.parentNode.insertBefore(e,n):L(e,R(t))}}}function M(e){if(e instanceof Element)return e;const t=$(e);if(t)return t.previousSibling;{const t=R(e);return t instanceof Element?t.lastChild:M(t)}}function O(e){return"function"==typeof Symbol?Symbol():e}function H(e){return`_bl_${e}`}e.attachReviver(((e,t)=>t&&"object"==typeof t&&t.hasOwnProperty("__internalId")&&"string"==typeof t.__internalId?function(e){const t=`[${H(e)}]`;return document.querySelector(t)}(t.__internalId):t));const F="_blazorSelectValue",j=document.createElement("template"),W=document.createElementNS("http://www.w3.org/2000/svg","g"),z={},q="__internal_",J="preventDefault_",K="stopPropagation_";class V{constructor(e){this.childComponentLocations={},this.eventDelegator=new v(e),this.eventDelegator.notifyAfterClick((e=>{if(!ee)return;if(0!==e.button||function(e){return e.ctrlKey||e.shiftKey||e.altKey||e.metaKey}(e))return;if(e.defaultPrevented)return;const t=function(e){const t=!window._blazorDisableComposedPath&&e.composedPath&&e.composedPath();if(t){for(let e=0;ese(!1))))},enableNavigationInterception:function(){ee=!0},navigateTo:oe,getBaseURI:()=>document.baseURI,getLocationHref:()=>location.href};function oe(e,t,n=!1){const r=ce(e);if(!t&&he(r))ie(r,!1,n);else if(t&&location.href===e){const t=e+"?";history.replaceState(null,"",t),location.replace(e)}else n?history.replaceState(null,"",r):location.href=e}function ie(e,t,n=!1){Z=!0,n?history.replaceState(null,"",e):history.pushState(null,"",e),se(t)}async function se(e){ne&&await ne(location.href,e)}let ae;function ce(e){return ae=ae||document.createElement("a"),ae.href=e,ae.href}function le(e,t){return e?e.tagName===t?e:le(e.parentElement,t):null}function he(e){const t=(n=document.baseURI).substr(0,n.lastIndexOf("/")+1);var n;return e.startsWith(t)}const ue={init:function(e,t,n,r=50){const o=pe(t);(o||document.documentElement).style.overflowAnchor="none";const i=new IntersectionObserver((function(r){r.forEach((r=>{var o;if(!r.isIntersecting)return;const i=t.getBoundingClientRect(),s=n.getBoundingClientRect().top-i.bottom,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`});i.observe(t),i.observe(n);const s=c(t),a=c(n);function c(e){const t=new MutationObserver((()=>{i.unobserve(e),i.observe(e)}));return t.observe(e,{attributes:!0}),t}de[e._id]={intersectionObserver:i,mutationObserverBefore:s,mutationObserverAfter:a}},dispose:function(e){const t=de[e._id];t&&(t.intersectionObserver.disconnect(),t.mutationObserverBefore.disconnect(),t.mutationObserverAfter.disconnect(),e.dispose(),delete de[e._id])}},de={};function pe(e){return e?"visible"!==getComputedStyle(e).overflowY?e:pe(e.parentElement):null}const fe={navigateTo:oe,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=a.get(t.browserEventName);n?n.push(e):a.set(t.browserEventName,[e]),l.forEach((n=>n(e,t.browserEventName)))}s.set(e,t)},_internal:{navigationManager:re,domWrapper:{focus:function(e,t){if(!(e instanceof HTMLElement))throw new Error("Unable to focus an invalid element.");e.focus({preventScroll:t})},focusBySelector:function(e){const t=document.querySelector(e);t&&(t.hasAttribute("tabindex")||(t.tabIndex=-1),t.focus())}},Virtualize:ue}};window.Blazor=fe;const ge=[0,2e3,1e4,3e4,null];class me{constructor(e){this._retryDelays=void 0!==e?[...e,null]:ge}nextRetryDelayInMilliseconds(e){return this._retryDelays[e.previousRetryCount]}}class ye extends Error{constructor(e,t){const n=new.target.prototype;super(`${e}: Status code '${t}'`),this.statusCode=t,this.__proto__=n}}class we extends Error{constructor(e="A timeout occurred."){const t=new.target.prototype;super(e),this.__proto__=t}}class ve extends Error{constructor(e="An abort occurred."){const t=new.target.prototype;super(e),this.__proto__=t}}class be{constructor(e,t,n){this.statusCode=e,this.statusText=t,this.content=n}}class _e{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""}}var Ee,Se,Ce,Ie,ke;!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"}(Ee||(Ee={}));class Te extends _e{constructor(e){if(super(),this._logger=e,"undefined"==typeof fetch){const e=require;this._jar=new(e("tough-cookie").CookieJar),this._fetchType=e("node-fetch"),this._fetchType=e("fetch-cookie")(this._fetchType,this._jar),this._abortControllerType=e("abort-controller")}else this._fetchType=fetch.bind(self),this._abortControllerType=AbortController}async send(e){if(e.abortSignal&&e.abortSignal.aborted)throw new ve;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 ve});let r,o=null;if(e.timeout){const r=e.timeout;o=setTimeout((()=>{t.abort(),this._logger.log(Ee.Warning,"Timeout from HTTP request."),n=new we}),r)}try{r=await this._fetchType(e.url,{body:e.content,cache:"no-cache",credentials:!0===e.withCredentials?"include":"same-origin",headers:{"Content-Type":"text/plain;charset=UTF-8","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(Ee.Warning,`Error from HTTP request. ${e}.`),e}finally{o&&clearTimeout(o),e.abortSignal&&(e.abortSignal.onabort=null)}if(!r.ok){const e=await xe(r,"text");throw new ye(e||r.statusText,r.status)}const i=xe(r,e.responseType),s=await i;return new be(r.status,r.statusText,s)}getCookieString(e){return""}}function xe(e,t){let n;switch(t){case"arraybuffer":n=e.arrayBuffer();break;case"text":n=e.text();break;case"blob":case"document":case"json":throw new Error(`${t} is not supported.`);default:n=e.text()}return n}class De extends _e{constructor(e){super(),this._logger=e}send(e){return e.abortSignal&&e.abortSignal.aborted?Promise.reject(new ve):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"),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 ve)}),e.timeout&&(r.timeout=e.timeout),r.onload=()=>{e.abortSignal&&(e.abortSignal.onabort=null),r.status>=200&&r.status<300?t(new be(r.status,r.statusText,r.response||r.responseText)):n(new ye(r.response||r.responseText||r.statusText,r.status))},r.onerror=()=>{this._logger.log(Ee.Warning,`Error from HTTP request. ${r.status}: ${r.statusText}.`),n(new ye(r.statusText,r.status))},r.ontimeout=()=>{this._logger.log(Ee.Warning,"Timeout from HTTP request."),n(new we)},r.send(e.content||"")})):Promise.reject(new Error("No url defined.")):Promise.reject(new Error("No method defined."))}}class Re extends _e{constructor(e){if(super(),"undefined"!=typeof fetch)this._httpClient=new Te(e);else{if("undefined"==typeof XMLHttpRequest)throw new Error("No usable HttpClient found.");this._httpClient=new De(e)}}send(e){return e.abortSignal&&e.abortSignal.aborted?Promise.reject(new ve):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)}}class Pe{}Pe.Authorization="Authorization",Pe.Cookie="Cookie",function(e){e[e.None=0]="None",e[e.WebSockets=1]="WebSockets",e[e.ServerSentEvents=2]="ServerSentEvents",e[e.LongPolling=4]="LongPolling"}(Se||(Se={})),function(e){e[e.Text=1]="Text",e[e.Binary=2]="Binary"}(Ce||(Ce={}));class Ue{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 Ae{constructor(){}log(e,t){}}Ae.instance=new Ae;class Ne{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 Be{static get isBrowser(){return"object"==typeof window}static get isWebWorker(){return"object"==typeof self&&"importScripts"in self}static get isNode(){return!this.isBrowser&&!this.isWebWorker}}function $e(e,t){let n="";return Le(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 Le(e){return e&&"undefined"!=typeof ArrayBuffer&&(e instanceof ArrayBuffer||e.constructor&&"ArrayBuffer"===e.constructor.name)}async function Me(e,t,n,r,o,i,s,a,c){let l={};if(o){const e=await o();e&&(l={Authorization:`Bearer ${e}`})}const[h,u]=Fe();l[h]=u,e.log(Ee.Trace,`(${t} transport) sending data. ${$e(i,s)}.`);const d=Le(i)?"arraybuffer":"text",p=await n.post(r,{content:i,headers:{...l,...c},responseType:d,withCredentials:a});e.log(Ee.Trace,`(${t} transport) request complete. Response status: ${p.statusCode}.`)}class Oe{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 He{constructor(e){this._minLevel=e,this.out=console}log(e,t){if(e>=this._minLevel){const n=`[${(new Date).toISOString()}] ${Ee[e]}: ${t}`;switch(e){case Ee.Critical:case Ee.Error:this.out.error(n);break;case Ee.Warning:this.out.warn(n);break;case Ee.Information:this.out.info(n);break;default:this.out.log(n)}}}}function Fe(){let e="X-SignalR-User-Agent";return Be.isNode&&(e="User-Agent"),[e,je("0.0.0-DEV_BUILD",We(),Be.isNode?"NodeJS":"Browser",ze())]}function je(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 We(){if(!Be.isNode)return"";switch(process.platform){case"win32":return"Windows NT";case"darwin":return"macOS";case"linux":return"Linux";default:return process.platform}}function ze(){if(Be.isNode)return process.versions.node}class qe{constructor(e,t,n,r,o,i){this._httpClient=e,this._accessTokenFactory=t,this._logger=n,this._pollAbort=new Ue,this._logMessageContent=r,this._withCredentials=o,this._headers=i,this._running=!1,this.onreceive=null,this.onclose=null}get pollAborted(){return this._pollAbort.aborted}async connect(e,t){if(Ne.isRequired(e,"url"),Ne.isRequired(t,"transferFormat"),Ne.isIn(t,Ce,"transferFormat"),this._url=e,this._logger.log(Ee.Trace,"(LongPolling transport) Connecting."),t===Ce.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]=Fe(),o={[n]:r,...this._headers},i={abortSignal:this._pollAbort.signal,headers:o,timeout:1e5,withCredentials:this._withCredentials};t===Ce.Binary&&(i.responseType="arraybuffer");const s=await this._getAccessToken();this._updateHeaderToken(i,s);const a=`${e}&_=${Date.now()}`;this._logger.log(Ee.Trace,`(LongPolling transport) polling: ${a}.`);const c=await this._httpClient.get(a,i);200!==c.statusCode?(this._logger.log(Ee.Error,`(LongPolling transport) Unexpected response code: ${c.statusCode}.`),this._closeError=new ye(c.statusText||"",c.statusCode),this._running=!1):this._running=!0,this._receiving=this._poll(this._url,i)}async _getAccessToken(){return this._accessTokenFactory?await this._accessTokenFactory():null}_updateHeaderToken(e,t){e.headers||(e.headers={}),t?e.headers[Pe.Authorization]=`Bearer ${t}`:e.headers[Pe.Authorization]&&delete e.headers[Pe.Authorization]}async _poll(e,t){try{for(;this._running;){const n=await this._getAccessToken();this._updateHeaderToken(t,n);try{const n=`${e}&_=${Date.now()}`;this._logger.log(Ee.Trace,`(LongPolling transport) polling: ${n}.`);const r=await this._httpClient.get(n,t);204===r.statusCode?(this._logger.log(Ee.Information,"(LongPolling transport) Poll terminated by server."),this._running=!1):200!==r.statusCode?(this._logger.log(Ee.Error,`(LongPolling transport) Unexpected response code: ${r.statusCode}.`),this._closeError=new ye(r.statusText||"",r.statusCode),this._running=!1):r.content?(this._logger.log(Ee.Trace,`(LongPolling transport) data received. ${$e(r.content,this._logMessageContent)}.`),this.onreceive&&this.onreceive(r.content)):this._logger.log(Ee.Trace,"(LongPolling transport) Poll timed out, reissuing.")}catch(e){this._running?e instanceof we?this._logger.log(Ee.Trace,"(LongPolling transport) Poll timed out, reissuing."):(this._closeError=e,this._running=!1):this._logger.log(Ee.Trace,`(LongPolling transport) Poll errored after shutdown: ${e.message}`)}}}finally{this._logger.log(Ee.Trace,"(LongPolling transport) Polling complete."),this.pollAborted||this._raiseOnClose()}}async send(e){return this._running?Me(this._logger,"LongPolling",this._httpClient,this._url,this._accessTokenFactory,e,this._logMessageContent,this._withCredentials,this._headers):Promise.reject(new Error("Cannot send until the transport is connected"))}async stop(){this._logger.log(Ee.Trace,"(LongPolling transport) Stopping polling."),this._running=!1,this._pollAbort.abort();try{await this._receiving,this._logger.log(Ee.Trace,`(LongPolling transport) sending DELETE request to ${this._url}.`);const e={},[t,n]=Fe();e[t]=n;const r={headers:{...e,...this._headers},withCredentials:this._withCredentials},o=await this._getAccessToken();this._updateHeaderToken(r,o),await this._httpClient.delete(this._url,r),this._logger.log(Ee.Trace,"(LongPolling transport) DELETE request sent.")}finally{this._logger.log(Ee.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(Ee.Trace,e),this.onclose(this._closeError)}}}class Je{constructor(e,t,n,r,o,i,s){this._httpClient=e,this._accessTokenFactory=t,this._logger=n,this._logMessageContent=r,this._withCredentials=i,this._eventSourceConstructor=o,this._headers=s,this.onreceive=null,this.onclose=null}async connect(e,t){if(Ne.isRequired(e,"url"),Ne.isRequired(t,"transferFormat"),Ne.isIn(t,Ce,"transferFormat"),this._logger.log(Ee.Trace,"(SSE transport) Connecting."),this._url=e,this._accessTokenFactory){const t=await this._accessTokenFactory();t&&(e+=(e.indexOf("?")<0?"?":"&")+`access_token=${encodeURIComponent(t)}`)}return new Promise(((n,r)=>{let o,i=!1;if(t===Ce.Text){if(Be.isBrowser||Be.isWebWorker)o=new this._eventSourceConstructor(e,{withCredentials:this._withCredentials});else{const t=this._httpClient.getCookieString(e),n={};n.Cookie=t;const[r,i]=Fe();n[r]=i,o=new this._eventSourceConstructor(e,{withCredentials:this._withCredentials,headers:{...n,...this._headers}})}try{o.onmessage=e=>{if(this.onreceive)try{this._logger.log(Ee.Trace,`(SSE transport) data received. ${$e(e.data,this._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(Ee.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?Me(this._logger,"SSE",this._httpClient,this._url,this._accessTokenFactory,e,this._logMessageContent,this._withCredentials,this._headers):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 Ke{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){if(Ne.isRequired(e,"url"),Ne.isRequired(t,"transferFormat"),Ne.isIn(t,Ce,"transferFormat"),this._logger.log(Ee.Trace,"(WebSockets transport) Connecting."),this._accessTokenFactory){const t=await this._accessTokenFactory();t&&(e+=(e.indexOf("?")<0?"?":"&")+`access_token=${encodeURIComponent(t)}`)}return new Promise(((n,r)=>{let o;e=e.replace(/^http/,"ws"),this._httpClient.getCookieString(e);let i=!1;o||(o=new this._webSocketConstructor(e)),t===Ce.Binary&&(o.binaryType="arraybuffer"),o.onopen=t=>{this._logger.log(Ee.Information,`WebSocket connected to ${e}.`),this._webSocket=o,i=!0,n()},o.onerror=e=>{let t=null;t="undefined"!=typeof ErrorEvent&&e instanceof ErrorEvent?e.error:"There was an error with the transport",this._logger.log(Ee.Information,`(WebSockets transport) ${t}.`)},o.onmessage=e=>{if(this._logger.log(Ee.Trace,`(WebSockets transport) data received. ${$e(e.data,this._logMessageContent)}.`),this.onreceive)try{this.onreceive(e.data)}catch(e){return void this._close(e)}},o.onclose=e=>{if(i)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(Ee.Trace,`(WebSockets transport) sending data. ${$e(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(Ee.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 Ve{constructor(e,t={}){var n;if(this._stopPromiseResolver=()=>{},this.features={},this._negotiateVersion=1,Ne.isRequired(e,"url"),this._logger=void 0===(n=t.logger)?new He(Ee.Information):null===n?Ae.instance:void 0!==n.log?n:new He(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,"undefined"==typeof WebSocket||t.WebSocket||(t.WebSocket=WebSocket),"undefined"==typeof EventSource||t.EventSource||(t.EventSource=EventSource),this._httpClient=t.httpClient||new Re(this._logger),this._connectionState="Disconnected",this._connectionStarted=!1,this._options=t,this.onreceive=null,this.onclose=null}async start(e){if(e=e||Ce.Binary,Ne.isIn(e,Ce,"transferFormat"),this._logger.log(Ee.Debug,`Starting connection with transfer format '${Ce[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(Ee.Error,e),await this._stopPromise,Promise.reject(new Error(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(Ee.Error,e),Promise.reject(new Error(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 Xe(this.transport)),this._sendQueue.send(e))}async stop(e){return"Disconnected"===this._connectionState?(this._logger.log(Ee.Debug,`Call to HttpConnection.stop(${e}) ignored because the connection is already in the disconnected state.`),Promise.resolve()):"Disconnecting"===this._connectionState?(this._logger.log(Ee.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(Ee.Error,`HttpConnection.transport.stop() threw error '${e}'.`),this._stopConnection()}this.transport=void 0}else this._logger.log(Ee.Debug,"HttpConnection.transport is undefined in HttpConnection.stop() because start() failed.")}async _startInternal(e){let t=this.baseUrl;this._accessTokenFactory=this._options.accessTokenFactory;try{if(this._options.skipNegotiation){if(this._options.transport!==Se.WebSockets)throw new Error("Negotiation can only be skipped when using the WebSocket transport directly.");this.transport=this._constructTransport(Se.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 Error("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}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 qe&&(this.features.inherentKeepAlive=!0),"Connecting"===this._connectionState&&(this._logger.log(Ee.Debug,"The HttpConnection connected successfully."),this._connectionState="Connected")}catch(e){return this._logger.log(Ee.Error,"Failed to start the connection: "+e),this._connectionState="Disconnected",this.transport=void 0,this._stopPromiseResolver(),Promise.reject(e)}}async _getNegotiationResponse(e){const t={};if(this._accessTokenFactory){const e=await this._accessTokenFactory();e&&(t[Pe.Authorization]=`Bearer ${e}`)}const[n,r]=Fe();t[n]=r;const o=this._resolveNegotiateUrl(e);this._logger.log(Ee.Debug,`Sending negotiation request: ${o}.`);try{const e=await this._httpClient.post(o,{content:"",headers:{...t,...this._options.headers},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 ye&&404===e.statusCode&&(t+=" Either this is not a SignalR endpoint or there is a proxy blocking the connection."),this._logger.log(Ee.Error,t),Promise.reject(new Error(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(Ee.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: ${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(Ee.Error,`Failed to start the transport '${n.transport}': ${e}`),a=void 0,i.push(`${n.transport} failed: ${e}`),"Connecting"!==this._connectionState){const e="Failed to select transport before stop() was called.";return this._logger.log(Ee.Debug,e),Promise.reject(new Error(e))}}}}return i.length>0?Promise.reject(new Error(`Unable to connect to the server with any of the available transports. ${i.join(" ")}`)):Promise.reject(new Error("None of the transports supported by the client are supported by the server."))}_constructTransport(e){switch(e){case Se.WebSockets:if(!this._options.WebSocket)throw new Error("'WebSocket' is not supported in your environment.");return new Ke(this._httpClient,this._accessTokenFactory,this._logger,this._options.logMessageContent||!1,this._options.WebSocket,this._options.headers||{});case Se.ServerSentEvents:if(!this._options.EventSource)throw new Error("'EventSource' is not supported in your environment.");return new Je(this._httpClient,this._accessTokenFactory,this._logger,this._options.logMessageContent||!1,this._options.EventSource,this._options.withCredentials,this._options.headers||{});case Se.LongPolling:return new qe(this._httpClient,this._accessTokenFactory,this._logger,this._options.logMessageContent||!1,this._options.withCredentials,this._options.headers||{});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=Se[e.transport];if(null==r)return this._logger.log(Ee.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(Ee.Debug,`Skipping transport '${Se[r]}' because it was disabled by the client.`),new Error(`'${Se[r]}' is disabled by the client.`);if(!(e.transferFormats.map((e=>Ce[e])).indexOf(n)>=0))return this._logger.log(Ee.Debug,`Skipping transport '${Se[r]}' because it does not support the requested transfer format '${Ce[n]}'.`),new Error(`'${Se[r]}' does not support ${Ce[n]}.`);if(r===Se.WebSockets&&!this._options.WebSocket||r===Se.ServerSentEvents&&!this._options.EventSource)return this._logger.log(Ee.Debug,`Skipping transport '${Se[r]}' because it is not supported in your environment.'`),new Error(`'${Se[r]}' is not supported in your environment.`);this._logger.log(Ee.Debug,`Selecting transport '${Se[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(Ee.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(Ee.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(Ee.Error,`Connection disconnected with error '${e}'.`):this._logger.log(Ee.Information,"Connection disconnected."),this._sendQueue&&(this._sendQueue.stop().catch((e=>{this._logger.log(Ee.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(Ee.Error,`HttpConnection.onclose(${e}) threw error '${t}'.`)}}}else this._logger.log(Ee.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(!Be.isBrowser||!window.document)throw new Error(`Cannot resolve '${e}'.`);const t=window.document.createElement("a");return t.href=e,this._logger.log(Ee.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 Xe{constructor(e){this._transport=e,this._buffer=[],this._executing=!0,this._sendBufferedData=new Ye,this._transportResult=new Ye,this._sendLoopPromise=this._sendLoop()}send(e){return this._bufferData(e),this._transportResult||(this._transportResult=new Ye),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 Ye;const e=this._transportResult;this._transportResult=void 0;const t="string"==typeof this._buffer[0]?this._buffer.join(""):Xe._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 Ye{constructor(){this.promise=new Promise(((e,t)=>[this._resolver,this._rejecter]=[e,t]))}resolve(){this._resolver()}reject(e){this._rejecter(e)}}class Ge{static write(e){return`${e}${Ge.RecordSeparator}`}static parse(e){if(e[e.length-1]!==Ge.RecordSeparator)throw new Error("Message is incomplete.");const t=e.split(Ge.RecordSeparator);return t.pop(),t}}Ge.RecordSeparatorCode=30,Ge.RecordSeparator=String.fromCharCode(Ge.RecordSeparatorCode);class Qe{writeHandshakeRequest(e){return Ge.write(JSON.stringify(e))}parseHandshakeResponse(e){let t,n;if(Le(e)){const r=new Uint8Array(e),o=r.indexOf(Ge.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(Ge.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=Ge.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"}(Ie||(Ie={}));class Ze{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 Oe(this,e)}}!function(e){e.Disconnected="Disconnected",e.Connecting="Connecting",e.Connected="Connected",e.Disconnecting="Disconnecting",e.Reconnecting="Reconnecting"}(ke||(ke={}));class et{constructor(e,t,n,r){this._nextKeepAlive=0,Ne.isRequired(e,"connection"),Ne.isRequired(t,"logger"),Ne.isRequired(n,"protocol"),this.serverTimeoutInMilliseconds=3e4,this.keepAliveIntervalInMilliseconds=15e3,this._logger=t,this._protocol=n,this.connection=e,this._reconnectPolicy=r,this._handshakeProtocol=new Qe,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=ke.Disconnected,this._connectionStarted=!1,this._cachedPingMessage=this._protocol.writeMessage({type:Ie.Ping})}static create(e,t,n,r){return new et(e,t,n,r)}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!==ke.Disconnected&&this._connectionState!==ke.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!==ke.Disconnected)return Promise.reject(new Error("Cannot start a HubConnection that is not in the 'Disconnected' state."));this._connectionState=ke.Connecting,this._logger.log(Ee.Debug,"Starting HubConnection.");try{await this._startInternal(),this._connectionState=ke.Connected,this._connectionStarted=!0,this._logger.log(Ee.Debug,"HubConnection connected successfully.")}catch(e){return this._connectionState=ke.Disconnected,this._logger.log(Ee.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(Ee.Debug,"Sending handshake request."),await this._sendMessage(this._handshakeProtocol.writeHandshakeRequest(t)),this._logger.log(Ee.Information,`Using HubProtocol '${this._protocol.name}'.`),this._cleanupTimeout(),this._resetTimeoutPeriod(),this._resetKeepAliveInterval(),await e,this._stopDuringStartError)throw this._stopDuringStartError}catch(e){throw this._logger.log(Ee.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){return this._connectionState===ke.Disconnected?(this._logger.log(Ee.Debug,`Call to HubConnection.stop(${e}) ignored because it is already in the disconnected state.`),Promise.resolve()):this._connectionState===ke.Disconnecting?(this._logger.log(Ee.Debug,`Call to HttpConnection.stop(${e}) ignored because the connection is already in the disconnecting state.`),this._stopPromise):(this._connectionState=ke.Disconnecting,this._logger.log(Ee.Debug,"Stopping HubConnection."),this._reconnectDelayHandle?(this._logger.log(Ee.Debug,"Connection stopped during reconnect delay. Done reconnecting."),clearTimeout(this._reconnectDelayHandle),this._reconnectDelayHandle=void 0,this._completeClose(),Promise.resolve()):(this._cleanupTimeout(),this._cleanupPingTimer(),this._stopDuringStartError=e||new Error("The connection was stopped before the hub handshake could complete."),this.connection.stop(e)))}stream(e,...t){const[n,r]=this._replaceStreamingParams(t),o=this._createStreamInvocation(e,t,r);let i;const s=new Ze;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===Ie.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===Ie.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 Ie.Invocation:this._invokeClientMethod(e);break;case Ie.StreamItem:case Ie.Completion:{const t=this._callbacks[e.invocationId];t&&(e.type===Ie.Completion&&delete this._callbacks[e.invocationId],t(e));break}case Ie.Ping:break;case Ie.Close:{this._logger.log(Ee.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(Ee.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(Ee.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(Ee.Error,e);const n=new Error(e);throw this._handshakeRejecter(n),n}return this._logger.log(Ee.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===ke.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."))}_invokeClientMethod(e){const t=this._methods[e.target.toLowerCase()];if(t){try{t.forEach((t=>t.apply(this,e.arguments)))}catch(t){this._logger.log(Ee.Error,`A callback for the method ${e.target.toLowerCase()} threw error '${t}'.`)}if(e.invocationId){const e="Server requested a response, which is not supported in this version of the client.";this._logger.log(Ee.Error,e),this._stopPromise=this._stopInternal(new Error(e))}}else this._logger.log(Ee.Warning,`No client method with the name '${e.target}' found.`)}_connectionClosed(e){this._logger.log(Ee.Debug,`HubConnection.connectionClosed(${e}) called while in state ${this._connectionState}.`),this._stopDuringStartError=this._stopDuringStartError||e||new Error("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===ke.Disconnecting?this._completeClose(e):this._connectionState===ke.Connected&&this._reconnectPolicy?this._reconnect(e):this._connectionState===ke.Connected&&this._completeClose(e)}_completeClose(e){if(this._connectionStarted){this._connectionState=ke.Disconnected,this._connectionStarted=!1;try{this._closedCallbacks.forEach((t=>t.apply(this,[e])))}catch(t){this._logger.log(Ee.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(Ee.Debug,"Connection not reconnecting because the IRetryPolicy returned null on the first reconnect attempt."),void this._completeClose(e);if(this._connectionState=ke.Reconnecting,e?this._logger.log(Ee.Information,`Connection reconnecting because of error '${e}'.`):this._logger.log(Ee.Information,"Connection reconnecting."),0!==this._reconnectingCallbacks.length){try{this._reconnectingCallbacks.forEach((t=>t.apply(this,[e])))}catch(t){this._logger.log(Ee.Error,`An onreconnecting callback called with error '${e}' threw error '${t}'.`)}if(this._connectionState!==ke.Reconnecting)return void this._logger.log(Ee.Debug,"Connection left the reconnecting state in onreconnecting callback. Done reconnecting.")}for(;null!==o;){if(this._logger.log(Ee.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!==ke.Reconnecting)return void this._logger.log(Ee.Debug,"Connection left the reconnecting state during reconnect delay. Done reconnecting.");try{if(await this._startInternal(),this._connectionState=ke.Connected,this._logger.log(Ee.Information,"HubConnection reconnected successfully."),0!==this._reconnectedCallbacks.length)try{this._reconnectedCallbacks.forEach((e=>e.apply(this,[this.connection.connectionId])))}catch(e){this._logger.log(Ee.Error,`An onreconnected callback called with connectionId '${this.connection.connectionId}; threw error '${e}'.`)}return}catch(e){if(this._logger.log(Ee.Information,`Reconnect attempt failed because of error '${e}'.`),this._connectionState!==ke.Reconnecting)return this._logger.log(Ee.Debug,`Connection moved to the '${this._connectionState}' from the reconnecting state during reconnect attempt. Done reconnecting.`),void(this._connectionState===ke.Disconnecting&&this._completeClose());r=e instanceof Error?e:new Error(e.toString()),o=this._getNextRetryDelay(n++,Date.now()-t,r)}}this._logger.log(Ee.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(Ee.Error,`IRetryPolicy.nextRetryDelayInMilliseconds(${e}, ${t}) threw error '${n}'.`),null}}_cancelCallbacksWithError(e){const t=this._callbacks;this._callbacks={},Object.keys(t).forEach((n=>{(0,t[n])(null,e)}))}_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:Ie.Invocation}:{arguments:t,target:e,type:Ie.Invocation};{const n=this._invocationId;return this._invocationId++,0!==r.length?{arguments:t,invocationId:n.toString(),streamIds:r,target:e,type:Ie.Invocation}:{arguments:t,invocationId:n.toString(),target:e,type:Ie.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 ut=ot?new TextDecoder:null,dt=ot?"undefined"!=typeof process&&"force"!==process.env.TEXT_DECODER?200:0:it,pt=function(e,t){this.type=e,this.data=t};function ft(e,t,n){var r=Math.floor(n/4294967296),o=n;e.setUint32(t,r),e.setUint32(t+4,o)}function gt(e,t){return 4294967296*e.getInt32(t)+e.getUint32(t+4)}var mt={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),ft(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:gt(t,4),nsec:t.getUint32(0)};default:throw new Error("Unrecognized data size for timestamp: "+e.length)}}(e);return new Date(1e3*t.sec+t.nsec/1e6)}},yt=function(){function e(){this.builtInEncoders=[],this.builtInDecoders=[],this.encoders=[],this.decoders=[],this.register(mt)}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 "+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: "+e+" bytes in UTF-8");this.writeU8(219),this.writeU32(e)}},e.prototype.encodeString=function(e){if(e.length>ct){var t=st(e);this.ensureBufferSizeToWrite(5+t),this.writeStringHeader(t),lt(e,this.bytes,this.pos),this.pos+=t}else t=st(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: "+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: "+t);this.writeU8(198),this.writeU32(t)}var n=wt(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: "+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=ht(e,t,n),i=Uint8Array.prototype.slice.call(e,t,t+n);return this.store(i,o),o},e}(),St=(_t=function(e,t){return(_t=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])})(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}_t(e,t),e.prototype=null===t?Object.create(t):(n.prototype=t.prototype,new n)}),Ct=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]1||a(e,t)}))})}function a(e,t){try{(n=o[e](t)).value instanceof kt?Promise.resolve(n.value.v).then(c,l):h(i[0][2],n)}catch(e){h(i[0][3],e)}var n}function c(e){a("next",e)}function l(e){a("throw",e)}function h(e,t){e(t),i.shift(),i.length&&a(i[0][0],i[0][1])}},xt=new DataView(new ArrayBuffer(0)),Dt=new Uint8Array(xt.buffer),Rt=function(){try{xt.getInt8(0)}catch(e){return e.constructor}throw new Error("never reached")}(),Pt=new Rt("Insufficient data"),Ut=4294967295,At=new Et,Nt=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 St(t,e),t}(Error),Bt=function(){function e(e,t,n,r,o,i,s,a){void 0===e&&(e=yt.defaultCodec),void 0===t&&(t=void 0),void 0===n&&(n=Ut),void 0===r&&(r=Ut),void 0===o&&(o=Ut),void 0===i&&(i=Ut),void 0===s&&(s=Ut),void 0===a&&(a=At),this.extensionCodec=e,this.context=t,this.maxStrLength=n,this.maxBinLength=r,this.maxArrayLength=o,this.maxMapLength=i,this.maxExtLength=s,this.keyDecoder=a,this.totalPos=0,this.pos=0,this.view=xt,this.bytes=Dt,this.headByte=-1,this.stack=[]}return e.prototype.reinitializeState=function(){this.totalPos=0,this.headByte=-1,this.stack.length=0},e.prototype.setBuffer=function(e){this.bytes=wt(e),this.view=function(e){if(e instanceof ArrayBuffer)return new DataView(e);var t=wt(e);return new DataView(t.buffer,t.byteOffset,t.byteLength)}(this.bytes),this.pos=0},e.prototype.appendBuffer=function(e){if(-1!==this.headByte||this.hasRemaining()){var t=this.bytes.subarray(this.pos),n=wt(e),r=new Uint8Array(t.length+n.length);r.set(t),r.set(n,t.length),this.setBuffer(r)}else this.setBuffer(e)},e.prototype.hasRemaining=function(e){return void 0===e&&(e=1),this.view.byteLength-this.pos>=e},e.prototype.createExtraByteError=function(e){var t=this.view,n=this.pos;return new RangeError("Extra "+(t.byteLength-n)+" of "+t.byteLength+" byte(s) found at buffer["+e+"]")},e.prototype.decode=function(e){this.reinitializeState(),this.setBuffer(e);var t=this.doDecodeSync();if(this.hasRemaining())throw this.createExtraByteError(this.pos);return t},e.prototype.decodeMulti=function(e){return Ct(this,(function(t){switch(t.label){case 0:this.reinitializeState(),this.setBuffer(e),t.label=1;case 1:return this.hasRemaining()?[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,u,d;return Ct(this,(function(p){switch(p.label){case 0:i=!1,p.label=1;case 1:p.trys.push([1,6,7,12]),t=It(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 Rt))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())throw this.createExtraByteError(this.totalPos);return[2,s]}throw h=(l=this).headByte,u=l.pos,d=l.totalPos,new RangeError("Insufficient data in parsing "+bt(h)+" at "+d+" ("+u+" 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 Tt(this,arguments,(function(){var n,r,o,i,s,a,c,l,h;return Ct(this,(function(u){switch(u.label){case 0:n=t,r=-1,u.label=1;case 1:u.trys.push([1,13,14,19]),o=It(e),u.label=2;case 2:return[4,kt(o.next())];case 3:if((i=u.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()),u.label=4;case 4:u.trys.push([4,9,,10]),u.label=5;case 5:return[4,kt(this.doDecodeSync())];case 6:return[4,u.sent()];case 7:return u.sent(),0==--r?[3,8]:[3,5];case 8:return[3,10];case 9:if(!((a=u.sent())instanceof Rt))throw a;return[3,10];case 10:this.totalPos+=this.pos,u.label=11;case 11:return[3,2];case 12:return[3,19];case 13:return c=u.sent(),l={error:c},[3,19];case 14:return u.trys.push([14,,17,18]),i&&!i.done&&(h=o.return)?[4,kt(h.call(o))]:[3,16];case 15:u.sent(),u.label=16;case 16:return[3,18];case 17:if(l)throw l.error;return[7];case 18:return[7];case 19:return[2]}}))}))},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 Nt("Unrecognized type byte: "+bt(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 Nt("The type of key must be string or number but "+typeof t);if("__proto__"===t)throw new Nt("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 Nt("Unrecognized array type byte: "+bt(e))}},e.prototype.pushMapState=function(e){if(e>this.maxMapLength)throw new Nt("Max length exceeded: map length ("+e+") > maxMapLengthLength ("+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 Nt("Max length exceeded: array length ("+e+") > maxArrayLength ("+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 Nt("Max length exceeded: UTF-8 byte length ("+e+") > maxStrLength ("+this.maxStrLength+")");if(this.bytes.byteLengthdt?function(e,t,n){var r=e.subarray(t,t+n);return ut.decode(r)}(this.bytes,o,e):ht(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 Nt("Max length exceeded: bin length ("+e+") > maxBinLength ("+this.maxBinLength+")");if(!this.hasRemaining(e+t))throw Pt;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 Nt("Max length exceeded: ext length ("+e+") > maxExtLength ("+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=gt(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 $t{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 Lt=new Uint8Array([145,Ie.Ping]);class Mt{constructor(e){this.name="messagepack",this.version=1,this.transferFormat=Ce.Binary,this._errorResult=1,this._voidResult=2,this._nonVoidResult=3,e=e||{},this._encoder=new vt(e.extensionCodec,e.context,e.maxDepth,e.initialBufferSize,e.sortKeys,e.forceFloat32,e.ignoreUndefined,e.forceIntegerToFloat),this._decoder=new Bt(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=Ae.instance);const r=$t.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 Ie.Invocation:return this._writeInvocation(e);case Ie.StreamInvocation:return this._writeStreamInvocation(e);case Ie.StreamItem:return this._writeStreamItem(e);case Ie.Completion:return this._writeCompletion(e);case Ie.Ping:return $t.write(Lt);case Ie.CancelInvocation:return this._writeCancelInvocation(e);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 Ie.Invocation:return this._createInvocationMessage(this._readHeaders(n),n);case Ie.StreamItem:return this._createStreamItemMessage(this._readHeaders(n),n);case Ie.Completion:return this._createCompletionMessage(this._readHeaders(n),n);case Ie.Ping:return this._createPingMessage(n);case Ie.Close:return this._createCloseMessage(n);default:return t.log(Ee.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:Ie.Close}}_createPingMessage(e){if(e.length<1)throw new Error("Invalid payload for Ping message.");return{type:Ie.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:Ie.Invocation}:{arguments:t[4],headers:e,streamIds:[],target:t[3],type:Ie.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:Ie.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:Ie.Completion}}_writeInvocation(e){let t;return t=e.streamIds?this._encoder.encode([Ie.Invocation,e.headers||{},e.invocationId||null,e.target,e.arguments,e.streamIds]):this._encoder.encode([Ie.Invocation,e.headers||{},e.invocationId||null,e.target,e.arguments]),$t.write(t.slice())}_writeStreamInvocation(e){let t;return t=e.streamIds?this._encoder.encode([Ie.StreamInvocation,e.headers||{},e.invocationId,e.target,e.arguments,e.streamIds]):this._encoder.encode([Ie.StreamInvocation,e.headers||{},e.invocationId,e.target,e.arguments]),$t.write(t.slice())}_writeStreamItem(e){const t=this._encoder.encode([Ie.StreamItem,e.headers||{},e.invocationId,e.item]);return $t.write(t.slice())}_writeCompletion(e){const t=e.error?this._errorResult:e.result?this._nonVoidResult:this._voidResult;let n;switch(t){case this._errorResult:n=this._encoder.encode([Ie.Completion,e.headers||{},e.invocationId,t,e.error]);break;case this._voidResult:n=this._encoder.encode([Ie.Completion,e.headers||{},e.invocationId,t]);break;case this._nonVoidResult:n=this._encoder.encode([Ie.Completion,e.headers||{},e.invocationId,t,e.result])}return $t.write(n.slice())}_writeCancelInvocation(e){const t=this._encoder.encode([Ie.CancelInvocation,e.headers||{},e.invocationId]);return $t.write(t.slice())}_readHeaders(e){const t=e[1];if("object"!=typeof t)throw new Error("Invalid headers.");return t}}let Ot=!1;const Ht="function"==typeof TextDecoder?new TextDecoder("utf-8"):null,Ft=Ht?Ht.decode.bind(Ht):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("")},jt=Math.pow(2,32),Wt=Math.pow(2,21)-1;function zt(e,t){return e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24}function qt(e,t){return e[t]+(e[t+1]<<8)+(e[t+2]<<16)+(e[t+3]<<24>>>0)}function Jt(e,t){const n=qt(e,t+4);if(n>Wt)throw new Error(`Cannot read uint64 with high order part ${n}, because the result would exceed Number.MAX_SAFE_INTEGER.`);return n*jt+qt(e,t)}class Kt{constructor(e){this.batchData=e;const t=new Gt(e);this.arrayRangeReader=new Qt(e),this.arrayBuilderSegmentReader=new Zt(e),this.diffReader=new Vt(e),this.editReader=new Xt(e,t),this.frameReader=new Yt(e,t)}updatedComponents(){return zt(this.batchData,this.batchData.length-20)}referenceFrames(){return zt(this.batchData,this.batchData.length-16)}disposedComponentIds(){return zt(this.batchData,this.batchData.length-12)}disposedEventHandlerIds(){return zt(this.batchData,this.batchData.length-8)}updatedComponentsEntry(e,t){const n=e+4*t;return zt(this.batchData,n)}referenceFramesEntry(e,t){return e+20*t}disposedComponentIdsEntry(e,t){const n=e+4*t;return zt(this.batchData,n)}disposedEventHandlerIdsEntry(e,t){const n=e+8*t;return Jt(this.batchData,n)}}class Vt{constructor(e){this.batchDataUint8=e}componentId(e){return zt(this.batchDataUint8,e)}edits(e){return e+4}editsEntry(e,t){return e+16*t}}class Xt{constructor(e,t){this.batchDataUint8=e,this.stringReader=t}editType(e){return zt(this.batchDataUint8,e)}siblingIndex(e){return zt(this.batchDataUint8,e+4)}newTreeIndex(e){return zt(this.batchDataUint8,e+8)}moveToSiblingIndex(e){return zt(this.batchDataUint8,e+8)}removedAttributeName(e){const t=zt(this.batchDataUint8,e+12);return this.stringReader.readString(t)}}class Yt{constructor(e,t){this.batchDataUint8=e,this.stringReader=t}frameType(e){return zt(this.batchDataUint8,e)}subtreeLength(e){return zt(this.batchDataUint8,e+4)}elementReferenceCaptureId(e){const t=zt(this.batchDataUint8,e+4);return this.stringReader.readString(t)}componentId(e){return zt(this.batchDataUint8,e+8)}elementName(e){const t=zt(this.batchDataUint8,e+8);return this.stringReader.readString(t)}textContent(e){const t=zt(this.batchDataUint8,e+4);return this.stringReader.readString(t)}markupContent(e){const t=zt(this.batchDataUint8,e+4);return this.stringReader.readString(t)}attributeName(e){const t=zt(this.batchDataUint8,e+4);return this.stringReader.readString(t)}attributeValue(e){const t=zt(this.batchDataUint8,e+8);return this.stringReader.readString(t)}attributeEventHandlerId(e){return Jt(this.batchDataUint8,e+12)}}class Gt{constructor(e){this.batchDataUint8=e,this.stringTableStartIndex=zt(e,e.length-4)}readString(e){if(-1===e)return null;{const n=zt(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(en.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(en.Debug,`Waiting for batch ${this.nextBatchId}. Batch ${e} not processed.`);try{this.nextBatchId++,this.logger.log(en.Debug,`Applying batch ${e}.`),function(e,t){const n=Q[e];if(!n)throw new Error(`There is no browser renderer with ID ${e}.`);const r=t.arrayRangeReader,o=t.updatedComponents(),i=r.values(o),s=r.count(o),a=t.referenceFrames(),c=r.values(a),l=t.diffReader;for(let e=0;e=this.minLevel){const n=`[${(new Date).toISOString()}] ${en[e]}: ${t}`;switch(e){case en.Critical:case en.Error:console.error(n);break;case en.Warning:console.warn(n);break;case en.Information:console.info(n);break;default:console.log(n)}}}}class on{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!==ke.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!==ke.Connected)return!1;const t=await e.invoke("StartCircuit",re.getBaseURI(),re.getLocationHref(),JSON.stringify(this.components.map((e=>e.toRecord()))),this.applicationState||"");return!!t&&(this.initialize(t),!0)}resolveElement(e){const t=Number.parseInt(e);if(Number.isNaN(t))throw new Error(`Invalid sequence number '${e}'.`);return function(e,t){if(!e.parentNode)throw new Error(`Comment not connected to the DOM ${e.textContent}`);const n=e.parentNode,r=k(n,!0),o=A(r);return Array.from(n.childNodes).forEach((e=>o.push(e))),e[C]=r,t&&(e[I]=t,k(t)),k(e)}(this.components[t].start,this.components[t].end)}}const sn={configureSignalR:e=>{},logLevel:en.Warning,reconnectionOptions:{maxRetries:8,retryIntervalMilliseconds:2e4,dialogId:"components-reconnect-modal"}};class an{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.modal.innerHTML='

Alternatively, reload

',this.message=this.modal.querySelector("h5"),this.button=this.modal.querySelector("button"),this.reloadParagraph=this.modal.querySelector("p"),this.loader=this.getLoader(),this.message.after(this.loader),this.button.addEventListener("click",(async()=>{this.show();try{await(null==fe?void 0:fe.reconnect)()||this.rejected()}catch(e){this.logger.log(en.Error,e),this.failed()}})),this.reloadParagraph.querySelector("a").addEventListener("click",(()=>location.reload()))}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",this.message.innerHTML="Reconnection failed. Try reloading the page if you're unable to reconnect.",this.message.querySelector("a").addEventListener("click",(()=>location.reload()))}rejected(){this.button.style.display="none",this.reloadParagraph.style.display="none",this.loader.style.display="none",this.message.innerHTML="Could not reconnect to the server. Reload the page to restore functionality.",this.message.querySelector("a").addEventListener("click",(()=>location.reload()))}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 cn{constructor(e,t,n){this.dialog=e,this.maxRetries=t,this.document=n,this.document=n;const r=this.document.getElementById(cn.MaxRetriesId);r&&(r.innerText=this.maxRetries.toString())}show(){this.removeClasses(),this.dialog.classList.add(cn.ShowClassName)}update(e){const t=this.document.getElementById(cn.CurrentAttemptId);t&&(t.innerText=e.toString())}hide(){this.removeClasses(),this.dialog.classList.add(cn.HideClassName)}failed(){this.removeClasses(),this.dialog.classList.add(cn.FailedClassName)}rejected(){this.removeClasses(),this.dialog.classList.add(cn.RejectedClassName)}removeClasses(){this.dialog.classList.remove(cn.ShowClassName,cn.HideClassName,cn.FailedClassName,cn.RejectedClassName)}}cn.ShowClassName="components-reconnect-show",cn.HideClassName="components-reconnect-hide",cn.FailedClassName="components-reconnect-failed",cn.RejectedClassName="components-reconnect-rejected",cn.MaxRetriesId="components-reconnect-max-retries",cn.CurrentAttemptId="components-reconnect-current-attempt";class ln{constructor(e,t,n){this._currentReconnectionProcess=null,this._logger=e,this._reconnectionDisplay=t,this._reconnectCallback=n||(()=>fe.reconnect())}onConnectionDown(e,t){if(!this._reconnectionDisplay){const t=document.getElementById(e.dialogId);this._reconnectionDisplay=t?new cn(t,e.maxRetries,document):new an(e.dialogId,e.maxRetries,document,this._logger)}this._currentReconnectionProcess||(this._currentReconnectionProcess=new hn(e,this._logger,this._reconnectCallback,this._reconnectionDisplay))}onConnectionUp(){this._currentReconnectionProcess&&(this._currentReconnectionProcess.dispose(),this._currentReconnectionProcess=null)}}class hn{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;thn.MaximumFirstRetryInterval?hn.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(en.Error,e)}}this.reconnectDisplay.failed()}delay(e){return new Promise((t=>setTimeout(t,e)))}}hn.MaximumFirstRetryInterval=3e3;const un=/^\s*Blazor-Component-State:(?[a-zA-Z0-9\+\/=]+)$/;function dn(e){var t;if(e.nodeType===Node.COMMENT_NODE){const n=e.textContent||"",r=un.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 gn(e,t){const n=e.currentElement;if(n&&n.nodeType===Node.COMMENT_NODE&&n.textContent){const r=fn.exec(n.textContent),o=r&&r.groups&&r.groups.descriptor;if(!o)return;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;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.");if(c){const e=mn(c,n);if(!e)throw new Error(`Could not find an end component comment for '${t}'`);return{type:r,assembly:o,typeName:i,parameterDefinitions:s&&atob(s),parameterValues:a&&atob(a),start:t,prerenderId:c,end:e}}return{type:r,assembly:o,typeName:i,parameterDefinitions:s&&atob(s),parameterValues:a&&atob(a),start:t}}}(r,n,e);case"server":return function(e,t,n){const{type:r,descriptor:o,sequence:i,prerenderId:s}=e;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)}'`);if(s){const e=mn(s,n);if(!e)throw new Error(`Could not find an end component comment for '${t}'`);return{type:r,sequence:i,descriptor:o,start:t,prerenderId:s,end:e}}return{type:r,sequence:i,descriptor:o,start:t}}}(r,n,e)}}catch(e){throw new Error(`Found malformed component comment at ${n.textContent}`)}}}function mn(e,t){for(;t.next()&&t.currentElement;){const n=t.currentElement;if(n.nodeType!==Node.COMMENT_NODE)continue;if(!n.textContent)continue;const r=fn.exec(n.textContent),o=r&&r[1];if(o)return yn(o,e),n}}function yn(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 wn{constructor(e){this.childNodes=e,this.currentIndex=-1,this.length=e.length}next(){return this.currentIndex++,this.currentIndexe.sequence-t.sequence))}(e)}(document),o=dn(document),i=new on(r,o||""),s=await Tn(t,n,i);if(!await i.startCircuit(s))return void n.log(en.Error,"Failed to start the circuit.");let a=!1;const c=()=>{if(!a){const e=new FormData,t=i.circuitId;e.append("circuitId",t),a=navigator.sendBeacon("_blazor/disconnect",e)}};fe.disconnect=c,window.addEventListener("unload",c,{capture:!1,once:!0}),fe.reconnect=async e=>{if(Cn)return!1;const r=e||await Tn(t,n,i);return await i.reconnect(r)?(t.reconnectionHandler.onConnectionUp(),!0):(n.log(en.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)},n.log(en.Information,"Blazor server-side application started.")}async function Tn(t,n,r){const i=new Mt;i.name="blazorpack";const s=(new rt).withUrl("_blazor").withHubProtocol(i);t.configureSignalR(s);const a=s.build();o=(e,t)=>{a.send("DispatchBrowserEvent",JSON.stringify(e),JSON.stringify(t))},fe._internal.navigationManager.listenForNavigationEvents(((e,t)=>a.send("OnLocationChanged",e,t))),a.on("JS.AttachComponent",((e,t)=>function(e,t,n){let r=Q[0];r||(r=Q[0]=new V(0)),r.attachRootComponentToLogicalElement(n,t)}(0,r.resolveElement(t),e))),a.on("JS.BeginInvokeJS",e.jsCallDispatcher.beginInvokeJSFromDotNet),a.on("JS.EndInvokeDotNet",e.jsCallDispatcher.endInvokeDotNetFromJS),a.on("JS.ReceiveByteArray",e.jsCallDispatcher.receiveByteArray);const c=tn.getOrCreate(n);a.on("JS.RenderBatch",((e,t)=>{n.log(en.Debug,`Received render batch with id ${e} and ${t.byteLength} bytes.`),c.processBatch(e,t,a)})),a.onclose((e=>!Cn&&t.reconnectionHandler.onConnectionDown(t.reconnectionOptions,e))),a.on("JS.Error",(e=>{Cn=!0,xn(a,e,n),async function(){let e=document.querySelector("#blazor-error-ui");e&&(e.style.display="block"),Ot||(Ot=!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()}})))}()})),fe._internal.forceCloseConnection=()=>a.stop(),fe._internal.sendJSDataStream=(e,t,n)=>function(e,t,n,r){setTimeout((async()=>{let o=5,i=(new Date).valueOf();try{let s=0,a=0;for(;s1)await e.send("ReceiveJSDataChunk",n,a,l,null);else{if(!await e.invoke("ReceiveJSDataChunk",n,a,l,null))break;const t=(new Date).valueOf(),r=t-i;i=t,o=Math.max(1,Math.round(500/Math.max(1,r)))}s+=c,a++}}catch(t){await e.send("ReceiveJSDataChunk",n,-1,null,t.toString())}}),0)}(a,e,t,n);try{await a.start()}catch(e){xn(a,e,n)}return e.attachDispatcher({beginInvokeDotNetFromJS:(e,t,n,r,o)=>{a.send("BeginInvokeDotNetFromJS",e?e.toString():null,t,n,r||0,o)},endInvokeJSFromDotNet:(e,t,n)=>{a.send("EndInvokeJSFromDotNet",e,t,n)},sendByteArray:(e,t)=>{a.send("ReceiveByteArray",e,t)}}),a}function xn(e,t,n){n.log(en.Error,t),e&&e.stop()}fe.start=kn,document&&document.currentScript&&"false"!==document.currentScript.getAttribute("autostart")&&kn()})(); \ 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 7ba8522cc3e8..3b575e10f03e 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;!function(e){window.DotNet=e;const t=[],n=new Map;class r{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 o="__jsObjectId",a={},i={0:new r(window)};i[0]._cachedFunctions.set("import",(e=>("string"==typeof e&&e.startsWith("./")&&(e=document.baseURI+e.substr(2)),import(e))));let s,c=1,l=1,u=null;function d(e){t.push(e)}function h(e){if(e&&"object"==typeof e){i[l]=new r(e);const t={[o]:l};return l++,t}throw new Error(`Cannot create a JSObjectReference from the value '${e}'.`)}function f(e){if(!(e.buffer instanceof ArrayBuffer))throw new Error(`Cannot create a JSStreamReference from the value '${e}' as it is not a valid ArrayBuffer.`);if(void 0===e.byteLength)throw new Error(`Cannot create a JSStreamReference from the value '${e}' as it doesn't have a byteLength.`);const t={__jsStreamReferenceLength:e.byteLength-5};try{const n=h(e);t.__jsObjectId=n.__jsObjectId}catch{throw new Error(`Cannot create a JSStreamReference from the value '${e}'.`)}return t}function m(e){return e?JSON.parse(e,((e,n)=>t.reduce(((t,n)=>n(e,t)),n))):null}function p(e,t,n,r){const o=g();if(o.invokeDotNetFromJS){const a=D(r),i=o.invokeDotNetFromJS(e,t,n,a);return i?m(i):null}throw new Error("The current dispatcher does not support synchronous calls from JS to .NET. Use invokeMethodAsync instead.")}function v(e,t,n,r){if(e&&n)throw new Error(`For instance method calls, assemblyName should be null. Received '${e}'.`);const o=c++,i=new Promise(((e,t)=>{a[o]={resolve:e,reject:t}}));try{const a=D(r);g().beginInvokeDotNetFromJS(o,e,t,n,a)}catch(e){b(o,!1,e)}return i}function g(){if(null!==u)return u;throw new Error("No .NET call dispatcher has been set.")}function b(e,t,n){if(!a.hasOwnProperty(e))throw new Error(`There is no pending async call with ID ${e}.`);const r=a[e];delete a[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){let n=i[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 i[e]}e.attachDispatcher=function(e){u=e},e.attachReviver=d,e.invokeMethod=function(e,t,...n){return p(e,t,null,n)},e.invokeMethodAsync=function(e,t,...n){return v(e,t,null,n)},e.createJSObjectReference=h,e.createJSStreamReference=f,e.disposeJSObjectReference=function(e){const t=e&&e.__jsObjectId;"number"==typeof t&&E(t)},function(e){e[e.Default=0]="Default",e[e.JSObjectReference=1]="JSObjectReference",e[e.JSStreamReference=2]="JSStreamReference"}(s=e.JSCallResultType||(e.JSCallResultType={})),e.jsCallDispatcher={findJSFunction:w,disposeJSObjectReferenceById:E,invokeJSFromDotNet:(e,t,n,r)=>{const o=C(w(e,r).apply(null,m(t)),n);return null==o?null:D(o)},beginInvokeJSFromDotNet:(e,t,n,r,o)=>{const a=new Promise((e=>{e(w(t,o).apply(null,m(n)))}));e&&a.then((t=>g().endInvokeJSFromDotNet(e,!0,D([e,!0,C(t,r)]))),(t=>g().endInvokeJSFromDotNet(e,!1,JSON.stringify([e,!1,y(t)]))))},endInvokeDotNetFromJS:(e,t,n)=>{const r=t?m(n):new Error(n);b(parseInt(e),t,r)},receiveByteArray:(e,t)=>{n.set(e,t)}};class I{constructor(e){this._id=e}invokeMethod(e,...t){return p(null,e,this._id,t)}invokeMethodAsync(e,...t){return v(null,e,this._id,t)}dispose(){v(null,"__Dispose",this._id,null).catch((e=>console.error(e)))}serializeAsArg(){return{__dotNetObject:this._id}}}const S="__byte[]";function C(e,t){switch(t){case s.Default:return e;case s.JSObjectReference:return h(e);case s.JSStreamReference:return f(e);default:throw new Error(`Invalid JS call result type '${t}'.`)}}d((function(e,t){if(t&&"object"==typeof t){if(t.hasOwnProperty("__dotNetObject"))return new I(t.__dotNetObject);if(t.hasOwnProperty(o)){const e=t.__jsObjectId,n=i[e];if(n)return n.getWrappedObject();throw new Error(`JS object instance with Id '${e}' does not exist. It may have been disposed.`)}if(t.hasOwnProperty(S)){const e=t["__byte[]"],r=n.get(e);if(void 0===r)throw new Error(`Byte array index '${e}' does not exist.`);return r}}return t}));let A=0;function D(e){return A=0,JSON.stringify(e,T)}function T(e,t){if(t instanceof I)return t.serializeAsArg();if(t instanceof Uint8Array){u.sendByteArray(A,t);const e={[S]: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"}(n||(n={}));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}}let o;function a(e,t){if(!o)throw new Error("eventDispatcher not initialized. Call 'setEventDispatcher' to configure it.");o(e,t)}const i=new Map,s=new Map,c={createEventArgs:()=>({})},l=[];function u(e){return i.get(e)}function d(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 f(e){const t=[];for(let n=0;n{return{...m(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"],c),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};var t}}),h(["contextmenu","click","mouseover","mouseout","mousemove","mousedown","mouseup","dblclick"],{createEventArgs:e=>m(e)}),h(["error"],{createEventArgs:e=>{return{message:(t=e).message,filename:t.filename,lineno:t.lineno,colno:t.colno};var t}}),h(["loadstart","timeout","abort","load","loadend","progress"],{createEventArgs:e=>{return{lengthComputable:(t=e).lengthComputable,loaded:t.loaded,total:t.total};var t}}),h(["touchcancel","touchend","touchmove","touchenter","touchleave","touchstart"],{createEventArgs:e=>{return{detail:(t=e).detail,touches:f(t.touches),targetTouches:f(t.targetTouches),changedTouches:f(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{...m(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{...m(t=e),deltaX:t.deltaX,deltaY:t.deltaY,deltaZ:t.deltaZ,deltaMode:t.deltaMode};var t}}),h(["toggle"],c);const p=["date","datetime-local","month","time","week"],v=I(["abort","blur","change","error","focus","load","loadend","loadstart","mouseenter","mouseleave","progress","reset","scroll","submit","unload","toggle","DOMNodeInsertedIntoDocument","DOMNodeRemovedFromDocument"]),g={submit:!0},b=I(["click","dblclick","mousedown","mousemove","mouseup"]);class y{constructor(e){this.browserRendererId=e,this.afterClickCallbacks=[];const t=++y.nextEventDelegatorId;this.eventsCollectionKey=`_blazorEvents_${t}`,this.eventInfoStore=new w(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){let n=t.target,o=null,i=!1;const s=v.hasOwnProperty(e);let c=!1;for(;n;){const h=this.getEventHandlerInfosForElement(n,!1);if(h){const s=h.getHandler(e);if(s&&(l=n,d=t.type,!((l instanceof HTMLButtonElement||l instanceof HTMLInputElement||l instanceof HTMLTextAreaElement||l instanceof HTMLSelectElement)&&b.hasOwnProperty(d)&&l.disabled))){if(!i){const n=u(e);o=(null==n?void 0:n.createEventArgs)?n.createEventArgs(t):{},i=!0}g.hasOwnProperty(t.type)&&t.preventDefault(),a({browserRendererId:this.browserRendererId,eventHandlerId:s.eventHandlerId,eventName:e,eventFieldInfo:r.fromEvent(s.renderingComponentId,t)},o)}h.stopPropagation(e)&&(c=!0),h.preventDefault(e)&&t.preventDefault()}n=s||c?null:n.parentElement}var l,d}getEventHandlerInfosForElement(e,t){return e.hasOwnProperty(this.eventsCollectionKey)?e[this.eventsCollectionKey]:t?e[this.eventsCollectionKey]=new E:null}}y.nextEventDelegatorId=0;class w{constructor(e){this.globalListener=e,this.infosByEventHandlerId={},this.countByEventName={},l.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=d(e),this.countByEventName.hasOwnProperty(e))this.countByEventName[e]++;else{this.countByEventName[e]=1;const t=v.hasOwnProperty(e);document.addEventListener(e,this.globalListener,t)}}update(e,t){if(this.infosByEventHandlerId.hasOwnProperty(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=d(t.eventName);0==--this.countByEventName[n]&&(delete this.countByEventName[n],document.removeEventListener(n,this.globalListener))}return t}handleEventNameAliasAdded(e,t){if(this.countByEventName.hasOwnProperty(e)){const n=this.countByEventName[e];delete this.countByEventName[e],document.removeEventListener(e,this.globalListener),this.addGlobalListener(t),this.countByEventName[t]+=n-1}}}class E{constructor(){this.handlers={},this.preventDefaultFlags=null,this.stopPropagationFlags=null}getHandler(e){return this.handlers.hasOwnProperty(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 I(e){const t={};return e.forEach((e=>{t[e]=!0})),t}const S=M("_blazorLogicalChildren"),C=M("_blazorLogicalParent"),A=M("_blazorLogicalEnd");function D(e,t){if(e.childNodes.length>0&&!t)throw new Error("New logical elements must start empty, or allowExistingContents must be true");return S in e||(e[S]=[]),e}function T(e,t){const n=document.createComment("!");return N(n,e,t),n}function N(e,t,n){const r=e;if(e instanceof Comment&&O(r)&&O(r).length>0)throw new Error("Not implemented: inserting non-empty logical container");if(k(r))throw new Error("Not implemented: moving existing logical children");const o=O(t);if(n0;)R(n,0)}const r=n;r.parentNode.removeChild(r)}function k(e){return e[C]||null}function F(e,t){return O(e)[t]}function _(e){var t=B(e);return"http://www.w3.org/2000/svg"===t.namespaceURI&&"foreignObject"!==t.tagName}function O(e){return e[S]}function x(e,t){const n=O(e);t.forEach((e=>{e.moveRangeStart=n[e.fromSiblingIndex],e.moveRangeEnd=H(e.moveRangeStart)})),t.forEach((t=>{const r=t.moveToBeforeMarker=document.createComment("marker"),o=n[t.toSiblingIndex+1];o?o.parentNode.insertBefore(r,o):P(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 B(e){if(e instanceof Element)return e;if(e instanceof Comment)return e.parentNode;throw new Error("Not a valid logical element")}function L(e){const t=O(k(e));return t[Array.prototype.indexOf.call(t,e)+1]||null}function P(e,t){if(t instanceof Element)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=L(t);n?n.parentNode.insertBefore(e,n):P(e,k(t))}}}function H(e){if(e instanceof Element)return e;const t=L(e);if(t)return t.previousSibling;{const t=k(e);return t instanceof Element?t.lastChild:H(t)}}function M(e){return"function"==typeof Symbol?Symbol():e}function U(e){return`_bl_${e}`}e.attachReviver(((e,t)=>t&&"object"==typeof t&&t.hasOwnProperty("__internalId")&&"string"==typeof t.__internalId?function(e){const t=`[${U(e)}]`;return document.querySelector(t)}(t.__internalId):t));const j="_blazorSelectValue",J=document.createElement("template"),$=document.createElementNS("http://www.w3.org/2000/svg","g"),K={},z="__internal_",V="preventDefault_",X="stopPropagation_";class Y{constructor(e){this.childComponentLocations={},this.eventDelegator=new y(e),this.eventDelegator.notifyAfterClick((e=>{if(!ee)return;if(0!==e.button||function(e){return e.ctrlKey||e.shiftKey||e.altKey||e.metaKey}(e))return;if(e.defaultPrevented)return;const t=function(e){const t=!window._blazorDisableComposedPath&&e.composedPath&&e.composedPath();if(t){for(let e=0;eie(!1))))},enableNavigationInterception:function(){ee=!0},navigateTo:oe,getBaseURI:()=>document.baseURI,getLocationHref:()=>location.href};function oe(e,t,n=!1){const r=ce(e);if(!t&&ue(r))ae(r,!1,n);else if(t&&location.href===e){const t=e+"?";history.replaceState(null,"",t),location.replace(e)}else n?history.replaceState(null,"",r):location.href=e}function ae(e,t,n=!1){Q=!0,n?history.replaceState(null,"",e):history.pushState(null,"",e),ie(t)}async function ie(e){ne&&await ne(location.href,e)}let se;function ce(e){return se=se||document.createElement("a"),se.href=e,se.href}function le(e,t){return e?e.tagName===t?e:le(e.parentElement,t):null}function ue(e){const t=(n=document.baseURI).substr(0,n.lastIndexOf("/")+1);var n;return e.startsWith(t)}const de={init:function(e,t,n,r=50){const o=fe(t);(o||document.documentElement).style.overflowAnchor="none";const a=new IntersectionObserver((function(r){r.forEach((r=>{var o;if(!r.isIntersecting)return;const a=t.getBoundingClientRect(),i=n.getBoundingClientRect().top-a.bottom,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`});a.observe(t),a.observe(n);const i=c(t),s=c(n);function c(e){const t=new MutationObserver((()=>{a.unobserve(e),a.observe(e)}));return t.observe(e,{attributes:!0}),t}he[e._id]={intersectionObserver:a,mutationObserverBefore:i,mutationObserverAfter:s}},dispose:function(e){const t=he[e._id];t&&(t.intersectionObserver.disconnect(),t.mutationObserverBefore.disconnect(),t.mutationObserverAfter.disconnect(),e.dispose(),delete he[e._id])}},he={};function fe(e){return e?"visible"!==getComputedStyle(e).overflowY?e:fe(e.parentElement):null}const me={navigateTo:oe,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]),l.forEach((n=>n(e,t.browserEventName)))}i.set(e,t)},_internal:{navigationManager:re,domWrapper:{focus:function(e,t){if(!(e instanceof HTMLElement))throw new Error("Unable to focus an invalid element.");e.focus({preventScroll:t})},focusBySelector:function(e){const t=document.querySelector(e);t&&(t.hasAttribute("tabindex")||(t.tabIndex=-1),t.focus())}},Virtualize:de}};window.Blazor=me;let pe=!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("")},be=Math.pow(2,32),ye=Math.pow(2,21)-1;function we(e,t){return e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24}function Ee(e,t){return e[t]+(e[t+1]<<8)+(e[t+2]<<16)+(e[t+3]<<24>>>0)}function Ie(e,t){const n=Ee(e,t+4);if(n>ye)throw new Error(`Cannot read uint64 with high order part ${n}, because the result would exceed Number.MAX_SAFE_INTEGER.`);return n*be+Ee(e,t)}class Se{constructor(e){this.batchData=e;const t=new Te(e);this.arrayRangeReader=new Ne(e),this.arrayBuilderSegmentReader=new Re(e),this.diffReader=new Ce(e),this.editReader=new Ae(e,t),this.frameReader=new De(e,t)}updatedComponents(){return we(this.batchData,this.batchData.length-20)}referenceFrames(){return we(this.batchData,this.batchData.length-16)}disposedComponentIds(){return we(this.batchData,this.batchData.length-12)}disposedEventHandlerIds(){return we(this.batchData,this.batchData.length-8)}updatedComponentsEntry(e,t){const n=e+4*t;return we(this.batchData,n)}referenceFramesEntry(e,t){return e+20*t}disposedComponentIdsEntry(e,t){const n=e+4*t;return we(this.batchData,n)}disposedEventHandlerIdsEntry(e,t){const n=e+8*t;return Ie(this.batchData,n)}}class Ce{constructor(e){this.batchDataUint8=e}componentId(e){return we(this.batchDataUint8,e)}edits(e){return e+4}editsEntry(e,t){return e+16*t}}class Ae{constructor(e,t){this.batchDataUint8=e,this.stringReader=t}editType(e){return we(this.batchDataUint8,e)}siblingIndex(e){return we(this.batchDataUint8,e+4)}newTreeIndex(e){return we(this.batchDataUint8,e+8)}moveToSiblingIndex(e){return we(this.batchDataUint8,e+8)}removedAttributeName(e){const t=we(this.batchDataUint8,e+12);return this.stringReader.readString(t)}}class De{constructor(e,t){this.batchDataUint8=e,this.stringReader=t}frameType(e){return we(this.batchDataUint8,e)}subtreeLength(e){return we(this.batchDataUint8,e+4)}elementReferenceCaptureId(e){const t=we(this.batchDataUint8,e+4);return this.stringReader.readString(t)}componentId(e){return we(this.batchDataUint8,e+8)}elementName(e){const t=we(this.batchDataUint8,e+8);return this.stringReader.readString(t)}textContent(e){const t=we(this.batchDataUint8,e+4);return this.stringReader.readString(t)}markupContent(e){const t=we(this.batchDataUint8,e+4);return this.stringReader.readString(t)}attributeName(e){const t=we(this.batchDataUint8,e+4);return this.stringReader.readString(t)}attributeValue(e){const t=we(this.batchDataUint8,e+8);return this.stringReader.readString(t)}attributeEventHandlerId(e){return Ie(this.batchDataUint8,e+12)}}class Te{constructor(e){this.batchDataUint8=e,this.stringTableStartIndex=we(e,e.length-4)}readString(e){if(-1===e)return null;{const n=we(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)<{!function(e,t,n){const r=document.querySelector(e);if(!r)throw new Error(`Could not find any element matching selector '${e}'.`);!function(e,t,n){let r=Z[0];r||(r=Z[0]=new Y(0)),r.attachRootComponentToLogicalElement(n,t)}(0,D(r,!0),t)}(t,e)},RenderBatch:(e,t)=>{try{const n=Me(t);(function(e,t){const n=Z[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{Fe=!0,console.error(`${e}\n${t}`),async function(){let e=document.querySelector("#blazor-error-ui");e&&(e.style.display="block"),pe||(pe=!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:e.jsCallDispatcher.beginInvokeJSFromDotNet,EndInvokeDotNet:e.jsCallDispatcher.endInvokeDotNetFromJS,SendByteArrayToJS:He,Navigate:re.navigateTo};window.external.receiveMessage((e=>{const n=function(e){if(Fe||!e||!e.startsWith(ke))return null;const t=e.substring(ke.length),[n,...r]=JSON.parse(t);return{messageType:n,args:r}}(e);if(n){if(!t.hasOwnProperty(n.messageType))throw new Error(`Unsupported IPC message type '${n.messageType}'`);t[n.messageType].apply(null,n.args)}}))}(),e.attachDispatcher({beginInvokeDotNetFromJS:Oe,endInvokeJSFromDotNet:xe,sendByteArray:Be}),me._internal.InputFile=Ue,re.enableNavigationInterception(),re.listenForNavigationEvents(Le),Pe("AttachPage",re.getBaseURI(),re.getLocationHref())}o=function(e,t){Pe("DispatchBrowserEvent",e,t)},me.start=Ke,document&&document.currentScript&&"false"!==document.currentScript.getAttribute("autostart")&&Ke()})(); \ No newline at end of file +(()=>{"use strict";var e,t,n;!function(e){window.DotNet=e;const t=[],n=new Map;class r{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 o="__jsObjectId",a={},i={0:new r(window)};i[0]._cachedFunctions.set("import",(e=>("string"==typeof e&&e.startsWith("./")&&(e=document.baseURI+e.substr(2)),import(e))));let s,c=1,l=1,u=null;function d(e){t.push(e)}function h(e){if(e&&"object"==typeof e){i[l]=new r(e);const t={[o]:l};return l++,t}throw new Error(`Cannot create a JSObjectReference from the value '${e}'.`)}function f(e){if(!(e.buffer instanceof ArrayBuffer))throw new Error(`Cannot create a JSStreamReference from the value '${e}' as it is not a valid ArrayBuffer.`);if(void 0===e.byteLength)throw new Error(`Cannot create a JSStreamReference from the value '${e}' as it doesn't have a byteLength.`);const t={__jsStreamReferenceLength:e.byteLength};try{const n=h(e);t.__jsObjectId=n.__jsObjectId}catch{throw new Error(`Cannot create a JSStreamReference from the value '${e}'.`)}return t}function m(e){return e?JSON.parse(e,((e,n)=>t.reduce(((t,n)=>n(e,t)),n))):null}function p(e,t,n,r){const o=g();if(o.invokeDotNetFromJS){const a=D(r),i=o.invokeDotNetFromJS(e,t,n,a);return i?m(i):null}throw new Error("The current dispatcher does not support synchronous calls from JS to .NET. Use invokeMethodAsync instead.")}function v(e,t,n,r){if(e&&n)throw new Error(`For instance method calls, assemblyName should be null. Received '${e}'.`);const o=c++,i=new Promise(((e,t)=>{a[o]={resolve:e,reject:t}}));try{const a=D(r);g().beginInvokeDotNetFromJS(o,e,t,n,a)}catch(e){b(o,!1,e)}return i}function g(){if(null!==u)return u;throw new Error("No .NET call dispatcher has been set.")}function b(e,t,n){if(!a.hasOwnProperty(e))throw new Error(`There is no pending async call with ID ${e}.`);const r=a[e];delete a[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){let n=i[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 i[e]}e.attachDispatcher=function(e){u=e},e.attachReviver=d,e.invokeMethod=function(e,t,...n){return p(e,t,null,n)},e.invokeMethodAsync=function(e,t,...n){return v(e,t,null,n)},e.createJSObjectReference=h,e.createJSStreamReference=f,e.disposeJSObjectReference=function(e){const t=e&&e.__jsObjectId;"number"==typeof t&&E(t)},function(e){e[e.Default=0]="Default",e[e.JSObjectReference=1]="JSObjectReference",e[e.JSStreamReference=2]="JSStreamReference"}(s=e.JSCallResultType||(e.JSCallResultType={})),e.jsCallDispatcher={findJSFunction:w,disposeJSObjectReferenceById:E,invokeJSFromDotNet:(e,t,n,r)=>{const o=C(w(e,r).apply(null,m(t)),n);return null==o?null:D(o)},beginInvokeJSFromDotNet:(e,t,n,r,o)=>{const a=new Promise((e=>{e(w(t,o).apply(null,m(n)))}));e&&a.then((t=>g().endInvokeJSFromDotNet(e,!0,D([e,!0,C(t,r)]))),(t=>g().endInvokeJSFromDotNet(e,!1,JSON.stringify([e,!1,y(t)]))))},endInvokeDotNetFromJS:(e,t,n)=>{const r=t?m(n):new Error(n);b(parseInt(e),t,r)},receiveByteArray:(e,t)=>{n.set(e,t)}};class I{constructor(e){this._id=e}invokeMethod(e,...t){return p(null,e,this._id,t)}invokeMethodAsync(e,...t){return v(null,e,this._id,t)}dispose(){v(null,"__Dispose",this._id,null).catch((e=>console.error(e)))}serializeAsArg(){return{__dotNetObject:this._id}}}const S="__byte[]";function C(e,t){switch(t){case s.Default:return e;case s.JSObjectReference:return h(e);case s.JSStreamReference:return f(e);default:throw new Error(`Invalid JS call result type '${t}'.`)}}d((function(e,t){if(t&&"object"==typeof t){if(t.hasOwnProperty("__dotNetObject"))return new I(t.__dotNetObject);if(t.hasOwnProperty(o)){const e=t.__jsObjectId,n=i[e];if(n)return n.getWrappedObject();throw new Error(`JS object instance with Id '${e}' does not exist. It may have been disposed.`)}if(t.hasOwnProperty(S)){const e=t["__byte[]"],r=n.get(e);if(void 0===r)throw new Error(`Byte array index '${e}' does not exist.`);return r}}return t}));let A=0;function D(e){return A=0,JSON.stringify(e,T)}function T(e,t){if(t instanceof I)return t.serializeAsArg();if(t instanceof Uint8Array){u.sendByteArray(A,t);const e={[S]: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"}(n||(n={}));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}}let o;function a(e,t){if(!o)throw new Error("eventDispatcher not initialized. Call 'setEventDispatcher' to configure it.");o(e,t)}const i=new Map,s=new Map,c={createEventArgs:()=>({})},l=[];function u(e){return i.get(e)}function d(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 f(e){const t=[];for(let n=0;n{return{...m(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"],c),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};var t}}),h(["contextmenu","click","mouseover","mouseout","mousemove","mousedown","mouseup","dblclick"],{createEventArgs:e=>m(e)}),h(["error"],{createEventArgs:e=>{return{message:(t=e).message,filename:t.filename,lineno:t.lineno,colno:t.colno};var t}}),h(["loadstart","timeout","abort","load","loadend","progress"],{createEventArgs:e=>{return{lengthComputable:(t=e).lengthComputable,loaded:t.loaded,total:t.total};var t}}),h(["touchcancel","touchend","touchmove","touchenter","touchleave","touchstart"],{createEventArgs:e=>{return{detail:(t=e).detail,touches:f(t.touches),targetTouches:f(t.targetTouches),changedTouches:f(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{...m(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{...m(t=e),deltaX:t.deltaX,deltaY:t.deltaY,deltaZ:t.deltaZ,deltaMode:t.deltaMode};var t}}),h(["toggle"],c);const p=["date","datetime-local","month","time","week"],v=I(["abort","blur","change","error","focus","load","loadend","loadstart","mouseenter","mouseleave","progress","reset","scroll","submit","unload","toggle","DOMNodeInsertedIntoDocument","DOMNodeRemovedFromDocument"]),g={submit:!0},b=I(["click","dblclick","mousedown","mousemove","mouseup"]);class y{constructor(e){this.browserRendererId=e,this.afterClickCallbacks=[];const t=++y.nextEventDelegatorId;this.eventsCollectionKey=`_blazorEvents_${t}`,this.eventInfoStore=new w(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){let n=t.target,o=null,i=!1;const s=v.hasOwnProperty(e);let c=!1;for(;n;){const h=this.getEventHandlerInfosForElement(n,!1);if(h){const s=h.getHandler(e);if(s&&(l=n,d=t.type,!((l instanceof HTMLButtonElement||l instanceof HTMLInputElement||l instanceof HTMLTextAreaElement||l instanceof HTMLSelectElement)&&b.hasOwnProperty(d)&&l.disabled))){if(!i){const n=u(e);o=(null==n?void 0:n.createEventArgs)?n.createEventArgs(t):{},i=!0}g.hasOwnProperty(t.type)&&t.preventDefault(),a({browserRendererId:this.browserRendererId,eventHandlerId:s.eventHandlerId,eventName:e,eventFieldInfo:r.fromEvent(s.renderingComponentId,t)},o)}h.stopPropagation(e)&&(c=!0),h.preventDefault(e)&&t.preventDefault()}n=s||c?null:n.parentElement}var l,d}getEventHandlerInfosForElement(e,t){return e.hasOwnProperty(this.eventsCollectionKey)?e[this.eventsCollectionKey]:t?e[this.eventsCollectionKey]=new E:null}}y.nextEventDelegatorId=0;class w{constructor(e){this.globalListener=e,this.infosByEventHandlerId={},this.countByEventName={},l.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=d(e),this.countByEventName.hasOwnProperty(e))this.countByEventName[e]++;else{this.countByEventName[e]=1;const t=v.hasOwnProperty(e);document.addEventListener(e,this.globalListener,t)}}update(e,t){if(this.infosByEventHandlerId.hasOwnProperty(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=d(t.eventName);0==--this.countByEventName[n]&&(delete this.countByEventName[n],document.removeEventListener(n,this.globalListener))}return t}handleEventNameAliasAdded(e,t){if(this.countByEventName.hasOwnProperty(e)){const n=this.countByEventName[e];delete this.countByEventName[e],document.removeEventListener(e,this.globalListener),this.addGlobalListener(t),this.countByEventName[t]+=n-1}}}class E{constructor(){this.handlers={},this.preventDefaultFlags=null,this.stopPropagationFlags=null}getHandler(e){return this.handlers.hasOwnProperty(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 I(e){const t={};return e.forEach((e=>{t[e]=!0})),t}const S=M("_blazorLogicalChildren"),C=M("_blazorLogicalParent"),A=M("_blazorLogicalEnd");function D(e,t){if(e.childNodes.length>0&&!t)throw new Error("New logical elements must start empty, or allowExistingContents must be true");return S in e||(e[S]=[]),e}function T(e,t){const n=document.createComment("!");return N(n,e,t),n}function N(e,t,n){const r=e;if(e instanceof Comment&&O(r)&&O(r).length>0)throw new Error("Not implemented: inserting non-empty logical container");if(k(r))throw new Error("Not implemented: moving existing logical children");const o=O(t);if(n0;)R(n,0)}const r=n;r.parentNode.removeChild(r)}function k(e){return e[C]||null}function F(e,t){return O(e)[t]}function _(e){var t=B(e);return"http://www.w3.org/2000/svg"===t.namespaceURI&&"foreignObject"!==t.tagName}function O(e){return e[S]}function x(e,t){const n=O(e);t.forEach((e=>{e.moveRangeStart=n[e.fromSiblingIndex],e.moveRangeEnd=H(e.moveRangeStart)})),t.forEach((t=>{const r=t.moveToBeforeMarker=document.createComment("marker"),o=n[t.toSiblingIndex+1];o?o.parentNode.insertBefore(r,o):P(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 B(e){if(e instanceof Element)return e;if(e instanceof Comment)return e.parentNode;throw new Error("Not a valid logical element")}function L(e){const t=O(k(e));return t[Array.prototype.indexOf.call(t,e)+1]||null}function P(e,t){if(t instanceof Element)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=L(t);n?n.parentNode.insertBefore(e,n):P(e,k(t))}}}function H(e){if(e instanceof Element)return e;const t=L(e);if(t)return t.previousSibling;{const t=k(e);return t instanceof Element?t.lastChild:H(t)}}function M(e){return"function"==typeof Symbol?Symbol():e}function U(e){return`_bl_${e}`}e.attachReviver(((e,t)=>t&&"object"==typeof t&&t.hasOwnProperty("__internalId")&&"string"==typeof t.__internalId?function(e){const t=`[${U(e)}]`;return document.querySelector(t)}(t.__internalId):t));const j="_blazorSelectValue",J=document.createElement("template"),$=document.createElementNS("http://www.w3.org/2000/svg","g"),K={},z="__internal_",V="preventDefault_",X="stopPropagation_";class Y{constructor(e){this.childComponentLocations={},this.eventDelegator=new y(e),this.eventDelegator.notifyAfterClick((e=>{if(!ee)return;if(0!==e.button||function(e){return e.ctrlKey||e.shiftKey||e.altKey||e.metaKey}(e))return;if(e.defaultPrevented)return;const t=function(e){const t=!window._blazorDisableComposedPath&&e.composedPath&&e.composedPath();if(t){for(let e=0;eie(!1))))},enableNavigationInterception:function(){ee=!0},navigateTo:oe,getBaseURI:()=>document.baseURI,getLocationHref:()=>location.href};function oe(e,t,n=!1){const r=ce(e);if(!t&&ue(r))ae(r,!1,n);else if(t&&location.href===e){const t=e+"?";history.replaceState(null,"",t),location.replace(e)}else n?history.replaceState(null,"",r):location.href=e}function ae(e,t,n=!1){Q=!0,n?history.replaceState(null,"",e):history.pushState(null,"",e),ie(t)}async function ie(e){ne&&await ne(location.href,e)}let se;function ce(e){return se=se||document.createElement("a"),se.href=e,se.href}function le(e,t){return e?e.tagName===t?e:le(e.parentElement,t):null}function ue(e){const t=(n=document.baseURI).substr(0,n.lastIndexOf("/")+1);var n;return e.startsWith(t)}const de={init:function(e,t,n,r=50){const o=fe(t);(o||document.documentElement).style.overflowAnchor="none";const a=new IntersectionObserver((function(r){r.forEach((r=>{var o;if(!r.isIntersecting)return;const a=t.getBoundingClientRect(),i=n.getBoundingClientRect().top-a.bottom,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`});a.observe(t),a.observe(n);const i=c(t),s=c(n);function c(e){const t=new MutationObserver((()=>{a.unobserve(e),a.observe(e)}));return t.observe(e,{attributes:!0}),t}he[e._id]={intersectionObserver:a,mutationObserverBefore:i,mutationObserverAfter:s}},dispose:function(e){const t=he[e._id];t&&(t.intersectionObserver.disconnect(),t.mutationObserverBefore.disconnect(),t.mutationObserverAfter.disconnect(),e.dispose(),delete he[e._id])}},he={};function fe(e){return e?"visible"!==getComputedStyle(e).overflowY?e:fe(e.parentElement):null}const me={navigateTo:oe,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]),l.forEach((n=>n(e,t.browserEventName)))}i.set(e,t)},_internal:{navigationManager:re,domWrapper:{focus:function(e,t){if(!(e instanceof HTMLElement))throw new Error("Unable to focus an invalid element.");e.focus({preventScroll:t})},focusBySelector:function(e){const t=document.querySelector(e);t&&(t.hasAttribute("tabindex")||(t.tabIndex=-1),t.focus())}},Virtualize:de}};window.Blazor=me;let pe=!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("")},be=Math.pow(2,32),ye=Math.pow(2,21)-1;function we(e,t){return e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24}function Ee(e,t){return e[t]+(e[t+1]<<8)+(e[t+2]<<16)+(e[t+3]<<24>>>0)}function Ie(e,t){const n=Ee(e,t+4);if(n>ye)throw new Error(`Cannot read uint64 with high order part ${n}, because the result would exceed Number.MAX_SAFE_INTEGER.`);return n*be+Ee(e,t)}class Se{constructor(e){this.batchData=e;const t=new Te(e);this.arrayRangeReader=new Ne(e),this.arrayBuilderSegmentReader=new Re(e),this.diffReader=new Ce(e),this.editReader=new Ae(e,t),this.frameReader=new De(e,t)}updatedComponents(){return we(this.batchData,this.batchData.length-20)}referenceFrames(){return we(this.batchData,this.batchData.length-16)}disposedComponentIds(){return we(this.batchData,this.batchData.length-12)}disposedEventHandlerIds(){return we(this.batchData,this.batchData.length-8)}updatedComponentsEntry(e,t){const n=e+4*t;return we(this.batchData,n)}referenceFramesEntry(e,t){return e+20*t}disposedComponentIdsEntry(e,t){const n=e+4*t;return we(this.batchData,n)}disposedEventHandlerIdsEntry(e,t){const n=e+8*t;return Ie(this.batchData,n)}}class Ce{constructor(e){this.batchDataUint8=e}componentId(e){return we(this.batchDataUint8,e)}edits(e){return e+4}editsEntry(e,t){return e+16*t}}class Ae{constructor(e,t){this.batchDataUint8=e,this.stringReader=t}editType(e){return we(this.batchDataUint8,e)}siblingIndex(e){return we(this.batchDataUint8,e+4)}newTreeIndex(e){return we(this.batchDataUint8,e+8)}moveToSiblingIndex(e){return we(this.batchDataUint8,e+8)}removedAttributeName(e){const t=we(this.batchDataUint8,e+12);return this.stringReader.readString(t)}}class De{constructor(e,t){this.batchDataUint8=e,this.stringReader=t}frameType(e){return we(this.batchDataUint8,e)}subtreeLength(e){return we(this.batchDataUint8,e+4)}elementReferenceCaptureId(e){const t=we(this.batchDataUint8,e+4);return this.stringReader.readString(t)}componentId(e){return we(this.batchDataUint8,e+8)}elementName(e){const t=we(this.batchDataUint8,e+8);return this.stringReader.readString(t)}textContent(e){const t=we(this.batchDataUint8,e+4);return this.stringReader.readString(t)}markupContent(e){const t=we(this.batchDataUint8,e+4);return this.stringReader.readString(t)}attributeName(e){const t=we(this.batchDataUint8,e+4);return this.stringReader.readString(t)}attributeValue(e){const t=we(this.batchDataUint8,e+8);return this.stringReader.readString(t)}attributeEventHandlerId(e){return Ie(this.batchDataUint8,e+12)}}class Te{constructor(e){this.batchDataUint8=e,this.stringTableStartIndex=we(e,e.length-4)}readString(e){if(-1===e)return null;{const n=we(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)<{!function(e,t,n){const r=document.querySelector(e);if(!r)throw new Error(`Could not find any element matching selector '${e}'.`);!function(e,t,n){let r=Z[0];r||(r=Z[0]=new Y(0)),r.attachRootComponentToLogicalElement(n,t)}(0,D(r,!0),t)}(t,e)},RenderBatch:(e,t)=>{try{const n=Me(t);(function(e,t){const n=Z[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{Fe=!0,console.error(`${e}\n${t}`),async function(){let e=document.querySelector("#blazor-error-ui");e&&(e.style.display="block"),pe||(pe=!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:e.jsCallDispatcher.beginInvokeJSFromDotNet,EndInvokeDotNet:e.jsCallDispatcher.endInvokeDotNetFromJS,SendByteArrayToJS:He,Navigate:re.navigateTo};window.external.receiveMessage((e=>{const n=function(e){if(Fe||!e||!e.startsWith(ke))return null;const t=e.substring(ke.length),[n,...r]=JSON.parse(t);return{messageType:n,args:r}}(e);if(n){if(!t.hasOwnProperty(n.messageType))throw new Error(`Unsupported IPC message type '${n.messageType}'`);t[n.messageType].apply(null,n.args)}}))}(),e.attachDispatcher({beginInvokeDotNetFromJS:Oe,endInvokeJSFromDotNet:xe,sendByteArray:Be}),me._internal.InputFile=Ue,re.enableNavigationInterception(),re.listenForNavigationEvents(Le),Pe("AttachPage",re.getBaseURI(),re.getLocationHref())}o=function(e,t){Pe("DispatchBrowserEvent",e,t)},me.start=Ke,document&&document.currentScript&&"false"!==document.currentScript.getAttribute("autostart")&&Ke()})(); \ No newline at end of file diff --git a/src/Components/Web.JS/src/Platform/Circuits/CircuitStreamingInterop.ts b/src/Components/Web.JS/src/Platform/Circuits/CircuitStreamingInterop.ts index 43d3ed02da8f..744aa7d81d8f 100644 --- a/src/Components/Web.JS/src/Platform/Circuits/CircuitStreamingInterop.ts +++ b/src/Components/Web.JS/src/Platform/Circuits/CircuitStreamingInterop.ts @@ -10,6 +10,7 @@ export function sendJSDataStream(connection: HubConnection, data: ArrayBufferVie let lastAckTime = new Date().valueOf(); try { let position = 0; + let chunkId = 0; // Note: The server-side `StreamBufferCapacity` option (defaults to 10) can be configured to limit how many // stream items from the client (per stream) will be stored before reading any more stream items (thus applying backpressure). @@ -20,14 +21,14 @@ export function sendJSDataStream(connection: HubConnection, data: ArrayBufferVie numChunksUntilNextAck--; if (numChunksUntilNextAck > 1) { // Most of the time just send and buffer within the network layer - await connection.send('ReceiveJSDataChunk', streamId, nextChunkData, null); + await connection.send('ReceiveJSDataChunk', streamId, chunkId, nextChunkData, null); } else { // But regularly, wait for an ACK, so other events can be interleaved // The use of "invoke" (not "send") here is what prevents the JS side from queuing up chunks // faster than the .NET side can receive them. It means that if there are other user interactions // while the transfer is in progress, they would get inserted in the middle, so it would be // possible to navigate away or cancel without first waiting for all the remaining chunks. - const streamIsAlive = await connection.invoke('ReceiveJSDataChunk', streamId, nextChunkData, null); + const streamIsAlive = await connection.invoke('ReceiveJSDataChunk', streamId, chunkId, nextChunkData, null); // Checks to see if we should continue streaming or if the stream has been cancelled/disposed. if (!streamIsAlive) { @@ -43,9 +44,10 @@ export function sendJSDataStream(connection: HubConnection, data: ArrayBufferVie } position += nextChunkSize; + chunkId++; } } catch (error) { - await connection.send('ReceiveJSDataChunk', streamId, null, error.toString()); + await connection.send('ReceiveJSDataChunk', streamId, -1, null, error.toString()); } }, 0); }; From b5615c70578000c38c31e53bb1fda67ce7b70df3 Mon Sep 17 00:00:00 2001 From: Tanay Parikh Date: Tue, 22 Jun 2021 11:42:02 -0700 Subject: [PATCH 29/37] Update ReceiveDataTimeout --- .../Server/src/Circuits/RemoteJSDataStream.cs | 33 ++++++++++++------- .../Server/src/Circuits/RemoteJSRuntime.cs | 2 +- .../test/Circuits/RemoteJSDataStreamTest.cs | 19 ++++++----- 3 files changed, 33 insertions(+), 21 deletions(-) diff --git a/src/Components/Server/src/Circuits/RemoteJSDataStream.cs b/src/Components/Server/src/Circuits/RemoteJSDataStream.cs index 13d6451467ae..d0917a44e2ba 100644 --- a/src/Components/Server/src/Circuits/RemoteJSDataStream.cs +++ b/src/Components/Server/src/Circuits/RemoteJSDataStream.cs @@ -15,12 +15,13 @@ internal sealed class RemoteJSDataStream : Stream private readonly RemoteJSRuntime _runtime; private readonly long _streamId; private readonly long _totalLength; + private readonly TimeSpan _jsInteropDefaultCallTimeout; private readonly CancellationToken _streamCancellationToken; - private readonly Timer _receiveDataTimer; private readonly Stream _pipeReaderStream; private readonly Pipe _pipe; private long _bytesRead; private long _expectedChunkId; + private CancellationTokenSource _timeoutCancellationTokenSource; public static async Task ReceiveData(RemoteJSRuntime runtime, long streamId, long chunkId, byte[] chunk, string error) { @@ -40,6 +41,7 @@ public static async ValueTask CreateRemoteJSDataStreamAsync( long totalLength, long maxBufferSize, long maximumIncomingBytes, + TimeSpan jsInteropDefaultCallTimeout, CancellationToken cancellationToken = default) { // Enforce minimum 1 kb SignalR message size as we budget 512 bytes @@ -50,7 +52,7 @@ public static async ValueTask CreateRemoteJSDataStreamAsync( throw new ArgumentException($"SignalR MaximumIncomingBytes must be at least 1 kb."); var streamId = runtime.RemoteJSDataStreamNextInstanceId++; - var remoteJSDataStream = new RemoteJSDataStream(runtime, streamId, totalLength, maxBufferSize, cancellationToken); + var remoteJSDataStream = new RemoteJSDataStream(runtime, streamId, totalLength, maxBufferSize, jsInteropDefaultCallTimeout, cancellationToken); await runtime.InvokeVoidAsync("Blazor._internal.sendJSDataStream", jsStreamReference, streamId, chunkSize); return remoteJSDataStream; } @@ -60,19 +62,17 @@ private RemoteJSDataStream( long streamId, long totalLength, long maxBufferSize, + TimeSpan jsInteropDefaultCallTimeout, CancellationToken cancellationToken) { _runtime = runtime; _streamId = streamId; _totalLength = totalLength; + _jsInteropDefaultCallTimeout = jsInteropDefaultCallTimeout; _streamCancellationToken = cancellationToken; - // Dispose of the stream if a chunk isn't received within 1 minute. - _receiveDataTimer = new Timer(new TimerCallback(async (state) => { - var stream = state as RemoteJSDataStream; - var timeoutException = new TimeoutException("Did not receive any data in the alloted time."); - await stream.CompletePipeAndDisposeStream(timeoutException); - }), this, dueTime: ReceiveDataTimeout, period: Timeout.InfiniteTimeSpan); + _timeoutCancellationTokenSource = new CancellationTokenSource(); + _ = ThrowOnTimeout(_timeoutCancellationTokenSource.Token); _runtime.RemoteJSDataStreamInstances.Add(_streamId, this); @@ -80,15 +80,14 @@ private RemoteJSDataStream( _pipeReaderStream = _pipe.Reader.AsStream(); } - // internal for testing - internal TimeSpan ReceiveDataTimeout { private get; set; } = TimeSpan.FromMinutes(1); - private async Task ReceiveData(long chunkId, byte[] chunk, string error) { try { // Reset the timeout as a chunk has been received - _receiveDataTimer.Change(dueTime: ReceiveDataTimeout, period: Timeout.InfiniteTimeSpan); + _timeoutCancellationTokenSource.Cancel(); + _timeoutCancellationTokenSource = new CancellationTokenSource(); + _ = ThrowOnTimeout(_timeoutCancellationTokenSource.Token); if (!string.IsNullOrEmpty(error)) { @@ -193,6 +192,16 @@ private static CancellationToken GetLinkedCancellationToken(CancellationToken a, return b; } + private async Task ThrowOnTimeout(CancellationToken cancellationToken) + { + await Task.Delay(_jsInteropDefaultCallTimeout, cancellationToken); + + // Dispose of the stream if a chunk isn't received within the jsInteropDefaultCallTimeout. + var timeoutException = new TimeoutException("Did not receive any data in the alloted time."); + await CompletePipeAndDisposeStream(timeoutException); + throw timeoutException; + } + internal async Task CompletePipeAndDisposeStream(Exception? ex = null) { await _pipe.Writer.CompleteAsync(ex); diff --git a/src/Components/Server/src/Circuits/RemoteJSRuntime.cs b/src/Components/Server/src/Circuits/RemoteJSRuntime.cs index 54157ddb1599..789fc3936e00 100644 --- a/src/Components/Server/src/Circuits/RemoteJSRuntime.cs +++ b/src/Components/Server/src/Circuits/RemoteJSRuntime.cs @@ -148,7 +148,7 @@ public void MarkPermanentlyDisconnected() } protected override async Task ReadJSDataAsStreamAsync(IJSStreamReference jsStreamReference, long totalLength, long maxBufferSize, CancellationToken cancellationToken) - => await RemoteJSDataStream.CreateRemoteJSDataStreamAsync(this, jsStreamReference, totalLength, maxBufferSize, _maximumIncomingBytes, cancellationToken); + => await RemoteJSDataStream.CreateRemoteJSDataStreamAsync(this, jsStreamReference, totalLength, maxBufferSize, _maximumIncomingBytes, _options.JSInteropDefaultCallTimeout, cancellationToken); public static class Log { diff --git a/src/Components/Server/test/Circuits/RemoteJSDataStreamTest.cs b/src/Components/Server/test/Circuits/RemoteJSDataStreamTest.cs index 5b51150cf115..cf3ebb99cdc1 100644 --- a/src/Components/Server/test/Circuits/RemoteJSDataStreamTest.cs +++ b/src/Components/Server/test/Circuits/RemoteJSDataStreamTest.cs @@ -25,7 +25,7 @@ public async void CreateRemoteJSDataStreamAsync_CreatesStream() var jsStreamReference = Mock.Of(); // Act - var remoteJSDataStream = await RemoteJSDataStream.CreateRemoteJSDataStreamAsync(_jsRuntime, jsStreamReference, totalLength: 100, maxBufferSize: 50, maximumIncomingBytes: 10_000); + var remoteJSDataStream = await RemoteJSDataStream.CreateRemoteJSDataStreamAsync(_jsRuntime, jsStreamReference, totalLength: 100, maxBufferSize: 50, maximumIncomingBytes: 10_000, jsInteropDefaultCallTimeout: TimeSpan.FromMinutes(1)); // Assert Assert.NotNull(remoteJSDataStream); @@ -79,13 +79,16 @@ public async void ReceiveData_ReceiveDataTimeout_StreamDisposed() // Arrange var jsRuntime = new TestRemoteJSRuntime(Options.Create(new CircuitOptions()), Options.Create(new HubOptions()), Mock.Of>()); var jsStreamReference = Mock.Of(); - var remoteJSDataStream = await RemoteJSDataStream.CreateRemoteJSDataStreamAsync(jsRuntime ?? _jsRuntime, jsStreamReference, totalLength: 9, maxBufferSize: 50, maximumIncomingBytes: 10_000); + var remoteJSDataStream = await RemoteJSDataStream.CreateRemoteJSDataStreamAsync( + jsRuntime ?? _jsRuntime, + jsStreamReference, + totalLength: 9, + maxBufferSize: 50, + maximumIncomingBytes: 10_000, + jsInteropDefaultCallTimeout: TimeSpan.FromSeconds(15)); // Note we're using a 15 second timeout for this test var streamId = GetStreamId(remoteJSDataStream, jsRuntime); var chunk = new byte[] { 3, 5, 7 }; - // Set a 15 second timeout for testing - remoteJSDataStream.ReceiveDataTimeout = TimeSpan.FromSeconds(15); - var sendDataTask = Task.Run(async () => { // Act & Assert 1 @@ -164,7 +167,7 @@ public async void ReceiveData_ProvidedWithMoreBytesThanRemaining() // Arrange var jsRuntime = new TestRemoteJSRuntime(Options.Create(new CircuitOptions()), Options.Create(new HubOptions()), Mock.Of>()); var jsStreamReference = Mock.Of(); - var remoteJSDataStream = await RemoteJSDataStream.CreateRemoteJSDataStreamAsync(jsRuntime, jsStreamReference, totalLength: 100, maxBufferSize: 50, maximumIncomingBytes: 10_000); + var remoteJSDataStream = await RemoteJSDataStream.CreateRemoteJSDataStreamAsync(jsRuntime, jsStreamReference, totalLength: 100, maxBufferSize: 50, maximumIncomingBytes: 10_000, jsInteropDefaultCallTimeout: TimeSpan.FromMinutes(1)); var streamId = GetStreamId(remoteJSDataStream, jsRuntime); var chunk = new byte[110]; // 100 byte totalLength for stream @@ -184,7 +187,7 @@ public async void ReceiveData_ProvidedWithOutOfOrderChunk_SimulatesSignalRDiscon // Arrange var jsRuntime = new TestRemoteJSRuntime(Options.Create(new CircuitOptions()), Options.Create(new HubOptions()), Mock.Of>()); var jsStreamReference = Mock.Of(); - var remoteJSDataStream = await RemoteJSDataStream.CreateRemoteJSDataStreamAsync(jsRuntime, jsStreamReference, totalLength: 100, maxBufferSize: 50, maximumIncomingBytes: 10_000); + var remoteJSDataStream = await RemoteJSDataStream.CreateRemoteJSDataStreamAsync(jsRuntime, jsStreamReference, totalLength: 100, maxBufferSize: 50, maximumIncomingBytes: 10_000, jsInteropDefaultCallTimeout: TimeSpan.FromMinutes(1)); var streamId = GetStreamId(remoteJSDataStream, jsRuntime); var chunk = new byte[5]; @@ -205,7 +208,7 @@ public async void ReceiveData_ProvidedWithOutOfOrderChunk_SimulatesSignalRDiscon private static async Task CreateRemoteJSDataStreamAsync(TestRemoteJSRuntime jsRuntime = null) { var jsStreamReference = Mock.Of(); - var remoteJSDataStream = await RemoteJSDataStream.CreateRemoteJSDataStreamAsync(jsRuntime ?? _jsRuntime, jsStreamReference, totalLength: 100, maxBufferSize: 50, maximumIncomingBytes: 10_000); + var remoteJSDataStream = await RemoteJSDataStream.CreateRemoteJSDataStreamAsync(jsRuntime ?? _jsRuntime, jsStreamReference, totalLength: 100, maxBufferSize: 50, maximumIncomingBytes: 10_000, jsInteropDefaultCallTimeout: TimeSpan.FromMinutes(1)); return remoteJSDataStream; } From 53f0392109ffa0fc683b4f7f9d4b508afd0d4b57 Mon Sep 17 00:00:00 2001 From: Tanay Parikh Date: Tue, 22 Jun 2021 12:18:04 -0700 Subject: [PATCH 30/37] Update RemoteJSDataStream.cs --- .../Server/src/Circuits/RemoteJSDataStream.cs | 27 ++++++++++--------- 1 file changed, 14 insertions(+), 13 deletions(-) diff --git a/src/Components/Server/src/Circuits/RemoteJSDataStream.cs b/src/Components/Server/src/Circuits/RemoteJSDataStream.cs index d0917a44e2ba..77c7a5e8b5b1 100644 --- a/src/Components/Server/src/Circuits/RemoteJSDataStream.cs +++ b/src/Components/Server/src/Circuits/RemoteJSDataStream.cs @@ -21,7 +21,7 @@ internal sealed class RemoteJSDataStream : Stream private readonly Pipe _pipe; private long _bytesRead; private long _expectedChunkId; - private CancellationTokenSource _timeoutCancellationTokenSource; + private DateTimeOffset _lastDataReceivedTime; public static async Task ReceiveData(RemoteJSRuntime runtime, long streamId, long chunkId, byte[] chunk, string error) { @@ -71,8 +71,8 @@ private RemoteJSDataStream( _jsInteropDefaultCallTimeout = jsInteropDefaultCallTimeout; _streamCancellationToken = cancellationToken; - _timeoutCancellationTokenSource = new CancellationTokenSource(); - _ = ThrowOnTimeout(_timeoutCancellationTokenSource.Token); + _lastDataReceivedTime = DateTime.UtcNow; + _ = ThrowOnTimeout(); _runtime.RemoteJSDataStreamInstances.Add(_streamId, this); @@ -84,10 +84,8 @@ private async Task ReceiveData(long chunkId, byte[] chunk, string error) { try { - // Reset the timeout as a chunk has been received - _timeoutCancellationTokenSource.Cancel(); - _timeoutCancellationTokenSource = new CancellationTokenSource(); - _ = ThrowOnTimeout(_timeoutCancellationTokenSource.Token); + _lastDataReceivedTime = DateTime.UtcNow; + _ = ThrowOnTimeout(); if (!string.IsNullOrEmpty(error)) { @@ -192,14 +190,17 @@ private static CancellationToken GetLinkedCancellationToken(CancellationToken a, return b; } - private async Task ThrowOnTimeout(CancellationToken cancellationToken) + private async Task ThrowOnTimeout() { - await Task.Delay(_jsInteropDefaultCallTimeout, cancellationToken); + await Task.Delay(_jsInteropDefaultCallTimeout); - // Dispose of the stream if a chunk isn't received within the jsInteropDefaultCallTimeout. - var timeoutException = new TimeoutException("Did not receive any data in the alloted time."); - await CompletePipeAndDisposeStream(timeoutException); - throw timeoutException; + if (DateTime.UtcNow >= _lastDataReceivedTime.Add(_jsInteropDefaultCallTimeout)) + { + // Dispose of the stream if a chunk isn't received within the jsInteropDefaultCallTimeout. + var timeoutException = new TimeoutException("Did not receive any data in the alloted time."); + await CompletePipeAndDisposeStream(timeoutException); + throw timeoutException; + } } internal async Task CompletePipeAndDisposeStream(Exception? ex = null) From 3cd7619020aec49b8d1dcdf2700ac4c6df014868 Mon Sep 17 00:00:00 2001 From: Tanay Parikh Date: Tue, 22 Jun 2021 12:46:37 -0700 Subject: [PATCH 31/37] ReceiveData Timeout UnhandledException --- src/Components/Server/src/Circuits/CircuitHost.cs | 8 +++++--- .../Server/src/Circuits/RemoteJSDataStream.cs | 7 +++++-- src/Components/Server/src/Circuits/RemoteJSRuntime.cs | 10 ++++++++++ 3 files changed, 20 insertions(+), 5 deletions(-) diff --git a/src/Components/Server/src/Circuits/CircuitHost.cs b/src/Components/Server/src/Circuits/CircuitHost.cs index f6b544d6f7e2..a8d43c703364 100644 --- a/src/Components/Server/src/Circuits/CircuitHost.cs +++ b/src/Components/Server/src/Circuits/CircuitHost.cs @@ -68,8 +68,11 @@ public CircuitHost( Circuit = new Circuit(this); Handle = new CircuitHandle() { CircuitHost = this, }; - Renderer.UnhandledException += Renderer_UnhandledException; + // An unhandled exception from the renderer is always fatal because it came from user code. + Renderer.UnhandledException += ReportAndInvoke_UnhandledException; Renderer.UnhandledSynchronizationException += SynchronizationContext_UnhandledException; + + JSRuntime.UnhandledException += ReportAndInvoke_UnhandledException; } public CircuitHandle Handle { get; } @@ -571,9 +574,8 @@ private void AssertNotDisposed() } } - // An unhandled exception from the renderer is always fatal because it came from user code. // We want to notify the client if it's still connected, and then tear-down the circuit. - private async void Renderer_UnhandledException(object sender, Exception e) + private async void ReportAndInvoke_UnhandledException(object sender, Exception e) { await ReportUnhandledException(e); UnhandledException?.Invoke(this, new UnhandledExceptionEventArgs(e, isTerminating: false)); diff --git a/src/Components/Server/src/Circuits/RemoteJSDataStream.cs b/src/Components/Server/src/Circuits/RemoteJSDataStream.cs index 77c7a5e8b5b1..991ab9299bad 100644 --- a/src/Components/Server/src/Circuits/RemoteJSDataStream.cs +++ b/src/Components/Server/src/Circuits/RemoteJSDataStream.cs @@ -22,6 +22,7 @@ internal sealed class RemoteJSDataStream : Stream private long _bytesRead; private long _expectedChunkId; private DateTimeOffset _lastDataReceivedTime; + private bool _disposed; public static async Task ReceiveData(RemoteJSRuntime runtime, long streamId, long chunkId, byte[] chunk, string error) { @@ -194,12 +195,12 @@ private async Task ThrowOnTimeout() { await Task.Delay(_jsInteropDefaultCallTimeout); - if (DateTime.UtcNow >= _lastDataReceivedTime.Add(_jsInteropDefaultCallTimeout)) + if (!_disposed && (DateTime.UtcNow >= _lastDataReceivedTime.Add(_jsInteropDefaultCallTimeout))) { // Dispose of the stream if a chunk isn't received within the jsInteropDefaultCallTimeout. var timeoutException = new TimeoutException("Did not receive any data in the alloted time."); await CompletePipeAndDisposeStream(timeoutException); - throw timeoutException; + _runtime.RaiseUnhandledException(timeoutException); } } @@ -215,6 +216,8 @@ protected override void Dispose(bool disposing) { _runtime.RemoteJSDataStreamInstances.Remove(_streamId); } + + _disposed = true; } } } diff --git a/src/Components/Server/src/Circuits/RemoteJSRuntime.cs b/src/Components/Server/src/Circuits/RemoteJSRuntime.cs index 789fc3936e00..757359f1f926 100644 --- a/src/Components/Server/src/Circuits/RemoteJSRuntime.cs +++ b/src/Components/Server/src/Circuits/RemoteJSRuntime.cs @@ -31,6 +31,11 @@ internal class RemoteJSRuntime : JSRuntime public bool IsInitialized => _clientProxy is not null; + /// + /// Notifies when a runtime exception occurred. + /// + public event EventHandler? UnhandledException; + public RemoteJSRuntime( IOptions circuitOptions, IOptions hubOptions, @@ -53,6 +58,11 @@ internal void Initialize(CircuitClientProxy clientProxy) _clientProxy = clientProxy ?? throw new ArgumentNullException(nameof(clientProxy)); } + internal void RaiseUnhandledException(Exception ex) + { + UnhandledException?.Invoke(this, ex); + } + protected override void EndInvokeDotNet(DotNetInvocationInfo invocationInfo, in DotNetInvocationResult invocationResult) { if (!invocationResult.Success) From d5497842ee52c750840399b8ec2d582b340719b9 Mon Sep 17 00:00:00 2001 From: Tanay Parikh Date: Tue, 22 Jun 2021 16:02:45 -0700 Subject: [PATCH 32/37] Improve test reliability --- .../Server/test/Circuits/RemoteJSDataStreamTest.cs | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/src/Components/Server/test/Circuits/RemoteJSDataStreamTest.cs b/src/Components/Server/test/Circuits/RemoteJSDataStreamTest.cs index cf3ebb99cdc1..6c513e781fe4 100644 --- a/src/Components/Server/test/Circuits/RemoteJSDataStreamTest.cs +++ b/src/Components/Server/test/Circuits/RemoteJSDataStreamTest.cs @@ -85,7 +85,7 @@ public async void ReceiveData_ReceiveDataTimeout_StreamDisposed() totalLength: 9, maxBufferSize: 50, maximumIncomingBytes: 10_000, - jsInteropDefaultCallTimeout: TimeSpan.FromSeconds(15)); // Note we're using a 15 second timeout for this test + jsInteropDefaultCallTimeout: TimeSpan.FromSeconds(40)); // Note we're using a 40 second timeout for this test var streamId = GetStreamId(remoteJSDataStream, jsRuntime); var chunk = new byte[] { 3, 5, 7 }; @@ -95,13 +95,14 @@ public async void ReceiveData_ReceiveDataTimeout_StreamDisposed() var success = await RemoteJSDataStream.ReceiveData(jsRuntime, streamId, chunkId: 0, chunk, error: null); Assert.True(success); - await Task.Delay(TimeSpan.FromSeconds(10)); + await Task.Delay(TimeSpan.FromSeconds(20)); // Act & Assert 2 success = await RemoteJSDataStream.ReceiveData(jsRuntime, streamId, chunkId: 1, chunk, error: null); Assert.True(success); - await Task.Delay(TimeSpan.FromSeconds(20)); + // Wait 60 seconds (40 sec timeout + 20 sec buffer room) + await Task.Delay(TimeSpan.FromSeconds(60)); // Act & Assert 3 // Ensures stream is disposed after the timeout and any additional chunks aren't accepted @@ -110,9 +111,8 @@ public async void ReceiveData_ReceiveDataTimeout_StreamDisposed() return true; }); - // Wait past the initial 15 second timeout to ensure it gets reset after - // a new data chunk is received. - await Task.Delay(TimeSpan.FromSeconds(20)); + // Wait 80 seconds (20 sec between first two calls + 40 sec timeout + 20 sec buffer room) + await Task.Delay(TimeSpan.FromSeconds(80)); // Act & Assert 4 using var mem = new MemoryStream(); From 9e63bb6e06d00425a0c23bc83dc4db266d959661 Mon Sep 17 00:00:00 2001 From: Tanay Parikh Date: Fri, 25 Jun 2021 11:26:07 -0700 Subject: [PATCH 33/37] PR Feedback --- src/Components/Server/src/Circuits/CircuitHost.cs | 5 ++++- src/Components/Server/src/Circuits/RemoteJSDataStream.cs | 2 +- .../Microsoft.JSInterop.JS/src/src/Microsoft.JSInterop.ts | 2 +- 3 files changed, 6 insertions(+), 3 deletions(-) diff --git a/src/Components/Server/src/Circuits/CircuitHost.cs b/src/Components/Server/src/Circuits/CircuitHost.cs index a8d43c703364..b6743eee4866 100644 --- a/src/Components/Server/src/Circuits/CircuitHost.cs +++ b/src/Components/Server/src/Circuits/CircuitHost.cs @@ -428,7 +428,10 @@ internal async Task ReceiveJSDataChunk(long streamId, long chunkId, byte[] try { - return await RemoteJSDataStream.ReceiveData(JSRuntime, streamId, chunkId, chunk, error); + return await Renderer.Dispatcher.InvokeAsync(() => + { + return RemoteJSDataStream.ReceiveData(JSRuntime, streamId, chunkId, chunk, error); + }); } catch (Exception ex) { diff --git a/src/Components/Server/src/Circuits/RemoteJSDataStream.cs b/src/Components/Server/src/Circuits/RemoteJSDataStream.cs index 991ab9299bad..a60b66b48ea8 100644 --- a/src/Components/Server/src/Circuits/RemoteJSDataStream.cs +++ b/src/Components/Server/src/Circuits/RemoteJSDataStream.cs @@ -49,7 +49,7 @@ public static async ValueTask CreateRemoteJSDataStreamAsync( // overhead for the transfer, thus leaving at least 512 bytes for data // transfer per chunk. var chunkSize = maximumIncomingBytes > 1024 ? - maximumIncomingBytes - 512 : + Math.Min(maximumIncomingBytes, 50*1024) - 512 : throw new ArgumentException($"SignalR MaximumIncomingBytes must be at least 1 kb."); var streamId = runtime.RemoteJSDataStreamNextInstanceId++; diff --git a/src/JSInterop/Microsoft.JSInterop.JS/src/src/Microsoft.JSInterop.ts b/src/JSInterop/Microsoft.JSInterop.JS/src/src/Microsoft.JSInterop.ts index fa7530a84d45..dc8c6421266c 100644 --- a/src/JSInterop/Microsoft.JSInterop.JS/src/src/Microsoft.JSInterop.ts +++ b/src/JSInterop/Microsoft.JSInterop.JS/src/src/Microsoft.JSInterop.ts @@ -150,7 +150,7 @@ export module DotNet { // Check if this is an ArrayBufferView, and if it has a valid byteLength for transfer // using a JSStreamReference. if (!(arrayBufferView.buffer instanceof ArrayBuffer)) { - throw new Error(`Cannot create a JSStreamReference from the value '${arrayBufferView}' as it is not a valid ArrayBuffer.`); + throw new Error(`Cannot create a JSStreamReference from the value '${arrayBufferView}' as it is not have a 'buffer' property of type 'ArrayBuffer'.`); } else if (arrayBufferView.byteLength === undefined) { throw new Error(`Cannot create a JSStreamReference from the value '${arrayBufferView}' as it doesn't have a byteLength.`); } From f565366225e23c3621d36605a5821a0450abc427 Mon Sep 17 00:00:00 2001 From: Tanay Parikh Date: Fri, 25 Jun 2021 11:26:13 -0700 Subject: [PATCH 34/37] Update RemoteJSDataStreamTest.cs --- .../test/Circuits/RemoteJSDataStreamTest.cs | 35 +++++++------------ 1 file changed, 12 insertions(+), 23 deletions(-) diff --git a/src/Components/Server/test/Circuits/RemoteJSDataStreamTest.cs b/src/Components/Server/test/Circuits/RemoteJSDataStreamTest.cs index 6c513e781fe4..67ee306c55af 100644 --- a/src/Components/Server/test/Circuits/RemoteJSDataStreamTest.cs +++ b/src/Components/Server/test/Circuits/RemoteJSDataStreamTest.cs @@ -89,39 +89,28 @@ public async void ReceiveData_ReceiveDataTimeout_StreamDisposed() var streamId = GetStreamId(remoteJSDataStream, jsRuntime); var chunk = new byte[] { 3, 5, 7 }; - var sendDataTask = Task.Run(async () => - { - // Act & Assert 1 - var success = await RemoteJSDataStream.ReceiveData(jsRuntime, streamId, chunkId: 0, chunk, error: null); - Assert.True(success); - - await Task.Delay(TimeSpan.FromSeconds(20)); - - // Act & Assert 2 - success = await RemoteJSDataStream.ReceiveData(jsRuntime, streamId, chunkId: 1, chunk, error: null); - Assert.True(success); + // Act & Assert 1 + var success = await RemoteJSDataStream.ReceiveData(jsRuntime, streamId, chunkId: 0, chunk, error: null); + Assert.True(success); - // Wait 60 seconds (40 sec timeout + 20 sec buffer room) - await Task.Delay(TimeSpan.FromSeconds(60)); + await Task.Delay(TimeSpan.FromSeconds(20)); - // Act & Assert 3 - // Ensures stream is disposed after the timeout and any additional chunks aren't accepted - success = await RemoteJSDataStream.ReceiveData(jsRuntime, streamId, chunkId: 2, chunk, error: null); - Assert.False(success); - return true; - }); + // Act & Assert 2 + success = await RemoteJSDataStream.ReceiveData(jsRuntime, streamId, chunkId: 1, chunk, error: null); + Assert.True(success); // Wait 80 seconds (20 sec between first two calls + 40 sec timeout + 20 sec buffer room) await Task.Delay(TimeSpan.FromSeconds(80)); - // Act & Assert 4 + // Act & Assert 3 using var mem = new MemoryStream(); var ex = await Assert.ThrowsAsync(async() => await remoteJSDataStream.CopyToAsync(mem)); Assert.Equal("Did not receive any data in the alloted time.", ex.Message); - // Act & Assert 5 - var sendDataCompleted = await sendDataTask; - Assert.True(sendDataCompleted); + // Act & Assert 4 + // Ensures stream is disposed after the timeout and any additional chunks aren't accepted + success = await RemoteJSDataStream.ReceiveData(jsRuntime, streamId, chunkId: 2, chunk, error: null); + Assert.False(success); } [Fact] From c1e0873e44831fc546bd96313fad64224c0db705 Mon Sep 17 00:00:00 2001 From: Tanay Parikh Date: Fri, 25 Jun 2021 14:38:26 -0700 Subject: [PATCH 35/37] Update blazor.*.js --- src/Components/Web.JS/dist/Release/blazor.server.js | 2 +- src/Components/Web.JS/dist/Release/blazor.webview.js | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/Components/Web.JS/dist/Release/blazor.server.js b/src/Components/Web.JS/dist/Release/blazor.server.js index 215b8cb31037..654969b2ea1a 100644 --- a/src/Components/Web.JS/dist/Release/blazor.server.js +++ b/src/Components/Web.JS/dist/Release/blazor.server.js @@ -1 +1 @@ -(()=>{"use strict";var e,t,n;!function(e){window.DotNet=e;const t=[],n=new Map;class r{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 o="__jsObjectId",i={},s={0:new r(window)};s[0]._cachedFunctions.set("import",(e=>("string"==typeof e&&e.startsWith("./")&&(e=document.baseURI+e.substr(2)),import(e))));let a,c=1,l=1,h=null;function u(e){t.push(e)}function d(e){if(e&&"object"==typeof e){s[l]=new r(e);const t={[o]:l};return l++,t}throw new Error(`Cannot create a JSObjectReference from the value '${e}'.`)}function p(e){return e?JSON.parse(e,((e,n)=>t.reduce(((t,n)=>n(e,t)),n))):null}function f(e,t,n,r){const o=m();if(o.invokeDotNetFromJS){const i=I(r),s=o.invokeDotNetFromJS(e,t,n,i);return s?p(s):null}throw new Error("The current dispatcher does not support synchronous calls from JS to .NET. Use invokeMethodAsync instead.")}function g(e,t,n,r){if(e&&n)throw new Error(`For instance method calls, assemblyName should be null. Received '${e}'.`);const o=c++,s=new Promise(((e,t)=>{i[o]={resolve:e,reject:t}}));try{const i=I(r);m().beginInvokeDotNetFromJS(o,e,t,n,i)}catch(e){y(o,!1,e)}return s}function m(){if(null!==h)return h;throw new Error("No .NET call dispatcher has been set.")}function y(e,t,n){if(!i.hasOwnProperty(e))throw new Error(`There is no pending async call with ID ${e}.`);const r=i[e];delete i[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 v(e,t){let n=s[t];if(n)return n.findFunction(e);throw new Error(`JS object instance with ID ${t} does not exist (has it been disposed?).`)}function b(e){delete s[e]}e.attachDispatcher=function(e){h=e},e.attachReviver=u,e.invokeMethod=function(e,t,...n){return f(e,t,null,n)},e.invokeMethodAsync=function(e,t,...n){return g(e,t,null,n)},e.createJSObjectReference=d,e.disposeJSObjectReference=function(e){const t=e&&e.__jsObjectId;"number"==typeof t&&b(t)},function(e){e[e.Default=0]="Default",e[e.JSObjectReference=1]="JSObjectReference"}(a=e.JSCallResultType||(e.JSCallResultType={})),e.jsCallDispatcher={findJSFunction:v,disposeJSObjectReferenceById:b,invokeJSFromDotNet:(e,t,n,r)=>{const o=S(v(e,r).apply(null,p(t)),n);return null==o?null:I(o)},beginInvokeJSFromDotNet:(e,t,n,r,o)=>{const i=new Promise((e=>{e(v(t,o).apply(null,p(n)))}));e&&i.then((t=>m().endInvokeJSFromDotNet(e,!0,I([e,!0,S(t,r)]))),(t=>m().endInvokeJSFromDotNet(e,!1,JSON.stringify([e,!1,w(t)]))))},endInvokeDotNetFromJS:(e,t,n)=>{const r=t?p(n):new Error(n);y(parseInt(e),t,r)},receiveByteArray:(e,t)=>{n.set(e,t)}};class _{constructor(e){this._id=e}invokeMethod(e,...t){return f(null,e,this._id,t)}invokeMethodAsync(e,...t){return g(null,e,this._id,t)}dispose(){g(null,"__Dispose",this._id,null).catch((e=>console.error(e)))}serializeAsArg(){return{__dotNetObject:this._id}}}const E="__byte[]";function S(e,t){switch(t){case a.Default:return e;case a.JSObjectReference:return d(e);default:throw new Error(`Invalid JS call result type '${t}'.`)}}u((function(e,t){if(t&&"object"==typeof t){if(t.hasOwnProperty("__dotNetObject"))return new _(t.__dotNetObject);if(t.hasOwnProperty(o)){const e=t.__jsObjectId,n=s[e];if(n)return n.getWrappedObject();throw new Error(`JS object instance with Id '${e}' does not exist. It may have been disposed.`)}if(t.hasOwnProperty(E)){const e=t["__byte[]"],r=n.get(e);if(void 0===r)throw new Error(`Byte array index '${e}' does not exist.`);return r}}return t}));let C=0;function I(e){return C=0,JSON.stringify(e,k)}function k(e,t){if(t instanceof _)return t.serializeAsArg();if(t instanceof Uint8Array){h.sendByteArray(C,t);const e={[E]:C};return C++,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"}(n||(n={}));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}}let o;function i(e,t){if(!o)throw new Error("eventDispatcher not initialized. Call 'setEventDispatcher' to configure it.");o(e,t)}const s=new Map,a=new Map,c={createEventArgs:()=>({})},l=[];function h(e){return s.get(e)}function u(e){const t=s.get(e);return(null==t?void 0:t.browserEventName)||e}function d(e,t){e.forEach((e=>s.set(e,t)))}function p(e){const t=[];for(let n=0;n{return{...f(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}}),d(["focus","blur","focusin","focusout"],c),d(["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};var t}}),d(["contextmenu","click","mouseover","mouseout","mousemove","mousedown","mouseup","dblclick"],{createEventArgs:e=>f(e)}),d(["error"],{createEventArgs:e=>{return{message:(t=e).message,filename:t.filename,lineno:t.lineno,colno:t.colno};var t}}),d(["loadstart","timeout","abort","load","loadend","progress"],{createEventArgs:e=>{return{lengthComputable:(t=e).lengthComputable,loaded:t.loaded,total:t.total};var t}}),d(["touchcancel","touchend","touchmove","touchenter","touchleave","touchstart"],{createEventArgs:e=>{return{detail:(t=e).detail,touches:p(t.touches),targetTouches:p(t.targetTouches),changedTouches:p(t.changedTouches),ctrlKey:t.ctrlKey,shiftKey:t.shiftKey,altKey:t.altKey,metaKey:t.metaKey,type:t.type};var t}}),d(["gotpointercapture","lostpointercapture","pointercancel","pointerdown","pointerenter","pointerleave","pointermove","pointerout","pointerover","pointerup"],{createEventArgs:e=>{return{...f(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}}),d(["wheel","mousewheel"],{createEventArgs:e=>{return{...f(t=e),deltaX:t.deltaX,deltaY:t.deltaY,deltaZ:t.deltaZ,deltaMode:t.deltaMode};var t}}),d(["toggle"],c);const g=["date","datetime-local","month","time","week"],m=E(["abort","blur","change","error","focus","load","loadend","loadstart","mouseenter","mouseleave","progress","reset","scroll","submit","unload","toggle","DOMNodeInsertedIntoDocument","DOMNodeRemovedFromDocument"]),y={submit:!0},w=E(["click","dblclick","mousedown","mousemove","mouseup"]);class v{constructor(e){this.browserRendererId=e,this.afterClickCallbacks=[];const t=++v.nextEventDelegatorId;this.eventsCollectionKey=`_blazorEvents_${t}`,this.eventInfoStore=new b(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,a.get(n));var n;t&&t.forEach((t=>this.dispatchGlobalEventToAllElements(t,e))),"click"===e.type&&this.afterClickCallbacks.forEach((t=>t(e)))}dispatchGlobalEventToAllElements(e,t){let n=t.target,o=null,s=!1;const a=m.hasOwnProperty(e);let c=!1;for(;n;){const d=this.getEventHandlerInfosForElement(n,!1);if(d){const a=d.getHandler(e);if(a&&(l=n,u=t.type,!((l instanceof HTMLButtonElement||l instanceof HTMLInputElement||l instanceof HTMLTextAreaElement||l instanceof HTMLSelectElement)&&w.hasOwnProperty(u)&&l.disabled))){if(!s){const n=h(e);o=(null==n?void 0:n.createEventArgs)?n.createEventArgs(t):{},s=!0}y.hasOwnProperty(t.type)&&t.preventDefault(),i({browserRendererId:this.browserRendererId,eventHandlerId:a.eventHandlerId,eventName:e,eventFieldInfo:r.fromEvent(a.renderingComponentId,t)},o)}d.stopPropagation(e)&&(c=!0),d.preventDefault(e)&&t.preventDefault()}n=a||c?null:n.parentElement}var l,u}getEventHandlerInfosForElement(e,t){return e.hasOwnProperty(this.eventsCollectionKey)?e[this.eventsCollectionKey]:t?e[this.eventsCollectionKey]=new _:null}}v.nextEventDelegatorId=0;class b{constructor(e){this.globalListener=e,this.infosByEventHandlerId={},this.countByEventName={},l.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=u(e),this.countByEventName.hasOwnProperty(e))this.countByEventName[e]++;else{this.countByEventName[e]=1;const t=m.hasOwnProperty(e);document.addEventListener(e,this.globalListener,t)}}update(e,t){if(this.infosByEventHandlerId.hasOwnProperty(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=u(t.eventName);0==--this.countByEventName[n]&&(delete this.countByEventName[n],document.removeEventListener(n,this.globalListener))}return t}handleEventNameAliasAdded(e,t){if(this.countByEventName.hasOwnProperty(e)){const n=this.countByEventName[e];delete this.countByEventName[e],document.removeEventListener(e,this.globalListener),this.addGlobalListener(t),this.countByEventName[t]+=n-1}}}class _{constructor(){this.handlers={},this.preventDefaultFlags=null,this.stopPropagationFlags=null}getHandler(e){return this.handlers.hasOwnProperty(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 E(e){const t={};return e.forEach((e=>{t[e]=!0})),t}const S=F("_blazorLogicalChildren"),C=F("_blazorLogicalParent"),I=F("_blazorLogicalEnd");function k(e,t){if(e.childNodes.length>0&&!t)throw new Error("New logical elements must start empty, or allowExistingContents must be true");return S in e||(e[S]=[]),e}function T(e,t){const n=document.createComment("!");return x(n,e,t),n}function x(e,t,n){const r=e;if(e instanceof Comment&&A(r)&&A(r).length>0)throw new Error("Not implemented: inserting non-empty logical container");if(R(r))throw new Error("Not implemented: moving existing logical children");const o=A(t);if(n0;)D(n,0)}const r=n;r.parentNode.removeChild(r)}function R(e){return e[C]||null}function P(e,t){return A(e)[t]}function U(e){var t=B(e);return"http://www.w3.org/2000/svg"===t.namespaceURI&&"foreignObject"!==t.tagName}function A(e){return e[S]}function N(e,t){const n=A(e);t.forEach((e=>{e.moveRangeStart=n[e.fromSiblingIndex],e.moveRangeEnd=L(e.moveRangeStart)})),t.forEach((t=>{const r=t.moveToBeforeMarker=document.createComment("marker"),o=n[t.toSiblingIndex+1];o?o.parentNode.insertBefore(r,o):M(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 B(e){if(e instanceof Element)return e;if(e instanceof Comment)return e.parentNode;throw new Error("Not a valid logical element")}function $(e){const t=A(R(e));return t[Array.prototype.indexOf.call(t,e)+1]||null}function M(e,t){if(t instanceof Element)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=$(t);n?n.parentNode.insertBefore(e,n):M(e,R(t))}}}function L(e){if(e instanceof Element)return e;const t=$(e);if(t)return t.previousSibling;{const t=R(e);return t instanceof Element?t.lastChild:L(t)}}function F(e){return"function"==typeof Symbol?Symbol():e}function H(e){return`_bl_${e}`}e.attachReviver(((e,t)=>t&&"object"==typeof t&&t.hasOwnProperty("__internalId")&&"string"==typeof t.__internalId?function(e){const t=`[${H(e)}]`;return document.querySelector(t)}(t.__internalId):t));const O="_blazorDeferredValue",j=document.createElement("template"),W=document.createElementNS("http://www.w3.org/2000/svg","g"),z={},q="__internal_",J="preventDefault_",K="stopPropagation_";class V{constructor(e){this.childComponentLocations={},this.eventDelegator=new v(e),this.eventDelegator.notifyAfterClick((e=>{if(!ee)return;if(0!==e.button||function(e){return e.ctrlKey||e.shiftKey||e.altKey||e.metaKey}(e))return;if(e.defaultPrevented)return;const t=function(e){const t=!window._blazorDisableComposedPath&&e.composedPath&&e.composedPath();if(t){for(let e=0;ese(!1))))},enableNavigationInterception:function(){ee=!0},navigateTo:oe,getBaseURI:()=>document.baseURI,getLocationHref:()=>location.href};function oe(e,t,n=!1){const r=ce(e);if(!t&&he(r))ie(r,!1,n);else if(t&&location.href===e){const t=e+"?";history.replaceState(null,"",t),location.replace(e)}else n?history.replaceState(null,"",r):location.href=e}function ie(e,t,n=!1){Z=!0,n?history.replaceState(null,"",e):history.pushState(null,"",e),se(t)}async function se(e){ne&&await ne(location.href,e)}let ae;function ce(e){return ae=ae||document.createElement("a"),ae.href=e,ae.href}function le(e,t){return e?e.tagName===t?e:le(e.parentElement,t):null}function he(e){const t=(n=document.baseURI).substr(0,n.lastIndexOf("/")+1);var n;return e.startsWith(t)}const ue={init:function(e,t,n,r=50){const o=pe(t);(o||document.documentElement).style.overflowAnchor="none";const i=new IntersectionObserver((function(r){r.forEach((r=>{var o;if(!r.isIntersecting)return;const i=t.getBoundingClientRect(),s=n.getBoundingClientRect().top-i.bottom,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`});i.observe(t),i.observe(n);const s=c(t),a=c(n);function c(e){const t=new MutationObserver((()=>{i.unobserve(e),i.observe(e)}));return t.observe(e,{attributes:!0}),t}de[e._id]={intersectionObserver:i,mutationObserverBefore:s,mutationObserverAfter:a}},dispose:function(e){const t=de[e._id];t&&(t.intersectionObserver.disconnect(),t.mutationObserverBefore.disconnect(),t.mutationObserverAfter.disconnect(),e.dispose(),delete de[e._id])}},de={};function pe(e){return e?"visible"!==getComputedStyle(e).overflowY?e:pe(e.parentElement):null}const fe={navigateTo:oe,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=a.get(t.browserEventName);n?n.push(e):a.set(t.browserEventName,[e]),l.forEach((n=>n(e,t.browserEventName)))}s.set(e,t)},_internal:{navigationManager:re,domWrapper:{focus:function(e,t){if(!(e instanceof HTMLElement))throw new Error("Unable to focus an invalid element.");e.focus({preventScroll:t})},focusBySelector:function(e){const t=document.querySelector(e);t&&(t.hasAttribute("tabindex")||(t.tabIndex=-1),t.focus())}},Virtualize:ue}};window.Blazor=fe;const ge=[0,2e3,1e4,3e4,null];class me{constructor(e){this._retryDelays=void 0!==e?[...e,null]:ge}nextRetryDelayInMilliseconds(e){return this._retryDelays[e.previousRetryCount]}}class ye extends Error{constructor(e,t){const n=new.target.prototype;super(`${e}: Status code '${t}'`),this.statusCode=t,this.__proto__=n}}class we extends Error{constructor(e="A timeout occurred."){const t=new.target.prototype;super(e),this.__proto__=t}}class ve extends Error{constructor(e="An abort occurred."){const t=new.target.prototype;super(e),this.__proto__=t}}class be{constructor(e,t,n){this.statusCode=e,this.statusText=t,this.content=n}}class _e{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""}}var Ee,Se,Ce,Ie,ke;!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"}(Ee||(Ee={}));class Te extends _e{constructor(e){if(super(),this._logger=e,"undefined"==typeof fetch){const e=require;this._jar=new(e("tough-cookie").CookieJar),this._fetchType=e("node-fetch"),this._fetchType=e("fetch-cookie")(this._fetchType,this._jar),this._abortControllerType=e("abort-controller")}else this._fetchType=fetch.bind(self),this._abortControllerType=AbortController}async send(e){if(e.abortSignal&&e.abortSignal.aborted)throw new ve;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 ve});let r,o=null;if(e.timeout){const r=e.timeout;o=setTimeout((()=>{t.abort(),this._logger.log(Ee.Warning,"Timeout from HTTP request."),n=new we}),r)}try{r=await this._fetchType(e.url,{body:e.content,cache:"no-cache",credentials:!0===e.withCredentials?"include":"same-origin",headers:{"Content-Type":"text/plain;charset=UTF-8","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(Ee.Warning,`Error from HTTP request. ${e}.`),e}finally{o&&clearTimeout(o),e.abortSignal&&(e.abortSignal.onabort=null)}if(!r.ok){const e=await xe(r,"text");throw new ye(e||r.statusText,r.status)}const i=xe(r,e.responseType),s=await i;return new be(r.status,r.statusText,s)}getCookieString(e){return""}}function xe(e,t){let n;switch(t){case"arraybuffer":n=e.arrayBuffer();break;case"text":n=e.text();break;case"blob":case"document":case"json":throw new Error(`${t} is not supported.`);default:n=e.text()}return n}class De extends _e{constructor(e){super(),this._logger=e}send(e){return e.abortSignal&&e.abortSignal.aborted?Promise.reject(new ve):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"),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 ve)}),e.timeout&&(r.timeout=e.timeout),r.onload=()=>{e.abortSignal&&(e.abortSignal.onabort=null),r.status>=200&&r.status<300?t(new be(r.status,r.statusText,r.response||r.responseText)):n(new ye(r.response||r.responseText||r.statusText,r.status))},r.onerror=()=>{this._logger.log(Ee.Warning,`Error from HTTP request. ${r.status}: ${r.statusText}.`),n(new ye(r.statusText,r.status))},r.ontimeout=()=>{this._logger.log(Ee.Warning,"Timeout from HTTP request."),n(new we)},r.send(e.content||"")})):Promise.reject(new Error("No url defined.")):Promise.reject(new Error("No method defined."))}}class Re extends _e{constructor(e){if(super(),"undefined"!=typeof fetch)this._httpClient=new Te(e);else{if("undefined"==typeof XMLHttpRequest)throw new Error("No usable HttpClient found.");this._httpClient=new De(e)}}send(e){return e.abortSignal&&e.abortSignal.aborted?Promise.reject(new ve):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)}}class Pe{}Pe.Authorization="Authorization",Pe.Cookie="Cookie",function(e){e[e.None=0]="None",e[e.WebSockets=1]="WebSockets",e[e.ServerSentEvents=2]="ServerSentEvents",e[e.LongPolling=4]="LongPolling"}(Se||(Se={})),function(e){e[e.Text=1]="Text",e[e.Binary=2]="Binary"}(Ce||(Ce={}));class Ue{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 Ae{constructor(){}log(e,t){}}Ae.instance=new Ae;class Ne{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 Be{static get isBrowser(){return"object"==typeof window}static get isWebWorker(){return"object"==typeof self&&"importScripts"in self}static get isNode(){return!this.isBrowser&&!this.isWebWorker}}function $e(e,t){let n="";return Me(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 Me(e){return e&&"undefined"!=typeof ArrayBuffer&&(e instanceof ArrayBuffer||e.constructor&&"ArrayBuffer"===e.constructor.name)}async function Le(e,t,n,r,o,i,s,a,c){let l={};if(o){const e=await o();e&&(l={Authorization:`Bearer ${e}`})}const[h,u]=Oe();l[h]=u,e.log(Ee.Trace,`(${t} transport) sending data. ${$e(i,s)}.`);const d=Me(i)?"arraybuffer":"text",p=await n.post(r,{content:i,headers:{...l,...c},responseType:d,withCredentials:a});e.log(Ee.Trace,`(${t} transport) request complete. Response status: ${p.statusCode}.`)}class Fe{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 He{constructor(e){this._minLevel=e,this.out=console}log(e,t){if(e>=this._minLevel){const n=`[${(new Date).toISOString()}] ${Ee[e]}: ${t}`;switch(e){case Ee.Critical:case Ee.Error:this.out.error(n);break;case Ee.Warning:this.out.warn(n);break;case Ee.Information:this.out.info(n);break;default:this.out.log(n)}}}}function Oe(){let e="X-SignalR-User-Agent";return Be.isNode&&(e="User-Agent"),[e,je("0.0.0-DEV_BUILD",We(),Be.isNode?"NodeJS":"Browser",ze())]}function je(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 We(){if(!Be.isNode)return"";switch(process.platform){case"win32":return"Windows NT";case"darwin":return"macOS";case"linux":return"Linux";default:return process.platform}}function ze(){if(Be.isNode)return process.versions.node}class qe{constructor(e,t,n,r,o,i){this._httpClient=e,this._accessTokenFactory=t,this._logger=n,this._pollAbort=new Ue,this._logMessageContent=r,this._withCredentials=o,this._headers=i,this._running=!1,this.onreceive=null,this.onclose=null}get pollAborted(){return this._pollAbort.aborted}async connect(e,t){if(Ne.isRequired(e,"url"),Ne.isRequired(t,"transferFormat"),Ne.isIn(t,Ce,"transferFormat"),this._url=e,this._logger.log(Ee.Trace,"(LongPolling transport) Connecting."),t===Ce.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]=Oe(),o={[n]:r,...this._headers},i={abortSignal:this._pollAbort.signal,headers:o,timeout:1e5,withCredentials:this._withCredentials};t===Ce.Binary&&(i.responseType="arraybuffer");const s=await this._getAccessToken();this._updateHeaderToken(i,s);const a=`${e}&_=${Date.now()}`;this._logger.log(Ee.Trace,`(LongPolling transport) polling: ${a}.`);const c=await this._httpClient.get(a,i);200!==c.statusCode?(this._logger.log(Ee.Error,`(LongPolling transport) Unexpected response code: ${c.statusCode}.`),this._closeError=new ye(c.statusText||"",c.statusCode),this._running=!1):this._running=!0,this._receiving=this._poll(this._url,i)}async _getAccessToken(){return this._accessTokenFactory?await this._accessTokenFactory():null}_updateHeaderToken(e,t){e.headers||(e.headers={}),t?e.headers[Pe.Authorization]=`Bearer ${t}`:e.headers[Pe.Authorization]&&delete e.headers[Pe.Authorization]}async _poll(e,t){try{for(;this._running;){const n=await this._getAccessToken();this._updateHeaderToken(t,n);try{const n=`${e}&_=${Date.now()}`;this._logger.log(Ee.Trace,`(LongPolling transport) polling: ${n}.`);const r=await this._httpClient.get(n,t);204===r.statusCode?(this._logger.log(Ee.Information,"(LongPolling transport) Poll terminated by server."),this._running=!1):200!==r.statusCode?(this._logger.log(Ee.Error,`(LongPolling transport) Unexpected response code: ${r.statusCode}.`),this._closeError=new ye(r.statusText||"",r.statusCode),this._running=!1):r.content?(this._logger.log(Ee.Trace,`(LongPolling transport) data received. ${$e(r.content,this._logMessageContent)}.`),this.onreceive&&this.onreceive(r.content)):this._logger.log(Ee.Trace,"(LongPolling transport) Poll timed out, reissuing.")}catch(e){this._running?e instanceof we?this._logger.log(Ee.Trace,"(LongPolling transport) Poll timed out, reissuing."):(this._closeError=e,this._running=!1):this._logger.log(Ee.Trace,`(LongPolling transport) Poll errored after shutdown: ${e.message}`)}}}finally{this._logger.log(Ee.Trace,"(LongPolling transport) Polling complete."),this.pollAborted||this._raiseOnClose()}}async send(e){return this._running?Le(this._logger,"LongPolling",this._httpClient,this._url,this._accessTokenFactory,e,this._logMessageContent,this._withCredentials,this._headers):Promise.reject(new Error("Cannot send until the transport is connected"))}async stop(){this._logger.log(Ee.Trace,"(LongPolling transport) Stopping polling."),this._running=!1,this._pollAbort.abort();try{await this._receiving,this._logger.log(Ee.Trace,`(LongPolling transport) sending DELETE request to ${this._url}.`);const e={},[t,n]=Oe();e[t]=n;const r={headers:{...e,...this._headers},withCredentials:this._withCredentials},o=await this._getAccessToken();this._updateHeaderToken(r,o),await this._httpClient.delete(this._url,r),this._logger.log(Ee.Trace,"(LongPolling transport) DELETE request sent.")}finally{this._logger.log(Ee.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(Ee.Trace,e),this.onclose(this._closeError)}}}class Je{constructor(e,t,n,r,o,i,s){this._httpClient=e,this._accessTokenFactory=t,this._logger=n,this._logMessageContent=r,this._withCredentials=i,this._eventSourceConstructor=o,this._headers=s,this.onreceive=null,this.onclose=null}async connect(e,t){if(Ne.isRequired(e,"url"),Ne.isRequired(t,"transferFormat"),Ne.isIn(t,Ce,"transferFormat"),this._logger.log(Ee.Trace,"(SSE transport) Connecting."),this._url=e,this._accessTokenFactory){const t=await this._accessTokenFactory();t&&(e+=(e.indexOf("?")<0?"?":"&")+`access_token=${encodeURIComponent(t)}`)}return new Promise(((n,r)=>{let o,i=!1;if(t===Ce.Text){if(Be.isBrowser||Be.isWebWorker)o=new this._eventSourceConstructor(e,{withCredentials:this._withCredentials});else{const t=this._httpClient.getCookieString(e),n={};n.Cookie=t;const[r,i]=Oe();n[r]=i,o=new this._eventSourceConstructor(e,{withCredentials:this._withCredentials,headers:{...n,...this._headers}})}try{o.onmessage=e=>{if(this.onreceive)try{this._logger.log(Ee.Trace,`(SSE transport) data received. ${$e(e.data,this._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(Ee.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?Le(this._logger,"SSE",this._httpClient,this._url,this._accessTokenFactory,e,this._logMessageContent,this._withCredentials,this._headers):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 Ke{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){if(Ne.isRequired(e,"url"),Ne.isRequired(t,"transferFormat"),Ne.isIn(t,Ce,"transferFormat"),this._logger.log(Ee.Trace,"(WebSockets transport) Connecting."),this._accessTokenFactory){const t=await this._accessTokenFactory();t&&(e+=(e.indexOf("?")<0?"?":"&")+`access_token=${encodeURIComponent(t)}`)}return new Promise(((n,r)=>{let o;e=e.replace(/^http/,"ws"),this._httpClient.getCookieString(e);let i=!1;o||(o=new this._webSocketConstructor(e)),t===Ce.Binary&&(o.binaryType="arraybuffer"),o.onopen=t=>{this._logger.log(Ee.Information,`WebSocket connected to ${e}.`),this._webSocket=o,i=!0,n()},o.onerror=e=>{let t=null;t="undefined"!=typeof ErrorEvent&&e instanceof ErrorEvent?e.error:"There was an error with the transport",this._logger.log(Ee.Information,`(WebSockets transport) ${t}.`)},o.onmessage=e=>{if(this._logger.log(Ee.Trace,`(WebSockets transport) data received. ${$e(e.data,this._logMessageContent)}.`),this.onreceive)try{this.onreceive(e.data)}catch(e){return void this._close(e)}},o.onclose=e=>{if(i)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(Ee.Trace,`(WebSockets transport) sending data. ${$e(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(Ee.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 Ve{constructor(e,t={}){var n;if(this._stopPromiseResolver=()=>{},this.features={},this._negotiateVersion=1,Ne.isRequired(e,"url"),this._logger=void 0===(n=t.logger)?new He(Ee.Information):null===n?Ae.instance:void 0!==n.log?n:new He(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,"undefined"==typeof WebSocket||t.WebSocket||(t.WebSocket=WebSocket),"undefined"==typeof EventSource||t.EventSource||(t.EventSource=EventSource),this._httpClient=t.httpClient||new Re(this._logger),this._connectionState="Disconnected",this._connectionStarted=!1,this._options=t,this.onreceive=null,this.onclose=null}async start(e){if(e=e||Ce.Binary,Ne.isIn(e,Ce,"transferFormat"),this._logger.log(Ee.Debug,`Starting connection with transfer format '${Ce[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(Ee.Error,e),await this._stopPromise,Promise.reject(new Error(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(Ee.Error,e),Promise.reject(new Error(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 Xe(this.transport)),this._sendQueue.send(e))}async stop(e){return"Disconnected"===this._connectionState?(this._logger.log(Ee.Debug,`Call to HttpConnection.stop(${e}) ignored because the connection is already in the disconnected state.`),Promise.resolve()):"Disconnecting"===this._connectionState?(this._logger.log(Ee.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(Ee.Error,`HttpConnection.transport.stop() threw error '${e}'.`),this._stopConnection()}this.transport=void 0}else this._logger.log(Ee.Debug,"HttpConnection.transport is undefined in HttpConnection.stop() because start() failed.")}async _startInternal(e){let t=this.baseUrl;this._accessTokenFactory=this._options.accessTokenFactory;try{if(this._options.skipNegotiation){if(this._options.transport!==Se.WebSockets)throw new Error("Negotiation can only be skipped when using the WebSocket transport directly.");this.transport=this._constructTransport(Se.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 Error("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}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 qe&&(this.features.inherentKeepAlive=!0),"Connecting"===this._connectionState&&(this._logger.log(Ee.Debug,"The HttpConnection connected successfully."),this._connectionState="Connected")}catch(e){return this._logger.log(Ee.Error,"Failed to start the connection: "+e),this._connectionState="Disconnected",this.transport=void 0,this._stopPromiseResolver(),Promise.reject(e)}}async _getNegotiationResponse(e){const t={};if(this._accessTokenFactory){const e=await this._accessTokenFactory();e&&(t[Pe.Authorization]=`Bearer ${e}`)}const[n,r]=Oe();t[n]=r;const o=this._resolveNegotiateUrl(e);this._logger.log(Ee.Debug,`Sending negotiation request: ${o}.`);try{const e=await this._httpClient.post(o,{content:"",headers:{...t,...this._options.headers},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 ye&&404===e.statusCode&&(t+=" Either this is not a SignalR endpoint or there is a proxy blocking the connection."),this._logger.log(Ee.Error,t),Promise.reject(new Error(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(Ee.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: ${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(Ee.Error,`Failed to start the transport '${n.transport}': ${e}`),a=void 0,i.push(`${n.transport} failed: ${e}`),"Connecting"!==this._connectionState){const e="Failed to select transport before stop() was called.";return this._logger.log(Ee.Debug,e),Promise.reject(new Error(e))}}}}return i.length>0?Promise.reject(new Error(`Unable to connect to the server with any of the available transports. ${i.join(" ")}`)):Promise.reject(new Error("None of the transports supported by the client are supported by the server."))}_constructTransport(e){switch(e){case Se.WebSockets:if(!this._options.WebSocket)throw new Error("'WebSocket' is not supported in your environment.");return new Ke(this._httpClient,this._accessTokenFactory,this._logger,this._options.logMessageContent||!1,this._options.WebSocket,this._options.headers||{});case Se.ServerSentEvents:if(!this._options.EventSource)throw new Error("'EventSource' is not supported in your environment.");return new Je(this._httpClient,this._accessTokenFactory,this._logger,this._options.logMessageContent||!1,this._options.EventSource,this._options.withCredentials,this._options.headers||{});case Se.LongPolling:return new qe(this._httpClient,this._accessTokenFactory,this._logger,this._options.logMessageContent||!1,this._options.withCredentials,this._options.headers||{});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=Se[e.transport];if(null==r)return this._logger.log(Ee.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(Ee.Debug,`Skipping transport '${Se[r]}' because it was disabled by the client.`),new Error(`'${Se[r]}' is disabled by the client.`);if(!(e.transferFormats.map((e=>Ce[e])).indexOf(n)>=0))return this._logger.log(Ee.Debug,`Skipping transport '${Se[r]}' because it does not support the requested transfer format '${Ce[n]}'.`),new Error(`'${Se[r]}' does not support ${Ce[n]}.`);if(r===Se.WebSockets&&!this._options.WebSocket||r===Se.ServerSentEvents&&!this._options.EventSource)return this._logger.log(Ee.Debug,`Skipping transport '${Se[r]}' because it is not supported in your environment.'`),new Error(`'${Se[r]}' is not supported in your environment.`);this._logger.log(Ee.Debug,`Selecting transport '${Se[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(Ee.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(Ee.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(Ee.Error,`Connection disconnected with error '${e}'.`):this._logger.log(Ee.Information,"Connection disconnected."),this._sendQueue&&(this._sendQueue.stop().catch((e=>{this._logger.log(Ee.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(Ee.Error,`HttpConnection.onclose(${e}) threw error '${t}'.`)}}}else this._logger.log(Ee.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(!Be.isBrowser||!window.document)throw new Error(`Cannot resolve '${e}'.`);const t=window.document.createElement("a");return t.href=e,this._logger.log(Ee.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 Xe{constructor(e){this._transport=e,this._buffer=[],this._executing=!0,this._sendBufferedData=new Ye,this._transportResult=new Ye,this._sendLoopPromise=this._sendLoop()}send(e){return this._bufferData(e),this._transportResult||(this._transportResult=new Ye),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 Ye;const e=this._transportResult;this._transportResult=void 0;const t="string"==typeof this._buffer[0]?this._buffer.join(""):Xe._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 Ye{constructor(){this.promise=new Promise(((e,t)=>[this._resolver,this._rejecter]=[e,t]))}resolve(){this._resolver()}reject(e){this._rejecter(e)}}class Ge{static write(e){return`${e}${Ge.RecordSeparator}`}static parse(e){if(e[e.length-1]!==Ge.RecordSeparator)throw new Error("Message is incomplete.");const t=e.split(Ge.RecordSeparator);return t.pop(),t}}Ge.RecordSeparatorCode=30,Ge.RecordSeparator=String.fromCharCode(Ge.RecordSeparatorCode);class Qe{writeHandshakeRequest(e){return Ge.write(JSON.stringify(e))}parseHandshakeResponse(e){let t,n;if(Me(e)){const r=new Uint8Array(e),o=r.indexOf(Ge.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(Ge.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=Ge.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"}(Ie||(Ie={}));class Ze{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 Fe(this,e)}}!function(e){e.Disconnected="Disconnected",e.Connecting="Connecting",e.Connected="Connected",e.Disconnecting="Disconnecting",e.Reconnecting="Reconnecting"}(ke||(ke={}));class et{constructor(e,t,n,r){this._nextKeepAlive=0,Ne.isRequired(e,"connection"),Ne.isRequired(t,"logger"),Ne.isRequired(n,"protocol"),this.serverTimeoutInMilliseconds=3e4,this.keepAliveIntervalInMilliseconds=15e3,this._logger=t,this._protocol=n,this.connection=e,this._reconnectPolicy=r,this._handshakeProtocol=new Qe,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=ke.Disconnected,this._connectionStarted=!1,this._cachedPingMessage=this._protocol.writeMessage({type:Ie.Ping})}static create(e,t,n,r){return new et(e,t,n,r)}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!==ke.Disconnected&&this._connectionState!==ke.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!==ke.Disconnected)return Promise.reject(new Error("Cannot start a HubConnection that is not in the 'Disconnected' state."));this._connectionState=ke.Connecting,this._logger.log(Ee.Debug,"Starting HubConnection.");try{await this._startInternal(),this._connectionState=ke.Connected,this._connectionStarted=!0,this._logger.log(Ee.Debug,"HubConnection connected successfully.")}catch(e){return this._connectionState=ke.Disconnected,this._logger.log(Ee.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(Ee.Debug,"Sending handshake request."),await this._sendMessage(this._handshakeProtocol.writeHandshakeRequest(t)),this._logger.log(Ee.Information,`Using HubProtocol '${this._protocol.name}'.`),this._cleanupTimeout(),this._resetTimeoutPeriod(),this._resetKeepAliveInterval(),await e,this._stopDuringStartError)throw this._stopDuringStartError}catch(e){throw this._logger.log(Ee.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){return this._connectionState===ke.Disconnected?(this._logger.log(Ee.Debug,`Call to HubConnection.stop(${e}) ignored because it is already in the disconnected state.`),Promise.resolve()):this._connectionState===ke.Disconnecting?(this._logger.log(Ee.Debug,`Call to HttpConnection.stop(${e}) ignored because the connection is already in the disconnecting state.`),this._stopPromise):(this._connectionState=ke.Disconnecting,this._logger.log(Ee.Debug,"Stopping HubConnection."),this._reconnectDelayHandle?(this._logger.log(Ee.Debug,"Connection stopped during reconnect delay. Done reconnecting."),clearTimeout(this._reconnectDelayHandle),this._reconnectDelayHandle=void 0,this._completeClose(),Promise.resolve()):(this._cleanupTimeout(),this._cleanupPingTimer(),this._stopDuringStartError=e||new Error("The connection was stopped before the hub handshake could complete."),this.connection.stop(e)))}stream(e,...t){const[n,r]=this._replaceStreamingParams(t),o=this._createStreamInvocation(e,t,r);let i;const s=new Ze;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===Ie.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===Ie.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 Ie.Invocation:this._invokeClientMethod(e);break;case Ie.StreamItem:case Ie.Completion:{const t=this._callbacks[e.invocationId];t&&(e.type===Ie.Completion&&delete this._callbacks[e.invocationId],t(e));break}case Ie.Ping:break;case Ie.Close:{this._logger.log(Ee.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(Ee.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(Ee.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(Ee.Error,e);const n=new Error(e);throw this._handshakeRejecter(n),n}return this._logger.log(Ee.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===ke.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."))}_invokeClientMethod(e){const t=this._methods[e.target.toLowerCase()];if(t){try{t.forEach((t=>t.apply(this,e.arguments)))}catch(t){this._logger.log(Ee.Error,`A callback for the method ${e.target.toLowerCase()} threw error '${t}'.`)}if(e.invocationId){const e="Server requested a response, which is not supported in this version of the client.";this._logger.log(Ee.Error,e),this._stopPromise=this._stopInternal(new Error(e))}}else this._logger.log(Ee.Warning,`No client method with the name '${e.target}' found.`)}_connectionClosed(e){this._logger.log(Ee.Debug,`HubConnection.connectionClosed(${e}) called while in state ${this._connectionState}.`),this._stopDuringStartError=this._stopDuringStartError||e||new Error("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===ke.Disconnecting?this._completeClose(e):this._connectionState===ke.Connected&&this._reconnectPolicy?this._reconnect(e):this._connectionState===ke.Connected&&this._completeClose(e)}_completeClose(e){if(this._connectionStarted){this._connectionState=ke.Disconnected,this._connectionStarted=!1;try{this._closedCallbacks.forEach((t=>t.apply(this,[e])))}catch(t){this._logger.log(Ee.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(Ee.Debug,"Connection not reconnecting because the IRetryPolicy returned null on the first reconnect attempt."),void this._completeClose(e);if(this._connectionState=ke.Reconnecting,e?this._logger.log(Ee.Information,`Connection reconnecting because of error '${e}'.`):this._logger.log(Ee.Information,"Connection reconnecting."),0!==this._reconnectingCallbacks.length){try{this._reconnectingCallbacks.forEach((t=>t.apply(this,[e])))}catch(t){this._logger.log(Ee.Error,`An onreconnecting callback called with error '${e}' threw error '${t}'.`)}if(this._connectionState!==ke.Reconnecting)return void this._logger.log(Ee.Debug,"Connection left the reconnecting state in onreconnecting callback. Done reconnecting.")}for(;null!==o;){if(this._logger.log(Ee.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!==ke.Reconnecting)return void this._logger.log(Ee.Debug,"Connection left the reconnecting state during reconnect delay. Done reconnecting.");try{if(await this._startInternal(),this._connectionState=ke.Connected,this._logger.log(Ee.Information,"HubConnection reconnected successfully."),0!==this._reconnectedCallbacks.length)try{this._reconnectedCallbacks.forEach((e=>e.apply(this,[this.connection.connectionId])))}catch(e){this._logger.log(Ee.Error,`An onreconnected callback called with connectionId '${this.connection.connectionId}; threw error '${e}'.`)}return}catch(e){if(this._logger.log(Ee.Information,`Reconnect attempt failed because of error '${e}'.`),this._connectionState!==ke.Reconnecting)return this._logger.log(Ee.Debug,`Connection moved to the '${this._connectionState}' from the reconnecting state during reconnect attempt. Done reconnecting.`),void(this._connectionState===ke.Disconnecting&&this._completeClose());r=e instanceof Error?e:new Error(e.toString()),o=this._getNextRetryDelay(n++,Date.now()-t,r)}}this._logger.log(Ee.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(Ee.Error,`IRetryPolicy.nextRetryDelayInMilliseconds(${e}, ${t}) threw error '${n}'.`),null}}_cancelCallbacksWithError(e){const t=this._callbacks;this._callbacks={},Object.keys(t).forEach((n=>{(0,t[n])(null,e)}))}_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:Ie.Invocation}:{arguments:t,target:e,type:Ie.Invocation};{const n=this._invocationId;return this._invocationId++,0!==r.length?{arguments:t,invocationId:n.toString(),streamIds:r,target:e,type:Ie.Invocation}:{arguments:t,invocationId:n.toString(),target:e,type:Ie.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 ut=ot?new TextDecoder:null,dt=ot?"undefined"!=typeof process&&"force"!==process.env.TEXT_DECODER?200:0:it,pt=function(e,t){this.type=e,this.data=t};function ft(e,t,n){var r=Math.floor(n/4294967296),o=n;e.setUint32(t,r),e.setUint32(t+4,o)}function gt(e,t){return 4294967296*e.getInt32(t)+e.getUint32(t+4)}var mt={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),ft(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:gt(t,4),nsec:t.getUint32(0)};default:throw new Error("Unrecognized data size for timestamp: "+e.length)}}(e);return new Date(1e3*t.sec+t.nsec/1e6)}},yt=function(){function e(){this.builtInEncoders=[],this.builtInDecoders=[],this.encoders=[],this.decoders=[],this.register(mt)}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 "+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: "+e+" bytes in UTF-8");this.writeU8(219),this.writeU32(e)}},e.prototype.encodeString=function(e){if(e.length>ct){var t=st(e);this.ensureBufferSizeToWrite(5+t),this.writeStringHeader(t),lt(e,this.bytes,this.pos),this.pos+=t}else t=st(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: "+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: "+t);this.writeU8(198),this.writeU32(t)}var n=wt(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: "+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=ht(e,t,n),i=Uint8Array.prototype.slice.call(e,t,t+n);return this.store(i,o),o},e}(),St=(_t=function(e,t){return(_t=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])})(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}_t(e,t),e.prototype=null===t?Object.create(t):(n.prototype=t.prototype,new n)}),Ct=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]1||a(e,t)}))})}function a(e,t){try{(n=o[e](t)).value instanceof kt?Promise.resolve(n.value.v).then(c,l):h(i[0][2],n)}catch(e){h(i[0][3],e)}var n}function c(e){a("next",e)}function l(e){a("throw",e)}function h(e,t){e(t),i.shift(),i.length&&a(i[0][0],i[0][1])}},xt=new DataView(new ArrayBuffer(0)),Dt=new Uint8Array(xt.buffer),Rt=function(){try{xt.getInt8(0)}catch(e){return e.constructor}throw new Error("never reached")}(),Pt=new Rt("Insufficient data"),Ut=4294967295,At=new Et,Nt=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 St(t,e),t}(Error),Bt=function(){function e(e,t,n,r,o,i,s,a){void 0===e&&(e=yt.defaultCodec),void 0===t&&(t=void 0),void 0===n&&(n=Ut),void 0===r&&(r=Ut),void 0===o&&(o=Ut),void 0===i&&(i=Ut),void 0===s&&(s=Ut),void 0===a&&(a=At),this.extensionCodec=e,this.context=t,this.maxStrLength=n,this.maxBinLength=r,this.maxArrayLength=o,this.maxMapLength=i,this.maxExtLength=s,this.keyDecoder=a,this.totalPos=0,this.pos=0,this.view=xt,this.bytes=Dt,this.headByte=-1,this.stack=[]}return e.prototype.reinitializeState=function(){this.totalPos=0,this.headByte=-1,this.stack.length=0},e.prototype.setBuffer=function(e){this.bytes=wt(e),this.view=function(e){if(e instanceof ArrayBuffer)return new DataView(e);var t=wt(e);return new DataView(t.buffer,t.byteOffset,t.byteLength)}(this.bytes),this.pos=0},e.prototype.appendBuffer=function(e){if(-1!==this.headByte||this.hasRemaining()){var t=this.bytes.subarray(this.pos),n=wt(e),r=new Uint8Array(t.length+n.length);r.set(t),r.set(n,t.length),this.setBuffer(r)}else this.setBuffer(e)},e.prototype.hasRemaining=function(e){return void 0===e&&(e=1),this.view.byteLength-this.pos>=e},e.prototype.createExtraByteError=function(e){var t=this.view,n=this.pos;return new RangeError("Extra "+(t.byteLength-n)+" of "+t.byteLength+" byte(s) found at buffer["+e+"]")},e.prototype.decode=function(e){this.reinitializeState(),this.setBuffer(e);var t=this.doDecodeSync();if(this.hasRemaining())throw this.createExtraByteError(this.pos);return t},e.prototype.decodeMulti=function(e){return Ct(this,(function(t){switch(t.label){case 0:this.reinitializeState(),this.setBuffer(e),t.label=1;case 1:return this.hasRemaining()?[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,u,d;return Ct(this,(function(p){switch(p.label){case 0:i=!1,p.label=1;case 1:p.trys.push([1,6,7,12]),t=It(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 Rt))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())throw this.createExtraByteError(this.totalPos);return[2,s]}throw h=(l=this).headByte,u=l.pos,d=l.totalPos,new RangeError("Insufficient data in parsing "+bt(h)+" at "+d+" ("+u+" 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 Tt(this,arguments,(function(){var n,r,o,i,s,a,c,l,h;return Ct(this,(function(u){switch(u.label){case 0:n=t,r=-1,u.label=1;case 1:u.trys.push([1,13,14,19]),o=It(e),u.label=2;case 2:return[4,kt(o.next())];case 3:if((i=u.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()),u.label=4;case 4:u.trys.push([4,9,,10]),u.label=5;case 5:return[4,kt(this.doDecodeSync())];case 6:return[4,u.sent()];case 7:return u.sent(),0==--r?[3,8]:[3,5];case 8:return[3,10];case 9:if(!((a=u.sent())instanceof Rt))throw a;return[3,10];case 10:this.totalPos+=this.pos,u.label=11;case 11:return[3,2];case 12:return[3,19];case 13:return c=u.sent(),l={error:c},[3,19];case 14:return u.trys.push([14,,17,18]),i&&!i.done&&(h=o.return)?[4,kt(h.call(o))]:[3,16];case 15:u.sent(),u.label=16;case 16:return[3,18];case 17:if(l)throw l.error;return[7];case 18:return[7];case 19:return[2]}}))}))},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 Nt("Unrecognized type byte: "+bt(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 Nt("The type of key must be string or number but "+typeof t);if("__proto__"===t)throw new Nt("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 Nt("Unrecognized array type byte: "+bt(e))}},e.prototype.pushMapState=function(e){if(e>this.maxMapLength)throw new Nt("Max length exceeded: map length ("+e+") > maxMapLengthLength ("+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 Nt("Max length exceeded: array length ("+e+") > maxArrayLength ("+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 Nt("Max length exceeded: UTF-8 byte length ("+e+") > maxStrLength ("+this.maxStrLength+")");if(this.bytes.byteLengthdt?function(e,t,n){var r=e.subarray(t,t+n);return ut.decode(r)}(this.bytes,o,e):ht(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 Nt("Max length exceeded: bin length ("+e+") > maxBinLength ("+this.maxBinLength+")");if(!this.hasRemaining(e+t))throw Pt;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 Nt("Max length exceeded: ext length ("+e+") > maxExtLength ("+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=gt(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 $t{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 Mt=new Uint8Array([145,Ie.Ping]);class Lt{constructor(e){this.name="messagepack",this.version=1,this.transferFormat=Ce.Binary,this._errorResult=1,this._voidResult=2,this._nonVoidResult=3,e=e||{},this._encoder=new vt(e.extensionCodec,e.context,e.maxDepth,e.initialBufferSize,e.sortKeys,e.forceFloat32,e.ignoreUndefined,e.forceIntegerToFloat),this._decoder=new Bt(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=Ae.instance);const r=$t.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 Ie.Invocation:return this._writeInvocation(e);case Ie.StreamInvocation:return this._writeStreamInvocation(e);case Ie.StreamItem:return this._writeStreamItem(e);case Ie.Completion:return this._writeCompletion(e);case Ie.Ping:return $t.write(Mt);case Ie.CancelInvocation:return this._writeCancelInvocation(e);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 Ie.Invocation:return this._createInvocationMessage(this._readHeaders(n),n);case Ie.StreamItem:return this._createStreamItemMessage(this._readHeaders(n),n);case Ie.Completion:return this._createCompletionMessage(this._readHeaders(n),n);case Ie.Ping:return this._createPingMessage(n);case Ie.Close:return this._createCloseMessage(n);default:return t.log(Ee.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:Ie.Close}}_createPingMessage(e){if(e.length<1)throw new Error("Invalid payload for Ping message.");return{type:Ie.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:Ie.Invocation}:{arguments:t[4],headers:e,streamIds:[],target:t[3],type:Ie.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:Ie.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:Ie.Completion}}_writeInvocation(e){let t;return t=e.streamIds?this._encoder.encode([Ie.Invocation,e.headers||{},e.invocationId||null,e.target,e.arguments,e.streamIds]):this._encoder.encode([Ie.Invocation,e.headers||{},e.invocationId||null,e.target,e.arguments]),$t.write(t.slice())}_writeStreamInvocation(e){let t;return t=e.streamIds?this._encoder.encode([Ie.StreamInvocation,e.headers||{},e.invocationId,e.target,e.arguments,e.streamIds]):this._encoder.encode([Ie.StreamInvocation,e.headers||{},e.invocationId,e.target,e.arguments]),$t.write(t.slice())}_writeStreamItem(e){const t=this._encoder.encode([Ie.StreamItem,e.headers||{},e.invocationId,e.item]);return $t.write(t.slice())}_writeCompletion(e){const t=e.error?this._errorResult:e.result?this._nonVoidResult:this._voidResult;let n;switch(t){case this._errorResult:n=this._encoder.encode([Ie.Completion,e.headers||{},e.invocationId,t,e.error]);break;case this._voidResult:n=this._encoder.encode([Ie.Completion,e.headers||{},e.invocationId,t]);break;case this._nonVoidResult:n=this._encoder.encode([Ie.Completion,e.headers||{},e.invocationId,t,e.result])}return $t.write(n.slice())}_writeCancelInvocation(e){const t=this._encoder.encode([Ie.CancelInvocation,e.headers||{},e.invocationId]);return $t.write(t.slice())}_readHeaders(e){const t=e[1];if("object"!=typeof t)throw new Error("Invalid headers.");return t}}let Ft=!1;const Ht="function"==typeof TextDecoder?new TextDecoder("utf-8"):null,Ot=Ht?Ht.decode.bind(Ht):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("")},jt=Math.pow(2,32),Wt=Math.pow(2,21)-1;function zt(e,t){return e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24}function qt(e,t){return e[t]+(e[t+1]<<8)+(e[t+2]<<16)+(e[t+3]<<24>>>0)}function Jt(e,t){const n=qt(e,t+4);if(n>Wt)throw new Error(`Cannot read uint64 with high order part ${n}, because the result would exceed Number.MAX_SAFE_INTEGER.`);return n*jt+qt(e,t)}class Kt{constructor(e){this.batchData=e;const t=new Gt(e);this.arrayRangeReader=new Qt(e),this.arrayBuilderSegmentReader=new Zt(e),this.diffReader=new Vt(e),this.editReader=new Xt(e,t),this.frameReader=new Yt(e,t)}updatedComponents(){return zt(this.batchData,this.batchData.length-20)}referenceFrames(){return zt(this.batchData,this.batchData.length-16)}disposedComponentIds(){return zt(this.batchData,this.batchData.length-12)}disposedEventHandlerIds(){return zt(this.batchData,this.batchData.length-8)}updatedComponentsEntry(e,t){const n=e+4*t;return zt(this.batchData,n)}referenceFramesEntry(e,t){return e+20*t}disposedComponentIdsEntry(e,t){const n=e+4*t;return zt(this.batchData,n)}disposedEventHandlerIdsEntry(e,t){const n=e+8*t;return Jt(this.batchData,n)}}class Vt{constructor(e){this.batchDataUint8=e}componentId(e){return zt(this.batchDataUint8,e)}edits(e){return e+4}editsEntry(e,t){return e+16*t}}class Xt{constructor(e,t){this.batchDataUint8=e,this.stringReader=t}editType(e){return zt(this.batchDataUint8,e)}siblingIndex(e){return zt(this.batchDataUint8,e+4)}newTreeIndex(e){return zt(this.batchDataUint8,e+8)}moveToSiblingIndex(e){return zt(this.batchDataUint8,e+8)}removedAttributeName(e){const t=zt(this.batchDataUint8,e+12);return this.stringReader.readString(t)}}class Yt{constructor(e,t){this.batchDataUint8=e,this.stringReader=t}frameType(e){return zt(this.batchDataUint8,e)}subtreeLength(e){return zt(this.batchDataUint8,e+4)}elementReferenceCaptureId(e){const t=zt(this.batchDataUint8,e+4);return this.stringReader.readString(t)}componentId(e){return zt(this.batchDataUint8,e+8)}elementName(e){const t=zt(this.batchDataUint8,e+8);return this.stringReader.readString(t)}textContent(e){const t=zt(this.batchDataUint8,e+4);return this.stringReader.readString(t)}markupContent(e){const t=zt(this.batchDataUint8,e+4);return this.stringReader.readString(t)}attributeName(e){const t=zt(this.batchDataUint8,e+4);return this.stringReader.readString(t)}attributeValue(e){const t=zt(this.batchDataUint8,e+8);return this.stringReader.readString(t)}attributeEventHandlerId(e){return Jt(this.batchDataUint8,e+12)}}class Gt{constructor(e){this.batchDataUint8=e,this.stringTableStartIndex=zt(e,e.length-4)}readString(e){if(-1===e)return null;{const n=zt(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(en.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(en.Debug,`Waiting for batch ${this.nextBatchId}. Batch ${e} not processed.`);try{this.nextBatchId++,this.logger.log(en.Debug,`Applying batch ${e}.`),function(e,t){const n=Q[e];if(!n)throw new Error(`There is no browser renderer with ID ${e}.`);const r=t.arrayRangeReader,o=t.updatedComponents(),i=r.values(o),s=r.count(o),a=t.referenceFrames(),c=r.values(a),l=t.diffReader;for(let e=0;e=this.minLevel){const n=`[${(new Date).toISOString()}] ${en[e]}: ${t}`;switch(e){case en.Critical:case en.Error:console.error(n);break;case en.Warning:console.warn(n);break;case en.Information:console.info(n);break;default:console.log(n)}}}}class on{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!==ke.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!==ke.Connected)return!1;const t=await e.invoke("StartCircuit",re.getBaseURI(),re.getLocationHref(),JSON.stringify(this.components.map((e=>e.toRecord()))),this.applicationState||"");return!!t&&(this.initialize(t),!0)}resolveElement(e){const t=Number.parseInt(e);if(Number.isNaN(t))throw new Error(`Invalid sequence number '${e}'.`);return function(e,t){if(!e.parentNode)throw new Error(`Comment not connected to the DOM ${e.textContent}`);const n=e.parentNode,r=k(n,!0),o=A(r);return Array.from(n.childNodes).forEach((e=>o.push(e))),e[C]=r,t&&(e[I]=t,k(t)),k(e)}(this.components[t].start,this.components[t].end)}}const sn={configureSignalR:e=>{},logLevel:en.Warning,reconnectionOptions:{maxRetries:8,retryIntervalMilliseconds:2e4,dialogId:"components-reconnect-modal"}};class an{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.modal.innerHTML='

Alternatively, reload

',this.message=this.modal.querySelector("h5"),this.button=this.modal.querySelector("button"),this.reloadParagraph=this.modal.querySelector("p"),this.loader=this.getLoader(),this.message.after(this.loader),this.button.addEventListener("click",(async()=>{this.show();try{await(null==fe?void 0:fe.reconnect)()||this.rejected()}catch(e){this.logger.log(en.Error,e),this.failed()}})),this.reloadParagraph.querySelector("a").addEventListener("click",(()=>location.reload()))}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",this.message.innerHTML="Reconnection failed. Try reloading the page if you're unable to reconnect.",this.message.querySelector("a").addEventListener("click",(()=>location.reload()))}rejected(){this.button.style.display="none",this.reloadParagraph.style.display="none",this.loader.style.display="none",this.message.innerHTML="Could not reconnect to the server. Reload the page to restore functionality.",this.message.querySelector("a").addEventListener("click",(()=>location.reload()))}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 cn{constructor(e,t,n){this.dialog=e,this.maxRetries=t,this.document=n,this.document=n;const r=this.document.getElementById(cn.MaxRetriesId);r&&(r.innerText=this.maxRetries.toString())}show(){this.removeClasses(),this.dialog.classList.add(cn.ShowClassName)}update(e){const t=this.document.getElementById(cn.CurrentAttemptId);t&&(t.innerText=e.toString())}hide(){this.removeClasses(),this.dialog.classList.add(cn.HideClassName)}failed(){this.removeClasses(),this.dialog.classList.add(cn.FailedClassName)}rejected(){this.removeClasses(),this.dialog.classList.add(cn.RejectedClassName)}removeClasses(){this.dialog.classList.remove(cn.ShowClassName,cn.HideClassName,cn.FailedClassName,cn.RejectedClassName)}}cn.ShowClassName="components-reconnect-show",cn.HideClassName="components-reconnect-hide",cn.FailedClassName="components-reconnect-failed",cn.RejectedClassName="components-reconnect-rejected",cn.MaxRetriesId="components-reconnect-max-retries",cn.CurrentAttemptId="components-reconnect-current-attempt";class ln{constructor(e,t,n){this._currentReconnectionProcess=null,this._logger=e,this._reconnectionDisplay=t,this._reconnectCallback=n||(()=>fe.reconnect())}onConnectionDown(e,t){if(!this._reconnectionDisplay){const t=document.getElementById(e.dialogId);this._reconnectionDisplay=t?new cn(t,e.maxRetries,document):new an(e.dialogId,e.maxRetries,document,this._logger)}this._currentReconnectionProcess||(this._currentReconnectionProcess=new hn(e,this._logger,this._reconnectCallback,this._reconnectionDisplay))}onConnectionUp(){this._currentReconnectionProcess&&(this._currentReconnectionProcess.dispose(),this._currentReconnectionProcess=null)}}class hn{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;thn.MaximumFirstRetryInterval?hn.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(en.Error,e)}}this.reconnectDisplay.failed()}delay(e){return new Promise((t=>setTimeout(t,e)))}}hn.MaximumFirstRetryInterval=3e3;const un=/^\s*Blazor-Component-State:(?[a-zA-Z0-9\+\/=]+)$/;function dn(e){var t;if(e.nodeType===Node.COMMENT_NODE){const n=e.textContent||"",r=un.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 gn(e,t){const n=e.currentElement;if(n&&n.nodeType===Node.COMMENT_NODE&&n.textContent){const r=fn.exec(n.textContent),o=r&&r.groups&&r.groups.descriptor;if(!o)return;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;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.");if(c){const e=mn(c,n);if(!e)throw new Error(`Could not find an end component comment for '${t}'`);return{type:r,assembly:o,typeName:i,parameterDefinitions:s&&atob(s),parameterValues:a&&atob(a),start:t,prerenderId:c,end:e}}return{type:r,assembly:o,typeName:i,parameterDefinitions:s&&atob(s),parameterValues:a&&atob(a),start:t}}}(r,n,e);case"server":return function(e,t,n){const{type:r,descriptor:o,sequence:i,prerenderId:s}=e;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)}'`);if(s){const e=mn(s,n);if(!e)throw new Error(`Could not find an end component comment for '${t}'`);return{type:r,sequence:i,descriptor:o,start:t,prerenderId:s,end:e}}return{type:r,sequence:i,descriptor:o,start:t}}}(r,n,e)}}catch(e){throw new Error(`Found malformed component comment at ${n.textContent}`)}}}function mn(e,t){for(;t.next()&&t.currentElement;){const n=t.currentElement;if(n.nodeType!==Node.COMMENT_NODE)continue;if(!n.textContent)continue;const r=fn.exec(n.textContent),o=r&&r[1];if(o)return yn(o,e),n}}function yn(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 wn{constructor(e){this.childNodes=e,this.currentIndex=-1,this.length=e.length}next(){return this.currentIndex++,this.currentIndexe.sequence-t.sequence))}(e)}(document),o=dn(document),i=new on(r,o||""),s=await Tn(t,n,i);if(!await i.startCircuit(s))return void n.log(en.Error,"Failed to start the circuit.");let a=!1;const c=()=>{if(!a){const e=new FormData,t=i.circuitId;e.append("circuitId",t),a=navigator.sendBeacon("_blazor/disconnect",e)}};fe.disconnect=c,window.addEventListener("unload",c,{capture:!1,once:!0}),fe.reconnect=async e=>{if(Cn)return!1;const r=e||await Tn(t,n,i);return await i.reconnect(r)?(t.reconnectionHandler.onConnectionUp(),!0):(n.log(en.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)},n.log(en.Information,"Blazor server-side application started.")}async function Tn(t,n,r){const i=new Lt;i.name="blazorpack";const s=(new rt).withUrl("_blazor").withHubProtocol(i);t.configureSignalR(s);const a=s.build();o=(e,t)=>{a.send("DispatchBrowserEvent",JSON.stringify(e),JSON.stringify(t))},fe._internal.navigationManager.listenForNavigationEvents(((e,t)=>a.send("OnLocationChanged",e,t))),a.on("JS.AttachComponent",((e,t)=>function(e,t,n){let r=Q[0];r||(r=Q[0]=new V(0)),r.attachRootComponentToLogicalElement(n,t)}(0,r.resolveElement(t),e))),a.on("JS.BeginInvokeJS",e.jsCallDispatcher.beginInvokeJSFromDotNet),a.on("JS.EndInvokeDotNet",e.jsCallDispatcher.endInvokeDotNetFromJS),a.on("JS.ReceiveByteArray",e.jsCallDispatcher.receiveByteArray);const c=tn.getOrCreate(n);a.on("JS.RenderBatch",((e,t)=>{n.log(en.Debug,`Received render batch with id ${e} and ${t.byteLength} bytes.`),c.processBatch(e,t,a)})),a.onclose((e=>!Cn&&t.reconnectionHandler.onConnectionDown(t.reconnectionOptions,e))),a.on("JS.Error",(e=>{Cn=!0,xn(a,e,n),async function(){let e=document.querySelector("#blazor-error-ui");e&&(e.style.display="block"),Ft||(Ft=!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()}})))}()})),fe._internal.forceCloseConnection=()=>a.stop();try{await a.start()}catch(e){xn(a,e,n)}return e.attachDispatcher({beginInvokeDotNetFromJS:(e,t,n,r,o)=>{a.send("BeginInvokeDotNetFromJS",e?e.toString():null,t,n,r||0,o)},endInvokeJSFromDotNet:(e,t,n)=>{a.send("EndInvokeJSFromDotNet",e,t,n)},sendByteArray:(e,t)=>{a.send("ReceiveByteArray",e,t)}}),a}function xn(e,t,n){n.log(en.Error,t),e&&e.stop()}fe.start=kn,document&&document.currentScript&&"false"!==document.currentScript.getAttribute("autostart")&&kn()})(); \ No newline at end of file +(()=>{"use strict";var e,t,n;!function(e){window.DotNet=e;const t=[],n=new Map;class r{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 o="__jsObjectId",i={},s={0:new r(window)};s[0]._cachedFunctions.set("import",(e=>("string"==typeof e&&e.startsWith("./")&&(e=document.baseURI+e.substr(2)),import(e))));let a,c=1,l=1,h=null;function u(e){t.push(e)}function d(e){if(e&&"object"==typeof e){s[l]=new r(e);const t={[o]:l};return l++,t}throw new Error(`Cannot create a JSObjectReference from the value '${e}'.`)}function p(e){if(!(e.buffer instanceof ArrayBuffer))throw new Error(`Cannot create a JSStreamReference from the value '${e}' as it is not have a 'buffer' property of type 'ArrayBuffer'.`);if(void 0===e.byteLength)throw new Error(`Cannot create a JSStreamReference from the value '${e}' as it doesn't have a byteLength.`);const t={__jsStreamReferenceLength:e.byteLength};try{const n=d(e);t.__jsObjectId=n.__jsObjectId}catch{throw new Error(`Cannot create a JSStreamReference from the value '${e}'.`)}return t}function f(e){return e?JSON.parse(e,((e,n)=>t.reduce(((t,n)=>n(e,t)),n))):null}function g(e,t,n,r){const o=y();if(o.invokeDotNetFromJS){const i=k(r),s=o.invokeDotNetFromJS(e,t,n,i);return s?f(s):null}throw new Error("The current dispatcher does not support synchronous calls from JS to .NET. Use invokeMethodAsync instead.")}function m(e,t,n,r){if(e&&n)throw new Error(`For instance method calls, assemblyName should be null. Received '${e}'.`);const o=c++,s=new Promise(((e,t)=>{i[o]={resolve:e,reject:t}}));try{const i=k(r);y().beginInvokeDotNetFromJS(o,e,t,n,i)}catch(e){w(o,!1,e)}return s}function y(){if(null!==h)return h;throw new Error("No .NET call dispatcher has been set.")}function w(e,t,n){if(!i.hasOwnProperty(e))throw new Error(`There is no pending async call with ID ${e}.`);const r=i[e];delete i[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){let n=s[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 s[e]}e.attachDispatcher=function(e){h=e},e.attachReviver=u,e.invokeMethod=function(e,t,...n){return g(e,t,null,n)},e.invokeMethodAsync=function(e,t,...n){return m(e,t,null,n)},e.createJSObjectReference=d,e.createJSStreamReference=p,e.disposeJSObjectReference=function(e){const t=e&&e.__jsObjectId;"number"==typeof t&&_(t)},function(e){e[e.Default=0]="Default",e[e.JSObjectReference=1]="JSObjectReference",e[e.JSStreamReference=2]="JSStreamReference"}(a=e.JSCallResultType||(e.JSCallResultType={})),e.jsCallDispatcher={findJSFunction:b,disposeJSObjectReferenceById:_,invokeJSFromDotNet:(e,t,n,r)=>{const o=C(b(e,r).apply(null,f(t)),n);return null==o?null:k(o)},beginInvokeJSFromDotNet:(e,t,n,r,o)=>{const i=new Promise((e=>{e(b(t,o).apply(null,f(n)))}));e&&i.then((t=>y().endInvokeJSFromDotNet(e,!0,k([e,!0,C(t,r)]))),(t=>y().endInvokeJSFromDotNet(e,!1,JSON.stringify([e,!1,v(t)]))))},endInvokeDotNetFromJS:(e,t,n)=>{const r=t?f(n):new Error(n);w(parseInt(e),t,r)},receiveByteArray:(e,t)=>{n.set(e,t)}};class E{constructor(e){this._id=e}invokeMethod(e,...t){return g(null,e,this._id,t)}invokeMethodAsync(e,...t){return m(null,e,this._id,t)}dispose(){m(null,"__Dispose",this._id,null).catch((e=>console.error(e)))}serializeAsArg(){return{__dotNetObject:this._id}}}const S="__byte[]";function C(e,t){switch(t){case a.Default:return e;case a.JSObjectReference:return d(e);case a.JSStreamReference:return p(e);default:throw new Error(`Invalid JS call result type '${t}'.`)}}u((function(e,t){if(t&&"object"==typeof t){if(t.hasOwnProperty("__dotNetObject"))return new E(t.__dotNetObject);if(t.hasOwnProperty(o)){const e=t.__jsObjectId,n=s[e];if(n)return n.getWrappedObject();throw new Error(`JS object instance with Id '${e}' does not exist. It may have been disposed.`)}if(t.hasOwnProperty(S)){const e=t["__byte[]"],r=n.get(e);if(void 0===r)throw new Error(`Byte array index '${e}' does not exist.`);return r}}return t}));let I=0;function k(e){return I=0,JSON.stringify(e,T)}function T(e,t){if(t instanceof E)return t.serializeAsArg();if(t instanceof Uint8Array){h.sendByteArray(I,t);const e={[S]:I};return I++,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"}(n||(n={}));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}}let o;function i(e,t){if(!o)throw new Error("eventDispatcher not initialized. Call 'setEventDispatcher' to configure it.");o(e,t)}const s=new Map,a=new Map,c={createEventArgs:()=>({})},l=[];function h(e){return s.get(e)}function u(e){const t=s.get(e);return(null==t?void 0:t.browserEventName)||e}function d(e,t){e.forEach((e=>s.set(e,t)))}function p(e){const t=[];for(let n=0;n{return{...f(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}}),d(["focus","blur","focusin","focusout"],c),d(["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};var t}}),d(["contextmenu","click","mouseover","mouseout","mousemove","mousedown","mouseup","dblclick"],{createEventArgs:e=>f(e)}),d(["error"],{createEventArgs:e=>{return{message:(t=e).message,filename:t.filename,lineno:t.lineno,colno:t.colno};var t}}),d(["loadstart","timeout","abort","load","loadend","progress"],{createEventArgs:e=>{return{lengthComputable:(t=e).lengthComputable,loaded:t.loaded,total:t.total};var t}}),d(["touchcancel","touchend","touchmove","touchenter","touchleave","touchstart"],{createEventArgs:e=>{return{detail:(t=e).detail,touches:p(t.touches),targetTouches:p(t.targetTouches),changedTouches:p(t.changedTouches),ctrlKey:t.ctrlKey,shiftKey:t.shiftKey,altKey:t.altKey,metaKey:t.metaKey,type:t.type};var t}}),d(["gotpointercapture","lostpointercapture","pointercancel","pointerdown","pointerenter","pointerleave","pointermove","pointerout","pointerover","pointerup"],{createEventArgs:e=>{return{...f(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}}),d(["wheel","mousewheel"],{createEventArgs:e=>{return{...f(t=e),deltaX:t.deltaX,deltaY:t.deltaY,deltaZ:t.deltaZ,deltaMode:t.deltaMode};var t}}),d(["toggle"],c);const g=["date","datetime-local","month","time","week"],m=E(["abort","blur","change","error","focus","load","loadend","loadstart","mouseenter","mouseleave","progress","reset","scroll","submit","unload","toggle","DOMNodeInsertedIntoDocument","DOMNodeRemovedFromDocument"]),y={submit:!0},w=E(["click","dblclick","mousedown","mousemove","mouseup"]);class v{constructor(e){this.browserRendererId=e,this.afterClickCallbacks=[];const t=++v.nextEventDelegatorId;this.eventsCollectionKey=`_blazorEvents_${t}`,this.eventInfoStore=new b(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,a.get(n));var n;t&&t.forEach((t=>this.dispatchGlobalEventToAllElements(t,e))),"click"===e.type&&this.afterClickCallbacks.forEach((t=>t(e)))}dispatchGlobalEventToAllElements(e,t){let n=t.target,o=null,s=!1;const a=m.hasOwnProperty(e);let c=!1;for(;n;){const d=this.getEventHandlerInfosForElement(n,!1);if(d){const a=d.getHandler(e);if(a&&(l=n,u=t.type,!((l instanceof HTMLButtonElement||l instanceof HTMLInputElement||l instanceof HTMLTextAreaElement||l instanceof HTMLSelectElement)&&w.hasOwnProperty(u)&&l.disabled))){if(!s){const n=h(e);o=(null==n?void 0:n.createEventArgs)?n.createEventArgs(t):{},s=!0}y.hasOwnProperty(t.type)&&t.preventDefault(),i({browserRendererId:this.browserRendererId,eventHandlerId:a.eventHandlerId,eventName:e,eventFieldInfo:r.fromEvent(a.renderingComponentId,t)},o)}d.stopPropagation(e)&&(c=!0),d.preventDefault(e)&&t.preventDefault()}n=a||c?null:n.parentElement}var l,u}getEventHandlerInfosForElement(e,t){return e.hasOwnProperty(this.eventsCollectionKey)?e[this.eventsCollectionKey]:t?e[this.eventsCollectionKey]=new _:null}}v.nextEventDelegatorId=0;class b{constructor(e){this.globalListener=e,this.infosByEventHandlerId={},this.countByEventName={},l.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=u(e),this.countByEventName.hasOwnProperty(e))this.countByEventName[e]++;else{this.countByEventName[e]=1;const t=m.hasOwnProperty(e);document.addEventListener(e,this.globalListener,t)}}update(e,t){if(this.infosByEventHandlerId.hasOwnProperty(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=u(t.eventName);0==--this.countByEventName[n]&&(delete this.countByEventName[n],document.removeEventListener(n,this.globalListener))}return t}handleEventNameAliasAdded(e,t){if(this.countByEventName.hasOwnProperty(e)){const n=this.countByEventName[e];delete this.countByEventName[e],document.removeEventListener(e,this.globalListener),this.addGlobalListener(t),this.countByEventName[t]+=n-1}}}class _{constructor(){this.handlers={},this.preventDefaultFlags=null,this.stopPropagationFlags=null}getHandler(e){return this.handlers.hasOwnProperty(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 E(e){const t={};return e.forEach((e=>{t[e]=!0})),t}const S=O("_blazorLogicalChildren"),C=O("_blazorLogicalParent"),I=O("_blazorLogicalEnd");function k(e,t){if(e.childNodes.length>0&&!t)throw new Error("New logical elements must start empty, or allowExistingContents must be true");return S in e||(e[S]=[]),e}function T(e,t){const n=document.createComment("!");return D(n,e,t),n}function D(e,t,n){const r=e;if(e instanceof Comment&&A(r)&&A(r).length>0)throw new Error("Not implemented: inserting non-empty logical container");if(R(r))throw new Error("Not implemented: moving existing logical children");const o=A(t);if(n0;)x(n,0)}const r=n;r.parentNode.removeChild(r)}function R(e){return e[C]||null}function P(e,t){return A(e)[t]}function U(e){var t=B(e);return"http://www.w3.org/2000/svg"===t.namespaceURI&&"foreignObject"!==t.tagName}function A(e){return e[S]}function N(e,t){const n=A(e);t.forEach((e=>{e.moveRangeStart=n[e.fromSiblingIndex],e.moveRangeEnd=M(e.moveRangeStart)})),t.forEach((t=>{const r=t.moveToBeforeMarker=document.createComment("marker"),o=n[t.toSiblingIndex+1];o?o.parentNode.insertBefore(r,o):L(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 B(e){if(e instanceof Element)return e;if(e instanceof Comment)return e.parentNode;throw new Error("Not a valid logical element")}function $(e){const t=A(R(e));return t[Array.prototype.indexOf.call(t,e)+1]||null}function L(e,t){if(t instanceof Element)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=$(t);n?n.parentNode.insertBefore(e,n):L(e,R(t))}}}function M(e){if(e instanceof Element)return e;const t=$(e);if(t)return t.previousSibling;{const t=R(e);return t instanceof Element?t.lastChild:M(t)}}function O(e){return"function"==typeof Symbol?Symbol():e}function F(e){return`_bl_${e}`}e.attachReviver(((e,t)=>t&&"object"==typeof t&&t.hasOwnProperty("__internalId")&&"string"==typeof t.__internalId?function(e){const t=`[${F(e)}]`;return document.querySelector(t)}(t.__internalId):t));const H="_blazorDeferredValue",j=document.createElement("template"),W=document.createElementNS("http://www.w3.org/2000/svg","g"),z={},q="__internal_",J="preventDefault_",K="stopPropagation_";class V{constructor(e){this.childComponentLocations={},this.eventDelegator=new v(e),this.eventDelegator.notifyAfterClick((e=>{if(!ee)return;if(0!==e.button||function(e){return e.ctrlKey||e.shiftKey||e.altKey||e.metaKey}(e))return;if(e.defaultPrevented)return;const t=function(e){const t=!window._blazorDisableComposedPath&&e.composedPath&&e.composedPath();if(t){for(let e=0;ese(!1))))},enableNavigationInterception:function(){ee=!0},navigateTo:oe,getBaseURI:()=>document.baseURI,getLocationHref:()=>location.href};function oe(e,t,n=!1){const r=ce(e);if(!t&&he(r))ie(r,!1,n);else if(t&&location.href===e){const t=e+"?";history.replaceState(null,"",t),location.replace(e)}else n?history.replaceState(null,"",r):location.href=e}function ie(e,t,n=!1){Z=!0,n?history.replaceState(null,"",e):history.pushState(null,"",e),se(t)}async function se(e){ne&&await ne(location.href,e)}let ae;function ce(e){return ae=ae||document.createElement("a"),ae.href=e,ae.href}function le(e,t){return e?e.tagName===t?e:le(e.parentElement,t):null}function he(e){const t=(n=document.baseURI).substr(0,n.lastIndexOf("/")+1);var n;return e.startsWith(t)}const ue={init:function(e,t,n,r=50){const o=pe(t);(o||document.documentElement).style.overflowAnchor="none";const i=new IntersectionObserver((function(r){r.forEach((r=>{var o;if(!r.isIntersecting)return;const i=t.getBoundingClientRect(),s=n.getBoundingClientRect().top-i.bottom,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`});i.observe(t),i.observe(n);const s=c(t),a=c(n);function c(e){const t=new MutationObserver((()=>{i.unobserve(e),i.observe(e)}));return t.observe(e,{attributes:!0}),t}de[e._id]={intersectionObserver:i,mutationObserverBefore:s,mutationObserverAfter:a}},dispose:function(e){const t=de[e._id];t&&(t.intersectionObserver.disconnect(),t.mutationObserverBefore.disconnect(),t.mutationObserverAfter.disconnect(),e.dispose(),delete de[e._id])}},de={};function pe(e){return e?"visible"!==getComputedStyle(e).overflowY?e:pe(e.parentElement):null}const fe={navigateTo:oe,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=a.get(t.browserEventName);n?n.push(e):a.set(t.browserEventName,[e]),l.forEach((n=>n(e,t.browserEventName)))}s.set(e,t)},_internal:{navigationManager:re,domWrapper:{focus:function(e,t){if(!(e instanceof HTMLElement))throw new Error("Unable to focus an invalid element.");e.focus({preventScroll:t})},focusBySelector:function(e){const t=document.querySelector(e);t&&(t.hasAttribute("tabindex")||(t.tabIndex=-1),t.focus())}},Virtualize:ue}};window.Blazor=fe;const ge=[0,2e3,1e4,3e4,null];class me{constructor(e){this._retryDelays=void 0!==e?[...e,null]:ge}nextRetryDelayInMilliseconds(e){return this._retryDelays[e.previousRetryCount]}}class ye extends Error{constructor(e,t){const n=new.target.prototype;super(`${e}: Status code '${t}'`),this.statusCode=t,this.__proto__=n}}class we extends Error{constructor(e="A timeout occurred."){const t=new.target.prototype;super(e),this.__proto__=t}}class ve extends Error{constructor(e="An abort occurred."){const t=new.target.prototype;super(e),this.__proto__=t}}class be{constructor(e,t,n){this.statusCode=e,this.statusText=t,this.content=n}}class _e{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""}}var Ee,Se,Ce,Ie,ke;!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"}(Ee||(Ee={}));class Te extends _e{constructor(e){if(super(),this._logger=e,"undefined"==typeof fetch){const e=require;this._jar=new(e("tough-cookie").CookieJar),this._fetchType=e("node-fetch"),this._fetchType=e("fetch-cookie")(this._fetchType,this._jar),this._abortControllerType=e("abort-controller")}else this._fetchType=fetch.bind(self),this._abortControllerType=AbortController}async send(e){if(e.abortSignal&&e.abortSignal.aborted)throw new ve;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 ve});let r,o=null;if(e.timeout){const r=e.timeout;o=setTimeout((()=>{t.abort(),this._logger.log(Ee.Warning,"Timeout from HTTP request."),n=new we}),r)}try{r=await this._fetchType(e.url,{body:e.content,cache:"no-cache",credentials:!0===e.withCredentials?"include":"same-origin",headers:{"Content-Type":"text/plain;charset=UTF-8","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(Ee.Warning,`Error from HTTP request. ${e}.`),e}finally{o&&clearTimeout(o),e.abortSignal&&(e.abortSignal.onabort=null)}if(!r.ok){const e=await De(r,"text");throw new ye(e||r.statusText,r.status)}const i=De(r,e.responseType),s=await i;return new be(r.status,r.statusText,s)}getCookieString(e){return""}}function De(e,t){let n;switch(t){case"arraybuffer":n=e.arrayBuffer();break;case"text":n=e.text();break;case"blob":case"document":case"json":throw new Error(`${t} is not supported.`);default:n=e.text()}return n}class xe extends _e{constructor(e){super(),this._logger=e}send(e){return e.abortSignal&&e.abortSignal.aborted?Promise.reject(new ve):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"),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 ve)}),e.timeout&&(r.timeout=e.timeout),r.onload=()=>{e.abortSignal&&(e.abortSignal.onabort=null),r.status>=200&&r.status<300?t(new be(r.status,r.statusText,r.response||r.responseText)):n(new ye(r.response||r.responseText||r.statusText,r.status))},r.onerror=()=>{this._logger.log(Ee.Warning,`Error from HTTP request. ${r.status}: ${r.statusText}.`),n(new ye(r.statusText,r.status))},r.ontimeout=()=>{this._logger.log(Ee.Warning,"Timeout from HTTP request."),n(new we)},r.send(e.content||"")})):Promise.reject(new Error("No url defined.")):Promise.reject(new Error("No method defined."))}}class Re extends _e{constructor(e){if(super(),"undefined"!=typeof fetch)this._httpClient=new Te(e);else{if("undefined"==typeof XMLHttpRequest)throw new Error("No usable HttpClient found.");this._httpClient=new xe(e)}}send(e){return e.abortSignal&&e.abortSignal.aborted?Promise.reject(new ve):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)}}class Pe{}Pe.Authorization="Authorization",Pe.Cookie="Cookie",function(e){e[e.None=0]="None",e[e.WebSockets=1]="WebSockets",e[e.ServerSentEvents=2]="ServerSentEvents",e[e.LongPolling=4]="LongPolling"}(Se||(Se={})),function(e){e[e.Text=1]="Text",e[e.Binary=2]="Binary"}(Ce||(Ce={}));class Ue{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 Ae{constructor(){}log(e,t){}}Ae.instance=new Ae;class Ne{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 Be{static get isBrowser(){return"object"==typeof window}static get isWebWorker(){return"object"==typeof self&&"importScripts"in self}static get isNode(){return!this.isBrowser&&!this.isWebWorker}}function $e(e,t){let n="";return Le(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 Le(e){return e&&"undefined"!=typeof ArrayBuffer&&(e instanceof ArrayBuffer||e.constructor&&"ArrayBuffer"===e.constructor.name)}async function Me(e,t,n,r,o,i,s,a,c){let l={};if(o){const e=await o();e&&(l={Authorization:`Bearer ${e}`})}const[h,u]=He();l[h]=u,e.log(Ee.Trace,`(${t} transport) sending data. ${$e(i,s)}.`);const d=Le(i)?"arraybuffer":"text",p=await n.post(r,{content:i,headers:{...l,...c},responseType:d,withCredentials:a});e.log(Ee.Trace,`(${t} transport) request complete. Response status: ${p.statusCode}.`)}class Oe{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 Fe{constructor(e){this._minLevel=e,this.out=console}log(e,t){if(e>=this._minLevel){const n=`[${(new Date).toISOString()}] ${Ee[e]}: ${t}`;switch(e){case Ee.Critical:case Ee.Error:this.out.error(n);break;case Ee.Warning:this.out.warn(n);break;case Ee.Information:this.out.info(n);break;default:this.out.log(n)}}}}function He(){let e="X-SignalR-User-Agent";return Be.isNode&&(e="User-Agent"),[e,je("0.0.0-DEV_BUILD",We(),Be.isNode?"NodeJS":"Browser",ze())]}function je(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 We(){if(!Be.isNode)return"";switch(process.platform){case"win32":return"Windows NT";case"darwin":return"macOS";case"linux":return"Linux";default:return process.platform}}function ze(){if(Be.isNode)return process.versions.node}class qe{constructor(e,t,n,r,o,i){this._httpClient=e,this._accessTokenFactory=t,this._logger=n,this._pollAbort=new Ue,this._logMessageContent=r,this._withCredentials=o,this._headers=i,this._running=!1,this.onreceive=null,this.onclose=null}get pollAborted(){return this._pollAbort.aborted}async connect(e,t){if(Ne.isRequired(e,"url"),Ne.isRequired(t,"transferFormat"),Ne.isIn(t,Ce,"transferFormat"),this._url=e,this._logger.log(Ee.Trace,"(LongPolling transport) Connecting."),t===Ce.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]=He(),o={[n]:r,...this._headers},i={abortSignal:this._pollAbort.signal,headers:o,timeout:1e5,withCredentials:this._withCredentials};t===Ce.Binary&&(i.responseType="arraybuffer");const s=await this._getAccessToken();this._updateHeaderToken(i,s);const a=`${e}&_=${Date.now()}`;this._logger.log(Ee.Trace,`(LongPolling transport) polling: ${a}.`);const c=await this._httpClient.get(a,i);200!==c.statusCode?(this._logger.log(Ee.Error,`(LongPolling transport) Unexpected response code: ${c.statusCode}.`),this._closeError=new ye(c.statusText||"",c.statusCode),this._running=!1):this._running=!0,this._receiving=this._poll(this._url,i)}async _getAccessToken(){return this._accessTokenFactory?await this._accessTokenFactory():null}_updateHeaderToken(e,t){e.headers||(e.headers={}),t?e.headers[Pe.Authorization]=`Bearer ${t}`:e.headers[Pe.Authorization]&&delete e.headers[Pe.Authorization]}async _poll(e,t){try{for(;this._running;){const n=await this._getAccessToken();this._updateHeaderToken(t,n);try{const n=`${e}&_=${Date.now()}`;this._logger.log(Ee.Trace,`(LongPolling transport) polling: ${n}.`);const r=await this._httpClient.get(n,t);204===r.statusCode?(this._logger.log(Ee.Information,"(LongPolling transport) Poll terminated by server."),this._running=!1):200!==r.statusCode?(this._logger.log(Ee.Error,`(LongPolling transport) Unexpected response code: ${r.statusCode}.`),this._closeError=new ye(r.statusText||"",r.statusCode),this._running=!1):r.content?(this._logger.log(Ee.Trace,`(LongPolling transport) data received. ${$e(r.content,this._logMessageContent)}.`),this.onreceive&&this.onreceive(r.content)):this._logger.log(Ee.Trace,"(LongPolling transport) Poll timed out, reissuing.")}catch(e){this._running?e instanceof we?this._logger.log(Ee.Trace,"(LongPolling transport) Poll timed out, reissuing."):(this._closeError=e,this._running=!1):this._logger.log(Ee.Trace,`(LongPolling transport) Poll errored after shutdown: ${e.message}`)}}}finally{this._logger.log(Ee.Trace,"(LongPolling transport) Polling complete."),this.pollAborted||this._raiseOnClose()}}async send(e){return this._running?Me(this._logger,"LongPolling",this._httpClient,this._url,this._accessTokenFactory,e,this._logMessageContent,this._withCredentials,this._headers):Promise.reject(new Error("Cannot send until the transport is connected"))}async stop(){this._logger.log(Ee.Trace,"(LongPolling transport) Stopping polling."),this._running=!1,this._pollAbort.abort();try{await this._receiving,this._logger.log(Ee.Trace,`(LongPolling transport) sending DELETE request to ${this._url}.`);const e={},[t,n]=He();e[t]=n;const r={headers:{...e,...this._headers},withCredentials:this._withCredentials},o=await this._getAccessToken();this._updateHeaderToken(r,o),await this._httpClient.delete(this._url,r),this._logger.log(Ee.Trace,"(LongPolling transport) DELETE request sent.")}finally{this._logger.log(Ee.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(Ee.Trace,e),this.onclose(this._closeError)}}}class Je{constructor(e,t,n,r,o,i,s){this._httpClient=e,this._accessTokenFactory=t,this._logger=n,this._logMessageContent=r,this._withCredentials=i,this._eventSourceConstructor=o,this._headers=s,this.onreceive=null,this.onclose=null}async connect(e,t){if(Ne.isRequired(e,"url"),Ne.isRequired(t,"transferFormat"),Ne.isIn(t,Ce,"transferFormat"),this._logger.log(Ee.Trace,"(SSE transport) Connecting."),this._url=e,this._accessTokenFactory){const t=await this._accessTokenFactory();t&&(e+=(e.indexOf("?")<0?"?":"&")+`access_token=${encodeURIComponent(t)}`)}return new Promise(((n,r)=>{let o,i=!1;if(t===Ce.Text){if(Be.isBrowser||Be.isWebWorker)o=new this._eventSourceConstructor(e,{withCredentials:this._withCredentials});else{const t=this._httpClient.getCookieString(e),n={};n.Cookie=t;const[r,i]=He();n[r]=i,o=new this._eventSourceConstructor(e,{withCredentials:this._withCredentials,headers:{...n,...this._headers}})}try{o.onmessage=e=>{if(this.onreceive)try{this._logger.log(Ee.Trace,`(SSE transport) data received. ${$e(e.data,this._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(Ee.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?Me(this._logger,"SSE",this._httpClient,this._url,this._accessTokenFactory,e,this._logMessageContent,this._withCredentials,this._headers):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 Ke{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){if(Ne.isRequired(e,"url"),Ne.isRequired(t,"transferFormat"),Ne.isIn(t,Ce,"transferFormat"),this._logger.log(Ee.Trace,"(WebSockets transport) Connecting."),this._accessTokenFactory){const t=await this._accessTokenFactory();t&&(e+=(e.indexOf("?")<0?"?":"&")+`access_token=${encodeURIComponent(t)}`)}return new Promise(((n,r)=>{let o;e=e.replace(/^http/,"ws"),this._httpClient.getCookieString(e);let i=!1;o||(o=new this._webSocketConstructor(e)),t===Ce.Binary&&(o.binaryType="arraybuffer"),o.onopen=t=>{this._logger.log(Ee.Information,`WebSocket connected to ${e}.`),this._webSocket=o,i=!0,n()},o.onerror=e=>{let t=null;t="undefined"!=typeof ErrorEvent&&e instanceof ErrorEvent?e.error:"There was an error with the transport",this._logger.log(Ee.Information,`(WebSockets transport) ${t}.`)},o.onmessage=e=>{if(this._logger.log(Ee.Trace,`(WebSockets transport) data received. ${$e(e.data,this._logMessageContent)}.`),this.onreceive)try{this.onreceive(e.data)}catch(e){return void this._close(e)}},o.onclose=e=>{if(i)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(Ee.Trace,`(WebSockets transport) sending data. ${$e(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(Ee.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 Ve{constructor(e,t={}){var n;if(this._stopPromiseResolver=()=>{},this.features={},this._negotiateVersion=1,Ne.isRequired(e,"url"),this._logger=void 0===(n=t.logger)?new Fe(Ee.Information):null===n?Ae.instance:void 0!==n.log?n:new Fe(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,"undefined"==typeof WebSocket||t.WebSocket||(t.WebSocket=WebSocket),"undefined"==typeof EventSource||t.EventSource||(t.EventSource=EventSource),this._httpClient=t.httpClient||new Re(this._logger),this._connectionState="Disconnected",this._connectionStarted=!1,this._options=t,this.onreceive=null,this.onclose=null}async start(e){if(e=e||Ce.Binary,Ne.isIn(e,Ce,"transferFormat"),this._logger.log(Ee.Debug,`Starting connection with transfer format '${Ce[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(Ee.Error,e),await this._stopPromise,Promise.reject(new Error(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(Ee.Error,e),Promise.reject(new Error(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 Xe(this.transport)),this._sendQueue.send(e))}async stop(e){return"Disconnected"===this._connectionState?(this._logger.log(Ee.Debug,`Call to HttpConnection.stop(${e}) ignored because the connection is already in the disconnected state.`),Promise.resolve()):"Disconnecting"===this._connectionState?(this._logger.log(Ee.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(Ee.Error,`HttpConnection.transport.stop() threw error '${e}'.`),this._stopConnection()}this.transport=void 0}else this._logger.log(Ee.Debug,"HttpConnection.transport is undefined in HttpConnection.stop() because start() failed.")}async _startInternal(e){let t=this.baseUrl;this._accessTokenFactory=this._options.accessTokenFactory;try{if(this._options.skipNegotiation){if(this._options.transport!==Se.WebSockets)throw new Error("Negotiation can only be skipped when using the WebSocket transport directly.");this.transport=this._constructTransport(Se.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 Error("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}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 qe&&(this.features.inherentKeepAlive=!0),"Connecting"===this._connectionState&&(this._logger.log(Ee.Debug,"The HttpConnection connected successfully."),this._connectionState="Connected")}catch(e){return this._logger.log(Ee.Error,"Failed to start the connection: "+e),this._connectionState="Disconnected",this.transport=void 0,this._stopPromiseResolver(),Promise.reject(e)}}async _getNegotiationResponse(e){const t={};if(this._accessTokenFactory){const e=await this._accessTokenFactory();e&&(t[Pe.Authorization]=`Bearer ${e}`)}const[n,r]=He();t[n]=r;const o=this._resolveNegotiateUrl(e);this._logger.log(Ee.Debug,`Sending negotiation request: ${o}.`);try{const e=await this._httpClient.post(o,{content:"",headers:{...t,...this._options.headers},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 ye&&404===e.statusCode&&(t+=" Either this is not a SignalR endpoint or there is a proxy blocking the connection."),this._logger.log(Ee.Error,t),Promise.reject(new Error(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(Ee.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: ${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(Ee.Error,`Failed to start the transport '${n.transport}': ${e}`),a=void 0,i.push(`${n.transport} failed: ${e}`),"Connecting"!==this._connectionState){const e="Failed to select transport before stop() was called.";return this._logger.log(Ee.Debug,e),Promise.reject(new Error(e))}}}}return i.length>0?Promise.reject(new Error(`Unable to connect to the server with any of the available transports. ${i.join(" ")}`)):Promise.reject(new Error("None of the transports supported by the client are supported by the server."))}_constructTransport(e){switch(e){case Se.WebSockets:if(!this._options.WebSocket)throw new Error("'WebSocket' is not supported in your environment.");return new Ke(this._httpClient,this._accessTokenFactory,this._logger,this._options.logMessageContent||!1,this._options.WebSocket,this._options.headers||{});case Se.ServerSentEvents:if(!this._options.EventSource)throw new Error("'EventSource' is not supported in your environment.");return new Je(this._httpClient,this._accessTokenFactory,this._logger,this._options.logMessageContent||!1,this._options.EventSource,this._options.withCredentials,this._options.headers||{});case Se.LongPolling:return new qe(this._httpClient,this._accessTokenFactory,this._logger,this._options.logMessageContent||!1,this._options.withCredentials,this._options.headers||{});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=Se[e.transport];if(null==r)return this._logger.log(Ee.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(Ee.Debug,`Skipping transport '${Se[r]}' because it was disabled by the client.`),new Error(`'${Se[r]}' is disabled by the client.`);if(!(e.transferFormats.map((e=>Ce[e])).indexOf(n)>=0))return this._logger.log(Ee.Debug,`Skipping transport '${Se[r]}' because it does not support the requested transfer format '${Ce[n]}'.`),new Error(`'${Se[r]}' does not support ${Ce[n]}.`);if(r===Se.WebSockets&&!this._options.WebSocket||r===Se.ServerSentEvents&&!this._options.EventSource)return this._logger.log(Ee.Debug,`Skipping transport '${Se[r]}' because it is not supported in your environment.'`),new Error(`'${Se[r]}' is not supported in your environment.`);this._logger.log(Ee.Debug,`Selecting transport '${Se[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(Ee.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(Ee.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(Ee.Error,`Connection disconnected with error '${e}'.`):this._logger.log(Ee.Information,"Connection disconnected."),this._sendQueue&&(this._sendQueue.stop().catch((e=>{this._logger.log(Ee.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(Ee.Error,`HttpConnection.onclose(${e}) threw error '${t}'.`)}}}else this._logger.log(Ee.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(!Be.isBrowser||!window.document)throw new Error(`Cannot resolve '${e}'.`);const t=window.document.createElement("a");return t.href=e,this._logger.log(Ee.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 Xe{constructor(e){this._transport=e,this._buffer=[],this._executing=!0,this._sendBufferedData=new Ye,this._transportResult=new Ye,this._sendLoopPromise=this._sendLoop()}send(e){return this._bufferData(e),this._transportResult||(this._transportResult=new Ye),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 Ye;const e=this._transportResult;this._transportResult=void 0;const t="string"==typeof this._buffer[0]?this._buffer.join(""):Xe._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 Ye{constructor(){this.promise=new Promise(((e,t)=>[this._resolver,this._rejecter]=[e,t]))}resolve(){this._resolver()}reject(e){this._rejecter(e)}}class Ge{static write(e){return`${e}${Ge.RecordSeparator}`}static parse(e){if(e[e.length-1]!==Ge.RecordSeparator)throw new Error("Message is incomplete.");const t=e.split(Ge.RecordSeparator);return t.pop(),t}}Ge.RecordSeparatorCode=30,Ge.RecordSeparator=String.fromCharCode(Ge.RecordSeparatorCode);class Qe{writeHandshakeRequest(e){return Ge.write(JSON.stringify(e))}parseHandshakeResponse(e){let t,n;if(Le(e)){const r=new Uint8Array(e),o=r.indexOf(Ge.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(Ge.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=Ge.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"}(Ie||(Ie={}));class Ze{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 Oe(this,e)}}!function(e){e.Disconnected="Disconnected",e.Connecting="Connecting",e.Connected="Connected",e.Disconnecting="Disconnecting",e.Reconnecting="Reconnecting"}(ke||(ke={}));class et{constructor(e,t,n,r){this._nextKeepAlive=0,Ne.isRequired(e,"connection"),Ne.isRequired(t,"logger"),Ne.isRequired(n,"protocol"),this.serverTimeoutInMilliseconds=3e4,this.keepAliveIntervalInMilliseconds=15e3,this._logger=t,this._protocol=n,this.connection=e,this._reconnectPolicy=r,this._handshakeProtocol=new Qe,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=ke.Disconnected,this._connectionStarted=!1,this._cachedPingMessage=this._protocol.writeMessage({type:Ie.Ping})}static create(e,t,n,r){return new et(e,t,n,r)}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!==ke.Disconnected&&this._connectionState!==ke.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!==ke.Disconnected)return Promise.reject(new Error("Cannot start a HubConnection that is not in the 'Disconnected' state."));this._connectionState=ke.Connecting,this._logger.log(Ee.Debug,"Starting HubConnection.");try{await this._startInternal(),this._connectionState=ke.Connected,this._connectionStarted=!0,this._logger.log(Ee.Debug,"HubConnection connected successfully.")}catch(e){return this._connectionState=ke.Disconnected,this._logger.log(Ee.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(Ee.Debug,"Sending handshake request."),await this._sendMessage(this._handshakeProtocol.writeHandshakeRequest(t)),this._logger.log(Ee.Information,`Using HubProtocol '${this._protocol.name}'.`),this._cleanupTimeout(),this._resetTimeoutPeriod(),this._resetKeepAliveInterval(),await e,this._stopDuringStartError)throw this._stopDuringStartError}catch(e){throw this._logger.log(Ee.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){return this._connectionState===ke.Disconnected?(this._logger.log(Ee.Debug,`Call to HubConnection.stop(${e}) ignored because it is already in the disconnected state.`),Promise.resolve()):this._connectionState===ke.Disconnecting?(this._logger.log(Ee.Debug,`Call to HttpConnection.stop(${e}) ignored because the connection is already in the disconnecting state.`),this._stopPromise):(this._connectionState=ke.Disconnecting,this._logger.log(Ee.Debug,"Stopping HubConnection."),this._reconnectDelayHandle?(this._logger.log(Ee.Debug,"Connection stopped during reconnect delay. Done reconnecting."),clearTimeout(this._reconnectDelayHandle),this._reconnectDelayHandle=void 0,this._completeClose(),Promise.resolve()):(this._cleanupTimeout(),this._cleanupPingTimer(),this._stopDuringStartError=e||new Error("The connection was stopped before the hub handshake could complete."),this.connection.stop(e)))}stream(e,...t){const[n,r]=this._replaceStreamingParams(t),o=this._createStreamInvocation(e,t,r);let i;const s=new Ze;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===Ie.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===Ie.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 Ie.Invocation:this._invokeClientMethod(e);break;case Ie.StreamItem:case Ie.Completion:{const t=this._callbacks[e.invocationId];t&&(e.type===Ie.Completion&&delete this._callbacks[e.invocationId],t(e));break}case Ie.Ping:break;case Ie.Close:{this._logger.log(Ee.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(Ee.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(Ee.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(Ee.Error,e);const n=new Error(e);throw this._handshakeRejecter(n),n}return this._logger.log(Ee.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===ke.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."))}_invokeClientMethod(e){const t=this._methods[e.target.toLowerCase()];if(t){try{t.forEach((t=>t.apply(this,e.arguments)))}catch(t){this._logger.log(Ee.Error,`A callback for the method ${e.target.toLowerCase()} threw error '${t}'.`)}if(e.invocationId){const e="Server requested a response, which is not supported in this version of the client.";this._logger.log(Ee.Error,e),this._stopPromise=this._stopInternal(new Error(e))}}else this._logger.log(Ee.Warning,`No client method with the name '${e.target}' found.`)}_connectionClosed(e){this._logger.log(Ee.Debug,`HubConnection.connectionClosed(${e}) called while in state ${this._connectionState}.`),this._stopDuringStartError=this._stopDuringStartError||e||new Error("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===ke.Disconnecting?this._completeClose(e):this._connectionState===ke.Connected&&this._reconnectPolicy?this._reconnect(e):this._connectionState===ke.Connected&&this._completeClose(e)}_completeClose(e){if(this._connectionStarted){this._connectionState=ke.Disconnected,this._connectionStarted=!1;try{this._closedCallbacks.forEach((t=>t.apply(this,[e])))}catch(t){this._logger.log(Ee.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(Ee.Debug,"Connection not reconnecting because the IRetryPolicy returned null on the first reconnect attempt."),void this._completeClose(e);if(this._connectionState=ke.Reconnecting,e?this._logger.log(Ee.Information,`Connection reconnecting because of error '${e}'.`):this._logger.log(Ee.Information,"Connection reconnecting."),0!==this._reconnectingCallbacks.length){try{this._reconnectingCallbacks.forEach((t=>t.apply(this,[e])))}catch(t){this._logger.log(Ee.Error,`An onreconnecting callback called with error '${e}' threw error '${t}'.`)}if(this._connectionState!==ke.Reconnecting)return void this._logger.log(Ee.Debug,"Connection left the reconnecting state in onreconnecting callback. Done reconnecting.")}for(;null!==o;){if(this._logger.log(Ee.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!==ke.Reconnecting)return void this._logger.log(Ee.Debug,"Connection left the reconnecting state during reconnect delay. Done reconnecting.");try{if(await this._startInternal(),this._connectionState=ke.Connected,this._logger.log(Ee.Information,"HubConnection reconnected successfully."),0!==this._reconnectedCallbacks.length)try{this._reconnectedCallbacks.forEach((e=>e.apply(this,[this.connection.connectionId])))}catch(e){this._logger.log(Ee.Error,`An onreconnected callback called with connectionId '${this.connection.connectionId}; threw error '${e}'.`)}return}catch(e){if(this._logger.log(Ee.Information,`Reconnect attempt failed because of error '${e}'.`),this._connectionState!==ke.Reconnecting)return this._logger.log(Ee.Debug,`Connection moved to the '${this._connectionState}' from the reconnecting state during reconnect attempt. Done reconnecting.`),void(this._connectionState===ke.Disconnecting&&this._completeClose());r=e instanceof Error?e:new Error(e.toString()),o=this._getNextRetryDelay(n++,Date.now()-t,r)}}this._logger.log(Ee.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(Ee.Error,`IRetryPolicy.nextRetryDelayInMilliseconds(${e}, ${t}) threw error '${n}'.`),null}}_cancelCallbacksWithError(e){const t=this._callbacks;this._callbacks={},Object.keys(t).forEach((n=>{(0,t[n])(null,e)}))}_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:Ie.Invocation}:{arguments:t,target:e,type:Ie.Invocation};{const n=this._invocationId;return this._invocationId++,0!==r.length?{arguments:t,invocationId:n.toString(),streamIds:r,target:e,type:Ie.Invocation}:{arguments:t,invocationId:n.toString(),target:e,type:Ie.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 ut=ot?new TextDecoder:null,dt=ot?"undefined"!=typeof process&&"force"!==process.env.TEXT_DECODER?200:0:it,pt=function(e,t){this.type=e,this.data=t};function ft(e,t,n){var r=Math.floor(n/4294967296),o=n;e.setUint32(t,r),e.setUint32(t+4,o)}function gt(e,t){return 4294967296*e.getInt32(t)+e.getUint32(t+4)}var mt={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),ft(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:gt(t,4),nsec:t.getUint32(0)};default:throw new Error("Unrecognized data size for timestamp: "+e.length)}}(e);return new Date(1e3*t.sec+t.nsec/1e6)}},yt=function(){function e(){this.builtInEncoders=[],this.builtInDecoders=[],this.encoders=[],this.decoders=[],this.register(mt)}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 "+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: "+e+" bytes in UTF-8");this.writeU8(219),this.writeU32(e)}},e.prototype.encodeString=function(e){if(e.length>ct){var t=st(e);this.ensureBufferSizeToWrite(5+t),this.writeStringHeader(t),lt(e,this.bytes,this.pos),this.pos+=t}else t=st(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: "+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: "+t);this.writeU8(198),this.writeU32(t)}var n=wt(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: "+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=ht(e,t,n),i=Uint8Array.prototype.slice.call(e,t,t+n);return this.store(i,o),o},e}(),St=(_t=function(e,t){return(_t=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])})(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}_t(e,t),e.prototype=null===t?Object.create(t):(n.prototype=t.prototype,new n)}),Ct=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]1||a(e,t)}))})}function a(e,t){try{(n=o[e](t)).value instanceof kt?Promise.resolve(n.value.v).then(c,l):h(i[0][2],n)}catch(e){h(i[0][3],e)}var n}function c(e){a("next",e)}function l(e){a("throw",e)}function h(e,t){e(t),i.shift(),i.length&&a(i[0][0],i[0][1])}},Dt=new DataView(new ArrayBuffer(0)),xt=new Uint8Array(Dt.buffer),Rt=function(){try{Dt.getInt8(0)}catch(e){return e.constructor}throw new Error("never reached")}(),Pt=new Rt("Insufficient data"),Ut=4294967295,At=new Et,Nt=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 St(t,e),t}(Error),Bt=function(){function e(e,t,n,r,o,i,s,a){void 0===e&&(e=yt.defaultCodec),void 0===t&&(t=void 0),void 0===n&&(n=Ut),void 0===r&&(r=Ut),void 0===o&&(o=Ut),void 0===i&&(i=Ut),void 0===s&&(s=Ut),void 0===a&&(a=At),this.extensionCodec=e,this.context=t,this.maxStrLength=n,this.maxBinLength=r,this.maxArrayLength=o,this.maxMapLength=i,this.maxExtLength=s,this.keyDecoder=a,this.totalPos=0,this.pos=0,this.view=Dt,this.bytes=xt,this.headByte=-1,this.stack=[]}return e.prototype.reinitializeState=function(){this.totalPos=0,this.headByte=-1,this.stack.length=0},e.prototype.setBuffer=function(e){this.bytes=wt(e),this.view=function(e){if(e instanceof ArrayBuffer)return new DataView(e);var t=wt(e);return new DataView(t.buffer,t.byteOffset,t.byteLength)}(this.bytes),this.pos=0},e.prototype.appendBuffer=function(e){if(-1!==this.headByte||this.hasRemaining()){var t=this.bytes.subarray(this.pos),n=wt(e),r=new Uint8Array(t.length+n.length);r.set(t),r.set(n,t.length),this.setBuffer(r)}else this.setBuffer(e)},e.prototype.hasRemaining=function(e){return void 0===e&&(e=1),this.view.byteLength-this.pos>=e},e.prototype.createExtraByteError=function(e){var t=this.view,n=this.pos;return new RangeError("Extra "+(t.byteLength-n)+" of "+t.byteLength+" byte(s) found at buffer["+e+"]")},e.prototype.decode=function(e){this.reinitializeState(),this.setBuffer(e);var t=this.doDecodeSync();if(this.hasRemaining())throw this.createExtraByteError(this.pos);return t},e.prototype.decodeMulti=function(e){return Ct(this,(function(t){switch(t.label){case 0:this.reinitializeState(),this.setBuffer(e),t.label=1;case 1:return this.hasRemaining()?[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,u,d;return Ct(this,(function(p){switch(p.label){case 0:i=!1,p.label=1;case 1:p.trys.push([1,6,7,12]),t=It(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 Rt))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())throw this.createExtraByteError(this.totalPos);return[2,s]}throw h=(l=this).headByte,u=l.pos,d=l.totalPos,new RangeError("Insufficient data in parsing "+bt(h)+" at "+d+" ("+u+" 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 Tt(this,arguments,(function(){var n,r,o,i,s,a,c,l,h;return Ct(this,(function(u){switch(u.label){case 0:n=t,r=-1,u.label=1;case 1:u.trys.push([1,13,14,19]),o=It(e),u.label=2;case 2:return[4,kt(o.next())];case 3:if((i=u.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()),u.label=4;case 4:u.trys.push([4,9,,10]),u.label=5;case 5:return[4,kt(this.doDecodeSync())];case 6:return[4,u.sent()];case 7:return u.sent(),0==--r?[3,8]:[3,5];case 8:return[3,10];case 9:if(!((a=u.sent())instanceof Rt))throw a;return[3,10];case 10:this.totalPos+=this.pos,u.label=11;case 11:return[3,2];case 12:return[3,19];case 13:return c=u.sent(),l={error:c},[3,19];case 14:return u.trys.push([14,,17,18]),i&&!i.done&&(h=o.return)?[4,kt(h.call(o))]:[3,16];case 15:u.sent(),u.label=16;case 16:return[3,18];case 17:if(l)throw l.error;return[7];case 18:return[7];case 19:return[2]}}))}))},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 Nt("Unrecognized type byte: "+bt(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 Nt("The type of key must be string or number but "+typeof t);if("__proto__"===t)throw new Nt("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 Nt("Unrecognized array type byte: "+bt(e))}},e.prototype.pushMapState=function(e){if(e>this.maxMapLength)throw new Nt("Max length exceeded: map length ("+e+") > maxMapLengthLength ("+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 Nt("Max length exceeded: array length ("+e+") > maxArrayLength ("+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 Nt("Max length exceeded: UTF-8 byte length ("+e+") > maxStrLength ("+this.maxStrLength+")");if(this.bytes.byteLengthdt?function(e,t,n){var r=e.subarray(t,t+n);return ut.decode(r)}(this.bytes,o,e):ht(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 Nt("Max length exceeded: bin length ("+e+") > maxBinLength ("+this.maxBinLength+")");if(!this.hasRemaining(e+t))throw Pt;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 Nt("Max length exceeded: ext length ("+e+") > maxExtLength ("+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=gt(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 $t{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 Lt=new Uint8Array([145,Ie.Ping]);class Mt{constructor(e){this.name="messagepack",this.version=1,this.transferFormat=Ce.Binary,this._errorResult=1,this._voidResult=2,this._nonVoidResult=3,e=e||{},this._encoder=new vt(e.extensionCodec,e.context,e.maxDepth,e.initialBufferSize,e.sortKeys,e.forceFloat32,e.ignoreUndefined,e.forceIntegerToFloat),this._decoder=new Bt(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=Ae.instance);const r=$t.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 Ie.Invocation:return this._writeInvocation(e);case Ie.StreamInvocation:return this._writeStreamInvocation(e);case Ie.StreamItem:return this._writeStreamItem(e);case Ie.Completion:return this._writeCompletion(e);case Ie.Ping:return $t.write(Lt);case Ie.CancelInvocation:return this._writeCancelInvocation(e);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 Ie.Invocation:return this._createInvocationMessage(this._readHeaders(n),n);case Ie.StreamItem:return this._createStreamItemMessage(this._readHeaders(n),n);case Ie.Completion:return this._createCompletionMessage(this._readHeaders(n),n);case Ie.Ping:return this._createPingMessage(n);case Ie.Close:return this._createCloseMessage(n);default:return t.log(Ee.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:Ie.Close}}_createPingMessage(e){if(e.length<1)throw new Error("Invalid payload for Ping message.");return{type:Ie.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:Ie.Invocation}:{arguments:t[4],headers:e,streamIds:[],target:t[3],type:Ie.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:Ie.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:Ie.Completion}}_writeInvocation(e){let t;return t=e.streamIds?this._encoder.encode([Ie.Invocation,e.headers||{},e.invocationId||null,e.target,e.arguments,e.streamIds]):this._encoder.encode([Ie.Invocation,e.headers||{},e.invocationId||null,e.target,e.arguments]),$t.write(t.slice())}_writeStreamInvocation(e){let t;return t=e.streamIds?this._encoder.encode([Ie.StreamInvocation,e.headers||{},e.invocationId,e.target,e.arguments,e.streamIds]):this._encoder.encode([Ie.StreamInvocation,e.headers||{},e.invocationId,e.target,e.arguments]),$t.write(t.slice())}_writeStreamItem(e){const t=this._encoder.encode([Ie.StreamItem,e.headers||{},e.invocationId,e.item]);return $t.write(t.slice())}_writeCompletion(e){const t=e.error?this._errorResult:e.result?this._nonVoidResult:this._voidResult;let n;switch(t){case this._errorResult:n=this._encoder.encode([Ie.Completion,e.headers||{},e.invocationId,t,e.error]);break;case this._voidResult:n=this._encoder.encode([Ie.Completion,e.headers||{},e.invocationId,t]);break;case this._nonVoidResult:n=this._encoder.encode([Ie.Completion,e.headers||{},e.invocationId,t,e.result])}return $t.write(n.slice())}_writeCancelInvocation(e){const t=this._encoder.encode([Ie.CancelInvocation,e.headers||{},e.invocationId]);return $t.write(t.slice())}_readHeaders(e){const t=e[1];if("object"!=typeof t)throw new Error("Invalid headers.");return t}}let Ot=!1;const Ft="function"==typeof TextDecoder?new TextDecoder("utf-8"):null,Ht=Ft?Ft.decode.bind(Ft):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("")},jt=Math.pow(2,32),Wt=Math.pow(2,21)-1;function zt(e,t){return e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24}function qt(e,t){return e[t]+(e[t+1]<<8)+(e[t+2]<<16)+(e[t+3]<<24>>>0)}function Jt(e,t){const n=qt(e,t+4);if(n>Wt)throw new Error(`Cannot read uint64 with high order part ${n}, because the result would exceed Number.MAX_SAFE_INTEGER.`);return n*jt+qt(e,t)}class Kt{constructor(e){this.batchData=e;const t=new Gt(e);this.arrayRangeReader=new Qt(e),this.arrayBuilderSegmentReader=new Zt(e),this.diffReader=new Vt(e),this.editReader=new Xt(e,t),this.frameReader=new Yt(e,t)}updatedComponents(){return zt(this.batchData,this.batchData.length-20)}referenceFrames(){return zt(this.batchData,this.batchData.length-16)}disposedComponentIds(){return zt(this.batchData,this.batchData.length-12)}disposedEventHandlerIds(){return zt(this.batchData,this.batchData.length-8)}updatedComponentsEntry(e,t){const n=e+4*t;return zt(this.batchData,n)}referenceFramesEntry(e,t){return e+20*t}disposedComponentIdsEntry(e,t){const n=e+4*t;return zt(this.batchData,n)}disposedEventHandlerIdsEntry(e,t){const n=e+8*t;return Jt(this.batchData,n)}}class Vt{constructor(e){this.batchDataUint8=e}componentId(e){return zt(this.batchDataUint8,e)}edits(e){return e+4}editsEntry(e,t){return e+16*t}}class Xt{constructor(e,t){this.batchDataUint8=e,this.stringReader=t}editType(e){return zt(this.batchDataUint8,e)}siblingIndex(e){return zt(this.batchDataUint8,e+4)}newTreeIndex(e){return zt(this.batchDataUint8,e+8)}moveToSiblingIndex(e){return zt(this.batchDataUint8,e+8)}removedAttributeName(e){const t=zt(this.batchDataUint8,e+12);return this.stringReader.readString(t)}}class Yt{constructor(e,t){this.batchDataUint8=e,this.stringReader=t}frameType(e){return zt(this.batchDataUint8,e)}subtreeLength(e){return zt(this.batchDataUint8,e+4)}elementReferenceCaptureId(e){const t=zt(this.batchDataUint8,e+4);return this.stringReader.readString(t)}componentId(e){return zt(this.batchDataUint8,e+8)}elementName(e){const t=zt(this.batchDataUint8,e+8);return this.stringReader.readString(t)}textContent(e){const t=zt(this.batchDataUint8,e+4);return this.stringReader.readString(t)}markupContent(e){const t=zt(this.batchDataUint8,e+4);return this.stringReader.readString(t)}attributeName(e){const t=zt(this.batchDataUint8,e+4);return this.stringReader.readString(t)}attributeValue(e){const t=zt(this.batchDataUint8,e+8);return this.stringReader.readString(t)}attributeEventHandlerId(e){return Jt(this.batchDataUint8,e+12)}}class Gt{constructor(e){this.batchDataUint8=e,this.stringTableStartIndex=zt(e,e.length-4)}readString(e){if(-1===e)return null;{const n=zt(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(en.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(en.Debug,`Waiting for batch ${this.nextBatchId}. Batch ${e} not processed.`);try{this.nextBatchId++,this.logger.log(en.Debug,`Applying batch ${e}.`),function(e,t){const n=Q[e];if(!n)throw new Error(`There is no browser renderer with ID ${e}.`);const r=t.arrayRangeReader,o=t.updatedComponents(),i=r.values(o),s=r.count(o),a=t.referenceFrames(),c=r.values(a),l=t.diffReader;for(let e=0;e=this.minLevel){const n=`[${(new Date).toISOString()}] ${en[e]}: ${t}`;switch(e){case en.Critical:case en.Error:console.error(n);break;case en.Warning:console.warn(n);break;case en.Information:console.info(n);break;default:console.log(n)}}}}class on{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!==ke.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!==ke.Connected)return!1;const t=await e.invoke("StartCircuit",re.getBaseURI(),re.getLocationHref(),JSON.stringify(this.components.map((e=>e.toRecord()))),this.applicationState||"");return!!t&&(this.initialize(t),!0)}resolveElement(e){const t=Number.parseInt(e);if(Number.isNaN(t))throw new Error(`Invalid sequence number '${e}'.`);return function(e,t){if(!e.parentNode)throw new Error(`Comment not connected to the DOM ${e.textContent}`);const n=e.parentNode,r=k(n,!0),o=A(r);return Array.from(n.childNodes).forEach((e=>o.push(e))),e[C]=r,t&&(e[I]=t,k(t)),k(e)}(this.components[t].start,this.components[t].end)}}const sn={configureSignalR:e=>{},logLevel:en.Warning,reconnectionOptions:{maxRetries:8,retryIntervalMilliseconds:2e4,dialogId:"components-reconnect-modal"}};class an{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.modal.innerHTML='

Alternatively, reload

',this.message=this.modal.querySelector("h5"),this.button=this.modal.querySelector("button"),this.reloadParagraph=this.modal.querySelector("p"),this.loader=this.getLoader(),this.message.after(this.loader),this.button.addEventListener("click",(async()=>{this.show();try{await(null==fe?void 0:fe.reconnect)()||this.rejected()}catch(e){this.logger.log(en.Error,e),this.failed()}})),this.reloadParagraph.querySelector("a").addEventListener("click",(()=>location.reload()))}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",this.message.innerHTML="Reconnection failed. Try reloading the page if you're unable to reconnect.",this.message.querySelector("a").addEventListener("click",(()=>location.reload()))}rejected(){this.button.style.display="none",this.reloadParagraph.style.display="none",this.loader.style.display="none",this.message.innerHTML="Could not reconnect to the server. Reload the page to restore functionality.",this.message.querySelector("a").addEventListener("click",(()=>location.reload()))}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 cn{constructor(e,t,n){this.dialog=e,this.maxRetries=t,this.document=n,this.document=n;const r=this.document.getElementById(cn.MaxRetriesId);r&&(r.innerText=this.maxRetries.toString())}show(){this.removeClasses(),this.dialog.classList.add(cn.ShowClassName)}update(e){const t=this.document.getElementById(cn.CurrentAttemptId);t&&(t.innerText=e.toString())}hide(){this.removeClasses(),this.dialog.classList.add(cn.HideClassName)}failed(){this.removeClasses(),this.dialog.classList.add(cn.FailedClassName)}rejected(){this.removeClasses(),this.dialog.classList.add(cn.RejectedClassName)}removeClasses(){this.dialog.classList.remove(cn.ShowClassName,cn.HideClassName,cn.FailedClassName,cn.RejectedClassName)}}cn.ShowClassName="components-reconnect-show",cn.HideClassName="components-reconnect-hide",cn.FailedClassName="components-reconnect-failed",cn.RejectedClassName="components-reconnect-rejected",cn.MaxRetriesId="components-reconnect-max-retries",cn.CurrentAttemptId="components-reconnect-current-attempt";class ln{constructor(e,t,n){this._currentReconnectionProcess=null,this._logger=e,this._reconnectionDisplay=t,this._reconnectCallback=n||(()=>fe.reconnect())}onConnectionDown(e,t){if(!this._reconnectionDisplay){const t=document.getElementById(e.dialogId);this._reconnectionDisplay=t?new cn(t,e.maxRetries,document):new an(e.dialogId,e.maxRetries,document,this._logger)}this._currentReconnectionProcess||(this._currentReconnectionProcess=new hn(e,this._logger,this._reconnectCallback,this._reconnectionDisplay))}onConnectionUp(){this._currentReconnectionProcess&&(this._currentReconnectionProcess.dispose(),this._currentReconnectionProcess=null)}}class hn{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;thn.MaximumFirstRetryInterval?hn.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(en.Error,e)}}this.reconnectDisplay.failed()}delay(e){return new Promise((t=>setTimeout(t,e)))}}hn.MaximumFirstRetryInterval=3e3;const un=/^\s*Blazor-Component-State:(?[a-zA-Z0-9\+\/=]+)$/;function dn(e){var t;if(e.nodeType===Node.COMMENT_NODE){const n=e.textContent||"",r=un.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 gn(e,t){const n=e.currentElement;if(n&&n.nodeType===Node.COMMENT_NODE&&n.textContent){const r=fn.exec(n.textContent),o=r&&r.groups&&r.groups.descriptor;if(!o)return;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;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.");if(c){const e=mn(c,n);if(!e)throw new Error(`Could not find an end component comment for '${t}'`);return{type:r,assembly:o,typeName:i,parameterDefinitions:s&&atob(s),parameterValues:a&&atob(a),start:t,prerenderId:c,end:e}}return{type:r,assembly:o,typeName:i,parameterDefinitions:s&&atob(s),parameterValues:a&&atob(a),start:t}}}(r,n,e);case"server":return function(e,t,n){const{type:r,descriptor:o,sequence:i,prerenderId:s}=e;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)}'`);if(s){const e=mn(s,n);if(!e)throw new Error(`Could not find an end component comment for '${t}'`);return{type:r,sequence:i,descriptor:o,start:t,prerenderId:s,end:e}}return{type:r,sequence:i,descriptor:o,start:t}}}(r,n,e)}}catch(e){throw new Error(`Found malformed component comment at ${n.textContent}`)}}}function mn(e,t){for(;t.next()&&t.currentElement;){const n=t.currentElement;if(n.nodeType!==Node.COMMENT_NODE)continue;if(!n.textContent)continue;const r=fn.exec(n.textContent),o=r&&r[1];if(o)return yn(o,e),n}}function yn(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 wn{constructor(e){this.childNodes=e,this.currentIndex=-1,this.length=e.length}next(){return this.currentIndex++,this.currentIndexe.sequence-t.sequence))}(e)}(document),o=dn(document),i=new on(r,o||""),s=await Tn(t,n,i);if(!await i.startCircuit(s))return void n.log(en.Error,"Failed to start the circuit.");let a=!1;const c=()=>{if(!a){const e=new FormData,t=i.circuitId;e.append("circuitId",t),a=navigator.sendBeacon("_blazor/disconnect",e)}};fe.disconnect=c,window.addEventListener("unload",c,{capture:!1,once:!0}),fe.reconnect=async e=>{if(Cn)return!1;const r=e||await Tn(t,n,i);return await i.reconnect(r)?(t.reconnectionHandler.onConnectionUp(),!0):(n.log(en.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)},n.log(en.Information,"Blazor server-side application started.")}async function Tn(t,n,r){const i=new Mt;i.name="blazorpack";const s=(new rt).withUrl("_blazor").withHubProtocol(i);t.configureSignalR(s);const a=s.build();o=(e,t)=>{a.send("DispatchBrowserEvent",JSON.stringify(e),JSON.stringify(t))},fe._internal.navigationManager.listenForNavigationEvents(((e,t)=>a.send("OnLocationChanged",e,t))),a.on("JS.AttachComponent",((e,t)=>function(e,t,n){let r=Q[0];r||(r=Q[0]=new V(0)),r.attachRootComponentToLogicalElement(n,t)}(0,r.resolveElement(t),e))),a.on("JS.BeginInvokeJS",e.jsCallDispatcher.beginInvokeJSFromDotNet),a.on("JS.EndInvokeDotNet",e.jsCallDispatcher.endInvokeDotNetFromJS),a.on("JS.ReceiveByteArray",e.jsCallDispatcher.receiveByteArray);const c=tn.getOrCreate(n);a.on("JS.RenderBatch",((e,t)=>{n.log(en.Debug,`Received render batch with id ${e} and ${t.byteLength} bytes.`),c.processBatch(e,t,a)})),a.onclose((e=>!Cn&&t.reconnectionHandler.onConnectionDown(t.reconnectionOptions,e))),a.on("JS.Error",(e=>{Cn=!0,Dn(a,e,n),async function(){let e=document.querySelector("#blazor-error-ui");e&&(e.style.display="block"),Ot||(Ot=!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()}})))}()})),fe._internal.forceCloseConnection=()=>a.stop(),fe._internal.sendJSDataStream=(e,t,n)=>function(e,t,n,r){setTimeout((async()=>{let o=5,i=(new Date).valueOf();try{let s=0,a=0;for(;s1)await e.send("ReceiveJSDataChunk",n,a,l,null);else{if(!await e.invoke("ReceiveJSDataChunk",n,a,l,null))break;const t=(new Date).valueOf(),r=t-i;i=t,o=Math.max(1,Math.round(500/Math.max(1,r)))}s+=c,a++}}catch(t){await e.send("ReceiveJSDataChunk",n,-1,null,t.toString())}}),0)}(a,e,t,n);try{await a.start()}catch(e){Dn(a,e,n)}return e.attachDispatcher({beginInvokeDotNetFromJS:(e,t,n,r,o)=>{a.send("BeginInvokeDotNetFromJS",e?e.toString():null,t,n,r||0,o)},endInvokeJSFromDotNet:(e,t,n)=>{a.send("EndInvokeJSFromDotNet",e,t,n)},sendByteArray:(e,t)=>{a.send("ReceiveByteArray",e,t)}}),a}function Dn(e,t,n){n.log(en.Error,t),e&&e.stop()}fe.start=kn,document&&document.currentScript&&"false"!==document.currentScript.getAttribute("autostart")&&kn()})(); \ 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 76f9d38090bd..48ae47f3e564 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;!function(e){window.DotNet=e;const t=[],n=new Map;class r{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 o="__jsObjectId",a={},i={0:new r(window)};i[0]._cachedFunctions.set("import",(e=>("string"==typeof e&&e.startsWith("./")&&(e=document.baseURI+e.substr(2)),import(e))));let s,c=1,l=1,u=null;function d(e){t.push(e)}function h(e){if(e&&"object"==typeof e){i[l]=new r(e);const t={[o]:l};return l++,t}throw new Error(`Cannot create a JSObjectReference from the value '${e}'.`)}function f(e){return e?JSON.parse(e,((e,n)=>t.reduce(((t,n)=>n(e,t)),n))):null}function p(e,t,n,r){const o=v();if(o.invokeDotNetFromJS){const a=C(r),i=o.invokeDotNetFromJS(e,t,n,a);return i?f(i):null}throw new Error("The current dispatcher does not support synchronous calls from JS to .NET. Use invokeMethodAsync instead.")}function m(e,t,n,r){if(e&&n)throw new Error(`For instance method calls, assemblyName should be null. Received '${e}'.`);const o=c++,i=new Promise(((e,t)=>{a[o]={resolve:e,reject:t}}));try{const a=C(r);v().beginInvokeDotNetFromJS(o,e,t,n,a)}catch(e){g(o,!1,e)}return i}function v(){if(null!==u)return u;throw new Error("No .NET call dispatcher has been set.")}function g(e,t,n){if(!a.hasOwnProperty(e))throw new Error(`There is no pending async call with ID ${e}.`);const r=a[e];delete a[e],t?r.resolve(n):r.reject(n)}function b(e){return e instanceof Error?`${e.message}\n${e.stack}`:e?e.toString():"null"}function y(e,t){let n=i[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 i[e]}e.attachDispatcher=function(e){u=e},e.attachReviver=d,e.invokeMethod=function(e,t,...n){return p(e,t,null,n)},e.invokeMethodAsync=function(e,t,...n){return m(e,t,null,n)},e.createJSObjectReference=h,e.disposeJSObjectReference=function(e){const t=e&&e.__jsObjectId;"number"==typeof t&&E(t)},function(e){e[e.Default=0]="Default",e[e.JSObjectReference=1]="JSObjectReference"}(s=e.JSCallResultType||(e.JSCallResultType={})),e.jsCallDispatcher={findJSFunction:y,disposeJSObjectReferenceById:E,invokeJSFromDotNet:(e,t,n,r)=>{const o=S(y(e,r).apply(null,f(t)),n);return null==o?null:C(o)},beginInvokeJSFromDotNet:(e,t,n,r,o)=>{const a=new Promise((e=>{e(y(t,o).apply(null,f(n)))}));e&&a.then((t=>v().endInvokeJSFromDotNet(e,!0,C([e,!0,S(t,r)]))),(t=>v().endInvokeJSFromDotNet(e,!1,JSON.stringify([e,!1,b(t)]))))},endInvokeDotNetFromJS:(e,t,n)=>{const r=t?f(n):new Error(n);g(parseInt(e),t,r)},receiveByteArray:(e,t)=>{n.set(e,t)}};class w{constructor(e){this._id=e}invokeMethod(e,...t){return p(null,e,this._id,t)}invokeMethodAsync(e,...t){return m(null,e,this._id,t)}dispose(){m(null,"__Dispose",this._id,null).catch((e=>console.error(e)))}serializeAsArg(){return{__dotNetObject:this._id}}}const I="__byte[]";function S(e,t){switch(t){case s.Default:return e;case s.JSObjectReference:return h(e);default:throw new Error(`Invalid JS call result type '${t}'.`)}}d((function(e,t){if(t&&"object"==typeof t){if(t.hasOwnProperty("__dotNetObject"))return new w(t.__dotNetObject);if(t.hasOwnProperty(o)){const e=t.__jsObjectId,n=i[e];if(n)return n.getWrappedObject();throw new Error(`JS object instance with Id '${e}' does not exist. It may have been disposed.`)}if(t.hasOwnProperty(I)){const e=t["__byte[]"],r=n.get(e);if(void 0===r)throw new Error(`Byte array index '${e}' does not exist.`);return r}}return t}));let D=0;function C(e){return D=0,JSON.stringify(e,A)}function A(e,t){if(t instanceof w)return t.serializeAsArg();if(t instanceof Uint8Array){u.sendByteArray(D,t);const e={[I]:D};return D++,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"}(n||(n={}));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}}let o;function a(e,t){if(!o)throw new Error("eventDispatcher not initialized. Call 'setEventDispatcher' to configure it.");o(e,t)}const i=new Map,s=new Map,c={createEventArgs:()=>({})},l=[];function u(e){return i.get(e)}function d(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 f(e){const t=[];for(let n=0;n{return{...p(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"],c),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};var t}}),h(["contextmenu","click","mouseover","mouseout","mousemove","mousedown","mouseup","dblclick"],{createEventArgs:e=>p(e)}),h(["error"],{createEventArgs:e=>{return{message:(t=e).message,filename:t.filename,lineno:t.lineno,colno:t.colno};var t}}),h(["loadstart","timeout","abort","load","loadend","progress"],{createEventArgs:e=>{return{lengthComputable:(t=e).lengthComputable,loaded:t.loaded,total:t.total};var t}}),h(["touchcancel","touchend","touchmove","touchenter","touchleave","touchstart"],{createEventArgs:e=>{return{detail:(t=e).detail,touches:f(t.touches),targetTouches:f(t.targetTouches),changedTouches:f(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{...p(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{...p(t=e),deltaX:t.deltaX,deltaY:t.deltaY,deltaZ:t.deltaZ,deltaMode:t.deltaMode};var t}}),h(["toggle"],c);const m=["date","datetime-local","month","time","week"],v=I(["abort","blur","change","error","focus","load","loadend","loadstart","mouseenter","mouseleave","progress","reset","scroll","submit","unload","toggle","DOMNodeInsertedIntoDocument","DOMNodeRemovedFromDocument"]),g={submit:!0},b=I(["click","dblclick","mousedown","mousemove","mouseup"]);class y{constructor(e){this.browserRendererId=e,this.afterClickCallbacks=[];const t=++y.nextEventDelegatorId;this.eventsCollectionKey=`_blazorEvents_${t}`,this.eventInfoStore=new E(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){let n=t.target,o=null,i=!1;const s=v.hasOwnProperty(e);let c=!1;for(;n;){const h=this.getEventHandlerInfosForElement(n,!1);if(h){const s=h.getHandler(e);if(s&&(l=n,d=t.type,!((l instanceof HTMLButtonElement||l instanceof HTMLInputElement||l instanceof HTMLTextAreaElement||l instanceof HTMLSelectElement)&&b.hasOwnProperty(d)&&l.disabled))){if(!i){const n=u(e);o=(null==n?void 0:n.createEventArgs)?n.createEventArgs(t):{},i=!0}g.hasOwnProperty(t.type)&&t.preventDefault(),a({browserRendererId:this.browserRendererId,eventHandlerId:s.eventHandlerId,eventName:e,eventFieldInfo:r.fromEvent(s.renderingComponentId,t)},o)}h.stopPropagation(e)&&(c=!0),h.preventDefault(e)&&t.preventDefault()}n=s||c?null:n.parentElement}var l,d}getEventHandlerInfosForElement(e,t){return e.hasOwnProperty(this.eventsCollectionKey)?e[this.eventsCollectionKey]:t?e[this.eventsCollectionKey]=new w:null}}y.nextEventDelegatorId=0;class E{constructor(e){this.globalListener=e,this.infosByEventHandlerId={},this.countByEventName={},l.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=d(e),this.countByEventName.hasOwnProperty(e))this.countByEventName[e]++;else{this.countByEventName[e]=1;const t=v.hasOwnProperty(e);document.addEventListener(e,this.globalListener,t)}}update(e,t){if(this.infosByEventHandlerId.hasOwnProperty(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=d(t.eventName);0==--this.countByEventName[n]&&(delete this.countByEventName[n],document.removeEventListener(n,this.globalListener))}return t}handleEventNameAliasAdded(e,t){if(this.countByEventName.hasOwnProperty(e)){const n=this.countByEventName[e];delete this.countByEventName[e],document.removeEventListener(e,this.globalListener),this.addGlobalListener(t),this.countByEventName[t]+=n-1}}}class w{constructor(){this.handlers={},this.preventDefaultFlags=null,this.stopPropagationFlags=null}getHandler(e){return this.handlers.hasOwnProperty(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 I(e){const t={};return e.forEach((e=>{t[e]=!0})),t}const S=M("_blazorLogicalChildren"),D=M("_blazorLogicalParent"),C=M("_blazorLogicalEnd");function A(e,t){if(e.childNodes.length>0&&!t)throw new Error("New logical elements must start empty, or allowExistingContents must be true");return S in e||(e[S]=[]),e}function T(e,t){const n=document.createComment("!");return N(n,e,t),n}function N(e,t,n){const r=e;if(e instanceof Comment&&x(r)&&x(r).length>0)throw new Error("Not implemented: inserting non-empty logical container");if(R(r))throw new Error("Not implemented: moving existing logical children");const o=x(t);if(n0;)k(n,0)}const r=n;r.parentNode.removeChild(r)}function R(e){return e[D]||null}function F(e,t){return x(e)[t]}function _(e){var t=P(e);return"http://www.w3.org/2000/svg"===t.namespaceURI&&"foreignObject"!==t.tagName}function x(e){return e[S]}function O(e,t){const n=x(e);t.forEach((e=>{e.moveRangeStart=n[e.fromSiblingIndex],e.moveRangeEnd=H(e.moveRangeStart)})),t.forEach((t=>{const r=t.moveToBeforeMarker=document.createComment("marker"),o=n[t.toSiblingIndex+1];o?o.parentNode.insertBefore(r,o):L(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 P(e){if(e instanceof Element)return e;if(e instanceof Comment)return e.parentNode;throw new Error("Not a valid logical element")}function B(e){const t=x(R(e));return t[Array.prototype.indexOf.call(t,e)+1]||null}function L(e,t){if(t instanceof Element)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=B(t);n?n.parentNode.insertBefore(e,n):L(e,R(t))}}}function H(e){if(e instanceof Element)return e;const t=B(e);if(t)return t.previousSibling;{const t=R(e);return t instanceof Element?t.lastChild:H(t)}}function M(e){return"function"==typeof Symbol?Symbol():e}function U(e){return`_bl_${e}`}e.attachReviver(((e,t)=>t&&"object"==typeof t&&t.hasOwnProperty("__internalId")&&"string"==typeof t.__internalId?function(e){const t=`[${U(e)}]`;return document.querySelector(t)}(t.__internalId):t));const j="_blazorDeferredValue",J=document.createElement("template"),$=document.createElementNS("http://www.w3.org/2000/svg","g"),K={},z="__internal_",V="preventDefault_",X="stopPropagation_";class Y{constructor(e){this.childComponentLocations={},this.eventDelegator=new y(e),this.eventDelegator.notifyAfterClick((e=>{if(!ee)return;if(0!==e.button||function(e){return e.ctrlKey||e.shiftKey||e.altKey||e.metaKey}(e))return;if(e.defaultPrevented)return;const t=function(e){const t=!window._blazorDisableComposedPath&&e.composedPath&&e.composedPath();if(t){for(let e=0;eie(!1))))},enableNavigationInterception:function(){ee=!0},navigateTo:oe,getBaseURI:()=>document.baseURI,getLocationHref:()=>location.href};function oe(e,t,n=!1){const r=ce(e);if(!t&&ue(r))ae(r,!1,n);else if(t&&location.href===e){const t=e+"?";history.replaceState(null,"",t),location.replace(e)}else n?history.replaceState(null,"",r):location.href=e}function ae(e,t,n=!1){Q=!0,n?history.replaceState(null,"",e):history.pushState(null,"",e),ie(t)}async function ie(e){ne&&await ne(location.href,e)}let se;function ce(e){return se=se||document.createElement("a"),se.href=e,se.href}function le(e,t){return e?e.tagName===t?e:le(e.parentElement,t):null}function ue(e){const t=(n=document.baseURI).substr(0,n.lastIndexOf("/")+1);var n;return e.startsWith(t)}const de={init:function(e,t,n,r=50){const o=fe(t);(o||document.documentElement).style.overflowAnchor="none";const a=new IntersectionObserver((function(r){r.forEach((r=>{var o;if(!r.isIntersecting)return;const a=t.getBoundingClientRect(),i=n.getBoundingClientRect().top-a.bottom,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`});a.observe(t),a.observe(n);const i=c(t),s=c(n);function c(e){const t=new MutationObserver((()=>{a.unobserve(e),a.observe(e)}));return t.observe(e,{attributes:!0}),t}he[e._id]={intersectionObserver:a,mutationObserverBefore:i,mutationObserverAfter:s}},dispose:function(e){const t=he[e._id];t&&(t.intersectionObserver.disconnect(),t.mutationObserverBefore.disconnect(),t.mutationObserverAfter.disconnect(),e.dispose(),delete he[e._id])}},he={};function fe(e){return e?"visible"!==getComputedStyle(e).overflowY?e:fe(e.parentElement):null}const pe={navigateTo:oe,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]),l.forEach((n=>n(e,t.browserEventName)))}i.set(e,t)},_internal:{navigationManager:re,domWrapper:{focus:function(e,t){if(!(e instanceof HTMLElement))throw new Error("Unable to focus an invalid element.");e.focus({preventScroll:t})},focusBySelector:function(e){const t=document.querySelector(e);t&&(t.hasAttribute("tabindex")||(t.tabIndex=-1),t.focus())}},Virtualize:de}};window.Blazor=pe;let me=!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("")},be=Math.pow(2,32),ye=Math.pow(2,21)-1;function Ee(e,t){return e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24}function we(e,t){return e[t]+(e[t+1]<<8)+(e[t+2]<<16)+(e[t+3]<<24>>>0)}function Ie(e,t){const n=we(e,t+4);if(n>ye)throw new Error(`Cannot read uint64 with high order part ${n}, because the result would exceed Number.MAX_SAFE_INTEGER.`);return n*be+we(e,t)}class Se{constructor(e){this.batchData=e;const t=new Te(e);this.arrayRangeReader=new Ne(e),this.arrayBuilderSegmentReader=new ke(e),this.diffReader=new De(e),this.editReader=new Ce(e,t),this.frameReader=new Ae(e,t)}updatedComponents(){return Ee(this.batchData,this.batchData.length-20)}referenceFrames(){return Ee(this.batchData,this.batchData.length-16)}disposedComponentIds(){return Ee(this.batchData,this.batchData.length-12)}disposedEventHandlerIds(){return Ee(this.batchData,this.batchData.length-8)}updatedComponentsEntry(e,t){const n=e+4*t;return Ee(this.batchData,n)}referenceFramesEntry(e,t){return e+20*t}disposedComponentIdsEntry(e,t){const n=e+4*t;return Ee(this.batchData,n)}disposedEventHandlerIdsEntry(e,t){const n=e+8*t;return Ie(this.batchData,n)}}class De{constructor(e){this.batchDataUint8=e}componentId(e){return Ee(this.batchDataUint8,e)}edits(e){return e+4}editsEntry(e,t){return e+16*t}}class Ce{constructor(e,t){this.batchDataUint8=e,this.stringReader=t}editType(e){return Ee(this.batchDataUint8,e)}siblingIndex(e){return Ee(this.batchDataUint8,e+4)}newTreeIndex(e){return Ee(this.batchDataUint8,e+8)}moveToSiblingIndex(e){return Ee(this.batchDataUint8,e+8)}removedAttributeName(e){const t=Ee(this.batchDataUint8,e+12);return this.stringReader.readString(t)}}class Ae{constructor(e,t){this.batchDataUint8=e,this.stringReader=t}frameType(e){return Ee(this.batchDataUint8,e)}subtreeLength(e){return Ee(this.batchDataUint8,e+4)}elementReferenceCaptureId(e){const t=Ee(this.batchDataUint8,e+4);return this.stringReader.readString(t)}componentId(e){return Ee(this.batchDataUint8,e+8)}elementName(e){const t=Ee(this.batchDataUint8,e+8);return this.stringReader.readString(t)}textContent(e){const t=Ee(this.batchDataUint8,e+4);return this.stringReader.readString(t)}markupContent(e){const t=Ee(this.batchDataUint8,e+4);return this.stringReader.readString(t)}attributeName(e){const t=Ee(this.batchDataUint8,e+4);return this.stringReader.readString(t)}attributeValue(e){const t=Ee(this.batchDataUint8,e+8);return this.stringReader.readString(t)}attributeEventHandlerId(e){return Ie(this.batchDataUint8,e+12)}}class Te{constructor(e){this.batchDataUint8=e,this.stringTableStartIndex=Ee(e,e.length-4)}readString(e){if(-1===e)return null;{const n=Ee(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)<{!function(e,t,n){const r=document.querySelector(e);if(!r)throw new Error(`Could not find any element matching selector '${e}'.`);!function(e,t,n){let r=Z[0];r||(r=Z[0]=new Y(0)),r.attachRootComponentToLogicalElement(n,t)}(0,A(r,!0),t)}(t,e)},RenderBatch:(e,t)=>{try{const n=Me(t);(function(e,t){const n=Z[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{Fe=!0,console.error(`${e}\n${t}`),async function(){let e=document.querySelector("#blazor-error-ui");e&&(e.style.display="block"),me||(me=!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:e.jsCallDispatcher.beginInvokeJSFromDotNet,EndInvokeDotNet:e.jsCallDispatcher.endInvokeDotNetFromJS,SendByteArrayToJS:He,Navigate:re.navigateTo};window.external.receiveMessage((e=>{const n=function(e){if(Fe||!e||!e.startsWith(Re))return null;const t=e.substring(Re.length),[n,...r]=JSON.parse(t);return{messageType:n,args:r}}(e);if(n){if(!t.hasOwnProperty(n.messageType))throw new Error(`Unsupported IPC message type '${n.messageType}'`);t[n.messageType].apply(null,n.args)}}))}(),e.attachDispatcher({beginInvokeDotNetFromJS:xe,endInvokeJSFromDotNet:Oe,sendByteArray:Pe}),pe._internal.InputFile=Ue,re.enableNavigationInterception(),re.listenForNavigationEvents(Be),Le("AttachPage",re.getBaseURI(),re.getLocationHref())}o=function(e,t){Le("DispatchBrowserEvent",e,t)},pe.start=Ke,document&&document.currentScript&&"false"!==document.currentScript.getAttribute("autostart")&&Ke()})(); \ No newline at end of file +(()=>{"use strict";var e,t,n;!function(e){window.DotNet=e;const t=[],n=new Map;class r{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 o="__jsObjectId",a={},i={0:new r(window)};i[0]._cachedFunctions.set("import",(e=>("string"==typeof e&&e.startsWith("./")&&(e=document.baseURI+e.substr(2)),import(e))));let s,c=1,l=1,u=null;function d(e){t.push(e)}function f(e){if(e&&"object"==typeof e){i[l]=new r(e);const t={[o]:l};return l++,t}throw new Error(`Cannot create a JSObjectReference from the value '${e}'.`)}function h(e){if(!(e.buffer instanceof ArrayBuffer))throw new Error(`Cannot create a JSStreamReference from the value '${e}' as it is not have a 'buffer' property of type 'ArrayBuffer'.`);if(void 0===e.byteLength)throw new Error(`Cannot create a JSStreamReference from the value '${e}' as it doesn't have a byteLength.`);const t={__jsStreamReferenceLength:e.byteLength};try{const n=f(e);t.__jsObjectId=n.__jsObjectId}catch{throw new Error(`Cannot create a JSStreamReference from the value '${e}'.`)}return t}function m(e){return e?JSON.parse(e,((e,n)=>t.reduce(((t,n)=>n(e,t)),n))):null}function p(e,t,n,r){const o=g();if(o.invokeDotNetFromJS){const a=A(r),i=o.invokeDotNetFromJS(e,t,n,a);return i?m(i):null}throw new Error("The current dispatcher does not support synchronous calls from JS to .NET. Use invokeMethodAsync instead.")}function v(e,t,n,r){if(e&&n)throw new Error(`For instance method calls, assemblyName should be null. Received '${e}'.`);const o=c++,i=new Promise(((e,t)=>{a[o]={resolve:e,reject:t}}));try{const a=A(r);g().beginInvokeDotNetFromJS(o,e,t,n,a)}catch(e){b(o,!1,e)}return i}function g(){if(null!==u)return u;throw new Error("No .NET call dispatcher has been set.")}function b(e,t,n){if(!a.hasOwnProperty(e))throw new Error(`There is no pending async call with ID ${e}.`);const r=a[e];delete a[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){let n=i[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 i[e]}e.attachDispatcher=function(e){u=e},e.attachReviver=d,e.invokeMethod=function(e,t,...n){return p(e,t,null,n)},e.invokeMethodAsync=function(e,t,...n){return v(e,t,null,n)},e.createJSObjectReference=f,e.createJSStreamReference=h,e.disposeJSObjectReference=function(e){const t=e&&e.__jsObjectId;"number"==typeof t&&E(t)},function(e){e[e.Default=0]="Default",e[e.JSObjectReference=1]="JSObjectReference",e[e.JSStreamReference=2]="JSStreamReference"}(s=e.JSCallResultType||(e.JSCallResultType={})),e.jsCallDispatcher={findJSFunction:w,disposeJSObjectReferenceById:E,invokeJSFromDotNet:(e,t,n,r)=>{const o=D(w(e,r).apply(null,m(t)),n);return null==o?null:A(o)},beginInvokeJSFromDotNet:(e,t,n,r,o)=>{const a=new Promise((e=>{e(w(t,o).apply(null,m(n)))}));e&&a.then((t=>g().endInvokeJSFromDotNet(e,!0,A([e,!0,D(t,r)]))),(t=>g().endInvokeJSFromDotNet(e,!1,JSON.stringify([e,!1,y(t)]))))},endInvokeDotNetFromJS:(e,t,n)=>{const r=t?m(n):new Error(n);b(parseInt(e),t,r)},receiveByteArray:(e,t)=>{n.set(e,t)}};class I{constructor(e){this._id=e}invokeMethod(e,...t){return p(null,e,this._id,t)}invokeMethodAsync(e,...t){return v(null,e,this._id,t)}dispose(){v(null,"__Dispose",this._id,null).catch((e=>console.error(e)))}serializeAsArg(){return{__dotNetObject:this._id}}}const S="__byte[]";function D(e,t){switch(t){case s.Default:return e;case s.JSObjectReference:return f(e);case s.JSStreamReference:return h(e);default:throw new Error(`Invalid JS call result type '${t}'.`)}}d((function(e,t){if(t&&"object"==typeof t){if(t.hasOwnProperty("__dotNetObject"))return new I(t.__dotNetObject);if(t.hasOwnProperty(o)){const e=t.__jsObjectId,n=i[e];if(n)return n.getWrappedObject();throw new Error(`JS object instance with Id '${e}' does not exist. It may have been disposed.`)}if(t.hasOwnProperty(S)){const e=t["__byte[]"],r=n.get(e);if(void 0===r)throw new Error(`Byte array index '${e}' does not exist.`);return r}}return t}));let C=0;function A(e){return C=0,JSON.stringify(e,T)}function T(e,t){if(t instanceof I)return t.serializeAsArg();if(t instanceof Uint8Array){u.sendByteArray(C,t);const e={[S]:C};return C++,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"}(n||(n={}));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}}let o;function a(e,t){if(!o)throw new Error("eventDispatcher not initialized. Call 'setEventDispatcher' to configure it.");o(e,t)}const i=new Map,s=new Map,c={createEventArgs:()=>({})},l=[];function u(e){return i.get(e)}function d(e){const t=i.get(e);return(null==t?void 0:t.browserEventName)||e}function f(e,t){e.forEach((e=>i.set(e,t)))}function h(e){const t=[];for(let n=0;n{return{...m(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}}),f(["focus","blur","focusin","focusout"],c),f(["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};var t}}),f(["contextmenu","click","mouseover","mouseout","mousemove","mousedown","mouseup","dblclick"],{createEventArgs:e=>m(e)}),f(["error"],{createEventArgs:e=>{return{message:(t=e).message,filename:t.filename,lineno:t.lineno,colno:t.colno};var t}}),f(["loadstart","timeout","abort","load","loadend","progress"],{createEventArgs:e=>{return{lengthComputable:(t=e).lengthComputable,loaded:t.loaded,total:t.total};var t}}),f(["touchcancel","touchend","touchmove","touchenter","touchleave","touchstart"],{createEventArgs:e=>{return{detail:(t=e).detail,touches:h(t.touches),targetTouches:h(t.targetTouches),changedTouches:h(t.changedTouches),ctrlKey:t.ctrlKey,shiftKey:t.shiftKey,altKey:t.altKey,metaKey:t.metaKey,type:t.type};var t}}),f(["gotpointercapture","lostpointercapture","pointercancel","pointerdown","pointerenter","pointerleave","pointermove","pointerout","pointerover","pointerup"],{createEventArgs:e=>{return{...m(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}}),f(["wheel","mousewheel"],{createEventArgs:e=>{return{...m(t=e),deltaX:t.deltaX,deltaY:t.deltaY,deltaZ:t.deltaZ,deltaMode:t.deltaMode};var t}}),f(["toggle"],c);const p=["date","datetime-local","month","time","week"],v=I(["abort","blur","change","error","focus","load","loadend","loadstart","mouseenter","mouseleave","progress","reset","scroll","submit","unload","toggle","DOMNodeInsertedIntoDocument","DOMNodeRemovedFromDocument"]),g={submit:!0},b=I(["click","dblclick","mousedown","mousemove","mouseup"]);class y{constructor(e){this.browserRendererId=e,this.afterClickCallbacks=[];const t=++y.nextEventDelegatorId;this.eventsCollectionKey=`_blazorEvents_${t}`,this.eventInfoStore=new w(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){let n=t.target,o=null,i=!1;const s=v.hasOwnProperty(e);let c=!1;for(;n;){const f=this.getEventHandlerInfosForElement(n,!1);if(f){const s=f.getHandler(e);if(s&&(l=n,d=t.type,!((l instanceof HTMLButtonElement||l instanceof HTMLInputElement||l instanceof HTMLTextAreaElement||l instanceof HTMLSelectElement)&&b.hasOwnProperty(d)&&l.disabled))){if(!i){const n=u(e);o=(null==n?void 0:n.createEventArgs)?n.createEventArgs(t):{},i=!0}g.hasOwnProperty(t.type)&&t.preventDefault(),a({browserRendererId:this.browserRendererId,eventHandlerId:s.eventHandlerId,eventName:e,eventFieldInfo:r.fromEvent(s.renderingComponentId,t)},o)}f.stopPropagation(e)&&(c=!0),f.preventDefault(e)&&t.preventDefault()}n=s||c?null:n.parentElement}var l,d}getEventHandlerInfosForElement(e,t){return e.hasOwnProperty(this.eventsCollectionKey)?e[this.eventsCollectionKey]:t?e[this.eventsCollectionKey]=new E:null}}y.nextEventDelegatorId=0;class w{constructor(e){this.globalListener=e,this.infosByEventHandlerId={},this.countByEventName={},l.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=d(e),this.countByEventName.hasOwnProperty(e))this.countByEventName[e]++;else{this.countByEventName[e]=1;const t=v.hasOwnProperty(e);document.addEventListener(e,this.globalListener,t)}}update(e,t){if(this.infosByEventHandlerId.hasOwnProperty(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=d(t.eventName);0==--this.countByEventName[n]&&(delete this.countByEventName[n],document.removeEventListener(n,this.globalListener))}return t}handleEventNameAliasAdded(e,t){if(this.countByEventName.hasOwnProperty(e)){const n=this.countByEventName[e];delete this.countByEventName[e],document.removeEventListener(e,this.globalListener),this.addGlobalListener(t),this.countByEventName[t]+=n-1}}}class E{constructor(){this.handlers={},this.preventDefaultFlags=null,this.stopPropagationFlags=null}getHandler(e){return this.handlers.hasOwnProperty(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 I(e){const t={};return e.forEach((e=>{t[e]=!0})),t}const S=M("_blazorLogicalChildren"),D=M("_blazorLogicalParent"),C=M("_blazorLogicalEnd");function A(e,t){if(e.childNodes.length>0&&!t)throw new Error("New logical elements must start empty, or allowExistingContents must be true");return S in e||(e[S]=[]),e}function T(e,t){const n=document.createComment("!");return N(n,e,t),n}function N(e,t,n){const r=e;if(e instanceof Comment&&O(r)&&O(r).length>0)throw new Error("Not implemented: inserting non-empty logical container");if(k(r))throw new Error("Not implemented: moving existing logical children");const o=O(t);if(n0;)R(n,0)}const r=n;r.parentNode.removeChild(r)}function k(e){return e[D]||null}function F(e,t){return O(e)[t]}function _(e){var t=B(e);return"http://www.w3.org/2000/svg"===t.namespaceURI&&"foreignObject"!==t.tagName}function O(e){return e[S]}function x(e,t){const n=O(e);t.forEach((e=>{e.moveRangeStart=n[e.fromSiblingIndex],e.moveRangeEnd=H(e.moveRangeStart)})),t.forEach((t=>{const r=t.moveToBeforeMarker=document.createComment("marker"),o=n[t.toSiblingIndex+1];o?o.parentNode.insertBefore(r,o):L(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 B(e){if(e instanceof Element)return e;if(e instanceof Comment)return e.parentNode;throw new Error("Not a valid logical element")}function P(e){const t=O(k(e));return t[Array.prototype.indexOf.call(t,e)+1]||null}function L(e,t){if(t instanceof Element)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=P(t);n?n.parentNode.insertBefore(e,n):L(e,k(t))}}}function H(e){if(e instanceof Element)return e;const t=P(e);if(t)return t.previousSibling;{const t=k(e);return t instanceof Element?t.lastChild:H(t)}}function M(e){return"function"==typeof Symbol?Symbol():e}function U(e){return`_bl_${e}`}e.attachReviver(((e,t)=>t&&"object"==typeof t&&t.hasOwnProperty("__internalId")&&"string"==typeof t.__internalId?function(e){const t=`[${U(e)}]`;return document.querySelector(t)}(t.__internalId):t));const j="_blazorDeferredValue",J=document.createElement("template"),$=document.createElementNS("http://www.w3.org/2000/svg","g"),K={},z="__internal_",V="preventDefault_",X="stopPropagation_";class Y{constructor(e){this.childComponentLocations={},this.eventDelegator=new y(e),this.eventDelegator.notifyAfterClick((e=>{if(!ee)return;if(0!==e.button||function(e){return e.ctrlKey||e.shiftKey||e.altKey||e.metaKey}(e))return;if(e.defaultPrevented)return;const t=function(e){const t=!window._blazorDisableComposedPath&&e.composedPath&&e.composedPath();if(t){for(let e=0;eie(!1))))},enableNavigationInterception:function(){ee=!0},navigateTo:oe,getBaseURI:()=>document.baseURI,getLocationHref:()=>location.href};function oe(e,t,n=!1){const r=ce(e);if(!t&&ue(r))ae(r,!1,n);else if(t&&location.href===e){const t=e+"?";history.replaceState(null,"",t),location.replace(e)}else n?history.replaceState(null,"",r):location.href=e}function ae(e,t,n=!1){Q=!0,n?history.replaceState(null,"",e):history.pushState(null,"",e),ie(t)}async function ie(e){ne&&await ne(location.href,e)}let se;function ce(e){return se=se||document.createElement("a"),se.href=e,se.href}function le(e,t){return e?e.tagName===t?e:le(e.parentElement,t):null}function ue(e){const t=(n=document.baseURI).substr(0,n.lastIndexOf("/")+1);var n;return e.startsWith(t)}const de={init:function(e,t,n,r=50){const o=he(t);(o||document.documentElement).style.overflowAnchor="none";const a=new IntersectionObserver((function(r){r.forEach((r=>{var o;if(!r.isIntersecting)return;const a=t.getBoundingClientRect(),i=n.getBoundingClientRect().top-a.bottom,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`});a.observe(t),a.observe(n);const i=c(t),s=c(n);function c(e){const t=new MutationObserver((()=>{a.unobserve(e),a.observe(e)}));return t.observe(e,{attributes:!0}),t}fe[e._id]={intersectionObserver:a,mutationObserverBefore:i,mutationObserverAfter:s}},dispose:function(e){const t=fe[e._id];t&&(t.intersectionObserver.disconnect(),t.mutationObserverBefore.disconnect(),t.mutationObserverAfter.disconnect(),e.dispose(),delete fe[e._id])}},fe={};function he(e){return e?"visible"!==getComputedStyle(e).overflowY?e:he(e.parentElement):null}const me={navigateTo:oe,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]),l.forEach((n=>n(e,t.browserEventName)))}i.set(e,t)},_internal:{navigationManager:re,domWrapper:{focus:function(e,t){if(!(e instanceof HTMLElement))throw new Error("Unable to focus an invalid element.");e.focus({preventScroll:t})},focusBySelector:function(e){const t=document.querySelector(e);t&&(t.hasAttribute("tabindex")||(t.tabIndex=-1),t.focus())}},Virtualize:de}};window.Blazor=me;let pe=!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("")},be=Math.pow(2,32),ye=Math.pow(2,21)-1;function we(e,t){return e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24}function Ee(e,t){return e[t]+(e[t+1]<<8)+(e[t+2]<<16)+(e[t+3]<<24>>>0)}function Ie(e,t){const n=Ee(e,t+4);if(n>ye)throw new Error(`Cannot read uint64 with high order part ${n}, because the result would exceed Number.MAX_SAFE_INTEGER.`);return n*be+Ee(e,t)}class Se{constructor(e){this.batchData=e;const t=new Te(e);this.arrayRangeReader=new Ne(e),this.arrayBuilderSegmentReader=new Re(e),this.diffReader=new De(e),this.editReader=new Ce(e,t),this.frameReader=new Ae(e,t)}updatedComponents(){return we(this.batchData,this.batchData.length-20)}referenceFrames(){return we(this.batchData,this.batchData.length-16)}disposedComponentIds(){return we(this.batchData,this.batchData.length-12)}disposedEventHandlerIds(){return we(this.batchData,this.batchData.length-8)}updatedComponentsEntry(e,t){const n=e+4*t;return we(this.batchData,n)}referenceFramesEntry(e,t){return e+20*t}disposedComponentIdsEntry(e,t){const n=e+4*t;return we(this.batchData,n)}disposedEventHandlerIdsEntry(e,t){const n=e+8*t;return Ie(this.batchData,n)}}class De{constructor(e){this.batchDataUint8=e}componentId(e){return we(this.batchDataUint8,e)}edits(e){return e+4}editsEntry(e,t){return e+16*t}}class Ce{constructor(e,t){this.batchDataUint8=e,this.stringReader=t}editType(e){return we(this.batchDataUint8,e)}siblingIndex(e){return we(this.batchDataUint8,e+4)}newTreeIndex(e){return we(this.batchDataUint8,e+8)}moveToSiblingIndex(e){return we(this.batchDataUint8,e+8)}removedAttributeName(e){const t=we(this.batchDataUint8,e+12);return this.stringReader.readString(t)}}class Ae{constructor(e,t){this.batchDataUint8=e,this.stringReader=t}frameType(e){return we(this.batchDataUint8,e)}subtreeLength(e){return we(this.batchDataUint8,e+4)}elementReferenceCaptureId(e){const t=we(this.batchDataUint8,e+4);return this.stringReader.readString(t)}componentId(e){return we(this.batchDataUint8,e+8)}elementName(e){const t=we(this.batchDataUint8,e+8);return this.stringReader.readString(t)}textContent(e){const t=we(this.batchDataUint8,e+4);return this.stringReader.readString(t)}markupContent(e){const t=we(this.batchDataUint8,e+4);return this.stringReader.readString(t)}attributeName(e){const t=we(this.batchDataUint8,e+4);return this.stringReader.readString(t)}attributeValue(e){const t=we(this.batchDataUint8,e+8);return this.stringReader.readString(t)}attributeEventHandlerId(e){return Ie(this.batchDataUint8,e+12)}}class Te{constructor(e){this.batchDataUint8=e,this.stringTableStartIndex=we(e,e.length-4)}readString(e){if(-1===e)return null;{const n=we(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)<{!function(e,t,n){const r=document.querySelector(e);if(!r)throw new Error(`Could not find any element matching selector '${e}'.`);!function(e,t,n){let r=Z[0];r||(r=Z[0]=new Y(0)),r.attachRootComponentToLogicalElement(n,t)}(0,A(r,!0),t)}(t,e)},RenderBatch:(e,t)=>{try{const n=Me(t);(function(e,t){const n=Z[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{Fe=!0,console.error(`${e}\n${t}`),async function(){let e=document.querySelector("#blazor-error-ui");e&&(e.style.display="block"),pe||(pe=!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:e.jsCallDispatcher.beginInvokeJSFromDotNet,EndInvokeDotNet:e.jsCallDispatcher.endInvokeDotNetFromJS,SendByteArrayToJS:He,Navigate:re.navigateTo};window.external.receiveMessage((e=>{const n=function(e){if(Fe||!e||!e.startsWith(ke))return null;const t=e.substring(ke.length),[n,...r]=JSON.parse(t);return{messageType:n,args:r}}(e);if(n){if(!t.hasOwnProperty(n.messageType))throw new Error(`Unsupported IPC message type '${n.messageType}'`);t[n.messageType].apply(null,n.args)}}))}(),e.attachDispatcher({beginInvokeDotNetFromJS:Oe,endInvokeJSFromDotNet:xe,sendByteArray:Be}),me._internal.InputFile=Ue,re.enableNavigationInterception(),re.listenForNavigationEvents(Pe),Le("AttachPage",re.getBaseURI(),re.getLocationHref())}o=function(e,t){Le("DispatchBrowserEvent",e,t)},me.start=Ke,document&&document.currentScript&&"false"!==document.currentScript.getAttribute("autostart")&&Ke()})(); \ No newline at end of file From 6e91d845d34212834bdbed036b9ab43dab72055a Mon Sep 17 00:00:00 2001 From: Tanay Parikh Date: Fri, 25 Jun 2021 17:00:50 -0700 Subject: [PATCH 36/37] Cleanup & Fix Test --- .../Server/src/Circuits/RemoteJSDataStream.cs | 13 ++-- src/Components/Server/src/ComponentHub.cs | 5 ++ .../test/Circuits/RemoteJSDataStreamTest.cs | 62 +++++++++++++++---- .../Circuits/CircuitStreamingInterop.ts | 2 - 4 files changed, 63 insertions(+), 19 deletions(-) diff --git a/src/Components/Server/src/Circuits/RemoteJSDataStream.cs b/src/Components/Server/src/Circuits/RemoteJSDataStream.cs index a60b66b48ea8..807f18402401 100644 --- a/src/Components/Server/src/Circuits/RemoteJSDataStream.cs +++ b/src/Components/Server/src/Circuits/RemoteJSDataStream.cs @@ -45,9 +45,10 @@ public static async ValueTask CreateRemoteJSDataStreamAsync( TimeSpan jsInteropDefaultCallTimeout, CancellationToken cancellationToken = default) { - // Enforce minimum 1 kb SignalR message size as we budget 512 bytes - // overhead for the transfer, thus leaving at least 512 bytes for data - // transfer per chunk. + // Enforce minimum 1 kb, maximum 50 kb, SignalR message size. + // We budget 512 bytes overhead for the transfer, thus leaving at least 512 bytes for data + // transfer per chunk with a 1 kb message size. + // Additionally, to maintain interactivity, we put an upper limit of 50 kb on the message size. var chunkSize = maximumIncomingBytes > 1024 ? Math.Min(maximumIncomingBytes, 50*1024) - 512 : throw new ArgumentException($"SignalR MaximumIncomingBytes must be at least 1 kb."); @@ -72,7 +73,7 @@ private RemoteJSDataStream( _jsInteropDefaultCallTimeout = jsInteropDefaultCallTimeout; _streamCancellationToken = cancellationToken; - _lastDataReceivedTime = DateTime.UtcNow; + _lastDataReceivedTime = DateTimeOffset.UtcNow; _ = ThrowOnTimeout(); _runtime.RemoteJSDataStreamInstances.Add(_streamId, this); @@ -85,7 +86,7 @@ private async Task ReceiveData(long chunkId, byte[] chunk, string error) { try { - _lastDataReceivedTime = DateTime.UtcNow; + _lastDataReceivedTime = DateTimeOffset.UtcNow; _ = ThrowOnTimeout(); if (!string.IsNullOrEmpty(error)) @@ -195,7 +196,7 @@ private async Task ThrowOnTimeout() { await Task.Delay(_jsInteropDefaultCallTimeout); - if (!_disposed && (DateTime.UtcNow >= _lastDataReceivedTime.Add(_jsInteropDefaultCallTimeout))) + if (!_disposed && (DateTimeOffset.UtcNow >= _lastDataReceivedTime.Add(_jsInteropDefaultCallTimeout))) { // Dispose of the stream if a chunk isn't received within the jsInteropDefaultCallTimeout. var timeoutException = new TimeoutException("Did not receive any data in the alloted time."); diff --git a/src/Components/Server/src/ComponentHub.cs b/src/Components/Server/src/ComponentHub.cs index 01b65d9073db..2bca9c1dd9df 100644 --- a/src/Components/Server/src/ComponentHub.cs +++ b/src/Components/Server/src/ComponentHub.cs @@ -232,6 +232,11 @@ public async ValueTask ReceiveJSDataChunk(long streamId, long chunkId, byt return false; } + // Note: this await will block the circuit. This is intentional. + // The call into the circuitHost.ReceiveJSDataChunk will block regardless as we call into Renderer.Dispatcher.InvokeAsync + // which ensures we're running on the main circuit thread so that the server/client remain in the same + // synchronization context. Additionally, we're utilizing the return value as a heartbeat for the transfer + // process, and without it would likely need to setup a separate endpoint to handle that functionality. return await circuitHost.ReceiveJSDataChunk(streamId, chunkId, chunk, error); } diff --git a/src/Components/Server/test/Circuits/RemoteJSDataStreamTest.cs b/src/Components/Server/test/Circuits/RemoteJSDataStreamTest.cs index 67ee306c55af..113bf7441ada 100644 --- a/src/Components/Server/test/Circuits/RemoteJSDataStreamTest.cs +++ b/src/Components/Server/test/Circuits/RemoteJSDataStreamTest.cs @@ -74,18 +74,60 @@ public async void ReceiveData_SuccessReadsBackStream() } [Fact] - public async void ReceiveData_ReceiveDataTimeout_StreamDisposed() + public async void ReceiveData_NoDataProvidedBeforeTimeout_StreamDisposed() { // Arrange var jsRuntime = new TestRemoteJSRuntime(Options.Create(new CircuitOptions()), Options.Create(new HubOptions()), Mock.Of>()); + var timeoutExceptionRaised = false; + jsRuntime.UnhandledException += (_, ex) => + { + Assert.Equal("Did not receive any data in the alloted time.", ex.Message); + timeoutExceptionRaised = ex is TimeoutException; + }; + var jsStreamReference = Mock.Of(); var remoteJSDataStream = await RemoteJSDataStream.CreateRemoteJSDataStreamAsync( - jsRuntime ?? _jsRuntime, + jsRuntime, jsStreamReference, totalLength: 9, maxBufferSize: 50, maximumIncomingBytes: 10_000, - jsInteropDefaultCallTimeout: TimeSpan.FromSeconds(40)); // Note we're using a 40 second timeout for this test + jsInteropDefaultCallTimeout: TimeSpan.FromSeconds(10)); // Note we're using a 10 second timeout for this test + var streamId = GetStreamId(remoteJSDataStream, jsRuntime); + var chunk = new byte[] { 3, 5, 7 }; + + // Act & Assert 1 + // Wait past the initial timeout + 15 sec buffer room and then + // confirm unhandled exception raised to crush circuit + await Task.Delay(TimeSpan.FromSeconds(25)); + Assert.True(timeoutExceptionRaised); + + // Act & Assert 2 + // Ensures stream is disposed after the timeout and any additional chunks aren't accepted + var success = await RemoteJSDataStream.ReceiveData(jsRuntime, streamId, chunkId: 0, chunk, error: null); + Assert.False(success); + } + + [Fact] + public async void ReceiveData_ReceivesDataThenTimesout_StreamDisposed() + { + // Arrange + var jsRuntime = new TestRemoteJSRuntime(Options.Create(new CircuitOptions()), Options.Create(new HubOptions()), Mock.Of>()); + var timeoutExceptionRaised = false; + jsRuntime.UnhandledException += (_, ex) => + { + Assert.Equal("Did not receive any data in the alloted time.", ex.Message); + timeoutExceptionRaised = ex is TimeoutException; + }; + + var jsStreamReference = Mock.Of(); + var remoteJSDataStream = await RemoteJSDataStream.CreateRemoteJSDataStreamAsync( + jsRuntime, + jsStreamReference, + totalLength: 9, + maxBufferSize: 50, + maximumIncomingBytes: 10_000, + jsInteropDefaultCallTimeout: TimeSpan.FromSeconds(30)); // Note we're using a 30 second timeout for this test var streamId = GetStreamId(remoteJSDataStream, jsRuntime); var chunk = new byte[] { 3, 5, 7 }; @@ -93,19 +135,17 @@ public async void ReceiveData_ReceiveDataTimeout_StreamDisposed() var success = await RemoteJSDataStream.ReceiveData(jsRuntime, streamId, chunkId: 0, chunk, error: null); Assert.True(success); - await Task.Delay(TimeSpan.FromSeconds(20)); + await Task.Delay(TimeSpan.FromSeconds(15)); // Act & Assert 2 success = await RemoteJSDataStream.ReceiveData(jsRuntime, streamId, chunkId: 1, chunk, error: null); Assert.True(success); - // Wait 80 seconds (20 sec between first two calls + 40 sec timeout + 20 sec buffer room) - await Task.Delay(TimeSpan.FromSeconds(80)); - // Act & Assert 3 - using var mem = new MemoryStream(); - var ex = await Assert.ThrowsAsync(async() => await remoteJSDataStream.CopyToAsync(mem)); - Assert.Equal("Did not receive any data in the alloted time.", ex.Message); + // Wait past the 30 sec timeout + 15 sec buffer room + // confirm unhandled exception raised to crush circuit + await Task.Delay(TimeSpan.FromSeconds(45)); + Assert.True(timeoutExceptionRaised); // Act & Assert 4 // Ensures stream is disposed after the timeout and any additional chunks aren't accepted @@ -210,7 +250,7 @@ public TestRemoteJSRuntime(IOptions circuitOptions, IOptions InvokeAsync(string identifier, object[] args) + public new ValueTask InvokeAsync(string identifier, object[] args) { Assert.Equal("Blazor._internal.sendJSDataStream", identifier); return ValueTask.FromResult(default); diff --git a/src/Components/Web.JS/src/Platform/Circuits/CircuitStreamingInterop.ts b/src/Components/Web.JS/src/Platform/Circuits/CircuitStreamingInterop.ts index 744aa7d81d8f..99d4a6373ee9 100644 --- a/src/Components/Web.JS/src/Platform/Circuits/CircuitStreamingInterop.ts +++ b/src/Components/Web.JS/src/Platform/Circuits/CircuitStreamingInterop.ts @@ -12,8 +12,6 @@ export function sendJSDataStream(connection: HubConnection, data: ArrayBufferVie let position = 0; let chunkId = 0; - // Note: The server-side `StreamBufferCapacity` option (defaults to 10) can be configured to limit how many - // stream items from the client (per stream) will be stored before reading any more stream items (thus applying backpressure). while (position < data.byteLength) { const nextChunkSize = Math.min(chunkSize, data.byteLength - position); const nextChunkData = new Uint8Array(data.buffer, data.byteOffset + position, nextChunkSize); From 20e84896fa2d8841c232c4563e7d4e87fa26d3fb Mon Sep 17 00:00:00 2001 From: Tanay Parikh Date: Sun, 27 Jun 2021 11:22:07 -0700 Subject: [PATCH 37/37] Remote timeout related tests --- .../test/Circuits/RemoteJSDataStreamTest.cs | 80 ------------------- 1 file changed, 80 deletions(-) diff --git a/src/Components/Server/test/Circuits/RemoteJSDataStreamTest.cs b/src/Components/Server/test/Circuits/RemoteJSDataStreamTest.cs index 113bf7441ada..14dcf3eec46c 100644 --- a/src/Components/Server/test/Circuits/RemoteJSDataStreamTest.cs +++ b/src/Components/Server/test/Circuits/RemoteJSDataStreamTest.cs @@ -73,86 +73,6 @@ public async void ReceiveData_SuccessReadsBackStream() Assert.True(sendDataCompleted); } - [Fact] - public async void ReceiveData_NoDataProvidedBeforeTimeout_StreamDisposed() - { - // Arrange - var jsRuntime = new TestRemoteJSRuntime(Options.Create(new CircuitOptions()), Options.Create(new HubOptions()), Mock.Of>()); - var timeoutExceptionRaised = false; - jsRuntime.UnhandledException += (_, ex) => - { - Assert.Equal("Did not receive any data in the alloted time.", ex.Message); - timeoutExceptionRaised = ex is TimeoutException; - }; - - var jsStreamReference = Mock.Of(); - var remoteJSDataStream = await RemoteJSDataStream.CreateRemoteJSDataStreamAsync( - jsRuntime, - jsStreamReference, - totalLength: 9, - maxBufferSize: 50, - maximumIncomingBytes: 10_000, - jsInteropDefaultCallTimeout: TimeSpan.FromSeconds(10)); // Note we're using a 10 second timeout for this test - var streamId = GetStreamId(remoteJSDataStream, jsRuntime); - var chunk = new byte[] { 3, 5, 7 }; - - // Act & Assert 1 - // Wait past the initial timeout + 15 sec buffer room and then - // confirm unhandled exception raised to crush circuit - await Task.Delay(TimeSpan.FromSeconds(25)); - Assert.True(timeoutExceptionRaised); - - // Act & Assert 2 - // Ensures stream is disposed after the timeout and any additional chunks aren't accepted - var success = await RemoteJSDataStream.ReceiveData(jsRuntime, streamId, chunkId: 0, chunk, error: null); - Assert.False(success); - } - - [Fact] - public async void ReceiveData_ReceivesDataThenTimesout_StreamDisposed() - { - // Arrange - var jsRuntime = new TestRemoteJSRuntime(Options.Create(new CircuitOptions()), Options.Create(new HubOptions()), Mock.Of>()); - var timeoutExceptionRaised = false; - jsRuntime.UnhandledException += (_, ex) => - { - Assert.Equal("Did not receive any data in the alloted time.", ex.Message); - timeoutExceptionRaised = ex is TimeoutException; - }; - - var jsStreamReference = Mock.Of(); - var remoteJSDataStream = await RemoteJSDataStream.CreateRemoteJSDataStreamAsync( - jsRuntime, - jsStreamReference, - totalLength: 9, - maxBufferSize: 50, - maximumIncomingBytes: 10_000, - jsInteropDefaultCallTimeout: TimeSpan.FromSeconds(30)); // Note we're using a 30 second timeout for this test - var streamId = GetStreamId(remoteJSDataStream, jsRuntime); - var chunk = new byte[] { 3, 5, 7 }; - - // Act & Assert 1 - var success = await RemoteJSDataStream.ReceiveData(jsRuntime, streamId, chunkId: 0, chunk, error: null); - Assert.True(success); - - await Task.Delay(TimeSpan.FromSeconds(15)); - - // Act & Assert 2 - success = await RemoteJSDataStream.ReceiveData(jsRuntime, streamId, chunkId: 1, chunk, error: null); - Assert.True(success); - - // Act & Assert 3 - // Wait past the 30 sec timeout + 15 sec buffer room - // confirm unhandled exception raised to crush circuit - await Task.Delay(TimeSpan.FromSeconds(45)); - Assert.True(timeoutExceptionRaised); - - // Act & Assert 4 - // Ensures stream is disposed after the timeout and any additional chunks aren't accepted - success = await RemoteJSDataStream.ReceiveData(jsRuntime, streamId, chunkId: 2, chunk, error: null); - Assert.False(success); - } - [Fact] public async void ReceiveData_WithError() {