@forgeax/engine-rhi-webgpu 0.1.7 → 0.1.19
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +18 -2
- package/dist/.tsbuildinfo +1 -1
- package/dist/__tests__/rgba16float-live-probe.browser.test.d.ts +2 -0
- package/dist/__tests__/rgba16float-live-probe.browser.test.d.ts.map +1 -0
- package/dist/__tests__/rgba16float-live-probe.dawn.test.d.ts +2 -0
- package/dist/__tests__/rgba16float-live-probe.dawn.test.d.ts.map +1 -0
- package/dist/index.d.ts +12 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.mjs +23 -5
- package/dist/index.mjs.map +1 -1
- package/package.json +3 -3
- package/src/__tests__/dawn-real-gpu.dawn.test.ts +19 -0
- package/src/__tests__/rgba16float-live-probe.browser.test.ts +19 -0
- package/src/__tests__/rgba16float-live-probe.dawn.test.ts +20 -0
- package/src/__tests__/rhi-webgpu.unit.test.ts +25 -1
- package/src/index.ts +77 -40
package/dist/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/errors.ts","../src/internal/timestamp-query.ts","../src/device.ts","../src/internal/error-translation.ts","../src/index.ts"],"names":["err","RhiError","RhiErrorClass","ok","out"],"mappings":";;;;AAeO,SAAS,kBAAA,GAA8C;AAC5D,EAAA,OAAO,GAAA;AAAA,IACL,IAAI,QAAA,CAAS;AAAA,MACX,IAAA,EAAM,qBAAA;AAAA,MACN,QAAA,EAAU,4CAAA;AAAA,MACV,IAAA,EAAM;AAAA,KACP;AAAA,GACH;AACF;AAGO,SAAS,qBAAqB,KAAA,EAAyC;AAC5E,EAAA,MAAM,SACJ,KAAA,KAAU,IAAA,IAAQ,OAAO,KAAA,KAAU,WAC9B,KAAA,GACD,MAAA;AACN,EAAA,MAAM,IAAA,GAAO,OAAO,MAAA,EAAQ,IAAA,KAAS,QAAA,IAAY,OAAO,IAAA,CAAK,MAAA,GAAS,CAAA,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AMA,EAAA,IAAI,OAAA;AACJ,EAAA,IAAI;AACF,IAAA,OAAA,GAAU,MAAM,OAAA,CAAQ,cAAA,CAAe,IAA4C,CAAA;AAAA,EACrF,SAAS,KAAA,EAAO;AACd,IAAA,OAAO,qBAAqB,KAAK,CAAA;AAAA,EACnC;AACA,EAAA,IAAI,YAAY,IAAA,EAAM;AACpB,IAAA,OAAO,kBAAA,EAAmB;AAAA,EAC5B;AACA,EAAA,OAAOA,EAAAA;AAAA,IACL,cAAA;AAAA,MACE;AAAA;AAMF,GACF;AACF;AAyBO,SAAS,qBACd,MAAA,EACoC;AACpC,EAAA,IAAI,UAAA;AACJ,EAAA,IAAI;AACF,IAAA,UAAA,GAAa,MAAA,CAAO,WAAW,QAAQ,CAAA;AAAA,EACzC,CAAA,CAAA,MAAQ;AACN,IAAA,UAAA,GAAa,IAAA;AAAA,EACf;AACA,EAAA,IAAI,eAAe,IAAA,EAAM;AACvB,IAAA,OAAOH,GAAAA;AAAA,MACL,IAAIE,QAAAA,CAAc;AAAA,QAChB,IAAA,EAAM,mBAAA;AAAA,QACN,QAAA,EAAU,mEAAA;AAAA,QACV,IAAA,EAAM;AAAA,OACP;AAAA,KACH;AAAA,EACF;AACA,EAAA,OAAOC,EAAAA,CAAG,iBAAA,CAAkB,UAAU,CAAC,CAAA;AACzC;AAiBO,IAAM,GAAA,GAGT;AAAA,EACF,cAAA;AAAA,EACA,kBAAA;AAAA,EACA;AACF","file":"index.mjs","sourcesContent":["// @forgeax/engine-rhi-webgpu/src/errors — RhiError factory functions.\n//\n// Source of truth for the .expected / .hint copy: plan-strategy 7.3 error-info\n// table. After feat-20260508-rhi-surface-completion w7 (D-S3) the surface\n// covers 8 factories: 4 device/shader paths (Round 1) + 4 command/queue paths\n// (this closure: command-encoder-finished / render-pass-not-ended /\n// queue-submit-failed / queue-write-buffer-out-of-bounds).\n//\n// Each .expected / .hint string aligns one-to-one with requirements boundary\n// cases + plan-strategy 7.3 (charter proposition 3: machine-readable hint\n// over prose).\n\nimport { err, type Result, RhiError, type RhiShaderCompileDetail } from '@forgeax/engine-rhi';\n\n/** adapter null path (research F-5 single null channel). */\nexport function adapterUnavailable(): Result<never, RhiError> {\n return err(\n new RhiError({\n code: 'adapter-unavailable',\n expected: 'an available browser-native WebGPU adapter',\n hint: 'this only reports the browser-native WebGPU channel; ForgeaX may continue through its wgpu/WebGL2 fallback, so do not conclude that the browser or machine is unsupported unless both backend causes fail',\n }),\n );\n}\n\n/** `GPU.requestAdapter()` rejected instead of reporting adapter absence with `null`. */\nexport function requestAdapterFailed(cause: unknown): Result<never, RhiError> {\n const record =\n cause !== null && typeof cause === 'object'\n ? (cause as { readonly name?: unknown; readonly message?: unknown })\n : undefined;\n const name = typeof record?.name === 'string' && record.name.length > 0 ? record.name : undefined;\n let message =\n typeof record?.message === 'string' && record.message.length > 0\n ? record.message\n : typeof cause === 'string'\n ? cause\n : '';\n if (message.length === 0 && cause !== undefined) {\n try {\n const serialized = JSON.stringify(cause);\n message = serialized && serialized !== '{}' ? serialized : 'unknown thrown object';\n } catch {\n message = 'unserializable thrown object';\n }\n }\n if (message.length === 0) message = 'unknown requestAdapter failure';\n return err(\n new RhiError({\n code: 'webgpu-runtime-error',\n expected: 'navigator.gpu.requestAdapter() resolves with an adapter or null',\n hint: 'inspect detail.error before assigning the failure to WebGPU capability; the ForgeaX runtime can still attempt its wgpu/WebGL2 fallback',\n detail: {\n error: {\n code: 'request-adapter-threw',\n ...(name === undefined ? {} : { name }),\n message,\n },\n },\n }),\n );\n}\n\n/** feature not enabled path (boundary cases / requirements). */\nexport function featureNotEnabled(featureName?: string | undefined): Result<never, RhiError> {\n const fname = featureName ?? 'compute';\n return err(\n new RhiError({\n code: 'feature-not-enabled',\n expected: `feature ${fname} to be enabled`,\n hint: `verify device.features.${fname} before calling this entry point`,\n }),\n );\n}\n\n/** limit exceeded path (boundary cases / requirements). */\nexport function limitExceeded(limitName?: string | undefined): Result<never, RhiError> {\n const lname = limitName ?? 'maxBindGroups';\n return err(\n new RhiError({\n code: 'limit-exceeded',\n expected: `${lname} to be within bounds`,\n hint: `verify device.limits.${lname}`,\n }),\n );\n}\n\n/** shader compile failed path + detail.compilerMessages forwarding (OQ-P2 6 fields). */\nexport function shaderCompileFailed(\n compilerMessages: readonly GPUCompilationMessage[],\n): Result<never, RhiError> {\n const detail: RhiShaderCompileDetail = { compilerMessages };\n return err(\n new RhiError({\n code: 'shader-compile-failed',\n expected: 'valid WGSL source',\n hint: 'inspect RhiError.detail.compilerMessages (each entry: { message, type, lineNum, linePos, offset, length } per WebGPU GPUCompilationMessage shape)',\n detail,\n }),\n );\n}\n\n/**\n * Command encoder reused after finish() (W3C WebGPU 22 GPUCommandEncoder lifecycle).\n *\n * Trigger: encoder.beginRenderPass / copyXxx / finish called after a prior finish().\n * Distinct from 'rhi-not-available': this is a real-path validation failure,\n * not a placeholder for unimplemented surface (plan-strategy D-S3 template 1).\n */\nexport function commandEncoderFinished(): Result<never, RhiError> {\n return err(\n new RhiError({\n code: 'command-encoder-finished',\n expected: 'command encoder must not be finished before recording new commands',\n hint: 'create a new command encoder via device.createCommandEncoder() for each frame; do not reuse a finished encoder',\n }),\n );\n}\n\n/**\n * Render pass not ended before next pass / finish (W3C WebGPU 22.7 Render pass).\n *\n * Trigger: encoder.beginRenderPass while previous pass active, or encoder.finish\n * with active pass still recording (plan-strategy D-S3 template 2).\n */\nexport function renderPassNotEnded(): Result<never, RhiError> {\n return err(\n new RhiError({\n code: 'render-pass-not-ended',\n expected:\n 'previous render pass must be ended before beginning a new pass or finishing the encoder',\n hint: 'call pass.end() before beginRenderPass() or encoder.finish()',\n }),\n );\n}\n\n/**\n * Queue.submit real-path failure (W3C WebGPU 23 Queue).\n *\n * Trigger: submit([cb]) with destroyed buffer/pipeline references, or GPU validation\n * error fan-out via onuncapturederror. Explicitly distinct from 'rhi-not-available'\n * (device-lost subclass) - submit-failed signals dynamic resource life-cycle issues\n * the AI user can self-recover from (plan-strategy D-S3 template 3).\n */\nexport function queueSubmitFailed(detailMessage?: string | undefined): Result<never, RhiError> {\n const baseHint =\n 'check if any referenced buffer / pipeline / texture has been destroyed before submit';\n const hint =\n detailMessage !== undefined && detailMessage.length > 0\n ? `${baseHint}; underlying GPU error: ${detailMessage}`\n : baseHint;\n return err(\n new RhiError({\n code: 'queue-submit-failed',\n expected:\n 'command buffer references must be valid at submit time (not destroyed; not from a different device)',\n hint,\n }),\n );\n}\n\n/**\n * Queue.writeBuffer offset/size out of bounds (W3C WebGPU 23.2 writeBuffer).\n *\n * Trigger: writeBuffer(buf, offset, data) where offset is not 4-byte aligned, or\n * offset + data.byteLength exceeds buffer.size. Distinct from 'limit-exceeded'\n * (static device.limits) - out-of-bounds is a dynamic per-buffer boundary\n * (plan-strategy D-S3 template 4).\n */\nexport function queueWriteBufferOutOfBounds(args: {\n offset: number;\n byteLength: number;\n bufferSize: number;\n}): Result<never, RhiError> {\n return err(\n new RhiError({\n code: 'queue-write-buffer-out-of-bounds',\n expected:\n 'writeBuffer offset + data.byteLength must be <= buffer.size; offset must be 4-byte aligned',\n hint: `verify offset alignment and bounds: offset (got ${args.offset}) + data.byteLength (got ${args.byteLength}) must be <= buffer.size (got ${args.bufferSize})`,\n }),\n );\n}\n","/// <reference types=\"@webgpu/types\" />\n\nimport { err, ok, type Result, RhiError } from '@forgeax/engine-rhi';\n\nexport function resolveTimestampQueries(args: {\n rawEncoder: GPUCommandEncoder;\n rawQuerySet: GPUQuerySet;\n firstQuery: number;\n queryCount: number;\n rawDestination: GPUBuffer;\n destinationOffset: number;\n}): Result<void, RhiError> {\n try {\n args.rawEncoder.resolveQuerySet(\n args.rawQuerySet,\n args.firstQuery,\n args.queryCount,\n args.rawDestination,\n args.destinationOffset,\n );\n return ok(undefined);\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n return err(\n new RhiError({\n code: 'webgpu-runtime-error',\n expected: 'underlying GPUCommandEncoder.resolveQuerySet to succeed',\n hint: `resolveQuerySet raised: ${message}`,\n }),\n );\n }\n}\n\nexport function writeTimestamp(args: {\n rawEncoder: GPUCommandEncoder;\n rawQuerySet: GPUQuerySet;\n queryIndex: number;\n}): void {\n const encoderWithTimestamp = args.rawEncoder as unknown as {\n writeTimestamp?: (querySet: GPUQuerySet, queryIndex: number) => void;\n };\n if (typeof encoderWithTimestamp.writeTimestamp !== 'function') {\n throw new RhiError({\n code: 'webgpu-runtime-error',\n expected: 'underlying GPUCommandEncoder.writeTimestamp to be callable',\n hint: 'timestamp-query is advertised but the raw encoder has no writeTimestamp method',\n });\n }\n try {\n encoderWithTimestamp.writeTimestamp(args.rawQuerySet, args.queryIndex);\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n throw new RhiError({\n code: 'webgpu-runtime-error',\n expected: 'underlying GPUCommandEncoder.writeTimestamp to succeed',\n hint: `writeTimestamp raised: ${message}`,\n });\n }\n}\n","// @forgeax/engine-rhi-webgpu/src/device - WebGPU GPUDevice -> RhiDevice thin shim.\n//\n// Iron laws (README + AGENTS.md \"## RHI / WebGPU\"):\n// - spec-aligned: 5 + 4 descriptor field names match GPUDevice.createX byte-for-byte.\n// - `?: T | undefined` + `'x' in src` guard distinguishes \"missing\" vs\n// \"explicit undefined\" (research F-3 anti-pattern 2 / hard-constraint 10).\n// - opaque handle: RhiDevice.createX returns Result.ok(handle); the handle\n// internally references the GPU resource but exposes only a brand-only\n// opaque shape (research R5).\n// - capability-gated: caps / features / limits exposed independently as\n// readonly layers (charter proposition 5).\n// - device.lost two-track: spec Promise passthrough + engine-layer\n// LostListenerRegistry (R2 mitigation / research F-4); this package only\n// exposes the spec Promise without a second cache.\n//\n// w3 / w5 / w6 (feat-20260508-rhi-surface-completion, co-commit):\n// - createCommandEncoder + 12 RhiCommandEncoder methods + 3 mixin (w3)\n// - 17 RhiRenderPassEncoder spec stable methods + 1 setBindGroup overload +\n// 3 placeholders (executeBundles / beginOcclusionQuery / endOcclusionQuery) (w5)\n// - Queue.submit / writeBuffer real implementation + bounds validation (w6)\n//\n// co-commit reason: w3, w5, w6 each modify both `@forgeax/engine-rhi/src/index.ts`\n// and `@forgeax/engine-rhi-webgpu/src/device.ts`; the encoder lifecycle (D-S3\n// templates 1 + 2) couples render-pass end() to command-encoder finish(),\n// so independent commits would leave the interface and shim inconsistent\n// between commits.\n\n/// <reference types=\"@webgpu/types\" />\n\nimport type {\n BindGroup,\n BindGroupDescriptor,\n BindGroupLayout,\n BindGroupLayoutDescriptor,\n Buffer,\n BufferDescriptor,\n CanvasConfiguration,\n CommandBuffer,\n CommandEncoderDescriptor,\n ComputePassDescriptor,\n ComputePipeline,\n ComputePipelineDescriptor,\n ExternalImageTextureDestination,\n MappedBuffer,\n PipelineLayout,\n PipelineLayoutDescriptor,\n QuerySet,\n QuerySetDescriptor,\n RenderPassDescriptor,\n RenderPipeline,\n RenderPipelineDescriptor,\n Result,\n RhiCanvasContext,\n RhiCaps,\n RhiCommandEncoder,\n RhiComputePassEncoder,\n RhiDevice,\n RhiError,\n RhiFeatures,\n RhiLimits,\n RhiQueue,\n RhiRenderPassEncoder,\n Sampler,\n SamplerDescriptor,\n Texture,\n TextureDescriptor,\n TextureView,\n TextureViewDescriptor,\n TextureWriteDestination,\n} from '@forgeax/engine-rhi';\nimport { err, ok, RhiError as RhiErrorClass } from '@forgeax/engine-rhi';\nimport {\n commandEncoderFinished,\n queueSubmitFailed,\n queueWriteBufferOutOfBounds,\n renderPassNotEnded,\n} from './errors';\nimport { resolveTimestampQueries, writeTimestamp } from './internal/timestamp-query';\n\n/**\n * Mirror forgeax `?: T | undefined` descriptor onto the spec GPUXxxDescriptor\n * shape with `'x' in src` guards distinguishing missing vs explicit-undefined:\n *\n * - missing key -> out has no key (preserves the spec `?: T` simplified form)\n * - present + undefined -> out has the key set to undefined (technically out\n * of bounds for spec `?: T` but the shim preserves writer intent for\n * downstream test assertions; research F-3 trade-off)\n * - present + value -> out has the key with the value\n *\n * Equivalent shape: under exactOptionalPropertyTypes:true we must spread\n * rather than `dst[k] = src[k]` because the latter maps both missing and\n * explicit-undefined to \"present + undefined\".\n */\ntype MirrorOut = Record<string, unknown>;\n\nfunction mirror<TIn extends Record<string, unknown>>(\n src: TIn,\n keys: readonly (keyof TIn & string)[],\n): MirrorOut {\n const out: MirrorOut = {};\n for (const k of keys) {\n if (k in src) {\n out[k] = src[k];\n }\n }\n return out;\n}\n\nconst BUFFER_KEYS = ['label', 'size', 'usage', 'mappedAtCreation'] as const;\nconst TEXTURE_KEYS = [\n 'label',\n 'size',\n 'mipLevelCount',\n 'sampleCount',\n 'dimension',\n 'format',\n 'usage',\n 'viewFormats',\n 'textureBindingViewDimension',\n] as const;\nconst SAMPLER_KEYS = [\n 'label',\n 'addressModeU',\n 'addressModeV',\n 'addressModeW',\n 'magFilter',\n 'minFilter',\n 'mipmapFilter',\n 'lodMinClamp',\n 'lodMaxClamp',\n 'compare',\n 'maxAnisotropy',\n] as const;\nconst BGL_KEYS = ['label', 'entries'] as const;\n// BG_KEYS removed in w20 — createBindGroup now uses tagged-union dispatch\n// over RhiBindingResource 4 kinds (not field-mirror passthrough).\nconst PL_KEYS = ['label', 'bindGroupLayouts'] as const;\nconst ENC_KEYS = ['label'] as const;\nconst TEXTURE_VIEW_KEYS = [\n 'label',\n 'format',\n 'dimension',\n 'usage',\n 'aspect',\n 'baseMipLevel',\n 'mipLevelCount',\n 'baseArrayLayer',\n 'arrayLayerCount',\n] as const;\nconst CP_KEYS = ['label', 'layout', 'compute'] as const;\nconst QS_KEYS = ['label', 'type', 'count'] as const;\n/** Spec normative upper bound on QuerySet.count (research §1.3 device timeline step 1). */\nconst QUERY_SET_COUNT_LIMIT = 4096;\n\n/**\n * RhiDevice -> raw GPUDevice reverse lookup table (fix-f3).\n *\n * After RhiDevice.createShaderModule was removed, the top-level async\n * `createShaderModule(device, desc)` entry point needs to reach the\n * underlying GPUDevice. The WeakMap keeps the public RhiDevice surface clean\n * (no internal field) and clears automatically when the device is GC'd\n * (charter proposition 5 consistent abstraction).\n *\n * Buffer<->raw GPUBuffer / Encoder<->raw GPUCommandEncoder etc. WeakMaps\n * follow the same pattern; they enable the queue.writeBuffer real-path to\n * resolve buffer.size for bounds validation, and the encoder shim to\n * forward recording calls to the underlying GPUCommandEncoder.\n */\nconst RAW_DEVICE_MAP: WeakMap<RhiDevice, GPUDevice> = new WeakMap();\nconst BUFFER_RAW_MAP: WeakMap<Buffer, GPUBuffer> = new WeakMap();\nconst TEXTURE_VIEW_RAW_MAP: WeakMap<TextureView, GPUTextureView> = new WeakMap();\nconst ENCODER_STATE: WeakMap<RhiCommandEncoder, EncoderState> = new WeakMap();\nconst PASS_STATE: WeakMap<RhiRenderPassEncoder, PassState> = new WeakMap();\nconst COMMAND_BUFFER_RAW_MAP: WeakMap<CommandBuffer, GPUCommandBuffer> = new WeakMap();\n\n/**\n * Texture metadata tracked by the shim for createTextureView fast-path\n * cross-resource validation (research §1.1):\n * - format / viewFormats: format must be in (format ∪ viewFormats).\n * - usage: createTextureView usage must be a subset of source usage.\n *\n * The shim records these at createTexture time; createTextureView reads them\n * before forwarding to the raw GPU. spec rationale: GPUTexture exposes\n * `.format` / `.usage` etc. as readonly fields, but `.viewFormats` is not\n * surfaced as a runtime field on GPUTexture in @webgpu/types v0.1.69 — the\n * shim must remember it from the descriptor.\n */\ninterface TextureMeta {\n readonly format: GPUTextureFormat;\n readonly usage: GPUTextureUsageFlags;\n readonly viewFormats: readonly GPUTextureFormat[];\n /**\n * Per-handle lifecycle marker for `RhiDevice.destroyTexture` fail-fast\n * (feat-20260612 D-7). Mutated to `true` by the first successful\n * `destroyTexture(tex)` call; a second destroy on the same handle reads\n * the flag and surfaces `Result.err({ code: 'destroy-after-destroy' })`\n * rather than forwarding to the underlying spec idempotent void.\n */\n destroyed: boolean;\n}\nconst TEXTURE_META_MAP: WeakMap<Texture, TextureMeta> = new WeakMap();\n\ninterface EncoderState {\n raw: GPUCommandEncoder;\n finished: boolean;\n activePass: RhiRenderPassEncoder | null;\n}\n\ninterface PassState {\n raw: GPURenderPassEncoder;\n ended: boolean;\n encoder: RhiCommandEncoder;\n // [[occlusion_query_set]] (research §2.1): the QuerySet injected via\n // GPURenderPassDescriptor.occlusionQuerySet at beginRenderPass time.\n // null means occlusion queries are unavailable in this pass.\n occlusionQuerySet: QuerySet | null;\n // [[occlusion_query_active]] (research §2.1): true when a beginOcclusionQuery\n // has been issued without a matching endOcclusionQuery yet. Spec normative:\n // pairs cannot nest.\n occlusionQueryActive: boolean;\n // queryIndex written by a previous beginOcclusionQuery in this pass; spec\n // normative: a queryIndex written previously in this pass cannot be reused\n // (cross-pass reuse on the same querySet is legal per dawn `Rewrite` mode).\n occlusionQueryWritten: Set<number>;\n}\n\n/** WeakMap that tracks raw GPUQuerySet for createQuerySet handles so the shim\n * can read `.count` for queryIndex bounds checking (research §2.1 step 2). */\nconst QUERY_SET_RAW_MAP: WeakMap<QuerySet, GPUQuerySet> = new WeakMap();\nconst QUERY_SET_DESTROYED_MAP: WeakMap<QuerySet, { destroyed: boolean }> = new WeakMap();\n\n/**\n * WeakMap that tracks Buffer metadata (size + usage) so resolveQuerySet (and\n * other shim entry points) can validate spec preconditions before forwarding\n * to the raw GPU (research §2.3 destination.usage / destinationOffset bounds).\n *\n * usage is the bitmask passed at createBuffer time; size is `desc.size` (the\n * underlying GPUBuffer.size is also readable but the shim records the\n * descriptor-level size for parity with TextureMeta).\n */\ninterface BufferMeta {\n readonly size: number;\n readonly usage: GPUBufferUsageFlags;\n /**\n * Per-handle lifecycle marker for `RhiDevice.destroyBuffer` fail-fast\n * (feat-20260612 D-7). Mutated to `true` by the first successful\n * `destroyBuffer(buf)` call; a second destroy on the same handle reads\n * the flag and surfaces `Result.err({ code: 'destroy-after-destroy' })`\n * rather than forwarding to the underlying spec idempotent void.\n */\n destroyed: boolean;\n}\nconst BUFFER_META_MAP: WeakMap<Buffer, BufferMeta> = new WeakMap();\n/** GPUBufferUsage.QUERY_RESOLVE bit (W3C WebGPU §3.5.2 GPUBufferUsage). */\nconst BUFFER_USAGE_QUERY_RESOLVE = 0x200;\n/** Spec normative resolve alignment (research §2.3 step 6 +\n * kQueryResolveAlignment in dawn). */\nconst QUERY_RESOLVE_ALIGNMENT = 256;\n\n/**\n * Get the underlying GPUDevice associated with a RhiDevice.\n *\n * @internal\n *\n * Single-point escape hatch (D-S1 / feat-20260508-rhi-surface-completion).\n * The `_internal_` prefix + `@internal` JSDoc tag mark this as engine-internal\n * plumbing; the only sanctioned consumer is\n * `apps/hello/triangle/src/main.ts:96` which threads the raw GPUDevice into\n * the host's internal canvas-device configuration slot so the canvas\n * `GPUCanvasContext.configure({device})` slot keeps working\n * (GPUCanvasContext is outside the RHI surface). Every other engine path\n * goes through the RHI interface.\n *\n * Future: deprecated once `feat-future-rhi-adapter-surface` lands a\n * `RhiCanvasContext` abstraction; this function will be removed at that\n * closure. AC-08 grep gate keeps further callers out via word-boundary\n * `\\bgetRawDevice\\b` allow-list (see apps/hello/triangle/scripts/ac-08-grep-gate.mjs).\n */\nexport function _internal_getRawDevice(device: RhiDevice): GPUDevice | undefined {\n return RAW_DEVICE_MAP.get(device);\n}\n\n// Caps probe — split by spec-feature gate vs mandatory-but-spec-noncompliant\n// fallback (m1-1-b scope-amend, plan §6 D-2 gap):\n//\n// * Optional spec features (`rg11b10ufloat-renderable`,\n// `float32-filterable`) carry an authoritative `device.features.has(...)`\n// answer. A `createTexture` probe on the unsupported format triggers a\n// WebGPU validation error which the dawn / Chrome implementations\n// fan out via `device.onuncapturederror` even when caught by JS try /\n// catch — the SUT-level `onerror-gate` (apps/shared/src/onerror-gate.ts)\n// observes that channel and turns a green-on-paper probe into a CI red\n// `limit-exceeded` error. Solution: gate the probe by `features.has(...)`\n// first and skip the destructive `createTexture` call entirely when the\n// feature is absent.\n//\n// * `rgba16float` is mandatory `RENDER_ATTACHMENT` per spec but observed\n// unreliable on WebKit — exactly the AC-02 motivation. Keep the real\n// `createTexture` probe here: any browser declaring it but rejecting at\n// `createTexture` time deserves a `false` cap, and a violation under\n// `rgba16float` would ALREADY break HDR / IBL paths so the\n// onuncapturederror fan-out is correctly diagnostic, not noise.\n\nfunction probeRgba16floatRenderable(device: GPUDevice): boolean {\n let tex: GPUTexture | undefined;\n try {\n tex = device.createTexture({\n label: 'forgeax-caps-probe-rgba16float-renderable',\n format: 'rgba16float',\n usage: 16, // GPUTextureUsage.RENDER_ATTACHMENT\n size: [1, 1, 1],\n });\n return true;\n } catch {\n return false;\n } finally {\n tex?.destroy?.();\n }\n}\n\nfunction probeRg11b10ufloatRenderable(device: GPUDevice, features: GPUSupportedFeatures): boolean {\n // Feature-gated: `rg11b10ufloat-renderable` is an optional feature per spec.\n // Skip the destructive createTexture probe when the feature is absent so the\n // dawn / Chrome backend's onuncapturederror channel does not fire (CI gate).\n if (!features.has('rg11b10ufloat-renderable' as GPUFeatureName)) return false;\n let tex: GPUTexture | undefined;\n try {\n tex = device.createTexture({\n label: 'forgeax-caps-probe-rg11b10ufloat-renderable',\n format: 'rg11b10ufloat',\n usage: 16, // GPUTextureUsage.RENDER_ATTACHMENT\n size: [1, 1, 1],\n });\n return true;\n } catch {\n return false;\n } finally {\n tex?.destroy?.();\n }\n}\n\nfunction probeFloat32Filterable(device: GPUDevice, features: GPUSupportedFeatures): boolean {\n // Feature-gated: `float32-filterable` is an optional feature per spec.\n // The bind-group-layout validation below would trigger\n // onuncapturederror when the feature is absent.\n if (!features.has('float32-filterable' as GPUFeatureName)) return false;\n try {\n device.createBindGroupLayout({\n entries: [\n { binding: 0, visibility: 2, sampler: { type: 'filtering' } }, // GPUShaderStage.FRAGMENT = 2\n { binding: 1, visibility: 2, texture: { sampleType: 'float' } },\n ],\n });\n device.createSampler({ minFilter: 'linear', magFilter: 'linear' });\n return true;\n } catch {\n return false;\n }\n}\n\n/** Probe the 11 caps fields from GPUDevice.features + GPUDevice.limits\n * (charter proposition 5). 4 new fields (samplerAliasing /\n * firstInstanceIndirect / storageBuffer / storageTexture) added by\n * feat-20260511-rhi-spec-realign-aggressive w19 per D-P3 + research R-03\n * §3.1 mapping matrix. 3 new HDR / filterable caps fields\n * (rgba16floatRenderable / rg11b10ufloatRenderable / float32Filterable)\n * added by feat-20260608-rhi-hdr-renderable-caps-and-warn-once M1 per\n * D-1 + D-2 + D-2.1. */\nfunction deriveCaps(\n rawDevice: GPUDevice,\n features: GPUSupportedFeatures,\n limits: GPUSupportedLimits,\n): RhiCaps {\n const has = (name: string): boolean => features.has(name as GPUFeatureName);\n // Texture-compression three-way caps (M4 w26): derived from adapter.features\n // per-compression-format, replacing the single rolled-up boolean.\n // D-8: no hand-assigned true/false literals; all derived via has(...) from\n // the features Set.\n const textureCompressionBc = has('texture-compression-bc');\n const textureCompressionEtc2 = has('texture-compression-etc2');\n const textureCompressionAstc = has('texture-compression-astc');\n // HDR renderable + filterable caps (m1-1-b: split probe by spec-feature gate\n // vs mandatory-but-noncompliant fallback). `rgba16float` is mandatory\n // `RENDER_ATTACHMENT` per spec but unreliable on WebKit — keep the real\n // probe (AC-02 motivation). `rg11b10ufloat-renderable` and `float32-\n // filterable` carry authoritative `features.has(...)` answers; gate by\n // feature first to avoid fan-out via `device.onuncapturederror` (apps/\n // shared/src/onerror-gate.ts) when the optional feature is absent.\n const hdrCaps = {\n rgba16floatRenderable: probeRgba16floatRenderable(rawDevice),\n rg11b10ufloatRenderable: probeRg11b10ufloatRenderable(rawDevice, features),\n float32Filterable: probeFloat32Filterable(rawDevice, features),\n };\n return {\n backendKind: 'webgpu' as const,\n compute: true, // WebGPU spec mandates compute-pipeline support.\n timestampQuery: has('timestamp-query'),\n timestampPeriodNanoseconds: has('timestamp-query') ? 1 : null,\n indirectDrawing: true, // WebGPU spec mandates drawIndirect / drawIndexedIndirect.\n textureCompressionBc,\n textureCompressionEtc2,\n textureCompressionAstc,\n multiDrawIndirect: false, // wgpu native extension; unavailable on WebGPU browser path.\n pushConstants: false, // wgpu native extension; unavailable on WebGPU browser path.\n textureBindingArray: false, // wgpu native extension; unavailable on WebGPU browser path.\n // 4 new fields (D-P3 / R-03 §3.1):\n samplerAliasing: true, // spec mandatory on browser backends.\n firstInstanceIndirect: has('indirect-first-instance'),\n storageBuffer: (limits.maxStorageBuffersPerShaderStage ?? 0) > 0,\n storageTexture: (limits.maxStorageTexturesPerShaderStage ?? 0) > 0,\n // HDR / filterable caps (feat-20260608 M1):\n ...hdrCaps,\n maxColorAttachments: limits.maxColorAttachments ?? 4,\n };\n}\n\n/**\n * Build a RhiRenderPassEncoder around a raw GPURenderPassEncoder (w5).\n *\n * - 14 real-path methods forward to GPURenderPassEncoder.\n * - 3 placeholders (executeBundles / beginOcclusionQuery / endOcclusionQuery)\n * return Result.err({ code: 'rhi-not-available' }) per D-S4.\n * - end() flips PassState.ended so the encoder finish() can detect a\n * render-pass-not-ended condition (D-S3 template 2).\n */\nfunction makeRenderPassEncoder(\n rawPass: GPURenderPassEncoder,\n encoder: RhiCommandEncoder,\n occlusionQuerySet: QuerySet | null,\n): RhiRenderPassEncoder {\n const pass: RhiRenderPassEncoder = {\n setPipeline(pipeline: RenderPipeline): void {\n rawPass.setPipeline(pipeline as unknown as GPURenderPipeline);\n },\n setVertexBuffer(\n slot: number,\n buffer: Buffer,\n offset?: number | undefined,\n size?: number | undefined,\n ): void {\n // M5 / w35: resolve forgeax Buffer wrapper to raw GPUBuffer.\n const rawBuf = BUFFER_RAW_MAP.get(buffer) ?? (buffer as unknown as GPUBuffer);\n rawPass.setVertexBuffer(slot, rawBuf, offset, size);\n },\n setIndexBuffer(\n buffer: Buffer,\n format: 'uint16' | 'uint32',\n offset?: number | undefined,\n size?: number | undefined,\n ): void {\n // M5 / w35: resolve forgeax Buffer wrapper to raw GPUBuffer.\n const rawBuf = BUFFER_RAW_MAP.get(buffer) ?? (buffer as unknown as GPUBuffer);\n rawPass.setIndexBuffer(rawBuf, format, offset, size);\n },\n setBindGroup(\n index: number,\n bindGroup: BindGroup,\n arg3?: readonly number[] | Uint32Array | undefined,\n arg4?: number | undefined,\n arg5?: number | undefined,\n ): void {\n // Two overload forms (D-S4 setBindGroup):\n // (a) (index, bindGroup, dynamicOffsets?: readonly number[])\n // (b) (index, bindGroup, dynamicOffsetsData: Uint32Array,\n // dynamicOffsetsDataStart, dynamicOffsetsDataLength)\n if (arg3 instanceof Uint32Array) {\n rawPass.setBindGroup(\n index,\n bindGroup as unknown as GPUBindGroup,\n arg3,\n arg4 ?? 0,\n arg5 ?? arg3.length,\n );\n } else if (arg3 === undefined) {\n rawPass.setBindGroup(index, bindGroup as unknown as GPUBindGroup);\n } else {\n rawPass.setBindGroup(index, bindGroup as unknown as GPUBindGroup, arg3);\n }\n },\n draw(\n vertexCount: number,\n instanceCount?: number | undefined,\n firstVertex?: number | undefined,\n firstInstance?: number | undefined,\n ): void {\n rawPass.draw(vertexCount, instanceCount, firstVertex, firstInstance);\n },\n drawIndexed(\n indexCount: number,\n instanceCount?: number | undefined,\n firstIndex?: number | undefined,\n baseVertex?: number | undefined,\n firstInstance?: number | undefined,\n ): void {\n rawPass.drawIndexed(indexCount, instanceCount, firstIndex, baseVertex, firstInstance);\n },\n setViewport(\n x: number,\n y: number,\n w: number,\n h: number,\n minDepth: number,\n maxDepth: number,\n ): void {\n rawPass.setViewport(x, y, w, h, minDepth, maxDepth);\n },\n setScissorRect(x: number, y: number, w: number, h: number): void {\n rawPass.setScissorRect(x, y, w, h);\n },\n setBlendConstant(color: GPUColor): void {\n rawPass.setBlendConstant(color);\n },\n setStencilReference(reference: number): void {\n rawPass.setStencilReference(reference);\n },\n drawIndirect(indirectBuffer: Buffer, indirectOffset: number): void {\n const rawBuf = BUFFER_RAW_MAP.get(indirectBuffer) ?? (indirectBuffer as unknown as GPUBuffer);\n rawPass.drawIndirect(rawBuf, indirectOffset);\n },\n drawIndexedIndirect(indirectBuffer: Buffer, indirectOffset: number): void {\n const rawBuf = BUFFER_RAW_MAP.get(indirectBuffer) ?? (indirectBuffer as unknown as GPUBuffer);\n rawPass.drawIndexedIndirect(rawBuf, indirectOffset);\n },\n pushDebugGroup(groupLabel: string): void {\n rawPass.pushDebugGroup(groupLabel);\n },\n popDebugGroup(): void {\n rawPass.popDebugGroup();\n },\n insertDebugMarker(markerLabel: string): void {\n rawPass.insertDebugMarker(markerLabel);\n },\n executeBundles(_bundles: Iterable<unknown>): Result<void, RhiError> {\n return err(\n new RhiErrorClass({\n code: 'rhi-not-available',\n expected: 'render bundle creation requires future closed loop',\n hint: 'see feat-future-rhi-render-bundle',\n }),\n );\n },\n beginOcclusionQuery(queryIndex: number): Result<void, RhiError> {\n const state = PASS_STATE.get(pass);\n if (state === undefined) {\n return err(\n new RhiErrorClass({\n code: 'webgpu-runtime-error',\n expected: 'render pass state must exist',\n hint: 'beginOcclusionQuery called on an untracked render pass',\n }),\n );\n }\n // Step 1 (research §2.1): [[occlusion_query_set]] != null.\n if (state.occlusionQuerySet === null) {\n return err(\n new RhiErrorClass({\n code: 'webgpu-runtime-error',\n expected: 'GPURenderPassDescriptor.occlusionQuerySet must be set',\n hint: 'pass occlusionQuerySet in RenderPassDescriptor before beginOcclusionQuery',\n }),\n );\n }\n // Step 4 (research §2.1): [[occlusion_query_active]] == false (no nesting).\n // K-2: nested begin maps to webgpu-runtime-error (NOT a new code).\n if (state.occlusionQueryActive) {\n return err(\n new RhiErrorClass({\n code: 'webgpu-runtime-error',\n expected:\n '[[occlusion_query_active]] == false; pair beginOcclusionQuery / endOcclusionQuery',\n hint: 'call endOcclusionQuery() before beginOcclusionQuery() again; occlusion queries cannot nest (spec §render-passes)',\n }),\n );\n }\n // Step 2 (research §2.1): queryIndex < querySet.count.\n const rawQs = QUERY_SET_RAW_MAP.get(state.occlusionQuerySet);\n const qsCount =\n rawQs !== undefined && typeof rawQs.count === 'number'\n ? rawQs.count\n : Number.MAX_SAFE_INTEGER;\n if (queryIndex < 0 || queryIndex >= qsCount) {\n return err(\n new RhiErrorClass({\n code: 'webgpu-runtime-error',\n expected: 'queryIndex < querySet.count',\n hint: `got queryIndex=${queryIndex}; querySet.count=${qsCount}`,\n }),\n );\n }\n // Step 3 (research §2.1): queryIndex not yet written in this pass.\n // Cross-pass reuse on the same querySet is legal (dawn `Rewrite` mode).\n if (state.occlusionQueryWritten.has(queryIndex)) {\n return err(\n new RhiErrorClass({\n code: 'webgpu-runtime-error',\n expected: 'queryIndex must not have been written in this pass',\n hint: `queryIndex=${queryIndex} was already written; cross-pass reuse on the same querySet is legal but in-pass reuse is not (spec §queries)`,\n }),\n );\n }\n try {\n rawPass.beginOcclusionQuery(queryIndex);\n state.occlusionQueryActive = true;\n state.occlusionQueryWritten.add(queryIndex);\n return ok(undefined);\n } catch (e) {\n const message = e instanceof Error ? e.message : String(e);\n return err(\n new RhiErrorClass({\n code: 'webgpu-runtime-error',\n expected: 'underlying GPURenderPassEncoder.beginOcclusionQuery to succeed',\n hint: `beginOcclusionQuery raised: ${message}`,\n }),\n );\n }\n },\n endOcclusionQuery(): Result<void, RhiError> {\n const state = PASS_STATE.get(pass);\n if (state === undefined) {\n return err(\n new RhiErrorClass({\n code: 'webgpu-runtime-error',\n expected: 'render pass state must exist',\n hint: 'endOcclusionQuery called on an untracked render pass',\n }),\n );\n }\n // Spec normative (research §2.1): [[occlusion_query_active]] must be true.\n // K-2: end without active begin maps to render-pass-not-ended (existing\n // 14-member union).\n if (!state.occlusionQueryActive) {\n return renderPassNotEnded();\n }\n try {\n rawPass.endOcclusionQuery();\n state.occlusionQueryActive = false;\n return ok(undefined);\n } catch (e) {\n const message = e instanceof Error ? e.message : String(e);\n return err(\n new RhiErrorClass({\n code: 'webgpu-runtime-error',\n expected: 'underlying GPURenderPassEncoder.endOcclusionQuery to succeed',\n hint: `endOcclusionQuery raised: ${message}`,\n }),\n );\n }\n },\n end(): void {\n const state = PASS_STATE.get(pass);\n if (state !== undefined) {\n state.ended = true;\n }\n rawPass.end();\n // Clear active-pass tracking on the owning encoder.\n const encState = ENCODER_STATE.get(encoder);\n if (encState !== undefined && encState.activePass === pass) {\n encState.activePass = null;\n }\n },\n };\n PASS_STATE.set(pass, {\n raw: rawPass,\n ended: false,\n encoder,\n occlusionQuerySet,\n occlusionQueryActive: false,\n occlusionQueryWritten: new Set<number>(),\n });\n return pass;\n}\n\nconst ENCODER_FINISHED_ERROR_ARGS = {\n code: 'command-encoder-finished' as const,\n expected: 'command encoder must not be finished before recording new commands',\n hint: 'create a new command encoder via device.createCommandEncoder() for each frame; do not reuse a finished encoder',\n};\n\nfunction throwIfFinished(state: EncoderState | undefined): void {\n if (state?.finished) {\n throw new RhiErrorClass(ENCODER_FINISHED_ERROR_ARGS);\n }\n}\n\nfunction rawTextureView(view: TextureView): GPUTextureView {\n return TEXTURE_VIEW_RAW_MAP.get(view) ?? (view as unknown as GPUTextureView);\n}\n\nfunction mirrorRenderPassDescriptor(desc: RenderPassDescriptor): GPURenderPassDescriptor {\n const colorAttachments: Array<GPURenderPassColorAttachment | null> = [];\n for (const attachment of desc.colorAttachments) {\n if (attachment === null || attachment === undefined) {\n colorAttachments.push(null);\n continue;\n }\n if (attachment.loadOp === undefined || attachment.storeOp === undefined) {\n throw new TypeError('RHI render-pass color attachments require loadOp and storeOp');\n }\n colorAttachments.push({\n view: rawTextureView(attachment.view),\n ...(attachment.depthSlice === undefined ? {} : { depthSlice: attachment.depthSlice }),\n ...(attachment.resolveTarget === undefined\n ? {}\n : { resolveTarget: rawTextureView(attachment.resolveTarget) }),\n ...(attachment.clearValue === undefined ? {} : { clearValue: attachment.clearValue }),\n loadOp: attachment.loadOp,\n storeOp: attachment.storeOp,\n });\n }\n\n return {\n ...(desc.label === undefined ? {} : { label: desc.label }),\n colorAttachments,\n ...(desc.depthStencilAttachment === undefined\n ? {}\n : {\n depthStencilAttachment: {\n view: rawTextureView(desc.depthStencilAttachment.view),\n ...(desc.depthStencilAttachment.depthClearValue === undefined\n ? {}\n : { depthClearValue: desc.depthStencilAttachment.depthClearValue }),\n ...(desc.depthStencilAttachment.depthLoadOp === undefined\n ? {}\n : { depthLoadOp: desc.depthStencilAttachment.depthLoadOp }),\n ...(desc.depthStencilAttachment.depthStoreOp === undefined\n ? {}\n : { depthStoreOp: desc.depthStencilAttachment.depthStoreOp }),\n ...(desc.depthStencilAttachment.depthReadOnly === undefined\n ? {}\n : { depthReadOnly: desc.depthStencilAttachment.depthReadOnly }),\n ...(desc.depthStencilAttachment.stencilClearValue === undefined\n ? {}\n : { stencilClearValue: desc.depthStencilAttachment.stencilClearValue }),\n ...(desc.depthStencilAttachment.stencilLoadOp === undefined\n ? {}\n : { stencilLoadOp: desc.depthStencilAttachment.stencilLoadOp }),\n ...(desc.depthStencilAttachment.stencilStoreOp === undefined\n ? {}\n : { stencilStoreOp: desc.depthStencilAttachment.stencilStoreOp }),\n ...(desc.depthStencilAttachment.stencilReadOnly === undefined\n ? {}\n : { stencilReadOnly: desc.depthStencilAttachment.stencilReadOnly }),\n },\n }),\n ...(desc.occlusionQuerySet === undefined\n ? {}\n : {\n occlusionQuerySet:\n QUERY_SET_RAW_MAP.get(desc.occlusionQuerySet) ??\n (desc.occlusionQuerySet as unknown as GPUQuerySet),\n }),\n ...(desc.timestampWrites === undefined\n ? {}\n : {\n timestampWrites: {\n querySet:\n QUERY_SET_RAW_MAP.get(desc.timestampWrites.querySet) ??\n (desc.timestampWrites.querySet as unknown as GPUQuerySet),\n ...(desc.timestampWrites.beginningOfPassWriteIndex === undefined\n ? {}\n : { beginningOfPassWriteIndex: desc.timestampWrites.beginningOfPassWriteIndex }),\n ...(desc.timestampWrites.endOfPassWriteIndex === undefined\n ? {}\n : { endOfPassWriteIndex: desc.timestampWrites.endOfPassWriteIndex }),\n },\n }),\n ...(desc.maxDrawCount === undefined ? {} : { maxDrawCount: desc.maxDrawCount }),\n };\n}\n\nfunction mirrorRenderPipelineDescriptor(\n desc: RenderPipelineDescriptor,\n): GPURenderPipelineDescriptor {\n const vertex: GPUVertexState = {\n module: desc.vertex.module as unknown as GPUShaderModule,\n ...(desc.vertex.buffers === undefined ? {} : { buffers: Array.from(desc.vertex.buffers) }),\n ...(desc.vertex.entryPoint === undefined ? {} : { entryPoint: desc.vertex.entryPoint }),\n ...(desc.vertex.constants === undefined ? {} : { constants: desc.vertex.constants }),\n };\n const fragment: GPUFragmentState | undefined =\n desc.fragment === undefined\n ? undefined\n : {\n module: desc.fragment.module as unknown as GPUShaderModule,\n targets: Array.from(desc.fragment.targets),\n ...(desc.fragment.entryPoint === undefined\n ? {}\n : { entryPoint: desc.fragment.entryPoint }),\n ...(desc.fragment.constants === undefined ? {} : { constants: desc.fragment.constants }),\n };\n return {\n ...(desc.label === undefined ? {} : { label: desc.label }),\n layout: desc.layout === 'auto' ? 'auto' : (desc.layout as unknown as GPUPipelineLayout),\n vertex,\n ...(desc.primitive === undefined ? {} : { primitive: desc.primitive }),\n ...(desc.depthStencil === undefined ? {} : { depthStencil: desc.depthStencil }),\n ...(desc.multisample === undefined ? {} : { multisample: desc.multisample }),\n ...(fragment === undefined ? {} : { fragment }),\n };\n}\n\n/**\n * Build a RhiCommandEncoder around a raw GPUCommandEncoder (w3).\n *\n * Lifecycle:\n * - finish() flips finished=true and returns CommandBuffer once.\n * - subsequent recording calls (beginRenderPass / copyXxx / clearBuffer /\n * finish itself) return Result.err({ code: 'command-encoder-finished' })\n * for those methods that return Result; the void-returning methods throw\n * the structured error so AI users observe the failure (charter\n * proposition 4 explicit failure).\n * - render-pass-not-ended is detected by tracking activePass; finish()\n * while a pass has not been end()-ed returns the structured error.\n */\nfunction makeCommandEncoder(\n rawEncoder: GPUCommandEncoder,\n caps: { readonly timestampQuery: boolean },\n fireFeatureNotEnabled: (featureName: string, hint: string) => void,\n): RhiCommandEncoder {\n function mirrorComputePassDescriptor(\n desc: ComputePassDescriptor | undefined,\n ): GPUComputePassDescriptor | undefined {\n if (desc === undefined) return undefined;\n const out = mirror(desc, ['label']);\n if ('timestampWrites' in desc) {\n const writes = desc.timestampWrites;\n out.timestampWrites =\n writes === undefined\n ? undefined\n : {\n querySet:\n QUERY_SET_RAW_MAP.get(writes.querySet) ??\n (writes.querySet as unknown as GPUQuerySet),\n ...(writes.beginningOfPassWriteIndex === undefined\n ? {}\n : { beginningOfPassWriteIndex: writes.beginningOfPassWriteIndex }),\n ...(writes.endOfPassWriteIndex === undefined\n ? {}\n : { endOfPassWriteIndex: writes.endOfPassWriteIndex }),\n };\n }\n return out as unknown as GPUComputePassDescriptor;\n }\n\n const enc: RhiCommandEncoder = {\n beginRenderPass(desc: RenderPassDescriptor): RhiRenderPassEncoder {\n const state = ENCODER_STATE.get(enc);\n throwIfFinished(state);\n const rawPass = rawEncoder.beginRenderPass(mirrorRenderPassDescriptor(desc));\n // Extract occlusionQuerySet from the descriptor (research §2.2:\n // RPDesc.occlusionQuerySet is the injection point; the render pass\n // PassState.[[occlusion_query_set]] mirrors it). The forgeax\n // RenderPassDescriptor declares occlusionQuerySet as `QuerySet |\n // undefined`; the raw GPU descriptor is structurally compatible.\n const occlusionQuerySet = desc.occlusionQuerySet ?? null;\n const pass = makeRenderPassEncoder(rawPass, enc, occlusionQuerySet);\n if (state !== undefined) state.activePass = pass;\n return pass;\n },\n beginComputePass(desc?: ComputePassDescriptor | undefined): RhiComputePassEncoder {\n const state = ENCODER_STATE.get(enc);\n throwIfFinished(state);\n const rawDescriptor = mirrorComputePassDescriptor(desc);\n const rawPass =\n rawDescriptor === undefined\n ? rawEncoder.beginComputePass()\n : rawEncoder.beginComputePass(rawDescriptor);\n const pass: RhiComputePassEncoder = {\n setPipeline(pipeline) {\n rawPass.setPipeline(pipeline as unknown as GPUComputePipeline);\n },\n setBindGroup(index, bindGroup, dynamicOffsets) {\n if (dynamicOffsets === undefined) {\n rawPass.setBindGroup(index, bindGroup as unknown as GPUBindGroup);\n } else {\n rawPass.setBindGroup(index, bindGroup as unknown as GPUBindGroup, dynamicOffsets);\n }\n },\n dispatchWorkgroups(x, y, z) {\n rawPass.dispatchWorkgroups(x, y, z);\n },\n dispatchWorkgroupsIndirect(indirectBuffer, indirectOffset) {\n const rawBuffer =\n BUFFER_RAW_MAP.get(indirectBuffer) ?? (indirectBuffer as unknown as GPUBuffer);\n rawPass.dispatchWorkgroupsIndirect(rawBuffer, indirectOffset);\n },\n end() {\n rawPass.end();\n },\n };\n return pass;\n },\n copyBufferToBuffer(\n source: Buffer,\n arg2: number | Buffer,\n arg3?: Buffer | number | undefined,\n arg4?: number | undefined,\n arg5?: number | undefined,\n ): void {\n const state = ENCODER_STATE.get(enc);\n throwIfFinished(state);\n // M5 / w35: the forgeax Buffer is a wrapper (not the raw GPUBuffer);\n // resolve through BUFFER_RAW_MAP before delegating.\n const rawSource = BUFFER_RAW_MAP.get(source) ?? (source as unknown as GPUBuffer);\n // Two overloads (research F-1):\n // (a) (src, dst, size?) - 3-arg shorthand\n // (b) (src, srcOffset, dst, dstOffset, size) - 5-arg full form\n if (typeof arg2 === 'number') {\n // 5-arg form\n const dst = arg3 as Buffer;\n const rawDst = BUFFER_RAW_MAP.get(dst) ?? (dst as unknown as GPUBuffer);\n rawEncoder.copyBufferToBuffer(rawSource, arg2, rawDst, arg4 ?? 0, arg5 ?? 0);\n } else {\n // 3-arg shorthand\n const dst = arg2 as Buffer;\n const rawDst = BUFFER_RAW_MAP.get(dst) ?? (dst as unknown as GPUBuffer);\n rawEncoder.copyBufferToBuffer(rawSource, rawDst, arg3 as number | undefined);\n }\n },\n copyBufferToTexture(\n source: GPUTexelCopyBufferInfo,\n destination: GPUTexelCopyTextureInfo,\n copySize: GPUExtent3DStrict,\n ): void {\n const state = ENCODER_STATE.get(enc);\n throwIfFinished(state);\n const rawSrc = {\n ...source,\n buffer:\n BUFFER_RAW_MAP.get(source.buffer as unknown as Buffer) ??\n (source.buffer as unknown as GPUBuffer),\n };\n rawEncoder.copyBufferToTexture(rawSrc, destination, copySize);\n },\n copyTextureToBuffer(\n source: GPUTexelCopyTextureInfo,\n destination: GPUTexelCopyBufferInfo,\n copySize: GPUExtent3DStrict,\n ): void {\n const state = ENCODER_STATE.get(enc);\n throwIfFinished(state);\n const rawDst = {\n ...destination,\n buffer:\n BUFFER_RAW_MAP.get(destination.buffer as unknown as Buffer) ??\n (destination.buffer as unknown as GPUBuffer),\n };\n rawEncoder.copyTextureToBuffer(source, rawDst, copySize);\n },\n copyTextureToTexture(\n source: GPUTexelCopyTextureInfo,\n destination: GPUTexelCopyTextureInfo,\n copySize: GPUExtent3DStrict,\n ): void {\n const state = ENCODER_STATE.get(enc);\n throwIfFinished(state);\n rawEncoder.copyTextureToTexture(source, destination, copySize);\n },\n clearBuffer(buffer: Buffer, offset?: number | undefined, size?: number | undefined): void {\n const state = ENCODER_STATE.get(enc);\n throwIfFinished(state);\n // M5 / w35: resolve forgeax Buffer wrapper to raw GPUBuffer.\n const rawBuf = BUFFER_RAW_MAP.get(buffer) ?? (buffer as unknown as GPUBuffer);\n rawEncoder.clearBuffer(rawBuf, offset, size);\n },\n resolveQuerySet(\n querySet: QuerySet,\n firstQuery: number,\n queryCount: number,\n destination: Buffer,\n destinationOffset: number,\n ): Result<void, RhiError> {\n const state = ENCODER_STATE.get(enc);\n if (state?.finished) {\n return commandEncoderFinished();\n }\n // Step 6 (research §2.3): destinationOffset is a multiple of 256.\n // K-2: alignment violation maps to webgpu-runtime-error.\n if (destinationOffset % QUERY_RESOLVE_ALIGNMENT !== 0) {\n return err(\n new RhiErrorClass({\n code: 'webgpu-runtime-error',\n expected: 'destinationOffset % 256 == 0 (spec normative)',\n hint: `got destinationOffset=${destinationOffset}; align to a multiple of 256 bytes (kQueryResolveAlignment)`,\n }),\n );\n }\n // Step 3 (research §2.3): destination.usage contains QUERY_RESOLVE.\n const dstMeta = BUFFER_META_MAP.get(destination);\n if (dstMeta !== undefined && (dstMeta.usage & BUFFER_USAGE_QUERY_RESOLVE) === 0) {\n return err(\n new RhiErrorClass({\n code: 'webgpu-runtime-error',\n expected: 'destination.usage must contain QUERY_RESOLVE',\n hint: `got destination.usage=0x${dstMeta.usage.toString(16)}; create the buffer with GPUBufferUsage.QUERY_RESOLVE (0x200)`,\n }),\n );\n }\n // Steps 4 + 5 (research §2.3): firstQuery + queryCount <= querySet.count\n // (which subsumes firstQuery < count as a derived constraint).\n const rawQs = QUERY_SET_RAW_MAP.get(querySet);\n const qsCount =\n rawQs !== undefined && typeof rawQs.count === 'number'\n ? rawQs.count\n : Number.MAX_SAFE_INTEGER;\n if (firstQuery < 0 || firstQuery + queryCount > qsCount) {\n return err(\n new RhiErrorClass({\n code: 'webgpu-runtime-error',\n expected: 'firstQuery + queryCount <= querySet.count',\n hint: `got firstQuery=${firstQuery}, queryCount=${queryCount}; querySet.count=${qsCount}`,\n }),\n );\n }\n // Step 7 (research §2.3): destinationOffset + 8 * queryCount <= dst.size.\n if (dstMeta !== undefined) {\n const requiredBytes = destinationOffset + 8 * queryCount;\n if (requiredBytes > dstMeta.size) {\n return err(\n new RhiErrorClass({\n code: 'webgpu-runtime-error',\n expected: 'destinationOffset + 8 * queryCount <= destination.size',\n hint: `got destinationOffset=${destinationOffset}, queryCount=${queryCount} (8 * queryCount = ${8 * queryCount}); destination.size=${dstMeta.size}`,\n }),\n );\n }\n }\n const rawQsHandle = QUERY_SET_RAW_MAP.get(querySet) ?? (querySet as unknown as GPUQuerySet);\n const rawDstHandle = BUFFER_RAW_MAP.get(destination) ?? (destination as unknown as GPUBuffer);\n return resolveTimestampQueries({\n rawEncoder,\n rawQuerySet: rawQsHandle,\n firstQuery,\n queryCount,\n rawDestination: rawDstHandle,\n destinationOffset,\n });\n },\n pushDebugGroup(groupLabel: string): void {\n rawEncoder.pushDebugGroup(groupLabel);\n },\n popDebugGroup(): void {\n rawEncoder.popDebugGroup();\n },\n insertDebugMarker(markerLabel: string): void {\n rawEncoder.insertDebugMarker(markerLabel);\n },\n writeTimestamp(querySet: QuerySet, queryIndex: number): void {\n // M5 / K-3 (research §2.4): timestamp-query feature gate. spec\n // writeTimestamp returns void; the forgeax form keeps the void shape\n // and fans out 'feature-not-enabled' through the engine onError\n // channel rather than wrapping in Result. When the capability is true,\n // a missing or throwing raw write is a structured runtime failure so a\n // Render capture cannot publish a fabricated interval.\n const state = ENCODER_STATE.get(enc);\n throwIfFinished(state);\n if (caps.timestampQuery !== true) {\n fireFeatureNotEnabled(\n 'timestamp-query',\n 'check device.caps.timestampQuery before calling writeTimestamp',\n );\n return;\n }\n const rawQs = QUERY_SET_RAW_MAP.get(querySet) ?? (querySet as unknown as GPUQuerySet);\n writeTimestamp({ rawEncoder, rawQuerySet: rawQs, queryIndex });\n },\n finish(): Result<CommandBuffer, RhiError> {\n const state = ENCODER_STATE.get(enc);\n if (state === undefined) {\n // Should not happen in practice; treat as a finished encoder.\n return commandEncoderFinished();\n }\n if (state.finished) {\n return commandEncoderFinished();\n }\n if (state.activePass !== null) {\n const passState = PASS_STATE.get(state.activePass);\n if (passState !== undefined && !passState.ended) {\n return renderPassNotEnded();\n }\n }\n const rawCommandBuffer = rawEncoder.finish();\n state.finished = true;\n const cb = rawCommandBuffer as unknown as CommandBuffer;\n COMMAND_BUFFER_RAW_MAP.set(cb, rawCommandBuffer);\n return ok(cb);\n },\n };\n ENCODER_STATE.set(enc, { raw: rawEncoder, finished: false, activePass: null });\n return enc;\n}\n\n// ============================================================================\n// M5 / w35 - Buffer wrapper (mapAsync / getMappedRange / unmap / mapState).\n// ============================================================================\n//\n// research §4.1 mapState 3-state enum + §4.2 mapAsync 8-validation +\n// §4.4 unmap detach. K-1 decision: mode is the raw GPUMapMode bitmask.\n// K-2 decision: alignment / mode-usage / detach faults all ride\n// 'webgpu-runtime-error' with structured .expected / .hint per F-3\n// ai-user-review carry-over.\n\n/** Spec normative GPUMapMode bits (research §4.2 step 7). */\nconst MAP_MODE_READ = 0x1;\nconst MAP_MODE_WRITE = 0x2;\n/** GPUBufferUsage MAP_READ / MAP_WRITE bits (research §4.2 step 9 / F-8 row 3). */\nconst BUFFER_USAGE_MAP_READ = 0x0001;\nconst BUFFER_USAGE_MAP_WRITE = 0x0002;\n\nfunction rangeError(args: { expected: string; hint: string }): Result<never, RhiError> {\n return err(\n new RhiErrorClass({\n code: 'webgpu-runtime-error',\n expected: args.expected,\n hint: args.hint,\n }),\n );\n}\n\n/**\n * Build a forgeax Buffer wrapper around a raw GPUBuffer (w35).\n *\n * The wrapper exposes the brand-only Buffer interface plus the M5 mapping\n * surface (mapAsync / getMappedRange / unmap + mapState getter).\n *\n * Validation policy (K-2 + research §4.2 + F-8 three rows):\n * - mapAsync rejects on 8 spec validation steps + F-8 row 1/3 with\n * 'webgpu-runtime-error' before delegating to raw mapAsync. The raw\n * mapAsync may still reject (driver-level validation); the shim wraps\n * such rejections via 'webgpu-runtime-error' carrying the underlying\n * message in .hint.\n * - getMappedRange rejects with 'webgpu-runtime-error' when mapState !==\n * 'mapped' (F-8 row 2 detach guard) before delegating.\n * - unmap is silent (spec normative; research §4.4) and resets the\n * internal mapState slot to 'unmapped'.\n *\n * The wrapper carries an internal mapState slot so the shim can detect F-8\n * row 1 / row 2 fast-path; the slot is initialized to 'mapped' when the\n * descriptor sets `mappedAtCreation:true` (research §4.3) and otherwise\n * starts at 'unmapped'.\n */\nfunction makeBufferWrapper(raw: GPUBuffer, size: number, usage: GPUBufferUsageFlags): Buffer {\n // Track mapState locally so the shim does not need to query raw.mapState\n // (the spec exposes it but for symmetry with the F-8 guard semantics we\n // mirror the slot in the wrapper).\n const initialState =\n typeof (raw as { mapState?: string }).mapState === 'string'\n ? (raw as { mapState: 'unmapped' | 'pending' | 'mapped' }).mapState\n : 'unmapped';\n let mapState: 'unmapped' | 'pending' | 'mapped' = initialState;\n const wrapper = {\n get mapState(): 'unmapped' | 'pending' | 'mapped' {\n // Prefer the raw slot if available so destroyed-buffer transitions\n // surface to AI users; fall back to the local slot for mocks that do\n // not expose mapState (mock buffers keep a logical mapState only).\n const rs = (raw as { mapState?: 'unmapped' | 'pending' | 'mapped' }).mapState;\n if (typeof rs === 'string') {\n mapState = rs;\n return rs;\n }\n return mapState;\n },\n async mapAsync(\n mode: GPUMapModeFlags,\n offset?: number | undefined,\n sizeArg?: number | undefined,\n ): Promise<Result<MappedBuffer, RhiError>> {\n // F-8 row 1: mapState must be 'unmapped' (research §4.2 step 1).\n const cur = wrapper.mapState;\n if (cur !== 'unmapped') {\n return rangeError({\n expected: 'buffer.mapState === \"unmapped\" before mapAsync',\n hint: `got mapState=${cur}; call buffer.unmap() before mapAsync, or wait for the previous mapAsync to settle`,\n });\n }\n const off = offset ?? 0;\n const rangeSize = sizeArg === undefined ? Math.max(0, size - off) : sizeArg;\n // step 4: offset % 8 == 0\n if (off % 8 !== 0) {\n return rangeError({\n expected: 'mapAsync offset % 8 == 0 (spec normative)',\n hint: `got offset=${off}; align offset to 8 bytes`,\n });\n }\n // step 5: rangeSize % 4 == 0\n if (rangeSize % 4 !== 0) {\n return rangeError({\n expected: 'mapAsync rangeSize % 4 == 0 (spec normative)',\n hint: `got rangeSize=${rangeSize}; align rangeSize to 4 bytes`,\n });\n }\n // step 6: offset + rangeSize <= size\n if (off + rangeSize > size) {\n return rangeError({\n expected: 'mapAsync offset + rangeSize <= buffer.size',\n hint: `got offset=${off}, rangeSize=${rangeSize}; buffer.size=${size}`,\n });\n }\n // step 7: mode contains only allowed bits\n const allowed = MAP_MODE_READ | MAP_MODE_WRITE;\n if ((mode & ~allowed) !== 0) {\n return rangeError({\n expected: 'mapAsync mode contains only READ or WRITE bits',\n hint: `got mode=0x${mode.toString(16)}; pass GPUMapMode.READ (0x1) or GPUMapMode.WRITE (0x2)`,\n });\n }\n // step 8: mode is exactly READ or WRITE (not both)\n if (mode !== MAP_MODE_READ && mode !== MAP_MODE_WRITE) {\n return rangeError({\n expected: 'mapAsync mode is exactly one of READ | WRITE (not both)',\n hint: `got mode=0x${mode.toString(16)}; pass GPUMapMode.READ (0x1) or GPUMapMode.WRITE (0x2), not the OR-combined mask`,\n });\n }\n // step 9: mode-usage cross-check (F-8 row 3)\n if ((mode & MAP_MODE_READ) !== 0 && (usage & BUFFER_USAGE_MAP_READ) === 0) {\n return rangeError({\n expected: 'mapAsync mode READ requires buffer.usage to contain MAP_READ',\n hint: `got mode=READ, buffer.usage=0x${usage.toString(16)}; create buffer with GPUBufferUsage.MAP_READ`,\n });\n }\n if ((mode & MAP_MODE_WRITE) !== 0 && (usage & BUFFER_USAGE_MAP_WRITE) === 0) {\n return rangeError({\n expected: 'mapAsync mode WRITE requires buffer.usage to contain MAP_WRITE',\n hint: `got mode=WRITE, buffer.usage=0x${usage.toString(16)}; create buffer with GPUBufferUsage.MAP_WRITE`,\n });\n }\n // Delegate to raw GPUBuffer; raw rejection wraps as webgpu-runtime-error.\n mapState = 'pending';\n try {\n if (typeof raw.mapAsync === 'function') {\n if (sizeArg === undefined && offset === undefined) {\n await raw.mapAsync(mode);\n } else if (sizeArg === undefined) {\n await raw.mapAsync(mode, off);\n } else {\n await raw.mapAsync(mode, off, sizeArg);\n }\n }\n mapState = 'mapped';\n // D-P2 #6: the structural wrapper carries both Buffer + MappedBuffer\n // members; on the success path we surface the same JS object typed as\n // the branded MappedBuffer (charter proposition 5: brand is structural,\n // no runtime cost).\n return ok(wrapper as unknown as MappedBuffer);\n } catch (e) {\n mapState = 'unmapped';\n const message = e instanceof Error ? e.message : String(e);\n return rangeError({\n expected: 'underlying GPUBuffer.mapAsync to succeed',\n hint: `mapAsync raised: ${message}`,\n });\n }\n },\n getMappedRange(\n offset?: number | undefined,\n sizeArg?: number | undefined,\n ): Result<ArrayBuffer, RhiError> {\n // F-8 row 2 detach guard: mapState must be 'mapped'.\n const cur = wrapper.mapState;\n if (cur !== 'mapped') {\n return rangeError({\n expected: 'buffer.mapState === \"mapped\" before getMappedRange',\n hint: 'call buffer.mapAsync(MODE) and await it before getMappedRange',\n });\n }\n try {\n if (typeof raw.getMappedRange !== 'function') {\n return rangeError({\n expected: 'underlying GPUBuffer.getMappedRange to be available',\n hint: 'mock or driver does not expose getMappedRange; use a real GPUBuffer',\n });\n }\n const view =\n sizeArg === undefined\n ? offset === undefined\n ? raw.getMappedRange()\n : raw.getMappedRange(offset)\n : raw.getMappedRange(offset ?? 0, sizeArg);\n return ok(view);\n } catch (e) {\n const message = e instanceof Error ? e.message : String(e);\n return rangeError({\n expected: 'underlying GPUBuffer.getMappedRange to succeed',\n hint: `getMappedRange raised: ${message}`,\n });\n }\n },\n unmap(): void {\n // Spec normative silent no-op (research §4.4): unmap on a destroyed or\n // already-unmapped buffer must NOT throw / return an error.\n try {\n if (typeof raw.unmap === 'function') {\n raw.unmap();\n }\n } catch {\n // swallow per spec; the forgeax form does not surface unmap failures.\n }\n mapState = 'unmapped';\n },\n } as unknown as Buffer;\n return wrapper;\n}\n\n/**\n * Build a RhiQueue around a raw GPUQueue (w6).\n *\n * Real-path implementation:\n * - submit forwards to rawQueue.submit; failures (validation / destroyed\n * resource references) wrap to 'queue-submit-failed' (D-S3 #3).\n * - writeBuffer validates offset alignment + bounds before forwarding;\n * out-of-bounds writes return 'queue-write-buffer-out-of-bounds' (D-S3 #4).\n */\nfunction makeQueue(rawQueue: GPUQueue): RhiQueue {\n return {\n writeBuffer(\n buffer: Buffer,\n bufferOffset: number,\n data: ArrayBufferView | ArrayBuffer,\n dataOffset?: number | undefined,\n size?: number | undefined,\n ): Result<void, RhiError> {\n const rawBuffer = BUFFER_RAW_MAP.get(buffer) ?? (buffer as unknown as GPUBuffer);\n const bufferSize =\n typeof (rawBuffer as { size?: number }).size === 'number'\n ? (rawBuffer as { size: number }).size\n : Number.MAX_SAFE_INTEGER;\n // 4-byte alignment validation (W3C WebGPU 23.2 writeBuffer).\n if (bufferOffset % 4 !== 0) {\n return queueWriteBufferOutOfBounds({\n offset: bufferOffset,\n byteLength:\n data instanceof ArrayBuffer ? data.byteLength : (data as ArrayBufferView).byteLength,\n bufferSize,\n });\n }\n const dataByteLength =\n data instanceof ArrayBuffer ? data.byteLength : (data as ArrayBufferView).byteLength;\n const writeStart = dataOffset ?? 0;\n const writeSize = size ?? dataByteLength - writeStart;\n // Bounds validation: bufferOffset + writeSize <= bufferSize.\n if (bufferOffset + writeSize > bufferSize) {\n return queueWriteBufferOutOfBounds({\n offset: bufferOffset,\n byteLength: writeSize,\n bufferSize,\n });\n }\n try {\n if (size !== undefined) {\n rawQueue.writeBuffer(\n rawBuffer,\n bufferOffset,\n data as GPUAllowSharedBufferSource,\n writeStart,\n size,\n );\n } else if (dataOffset !== undefined) {\n rawQueue.writeBuffer(\n rawBuffer,\n bufferOffset,\n data as GPUAllowSharedBufferSource,\n writeStart,\n );\n } else {\n rawQueue.writeBuffer(rawBuffer, bufferOffset, data as GPUAllowSharedBufferSource);\n }\n return ok(undefined);\n } catch (e) {\n const message = e instanceof Error ? e.message : String(e);\n // GPU validation may surface bounds errors; wrap as out-of-bounds for\n // AI-user routing parity (charter proposition 4 explicit failure).\n if (/out of (bounds|range)|exceed/i.test(message)) {\n return queueWriteBufferOutOfBounds({\n offset: bufferOffset,\n byteLength: writeSize,\n bufferSize,\n });\n }\n return queueSubmitFailed(message);\n }\n },\n submit(commandBuffers: readonly CommandBuffer[]): Result<void, RhiError> {\n const rawList: GPUCommandBuffer[] = [];\n for (const cb of commandBuffers) {\n const raw = COMMAND_BUFFER_RAW_MAP.get(cb);\n if (raw !== undefined) {\n rawList.push(raw);\n } else {\n rawList.push(cb as unknown as GPUCommandBuffer);\n }\n }\n try {\n rawQueue.submit(rawList);\n return ok(undefined);\n } catch (e) {\n const message = e instanceof Error ? e.message : String(e);\n return queueSubmitFailed(message);\n }\n },\n writeTexture(\n destination: TextureWriteDestination,\n data: ArrayBufferView | ArrayBuffer,\n dataLayout: GPUTexelCopyBufferLayout,\n size: GPUExtent3DStrict,\n ): Result<void, RhiError> {\n // writeTexture calls validating texture buffer copy(..., aligned=false)\n // per WebGPU spec §19.2 GPUQueue.writeTexture, which explicitly notes\n // \"unlike copyBufferToTexture, there is no alignment requirement on\n // either dataLayout.bytesPerRow or dataLayout.offset.\"\n // The 256-byte alignment lives in §11.2.2 validating GPUTexelCopyBufferInfo,\n // called only by copyBufferToTexture / copyTextureToBuffer where the source\n // is a GPUBuffer. The lower bound bytesPerRow >= widthInBlocks * blockSize\n // is enforced by dawn / WebGPU via §11.2.6 validating linear texture data\n // and surfaces as webgpu-runtime-error through the try/catch below.\n try {\n // The destination.texture is a forgeax Texture brand; the shim stored\n // the raw GPUTexture as the brand carrier in createTexture. Spec\n // structural compatibility lets us forward verbatim with a cast.\n // The data + size casts cover @webgpu/types polymorphism that the\n // forgeax form normalises to the strict spec subset.\n const rawDestination: GPUTexelCopyTextureInfo = {\n texture: destination.texture as unknown as GPUTexture,\n };\n if (destination.mipLevel !== undefined) rawDestination.mipLevel = destination.mipLevel;\n if (destination.origin !== undefined) rawDestination.origin = destination.origin;\n if (destination.aspect !== undefined) rawDestination.aspect = destination.aspect;\n rawQueue.writeTexture(\n rawDestination,\n data as unknown as GPUAllowSharedBufferSource,\n dataLayout,\n size as unknown as GPUExtent3D,\n );\n return ok(undefined);\n } catch (e) {\n const message = e instanceof Error ? e.message : String(e);\n return err(\n new RhiErrorClass({\n code: 'webgpu-runtime-error',\n expected: 'underlying GPUQueue.writeTexture to succeed',\n hint: `writeTexture raised: ${message}`,\n }),\n );\n }\n },\n copyExternalImageToTexture(\n source: GPUCopyExternalImageSourceInfo,\n destination: ExternalImageTextureDestination,\n copySize: GPUExtent3DStrict,\n ): Result<void, RhiError> {\n try {\n rawQueue.copyExternalImageToTexture(\n source,\n {\n texture: destination.texture as unknown as GPUTexture,\n ...(destination.mipLevel === undefined ? {} : { mipLevel: destination.mipLevel }),\n ...(destination.origin === undefined ? {} : { origin: destination.origin }),\n ...(destination.aspect === undefined ? {} : { aspect: destination.aspect }),\n ...(destination.colorSpace === undefined ? {} : { colorSpace: destination.colorSpace }),\n ...(destination.premultipliedAlpha === undefined\n ? {}\n : { premultipliedAlpha: destination.premultipliedAlpha }),\n },\n copySize,\n );\n return ok(undefined);\n } catch (e) {\n const message = e instanceof Error ? e.message : String(e);\n return err(\n new RhiErrorClass({\n code: 'webgpu-runtime-error',\n expected: 'underlying GPUQueue.copyExternalImageToTexture to succeed',\n hint: `copyExternalImageToTexture raised: ${message}`,\n }),\n );\n }\n },\n // forgeax-async-whitelist: dom-native — spec `GPUQueue.onSubmittedWorkDone()` Promise passthrough\n onSubmittedWorkDone(): Promise<undefined> {\n // research §5.1 spec normative: no reject path. Forward the raw\n // Promise verbatim; the forgeax Promise<undefined> matches the spec\n // shape (no Result wrapping; device-lost flows through RhiDevice.lost).\n return rawQueue.onSubmittedWorkDone();\n },\n };\n}\n\n/**\n * Construct a RhiDevice shim wrapping GPUDevice.\n *\n * Does not cache or reclassify device.lost (single-source subscription +\n * dual-form fan-out is the engine layer's job; this package only exposes the\n * spec Promise). See plan-strategy 3 R2 mitigation.\n */\nexport function makeRhiDevice(rawDevice: GPUDevice): {\n device: RhiDevice;\n /** Exposed for createShaderModule and other shim entry points that need to\n * bypass the createX Result wrapper. */\n raw: GPUDevice;\n} {\n const caps = deriveCaps(rawDevice, rawDevice.features, rawDevice.limits);\n const features = rawDevice.features as unknown as RhiFeatures;\n const limits = rawDevice.limits as RhiLimits;\n\n const queue: RhiQueue = makeQueue(rawDevice.queue);\n\n const device: RhiDevice = {\n caps,\n features,\n limits,\n queue,\n lost: rawDevice.lost as unknown as Promise<{\n readonly reason: 'destroyed' | 'unknown';\n readonly message: string;\n }>,\n createBuffer(desc: BufferDescriptor): Result<Buffer, RhiError> {\n // M5 / K-7 / OQ-7 / D-R3: mappedAtCreation passthrough is delivered by\n // BUFFER_KEYS containing 'mappedAtCreation'; mirror() ships the field to\n // the raw GPUBufferDescriptor when present (`'mappedAtCreation' in desc`\n // semantics), so createBuffer({mappedAtCreation:true}) yields a buffer\n // in `'mapped'` state per spec §buffer-creation step 6 (research §4.3).\n // w31 (M5) dawn-real-gpu Pattern B is the regression guard - it asserts\n // mapState === 'mapped' + getMappedRange().byteLength === 16 + the init\n // data round-trips through copyBufferToBuffer + mapAsync(READ).\n const out = rawDevice.createBuffer(\n mirror(desc, BUFFER_KEYS) as unknown as GPUBufferDescriptor,\n );\n // Record metadata for downstream shim validation (resolveQuerySet\n // destination.usage / destinationOffset bounds, research §2.3 +\n // M5 mapAsync mode-usage cross-check, research §4.2 step 9 / F-8 row 3).\n const sizeField = typeof desc.size === 'number' ? desc.size : 0;\n const usageField = (desc.usage as GPUBufferUsageFlags | undefined) ?? 0;\n // M5 / w35: wrap the raw GPUBuffer in a forgeax Buffer wrapper that\n // exposes the mapping surface (mapAsync / getMappedRange / unmap /\n // mapState getter). The wrapper validates BEFORE delegating to the raw\n // GPUBuffer; failures ride 'webgpu-runtime-error' with structured\n // .expected / .hint (K-2 + research §4.2 / F-8 three rows).\n const handle = makeBufferWrapper(out, sizeField, usageField);\n BUFFER_RAW_MAP.set(handle, out);\n BUFFER_META_MAP.set(handle, {\n size: sizeField,\n usage: usageField,\n destroyed: false,\n });\n return ok(handle);\n },\n createTexture(desc: TextureDescriptor): Result<Texture, RhiError> {\n const out = rawDevice.createTexture(\n mirror(desc, TEXTURE_KEYS) as unknown as GPUTextureDescriptor,\n );\n const handle = out as unknown as Texture;\n // Record metadata for createTextureView cross-resource validation.\n const viewFormats =\n desc.viewFormats === undefined\n ? []\n : Array.from(desc.viewFormats as Iterable<GPUTextureFormat>);\n TEXTURE_META_MAP.set(handle, {\n format: desc.format as GPUTextureFormat,\n usage: desc.usage as GPUTextureUsageFlags,\n viewFormats,\n destroyed: false,\n });\n return ok(handle);\n },\n destroyBuffer(buf: Buffer): Result<void, RhiError> {\n // feat-20260612 M1 / w4 — fail-fast over the spec idempotent-void\n // contract (plan-strategy D-7). The shim layer tracks\n // `destroyed: boolean` on per-handle BufferMeta and routes the second\n // destroy to 'destroy-after-destroy' rather than forwarding to the\n // underlying GPUBuffer.destroy(). Charter proposition 4 explicit\n // failure + architecture-principles §5 Fail Fast.\n const meta = BUFFER_META_MAP.get(buf);\n if (meta?.destroyed) {\n return err(\n new RhiErrorClass({\n code: 'destroy-after-destroy',\n expected: 'GPU buffer handle has not been destroyed yet',\n hint: 'object already destroyed; track lifecycle in caller or check isDestroyed before re-destroy',\n }),\n );\n }\n const rawBuf = BUFFER_RAW_MAP.get(buf);\n try {\n if (rawBuf !== undefined && typeof rawBuf.destroy === 'function') {\n rawBuf.destroy();\n }\n } catch (e) {\n const message = e instanceof Error ? e.message : String(e);\n return err(\n new RhiErrorClass({\n code: 'webgpu-runtime-error',\n expected: 'underlying GPUBuffer.destroy() to succeed',\n hint: `destroy raised: ${message}`,\n }),\n );\n }\n if (meta !== undefined) meta.destroyed = true;\n return ok(undefined);\n },\n destroyTexture(tex: Texture): Result<void, RhiError> {\n // feat-20260612 M1 / w4 — fail-fast on second destroy (D-7); shape\n // mirrors destroyBuffer above. The shim tracks `destroyed: boolean`\n // on per-handle TextureMeta; the underlying GPUTexture.destroy()\n // is invoked exactly once per handle.\n const meta = TEXTURE_META_MAP.get(tex);\n if (meta?.destroyed) {\n return err(\n new RhiErrorClass({\n code: 'destroy-after-destroy',\n expected: 'GPU texture handle has not been destroyed yet',\n hint: 'object already destroyed; track lifecycle in caller or check isDestroyed before re-destroy',\n }),\n );\n }\n const rawTex = tex as unknown as { destroy?: () => void };\n try {\n if (typeof rawTex.destroy === 'function') {\n rawTex.destroy();\n }\n } catch (e) {\n const message = e instanceof Error ? e.message : String(e);\n return err(\n new RhiErrorClass({\n code: 'webgpu-runtime-error',\n expected: 'underlying GPUTexture.destroy() to succeed',\n hint: `destroy raised: ${message}`,\n }),\n );\n }\n if (meta !== undefined) meta.destroyed = true;\n return ok(undefined);\n },\n createTextureView(\n texture: Texture,\n desc: TextureViewDescriptor,\n ): Result<TextureView, RhiError> {\n // Cross-resource validation fast-path (research §1.1). When metadata is\n // available, validate format ∈ source.format ∪ source.viewFormats and\n // usage ⊆ source.usage; both violations map to 'webgpu-runtime-error'\n // (charter proposition 4 explicit failure).\n const meta = TEXTURE_META_MAP.get(texture);\n if (meta !== undefined) {\n const fmt = desc.format as GPUTextureFormat | undefined;\n if (fmt !== undefined && fmt !== meta.format && !meta.viewFormats.includes(fmt)) {\n return err(\n new RhiErrorClass({\n code: 'webgpu-runtime-error',\n expected:\n 'createTextureView format must be the source texture format or one of source.viewFormats',\n hint: `got format='${fmt}'; source.format='${meta.format}'; source.viewFormats=[${meta.viewFormats.join(', ')}]`,\n }),\n );\n }\n const reqUsage = desc.usage as GPUTextureUsageFlags | undefined;\n if (reqUsage !== undefined && reqUsage !== 0 && (reqUsage & ~meta.usage) !== 0) {\n return err(\n new RhiErrorClass({\n code: 'webgpu-runtime-error',\n expected: 'createTextureView usage must be a subset of source.usage',\n hint: `got usage=0x${reqUsage.toString(16)}; source.usage=0x${meta.usage.toString(16)}`,\n }),\n );\n }\n }\n const rawTexture = texture as unknown as GPUTexture;\n try {\n const rawView = rawTexture.createView(\n mirror(desc, TEXTURE_VIEW_KEYS) as unknown as GPUTextureViewDescriptor,\n );\n const handle = rawView as unknown as TextureView;\n TEXTURE_VIEW_RAW_MAP.set(handle, rawView);\n return ok(handle);\n } catch (e) {\n const message = e instanceof Error ? e.message : String(e);\n return err(\n new RhiErrorClass({\n code: 'webgpu-runtime-error',\n expected: 'underlying GPUTexture.createView to succeed',\n hint: `createView raised: ${message}`,\n }),\n );\n }\n },\n createSampler(desc?: SamplerDescriptor | undefined): Result<Sampler, RhiError> {\n // Sampler descriptor is fully optional; if undefined call createSampler() with no arg.\n if (desc === undefined) {\n const out = rawDevice.createSampler();\n return ok(out as unknown as Sampler);\n }\n const out = rawDevice.createSampler(\n mirror(desc, SAMPLER_KEYS) as unknown as GPUSamplerDescriptor,\n );\n return ok(out as unknown as Sampler);\n },\n createBindGroupLayout(desc: BindGroupLayoutDescriptor): Result<BindGroupLayout, RhiError> {\n const out = rawDevice.createBindGroupLayout(\n mirror(desc, BGL_KEYS) as unknown as GPUBindGroupLayoutDescriptor,\n );\n return ok(out as unknown as BindGroupLayout);\n },\n createBindGroup(desc: BindGroupDescriptor): Result<BindGroup, RhiError> {\n // w20 — tagged-union RhiBindingResource 4-kind adapter. Each forgeax\n // entry carries `{ binding, resource: { kind, value } }` (the 4\n // discriminator values are 'sampler' / 'buffer' / 'textureView' /\n // 'externalTexture' per @forgeax/engine-rhi RhiBindingResource). The shim\n // dispatches on `resource.kind` and emits the spec-verbatim\n // GPUBindGroupEntry shape per kind. The default branch trips\n // `assertNever` so a future RhiBindingResource extension forces a\n // TS2367 here at compile time (charter proposition 4 explicit failure\n // + proposition 5 consistent abstraction over duck-typing).\n const mirrored: {\n label?: string | undefined;\n layout: GPUBindGroupLayout;\n entries: GPUBindGroupEntry[];\n } = {\n layout: desc.layout as unknown as GPUBindGroupLayout,\n entries: [],\n };\n if ('label' in desc && desc.label !== undefined) mirrored.label = desc.label;\n for (const entry of desc.entries) {\n const resource = entry.resource;\n switch (resource.kind) {\n case 'sampler': {\n mirrored.entries.push({\n binding: entry.binding,\n resource: resource.value as unknown as GPUSampler,\n });\n break;\n }\n case 'buffer': {\n const { buffer, offset, size } = resource.value;\n const rawBuf = BUFFER_RAW_MAP.get(buffer) ?? (buffer as unknown as GPUBuffer);\n const bufferBinding: GPUBufferBinding = { buffer: rawBuf };\n if (offset !== undefined) bufferBinding.offset = offset;\n if (size !== undefined) bufferBinding.size = size;\n mirrored.entries.push({ binding: entry.binding, resource: bufferBinding });\n break;\n }\n case 'textureView': {\n mirrored.entries.push({\n binding: entry.binding,\n resource: resource.value as unknown as GPUTextureView,\n });\n break;\n }\n case 'externalTexture': {\n mirrored.entries.push({\n binding: entry.binding,\n resource: resource.value as unknown as GPUExternalTexture,\n });\n break;\n }\n default: {\n // assertNever — adding a fifth kind would trip TS2367 here.\n const _exhaustive: never = resource;\n void _exhaustive;\n throw new Error(`rhi-webgpu: unreachable RhiBindingResource kind in createBindGroup`);\n }\n }\n }\n const out = rawDevice.createBindGroup(mirrored as unknown as GPUBindGroupDescriptor);\n return ok(out as unknown as BindGroup);\n },\n createPipelineLayout(desc: PipelineLayoutDescriptor): Result<PipelineLayout, RhiError> {\n const out = rawDevice.createPipelineLayout(\n mirror(desc, PL_KEYS) as unknown as GPUPipelineLayoutDescriptor,\n );\n return ok(out as unknown as PipelineLayout);\n },\n createRenderPipeline(desc: RenderPipelineDescriptor): Result<RenderPipeline, RhiError> {\n try {\n const out = rawDevice.createRenderPipeline(mirrorRenderPipelineDescriptor(desc));\n return ok(out as unknown as RenderPipeline);\n } catch (e) {\n const message = e instanceof Error ? e.message : String(e);\n // Keep synchronous render-pipeline creation on the same structured\n // Result boundary as compute-pipeline creation. A failed PSO must not\n // escape as an exception and abort the caller's whole frame.\n if (/compile|shader|wgsl/i.test(message)) {\n return err(\n new RhiErrorClass({\n code: 'shader-compile-failed',\n expected: 'render shader modules + entry points to be valid',\n hint: `compile error: ${message}`,\n }),\n );\n }\n return err(\n new RhiErrorClass({\n code: 'webgpu-runtime-error',\n expected: 'underlying GPUDevice.createRenderPipeline to succeed',\n hint: `createRenderPipeline raised: ${message}`,\n }),\n );\n }\n },\n createComputePipeline(desc: ComputePipelineDescriptor): Result<ComputePipeline, RhiError> {\n // Capability gate (research §1.2 NOTE; plan-strategy §4.3 boundary\n // case row 1). MVP WebGPU path always has caps.compute=true; the gate\n // exists for potential future backends that lack compute.\n if (caps.compute === false) {\n return err(\n new RhiErrorClass({\n code: 'feature-not-enabled',\n expected: 'caps.compute === true',\n hint: 'check device.caps.compute before calling createComputePipeline',\n }),\n );\n }\n try {\n const out = rawDevice.createComputePipeline(\n mirror(desc, CP_KEYS) as unknown as GPUComputePipelineDescriptor,\n );\n return ok(out as unknown as ComputePipeline);\n } catch (e) {\n const message = e instanceof Error ? e.message : String(e);\n // Shader / module compilation issues surface as 'shader-compile-failed'\n // with the underlying message; everything else maps to a generic\n // webgpu runtime error (charter proposition 4 explicit failure).\n if (/compile|shader|wgsl/i.test(message)) {\n return err(\n new RhiErrorClass({\n code: 'shader-compile-failed',\n expected: 'compute shader module + entry point to be valid',\n hint: `compile error: ${message}`,\n }),\n );\n }\n return err(\n new RhiErrorClass({\n code: 'webgpu-runtime-error',\n expected: 'underlying GPUDevice.createComputePipeline to succeed',\n hint: `createComputePipeline raised: ${message}`,\n }),\n );\n }\n },\n createQuerySet(desc: QuerySetDescriptor): Result<QuerySet, RhiError> {\n // Hard constraint: count <= 4096 (research §1.3 device timeline step 1).\n const count = desc.count as number | undefined;\n if (typeof count === 'number' && count > QUERY_SET_COUNT_LIMIT) {\n return err(\n new RhiErrorClass({\n code: 'limit-exceeded',\n expected: 'count <= 4096 (spec normative)',\n hint: 'create multiple QuerySet instances if more than 4096 queries needed',\n }),\n );\n }\n // Hard constraint: timestamp requires caps.timestampQuery.\n if (desc.type === 'timestamp' && caps.timestampQuery !== true) {\n return err(\n new RhiErrorClass({\n code: 'feature-not-enabled',\n expected: 'caps.timestampQuery === true (timestamp-query feature)',\n hint: 'request the timestamp-query feature at requestDevice and check device.caps.timestampQuery before creating timestamp QuerySets',\n }),\n );\n }\n try {\n const out = rawDevice.createQuerySet(\n mirror(desc, QS_KEYS) as unknown as GPUQuerySetDescriptor,\n );\n const handle = out as unknown as QuerySet;\n // Register raw handle so the RPE / encoder paths can read `.count` /\n // `.type` for bounds + alignment checks (research §2.1 + §2.3).\n QUERY_SET_RAW_MAP.set(handle, out);\n QUERY_SET_DESTROYED_MAP.set(handle, { destroyed: false });\n return ok(handle);\n } catch (e) {\n const message = e instanceof Error ? e.message : String(e);\n return err(\n new RhiErrorClass({\n code: 'webgpu-runtime-error',\n expected: 'underlying GPUDevice.createQuerySet to succeed',\n hint: `createQuerySet raised: ${message}`,\n }),\n );\n }\n },\n destroyQuerySet(querySet: QuerySet): Result<void, RhiError> {\n const marker = QUERY_SET_DESTROYED_MAP.get(querySet);\n if (marker?.destroyed) {\n return err(\n new RhiErrorClass({\n code: 'destroy-after-destroy',\n expected: 'GPU query-set handle has not been destroyed yet',\n hint: 'object already destroyed; release each timestamp QuerySet exactly once',\n }),\n );\n }\n const rawQuery = QUERY_SET_RAW_MAP.get(querySet) as\n | (GPUQuerySet & { destroy?: () => void })\n | undefined;\n try {\n if (rawQuery !== undefined && typeof rawQuery.destroy === 'function') rawQuery.destroy();\n } catch (e) {\n const message = e instanceof Error ? e.message : String(e);\n return err(\n new RhiErrorClass({\n code: 'webgpu-runtime-error',\n expected: 'underlying GPUQuerySet.destroy() to succeed',\n hint: `destroy raised: ${message}`,\n }),\n );\n }\n if (marker !== undefined) marker.destroyed = true;\n return ok(undefined);\n },\n createCommandEncoder(\n desc?: CommandEncoderDescriptor | undefined,\n ): Result<RhiCommandEncoder, RhiError> {\n const rawEnc =\n desc === undefined\n ? rawDevice.createCommandEncoder()\n : rawDevice.createCommandEncoder(\n mirror(desc, ENC_KEYS) as unknown as GPUCommandEncoderDescriptor,\n );\n // M5 / w39: pass caps.timestampQuery + an onError-style fan-out so\n // writeTimestamp can fire 'feature-not-enabled' through the engine\n // channel when caps.timestampQuery is false (K-3: spec writeTimestamp\n // returns void; the forgeax form keeps that shape).\n //\n // Round 3 fix-up F-P3-3: the forgeax RhiDevice\n // does not expose `onError` directly (charter proposition 5: keep\n // RHI math-free + listener-free), so the shim writes a structured\n // diagnostic to `console.error` matching the RhiError shape. The\n // engine layer subscribes through `Renderer.onError` and fans the\n // same RhiError out; this keeps the unsupported capability observable\n // for pure-RHI consumers (mock unit tests, dawn-real-gpu probes) that\n // never instantiate a Renderer.\n const fireFeatureNotEnabled = (featureName: string, hint: string): void => {\n // Diagnostic channel (a) of the K-9 double-channel pattern: default\n // console.error so AI consumers running headless / mock paths still\n // observe the unsupported capability without subscribing to a\n // listener. The capability-disabled entry remains non-throwing.\n console.error(\n `[RhiError feature-not-enabled] expected: device.features.has('${featureName}') === true; hint: ${hint}`,\n );\n };\n return ok(makeCommandEncoder(rawEnc, caps, fireFeatureNotEnabled));\n },\n // fix-f3: synchronous createShaderModule placeholder removed; the\n // shader-compile-failed path lives in the top-level async factory\n // (see ../index.ts).\n };\n RAW_DEVICE_MAP.set(device, rawDevice);\n return { device, raw: rawDevice };\n}\n\n// ============================================================================\n// RhiCanvasContext shim (M3 / K-4 / w21)\n// ============================================================================\n//\n// Spec anchor: W3C WebGPU §3.3 GPUCanvasContext / GPUCanvasConfiguration.\n// 4 methods (research §3.1) + 7 fields (§3.2) + 4 method algorithms (§3.3).\n\n/** Spec normative supported context formats (research §3.2 normative). */\nconst SUPPORTED_CONTEXT_FORMATS: ReadonlySet<string> = new Set([\n 'bgra8unorm',\n 'rgba8unorm',\n 'rgba16float',\n]);\n\nconst CANVAS_CONFIG_KEYS = [\n 'device',\n 'format',\n 'usage',\n 'viewFormats',\n 'colorSpace',\n 'toneMapping',\n 'alphaMode',\n] as const;\n\n/** Stripped-down GPUCanvasContext shape the shim consumes. Real\n * GPUCanvasContext satisfies this; the unit-test mock fixture only\n * implements what is needed (charter proposition 1: progressive disclosure). */\nexport interface GpuCanvasContextLike {\n configure(configuration: GPUCanvasConfiguration): void;\n unconfigure(): void;\n getConfiguration(): GPUCanvasConfiguration | null;\n getCurrentTexture(): GPUTexture;\n}\n\n/**\n * Build a RhiCanvasContext shim around a raw GPUCanvasContext (M3 / K-4 /\n * w21).\n *\n * Pre-configure validation (research §3.3 mapping):\n * - format gate: format must be in SUPPORTED_CONTEXT_FORMATS; otherwise\n * fast-path returns `'webgpu-runtime-error'` with the spec-aligned\n * `.expected` literal `'one of bgra8unorm/rgba8unorm/rgba16float'`.\n *\n * Post-configure semantics:\n * - getCurrentTexture forwards each call to the raw context (NO cross-frame\n * caching, research §3.3 [[Expire the current texture]]); spec\n * InvalidStateError catches map to `'webgpu-runtime-error'`.\n * - getConfiguration projects the spec record verbatim; missing fields\n * remain missing (feature-detection idiom, research §3.2 toneMapping\n * NOTE).\n */\nexport function makeCanvasContext(rawContext: GpuCanvasContextLike): RhiCanvasContext {\n return {\n configure(desc: CanvasConfiguration): Result<void, RhiError> {\n const fmt = desc.format as GPUTextureFormat | undefined;\n if (typeof fmt === 'string' && !SUPPORTED_CONTEXT_FORMATS.has(fmt)) {\n return err(\n new RhiErrorClass({\n code: 'webgpu-runtime-error',\n expected: 'one of bgra8unorm/rgba8unorm/rgba16float',\n hint: `got format='${fmt}'; canvas configuration cannot use srgb formats — use the non-srgb form (e.g. 'bgra8unorm') and put the srgb format in viewFormats, then createView with the srgb format`,\n }),\n );\n }\n try {\n const mirrored = mirror(\n desc as unknown as Record<string, unknown>,\n CANVAS_CONFIG_KEYS,\n ) as unknown as Record<string, unknown>;\n // CanvasConfiguration.device is a forgeax RhiDevice brand (D-S5);\n // the spec GPUCanvasContext.configure({ device }) slot needs the raw\n // GPUDevice. Translate via RAW_DEVICE_MAP so AI-user-facing code only\n // sees the forgeax abstraction while the underlying spec call still\n // receives a valid raw device (charter proposition 5 consistent\n // abstraction red line + feat-20260510-rhi-resource-creation M4\n // escape hatch tear-down: the translation is fully internal to\n // packages/rhi-webgpu/src and does not surface a reverse-lookup\n // entry across the package boundary).\n if ('device' in mirrored) {\n const forgeaxDevice = desc.device as RhiDevice;\n const rawDev = RAW_DEVICE_MAP.get(forgeaxDevice);\n if (rawDev === undefined) {\n return err(\n new RhiErrorClass({\n code: 'rhi-not-available',\n expected:\n 'CanvasConfiguration.device must be a RhiDevice produced by rhi.requestAdapter().requestDevice() (or the deprecated rhi.requestDevice factory)',\n hint: 'pass the device returned by the forgeax rhi.requestAdapter() / rhi.requestDevice() entries; passing a foreign RhiDevice or a raw GPUDevice is rejected because the canvas-context spec requires the same raw GPUDevice that the forgeax shim wraps',\n }),\n );\n }\n mirrored.device = rawDev;\n }\n rawContext.configure(mirrored as unknown as GPUCanvasConfiguration);\n return ok(undefined);\n } catch (e) {\n const msg = e instanceof Error ? e.message : String(e);\n // Spec maps invalid / lost device to InvalidStateError; we map the\n // catch-all to webgpu-runtime-error so AI users get a structured\n // failure (charter proposition 4 explicit failure).\n if (e instanceof Error && (e.name === 'InvalidStateError' || /lost|destroyed/i.test(msg))) {\n return err(\n new RhiErrorClass({\n code: 'rhi-not-available',\n expected: 'CanvasConfiguration.device must be valid (not lost / destroyed)',\n hint: `configure raised: ${msg}`,\n }),\n );\n }\n return err(\n new RhiErrorClass({\n code: 'webgpu-runtime-error',\n expected: 'underlying GPUCanvasContext.configure to succeed',\n hint: `configure raised: ${msg}`,\n }),\n );\n }\n },\n unconfigure(): void {\n rawContext.unconfigure();\n },\n getConfiguration(): CanvasConfiguration | undefined {\n const conf = rawContext.getConfiguration();\n if (conf === null) return undefined;\n // Project spec fields onto the forgeax record verbatim; missing fields\n // remain missing (feature-detection idiom).\n const out: Record<string, unknown> = {};\n for (const k of CANVAS_CONFIG_KEYS) {\n if (k in (conf as unknown as Record<string, unknown>)) {\n out[k] = (conf as unknown as Record<string, unknown>)[k];\n }\n }\n return out as unknown as CanvasConfiguration;\n },\n getCurrentTexture(): Result<Texture, RhiError> {\n try {\n const rawTex = rawContext.getCurrentTexture();\n return ok(rawTex as unknown as Texture);\n } catch (e) {\n const msg = e instanceof Error ? e.message : String(e);\n // Spec InvalidStateError on unconfigured context maps to\n // 'webgpu-runtime-error' (charter proposition 4).\n return err(\n new RhiErrorClass({\n code: 'webgpu-runtime-error',\n expected: 'GPUCanvasContext.getCurrentTexture to succeed (context configured)',\n hint: `getCurrentTexture raised: ${msg}`,\n }),\n );\n }\n },\n };\n}\n","// @forgeax/engine-rhi-webgpu/src/internal/error-translation — spec GPUError +\n// GPUDeviceLostInfo -> 17-member RhiErrorCode dispatch translator (D-P4 literal).\n//\n// Charter: proposition 4 (explicit failure) — every WebGPU async dispatch\n// error reachable through onuncapturederror / device.lost has a closed-union\n// RhiErrorCode mapping; proposition 5 (consistent abstraction) — the dual\n// backends (rhi-webgpu / rhi-wgpu) translate the SAME spec event shape to the\n// SAME 17-member union so engine.onError listeners see byte-for-byte aligned\n// .code values regardless of which backend dispatched the error.\n//\n// Mapping rules (plan-strategy D-P4 table literal):\n// (a) GPUValidationError — sub-pattern on the message text:\n// - /shader|compile|wgsl/i -> 'shader-compile-failed'\n// - /size|alignment|out of bounds/i -> 'queue-write-buffer-out-of-bounds'\n// - /encoder.*finished|finished encoder/i -> 'command-encoder-finished'\n// - /render pass.*not ended|not ended/i -> 'render-pass-not-ended'\n// - /submit/i -> 'queue-submit-failed'\n// - default -> 'limit-exceeded' (the broadest spec validation bucket\n// reachable from validation messages; AI users still get a\n// structured code, not 'webgpu-runtime-error' which is reserved for\n// unrecognised types).\n// (b) GPUOutOfMemoryError -> 'oom' (RhiErrorCode 17-member addition w6).\n// (c) GPUInternalError -> 'internal-error' (RhiErrorCode 17-member addition w6).\n// (d) GPUDeviceLostInfo -> 'device-lost' (RhiErrorCode 17-member addition w6).\n// (e) Unrecognised event type -> 'webgpu-runtime-error' (catch-all bucket;\n// AI users `switch (err.code)` still exhausts the closed union).\n//\n// Dual-channel responsibility boundary (D-PD4):\n// - createX entries return Result.ok / Result.err *synchronously* — sync\n// validation errors (size=0, missing layout, etc.) flow through this\n// channel via the existing errors.ts factories.\n// - device.lost + onuncapturederror channels carry *async* dispatch errors\n// — this translator is the sole gateway from spec event -> RhiError in\n// that async channel. The engine RhiErrorListenerRegistry fan-out happens\n// downstream (packages/engine/src/renderer.ts).\n//\n// Anchors: requirements AC-02 + AC-04; research R-02 §2.1 spec / wgpu / dawn\n// three-way fact; plan-strategy D-P4 mapping table literal; charter propositions\n// 4 + 5; AGENTS.md \"## RHI / Shader / error model contract\" evolution contract\n// minor add-only.\n\n/// <reference types=\"@webgpu/types\" />\n\nimport { err, type Result, RhiError } from '@forgeax/engine-rhi';\n\n/** Translate a spec async-dispatch error event into a closed-union RhiError.\n *\n * This is the single gateway from `GPUUncapturedErrorEvent` / `device.lost`\n * Promise into the 17-member `RhiErrorCode` union (charter proposition 5\n * consistent abstraction: dual-backend dispatch tables align byte-for-byte).\n *\n * @note GPUValidationError dispatch defaults to the 'limit-exceeded' bucket when the device-side message does not match any narrower regex pattern; see L12-21 module-level mapping rules comment for the full sub-pattern table (5 narrower regexes + default fallback). AI users still receive a structured `.code` rather than `'webgpu-runtime-error'` (reserved for unrecognised event types only); charter proposition 4 explicit failure — every spec event maps to a real union member.\n * @param event one of:\n * - `GPUUncapturedErrorEvent` (carries a `.error` of `GPUValidationError |\n * GPUOutOfMemoryError | GPUInternalError`);\n * - `GPUDeviceLostInfo` (carries `.reason` + `.message`);\n * - opaque (catch-all → 'webgpu-runtime-error').\n */\nexport function translateErrorEventToRhiError(\n event: GPUUncapturedErrorEvent | GPUDeviceLostInfo | unknown,\n): Result<never, RhiError> {\n // (d) device-lost branch — GPUDeviceLostInfo shape has `.reason` enum.\n if (\n typeof event === 'object' &&\n event !== null &&\n 'reason' in event &&\n typeof (event as { reason: unknown }).reason === 'string'\n ) {\n const info = event as GPUDeviceLostInfo;\n return err(\n new RhiError({\n code: 'device-lost',\n expected: 'device must remain alive (driver / browser must not destroy the GPUDevice)',\n hint: `device-lost reason: ${info.reason}; message: ${info.message ?? '<empty>'}`,\n }),\n );\n }\n\n // GPUUncapturedErrorEvent branch — carries `.error` of GPUError subtype.\n if (\n typeof event === 'object' &&\n event !== null &&\n 'error' in event &&\n typeof (event as { error: unknown }).error === 'object' &&\n (event as { error: unknown }).error !== null\n ) {\n const error = (event as { error: unknown }).error as object;\n const message =\n typeof (error as { message?: unknown }).message === 'string'\n ? (error as { message: string }).message\n : '<no message>';\n\n // (b) GPUOutOfMemoryError → 'oom' — detected by constructor name.\n if (error.constructor.name === 'GPUOutOfMemoryError') {\n return err(\n new RhiError({\n code: 'oom',\n expected: 'sufficient GPU memory to satisfy the allocation',\n hint: `GPU out-of-memory: ${message}`,\n }),\n );\n }\n\n // (c) GPUInternalError → 'internal-error' — detected by constructor name.\n if (error.constructor.name === 'GPUInternalError') {\n return err(\n new RhiError({\n code: 'internal-error',\n expected: 'driver / browser must report a recognised validation error',\n hint: `GPU internal error: ${message}`,\n }),\n );\n }\n\n // (a) GPUValidationError → sub-pattern dispatch via message text.\n if (error.constructor.name === 'GPUValidationError') {\n if (/shader|compile|wgsl/i.test(message)) {\n return err(\n new RhiError({\n code: 'shader-compile-failed',\n expected: 'valid WGSL source + matching pipeline layout',\n hint: `GPU validation: ${message}`,\n }),\n );\n }\n if (/size|alignment|out of bounds/i.test(message)) {\n return err(\n new RhiError({\n code: 'queue-write-buffer-out-of-bounds',\n expected: 'writeBuffer offset + data.byteLength must be within buffer.size',\n hint: `GPU validation: ${message}`,\n }),\n );\n }\n if (/encoder.*finished|finished encoder/i.test(message)) {\n return err(\n new RhiError({\n code: 'command-encoder-finished',\n expected: 'command encoder must not be finished before recording new commands',\n hint: `GPU validation: ${message}`,\n }),\n );\n }\n if (/render pass.*not ended|pass.*not ended/i.test(message)) {\n return err(\n new RhiError({\n code: 'render-pass-not-ended',\n expected: 'previous render pass must be ended before beginning a new pass',\n hint: `GPU validation: ${message}`,\n }),\n );\n }\n if (/submit/i.test(message)) {\n return err(\n new RhiError({\n code: 'queue-submit-failed',\n expected: 'command buffer references must be valid at submit time',\n hint: `GPU validation: ${message}`,\n }),\n );\n }\n // Default validation bucket — limit-exceeded is the broadest reachable\n // spec validation code (AI users still get a structured code, not the\n // catch-all 'webgpu-runtime-error').\n return err(\n new RhiError({\n code: 'limit-exceeded',\n expected: 'descriptor field values within device limits',\n hint: `GPU validation: ${message}`,\n }),\n );\n }\n }\n\n // (e) Catch-all — unrecognised event type → 'webgpu-runtime-error'.\n const repr =\n typeof event === 'object' && event !== null && 'toString' in event\n ? String(event)\n : '<unknown>';\n return err(\n new RhiError({\n code: 'webgpu-runtime-error',\n expected: 'spec-recognised GPUUncapturedErrorEvent or GPUDeviceLostInfo',\n hint: `unrecognised async-dispatch event: ${repr}`,\n }),\n );\n}\n","// @forgeax/engine-rhi-webgpu — thin WebGPU shim implementing the @forgeax/engine-rhi interface shape.\n//\n// Shape rules (shared between README + AGENTS.md '## RHI / WebGPU' section):\n// - spec alignment — the 5 descriptor field names pass through verbatim to\n// GPUDevice.createX.\n// - `?: T | undefined` + `'x' in src` guard (decision S-7 / research §F-3).\n// - opaque handle — `RhiDevice.createX` returns `Result.ok(handle)`; the handle\n// internally references the GPU resource object but exposes only a brand-only\n// opaque shape externally (research §R5).\n// - capability-gated — caps / features / limits are exposed as three independent\n// readonly layers (charter proposition 5).\n// - device.lost dual-track — the spec Promise passes through (research §F-4 / R2\n// countermeasure); the engine layer does the fan-out, this package does not\n// introduce a secondary cache.\n//\n// Public entries (charter proposition 1: progressive disclosure / single entry that\n// surfaces the full surface area at once):\n// - requestAdapter(opts?) — entry 1: spec-aligned strict two-step\n// path (M3 break-point #2 + M6 fix-up\n// [w51]); returns Result<RhiAdapter, RhiError>.\n// - createShaderModule(d, desc) — entry 2: async, returns\n// Result<ShaderModule, RhiError>; the\n// shader-compile-failed path includes\n// detail.compilerMessages.\n// - acquireCanvasContext(canvas) — entry 3: calls canvas.getContext('webgpu')\n// + wraps as branded RhiCanvasContext (M3 / w15).\n// - rhi — singleton entry (plan-strategy §7.4\n// 'import { rhi } from @forgeax/engine-rhi-webgpu' +\n// Engine.create({ rhi, canvas })).\n//\n// The legacy single-step `rhi.requestDevice(opts)` factory was retired in\n// M6 fix-up [w51] (AGENTS.md break-point list 2026-05-10 #2). Callers go\n// through `(await rhi.requestAdapter()).value.requestDevice(opts)`.\n//\n// Anchors: requirements §AC AC-05 + AC-10 + MVP-1.1 / MVP-1.2 / MVP-1.7 + edge cases\n// + §hard constraint 10; plan-strategy §1 architecture + §2 S-7 + §6 M2 +\n// §7.3 error-message strategy table + §7.4 discoverability;\n// research §F-1 / §F-3 / §F-4 / §F-5 / §F-6.\n\n/// <reference types=\"@webgpu/types\" />\n\nimport type {\n RequestDeviceOptions as ForgeaXRequestDeviceOptions,\n RequestAdapterOptions,\n Result,\n RhiAdapter,\n RhiCanvasContext,\n RhiDevice,\n RhiError,\n RhiInstance,\n ShaderModule,\n} from '@forgeax/engine-rhi';\nimport { err, ok, RhiError as RhiErrorClass } from '@forgeax/engine-rhi';\nimport { _internal_getRawDevice, makeCanvasContext, makeRhiDevice } from './device';\nimport {\n adapterUnavailable,\n featureNotEnabled,\n limitExceeded,\n requestAdapterFailed,\n shaderCompileFailed,\n} from './errors';\n\n/**\n * The `GPU` subset accepted at the provider seam (research §F-6 webgpu-utils +\n * CTS consensus).\n *\n * The shim only calls the two entries `gpu.requestAdapter()` →\n * `adapter.requestDevice()`; accepting a structural subset rather than requiring\n * a full GPU interface implementation lets the mock fixture\n * (src/__tests__/__mocks__/gpu-device.ts) skip implementing\n * `wgslLanguageFeatures` / `getPreferredCanvasFormat` and other fields this loop\n * does not consume (charter proposition 1: progressive disclosure).\n */\nexport interface GpuLike {\n // forgeax-async-whitelist: dom-native — spec `GPU.requestAdapter()` raw entry\n requestAdapter(options?: GPURequestAdapterOptions | undefined): Promise<GpuAdapterLike | null>;\n}\n\n/** The `GPUAdapter` subset accepted at the provider seam — only the `requestDevice` entry is consumed. */\nexport interface GpuAdapterLike {\n // forgeax-async-whitelist: dom-native — spec `GPUAdapter.requestDevice()` raw entry\n requestDevice(descriptor?: GPUDeviceDescriptor | undefined): Promise<GpuDeviceLike>;\n}\n\n/**\n * The `GPUDevice` subset accepted at the provider seam — exactly the fields the\n * shim actually touches (the 5 descriptor `createX` calls + features / limits /\n * lost + a `queue` placeholder).\n *\n * Differences from the full GPUDevice spec:\n * - `onuncapturederror` / `pushErrorScope` / `createCommandEncoder` not required\n * (only needed at M3).\n * - `wgslLanguageFeatures` / `getPreferredCanvasFormat` not required (charter\n * proposition 1: progressive disclosure).\n *\n * The coverage of `cast as GPUDevice` inside `makeRhiDevice` matches this\n * interface exactly; both the mock and the real GPUDevice only need to satisfy\n * this structural subset.\n */\nexport interface GpuDeviceLike {\n readonly features: GPUSupportedFeatures;\n readonly limits: GPUSupportedLimits;\n // forgeax-async-whitelist: dom-native — spec `GPUDevice.lost` Promise passthrough\n readonly lost: Promise<GPUDeviceLostInfo>;\n readonly queue: unknown;\n createBuffer(descriptor: GPUBufferDescriptor): unknown;\n createTexture(descriptor: GPUTextureDescriptor): unknown;\n createSampler(descriptor?: GPUSamplerDescriptor | undefined): unknown;\n createBindGroupLayout(descriptor: GPUBindGroupLayoutDescriptor): unknown;\n createBindGroup(descriptor: GPUBindGroupDescriptor): unknown;\n createPipelineLayout(descriptor: GPUPipelineLayoutDescriptor): unknown;\n createRenderPipeline(descriptor: GPURenderPipelineDescriptor): unknown;\n createShaderModule(descriptor: GPUShaderModuleDescriptor): unknown;\n}\n\n/**\n * Options for the `requestDevice` entry.\n *\n * `gpu?: GpuLike` is the provider seam (research §F-6 webgpu-utils + CTS\n * consensus):\n * - omitted → falls back to `globalThis.navigator.gpu` (real-device path).\n * - explicitly provided → uses the caller-injected mock / real GPU object (mock\n * unit-test path).\n *\n * `adapterOptions` / `deviceDescriptor` pass through to the corresponding spec\n * entries.\n */\nexport interface RequestDeviceOptions {\n gpu?: GpuLike | undefined;\n adapterOptions?: GPURequestAdapterOptions | undefined;\n deviceDescriptor?: GPUDeviceDescriptor | undefined;\n}\n\n/**\n * Maps an OperationError that may occur during `requestDevice` back into a\n * RhiError.\n *\n * Spec behavior (research §F-5 / W3C CR §\"Adapter Selection\"):\n * - `requiredFeatures` exceeds the adapter → reject with `OperationError`.\n * - `requiredLimits` exceeds the adapter → reject with `OperationError`.\n *\n * This package distinguishes feature vs limit by message keyword; the message\n * format is not interoperable between the mock and real GPU implementations\n * (research §F-4: ecosystem-wide message-field inconsistency), but the keywords\n * 'feature' / 'limit' work as a heuristic on both sides. Detailed\n * classification (including limit-name / feature-name extraction) is left to a\n * follow-up loop (plan-strategy §3 R2 fallback).\n */\nfunction classifyRequestDeviceError(e: unknown): Result<never, RhiError> {\n const msg = e instanceof Error ? e.message : String(e);\n if (/feature/i.test(msg)) return featureNotEnabled();\n if (/limit/i.test(msg)) return limitExceeded();\n // Fallback: an unrecognized message keyword is classified as feature-not-enabled\n // (charter proposition 4: explicit failure + structured errors over hidden\n // branches). Subsequent loops can extend the classification.\n return featureNotEnabled();\n}\n\n/**\n * Internal `requestDevice` — single-step factory accepting an injected\n * `gpu` mock provider. **Not part of the public RHI surface**: AI users go\n * through the spec-aligned two-step path\n * `rhi.requestAdapter() -> adapter.requestDevice()` (M3 break-point #2 + M6\n * fix-up [w51]; AGENTS.md break-point list 2026-05-10 #2). This entry is\n * retained as the unit-test seam (`packages/rhi-webgpu/src/__tests__/*`)\n * for `gpu` mock injection; it is **not** re-exported through the `rhi`\n * singleton and is **not** referenced by engine / apps / dawn paths\n * (charter proposition 5 consistent abstraction red line + grep gate\n * `m6-e: rhi.requestDevice( 0 hit`).\n *\n * Generates 3 of the 4 error paths here (research §F-5):\n * - adapter null → `Result.err(RhiError { code: 'adapter-unavailable' })`\n * - feature not enabled → `Result.err(RhiError { code: 'feature-not-enabled' })`\n * - limit exceeded → `Result.err(RhiError { code: 'limit-exceeded' })`\n *\n * The 4th path (shader-compile-failed) is generated by the\n * `createShaderModule` entry.\n */\nexport async function requestDevice(\n opts: RequestDeviceOptions = {},\n): Promise<Result<RhiDevice, RhiError>> {\n const injected: GpuLike | undefined = opts.gpu;\n const ambient: GPU | undefined =\n typeof globalThis !== 'undefined'\n ? (globalThis as { navigator?: Navigator }).navigator?.gpu\n : undefined;\n const gpu: GpuLike | undefined = injected ?? ambient;\n if (gpu === undefined || gpu === null) {\n return adapterUnavailable();\n }\n\n const adapter = await gpu.requestAdapter(opts.adapterOptions);\n if (adapter === null) {\n return adapterUnavailable();\n }\n\n let rawDevice: GpuDeviceLike;\n try {\n rawDevice = await adapter.requestDevice(opts.deviceDescriptor);\n } catch (e) {\n return classifyRequestDeviceError(e);\n }\n\n const { device } = makeRhiDevice(rawDevice as unknown as GPUDevice);\n return ok(device);\n}\n\n/**\n * Entry 2 - async `createShaderModule`. The shader-compile-failed path\n * forwards every 6 fields of `GPUCompilationMessage` to\n * `RhiError.detail.compilerMessages` (OQ-P2 / F-3 finding).\n *\n * Implementation (post fix-f3):\n * 1) Look up the underlying `GPUDevice` via the in-package\n * `_internal_getRawDevice` (RAW_DEVICE_MAP reverse lookup; same module).\n * 2) `rawDevice.createShaderModule(desc)` calls the spec entry to obtain\n * a `GPUShaderModule`.\n * 3) `await module.getCompilationInfo()` retrieves compilation info.\n * 4) If any message has `type === 'error'`, return\n * `Result.err(RhiError { code: 'shader-compile-failed',\n * detail: { compilerMessages } })`.\n * 5) Otherwise return `Result.ok(module as ShaderModule)`.\n *\n * Note: this entry accepts a shim-wrapped RhiDevice (not a raw GPUDevice)\n * to keep the public API single-source; the in-package\n * `_internal_getRawDevice` is the only sanctioned reverse lookup.\n *\n * fix-f3: the synchronous `RhiDevice.createShaderModule` placeholder is\n * removed; the shader-compile-failed path closes inside this async entry\n * (charter proposition 5 consistent abstraction + proposition 4 explicit\n * failure).\n */\nexport async function createShaderModule(\n device: RhiDevice,\n desc: { label?: string | undefined; code: string },\n): Promise<Result<ShaderModule, RhiError>> {\n // In-package reverse lookup of the underlying GPUDevice. After D-S1 the\n // function is renamed to `_internal_getRawDevice`; this call is in the\n // same package as the WeakMap registry so it is allowed by the AC-08\n // grep gate (the gate only restricts cross-package callers).\n const rawDevice = _internal_getRawDevice(device);\n if (rawDevice === undefined) {\n // Rare: the device was not created by makeRhiDevice (external mock, etc.);\n // the degraded path returns shader-compile-failed as a fallback so an AI\n // user's exhaustive switch still matches (proposition 9: graceful\n // degradation).\n return shaderCompileFailed([\n {\n type: 'error',\n message: 'rhi-webgpu: createShaderModule called with unregistered RhiDevice',\n lineNum: 0,\n linePos: 0,\n offset: 0,\n length: 0,\n } as GPUCompilationMessage,\n ]);\n }\n const mirrored: { label?: string; code: string } = { code: desc.code };\n if ('label' in desc && desc.label !== undefined) mirrored.label = desc.label;\n let handle: GPUShaderModule;\n try {\n handle = rawDevice.createShaderModule(mirrored as GPUShaderModuleDescriptor);\n } catch (e) {\n // The synchronous part of a real-device createShaderModule rarely throws\n // (spec: errors are surfaced asynchronously through getCompilationInfo);\n // a few mock shapes might throw — fall back to the\n // shader-compile-failed path.\n const message = e instanceof Error ? e.message : String(e);\n return shaderCompileFailed([\n {\n type: 'error',\n message,\n lineNum: 0,\n linePos: 0,\n offset: 0,\n length: 0,\n } as GPUCompilationMessage,\n ]);\n }\n const handleWithInfo = handle as GPUShaderModule & {\n // forgeax-async-whitelist: dom-native — spec `GPUShaderModule.getCompilationInfo()`\n getCompilationInfo?: () => Promise<GPUCompilationInfo>;\n };\n if (typeof handleWithInfo.getCompilationInfo !== 'function') {\n // A real GPUShaderModule always has getCompilationInfo (spec-mandated);\n // its absence implies the shim path drifted from the spec — the degraded\n // path returns ok (does not block the engine layer; charter\n // proposition 9: graceful degradation).\n return ok(handle as unknown as ShaderModule);\n }\n let info: GPUCompilationInfo;\n try {\n info = await handleWithInfo.getCompilationInfo();\n } catch {\n // getCompilationInfo() rejects when the underlying GPU instance is dropped\n // mid-await — the device was destroyed (or the page is tearing down) while\n // the async compilation-info query was in flight. The module handle was\n // already created synchronously above, so there is nothing left to report;\n // returning ok keeps an unobserved teardown rejection from escaping as an\n // unhandled rejection (charter proposition 9: graceful degradation, same\n // degraded path as the missing-getCompilationInfo branch above).\n return ok(handle as unknown as ShaderModule);\n }\n const errors = info.messages.filter((m) => m.type === 'error');\n if (errors.length > 0) {\n return shaderCompileFailed(info.messages);\n }\n return ok(handle as unknown as ShaderModule);\n}\n\n/**\n * Build a RhiAdapter shim around a raw GPUAdapter (M3 / break-point #2 / K-5 +\n * K-6).\n *\n * Field projection:\n * - `features` <- `new Set([...adapter.features])` (Round 3 fix-up F-P1-2:\n * surfaces a `ReadonlySet<GPUFeatureName>` aligned with\n * `RhiDevice.features`, so AI users use `.has(name)` uniformly across\n * both abstraction layers; previously projected to `ReadonlyArray<string>`\n * which split the cross-tier idiom).\n * - `limits` <- structural copy of `adapter.limits` numeric fields. Spec\n * `GPUSupportedLimits` is a typed object whose enumerable own-keys are\n * exactly the limit fields (research §6.3 + spec normative); the shim\n * surfaces them via `Readonly<Record<string, number>>` for ergonomic AI-\n * user lookups (`adapter.limits.maxTextureDimension2D`).\n * - `requestDevice` forwards to `adapter.requestDevice(opts)` and wraps the\n * resulting `GPUDevice` via `makeRhiDevice` (research §F-5 error paths).\n */\nfunction makeRhiAdapter(rawAdapter: {\n readonly features?: GPUSupportedFeatures | undefined;\n readonly limits?: GPUSupportedLimits | undefined;\n // forgeax-async-whitelist: dom-native — spec `GPUAdapter.requestDevice()` raw forward\n requestDevice(descriptor?: GPUDeviceDescriptor | undefined): Promise<unknown>;\n}): RhiAdapter {\n // Defensive against minimal mock adapters that omit features / limits\n // (the spec mandates them on real adapters, but unit-test mocks\n // historically expose only `requestDevice`). Defaults to empty\n // projections; real adapters always supply both fields.\n const rawFeatures = rawAdapter.features as unknown as ReadonlySet<GPUFeatureName> | undefined;\n const features: ReadonlySet<GPUFeatureName> =\n rawFeatures !== undefined && rawFeatures !== null\n ? new Set(rawFeatures)\n : new Set<GPUFeatureName>();\n const limitsRaw = (rawAdapter.limits as unknown as Record<string, unknown> | undefined) ?? {};\n const limits: Record<string, number> = {};\n for (const key in limitsRaw) {\n const v = limitsRaw[key];\n if (typeof v === 'number') {\n limits[key] = v;\n }\n }\n return {\n features,\n limits: limits as Readonly<Record<string, number>>,\n async requestDevice(\n opts?: ForgeaXRequestDeviceOptions | undefined,\n ): Promise<Result<RhiDevice, RhiError>> {\n let rawDevice: GpuDeviceLike;\n try {\n rawDevice = (await rawAdapter.requestDevice(\n opts as GPUDeviceDescriptor | undefined,\n )) as GpuDeviceLike;\n } catch (e) {\n return classifyRequestDeviceError(e);\n }\n const { device } = makeRhiDevice(rawDevice as unknown as GPUDevice);\n return ok(device);\n },\n };\n}\n\n/**\n * Entry — `requestAdapter` walks `navigator.gpu.requestAdapter(opts)` and\n * wraps the result as a forgeax `RhiAdapter` (M3 break-point #2; K-5 + K-6).\n *\n * Strict two-step path mirrors wgpu / Dawn (research §6); the legacy\n * `requestDevice(opts)` factory below is the deprecated single-step shortcut\n * kept for backward compatibility while existing callers migrate.\n *\n * Optional `gpu` provider seam at the `RequestAdapterOptions`-side: this\n * factory takes only the forgeax-spec `RequestAdapterOptions` (powerPreference\n * / forceFallbackAdapter); when callers need the mock-injection seam they go\n * through the legacy `requestDevice({ gpu })` form.\n *\n * @param opts — W3C-spec request adapter options.\n * @param _compatibleSurface — accepted for dual-impl symmetry\n * (plan-strategy D-5; AGENTS.md \"Dual-impl ship-together\" rule).\n * The browser WebGPU backend does not use this parameter; it is\n * ignored. rhi-wgpu routes it to `requestAdapterWithCanvas`.\n */\nexport async function requestAdapter(\n opts?: RequestAdapterOptions | undefined,\n _compatibleSurface?: HTMLCanvasElement | OffscreenCanvas | undefined,\n): Promise<Result<RhiAdapter, RhiError>> {\n const ambient: GPU | undefined =\n typeof globalThis !== 'undefined'\n ? (globalThis as { navigator?: Navigator }).navigator?.gpu\n : undefined;\n if (ambient === undefined || ambient === null) {\n return adapterUnavailable();\n }\n // `null` is the spec adapter-absence channel. A rejection is a different\n // failure (permission policy, insecure context, browser/runtime fault, etc.)\n // and must retain its cause instead of being rewritten as unsupported WebGPU.\n // Both outcomes remain structured, so Runtime can still try its wgpu/WebGL2\n // fallback without erasing the browser-native channel diagnosis.\n let adapter: unknown;\n try {\n adapter = await ambient.requestAdapter(opts as GPURequestAdapterOptions | undefined);\n } catch (cause) {\n return requestAdapterFailed(cause);\n }\n if (adapter === null) {\n return adapterUnavailable();\n }\n return ok(\n makeRhiAdapter(\n adapter as unknown as {\n readonly features?: GPUSupportedFeatures | undefined;\n readonly limits?: GPUSupportedLimits | undefined;\n // forgeax-async-whitelist: dom-native — spec `GPUAdapter.requestDevice()` cast\n requestDevice(descriptor?: GPUDeviceDescriptor | undefined): Promise<unknown>;\n },\n ),\n );\n}\n\n/**\n * Acquire a canvas rendering context from an HTMLCanvasElement (M3 / w15).\n *\n * Spec anchor: W3C WebGPU §3.3 GPUCanvasContext.\n *\n * Internally calls `canvas.getContext('webgpu')` and wraps the result as a\n * branded RhiCanvasContext. Returns `Result<RhiCanvasContext, RhiError>` —\n * canvas does not support WebGPU returns `RhiError { code: 'rhi-not-available' }`\n * with a precise `.hint` so AI users can display a degradation banner (charter\n * proposition 4 explicit failure).\n *\n * This replaces the legacy `createCanvasContext(rawCtx)` — AGENTS.md §Change stance\n * authorizes the breaking rename (acquireCanvasContext, optimal > compatible).\n *\n * @example\n * const ctxResult = acquireCanvasContext(canvas);\n * if (!ctxResult.ok) {\n * // canvas does not support WebGPU\n * return;\n * }\n * const canvasContext = ctxResult.value;\n * canvasContext.configure({ device, format: 'bgra8unorm', usage: 0x10 });\n */\nexport function acquireCanvasContext(\n canvas: HTMLCanvasElement | OffscreenCanvas,\n): Result<RhiCanvasContext, RhiError> {\n let rawContext: GPUCanvasContext | null;\n try {\n rawContext = canvas.getContext('webgpu') as GPUCanvasContext | null;\n } catch {\n rawContext = null;\n }\n if (rawContext === null) {\n return err(\n new RhiErrorClass({\n code: 'rhi-not-available',\n expected: 'canvas.getContext(\"webgpu\") to return a non-null GPUCanvasContext',\n hint: 'canvas does not support WebGPU — pass an HTMLCanvasElement (or OffscreenCanvas) whose getContext(\"webgpu\") returns a valid GPUCanvasContext',\n }),\n );\n }\n return ok(makeCanvasContext(rawContext));\n}\n\n/**\n * The `rhi` singleton entry (charter proposition 1: progressive disclosure +\n * plan-strategy §7.4 discoverability:\n * 'import { rhi } from @forgeax/engine-rhi-webgpu' + 'Engine.create({ rhi, canvas })'\n * injection shape).\n *\n * Strict two-step path (M3 break-point #2 + M6 fix-up [w51]; K-5 + K-6):\n * `rhi.requestAdapter(opts) -> adapter.requestDevice(opts)`\n *\n * The legacy single-step `rhi.requestDevice(opts)` factory was retired here\n * (AGENTS.md break-point list 2026-05-10 #2). AI users follow the spec\n * idiom (charter proposition 5 consistent abstraction red line):\n * const adapter = (await rhi.requestAdapter()).unwrap();\n * const device = (await adapter.requestDevice(opts)).unwrap();\n */\nexport const rhi: RhiInstance & {\n createShaderModule: typeof createShaderModule;\n acquireCanvasContext: typeof acquireCanvasContext;\n} = {\n requestAdapter,\n createShaderModule,\n acquireCanvasContext,\n};\n\n// Re-export public types so callers consume them through a single entry\n// (charter proposition 1: progressive disclosure / single import surfaces\n// the full RHI consumption chain). Round 3 fix-up F-P2-1: extended from\n// 3 to the full set so AI users do not need a transitive\n// `import { RhiAdapter, ... } from '@forgeax/engine-rhi'` alongside the\n// rhi-webgpu singleton.\nexport type {\n // 14 opaque handles (charter proposition 5 consistent abstraction:\n // brand-only surface; AI users hold these for cross-call resource flow).\n BindGroup,\n // 14 descriptors (Pick<GPU*Descriptor, ...> mirrors; AI users compose\n // these inline before calling device.createX).\n BindGroupDescriptor,\n BindGroupLayout,\n BindGroupLayoutDescriptor,\n Buffer,\n BufferDescriptor,\n CanvasConfiguration,\n CommandBuffer,\n CommandEncoderDescriptor,\n ComputePassDescriptor,\n ComputePassTimestampWrites,\n ComputePipeline,\n ComputePipelineDescriptor,\n Fence,\n PipelineLayout,\n PipelineLayoutDescriptor,\n QuerySet,\n QuerySetDescriptor,\n RenderPassColorAttachment,\n RenderPassDepthStencilAttachment,\n RenderPassDescriptor,\n RenderPipeline,\n RenderPipelineDescriptor,\n RequestAdapterOptions,\n RequestDeviceOptions as RhiRequestDeviceOptions,\n // Result + error model (RhiError class is exported as a value below).\n Result,\n ResultErr,\n ResultOk,\n // Adapter / Device / Instance / surface (M2-M3 main interfaces).\n RhiAdapter,\n RhiAssetNotRegisteredDetail,\n RhiCanvasContext,\n RhiCaps,\n // Command / pass encoder interfaces (M3-M4).\n RhiCommandEncoder,\n RhiComputePassEncoder,\n RhiDevice,\n RhiError,\n RhiErrorCode,\n RhiErrorDetail,\n RhiFeatures,\n RhiInstance,\n RhiLimits,\n RhiQueue,\n RhiRenderPassEncoder,\n RhiShaderCompileDetail,\n RhiSurface,\n RhiWebgpuRuntimeDetail,\n Sampler,\n SamplerDescriptor,\n ShaderModule,\n Texture,\n TextureDescriptor,\n TextureView,\n TextureViewDescriptor,\n} from '@forgeax/engine-rhi';\n\n// Re-export Result factories + RhiError class as values (the rhi-webgpu\n// top-level surface stays single-import for both type-only and runtime\n// consumption).\nexport { err, ok, RhiError as RhiErrorClass } from '@forgeax/engine-rhi';\n// feat-20260511-rhi-spec-realign-aggressive D-VD2 (Round 2) — re-export the\n// `_internal_getRawDevice` reverse lookup. Re-introduces the M4-removed escape\n// hatch for the sole engine consumer that needs to register the spec\n// `onuncapturederror` listener on the raw GPUDevice:\n// `packages/engine/src/createRenderer.ts`. The listener registration is the\n// only browser-WebGPU path through which `Renderer.onError(err =>\n// switch err.code { case 'oom' | 'internal-error' | 'shader-compile-failed':\n// ... })` can fire (AGENTS.md break-point #4 promise; spec GPUDevice extends\n// EventTarget and exposes `onuncapturederror` as a settable property).\n//\n// AC-08 grep gate (`apps/hello/triangle/scripts/ac-08-grep-gate.mjs`) allows\n// engine-internal usage of `_internal_getRawDevice` through the existing\n// `\\bgetRawDevice\\b` word-boundary allowlist; consumers outside the engine\n// layer remain forbidden (charter proposition 5 consistent abstraction red\n// line: the RHI surface stays brand-only for AI-user-facing code; the reverse\n// lookup is the named single-point escape hatch the engine uses to satisfy\n// spec event-target requirements).\nexport { _internal_getRawDevice } from './device';\n// feat-20260511-rhi-spec-realign-aggressive D-VD2 wire-up: re-export the\n// async-dispatch event translator at the top level so the engine layer\n// (packages/engine/src/createRenderer.ts) can register the spec\n// `device.onuncapturederror` listener + the dual-channel `device.lost`\n// fan-out without reaching into `internal/`. AGENTS.md break-point #4 dispatch\n// path promise: rhi-webgpu/src/internal/error-translation.ts translates\n// GPUUncapturedErrorEvent / GPUDeviceLostInfo to the 17-member RhiErrorCode\n// union; engine.onError captures the dispatch (charter proposition 4\n// explicit failure + proposition 5 consistent abstraction across both\n// browser-direct and rhi-wgpu wasm dual paths).\nexport { translateErrorEventToRhiError } from './internal/error-translation';\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/errors.ts","../src/internal/timestamp-query.ts","../src/device.ts","../src/internal/error-translation.ts","../src/index.ts"],"names":["err","RhiError","RhiErrorClass","ok","out"],"mappings":";;;;AAeO,SAAS,kBAAA,GAA8C;AAC5D,EAAA,OAAO,GAAA;AAAA,IACL,IAAI,QAAA,CAAS;AAAA,MACX,IAAA,EAAM,qBAAA;AAAA,MACN,QAAA,EAAU,4CAAA;AAAA,MACV,IAAA,EAAM;AAAA,KACP;AAAA,GACH;AACF;AAGO,SAAS,qBAAqB,KAAA,EAAyC;AAC5E,EAAA,MAAM,SACJ,KAAA,KAAU,IAAA,IA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5B;AAMA,EAAA,IAAI,OAAA;AACJ,EAAA,IAAI;AACF,IAAA,OAAA,GAAU,MAAM,OAAA,CAAQ,cAAA,CAAe,IAA4C,CAAA;AAAA,EACrF,SAAS,KAAA,EAAO;AACd,IAAA,OAAO,qBAAqB,KAAK,CAAA;AAAA,EACnC;AACA,EAAA,IAAI,YAAY,IAAA,EAAM;AACpB,IAAA,OAAO,kBAAA,EAAmB;AAAA,EAC5B;AACA,EAAA,OAAOA,EAAAA;AAAA,IACL,cAAA;AAAA,MACE;AAAA;AAMF,GACF;AACF;AAyBO,SAAS,qBACd,MAAA,EACoC;AACpC,EAAA,IAAI,UAAA;AACJ,EAAA,IAAI;AACF,IAAA,UAAA,GAAa,MAAA,CAAO,WAAW,QAAQ,CAAA;AAAA,EACzC,CAAA,CAAA,MAAQ;AACN,IAAA,UAAA,GAAa,IAAA;AAAA,EACf;AACA,EAAA,IAAI,eAAe,IAAA,EAAM;AACvB,IAAA,OAAOH,GAAAA;AAAA,MACL,IAAIE,QAAAA,CAAc;AAAA,QAChB,IAAA,EAAM,mBAAA;AAAA,QACN,QAAA,EAAU,mEAAA;AAAA,QACV,IAAA,EAAM;AAAA,OACP;AAAA,KACH;AAAA,EACF;AACA,EAAA,OAAOC,EAAAA,CAAG,iBAAA,CAAkB,UAAU,CAAC,CAAA;AACzC;AAiBO,IAAM,GAAA,GAIT;AAAA,EACF,cAAA;AAAA,EACA,kBAAA;AAAA,EACA,2BAAA;AAAA,EACA;AACF","file":"index.mjs","sourcesContent":["// @forgeax/engine-rhi-webgpu/src/errors — RhiError factory functions.\n//\n// Source of truth for the .expected / .hint copy: plan-strategy 7.3 error-info\n// table. After feat-20260508-rhi-surface-completion w7 (D-S3) the surface\n// covers 8 factories: 4 device/shader paths (Round 1) + 4 command/queue paths\n// (this closure: command-encoder-finished / render-pass-not-ended /\n// queue-submit-failed / queue-write-buffer-out-of-bounds).\n//\n// Each .expected / .hint string aligns one-to-one with requirements boundary\n// cases + plan-strategy 7.3 (charter proposition 3: machine-readable hint\n// over prose).\n\nimport { err, type Result, RhiError, type RhiShaderCompileDetail } from '@forgeax/engine-rhi';\n\n/** adapter null path (research F-5 single null channel). */\nexport function adapterUnavailable(): Result<never, RhiError> {\n return err(\n new RhiError({\n code: 'adapter-unavailable',\n expected: 'an available browser-native WebGPU adapter',\n hint: 'this only reports the browser-native WebGPU channel; ForgeaX may continue through its wgpu/WebGL2 fallback, so do not conclude that the browser or machine is unsupported unless both backend causes fail',\n }),\n );\n}\n\n/** `GPU.requestAdapter()` rejected instead of reporting adapter absence with `null`. */\nexport function requestAdapterFailed(cause: unknown): Result<never, RhiError> {\n const record =\n cause !== null && typeof cause === 'object'\n ? (cause as { readonly name?: unknown; readonly message?: unknown })\n : undefined;\n const name = typeof record?.name === 'string' && record.name.length > 0 ? record.name : undefined;\n let message =\n typeof record?.message === 'string' && record.message.length > 0\n ? record.message\n : typeof cause === 'string'\n ? cause\n : '';\n if (message.length === 0 && cause !== undefined) {\n try {\n const serialized = JSON.stringify(cause);\n message = serialized && serialized !== '{}' ? serialized : 'unknown thrown object';\n } catch {\n message = 'unserializable thrown object';\n }\n }\n if (message.length === 0) message = 'unknown requestAdapter failure';\n return err(\n new RhiError({\n code: 'webgpu-runtime-error',\n expected: 'navigator.gpu.requestAdapter() resolves with an adapter or null',\n hint: 'inspect detail.error before assigning the failure to WebGPU capability; the ForgeaX runtime can still attempt its wgpu/WebGL2 fallback',\n detail: {\n error: {\n code: 'request-adapter-threw',\n ...(name === undefined ? {} : { name }),\n message,\n },\n },\n }),\n );\n}\n\n/** feature not enabled path (boundary cases / requirements). */\nexport function featureNotEnabled(featureName?: string | undefined): Result<never, RhiError> {\n const fname = featureName ?? 'compute';\n return err(\n new RhiError({\n code: 'feature-not-enabled',\n expected: `feature ${fname} to be enabled`,\n hint: `verify device.features.${fname} before calling this entry point`,\n }),\n );\n}\n\n/** limit exceeded path (boundary cases / requirements). */\nexport function limitExceeded(limitName?: string | undefined): Result<never, RhiError> {\n const lname = limitName ?? 'maxBindGroups';\n return err(\n new RhiError({\n code: 'limit-exceeded',\n expected: `${lname} to be within bounds`,\n hint: `verify device.limits.${lname}`,\n }),\n );\n}\n\n/** shader compile failed path + detail.compilerMessages forwarding (OQ-P2 6 fields). */\nexport function shaderCompileFailed(\n compilerMessages: readonly GPUCompilationMessage[],\n): Result<never, RhiError> {\n const detail: RhiShaderCompileDetail = { compilerMessages };\n return err(\n new RhiError({\n code: 'shader-compile-failed',\n expected: 'valid WGSL source',\n hint: 'inspect RhiError.detail.compilerMessages (each entry: { message, type, lineNum, linePos, offset, length } per WebGPU GPUCompilationMessage shape)',\n detail,\n }),\n );\n}\n\n/**\n * Command encoder reused after finish() (W3C WebGPU 22 GPUCommandEncoder lifecycle).\n *\n * Trigger: encoder.beginRenderPass / copyXxx / finish called after a prior finish().\n * Distinct from 'rhi-not-available': this is a real-path validation failure,\n * not a placeholder for unimplemented surface (plan-strategy D-S3 template 1).\n */\nexport function commandEncoderFinished(): Result<never, RhiError> {\n return err(\n new RhiError({\n code: 'command-encoder-finished',\n expected: 'command encoder must not be finished before recording new commands',\n hint: 'create a new command encoder via device.createCommandEncoder() for each frame; do not reuse a finished encoder',\n }),\n );\n}\n\n/**\n * Render pass not ended before next pass / finish (W3C WebGPU 22.7 Render pass).\n *\n * Trigger: encoder.beginRenderPass while previous pass active, or encoder.finish\n * with active pass still recording (plan-strategy D-S3 template 2).\n */\nexport function renderPassNotEnded(): Result<never, RhiError> {\n return err(\n new RhiError({\n code: 'render-pass-not-ended',\n expected:\n 'previous render pass must be ended before beginning a new pass or finishing the encoder',\n hint: 'call pass.end() before beginRenderPass() or encoder.finish()',\n }),\n );\n}\n\n/**\n * Queue.submit real-path failure (W3C WebGPU 23 Queue).\n *\n * Trigger: submit([cb]) with destroyed buffer/pipeline references, or GPU validation\n * error fan-out via onuncapturederror. Explicitly distinct from 'rhi-not-available'\n * (device-lost subclass) - submit-failed signals dynamic resource life-cycle issues\n * the AI user can self-recover from (plan-strategy D-S3 template 3).\n */\nexport function queueSubmitFailed(detailMessage?: string | undefined): Result<never, RhiError> {\n const baseHint =\n 'check if any referenced buffer / pipeline / texture has been destroyed before submit';\n const hint =\n detailMessage !== undefined && detailMessage.length > 0\n ? `${baseHint}; underlying GPU error: ${detailMessage}`\n : baseHint;\n return err(\n new RhiError({\n code: 'queue-submit-failed',\n expected:\n 'command buffer references must be valid at submit time (not destroyed; not from a different device)',\n hint,\n }),\n );\n}\n\n/**\n * Queue.writeBuffer offset/size out of bounds (W3C WebGPU 23.2 writeBuffer).\n *\n * Trigger: writeBuffer(buf, offset, data) where offset is not 4-byte aligned, or\n * offset + data.byteLength exceeds buffer.size. Distinct from 'limit-exceeded'\n * (static device.limits) - out-of-bounds is a dynamic per-buffer boundary\n * (plan-strategy D-S3 template 4).\n */\nexport function queueWriteBufferOutOfBounds(args: {\n offset: number;\n byteLength: number;\n bufferSize: number;\n}): Result<never, RhiError> {\n return err(\n new RhiError({\n code: 'queue-write-buffer-out-of-bounds',\n expected:\n 'writeBuffer offset + data.byteLength must be <= buffer.size; offset must be 4-byte aligned',\n hint: `verify offset alignment and bounds: offset (got ${args.offset}) + data.byteLength (got ${args.byteLength}) must be <= buffer.size (got ${args.bufferSize})`,\n }),\n );\n}\n","/// <reference types=\"@webgpu/types\" />\n\nimport { err, ok, type Result, RhiError } from '@forgeax/engine-rhi';\n\nexport function resolveTimestampQueries(args: {\n rawEncoder: GPUCommandEncoder;\n rawQuerySet: GPUQuerySet;\n firstQuery: number;\n queryCount: number;\n rawDestination: GPUBuffer;\n destinationOffset: number;\n}): Result<void, RhiError> {\n try {\n args.rawEncoder.resolveQuerySet(\n args.rawQuerySet,\n args.firstQuery,\n args.queryCount,\n args.rawDestination,\n args.destinationOffset,\n );\n return ok(undefined);\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n return err(\n new RhiError({\n code: 'webgpu-runtime-error',\n expected: 'underlying GPUCommandEncoder.resolveQuerySet to succeed',\n hint: `resolveQuerySet raised: ${message}`,\n }),\n );\n }\n}\n\nexport function writeTimestamp(args: {\n rawEncoder: GPUCommandEncoder;\n rawQuerySet: GPUQuerySet;\n queryIndex: number;\n}): void {\n const encoderWithTimestamp = args.rawEncoder as unknown as {\n writeTimestamp?: (querySet: GPUQuerySet, queryIndex: number) => void;\n };\n if (typeof encoderWithTimestamp.writeTimestamp !== 'function') {\n throw new RhiError({\n code: 'webgpu-runtime-error',\n expected: 'underlying GPUCommandEncoder.writeTimestamp to be callable',\n hint: 'timestamp-query is advertised but the raw encoder has no writeTimestamp method',\n });\n }\n try {\n encoderWithTimestamp.writeTimestamp(args.rawQuerySet, args.queryIndex);\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n throw new RhiError({\n code: 'webgpu-runtime-error',\n expected: 'underlying GPUCommandEncoder.writeTimestamp to succeed',\n hint: `writeTimestamp raised: ${message}`,\n });\n }\n}\n","// @forgeax/engine-rhi-webgpu/src/device - WebGPU GPUDevice -> RhiDevice thin shim.\n//\n// Iron laws (README + AGENTS.md \"## RHI / WebGPU\"):\n// - spec-aligned: 5 + 4 descriptor field names match GPUDevice.createX byte-for-byte.\n// - `?: T | undefined` + `'x' in src` guard distinguishes \"missing\" vs\n// \"explicit undefined\" (research F-3 anti-pattern 2 / hard-constraint 10).\n// - opaque handle: RhiDevice.createX returns Result.ok(handle); the handle\n// internally references the GPU resource but exposes only a brand-only\n// opaque shape (research R5).\n// - capability-gated: caps / features / limits exposed independently as\n// readonly layers (charter proposition 5).\n// - device.lost two-track: spec Promise passthrough + engine-layer\n// LostListenerRegistry (R2 mitigation / research F-4); this package only\n// exposes the spec Promise without a second cache.\n//\n// w3 / w5 / w6 (feat-20260508-rhi-surface-completion, co-commit):\n// - createCommandEncoder + 12 RhiCommandEncoder methods + 3 mixin (w3)\n// - 17 RhiRenderPassEncoder spec stable methods + 1 setBindGroup overload +\n// 3 placeholders (executeBundles / beginOcclusionQuery / endOcclusionQuery) (w5)\n// - Queue.submit / writeBuffer real implementation + bounds validation (w6)\n//\n// co-commit reason: w3, w5, w6 each modify both `@forgeax/engine-rhi/src/index.ts`\n// and `@forgeax/engine-rhi-webgpu/src/device.ts`; the encoder lifecycle (D-S3\n// templates 1 + 2) couples render-pass end() to command-encoder finish(),\n// so independent commits would leave the interface and shim inconsistent\n// between commits.\n\n/// <reference types=\"@webgpu/types\" />\n\nimport type {\n BindGroup,\n BindGroupDescriptor,\n BindGroupLayout,\n BindGroupLayoutDescriptor,\n Buffer,\n BufferDescriptor,\n CanvasConfiguration,\n CommandBuffer,\n CommandEncoderDescriptor,\n ComputePassDescriptor,\n ComputePipeline,\n ComputePipelineDescriptor,\n ExternalImageTextureDestination,\n MappedBuffer,\n PipelineLayout,\n PipelineLayoutDescriptor,\n QuerySet,\n QuerySetDescriptor,\n RenderPassDescriptor,\n RenderPipeline,\n RenderPipelineDescriptor,\n Result,\n RhiCanvasContext,\n RhiCaps,\n RhiCommandEncoder,\n RhiComputePassEncoder,\n RhiDevice,\n RhiError,\n RhiFeatures,\n RhiLimits,\n RhiQueue,\n RhiRenderPassEncoder,\n Sampler,\n SamplerDescriptor,\n Texture,\n TextureDescriptor,\n TextureView,\n TextureViewDescriptor,\n TextureWriteDestination,\n} from '@forgeax/engine-rhi';\nimport { err, ok, RhiError as RhiErrorClass } from '@forgeax/engine-rhi';\nimport {\n commandEncoderFinished,\n queueSubmitFailed,\n queueWriteBufferOutOfBounds,\n renderPassNotEnded,\n} from './errors';\nimport { resolveTimestampQueries, writeTimestamp } from './internal/timestamp-query';\n\n/**\n * Mirror forgeax `?: T | undefined` descriptor onto the spec GPUXxxDescriptor\n * shape with `'x' in src` guards distinguishing missing vs explicit-undefined:\n *\n * - missing key -> out has no key (preserves the spec `?: T` simplified form)\n * - present + undefined -> out has the key set to undefined (technically out\n * of bounds for spec `?: T` but the shim preserves writer intent for\n * downstream test assertions; research F-3 trade-off)\n * - present + value -> out has the key with the value\n *\n * Equivalent shape: under exactOptionalPropertyTypes:true we must spread\n * rather than `dst[k] = src[k]` because the latter maps both missing and\n * explicit-undefined to \"present + undefined\".\n */\ntype MirrorOut = Record<string, unknown>;\n\nfunction mirror<TIn extends Record<string, unknown>>(\n src: TIn,\n keys: readonly (keyof TIn & string)[],\n): MirrorOut {\n const out: MirrorOut = {};\n for (const k of keys) {\n if (k in src) {\n out[k] = src[k];\n }\n }\n return out;\n}\n\nconst BUFFER_KEYS = ['label', 'size', 'usage', 'mappedAtCreation'] as const;\nconst TEXTURE_KEYS = [\n 'label',\n 'size',\n 'mipLevelCount',\n 'sampleCount',\n 'dimension',\n 'format',\n 'usage',\n 'viewFormats',\n 'textureBindingViewDimension',\n] as const;\nconst SAMPLER_KEYS = [\n 'label',\n 'addressModeU',\n 'addressModeV',\n 'addressModeW',\n 'magFilter',\n 'minFilter',\n 'mipmapFilter',\n 'lodMinClamp',\n 'lodMaxClamp',\n 'compare',\n 'maxAnisotropy',\n] as const;\nconst BGL_KEYS = ['label', 'entries'] as const;\n// BG_KEYS removed in w20 — createBindGroup now uses tagged-union dispatch\n// over RhiBindingResource 4 kinds (not field-mirror passthrough).\nconst PL_KEYS = ['label', 'bindGroupLayouts'] as const;\nconst ENC_KEYS = ['label'] as const;\nconst TEXTURE_VIEW_KEYS = [\n 'label',\n 'format',\n 'dimension',\n 'usage',\n 'aspect',\n 'baseMipLevel',\n 'mipLevelCount',\n 'baseArrayLayer',\n 'arrayLayerCount',\n] as const;\nconst CP_KEYS = ['label', 'layout', 'compute'] as const;\nconst QS_KEYS = ['label', 'type', 'count'] as const;\n/** Spec normative upper bound on QuerySet.count (research §1.3 device timeline step 1). */\nconst QUERY_SET_COUNT_LIMIT = 4096;\n\n/**\n * RhiDevice -> raw GPUDevice reverse lookup table (fix-f3).\n *\n * After RhiDevice.createShaderModule was removed, the top-level async\n * `createShaderModule(device, desc)` entry point needs to reach the\n * underlying GPUDevice. The WeakMap keeps the public RhiDevice surface clean\n * (no internal field) and clears automatically when the device is GC'd\n * (charter proposition 5 consistent abstraction).\n *\n * Buffer<->raw GPUBuffer / Encoder<->raw GPUCommandEncoder etc. WeakMaps\n * follow the same pattern; they enable the queue.writeBuffer real-path to\n * resolve buffer.size for bounds validation, and the encoder shim to\n * forward recording calls to the underlying GPUCommandEncoder.\n */\nconst RAW_DEVICE_MAP: WeakMap<RhiDevice, GPUDevice> = new WeakMap();\nconst BUFFER_RAW_MAP: WeakMap<Buffer, GPUBuffer> = new WeakMap();\nconst TEXTURE_VIEW_RAW_MAP: WeakMap<TextureView, GPUTextureView> = new WeakMap();\nconst ENCODER_STATE: WeakMap<RhiCommandEncoder, EncoderState> = new WeakMap();\nconst PASS_STATE: WeakMap<RhiRenderPassEncoder, PassState> = new WeakMap();\nconst COMMAND_BUFFER_RAW_MAP: WeakMap<CommandBuffer, GPUCommandBuffer> = new WeakMap();\n\n/**\n * Texture metadata tracked by the shim for createTextureView fast-path\n * cross-resource validation (research §1.1):\n * - format / viewFormats: format must be in (format ∪ viewFormats).\n * - usage: createTextureView usage must be a subset of source usage.\n *\n * The shim records these at createTexture time; createTextureView reads them\n * before forwarding to the raw GPU. spec rationale: GPUTexture exposes\n * `.format` / `.usage` etc. as readonly fields, but `.viewFormats` is not\n * surfaced as a runtime field on GPUTexture in @webgpu/types v0.1.69 — the\n * shim must remember it from the descriptor.\n */\ninterface TextureMeta {\n readonly format: GPUTextureFormat;\n readonly usage: GPUTextureUsageFlags;\n readonly viewFormats: readonly GPUTextureFormat[];\n /**\n * Per-handle lifecycle marker for `RhiDevice.destroyTexture` fail-fast\n * (feat-20260612 D-7). Mutated to `true` by the first successful\n * `destroyTexture(tex)` call; a second destroy on the same handle reads\n * the flag and surfaces `Result.err({ code: 'destroy-after-destroy' })`\n * rather than forwarding to the underlying spec idempotent void.\n */\n destroyed: boolean;\n}\nconst TEXTURE_META_MAP: WeakMap<Texture, TextureMeta> = new WeakMap();\n\ninterface EncoderState {\n raw: GPUCommandEncoder;\n finished: boolean;\n activePass: RhiRenderPassEncoder | null;\n}\n\ninterface PassState {\n raw: GPURenderPassEncoder;\n ended: boolean;\n encoder: RhiCommandEncoder;\n // [[occlusion_query_set]] (research §2.1): the QuerySet injected via\n // GPURenderPassDescriptor.occlusionQuerySet at beginRenderPass time.\n // null means occlusion queries are unavailable in this pass.\n occlusionQuerySet: QuerySet | null;\n // [[occlusion_query_active]] (research §2.1): true when a beginOcclusionQuery\n // has been issued without a matching endOcclusionQuery yet. Spec normative:\n // pairs cannot nest.\n occlusionQueryActive: boolean;\n // queryIndex written by a previous beginOcclusionQuery in this pass; spec\n // normative: a queryIndex written previously in this pass cannot be reused\n // (cross-pass reuse on the same querySet is legal per dawn `Rewrite` mode).\n occlusionQueryWritten: Set<number>;\n}\n\n/** WeakMap that tracks raw GPUQuerySet for createQuerySet handles so the shim\n * can read `.count` for queryIndex bounds checking (research §2.1 step 2). */\nconst QUERY_SET_RAW_MAP: WeakMap<QuerySet, GPUQuerySet> = new WeakMap();\nconst QUERY_SET_DESTROYED_MAP: WeakMap<QuerySet, { destroyed: boolean }> = new WeakMap();\n\n/**\n * WeakMap that tracks Buffer metadata (size + usage) so resolveQuerySet (and\n * other shim entry points) can validate spec preconditions before forwarding\n * to the raw GPU (research §2.3 destination.usage / destinationOffset bounds).\n *\n * usage is the bitmask passed at createBuffer time; size is `desc.size` (the\n * underlying GPUBuffer.size is also readable but the shim records the\n * descriptor-level size for parity with TextureMeta).\n */\ninterface BufferMeta {\n readonly size: number;\n readonly usage: GPUBufferUsageFlags;\n /**\n * Per-handle lifecycle marker for `RhiDevice.destroyBuffer` fail-fast\n * (feat-20260612 D-7). Mutated to `true` by the first successful\n * `destroyBuffer(buf)` call; a second destroy on the same handle reads\n * the flag and surfaces `Result.err({ code: 'destroy-after-destroy' })`\n * rather than forwarding to the underlying spec idempotent void.\n */\n destroyed: boolean;\n}\nconst BUFFER_META_MAP: WeakMap<Buffer, BufferMeta> = new WeakMap();\n/** GPUBufferUsage.QUERY_RESOLVE bit (W3C WebGPU §3.5.2 GPUBufferUsage). */\nconst BUFFER_USAGE_QUERY_RESOLVE = 0x200;\n/** Spec normative resolve alignment (research §2.3 step 6 +\n * kQueryResolveAlignment in dawn). */\nconst QUERY_RESOLVE_ALIGNMENT = 256;\n\n/**\n * Get the underlying GPUDevice associated with a RhiDevice.\n *\n * @internal\n *\n * Single-point escape hatch (D-S1 / feat-20260508-rhi-surface-completion).\n * The `_internal_` prefix + `@internal` JSDoc tag mark this as engine-internal\n * plumbing; the only sanctioned consumer is\n * `apps/hello/triangle/src/main.ts:96` which threads the raw GPUDevice into\n * the host's internal canvas-device configuration slot so the canvas\n * `GPUCanvasContext.configure({device})` slot keeps working\n * (GPUCanvasContext is outside the RHI surface). Every other engine path\n * goes through the RHI interface.\n *\n * Future: deprecated once `feat-future-rhi-adapter-surface` lands a\n * `RhiCanvasContext` abstraction; this function will be removed at that\n * closure. AC-08 grep gate keeps further callers out via word-boundary\n * `\\bgetRawDevice\\b` allow-list (see apps/hello/triangle/scripts/ac-08-grep-gate.mjs).\n */\nexport function _internal_getRawDevice(device: RhiDevice): GPUDevice | undefined {\n return RAW_DEVICE_MAP.get(device);\n}\n\n// Caps probe — split by spec-feature gate vs mandatory-but-spec-noncompliant\n// fallback (m1-1-b scope-amend, plan §6 D-2 gap):\n//\n// * Optional spec features (`rg11b10ufloat-renderable`,\n// `float32-filterable`) carry an authoritative `device.features.has(...)`\n// answer. A `createTexture` probe on the unsupported format triggers a\n// WebGPU validation error which the dawn / Chrome implementations\n// fan out via `device.onuncapturederror` even when caught by JS try /\n// catch — the SUT-level `onerror-gate` (apps/shared/src/onerror-gate.ts)\n// observes that channel and turns a green-on-paper probe into a CI red\n// `limit-exceeded` error. Solution: gate the probe by `features.has(...)`\n// first and skip the destructive `createTexture` call entirely when the\n// feature is absent.\n//\n// * `rgba16float` is mandatory `RENDER_ATTACHMENT` per spec but observed\n// unreliable on WebKit — exactly the AC-02 motivation. Keep the real\n// `createTexture` probe here: any browser declaring it but rejecting at\n// `createTexture` time deserves a `false` cap, and a violation under\n// `rgba16float` would ALREADY break HDR / IBL paths so the\n// onuncapturederror fan-out is correctly diagnostic, not noise.\n\nfunction probeRgba16floatRenderable(device: GPUDevice): boolean {\n let tex: GPUTexture | undefined;\n try {\n tex = device.createTexture({\n label: 'forgeax-caps-probe-rgba16float-renderable',\n format: 'rgba16float',\n usage: 16, // GPUTextureUsage.RENDER_ATTACHMENT\n size: [1, 1, 1],\n });\n return true;\n } catch {\n return false;\n } finally {\n tex?.destroy?.();\n }\n}\n\nfunction probeRg11b10ufloatRenderable(device: GPUDevice, features: GPUSupportedFeatures): boolean {\n // Feature-gated: `rg11b10ufloat-renderable` is an optional feature per spec.\n // Skip the destructive createTexture probe when the feature is absent so the\n // dawn / Chrome backend's onuncapturederror channel does not fire (CI gate).\n if (!features.has('rg11b10ufloat-renderable' as GPUFeatureName)) return false;\n let tex: GPUTexture | undefined;\n try {\n tex = device.createTexture({\n label: 'forgeax-caps-probe-rg11b10ufloat-renderable',\n format: 'rg11b10ufloat',\n usage: 16, // GPUTextureUsage.RENDER_ATTACHMENT\n size: [1, 1, 1],\n });\n return true;\n } catch {\n return false;\n } finally {\n tex?.destroy?.();\n }\n}\n\nfunction probeFloat32Filterable(device: GPUDevice, features: GPUSupportedFeatures): boolean {\n // Feature-gated: `float32-filterable` is an optional feature per spec.\n // The bind-group-layout validation below would trigger\n // onuncapturederror when the feature is absent.\n if (!features.has('float32-filterable' as GPUFeatureName)) return false;\n try {\n device.createBindGroupLayout({\n entries: [\n { binding: 0, visibility: 2, sampler: { type: 'filtering' } }, // GPUShaderStage.FRAGMENT = 2\n { binding: 1, visibility: 2, texture: { sampleType: 'float' } },\n ],\n });\n device.createSampler({ minFilter: 'linear', magFilter: 'linear' });\n return true;\n } catch {\n return false;\n }\n}\n\n/** Probe the 11 caps fields from GPUDevice.features + GPUDevice.limits\n * (charter proposition 5). 4 new fields (samplerAliasing /\n * firstInstanceIndirect / storageBuffer / storageTexture) added by\n * feat-20260511-rhi-spec-realign-aggressive w19 per D-P3 + research R-03\n * §3.1 mapping matrix. 3 new HDR / filterable caps fields\n * (rgba16floatRenderable / rg11b10ufloatRenderable / float32Filterable)\n * added by feat-20260608-rhi-hdr-renderable-caps-and-warn-once M1 per\n * D-1 + D-2 + D-2.1. */\nfunction deriveCaps(\n rawDevice: GPUDevice,\n features: GPUSupportedFeatures,\n limits: GPUSupportedLimits,\n): RhiCaps {\n const has = (name: string): boolean => features.has(name as GPUFeatureName);\n // Texture-compression three-way caps (M4 w26): derived from adapter.features\n // per-compression-format, replacing the single rolled-up boolean.\n // D-8: no hand-assigned true/false literals; all derived via has(...) from\n // the features Set.\n const textureCompressionBc = has('texture-compression-bc');\n const textureCompressionEtc2 = has('texture-compression-etc2');\n const textureCompressionAstc = has('texture-compression-astc');\n // HDR renderable + filterable caps (m1-1-b: split probe by spec-feature gate\n // vs mandatory-but-noncompliant fallback). `rgba16float` is mandatory\n // `RENDER_ATTACHMENT` per spec but unreliable on WebKit — keep the real\n // probe (AC-02 motivation). `rg11b10ufloat-renderable` and `float32-\n // filterable` carry authoritative `features.has(...)` answers; gate by\n // feature first to avoid fan-out via `device.onuncapturederror` (apps/\n // shared/src/onerror-gate.ts) when the optional feature is absent.\n const hdrCaps = {\n rgba16floatRenderable: probeRgba16floatRenderable(rawDevice),\n rg11b10ufloatRenderable: probeRg11b10ufloatRenderable(rawDevice, features),\n float32Filterable: probeFloat32Filterable(rawDevice, features),\n };\n return {\n backendKind: 'webgpu' as const,\n compute: true, // WebGPU spec mandates compute-pipeline support.\n timestampQuery: has('timestamp-query'),\n timestampPeriodNanoseconds: has('timestamp-query') ? 1 : null,\n indirectDrawing: true, // WebGPU spec mandates drawIndirect / drawIndexedIndirect.\n textureCompressionBc,\n textureCompressionEtc2,\n textureCompressionAstc,\n multiDrawIndirect: false, // wgpu native extension; unavailable on WebGPU browser path.\n pushConstants: false, // wgpu native extension; unavailable on WebGPU browser path.\n textureBindingArray: false, // wgpu native extension; unavailable on WebGPU browser path.\n // 4 new fields (D-P3 / R-03 §3.1):\n samplerAliasing: true, // spec mandatory on browser backends.\n firstInstanceIndirect: has('indirect-first-instance'),\n storageBuffer: (limits.maxStorageBuffersPerShaderStage ?? 0) > 0,\n storageTexture: (limits.maxStorageTexturesPerShaderStage ?? 0) > 0,\n // HDR / filterable caps (feat-20260608 M1):\n ...hdrCaps,\n maxColorAttachments: limits.maxColorAttachments ?? 4,\n };\n}\n\n/**\n * Build a RhiRenderPassEncoder around a raw GPURenderPassEncoder (w5).\n *\n * - 14 real-path methods forward to GPURenderPassEncoder.\n * - 3 placeholders (executeBundles / beginOcclusionQuery / endOcclusionQuery)\n * return Result.err({ code: 'rhi-not-available' }) per D-S4.\n * - end() flips PassState.ended so the encoder finish() can detect a\n * render-pass-not-ended condition (D-S3 template 2).\n */\nfunction makeRenderPassEncoder(\n rawPass: GPURenderPassEncoder,\n encoder: RhiCommandEncoder,\n occlusionQuerySet: QuerySet | null,\n): RhiRenderPassEncoder {\n const pass: RhiRenderPassEncoder = {\n setPipeline(pipeline: RenderPipeline): void {\n rawPass.setPipeline(pipeline as unknown as GPURenderPipeline);\n },\n setVertexBuffer(\n slot: number,\n buffer: Buffer,\n offset?: number | undefined,\n size?: number | undefined,\n ): void {\n // M5 / w35: resolve forgeax Buffer wrapper to raw GPUBuffer.\n const rawBuf = BUFFER_RAW_MAP.get(buffer) ?? (buffer as unknown as GPUBuffer);\n rawPass.setVertexBuffer(slot, rawBuf, offset, size);\n },\n setIndexBuffer(\n buffer: Buffer,\n format: 'uint16' | 'uint32',\n offset?: number | undefined,\n size?: number | undefined,\n ): void {\n // M5 / w35: resolve forgeax Buffer wrapper to raw GPUBuffer.\n const rawBuf = BUFFER_RAW_MAP.get(buffer) ?? (buffer as unknown as GPUBuffer);\n rawPass.setIndexBuffer(rawBuf, format, offset, size);\n },\n setBindGroup(\n index: number,\n bindGroup: BindGroup,\n arg3?: readonly number[] | Uint32Array | undefined,\n arg4?: number | undefined,\n arg5?: number | undefined,\n ): void {\n // Two overload forms (D-S4 setBindGroup):\n // (a) (index, bindGroup, dynamicOffsets?: readonly number[])\n // (b) (index, bindGroup, dynamicOffsetsData: Uint32Array,\n // dynamicOffsetsDataStart, dynamicOffsetsDataLength)\n if (arg3 instanceof Uint32Array) {\n rawPass.setBindGroup(\n index,\n bindGroup as unknown as GPUBindGroup,\n arg3,\n arg4 ?? 0,\n arg5 ?? arg3.length,\n );\n } else if (arg3 === undefined) {\n rawPass.setBindGroup(index, bindGroup as unknown as GPUBindGroup);\n } else {\n rawPass.setBindGroup(index, bindGroup as unknown as GPUBindGroup, arg3);\n }\n },\n draw(\n vertexCount: number,\n instanceCount?: number | undefined,\n firstVertex?: number | undefined,\n firstInstance?: number | undefined,\n ): void {\n rawPass.draw(vertexCount, instanceCount, firstVertex, firstInstance);\n },\n drawIndexed(\n indexCount: number,\n instanceCount?: number | undefined,\n firstIndex?: number | undefined,\n baseVertex?: number | undefined,\n firstInstance?: number | undefined,\n ): void {\n rawPass.drawIndexed(indexCount, instanceCount, firstIndex, baseVertex, firstInstance);\n },\n setViewport(\n x: number,\n y: number,\n w: number,\n h: number,\n minDepth: number,\n maxDepth: number,\n ): void {\n rawPass.setViewport(x, y, w, h, minDepth, maxDepth);\n },\n setScissorRect(x: number, y: number, w: number, h: number): void {\n rawPass.setScissorRect(x, y, w, h);\n },\n setBlendConstant(color: GPUColor): void {\n rawPass.setBlendConstant(color);\n },\n setStencilReference(reference: number): void {\n rawPass.setStencilReference(reference);\n },\n drawIndirect(indirectBuffer: Buffer, indirectOffset: number): void {\n const rawBuf = BUFFER_RAW_MAP.get(indirectBuffer) ?? (indirectBuffer as unknown as GPUBuffer);\n rawPass.drawIndirect(rawBuf, indirectOffset);\n },\n drawIndexedIndirect(indirectBuffer: Buffer, indirectOffset: number): void {\n const rawBuf = BUFFER_RAW_MAP.get(indirectBuffer) ?? (indirectBuffer as unknown as GPUBuffer);\n rawPass.drawIndexedIndirect(rawBuf, indirectOffset);\n },\n pushDebugGroup(groupLabel: string): void {\n rawPass.pushDebugGroup(groupLabel);\n },\n popDebugGroup(): void {\n rawPass.popDebugGroup();\n },\n insertDebugMarker(markerLabel: string): void {\n rawPass.insertDebugMarker(markerLabel);\n },\n executeBundles(_bundles: Iterable<unknown>): Result<void, RhiError> {\n return err(\n new RhiErrorClass({\n code: 'rhi-not-available',\n expected: 'render bundle creation requires future closed loop',\n hint: 'see feat-future-rhi-render-bundle',\n }),\n );\n },\n beginOcclusionQuery(queryIndex: number): Result<void, RhiError> {\n const state = PASS_STATE.get(pass);\n if (state === undefined) {\n return err(\n new RhiErrorClass({\n code: 'webgpu-runtime-error',\n expected: 'render pass state must exist',\n hint: 'beginOcclusionQuery called on an untracked render pass',\n }),\n );\n }\n // Step 1 (research §2.1): [[occlusion_query_set]] != null.\n if (state.occlusionQuerySet === null) {\n return err(\n new RhiErrorClass({\n code: 'webgpu-runtime-error',\n expected: 'GPURenderPassDescriptor.occlusionQuerySet must be set',\n hint: 'pass occlusionQuerySet in RenderPassDescriptor before beginOcclusionQuery',\n }),\n );\n }\n // Step 4 (research §2.1): [[occlusion_query_active]] == false (no nesting).\n // K-2: nested begin maps to webgpu-runtime-error (NOT a new code).\n if (state.occlusionQueryActive) {\n return err(\n new RhiErrorClass({\n code: 'webgpu-runtime-error',\n expected:\n '[[occlusion_query_active]] == false; pair beginOcclusionQuery / endOcclusionQuery',\n hint: 'call endOcclusionQuery() before beginOcclusionQuery() again; occlusion queries cannot nest (spec §render-passes)',\n }),\n );\n }\n // Step 2 (research §2.1): queryIndex < querySet.count.\n const rawQs = QUERY_SET_RAW_MAP.get(state.occlusionQuerySet);\n const qsCount =\n rawQs !== undefined && typeof rawQs.count === 'number'\n ? rawQs.count\n : Number.MAX_SAFE_INTEGER;\n if (queryIndex < 0 || queryIndex >= qsCount) {\n return err(\n new RhiErrorClass({\n code: 'webgpu-runtime-error',\n expected: 'queryIndex < querySet.count',\n hint: `got queryIndex=${queryIndex}; querySet.count=${qsCount}`,\n }),\n );\n }\n // Step 3 (research §2.1): queryIndex not yet written in this pass.\n // Cross-pass reuse on the same querySet is legal (dawn `Rewrite` mode).\n if (state.occlusionQueryWritten.has(queryIndex)) {\n return err(\n new RhiErrorClass({\n code: 'webgpu-runtime-error',\n expected: 'queryIndex must not have been written in this pass',\n hint: `queryIndex=${queryIndex} was already written; cross-pass reuse on the same querySet is legal but in-pass reuse is not (spec §queries)`,\n }),\n );\n }\n try {\n rawPass.beginOcclusionQuery(queryIndex);\n state.occlusionQueryActive = true;\n state.occlusionQueryWritten.add(queryIndex);\n return ok(undefined);\n } catch (e) {\n const message = e instanceof Error ? e.message : String(e);\n return err(\n new RhiErrorClass({\n code: 'webgpu-runtime-error',\n expected: 'underlying GPURenderPassEncoder.beginOcclusionQuery to succeed',\n hint: `beginOcclusionQuery raised: ${message}`,\n }),\n );\n }\n },\n endOcclusionQuery(): Result<void, RhiError> {\n const state = PASS_STATE.get(pass);\n if (state === undefined) {\n return err(\n new RhiErrorClass({\n code: 'webgpu-runtime-error',\n expected: 'render pass state must exist',\n hint: 'endOcclusionQuery called on an untracked render pass',\n }),\n );\n }\n // Spec normative (research §2.1): [[occlusion_query_active]] must be true.\n // K-2: end without active begin maps to render-pass-not-ended (existing\n // 14-member union).\n if (!state.occlusionQueryActive) {\n return renderPassNotEnded();\n }\n try {\n rawPass.endOcclusionQuery();\n state.occlusionQueryActive = false;\n return ok(undefined);\n } catch (e) {\n const message = e instanceof Error ? e.message : String(e);\n return err(\n new RhiErrorClass({\n code: 'webgpu-runtime-error',\n expected: 'underlying GPURenderPassEncoder.endOcclusionQuery to succeed',\n hint: `endOcclusionQuery raised: ${message}`,\n }),\n );\n }\n },\n end(): void {\n const state = PASS_STATE.get(pass);\n if (state !== undefined) {\n state.ended = true;\n }\n rawPass.end();\n // Clear active-pass tracking on the owning encoder.\n const encState = ENCODER_STATE.get(encoder);\n if (encState !== undefined && encState.activePass === pass) {\n encState.activePass = null;\n }\n },\n };\n PASS_STATE.set(pass, {\n raw: rawPass,\n ended: false,\n encoder,\n occlusionQuerySet,\n occlusionQueryActive: false,\n occlusionQueryWritten: new Set<number>(),\n });\n return pass;\n}\n\nconst ENCODER_FINISHED_ERROR_ARGS = {\n code: 'command-encoder-finished' as const,\n expected: 'command encoder must not be finished before recording new commands',\n hint: 'create a new command encoder via device.createCommandEncoder() for each frame; do not reuse a finished encoder',\n};\n\nfunction throwIfFinished(state: EncoderState | undefined): void {\n if (state?.finished) {\n throw new RhiErrorClass(ENCODER_FINISHED_ERROR_ARGS);\n }\n}\n\nfunction rawTextureView(view: TextureView): GPUTextureView {\n return TEXTURE_VIEW_RAW_MAP.get(view) ?? (view as unknown as GPUTextureView);\n}\n\nfunction mirrorRenderPassDescriptor(desc: RenderPassDescriptor): GPURenderPassDescriptor {\n const colorAttachments: Array<GPURenderPassColorAttachment | null> = [];\n for (const attachment of desc.colorAttachments) {\n if (attachment === null || attachment === undefined) {\n colorAttachments.push(null);\n continue;\n }\n if (attachment.loadOp === undefined || attachment.storeOp === undefined) {\n throw new TypeError('RHI render-pass color attachments require loadOp and storeOp');\n }\n colorAttachments.push({\n view: rawTextureView(attachment.view),\n ...(attachment.depthSlice === undefined ? {} : { depthSlice: attachment.depthSlice }),\n ...(attachment.resolveTarget === undefined\n ? {}\n : { resolveTarget: rawTextureView(attachment.resolveTarget) }),\n ...(attachment.clearValue === undefined ? {} : { clearValue: attachment.clearValue }),\n loadOp: attachment.loadOp,\n storeOp: attachment.storeOp,\n });\n }\n\n return {\n ...(desc.label === undefined ? {} : { label: desc.label }),\n colorAttachments,\n ...(desc.depthStencilAttachment === undefined\n ? {}\n : {\n depthStencilAttachment: {\n view: rawTextureView(desc.depthStencilAttachment.view),\n ...(desc.depthStencilAttachment.depthClearValue === undefined\n ? {}\n : { depthClearValue: desc.depthStencilAttachment.depthClearValue }),\n ...(desc.depthStencilAttachment.depthLoadOp === undefined\n ? {}\n : { depthLoadOp: desc.depthStencilAttachment.depthLoadOp }),\n ...(desc.depthStencilAttachment.depthStoreOp === undefined\n ? {}\n : { depthStoreOp: desc.depthStencilAttachment.depthStoreOp }),\n ...(desc.depthStencilAttachment.depthReadOnly === undefined\n ? {}\n : { depthReadOnly: desc.depthStencilAttachment.depthReadOnly }),\n ...(desc.depthStencilAttachment.stencilClearValue === undefined\n ? {}\n : { stencilClearValue: desc.depthStencilAttachment.stencilClearValue }),\n ...(desc.depthStencilAttachment.stencilLoadOp === undefined\n ? {}\n : { stencilLoadOp: desc.depthStencilAttachment.stencilLoadOp }),\n ...(desc.depthStencilAttachment.stencilStoreOp === undefined\n ? {}\n : { stencilStoreOp: desc.depthStencilAttachment.stencilStoreOp }),\n ...(desc.depthStencilAttachment.stencilReadOnly === undefined\n ? {}\n : { stencilReadOnly: desc.depthStencilAttachment.stencilReadOnly }),\n },\n }),\n ...(desc.occlusionQuerySet === undefined\n ? {}\n : {\n occlusionQuerySet:\n QUERY_SET_RAW_MAP.get(desc.occlusionQuerySet) ??\n (desc.occlusionQuerySet as unknown as GPUQuerySet),\n }),\n ...(desc.timestampWrites === undefined\n ? {}\n : {\n timestampWrites: {\n querySet:\n QUERY_SET_RAW_MAP.get(desc.timestampWrites.querySet) ??\n (desc.timestampWrites.querySet as unknown as GPUQuerySet),\n ...(desc.timestampWrites.beginningOfPassWriteIndex === undefined\n ? {}\n : { beginningOfPassWriteIndex: desc.timestampWrites.beginningOfPassWriteIndex }),\n ...(desc.timestampWrites.endOfPassWriteIndex === undefined\n ? {}\n : { endOfPassWriteIndex: desc.timestampWrites.endOfPassWriteIndex }),\n },\n }),\n ...(desc.maxDrawCount === undefined ? {} : { maxDrawCount: desc.maxDrawCount }),\n };\n}\n\nfunction mirrorRenderPipelineDescriptor(\n desc: RenderPipelineDescriptor,\n): GPURenderPipelineDescriptor {\n const vertex: GPUVertexState = {\n module: desc.vertex.module as unknown as GPUShaderModule,\n ...(desc.vertex.buffers === undefined ? {} : { buffers: Array.from(desc.vertex.buffers) }),\n ...(desc.vertex.entryPoint === undefined ? {} : { entryPoint: desc.vertex.entryPoint }),\n ...(desc.vertex.constants === undefined ? {} : { constants: desc.vertex.constants }),\n };\n const fragment: GPUFragmentState | undefined =\n desc.fragment === undefined\n ? undefined\n : {\n module: desc.fragment.module as unknown as GPUShaderModule,\n targets: Array.from(desc.fragment.targets),\n ...(desc.fragment.entryPoint === undefined\n ? {}\n : { entryPoint: desc.fragment.entryPoint }),\n ...(desc.fragment.constants === undefined ? {} : { constants: desc.fragment.constants }),\n };\n return {\n ...(desc.label === undefined ? {} : { label: desc.label }),\n layout: desc.layout === 'auto' ? 'auto' : (desc.layout as unknown as GPUPipelineLayout),\n vertex,\n ...(desc.primitive === undefined ? {} : { primitive: desc.primitive }),\n ...(desc.depthStencil === undefined ? {} : { depthStencil: desc.depthStencil }),\n ...(desc.multisample === undefined ? {} : { multisample: desc.multisample }),\n ...(fragment === undefined ? {} : { fragment }),\n };\n}\n\n/**\n * Build a RhiCommandEncoder around a raw GPUCommandEncoder (w3).\n *\n * Lifecycle:\n * - finish() flips finished=true and returns CommandBuffer once.\n * - subsequent recording calls (beginRenderPass / copyXxx / clearBuffer /\n * finish itself) return Result.err({ code: 'command-encoder-finished' })\n * for those methods that return Result; the void-returning methods throw\n * the structured error so AI users observe the failure (charter\n * proposition 4 explicit failure).\n * - render-pass-not-ended is detected by tracking activePass; finish()\n * while a pass has not been end()-ed returns the structured error.\n */\nfunction makeCommandEncoder(\n rawEncoder: GPUCommandEncoder,\n caps: { readonly timestampQuery: boolean },\n fireFeatureNotEnabled: (featureName: string, hint: string) => void,\n): RhiCommandEncoder {\n function mirrorComputePassDescriptor(\n desc: ComputePassDescriptor | undefined,\n ): GPUComputePassDescriptor | undefined {\n if (desc === undefined) return undefined;\n const out = mirror(desc, ['label']);\n if ('timestampWrites' in desc) {\n const writes = desc.timestampWrites;\n out.timestampWrites =\n writes === undefined\n ? undefined\n : {\n querySet:\n QUERY_SET_RAW_MAP.get(writes.querySet) ??\n (writes.querySet as unknown as GPUQuerySet),\n ...(writes.beginningOfPassWriteIndex === undefined\n ? {}\n : { beginningOfPassWriteIndex: writes.beginningOfPassWriteIndex }),\n ...(writes.endOfPassWriteIndex === undefined\n ? {}\n : { endOfPassWriteIndex: writes.endOfPassWriteIndex }),\n };\n }\n return out as unknown as GPUComputePassDescriptor;\n }\n\n const enc: RhiCommandEncoder = {\n beginRenderPass(desc: RenderPassDescriptor): RhiRenderPassEncoder {\n const state = ENCODER_STATE.get(enc);\n throwIfFinished(state);\n const rawPass = rawEncoder.beginRenderPass(mirrorRenderPassDescriptor(desc));\n // Extract occlusionQuerySet from the descriptor (research §2.2:\n // RPDesc.occlusionQuerySet is the injection point; the render pass\n // PassState.[[occlusion_query_set]] mirrors it). The forgeax\n // RenderPassDescriptor declares occlusionQuerySet as `QuerySet |\n // undefined`; the raw GPU descriptor is structurally compatible.\n const occlusionQuerySet = desc.occlusionQuerySet ?? null;\n const pass = makeRenderPassEncoder(rawPass, enc, occlusionQuerySet);\n if (state !== undefined) state.activePass = pass;\n return pass;\n },\n beginComputePass(desc?: ComputePassDescriptor | undefined): RhiComputePassEncoder {\n const state = ENCODER_STATE.get(enc);\n throwIfFinished(state);\n const rawDescriptor = mirrorComputePassDescriptor(desc);\n const rawPass =\n rawDescriptor === undefined\n ? rawEncoder.beginComputePass()\n : rawEncoder.beginComputePass(rawDescriptor);\n const pass: RhiComputePassEncoder = {\n setPipeline(pipeline) {\n rawPass.setPipeline(pipeline as unknown as GPUComputePipeline);\n },\n setBindGroup(index, bindGroup, dynamicOffsets) {\n if (dynamicOffsets === undefined) {\n rawPass.setBindGroup(index, bindGroup as unknown as GPUBindGroup);\n } else {\n rawPass.setBindGroup(index, bindGroup as unknown as GPUBindGroup, dynamicOffsets);\n }\n },\n dispatchWorkgroups(x, y, z) {\n rawPass.dispatchWorkgroups(x, y, z);\n },\n dispatchWorkgroupsIndirect(indirectBuffer, indirectOffset) {\n const rawBuffer =\n BUFFER_RAW_MAP.get(indirectBuffer) ?? (indirectBuffer as unknown as GPUBuffer);\n rawPass.dispatchWorkgroupsIndirect(rawBuffer, indirectOffset);\n },\n end() {\n rawPass.end();\n },\n };\n return pass;\n },\n copyBufferToBuffer(\n source: Buffer,\n arg2: number | Buffer,\n arg3?: Buffer | number | undefined,\n arg4?: number | undefined,\n arg5?: number | undefined,\n ): void {\n const state = ENCODER_STATE.get(enc);\n throwIfFinished(state);\n // M5 / w35: the forgeax Buffer is a wrapper (not the raw GPUBuffer);\n // resolve through BUFFER_RAW_MAP before delegating.\n const rawSource = BUFFER_RAW_MAP.get(source) ?? (source as unknown as GPUBuffer);\n // Two overloads (research F-1):\n // (a) (src, dst, size?) - 3-arg shorthand\n // (b) (src, srcOffset, dst, dstOffset, size) - 5-arg full form\n if (typeof arg2 === 'number') {\n // 5-arg form\n const dst = arg3 as Buffer;\n const rawDst = BUFFER_RAW_MAP.get(dst) ?? (dst as unknown as GPUBuffer);\n rawEncoder.copyBufferToBuffer(rawSource, arg2, rawDst, arg4 ?? 0, arg5 ?? 0);\n } else {\n // 3-arg shorthand\n const dst = arg2 as Buffer;\n const rawDst = BUFFER_RAW_MAP.get(dst) ?? (dst as unknown as GPUBuffer);\n rawEncoder.copyBufferToBuffer(rawSource, rawDst, arg3 as number | undefined);\n }\n },\n copyBufferToTexture(\n source: GPUTexelCopyBufferInfo,\n destination: GPUTexelCopyTextureInfo,\n copySize: GPUExtent3DStrict,\n ): void {\n const state = ENCODER_STATE.get(enc);\n throwIfFinished(state);\n const rawSrc = {\n ...source,\n buffer:\n BUFFER_RAW_MAP.get(source.buffer as unknown as Buffer) ??\n (source.buffer as unknown as GPUBuffer),\n };\n rawEncoder.copyBufferToTexture(rawSrc, destination, copySize);\n },\n copyTextureToBuffer(\n source: GPUTexelCopyTextureInfo,\n destination: GPUTexelCopyBufferInfo,\n copySize: GPUExtent3DStrict,\n ): void {\n const state = ENCODER_STATE.get(enc);\n throwIfFinished(state);\n const rawDst = {\n ...destination,\n buffer:\n BUFFER_RAW_MAP.get(destination.buffer as unknown as Buffer) ??\n (destination.buffer as unknown as GPUBuffer),\n };\n rawEncoder.copyTextureToBuffer(source, rawDst, copySize);\n },\n copyTextureToTexture(\n source: GPUTexelCopyTextureInfo,\n destination: GPUTexelCopyTextureInfo,\n copySize: GPUExtent3DStrict,\n ): void {\n const state = ENCODER_STATE.get(enc);\n throwIfFinished(state);\n rawEncoder.copyTextureToTexture(source, destination, copySize);\n },\n clearBuffer(buffer: Buffer, offset?: number | undefined, size?: number | undefined): void {\n const state = ENCODER_STATE.get(enc);\n throwIfFinished(state);\n // M5 / w35: resolve forgeax Buffer wrapper to raw GPUBuffer.\n const rawBuf = BUFFER_RAW_MAP.get(buffer) ?? (buffer as unknown as GPUBuffer);\n rawEncoder.clearBuffer(rawBuf, offset, size);\n },\n resolveQuerySet(\n querySet: QuerySet,\n firstQuery: number,\n queryCount: number,\n destination: Buffer,\n destinationOffset: number,\n ): Result<void, RhiError> {\n const state = ENCODER_STATE.get(enc);\n if (state?.finished) {\n return commandEncoderFinished();\n }\n // Step 6 (research §2.3): destinationOffset is a multiple of 256.\n // K-2: alignment violation maps to webgpu-runtime-error.\n if (destinationOffset % QUERY_RESOLVE_ALIGNMENT !== 0) {\n return err(\n new RhiErrorClass({\n code: 'webgpu-runtime-error',\n expected: 'destinationOffset % 256 == 0 (spec normative)',\n hint: `got destinationOffset=${destinationOffset}; align to a multiple of 256 bytes (kQueryResolveAlignment)`,\n }),\n );\n }\n // Step 3 (research §2.3): destination.usage contains QUERY_RESOLVE.\n const dstMeta = BUFFER_META_MAP.get(destination);\n if (dstMeta !== undefined && (dstMeta.usage & BUFFER_USAGE_QUERY_RESOLVE) === 0) {\n return err(\n new RhiErrorClass({\n code: 'webgpu-runtime-error',\n expected: 'destination.usage must contain QUERY_RESOLVE',\n hint: `got destination.usage=0x${dstMeta.usage.toString(16)}; create the buffer with GPUBufferUsage.QUERY_RESOLVE (0x200)`,\n }),\n );\n }\n // Steps 4 + 5 (research §2.3): firstQuery + queryCount <= querySet.count\n // (which subsumes firstQuery < count as a derived constraint).\n const rawQs = QUERY_SET_RAW_MAP.get(querySet);\n const qsCount =\n rawQs !== undefined && typeof rawQs.count === 'number'\n ? rawQs.count\n : Number.MAX_SAFE_INTEGER;\n if (firstQuery < 0 || firstQuery + queryCount > qsCount) {\n return err(\n new RhiErrorClass({\n code: 'webgpu-runtime-error',\n expected: 'firstQuery + queryCount <= querySet.count',\n hint: `got firstQuery=${firstQuery}, queryCount=${queryCount}; querySet.count=${qsCount}`,\n }),\n );\n }\n // Step 7 (research §2.3): destinationOffset + 8 * queryCount <= dst.size.\n if (dstMeta !== undefined) {\n const requiredBytes = destinationOffset + 8 * queryCount;\n if (requiredBytes > dstMeta.size) {\n return err(\n new RhiErrorClass({\n code: 'webgpu-runtime-error',\n expected: 'destinationOffset + 8 * queryCount <= destination.size',\n hint: `got destinationOffset=${destinationOffset}, queryCount=${queryCount} (8 * queryCount = ${8 * queryCount}); destination.size=${dstMeta.size}`,\n }),\n );\n }\n }\n const rawQsHandle = QUERY_SET_RAW_MAP.get(querySet) ?? (querySet as unknown as GPUQuerySet);\n const rawDstHandle = BUFFER_RAW_MAP.get(destination) ?? (destination as unknown as GPUBuffer);\n return resolveTimestampQueries({\n rawEncoder,\n rawQuerySet: rawQsHandle,\n firstQuery,\n queryCount,\n rawDestination: rawDstHandle,\n destinationOffset,\n });\n },\n pushDebugGroup(groupLabel: string): void {\n rawEncoder.pushDebugGroup(groupLabel);\n },\n popDebugGroup(): void {\n rawEncoder.popDebugGroup();\n },\n insertDebugMarker(markerLabel: string): void {\n rawEncoder.insertDebugMarker(markerLabel);\n },\n writeTimestamp(querySet: QuerySet, queryIndex: number): void {\n // M5 / K-3 (research §2.4): timestamp-query feature gate. spec\n // writeTimestamp returns void; the forgeax form keeps the void shape\n // and fans out 'feature-not-enabled' through the engine onError\n // channel rather than wrapping in Result. When the capability is true,\n // a missing or throwing raw write is a structured runtime failure so a\n // Render capture cannot publish a fabricated interval.\n const state = ENCODER_STATE.get(enc);\n throwIfFinished(state);\n if (caps.timestampQuery !== true) {\n fireFeatureNotEnabled(\n 'timestamp-query',\n 'check device.caps.timestampQuery before calling writeTimestamp',\n );\n return;\n }\n const rawQs = QUERY_SET_RAW_MAP.get(querySet) ?? (querySet as unknown as GPUQuerySet);\n writeTimestamp({ rawEncoder, rawQuerySet: rawQs, queryIndex });\n },\n finish(): Result<CommandBuffer, RhiError> {\n const state = ENCODER_STATE.get(enc);\n if (state === undefined) {\n // Should not happen in practice; treat as a finished encoder.\n return commandEncoderFinished();\n }\n if (state.finished) {\n return commandEncoderFinished();\n }\n if (state.activePass !== null) {\n const passState = PASS_STATE.get(state.activePass);\n if (passState !== undefined && !passState.ended) {\n return renderPassNotEnded();\n }\n }\n const rawCommandBuffer = rawEncoder.finish();\n state.finished = true;\n const cb = rawCommandBuffer as unknown as CommandBuffer;\n COMMAND_BUFFER_RAW_MAP.set(cb, rawCommandBuffer);\n return ok(cb);\n },\n };\n ENCODER_STATE.set(enc, { raw: rawEncoder, finished: false, activePass: null });\n return enc;\n}\n\n// ============================================================================\n// M5 / w35 - Buffer wrapper (mapAsync / getMappedRange / unmap / mapState).\n// ============================================================================\n//\n// research §4.1 mapState 3-state enum + §4.2 mapAsync 8-validation +\n// §4.4 unmap detach. K-1 decision: mode is the raw GPUMapMode bitmask.\n// K-2 decision: alignment / mode-usage / detach faults all ride\n// 'webgpu-runtime-error' with structured .expected / .hint per F-3\n// ai-user-review carry-over.\n\n/** Spec normative GPUMapMode bits (research §4.2 step 7). */\nconst MAP_MODE_READ = 0x1;\nconst MAP_MODE_WRITE = 0x2;\n/** GPUBufferUsage MAP_READ / MAP_WRITE bits (research §4.2 step 9 / F-8 row 3). */\nconst BUFFER_USAGE_MAP_READ = 0x0001;\nconst BUFFER_USAGE_MAP_WRITE = 0x0002;\n\nfunction rangeError(args: { expected: string; hint: string }): Result<never, RhiError> {\n return err(\n new RhiErrorClass({\n code: 'webgpu-runtime-error',\n expected: args.expected,\n hint: args.hint,\n }),\n );\n}\n\n/**\n * Build a forgeax Buffer wrapper around a raw GPUBuffer (w35).\n *\n * The wrapper exposes the brand-only Buffer interface plus the M5 mapping\n * surface (mapAsync / getMappedRange / unmap + mapState getter).\n *\n * Validation policy (K-2 + research §4.2 + F-8 three rows):\n * - mapAsync rejects on 8 spec validation steps + F-8 row 1/3 with\n * 'webgpu-runtime-error' before delegating to raw mapAsync. The raw\n * mapAsync may still reject (driver-level validation); the shim wraps\n * such rejections via 'webgpu-runtime-error' carrying the underlying\n * message in .hint.\n * - getMappedRange rejects with 'webgpu-runtime-error' when mapState !==\n * 'mapped' (F-8 row 2 detach guard) before delegating.\n * - unmap is silent (spec normative; research §4.4) and resets the\n * internal mapState slot to 'unmapped'.\n *\n * The wrapper carries an internal mapState slot so the shim can detect F-8\n * row 1 / row 2 fast-path; the slot is initialized to 'mapped' when the\n * descriptor sets `mappedAtCreation:true` (research §4.3) and otherwise\n * starts at 'unmapped'.\n */\nfunction makeBufferWrapper(raw: GPUBuffer, size: number, usage: GPUBufferUsageFlags): Buffer {\n // Track mapState locally so the shim does not need to query raw.mapState\n // (the spec exposes it but for symmetry with the F-8 guard semantics we\n // mirror the slot in the wrapper).\n const initialState =\n typeof (raw as { mapState?: string }).mapState === 'string'\n ? (raw as { mapState: 'unmapped' | 'pending' | 'mapped' }).mapState\n : 'unmapped';\n let mapState: 'unmapped' | 'pending' | 'mapped' = initialState;\n const wrapper = {\n get mapState(): 'unmapped' | 'pending' | 'mapped' {\n // Prefer the raw slot if available so destroyed-buffer transitions\n // surface to AI users; fall back to the local slot for mocks that do\n // not expose mapState (mock buffers keep a logical mapState only).\n const rs = (raw as { mapState?: 'unmapped' | 'pending' | 'mapped' }).mapState;\n if (typeof rs === 'string') {\n mapState = rs;\n return rs;\n }\n return mapState;\n },\n async mapAsync(\n mode: GPUMapModeFlags,\n offset?: number | undefined,\n sizeArg?: number | undefined,\n ): Promise<Result<MappedBuffer, RhiError>> {\n // F-8 row 1: mapState must be 'unmapped' (research §4.2 step 1).\n const cur = wrapper.mapState;\n if (cur !== 'unmapped') {\n return rangeError({\n expected: 'buffer.mapState === \"unmapped\" before mapAsync',\n hint: `got mapState=${cur}; call buffer.unmap() before mapAsync, or wait for the previous mapAsync to settle`,\n });\n }\n const off = offset ?? 0;\n const rangeSize = sizeArg === undefined ? Math.max(0, size - off) : sizeArg;\n // step 4: offset % 8 == 0\n if (off % 8 !== 0) {\n return rangeError({\n expected: 'mapAsync offset % 8 == 0 (spec normative)',\n hint: `got offset=${off}; align offset to 8 bytes`,\n });\n }\n // step 5: rangeSize % 4 == 0\n if (rangeSize % 4 !== 0) {\n return rangeError({\n expected: 'mapAsync rangeSize % 4 == 0 (spec normative)',\n hint: `got rangeSize=${rangeSize}; align rangeSize to 4 bytes`,\n });\n }\n // step 6: offset + rangeSize <= size\n if (off + rangeSize > size) {\n return rangeError({\n expected: 'mapAsync offset + rangeSize <= buffer.size',\n hint: `got offset=${off}, rangeSize=${rangeSize}; buffer.size=${size}`,\n });\n }\n // step 7: mode contains only allowed bits\n const allowed = MAP_MODE_READ | MAP_MODE_WRITE;\n if ((mode & ~allowed) !== 0) {\n return rangeError({\n expected: 'mapAsync mode contains only READ or WRITE bits',\n hint: `got mode=0x${mode.toString(16)}; pass GPUMapMode.READ (0x1) or GPUMapMode.WRITE (0x2)`,\n });\n }\n // step 8: mode is exactly READ or WRITE (not both)\n if (mode !== MAP_MODE_READ && mode !== MAP_MODE_WRITE) {\n return rangeError({\n expected: 'mapAsync mode is exactly one of READ | WRITE (not both)',\n hint: `got mode=0x${mode.toString(16)}; pass GPUMapMode.READ (0x1) or GPUMapMode.WRITE (0x2), not the OR-combined mask`,\n });\n }\n // step 9: mode-usage cross-check (F-8 row 3)\n if ((mode & MAP_MODE_READ) !== 0 && (usage & BUFFER_USAGE_MAP_READ) === 0) {\n return rangeError({\n expected: 'mapAsync mode READ requires buffer.usage to contain MAP_READ',\n hint: `got mode=READ, buffer.usage=0x${usage.toString(16)}; create buffer with GPUBufferUsage.MAP_READ`,\n });\n }\n if ((mode & MAP_MODE_WRITE) !== 0 && (usage & BUFFER_USAGE_MAP_WRITE) === 0) {\n return rangeError({\n expected: 'mapAsync mode WRITE requires buffer.usage to contain MAP_WRITE',\n hint: `got mode=WRITE, buffer.usage=0x${usage.toString(16)}; create buffer with GPUBufferUsage.MAP_WRITE`,\n });\n }\n // Delegate to raw GPUBuffer; raw rejection wraps as webgpu-runtime-error.\n mapState = 'pending';\n try {\n if (typeof raw.mapAsync === 'function') {\n if (sizeArg === undefined && offset === undefined) {\n await raw.mapAsync(mode);\n } else if (sizeArg === undefined) {\n await raw.mapAsync(mode, off);\n } else {\n await raw.mapAsync(mode, off, sizeArg);\n }\n }\n mapState = 'mapped';\n // D-P2 #6: the structural wrapper carries both Buffer + MappedBuffer\n // members; on the success path we surface the same JS object typed as\n // the branded MappedBuffer (charter proposition 5: brand is structural,\n // no runtime cost).\n return ok(wrapper as unknown as MappedBuffer);\n } catch (e) {\n mapState = 'unmapped';\n const message = e instanceof Error ? e.message : String(e);\n return rangeError({\n expected: 'underlying GPUBuffer.mapAsync to succeed',\n hint: `mapAsync raised: ${message}`,\n });\n }\n },\n getMappedRange(\n offset?: number | undefined,\n sizeArg?: number | undefined,\n ): Result<ArrayBuffer, RhiError> {\n // F-8 row 2 detach guard: mapState must be 'mapped'.\n const cur = wrapper.mapState;\n if (cur !== 'mapped') {\n return rangeError({\n expected: 'buffer.mapState === \"mapped\" before getMappedRange',\n hint: 'call buffer.mapAsync(MODE) and await it before getMappedRange',\n });\n }\n try {\n if (typeof raw.getMappedRange !== 'function') {\n return rangeError({\n expected: 'underlying GPUBuffer.getMappedRange to be available',\n hint: 'mock or driver does not expose getMappedRange; use a real GPUBuffer',\n });\n }\n const view =\n sizeArg === undefined\n ? offset === undefined\n ? raw.getMappedRange()\n : raw.getMappedRange(offset)\n : raw.getMappedRange(offset ?? 0, sizeArg);\n return ok(view);\n } catch (e) {\n const message = e instanceof Error ? e.message : String(e);\n return rangeError({\n expected: 'underlying GPUBuffer.getMappedRange to succeed',\n hint: `getMappedRange raised: ${message}`,\n });\n }\n },\n unmap(): void {\n // Spec normative silent no-op (research §4.4): unmap on a destroyed or\n // already-unmapped buffer must NOT throw / return an error.\n try {\n if (typeof raw.unmap === 'function') {\n raw.unmap();\n }\n } catch {\n // swallow per spec; the forgeax form does not surface unmap failures.\n }\n mapState = 'unmapped';\n },\n } as unknown as Buffer;\n return wrapper;\n}\n\n/**\n * Build a RhiQueue around a raw GPUQueue (w6).\n *\n * Real-path implementation:\n * - submit forwards to rawQueue.submit; failures (validation / destroyed\n * resource references) wrap to 'queue-submit-failed' (D-S3 #3).\n * - writeBuffer validates offset alignment + bounds before forwarding;\n * out-of-bounds writes return 'queue-write-buffer-out-of-bounds' (D-S3 #4).\n */\nfunction makeQueue(rawQueue: GPUQueue): RhiQueue {\n return {\n writeBuffer(\n buffer: Buffer,\n bufferOffset: number,\n data: ArrayBufferView | ArrayBuffer,\n dataOffset?: number | undefined,\n size?: number | undefined,\n ): Result<void, RhiError> {\n const rawBuffer = BUFFER_RAW_MAP.get(buffer) ?? (buffer as unknown as GPUBuffer);\n const bufferSize =\n typeof (rawBuffer as { size?: number }).size === 'number'\n ? (rawBuffer as { size: number }).size\n : Number.MAX_SAFE_INTEGER;\n // 4-byte alignment validation (W3C WebGPU 23.2 writeBuffer).\n if (bufferOffset % 4 !== 0) {\n return queueWriteBufferOutOfBounds({\n offset: bufferOffset,\n byteLength:\n data instanceof ArrayBuffer ? data.byteLength : (data as ArrayBufferView).byteLength,\n bufferSize,\n });\n }\n const dataByteLength =\n data instanceof ArrayBuffer ? data.byteLength : (data as ArrayBufferView).byteLength;\n const writeStart = dataOffset ?? 0;\n const writeSize = size ?? dataByteLength - writeStart;\n // Bounds validation: bufferOffset + writeSize <= bufferSize.\n if (bufferOffset + writeSize > bufferSize) {\n return queueWriteBufferOutOfBounds({\n offset: bufferOffset,\n byteLength: writeSize,\n bufferSize,\n });\n }\n try {\n if (size !== undefined) {\n rawQueue.writeBuffer(\n rawBuffer,\n bufferOffset,\n data as GPUAllowSharedBufferSource,\n writeStart,\n size,\n );\n } else if (dataOffset !== undefined) {\n rawQueue.writeBuffer(\n rawBuffer,\n bufferOffset,\n data as GPUAllowSharedBufferSource,\n writeStart,\n );\n } else {\n rawQueue.writeBuffer(rawBuffer, bufferOffset, data as GPUAllowSharedBufferSource);\n }\n return ok(undefined);\n } catch (e) {\n const message = e instanceof Error ? e.message : String(e);\n // GPU validation may surface bounds errors; wrap as out-of-bounds for\n // AI-user routing parity (charter proposition 4 explicit failure).\n if (/out of (bounds|range)|exceed/i.test(message)) {\n return queueWriteBufferOutOfBounds({\n offset: bufferOffset,\n byteLength: writeSize,\n bufferSize,\n });\n }\n return queueSubmitFailed(message);\n }\n },\n submit(commandBuffers: readonly CommandBuffer[]): Result<void, RhiError> {\n const rawList: GPUCommandBuffer[] = [];\n for (const cb of commandBuffers) {\n const raw = COMMAND_BUFFER_RAW_MAP.get(cb);\n if (raw !== undefined) {\n rawList.push(raw);\n } else {\n rawList.push(cb as unknown as GPUCommandBuffer);\n }\n }\n try {\n rawQueue.submit(rawList);\n return ok(undefined);\n } catch (e) {\n const message = e instanceof Error ? e.message : String(e);\n return queueSubmitFailed(message);\n }\n },\n writeTexture(\n destination: TextureWriteDestination,\n data: ArrayBufferView | ArrayBuffer,\n dataLayout: GPUTexelCopyBufferLayout,\n size: GPUExtent3DStrict,\n ): Result<void, RhiError> {\n // writeTexture calls validating texture buffer copy(..., aligned=false)\n // per WebGPU spec §19.2 GPUQueue.writeTexture, which explicitly notes\n // \"unlike copyBufferToTexture, there is no alignment requirement on\n // either dataLayout.bytesPerRow or dataLayout.offset.\"\n // The 256-byte alignment lives in §11.2.2 validating GPUTexelCopyBufferInfo,\n // called only by copyBufferToTexture / copyTextureToBuffer where the source\n // is a GPUBuffer. The lower bound bytesPerRow >= widthInBlocks * blockSize\n // is enforced by dawn / WebGPU via §11.2.6 validating linear texture data\n // and surfaces as webgpu-runtime-error through the try/catch below.\n try {\n // The destination.texture is a forgeax Texture brand; the shim stored\n // the raw GPUTexture as the brand carrier in createTexture. Spec\n // structural compatibility lets us forward verbatim with a cast.\n // The data + size casts cover @webgpu/types polymorphism that the\n // forgeax form normalises to the strict spec subset.\n const rawDestination: GPUTexelCopyTextureInfo = {\n texture: destination.texture as unknown as GPUTexture,\n };\n if (destination.mipLevel !== undefined) rawDestination.mipLevel = destination.mipLevel;\n if (destination.origin !== undefined) rawDestination.origin = destination.origin;\n if (destination.aspect !== undefined) rawDestination.aspect = destination.aspect;\n rawQueue.writeTexture(\n rawDestination,\n data as unknown as GPUAllowSharedBufferSource,\n dataLayout,\n size as unknown as GPUExtent3D,\n );\n return ok(undefined);\n } catch (e) {\n const message = e instanceof Error ? e.message : String(e);\n return err(\n new RhiErrorClass({\n code: 'webgpu-runtime-error',\n expected: 'underlying GPUQueue.writeTexture to succeed',\n hint: `writeTexture raised: ${message}`,\n }),\n );\n }\n },\n copyExternalImageToTexture(\n source: GPUCopyExternalImageSourceInfo,\n destination: ExternalImageTextureDestination,\n copySize: GPUExtent3DStrict,\n ): Result<void, RhiError> {\n try {\n rawQueue.copyExternalImageToTexture(\n source,\n {\n texture: destination.texture as unknown as GPUTexture,\n ...(destination.mipLevel === undefined ? {} : { mipLevel: destination.mipLevel }),\n ...(destination.origin === undefined ? {} : { origin: destination.origin }),\n ...(destination.aspect === undefined ? {} : { aspect: destination.aspect }),\n ...(destination.colorSpace === undefined ? {} : { colorSpace: destination.colorSpace }),\n ...(destination.premultipliedAlpha === undefined\n ? {}\n : { premultipliedAlpha: destination.premultipliedAlpha }),\n },\n copySize,\n );\n return ok(undefined);\n } catch (e) {\n const message = e instanceof Error ? e.message : String(e);\n return err(\n new RhiErrorClass({\n code: 'webgpu-runtime-error',\n expected: 'underlying GPUQueue.copyExternalImageToTexture to succeed',\n hint: `copyExternalImageToTexture raised: ${message}`,\n }),\n );\n }\n },\n // forgeax-async-whitelist: dom-native — spec `GPUQueue.onSubmittedWorkDone()` Promise passthrough\n onSubmittedWorkDone(): Promise<undefined> {\n // research §5.1 spec normative: no reject path. Forward the raw\n // Promise verbatim; the forgeax Promise<undefined> matches the spec\n // shape (no Result wrapping; device-lost flows through RhiDevice.lost).\n return rawQueue.onSubmittedWorkDone();\n },\n };\n}\n\n/**\n * Construct a RhiDevice shim wrapping GPUDevice.\n *\n * Does not cache or reclassify device.lost (single-source subscription +\n * dual-form fan-out is the engine layer's job; this package only exposes the\n * spec Promise). See plan-strategy 3 R2 mitigation.\n */\nexport function makeRhiDevice(rawDevice: GPUDevice): {\n device: RhiDevice;\n /** Exposed for createShaderModule and other shim entry points that need to\n * bypass the createX Result wrapper. */\n raw: GPUDevice;\n} {\n const caps = deriveCaps(rawDevice, rawDevice.features, rawDevice.limits);\n const features = rawDevice.features as unknown as RhiFeatures;\n const limits = rawDevice.limits as RhiLimits;\n\n const queue: RhiQueue = makeQueue(rawDevice.queue);\n\n const device: RhiDevice = {\n caps,\n features,\n limits,\n queue,\n lost: rawDevice.lost as unknown as Promise<{\n readonly reason: 'destroyed' | 'unknown';\n readonly message: string;\n }>,\n createBuffer(desc: BufferDescriptor): Result<Buffer, RhiError> {\n // M5 / K-7 / OQ-7 / D-R3: mappedAtCreation passthrough is delivered by\n // BUFFER_KEYS containing 'mappedAtCreation'; mirror() ships the field to\n // the raw GPUBufferDescriptor when present (`'mappedAtCreation' in desc`\n // semantics), so createBuffer({mappedAtCreation:true}) yields a buffer\n // in `'mapped'` state per spec §buffer-creation step 6 (research §4.3).\n // w31 (M5) dawn-real-gpu Pattern B is the regression guard - it asserts\n // mapState === 'mapped' + getMappedRange().byteLength === 16 + the init\n // data round-trips through copyBufferToBuffer + mapAsync(READ).\n const out = rawDevice.createBuffer(\n mirror(desc, BUFFER_KEYS) as unknown as GPUBufferDescriptor,\n );\n // Record metadata for downstream shim validation (resolveQuerySet\n // destination.usage / destinationOffset bounds, research §2.3 +\n // M5 mapAsync mode-usage cross-check, research §4.2 step 9 / F-8 row 3).\n const sizeField = typeof desc.size === 'number' ? desc.size : 0;\n const usageField = (desc.usage as GPUBufferUsageFlags | undefined) ?? 0;\n // M5 / w35: wrap the raw GPUBuffer in a forgeax Buffer wrapper that\n // exposes the mapping surface (mapAsync / getMappedRange / unmap /\n // mapState getter). The wrapper validates BEFORE delegating to the raw\n // GPUBuffer; failures ride 'webgpu-runtime-error' with structured\n // .expected / .hint (K-2 + research §4.2 / F-8 three rows).\n const handle = makeBufferWrapper(out, sizeField, usageField);\n BUFFER_RAW_MAP.set(handle, out);\n BUFFER_META_MAP.set(handle, {\n size: sizeField,\n usage: usageField,\n destroyed: false,\n });\n return ok(handle);\n },\n createTexture(desc: TextureDescriptor): Result<Texture, RhiError> {\n const out = rawDevice.createTexture(\n mirror(desc, TEXTURE_KEYS) as unknown as GPUTextureDescriptor,\n );\n const handle = out as unknown as Texture;\n // Record metadata for createTextureView cross-resource validation.\n const viewFormats =\n desc.viewFormats === undefined\n ? []\n : Array.from(desc.viewFormats as Iterable<GPUTextureFormat>);\n TEXTURE_META_MAP.set(handle, {\n format: desc.format as GPUTextureFormat,\n usage: desc.usage as GPUTextureUsageFlags,\n viewFormats,\n destroyed: false,\n });\n return ok(handle);\n },\n destroyBuffer(buf: Buffer): Result<void, RhiError> {\n // feat-20260612 M1 / w4 — fail-fast over the spec idempotent-void\n // contract (plan-strategy D-7). The shim layer tracks\n // `destroyed: boolean` on per-handle BufferMeta and routes the second\n // destroy to 'destroy-after-destroy' rather than forwarding to the\n // underlying GPUBuffer.destroy(). Charter proposition 4 explicit\n // failure + architecture-principles §5 Fail Fast.\n const meta = BUFFER_META_MAP.get(buf);\n if (meta?.destroyed) {\n return err(\n new RhiErrorClass({\n code: 'destroy-after-destroy',\n expected: 'GPU buffer handle has not been destroyed yet',\n hint: 'object already destroyed; track lifecycle in caller or check isDestroyed before re-destroy',\n }),\n );\n }\n const rawBuf = BUFFER_RAW_MAP.get(buf);\n try {\n if (rawBuf !== undefined && typeof rawBuf.destroy === 'function') {\n rawBuf.destroy();\n }\n } catch (e) {\n const message = e instanceof Error ? e.message : String(e);\n return err(\n new RhiErrorClass({\n code: 'webgpu-runtime-error',\n expected: 'underlying GPUBuffer.destroy() to succeed',\n hint: `destroy raised: ${message}`,\n }),\n );\n }\n if (meta !== undefined) meta.destroyed = true;\n return ok(undefined);\n },\n destroyTexture(tex: Texture): Result<void, RhiError> {\n // feat-20260612 M1 / w4 — fail-fast on second destroy (D-7); shape\n // mirrors destroyBuffer above. The shim tracks `destroyed: boolean`\n // on per-handle TextureMeta; the underlying GPUTexture.destroy()\n // is invoked exactly once per handle.\n const meta = TEXTURE_META_MAP.get(tex);\n if (meta?.destroyed) {\n return err(\n new RhiErrorClass({\n code: 'destroy-after-destroy',\n expected: 'GPU texture handle has not been destroyed yet',\n hint: 'object already destroyed; track lifecycle in caller or check isDestroyed before re-destroy',\n }),\n );\n }\n const rawTex = tex as unknown as { destroy?: () => void };\n try {\n if (typeof rawTex.destroy === 'function') {\n rawTex.destroy();\n }\n } catch (e) {\n const message = e instanceof Error ? e.message : String(e);\n return err(\n new RhiErrorClass({\n code: 'webgpu-runtime-error',\n expected: 'underlying GPUTexture.destroy() to succeed',\n hint: `destroy raised: ${message}`,\n }),\n );\n }\n if (meta !== undefined) meta.destroyed = true;\n return ok(undefined);\n },\n createTextureView(\n texture: Texture,\n desc: TextureViewDescriptor,\n ): Result<TextureView, RhiError> {\n // Cross-resource validation fast-path (research §1.1). When metadata is\n // available, validate format ∈ source.format ∪ source.viewFormats and\n // usage ⊆ source.usage; both violations map to 'webgpu-runtime-error'\n // (charter proposition 4 explicit failure).\n const meta = TEXTURE_META_MAP.get(texture);\n if (meta !== undefined) {\n const fmt = desc.format as GPUTextureFormat | undefined;\n if (fmt !== undefined && fmt !== meta.format && !meta.viewFormats.includes(fmt)) {\n return err(\n new RhiErrorClass({\n code: 'webgpu-runtime-error',\n expected:\n 'createTextureView format must be the source texture format or one of source.viewFormats',\n hint: `got format='${fmt}'; source.format='${meta.format}'; source.viewFormats=[${meta.viewFormats.join(', ')}]`,\n }),\n );\n }\n const reqUsage = desc.usage as GPUTextureUsageFlags | undefined;\n if (reqUsage !== undefined && reqUsage !== 0 && (reqUsage & ~meta.usage) !== 0) {\n return err(\n new RhiErrorClass({\n code: 'webgpu-runtime-error',\n expected: 'createTextureView usage must be a subset of source.usage',\n hint: `got usage=0x${reqUsage.toString(16)}; source.usage=0x${meta.usage.toString(16)}`,\n }),\n );\n }\n }\n const rawTexture = texture as unknown as GPUTexture;\n try {\n const rawView = rawTexture.createView(\n mirror(desc, TEXTURE_VIEW_KEYS) as unknown as GPUTextureViewDescriptor,\n );\n const handle = rawView as unknown as TextureView;\n TEXTURE_VIEW_RAW_MAP.set(handle, rawView);\n return ok(handle);\n } catch (e) {\n const message = e instanceof Error ? e.message : String(e);\n return err(\n new RhiErrorClass({\n code: 'webgpu-runtime-error',\n expected: 'underlying GPUTexture.createView to succeed',\n hint: `createView raised: ${message}`,\n }),\n );\n }\n },\n createSampler(desc?: SamplerDescriptor | undefined): Result<Sampler, RhiError> {\n // Sampler descriptor is fully optional; if undefined call createSampler() with no arg.\n if (desc === undefined) {\n const out = rawDevice.createSampler();\n return ok(out as unknown as Sampler);\n }\n const out = rawDevice.createSampler(\n mirror(desc, SAMPLER_KEYS) as unknown as GPUSamplerDescriptor,\n );\n return ok(out as unknown as Sampler);\n },\n createBindGroupLayout(desc: BindGroupLayoutDescriptor): Result<BindGroupLayout, RhiError> {\n const out = rawDevice.createBindGroupLayout(\n mirror(desc, BGL_KEYS) as unknown as GPUBindGroupLayoutDescriptor,\n );\n return ok(out as unknown as BindGroupLayout);\n },\n createBindGroup(desc: BindGroupDescriptor): Result<BindGroup, RhiError> {\n // w20 — tagged-union RhiBindingResource 4-kind adapter. Each forgeax\n // entry carries `{ binding, resource: { kind, value } }` (the 4\n // discriminator values are 'sampler' / 'buffer' / 'textureView' /\n // 'externalTexture' per @forgeax/engine-rhi RhiBindingResource). The shim\n // dispatches on `resource.kind` and emits the spec-verbatim\n // GPUBindGroupEntry shape per kind. The default branch trips\n // `assertNever` so a future RhiBindingResource extension forces a\n // TS2367 here at compile time (charter proposition 4 explicit failure\n // + proposition 5 consistent abstraction over duck-typing).\n const mirrored: {\n label?: string | undefined;\n layout: GPUBindGroupLayout;\n entries: GPUBindGroupEntry[];\n } = {\n layout: desc.layout as unknown as GPUBindGroupLayout,\n entries: [],\n };\n if ('label' in desc && desc.label !== undefined) mirrored.label = desc.label;\n for (const entry of desc.entries) {\n const resource = entry.resource;\n switch (resource.kind) {\n case 'sampler': {\n mirrored.entries.push({\n binding: entry.binding,\n resource: resource.value as unknown as GPUSampler,\n });\n break;\n }\n case 'buffer': {\n const { buffer, offset, size } = resource.value;\n const rawBuf = BUFFER_RAW_MAP.get(buffer) ?? (buffer as unknown as GPUBuffer);\n const bufferBinding: GPUBufferBinding = { buffer: rawBuf };\n if (offset !== undefined) bufferBinding.offset = offset;\n if (size !== undefined) bufferBinding.size = size;\n mirrored.entries.push({ binding: entry.binding, resource: bufferBinding });\n break;\n }\n case 'textureView': {\n mirrored.entries.push({\n binding: entry.binding,\n resource: resource.value as unknown as GPUTextureView,\n });\n break;\n }\n case 'externalTexture': {\n mirrored.entries.push({\n binding: entry.binding,\n resource: resource.value as unknown as GPUExternalTexture,\n });\n break;\n }\n default: {\n // assertNever — adding a fifth kind would trip TS2367 here.\n const _exhaustive: never = resource;\n void _exhaustive;\n throw new Error(`rhi-webgpu: unreachable RhiBindingResource kind in createBindGroup`);\n }\n }\n }\n const out = rawDevice.createBindGroup(mirrored as unknown as GPUBindGroupDescriptor);\n return ok(out as unknown as BindGroup);\n },\n createPipelineLayout(desc: PipelineLayoutDescriptor): Result<PipelineLayout, RhiError> {\n const out = rawDevice.createPipelineLayout(\n mirror(desc, PL_KEYS) as unknown as GPUPipelineLayoutDescriptor,\n );\n return ok(out as unknown as PipelineLayout);\n },\n createRenderPipeline(desc: RenderPipelineDescriptor): Result<RenderPipeline, RhiError> {\n try {\n const out = rawDevice.createRenderPipeline(mirrorRenderPipelineDescriptor(desc));\n return ok(out as unknown as RenderPipeline);\n } catch (e) {\n const message = e instanceof Error ? e.message : String(e);\n // Keep synchronous render-pipeline creation on the same structured\n // Result boundary as compute-pipeline creation. A failed PSO must not\n // escape as an exception and abort the caller's whole frame.\n if (/compile|shader|wgsl/i.test(message)) {\n return err(\n new RhiErrorClass({\n code: 'shader-compile-failed',\n expected: 'render shader modules + entry points to be valid',\n hint: `compile error: ${message}`,\n }),\n );\n }\n return err(\n new RhiErrorClass({\n code: 'webgpu-runtime-error',\n expected: 'underlying GPUDevice.createRenderPipeline to succeed',\n hint: `createRenderPipeline raised: ${message}`,\n }),\n );\n }\n },\n createComputePipeline(desc: ComputePipelineDescriptor): Result<ComputePipeline, RhiError> {\n // Capability gate (research §1.2 NOTE; plan-strategy §4.3 boundary\n // case row 1). MVP WebGPU path always has caps.compute=true; the gate\n // exists for potential future backends that lack compute.\n if (caps.compute === false) {\n return err(\n new RhiErrorClass({\n code: 'feature-not-enabled',\n expected: 'caps.compute === true',\n hint: 'check device.caps.compute before calling createComputePipeline',\n }),\n );\n }\n try {\n const out = rawDevice.createComputePipeline(\n mirror(desc, CP_KEYS) as unknown as GPUComputePipelineDescriptor,\n );\n return ok(out as unknown as ComputePipeline);\n } catch (e) {\n const message = e instanceof Error ? e.message : String(e);\n // Shader / module compilation issues surface as 'shader-compile-failed'\n // with the underlying message; everything else maps to a generic\n // webgpu runtime error (charter proposition 4 explicit failure).\n if (/compile|shader|wgsl/i.test(message)) {\n return err(\n new RhiErrorClass({\n code: 'shader-compile-failed',\n expected: 'compute shader module + entry point to be valid',\n hint: `compile error: ${message}`,\n }),\n );\n }\n return err(\n new RhiErrorClass({\n code: 'webgpu-runtime-error',\n expected: 'underlying GPUDevice.createComputePipeline to succeed',\n hint: `createComputePipeline raised: ${message}`,\n }),\n );\n }\n },\n createQuerySet(desc: QuerySetDescriptor): Result<QuerySet, RhiError> {\n // Hard constraint: count <= 4096 (research §1.3 device timeline step 1).\n const count = desc.count as number | undefined;\n if (typeof count === 'number' && count > QUERY_SET_COUNT_LIMIT) {\n return err(\n new RhiErrorClass({\n code: 'limit-exceeded',\n expected: 'count <= 4096 (spec normative)',\n hint: 'create multiple QuerySet instances if more than 4096 queries needed',\n }),\n );\n }\n // Hard constraint: timestamp requires caps.timestampQuery.\n if (desc.type === 'timestamp' && caps.timestampQuery !== true) {\n return err(\n new RhiErrorClass({\n code: 'feature-not-enabled',\n expected: 'caps.timestampQuery === true (timestamp-query feature)',\n hint: 'request the timestamp-query feature at requestDevice and check device.caps.timestampQuery before creating timestamp QuerySets',\n }),\n );\n }\n try {\n const out = rawDevice.createQuerySet(\n mirror(desc, QS_KEYS) as unknown as GPUQuerySetDescriptor,\n );\n const handle = out as unknown as QuerySet;\n // Register raw handle so the RPE / encoder paths can read `.count` /\n // `.type` for bounds + alignment checks (research §2.1 + §2.3).\n QUERY_SET_RAW_MAP.set(handle, out);\n QUERY_SET_DESTROYED_MAP.set(handle, { destroyed: false });\n return ok(handle);\n } catch (e) {\n const message = e instanceof Error ? e.message : String(e);\n return err(\n new RhiErrorClass({\n code: 'webgpu-runtime-error',\n expected: 'underlying GPUDevice.createQuerySet to succeed',\n hint: `createQuerySet raised: ${message}`,\n }),\n );\n }\n },\n destroyQuerySet(querySet: QuerySet): Result<void, RhiError> {\n const marker = QUERY_SET_DESTROYED_MAP.get(querySet);\n if (marker?.destroyed) {\n return err(\n new RhiErrorClass({\n code: 'destroy-after-destroy',\n expected: 'GPU query-set handle has not been destroyed yet',\n hint: 'object already destroyed; release each timestamp QuerySet exactly once',\n }),\n );\n }\n const rawQuery = QUERY_SET_RAW_MAP.get(querySet) as\n | (GPUQuerySet & { destroy?: () => void })\n | undefined;\n try {\n if (rawQuery !== undefined && typeof rawQuery.destroy === 'function') rawQuery.destroy();\n } catch (e) {\n const message = e instanceof Error ? e.message : String(e);\n return err(\n new RhiErrorClass({\n code: 'webgpu-runtime-error',\n expected: 'underlying GPUQuerySet.destroy() to succeed',\n hint: `destroy raised: ${message}`,\n }),\n );\n }\n if (marker !== undefined) marker.destroyed = true;\n return ok(undefined);\n },\n createCommandEncoder(\n desc?: CommandEncoderDescriptor | undefined,\n ): Result<RhiCommandEncoder, RhiError> {\n const rawEnc =\n desc === undefined\n ? rawDevice.createCommandEncoder()\n : rawDevice.createCommandEncoder(\n mirror(desc, ENC_KEYS) as unknown as GPUCommandEncoderDescriptor,\n );\n // M5 / w39: pass caps.timestampQuery + an onError-style fan-out so\n // writeTimestamp can fire 'feature-not-enabled' through the engine\n // channel when caps.timestampQuery is false (K-3: spec writeTimestamp\n // returns void; the forgeax form keeps that shape).\n //\n // Round 3 fix-up F-P3-3: the forgeax RhiDevice\n // does not expose `onError` directly (charter proposition 5: keep\n // RHI math-free + listener-free), so the shim writes a structured\n // diagnostic to `console.error` matching the RhiError shape. The\n // engine layer subscribes through `Renderer.onError` and fans the\n // same RhiError out; this keeps the unsupported capability observable\n // for pure-RHI consumers (mock unit tests, dawn-real-gpu probes) that\n // never instantiate a Renderer.\n const fireFeatureNotEnabled = (featureName: string, hint: string): void => {\n // Diagnostic channel (a) of the K-9 double-channel pattern: default\n // console.error so AI consumers running headless / mock paths still\n // observe the unsupported capability without subscribing to a\n // listener. The capability-disabled entry remains non-throwing.\n console.error(\n `[RhiError feature-not-enabled] expected: device.features.has('${featureName}') === true; hint: ${hint}`,\n );\n };\n return ok(makeCommandEncoder(rawEnc, caps, fireFeatureNotEnabled));\n },\n // fix-f3: synchronous createShaderModule placeholder removed; the\n // shader-compile-failed path lives in the top-level async factory\n // (see ../index.ts).\n };\n RAW_DEVICE_MAP.set(device, rawDevice);\n return { device, raw: rawDevice };\n}\n\n// ============================================================================\n// RhiCanvasContext shim (M3 / K-4 / w21)\n// ============================================================================\n//\n// Spec anchor: W3C WebGPU §3.3 GPUCanvasContext / GPUCanvasConfiguration.\n// 4 methods (research §3.1) + 7 fields (§3.2) + 4 method algorithms (§3.3).\n\n/** Spec normative supported context formats (research §3.2 normative). */\nconst SUPPORTED_CONTEXT_FORMATS: ReadonlySet<string> = new Set([\n 'bgra8unorm',\n 'rgba8unorm',\n 'rgba16float',\n]);\n\nconst CANVAS_CONFIG_KEYS = [\n 'device',\n 'format',\n 'usage',\n 'viewFormats',\n 'colorSpace',\n 'toneMapping',\n 'alphaMode',\n] as const;\n\n/** Stripped-down GPUCanvasContext shape the shim consumes. Real\n * GPUCanvasContext satisfies this; the unit-test mock fixture only\n * implements what is needed (charter proposition 1: progressive disclosure). */\nexport interface GpuCanvasContextLike {\n configure(configuration: GPUCanvasConfiguration): void;\n unconfigure(): void;\n getConfiguration(): GPUCanvasConfiguration | null;\n getCurrentTexture(): GPUTexture;\n}\n\n/**\n * Build a RhiCanvasContext shim around a raw GPUCanvasContext (M3 / K-4 /\n * w21).\n *\n * Pre-configure validation (research §3.3 mapping):\n * - format gate: format must be in SUPPORTED_CONTEXT_FORMATS; otherwise\n * fast-path returns `'webgpu-runtime-error'` with the spec-aligned\n * `.expected` literal `'one of bgra8unorm/rgba8unorm/rgba16float'`.\n *\n * Post-configure semantics:\n * - getCurrentTexture forwards each call to the raw context (NO cross-frame\n * caching, research §3.3 [[Expire the current texture]]); spec\n * InvalidStateError catches map to `'webgpu-runtime-error'`.\n * - getConfiguration projects the spec record verbatim; missing fields\n * remain missing (feature-detection idiom, research §3.2 toneMapping\n * NOTE).\n */\nexport function makeCanvasContext(rawContext: GpuCanvasContextLike): RhiCanvasContext {\n return {\n configure(desc: CanvasConfiguration): Result<void, RhiError> {\n const fmt = desc.format as GPUTextureFormat | undefined;\n if (typeof fmt === 'string' && !SUPPORTED_CONTEXT_FORMATS.has(fmt)) {\n return err(\n new RhiErrorClass({\n code: 'webgpu-runtime-error',\n expected: 'one of bgra8unorm/rgba8unorm/rgba16float',\n hint: `got format='${fmt}'; canvas configuration cannot use srgb formats — use the non-srgb form (e.g. 'bgra8unorm') and put the srgb format in viewFormats, then createView with the srgb format`,\n }),\n );\n }\n try {\n const mirrored = mirror(\n desc as unknown as Record<string, unknown>,\n CANVAS_CONFIG_KEYS,\n ) as unknown as Record<string, unknown>;\n // CanvasConfiguration.device is a forgeax RhiDevice brand (D-S5);\n // the spec GPUCanvasContext.configure({ device }) slot needs the raw\n // GPUDevice. Translate via RAW_DEVICE_MAP so AI-user-facing code only\n // sees the forgeax abstraction while the underlying spec call still\n // receives a valid raw device (charter proposition 5 consistent\n // abstraction red line + feat-20260510-rhi-resource-creation M4\n // escape hatch tear-down: the translation is fully internal to\n // packages/rhi-webgpu/src and does not surface a reverse-lookup\n // entry across the package boundary).\n if ('device' in mirrored) {\n const forgeaxDevice = desc.device as RhiDevice;\n const rawDev = RAW_DEVICE_MAP.get(forgeaxDevice);\n if (rawDev === undefined) {\n return err(\n new RhiErrorClass({\n code: 'rhi-not-available',\n expected:\n 'CanvasConfiguration.device must be a RhiDevice produced by rhi.requestAdapter().requestDevice() (or the deprecated rhi.requestDevice factory)',\n hint: 'pass the device returned by the forgeax rhi.requestAdapter() / rhi.requestDevice() entries; passing a foreign RhiDevice or a raw GPUDevice is rejected because the canvas-context spec requires the same raw GPUDevice that the forgeax shim wraps',\n }),\n );\n }\n mirrored.device = rawDev;\n }\n rawContext.configure(mirrored as unknown as GPUCanvasConfiguration);\n return ok(undefined);\n } catch (e) {\n const msg = e instanceof Error ? e.message : String(e);\n // Spec maps invalid / lost device to InvalidStateError; we map the\n // catch-all to webgpu-runtime-error so AI users get a structured\n // failure (charter proposition 4 explicit failure).\n if (e instanceof Error && (e.name === 'InvalidStateError' || /lost|destroyed/i.test(msg))) {\n return err(\n new RhiErrorClass({\n code: 'rhi-not-available',\n expected: 'CanvasConfiguration.device must be valid (not lost / destroyed)',\n hint: `configure raised: ${msg}`,\n }),\n );\n }\n return err(\n new RhiErrorClass({\n code: 'webgpu-runtime-error',\n expected: 'underlying GPUCanvasContext.configure to succeed',\n hint: `configure raised: ${msg}`,\n }),\n );\n }\n },\n unconfigure(): void {\n rawContext.unconfigure();\n },\n getConfiguration(): CanvasConfiguration | undefined {\n const conf = rawContext.getConfiguration();\n if (conf === null) return undefined;\n // Project spec fields onto the forgeax record verbatim; missing fields\n // remain missing (feature-detection idiom).\n const out: Record<string, unknown> = {};\n for (const k of CANVAS_CONFIG_KEYS) {\n if (k in (conf as unknown as Record<string, unknown>)) {\n out[k] = (conf as unknown as Record<string, unknown>)[k];\n }\n }\n return out as unknown as CanvasConfiguration;\n },\n getCurrentTexture(): Result<Texture, RhiError> {\n try {\n const rawTex = rawContext.getCurrentTexture();\n return ok(rawTex as unknown as Texture);\n } catch (e) {\n const msg = e instanceof Error ? e.message : String(e);\n // Spec InvalidStateError on unconfigured context maps to\n // 'webgpu-runtime-error' (charter proposition 4).\n return err(\n new RhiErrorClass({\n code: 'webgpu-runtime-error',\n expected: 'GPUCanvasContext.getCurrentTexture to succeed (context configured)',\n hint: `getCurrentTexture raised: ${msg}`,\n }),\n );\n }\n },\n };\n}\n","// @forgeax/engine-rhi-webgpu/src/internal/error-translation — spec GPUError +\n// GPUDeviceLostInfo -> 17-member RhiErrorCode dispatch translator (D-P4 literal).\n//\n// Charter: proposition 4 (explicit failure) — every WebGPU async dispatch\n// error reachable through onuncapturederror / device.lost has a closed-union\n// RhiErrorCode mapping; proposition 5 (consistent abstraction) — the dual\n// backends (rhi-webgpu / rhi-wgpu) translate the SAME spec event shape to the\n// SAME 17-member union so engine.onError listeners see byte-for-byte aligned\n// .code values regardless of which backend dispatched the error.\n//\n// Mapping rules (plan-strategy D-P4 table literal):\n// (a) GPUValidationError — sub-pattern on the message text:\n// - /shader|compile|wgsl/i -> 'shader-compile-failed'\n// - /size|alignment|out of bounds/i -> 'queue-write-buffer-out-of-bounds'\n// - /encoder.*finished|finished encoder/i -> 'command-encoder-finished'\n// - /render pass.*not ended|not ended/i -> 'render-pass-not-ended'\n// - /submit/i -> 'queue-submit-failed'\n// - default -> 'limit-exceeded' (the broadest spec validation bucket\n// reachable from validation messages; AI users still get a\n// structured code, not 'webgpu-runtime-error' which is reserved for\n// unrecognised types).\n// (b) GPUOutOfMemoryError -> 'oom' (RhiErrorCode 17-member addition w6).\n// (c) GPUInternalError -> 'internal-error' (RhiErrorCode 17-member addition w6).\n// (d) GPUDeviceLostInfo -> 'device-lost' (RhiErrorCode 17-member addition w6).\n// (e) Unrecognised event type -> 'webgpu-runtime-error' (catch-all bucket;\n// AI users `switch (err.code)` still exhausts the closed union).\n//\n// Dual-channel responsibility boundary (D-PD4):\n// - createX entries return Result.ok / Result.err *synchronously* — sync\n// validation errors (size=0, missing layout, etc.) flow through this\n// channel via the existing errors.ts factories.\n// - device.lost + onuncapturederror channels carry *async* dispatch errors\n// — this translator is the sole gateway from spec event -> RhiError in\n// that async channel. The engine RhiErrorListenerRegistry fan-out happens\n// downstream (packages/engine/src/renderer.ts).\n//\n// Anchors: requirements AC-02 + AC-04; research R-02 §2.1 spec / wgpu / dawn\n// three-way fact; plan-strategy D-P4 mapping table literal; charter propositions\n// 4 + 5; AGENTS.md \"## RHI / Shader / error model contract\" evolution contract\n// minor add-only.\n\n/// <reference types=\"@webgpu/types\" />\n\nimport { err, type Result, RhiError } from '@forgeax/engine-rhi';\n\n/** Translate a spec async-dispatch error event into a closed-union RhiError.\n *\n * This is the single gateway from `GPUUncapturedErrorEvent` / `device.lost`\n * Promise into the 17-member `RhiErrorCode` union (charter proposition 5\n * consistent abstraction: dual-backend dispatch tables align byte-for-byte).\n *\n * @note GPUValidationError dispatch defaults to the 'limit-exceeded' bucket when the device-side message does not match any narrower regex pattern; see L12-21 module-level mapping rules comment for the full sub-pattern table (5 narrower regexes + default fallback). AI users still receive a structured `.code` rather than `'webgpu-runtime-error'` (reserved for unrecognised event types only); charter proposition 4 explicit failure — every spec event maps to a real union member.\n * @param event one of:\n * - `GPUUncapturedErrorEvent` (carries a `.error` of `GPUValidationError |\n * GPUOutOfMemoryError | GPUInternalError`);\n * - `GPUDeviceLostInfo` (carries `.reason` + `.message`);\n * - opaque (catch-all → 'webgpu-runtime-error').\n */\nexport function translateErrorEventToRhiError(\n event: GPUUncapturedErrorEvent | GPUDeviceLostInfo | unknown,\n): Result<never, RhiError> {\n // (d) device-lost branch — GPUDeviceLostInfo shape has `.reason` enum.\n if (\n typeof event === 'object' &&\n event !== null &&\n 'reason' in event &&\n typeof (event as { reason: unknown }).reason === 'string'\n ) {\n const info = event as GPUDeviceLostInfo;\n return err(\n new RhiError({\n code: 'device-lost',\n expected: 'device must remain alive (driver / browser must not destroy the GPUDevice)',\n hint: `device-lost reason: ${info.reason}; message: ${info.message ?? '<empty>'}`,\n }),\n );\n }\n\n // GPUUncapturedErrorEvent branch — carries `.error` of GPUError subtype.\n if (\n typeof event === 'object' &&\n event !== null &&\n 'error' in event &&\n typeof (event as { error: unknown }).error === 'object' &&\n (event as { error: unknown }).error !== null\n ) {\n const error = (event as { error: unknown }).error as object;\n const message =\n typeof (error as { message?: unknown }).message === 'string'\n ? (error as { message: string }).message\n : '<no message>';\n\n // (b) GPUOutOfMemoryError → 'oom' — detected by constructor name.\n if (error.constructor.name === 'GPUOutOfMemoryError') {\n return err(\n new RhiError({\n code: 'oom',\n expected: 'sufficient GPU memory to satisfy the allocation',\n hint: `GPU out-of-memory: ${message}`,\n }),\n );\n }\n\n // (c) GPUInternalError → 'internal-error' — detected by constructor name.\n if (error.constructor.name === 'GPUInternalError') {\n return err(\n new RhiError({\n code: 'internal-error',\n expected: 'driver / browser must report a recognised validation error',\n hint: `GPU internal error: ${message}`,\n }),\n );\n }\n\n // (a) GPUValidationError → sub-pattern dispatch via message text.\n if (error.constructor.name === 'GPUValidationError') {\n if (/shader|compile|wgsl/i.test(message)) {\n return err(\n new RhiError({\n code: 'shader-compile-failed',\n expected: 'valid WGSL source + matching pipeline layout',\n hint: `GPU validation: ${message}`,\n }),\n );\n }\n if (/size|alignment|out of bounds/i.test(message)) {\n return err(\n new RhiError({\n code: 'queue-write-buffer-out-of-bounds',\n expected: 'writeBuffer offset + data.byteLength must be within buffer.size',\n hint: `GPU validation: ${message}`,\n }),\n );\n }\n if (/encoder.*finished|finished encoder/i.test(message)) {\n return err(\n new RhiError({\n code: 'command-encoder-finished',\n expected: 'command encoder must not be finished before recording new commands',\n hint: `GPU validation: ${message}`,\n }),\n );\n }\n if (/render pass.*not ended|pass.*not ended/i.test(message)) {\n return err(\n new RhiError({\n code: 'render-pass-not-ended',\n expected: 'previous render pass must be ended before beginning a new pass',\n hint: `GPU validation: ${message}`,\n }),\n );\n }\n if (/submit/i.test(message)) {\n return err(\n new RhiError({\n code: 'queue-submit-failed',\n expected: 'command buffer references must be valid at submit time',\n hint: `GPU validation: ${message}`,\n }),\n );\n }\n // Default validation bucket — limit-exceeded is the broadest reachable\n // spec validation code (AI users still get a structured code, not the\n // catch-all 'webgpu-runtime-error').\n return err(\n new RhiError({\n code: 'limit-exceeded',\n expected: 'descriptor field values within device limits',\n hint: `GPU validation: ${message}`,\n }),\n );\n }\n }\n\n // (e) Catch-all — unrecognised event type → 'webgpu-runtime-error'.\n const repr =\n typeof event === 'object' && event !== null && 'toString' in event\n ? String(event)\n : '<unknown>';\n return err(\n new RhiError({\n code: 'webgpu-runtime-error',\n expected: 'spec-recognised GPUUncapturedErrorEvent or GPUDeviceLostInfo',\n hint: `unrecognised async-dispatch event: ${repr}`,\n }),\n );\n}\n","// @forgeax/engine-rhi-webgpu — thin WebGPU shim implementing the @forgeax/engine-rhi interface shape.\n//\n// Shape rules (shared between README + AGENTS.md '## RHI / WebGPU' section):\n// - spec alignment — the 5 descriptor field names pass through verbatim to\n// GPUDevice.createX.\n// - `?: T | undefined` + `'x' in src` guard (decision S-7 / research §F-3).\n// - opaque handle — `RhiDevice.createX` returns `Result.ok(handle)`; the handle\n// internally references the GPU resource object but exposes only a brand-only\n// opaque shape externally (research §R5).\n// - capability-gated — caps / features / limits are exposed as three independent\n// readonly layers (charter proposition 5).\n// - device.lost dual-track — the spec Promise passes through (research §F-4 / R2\n// countermeasure); the engine layer does the fan-out, this package does not\n// introduce a secondary cache.\n//\n// Public entries (charter proposition 1: progressive disclosure / single entry that\n// surfaces the full surface area at once):\n// - requestAdapter(opts?) — entry 1: spec-aligned strict two-step\n// path (M3 break-point #2 + M6 fix-up\n// [w51]); returns Result<RhiAdapter, RhiError>.\n// - createShaderModule(d, desc) — entry 2: async, returns\n// Result<ShaderModule, RhiError>; the\n// shader-compile-failed path includes\n// detail.compilerMessages.\n// - acquireCanvasContext(canvas) — entry 3: calls canvas.getContext('webgpu')\n// + wraps as branded RhiCanvasContext (M3 / w15).\n// - rhi — singleton entry (plan-strategy §7.4\n// 'import { rhi } from @forgeax/engine-rhi-webgpu' +\n// Engine.create({ rhi, canvas })).\n//\n// The legacy single-step `rhi.requestDevice(opts)` factory was retired in\n// M6 fix-up [w51] (AGENTS.md break-point list 2026-05-10 #2). Callers go\n// through `(await rhi.requestAdapter()).value.requestDevice(opts)`.\n//\n// Anchors: requirements §AC AC-05 + AC-10 + MVP-1.1 / MVP-1.2 / MVP-1.7 + edge cases\n// + §hard constraint 10; plan-strategy §1 architecture + §2 S-7 + §6 M2 +\n// §7.3 error-message strategy table + §7.4 discoverability;\n// research §F-1 / §F-3 / §F-4 / §F-5 / §F-6.\n\n/// <reference types=\"@webgpu/types\" />\n\nimport type {\n RequestDeviceOptions as ForgeaXRequestDeviceOptions,\n RequestAdapterOptions,\n Result,\n RhiAdapter,\n RhiCanvasContext,\n RhiDevice,\n RhiError,\n RhiInstance,\n ShaderModule,\n} from '@forgeax/engine-rhi';\nimport { err, ok, RhiError as RhiErrorClass } from '@forgeax/engine-rhi';\nimport { _internal_getRawDevice, makeCanvasContext, makeRhiDevice } from './device';\nimport {\n adapterUnavailable,\n featureNotEnabled,\n limitExceeded,\n requestAdapterFailed,\n shaderCompileFailed,\n} from './errors';\n\n/**\n * The `GPU` subset accepted at the provider seam (research §F-6 webgpu-utils +\n * CTS consensus).\n *\n * The shim only calls the two entries `gpu.requestAdapter()` →\n * `adapter.requestDevice()`; accepting a structural subset rather than requiring\n * a full GPU interface implementation lets the mock fixture\n * (src/__tests__/__mocks__/gpu-device.ts) skip implementing\n * `wgslLanguageFeatures` / `getPreferredCanvasFormat` and other fields this loop\n * does not consume (charter proposition 1: progressive disclosure).\n */\nexport interface GpuLike {\n // forgeax-async-whitelist: dom-native — spec `GPU.requestAdapter()` raw entry\n requestAdapter(options?: GPURequestAdapterOptions | undefined): Promise<GpuAdapterLike | null>;\n}\n\n/** The `GPUAdapter` subset accepted at the provider seam — only the `requestDevice` entry is consumed. */\nexport interface GpuAdapterLike {\n // forgeax-async-whitelist: dom-native — spec `GPUAdapter.requestDevice()` raw entry\n requestDevice(descriptor?: GPUDeviceDescriptor | undefined): Promise<GpuDeviceLike>;\n}\n\n/**\n * The `GPUDevice` subset accepted at the provider seam — exactly the fields the\n * shim actually touches (the 5 descriptor `createX` calls + features / limits /\n * lost + a `queue` placeholder).\n *\n * Differences from the full GPUDevice spec:\n * - `onuncapturederror` / `pushErrorScope` / `createCommandEncoder` not required\n * (only needed at M3).\n * - `wgslLanguageFeatures` / `getPreferredCanvasFormat` not required (charter\n * proposition 1: progressive disclosure).\n *\n * The coverage of `cast as GPUDevice` inside `makeRhiDevice` matches this\n * interface exactly; both the mock and the real GPUDevice only need to satisfy\n * this structural subset.\n */\nexport interface GpuDeviceLike {\n readonly features: GPUSupportedFeatures;\n readonly limits: GPUSupportedLimits;\n // forgeax-async-whitelist: dom-native — spec `GPUDevice.lost` Promise passthrough\n readonly lost: Promise<GPUDeviceLostInfo>;\n readonly queue: unknown;\n createBuffer(descriptor: GPUBufferDescriptor): unknown;\n createTexture(descriptor: GPUTextureDescriptor): unknown;\n createSampler(descriptor?: GPUSamplerDescriptor | undefined): unknown;\n createBindGroupLayout(descriptor: GPUBindGroupLayoutDescriptor): unknown;\n createBindGroup(descriptor: GPUBindGroupDescriptor): unknown;\n createPipelineLayout(descriptor: GPUPipelineLayoutDescriptor): unknown;\n createRenderPipeline(descriptor: GPURenderPipelineDescriptor): unknown;\n createShaderModule(descriptor: GPUShaderModuleDescriptor): unknown;\n}\n\n/**\n * Options for the `requestDevice` entry.\n *\n * `gpu?: GpuLike` is the provider seam (research §F-6 webgpu-utils + CTS\n * consensus):\n * - omitted → falls back to `globalThis.navigator.gpu` (real-device path).\n * - explicitly provided → uses the caller-injected mock / real GPU object (mock\n * unit-test path).\n *\n * `adapterOptions` / `deviceDescriptor` pass through to the corresponding spec\n * entries.\n */\nexport interface RequestDeviceOptions {\n gpu?: GpuLike | undefined;\n adapterOptions?: GPURequestAdapterOptions | undefined;\n deviceDescriptor?: GPUDeviceDescriptor | undefined;\n}\n\n/**\n * Maps an OperationError that may occur during `requestDevice` back into a\n * RhiError.\n *\n * Spec behavior (research §F-5 / W3C CR §\"Adapter Selection\"):\n * - `requiredFeatures` exceeds the adapter → reject with `OperationError`.\n * - `requiredLimits` exceeds the adapter → reject with `OperationError`.\n *\n * This package distinguishes feature vs limit by message keyword; the message\n * format is not interoperable between the mock and real GPU implementations\n * (research §F-4: ecosystem-wide message-field inconsistency), but the keywords\n * 'feature' / 'limit' work as a heuristic on both sides. Detailed\n * classification (including limit-name / feature-name extraction) is left to a\n * follow-up loop (plan-strategy §3 R2 fallback).\n */\nfunction classifyRequestDeviceError(e: unknown): Result<never, RhiError> {\n const msg = e instanceof Error ? e.message : String(e);\n if (/feature/i.test(msg)) return featureNotEnabled();\n if (/limit/i.test(msg)) return limitExceeded();\n // Fallback: an unrecognized message keyword is classified as feature-not-enabled\n // (charter proposition 4: explicit failure + structured errors over hidden\n // branches). Subsequent loops can extend the classification.\n return featureNotEnabled();\n}\n\n/**\n * Internal `requestDevice` — single-step factory accepting an injected\n * `gpu` mock provider. **Not part of the public RHI surface**: AI users go\n * through the spec-aligned two-step path\n * `rhi.requestAdapter() -> adapter.requestDevice()` (M3 break-point #2 + M6\n * fix-up [w51]; AGENTS.md break-point list 2026-05-10 #2). This entry is\n * retained as the unit-test seam (`packages/rhi-webgpu/src/__tests__/*`)\n * for `gpu` mock injection; it is **not** re-exported through the `rhi`\n * singleton and is **not** referenced by engine / apps / dawn paths\n * (charter proposition 5 consistent abstraction red line + grep gate\n * `m6-e: rhi.requestDevice( 0 hit`).\n *\n * Generates 3 of the 4 error paths here (research §F-5):\n * - adapter null → `Result.err(RhiError { code: 'adapter-unavailable' })`\n * - feature not enabled → `Result.err(RhiError { code: 'feature-not-enabled' })`\n * - limit exceeded → `Result.err(RhiError { code: 'limit-exceeded' })`\n *\n * The 4th path (shader-compile-failed) is generated by the\n * `createShaderModule` entry.\n */\nexport async function requestDevice(\n opts: RequestDeviceOptions = {},\n): Promise<Result<RhiDevice, RhiError>> {\n const injected: GpuLike | undefined = opts.gpu;\n const ambient: GPU | undefined =\n typeof globalThis !== 'undefined'\n ? (globalThis as { navigator?: Navigator }).navigator?.gpu\n : undefined;\n const gpu: GpuLike | undefined = injected ?? ambient;\n if (gpu === undefined || gpu === null) {\n return adapterUnavailable();\n }\n\n const adapter = await gpu.requestAdapter(opts.adapterOptions);\n if (adapter === null) {\n return adapterUnavailable();\n }\n\n let rawDevice: GpuDeviceLike;\n try {\n rawDevice = await adapter.requestDevice(opts.deviceDescriptor);\n } catch (e) {\n return classifyRequestDeviceError(e);\n }\n\n const { device } = makeRhiDevice(rawDevice as unknown as GPUDevice);\n return ok(device);\n}\n\nfunction createRawShaderModule(\n device: RhiDevice,\n desc: { label?: string | undefined; code: string },\n): Result<GPUShaderModule, RhiError> {\n // In-package reverse lookup of the underlying GPUDevice. The raw handle is\n // intentionally kept behind this package boundary; render assembly may use\n // this synchronous step, while public callers use the diagnostic-rich async\n // entry below.\n const rawDevice = _internal_getRawDevice(device);\n if (rawDevice === undefined) {\n return shaderCompileFailed([\n {\n type: 'error',\n message: 'rhi-webgpu: createShaderModule called with unregistered RhiDevice',\n lineNum: 0,\n linePos: 0,\n offset: 0,\n length: 0,\n } as GPUCompilationMessage,\n ]);\n }\n const mirrored: { label?: string; code: string } = { code: desc.code };\n if ('label' in desc && desc.label !== undefined) mirrored.label = desc.label;\n try {\n return ok(rawDevice.createShaderModule(mirrored as GPUShaderModuleDescriptor));\n } catch (e) {\n // The synchronous part of a real-device createShaderModule rarely throws\n // (spec: errors are surfaced asynchronously through getCompilationInfo);\n // a few mock shapes might throw — preserve the public structured error.\n const message = e instanceof Error ? e.message : String(e);\n return shaderCompileFailed([\n {\n type: 'error',\n message,\n lineNum: 0,\n linePos: 0,\n offset: 0,\n length: 0,\n } as GPUCompilationMessage,\n ]);\n }\n}\n\n/**\n * Entry 2 - async `createShaderModule`. The shader-compile-failed path\n * forwards every 6 fields of `GPUCompilationMessage` to\n * `RhiError.detail.compilerMessages` (OQ-P2 / F-3 finding).\n *\n * Implementation (post fix-f3):\n * 1) Look up the underlying `GPUDevice` via the in-package\n * `_internal_getRawDevice` (RAW_DEVICE_MAP reverse lookup; same module).\n * 2) `rawDevice.createShaderModule(desc)` calls the spec entry to obtain\n * a `GPUShaderModule`.\n * 3) `await module.getCompilationInfo()` retrieves compilation info.\n * 4) If any message has `type === 'error'`, return\n * `Result.err(RhiError { code: 'shader-compile-failed',\n * detail: { compilerMessages } })`.\n * 5) Otherwise return `Result.ok(module as ShaderModule)`.\n *\n * Note: this entry accepts a shim-wrapped RhiDevice (not a raw GPUDevice)\n * to keep the public API single-source; the in-package\n * `_internal_getRawDevice` is the only sanctioned reverse lookup.\n *\n * fix-f3: the synchronous `RhiDevice.createShaderModule` placeholder is\n * removed; the shader-compile-failed path closes inside this async entry\n * (charter proposition 5 consistent abstraction + proposition 4 explicit\n * failure).\n */\nexport async function createShaderModule(\n device: RhiDevice,\n desc: { label?: string | undefined; code: string },\n): Promise<Result<ShaderModule, RhiError>> {\n const rawResult = createRawShaderModule(device, desc);\n if (!rawResult.ok) return rawResult;\n const handle = rawResult.value;\n const handleWithInfo = handle as GPUShaderModule & {\n // forgeax-async-whitelist: dom-native — spec `GPUShaderModule.getCompilationInfo()`\n getCompilationInfo?: () => Promise<GPUCompilationInfo>;\n };\n if (typeof handleWithInfo.getCompilationInfo !== 'function') {\n // A real GPUShaderModule always has getCompilationInfo (spec-mandated);\n // its absence implies the shim path drifted from the spec — the degraded\n // path returns ok (does not block the engine layer; charter\n // proposition 9: graceful degradation).\n return ok(handle as unknown as ShaderModule);\n }\n let info: GPUCompilationInfo;\n try {\n info = await handleWithInfo.getCompilationInfo();\n } catch {\n // getCompilationInfo() rejects when the underlying GPU instance is dropped\n // mid-await — the device was destroyed (or the page is tearing down) while\n // the async compilation-info query was in flight. The module handle was\n // already created synchronously above, so there is nothing left to report;\n // returning ok keeps an unobserved teardown rejection from escaping as an\n // unhandled rejection (charter proposition 9: graceful degradation, same\n // degraded path as the missing-getCompilationInfo branch above).\n return ok(handle as unknown as ShaderModule);\n }\n const errors = info.messages.filter((m) => m.type === 'error');\n if (errors.length > 0) {\n // Keep the public six-field GPUCompilationMessage shape intact while\n // making browser failures attributable to the shader producer. Dawn's\n // aggregate output is otherwise indistinguishable when several modules\n // are created during renderer bootstrap.\n const sourcePrefix =\n desc.label === undefined ? '' : ` source=${JSON.stringify(desc.code.slice(0, 24))}`;\n const labeledMessages = info.messages.map((message) => ({\n message:\n desc.label === undefined\n ? message.message\n : `[${desc.label}]${sourcePrefix} ${message.message}`,\n type: message.type,\n lineNum: message.lineNum,\n linePos: message.linePos,\n offset: message.offset,\n length: message.length,\n })) as GPUCompilationMessage[];\n return shaderCompileFailed(labeledMessages);\n }\n return ok(handle as unknown as ShaderModule);\n}\n\n/**\n * Internal render-path shader creation. WebGPU returns a module handle\n * synchronously; compiler diagnostics remain owned by the public async\n * `createShaderModule` entry. Render pipeline creation is the validation point\n * for this path, so software adapters do not serialize their first frame on\n * `getCompilationInfo()` for every material.\n */\nexport function createShaderModuleImmediate(\n device: RhiDevice,\n desc: { label?: string | undefined; code: string },\n): Result<ShaderModule, RhiError> {\n const result = createRawShaderModule(device, desc);\n return result.ok ? ok(result.value as unknown as ShaderModule) : result;\n}\n\n/**\n * Build a RhiAdapter shim around a raw GPUAdapter (M3 / break-point #2 / K-5 +\n * K-6).\n *\n * Field projection:\n * - `features` <- `new Set([...adapter.features])` (Round 3 fix-up F-P1-2:\n * surfaces a `ReadonlySet<GPUFeatureName>` aligned with\n * `RhiDevice.features`, so AI users use `.has(name)` uniformly across\n * both abstraction layers; previously projected to `ReadonlyArray<string>`\n * which split the cross-tier idiom).\n * - `limits` <- structural copy of `adapter.limits` numeric fields. Spec\n * `GPUSupportedLimits` is a typed object whose enumerable own-keys are\n * exactly the limit fields (research §6.3 + spec normative); the shim\n * surfaces them via `Readonly<Record<string, number>>` for ergonomic AI-\n * user lookups (`adapter.limits.maxTextureDimension2D`).\n * - `requestDevice` forwards to `adapter.requestDevice(opts)` and wraps the\n * resulting `GPUDevice` via `makeRhiDevice` (research §F-5 error paths).\n */\nfunction makeRhiAdapter(rawAdapter: {\n readonly features?: GPUSupportedFeatures | undefined;\n readonly limits?: GPUSupportedLimits | undefined;\n // forgeax-async-whitelist: dom-native — spec `GPUAdapter.requestDevice()` raw forward\n requestDevice(descriptor?: GPUDeviceDescriptor | undefined): Promise<unknown>;\n}): RhiAdapter {\n // Defensive against minimal mock adapters that omit features / limits\n // (the spec mandates them on real adapters, but unit-test mocks\n // historically expose only `requestDevice`). Defaults to empty\n // projections; real adapters always supply both fields.\n const rawFeatures = rawAdapter.features as unknown as ReadonlySet<GPUFeatureName> | undefined;\n const features: ReadonlySet<GPUFeatureName> =\n rawFeatures !== undefined && rawFeatures !== null\n ? new Set(rawFeatures)\n : new Set<GPUFeatureName>();\n const limitsRaw = (rawAdapter.limits as unknown as Record<string, unknown> | undefined) ?? {};\n const limits: Record<string, number> = {};\n for (const key in limitsRaw) {\n const v = limitsRaw[key];\n if (typeof v === 'number') {\n limits[key] = v;\n }\n }\n return {\n features,\n limits: limits as Readonly<Record<string, number>>,\n async requestDevice(\n opts?: ForgeaXRequestDeviceOptions | undefined,\n ): Promise<Result<RhiDevice, RhiError>> {\n let rawDevice: GpuDeviceLike;\n try {\n rawDevice = (await rawAdapter.requestDevice(\n opts as GPUDeviceDescriptor | undefined,\n )) as GpuDeviceLike;\n } catch (e) {\n return classifyRequestDeviceError(e);\n }\n const { device } = makeRhiDevice(rawDevice as unknown as GPUDevice);\n return ok(device);\n },\n };\n}\n\n/**\n * Entry — `requestAdapter` walks `navigator.gpu.requestAdapter(opts)` and\n * wraps the result as a forgeax `RhiAdapter` (M3 break-point #2; K-5 + K-6).\n *\n * Strict two-step path mirrors wgpu / Dawn (research §6); the legacy\n * `requestDevice(opts)` factory below is the deprecated single-step shortcut\n * kept for backward compatibility while existing callers migrate.\n *\n * Optional `gpu` provider seam at the `RequestAdapterOptions`-side: this\n * factory takes only the forgeax-spec `RequestAdapterOptions` (powerPreference\n * / forceFallbackAdapter); when callers need the mock-injection seam they go\n * through the legacy `requestDevice({ gpu })` form.\n *\n * @param opts — W3C-spec request adapter options.\n * @param _compatibleSurface — accepted for dual-impl symmetry\n * (plan-strategy D-5; AGENTS.md \"Dual-impl ship-together\" rule).\n * The browser WebGPU backend does not use this parameter; it is\n * ignored. rhi-wgpu routes it to `requestAdapterWithCanvas`.\n */\nexport async function requestAdapter(\n opts?: RequestAdapterOptions | undefined,\n _compatibleSurface?: HTMLCanvasElement | OffscreenCanvas | undefined,\n): Promise<Result<RhiAdapter, RhiError>> {\n const ambient: GPU | undefined =\n typeof globalThis !== 'undefined'\n ? (globalThis as { navigator?: Navigator }).navigator?.gpu\n : undefined;\n if (ambient === undefined || ambient === null) {\n return adapterUnavailable();\n }\n // `null` is the spec adapter-absence channel. A rejection is a different\n // failure (permission policy, insecure context, browser/runtime fault, etc.)\n // and must retain its cause instead of being rewritten as unsupported WebGPU.\n // Both outcomes remain structured, so Runtime can still try its wgpu/WebGL2\n // fallback without erasing the browser-native channel diagnosis.\n let adapter: unknown;\n try {\n adapter = await ambient.requestAdapter(opts as GPURequestAdapterOptions | undefined);\n } catch (cause) {\n return requestAdapterFailed(cause);\n }\n if (adapter === null) {\n return adapterUnavailable();\n }\n return ok(\n makeRhiAdapter(\n adapter as unknown as {\n readonly features?: GPUSupportedFeatures | undefined;\n readonly limits?: GPUSupportedLimits | undefined;\n // forgeax-async-whitelist: dom-native — spec `GPUAdapter.requestDevice()` cast\n requestDevice(descriptor?: GPUDeviceDescriptor | undefined): Promise<unknown>;\n },\n ),\n );\n}\n\n/**\n * Acquire a canvas rendering context from an HTMLCanvasElement (M3 / w15).\n *\n * Spec anchor: W3C WebGPU §3.3 GPUCanvasContext.\n *\n * Internally calls `canvas.getContext('webgpu')` and wraps the result as a\n * branded RhiCanvasContext. Returns `Result<RhiCanvasContext, RhiError>` —\n * canvas does not support WebGPU returns `RhiError { code: 'rhi-not-available' }`\n * with a precise `.hint` so AI users can display a degradation banner (charter\n * proposition 4 explicit failure).\n *\n * This replaces the legacy `createCanvasContext(rawCtx)` — AGENTS.md §Change stance\n * authorizes the breaking rename (acquireCanvasContext, optimal > compatible).\n *\n * @example\n * const ctxResult = acquireCanvasContext(canvas);\n * if (!ctxResult.ok) {\n * // canvas does not support WebGPU\n * return;\n * }\n * const canvasContext = ctxResult.value;\n * canvasContext.configure({ device, format: 'bgra8unorm', usage: 0x10 });\n */\nexport function acquireCanvasContext(\n canvas: HTMLCanvasElement | OffscreenCanvas,\n): Result<RhiCanvasContext, RhiError> {\n let rawContext: GPUCanvasContext | null;\n try {\n rawContext = canvas.getContext('webgpu') as GPUCanvasContext | null;\n } catch {\n rawContext = null;\n }\n if (rawContext === null) {\n return err(\n new RhiErrorClass({\n code: 'rhi-not-available',\n expected: 'canvas.getContext(\"webgpu\") to return a non-null GPUCanvasContext',\n hint: 'canvas does not support WebGPU — pass an HTMLCanvasElement (or OffscreenCanvas) whose getContext(\"webgpu\") returns a valid GPUCanvasContext',\n }),\n );\n }\n return ok(makeCanvasContext(rawContext));\n}\n\n/**\n * The `rhi` singleton entry (charter proposition 1: progressive disclosure +\n * plan-strategy §7.4 discoverability:\n * 'import { rhi } from @forgeax/engine-rhi-webgpu' + 'Engine.create({ rhi, canvas })'\n * injection shape).\n *\n * Strict two-step path (M3 break-point #2 + M6 fix-up [w51]; K-5 + K-6):\n * `rhi.requestAdapter(opts) -> adapter.requestDevice(opts)`\n *\n * The legacy single-step `rhi.requestDevice(opts)` factory was retired here\n * (AGENTS.md break-point list 2026-05-10 #2). AI users follow the spec\n * idiom (charter proposition 5 consistent abstraction red line):\n * const adapter = (await rhi.requestAdapter()).unwrap();\n * const device = (await adapter.requestDevice(opts)).unwrap();\n */\nexport const rhi: RhiInstance & {\n createShaderModule: typeof createShaderModule;\n createShaderModuleImmediate: typeof createShaderModuleImmediate;\n acquireCanvasContext: typeof acquireCanvasContext;\n} = {\n requestAdapter,\n createShaderModule,\n createShaderModuleImmediate,\n acquireCanvasContext,\n};\n\n// Re-export public types so callers consume them through a single entry\n// (charter proposition 1: progressive disclosure / single import surfaces\n// the full RHI consumption chain). Round 3 fix-up F-P2-1: extended from\n// 3 to the full set so AI users do not need a transitive\n// `import { RhiAdapter, ... } from '@forgeax/engine-rhi'` alongside the\n// rhi-webgpu singleton.\nexport type {\n // 14 opaque handles (charter proposition 5 consistent abstraction:\n // brand-only surface; AI users hold these for cross-call resource flow).\n BindGroup,\n // 14 descriptors (Pick<GPU*Descriptor, ...> mirrors; AI users compose\n // these inline before calling device.createX).\n BindGroupDescriptor,\n BindGroupLayout,\n BindGroupLayoutDescriptor,\n Buffer,\n BufferDescriptor,\n CanvasConfiguration,\n CommandBuffer,\n CommandEncoderDescriptor,\n ComputePassDescriptor,\n ComputePassTimestampWrites,\n ComputePipeline,\n ComputePipelineDescriptor,\n Fence,\n PipelineLayout,\n PipelineLayoutDescriptor,\n QuerySet,\n QuerySetDescriptor,\n RenderPassColorAttachment,\n RenderPassDepthStencilAttachment,\n RenderPassDescriptor,\n RenderPipeline,\n RenderPipelineDescriptor,\n RequestAdapterOptions,\n RequestDeviceOptions as RhiRequestDeviceOptions,\n // Result + error model (RhiError class is exported as a value below).\n Result,\n ResultErr,\n ResultOk,\n // Adapter / Device / Instance / surface (M2-M3 main interfaces).\n RhiAdapter,\n RhiAssetNotRegisteredDetail,\n RhiCanvasContext,\n RhiCaps,\n // Command / pass encoder interfaces (M3-M4).\n RhiCommandEncoder,\n RhiComputePassEncoder,\n RhiDevice,\n RhiError,\n RhiErrorCode,\n RhiErrorDetail,\n RhiFeatures,\n RhiInstance,\n RhiLimits,\n RhiQueue,\n RhiRenderPassEncoder,\n RhiShaderCompileDetail,\n RhiSurface,\n RhiWebgpuRuntimeDetail,\n Sampler,\n SamplerDescriptor,\n ShaderModule,\n Texture,\n TextureDescriptor,\n TextureView,\n TextureViewDescriptor,\n} from '@forgeax/engine-rhi';\n\n// Re-export Result factories + RhiError class as values (the rhi-webgpu\n// top-level surface stays single-import for both type-only and runtime\n// consumption).\nexport { err, ok, RhiError as RhiErrorClass } from '@forgeax/engine-rhi';\n// feat-20260511-rhi-spec-realign-aggressive D-VD2 (Round 2) — re-export the\n// `_internal_getRawDevice` reverse lookup. Re-introduces the M4-removed escape\n// hatch for the sole engine consumer that needs to register the spec\n// `onuncapturederror` listener on the raw GPUDevice:\n// `packages/engine/src/createRenderer.ts`. The listener registration is the\n// only browser-WebGPU path through which `Renderer.onError(err =>\n// switch err.code { case 'oom' | 'internal-error' | 'shader-compile-failed':\n// ... })` can fire (AGENTS.md break-point #4 promise; spec GPUDevice extends\n// EventTarget and exposes `onuncapturederror` as a settable property).\n//\n// AC-08 grep gate (`apps/hello/triangle/scripts/ac-08-grep-gate.mjs`) allows\n// engine-internal usage of `_internal_getRawDevice` through the existing\n// `\\bgetRawDevice\\b` word-boundary allowlist; consumers outside the engine\n// layer remain forbidden (charter proposition 5 consistent abstraction red\n// line: the RHI surface stays brand-only for AI-user-facing code; the reverse\n// lookup is the named single-point escape hatch the engine uses to satisfy\n// spec event-target requirements).\nexport { _internal_getRawDevice } from './device';\n// feat-20260511-rhi-spec-realign-aggressive D-VD2 wire-up: re-export the\n// async-dispatch event translator at the top level so the engine layer\n// (packages/engine/src/createRenderer.ts) can register the spec\n// `device.onuncapturederror` listener + the dual-channel `device.lost`\n// fan-out without reaching into `internal/`. AGENTS.md break-point #4 dispatch\n// path promise: rhi-webgpu/src/internal/error-translation.ts translates\n// GPUUncapturedErrorEvent / GPUDeviceLostInfo to the 17-member RhiErrorCode\n// union; engine.onError captures the dispatch (charter proposition 4\n// explicit failure + proposition 5 consistent abstraction across both\n// browser-direct and rhi-wgpu wasm dual paths).\nexport { translateErrorEventToRhiError } from './internal/error-translation';\n"]}
|