{"version":3,"sources":["../../../src/ILogger.ts","../../../src/Loggers.ts","../../../src/TextMessageFormat.ts","../../../src/Errors.ts","../../../src/HttpClient.ts","../../../src/FetchHttpClient.ts","../../../src/IHubProtocol.ts","../../../src/XhrHttpClient.ts","../../../src/DefaultHttpClient.ts","../../../src/Subject.ts","../../../src/HubConnection.ts","../../../src/ITransport.ts","../../../src/DefaultReconnectPolicy.ts","../../../src/AbortController.ts","../../../src/LongPollingTransport.ts","../../../src/ServerSentEventsTransport.ts","../../../src/WebSocketTransport.ts","../../../src/HttpConnection.ts","../../../src/JsonHubProtocol.ts","../../../src/HubConnectionBuilder.ts","../../../src/Utils.ts","../../../src/HandshakeProtocol.ts","../../src/utils/errors.ts","../../src/utils/common.ts","../../src/utils/plugins.ts","../../src/core/scope.ts","../../src/core/finalize.ts","../../src/core/proxy.ts","../../src/core/immerClass.ts","../../src/core/current.ts","../../src/plugins/es5.ts","../../src/immer.ts","../../src/utils/env.ts","../node_modules/@reduxjs/toolkit/dist/redux-toolkit.esm.js"],"names":["LogLevel","log","_logLevel","_message","instance","NullLogger","write","output","TextMessageFormat","RecordSeparator","parse","input","length","Error","messages","split","pop","RecordSeparatorCode","String","fromCharCode","errorMessage","statusCode","trueProto","prototype","__proto__","statusText","content","get","url","options","this","send","method","post","delete","getCookieString","logger","fetch","requireFunc","jar","fetchType","abortControllerType","bind","self","AbortController","request","abortSignal","aborted","AbortError","abortController","onabort","abort","error","timeoutId","timeout","msTimeout","setTimeout","Warning","TimeoutError","body","cache","credentials","withCredentials","headers","mode","redirect","signal","response","clearTimeout","ok","HttpError","status","responseType","arrayBuffer","text","deserializeContent","payload","HttpResponse","cookies","isNode","getCookies","e","c","join","HttpClient","MessageType","Promise","reject","resolve","xhr","XMLHttpRequest","open","undefined","setRequestHeader","Object","keys","forEach","header","onload","responseText","onerror","ontimeout","httpClient","HubConnectionState","observers","next","item","err","observer","complete","subscribe","push","HttpTransportType","TransferFormat","connection","protocol","reconnectPolicy","nextKeepAlive","isRequired","serverTimeoutInMilliseconds","keepAliveIntervalInMilliseconds","handshakeProtocol","HandshakeProtocol","onreceive","data","processIncomingData","onclose","connectionClosed","callbacks","methods","closedCallbacks","reconnectingCallbacks","reconnectedCallbacks","invocationId","receivedHandshakeResponse","connectionState","Disconnected","connectionStarted","cachedPingMessage","writeMessage","type","Ping","create","HubConnection","connectionId","baseUrl","Reconnecting","start","startPromise","startWithStateTransitions","Connecting","Debug","startInternal","Connected","stopDuringStartError","handshakePromise","handshakeResolver","handshakeRejecter","transferFormat","handshakeRequest","name","version","sendMessage","writeHandshakeRequest","Information","cleanupTimeout","resetTimeoutPeriod","resetKeepAliveInterval","cleanupPingTimer","stop","stopPromise","stopInternal","Disconnecting","reconnectDelayHandle","completeClose","stream","methodName","promiseQueue","streams","streamIds","invocationDescriptor","createStreamInvocation","args","subject","cancelCallback","cancelInvocation","createCancelInvocation","then","sendWithProtocol","invocationEvent","Completion","catch","launchStreams","message","sendPromise","createInvocation","invoke","p","result","on","newMethod","toLowerCase","indexOf","off","handlers","removeIdx","splice","callback","onreconnecting","onreconnected","processHandshakeResponse","parseMessages","Invocation","invokeClientMethod","StreamItem","Close","allowReconnect","responseMessage","remainingData","features","inherentKeepAlive","Date","getTime","timeoutHandle","pingServerHandle","nextPing","serverTimeout","invocationMessage","target","m","apply","cancelCallbacksWithError","reconnect","reconnectStartTime","now","previousReconnectAttempts","retryError","nextRetryDelay","getNextRetryDelay","toString","previousRetryCount","elapsedMilliseconds","retryReason","nextRetryDelayInMilliseconds","key","nonblocking","arguments","streamId","createCompletionMessage","createStreamItemMessage","replaceStreamingParams","i","argument","isObservable","arg","StreamInvocation","id","CancelInvocation","DEFAULT_RETRY_DELAYS_IN_MILLISECONDS","retryDelays","retryContext","isAborted","accessTokenFactory","logMessageContent","pollAbort","running","connect","isIn","Trace","Binary","value","pollOptions","getAccessToken","token","updateHeaderToken","pollUrl","closeError","receiving","poll","pollAborted","raiseOnClose","deleteOptions","logMessage","eventSourceConstructor","encodeURIComponent","opened","Text","eventSource","isBrowser","isWebWorker","Cookie","onmessage","close","onopen","webSocketConstructor","webSocket","replace","binaryType","_event","event","ErrorEvent","readyState","OPEN","isCloseEvent","wasClean","code","reason","stopPromiseResolver","negotiateVersion","resolveUrl","webSocketModule","eventSourceModule","WebSocket","EventSource","startInternalPromise","sendQueue","TransportSendQueue","transport","stopError","stopConnection","skipNegotiation","WebSockets","constructTransport","startTransport","negotiateResponse","redirects","getNegotiationResponse","ProtocolVersion","accessToken","createTransport","negotiateUrl","resolveNegotiateUrl","JSON","connectionToken","createConnectUrl","requestedTransport","requestedTransferFormat","connectUrl","isITransport","transportExceptions","transports","availableTransports","negotiate","endpoint","transportOrError","resolveTransportOrError","ServerSentEvents","LongPolling","actualTransport","transportMatches","transferFormats","map","s","ex","lastIndexOf","window","document","aTag","createElement","href","index","substring","buffer","executing","sendBufferedData","PromiseSource","transportResult","sendLoopPromise","sendLoop","bufferData","promise","concatBuffers","arrayBuffers","totalLength","b","reduce","a","Uint8Array","offset","set","byteLength","resolver","rejecter","hubMessages","parsedMessage","isInvocationMessage","isStreamItemMessage","isCompletionMessage","stringify","assertNotEmptyString","LogLevelNameMapping","trace","debug","info","information","warn","warning","critical","Critical","none","None","configureLogging","logging","logLevel","mapping","parseLogLevel","withUrl","transportTypeOrOptions","isNotEmpty","httpConnectionOptions","withHubProtocol","withAutomaticReconnect","retryDelaysOrReconnectPolicy","Array","isArray","DefaultReconnectPolicy","build","val","match","values","includeContent","detail","isArrayBuffer","view","str","num","substr","formatArrayBuffer","ArrayBuffer","constructor","transportName","defaultHeaders","getUserAgentHeader","getDataDetail","ConsoleLogger","dispose","_","minimumLogLevel","outputConsole","console","toISOString","userAgentHeaderName","Platform","constructUserAgent","getOsName","getRuntime","getRuntimeVersion","os","runtime","runtimeVersion","userAgent","majorAndMinor","process","platform","versions","node","parseHandshakeResponse","messageData","Buffer","binaryData","separatorIndex","responseLength","slice","textData","die","msg","isDraft","DRAFT_STATE","isDraftable","proto","getPrototypeOf","Ctor","hasOwnProperty","call","Function","objectCtorString","DRAFTABLE","isMap","isSet","each","obj","iter","enumerableOnly","getArchtype","ownKeys","entry","thing","state","type_","has","prop","propOrOldValue","t","add","is","x","y","hasMap","Map","hasSet","Set","latest","copy_","base_","shallowCopy","base","descriptors","getOwnPropertyDescriptors","desc","writable","configurable","enumerable","freeze","deep","isFrozen","clear","dontMutateFrozenCollections","getPlugin","pluginKey","plugin","plugins","loadPlugin","implementation","getCurrentScope","currentScope","usePatchesInScope","scope","patchListener","patches_","inversePatches_","patchListener_","revokeScope","leaveScope","drafts_","revokeDraft","parent_","enterScope","immer","immer_","canAutoFreeze_","unfinalizedDrafts_","draft","revoke_","revoked_","processResult","baseDraft","isReplaced","useProxies_","willFinalizeES5_","modified_","finalize","maybeFreeze","generateReplacementPatches_","NOTHING","rootScope","path","childValue","finalizeProperty","scope_","finalized_","draft_","generatePatches_","parentState","targetObject","rootPath","res","assigned_","concat","autoFreeze_","peek","getDescriptorFromProto","source","getOwnPropertyDescriptor","markChanged","prepareCopy","createProxy","parent","proxyMap_","proxySet_","isManual_","traps","objectTraps","arrayTraps","Proxy","revocable","revoke","proxy","createES5Proxy_","current","currentImpl","copy","archType","hasChanges_","copyHelper","from","enableES5","proxyProperty","markChangesSweep","drafts","hasArrayChanges","hasObjectChanges","baseValue","baseIsDraft","descriptor","defineProperty","markChangesRecursively","object","min","Math","hasSymbol","Symbol","hasProxies","Reflect","for","iterator","getOwnPropertySymbols","getOwnPropertyNames","currentState","deleteProperty","owner","setPrototypeOf","fn","Immer","config","recipe","defaultBase","_this","produce","_this2","hasError","arg1","arg2","produceWithPatches","ip","patches","inversePatches","useProxies","setUseProxies","autoFreeze","setAutoFreeze","createDraft","finishDraft","applyPatches","patch","op","applyPatchesImpl","applyPatches_","__extends","extendStatics","d","TypeError","__","__generator","thisArg","f","g","label","sent","trys","ops","verb","n","v","done","step","__spreadArray","to","il","j","__defProp","__defProps","defineProperties","__getOwnPropDescs","__getOwnPropSymbols","__hasOwnProp","__propIsEnum","propertyIsEnumerable","__defNormalProp","__spreadValues","_i","_b","__spreadProps","__REDUX_DEVTOOLS_EXTENSION_COMPOSE__","__REDUX_DEVTOOLS_EXTENSION__","_super","MiddlewareArray","species","arr","prepend","createAction","prepareAction","actionCreator","prepared","meta","action","executeReducerBuilderCallback","builderCallback","defaultCaseReducer","actionsMap","actionMatchers","builder","addCase","typeOrActionCreator","reducer","addMatcher","matcher","addDefaultCase","createSlice","initialState","reducers","extraReducers","_c","_d","_e","reducerNames","sliceCaseReducersByName","sliceCaseReducersByType","actionCreators","reducerName","caseReducer","prepareCallback","maybeReducerWithPrepare","prepare","mapOrBuilderCallback","finalActionMatchers","finalDefaultCaseReducer","frozenInitialState","createNextState","caseReducers","filter","cr","previousState","isDraft2","createReducer","actions","nanoid","size","random","commonProperties","RejectWithValue","FulfillWithMeta","miniSerializeError","simpleError","commonProperties_1","property","createAsyncThunk","typePrefix","payloadCreator","fulfilled","requestId","requestStatus","pending","rejected","serializeError","rejectedWithValue","condition","AC","class_1","addEventListener","dispatchEvent","removeEventListener","assign","dispatch","getState","extra","_a","abortReason","idGenerator","abortedPromise","started","__this","__arguments","generator","_a2","finalAction","err_1","getPendingMeta","race","rejectWithValue","fulfillWithValue","dispatchConditionRejection","throw","unwrap","unwrapResult"],"mappings":"kIAQA,IAAYA,EARZ,kCAQA,SAAYA,GAER,qBAEA,qBAEA,iCAEA,yBAEA,qBAEA,2BAEA,mBAdJ,CAAYA,MAAQ,M,iCCRpB,kCAMA,iBAII,cAMJ,OAFW,YAAAC,IAAP,SAAWC,EAAqBC,KANlB,EAAAC,SAAoB,IAAIC,EAQ1C,EAVA,I,iCCNA,kCAKA,+BAiBA,OAbkB,EAAAC,MAAd,SAAoBC,GAChB,MAAO,GAAGA,EAASC,EAAkBC,iBAG3B,EAAAC,MAAd,SAAoBC,GAChB,GAAIA,EAAMA,EAAMC,OAAS,KAAOJ,EAAkBC,gBAC9C,MAAM,IAAII,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AEwK,KAAO/jB,EAAQuZ,EAAEjO,OAASxL,QAAQE,QAAQuZ,EAAEjO,OAAOnF,KAAKijB,EAAWI,IACtGxF,GAAM4G,EAAYA,EAAU9hB,MAAM4hB,EAAQC,IAAc1pB,WAnBlD,IAAUypB,EAAQC,EAAaC,EAmgCnB,GAwDd,OAAOtqB,OAAO2pB,OAAOvY,EAAS,CAC1B/T,MA/DJ,SAAe+P,GACP+c,IACAH,EAAc5c,EACdjQ,EAAgBE,UA6DpB0rB,UAAWA,EACX/e,IAAKA,EACLghB,OAAQ,WACJ,OAAO5Z,EAAQvL,KAAKolB,UAKA,CAChChC,QAASA,EACTC,SAAUA,EACVJ,UAAWA,EACXF,WAAYA,IAGpB,SAASqC,GAAazF,GAClB,GAAIA,EAAOD,MAAQC,EAAOD,KAAK6D,kBAC3B,MAAM5D,EAAO1mB,QAEjB,GAAI0mB,EAAOloB,MACP,MAAMkoB,EAAOloB,MAEjB,OAAOkoB,EAAO1mB,QA0IlBugB","file":"static/js/46.7e1503d2.chunk.js","sourcesContent":["// Copyright (c) .NET Foundation. All rights reserved.\r\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\r\n\r\n// These values are designed to match the ASP.NET Log Levels since that's the pattern we're emulating here.\r\n/** Indicates the severity of a log message.\r\n *\r\n * Log Levels are ordered in increasing severity. So `Debug` is more severe than `Trace`, etc.\r\n */\r\nexport enum LogLevel {\r\n /** Log level for very low severity diagnostic messages. */\r\n Trace = 0,\r\n /** Log level for low severity diagnostic messages. */\r\n Debug = 1,\r\n /** Log level for informational diagnostic messages. */\r\n Information = 2,\r\n /** Log level for diagnostic messages that indicate a non-fatal problem. */\r\n Warning = 3,\r\n /** Log level for diagnostic messages that indicate a failure in the current operation. */\r\n Error = 4,\r\n /** Log level for diagnostic messages that indicate a failure that will terminate the entire application. */\r\n Critical = 5,\r\n /** The highest possible log level. Used when configuring logging to indicate that no log messages should be emitted. */\r\n None = 6,\r\n}\r\n\r\n/** An abstraction that provides a sink for diagnostic messages. */\r\nexport interface ILogger {\r\n /** Called by the framework to emit a diagnostic message.\r\n *\r\n * @param {LogLevel} logLevel The severity level of the message.\r\n * @param {string} message The message.\r\n */\r\n log(logLevel: LogLevel, message: string): void;\r\n}\r\n","// Copyright (c) .NET Foundation. All rights reserved.\r\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\r\n\r\nimport { ILogger, LogLevel } from \"./ILogger\";\r\n\r\n/** A logger that does nothing when log messages are sent to it. */\r\nexport class NullLogger implements ILogger {\r\n /** The singleton instance of the {@link @microsoft/signalr.NullLogger}. */\r\n public static instance: ILogger = new NullLogger();\r\n\r\n private constructor() {}\r\n\r\n /** @inheritDoc */\r\n // tslint:disable-next-line\r\n public log(_logLevel: LogLevel, _message: string): void {\r\n }\r\n}\r\n","// Copyright (c) .NET Foundation. All rights reserved.\r\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\r\n\r\n// Not exported from index\r\n/** @private */\r\nexport class TextMessageFormat {\r\n public static RecordSeparatorCode = 0x1e;\r\n public static RecordSeparator = String.fromCharCode(TextMessageFormat.RecordSeparatorCode);\r\n\r\n public static write(output: string): string {\r\n return `${output}${TextMessageFormat.RecordSeparator}`;\r\n }\r\n\r\n public static parse(input: string): string[] {\r\n if (input[input.length - 1] !== TextMessageFormat.RecordSeparator) {\r\n throw new Error(\"Message is incomplete.\");\r\n }\r\n\r\n const messages = input.split(TextMessageFormat.RecordSeparator);\r\n messages.pop();\r\n return messages;\r\n }\r\n}\r\n","// Copyright (c) .NET Foundation. All rights reserved.\r\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\r\n\r\n/** Error thrown when an HTTP request fails. */\r\nexport class HttpError extends Error {\r\n // @ts-ignore: Intentionally unused.\r\n // tslint:disable-next-line:variable-name\r\n private __proto__: Error;\r\n\r\n /** The HTTP status code represented by this error. */\r\n public statusCode: number;\r\n\r\n /** Constructs a new instance of {@link @microsoft/signalr.HttpError}.\r\n *\r\n * @param {string} errorMessage A descriptive error message.\r\n * @param {number} statusCode The HTTP status code represented by this error.\r\n */\r\n constructor(errorMessage: string, statusCode: number) {\r\n const trueProto = new.target.prototype;\r\n super(errorMessage);\r\n this.statusCode = statusCode;\r\n\r\n // Workaround issue in Typescript compiler\r\n // https://github.com/Microsoft/TypeScript/issues/13965#issuecomment-278570200\r\n this.__proto__ = trueProto;\r\n }\r\n}\r\n\r\n/** Error thrown when a timeout elapses. */\r\nexport class TimeoutError extends Error {\r\n // @ts-ignore: Intentionally unused.\r\n // tslint:disable-next-line:variable-name\r\n private __proto__: Error;\r\n\r\n /** Constructs a new instance of {@link @microsoft/signalr.TimeoutError}.\r\n *\r\n * @param {string} errorMessage A descriptive error message.\r\n */\r\n constructor(errorMessage: string = \"A timeout occurred.\") {\r\n const trueProto = new.target.prototype;\r\n super(errorMessage);\r\n\r\n // Workaround issue in Typescript compiler\r\n // https://github.com/Microsoft/TypeScript/issues/13965#issuecomment-278570200\r\n this.__proto__ = trueProto;\r\n }\r\n}\r\n\r\n/** Error thrown when an action is aborted. */\r\nexport class AbortError extends Error {\r\n // @ts-ignore: Intentionally unused.\r\n // tslint:disable-next-line:variable-name\r\n private __proto__: Error;\r\n\r\n /** Constructs a new instance of {@link AbortError}.\r\n *\r\n * @param {string} errorMessage A descriptive error message.\r\n */\r\n constructor(errorMessage: string = \"An abort occurred.\") {\r\n const trueProto = new.target.prototype;\r\n super(errorMessage);\r\n\r\n // Workaround issue in Typescript compiler\r\n // https://github.com/Microsoft/TypeScript/issues/13965#issuecomment-278570200\r\n this.__proto__ = trueProto;\r\n }\r\n}\r\n","// Copyright (c) .NET Foundation. All rights reserved.\r\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\r\n\r\nimport { AbortSignal } from \"./AbortController\";\r\nimport { MessageHeaders } from \"./IHubProtocol\";\r\n\r\n/** Represents an HTTP request. */\r\nexport interface HttpRequest {\r\n /** The HTTP method to use for the request. */\r\n method?: string;\r\n\r\n /** The URL for the request. */\r\n url?: string;\r\n\r\n /** The body content for the request. May be a string or an ArrayBuffer (for binary data). */\r\n content?: string | ArrayBuffer;\r\n\r\n /** An object describing headers to apply to the request. */\r\n headers?: MessageHeaders;\r\n\r\n /** The XMLHttpRequestResponseType to apply to the request. */\r\n responseType?: XMLHttpRequestResponseType;\r\n\r\n /** An AbortSignal that can be monitored for cancellation. */\r\n abortSignal?: AbortSignal;\r\n\r\n /** The time to wait for the request to complete before throwing a TimeoutError. Measured in milliseconds. */\r\n timeout?: number;\r\n\r\n /** This controls whether credentials such as cookies are sent in cross-site requests. */\r\n withCredentials?: boolean;\r\n}\r\n\r\n/** Represents an HTTP response. */\r\nexport class HttpResponse {\r\n /** Constructs a new instance of {@link @microsoft/signalr.HttpResponse} with the specified status code.\r\n *\r\n * @param {number} statusCode The status code of the response.\r\n */\r\n constructor(statusCode: number);\r\n\r\n /** Constructs a new instance of {@link @microsoft/signalr.HttpResponse} with the specified status code and message.\r\n *\r\n * @param {number} statusCode The status code of the response.\r\n * @param {string} statusText The status message of the response.\r\n */\r\n constructor(statusCode: number, statusText: string);\r\n\r\n /** Constructs a new instance of {@link @microsoft/signalr.HttpResponse} with the specified status code, message and string content.\r\n *\r\n * @param {number} statusCode The status code of the response.\r\n * @param {string} statusText The status message of the response.\r\n * @param {string} content The content of the response.\r\n */\r\n constructor(statusCode: number, statusText: string, content: string);\r\n\r\n /** Constructs a new instance of {@link @microsoft/signalr.HttpResponse} with the specified status code, message and binary content.\r\n *\r\n * @param {number} statusCode The status code of the response.\r\n * @param {string} statusText The status message of the response.\r\n * @param {ArrayBuffer} content The content of the response.\r\n */\r\n constructor(statusCode: number, statusText: string, content: ArrayBuffer);\r\n\r\n /** Constructs a new instance of {@link @microsoft/signalr.HttpResponse} with the specified status code, message and binary content.\r\n *\r\n * @param {number} statusCode The status code of the response.\r\n * @param {string} statusText The status message of the response.\r\n * @param {string | ArrayBuffer} content The content of the response.\r\n */\r\n constructor(statusCode: number, statusText: string, content: string | ArrayBuffer);\r\n constructor(\r\n public readonly statusCode: number,\r\n public readonly statusText?: string,\r\n public readonly content?: string | ArrayBuffer) {\r\n }\r\n}\r\n\r\n/** Abstraction over an HTTP client.\r\n *\r\n * This class provides an abstraction over an HTTP client so that a different implementation can be provided on different platforms.\r\n */\r\nexport abstract class HttpClient {\r\n /** Issues an HTTP GET request to the specified URL, returning a Promise that resolves with an {@link @microsoft/signalr.HttpResponse} representing the result.\r\n *\r\n * @param {string} url The URL for the request.\r\n * @returns {Promise} A Promise that resolves with an {@link @microsoft/signalr.HttpResponse} describing the response, or rejects with an Error indicating a failure.\r\n */\r\n public get(url: string): Promise;\r\n\r\n /** Issues an HTTP GET request to the specified URL, returning a Promise that resolves with an {@link @microsoft/signalr.HttpResponse} representing the result.\r\n *\r\n * @param {string} url The URL for the request.\r\n * @param {HttpRequest} options Additional options to configure the request. The 'url' field in this object will be overridden by the url parameter.\r\n * @returns {Promise} A Promise that resolves with an {@link @microsoft/signalr.HttpResponse} describing the response, or rejects with an Error indicating a failure.\r\n */\r\n public get(url: string, options: HttpRequest): Promise;\r\n public get(url: string, options?: HttpRequest): Promise {\r\n return this.send({\r\n ...options,\r\n method: \"GET\",\r\n url,\r\n });\r\n }\r\n\r\n /** Issues an HTTP POST request to the specified URL, returning a Promise that resolves with an {@link @microsoft/signalr.HttpResponse} representing the result.\r\n *\r\n * @param {string} url The URL for the request.\r\n * @returns {Promise} A Promise that resolves with an {@link @microsoft/signalr.HttpResponse} describing the response, or rejects with an Error indicating a failure.\r\n */\r\n public post(url: string): Promise;\r\n\r\n /** Issues an HTTP POST request to the specified URL, returning a Promise that resolves with an {@link @microsoft/signalr.HttpResponse} representing the result.\r\n *\r\n * @param {string} url The URL for the request.\r\n * @param {HttpRequest} options Additional options to configure the request. The 'url' field in this object will be overridden by the url parameter.\r\n * @returns {Promise} A Promise that resolves with an {@link @microsoft/signalr.HttpResponse} describing the response, or rejects with an Error indicating a failure.\r\n */\r\n public post(url: string, options: HttpRequest): Promise;\r\n public post(url: string, options?: HttpRequest): Promise {\r\n return this.send({\r\n ...options,\r\n method: \"POST\",\r\n url,\r\n });\r\n }\r\n\r\n /** Issues an HTTP DELETE request to the specified URL, returning a Promise that resolves with an {@link @microsoft/signalr.HttpResponse} representing the result.\r\n *\r\n * @param {string} url The URL for the request.\r\n * @returns {Promise} A Promise that resolves with an {@link @microsoft/signalr.HttpResponse} describing the response, or rejects with an Error indicating a failure.\r\n */\r\n public delete(url: string): Promise;\r\n\r\n /** Issues an HTTP DELETE request to the specified URL, returning a Promise that resolves with an {@link @microsoft/signalr.HttpResponse} representing the result.\r\n *\r\n * @param {string} url The URL for the request.\r\n * @param {HttpRequest} options Additional options to configure the request. The 'url' field in this object will be overridden by the url parameter.\r\n * @returns {Promise} A Promise that resolves with an {@link @microsoft/signalr.HttpResponse} describing the response, or rejects with an Error indicating a failure.\r\n */\r\n public delete(url: string, options: HttpRequest): Promise;\r\n public delete(url: string, options?: HttpRequest): Promise {\r\n return this.send({\r\n ...options,\r\n method: \"DELETE\",\r\n url,\r\n });\r\n }\r\n\r\n /** Issues an HTTP request to the specified URL, returning a {@link Promise} that resolves with an {@link @microsoft/signalr.HttpResponse} representing the result.\r\n *\r\n * @param {HttpRequest} request An {@link @microsoft/signalr.HttpRequest} describing the request to send.\r\n * @returns {Promise} A Promise that resolves with an HttpResponse describing the response, or rejects with an Error indicating a failure.\r\n */\r\n public abstract send(request: HttpRequest): Promise;\r\n\r\n /** Gets all cookies that apply to the specified URL.\r\n *\r\n * @param url The URL that the cookies are valid for.\r\n * @returns {string} A string containing all the key-value cookie pairs for the specified URL.\r\n */\r\n // @ts-ignore\r\n public getCookieString(url: string): string {\r\n return \"\";\r\n }\r\n}\r\n","// Copyright (c) .NET Foundation. All rights reserved.\r\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\r\n\r\n// @ts-ignore: This will be removed from built files and is here to make the types available during dev work\r\nimport * as tough from \"@types/tough-cookie\";\r\n\r\nimport { AbortError, HttpError, TimeoutError } from \"./Errors\";\r\nimport { HttpClient, HttpRequest, HttpResponse } from \"./HttpClient\";\r\nimport { ILogger, LogLevel } from \"./ILogger\";\r\nimport { Platform } from \"./Utils\";\r\n\r\nexport class FetchHttpClient extends HttpClient {\r\n private readonly abortControllerType: { prototype: AbortController, new(): AbortController };\r\n private readonly fetchType: (input: RequestInfo, init?: RequestInit) => Promise;\r\n private readonly jar?: tough.CookieJar;\r\n\r\n private readonly logger: ILogger;\r\n\r\n public constructor(logger: ILogger) {\r\n super();\r\n this.logger = logger;\r\n\r\n if (typeof fetch === \"undefined\") {\r\n // In order to ignore the dynamic require in webpack builds we need to do this magic\r\n // @ts-ignore: TS doesn't know about these names\r\n const requireFunc = typeof __webpack_require__ === \"function\" ? __non_webpack_require__ : require;\r\n\r\n // Cookies aren't automatically handled in Node so we need to add a CookieJar to preserve cookies across requests\r\n this.jar = new (requireFunc(\"tough-cookie\")).CookieJar();\r\n this.fetchType = requireFunc(\"node-fetch\");\r\n\r\n // node-fetch doesn't have a nice API for getting and setting cookies\r\n // fetch-cookie will wrap a fetch implementation with a default CookieJar or a provided one\r\n this.fetchType = requireFunc(\"fetch-cookie\")(this.fetchType, this.jar);\r\n\r\n // Node needs EventListener methods on AbortController which our custom polyfill doesn't provide\r\n this.abortControllerType = requireFunc(\"abort-controller\");\r\n } else {\r\n this.fetchType = fetch.bind(self);\r\n this.abortControllerType = AbortController;\r\n }\r\n }\r\n\r\n /** @inheritDoc */\r\n public async send(request: HttpRequest): Promise {\r\n // Check that abort was not signaled before calling send\r\n if (request.abortSignal && request.abortSignal.aborted) {\r\n throw new AbortError();\r\n }\r\n\r\n if (!request.method) {\r\n throw new Error(\"No method defined.\");\r\n }\r\n if (!request.url) {\r\n throw new Error(\"No url defined.\");\r\n }\r\n\r\n const abortController = new this.abortControllerType();\r\n\r\n let error: any;\r\n // Hook our abortSignal into the abort controller\r\n if (request.abortSignal) {\r\n request.abortSignal.onabort = () => {\r\n abortController.abort();\r\n error = new AbortError();\r\n };\r\n }\r\n\r\n // If a timeout has been passed in, setup a timeout to call abort\r\n // Type needs to be any to fit window.setTimeout and NodeJS.setTimeout\r\n let timeoutId: any = null;\r\n if (request.timeout) {\r\n const msTimeout = request.timeout!;\r\n timeoutId = setTimeout(() => {\r\n abortController.abort();\r\n this.logger.log(LogLevel.Warning, `Timeout from HTTP request.`);\r\n error = new TimeoutError();\r\n }, msTimeout);\r\n }\r\n\r\n let response: Response;\r\n try {\r\n response = await this.fetchType(request.url!, {\r\n body: request.content!,\r\n cache: \"no-cache\",\r\n credentials: request.withCredentials === true ? \"include\" : \"same-origin\",\r\n headers: {\r\n \"Content-Type\": \"text/plain;charset=UTF-8\",\r\n \"X-Requested-With\": \"XMLHttpRequest\",\r\n ...request.headers,\r\n },\r\n method: request.method!,\r\n mode: \"cors\",\r\n redirect: \"manual\",\r\n signal: abortController.signal,\r\n });\r\n } catch (e) {\r\n if (error) {\r\n throw error;\r\n }\r\n this.logger.log(\r\n LogLevel.Warning,\r\n `Error from HTTP request. ${e}.`,\r\n );\r\n throw e;\r\n } finally {\r\n if (timeoutId) {\r\n clearTimeout(timeoutId);\r\n }\r\n if (request.abortSignal) {\r\n request.abortSignal.onabort = null;\r\n }\r\n }\r\n\r\n if (!response.ok) {\r\n throw new HttpError(response.statusText, response.status);\r\n }\r\n\r\n const content = deserializeContent(response, request.responseType);\r\n const payload = await content;\r\n\r\n return new HttpResponse(\r\n response.status,\r\n response.statusText,\r\n payload,\r\n );\r\n }\r\n\r\n public getCookieString(url: string): string {\r\n let cookies: string = \"\";\r\n if (Platform.isNode && this.jar) {\r\n // @ts-ignore: unused variable\r\n this.jar.getCookies(url, (e, c) => cookies = c.join(\"; \"));\r\n }\r\n return cookies;\r\n }\r\n}\r\n\r\nfunction deserializeContent(response: Response, responseType?: XMLHttpRequestResponseType): Promise {\r\n let content;\r\n switch (responseType) {\r\n case \"arraybuffer\":\r\n content = response.arrayBuffer();\r\n break;\r\n case \"text\":\r\n content = response.text();\r\n break;\r\n case \"blob\":\r\n case \"document\":\r\n case \"json\":\r\n throw new Error(`${responseType} is not supported.`);\r\n default:\r\n content = response.text();\r\n break;\r\n }\r\n\r\n return content;\r\n}\r\n","// Copyright (c) .NET Foundation. All rights reserved.\r\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\r\n\r\nimport { ILogger } from \"./ILogger\";\r\nimport { TransferFormat } from \"./ITransport\";\r\n\r\n/** Defines the type of a Hub Message. */\r\nexport enum MessageType {\r\n /** Indicates the message is an Invocation message and implements the {@link @microsoft/signalr.InvocationMessage} interface. */\r\n Invocation = 1,\r\n /** Indicates the message is a StreamItem message and implements the {@link @microsoft/signalr.StreamItemMessage} interface. */\r\n StreamItem = 2,\r\n /** Indicates the message is a Completion message and implements the {@link @microsoft/signalr.CompletionMessage} interface. */\r\n Completion = 3,\r\n /** Indicates the message is a Stream Invocation message and implements the {@link @microsoft/signalr.StreamInvocationMessage} interface. */\r\n StreamInvocation = 4,\r\n /** Indicates the message is a Cancel Invocation message and implements the {@link @microsoft/signalr.CancelInvocationMessage} interface. */\r\n CancelInvocation = 5,\r\n /** Indicates the message is a Ping message and implements the {@link @microsoft/signalr.PingMessage} interface. */\r\n Ping = 6,\r\n /** Indicates the message is a Close message and implements the {@link @microsoft/signalr.CloseMessage} interface. */\r\n Close = 7,\r\n}\r\n\r\n/** Defines a dictionary of string keys and string values representing headers attached to a Hub message. */\r\nexport interface MessageHeaders {\r\n /** Gets or sets the header with the specified key. */\r\n [key: string]: string;\r\n}\r\n\r\n/** Union type of all known Hub messages. */\r\nexport type HubMessage =\r\n InvocationMessage |\r\n StreamInvocationMessage |\r\n StreamItemMessage |\r\n CompletionMessage |\r\n CancelInvocationMessage |\r\n PingMessage |\r\n CloseMessage;\r\n\r\n/** Defines properties common to all Hub messages. */\r\nexport interface HubMessageBase {\r\n /** A {@link @microsoft/signalr.MessageType} value indicating the type of this message. */\r\n readonly type: MessageType;\r\n}\r\n\r\n/** Defines properties common to all Hub messages relating to a specific invocation. */\r\nexport interface HubInvocationMessage extends HubMessageBase {\r\n /** A {@link @microsoft/signalr.MessageHeaders} dictionary containing headers attached to the message. */\r\n readonly headers?: MessageHeaders;\r\n /** The ID of the invocation relating to this message.\r\n *\r\n * This is expected to be present for {@link @microsoft/signalr.StreamInvocationMessage} and {@link @microsoft/signalr.CompletionMessage}. It may\r\n * be 'undefined' for an {@link @microsoft/signalr.InvocationMessage} if the sender does not expect a response.\r\n */\r\n readonly invocationId?: string;\r\n}\r\n\r\n/** A hub message representing a non-streaming invocation. */\r\nexport interface InvocationMessage extends HubInvocationMessage {\r\n /** @inheritDoc */\r\n readonly type: MessageType.Invocation;\r\n /** The target method name. */\r\n readonly target: string;\r\n /** The target method arguments. */\r\n readonly arguments: any[];\r\n /** The target methods stream IDs. */\r\n readonly streamIds?: string[];\r\n}\r\n\r\n/** A hub message representing a streaming invocation. */\r\nexport interface StreamInvocationMessage extends HubInvocationMessage {\r\n /** @inheritDoc */\r\n readonly type: MessageType.StreamInvocation;\r\n\r\n /** The invocation ID. */\r\n readonly invocationId: string;\r\n /** The target method name. */\r\n readonly target: string;\r\n /** The target method arguments. */\r\n readonly arguments: any[];\r\n /** The target methods stream IDs. */\r\n readonly streamIds?: string[];\r\n}\r\n\r\n/** A hub message representing a single item produced as part of a result stream. */\r\nexport interface StreamItemMessage extends HubInvocationMessage {\r\n /** @inheritDoc */\r\n readonly type: MessageType.StreamItem;\r\n\r\n /** The invocation ID. */\r\n readonly invocationId: string;\r\n\r\n /** The item produced by the server. */\r\n readonly item?: any;\r\n}\r\n\r\n/** A hub message representing the result of an invocation. */\r\nexport interface CompletionMessage extends HubInvocationMessage {\r\n /** @inheritDoc */\r\n readonly type: MessageType.Completion;\r\n /** The invocation ID. */\r\n readonly invocationId: string;\r\n /** The error produced by the invocation, if any.\r\n *\r\n * Either {@link @microsoft/signalr.CompletionMessage.error} or {@link @microsoft/signalr.CompletionMessage.result} must be defined, but not both.\r\n */\r\n readonly error?: string;\r\n /** The result produced by the invocation, if any.\r\n *\r\n * Either {@link @microsoft/signalr.CompletionMessage.error} or {@link @microsoft/signalr.CompletionMessage.result} must be defined, but not both.\r\n */\r\n readonly result?: any;\r\n}\r\n\r\n/** A hub message indicating that the sender is still active. */\r\nexport interface PingMessage extends HubMessageBase {\r\n /** @inheritDoc */\r\n readonly type: MessageType.Ping;\r\n}\r\n\r\n/** A hub message indicating that the sender is closing the connection.\r\n *\r\n * If {@link @microsoft/signalr.CloseMessage.error} is defined, the sender is closing the connection due to an error.\r\n */\r\nexport interface CloseMessage extends HubMessageBase {\r\n /** @inheritDoc */\r\n readonly type: MessageType.Close;\r\n /** The error that triggered the close, if any.\r\n *\r\n * If this property is undefined, the connection was closed normally and without error.\r\n */\r\n readonly error?: string;\r\n\r\n /** If true, clients with automatic reconnects enabled should attempt to reconnect after receiving the CloseMessage. Otherwise, they should not. */\r\n readonly allowReconnect?: boolean;\r\n}\r\n\r\n/** A hub message sent to request that a streaming invocation be canceled. */\r\nexport interface CancelInvocationMessage extends HubInvocationMessage {\r\n /** @inheritDoc */\r\n readonly type: MessageType.CancelInvocation;\r\n /** The invocation ID. */\r\n readonly invocationId: string;\r\n}\r\n\r\n/** A protocol abstraction for communicating with SignalR Hubs. */\r\nexport interface IHubProtocol {\r\n /** The name of the protocol. This is used by SignalR to resolve the protocol between the client and server. */\r\n readonly name: string;\r\n /** The version of the protocol. */\r\n readonly version: number;\r\n /** The {@link @microsoft/signalr.TransferFormat} of the protocol. */\r\n readonly transferFormat: TransferFormat;\r\n\r\n /** Creates an array of {@link @microsoft/signalr.HubMessage} objects from the specified serialized representation.\r\n *\r\n * If {@link @microsoft/signalr.IHubProtocol.transferFormat} is 'Text', the `input` parameter must be a string, otherwise it must be an ArrayBuffer.\r\n *\r\n * @param {string | ArrayBuffer | Buffer} input A string, ArrayBuffer, or Buffer containing the serialized representation.\r\n * @param {ILogger} logger A logger that will be used to log messages that occur during parsing.\r\n */\r\n parseMessages(input: string | ArrayBuffer | Buffer, logger: ILogger): HubMessage[];\r\n\r\n /** Writes the specified {@link @microsoft/signalr.HubMessage} to a string or ArrayBuffer and returns it.\r\n *\r\n * If {@link @microsoft/signalr.IHubProtocol.transferFormat} is 'Text', the result of this method will be a string, otherwise it will be an ArrayBuffer.\r\n *\r\n * @param {HubMessage} message The message to write.\r\n * @returns {string | ArrayBuffer} A string or ArrayBuffer containing the serialized representation of the message.\r\n */\r\n writeMessage(message: HubMessage): string | ArrayBuffer;\r\n}\r\n","// Copyright (c) .NET Foundation. All rights reserved.\r\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\r\n\r\nimport { AbortError, HttpError, TimeoutError } from \"./Errors\";\r\nimport { HttpClient, HttpRequest, HttpResponse } from \"./HttpClient\";\r\nimport { ILogger, LogLevel } from \"./ILogger\";\r\n\r\nexport class XhrHttpClient extends HttpClient {\r\n private readonly logger: ILogger;\r\n\r\n public constructor(logger: ILogger) {\r\n super();\r\n this.logger = logger;\r\n }\r\n\r\n /** @inheritDoc */\r\n public send(request: HttpRequest): Promise {\r\n // Check that abort was not signaled before calling send\r\n if (request.abortSignal && request.abortSignal.aborted) {\r\n return Promise.reject(new AbortError());\r\n }\r\n\r\n if (!request.method) {\r\n return Promise.reject(new Error(\"No method defined.\"));\r\n }\r\n if (!request.url) {\r\n return Promise.reject(new Error(\"No url defined.\"));\r\n }\r\n\r\n return new Promise((resolve, reject) => {\r\n const xhr = new XMLHttpRequest();\r\n\r\n xhr.open(request.method!, request.url!, true);\r\n xhr.withCredentials = request.withCredentials === undefined ? true : request.withCredentials;\r\n xhr.setRequestHeader(\"X-Requested-With\", \"XMLHttpRequest\");\r\n // Explicitly setting the Content-Type header for React Native on Android platform.\r\n xhr.setRequestHeader(\"Content-Type\", \"text/plain;charset=UTF-8\");\r\n\r\n const headers = request.headers;\r\n if (headers) {\r\n Object.keys(headers)\r\n .forEach((header) => {\r\n xhr.setRequestHeader(header, headers[header]);\r\n });\r\n }\r\n\r\n if (request.responseType) {\r\n xhr.responseType = request.responseType;\r\n }\r\n\r\n if (request.abortSignal) {\r\n request.abortSignal.onabort = () => {\r\n xhr.abort();\r\n reject(new AbortError());\r\n };\r\n }\r\n\r\n if (request.timeout) {\r\n xhr.timeout = request.timeout;\r\n }\r\n\r\n xhr.onload = () => {\r\n if (request.abortSignal) {\r\n request.abortSignal.onabort = null;\r\n }\r\n\r\n if (xhr.status >= 200 && xhr.status < 300) {\r\n resolve(new HttpResponse(xhr.status, xhr.statusText, xhr.response || xhr.responseText));\r\n } else {\r\n reject(new HttpError(xhr.statusText, xhr.status));\r\n }\r\n };\r\n\r\n xhr.onerror = () => {\r\n this.logger.log(LogLevel.Warning, `Error from HTTP request. ${xhr.status}: ${xhr.statusText}.`);\r\n reject(new HttpError(xhr.statusText, xhr.status));\r\n };\r\n\r\n xhr.ontimeout = () => {\r\n this.logger.log(LogLevel.Warning, `Timeout from HTTP request.`);\r\n reject(new TimeoutError());\r\n };\r\n\r\n xhr.send(request.content || \"\");\r\n });\r\n }\r\n}\r\n","// Copyright (c) .NET Foundation. All rights reserved.\r\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\r\n\r\nimport { AbortError } from \"./Errors\";\r\nimport { FetchHttpClient } from \"./FetchHttpClient\";\r\nimport { HttpClient, HttpRequest, HttpResponse } from \"./HttpClient\";\r\nimport { ILogger } from \"./ILogger\";\r\nimport { Platform } from \"./Utils\";\r\nimport { XhrHttpClient } from \"./XhrHttpClient\";\r\n\r\n/** Default implementation of {@link @microsoft/signalr.HttpClient}. */\r\nexport class DefaultHttpClient extends HttpClient {\r\n private readonly httpClient: HttpClient;\r\n\r\n /** Creates a new instance of the {@link @microsoft/signalr.DefaultHttpClient}, using the provided {@link @microsoft/signalr.ILogger} to log messages. */\r\n public constructor(logger: ILogger) {\r\n super();\r\n\r\n if (typeof fetch !== \"undefined\" || Platform.isNode) {\r\n this.httpClient = new FetchHttpClient(logger);\r\n } else if (typeof XMLHttpRequest !== \"undefined\") {\r\n this.httpClient = new XhrHttpClient(logger);\r\n } else {\r\n throw new Error(\"No usable HttpClient found.\");\r\n }\r\n }\r\n\r\n /** @inheritDoc */\r\n public send(request: HttpRequest): Promise {\r\n // Check that abort was not signaled before calling send\r\n if (request.abortSignal && request.abortSignal.aborted) {\r\n return Promise.reject(new AbortError());\r\n }\r\n\r\n if (!request.method) {\r\n return Promise.reject(new Error(\"No method defined.\"));\r\n }\r\n if (!request.url) {\r\n return Promise.reject(new Error(\"No url defined.\"));\r\n }\r\n\r\n return this.httpClient.send(request);\r\n }\r\n\r\n public getCookieString(url: string): string {\r\n return this.httpClient.getCookieString(url);\r\n }\r\n}\r\n","// Copyright (c) .NET Foundation. All rights reserved.\r\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\r\n\r\nimport { IStreamResult, IStreamSubscriber, ISubscription } from \"./Stream\";\r\nimport { SubjectSubscription } from \"./Utils\";\r\n\r\n/** Stream implementation to stream items to the server. */\r\nexport class Subject implements IStreamResult {\r\n /** @internal */\r\n public observers: Array>;\r\n\r\n /** @internal */\r\n public cancelCallback?: () => Promise;\r\n\r\n constructor() {\r\n this.observers = [];\r\n }\r\n\r\n public next(item: T): void {\r\n for (const observer of this.observers) {\r\n observer.next(item);\r\n }\r\n }\r\n\r\n public error(err: any): void {\r\n for (const observer of this.observers) {\r\n if (observer.error) {\r\n observer.error(err);\r\n }\r\n }\r\n }\r\n\r\n public complete(): void {\r\n for (const observer of this.observers) {\r\n if (observer.complete) {\r\n observer.complete();\r\n }\r\n }\r\n }\r\n\r\n public subscribe(observer: IStreamSubscriber): ISubscription {\r\n this.observers.push(observer);\r\n return new SubjectSubscription(this, observer);\r\n }\r\n}\r\n","// Copyright (c) .NET Foundation. All rights reserved.\r\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\r\n\r\nimport { HandshakeProtocol, HandshakeRequestMessage, HandshakeResponseMessage } from \"./HandshakeProtocol\";\r\nimport { IConnection } from \"./IConnection\";\r\nimport { CancelInvocationMessage, CompletionMessage, IHubProtocol, InvocationMessage, MessageType, StreamInvocationMessage, StreamItemMessage } from \"./IHubProtocol\";\r\nimport { ILogger, LogLevel } from \"./ILogger\";\r\nimport { IRetryPolicy } from \"./IRetryPolicy\";\r\nimport { IStreamResult } from \"./Stream\";\r\nimport { Subject } from \"./Subject\";\r\nimport { Arg } from \"./Utils\";\r\n\r\nconst DEFAULT_TIMEOUT_IN_MS: number = 30 * 1000;\r\nconst DEFAULT_PING_INTERVAL_IN_MS: number = 15 * 1000;\r\n\r\n/** Describes the current state of the {@link HubConnection} to the server. */\r\nexport enum HubConnectionState {\r\n /** The hub connection is disconnected. */\r\n Disconnected = \"Disconnected\",\r\n /** The hub connection is connecting. */\r\n Connecting = \"Connecting\",\r\n /** The hub connection is connected. */\r\n Connected = \"Connected\",\r\n /** The hub connection is disconnecting. */\r\n Disconnecting = \"Disconnecting\",\r\n /** The hub connection is reconnecting. */\r\n Reconnecting = \"Reconnecting\",\r\n}\r\n\r\n/** Represents a connection to a SignalR Hub. */\r\nexport class HubConnection {\r\n private readonly cachedPingMessage: string | ArrayBuffer;\r\n private readonly connection: IConnection;\r\n private readonly logger: ILogger;\r\n private readonly reconnectPolicy?: IRetryPolicy;\r\n private protocol: IHubProtocol;\r\n private handshakeProtocol: HandshakeProtocol;\r\n private callbacks: { [invocationId: string]: (invocationEvent: StreamItemMessage | CompletionMessage | null, error?: Error) => void };\r\n private methods: { [name: string]: Array<(...args: any[]) => void> };\r\n private invocationId: number;\r\n\r\n private closedCallbacks: Array<(error?: Error) => void>;\r\n private reconnectingCallbacks: Array<(error?: Error) => void>;\r\n private reconnectedCallbacks: Array<(connectionId?: string) => void>;\r\n\r\n private receivedHandshakeResponse: boolean;\r\n private handshakeResolver!: (value?: PromiseLike<{}>) => void;\r\n private handshakeRejecter!: (reason?: any) => void;\r\n private stopDuringStartError?: Error;\r\n\r\n private connectionState: HubConnectionState;\r\n // connectionStarted is tracked independently from connectionState, so we can check if the\r\n // connection ever did successfully transition from connecting to connected before disconnecting.\r\n private connectionStarted: boolean;\r\n private startPromise?: Promise;\r\n private stopPromise?: Promise;\r\n private nextKeepAlive: number = 0;\r\n\r\n // The type of these a) doesn't matter and b) varies when building in browser and node contexts\r\n // Since we're building the WebPack bundle directly from the TypeScript, this matters (previously\r\n // we built the bundle from the compiled JavaScript).\r\n private reconnectDelayHandle?: any;\r\n private timeoutHandle?: any;\r\n private pingServerHandle?: any;\r\n\r\n /** The server timeout in milliseconds.\r\n *\r\n * If this timeout elapses without receiving any messages from the server, the connection will be terminated with an error.\r\n * The default timeout value is 30,000 milliseconds (30 seconds).\r\n */\r\n public serverTimeoutInMilliseconds: number;\r\n\r\n /** Default interval at which to ping the server.\r\n *\r\n * The default value is 15,000 milliseconds (15 seconds).\r\n * Allows the server to detect hard disconnects (like when a client unplugs their computer).\r\n * The ping will happen at most as often as the server pings.\r\n * If the server pings every 5 seconds, a value lower than 5 will ping every 5 seconds.\r\n */\r\n public keepAliveIntervalInMilliseconds: number;\r\n\r\n /** @internal */\r\n // Using a public static factory method means we can have a private constructor and an _internal_\r\n // create method that can be used by HubConnectionBuilder. An \"internal\" constructor would just\r\n // be stripped away and the '.d.ts' file would have no constructor, which is interpreted as a\r\n // public parameter-less constructor.\r\n public static create(connection: IConnection, logger: ILogger, protocol: IHubProtocol, reconnectPolicy?: IRetryPolicy): HubConnection {\r\n return new HubConnection(connection, logger, protocol, reconnectPolicy);\r\n }\r\n\r\n private constructor(connection: IConnection, logger: ILogger, protocol: IHubProtocol, reconnectPolicy?: IRetryPolicy) {\r\n Arg.isRequired(connection, \"connection\");\r\n Arg.isRequired(logger, \"logger\");\r\n Arg.isRequired(protocol, \"protocol\");\r\n\r\n this.serverTimeoutInMilliseconds = DEFAULT_TIMEOUT_IN_MS;\r\n this.keepAliveIntervalInMilliseconds = DEFAULT_PING_INTERVAL_IN_MS;\r\n\r\n this.logger = logger;\r\n this.protocol = protocol;\r\n this.connection = connection;\r\n this.reconnectPolicy = reconnectPolicy;\r\n this.handshakeProtocol = new HandshakeProtocol();\r\n\r\n this.connection.onreceive = (data: any) => this.processIncomingData(data);\r\n this.connection.onclose = (error?: Error) => this.connectionClosed(error);\r\n\r\n this.callbacks = {};\r\n this.methods = {};\r\n this.closedCallbacks = [];\r\n this.reconnectingCallbacks = [];\r\n this.reconnectedCallbacks = [];\r\n this.invocationId = 0;\r\n this.receivedHandshakeResponse = false;\r\n this.connectionState = HubConnectionState.Disconnected;\r\n this.connectionStarted = false;\r\n\r\n this.cachedPingMessage = this.protocol.writeMessage({ type: MessageType.Ping });\r\n }\r\n\r\n /** Indicates the state of the {@link HubConnection} to the server. */\r\n get state(): HubConnectionState {\r\n return this.connectionState;\r\n }\r\n\r\n /** Represents the connection id of the {@link HubConnection} on the server. The connection id will be null when the connection is either\r\n * in the disconnected state or if the negotiation step was skipped.\r\n */\r\n get connectionId(): string | null {\r\n return this.connection ? (this.connection.connectionId || null) : null;\r\n }\r\n\r\n /** Indicates the url of the {@link HubConnection} to the server. */\r\n get baseUrl(): string {\r\n return this.connection.baseUrl || \"\";\r\n }\r\n\r\n /**\r\n * Sets a new url for the HubConnection. Note that the url can only be changed when the connection is in either the Disconnected or\r\n * Reconnecting states.\r\n * @param {string} url The url to connect to.\r\n */\r\n set baseUrl(url: string) {\r\n if (this.connectionState !== HubConnectionState.Disconnected && this.connectionState !== HubConnectionState.Reconnecting) {\r\n throw new Error(\"The HubConnection must be in the Disconnected or Reconnecting state to change the url.\");\r\n }\r\n\r\n if (!url) {\r\n throw new Error(\"The HubConnection url must be a valid url.\");\r\n }\r\n\r\n this.connection.baseUrl = url;\r\n }\r\n\r\n /** Starts the connection.\r\n *\r\n * @returns {Promise} A Promise that resolves when the connection has been successfully established, or rejects with an error.\r\n */\r\n public start(): Promise {\r\n this.startPromise = this.startWithStateTransitions();\r\n return this.startPromise;\r\n }\r\n\r\n private async startWithStateTransitions(): Promise {\r\n if (this.connectionState !== HubConnectionState.Disconnected) {\r\n return Promise.reject(new Error(\"Cannot start a HubConnection that is not in the 'Disconnected' state.\"));\r\n }\r\n\r\n this.connectionState = HubConnectionState.Connecting;\r\n this.logger.log(LogLevel.Debug, \"Starting HubConnection.\");\r\n\r\n try {\r\n await this.startInternal();\r\n\r\n this.connectionState = HubConnectionState.Connected;\r\n this.connectionStarted = true;\r\n this.logger.log(LogLevel.Debug, \"HubConnection connected successfully.\");\r\n } catch (e) {\r\n this.connectionState = HubConnectionState.Disconnected;\r\n this.logger.log(LogLevel.Debug, `HubConnection failed to start successfully because of error '${e}'.`);\r\n return Promise.reject(e);\r\n }\r\n }\r\n\r\n private async startInternal() {\r\n this.stopDuringStartError = undefined;\r\n this.receivedHandshakeResponse = false;\r\n // Set up the promise before any connection is (re)started otherwise it could race with received messages\r\n const handshakePromise = new Promise((resolve, reject) => {\r\n this.handshakeResolver = resolve;\r\n this.handshakeRejecter = reject;\r\n });\r\n\r\n await this.connection.start(this.protocol.transferFormat);\r\n\r\n try {\r\n const handshakeRequest: HandshakeRequestMessage = {\r\n protocol: this.protocol.name,\r\n version: this.protocol.version,\r\n };\r\n\r\n this.logger.log(LogLevel.Debug, \"Sending handshake request.\");\r\n\r\n await this.sendMessage(this.handshakeProtocol.writeHandshakeRequest(handshakeRequest));\r\n\r\n this.logger.log(LogLevel.Information, `Using HubProtocol '${this.protocol.name}'.`);\r\n\r\n // defensively cleanup timeout in case we receive a message from the server before we finish start\r\n this.cleanupTimeout();\r\n this.resetTimeoutPeriod();\r\n this.resetKeepAliveInterval();\r\n\r\n await handshakePromise;\r\n\r\n // It's important to check the stopDuringStartError instead of just relying on the handshakePromise\r\n // being rejected on close, because this continuation can run after both the handshake completed successfully\r\n // and the connection was closed.\r\n if (this.stopDuringStartError) {\r\n // It's important to throw instead of returning a rejected promise, because we don't want to allow any state\r\n // transitions to occur between now and the calling code observing the exceptions. Returning a rejected promise\r\n // will cause the calling continuation to get scheduled to run later.\r\n throw this.stopDuringStartError;\r\n }\r\n } catch (e) {\r\n this.logger.log(LogLevel.Debug, `Hub handshake failed with error '${e}' during start(). Stopping HubConnection.`);\r\n\r\n this.cleanupTimeout();\r\n this.cleanupPingTimer();\r\n\r\n // HttpConnection.stop() should not complete until after the onclose callback is invoked.\r\n // This will transition the HubConnection to the disconnected state before HttpConnection.stop() completes.\r\n await this.connection.stop(e);\r\n throw e;\r\n }\r\n }\r\n\r\n /** Stops the connection.\r\n *\r\n * @returns {Promise} A Promise that resolves when the connection has been successfully terminated, or rejects with an error.\r\n */\r\n public async stop(): Promise {\r\n // Capture the start promise before the connection might be restarted in an onclose callback.\r\n const startPromise = this.startPromise;\r\n\r\n this.stopPromise = this.stopInternal();\r\n await this.stopPromise;\r\n\r\n try {\r\n // Awaiting undefined continues immediately\r\n await startPromise;\r\n } catch (e) {\r\n // This exception is returned to the user as a rejected Promise from the start method.\r\n }\r\n }\r\n\r\n private stopInternal(error?: Error): Promise {\r\n if (this.connectionState === HubConnectionState.Disconnected) {\r\n this.logger.log(LogLevel.Debug, `Call to HubConnection.stop(${error}) ignored because it is already in the disconnected state.`);\r\n return Promise.resolve();\r\n }\r\n\r\n if (this.connectionState === HubConnectionState.Disconnecting) {\r\n this.logger.log(LogLevel.Debug, `Call to HttpConnection.stop(${error}) ignored because the connection is already in the disconnecting state.`);\r\n return this.stopPromise!;\r\n }\r\n\r\n this.connectionState = HubConnectionState.Disconnecting;\r\n\r\n this.logger.log(LogLevel.Debug, \"Stopping HubConnection.\");\r\n\r\n if (this.reconnectDelayHandle) {\r\n // We're in a reconnect delay which means the underlying connection is currently already stopped.\r\n // Just clear the handle to stop the reconnect loop (which no one is waiting on thankfully) and\r\n // fire the onclose callbacks.\r\n this.logger.log(LogLevel.Debug, \"Connection stopped during reconnect delay. Done reconnecting.\");\r\n\r\n clearTimeout(this.reconnectDelayHandle);\r\n this.reconnectDelayHandle = undefined;\r\n\r\n this.completeClose();\r\n return Promise.resolve();\r\n }\r\n\r\n this.cleanupTimeout();\r\n this.cleanupPingTimer();\r\n this.stopDuringStartError = error || new Error(\"The connection was stopped before the hub handshake could complete.\");\r\n\r\n // HttpConnection.stop() should not complete until after either HttpConnection.start() fails\r\n // or the onclose callback is invoked. The onclose callback will transition the HubConnection\r\n // to the disconnected state if need be before HttpConnection.stop() completes.\r\n return this.connection.stop(error);\r\n }\r\n\r\n /** Invokes a streaming hub method on the server using the specified name and arguments.\r\n *\r\n * @typeparam T The type of the items returned by the server.\r\n * @param {string} methodName The name of the server method to invoke.\r\n * @param {any[]} args The arguments used to invoke the server method.\r\n * @returns {IStreamResult} An object that yields results from the server as they are received.\r\n */\r\n public stream(methodName: string, ...args: any[]): IStreamResult {\r\n const [streams, streamIds] = this.replaceStreamingParams(args);\r\n const invocationDescriptor = this.createStreamInvocation(methodName, args, streamIds);\r\n\r\n let promiseQueue: Promise;\r\n const subject = new Subject();\r\n subject.cancelCallback = () => {\r\n const cancelInvocation: CancelInvocationMessage = this.createCancelInvocation(invocationDescriptor.invocationId);\r\n\r\n delete this.callbacks[invocationDescriptor.invocationId];\r\n\r\n return promiseQueue.then(() => {\r\n return this.sendWithProtocol(cancelInvocation);\r\n });\r\n };\r\n\r\n this.callbacks[invocationDescriptor.invocationId] = (invocationEvent: CompletionMessage | StreamItemMessage | null, error?: Error) => {\r\n if (error) {\r\n subject.error(error);\r\n return;\r\n } else if (invocationEvent) {\r\n // invocationEvent will not be null when an error is not passed to the callback\r\n if (invocationEvent.type === MessageType.Completion) {\r\n if (invocationEvent.error) {\r\n subject.error(new Error(invocationEvent.error));\r\n } else {\r\n subject.complete();\r\n }\r\n } else {\r\n subject.next((invocationEvent.item) as T);\r\n }\r\n }\r\n };\r\n\r\n promiseQueue = this.sendWithProtocol(invocationDescriptor)\r\n .catch((e) => {\r\n subject.error(e);\r\n delete this.callbacks[invocationDescriptor.invocationId];\r\n });\r\n\r\n this.launchStreams(streams, promiseQueue);\r\n\r\n return subject;\r\n }\r\n\r\n private sendMessage(message: any) {\r\n this.resetKeepAliveInterval();\r\n return this.connection.send(message);\r\n }\r\n\r\n /**\r\n * Sends a js object to the server.\r\n * @param message The js object to serialize and send.\r\n */\r\n private sendWithProtocol(message: any) {\r\n return this.sendMessage(this.protocol.writeMessage(message));\r\n }\r\n\r\n /** Invokes a hub method on the server using the specified name and arguments. Does not wait for a response from the receiver.\r\n *\r\n * The Promise returned by this method resolves when the client has sent the invocation to the server. The server may still\r\n * be processing the invocation.\r\n *\r\n * @param {string} methodName The name of the server method to invoke.\r\n * @param {any[]} args The arguments used to invoke the server method.\r\n * @returns {Promise} A Promise that resolves when the invocation has been successfully sent, or rejects with an error.\r\n */\r\n public send(methodName: string, ...args: any[]): Promise {\r\n const [streams, streamIds] = this.replaceStreamingParams(args);\r\n const sendPromise = this.sendWithProtocol(this.createInvocation(methodName, args, true, streamIds));\r\n\r\n this.launchStreams(streams, sendPromise);\r\n\r\n return sendPromise;\r\n }\r\n\r\n /** Invokes a hub method on the server using the specified name and arguments.\r\n *\r\n * The Promise returned by this method resolves when the server indicates it has finished invoking the method. When the promise\r\n * resolves, the server has finished invoking the method. If the server method returns a result, it is produced as the result of\r\n * resolving the Promise.\r\n *\r\n * @typeparam T The expected return type.\r\n * @param {string} methodName The name of the server method to invoke.\r\n * @param {any[]} args The arguments used to invoke the server method.\r\n * @returns {Promise} A Promise that resolves with the result of the server method (if any), or rejects with an error.\r\n */\r\n public invoke(methodName: string, ...args: any[]): Promise {\r\n const [streams, streamIds] = this.replaceStreamingParams(args);\r\n const invocationDescriptor = this.createInvocation(methodName, args, false, streamIds);\r\n\r\n const p = new Promise((resolve, reject) => {\r\n // invocationId will always have a value for a non-blocking invocation\r\n this.callbacks[invocationDescriptor.invocationId!] = (invocationEvent: StreamItemMessage | CompletionMessage | null, error?: Error) => {\r\n if (error) {\r\n reject(error);\r\n return;\r\n } else if (invocationEvent) {\r\n // invocationEvent will not be null when an error is not passed to the callback\r\n if (invocationEvent.type === MessageType.Completion) {\r\n if (invocationEvent.error) {\r\n reject(new Error(invocationEvent.error));\r\n } else {\r\n resolve(invocationEvent.result);\r\n }\r\n } else {\r\n reject(new Error(`Unexpected message type: ${invocationEvent.type}`));\r\n }\r\n }\r\n };\r\n\r\n const promiseQueue = this.sendWithProtocol(invocationDescriptor)\r\n .catch((e) => {\r\n reject(e);\r\n // invocationId will always have a value for a non-blocking invocation\r\n delete this.callbacks[invocationDescriptor.invocationId!];\r\n });\r\n\r\n this.launchStreams(streams, promiseQueue);\r\n });\r\n\r\n return p;\r\n }\r\n\r\n /** Registers a handler that will be invoked when the hub method with the specified method name is invoked.\r\n *\r\n * @param {string} methodName The name of the hub method to define.\r\n * @param {Function} newMethod The handler that will be raised when the hub method is invoked.\r\n */\r\n public on(methodName: string, newMethod: (...args: any[]) => void) {\r\n if (!methodName || !newMethod) {\r\n return;\r\n }\r\n\r\n methodName = methodName.toLowerCase();\r\n if (!this.methods[methodName]) {\r\n this.methods[methodName] = [];\r\n }\r\n\r\n // Preventing adding the same handler multiple times.\r\n if (this.methods[methodName].indexOf(newMethod) !== -1) {\r\n return;\r\n }\r\n\r\n this.methods[methodName].push(newMethod);\r\n }\r\n\r\n /** Removes all handlers for the specified hub method.\r\n *\r\n * @param {string} methodName The name of the method to remove handlers for.\r\n */\r\n public off(methodName: string): void;\r\n\r\n /** Removes the specified handler for the specified hub method.\r\n *\r\n * You must pass the exact same Function instance as was previously passed to {@link @microsoft/signalr.HubConnection.on}. Passing a different instance (even if the function\r\n * body is the same) will not remove the handler.\r\n *\r\n * @param {string} methodName The name of the method to remove handlers for.\r\n * @param {Function} method The handler to remove. This must be the same Function instance as the one passed to {@link @microsoft/signalr.HubConnection.on}.\r\n */\r\n public off(methodName: string, method: (...args: any[]) => void): void;\r\n public off(methodName: string, method?: (...args: any[]) => void): void {\r\n if (!methodName) {\r\n return;\r\n }\r\n\r\n methodName = methodName.toLowerCase();\r\n const handlers = this.methods[methodName];\r\n if (!handlers) {\r\n return;\r\n }\r\n if (method) {\r\n const removeIdx = handlers.indexOf(method);\r\n if (removeIdx !== -1) {\r\n handlers.splice(removeIdx, 1);\r\n if (handlers.length === 0) {\r\n delete this.methods[methodName];\r\n }\r\n }\r\n } else {\r\n delete this.methods[methodName];\r\n }\r\n\r\n }\r\n\r\n /** Registers a handler that will be invoked when the connection is closed.\r\n *\r\n * @param {Function} callback The handler that will be invoked when the connection is closed. Optionally receives a single argument containing the error that caused the connection to close (if any).\r\n */\r\n public onclose(callback: (error?: Error) => void) {\r\n if (callback) {\r\n this.closedCallbacks.push(callback);\r\n }\r\n }\r\n\r\n /** Registers a handler that will be invoked when the connection starts reconnecting.\r\n *\r\n * @param {Function} callback The handler that will be invoked when the connection starts reconnecting. Optionally receives a single argument containing the error that caused the connection to start reconnecting (if any).\r\n */\r\n public onreconnecting(callback: (error?: Error) => void) {\r\n if (callback) {\r\n this.reconnectingCallbacks.push(callback);\r\n }\r\n }\r\n\r\n /** Registers a handler that will be invoked when the connection successfully reconnects.\r\n *\r\n * @param {Function} callback The handler that will be invoked when the connection successfully reconnects.\r\n */\r\n public onreconnected(callback: (connectionId?: string) => void) {\r\n if (callback) {\r\n this.reconnectedCallbacks.push(callback);\r\n }\r\n }\r\n\r\n private processIncomingData(data: any) {\r\n this.cleanupTimeout();\r\n\r\n if (!this.receivedHandshakeResponse) {\r\n data = this.processHandshakeResponse(data);\r\n this.receivedHandshakeResponse = true;\r\n }\r\n\r\n // Data may have all been read when processing handshake response\r\n if (data) {\r\n // Parse the messages\r\n const messages = this.protocol.parseMessages(data, this.logger);\r\n\r\n for (const message of messages) {\r\n switch (message.type) {\r\n case MessageType.Invocation:\r\n this.invokeClientMethod(message);\r\n break;\r\n case MessageType.StreamItem:\r\n case MessageType.Completion:\r\n const callback = this.callbacks[message.invocationId];\r\n if (callback) {\r\n if (message.type === MessageType.Completion) {\r\n delete this.callbacks[message.invocationId];\r\n }\r\n callback(message);\r\n }\r\n break;\r\n case MessageType.Ping:\r\n // Don't care about pings\r\n break;\r\n case MessageType.Close:\r\n this.logger.log(LogLevel.Information, \"Close message received from server.\");\r\n\r\n const error = message.error ? new Error(\"Server returned an error on close: \" + message.error) : undefined;\r\n\r\n if (message.allowReconnect === true) {\r\n // It feels wrong not to await connection.stop() here, but processIncomingData is called as part of an onreceive callback which is not async,\r\n // this is already the behavior for serverTimeout(), and HttpConnection.Stop() should catch and log all possible exceptions.\r\n\r\n // tslint:disable-next-line:no-floating-promises\r\n this.connection.stop(error);\r\n } else {\r\n // We cannot await stopInternal() here, but subsequent calls to stop() will await this if stopInternal() is still ongoing.\r\n this.stopPromise = this.stopInternal(error);\r\n }\r\n\r\n break;\r\n default:\r\n this.logger.log(LogLevel.Warning, `Invalid message type: ${message.type}.`);\r\n break;\r\n }\r\n }\r\n }\r\n\r\n this.resetTimeoutPeriod();\r\n }\r\n\r\n private processHandshakeResponse(data: any): any {\r\n let responseMessage: HandshakeResponseMessage;\r\n let remainingData: any;\r\n\r\n try {\r\n [remainingData, responseMessage] = this.handshakeProtocol.parseHandshakeResponse(data);\r\n } catch (e) {\r\n const message = \"Error parsing handshake response: \" + e;\r\n this.logger.log(LogLevel.Error, message);\r\n\r\n const error = new Error(message);\r\n this.handshakeRejecter(error);\r\n throw error;\r\n }\r\n if (responseMessage.error) {\r\n const message = \"Server returned handshake error: \" + responseMessage.error;\r\n this.logger.log(LogLevel.Error, message);\r\n\r\n const error = new Error(message);\r\n this.handshakeRejecter(error);\r\n throw error;\r\n } else {\r\n this.logger.log(LogLevel.Debug, \"Server handshake complete.\");\r\n }\r\n\r\n this.handshakeResolver();\r\n return remainingData;\r\n }\r\n\r\n private resetKeepAliveInterval() {\r\n if (this.connection.features.inherentKeepAlive) {\r\n return;\r\n }\r\n\r\n // Set the time we want the next keep alive to be sent\r\n // Timer will be setup on next message receive\r\n this.nextKeepAlive = new Date().getTime() + this.keepAliveIntervalInMilliseconds;\r\n\r\n this.cleanupPingTimer();\r\n }\r\n\r\n private resetTimeoutPeriod() {\r\n if (!this.connection.features || !this.connection.features.inherentKeepAlive) {\r\n // Set the timeout timer\r\n this.timeoutHandle = setTimeout(() => this.serverTimeout(), this.serverTimeoutInMilliseconds);\r\n\r\n // Set keepAlive timer if there isn't one\r\n if (this.pingServerHandle === undefined) {\r\n let nextPing = this.nextKeepAlive - new Date().getTime();\r\n if (nextPing < 0) {\r\n nextPing = 0;\r\n }\r\n\r\n // The timer needs to be set from a networking callback to avoid Chrome timer throttling from causing timers to run once a minute\r\n this.pingServerHandle = setTimeout(async () => {\r\n if (this.connectionState === HubConnectionState.Connected) {\r\n try {\r\n await this.sendMessage(this.cachedPingMessage);\r\n } catch {\r\n // We don't care about the error. It should be seen elsewhere in the client.\r\n // The connection is probably in a bad or closed state now, cleanup the timer so it stops triggering\r\n this.cleanupPingTimer();\r\n }\r\n }\r\n }, nextPing);\r\n }\r\n }\r\n }\r\n\r\n private serverTimeout() {\r\n // The server hasn't talked to us in a while. It doesn't like us anymore ... :(\r\n // Terminate the connection, but we don't need to wait on the promise. This could trigger reconnecting.\r\n // tslint:disable-next-line:no-floating-promises\r\n this.connection.stop(new Error(\"Server timeout elapsed without receiving a message from the server.\"));\r\n }\r\n\r\n private invokeClientMethod(invocationMessage: InvocationMessage) {\r\n const methods = this.methods[invocationMessage.target.toLowerCase()];\r\n if (methods) {\r\n try {\r\n methods.forEach((m) => m.apply(this, invocationMessage.arguments));\r\n } catch (e) {\r\n this.logger.log(LogLevel.Error, `A callback for the method ${invocationMessage.target.toLowerCase()} threw error '${e}'.`);\r\n }\r\n\r\n if (invocationMessage.invocationId) {\r\n // This is not supported in v1. So we return an error to avoid blocking the server waiting for the response.\r\n const message = \"Server requested a response, which is not supported in this version of the client.\";\r\n this.logger.log(LogLevel.Error, message);\r\n\r\n // We don't want to wait on the stop itself.\r\n this.stopPromise = this.stopInternal(new Error(message));\r\n }\r\n } else {\r\n this.logger.log(LogLevel.Warning, `No client method with the name '${invocationMessage.target}' found.`);\r\n }\r\n }\r\n\r\n private connectionClosed(error?: Error) {\r\n this.logger.log(LogLevel.Debug, `HubConnection.connectionClosed(${error}) called while in state ${this.connectionState}.`);\r\n\r\n // Triggering this.handshakeRejecter is insufficient because it could already be resolved without the continuation having run yet.\r\n this.stopDuringStartError = this.stopDuringStartError || error || new Error(\"The underlying connection was closed before the hub handshake could complete.\");\r\n\r\n // If the handshake is in progress, start will be waiting for the handshake promise, so we complete it.\r\n // If it has already completed, this should just noop.\r\n if (this.handshakeResolver) {\r\n this.handshakeResolver();\r\n }\r\n\r\n this.cancelCallbacksWithError(error || new Error(\"Invocation canceled due to the underlying connection being closed.\"));\r\n\r\n this.cleanupTimeout();\r\n this.cleanupPingTimer();\r\n\r\n if (this.connectionState === HubConnectionState.Disconnecting) {\r\n this.completeClose(error);\r\n } else if (this.connectionState === HubConnectionState.Connected && this.reconnectPolicy) {\r\n // tslint:disable-next-line:no-floating-promises\r\n this.reconnect(error);\r\n } else if (this.connectionState === HubConnectionState.Connected) {\r\n this.completeClose(error);\r\n }\r\n\r\n // If none of the above if conditions were true were called the HubConnection must be in either:\r\n // 1. The Connecting state in which case the handshakeResolver will complete it and stopDuringStartError will fail it.\r\n // 2. The Reconnecting state in which case the handshakeResolver will complete it and stopDuringStartError will fail the current reconnect attempt\r\n // and potentially continue the reconnect() loop.\r\n // 3. The Disconnected state in which case we're already done.\r\n }\r\n\r\n private completeClose(error?: Error) {\r\n if (this.connectionStarted) {\r\n this.connectionState = HubConnectionState.Disconnected;\r\n this.connectionStarted = false;\r\n\r\n try {\r\n this.closedCallbacks.forEach((c) => c.apply(this, [error]));\r\n } catch (e) {\r\n this.logger.log(LogLevel.Error, `An onclose callback called with error '${error}' threw error '${e}'.`);\r\n }\r\n }\r\n }\r\n\r\n private async reconnect(error?: Error) {\r\n const reconnectStartTime = Date.now();\r\n let previousReconnectAttempts = 0;\r\n let retryError = error !== undefined ? error : new Error(\"Attempting to reconnect due to a unknown error.\");\r\n\r\n let nextRetryDelay = this.getNextRetryDelay(previousReconnectAttempts++, 0, retryError);\r\n\r\n if (nextRetryDelay === null) {\r\n this.logger.log(LogLevel.Debug, \"Connection not reconnecting because the IRetryPolicy returned null on the first reconnect attempt.\");\r\n this.completeClose(error);\r\n return;\r\n }\r\n\r\n this.connectionState = HubConnectionState.Reconnecting;\r\n\r\n if (error) {\r\n this.logger.log(LogLevel.Information, `Connection reconnecting because of error '${error}'.`);\r\n } else {\r\n this.logger.log(LogLevel.Information, \"Connection reconnecting.\");\r\n }\r\n\r\n if (this.onreconnecting) {\r\n try {\r\n this.reconnectingCallbacks.forEach((c) => c.apply(this, [error]));\r\n } catch (e) {\r\n this.logger.log(LogLevel.Error, `An onreconnecting callback called with error '${error}' threw error '${e}'.`);\r\n }\r\n\r\n // Exit early if an onreconnecting callback called connection.stop().\r\n if (this.connectionState !== HubConnectionState.Reconnecting) {\r\n this.logger.log(LogLevel.Debug, \"Connection left the reconnecting state in onreconnecting callback. Done reconnecting.\");\r\n return;\r\n }\r\n }\r\n\r\n while (nextRetryDelay !== null) {\r\n this.logger.log(LogLevel.Information, `Reconnect attempt number ${previousReconnectAttempts} will start in ${nextRetryDelay} ms.`);\r\n\r\n await new Promise((resolve) => {\r\n this.reconnectDelayHandle = setTimeout(resolve, nextRetryDelay!);\r\n });\r\n this.reconnectDelayHandle = undefined;\r\n\r\n if (this.connectionState !== HubConnectionState.Reconnecting) {\r\n this.logger.log(LogLevel.Debug, \"Connection left the reconnecting state during reconnect delay. Done reconnecting.\");\r\n return;\r\n }\r\n\r\n try {\r\n await this.startInternal();\r\n\r\n this.connectionState = HubConnectionState.Connected;\r\n this.logger.log(LogLevel.Information, \"HubConnection reconnected successfully.\");\r\n\r\n if (this.onreconnected) {\r\n try {\r\n this.reconnectedCallbacks.forEach((c) => c.apply(this, [this.connection.connectionId]));\r\n } catch (e) {\r\n this.logger.log(LogLevel.Error, `An onreconnected callback called with connectionId '${this.connection.connectionId}; threw error '${e}'.`);\r\n }\r\n }\r\n\r\n return;\r\n } catch (e) {\r\n this.logger.log(LogLevel.Information, `Reconnect attempt failed because of error '${e}'.`);\r\n\r\n if (this.connectionState !== HubConnectionState.Reconnecting) {\r\n this.logger.log(LogLevel.Debug, `Connection moved to the '${this.connectionState}' from the reconnecting state during reconnect attempt. Done reconnecting.`);\r\n // The TypeScript compiler thinks that connectionState must be Connected here. The TypeScript compiler is wrong.\r\n if (this.connectionState as any === HubConnectionState.Disconnecting) {\r\n this.completeClose();\r\n }\r\n return;\r\n }\r\n\r\n retryError = e instanceof Error ? e : new Error(e.toString());\r\n nextRetryDelay = this.getNextRetryDelay(previousReconnectAttempts++, Date.now() - reconnectStartTime, retryError);\r\n }\r\n }\r\n\r\n this.logger.log(LogLevel.Information, `Reconnect retries have been exhausted after ${Date.now() - reconnectStartTime} ms and ${previousReconnectAttempts} failed attempts. Connection disconnecting.`);\r\n\r\n this.completeClose();\r\n }\r\n\r\n private getNextRetryDelay(previousRetryCount: number, elapsedMilliseconds: number, retryReason: Error) {\r\n try {\r\n return this.reconnectPolicy!.nextRetryDelayInMilliseconds({\r\n elapsedMilliseconds,\r\n previousRetryCount,\r\n retryReason,\r\n });\r\n } catch (e) {\r\n this.logger.log(LogLevel.Error, `IRetryPolicy.nextRetryDelayInMilliseconds(${previousRetryCount}, ${elapsedMilliseconds}) threw error '${e}'.`);\r\n return null;\r\n }\r\n }\r\n\r\n private cancelCallbacksWithError(error: Error) {\r\n const callbacks = this.callbacks;\r\n this.callbacks = {};\r\n\r\n Object.keys(callbacks)\r\n .forEach((key) => {\r\n const callback = callbacks[key];\r\n callback(null, error);\r\n });\r\n }\r\n\r\n private cleanupPingTimer(): void {\r\n if (this.pingServerHandle) {\r\n clearTimeout(this.pingServerHandle);\r\n this.pingServerHandle = undefined;\r\n }\r\n }\r\n\r\n private cleanupTimeout(): void {\r\n if (this.timeoutHandle) {\r\n clearTimeout(this.timeoutHandle);\r\n }\r\n }\r\n\r\n private createInvocation(methodName: string, args: any[], nonblocking: boolean, streamIds: string[]): InvocationMessage {\r\n if (nonblocking) {\r\n if (streamIds.length !== 0) {\r\n return {\r\n arguments: args,\r\n streamIds,\r\n target: methodName,\r\n type: MessageType.Invocation,\r\n };\r\n } else {\r\n return {\r\n arguments: args,\r\n target: methodName,\r\n type: MessageType.Invocation,\r\n };\r\n }\r\n } else {\r\n const invocationId = this.invocationId;\r\n this.invocationId++;\r\n\r\n if (streamIds.length !== 0) {\r\n return {\r\n arguments: args,\r\n invocationId: invocationId.toString(),\r\n streamIds,\r\n target: methodName,\r\n type: MessageType.Invocation,\r\n };\r\n } else {\r\n return {\r\n arguments: args,\r\n invocationId: invocationId.toString(),\r\n target: methodName,\r\n type: MessageType.Invocation,\r\n };\r\n }\r\n }\r\n }\r\n\r\n private launchStreams(streams: Array>, promiseQueue: Promise): void {\r\n if (streams.length === 0) {\r\n return;\r\n }\r\n\r\n // Synchronize stream data so they arrive in-order on the server\r\n if (!promiseQueue) {\r\n promiseQueue = Promise.resolve();\r\n }\r\n\r\n // We want to iterate over the keys, since the keys are the stream ids\r\n // tslint:disable-next-line:forin\r\n for (const streamId in streams) {\r\n streams[streamId].subscribe({\r\n complete: () => {\r\n promiseQueue = promiseQueue.then(() => this.sendWithProtocol(this.createCompletionMessage(streamId)));\r\n },\r\n error: (err) => {\r\n let message: string;\r\n if (err instanceof Error) {\r\n message = err.message;\r\n } else if (err && err.toString) {\r\n message = err.toString();\r\n } else {\r\n message = \"Unknown error\";\r\n }\r\n\r\n promiseQueue = promiseQueue.then(() => this.sendWithProtocol(this.createCompletionMessage(streamId, message)));\r\n },\r\n next: (item) => {\r\n promiseQueue = promiseQueue.then(() => this.sendWithProtocol(this.createStreamItemMessage(streamId, item)));\r\n },\r\n });\r\n }\r\n }\r\n\r\n private replaceStreamingParams(args: any[]): [Array>, string[]] {\r\n const streams: Array> = [];\r\n const streamIds: string[] = [];\r\n for (let i = 0; i < args.length; i++) {\r\n const argument = args[i];\r\n if (this.isObservable(argument)) {\r\n const streamId = this.invocationId;\r\n this.invocationId++;\r\n // Store the stream for later use\r\n streams[streamId] = argument;\r\n streamIds.push(streamId.toString());\r\n\r\n // remove stream from args\r\n args.splice(i, 1);\r\n }\r\n }\r\n\r\n return [streams, streamIds];\r\n }\r\n\r\n private isObservable(arg: any): arg is IStreamResult {\r\n // This allows other stream implementations to just work (like rxjs)\r\n return arg && arg.subscribe && typeof arg.subscribe === \"function\";\r\n }\r\n\r\n private createStreamInvocation(methodName: string, args: any[], streamIds: string[]): StreamInvocationMessage {\r\n const invocationId = this.invocationId;\r\n this.invocationId++;\r\n\r\n if (streamIds.length !== 0) {\r\n return {\r\n arguments: args,\r\n invocationId: invocationId.toString(),\r\n streamIds,\r\n target: methodName,\r\n type: MessageType.StreamInvocation,\r\n };\r\n } else {\r\n return {\r\n arguments: args,\r\n invocationId: invocationId.toString(),\r\n target: methodName,\r\n type: MessageType.StreamInvocation,\r\n };\r\n }\r\n }\r\n\r\n private createCancelInvocation(id: string): CancelInvocationMessage {\r\n return {\r\n invocationId: id,\r\n type: MessageType.CancelInvocation,\r\n };\r\n }\r\n\r\n private createStreamItemMessage(id: string, item: any): StreamItemMessage {\r\n return {\r\n invocationId: id,\r\n item,\r\n type: MessageType.StreamItem,\r\n };\r\n }\r\n\r\n private createCompletionMessage(id: string, error?: any, result?: any): CompletionMessage {\r\n if (error) {\r\n return {\r\n error,\r\n invocationId: id,\r\n type: MessageType.Completion,\r\n };\r\n }\r\n\r\n return {\r\n invocationId: id,\r\n result,\r\n type: MessageType.Completion,\r\n };\r\n }\r\n}\r\n","// Copyright (c) .NET Foundation. All rights reserved.\r\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\r\n\r\n// This will be treated as a bit flag in the future, so we keep it using power-of-two values.\r\n/** Specifies a specific HTTP transport type. */\r\nexport enum HttpTransportType {\r\n /** Specifies no transport preference. */\r\n None = 0,\r\n /** Specifies the WebSockets transport. */\r\n WebSockets = 1,\r\n /** Specifies the Server-Sent Events transport. */\r\n ServerSentEvents = 2,\r\n /** Specifies the Long Polling transport. */\r\n LongPolling = 4,\r\n}\r\n\r\n/** Specifies the transfer format for a connection. */\r\nexport enum TransferFormat {\r\n /** Specifies that only text data will be transmitted over the connection. */\r\n Text = 1,\r\n /** Specifies that binary data will be transmitted over the connection. */\r\n Binary = 2,\r\n}\r\n\r\n/** An abstraction over the behavior of transports. This is designed to support the framework and not intended for use by applications. */\r\nexport interface ITransport {\r\n connect(url: string, transferFormat: TransferFormat): Promise;\r\n send(data: any): Promise;\r\n stop(): Promise;\r\n onreceive: ((data: string | ArrayBuffer) => void) | null;\r\n onclose: ((error?: Error) => void) | null;\r\n}\r\n","// Copyright (c) .NET Foundation. All rights reserved.\r\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\r\n\r\nimport { IRetryPolicy, RetryContext } from \"./IRetryPolicy\";\r\n\r\n// 0, 2, 10, 30 second delays before reconnect attempts.\r\nconst DEFAULT_RETRY_DELAYS_IN_MILLISECONDS = [0, 2000, 10000, 30000, null];\r\n\r\n/** @private */\r\nexport class DefaultReconnectPolicy implements IRetryPolicy {\r\n private readonly retryDelays: Array;\r\n\r\n constructor(retryDelays?: number[]) {\r\n this.retryDelays = retryDelays !== undefined ? [...retryDelays, null] : DEFAULT_RETRY_DELAYS_IN_MILLISECONDS;\r\n }\r\n\r\n public nextRetryDelayInMilliseconds(retryContext: RetryContext): number | null {\r\n return this.retryDelays[retryContext.previousRetryCount];\r\n }\r\n}\r\n","// Copyright (c) .NET Foundation. All rights reserved.\r\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\r\n\r\n// Rough polyfill of https://developer.mozilla.org/en-US/docs/Web/API/AbortController\r\n// We don't actually ever use the API being polyfilled, we always use the polyfill because\r\n// it's a very new API right now.\r\n\r\n// Not exported from index.\r\n/** @private */\r\nexport class AbortController implements AbortSignal {\r\n private isAborted: boolean = false;\r\n public onabort: (() => void) | null = null;\r\n\r\n public abort() {\r\n if (!this.isAborted) {\r\n this.isAborted = true;\r\n if (this.onabort) {\r\n this.onabort();\r\n }\r\n }\r\n }\r\n\r\n get signal(): AbortSignal {\r\n return this;\r\n }\r\n\r\n get aborted(): boolean {\r\n return this.isAborted;\r\n }\r\n}\r\n\r\n/** Represents a signal that can be monitored to determine if a request has been aborted. */\r\nexport interface AbortSignal {\r\n /** Indicates if the request has been aborted. */\r\n aborted: boolean;\r\n /** Set this to a handler that will be invoked when the request is aborted. */\r\n onabort: (() => void) | null;\r\n}\r\n","// Copyright (c) .NET Foundation. All rights reserved.\r\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\r\n\r\nimport { AbortController } from \"./AbortController\";\r\nimport { HttpError, TimeoutError } from \"./Errors\";\r\nimport { HttpClient, HttpRequest } from \"./HttpClient\";\r\nimport { MessageHeaders } from \"./IHubProtocol\";\r\nimport { ILogger, LogLevel } from \"./ILogger\";\r\nimport { ITransport, TransferFormat } from \"./ITransport\";\r\nimport { Arg, getDataDetail, getUserAgentHeader, sendMessage } from \"./Utils\";\r\n\r\n// Not exported from 'index', this type is internal.\r\n/** @private */\r\nexport class LongPollingTransport implements ITransport {\r\n private readonly httpClient: HttpClient;\r\n private readonly accessTokenFactory: (() => string | Promise) | undefined;\r\n private readonly logger: ILogger;\r\n private readonly logMessageContent: boolean;\r\n private readonly withCredentials: boolean;\r\n private readonly pollAbort: AbortController;\r\n private readonly headers: MessageHeaders;\r\n\r\n private url?: string;\r\n private running: boolean;\r\n private receiving?: Promise;\r\n private closeError?: Error;\r\n\r\n public onreceive: ((data: string | ArrayBuffer) => void) | null;\r\n public onclose: ((error?: Error) => void) | null;\r\n\r\n // This is an internal type, not exported from 'index' so this is really just internal.\r\n public get pollAborted() {\r\n return this.pollAbort.aborted;\r\n }\r\n\r\n constructor(httpClient: HttpClient, accessTokenFactory: (() => string | Promise) | undefined, logger: ILogger, logMessageContent: boolean, withCredentials: boolean, headers: MessageHeaders) {\r\n this.httpClient = httpClient;\r\n this.accessTokenFactory = accessTokenFactory;\r\n this.logger = logger;\r\n this.pollAbort = new AbortController();\r\n this.logMessageContent = logMessageContent;\r\n this.withCredentials = withCredentials;\r\n this.headers = headers;\r\n\r\n this.running = false;\r\n\r\n this.onreceive = null;\r\n this.onclose = null;\r\n }\r\n\r\n public async connect(url: string, transferFormat: TransferFormat): Promise {\r\n Arg.isRequired(url, \"url\");\r\n Arg.isRequired(transferFormat, \"transferFormat\");\r\n Arg.isIn(transferFormat, TransferFormat, \"transferFormat\");\r\n\r\n this.url = url;\r\n\r\n this.logger.log(LogLevel.Trace, \"(LongPolling transport) Connecting.\");\r\n\r\n // Allow binary format on Node and Browsers that support binary content (indicated by the presence of responseType property)\r\n if (transferFormat === TransferFormat.Binary &&\r\n (typeof XMLHttpRequest !== \"undefined\" && typeof new XMLHttpRequest().responseType !== \"string\")) {\r\n throw new Error(\"Binary protocols over XmlHttpRequest not implementing advanced features are not supported.\");\r\n }\r\n\r\n const [name, value] = getUserAgentHeader();\r\n const headers = { [name]: value, ...this.headers };\r\n\r\n const pollOptions: HttpRequest = {\r\n abortSignal: this.pollAbort.signal,\r\n headers,\r\n timeout: 100000,\r\n withCredentials: this.withCredentials,\r\n };\r\n\r\n if (transferFormat === TransferFormat.Binary) {\r\n pollOptions.responseType = \"arraybuffer\";\r\n }\r\n\r\n const token = await this.getAccessToken();\r\n this.updateHeaderToken(pollOptions, token);\r\n\r\n // Make initial long polling request\r\n // Server uses first long polling request to finish initializing connection and it returns without data\r\n const pollUrl = `${url}&_=${Date.now()}`;\r\n this.logger.log(LogLevel.Trace, `(LongPolling transport) polling: ${pollUrl}.`);\r\n const response = await this.httpClient.get(pollUrl, pollOptions);\r\n if (response.statusCode !== 200) {\r\n this.logger.log(LogLevel.Error, `(LongPolling transport) Unexpected response code: ${response.statusCode}.`);\r\n\r\n // Mark running as false so that the poll immediately ends and runs the close logic\r\n this.closeError = new HttpError(response.statusText || \"\", response.statusCode);\r\n this.running = false;\r\n } else {\r\n this.running = true;\r\n }\r\n\r\n this.receiving = this.poll(this.url, pollOptions);\r\n }\r\n\r\n private async getAccessToken(): Promise {\r\n if (this.accessTokenFactory) {\r\n return await this.accessTokenFactory();\r\n }\r\n\r\n return null;\r\n }\r\n\r\n private updateHeaderToken(request: HttpRequest, token: string | null) {\r\n if (!request.headers) {\r\n request.headers = {};\r\n }\r\n if (token) {\r\n // tslint:disable-next-line:no-string-literal\r\n request.headers[\"Authorization\"] = `Bearer ${token}`;\r\n return;\r\n }\r\n // tslint:disable-next-line:no-string-literal\r\n if (request.headers[\"Authorization\"]) {\r\n // tslint:disable-next-line:no-string-literal\r\n delete request.headers[\"Authorization\"];\r\n }\r\n }\r\n\r\n private async poll(url: string, pollOptions: HttpRequest): Promise {\r\n try {\r\n while (this.running) {\r\n // We have to get the access token on each poll, in case it changes\r\n const token = await this.getAccessToken();\r\n this.updateHeaderToken(pollOptions, token);\r\n\r\n try {\r\n const pollUrl = `${url}&_=${Date.now()}`;\r\n this.logger.log(LogLevel.Trace, `(LongPolling transport) polling: ${pollUrl}.`);\r\n const response = await this.httpClient.get(pollUrl, pollOptions);\r\n\r\n if (response.statusCode === 204) {\r\n this.logger.log(LogLevel.Information, \"(LongPolling transport) Poll terminated by server.\");\r\n\r\n this.running = false;\r\n } else if (response.statusCode !== 200) {\r\n this.logger.log(LogLevel.Error, `(LongPolling transport) Unexpected response code: ${response.statusCode}.`);\r\n\r\n // Unexpected status code\r\n this.closeError = new HttpError(response.statusText || \"\", response.statusCode);\r\n this.running = false;\r\n } else {\r\n // Process the response\r\n if (response.content) {\r\n this.logger.log(LogLevel.Trace, `(LongPolling transport) data received. ${getDataDetail(response.content, this.logMessageContent)}.`);\r\n if (this.onreceive) {\r\n this.onreceive(response.content);\r\n }\r\n } else {\r\n // This is another way timeout manifest.\r\n this.logger.log(LogLevel.Trace, \"(LongPolling transport) Poll timed out, reissuing.\");\r\n }\r\n }\r\n } catch (e) {\r\n if (!this.running) {\r\n // Log but disregard errors that occur after stopping\r\n this.logger.log(LogLevel.Trace, `(LongPolling transport) Poll errored after shutdown: ${e.message}`);\r\n } else {\r\n if (e instanceof TimeoutError) {\r\n // Ignore timeouts and reissue the poll.\r\n this.logger.log(LogLevel.Trace, \"(LongPolling transport) Poll timed out, reissuing.\");\r\n } else {\r\n // Close the connection with the error as the result.\r\n this.closeError = e;\r\n this.running = false;\r\n }\r\n }\r\n }\r\n }\r\n } finally {\r\n this.logger.log(LogLevel.Trace, \"(LongPolling transport) Polling complete.\");\r\n\r\n // We will reach here with pollAborted==false when the server returned a response causing the transport to stop.\r\n // If pollAborted==true then client initiated the stop and the stop method will raise the close event after DELETE is sent.\r\n if (!this.pollAborted) {\r\n this.raiseOnClose();\r\n }\r\n }\r\n }\r\n\r\n public async send(data: any): Promise {\r\n if (!this.running) {\r\n return Promise.reject(new Error(\"Cannot send until the transport is connected\"));\r\n }\r\n return sendMessage(this.logger, \"LongPolling\", this.httpClient, this.url!, this.accessTokenFactory, data, this.logMessageContent, this.withCredentials, this.headers);\r\n }\r\n\r\n public async stop(): Promise {\r\n this.logger.log(LogLevel.Trace, \"(LongPolling transport) Stopping polling.\");\r\n\r\n // Tell receiving loop to stop, abort any current request, and then wait for it to finish\r\n this.running = false;\r\n this.pollAbort.abort();\r\n\r\n try {\r\n await this.receiving;\r\n\r\n // Send DELETE to clean up long polling on the server\r\n this.logger.log(LogLevel.Trace, `(LongPolling transport) sending DELETE request to ${this.url}.`);\r\n\r\n const headers = {};\r\n const [name, value] = getUserAgentHeader();\r\n headers[name] = value;\r\n\r\n const deleteOptions: HttpRequest = {\r\n headers: { ...headers, ...this.headers },\r\n withCredentials: this.withCredentials,\r\n };\r\n const token = await this.getAccessToken();\r\n this.updateHeaderToken(deleteOptions, token);\r\n await this.httpClient.delete(this.url!, deleteOptions);\r\n\r\n this.logger.log(LogLevel.Trace, \"(LongPolling transport) DELETE request sent.\");\r\n } finally {\r\n this.logger.log(LogLevel.Trace, \"(LongPolling transport) Stop finished.\");\r\n\r\n // Raise close event here instead of in polling\r\n // It needs to happen after the DELETE request is sent\r\n this.raiseOnClose();\r\n }\r\n }\r\n\r\n private raiseOnClose() {\r\n if (this.onclose) {\r\n let logMessage = \"(LongPolling transport) Firing onclose event.\";\r\n if (this.closeError) {\r\n logMessage += \" Error: \" + this.closeError;\r\n }\r\n this.logger.log(LogLevel.Trace, logMessage);\r\n this.onclose(this.closeError);\r\n }\r\n }\r\n}\r\n","// Copyright (c) .NET Foundation. All rights reserved.\r\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\r\n\r\nimport { HttpClient } from \"./HttpClient\";\r\nimport { MessageHeaders } from \"./IHubProtocol\";\r\nimport { ILogger, LogLevel } from \"./ILogger\";\r\nimport { ITransport, TransferFormat } from \"./ITransport\";\r\nimport { EventSourceConstructor } from \"./Polyfills\";\r\nimport { Arg, getDataDetail, getUserAgentHeader, Platform, sendMessage } from \"./Utils\";\r\n\r\n/** @private */\r\nexport class ServerSentEventsTransport implements ITransport {\r\n private readonly httpClient: HttpClient;\r\n private readonly accessTokenFactory: (() => string | Promise) | undefined;\r\n private readonly logger: ILogger;\r\n private readonly logMessageContent: boolean;\r\n private readonly withCredentials: boolean;\r\n private readonly eventSourceConstructor: EventSourceConstructor;\r\n private eventSource?: EventSource;\r\n private url?: string;\r\n private headers: MessageHeaders;\r\n\r\n public onreceive: ((data: string | ArrayBuffer) => void) | null;\r\n public onclose: ((error?: Error) => void) | null;\r\n\r\n constructor(httpClient: HttpClient, accessTokenFactory: (() => string | Promise) | undefined, logger: ILogger,\r\n logMessageContent: boolean, eventSourceConstructor: EventSourceConstructor, withCredentials: boolean, headers: MessageHeaders) {\r\n this.httpClient = httpClient;\r\n this.accessTokenFactory = accessTokenFactory;\r\n this.logger = logger;\r\n this.logMessageContent = logMessageContent;\r\n this.withCredentials = withCredentials;\r\n this.eventSourceConstructor = eventSourceConstructor;\r\n this.headers = headers;\r\n\r\n this.onreceive = null;\r\n this.onclose = null;\r\n }\r\n\r\n public async connect(url: string, transferFormat: TransferFormat): Promise {\r\n Arg.isRequired(url, \"url\");\r\n Arg.isRequired(transferFormat, \"transferFormat\");\r\n Arg.isIn(transferFormat, TransferFormat, \"transferFormat\");\r\n\r\n this.logger.log(LogLevel.Trace, \"(SSE transport) Connecting.\");\r\n\r\n // set url before accessTokenFactory because this.url is only for send and we set the auth header instead of the query string for send\r\n this.url = url;\r\n\r\n if (this.accessTokenFactory) {\r\n const token = await this.accessTokenFactory();\r\n if (token) {\r\n url += (url.indexOf(\"?\") < 0 ? \"?\" : \"&\") + `access_token=${encodeURIComponent(token)}`;\r\n }\r\n }\r\n\r\n return new Promise((resolve, reject) => {\r\n let opened = false;\r\n if (transferFormat !== TransferFormat.Text) {\r\n reject(new Error(\"The Server-Sent Events transport only supports the 'Text' transfer format\"));\r\n return;\r\n }\r\n\r\n let eventSource: EventSource;\r\n if (Platform.isBrowser || Platform.isWebWorker) {\r\n eventSource = new this.eventSourceConstructor(url, { withCredentials: this.withCredentials });\r\n } else {\r\n // Non-browser passes cookies via the dictionary\r\n const cookies = this.httpClient.getCookieString(url);\r\n const headers: MessageHeaders = {};\r\n headers.Cookie = cookies;\r\n const [name, value] = getUserAgentHeader();\r\n headers[name] = value;\r\n\r\n eventSource = new this.eventSourceConstructor(url, { withCredentials: this.withCredentials, headers: { ...headers, ...this.headers} } as EventSourceInit);\r\n }\r\n\r\n try {\r\n eventSource.onmessage = (e: MessageEvent) => {\r\n if (this.onreceive) {\r\n try {\r\n this.logger.log(LogLevel.Trace, `(SSE transport) data received. ${getDataDetail(e.data, this.logMessageContent)}.`);\r\n this.onreceive(e.data);\r\n } catch (error) {\r\n this.close(error);\r\n return;\r\n }\r\n }\r\n };\r\n\r\n eventSource.onerror = (e: MessageEvent) => {\r\n const error = new Error(e.data || \"Error occurred\");\r\n if (opened) {\r\n this.close(error);\r\n } else {\r\n reject(error);\r\n }\r\n };\r\n\r\n eventSource.onopen = () => {\r\n this.logger.log(LogLevel.Information, `SSE connected to ${this.url}`);\r\n this.eventSource = eventSource;\r\n opened = true;\r\n resolve();\r\n };\r\n } catch (e) {\r\n reject(e);\r\n return;\r\n }\r\n });\r\n }\r\n\r\n public async send(data: any): Promise {\r\n if (!this.eventSource) {\r\n return Promise.reject(new Error(\"Cannot send until the transport is connected\"));\r\n }\r\n return sendMessage(this.logger, \"SSE\", this.httpClient, this.url!, this.accessTokenFactory, data, this.logMessageContent, this.withCredentials, this.headers);\r\n }\r\n\r\n public stop(): Promise {\r\n this.close();\r\n return Promise.resolve();\r\n }\r\n\r\n private close(e?: Error) {\r\n if (this.eventSource) {\r\n this.eventSource.close();\r\n this.eventSource = undefined;\r\n\r\n if (this.onclose) {\r\n this.onclose(e);\r\n }\r\n }\r\n }\r\n}\r\n","// Copyright (c) .NET Foundation. All rights reserved.\r\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\r\n\r\nimport { HttpClient } from \"./HttpClient\";\r\nimport { MessageHeaders } from \"./IHubProtocol\";\r\nimport { ILogger, LogLevel } from \"./ILogger\";\r\nimport { ITransport, TransferFormat } from \"./ITransport\";\r\nimport { WebSocketConstructor } from \"./Polyfills\";\r\nimport { Arg, getDataDetail, getUserAgentHeader, Platform } from \"./Utils\";\r\n\r\n/** @private */\r\nexport class WebSocketTransport implements ITransport {\r\n private readonly logger: ILogger;\r\n private readonly accessTokenFactory: (() => string | Promise) | undefined;\r\n private readonly logMessageContent: boolean;\r\n private readonly webSocketConstructor: WebSocketConstructor;\r\n private readonly httpClient: HttpClient;\r\n private webSocket?: WebSocket;\r\n private headers: MessageHeaders;\r\n\r\n public onreceive: ((data: string | ArrayBuffer) => void) | null;\r\n public onclose: ((error?: Error) => void) | null;\r\n\r\n constructor(httpClient: HttpClient, accessTokenFactory: (() => string | Promise) | undefined, logger: ILogger,\r\n logMessageContent: boolean, webSocketConstructor: WebSocketConstructor, headers: MessageHeaders) {\r\n this.logger = logger;\r\n this.accessTokenFactory = accessTokenFactory;\r\n this.logMessageContent = logMessageContent;\r\n this.webSocketConstructor = webSocketConstructor;\r\n this.httpClient = httpClient;\r\n\r\n this.onreceive = null;\r\n this.onclose = null;\r\n this.headers = headers;\r\n }\r\n\r\n public async connect(url: string, transferFormat: TransferFormat): Promise {\r\n Arg.isRequired(url, \"url\");\r\n Arg.isRequired(transferFormat, \"transferFormat\");\r\n Arg.isIn(transferFormat, TransferFormat, \"transferFormat\");\r\n this.logger.log(LogLevel.Trace, \"(WebSockets transport) Connecting.\");\r\n\r\n if (this.accessTokenFactory) {\r\n const token = await this.accessTokenFactory();\r\n if (token) {\r\n url += (url.indexOf(\"?\") < 0 ? \"?\" : \"&\") + `access_token=${encodeURIComponent(token)}`;\r\n }\r\n }\r\n\r\n return new Promise((resolve, reject) => {\r\n url = url.replace(/^http/, \"ws\");\r\n let webSocket: WebSocket | undefined;\r\n const cookies = this.httpClient.getCookieString(url);\r\n let opened = false;\r\n\r\n if (Platform.isNode) {\r\n const headers = {};\r\n const [name, value] = getUserAgentHeader();\r\n headers[name] = value;\r\n\r\n if (cookies) {\r\n headers[`Cookie`] = `${cookies}`;\r\n }\r\n\r\n // Only pass headers when in non-browser environments\r\n webSocket = new this.webSocketConstructor(url, undefined, {\r\n headers: { ...headers, ...this.headers },\r\n });\r\n }\r\n\r\n if (!webSocket) {\r\n // Chrome is not happy with passing 'undefined' as protocol\r\n webSocket = new this.webSocketConstructor(url);\r\n }\r\n\r\n if (transferFormat === TransferFormat.Binary) {\r\n webSocket.binaryType = \"arraybuffer\";\r\n }\r\n\r\n // tslint:disable-next-line:variable-name\r\n webSocket.onopen = (_event: Event) => {\r\n this.logger.log(LogLevel.Information, `WebSocket connected to ${url}.`);\r\n this.webSocket = webSocket;\r\n opened = true;\r\n resolve();\r\n };\r\n\r\n webSocket.onerror = (event: Event) => {\r\n let error: any = null;\r\n // ErrorEvent is a browser only type we need to check if the type exists before using it\r\n if (typeof ErrorEvent !== \"undefined\" && event instanceof ErrorEvent) {\r\n error = event.error;\r\n } else {\r\n error = new Error(\"There was an error with the transport.\");\r\n }\r\n\r\n reject(error);\r\n };\r\n\r\n webSocket.onmessage = (message: MessageEvent) => {\r\n this.logger.log(LogLevel.Trace, `(WebSockets transport) data received. ${getDataDetail(message.data, this.logMessageContent)}.`);\r\n if (this.onreceive) {\r\n try {\r\n this.onreceive(message.data);\r\n } catch (error) {\r\n this.close(error);\r\n return;\r\n }\r\n }\r\n };\r\n\r\n webSocket.onclose = (event: CloseEvent) => {\r\n // Don't call close handler if connection was never established\r\n // We'll reject the connect call instead\r\n if (opened) {\r\n this.close(event);\r\n } else {\r\n let error: any = null;\r\n // ErrorEvent is a browser only type we need to check if the type exists before using it\r\n if (typeof ErrorEvent !== \"undefined\" && event instanceof ErrorEvent) {\r\n error = event.error;\r\n } else {\r\n error = new Error(\"There was an error with the transport.\");\r\n }\r\n\r\n reject(error);\r\n }\r\n };\r\n });\r\n }\r\n\r\n public send(data: any): Promise {\r\n if (this.webSocket && this.webSocket.readyState === this.webSocketConstructor.OPEN) {\r\n this.logger.log(LogLevel.Trace, `(WebSockets transport) sending data. ${getDataDetail(data, this.logMessageContent)}.`);\r\n this.webSocket.send(data);\r\n return Promise.resolve();\r\n }\r\n\r\n return Promise.reject(\"WebSocket is not in the OPEN state\");\r\n }\r\n\r\n public stop(): Promise {\r\n if (this.webSocket) {\r\n // Manually invoke onclose callback inline so we know the HttpConnection was closed properly before returning\r\n // This also solves an issue where websocket.onclose could take 18+ seconds to trigger during network disconnects\r\n this.close(undefined);\r\n }\r\n\r\n return Promise.resolve();\r\n }\r\n\r\n private close(event?: CloseEvent | Error): void {\r\n // webSocket will be null if the transport did not start successfully\r\n if (this.webSocket) {\r\n // Clear websocket handlers because we are considering the socket closed now\r\n this.webSocket.onclose = () => {};\r\n this.webSocket.onmessage = () => {};\r\n this.webSocket.onerror = () => {};\r\n this.webSocket.close();\r\n this.webSocket = undefined;\r\n }\r\n\r\n this.logger.log(LogLevel.Trace, \"(WebSockets transport) socket closed.\");\r\n if (this.onclose) {\r\n if (this.isCloseEvent(event) && (event.wasClean === false || event.code !== 1000)) {\r\n this.onclose(new Error(`WebSocket closed with status code: ${event.code} (${event.reason}).`));\r\n } else if (event instanceof Error) {\r\n this.onclose(event);\r\n } else {\r\n this.onclose();\r\n }\r\n }\r\n }\r\n\r\n private isCloseEvent(event?: any): event is CloseEvent {\r\n return event && typeof event.wasClean === \"boolean\" && typeof event.code === \"number\";\r\n }\r\n}\r\n","// Copyright (c) .NET Foundation. All rights reserved.\r\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\r\n\r\nimport { DefaultHttpClient } from \"./DefaultHttpClient\";\r\nimport { HttpClient } from \"./HttpClient\";\r\nimport { IConnection } from \"./IConnection\";\r\nimport { IHttpConnectionOptions } from \"./IHttpConnectionOptions\";\r\nimport { ILogger, LogLevel } from \"./ILogger\";\r\nimport { HttpTransportType, ITransport, TransferFormat } from \"./ITransport\";\r\nimport { LongPollingTransport } from \"./LongPollingTransport\";\r\nimport { ServerSentEventsTransport } from \"./ServerSentEventsTransport\";\r\nimport { Arg, createLogger, getUserAgentHeader, Platform } from \"./Utils\";\r\nimport { WebSocketTransport } from \"./WebSocketTransport\";\r\n\r\n/** @private */\r\nconst enum ConnectionState {\r\n Connecting = \"Connecting\",\r\n Connected = \"Connected\",\r\n Disconnected = \"Disconnected\",\r\n Disconnecting = \"Disconnecting\",\r\n}\r\n\r\n/** @private */\r\nexport interface INegotiateResponse {\r\n connectionId?: string;\r\n connectionToken?: string;\r\n negotiateVersion?: number;\r\n availableTransports?: IAvailableTransport[];\r\n url?: string;\r\n accessToken?: string;\r\n error?: string;\r\n}\r\n\r\n/** @private */\r\nexport interface IAvailableTransport {\r\n transport: keyof typeof HttpTransportType;\r\n transferFormats: Array;\r\n}\r\n\r\nconst MAX_REDIRECTS = 100;\r\n\r\n/** @private */\r\nexport class HttpConnection implements IConnection {\r\n private connectionState: ConnectionState;\r\n // connectionStarted is tracked independently from connectionState, so we can check if the\r\n // connection ever did successfully transition from connecting to connected before disconnecting.\r\n private connectionStarted: boolean;\r\n private readonly httpClient: HttpClient;\r\n private readonly logger: ILogger;\r\n private readonly options: IHttpConnectionOptions;\r\n private transport?: ITransport;\r\n private startInternalPromise?: Promise;\r\n private stopPromise?: Promise;\r\n private stopPromiseResolver: (value?: PromiseLike) => void = () => {};\r\n private stopError?: Error;\r\n private accessTokenFactory?: () => string | Promise;\r\n private sendQueue?: TransportSendQueue;\r\n\r\n public readonly features: any = {};\r\n public baseUrl: string;\r\n public connectionId?: string;\r\n public onreceive: ((data: string | ArrayBuffer) => void) | null;\r\n public onclose: ((e?: Error) => void) | null;\r\n\r\n private readonly negotiateVersion: number = 1;\r\n\r\n constructor(url: string, options: IHttpConnectionOptions = {}) {\r\n Arg.isRequired(url, \"url\");\r\n\r\n this.logger = createLogger(options.logger);\r\n this.baseUrl = this.resolveUrl(url);\r\n\r\n options = options || {};\r\n options.logMessageContent = options.logMessageContent === undefined ? false : options.logMessageContent;\r\n if (typeof options.withCredentials === \"boolean\" || options.withCredentials === undefined) {\r\n options.withCredentials = options.withCredentials === undefined ? true : options.withCredentials;\r\n } else {\r\n throw new Error(\"withCredentials option was not a 'boolean' or 'undefined' value\");\r\n }\r\n\r\n let webSocketModule: any = null;\r\n let eventSourceModule: any = null;\r\n\r\n if (Platform.isNode && typeof require !== \"undefined\") {\r\n // In order to ignore the dynamic require in webpack builds we need to do this magic\r\n // @ts-ignore: TS doesn't know about these names\r\n const requireFunc = typeof __webpack_require__ === \"function\" ? __non_webpack_require__ : require;\r\n webSocketModule = requireFunc(\"ws\");\r\n eventSourceModule = requireFunc(\"eventsource\");\r\n }\r\n\r\n if (!Platform.isNode && typeof WebSocket !== \"undefined\" && !options.WebSocket) {\r\n options.WebSocket = WebSocket;\r\n } else if (Platform.isNode && !options.WebSocket) {\r\n if (webSocketModule) {\r\n options.WebSocket = webSocketModule;\r\n }\r\n }\r\n\r\n if (!Platform.isNode && typeof EventSource !== \"undefined\" && !options.EventSource) {\r\n options.EventSource = EventSource;\r\n } else if (Platform.isNode && !options.EventSource) {\r\n if (typeof eventSourceModule !== \"undefined\") {\r\n options.EventSource = eventSourceModule;\r\n }\r\n }\r\n\r\n this.httpClient = options.httpClient || new DefaultHttpClient(this.logger);\r\n this.connectionState = ConnectionState.Disconnected;\r\n this.connectionStarted = false;\r\n this.options = options;\r\n\r\n this.onreceive = null;\r\n this.onclose = null;\r\n }\r\n\r\n public start(): Promise;\r\n public start(transferFormat: TransferFormat): Promise;\r\n public async start(transferFormat?: TransferFormat): Promise {\r\n transferFormat = transferFormat || TransferFormat.Binary;\r\n\r\n Arg.isIn(transferFormat, TransferFormat, \"transferFormat\");\r\n\r\n this.logger.log(LogLevel.Debug, `Starting connection with transfer format '${TransferFormat[transferFormat]}'.`);\r\n\r\n if (this.connectionState !== ConnectionState.Disconnected) {\r\n return Promise.reject(new Error(\"Cannot start an HttpConnection that is not in the 'Disconnected' state.\"));\r\n }\r\n\r\n this.connectionState = ConnectionState.Connecting;\r\n\r\n this.startInternalPromise = this.startInternal(transferFormat);\r\n await this.startInternalPromise;\r\n\r\n // The TypeScript compiler thinks that connectionState must be Connecting here. The TypeScript compiler is wrong.\r\n if (this.connectionState as any === ConnectionState.Disconnecting) {\r\n // stop() was called and transitioned the client into the Disconnecting state.\r\n const message = \"Failed to start the HttpConnection before stop() was called.\";\r\n this.logger.log(LogLevel.Error, message);\r\n\r\n // We cannot await stopPromise inside startInternal since stopInternal awaits the startInternalPromise.\r\n await this.stopPromise;\r\n\r\n return Promise.reject(new Error(message));\r\n } else if (this.connectionState as any !== ConnectionState.Connected) {\r\n // stop() was called and transitioned the client into the Disconnecting state.\r\n const message = \"HttpConnection.startInternal completed gracefully but didn't enter the connection into the connected state!\";\r\n this.logger.log(LogLevel.Error, message);\r\n return Promise.reject(new Error(message));\r\n }\r\n\r\n this.connectionStarted = true;\r\n }\r\n\r\n public send(data: string | ArrayBuffer): Promise {\r\n if (this.connectionState !== ConnectionState.Connected) {\r\n return Promise.reject(new Error(\"Cannot send data if the connection is not in the 'Connected' State.\"));\r\n }\r\n\r\n if (!this.sendQueue) {\r\n this.sendQueue = new TransportSendQueue(this.transport!);\r\n }\r\n\r\n // Transport will not be null if state is connected\r\n return this.sendQueue.send(data);\r\n }\r\n\r\n public async stop(error?: Error): Promise {\r\n if (this.connectionState === ConnectionState.Disconnected) {\r\n this.logger.log(LogLevel.Debug, `Call to HttpConnection.stop(${error}) ignored because the connection is already in the disconnected state.`);\r\n return Promise.resolve();\r\n }\r\n\r\n if (this.connectionState === ConnectionState.Disconnecting) {\r\n this.logger.log(LogLevel.Debug, `Call to HttpConnection.stop(${error}) ignored because the connection is already in the disconnecting state.`);\r\n return this.stopPromise;\r\n }\r\n\r\n this.connectionState = ConnectionState.Disconnecting;\r\n\r\n this.stopPromise = new Promise((resolve) => {\r\n // Don't complete stop() until stopConnection() completes.\r\n this.stopPromiseResolver = resolve;\r\n });\r\n\r\n // stopInternal should never throw so just observe it.\r\n await this.stopInternal(error);\r\n await this.stopPromise;\r\n }\r\n\r\n private async stopInternal(error?: Error): Promise {\r\n // Set error as soon as possible otherwise there is a race between\r\n // the transport closing and providing an error and the error from a close message\r\n // We would prefer the close message error.\r\n this.stopError = error;\r\n\r\n try {\r\n await this.startInternalPromise;\r\n } catch (e) {\r\n // This exception is returned to the user as a rejected Promise from the start method.\r\n }\r\n\r\n // The transport's onclose will trigger stopConnection which will run our onclose event.\r\n // The transport should always be set if currently connected. If it wasn't set, it's likely because\r\n // stop was called during start() and start() failed.\r\n if (this.transport) {\r\n try {\r\n await this.transport.stop();\r\n } catch (e) {\r\n this.logger.log(LogLevel.Error, `HttpConnection.transport.stop() threw error '${e}'.`);\r\n this.stopConnection();\r\n }\r\n\r\n this.transport = undefined;\r\n } else {\r\n this.logger.log(LogLevel.Debug, \"HttpConnection.transport is undefined in HttpConnection.stop() because start() failed.\");\r\n }\r\n }\r\n\r\n private async startInternal(transferFormat: TransferFormat): Promise {\r\n // Store the original base url and the access token factory since they may change\r\n // as part of negotiating\r\n let url = this.baseUrl;\r\n this.accessTokenFactory = this.options.accessTokenFactory;\r\n\r\n try {\r\n if (this.options.skipNegotiation) {\r\n if (this.options.transport === HttpTransportType.WebSockets) {\r\n // No need to add a connection ID in this case\r\n this.transport = this.constructTransport(HttpTransportType.WebSockets);\r\n // We should just call connect directly in this case.\r\n // No fallback or negotiate in this case.\r\n await this.startTransport(url, transferFormat);\r\n } else {\r\n throw new Error(\"Negotiation can only be skipped when using the WebSocket transport directly.\");\r\n }\r\n } else {\r\n let negotiateResponse: INegotiateResponse | null = null;\r\n let redirects = 0;\r\n\r\n do {\r\n negotiateResponse = await this.getNegotiationResponse(url);\r\n // the user tries to stop the connection when it is being started\r\n if (this.connectionState === ConnectionState.Disconnecting || this.connectionState === ConnectionState.Disconnected) {\r\n throw new Error(\"The connection was stopped during negotiation.\");\r\n }\r\n\r\n if (negotiateResponse.error) {\r\n throw new Error(negotiateResponse.error);\r\n }\r\n\r\n if ((negotiateResponse as any).ProtocolVersion) {\r\n 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.\");\r\n }\r\n\r\n if (negotiateResponse.url) {\r\n url = negotiateResponse.url;\r\n }\r\n\r\n if (negotiateResponse.accessToken) {\r\n // Replace the current access token factory with one that uses\r\n // the returned access token\r\n const accessToken = negotiateResponse.accessToken;\r\n this.accessTokenFactory = () => accessToken;\r\n }\r\n\r\n redirects++;\r\n }\r\n while (negotiateResponse.url && redirects < MAX_REDIRECTS);\r\n\r\n if (redirects === MAX_REDIRECTS && negotiateResponse.url) {\r\n throw new Error(\"Negotiate redirection limit exceeded.\");\r\n }\r\n\r\n await this.createTransport(url, this.options.transport, negotiateResponse, transferFormat);\r\n }\r\n\r\n if (this.transport instanceof LongPollingTransport) {\r\n this.features.inherentKeepAlive = true;\r\n }\r\n\r\n if (this.connectionState === ConnectionState.Connecting) {\r\n // Ensure the connection transitions to the connected state prior to completing this.startInternalPromise.\r\n // start() will handle the case when stop was called and startInternal exits still in the disconnecting state.\r\n this.logger.log(LogLevel.Debug, \"The HttpConnection connected successfully.\");\r\n this.connectionState = ConnectionState.Connected;\r\n }\r\n\r\n // stop() is waiting on us via this.startInternalPromise so keep this.transport around so it can clean up.\r\n // This is the only case startInternal can exit in neither the connected nor disconnected state because stopConnection()\r\n // will transition to the disconnected state. start() will wait for the transition using the stopPromise.\r\n } catch (e) {\r\n this.logger.log(LogLevel.Error, \"Failed to start the connection: \" + e);\r\n this.connectionState = ConnectionState.Disconnected;\r\n this.transport = undefined;\r\n\r\n // if start fails, any active calls to stop assume that start will complete the stop promise\r\n this.stopPromiseResolver();\r\n return Promise.reject(e);\r\n }\r\n }\r\n\r\n private async getNegotiationResponse(url: string): Promise {\r\n const headers = {};\r\n if (this.accessTokenFactory) {\r\n const token = await this.accessTokenFactory();\r\n if (token) {\r\n headers[`Authorization`] = `Bearer ${token}`;\r\n }\r\n }\r\n\r\n const [name, value] = getUserAgentHeader();\r\n headers[name] = value;\r\n\r\n const negotiateUrl = this.resolveNegotiateUrl(url);\r\n this.logger.log(LogLevel.Debug, `Sending negotiation request: ${negotiateUrl}.`);\r\n try {\r\n const response = await this.httpClient.post(negotiateUrl, {\r\n content: \"\",\r\n headers: { ...headers, ...this.options.headers },\r\n withCredentials: this.options.withCredentials,\r\n });\r\n\r\n if (response.statusCode !== 200) {\r\n return Promise.reject(new Error(`Unexpected status code returned from negotiate '${response.statusCode}'`));\r\n }\r\n\r\n const negotiateResponse = JSON.parse(response.content as string) as INegotiateResponse;\r\n if (!negotiateResponse.negotiateVersion || negotiateResponse.negotiateVersion < 1) {\r\n // Negotiate version 0 doesn't use connectionToken\r\n // So we set it equal to connectionId so all our logic can use connectionToken without being aware of the negotiate version\r\n negotiateResponse.connectionToken = negotiateResponse.connectionId;\r\n }\r\n return negotiateResponse;\r\n } catch (e) {\r\n this.logger.log(LogLevel.Error, \"Failed to complete negotiation with the server: \" + e);\r\n return Promise.reject(e);\r\n }\r\n }\r\n\r\n private createConnectUrl(url: string, connectionToken: string | null | undefined) {\r\n if (!connectionToken) {\r\n return url;\r\n }\r\n\r\n return url + (url.indexOf(\"?\") === -1 ? \"?\" : \"&\") + `id=${connectionToken}`;\r\n }\r\n\r\n private async createTransport(url: string, requestedTransport: HttpTransportType | ITransport | undefined, negotiateResponse: INegotiateResponse, requestedTransferFormat: TransferFormat): Promise {\r\n let connectUrl = this.createConnectUrl(url, negotiateResponse.connectionToken);\r\n if (this.isITransport(requestedTransport)) {\r\n this.logger.log(LogLevel.Debug, \"Connection was provided an instance of ITransport, using that directly.\");\r\n this.transport = requestedTransport;\r\n await this.startTransport(connectUrl, requestedTransferFormat);\r\n\r\n this.connectionId = negotiateResponse.connectionId;\r\n return;\r\n }\r\n\r\n const transportExceptions: any[] = [];\r\n const transports = negotiateResponse.availableTransports || [];\r\n let negotiate: INegotiateResponse | undefined = negotiateResponse;\r\n for (const endpoint of transports) {\r\n const transportOrError = this.resolveTransportOrError(endpoint, requestedTransport, requestedTransferFormat);\r\n if (transportOrError instanceof Error) {\r\n // Store the error and continue, we don't want to cause a re-negotiate in these cases\r\n transportExceptions.push(`${endpoint.transport} failed: ${transportOrError}`);\r\n } else if (this.isITransport(transportOrError)) {\r\n this.transport = transportOrError;\r\n if (!negotiate) {\r\n try {\r\n negotiate = await this.getNegotiationResponse(url);\r\n } catch (ex) {\r\n return Promise.reject(ex);\r\n }\r\n connectUrl = this.createConnectUrl(url, negotiate.connectionToken);\r\n }\r\n try {\r\n await this.startTransport(connectUrl, requestedTransferFormat);\r\n this.connectionId = negotiate.connectionId;\r\n return;\r\n } catch (ex) {\r\n this.logger.log(LogLevel.Error, `Failed to start the transport '${endpoint.transport}': ${ex}`);\r\n negotiate = undefined;\r\n transportExceptions.push(`${endpoint.transport} failed: ${ex}`);\r\n\r\n if (this.connectionState !== ConnectionState.Connecting) {\r\n const message = \"Failed to select transport before stop() was called.\";\r\n this.logger.log(LogLevel.Debug, message);\r\n return Promise.reject(new Error(message));\r\n }\r\n }\r\n }\r\n }\r\n\r\n if (transportExceptions.length > 0) {\r\n return Promise.reject(new Error(`Unable to connect to the server with any of the available transports. ${transportExceptions.join(\" \")}`));\r\n }\r\n return Promise.reject(new Error(\"None of the transports supported by the client are supported by the server.\"));\r\n }\r\n\r\n private constructTransport(transport: HttpTransportType): ITransport {\r\n switch (transport) {\r\n case HttpTransportType.WebSockets:\r\n if (!this.options.WebSocket) {\r\n throw new Error(\"'WebSocket' is not supported in your environment.\");\r\n }\r\n return new WebSocketTransport(this.httpClient, this.accessTokenFactory, this.logger, this.options.logMessageContent || false, this.options.WebSocket, this.options.headers || {});\r\n case HttpTransportType.ServerSentEvents:\r\n if (!this.options.EventSource) {\r\n throw new Error(\"'EventSource' is not supported in your environment.\");\r\n }\r\n return new ServerSentEventsTransport(this.httpClient, this.accessTokenFactory, this.logger, this.options.logMessageContent || false, this.options.EventSource, this.options.withCredentials!, this.options.headers || {});\r\n case HttpTransportType.LongPolling:\r\n return new LongPollingTransport(this.httpClient, this.accessTokenFactory, this.logger, this.options.logMessageContent || false, this.options.withCredentials!, this.options.headers || {});\r\n default:\r\n throw new Error(`Unknown transport: ${transport}.`);\r\n }\r\n }\r\n\r\n private startTransport(url: string, transferFormat: TransferFormat): Promise {\r\n this.transport!.onreceive = this.onreceive;\r\n this.transport!.onclose = (e) => this.stopConnection(e);\r\n return this.transport!.connect(url, transferFormat);\r\n }\r\n\r\n private resolveTransportOrError(endpoint: IAvailableTransport, requestedTransport: HttpTransportType | undefined, requestedTransferFormat: TransferFormat): ITransport | Error {\r\n const transport = HttpTransportType[endpoint.transport];\r\n if (transport === null || transport === undefined) {\r\n this.logger.log(LogLevel.Debug, `Skipping transport '${endpoint.transport}' because it is not supported by this client.`);\r\n return new Error(`Skipping transport '${endpoint.transport}' because it is not supported by this client.`);\r\n } else {\r\n if (transportMatches(requestedTransport, transport)) {\r\n const transferFormats = endpoint.transferFormats.map((s) => TransferFormat[s]);\r\n if (transferFormats.indexOf(requestedTransferFormat) >= 0) {\r\n if ((transport === HttpTransportType.WebSockets && !this.options.WebSocket) ||\r\n (transport === HttpTransportType.ServerSentEvents && !this.options.EventSource)) {\r\n this.logger.log(LogLevel.Debug, `Skipping transport '${HttpTransportType[transport]}' because it is not supported in your environment.'`);\r\n return new Error(`'${HttpTransportType[transport]}' is not supported in your environment.`);\r\n } else {\r\n this.logger.log(LogLevel.Debug, `Selecting transport '${HttpTransportType[transport]}'.`);\r\n try {\r\n return this.constructTransport(transport);\r\n } catch (ex) {\r\n return ex;\r\n }\r\n }\r\n } else {\r\n this.logger.log(LogLevel.Debug, `Skipping transport '${HttpTransportType[transport]}' because it does not support the requested transfer format '${TransferFormat[requestedTransferFormat]}'.`);\r\n return new Error(`'${HttpTransportType[transport]}' does not support ${TransferFormat[requestedTransferFormat]}.`);\r\n }\r\n } else {\r\n this.logger.log(LogLevel.Debug, `Skipping transport '${HttpTransportType[transport]}' because it was disabled by the client.`);\r\n return new Error(`'${HttpTransportType[transport]}' is disabled by the client.`);\r\n }\r\n }\r\n }\r\n\r\n private isITransport(transport: any): transport is ITransport {\r\n return transport && typeof (transport) === \"object\" && \"connect\" in transport;\r\n }\r\n\r\n private stopConnection(error?: Error): void {\r\n this.logger.log(LogLevel.Debug, `HttpConnection.stopConnection(${error}) called while in state ${this.connectionState}.`);\r\n\r\n this.transport = undefined;\r\n\r\n // If we have a stopError, it takes precedence over the error from the transport\r\n error = this.stopError || error;\r\n this.stopError = undefined;\r\n\r\n if (this.connectionState === ConnectionState.Disconnected) {\r\n this.logger.log(LogLevel.Debug, `Call to HttpConnection.stopConnection(${error}) was ignored because the connection is already in the disconnected state.`);\r\n return;\r\n }\r\n\r\n if (this.connectionState === ConnectionState.Connecting) {\r\n this.logger.log(LogLevel.Warning, `Call to HttpConnection.stopConnection(${error}) was ignored because the connection is still in the connecting state.`);\r\n throw new Error(`HttpConnection.stopConnection(${error}) was called while the connection is still in the connecting state.`);\r\n }\r\n\r\n if (this.connectionState === ConnectionState.Disconnecting) {\r\n // A call to stop() induced this call to stopConnection and needs to be completed.\r\n // Any stop() awaiters will be scheduled to continue after the onclose callback fires.\r\n this.stopPromiseResolver();\r\n }\r\n\r\n if (error) {\r\n this.logger.log(LogLevel.Error, `Connection disconnected with error '${error}'.`);\r\n } else {\r\n this.logger.log(LogLevel.Information, \"Connection disconnected.\");\r\n }\r\n\r\n if (this.sendQueue) {\r\n this.sendQueue.stop().catch((e) => {\r\n this.logger.log(LogLevel.Error, `TransportSendQueue.stop() threw error '${e}'.`);\r\n });\r\n this.sendQueue = undefined;\r\n }\r\n\r\n this.connectionId = undefined;\r\n this.connectionState = ConnectionState.Disconnected;\r\n\r\n if (this.connectionStarted) {\r\n this.connectionStarted = false;\r\n try {\r\n if (this.onclose) {\r\n this.onclose(error);\r\n }\r\n } catch (e) {\r\n this.logger.log(LogLevel.Error, `HttpConnection.onclose(${error}) threw error '${e}'.`);\r\n }\r\n }\r\n }\r\n\r\n private resolveUrl(url: string): string {\r\n // startsWith is not supported in IE\r\n if (url.lastIndexOf(\"https://\", 0) === 0 || url.lastIndexOf(\"http://\", 0) === 0) {\r\n return url;\r\n }\r\n\r\n if (!Platform.isBrowser || !window.document) {\r\n throw new Error(`Cannot resolve '${url}'.`);\r\n }\r\n\r\n // Setting the url to the href propery of an anchor tag handles normalization\r\n // for us. There are 3 main cases.\r\n // 1. Relative path normalization e.g \"b\" -> \"http://localhost:5000/a/b\"\r\n // 2. Absolute path normalization e.g \"/a/b\" -> \"http://localhost:5000/a/b\"\r\n // 3. Networkpath reference normalization e.g \"//localhost:5000/a/b\" -> \"http://localhost:5000/a/b\"\r\n const aTag = window.document.createElement(\"a\");\r\n aTag.href = url;\r\n\r\n this.logger.log(LogLevel.Information, `Normalizing '${url}' to '${aTag.href}'.`);\r\n return aTag.href;\r\n }\r\n\r\n private resolveNegotiateUrl(url: string): string {\r\n const index = url.indexOf(\"?\");\r\n let negotiateUrl = url.substring(0, index === -1 ? url.length : index);\r\n if (negotiateUrl[negotiateUrl.length - 1] !== \"/\") {\r\n negotiateUrl += \"/\";\r\n }\r\n negotiateUrl += \"negotiate\";\r\n negotiateUrl += index === -1 ? \"\" : url.substring(index);\r\n\r\n if (negotiateUrl.indexOf(\"negotiateVersion\") === -1) {\r\n negotiateUrl += index === -1 ? \"?\" : \"&\";\r\n negotiateUrl += \"negotiateVersion=\" + this.negotiateVersion;\r\n }\r\n return negotiateUrl;\r\n }\r\n}\r\n\r\nfunction transportMatches(requestedTransport: HttpTransportType | undefined, actualTransport: HttpTransportType) {\r\n return !requestedTransport || ((actualTransport & requestedTransport) !== 0);\r\n}\r\n\r\n/** @private */\r\nexport class TransportSendQueue {\r\n private buffer: any[] = [];\r\n private sendBufferedData: PromiseSource;\r\n private executing: boolean = true;\r\n private transportResult?: PromiseSource;\r\n private sendLoopPromise: Promise;\r\n\r\n constructor(private readonly transport: ITransport) {\r\n this.sendBufferedData = new PromiseSource();\r\n this.transportResult = new PromiseSource();\r\n\r\n this.sendLoopPromise = this.sendLoop();\r\n }\r\n\r\n public send(data: string | ArrayBuffer): Promise {\r\n this.bufferData(data);\r\n if (!this.transportResult) {\r\n this.transportResult = new PromiseSource();\r\n }\r\n return this.transportResult.promise;\r\n }\r\n\r\n public stop(): Promise {\r\n this.executing = false;\r\n this.sendBufferedData.resolve();\r\n return this.sendLoopPromise;\r\n }\r\n\r\n private bufferData(data: string | ArrayBuffer): void {\r\n if (this.buffer.length && typeof(this.buffer[0]) !== typeof(data)) {\r\n throw new Error(`Expected data to be of type ${typeof(this.buffer)} but was of type ${typeof(data)}`);\r\n }\r\n\r\n this.buffer.push(data);\r\n this.sendBufferedData.resolve();\r\n }\r\n\r\n private async sendLoop(): Promise {\r\n while (true) {\r\n await this.sendBufferedData.promise;\r\n\r\n if (!this.executing) {\r\n if (this.transportResult) {\r\n this.transportResult.reject(\"Connection stopped.\");\r\n }\r\n\r\n break;\r\n }\r\n\r\n this.sendBufferedData = new PromiseSource();\r\n\r\n const transportResult = this.transportResult!;\r\n this.transportResult = undefined;\r\n\r\n const data = typeof(this.buffer[0]) === \"string\" ?\r\n this.buffer.join(\"\") :\r\n TransportSendQueue.concatBuffers(this.buffer);\r\n\r\n this.buffer.length = 0;\r\n\r\n try {\r\n await this.transport.send(data);\r\n transportResult.resolve();\r\n } catch (error) {\r\n transportResult.reject(error);\r\n }\r\n }\r\n }\r\n\r\n private static concatBuffers(arrayBuffers: ArrayBuffer[]): ArrayBuffer {\r\n const totalLength = arrayBuffers.map((b) => b.byteLength).reduce((a, b) => a + b);\r\n const result = new Uint8Array(totalLength);\r\n let offset = 0;\r\n for (const item of arrayBuffers) {\r\n result.set(new Uint8Array(item), offset);\r\n offset += item.byteLength;\r\n }\r\n\r\n return result.buffer;\r\n }\r\n}\r\n\r\nclass PromiseSource {\r\n private resolver?: () => void;\r\n private rejecter!: (reason?: any) => void;\r\n public promise: Promise;\r\n\r\n constructor() {\r\n this.promise = new Promise((resolve, reject) => [this.resolver, this.rejecter] = [resolve, reject]);\r\n }\r\n\r\n public resolve(): void {\r\n this.resolver!();\r\n }\r\n\r\n public reject(reason?: any): void {\r\n this.rejecter!(reason);\r\n }\r\n}\r\n","// Copyright (c) .NET Foundation. All rights reserved.\r\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\r\n\r\nimport { CompletionMessage, HubMessage, IHubProtocol, InvocationMessage, MessageType, StreamItemMessage } from \"./IHubProtocol\";\r\nimport { ILogger, LogLevel } from \"./ILogger\";\r\nimport { TransferFormat } from \"./ITransport\";\r\nimport { NullLogger } from \"./Loggers\";\r\nimport { TextMessageFormat } from \"./TextMessageFormat\";\r\n\r\nconst JSON_HUB_PROTOCOL_NAME: string = \"json\";\r\n\r\n/** Implements the JSON Hub Protocol. */\r\nexport class JsonHubProtocol implements IHubProtocol {\r\n\r\n /** @inheritDoc */\r\n public readonly name: string = JSON_HUB_PROTOCOL_NAME;\r\n /** @inheritDoc */\r\n public readonly version: number = 1;\r\n\r\n /** @inheritDoc */\r\n public readonly transferFormat: TransferFormat = TransferFormat.Text;\r\n\r\n /** Creates an array of {@link @microsoft/signalr.HubMessage} objects from the specified serialized representation.\r\n *\r\n * @param {string} input A string containing the serialized representation.\r\n * @param {ILogger} logger A logger that will be used to log messages that occur during parsing.\r\n */\r\n public parseMessages(input: string, logger: ILogger): HubMessage[] {\r\n // The interface does allow \"ArrayBuffer\" to be passed in, but this implementation does not. So let's throw a useful error.\r\n if (typeof input !== \"string\") {\r\n throw new Error(\"Invalid input for JSON hub protocol. Expected a string.\");\r\n }\r\n\r\n if (!input) {\r\n return [];\r\n }\r\n\r\n if (logger === null) {\r\n logger = NullLogger.instance;\r\n }\r\n\r\n // Parse the messages\r\n const messages = TextMessageFormat.parse(input);\r\n\r\n const hubMessages = [];\r\n for (const message of messages) {\r\n const parsedMessage = JSON.parse(message) as HubMessage;\r\n if (typeof parsedMessage.type !== \"number\") {\r\n throw new Error(\"Invalid payload.\");\r\n }\r\n switch (parsedMessage.type) {\r\n case MessageType.Invocation:\r\n this.isInvocationMessage(parsedMessage);\r\n break;\r\n case MessageType.StreamItem:\r\n this.isStreamItemMessage(parsedMessage);\r\n break;\r\n case MessageType.Completion:\r\n this.isCompletionMessage(parsedMessage);\r\n break;\r\n case MessageType.Ping:\r\n // Single value, no need to validate\r\n break;\r\n case MessageType.Close:\r\n // All optional values, no need to validate\r\n break;\r\n default:\r\n // Future protocol changes can add message types, old clients can ignore them\r\n logger.log(LogLevel.Information, \"Unknown message type '\" + parsedMessage.type + \"' ignored.\");\r\n continue;\r\n }\r\n hubMessages.push(parsedMessage);\r\n }\r\n\r\n return hubMessages;\r\n }\r\n\r\n /** Writes the specified {@link @microsoft/signalr.HubMessage} to a string and returns it.\r\n *\r\n * @param {HubMessage} message The message to write.\r\n * @returns {string} A string containing the serialized representation of the message.\r\n */\r\n public writeMessage(message: HubMessage): string {\r\n return TextMessageFormat.write(JSON.stringify(message));\r\n }\r\n\r\n private isInvocationMessage(message: InvocationMessage): void {\r\n this.assertNotEmptyString(message.target, \"Invalid payload for Invocation message.\");\r\n\r\n if (message.invocationId !== undefined) {\r\n this.assertNotEmptyString(message.invocationId, \"Invalid payload for Invocation message.\");\r\n }\r\n }\r\n\r\n private isStreamItemMessage(message: StreamItemMessage): void {\r\n this.assertNotEmptyString(message.invocationId, \"Invalid payload for StreamItem message.\");\r\n\r\n if (message.item === undefined) {\r\n throw new Error(\"Invalid payload for StreamItem message.\");\r\n }\r\n }\r\n\r\n private isCompletionMessage(message: CompletionMessage): void {\r\n if (message.result && message.error) {\r\n throw new Error(\"Invalid payload for Completion message.\");\r\n }\r\n\r\n if (!message.result && message.error) {\r\n this.assertNotEmptyString(message.error, \"Invalid payload for Completion message.\");\r\n }\r\n\r\n this.assertNotEmptyString(message.invocationId, \"Invalid payload for Completion message.\");\r\n }\r\n\r\n private assertNotEmptyString(value: any, errorMessage: string): void {\r\n if (typeof value !== \"string\" || value === \"\") {\r\n throw new Error(errorMessage);\r\n }\r\n }\r\n}\r\n","// Copyright (c) .NET Foundation. All rights reserved.\r\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\r\n\r\nimport { DefaultReconnectPolicy } from \"./DefaultReconnectPolicy\";\r\nimport { HttpConnection } from \"./HttpConnection\";\r\nimport { HubConnection } from \"./HubConnection\";\r\nimport { IHttpConnectionOptions } from \"./IHttpConnectionOptions\";\r\nimport { IHubProtocol } from \"./IHubProtocol\";\r\nimport { ILogger, LogLevel } from \"./ILogger\";\r\nimport { IRetryPolicy } from \"./IRetryPolicy\";\r\nimport { HttpTransportType } from \"./ITransport\";\r\nimport { JsonHubProtocol } from \"./JsonHubProtocol\";\r\nimport { NullLogger } from \"./Loggers\";\r\nimport { Arg, ConsoleLogger } from \"./Utils\";\r\n\r\n// tslint:disable:object-literal-sort-keys\r\nconst LogLevelNameMapping = {\r\n trace: LogLevel.Trace,\r\n debug: LogLevel.Debug,\r\n info: LogLevel.Information,\r\n information: LogLevel.Information,\r\n warn: LogLevel.Warning,\r\n warning: LogLevel.Warning,\r\n error: LogLevel.Error,\r\n critical: LogLevel.Critical,\r\n none: LogLevel.None,\r\n};\r\n\r\nfunction parseLogLevel(name: string): LogLevel {\r\n // Case-insensitive matching via lower-casing\r\n // Yes, I know case-folding is a complicated problem in Unicode, but we only support\r\n // the ASCII strings defined in LogLevelNameMapping anyway, so it's fine -anurse.\r\n const mapping = LogLevelNameMapping[name.toLowerCase()];\r\n if (typeof mapping !== \"undefined\") {\r\n return mapping;\r\n } else {\r\n throw new Error(`Unknown log level: ${name}`);\r\n }\r\n}\r\n\r\n/** A builder for configuring {@link @microsoft/signalr.HubConnection} instances. */\r\nexport class HubConnectionBuilder {\r\n /** @internal */\r\n public protocol?: IHubProtocol;\r\n /** @internal */\r\n public httpConnectionOptions?: IHttpConnectionOptions;\r\n /** @internal */\r\n public url?: string;\r\n /** @internal */\r\n public logger?: ILogger;\r\n\r\n /** If defined, this indicates the client should automatically attempt to reconnect if the connection is lost. */\r\n /** @internal */\r\n public reconnectPolicy?: IRetryPolicy;\r\n\r\n /** Configures console logging for the {@link @microsoft/signalr.HubConnection}.\r\n *\r\n * @param {LogLevel} logLevel The minimum level of messages to log. Anything at this level, or a more severe level, will be logged.\r\n * @returns The {@link @microsoft/signalr.HubConnectionBuilder} instance, for chaining.\r\n */\r\n public configureLogging(logLevel: LogLevel): HubConnectionBuilder;\r\n\r\n /** Configures custom logging for the {@link @microsoft/signalr.HubConnection}.\r\n *\r\n * @param {ILogger} logger An object implementing the {@link @microsoft/signalr.ILogger} interface, which will be used to write all log messages.\r\n * @returns The {@link @microsoft/signalr.HubConnectionBuilder} instance, for chaining.\r\n */\r\n public configureLogging(logger: ILogger): HubConnectionBuilder;\r\n\r\n /** Configures custom logging for the {@link @microsoft/signalr.HubConnection}.\r\n *\r\n * @param {string} logLevel A string representing a LogLevel setting a minimum level of messages to log.\r\n * See {@link https://docs.microsoft.com/aspnet/core/signalr/configuration#configure-logging|the documentation for client logging configuration} for more details.\r\n */\r\n public configureLogging(logLevel: string): HubConnectionBuilder;\r\n\r\n /** Configures custom logging for the {@link @microsoft/signalr.HubConnection}.\r\n *\r\n * @param {LogLevel | string | ILogger} logging A {@link @microsoft/signalr.LogLevel}, a string representing a LogLevel, or an object implementing the {@link @microsoft/signalr.ILogger} interface.\r\n * See {@link https://docs.microsoft.com/aspnet/core/signalr/configuration#configure-logging|the documentation for client logging configuration} for more details.\r\n * @returns The {@link @microsoft/signalr.HubConnectionBuilder} instance, for chaining.\r\n */\r\n public configureLogging(logging: LogLevel | string | ILogger): HubConnectionBuilder;\r\n public configureLogging(logging: LogLevel | string | ILogger): HubConnectionBuilder {\r\n Arg.isRequired(logging, \"logging\");\r\n\r\n if (isLogger(logging)) {\r\n this.logger = logging;\r\n } else if (typeof logging === \"string\") {\r\n const logLevel = parseLogLevel(logging);\r\n this.logger = new ConsoleLogger(logLevel);\r\n } else {\r\n this.logger = new ConsoleLogger(logging);\r\n }\r\n\r\n return this;\r\n }\r\n\r\n /** Configures the {@link @microsoft/signalr.HubConnection} to use HTTP-based transports to connect to the specified URL.\r\n *\r\n * The transport will be selected automatically based on what the server and client support.\r\n *\r\n * @param {string} url The URL the connection will use.\r\n * @returns The {@link @microsoft/signalr.HubConnectionBuilder} instance, for chaining.\r\n */\r\n public withUrl(url: string): HubConnectionBuilder;\r\n\r\n /** Configures the {@link @microsoft/signalr.HubConnection} to use the specified HTTP-based transport to connect to the specified URL.\r\n *\r\n * @param {string} url The URL the connection will use.\r\n * @param {HttpTransportType} transportType The specific transport to use.\r\n * @returns The {@link @microsoft/signalr.HubConnectionBuilder} instance, for chaining.\r\n */\r\n public withUrl(url: string, transportType: HttpTransportType): HubConnectionBuilder;\r\n\r\n /** Configures the {@link @microsoft/signalr.HubConnection} to use HTTP-based transports to connect to the specified URL.\r\n *\r\n * @param {string} url The URL the connection will use.\r\n * @param {IHttpConnectionOptions} options An options object used to configure the connection.\r\n * @returns The {@link @microsoft/signalr.HubConnectionBuilder} instance, for chaining.\r\n */\r\n public withUrl(url: string, options: IHttpConnectionOptions): HubConnectionBuilder;\r\n public withUrl(url: string, transportTypeOrOptions?: IHttpConnectionOptions | HttpTransportType): HubConnectionBuilder {\r\n Arg.isRequired(url, \"url\");\r\n Arg.isNotEmpty(url, \"url\");\r\n\r\n this.url = url;\r\n\r\n // Flow-typing knows where it's at. Since HttpTransportType is a number and IHttpConnectionOptions is guaranteed\r\n // to be an object, we know (as does TypeScript) this comparison is all we need to figure out which overload was called.\r\n if (typeof transportTypeOrOptions === \"object\") {\r\n this.httpConnectionOptions = { ...this.httpConnectionOptions, ...transportTypeOrOptions };\r\n } else {\r\n this.httpConnectionOptions = {\r\n ...this.httpConnectionOptions,\r\n transport: transportTypeOrOptions,\r\n };\r\n }\r\n\r\n return this;\r\n }\r\n\r\n /** Configures the {@link @microsoft/signalr.HubConnection} to use the specified Hub Protocol.\r\n *\r\n * @param {IHubProtocol} protocol The {@link @microsoft/signalr.IHubProtocol} implementation to use.\r\n */\r\n public withHubProtocol(protocol: IHubProtocol): HubConnectionBuilder {\r\n Arg.isRequired(protocol, \"protocol\");\r\n\r\n this.protocol = protocol;\r\n return this;\r\n }\r\n\r\n /** Configures the {@link @microsoft/signalr.HubConnection} to automatically attempt to reconnect if the connection is lost.\r\n * By default, the client will wait 0, 2, 10 and 30 seconds respectively before trying up to 4 reconnect attempts.\r\n */\r\n public withAutomaticReconnect(): HubConnectionBuilder;\r\n\r\n /** Configures the {@link @microsoft/signalr.HubConnection} to automatically attempt to reconnect if the connection is lost.\r\n *\r\n * @param {number[]} retryDelays An array containing the delays in milliseconds before trying each reconnect attempt.\r\n * The length of the array represents how many failed reconnect attempts it takes before the client will stop attempting to reconnect.\r\n */\r\n public withAutomaticReconnect(retryDelays: number[]): HubConnectionBuilder;\r\n\r\n /** Configures the {@link @microsoft/signalr.HubConnection} to automatically attempt to reconnect if the connection is lost.\r\n *\r\n * @param {IRetryPolicy} reconnectPolicy An {@link @microsoft/signalR.IRetryPolicy} that controls the timing and number of reconnect attempts.\r\n */\r\n public withAutomaticReconnect(reconnectPolicy: IRetryPolicy): HubConnectionBuilder;\r\n public withAutomaticReconnect(retryDelaysOrReconnectPolicy?: number[] | IRetryPolicy): HubConnectionBuilder {\r\n if (this.reconnectPolicy) {\r\n throw new Error(\"A reconnectPolicy has already been set.\");\r\n }\r\n\r\n if (!retryDelaysOrReconnectPolicy) {\r\n this.reconnectPolicy = new DefaultReconnectPolicy();\r\n } else if (Array.isArray(retryDelaysOrReconnectPolicy)) {\r\n this.reconnectPolicy = new DefaultReconnectPolicy(retryDelaysOrReconnectPolicy);\r\n } else {\r\n this.reconnectPolicy = retryDelaysOrReconnectPolicy;\r\n }\r\n\r\n return this;\r\n }\r\n\r\n /** Creates a {@link @microsoft/signalr.HubConnection} from the configuration options specified in this builder.\r\n *\r\n * @returns {HubConnection} The configured {@link @microsoft/signalr.HubConnection}.\r\n */\r\n public build(): HubConnection {\r\n // If httpConnectionOptions has a logger, use it. Otherwise, override it with the one\r\n // provided to configureLogger\r\n const httpConnectionOptions = this.httpConnectionOptions || {};\r\n\r\n // If it's 'null', the user **explicitly** asked for null, don't mess with it.\r\n if (httpConnectionOptions.logger === undefined) {\r\n // If our logger is undefined or null, that's OK, the HttpConnection constructor will handle it.\r\n httpConnectionOptions.logger = this.logger;\r\n }\r\n\r\n // Now create the connection\r\n if (!this.url) {\r\n throw new Error(\"The 'HubConnectionBuilder.withUrl' method must be called before building the connection.\");\r\n }\r\n const connection = new HttpConnection(this.url, httpConnectionOptions);\r\n\r\n return HubConnection.create(\r\n connection,\r\n this.logger || NullLogger.instance,\r\n this.protocol || new JsonHubProtocol(),\r\n this.reconnectPolicy);\r\n }\r\n}\r\n\r\nfunction isLogger(logger: any): logger is ILogger {\r\n return logger.log !== undefined;\r\n}\r\n","// Copyright (c) .NET Foundation. All rights reserved.\r\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\r\n\r\nimport { HttpClient } from \"./HttpClient\";\r\nimport { MessageHeaders } from \"./IHubProtocol\";\r\nimport { ILogger, LogLevel } from \"./ILogger\";\r\nimport { NullLogger } from \"./Loggers\";\r\nimport { IStreamSubscriber, ISubscription } from \"./Stream\";\r\nimport { Subject } from \"./Subject\";\r\n\r\n// Version token that will be replaced by the prepack command\r\n/** The version of the SignalR client. */\r\nexport const VERSION: string = \"0.0.0-DEV_BUILD\";\r\n\r\n/** @private */\r\nexport class Arg {\r\n public static isRequired(val: any, name: string): void {\r\n if (val === null || val === undefined) {\r\n throw new Error(`The '${name}' argument is required.`);\r\n }\r\n }\r\n public static isNotEmpty(val: string, name: string): void {\r\n if (!val || val.match(/^\\s*$/)) {\r\n throw new Error(`The '${name}' argument should not be empty.`);\r\n }\r\n }\r\n\r\n public static isIn(val: any, values: any, name: string): void {\r\n // TypeScript enums have keys for **both** the name and the value of each enum member on the type itself.\r\n if (!(val in values)) {\r\n throw new Error(`Unknown ${name} value: ${val}.`);\r\n }\r\n }\r\n}\r\n\r\n/** @private */\r\nexport class Platform {\r\n public static get isBrowser(): boolean {\r\n return typeof window === \"object\";\r\n }\r\n\r\n public static get isWebWorker(): boolean {\r\n return typeof self === \"object\" && \"importScripts\" in self;\r\n }\r\n\r\n public static get isNode(): boolean {\r\n return !this.isBrowser && !this.isWebWorker;\r\n }\r\n}\r\n\r\n/** @private */\r\nexport function getDataDetail(data: any, includeContent: boolean): string {\r\n let detail = \"\";\r\n if (isArrayBuffer(data)) {\r\n detail = `Binary data of length ${data.byteLength}`;\r\n if (includeContent) {\r\n detail += `. Content: '${formatArrayBuffer(data)}'`;\r\n }\r\n } else if (typeof data === \"string\") {\r\n detail = `String data of length ${data.length}`;\r\n if (includeContent) {\r\n detail += `. Content: '${data}'`;\r\n }\r\n }\r\n return detail;\r\n}\r\n\r\n/** @private */\r\nexport function formatArrayBuffer(data: ArrayBuffer): string {\r\n const view = new Uint8Array(data);\r\n\r\n // Uint8Array.map only supports returning another Uint8Array?\r\n let str = \"\";\r\n view.forEach((num) => {\r\n const pad = num < 16 ? \"0\" : \"\";\r\n str += `0x${pad}${num.toString(16)} `;\r\n });\r\n\r\n // Trim of trailing space.\r\n return str.substr(0, str.length - 1);\r\n}\r\n\r\n// Also in signalr-protocol-msgpack/Utils.ts\r\n/** @private */\r\nexport function isArrayBuffer(val: any): val is ArrayBuffer {\r\n return val && typeof ArrayBuffer !== \"undefined\" &&\r\n (val instanceof ArrayBuffer ||\r\n // Sometimes we get an ArrayBuffer that doesn't satisfy instanceof\r\n (val.constructor && val.constructor.name === \"ArrayBuffer\"));\r\n}\r\n\r\n/** @private */\r\nexport async function sendMessage(logger: ILogger, transportName: string, httpClient: HttpClient, url: string, accessTokenFactory: (() => string | Promise) | undefined,\r\n content: string | ArrayBuffer, logMessageContent: boolean, withCredentials: boolean, defaultHeaders: MessageHeaders): Promise {\r\n let headers = {};\r\n if (accessTokenFactory) {\r\n const token = await accessTokenFactory();\r\n if (token) {\r\n headers = {\r\n [\"Authorization\"]: `Bearer ${token}`,\r\n };\r\n }\r\n }\r\n\r\n const [name, value] = getUserAgentHeader();\r\n headers[name] = value;\r\n\r\n logger.log(LogLevel.Trace, `(${transportName} transport) sending data. ${getDataDetail(content, logMessageContent)}.`);\r\n\r\n const responseType = isArrayBuffer(content) ? \"arraybuffer\" : \"text\";\r\n const response = await httpClient.post(url, {\r\n content,\r\n headers: { ...headers, ...defaultHeaders},\r\n responseType,\r\n withCredentials,\r\n });\r\n\r\n logger.log(LogLevel.Trace, `(${transportName} transport) request complete. Response status: ${response.statusCode}.`);\r\n}\r\n\r\n/** @private */\r\nexport function createLogger(logger?: ILogger | LogLevel) {\r\n if (logger === undefined) {\r\n return new ConsoleLogger(LogLevel.Information);\r\n }\r\n\r\n if (logger === null) {\r\n return NullLogger.instance;\r\n }\r\n\r\n if ((logger as ILogger).log) {\r\n return logger as ILogger;\r\n }\r\n\r\n return new ConsoleLogger(logger as LogLevel);\r\n}\r\n\r\n/** @private */\r\nexport class SubjectSubscription implements ISubscription {\r\n private subject: Subject;\r\n private observer: IStreamSubscriber;\r\n\r\n constructor(subject: Subject, observer: IStreamSubscriber) {\r\n this.subject = subject;\r\n this.observer = observer;\r\n }\r\n\r\n public dispose(): void {\r\n const index: number = this.subject.observers.indexOf(this.observer);\r\n if (index > -1) {\r\n this.subject.observers.splice(index, 1);\r\n }\r\n\r\n if (this.subject.observers.length === 0 && this.subject.cancelCallback) {\r\n this.subject.cancelCallback().catch((_) => { });\r\n }\r\n }\r\n}\r\n\r\n/** @private */\r\nexport class ConsoleLogger implements ILogger {\r\n private readonly minimumLogLevel: LogLevel;\r\n\r\n // Public for testing purposes.\r\n public outputConsole: {\r\n error(message: any): void,\r\n warn(message: any): void,\r\n info(message: any): void,\r\n log(message: any): void,\r\n };\r\n\r\n constructor(minimumLogLevel: LogLevel) {\r\n this.minimumLogLevel = minimumLogLevel;\r\n this.outputConsole = console;\r\n }\r\n\r\n public log(logLevel: LogLevel, message: string): void {\r\n if (logLevel >= this.minimumLogLevel) {\r\n switch (logLevel) {\r\n case LogLevel.Critical:\r\n case LogLevel.Error:\r\n this.outputConsole.error(`[${new Date().toISOString()}] ${LogLevel[logLevel]}: ${message}`);\r\n break;\r\n case LogLevel.Warning:\r\n this.outputConsole.warn(`[${new Date().toISOString()}] ${LogLevel[logLevel]}: ${message}`);\r\n break;\r\n case LogLevel.Information:\r\n this.outputConsole.info(`[${new Date().toISOString()}] ${LogLevel[logLevel]}: ${message}`);\r\n break;\r\n default:\r\n // console.debug only goes to attached debuggers in Node, so we use console.log for Trace and Debug\r\n this.outputConsole.log(`[${new Date().toISOString()}] ${LogLevel[logLevel]}: ${message}`);\r\n break;\r\n }\r\n }\r\n }\r\n}\r\n\r\n/** @private */\r\nexport function getUserAgentHeader(): [string, string] {\r\n let userAgentHeaderName = \"X-SignalR-User-Agent\";\r\n if (Platform.isNode) {\r\n userAgentHeaderName = \"User-Agent\";\r\n }\r\n return [ userAgentHeaderName, constructUserAgent(VERSION, getOsName(), getRuntime(), getRuntimeVersion()) ];\r\n}\r\n\r\n/** @private */\r\nexport function constructUserAgent(version: string, os: string, runtime: string, runtimeVersion: string | undefined): string {\r\n // Microsoft SignalR/[Version] ([Detailed Version]; [Operating System]; [Runtime]; [Runtime Version])\r\n let userAgent: string = \"Microsoft SignalR/\";\r\n\r\n const majorAndMinor = version.split(\".\");\r\n userAgent += `${majorAndMinor[0]}.${majorAndMinor[1]}`;\r\n userAgent += ` (${version}; `;\r\n\r\n if (os && os !== \"\") {\r\n userAgent += `${os}; `;\r\n } else {\r\n userAgent += \"Unknown OS; \";\r\n }\r\n\r\n userAgent += `${runtime}`;\r\n\r\n if (runtimeVersion) {\r\n userAgent += `; ${runtimeVersion}`;\r\n } else {\r\n userAgent += \"; Unknown Runtime Version\";\r\n }\r\n\r\n userAgent += \")\";\r\n return userAgent;\r\n}\r\n\r\nfunction getOsName(): string {\r\n if (Platform.isNode) {\r\n switch (process.platform) {\r\n case \"win32\":\r\n return \"Windows NT\";\r\n case \"darwin\":\r\n return \"macOS\";\r\n case \"linux\":\r\n return \"Linux\";\r\n default:\r\n return process.platform;\r\n }\r\n } else {\r\n return \"\";\r\n }\r\n}\r\n\r\nfunction getRuntimeVersion(): string | undefined {\r\n if (Platform.isNode) {\r\n return process.versions.node;\r\n }\r\n return undefined;\r\n}\r\n\r\nfunction getRuntime(): string {\r\n if (Platform.isNode) {\r\n return \"NodeJS\";\r\n } else {\r\n return \"Browser\";\r\n }\r\n}\r\n","// Copyright (c) .NET Foundation. All rights reserved.\r\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\r\n\r\nimport { TextMessageFormat } from \"./TextMessageFormat\";\r\nimport { isArrayBuffer } from \"./Utils\";\r\n\r\n/** @private */\r\nexport interface HandshakeRequestMessage {\r\n readonly protocol: string;\r\n readonly version: number;\r\n}\r\n\r\n/** @private */\r\nexport interface HandshakeResponseMessage {\r\n readonly error: string;\r\n readonly minorVersion: number;\r\n}\r\n\r\n/** @private */\r\nexport class HandshakeProtocol {\r\n // Handshake request is always JSON\r\n public writeHandshakeRequest(handshakeRequest: HandshakeRequestMessage): string {\r\n return TextMessageFormat.write(JSON.stringify(handshakeRequest));\r\n }\r\n\r\n public parseHandshakeResponse(data: any): [any, HandshakeResponseMessage] {\r\n let responseMessage: HandshakeResponseMessage;\r\n let messageData: string;\r\n let remainingData: any;\r\n\r\n if (isArrayBuffer(data) || (typeof Buffer !== \"undefined\" && data instanceof Buffer)) {\r\n // Format is binary but still need to read JSON text from handshake response\r\n const binaryData = new Uint8Array(data);\r\n const separatorIndex = binaryData.indexOf(TextMessageFormat.RecordSeparatorCode);\r\n if (separatorIndex === -1) {\r\n throw new Error(\"Message is incomplete.\");\r\n }\r\n\r\n // content before separator is handshake response\r\n // optional content after is additional messages\r\n const responseLength = separatorIndex + 1;\r\n messageData = String.fromCharCode.apply(null, binaryData.slice(0, responseLength));\r\n remainingData = (binaryData.byteLength > responseLength) ? binaryData.slice(responseLength).buffer : null;\r\n } else {\r\n const textData: string = data;\r\n const separatorIndex = textData.indexOf(TextMessageFormat.RecordSeparator);\r\n if (separatorIndex === -1) {\r\n throw new Error(\"Message is incomplete.\");\r\n }\r\n\r\n // content before separator is handshake response\r\n // optional content after is additional messages\r\n const responseLength = separatorIndex + 1;\r\n messageData = textData.substring(0, responseLength);\r\n remainingData = (textData.length > responseLength) ? textData.substring(responseLength) : null;\r\n }\r\n\r\n // At this point we should have just the single handshake message\r\n const messages = TextMessageFormat.parse(messageData);\r\n const response = JSON.parse(messages[0]);\r\n if (response.type) {\r\n throw new Error(\"Expected a handshake response from the server.\");\r\n }\r\n responseMessage = response;\r\n\r\n // multiple messages could have arrived with handshake\r\n // return additional data to be parsed as usual, or null if all parsed\r\n return [remainingData, responseMessage];\r\n }\r\n}\r\n","const errors = {\n\t0: \"Illegal state\",\n\t1: \"Immer drafts cannot have computed properties\",\n\t2: \"This object has been frozen and should not be mutated\",\n\t3(data: any) {\n\t\treturn (\n\t\t\t\"Cannot use a proxy that has been revoked. Did you pass an object from inside an immer function to an async process? \" +\n\t\t\tdata\n\t\t)\n\t},\n\t4: \"An immer producer returned a new value *and* modified its draft. Either return a new value *or* modify the draft.\",\n\t5: \"Immer forbids circular references\",\n\t6: \"The first or second argument to `produce` must be a function\",\n\t7: \"The third argument to `produce` must be a function or undefined\",\n\t8: \"First argument to `createDraft` must be a plain object, an array, or an immerable object\",\n\t9: \"First argument to `finishDraft` must be a draft returned by `createDraft`\",\n\t10: \"The given draft is already finalized\",\n\t11: \"Object.defineProperty() cannot be used on an Immer draft\",\n\t12: \"Object.setPrototypeOf() cannot be used on an Immer draft\",\n\t13: \"Immer only supports deleting array indices\",\n\t14: \"Immer only supports setting array indices and the 'length' property\",\n\t15(path: string) {\n\t\treturn \"Cannot apply patch, path doesn't resolve: \" + path\n\t},\n\t16: 'Sets cannot have \"replace\" patches.',\n\t17(op: string) {\n\t\treturn \"Unsupported patch operation: \" + op\n\t},\n\t18(plugin: string) {\n\t\treturn `The plugin for '${plugin}' has not been loaded into Immer. To enable the plugin, import and call \\`enable${plugin}()\\` when initializing your application.`\n\t},\n\t20: \"Cannot use proxies if Proxy, Proxy.revocable or Reflect are not available\",\n\t21(thing: string) {\n\t\treturn `produce can only be called on things that are draftable: plain objects, arrays, Map, Set or classes that are marked with '[immerable]: true'. Got '${thing}'`\n\t},\n\t22(thing: string) {\n\t\treturn `'current' expects a draft, got: ${thing}`\n\t},\n\t23(thing: string) {\n\t\treturn `'original' expects a draft, got: ${thing}`\n\t},\n\t24: \"Patching reserved attributes like __proto__, prototype and constructor is not allowed\"\n} as const\n\nexport function die(error: keyof typeof errors, ...args: any[]): never {\n\tif (__DEV__) {\n\t\tconst e = errors[error]\n\t\tconst msg = !e\n\t\t\t? \"unknown error nr: \" + error\n\t\t\t: typeof e === \"function\"\n\t\t\t? e.apply(null, args as any)\n\t\t\t: e\n\t\tthrow new Error(`[Immer] ${msg}`)\n\t}\n\tthrow new Error(\n\t\t`[Immer] minified error nr: ${error}${\n\t\t\targs.length ? \" \" + args.map(s => `'${s}'`).join(\",\") : \"\"\n\t\t}. Find the full error at: https://bit.ly/3cXEKWf`\n\t)\n}\n","import {\n\tDRAFT_STATE,\n\tDRAFTABLE,\n\thasSet,\n\tObjectish,\n\tDrafted,\n\tAnyObject,\n\tAnyMap,\n\tAnySet,\n\tImmerState,\n\thasMap,\n\tArchtype,\n\tdie\n} from \"../internal\"\n\n/** Returns true if the given value is an Immer draft */\n/*#__PURE__*/\nexport function isDraft(value: any): boolean {\n\treturn !!value && !!value[DRAFT_STATE]\n}\n\n/** Returns true if the given value can be drafted by Immer */\n/*#__PURE__*/\nexport function isDraftable(value: any): boolean {\n\tif (!value) return false\n\treturn (\n\t\tisPlainObject(value) ||\n\t\tArray.isArray(value) ||\n\t\t!!value[DRAFTABLE] ||\n\t\t!!value.constructor[DRAFTABLE] ||\n\t\tisMap(value) ||\n\t\tisSet(value)\n\t)\n}\n\nconst objectCtorString = Object.prototype.constructor.toString()\n/*#__PURE__*/\nexport function isPlainObject(value: any): boolean {\n\tif (!value || typeof value !== \"object\") return false\n\tconst proto = Object.getPrototypeOf(value)\n\tif (proto === null) {\n\t\treturn true\n\t}\n\tconst Ctor =\n\t\tObject.hasOwnProperty.call(proto, \"constructor\") && proto.constructor\n\n\tif (Ctor === Object) return true\n\n\treturn (\n\t\ttypeof Ctor == \"function\" &&\n\t\tFunction.toString.call(Ctor) === objectCtorString\n\t)\n}\n\n/** Get the underlying object that is represented by the given draft */\n/*#__PURE__*/\nexport function original(value: T): T | undefined\nexport function original(value: Drafted): any {\n\tif (!isDraft(value)) die(23, value)\n\treturn value[DRAFT_STATE].base_\n}\n\n/*#__PURE__*/\nexport const ownKeys: (target: AnyObject) => PropertyKey[] =\n\ttypeof Reflect !== \"undefined\" && Reflect.ownKeys\n\t\t? Reflect.ownKeys\n\t\t: typeof Object.getOwnPropertySymbols !== \"undefined\"\n\t\t? obj =>\n\t\t\t\tObject.getOwnPropertyNames(obj).concat(\n\t\t\t\t\tObject.getOwnPropertySymbols(obj) as any\n\t\t\t\t)\n\t\t: /* istanbul ignore next */ Object.getOwnPropertyNames\n\nexport const getOwnPropertyDescriptors =\n\tObject.getOwnPropertyDescriptors ||\n\tfunction getOwnPropertyDescriptors(target: any) {\n\t\t// Polyfill needed for Hermes and IE, see https://github.com/facebook/hermes/issues/274\n\t\tconst res: any = {}\n\t\townKeys(target).forEach(key => {\n\t\t\tres[key] = Object.getOwnPropertyDescriptor(target, key)\n\t\t})\n\t\treturn res\n\t}\n\nexport function each(\n\tobj: T,\n\titer: (key: string | number, value: any, source: T) => void,\n\tenumerableOnly?: boolean\n): void\nexport function each(obj: any, iter: any, enumerableOnly = false) {\n\tif (getArchtype(obj) === Archtype.Object) {\n\t\t;(enumerableOnly ? Object.keys : ownKeys)(obj).forEach(key => {\n\t\t\tif (!enumerableOnly || typeof key !== \"symbol\") iter(key, obj[key], obj)\n\t\t})\n\t} else {\n\t\tobj.forEach((entry: any, index: any) => iter(index, entry, obj))\n\t}\n}\n\n/*#__PURE__*/\nexport function getArchtype(thing: any): Archtype {\n\t/* istanbul ignore next */\n\tconst state: undefined | ImmerState = thing[DRAFT_STATE]\n\treturn state\n\t\t? state.type_ > 3\n\t\t\t? state.type_ - 4 // cause Object and Array map back from 4 and 5\n\t\t\t: (state.type_ as any) // others are the same\n\t\t: Array.isArray(thing)\n\t\t? Archtype.Array\n\t\t: isMap(thing)\n\t\t? Archtype.Map\n\t\t: isSet(thing)\n\t\t? Archtype.Set\n\t\t: Archtype.Object\n}\n\n/*#__PURE__*/\nexport function has(thing: any, prop: PropertyKey): boolean {\n\treturn getArchtype(thing) === Archtype.Map\n\t\t? thing.has(prop)\n\t\t: Object.prototype.hasOwnProperty.call(thing, prop)\n}\n\n/*#__PURE__*/\nexport function get(thing: AnyMap | AnyObject, prop: PropertyKey): any {\n\t// @ts-ignore\n\treturn getArchtype(thing) === Archtype.Map ? thing.get(prop) : thing[prop]\n}\n\n/*#__PURE__*/\nexport function set(thing: any, propOrOldValue: PropertyKey, value: any) {\n\tconst t = getArchtype(thing)\n\tif (t === Archtype.Map) thing.set(propOrOldValue, value)\n\telse if (t === Archtype.Set) {\n\t\tthing.delete(propOrOldValue)\n\t\tthing.add(value)\n\t} else thing[propOrOldValue] = value\n}\n\n/*#__PURE__*/\nexport function is(x: any, y: any): boolean {\n\t// From: https://github.com/facebook/fbjs/blob/c69904a511b900266935168223063dd8772dfc40/packages/fbjs/src/core/shallowEqual.js\n\tif (x === y) {\n\t\treturn x !== 0 || 1 / x === 1 / y\n\t} else {\n\t\treturn x !== x && y !== y\n\t}\n}\n\n/*#__PURE__*/\nexport function isMap(target: any): target is AnyMap {\n\treturn hasMap && target instanceof Map\n}\n\n/*#__PURE__*/\nexport function isSet(target: any): target is AnySet {\n\treturn hasSet && target instanceof Set\n}\n/*#__PURE__*/\nexport function latest(state: ImmerState): any {\n\treturn state.copy_ || state.base_\n}\n\n/*#__PURE__*/\nexport function shallowCopy(base: any) {\n\tif (Array.isArray(base)) return Array.prototype.slice.call(base)\n\tconst descriptors = getOwnPropertyDescriptors(base)\n\tdelete descriptors[DRAFT_STATE as any]\n\tlet keys = ownKeys(descriptors)\n\tfor (let i = 0; i < keys.length; i++) {\n\t\tconst key: any = keys[i]\n\t\tconst desc = descriptors[key]\n\t\tif (desc.writable === false) {\n\t\t\tdesc.writable = true\n\t\t\tdesc.configurable = true\n\t\t}\n\t\t// like object.assign, we will read any _own_, get/set accessors. This helps in dealing\n\t\t// with libraries that trap values, like mobx or vue\n\t\t// unlike object.assign, non-enumerables will be copied as well\n\t\tif (desc.get || desc.set)\n\t\t\tdescriptors[key] = {\n\t\t\t\tconfigurable: true,\n\t\t\t\twritable: true, // could live with !!desc.set as well here...\n\t\t\t\tenumerable: desc.enumerable,\n\t\t\t\tvalue: base[key]\n\t\t\t}\n\t}\n\treturn Object.create(Object.getPrototypeOf(base), descriptors)\n}\n\n/**\n * Freezes draftable objects. Returns the original object.\n * By default freezes shallowly, but if the second argument is `true` it will freeze recursively.\n *\n * @param obj\n * @param deep\n */\nexport function freeze(obj: T, deep?: boolean): T\nexport function freeze(obj: any, deep: boolean = false): T {\n\tif (isFrozen(obj) || isDraft(obj) || !isDraftable(obj)) return obj\n\tif (getArchtype(obj) > 1 /* Map or Set */) {\n\t\tobj.set = obj.add = obj.clear = obj.delete = dontMutateFrozenCollections as any\n\t}\n\tObject.freeze(obj)\n\tif (deep) each(obj, (key, value) => freeze(value, true), true)\n\treturn obj\n}\n\nfunction dontMutateFrozenCollections() {\n\tdie(2)\n}\n\nexport function isFrozen(obj: any): boolean {\n\tif (obj == null || typeof obj !== \"object\") return true\n\t// See #600, IE dies on non-objects in Object.isFrozen\n\treturn Object.isFrozen(obj)\n}\n","import {\n\tImmerState,\n\tPatch,\n\tImmerScope,\n\tDrafted,\n\tAnyObject,\n\tImmerBaseState,\n\tAnyMap,\n\tAnySet,\n\tProxyType,\n\tdie\n} from \"../internal\"\n\n/** Plugin utilities */\nconst plugins: {\n\tPatches?: {\n\t\tgeneratePatches_(\n\t\t\tstate: ImmerState,\n\t\t\tbasePath: PatchPath,\n\t\t\tpatches: Patch[],\n\t\t\tinversePatches: Patch[]\n\t\t): void\n\t\tgenerateReplacementPatches_(\n\t\t\trootState: ImmerState,\n\t\t\treplacement: any,\n\t\t\tpatches: Patch[],\n\t\t\tinversePatches: Patch[]\n\t\t): void\n\t\tapplyPatches_(draft: T, patches: Patch[]): T\n\t}\n\tES5?: {\n\t\twillFinalizeES5_(scope: ImmerScope, result: any, isReplaced: boolean): void\n\t\tcreateES5Proxy_(\n\t\t\tbase: T,\n\t\t\tparent?: ImmerState\n\t\t): Drafted\n\t\thasChanges_(state: ES5ArrayState | ES5ObjectState): boolean\n\t}\n\tMapSet?: {\n\t\tproxyMap_(target: T, parent?: ImmerState): T\n\t\tproxySet_(target: T, parent?: ImmerState): T\n\t}\n} = {}\n\ntype Plugins = typeof plugins\n\nexport function getPlugin(\n\tpluginKey: K\n): Exclude {\n\tconst plugin = plugins[pluginKey]\n\tif (!plugin) {\n\t\tdie(18, pluginKey)\n\t}\n\t// @ts-ignore\n\treturn plugin\n}\n\nexport function loadPlugin(\n\tpluginKey: K,\n\timplementation: Plugins[K]\n): void {\n\tif (!plugins[pluginKey]) plugins[pluginKey] = implementation\n}\n\n/** ES5 Plugin */\n\ninterface ES5BaseState extends ImmerBaseState {\n\tassigned_: {[key: string]: any}\n\tparent_?: ImmerState\n\trevoked_: boolean\n}\n\nexport interface ES5ObjectState extends ES5BaseState {\n\ttype_: ProxyType.ES5Object\n\tdraft_: Drafted\n\tbase_: AnyObject\n\tcopy_: AnyObject | null\n}\n\nexport interface ES5ArrayState extends ES5BaseState {\n\ttype_: ProxyType.ES5Array\n\tdraft_: Drafted\n\tbase_: any\n\tcopy_: any\n}\n\n/** Map / Set plugin */\n\nexport interface MapState extends ImmerBaseState {\n\ttype_: ProxyType.Map\n\tcopy_: AnyMap | undefined\n\tassigned_: Map | undefined\n\tbase_: AnyMap\n\trevoked_: boolean\n\tdraft_: Drafted\n}\n\nexport interface SetState extends ImmerBaseState {\n\ttype_: ProxyType.Set\n\tcopy_: AnySet | undefined\n\tbase_: AnySet\n\tdrafts_: Map // maps the original value to the draft value in the new set\n\trevoked_: boolean\n\tdraft_: Drafted\n}\n\n/** Patches plugin */\n\nexport type PatchPath = (string | number)[]\n","import {\n\tPatch,\n\tPatchListener,\n\tDrafted,\n\tImmer,\n\tDRAFT_STATE,\n\tImmerState,\n\tProxyType,\n\tgetPlugin\n} from \"../internal\"\nimport {die} from \"../utils/errors\"\n\n/** Each scope represents a `produce` call. */\n\nexport interface ImmerScope {\n\tpatches_?: Patch[]\n\tinversePatches_?: Patch[]\n\tcanAutoFreeze_: boolean\n\tdrafts_: any[]\n\tparent_?: ImmerScope\n\tpatchListener_?: PatchListener\n\timmer_: Immer\n\tunfinalizedDrafts_: number\n}\n\nlet currentScope: ImmerScope | undefined\n\nexport function getCurrentScope() {\n\tif (__DEV__ && !currentScope) die(0)\n\treturn currentScope!\n}\n\nfunction createScope(\n\tparent_: ImmerScope | undefined,\n\timmer_: Immer\n): ImmerScope {\n\treturn {\n\t\tdrafts_: [],\n\t\tparent_,\n\t\timmer_,\n\t\t// Whenever the modified draft contains a draft from another scope, we\n\t\t// need to prevent auto-freezing so the unowned draft can be finalized.\n\t\tcanAutoFreeze_: true,\n\t\tunfinalizedDrafts_: 0\n\t}\n}\n\nexport function usePatchesInScope(\n\tscope: ImmerScope,\n\tpatchListener?: PatchListener\n) {\n\tif (patchListener) {\n\t\tgetPlugin(\"Patches\") // assert we have the plugin\n\t\tscope.patches_ = []\n\t\tscope.inversePatches_ = []\n\t\tscope.patchListener_ = patchListener\n\t}\n}\n\nexport function revokeScope(scope: ImmerScope) {\n\tleaveScope(scope)\n\tscope.drafts_.forEach(revokeDraft)\n\t// @ts-ignore\n\tscope.drafts_ = null\n}\n\nexport function leaveScope(scope: ImmerScope) {\n\tif (scope === currentScope) {\n\t\tcurrentScope = scope.parent_\n\t}\n}\n\nexport function enterScope(immer: Immer) {\n\treturn (currentScope = createScope(currentScope, immer))\n}\n\nfunction revokeDraft(draft: Drafted) {\n\tconst state: ImmerState = draft[DRAFT_STATE]\n\tif (\n\t\tstate.type_ === ProxyType.ProxyObject ||\n\t\tstate.type_ === ProxyType.ProxyArray\n\t)\n\t\tstate.revoke_()\n\telse state.revoked_ = true\n}\n","import {\n\tImmerScope,\n\tDRAFT_STATE,\n\tisDraftable,\n\tNOTHING,\n\tPatchPath,\n\teach,\n\thas,\n\tfreeze,\n\tImmerState,\n\tisDraft,\n\tSetState,\n\tset,\n\tProxyType,\n\tgetPlugin,\n\tdie,\n\trevokeScope,\n\tisFrozen,\n\tshallowCopy\n} from \"../internal\"\n\nexport function processResult(result: any, scope: ImmerScope) {\n\tscope.unfinalizedDrafts_ = scope.drafts_.length\n\tconst baseDraft = scope.drafts_![0]\n\tconst isReplaced = result !== undefined && result !== baseDraft\n\tif (!scope.immer_.useProxies_)\n\t\tgetPlugin(\"ES5\").willFinalizeES5_(scope, result, isReplaced)\n\tif (isReplaced) {\n\t\tif (baseDraft[DRAFT_STATE].modified_) {\n\t\t\trevokeScope(scope)\n\t\t\tdie(4)\n\t\t}\n\t\tif (isDraftable(result)) {\n\t\t\t// Finalize the result in case it contains (or is) a subset of the draft.\n\t\t\tresult = finalize(scope, result)\n\t\t\tif (!scope.parent_) maybeFreeze(scope, result)\n\t\t}\n\t\tif (scope.patches_) {\n\t\t\tgetPlugin(\"Patches\").generateReplacementPatches_(\n\t\t\t\tbaseDraft[DRAFT_STATE],\n\t\t\t\tresult,\n\t\t\t\tscope.patches_,\n\t\t\t\tscope.inversePatches_!\n\t\t\t)\n\t\t}\n\t} else {\n\t\t// Finalize the base draft.\n\t\tresult = finalize(scope, baseDraft, [])\n\t}\n\trevokeScope(scope)\n\tif (scope.patches_) {\n\t\tscope.patchListener_!(scope.patches_, scope.inversePatches_!)\n\t}\n\treturn result !== NOTHING ? result : undefined\n}\n\nfunction finalize(rootScope: ImmerScope, value: any, path?: PatchPath) {\n\t// Don't recurse in tho recursive data structures\n\tif (isFrozen(value)) return value\n\n\tconst state: ImmerState = value[DRAFT_STATE]\n\t// A plain object, might need freezing, might contain drafts\n\tif (!state) {\n\t\teach(\n\t\t\tvalue,\n\t\t\t(key, childValue) =>\n\t\t\t\tfinalizeProperty(rootScope, state, value, key, childValue, path),\n\t\t\ttrue // See #590, don't recurse into non-enumarable of non drafted objects\n\t\t)\n\t\treturn value\n\t}\n\t// Never finalize drafts owned by another scope.\n\tif (state.scope_ !== rootScope) return value\n\t// Unmodified draft, return the (frozen) original\n\tif (!state.modified_) {\n\t\tmaybeFreeze(rootScope, state.base_, true)\n\t\treturn state.base_\n\t}\n\t// Not finalized yet, let's do that now\n\tif (!state.finalized_) {\n\t\tstate.finalized_ = true\n\t\tstate.scope_.unfinalizedDrafts_--\n\t\tconst result =\n\t\t\t// For ES5, create a good copy from the draft first, with added keys and without deleted keys.\n\t\t\tstate.type_ === ProxyType.ES5Object || state.type_ === ProxyType.ES5Array\n\t\t\t\t? (state.copy_ = shallowCopy(state.draft_))\n\t\t\t\t: state.copy_\n\t\t// Finalize all children of the copy\n\t\t// For sets we clone before iterating, otherwise we can get in endless loop due to modifying during iteration, see #628\n\t\t// Although the original test case doesn't seem valid anyway, so if this in the way we can turn the next line\n\t\t// back to each(result, ....)\n\t\teach(\n\t\t\tstate.type_ === ProxyType.Set ? new Set(result) : result,\n\t\t\t(key, childValue) =>\n\t\t\t\tfinalizeProperty(rootScope, state, result, key, childValue, path)\n\t\t)\n\t\t// everything inside is frozen, we can freeze here\n\t\tmaybeFreeze(rootScope, result, false)\n\t\t// first time finalizing, let's create those patches\n\t\tif (path && rootScope.patches_) {\n\t\t\tgetPlugin(\"Patches\").generatePatches_(\n\t\t\t\tstate,\n\t\t\t\tpath,\n\t\t\t\trootScope.patches_,\n\t\t\t\trootScope.inversePatches_!\n\t\t\t)\n\t\t}\n\t}\n\treturn state.copy_\n}\n\nfunction finalizeProperty(\n\trootScope: ImmerScope,\n\tparentState: undefined | ImmerState,\n\ttargetObject: any,\n\tprop: string | number,\n\tchildValue: any,\n\trootPath?: PatchPath\n) {\n\tif (__DEV__ && childValue === targetObject) die(5)\n\tif (isDraft(childValue)) {\n\t\tconst path =\n\t\t\trootPath &&\n\t\t\tparentState &&\n\t\t\tparentState!.type_ !== ProxyType.Set && // Set objects are atomic since they have no keys.\n\t\t\t!has((parentState as Exclude).assigned_!, prop) // Skip deep patches for assigned keys.\n\t\t\t\t? rootPath!.concat(prop)\n\t\t\t\t: undefined\n\t\t// Drafts owned by `scope` are finalized here.\n\t\tconst res = finalize(rootScope, childValue, path)\n\t\tset(targetObject, prop, res)\n\t\t// Drafts from another scope must prevented to be frozen\n\t\t// if we got a draft back from finalize, we're in a nested produce and shouldn't freeze\n\t\tif (isDraft(res)) {\n\t\t\trootScope.canAutoFreeze_ = false\n\t\t} else return\n\t}\n\t// Search new objects for unfinalized drafts. Frozen objects should never contain drafts.\n\tif (isDraftable(childValue) && !isFrozen(childValue)) {\n\t\tif (!rootScope.immer_.autoFreeze_ && rootScope.unfinalizedDrafts_ < 1) {\n\t\t\t// optimization: if an object is not a draft, and we don't have to\n\t\t\t// deepfreeze everything, and we are sure that no drafts are left in the remaining object\n\t\t\t// cause we saw and finalized all drafts already; we can stop visiting the rest of the tree.\n\t\t\t// This benefits especially adding large data tree's without further processing.\n\t\t\t// See add-data.js perf test\n\t\t\treturn\n\t\t}\n\t\tfinalize(rootScope, childValue)\n\t\t// immer deep freezes plain objects, so if there is no parent state, we freeze as well\n\t\tif (!parentState || !parentState.scope_.parent_)\n\t\t\tmaybeFreeze(rootScope, childValue)\n\t}\n}\n\nfunction maybeFreeze(scope: ImmerScope, value: any, deep = false) {\n\tif (scope.immer_.autoFreeze_ && scope.canAutoFreeze_) {\n\t\tfreeze(value, deep)\n\t}\n}\n","import {\n\teach,\n\thas,\n\tis,\n\tisDraftable,\n\tshallowCopy,\n\tlatest,\n\tImmerBaseState,\n\tImmerState,\n\tDrafted,\n\tAnyObject,\n\tAnyArray,\n\tObjectish,\n\tgetCurrentScope,\n\tDRAFT_STATE,\n\tdie,\n\tcreateProxy,\n\tProxyType\n} from \"../internal\"\n\ninterface ProxyBaseState extends ImmerBaseState {\n\tassigned_: {\n\t\t[property: string]: boolean\n\t}\n\tparent_?: ImmerState\n\trevoke_(): void\n}\n\nexport interface ProxyObjectState extends ProxyBaseState {\n\ttype_: ProxyType.ProxyObject\n\tbase_: any\n\tcopy_: any\n\tdraft_: Drafted\n}\n\nexport interface ProxyArrayState extends ProxyBaseState {\n\ttype_: ProxyType.ProxyArray\n\tbase_: AnyArray\n\tcopy_: AnyArray | null\n\tdraft_: Drafted\n}\n\ntype ProxyState = ProxyObjectState | ProxyArrayState\n\n/**\n * Returns a new draft of the `base` object.\n *\n * The second argument is the parent draft-state (used internally).\n */\nexport function createProxyProxy(\n\tbase: T,\n\tparent?: ImmerState\n): Drafted {\n\tconst isArray = Array.isArray(base)\n\tconst state: ProxyState = {\n\t\ttype_: isArray ? ProxyType.ProxyArray : (ProxyType.ProxyObject as any),\n\t\t// Track which produce call this is associated with.\n\t\tscope_: parent ? parent.scope_ : getCurrentScope()!,\n\t\t// True for both shallow and deep changes.\n\t\tmodified_: false,\n\t\t// Used during finalization.\n\t\tfinalized_: false,\n\t\t// Track which properties have been assigned (true) or deleted (false).\n\t\tassigned_: {},\n\t\t// The parent draft state.\n\t\tparent_: parent,\n\t\t// The base state.\n\t\tbase_: base,\n\t\t// The base proxy.\n\t\tdraft_: null as any, // set below\n\t\t// The base copy with any updated values.\n\t\tcopy_: null,\n\t\t// Called by the `produce` function.\n\t\trevoke_: null as any,\n\t\tisManual_: false\n\t}\n\n\t// the traps must target something, a bit like the 'real' base.\n\t// but also, we need to be able to determine from the target what the relevant state is\n\t// (to avoid creating traps per instance to capture the state in closure,\n\t// and to avoid creating weird hidden properties as well)\n\t// So the trick is to use 'state' as the actual 'target'! (and make sure we intercept everything)\n\t// Note that in the case of an array, we put the state in an array to have better Reflect defaults ootb\n\tlet target: T = state as any\n\tlet traps: ProxyHandler> = objectTraps\n\tif (isArray) {\n\t\ttarget = [state] as any\n\t\ttraps = arrayTraps\n\t}\n\n\tconst {revoke, proxy} = Proxy.revocable(target, traps)\n\tstate.draft_ = proxy as any\n\tstate.revoke_ = revoke\n\treturn proxy as any\n}\n\n/**\n * Object drafts\n */\nexport const objectTraps: ProxyHandler = {\n\tget(state, prop) {\n\t\tif (prop === DRAFT_STATE) return state\n\n\t\tconst source = latest(state)\n\t\tif (!has(source, prop)) {\n\t\t\t// non-existing or non-own property...\n\t\t\treturn readPropFromProto(state, source, prop)\n\t\t}\n\t\tconst value = source[prop]\n\t\tif (state.finalized_ || !isDraftable(value)) {\n\t\t\treturn value\n\t\t}\n\t\t// Check for existing draft in modified state.\n\t\t// Assigned values are never drafted. This catches any drafts we created, too.\n\t\tif (value === peek(state.base_, prop)) {\n\t\t\tprepareCopy(state)\n\t\t\treturn (state.copy_![prop as any] = createProxy(\n\t\t\t\tstate.scope_.immer_,\n\t\t\t\tvalue,\n\t\t\t\tstate\n\t\t\t))\n\t\t}\n\t\treturn value\n\t},\n\thas(state, prop) {\n\t\treturn prop in latest(state)\n\t},\n\townKeys(state) {\n\t\treturn Reflect.ownKeys(latest(state))\n\t},\n\tset(\n\t\tstate: ProxyObjectState,\n\t\tprop: string /* strictly not, but helps TS */,\n\t\tvalue\n\t) {\n\t\tconst desc = getDescriptorFromProto(latest(state), prop)\n\t\tif (desc?.set) {\n\t\t\t// special case: if this write is captured by a setter, we have\n\t\t\t// to trigger it with the correct context\n\t\t\tdesc.set.call(state.draft_, value)\n\t\t\treturn true\n\t\t}\n\t\tif (!state.modified_) {\n\t\t\t// the last check is because we need to be able to distinguish setting a non-existing to undefined (which is a change)\n\t\t\t// from setting an existing property with value undefined to undefined (which is not a change)\n\t\t\tconst current = peek(latest(state), prop)\n\t\t\t// special case, if we assigning the original value to a draft, we can ignore the assignment\n\t\t\tconst currentState: ProxyObjectState = current?.[DRAFT_STATE]\n\t\t\tif (currentState && currentState.base_ === value) {\n\t\t\t\tstate.copy_![prop] = value\n\t\t\t\tstate.assigned_[prop] = false\n\t\t\t\treturn true\n\t\t\t}\n\t\t\tif (is(value, current) && (value !== undefined || has(state.base_, prop)))\n\t\t\t\treturn true\n\t\t\tprepareCopy(state)\n\t\t\tmarkChanged(state)\n\t\t}\n\n\t\tif (\n\t\t\tstate.copy_![prop] === value &&\n\t\t\t// special case: NaN\n\t\t\ttypeof value !== \"number\" &&\n\t\t\t// special case: handle new props with value 'undefined'\n\t\t\t(value !== undefined || prop in state.copy_)\n\t\t)\n\t\t\treturn true\n\n\t\t// @ts-ignore\n\t\tstate.copy_![prop] = value\n\t\tstate.assigned_[prop] = true\n\t\treturn true\n\t},\n\tdeleteProperty(state, prop: string) {\n\t\t// The `undefined` check is a fast path for pre-existing keys.\n\t\tif (peek(state.base_, prop) !== undefined || prop in state.base_) {\n\t\t\tstate.assigned_[prop] = false\n\t\t\tprepareCopy(state)\n\t\t\tmarkChanged(state)\n\t\t} else {\n\t\t\t// if an originally not assigned property was deleted\n\t\t\tdelete state.assigned_[prop]\n\t\t}\n\t\t// @ts-ignore\n\t\tif (state.copy_) delete state.copy_[prop]\n\t\treturn true\n\t},\n\t// Note: We never coerce `desc.value` into an Immer draft, because we can't make\n\t// the same guarantee in ES5 mode.\n\tgetOwnPropertyDescriptor(state, prop) {\n\t\tconst owner = latest(state)\n\t\tconst desc = Reflect.getOwnPropertyDescriptor(owner, prop)\n\t\tif (!desc) return desc\n\t\treturn {\n\t\t\twritable: true,\n\t\t\tconfigurable: state.type_ !== ProxyType.ProxyArray || prop !== \"length\",\n\t\t\tenumerable: desc.enumerable,\n\t\t\tvalue: owner[prop]\n\t\t}\n\t},\n\tdefineProperty() {\n\t\tdie(11)\n\t},\n\tgetPrototypeOf(state) {\n\t\treturn Object.getPrototypeOf(state.base_)\n\t},\n\tsetPrototypeOf() {\n\t\tdie(12)\n\t}\n}\n\n/**\n * Array drafts\n */\n\nconst arrayTraps: ProxyHandler<[ProxyArrayState]> = {}\neach(objectTraps, (key, fn) => {\n\t// @ts-ignore\n\tarrayTraps[key] = function() {\n\t\targuments[0] = arguments[0][0]\n\t\treturn fn.apply(this, arguments)\n\t}\n})\narrayTraps.deleteProperty = function(state, prop) {\n\tif (__DEV__ && isNaN(parseInt(prop as any))) die(13)\n\treturn objectTraps.deleteProperty!.call(this, state[0], prop)\n}\narrayTraps.set = function(state, prop, value) {\n\tif (__DEV__ && prop !== \"length\" && isNaN(parseInt(prop as any))) die(14)\n\treturn objectTraps.set!.call(this, state[0], prop, value, state[0])\n}\n\n// Access a property without creating an Immer draft.\nfunction peek(draft: Drafted, prop: PropertyKey) {\n\tconst state = draft[DRAFT_STATE]\n\tconst source = state ? latest(state) : draft\n\treturn source[prop]\n}\n\nfunction readPropFromProto(state: ImmerState, source: any, prop: PropertyKey) {\n\tconst desc = getDescriptorFromProto(source, prop)\n\treturn desc\n\t\t? `value` in desc\n\t\t\t? desc.value\n\t\t\t: // This is a very special case, if the prop is a getter defined by the\n\t\t\t // prototype, we should invoke it with the draft as context!\n\t\t\t desc.get?.call(state.draft_)\n\t\t: undefined\n}\n\nfunction getDescriptorFromProto(\n\tsource: any,\n\tprop: PropertyKey\n): PropertyDescriptor | undefined {\n\t// 'in' checks proto!\n\tif (!(prop in source)) return undefined\n\tlet proto = Object.getPrototypeOf(source)\n\twhile (proto) {\n\t\tconst desc = Object.getOwnPropertyDescriptor(proto, prop)\n\t\tif (desc) return desc\n\t\tproto = Object.getPrototypeOf(proto)\n\t}\n\treturn undefined\n}\n\nexport function markChanged(state: ImmerState) {\n\tif (!state.modified_) {\n\t\tstate.modified_ = true\n\t\tif (state.parent_) {\n\t\t\tmarkChanged(state.parent_)\n\t\t}\n\t}\n}\n\nexport function prepareCopy(state: {base_: any; copy_: any}) {\n\tif (!state.copy_) {\n\t\tstate.copy_ = shallowCopy(state.base_)\n\t}\n}\n","import {\n\tIProduceWithPatches,\n\tIProduce,\n\tImmerState,\n\tDrafted,\n\tisDraftable,\n\tprocessResult,\n\tPatch,\n\tObjectish,\n\tDRAFT_STATE,\n\tDraft,\n\tPatchListener,\n\tisDraft,\n\tisMap,\n\tisSet,\n\tcreateProxyProxy,\n\tgetPlugin,\n\tdie,\n\thasProxies,\n\tenterScope,\n\trevokeScope,\n\tleaveScope,\n\tusePatchesInScope,\n\tgetCurrentScope,\n\tNOTHING,\n\tfreeze,\n\tcurrent\n} from \"../internal\"\n\ninterface ProducersFns {\n\tproduce: IProduce\n\tproduceWithPatches: IProduceWithPatches\n}\n\nexport class Immer implements ProducersFns {\n\tuseProxies_: boolean = hasProxies\n\n\tautoFreeze_: boolean = true\n\n\tconstructor(config?: {useProxies?: boolean; autoFreeze?: boolean}) {\n\t\tif (typeof config?.useProxies === \"boolean\")\n\t\t\tthis.setUseProxies(config!.useProxies)\n\t\tif (typeof config?.autoFreeze === \"boolean\")\n\t\t\tthis.setAutoFreeze(config!.autoFreeze)\n\t}\n\n\t/**\n\t * The `produce` function takes a value and a \"recipe function\" (whose\n\t * return value often depends on the base state). The recipe function is\n\t * free to mutate its first argument however it wants. All mutations are\n\t * only ever applied to a __copy__ of the base state.\n\t *\n\t * Pass only a function to create a \"curried producer\" which relieves you\n\t * from passing the recipe function every time.\n\t *\n\t * Only plain objects and arrays are made mutable. All other objects are\n\t * considered uncopyable.\n\t *\n\t * Note: This function is __bound__ to its `Immer` instance.\n\t *\n\t * @param {any} base - the initial state\n\t * @param {Function} producer - function that receives a proxy of the base state as first argument and which can be freely modified\n\t * @param {Function} patchListener - optional function that will be called with all the patches produced here\n\t * @returns {any} a new state, or the initial state if nothing was modified\n\t */\n\tproduce: IProduce = (base: any, recipe?: any, patchListener?: any) => {\n\t\t// curried invocation\n\t\tif (typeof base === \"function\" && typeof recipe !== \"function\") {\n\t\t\tconst defaultBase = recipe\n\t\t\trecipe = base\n\n\t\t\tconst self = this\n\t\t\treturn function curriedProduce(\n\t\t\t\tthis: any,\n\t\t\t\tbase = defaultBase,\n\t\t\t\t...args: any[]\n\t\t\t) {\n\t\t\t\treturn self.produce(base, (draft: Drafted) => recipe.call(this, draft, ...args)) // prettier-ignore\n\t\t\t}\n\t\t}\n\n\t\tif (typeof recipe !== \"function\") die(6)\n\t\tif (patchListener !== undefined && typeof patchListener !== \"function\")\n\t\t\tdie(7)\n\n\t\tlet result\n\n\t\t// Only plain objects, arrays, and \"immerable classes\" are drafted.\n\t\tif (isDraftable(base)) {\n\t\t\tconst scope = enterScope(this)\n\t\t\tconst proxy = createProxy(this, base, undefined)\n\t\t\tlet hasError = true\n\t\t\ttry {\n\t\t\t\tresult = recipe(proxy)\n\t\t\t\thasError = false\n\t\t\t} finally {\n\t\t\t\t// finally instead of catch + rethrow better preserves original stack\n\t\t\t\tif (hasError) revokeScope(scope)\n\t\t\t\telse leaveScope(scope)\n\t\t\t}\n\t\t\tif (typeof Promise !== \"undefined\" && result instanceof Promise) {\n\t\t\t\treturn result.then(\n\t\t\t\t\tresult => {\n\t\t\t\t\t\tusePatchesInScope(scope, patchListener)\n\t\t\t\t\t\treturn processResult(result, scope)\n\t\t\t\t\t},\n\t\t\t\t\terror => {\n\t\t\t\t\t\trevokeScope(scope)\n\t\t\t\t\t\tthrow error\n\t\t\t\t\t}\n\t\t\t\t)\n\t\t\t}\n\t\t\tusePatchesInScope(scope, patchListener)\n\t\t\treturn processResult(result, scope)\n\t\t} else if (!base || typeof base !== \"object\") {\n\t\t\tresult = recipe(base)\n\t\t\tif (result === NOTHING) return undefined\n\t\t\tif (result === undefined) result = base\n\t\t\tif (this.autoFreeze_) freeze(result, true)\n\t\t\treturn result\n\t\t} else die(21, base)\n\t}\n\n\tproduceWithPatches: IProduceWithPatches = (\n\t\targ1: any,\n\t\targ2?: any,\n\t\targ3?: any\n\t): any => {\n\t\tif (typeof arg1 === \"function\") {\n\t\t\treturn (state: any, ...args: any[]) =>\n\t\t\t\tthis.produceWithPatches(state, (draft: any) => arg1(draft, ...args))\n\t\t}\n\n\t\tlet patches: Patch[], inversePatches: Patch[]\n\t\tconst nextState = this.produce(arg1, arg2, (p: Patch[], ip: Patch[]) => {\n\t\t\tpatches = p\n\t\t\tinversePatches = ip\n\t\t})\n\t\treturn [nextState, patches!, inversePatches!]\n\t}\n\n\tcreateDraft(base: T): Draft {\n\t\tif (!isDraftable(base)) die(8)\n\t\tif (isDraft(base)) base = current(base)\n\t\tconst scope = enterScope(this)\n\t\tconst proxy = createProxy(this, base, undefined)\n\t\tproxy[DRAFT_STATE].isManual_ = true\n\t\tleaveScope(scope)\n\t\treturn proxy as any\n\t}\n\n\tfinishDraft>(\n\t\tdraft: D,\n\t\tpatchListener?: PatchListener\n\t): D extends Draft ? T : never {\n\t\tconst state: ImmerState = draft && (draft as any)[DRAFT_STATE]\n\t\tif (__DEV__) {\n\t\t\tif (!state || !state.isManual_) die(9)\n\t\t\tif (state.finalized_) die(10)\n\t\t}\n\t\tconst {scope_: scope} = state\n\t\tusePatchesInScope(scope, patchListener)\n\t\treturn processResult(undefined, scope)\n\t}\n\n\t/**\n\t * Pass true to automatically freeze all copies created by Immer.\n\t *\n\t * By default, auto-freezing is enabled.\n\t */\n\tsetAutoFreeze(value: boolean) {\n\t\tthis.autoFreeze_ = value\n\t}\n\n\t/**\n\t * Pass true to use the ES2015 `Proxy` class when creating drafts, which is\n\t * always faster than using ES5 proxies.\n\t *\n\t * By default, feature detection is used, so calling this is rarely necessary.\n\t */\n\tsetUseProxies(value: boolean) {\n\t\tif (value && !hasProxies) {\n\t\t\tdie(20)\n\t\t}\n\t\tthis.useProxies_ = value\n\t}\n\n\tapplyPatches(base: T, patches: Patch[]): T {\n\t\t// If a patch replaces the entire state, take that replacement as base\n\t\t// before applying patches\n\t\tlet i: number\n\t\tfor (i = patches.length - 1; i >= 0; i--) {\n\t\t\tconst patch = patches[i]\n\t\t\tif (patch.path.length === 0 && patch.op === \"replace\") {\n\t\t\t\tbase = patch.value\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\tconst applyPatchesImpl = getPlugin(\"Patches\").applyPatches_\n\t\tif (isDraft(base)) {\n\t\t\t// N.B: never hits if some patch a replacement, patches are never drafts\n\t\t\treturn applyPatchesImpl(base, patches) as any\n\t\t}\n\t\t// Otherwise, produce a copy of the base state.\n\t\treturn this.produce(base, (draft: Drafted) =>\n\t\t\tapplyPatchesImpl(draft, patches.slice(i + 1))\n\t\t) as any\n\t}\n}\n\nexport function createProxy(\n\timmer: Immer,\n\tvalue: T,\n\tparent?: ImmerState\n): Drafted {\n\t// precondition: createProxy should be guarded by isDraftable, so we know we can safely draft\n\tconst draft: Drafted = isMap(value)\n\t\t? getPlugin(\"MapSet\").proxyMap_(value, parent)\n\t\t: isSet(value)\n\t\t? getPlugin(\"MapSet\").proxySet_(value, parent)\n\t\t: immer.useProxies_\n\t\t? createProxyProxy(value, parent)\n\t\t: getPlugin(\"ES5\").createES5Proxy_(value, parent)\n\n\tconst scope = parent ? parent.scope_ : getCurrentScope()\n\tscope.drafts_.push(draft)\n\treturn draft\n}\n","import {\n\tdie,\n\tisDraft,\n\tshallowCopy,\n\teach,\n\tDRAFT_STATE,\n\tget,\n\tset,\n\tImmerState,\n\tisDraftable,\n\tArchtype,\n\tgetArchtype,\n\tgetPlugin\n} from \"../internal\"\n\n/** Takes a snapshot of the current state of a draft and finalizes it (but without freezing). This is a great utility to print the current state during debugging (no Proxies in the way). The output of current can also be safely leaked outside the producer. */\nexport function current(value: T): T\nexport function current(value: any): any {\n\tif (!isDraft(value)) die(22, value)\n\treturn currentImpl(value)\n}\n\nfunction currentImpl(value: any): any {\n\tif (!isDraftable(value)) return value\n\tconst state: ImmerState | undefined = value[DRAFT_STATE]\n\tlet copy: any\n\tconst archType = getArchtype(value)\n\tif (state) {\n\t\tif (\n\t\t\t!state.modified_ &&\n\t\t\t(state.type_ < 4 || !getPlugin(\"ES5\").hasChanges_(state as any))\n\t\t)\n\t\t\treturn state.base_\n\t\t// Optimization: avoid generating new drafts during copying\n\t\tstate.finalized_ = true\n\t\tcopy = copyHelper(value, archType)\n\t\tstate.finalized_ = false\n\t} else {\n\t\tcopy = copyHelper(value, archType)\n\t}\n\n\teach(copy, (key, childValue) => {\n\t\tif (state && get(state.base_, key) === childValue) return // no need to copy or search in something that didn't change\n\t\tset(copy, key, currentImpl(childValue))\n\t})\n\t// In the future, we might consider freezing here, based on the current settings\n\treturn archType === Archtype.Set ? new Set(copy) : copy\n}\n\nfunction copyHelper(value: any, archType: number): any {\n\t// creates a shallow copy, even if it is a map or set\n\tswitch (archType) {\n\t\tcase Archtype.Map:\n\t\t\treturn new Map(value)\n\t\tcase Archtype.Set:\n\t\t\t// Set will be cloned as array temporarily, so that we can replace individual items\n\t\t\treturn Array.from(value)\n\t}\n\treturn shallowCopy(value)\n}\n","import {\n\tImmerState,\n\tDrafted,\n\tES5ArrayState,\n\tES5ObjectState,\n\teach,\n\thas,\n\tisDraft,\n\tlatest,\n\tDRAFT_STATE,\n\tis,\n\tloadPlugin,\n\tImmerScope,\n\tProxyType,\n\tgetCurrentScope,\n\tdie,\n\tmarkChanged,\n\tobjectTraps,\n\townKeys,\n\tgetOwnPropertyDescriptors\n} from \"../internal\"\n\ntype ES5State = ES5ArrayState | ES5ObjectState\n\nexport function enableES5() {\n\tfunction willFinalizeES5_(\n\t\tscope: ImmerScope,\n\t\tresult: any,\n\t\tisReplaced: boolean\n\t) {\n\t\tif (!isReplaced) {\n\t\t\tif (scope.patches_) {\n\t\t\t\tmarkChangesRecursively(scope.drafts_![0])\n\t\t\t}\n\t\t\t// This is faster when we don't care about which attributes changed.\n\t\t\tmarkChangesSweep(scope.drafts_)\n\t\t}\n\t\t// When a child draft is returned, look for changes.\n\t\telse if (\n\t\t\tisDraft(result) &&\n\t\t\t(result[DRAFT_STATE] as ES5State).scope_ === scope\n\t\t) {\n\t\t\tmarkChangesSweep(scope.drafts_)\n\t\t}\n\t}\n\n\tfunction createES5Draft(isArray: boolean, base: any) {\n\t\tif (isArray) {\n\t\t\tconst draft = new Array(base.length)\n\t\t\tfor (let i = 0; i < base.length; i++)\n\t\t\t\tObject.defineProperty(draft, \"\" + i, proxyProperty(i, true))\n\t\t\treturn draft\n\t\t} else {\n\t\t\tconst descriptors = getOwnPropertyDescriptors(base)\n\t\t\tdelete descriptors[DRAFT_STATE as any]\n\t\t\tconst keys = ownKeys(descriptors)\n\t\t\tfor (let i = 0; i < keys.length; i++) {\n\t\t\t\tconst key: any = keys[i]\n\t\t\t\tdescriptors[key] = proxyProperty(\n\t\t\t\t\tkey,\n\t\t\t\t\tisArray || !!descriptors[key].enumerable\n\t\t\t\t)\n\t\t\t}\n\t\t\treturn Object.create(Object.getPrototypeOf(base), descriptors)\n\t\t}\n\t}\n\n\tfunction createES5Proxy_(\n\t\tbase: T,\n\t\tparent?: ImmerState\n\t): Drafted {\n\t\tconst isArray = Array.isArray(base)\n\t\tconst draft = createES5Draft(isArray, base)\n\n\t\tconst state: ES5ObjectState | ES5ArrayState = {\n\t\t\ttype_: isArray ? ProxyType.ES5Array : (ProxyType.ES5Object as any),\n\t\t\tscope_: parent ? parent.scope_ : getCurrentScope(),\n\t\t\tmodified_: false,\n\t\t\tfinalized_: false,\n\t\t\tassigned_: {},\n\t\t\tparent_: parent,\n\t\t\t// base is the object we are drafting\n\t\t\tbase_: base,\n\t\t\t// draft is the draft object itself, that traps all reads and reads from either the base (if unmodified) or copy (if modified)\n\t\t\tdraft_: draft,\n\t\t\tcopy_: null,\n\t\t\trevoked_: false,\n\t\t\tisManual_: false\n\t\t}\n\n\t\tObject.defineProperty(draft, DRAFT_STATE, {\n\t\t\tvalue: state,\n\t\t\t// enumerable: false <- the default\n\t\t\twritable: true\n\t\t})\n\t\treturn draft\n\t}\n\n\t// property descriptors are recycled to make sure we don't create a get and set closure per property,\n\t// but share them all instead\n\tconst descriptors: {[prop: string]: PropertyDescriptor} = {}\n\n\tfunction proxyProperty(\n\t\tprop: string | number,\n\t\tenumerable: boolean\n\t): PropertyDescriptor {\n\t\tlet desc = descriptors[prop]\n\t\tif (desc) {\n\t\t\tdesc.enumerable = enumerable\n\t\t} else {\n\t\t\tdescriptors[prop] = desc = {\n\t\t\t\tconfigurable: true,\n\t\t\t\tenumerable,\n\t\t\t\tget(this: any) {\n\t\t\t\t\tconst state = this[DRAFT_STATE]\n\t\t\t\t\tif (__DEV__) assertUnrevoked(state)\n\t\t\t\t\t// @ts-ignore\n\t\t\t\t\treturn objectTraps.get(state, prop)\n\t\t\t\t},\n\t\t\t\tset(this: any, value) {\n\t\t\t\t\tconst state = this[DRAFT_STATE]\n\t\t\t\t\tif (__DEV__) assertUnrevoked(state)\n\t\t\t\t\t// @ts-ignore\n\t\t\t\t\tobjectTraps.set(state, prop, value)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn desc\n\t}\n\n\t// This looks expensive, but only proxies are visited, and only objects without known changes are scanned.\n\tfunction markChangesSweep(drafts: Drafted[]) {\n\t\t// The natural order of drafts in the `scope` array is based on when they\n\t\t// were accessed. By processing drafts in reverse natural order, we have a\n\t\t// better chance of processing leaf nodes first. When a leaf node is known to\n\t\t// have changed, we can avoid any traversal of its ancestor nodes.\n\t\tfor (let i = drafts.length - 1; i >= 0; i--) {\n\t\t\tconst state: ES5State = drafts[i][DRAFT_STATE]\n\t\t\tif (!state.modified_) {\n\t\t\t\tswitch (state.type_) {\n\t\t\t\t\tcase ProxyType.ES5Array:\n\t\t\t\t\t\tif (hasArrayChanges(state)) markChanged(state)\n\t\t\t\t\t\tbreak\n\t\t\t\t\tcase ProxyType.ES5Object:\n\t\t\t\t\t\tif (hasObjectChanges(state)) markChanged(state)\n\t\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tfunction markChangesRecursively(object: any) {\n\t\tif (!object || typeof object !== \"object\") return\n\t\tconst state: ES5State | undefined = object[DRAFT_STATE]\n\t\tif (!state) return\n\t\tconst {base_, draft_, assigned_, type_} = state\n\t\tif (type_ === ProxyType.ES5Object) {\n\t\t\t// Look for added keys.\n\t\t\t// probably there is a faster way to detect changes, as sweep + recurse seems to do some\n\t\t\t// unnecessary work.\n\t\t\t// also: probably we can store the information we detect here, to speed up tree finalization!\n\t\t\teach(draft_, key => {\n\t\t\t\tif ((key as any) === DRAFT_STATE) return\n\t\t\t\t// The `undefined` check is a fast path for pre-existing keys.\n\t\t\t\tif ((base_ as any)[key] === undefined && !has(base_, key)) {\n\t\t\t\t\tassigned_[key] = true\n\t\t\t\t\tmarkChanged(state)\n\t\t\t\t} else if (!assigned_[key]) {\n\t\t\t\t\t// Only untouched properties trigger recursion.\n\t\t\t\t\tmarkChangesRecursively(draft_[key])\n\t\t\t\t}\n\t\t\t})\n\t\t\t// Look for removed keys.\n\t\t\teach(base_, key => {\n\t\t\t\t// The `undefined` check is a fast path for pre-existing keys.\n\t\t\t\tif (draft_[key] === undefined && !has(draft_, key)) {\n\t\t\t\t\tassigned_[key] = false\n\t\t\t\t\tmarkChanged(state)\n\t\t\t\t}\n\t\t\t})\n\t\t} else if (type_ === ProxyType.ES5Array) {\n\t\t\tif (hasArrayChanges(state as ES5ArrayState)) {\n\t\t\t\tmarkChanged(state)\n\t\t\t\tassigned_.length = true\n\t\t\t}\n\n\t\t\tif (draft_.length < base_.length) {\n\t\t\t\tfor (let i = draft_.length; i < base_.length; i++) assigned_[i] = false\n\t\t\t} else {\n\t\t\t\tfor (let i = base_.length; i < draft_.length; i++) assigned_[i] = true\n\t\t\t}\n\n\t\t\t// Minimum count is enough, the other parts has been processed.\n\t\t\tconst min = Math.min(draft_.length, base_.length)\n\n\t\t\tfor (let i = 0; i < min; i++) {\n\t\t\t\t// Only untouched indices trigger recursion.\n\t\t\t\tif (assigned_[i] === undefined) markChangesRecursively(draft_[i])\n\t\t\t}\n\t\t}\n\t}\n\n\tfunction hasObjectChanges(state: ES5ObjectState) {\n\t\tconst {base_, draft_} = state\n\n\t\t// Search for added keys and changed keys. Start at the back, because\n\t\t// non-numeric keys are ordered by time of definition on the object.\n\t\tconst keys = ownKeys(draft_)\n\t\tfor (let i = keys.length - 1; i >= 0; i--) {\n\t\t\tconst key: any = keys[i]\n\t\t\tif (key === DRAFT_STATE) continue\n\t\t\tconst baseValue = base_[key]\n\t\t\t// The `undefined` check is a fast path for pre-existing keys.\n\t\t\tif (baseValue === undefined && !has(base_, key)) {\n\t\t\t\treturn true\n\t\t\t}\n\t\t\t// Once a base key is deleted, future changes go undetected, because its\n\t\t\t// descriptor is erased. This branch detects any missed changes.\n\t\t\telse {\n\t\t\t\tconst value = draft_[key]\n\t\t\t\tconst state: ImmerState = value && value[DRAFT_STATE]\n\t\t\t\tif (state ? state.base_ !== baseValue : !is(value, baseValue)) {\n\t\t\t\t\treturn true\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// At this point, no keys were added or changed.\n\t\t// Compare key count to determine if keys were deleted.\n\t\tconst baseIsDraft = !!base_[DRAFT_STATE as any]\n\t\treturn keys.length !== ownKeys(base_).length + (baseIsDraft ? 0 : 1) // + 1 to correct for DRAFT_STATE\n\t}\n\n\tfunction hasArrayChanges(state: ES5ArrayState) {\n\t\tconst {draft_} = state\n\t\tif (draft_.length !== state.base_.length) return true\n\t\t// See #116\n\t\t// If we first shorten the length, our array interceptors will be removed.\n\t\t// If after that new items are added, result in the same original length,\n\t\t// those last items will have no intercepting property.\n\t\t// So if there is no own descriptor on the last position, we know that items were removed and added\n\t\t// N.B.: splice, unshift, etc only shift values around, but not prop descriptors, so we only have to check\n\t\t// the last one\n\t\tconst descriptor = Object.getOwnPropertyDescriptor(\n\t\t\tdraft_,\n\t\t\tdraft_.length - 1\n\t\t)\n\t\t// descriptor can be null, but only for newly created sparse arrays, eg. new Array(10)\n\t\tif (descriptor && !descriptor.get) return true\n\t\t// For all other cases, we don't have to compare, as they would have been picked up by the index setters\n\t\treturn false\n\t}\n\n\tfunction hasChanges_(state: ES5State) {\n\t\treturn state.type_ === ProxyType.ES5Object\n\t\t\t? hasObjectChanges(state)\n\t\t\t: hasArrayChanges(state)\n\t}\n\n\tfunction assertUnrevoked(state: any /*ES5State | MapState | SetState*/) {\n\t\tif (state.revoked_) die(3, JSON.stringify(latest(state)))\n\t}\n\n\tloadPlugin(\"ES5\", {\n\t\tcreateES5Proxy_,\n\t\twillFinalizeES5_,\n\t\thasChanges_\n\t})\n}\n","import {\n\tIProduce,\n\tIProduceWithPatches,\n\tImmer,\n\tDraft,\n\tImmutable\n} from \"./internal\"\n\nexport {\n\tDraft,\n\tImmutable,\n\tPatch,\n\tPatchListener,\n\toriginal,\n\tcurrent,\n\tisDraft,\n\tisDraftable,\n\tNOTHING as nothing,\n\tDRAFTABLE as immerable,\n\tfreeze\n} from \"./internal\"\n\nconst immer = new Immer()\n\n/**\n * The `produce` function takes a value and a \"recipe function\" (whose\n * return value often depends on the base state). The recipe function is\n * free to mutate its first argument however it wants. All mutations are\n * only ever applied to a __copy__ of the base state.\n *\n * Pass only a function to create a \"curried producer\" which relieves you\n * from passing the recipe function every time.\n *\n * Only plain objects and arrays are made mutable. All other objects are\n * considered uncopyable.\n *\n * Note: This function is __bound__ to its `Immer` instance.\n *\n * @param {any} base - the initial state\n * @param {Function} producer - function that receives a proxy of the base state as first argument and which can be freely modified\n * @param {Function} patchListener - optional function that will be called with all the patches produced here\n * @returns {any} a new state, or the initial state if nothing was modified\n */\nexport const produce: IProduce = immer.produce\nexport default produce\n\n/**\n * Like `produce`, but `produceWithPatches` always returns a tuple\n * [nextState, patches, inversePatches] (instead of just the next state)\n */\nexport const produceWithPatches: IProduceWithPatches = immer.produceWithPatches.bind(\n\timmer\n)\n\n/**\n * Pass true to automatically freeze all copies created by Immer.\n *\n * Always freeze by default, even in production mode\n */\nexport const setAutoFreeze = immer.setAutoFreeze.bind(immer)\n\n/**\n * Pass true to use the ES2015 `Proxy` class when creating drafts, which is\n * always faster than using ES5 proxies.\n *\n * By default, feature detection is used, so calling this is rarely necessary.\n */\nexport const setUseProxies = immer.setUseProxies.bind(immer)\n\n/**\n * Apply an array of Immer patches to the first argument.\n *\n * This function is a producer, which means copy-on-write is in effect.\n */\nexport const applyPatches = immer.applyPatches.bind(immer)\n\n/**\n * Create an Immer draft from the given base state, which may be a draft itself.\n * The draft can be modified until you finalize it with the `finishDraft` function.\n */\nexport const createDraft = immer.createDraft.bind(immer)\n\n/**\n * Finalize an Immer draft from a `createDraft` call, returning the base state\n * (if no changes were made) or a modified copy. The draft must *not* be\n * mutated afterwards.\n *\n * Pass a function as the 2nd argument to generate Immer patches based on the\n * changes that were made.\n */\nexport const finishDraft = immer.finishDraft.bind(immer)\n\n/**\n * This function is actually a no-op, but can be used to cast an immutable type\n * to an draft type and make TypeScript happy\n *\n * @param value\n */\nexport function castDraft(value: T): Draft {\n\treturn value as any\n}\n\n/**\n * This function is actually a no-op, but can be used to cast a mutable type\n * to an immutable type and make TypeScript happy\n * @param value\n */\nexport function castImmutable(value: T): Immutable {\n\treturn value as any\n}\n\nexport {Immer}\n\nexport {enableES5} from \"./plugins/es5\"\nexport {enablePatches} from \"./plugins/patches\"\nexport {enableMapSet} from \"./plugins/mapset\"\nexport {enableAllPlugins} from \"./plugins/all\"\n","// Should be no imports here!\n\n// Some things that should be evaluated before all else...\n\n// We only want to know if non-polyfilled symbols are available\nconst hasSymbol =\n\ttypeof Symbol !== \"undefined\" && typeof Symbol(\"x\") === \"symbol\"\nexport const hasMap = typeof Map !== \"undefined\"\nexport const hasSet = typeof Set !== \"undefined\"\nexport const hasProxies =\n\ttypeof Proxy !== \"undefined\" &&\n\ttypeof Proxy.revocable !== \"undefined\" &&\n\ttypeof Reflect !== \"undefined\"\n\n/**\n * The sentinel value returned by producers to replace the draft with undefined.\n */\nexport const NOTHING: Nothing = hasSymbol\n\t? Symbol.for(\"immer-nothing\")\n\t: ({[\"immer-nothing\"]: true} as any)\n\n/**\n * To let Immer treat your class instances as plain immutable objects\n * (albeit with a custom prototype), you must define either an instance property\n * or a static property on each of your custom classes.\n *\n * Otherwise, your class instance will never be drafted, which means it won't be\n * safe to mutate in a produce callback.\n */\nexport const DRAFTABLE: unique symbol = hasSymbol\n\t? Symbol.for(\"immer-draftable\")\n\t: (\"__$immer_draftable\" as any)\n\nexport const DRAFT_STATE: unique symbol = hasSymbol\n\t? Symbol.for(\"immer-state\")\n\t: (\"__$immer_state\" as any)\n\n// Even a polyfilled Symbol might provide Symbol.iterator\nexport const iteratorSymbol: typeof Symbol.iterator =\n\t(typeof Symbol != \"undefined\" && Symbol.iterator) || (\"@@iterator\" as any)\n\n/** Use a class type for `nothing` so its type is unique */\nexport class Nothing {\n\t// This lets us do `Exclude`\n\t// @ts-ignore\n\tprivate _!: unique symbol\n}\n","var __extends = (this && this.__extends) || (function () {\r\n var extendStatics = function (d, b) {\r\n extendStatics = Object.setPrototypeOf ||\r\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\r\n function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };\r\n return extendStatics(d, b);\r\n };\r\n return function (d, b) {\r\n if (typeof b !== \"function\" && b !== null)\r\n throw new TypeError(\"Class extends value \" + String(b) + \" is not a constructor or null\");\r\n extendStatics(d, b);\r\n function __() { this.constructor = d; }\r\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\r\n };\r\n})();\r\nvar __generator = (this && this.__generator) || function (thisArg, body) {\r\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;\r\n return g = { next: verb(0), \"throw\": verb(1), \"return\": verb(2) }, typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\r\n function verb(n) { return function (v) { return step([n, v]); }; }\r\n function step(op) {\r\n if (f) throw new TypeError(\"Generator is already executing.\");\r\n while (_) try {\r\n if (f = 1, y && (t = op[0] & 2 ? y[\"return\"] : op[0] ? y[\"throw\"] || ((t = y[\"return\"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;\r\n if (y = 0, t) op = [op[0] & 2, t.value];\r\n switch (op[0]) {\r\n case 0: case 1: t = op; break;\r\n case 4: _.label++; return { value: op[1], done: false };\r\n case 5: _.label++; y = op[1]; op = [0]; continue;\r\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\r\n default:\r\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\r\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\r\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\r\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\r\n if (t[2]) _.ops.pop();\r\n _.trys.pop(); continue;\r\n }\r\n op = body.call(thisArg, _);\r\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\r\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\r\n }\r\n};\r\nvar __spreadArray = (this && this.__spreadArray) || function (to, from) {\r\n for (var i = 0, il = from.length, j = to.length; i < il; i++, j++)\r\n to[j] = from[i];\r\n return to;\r\n};\r\nvar __defProp = Object.defineProperty;\r\nvar __defProps = Object.defineProperties;\r\nvar __getOwnPropDescs = Object.getOwnPropertyDescriptors;\r\nvar __getOwnPropSymbols = Object.getOwnPropertySymbols;\r\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\r\nvar __propIsEnum = Object.prototype.propertyIsEnumerable;\r\nvar __defNormalProp = function (obj, key, value) { return key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value: value }) : obj[key] = value; };\r\nvar __spreadValues = function (a, b) {\r\n for (var prop in b || (b = {}))\r\n if (__hasOwnProp.call(b, prop))\r\n __defNormalProp(a, prop, b[prop]);\r\n if (__getOwnPropSymbols)\r\n for (var _i = 0, _b = __getOwnPropSymbols(b); _i < _b.length; _i++) {\r\n var prop = _b[_i];\r\n if (__propIsEnum.call(b, prop))\r\n __defNormalProp(a, prop, b[prop]);\r\n }\r\n return a;\r\n};\r\nvar __spreadProps = function (a, b) { return __defProps(a, __getOwnPropDescs(b)); };\r\nvar __async = function (__this, __arguments, generator) {\r\n return new Promise(function (resolve, reject) {\r\n var fulfilled = function (value) {\r\n try {\r\n step(generator.next(value));\r\n }\r\n catch (e) {\r\n reject(e);\r\n }\r\n };\r\n var rejected = function (value) {\r\n try {\r\n step(generator.throw(value));\r\n }\r\n catch (e) {\r\n reject(e);\r\n }\r\n };\r\n var step = function (x) { return x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected); };\r\n step((generator = generator.apply(__this, __arguments)).next());\r\n });\r\n};\r\n// src/index.ts\r\nimport { enableES5 } from \"immer\";\r\nexport * from \"redux\";\r\nimport { default as default2, current as current2, freeze, original, isDraft as isDraft4 } from \"immer\";\r\nimport { createSelector as createSelector2 } from \"reselect\";\r\n// src/createDraftSafeSelector.ts\r\nimport { current, isDraft } from \"immer\";\r\nimport { createSelector } from \"reselect\";\r\nvar createDraftSafeSelector = function () {\r\n var args = [];\r\n for (var _i = 0; _i < arguments.length; _i++) {\r\n args[_i] = arguments[_i];\r\n }\r\n var selector = createSelector.apply(void 0, args);\r\n var wrappedSelector = function (value) {\r\n var rest = [];\r\n for (var _i = 1; _i < arguments.length; _i++) {\r\n rest[_i - 1] = arguments[_i];\r\n }\r\n return selector.apply(void 0, __spreadArray([isDraft(value) ? current(value) : value], rest));\r\n };\r\n return wrappedSelector;\r\n};\r\n// src/configureStore.ts\r\nimport { createStore, compose as compose2, applyMiddleware, combineReducers } from \"redux\";\r\n// src/devtoolsExtension.ts\r\nimport { compose } from \"redux\";\r\nvar composeWithDevTools = typeof window !== \"undefined\" && window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ ? window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ : function () {\r\n if (arguments.length === 0)\r\n return void 0;\r\n if (typeof arguments[0] === \"object\")\r\n return compose;\r\n return compose.apply(null, arguments);\r\n};\r\nvar devToolsEnhancer = typeof window !== \"undefined\" && window.__REDUX_DEVTOOLS_EXTENSION__ ? window.__REDUX_DEVTOOLS_EXTENSION__ : function () {\r\n return function (noop) {\r\n return noop;\r\n };\r\n};\r\n// src/isPlainObject.ts\r\nfunction isPlainObject(value) {\r\n if (typeof value !== \"object\" || value === null)\r\n return false;\r\n var proto = value;\r\n while (Object.getPrototypeOf(proto) !== null) {\r\n proto = Object.getPrototypeOf(proto);\r\n }\r\n return Object.getPrototypeOf(value) === proto;\r\n}\r\n// src/getDefaultMiddleware.ts\r\nimport thunkMiddleware from \"redux-thunk\";\r\n// src/utils.ts\r\nfunction getTimeMeasureUtils(maxDelay, fnName) {\r\n var elapsed = 0;\r\n return {\r\n measureTime: function (fn) {\r\n var started = Date.now();\r\n try {\r\n return fn();\r\n }\r\n finally {\r\n var finished = Date.now();\r\n elapsed += finished - started;\r\n }\r\n },\r\n warnIfExceeded: function () {\r\n if (elapsed > maxDelay) {\r\n console.warn(fnName + \" took \" + elapsed + \"ms, which is more than the warning threshold of \" + maxDelay + \"ms. \\nIf your state or actions are very large, you may want to disable the middleware as it might cause too much of a slowdown in development mode. See https://redux-toolkit.js.org/api/getDefaultMiddleware for instructions.\\nIt is disabled in production builds, so you don't need to worry about that.\");\r\n }\r\n }\r\n };\r\n}\r\nvar MiddlewareArray = /** @class */ (function (_super) {\r\n __extends(MiddlewareArray, _super);\r\n function MiddlewareArray() {\r\n var args = [];\r\n for (var _i = 0; _i < arguments.length; _i++) {\r\n args[_i] = arguments[_i];\r\n }\r\n var _this = _super.apply(this, args) || this;\r\n Object.setPrototypeOf(_this, MiddlewareArray.prototype);\r\n return _this;\r\n }\r\n Object.defineProperty(MiddlewareArray, Symbol.species, {\r\n get: function () {\r\n return MiddlewareArray;\r\n },\r\n enumerable: false,\r\n configurable: true\r\n });\r\n MiddlewareArray.prototype.concat = function () {\r\n var arr = [];\r\n for (var _i = 0; _i < arguments.length; _i++) {\r\n arr[_i] = arguments[_i];\r\n }\r\n return _super.prototype.concat.apply(this, arr);\r\n };\r\n MiddlewareArray.prototype.prepend = function () {\r\n var arr = [];\r\n for (var _i = 0; _i < arguments.length; _i++) {\r\n arr[_i] = arguments[_i];\r\n }\r\n if (arr.length === 1 && Array.isArray(arr[0])) {\r\n return new (MiddlewareArray.bind.apply(MiddlewareArray, __spreadArray([void 0], arr[0].concat(this))))();\r\n }\r\n return new (MiddlewareArray.bind.apply(MiddlewareArray, __spreadArray([void 0], arr.concat(this))))();\r\n };\r\n return MiddlewareArray;\r\n}(Array));\r\n// src/immutableStateInvariantMiddleware.ts\r\nvar isProduction = process.env.NODE_ENV === \"production\";\r\nvar prefix = \"Invariant failed\";\r\nfunction invariant(condition, message) {\r\n if (condition) {\r\n return;\r\n }\r\n if (isProduction) {\r\n throw new Error(prefix);\r\n }\r\n throw new Error(prefix + \": \" + (message || \"\"));\r\n}\r\nfunction stringify(obj, serializer, indent, decycler) {\r\n return JSON.stringify(obj, getSerialize(serializer, decycler), indent);\r\n}\r\nfunction getSerialize(serializer, decycler) {\r\n var stack = [], keys = [];\r\n if (!decycler)\r\n decycler = function (_, value) {\r\n if (stack[0] === value)\r\n return \"[Circular ~]\";\r\n return \"[Circular ~.\" + keys.slice(0, stack.indexOf(value)).join(\".\") + \"]\";\r\n };\r\n return function (key, value) {\r\n if (stack.length > 0) {\r\n var thisPos = stack.indexOf(this);\r\n ~thisPos ? stack.splice(thisPos + 1) : stack.push(this);\r\n ~thisPos ? keys.splice(thisPos, Infinity, key) : keys.push(key);\r\n if (~stack.indexOf(value))\r\n value = decycler.call(this, key, value);\r\n }\r\n else\r\n stack.push(value);\r\n return serializer == null ? value : serializer.call(this, key, value);\r\n };\r\n}\r\nfunction isImmutableDefault(value) {\r\n return typeof value !== \"object\" || value === null || typeof value === \"undefined\" || Object.isFrozen(value);\r\n}\r\nfunction trackForMutations(isImmutable, ignorePaths, obj) {\r\n var trackedProperties = trackProperties(isImmutable, ignorePaths, obj);\r\n return {\r\n detectMutations: function () {\r\n return detectMutations(isImmutable, ignorePaths, trackedProperties, obj);\r\n }\r\n };\r\n}\r\nfunction trackProperties(isImmutable, ignorePaths, obj, path) {\r\n if (ignorePaths === void 0) { ignorePaths = []; }\r\n if (path === void 0) { path = \"\"; }\r\n var tracked = { value: obj };\r\n if (!isImmutable(obj)) {\r\n tracked.children = {};\r\n for (var key in obj) {\r\n var childPath = path ? path + \".\" + key : key;\r\n if (ignorePaths.length && ignorePaths.indexOf(childPath) !== -1) {\r\n continue;\r\n }\r\n tracked.children[key] = trackProperties(isImmutable, ignorePaths, obj[key], childPath);\r\n }\r\n }\r\n return tracked;\r\n}\r\nfunction detectMutations(isImmutable, ignorePaths, trackedProperty, obj, sameParentRef, path) {\r\n if (ignorePaths === void 0) { ignorePaths = []; }\r\n if (sameParentRef === void 0) { sameParentRef = false; }\r\n if (path === void 0) { path = \"\"; }\r\n var prevObj = trackedProperty ? trackedProperty.value : void 0;\r\n var sameRef = prevObj === obj;\r\n if (sameParentRef && !sameRef && !Number.isNaN(obj)) {\r\n return { wasMutated: true, path: path };\r\n }\r\n if (isImmutable(prevObj) || isImmutable(obj)) {\r\n return { wasMutated: false };\r\n }\r\n var keysToDetect = {};\r\n for (var key in trackedProperty.children) {\r\n keysToDetect[key] = true;\r\n }\r\n for (var key in obj) {\r\n keysToDetect[key] = true;\r\n }\r\n for (var key in keysToDetect) {\r\n var childPath = path ? path + \".\" + key : key;\r\n if (ignorePaths.length && ignorePaths.indexOf(childPath) !== -1) {\r\n continue;\r\n }\r\n var result = detectMutations(isImmutable, ignorePaths, trackedProperty.children[key], obj[key], sameRef, childPath);\r\n if (result.wasMutated) {\r\n return result;\r\n }\r\n }\r\n return { wasMutated: false };\r\n}\r\nfunction createImmutableStateInvariantMiddleware(options) {\r\n if (options === void 0) { options = {}; }\r\n if (process.env.NODE_ENV === \"production\") {\r\n return function () { return function (next) { return function (action) { return next(action); }; }; };\r\n }\r\n var _b = options.isImmutable, isImmutable = _b === void 0 ? isImmutableDefault : _b, ignoredPaths = options.ignoredPaths, _c = options.warnAfter, warnAfter = _c === void 0 ? 32 : _c, ignore = options.ignore;\r\n ignoredPaths = ignoredPaths || ignore;\r\n var track = trackForMutations.bind(null, isImmutable, ignoredPaths);\r\n return function (_b) {\r\n var getState = _b.getState;\r\n var state = getState();\r\n var tracker = track(state);\r\n var result;\r\n return function (next) { return function (action) {\r\n var measureUtils = getTimeMeasureUtils(warnAfter, \"ImmutableStateInvariantMiddleware\");\r\n measureUtils.measureTime(function () {\r\n state = getState();\r\n result = tracker.detectMutations();\r\n tracker = track(state);\r\n invariant(!result.wasMutated, \"A state mutation was detected between dispatches, in the path '\" + (result.path || \"\") + \"'. This may cause incorrect behavior. (https://redux.js.org/style-guide/style-guide#do-not-mutate-state)\");\r\n });\r\n var dispatchedAction = next(action);\r\n measureUtils.measureTime(function () {\r\n state = getState();\r\n result = tracker.detectMutations();\r\n tracker = track(state);\r\n result.wasMutated && invariant(!result.wasMutated, \"A state mutation was detected inside a dispatch, in the path: \" + (result.path || \"\") + \". Take a look at the reducer(s) handling the action \" + stringify(action) + \". (https://redux.js.org/style-guide/style-guide#do-not-mutate-state)\");\r\n });\r\n measureUtils.warnIfExceeded();\r\n return dispatchedAction;\r\n }; };\r\n };\r\n}\r\n// src/serializableStateInvariantMiddleware.ts\r\nfunction isPlain(val) {\r\n var type = typeof val;\r\n return type === \"undefined\" || val === null || type === \"string\" || type === \"boolean\" || type === \"number\" || Array.isArray(val) || isPlainObject(val);\r\n}\r\nfunction findNonSerializableValue(value, path, isSerializable, getEntries, ignoredPaths) {\r\n if (path === void 0) { path = \"\"; }\r\n if (isSerializable === void 0) { isSerializable = isPlain; }\r\n if (ignoredPaths === void 0) { ignoredPaths = []; }\r\n var foundNestedSerializable;\r\n if (!isSerializable(value)) {\r\n return {\r\n keyPath: path || \"\",\r\n value: value\r\n };\r\n }\r\n if (typeof value !== \"object\" || value === null) {\r\n return false;\r\n }\r\n var entries = getEntries != null ? getEntries(value) : Object.entries(value);\r\n var hasIgnoredPaths = ignoredPaths.length > 0;\r\n for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {\r\n var _b = entries_1[_i], key = _b[0], nestedValue = _b[1];\r\n var nestedPath = path ? path + \".\" + key : key;\r\n if (hasIgnoredPaths && ignoredPaths.indexOf(nestedPath) >= 0) {\r\n continue;\r\n }\r\n if (!isSerializable(nestedValue)) {\r\n return {\r\n keyPath: nestedPath,\r\n value: nestedValue\r\n };\r\n }\r\n if (typeof nestedValue === \"object\") {\r\n foundNestedSerializable = findNonSerializableValue(nestedValue, nestedPath, isSerializable, getEntries, ignoredPaths);\r\n if (foundNestedSerializable) {\r\n return foundNestedSerializable;\r\n }\r\n }\r\n }\r\n return false;\r\n}\r\nfunction createSerializableStateInvariantMiddleware(options) {\r\n if (options === void 0) { options = {}; }\r\n if (process.env.NODE_ENV === \"production\") {\r\n return function () { return function (next) { return function (action) { return next(action); }; }; };\r\n }\r\n var _b = options.isSerializable, isSerializable = _b === void 0 ? isPlain : _b, getEntries = options.getEntries, _c = options.ignoredActions, ignoredActions = _c === void 0 ? [] : _c, _d = options.ignoredActionPaths, ignoredActionPaths = _d === void 0 ? [\"meta.arg\", \"meta.baseQueryMeta\"] : _d, _e = options.ignoredPaths, ignoredPaths = _e === void 0 ? [] : _e, _f = options.warnAfter, warnAfter = _f === void 0 ? 32 : _f, _g = options.ignoreState, ignoreState = _g === void 0 ? false : _g;\r\n return function (storeAPI) { return function (next) { return function (action) {\r\n if (ignoredActions.length && ignoredActions.indexOf(action.type) !== -1) {\r\n return next(action);\r\n }\r\n var measureUtils = getTimeMeasureUtils(warnAfter, \"SerializableStateInvariantMiddleware\");\r\n measureUtils.measureTime(function () {\r\n var foundActionNonSerializableValue = findNonSerializableValue(action, \"\", isSerializable, getEntries, ignoredActionPaths);\r\n if (foundActionNonSerializableValue) {\r\n var keyPath = foundActionNonSerializableValue.keyPath, value = foundActionNonSerializableValue.value;\r\n console.error(\"A non-serializable value was detected in an action, in the path: `\" + keyPath + \"`. Value:\", value, \"\\nTake a look at the logic that dispatched this action: \", action, \"\\n(See https://redux.js.org/faq/actions#why-should-type-be-a-string-or-at-least-serializable-why-should-my-action-types-be-constants)\", \"\\n(To allow non-serializable values see: https://redux-toolkit.js.org/usage/usage-guide#working-with-non-serializable-data)\");\r\n }\r\n });\r\n var result = next(action);\r\n if (!ignoreState) {\r\n measureUtils.measureTime(function () {\r\n var state = storeAPI.getState();\r\n var foundStateNonSerializableValue = findNonSerializableValue(state, \"\", isSerializable, getEntries, ignoredPaths);\r\n if (foundStateNonSerializableValue) {\r\n var keyPath = foundStateNonSerializableValue.keyPath, value = foundStateNonSerializableValue.value;\r\n console.error(\"A non-serializable value was detected in the state, in the path: `\" + keyPath + \"`. Value:\", value, \"\\nTake a look at the reducer(s) handling this action type: \" + action.type + \".\\n(See https://redux.js.org/faq/organizing-state#can-i-put-functions-promises-or-other-non-serializable-items-in-my-store-state)\");\r\n }\r\n });\r\n measureUtils.warnIfExceeded();\r\n }\r\n return result;\r\n }; }; };\r\n}\r\n// src/getDefaultMiddleware.ts\r\nfunction isBoolean(x) {\r\n return typeof x === \"boolean\";\r\n}\r\nfunction curryGetDefaultMiddleware() {\r\n return function curriedGetDefaultMiddleware(options) {\r\n return getDefaultMiddleware(options);\r\n };\r\n}\r\nfunction getDefaultMiddleware(options) {\r\n if (options === void 0) { options = {}; }\r\n var _b = options.thunk, thunk = _b === void 0 ? true : _b, _c = options.immutableCheck, immutableCheck = _c === void 0 ? true : _c, _d = options.serializableCheck, serializableCheck = _d === void 0 ? true : _d;\r\n var middlewareArray = new MiddlewareArray();\r\n if (thunk) {\r\n if (isBoolean(thunk)) {\r\n middlewareArray.push(thunkMiddleware);\r\n }\r\n else {\r\n middlewareArray.push(thunkMiddleware.withExtraArgument(thunk.extraArgument));\r\n }\r\n }\r\n if (process.env.NODE_ENV !== \"production\") {\r\n if (immutableCheck) {\r\n var immutableOptions = {};\r\n if (!isBoolean(immutableCheck)) {\r\n immutableOptions = immutableCheck;\r\n }\r\n middlewareArray.unshift(createImmutableStateInvariantMiddleware(immutableOptions));\r\n }\r\n if (serializableCheck) {\r\n var serializableOptions = {};\r\n if (!isBoolean(serializableCheck)) {\r\n serializableOptions = serializableCheck;\r\n }\r\n middlewareArray.push(createSerializableStateInvariantMiddleware(serializableOptions));\r\n }\r\n }\r\n return middlewareArray;\r\n}\r\n// src/configureStore.ts\r\nvar IS_PRODUCTION = process.env.NODE_ENV === \"production\";\r\nfunction configureStore(options) {\r\n var curriedGetDefaultMiddleware = curryGetDefaultMiddleware();\r\n var _b = options || {}, _c = _b.reducer, reducer = _c === void 0 ? void 0 : _c, _d = _b.middleware, middleware = _d === void 0 ? curriedGetDefaultMiddleware() : _d, _e = _b.devTools, devTools = _e === void 0 ? true : _e, _f = _b.preloadedState, preloadedState = _f === void 0 ? void 0 : _f, _g = _b.enhancers, enhancers = _g === void 0 ? void 0 : _g;\r\n var rootReducer;\r\n if (typeof reducer === \"function\") {\r\n rootReducer = reducer;\r\n }\r\n else if (isPlainObject(reducer)) {\r\n rootReducer = combineReducers(reducer);\r\n }\r\n else {\r\n throw new Error('\"reducer\" is a required argument, and must be a function or an object of functions that can be passed to combineReducers');\r\n }\r\n var finalMiddleware = middleware;\r\n if (typeof finalMiddleware === \"function\") {\r\n finalMiddleware = finalMiddleware(curriedGetDefaultMiddleware);\r\n if (!IS_PRODUCTION && !Array.isArray(finalMiddleware)) {\r\n throw new Error(\"when using a middleware builder function, an array of middleware must be returned\");\r\n }\r\n }\r\n if (!IS_PRODUCTION && finalMiddleware.some(function (item) { return typeof item !== \"function\"; })) {\r\n throw new Error(\"each middleware provided to configureStore must be a function\");\r\n }\r\n var middlewareEnhancer = applyMiddleware.apply(void 0, finalMiddleware);\r\n var finalCompose = compose2;\r\n if (devTools) {\r\n finalCompose = composeWithDevTools(__spreadValues({\r\n trace: !IS_PRODUCTION\r\n }, typeof devTools === \"object\" && devTools));\r\n }\r\n var storeEnhancers = [middlewareEnhancer];\r\n if (Array.isArray(enhancers)) {\r\n storeEnhancers = __spreadArray([middlewareEnhancer], enhancers);\r\n }\r\n else if (typeof enhancers === \"function\") {\r\n storeEnhancers = enhancers(storeEnhancers);\r\n }\r\n var composedEnhancer = finalCompose.apply(void 0, storeEnhancers);\r\n return createStore(rootReducer, preloadedState, composedEnhancer);\r\n}\r\n// src/createAction.ts\r\nfunction createAction(type, prepareAction) {\r\n function actionCreator() {\r\n var args = [];\r\n for (var _i = 0; _i < arguments.length; _i++) {\r\n args[_i] = arguments[_i];\r\n }\r\n if (prepareAction) {\r\n var prepared = prepareAction.apply(void 0, args);\r\n if (!prepared) {\r\n throw new Error(\"prepareAction did not return an object\");\r\n }\r\n return __spreadValues(__spreadValues({\r\n type: type,\r\n payload: prepared.payload\r\n }, \"meta\" in prepared && { meta: prepared.meta }), \"error\" in prepared && { error: prepared.error });\r\n }\r\n return { type: type, payload: args[0] };\r\n }\r\n actionCreator.toString = function () { return \"\" + type; };\r\n actionCreator.type = type;\r\n actionCreator.match = function (action) { return action.type === type; };\r\n return actionCreator;\r\n}\r\nfunction isFSA(action) {\r\n return isPlainObject(action) && typeof action.type === \"string\" && Object.keys(action).every(isValidKey);\r\n}\r\nfunction isValidKey(key) {\r\n return [\"type\", \"payload\", \"error\", \"meta\"].indexOf(key) > -1;\r\n}\r\nfunction getType(actionCreator) {\r\n return \"\" + actionCreator;\r\n}\r\n// src/createReducer.ts\r\nimport createNextState, { isDraft as isDraft2, isDraftable } from \"immer\";\r\n// src/mapBuilders.ts\r\nfunction executeReducerBuilderCallback(builderCallback) {\r\n var actionsMap = {};\r\n var actionMatchers = [];\r\n var defaultCaseReducer;\r\n var builder = {\r\n addCase: function (typeOrActionCreator, reducer) {\r\n if (process.env.NODE_ENV !== \"production\") {\r\n if (actionMatchers.length > 0) {\r\n throw new Error(\"`builder.addCase` should only be called before calling `builder.addMatcher`\");\r\n }\r\n if (defaultCaseReducer) {\r\n throw new Error(\"`builder.addCase` should only be called before calling `builder.addDefaultCase`\");\r\n }\r\n }\r\n var type = typeof typeOrActionCreator === \"string\" ? typeOrActionCreator : typeOrActionCreator.type;\r\n if (type in actionsMap) {\r\n throw new Error(\"addCase cannot be called with two reducers for the same action type\");\r\n }\r\n actionsMap[type] = reducer;\r\n return builder;\r\n },\r\n addMatcher: function (matcher, reducer) {\r\n if (process.env.NODE_ENV !== \"production\") {\r\n if (defaultCaseReducer) {\r\n throw new Error(\"`builder.addMatcher` should only be called before calling `builder.addDefaultCase`\");\r\n }\r\n }\r\n actionMatchers.push({ matcher: matcher, reducer: reducer });\r\n return builder;\r\n },\r\n addDefaultCase: function (reducer) {\r\n if (process.env.NODE_ENV !== \"production\") {\r\n if (defaultCaseReducer) {\r\n throw new Error(\"`builder.addDefaultCase` can only be called once\");\r\n }\r\n }\r\n defaultCaseReducer = reducer;\r\n return builder;\r\n }\r\n };\r\n builderCallback(builder);\r\n return [actionsMap, actionMatchers, defaultCaseReducer];\r\n}\r\n// src/createReducer.ts\r\nfunction createReducer(initialState, mapOrBuilderCallback, actionMatchers, defaultCaseReducer) {\r\n if (actionMatchers === void 0) { actionMatchers = []; }\r\n var _b = typeof mapOrBuilderCallback === \"function\" ? executeReducerBuilderCallback(mapOrBuilderCallback) : [mapOrBuilderCallback, actionMatchers, defaultCaseReducer], actionsMap = _b[0], finalActionMatchers = _b[1], finalDefaultCaseReducer = _b[2];\r\n var frozenInitialState = createNextState(initialState, function () {\r\n });\r\n return function (state, action) {\r\n if (state === void 0) { state = frozenInitialState; }\r\n var caseReducers = __spreadArray([\r\n actionsMap[action.type]\r\n ], finalActionMatchers.filter(function (_b) {\r\n var matcher = _b.matcher;\r\n return matcher(action);\r\n }).map(function (_b) {\r\n var reducer = _b.reducer;\r\n return reducer;\r\n }));\r\n if (caseReducers.filter(function (cr) { return !!cr; }).length === 0) {\r\n caseReducers = [finalDefaultCaseReducer];\r\n }\r\n return caseReducers.reduce(function (previousState, caseReducer) {\r\n if (caseReducer) {\r\n if (isDraft2(previousState)) {\r\n var draft = previousState;\r\n var result = caseReducer(draft, action);\r\n if (typeof result === \"undefined\") {\r\n return previousState;\r\n }\r\n return result;\r\n }\r\n else if (!isDraftable(previousState)) {\r\n var result = caseReducer(previousState, action);\r\n if (typeof result === \"undefined\") {\r\n if (previousState === null) {\r\n return previousState;\r\n }\r\n throw Error(\"A case reducer on a non-draftable value must not return undefined\");\r\n }\r\n return result;\r\n }\r\n else {\r\n return createNextState(previousState, function (draft) {\r\n return caseReducer(draft, action);\r\n });\r\n }\r\n }\r\n return previousState;\r\n }, state);\r\n };\r\n}\r\n// src/createSlice.ts\r\nfunction getType2(slice, actionKey) {\r\n return slice + \"/\" + actionKey;\r\n}\r\nfunction createSlice(options) {\r\n var name = options.name, initialState = options.initialState;\r\n if (!name) {\r\n throw new Error(\"`name` is a required option for createSlice\");\r\n }\r\n var reducers = options.reducers || {};\r\n var _b = typeof options.extraReducers === \"function\" ? executeReducerBuilderCallback(options.extraReducers) : [options.extraReducers], _c = _b[0], extraReducers = _c === void 0 ? {} : _c, _d = _b[1], actionMatchers = _d === void 0 ? [] : _d, _e = _b[2], defaultCaseReducer = _e === void 0 ? void 0 : _e;\r\n var reducerNames = Object.keys(reducers);\r\n var sliceCaseReducersByName = {};\r\n var sliceCaseReducersByType = {};\r\n var actionCreators = {};\r\n reducerNames.forEach(function (reducerName) {\r\n var maybeReducerWithPrepare = reducers[reducerName];\r\n var type = getType2(name, reducerName);\r\n var caseReducer;\r\n var prepareCallback;\r\n if (\"reducer\" in maybeReducerWithPrepare) {\r\n caseReducer = maybeReducerWithPrepare.reducer;\r\n prepareCallback = maybeReducerWithPrepare.prepare;\r\n }\r\n else {\r\n caseReducer = maybeReducerWithPrepare;\r\n }\r\n sliceCaseReducersByName[reducerName] = caseReducer;\r\n sliceCaseReducersByType[type] = caseReducer;\r\n actionCreators[reducerName] = prepareCallback ? createAction(type, prepareCallback) : createAction(type);\r\n });\r\n var finalCaseReducers = __spreadValues(__spreadValues({}, extraReducers), sliceCaseReducersByType);\r\n var reducer = createReducer(initialState, finalCaseReducers, actionMatchers, defaultCaseReducer);\r\n return {\r\n name: name,\r\n reducer: reducer,\r\n actions: actionCreators,\r\n caseReducers: sliceCaseReducersByName\r\n };\r\n}\r\n// src/entities/entity_state.ts\r\nfunction getInitialEntityState() {\r\n return {\r\n ids: [],\r\n entities: {}\r\n };\r\n}\r\nfunction createInitialStateFactory() {\r\n function getInitialState(additionalState) {\r\n if (additionalState === void 0) { additionalState = {}; }\r\n return Object.assign(getInitialEntityState(), additionalState);\r\n }\r\n return { getInitialState: getInitialState };\r\n}\r\n// src/entities/state_selectors.ts\r\nfunction createSelectorsFactory() {\r\n function getSelectors(selectState) {\r\n var selectIds = function (state) { return state.ids; };\r\n var selectEntities = function (state) { return state.entities; };\r\n var selectAll = createDraftSafeSelector(selectIds, selectEntities, function (ids, entities) { return ids.map(function (id) { return entities[id]; }); });\r\n var selectId = function (_, id) { return id; };\r\n var selectById = function (entities, id) { return entities[id]; };\r\n var selectTotal = createDraftSafeSelector(selectIds, function (ids) { return ids.length; });\r\n if (!selectState) {\r\n return {\r\n selectIds: selectIds,\r\n selectEntities: selectEntities,\r\n selectAll: selectAll,\r\n selectTotal: selectTotal,\r\n selectById: createDraftSafeSelector(selectEntities, selectId, selectById)\r\n };\r\n }\r\n var selectGlobalizedEntities = createDraftSafeSelector(selectState, selectEntities);\r\n return {\r\n selectIds: createDraftSafeSelector(selectState, selectIds),\r\n selectEntities: selectGlobalizedEntities,\r\n selectAll: createDraftSafeSelector(selectState, selectAll),\r\n selectTotal: createDraftSafeSelector(selectState, selectTotal),\r\n selectById: createDraftSafeSelector(selectGlobalizedEntities, selectId, selectById)\r\n };\r\n }\r\n return { getSelectors: getSelectors };\r\n}\r\n// src/entities/state_adapter.ts\r\nimport createNextState2, { isDraft as isDraft3 } from \"immer\";\r\nfunction createSingleArgumentStateOperator(mutator) {\r\n var operator = createStateOperator(function (_, state) { return mutator(state); });\r\n return function operation(state) {\r\n return operator(state, void 0);\r\n };\r\n}\r\nfunction createStateOperator(mutator) {\r\n return function operation(state, arg) {\r\n function isPayloadActionArgument(arg2) {\r\n return isFSA(arg2);\r\n }\r\n var runMutator = function (draft) {\r\n if (isPayloadActionArgument(arg)) {\r\n mutator(arg.payload, draft);\r\n }\r\n else {\r\n mutator(arg, draft);\r\n }\r\n };\r\n if (isDraft3(state)) {\r\n runMutator(state);\r\n return state;\r\n }\r\n else {\r\n return createNextState2(state, runMutator);\r\n }\r\n };\r\n}\r\n// src/entities/utils.ts\r\nfunction selectIdValue(entity, selectId) {\r\n var key = selectId(entity);\r\n if (process.env.NODE_ENV !== \"production\" && key === void 0) {\r\n console.warn(\"The entity passed to the `selectId` implementation returned undefined.\", \"You should probably provide your own `selectId` implementation.\", \"The entity that was passed:\", entity, \"The `selectId` implementation:\", selectId.toString());\r\n }\r\n return key;\r\n}\r\nfunction ensureEntitiesArray(entities) {\r\n if (!Array.isArray(entities)) {\r\n entities = Object.values(entities);\r\n }\r\n return entities;\r\n}\r\nfunction splitAddedUpdatedEntities(newEntities, selectId, state) {\r\n newEntities = ensureEntitiesArray(newEntities);\r\n var added = [];\r\n var updated = [];\r\n for (var _i = 0, newEntities_1 = newEntities; _i < newEntities_1.length; _i++) {\r\n var entity = newEntities_1[_i];\r\n var id = selectIdValue(entity, selectId);\r\n if (id in state.entities) {\r\n updated.push({ id: id, changes: entity });\r\n }\r\n else {\r\n added.push(entity);\r\n }\r\n }\r\n return [added, updated];\r\n}\r\n// src/entities/unsorted_state_adapter.ts\r\nfunction createUnsortedStateAdapter(selectId) {\r\n function addOneMutably(entity, state) {\r\n var key = selectIdValue(entity, selectId);\r\n if (key in state.entities) {\r\n return;\r\n }\r\n state.ids.push(key);\r\n state.entities[key] = entity;\r\n }\r\n function addManyMutably(newEntities, state) {\r\n newEntities = ensureEntitiesArray(newEntities);\r\n for (var _i = 0, newEntities_2 = newEntities; _i < newEntities_2.length; _i++) {\r\n var entity = newEntities_2[_i];\r\n addOneMutably(entity, state);\r\n }\r\n }\r\n function setOneMutably(entity, state) {\r\n var key = selectIdValue(entity, selectId);\r\n if (!(key in state.entities)) {\r\n state.ids.push(key);\r\n }\r\n state.entities[key] = entity;\r\n }\r\n function setManyMutably(newEntities, state) {\r\n newEntities = ensureEntitiesArray(newEntities);\r\n for (var _i = 0, newEntities_3 = newEntities; _i < newEntities_3.length; _i++) {\r\n var entity = newEntities_3[_i];\r\n setOneMutably(entity, state);\r\n }\r\n }\r\n function setAllMutably(newEntities, state) {\r\n newEntities = ensureEntitiesArray(newEntities);\r\n state.ids = [];\r\n state.entities = {};\r\n addManyMutably(newEntities, state);\r\n }\r\n function removeOneMutably(key, state) {\r\n return removeManyMutably([key], state);\r\n }\r\n function removeManyMutably(keys, state) {\r\n var didMutate = false;\r\n keys.forEach(function (key) {\r\n if (key in state.entities) {\r\n delete state.entities[key];\r\n didMutate = true;\r\n }\r\n });\r\n if (didMutate) {\r\n state.ids = state.ids.filter(function (id) { return id in state.entities; });\r\n }\r\n }\r\n function removeAllMutably(state) {\r\n Object.assign(state, {\r\n ids: [],\r\n entities: {}\r\n });\r\n }\r\n function takeNewKey(keys, update, state) {\r\n var original2 = state.entities[update.id];\r\n var updated = Object.assign({}, original2, update.changes);\r\n var newKey = selectIdValue(updated, selectId);\r\n var hasNewKey = newKey !== update.id;\r\n if (hasNewKey) {\r\n keys[update.id] = newKey;\r\n delete state.entities[update.id];\r\n }\r\n state.entities[newKey] = updated;\r\n return hasNewKey;\r\n }\r\n function updateOneMutably(update, state) {\r\n return updateManyMutably([update], state);\r\n }\r\n function updateManyMutably(updates, state) {\r\n var newKeys = {};\r\n var updatesPerEntity = {};\r\n updates.forEach(function (update) {\r\n if (update.id in state.entities) {\r\n updatesPerEntity[update.id] = {\r\n id: update.id,\r\n changes: __spreadValues(__spreadValues({}, updatesPerEntity[update.id] ? updatesPerEntity[update.id].changes : null), update.changes)\r\n };\r\n }\r\n });\r\n updates = Object.values(updatesPerEntity);\r\n var didMutateEntities = updates.length > 0;\r\n if (didMutateEntities) {\r\n var didMutateIds = updates.filter(function (update) { return takeNewKey(newKeys, update, state); }).length > 0;\r\n if (didMutateIds) {\r\n state.ids = state.ids.map(function (id) { return newKeys[id] || id; });\r\n }\r\n }\r\n }\r\n function upsertOneMutably(entity, state) {\r\n return upsertManyMutably([entity], state);\r\n }\r\n function upsertManyMutably(newEntities, state) {\r\n var _b = splitAddedUpdatedEntities(newEntities, selectId, state), added = _b[0], updated = _b[1];\r\n updateManyMutably(updated, state);\r\n addManyMutably(added, state);\r\n }\r\n return {\r\n removeAll: createSingleArgumentStateOperator(removeAllMutably),\r\n addOne: createStateOperator(addOneMutably),\r\n addMany: createStateOperator(addManyMutably),\r\n setOne: createStateOperator(setOneMutably),\r\n setMany: createStateOperator(setManyMutably),\r\n setAll: createStateOperator(setAllMutably),\r\n updateOne: createStateOperator(updateOneMutably),\r\n updateMany: createStateOperator(updateManyMutably),\r\n upsertOne: createStateOperator(upsertOneMutably),\r\n upsertMany: createStateOperator(upsertManyMutably),\r\n removeOne: createStateOperator(removeOneMutably),\r\n removeMany: createStateOperator(removeManyMutably)\r\n };\r\n}\r\n// src/entities/sorted_state_adapter.ts\r\nfunction createSortedStateAdapter(selectId, sort) {\r\n var _b = createUnsortedStateAdapter(selectId), removeOne = _b.removeOne, removeMany = _b.removeMany, removeAll = _b.removeAll;\r\n function addOneMutably(entity, state) {\r\n return addManyMutably([entity], state);\r\n }\r\n function addManyMutably(newEntities, state) {\r\n newEntities = ensureEntitiesArray(newEntities);\r\n var models = newEntities.filter(function (model) { return !(selectIdValue(model, selectId) in state.entities); });\r\n if (models.length !== 0) {\r\n merge(models, state);\r\n }\r\n }\r\n function setOneMutably(entity, state) {\r\n return setManyMutably([entity], state);\r\n }\r\n function setManyMutably(newEntities, state) {\r\n newEntities = ensureEntitiesArray(newEntities);\r\n if (newEntities.length !== 0) {\r\n merge(newEntities, state);\r\n }\r\n }\r\n function setAllMutably(newEntities, state) {\r\n newEntities = ensureEntitiesArray(newEntities);\r\n state.entities = {};\r\n state.ids = [];\r\n addManyMutably(newEntities, state);\r\n }\r\n function updateOneMutably(update, state) {\r\n return updateManyMutably([update], state);\r\n }\r\n function takeUpdatedModel(models, update, state) {\r\n if (!(update.id in state.entities)) {\r\n return false;\r\n }\r\n var original2 = state.entities[update.id];\r\n var updated = Object.assign({}, original2, update.changes);\r\n var newKey = selectIdValue(updated, selectId);\r\n delete state.entities[update.id];\r\n models.push(updated);\r\n return newKey !== update.id;\r\n }\r\n function updateManyMutably(updates, state) {\r\n var models = [];\r\n updates.forEach(function (update) { return takeUpdatedModel(models, update, state); });\r\n if (models.length !== 0) {\r\n merge(models, state);\r\n }\r\n }\r\n function upsertOneMutably(entity, state) {\r\n return upsertManyMutably([entity], state);\r\n }\r\n function upsertManyMutably(newEntities, state) {\r\n var _b = splitAddedUpdatedEntities(newEntities, selectId, state), added = _b[0], updated = _b[1];\r\n updateManyMutably(updated, state);\r\n addManyMutably(added, state);\r\n }\r\n function areArraysEqual(a, b) {\r\n if (a.length !== b.length) {\r\n return false;\r\n }\r\n for (var i = 0; i < a.length && i < b.length; i++) {\r\n if (a[i] === b[i]) {\r\n continue;\r\n }\r\n return false;\r\n }\r\n return true;\r\n }\r\n function merge(models, state) {\r\n models.forEach(function (model) {\r\n state.entities[selectId(model)] = model;\r\n });\r\n var allEntities = Object.values(state.entities);\r\n allEntities.sort(sort);\r\n var newSortedIds = allEntities.map(selectId);\r\n var ids = state.ids;\r\n if (!areArraysEqual(ids, newSortedIds)) {\r\n state.ids = newSortedIds;\r\n }\r\n }\r\n return {\r\n removeOne: removeOne,\r\n removeMany: removeMany,\r\n removeAll: removeAll,\r\n addOne: createStateOperator(addOneMutably),\r\n updateOne: createStateOperator(updateOneMutably),\r\n upsertOne: createStateOperator(upsertOneMutably),\r\n setOne: createStateOperator(setOneMutably),\r\n setMany: createStateOperator(setManyMutably),\r\n setAll: createStateOperator(setAllMutably),\r\n addMany: createStateOperator(addManyMutably),\r\n updateMany: createStateOperator(updateManyMutably),\r\n upsertMany: createStateOperator(upsertManyMutably)\r\n };\r\n}\r\n// src/entities/create_adapter.ts\r\nfunction createEntityAdapter(options) {\r\n if (options === void 0) { options = {}; }\r\n var _b = __spreadValues({\r\n sortComparer: false,\r\n selectId: function (instance) { return instance.id; }\r\n }, options), selectId = _b.selectId, sortComparer = _b.sortComparer;\r\n var stateFactory = createInitialStateFactory();\r\n var selectorsFactory = createSelectorsFactory();\r\n var stateAdapter = sortComparer ? createSortedStateAdapter(selectId, sortComparer) : createUnsortedStateAdapter(selectId);\r\n return __spreadValues(__spreadValues(__spreadValues({\r\n selectId: selectId,\r\n sortComparer: sortComparer\r\n }, stateFactory), selectorsFactory), stateAdapter);\r\n}\r\n// src/nanoid.ts\r\nvar urlAlphabet = \"ModuleSymbhasOwnPr-0123456789ABCDEFGHNRVfgctiUvz_KqYTJkLxpZXIjQW\";\r\nvar nanoid = function (size) {\r\n if (size === void 0) { size = 21; }\r\n var id = \"\";\r\n var i = size;\r\n while (i--) {\r\n id += urlAlphabet[Math.random() * 64 | 0];\r\n }\r\n return id;\r\n};\r\n// src/createAsyncThunk.ts\r\nvar commonProperties = [\r\n \"name\",\r\n \"message\",\r\n \"stack\",\r\n \"code\"\r\n];\r\nvar RejectWithValue = /** @class */ (function () {\r\n function RejectWithValue(payload, meta) {\r\n this.payload = payload;\r\n this.meta = meta;\r\n }\r\n return RejectWithValue;\r\n}());\r\nvar FulfillWithMeta = /** @class */ (function () {\r\n function FulfillWithMeta(payload, meta) {\r\n this.payload = payload;\r\n this.meta = meta;\r\n }\r\n return FulfillWithMeta;\r\n}());\r\nvar miniSerializeError = function (value) {\r\n if (typeof value === \"object\" && value !== null) {\r\n var simpleError = {};\r\n for (var _i = 0, commonProperties_1 = commonProperties; _i < commonProperties_1.length; _i++) {\r\n var property = commonProperties_1[_i];\r\n if (typeof value[property] === \"string\") {\r\n simpleError[property] = value[property];\r\n }\r\n }\r\n return simpleError;\r\n }\r\n return { message: String(value) };\r\n};\r\nfunction createAsyncThunk(typePrefix, payloadCreator, options) {\r\n var fulfilled = createAction(typePrefix + \"/fulfilled\", function (payload, requestId, arg, meta) { return ({\r\n payload: payload,\r\n meta: __spreadProps(__spreadValues({}, meta || {}), {\r\n arg: arg,\r\n requestId: requestId,\r\n requestStatus: \"fulfilled\"\r\n })\r\n }); });\r\n var pending = createAction(typePrefix + \"/pending\", function (requestId, arg, meta) { return ({\r\n payload: void 0,\r\n meta: __spreadProps(__spreadValues({}, meta || {}), {\r\n arg: arg,\r\n requestId: requestId,\r\n requestStatus: \"pending\"\r\n })\r\n }); });\r\n var rejected = createAction(typePrefix + \"/rejected\", function (error, requestId, arg, payload, meta) { return ({\r\n payload: payload,\r\n error: (options && options.serializeError || miniSerializeError)(error || \"Rejected\"),\r\n meta: __spreadProps(__spreadValues({}, meta || {}), {\r\n arg: arg,\r\n requestId: requestId,\r\n rejectedWithValue: !!payload,\r\n requestStatus: \"rejected\",\r\n aborted: (error == null ? void 0 : error.name) === \"AbortError\",\r\n condition: (error == null ? void 0 : error.name) === \"ConditionError\"\r\n })\r\n }); });\r\n var displayedWarning = false;\r\n var AC = typeof AbortController !== \"undefined\" ? AbortController : /** @class */ (function () {\r\n function class_1() {\r\n this.signal = {\r\n aborted: false,\r\n addEventListener: function () {\r\n },\r\n dispatchEvent: function () {\r\n return false;\r\n },\r\n onabort: function () {\r\n },\r\n removeEventListener: function () {\r\n }\r\n };\r\n }\r\n class_1.prototype.abort = function () {\r\n if (process.env.NODE_ENV !== \"production\") {\r\n if (!displayedWarning) {\r\n displayedWarning = true;\r\n console.info(\"This platform does not implement AbortController. \\nIf you want to use the AbortController to react to `abort` events, please consider importing a polyfill like 'abortcontroller-polyfill/dist/abortcontroller-polyfill-only'.\");\r\n }\r\n }\r\n };\r\n return class_1;\r\n }());\r\n function actionCreator(arg) {\r\n return function (dispatch, getState, extra) {\r\n var _a;\r\n var requestId = ((_a = options == null ? void 0 : options.idGenerator) != null ? _a : nanoid)();\r\n var abortController = new AC();\r\n var abortReason;\r\n var abortedPromise = new Promise(function (_, reject) { return abortController.signal.addEventListener(\"abort\", function () { return reject({ name: \"AbortError\", message: abortReason || \"Aborted\" }); }); });\r\n var started = false;\r\n function abort(reason) {\r\n if (started) {\r\n abortReason = reason;\r\n abortController.abort();\r\n }\r\n }\r\n var promise = function () {\r\n return __async(this, null, function () {\r\n var _a2, finalAction, err_1, skipDispatch;\r\n return __generator(this, function (_b) {\r\n switch (_b.label) {\r\n case 0:\r\n _b.trys.push([0, 2, , 3]);\r\n if (options && options.condition && options.condition(arg, { getState: getState, extra: extra }) === false) {\r\n throw {\r\n name: \"ConditionError\",\r\n message: \"Aborted due to condition callback returning false.\"\r\n };\r\n }\r\n started = true;\r\n dispatch(pending(requestId, arg, (_a2 = options == null ? void 0 : options.getPendingMeta) == null ? void 0 : _a2.call(options, { requestId: requestId, arg: arg }, { getState: getState, extra: extra })));\r\n return [4 /*yield*/, Promise.race([\r\n abortedPromise,\r\n Promise.resolve(payloadCreator(arg, {\r\n dispatch: dispatch,\r\n getState: getState,\r\n extra: extra,\r\n requestId: requestId,\r\n signal: abortController.signal,\r\n rejectWithValue: function (value, meta) {\r\n return new RejectWithValue(value, meta);\r\n },\r\n fulfillWithValue: function (value, meta) {\r\n return new FulfillWithMeta(value, meta);\r\n }\r\n })).then(function (result) {\r\n if (result instanceof RejectWithValue) {\r\n throw result;\r\n }\r\n if (result instanceof FulfillWithMeta) {\r\n return fulfilled(result.payload, requestId, arg, result.meta);\r\n }\r\n return fulfilled(result, requestId, arg);\r\n })\r\n ])];\r\n case 1:\r\n finalAction = _b.sent();\r\n return [3 /*break*/, 3];\r\n case 2:\r\n err_1 = _b.sent();\r\n finalAction = err_1 instanceof RejectWithValue ? rejected(null, requestId, arg, err_1.payload, err_1.meta) : rejected(err_1, requestId, arg);\r\n return [3 /*break*/, 3];\r\n case 3:\r\n skipDispatch = options && !options.dispatchConditionRejection && rejected.match(finalAction) && finalAction.meta.condition;\r\n if (!skipDispatch) {\r\n dispatch(finalAction);\r\n }\r\n return [2 /*return*/, finalAction];\r\n }\r\n });\r\n });\r\n }();\r\n return Object.assign(promise, {\r\n abort: abort,\r\n requestId: requestId,\r\n arg: arg,\r\n unwrap: function () {\r\n return promise.then(unwrapResult);\r\n }\r\n });\r\n };\r\n }\r\n return Object.assign(actionCreator, {\r\n pending: pending,\r\n rejected: rejected,\r\n fulfilled: fulfilled,\r\n typePrefix: typePrefix\r\n });\r\n}\r\nfunction unwrapResult(action) {\r\n if (action.meta && action.meta.rejectedWithValue) {\r\n throw action.payload;\r\n }\r\n if (action.error) {\r\n throw action.error;\r\n }\r\n return action.payload;\r\n}\r\n// src/tsHelpers.ts\r\nvar hasMatchFunction = function (v) {\r\n return v && typeof v.match === \"function\";\r\n};\r\n// src/matchers.ts\r\nvar matches = function (matcher, action) {\r\n if (hasMatchFunction(matcher)) {\r\n return matcher.match(action);\r\n }\r\n else {\r\n return matcher(action);\r\n }\r\n};\r\nfunction isAnyOf() {\r\n var matchers = [];\r\n for (var _i = 0; _i < arguments.length; _i++) {\r\n matchers[_i] = arguments[_i];\r\n }\r\n return function (action) {\r\n return matchers.some(function (matcher) { return matches(matcher, action); });\r\n };\r\n}\r\nfunction isAllOf() {\r\n var matchers = [];\r\n for (var _i = 0; _i < arguments.length; _i++) {\r\n matchers[_i] = arguments[_i];\r\n }\r\n return function (action) {\r\n return matchers.every(function (matcher) { return matches(matcher, action); });\r\n };\r\n}\r\nfunction hasExpectedRequestMetadata(action, validStatus) {\r\n if (!action || !action.meta)\r\n return false;\r\n var hasValidRequestId = typeof action.meta.requestId === \"string\";\r\n var hasValidRequestStatus = validStatus.indexOf(action.meta.requestStatus) > -1;\r\n return hasValidRequestId && hasValidRequestStatus;\r\n}\r\nfunction isAsyncThunkArray(a) {\r\n return typeof a[0] === \"function\" && \"pending\" in a[0] && \"fulfilled\" in a[0] && \"rejected\" in a[0];\r\n}\r\nfunction isPending() {\r\n var asyncThunks = [];\r\n for (var _i = 0; _i < arguments.length; _i++) {\r\n asyncThunks[_i] = arguments[_i];\r\n }\r\n if (asyncThunks.length === 0) {\r\n return function (action) { return hasExpectedRequestMetadata(action, [\"pending\"]); };\r\n }\r\n if (!isAsyncThunkArray(asyncThunks)) {\r\n return isPending()(asyncThunks[0]);\r\n }\r\n return function (action) {\r\n var matchers = asyncThunks.map(function (asyncThunk) { return asyncThunk.pending; });\r\n var combinedMatcher = isAnyOf.apply(void 0, matchers);\r\n return combinedMatcher(action);\r\n };\r\n}\r\nfunction isRejected() {\r\n var asyncThunks = [];\r\n for (var _i = 0; _i < arguments.length; _i++) {\r\n asyncThunks[_i] = arguments[_i];\r\n }\r\n if (asyncThunks.length === 0) {\r\n return function (action) { return hasExpectedRequestMetadata(action, [\"rejected\"]); };\r\n }\r\n if (!isAsyncThunkArray(asyncThunks)) {\r\n return isRejected()(asyncThunks[0]);\r\n }\r\n return function (action) {\r\n var matchers = asyncThunks.map(function (asyncThunk) { return asyncThunk.rejected; });\r\n var combinedMatcher = isAnyOf.apply(void 0, matchers);\r\n return combinedMatcher(action);\r\n };\r\n}\r\nfunction isRejectedWithValue() {\r\n var asyncThunks = [];\r\n for (var _i = 0; _i < arguments.length; _i++) {\r\n asyncThunks[_i] = arguments[_i];\r\n }\r\n var hasFlag = function (action) {\r\n return action && action.meta && action.meta.rejectedWithValue;\r\n };\r\n if (asyncThunks.length === 0) {\r\n return function (action) {\r\n var combinedMatcher = isAllOf(isRejected.apply(void 0, asyncThunks), hasFlag);\r\n return combinedMatcher(action);\r\n };\r\n }\r\n if (!isAsyncThunkArray(asyncThunks)) {\r\n return isRejectedWithValue()(asyncThunks[0]);\r\n }\r\n return function (action) {\r\n var combinedMatcher = isAllOf(isRejected.apply(void 0, asyncThunks), hasFlag);\r\n return combinedMatcher(action);\r\n };\r\n}\r\nfunction isFulfilled() {\r\n var asyncThunks = [];\r\n for (var _i = 0; _i < arguments.length; _i++) {\r\n asyncThunks[_i] = arguments[_i];\r\n }\r\n if (asyncThunks.length === 0) {\r\n return function (action) { return hasExpectedRequestMetadata(action, [\"fulfilled\"]); };\r\n }\r\n if (!isAsyncThunkArray(asyncThunks)) {\r\n return isFulfilled()(asyncThunks[0]);\r\n }\r\n return function (action) {\r\n var matchers = asyncThunks.map(function (asyncThunk) { return asyncThunk.fulfilled; });\r\n var combinedMatcher = isAnyOf.apply(void 0, matchers);\r\n return combinedMatcher(action);\r\n };\r\n}\r\nfunction isAsyncThunkAction() {\r\n var asyncThunks = [];\r\n for (var _i = 0; _i < arguments.length; _i++) {\r\n asyncThunks[_i] = arguments[_i];\r\n }\r\n if (asyncThunks.length === 0) {\r\n return function (action) { return hasExpectedRequestMetadata(action, [\"pending\", \"fulfilled\", \"rejected\"]); };\r\n }\r\n if (!isAsyncThunkArray(asyncThunks)) {\r\n return isAsyncThunkAction()(asyncThunks[0]);\r\n }\r\n return function (action) {\r\n var matchers = [];\r\n for (var _i = 0, asyncThunks_1 = asyncThunks; _i < asyncThunks_1.length; _i++) {\r\n var asyncThunk = asyncThunks_1[_i];\r\n matchers.push(asyncThunk.pending, asyncThunk.rejected, asyncThunk.fulfilled);\r\n }\r\n var combinedMatcher = isAnyOf.apply(void 0, matchers);\r\n return combinedMatcher(action);\r\n };\r\n}\r\n// src/index.ts\r\nenableES5();\r\nexport { MiddlewareArray, configureStore, createAction, createAsyncThunk, createDraftSafeSelector, createEntityAdapter, createImmutableStateInvariantMiddleware, default2 as createNextState, createReducer, createSelector2 as createSelector, createSerializableStateInvariantMiddleware, createSlice, current2 as current, findNonSerializableValue, freeze, getDefaultMiddleware, getType, isAllOf, isAnyOf, isAsyncThunkAction, isDraft4 as isDraft, isFulfilled, isImmutableDefault, isPending, isPlain, isPlainObject, isRejected, isRejectedWithValue, miniSerializeError, nanoid, original, unwrapResult };\r\n//# sourceMappingURL=module.js.map"],"sourceRoot":""}