JavaScriptExtensionsAspire–part 2–execution

Now about the execution of https://www.nuget.org/packages/JavaScriptExtensionsAspire

Finding and parsing the package json is pretty easy – this is the code

var builder = appResource.ApplicationBuilder;
var wd = appResource.Resource.WorkingDirectory;
var packageJsonPath = Path.Combine(wd, "package.json");
if (!File.Exists(packageJsonPath))
{
    throw new FileNotFoundException($"Could not find package.json at {packageJsonPath}");
}
var packageJson = System.Text.Json.JsonDocument.Parse(File.ReadAllText(packageJsonPath));
if (!packageJson.RootElement.TryGetProperty("scripts", out var scripts))
{
    throw new Exception($"No scripts section found in package.json at {packageJsonPath}");
}

More interessant is to find the name of npm executable

var npmPath = "npm";

if (OperatingSystem.IsWindows())
    npmPath = "npm.cmd";
npmPath = FullExeName(npmPath);
private static string FullExeName(string command)
{
    var paths = Environment.GetEnvironmentVariable("PATH");
    if (paths == null) return command;
    var where = paths.Split(new char[] { Path.PathSeparator }, StringSplitOptions.RemoveEmptyEntries)
        .Select(p => Path.Combine(p, command))
        .FirstOrDefault(p => File.Exists(p));

    return where ?? command;
}

Also I want to add the environment variables from the original javascript app

if (appResource.Resource.TryGetEnvironmentVariables(out var envCallback))
{
    Dictionary<string, object> envDict = new();
    EnvironmentCallbackContext environmentCallbackContext = new(builder.ExecutionContext, envDict);
    foreach (var env in envCallback)
    {
        await env.Callback(environmentCallbackContext);

    }
    var envs = environmentCallbackContext.EnvironmentVariables;

    foreach (var kvp in envs)
    {
        exportStartInfo.Environment[kvp.Key] = kvp.Value?.ToString() ?? "";
    }
}

Otherwise, pretty obvious stuff of starting the npm process info .

NuGet Package: https://www.nuget.org/packages/JavaScriptExtensionsAspire
GitHub Repository: https://github.com/ignatandrei/aspireExtensions
See demo at https://ignatandrei.github.io/aspireExtensions/images/JavaScriptExtensions/packageJson.mp4


by

Tags: