mirror of
https://github.com/aspnet/JavaScriptServices.git
synced 2025-12-23 10:08:57 +00:00
Compare commits
22 Commits
rybrande/m
...
rel/2.0.0-
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
da705176c8 | ||
|
|
4b54cd1a32 | ||
|
|
bf1121f402 | ||
|
|
531a22774a | ||
|
|
9b7994bc9b | ||
|
|
c01193dd7b | ||
|
|
e6708aa549 | ||
|
|
c03fea4018 | ||
|
|
8a8db2317c | ||
|
|
26d666d4f1 | ||
|
|
e024e5bdcd | ||
|
|
25be429d57 | ||
|
|
4ed3fab3bc | ||
|
|
8da62b8565 | ||
|
|
39e6121937 | ||
|
|
c002937377 | ||
|
|
eb415b6282 | ||
|
|
dcbe4b1c33 | ||
|
|
f2175e6c23 | ||
|
|
064f43ab26 | ||
|
|
685f7da091 | ||
|
|
e6309ba784 |
21
.appveyor.yml
Executable file
21
.appveyor.yml
Executable file
@@ -0,0 +1,21 @@
|
||||
init:
|
||||
- git config --global core.autocrlf true
|
||||
install:
|
||||
- ps: Install-Product node 6.9.2 x64
|
||||
branches:
|
||||
only:
|
||||
- master
|
||||
- release
|
||||
- dev
|
||||
- /^(.*\/)?ci-.*$/
|
||||
- /^rel\/.*/
|
||||
build_script:
|
||||
- ps: .\run.ps1 default-build
|
||||
clone_depth: 1
|
||||
environment:
|
||||
global:
|
||||
DOTNET_SKIP_FIRST_TIME_EXPERIENCE: true
|
||||
DOTNET_CLI_TELEMETRY_OPTOUT: 1
|
||||
test: off
|
||||
deploy: off
|
||||
os: Visual Studio 2017
|
||||
51
.gitattributes
vendored
Executable file
51
.gitattributes
vendored
Executable file
@@ -0,0 +1,51 @@
|
||||
*.doc diff=astextplain
|
||||
*.DOC diff=astextplain
|
||||
*.docx diff=astextplain
|
||||
*.DOCX diff=astextplain
|
||||
*.dot diff=astextplain
|
||||
*.DOT diff=astextplain
|
||||
*.pdf diff=astextplain
|
||||
*.PDF diff=astextplain
|
||||
*.rtf diff=astextplain
|
||||
*.RTF diff=astextplain
|
||||
|
||||
*.jpg binary
|
||||
*.png binary
|
||||
*.gif binary
|
||||
|
||||
*.cs text=auto diff=csharp
|
||||
*.vb text=auto
|
||||
*.resx text=auto
|
||||
*.c text=auto
|
||||
*.cpp text=auto
|
||||
*.cxx text=auto
|
||||
*.h text=auto
|
||||
*.hxx text=auto
|
||||
*.py text=auto
|
||||
*.rb text=auto
|
||||
*.java text=auto
|
||||
*.html text=auto
|
||||
*.htm text=auto
|
||||
*.css text=auto
|
||||
*.scss text=auto
|
||||
*.sass text=auto
|
||||
*.less text=auto
|
||||
*.js text=auto
|
||||
*.lisp text=auto
|
||||
*.clj text=auto
|
||||
*.sql text=auto
|
||||
*.php text=auto
|
||||
*.lua text=auto
|
||||
*.m text=auto
|
||||
*.asm text=auto
|
||||
*.erl text=auto
|
||||
*.fs text=auto
|
||||
*.fsx text=auto
|
||||
*.hs text=auto
|
||||
|
||||
*.csproj text=auto
|
||||
*.vbproj text=auto
|
||||
*.fsproj text=auto
|
||||
*.dbproj text=auto
|
||||
*.sln text=auto eol=crlf
|
||||
*.sh eol=lf
|
||||
19
.travis.yml
Executable file
19
.travis.yml
Executable file
@@ -0,0 +1,19 @@
|
||||
language: csharp
|
||||
sudo: required
|
||||
dist: trusty
|
||||
addons:
|
||||
apt:
|
||||
packages:
|
||||
- gettext
|
||||
- libcurl4-openssl-dev
|
||||
- libicu-dev
|
||||
- libssl-dev
|
||||
- libunwind8
|
||||
- zlib1g
|
||||
mono: none
|
||||
os:
|
||||
- linux
|
||||
- osx
|
||||
osx_image: xcode7.1
|
||||
script:
|
||||
- ./build.sh
|
||||
4
CONTRIBUTING.md
Normal file
4
CONTRIBUTING.md
Normal file
@@ -0,0 +1,4 @@
|
||||
Contributing
|
||||
======
|
||||
|
||||
Information on contributing to this repo is in the [Contributing Guide](https://github.com/aspnet/Home/blob/dev/CONTRIBUTING.md) in the Home repo.
|
||||
@@ -1,7 +1,6 @@
|
||||
<Project>
|
||||
<Import Project="version.props" />
|
||||
<Import Project="build\dependencies.props" />
|
||||
<Import Project="build\sources.props" />
|
||||
|
||||
<PropertyGroup>
|
||||
<Product>Microsoft ASP.NET Core</Product>
|
||||
@@ -10,6 +9,7 @@
|
||||
<RepositoryRoot>$(MSBuildThisFileDirectory)</RepositoryRoot>
|
||||
<AssemblyOriginatorKeyFile>$(MSBuildThisFileDirectory)build\Key.snk</AssemblyOriginatorKeyFile>
|
||||
<SignAssembly>true</SignAssembly>
|
||||
<PublicSign Condition="'$(OS)' != 'Windows_NT'">true</PublicSign>
|
||||
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
|
||||
</PropertyGroup>
|
||||
</Project>
|
||||
5
Directory.Build.targets
Normal file
5
Directory.Build.targets
Normal file
@@ -0,0 +1,5 @@
|
||||
<Project>
|
||||
<PropertyGroup>
|
||||
<RuntimeFrameworkVersion Condition=" '$(TargetFramework)' == 'netcoreapp2.0' ">$(MicrosoftNETCoreApp20PackageVersion)</RuntimeFrameworkVersion>
|
||||
</PropertyGroup>
|
||||
</Project>
|
||||
46
JavaScriptServices.sln
Normal file
46
JavaScriptServices.sln
Normal file
@@ -0,0 +1,46 @@
|
||||
|
||||
Microsoft Visual Studio Solution File, Format Version 12.00
|
||||
# Visual Studio 15
|
||||
VisualStudioVersion = 15.0.27019.1
|
||||
MinimumVisualStudioVersion = 15.0.26730.03
|
||||
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "src", "src", "{27304DDE-AFB2-4F8B-B765-E3E2F11E886C}"
|
||||
ProjectSection(SolutionItems) = preProject
|
||||
src\Directory.Build.props = src\Directory.Build.props
|
||||
EndProjectSection
|
||||
EndProject
|
||||
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "misc", "misc", "{99EAF1FE-22C8-4526-BE78-74B24125D37F}"
|
||||
ProjectSection(SolutionItems) = preProject
|
||||
.gitignore = .gitignore
|
||||
global.json = global.json
|
||||
README.md = README.md
|
||||
EndProjectSection
|
||||
EndProject
|
||||
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{645F7363-1240-4FB6-9422-B32A327C979F}"
|
||||
ProjectSection(SolutionItems) = preProject
|
||||
Directory.Build.props = Directory.Build.props
|
||||
Directory.Build.targets = Directory.Build.targets
|
||||
EndProjectSection
|
||||
EndProject
|
||||
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.AspNetCore.SpaServices.Extensions", "src\Microsoft.AspNetCore.SpaServices.Extensions\Microsoft.AspNetCore.SpaServices.Extensions.csproj", "{D40BD1C4-6A6F-4213-8535-1057F3EB3400}"
|
||||
EndProject
|
||||
Global
|
||||
GlobalSection(SolutionConfigurationPlatforms) = preSolution
|
||||
Debug|Any CPU = Debug|Any CPU
|
||||
Release|Any CPU = Release|Any CPU
|
||||
EndGlobalSection
|
||||
GlobalSection(ProjectConfigurationPlatforms) = postSolution
|
||||
{D40BD1C4-6A6F-4213-8535-1057F3EB3400}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{D40BD1C4-6A6F-4213-8535-1057F3EB3400}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{D40BD1C4-6A6F-4213-8535-1057F3EB3400}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{D40BD1C4-6A6F-4213-8535-1057F3EB3400}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
EndGlobalSection
|
||||
GlobalSection(SolutionProperties) = preSolution
|
||||
HideSolutionNode = FALSE
|
||||
EndGlobalSection
|
||||
GlobalSection(NestedProjects) = preSolution
|
||||
{D40BD1C4-6A6F-4213-8535-1057F3EB3400} = {27304DDE-AFB2-4F8B-B765-E3E2F11E886C}
|
||||
EndGlobalSection
|
||||
GlobalSection(ExtensibilityGlobals) = postSolution
|
||||
SolutionGuid = {DDF59B0D-2DEC-45D6-8667-DCB767487101}
|
||||
EndGlobalSection
|
||||
EndGlobal
|
||||
@@ -1,10 +1,12 @@
|
||||
Copyright (c) .NET Foundation. All rights reserved.
|
||||
Copyright (c) .NET Foundation and Contributors
|
||||
|
||||
All rights reserved.
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License"); you may not use
|
||||
these files except in compliance with the License. You may obtain a copy of the
|
||||
this file except in compliance with the License. You may obtain a copy of the
|
||||
License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software distributed
|
||||
under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
|
||||
9
NuGet.config
Normal file
9
NuGet.config
Normal file
@@ -0,0 +1,9 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<configuration>
|
||||
<packageSources>
|
||||
<clear />
|
||||
<add key="AspNetCore" value="https://dotnet.myget.org/F/aspnetcore-ci-dev/api/v3/index.json" />
|
||||
<add key="AspNetCoreTools" value="https://dotnet.myget.org/F/aspnetcore-tools/api/v3/index.json" />
|
||||
<add key="NuGet" value="https://api.nuget.org/v3/index.json" />
|
||||
</packageSources>
|
||||
</configuration>
|
||||
1
README.md
Normal file
1
README.md
Normal file
@@ -0,0 +1 @@
|
||||
This branch exists only to build `Microsoft.AspNetCore.SpaServices.Extensions` for an OOB release. It does not contain sources for any other packages or samples.
|
||||
2
build.cmd
Executable file
2
build.cmd
Executable file
@@ -0,0 +1,2 @@
|
||||
@ECHO OFF
|
||||
PowerShell -NoProfile -NoLogo -ExecutionPolicy unrestricted -Command "[System.Threading.Thread]::CurrentThread.CurrentCulture = ''; [System.Threading.Thread]::CurrentThread.CurrentUICulture = '';& '%~dp0run.ps1' default-build %*; exit $LASTEXITCODE"
|
||||
8
build.sh
Executable file
8
build.sh
Executable file
@@ -0,0 +1,8 @@
|
||||
#!/usr/bin/env bash
|
||||
|
||||
set -euo pipefail
|
||||
DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
|
||||
|
||||
# Call "sync" between "chmod" and execution to prevent "text file busy" error in Docker (aufs)
|
||||
chmod +x "$DIR/run.sh"; sync
|
||||
"$DIR/run.sh" default-build "$@"
|
||||
15
build/Push.targets
Normal file
15
build/Push.targets
Normal file
@@ -0,0 +1,15 @@
|
||||
<Project>
|
||||
<Target Name="Push" DependsOnTargets="_PushNuGet" />
|
||||
|
||||
<ItemGroup>
|
||||
<PackagesToPush Include="$(BuildDir)*.nupkg" />
|
||||
</ItemGroup>
|
||||
|
||||
<Target Name="_PushNuGet" Condition="@(PackagesToPush->Count()) != 0">
|
||||
<Error Text="Missing required property: NuGetPublishFeed" Condition=" '$(NuGetPublishFeed)' == '' "/>
|
||||
<PushNuGetPackages
|
||||
Packages="@(PackagesToPush)"
|
||||
Feed="$(NuGetPublishFeed)"
|
||||
ApiKey="$(APIKey)" />
|
||||
</Target>
|
||||
</Project>
|
||||
27
build/dependencies.props
Normal file
27
build/dependencies.props
Normal file
@@ -0,0 +1,27 @@
|
||||
<Project>
|
||||
<PropertyGroup>
|
||||
<MSBuildAllProjects>$(MSBuildAllProjects);$(MSBuildThisFileFullPath)</MSBuildAllProjects>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Label="Package Versions">
|
||||
<InternalAspNetCoreSdkPackageVersion>2.1.0-preview1-15549</InternalAspNetCoreSdkPackageVersion>
|
||||
<MicrosoftAspNetCoreDiagnosticsPackageVersion>2.0.1</MicrosoftAspNetCoreDiagnosticsPackageVersion>
|
||||
<MicrosoftAspNetCoreHostingAbstractionsPackageVersion>2.0.1</MicrosoftAspNetCoreHostingAbstractionsPackageVersion>
|
||||
<MicrosoftAspNetCoreHostingPackageVersion>2.0.1</MicrosoftAspNetCoreHostingPackageVersion>
|
||||
<MicrosoftAspNetCoreMvcPackageVersion>2.0.1</MicrosoftAspNetCoreMvcPackageVersion>
|
||||
<MicrosoftAspNetCoreMvcTagHelpersPackageVersion>2.0.1</MicrosoftAspNetCoreMvcTagHelpersPackageVersion>
|
||||
<MicrosoftAspNetCoreMvcViewFeaturesPackageVersion>2.0.1</MicrosoftAspNetCoreMvcViewFeaturesPackageVersion>
|
||||
<MicrosoftAspNetCoreServerIISIntegrationPackageVersion>2.0.1</MicrosoftAspNetCoreServerIISIntegrationPackageVersion>
|
||||
<MicrosoftAspNetCoreServerKestrelPackageVersion>2.0.1</MicrosoftAspNetCoreServerKestrelPackageVersion>
|
||||
<MicrosoftAspNetCoreSpaServicesPackageVersion>2.0.1</MicrosoftAspNetCoreSpaServicesPackageVersion>
|
||||
<MicrosoftAspNetCoreStaticFilesPackageVersion>2.0.1</MicrosoftAspNetCoreStaticFilesPackageVersion>
|
||||
<MicrosoftAspNetCoreWebSocketsPackageVersion>2.0.1</MicrosoftAspNetCoreWebSocketsPackageVersion>
|
||||
<MicrosoftExtensionsDependencyInjectionPackageVersion>2.0.0</MicrosoftExtensionsDependencyInjectionPackageVersion>
|
||||
<MicrosoftExtensionsFileProvidersPhysicalPackageVersion>2.0.0</MicrosoftExtensionsFileProvidersPhysicalPackageVersion>
|
||||
<MicrosoftExtensionsLoggingConsolePackageVersion>2.0.0</MicrosoftExtensionsLoggingConsolePackageVersion>
|
||||
<MicrosoftExtensionsLoggingDebugPackageVersion>2.0.0</MicrosoftExtensionsLoggingDebugPackageVersion>
|
||||
<MicrosoftNETCoreApp20PackageVersion>2.0.0</MicrosoftNETCoreApp20PackageVersion>
|
||||
<NewtonsoftJsonPackageVersion>10.0.1</NewtonsoftJsonPackageVersion>
|
||||
<SystemThreadingTasksDataflowPackageVersion>4.8.0</SystemThreadingTasksDataflowPackageVersion>
|
||||
</PropertyGroup>
|
||||
<Import Project="$(DotNetPackageVersionPropsPath)" Condition=" '$(DotNetPackageVersionPropsPath)' != '' " />
|
||||
</Project>
|
||||
@@ -1,13 +1,7 @@
|
||||
<Project>
|
||||
<Import Project="dependencies.props" />
|
||||
|
||||
<Project>
|
||||
<PropertyGroup>
|
||||
<!-- These properties are use by the automation that updates dependencies.props -->
|
||||
<LineupPackageId>Internal.AspNetCore.Universe.Lineup</LineupPackageId>
|
||||
<LineupPackageRestoreSource>https://dotnet.myget.org/F/aspnetcore-dev/api/v3/index.json</LineupPackageRestoreSource>
|
||||
<LineupPackageRestoreSource>https://dotnet.myget.org/F/aspnetcore-ci-dev/api/v3/index.json</LineupPackageRestoreSource>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<DotNetCoreRuntime Include="$(MicrosoftNETCoreAppPackageVersion)" />
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
3
build/repo.targets
Normal file
3
build/repo.targets
Normal file
@@ -0,0 +1,3 @@
|
||||
<Project>
|
||||
<Import Project="Push.targets" />
|
||||
</Project>
|
||||
2
korebuild-lock.txt
Normal file
2
korebuild-lock.txt
Normal file
@@ -0,0 +1,2 @@
|
||||
version:2.1.0-preview1-15549
|
||||
commithash:f570e08585fec510dd60cd4bfe8795388b757a95
|
||||
10
korebuild.json
Normal file
10
korebuild.json
Normal file
@@ -0,0 +1,10 @@
|
||||
{
|
||||
"$schema": "https://raw.githubusercontent.com/aspnet/BuildTools/dev/tools/korebuild.schema.json",
|
||||
"channel": "dev",
|
||||
"toolsets": {
|
||||
"nodejs": {
|
||||
"required": true,
|
||||
"minVersion": "6.9"
|
||||
}
|
||||
}
|
||||
}
|
||||
2
run.cmd
Normal file
2
run.cmd
Normal file
@@ -0,0 +1,2 @@
|
||||
@ECHO OFF
|
||||
PowerShell -NoProfile -NoLogo -ExecutionPolicy unrestricted -Command "[System.Threading.Thread]::CurrentThread.CurrentCulture = ''; [System.Threading.Thread]::CurrentThread.CurrentUICulture = '';& '%~dp0run.ps1' %*; exit $LASTEXITCODE"
|
||||
191
run.ps1
Normal file
191
run.ps1
Normal file
@@ -0,0 +1,191 @@
|
||||
#!/usr/bin/env powershell
|
||||
#requires -version 4
|
||||
|
||||
<#
|
||||
.SYNOPSIS
|
||||
Executes KoreBuild commands.
|
||||
|
||||
.DESCRIPTION
|
||||
Downloads korebuild if required. Then executes the KoreBuild command. To see available commands, execute with `-Command help`.
|
||||
|
||||
.PARAMETER Command
|
||||
The KoreBuild command to run.
|
||||
|
||||
.PARAMETER Path
|
||||
The folder to build. Defaults to the folder containing this script.
|
||||
|
||||
.PARAMETER Channel
|
||||
The channel of KoreBuild to download. Overrides the value from the config file.
|
||||
|
||||
.PARAMETER DotNetHome
|
||||
The directory where .NET Core tools will be stored.
|
||||
|
||||
.PARAMETER ToolsSource
|
||||
The base url where build tools can be downloaded. Overrides the value from the config file.
|
||||
|
||||
.PARAMETER Update
|
||||
Updates KoreBuild to the latest version even if a lock file is present.
|
||||
|
||||
.PARAMETER ConfigFile
|
||||
The path to the configuration file that stores values. Defaults to korebuild.json.
|
||||
|
||||
.PARAMETER Arguments
|
||||
Arguments to be passed to the command
|
||||
|
||||
.NOTES
|
||||
This function will create a file $PSScriptRoot/korebuild-lock.txt. This lock file can be committed to source, but does not have to be.
|
||||
When the lockfile is not present, KoreBuild will create one using latest available version from $Channel.
|
||||
|
||||
The $ConfigFile is expected to be an JSON file. It is optional, and the configuration values in it are optional as well. Any options set
|
||||
in the file are overridden by command line parameters.
|
||||
|
||||
.EXAMPLE
|
||||
Example config file:
|
||||
```json
|
||||
{
|
||||
"$schema": "https://raw.githubusercontent.com/aspnet/BuildTools/dev/tools/korebuild.schema.json",
|
||||
"channel": "dev",
|
||||
"toolsSource": "https://aspnetcore.blob.core.windows.net/buildtools"
|
||||
}
|
||||
```
|
||||
#>
|
||||
[CmdletBinding(PositionalBinding = $false)]
|
||||
param(
|
||||
[Parameter(Mandatory=$true, Position = 0)]
|
||||
[string]$Command,
|
||||
[string]$Path = $PSScriptRoot,
|
||||
[Alias('c')]
|
||||
[string]$Channel,
|
||||
[Alias('d')]
|
||||
[string]$DotNetHome,
|
||||
[Alias('s')]
|
||||
[string]$ToolsSource,
|
||||
[Alias('u')]
|
||||
[switch]$Update,
|
||||
[string]$ConfigFile,
|
||||
[Parameter(ValueFromRemainingArguments = $true)]
|
||||
[string[]]$Arguments
|
||||
)
|
||||
|
||||
Set-StrictMode -Version 2
|
||||
$ErrorActionPreference = 'Stop'
|
||||
|
||||
#
|
||||
# Functions
|
||||
#
|
||||
|
||||
function Get-KoreBuild {
|
||||
|
||||
$lockFile = Join-Path $Path 'korebuild-lock.txt'
|
||||
|
||||
if (!(Test-Path $lockFile) -or $Update) {
|
||||
Get-RemoteFile "$ToolsSource/korebuild/channels/$Channel/latest.txt" $lockFile
|
||||
}
|
||||
|
||||
$version = Get-Content $lockFile | Where-Object { $_ -like 'version:*' } | Select-Object -first 1
|
||||
if (!$version) {
|
||||
Write-Error "Failed to parse version from $lockFile. Expected a line that begins with 'version:'"
|
||||
}
|
||||
$version = $version.TrimStart('version:').Trim()
|
||||
$korebuildPath = Join-Paths $DotNetHome ('buildtools', 'korebuild', $version)
|
||||
|
||||
if (!(Test-Path $korebuildPath)) {
|
||||
Write-Host -ForegroundColor Magenta "Downloading KoreBuild $version"
|
||||
New-Item -ItemType Directory -Path $korebuildPath | Out-Null
|
||||
$remotePath = "$ToolsSource/korebuild/artifacts/$version/korebuild.$version.zip"
|
||||
|
||||
try {
|
||||
$tmpfile = Join-Path ([IO.Path]::GetTempPath()) "KoreBuild-$([guid]::NewGuid()).zip"
|
||||
Get-RemoteFile $remotePath $tmpfile
|
||||
if (Get-Command -Name 'Expand-Archive' -ErrorAction Ignore) {
|
||||
# Use built-in commands where possible as they are cross-plat compatible
|
||||
Expand-Archive -Path $tmpfile -DestinationPath $korebuildPath
|
||||
}
|
||||
else {
|
||||
# Fallback to old approach for old installations of PowerShell
|
||||
Add-Type -AssemblyName System.IO.Compression.FileSystem
|
||||
[System.IO.Compression.ZipFile]::ExtractToDirectory($tmpfile, $korebuildPath)
|
||||
}
|
||||
}
|
||||
catch {
|
||||
Remove-Item -Recurse -Force $korebuildPath -ErrorAction Ignore
|
||||
throw
|
||||
}
|
||||
finally {
|
||||
Remove-Item $tmpfile -ErrorAction Ignore
|
||||
}
|
||||
}
|
||||
|
||||
return $korebuildPath
|
||||
}
|
||||
|
||||
function Join-Paths([string]$path, [string[]]$childPaths) {
|
||||
$childPaths | ForEach-Object { $path = Join-Path $path $_ }
|
||||
return $path
|
||||
}
|
||||
|
||||
function Get-RemoteFile([string]$RemotePath, [string]$LocalPath) {
|
||||
if ($RemotePath -notlike 'http*') {
|
||||
Copy-Item $RemotePath $LocalPath
|
||||
return
|
||||
}
|
||||
|
||||
$retries = 10
|
||||
while ($retries -gt 0) {
|
||||
$retries -= 1
|
||||
try {
|
||||
Invoke-WebRequest -UseBasicParsing -Uri $RemotePath -OutFile $LocalPath
|
||||
return
|
||||
}
|
||||
catch {
|
||||
Write-Verbose "Request failed. $retries retries remaining"
|
||||
}
|
||||
}
|
||||
|
||||
Write-Error "Download failed: '$RemotePath'."
|
||||
}
|
||||
|
||||
#
|
||||
# Main
|
||||
#
|
||||
|
||||
# Load configuration or set defaults
|
||||
|
||||
$Path = Resolve-Path $Path
|
||||
if (!$ConfigFile) { $ConfigFile = Join-Path $Path 'korebuild.json' }
|
||||
|
||||
if (Test-Path $ConfigFile) {
|
||||
try {
|
||||
$config = Get-Content -Raw -Encoding UTF8 -Path $ConfigFile | ConvertFrom-Json
|
||||
if ($config) {
|
||||
if (!($Channel) -and (Get-Member -Name 'channel' -InputObject $config)) { [string] $Channel = $config.channel }
|
||||
if (!($ToolsSource) -and (Get-Member -Name 'toolsSource' -InputObject $config)) { [string] $ToolsSource = $config.toolsSource}
|
||||
}
|
||||
} catch {
|
||||
Write-Warning "$ConfigFile could not be read. Its settings will be ignored."
|
||||
Write-Warning $Error[0]
|
||||
}
|
||||
}
|
||||
|
||||
if (!$DotNetHome) {
|
||||
$DotNetHome = if ($env:DOTNET_HOME) { $env:DOTNET_HOME } `
|
||||
elseif ($env:USERPROFILE) { Join-Path $env:USERPROFILE '.dotnet'} `
|
||||
elseif ($env:HOME) {Join-Path $env:HOME '.dotnet'}`
|
||||
else { Join-Path $PSScriptRoot '.dotnet'}
|
||||
}
|
||||
|
||||
if (!$Channel) { $Channel = 'dev' }
|
||||
if (!$ToolsSource) { $ToolsSource = 'https://aspnetcore.blob.core.windows.net/buildtools' }
|
||||
|
||||
# Execute
|
||||
|
||||
$korebuildPath = Get-KoreBuild
|
||||
Import-Module -Force -Scope Local (Join-Path $korebuildPath 'KoreBuild.psd1')
|
||||
|
||||
try {
|
||||
Set-KoreBuildSettings -ToolsSource $ToolsSource -DotNetHome $DotNetHome -RepoPath $Path -ConfigFile $ConfigFile
|
||||
Invoke-KoreBuildCommand $Command @Arguments
|
||||
}
|
||||
finally {
|
||||
Remove-Module 'KoreBuild' -ErrorAction Ignore
|
||||
}
|
||||
223
run.sh
Executable file
223
run.sh
Executable file
@@ -0,0 +1,223 @@
|
||||
#!/usr/bin/env bash
|
||||
|
||||
set -euo pipefail
|
||||
|
||||
#
|
||||
# variables
|
||||
#
|
||||
|
||||
RESET="\033[0m"
|
||||
RED="\033[0;31m"
|
||||
YELLOW="\033[0;33m"
|
||||
MAGENTA="\033[0;95m"
|
||||
DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
|
||||
[ -z "${DOTNET_HOME:-}" ] && DOTNET_HOME="$HOME/.dotnet"
|
||||
verbose=false
|
||||
update=false
|
||||
repo_path="$DIR"
|
||||
channel=''
|
||||
tools_source=''
|
||||
|
||||
#
|
||||
# Functions
|
||||
#
|
||||
__usage() {
|
||||
echo "Usage: $(basename "${BASH_SOURCE[0]}") command [options] [[--] <Arguments>...]"
|
||||
echo ""
|
||||
echo "Arguments:"
|
||||
echo " command The command to be run."
|
||||
echo " <Arguments>... Arguments passed to the command. Variable number of arguments allowed."
|
||||
echo ""
|
||||
echo "Options:"
|
||||
echo " --verbose Show verbose output."
|
||||
echo " -c|--channel <CHANNEL> The channel of KoreBuild to download. Overrides the value from the config file.."
|
||||
echo " --config-file <FILE> The path to the configuration file that stores values. Defaults to korebuild.json."
|
||||
echo " -d|--dotnet-home <DIR> The directory where .NET Core tools will be stored. Defaults to '\$DOTNET_HOME' or '\$HOME/.dotnet."
|
||||
echo " --path <PATH> The directory to build. Defaults to the directory containing the script."
|
||||
echo " -s|--tools-source|-ToolsSource <URL> The base url where build tools can be downloaded. Overrides the value from the config file."
|
||||
echo " -u|--update Update to the latest KoreBuild even if the lock file is present."
|
||||
echo ""
|
||||
echo "Description:"
|
||||
echo " This function will create a file \$DIR/korebuild-lock.txt. This lock file can be committed to source, but does not have to be."
|
||||
echo " When the lockfile is not present, KoreBuild will create one using latest available version from \$channel."
|
||||
|
||||
if [[ "${1:-}" != '--no-exit' ]]; then
|
||||
exit 2
|
||||
fi
|
||||
}
|
||||
|
||||
get_korebuild() {
|
||||
local version
|
||||
local lock_file="$repo_path/korebuild-lock.txt"
|
||||
if [ ! -f "$lock_file" ] || [ "$update" = true ]; then
|
||||
__get_remote_file "$tools_source/korebuild/channels/$channel/latest.txt" "$lock_file"
|
||||
fi
|
||||
version="$(grep 'version:*' -m 1 "$lock_file")"
|
||||
if [[ "$version" == '' ]]; then
|
||||
__error "Failed to parse version from $lock_file. Expected a line that begins with 'version:'"
|
||||
return 1
|
||||
fi
|
||||
version="$(echo "${version#version:}" | sed -e 's/^[[:space:]]*//' -e 's/[[:space:]]*$//')"
|
||||
local korebuild_path="$DOTNET_HOME/buildtools/korebuild/$version"
|
||||
|
||||
{
|
||||
if [ ! -d "$korebuild_path" ]; then
|
||||
mkdir -p "$korebuild_path"
|
||||
local remote_path="$tools_source/korebuild/artifacts/$version/korebuild.$version.zip"
|
||||
tmpfile="$(mktemp)"
|
||||
echo -e "${MAGENTA}Downloading KoreBuild ${version}${RESET}"
|
||||
if __get_remote_file "$remote_path" "$tmpfile"; then
|
||||
unzip -q -d "$korebuild_path" "$tmpfile"
|
||||
fi
|
||||
rm "$tmpfile" || true
|
||||
fi
|
||||
|
||||
source "$korebuild_path/KoreBuild.sh"
|
||||
} || {
|
||||
if [ -d "$korebuild_path" ]; then
|
||||
echo "Cleaning up after failed installation"
|
||||
rm -rf "$korebuild_path" || true
|
||||
fi
|
||||
return 1
|
||||
}
|
||||
}
|
||||
|
||||
__error() {
|
||||
echo -e "${RED}error: $*${RESET}" 1>&2
|
||||
}
|
||||
|
||||
__warn() {
|
||||
echo -e "${YELLOW}warning: $*${RESET}"
|
||||
}
|
||||
|
||||
__machine_has() {
|
||||
hash "$1" > /dev/null 2>&1
|
||||
return $?
|
||||
}
|
||||
|
||||
__get_remote_file() {
|
||||
local remote_path=$1
|
||||
local local_path=$2
|
||||
|
||||
if [[ "$remote_path" != 'http'* ]]; then
|
||||
cp "$remote_path" "$local_path"
|
||||
return 0
|
||||
fi
|
||||
|
||||
local failed=false
|
||||
if __machine_has wget; then
|
||||
wget --tries 10 --quiet -O "$local_path" "$remote_path" || failed=true
|
||||
else
|
||||
failed=true
|
||||
fi
|
||||
|
||||
if [ "$failed" = true ] && __machine_has curl; then
|
||||
failed=false
|
||||
curl --retry 10 -sSL -f --create-dirs -o "$local_path" "$remote_path" || failed=true
|
||||
fi
|
||||
|
||||
if [ "$failed" = true ]; then
|
||||
__error "Download failed: $remote_path" 1>&2
|
||||
return 1
|
||||
fi
|
||||
}
|
||||
|
||||
#
|
||||
# main
|
||||
#
|
||||
|
||||
command="${1:-}"
|
||||
shift
|
||||
|
||||
while [[ $# -gt 0 ]]; do
|
||||
case $1 in
|
||||
-\?|-h|--help)
|
||||
__usage --no-exit
|
||||
exit 0
|
||||
;;
|
||||
-c|--channel|-Channel)
|
||||
shift
|
||||
channel="${1:-}"
|
||||
[ -z "$channel" ] && __usage
|
||||
;;
|
||||
--config-file|-ConfigFile)
|
||||
shift
|
||||
config_file="${1:-}"
|
||||
[ -z "$config_file" ] && __usage
|
||||
if [ ! -f "$config_file" ]; then
|
||||
__error "Invalid value for --config-file. $config_file does not exist."
|
||||
exit 1
|
||||
fi
|
||||
;;
|
||||
-d|--dotnet-home|-DotNetHome)
|
||||
shift
|
||||
DOTNET_HOME="${1:-}"
|
||||
[ -z "$DOTNET_HOME" ] && __usage
|
||||
;;
|
||||
--path|-Path)
|
||||
shift
|
||||
repo_path="${1:-}"
|
||||
[ -z "$repo_path" ] && __usage
|
||||
;;
|
||||
-s|--tools-source|-ToolsSource)
|
||||
shift
|
||||
tools_source="${1:-}"
|
||||
[ -z "$tools_source" ] && __usage
|
||||
;;
|
||||
-u|--update|-Update)
|
||||
update=true
|
||||
;;
|
||||
--verbose|-Verbose)
|
||||
verbose=true
|
||||
;;
|
||||
--)
|
||||
shift
|
||||
break
|
||||
;;
|
||||
*)
|
||||
break
|
||||
;;
|
||||
esac
|
||||
shift
|
||||
done
|
||||
|
||||
if ! __machine_has unzip; then
|
||||
__error 'Missing required command: unzip'
|
||||
exit 1
|
||||
fi
|
||||
|
||||
if ! __machine_has curl && ! __machine_has wget; then
|
||||
__error 'Missing required command. Either wget or curl is required.'
|
||||
exit 1
|
||||
fi
|
||||
|
||||
[ -z "${config_file:-}" ] && config_file="$repo_path/korebuild.json"
|
||||
if [ -f "$config_file" ]; then
|
||||
if __machine_has jq ; then
|
||||
if jq '.' "$config_file" >/dev/null ; then
|
||||
config_channel="$(jq -r 'select(.channel!=null) | .channel' "$config_file")"
|
||||
config_tools_source="$(jq -r 'select(.toolsSource!=null) | .toolsSource' "$config_file")"
|
||||
else
|
||||
__warn "$config_file is invalid JSON. Its settings will be ignored."
|
||||
fi
|
||||
elif __machine_has python ; then
|
||||
if python -c "import json,codecs;obj=json.load(codecs.open('$config_file', 'r', 'utf-8-sig'))" >/dev/null ; then
|
||||
config_channel="$(python -c "import json,codecs;obj=json.load(codecs.open('$config_file', 'r', 'utf-8-sig'));print(obj['channel'] if 'channel' in obj else '')")"
|
||||
config_tools_source="$(python -c "import json,codecs;obj=json.load(codecs.open('$config_file', 'r', 'utf-8-sig'));print(obj['toolsSource'] if 'toolsSource' in obj else '')")"
|
||||
else
|
||||
__warn "$config_file is invalid JSON. Its settings will be ignored."
|
||||
fi
|
||||
else
|
||||
__warn 'Missing required command: jq or pyton. Could not parse the JSON file. Its settings will be ignored.'
|
||||
fi
|
||||
|
||||
[ ! -z "${config_channel:-}" ] && channel="$config_channel"
|
||||
[ ! -z "${config_tools_source:-}" ] && tools_source="$config_tools_source"
|
||||
fi
|
||||
|
||||
[ -z "$channel" ] && channel='dev'
|
||||
[ -z "$tools_source" ] && tools_source='https://aspnetcore.blob.core.windows.net/buildtools'
|
||||
|
||||
get_korebuild
|
||||
set_korebuildsettings "$tools_source" "$DOTNET_HOME" "$repo_path" "$config_file"
|
||||
invoke_korebuild_command "$command" "$@"
|
||||
@@ -1,6 +0,0 @@
|
||||
<Project>
|
||||
<PropertyGroup>
|
||||
<RuntimeFrameworkVersion Condition=" '$(TargetFramework)' == 'netcoreapp3.0' ">$(MicrosoftNETCoreAppPackageVersion)</RuntimeFrameworkVersion>
|
||||
<NETStandardImplicitPackageVersion Condition=" '$(TargetFramework)' == 'netstandard2.0' ">$(NETStandardLibrary20PackageVersion)</NETStandardImplicitPackageVersion>
|
||||
</PropertyGroup>
|
||||
</Project>
|
||||
@@ -1,93 +0,0 @@
|
||||
|
||||
Microsoft Visual Studio Solution File, Format Version 12.00
|
||||
# Visual Studio 15
|
||||
VisualStudioVersion = 15.0.26730.16
|
||||
MinimumVisualStudioVersion = 15.0.26730.03
|
||||
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "src", "src", "{27304DDE-AFB2-4F8B-B765-E3E2F11E886C}"
|
||||
ProjectSection(SolutionItems) = preProject
|
||||
src\Directory.Build.props = src\Directory.Build.props
|
||||
EndProjectSection
|
||||
EndProject
|
||||
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.AspNetCore.NodeServices", "src\Microsoft.AspNetCore.NodeServices\Microsoft.AspNetCore.NodeServices.csproj", "{66B77203-1469-41DF-92F2-2BE6900BD36F}"
|
||||
EndProject
|
||||
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.AspNetCore.NodeServices.Sockets", "src\Microsoft.AspNetCore.NodeServices.Sockets\Microsoft.AspNetCore.NodeServices.Sockets.csproj", "{F46DEF99-6FAA-4406-B5D8-6FF34EF669E3}"
|
||||
EndProject
|
||||
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.AspNetCore.SpaServices", "src\Microsoft.AspNetCore.SpaServices\Microsoft.AspNetCore.SpaServices.csproj", "{66B071A8-EFC8-4A06-BEF6-06B99AE27EEC}"
|
||||
EndProject
|
||||
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "misc", "misc", "{99EAF1FE-22C8-4526-BE78-74B24125D37F}"
|
||||
ProjectSection(SolutionItems) = preProject
|
||||
.gitignore = .gitignore
|
||||
global.json = global.json
|
||||
README.md = README.md
|
||||
EndProjectSection
|
||||
EndProject
|
||||
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "samples", "samples", "{23836492-E7F4-4376-85BF-A635C304AC46}"
|
||||
EndProject
|
||||
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "misc", "misc", "{E6A161EA-646C-4033-9090-95BE809AB8D9}"
|
||||
EndProject
|
||||
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "LatencyTest", "samples\misc\LatencyTest\LatencyTest.csproj", "{1931B19A-EC42-4D56-B2D0-FB06D17244DA}"
|
||||
EndProject
|
||||
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Webpack", "samples\misc\Webpack\Webpack.csproj", "{DE479DC3-1461-4EAD-A188-4AF7AA4AE344}"
|
||||
EndProject
|
||||
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "NodeServicesExamples", "samples\misc\NodeServicesExamples\NodeServicesExamples.csproj", "{93EFCC5F-C6EE-4623-894F-A42B22C0B6FE}"
|
||||
EndProject
|
||||
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{645F7363-1240-4FB6-9422-B32A327C979F}"
|
||||
ProjectSection(SolutionItems) = preProject
|
||||
Directory.Build.props = Directory.Build.props
|
||||
Directory.Build.targets = Directory.Build.targets
|
||||
EndProjectSection
|
||||
EndProject
|
||||
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.AspNetCore.SpaServices.Extensions", "src\Microsoft.AspNetCore.SpaServices.Extensions\Microsoft.AspNetCore.SpaServices.Extensions.csproj", "{D40BD1C4-6A6F-4213-8535-1057F3EB3400}"
|
||||
EndProject
|
||||
Global
|
||||
GlobalSection(SolutionConfigurationPlatforms) = preSolution
|
||||
Debug|Any CPU = Debug|Any CPU
|
||||
Release|Any CPU = Release|Any CPU
|
||||
EndGlobalSection
|
||||
GlobalSection(ProjectConfigurationPlatforms) = postSolution
|
||||
{66B77203-1469-41DF-92F2-2BE6900BD36F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{66B77203-1469-41DF-92F2-2BE6900BD36F}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{66B77203-1469-41DF-92F2-2BE6900BD36F}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{66B77203-1469-41DF-92F2-2BE6900BD36F}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
{F46DEF99-6FAA-4406-B5D8-6FF34EF669E3}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{F46DEF99-6FAA-4406-B5D8-6FF34EF669E3}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{F46DEF99-6FAA-4406-B5D8-6FF34EF669E3}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{F46DEF99-6FAA-4406-B5D8-6FF34EF669E3}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
{66B071A8-EFC8-4A06-BEF6-06B99AE27EEC}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{66B071A8-EFC8-4A06-BEF6-06B99AE27EEC}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{66B071A8-EFC8-4A06-BEF6-06B99AE27EEC}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{66B071A8-EFC8-4A06-BEF6-06B99AE27EEC}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
{1931B19A-EC42-4D56-B2D0-FB06D17244DA}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{1931B19A-EC42-4D56-B2D0-FB06D17244DA}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{1931B19A-EC42-4D56-B2D0-FB06D17244DA}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{1931B19A-EC42-4D56-B2D0-FB06D17244DA}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
{DE479DC3-1461-4EAD-A188-4AF7AA4AE344}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{DE479DC3-1461-4EAD-A188-4AF7AA4AE344}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{DE479DC3-1461-4EAD-A188-4AF7AA4AE344}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{DE479DC3-1461-4EAD-A188-4AF7AA4AE344}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
{93EFCC5F-C6EE-4623-894F-A42B22C0B6FE}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{93EFCC5F-C6EE-4623-894F-A42B22C0B6FE}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{93EFCC5F-C6EE-4623-894F-A42B22C0B6FE}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{93EFCC5F-C6EE-4623-894F-A42B22C0B6FE}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
{D40BD1C4-6A6F-4213-8535-1057F3EB3400}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{D40BD1C4-6A6F-4213-8535-1057F3EB3400}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{D40BD1C4-6A6F-4213-8535-1057F3EB3400}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{D40BD1C4-6A6F-4213-8535-1057F3EB3400}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
EndGlobalSection
|
||||
GlobalSection(SolutionProperties) = preSolution
|
||||
HideSolutionNode = FALSE
|
||||
EndGlobalSection
|
||||
GlobalSection(NestedProjects) = preSolution
|
||||
{66B77203-1469-41DF-92F2-2BE6900BD36F} = {27304DDE-AFB2-4F8B-B765-E3E2F11E886C}
|
||||
{F46DEF99-6FAA-4406-B5D8-6FF34EF669E3} = {27304DDE-AFB2-4F8B-B765-E3E2F11E886C}
|
||||
{66B071A8-EFC8-4A06-BEF6-06B99AE27EEC} = {27304DDE-AFB2-4F8B-B765-E3E2F11E886C}
|
||||
{E6A161EA-646C-4033-9090-95BE809AB8D9} = {23836492-E7F4-4376-85BF-A635C304AC46}
|
||||
{1931B19A-EC42-4D56-B2D0-FB06D17244DA} = {E6A161EA-646C-4033-9090-95BE809AB8D9}
|
||||
{DE479DC3-1461-4EAD-A188-4AF7AA4AE344} = {E6A161EA-646C-4033-9090-95BE809AB8D9}
|
||||
{93EFCC5F-C6EE-4623-894F-A42B22C0B6FE} = {E6A161EA-646C-4033-9090-95BE809AB8D9}
|
||||
{D40BD1C4-6A6F-4213-8535-1057F3EB3400} = {27304DDE-AFB2-4F8B-B765-E3E2F11E886C}
|
||||
EndGlobalSection
|
||||
GlobalSection(ExtensibilityGlobals) = postSolution
|
||||
SolutionGuid = {DDF59B0D-2DEC-45D6-8667-DCB767487101}
|
||||
EndGlobalSection
|
||||
EndGlobal
|
||||
@@ -1,7 +0,0 @@
|
||||
{
|
||||
"Default": {
|
||||
"rules": [
|
||||
"DefaultCompositeRule"
|
||||
]
|
||||
}
|
||||
}
|
||||
@@ -1,96 +0,0 @@
|
||||
# JavaScriptServices
|
||||
|
||||
AppVeyor: [](https://ci.appveyor.com/project/aspnetci/javascriptservices/branch/dev)
|
||||
|
||||
This project is part of ASP.NET Core. You can find samples, documentation and getting started instructions for ASP.NET Core at the [Home](https://github.com/aspnet/home) repo.
|
||||
|
||||
## What is this?
|
||||
|
||||
`JavaScriptServices` is a set of client-side technologies for ASP.NET Core. It provides infrastructure that you'll find useful if you:
|
||||
|
||||
- Use Angular / React / Vue / Aurelia / Knockout / etc.
|
||||
- Build your client-side resources using Webpack.
|
||||
- Execute JavaScript on the server at runtime.
|
||||
|
||||
Read [Building Single Page Applications on ASP.NET Core with JavaScriptServices](https://blogs.msdn.microsoft.com/webdev/2017/02/14/building-single-page-applications-on-asp-net-core-with-javascriptservices/) for more details.
|
||||
|
||||
This repo contains:
|
||||
|
||||
* A set of NuGet/NPM packages that implement functionality for:
|
||||
* Invoking arbitrary NPM packages at runtime from .NET code ([docs](/src/Microsoft.AspNetCore.NodeServices#simple-usage-example))
|
||||
* Server-side prerendering of SPA components ([docs](/src/Microsoft.AspNetCore.SpaServices#server-side-prerendering))
|
||||
* Webpack dev middleware ([docs](/src/Microsoft.AspNetCore.SpaServices#webpack-dev-middleware))
|
||||
* Hot module replacement (HMR) ([docs](/src/Microsoft.AspNetCore.SpaServices#webpack-hot-module-replacement))
|
||||
* Server-side and client-side routing integration ([docs](/src/Microsoft.AspNetCore.SpaServices#routing-helper-mapspafallbackroute))
|
||||
* Server-side and client-side validation integration
|
||||
* "Lazy loading" for Knockout apps
|
||||
* Samples and docs
|
||||
|
||||
It's cross-platform (Windows, Linux, or macOS) and works with .NET Core 2.0 or later.
|
||||
|
||||
## Creating new applications
|
||||
|
||||
Prerequisites:
|
||||
|
||||
* [.NET Core 2.0](https://www.microsoft.com/net/core) (or later) SDK
|
||||
* [Node.js](https://nodejs.org/) version 6 (or later)
|
||||
|
||||
With these prerequisites, you can immediately create new ASP.NET Core applications that use Angular, React, or React+Redux without having to install anything extra.
|
||||
|
||||
### Option 1: Creating Angular/React/Redux applications from the command line (cross-platform)
|
||||
|
||||
In an empty directory, run (for example) `dotnet new angular`. Other supported SPA frameworks include React and React+Redux. You can see the list of available SPA templates by running `dotnet new spa`.
|
||||
|
||||
Once the generator has run and restored all the dependencies, you can start up your new ASP.NET Core SPA:
|
||||
|
||||
npm install
|
||||
dotnet run
|
||||
|
||||
### Option 2: Creating Angular/React/Redux applications using Visual Studio 2017 Update 3 or later (Windows only)
|
||||
|
||||
Using the `File`->`New Project` dialog, select *ASP.NET Core Web Application*. You will then be offered the option to create an application with Angular, React, or React+Redux. When the application is created, you can build and run it in the normal way.
|
||||
|
||||
### More info and other SPA frameworks
|
||||
|
||||
For a more detailed (albeit somewhat outdated) walkthrough, see [getting started with the `aspnetcore-spa` generator](http://blog.stevensanderson.com/2016/05/02/angular2-react-knockout-apps-on-aspnet-core/).
|
||||
|
||||
If you want to build an ASP.NET Core application with Aurelia, Knockout, or Vue, you can use the `Microsoft.AspNetCore.SpaTemplates` package. On the command line, run `dotnet new --install Microsoft.AspNetCore.SpaTemplates`. Then you will be able to run `dotnet new aurelia` (or `dotnet new vue`, etc.) to create your new application.
|
||||
|
||||
## Adding to existing applications
|
||||
|
||||
If you have an existing ASP.NET Core application, or if you just want to use the underlying JavaScriptServices packages directly, you can install these packages using NuGet and NPM:
|
||||
|
||||
* `Microsoft.AspNetCore.NodeServices`
|
||||
* This provides a fast and robust way for .NET code to run JavaScript on the server inside a Node.js environment. You can use this to consume arbitrary functionality from NPM packages at runtime in your ASP.NET Core app.
|
||||
* Most applications developers don't need to use this directly, but you can do so if you want to implement your own functionality that involves calling Node.js code from .NET at runtime.
|
||||
* Find [documentation and usage examples here](/src/Microsoft.AspNetCore.NodeServices#microsoftaspnetcorenodeservices).
|
||||
* `Microsoft.AspNetCore.SpaServices`
|
||||
* This provides infrastructure that's generally useful when building Single Page Applications (SPAs) with technologies such as Angular or React (for example, server-side prerendering and webpack middleware). Internally, it uses the `NodeServices` package to implement its features.
|
||||
* Find [documentation and usage examples here](/src/Microsoft.AspNetCore.SpaServices#microsoftaspnetcorespaservices)
|
||||
|
||||
There were previously other packages called `Microsoft.AspNetCore.AngularServices` and `Microsoft.AspNetCore.ReactServices` but these are not currently needed - all applicable functionality is in `Microsoft.AspNetCore.SpaServices`, because it's sufficiently general.
|
||||
|
||||
If you want to build a helper library for some other SPA framework, you can do so by taking a dependency on `Microsoft.AspNetCore.SpaServices` and wrapping its functionality in whatever way is most useful for your SPA framework.
|
||||
|
||||
## Samples
|
||||
|
||||
The [`samples` directory](/samples) contains examples of:
|
||||
|
||||
- Using the JavaScript services family of packages with Angular and React.
|
||||
- A standalone `NodeServices` usage for runtime code transpilation and image processing.
|
||||
|
||||
**To run the samples:**
|
||||
|
||||
* Clone this repo
|
||||
* At the repo's root directory (the one containing `src`, `samples`, etc.), run `dotnet restore`
|
||||
* Change directory to the sample you want to run (for example, `cd samples/angular/MusicStore`)
|
||||
* Restore Node dependencies by running `npm install`
|
||||
* If you're trying to run the Angular "Music Store" sample, then also run `gulp` (which you need to have installed globally). None of the other samples require this.
|
||||
* Run the application (`dotnet run`)
|
||||
* Browse to [http://localhost:5000](http://localhost:5000)
|
||||
|
||||
## Contributing
|
||||
|
||||
If you're interested in contributing to the various packages, samples, and project templates in this repo, that's great!
|
||||
|
||||
Before working on a pull request, especially if it's more than a trivial fix (for example, for a typo), it's usually a good idea first to file an issue describing what you're proposing to do and how it will work. Then you can find out if it's likely that such a pull request will be accepted, and how it fits into wider ongoing plans.
|
||||
@@ -1,30 +0,0 @@
|
||||
<Project>
|
||||
<PropertyGroup>
|
||||
<MSBuildAllProjects>$(MSBuildAllProjects);$(MSBuildThisFileFullPath)</MSBuildAllProjects>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Label="Package Versions">
|
||||
<InternalAspNetCoreSdkPackageVersion>3.0.0-build-20181114.5</InternalAspNetCoreSdkPackageVersion>
|
||||
<MicrosoftAspNetCoreDiagnosticsPackageVersion>3.0.0-alpha1-10742</MicrosoftAspNetCoreDiagnosticsPackageVersion>
|
||||
<MicrosoftAspNetCoreHostingAbstractionsPackageVersion>3.0.0-alpha1-10742</MicrosoftAspNetCoreHostingAbstractionsPackageVersion>
|
||||
<MicrosoftAspNetCoreHostingPackageVersion>3.0.0-alpha1-10742</MicrosoftAspNetCoreHostingPackageVersion>
|
||||
<MicrosoftAspNetCoreMvcPackageVersion>3.0.0-alpha1-10742</MicrosoftAspNetCoreMvcPackageVersion>
|
||||
<MicrosoftAspNetCoreMvcTagHelpersPackageVersion>3.0.0-alpha1-10742</MicrosoftAspNetCoreMvcTagHelpersPackageVersion>
|
||||
<MicrosoftAspNetCoreMvcViewFeaturesPackageVersion>3.0.0-alpha1-10742</MicrosoftAspNetCoreMvcViewFeaturesPackageVersion>
|
||||
<MicrosoftAspNetCoreServerIISIntegrationPackageVersion>3.0.0-alpha1-10742</MicrosoftAspNetCoreServerIISIntegrationPackageVersion>
|
||||
<MicrosoftAspNetCoreServerKestrelPackageVersion>3.0.0-alpha1-10742</MicrosoftAspNetCoreServerKestrelPackageVersion>
|
||||
<MicrosoftAspNetCoreStaticFilesPackageVersion>3.0.0-alpha1-10742</MicrosoftAspNetCoreStaticFilesPackageVersion>
|
||||
<MicrosoftAspNetCoreWebSocketsPackageVersion>3.0.0-alpha1-10742</MicrosoftAspNetCoreWebSocketsPackageVersion>
|
||||
<MicrosoftExtensionsDependencyInjectionPackageVersion>3.0.0-preview-181113-11</MicrosoftExtensionsDependencyInjectionPackageVersion>
|
||||
<MicrosoftExtensionsFileProvidersPhysicalPackageVersion>3.0.0-preview-181113-11</MicrosoftExtensionsFileProvidersPhysicalPackageVersion>
|
||||
<MicrosoftExtensionsLoggingAbstractionsPackageVersion>3.0.0-preview-181113-11</MicrosoftExtensionsLoggingAbstractionsPackageVersion>
|
||||
<MicrosoftExtensionsLoggingConsolePackageVersion>3.0.0-preview-181113-11</MicrosoftExtensionsLoggingConsolePackageVersion>
|
||||
<MicrosoftExtensionsLoggingDebugPackageVersion>3.0.0-preview-181113-11</MicrosoftExtensionsLoggingDebugPackageVersion>
|
||||
<MicrosoftNETCoreAppPackageVersion>3.0.0-preview1-26907-05</MicrosoftNETCoreAppPackageVersion>
|
||||
<MicrosoftNETSdkRazorPackageVersion>3.0.0-alpha1-10742</MicrosoftNETSdkRazorPackageVersion>
|
||||
<NETStandardLibrary20PackageVersion>2.0.3</NETStandardLibrary20PackageVersion>
|
||||
<NewtonsoftJsonPackageVersion>11.0.2</NewtonsoftJsonPackageVersion>
|
||||
<SystemThreadingTasksDataflowPackageVersion>4.10.0-preview1-26907-04</SystemThreadingTasksDataflowPackageVersion>
|
||||
</PropertyGroup>
|
||||
<Import Project="$(DotNetPackageVersionPropsPath)" Condition=" '$(DotNetPackageVersionPropsPath)' != '' " />
|
||||
<PropertyGroup Label="Package Versions: Pinned" />
|
||||
</Project>
|
||||
@@ -1,17 +0,0 @@
|
||||
<Project>
|
||||
<Import Project="$(DotNetRestoreSourcePropsPath)" Condition="'$(DotNetRestoreSourcePropsPath)' != ''"/>
|
||||
|
||||
<PropertyGroup Label="RestoreSources">
|
||||
<RestoreSources>$(DotNetRestoreSources)</RestoreSources>
|
||||
<RestoreSources Condition="'$(DotNetBuildOffline)' != 'true' AND '$(AspNetUniverseBuildOffline)' != 'true' ">
|
||||
$(RestoreSources);
|
||||
https://dotnet.myget.org/F/dotnet-core/api/v3/index.json;
|
||||
https://dotnet.myget.org/F/aspnetcore-dev/api/v3/index.json;
|
||||
https://dotnet.myget.org/F/aspnetcore-tools/api/v3/index.json;
|
||||
</RestoreSources>
|
||||
<RestoreSources Condition="'$(DotNetBuildOffline)' != 'true'">
|
||||
$(RestoreSources);
|
||||
https://api.nuget.org/v3/index.json;
|
||||
</RestoreSources>
|
||||
</PropertyGroup>
|
||||
</Project>
|
||||
@@ -1,19 +0,0 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>netcoreapp3.0</TargetFramework>
|
||||
<IsPackable>false</IsPackable>
|
||||
<OutputType>exe</OutputType>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\..\..\src\Microsoft.AspNetCore.NodeServices\Microsoft.AspNetCore.NodeServices.csproj" />
|
||||
<ProjectReference Include="..\..\..\src\Microsoft.AspNetCore.NodeServices.Sockets\Microsoft.AspNetCore.NodeServices.Sockets.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="$(MicrosoftExtensionsDependencyInjectionPackageVersion)" />
|
||||
<PackageReference Include="Microsoft.Extensions.Logging.Console" Version="$(MicrosoftExtensionsLoggingConsolePackageVersion)" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
@@ -1,52 +0,0 @@
|
||||
using System;
|
||||
using System.Diagnostics;
|
||||
using System.IO;
|
||||
using System.Threading.Tasks;
|
||||
using Microsoft.AspNetCore.NodeServices;
|
||||
using Microsoft.AspNetCore.NodeServices.Sockets;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
|
||||
namespace ConsoleApplication
|
||||
{
|
||||
// This project is a micro-benchmark for .NET->Node RPC via NodeServices. It doesn't reflect
|
||||
// real-world usage patterns (you're not likely to make hundreds of sequential calls like this),
|
||||
// but is a starting point for comparing the overhead of different hosting models and transports.
|
||||
public class Program
|
||||
{
|
||||
public static void Main(string[] args) {
|
||||
// Set up the DI system
|
||||
var services = new ServiceCollection();
|
||||
services.AddNodeServices(options => {
|
||||
// To compare with Socket hosting, uncomment the following line
|
||||
// Since .NET Core 1.1, the HTTP hosting model has become basically as fast as the Socket hosting model
|
||||
//options.UseSocketHosting();
|
||||
|
||||
options.WatchFileExtensions = new string[] {}; // Don't watch anything
|
||||
});
|
||||
var serviceProvider = services.BuildServiceProvider();
|
||||
|
||||
// Now instantiate an INodeServices and use it
|
||||
using (var nodeServices = serviceProvider.GetRequiredService<INodeServices>()) {
|
||||
MeasureLatency(nodeServices).Wait();
|
||||
}
|
||||
}
|
||||
|
||||
private static async Task MeasureLatency(INodeServices nodeServices) {
|
||||
// Ensure the connection is open, so we can measure per-request timings below
|
||||
var response = await nodeServices.InvokeAsync<string>("latencyTest", "C#");
|
||||
Console.WriteLine(response);
|
||||
|
||||
// Now perform a series of requests, capturing the time taken
|
||||
const int requestCount = 100;
|
||||
var watch = Stopwatch.StartNew();
|
||||
for (var i = 0; i < requestCount; i++) {
|
||||
await nodeServices.InvokeAsync<string>("latencyTest", "C#");
|
||||
}
|
||||
|
||||
// Display results
|
||||
var elapsedSeconds = (float)watch.ElapsedTicks / Stopwatch.Frequency;
|
||||
Console.WriteLine("\nTotal time: {0:F2} milliseconds", 1000 * elapsedSeconds);
|
||||
Console.WriteLine("\nTime per invocation: {0:F2} milliseconds", 1000 * elapsedSeconds / requestCount);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,4 +0,0 @@
|
||||
module.exports = function(callback, incomingParam1) {
|
||||
var result = 'Hello, ' + incomingParam1 + '!';
|
||||
callback(/* error */ null, result);
|
||||
}
|
||||
@@ -1,2 +0,0 @@
|
||||
/node_modules/
|
||||
/Properties/launchSettings.json
|
||||
@@ -1,57 +0,0 @@
|
||||
using System.Threading.Tasks;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.AspNetCore.NodeServices;
|
||||
using Microsoft.AspNetCore.SpaServices.Prerendering;
|
||||
|
||||
namespace NodeServicesExamples.Controllers
|
||||
{
|
||||
public class HomeController : Controller
|
||||
{
|
||||
public IActionResult Index(int pageIndex)
|
||||
{
|
||||
return View();
|
||||
}
|
||||
|
||||
public IActionResult ES2015Transpilation()
|
||||
{
|
||||
return View();
|
||||
}
|
||||
|
||||
public async Task<IActionResult> Chart([FromServices] INodeServices nodeServices)
|
||||
{
|
||||
var options = new { width = 400, height = 200, showArea = true, showPoint = true, fullWidth = true };
|
||||
var data = new
|
||||
{
|
||||
labels = new[] { "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" },
|
||||
series = new[] {
|
||||
new[] { 1, 5, 2, 5, 4, 3 },
|
||||
new[] { 2, 3, 4, 8, 1, 2 },
|
||||
new[] { 5, 4, 3, 2, 1, 0 }
|
||||
}
|
||||
};
|
||||
|
||||
ViewData["ChartMarkup"] = await nodeServices.InvokeAsync<string>("./Node/renderChart", "line", options, data);
|
||||
|
||||
return View();
|
||||
}
|
||||
|
||||
public async Task<IActionResult> Prerendering([FromServices] ISpaPrerenderer prerenderer)
|
||||
{
|
||||
var result = await prerenderer.RenderToString("./Node/prerenderPage");
|
||||
|
||||
if (!string.IsNullOrEmpty(result.RedirectUrl))
|
||||
{
|
||||
return Redirect(result.RedirectUrl);
|
||||
}
|
||||
|
||||
ViewData["PrerenderedHtml"] = result.Html;
|
||||
ViewData["PrerenderedGlobals"] = result.CreateGlobalsAssignmentScript();
|
||||
return View();
|
||||
}
|
||||
|
||||
public IActionResult Error()
|
||||
{
|
||||
return View("~/Views/Shared/Error.cshtml");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,14 +0,0 @@
|
||||
var createServerRenderer = require('aspnet-prerendering').createServerRenderer;
|
||||
|
||||
module.exports = createServerRenderer(function(params) {
|
||||
return new Promise(function (resolve, reject) {
|
||||
var message = 'The HTML was returned by the prerendering boot function. '
|
||||
+ 'The boot function received the following params:'
|
||||
+ '<pre>' + JSON.stringify(params, null, 4) + '</pre>';
|
||||
|
||||
resolve({
|
||||
html: '<h3>Hello, world!</h3>' + message,
|
||||
globals: { sampleData: { nodeVersion: process.version } }
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,8 +0,0 @@
|
||||
var generate = require('node-chartist');
|
||||
|
||||
module.exports = function (callback, type, options, data) {
|
||||
generate(type, options, data).then(
|
||||
result => callback(null, result), // Success case
|
||||
error => callback(error) // Error case
|
||||
);
|
||||
};
|
||||
@@ -1,12 +0,0 @@
|
||||
var fs = require('fs');
|
||||
var babelCore = require('babel-core');
|
||||
|
||||
module.exports = function(cb, physicalPath, requestPath) {
|
||||
var originalContents = fs.readFileSync(physicalPath);
|
||||
var result = babelCore.transform(originalContents, {
|
||||
presets: ['es2015'],
|
||||
sourceMaps: 'inline',
|
||||
sourceFileName: '/sourcemapped' + requestPath
|
||||
});
|
||||
cb(null, result.code);
|
||||
}
|
||||
@@ -1,29 +0,0 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk.Web">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>netcoreapp3.0</TargetFramework>
|
||||
<TypeScriptCompileBlocked>true</TypeScriptCompileBlocked>
|
||||
<IsPackable>false</IsPackable>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\..\..\src\Microsoft.AspNetCore.SpaServices\Microsoft.AspNetCore.SpaServices.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Microsoft.AspNetCore.Diagnostics" Version="$(MicrosoftAspNetCoreDiagnosticsPackageVersion)" />
|
||||
<PackageReference Include="Microsoft.AspNetCore.Hosting" Version="$(MicrosoftAspNetCoreHostingPackageVersion)" />
|
||||
<PackageReference Include="Microsoft.AspNetCore.Server.IISIntegration" Version="$(MicrosoftAspNetCoreServerIISIntegrationPackageVersion)" />
|
||||
<PackageReference Include="Microsoft.AspNetCore.Mvc" Version="$(MicrosoftAspNetCoreMvcPackageVersion)" />
|
||||
<PackageReference Include="Microsoft.AspNetCore.Server.Kestrel" Version="$(MicrosoftAspNetCoreServerKestrelPackageVersion)" />
|
||||
<PackageReference Include="Microsoft.AspNetCore.StaticFiles" Version="$(MicrosoftAspNetCoreStaticFilesPackageVersion)" />
|
||||
<PackageReference Include="Microsoft.Extensions.Logging.Debug" Version="$(MicrosoftExtensionsLoggingDebugPackageVersion)" />
|
||||
<PackageReference Include="Microsoft.Extensions.Logging.Console" Version="$(MicrosoftExtensionsLoggingConsolePackageVersion)" />
|
||||
<PackageReference Include="Microsoft.NET.Sdk.Razor" Version="$(MicrosoftNETSdkRazorPackageVersion)" PrivateAssets="All" />
|
||||
</ItemGroup>
|
||||
|
||||
<Target Name="PrepublishScript" BeforeTargets="PrepareForPublish">
|
||||
<Exec Command="npm install" />
|
||||
</Target>
|
||||
|
||||
</Project>
|
||||
@@ -1,70 +0,0 @@
|
||||
using Microsoft.AspNetCore.Builder;
|
||||
using Microsoft.AspNetCore.Hosting;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.AspNetCore.NodeServices;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using System.IO;
|
||||
|
||||
namespace NodeServicesExamples
|
||||
{
|
||||
public class Startup
|
||||
{
|
||||
// This method gets called by the runtime. Use this method to add services to the container.
|
||||
public void ConfigureServices(IServiceCollection services)
|
||||
{
|
||||
services.AddMvc();
|
||||
|
||||
// Enable Node Services
|
||||
services.AddNodeServices();
|
||||
services.AddSpaPrerenderer();
|
||||
}
|
||||
|
||||
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
|
||||
public void Configure(IApplicationBuilder app, ILoggerFactory loggerFactory, IHostingEnvironment env, INodeServices nodeServices)
|
||||
{
|
||||
app.UseDeveloperExceptionPage();
|
||||
|
||||
// Dynamically transpile any .js files under the '/js/' directory
|
||||
app.Use(next => async context => {
|
||||
var requestPath = context.Request.Path.Value;
|
||||
if (requestPath.StartsWith("/js/") && requestPath.EndsWith(".js")) {
|
||||
var fileInfo = env.WebRootFileProvider.GetFileInfo(requestPath);
|
||||
if (fileInfo.Exists) {
|
||||
var transpiled = await nodeServices.InvokeAsync<string>("./Node/transpilation.js", fileInfo.PhysicalPath, requestPath);
|
||||
await context.Response.WriteAsync(transpiled);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
// Not a JS file, or doesn't exist - let some other middleware handle it
|
||||
await next.Invoke(context);
|
||||
});
|
||||
|
||||
app.UseStaticFiles();
|
||||
app.UseMvc(routes =>
|
||||
{
|
||||
routes.MapRoute(
|
||||
name: "default",
|
||||
template: "{controller=Home}/{action=Index}/{id?}");
|
||||
});
|
||||
}
|
||||
|
||||
public static void Main(string[] args)
|
||||
{
|
||||
var host = new WebHostBuilder()
|
||||
.ConfigureLogging(factory =>
|
||||
{
|
||||
factory.AddConsole();
|
||||
factory.AddDebug();
|
||||
})
|
||||
.UseContentRoot(Directory.GetCurrentDirectory())
|
||||
.UseIISIntegration()
|
||||
.UseKestrel()
|
||||
.UseStartup<Startup>()
|
||||
.Build();
|
||||
|
||||
host.Run();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,12 +0,0 @@
|
||||
<h1>Server-rendered chart</h1>
|
||||
|
||||
<p>
|
||||
This sample demonstrates how arbitrary NPM modules can be invoked from .NET code.
|
||||
</p>
|
||||
<p>
|
||||
In this case, we use <code>node-chartist</code> to render the following chart on the server. The output is
|
||||
identical to what you'd get if you used <a href='https://gionkunz.github.io/chartist-js/'>chartist.js</a>
|
||||
on the client, except that in this example, we're not executing any client-side code at all.
|
||||
</p>
|
||||
|
||||
@Html.Raw(ViewData["ChartMarkup"])
|
||||
@@ -1,16 +0,0 @@
|
||||
<h1>ES2015 Transpilation</h1>
|
||||
|
||||
<p>
|
||||
This sample demonstrates a way of intercepting requests for .js files and dynamically transpiling them
|
||||
from ES2015 code to browser-compatible ES5 code using the Babel library.
|
||||
</p>
|
||||
|
||||
<p>
|
||||
To see that it's working, open your browser's 'Debug' console and look for the log message. This is
|
||||
produced by the file <a href='/js/main.js'>/js/main.js</a>, which is transpiled from ES2015 dynamically
|
||||
when requested.
|
||||
</p>
|
||||
|
||||
@section scripts {
|
||||
<script src='/js/main.js'></script>
|
||||
}
|
||||
@@ -1,13 +0,0 @@
|
||||
<h1>NodeServices examples</h1>
|
||||
|
||||
<p>
|
||||
These examples demonstrate the direct use of the NodeServices package, independently of the usual SPA scenarios.
|
||||
In general, NodeServices offers an efficient way to use Node-provided functionality (e.g., NPM modules) from inside
|
||||
a .NET application.
|
||||
</p>
|
||||
|
||||
<ul>
|
||||
<li><a asp-action="ES2015Transpilation">ES2015 transpilation</a></li>
|
||||
<li><a asp-action="Chart">Server-side chart rendering</a></li>
|
||||
<li><a asp-action="Prerendering">Server-side SPA prerendering</a></li>
|
||||
</ul>
|
||||
@@ -1,21 +0,0 @@
|
||||
<h1>Server-side prerendering</h1>
|
||||
|
||||
<p>
|
||||
This sample demonstrates how you can invoke a JavaScript module that contains
|
||||
prerendering logic for a Single-Page Application framework.
|
||||
</p>
|
||||
</p>
|
||||
Your prerendering boot function will receive parameters that describe the page
|
||||
being rendered and any data supplied by the .NET code. The return value should be
|
||||
a promise that resolves with data to be injected into the page, such as the
|
||||
rendered HTML and any global data that should be made available to client-side code.
|
||||
</p>
|
||||
|
||||
@Html.Raw(ViewData["PrerenderedHtml"])
|
||||
|
||||
<script>@Html.Raw(ViewData["PrerenderedGlobals"])</script>
|
||||
|
||||
<script>
|
||||
// Demonstrates how client-side code can receive data from the prerendering process
|
||||
console.log('Received Node version from prerendering logic: ' + sampleData.nodeVersion);
|
||||
</script>
|
||||
@@ -1,6 +0,0 @@
|
||||
@{
|
||||
ViewData["Title"] = "Error";
|
||||
}
|
||||
|
||||
<h1 class="text-danger">Error.</h1>
|
||||
<h2 class="text-danger">An error occurred while processing your request.</h2>
|
||||
@@ -1,12 +0,0 @@
|
||||
<!doctype html>
|
||||
<html>
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<title>NodeServices Examples</title>
|
||||
<link rel="stylesheet" href="~/css/chartist.min.css" />
|
||||
</head>
|
||||
<body>
|
||||
@RenderBody()
|
||||
@RenderSection("scripts", required: false)
|
||||
</body>
|
||||
</html>
|
||||
@@ -1,2 +0,0 @@
|
||||
@using NodeServicesExamples
|
||||
@addTagHelper "*, Microsoft.AspNetCore.Mvc.TagHelpers"
|
||||
@@ -1,3 +0,0 @@
|
||||
@{
|
||||
Layout = "_Layout";
|
||||
}
|
||||
@@ -1 +0,0 @@
|
||||
{}
|
||||
@@ -1,6 +0,0 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "ES6",
|
||||
"module": "commonjs"
|
||||
}
|
||||
}
|
||||
@@ -1,10 +0,0 @@
|
||||
{
|
||||
"name": "nodeservicesexamples",
|
||||
"version": "0.0.0",
|
||||
"dependencies": {
|
||||
"aspnet-prerendering": "^2.0.6",
|
||||
"babel-core": "^6.7.4",
|
||||
"babel-preset-es2015": "^6.6.0",
|
||||
"node-chartist": "^1.0.2"
|
||||
}
|
||||
}
|
||||
File diff suppressed because one or more lines are too long
Binary file not shown.
|
Before Width: | Height: | Size: 31 KiB |
@@ -1,7 +0,0 @@
|
||||
class Greeting {
|
||||
getMessage() {
|
||||
return 'Hello from the ES2015 class';
|
||||
}
|
||||
}
|
||||
|
||||
console.log(new Greeting().getMessage());
|
||||
@@ -1,9 +0,0 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<configuration>
|
||||
<system.webServer>
|
||||
<handlers>
|
||||
<add name="httpPlatformHandler" path="*" verb="*" modules="httpPlatformHandler" resourceType="Unspecified" />
|
||||
</handlers>
|
||||
<httpPlatform processPath="%DNX_PATH%" arguments="%DNX_ARGS%" stdoutLogEnabled="false" forwardWindowsAuthToken="false" startupTimeLimit="3600" />
|
||||
</system.webServer>
|
||||
</configuration>
|
||||
@@ -1,233 +0,0 @@
|
||||
## Ignore Visual Studio temporary files, build results, and
|
||||
## files generated by popular Visual Studio add-ons.
|
||||
|
||||
yarn.lock
|
||||
wwwroot/dist
|
||||
|
||||
# User-specific files
|
||||
*.suo
|
||||
*.user
|
||||
*.userosscache
|
||||
*.sln.docstates
|
||||
|
||||
# User-specific files (MonoDevelop/Xamarin Studio)
|
||||
*.userprefs
|
||||
|
||||
# Build results
|
||||
[Dd]ebug/
|
||||
[Dd]ebugPublic/
|
||||
[Rr]elease/
|
||||
[Rr]eleases/
|
||||
x64/
|
||||
x86/
|
||||
build/
|
||||
bld/
|
||||
[Bb]in/
|
||||
[Oo]bj/
|
||||
|
||||
# Visual Studio 2015 cache/options directory
|
||||
.vs/
|
||||
# Uncomment if you have tasks that create the project's static files in wwwroot
|
||||
#wwwroot/
|
||||
|
||||
# MSTest test Results
|
||||
[Tt]est[Rr]esult*/
|
||||
[Bb]uild[Ll]og.*
|
||||
|
||||
# NUNIT
|
||||
*.VisualState.xml
|
||||
TestResult.xml
|
||||
|
||||
# Build Results of an ATL Project
|
||||
[Dd]ebugPS/
|
||||
[Rr]eleasePS/
|
||||
dlldata.c
|
||||
|
||||
*_i.c
|
||||
*_p.c
|
||||
*_i.h
|
||||
*.ilk
|
||||
*.meta
|
||||
*.obj
|
||||
*.pch
|
||||
*.pdb
|
||||
*.pgc
|
||||
*.pgd
|
||||
*.rsp
|
||||
*.sbr
|
||||
*.tlb
|
||||
*.tli
|
||||
*.tlh
|
||||
*.tmp
|
||||
*.tmp_proj
|
||||
*.log
|
||||
*.vspscc
|
||||
*.vssscc
|
||||
.builds
|
||||
*.pidb
|
||||
*.svclog
|
||||
*.scc
|
||||
|
||||
# Chutzpah Test files
|
||||
_Chutzpah*
|
||||
|
||||
# Visual C++ cache files
|
||||
ipch/
|
||||
*.aps
|
||||
*.ncb
|
||||
*.opendb
|
||||
*.opensdf
|
||||
*.sdf
|
||||
*.cachefile
|
||||
|
||||
# Visual Studio profiler
|
||||
*.psess
|
||||
*.vsp
|
||||
*.vspx
|
||||
*.sap
|
||||
|
||||
# TFS 2012 Local Workspace
|
||||
$tf/
|
||||
|
||||
# Guidance Automation Toolkit
|
||||
*.gpState
|
||||
|
||||
# ReSharper is a .NET coding add-in
|
||||
_ReSharper*/
|
||||
*.[Rr]e[Ss]harper
|
||||
*.DotSettings.user
|
||||
|
||||
# JustCode is a .NET coding add-in
|
||||
.JustCode
|
||||
|
||||
# TeamCity is a build add-in
|
||||
_TeamCity*
|
||||
|
||||
# DotCover is a Code Coverage Tool
|
||||
*.dotCover
|
||||
|
||||
# NCrunch
|
||||
_NCrunch_*
|
||||
.*crunch*.local.xml
|
||||
nCrunchTemp_*
|
||||
|
||||
# MightyMoose
|
||||
*.mm.*
|
||||
AutoTest.Net/
|
||||
|
||||
# Web workbench (sass)
|
||||
.sass-cache/
|
||||
|
||||
# Installshield output folder
|
||||
[Ee]xpress/
|
||||
|
||||
# DocProject is a documentation generator add-in
|
||||
DocProject/buildhelp/
|
||||
DocProject/Help/*.HxT
|
||||
DocProject/Help/*.HxC
|
||||
DocProject/Help/*.hhc
|
||||
DocProject/Help/*.hhk
|
||||
DocProject/Help/*.hhp
|
||||
DocProject/Help/Html2
|
||||
DocProject/Help/html
|
||||
|
||||
# Click-Once directory
|
||||
publish/
|
||||
|
||||
# Publish Web Output
|
||||
*.[Pp]ublish.xml
|
||||
*.azurePubxml
|
||||
# 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
|
||||
|
||||
# NuGet Packages
|
||||
*.nupkg
|
||||
# The packages folder can be ignored because of Package Restore
|
||||
**/packages/*
|
||||
# except build/, which is used as an MSBuild target.
|
||||
!**/packages/build/
|
||||
# Uncomment if necessary however generally it will be regenerated when needed
|
||||
#!**/packages/repositories.config
|
||||
|
||||
# Microsoft Azure Build Output
|
||||
csx/
|
||||
*.build.csdef
|
||||
|
||||
# Microsoft Azure Emulator
|
||||
ecf/
|
||||
rcf/
|
||||
|
||||
# Microsoft Azure ApplicationInsights config file
|
||||
ApplicationInsights.config
|
||||
|
||||
# Windows Store app package directory
|
||||
AppPackages/
|
||||
BundleArtifacts/
|
||||
|
||||
# Visual Studio cache files
|
||||
# files ending in .cache can be ignored
|
||||
*.[Cc]ache
|
||||
# but keep track of directories ending in .cache
|
||||
!*.[Cc]ache/
|
||||
|
||||
# Others
|
||||
ClientBin/
|
||||
~$*
|
||||
*~
|
||||
*.dbmdl
|
||||
*.dbproj.schemaview
|
||||
*.pfx
|
||||
*.publishsettings
|
||||
node_modules/
|
||||
orleans.codegen.cs
|
||||
|
||||
# RIA/Silverlight projects
|
||||
Generated_Code/
|
||||
|
||||
# Backup & report files from converting an old project file
|
||||
# to a newer Visual Studio version. Backup files are not needed,
|
||||
# because we have git ;-)
|
||||
_UpgradeReport_Files/
|
||||
Backup*/
|
||||
UpgradeLog*.XML
|
||||
UpgradeLog*.htm
|
||||
|
||||
# SQL Server files
|
||||
*.mdf
|
||||
*.ldf
|
||||
|
||||
# Business Intelligence projects
|
||||
*.rdl.data
|
||||
*.bim.layout
|
||||
*.bim_*.settings
|
||||
|
||||
# Microsoft Fakes
|
||||
FakesAssemblies/
|
||||
|
||||
# GhostDoc plugin setting file
|
||||
*.GhostDoc.xml
|
||||
|
||||
# Node.js Tools for Visual Studio
|
||||
.ntvs_analysis.dat
|
||||
|
||||
# Visual Studio 6 build log
|
||||
*.plg
|
||||
|
||||
# Visual Studio 6 workspace options file
|
||||
*.opt
|
||||
|
||||
# Visual Studio LightSwitch build output
|
||||
**/*.HTMLClient/GeneratedArtifacts
|
||||
**/*.DesktopClient/GeneratedArtifacts
|
||||
**/*.DesktopClient/ModelManifest.xml
|
||||
**/*.Server/GeneratedArtifacts
|
||||
**/*.Server/ModelManifest.xml
|
||||
_Pvt_Extensions
|
||||
|
||||
# Paket dependency manager
|
||||
.paket/paket.exe
|
||||
|
||||
# FAKE - F# Make
|
||||
.fake/
|
||||
@@ -1,51 +0,0 @@
|
||||
using System.Threading.Tasks;
|
||||
using Microsoft.AspNetCore.Hosting;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.AspNetCore.Http.Extensions;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.AspNetCore.NodeServices;
|
||||
using Microsoft.AspNetCore.SpaServices.Prerendering;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
|
||||
namespace Webpack.ActionResults
|
||||
{
|
||||
// This is an example of how you could invoke the prerendering API from an ActionResult, so as to
|
||||
// prerender a SPA component as the entire response page (instead of injecting the SPA component
|
||||
// into a Razor view's output)
|
||||
public class PrerenderResult : ActionResult
|
||||
{
|
||||
private JavaScriptModuleExport _moduleExport;
|
||||
private object _dataToSupply;
|
||||
|
||||
public PrerenderResult(JavaScriptModuleExport moduleExport, object dataToSupply = null)
|
||||
{
|
||||
_moduleExport = moduleExport;
|
||||
_dataToSupply = dataToSupply;
|
||||
}
|
||||
|
||||
public override async Task ExecuteResultAsync(ActionContext context)
|
||||
{
|
||||
var nodeServices = context.HttpContext.RequestServices.GetRequiredService<INodeServices>();
|
||||
var hostEnv = context.HttpContext.RequestServices.GetRequiredService<IHostingEnvironment>();
|
||||
var applicationLifetime = context.HttpContext.RequestServices.GetRequiredService<IApplicationLifetime>();
|
||||
var applicationBasePath = hostEnv.ContentRootPath;
|
||||
var request = context.HttpContext.Request;
|
||||
var response = context.HttpContext.Response;
|
||||
|
||||
var prerenderedHtml = await Prerenderer.RenderToString(
|
||||
applicationBasePath,
|
||||
nodeServices,
|
||||
applicationLifetime.ApplicationStopping,
|
||||
_moduleExport,
|
||||
request.GetEncodedUrl(),
|
||||
request.Path + request.QueryString.Value,
|
||||
_dataToSupply,
|
||||
/* timeoutMilliseconds */ 30000,
|
||||
/* requestPathBase */ "/"
|
||||
);
|
||||
|
||||
response.ContentType = "text/html";
|
||||
await response.WriteAsync(prerenderedHtml.Html);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,13 +0,0 @@
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.AspNetCore.SpaServices.Prerendering;
|
||||
|
||||
namespace Webpack.ActionResults
|
||||
{
|
||||
public static class PrerenderResultExtensions
|
||||
{
|
||||
public static PrerenderResult Prerender(this ControllerBase controller, JavaScriptModuleExport exportToPrerender, object dataToSupply = null)
|
||||
{
|
||||
return new PrerenderResult(exportToPrerender, dataToSupply);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,4 +0,0 @@
|
||||
import { HelloWorld } from './HelloWorld';
|
||||
import './styles/main.less';
|
||||
|
||||
new HelloWorld().doIt();
|
||||
@@ -1,5 +0,0 @@
|
||||
export class HelloWorld {
|
||||
public doIt() {
|
||||
console.log('Hello from MyApp');
|
||||
}
|
||||
}
|
||||
@@ -1,5 +0,0 @@
|
||||
@headerColor: red;
|
||||
|
||||
h1 {
|
||||
color: @headerColor;
|
||||
}
|
||||
@@ -1,16 +0,0 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Threading.Tasks;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
|
||||
namespace Webpack.Controllers
|
||||
{
|
||||
public class HomeController : Controller
|
||||
{
|
||||
public IActionResult Index()
|
||||
{
|
||||
return View();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,25 +0,0 @@
|
||||
{
|
||||
"iisSettings": {
|
||||
"windowsAuthentication": false,
|
||||
"anonymousAuthentication": true,
|
||||
"iisExpress": {
|
||||
"applicationUrl": "http://localhost:51463/",
|
||||
"sslPort": 0
|
||||
}
|
||||
},
|
||||
"profiles": {
|
||||
"IIS Express": {
|
||||
"commandName": "IISExpress",
|
||||
"launchBrowser": true,
|
||||
"environmentVariables": {
|
||||
"ASPNETCORE_ENVIRONMENT": "Development"
|
||||
}
|
||||
},
|
||||
"dotnet cli": {
|
||||
"commandName": "Project",
|
||||
"environmentVariables": {
|
||||
"ASPNETCORE_ENVIRONMENT": "Development"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,60 +0,0 @@
|
||||
using Microsoft.AspNetCore.Builder;
|
||||
using Microsoft.AspNetCore.Hosting;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.AspNetCore.SpaServices.Webpack;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using System.IO;
|
||||
using Microsoft.AspNetCore.NodeServices;
|
||||
|
||||
namespace Webpack
|
||||
{
|
||||
public class Startup
|
||||
{
|
||||
// This method gets called by the runtime. Use this method to add services to the container.
|
||||
public void ConfigureServices(IServiceCollection services)
|
||||
{
|
||||
services.AddMvc();
|
||||
services.AddNodeServices();
|
||||
}
|
||||
|
||||
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
|
||||
public void Configure(IApplicationBuilder app, ILoggerFactory loggerFactory, IHostingEnvironment env)
|
||||
{
|
||||
app.UseDeveloperExceptionPage();
|
||||
|
||||
// For real apps, you should only use Webpack Dev Middleware at development time. For production,
|
||||
// you'll get better performance and reliability if you precompile the webpack output and simply
|
||||
// serve the resulting static files. For examples of setting up this automatic switch between
|
||||
// development-style and production-style webpack usage, see the 'templates' dir in this repo.
|
||||
app.UseWebpackDevMiddleware(new WebpackDevMiddlewareOptions {
|
||||
HotModuleReplacement = true
|
||||
});
|
||||
|
||||
app.UseStaticFiles();
|
||||
app.UseMvc(routes =>
|
||||
{
|
||||
routes.MapRoute(
|
||||
name: "default",
|
||||
template: "{controller=Home}/{action=Index}/{id?}");
|
||||
});
|
||||
}
|
||||
|
||||
public static void Main(string[] args)
|
||||
{
|
||||
var host = new WebHostBuilder()
|
||||
.ConfigureLogging(factory =>
|
||||
{
|
||||
factory.AddConsole();
|
||||
factory.AddDebug();
|
||||
})
|
||||
.UseContentRoot(Directory.GetCurrentDirectory())
|
||||
.UseIISIntegration()
|
||||
.UseKestrel()
|
||||
.UseStartup<Startup>()
|
||||
.Build();
|
||||
|
||||
host.Run();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,10 +0,0 @@
|
||||
@{
|
||||
ViewData["Title"] = "Home Page";
|
||||
}
|
||||
|
||||
<h1>Hello</h1>
|
||||
Hi there. Enter some text: <input />
|
||||
|
||||
@section scripts {
|
||||
<script src="dist/main.js"></script>
|
||||
}
|
||||
@@ -1,6 +0,0 @@
|
||||
@{
|
||||
ViewData["Title"] = "Error";
|
||||
}
|
||||
|
||||
<h1 class="text-danger">Error.</h1>
|
||||
<h2 class="text-danger">An error occurred while processing your request.</h2>
|
||||
@@ -1,14 +0,0 @@
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<title>@ViewData["Title"]</title>
|
||||
<environment names="Production">
|
||||
<link rel="stylesheet" href="dist/my-styles.css" />
|
||||
</environment>
|
||||
</head>
|
||||
<body>
|
||||
@RenderBody()
|
||||
@RenderSection("scripts", required: false)
|
||||
</body>
|
||||
</html>
|
||||
@@ -1,2 +0,0 @@
|
||||
@using Webpack
|
||||
@addTagHelper "*, Microsoft.AspNetCore.Mvc.TagHelpers"
|
||||
@@ -1,3 +0,0 @@
|
||||
@{
|
||||
Layout = "_Layout";
|
||||
}
|
||||
@@ -1,29 +0,0 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk.Web">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>netcoreapp3.0</TargetFramework>
|
||||
<TypeScriptCompileBlocked>true</TypeScriptCompileBlocked>
|
||||
<IsPackable>false</IsPackable>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\..\..\src\Microsoft.AspNetCore.SpaServices\Microsoft.AspNetCore.SpaServices.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Microsoft.AspNetCore.Diagnostics" Version="$(MicrosoftAspNetCoreDiagnosticsPackageVersion)" />
|
||||
<PackageReference Include="Microsoft.AspNetCore.Hosting" Version="$(MicrosoftAspNetCoreHostingPackageVersion)" />
|
||||
<PackageReference Include="Microsoft.AspNetCore.Server.IISIntegration" Version="$(MicrosoftAspNetCoreServerIISIntegrationPackageVersion)" />
|
||||
<PackageReference Include="Microsoft.AspNetCore.Mvc" Version="$(MicrosoftAspNetCoreMvcPackageVersion)" />
|
||||
<PackageReference Include="Microsoft.AspNetCore.Server.Kestrel" Version="$(MicrosoftAspNetCoreServerKestrelPackageVersion)" />
|
||||
<PackageReference Include="Microsoft.AspNetCore.StaticFiles" Version="$(MicrosoftAspNetCoreStaticFilesPackageVersion)" />
|
||||
<PackageReference Include="Microsoft.Extensions.Logging.Debug" Version="$(MicrosoftExtensionsLoggingDebugPackageVersion)" />
|
||||
<PackageReference Include="Microsoft.Extensions.Logging.Console" Version="$(MicrosoftExtensionsLoggingConsolePackageVersion)" />
|
||||
<PackageReference Include="Microsoft.NET.Sdk.Razor" Version="$(MicrosoftNETSdkRazorPackageVersion)" PrivateAssets="All" />
|
||||
</ItemGroup>
|
||||
|
||||
<Target Name="PrepublishScript" BeforeTargets="PrepareForPublish">
|
||||
<Exec Command="npm install" />
|
||||
</Target>
|
||||
|
||||
</Project>
|
||||
@@ -1,10 +0,0 @@
|
||||
{
|
||||
"Logging": {
|
||||
"IncludeScopes": false,
|
||||
"LogLevel": {
|
||||
"Default": "Verbose",
|
||||
"System": "Information",
|
||||
"Microsoft": "Information"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,20 +0,0 @@
|
||||
{
|
||||
"name": "Webpack",
|
||||
"version": "0.0.0",
|
||||
"devDependencies": {
|
||||
"css-loader": "^0.23.1",
|
||||
"extendify": "^1.0.0",
|
||||
"extract-text-webpack-plugin": "^1.0.1",
|
||||
"less": "^2.6.0",
|
||||
"less-loader": "^2.2.2",
|
||||
"style-loader": "^0.13.0",
|
||||
"webpack-hot-middleware": "^2.7.1"
|
||||
},
|
||||
"dependencies": {
|
||||
"aspnet-prerendering": "^1.0.4",
|
||||
"aspnet-webpack": "^1.0.3",
|
||||
"ts-loader": "^0.8.1",
|
||||
"typescript": "^2.0.0",
|
||||
"webpack": "^1.13.3"
|
||||
}
|
||||
}
|
||||
@@ -1,13 +0,0 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"moduleResolution": "node",
|
||||
"module": "commonjs",
|
||||
"target": "es5",
|
||||
"jsx": "preserve",
|
||||
"sourceMap": true,
|
||||
"lib": ["es6", "dom"]
|
||||
},
|
||||
"exclude": [
|
||||
"node_modules"
|
||||
]
|
||||
}
|
||||
@@ -1,8 +0,0 @@
|
||||
module.exports = {
|
||||
devtool: 'inline-source-map',
|
||||
module: {
|
||||
loaders: [
|
||||
{ test: /\.less$/, loader: 'style-loader!css-loader!less-loader' }
|
||||
]
|
||||
}
|
||||
};
|
||||
@@ -1,25 +0,0 @@
|
||||
var path = require('path');
|
||||
var merge = require('extendify')({ isDeep: true, arrays: 'concat' });
|
||||
var devConfig = require('./webpack.config.dev');
|
||||
var prodConfig = require('./webpack.config.prod');
|
||||
var isDevelopment = process.env.ASPNETCORE_ENVIRONMENT === 'Development';
|
||||
|
||||
module.exports = merge({
|
||||
resolve: {
|
||||
extensions: [ '', '.js', '.jsx', '.ts', '.tsx' ]
|
||||
},
|
||||
module: {
|
||||
loaders: [
|
||||
{ test: /\.ts(x?)$/, exclude: /node_modules/, loader: 'ts-loader?silent' }
|
||||
],
|
||||
},
|
||||
entry: {
|
||||
main: ['./Clientside/App.ts']
|
||||
},
|
||||
output: {
|
||||
path: path.join(__dirname, 'wwwroot', 'dist'),
|
||||
filename: '[name].js',
|
||||
publicPath: '/dist/'
|
||||
},
|
||||
plugins: []
|
||||
}, isDevelopment ? devConfig : prodConfig);
|
||||
@@ -1,15 +0,0 @@
|
||||
var webpack = require('webpack');
|
||||
var ExtractTextPlugin = require('extract-text-webpack-plugin');
|
||||
var extractLESS = new ExtractTextPlugin('my-styles.css');
|
||||
|
||||
module.exports = {
|
||||
module: {
|
||||
loaders: [
|
||||
{ test: /\.less$/, loader: extractLESS.extract(['css-loader', 'less-loader']) },
|
||||
]
|
||||
},
|
||||
plugins: [
|
||||
extractLESS,
|
||||
new webpack.optimize.UglifyJsPlugin({ minimize: true, compressor: { warnings: false } })
|
||||
]
|
||||
};
|
||||
Binary file not shown.
|
Before Width: | Height: | Size: 31 KiB |
@@ -1,9 +0,0 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<configuration>
|
||||
<system.webServer>
|
||||
<handlers>
|
||||
<add name="httpPlatformHandler" path="*" verb="*" modules="httpPlatformHandler" resourceType="Unspecified"/>
|
||||
</handlers>
|
||||
<httpPlatform processPath="%DNX_PATH%" arguments="%DNX_ARGS%" stdoutLogEnabled="false"/>
|
||||
</system.webServer>
|
||||
</configuration>
|
||||
@@ -1,28 +0,0 @@
|
||||
[cmdletbinding(SupportsShouldProcess = $true)]
|
||||
param(
|
||||
)
|
||||
|
||||
$ErrorActionPreference = 'Stop'
|
||||
Set-StrictMode -Version 2
|
||||
|
||||
Push-Location "src"
|
||||
try {
|
||||
$dirs = Get-ChildItem -Directory
|
||||
foreach($dir in $dirs)
|
||||
{
|
||||
Push-Location $dir
|
||||
try{
|
||||
if(Test-Path -Path "package.json")
|
||||
{
|
||||
npm install
|
||||
npm run build
|
||||
}
|
||||
}
|
||||
finally{
|
||||
Pop-Location
|
||||
}
|
||||
}
|
||||
}
|
||||
finally {
|
||||
Pop-Location
|
||||
}
|
||||
@@ -1,3 +0,0 @@
|
||||
/bin/
|
||||
/node_modules/
|
||||
yarn.lock
|
||||
@@ -1,626 +0,0 @@
|
||||
(function (e, a) { for (var i in a) e[i] = a[i]; }(exports, /******/(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, exports, __webpack_require__) {
|
||||
|
||||
module.exports = __webpack_require__(1);
|
||||
|
||||
|
||||
/***/
|
||||
}),
|
||||
/* 1 */
|
||||
/***/ (function (module, exports, __webpack_require__) {
|
||||
|
||||
"use strict";
|
||||
|
||||
exports.__esModule = true;
|
||||
// Limit dependencies to core Node modules. This means the code in this file has to be very low-level and unattractive,
|
||||
// but simplifies things for the consumer of this module.
|
||||
__webpack_require__(2);
|
||||
var net = __webpack_require__(3);
|
||||
var path = __webpack_require__(4);
|
||||
var readline = __webpack_require__(5);
|
||||
var ArgsUtil_1 = __webpack_require__(6);
|
||||
var ExitWhenParentExits_1 = __webpack_require__(7);
|
||||
var virtualConnectionServer = __webpack_require__(8);
|
||||
// Webpack doesn't support dynamic requires for files not present at compile time, so grab a direct
|
||||
// reference to Node's runtime 'require' function.
|
||||
var dynamicRequire = eval('require');
|
||||
// Signal to the .NET side when we're ready to accept invocations
|
||||
var server = net.createServer().on('listening', function () {
|
||||
console.log('[Microsoft.AspNetCore.NodeServices:Listening]');
|
||||
});
|
||||
// Each virtual connection represents a separate invocation
|
||||
virtualConnectionServer.createInterface(server).on('connection', function (connection) {
|
||||
readline.createInterface(connection, null).on('line', function (line) {
|
||||
try {
|
||||
// Get a reference to the function to invoke
|
||||
var invocation = JSON.parse(line);
|
||||
var invokedModule = dynamicRequire(path.resolve(process.cwd(), invocation.moduleName));
|
||||
var invokedFunction = invocation.exportedFunctionName ? invokedModule[invocation.exportedFunctionName] : invokedModule;
|
||||
// Prepare a callback for accepting non-streamed JSON responses
|
||||
var hasInvokedCallback_1 = false;
|
||||
var invocationCallback = function (errorValue, successValue) {
|
||||
if (hasInvokedCallback_1) {
|
||||
throw new Error('Cannot supply more than one result. The callback has already been invoked,'
|
||||
+ ' or the result stream has already been accessed');
|
||||
}
|
||||
hasInvokedCallback_1 = true;
|
||||
connection.end(JSON.stringify({
|
||||
result: successValue,
|
||||
errorMessage: errorValue && (errorValue.message || errorValue),
|
||||
errorDetails: errorValue && (errorValue.stack || null)
|
||||
}));
|
||||
};
|
||||
// Also support streamed binary responses
|
||||
Object.defineProperty(invocationCallback, 'stream', {
|
||||
enumerable: true,
|
||||
get: function () {
|
||||
hasInvokedCallback_1 = true;
|
||||
return connection;
|
||||
}
|
||||
});
|
||||
// Actually invoke it, passing through any supplied args
|
||||
invokedFunction.apply(null, [invocationCallback].concat(invocation.args));
|
||||
}
|
||||
catch (ex) {
|
||||
connection.end(JSON.stringify({
|
||||
errorMessage: ex.message,
|
||||
errorDetails: ex.stack
|
||||
}));
|
||||
}
|
||||
});
|
||||
});
|
||||
// Begin listening now. The underlying transport varies according to the runtime platform.
|
||||
// On Windows it's Named Pipes; on Linux/OSX it's Domain Sockets.
|
||||
var useWindowsNamedPipes = /^win/.test(process.platform);
|
||||
var parsedArgs = ArgsUtil_1.parseArgs(process.argv);
|
||||
var listenAddress = (useWindowsNamedPipes ? '\\\\.\\pipe\\' : '/tmp/') + parsedArgs.listenAddress;
|
||||
server.listen(listenAddress);
|
||||
ExitWhenParentExits_1.exitWhenParentExits(parseInt(parsedArgs.parentPid), /* ignoreSigint */ true);
|
||||
|
||||
|
||||
/***/
|
||||
}),
|
||||
/* 2 */
|
||||
/***/ (function (module, exports) {
|
||||
|
||||
// When Node writes to stdout/strerr, we capture that and convert the lines into calls on the
|
||||
// active .NET ILogger. But by default, stdout/stderr don't have any way of distinguishing
|
||||
// linebreaks inside log messages from the linebreaks that delimit separate log messages,
|
||||
// so multiline strings will end up being written to the ILogger as multiple independent
|
||||
// log messages. This makes them very hard to make sense of, especially when they represent
|
||||
// something like stack traces.
|
||||
//
|
||||
// To fix this, we intercept stdout/stderr writes, and replace internal linebreaks with a
|
||||
// marker token. When .NET receives the lines, it converts the marker tokens back to regular
|
||||
// linebreaks within the logged messages.
|
||||
//
|
||||
// Note that it's better to do the interception at the stdout/stderr level, rather than at
|
||||
// the console.log/console.error (etc.) level, because this takes place after any native
|
||||
// message formatting has taken place (e.g., inserting values for % placeholders).
|
||||
var findInternalNewlinesRegex = /\n(?!$)/g;
|
||||
var encodedNewline = '__ns_newline__';
|
||||
encodeNewlinesWrittenToStream(process.stdout);
|
||||
encodeNewlinesWrittenToStream(process.stderr);
|
||||
function encodeNewlinesWrittenToStream(outputStream) {
|
||||
var origWriteFunction = outputStream.write;
|
||||
outputStream.write = function (value) {
|
||||
// Only interfere with the write if it's definitely a string
|
||||
if (typeof value === 'string') {
|
||||
var argsClone = Array.prototype.slice.call(arguments, 0);
|
||||
argsClone[0] = encodeNewlinesInString(value);
|
||||
origWriteFunction.apply(this, argsClone);
|
||||
}
|
||||
else {
|
||||
origWriteFunction.apply(this, arguments);
|
||||
}
|
||||
};
|
||||
}
|
||||
function encodeNewlinesInString(str) {
|
||||
return str.replace(findInternalNewlinesRegex, encodedNewline);
|
||||
}
|
||||
|
||||
|
||||
/***/
|
||||
}),
|
||||
/* 3 */
|
||||
/***/ (function (module, exports) {
|
||||
|
||||
module.exports = require("net");
|
||||
|
||||
/***/
|
||||
}),
|
||||
/* 4 */
|
||||
/***/ (function (module, exports) {
|
||||
|
||||
module.exports = require("path");
|
||||
|
||||
/***/
|
||||
}),
|
||||
/* 5 */
|
||||
/***/ (function (module, exports) {
|
||||
|
||||
module.exports = require("readline");
|
||||
|
||||
/***/
|
||||
}),
|
||||
/* 6 */
|
||||
/***/ (function (module, exports, __webpack_require__) {
|
||||
|
||||
"use strict";
|
||||
|
||||
exports.__esModule = true;
|
||||
function parseArgs(args) {
|
||||
// Very simplistic parsing which is sufficient for the cases needed. We don't want to bring in any external
|
||||
// dependencies (such as an args-parsing library) to this file.
|
||||
var result = {};
|
||||
var currentKey = null;
|
||||
args.forEach(function (arg) {
|
||||
if (arg.indexOf('--') === 0) {
|
||||
var argName = arg.substring(2);
|
||||
result[argName] = undefined;
|
||||
currentKey = argName;
|
||||
}
|
||||
else if (currentKey) {
|
||||
result[currentKey] = arg;
|
||||
currentKey = null;
|
||||
}
|
||||
});
|
||||
return result;
|
||||
}
|
||||
exports.parseArgs = parseArgs;
|
||||
|
||||
|
||||
/***/
|
||||
}),
|
||||
/* 7 */
|
||||
/***/ (function (module, exports, __webpack_require__) {
|
||||
|
||||
"use strict";
|
||||
|
||||
/*
|
||||
In general, we want the Node child processes to be terminated as soon as the parent .NET processes exit,
|
||||
because we have no further use for them. If the .NET process shuts down gracefully, it will run its
|
||||
finalizers, one of which (in OutOfProcessNodeInstance.cs) will kill its associated Node process immediately.
|
||||
|
||||
But if the .NET process is terminated forcefully (e.g., on Linux/OSX with 'kill -9'), then it won't have
|
||||
any opportunity to shut down its child processes, and by default they will keep running. In this case, it's
|
||||
up to the child process to detect this has happened and terminate itself.
|
||||
|
||||
There are many possible approaches to detecting when a parent process has exited, most of which behave
|
||||
differently between Windows and Linux/OS X:
|
||||
|
||||
- On Windows, the parent process can mark its child as being a 'job' that should auto-terminate when
|
||||
the parent does (http://stackoverflow.com/a/4657392). Not cross-platform.
|
||||
- The child Node process can get a callback when the parent disconnects (process.on('disconnect', ...)).
|
||||
But despite http://stackoverflow.com/a/16487966, no callback fires in any case I've tested (Windows / OS X).
|
||||
- The child Node process can get a callback when its stdin/stdout are disconnected, as described at
|
||||
http://stackoverflow.com/a/15693934. This works well on OS X, but calling stdout.resume() on Windows
|
||||
causes the process to terminate prematurely.
|
||||
- I don't know why, but on Windows, it's enough to invoke process.stdin.resume(). For some reason this causes
|
||||
the child Node process to exit as soon as the parent one does, but I don't see this documented anywhere.
|
||||
- You can poll to see if the parent process, or your stdin/stdout connection to it, is gone
|
||||
- You can directly pass a parent process PID to the child, and then have the child poll to see if it's
|
||||
still running (e.g., using process.kill(pid, 0), which doesn't kill it but just tests whether it exists,
|
||||
as per https://nodejs.org/api/process.html#process_process_kill_pid_signal)
|
||||
- Or, on each poll, you can try writing to process.stdout. If the parent has died, then this will throw.
|
||||
However I don't see this documented anywhere. It would be nice if you could just poll for whether or not
|
||||
process.stdout is still connected (without actually writing to it) but I haven't found any property whose
|
||||
value changes until you actually try to write to it.
|
||||
|
||||
Of these, the only cross-platform approach that is actually documented as a valid strategy is simply polling
|
||||
to check whether the parent PID is still running. So that's what we do here.
|
||||
*/
|
||||
exports.__esModule = true;
|
||||
var pollIntervalMs = 1000;
|
||||
function exitWhenParentExits(parentPid, ignoreSigint) {
|
||||
setInterval(function () {
|
||||
if (!processExists(parentPid)) {
|
||||
// Can't log anything at this point, because out stdout was connected to the parent,
|
||||
// but the parent is gone.
|
||||
process.exit();
|
||||
}
|
||||
}, pollIntervalMs);
|
||||
if (ignoreSigint) {
|
||||
// Pressing ctrl+c in the terminal sends a SIGINT to all processes in the foreground process tree.
|
||||
// By default, the Node process would then exit before the .NET process, because ASP.NET implements
|
||||
// a delayed shutdown to allow ongoing requests to complete.
|
||||
//
|
||||
// This is problematic, because if Node exits first, the CopyToAsync code in ConditionalProxyMiddleware
|
||||
// will experience a read fault, and logs a huge load of errors. Fortunately, since the Node process is
|
||||
// already set up to shut itself down if it detects the .NET process is terminated, all we have to do is
|
||||
// ignore the SIGINT. The Node process will then terminate automatically after the .NET process does.
|
||||
//
|
||||
// A better solution would be to have WebpackDevMiddleware listen for SIGINT and gracefully close any
|
||||
// ongoing EventSource connections before letting the Node process exit, independently of the .NET
|
||||
// process exiting. However, doing this well in general is very nontrivial (see all the discussion at
|
||||
// https://github.com/nodejs/node/issues/2642).
|
||||
process.on('SIGINT', function () {
|
||||
console.log('Received SIGINT. Waiting for .NET process to exit...');
|
||||
});
|
||||
}
|
||||
}
|
||||
exports.exitWhenParentExits = exitWhenParentExits;
|
||||
function processExists(pid) {
|
||||
try {
|
||||
// Sending signal 0 - on all platforms - tests whether the process exists. As long as it doesn't
|
||||
// throw, that means it does exist.
|
||||
process.kill(pid, 0);
|
||||
return true;
|
||||
}
|
||||
catch (ex) {
|
||||
// If the reason for the error is that we don't have permission to ask about this process,
|
||||
// report that as a separate problem.
|
||||
if (ex.code === 'EPERM') {
|
||||
throw new Error("Attempted to check whether process " + pid + " was running, but got a permissions error.");
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/***/
|
||||
}),
|
||||
/* 8 */
|
||||
/***/ (function (module, exports, __webpack_require__) {
|
||||
|
||||
"use strict";
|
||||
|
||||
exports.__esModule = true;
|
||||
var events_1 = __webpack_require__(9);
|
||||
var VirtualConnection_1 = __webpack_require__(10);
|
||||
// Keep this in sync with the equivalent constant in the .NET code. Both sides split up their transmissions into frames with this max length,
|
||||
// and both will reject longer frames.
|
||||
var MaxFrameBodyLength = 16 * 1024;
|
||||
/**
|
||||
* Accepts connections to a net.Server and adapts them to behave as multiplexed connections. That is, for each physical socket connection,
|
||||
* we track a list of 'virtual connections' whose API is a Duplex stream. The remote clients may open and close as many virtual connections
|
||||
* as they wish, reading and writing to them independently, without the overhead of establishing new physical connections each time.
|
||||
*/
|
||||
function createInterface(server) {
|
||||
var emitter = new events_1.EventEmitter();
|
||||
server.on('connection', function (socket) {
|
||||
// For each physical socket connection, maintain a set of virtual connections. Issue a notification whenever
|
||||
// a new virtual connections is opened.
|
||||
var childSockets = new VirtualConnectionsCollection(socket, function (virtualConnection) {
|
||||
emitter.emit('connection', virtualConnection);
|
||||
});
|
||||
});
|
||||
return emitter;
|
||||
}
|
||||
exports.createInterface = createInterface;
|
||||
/**
|
||||
* Tracks the 'virtual connections' associated with a single physical socket connection.
|
||||
*/
|
||||
var VirtualConnectionsCollection = /** @class */ (function () {
|
||||
function VirtualConnectionsCollection(_socket, _onVirtualConnectionCallback) {
|
||||
var _this = this;
|
||||
this._socket = _socket;
|
||||
this._onVirtualConnectionCallback = _onVirtualConnectionCallback;
|
||||
this._currentFrameHeader = null;
|
||||
this._virtualConnections = {};
|
||||
// If the remote end closes the physical socket, treat all the virtual connections as being closed remotely too
|
||||
this._socket.on('close', function () {
|
||||
Object.getOwnPropertyNames(_this._virtualConnections).forEach(function (id) {
|
||||
// A 'null' frame signals that the connection was closed remotely
|
||||
_this._virtualConnections[id].onReceivedData(null);
|
||||
});
|
||||
});
|
||||
this._socket.on('readable', this._onIncomingDataAvailable.bind(this));
|
||||
}
|
||||
/**
|
||||
* This is called whenever the underlying socket signals that it may have some data available to read. It will synchronously read as many
|
||||
* message frames as it can from the underlying socket, opens virtual connections as needed, and dispatches data to them.
|
||||
*/
|
||||
VirtualConnectionsCollection.prototype._onIncomingDataAvailable = function () {
|
||||
var exhaustedAllData = false;
|
||||
while (!exhaustedAllData) {
|
||||
// We might already have a pending frame header from the previous time this method ran, but if not, that's the next thing we need to read
|
||||
if (this._currentFrameHeader === null) {
|
||||
this._currentFrameHeader = this._readNextFrameHeader();
|
||||
}
|
||||
if (this._currentFrameHeader === null) {
|
||||
// There's not enough data to fill a frameheader, so wait until more arrives later
|
||||
// The next attempt to read from the socket will start from the same place this one did (incomplete reads don't consume any data)
|
||||
exhaustedAllData = true;
|
||||
}
|
||||
else {
|
||||
var frameBodyLength = this._currentFrameHeader.bodyLength;
|
||||
var frameBodyOrNull = frameBodyLength > 0 ? this._socket.read(this._currentFrameHeader.bodyLength) : null;
|
||||
if (frameBodyOrNull !== null || frameBodyLength === 0) {
|
||||
// We have a complete frame header+body pair, so we can now dispatch this to a virtual connection. We set _currentFrameHeader back to null
|
||||
// so that the next thing we try to read is the next frame header.
|
||||
var headerCopy = this._currentFrameHeader;
|
||||
this._currentFrameHeader = null;
|
||||
this._onReceivedCompleteFrame(headerCopy, frameBodyOrNull);
|
||||
}
|
||||
else {
|
||||
// There's not enough data to fill the pending frame body, so wait until more arrives later
|
||||
// The next attempt to read from the socket will start from the same place this one did (incomplete reads don't consume any data)
|
||||
exhaustedAllData = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
VirtualConnectionsCollection.prototype._onReceivedCompleteFrame = function (header, bodyIfNotEmpty) {
|
||||
// An incoming zero-length frame signals that there's no more data to read.
|
||||
// Signal this to the Node stream APIs by pushing a 'null' chunk to it.
|
||||
var virtualConnection = this._getOrOpenVirtualConnection(header);
|
||||
virtualConnection.onReceivedData(header.bodyLength > 0 ? bodyIfNotEmpty : null);
|
||||
};
|
||||
VirtualConnectionsCollection.prototype._getOrOpenVirtualConnection = function (header) {
|
||||
if (this._virtualConnections.hasOwnProperty(header.connectionIdString)) {
|
||||
// It's an existing virtual connection
|
||||
return this._virtualConnections[header.connectionIdString];
|
||||
}
|
||||
else {
|
||||
// It's a new one
|
||||
return this._openVirtualConnection(header);
|
||||
}
|
||||
};
|
||||
VirtualConnectionsCollection.prototype._openVirtualConnection = function (header) {
|
||||
var _this = this;
|
||||
var beginWriteCallback = function (data, writeCompletedCallback) {
|
||||
// Only send nonempty frames, since empty ones are a signal to close the virtual connection
|
||||
if (data.length > 0) {
|
||||
_this._sendFrame(header.connectionIdBinary, data, writeCompletedCallback);
|
||||
}
|
||||
};
|
||||
var newVirtualConnection = new VirtualConnection_1.VirtualConnection(beginWriteCallback);
|
||||
newVirtualConnection.on('end', function () {
|
||||
// The virtual connection was closed remotely. Clean up locally.
|
||||
_this._onVirtualConnectionWasClosed(header.connectionIdString);
|
||||
});
|
||||
newVirtualConnection.on('finish', function () {
|
||||
// The virtual connection was closed locally. Clean up locally, and notify the remote that we're done.
|
||||
_this._onVirtualConnectionWasClosed(header.connectionIdString);
|
||||
_this._sendFrame(header.connectionIdBinary, Buffer.alloc(0));
|
||||
});
|
||||
this._virtualConnections[header.connectionIdString] = newVirtualConnection;
|
||||
this._onVirtualConnectionCallback(newVirtualConnection);
|
||||
return newVirtualConnection;
|
||||
};
|
||||
/**
|
||||
* Attempts to read a complete frame header, synchronously, from the underlying socket.
|
||||
* If not enough data is available synchronously, returns null without consuming any data from the socket.
|
||||
*/
|
||||
VirtualConnectionsCollection.prototype._readNextFrameHeader = function () {
|
||||
var headerBuf = this._socket.read(12);
|
||||
if (headerBuf !== null) {
|
||||
// We have enough data synchronously
|
||||
var connectionIdBinary = headerBuf.slice(0, 8);
|
||||
var connectionIdString = connectionIdBinary.toString('hex');
|
||||
var bodyLength = headerBuf.readInt32LE(8);
|
||||
if (bodyLength < 0 || bodyLength > MaxFrameBodyLength) {
|
||||
// Throwing here is going to bring down the whole process, so this cannot be allowed to happen in real use.
|
||||
// But it won't happen in real use, because this is only used with our .NET client, which doesn't violate this rule.
|
||||
throw new Error('Illegal frame body length: ' + bodyLength);
|
||||
}
|
||||
return { connectionIdBinary: connectionIdBinary, connectionIdString: connectionIdString, bodyLength: bodyLength };
|
||||
}
|
||||
else {
|
||||
// Not enough bytes are available synchronously, so none were consumed
|
||||
return null;
|
||||
}
|
||||
};
|
||||
VirtualConnectionsCollection.prototype._sendFrame = function (connectionIdBinary, data, callback) {
|
||||
// For all sends other than the last one, only invoke the callback if it failed.
|
||||
// Also, only invoke the callback at most once.
|
||||
var hasInvokedCallback = false;
|
||||
var finalCallback = callback && (function (error) {
|
||||
if (!hasInvokedCallback) {
|
||||
hasInvokedCallback = true;
|
||||
callback(error);
|
||||
}
|
||||
});
|
||||
var notFinalCallback = callback && (function (error) {
|
||||
if (error) {
|
||||
finalCallback(error);
|
||||
}
|
||||
});
|
||||
// The amount of data we're writing might exceed MaxFrameBodyLength, so split into frames as needed.
|
||||
// Note that we always send at least one frame, even if it's empty (because that's the close-virtual-connection signal).
|
||||
// If needed, this could be changed to send frames asynchronously, so that large sends could proceed in parallel
|
||||
// (though that would involve making a clone of 'data', to avoid the risk of it being mutated during the send).
|
||||
var bytesSent = 0;
|
||||
do {
|
||||
var nextFrameBodyLength = Math.min(MaxFrameBodyLength, data.length - bytesSent);
|
||||
var isFinalChunk = (bytesSent + nextFrameBodyLength) === data.length;
|
||||
this._socket.write(connectionIdBinary, notFinalCallback);
|
||||
this._sendInt32LE(nextFrameBodyLength, notFinalCallback);
|
||||
this._socket.write(data.slice(bytesSent, bytesSent + nextFrameBodyLength), isFinalChunk ? finalCallback : notFinalCallback);
|
||||
bytesSent += nextFrameBodyLength;
|
||||
} while (bytesSent < data.length);
|
||||
};
|
||||
/**
|
||||
* Sends a number serialized in the correct format for .NET to receive as a System.Int32
|
||||
*/
|
||||
VirtualConnectionsCollection.prototype._sendInt32LE = function (value, callback) {
|
||||
var buf = Buffer.alloc(4);
|
||||
buf.writeInt32LE(value, 0);
|
||||
this._socket.write(buf, callback);
|
||||
};
|
||||
VirtualConnectionsCollection.prototype._onVirtualConnectionWasClosed = function (id) {
|
||||
if (this._virtualConnections.hasOwnProperty(id)) {
|
||||
delete this._virtualConnections[id];
|
||||
}
|
||||
};
|
||||
return VirtualConnectionsCollection;
|
||||
}());
|
||||
|
||||
|
||||
/***/
|
||||
}),
|
||||
/* 9 */
|
||||
/***/ (function (module, exports) {
|
||||
|
||||
module.exports = require("events");
|
||||
|
||||
/***/
|
||||
}),
|
||||
/* 10 */
|
||||
/***/ (function (module, exports, __webpack_require__) {
|
||||
|
||||
"use strict";
|
||||
|
||||
var __extends = (this && this.__extends) || (function () {
|
||||
var extendStatics = function (d, b) {
|
||||
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 extendStatics(d, b);
|
||||
}
|
||||
return function (d, b) {
|
||||
extendStatics(d, b);
|
||||
function __() { this.constructor = d; }
|
||||
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
|
||||
};
|
||||
})();
|
||||
exports.__esModule = true;
|
||||
var stream_1 = __webpack_require__(11);
|
||||
/**
|
||||
* Represents a virtual connection. Multiple virtual connections may be multiplexed over a single physical socket connection.
|
||||
*/
|
||||
var VirtualConnection = /** @class */ (function (_super) {
|
||||
__extends(VirtualConnection, _super);
|
||||
function VirtualConnection(_beginWriteCallback) {
|
||||
var _this = _super.call(this) || this;
|
||||
_this._beginWriteCallback = _beginWriteCallback;
|
||||
_this._flowing = false;
|
||||
_this._receivedDataQueue = [];
|
||||
return _this;
|
||||
}
|
||||
VirtualConnection.prototype._read = function () {
|
||||
this._flowing = true;
|
||||
// Keep pushing data until we run out, or the underlying framework asks us to stop.
|
||||
// When we finish, the 'flowing' state is detemined by whether more data is still being requested.
|
||||
while (this._flowing && this._receivedDataQueue.length > 0) {
|
||||
var nextChunk = this._receivedDataQueue.shift();
|
||||
this._flowing = this.push(nextChunk);
|
||||
}
|
||||
};
|
||||
VirtualConnection.prototype._write = function (chunk, encodingIfString, callback) {
|
||||
if (typeof chunk === 'string') {
|
||||
chunk = Buffer.from(chunk, encodingIfString);
|
||||
}
|
||||
this._beginWriteCallback(chunk, callback);
|
||||
};
|
||||
VirtualConnection.prototype.onReceivedData = function (dataOrNullToSignalEOF) {
|
||||
if (this._flowing) {
|
||||
this._flowing = this.push(dataOrNullToSignalEOF);
|
||||
}
|
||||
else {
|
||||
this._receivedDataQueue.push(dataOrNullToSignalEOF);
|
||||
}
|
||||
};
|
||||
return VirtualConnection;
|
||||
}(stream_1.Duplex));
|
||||
exports.VirtualConnection = VirtualConnection;
|
||||
|
||||
|
||||
/***/
|
||||
}),
|
||||
/* 11 */
|
||||
/***/ (function (module, exports) {
|
||||
|
||||
module.exports = require("stream");
|
||||
|
||||
/***/
|
||||
})
|
||||
/******/])));
|
||||
@@ -1,26 +0,0 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<Description>Socket-based RPC for Microsoft.AspNetCore.NodeServices.</Description>
|
||||
<TargetFramework>netcoreapp3.0</TargetFramework>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<None Remove="node_modules\**\*" />
|
||||
<EmbeddedResource Include="Content\**\*" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\Microsoft.AspNetCore.NodeServices\Microsoft.AspNetCore.NodeServices.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="System.Threading.Tasks.Dataflow" Version="$(SystemThreadingTasksDataflowPackageVersion)" />
|
||||
</ItemGroup>
|
||||
|
||||
<Target Name="PrepublishScript" BeforeTargets="PrepareForPublish" Condition=" '$(IsCrossTargetingBuild)' != 'true' ">
|
||||
<Exec Command="npm install" />
|
||||
<Exec Command="node node_modules/webpack/bin/webpack.js" />
|
||||
</Target>
|
||||
|
||||
</Project>
|
||||
@@ -1,40 +0,0 @@
|
||||
using System.IO;
|
||||
using System.IO.Pipes;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace Microsoft.AspNetCore.NodeServices.Sockets.PhysicalConnections
|
||||
{
|
||||
internal class NamedPipeConnection : StreamConnection
|
||||
{
|
||||
private bool _disposedValue = false;
|
||||
private NamedPipeClientStream _namedPipeClientStream;
|
||||
|
||||
#pragma warning disable 1998 // Because in the NET451 code path, there's nothing to await
|
||||
public override async Task<Stream> Open(string address)
|
||||
{
|
||||
_namedPipeClientStream = new NamedPipeClientStream(
|
||||
".",
|
||||
address,
|
||||
PipeDirection.InOut,
|
||||
PipeOptions.Asynchronous);
|
||||
|
||||
await _namedPipeClientStream.ConnectAsync().ConfigureAwait(false);
|
||||
|
||||
return _namedPipeClientStream;
|
||||
}
|
||||
#pragma warning restore 1998
|
||||
|
||||
public override void Dispose()
|
||||
{
|
||||
if (!_disposedValue)
|
||||
{
|
||||
if (_namedPipeClientStream != null)
|
||||
{
|
||||
_namedPipeClientStream.Dispose();
|
||||
}
|
||||
|
||||
_disposedValue = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,26 +0,0 @@
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace Microsoft.AspNetCore.NodeServices.Sockets.PhysicalConnections
|
||||
{
|
||||
internal abstract class StreamConnection : IDisposable
|
||||
{
|
||||
public abstract Task<Stream> Open(string address);
|
||||
public abstract void Dispose();
|
||||
|
||||
public static StreamConnection Create()
|
||||
{
|
||||
var useNamedPipes = System.Runtime.InteropServices.RuntimeInformation.IsOSPlatform(
|
||||
System.Runtime.InteropServices.OSPlatform.Windows);
|
||||
if (useNamedPipes)
|
||||
{
|
||||
return new NamedPipeConnection();
|
||||
}
|
||||
else
|
||||
{
|
||||
return new UnixDomainSocketConnection();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,40 +0,0 @@
|
||||
using System.IO;
|
||||
using System.Net.Sockets;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace Microsoft.AspNetCore.NodeServices.Sockets.PhysicalConnections
|
||||
{
|
||||
internal class UnixDomainSocketConnection : StreamConnection
|
||||
{
|
||||
private bool _disposedValue = false;
|
||||
private NetworkStream _networkStream;
|
||||
private Socket _socket;
|
||||
|
||||
public override async Task<Stream> Open(string address)
|
||||
{
|
||||
var endPoint = new UnixDomainSocketEndPoint("/tmp/" + address);
|
||||
_socket = new Socket(endPoint.AddressFamily, SocketType.Stream, ProtocolType.Unspecified);
|
||||
await _socket.ConnectAsync(endPoint).ConfigureAwait(false);
|
||||
_networkStream = new NetworkStream(_socket);
|
||||
return _networkStream;
|
||||
}
|
||||
|
||||
public override void Dispose()
|
||||
{
|
||||
if (!_disposedValue)
|
||||
{
|
||||
if (_networkStream != null)
|
||||
{
|
||||
_networkStream.Dispose();
|
||||
}
|
||||
|
||||
if (_socket != null)
|
||||
{
|
||||
_socket.Dispose();
|
||||
}
|
||||
|
||||
_disposedValue = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,86 +0,0 @@
|
||||
using System;
|
||||
using System.Net;
|
||||
using System.Net.Sockets;
|
||||
using System.Text;
|
||||
|
||||
namespace Microsoft.AspNetCore.NodeServices.Sockets.PhysicalConnections
|
||||
{
|
||||
// From System.IO.Pipes/src/System/Net/Sockets/UnixDomainSocketEndPoint.cs (an internal class in System.IO.Pipes)
|
||||
internal sealed class UnixDomainSocketEndPoint : EndPoint
|
||||
{
|
||||
private const AddressFamily EndPointAddressFamily = AddressFamily.Unix;
|
||||
|
||||
private static readonly Encoding s_pathEncoding = Encoding.UTF8;
|
||||
private static readonly int s_nativePathOffset = 2; // = offsetof(struct sockaddr_un, sun_path). It's the same on Linux and OSX
|
||||
private static readonly int s_nativePathLength = 91; // sockaddr_un.sun_path at http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/sys_un.h.html, -1 for terminator
|
||||
private static readonly int s_nativeAddressSize = s_nativePathOffset + s_nativePathLength;
|
||||
|
||||
private readonly string _path;
|
||||
private readonly byte[] _encodedPath;
|
||||
|
||||
public UnixDomainSocketEndPoint(string path)
|
||||
{
|
||||
if (path == null)
|
||||
{
|
||||
throw new ArgumentNullException(nameof(path));
|
||||
}
|
||||
|
||||
_path = path;
|
||||
_encodedPath = s_pathEncoding.GetBytes(_path);
|
||||
|
||||
if (path.Length == 0 || _encodedPath.Length > s_nativePathLength)
|
||||
{
|
||||
throw new ArgumentOutOfRangeException(nameof(path));
|
||||
}
|
||||
}
|
||||
|
||||
internal UnixDomainSocketEndPoint(SocketAddress socketAddress)
|
||||
{
|
||||
if (socketAddress == null)
|
||||
{
|
||||
throw new ArgumentNullException(nameof(socketAddress));
|
||||
}
|
||||
|
||||
if (socketAddress.Family != EndPointAddressFamily ||
|
||||
socketAddress.Size > s_nativeAddressSize)
|
||||
{
|
||||
throw new ArgumentOutOfRangeException(nameof(socketAddress));
|
||||
}
|
||||
|
||||
if (socketAddress.Size > s_nativePathOffset)
|
||||
{
|
||||
_encodedPath = new byte[socketAddress.Size - s_nativePathOffset];
|
||||
for (int i = 0; i < _encodedPath.Length; i++)
|
||||
{
|
||||
_encodedPath[i] = socketAddress[s_nativePathOffset + i];
|
||||
}
|
||||
|
||||
_path = s_pathEncoding.GetString(_encodedPath, 0, _encodedPath.Length);
|
||||
}
|
||||
else
|
||||
{
|
||||
_encodedPath = Array.Empty<byte>();
|
||||
_path = string.Empty;
|
||||
}
|
||||
}
|
||||
|
||||
public override SocketAddress Serialize()
|
||||
{
|
||||
var result = new SocketAddress(AddressFamily.Unix, s_nativeAddressSize);
|
||||
|
||||
for (int index = 0; index < _encodedPath.Length; index++)
|
||||
{
|
||||
result[s_nativePathOffset + index] = _encodedPath[index];
|
||||
}
|
||||
result[s_nativePathOffset + _encodedPath.Length] = 0; // path must be null-terminated
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
public override EndPoint Create(SocketAddress socketAddress) => new UnixDomainSocketEndPoint(socketAddress);
|
||||
|
||||
public override AddressFamily AddressFamily => EndPointAddressFamily;
|
||||
|
||||
public override string ToString() => _path;
|
||||
}
|
||||
}
|
||||
@@ -1,240 +0,0 @@
|
||||
using System.IO;
|
||||
using System.Text;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using Microsoft.AspNetCore.NodeServices.HostingModels;
|
||||
using Microsoft.AspNetCore.NodeServices.Sockets.PhysicalConnections;
|
||||
using Microsoft.AspNetCore.NodeServices.Sockets.VirtualConnections;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Newtonsoft.Json;
|
||||
using Newtonsoft.Json.Serialization;
|
||||
|
||||
namespace Microsoft.AspNetCore.NodeServices.Sockets
|
||||
{
|
||||
/// <summary>
|
||||
/// A specialisation of the OutOfProcessNodeInstance base class that uses a lightweight binary streaming protocol
|
||||
/// to perform RPC invocations. The physical transport is Named Pipes on Windows, or Domain Sockets on Linux/Mac.
|
||||
/// For details on the binary streaming protocol, see <see cref="Microsoft.AspNetCore.NodeServices.Sockets.VirtualConnections.VirtualConnectionClient" />
|
||||
/// The advantage versus using HTTP for RPC is that this is faster (not surprisingly - there's much less overhead
|
||||
/// because we don't need most of the functionality of HTTP.
|
||||
///
|
||||
/// The address of the pipe/socket is selected randomly here on the .NET side and sent to the child process as a
|
||||
/// command-line argument (the address space is wide enough that there's no real risk of a clash, unlike when
|
||||
/// selecting TCP port numbers).
|
||||
/// </summary>
|
||||
/// <seealso cref="Microsoft.AspNetCore.NodeServices.HostingModels.OutOfProcessNodeInstance" />
|
||||
internal class SocketNodeInstance : OutOfProcessNodeInstance
|
||||
{
|
||||
private readonly static JsonSerializerSettings jsonSerializerSettings = new JsonSerializerSettings
|
||||
{
|
||||
ContractResolver = new CamelCasePropertyNamesContractResolver(),
|
||||
TypeNameHandling = TypeNameHandling.None
|
||||
};
|
||||
|
||||
private readonly static int streamBufferSize = 16 * 1024;
|
||||
private readonly static UTF8Encoding utf8EncodingWithoutBom = new UTF8Encoding(false);
|
||||
|
||||
private readonly SemaphoreSlim _connectionCreationSemaphore = new SemaphoreSlim(1);
|
||||
private bool _connectionHasFailed;
|
||||
private StreamConnection _physicalConnection;
|
||||
private string _socketAddress;
|
||||
private VirtualConnectionClient _virtualConnectionClient;
|
||||
|
||||
public SocketNodeInstance(NodeServicesOptions options, string socketAddress)
|
||||
: base(
|
||||
EmbeddedResourceReader.Read(
|
||||
typeof(SocketNodeInstance),
|
||||
"/Content/Node/entrypoint-socket.js"),
|
||||
options.ProjectPath,
|
||||
options.WatchFileExtensions,
|
||||
MakeNewCommandLineOptions(socketAddress),
|
||||
options.ApplicationStoppingToken,
|
||||
options.NodeInstanceOutputLogger,
|
||||
options.EnvironmentVariables,
|
||||
options.InvocationTimeoutMilliseconds,
|
||||
options.LaunchWithDebugging,
|
||||
options.DebuggingPort)
|
||||
{
|
||||
_socketAddress = socketAddress;
|
||||
}
|
||||
|
||||
protected override async Task<T> InvokeExportAsync<T>(NodeInvocationInfo invocationInfo, CancellationToken cancellationToken)
|
||||
{
|
||||
if (_connectionHasFailed)
|
||||
{
|
||||
// _connectionHasFailed implies a protocol-level error. The old instance is no longer of any use.
|
||||
var allowConnectionDraining = false;
|
||||
|
||||
// This special exception type forces NodeServicesImpl to restart the Node instance
|
||||
throw new NodeInvocationException(
|
||||
"The SocketNodeInstance socket connection failed. See logs to identify the reason.",
|
||||
details: null,
|
||||
nodeInstanceUnavailable: true,
|
||||
allowConnectionDraining: allowConnectionDraining);
|
||||
}
|
||||
|
||||
if (_virtualConnectionClient == null)
|
||||
{
|
||||
// Although we could pass the cancellationToken into EnsureVirtualConnectionClientCreated and
|
||||
// have it signal cancellations upstream, that would be a bad thing to do, because all callers
|
||||
// wait for the same connection task. There's no reason why the first caller should have the
|
||||
// special ability to cancel the connection process in a way that would affect subsequent
|
||||
// callers. So, each caller just independently stops awaiting connection if that call is cancelled.
|
||||
await ThrowOnCancellation(EnsureVirtualConnectionClientCreated(), cancellationToken);
|
||||
}
|
||||
|
||||
// For each invocation, we open a new virtual connection. This gives an API equivalent to opening a new
|
||||
// physical connection to the child process, but without the overhead of doing so, because it's really
|
||||
// just multiplexed into the existing physical connection stream.
|
||||
bool shouldDisposeVirtualConnection = true;
|
||||
Stream virtualConnection = null;
|
||||
try
|
||||
{
|
||||
virtualConnection = _virtualConnectionClient.OpenVirtualConnection();
|
||||
|
||||
// Send request
|
||||
WriteJsonLine(virtualConnection, invocationInfo);
|
||||
|
||||
// Determine what kind of response format is expected
|
||||
if (typeof(T) == typeof(Stream))
|
||||
{
|
||||
// Pass through streamed binary response
|
||||
// It is up to the consumer to dispose this stream, so don't do so here
|
||||
shouldDisposeVirtualConnection = false;
|
||||
return (T)(object)virtualConnection;
|
||||
}
|
||||
else
|
||||
{
|
||||
// Parse and return non-streamed JSON response
|
||||
var response = await ReadJsonAsync<RpcJsonResponse<T>>(virtualConnection, cancellationToken);
|
||||
if (response.ErrorMessage != null)
|
||||
{
|
||||
throw new NodeInvocationException(response.ErrorMessage, response.ErrorDetails);
|
||||
}
|
||||
|
||||
return response.Result;
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
if (shouldDisposeVirtualConnection)
|
||||
{
|
||||
virtualConnection.Dispose();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private async Task EnsureVirtualConnectionClientCreated()
|
||||
{
|
||||
// Asynchronous equivalent to a 'lock(...) { ... }'
|
||||
await _connectionCreationSemaphore.WaitAsync();
|
||||
try
|
||||
{
|
||||
if (_virtualConnectionClient == null)
|
||||
{
|
||||
_physicalConnection = StreamConnection.Create();
|
||||
|
||||
var connection = await _physicalConnection.Open(_socketAddress);
|
||||
_virtualConnectionClient = new VirtualConnectionClient(connection);
|
||||
_virtualConnectionClient.OnError += (ex) =>
|
||||
{
|
||||
// This callback is fired only if there's a protocol-level failure (e.g., child process disconnected
|
||||
// unexpectedly). It does *not* fire when RPC calls return errors. Since there's been a protocol-level
|
||||
// failure, this Node instance is no longer usable and should be discarded.
|
||||
_connectionHasFailed = true;
|
||||
|
||||
OutputLogger.LogError(0, ex, ex.Message);
|
||||
};
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
_connectionCreationSemaphore.Release();
|
||||
}
|
||||
}
|
||||
|
||||
protected override void Dispose(bool disposing)
|
||||
{
|
||||
if (disposing)
|
||||
{
|
||||
if (_virtualConnectionClient != null)
|
||||
{
|
||||
_virtualConnectionClient.Dispose();
|
||||
_virtualConnectionClient = null;
|
||||
}
|
||||
|
||||
if (_physicalConnection != null)
|
||||
{
|
||||
_physicalConnection.Dispose();
|
||||
_physicalConnection = null;
|
||||
}
|
||||
}
|
||||
|
||||
base.Dispose(disposing);
|
||||
}
|
||||
|
||||
private static void WriteJsonLine(Stream stream, object serializableObject)
|
||||
{
|
||||
using (var streamWriter = new StreamWriter(stream, utf8EncodingWithoutBom, streamBufferSize, true))
|
||||
using (var jsonWriter = new JsonTextWriter(streamWriter))
|
||||
{
|
||||
jsonWriter.CloseOutput = false;
|
||||
jsonWriter.AutoCompleteOnClose = false;
|
||||
|
||||
var serializer = JsonSerializer.Create(jsonSerializerSettings);
|
||||
serializer.Serialize(jsonWriter, serializableObject);
|
||||
jsonWriter.Flush();
|
||||
|
||||
streamWriter.WriteLine();
|
||||
streamWriter.Flush();
|
||||
}
|
||||
}
|
||||
|
||||
private static async Task<T> ReadJsonAsync<T>(Stream stream, CancellationToken cancellationToken)
|
||||
{
|
||||
var json = Encoding.UTF8.GetString(await ReadAllBytesAsync(stream, cancellationToken));
|
||||
return JsonConvert.DeserializeObject<T>(json, jsonSerializerSettings);
|
||||
}
|
||||
|
||||
private static async Task<byte[]> ReadAllBytesAsync(Stream input, CancellationToken cancellationToken)
|
||||
{
|
||||
byte[] buffer = new byte[streamBufferSize];
|
||||
|
||||
using (var ms = new MemoryStream())
|
||||
{
|
||||
int read;
|
||||
while ((read = await input.ReadAsync(buffer, 0, buffer.Length, cancellationToken)) > 0)
|
||||
{
|
||||
ms.Write(buffer, 0, read);
|
||||
}
|
||||
|
||||
return ms.ToArray();
|
||||
}
|
||||
}
|
||||
|
||||
private static string MakeNewCommandLineOptions(string listenAddress)
|
||||
{
|
||||
return $"--listenAddress {listenAddress}";
|
||||
}
|
||||
|
||||
private static Task ThrowOnCancellation(Task task, CancellationToken cancellationToken)
|
||||
{
|
||||
return task.IsCompleted
|
||||
? task // If the task is already completed, no need to wrap it in a further layer of task
|
||||
: task.ContinueWith(
|
||||
_ => {}, // If the task completes, allow execution to continue
|
||||
cancellationToken,
|
||||
TaskContinuationOptions.ExecuteSynchronously,
|
||||
TaskScheduler.Default);
|
||||
}
|
||||
|
||||
#pragma warning disable 649 // These properties are populated via JSON deserialization
|
||||
private class RpcJsonResponse<TResult>
|
||||
{
|
||||
public TResult Result { get; set; }
|
||||
public string ErrorMessage { get; set; }
|
||||
public string ErrorDetails { get; set; }
|
||||
}
|
||||
#pragma warning restore 649
|
||||
}
|
||||
}
|
||||
@@ -1,21 +0,0 @@
|
||||
using System;
|
||||
|
||||
namespace Microsoft.AspNetCore.NodeServices.Sockets
|
||||
{
|
||||
/// <summary>
|
||||
/// Extension methods that help with populating a <see cref="NodeServicesOptions"/> object.
|
||||
/// </summary>
|
||||
public static class NodeServicesOptionsExtensions
|
||||
{
|
||||
/// <summary>
|
||||
/// Configures the <see cref="INodeServices"/> service so that it will use out-of-process
|
||||
/// Node.js instances and perform RPC calls over binary sockets (on Windows, this is
|
||||
/// implemented as named pipes; on other platforms it uses domain sockets).
|
||||
/// </summary>
|
||||
public static void UseSocketHosting(this NodeServicesOptions options)
|
||||
{
|
||||
var pipeName = "pni-" + Guid.NewGuid().ToString("D"); // Arbitrary non-clashing string
|
||||
options.NodeInstanceFactory = () => new SocketNodeInstance(options, pipeName);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,79 +0,0 @@
|
||||
// Limit dependencies to core Node modules. This means the code in this file has to be very low-level and unattractive,
|
||||
// but simplifies things for the consumer of this module.
|
||||
import '../../Microsoft.AspNetCore.NodeServices/TypeScript/Util/OverrideStdOutputs';
|
||||
import * as net from 'net';
|
||||
import * as path from 'path';
|
||||
import * as readline from 'readline';
|
||||
import { Duplex } from 'stream';
|
||||
import { parseArgs } from '../../Microsoft.AspNetCore.NodeServices/TypeScript/Util/ArgsUtil';
|
||||
import { exitWhenParentExits } from '../../Microsoft.AspNetCore.NodeServices/TypeScript/Util/ExitWhenParentExits';
|
||||
import * as virtualConnectionServer from './VirtualConnections/VirtualConnectionServer';
|
||||
|
||||
// Webpack doesn't support dynamic requires for files not present at compile time, so grab a direct
|
||||
// reference to Node's runtime 'require' function.
|
||||
const dynamicRequire: (name: string) => any = eval('require');
|
||||
|
||||
// Signal to the .NET side when we're ready to accept invocations
|
||||
const server = net.createServer().on('listening', () => {
|
||||
console.log('[Microsoft.AspNetCore.NodeServices:Listening]');
|
||||
});
|
||||
|
||||
// Each virtual connection represents a separate invocation
|
||||
virtualConnectionServer.createInterface(server).on('connection', (connection: Duplex) => {
|
||||
readline.createInterface(connection, null).on('line', line => {
|
||||
try {
|
||||
// Get a reference to the function to invoke
|
||||
const invocation = JSON.parse(line) as RpcInvocation;
|
||||
const invokedModule = dynamicRequire(path.resolve(process.cwd(), invocation.moduleName));
|
||||
const invokedFunction = invocation.exportedFunctionName ? invokedModule[invocation.exportedFunctionName] : invokedModule;
|
||||
|
||||
// Prepare a callback for accepting non-streamed JSON responses
|
||||
let hasInvokedCallback = false;
|
||||
const invocationCallback = (errorValue, successValue) => {
|
||||
if (hasInvokedCallback) {
|
||||
throw new Error('Cannot supply more than one result. The callback has already been invoked,'
|
||||
+ ' or the result stream has already been accessed');
|
||||
}
|
||||
|
||||
hasInvokedCallback = true;
|
||||
connection.end(JSON.stringify({
|
||||
result: successValue,
|
||||
errorMessage: errorValue && (errorValue.message || errorValue),
|
||||
errorDetails: errorValue && (errorValue.stack || null)
|
||||
}));
|
||||
};
|
||||
|
||||
// Also support streamed binary responses
|
||||
Object.defineProperty(invocationCallback, 'stream', {
|
||||
enumerable: true,
|
||||
get: (): Duplex => {
|
||||
hasInvokedCallback = true;
|
||||
return connection;
|
||||
}
|
||||
});
|
||||
|
||||
// Actually invoke it, passing through any supplied args
|
||||
invokedFunction.apply(null, [invocationCallback].concat(invocation.args));
|
||||
} catch (ex) {
|
||||
connection.end(JSON.stringify({
|
||||
errorMessage: ex.message,
|
||||
errorDetails: ex.stack
|
||||
}));
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
// Begin listening now. The underlying transport varies according to the runtime platform.
|
||||
// On Windows it's Named Pipes; on Linux/OSX it's Domain Sockets.
|
||||
const useWindowsNamedPipes = /^win/.test(process.platform);
|
||||
const parsedArgs = parseArgs(process.argv);
|
||||
const listenAddress = (useWindowsNamedPipes ? '\\\\.\\pipe\\' : '/tmp/') + parsedArgs.listenAddress;
|
||||
server.listen(listenAddress);
|
||||
|
||||
exitWhenParentExits(parseInt(parsedArgs.parentPid), /* ignoreSigint */ true);
|
||||
|
||||
interface RpcInvocation {
|
||||
moduleName: string;
|
||||
exportedFunctionName: string;
|
||||
args: any[];
|
||||
}
|
||||
@@ -1,43 +0,0 @@
|
||||
import { Duplex } from 'stream';
|
||||
|
||||
export type EndWriteCallback = (error?: any) => void;
|
||||
export type BeginWriteCallback = (data: Buffer, callback: EndWriteCallback) => void;
|
||||
|
||||
/**
|
||||
* Represents a virtual connection. Multiple virtual connections may be multiplexed over a single physical socket connection.
|
||||
*/
|
||||
export class VirtualConnection extends Duplex {
|
||||
private _flowing = false;
|
||||
private _receivedDataQueue: Buffer[] = [];
|
||||
|
||||
constructor(private _beginWriteCallback: BeginWriteCallback) {
|
||||
super();
|
||||
}
|
||||
|
||||
public _read() {
|
||||
this._flowing = true;
|
||||
|
||||
// Keep pushing data until we run out, or the underlying framework asks us to stop.
|
||||
// When we finish, the 'flowing' state is detemined by whether more data is still being requested.
|
||||
while (this._flowing && this._receivedDataQueue.length > 0) {
|
||||
const nextChunk = this._receivedDataQueue.shift();
|
||||
this._flowing = this.push(nextChunk);
|
||||
}
|
||||
}
|
||||
|
||||
public _write(chunk: Buffer | string, encodingIfString: string, callback: EndWriteCallback) {
|
||||
if (typeof chunk === 'string') {
|
||||
chunk = Buffer.from(chunk as string, encodingIfString);
|
||||
}
|
||||
|
||||
this._beginWriteCallback(chunk as Buffer, callback);
|
||||
}
|
||||
|
||||
public onReceivedData(dataOrNullToSignalEOF: Buffer) {
|
||||
if (this._flowing) {
|
||||
this._flowing = this.push(dataOrNullToSignalEOF);
|
||||
} else {
|
||||
this._receivedDataQueue.push(dataOrNullToSignalEOF);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,199 +0,0 @@
|
||||
import { Server, Socket } from 'net';
|
||||
import { EventEmitter } from 'events';
|
||||
import { Duplex } from 'stream';
|
||||
import { VirtualConnection, EndWriteCallback } from './VirtualConnection';
|
||||
|
||||
// Keep this in sync with the equivalent constant in the .NET code. Both sides split up their transmissions into frames with this max length,
|
||||
// and both will reject longer frames.
|
||||
const MaxFrameBodyLength = 16 * 1024;
|
||||
|
||||
/**
|
||||
* Accepts connections to a net.Server and adapts them to behave as multiplexed connections. That is, for each physical socket connection,
|
||||
* we track a list of 'virtual connections' whose API is a Duplex stream. The remote clients may open and close as many virtual connections
|
||||
* as they wish, reading and writing to them independently, without the overhead of establishing new physical connections each time.
|
||||
*/
|
||||
export function createInterface(server: Server): EventEmitter {
|
||||
const emitter = new EventEmitter();
|
||||
|
||||
server.on('connection', (socket: Socket) => {
|
||||
// For each physical socket connection, maintain a set of virtual connections. Issue a notification whenever
|
||||
// a new virtual connections is opened.
|
||||
const childSockets = new VirtualConnectionsCollection(socket, virtualConnection => {
|
||||
emitter.emit('connection', virtualConnection);
|
||||
});
|
||||
});
|
||||
|
||||
return emitter;
|
||||
}
|
||||
|
||||
/**
|
||||
* Tracks the 'virtual connections' associated with a single physical socket connection.
|
||||
*/
|
||||
class VirtualConnectionsCollection {
|
||||
private _currentFrameHeader: FrameHeader = null;
|
||||
private _virtualConnections: { [id: string]: VirtualConnection } = {};
|
||||
|
||||
constructor(private _socket: Socket, private _onVirtualConnectionCallback: (virtualConnection: Duplex) => void) {
|
||||
// If the remote end closes the physical socket, treat all the virtual connections as being closed remotely too
|
||||
this._socket.on('close', () => {
|
||||
Object.getOwnPropertyNames(this._virtualConnections).forEach(id => {
|
||||
// A 'null' frame signals that the connection was closed remotely
|
||||
this._virtualConnections[id].onReceivedData(null);
|
||||
});
|
||||
});
|
||||
|
||||
this._socket.on('readable', this._onIncomingDataAvailable.bind(this));
|
||||
}
|
||||
|
||||
/**
|
||||
* This is called whenever the underlying socket signals that it may have some data available to read. It will synchronously read as many
|
||||
* message frames as it can from the underlying socket, opens virtual connections as needed, and dispatches data to them.
|
||||
*/
|
||||
private _onIncomingDataAvailable() {
|
||||
let exhaustedAllData = false;
|
||||
|
||||
while (!exhaustedAllData) {
|
||||
// We might already have a pending frame header from the previous time this method ran, but if not, that's the next thing we need to read
|
||||
if (this._currentFrameHeader === null) {
|
||||
this._currentFrameHeader = this._readNextFrameHeader();
|
||||
}
|
||||
|
||||
if (this._currentFrameHeader === null) {
|
||||
// There's not enough data to fill a frameheader, so wait until more arrives later
|
||||
// The next attempt to read from the socket will start from the same place this one did (incomplete reads don't consume any data)
|
||||
exhaustedAllData = true;
|
||||
} else {
|
||||
const frameBodyLength = this._currentFrameHeader.bodyLength;
|
||||
const frameBodyOrNull: Buffer = frameBodyLength > 0 ? this._socket.read(this._currentFrameHeader.bodyLength) : null;
|
||||
if (frameBodyOrNull !== null || frameBodyLength === 0) {
|
||||
// We have a complete frame header+body pair, so we can now dispatch this to a virtual connection. We set _currentFrameHeader back to null
|
||||
// so that the next thing we try to read is the next frame header.
|
||||
const headerCopy = this._currentFrameHeader;
|
||||
this._currentFrameHeader = null;
|
||||
this._onReceivedCompleteFrame(headerCopy, frameBodyOrNull);
|
||||
} else {
|
||||
// There's not enough data to fill the pending frame body, so wait until more arrives later
|
||||
// The next attempt to read from the socket will start from the same place this one did (incomplete reads don't consume any data)
|
||||
exhaustedAllData = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private _onReceivedCompleteFrame(header: FrameHeader, bodyIfNotEmpty: Buffer) {
|
||||
// An incoming zero-length frame signals that there's no more data to read.
|
||||
// Signal this to the Node stream APIs by pushing a 'null' chunk to it.
|
||||
const virtualConnection = this._getOrOpenVirtualConnection(header);
|
||||
virtualConnection.onReceivedData(header.bodyLength > 0 ? bodyIfNotEmpty : null);
|
||||
}
|
||||
|
||||
private _getOrOpenVirtualConnection(header: FrameHeader) {
|
||||
if (this._virtualConnections.hasOwnProperty(header.connectionIdString)) {
|
||||
// It's an existing virtual connection
|
||||
return this._virtualConnections[header.connectionIdString];
|
||||
} else {
|
||||
// It's a new one
|
||||
return this._openVirtualConnection(header);
|
||||
}
|
||||
}
|
||||
|
||||
private _openVirtualConnection(header: FrameHeader) {
|
||||
const beginWriteCallback = (data, writeCompletedCallback) => {
|
||||
// Only send nonempty frames, since empty ones are a signal to close the virtual connection
|
||||
if (data.length > 0) {
|
||||
this._sendFrame(header.connectionIdBinary, data, writeCompletedCallback);
|
||||
}
|
||||
};
|
||||
|
||||
const newVirtualConnection = new VirtualConnection(beginWriteCallback);
|
||||
newVirtualConnection.on('end', () => {
|
||||
// The virtual connection was closed remotely. Clean up locally.
|
||||
this._onVirtualConnectionWasClosed(header.connectionIdString);
|
||||
});
|
||||
newVirtualConnection.on('finish', () => {
|
||||
// The virtual connection was closed locally. Clean up locally, and notify the remote that we're done.
|
||||
this._onVirtualConnectionWasClosed(header.connectionIdString);
|
||||
this._sendFrame(header.connectionIdBinary, Buffer.alloc(0));
|
||||
});
|
||||
|
||||
this._virtualConnections[header.connectionIdString] = newVirtualConnection;
|
||||
this._onVirtualConnectionCallback(newVirtualConnection);
|
||||
return newVirtualConnection;
|
||||
}
|
||||
|
||||
/**
|
||||
* Attempts to read a complete frame header, synchronously, from the underlying socket.
|
||||
* If not enough data is available synchronously, returns null without consuming any data from the socket.
|
||||
*/
|
||||
private _readNextFrameHeader(): FrameHeader {
|
||||
const headerBuf: Buffer = this._socket.read(12);
|
||||
if (headerBuf !== null) {
|
||||
// We have enough data synchronously
|
||||
const connectionIdBinary = headerBuf.slice(0, 8);
|
||||
const connectionIdString = connectionIdBinary.toString('hex');
|
||||
const bodyLength = headerBuf.readInt32LE(8);
|
||||
if (bodyLength < 0 || bodyLength > MaxFrameBodyLength) {
|
||||
// Throwing here is going to bring down the whole process, so this cannot be allowed to happen in real use.
|
||||
// But it won't happen in real use, because this is only used with our .NET client, which doesn't violate this rule.
|
||||
throw new Error('Illegal frame body length: ' + bodyLength);
|
||||
}
|
||||
|
||||
return { connectionIdBinary, connectionIdString, bodyLength };
|
||||
} else {
|
||||
// Not enough bytes are available synchronously, so none were consumed
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private _sendFrame(connectionIdBinary: Buffer, data: Buffer, callback?: EndWriteCallback) {
|
||||
// For all sends other than the last one, only invoke the callback if it failed.
|
||||
// Also, only invoke the callback at most once.
|
||||
let hasInvokedCallback = false;
|
||||
const finalCallback: EndWriteCallback = callback && (error => {
|
||||
if (!hasInvokedCallback) {
|
||||
hasInvokedCallback = true;
|
||||
callback(error);
|
||||
}
|
||||
});
|
||||
const notFinalCallback: EndWriteCallback = callback && (error => {
|
||||
if (error) {
|
||||
finalCallback(error);
|
||||
}
|
||||
});
|
||||
|
||||
// The amount of data we're writing might exceed MaxFrameBodyLength, so split into frames as needed.
|
||||
// Note that we always send at least one frame, even if it's empty (because that's the close-virtual-connection signal).
|
||||
// If needed, this could be changed to send frames asynchronously, so that large sends could proceed in parallel
|
||||
// (though that would involve making a clone of 'data', to avoid the risk of it being mutated during the send).
|
||||
let bytesSent = 0;
|
||||
do {
|
||||
const nextFrameBodyLength = Math.min(MaxFrameBodyLength, data.length - bytesSent);
|
||||
const isFinalChunk = (bytesSent + nextFrameBodyLength) === data.length;
|
||||
this._socket.write(connectionIdBinary, notFinalCallback);
|
||||
this._sendInt32LE(nextFrameBodyLength, notFinalCallback);
|
||||
this._socket.write(data.slice(bytesSent, bytesSent + nextFrameBodyLength), isFinalChunk ? finalCallback : notFinalCallback);
|
||||
bytesSent += nextFrameBodyLength;
|
||||
} while (bytesSent < data.length);
|
||||
}
|
||||
|
||||
/**
|
||||
* Sends a number serialized in the correct format for .NET to receive as a System.Int32
|
||||
*/
|
||||
private _sendInt32LE(value: number, callback?: EndWriteCallback) {
|
||||
const buf = Buffer.alloc(4);
|
||||
buf.writeInt32LE(value, 0);
|
||||
this._socket.write(buf, callback);
|
||||
}
|
||||
|
||||
private _onVirtualConnectionWasClosed(id: string) {
|
||||
if (this._virtualConnections.hasOwnProperty(id)) {
|
||||
delete this._virtualConnections[id];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
interface FrameHeader {
|
||||
connectionIdBinary: Buffer;
|
||||
connectionIdString: string;
|
||||
bodyLength: number;
|
||||
}
|
||||
@@ -1,11 +0,0 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "es3",
|
||||
"module": "commonjs",
|
||||
"moduleResolution": "node",
|
||||
"types": ["node"]
|
||||
},
|
||||
"exclude": [
|
||||
"node_modules"
|
||||
]
|
||||
}
|
||||
@@ -1,150 +0,0 @@
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using System.Threading.Tasks.Dataflow;
|
||||
|
||||
namespace Microsoft.AspNetCore.NodeServices.Sockets.VirtualConnections
|
||||
{
|
||||
/// <summary>
|
||||
/// A virtual read/write connection, typically to a remote process. Multiple virtual connections can be
|
||||
/// multiplexed over a single physical connection (e.g., a named pipe, domain socket, or TCP socket).
|
||||
/// </summary>
|
||||
internal class VirtualConnection : Stream
|
||||
{
|
||||
private readonly static Task CompletedTask = Task.CompletedTask;
|
||||
private VirtualConnectionClient _host;
|
||||
private readonly BufferBlock<byte[]> _receivedDataQueue = new BufferBlock<byte[]>();
|
||||
private ArraySegment<byte> _receivedDataNotYetUsed;
|
||||
private bool _wasClosedByRemote;
|
||||
private bool _isDisposed;
|
||||
|
||||
public VirtualConnection(long id, VirtualConnectionClient host)
|
||||
{
|
||||
Id = id;
|
||||
_host = host;
|
||||
}
|
||||
|
||||
public long Id { get; }
|
||||
|
||||
public override bool CanRead { get { return true; } }
|
||||
public override bool CanSeek { get { return false; } }
|
||||
public override bool CanWrite { get { return true; } }
|
||||
|
||||
public override long Length
|
||||
{
|
||||
get { throw new NotImplementedException(); }
|
||||
}
|
||||
|
||||
public override long Position
|
||||
{
|
||||
get { throw new NotImplementedException(); }
|
||||
set { throw new NotImplementedException(); }
|
||||
}
|
||||
|
||||
public override void Flush()
|
||||
{
|
||||
// We're auto-flushing, so this is a no-op.
|
||||
}
|
||||
|
||||
public override async Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
|
||||
{
|
||||
if (_wasClosedByRemote)
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
|
||||
var bytesRead = 0;
|
||||
while (true)
|
||||
{
|
||||
// Pull as many applicable bytes as we can out of receivedDataNotYetUsed, then update its offset/length
|
||||
int bytesToExtract = Math.Min(count - bytesRead, _receivedDataNotYetUsed.Count);
|
||||
if (bytesToExtract > 0)
|
||||
{
|
||||
Buffer.BlockCopy(_receivedDataNotYetUsed.Array, _receivedDataNotYetUsed.Offset, buffer, bytesRead, bytesToExtract);
|
||||
_receivedDataNotYetUsed = new ArraySegment<byte>(_receivedDataNotYetUsed.Array, _receivedDataNotYetUsed.Offset + bytesToExtract, _receivedDataNotYetUsed.Count - bytesToExtract);
|
||||
bytesRead += bytesToExtract;
|
||||
}
|
||||
|
||||
// If we've completely filled the output buffer, we're done
|
||||
if (bytesRead == count)
|
||||
{
|
||||
return bytesRead;
|
||||
}
|
||||
|
||||
// We haven't yet filled the output buffer, so we must have exhausted receivedDataNotYetUsed instead.
|
||||
// We want to get the next block of data from the underlying queue.
|
||||
byte[] nextReceivedBlock;
|
||||
if (bytesRead > 0)
|
||||
{
|
||||
if (!_receivedDataQueue.TryReceive(null, out nextReceivedBlock))
|
||||
{
|
||||
// No more data is available synchronously, and we already have some data, so we can stop now
|
||||
return bytesRead;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
// Since we don't yet have anything, wait for the underlying source
|
||||
nextReceivedBlock = await _receivedDataQueue.ReceiveAsync(cancellationToken);
|
||||
}
|
||||
|
||||
if (nextReceivedBlock.Length == 0)
|
||||
{
|
||||
// A zero-length block signals that the remote regards this virtual connection as closed
|
||||
_wasClosedByRemote = true;
|
||||
return bytesRead;
|
||||
}
|
||||
else
|
||||
{
|
||||
// We got some more data, so can continue trying to fill the output buffer
|
||||
_receivedDataNotYetUsed = new ArraySegment<byte>(nextReceivedBlock, 0, nextReceivedBlock.Length);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
|
||||
{
|
||||
if (_wasClosedByRemote)
|
||||
{
|
||||
throw new InvalidOperationException("The connection was already closed by the remote party");
|
||||
}
|
||||
|
||||
return count > 0 ? _host.WriteAsync(Id, buffer, offset, count, cancellationToken) : CompletedTask;
|
||||
}
|
||||
|
||||
public override int Read(byte[] buffer, int offset, int count)
|
||||
{
|
||||
return ReadAsync(buffer, offset, count, CancellationToken.None).Result;
|
||||
}
|
||||
|
||||
public override long Seek(long offset, SeekOrigin origin)
|
||||
{
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
|
||||
public override void SetLength(long value)
|
||||
{
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
|
||||
public override void Write(byte[] buffer, int offset, int count)
|
||||
{
|
||||
WriteAsync(buffer, offset, count, CancellationToken.None).Wait();
|
||||
}
|
||||
|
||||
protected override void Dispose(bool disposing)
|
||||
{
|
||||
if (disposing && !_isDisposed)
|
||||
{
|
||||
_isDisposed = true;
|
||||
_host.CloseInnerStream(Id, _wasClosedByRemote);
|
||||
}
|
||||
}
|
||||
|
||||
public async Task AddDataToQueue(byte[] data)
|
||||
{
|
||||
await _receivedDataQueue.SendAsync(data);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,238 +0,0 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace Microsoft.AspNetCore.NodeServices.Sockets.VirtualConnections
|
||||
{
|
||||
/// <summary>
|
||||
/// A callback that will be invoked if the <see cref="VirtualConnectionClient"/> encounters a read error.
|
||||
/// </summary>
|
||||
/// <param name="ex"></param>
|
||||
public delegate void VirtualConnectionReadErrorHandler(Exception ex);
|
||||
|
||||
/// <summary>
|
||||
/// Wraps an underlying physical read/write stream (e.g., named pipes, domain sockets, or TCP sockets) and
|
||||
/// exposes an API for making 'virtual connections', which act as independent read/write streams.
|
||||
/// Traffic over these virtual connections is multiplexed over the underlying physical stream. This is useful
|
||||
/// for fast stream-based inter-process communication because it avoids the overhead of opening a new physical
|
||||
/// connection each time a new communication channel is needed.
|
||||
/// </summary>
|
||||
internal class VirtualConnectionClient : IDisposable
|
||||
{
|
||||
internal const int MaxFrameBodyLength = 16 * 1024;
|
||||
|
||||
public event VirtualConnectionReadErrorHandler OnError;
|
||||
|
||||
private Stream _underlyingTransport;
|
||||
private Dictionary<long, VirtualConnection> _activeInnerStreams;
|
||||
private long _nextInnerStreamId;
|
||||
private readonly SemaphoreSlim _streamWriterSemaphore = new SemaphoreSlim(1);
|
||||
private readonly object _readControlLock = new object();
|
||||
private Exception _readLoopExitedWithException;
|
||||
private readonly CancellationTokenSource _disposalCancellatonToken = new CancellationTokenSource();
|
||||
private bool _disposedValue = false;
|
||||
|
||||
public VirtualConnectionClient(Stream underlyingTransport)
|
||||
{
|
||||
_underlyingTransport = underlyingTransport;
|
||||
_activeInnerStreams = new Dictionary<long, VirtualConnection>();
|
||||
|
||||
RunReadLoop();
|
||||
}
|
||||
|
||||
public Stream OpenVirtualConnection()
|
||||
{
|
||||
// Improve discoverability of read-loop errors (in case the developer doesn't add an OnError listener)
|
||||
ThrowIfReadLoopFailed();
|
||||
|
||||
var id = Interlocked.Increment(ref _nextInnerStreamId);
|
||||
var newInnerStream = new VirtualConnection(id, this);
|
||||
lock (_activeInnerStreams)
|
||||
{
|
||||
_activeInnerStreams.Add(id, newInnerStream);
|
||||
}
|
||||
|
||||
return newInnerStream;
|
||||
}
|
||||
|
||||
// It's async void because nothing waits for it to finish (it continues indefinitely). It signals any errors via
|
||||
// a separate channel.
|
||||
private async void RunReadLoop()
|
||||
{
|
||||
try
|
||||
{
|
||||
while (!_disposalCancellatonToken.IsCancellationRequested)
|
||||
{
|
||||
var remoteIsStillConnected = await ProcessNextFrameAsync();
|
||||
if (!remoteIsStillConnected)
|
||||
{
|
||||
CloseAllActiveStreams();
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
// Not all underlying transports correctly honor cancellation tokens. For example,
|
||||
// DomainSocketStreamTransport's ReadAsync ignores them, so we only know to stop
|
||||
// the read loop when the underlying stream is disposed and then it throws ObjectDisposedException.
|
||||
if (!(ex is TaskCanceledException || ex is ObjectDisposedException))
|
||||
{
|
||||
_readLoopExitedWithException = ex;
|
||||
|
||||
var evt = OnError;
|
||||
if (evt != null)
|
||||
{
|
||||
evt(ex);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private async Task<bool> ProcessNextFrameAsync()
|
||||
{
|
||||
// First read frame header
|
||||
var frameHeaderBuffer = await ReadExactLength(12);
|
||||
if (frameHeaderBuffer == null)
|
||||
{
|
||||
return false; // Underlying stream was closed
|
||||
}
|
||||
|
||||
// Parse frame header, then read the frame body
|
||||
long streamId = BitConverter.ToInt64(frameHeaderBuffer, 0);
|
||||
int frameBodyLength = BitConverter.ToInt32(frameHeaderBuffer, 8);
|
||||
if (frameBodyLength < 0 || frameBodyLength > MaxFrameBodyLength)
|
||||
{
|
||||
throw new InvalidDataException("Illegal frame length: " + frameBodyLength);
|
||||
}
|
||||
|
||||
var frameBody = await ReadExactLength(frameBodyLength);
|
||||
if (frameBody == null)
|
||||
{
|
||||
return false; // Underlying stream was closed
|
||||
}
|
||||
|
||||
// Dispatch the frame to the relevant inner stream
|
||||
VirtualConnection innerStream;
|
||||
lock (_activeInnerStreams)
|
||||
{
|
||||
_activeInnerStreams.TryGetValue(streamId, out innerStream);
|
||||
}
|
||||
|
||||
if (innerStream != null)
|
||||
{
|
||||
await innerStream.AddDataToQueue(frameBody);
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
private async Task<byte[]> ReadExactLength(int lengthToRead) {
|
||||
byte[] buffer = new byte[lengthToRead];
|
||||
var totalBytesRead = 0;
|
||||
var ct = _disposalCancellatonToken.Token;
|
||||
while (totalBytesRead < lengthToRead)
|
||||
{
|
||||
var chunkLengthRead = await _underlyingTransport.ReadAsync(buffer, totalBytesRead, lengthToRead - totalBytesRead, ct);
|
||||
if (chunkLengthRead == 0)
|
||||
{
|
||||
// Underlying stream was closed
|
||||
return null;
|
||||
}
|
||||
|
||||
totalBytesRead += chunkLengthRead;
|
||||
}
|
||||
|
||||
return buffer;
|
||||
}
|
||||
|
||||
private void CloseAllActiveStreams()
|
||||
{
|
||||
IList<VirtualConnection> innerStreamsCopy;
|
||||
|
||||
// Only hold the lock while cloning the list of inner streams. Release the lock before
|
||||
// actually disposing them, because each 'dispose' call will try to take another lock
|
||||
// so it can remove that inner stream from activeInnerStreams.
|
||||
lock (_activeInnerStreams)
|
||||
{
|
||||
innerStreamsCopy = _activeInnerStreams.Values.ToList();
|
||||
}
|
||||
|
||||
foreach (var stream in innerStreamsCopy)
|
||||
{
|
||||
stream.Dispose();
|
||||
}
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
if (!_disposedValue)
|
||||
{
|
||||
_disposedValue = true;
|
||||
|
||||
_disposalCancellatonToken.Cancel(); // Stops the read loop
|
||||
CloseAllActiveStreams();
|
||||
}
|
||||
}
|
||||
|
||||
public async Task WriteAsync(long innerStreamId, byte[] data, int offset, int count, CancellationToken cancellationToken)
|
||||
{
|
||||
// In case the amount of data to be sent exceeds the max frame length, split it into separate frames
|
||||
// Note that we always send at least one frame, even if it's empty, because the zero-length frame is the signal to close a virtual connection
|
||||
// (hence 'do..while' instead of just 'while').
|
||||
int bytesWritten = 0;
|
||||
do {
|
||||
// Improve discoverability of read-loop errors (in case the developer doesn't add an OnError listener)
|
||||
ThrowIfReadLoopFailed();
|
||||
|
||||
// Hold the write lock only for the time taken to send a single frame, not all frames, to allow large sends to be proceed in parallel
|
||||
await _streamWriterSemaphore.WaitAsync(cancellationToken).ConfigureAwait(false);
|
||||
try
|
||||
{
|
||||
// Write stream ID, then length prefix, then chunk payload, then flush
|
||||
var nextChunkBodyLength = Math.Min(MaxFrameBodyLength, count - bytesWritten);
|
||||
await _underlyingTransport.WriteAsync(BitConverter.GetBytes(innerStreamId), 0, 8, cancellationToken).ConfigureAwait(false);
|
||||
await _underlyingTransport.WriteAsync(BitConverter.GetBytes(nextChunkBodyLength), 0, 4, cancellationToken).ConfigureAwait(false);
|
||||
|
||||
if (nextChunkBodyLength > 0)
|
||||
{
|
||||
await _underlyingTransport.WriteAsync(data, offset + bytesWritten, nextChunkBodyLength, cancellationToken).ConfigureAwait(false);
|
||||
bytesWritten += nextChunkBodyLength;
|
||||
}
|
||||
|
||||
await _underlyingTransport.FlushAsync(cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
finally
|
||||
{
|
||||
_streamWriterSemaphore.Release();
|
||||
}
|
||||
} while (bytesWritten < count);
|
||||
}
|
||||
|
||||
public void CloseInnerStream(long innerStreamId, bool isAlreadyClosedRemotely)
|
||||
{
|
||||
lock (_activeInnerStreams)
|
||||
{
|
||||
if (_activeInnerStreams.ContainsKey(innerStreamId))
|
||||
{
|
||||
_activeInnerStreams.Remove(innerStreamId);
|
||||
}
|
||||
}
|
||||
|
||||
if (!isAlreadyClosedRemotely) {
|
||||
// Also notify the remote that this innerstream is closed
|
||||
WriteAsync(innerStreamId, new byte[0], 0, 0, new CancellationToken()).Wait();
|
||||
}
|
||||
}
|
||||
|
||||
private void ThrowIfReadLoopFailed()
|
||||
{
|
||||
if (_readLoopExitedWithException != null)
|
||||
{
|
||||
throw new AggregateException("The connection failed - see InnerException for details.", _readLoopExitedWithException);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,109 +0,0 @@
|
||||
{
|
||||
"AssemblyIdentity": "Microsoft.AspNetCore.NodeServices.Sockets, Version=2.1.1.0, Culture=neutral, PublicKeyToken=adb9793829ddae60",
|
||||
"Types": [
|
||||
{
|
||||
"Name": "Microsoft.AspNetCore.NodeServices.Sockets.NodeServicesOptionsExtensions",
|
||||
"Visibility": "Public",
|
||||
"Kind": "Class",
|
||||
"Abstract": true,
|
||||
"Static": true,
|
||||
"Sealed": true,
|
||||
"ImplementedInterfaces": [],
|
||||
"Members": [
|
||||
{
|
||||
"Kind": "Method",
|
||||
"Name": "UseSocketHosting",
|
||||
"Parameters": [
|
||||
{
|
||||
"Name": "options",
|
||||
"Type": "Microsoft.AspNetCore.NodeServices.NodeServicesOptions"
|
||||
}
|
||||
],
|
||||
"ReturnType": "System.Void",
|
||||
"Static": true,
|
||||
"Extension": true,
|
||||
"Visibility": "Public",
|
||||
"GenericParameter": []
|
||||
}
|
||||
],
|
||||
"GenericParameters": []
|
||||
},
|
||||
{
|
||||
"Name": "Microsoft.AspNetCore.NodeServices.Sockets.VirtualConnections.VirtualConnectionReadErrorHandler",
|
||||
"Visibility": "Public",
|
||||
"Kind": "Class",
|
||||
"Sealed": true,
|
||||
"BaseType": "System.MulticastDelegate",
|
||||
"ImplementedInterfaces": [],
|
||||
"Members": [
|
||||
{
|
||||
"Kind": "Method",
|
||||
"Name": "Invoke",
|
||||
"Parameters": [
|
||||
{
|
||||
"Name": "ex",
|
||||
"Type": "System.Exception"
|
||||
}
|
||||
],
|
||||
"ReturnType": "System.Void",
|
||||
"Virtual": true,
|
||||
"Visibility": "Public",
|
||||
"GenericParameter": []
|
||||
},
|
||||
{
|
||||
"Kind": "Method",
|
||||
"Name": "BeginInvoke",
|
||||
"Parameters": [
|
||||
{
|
||||
"Name": "ex",
|
||||
"Type": "System.Exception"
|
||||
},
|
||||
{
|
||||
"Name": "callback",
|
||||
"Type": "System.AsyncCallback"
|
||||
},
|
||||
{
|
||||
"Name": "object",
|
||||
"Type": "System.Object"
|
||||
}
|
||||
],
|
||||
"ReturnType": "System.IAsyncResult",
|
||||
"Virtual": true,
|
||||
"Visibility": "Public",
|
||||
"GenericParameter": []
|
||||
},
|
||||
{
|
||||
"Kind": "Method",
|
||||
"Name": "EndInvoke",
|
||||
"Parameters": [
|
||||
{
|
||||
"Name": "result",
|
||||
"Type": "System.IAsyncResult"
|
||||
}
|
||||
],
|
||||
"ReturnType": "System.Void",
|
||||
"Virtual": true,
|
||||
"Visibility": "Public",
|
||||
"GenericParameter": []
|
||||
},
|
||||
{
|
||||
"Kind": "Constructor",
|
||||
"Name": ".ctor",
|
||||
"Parameters": [
|
||||
{
|
||||
"Name": "object",
|
||||
"Type": "System.Object"
|
||||
},
|
||||
{
|
||||
"Name": "method",
|
||||
"Type": "System.IntPtr"
|
||||
}
|
||||
],
|
||||
"Visibility": "Public",
|
||||
"GenericParameter": []
|
||||
}
|
||||
],
|
||||
"GenericParameters": []
|
||||
}
|
||||
]
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,19 +0,0 @@
|
||||
{
|
||||
"name": "nodeservices.sockets",
|
||||
"version": "1.0.0",
|
||||
"description": "This is not really an NPM package and will not be published. This file exists only to reference compilation tools.",
|
||||
"main": "index.js",
|
||||
"scripts": {
|
||||
"test": "echo \"Error: no test specified\" && exit 1",
|
||||
"build": "webpack --mode production"
|
||||
},
|
||||
"author": "Microsoft",
|
||||
"license": "Apache-2.0",
|
||||
"devDependencies": {
|
||||
"@types/node": "^10.9.2",
|
||||
"ts-loader": "^4.5.0",
|
||||
"typescript": "^3.0.1",
|
||||
"webpack": "^4.17.1",
|
||||
"webpack-cli": "^3.1.0"
|
||||
}
|
||||
}
|
||||
@@ -1,24 +0,0 @@
|
||||
const path = require('path');
|
||||
|
||||
module.exports = {
|
||||
target: 'node',
|
||||
resolve: {
|
||||
extensions: [ '.ts' ]
|
||||
},
|
||||
module: {
|
||||
rules: [
|
||||
{ test: /\.ts$/, use: 'ts-loader' },
|
||||
]
|
||||
},
|
||||
entry: {
|
||||
'entrypoint-socket': ['./TypeScript/SocketNodeInstanceEntryPoint'],
|
||||
},
|
||||
output: {
|
||||
libraryTarget: 'commonjs',
|
||||
path: path.join(__dirname, 'Content', 'Node'),
|
||||
filename: '[name].js'
|
||||
},
|
||||
optimization: {
|
||||
minimize: false
|
||||
}
|
||||
};
|
||||
@@ -1,3 +0,0 @@
|
||||
/bin/
|
||||
/node_modules/
|
||||
yarn.lock
|
||||
@@ -1,25 +0,0 @@
|
||||
using System;
|
||||
|
||||
namespace Microsoft.AspNetCore.NodeServices
|
||||
{
|
||||
/// <summary>
|
||||
/// Supplies INodeServices instances.
|
||||
/// </summary>
|
||||
public static class NodeServicesFactory
|
||||
{
|
||||
/// <summary>
|
||||
/// Create an <see cref="INodeServices"/> instance according to the supplied options.
|
||||
/// </summary>
|
||||
/// <param name="options">Options for creating the <see cref="INodeServices"/> instance.</param>
|
||||
/// <returns>An <see cref="INodeServices"/> instance.</returns>
|
||||
public static INodeServices CreateNodeServices(NodeServicesOptions options)
|
||||
{
|
||||
if (options == null)
|
||||
{
|
||||
throw new ArgumentNullException(nameof (options));
|
||||
}
|
||||
|
||||
return new NodeServicesImpl(options.NodeInstanceFactory);
|
||||
}
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user