Repository navigation
Description
Background and motivation
[JSExport] generates wrappers that marshal arguments and invoke managed methods from JavaScript. Existing generated registration identifies wrappers and its assembly registration entry point by name, requiring reflection to locate them.
Propose a generator-facing assembly provider for export discovery and lazy binding, plus a BindManagedFunction overload accepting the marshaling wrapper as a managed function pointer. Generate one provider class per assembly: its string catalog initializes ordinary JS export objects, and a string-ID dispatcher binds each method only on its first invocation. No generated module initializer or per-method provider type is required.
These APIs are for the JavaScript interop source generator, not handwritten application code. They must be public because generated code lives in application assemblies. The user-facing programming model remains [JSExport] and JavaScript's getAssemblyExports().
Approved precedents: #70133 introduced editor-hidden generator-facing JS interop infrastructure; #123706 extended the marshaling APIs while distinguishing them from handwritten user code.
API Proposal
using System;
using System.ComponentModel;
using System.Diagnostics;
using System.Runtime.Versioning;
namespace System.Runtime.InteropServices.JavaScript;
+[SupportedOSPlatform("browser")]
+[EditorBrowsable(EditorBrowsableState.Never)]
+public abstract class JSExportProvider
+{
+ protected JSExportProvider();
+
+ [DebuggerNonUserCode]
+ public abstract string[] GetExportNames();
+
+ [DebuggerNonUserCode]
+ public abstract void Bind(string methodId);
+}
// Existing infrastructure type; only the proposed overload is shown.
[SupportedOSPlatform("browser")]
[CLSCompliant(false)]
[EditorBrowsable(EditorBrowsableState.Never)]
public sealed partial class JSFunctionBinding
{
+ [EditorBrowsable(EditorBrowsableState.Never)]
+ [DebuggerNonUserCode]
+ public static unsafe JSFunctionBinding BindManagedFunction(
+ string fullyQualifiedName,
+ int signatureHash,
+ ReadOnlySpan<JSMarshalerType> signatures,
+ delegate*<JSMarshalerArgument*, void> callback);
}GetExportNames()returns the assembly's fully qualified export names, including signature hashes, in generated catalog order. It does not construct marshaling signatures or bind methods.Bind(string methodId)binds one export for the current context. Its ID is the invariant decimal catalog index, e.g."0"or"1", not the signature hash. IDs are local to the generated assembly build and are not stable across builds.BindManagedFunctionreceives the generated wrapper as a managed function pointer, not an unmanaged entry point or a pointer directly to the user's method. Its other parameters retain the meaning of the existing three-argument overload.- The existing overload and legacy assembly-registration fallback remain for older generated binaries and wrappers that cannot be referenced directly.
- This replaces the earlier
RegisterAssemblyExports(string, Action)proposal.
Prototype: #136924, at a3e3c1d.
API Usage
Application code is unchanged:
using System.Runtime.InteropServices.JavaScript;
namespace Example;
public static partial class Exports
{
[JSExport]
public static int Add(int left, int right) => left + right;
[JSExport]
public static string Echo(string value) => value;
}For an assembly named ExampleApp, the generated provider has this shape (qualification shortened; existing generated marshaling wrapper bodies omitted):
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.InteropServices.JavaScript;
[assembly: TypeMap<JSExportProvider>(
"ExampleApp", typeof(__GeneratedJSExportProvider))]
namespace System.Runtime.InteropServices.JavaScript
{
[CompilerGenerated]
file sealed class __GeneratedJSExportProvider : JSExportProvider
{
public __GeneratedJSExportProvider() { }
[DynamicDependency(
DynamicallyAccessedMemberTypes.PublicParameterlessConstructor,
typeof(__GeneratedJSExportProvider))]
[DebuggerNonUserCode]
public override string[] GetExportNames()
{
return [
"[ExampleApp]Example.Exports:Add#1568108894",
"[ExampleApp]Example.Exports:Echo#304094707"
];
}
[DebuggerNonUserCode]
public override void Bind(string methodId)
{
switch (methodId)
{
case "0":
unsafe
{
JSFunctionBinding.BindManagedFunction(
"[ExampleApp]Example.Exports:Add", 1568108894,
[JSMarshalerType.Int32, JSMarshalerType.Int32, JSMarshalerType.Int32],
&global::Example.Exports.__Wrapper_Add_1568108894);
}
return;
case "1":
unsafe
{
JSFunctionBinding.BindManagedFunction(
"[ExampleApp]Example.Exports:Echo", 304094707,
[JSMarshalerType.String, JSMarshalerType.String],
&global::Example.Exports.__Wrapper_Echo_304094707);
}
return;
default:
throw new global::System.ArgumentOutOfRangeException(
nameof(methodId), methodId, null);
}
}
}
}Each additional export adds a catalog string and a switch case, not another provider class or type-map entry. The existing wrapper still unmarshals arguments, calls the user's method, marshals the result, and captures exceptions in the interop argument buffer.
The runtime uses supported TryGetValue lookup by assembly name, activates one provider for discovery, and passes its instance Bind delegate through the existing managed-delegate bridge. Type-map enumeration is deliberately unsupported on CoreCLR; the explicit catalog avoids it. The constructor is preserved through GetExportNames; reflection-fallback wrapper dependencies remain on Bind. Consumers receive TypeMapAssemblyTarget<JSExportProvider> entries for referenced provider assemblies.
const asm = await getAssemblyExports("ExampleApp");
// Provider activated and JS objects created; no method bound yet.
const add = asm.Example.Exports.Add; // Still no binding.
const first = add(17, 25); // Bind("0"), then invoke: 42.
const second = add(19, 23); // Reuse cached binding.
const text = asm.Example.Exports.Echo("hello"); // Bind("1"), then invoke.
asm.Example.Exports["Add.1568108894"] === add; // trueOrdinary JS objects support enumeration and stable function identity without a JS Proxy. Hash-qualified and plain-name aliases share a deferred function; the first overload in catalog order supplies the plain-name alias. Synchronous calls remain synchronous, async exports retain their behavior, and unused methods are never bound.
Browser builds configure the type-map discovery root because JS can request exports before the browser host establishes the managed entry assembly. The prototype also preserves the native BindAssemblyExports bootstrap entry point for trimming.
Alternative Designs
- Module-initializer callback registration ([WASM] Bind JSExports by function pointer #134923): the original
RegisterAssemblyExports(string, Action)proposal. Type-map discovery removes that registration mechanism and explicitRunModuleConstructor. - Per-assembly eager provider ([WASM] Prototype per-assembly type-map providers for JSExports #136858): one provider binds all exports together. The current proposal keeps one provider but defers individual signature/marshaler binding.
- Per-method providers plus an assembly catalog ([WASM] Prototype first-call JSExport binding with per-method providers #136922): also supports first-call binding, but adds a provider type and map entries per method plus a separate catalog class.
- Dispatch by full method name/hash instead of ordinal ID: possible, but repeats longer keys in the dispatcher. The current prototype uses compact build-local index strings.
- Keep reflection-based wrapper lookup, or pass a delegate per wrapper: the managed pointer expresses a direct reference using the existing marshaling-buffer signature without a delegate object for every export. The assembly binder remains a shared
Action<string>. - Make the APIs internal: application assemblies could not use them from generated code.
Risks and validation
- The pointer API is unsafe and relies on matching the wrapper and marshaling signature. Provider activation still uses
Activator.CreateInstance; this is not a claim that all reflection is removed. - New generated binaries require a runtime exposing these APIs. Old generated binaries retain the legacy path; previous experimental prototype API shapes are not a compatibility commitment.
- Inaccessible containing types can prevent direct wrapper references; the prototype retains the reflection path and diagnostic
SYSLIB1076. - Discovery still constructs the export-name/object tree, and stable functions retain a JS forwarding call. Size, startup, allocations, and throughput have not been benchmarked.
- Local CoreCLR/browser validation: 43 generator cases passed; 5 browser cases passed (Debug/Release trimmed and Debug untrimmed provider apps, plus Debug/Release unchanged .NET 10-generated binaries); full interop suite: 511 total, 509 passed, zero failed, 2 existing skips. TypeScript lint/bundling and reference-source generation passed.
- Counting tests verify one provider activation at discovery, no binding during discovery/property read, one first-call binding even when user code throws, no unused-method binding, stable aliases, and cached subsequent calls. Both bound and never-bound captured-export disposal cases executed.
- The prototype is CoreCLR-first. Mono remains eager and retains its untrimmed type-map limitation; new Mono and NativeAOT execution have not been validated. This is not an approved API submission.
Usage in dotnet/runtime
- The JSExport source generator emits the provider, catalog, dispatch cases, wrapper dependencies, and referenced-assembly targets.
- The JS interop managed host discovers providers and supplies the instance binder; its CoreCLR JS runtime creates and caches deferred functions.
- Generator tests and browser test fixtures exercise generated and handwritten providers, JS-only referenced libraries, overloads, synchronous/async returns, runtime isolation, trimming, and legacy binaries. No application-source migration is required.
Iteration history
- Original callback/function-pointer prototype: [WASM] Bind JSExports by function pointer #134923, commit
d0dbeaf1cc821b95c3fbb77ae274f6400874e483. - Per-assembly eager provider: [WASM] Prototype per-assembly type-map providers for JSExports #136858, commit
84a41ea4d53bd3ead4f1efe467d8260e1a338ec7. - Per-method lazy providers with separate catalog: [WASM] Prototype first-call JSExport binding with per-method providers #136922, commit
c3e784ab82ef72ee1c687e2d0957fc83a975473c. - Current proposal: single-class per-assembly catalog and lazy string-ID dispatcher, [WASM] Bind CoreCLR JSExports lazily using assembly type-map providers #136924, commit
a3e3c1d10c75086425744ba17b035e651577a0ca.
Note
This API proposal was updated with GitHub Copilot.
Metadata
Metadata
Assignees
Labels
Type
Projects
- StatusShow more project fieldsNo status
Activity
dotnet-policy-service commentedon Oct 26, 2026
Tagging subscribers to this area: @dotnet/interop-contrib
See info in area-owners.md if you want to be subscribed.
jkoritzinsky commentedon Oct 26, 2026
For the
feature/NativeAOT-LLVMexperiment in runtimelab, they adjusted theJSExportgenerator to emitUnmanagedCallersOnlyhelpers instead of a helper with a managed signature. Why did we decide to go with a managed signature? Is a managed signature here future-proof for when we add WASM support for NativeAOT (I think so, but I want to make sure we don't back ourselves into a corner here)?pavelsavara commentedon Oct 27, 2026
I think NAOT is compatible with this proposal.
UCO could be possibly better optimized by LLVM/NAOT compiler, than R2R thunks.
But for shipping JSExport without native linker (wasm-tools workload), we need existing native runtime entrypoint, which is this proposal.
UCO will also need to create WASM exports that JS will call. And it will be more code per export. Also more MSbuild logic to resolve the index of the exported function in WASM function table.
We could eventually add UCO option later, if we proof the performance is worth it. Right now, I think it's not worth it. For Mono it was reflection dispatch so far, this will make it much faster already. We only got few people complaining about perf. Calling this interop inside tight loop is probably bad usage pattern anyway.
jkoritzinsky commentedon Oct 28, 2026
Sounds good to me.
One more question: the ModuleInitializer (and manually having to run it via reflection APIs in the prototype) is quite hacky. Is there some way we could implement this such that we didn't need to do that? Maybe something with the type map to map exported name to a type with the callback and have a lazy lookup in JS where we only try to look up the member at invoke time based on the invoked name via a Proxy object with a callback?
pavelsavara commentedon Oct 29, 2026
Agreed it's ugly. It has 2 functions
getAssemblyExports()is the first thing that uses the assembly, and so the module was not initialized yet.This would do it, but we would have to still instantiate it via reflection.
We could possibly do it also with just naming convention - without type map, mono worked this way in the past.
jkoritzinsky commentedon Oct 30, 2026
I'd prefer something like the typemap as that is trim-safe reflection by design and is less ugly to me than the manual call to
RunModuleInitializerafter theAssembly.Loadcall.I'd personally structure the type map as having one entry per JSExport so you could look up the specific JSExport callback lazily per-export instead of per-assembly:
And then the JS logic with
getAssemblyExportswould useProxyobjects or something of the like to delay the resolution of the export until the getter for the actual method. Something like the following:I think a design with a per-assembly lookup with the type map would work as well, just would be a little uglier of a design than per-export.
pavelsavara commentedon Nov 2, 2026
I'm prototyping it.
I have 2 objections to per-export.
With per-assembly, we don't need to use proxy here. We are already binding it lazily today, on a first call. Until then, JS only knows the method handle.
pavelsavara commentedon Nov 2, 2026
pavelsavara commentedon Nov 3, 2026
I implemented another alternative: per-method type-map providers with first-call binding in #136922.
This is separate from the per-assembly prototype in #136858. It splits name discovery from signature/marshaler binding:
getAssemblyExports()creates ordinary JS objects containing deferred functions, but a method's provider is activated and bound only on its first invocation, not property access. No JSProxyis needed.API proposal
The function-pointer overload remains unchanged. Compared with the per-assembly alternative,
JSExportProvider.Register()becomes a per-methodBind(), and a separate name-only assembly catalog supports discovery:Why the catalog?
CoreCLR's lazy type maps deliberately do not support enumeration:
GetEnumerator,Keys,Values, andCountthrow to protect trimmer invariants. The runtime therefore looks up one catalog by assembly name and obtains its explicit name list. It then uses supported type-map lookups rather than enumerating the maps or scanning potentially trimmed custom attributes.Only the catalog is activated during discovery. The per-method providers remain uninstantiated until their functions are called.
Generated code
For
[JSExport] int Add(int left, int right)inExample.Exports, representative generated code is below. Qualification is shortened; the existing marshaling wrapper body is omitted.Each additional export gets another provider and catalog entry. A plain-name map entry identifies the default overload; canonical entries retain the signature hash. Consumers get
TypeMapAssemblyTargetentries for both catalog and provider groups.JS behavior
The shared synchronous binder uses the existing managed-delegate bridge; no new native export is required. Plain-name/hash-qualified aliases share the same stable function object. An unused method is never bound. Legacy assemblies retain their existing eager registration fallback.
The type-map entry-assembly configuration and native bootstrap trimming root from the per-assembly prototype remain necessary. There is still no generated module initializer or explicit
RunModuleConstructorcall.Validation and trade-offs
Local CoreCLR validation: 43 generator cases passed; 5 browser provider/legacy compatibility cases passed; the full interop suite had 511 total, 509 passed, zero failed, 2 existing skips. Both captured-export disposal cases also passed a final targeted rerun.
Counting fixture providers verify zero method-provider activations at discovery/property read, exactly one activation/binding on first invocation, cached binding after a first-call user exception, and no activation of an unused provider. Coverage includes overload aliases, synchronous and async returns, runtime isolation, trimming, JS-only libraries, and .NET 10 generated binaries.
This adds per-method type metadata plus one catalog per assembly. Stable function identity also retains a JS forwarding function on subsequent calls. Size and performance have not been measured. Deferred binding is currently CoreCLR-only; Mono remains eager, its untrimmed type-map limitation remains, and NativeAOT execution is unvalidated. This is an API prototype for comparison, not an approved API submission.
Note
This comment was drafted with GitHub Copilot.
pavelsavara commentedon Nov 3, 2026
I implemented another alternative: one type-map provider class per assembly, with a string catalog and first-call binding in #136924.
This combines the single-provider structure of #136858 with lazy binding from #136922. There is no separate catalog class and no per-method provider class. One provider instance supplies the names at discovery and dispatches binding by method ID on first invocation.
API proposal
Fold
GetExportNames()intoJSExportProviderand changeBind()toBind(string methodId). RemoveJSExportCatalog. The proposed function-pointer overload remains unchanged:GetExportNames()returns fully qualified names including signature hashes.methodIdis the invariant decimal catalog index, e.g."0"or"1", not the signature hash. IDs are internal to that generated assembly build and are not stable across builds.Generated code
For
[JSExport] int Add(int left, int right)and[JSExport] string Echo(string value)inExample.Exports, the generated provider has this shape. Qualification is shortened; the existing marshaling wrapper bodies are omitted.Each additional export adds a catalog string and a switch case, not another provider type or type-map entry. The runtime looks up the provider by assembly name using
TryGetValue, activates it once for discovery, and passes its instanceBinddelegate through the existing managed-delegate bridge. No type-map enumeration is needed. Referenced assemblies receive targets for the single provider map group.The constructor is explicitly preserved through
GetExportNames(). For wrappers that need the reflection fallback, their generatedDynamicDependencyattributes remain onBind.JS behavior
Discovery still creates ordinary JS objects and stable deferred functions, without a JS
Proxy. Plain-name and hash-qualified aliases share the same function; the first overload in catalog order supplies the plain-name alias. Synchronous calls remain synchronous, async exports retain their behavior, and unused methods are never bound.The browser discovery-root configuration and native bootstrap trimming root from the earlier prototypes remain necessary. There is no generated module initializer or explicit
RunModuleConstructor. Legacy generated assemblies retain their existing registration fallback.Validation and trade-offs
Local CoreCLR validation: 43 generator cases passed; 5 browser provider/legacy compatibility cases passed; full interop suite: 511 total, 509 passed, zero failed, 2 existing skips. Both bound and never-bound captured-export disposal cases executed. TypeScript lint/bundling and reference-source generation passed.
The counting fixture asserts
constructor -> discovery -> property read -> bind -> first invocation -> repeated invocation: one provider activation during discovery, no binding during discovery/property read, exactly one binding even when the first user invocation throws, and no binding of an unused method. Coverage includes trimming, overload aliases, synchronous/async returns, runtime isolation, JS-only referenced libraries, and unchanged .NET 10-generated binaries.Compared with the per-method prototype, this removes per-method provider metadata and the separate catalog type, but introduces a shared string-ID dispatcher. Discovery still builds the name/object tree; stable function identity still retains a JS forwarding function. Size and performance have not been measured. Deferred binding remains CoreCLR-only; Mono stays eager, its untrimmed type-map limitation remains, and NativeAOT execution is unvalidated. This is an API prototype for comparison, not an approved API submission.
Delta from the per-method prototype.
Note
This comment was drafted with GitHub Copilot.
bartonjs commentedon Nov 3, 2026
Video
string[]toReadOnlySpan<string>is more aligned with our current API designs (preventing caller modification of a reused array)