Skip to content

Commit efaf38d

Browse files
authored
Add the NodeApi.Embedding package (#518)
1 parent e4388b0 commit efaf38d

15 files changed

Lines changed: 327 additions & 10 deletions

File tree

‎NodeApi.sln‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,8 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "NodeApi.DotNetHost", "src\N
3131
EndProject
3232
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "NodeApi.Bench", "bench\NodeApi.Bench.csproj", "{9EC2AB75-6B03-4E83-8A5D-8660B40B0A9C}"
3333
EndProject
34+
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "NodeApi.Embedding", "src\NodeApi.Embedding\NodeApi.Embedding.csproj", "{A8373A97-43A1-4AB3-8437-C0745B187E77}"
35+
EndProject
3436
Global
3537
GlobalSection(SolutionConfigurationPlatforms) = preSolution
3638
Debug|Any CPU = Debug|Any CPU
@@ -57,6 +59,10 @@ Global
5759
{9EC2AB75-6B03-4E83-8A5D-8660B40B0A9C}.Debug|Any CPU.Build.0 = Debug|Any CPU
5860
{9EC2AB75-6B03-4E83-8A5D-8660B40B0A9C}.Release|Any CPU.ActiveCfg = Release|Any CPU
5961
{9EC2AB75-6B03-4E83-8A5D-8660B40B0A9C}.Release|Any CPU.Build.0 = Release|Any CPU
62+
{A8373A97-43A1-4AB3-8437-C0745B187E77}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
63+
{A8373A97-43A1-4AB3-8437-C0745B187E77}.Debug|Any CPU.Build.0 = Debug|Any CPU
64+
{A8373A97-43A1-4AB3-8437-C0745B187E77}.Release|Any CPU.ActiveCfg = Release|Any CPU
65+
{A8373A97-43A1-4AB3-8437-C0745B187E77}.Release|Any CPU.Build.0 = Release|Any CPU
6066
EndGlobalSection
6167
GlobalSection(SolutionProperties) = preSolution
6268
HideSolutionNode = FALSE

‎docs/reference/packages-releases.md‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,16 @@ code-generation for dynamic marshalling. See the [.NET API reference](../referen
1010
Contains the MSBuild tasks and supporting assemblies for generating marshalling code at compile
1111
time, and for generating TypeScript type defintions for .NET APIs.
1212

13+
[`Microsoft.JavaScript.NodeApi.Embedding`](https://www.nuget.org/packages/Microsoft.JavaScript.NodeApi.Embedding/) -
14+
Embeds Node.js in a .NET application. It has no assembly of its own; it brings in
15+
`Microsoft.JavaScript.NodeApi` and `Microsoft.JavaScript.LibNode`, which provides the `libnode`
16+
native library for Windows, Linux, and macOS on x64 and arm64. See
17+
[Embedding a JS runtime](../scenarios/dotnet-js).
18+
19+
[`Microsoft.JavaScript.NodeApi.DotNetHost`](https://www.nuget.org/packages/Microsoft.JavaScript.NodeApi.DotNetHost/) -
20+
Hosts .NET in a Node.js process, the opposite direction from `.Embedding`. An application that
21+
works in both directions can reference both packages, as the WinUI Fluid example does.
22+
1323
## NPM packages
1424

1525
[`node-api-dotnet`](https://www.npmjs.com/package/node-api-dotnet) - Supports loading .NET

‎docs/scenarios/dotnet-js.md‎

Lines changed: 32 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -6,13 +6,32 @@ should be.
66
:::
77

88
## Acquiring the required `libnode` binary
9-
Reference [`Microsoft.JavaScript.LibNode`](https://www.nuget.org/packages/Microsoft.JavaScript.LibNode).
10-
It provides `libnode` built from Node.js 26 with the ABI-stable embedding API, for
9+
Reference the
10+
[`Microsoft.JavaScript.NodeApi.Embedding`](https://www.nuget.org/packages/Microsoft.JavaScript.NodeApi.Embedding)
11+
package:
12+
13+
```xml
14+
<PackageReference Include="Microsoft.JavaScript.NodeApi.Embedding" Version="..." />
15+
```
16+
17+
It has no assembly of its own; it brings in `Microsoft.JavaScript.NodeApi` and
18+
[`Microsoft.JavaScript.LibNode`](https://www.nuget.org/packages/Microsoft.JavaScript.LibNode).
19+
LibNode provides `libnode` built from Node.js 26 with the ABI-stable embedding API, for
1120
`win-x64`, `win-arm64`, `linux-x64`, `linux-arm64`, `osx-x64`, and `osx-arm64`.
12-
The embedding API is not yet in upstream Node.js and changes between versions; use the LibNode
13-
version pinned in `Directory.Packages.props`, the only one tested with each release.
14-
To restore a single platform, reference `Microsoft.JavaScript.LibNode.<rid>` instead.
15-
Also reference `Microsoft.JavaScript.NodeApi` for the .NET APIs.
21+
Referencing `Microsoft.JavaScript.NodeApi` and `Microsoft.JavaScript.LibNode` directly also works.
22+
23+
The embedding API is not yet in upstream Node.js and changes between versions. Each release is
24+
tested with one LibNode version, which is the embedding package's minimum LibNode dependency.
25+
Newer LibNode versions are allowed; test your application with them.
26+
27+
The package restores `libnode` for all six platforms, about 280 MB once per LibNode version.
28+
A RID-specific .NET build copies only its platform's library to the output; portable and
29+
.NET Framework builds copy all six. To restore a single platform, reference
30+
`Microsoft.JavaScript.NodeApi` and `Microsoft.JavaScript.LibNode.<rid>` instead (for example,
31+
`Microsoft.JavaScript.LibNode.win-x64`).
32+
33+
`Microsoft.JavaScript.NodeApi.DotNetHost` works the other way around: it hosts .NET in a Node.js
34+
process, and embedding doesn't need it.
1635
See [Embedding (LibNode) requirements](../requirements#embedding-libnode) for OS requirements.
1736

1837
## Importing JS modules into .NET
@@ -99,3 +118,10 @@ Then attach a JavaScript debugger such as VS Code or Chrome to the inspection UR
99118
- .NET Framework apps must run 64-bit. Keep the SDK default AnyCPU with `Prefer32Bit` false,
100119
or set `PlatformTarget` to `x64`/`arm64` or `RuntimeIdentifier` to `win-x64`/`win-arm64`.
101120
Do not target x86 or enable `Prefer32Bit`. IIS app pools must also run 64-bit.
121+
122+
The embedding package reports build warning `NODEAPIEMBED001` when `PlatformTarget` is `x86`, or
123+
for a .NET Framework `AnyCPU` build with `Prefer32Bit` set to `true`. It is a warning, not an
124+
error, because an application can supply its own 32-bit `libnode` through
125+
`NodeEmbeddingPlatformSettings.LibNodePath`. Such an application can suppress it with
126+
`<NoWarn>$(NoWarn);NODEAPIEMBED001</NoWarn>`, which also works with `TreatWarningsAsErrors`.
127+
The package can't detect a 32-bit IIS application pool; configure the pool to run 64-bit.

‎examples/jsdom/jsdom.csproj‎

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,6 @@
1414
</ItemGroup>
1515

1616
<ItemGroup>
17-
<PackageReference Include="Microsoft.JavaScript.LibNode" Version="$(LibNodePackageVersion)" />
18-
<PackageReference Include="Microsoft.JavaScript.NodeApi" Version="$(NodeApiDotnetPackageVersion)" />
17+
<PackageReference Include="Microsoft.JavaScript.NodeApi.Embedding" Version="$(NodeApiDotnetPackageVersion)" />
1918
</ItemGroup>
2019
</Project>

‎examples/winui-fluid/winui-fluid.csproj‎

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -45,8 +45,7 @@
4545
</ItemGroup>
4646

4747
<ItemGroup>
48-
<PackageReference Include="Microsoft.JavaScript.LibNode" Version="$(LibNodePackageVersion)" />
49-
<PackageReference Include="Microsoft.JavaScript.NodeApi" Version="$(NodeApiDotnetPackageVersion)" />
48+
<PackageReference Include="Microsoft.JavaScript.NodeApi.Embedding" Version="$(NodeApiDotnetPackageVersion)" />
5049
<PackageReference Include="Microsoft.JavaScript.NodeApi.DotNetHost" Version="$(NodeApiDotnetPackageVersion)" />
5150
<PackageReference Include="Microsoft.WindowsAppSDK" Version="1.*" />
5251
<PackageReference Include="Microsoft.Windows.SDK.BuildTools" Version="10.0.26100.4654" />
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
<Project Sdk="Microsoft.NET.Sdk">
2+
<PropertyGroup>
3+
<AssemblyName>Microsoft.JavaScript.NodeApi.Embedding</AssemblyName>
4+
<IsPackable>true</IsPackable>
5+
<IncludeBuildOutput>false</IncludeBuildOutput>
6+
<IncludeSymbols>false</IncludeSymbols>
7+
<Description>Embeds Node.js in .NET apps: brings Microsoft.JavaScript.NodeApi and Microsoft.JavaScript.LibNode (win/linux/osx, x64/arm64).</Description>
8+
<TargetsForTfmSpecificContentInPackage>$(TargetsForTfmSpecificContentInPackage);IncludeFrameworkSentinel</TargetsForTfmSpecificContentInPackage>
9+
</PropertyGroup>
10+
11+
<ItemGroup>
12+
<ProjectReference Include="../NodeApi/NodeApi.csproj" PrivateAssets="none" />
13+
<PackageReference Include="Microsoft.JavaScript.LibNode" PrivateAssets="none" />
14+
<None Include="../../README.md" Pack="true" PackagePath="/" />
15+
<None Include="buildTransitive/*.targets" Pack="true" PackagePath="buildTransitive/" />
16+
</ItemGroup>
17+
18+
<Target Name="IncludeFrameworkSentinel">
19+
<ItemGroup>
20+
<TfmSpecificPackageFile Include="$(MSBuildProjectDirectory)/_._" PackagePath="lib/$(TargetFramework)/" />
21+
</ItemGroup>
22+
</Target>
23+
</Project>

‎src/NodeApi.Embedding/_._‎

Whitespace-only changes.
Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
<Project>
2+
<Target Name="WarnNodeApiEmbeddingBitness" AfterTargets="CoreCompile"
3+
Condition=" '$(PlatformTarget)' == 'x86' OR ('$(TargetFrameworkIdentifier)' == '.NETFramework' AND '$(PlatformTarget)' == 'AnyCPU' AND '$(Prefer32Bit)' == 'true') ">
4+
<Warning Code="NODEAPIEMBED001"
5+
Text="libnode has no x86 build; use x64/arm64. A custom NodeEmbeddingPlatformSettings.LibNodePath is required for a 32-bit process." />
6+
</Target>
7+
</Project>

‎test/EmbeddingPackageTests.cs‎

Lines changed: 190 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,190 @@
1+
// Copyright (c) Microsoft Corporation.
2+
// Licensed under the MIT License.
3+
4+
#if NET10_0 || NETFRAMEWORK
5+
using System;
6+
using System.Collections.Generic;
7+
using System.Diagnostics;
8+
using System.IO;
9+
using System.Linq;
10+
using System.Runtime.InteropServices;
11+
using System.Threading.Tasks;
12+
using System.Xml.Linq;
13+
using Xunit;
14+
using static Microsoft.JavaScript.NodeApi.Test.TestBuilder;
15+
using static Microsoft.JavaScript.NodeApi.Test.TestUtils;
16+
17+
namespace Microsoft.JavaScript.NodeApi.Test;
18+
19+
[CollectionDefinition(nameof(EmbeddingPackageTests), DisableParallelization = true)]
20+
[Collection(nameof(EmbeddingPackageTests))]
21+
public sealed class EmbeddingPackageTests : IDisposable
22+
{
23+
private const string WarningCode = "NODEAPIEMBED001";
24+
private readonly string _fixture = Path.Combine(TestCasesDirectory, "EmbeddingPackage");
25+
private readonly string _packages = Path.Combine(RepoRootDirectory, "out", "obj",
26+
Configuration, "TestCases", "EmbeddingConsumer", "packages");
27+
private readonly string _version;
28+
private readonly string _libNodeVersion;
29+
30+
public EmbeddingPackageTests()
31+
{
32+
XElement versions = XElement.Load(Path.Combine(RepoRootDirectory, "out", "pkg", "version.props"));
33+
_version = versions.Descendants("NodeApiDotNetPackageVersion").Single().Value;
34+
_libNodeVersion = versions.Descendants("LibNodePackageVersion").Single().Value;
35+
if (Directory.Exists(_packages)) Directory.Delete(_packages, recursive: true);
36+
Directory.CreateDirectory(_packages);
37+
38+
// A net10 run writes this file; net472 must use the repository SDK, not a stale file.
39+
File.Delete(Path.Combine(_fixture, "global.json"));
40+
}
41+
42+
public void Dispose() => File.Delete(Path.Combine(_fixture, "global.json"));
43+
44+
#if NET10_0
45+
[Fact]
46+
public void PortableConsumerImportsEsmRegardlessOfPrefer32Bit()
47+
{
48+
string output = BuildConsumer("portable");
49+
AssertConsumerRuns(output);
50+
51+
// Modern .NET ignores Prefer32Bit, so it must still build without NODEAPIEMBED001.
52+
output = BuildConsumer("prefer32bit", "AnyCPU", prefer32Bit: true);
53+
AssertConsumerRuns(output);
54+
}
55+
56+
[Fact]
57+
public void WindowsPackageContainsFrameworkSentinelsAndTransitiveDependencies()
58+
{
59+
// Windows-only: other platforms omit net472, and this project has no dynamic skip mechanism.
60+
if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) return;
61+
62+
string extracted = Path.Combine(_packages, "inspection");
63+
string package = Path.Combine(RepoRootDirectory, "out", "pkg",
64+
$"Microsoft.JavaScript.NodeApi.Embedding.{_version}.nupkg");
65+
System.IO.Compression.ZipFile.ExtractToDirectory(package, extracted);
66+
XElement metadata = XDocument.Load(Directory.GetFiles(extracted, "*.nuspec").Single())
67+
.Root!.Elements().Single();
68+
XNamespace ns = metadata.Name.Namespace;
69+
Assert.Equal("Embeds Node.js in .NET apps: brings Microsoft.JavaScript.NodeApi and " +
70+
"Microsoft.JavaScript.LibNode (win/linux/osx, x64/arm64).",
71+
metadata.Element(ns + "description")!.Value);
72+
XElement[] groups = metadata.Element(ns + "dependencies")!.Elements().ToArray();
73+
string[] expectedFrameworks =
74+
{ ".NETFramework4.7.2", ".NETStandard2.0", "net10.0", "net8.0", "net9.0" };
75+
Assert.Equal(expectedFrameworks,
76+
groups.Select(g => g.Attribute("targetFramework")!.Value).OrderBy(t => t, StringComparer.Ordinal));
77+
foreach (XElement group in groups)
78+
{
79+
XElement[] dependencies = group.Elements().ToArray();
80+
Assert.Equal(2, dependencies.Length);
81+
Assert.All(dependencies, d => Assert.Equal("All", d.Attribute("include")!.Value));
82+
Assert.Equal(_libNodeVersion, dependencies.Single(d =>
83+
d.Attribute("id")!.Value == "Microsoft.JavaScript.LibNode").Attribute("version")!.Value);
84+
Assert.Equal(_version, dependencies.Single(d =>
85+
d.Attribute("id")!.Value == "Microsoft.JavaScript.NodeApi").Attribute("version")!.Value);
86+
}
87+
88+
foreach (string tfm in new[] { "net10.0", "net9.0", "net8.0", "netstandard2.0", "net472" })
89+
{
90+
Assert.True(File.Exists(Path.Combine(extracted, "lib", tfm, "_._")), tfm);
91+
}
92+
Assert.Empty(Directory.GetFiles(extracted, "*.dll", SearchOption.AllDirectories));
93+
Assert.False(File.Exists(Path.ChangeExtension(package, ".snupkg")));
94+
Assert.True(File.Exists(Path.Combine(extracted, "README.md")));
95+
Assert.True(File.Exists(Path.Combine(extracted, "buildTransitive",
96+
"Microsoft.JavaScript.NodeApi.Embedding.targets")));
97+
}
98+
#else
99+
[Fact]
100+
public void FrameworkX64ConsumerImportsEsm()
101+
{
102+
string output = BuildConsumer("x64", "x64");
103+
Assert.True(File.Exists(Path.Combine(output, "runtimes", "win-x64", "native", "libnode.dll")));
104+
AssertConsumerRuns(output);
105+
}
106+
107+
[Fact]
108+
public void FrameworkDefaultConsumerRunsAs64BitAnyCpu()
109+
{
110+
string output = BuildConsumer("default");
111+
Assert.Equal("AnyCPU", File.ReadAllText(Path.Combine(output, "platform.txt")).Trim());
112+
AssertConsumerRuns(output);
113+
}
114+
115+
// Both explicit x86 and legacy Prefer32Bit must warn, without running a 32-bit process.
116+
[Theory]
117+
[InlineData("x86", false)]
118+
[InlineData("AnyCPU", true)]
119+
public void Framework32BitConsumerBuildWarns(string platform, bool prefer32Bit)
120+
{
121+
BuildConsumer("warning-" + platform, platform, prefer32Bit, expectWarning: true);
122+
}
123+
#endif
124+
125+
private string BuildConsumer(
126+
string lane, string? platform = null, bool prefer32Bit = false, bool expectWarning = false)
127+
{
128+
string framework = GetCurrentFrameworkTarget();
129+
string fallback = Environment.GetEnvironmentVariable("NUGET_PACKAGES") ??
130+
Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), ".nuget", "packages");
131+
var properties = new Dictionary<string, string>
132+
{
133+
["Configuration"] = Configuration,
134+
["TargetFrameworks"] = framework,
135+
["ConsumerLane"] = lane,
136+
["RestorePackagesPath"] = _packages,
137+
["RestoreFallbackFolders"] = fallback,
138+
["RestoreNoHttpCache"] = "true",
139+
["RestoreForce"] = "true",
140+
};
141+
if (platform != null) properties["PlatformTarget"] = platform;
142+
if (prefer32Bit) properties["Prefer32Bit"] = "true";
143+
string log = GetBuildLogFilePath(lane, "EmbeddingConsumer");
144+
BuildProject(Path.Combine(_fixture, "EmbeddingConsumer.csproj"), "Rebuild", properties, log);
145+
string buildLog = File.ReadAllText(log);
146+
Assert.Equal(expectWarning, buildLog.Contains(WarningCode));
147+
foreach (string id in new[] { "microsoft.javascript.nodeapi", "microsoft.javascript.nodeapi.embedding" })
148+
{
149+
Assert.True(File.Exists(Path.Combine(_packages, id, _version, id + ".nuspec")), id);
150+
}
151+
// LibNode must come from the already-restored fallback, not another six-RID extraction.
152+
Assert.Empty(Directory.GetDirectories(_packages, "microsoft.javascript.libnode*"));
153+
return Path.Combine(RepoRootDirectory, "out", "bin", Configuration,
154+
"EmbeddingConsumer", lane, framework);
155+
}
156+
157+
private static void AssertConsumerRuns(string output)
158+
{
159+
string executable = Path.Combine(output, "EmbeddingConsumer.exe");
160+
ProcessStartInfo start = new()
161+
{
162+
FileName = GetCurrentFrameworkTarget() == "net472" ? executable : "dotnet",
163+
Arguments = GetCurrentFrameworkTarget() == "net472" ? string.Empty :
164+
"\"" + Path.Combine(output, "EmbeddingConsumer.dll") + "\"",
165+
WorkingDirectory = output,
166+
UseShellExecute = false,
167+
RedirectStandardOutput = true,
168+
RedirectStandardError = true,
169+
};
170+
using Process process = Process.Start(start)!;
171+
Task<string> stdoutTask = process.StandardOutput.ReadToEndAsync();
172+
Task<string> stderrTask = process.StandardError.ReadToEndAsync();
173+
if (!process.WaitForExit(60000))
174+
{
175+
process.Kill();
176+
Assert.Fail("Consumer did not exit within 60 seconds.");
177+
}
178+
string stdout = stdoutTask.GetAwaiter().GetResult();
179+
string stderr = stderrTask.GetAwaiter().GetResult();
180+
Assert.True(process.ExitCode == 0, stdout + stderr);
181+
Assert.Equal(string.Empty, stderr);
182+
Assert.Contains("ESM=embedded ESM works", stdout);
183+
Assert.Contains("BITS=64", stdout);
184+
string? nodeVersion = null;
185+
NodejsEmbeddingTests.RunInNodejsEnvironment(() =>
186+
nodeVersion = (string)JSValue.Global["process"]["versions"]["node"]);
187+
Assert.Contains("NODE=" + nodeVersion, stdout);
188+
}
189+
}
190+
#endif
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
!*.csproj

0 commit comments

Comments
 (0)