Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 14 additions & 1 deletion .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ on: [push, pull_request]

env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
NUGET_API_KEY: ${{ secrets.NUGET_API_KEY }}
DOCS_PATH: ${{ secrets.DOCS_PATH }}
DOCS_BRANCH: ${{ secrets.DOCS_BRANCH }}

Expand Down Expand Up @@ -61,6 +60,9 @@ jobs:

windows:
runs-on: windows-latest
permissions:
contents: write # create the GitHub release
id-token: write # request the OIDC token for NuGet trusted publishing

steps:
- uses: actions/checkout@v5
Expand All @@ -71,7 +73,18 @@ jobs:
dotnet-version: |
10.0.x

# Exchanges the GitHub OIDC token for a short-lived (1 hour) NuGet API key.
# Requires a trusted publishing policy on nuget.org for this repository and workflow file.
- name: NuGet login
id: nuget_login
if: github.event_name == 'push' && (github.ref == 'refs/heads/main' || github.ref == 'refs/heads/devel')
uses: NuGet/login@v1
with:
user: ${{ secrets.NUGET_USER }}

- name: Build
env:
NUGET_API_KEY: ${{ steps.nuget_login.outputs.NUGET_API_KEY }}
run: |
if ($env:GITHUB_REF -eq "refs/heads/main") {
.\build.ps1 -Target Publish -AngleSharpVersion 1.5.0
Expand Down
3 changes: 3 additions & 0 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,9 @@ AngleSharp.Wasm extends AngleSharp with WebAssembly execution and a DOM/JavaScri
- The solution is `src/AngleSharp.Wasm.sln`.
- The library and test projects target `net8.0` and `net10.0`.
- The library references AngleSharp 1.x and Wasmtime 44.0.0.
- The library sets `IsAotCompatible`, so a trim or AOT analyzer warning breaks the build. Avoid
reflection over runtime types; the analyzers only see this assembly, so publishing a small
`PublishAot` console app against it is the end-to-end check.
- The default runtime is `WasmtimeWasmRuntime`, registered through `Configuration.WithWasm()`.
- `global.json`, when present, controls the SDK version used by the build wrapper.

Expand Down
8 changes: 8 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,11 @@
# 1.1.1

Released on Thursday, November 12 2026.

- Fixed host import arguments arriving as `double` instead of their WebAssembly types (#18) @michaelthyregod
- Added trimming and Native AOT compatibility (`IsAotCompatible`) for the .NET 8 and .NET 10 targets (#17) @michaelthyregod
- Added `WasmRuntimeOptions` to limit memory size, table elements and fuel per call (#19) @michaelthyregod

# 1.1.0

Released on Friday, August 21 2026.
Expand Down
1 change: 1 addition & 0 deletions CONTRIBUTORS.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ Thanks :heart: to all who contributed to AngleSharp.Wasm via issues, pull reques
AngleSharp.Wasm contains code written by (in order of first pull request / commit):

* [Florian Rappl](https://github.com/FlorianRappl)
* [Michael Thyregod](https://github.com/michaelthyregod)

Without these awesome people AngleSharp.Wasm could not exist. Thanks to everyone for your contributions! :beers:

Expand Down
2 changes: 1 addition & 1 deletion build/Build.cs
Original file line number Diff line number Diff line change
Expand Up @@ -197,9 +197,9 @@ protected override void OnBuildInitialized()
.DependsOn(RunUnitTests)
.Executes(() =>
{
// In CI this is the short-lived key issued by NuGet trusted publishing (NuGet/login).
var apiKey = Environment.GetEnvironmentVariable("NUGET_API_KEY");


if (apiKey.IsNullOrEmpty())
{
throw new BuildAbortedException("Could not resolve the NuGet API key.");
Expand Down
24 changes: 24 additions & 0 deletions docs/tutorials/01-API.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,30 @@ Registers the default Wasmtime-backed runtime factory.
var config = Configuration.Default.WithWasm();
```

### `WithWasm(WasmRuntimeOptions)`

Registers the default Wasmtime-backed runtime factory with resource limits. Every limit is off by
default; set them when pages with untrusted WebAssembly are loaded.

```cs
var config = Configuration.Default.WithWasm(new WasmRuntimeOptions
{
MaximumMemorySize = 64 * 1024 * 1024, // bytes per linear memory
MaximumTableElements = 10_000, // elements per table
Fuel = 100_000_000, // per call from the host and per instantiation
});
```

- `MaximumMemorySize` and `MaximumTableElements` make instantiation fail when a memory or table
starts larger, and make growing beyond them fail.
- `Fuel` is roughly one unit per executed WebAssembly instruction. A call that spends it traps,
which the bridge reports as `RuntimeError`; the next call gets a full budget again. Calls that
WebAssembly makes back into its own instance through a host import share the outer call's budget.
Fuel metering slows execution down, so it is only enabled when `Fuel` is set.

The same options can be passed to `new WasmtimeWasmRuntime(options)` and
`new WasmtimeWasmRuntimeFactory(options)`.

### `WithWasm(Func<IBrowsingContext, IWasmRuntimeFactory>)`

Registers a custom runtime factory creator.
Expand Down
6 changes: 6 additions & 0 deletions docs/tutorials/03-Questions.md
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,12 @@ Current numeric value kinds are supported:
- `f32`
- `f64`

## How do I limit what a module can consume?

By default a module can grow its memory and tables up to the WebAssembly maximum and run for as
long as it likes. Pass `WasmRuntimeOptions` to `WithWasm(...)` to cap memory size, table
elements and fuel (executed instructions per call); see the API page.

## What are known limitations today?

- No Promise-based `compile` / `instantiate` bridge methods.
Expand Down
2 changes: 1 addition & 1 deletion src/AngleSharp.Wasm.Docs/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@anglesharp/wasm",
"version": "1.1.0",
"version": "1.1.1",
"preview": true,
"description": "The doclet for the AngleSharp.Wasm documentation.",
"keywords": [
Expand Down
184 changes: 184 additions & 0 deletions src/AngleSharp.Wasm.Tests/WasmtimeRuntimeLimitsTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,184 @@
namespace AngleSharp.Wasm.Tests;

using System;
using System.Threading.Tasks;
using AngleSharp.Wasm.Dom;
using NUnit.Framework;

[TestFixture]
public sealed class WasmtimeRuntimeLimitsTests
{
// (module
// (func (export "spin") (loop br 0))
// (func (export "answer") (result i32) i32.const 42))
private static readonly byte[] SpinModule =
{
0x00, 0x61, 0x73, 0x6D,
0x01, 0x00, 0x00, 0x00,
0x01, 0x08, 0x02, 0x60, 0x00, 0x00, 0x60, 0x00, 0x01, 0x7F,
0x03, 0x03, 0x02, 0x00, 0x01,
0x07, 0x11, 0x02, 0x04, 0x73, 0x70, 0x69, 0x6E, 0x00, 0x00, 0x06, 0x61, 0x6E, 0x73, 0x77, 0x65, 0x72, 0x00, 0x01,
0x0A, 0x0E, 0x02, 0x07, 0x00, 0x03, 0x40, 0x0C, 0x00, 0x0B, 0x0B, 0x04, 0x00, 0x41, 0x2A, 0x0B,
};

// (module
// (import "host" "reenter" (func $reenter))
// (func (export "spin") (loop call $reenter br 0))
// (func (export "answer") (result i32) i32.const 42))
private static readonly byte[] ReenteringSpinModule =
{
0x00, 0x61, 0x73, 0x6D,
0x01, 0x00, 0x00, 0x00,
0x01, 0x08, 0x02, 0x60, 0x00, 0x00, 0x60, 0x00, 0x01, 0x7F,
0x02, 0x10, 0x01, 0x04, 0x68, 0x6F, 0x73, 0x74, 0x07, 0x72, 0x65, 0x65, 0x6E, 0x74, 0x65, 0x72, 0x00, 0x00,
0x03, 0x03, 0x02, 0x00, 0x01,
0x07, 0x11, 0x02, 0x04, 0x73, 0x70, 0x69, 0x6E, 0x00, 0x01, 0x06, 0x61, 0x6E, 0x73, 0x77, 0x65, 0x72, 0x00, 0x02,
0x0A, 0x10, 0x02, 0x09, 0x00, 0x03, 0x40, 0x10, 0x00, 0x0C, 0x00, 0x0B, 0x0B, 0x04, 0x00, 0x41, 0x2A, 0x0B,
};

// (module (memory (export "mem") 1))
private static readonly byte[] OnePageMemoryModule =
{
0x00, 0x61, 0x73, 0x6D,
0x01, 0x00, 0x00, 0x00,
0x05, 0x03, 0x01, 0x00, 0x01,
0x07, 0x07, 0x01, 0x03, 0x6D, 0x65, 0x6D, 0x02, 0x00,
};

// (module (memory (export "mem") 3))
private static readonly byte[] ThreePageMemoryModule =
{
0x00, 0x61, 0x73, 0x6D,
0x01, 0x00, 0x00, 0x00,
0x05, 0x03, 0x01, 0x00, 0x03,
0x07, 0x07, 0x01, 0x03, 0x6D, 0x65, 0x6D, 0x02, 0x00,
};

// (module (table (export "tab") 1 funcref))
private static readonly byte[] OneElementTableModule =
{
0x00, 0x61, 0x73, 0x6D,
0x01, 0x00, 0x00, 0x00,
0x04, 0x04, 0x01, 0x70, 0x00, 0x01,
0x07, 0x07, 0x01, 0x03, 0x74, 0x61, 0x62, 0x01, 0x00,
};

private const long PageSize = 65536;

[Test]
public async Task FuelStopsAnEndlessLoopAndIsRefilledForTheNextCall()
{
using var runtime = new WasmtimeWasmRuntime(new WasmRuntimeOptions { Fuel = 10_000 });
using var module = await runtime.CompileAsync(SpinModule).ConfigureAwait(false);
using var instance = await runtime.InstantiateAsync(module).ConfigureAwait(false);

Assert.That(async () => await instance.InvokeAsync("spin").ConfigureAwait(false), Throws.Exception.With.Message.Contains("fuel"));
Assert.That(async () => await instance.InvokeAsync("spin").ConfigureAwait(false), Throws.Exception.With.Message.Contains("fuel"));
Assert.That(await instance.InvokeAsync("answer").ConfigureAwait(false), Is.EqualTo(42));
}

[Test]
public async Task FuelAppliesToExportedFunctionsObtainedFromTheInstance()
{
using var runtime = new WasmtimeWasmRuntime(new WasmRuntimeOptions { Fuel = 10_000 });
using var module = await runtime.CompileAsync(SpinModule).ConfigureAwait(false);
using var instance = await runtime.InstantiateAsync(module).ConfigureAwait(false);
var functions = (IWasmFunctionProvider)instance;

Assert.That(() => functions.GetFunction("spin")!.Invoke(), Throws.Exception.With.Message.Contains("fuel"));
Assert.That(functions.GetFunction("answer")!.Invoke(), Is.EqualTo(42));
}

[Test]
public async Task ReenteringTheInstanceFromAHostImportDoesNotRefillTheFuel()
{
using var runtime = new WasmtimeWasmRuntime(new WasmRuntimeOptions { Fuel = 10_000 });
using var module = await runtime.CompileAsync(ReenteringSpinModule).ConfigureAwait(false);
IWasmInstance? self = null;
var reentries = 0;

var imports = new[]
{
new WasmImportFunction(
"host",
"reenter",
Array.Empty<WasmValueType>(),
Array.Empty<WasmValueType>(),
_ =>
{
reentries++;
return self!.InvokeAsync("answer").AsTask().GetAwaiter().GetResult();
}),
};

using var instance = await runtime.InstantiateAsync(module, imports).ConfigureAwait(false);
self = instance;

Assert.That(async () => await instance.InvokeAsync("spin").ConfigureAwait(false), Throws.Exception.With.Message.Contains("fuel"));
Assert.That(reentries, Is.GreaterThan(0));
Assert.That(await instance.InvokeAsync("answer").ConfigureAwait(false), Is.EqualTo(42));
}

[Test]
public async Task MaximumMemorySizeStopsGrowthAndLargerInitialMemory()
{
using var runtime = new WasmtimeWasmRuntime(new WasmRuntimeOptions { MaximumMemorySize = 2 * PageSize });
using var module = await runtime.CompileAsync(OnePageMemoryModule).ConfigureAwait(false);
using var instance = await runtime.InstantiateAsync(module).ConfigureAwait(false);
var memory = ((IWasmMemoryProvider)instance).GetMemory("mem")!;

Assert.That(memory.Grow(1), Is.EqualTo(1));
Assert.That(() => memory.Grow(1), Throws.Exception.With.Message.Contains("failed to grow memory"));
Assert.That(memory.Length, Is.EqualTo(2 * PageSize));

using var largerModule = await runtime.CompileAsync(ThreePageMemoryModule).ConfigureAwait(false);
Assert.That(async () => await runtime.InstantiateAsync(largerModule).ConfigureAwait(false), Throws.Exception.With.Message.Contains("exceeds memory limits"));
}

[Test]
public async Task MaximumTableElementsStopsGrowth()
{
using var runtime = new WasmtimeWasmRuntime(new WasmRuntimeOptions { MaximumTableElements = 2 });
using var module = await runtime.CompileAsync(OneElementTableModule).ConfigureAwait(false);
using var instance = await runtime.InstantiateAsync(module).ConfigureAwait(false);
var table = ((IWasmTableProvider)instance).GetTable("tab")!;

Assert.That(table.Grow(1, null), Is.EqualTo(1UL));
Assert.That(() => table.Grow(1, null), Throws.Exception.With.Message.Contains("failed to grow table"));
Assert.That(table.Length, Is.EqualTo(2UL));
}

[Test]
public void NegativeMaximumMemorySizeIsRejected()
{
Assert.That(
() => new WasmtimeWasmRuntime(new WasmRuntimeOptions { MaximumMemorySize = -1 }),
Throws.InstanceOf<ArgumentOutOfRangeException>());
}

[Test]
public async Task BridgeReportsSpentFuelAsRuntimeError()
{
var config = Configuration.Default.WithWasm(new WasmRuntimeOptions { Fuel = 10_000 });
using var context = BrowsingContext.New(config);
using var document = await context.OpenNewAsync();

var instance = WebAssembly.Instantiate(context.Current!, SpinModule).Instance;

Assert.That(() => instance.Invoke("spin"), Throws.InstanceOf<WasmJsRuntimeError>().With.Message.Contains("fuel"));
Assert.That(() => ((WasmJsExportedFunction)instance.Exports["spin"]!).Invoke(), Throws.InstanceOf<WasmJsRuntimeError>().With.Message.Contains("fuel"));
Assert.That(instance.Invoke("answer"), Is.EqualTo(42));
}

[Test]
public async Task BridgeWithoutOptionsKeepsMemoryUnlimited()
{
var config = Configuration.Default.WithWasm();
using var context = BrowsingContext.New(config);
using var document = await context.OpenNewAsync();

var memory = (WasmJsMemory)WebAssembly.Instantiate(context.Current!, OnePageMemoryModule).Instance.Exports["mem"]!;

Assert.That(memory.Grow(16), Is.EqualTo(1));
}
}
47 changes: 47 additions & 0 deletions src/AngleSharp.Wasm.Tests/WasmtimeRuntimeTests.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
namespace AngleSharp.Wasm.Tests;

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using NUnit.Framework;

Expand Down Expand Up @@ -43,6 +45,21 @@ public sealed class WasmtimeRuntimeTests
0x0A, 0x09, 0x01, 0x07, 0x00, 0x10, 0x00, 0x41, 0x01, 0x6A, 0x0B,
};

// (module
// (import "host" "echo" (func $echo (param i32 i64 f32 f64)))
// (func (export "run") (param i32 i64 f32 f64)
// local.get 0 local.get 1 local.get 2 local.get 3 call $echo))
private static readonly byte[] HostImportArgumentsModule =
{
0x00, 0x61, 0x73, 0x6D,
0x01, 0x00, 0x00, 0x00,
0x01, 0x08, 0x01, 0x60, 0x04, 0x7F, 0x7E, 0x7D, 0x7C, 0x00,
0x02, 0x0D, 0x01, 0x04, 0x68, 0x6F, 0x73, 0x74, 0x04, 0x65, 0x63, 0x68, 0x6F, 0x00, 0x00,
0x03, 0x02, 0x01, 0x00,
0x07, 0x07, 0x01, 0x03, 0x72, 0x75, 0x6E, 0x00, 0x01,
0x0A, 0x0E, 0x01, 0x0C, 0x00, 0x20, 0x00, 0x20, 0x01, 0x20, 0x02, 0x20, 0x03, 0x10, 0x00, 0x0B,
};

[Test]
public async Task CanCompileInstantiateAndInvokeExport()
{
Expand Down Expand Up @@ -97,4 +114,34 @@ public async Task CanInstantiateWithHostImport()

Assert.That(Convert.ToInt32(result), Is.EqualTo(42));
}

[Test]
public async Task HostImportReceivesArgumentsWithTheirWasmTypes()
{
using var runtime = new WasmtimeWasmRuntime();
using var module = await runtime.CompileAsync(HostImportArgumentsModule).ConfigureAwait(false);
var types = new[] { WasmValueType.Int32, WasmValueType.Int64, WasmValueType.Float32, WasmValueType.Float64 };
IReadOnlyList<object?>? received = null;

var imports = new[]
{
new WasmImportFunction(
"host",
"echo",
types,
Array.Empty<WasmValueType>(),
arguments =>
{
received = arguments;
return null;
}),
};

using var instance = await runtime.InstantiateAsync(module, imports).ConfigureAwait(false);
await instance.InvokeAsync("run", new object?[] { 7, 9007199254740993L, 1.5f, 2.25 }).ConfigureAwait(false);

Assert.That(received, Is.EqualTo(new object?[] { 7, 9007199254740993L, 1.5f, 2.25 }));
Assert.That(received!.Select(argument => argument?.GetType()),
Is.EqualTo(new[] { typeof(int), typeof(long), typeof(float), typeof(double) }));
}
}
Loading
Loading