-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathConnection.cs
More file actions
104 lines (92 loc) · 3.75 KB
/
Connection.cs
File metadata and controls
104 lines (92 loc) · 3.75 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.SpaServices;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using System;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net.NetworkInformation;
using System.Runtime.InteropServices;
using System.Threading.Tasks;
namespace dotnet_sapper
{
public static class Connection
{
private static int port { get; } = 3000;
private static Uri DevelopmentServerEndpoint { get; } = new Uri($"http://localhost:{port}");
private static TimeSpan Timeout { get; } = TimeSpan.FromSeconds(60);
private static string DoneMessage { get; } = "DONE Compiled successfully in";
public static void UseSapperDevelopmentServer(this ISpaBuilder spa, string npmScript)
{
spa.UseProxyToSpaDevelopmentServer(async () =>
{
var loggerFactory = spa.ApplicationBuilder.ApplicationServices.GetService<ILoggerFactory>();
var logger = loggerFactory.CreateLogger("Sapper");
if (IsRunning())
{
return DevelopmentServerEndpoint;
}
var isWindows = RuntimeInformation.IsOSPlatform(OSPlatform.Windows);
var processInfo = new ProcessStartInfo
{
FileName = isWindows ? "cmd" : "npm",
Arguments = $"{(isWindows ? "/c npm " : "")}run {npmScript}",
WorkingDirectory = spa.Options.SourcePath,
RedirectStandardError = true,
RedirectStandardInput = true,
RedirectStandardOutput = true,
UseShellExecute = false,
};
var process = Process.Start(processInfo);
var tcs = new TaskCompletionSource<int>();
_ = Task.Run(() =>
{
try
{
string line;
while ((line = process.StandardOutput.ReadLine()) != null)
{
logger.LogInformation(line);
if (!tcs.Task.IsCompleted && line.Contains(DoneMessage))
{
tcs.SetResult(1);
}
}
}
catch (EndOfStreamException ex)
{
logger.LogError(ex.ToString());
tcs.SetException(new InvalidOperationException($"'npm run {npmScript}' failed.", ex));
}
});
_ = Task.Run(() =>
{
try
{
string line;
while ((line = process.StandardError.ReadLine()) != null)
{
logger.LogError(line);
}
}
catch (EndOfStreamException ex)
{
logger.LogError(ex.ToString());
tcs.SetException(new InvalidOperationException($"'npm run {npmScript}' failed.", ex));
}
});
var timeout = Task.Delay(Timeout);
if (await Task.WhenAny(timeout, tcs.Task) == timeout)
{
throw new TimeoutException();
}
return DevelopmentServerEndpoint;
});
}
private static bool IsRunning() => IPGlobalProperties.GetIPGlobalProperties()
.GetActiveTcpListeners()
.Select(x => x.Port)
.Contains(port);
}
}