diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..b24d7d8 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,2 @@ +*.sh text eol=lf +*.sh text eol=lf \ No newline at end of file diff --git a/.gitignore b/.gitignore index 3e759b7..83c0980 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,14 @@ +# Custom +tools/ +build/ +.nuget/ +.dotnet/ +.idea/ +.[Dd][Ss]_[Ss]tore + +## NBench output +[Pp]erf[Rr]esult*/ + ## Ignore Visual Studio temporary files, build results, and ## files generated by popular Visual Studio add-ons. ## @@ -24,14 +35,18 @@ bld/ [Oo]bj/ [Ll]og/ -# Visual Studio 2015/2017 cache/options directory +#FAKE +.fake +tools/ + +#DocFx output +_site/ + +# Visual Studio 2015 cache/options directory .vs/ # Uncomment if you have tasks that create the project's static files in wwwroot #wwwroot/ -# Visual Studio 2017 auto generated files -Generated\ Files/ - # MSTest test Results [Tt]est[Rr]esult*/ [Bb]uild[Ll]og.* @@ -45,29 +60,20 @@ TestResult.xml [Rr]eleasePS/ dlldata.c -# Benchmark Results -BenchmarkDotNet.Artifacts/ - # .NET Core project.lock.json project.fragment.lock.json artifacts/ **/Properties/launchSettings.json -# StyleCop -StyleCopReport.xml - -# Files built by Visual Studio *_i.c *_p.c *_i.h *.ilk *.meta *.obj -*.iobj *.pch *.pdb -*.ipdb *.pgc *.pgd *.rsp @@ -105,9 +111,6 @@ ipch/ *.vspx *.sap -# Visual Studio Trace Files -*.e2e - # TFS 2012 Local Workspace $tf/ @@ -128,10 +131,6 @@ _TeamCity* # DotCover is a Code Coverage Tool *.dotCover -# AxoCover is a Code Coverage Tool -.axoCover/* -!.axoCover/settings.json - # Visual Studio code coverage results *.coverage *.coveragexml @@ -167,7 +166,7 @@ publish/ # Publish Web Output *.[Pp]ublish.xml *.azurePubxml -# Note: Comment the next line if you want to checkin your web deploy settings, +# TODO: Comment the next line if you want to checkin your web deploy settings # but database connection strings (with potential passwords) will be unencrypted *.pubxml *.publishproj @@ -180,11 +179,11 @@ PublishScripts/ # NuGet Packages *.nupkg # The packages folder can be ignored because of Package Restore -**/[Pp]ackages/* +**/packages/* # except build/, which is used as an MSBuild target. -!**/[Pp]ackages/build/ +!**/packages/build/ # Uncomment if necessary however generally it will be regenerated when needed -#!**/[Pp]ackages/repositories.config +#!**/packages/repositories.config # NuGet v3's project.json files produces more ignorable files *.nuget.props *.nuget.targets @@ -202,7 +201,6 @@ AppPackages/ BundleArtifacts/ Package.StoreAssociation.xml _pkginfo.txt -*.appx # Visual Studio cache files # files ending in .cache can be ignored @@ -221,10 +219,6 @@ ClientBin/ *.publishsettings orleans.codegen.cs -# Including strong name files can present a security risk -# (https://github.com/github/gitignore/pull/2483#issue-259490424) -#*.snk - # Since there are multiple workflows, uncomment next line to ignore bower_components # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) #bower_components/ @@ -239,8 +233,6 @@ _UpgradeReport_Files/ Backup*/ UpgradeLog*.XML UpgradeLog*.htm -ServiceFabricBackup/ -*.rptproj.bak # SQL Server files *.mdf @@ -251,7 +243,6 @@ ServiceFabricBackup/ *.rdl.data *.bim.layout *.bim_*.settings -*.rptproj.rsuser # Microsoft Fakes FakesAssemblies/ @@ -263,6 +254,9 @@ FakesAssemblies/ .ntvs_analysis.dat node_modules/ +# Typescript v1 declaration files +typings/ + # Visual Studio 6 build log *.plg @@ -302,9 +296,6 @@ __pycache__/ # tools/** # !tools/packages.config -# Tabs Studio -*.tss - # Telerik's JustMock configuration file *.jmconfig @@ -313,18 +304,3 @@ __pycache__/ *.btm.cs *.odx.cs *.xsd.cs - -# OpenCover UI analysis results -OpenCover/ - -# Azure Stream Analytics local run output -ASALocalRun/ - -# MSBuild Binary and Structured Log -*.binlog - -# NVidia Nsight GPU debugger configuration file -*.nvuser - -# MFractors (Xamarin productivity tool) working folder -.mfractor/ diff --git a/RELEASE_NOTES.md b/RELEASE_NOTES.md new file mode 100644 index 0000000..6902707 --- /dev/null +++ b/RELEASE_NOTES.md @@ -0,0 +1,13 @@ +#### 0.2.2 Feb 07 2019 #### +* Added shared DevOps infrastructure. +* Setting the stage for the use of Phobos in future releases. +* Resolved [Install pbm on all nodes](https://github.com/petabridge/Cluster.WebCrawler/issues/10) + +#### 0.2.1 Feb 07 2019 #### +* Made it possible to invoke `CoordinatedShutdown` automatically via the `AppDomain.CurrentDomain.ProcessExit` event in .NET Core on `TrackerService`, `Lighthouse`, `CrawlerService`, and the `Web` application. + +#### 0.2.0 Feb 06 2019 #### +Upgraded to .NET Core 2.1 for all services. + +#### 0.1.0 Feb 04 2019 #### +First release \ No newline at end of file diff --git a/WebCrawler.sln b/WebCrawler.sln index 2900777..f28afb5 100644 --- a/WebCrawler.sln +++ b/WebCrawler.sln @@ -15,6 +15,18 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "WebCrawler.Web", "src\WebCr EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Lighthouse", "src\Lighthouse\Lighthouse.csproj", "{7A2C40A8-F6D1-4A28-8FD4-886818D7CB35}" EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "build", "build", "{FEFC4143-1464-45FE-9276-DCEBADA7E1C6}" + ProjectSection(SolutionItems) = preProject + build.cmd = build.cmd + build.fsx = build.fsx + build.ps1 = build.ps1 + build.sh = build.sh + EndProjectSection +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "WebCrawler.Shared.DevOps", "src\WebCrawler.Shared.DevOps\WebCrawler.Shared.DevOps.csproj", "{B6DF5688-61D1-462B-9B29-37E0898E2A94}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "WebCrawler.Shared.DevOps.Tests", "src\WebCrawler.Shared.DevOps.Tests\WebCrawler.Shared.DevOps.Tests.csproj", "{FED11EA4-D0F5-4B7D-9696-135E61ED3186}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -45,6 +57,14 @@ Global {7A2C40A8-F6D1-4A28-8FD4-886818D7CB35}.Debug|Any CPU.Build.0 = Debug|Any CPU {7A2C40A8-F6D1-4A28-8FD4-886818D7CB35}.Release|Any CPU.ActiveCfg = Release|Any CPU {7A2C40A8-F6D1-4A28-8FD4-886818D7CB35}.Release|Any CPU.Build.0 = Release|Any CPU + {B6DF5688-61D1-462B-9B29-37E0898E2A94}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {B6DF5688-61D1-462B-9B29-37E0898E2A94}.Debug|Any CPU.Build.0 = Debug|Any CPU + {B6DF5688-61D1-462B-9B29-37E0898E2A94}.Release|Any CPU.ActiveCfg = Release|Any CPU + {B6DF5688-61D1-462B-9B29-37E0898E2A94}.Release|Any CPU.Build.0 = Release|Any CPU + {FED11EA4-D0F5-4B7D-9696-135E61ED3186}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {FED11EA4-D0F5-4B7D-9696-135E61ED3186}.Debug|Any CPU.Build.0 = Debug|Any CPU + {FED11EA4-D0F5-4B7D-9696-135E61ED3186}.Release|Any CPU.ActiveCfg = Release|Any CPU + {FED11EA4-D0F5-4B7D-9696-135E61ED3186}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE diff --git a/build.cmd b/build.cmd new file mode 100644 index 0000000..3cb534e --- /dev/null +++ b/build.cmd @@ -0,0 +1 @@ +PowerShell.exe -file "build.ps1" %* \ No newline at end of file diff --git a/build.fsx b/build.fsx new file mode 100644 index 0000000..f32edd2 --- /dev/null +++ b/build.fsx @@ -0,0 +1,401 @@ +#I @"tools/FAKE/tools" +#r "FakeLib.dll" + +open System +open System.IO +open System.Text + +open Fake +open Fake.DotNetCli +open Fake.DocFxHelper + +// Information about the project for Nuget and Assembly info files +let product = "Cluster.WebCrawler" +let configuration = "Release" + +// Metadata used when signing packages and DLLs +let signingName = "My Library" +let signingDescription = "My REALLY COOL Library" +let signingUrl = "https://signing.is.cool/" + +// Read release notes and version +let solutionFile = FindFirstMatchingFile "*.sln" __SOURCE_DIRECTORY__ // dynamically look up the solution +let buildNumber = environVarOrDefault "BUILD_NUMBER" "0" +let hasTeamCity = (not (buildNumber = "0")) // check if we have the TeamCity environment variable for build # set +let preReleaseVersionSuffix = "beta" + (if (not (buildNumber = "0")) then (buildNumber) else DateTime.UtcNow.Ticks.ToString()) +let versionSuffix = + match (getBuildParam "nugetprerelease") with + | "dev" -> preReleaseVersionSuffix + | _ -> "" + +let releaseNotes = + File.ReadLines "./RELEASE_NOTES.md" + |> ReleaseNotesHelper.parseReleaseNotes + +// Directories +let toolsDir = __SOURCE_DIRECTORY__ @@ "tools" +let output = __SOURCE_DIRECTORY__ @@ "bin" +let outputTests = __SOURCE_DIRECTORY__ @@ "TestResults" +let outputPerfTests = __SOURCE_DIRECTORY__ @@ "PerfResults" +let outputNuGet = output @@ "nuget" + +// Copied from original NugetCreate target +let nugetDir = output @@ "nuget" +let workingDir = output @@ "build" +let nugetExe = FullName @"./tools/nuget.exe" + +Target "Clean" (fun _ -> + ActivateFinalTarget "KillCreatedProcesses" + + CleanDir output + CleanDir outputTests + CleanDir outputPerfTests + CleanDir outputNuGet + CleanDir "docs/_site" +) + +(* + + Creates an environment variable that can be read by other processes afterwards for deployments and such + +*) +Target "SetReleaseVersion" (fun _ -> + setEnvironVar "RELEASE_NUMBER" releaseNotes.AssemblyVersion +) + +Target "AssemblyInfo" (fun _ -> + XmlPokeInnerText "./src/common.props" "//Project/PropertyGroup/VersionPrefix" releaseNotes.AssemblyVersion + XmlPokeInnerText "./src/common.props" "//Project/PropertyGroup/PackageReleaseNotes" (releaseNotes.Notes |> String.concat "\n") +) + +Target "RestorePackages" (fun _ -> + DotNetCli.Restore + (fun p -> + { p with + Project = solutionFile + NoCache = false }) +) + +Target "Build" (fun _ -> + DotNetCli.Build + (fun p -> + { p with + Project = solutionFile + Configuration = configuration }) // "Rebuild" +) + + +//-------------------------------------------------------------------------------- +// Tests targets +//-------------------------------------------------------------------------------- +module internal ResultHandling = + let (|OK|Failure|) = function + | 0 -> OK + | x -> Failure x + + let buildErrorMessage = function + | OK -> None + | Failure errorCode -> + Some (sprintf "xUnit2 reported an error (Error Code %d)" errorCode) + + let failBuildWithMessage = function + | DontFailBuild -> traceError + | _ -> (fun m -> raise(FailedTestsException m)) + + let failBuildIfXUnitReportedError errorLevel = + buildErrorMessage + >> Option.iter (failBuildWithMessage errorLevel) + +Target "RunTests" (fun _ -> + let projects = + match (isWindows) with + | true -> !! "./src/**/*.Tests.csproj" + | _ -> !! "./src/**/*.Tests.csproj" // if you need to filter specs for Linux vs. Windows, do it here + + let runSingleProject project = + let arguments = + match (hasTeamCity) with + | true -> (sprintf "test -c Release --no-build --logger:\"console;verbosity=normal\" --results-directory %s -- -parallel none -teamcity" (outputTests)) + | false -> (sprintf "test -c Release --no-build --logger:\"console;verbosity=normal\" --results-directory %s -- -parallel none" (outputTests)) + + let result = ExecProcess(fun info -> + info.FileName <- "dotnet" + info.WorkingDirectory <- (Directory.GetParent project).FullName + info.Arguments <- arguments) (TimeSpan.FromMinutes 30.0) + + ResultHandling.failBuildIfXUnitReportedError TestRunnerErrorLevel.DontFailBuild result + + projects |> Seq.iter (log) + projects |> Seq.iter (runSingleProject) +) + +Target "NBench" <| fun _ -> + let projects = + match (isWindows) with + | true -> !! "./src/**/*.Tests.Performance.csproj" + | _ -> !! "./src/**/*.Tests.Performance.csproj" // if you need to filter specs for Linux vs. Windows, do it here + + + let runSingleProject project = + let arguments = + match (hasTeamCity) with + | true -> (sprintf "nbench --nobuild --teamcity --concurrent true --trace true --output %s" (outputPerfTests)) + | false -> (sprintf "nbench --nobuild --concurrent true --trace true --output %s" (outputPerfTests)) + + let result = ExecProcess(fun info -> + info.FileName <- "dotnet" + info.WorkingDirectory <- (Directory.GetParent project).FullName + info.Arguments <- arguments) (TimeSpan.FromMinutes 30.0) + + ResultHandling.failBuildIfXUnitReportedError TestRunnerErrorLevel.DontFailBuild result + + projects |> Seq.iter runSingleProject + + +//-------------------------------------------------------------------------------- +// Code signing targets +//-------------------------------------------------------------------------------- +Target "SignPackages" (fun _ -> + let canSign = hasBuildParam "SignClientSecret" && hasBuildParam "SignClientUser" + if(canSign) then + log "Signing information is available." + + let assemblies = !! (outputNuGet @@ "*.nupkg") + + let signPath = + let globalTool = tryFindFileOnPath "SignClient.exe" + match globalTool with + | Some t -> t + | None -> if isWindows then findToolInSubPath "SignClient.exe" "tools/signclient" + elif isMacOS then findToolInSubPath "SignClient" "tools/signclient" + else findToolInSubPath "SignClient" "tools/signclient" + + let signAssembly assembly = + let args = StringBuilder() + |> append "sign" + |> append "--config" + |> append (__SOURCE_DIRECTORY__ @@ "appsettings.json") + |> append "-i" + |> append assembly + |> append "-r" + |> append (getBuildParam "SignClientUser") + |> append "-s" + |> append (getBuildParam "SignClientSecret") + |> append "-n" + |> append signingName + |> append "-d" + |> append signingDescription + |> append "-u" + |> append signingUrl + |> toText + + let result = ExecProcess(fun info -> + info.FileName <- signPath + info.WorkingDirectory <- __SOURCE_DIRECTORY__ + info.Arguments <- args) (System.TimeSpan.FromMinutes 5.0) (* Reasonably long-running task. *) + if result <> 0 then failwithf "SignClient failed.%s" args + + assemblies |> Seq.iter (signAssembly) + else + log "SignClientSecret not available. Skipping signing" +) + +//-------------------------------------------------------------------------------- +// Nuget targets +//-------------------------------------------------------------------------------- + +let overrideVersionSuffix (project:string) = + match project with + | _ -> versionSuffix // add additional matches to publish different versions for different projects in solution +Target "CreateNuget" (fun _ -> + let projects = !! "src/**/*.csproj" + -- "src/**/*Tests.csproj" // Don't publish unit tests + -- "src/**/*Tests*.csproj" + + let runSingleProject project = + DotNetCli.Pack + (fun p -> + { p with + Project = project + Configuration = configuration + AdditionalArgs = ["--include-symbols --no-build"] + VersionSuffix = overrideVersionSuffix project + OutputPath = outputNuGet }) + + projects |> Seq.iter (runSingleProject) +) + +Target "PublishNuget" (fun _ -> + let projects = !! "./bin/nuget/*.nupkg" -- "./bin/nuget/*.symbols.nupkg" + let apiKey = getBuildParamOrDefault "nugetkey" "" + let source = getBuildParamOrDefault "nugetpublishurl" "" + let symbolSource = getBuildParamOrDefault "symbolspublishurl" "" + let shouldPublishSymbolsPackages = not (symbolSource = "") + + if (not (source = "") && not (apiKey = "") && shouldPublishSymbolsPackages) then + let runSingleProject project = + DotNetCli.RunCommand + (fun p -> + { p with + TimeOut = TimeSpan.FromMinutes 10. }) + (sprintf "nuget push %s --api-key %s --source %s --symbol-source %s" project apiKey source symbolSource) + + projects |> Seq.iter (runSingleProject) + else if (not (source = "") && not (apiKey = "") && not shouldPublishSymbolsPackages) then + let runSingleProject project = + DotNetCli.RunCommand + (fun p -> + { p with + TimeOut = TimeSpan.FromMinutes 10. }) + (sprintf "nuget push %s --api-key %s --source %s" project apiKey source) + + projects |> Seq.iter (runSingleProject) +) + +//-------------------------------------------------------------------------------- +// Documentation +//-------------------------------------------------------------------------------- +Target "DocFx" (fun _ -> + DotNetCli.Restore (fun p -> { p with Project = solutionFile }) + DotNetCli.Build (fun p -> { p with Project = solutionFile; Configuration = configuration }) + + let docsPath = "./docs" + + DocFx (fun p -> + { p with + Timeout = TimeSpan.FromMinutes 30.0; + WorkingDirectory = docsPath; + DocFxJson = docsPath @@ "docfx.json" }) +) + +//-------------------------------------------------------------------------------- +// Docker Targets +//-------------------------------------------------------------------------------- +Target "PublishCode" (fun _ -> + let projects = !! "src/**/*.csproj" + -- "src/WebCrawler.Shared/*.csproj" + -- "src/WebCrawler.Shared.*/*.csproj" + -- "src/**/*Tests.csproj" // Don't publish unit tests + -- "src/**/*Tests*.csproj" + + let runSingleProject project = + DotNetCli.Publish + (fun p -> + { p with + Project = project + Configuration = configuration + VersionSuffix = overrideVersionSuffix project + }) + + projects |> Seq.iter (runSingleProject) +) + +let mapDockerImageName (projectName:string) = + match projectName with + | "Lighthouse" -> Some("webcrawler.lighthouse") + | "WebCrawler.CrawlService" -> Some("webcrawler.crawlservice") + | "WebCrawler.TrackerService" -> Some("webcrawler.trackerservice") + | "WebCrawler.Web" -> Some("webcrawler.web") + | _ -> None + +Target "BuildDockerImages" (fun _ -> + let projects = !! "src/**/*.csproj" + -- "src/**/*Tests.csproj" // Don't publish unit tests + -- "src/**/*Tests*.csproj" + + let buildDockerImage imageName projectPath = + let args = StringBuilder() + |> append "build" + |> append "-t" + |> append (imageName + ":" + releaseNotes.AssemblyVersion) + |> append "-t" + |> append (imageName + ":latest") + |> append "." + |> toText + + ExecProcess(fun info -> + info.FileName <- "docker" + info.WorkingDirectory <- Path.GetDirectoryName projectPath + info.Arguments <- args) (System.TimeSpan.FromMinutes 5.0) (* Reasonably long-running task. *) + + let runSingleProject project = + let projectName = Path.GetFileNameWithoutExtension project + let imageName = mapDockerImageName projectName + let result = match imageName with + | None -> 0 + | Some(name) -> buildDockerImage name project + if result <> 0 then failwithf "docker build failed. %s" project + + projects |> Seq.iter (runSingleProject) +) + +//-------------------------------------------------------------------------------- +// Cleanup +//-------------------------------------------------------------------------------- + +FinalTarget "KillCreatedProcesses" (fun _ -> + log "Shutting down dotnet build-server" + let result = ExecProcess(fun info -> + info.FileName <- "dotnet" + info.WorkingDirectory <- __SOURCE_DIRECTORY__ + info.Arguments <- "build-server shutdown") (System.TimeSpan.FromMinutes 2.0) + if result <> 0 then failwithf "dotnet build-server shutdown failed" +) + +//-------------------------------------------------------------------------------- +// Help +//-------------------------------------------------------------------------------- + +Target "Help" <| fun _ -> + List.iter printfn [ + "usage:" + "./build.ps1 [target]" + "" + " Targets for building:" + " * Build Builds" + " * Nuget Create and optionally publish nugets packages" + " * SignPackages Signs all NuGet packages, provided that the following arguments are passed into the script: SignClientSecret={secret} and SignClientUser={username}" + " * RunTests Runs tests" + " * All Builds, run tests, creates and optionally publish nuget packages" + " * DocFx Creates a DocFx-based website for this solution" + "" + " Other Targets" + " * Help Display this help" + ""] + +//-------------------------------------------------------------------------------- +// Target dependencies +//-------------------------------------------------------------------------------- + +Target "BuildRelease" DoNothing +Target "All" DoNothing +Target "Nuget" DoNothing +Target "Docker" DoNothing +Target "PrepareDeploy" DoNothing + +// build dependencies +"Clean" ==> "RestorePackages" ==> "SetReleaseVersion" ==> "AssemblyInfo" ==> "Build" ==> "BuildRelease" + +// tests dependencies +"Clean" ==> "RestorePackages" ==> "Build" ==> "RunTests" + +// nuget dependencies +"Clean" ==> "RestorePackages" ==> "Build" ==> "CreateNuget" +"CreateNuget" ==> "SignPackages" ==> "PublishNuget" ==> "Nuget" + +// docs +"Clean" ==> "RestorePackages" ==> "BuildRelease" ==> "Docfx" + +// Docker +"Clean" ==> "PublishCode" ==> "BuildDockerImages" ==> "Docker" + +// all +"BuildRelease" ==> "All" +"RunTests" ==> "All" +"NBench" ==> "All" +"Nuget" ==> "All" + +// Deploy +"BuildRelease" ==> "Docker" ==> "PrepareDeploy" + +RunTargetOrDefault "Help" \ No newline at end of file diff --git a/build.ps1 b/build.ps1 new file mode 100644 index 0000000..4e9a3e4 --- /dev/null +++ b/build.ps1 @@ -0,0 +1,336 @@ +<# +.SYNOPSIS +This is a Powershell script to bootstrap a Fake build. +.DESCRIPTION +This Powershell script will download NuGet if missing, restore NuGet tools (including Fake) +and execute your Fake build script with the parameters you provide. +.PARAMETER Target +The build script target to run. +.PARAMETER Configuration +The build configuration to use. +.PARAMETER Verbosity +Specifies the amount of information to be displayed. +.PARAMETER WhatIf +Performs a dry run of the build script. +No tasks will be executed. +.PARAMETER ScriptArgs +Remaining arguments are added here. +#> + +[CmdletBinding()] +Param( + [string]$Target = "Default", + [ValidateSet("Release", "Debug")] + [string]$Configuration = "Release", + [ValidateSet("Quiet", "Minimal", "Normal", "Verbose", "Diagnostic")] + [string]$Verbosity = "Verbose", + [switch]$WhatIf, + [Parameter(Position=0,Mandatory=$false,ValueFromRemainingArguments=$true)] + [string[]]$ScriptArgs +) + +$FakeVersion = "4.61.2" +$DotNetChannel = "LTS"; +$DotNetVersion = "2.1.500"; +$DotNetInstallerUri = "https://raw.githubusercontent.com/dotnet/cli/v$DotNetVersion/scripts/obtain/dotnet-install.ps1"; +$NugetVersion = "4.1.0"; +$NugetUrl = "https://dist.nuget.org/win-x86-commandline/v$NugetVersion/nuget.exe" +$ProtobufVersion = "3.4.0" +$DocfxVersion = "2.40.5" + +# Make sure tools folder exists +$PSScriptRoot = Split-Path $MyInvocation.MyCommand.Path -Parent +$ToolPath = Join-Path $PSScriptRoot "tools" +if (!(Test-Path $ToolPath)) { + Write-Verbose "Creating tools directory..." + New-Item -Path $ToolPath -Type directory | out-null +} + +########################################################################### +# INSTALL .NET CORE CLI +########################################################################### + +Function Remove-PathVariable([string]$VariableToRemove) +{ + $path = [Environment]::GetEnvironmentVariable("PATH", "User") + if ($path -ne $null) + { + $newItems = $path.Split(';', [StringSplitOptions]::RemoveEmptyEntries) | Where-Object { "$($_)" -inotlike $VariableToRemove } + [Environment]::SetEnvironmentVariable("PATH", [System.String]::Join(';', $newItems), "User") + } + + $path = [Environment]::GetEnvironmentVariable("PATH", "Process") + if ($path -ne $null) + { + $newItems = $path.Split(';', [StringSplitOptions]::RemoveEmptyEntries) | Where-Object { "$($_)" -inotlike $VariableToRemove } + [Environment]::SetEnvironmentVariable("PATH", [System.String]::Join(';', $newItems), "Process") + } +} + +# Get .NET Core CLI path if installed. +$FoundDotNetCliVersion = $null; +if (Get-Command dotnet -ErrorAction SilentlyContinue) { + $FoundDotNetCliVersion = dotnet --version; + $env:DOTNET_SKIP_FIRST_TIME_EXPERIENCE=1 + $env:DOTNET_CLI_TELEMETRY_OPTOUT=1 +} + +if($FoundDotNetCliVersion -ne $DotNetVersion) { + $InstallPath = Join-Path $PSScriptRoot ".dotnet" + if (!(Test-Path $InstallPath)) { + mkdir -Force $InstallPath | Out-Null; + } + (New-Object System.Net.WebClient).DownloadFile($DotNetInstallerUri, "$InstallPath\dotnet-install.ps1"); + & $InstallPath\dotnet-install.ps1 -Channel $DotNetChannel -Version $DotNetVersion -InstallDir $InstallPath -Architecture x64; + + Remove-PathVariable "$InstallPath" + $env:PATH = "$InstallPath;$env:PATH" + $env:DOTNET_SKIP_FIRST_TIME_EXPERIENCE=1 + $env:DOTNET_CLI_TELEMETRY_OPTOUT=1 +} + +########################################################################### +# INSTALL NUGET +########################################################################### + +# Make sure nuget.exe exists. +$NugetPath = Join-Path $ToolPath "nuget.exe" +if (!(Test-Path $NugetPath)) { + Write-Host "Downloading NuGet.exe..." + (New-Object System.Net.WebClient).DownloadFile($NugetUrl, $NugetPath); +} + +########################################################################### +# INSTALL FAKE +########################################################################### +# Make sure Fake has been installed. + +$FakeExePath = Join-Path $ToolPath "FAKE/tools/FAKE.exe" +if (!(Test-Path $FakeExePath)) { + Write-Host "Installing Fake..." + Invoke-Expression "&`"$NugetPath`" install Fake -ExcludeVersion -Version $FakeVersion -OutputDirectory `"$ToolPath`"" | Out-Null; + if ($LASTEXITCODE -ne 0) { + Throw "An error occured while restoring Fake from NuGet." + } +} + +########################################################################### +# Docfx +########################################################################### + +# Make sure Docfx has been installed. +$DocfxExePath = Join-Path $ToolPath "docfx.console/tools/docfx.exe" +if (!(Test-Path $DocfxExePath)) { + Write-Host "Installing Docfx..." + Invoke-Expression "&`"$NugetPath`" install docfx.console -ExcludeVersion -Version $DocfxVersion -OutputDirectory `"$ToolPath`"" | Out-Null; + if ($LASTEXITCODE -ne 0) { + Throw "An error occured while restoring docfx.console from NuGet." + } +} + +########################################################################### +# SignTool +########################################################################### + +# Make sure the SignClient has been installed +if (Get-Command signclient -ErrorAction SilentlyContinue) { + Write-Host "Found SignClient. Skipping install." +} +else{ + $SignClientFolder = Join-Path $ToolPath "signclient" + Write-Host "SignClient not found. Installing to ... $SignClientFolder" + dotnet tool install SignClient --version 1.0.82 --tool-path "$SignClientFolder" +} + +########################################################################### +# RUN BUILD SCRIPT +########################################################################### + +# Build the argument list. +$Arguments = @{ + target=$Target; + configuration=$Configuration; + verbosity=$Verbosity; + dryrun=$WhatIf; +}.GetEnumerator() | %{"--{0}=`"{1}`"" -f $_.key, $_.value }; + +# Start Fake +Write-Host "Running build script..." +Invoke-Expression "$FakeExePath `"build.fsx`" $ScriptArgs $Arguments" + +exit $LASTEXITCODE +# SIG # Begin signature block +# MIIgTwYJKoZIhvcNAQcCoIIgQDCCIDwCAQExDzANBglghkgBZQMEAgEFADB5Bgor +# BgEEAYI3AgEEoGswaTA0BgorBgEEAYI3AgEeMCYCAwEAAAQQH8w7YFlLCE63JNLG +# KX7zUQIBAAIBAAIBAAIBAAIBADAxMA0GCWCGSAFlAwQCAQUABCBE0jzTDwazSHs/ +# gLc53cqa6x5OxdrKHZEi0WVogAAGB6CCDiIwggO3MIICn6ADAgECAhAM5+DlF9hG +# /o/lYPwb8DA5MA0GCSqGSIb3DQEBBQUAMGUxCzAJBgNVBAYTAlVTMRUwEwYDVQQK +# EwxEaWdpQ2VydCBJbmMxGTAXBgNVBAsTEHd3dy5kaWdpY2VydC5jb20xJDAiBgNV +# BAMTG0RpZ2lDZXJ0IEFzc3VyZWQgSUQgUm9vdCBDQTAeFw0wNjExMTAwMDAwMDBa +# Fw0zMTExMTAwMDAwMDBaMGUxCzAJBgNVBAYTAlVTMRUwEwYDVQQKEwxEaWdpQ2Vy +# dCBJbmMxGTAXBgNVBAsTEHd3dy5kaWdpY2VydC5jb20xJDAiBgNVBAMTG0RpZ2lD +# ZXJ0IEFzc3VyZWQgSUQgUm9vdCBDQTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCC +# AQoCggEBAK0OFc7kQ4BcsYfzt2D5cRKlrtwmlIiq9M71IDkoWGAM+IDaqRWVMmE8 +# tbEohIqK3J8KDIMXeo+QrIrneVNcMYQq9g+YMjZ2zN7dPKii72r7IfJSYd+fINcf +# 4rHZ/hhk0hJbX/lYGDW8R82hNvlrf9SwOD7BG8OMM9nYLxj+KA+zp4PWw25EwGE1 +# lhb+WZyLdm3X8aJLDSv/C3LanmDQjpA1xnhVhyChz+VtCshJfDGYM2wi6YfQMlqi +# uhOCEe05F52ZOnKh5vqk2dUXMXWuhX0irj8BRob2KHnIsdrkVxfEfhwOs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HAgh8Sa4TtuF8QkIoxhhWz0E0tmZdtnR79VYzIi8iNrJLokqV2PWm +# jlIxggJNMIICSQIBATCBhjByMQswCQYDVQQGEwJVUzEVMBMGA1UEChMMRGlnaUNl +# cnQgSW5jMRkwFwYDVQQLExB3d3cuZGlnaWNlcnQuY29tMTEwLwYDVQQDEyhEaWdp +# Q2VydCBTSEEyIEFzc3VyZWQgSUQgVGltZXN0YW1waW5nIENBAhAJwPxGyARCE7VZ +# i68oT05BMA0GCWCGSAFlAwQCAQUAoIGYMBoGCSqGSIb3DQEJAzENBgsqhkiG9w0B +# CRABBDAcBgkqhkiG9w0BCQUxDxcNMTgxMjMxMjIyMjE5WjArBgsqhkiG9w0BCRAC +# DDEcMBowGDAWBBRAAZFHXJiJHeuhBK9HCRtettTLyzAvBgkqhkiG9w0BCQQxIgQg +# DuDbP/oIRKuz94N4Kuag2Y1WotWj9oZU0MTaGEa5ynUwDQYJKoZIhvcNAQEBBQAE +# ggEAS0HrLgkQmG9B2SOTeGrNT1eLdl9Eb9yY1exfb9uQBWQopI66aqTkLr9uyYrc +# UndjRp391Nxqkw30jr4geLBavjA12fLEY3mzESgMkLiFloavlcUgBdAwW7S7sGgZ +# D9220Q1/Uk5FniT3LqPWpDEwsMP1u5Ob5mZeb7JbmlbPWkWtwtrO/ledrpCiXuth +# hzjwwpaWllc33KKa7hykVS6aycrRMWW8UdAF+EYH0qcyLU2LBl+BuhEPhjMjOwm6 +# v7+DDMVeZqIa580kBZHrZhqiZV83DUf9MFevebnc+GgU/1XswzzWqkYPpTb61ySG +# YQLWggh/qRiHiAmURpgBnqhomQ== +# SIG # End signature block diff --git a/build.sh b/build.sh new file mode 100644 index 0000000..73752bc --- /dev/null +++ b/build.sh @@ -0,0 +1,132 @@ +#!/usr/bin/env bash +########################################################################## +# This is the Fake bootstrapper script for Linux and OS X. +########################################################################## + +# Define directories. +SCRIPT_DIR=$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd ) +TOOLS_DIR=$SCRIPT_DIR/tools +SIGNCLIENT_DIR=$TOOLS_DIR/signclient +NUGET_EXE=$TOOLS_DIR/nuget.exe +NUGET_URL=https://dist.nuget.org/win-x86-commandline/v4.0.0/nuget.exe +FAKE_VERSION=4.61.2 +FAKE_EXE=$TOOLS_DIR/FAKE/tools/FAKE.exe +DOTNET_VERSION=2.1.500 +DOTNET_INSTALLER_URL=https://raw.githubusercontent.com/dotnet/cli/v$DOTNET_VERSION/scripts/obtain/dotnet-install.sh +DOTNET_CHANNEL=LTS; +DOCFX_VERSION=2.40.5 +DOCFX_EXE=$TOOLS_DIR/docfx.console/tools/docfx.exe + +# Define default arguments. +TARGET="Default" +CONFIGURATION="Release" +VERBOSITY="verbose" +DRYRUN= +SCRIPT_ARGUMENTS=() + +# Parse arguments. +for i in "$@"; do + case $1 in + -t|--target) TARGET="$2"; shift ;; + -c|--configuration) CONFIGURATION="$2"; shift ;; + -v|--verbosity) VERBOSITY="$2"; shift ;; + -d|--dryrun) DRYRUN="-dryrun" ;; + --) shift; SCRIPT_ARGUMENTS+=("$@"); break ;; + *) SCRIPT_ARGUMENTS+=("$1") ;; + esac + shift +done + +# Make sure the tools folder exist. +if [ ! -d "$TOOLS_DIR" ]; then + mkdir "$TOOLS_DIR" +fi + +########################################################################### +# INSTALL .NET CORE CLI +########################################################################### + +echo "Installing .NET CLI..." +if [ ! -d "$SCRIPT_DIR/.dotnet" ]; then + mkdir "$SCRIPT_DIR/.dotnet" +fi +curl -Lsfo "$SCRIPT_DIR/.dotnet/dotnet-install.sh" $DOTNET_INSTALLER_URL +bash "$SCRIPT_DIR/.dotnet/dotnet-install.sh" --version $DOTNET_VERSION --channel $DOTNET_CHANNEL --install-dir .dotnet --no-path +export PATH="$SCRIPT_DIR/.dotnet":$PATH +export DOTNET_SKIP_FIRST_TIME_EXPERIENCE=1 +export DOTNET_CLI_TELEMETRY_OPTOUT=1 +chmod -R 0755 ".dotnet" +"$SCRIPT_DIR/.dotnet/dotnet" --info + + +########################################################################### +# INSTALL NUGET +########################################################################### + +# Download NuGet if it does not exist. +if [ ! -f "$NUGET_EXE" ]; then + echo "Downloading NuGet..." + curl -Lsfo "$NUGET_EXE" $NUGET_URL + if [ $? -ne 0 ]; then + echo "An error occured while downloading nuget.exe." + exit 1 + fi +fi + +########################################################################### +# INSTALL FAKE +########################################################################### + +if [ ! -f "$FAKE_EXE" ]; then + mono "$NUGET_EXE" install Fake -ExcludeVersion -Version $FAKE_VERSION -OutputDirectory "$TOOLS_DIR" + if [ $? -ne 0 ]; then + echo "An error occured while installing Cake." + exit 1 + fi +fi + +# Make sure that Fake has been installed. +if [ ! -f "$FAKE_EXE" ]; then + echo "Could not find Fake.exe at '$FAKE_EXE'." + exit 1 +fi + +########################################################################### +# INSTALL DOCFX +########################################################################### +if [ ! -f "$DOCFX_EXE" ]; then + mono "$NUGET_EXE" install docfx.console -ExcludeVersion -Version $DOCFX_VERSION -OutputDirectory "$TOOLS_DIR" + if [ $? -ne 0 ]; then + echo "An error occured while installing DocFx." + exit 1 + fi +fi + +# Make sure that DocFx has been installed. +if [ ! -f "$DOCFX_EXE" ]; then + echo "Could not find docfx.exe at '$DOCFX_EXE'." + exit 1 +fi + +########################################################################### +# INSTALL SignTool +########################################################################### +if [ ! -f "$SIGNTOOL_EXE" ]; then + "$SCRIPT_DIR/.dotnet/dotnet" tool install SignClient --version 1.0.82 --tool-path "$SIGNCLIENT_DIR" + if [ $? -ne 0 ]; then + echo "SignClient already installed." + fi +fi + + +########################################################################### +# WORKAROUND FOR MONO +########################################################################### +export FrameworkPathOverride=/usr/lib/mono/4.5/ + +########################################################################### +# RUN BUILD SCRIPT +########################################################################### + +# Start Fake +exec mono "$FAKE_EXE" build.fsx "${SCRIPT_ARGUMENTS[@]}" --verbosity=$VERBOSITY --configuration=$CONFIGURATION --target=$TARGET $DRYRUN diff --git a/docker-compose.ci.build.yml b/docker-compose.ci.build.yml deleted file mode 100644 index 4df3cf0..0000000 --- a/docker-compose.ci.build.yml +++ /dev/null @@ -1,9 +0,0 @@ -version: '3.4' - -services: - ci-build: - image: microsoft/aspnetcore-build:1.0-2.0 - volumes: - - .:/src - working_dir: /src - command: /bin/bash -c "dotnet restore ./WebCrawler.sln && dotnet publish ./WebCrawler.sln -c Release -o ./obj/Docker/publish" diff --git a/docker-compose.dcproj b/docker-compose.dcproj deleted file mode 100644 index fd17d00..0000000 --- a/docker-compose.dcproj +++ /dev/null @@ -1,19 +0,0 @@ - - - - 2.1 - Linux - 188b87e9-7ff0-4488-a340-fe8a62688b27 - True - http://localhost:{ServicePort} - webcrawler.web - - - - docker-compose.yml - - - - - - \ No newline at end of file diff --git a/docker-compose.override.yml b/docker-compose.override.yml index adfee4b..18d45d3 100644 --- a/docker-compose.override.yml +++ b/docker-compose.override.yml @@ -1,4 +1,4 @@ -version: '3.4' +version: '3' services: webcrawler.web: diff --git a/docker-compose.yml b/docker-compose.yml index e63d074..163208f 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -1,52 +1,52 @@ -version: '3.4' +version: '3' services: - lighthouse: - image: petabridge/lighthouse:v0.9.2 + webcrawler.lighthouse: + image: webcrawler.lighthouse:latest + hostname: webcrawler.lighthouse ports: - '9110:9110' - '4053:4053' environment: ACTORSYSTEM: "webcrawler" - CLUSTER_IP: lighthouse CLUSTER_PORT: 4053 - CLUSTER_SEEDS: "akka.tcp://webcrawler@lighthouse:4053" + CLUSTER_IP: "webcrawler.lighthouse" + CLUSTER_SEEDS: "akka.tcp://webcrawler@webcrawler.lighthouse:4053" + webcrawler.lighthouse2: + image: webcrawler.lighthouse:latest + ports: + - '0:9110' + - '0:4053' + environment: + ACTORSYSTEM: "webcrawler" + CLUSTER_PORT: 4053 + CLUSTER_SEEDS: "akka.tcp://webcrawler@webcrawler.lighthouse:4053" + depends_on: + - "webcrawler.lighthouse" webcrawler.web: - image: webcrawler.web - build: - context: . - dockerfile: src/WebCrawler.Web/Dockerfile + image: webcrawler.web:latest ports: - - '8080:80' + - '0:80' environment: - CLUSTER_SEEDS: "akka.tcp://webcrawler@lighthouse:4053" - CLUSTER_IP: webcrawler.web + CLUSTER_SEEDS: "akka.tcp://webcrawler@webcrawler.lighthouse:4053" CLUSTER_PORT: 0 depends_on: - - "lighthouse" + - "webcrawler.lighthouse" webcrawler.crawlservice: - image: webcrawler.crawlservice - build: - context: . - dockerfile: src/WebCrawler.CrawlService/Dockerfile + image: webcrawler.crawlservice:latest environment: - CLUSTER_SEEDS: "akka.tcp://webcrawler@lighthouse:4053" - CLUSTER_IP: webcrawler.crawlservice + CLUSTER_SEEDS: "akka.tcp://webcrawler@webcrawler.lighthouse:4053" CLUSTER_PORT: 0 depends_on: - - "lighthouse" + - "webcrawler.lighthouse" webcrawler.trackerservice: - image: webcrawler.trackerservice - build: - context: . - dockerfile: src/WebCrawler.TrackerService/Dockerfile + image: webcrawler.trackerservice:latest environment: - CLUSTER_SEEDS: "akka.tcp://webcrawler@lighthouse:4053" - CLUSTER_IP: webcrawler.trackerservice + CLUSTER_SEEDS: "akka.tcp://webcrawler@webcrawler.lighthouse:4053" CLUSTER_PORT: 0 depends_on: - - "lighthouse" + - "webcrawler.lighthouse" diff --git a/docker-images.txt b/docker-images.txt new file mode 100644 index 0000000..998e273 --- /dev/null +++ b/docker-images.txt @@ -0,0 +1,4 @@ +webcrawler.lighthouse +webcrawler.crawlservice +webcrawler.trackerservice +webcrawler.web \ No newline at end of file diff --git a/get-dockerip.sh b/get-dockerip.sh deleted file mode 100644 index b73aa8b..0000000 --- a/get-dockerip.sh +++ /dev/null @@ -1,10 +0,0 @@ -#!/bin/sh -if [ -z "$CLUSTER_IP"]; then - host=$(hostname -i) - echo "Docker container bound on $host" - export CLUSTER_IP="$host" -else - echo "Docker container bound on $CLUSTER_IP" -fi - -exec "$@" \ No newline at end of file diff --git a/src/Lighthouse/Dockerfile b/src/Lighthouse/Dockerfile index f9212d4..c8dcf13 100644 --- a/src/Lighthouse/Dockerfile +++ b/src/Lighthouse/Dockerfile @@ -1,25 +1,23 @@ -FROM microsoft/dotnet:1.1-sdk AS build-env +FROM microsoft/dotnet:2.1-sdk AS base WORKDIR /app -ENV ACTORSYSTEM "lighthouse" - # should be a comma-delimited list -ENV SEEDS "[]" - -COPY src/Lighthouse/*.csproj ./ -RUN dotnet restore +ENV CLUSTER_SEEDS "[]" +ENV CLUSTER_IP "" +ENV CLUSTER_PORT "4053" -COPY src/Lighthouse ./ -RUN dotnet publish -c Release --framework netcoreapp1.1 -o out - -FROM microsoft/dotnet:1.1-runtime AS runtime -WORKDIR /app -COPY --from=build-env /app/out ./ -COPY --from=build-env /app/get-dockerip.sh ./get-dockerip.sh -ENTRYPOINT ["/bin/bash","get-dockerip.sh"] +COPY ./bin/Release/netcoreapp2.1/publish/ /app # 9110 - Petabridge.Cmd # 4053 - Akka.Cluster EXPOSE 9110 4053 +# Install Petabridge.Cmd client +RUN dotnet tool install --global pbm + +# Needed because https://stackoverflow.com/questions/51977474/install-dotnet-core-tool-dockerfile +ENV PATH="${PATH}:/root/.dotnet/tools" + +# RUN pbm help + CMD ["dotnet", "Lighthouse.dll"] \ No newline at end of file diff --git a/src/Lighthouse/Lighthouse.csproj b/src/Lighthouse/Lighthouse.csproj index 7903e06..fffab4f 100644 --- a/src/Lighthouse/Lighthouse.csproj +++ b/src/Lighthouse/Lighthouse.csproj @@ -2,13 +2,17 @@ Exe - $(NetCoreVersion) + $(NetCoreVersion) + - + + + + diff --git a/src/Lighthouse/LighthouseHostFactory.cs b/src/Lighthouse/LighthouseHostFactory.cs index be0697a..7ccbcd3 100644 --- a/src/Lighthouse/LighthouseHostFactory.cs +++ b/src/Lighthouse/LighthouseHostFactory.cs @@ -1,8 +1,11 @@ using System; using System.IO; using System.Linq; +using System.Net; using Akka.Actor; +using Akka.Bootstrap.Docker; using Akka.Configuration; +using WebCrawler.Shared.DevOps; using ConfigurationException = Akka.Configuration.ConfigurationException; namespace Lighthouse @@ -12,20 +15,11 @@ namespace Lighthouse /// public static class LighthouseHostFactory { - public static ActorSystem LaunchLighthouse(string ipAddress = null, int? specifiedPort = null, string systemName = null) + public static ActorSystem LaunchLighthouse() { - systemName = systemName ?? Environment.GetEnvironmentVariable("ACTORSYSTEM")?.Trim(); - ipAddress = ipAddress ?? Environment.GetEnvironmentVariable("CLUSTER_IP")?.Trim(); - if (specifiedPort == null) - { - var envPort = Environment.GetEnvironmentVariable("CLUSTER_PORT")?.Trim(); - if (!string.IsNullOrEmpty(envPort) && int.TryParse(envPort, out var actualPort)) - { - specifiedPort = actualPort; - } - } + var systemName = Environment.GetEnvironmentVariable("ACTORSYSTEM")?.Trim(); - var clusterConfig = ConfigurationFactory.ParseString(File.ReadAllText("akka.hocon")); + var clusterConfig = ConfigurationFactory.ParseString(File.ReadAllText("akka.hocon")).ApplyOpsConfig(); var lighthouseConfig = clusterConfig.GetConfig("lighthouse"); if (lighthouseConfig != null && string.IsNullOrEmpty(systemName)) @@ -33,17 +27,8 @@ public static ActorSystem LaunchLighthouse(string ipAddress = null, int? specifi systemName = lighthouseConfig.GetString("actorsystem", systemName); } - var remoteConfig = clusterConfig.GetConfig("akka.remote"); - - if (string.IsNullOrEmpty(ipAddress)) - { - ipAddress = remoteConfig.GetString("dot-netty.tcp.public-hostname") ?? - "127.0.0.1"; //localhost as a final default - } - - int port = specifiedPort ?? remoteConfig.GetInt("dot-netty.tcp.port"); - - if (port == 0) throw new ConfigurationException("Need to specify an explicit port for Lighthouse. Found an undefined port or a port value of 0 in App.config."); + var ipAddress = clusterConfig.GetString("akka.remote.dot-netty.tcp.public-hostname"); + var port = clusterConfig.GetInt("akka.remote.dot-netty.tcp.port"); var selfAddress = $"akka.tcp://{systemName}@{ipAddress}:{port}"; @@ -55,34 +40,34 @@ public static ActorSystem LaunchLighthouse(string ipAddress = null, int? specifi selfAddress = new Address("akka.tcp", systemName, ipAddress.Trim(), port).ToString(); Console.WriteLine("[Lighthouse] Parse successful."); - var clusterSeeds = Environment.GetEnvironmentVariable("CLUSTER_SEEDS")?.Trim(); - var seeds = clusterConfig.GetStringList("akka.cluster.seed-nodes"); - if (!string.IsNullOrEmpty(clusterSeeds)) - { - var tempSeeds = clusterSeeds.Trim('[', ']').Split(','); - if (tempSeeds.Any()) - { - seeds = tempSeeds; - } - } + var seeds = clusterConfig.GetStringList("akka.cluster.seed-nodes").ToList(); + + Config injectedClusterConfigString = null; + - if (!seeds.Contains(selfAddress)) { seeds.Add(selfAddress); + + if (seeds.Count > 1) + { + injectedClusterConfigString = seeds.Aggregate("akka.cluster.seed-nodes = [", (current, seed) => current + (@"""" + seed + @""", ")); + injectedClusterConfigString += "]"; + } + else + { + injectedClusterConfigString = "akka.cluster.seed-nodes = [\""+ selfAddress +"\"]"; + } } - var injectedClusterConfigString = seeds.Aggregate("akka.cluster.seed-nodes = [", (current, seed) => current + (@"""" + seed + @""", ")); - injectedClusterConfigString += "]"; + - var finalConfig = ConfigurationFactory.ParseString( - string.Format(@"akka.remote.dot-netty.tcp.public-hostname = {0} -akka.remote.dot-netty.tcp.port = {1}", ipAddress, port)) - .WithFallback(ConfigurationFactory.ParseString(injectedClusterConfigString)) - .WithFallback(clusterConfig); + var finalConfig = injectedClusterConfigString != null ? injectedClusterConfigString + .WithFallback(clusterConfig) : clusterConfig; - return ActorSystem.Create(systemName, finalConfig); + return ActorSystem.Create(systemName, finalConfig) + .StartPbm(); } } } diff --git a/src/Lighthouse/LighthouseService.cs b/src/Lighthouse/LighthouseService.cs index 872c4d2..d89747c 100644 --- a/src/Lighthouse/LighthouseService.cs +++ b/src/Lighthouse/LighthouseService.cs @@ -22,27 +22,11 @@ namespace Lighthouse { public class LighthouseService { - private readonly string _ipAddress; - private readonly int? _port; - private readonly string _actorSystemName; - private ActorSystem _lighthouseSystem; - public LighthouseService() : this(null, null, null) { } - - public LighthouseService(string ipAddress, int? port, string actorSystemName) - { - _ipAddress = ipAddress; - _port = port; - _actorSystemName = actorSystemName; - } - public void Start() { - _lighthouseSystem = LighthouseHostFactory.LaunchLighthouse(_ipAddress, _port, _actorSystemName); - var pbm = PetabridgeCmd.Get(_lighthouseSystem); - pbm.RegisterCommandPalette(ClusterCommands.Instance); // enable cluster management commands - pbm.Start(); + _lighthouseSystem = LighthouseHostFactory.LaunchLighthouse(); } /// diff --git a/src/Lighthouse/Program.NetCore.cs b/src/Lighthouse/Program.NetCore.cs index 0c5d04e..a7f6f36 100644 --- a/src/Lighthouse/Program.NetCore.cs +++ b/src/Lighthouse/Program.NetCore.cs @@ -1,21 +1,26 @@ using System; +using System.Diagnostics; namespace Lighthouse { - public partial class Program + public class Program { -#if NETCOREAPP1_1 public static void Main(string[] args) { var lighthouseService = new LighthouseService(); lighthouseService.Start(); Console.WriteLine("Press Control + C to terminate."); + + AppDomain.CurrentDomain.ProcessExit += async (sender, eventArgs) => + { + await lighthouseService.StopAsync(); + }; + Console.CancelKeyPress += async (sender, eventArgs) => { await lighthouseService.StopAsync(); }; lighthouseService.TerminationHandle.Wait(); } -#endif } } diff --git a/src/Lighthouse/Program.NetFramework.cs b/src/Lighthouse/Program.NetFramework.cs deleted file mode 100644 index be8b7ea..0000000 --- a/src/Lighthouse/Program.NetFramework.cs +++ /dev/null @@ -1,36 +0,0 @@ -#if NET452 -using Topshelf; -#endif - -namespace Lighthouse -{ - public partial class Program - { -#if NET452 - public static void Main(string[] args) - { - HostFactory.Run(x => - { - x.SetServiceName("Lighthouse"); - x.SetDisplayName("Lighthouse"); - x.SetDescription("Seed node for the Akka Cluster"); - - x.UseAssemblyInfoForServiceInfo(); - x.RunAsLocalSystem(); - x.StartAutomatically(); - - x.Service(sc => - { - sc.ConstructUsing(() => new LighthouseService()); - - // the start and stop methods for the service - sc.WhenStarted(s => s.Start()); - sc.WhenStopped(s => s.StopAsync().Wait()); - }); - - x.EnableServiceRecovery(r => r.RestartService(1)); - }); - } -#endif - } -} diff --git a/src/Lighthouse/akka.hocon b/src/Lighthouse/akka.hocon index 68eb4a3..4ba6511 100644 --- a/src/Lighthouse/akka.hocon +++ b/src/Lighthouse/akka.hocon @@ -13,6 +13,7 @@ petabridge.cmd{ } akka { + coordinated-shutdown.exit-clr = on actor { provider = cluster } diff --git a/src/Lighthouse/get-dockerip.sh b/src/Lighthouse/get-dockerip.sh deleted file mode 100644 index 2da6bc0..0000000 --- a/src/Lighthouse/get-dockerip.sh +++ /dev/null @@ -1,11 +0,0 @@ -#!/bin/sh - -if [ -z "$CLUSTER_IP" ]; then - host=$(hostname -i) - echo "Docker container bound on $host" - export CLUSTER_IP="$host" -else - echo "Docker container bound on $CLUSTER_IP" -fi - -exec "$@" \ No newline at end of file diff --git a/src/WebCrawler.CrawlService/CrawlerService.cs b/src/WebCrawler.CrawlService/CrawlerService.cs index 7c50c38..1fac33a 100644 --- a/src/WebCrawler.CrawlService/CrawlerService.cs +++ b/src/WebCrawler.CrawlService/CrawlerService.cs @@ -5,6 +5,7 @@ using Akka.Actor; using Akka.Bootstrap.Docker; using WebCrawler.Shared.Config; +using WebCrawler.Shared.DevOps; namespace WebCrawler.CrawlService { @@ -18,13 +19,13 @@ public class CrawlerService public bool Start() { var config = HoconLoader.ParseConfig("crawler.hocon"); - ClusterSystem = ActorSystem.Create("webcrawler", config.BootstrapFromDocker()); + ClusterSystem = ActorSystem.Create("webcrawler", config.ApplyOpsConfig()).StartPbm(); return true; } - public Task Stop() + public async Task Stop() { - return CoordinatedShutdown.Get(ClusterSystem).Run(CoordinatedShutdown.ClrExitReason.Instance); + await CoordinatedShutdown.Get(ClusterSystem).Run(CoordinatedShutdown.ClrExitReason.Instance); } } } diff --git a/src/WebCrawler.CrawlService/Dockerfile b/src/WebCrawler.CrawlService/Dockerfile index 0008005..9fa50a7 100644 --- a/src/WebCrawler.CrawlService/Dockerfile +++ b/src/WebCrawler.CrawlService/Dockerfile @@ -1,4 +1,4 @@ -FROM microsoft/dotnet:2.0-runtime AS base +FROM microsoft/dotnet:2.1-sdk AS base WORKDIR /app # should be a comma-delimited list @@ -9,26 +9,14 @@ ENV CLUSTER_PORT "5213" #Akka.Remote inbound listening endpoint EXPOSE 5213 -FROM microsoft/dotnet:2.0-sdk AS build -WORKDIR /src -COPY *.sln ./ -COPY ./get-dockerip.sh ./get-dockerip.sh -COPY src/WebCrawler.CrawlService/WebCrawler.CrawlService.csproj src/WebCrawler.CrawlService/ -COPY src/WebCrawler.Shared/WebCrawler.Shared.csproj src/WebCrawler.Shared/ -COPY src/WebCrawler.Shared.IO/WebCrawler.Shared.IO.csproj src/WebCrawler.Shared.IO/ -RUN dotnet restore -COPY . . -WORKDIR /src/src/WebCrawler.CrawlService -RUN dotnet build -c Release -o /app +COPY ./bin/Release/netcoreapp2.1/publish/ /app -FROM build AS publish -RUN dotnet publish -c Release -o /app +# Install Petabridge.Cmd client +RUN dotnet tool install --global pbm -FROM base AS final -WORKDIR /app -COPY --from=build /src/get-dockerip.sh ./get-dockerip.sh -COPY --from=publish /app . +# Needed because https://stackoverflow.com/questions/51977474/install-dotnet-core-tool-dockerfile +ENV PATH="${PATH}:/root/.dotnet/tools" -ENTRYPOINT ["/bin/bash","get-dockerip.sh"] +# RUN pbm help CMD ["dotnet", "WebCrawler.CrawlService.dll"] diff --git a/src/WebCrawler.CrawlService/Program.cs b/src/WebCrawler.CrawlService/Program.cs index a8ea3f1..6b9c73f 100644 --- a/src/WebCrawler.CrawlService/Program.cs +++ b/src/WebCrawler.CrawlService/Program.cs @@ -9,9 +9,14 @@ static void Main(string[] args) var crawlerService = new CrawlerService(); crawlerService.Start(); - Console.CancelKeyPress += (sender, eventArgs) => + AppDomain.CurrentDomain.ProcessExit += (sender, eventArgs) => { - crawlerService.Stop(); + crawlerService.Stop().Wait(TimeSpan.FromSeconds(30)); + }; + + Console.CancelKeyPress += async (sender, eventArgs) => + { + await crawlerService.Stop(); eventArgs.Cancel = true; }; diff --git a/src/WebCrawler.CrawlService/WebCrawler.CrawlService.csproj b/src/WebCrawler.CrawlService/WebCrawler.CrawlService.csproj index da5231a..262781d 100644 --- a/src/WebCrawler.CrawlService/WebCrawler.CrawlService.csproj +++ b/src/WebCrawler.CrawlService/WebCrawler.CrawlService.csproj @@ -1,14 +1,10 @@ - - + + Exe - netcoreapp2.0 + $(NetCoreVersion) - - - - Always @@ -16,11 +12,14 @@ - - + + + + + diff --git a/src/WebCrawler.Shared.DevOps.Tests/ActorSystemStartupSpecs.cs b/src/WebCrawler.Shared.DevOps.Tests/ActorSystemStartupSpecs.cs new file mode 100644 index 0000000..6b6f444 --- /dev/null +++ b/src/WebCrawler.Shared.DevOps.Tests/ActorSystemStartupSpecs.cs @@ -0,0 +1,49 @@ +using System; +using System.Collections.Generic; +using System.Text; +using Akka.Actor; +using Akka.Cluster.HealthCheck; +using Akka.HealthCheck; +using Akka.HealthCheck.Liveness; +using Akka.HealthCheck.Readiness; +using Akka.TestKit.Xunit2; +using FluentAssertions; +using Xunit; +using Xunit.Abstractions; + +namespace WebCrawler.Shared.DevOps.Tests +{ + public class ActorSystemStartupSpecs : TestKit + { + public ActorSystemStartupSpecs(ITestOutputHelper helper) + : base(Akka.Configuration.Config.Empty.ApplyOpsConfig(), output: helper) { } + + [Fact(DisplayName = "Instrumented ActorSystem should start HealthChecks automatically")] + public void ActorSystem_should_start_HealthChecks_automatically() + { + /* + * Without explicitly invoking the AkkaHealthCheck extension, we should see + * that the actors responsible for publishing that information have already + * started and begun broadcasting readiness / liveness status in the background + * since we enable the extension via the `akka.extensions` HOCON + */ + + // Liveness + AwaitAssert(() => + { + Sys.ActorSelection("/system/healthcheck-live").Tell(GetCurrentLiveness.Instance); + ExpectMsg(TimeSpan.FromMilliseconds(30)); + }, TimeSpan.FromSeconds(3), TimeSpan.FromMilliseconds(40)); + + // Readiness + AwaitAssert(() => + { + Sys.ActorSelection("/system/healthcheck-readiness").Tell(GetCurrentReadiness.Instance); + ExpectMsg(TimeSpan.FromMilliseconds(30)); + }, TimeSpan.FromSeconds(3), TimeSpan.FromMilliseconds(40)); + + // should be running with the Akka.Cluster healthcheck probe + //AkkaHealthCheck.For(Sys).ReadinessProvider.Should().BeOfType(); + } + } +} diff --git a/src/WebCrawler.Shared.DevOps.Tests/Config/OpsConfigSpec.cs b/src/WebCrawler.Shared.DevOps.Tests/Config/OpsConfigSpec.cs new file mode 100644 index 0000000..31899e0 --- /dev/null +++ b/src/WebCrawler.Shared.DevOps.Tests/Config/OpsConfigSpec.cs @@ -0,0 +1,16 @@ +using FluentAssertions; +using WebCrawler.Shared.DevOps.Config; +using Xunit; + +namespace WebCrawler.Shared.DevOps.Tests.Config +{ + public class OpsConfigSpec + { + [Fact] + public void Should_load_default_OpsConfig() + { + var config = OpsConfig.GetOpsConfig(); + config.Should().NotBeNull(); + } + } +} diff --git a/src/WebCrawler.Shared.DevOps.Tests/WebCrawler.Shared.DevOps.Tests.csproj b/src/WebCrawler.Shared.DevOps.Tests/WebCrawler.Shared.DevOps.Tests.csproj new file mode 100644 index 0000000..90b451c --- /dev/null +++ b/src/WebCrawler.Shared.DevOps.Tests/WebCrawler.Shared.DevOps.Tests.csproj @@ -0,0 +1,20 @@ + + + + $(NetCoreVersion) + false + + + + + + + + + + + + + + + diff --git a/src/WebCrawler.Shared.DevOps/Config/OpsConfig.cs b/src/WebCrawler.Shared.DevOps/Config/OpsConfig.cs new file mode 100644 index 0000000..a772246 --- /dev/null +++ b/src/WebCrawler.Shared.DevOps/Config/OpsConfig.cs @@ -0,0 +1,50 @@ +using System; +using System.Collections.Generic; +using System.Text; +using Akka.Configuration; + +namespace WebCrawler.Shared.DevOps.Config +{ + /// + /// Holder for shared configuration data used by all WebCrawler services + /// + public class OpsConfig + { + /// + /// Name of the variable used to look for Phobos + /// + public const string PHOBOS_ENABLED = "PHOBOS_ENABLED"; + + /// + /// Name of the variable used to direct Phobos' StatsD + /// output. + /// + public const string STATSD_URL = "STATSD_URL"; + + /// + /// Name of the variable used to direct Phobos' StatsD + /// output. + /// + public const string STATSD_PORT = "STATSD_PORT"; + + public static Akka.Configuration.Config GetOpsConfig() + { + return ConfigurationFactory.FromResource("WebCrawler.Shared.DevOps.Config.crawler.DevOps.conf"); + } + + public static Akka.Configuration.Config GetPhobosConfig() + { + + var rawPhobosConfig = ConfigurationFactory.FromResource("WebCrawler.Shared.DevOps.Config.crawler.Phobos.conf"); + var statsdUrl = Environment.GetEnvironmentVariable(STATSD_URL); + var statsDPort = Environment.GetEnvironmentVariable(STATSD_PORT); + if (!string.IsNullOrEmpty(statsdUrl) && int.TryParse(statsDPort, out var portNum)) + { + return ConfigurationFactory.ParseString($"phobos.monitoring.statsd.endpoint=\"{statsdUrl}\"" + Environment.NewLine + + $"phobos.monitoring.statsd.port={portNum}").WithFallback(rawPhobosConfig); + } + + return rawPhobosConfig; + } + } +} diff --git a/src/WebCrawler.Shared.DevOps/Config/crawler.DevOps.conf b/src/WebCrawler.Shared.DevOps/Config/crawler.DevOps.conf new file mode 100644 index 0000000..ed0421a --- /dev/null +++ b/src/WebCrawler.Shared.DevOps/Config/crawler.DevOps.conf @@ -0,0 +1,42 @@ +############################################ +# WebCrawler Shared DevOps Config File # +############################################ + +# Used to help ensure that the Cluster uses a standardized set of tools for monitoring, +# healthchecks, lifecycles, and more. + +# See petabridge.cmd configuration options here: https://cmd.petabridge.com/articles/install/host-configuration.html +petabridge.cmd{ + # default IP address used to listen for incoming petabridge.cmd client connections + # should be a safe default as it listens on "all network interfaces". + host = "0.0.0.0" + + # default port number used to listen for incoming petabridge.cmd client connections + port = 9110 +} + +# Akka.Cluster split-brain resolver configurations +akka.cluster{ + downing-provider-class = "Akka.Cluster.SplitBrainResolver, Akka.Cluster" + split-brain-resolver { + active-strategy = keep-majority + } +} + +# Akka.NET healthchecks +akka{ + extensions = ["Akka.HealthCheck.AkkaHealthCheckExt, Akka.HealthCheck"] +} + +akka.healthcheck{ + # Not explicitly setting the liveness provider. The Akka.Remote port + # is usually an effective-enough tool for this. + + readiness{ + # Use the cluster readiness provider + # BUG: cluster readiness provider not sending back expected replies + #provider = "Akka.Cluster.HealthCheck.ClusterReadinessProbeProvider, Akka.Cluster.HealthCheck" + transport = tcp # use a second socket for TCP readiness checks from K8s + tcp.port = 11001 + } +} \ No newline at end of file diff --git a/src/WebCrawler.Shared.DevOps/Config/crawler.Phobos.conf b/src/WebCrawler.Shared.DevOps/Config/crawler.Phobos.conf new file mode 100644 index 0000000..89dff03 --- /dev/null +++ b/src/WebCrawler.Shared.DevOps/Config/crawler.Phobos.conf @@ -0,0 +1,24 @@ +############################################ +# WebCrawler Phobos Config File # +############################################ + +# Used only instances where PHOBOS_ENABLED is set to TRUE +akka.actor.provider = "Phobos.Actor.Cluster.PhobosClusterActorRefProvider,Phobos.Actor.Cluster" + +phobos{ + monitoring{ + provider-type = statsd + monitor-mailbox-depth = on + statsd{ + endpoint = 127.0.0.1 + } + } + + tracing{ + provider-type = jaeger + jaeger{ + # Reporting via a locally deployed sidecar Jaeger agent + port = 6831 + } + } +} diff --git a/src/WebCrawler.Shared.DevOps/CrawlerBootstrapper.cs b/src/WebCrawler.Shared.DevOps/CrawlerBootstrapper.cs new file mode 100644 index 0000000..71f8d59 --- /dev/null +++ b/src/WebCrawler.Shared.DevOps/CrawlerBootstrapper.cs @@ -0,0 +1,46 @@ +using System; +using Akka.Actor; +using Akka.Bootstrap.Docker; +using Petabridge.Cmd.Cluster; +using Petabridge.Cmd.Host; +using WebCrawler.Shared.DevOps.Config; + +namespace WebCrawler.Shared.DevOps +{ + /// + /// Used to help inject and standardize all of the different components + /// needed to run all of the crawler services in production. + /// + public static class CrawlerBootstrapper + { + public static Akka.Configuration.Config ApplyOpsConfig(this Akka.Configuration.Config previousConfig) + { + var nextConfig = previousConfig.BootstrapFromDocker(); + return OpsConfig.GetOpsConfig().ApplyPhobosConfig().WithFallback(nextConfig); + } + + public static Akka.Configuration.Config ApplyPhobosConfig(this Akka.Configuration.Config previousConfig) + { + var enabledPhobosStr = Environment.GetEnvironmentVariable(OpsConfig.PHOBOS_ENABLED)?.Trim().ToLowerInvariant() ?? "false"; + if (bool.TryParse(enabledPhobosStr, out var enabledPhobos) && enabledPhobos) + { + return OpsConfig.GetPhobosConfig().WithFallback(previousConfig); + } + + return previousConfig; + } + + /// + /// Start Petabridge.Cmd + /// + /// The that will run Petabridge.Cmd + /// The same + public static ActorSystem StartPbm(this ActorSystem system) + { + var pbm = PetabridgeCmd.Get(system); + pbm.RegisterCommandPalette(ClusterCommands.Instance); // enable cluster management commands + pbm.Start(); + return system; + } + } +} diff --git a/src/WebCrawler.Shared.DevOps/WebCrawler.Shared.DevOps.csproj b/src/WebCrawler.Shared.DevOps/WebCrawler.Shared.DevOps.csproj new file mode 100644 index 0000000..141f4ae --- /dev/null +++ b/src/WebCrawler.Shared.DevOps/WebCrawler.Shared.DevOps.csproj @@ -0,0 +1,22 @@ + + + + netstandard2.0 + Common DevOps configuration and instrumentation for WebCrawler. + + + + + + + + + + + + + + + + + diff --git a/src/WebCrawler.Shared.IO/WebCrawler.Shared.IO.csproj b/src/WebCrawler.Shared.IO/WebCrawler.Shared.IO.csproj index 6fac465..3f0f213 100644 --- a/src/WebCrawler.Shared.IO/WebCrawler.Shared.IO.csproj +++ b/src/WebCrawler.Shared.IO/WebCrawler.Shared.IO.csproj @@ -1,11 +1,11 @@ - - + + netstandard2.0 - + diff --git a/src/WebCrawler.Shared/WebCrawler.Shared.csproj b/src/WebCrawler.Shared/WebCrawler.Shared.csproj index 8df4f47..57aee4e 100644 --- a/src/WebCrawler.Shared/WebCrawler.Shared.csproj +++ b/src/WebCrawler.Shared/WebCrawler.Shared.csproj @@ -1,11 +1,11 @@ - - + + netstandard2.0 - + diff --git a/src/WebCrawler.TrackerService/Actors/IO/CrawlMaster.cs b/src/WebCrawler.TrackerService/Actors/IO/CrawlMaster.cs index 1c58838..e4de58f 100644 --- a/src/WebCrawler.TrackerService/Actors/IO/CrawlMaster.cs +++ b/src/WebCrawler.TrackerService/Actors/IO/CrawlMaster.cs @@ -213,7 +213,6 @@ private void PublishJobStatus() { foreach (var sub in Subscribers) sub.Tell(RunningStatus); - Context.System.EventStream.Publish(1.0d); } } } diff --git a/src/WebCrawler.TrackerService/Dockerfile b/src/WebCrawler.TrackerService/Dockerfile index d73ac68..58530a5 100644 --- a/src/WebCrawler.TrackerService/Dockerfile +++ b/src/WebCrawler.TrackerService/Dockerfile @@ -1,4 +1,4 @@ -FROM microsoft/dotnet:2.0-runtime AS base +FROM microsoft/dotnet:2.1-sdk AS base WORKDIR /app # should be a comma-delimited list @@ -9,26 +9,14 @@ ENV CLUSTER_PORT "5212" #Akka.Remote inbound listening endpoint EXPOSE 5212 -FROM microsoft/dotnet:2.0-sdk AS build -WORKDIR /src -COPY *.sln ./ -COPY ./get-dockerip.sh ./get-dockerip.sh -COPY src/WebCrawler.TrackerService/WebCrawler.TrackerService.csproj src/WebCrawler.TrackerService/ -COPY src/WebCrawler.Shared/WebCrawler.Shared.csproj src/WebCrawler.Shared/ -COPY src/WebCrawler.Shared.IO/WebCrawler.Shared.IO.csproj src/WebCrawler.Shared.IO/ -RUN dotnet restore -COPY . . -WORKDIR /src/src/WebCrawler.TrackerService -RUN dotnet build -c Release -o /app +COPY ./bin/Release/netcoreapp2.1/publish/ /app -FROM build AS publish -RUN dotnet publish -c Release -o /app +# Install Petabridge.Cmd client +RUN dotnet tool install --global pbm -FROM base AS final -WORKDIR /app -COPY --from=build /src/get-dockerip.sh ./get-dockerip.sh -COPY --from=publish /app . +# Needed because https://stackoverflow.com/questions/51977474/install-dotnet-core-tool-dockerfile +ENV PATH="${PATH}:/root/.dotnet/tools" -ENTRYPOINT ["/bin/bash","get-dockerip.sh"] +# RUN pbm help CMD ["dotnet", "WebCrawler.TrackerService.dll"] diff --git a/src/WebCrawler.TrackerService/Program.cs b/src/WebCrawler.TrackerService/Program.cs index 92a2c97..da27fc1 100644 --- a/src/WebCrawler.TrackerService/Program.cs +++ b/src/WebCrawler.TrackerService/Program.cs @@ -15,9 +15,14 @@ private static void Main(string[] args) var trackingService = new TrackerService(); trackingService.Start(); - Console.CancelKeyPress += (sender, eventArgs) => + AppDomain.CurrentDomain.ProcessExit += (sender, eventArgs) => { - trackingService.Stop(); + trackingService.Stop().Wait(TimeSpan.FromSeconds(30)); + }; + + Console.CancelKeyPress += async (sender, eventArgs) => + { + await trackingService.Stop(); eventArgs.Cancel = true; }; diff --git a/src/WebCrawler.TrackerService/TrackerService.cs b/src/WebCrawler.TrackerService/TrackerService.cs index 491042b..0e0bd7c 100644 --- a/src/WebCrawler.TrackerService/TrackerService.cs +++ b/src/WebCrawler.TrackerService/TrackerService.cs @@ -10,6 +10,7 @@ using WebCrawler.Shared.Config; using WebCrawler.TrackerService.Actors; using WebCrawler.TrackerService.Actors.Tracking; +using WebCrawler.Shared.DevOps; namespace WebCrawler.TrackerService { @@ -25,15 +26,15 @@ public class TrackerService public bool Start() { var config = HoconLoader.ParseConfig("tracker.hocon"); - ClusterSystem = ActorSystem.Create("webcrawler", config.BootstrapFromDocker()); + ClusterSystem = ActorSystem.Create("webcrawler", config.ApplyOpsConfig()).StartPbm(); ApiMaster = ClusterSystem.ActorOf(Props.Create(() => new ApiMaster()), "api"); DownloadMaster = ClusterSystem.ActorOf(Props.Create(() => new DownloadsMaster()), "downloads"); return true; } - public Task Stop() + public async Task Stop() { - return CoordinatedShutdown.Get(ClusterSystem).Run(); + await CoordinatedShutdown.Get(ClusterSystem).Run(CoordinatedShutdown.ClrExitReason.Instance); } } } \ No newline at end of file diff --git a/src/WebCrawler.TrackerService/WebCrawler.TrackerService.csproj b/src/WebCrawler.TrackerService/WebCrawler.TrackerService.csproj index 0747c0f..2352da3 100644 --- a/src/WebCrawler.TrackerService/WebCrawler.TrackerService.csproj +++ b/src/WebCrawler.TrackerService/WebCrawler.TrackerService.csproj @@ -1,14 +1,10 @@ - - + + Exe - netcoreapp2.0 + $(NetCoreVersion) - - - - Always @@ -16,11 +12,13 @@ - - + + + + diff --git a/src/WebCrawler.Web/AkkaStartupTasks.cs b/src/WebCrawler.Web/AkkaStartupTasks.cs index aa366db..003803a 100644 --- a/src/WebCrawler.Web/AkkaStartupTasks.cs +++ b/src/WebCrawler.Web/AkkaStartupTasks.cs @@ -2,6 +2,7 @@ using Akka.Bootstrap.Docker; using Akka.Routing; using WebCrawler.Shared.Config; +using WebCrawler.Shared.DevOps; using WebCrawler.Web.Actors; namespace WebCrawler.Web @@ -11,7 +12,7 @@ public static class AkkaStartupTasks public static ActorSystem StartAkka() { var config = HoconLoader.ParseConfig("web.hocon"); - SystemActors.ActorSystem = ActorSystem.Create("webcrawler", config.BootstrapFromDocker()); + SystemActors.ActorSystem = ActorSystem.Create("webcrawler", config.ApplyOpsConfig()).StartPbm(); var router = SystemActors.ActorSystem.ActorOf(Props.Empty.WithRouter(FromConfig.Instance), "tasker"); var processor = SystemActors.CommandProcessor = SystemActors.ActorSystem.ActorOf(Props.Create(() => new CommandProcessor(router)), "commands"); diff --git a/src/WebCrawler.Web/Dockerfile b/src/WebCrawler.Web/Dockerfile index 172b63c..7767618 100644 --- a/src/WebCrawler.Web/Dockerfile +++ b/src/WebCrawler.Web/Dockerfile @@ -1,4 +1,4 @@ -FROM microsoft/aspnetcore:2.0 AS base +FROM microsoft/dotnet:2.1-sdk AS base WORKDIR /app # should be a comma-delimited list @@ -6,31 +6,18 @@ ENV CLUSTER_SEEDS "[]" ENV CLUSTER_IP "" ENV CLUSTER_PORT "16666" -EXPOSE 80 - #Akka.Remote inbound listening endpoint +EXPOSE 80 EXPOSE 16666 +# Install Petabridge.Cmd client +RUN dotnet tool install --global pbm -FROM microsoft/aspnetcore-build:2.0 AS build -WORKDIR /src -COPY *.sln ./ -COPY ./get-dockerip.sh ./get-dockerip.sh -COPY src/WebCrawler.Web/WebCrawler.Web.csproj src/WebCrawler.Web/ -COPY src/WebCrawler.Shared/WebCrawler.Shared.csproj src/WebCrawler.Shared/ -RUN dotnet restore -COPY . . -WORKDIR /src/src/WebCrawler.Web -RUN dotnet build -c Release -o /app +# Needed because https://stackoverflow.com/questions/51977474/install-dotnet-core-tool-dockerfile +ENV PATH="${PATH}:/root/.dotnet/tools" -FROM build AS publish -RUN dotnet publish -c Release -o /app - -FROM base AS final -WORKDIR /app -COPY --from=build /src/get-dockerip.sh ./get-dockerip.sh -COPY --from=publish /app . +# RUN pbm help -ENTRYPOINT ["/bin/bash","get-dockerip.sh"] +COPY ./bin/Release/netcoreapp2.1/publish/ /app CMD ["dotnet", "WebCrawler.Web.dll"] diff --git a/src/WebCrawler.Web/Program.cs b/src/WebCrawler.Web/Program.cs index 8992a9d..ffb4818 100644 --- a/src/WebCrawler.Web/Program.cs +++ b/src/WebCrawler.Web/Program.cs @@ -20,7 +20,7 @@ public static void Main(string[] args) Console.CancelKeyPress += async (sender, eventArgs) => { - var wait = CoordinatedShutdown.Get(SystemActors.ActorSystem).Run(); + var wait = CoordinatedShutdown.Get(SystemActors.ActorSystem).Run(CoordinatedShutdown.ClrExitReason.Instance); await host.StopAsync(TimeSpan.FromSeconds(10)); await wait; }; diff --git a/src/WebCrawler.Web/Views/Home/Index.cshtml b/src/WebCrawler.Web/Views/Home/Index.cshtml index 5fdd7ea..30c1779 100644 --- a/src/WebCrawler.Web/Views/Home/Index.cshtml +++ b/src/WebCrawler.Web/Views/Home/Index.cshtml @@ -47,7 +47,7 @@ $(function() { // Reference the auto-generated proxy for the hub. - var chat = new signalR.HubConnection("/hubs/crawlHub"); + var chat = new signalR.HubConnectionBuilder().withUrl("/hubs/crawlHub").build(); // Create a function that the hub can call back to display messages. chat.on("writeStatus", function(message) { stream.addMessage(message); diff --git a/src/WebCrawler.Web/WebCrawler.Web.csproj b/src/WebCrawler.Web/WebCrawler.Web.csproj index 879c080..5d03c34 100644 --- a/src/WebCrawler.Web/WebCrawler.Web.csproj +++ b/src/WebCrawler.Web/WebCrawler.Web.csproj @@ -1,26 +1,23 @@ - + + - netcoreapp2.0 + $(NetCoreVersion) ..\..\docker-compose.dcproj - - - Always - - - - - - - + + + + + + diff --git a/src/WebCrawler.Web/package-lock.json b/src/WebCrawler.Web/package-lock.json deleted file mode 100644 index ba627e6..0000000 --- a/src/WebCrawler.Web/package-lock.json +++ /dev/null @@ -1,11 +0,0 @@ -{ - "requires": true, - "lockfileVersion": 1, - "dependencies": { - "@aspnet/signalr": { - "version": "1.0.0-preview1-update1", - "resolved": "https://registry.npmjs.org/@aspnet/signalr/-/signalr-1.0.0-preview1-update1.tgz", - "integrity": "sha512-TGFCoLa2svN37Ew5ue0kGFxbkmQzq2I9N5TMLFBWRrpTYF4txlE3yPX0EaPt/NToKBaK1A+VK8Q+1MGSYtnqUw==" - } - } -} diff --git a/src/WebCrawler.Web/package.json b/src/WebCrawler.Web/package.json new file mode 100644 index 0000000..e2226f3 --- /dev/null +++ b/src/WebCrawler.Web/package.json @@ -0,0 +1,12 @@ +{ + "name": "WebCrawler.Web", + "version": "1.0.0", + "description": "", + "main": "index.js", + "scripts": { + "test": "echo \"Error: no test specified\" && exit 1" + }, + "keywords": [], + "author": "", + "license": "ISC" +} diff --git a/src/WebCrawler.Web/wwwroot/lib/signalr/signalr.js b/src/WebCrawler.Web/wwwroot/lib/signalr/signalr.js index 2347156..e53c2b0 100644 --- a/src/WebCrawler.Web/wwwroot/lib/signalr/signalr.js +++ b/src/WebCrawler.Web/wwwroot/lib/signalr/signalr.js @@ -1,29 +1,173 @@ -/* @license - * Copyright (c) .NET Foundation. All rights reserved. - * Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - */ -(function (global, factory) { - typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() : - typeof define === 'function' && define.amd ? define(factory) : - (global.signalR = factory()); -}(this, (function () { 'use strict'; - -var commonjsGlobal = typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {}; +(function webpackUniversalModuleDefinition(root, factory) { + if(typeof exports === 'object' && typeof module === 'object') + module.exports = factory(); + else if(typeof define === 'function' && define.amd) + define([], factory); + else if(typeof exports === 'object') + exports["signalR"] = factory(); + else + root["signalR"] = factory(); +})(window, function() { +return /******/ (function(modules) { // webpackBootstrap +/******/ // The module cache +/******/ var installedModules = {}; +/******/ +/******/ // The require function +/******/ function __webpack_require__(moduleId) { +/******/ +/******/ // Check if module is in cache +/******/ if(installedModules[moduleId]) { +/******/ return installedModules[moduleId].exports; +/******/ } +/******/ // Create a new module (and put it into the cache) +/******/ var module = installedModules[moduleId] = { +/******/ i: moduleId, +/******/ l: false, +/******/ exports: {} +/******/ }; +/******/ +/******/ // Execute the module function +/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); +/******/ +/******/ // Flag the module as loaded +/******/ module.l = true; +/******/ +/******/ // Return the exports of the module +/******/ return module.exports; +/******/ } +/******/ +/******/ +/******/ // expose the modules object (__webpack_modules__) +/******/ __webpack_require__.m = modules; +/******/ +/******/ // expose the module cache +/******/ __webpack_require__.c = installedModules; +/******/ +/******/ // define getter function for harmony exports +/******/ __webpack_require__.d = function(exports, name, getter) { +/******/ if(!__webpack_require__.o(exports, name)) { +/******/ Object.defineProperty(exports, name, { enumerable: true, get: getter }); +/******/ } +/******/ }; +/******/ +/******/ // define __esModule on exports +/******/ __webpack_require__.r = function(exports) { +/******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) { +/******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' }); +/******/ } +/******/ Object.defineProperty(exports, '__esModule', { value: true }); +/******/ }; +/******/ +/******/ // create a fake namespace object +/******/ // mode & 1: value is a module id, require it +/******/ // mode & 2: merge all properties of value into the ns +/******/ // mode & 4: return value when already ns object +/******/ // mode & 8|1: behave like require +/******/ __webpack_require__.t = function(value, mode) { +/******/ if(mode & 1) value = __webpack_require__(value); +/******/ if(mode & 8) return value; +/******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value; +/******/ var ns = Object.create(null); +/******/ __webpack_require__.r(ns); +/******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value }); +/******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key)); +/******/ return ns; +/******/ }; +/******/ +/******/ // getDefaultExport function for compatibility with non-harmony modules +/******/ __webpack_require__.n = function(module) { +/******/ var getter = module && module.__esModule ? +/******/ function getDefault() { return module['default']; } : +/******/ function getModuleExports() { return module; }; +/******/ __webpack_require__.d(getter, 'a', getter); +/******/ return getter; +/******/ }; +/******/ +/******/ // Object.prototype.hasOwnProperty.call +/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); }; +/******/ +/******/ // __webpack_public_path__ +/******/ __webpack_require__.p = ""; +/******/ +/******/ +/******/ // Load entry module and return exports +/******/ return __webpack_require__(__webpack_require__.s = 0); +/******/ }) +/************************************************************************/ +/******/ ([ +/* 0 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony import */ var es6_promise_dist_es6_promise_auto_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1); +/* harmony import */ var es6_promise_dist_es6_promise_auto_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(es6_promise_dist_es6_promise_auto_js__WEBPACK_IMPORTED_MODULE_0__); +/* harmony import */ var _index__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(3); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "VERSION", function() { return _index__WEBPACK_IMPORTED_MODULE_1__["VERSION"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "AbortError", function() { return _index__WEBPACK_IMPORTED_MODULE_1__["AbortError"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "HttpError", function() { return _index__WEBPACK_IMPORTED_MODULE_1__["HttpError"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "TimeoutError", function() { return _index__WEBPACK_IMPORTED_MODULE_1__["TimeoutError"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "HttpClient", function() { return _index__WEBPACK_IMPORTED_MODULE_1__["HttpClient"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "HttpResponse", function() { return _index__WEBPACK_IMPORTED_MODULE_1__["HttpResponse"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "DefaultHttpClient", function() { return _index__WEBPACK_IMPORTED_MODULE_1__["DefaultHttpClient"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "HubConnection", function() { return _index__WEBPACK_IMPORTED_MODULE_1__["HubConnection"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "HubConnectionState", function() { return _index__WEBPACK_IMPORTED_MODULE_1__["HubConnectionState"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "HubConnectionBuilder", function() { return _index__WEBPACK_IMPORTED_MODULE_1__["HubConnectionBuilder"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "MessageType", function() { return _index__WEBPACK_IMPORTED_MODULE_1__["MessageType"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "LogLevel", function() { return _index__WEBPACK_IMPORTED_MODULE_1__["LogLevel"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "HttpTransportType", function() { return _index__WEBPACK_IMPORTED_MODULE_1__["HttpTransportType"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "TransferFormat", function() { return _index__WEBPACK_IMPORTED_MODULE_1__["TransferFormat"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "NullLogger", function() { return _index__WEBPACK_IMPORTED_MODULE_1__["NullLogger"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "JsonHubProtocol", function() { return _index__WEBPACK_IMPORTED_MODULE_1__["JsonHubProtocol"]; }); + +// Copyright (c) .NET Foundation. All rights reserved. +// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. +// This is where we add any polyfills we'll need for the browser. It is the entry module for browser-specific builds. -function commonjsRequire () { - throw new Error('Dynamic requires are not currently supported by rollup-plugin-commonjs'); +// Copy from Array.prototype into Uint8Array to polyfill on IE. It's OK because the implementations of indexOf and slice use properties +// that exist on Uint8Array with the same name, and JavaScript is magic. +// We make them 'writable' because the Buffer polyfill messes with it as well. +if (!Uint8Array.prototype.indexOf) { + Object.defineProperty(Uint8Array.prototype, "indexOf", { + value: Array.prototype.indexOf, + writable: true, + }); } - -function unwrapExports (x) { - return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x; +if (!Uint8Array.prototype.slice) { + Object.defineProperty(Uint8Array.prototype, "slice", { + value: Array.prototype.slice, + writable: true, + }); } - -function createCommonjsModule(fn, module) { - return module = { exports: {} }, fn(module, module.exports), module.exports; +if (!Uint8Array.prototype.forEach) { + Object.defineProperty(Uint8Array.prototype, "forEach", { + value: Array.prototype.forEach, + writable: true, + }); } -var es6Promise_auto = createCommonjsModule(function (module, exports) { -/*! + + +/***/ }), +/* 1 */ +/***/ (function(module, exports, __webpack_require__) { + +/* WEBPACK VAR INJECTION */(function(global) {var require;/*! * @overview es6-promise - a tiny implementation of Promises/A+. * @copyright Copyright (c) 2014 Yehuda Katz, Tom Dale, Stefan Penner and contributors (Conversion to ES6 API by Jake Archibald) * @license Licensed under MIT license @@ -32,8 +176,11 @@ var es6Promise_auto = createCommonjsModule(function (module, exports) { */ (function (global, factory) { - module.exports = factory(); -}(commonjsGlobal, (function () { function objectOrFunction(x) { + true ? module.exports = factory() : + undefined; +}(this, (function () { 'use strict'; + +function objectOrFunction(x) { var type = typeof x; return x !== null && (type === 'object' || type === 'function'); } @@ -157,8 +304,8 @@ function flush() { function attemptVertx() { try { - var r = commonjsRequire; - var vertx = r('vertx'); + var r = require; + var vertx = __webpack_require__(!(function webpackMissingModule() { var e = new Error("Cannot find module 'vertx'"); e.code = 'MODULE_NOT_FOUND'; throw e; }())); vertxNext = vertx.runOnLoop || vertx.runOnContext; return useVertxTimer(); } catch (e) { @@ -174,7 +321,7 @@ if (isNode) { scheduleFlush = useMutationObserver(); } else if (isWorker) { scheduleFlush = useMessageChannel(); -} else if (browserWindow === undefined && typeof commonjsRequire === 'function') { +} else if (browserWindow === undefined && "function" === 'function') { scheduleFlush = attemptVertx(); } else { scheduleFlush = useSetTimeout(); @@ -1168,8 +1315,8 @@ Promise$2._asap = asap; function polyfill() { var local = void 0; - if (typeof commonjsGlobal !== 'undefined') { - local = commonjsGlobal; + if (typeof global !== 'undefined') { + local = global; } else if (typeof self !== 'undefined') { local = self; } else { @@ -1210,11 +1357,112 @@ return Promise$2; +//# sourceMappingURL=es6-promise.auto.map -}); +/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(2))) + +/***/ }), +/* 2 */ +/***/ (function(module, exports) { + +var g; + +// This works in non-strict mode +g = (function() { + return this; +})(); + +try { + // This works if eval is allowed (see CSP) + g = g || Function("return this")() || (1, eval)("this"); +} catch (e) { + // This works if the window reference is available + if (typeof window === "object") g = window; +} + +// g can still be undefined, but nothing to do about it... +// We return undefined, instead of nothing here, so it's +// easier to handle this case. if(!global) { ...} + +module.exports = g; + + +/***/ }), +/* 3 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "VERSION", function() { return VERSION; }); +/* harmony import */ var _Errors__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(4); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "AbortError", function() { return _Errors__WEBPACK_IMPORTED_MODULE_0__["AbortError"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "HttpError", function() { return _Errors__WEBPACK_IMPORTED_MODULE_0__["HttpError"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "TimeoutError", function() { return _Errors__WEBPACK_IMPORTED_MODULE_0__["TimeoutError"]; }); + +/* harmony import */ var _HttpClient__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(5); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "HttpClient", function() { return _HttpClient__WEBPACK_IMPORTED_MODULE_1__["HttpClient"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "HttpResponse", function() { return _HttpClient__WEBPACK_IMPORTED_MODULE_1__["HttpResponse"]; }); + +/* harmony import */ var _DefaultHttpClient__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(6); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "DefaultHttpClient", function() { return _DefaultHttpClient__WEBPACK_IMPORTED_MODULE_2__["DefaultHttpClient"]; }); -var Errors = createCommonjsModule(function (module, exports) { -var __extends = (commonjsGlobal && commonjsGlobal.__extends) || (function () { +/* harmony import */ var _HubConnection__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(9); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "HubConnection", function() { return _HubConnection__WEBPACK_IMPORTED_MODULE_3__["HubConnection"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "HubConnectionState", function() { return _HubConnection__WEBPACK_IMPORTED_MODULE_3__["HubConnectionState"]; }); + +/* harmony import */ var _HubConnectionBuilder__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(15); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "HubConnectionBuilder", function() { return _HubConnectionBuilder__WEBPACK_IMPORTED_MODULE_4__["HubConnectionBuilder"]; }); + +/* harmony import */ var _IHubProtocol__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(14); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "MessageType", function() { return _IHubProtocol__WEBPACK_IMPORTED_MODULE_5__["MessageType"]; }); + +/* harmony import */ var _ILogger__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(8); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "LogLevel", function() { return _ILogger__WEBPACK_IMPORTED_MODULE_6__["LogLevel"]; }); + +/* harmony import */ var _ITransport__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(17); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "HttpTransportType", function() { return _ITransport__WEBPACK_IMPORTED_MODULE_7__["HttpTransportType"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "TransferFormat", function() { return _ITransport__WEBPACK_IMPORTED_MODULE_7__["TransferFormat"]; }); + +/* harmony import */ var _Loggers__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(13); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "NullLogger", function() { return _Loggers__WEBPACK_IMPORTED_MODULE_8__["NullLogger"]; }); + +/* harmony import */ var _JsonHubProtocol__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(22); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "JsonHubProtocol", function() { return _JsonHubProtocol__WEBPACK_IMPORTED_MODULE_9__["JsonHubProtocol"]; }); + +// Copyright (c) .NET Foundation. All rights reserved. +// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. +// Version token that will be replaced by the prepack command +/** The version of the SignalR client. */ +var VERSION = "1.1.0"; + + + + + + + + + + + + +/***/ }), +/* 4 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "HttpError", function() { return HttpError; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TimeoutError", function() { return TimeoutError; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "AbortError", function() { return AbortError; }); +// Copyright (c) .NET Foundation. All rights reserved. +// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. +var __extends = (undefined && undefined.__extends) || (function () { var extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; @@ -1224,45 +1472,83 @@ var __extends = (commonjsGlobal && commonjsGlobal.__extends) || (function () { d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); -Object.defineProperty(exports, "__esModule", { value: true }); +/** Error thrown when an HTTP request fails. */ var HttpError = /** @class */ (function (_super) { __extends(HttpError, _super); + /** Constructs a new instance of {@link @aspnet/signalr.HttpError}. + * + * @param {string} errorMessage A descriptive error message. + * @param {number} statusCode The HTTP status code represented by this error. + */ function HttpError(errorMessage, statusCode) { - var _this = _super.call(this, errorMessage) || this; + var _newTarget = this.constructor; + var _this = this; + var trueProto = _newTarget.prototype; + _this = _super.call(this, errorMessage) || this; _this.statusCode = statusCode; + // Workaround issue in Typescript compiler + // https://github.com/Microsoft/TypeScript/issues/13965#issuecomment-278570200 + _this.__proto__ = trueProto; return _this; } return HttpError; }(Error)); -exports.HttpError = HttpError; + +/** Error thrown when a timeout elapses. */ var TimeoutError = /** @class */ (function (_super) { __extends(TimeoutError, _super); + /** Constructs a new instance of {@link @aspnet/signalr.TimeoutError}. + * + * @param {string} errorMessage A descriptive error message. + */ function TimeoutError(errorMessage) { + var _newTarget = this.constructor; if (errorMessage === void 0) { errorMessage = "A timeout occurred."; } - return _super.call(this, errorMessage) || this; + var _this = this; + var trueProto = _newTarget.prototype; + _this = _super.call(this, errorMessage) || this; + // Workaround issue in Typescript compiler + // https://github.com/Microsoft/TypeScript/issues/13965#issuecomment-278570200 + _this.__proto__ = trueProto; + return _this; } return TimeoutError; }(Error)); -exports.TimeoutError = TimeoutError; -}); +/** Error thrown when an action is aborted. */ +var AbortError = /** @class */ (function (_super) { + __extends(AbortError, _super); + /** Constructs a new instance of {@link AbortError}. + * + * @param {string} errorMessage A descriptive error message. + */ + function AbortError(errorMessage) { + var _newTarget = this.constructor; + if (errorMessage === void 0) { errorMessage = "An abort occurred."; } + var _this = this; + var trueProto = _newTarget.prototype; + _this = _super.call(this, errorMessage) || this; + // Workaround issue in Typescript compiler + // https://github.com/Microsoft/TypeScript/issues/13965#issuecomment-278570200 + _this.__proto__ = trueProto; + return _this; + } + return AbortError; +}(Error)); -unwrapExports(Errors); -var Errors_1 = Errors.HttpError; -var Errors_2 = Errors.TimeoutError; -var HttpClient_1 = createCommonjsModule(function (module, exports) { -var __extends = (commonjsGlobal && commonjsGlobal.__extends) || (function () { - var extendStatics = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; - return function (d, b) { - extendStatics(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - }; -})(); -var __assign = (commonjsGlobal && commonjsGlobal.__assign) || Object.assign || function(t) { + +/***/ }), +/* 5 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "HttpResponse", function() { return HttpResponse; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "HttpClient", function() { return HttpClient; }); +// Copyright (c) .NET Foundation. All rights reserved. +// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. +var __assign = (undefined && undefined.__assign) || Object.assign || function(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) @@ -1270,8 +1556,7 @@ var __assign = (commonjsGlobal && commonjsGlobal.__assign) || Object.assign || f } return t; }; -Object.defineProperty(exports, "__esModule", { value: true }); - +/** Represents an HTTP response. */ var HttpResponse = /** @class */ (function () { function HttpResponse(statusCode, statusText, content) { this.statusCode = statusCode; @@ -1280,7 +1565,11 @@ var HttpResponse = /** @class */ (function () { } return HttpResponse; }()); -exports.HttpResponse = HttpResponse; + +/** Abstraction over an HTTP client. + * + * This class provides an abstraction over an HTTP client so that a different implementation can be provided on different platforms. + */ var HttpClient = /** @class */ (function () { function HttpClient() { } @@ -1290,21 +1579,152 @@ var HttpClient = /** @class */ (function () { HttpClient.prototype.post = function (url, options) { return this.send(__assign({}, options, { method: "POST", url: url })); }; + HttpClient.prototype.delete = function (url, options) { + return this.send(__assign({}, options, { method: "DELETE", url: url })); + }; + /** Gets all cookies that apply to the specified URL. + * + * @param url The URL that the cookies are valid for. + * @returns {string} A string containing all the key-value cookie pairs for the specified URL. + */ + // @ts-ignore + HttpClient.prototype.getCookieString = function (url) { + return ""; + }; return HttpClient; }()); -exports.HttpClient = HttpClient; + + + +/***/ }), +/* 6 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DefaultHttpClient", function() { return DefaultHttpClient; }); +/* harmony import */ var _Errors__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(4); +/* harmony import */ var _HttpClient__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(5); +/* harmony import */ var _XhrHttpClient__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(7); +// Copyright (c) .NET Foundation. All rights reserved. +// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. +var __extends = (undefined && undefined.__extends) || (function () { + var extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); + + + +var nodeHttpClientModule; +if (typeof XMLHttpRequest === "undefined") { + // In order to ignore the dynamic require in webpack builds we need to do this magic + // @ts-ignore: TS doesn't know about these names + var requireFunc = true ? require : undefined; + nodeHttpClientModule = requireFunc("./NodeHttpClient"); +} +/** Default implementation of {@link @aspnet/signalr.HttpClient}. */ var DefaultHttpClient = /** @class */ (function (_super) { __extends(DefaultHttpClient, _super); - function DefaultHttpClient() { - return _super !== null && _super.apply(this, arguments) || this; + /** Creates a new instance of the {@link @aspnet/signalr.DefaultHttpClient}, using the provided {@link @aspnet/signalr.ILogger} to log messages. */ + function DefaultHttpClient(logger) { + var _this = _super.call(this) || this; + if (typeof XMLHttpRequest !== "undefined") { + _this.httpClient = new _XhrHttpClient__WEBPACK_IMPORTED_MODULE_2__["XhrHttpClient"](logger); + } + else if (typeof nodeHttpClientModule !== "undefined") { + _this.httpClient = new nodeHttpClientModule.NodeHttpClient(logger); + } + else { + throw new Error("No HttpClient could be created."); + } + return _this; } + /** @inheritDoc */ DefaultHttpClient.prototype.send = function (request) { + // Check that abort was not signaled before calling send + if (request.abortSignal && request.abortSignal.aborted) { + return Promise.reject(new _Errors__WEBPACK_IMPORTED_MODULE_0__["AbortError"]()); + } + if (!request.method) { + return Promise.reject(new Error("No method defined.")); + } + if (!request.url) { + return Promise.reject(new Error("No url defined.")); + } + return this.httpClient.send(request); + }; + DefaultHttpClient.prototype.getCookieString = function (url) { + return this.httpClient.getCookieString(url); + }; + return DefaultHttpClient; +}(_HttpClient__WEBPACK_IMPORTED_MODULE_1__["HttpClient"])); + + + +/***/ }), +/* 7 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "XhrHttpClient", function() { return XhrHttpClient; }); +/* harmony import */ var _Errors__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(4); +/* harmony import */ var _HttpClient__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(5); +/* harmony import */ var _ILogger__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(8); +// Copyright (c) .NET Foundation. All rights reserved. +// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. +var __extends = (undefined && undefined.__extends) || (function () { + var extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); + + + +var XhrHttpClient = /** @class */ (function (_super) { + __extends(XhrHttpClient, _super); + function XhrHttpClient(logger) { + var _this = _super.call(this) || this; + _this.logger = logger; + return _this; + } + /** @inheritDoc */ + XhrHttpClient.prototype.send = function (request) { + var _this = this; + // Check that abort was not signaled before calling send + if (request.abortSignal && request.abortSignal.aborted) { + return Promise.reject(new _Errors__WEBPACK_IMPORTED_MODULE_0__["AbortError"]()); + } + if (!request.method) { + return Promise.reject(new Error("No method defined.")); + } + if (!request.url) { + return Promise.reject(new Error("No url defined.")); + } return new Promise(function (resolve, reject) { var xhr = new XMLHttpRequest(); xhr.open(request.method, request.url, true); + xhr.withCredentials = true; xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest"); - if (request.headers) { - request.headers.forEach(function (value, header) { return xhr.setRequestHeader(header, value); }); + // Explicitly setting the Content-Type header for React Native on Android platform. + xhr.setRequestHeader("Content-Type", "text/plain;charset=UTF-8"); + var headers = request.headers; + if (headers) { + Object.keys(headers) + .forEach(function (header) { + xhr.setRequestHeader(header, headers[header]); + }); } if (request.responseType) { xhr.responseType = request.responseType; @@ -1312,6 +1732,7 @@ var DefaultHttpClient = /** @class */ (function (_super) { if (request.abortSignal) { request.abortSignal.onabort = function () { xhr.abort(); + reject(new _Errors__WEBPACK_IMPORTED_MODULE_0__["AbortError"]()); }; } if (request.timeout) { @@ -1322,90 +1743,76 @@ var DefaultHttpClient = /** @class */ (function (_super) { request.abortSignal.onabort = null; } if (xhr.status >= 200 && xhr.status < 300) { - resolve(new HttpResponse(xhr.status, xhr.statusText, xhr.response || xhr.responseText)); + resolve(new _HttpClient__WEBPACK_IMPORTED_MODULE_1__["HttpResponse"](xhr.status, xhr.statusText, xhr.response || xhr.responseText)); } else { - reject(new Errors.HttpError(xhr.statusText, xhr.status)); + reject(new _Errors__WEBPACK_IMPORTED_MODULE_0__["HttpError"](xhr.statusText, xhr.status)); } }; xhr.onerror = function () { - reject(new Errors.HttpError(xhr.statusText, xhr.status)); + _this.logger.log(_ILogger__WEBPACK_IMPORTED_MODULE_2__["LogLevel"].Warning, "Error from HTTP request. " + xhr.status + ": " + xhr.statusText + "."); + reject(new _Errors__WEBPACK_IMPORTED_MODULE_0__["HttpError"](xhr.statusText, xhr.status)); }; xhr.ontimeout = function () { - reject(new Errors.TimeoutError()); + _this.logger.log(_ILogger__WEBPACK_IMPORTED_MODULE_2__["LogLevel"].Warning, "Timeout from HTTP request."); + reject(new _Errors__WEBPACK_IMPORTED_MODULE_0__["TimeoutError"]()); }; xhr.send(request.content || ""); }); }; - return DefaultHttpClient; -}(HttpClient)); -exports.DefaultHttpClient = DefaultHttpClient; + return XhrHttpClient; +}(_HttpClient__WEBPACK_IMPORTED_MODULE_1__["HttpClient"])); + -}); -unwrapExports(HttpClient_1); -var HttpClient_2 = HttpClient_1.HttpResponse; -var HttpClient_3 = HttpClient_1.HttpClient; -var HttpClient_4 = HttpClient_1.DefaultHttpClient; +/***/ }), +/* 8 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { -var ILogger = createCommonjsModule(function (module, exports) { -Object.defineProperty(exports, "__esModule", { value: true }); +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "LogLevel", function() { return LogLevel; }); +// Copyright (c) .NET Foundation. All rights reserved. +// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. +// These values are designed to match the ASP.NET Log Levels since that's the pattern we're emulating here. +/** Indicates the severity of a log message. + * + * Log Levels are ordered in increasing severity. So `Debug` is more severe than `Trace`, etc. + */ var LogLevel; (function (LogLevel) { + /** Log level for very low severity diagnostic messages. */ LogLevel[LogLevel["Trace"] = 0] = "Trace"; - LogLevel[LogLevel["Information"] = 1] = "Information"; - LogLevel[LogLevel["Warning"] = 2] = "Warning"; - LogLevel[LogLevel["Error"] = 3] = "Error"; - LogLevel[LogLevel["None"] = 4] = "None"; -})(LogLevel = exports.LogLevel || (exports.LogLevel = {})); - -}); - -unwrapExports(ILogger); -var ILogger_1 = ILogger.LogLevel; - -var AbortController_1 = createCommonjsModule(function (module, exports) { -Object.defineProperty(exports, "__esModule", { value: true }); -// Rough polyfill of https://developer.mozilla.org/en-US/docs/Web/API/AbortController -// We don't actually ever use the API being polyfilled, we always use the polyfill because -// it's a very new API right now. -var AbortController = /** @class */ (function () { - function AbortController() { - this.isAborted = false; - } - AbortController.prototype.abort = function () { - if (!this.isAborted) { - this.isAborted = true; - if (this.onabort) { - this.onabort(); - } - } - }; - Object.defineProperty(AbortController.prototype, "signal", { - get: function () { - return this; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(AbortController.prototype, "aborted", { - get: function () { - return this.isAborted; - }, - enumerable: true, - configurable: true - }); - return AbortController; -}()); -exports.AbortController = AbortController; - -}); - -unwrapExports(AbortController_1); -var AbortController_2 = AbortController_1.AbortController; - -var Transports = createCommonjsModule(function (module, exports) { -var __awaiter = (commonjsGlobal && commonjsGlobal.__awaiter) || function (thisArg, _arguments, P, generator) { + /** Log level for low severity diagnostic messages. */ + LogLevel[LogLevel["Debug"] = 1] = "Debug"; + /** Log level for informational diagnostic messages. */ + LogLevel[LogLevel["Information"] = 2] = "Information"; + /** Log level for diagnostic messages that indicate a non-fatal problem. */ + LogLevel[LogLevel["Warning"] = 3] = "Warning"; + /** Log level for diagnostic messages that indicate a failure in the current operation. */ + LogLevel[LogLevel["Error"] = 4] = "Error"; + /** Log level for diagnostic messages that indicate a failure that will terminate the entire application. */ + LogLevel[LogLevel["Critical"] = 5] = "Critical"; + /** The highest possible log level. Used when configuring logging to indicate that no log messages should be emitted. */ + LogLevel[LogLevel["None"] = 6] = "None"; +})(LogLevel || (LogLevel = {})); + + +/***/ }), +/* 9 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "HubConnectionState", function() { return HubConnectionState; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "HubConnection", function() { return HubConnection; }); +/* harmony import */ var _HandshakeProtocol__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(10); +/* harmony import */ var _IHubProtocol__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(14); +/* harmony import */ var _ILogger__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(8); +/* harmony import */ var _Utils__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(12); +// Copyright (c) .NET Foundation. All rights reserved. +// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. +var __awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } @@ -1413,15 +1820,15 @@ var __awaiter = (commonjsGlobal && commonjsGlobal.__awaiter) || function (thisAr step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; -var __generator = (commonjsGlobal && commonjsGlobal.__generator) || function (thisArg, body) { +var __generator = (undefined && undefined.__generator) || function (thisArg, body) { var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; function verb(n) { return function (v) { return step([n, v]); }; } function step(op) { if (f) throw new TypeError("Generator is already executing."); while (_) try { - if (f = 1, y && (t = y[op[0] & 2 ? "return" : op[0] ? "throw" : "next"]) && !(t = t.call(y, op[1])).done) return t; - if (y = 0, t) op = [0, t.value]; + 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; + if (y = 0, t) op = [op[0] & 2, t.value]; switch (op[0]) { case 0: case 1: t = op; break; case 4: _.label++; return { value: op[1], done: false }; @@ -1440,239 +1847,1679 @@ var __generator = (commonjsGlobal && commonjsGlobal.__generator) || function (th if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } }; -Object.defineProperty(exports, "__esModule", { value: true }); -var TransportType; -(function (TransportType) { - TransportType[TransportType["WebSockets"] = 0] = "WebSockets"; - TransportType[TransportType["ServerSentEvents"] = 1] = "ServerSentEvents"; - TransportType[TransportType["LongPolling"] = 2] = "LongPolling"; -})(TransportType = exports.TransportType || (exports.TransportType = {})); -var WebSocketTransport = /** @class */ (function () { - function WebSocketTransport(accessTokenFactory, logger) { + +var DEFAULT_TIMEOUT_IN_MS = 30 * 1000; +var DEFAULT_PING_INTERVAL_IN_MS = 15 * 1000; +/** Describes the current state of the {@link HubConnection} to the server. */ +var HubConnectionState; +(function (HubConnectionState) { + /** The hub connection is disconnected. */ + HubConnectionState[HubConnectionState["Disconnected"] = 0] = "Disconnected"; + /** The hub connection is connected. */ + HubConnectionState[HubConnectionState["Connected"] = 1] = "Connected"; +})(HubConnectionState || (HubConnectionState = {})); +/** Represents a connection to a SignalR Hub. */ +var HubConnection = /** @class */ (function () { + function HubConnection(connection, logger, protocol) { + var _this = this; + _Utils__WEBPACK_IMPORTED_MODULE_3__["Arg"].isRequired(connection, "connection"); + _Utils__WEBPACK_IMPORTED_MODULE_3__["Arg"].isRequired(logger, "logger"); + _Utils__WEBPACK_IMPORTED_MODULE_3__["Arg"].isRequired(protocol, "protocol"); + this.serverTimeoutInMilliseconds = DEFAULT_TIMEOUT_IN_MS; + this.keepAliveIntervalInMilliseconds = DEFAULT_PING_INTERVAL_IN_MS; this.logger = logger; - this.accessTokenFactory = accessTokenFactory || (function () { return null; }); + this.protocol = protocol; + this.connection = connection; + this.handshakeProtocol = new _HandshakeProtocol__WEBPACK_IMPORTED_MODULE_0__["HandshakeProtocol"](); + this.connection.onreceive = function (data) { return _this.processIncomingData(data); }; + this.connection.onclose = function (error) { return _this.connectionClosed(error); }; + this.callbacks = {}; + this.methods = {}; + this.closedCallbacks = []; + this.id = 0; + this.receivedHandshakeResponse = false; + this.connectionState = HubConnectionState.Disconnected; + this.cachedPingMessage = this.protocol.writeMessage({ type: _IHubProtocol__WEBPACK_IMPORTED_MODULE_1__["MessageType"].Ping }); } - WebSocketTransport.prototype.connect = function (url, requestedTransferMode, connection) { + /** @internal */ + // Using a public static factory method means we can have a private constructor and an _internal_ + // create method that can be used by HubConnectionBuilder. An "internal" constructor would just + // be stripped away and the '.d.ts' file would have no constructor, which is interpreted as a + // public parameter-less constructor. + HubConnection.create = function (connection, logger, protocol) { + return new HubConnection(connection, logger, protocol); + }; + Object.defineProperty(HubConnection.prototype, "state", { + /** Indicates the state of the {@link HubConnection} to the server. */ + get: function () { + return this.connectionState; + }, + enumerable: true, + configurable: true + }); + /** Starts the connection. + * + * @returns {Promise} A Promise that resolves when the connection has been successfully established, or rejects with an error. + */ + HubConnection.prototype.start = function () { + return __awaiter(this, void 0, void 0, function () { + var handshakeRequest, handshakePromise; + var _this = this; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + handshakeRequest = { + protocol: this.protocol.name, + version: this.protocol.version, + }; + this.logger.log(_ILogger__WEBPACK_IMPORTED_MODULE_2__["LogLevel"].Debug, "Starting HubConnection."); + this.receivedHandshakeResponse = false; + handshakePromise = new Promise(function (resolve, reject) { + _this.handshakeResolver = resolve; + _this.handshakeRejecter = reject; + }); + return [4 /*yield*/, this.connection.start(this.protocol.transferFormat)]; + case 1: + _a.sent(); + this.logger.log(_ILogger__WEBPACK_IMPORTED_MODULE_2__["LogLevel"].Debug, "Sending handshake request."); + return [4 /*yield*/, this.sendMessage(this.handshakeProtocol.writeHandshakeRequest(handshakeRequest))]; + case 2: + _a.sent(); + this.logger.log(_ILogger__WEBPACK_IMPORTED_MODULE_2__["LogLevel"].Information, "Using HubProtocol '" + this.protocol.name + "'."); + // defensively cleanup timeout in case we receive a message from the server before we finish start + this.cleanupTimeout(); + this.resetTimeoutPeriod(); + this.resetKeepAliveInterval(); + // Wait for the handshake to complete before marking connection as connected + return [4 /*yield*/, handshakePromise]; + case 3: + // Wait for the handshake to complete before marking connection as connected + _a.sent(); + this.connectionState = HubConnectionState.Connected; + return [2 /*return*/]; + } + }); + }); + }; + /** Stops the connection. + * + * @returns {Promise} A Promise that resolves when the connection has been successfully terminated, or rejects with an error. + */ + HubConnection.prototype.stop = function () { + this.logger.log(_ILogger__WEBPACK_IMPORTED_MODULE_2__["LogLevel"].Debug, "Stopping HubConnection."); + this.cleanupTimeout(); + this.cleanupPingTimer(); + return this.connection.stop(); + }; + /** Invokes a streaming hub method on the server using the specified name and arguments. + * + * @typeparam T The type of the items returned by the server. + * @param {string} methodName The name of the server method to invoke. + * @param {any[]} args The arguments used to invoke the server method. + * @returns {IStreamResult} An object that yields results from the server as they are received. + */ + HubConnection.prototype.stream = function (methodName) { var _this = this; - return new Promise(function (resolve, reject) { - url = url.replace(/^http/, "ws"); - var token = _this.accessTokenFactory(); - if (token) { - url += (url.indexOf("?") < 0 ? "?" : "&") + ("access_token=" + encodeURIComponent(token)); - } - var webSocket = new WebSocket(url); - if (requestedTransferMode == 2 /* Binary */) { - webSocket.binaryType = "arraybuffer"; + var args = []; + for (var _i = 1; _i < arguments.length; _i++) { + args[_i - 1] = arguments[_i]; + } + var invocationDescriptor = this.createStreamInvocation(methodName, args); + var subject = new _Utils__WEBPACK_IMPORTED_MODULE_3__["Subject"](function () { + var cancelInvocation = _this.createCancelInvocation(invocationDescriptor.invocationId); + var cancelMessage = _this.protocol.writeMessage(cancelInvocation); + delete _this.callbacks[invocationDescriptor.invocationId]; + return _this.sendMessage(cancelMessage); + }); + this.callbacks[invocationDescriptor.invocationId] = function (invocationEvent, error) { + if (error) { + subject.error(error); + return; } - webSocket.onopen = function (event) { - _this.logger.log(ILogger.LogLevel.Information, "WebSocket connected to " + url); - _this.webSocket = webSocket; - resolve(requestedTransferMode); - }; - webSocket.onerror = function (event) { - reject(); - }; - webSocket.onmessage = function (message) { - _this.logger.log(ILogger.LogLevel.Trace, "(WebSockets transport) data received: " + message.data); - if (_this.onreceive) { - _this.onreceive(message.data); - } - }; - webSocket.onclose = function (event) { - // webSocket will be null if the transport did not start successfully - if (_this.onclose && _this.webSocket) { - if (event.wasClean === false || event.code !== 1000) { - _this.onclose(new Error("Websocket closed with status code: " + event.code + " (" + event.reason + ")")); + else if (invocationEvent) { + // invocationEvent will not be null when an error is not passed to the callback + if (invocationEvent.type === _IHubProtocol__WEBPACK_IMPORTED_MODULE_1__["MessageType"].Completion) { + if (invocationEvent.error) { + subject.error(new Error(invocationEvent.error)); } else { - _this.onclose(); + subject.complete(); } } - }; + else { + subject.next((invocationEvent.item)); + } + } + }; + var message = this.protocol.writeMessage(invocationDescriptor); + this.sendMessage(message) + .catch(function (e) { + subject.error(e); + delete _this.callbacks[invocationDescriptor.invocationId]; }); + return subject; }; - WebSocketTransport.prototype.send = function (data) { - if (this.webSocket && this.webSocket.readyState === WebSocket.OPEN) { - this.webSocket.send(data); - return Promise.resolve(); - } - return Promise.reject("WebSocket is not in the OPEN state"); + HubConnection.prototype.sendMessage = function (message) { + this.resetKeepAliveInterval(); + return this.connection.send(message); }; - WebSocketTransport.prototype.stop = function () { - if (this.webSocket) { - this.webSocket.close(); - this.webSocket = null; + /** Invokes a hub method on the server using the specified name and arguments. Does not wait for a response from the receiver. + * + * The Promise returned by this method resolves when the client has sent the invocation to the server. The server may still + * be processing the invocation. + * + * @param {string} methodName The name of the server method to invoke. + * @param {any[]} args The arguments used to invoke the server method. + * @returns {Promise} A Promise that resolves when the invocation has been successfully sent, or rejects with an error. + */ + HubConnection.prototype.send = function (methodName) { + var args = []; + for (var _i = 1; _i < arguments.length; _i++) { + args[_i - 1] = arguments[_i]; } - return Promise.resolve(); + var invocationDescriptor = this.createInvocation(methodName, args, true); + var message = this.protocol.writeMessage(invocationDescriptor); + return this.sendMessage(message); }; - return WebSocketTransport; -}()); -exports.WebSocketTransport = WebSocketTransport; -var ServerSentEventsTransport = /** @class */ (function () { - function ServerSentEventsTransport(httpClient, accessTokenFactory, logger) { - this.httpClient = httpClient; - this.accessTokenFactory = accessTokenFactory || (function () { return null; }); - this.logger = logger; - } - ServerSentEventsTransport.prototype.connect = function (url, requestedTransferMode, connection) { + /** Invokes a hub method on the server using the specified name and arguments. + * + * The Promise returned by this method resolves when the server indicates it has finished invoking the method. When the promise + * resolves, the server has finished invoking the method. If the server method returns a result, it is produced as the result of + * resolving the Promise. + * + * @typeparam T The expected return type. + * @param {string} methodName The name of the server method to invoke. + * @param {any[]} args The arguments used to invoke the server method. + * @returns {Promise} A Promise that resolves with the result of the server method (if any), or rejects with an error. + */ + HubConnection.prototype.invoke = function (methodName) { + var _this = this; + var args = []; + for (var _i = 1; _i < arguments.length; _i++) { + args[_i - 1] = arguments[_i]; + } + var invocationDescriptor = this.createInvocation(methodName, args, false); + var p = new Promise(function (resolve, reject) { + // invocationId will always have a value for a non-blocking invocation + _this.callbacks[invocationDescriptor.invocationId] = function (invocationEvent, error) { + if (error) { + reject(error); + return; + } + else if (invocationEvent) { + // invocationEvent will not be null when an error is not passed to the callback + if (invocationEvent.type === _IHubProtocol__WEBPACK_IMPORTED_MODULE_1__["MessageType"].Completion) { + if (invocationEvent.error) { + reject(new Error(invocationEvent.error)); + } + else { + resolve(invocationEvent.result); + } + } + else { + reject(new Error("Unexpected message type: " + invocationEvent.type)); + } + } + }; + var message = _this.protocol.writeMessage(invocationDescriptor); + _this.sendMessage(message) + .catch(function (e) { + reject(e); + // invocationId will always have a value for a non-blocking invocation + delete _this.callbacks[invocationDescriptor.invocationId]; + }); + }); + return p; + }; + /** Registers a handler that will be invoked when the hub method with the specified method name is invoked. + * + * @param {string} methodName The name of the hub method to define. + * @param {Function} newMethod The handler that will be raised when the hub method is invoked. + */ + HubConnection.prototype.on = function (methodName, newMethod) { + if (!methodName || !newMethod) { + return; + } + methodName = methodName.toLowerCase(); + if (!this.methods[methodName]) { + this.methods[methodName] = []; + } + // Preventing adding the same handler multiple times. + if (this.methods[methodName].indexOf(newMethod) !== -1) { + return; + } + this.methods[methodName].push(newMethod); + }; + HubConnection.prototype.off = function (methodName, method) { + if (!methodName) { + return; + } + methodName = methodName.toLowerCase(); + var handlers = this.methods[methodName]; + if (!handlers) { + return; + } + if (method) { + var removeIdx = handlers.indexOf(method); + if (removeIdx !== -1) { + handlers.splice(removeIdx, 1); + if (handlers.length === 0) { + delete this.methods[methodName]; + } + } + } + else { + delete this.methods[methodName]; + } + }; + /** Registers a handler that will be invoked when the connection is closed. + * + * @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). + */ + HubConnection.prototype.onclose = function (callback) { + if (callback) { + this.closedCallbacks.push(callback); + } + }; + HubConnection.prototype.processIncomingData = function (data) { + this.cleanupTimeout(); + if (!this.receivedHandshakeResponse) { + data = this.processHandshakeResponse(data); + this.receivedHandshakeResponse = true; + } + // Data may have all been read when processing handshake response + if (data) { + // Parse the messages + var messages = this.protocol.parseMessages(data, this.logger); + for (var _i = 0, messages_1 = messages; _i < messages_1.length; _i++) { + var message = messages_1[_i]; + switch (message.type) { + case _IHubProtocol__WEBPACK_IMPORTED_MODULE_1__["MessageType"].Invocation: + this.invokeClientMethod(message); + break; + case _IHubProtocol__WEBPACK_IMPORTED_MODULE_1__["MessageType"].StreamItem: + case _IHubProtocol__WEBPACK_IMPORTED_MODULE_1__["MessageType"].Completion: + var callback = this.callbacks[message.invocationId]; + if (callback != null) { + if (message.type === _IHubProtocol__WEBPACK_IMPORTED_MODULE_1__["MessageType"].Completion) { + delete this.callbacks[message.invocationId]; + } + callback(message); + } + break; + case _IHubProtocol__WEBPACK_IMPORTED_MODULE_1__["MessageType"].Ping: + // Don't care about pings + break; + case _IHubProtocol__WEBPACK_IMPORTED_MODULE_1__["MessageType"].Close: + this.logger.log(_ILogger__WEBPACK_IMPORTED_MODULE_2__["LogLevel"].Information, "Close message received from server."); + // We don't want to wait on the stop itself. + // tslint:disable-next-line:no-floating-promises + this.connection.stop(message.error ? new Error("Server returned an error on close: " + message.error) : undefined); + break; + default: + this.logger.log(_ILogger__WEBPACK_IMPORTED_MODULE_2__["LogLevel"].Warning, "Invalid message type: " + message.type + "."); + break; + } + } + } + this.resetTimeoutPeriod(); + }; + HubConnection.prototype.processHandshakeResponse = function (data) { + var _a; + var responseMessage; + var remainingData; + try { + _a = this.handshakeProtocol.parseHandshakeResponse(data), remainingData = _a[0], responseMessage = _a[1]; + } + catch (e) { + var message = "Error parsing handshake response: " + e; + this.logger.log(_ILogger__WEBPACK_IMPORTED_MODULE_2__["LogLevel"].Error, message); + var error = new Error(message); + // We don't want to wait on the stop itself. + // tslint:disable-next-line:no-floating-promises + this.connection.stop(error); + this.handshakeRejecter(error); + throw error; + } + if (responseMessage.error) { + var message = "Server returned handshake error: " + responseMessage.error; + this.logger.log(_ILogger__WEBPACK_IMPORTED_MODULE_2__["LogLevel"].Error, message); + this.handshakeRejecter(message); + // We don't want to wait on the stop itself. + // tslint:disable-next-line:no-floating-promises + this.connection.stop(new Error(message)); + throw new Error(message); + } + else { + this.logger.log(_ILogger__WEBPACK_IMPORTED_MODULE_2__["LogLevel"].Debug, "Server handshake complete."); + } + this.handshakeResolver(); + return remainingData; + }; + HubConnection.prototype.resetKeepAliveInterval = function () { + var _this = this; + this.cleanupPingTimer(); + this.pingServerHandle = setTimeout(function () { return __awaiter(_this, void 0, void 0, function () { + var _a; + return __generator(this, function (_b) { + switch (_b.label) { + case 0: + if (!(this.connectionState === HubConnectionState.Connected)) return [3 /*break*/, 4]; + _b.label = 1; + case 1: + _b.trys.push([1, 3, , 4]); + return [4 /*yield*/, this.sendMessage(this.cachedPingMessage)]; + case 2: + _b.sent(); + return [3 /*break*/, 4]; + case 3: + _a = _b.sent(); + // We don't care about the error. It should be seen elsewhere in the client. + // The connection is probably in a bad or closed state now, cleanup the timer so it stops triggering + this.cleanupPingTimer(); + return [3 /*break*/, 4]; + case 4: return [2 /*return*/]; + } + }); + }); }, this.keepAliveIntervalInMilliseconds); + }; + HubConnection.prototype.resetTimeoutPeriod = function () { var _this = this; - if (typeof (EventSource) === "undefined") { - Promise.reject("EventSource not supported by the browser."); + if (!this.connection.features || !this.connection.features.inherentKeepAlive) { + // Set the timeout timer + this.timeoutHandle = setTimeout(function () { return _this.serverTimeout(); }, this.serverTimeoutInMilliseconds); + } + }; + HubConnection.prototype.serverTimeout = function () { + // The server hasn't talked to us in a while. It doesn't like us anymore ... :( + // Terminate the connection, but we don't need to wait on the promise. + // tslint:disable-next-line:no-floating-promises + this.connection.stop(new Error("Server timeout elapsed without receiving a message from the server.")); + }; + HubConnection.prototype.invokeClientMethod = function (invocationMessage) { + var _this = this; + var methods = this.methods[invocationMessage.target.toLowerCase()]; + if (methods) { + methods.forEach(function (m) { return m.apply(_this, invocationMessage.arguments); }); + if (invocationMessage.invocationId) { + // This is not supported in v1. So we return an error to avoid blocking the server waiting for the response. + var message = "Server requested a response, which is not supported in this version of the client."; + this.logger.log(_ILogger__WEBPACK_IMPORTED_MODULE_2__["LogLevel"].Error, message); + // We don't need to wait on this Promise. + // tslint:disable-next-line:no-floating-promises + this.connection.stop(new Error(message)); + } + } + else { + this.logger.log(_ILogger__WEBPACK_IMPORTED_MODULE_2__["LogLevel"].Warning, "No client method with the name '" + invocationMessage.target + "' found."); + } + }; + HubConnection.prototype.connectionClosed = function (error) { + var _this = this; + var callbacks = this.callbacks; + this.callbacks = {}; + this.connectionState = HubConnectionState.Disconnected; + // if handshake is in progress start will be waiting for the handshake promise, so we complete it + // if it has already completed this should just noop + if (this.handshakeRejecter) { + this.handshakeRejecter(error); + } + Object.keys(callbacks) + .forEach(function (key) { + var callback = callbacks[key]; + callback(null, error ? error : new Error("Invocation canceled due to connection being closed.")); + }); + this.cleanupTimeout(); + this.cleanupPingTimer(); + this.closedCallbacks.forEach(function (c) { return c.apply(_this, [error]); }); + }; + HubConnection.prototype.cleanupPingTimer = function () { + if (this.pingServerHandle) { + clearTimeout(this.pingServerHandle); + } + }; + HubConnection.prototype.cleanupTimeout = function () { + if (this.timeoutHandle) { + clearTimeout(this.timeoutHandle); + } + }; + HubConnection.prototype.createInvocation = function (methodName, args, nonblocking) { + if (nonblocking) { + return { + arguments: args, + target: methodName, + type: _IHubProtocol__WEBPACK_IMPORTED_MODULE_1__["MessageType"].Invocation, + }; + } + else { + var id = this.id; + this.id++; + return { + arguments: args, + invocationId: id.toString(), + target: methodName, + type: _IHubProtocol__WEBPACK_IMPORTED_MODULE_1__["MessageType"].Invocation, + }; + } + }; + HubConnection.prototype.createStreamInvocation = function (methodName, args) { + var id = this.id; + this.id++; + return { + arguments: args, + invocationId: id.toString(), + target: methodName, + type: _IHubProtocol__WEBPACK_IMPORTED_MODULE_1__["MessageType"].StreamInvocation, + }; + }; + HubConnection.prototype.createCancelInvocation = function (id) { + return { + invocationId: id, + type: _IHubProtocol__WEBPACK_IMPORTED_MODULE_1__["MessageType"].CancelInvocation, + }; + }; + return HubConnection; +}()); + + + +/***/ }), +/* 10 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "HandshakeProtocol", function() { return HandshakeProtocol; }); +/* harmony import */ var _TextMessageFormat__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(11); +/* harmony import */ var _Utils__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(12); +// Copyright (c) .NET Foundation. All rights reserved. +// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. + + +/** @private */ +var HandshakeProtocol = /** @class */ (function () { + function HandshakeProtocol() { + } + // Handshake request is always JSON + HandshakeProtocol.prototype.writeHandshakeRequest = function (handshakeRequest) { + return _TextMessageFormat__WEBPACK_IMPORTED_MODULE_0__["TextMessageFormat"].write(JSON.stringify(handshakeRequest)); + }; + HandshakeProtocol.prototype.parseHandshakeResponse = function (data) { + var responseMessage; + var messageData; + var remainingData; + if (Object(_Utils__WEBPACK_IMPORTED_MODULE_1__["isArrayBuffer"])(data) || (typeof Buffer !== "undefined" && data instanceof Buffer)) { + // Format is binary but still need to read JSON text from handshake response + var binaryData = new Uint8Array(data); + var separatorIndex = binaryData.indexOf(_TextMessageFormat__WEBPACK_IMPORTED_MODULE_0__["TextMessageFormat"].RecordSeparatorCode); + if (separatorIndex === -1) { + throw new Error("Message is incomplete."); + } + // content before separator is handshake response + // optional content after is additional messages + var responseLength = separatorIndex + 1; + messageData = String.fromCharCode.apply(null, binaryData.slice(0, responseLength)); + remainingData = (binaryData.byteLength > responseLength) ? binaryData.slice(responseLength).buffer : null; + } + else { + var textData = data; + var separatorIndex = textData.indexOf(_TextMessageFormat__WEBPACK_IMPORTED_MODULE_0__["TextMessageFormat"].RecordSeparator); + if (separatorIndex === -1) { + throw new Error("Message is incomplete."); + } + // content before separator is handshake response + // optional content after is additional messages + var responseLength = separatorIndex + 1; + messageData = textData.substring(0, responseLength); + remainingData = (textData.length > responseLength) ? textData.substring(responseLength) : null; + } + // At this point we should have just the single handshake message + var messages = _TextMessageFormat__WEBPACK_IMPORTED_MODULE_0__["TextMessageFormat"].parse(messageData); + var response = JSON.parse(messages[0]); + if (response.type) { + throw new Error("Expected a handshake response from the server."); } + responseMessage = response; + // multiple messages could have arrived with handshake + // return additional data to be parsed as usual, or null if all parsed + return [remainingData, responseMessage]; + }; + return HandshakeProtocol; +}()); + + + +/***/ }), +/* 11 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TextMessageFormat", function() { return TextMessageFormat; }); +// Copyright (c) .NET Foundation. All rights reserved. +// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. +// Not exported from index +/** @private */ +var TextMessageFormat = /** @class */ (function () { + function TextMessageFormat() { + } + TextMessageFormat.write = function (output) { + return "" + output + TextMessageFormat.RecordSeparator; + }; + TextMessageFormat.parse = function (input) { + if (input[input.length - 1] !== TextMessageFormat.RecordSeparator) { + throw new Error("Message is incomplete."); + } + var messages = input.split(TextMessageFormat.RecordSeparator); + messages.pop(); + return messages; + }; + TextMessageFormat.RecordSeparatorCode = 0x1e; + TextMessageFormat.RecordSeparator = String.fromCharCode(TextMessageFormat.RecordSeparatorCode); + return TextMessageFormat; +}()); + + + +/***/ }), +/* 12 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Arg", function() { return Arg; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getDataDetail", function() { return getDataDetail; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "formatArrayBuffer", function() { return formatArrayBuffer; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isArrayBuffer", function() { return isArrayBuffer; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "sendMessage", function() { return sendMessage; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "createLogger", function() { return createLogger; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Subject", function() { return Subject; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SubjectSubscription", function() { return SubjectSubscription; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ConsoleLogger", function() { return ConsoleLogger; }); +/* harmony import */ var _ILogger__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(8); +/* harmony import */ var _Loggers__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(13); +// Copyright (c) .NET Foundation. All rights reserved. +// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. +var __awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +var __generator = (undefined && undefined.__generator) || function (thisArg, body) { + var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; + return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; + function verb(n) { return function (v) { return step([n, v]); }; } + function step(op) { + if (f) throw new TypeError("Generator is already executing."); + while (_) try { + 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; + if (y = 0, t) op = [op[0] & 2, t.value]; + switch (op[0]) { + case 0: case 1: t = op; break; + case 4: _.label++; return { value: op[1], done: false }; + case 5: _.label++; y = op[1]; op = [0]; continue; + case 7: op = _.ops.pop(); _.trys.pop(); continue; + default: + if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } + if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } + if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } + if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } + if (t[2]) _.ops.pop(); + _.trys.pop(); continue; + } + op = body.call(thisArg, _); + } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } + if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; + } +}; + + +/** @private */ +var Arg = /** @class */ (function () { + function Arg() { + } + Arg.isRequired = function (val, name) { + if (val === null || val === undefined) { + throw new Error("The '" + name + "' argument is required."); + } + }; + Arg.isIn = function (val, values, name) { + // TypeScript enums have keys for **both** the name and the value of each enum member on the type itself. + if (!(val in values)) { + throw new Error("Unknown " + name + " value: " + val + "."); + } + }; + return Arg; +}()); + +/** @private */ +function getDataDetail(data, includeContent) { + var detail = ""; + if (isArrayBuffer(data)) { + detail = "Binary data of length " + data.byteLength; + if (includeContent) { + detail += ". Content: '" + formatArrayBuffer(data) + "'"; + } + } + else if (typeof data === "string") { + detail = "String data of length " + data.length; + if (includeContent) { + detail += ". Content: '" + data + "'"; + } + } + return detail; +} +/** @private */ +function formatArrayBuffer(data) { + var view = new Uint8Array(data); + // Uint8Array.map only supports returning another Uint8Array? + var str = ""; + view.forEach(function (num) { + var pad = num < 16 ? "0" : ""; + str += "0x" + pad + num.toString(16) + " "; + }); + // Trim of trailing space. + return str.substr(0, str.length - 1); +} +// Also in signalr-protocol-msgpack/Utils.ts +/** @private */ +function isArrayBuffer(val) { + return val && typeof ArrayBuffer !== "undefined" && + (val instanceof ArrayBuffer || + // Sometimes we get an ArrayBuffer that doesn't satisfy instanceof + (val.constructor && val.constructor.name === "ArrayBuffer")); +} +/** @private */ +function sendMessage(logger, transportName, httpClient, url, accessTokenFactory, content, logMessageContent) { + return __awaiter(this, void 0, void 0, function () { + var _a, headers, token, responseType, response; + return __generator(this, function (_b) { + switch (_b.label) { + case 0: + if (!accessTokenFactory) return [3 /*break*/, 2]; + return [4 /*yield*/, accessTokenFactory()]; + case 1: + token = _b.sent(); + if (token) { + headers = (_a = {}, + _a["Authorization"] = "Bearer " + token, + _a); + } + _b.label = 2; + case 2: + logger.log(_ILogger__WEBPACK_IMPORTED_MODULE_0__["LogLevel"].Trace, "(" + transportName + " transport) sending data. " + getDataDetail(content, logMessageContent) + "."); + responseType = isArrayBuffer(content) ? "arraybuffer" : "text"; + return [4 /*yield*/, httpClient.post(url, { + content: content, + headers: headers, + responseType: responseType, + })]; + case 3: + response = _b.sent(); + logger.log(_ILogger__WEBPACK_IMPORTED_MODULE_0__["LogLevel"].Trace, "(" + transportName + " transport) request complete. Response status: " + response.statusCode + "."); + return [2 /*return*/]; + } + }); + }); +} +/** @private */ +function createLogger(logger) { + if (logger === undefined) { + return new ConsoleLogger(_ILogger__WEBPACK_IMPORTED_MODULE_0__["LogLevel"].Information); + } + if (logger === null) { + return _Loggers__WEBPACK_IMPORTED_MODULE_1__["NullLogger"].instance; + } + if (logger.log) { + return logger; + } + return new ConsoleLogger(logger); +} +/** @private */ +var Subject = /** @class */ (function () { + function Subject(cancelCallback) { + this.observers = []; + this.cancelCallback = cancelCallback; + } + Subject.prototype.next = function (item) { + for (var _i = 0, _a = this.observers; _i < _a.length; _i++) { + var observer = _a[_i]; + observer.next(item); + } + }; + Subject.prototype.error = function (err) { + for (var _i = 0, _a = this.observers; _i < _a.length; _i++) { + var observer = _a[_i]; + if (observer.error) { + observer.error(err); + } + } + }; + Subject.prototype.complete = function () { + for (var _i = 0, _a = this.observers; _i < _a.length; _i++) { + var observer = _a[_i]; + if (observer.complete) { + observer.complete(); + } + } + }; + Subject.prototype.subscribe = function (observer) { + this.observers.push(observer); + return new SubjectSubscription(this, observer); + }; + return Subject; +}()); + +/** @private */ +var SubjectSubscription = /** @class */ (function () { + function SubjectSubscription(subject, observer) { + this.subject = subject; + this.observer = observer; + } + SubjectSubscription.prototype.dispose = function () { + var index = this.subject.observers.indexOf(this.observer); + if (index > -1) { + this.subject.observers.splice(index, 1); + } + if (this.subject.observers.length === 0) { + this.subject.cancelCallback().catch(function (_) { }); + } + }; + return SubjectSubscription; +}()); + +/** @private */ +var ConsoleLogger = /** @class */ (function () { + function ConsoleLogger(minimumLogLevel) { + this.minimumLogLevel = minimumLogLevel; + } + ConsoleLogger.prototype.log = function (logLevel, message) { + if (logLevel >= this.minimumLogLevel) { + switch (logLevel) { + case _ILogger__WEBPACK_IMPORTED_MODULE_0__["LogLevel"].Critical: + case _ILogger__WEBPACK_IMPORTED_MODULE_0__["LogLevel"].Error: + console.error("[" + new Date().toISOString() + "] " + _ILogger__WEBPACK_IMPORTED_MODULE_0__["LogLevel"][logLevel] + ": " + message); + break; + case _ILogger__WEBPACK_IMPORTED_MODULE_0__["LogLevel"].Warning: + console.warn("[" + new Date().toISOString() + "] " + _ILogger__WEBPACK_IMPORTED_MODULE_0__["LogLevel"][logLevel] + ": " + message); + break; + case _ILogger__WEBPACK_IMPORTED_MODULE_0__["LogLevel"].Information: + console.info("[" + new Date().toISOString() + "] " + _ILogger__WEBPACK_IMPORTED_MODULE_0__["LogLevel"][logLevel] + ": " + message); + break; + default: + // console.debug only goes to attached debuggers in Node, so we use console.log for Trace and Debug + console.log("[" + new Date().toISOString() + "] " + _ILogger__WEBPACK_IMPORTED_MODULE_0__["LogLevel"][logLevel] + ": " + message); + break; + } + } + }; + return ConsoleLogger; +}()); + + + +/***/ }), +/* 13 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "NullLogger", function() { return NullLogger; }); +// Copyright (c) .NET Foundation. All rights reserved. +// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. +/** A logger that does nothing when log messages are sent to it. */ +var NullLogger = /** @class */ (function () { + function NullLogger() { + } + /** @inheritDoc */ + // tslint:disable-next-line + NullLogger.prototype.log = function (_logLevel, _message) { + }; + /** The singleton instance of the {@link @aspnet/signalr.NullLogger}. */ + NullLogger.instance = new NullLogger(); + return NullLogger; +}()); + + + +/***/ }), +/* 14 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "MessageType", function() { return MessageType; }); +// Copyright (c) .NET Foundation. All rights reserved. +// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. +/** Defines the type of a Hub Message. */ +var MessageType; +(function (MessageType) { + /** Indicates the message is an Invocation message and implements the {@link @aspnet/signalr.InvocationMessage} interface. */ + MessageType[MessageType["Invocation"] = 1] = "Invocation"; + /** Indicates the message is a StreamItem message and implements the {@link @aspnet/signalr.StreamItemMessage} interface. */ + MessageType[MessageType["StreamItem"] = 2] = "StreamItem"; + /** Indicates the message is a Completion message and implements the {@link @aspnet/signalr.CompletionMessage} interface. */ + MessageType[MessageType["Completion"] = 3] = "Completion"; + /** Indicates the message is a Stream Invocation message and implements the {@link @aspnet/signalr.StreamInvocationMessage} interface. */ + MessageType[MessageType["StreamInvocation"] = 4] = "StreamInvocation"; + /** Indicates the message is a Cancel Invocation message and implements the {@link @aspnet/signalr.CancelInvocationMessage} interface. */ + MessageType[MessageType["CancelInvocation"] = 5] = "CancelInvocation"; + /** Indicates the message is a Ping message and implements the {@link @aspnet/signalr.PingMessage} interface. */ + MessageType[MessageType["Ping"] = 6] = "Ping"; + /** Indicates the message is a Close message and implements the {@link @aspnet/signalr.CloseMessage} interface. */ + MessageType[MessageType["Close"] = 7] = "Close"; +})(MessageType || (MessageType = {})); + + +/***/ }), +/* 15 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "HubConnectionBuilder", function() { return HubConnectionBuilder; }); +/* harmony import */ var _HttpConnection__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(16); +/* harmony import */ var _HubConnection__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(9); +/* harmony import */ var _JsonHubProtocol__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(22); +/* harmony import */ var _Loggers__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(13); +/* harmony import */ var _Utils__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(12); +// Copyright (c) .NET Foundation. All rights reserved. +// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. + + + + + +/** A builder for configuring {@link @aspnet/signalr.HubConnection} instances. */ +var HubConnectionBuilder = /** @class */ (function () { + function HubConnectionBuilder() { + } + HubConnectionBuilder.prototype.configureLogging = function (logging) { + _Utils__WEBPACK_IMPORTED_MODULE_4__["Arg"].isRequired(logging, "logging"); + if (isLogger(logging)) { + this.logger = logging; + } + else { + this.logger = new _Utils__WEBPACK_IMPORTED_MODULE_4__["ConsoleLogger"](logging); + } + return this; + }; + HubConnectionBuilder.prototype.withUrl = function (url, transportTypeOrOptions) { + _Utils__WEBPACK_IMPORTED_MODULE_4__["Arg"].isRequired(url, "url"); this.url = url; - return new Promise(function (resolve, reject) { - var token = _this.accessTokenFactory(); - if (token) { - url += (url.indexOf("?") < 0 ? "?" : "&") + ("access_token=" + encodeURIComponent(token)); + // Flow-typing knows where it's at. Since HttpTransportType is a number and IHttpConnectionOptions is guaranteed + // to be an object, we know (as does TypeScript) this comparison is all we need to figure out which overload was called. + if (typeof transportTypeOrOptions === "object") { + this.httpConnectionOptions = transportTypeOrOptions; + } + else { + this.httpConnectionOptions = { + transport: transportTypeOrOptions, + }; + } + return this; + }; + /** Configures the {@link @aspnet/signalr.HubConnection} to use the specified Hub Protocol. + * + * @param {IHubProtocol} protocol The {@link @aspnet/signalr.IHubProtocol} implementation to use. + */ + HubConnectionBuilder.prototype.withHubProtocol = function (protocol) { + _Utils__WEBPACK_IMPORTED_MODULE_4__["Arg"].isRequired(protocol, "protocol"); + this.protocol = protocol; + return this; + }; + /** Creates a {@link @aspnet/signalr.HubConnection} from the configuration options specified in this builder. + * + * @returns {HubConnection} The configured {@link @aspnet/signalr.HubConnection}. + */ + HubConnectionBuilder.prototype.build = function () { + // If httpConnectionOptions has a logger, use it. Otherwise, override it with the one + // provided to configureLogger + var httpConnectionOptions = this.httpConnectionOptions || {}; + // If it's 'null', the user **explicitly** asked for null, don't mess with it. + if (httpConnectionOptions.logger === undefined) { + // If our logger is undefined or null, that's OK, the HttpConnection constructor will handle it. + httpConnectionOptions.logger = this.logger; + } + // Now create the connection + if (!this.url) { + throw new Error("The 'HubConnectionBuilder.withUrl' method must be called before building the connection."); + } + var connection = new _HttpConnection__WEBPACK_IMPORTED_MODULE_0__["HttpConnection"](this.url, httpConnectionOptions); + return _HubConnection__WEBPACK_IMPORTED_MODULE_1__["HubConnection"].create(connection, this.logger || _Loggers__WEBPACK_IMPORTED_MODULE_3__["NullLogger"].instance, this.protocol || new _JsonHubProtocol__WEBPACK_IMPORTED_MODULE_2__["JsonHubProtocol"]()); + }; + return HubConnectionBuilder; +}()); + +function isLogger(logger) { + return logger.log !== undefined; +} + + +/***/ }), +/* 16 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "HttpConnection", function() { return HttpConnection; }); +/* harmony import */ var _DefaultHttpClient__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(6); +/* harmony import */ var _ILogger__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(8); +/* harmony import */ var _ITransport__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(17); +/* harmony import */ var _LongPollingTransport__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(18); +/* harmony import */ var _ServerSentEventsTransport__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(20); +/* harmony import */ var _Utils__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(12); +/* harmony import */ var _WebSocketTransport__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(21); +// Copyright (c) .NET Foundation. All rights reserved. +// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. +var __awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +var __generator = (undefined && undefined.__generator) || function (thisArg, body) { + var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; + return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; + function verb(n) { return function (v) { return step([n, v]); }; } + function step(op) { + if (f) throw new TypeError("Generator is already executing."); + while (_) try { + 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; + if (y = 0, t) op = [op[0] & 2, t.value]; + switch (op[0]) { + case 0: case 1: t = op; break; + case 4: _.label++; return { value: op[1], done: false }; + case 5: _.label++; y = op[1]; op = [0]; continue; + case 7: op = _.ops.pop(); _.trys.pop(); continue; + default: + if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } + if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } + if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } + if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } + if (t[2]) _.ops.pop(); + _.trys.pop(); continue; } - var eventSource = new EventSource(url); - try { - eventSource.onmessage = function (e) { - if (_this.onreceive) { - try { - _this.logger.log(ILogger.LogLevel.Trace, "(SSE transport) data received: " + e.data); - _this.onreceive(e.data); + op = body.call(thisArg, _); + } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } + if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; + } +}; + + + + + + + +var MAX_REDIRECTS = 100; +var WebSocketModule = null; +var EventSourceModule = null; +if (typeof window === "undefined" && "function" !== "undefined") { + // In order to ignore the dynamic require in webpack builds we need to do this magic + // @ts-ignore: TS doesn't know about these names + var requireFunc = true ? require : undefined; + WebSocketModule = requireFunc("ws"); + EventSourceModule = requireFunc("eventsource"); +} +/** @private */ +var HttpConnection = /** @class */ (function () { + function HttpConnection(url, options) { + if (options === void 0) { options = {}; } + this.features = {}; + _Utils__WEBPACK_IMPORTED_MODULE_5__["Arg"].isRequired(url, "url"); + this.logger = Object(_Utils__WEBPACK_IMPORTED_MODULE_5__["createLogger"])(options.logger); + this.baseUrl = this.resolveUrl(url); + options = options || {}; + options.logMessageContent = options.logMessageContent || false; + var isNode = typeof window === "undefined"; + if (!isNode && typeof WebSocket !== "undefined" && !options.WebSocket) { + options.WebSocket = WebSocket; + } + else if (isNode && !options.WebSocket) { + if (WebSocketModule) { + options.WebSocket = WebSocketModule; + } + } + if (!isNode && typeof EventSource !== "undefined" && !options.EventSource) { + options.EventSource = EventSource; + } + else if (isNode && !options.EventSource) { + if (typeof EventSourceModule !== "undefined") { + options.EventSource = EventSourceModule; + } + } + this.httpClient = options.httpClient || new _DefaultHttpClient__WEBPACK_IMPORTED_MODULE_0__["DefaultHttpClient"](this.logger); + this.connectionState = 2 /* Disconnected */; + this.options = options; + this.onreceive = null; + this.onclose = null; + } + HttpConnection.prototype.start = function (transferFormat) { + transferFormat = transferFormat || _ITransport__WEBPACK_IMPORTED_MODULE_2__["TransferFormat"].Binary; + _Utils__WEBPACK_IMPORTED_MODULE_5__["Arg"].isIn(transferFormat, _ITransport__WEBPACK_IMPORTED_MODULE_2__["TransferFormat"], "transferFormat"); + this.logger.log(_ILogger__WEBPACK_IMPORTED_MODULE_1__["LogLevel"].Debug, "Starting connection with transfer format '" + _ITransport__WEBPACK_IMPORTED_MODULE_2__["TransferFormat"][transferFormat] + "'."); + if (this.connectionState !== 2 /* Disconnected */) { + return Promise.reject(new Error("Cannot start a connection that is not in the 'Disconnected' state.")); + } + this.connectionState = 0 /* Connecting */; + this.startPromise = this.startInternal(transferFormat); + return this.startPromise; + }; + HttpConnection.prototype.send = function (data) { + if (this.connectionState !== 1 /* Connected */) { + throw new Error("Cannot send data if the connection is not in the 'Connected' State."); + } + // Transport will not be null if state is connected + return this.transport.send(data); + }; + HttpConnection.prototype.stop = function (error) { + return __awaiter(this, void 0, void 0, function () { + var e_1; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + this.connectionState = 2 /* Disconnected */; + // Set error as soon as possible otherwise there is a race between + // the transport closing and providing an error and the error from a close message + // We would prefer the close message error. + this.stopError = error; + _a.label = 1; + case 1: + _a.trys.push([1, 3, , 4]); + return [4 /*yield*/, this.startPromise]; + case 2: + _a.sent(); + return [3 /*break*/, 4]; + case 3: + e_1 = _a.sent(); + return [3 /*break*/, 4]; + case 4: + if (!this.transport) return [3 /*break*/, 6]; + return [4 /*yield*/, this.transport.stop()]; + case 5: + _a.sent(); + this.transport = undefined; + _a.label = 6; + case 6: return [2 /*return*/]; + } + }); + }); + }; + HttpConnection.prototype.startInternal = function (transferFormat) { + return __awaiter(this, void 0, void 0, function () { + var url, negotiateResponse, redirects, _loop_1, this_1, state_1, e_2; + var _this = this; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + url = this.baseUrl; + this.accessTokenFactory = this.options.accessTokenFactory; + _a.label = 1; + case 1: + _a.trys.push([1, 12, , 13]); + if (!this.options.skipNegotiation) return [3 /*break*/, 5]; + if (!(this.options.transport === _ITransport__WEBPACK_IMPORTED_MODULE_2__["HttpTransportType"].WebSockets)) return [3 /*break*/, 3]; + // No need to add a connection ID in this case + this.transport = this.constructTransport(_ITransport__WEBPACK_IMPORTED_MODULE_2__["HttpTransportType"].WebSockets); + // We should just call connect directly in this case. + // No fallback or negotiate in this case. + return [4 /*yield*/, this.transport.connect(url, transferFormat)]; + case 2: + // We should just call connect directly in this case. + // No fallback or negotiate in this case. + _a.sent(); + return [3 /*break*/, 4]; + case 3: throw Error("Negotiation can only be skipped when using the WebSocket transport directly."); + case 4: return [3 /*break*/, 11]; + case 5: + negotiateResponse = null; + redirects = 0; + _loop_1 = function () { + var accessToken_1; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, this_1.getNegotiationResponse(url)]; + case 1: + negotiateResponse = _a.sent(); + // the user tries to stop the connection when it is being started + if (this_1.connectionState === 2 /* Disconnected */) { + return [2 /*return*/, { value: void 0 }]; + } + if (negotiateResponse.error) { + throw Error(negotiateResponse.error); + } + if (negotiateResponse.ProtocolVersion) { + throw Error("Detected a connection attempt to an ASP.NET SignalR Server. This client only supports connecting to an ASP.NET Core SignalR Server. See https://aka.ms/signalr-core-differences for details."); + } + if (negotiateResponse.url) { + url = negotiateResponse.url; + } + if (negotiateResponse.accessToken) { + accessToken_1 = negotiateResponse.accessToken; + this_1.accessTokenFactory = function () { return accessToken_1; }; + } + redirects++; + return [2 /*return*/]; + } + }); + }; + this_1 = this; + _a.label = 6; + case 6: return [5 /*yield**/, _loop_1()]; + case 7: + state_1 = _a.sent(); + if (typeof state_1 === "object") + return [2 /*return*/, state_1.value]; + _a.label = 8; + case 8: + if (negotiateResponse.url && redirects < MAX_REDIRECTS) return [3 /*break*/, 6]; + _a.label = 9; + case 9: + if (redirects === MAX_REDIRECTS && negotiateResponse.url) { + throw Error("Negotiate redirection limit exceeded."); } - catch (error) { - if (_this.onclose) { - _this.onclose(error); - } - return; + return [4 /*yield*/, this.createTransport(url, this.options.transport, negotiateResponse, transferFormat)]; + case 10: + _a.sent(); + _a.label = 11; + case 11: + if (this.transport instanceof _LongPollingTransport__WEBPACK_IMPORTED_MODULE_3__["LongPollingTransport"]) { + this.features.inherentKeepAlive = true; } - } - }; - eventSource.onerror = function (e) { - reject(); - // don't report an error if the transport did not start successfully - if (_this.eventSource && _this.onclose) { - _this.onclose(new Error(e.message || "Error occurred")); - } - }; - eventSource.onopen = function () { - _this.logger.log(ILogger.LogLevel.Information, "SSE connected to " + _this.url); - _this.eventSource = eventSource; - // SSE is a text protocol - resolve(1 /* Text */); - }; - } - catch (e) { - return Promise.reject(e); - } + this.transport.onreceive = this.onreceive; + this.transport.onclose = function (e) { return _this.stopConnection(e); }; + // only change the state if we were connecting to not overwrite + // the state if the connection is already marked as Disconnected + this.changeState(0 /* Connecting */, 1 /* Connected */); + return [3 /*break*/, 13]; + case 12: + e_2 = _a.sent(); + this.logger.log(_ILogger__WEBPACK_IMPORTED_MODULE_1__["LogLevel"].Error, "Failed to start the connection: " + e_2); + this.connectionState = 2 /* Disconnected */; + this.transport = undefined; + throw e_2; + case 13: return [2 /*return*/]; + } + }); }); }; - ServerSentEventsTransport.prototype.send = function (data) { + HttpConnection.prototype.getNegotiationResponse = function (url) { return __awaiter(this, void 0, void 0, function () { + var _a, headers, token, negotiateUrl, response, e_3; + return __generator(this, function (_b) { + switch (_b.label) { + case 0: + if (!this.accessTokenFactory) return [3 /*break*/, 2]; + return [4 /*yield*/, this.accessTokenFactory()]; + case 1: + token = _b.sent(); + if (token) { + headers = (_a = {}, + _a["Authorization"] = "Bearer " + token, + _a); + } + _b.label = 2; + case 2: + negotiateUrl = this.resolveNegotiateUrl(url); + this.logger.log(_ILogger__WEBPACK_IMPORTED_MODULE_1__["LogLevel"].Debug, "Sending negotiation request: " + negotiateUrl + "."); + _b.label = 3; + case 3: + _b.trys.push([3, 5, , 6]); + return [4 /*yield*/, this.httpClient.post(negotiateUrl, { + content: "", + headers: headers, + })]; + case 4: + response = _b.sent(); + if (response.statusCode !== 200) { + throw Error("Unexpected status code returned from negotiate " + response.statusCode); + } + return [2 /*return*/, JSON.parse(response.content)]; + case 5: + e_3 = _b.sent(); + this.logger.log(_ILogger__WEBPACK_IMPORTED_MODULE_1__["LogLevel"].Error, "Failed to complete negotiation with the server: " + e_3); + throw e_3; + case 6: return [2 /*return*/]; + } + }); + }); + }; + HttpConnection.prototype.createConnectUrl = function (url, connectionId) { + if (!connectionId) { + return url; + } + return url + (url.indexOf("?") === -1 ? "?" : "&") + ("id=" + connectionId); + }; + HttpConnection.prototype.createTransport = function (url, requestedTransport, negotiateResponse, requestedTransferFormat) { + return __awaiter(this, void 0, void 0, function () { + var connectUrl, transports, _i, transports_1, endpoint, transport, ex_1; return __generator(this, function (_a) { - return [2 /*return*/, send(this.httpClient, this.url, this.accessTokenFactory, data)]; + switch (_a.label) { + case 0: + connectUrl = this.createConnectUrl(url, negotiateResponse.connectionId); + if (!this.isITransport(requestedTransport)) return [3 /*break*/, 2]; + this.logger.log(_ILogger__WEBPACK_IMPORTED_MODULE_1__["LogLevel"].Debug, "Connection was provided an instance of ITransport, using that directly."); + this.transport = requestedTransport; + return [4 /*yield*/, this.transport.connect(connectUrl, requestedTransferFormat)]; + case 1: + _a.sent(); + // only change the state if we were connecting to not overwrite + // the state if the connection is already marked as Disconnected + this.changeState(0 /* Connecting */, 1 /* Connected */); + return [2 /*return*/]; + case 2: + transports = negotiateResponse.availableTransports || []; + _i = 0, transports_1 = transports; + _a.label = 3; + case 3: + if (!(_i < transports_1.length)) return [3 /*break*/, 9]; + endpoint = transports_1[_i]; + this.connectionState = 0 /* Connecting */; + transport = this.resolveTransport(endpoint, requestedTransport, requestedTransferFormat); + if (!(typeof transport === "number")) return [3 /*break*/, 8]; + this.transport = this.constructTransport(transport); + if (!!negotiateResponse.connectionId) return [3 /*break*/, 5]; + return [4 /*yield*/, this.getNegotiationResponse(url)]; + case 4: + negotiateResponse = _a.sent(); + connectUrl = this.createConnectUrl(url, negotiateResponse.connectionId); + _a.label = 5; + case 5: + _a.trys.push([5, 7, , 8]); + return [4 /*yield*/, this.transport.connect(connectUrl, requestedTransferFormat)]; + case 6: + _a.sent(); + this.changeState(0 /* Connecting */, 1 /* Connected */); + return [2 /*return*/]; + case 7: + ex_1 = _a.sent(); + this.logger.log(_ILogger__WEBPACK_IMPORTED_MODULE_1__["LogLevel"].Error, "Failed to start the transport '" + _ITransport__WEBPACK_IMPORTED_MODULE_2__["HttpTransportType"][transport] + "': " + ex_1); + this.connectionState = 2 /* Disconnected */; + negotiateResponse.connectionId = undefined; + return [3 /*break*/, 8]; + case 8: + _i++; + return [3 /*break*/, 3]; + case 9: throw new Error("Unable to initialize any of the available transports."); + } }); }); }; - ServerSentEventsTransport.prototype.stop = function () { - if (this.eventSource) { - this.eventSource.close(); - this.eventSource = null; + HttpConnection.prototype.constructTransport = function (transport) { + switch (transport) { + case _ITransport__WEBPACK_IMPORTED_MODULE_2__["HttpTransportType"].WebSockets: + if (!this.options.WebSocket) { + throw new Error("'WebSocket' is not supported in your environment."); + } + return new _WebSocketTransport__WEBPACK_IMPORTED_MODULE_6__["WebSocketTransport"](this.httpClient, this.accessTokenFactory, this.logger, this.options.logMessageContent || false, this.options.WebSocket); + case _ITransport__WEBPACK_IMPORTED_MODULE_2__["HttpTransportType"].ServerSentEvents: + if (!this.options.EventSource) { + throw new Error("'EventSource' is not supported in your environment."); + } + return new _ServerSentEventsTransport__WEBPACK_IMPORTED_MODULE_4__["ServerSentEventsTransport"](this.httpClient, this.accessTokenFactory, this.logger, this.options.logMessageContent || false, this.options.EventSource); + case _ITransport__WEBPACK_IMPORTED_MODULE_2__["HttpTransportType"].LongPolling: + return new _LongPollingTransport__WEBPACK_IMPORTED_MODULE_3__["LongPollingTransport"](this.httpClient, this.accessTokenFactory, this.logger, this.options.logMessageContent || false); + default: + throw new Error("Unknown transport: " + transport + "."); } - return Promise.resolve(); }; - return ServerSentEventsTransport; + HttpConnection.prototype.resolveTransport = function (endpoint, requestedTransport, requestedTransferFormat) { + var transport = _ITransport__WEBPACK_IMPORTED_MODULE_2__["HttpTransportType"][endpoint.transport]; + if (transport === null || transport === undefined) { + this.logger.log(_ILogger__WEBPACK_IMPORTED_MODULE_1__["LogLevel"].Debug, "Skipping transport '" + endpoint.transport + "' because it is not supported by this client."); + } + else { + var transferFormats = endpoint.transferFormats.map(function (s) { return _ITransport__WEBPACK_IMPORTED_MODULE_2__["TransferFormat"][s]; }); + if (transportMatches(requestedTransport, transport)) { + if (transferFormats.indexOf(requestedTransferFormat) >= 0) { + if ((transport === _ITransport__WEBPACK_IMPORTED_MODULE_2__["HttpTransportType"].WebSockets && !this.options.WebSocket) || + (transport === _ITransport__WEBPACK_IMPORTED_MODULE_2__["HttpTransportType"].ServerSentEvents && !this.options.EventSource)) { + this.logger.log(_ILogger__WEBPACK_IMPORTED_MODULE_1__["LogLevel"].Debug, "Skipping transport '" + _ITransport__WEBPACK_IMPORTED_MODULE_2__["HttpTransportType"][transport] + "' because it is not supported in your environment.'"); + } + else { + this.logger.log(_ILogger__WEBPACK_IMPORTED_MODULE_1__["LogLevel"].Debug, "Selecting transport '" + _ITransport__WEBPACK_IMPORTED_MODULE_2__["HttpTransportType"][transport] + "'."); + return transport; + } + } + else { + this.logger.log(_ILogger__WEBPACK_IMPORTED_MODULE_1__["LogLevel"].Debug, "Skipping transport '" + _ITransport__WEBPACK_IMPORTED_MODULE_2__["HttpTransportType"][transport] + "' because it does not support the requested transfer format '" + _ITransport__WEBPACK_IMPORTED_MODULE_2__["TransferFormat"][requestedTransferFormat] + "'."); + } + } + else { + this.logger.log(_ILogger__WEBPACK_IMPORTED_MODULE_1__["LogLevel"].Debug, "Skipping transport '" + _ITransport__WEBPACK_IMPORTED_MODULE_2__["HttpTransportType"][transport] + "' because it was disabled by the client."); + } + } + return null; + }; + HttpConnection.prototype.isITransport = function (transport) { + return transport && typeof (transport) === "object" && "connect" in transport; + }; + HttpConnection.prototype.changeState = function (from, to) { + if (this.connectionState === from) { + this.connectionState = to; + return true; + } + return false; + }; + HttpConnection.prototype.stopConnection = function (error) { + this.transport = undefined; + // If we have a stopError, it takes precedence over the error from the transport + error = this.stopError || error; + if (error) { + this.logger.log(_ILogger__WEBPACK_IMPORTED_MODULE_1__["LogLevel"].Error, "Connection disconnected with error '" + error + "'."); + } + else { + this.logger.log(_ILogger__WEBPACK_IMPORTED_MODULE_1__["LogLevel"].Information, "Connection disconnected."); + } + this.connectionState = 2 /* Disconnected */; + if (this.onclose) { + this.onclose(error); + } + }; + HttpConnection.prototype.resolveUrl = function (url) { + // startsWith is not supported in IE + if (url.lastIndexOf("https://", 0) === 0 || url.lastIndexOf("http://", 0) === 0) { + return url; + } + if (typeof window === "undefined" || !window || !window.document) { + throw new Error("Cannot resolve '" + url + "'."); + } + // Setting the url to the href propery of an anchor tag handles normalization + // for us. There are 3 main cases. + // 1. Relative path normalization e.g "b" -> "http://localhost:5000/a/b" + // 2. Absolute path normalization e.g "/a/b" -> "http://localhost:5000/a/b" + // 3. Networkpath reference normalization e.g "//localhost:5000/a/b" -> "http://localhost:5000/a/b" + var aTag = window.document.createElement("a"); + aTag.href = url; + this.logger.log(_ILogger__WEBPACK_IMPORTED_MODULE_1__["LogLevel"].Information, "Normalizing '" + url + "' to '" + aTag.href + "'."); + return aTag.href; + }; + HttpConnection.prototype.resolveNegotiateUrl = function (url) { + var index = url.indexOf("?"); + var negotiateUrl = url.substring(0, index === -1 ? url.length : index); + if (negotiateUrl[negotiateUrl.length - 1] !== "/") { + negotiateUrl += "/"; + } + negotiateUrl += "negotiate"; + negotiateUrl += index === -1 ? "" : url.substring(index); + return negotiateUrl; + }; + return HttpConnection; }()); -exports.ServerSentEventsTransport = ServerSentEventsTransport; + +function transportMatches(requestedTransport, actualTransport) { + return !requestedTransport || ((actualTransport & requestedTransport) !== 0); +} + + +/***/ }), +/* 17 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "HttpTransportType", function() { return HttpTransportType; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TransferFormat", function() { return TransferFormat; }); +// Copyright (c) .NET Foundation. All rights reserved. +// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. +// This will be treated as a bit flag in the future, so we keep it using power-of-two values. +/** Specifies a specific HTTP transport type. */ +var HttpTransportType; +(function (HttpTransportType) { + /** Specifies no transport preference. */ + HttpTransportType[HttpTransportType["None"] = 0] = "None"; + /** Specifies the WebSockets transport. */ + HttpTransportType[HttpTransportType["WebSockets"] = 1] = "WebSockets"; + /** Specifies the Server-Sent Events transport. */ + HttpTransportType[HttpTransportType["ServerSentEvents"] = 2] = "ServerSentEvents"; + /** Specifies the Long Polling transport. */ + HttpTransportType[HttpTransportType["LongPolling"] = 4] = "LongPolling"; +})(HttpTransportType || (HttpTransportType = {})); +/** Specifies the transfer format for a connection. */ +var TransferFormat; +(function (TransferFormat) { + /** Specifies that only text data will be transmitted over the connection. */ + TransferFormat[TransferFormat["Text"] = 1] = "Text"; + /** Specifies that binary data will be transmitted over the connection. */ + TransferFormat[TransferFormat["Binary"] = 2] = "Binary"; +})(TransferFormat || (TransferFormat = {})); + + +/***/ }), +/* 18 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "LongPollingTransport", function() { return LongPollingTransport; }); +/* harmony import */ var _AbortController__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(19); +/* harmony import */ var _Errors__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(4); +/* harmony import */ var _ILogger__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(8); +/* harmony import */ var _ITransport__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(17); +/* harmony import */ var _Utils__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(12); +// Copyright (c) .NET Foundation. All rights reserved. +// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. +var __awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +var __generator = (undefined && undefined.__generator) || function (thisArg, body) { + var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; + return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; + function verb(n) { return function (v) { return step([n, v]); }; } + function step(op) { + if (f) throw new TypeError("Generator is already executing."); + while (_) try { + 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; + if (y = 0, t) op = [op[0] & 2, t.value]; + switch (op[0]) { + case 0: case 1: t = op; break; + case 4: _.label++; return { value: op[1], done: false }; + case 5: _.label++; y = op[1]; op = [0]; continue; + case 7: op = _.ops.pop(); _.trys.pop(); continue; + default: + if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } + if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } + if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } + if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } + if (t[2]) _.ops.pop(); + _.trys.pop(); continue; + } + op = body.call(thisArg, _); + } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } + if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; + } +}; + + + + + +// Not exported from 'index', this type is internal. +/** @private */ var LongPollingTransport = /** @class */ (function () { - function LongPollingTransport(httpClient, accessTokenFactory, logger) { + function LongPollingTransport(httpClient, accessTokenFactory, logger, logMessageContent) { this.httpClient = httpClient; - this.accessTokenFactory = accessTokenFactory || (function () { return null; }); + this.accessTokenFactory = accessTokenFactory; this.logger = logger; - this.pollAbort = new AbortController_1.AbortController(); + this.pollAbort = new _AbortController__WEBPACK_IMPORTED_MODULE_0__["AbortController"](); + this.logMessageContent = logMessageContent; + this.running = false; + this.onreceive = null; + this.onclose = null; } - LongPollingTransport.prototype.connect = function (url, requestedTransferMode, connection) { - this.url = url; - // Set a flag indicating we have inherent keep-alive in this transport. - connection.features.inherentKeepAlive = true; - if (requestedTransferMode === 2 /* Binary */ && (typeof new XMLHttpRequest().responseType !== "string")) { - // This will work if we fix: https://github.com/aspnet/SignalR/issues/742 - throw new Error("Binary protocols over XmlHttpRequest not implementing advanced features are not supported."); - } - this.poll(this.url, requestedTransferMode); - return Promise.resolve(requestedTransferMode); - }; - LongPollingTransport.prototype.poll = function (url, transferMode) { + Object.defineProperty(LongPollingTransport.prototype, "pollAborted", { + // This is an internal type, not exported from 'index' so this is really just internal. + get: function () { + return this.pollAbort.aborted; + }, + enumerable: true, + configurable: true + }); + LongPollingTransport.prototype.connect = function (url, transferFormat) { return __awaiter(this, void 0, void 0, function () { - var pollOptions, token, pollUrl, response, e_1; + var pollOptions, token, pollUrl, response; return __generator(this, function (_a) { switch (_a.label) { case 0: + _Utils__WEBPACK_IMPORTED_MODULE_4__["Arg"].isRequired(url, "url"); + _Utils__WEBPACK_IMPORTED_MODULE_4__["Arg"].isRequired(transferFormat, "transferFormat"); + _Utils__WEBPACK_IMPORTED_MODULE_4__["Arg"].isIn(transferFormat, _ITransport__WEBPACK_IMPORTED_MODULE_3__["TransferFormat"], "transferFormat"); + this.url = url; + this.logger.log(_ILogger__WEBPACK_IMPORTED_MODULE_2__["LogLevel"].Trace, "(LongPolling transport) Connecting."); + // Allow binary format on Node and Browsers that support binary content (indicated by the presence of responseType property) + if (transferFormat === _ITransport__WEBPACK_IMPORTED_MODULE_3__["TransferFormat"].Binary && + (typeof XMLHttpRequest !== "undefined" && typeof new XMLHttpRequest().responseType !== "string")) { + throw new Error("Binary protocols over XmlHttpRequest not implementing advanced features are not supported."); + } pollOptions = { - timeout: 120000, abortSignal: this.pollAbort.signal, - headers: new Map(), + headers: {}, + timeout: 100000, }; - if (transferMode === 2 /* Binary */) { + if (transferFormat === _ITransport__WEBPACK_IMPORTED_MODULE_3__["TransferFormat"].Binary) { pollOptions.responseType = "arraybuffer"; } - token = this.accessTokenFactory(); - if (token) { - pollOptions.headers.set("Authorization", "Bearer " + token); + return [4 /*yield*/, this.getAccessToken()]; + case 1: + token = _a.sent(); + this.updateHeaderToken(pollOptions, token); + pollUrl = url + "&_=" + Date.now(); + this.logger.log(_ILogger__WEBPACK_IMPORTED_MODULE_2__["LogLevel"].Trace, "(LongPolling transport) polling: " + pollUrl + "."); + return [4 /*yield*/, this.httpClient.get(pollUrl, pollOptions)]; + case 2: + response = _a.sent(); + if (response.statusCode !== 200) { + this.logger.log(_ILogger__WEBPACK_IMPORTED_MODULE_2__["LogLevel"].Error, "(LongPolling transport) Unexpected response code: " + response.statusCode + "."); + // Mark running as false so that the poll immediately ends and runs the close logic + this.closeError = new _Errors__WEBPACK_IMPORTED_MODULE_1__["HttpError"](response.statusText || "", response.statusCode); + this.running = false; } + else { + this.running = true; + } + this.receiving = this.poll(this.url, pollOptions); + return [2 /*return*/]; + } + }); + }); + }; + LongPollingTransport.prototype.getAccessToken = function () { + return __awaiter(this, void 0, void 0, function () { + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + if (!this.accessTokenFactory) return [3 /*break*/, 2]; + return [4 /*yield*/, this.accessTokenFactory()]; + case 1: return [2 /*return*/, _a.sent()]; + case 2: return [2 /*return*/, null]; + } + }); + }); + }; + LongPollingTransport.prototype.updateHeaderToken = function (request, token) { + if (!request.headers) { + request.headers = {}; + } + if (token) { + // tslint:disable-next-line:no-string-literal + request.headers["Authorization"] = "Bearer " + token; + return; + } + // tslint:disable-next-line:no-string-literal + if (request.headers["Authorization"]) { + // tslint:disable-next-line:no-string-literal + delete request.headers["Authorization"]; + } + }; + LongPollingTransport.prototype.poll = function (url, pollOptions) { + return __awaiter(this, void 0, void 0, function () { + var token, pollUrl, response, e_1; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + _a.trys.push([0, , 8, 9]); _a.label = 1; case 1: - if (!!this.pollAbort.signal.aborted) return [3 /*break*/, 6]; - _a.label = 2; + if (!this.running) return [3 /*break*/, 7]; + return [4 /*yield*/, this.getAccessToken()]; case 2: - _a.trys.push([2, 4, , 5]); + token = _a.sent(); + this.updateHeaderToken(pollOptions, token); + _a.label = 3; + case 3: + _a.trys.push([3, 5, , 6]); pollUrl = url + "&_=" + Date.now(); - this.logger.log(ILogger.LogLevel.Trace, "(LongPolling transport) polling: " + pollUrl); + this.logger.log(_ILogger__WEBPACK_IMPORTED_MODULE_2__["LogLevel"].Trace, "(LongPolling transport) polling: " + pollUrl + "."); return [4 /*yield*/, this.httpClient.get(pollUrl, pollOptions)]; - case 3: + case 4: response = _a.sent(); if (response.statusCode === 204) { - this.logger.log(ILogger.LogLevel.Information, "(LongPolling transport) Poll terminated by server"); - // Poll terminated by server - if (this.onclose) { - this.onclose(); - } - this.pollAbort.abort(); + this.logger.log(_ILogger__WEBPACK_IMPORTED_MODULE_2__["LogLevel"].Information, "(LongPolling transport) Poll terminated by server."); + this.running = false; } else if (response.statusCode !== 200) { - this.logger.log(ILogger.LogLevel.Error, "(LongPolling transport) Unexpected response code: " + response.statusCode); + this.logger.log(_ILogger__WEBPACK_IMPORTED_MODULE_2__["LogLevel"].Error, "(LongPolling transport) Unexpected response code: " + response.statusCode + "."); // Unexpected status code - if (this.onclose) { - this.onclose(new Errors.HttpError(response.statusText, response.statusCode)); - } - this.pollAbort.abort(); + this.closeError = new _Errors__WEBPACK_IMPORTED_MODULE_1__["HttpError"](response.statusText || "", response.statusCode); + this.running = false; } else { // Process the response if (response.content) { - this.logger.log(ILogger.LogLevel.Trace, "(LongPolling transport) data received: " + response.content); + this.logger.log(_ILogger__WEBPACK_IMPORTED_MODULE_2__["LogLevel"].Trace, "(LongPolling transport) data received. " + Object(_Utils__WEBPACK_IMPORTED_MODULE_4__["getDataDetail"])(response.content, this.logMessageContent) + "."); if (this.onreceive) { this.onreceive(response.content); } } else { // This is another way timeout manifest. - this.logger.log(ILogger.LogLevel.Trace, "(LongPolling transport) Poll timed out, reissuing."); + this.logger.log(_ILogger__WEBPACK_IMPORTED_MODULE_2__["LogLevel"].Trace, "(LongPolling transport) Poll timed out, reissuing."); } } - return [3 /*break*/, 5]; - case 4: + return [3 /*break*/, 6]; + case 5: e_1 = _a.sent(); - if (e_1 instanceof Errors.TimeoutError) { - // Ignore timeouts and reissue the poll. - this.logger.log(ILogger.LogLevel.Trace, "(LongPolling transport) Poll timed out, reissuing."); + if (!this.running) { + // Log but disregard errors that occur after stopping + this.logger.log(_ILogger__WEBPACK_IMPORTED_MODULE_2__["LogLevel"].Trace, "(LongPolling transport) Poll errored after shutdown: " + e_1.message); } else { - // Close the connection with the error as the result. - if (this.onclose) { - this.onclose(e_1); + if (e_1 instanceof _Errors__WEBPACK_IMPORTED_MODULE_1__["TimeoutError"]) { + // Ignore timeouts and reissue the poll. + this.logger.log(_ILogger__WEBPACK_IMPORTED_MODULE_2__["LogLevel"].Trace, "(LongPolling transport) Poll timed out, reissuing."); + } + else { + // Close the connection with the error as the result. + this.closeError = e_1; + this.running = false; } - this.pollAbort.abort(); } - return [3 /*break*/, 5]; - case 5: return [3 /*break*/, 1]; - case 6: return [2 /*return*/]; + return [3 /*break*/, 6]; + case 6: return [3 /*break*/, 1]; + case 7: return [3 /*break*/, 9]; + case 8: + this.logger.log(_ILogger__WEBPACK_IMPORTED_MODULE_2__["LogLevel"].Trace, "(LongPolling transport) Polling complete."); + // We will reach here with pollAborted==false when the server returned a response causing the transport to stop. + // If pollAborted==true then client initiated the stop and the stop method will raise the close event after DELETE is sent. + if (!this.pollAborted) { + this.raiseOnClose(); + } + return [7 /*endfinally*/]; + case 9: return [2 /*return*/]; } }); }); @@ -1680,110 +3527,128 @@ var LongPollingTransport = /** @class */ (function () { LongPollingTransport.prototype.send = function (data) { return __awaiter(this, void 0, void 0, function () { return __generator(this, function (_a) { - return [2 /*return*/, send(this.httpClient, this.url, this.accessTokenFactory, data)]; + if (!this.running) { + return [2 /*return*/, Promise.reject(new Error("Cannot send until the transport is connected"))]; + } + return [2 /*return*/, Object(_Utils__WEBPACK_IMPORTED_MODULE_4__["sendMessage"])(this.logger, "LongPolling", this.httpClient, this.url, this.accessTokenFactory, data, this.logMessageContent)]; }); }); }; LongPollingTransport.prototype.stop = function () { - this.pollAbort.abort(); - return Promise.resolve(); + return __awaiter(this, void 0, void 0, function () { + var deleteOptions, token; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + this.logger.log(_ILogger__WEBPACK_IMPORTED_MODULE_2__["LogLevel"].Trace, "(LongPolling transport) Stopping polling."); + // Tell receiving loop to stop, abort any current request, and then wait for it to finish + this.running = false; + this.pollAbort.abort(); + _a.label = 1; + case 1: + _a.trys.push([1, , 5, 6]); + return [4 /*yield*/, this.receiving]; + case 2: + _a.sent(); + // Send DELETE to clean up long polling on the server + this.logger.log(_ILogger__WEBPACK_IMPORTED_MODULE_2__["LogLevel"].Trace, "(LongPolling transport) sending DELETE request to " + this.url + "."); + deleteOptions = { + headers: {}, + }; + return [4 /*yield*/, this.getAccessToken()]; + case 3: + token = _a.sent(); + this.updateHeaderToken(deleteOptions, token); + return [4 /*yield*/, this.httpClient.delete(this.url, deleteOptions)]; + case 4: + _a.sent(); + this.logger.log(_ILogger__WEBPACK_IMPORTED_MODULE_2__["LogLevel"].Trace, "(LongPolling transport) DELETE request sent."); + return [3 /*break*/, 6]; + case 5: + this.logger.log(_ILogger__WEBPACK_IMPORTED_MODULE_2__["LogLevel"].Trace, "(LongPolling transport) Stop finished."); + // Raise close event here instead of in polling + // It needs to happen after the DELETE request is sent + this.raiseOnClose(); + return [7 /*endfinally*/]; + case 6: return [2 /*return*/]; + } + }); + }); }; - return LongPollingTransport; -}()); -exports.LongPollingTransport = LongPollingTransport; -function send(httpClient, url, accessTokenFactory, content) { - return __awaiter(this, void 0, void 0, function () { - var headers, token; - return __generator(this, function (_a) { - switch (_a.label) { - case 0: - token = accessTokenFactory(); - if (token) { - headers = new Map(); - headers.set("Authorization", "Bearer " + accessTokenFactory()); - } - return [4 /*yield*/, httpClient.post(url, { - content: content, - headers: headers - })]; - case 1: - _a.sent(); - return [2 /*return*/]; + LongPollingTransport.prototype.raiseOnClose = function () { + if (this.onclose) { + var logMessage = "(LongPolling transport) Firing onclose event."; + if (this.closeError) { + logMessage += " Error: " + this.closeError; } - }); - }); -} + this.logger.log(_ILogger__WEBPACK_IMPORTED_MODULE_2__["LogLevel"].Trace, logMessage); + this.onclose(this.closeError); + } + }; + return LongPollingTransport; +}()); -}); -unwrapExports(Transports); -var Transports_1 = Transports.TransportType; -var Transports_2 = Transports.WebSocketTransport; -var Transports_3 = Transports.ServerSentEventsTransport; -var Transports_4 = Transports.LongPollingTransport; -var Loggers = createCommonjsModule(function (module, exports) { -Object.defineProperty(exports, "__esModule", { value: true }); +/***/ }), +/* 19 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { -var NullLogger = /** @class */ (function () { - function NullLogger() { - } - NullLogger.prototype.log = function (logLevel, message) { - }; - return NullLogger; -}()); -exports.NullLogger = NullLogger; -var ConsoleLogger = /** @class */ (function () { - function ConsoleLogger(minimumLogLevel) { - this.minimumLogLevel = minimumLogLevel; +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "AbortController", function() { return AbortController; }); +// Copyright (c) .NET Foundation. All rights reserved. +// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. +// Rough polyfill of https://developer.mozilla.org/en-US/docs/Web/API/AbortController +// We don't actually ever use the API being polyfilled, we always use the polyfill because +// it's a very new API right now. +// Not exported from index. +/** @private */ +var AbortController = /** @class */ (function () { + function AbortController() { + this.isAborted = false; + this.onabort = null; } - ConsoleLogger.prototype.log = function (logLevel, message) { - if (logLevel >= this.minimumLogLevel) { - switch (logLevel) { - case ILogger.LogLevel.Error: - console.error(ILogger.LogLevel[logLevel] + ": " + message); - break; - case ILogger.LogLevel.Warning: - console.warn(ILogger.LogLevel[logLevel] + ": " + message); - break; - case ILogger.LogLevel.Information: - console.info(ILogger.LogLevel[logLevel] + ": " + message); - break; - default: - console.log(ILogger.LogLevel[logLevel] + ": " + message); - break; + AbortController.prototype.abort = function () { + if (!this.isAborted) { + this.isAborted = true; + if (this.onabort) { + this.onabort(); } } }; - return ConsoleLogger; + Object.defineProperty(AbortController.prototype, "signal", { + get: function () { + return this; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(AbortController.prototype, "aborted", { + get: function () { + return this.isAborted; + }, + enumerable: true, + configurable: true + }); + return AbortController; }()); -exports.ConsoleLogger = ConsoleLogger; -var LoggerFactory; -(function (LoggerFactory) { - function createLogger(logging) { - if (logging === undefined) { - return new ConsoleLogger(ILogger.LogLevel.Information); - } - if (logging === null) { - return new NullLogger(); - } - if (logging.log) { - return logging; - } - return new ConsoleLogger(logging); - } - LoggerFactory.createLogger = createLogger; -})(LoggerFactory = exports.LoggerFactory || (exports.LoggerFactory = {})); -}); -unwrapExports(Loggers); -var Loggers_1 = Loggers.NullLogger; -var Loggers_2 = Loggers.ConsoleLogger; -var Loggers_3 = Loggers.LoggerFactory; -var HttpConnection_1 = createCommonjsModule(function (module, exports) { -var __awaiter = (commonjsGlobal && commonjsGlobal.__awaiter) || function (thisArg, _arguments, P, generator) { +/***/ }), +/* 20 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ServerSentEventsTransport", function() { return ServerSentEventsTransport; }); +/* harmony import */ var _ILogger__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(8); +/* harmony import */ var _ITransport__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(17); +/* harmony import */ var _Utils__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(12); +// Copyright (c) .NET Foundation. All rights reserved. +// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. +var __awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } @@ -1791,15 +3656,15 @@ var __awaiter = (commonjsGlobal && commonjsGlobal.__awaiter) || function (thisAr step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; -var __generator = (commonjsGlobal && commonjsGlobal.__generator) || function (thisArg, body) { +var __generator = (undefined && undefined.__generator) || function (thisArg, body) { var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; function verb(n) { return function (v) { return step([n, v]); }; } function step(op) { if (f) throw new TypeError("Generator is already executing."); while (_) try { - if (f = 1, y && (t = y[op[0] & 2 ? "return" : op[0] ? "throw" : "next"]) && !(t = t.call(y, op[1])).done) return t; - if (y = 0, t) op = [0, t.value]; + 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; + if (y = 0, t) op = [op[0] & 2, t.value]; switch (op[0]) { case 0: case 1: t = op; break; case 4: _.label++; return { value: op[1], done: false }; @@ -1818,388 +3683,135 @@ var __generator = (commonjsGlobal && commonjsGlobal.__generator) || function (th if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } }; -Object.defineProperty(exports, "__esModule", { value: true }); - -var HttpConnection = /** @class */ (function () { - function HttpConnection(url, options) { - if (options === void 0) { options = {}; } - this.features = {}; - this.logger = Loggers.LoggerFactory.createLogger(options.logger); - this.baseUrl = this.resolveUrl(url); - options = options || {}; - options.accessTokenFactory = options.accessTokenFactory || (function () { return null; }); - this.httpClient = options.httpClient || new HttpClient_1.DefaultHttpClient(); - this.connectionState = 2 /* Disconnected */; - this.options = options; +/** @private */ +var ServerSentEventsTransport = /** @class */ (function () { + function ServerSentEventsTransport(httpClient, accessTokenFactory, logger, logMessageContent, eventSourceConstructor) { + this.httpClient = httpClient; + this.accessTokenFactory = accessTokenFactory; + this.logger = logger; + this.logMessageContent = logMessageContent; + this.eventSourceConstructor = eventSourceConstructor; + this.onreceive = null; + this.onclose = null; } - HttpConnection.prototype.start = function () { - return __awaiter(this, void 0, void 0, function () { - return __generator(this, function (_a) { - if (this.connectionState !== 2 /* Disconnected */) { - return [2 /*return*/, Promise.reject(new Error("Cannot start a connection that is not in the 'Disconnected' state."))]; - } - this.connectionState = 0 /* Connecting */; - this.startPromise = this.startInternal(); - return [2 /*return*/, this.startPromise]; - }); - }); - }; - HttpConnection.prototype.startInternal = function () { + ServerSentEventsTransport.prototype.connect = function (url, transferFormat) { return __awaiter(this, void 0, void 0, function () { + var token; var _this = this; - var headers, token, negotiatePayload, negotiateResponse, requestedTransferMode, _a, e_1; - return __generator(this, function (_b) { - switch (_b.label) { - case 0: - _b.trys.push([0, 5, , 6]); - if (!(this.options.transport === Transports.TransportType.WebSockets)) return [3 /*break*/, 1]; - // No need to add a connection ID in this case - this.url = this.baseUrl; - this.transport = this.createTransport(this.options.transport, [Transports.TransportType[Transports.TransportType.WebSockets]]); - return [3 /*break*/, 3]; - case 1: - headers = void 0; - token = this.options.accessTokenFactory(); - if (token) { - headers = new Map(); - headers.set("Authorization", "Bearer " + token); - } - return [4 /*yield*/, this.httpClient.post(this.resolveNegotiateUrl(this.baseUrl), { - content: "", - headers: headers - })]; - case 2: - negotiatePayload = _b.sent(); - negotiateResponse = JSON.parse(negotiatePayload.content); - this.connectionId = negotiateResponse.connectionId; - // the user tries to stop the the connection when it is being started - if (this.connectionState == 2 /* Disconnected */) { - return [2 /*return*/]; - } - if (this.connectionId) { - this.url = this.baseUrl + (this.baseUrl.indexOf("?") === -1 ? "?" : "&") + ("id=" + this.connectionId); - this.transport = this.createTransport(this.options.transport, negotiateResponse.availableTransports); - } - _b.label = 3; - case 3: - this.transport.onreceive = this.onreceive; - this.transport.onclose = function (e) { return _this.stopConnection(true, e); }; - requestedTransferMode = this.features.transferMode === 2 /* Binary */ - ? 2 /* Binary */ - : 1 /* Text */; - _a = this.features; - return [4 /*yield*/, this.transport.connect(this.url, requestedTransferMode, this)]; - case 4: - _a.transferMode = _b.sent(); - // only change the state if we were connecting to not overwrite - // the state if the connection is already marked as Disconnected - this.changeState(0 /* Connecting */, 1 /* Connected */); - return [3 /*break*/, 6]; - case 5: - e_1 = _b.sent(); - this.logger.log(ILogger.LogLevel.Error, "Failed to start the connection. " + e_1); - this.connectionState = 2 /* Disconnected */; - this.transport = null; - throw e_1; - case 6: - ; - return [2 /*return*/]; - } - }); - }); - }; - HttpConnection.prototype.createTransport = function (transport, availableTransports) { - if ((transport === null || transport === undefined) && availableTransports.length > 0) { - transport = Transports.TransportType[availableTransports[0]]; - } - if (transport === Transports.TransportType.WebSockets && availableTransports.indexOf(Transports.TransportType[transport]) >= 0) { - return new Transports.WebSocketTransport(this.options.accessTokenFactory, this.logger); - } - if (transport === Transports.TransportType.ServerSentEvents && availableTransports.indexOf(Transports.TransportType[transport]) >= 0) { - return new Transports.ServerSentEventsTransport(this.httpClient, this.options.accessTokenFactory, this.logger); - } - if (transport === Transports.TransportType.LongPolling && availableTransports.indexOf(Transports.TransportType[transport]) >= 0) { - return new Transports.LongPollingTransport(this.httpClient, this.options.accessTokenFactory, this.logger); - } - if (this.isITransport(transport)) { - return transport; - } - throw new Error("No available transports found."); - }; - HttpConnection.prototype.isITransport = function (transport) { - return typeof (transport) === "object" && "connect" in transport; - }; - HttpConnection.prototype.changeState = function (from, to) { - if (this.connectionState == from) { - this.connectionState = to; - return true; - } - return false; - }; - HttpConnection.prototype.send = function (data) { - if (this.connectionState != 1 /* Connected */) { - throw new Error("Cannot send data if the connection is not in the 'Connected' State"); - } - return this.transport.send(data); - }; - HttpConnection.prototype.stop = function (error) { - return __awaiter(this, void 0, void 0, function () { - var previousState, e_2; return __generator(this, function (_a) { switch (_a.label) { case 0: - previousState = this.connectionState; - this.connectionState = 2 /* Disconnected */; - _a.label = 1; + _Utils__WEBPACK_IMPORTED_MODULE_2__["Arg"].isRequired(url, "url"); + _Utils__WEBPACK_IMPORTED_MODULE_2__["Arg"].isRequired(transferFormat, "transferFormat"); + _Utils__WEBPACK_IMPORTED_MODULE_2__["Arg"].isIn(transferFormat, _ITransport__WEBPACK_IMPORTED_MODULE_1__["TransferFormat"], "transferFormat"); + this.logger.log(_ILogger__WEBPACK_IMPORTED_MODULE_0__["LogLevel"].Trace, "(SSE transport) Connecting."); + // set url before accessTokenFactory because this.url is only for send and we set the auth header instead of the query string for send + this.url = url; + if (!this.accessTokenFactory) return [3 /*break*/, 2]; + return [4 /*yield*/, this.accessTokenFactory()]; case 1: - _a.trys.push([1, 3, , 4]); - return [4 /*yield*/, this.startPromise]; - case 2: - _a.sent(); - return [3 /*break*/, 4]; - case 3: - e_2 = _a.sent(); - return [3 /*break*/, 4]; - case 4: - this.stopConnection(/*raiseClosed*/ previousState == 1 /* Connected */, error); - return [2 /*return*/]; + token = _a.sent(); + if (token) { + url += (url.indexOf("?") < 0 ? "?" : "&") + ("access_token=" + encodeURIComponent(token)); + } + _a.label = 2; + case 2: return [2 /*return*/, new Promise(function (resolve, reject) { + var opened = false; + if (transferFormat !== _ITransport__WEBPACK_IMPORTED_MODULE_1__["TransferFormat"].Text) { + reject(new Error("The Server-Sent Events transport only supports the 'Text' transfer format")); + return; + } + var eventSource; + if (typeof window !== "undefined") { + eventSource = new _this.eventSourceConstructor(url, { withCredentials: true }); + } + else { + // Non-browser passes cookies via the dictionary + var cookies = _this.httpClient.getCookieString(url); + eventSource = new _this.eventSourceConstructor(url, { withCredentials: true, headers: { Cookie: cookies } }); + } + try { + eventSource.onmessage = function (e) { + if (_this.onreceive) { + try { + _this.logger.log(_ILogger__WEBPACK_IMPORTED_MODULE_0__["LogLevel"].Trace, "(SSE transport) data received. " + Object(_Utils__WEBPACK_IMPORTED_MODULE_2__["getDataDetail"])(e.data, _this.logMessageContent) + "."); + _this.onreceive(e.data); + } + catch (error) { + _this.close(error); + return; + } + } + }; + eventSource.onerror = function (e) { + var error = new Error(e.data || "Error occurred"); + if (opened) { + _this.close(error); + } + else { + reject(error); + } + }; + eventSource.onopen = function () { + _this.logger.log(_ILogger__WEBPACK_IMPORTED_MODULE_0__["LogLevel"].Information, "SSE connected to " + _this.url); + _this.eventSource = eventSource; + opened = true; + resolve(); + }; + } + catch (e) { + reject(e); + return; + } + })]; } }); }); }; - HttpConnection.prototype.stopConnection = function (raiseClosed, error) { - if (this.transport) { - this.transport.stop(); - this.transport = null; - } - if (error) { - this.logger.log(ILogger.LogLevel.Error, "Connection disconnected with error '" + error + "'."); - } - else { - this.logger.log(ILogger.LogLevel.Information, "Connection disconnected."); - } - this.connectionState = 2 /* Disconnected */; - if (raiseClosed && this.onclose) { - this.onclose(error); - } - }; - HttpConnection.prototype.resolveUrl = function (url) { - // startsWith is not supported in IE - if (url.lastIndexOf("https://", 0) === 0 || url.lastIndexOf("http://", 0) === 0) { - return url; - } - if (typeof window === 'undefined' || !window || !window.document) { - throw new Error("Cannot resolve '" + url + "'."); - } - var parser = window.document.createElement("a"); - parser.href = url; - var baseUrl = (!parser.protocol || parser.protocol === ":") - ? window.document.location.protocol + "//" + (parser.host || window.document.location.host) - : parser.protocol + "//" + parser.host; - if (!url || url[0] != '/') { - url = '/' + url; - } - var normalizedUrl = baseUrl + url; - this.logger.log(ILogger.LogLevel.Information, "Normalizing '" + url + "' to '" + normalizedUrl + "'"); - return normalizedUrl; - }; - HttpConnection.prototype.resolveNegotiateUrl = function (url) { - var index = url.indexOf("?"); - var negotiateUrl = url.substring(0, index === -1 ? url.length : index); - if (negotiateUrl[negotiateUrl.length - 1] !== "/") { - negotiateUrl += "/"; - } - negotiateUrl += "negotiate"; - negotiateUrl += index === -1 ? "" : url.substring(index); - return negotiateUrl; - }; - return HttpConnection; -}()); -exports.HttpConnection = HttpConnection; - -}); - -unwrapExports(HttpConnection_1); -var HttpConnection_2 = HttpConnection_1.HttpConnection; - -var Observable = createCommonjsModule(function (module, exports) { -Object.defineProperty(exports, "__esModule", { value: true }); -var Subscription = /** @class */ (function () { - function Subscription(subject, observer) { - this.subject = subject; - this.observer = observer; - } - Subscription.prototype.dispose = function () { - var index = this.subject.observers.indexOf(this.observer); - if (index > -1) { - this.subject.observers.splice(index, 1); - } - if (this.subject.observers.length === 0) { - this.subject.cancelCallback().catch(function (_) { }); - } - }; - return Subscription; -}()); -exports.Subscription = Subscription; -var Subject = /** @class */ (function () { - function Subject(cancelCallback) { - this.observers = []; - this.cancelCallback = cancelCallback; - } - Subject.prototype.next = function (item) { - for (var _i = 0, _a = this.observers; _i < _a.length; _i++) { - var observer = _a[_i]; - observer.next(item); - } - }; - Subject.prototype.error = function (err) { - for (var _i = 0, _a = this.observers; _i < _a.length; _i++) { - var observer = _a[_i]; - if (observer.error) { - observer.error(err); - } - } - }; - Subject.prototype.complete = function () { - for (var _i = 0, _a = this.observers; _i < _a.length; _i++) { - var observer = _a[_i]; - if (observer.complete) { - observer.complete(); - } - } - }; - Subject.prototype.subscribe = function (observer) { - this.observers.push(observer); - return new Subscription(this, observer); - }; - return Subject; -}()); -exports.Subject = Subject; - -}); - -unwrapExports(Observable); -var Observable_1 = Observable.Subscription; -var Observable_2 = Observable.Subject; - -var TextMessageFormat_1 = createCommonjsModule(function (module, exports) { -Object.defineProperty(exports, "__esModule", { value: true }); -var TextMessageFormat = /** @class */ (function () { - function TextMessageFormat() { - } - TextMessageFormat.write = function (output) { - return "" + output + TextMessageFormat.RecordSeparator; - }; - TextMessageFormat.parse = function (input) { - if (input[input.length - 1] != TextMessageFormat.RecordSeparator) { - throw new Error("Message is incomplete."); - } - var messages = input.split(TextMessageFormat.RecordSeparator); - messages.pop(); - return messages; - }; - TextMessageFormat.RecordSeparator = String.fromCharCode(0x1e); - return TextMessageFormat; -}()); -exports.TextMessageFormat = TextMessageFormat; - -}); - -unwrapExports(TextMessageFormat_1); -var TextMessageFormat_2 = TextMessageFormat_1.TextMessageFormat; - -var JsonHubProtocol_1 = createCommonjsModule(function (module, exports) { -Object.defineProperty(exports, "__esModule", { value: true }); - -exports.JSON_HUB_PROTOCOL_NAME = "json"; -var JsonHubProtocol = /** @class */ (function () { - function JsonHubProtocol() { - this.name = exports.JSON_HUB_PROTOCOL_NAME; - this.type = 1 /* Text */; - } - JsonHubProtocol.prototype.parseMessages = function (input) { - if (!input) { - return []; - } - // Parse the messages - var messages = TextMessageFormat_1.TextMessageFormat.parse(input); - var hubMessages = []; - for (var i = 0; i < messages.length; ++i) { - hubMessages.push(JSON.parse(messages[i])); - } - return hubMessages; + ServerSentEventsTransport.prototype.send = function (data) { + return __awaiter(this, void 0, void 0, function () { + return __generator(this, function (_a) { + if (!this.eventSource) { + return [2 /*return*/, Promise.reject(new Error("Cannot send until the transport is connected"))]; + } + return [2 /*return*/, Object(_Utils__WEBPACK_IMPORTED_MODULE_2__["sendMessage"])(this.logger, "SSE", this.httpClient, this.url, this.accessTokenFactory, data, this.logMessageContent)]; + }); + }); }; - JsonHubProtocol.prototype.writeMessage = function (message) { - return TextMessageFormat_1.TextMessageFormat.write(JSON.stringify(message)); + ServerSentEventsTransport.prototype.stop = function () { + this.close(); + return Promise.resolve(); }; - return JsonHubProtocol; + ServerSentEventsTransport.prototype.close = function (e) { + if (this.eventSource) { + this.eventSource.close(); + this.eventSource = undefined; + if (this.onclose) { + this.onclose(e); + } + } + }; + return ServerSentEventsTransport; }()); -exports.JsonHubProtocol = JsonHubProtocol; -}); - -unwrapExports(JsonHubProtocol_1); -var JsonHubProtocol_2 = JsonHubProtocol_1.JSON_HUB_PROTOCOL_NAME; -var JsonHubProtocol_3 = JsonHubProtocol_1.JsonHubProtocol; - -var Base64EncodedHubProtocol_1 = createCommonjsModule(function (module, exports) { -Object.defineProperty(exports, "__esModule", { value: true }); -var Base64EncodedHubProtocol = /** @class */ (function () { - function Base64EncodedHubProtocol(protocol) { - this.wrappedProtocol = protocol; - this.name = this.wrappedProtocol.name; - this.type = 1 /* Text */; - } - Base64EncodedHubProtocol.prototype.parseMessages = function (input) { - // The format of the message is `size:message;` - var pos = input.indexOf(":"); - if (pos == -1 || input[input.length - 1] != ';') { - throw new Error("Invalid payload."); - } - var lenStr = input.substring(0, pos); - if (!/^[0-9]+$/.test(lenStr)) { - throw new Error("Invalid length: '" + lenStr + "'"); - } - var messageSize = parseInt(lenStr, 10); - // 2 accounts for ':' after message size and trailing ';' - if (messageSize != input.length - pos - 2) { - throw new Error("Invalid message size."); - } - var encodedMessage = input.substring(pos + 1, input.length - 1); - // atob/btoa are browsers APIs but they can be polyfilled. If this becomes problematic we can use - // base64-js module - var s = atob(encodedMessage); - var payload = new Uint8Array(s.length); - for (var i = 0; i < payload.length; i++) { - payload[i] = s.charCodeAt(i); - } - return this.wrappedProtocol.parseMessages(payload.buffer); - }; - Base64EncodedHubProtocol.prototype.writeMessage = function (message) { - var payload = new Uint8Array(this.wrappedProtocol.writeMessage(message)); - var s = ""; - for (var i = 0; i < payload.byteLength; i++) { - s += String.fromCharCode(payload[i]); - } - // atob/btoa are browsers APIs but they can be polyfilled. If this becomes problematic we can use - // base64-js module - var encodedMessage = btoa(s); - return encodedMessage.length.toString() + ":" + encodedMessage + ";"; - }; - return Base64EncodedHubProtocol; -}()); -exports.Base64EncodedHubProtocol = Base64EncodedHubProtocol; -}); -unwrapExports(Base64EncodedHubProtocol_1); -var Base64EncodedHubProtocol_2 = Base64EncodedHubProtocol_1.Base64EncodedHubProtocol; +/***/ }), +/* 21 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { -var HubConnection_1 = createCommonjsModule(function (module, exports) { -var __awaiter = (commonjsGlobal && commonjsGlobal.__awaiter) || function (thisArg, _arguments, P, generator) { +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "WebSocketTransport", function() { return WebSocketTransport; }); +/* harmony import */ var _ILogger__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(8); +/* harmony import */ var _ITransport__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(17); +/* harmony import */ var _Utils__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(12); +// Copyright (c) .NET Foundation. All rights reserved. +// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. +var __awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } @@ -2207,15 +3819,15 @@ var __awaiter = (commonjsGlobal && commonjsGlobal.__awaiter) || function (thisAr step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; -var __generator = (commonjsGlobal && commonjsGlobal.__generator) || function (thisArg, body) { +var __generator = (undefined && undefined.__generator) || function (thisArg, body) { var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; function verb(n) { return function (v) { return step([n, v]); }; } function step(op) { if (f) throw new TypeError("Generator is already executing."); while (_) try { - if (f = 1, y && (t = y[op[0] & 2 ? "return" : op[0] ? "throw" : "next"]) && !(t = t.call(y, op[1])).done) return t; - if (y = 0, t) op = [0, t.value]; + 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; + if (y = 0, t) op = [op[0] & 2, t.value]; switch (op[0]) { case 0: case 1: t = op; break; case 4: _.label++; return { value: op[1], done: false }; @@ -2234,339 +3846,243 @@ var __generator = (commonjsGlobal && commonjsGlobal.__generator) || function (th if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } }; -Object.defineProperty(exports, "__esModule", { value: true }); - - - -exports.JsonHubProtocol = JsonHubProtocol_1.JsonHubProtocol; - -var DEFAULT_TIMEOUT_IN_MS = 30 * 1000; -var HubConnection = /** @class */ (function () { - function HubConnection(urlOrConnection, options) { - if (options === void 0) { options = {}; } - var _this = this; - options = options || {}; - this.timeoutInMilliseconds = options.timeoutInMilliseconds || DEFAULT_TIMEOUT_IN_MS; - if (typeof urlOrConnection === "string") { - this.connection = new HttpConnection_1.HttpConnection(urlOrConnection, options); - } - else { - this.connection = urlOrConnection; - } - this.logger = Loggers.LoggerFactory.createLogger(options.logger); - this.protocol = options.protocol || new JsonHubProtocol_1.JsonHubProtocol(); - this.connection.onreceive = function (data) { return _this.processIncomingData(data); }; - this.connection.onclose = function (error) { return _this.connectionClosed(error); }; - this.callbacks = new Map(); - this.methods = new Map(); - this.closedCallbacks = []; - this.id = 0; +/** @private */ +var WebSocketTransport = /** @class */ (function () { + function WebSocketTransport(httpClient, accessTokenFactory, logger, logMessageContent, webSocketConstructor) { + this.logger = logger; + this.accessTokenFactory = accessTokenFactory; + this.logMessageContent = logMessageContent; + this.webSocketConstructor = webSocketConstructor; + this.httpClient = httpClient; + this.onreceive = null; + this.onclose = null; } - HubConnection.prototype.processIncomingData = function (data) { - if (this.timeoutHandle !== undefined) { - clearTimeout(this.timeoutHandle); - } - // Parse the messages - var messages = this.protocol.parseMessages(data); - for (var i = 0; i < messages.length; ++i) { - var message = messages[i]; - switch (message.type) { - case 1 /* Invocation */: - this.invokeClientMethod(message); - break; - case 2 /* StreamItem */: - case 3 /* Completion */: - var callback = this.callbacks.get(message.invocationId); - if (callback != null) { - if (message.type === 3 /* Completion */) { - this.callbacks.delete(message.invocationId); - } - callback(message); - } - break; - case 6 /* Ping */: - // Don't care about pings - break; - default: - this.logger.log(ILogger.LogLevel.Warning, "Invalid message type: " + data); - break; - } - } - this.configureTimeout(); - }; - HubConnection.prototype.configureTimeout = function () { - var _this = this; - if (!this.connection.features || !this.connection.features.inherentKeepAlive) { - // Set the timeout timer - this.timeoutHandle = setTimeout(function () { return _this.serverTimeout(); }, this.timeoutInMilliseconds); - } - }; - HubConnection.prototype.serverTimeout = function () { - // The server hasn't talked to us in a while. It doesn't like us anymore ... :( - // Terminate the connection - this.connection.stop(new Error("Server timeout elapsed without receiving a message from the server.")); - }; - HubConnection.prototype.invokeClientMethod = function (invocationMessage) { - var _this = this; - var methods = this.methods.get(invocationMessage.target.toLowerCase()); - if (methods) { - methods.forEach(function (m) { return m.apply(_this, invocationMessage.arguments); }); - if (invocationMessage.invocationId) { - // This is not supported in v1. So we return an error to avoid blocking the server waiting for the response. - var message = "Server requested a response, which is not supported in this version of the client."; - this.logger.log(ILogger.LogLevel.Error, message); - this.connection.stop(new Error(message)); - } - } - else { - this.logger.log(ILogger.LogLevel.Warning, "No client method with the name '" + invocationMessage.target + "' found."); - } - }; - HubConnection.prototype.connectionClosed = function (error) { - var _this = this; - this.callbacks.forEach(function (callback) { - callback(undefined, error ? error : new Error("Invocation canceled due to connection being closed.")); - }); - this.callbacks.clear(); - this.closedCallbacks.forEach(function (c) { return c.apply(_this, [error]); }); - this.cleanupTimeout(); - }; - HubConnection.prototype.start = function () { + WebSocketTransport.prototype.connect = function (url, transferFormat) { return __awaiter(this, void 0, void 0, function () { - var requestedTransferMode, actualTransferMode; + var token; + var _this = this; return __generator(this, function (_a) { switch (_a.label) { case 0: - requestedTransferMode = (this.protocol.type === 2 /* Binary */) - ? 2 /* Binary */ - : 1 /* Text */; - this.connection.features.transferMode = requestedTransferMode; - return [4 /*yield*/, this.connection.start()]; + _Utils__WEBPACK_IMPORTED_MODULE_2__["Arg"].isRequired(url, "url"); + _Utils__WEBPACK_IMPORTED_MODULE_2__["Arg"].isRequired(transferFormat, "transferFormat"); + _Utils__WEBPACK_IMPORTED_MODULE_2__["Arg"].isIn(transferFormat, _ITransport__WEBPACK_IMPORTED_MODULE_1__["TransferFormat"], "transferFormat"); + this.logger.log(_ILogger__WEBPACK_IMPORTED_MODULE_0__["LogLevel"].Trace, "(WebSockets transport) Connecting."); + if (!this.accessTokenFactory) return [3 /*break*/, 2]; + return [4 /*yield*/, this.accessTokenFactory()]; case 1: - _a.sent(); - actualTransferMode = this.connection.features.transferMode; - return [4 /*yield*/, this.connection.send(TextMessageFormat_1.TextMessageFormat.write(JSON.stringify({ protocol: this.protocol.name })))]; - case 2: - _a.sent(); - this.logger.log(ILogger.LogLevel.Information, "Using HubProtocol '" + this.protocol.name + "'."); - if (requestedTransferMode === 2 /* Binary */ && actualTransferMode === 1 /* Text */) { - this.protocol = new Base64EncodedHubProtocol_1.Base64EncodedHubProtocol(this.protocol); + token = _a.sent(); + if (token) { + url += (url.indexOf("?") < 0 ? "?" : "&") + ("access_token=" + encodeURIComponent(token)); } - this.configureTimeout(); - return [2 /*return*/]; + _a.label = 2; + case 2: return [2 /*return*/, new Promise(function (resolve, reject) { + url = url.replace(/^http/, "ws"); + var webSocket; + var cookies = _this.httpClient.getCookieString(url); + if (typeof window === "undefined" && cookies) { + // Only pass cookies when in non-browser environments + webSocket = new _this.webSocketConstructor(url, undefined, { + headers: { + Cookie: "" + cookies, + }, + }); + } + if (!webSocket) { + // Chrome is not happy with passing 'undefined' as protocol + webSocket = new _this.webSocketConstructor(url); + } + if (transferFormat === _ITransport__WEBPACK_IMPORTED_MODULE_1__["TransferFormat"].Binary) { + webSocket.binaryType = "arraybuffer"; + } + // tslint:disable-next-line:variable-name + webSocket.onopen = function (_event) { + _this.logger.log(_ILogger__WEBPACK_IMPORTED_MODULE_0__["LogLevel"].Information, "WebSocket connected to " + url + "."); + _this.webSocket = webSocket; + resolve(); + }; + webSocket.onerror = function (event) { + var error = null; + // ErrorEvent is a browser only type we need to check if the type exists before using it + if (typeof ErrorEvent !== "undefined" && event instanceof ErrorEvent) { + error = event.error; + } + reject(error); + }; + webSocket.onmessage = function (message) { + _this.logger.log(_ILogger__WEBPACK_IMPORTED_MODULE_0__["LogLevel"].Trace, "(WebSockets transport) data received. " + Object(_Utils__WEBPACK_IMPORTED_MODULE_2__["getDataDetail"])(message.data, _this.logMessageContent) + "."); + if (_this.onreceive) { + _this.onreceive(message.data); + } + }; + webSocket.onclose = function (event) { return _this.close(event); }; + })]; } }); }); }; - HubConnection.prototype.stop = function () { - this.cleanupTimeout(); - return this.connection.stop(); + WebSocketTransport.prototype.send = function (data) { + if (this.webSocket && this.webSocket.readyState === this.webSocketConstructor.OPEN) { + this.logger.log(_ILogger__WEBPACK_IMPORTED_MODULE_0__["LogLevel"].Trace, "(WebSockets transport) sending data. " + Object(_Utils__WEBPACK_IMPORTED_MODULE_2__["getDataDetail"])(data, this.logMessageContent) + "."); + this.webSocket.send(data); + return Promise.resolve(); + } + return Promise.reject("WebSocket is not in the OPEN state"); }; - HubConnection.prototype.stream = function (methodName) { - var _this = this; - var args = []; - for (var _i = 1; _i < arguments.length; _i++) { - args[_i - 1] = arguments[_i]; + WebSocketTransport.prototype.stop = function () { + if (this.webSocket) { + // Clear websocket handlers because we are considering the socket closed now + this.webSocket.onclose = function () { }; + this.webSocket.onmessage = function () { }; + this.webSocket.onerror = function () { }; + this.webSocket.close(); + this.webSocket = undefined; + // Manually invoke onclose callback inline so we know the HttpConnection was closed properly before returning + // This also solves an issue where websocket.onclose could take 18+ seconds to trigger during network disconnects + this.close(undefined); } - var invocationDescriptor = this.createStreamInvocation(methodName, args); - var subject = new Observable.Subject(function () { - var cancelInvocation = _this.createCancelInvocation(invocationDescriptor.invocationId); - var message = _this.protocol.writeMessage(cancelInvocation); - _this.callbacks.delete(invocationDescriptor.invocationId); - return _this.connection.send(message); - }); - this.callbacks.set(invocationDescriptor.invocationId, function (invocationEvent, error) { - if (error) { - subject.error(error); - return; - } - if (invocationEvent.type === 3 /* Completion */) { - var completionMessage = invocationEvent; - if (completionMessage.error) { - subject.error(new Error(completionMessage.error)); - } - else { - subject.complete(); - } + return Promise.resolve(); + }; + WebSocketTransport.prototype.close = function (event) { + // webSocket will be null if the transport did not start successfully + this.logger.log(_ILogger__WEBPACK_IMPORTED_MODULE_0__["LogLevel"].Trace, "(WebSockets transport) socket closed."); + if (this.onclose) { + if (event && (event.wasClean === false || event.code !== 1000)) { + this.onclose(new Error("WebSocket closed with status code: " + event.code + " (" + event.reason + ").")); } else { - subject.next(invocationEvent.item); + this.onclose(); } - }); - var message = this.protocol.writeMessage(invocationDescriptor); - this.connection.send(message) - .catch(function (e) { - subject.error(e); - _this.callbacks.delete(invocationDescriptor.invocationId); - }); - return subject; - }; - HubConnection.prototype.send = function (methodName) { - var args = []; - for (var _i = 1; _i < arguments.length; _i++) { - args[_i - 1] = arguments[_i]; - } - var invocationDescriptor = this.createInvocation(methodName, args, true); - var message = this.protocol.writeMessage(invocationDescriptor); - return this.connection.send(message); - }; - HubConnection.prototype.invoke = function (methodName) { - var _this = this; - var args = []; - for (var _i = 1; _i < arguments.length; _i++) { - args[_i - 1] = arguments[_i]; } - var invocationDescriptor = this.createInvocation(methodName, args, false); - var p = new Promise(function (resolve, reject) { - _this.callbacks.set(invocationDescriptor.invocationId, function (invocationEvent, error) { - if (error) { - reject(error); - return; - } - if (invocationEvent.type === 3 /* Completion */) { - var completionMessage = invocationEvent; - if (completionMessage.error) { - reject(new Error(completionMessage.error)); - } - else { - resolve(completionMessage.result); - } - } - else { - reject(new Error("Unexpected message type: " + invocationEvent.type)); - } - }); - var message = _this.protocol.writeMessage(invocationDescriptor); - _this.connection.send(message) - .catch(function (e) { - reject(e); - _this.callbacks.delete(invocationDescriptor.invocationId); - }); - }); - return p; }; - HubConnection.prototype.on = function (methodName, method) { - if (!methodName || !method) { - return; - } - methodName = methodName.toLowerCase(); - if (!this.methods.has(methodName)) { - this.methods.set(methodName, []); + return WebSocketTransport; +}()); + + + +/***/ }), +/* 22 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "JsonHubProtocol", function() { return JsonHubProtocol; }); +/* harmony import */ var _IHubProtocol__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(14); +/* harmony import */ var _ILogger__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(8); +/* harmony import */ var _ITransport__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(17); +/* harmony import */ var _Loggers__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(13); +/* harmony import */ var _TextMessageFormat__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(11); +// Copyright (c) .NET Foundation. All rights reserved. +// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. + + + + + +var JSON_HUB_PROTOCOL_NAME = "json"; +/** Implements the JSON Hub Protocol. */ +var JsonHubProtocol = /** @class */ (function () { + function JsonHubProtocol() { + /** @inheritDoc */ + this.name = JSON_HUB_PROTOCOL_NAME; + /** @inheritDoc */ + this.version = 1; + /** @inheritDoc */ + this.transferFormat = _ITransport__WEBPACK_IMPORTED_MODULE_2__["TransferFormat"].Text; + } + /** Creates an array of {@link @aspnet/signalr.HubMessage} objects from the specified serialized representation. + * + * @param {string} input A string containing the serialized representation. + * @param {ILogger} logger A logger that will be used to log messages that occur during parsing. + */ + JsonHubProtocol.prototype.parseMessages = function (input, logger) { + // The interface does allow "ArrayBuffer" to be passed in, but this implementation does not. So let's throw a useful error. + if (typeof input !== "string") { + throw new Error("Invalid input for JSON hub protocol. Expected a string."); } - this.methods.get(methodName).push(method); - }; - HubConnection.prototype.off = function (methodName, method) { - if (!methodName || !method) { - return; + if (!input) { + return []; } - methodName = methodName.toLowerCase(); - var handlers = this.methods.get(methodName); - if (!handlers) { - return; + if (logger === null) { + logger = _Loggers__WEBPACK_IMPORTED_MODULE_3__["NullLogger"].instance; } - var removeIdx = handlers.indexOf(method); - if (removeIdx != -1) { - handlers.splice(removeIdx, 1); + // Parse the messages + var messages = _TextMessageFormat__WEBPACK_IMPORTED_MODULE_4__["TextMessageFormat"].parse(input); + var hubMessages = []; + for (var _i = 0, messages_1 = messages; _i < messages_1.length; _i++) { + var message = messages_1[_i]; + var parsedMessage = JSON.parse(message); + if (typeof parsedMessage.type !== "number") { + throw new Error("Invalid payload."); + } + switch (parsedMessage.type) { + case _IHubProtocol__WEBPACK_IMPORTED_MODULE_0__["MessageType"].Invocation: + this.isInvocationMessage(parsedMessage); + break; + case _IHubProtocol__WEBPACK_IMPORTED_MODULE_0__["MessageType"].StreamItem: + this.isStreamItemMessage(parsedMessage); + break; + case _IHubProtocol__WEBPACK_IMPORTED_MODULE_0__["MessageType"].Completion: + this.isCompletionMessage(parsedMessage); + break; + case _IHubProtocol__WEBPACK_IMPORTED_MODULE_0__["MessageType"].Ping: + // Single value, no need to validate + break; + case _IHubProtocol__WEBPACK_IMPORTED_MODULE_0__["MessageType"].Close: + // All optional values, no need to validate + break; + default: + // Future protocol changes can add message types, old clients can ignore them + logger.log(_ILogger__WEBPACK_IMPORTED_MODULE_1__["LogLevel"].Information, "Unknown message type '" + parsedMessage.type + "' ignored."); + continue; + } + hubMessages.push(parsedMessage); } + return hubMessages; }; - HubConnection.prototype.onclose = function (callback) { - if (callback) { - this.closedCallbacks.push(callback); + /** Writes the specified {@link @aspnet/signalr.HubMessage} to a string and returns it. + * + * @param {HubMessage} message The message to write. + * @returns {string} A string containing the serialized representation of the message. + */ + JsonHubProtocol.prototype.writeMessage = function (message) { + return _TextMessageFormat__WEBPACK_IMPORTED_MODULE_4__["TextMessageFormat"].write(JSON.stringify(message)); + }; + JsonHubProtocol.prototype.isInvocationMessage = function (message) { + this.assertNotEmptyString(message.target, "Invalid payload for Invocation message."); + if (message.invocationId !== undefined) { + this.assertNotEmptyString(message.invocationId, "Invalid payload for Invocation message."); } }; - HubConnection.prototype.cleanupTimeout = function () { - if (this.timeoutHandle) { - clearTimeout(this.timeoutHandle); + JsonHubProtocol.prototype.isStreamItemMessage = function (message) { + this.assertNotEmptyString(message.invocationId, "Invalid payload for StreamItem message."); + if (message.item === undefined) { + throw new Error("Invalid payload for StreamItem message."); } }; - HubConnection.prototype.createInvocation = function (methodName, args, nonblocking) { - if (nonblocking) { - return { - type: 1 /* Invocation */, - target: methodName, - arguments: args, - }; + JsonHubProtocol.prototype.isCompletionMessage = function (message) { + if (message.result && message.error) { + throw new Error("Invalid payload for Completion message."); } - else { - var id = this.id; - this.id++; - return { - type: 1 /* Invocation */, - invocationId: id.toString(), - target: methodName, - arguments: args, - }; + if (!message.result && message.error) { + this.assertNotEmptyString(message.error, "Invalid payload for Completion message."); } + this.assertNotEmptyString(message.invocationId, "Invalid payload for Completion message."); }; - HubConnection.prototype.createStreamInvocation = function (methodName, args) { - var id = this.id; - this.id++; - return { - type: 4 /* StreamInvocation */, - invocationId: id.toString(), - target: methodName, - arguments: args, - }; - }; - HubConnection.prototype.createCancelInvocation = function (id) { - return { - type: 5 /* CancelInvocation */, - invocationId: id, - }; + JsonHubProtocol.prototype.assertNotEmptyString = function (value, errorMessage) { + if (typeof value !== "string" || value === "") { + throw new Error(errorMessage); + } }; - return HubConnection; + return JsonHubProtocol; }()); -exports.HubConnection = HubConnection; - -}); -unwrapExports(HubConnection_1); -var HubConnection_2 = HubConnection_1.JsonHubProtocol; -var HubConnection_3 = HubConnection_1.HubConnection; -var IHubProtocol = createCommonjsModule(function (module, exports) { -Object.defineProperty(exports, "__esModule", { value: true }); +/***/ }) +/******/ ]); }); - -unwrapExports(IHubProtocol); - -var cjs = createCommonjsModule(function (module, exports) { -function __export(m) { - for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p]; -} -Object.defineProperty(exports, "__esModule", { value: true }); -__export(Errors); -__export(HttpClient_1); -__export(HttpConnection_1); -__export(HubConnection_1); -__export(IHubProtocol); -__export(ILogger); -__export(Loggers); -__export(Transports); -__export(Observable); - -}); - -unwrapExports(cjs); - -var browserIndex = createCommonjsModule(function (module, exports) { -function __export(m) { - for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p]; -} -Object.defineProperty(exports, "__esModule", { value: true }); -// This is where we add any polyfills we'll need for the browser. It is the entry module for browser-specific builds. - -__export(cjs); - -}); - -var browserIndex$1 = unwrapExports(browserIndex); - -return browserIndex$1; - -}))); -//# sourceMappingURL=signalr.js.map +//# sourceMappingURL=signalr.js.map \ No newline at end of file diff --git a/src/WebCrawler.Web/wwwroot/lib/signalr/signalr.js.map b/src/WebCrawler.Web/wwwroot/lib/signalr/signalr.js.map new file mode 100644 index 0000000..c01bdb8 --- /dev/null +++ b/src/WebCrawler.Web/wwwroot/lib/signalr/signalr.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["webpack://signalR/webpack/universalModuleDefinition","webpack://signalR/webpack/bootstrap","webpack://signalR/src/browser-index.ts","webpack://signalR/node_modules/es6-promise/dist/es6-promise.auto.js","webpack://signalR/common/node_modules/webpack/buildin/global.js","webpack://signalR/src/index.ts","webpack://signalR/src/Errors.ts","webpack://signalR/src/HttpClient.ts","webpack://signalR/src/DefaultHttpClient.ts","webpack://signalR/src/XhrHttpClient.ts","webpack://signalR/src/ILogger.ts","webpack://signalR/src/HubConnection.ts","webpack://signalR/src/HandshakeProtocol.ts","webpack://signalR/src/TextMessageFormat.ts","webpack://signalR/src/Utils.ts","webpack://signalR/src/Loggers.ts","webpack://signalR/src/IHubProtocol.ts","webpack://signalR/src/HubConnectionBuilder.ts","webpack://signalR/src/HttpConnection.ts","webpack://signalR/src/ITransport.ts","webpack://signalR/src/LongPollingTransport.ts","webpack://signalR/src/AbortController.ts","webpack://signalR/src/ServerSentEventsTransport.ts","webpack://signalR/src/WebSocketTransport.ts","webpack://signalR/src/JsonHubProtocol.ts"],"names":[],"mappings":"AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,CAAC;AACD,O;ACVA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;;;AAGA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA,kDAA0C,gCAAgC;AAC1E;AACA;;AAEA;AACA;AACA;AACA,gEAAwD,kBAAkB;AAC1E;AACA,yDAAiD,cAAc;AAC/D;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,iDAAyC,iCAAiC;AAC1E,wHAAgH,mBAAmB,EAAE;AACrI;AACA;;AAEA;AACA;AACA;AACA,mCAA2B,0BAA0B,EAAE;AACvD,yCAAiC,eAAe;AAChD;AACA;AACA;;AAEA;AACA,8DAAsD,+DAA+D;;AAErH;AACA;;;AAGA;AACA;;;;;;;;;;;;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;AAEA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA,gFAAgF;;AAEhF;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA,0BAA0B,sBAAsB;;AAEhD;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,iBAAiB,SAAS;AAC1B;AACA;;AAEA;;AAEA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,GAAG;AACH;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA,CAAC;AACD;AACA,CAAC;AACD;AACA,CAAC;AACD;AACA,CAAC;AACD;AACA;;AAEA;AACA;;AAEA;;AAEA;AACA;AACA;;AAEA;;;AAGA;AACA;AACA;AACA;AACA,KAAK;AACL,GAAG;AACH;AACA;;AAEA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA,GAAG;;AAEH;AACA;AACA,GAAG;AACH;;AAEA;;AAEA;AACA;;AAEA;AACA;AACA,GAAG;AACH;;AAEA;AACA;AACA,UAAU,IAAI;AACd;AACA,WAAW,QAAQ;AACnB;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;;AAEA;;AAEA;AACA;AACA;;AAEA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA,GAAG;AACH;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,GAAG;AACH;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO;AACP;AACA;AACA,KAAK;AACL;AACA;AACA;AACA;;AAEA;AACA,KAAK;;AAEL;AACA;AACA;AACA;AACA,GAAG;AACH;;AAEA;AACA;AACA;AACA,GAAG;AACH;AACA,GAAG;AACH;AACA;AACA,KAAK;AACL;AACA,KAAK;AACL;AACA;;AAEA;AACA;AACA;AACA,GAAG;AACH;AACA;AACA;AACA,KAAK;AACL;AACA,KAAK;AACL;AACA,KAAK;AACL;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,GAAG;AACH;AACA,GAAG;AACH;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;;;AAGA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;;AAEA,iBAAiB,wBAAwB;AACzC;AACA;;AAEA;AACA;AACA,KAAK;AACL;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;;AAEA;;AAEA;AACA;AACA;AACA,GAAG;AACH;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA,KAAK;AACL;AACA;;AAEA;AACA;AACA;AACA;AACA,GAAG;AACH;AACA;AACA;;AAEA;AACA;AACA,GAAG;AACH;AACA,GAAG;AACH;AACA,GAAG;AACH;AACA,GAAG;AACH;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA,KAAK;AACL;AACA,KAAK;AACL,GAAG;AACH;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;;AAEA;AACA;AACA,OAAO;AACP;AACA;AACA;AACA;AACA;AACA;AACA,KAAK;AACL;AACA;AACA;;AAEA;AACA,mBAAmB,6CAA6C;AAChE;AACA;AACA;;AAEA;AACA;AACA;;;AAGA;AACA;;AAEA;AACA;AACA,OAAO;AACP;AACA;AACA,OAAO;AACP;AACA;AACA;AACA,OAAO;AACP;AACA;AACA,SAAS;AACT;AACA,KAAK;AACL;AACA;AACA;;AAEA;AACA;;;AAGA;AACA;;AAEA;AACA;AACA,OAAO;AACP;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA,KAAK;AACL;AACA,KAAK;AACL;;AAEA;AACA,CAAC;;AAED;AACA;AACA;AACA;AACA;;AAEA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,GAAG;AACH;;AAEA;AACA;AACA;;AAEA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,GAAG;AACH;AACA,GAAG;AACH;;AAEA;AACA;AACA,UAAU,MAAM;AAChB,UAAU,OAAO;AACjB;AACA,WAAW,QAAQ;AACnB;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;;AAEA;AACA;AACA;AACA;AACA,KAAK;AACL,GAAG;;AAEH;AACA;AACA;AACA,KAAK;AACL,GAAG;;AAEH;AACA;AACA;AACA,GAAG;AACH;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA,KAAK;AACL,GAAG;;AAEH;AACA;AACA;AACA,KAAK;AACL,GAAG;;AAEH;AACA;AACA,GAAG;AACH;AACA;AACA,GAAG;AACH;;AAEA;;AAEA;AACA;AACA;;AAEA;AACA;AACA,UAAU,MAAM;AAChB;AACA,WAAW,QAAQ;AACnB;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,KAAK;AACL,GAAG;AACH;AACA;AACA,qBAAqB,YAAY;AACjC;AACA;AACA,KAAK;AACL;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA,GAAG;;AAEH;AACA;AACA,GAAG;AACH;AACA,GAAG;AACH;;AAEA;;AAEA;AACA;;AAEA;AACA;AACA,GAAG;AACH;AACA,GAAG;AACH;;AAEA;AACA;AACA,UAAU,IAAI;AACd;AACA,WAAW,QAAQ;AACnB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;;AAGA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA,GAAG;;AAEH;AACA;AACA,GAAG;AACH;AACA,GAAG;AACH;;AAEA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA,WAAW;AACX;AACA;AACA;AACA;AACA,KAAK;AACL;;AAEA;AACA;AACA,GAAG;AACH;AACA,GAAG;AACH;;AAEA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA,GAAG;AACH;;AAEA;AACA,UAAU,SAAS;AACnB;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,GAAG;AACH;AACA,GAAG;AACH;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,GAAG;AACH;AACA,GAAG;AACH;AACA;AACA,GAAG;AACH;AACA;AACA,GAAG;AACH;AACA,GAAG;AACH;AACA,GAAG;AACH;AACA;AACA,GAAG;AACH;AACA;AACA;AACA;AACA;AACA,GAAG;AACH;AACA,GAAG;AACH;AACA,GAAG;AACH;AACA,GAAG;AACH;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,GAAG;AACH;AACA,GAAG;AACH;AACA;AACA;AACA;AACA;AACA,GAAG;AACH;AACA,GAAG;AACH;AACA,GAAG;AACH;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,GAAG;AACH;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,KAAK;AACL;AACA;AACA,GAAG;AACH;AACA;AACA;AACA;AACA;AACA,GAAG;AACH;AACA,GAAG;AACH;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,GAAG;AACH;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,KAAK;AACL;AACA;AACA;AACA;AACA,WAAW;AACX;AACA;AACA,aAAa;AACb;AACA;AACA;AACA,SAAS;AACT,OAAO;AACP;AACA;AACA;AACA;AACA,GAAG;AACH;AACA;AACA;AACA;AACA;AACA;AACA;AACA,GAAG;AACH;AACA,GAAG;AACH;AACA;AACA,UAAU,SAAS;AACnB,UAAU,SAAS;AACnB;AACA,WAAW;AACX;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,GAAG;AACH;AACA;AACA;AACA;AACA;AACA,GAAG;AACH;AACA;AACA,UAAU,SAAS;AACnB;AACA,WAAW;AACX;;;AAGA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA,0BAA0B;AAC1B,KAAK;AACL;AACA,KAAK;AACL;AACA;AACA;AACA;;AAEA;;AAEA;AACA;AACA;AACA,KAAK;AACL;AACA,KAAK;AACL;;AAEA;AACA,YAAY,SAAS;AACrB,aAAa;AACb;;;AAGA;AACA;AACA;;AAEA;AACA;AACA;AACA,OAAO;AACP,KAAK;AACL;AACA;AACA,OAAO;AACP,KAAK;AACL;;AAEA;AACA,CAAC;;AAED;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA,KAAK;AACL;AACA,KAAK;AACL;AACA;AACA,SAAS;AACT;AACA;AACA;;AAEA;;AAEA;AACA;AACA;AACA;AACA,SAAS;AACT;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;;AAEA;;AAEA;;AAEA,CAAC;;;;AAID;;;;;;;;ACvqCA;;AAEA;AACA;AACA;AACA,CAAC;;AAED;AACA;AACA;AAC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AI,OAAO,CAAC,YAAY,KAAK,SAAS,EAAE;YACpC,IAAI,CAAC,oBAAoB,CAAC,OAAO,CAAC,YAAY,EAAE,yCAAyC,CAAC,CAAC;SAC9F;IACL,CAAC;IAEO,6CAAmB,GAA3B,UAA4B,OAA0B;QAClD,IAAI,CAAC,oBAAoB,CAAC,OAAO,CAAC,YAAY,EAAE,yCAAyC,CAAC,CAAC;QAE3F,IAAI,OAAO,CAAC,IAAI,KAAK,SAAS,EAAE;YAC5B,MAAM,IAAI,KAAK,CAAC,yCAAyC,CAAC,CAAC;SAC9D;IACL,CAAC;IAEO,6CAAmB,GAA3B,UAA4B,OAA0B;QAClD,IAAI,OAAO,CAAC,MAAM,IAAI,OAAO,CAAC,KAAK,EAAE;YACjC,MAAM,IAAI,KAAK,CAAC,yCAAyC,CAAC,CAAC;SAC9D;QAED,IAAI,CAAC,OAAO,CAAC,MAAM,IAAI,OAAO,CAAC,KAAK,EAAE;YAClC,IAAI,CAAC,oBAAoB,CAAC,OAAO,CAAC,KAAK,EAAE,yCAAyC,CAAC,CAAC;SACvF;QAED,IAAI,CAAC,oBAAoB,CAAC,OAAO,CAAC,YAAY,EAAE,yCAAyC,CAAC,CAAC;IAC/F,CAAC;IAEO,8CAAoB,GAA5B,UAA6B,KAAU,EAAE,YAAoB;QACzD,IAAI,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,KAAK,EAAE,EAAE;YAC3C,MAAM,IAAI,KAAK,CAAC,YAAY,CAAC,CAAC;SACjC;IACL,CAAC;IACL,sBAAC;AAAD,CAAC","file":"signalr.js","sourcesContent":["(function webpackUniversalModuleDefinition(root, factory) {\n\tif(typeof exports === 'object' && typeof module === 'object')\n\t\tmodule.exports = factory();\n\telse if(typeof define === 'function' && define.amd)\n\t\tdefine([], factory);\n\telse if(typeof exports === 'object')\n\t\texports[\"signalR\"] = factory();\n\telse\n\t\troot[\"signalR\"] = factory();\n})(window, function() {\nreturn "," \t// The module cache\n \tvar installedModules = {};\n\n \t// The require function\n \tfunction __webpack_require__(moduleId) {\n\n \t\t// Check if module is in cache\n \t\tif(installedModules[moduleId]) {\n \t\t\treturn installedModules[moduleId].exports;\n \t\t}\n \t\t// Create a new module (and put it into the cache)\n \t\tvar module = installedModules[moduleId] = {\n \t\t\ti: moduleId,\n \t\t\tl: false,\n \t\t\texports: {}\n \t\t};\n\n \t\t// Execute the module function\n \t\tmodules[moduleId].call(module.exports, module, module.exports, __webpack_require__);\n\n \t\t// Flag the module as loaded\n \t\tmodule.l = true;\n\n \t\t// Return the exports of the module\n \t\treturn module.exports;\n \t}\n\n\n \t// expose the modules object (__webpack_modules__)\n \t__webpack_require__.m = modules;\n\n \t// expose the module cache\n \t__webpack_require__.c = installedModules;\n\n \t// define getter function for harmony exports\n \t__webpack_require__.d = function(exports, name, getter) {\n \t\tif(!__webpack_require__.o(exports, name)) {\n \t\t\tObject.defineProperty(exports, name, { enumerable: true, get: getter });\n \t\t}\n \t};\n\n \t// define __esModule on exports\n \t__webpack_require__.r = function(exports) {\n \t\tif(typeof Symbol !== 'undefined' && Symbol.toStringTag) {\n \t\t\tObject.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });\n \t\t}\n \t\tObject.defineProperty(exports, '__esModule', { value: true });\n \t};\n\n \t// create a fake namespace object\n \t// mode & 1: value is a module id, require it\n \t// mode & 2: merge all properties of value into the ns\n \t// mode & 4: return value when already ns object\n \t// mode & 8|1: behave like require\n \t__webpack_require__.t = function(value, mode) {\n \t\tif(mode & 1) value = __webpack_require__(value);\n \t\tif(mode & 8) return value;\n \t\tif((mode & 4) && typeof value === 'object' && value && value.__esModule) return value;\n \t\tvar ns = Object.create(null);\n \t\t__webpack_require__.r(ns);\n \t\tObject.defineProperty(ns, 'default', { enumerable: true, value: value });\n \t\tif(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key));\n \t\treturn ns;\n \t};\n\n \t// getDefaultExport function for compatibility with non-harmony modules\n \t__webpack_require__.n = function(module) {\n \t\tvar getter = module && module.__esModule ?\n \t\t\tfunction getDefault() { return module['default']; } :\n \t\t\tfunction getModuleExports() { return module; };\n \t\t__webpack_require__.d(getter, 'a', getter);\n \t\treturn getter;\n \t};\n\n \t// Object.prototype.hasOwnProperty.call\n \t__webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };\n\n \t// __webpack_public_path__\n \t__webpack_require__.p = \"\";\n\n\n \t// Load entry module and return exports\n \treturn __webpack_require__(__webpack_require__.s = 0);\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 is where we add any polyfills we'll need for the browser. It is the entry module for browser-specific builds.\r\n\r\nimport \"es6-promise/dist/es6-promise.auto.js\";\r\n\r\n// Copy from Array.prototype into Uint8Array to polyfill on IE. It's OK because the implementations of indexOf and slice use properties\r\n// that exist on Uint8Array with the same name, and JavaScript is magic.\r\n// We make them 'writable' because the Buffer polyfill messes with it as well.\r\nif (!Uint8Array.prototype.indexOf) {\r\n Object.defineProperty(Uint8Array.prototype, \"indexOf\", {\r\n value: Array.prototype.indexOf,\r\n writable: true,\r\n });\r\n}\r\nif (!Uint8Array.prototype.slice) {\r\n Object.defineProperty(Uint8Array.prototype, \"slice\", {\r\n value: Array.prototype.slice,\r\n writable: true,\r\n });\r\n}\r\nif (!Uint8Array.prototype.forEach) {\r\n Object.defineProperty(Uint8Array.prototype, \"forEach\", {\r\n value: Array.prototype.forEach,\r\n writable: true,\r\n });\r\n}\r\n\r\nexport * from \"./index\";\r\n","/*!\n * @overview es6-promise - a tiny implementation of Promises/A+.\n * @copyright Copyright (c) 2014 Yehuda Katz, Tom Dale, Stefan Penner and contributors (Conversion to ES6 API by Jake Archibald)\n * @license Licensed under MIT license\n * See https://raw.githubusercontent.com/stefanpenner/es6-promise/master/LICENSE\n * @version v4.2.2+97478eb6\n */\n\n(function (global, factory) {\n\ttypeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :\n\ttypeof define === 'function' && define.amd ? define(factory) :\n\t(global.ES6Promise = factory());\n}(this, (function () { 'use strict';\n\nfunction objectOrFunction(x) {\n var type = typeof x;\n return x !== null && (type === 'object' || type === 'function');\n}\n\nfunction isFunction(x) {\n return typeof x === 'function';\n}\n\n\n\nvar _isArray = void 0;\nif (Array.isArray) {\n _isArray = Array.isArray;\n} else {\n _isArray = function (x) {\n return Object.prototype.toString.call(x) === '[object Array]';\n };\n}\n\nvar isArray = _isArray;\n\nvar len = 0;\nvar vertxNext = void 0;\nvar customSchedulerFn = void 0;\n\nvar asap = function asap(callback, arg) {\n queue[len] = callback;\n queue[len + 1] = arg;\n len += 2;\n if (len === 2) {\n // If len is 2, that means that we need to schedule an async flush.\n // If additional callbacks are queued before the queue is flushed, they\n // will be processed by this flush that we are scheduling.\n if (customSchedulerFn) {\n customSchedulerFn(flush);\n } else {\n scheduleFlush();\n }\n }\n};\n\nfunction setScheduler(scheduleFn) {\n customSchedulerFn = scheduleFn;\n}\n\nfunction setAsap(asapFn) {\n asap = asapFn;\n}\n\nvar browserWindow = typeof window !== 'undefined' ? window : undefined;\nvar browserGlobal = browserWindow || {};\nvar BrowserMutationObserver = browserGlobal.MutationObserver || browserGlobal.WebKitMutationObserver;\nvar isNode = typeof self === 'undefined' && typeof process !== 'undefined' && {}.toString.call(process) === '[object process]';\n\n// test for web worker but not in IE10\nvar isWorker = typeof Uint8ClampedArray !== 'undefined' && typeof importScripts !== 'undefined' && typeof MessageChannel !== 'undefined';\n\n// node\nfunction useNextTick() {\n // node version 0.10.x displays a deprecation warning when nextTick is used recursively\n // see https://github.com/cujojs/when/issues/410 for details\n return function () {\n return process.nextTick(flush);\n };\n}\n\n// vertx\nfunction useVertxTimer() {\n if (typeof vertxNext !== 'undefined') {\n return function () {\n vertxNext(flush);\n };\n }\n\n return useSetTimeout();\n}\n\nfunction useMutationObserver() {\n var iterations = 0;\n var observer = new BrowserMutationObserver(flush);\n var node = document.createTextNode('');\n observer.observe(node, { characterData: true });\n\n return function () {\n node.data = iterations = ++iterations % 2;\n };\n}\n\n// web worker\nfunction useMessageChannel() {\n var channel = new MessageChannel();\n channel.port1.onmessage = flush;\n return function () {\n return channel.port2.postMessage(0);\n };\n}\n\nfunction useSetTimeout() {\n // Store setTimeout reference so es6-promise will be unaffected by\n // other code modifying setTimeout (like sinon.useFakeTimers())\n var globalSetTimeout = setTimeout;\n return function () {\n return globalSetTimeout(flush, 1);\n };\n}\n\nvar queue = new Array(1000);\nfunction flush() {\n for (var i = 0; i < len; i += 2) {\n var callback = queue[i];\n var arg = queue[i + 1];\n\n callback(arg);\n\n queue[i] = undefined;\n queue[i + 1] = undefined;\n }\n\n len = 0;\n}\n\nfunction attemptVertx() {\n try {\n var r = require;\n var vertx = r('vertx');\n vertxNext = vertx.runOnLoop || vertx.runOnContext;\n return useVertxTimer();\n } catch (e) {\n return useSetTimeout();\n }\n}\n\nvar scheduleFlush = void 0;\n// Decide what async method to use to triggering processing of queued callbacks:\nif (isNode) {\n scheduleFlush = useNextTick();\n} else if (BrowserMutationObserver) {\n scheduleFlush = useMutationObserver();\n} else if (isWorker) {\n scheduleFlush = useMessageChannel();\n} else if (browserWindow === undefined && typeof require === 'function') {\n scheduleFlush = attemptVertx();\n} else {\n scheduleFlush = useSetTimeout();\n}\n\nfunction then(onFulfillment, onRejection) {\n var parent = this;\n\n var child = new this.constructor(noop);\n\n if (child[PROMISE_ID] === undefined) {\n makePromise(child);\n }\n\n var _state = parent._state;\n\n\n if (_state) {\n var callback = arguments[_state - 1];\n asap(function () {\n return invokeCallback(_state, child, callback, parent._result);\n });\n } else {\n subscribe(parent, child, onFulfillment, onRejection);\n }\n\n return child;\n}\n\n/**\n `Promise.resolve` returns a promise that will become resolved with the\n passed `value`. It is shorthand for the following:\n\n ```javascript\n let promise = new Promise(function(resolve, reject){\n resolve(1);\n });\n\n promise.then(function(value){\n // value === 1\n });\n ```\n\n Instead of writing the above, your code now simply becomes the following:\n\n ```javascript\n let promise = Promise.resolve(1);\n\n promise.then(function(value){\n // value === 1\n });\n ```\n\n @method resolve\n @static\n @param {Any} value value that the returned promise will be resolved with\n Useful for tooling.\n @return {Promise} a promise that will become fulfilled with the given\n `value`\n*/\nfunction resolve$1(object) {\n /*jshint validthis:true */\n var Constructor = this;\n\n if (object && typeof object === 'object' && object.constructor === Constructor) {\n return object;\n }\n\n var promise = new Constructor(noop);\n resolve(promise, object);\n return promise;\n}\n\nvar PROMISE_ID = Math.random().toString(36).substring(16);\n\nfunction noop() {}\n\nvar PENDING = void 0;\nvar FULFILLED = 1;\nvar REJECTED = 2;\n\nvar GET_THEN_ERROR = new ErrorObject();\n\nfunction selfFulfillment() {\n return new TypeError(\"You cannot resolve a promise with itself\");\n}\n\nfunction cannotReturnOwn() {\n return new TypeError('A promises callback cannot return that same promise.');\n}\n\nfunction getThen(promise) {\n try {\n return promise.then;\n } catch (error) {\n GET_THEN_ERROR.error = error;\n return GET_THEN_ERROR;\n }\n}\n\nfunction tryThen(then$$1, value, fulfillmentHandler, rejectionHandler) {\n try {\n then$$1.call(value, fulfillmentHandler, rejectionHandler);\n } catch (e) {\n return e;\n }\n}\n\nfunction handleForeignThenable(promise, thenable, then$$1) {\n asap(function (promise) {\n var sealed = false;\n var error = tryThen(then$$1, thenable, function (value) {\n if (sealed) {\n return;\n }\n sealed = true;\n if (thenable !== value) {\n resolve(promise, value);\n } else {\n fulfill(promise, value);\n }\n }, function (reason) {\n if (sealed) {\n return;\n }\n sealed = true;\n\n reject(promise, reason);\n }, 'Settle: ' + (promise._label || ' unknown promise'));\n\n if (!sealed && error) {\n sealed = true;\n reject(promise, error);\n }\n }, promise);\n}\n\nfunction handleOwnThenable(promise, thenable) {\n if (thenable._state === FULFILLED) {\n fulfill(promise, thenable._result);\n } else if (thenable._state === REJECTED) {\n reject(promise, thenable._result);\n } else {\n subscribe(thenable, undefined, function (value) {\n return resolve(promise, value);\n }, function (reason) {\n return reject(promise, reason);\n });\n }\n}\n\nfunction handleMaybeThenable(promise, maybeThenable, then$$1) {\n if (maybeThenable.constructor === promise.constructor && then$$1 === then && maybeThenable.constructor.resolve === resolve$1) {\n handleOwnThenable(promise, maybeThenable);\n } else {\n if (then$$1 === GET_THEN_ERROR) {\n reject(promise, GET_THEN_ERROR.error);\n GET_THEN_ERROR.error = null;\n } else if (then$$1 === undefined) {\n fulfill(promise, maybeThenable);\n } else if (isFunction(then$$1)) {\n handleForeignThenable(promise, maybeThenable, then$$1);\n } else {\n fulfill(promise, maybeThenable);\n }\n }\n}\n\nfunction resolve(promise, value) {\n if (promise === value) {\n reject(promise, selfFulfillment());\n } else if (objectOrFunction(value)) {\n handleMaybeThenable(promise, value, getThen(value));\n } else {\n fulfill(promise, value);\n }\n}\n\nfunction publishRejection(promise) {\n if (promise._onerror) {\n promise._onerror(promise._result);\n }\n\n publish(promise);\n}\n\nfunction fulfill(promise, value) {\n if (promise._state !== PENDING) {\n return;\n }\n\n promise._result = value;\n promise._state = FULFILLED;\n\n if (promise._subscribers.length !== 0) {\n asap(publish, promise);\n }\n}\n\nfunction reject(promise, reason) {\n if (promise._state !== PENDING) {\n return;\n }\n promise._state = REJECTED;\n promise._result = reason;\n\n asap(publishRejection, promise);\n}\n\nfunction subscribe(parent, child, onFulfillment, onRejection) {\n var _subscribers = parent._subscribers;\n var length = _subscribers.length;\n\n\n parent._onerror = null;\n\n _subscribers[length] = child;\n _subscribers[length + FULFILLED] = onFulfillment;\n _subscribers[length + REJECTED] = onRejection;\n\n if (length === 0 && parent._state) {\n asap(publish, parent);\n }\n}\n\nfunction publish(promise) {\n var subscribers = promise._subscribers;\n var settled = promise._state;\n\n if (subscribers.length === 0) {\n return;\n }\n\n var child = void 0,\n callback = void 0,\n detail = promise._result;\n\n for (var i = 0; i < subscribers.length; i += 3) {\n child = subscribers[i];\n callback = subscribers[i + settled];\n\n if (child) {\n invokeCallback(settled, child, callback, detail);\n } else {\n callback(detail);\n }\n }\n\n promise._subscribers.length = 0;\n}\n\nfunction ErrorObject() {\n this.error = null;\n}\n\nvar TRY_CATCH_ERROR = new ErrorObject();\n\nfunction tryCatch(callback, detail) {\n try {\n return callback(detail);\n } catch (e) {\n TRY_CATCH_ERROR.error = e;\n return TRY_CATCH_ERROR;\n }\n}\n\nfunction invokeCallback(settled, promise, callback, detail) {\n var hasCallback = isFunction(callback),\n value = void 0,\n error = void 0,\n succeeded = void 0,\n failed = void 0;\n\n if (hasCallback) {\n value = tryCatch(callback, detail);\n\n if (value === TRY_CATCH_ERROR) {\n failed = true;\n error = value.error;\n value.error = null;\n } else {\n succeeded = true;\n }\n\n if (promise === value) {\n reject(promise, cannotReturnOwn());\n return;\n }\n } else {\n value = detail;\n succeeded = true;\n }\n\n if (promise._state !== PENDING) {\n // noop\n } else if (hasCallback && succeeded) {\n resolve(promise, value);\n } else if (failed) {\n reject(promise, error);\n } else if (settled === FULFILLED) {\n fulfill(promise, value);\n } else if (settled === REJECTED) {\n reject(promise, value);\n }\n}\n\nfunction initializePromise(promise, resolver) {\n try {\n resolver(function resolvePromise(value) {\n resolve(promise, value);\n }, function rejectPromise(reason) {\n reject(promise, reason);\n });\n } catch (e) {\n reject(promise, e);\n }\n}\n\nvar id = 0;\nfunction nextId() {\n return id++;\n}\n\nfunction makePromise(promise) {\n promise[PROMISE_ID] = id++;\n promise._state = undefined;\n promise._result = undefined;\n promise._subscribers = [];\n}\n\nfunction validationError() {\n return new Error('Array Methods must be provided an Array');\n}\n\nfunction validationError() {\n return new Error('Array Methods must be provided an Array');\n}\n\nvar Enumerator = function () {\n function Enumerator(Constructor, input) {\n this._instanceConstructor = Constructor;\n this.promise = new Constructor(noop);\n\n if (!this.promise[PROMISE_ID]) {\n makePromise(this.promise);\n }\n\n if (isArray(input)) {\n this.length = input.length;\n this._remaining = input.length;\n\n this._result = new Array(this.length);\n\n if (this.length === 0) {\n fulfill(this.promise, this._result);\n } else {\n this.length = this.length || 0;\n this._enumerate(input);\n if (this._remaining === 0) {\n fulfill(this.promise, this._result);\n }\n }\n } else {\n reject(this.promise, validationError());\n }\n }\n\n Enumerator.prototype._enumerate = function _enumerate(input) {\n for (var i = 0; this._state === PENDING && i < input.length; i++) {\n this._eachEntry(input[i], i);\n }\n };\n\n Enumerator.prototype._eachEntry = function _eachEntry(entry, i) {\n var c = this._instanceConstructor;\n var resolve$$1 = c.resolve;\n\n\n if (resolve$$1 === resolve$1) {\n var _then = getThen(entry);\n\n if (_then === then && entry._state !== PENDING) {\n this._settledAt(entry._state, i, entry._result);\n } else if (typeof _then !== 'function') {\n this._remaining--;\n this._result[i] = entry;\n } else if (c === Promise$2) {\n var promise = new c(noop);\n handleMaybeThenable(promise, entry, _then);\n this._willSettleAt(promise, i);\n } else {\n this._willSettleAt(new c(function (resolve$$1) {\n return resolve$$1(entry);\n }), i);\n }\n } else {\n this._willSettleAt(resolve$$1(entry), i);\n }\n };\n\n Enumerator.prototype._settledAt = function _settledAt(state, i, value) {\n var promise = this.promise;\n\n\n if (promise._state === PENDING) {\n this._remaining--;\n\n if (state === REJECTED) {\n reject(promise, value);\n } else {\n this._result[i] = value;\n }\n }\n\n if (this._remaining === 0) {\n fulfill(promise, this._result);\n }\n };\n\n Enumerator.prototype._willSettleAt = function _willSettleAt(promise, i) {\n var enumerator = this;\n\n subscribe(promise, undefined, function (value) {\n return enumerator._settledAt(FULFILLED, i, value);\n }, function (reason) {\n return enumerator._settledAt(REJECTED, i, reason);\n });\n };\n\n return Enumerator;\n}();\n\n/**\n `Promise.all` accepts an array of promises, and returns a new promise which\n is fulfilled with an array of fulfillment values for the passed promises, or\n rejected with the reason of the first passed promise to be rejected. It casts all\n elements of the passed iterable to promises as it runs this algorithm.\n\n Example:\n\n ```javascript\n let promise1 = resolve(1);\n let promise2 = resolve(2);\n let promise3 = resolve(3);\n let promises = [ promise1, promise2, promise3 ];\n\n Promise.all(promises).then(function(array){\n // The array here would be [ 1, 2, 3 ];\n });\n ```\n\n If any of the `promises` given to `all` are rejected, the first promise\n that is rejected will be given as an argument to the returned promises's\n rejection handler. For example:\n\n Example:\n\n ```javascript\n let promise1 = resolve(1);\n let promise2 = reject(new Error(\"2\"));\n let promise3 = reject(new Error(\"3\"));\n let promises = [ promise1, promise2, promise3 ];\n\n Promise.all(promises).then(function(array){\n // Code here never runs because there are rejected promises!\n }, function(error) {\n // error.message === \"2\"\n });\n ```\n\n @method all\n @static\n @param {Array} entries array of promises\n @param {String} label optional string for labeling the promise.\n Useful for tooling.\n @return {Promise} promise that is fulfilled when all `promises` have been\n fulfilled, or rejected if any of them become rejected.\n @static\n*/\nfunction all(entries) {\n return new Enumerator(this, entries).promise;\n}\n\n/**\n `Promise.race` returns a new promise which is settled in the same way as the\n first passed promise to settle.\n\n Example:\n\n ```javascript\n let promise1 = new Promise(function(resolve, reject){\n setTimeout(function(){\n resolve('promise 1');\n }, 200);\n });\n\n let promise2 = new Promise(function(resolve, reject){\n setTimeout(function(){\n resolve('promise 2');\n }, 100);\n });\n\n Promise.race([promise1, promise2]).then(function(result){\n // result === 'promise 2' because it was resolved before promise1\n // was resolved.\n });\n ```\n\n `Promise.race` is deterministic in that only the state of the first\n settled promise matters. For example, even if other promises given to the\n `promises` array argument are resolved, but the first settled promise has\n become rejected before the other promises became fulfilled, the returned\n promise will become rejected:\n\n ```javascript\n let promise1 = new Promise(function(resolve, reject){\n setTimeout(function(){\n resolve('promise 1');\n }, 200);\n });\n\n let promise2 = new Promise(function(resolve, reject){\n setTimeout(function(){\n reject(new Error('promise 2'));\n }, 100);\n });\n\n Promise.race([promise1, promise2]).then(function(result){\n // Code here never runs\n }, function(reason){\n // reason.message === 'promise 2' because promise 2 became rejected before\n // promise 1 became fulfilled\n });\n ```\n\n An example real-world use case is implementing timeouts:\n\n ```javascript\n Promise.race([ajax('foo.json'), timeout(5000)])\n ```\n\n @method race\n @static\n @param {Array} promises array of promises to observe\n Useful for tooling.\n @return {Promise} a promise which settles in the same way as the first passed\n promise to settle.\n*/\nfunction race(entries) {\n /*jshint validthis:true */\n var Constructor = this;\n\n if (!isArray(entries)) {\n return new Constructor(function (_, reject) {\n return reject(new TypeError('You must pass an array to race.'));\n });\n } else {\n return new Constructor(function (resolve, reject) {\n var length = entries.length;\n for (var i = 0; i < length; i++) {\n Constructor.resolve(entries[i]).then(resolve, reject);\n }\n });\n }\n}\n\n/**\n `Promise.reject` returns a promise rejected with the passed `reason`.\n It is shorthand for the following:\n\n ```javascript\n let promise = new Promise(function(resolve, reject){\n reject(new Error('WHOOPS'));\n });\n\n promise.then(function(value){\n // Code here doesn't run because the promise is rejected!\n }, function(reason){\n // reason.message === 'WHOOPS'\n });\n ```\n\n Instead of writing the above, your code now simply becomes the following:\n\n ```javascript\n let promise = Promise.reject(new Error('WHOOPS'));\n\n promise.then(function(value){\n // Code here doesn't run because the promise is rejected!\n }, function(reason){\n // reason.message === 'WHOOPS'\n });\n ```\n\n @method reject\n @static\n @param {Any} reason value that the returned promise will be rejected with.\n Useful for tooling.\n @return {Promise} a promise rejected with the given `reason`.\n*/\nfunction reject$1(reason) {\n /*jshint validthis:true */\n var Constructor = this;\n var promise = new Constructor(noop);\n reject(promise, reason);\n return promise;\n}\n\nfunction needsResolver() {\n throw new TypeError('You must pass a resolver function as the first argument to the promise constructor');\n}\n\nfunction needsNew() {\n throw new TypeError(\"Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function.\");\n}\n\n/**\n Promise objects represent the eventual result of an asynchronous operation. The\n primary way of interacting with a promise is through its `then` method, which\n registers callbacks to receive either a promise's eventual value or the reason\n why the promise cannot be fulfilled.\n\n Terminology\n -----------\n\n - `promise` is an object or function with a `then` method whose behavior conforms to this specification.\n - `thenable` is an object or function that defines a `then` method.\n - `value` is any legal JavaScript value (including undefined, a thenable, or a promise).\n - `exception` is a value that is thrown using the throw statement.\n - `reason` is a value that indicates why a promise was rejected.\n - `settled` the final resting state of a promise, fulfilled or rejected.\n\n A promise can be in one of three states: pending, fulfilled, or rejected.\n\n Promises that are fulfilled have a fulfillment value and are in the fulfilled\n state. Promises that are rejected have a rejection reason and are in the\n rejected state. A fulfillment value is never a thenable.\n\n Promises can also be said to *resolve* a value. If this value is also a\n promise, then the original promise's settled state will match the value's\n settled state. So a promise that *resolves* a promise that rejects will\n itself reject, and a promise that *resolves* a promise that fulfills will\n itself fulfill.\n\n\n Basic Usage:\n ------------\n\n ```js\n let promise = new Promise(function(resolve, reject) {\n // on success\n resolve(value);\n\n // on failure\n reject(reason);\n });\n\n promise.then(function(value) {\n // on fulfillment\n }, function(reason) {\n // on rejection\n });\n ```\n\n Advanced Usage:\n ---------------\n\n Promises shine when abstracting away asynchronous interactions such as\n `XMLHttpRequest`s.\n\n ```js\n function getJSON(url) {\n return new Promise(function(resolve, reject){\n let xhr = new XMLHttpRequest();\n\n xhr.open('GET', url);\n xhr.onreadystatechange = handler;\n xhr.responseType = 'json';\n xhr.setRequestHeader('Accept', 'application/json');\n xhr.send();\n\n function handler() {\n if (this.readyState === this.DONE) {\n if (this.status === 200) {\n resolve(this.response);\n } else {\n reject(new Error('getJSON: `' + url + '` failed with status: [' + this.status + ']'));\n }\n }\n };\n });\n }\n\n getJSON('/posts.json').then(function(json) {\n // on fulfillment\n }, function(reason) {\n // on rejection\n });\n ```\n\n Unlike callbacks, promises are great composable primitives.\n\n ```js\n Promise.all([\n getJSON('/posts'),\n getJSON('/comments')\n ]).then(function(values){\n values[0] // => postsJSON\n values[1] // => commentsJSON\n\n return values;\n });\n ```\n\n @class Promise\n @param {Function} resolver\n Useful for tooling.\n @constructor\n*/\n\nvar Promise$2 = function () {\n function Promise(resolver) {\n this[PROMISE_ID] = nextId();\n this._result = this._state = undefined;\n this._subscribers = [];\n\n if (noop !== resolver) {\n typeof resolver !== 'function' && needsResolver();\n this instanceof Promise ? initializePromise(this, resolver) : needsNew();\n }\n }\n\n /**\n The primary way of interacting with a promise is through its `then` method,\n which registers callbacks to receive either a promise's eventual value or the\n reason why the promise cannot be fulfilled.\n ```js\n findUser().then(function(user){\n // user is available\n }, function(reason){\n // user is unavailable, and you are given the reason why\n });\n ```\n Chaining\n --------\n The return value of `then` is itself a promise. This second, 'downstream'\n promise is resolved with the return value of the first promise's fulfillment\n or rejection handler, or rejected if the handler throws an exception.\n ```js\n findUser().then(function (user) {\n return user.name;\n }, function (reason) {\n return 'default name';\n }).then(function (userName) {\n // If `findUser` fulfilled, `userName` will be the user's name, otherwise it\n // will be `'default name'`\n });\n findUser().then(function (user) {\n throw new Error('Found user, but still unhappy');\n }, function (reason) {\n throw new Error('`findUser` rejected and we're unhappy');\n }).then(function (value) {\n // never reached\n }, function (reason) {\n // if `findUser` fulfilled, `reason` will be 'Found user, but still unhappy'.\n // If `findUser` rejected, `reason` will be '`findUser` rejected and we're unhappy'.\n });\n ```\n If the downstream promise does not specify a rejection handler, rejection reasons will be propagated further downstream.\n ```js\n findUser().then(function (user) {\n throw new PedagogicalException('Upstream error');\n }).then(function (value) {\n // never reached\n }).then(function (value) {\n // never reached\n }, function (reason) {\n // The `PedgagocialException` is propagated all the way down to here\n });\n ```\n Assimilation\n ------------\n Sometimes the value you want to propagate to a downstream promise can only be\n retrieved asynchronously. This can be achieved by returning a promise in the\n fulfillment or rejection handler. The downstream promise will then be pending\n until the returned promise is settled. This is called *assimilation*.\n ```js\n findUser().then(function (user) {\n return findCommentsByAuthor(user);\n }).then(function (comments) {\n // The user's comments are now available\n });\n ```\n If the assimliated promise rejects, then the downstream promise will also reject.\n ```js\n findUser().then(function (user) {\n return findCommentsByAuthor(user);\n }).then(function (comments) {\n // If `findCommentsByAuthor` fulfills, we'll have the value here\n }, function (reason) {\n // If `findCommentsByAuthor` rejects, we'll have the reason here\n });\n ```\n Simple Example\n --------------\n Synchronous Example\n ```javascript\n let result;\n try {\n result = findResult();\n // success\n } catch(reason) {\n // failure\n }\n ```\n Errback Example\n ```js\n findResult(function(result, err){\n if (err) {\n // failure\n } else {\n // success\n }\n });\n ```\n Promise Example;\n ```javascript\n findResult().then(function(result){\n // success\n }, function(reason){\n // failure\n });\n ```\n Advanced Example\n --------------\n Synchronous Example\n ```javascript\n let author, books;\n try {\n author = findAuthor();\n books = findBooksByAuthor(author);\n // success\n } catch(reason) {\n // failure\n }\n ```\n Errback Example\n ```js\n function foundBooks(books) {\n }\n function failure(reason) {\n }\n findAuthor(function(author, err){\n if (err) {\n failure(err);\n // failure\n } else {\n try {\n findBoooksByAuthor(author, function(books, err) {\n if (err) {\n failure(err);\n } else {\n try {\n foundBooks(books);\n } catch(reason) {\n failure(reason);\n }\n }\n });\n } catch(error) {\n failure(err);\n }\n // success\n }\n });\n ```\n Promise Example;\n ```javascript\n findAuthor().\n then(findBooksByAuthor).\n then(function(books){\n // found books\n }).catch(function(reason){\n // something went wrong\n });\n ```\n @method then\n @param {Function} onFulfilled\n @param {Function} onRejected\n Useful for tooling.\n @return {Promise}\n */\n\n /**\n `catch` is simply sugar for `then(undefined, onRejection)` which makes it the same\n as the catch block of a try/catch statement.\n ```js\n function findAuthor(){\n throw new Error('couldn't find that author');\n }\n // synchronous\n try {\n findAuthor();\n } catch(reason) {\n // something went wrong\n }\n // async with promises\n findAuthor().catch(function(reason){\n // something went wrong\n });\n ```\n @method catch\n @param {Function} onRejection\n Useful for tooling.\n @return {Promise}\n */\n\n\n Promise.prototype.catch = function _catch(onRejection) {\n return this.then(null, onRejection);\n };\n\n /**\n `finally` will be invoked regardless of the promise's fate just as native\n try/catch/finally behaves\n \n Synchronous example:\n \n ```js\n findAuthor() {\n if (Math.random() > 0.5) {\n throw new Error();\n }\n return new Author();\n }\n \n try {\n return findAuthor(); // succeed or fail\n } catch(error) {\n return findOtherAuther();\n } finally {\n // always runs\n // doesn't affect the return value\n }\n ```\n \n Asynchronous example:\n \n ```js\n findAuthor().catch(function(reason){\n return findOtherAuther();\n }).finally(function(){\n // author was either found, or not\n });\n ```\n \n @method finally\n @param {Function} callback\n @return {Promise}\n */\n\n\n Promise.prototype.finally = function _finally(callback) {\n var promise = this;\n var constructor = promise.constructor;\n\n return promise.then(function (value) {\n return constructor.resolve(callback()).then(function () {\n return value;\n });\n }, function (reason) {\n return constructor.resolve(callback()).then(function () {\n throw reason;\n });\n });\n };\n\n return Promise;\n}();\n\nPromise$2.prototype.then = then;\nPromise$2.all = all;\nPromise$2.race = race;\nPromise$2.resolve = resolve$1;\nPromise$2.reject = reject$1;\nPromise$2._setScheduler = setScheduler;\nPromise$2._setAsap = setAsap;\nPromise$2._asap = asap;\n\n/*global self*/\nfunction polyfill() {\n var local = void 0;\n\n if (typeof global !== 'undefined') {\n local = global;\n } else if (typeof self !== 'undefined') {\n local = self;\n } else {\n try {\n local = Function('return this')();\n } catch (e) {\n throw new Error('polyfill failed because global object is unavailable in this environment');\n }\n }\n\n var P = local.Promise;\n\n if (P) {\n var promiseToString = null;\n try {\n promiseToString = Object.prototype.toString.call(P.resolve());\n } catch (e) {\n // silently ignored\n }\n\n if (promiseToString === '[object Promise]' && !P.cast) {\n return;\n }\n }\n\n local.Promise = Promise$2;\n}\n\n// Strange compat..\nPromise$2.polyfill = polyfill;\nPromise$2.Promise = Promise$2;\n\nPromise$2.polyfill();\n\nreturn Promise$2;\n\n})));\n\n\n\n//# sourceMappingURL=es6-promise.auto.map\n","var g;\n\n// This works in non-strict mode\ng = (function() {\n\treturn this;\n})();\n\ntry {\n\t// This works if eval is allowed (see CSP)\n\tg = g || Function(\"return this\")() || (1, eval)(\"this\");\n} catch (e) {\n\t// This works if the window reference is available\n\tif (typeof window === \"object\") g = window;\n}\n\n// g can still be undefined, but nothing to do about it...\n// We return undefined, instead of nothing here, so it's\n// easier to handle this case. if(!global) { ...}\n\nmodule.exports = g;\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// 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// Everything that users need to access must be exported here. Including interfaces.\r\nexport { AbortSignal } from \"./AbortController\";\r\nexport { AbortError, HttpError, TimeoutError } from \"./Errors\";\r\nexport { HttpClient, HttpRequest, HttpResponse } from \"./HttpClient\";\r\nexport { DefaultHttpClient } from \"./DefaultHttpClient\";\r\nexport { IHttpConnectionOptions } from \"./IHttpConnectionOptions\";\r\nexport { HubConnection, HubConnectionState } from \"./HubConnection\";\r\nexport { HubConnectionBuilder } from \"./HubConnectionBuilder\";\r\nexport { MessageType, MessageHeaders, HubMessage, HubMessageBase, HubInvocationMessage, InvocationMessage, StreamInvocationMessage, StreamItemMessage, CompletionMessage, PingMessage, CloseMessage, CancelInvocationMessage, IHubProtocol } from \"./IHubProtocol\";\r\nexport { ILogger, LogLevel } from \"./ILogger\";\r\nexport { HttpTransportType, TransferFormat, ITransport } from \"./ITransport\";\r\nexport { IStreamSubscriber, IStreamResult, ISubscription } from \"./Stream\";\r\nexport { NullLogger } from \"./Loggers\";\r\nexport { JsonHubProtocol } from \"./JsonHubProtocol\";\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 @aspnet/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 @aspnet/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\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?: { [key: string]: string };\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\r\n/** Represents an HTTP response. */\r\nexport class HttpResponse {\r\n /** Constructs a new instance of {@link @aspnet/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 @aspnet/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 @aspnet/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 @aspnet/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 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 @aspnet/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 @aspnet/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 @aspnet/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 @aspnet/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 @aspnet/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 @aspnet/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 @aspnet/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 @aspnet/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 @aspnet/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 @aspnet/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 @aspnet/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 @aspnet/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 @aspnet/signalr.HttpResponse} representing the result.\r\n *\r\n * @param {HttpRequest} request An {@link @aspnet/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\nimport { AbortError } from \"./Errors\";\r\nimport { HttpClient, HttpRequest, HttpResponse } from \"./HttpClient\";\r\nimport { ILogger } from \"./ILogger\";\r\nimport { XhrHttpClient } from \"./XhrHttpClient\";\r\n\r\nlet nodeHttpClientModule: any;\r\nif (typeof XMLHttpRequest === \"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 nodeHttpClientModule = requireFunc(\"./NodeHttpClient\");\r\n}\r\n\r\n/** Default implementation of {@link @aspnet/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 @aspnet/signalr.DefaultHttpClient}, using the provided {@link @aspnet/signalr.ILogger} to log messages. */\r\n public constructor(logger: ILogger) {\r\n super();\r\n\r\n if (typeof XMLHttpRequest !== \"undefined\") {\r\n this.httpClient = new XhrHttpClient(logger);\r\n } else if (typeof nodeHttpClientModule !== \"undefined\") {\r\n this.httpClient = new nodeHttpClientModule.NodeHttpClient(logger);\r\n } else {\r\n throw new Error(\"No HttpClient could be created.\");\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 { 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 = true;\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\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 { 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 { IStreamResult } from \"./Stream\";\r\nimport { Arg, Subject } 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,\r\n /** The hub connection is connected. */\r\n Connected,\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 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 id: number;\r\n private closedCallbacks: Array<(error?: Error) => void>;\r\n private receivedHandshakeResponse: boolean;\r\n private handshakeResolver!: (value?: PromiseLike<{}>) => void;\r\n private handshakeRejecter!: (reason?: any) => void;\r\n private connectionState: HubConnectionState;\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 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 */\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): HubConnection {\r\n return new HubConnection(connection, logger, protocol);\r\n }\r\n\r\n private constructor(connection: IConnection, logger: ILogger, protocol: IHubProtocol) {\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.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.id = 0;\r\n this.receivedHandshakeResponse = false;\r\n this.connectionState = HubConnectionState.Disconnected;\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 /** 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 async start(): Promise {\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, \"Starting HubConnection.\");\r\n\r\n this.receivedHandshakeResponse = false;\r\n // Set up the promise before any connection is 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 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 // Wait for the handshake to complete before marking connection as connected\r\n await handshakePromise;\r\n this.connectionState = HubConnectionState.Connected;\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 stop(): Promise {\r\n this.logger.log(LogLevel.Debug, \"Stopping HubConnection.\");\r\n\r\n this.cleanupTimeout();\r\n this.cleanupPingTimer();\r\n return this.connection.stop();\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 invocationDescriptor = this.createStreamInvocation(methodName, args);\r\n\r\n const subject = new Subject(() => {\r\n const cancelInvocation: CancelInvocationMessage = this.createCancelInvocation(invocationDescriptor.invocationId);\r\n const cancelMessage: any = this.protocol.writeMessage(cancelInvocation);\r\n\r\n delete this.callbacks[invocationDescriptor.invocationId];\r\n\r\n return this.sendMessage(cancelMessage);\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 const message = this.protocol.writeMessage(invocationDescriptor);\r\n\r\n this.sendMessage(message)\r\n .catch((e) => {\r\n subject.error(e);\r\n delete this.callbacks[invocationDescriptor.invocationId];\r\n });\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 /** 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 invocationDescriptor = this.createInvocation(methodName, args, true);\r\n\r\n const message = this.protocol.writeMessage(invocationDescriptor);\r\n\r\n return this.sendMessage(message);\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 invocationDescriptor = this.createInvocation(methodName, args, false);\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 message = this.protocol.writeMessage(invocationDescriptor);\r\n\r\n this.sendMessage(message)\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\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 @aspnet/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 @aspnet/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 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 != null) {\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 // We don't want to wait on the stop itself.\r\n // tslint:disable-next-line:no-floating-promises\r\n this.connection.stop(message.error ? new Error(\"Server returned an error on close: \" + message.error) : undefined);\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\r\n // We don't want to wait on the stop itself.\r\n // tslint:disable-next-line:no-floating-promises\r\n this.connection.stop(error);\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 this.handshakeRejecter(message);\r\n // We don't want to wait on the stop itself.\r\n // tslint:disable-next-line:no-floating-promises\r\n this.connection.stop(new Error(message));\r\n throw new Error(message);\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 this.cleanupPingTimer();\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 }, this.keepAliveIntervalInMilliseconds);\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 }\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.\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 methods.forEach((m) => m.apply(this, invocationMessage.arguments));\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 need to wait on this Promise.\r\n // tslint:disable-next-line:no-floating-promises\r\n this.connection.stop(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 const callbacks = this.callbacks;\r\n this.callbacks = {};\r\n\r\n this.connectionState = HubConnectionState.Disconnected;\r\n\r\n // if 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.handshakeRejecter) {\r\n this.handshakeRejecter(error);\r\n }\r\n\r\n Object.keys(callbacks)\r\n .forEach((key) => {\r\n const callback = callbacks[key];\r\n callback(null, error ? error : new Error(\"Invocation canceled due to connection being closed.\"));\r\n });\r\n\r\n this.cleanupTimeout();\r\n this.cleanupPingTimer();\r\n\r\n this.closedCallbacks.forEach((c) => c.apply(this, [error]));\r\n }\r\n\r\n private cleanupPingTimer(): void {\r\n if (this.pingServerHandle) {\r\n clearTimeout(this.pingServerHandle);\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): InvocationMessage {\r\n if (nonblocking) {\r\n return {\r\n arguments: args,\r\n target: methodName,\r\n type: MessageType.Invocation,\r\n };\r\n } else {\r\n const id = this.id;\r\n this.id++;\r\n\r\n return {\r\n arguments: args,\r\n invocationId: id.toString(),\r\n target: methodName,\r\n type: MessageType.Invocation,\r\n };\r\n }\r\n }\r\n\r\n private createStreamInvocation(methodName: string, args: any[]): StreamInvocationMessage {\r\n const id = this.id;\r\n this.id++;\r\n\r\n return {\r\n arguments: args,\r\n invocationId: id.toString(),\r\n target: methodName,\r\n type: MessageType.StreamInvocation,\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","// 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}\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","// 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\nimport { HttpClient } from \"./HttpClient\";\r\nimport { ILogger, LogLevel } from \"./ILogger\";\r\nimport { NullLogger } from \"./Loggers\";\r\nimport { IStreamResult, IStreamSubscriber, ISubscription } from \"./Stream\";\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\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 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, content: string | ArrayBuffer, logMessageContent: boolean): 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 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,\r\n responseType,\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 Subject implements IStreamResult {\r\n public observers: Array>;\r\n public cancelCallback: () => Promise;\r\n\r\n constructor(cancelCallback: () => Promise) {\r\n this.observers = [];\r\n this.cancelCallback = cancelCallback;\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\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) {\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 constructor(minimumLogLevel: LogLevel) {\r\n this.minimumLogLevel = minimumLogLevel;\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 console.error(`[${new Date().toISOString()}] ${LogLevel[logLevel]}: ${message}`);\r\n break;\r\n case LogLevel.Warning:\r\n console.warn(`[${new Date().toISOString()}] ${LogLevel[logLevel]}: ${message}`);\r\n break;\r\n case LogLevel.Information:\r\n console.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 console.log(`[${new Date().toISOString()}] ${LogLevel[logLevel]}: ${message}`);\r\n break;\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 { 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 @aspnet/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\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 @aspnet/signalr.InvocationMessage} interface. */\r\n Invocation = 1,\r\n /** Indicates the message is a StreamItem message and implements the {@link @aspnet/signalr.StreamItemMessage} interface. */\r\n StreamItem = 2,\r\n /** Indicates the message is a Completion message and implements the {@link @aspnet/signalr.CompletionMessage} interface. */\r\n Completion = 3,\r\n /** Indicates the message is a Stream Invocation message and implements the {@link @aspnet/signalr.StreamInvocationMessage} interface. */\r\n StreamInvocation = 4,\r\n /** Indicates the message is a Cancel Invocation message and implements the {@link @aspnet/signalr.CancelInvocationMessage} interface. */\r\n CancelInvocation = 5,\r\n /** Indicates the message is a Ping message and implements the {@link @aspnet/signalr.PingMessage} interface. */\r\n Ping = 6,\r\n /** Indicates the message is a Close message and implements the {@link @aspnet/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 @aspnet/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 @aspnet/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 @aspnet/signalr.StreamInvocationMessage} and {@link @aspnet/signalr.CompletionMessage}. It may\r\n * be 'undefined' for an {@link @aspnet/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}\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}\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 @aspnet/signalr.CompletionMessage.error} or {@link @aspnet/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 @aspnet/signalr.CompletionMessage.error} or {@link @aspnet/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 @aspnet/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\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 @aspnet/signalr.TransferFormat} of the protocol. */\r\n readonly transferFormat: TransferFormat;\r\n\r\n /** Creates an array of {@link @aspnet/signalr.HubMessage} objects from the specified serialized representation.\r\n *\r\n * If {@link @aspnet/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} input A string, or ArrayBuffer 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, logger: ILogger): HubMessage[];\r\n\r\n /** Writes the specified {@link @aspnet/signalr.HubMessage} to a string or ArrayBuffer and returns it.\r\n *\r\n * If {@link @aspnet/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 { 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 { HttpTransportType } from \"./ITransport\";\r\nimport { JsonHubProtocol } from \"./JsonHubProtocol\";\r\nimport { NullLogger } from \"./Loggers\";\r\nimport { Arg, ConsoleLogger } from \"./Utils\";\r\n\r\n/** A builder for configuring {@link @aspnet/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 /** Configures console logging for the {@link @aspnet/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 @aspnet/signalr.HubConnectionBuilder} instance, for chaining.\r\n */\r\n public configureLogging(logLevel: LogLevel): HubConnectionBuilder;\r\n\r\n /** Configures custom logging for the {@link @aspnet/signalr.HubConnection}.\r\n *\r\n * @param {ILogger} logger An object implementing the {@link @aspnet/signalr.ILogger} interface, which will be used to write all log messages.\r\n * @returns The {@link @aspnet/signalr.HubConnectionBuilder} instance, for chaining.\r\n */\r\n public configureLogging(logger: ILogger): HubConnectionBuilder;\r\n /** Configures custom logging for the {@link @aspnet/signalr.HubConnection}.\r\n *\r\n * @param {LogLevel | ILogger} logging An object implementing the {@link @aspnet/signalr.ILogger} interface or {@link @aspnet/signalr.LogLevel}.\r\n * @returns The {@link @aspnet/signalr.HubConnectionBuilder} instance, for chaining.\r\n */\r\n public configureLogging(logging: LogLevel | ILogger): HubConnectionBuilder;\r\n public configureLogging(logging: LogLevel | ILogger): HubConnectionBuilder {\r\n Arg.isRequired(logging, \"logging\");\r\n\r\n if (isLogger(logging)) {\r\n this.logger = logging;\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 @aspnet/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 @aspnet/signalr.HubConnectionBuilder} instance, for chaining.\r\n */\r\n public withUrl(url: string): HubConnectionBuilder;\r\n\r\n /** Configures the {@link @aspnet/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 @aspnet/signalr.HubConnectionBuilder} instance, for chaining.\r\n */\r\n public withUrl(url: string, transportType: HttpTransportType): HubConnectionBuilder;\r\n\r\n /** Configures the {@link @aspnet/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 @aspnet/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\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 = transportTypeOrOptions;\r\n } else {\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 @aspnet/signalr.HubConnection} to use the specified Hub Protocol.\r\n *\r\n * @param {IHubProtocol} protocol The {@link @aspnet/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 /** Creates a {@link @aspnet/signalr.HubConnection} from the configuration options specified in this builder.\r\n *\r\n * @returns {HubConnection} The configured {@link @aspnet/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 }\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 { 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 } from \"./Utils\";\r\nimport { WebSocketTransport } from \"./WebSocketTransport\";\r\n\r\n/** @private */\r\nconst enum ConnectionState {\r\n Connecting,\r\n Connected,\r\n Disconnected,\r\n}\r\n\r\n/** @private */\r\nexport interface INegotiateResponse {\r\n connectionId?: string;\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\nlet WebSocketModule: any = null;\r\nlet EventSourceModule: any = null;\r\nif (typeof window === \"undefined\" && 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/** @private */\r\nexport class HttpConnection implements IConnection {\r\n private connectionState: ConnectionState;\r\n private baseUrl: string;\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 startPromise?: Promise;\r\n private stopError?: Error;\r\n private accessTokenFactory?: () => string | Promise;\r\n\r\n public readonly features: any = {};\r\n public onreceive: ((data: string | ArrayBuffer) => void) | null;\r\n public onclose: ((e?: Error) => void) | null;\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 || false;\r\n\r\n const isNode = typeof window === \"undefined\";\r\n if (!isNode && typeof WebSocket !== \"undefined\" && !options.WebSocket) {\r\n options.WebSocket = WebSocket;\r\n } else if (isNode && !options.WebSocket) {\r\n if (WebSocketModule) {\r\n options.WebSocket = WebSocketModule;\r\n }\r\n }\r\n\r\n if (!isNode && typeof EventSource !== \"undefined\" && !options.EventSource) {\r\n options.EventSource = EventSource;\r\n } else if (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.options = options;\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 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 a connection that is not in the 'Disconnected' state.\"));\r\n }\r\n\r\n this.connectionState = ConnectionState.Connecting;\r\n\r\n this.startPromise = this.startInternal(transferFormat);\r\n return this.startPromise;\r\n }\r\n\r\n public send(data: string | ArrayBuffer): Promise {\r\n if (this.connectionState !== ConnectionState.Connected) {\r\n throw new Error(\"Cannot send data if the connection is not in the 'Connected' State.\");\r\n }\r\n\r\n // Transport will not be null if state is connected\r\n return this.transport!.send(data);\r\n }\r\n\r\n public async stop(error?: Error): Promise {\r\n this.connectionState = ConnectionState.Disconnected;\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.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 // The transport's onclose will trigger stopConnection which will run our onclose event.\r\n if (this.transport) {\r\n await this.transport.stop();\r\n this.transport = undefined;\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.transport!.connect(url, transferFormat);\r\n } else {\r\n throw 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.Disconnected) {\r\n return;\r\n }\r\n\r\n if (negotiateResponse.error) {\r\n throw Error(negotiateResponse.error);\r\n }\r\n\r\n if ((negotiateResponse as any).ProtocolVersion) {\r\n throw 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 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 this.transport!.onreceive = this.onreceive;\r\n this.transport!.onclose = (e) => this.stopConnection(e);\r\n\r\n // only change the state if we were connecting to not overwrite\r\n // the state if the connection is already marked as Disconnected\r\n this.changeState(ConnectionState.Connecting, ConnectionState.Connected);\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 throw e;\r\n }\r\n }\r\n\r\n private async getNegotiationResponse(url: string): Promise {\r\n let headers;\r\n if (this.accessTokenFactory) {\r\n const token = await this.accessTokenFactory();\r\n if (token) {\r\n headers = {\r\n [\"Authorization\"]: `Bearer ${token}`,\r\n };\r\n }\r\n }\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,\r\n });\r\n\r\n if (response.statusCode !== 200) {\r\n throw Error(`Unexpected status code returned from negotiate ${response.statusCode}`);\r\n }\r\n\r\n return JSON.parse(response.content as string) as INegotiateResponse;\r\n } catch (e) {\r\n this.logger.log(LogLevel.Error, \"Failed to complete negotiation with the server: \" + e);\r\n throw e;\r\n }\r\n }\r\n\r\n private createConnectUrl(url: string, connectionId: string | null | undefined) {\r\n if (!connectionId) {\r\n return url;\r\n }\r\n return url + (url.indexOf(\"?\") === -1 ? \"?\" : \"&\") + `id=${connectionId}`;\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.connectionId);\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.transport.connect(connectUrl, requestedTransferFormat);\r\n\r\n // only change the state if we were connecting to not overwrite\r\n // the state if the connection is already marked as Disconnected\r\n this.changeState(ConnectionState.Connecting, ConnectionState.Connected);\r\n return;\r\n }\r\n\r\n const transports = negotiateResponse.availableTransports || [];\r\n for (const endpoint of transports) {\r\n this.connectionState = ConnectionState.Connecting;\r\n const transport = this.resolveTransport(endpoint, requestedTransport, requestedTransferFormat);\r\n if (typeof transport === \"number\") {\r\n this.transport = this.constructTransport(transport);\r\n if (!negotiateResponse.connectionId) {\r\n negotiateResponse = await this.getNegotiationResponse(url);\r\n connectUrl = this.createConnectUrl(url, negotiateResponse.connectionId);\r\n }\r\n try {\r\n await this.transport!.connect(connectUrl, requestedTransferFormat);\r\n this.changeState(ConnectionState.Connecting, ConnectionState.Connected);\r\n return;\r\n } catch (ex) {\r\n this.logger.log(LogLevel.Error, `Failed to start the transport '${HttpTransportType[transport]}': ${ex}`);\r\n this.connectionState = ConnectionState.Disconnected;\r\n negotiateResponse.connectionId = undefined;\r\n }\r\n }\r\n }\r\n\r\n throw new Error(\"Unable to initialize any of the available transports.\");\r\n }\r\n\r\n private constructTransport(transport: HttpTransportType) {\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);\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);\r\n case HttpTransportType.LongPolling:\r\n return new LongPollingTransport(this.httpClient, this.accessTokenFactory, this.logger, this.options.logMessageContent || false);\r\n default:\r\n throw new Error(`Unknown transport: ${transport}.`);\r\n }\r\n }\r\n\r\n private resolveTransport(endpoint: IAvailableTransport, requestedTransport: HttpTransportType | undefined, requestedTransferFormat: TransferFormat): HttpTransportType | null {\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 } else {\r\n const transferFormats = endpoint.transferFormats.map((s) => TransferFormat[s]);\r\n if (transportMatches(requestedTransport, transport)) {\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 } else {\r\n this.logger.log(LogLevel.Debug, `Selecting transport '${HttpTransportType[transport]}'.`);\r\n return transport;\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 }\r\n } else {\r\n this.logger.log(LogLevel.Debug, `Skipping transport '${HttpTransportType[transport]}' because it was disabled by the client.`);\r\n }\r\n }\r\n return null;\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 changeState(from: ConnectionState, to: ConnectionState): boolean {\r\n if (this.connectionState === from) {\r\n this.connectionState = to;\r\n return true;\r\n }\r\n return false;\r\n }\r\n\r\n private stopConnection(error?: Error): void {\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\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 this.connectionState = ConnectionState.Disconnected;\r\n\r\n if (this.onclose) {\r\n this.onclose(error);\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 (typeof window === \"undefined\" || !window || !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 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","// 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 { AbortController } from \"./AbortController\";\r\nimport { HttpError, TimeoutError } from \"./Errors\";\r\nimport { HttpClient, HttpRequest } from \"./HttpClient\";\r\nimport { ILogger, LogLevel } from \"./ILogger\";\r\nimport { ITransport, TransferFormat } from \"./ITransport\";\r\nimport { Arg, getDataDetail, 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 pollAbort: AbortController;\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) {\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\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 pollOptions: HttpRequest = {\r\n abortSignal: this.pollAbort.signal,\r\n headers: {},\r\n timeout: 100000,\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);\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 deleteOptions: HttpRequest = {\r\n headers: {},\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\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 { HttpClient } from \"./HttpClient\";\r\nimport { ILogger, LogLevel } from \"./ILogger\";\r\nimport { ITransport, TransferFormat } from \"./ITransport\";\r\nimport { EventSourceConstructor } from \"./Polyfills\";\r\nimport { Arg, getDataDetail, 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 eventSourceConstructor: EventSourceConstructor;\r\n private eventSource?: EventSource;\r\n private url?: string;\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) {\r\n this.httpClient = httpClient;\r\n this.accessTokenFactory = accessTokenFactory;\r\n this.logger = logger;\r\n this.logMessageContent = logMessageContent;\r\n this.eventSourceConstructor = eventSourceConstructor;\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 (typeof window !== \"undefined\") {\r\n eventSource = new this.eventSourceConstructor(url, { withCredentials: true });\r\n } else {\r\n // Non-browser passes cookies via the dictionary\r\n const cookies = this.httpClient.getCookieString(url);\r\n eventSource = new this.eventSourceConstructor(url, { withCredentials: true, headers: { Cookie: cookies } } 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);\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 { ILogger, LogLevel } from \"./ILogger\";\r\nimport { ITransport, TransferFormat } from \"./ITransport\";\r\nimport { WebSocketConstructor } from \"./Polyfills\";\r\nimport { Arg, getDataDetail } 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\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) {\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 }\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, \"(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\r\n if (typeof window === \"undefined\" && cookies) {\r\n // Only pass cookies when in non-browser environments\r\n webSocket = new this.webSocketConstructor(url, undefined, {\r\n headers: {\r\n Cookie: `${cookies}`,\r\n },\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 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 }\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 this.onreceive(message.data);\r\n }\r\n };\r\n\r\n webSocket.onclose = (event: CloseEvent) => this.close(event);\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 // 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 // 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): void {\r\n // webSocket will be null if the transport did not start successfully\r\n this.logger.log(LogLevel.Trace, \"(WebSockets transport) socket closed.\");\r\n if (this.onclose) {\r\n if (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 {\r\n this.onclose();\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 { 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 @aspnet/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 @aspnet/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"],"sourceRoot":""} \ No newline at end of file diff --git a/src/WebCrawler.Web/wwwroot/lib/signalr/signalr.min.js b/src/WebCrawler.Web/wwwroot/lib/signalr/signalr.min.js new file mode 100644 index 0000000..4023508 --- /dev/null +++ b/src/WebCrawler.Web/wwwroot/lib/signalr/signalr.min.js @@ -0,0 +1,17 @@ +(function webpackUniversalModuleDefinition(root,factory){if(typeof exports==="object"&&typeof module==="object")module.exports=factory();else if(typeof define==="function"&&define.amd)define([],factory);else if(typeof exports==="object")exports["signalR"]=factory();else root["signalR"]=factory()})(window,function(){return function(modules){var installedModules={};function __webpack_require__(moduleId){if(installedModules[moduleId]){return installedModules[moduleId].exports}var module=installedModules[moduleId]={i:moduleId,l:false,exports:{}};modules[moduleId].call(module.exports,module,module.exports,__webpack_require__);module.l=true;return module.exports}__webpack_require__.m=modules;__webpack_require__.c=installedModules;__webpack_require__.d=function(exports,name,getter){if(!__webpack_require__.o(exports,name)){Object.defineProperty(exports,name,{enumerable:true,get:getter})}};__webpack_require__.r=function(exports){if(typeof Symbol!=="undefined"&&Symbol.toStringTag){Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"})}Object.defineProperty(exports,"__esModule",{value:true})};__webpack_require__.t=function(value,mode){if(mode&1)value=__webpack_require__(value);if(mode&8)return value;if(mode&4&&typeof value==="object"&&value&&value.__esModule)return value;var ns=Object.create(null);__webpack_require__.r(ns);Object.defineProperty(ns,"default",{enumerable:true,value:value});if(mode&2&&typeof value!="string")for(var key in value)__webpack_require__.d(ns,key,function(key){return value[key]}.bind(null,key));return ns};__webpack_require__.n=function(module){var getter=module&&module.__esModule?function getDefault(){return module["default"]}:function getModuleExports(){return module};__webpack_require__.d(getter,"a",getter);return getter};__webpack_require__.o=function(object,property){return Object.prototype.hasOwnProperty.call(object,property)};__webpack_require__.p="";return __webpack_require__(__webpack_require__.s=0)}([function(module,__webpack_exports__,__webpack_require__){"use strict";__webpack_require__.r(__webpack_exports__);var es6_promise_dist_es6_promise_auto_js__WEBPACK_IMPORTED_MODULE_0__=__webpack_require__(1);var es6_promise_dist_es6_promise_auto_js__WEBPACK_IMPORTED_MODULE_0___default=__webpack_require__.n(es6_promise_dist_es6_promise_auto_js__WEBPACK_IMPORTED_MODULE_0__);var _index__WEBPACK_IMPORTED_MODULE_1__=__webpack_require__(3);__webpack_require__.d(__webpack_exports__,"VERSION",function(){return _index__WEBPACK_IMPORTED_MODULE_1__["VERSION"]});__webpack_require__.d(__webpack_exports__,"AbortError",function(){return _index__WEBPACK_IMPORTED_MODULE_1__["AbortError"]});__webpack_require__.d(__webpack_exports__,"HttpError",function(){return _index__WEBPACK_IMPORTED_MODULE_1__["HttpError"]});__webpack_require__.d(__webpack_exports__,"TimeoutError",function(){return _index__WEBPACK_IMPORTED_MODULE_1__["TimeoutError"]});__webpack_require__.d(__webpack_exports__,"HttpClient",function(){return _index__WEBPACK_IMPORTED_MODULE_1__["HttpClient"]});__webpack_require__.d(__webpack_exports__,"HttpResponse",function(){return _index__WEBPACK_IMPORTED_MODULE_1__["HttpResponse"]});__webpack_require__.d(__webpack_exports__,"DefaultHttpClient",function(){return _index__WEBPACK_IMPORTED_MODULE_1__["DefaultHttpClient"]});__webpack_require__.d(__webpack_exports__,"HubConnection",function(){return _index__WEBPACK_IMPORTED_MODULE_1__["HubConnection"]});__webpack_require__.d(__webpack_exports__,"HubConnectionState",function(){return _index__WEBPACK_IMPORTED_MODULE_1__["HubConnectionState"]});__webpack_require__.d(__webpack_exports__,"HubConnectionBuilder",function(){return _index__WEBPACK_IMPORTED_MODULE_1__["HubConnectionBuilder"]});__webpack_require__.d(__webpack_exports__,"MessageType",function(){return _index__WEBPACK_IMPORTED_MODULE_1__["MessageType"]});__webpack_require__.d(__webpack_exports__,"LogLevel",function(){return _index__WEBPACK_IMPORTED_MODULE_1__["LogLevel"]});__webpack_require__.d(__webpack_exports__,"HttpTransportType",function(){return _index__WEBPACK_IMPORTED_MODULE_1__["HttpTransportType"]});__webpack_require__.d(__webpack_exports__,"TransferFormat",function(){return _index__WEBPACK_IMPORTED_MODULE_1__["TransferFormat"]});__webpack_require__.d(__webpack_exports__,"NullLogger",function(){return _index__WEBPACK_IMPORTED_MODULE_1__["NullLogger"]});__webpack_require__.d(__webpack_exports__,"JsonHubProtocol",function(){return _index__WEBPACK_IMPORTED_MODULE_1__["JsonHubProtocol"]});if(!Uint8Array.prototype.indexOf){Object.defineProperty(Uint8Array.prototype,"indexOf",{value:Array.prototype.indexOf,writable:true})}if(!Uint8Array.prototype.slice){Object.defineProperty(Uint8Array.prototype,"slice",{value:Array.prototype.slice,writable:true})}if(!Uint8Array.prototype.forEach){Object.defineProperty(Uint8Array.prototype,"forEach",{value:Array.prototype.forEach,writable:true})}},function(module,exports,__webpack_require__){(function(global){var require; +/*! + * @overview es6-promise - a tiny implementation of Promises/A+. + * @copyright Copyright (c) 2014 Yehuda Katz, Tom Dale, Stefan Penner and contributors (Conversion to ES6 API by Jake Archibald) + * @license Licensed under MIT license + * See https://raw.githubusercontent.com/stefanpenner/es6-promise/master/LICENSE + * @version v4.2.2+97478eb6 + */ +/*! + * @overview es6-promise - a tiny implementation of Promises/A+. + * @copyright Copyright (c) 2014 Yehuda Katz, Tom Dale, Stefan Penner and contributors (Conversion to ES6 API by Jake Archibald) + * @license Licensed under MIT license + * See https://raw.githubusercontent.com/stefanpenner/es6-promise/master/LICENSE + * @version v4.2.2+97478eb6 + */ +(function(global,factory){true?module.exports=factory():undefined})(this,function(){"use strict";function objectOrFunction(x){var type=typeof x;return x!==null&&(type==="object"||type==="function")}function isFunction(x){return typeof x==="function"}var _isArray=void 0;if(Array.isArray){_isArray=Array.isArray}else{_isArray=function(x){return Object.prototype.toString.call(x)==="[object Array]"}}var isArray=_isArray;var len=0;var vertxNext=void 0;var customSchedulerFn=void 0;var asap=function asap(callback,arg){queue[len]=callback;queue[len+1]=arg;len+=2;if(len===2){if(customSchedulerFn){customSchedulerFn(flush)}else{scheduleFlush()}}};function setScheduler(scheduleFn){customSchedulerFn=scheduleFn}function setAsap(asapFn){asap=asapFn}var browserWindow=typeof window!=="undefined"?window:undefined;var browserGlobal=browserWindow||{};var BrowserMutationObserver=browserGlobal.MutationObserver||browserGlobal.WebKitMutationObserver;var isNode=typeof self==="undefined"&&typeof process!=="undefined"&&{}.toString.call(process)==="[object process]";var isWorker=typeof Uint8ClampedArray!=="undefined"&&typeof importScripts!=="undefined"&&typeof MessageChannel!=="undefined";function useNextTick(){return function(){return process.nextTick(flush)}}function useVertxTimer(){if(typeof vertxNext!=="undefined"){return function(){vertxNext(flush)}}return useSetTimeout()}function useMutationObserver(){var iterations=0;var observer=new BrowserMutationObserver(flush);var node=document.createTextNode("");observer.observe(node,{characterData:true});return function(){node.data=iterations=++iterations%2}}function useMessageChannel(){var channel=new MessageChannel;channel.port1.onmessage=flush;return function(){return channel.port2.postMessage(0)}}function useSetTimeout(){var globalSetTimeout=setTimeout;return function(){return globalSetTimeout(flush,1)}}var queue=new Array(1e3);function flush(){for(var i=0;i=200&&xhr.status<300){resolve(new _HttpClient__WEBPACK_IMPORTED_MODULE_1__["HttpResponse"](xhr.status,xhr.statusText,xhr.response||xhr.responseText))}else{reject(new _Errors__WEBPACK_IMPORTED_MODULE_0__["HttpError"](xhr.statusText,xhr.status))}};xhr.onerror=function(){_this.logger.log(_ILogger__WEBPACK_IMPORTED_MODULE_2__["LogLevel"].Warning,"Error from HTTP request. "+xhr.status+": "+xhr.statusText+".");reject(new _Errors__WEBPACK_IMPORTED_MODULE_0__["HttpError"](xhr.statusText,xhr.status))};xhr.ontimeout=function(){_this.logger.log(_ILogger__WEBPACK_IMPORTED_MODULE_2__["LogLevel"].Warning,"Timeout from HTTP request.");reject(new _Errors__WEBPACK_IMPORTED_MODULE_0__["TimeoutError"])};xhr.send(request.content||"")})};return XhrHttpClient}(_HttpClient__WEBPACK_IMPORTED_MODULE_1__["HttpClient"])},function(module,__webpack_exports__,__webpack_require__){"use strict";__webpack_require__.r(__webpack_exports__);__webpack_require__.d(__webpack_exports__,"LogLevel",function(){return LogLevel});var LogLevel;(function(LogLevel){LogLevel[LogLevel["Trace"]=0]="Trace";LogLevel[LogLevel["Debug"]=1]="Debug";LogLevel[LogLevel["Information"]=2]="Information";LogLevel[LogLevel["Warning"]=3]="Warning";LogLevel[LogLevel["Error"]=4]="Error";LogLevel[LogLevel["Critical"]=5]="Critical";LogLevel[LogLevel["None"]=6]="None"})(LogLevel||(LogLevel={}))},function(module,__webpack_exports__,__webpack_require__){"use strict";__webpack_require__.r(__webpack_exports__);__webpack_require__.d(__webpack_exports__,"HubConnectionState",function(){return HubConnectionState});__webpack_require__.d(__webpack_exports__,"HubConnection",function(){return HubConnection});var _HandshakeProtocol__WEBPACK_IMPORTED_MODULE_0__=__webpack_require__(10);var _IHubProtocol__WEBPACK_IMPORTED_MODULE_1__=__webpack_require__(14);var _ILogger__WEBPACK_IMPORTED_MODULE_2__=__webpack_require__(8);var _Utils__WEBPACK_IMPORTED_MODULE_3__=__webpack_require__(12);var __awaiter=undefined&&undefined.__awaiter||function(thisArg,_arguments,P,generator){return new(P||(P=Promise))(function(resolve,reject){function fulfilled(value){try{step(generator.next(value))}catch(e){reject(e)}}function rejected(value){try{step(generator["throw"](value))}catch(e){reject(e)}}function step(result){result.done?resolve(result.value):new P(function(resolve){resolve(result.value)}).then(fulfilled,rejected)}step((generator=generator.apply(thisArg,_arguments||[])).next())})};var __generator=undefined&&undefined.__generator||function(thisArg,body){var _={label:0,sent:function(){if(t[0]&1)throw t[1];return t[1]},trys:[],ops:[]},f,y,t,g;return g={next:verb(0),throw:verb(1),return:verb(2)},typeof Symbol==="function"&&(g[Symbol.iterator]=function(){return this}),g;function verb(n){return function(v){return step([n,v])}}function step(op){if(f)throw new TypeError("Generator is already executing.");while(_)try{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;if(y=0,t)op=[op[0]&2,t.value];switch(op[0]){case 0:case 1:t=op;break;case 4:_.label++;return{value:op[1],done:false};case 5:_.label++;y=op[1];op=[0];continue;case 7:op=_.ops.pop();_.trys.pop();continue;default:if(!(t=_.trys,t=t.length>0&&t[t.length-1])&&(op[0]===6||op[0]===2)){_=0;continue}if(op[0]===3&&(!t||op[1]>t[0]&&op[1]responseLength?binaryData.slice(responseLength).buffer:null}else{var textData=data;var separatorIndex=textData.indexOf(_TextMessageFormat__WEBPACK_IMPORTED_MODULE_0__["TextMessageFormat"].RecordSeparator);if(separatorIndex===-1){throw new Error("Message is incomplete.")}var responseLength=separatorIndex+1;messageData=textData.substring(0,responseLength);remainingData=textData.length>responseLength?textData.substring(responseLength):null}var messages=_TextMessageFormat__WEBPACK_IMPORTED_MODULE_0__["TextMessageFormat"].parse(messageData);var response=JSON.parse(messages[0]);if(response.type){throw new Error("Expected a handshake response from the server.")}responseMessage=response;return[remainingData,responseMessage]};return HandshakeProtocol}()},function(module,__webpack_exports__,__webpack_require__){"use strict";__webpack_require__.r(__webpack_exports__);__webpack_require__.d(__webpack_exports__,"TextMessageFormat",function(){return TextMessageFormat});var TextMessageFormat=function(){function TextMessageFormat(){}TextMessageFormat.write=function(output){return""+output+TextMessageFormat.RecordSeparator};TextMessageFormat.parse=function(input){if(input[input.length-1]!==TextMessageFormat.RecordSeparator){throw new Error("Message is incomplete.")}var messages=input.split(TextMessageFormat.RecordSeparator);messages.pop();return messages};TextMessageFormat.RecordSeparatorCode=30;TextMessageFormat.RecordSeparator=String.fromCharCode(TextMessageFormat.RecordSeparatorCode);return TextMessageFormat}()},function(module,__webpack_exports__,__webpack_require__){"use strict";__webpack_require__.r(__webpack_exports__);__webpack_require__.d(__webpack_exports__,"Arg",function(){return Arg});__webpack_require__.d(__webpack_exports__,"getDataDetail",function(){return getDataDetail});__webpack_require__.d(__webpack_exports__,"formatArrayBuffer",function(){return formatArrayBuffer});__webpack_require__.d(__webpack_exports__,"isArrayBuffer",function(){return isArrayBuffer});__webpack_require__.d(__webpack_exports__,"sendMessage",function(){return sendMessage});__webpack_require__.d(__webpack_exports__,"createLogger",function(){return createLogger});__webpack_require__.d(__webpack_exports__,"Subject",function(){return Subject});__webpack_require__.d(__webpack_exports__,"SubjectSubscription",function(){return SubjectSubscription});__webpack_require__.d(__webpack_exports__,"ConsoleLogger",function(){return ConsoleLogger});var _ILogger__WEBPACK_IMPORTED_MODULE_0__=__webpack_require__(8);var _Loggers__WEBPACK_IMPORTED_MODULE_1__=__webpack_require__(13);var __awaiter=undefined&&undefined.__awaiter||function(thisArg,_arguments,P,generator){return new(P||(P=Promise))(function(resolve,reject){function fulfilled(value){try{step(generator.next(value))}catch(e){reject(e)}}function rejected(value){try{step(generator["throw"](value))}catch(e){reject(e)}}function step(result){result.done?resolve(result.value):new P(function(resolve){resolve(result.value)}).then(fulfilled,rejected)}step((generator=generator.apply(thisArg,_arguments||[])).next())})};var __generator=undefined&&undefined.__generator||function(thisArg,body){var _={label:0,sent:function(){if(t[0]&1)throw t[1];return t[1]},trys:[],ops:[]},f,y,t,g;return g={next:verb(0),throw:verb(1),return:verb(2)},typeof Symbol==="function"&&(g[Symbol.iterator]=function(){return this}),g;function verb(n){return function(v){return step([n,v])}}function step(op){if(f)throw new TypeError("Generator is already executing.");while(_)try{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;if(y=0,t)op=[op[0]&2,t.value];switch(op[0]){case 0:case 1:t=op;break;case 4:_.label++;return{value:op[1],done:false};case 5:_.label++;y=op[1];op=[0];continue;case 7:op=_.ops.pop();_.trys.pop();continue;default:if(!(t=_.trys,t=t.length>0&&t[t.length-1])&&(op[0]===6||op[0]===2)){_=0;continue}if(op[0]===3&&(!t||op[1]>t[0]&&op[1]-1){this.subject.observers.splice(index,1)}if(this.subject.observers.length===0){this.subject.cancelCallback().catch(function(_){})}};return SubjectSubscription}();var ConsoleLogger=function(){function ConsoleLogger(minimumLogLevel){this.minimumLogLevel=minimumLogLevel}ConsoleLogger.prototype.log=function(logLevel,message){if(logLevel>=this.minimumLogLevel){switch(logLevel){case _ILogger__WEBPACK_IMPORTED_MODULE_0__["LogLevel"].Critical:case _ILogger__WEBPACK_IMPORTED_MODULE_0__["LogLevel"].Error:console.error("["+(new Date).toISOString()+"] "+_ILogger__WEBPACK_IMPORTED_MODULE_0__["LogLevel"][logLevel]+": "+message);break;case _ILogger__WEBPACK_IMPORTED_MODULE_0__["LogLevel"].Warning:console.warn("["+(new Date).toISOString()+"] "+_ILogger__WEBPACK_IMPORTED_MODULE_0__["LogLevel"][logLevel]+": "+message);break;case _ILogger__WEBPACK_IMPORTED_MODULE_0__["LogLevel"].Information:console.info("["+(new Date).toISOString()+"] "+_ILogger__WEBPACK_IMPORTED_MODULE_0__["LogLevel"][logLevel]+": "+message);break;default:console.log("["+(new Date).toISOString()+"] "+_ILogger__WEBPACK_IMPORTED_MODULE_0__["LogLevel"][logLevel]+": "+message);break}}};return ConsoleLogger}()},function(module,__webpack_exports__,__webpack_require__){"use strict";__webpack_require__.r(__webpack_exports__);__webpack_require__.d(__webpack_exports__,"NullLogger",function(){return NullLogger});var NullLogger=function(){function NullLogger(){}NullLogger.prototype.log=function(_logLevel,_message){};NullLogger.instance=new NullLogger;return NullLogger}()},function(module,__webpack_exports__,__webpack_require__){"use strict";__webpack_require__.r(__webpack_exports__);__webpack_require__.d(__webpack_exports__,"MessageType",function(){return MessageType});var MessageType;(function(MessageType){MessageType[MessageType["Invocation"]=1]="Invocation";MessageType[MessageType["StreamItem"]=2]="StreamItem";MessageType[MessageType["Completion"]=3]="Completion";MessageType[MessageType["StreamInvocation"]=4]="StreamInvocation";MessageType[MessageType["CancelInvocation"]=5]="CancelInvocation";MessageType[MessageType["Ping"]=6]="Ping";MessageType[MessageType["Close"]=7]="Close"})(MessageType||(MessageType={}))},function(module,__webpack_exports__,__webpack_require__){"use strict";__webpack_require__.r(__webpack_exports__);__webpack_require__.d(__webpack_exports__,"HubConnectionBuilder",function(){return HubConnectionBuilder});var _HttpConnection__WEBPACK_IMPORTED_MODULE_0__=__webpack_require__(16);var _HubConnection__WEBPACK_IMPORTED_MODULE_1__=__webpack_require__(9);var _JsonHubProtocol__WEBPACK_IMPORTED_MODULE_2__=__webpack_require__(22);var _Loggers__WEBPACK_IMPORTED_MODULE_3__=__webpack_require__(13);var _Utils__WEBPACK_IMPORTED_MODULE_4__=__webpack_require__(12);var HubConnectionBuilder=function(){function HubConnectionBuilder(){}HubConnectionBuilder.prototype.configureLogging=function(logging){_Utils__WEBPACK_IMPORTED_MODULE_4__["Arg"].isRequired(logging,"logging");if(isLogger(logging)){this.logger=logging}else{this.logger=new _Utils__WEBPACK_IMPORTED_MODULE_4__["ConsoleLogger"](logging)}return this};HubConnectionBuilder.prototype.withUrl=function(url,transportTypeOrOptions){_Utils__WEBPACK_IMPORTED_MODULE_4__["Arg"].isRequired(url,"url");this.url=url;if(typeof transportTypeOrOptions==="object"){this.httpConnectionOptions=transportTypeOrOptions}else{this.httpConnectionOptions={transport:transportTypeOrOptions}}return this};HubConnectionBuilder.prototype.withHubProtocol=function(protocol){_Utils__WEBPACK_IMPORTED_MODULE_4__["Arg"].isRequired(protocol,"protocol");this.protocol=protocol;return this};HubConnectionBuilder.prototype.build=function(){var httpConnectionOptions=this.httpConnectionOptions||{};if(httpConnectionOptions.logger===undefined){httpConnectionOptions.logger=this.logger}if(!this.url){throw new Error("The 'HubConnectionBuilder.withUrl' method must be called before building the connection.")}var connection=new _HttpConnection__WEBPACK_IMPORTED_MODULE_0__["HttpConnection"](this.url,httpConnectionOptions);return _HubConnection__WEBPACK_IMPORTED_MODULE_1__["HubConnection"].create(connection,this.logger||_Loggers__WEBPACK_IMPORTED_MODULE_3__["NullLogger"].instance,this.protocol||new _JsonHubProtocol__WEBPACK_IMPORTED_MODULE_2__["JsonHubProtocol"])};return HubConnectionBuilder}();function isLogger(logger){return logger.log!==undefined}},function(module,__webpack_exports__,__webpack_require__){"use strict";__webpack_require__.r(__webpack_exports__);__webpack_require__.d(__webpack_exports__,"HttpConnection",function(){return HttpConnection});var _DefaultHttpClient__WEBPACK_IMPORTED_MODULE_0__=__webpack_require__(6);var _ILogger__WEBPACK_IMPORTED_MODULE_1__=__webpack_require__(8);var _ITransport__WEBPACK_IMPORTED_MODULE_2__=__webpack_require__(17);var _LongPollingTransport__WEBPACK_IMPORTED_MODULE_3__=__webpack_require__(18);var _ServerSentEventsTransport__WEBPACK_IMPORTED_MODULE_4__=__webpack_require__(20);var _Utils__WEBPACK_IMPORTED_MODULE_5__=__webpack_require__(12);var _WebSocketTransport__WEBPACK_IMPORTED_MODULE_6__=__webpack_require__(21);var __awaiter=undefined&&undefined.__awaiter||function(thisArg,_arguments,P,generator){return new(P||(P=Promise))(function(resolve,reject){function fulfilled(value){try{step(generator.next(value))}catch(e){reject(e)}}function rejected(value){try{step(generator["throw"](value))}catch(e){reject(e)}}function step(result){result.done?resolve(result.value):new P(function(resolve){resolve(result.value)}).then(fulfilled,rejected)}step((generator=generator.apply(thisArg,_arguments||[])).next())})};var __generator=undefined&&undefined.__generator||function(thisArg,body){var _={label:0,sent:function(){if(t[0]&1)throw t[1];return t[1]},trys:[],ops:[]},f,y,t,g;return g={next:verb(0),throw:verb(1),return:verb(2)},typeof Symbol==="function"&&(g[Symbol.iterator]=function(){return this}),g;function verb(n){return function(v){return step([n,v])}}function step(op){if(f)throw new TypeError("Generator is already executing.");while(_)try{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;if(y=0,t)op=[op[0]&2,t.value];switch(op[0]){case 0:case 1:t=op;break;case 4:_.label++;return{value:op[1],done:false};case 5:_.label++;y=op[1];op=[0];continue;case 7:op=_.ops.pop();_.trys.pop();continue;default:if(!(t=_.trys,t=t.length>0&&t[t.length-1])&&(op[0]===6||op[0]===2)){_=0;continue}if(op[0]===3&&(!t||op[1]>t[0]&&op[1]=0){if(transport===_ITransport__WEBPACK_IMPORTED_MODULE_2__["HttpTransportType"].WebSockets&&!this.options.WebSocket||transport===_ITransport__WEBPACK_IMPORTED_MODULE_2__["HttpTransportType"].ServerSentEvents&&!this.options.EventSource){this.logger.log(_ILogger__WEBPACK_IMPORTED_MODULE_1__["LogLevel"].Debug,"Skipping transport '"+_ITransport__WEBPACK_IMPORTED_MODULE_2__["HttpTransportType"][transport]+"' because it is not supported in your environment.'")}else{this.logger.log(_ILogger__WEBPACK_IMPORTED_MODULE_1__["LogLevel"].Debug,"Selecting transport '"+_ITransport__WEBPACK_IMPORTED_MODULE_2__["HttpTransportType"][transport]+"'.");return transport}}else{this.logger.log(_ILogger__WEBPACK_IMPORTED_MODULE_1__["LogLevel"].Debug,"Skipping transport '"+_ITransport__WEBPACK_IMPORTED_MODULE_2__["HttpTransportType"][transport]+"' because it does not support the requested transfer format '"+_ITransport__WEBPACK_IMPORTED_MODULE_2__["TransferFormat"][requestedTransferFormat]+"'.")}}else{this.logger.log(_ILogger__WEBPACK_IMPORTED_MODULE_1__["LogLevel"].Debug,"Skipping transport '"+_ITransport__WEBPACK_IMPORTED_MODULE_2__["HttpTransportType"][transport]+"' because it was disabled by the client.")}}return null};HttpConnection.prototype.isITransport=function(transport){return transport&&typeof transport==="object"&&"connect"in transport};HttpConnection.prototype.changeState=function(from,to){if(this.connectionState===from){this.connectionState=to;return true}return false};HttpConnection.prototype.stopConnection=function(error){this.transport=undefined;error=this.stopError||error;if(error){this.logger.log(_ILogger__WEBPACK_IMPORTED_MODULE_1__["LogLevel"].Error,"Connection disconnected with error '"+error+"'.")}else{this.logger.log(_ILogger__WEBPACK_IMPORTED_MODULE_1__["LogLevel"].Information,"Connection disconnected.")}this.connectionState=2;if(this.onclose){this.onclose(error)}};HttpConnection.prototype.resolveUrl=function(url){if(url.lastIndexOf("https://",0)===0||url.lastIndexOf("http://",0)===0){return url}if(typeof window==="undefined"||!window||!window.document){throw new Error("Cannot resolve '"+url+"'.")}var aTag=window.document.createElement("a");aTag.href=url;this.logger.log(_ILogger__WEBPACK_IMPORTED_MODULE_1__["LogLevel"].Information,"Normalizing '"+url+"' to '"+aTag.href+"'.");return aTag.href};HttpConnection.prototype.resolveNegotiateUrl=function(url){var index=url.indexOf("?");var negotiateUrl=url.substring(0,index===-1?url.length:index);if(negotiateUrl[negotiateUrl.length-1]!=="/"){negotiateUrl+="/"}negotiateUrl+="negotiate";negotiateUrl+=index===-1?"":url.substring(index);return negotiateUrl};return HttpConnection}();function transportMatches(requestedTransport,actualTransport){return!requestedTransport||(actualTransport&requestedTransport)!==0}},function(module,__webpack_exports__,__webpack_require__){"use strict";__webpack_require__.r(__webpack_exports__);__webpack_require__.d(__webpack_exports__,"HttpTransportType",function(){return HttpTransportType});__webpack_require__.d(__webpack_exports__,"TransferFormat",function(){return TransferFormat});var HttpTransportType;(function(HttpTransportType){HttpTransportType[HttpTransportType["None"]=0]="None";HttpTransportType[HttpTransportType["WebSockets"]=1]="WebSockets";HttpTransportType[HttpTransportType["ServerSentEvents"]=2]="ServerSentEvents";HttpTransportType[HttpTransportType["LongPolling"]=4]="LongPolling"})(HttpTransportType||(HttpTransportType={}));var TransferFormat;(function(TransferFormat){TransferFormat[TransferFormat["Text"]=1]="Text";TransferFormat[TransferFormat["Binary"]=2]="Binary"})(TransferFormat||(TransferFormat={}))},function(module,__webpack_exports__,__webpack_require__){"use strict";__webpack_require__.r(__webpack_exports__);__webpack_require__.d(__webpack_exports__,"LongPollingTransport",function(){return LongPollingTransport});var _AbortController__WEBPACK_IMPORTED_MODULE_0__=__webpack_require__(19);var _Errors__WEBPACK_IMPORTED_MODULE_1__=__webpack_require__(4);var _ILogger__WEBPACK_IMPORTED_MODULE_2__=__webpack_require__(8);var _ITransport__WEBPACK_IMPORTED_MODULE_3__=__webpack_require__(17);var _Utils__WEBPACK_IMPORTED_MODULE_4__=__webpack_require__(12);var __awaiter=undefined&&undefined.__awaiter||function(thisArg,_arguments,P,generator){return new(P||(P=Promise))(function(resolve,reject){function fulfilled(value){try{step(generator.next(value))}catch(e){reject(e)}}function rejected(value){try{step(generator["throw"](value))}catch(e){reject(e)}}function step(result){result.done?resolve(result.value):new P(function(resolve){resolve(result.value)}).then(fulfilled,rejected)}step((generator=generator.apply(thisArg,_arguments||[])).next())})};var __generator=undefined&&undefined.__generator||function(thisArg,body){var _={label:0,sent:function(){if(t[0]&1)throw t[1];return t[1]},trys:[],ops:[]},f,y,t,g;return g={next:verb(0),throw:verb(1),return:verb(2)},typeof Symbol==="function"&&(g[Symbol.iterator]=function(){return this}),g;function verb(n){return function(v){return step([n,v])}}function step(op){if(f)throw new TypeError("Generator is already executing.");while(_)try{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;if(y=0,t)op=[op[0]&2,t.value];switch(op[0]){case 0:case 1:t=op;break;case 4:_.label++;return{value:op[1],done:false};case 5:_.label++;y=op[1];op=[0];continue;case 7:op=_.ops.pop();_.trys.pop();continue;default:if(!(t=_.trys,t=t.length>0&&t[t.length-1])&&(op[0]===6||op[0]===2)){_=0;continue}if(op[0]===3&&(!t||op[1]>t[0]&&op[1]0&&t[t.length-1])&&(op[0]===6||op[0]===2)){_=0;continue}if(op[0]===3&&(!t||op[1]>t[0]&&op[1]0&&t[t.length-1])&&(op[0]===6||op[0]===2)){_=0;continue}if(op[0]===3&&(!t||op[1]>t[0]&&op[1] - Copyright © 2015-2018 Petabridge, LLC + Copyright © 2015-2019 Petabridge, LLC Petabridge - 0.9.2 - Upgraded to Akka.NET 1.3.7. + 0.2.2 + Added shared DevOps infrastructure. +Setting the stage for the use of Phobos in future releases. +Resolved [Install pbm on all nodes](https://github.com/petabridge/Cluster.WebCrawler/issues/10) @@ -13,11 +15,11 @@ $(NoWarn);CS1591 - 2.3.1 + 2.4.1 1.3.11 - 0.1.3 + 0.2.0 0.1.0 0.4.1 - netcoreapp2.0 + netcoreapp2.1 \ No newline at end of file diff --git a/yaml/k8s-aws-web-loadbalancer.yaml b/yaml/k8s-aws-web-loadbalancer.yaml new file mode 100644 index 0000000..8e8fd7f --- /dev/null +++ b/yaml/k8s-aws-web-loadbalancer.yaml @@ -0,0 +1,14 @@ +apiVersion: v1 +kind: Service +metadata: + name: web-cluster-http + labels: + app: web-cluster +spec: + type: LoadBalancer + ports: + - protocol: TCP + port: 80 + targetPort: 9376 + selector: + app: web-cluster \ No newline at end of file diff --git a/yaml/k8s-crawler-service.yaml b/yaml/k8s-crawler-service.yaml new file mode 100644 index 0000000..0bc8bbf --- /dev/null +++ b/yaml/k8s-crawler-service.yaml @@ -0,0 +1,53 @@ +apiVersion: v1 +kind: Service +metadata: + name: crawler + labels: + app: crawler +spec: + clusterIP: None + ports: + - port: 5213 + selector: + app: crawler +--- +apiVersion: apps/v1 +kind: StatefulSet +metadata: + name: crawler + labels: + app: crawler +spec: + serviceName: crawler + replicas: 3 + selector: + matchLabels: + app: crawler + template: + metadata: + labels: + app: crawler + spec: + terminationGracePeriodSeconds: 35 + containers: + - name: crawler + image: webcrawler.crawlservice:0.2.2 + lifecycle: + preStop: + exec: + command: ["/bin/sh", "-c", "pbm 127.0.0.1:9110 cluster leave"] + env: + - name: POD_NAME + valueFrom: + fieldRef: + fieldPath: metadata.name + - name: CLUSTER_IP + value: "$(POD_NAME).crawler" + - name: CLUSTER_SEEDS + value: akka.tcp://webcrawler@lighthouse-0.lighthouse:4053,akka.tcp://webcrawler@lighthouse-1.lighthouse:4053,akka.tcp://webcrawler@lighthouse-2.lighthouse:4053 + livenessProbe: + tcpSocket: + port: 5213 + ports: + - containerPort: 5213 + protocol: TCP \ No newline at end of file diff --git a/yaml/k8s-lighthouse-service.yaml b/yaml/k8s-lighthouse-service.yaml new file mode 100644 index 0000000..5e6b006 --- /dev/null +++ b/yaml/k8s-lighthouse-service.yaml @@ -0,0 +1,55 @@ +apiVersion: v1 +kind: Service +metadata: + name: lighthouse + labels: + app: lighthouse +spec: + clusterIP: None + ports: + - port: 4053 + selector: + app: lighthouse +--- +apiVersion: apps/v1 +kind: StatefulSet +metadata: + name: lighthouse + labels: + app: lighthouse +spec: + serviceName: lighthouse + replicas: 3 + selector: + matchLabels: + app: lighthouse + template: + metadata: + labels: + app: lighthouse + spec: + terminationGracePeriodSeconds: 35 + containers: + - name: lighthouse + image: webcrawler.lighthouse:0.2.2 + lifecycle: + preStop: + exec: + command: ["/bin/sh", "-c", "pbm 127.0.0.1:9110 cluster leave"] + env: + - name: ACTORSYSTEM + value: webcrawler + - name: POD_NAME + valueFrom: + fieldRef: + fieldPath: metadata.name + - name: CLUSTER_IP + value: "$(POD_NAME).lighthouse" + - name: CLUSTER_SEEDS + value: akka.tcp://webcrawler@lighthouse-0.lighthouse:4053,akka.tcp://webcrawler@lighthouse-1.lighthouse:4053,akka.tcp://webcrawler@lighthouse-2.lighthouse:4053 + livenessProbe: + tcpSocket: + port: 4053 + ports: + - containerPort: 4053 + protocol: TCP \ No newline at end of file diff --git a/yaml/k8s-local-web-nodeport.yaml b/yaml/k8s-local-web-nodeport.yaml new file mode 100644 index 0000000..81b5c67 --- /dev/null +++ b/yaml/k8s-local-web-nodeport.yaml @@ -0,0 +1,16 @@ +apiVersion: v1 +kind: Service +metadata: + name: web-cluster-http + labels: + app: web-cluster + tier: frontend +spec: + type: LoadBalancer + ports: + - nodePort: 31231 + protocol: TCP + port: 80 + targetPort: 80 + selector: + app: web-cluster \ No newline at end of file diff --git a/yaml/k8s-tracker-service.yaml b/yaml/k8s-tracker-service.yaml new file mode 100644 index 0000000..625024c --- /dev/null +++ b/yaml/k8s-tracker-service.yaml @@ -0,0 +1,53 @@ +apiVersion: v1 +kind: Service +metadata: + name: tracker + labels: + app: tracker +spec: + clusterIP: None + ports: + - port: 5212 + selector: + app: tracker +--- +apiVersion: apps/v1 +kind: StatefulSet +metadata: + name: tracker + labels: + app: tracker +spec: + serviceName: tracker + replicas: 3 + selector: + matchLabels: + app: tracker + template: + metadata: + labels: + app: tracker + spec: + terminationGracePeriodSeconds: 35 + containers: + - name: tracker + image: webcrawler.trackerservice:0.2.2 + lifecycle: + preStop: + exec: + command: ["/bin/sh", "-c", "pbm 127.0.0.1:9110 cluster leave"] + env: + - name: POD_NAME + valueFrom: + fieldRef: + fieldPath: metadata.name + - name: CLUSTER_IP + value: "$(POD_NAME).tracker" + - name: CLUSTER_SEEDS + value: akka.tcp://webcrawler@lighthouse-0.lighthouse:4053,akka.tcp://webcrawler@lighthouse-1.lighthouse:4053,akka.tcp://webcrawler@lighthouse-2.lighthouse:4053 + livenessProbe: + tcpSocket: + port: 5212 + ports: + - containerPort: 5212 + protocol: TCP \ No newline at end of file diff --git a/yaml/k8s-web-service.yaml b/yaml/k8s-web-service.yaml new file mode 100644 index 0000000..c5451f3 --- /dev/null +++ b/yaml/k8s-web-service.yaml @@ -0,0 +1,58 @@ +apiVersion: v1 +kind: Service +metadata: + name: web-cluster + labels: + app: web-cluster +spec: + clusterIP: None + ports: + - port: 16666 + selector: + app: web-cluster +--- +apiVersion: apps/v1 +kind: StatefulSet +metadata: + name: web-cluster + labels: + app: web-cluster +spec: + serviceName: web-cluster + replicas: 3 + selector: + matchLabels: + app: web-cluster + template: + metadata: + labels: + app: web-cluster + spec: + terminationGracePeriodSeconds: 35 + containers: + - name: web-cluster + image: webcrawler.web:0.2.2 + lifecycle: + preStop: + exec: + command: ["/bin/sh", "-c", "pbm 127.0.0.1:9110 cluster leave"] + env: + - name: POD_NAME + valueFrom: + fieldRef: + fieldPath: metadata.name + - name: CLUSTER_IP + value: "$(POD_NAME).web-cluster" + - name: CLUSTER_SEEDS + value: akka.tcp://webcrawler@lighthouse-0.lighthouse:4053,akka.tcp://webcrawler@lighthouse-1.lighthouse:4053,akka.tcp://webcrawler@lighthouse-2.lighthouse:4053 + livenessProbe: + tcpSocket: + port: 16666 + readinessProbe: + tcpSocket: + port: 80 + ports: + - containerPort: 16666 + protocol: TCP + - containerPort: 80 + protocol: TCP \ No newline at end of file