CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-webgpu--types

Complete TypeScript type definitions for the WebGPU standard enabling type-safe GPU programming.

Pending
Overview
Eval results
Files

gpu-interfaces.mddocs/

GPU Interfaces

Main WebGPU interfaces including the root GPU object, adapters, and devices that provide the foundation for GPU access and resource management.

Capabilities

GPU Root Interface

The main entry point for WebGPU functionality, accessed through navigator.gpu.

interface GPU {
  /**
   * Requests a GPU adapter with optional configuration
   * @param options - Optional adapter selection criteria
   * @returns Promise resolving to adapter or null if unavailable
   */
  requestAdapter(options?: GPURequestAdapterOptions): Promise<GPUAdapter | null>;
  
  /**
   * Gets the preferred canvas format for the current platform
   * @returns The recommended texture format for canvas contexts
   */
  getPreferredCanvasFormat(): GPUTextureFormat;
  
  /** Set of WGSL language features supported by the implementation */
  readonly wgslLanguageFeatures: WGSLLanguageFeatures;
}

interface GPURequestAdapterOptions {
  powerPreference?: GPUPowerPreference;
  forceFallbackAdapter?: boolean;
}

GPU Adapter Interface

Represents a GPU adapter with information about capabilities and limits.

interface GPUAdapter {
  /** Set of features supported by this adapter */
  readonly features: GPUSupportedFeatures;
  
  /** Limits and capabilities of this adapter */
  readonly limits: GPUSupportedLimits;
  
  /** Information about the adapter hardware */
  readonly info: GPUAdapterInfo;
  
  /**
   * Requests a logical device from this adapter
   * @param descriptor - Optional device configuration
   * @returns Promise resolving to the device
   */
  requestDevice(descriptor?: GPUDeviceDescriptor): Promise<GPUDevice>;
}

interface GPUDeviceDescriptor extends GPUObjectDescriptorBase {
  requiredFeatures?: Iterable<GPUFeatureName>;
  requiredLimits?: Record<string, GPUSize64>;
  defaultQueue?: GPUQueueDescriptor;
}

interface GPUQueueDescriptor extends GPUObjectDescriptorBase {}

GPU Adapter Information

Detailed information about the GPU hardware and driver.

interface GPUAdapterInfo {
  /** The name of the vendor of the adapter, if available. Empty string otherwise. */
  readonly vendor: string;
  
  /** The name of the family or class of GPUs the adapter belongs to, if available. Empty string otherwise. */
  readonly architecture: string;
  
  /** A vendor-specific identifier for the adapter, if available. Empty string otherwise. */
  readonly device: string;
  
  /** A human readable string describing the adapter as reported by the driver, if available. Empty string otherwise. */
  readonly description: string;
  
  /** If the "subgroups" feature is supported, the minimum supported subgroup size for the adapter. */
  readonly subgroupMinSize?: number;
  
  /** If the "subgroups" feature is supported, the maximum supported subgroup size for the adapter. */
  readonly subgroupMaxSize?: number;
  
  /** Whether the adapter is a fallback adapter. */
  readonly isFallbackAdapter: boolean;
}

GPU Device Interface

The main logical device interface for creating resources and submitting commands.

interface GPUDevice extends EventTarget, GPUObjectBase {
  /** Set of features available on this device */
  readonly features: GPUSupportedFeatures;
  
  /** Limits and capabilities of this device */
  readonly limits: GPUSupportedLimits;
  
  /** Information about the physical adapter which created this device */
  readonly adapterInfo: GPUAdapterInfo;
  
  /** Default queue for command submission */
  readonly queue: GPUQueue;
  
  /** Current device state */
  readonly lost: Promise<GPUDeviceLostInfo>;
  
  /** Destroys the device and releases resources */
  destroy(): void;
  
  // Resource creation methods
  createBuffer(descriptor: GPUBufferDescriptor): GPUBuffer;
  createTexture(descriptor: GPUTextureDescriptor): GPUTexture;
  createSampler(descriptor?: GPUSamplerDescriptor): GPUSampler;
  
  /**
   * Creates a GPUExternalTexture wrapping the provided image source
   * @param descriptor - Provides the external image source object and any creation options
   */
  importExternalTexture(descriptor: GPUExternalTextureDescriptor): GPUExternalTexture;
  
  // Binding and layout creation
  createBindGroupLayout(descriptor: GPUBindGroupLayoutDescriptor): GPUBindGroupLayout;
  createPipelineLayout(descriptor: GPUPipelineLayoutDescriptor): GPUPipelineLayout;
  createBindGroup(descriptor: GPUBindGroupDescriptor): GPUBindGroup;
  
  // Shader and pipeline creation
  createShaderModule(descriptor: GPUShaderModuleDescriptor): GPUShaderModule;
  createComputePipeline(descriptor: GPUComputePipelineDescriptor): GPUComputePipeline;
  createRenderPipeline(descriptor: GPURenderPipelineDescriptor): GPURenderPipeline;
  createComputePipelineAsync(descriptor: GPUComputePipelineDescriptor): Promise<GPUComputePipeline>;
  createRenderPipelineAsync(descriptor: GPURenderPipelineDescriptor): Promise<GPURenderPipeline>;
  
  // Command recording
  createCommandEncoder(descriptor?: GPUCommandEncoderDescriptor): GPUCommandEncoder;
  createRenderBundleEncoder(descriptor: GPURenderBundleEncoderDescriptor): GPURenderBundleEncoder;
  
  // Query creation
  createQuerySet(descriptor: GPUQuerySetDescriptor): GPUQuerySet;
  
  // Error handling
  pushErrorScope(filter: GPUErrorFilter): void;
  popErrorScope(): Promise<GPUError | null>;
  
  // Event handling for uncaptured errors
  addEventListener<K extends keyof __GPUDeviceEventMap>(
    type: K,
    listener: (this: GPUDevice, ev: __GPUDeviceEventMap[K]) => any,
    options?: boolean | AddEventListenerOptions
  ): void;
  addEventListener(
    type: string,
    listener: EventListenerOrEventListenerObject,
    options?: boolean | AddEventListenerOptions
  ): void;
  removeEventListener<K extends keyof __GPUDeviceEventMap>(
    type: K,
    listener: (this: GPUDevice, ev: __GPUDeviceEventMap[K]) => any,
    options?: boolean | EventListenerOptions
  ): void;
  removeEventListener(
    type: string,
    listener: EventListenerOrEventListenerObject,
    options?: boolean | EventListenerOptions
  ): void;
}

interface __GPUDeviceEventMap {
  uncapturederror: GPUUncapturedErrorEvent;
}

type GPUErrorFilter = "validation" | "out-of-memory" | "internal";

GPU Queue Interface

Command queue for submitting work to the GPU.

interface GPUQueue {
  readonly label: string | undefined;
  
  /**
   * Submits command buffers for execution
   * @param commandBuffers - Array of command buffers to execute
   */
  submit(commandBuffers: Iterable<GPUCommandBuffer>): void;
  
  /**
   * Handles promise returned by buffer.mapAsync()
   * @param buffer - Buffer that was mapped
   */
  onSubmittedWorkDone(): Promise<void>;
  
  /**
   * Writes data directly to a buffer
   * @param buffer - Target buffer
   * @param bufferOffset - Offset in the buffer
   * @param data - Source data
   * @param dataOffset - Offset in source data (in elements)
   * @param size - Number of bytes to write
   */
  writeBuffer(
    buffer: GPUBuffer,
    bufferOffset: GPUSize64,
    data: GPUAllowSharedBufferSource,
    dataOffset?: GPUSize64,
    size?: GPUSize64
  ): void;
  
  /**
   * Writes data directly to a texture
   * @param destination - Target texture and layout
   * @param data - Source data
   * @param dataLayout - Data layout in the source
   * @param size - Size of the data to copy
   */
  writeTexture(
    destination: GPUTexelCopyTextureInfo,
    data: GPUAllowSharedBufferSource,
    dataLayout: GPUTexelCopyBufferLayout,
    size: GPUExtent3D
  ): void;
  
  /**
   * Copies an image from an external source to a texture
   * @param source - External image source
   * @param destination - Target texture
   * @param copySize - Size of the region to copy
   */
  copyExternalImageToTexture(
    source: GPUCopyExternalImageSourceInfo,
    destination: GPUCopyExternalImageDestInfo,
    copySize: GPUExtent3D
  ): void;
}

GPU Canvas Context

Context for WebGPU rendering to HTML canvas elements.

interface GPUCanvasContext {
  readonly canvas: HTMLCanvasElement | OffscreenCanvas;
  
  /**
   * Configures the context for rendering
   * @param configuration - Canvas configuration options
   */
  configure(configuration: GPUCanvasConfiguration): void;
  
  /** Returns the context configuration */
  getConfiguration(): GPUCanvasConfigurationOut | null;
  
  /** Unconfigures the context */
  unconfigure(): void;
  
  /**
   * Gets the current texture for rendering
   * @returns Texture representing the current frame
   */
  getCurrentTexture(): GPUTexture;
}

interface GPUCanvasConfiguration {
  device: GPUDevice;
  format: GPUTextureFormat;
  usage?: GPUTextureUsageFlags;
  colorSpace?: GPUCanvasColorSpace;
  toneMapping?: GPUCanvasToneMapping;
  alphaMode?: GPUCanvasAlphaMode;
}

type GPUCanvasColorSpace = "srgb" | "display-p3";
type GPUCanvasAlphaMode = "opaque" | "premultiplied";

interface GPUCanvasToneMapping {
  mode?: GPUCanvasToneMappingMode;
}

type GPUCanvasToneMappingMode = "standard" | "extended";

Supported Features and Limits

Information about device capabilities.

type GPUSupportedFeatures = ReadonlySet<string>;

interface GPUSupportedLimits {
  readonly maxTextureDimension1D: number;
  readonly maxTextureDimension2D: number;
  readonly maxTextureDimension3D: number;
  readonly maxTextureArrayLayers: number;
  readonly maxBindGroups: number;
  readonly maxBindGroupsPlusVertexBuffers: number;
  readonly maxBindingsPerBindGroup: number;
  readonly maxDynamicUniformBuffersPerPipelineLayout: number;
  readonly maxDynamicStorageBuffersPerPipelineLayout: number;
  readonly maxSampledTexturesPerShaderStage: number;
  readonly maxSamplersPerShaderStage: number;
  readonly maxStorageBuffersPerShaderStage: number;
  readonly maxStorageTexturesPerShaderStage: number;
  readonly maxUniformBuffersPerShaderStage: number;
  readonly maxUniformBufferBindingSize: number;
  readonly maxStorageBufferBindingSize: number;
  readonly minUniformBufferOffsetAlignment: number;
  readonly minStorageBufferOffsetAlignment: number;
  readonly maxVertexBuffers: number;
  readonly maxBufferSize: number;
  readonly maxVertexAttributes: number;
  readonly maxVertexBufferArrayStride: number;
  readonly maxInterStageShaderComponents: number;
  readonly maxInterStageShaderVariables: number;
  readonly maxColorAttachments: number;
  readonly maxColorAttachmentBytesPerSample: number;
  readonly maxComputeWorkgroupStorageSize: number;
  readonly maxComputeInvocationsPerWorkgroup: number;
  readonly maxComputeWorkgroupSizeX: number;
  readonly maxComputeWorkgroupSizeY: number;
  readonly maxComputeWorkgroupSizeZ: number;
  readonly maxComputeWorkgroupsPerDimension: number;
}

Device Lost Information

Information about device loss events.

interface GPUDeviceLostInfo {
  /** Reason for device loss */
  readonly reason: GPUDeviceLostReason;
  
  /** Human-readable message about the loss */
  readonly message: string;
}

type GPUDeviceLostReason = "unknown" | "destroyed";

Error Types

Complete error hierarchy for WebGPU error handling.

interface GPUError {
  /** Human-readable error message for debugging */
  readonly message: string;
}

interface GPUInternalError extends GPUError {
  /** @internal */
  readonly __brand: "GPUInternalError";
}

interface GPUOutOfMemoryError extends GPUError {
  /** @internal */
  readonly __brand: "GPUOutOfMemoryError";
}

interface GPUPipelineError extends DOMException {
  /** @internal */
  readonly __brand: "GPUPipelineError";
  
  /** The type of error encountered in pipeline creation */
  readonly reason: GPUPipelineErrorReason;
}

interface GPUValidationError extends GPUError {
  /** @internal */
  readonly __brand: "GPUValidationError";
}

interface GPUUncapturedErrorEvent extends Event {
  /** @internal */
  readonly __brand: "GPUUncapturedErrorEvent";
  
  /** The uncaptured error */
  readonly error: GPUError;
}

interface GPUUncapturedErrorEventInit extends EventInit {
  error: GPUError;
}

type GPUPipelineErrorReason = "validation" | "internal";

interface GPUPipelineErrorInit {
  reason: GPUPipelineErrorReason;
}

Navigator Integration

Extensions to the Navigator interface for WebGPU access.

interface NavigatorGPU {
  readonly gpu: GPU;
}

interface Navigator extends NavigatorGPU {}
interface WorkerNavigator extends NavigatorGPU {}

Usage Examples

Basic GPU Access

// Check for WebGPU support
if (!navigator.gpu) {
  throw new Error("WebGPU not supported");
}

// Get the GPU interface
const gpu: GPU = navigator.gpu;

// Request an adapter
const adapter: GPUAdapter | null = await gpu.requestAdapter({
  powerPreference: "high-performance"
});

if (!adapter) {
  throw new Error("No suitable GPU adapter found");
}

// Check adapter capabilities
console.log("Supported features:", Array.from(adapter.features));
console.log("Max texture size:", adapter.limits.maxTextureDimension2D);

Device Creation and Configuration

// Request a device with specific features
const device: GPUDevice = await adapter.requestDevice({
  requiredFeatures: ["timestamp-query", "depth-clip-control"],
  requiredLimits: {
    maxBufferSize: 1024 * 1024 * 1024, // Request 1GB max buffer size
    maxTextureDimension2D: 8192 // Request support for 8K textures
  }
});

// Set up error handling
device.addEventListener("uncapturederror", (event) => {
  console.error("Uncaptured WebGPU error:", event.error);
});

// Push error scope for validation errors
device.pushErrorScope("validation");

// ... GPU operations ...

// Check for validation errors
const error = await device.popErrorScope();
if (error) {
  console.error("Validation error:", error.message);
}

Canvas Setup

// Get canvas and context
const canvas = document.querySelector("canvas") as HTMLCanvasElement;
const context: GPUCanvasContext = canvas.getContext("webgpu")!;

// Configure canvas for rendering
context.configure({
  device,
  format: gpu.getPreferredCanvasFormat(),
  usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.COPY_SRC,
  alphaMode: "premultiplied"
});

// Get current frame texture
const currentTexture: GPUTexture = context.getCurrentTexture();

Queue Operations

// Write data directly to buffer
const data = new Float32Array([1, 2, 3, 4]);
device.queue.writeBuffer(
  buffer,
  0, // offset
  data.buffer,
  0, // data offset
  data.byteLength
);

// Submit command buffers
const commandBuffer = commandEncoder.finish();
device.queue.submit([commandBuffer]);

// Wait for submitted work to complete
await device.queue.onSubmittedWorkDone();

Feature Detection

// Check for optional features
const requiredFeatures: GPUFeatureName[] = [
  "depth-clip-control",
  "timestamp-query",
  "texture-compression-bc"
];

const hasAllFeatures = requiredFeatures.every(feature => 
  adapter.features.has(feature)
);

if (hasAllFeatures) {
  console.log("All required features supported");
} else {
  console.warn("Some features not available");
}

// Check specific limits
const limits = adapter.limits;
if (limits.maxTextureDimension2D >= 4096) {
  console.log("4K textures supported");
}

if (limits.maxComputeWorkgroupSizeX >= 1024) {
  console.log("Large compute workgroups supported");
}

Install with Tessl CLI

npx tessl i tessl/npm-webgpu--types

docs

commands.md

configuration.md

core-types.md

gpu-interfaces.md

index.md

pipelines.md

render-bundles.md

resources.md

tile.json