此项目将 TypeScript 类型声明转换为 C# 表示法,并使用 C# 源代码生成器来暴露自动的 JavaScript 互操作功能。
此项目将 TypeScript 类型声明转换为 C# 表示法,并使用 C# 源代码生成器来暴露自动的 JavaScript 互操作功能。
Thank you for perusing my Blazor C# Source Generator repository. I'd really appreciate a ⭐ if you find this interesting. Blazorators provides C# source generators and generated packages for strongly typed Blazor JavaScript interop, targeting either
IJSInProcessRuntimeorIJSRuntime. The repository supports two complementary generation paths:
Blazor.SourceGenerators for opt-in services generated from an attributed interface and TypeScript declarations.Blazor.DOM and focused capability packages generated from a strict semantic model of the browser DOM.The repository provides several NuGet packages:
Core libraries
| NuGet package | NuGet version | Description |
|---|---|---|
Blazor.SourceGenerators |
Core source generator library. | |
Blazor.Serialization |
Common serialization library, required in some scenarios when using generics. |
WebAssembly libraries
| NuGet package | NuGet version | Description |
|---|---|---|
Blazor.LocalStorage.WebAssembly |
Blazor WebAssembly class library exposing DI-ready IStorageService type for the localStorage implementation (relies on IJSInProcessRuntime). |
|
Blazor.SessionStorage.WebAssembly |
Blazor WebAssembly class library exposing DI-ready IStorageService type for the sessionStorage implementation (relies on IJSInProcessRuntime). |
|
Blazor.Geolocation.WebAssembly |
Razor class library exposing DI-ready IGeolocationService type (and dependent callback types) for the geolocation implementation (relies on IJSInProcessRuntime). |
|
Blazor.SpeechSynthesis.WebAssembly |
Razor class library exposing DI-ready ISpeechSynthesisService type for the speechSynthesis implementation (relies on IJSInProcessRuntime). |
|
Blazor.SpeechRecognition.WebAssembly |
Razor class library exposing DI-ready ISpeechRecognitionService type for the webkitSpeechRecognition implementation (relies on IJSInProcessRuntime). |
|
Blazor.Permissions.WebAssembly |
Razor class library exposing DI-ready IPermissionsService type for the permissions implementation (relies on IJSInProcessRuntime). |
Targets the
IJSInProcessRuntimetype.
Server libraries
| NuGet package | NuGet version | Description |
|---|---|---|
Blazor.LocalStorage |
Blazor Server class library exposing DI-ready IStorageService type for the localStorage implementation (relies on IJSRuntime) |
|
Blazor.SessionStorage |
Blazor Server class library exposing DI-ready IStorageService type for the sessionStorage implementation (relies on IJSRuntime) |
|
Blazor.Geolocation |
Razor class library exposing DI-ready IGeolocationService type (and dependent callback types) for the geolocation implementation (relies on IJSRuntime). |
|
Blazor.SpeechSynthesis |
Razor class library exposing DI-ready ISpeechSynthesisService type for the speechSynthesis implementation (relies on IJSRuntime). |
|
Blazor.SpeechRecognition |
Razor class library exposing DI-ready ISpeechRecognitionService type for the webkitSpeechRecognition implementation (relies on IJSRuntime). |
Targets the
IJSRuntimetype.
Legacy package note
The source-generator package pairs listed above ship separately for WebAssembly (
IJSInProcessRuntime) and Server (IJSRuntime). Both expose asynchronousValueTask-based APIs; the difference is which underlying JS runtime they dispatch through. The exhaustive DOM packages below use a newer host-specific runtime and projection model.
The exhaustive DOM packages are generated from exact-pinned TypeScript and Web IDL inputs rather than the legacy declaration parser. The semantic pipeline preserves merged declarations, inheritance, overloads, generics, event maps, constructors, global paths, documentation, deprecations, exposure metadata, and explicit transport semantics.
Generation runs once inside this repository's build graph and writes C# to intermediate obj output. Applications consuming the packages do not run Node.js, parse lib.dom.d.ts, or generate thousands of source files.
The current Window profile accounts for:
| Surface | Count |
|---|---|
| TypeScript symbols | 2,183 |
| Declarations | 3,022 |
| Members | 12,217 |
| Overloads | 3,880 |
| Parameters | 6,522 |
Every in-profile symbol and member must be generated, explicitly excluded with a reviewed reason, or fail generation. The current exhaustive profile projects every symbol cleanly with no excluded, deferred, or generation-failed outcomes. Worker, Service Worker, Shared Worker, and Worklet exposure is retained in the model but intentionally deferred to separate future profiles.
The host packages are mutually exclusive because they expose the same logical DOM surface with hosting-specific dispatch:
| Package | Hosting model | Behavior |
|---|---|---|
Blazor.DOM |
Blazor Server and hosting-neutral | Asynchronous, cancellable ValueTask dispatch through IJSRuntime and IJSObjectReference. |
Blazor.DOM.WebAssembly |
Blazor WebAssembly | Synchronous non-Promise operations through in-process references; Promise and lifecycle operations remain asynchronous. |
Both variants compile for net8.0, net9.0, and net10.0, with exact logical parity across 878 host symbols and 13,299 operations per host.
Register one package and inject the single IBrowser root:
// Blazor Server
builder.Services.AddBlazorDOM();
// Blazor WebAssembly
builder.Services.AddBlazorDOMWebAssembly();A Blazor Server component can then resolve and use a live document proxy:
@inject IBrowser Browser
@code {
protected override async Task OnAfterRenderAsync(bool firstRender)
{
if (!firstRender)
{
return;
}
await using var document = await Browser.GetDocumentProxyAsync();
var title = await document.GetTitleAsync();
}
}Generated browser interfaces are live JavaScript-reference proxies, not JSON snapshots. The runtime validates JSON dictionaries, strongly typed unions, binary values, streams, transferables, callbacks, and returned references before dispatch. Owned proxies, event subscriptions, callback-scoped borrowed references, and stream handles have explicit disposal rules.
Anonymous advanced shapes use deterministic semantic names derived from their declaring API slot and projected values, such as ClipboardItemDataStringOrBlobUnion. Structural fingerprints remain manifest-only; generation fails for an unresolved semantic collision rather than exposing hash suffixes or ordinal arm names in the public API.
Applications that do not need the complete DOM surface can reference a focused Server/WebAssembly pair generated from the same semantic model and runtime:
| Capability | Package pair |
|---|---|
| Permissions | Blazor.Permissions / Blazor.Permissions.WebAssembly |
| Clipboard | Blazor.Clipboard / Blazor.Clipboard.WebAssembly |
| Web Share | Blazor.Share / Blazor.Share.WebAssembly |
| Wake Lock | Blazor.WakeLock / Blazor.WakeLock.WebAssembly |
| Storage management | Blazor.StorageManagement / Blazor.StorageManagement.WebAssembly |
| Screen APIs | Blazor.Screen / Blazor.Screen.WebAssembly |
| Performance | Blazor.Performance / Blazor.Performance.WebAssembly |
| Web Crypto | Blazor.WebCrypto / Blazor.WebCrypto.WebAssembly |
| Credentials and WebAuthn | Blazor.Credentials / Blazor.Credentials.WebAssembly |
| Offline storage | Blazor.OfflineStorage / Blazor.OfflineStorage.WebAssembly |
| Browser coordination | Blazor.BrowserCoordination / Blazor.BrowserCoordination.WebAssembly |
| Media devices | Blazor.MediaDevices / Blazor.MediaDevices.WebAssembly |
| Notifications | Blazor.Notifications / Blazor.Notifications.WebAssembly |
| File System Access | Blazor.FileSystemAccess / Blazor.FileSystemAccess.WebAssembly |
Together, these profiles account for 772 operations and 966 projected members. Each focused package exposes a generated capability facade, DI registration method, exact transitive type closure, host parity, feature metadata, and package-local static web assets. For example:
builder.Services.AddClipboardCapability();@inject IClipboardCapability Capability
@code {
async Task CopyAsync()
{
await using var clipboard = Capability.GetClipboard();
await clipboard.WriteTextAsync("Generated DOM interop");
}
}The sample app includes an interactive DOM lab at /dom-e2e and a routed catalog of all 14 capabilities. Each page shows installation, registration, injection, generated contracts, a live browser workflow, operation facts, and the raw result envelope.
Install the SDK selected by global.json, then build from the repository root:
dotnet buildThe checked-in NuGet.config intentionally clears inherited machine-level package feeds and restores from NuGet.org. This keeps central package management deterministic across developer machines and CI. Command-line builds use MSBuild's static project graph so every project/framework combination has one artifact writer, including on Windows machines where antivirus scanning makes duplicate writes especially fragile. The shared DOM generation node is incremental; a clean build validates the pinned semantic inputs and generates all exhaustive and focused contracts under artifacts/obj.
Blazor.SourceGenerators packageAs an example, the official Blazor.LocalStorage.WebAssembly package consumes the Blazor.SourceGenerators package. It exposes extension methods specific to Blazor WebAssembly and the localStorage Web API.
Consider the IStorageService.cs C# file:
// Copyright (c) David Pine. All rights reserved.
// Licensed under the MIT License.
namespace Microsoft.JSInterop;
[JSAutoGenericInterop(
TypeName = "Storage",
Implementation = "window.localStorage",
Url = "http暂无开放 Issues,或尚未同步最近议题。