Skip to content

[API Proposal]: Generator-facing JSExport registration and function-pointer binding #136464

Description

@pavelsavara

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.
  • BindManagedFunction receives 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; // true

Ordinary 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 explicit RunModuleConstructor.
  • 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

Note

This API proposal was updated with GitHub Copilot.

Activity

  1. added
    api-suggestion
    on Oct 26, 2026
  2. added
    untriaged
    on Oct 26, 2026
  3. self-assigned this
    on Oct 26, 2026
  4. added
    os-browser
    on Oct 26, 2026
  5. dotnet-policy-service commented on Oct 26, 2026

    @dotnet-policy-service
    Contributor

    Tagging subscribers to this area: @dotnet/interop-contrib
    See info in area-owners.md if you want to be subscribed.

  6. added this to the 12.0.0 milestone on Oct 26, 2026
  7. added
    api-ready-for-review
    and removed
    untriaged
    on Oct 26, 2026
  8. jkoritzinsky commented on Oct 26, 2026

    @jkoritzinsky
    Member

    For the feature/NativeAOT-LLVM experiment in runtimelab, they adjusted the JSExport generator to emit UnmanagedCallersOnly helpers 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)?

  9. pavelsavara commented on Oct 27, 2026

    @pavelsavara
    MemberAuthor

    Is a managed signature here future-proof for when we add WASM support for NativeAOT

    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.

  10. jkoritzinsky commented on Oct 28, 2026

    @jkoritzinsky
    Member

    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?

  11. pavelsavara commented on Oct 29, 2026

    @pavelsavara
    MemberAuthor

    the ModuleInitializer is quite hacky.

    Agreed it's ugly. It has 2 functions

    • to protect the whole thing from IL trimming. This is not perfect, because if no other C# code uses something from the assembly, the assembly would get trimmed completely.
    • call it directly via reflection, in the case JS getAssemblyExports() is the first thing that uses the assembly, and so the module was not initialized yet.

    type map

    [assembly: TypeMap<JSExportProvider>(
        "ExampleApp", typeof(ExampleAppExports))]
    
    internal sealed class ExampleAppExports : JSExportProvider
    {
        public ExampleAppExports() { }
    
        public override unsafe void Register()
        {
            JSFunctionBinding.BindManagedFunction(
                "[ExampleApp]Example.Exports:Add",
                signatureHash,
                signatures,
                &Example.Exports.__Wrapper_Add);
        }
    }

    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.

  12. jkoritzinsky commented on Oct 30, 2026

    @jkoritzinsky
    Member

    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 RunModuleInitializer after the Assembly.Load call.

    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:

    // User code
    using System.Runtime.InteropServices.JavaScript;
    
    namespace Example;
    
    public static partial class Exports
    {
        [JSExport]
        public static int Add(int left, int right) => left + right;
    }
    // Generated registration
    
    [assembly: TypeMap<JSExportProvider>(
        "[ExampleApp]Example.Exports:Add", typeof(Export))]
    
    file sealed class Export : JSExportProvider
    {
        public ExampleAppExports() { }
    
        // Something like this that would do the signature binding now and give back enough info to create the callback lazily.
        public override unsafe JSFunctionBinding Binding =>  field ??= JSFunctionBinding.BindManagedFunction(
                "[ExampleApp]Example.Exports:Add",
                signatureHash,
                signatures,
                &Example.Exports.__Wrapper_Add);
    }

    And then the JS logic with getAssemblyExports would use Proxy objects or something of the like to delay the resolution of the export until the getter for the actual method. Something like the following:

    import { dotnet } from './_framework/dotnet.js'
    
    const { getAssemblyExports, getConfig } = await dotnet
      .withApplicationArguments("start")
      .create();
    
    const config = getConfig();
    const asmExports = await getAssemblyExports(config.mainAssemblyName); // This still runs the Assembly.Load and whatever else needs to be async.
    
    const exports = asmExports.Example.Exports; // Proxy object for Example.Exports class
    
    const add = exports.Add; // Resolves the type map entry and returns a callable proxy/callback object to the export.

    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.

  13. pavelsavara commented on Nov 2, 2026

    @pavelsavara
    MemberAuthor

    I'd prefer something like the typemap

    I'm prototyping it.

    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.

    I have 2 objections to per-export.

    • it will be larger managed code and download.
    • JS side doesn't know the method signature (hash part of the name) before the registration. There could be 2 JSExport on methods with same name but different signature. Current solution maps them to name containing the signature hash. I realized this is edge case and we could probably drop it.
         const exports = asmExports.Example.Exports; // Proxy object for Example.Exports class
    

    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.

  14. pavelsavara commented on Nov 2, 2026

    @pavelsavara
    Author
  15. pavelsavara commented on Nov 3, 2026

    @pavelsavara
    MemberAuthor

    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 JS Proxy is needed.

    API proposal

    The function-pointer overload remains unchanged. Compared with the per-assembly alternative, JSExportProvider.Register() becomes a per-method Bind(), and a separate name-only assembly catalog supports discovery:

    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 JSExportCatalog
    {
        protected JSExportCatalog();
    
        [DebuggerNonUserCode]
        public abstract string[] GetExportNames();
    }
    
    [SupportedOSPlatform("browser")]
    [EditorBrowsable(EditorBrowsableState.Never)]
    public abstract class JSExportProvider
    {
        protected JSExportProvider();
    
        [DebuggerNonUserCode]
        public abstract void Bind();
    }
    
    // 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);
    }

    Why the catalog?

    CoreCLR's lazy type maps deliberately do not support enumeration: GetEnumerator, Keys, Values, and Count throw 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) in Example.Exports, representative generated code is below. Qualification is shortened; the existing marshaling wrapper body is omitted.

    using System.Diagnostics;
    using System.Diagnostics.CodeAnalysis;
    using System.Runtime.CompilerServices;
    using System.Runtime.InteropServices;
    using System.Runtime.InteropServices.JavaScript;
    
    [assembly: TypeMap<JSExportCatalog>(
        "ExampleApp", typeof(__GeneratedJSExportCatalog))]
    [assembly: TypeMap<JSExportProvider>(
        "[ExampleApp]Example.Exports:Add#1568108894",
        typeof(__GeneratedJSExportProvider_0))]
    [assembly: TypeMap<JSExportProvider>(
        "[ExampleApp]Example.Exports:Add",
        typeof(__GeneratedJSExportProvider_0))]
    
    namespace System.Runtime.InteropServices.JavaScript
    {
        [CompilerGenerated]
        file sealed class __GeneratedJSExportCatalog : JSExportCatalog
        {
            public __GeneratedJSExportCatalog() { }
    
            [DynamicDependency(
                DynamicallyAccessedMemberTypes.PublicParameterlessConstructor,
                typeof(__GeneratedJSExportCatalog))]
            [DebuggerNonUserCode]
            public override string[] GetExportNames()
            {
                return ["[ExampleApp]Example.Exports:Add#1568108894"];
            }
        }
    
        [CompilerGenerated]
        file sealed class __GeneratedJSExportProvider_0 : JSExportProvider
        {
            public __GeneratedJSExportProvider_0() { }
    
            [DynamicDependency(
                DynamicallyAccessedMemberTypes.PublicParameterlessConstructor,
                typeof(__GeneratedJSExportProvider_0))]
            [DebuggerNonUserCode]
            public override void Bind()
            {
                unsafe
                {
                    JSFunctionBinding.BindManagedFunction(
                        "[ExampleApp]Example.Exports:Add",
                        1568108894,
                        [
                            JSMarshalerType.Int32,
                            JSMarshalerType.Int32,
                            JSMarshalerType.Int32
                        ],
                        &global::Example.Exports.__Wrapper_Add_1568108894);
                }
            }
        }
    }

    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 TypeMapAssemblyTarget entries for both catalog and provider groups.

    JS behavior

    const asm = await getAssemblyExports("ExampleApp");
    const add = asm.Example.Exports.Add; // No method-provider activation or binding.
    
    const first = add(17, 25);          // Bind once, then invoke; returns 42 synchronously.
    const second = add(19, 23);         // Reuse the cached binding.
    
    asm.Example.Exports["Add.1568108894"] === add; // true

    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 RunModuleConstructor call.

    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.

  16. pavelsavara commented on Nov 3, 2026

    @pavelsavara
    MemberAuthor

    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() into JSExportProvider and change Bind() to Bind(string methodId). Remove JSExportCatalog. The proposed function-pointer overload remains unchanged:

    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 fully qualified names including signature hashes. methodId is 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) in Example.Exports, the generated provider has this shape. Qualification is shortened; the existing marshaling wrapper bodies are 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 type or type-map entry. The runtime looks up the provider by assembly name using TryGetValue, activates it once for discovery, and passes its instance Bind delegate 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 generated DynamicDependency attributes remain on Bind.

    JS behavior

    const asm = await getAssemblyExports("ExampleApp");
    // One assembly-provider instance exists; no export has been bound.
    
    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 the cached binding.
    const text = asm.Example.Exports.Echo("hello"); // Bind("1"), then invoke.
    
    asm.Example.Exports["Add.1568108894"] === add; // true

    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.

  17. bartonjs commented on Nov 3, 2026

    @bartonjs
    Member

    Video

    • Even though it's only accessible via infrastructure code, changing string[] to ReadOnlySpan<string> is more aligned with our current API designs (preventing caller modification of a reused array)
    namespace System.Runtime.InteropServices.JavaScript;
    
    [SupportedOSPlatform("browser")]
    [EditorBrowsable(EditorBrowsableState.Never)]
    public abstract class JSExportProvider
    {
        protected JSExportProvider();
    
        [DebuggerNonUserCode]
        public abstract ReadOnlySpan<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);
    }
  18. added
    api-approved
    and removed
    api-suggestion
    api-ready-for-review
    on Nov 3, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

api-approvedarea-System.Runtime.InteropServices.JavaScriptos-browser

Type

No type

Projects

  • Status
    No status

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions