@plasius/gpu-shader 0.1.1 → 0.1.2

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.
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts","../src/contracts.ts","../src/canonical-json.ts","../src/hash.ts","../src/codec/codec.ts","../src/requirements-validation.ts","../src/compatibility.ts","../src/manifest-validation.ts","../src/runtime/trusted-values.ts","../src/runtime/catalog-loader.ts","../src/runtime/profile-preparer.ts","../src/runtime/style-controller.ts"],"sourcesContent":["export * from \"./contracts.js\";\nexport { canonicalizeGpuContract, parseCanonicalJson } from \"./canonical-json.js\";\nexport { asSha256Hex, computeGpuAbiHash, computeSha256, computeShaderManifestCoreSha256 } from \"./hash.js\";\nexport { createGpuRecordCodec } from \"./codec/codec.js\";\nexport { validateModelShaderCompatibility } from \"./compatibility.js\";\nexport { parseGpuInterfaceManifest, parseJsonBytes, parseModelGpuCompatibilityDescriptor, parseShaderStyleProfileManifest, parseShaderVersionManifest, parseShaderVersionManifestCore } from \"./manifest-validation.js\";\nexport { loadShaderStyleProfile } from \"./runtime/catalog-loader.js\";\nexport { prepareStyleProfile } from \"./runtime/profile-preparer.js\";\nexport { activateStyleProfile, createShaderStyleController } from \"./runtime/style-controller.js\";\n","/** Contract version shared by the first reflection-first manifest family. */\nexport const GPU_INTERFACE_MANIFEST_VERSION = \"1.0.0\" as const;\nexport const SHADER_VERSION_MANIFEST_VERSION = \"1.0.0\" as const;\nexport const SHADER_STYLE_PROFILE_MANIFEST_VERSION = \"1.0.0\" as const;\nexport const SHADER_COMPILE_UNIT_VERSION = \"1.0.0\" as const;\nexport const SHADER_VALIDATION_EVIDENCE_VERSION = \"1.0.0\" as const;\nexport const STABLE_WEBGPU_MATRIX_VERSION = \"1.0.0\" as const;\nexport const SHADER_QUALIFICATION_FIXTURE_VERSION = \"1.0.0\" as const;\nexport const SHADER_QUALIFICATION_BUNDLE_VERSION = \"1.0.0\" as const;\n/** Remotely controlled rollout gate owned by the asset service. */\nexport const GPU_SHADER_STORE_FEATURE_FLAG = \"asset.pipeline.shader-store.enabled\" as const;\n/** User-visible style discovery/selection entitlement owned by the capability service. */\nexport const GPU_SHADER_STYLE_SELECTION_CAPABILITY = \"gpu.shader.style.select\" as const;\n\n/** Lowercase hexadecimal SHA-256 value. Runtime parsers enforce its shape. */\nexport type Sha256Hex = string & { readonly __sha256Hex: unique symbol };\n\n/** Stable universal policies accepted by this contract implementation. */\nexport const SUPPORTED_STABLE_WEBGPU_MATRIX_POLICIES = [\n Object.freeze({\n matrixId: \"stable-webgpu\",\n matrixVersion: \"2026-07-13\",\n matrixSha256: \"4620eca44fd03004ee7650cfe9fcf42934493611a5097da5525f71578980b016\",\n }),\n] as const satisfies readonly {\n readonly matrixId: string;\n readonly matrixVersion: string;\n readonly matrixSha256: string;\n}[];\nObject.freeze(SUPPORTED_STABLE_WEBGPU_MATRIX_POLICIES);\n\n/**\n * Exact additive policies accepted by this release. Empty means supplemental\n * qualification fails closed until reviewed policy bytes and lanes are added.\n */\nexport const SUPPORTED_ADDITIVE_WEBGPU_MATRIX_POLICIES: readonly Readonly<{\n scope: string;\n matrixId: string;\n matrixVersion: string;\n matrixSha256: string;\n}>[] = Object.freeze([]);\n\nexport interface GitObjectId {\n readonly algorithm: \"sha1\" | \"sha256\";\n readonly hex: string;\n}\n\nexport type JsonPrimitive = string | number | boolean | null;\nexport type JsonValue =\n | JsonPrimitive\n | readonly JsonValue[]\n | { readonly [key: string]: JsonValue };\n\nexport type ShaderDiagnosticSeverity = \"error\" | \"warning\" | \"info\";\nexport type ShaderDiagnosticCode =\n | \"invalid-contract\"\n | \"digest-mismatch\"\n | \"model-abi-mismatch\"\n | \"interface-abi-mismatch\"\n | \"shader-abi-mismatch\"\n | \"incompatible-model-interface\"\n | \"missing-semantic\"\n | \"missing-feature\"\n | \"limit-not-met\"\n | \"unsupported-format\"\n | \"unpromoted-asset\"\n | \"compilation-error\"\n | \"pipeline-error\"\n | \"device-lost\"\n | \"activation-error\"\n | \"stale-evidence\"\n | \"incomplete-matrix\"\n | \"uncovered-fragment\"\n | \"timeout\"\n | \"runner-unavailable\"\n | \"adapter-unavailable\";\n\nexport interface ShaderDiagnostic {\n readonly code: ShaderDiagnosticCode;\n readonly severity: ShaderDiagnosticSeverity;\n readonly message: string;\n readonly path?: string;\n readonly expected?: JsonValue;\n readonly actual?: JsonValue;\n}\n\nexport type ShaderResult<T> =\n | { readonly ok: true; readonly value: T }\n | { readonly ok: false; readonly diagnostics: readonly ShaderDiagnostic[] };\n\nexport type GpuScalarKind = \"i32\" | \"u32\" | \"f32\" | \"f16\" | \"bool\";\nexport type GpuHostAddressSpace = \"uniform\" | \"storage\";\nexport type GpuAddressSpace =\n | GpuHostAddressSpace\n | \"function\"\n | \"private\"\n | \"workgroup\";\n\nexport interface GpuScalarLayout {\n readonly kind: \"scalar\";\n readonly scalar: GpuScalarKind;\n readonly alignment: number;\n readonly byteSize: number;\n}\n\nexport interface GpuAtomicLayout {\n readonly kind: \"atomic\";\n readonly scalar: \"i32\" | \"u32\";\n readonly alignment: number;\n readonly byteSize: number;\n}\n\nexport interface GpuVectorLayout {\n readonly kind: \"vector\";\n readonly scalar: GpuScalarKind;\n readonly width: 2 | 3 | 4;\n readonly alignment: number;\n readonly byteSize: number;\n}\n\nexport interface GpuMatrixLayout {\n readonly kind: \"matrix\";\n readonly scalar: \"f32\" | \"f16\";\n readonly columns: 2 | 3 | 4;\n readonly rows: 2 | 3 | 4;\n readonly columnStride: number;\n readonly alignment: number;\n readonly byteSize: number;\n}\n\nexport interface GpuArrayLayout {\n readonly kind: \"array\";\n readonly element: GpuTypeLayout;\n /** Null represents a WGSL runtime-sized array. */\n readonly count: number | null;\n readonly stride: number;\n readonly alignment: number;\n readonly byteSize: number | null;\n}\n\nexport interface GpuRecordReferenceLayout {\n readonly kind: \"record\";\n readonly recordName: string;\n readonly alignment: number;\n readonly byteSize: number | null;\n}\n\nexport type GpuTypeLayout =\n | GpuScalarLayout\n | GpuAtomicLayout\n | GpuVectorLayout\n | GpuMatrixLayout\n | GpuArrayLayout\n | GpuRecordReferenceLayout;\n\nexport interface GpuRecordMemberLayout {\n readonly name: string;\n readonly offset: number;\n /** Effective alignment after applying an optional WGSL `@align`. */\n readonly alignment: number;\n /** Logical size of the value, excluding a member-level `@size`. */\n readonly valueByteSize: number | null;\n /** Occupied member span, including a member-level `@size`. */\n readonly occupiedByteSize: number | null;\n readonly explicitAlign: number | null;\n readonly explicitSize: number | null;\n readonly type: GpuTypeLayout;\n}\n\nexport interface GpuRecordLayout {\n readonly name: string;\n readonly alignment: number;\n /** Null for records ending in a runtime-sized array. */\n readonly byteSize: number | null;\n /** Fixed prefix before any runtime-sized array. */\n readonly minimumByteSize: number;\n readonly runtimeArrayMember: string | null;\n readonly addressSpaces: readonly GpuAddressSpace[];\n /** WGSL declaration order; constructor and codec order depend on it. */\n readonly members: readonly GpuRecordMemberLayout[];\n}\n\nexport type GpuShaderStage = \"vertex\" | \"fragment\" | \"compute\";\nexport type GpuBindingAccess = \"read\" | \"write\" | \"read_write\";\n\nexport type GpuBindingResourceLayout =\n | {\n readonly kind: \"buffer\";\n readonly addressSpace: GpuHostAddressSpace;\n readonly access: GpuBindingAccess;\n readonly recordName: string | null;\n readonly minimumBindingSize: number;\n }\n | {\n readonly kind: \"sampler\";\n readonly samplerType: \"filtering\" | \"non-filtering\" | \"comparison\";\n }\n | {\n readonly kind: \"texture\";\n readonly sampleType: \"float\" | \"unfilterable-float\" | \"depth\" | \"sint\" | \"uint\";\n readonly viewDimension: \"1d\" | \"2d\" | \"2d-array\" | \"cube\" | \"cube-array\" | \"3d\";\n readonly multisampled: boolean;\n }\n | {\n readonly kind: \"storage-texture\";\n readonly access: \"write-only\" | \"read-only\" | \"read-write\";\n readonly format: string;\n readonly viewDimension: \"1d\" | \"2d\" | \"2d-array\" | \"3d\";\n }\n | { readonly kind: \"external-texture\" };\n\nexport interface GpuBindingLayout {\n readonly moduleId: string;\n readonly variableName: string;\n readonly group: number;\n readonly binding: number;\n readonly resource: GpuBindingResourceLayout;\n readonly visibility: readonly GpuShaderStage[];\n}\n\nexport interface GpuEntryPointIo {\n readonly name: string;\n readonly locationKind: \"location\" | \"builtin\";\n readonly location: number | string;\n readonly interpolation: string | null;\n readonly type: GpuTypeLayout;\n}\n\nexport type GpuWorkgroupDimension =\n | { readonly kind: \"literal\"; readonly value: number }\n | { readonly kind: \"override\"; readonly name: string };\n\nexport interface GpuEntryPointInterface {\n readonly moduleId: string;\n readonly name: string;\n readonly stage: GpuShaderStage;\n readonly inputs: readonly GpuEntryPointIo[];\n readonly outputs: readonly GpuEntryPointIo[];\n readonly bindingKeys: readonly string[];\n readonly overrideNames: readonly string[];\n readonly workgroupSize: readonly [\n GpuWorkgroupDimension,\n GpuWorkgroupDimension,\n GpuWorkgroupDimension,\n ] | null;\n /**\n * WebGPU workgroup-storage bytes statically used by a compute entry point.\n * This is null for non-compute entry points.\n */\n readonly workgroupStorageSize: number | null;\n}\n\nexport interface GpuVertexInputLayout {\n readonly pipelineId: string;\n readonly moduleId: string;\n readonly entryPoint: string;\n readonly shaderLocation: number;\n readonly shaderType: GpuTypeLayout;\n readonly bufferSlot: number;\n readonly format: string;\n readonly offset: number;\n readonly arrayStride: number;\n readonly stepMode: \"vertex\" | \"instance\";\n readonly semantic: string | null;\n}\n\n/** Shader-independent vertex bytes consumed from a model buffer. */\nexport interface GpuModelVertexInputLayout {\n readonly source: {\n readonly pipelineId: string;\n readonly shaderLocation: number;\n };\n readonly format: string;\n readonly offset: number;\n readonly arrayStride: number;\n readonly stepMode: \"vertex\" | \"instance\";\n readonly semantic: string;\n}\n\n/** A reflected model-facing resource projection; shader coordinates and visibility are excluded. */\nexport interface GpuModelBindingLayout {\n readonly source: {\n readonly moduleId: string;\n readonly group: number;\n readonly binding: number;\n };\n readonly resource: GpuBindingResourceLayout;\n readonly semantic: string | null;\n}\n\nexport interface GpuOverrideLayout {\n readonly moduleId: string;\n readonly name: string;\n readonly id: number | null;\n readonly type: \"bool\" | \"i32\" | \"u32\" | \"f32\" | \"f16\";\n readonly defaultValue: boolean | number | null;\n}\n\nexport type GpuSemanticSource =\n | {\n readonly kind: \"record-member\";\n readonly recordName: string;\n readonly memberPath: readonly string[];\n }\n | {\n readonly kind: \"vertex-attribute\";\n readonly pipelineId: string;\n readonly shaderLocation: number;\n }\n | {\n readonly kind: \"binding\";\n readonly moduleId: string;\n readonly group: number;\n readonly binding: number;\n };\n\nexport interface GpuSemanticProjection {\n readonly semantic: string;\n readonly source: GpuSemanticSource;\n}\n\nexport interface GpuModelAbiProjection {\n readonly recordNames: readonly string[];\n readonly bindings: readonly GpuModelBindingLayout[];\n readonly vertexInputs: readonly GpuModelVertexInputLayout[];\n readonly semantics: readonly GpuSemanticProjection[];\n}\n\nexport interface GpuInterfaceManifest {\n readonly contractVersion: typeof GPU_INTERFACE_MANIFEST_VERSION;\n readonly interfaceId: string;\n readonly interfaceVersion: string;\n readonly modules: readonly {\n readonly moduleId: string;\n readonly sha256: Sha256Hex;\n }[];\n readonly records: readonly GpuRecordLayout[];\n readonly bindings: readonly GpuBindingLayout[];\n readonly entryPoints: readonly GpuEntryPointInterface[];\n readonly vertexInputs: readonly GpuVertexInputLayout[];\n readonly overrides: readonly GpuOverrideLayout[];\n readonly modelAbi: GpuModelAbiProjection;\n readonly modelAbiHash: Sha256Hex;\n readonly interfaceAbiHash: Sha256Hex;\n readonly generatedBy: {\n readonly packageVersion: string;\n readonly reflector: \"wgsl_reflect\";\n readonly reflectorVersion: \"1.5.0\";\n };\n}\n\nexport interface GpuInterfaceRef {\n readonly interfaceId: string;\n readonly interfaceVersion: string;\n readonly manifestUri: string;\n readonly manifestSha256: Sha256Hex;\n readonly interfaceAbiHash: Sha256Hex;\n readonly modelAbiHash: Sha256Hex;\n}\n\nexport interface ShaderVersionRef {\n readonly shaderId: string;\n readonly version: string;\n readonly manifestUri: string;\n readonly manifestSha256: Sha256Hex;\n}\n\nexport interface ShaderStyleProfileRef {\n readonly profileId: string;\n readonly version: string;\n readonly manifestUri: string;\n readonly manifestSha256: Sha256Hex;\n}\n\nexport interface SerializableGpuProgrammableStage {\n readonly moduleId: string;\n readonly entryPoint: string;\n readonly constants: Readonly<Record<string, boolean | number>>;\n}\n\nexport interface SerializableGpuBindGroupLayout {\n readonly group: number;\n readonly entries: readonly Omit<GpuBindingLayout, \"moduleId\" | \"variableName\">[];\n}\n\nexport interface SerializableGpuPipelineLayout {\n readonly bindGroups: readonly SerializableGpuBindGroupLayout[];\n}\n\nexport interface SerializableGpuComputePipelineDescriptor {\n readonly kind: \"compute\";\n readonly pipelineId: string;\n readonly layout: SerializableGpuPipelineLayout;\n readonly compute: SerializableGpuProgrammableStage;\n}\n\nexport interface SerializableGpuRenderPipelineDescriptor {\n readonly kind: \"render\";\n readonly pipelineId: string;\n readonly layout: SerializableGpuPipelineLayout;\n readonly vertex: SerializableGpuProgrammableStage;\n readonly fragment: SerializableGpuProgrammableStage | null;\n readonly vertexBuffers: readonly {\n readonly arrayStride: number;\n readonly stepMode: \"vertex\" | \"instance\";\n readonly attributes: readonly {\n readonly format: string;\n readonly offset: number;\n readonly shaderLocation: number;\n readonly semantic: string | null;\n }[];\n }[];\n readonly primitive: {\n readonly topology: \"point-list\" | \"line-list\" | \"line-strip\" | \"triangle-list\" | \"triangle-strip\";\n readonly stripIndexFormat: \"uint16\" | \"uint32\" | null;\n readonly frontFace: \"ccw\" | \"cw\";\n readonly cullMode: \"none\" | \"front\" | \"back\";\n readonly unclippedDepth: boolean;\n };\n readonly colorTargets: readonly {\n readonly format: string;\n readonly blend: {\n readonly color: SerializableGpuBlendComponent;\n readonly alpha: SerializableGpuBlendComponent;\n } | null;\n readonly writeMask: number;\n }[];\n readonly depthStencil: {\n readonly format: string;\n readonly depthWriteEnabled: boolean;\n readonly depthCompare: GpuCompareFunction;\n readonly stencilFront: SerializableGpuStencilFaceState;\n readonly stencilBack: SerializableGpuStencilFaceState;\n readonly stencilReadMask: number;\n readonly stencilWriteMask: number;\n readonly depthBias: number;\n readonly depthBiasSlopeScale: number;\n readonly depthBiasClamp: number;\n } | null;\n readonly multisample: {\n readonly count: 1 | 4;\n readonly mask: number;\n readonly alphaToCoverageEnabled: boolean;\n };\n}\n\nexport type GpuCompareFunction = \"never\" | \"less\" | \"equal\" | \"less-equal\" | \"greater\" | \"not-equal\" | \"greater-equal\" | \"always\";\n\nexport interface SerializableGpuBlendComponent {\n readonly operation: \"add\" | \"subtract\" | \"reverse-subtract\" | \"min\" | \"max\";\n readonly srcFactor: \"zero\" | \"one\" | \"src\" | \"one-minus-src\" | \"src-alpha\" | \"one-minus-src-alpha\" | \"dst\" | \"one-minus-dst\" | \"dst-alpha\" | \"one-minus-dst-alpha\" | \"src-alpha-saturated\" | \"constant\" | \"one-minus-constant\";\n readonly dstFactor: \"zero\" | \"one\" | \"src\" | \"one-minus-src\" | \"src-alpha\" | \"one-minus-src-alpha\" | \"dst\" | \"one-minus-dst\" | \"dst-alpha\" | \"one-minus-dst-alpha\" | \"src-alpha-saturated\" | \"constant\" | \"one-minus-constant\";\n}\n\nexport interface SerializableGpuStencilFaceState {\n readonly compare: GpuCompareFunction;\n readonly failOp: \"keep\" | \"zero\" | \"replace\" | \"invert\" | \"increment-clamp\" | \"decrement-clamp\" | \"increment-wrap\" | \"decrement-wrap\";\n readonly depthFailOp: \"keep\" | \"zero\" | \"replace\" | \"invert\" | \"increment-clamp\" | \"decrement-clamp\" | \"increment-wrap\" | \"decrement-wrap\";\n readonly passOp: \"keep\" | \"zero\" | \"replace\" | \"invert\" | \"increment-clamp\" | \"decrement-clamp\" | \"increment-wrap\" | \"decrement-wrap\";\n}\n\nexport type SerializableGpuPipelineDescriptor =\n | SerializableGpuComputePipelineDescriptor\n | SerializableGpuRenderPipelineDescriptor;\n\nexport interface GpuLimitRequirement {\n readonly name: string;\n readonly comparator: \"at-least\" | \"at-most\";\n readonly value: number;\n}\n\nexport interface ShaderRequirements {\n readonly semantics: readonly string[];\n readonly features: readonly string[];\n readonly limits: readonly GpuLimitRequirement[];\n readonly formats: readonly string[];\n}\n\nexport type ShaderRenderRole =\n | \"material\"\n | \"lighting\"\n | \"outline\"\n | \"shadow\"\n | \"post-processing\";\n\nexport interface ShaderValidationEvidenceRef {\n readonly evidenceId: string;\n readonly uri: string;\n readonly sha256: Sha256Hex;\n readonly matrixId: string;\n readonly matrixVersion: string;\n /** Digest of the exact versioned matrix-policy bytes used to produce the evidence. */\n readonly matrixSha256: Sha256Hex;\n /** Exact external GitHub build-provenance reference artifact for the evidence bytes. */\n readonly attestationRef: {\n readonly uri: string;\n readonly sha256: Sha256Hex;\n };\n}\n\n/** Additional qualification required beyond the stable universal matrix. */\nexport interface ScopedShaderValidationEvidenceRef {\n /** Stable, profile-selectable scope such as `xr`; `universal` is reserved. */\n readonly scope: string;\n readonly evidence: ShaderValidationEvidenceRef;\n}\n\n/** Exact supplemental matrix policy a style profile requires for every role. */\nexport interface ShaderValidationScopeRequirement {\n /** Stable policy scope such as `xr`; `universal` is reserved. */\n readonly scope: string;\n readonly matrixId: string;\n readonly matrixVersion: string;\n readonly matrixSha256: Sha256Hex;\n}\n\nexport interface ShaderVersionManifest {\n readonly contractVersion: typeof SHADER_VERSION_MANIFEST_VERSION;\n readonly shaderId: string;\n readonly version: string;\n readonly modules: readonly {\n readonly moduleId: string;\n readonly uri: string;\n readonly byteLength: number;\n readonly sha256: Sha256Hex;\n readonly contentType: \"text/wgsl; charset=utf-8\";\n }[];\n readonly gpuInterface: GpuInterfaceRef;\n readonly pipelines: readonly SerializableGpuPipelineDescriptor[];\n readonly renderRoles: readonly {\n readonly role: ShaderRenderRole;\n readonly pipelineIds: readonly string[];\n }[];\n readonly compatibleModelInterfaces: readonly {\n readonly interfaceId: string;\n readonly interfaceVersion: string;\n readonly manifestSha256: Sha256Hex;\n readonly interfaceAbiHash: Sha256Hex;\n readonly modelAbiHash: Sha256Hex;\n }[];\n readonly requirements: ShaderRequirements;\n readonly shaderAbiHash: Sha256Hex;\n /** Passing evidence for the universal stable-WebGPU matrix. */\n readonly validationEvidence: ShaderValidationEvidenceRef;\n /** Passing evidence for additive matrices, for example XR device lanes. */\n readonly additionalValidationEvidence: readonly ScopedShaderValidationEvidenceRef[];\n}\n\n/** Immutable shader manifest fields qualified before external evidence is attached. */\nexport type ShaderVersionManifestCore = Omit<ShaderVersionManifest, \"validationEvidence\" | \"additionalValidationEvidence\">;\n\nexport interface ShaderStyleRoleBinding {\n readonly role: ShaderRenderRole;\n readonly shader: ShaderVersionRef;\n}\n\nexport interface ShaderStyleProfileManifest {\n readonly contractVersion: typeof SHADER_STYLE_PROFILE_MANIFEST_VERSION;\n readonly profileId: string;\n readonly version: string;\n readonly style: string;\n readonly roles: readonly ShaderStyleRoleBinding[];\n readonly compatibleModelInterfaces: readonly {\n readonly interfaceId: string;\n readonly interfaceVersion: string;\n readonly manifestSha256: Sha256Hex;\n readonly interfaceAbiHash: Sha256Hex;\n readonly modelAbiHash: Sha256Hex;\n }[];\n readonly requiredSemantics: readonly string[];\n /** Exact supplemental matrix policies every referenced shader must provide. */\n readonly requiredValidationScopes: readonly ShaderValidationScopeRequirement[];\n}\n\nexport interface ModelGpuCompatibilityDescriptor {\n readonly modelId: string;\n readonly version: string;\n readonly gpuInterface: GpuInterfaceRef;\n readonly modelAbiHash: Sha256Hex;\n readonly providedSemantics: readonly string[];\n readonly defaultStyleProfile: ShaderStyleProfileRef | null;\n}\n\nexport interface GpuCapabilitySnapshot {\n readonly features: readonly string[];\n readonly limits: Readonly<Record<string, number>>;\n readonly formats: readonly string[];\n}\n\nexport interface ModelShaderCompatibility {\n readonly modelAbiHash: Sha256Hex;\n readonly shaderAbiHash: Sha256Hex;\n readonly matchedInterfaceId: string;\n}\n\nexport type GpuScalarValue = number;\nexport type GpuVectorValue = readonly number[];\nexport type GpuMatrixValue = readonly (readonly number[])[];\nexport type GpuRecordValue = Readonly<Record<string, unknown>>;\n\nexport interface GpuRecordCodec<T = GpuRecordValue> {\n readonly record: GpuRecordLayout;\n readonly minimumByteLength: number;\n byteLength(value: T): number;\n encode(value: T): ArrayBuffer;\n encodeInto(\n value: T,\n destination: ArrayBuffer | ArrayBufferView,\n byteOffset?: number,\n ): number;\n decode(\n source: ArrayBuffer | ArrayBufferView,\n options?: { readonly byteOffset?: number; readonly byteLength?: number },\n ): T;\n}\n\nexport interface PromotedShaderCatalogResolver {\n /** Must prove the URI belongs to the configured promoted catalog root and exact immutable identity. */\n isCatalogAssetUri(uri: string): boolean;\n loadProfile(\n ref: ShaderStyleProfileRef,\n signal?: AbortSignal,\n ): Promise<{ readonly bytes: Uint8Array; readonly promoted: boolean }>;\n loadShader(\n ref: ShaderVersionRef,\n signal?: AbortSignal,\n ): Promise<{ readonly bytes: Uint8Array; readonly promoted: boolean }>;\n loadInterface(\n ref: GpuInterfaceRef,\n signal?: AbortSignal,\n ): Promise<{ readonly bytes: Uint8Array; readonly promoted: boolean }>;\n loadModule(\n shader: ShaderVersionRef,\n moduleId: string,\n uri: string,\n signal?: AbortSignal,\n ): Promise<{ readonly bytes: Uint8Array; readonly promoted: boolean }>;\n}\n\nexport interface LoadedShaderVersion {\n readonly ref: ShaderVersionRef;\n readonly manifest: ShaderVersionManifest;\n readonly gpuInterface: GpuInterfaceManifest;\n readonly modules: ReadonlyMap<string, Uint8Array>;\n}\n\nexport interface LoadedShaderStyleProfile {\n readonly ref: ShaderStyleProfileRef;\n readonly manifest: ShaderStyleProfileManifest;\n readonly shaders: ReadonlyMap<ShaderRenderRole, LoadedShaderVersion>;\n}\n\nexport interface GpuCompilationMessageLike {\n readonly type: \"error\" | \"warning\" | \"info\";\n readonly message: string;\n readonly lineNum?: number;\n readonly linePos?: number;\n}\n\nexport interface GpuShaderModuleLike {\n getCompilationInfo(): Promise<{ readonly messages: readonly GpuCompilationMessageLike[] }>;\n}\n\nexport interface GpuDeviceLike {\n readonly features: Iterable<string>;\n readonly limits: Readonly<Record<string, number>>;\n readonly lost?: Promise<{ readonly reason?: string; readonly message?: string }>;\n createShaderModule(descriptor: { readonly label?: string; readonly code: string }): GpuShaderModuleLike;\n createBindGroupLayout(descriptor: unknown): unknown;\n createPipelineLayout(descriptor: { readonly bindGroupLayouts: readonly unknown[] }): unknown;\n createComputePipelineAsync?(descriptor: unknown): Promise<unknown>;\n createRenderPipelineAsync?(descriptor: unknown): Promise<unknown>;\n createComputePipeline?(descriptor: unknown): unknown;\n createRenderPipeline?(descriptor: unknown): unknown;\n pushErrorScope?(filter: \"validation\"): void;\n popErrorScope?(): Promise<{ readonly message?: string } | null>;\n}\n\nexport interface PreparedShaderStyleProfile {\n readonly loaded: LoadedShaderStyleProfile;\n readonly pipelines: ReadonlyMap<string, unknown>;\n readonly preparedAt: number;\n dispose(): void;\n}\n\nexport interface ActiveShaderStyleProfile {\n readonly prepared: PreparedShaderStyleProfile;\n readonly activatedAt: number;\n}\n\nexport interface FrameBoundaryScheduler {\n schedule(operation: () => void): Promise<void>;\n}\n\nexport interface ShaderStyleController {\n readonly current: ActiveShaderStyleProfile | null;\n}\n\nexport interface AssembledWgslModule {\n readonly moduleId: string;\n readonly source: string;\n}\n\nexport type GpuSemanticSelector = GpuSemanticProjection;\n\n/** Selects a reflected binding. Callers cannot supply its resource layout. */\nexport interface GpuModelBindingSelector {\n readonly moduleId: string;\n readonly group: number;\n readonly binding: number;\n readonly semantic?: string | null;\n}\n\nexport interface ReflectGpuInterfaceInput {\n readonly interfaceId: string;\n readonly interfaceVersion: string;\n readonly modules: readonly AssembledWgslModule[];\n readonly pipelines: readonly SerializableGpuPipelineDescriptor[];\n readonly modelFacingRecordNames: readonly string[];\n readonly modelFacingBindings: readonly GpuModelBindingSelector[];\n readonly semantics: readonly GpuSemanticSelector[];\n}\n\nexport interface GeneratedGpuInterfaceArtifacts {\n readonly manifestJson: string;\n readonly jsonSchemas: string;\n readonly typescriptTypes: string;\n readonly byteConstants: string;\n readonly codecs: string;\n}\n\nexport interface ShaderCompileUnitManifest {\n readonly contractVersion: typeof SHADER_COMPILE_UNIT_VERSION;\n readonly compileUnitId: string;\n readonly fragmentIds: readonly string[];\n readonly modules: readonly {\n readonly moduleId: string;\n readonly sha256: Sha256Hex;\n readonly assembly: {\n /** UTF-8 fragment bytes joined by one LF byte, with no executable transforms. */\n readonly kind: \"concat-v1\";\n readonly fragmentIds: readonly string[];\n };\n }[];\n readonly entryPoints: readonly {\n readonly moduleId: string;\n readonly name: string;\n readonly stage: GpuShaderStage;\n }[];\n readonly pipelines: readonly SerializableGpuPipelineDescriptor[];\n readonly interfaceRef: GpuInterfaceRef;\n readonly overrideValues: Readonly<Record<string, boolean | number>>;\n readonly qualificationFixture: {\n readonly fixtureId: string;\n readonly path: string;\n readonly sha256: Sha256Hex;\n };\n}\n\nexport interface ShaderCompileUnitInventory {\n readonly contractVersion: typeof SHADER_COMPILE_UNIT_VERSION;\n readonly fragments: readonly {\n readonly fragmentId: string;\n readonly path: string;\n readonly sha256: Sha256Hex;\n }[];\n readonly compileUnits: readonly ShaderCompileUnitManifest[];\n}\n\nexport type ShaderMatrixBrowserName = \"chromium\" | \"chrome\" | \"edge\" | \"firefox\" | \"safari\";\nexport type ShaderMatrixOsName =\n | \"ubuntu\"\n | \"windows\"\n | \"macos\"\n | \"chromeos\"\n | \"android\"\n | \"ios\"\n | \"ipados\"\n | \"visionos\";\n\nexport interface StableWebGpuMatrixCell {\n readonly cellId: string;\n readonly runnerLabels: readonly string[];\n readonly browser: {\n readonly name: ShaderMatrixBrowserName;\n readonly channel: \"stable\" | \"playwright-bundled\";\n };\n readonly os: {\n readonly name: ShaderMatrixOsName;\n readonly versionRequirement:\n | { readonly kind: \"exact\"; readonly value: string }\n | { readonly kind: \"major\"; readonly value: number }\n | { readonly kind: \"minimum-major\"; readonly value: number }\n | { readonly kind: \"stable-channel\"; readonly channel: \"stable\" };\n readonly architecture: \"x64\" | \"arm64\";\n };\n readonly adapter: {\n readonly kind: \"software\" | \"physical\";\n readonly vendor: string;\n readonly family: string;\n readonly backend: \"swiftshader\" | \"d3d12\" | \"metal\" | \"vulkan\";\n };\n readonly automation: {\n readonly kind: \"playwright\" | \"webdriver\" | \"device-farm\" | \"safari-webdriver\";\n };\n readonly timeoutMs: number;\n readonly blocking: boolean;\n readonly countsTowardStableCoverage: boolean;\n}\n\nexport interface StableWebGpuMatrixManifest {\n readonly contractVersion: typeof STABLE_WEBGPU_MATRIX_VERSION;\n readonly matrixId: string;\n readonly version: string;\n readonly policy: {\n readonly coverage: \"all-cells-required\";\n readonly unavailable: \"fail\";\n readonly skipped: \"fail\";\n readonly timeout: \"fail\";\n readonly deviceLoss: \"fail\";\n readonly requiredPhysicalCellCount: 15;\n readonly requiredBlockingCellCount: 16;\n };\n readonly cells: readonly StableWebGpuMatrixCell[];\n}\n\nexport type ShaderQualificationStatus =\n | \"passed\"\n | \"failed\"\n | \"skipped\"\n | \"timeout\"\n | \"device-lost\"\n | \"runner-unavailable\"\n | \"adapter-unavailable\";\n\nexport type ShaderQualificationPhaseName =\n | \"assembly\"\n | \"reflection-schema\"\n | \"shader-compilation\"\n | \"pipeline-layout\"\n | \"pipeline-creation\"\n | \"bind-group-creation\"\n | \"cpu-to-gpu-layout\"\n | \"gpu-to-cpu-layout\"\n | \"bounded-execution\"\n | \"semantic-readback\";\n\nexport type ShaderQualificationPhaseEvidence =\n | {\n readonly name: Exclude<ShaderQualificationPhaseName, \"shader-compilation\" | \"semantic-readback\">;\n readonly status: \"passed\" | \"failed\";\n readonly durationMs: number;\n readonly evidenceSha256: Sha256Hex;\n }\n | {\n readonly name: \"shader-compilation\";\n readonly status: \"passed\" | \"failed\";\n readonly durationMs: number;\n readonly compilationMessagesSha256: Sha256Hex;\n readonly errorCount: number;\n }\n | {\n readonly name: \"semantic-readback\";\n readonly status: \"passed\" | \"failed\";\n readonly durationMs: number;\n readonly expectedSha256: Sha256Hex;\n readonly actualSha256: Sha256Hex;\n };\n\nexport interface ShaderQualificationResult {\n readonly compileUnitId: string;\n readonly cellId: string;\n readonly status: ShaderQualificationStatus;\n readonly startedAt: string;\n readonly completedAt: string;\n readonly observed: {\n readonly runner: { readonly id: string; readonly labels: readonly string[] };\n readonly os: { readonly name: string; readonly version: string; readonly channel: string | null; readonly architecture: string };\n readonly browser: { readonly name: string; readonly version: string; readonly channel: string };\n readonly adapter: {\n readonly physical: boolean;\n readonly vendor: string;\n readonly family: string;\n readonly architecture: string;\n readonly device: string;\n readonly description: string;\n readonly backend: string;\n readonly driver: string;\n };\n readonly features: readonly string[];\n readonly limits: Readonly<Record<string, number>>;\n };\n readonly phases: readonly ShaderQualificationPhaseEvidence[];\n readonly diagnostics: readonly ShaderDiagnostic[];\n}\n\n/** Candidate claims that can be serialized inside the candidate archive without a self-digest. */\nexport interface ShaderQualificationCandidateSubject {\n /** Digest of the ShaderVersionManifest projection with validationEvidence omitted. */\n readonly shaderManifestCore: {\n readonly shaderId: string;\n readonly version: string;\n readonly sha256: Sha256Hex;\n };\n readonly compileUnitInventorySha256: Sha256Hex;\n readonly shaderAbiHash: Sha256Hex;\n readonly interfaceManifestSha256: Sha256Hex;\n readonly modelAbiHashes: readonly Sha256Hex[];\n readonly modules: readonly { readonly moduleId: string; readonly sha256: Sha256Hex }[];\n readonly requiredCompileUnitIds: readonly string[];\n readonly requiredCellIds: readonly string[];\n}\n\nexport interface ShaderValidationEvidenceSubject extends ShaderQualificationCandidateSubject {\n /** Verified externally over the complete immutable archive; never embedded in that archive. */\n readonly dataBundleSha256: Sha256Hex;\n}\n\nexport interface ShaderTrustedWorkflowProvenance {\n readonly repository: string;\n readonly commit: GitObjectId;\n readonly ref: string;\n readonly workflowRef: string;\n readonly workflowSha: GitObjectId;\n readonly runId: string;\n readonly runAttempt: number;\n readonly job: string;\n readonly eventName: string;\n readonly oidcAttestation: {\n readonly issuer: \"https://token.actions.githubusercontent.com\";\n readonly subject: string;\n readonly audience: string;\n readonly verifiedClaimsSha256: Sha256Hex;\n readonly verifiedAt: string;\n readonly source: \"trusted-runner-preflight\";\n };\n}\n\n/** Identifies the workflow job and runner that produced a qualification-cell artifact. */\nexport interface ShaderQualificationExecutionProducer {\n readonly repository: string;\n readonly commit: GitObjectId;\n readonly ref: string;\n readonly runId: string;\n readonly runAttempt: number;\n readonly job: \"swiftshader\" | \"physical\" | \"physical-runner-preflight\";\n readonly trustedWorkflowRepository: \"Plasius-LTD/gpu-shader\";\n readonly trustedWorkflowRef: string;\n readonly trustedWorkflowSha: GitObjectId;\n readonly runner: {\n readonly name: string;\n readonly environment: \"github-hosted\" | \"self-hosted\" | \"device-farm\";\n readonly os: string;\n readonly architecture: string;\n };\n}\n\nexport interface ShaderValidationEvidence {\n readonly contractVersion: typeof SHADER_VALIDATION_EVIDENCE_VERSION;\n readonly evidenceId: string;\n readonly status: \"passed\" | \"failed\";\n readonly generatedAt: string;\n readonly subjectBindingSha256: Sha256Hex;\n readonly subject: ShaderValidationEvidenceSubject;\n readonly matrixRef: {\n readonly matrixId: string;\n readonly version: string;\n readonly sha256: Sha256Hex;\n };\n readonly toolchain: {\n readonly packageVersion: string;\n readonly reflectorVersion: \"1.5.0\";\n readonly harness: {\n readonly id: string;\n readonly version: string;\n readonly sha256: Sha256Hex;\n };\n };\n readonly qualificationPreflightProvenance: ShaderTrustedWorkflowProvenance;\n readonly counts: {\n readonly compileUnits: number;\n readonly cells: number;\n readonly expectedResults: number;\n readonly passedResults: number;\n };\n readonly cellRuns: readonly ShaderValidationCellRun[];\n readonly results: readonly ShaderQualificationResult[];\n}\n\nexport type ShaderQualificationResource =\n | {\n readonly kind: \"buffer\";\n readonly resourceId: string;\n readonly byteLength: number;\n readonly usage: readonly string[];\n readonly initialData: { readonly path: string; readonly sha256: Sha256Hex } | null;\n }\n | {\n readonly kind: \"texture\";\n readonly resourceId: string;\n readonly dimension: \"1d\" | \"2d\" | \"3d\";\n readonly size: readonly [number, number, number];\n readonly mipLevelCount: number;\n readonly sampleCount: 1 | 4;\n readonly format: string;\n readonly usage: readonly string[];\n readonly initialData: {\n readonly path: string;\n readonly sha256: Sha256Hex;\n readonly bytesPerRow: number;\n readonly rowsPerImage: number;\n readonly mipLevel: number;\n readonly origin: readonly [number, number, number];\n readonly aspect: \"all\" | \"depth-only\" | \"stencil-only\";\n } | null;\n }\n | {\n readonly kind: \"sampler\";\n readonly resourceId: string;\n readonly descriptor: Readonly<Record<string, JsonPrimitive>>;\n };\n\nexport type ShaderQualificationCommand =\n | {\n readonly kind: \"dispatch\";\n readonly pipelineId: string;\n readonly bindGroupIds: readonly string[];\n readonly workgroups: readonly [number, number, number];\n }\n | {\n readonly kind: \"draw\";\n readonly pipelineId: string;\n readonly bindGroupIds: readonly string[];\n readonly vertexBuffers: readonly {\n readonly slot: number;\n readonly resourceId: string;\n readonly offset: number;\n readonly size: number;\n }[];\n readonly colorAttachments: readonly {\n readonly resourceId: string;\n readonly view: ShaderQualificationTextureViewDescriptor;\n readonly clearValue: readonly [number, number, number, number];\n readonly loadOp: \"clear\" | \"load\";\n readonly storeOp: \"store\" | \"discard\";\n }[];\n readonly depthStencilAttachment: {\n readonly resourceId: string;\n readonly view: ShaderQualificationTextureViewDescriptor;\n readonly depthClearValue: number;\n readonly depthLoadOp: \"clear\" | \"load\";\n readonly depthStoreOp: \"store\" | \"discard\";\n readonly stencilClearValue: number;\n readonly stencilLoadOp: \"clear\" | \"load\" | null;\n readonly stencilStoreOp: \"store\" | \"discard\" | null;\n } | null;\n readonly vertexCount: number;\n readonly instanceCount: number;\n readonly firstVertex: number;\n readonly firstInstance: number;\n }\n | {\n readonly kind: \"copy-buffer\";\n readonly source: string;\n readonly destination: string;\n readonly byteLength: number;\n }\n | {\n readonly kind: \"copy-texture-to-buffer\";\n readonly source: {\n readonly resourceId: string;\n readonly mipLevel: number;\n readonly origin: readonly [number, number, number];\n readonly aspect: \"all\" | \"depth-only\" | \"stencil-only\";\n };\n readonly destination: {\n readonly resourceId: string;\n readonly offset: number;\n readonly bytesPerRow: number;\n readonly rowsPerImage: number;\n };\n readonly extent: readonly [number, number, number];\n };\n\nexport interface ShaderQualificationTextureViewDescriptor {\n readonly format: string | null;\n readonly dimension: \"1d\" | \"2d\" | \"2d-array\" | \"cube\" | \"cube-array\" | \"3d\" | null;\n readonly aspect: \"all\" | \"depth-only\" | \"stencil-only\";\n readonly baseMipLevel: number;\n readonly mipLevelCount: number | null;\n readonly baseArrayLayer: number;\n readonly arrayLayerCount: number | null;\n}\n\nexport type ShaderQualificationBindGroupResource =\n | { readonly kind: \"buffer\"; readonly resourceId: string; readonly offset: number; readonly size: number }\n | { readonly kind: \"texture-view\"; readonly resourceId: string; readonly view: ShaderQualificationTextureViewDescriptor }\n | { readonly kind: \"sampler\"; readonly resourceId: string };\n\n/** A declarative host-codec ↔ final-WGSL record-layout probe. */\nexport interface ShaderQualificationBufferRecordLayoutProbe {\n readonly kind: \"buffer-record\";\n readonly probeId: string;\n readonly source: {\n readonly moduleId: string;\n readonly group: number;\n readonly binding: number;\n readonly recordName: string;\n };\n readonly pipelineId: string;\n readonly commandIndex: number;\n readonly input: {\n readonly resourceId: string;\n readonly byteOffset: number;\n readonly byteLength: number;\n /** Encoded with createGpuRecordCodec and compared byte-for-byte with admitted initialData. */\n readonly value: JsonValue;\n };\n readonly output: {\n readonly readbackIndex: number;\n readonly recordName: string;\n /** GPU output is decoded with the reflected codec and compared to this value. */\n readonly expectedValue: JsonValue;\n };\n}\n\n/** A declarative host vertex-format encoder ↔ final-WGSL vertex-fetch probe. */\nexport interface ShaderQualificationVertexInputLayoutProbe {\n readonly kind: \"vertex-input\";\n readonly probeId: string;\n readonly source: {\n readonly pipelineId: string;\n readonly shaderLocation: number;\n readonly semantic: string;\n };\n readonly commandIndex: number;\n readonly input: {\n readonly resourceId: string;\n readonly vertexBufferSlot: number;\n /** Absolute vertex or instance element selected by the draw command. */\n readonly elementIndex: number;\n /** Encoded from the reflected GPUVertexFormat and compared with admitted bytes. */\n readonly value: JsonValue;\n };\n readonly output: {\n readonly readbackIndex: number;\n readonly recordName: string;\n /** GPU-observed vertex value encoded through this reflected output record. */\n readonly expectedValue: JsonValue;\n };\n}\n\nexport type ShaderQualificationLayoutProbe =\n | ShaderQualificationBufferRecordLayoutProbe\n | ShaderQualificationVertexInputLayoutProbe;\n\nexport interface ShaderQualificationFixtureManifest {\n readonly contractVersion: typeof SHADER_QUALIFICATION_FIXTURE_VERSION;\n readonly fixtureId: string;\n readonly resources: readonly ShaderQualificationResource[];\n readonly bindGroups: readonly {\n readonly bindGroupId: string;\n readonly group: number;\n readonly entries: readonly { readonly binding: number; readonly resource: ShaderQualificationBindGroupResource }[];\n }[];\n readonly commands: readonly ShaderQualificationCommand[];\n readonly layoutProbes: readonly ShaderQualificationLayoutProbe[];\n readonly readbacks: readonly {\n readonly resourceId: string;\n readonly byteOffset: number;\n readonly byteLength: number;\n readonly expectedSha256: Sha256Hex;\n }[];\n readonly bounds: {\n readonly maxBufferBytes: number;\n readonly maxTextureTexels: number;\n readonly maxCommands: number;\n readonly timeoutMs: number;\n };\n}\n\nexport interface ShaderQualificationBundleManifest {\n readonly contractVersion: typeof SHADER_QUALIFICATION_BUNDLE_VERSION;\n readonly inventory: ShaderCompileUnitInventory;\n readonly subject: ShaderQualificationCandidateSubject;\n readonly shaderManifestCorePath: string;\n readonly gpuInterfaceManifest: { readonly path: string; readonly sha256: Sha256Hex };\n readonly modelCompatibilityFixtures: readonly {\n readonly fixtureId: string;\n readonly path: string;\n readonly sha256: Sha256Hex;\n }[];\n readonly modules: readonly { readonly moduleId: string; readonly path: string; readonly sha256: Sha256Hex }[];\n readonly fixtures: readonly {\n readonly fixtureId: string;\n readonly path: string;\n readonly sha256: Sha256Hex;\n readonly kind: \"qualification-fixture\";\n }[];\n}\n\nexport interface ShaderQualificationModelCompatibilityFixture {\n readonly contractVersion: typeof SHADER_QUALIFICATION_FIXTURE_VERSION;\n readonly fixtureId: string;\n readonly model: ModelGpuCompatibilityDescriptor;\n}\n\nexport interface ShaderCellEvidence {\n readonly contractVersion: typeof SHADER_VALIDATION_EVIDENCE_VERSION;\n readonly qualificationId: string;\n readonly matrixId: string;\n readonly matrixVersion: string;\n readonly matrixSha256: Sha256Hex;\n readonly cellId: string;\n readonly dataBundleSha256: Sha256Hex;\n readonly compileUnitInventorySha256: Sha256Hex;\n readonly harness: {\n readonly id: string;\n readonly version: string;\n readonly sha256: Sha256Hex;\n };\n readonly automation: {\n readonly kind: \"playwright\" | \"webdriver\" | \"device-farm\" | \"safari-webdriver\";\n readonly driver: string;\n readonly version: string;\n readonly sha256: Sha256Hex;\n };\n /** `sha256(\"plasius.gpu.qualification-subject/v1\\n\" + canonical(subject,digests))`. */\n readonly subjectBindingSha256: Sha256Hex;\n readonly qualificationPreflightProvenance: ShaderTrustedWorkflowProvenance;\n readonly producer: ShaderQualificationExecutionProducer;\n readonly results: readonly ShaderQualificationResult[];\n}\n\nexport interface ShaderRunnerCellPreflightEvidence {\n readonly contractVersion: typeof SHADER_VALIDATION_EVIDENCE_VERSION;\n readonly kind: \"shader-runner-cell-preflight-evidence\";\n readonly qualificationId: string;\n readonly cellId: string;\n readonly status: \"available\" | \"runner-unavailable\";\n readonly matrixSha256: Sha256Hex;\n readonly runnerLabels: readonly string[];\n /** API-observed self-hosted/device labels, or hosted image labels derived from the actual OS/architecture environment. */\n readonly matchedRunners: readonly {\n readonly name: string;\n readonly labels: readonly string[];\n }[];\n /** Independently verified adapter package/code identity, or null when inventory cannot observe it. */\n readonly adapterHarness: {\n readonly id: string;\n readonly version: string;\n readonly sha256: Sha256Hex;\n } | null;\n readonly qualificationPreflightProvenance: ShaderTrustedWorkflowProvenance;\n readonly producer: ShaderQualificationExecutionProducer;\n}\n\nexport interface ShaderValidationCellRun {\n readonly cellId: string;\n readonly source: \"cell-evidence\" | \"runner-preflight\" | \"workflow-diagnostic\";\n readonly sourceArtifactSha256: Sha256Hex;\n readonly resultsSha256: Sha256Hex;\n readonly qualificationPreflightProvenance: ShaderTrustedWorkflowProvenance;\n readonly producer: ShaderQualificationExecutionProducer;\n readonly harness: {\n readonly id: string;\n readonly version: string;\n readonly sha256: Sha256Hex;\n };\n /** Null when no adapter actually executed (runner-unavailable/workflow diagnostic). */\n readonly automation: {\n readonly kind: \"playwright\" | \"webdriver\" | \"device-farm\" | \"safari-webdriver\";\n readonly driver: string;\n readonly version: string;\n readonly sha256: Sha256Hex;\n } | null;\n readonly resultCount: number;\n readonly status: ShaderQualificationStatus;\n}\n\n/** Non-secret claims emitted by the trusted prepare job after Blob version and OIDC verification. */\nexport interface ShaderQualificationPreflightManifest {\n readonly contractVersion: typeof SHADER_VALIDATION_EVIDENCE_VERSION;\n readonly kind: \"shader-qualification-preflight\";\n readonly qualificationId: string;\n readonly sourceBlob: {\n readonly host: string;\n readonly versionId: string;\n readonly uri: string;\n };\n readonly dataBundleSha256: Sha256Hex;\n readonly compileUnitInventorySha256: Sha256Hex;\n readonly matrixSha256: Sha256Hex;\n readonly harnessSha256: Sha256Hex;\n readonly subjectBindingSha256: Sha256Hex;\n readonly provenance: ShaderTrustedWorkflowProvenance;\n}\n\nexport interface ShaderNonQualifyingWorkflowDiagnostic {\n readonly contractVersion: typeof SHADER_VALIDATION_EVIDENCE_VERSION;\n readonly kind: \"non-qualifying-workflow-diagnostic\";\n readonly qualificationId: string;\n readonly cellId: string;\n readonly status: \"timeout\" | \"failed\";\n readonly matrixSha256: Sha256Hex;\n readonly message: string;\n readonly qualificationPreflightProvenance: ShaderTrustedWorkflowProvenance;\n readonly producer: ShaderQualificationExecutionProducer;\n}\n\n/** External GitHub build-provenance reference; verified outside the evidence JSON digest. */\nexport interface ShaderValidationEvidenceAttestationRef {\n readonly contractVersion: typeof SHADER_VALIDATION_EVIDENCE_VERSION;\n readonly kind: \"shader-validation-evidence-attestation-ref\";\n readonly evidence: { readonly name: string; readonly sha256: Sha256Hex };\n readonly attestation: {\n readonly id: string;\n readonly url: string;\n readonly bundle: { readonly name: string; readonly sha256: Sha256Hex };\n };\n readonly producer: {\n readonly repository: string;\n readonly runId: string;\n readonly runAttempt: number;\n readonly trustedWorkflowRepository: \"Plasius-LTD/gpu-shader\";\n readonly trustedWorkflowRef: string;\n readonly trustedWorkflowSha: GitObjectId;\n };\n}\n\nexport interface ShaderCompileFixture {\n /** Local/hosted testing only. Callback fixtures can never produce trusted physical evidence. */\n readonly qualificationEligible: false;\n readonly fixtureId: string;\n setup(context: ShaderCompileContext): Promise<void>;\n encode(context: ShaderCompileContext): Promise<void>;\n verify(context: ShaderCompileContext): Promise<void>;\n cleanup(context: ShaderCompileContext): Promise<void>;\n}\n\nexport interface ShaderCompileContext {\n readonly device: GpuDeviceLike;\n readonly unit: ShaderCompileUnitManifest;\n readonly modules: ReadonlyMap<string, GpuShaderModuleLike>;\n readonly state: Map<string, unknown>;\n}\n","import type { JsonValue } from \"./contracts.js\";\n\nfunction isPlainObject(value: object): value is Record<string, unknown> {\n const prototype = Object.getPrototypeOf(value);\n return prototype === Object.prototype || prototype === null;\n}\n\nfunction assertUnicodeScalarString(value: string, path: string): void {\n for (let index = 0; index < value.length; index += 1) {\n const code = value.charCodeAt(index);\n if (code >= 0xd800 && code <= 0xdbff) {\n const next = value.charCodeAt(index + 1);\n if (!(next >= 0xdc00 && next <= 0xdfff)) throw new TypeError(`${path} contains an unpaired UTF-16 surrogate.`);\n index += 1;\n } else if (code >= 0xdc00 && code <= 0xdfff) throw new TypeError(`${path} contains an unpaired UTF-16 surrogate.`);\n }\n}\n\n/**\n * Canonicalizes contract data using the JSON Canonicalization Scheme ordering\n * rules. Unsupported JavaScript values are rejected rather than silently lost.\n */\nexport function canonicalizeGpuContract(value: unknown): string {\n const ancestors = new Set<object>();\n\n const visit = (current: unknown, path: string): string => {\n if (current === null) return \"null\";\n if (typeof current === \"string\" || typeof current === \"boolean\") {\n if (typeof current === \"string\") assertUnicodeScalarString(current, path);\n return JSON.stringify(current);\n }\n if (typeof current === \"number\") {\n if (!Number.isFinite(current)) {\n throw new TypeError(`${path} contains a non-finite number.`);\n }\n return Object.is(current, -0) ? \"0\" : JSON.stringify(current);\n }\n if (typeof current !== \"object\") {\n throw new TypeError(`${path} contains a value that JSON cannot represent.`);\n }\n if (ancestors.has(current)) {\n throw new TypeError(`${path} contains a circular reference.`);\n }\n\n ancestors.add(current);\n try {\n if (Array.isArray(current)) {\n return `[${current.map((item, index) => visit(item, `${path}[${index}]`)).join(\",\")}]`;\n }\n if (!isPlainObject(current)) {\n throw new TypeError(`${path} must contain only plain JSON objects.`);\n }\n const keys = Object.keys(current).sort();\n const properties = keys.map((key) => {\n assertUnicodeScalarString(key, `${path} key`);\n const member = current[key];\n if (member === undefined) {\n throw new TypeError(`${path}.${key} is undefined.`);\n }\n return `${JSON.stringify(key)}:${visit(member, `${path}.${key}`)}`;\n });\n return `{${properties.join(\",\")}}`;\n } finally {\n ancestors.delete(current);\n }\n };\n\n return visit(value, \"$root\");\n}\n\n/** Parses and verifies exact JCS canonical JSON while preserving its JSON-only type. */\nexport function parseCanonicalJson(value: string): JsonValue {\n const parsed = JSON.parse(value) as JsonValue;\n if (canonicalizeGpuContract(parsed) !== value) throw new TypeError(\"JSON input is valid but not in canonical form.\");\n return parsed;\n}\n","import { canonicalizeGpuContract } from \"./canonical-json.js\";\nimport type {\n GpuInterfaceManifest,\n SerializableGpuPipelineDescriptor,\n Sha256Hex,\n ShaderRequirements,\n ShaderVersionManifest,\n} from \"./contracts.js\";\n\nconst SHA256_PATTERN = /^[a-f0-9]{64}$/u;\n\nexport function asSha256Hex(value: string): Sha256Hex {\n if (!SHA256_PATTERN.test(value)) {\n throw new TypeError(\"SHA-256 values must be lowercase 64-character hexadecimal strings.\");\n }\n return value as Sha256Hex;\n}\n\n/** Computes a SHA-256 digest using the browser-safe Web Crypto API. */\nexport async function computeSha256(value: Uint8Array | string): Promise<Sha256Hex> {\n const subtle = globalThis.crypto?.subtle;\n if (!subtle) {\n throw new Error(\"Web Crypto SHA-256 support is required.\");\n }\n const bytes = typeof value === \"string\" ? new TextEncoder().encode(value) : value;\n const digest = await subtle.digest(\"SHA-256\", bytes as BufferSource);\n return asSha256Hex(\n Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, \"0\")).join(\"\"),\n );\n}\n\nfunction sorted<T>(items: readonly T[], compare: (left: T, right: T) => number): T[] {\n return [...items].sort(compare);\n}\n\nfunction compareString(left: string, right: string): number {\n return left < right ? -1 : left > right ? 1 : 0;\n}\n\nfunction interfaceProjection(manifest: GpuInterfaceManifest): unknown {\n return {\n contractVersion: manifest.contractVersion,\n records: sorted(manifest.records, (left, right) => compareString(left.name, right.name)),\n bindings: sorted(manifest.bindings, (left, right) =>\n compareString(left.moduleId, right.moduleId) || left.group - right.group || left.binding - right.binding),\n entryPoints: sorted(manifest.entryPoints, (left, right) =>\n compareString(left.moduleId, right.moduleId)\n || compareString(left.stage, right.stage)\n || compareString(left.name, right.name)),\n vertexInputs: sorted(manifest.vertexInputs, (left, right) =>\n compareString(left.pipelineId, right.pipelineId) || left.shaderLocation - right.shaderLocation),\n overrides: sorted(manifest.overrides, (left, right) =>\n compareString(left.moduleId, right.moduleId) || compareString(left.name, right.name)),\n };\n}\n\nfunction modelProjection(manifest: GpuInterfaceManifest): unknown {\n const recordsByName = new Map(manifest.records.map((record) => [record.name, record]));\n const names = new Set<string>();\n const includeRecord = (name: string): void => {\n if (names.has(name)) return;\n const record = recordsByName.get(name);\n if (!record) throw new TypeError(`Model ABI references missing record ${name}.`);\n names.add(name);\n const visitType = (type: typeof record.members[number][\"type\"]): void => {\n if (type.kind === \"record\") includeRecord(type.recordName);\n if (type.kind === \"array\") visitType(type.element);\n };\n for (const member of record.members) visitType(member.type);\n };\n for (const name of manifest.modelAbi.recordNames) includeRecord(name);\n for (const binding of manifest.modelAbi.bindings) {\n if (binding.resource.kind === \"buffer\" && binding.resource.recordName) includeRecord(binding.resource.recordName);\n }\n for (const semantic of manifest.modelAbi.semantics) {\n if (semantic.source.kind === \"record-member\") includeRecord(semantic.source.recordName);\n }\n const semanticProjection = manifest.modelAbi.semantics.map((projection) => ({\n semantic: projection.semantic,\n source: projection.source.kind === \"record-member\"\n ? {\n kind: projection.source.kind,\n recordName: projection.source.recordName,\n memberPath: projection.source.memberPath,\n }\n : { kind: projection.source.kind },\n }));\n return {\n contractVersion: manifest.contractVersion,\n records: sorted(\n manifest.records.filter((record) => names.has(record.name)),\n (left, right) => compareString(left.name, right.name),\n ).map(({ addressSpaces: _shaderUsage, ...record }) => record),\n bindings: sorted(manifest.modelAbi.bindings, (left, right) =>\n compareString(left.semantic ?? \"\", right.semantic ?? \"\")\n || compareString(canonicalizeGpuContract(left.resource), canonicalizeGpuContract(right.resource)))\n .map(({ source: _selector, ...binding }) => binding),\n vertexInputs: sorted(manifest.modelAbi.vertexInputs, (left, right) =>\n compareString(left.semantic ?? \"\", right.semantic ?? \"\")\n || left.offset - right.offset)\n .map(({ source: _selector, ...vertex }) => vertex),\n semantics: sorted(semanticProjection, (left, right) =>\n compareString(left.semantic, right.semantic),\n ),\n };\n}\n\nexport type ComputeGpuAbiHashInput =\n | { readonly kind: \"model\"; readonly interface: GpuInterfaceManifest }\n | { readonly kind: \"interface\"; readonly interface: GpuInterfaceManifest }\n | {\n readonly kind: \"shader\";\n readonly interface: GpuInterfaceManifest;\n readonly pipelines: readonly SerializableGpuPipelineDescriptor[];\n readonly requirements: ShaderRequirements;\n };\n\n/** Computes a domain-separated ABI digest over normalized structural data. */\nexport async function computeGpuAbiHash(input: ComputeGpuAbiHashInput): Promise<Sha256Hex> {\n if (input.kind === \"model\") {\n return computeSha256(\n `plasius.gpu.model-abi/v1\\n${canonicalizeGpuContract(modelProjection(input.interface))}`,\n );\n }\n if (input.kind === \"interface\") {\n return computeSha256(\n `plasius.gpu.interface-abi/v1\\n${canonicalizeGpuContract(interfaceProjection(input.interface))}`,\n );\n }\n const pipelines = sorted(input.pipelines, (left, right) =>\n compareString(left.pipelineId, right.pipelineId),\n );\n const requirements = {\n semantics: [...input.requirements.semantics].sort(),\n features: [...input.requirements.features].sort(),\n limits: sorted(input.requirements.limits, (left, right) => compareString(left.name, right.name)),\n formats: [...input.requirements.formats].sort(),\n };\n return computeSha256(\n `plasius.gpu.shader-abi/v1\\n${canonicalizeGpuContract({\n interface: interfaceProjection(input.interface),\n pipelines,\n requirements,\n })}`,\n );\n}\n\n/** Breaks the manifest/evidence digest cycle by omitting only the evidence reference. */\nexport async function computeShaderManifestCoreSha256(\n manifest: Omit<ShaderVersionManifest, \"validationEvidence\" | \"additionalValidationEvidence\"> | ShaderVersionManifest,\n): Promise<Sha256Hex> {\n const core = Object.fromEntries(Object.entries(manifest).filter(\n ([key]) => key !== \"validationEvidence\" && key !== \"additionalValidationEvidence\",\n ));\n return computeSha256(\n `plasius.gpu.shader-manifest-core/v1\\n${canonicalizeGpuContract(core)}`,\n );\n}\n","import type {\n GpuArrayLayout,\n GpuRecordCodec,\n GpuRecordLayout,\n GpuRecordValue,\n GpuScalarKind,\n GpuTypeLayout,\n} from \"../contracts.js\";\n\ninterface BufferRegion {\n readonly buffer: ArrayBuffer;\n readonly byteOffset: number;\n readonly byteLength: number;\n}\n\nfunction bufferRegion(value: ArrayBuffer | ArrayBufferView): BufferRegion {\n if (value instanceof ArrayBuffer) {\n return { buffer: value, byteOffset: 0, byteLength: value.byteLength };\n }\n if (!(value.buffer instanceof ArrayBuffer)) {\n throw new TypeError(\"SharedArrayBuffer-backed views are not supported by the codec.\");\n }\n return { buffer: value.buffer, byteOffset: value.byteOffset, byteLength: value.byteLength };\n}\n\nfunction integer(value: unknown, minimum: number, maximum: number, path: string): number {\n if (typeof value !== \"number\" || !Number.isInteger(value) || value < minimum || value > maximum) {\n throw new TypeError(`${path} must be an integer from ${minimum} to ${maximum}.`);\n }\n return value;\n}\n\nfunction numeric(value: unknown, path: string): number {\n if (typeof value !== \"number\" || !Number.isFinite(value)) {\n throw new TypeError(`${path} must be a finite number.`);\n }\n return value;\n}\n\nfunction scalarByteSize(scalar: GpuScalarKind): number {\n if (scalar === \"f16\") return 2;\n return 4;\n}\n\nfunction roundTiesToEven(value: number): number {\n const lower = Math.floor(value);\n const fraction = value - lower;\n if (fraction < 0.5) return lower;\n if (fraction > 0.5) return lower + 1;\n return lower % 2 === 0 ? lower : lower + 1;\n}\n\n/** Converts a finite JavaScript number to IEEE 754 binary16 using round-to-nearest, ties-to-even. */\nexport function encodeFloat16Bits(value: unknown, path: string): number {\n const input = numeric(value, path);\n const negative = input < 0 || Object.is(input, -0);\n const magnitude = Math.abs(input);\n if (magnitude > 65_504) throw new TypeError(`${path} is outside the finite f16 range.`);\n const sign = negative ? 0x8000 : 0;\n if (magnitude === 0) return sign;\n\n if (magnitude < 2 ** -14) {\n const significand = roundTiesToEven(magnitude / 2 ** -24);\n return sign | significand;\n }\n\n let exponent = Math.floor(Math.log2(magnitude));\n let significand = roundTiesToEven(magnitude / 2 ** (exponent - 10));\n if (significand === 2048) {\n exponent += 1;\n significand = 1024;\n }\n if (exponent > 15) throw new TypeError(`${path} is outside the finite f16 range.`);\n return sign | ((exponent + 15) << 10) | (significand - 1024);\n}\n\nexport function decodeFloat16Bits(bits: number, path: string): number {\n const sign = (bits & 0x8000) === 0 ? 1 : -1;\n const exponent = (bits >>> 10) & 0x1f;\n const fraction = bits & 0x03ff;\n if (exponent === 0x1f) throw new TypeError(`${path} contains a non-finite f16 value.`);\n if (exponent === 0) return sign * fraction * 2 ** -24;\n return sign * (1 + fraction / 1024) * 2 ** (exponent - 15);\n}\n\nfunction writeScalar(view: DataView, offset: number, scalar: GpuScalarKind, value: unknown, path: string): void {\n switch (scalar) {\n case \"u32\":\n view.setUint32(offset, integer(value, 0, 0xffff_ffff, path), true);\n return;\n case \"i32\":\n view.setInt32(offset, integer(value, -0x8000_0000, 0x7fff_ffff, path), true);\n return;\n case \"f32\":\n {\n const rounded = Math.fround(numeric(value, path));\n if (!Number.isFinite(rounded)) throw new TypeError(`${path} is outside the finite f32 range.`);\n view.setFloat32(offset, rounded, true);\n }\n return;\n case \"f16\":\n view.setUint16(offset, encodeFloat16Bits(value, path), true);\n return;\n case \"bool\":\n throw new TypeError(`${path} uses bool, which is not host-shareable.`);\n }\n}\n\nfunction readScalar(view: DataView, offset: number, scalar: GpuScalarKind, path: string): number {\n switch (scalar) {\n case \"u32\":\n return view.getUint32(offset, true);\n case \"i32\":\n return view.getInt32(offset, true);\n case \"f32\":\n return view.getFloat32(offset, true);\n case \"f16\":\n return decodeFloat16Bits(view.getUint16(offset, true), path);\n case \"bool\":\n throw new TypeError(`${path} uses bool, which is not host-shareable.`);\n }\n}\n\nfunction arrayValue(value: unknown, expected: number | null, path: string): readonly unknown[] {\n if (!Array.isArray(value)) {\n throw new TypeError(`${path} must be an array.`);\n }\n if (expected !== null && value.length !== expected) {\n throw new RangeError(`${path} must contain exactly ${expected} values.`);\n }\n return value;\n}\n\nfunction assertRecordValue(\n value: unknown,\n record: GpuRecordLayout,\n path: string,\n): asserts value is Record<string, unknown> {\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n throw new TypeError(`${path} must be an object.`);\n }\n const expected = new Set(record.members.map((member) => member.name));\n for (const key of Object.keys(value)) {\n if (!expected.has(key)) throw new TypeError(`${path}.${key} is not a reflected WGSL member.`);\n }\n for (const member of record.members) {\n if (!Object.prototype.hasOwnProperty.call(value, member.name)) {\n throw new TypeError(`${path}.${member.name} is required.`);\n }\n }\n}\n\nfunction runtimeMember(record: GpuRecordLayout): { name: string; offset: number; type: GpuArrayLayout } | null {\n if (record.runtimeArrayMember === null) return null;\n const member = record.members.find((candidate) => candidate.name === record.runtimeArrayMember);\n if (!member || member.type.kind !== \"array\" || member.type.count !== null) {\n throw new TypeError(`${record.name} has an invalid runtimeArrayMember declaration.`);\n }\n if (record.members.at(-1) !== member) {\n throw new TypeError(`${record.name}.${member.name} must be the trailing member.`);\n }\n return { name: member.name, offset: member.offset, type: member.type };\n}\n\n/** Creates a strict, little-endian codec directly from reflected record layouts. */\nexport function createGpuRecordCodec<T = GpuRecordValue>(\n record: GpuRecordLayout,\n records: readonly GpuRecordLayout[] = [record],\n): GpuRecordCodec<T> {\n const byName = new Map(records.map((candidate) => [candidate.name, candidate]));\n if (!byName.has(record.name)) byName.set(record.name, record);\n const runtime = runtimeMember(record);\n\n const resolveRecord = (name: string): GpuRecordLayout => {\n const resolved = byName.get(name);\n if (!resolved) throw new TypeError(`Reflected record ${name} is unavailable to the codec.`);\n return resolved;\n };\n\n const writeType = (\n view: DataView,\n offset: number,\n type: GpuTypeLayout,\n value: unknown,\n path: string,\n ): void => {\n switch (type.kind) {\n case \"scalar\":\n writeScalar(view, offset, type.scalar, value, path);\n return;\n case \"atomic\":\n writeScalar(view, offset, type.scalar, value, path);\n return;\n case \"vector\": {\n const values = arrayValue(value, type.width, path);\n const width = scalarByteSize(type.scalar);\n values.forEach((item, index) => writeScalar(view, offset + index * width, type.scalar, item, `${path}[${index}]`));\n return;\n }\n case \"matrix\": {\n const columns = arrayValue(value, type.columns, path);\n columns.forEach((column, columnIndex) => {\n const values = arrayValue(column, type.rows, `${path}[${columnIndex}]`);\n values.forEach((item, rowIndex) =>\n writeScalar(\n view,\n offset + columnIndex * type.columnStride + rowIndex * scalarByteSize(type.scalar),\n type.scalar,\n item,\n `${path}[${columnIndex}][${rowIndex}]`,\n ),\n );\n });\n return;\n }\n case \"array\": {\n const values = arrayValue(value, type.count, path);\n values.forEach((item, index) =>\n writeType(view, offset + index * type.stride, type.element, item, `${path}[${index}]`),\n );\n return;\n }\n case \"record\":\n writeRecord(view, offset, resolveRecord(type.recordName), value, path);\n }\n };\n\n const writeRecord = (\n view: DataView,\n offset: number,\n target: GpuRecordLayout,\n value: unknown,\n path: string,\n ): void => {\n assertRecordValue(value, target, path);\n for (const member of target.members) {\n writeType(view, offset + member.offset, member.type, value[member.name], `${path}.${member.name}`);\n }\n };\n\n const readType = (\n view: DataView,\n offset: number,\n type: GpuTypeLayout,\n path: string,\n runtimeCount?: number,\n ): unknown => {\n switch (type.kind) {\n case \"scalar\":\n return readScalar(view, offset, type.scalar, path);\n case \"atomic\":\n return readScalar(view, offset, type.scalar, path);\n case \"vector\":\n return Array.from({ length: type.width }, (_, index) =>\n readScalar(view, offset + index * scalarByteSize(type.scalar), type.scalar, `${path}[${index}]`),\n );\n case \"matrix\":\n return Array.from({ length: type.columns }, (_, column) =>\n Array.from({ length: type.rows }, (_, row) =>\n readScalar(\n view,\n offset + column * type.columnStride + row * scalarByteSize(type.scalar),\n type.scalar,\n `${path}[${column}][${row}]`,\n ),\n ),\n );\n case \"array\": {\n const count = type.count ?? runtimeCount;\n if (count === undefined) throw new TypeError(`${path} requires a bounded runtime-array length.`);\n return Array.from({ length: count }, (_, index) =>\n readType(view, offset + index * type.stride, type.element, `${path}[${index}]`),\n );\n }\n case \"record\":\n return readRecord(view, offset, resolveRecord(type.recordName), path);\n }\n };\n\n const readRecord = (\n view: DataView,\n offset: number,\n target: GpuRecordLayout,\n path: string,\n rootRuntimeCount?: number,\n ): GpuRecordValue => {\n const result: Record<string, unknown> = {};\n for (const member of target.members) {\n const count = member.name === target.runtimeArrayMember ? rootRuntimeCount : undefined;\n result[member.name] = readType(view, offset + member.offset, member.type, `${path}.${member.name}`, count);\n }\n return result;\n };\n\n const byteLength = (value: T): number => {\n assertRecordValue(value, record, record.name);\n if (!runtime) {\n if (record.byteSize === null) throw new TypeError(`${record.name} is missing a fixed byte size.`);\n return record.byteSize;\n }\n const values = arrayValue(value[runtime.name], null, `${record.name}.${runtime.name}`);\n const tail = values.length * runtime.type.stride;\n const total = runtime.offset + tail;\n if (!Number.isSafeInteger(tail) || !Number.isSafeInteger(total) || total > 0xffff_ffff) {\n throw new RangeError(`${record.name}.${runtime.name} exceeds the bounded GPU buffer size.`);\n }\n return total;\n };\n\n const encodeInto = (\n value: T,\n destination: ArrayBuffer | ArrayBufferView,\n byteOffset = 0,\n ): number => {\n if (!Number.isSafeInteger(byteOffset) || byteOffset < 0) {\n throw new RangeError(\"byteOffset must be a non-negative safe integer.\");\n }\n const length = byteLength(value);\n const region = bufferRegion(destination);\n if (byteOffset + length > region.byteLength) {\n throw new RangeError(`Destination needs ${length} bytes from byteOffset ${byteOffset}.`);\n }\n const absoluteOffset = region.byteOffset + byteOffset;\n new Uint8Array(region.buffer, absoluteOffset, length).fill(0);\n writeRecord(new DataView(region.buffer), absoluteOffset, record, value, record.name);\n return length;\n };\n\n return {\n record,\n minimumByteLength: record.minimumByteSize,\n byteLength,\n encode(value: T): ArrayBuffer {\n const output = new ArrayBuffer(byteLength(value));\n encodeInto(value, output);\n return output;\n },\n encodeInto,\n decode(source, options = {}): T {\n const region = bufferRegion(source);\n const relativeOffset = options.byteOffset ?? 0;\n if (!Number.isSafeInteger(relativeOffset) || relativeOffset < 0) {\n throw new RangeError(\"byteOffset must be a non-negative safe integer.\");\n }\n const available = options.byteLength ?? region.byteLength - relativeOffset;\n if (!Number.isSafeInteger(available) || available < record.minimumByteSize) {\n throw new RangeError(`Source must provide at least ${record.minimumByteSize} bytes.`);\n }\n if (relativeOffset + available > region.byteLength) {\n throw new RangeError(\"Requested source region exceeds the supplied buffer.\");\n }\n let count: number | undefined;\n if (runtime) {\n const tailLength = available - runtime.offset;\n if (tailLength < 0 || tailLength % runtime.type.stride !== 0) {\n throw new RangeError(`${record.name}.${runtime.name} byte length is not stride-aligned.`);\n }\n count = tailLength / runtime.type.stride;\n if (!Number.isSafeInteger(count) || count > 0xffff_ffff) throw new RangeError(`${record.name}.${runtime.name} runtime count is unsafe.`);\n } else if (record.byteSize !== available) {\n throw new RangeError(`${record.name} requires exactly ${record.byteSize} bytes.`);\n }\n const absoluteOffset = region.byteOffset + relativeOffset;\n return readRecord(new DataView(region.buffer), absoluteOffset, record, record.name, count) as T;\n },\n };\n}\n","import { canonicalizeGpuContract } from \"./canonical-json.js\";\nimport type {\n GpuBindingResourceLayout,\n GpuEntryPointInterface,\n GpuInterfaceManifest,\n GpuShaderStage,\n GpuTypeLayout,\n SerializableGpuPipelineDescriptor,\n ShaderRequirements,\n ShaderVersionManifestCore,\n} from \"./contracts.js\";\n\nconst ENABLED_FEATURES: Readonly<Record<string, string>> = Object.freeze({\n f16: \"shader-f16\",\n clip_distances: \"clip-distances\",\n dual_source_blending: \"dual-source-blending\",\n subgroups: \"subgroups\",\n primitive_index: \"primitive-index\",\n subgroup_size_control: \"subgroup-size-control\",\n});\n\nconst STAGES: readonly GpuShaderStage[] = [\"vertex\", \"fragment\", \"compute\"];\nconst INTER_STAGE_FRAGMENT_BUILTINS = new Set([\n \"front_facing\",\n \"sample_index\",\n \"sample_mask\",\n \"primitive_index\",\n \"subgroup_invocation_id\",\n \"subgroup_size\",\n]);\n\nfunction commentFree(source: string): string {\n let result = \"\"; let index = 0; let blockDepth = 0; let line = false;\n while (index < source.length) {\n const pair = source.slice(index, index + 2);\n if (line) { if (source[index] === \"\\n\") { line = false; result += \"\\n\"; } else result += \" \"; index += 1; continue; }\n if (blockDepth > 0) { if (pair === \"/*\") { blockDepth += 1; result += \" \"; index += 2; continue; } if (pair === \"*/\") { blockDepth -= 1; result += \" \"; index += 2; continue; } result += source[index] === \"\\n\" ? \"\\n\" : \" \"; index += 1; continue; }\n if (pair === \"//\") { line = true; result += \" \"; index += 2; continue; }\n if (pair === \"/*\") { blockDepth = 1; result += \" \"; index += 2; continue; }\n result += source[index]; index += 1;\n }\n if (blockDepth !== 0) throw new TypeError(\"WGSL contains an unterminated block comment.\");\n return result;\n}\n\n/** Infers WebGPU device features from exact comment-free WGSL enable directives. */\nexport function inferWgslRequiredFeatures(sources: readonly string[]): readonly string[] {\n const result = new Set<string>();\n for (const source of sources) {\n const stripped = commentFree(source); const consumed = stripped.replace(/\\benable\\s+([^;]+);/gu, (_match, list: string) => {\n const names = list.split(\",\").map((item) => item.trim());\n if (names.length === 0 || names.some((name) => !/^[A-Za-z_][A-Za-z0-9_]*$/u.test(name))) throw new TypeError(\"WGSL contains a malformed enable directive.\");\n for (const name of names) { const feature = ENABLED_FEATURES[name]; if (!feature) throw new TypeError(`WGSL enable ${name} has no stable WebGPU feature mapping.`); result.add(feature); }\n return \" \".repeat(_match.length);\n });\n if (/\\benable\\b/u.test(consumed)) throw new TypeError(\"WGSL contains an unterminated or malformed enable directive.\");\n }\n return [...result].sort();\n}\n\nfunction declaredLimits(requirements: ShaderRequirements): ReadonlyMap<string, { readonly comparator: \"at-least\" | \"at-most\"; readonly value: number }> {\n return new Map(requirements.limits.map((limit) => [limit.name, limit]));\n}\n\nfunction requireAtLeast(\n limits: ReadonlyMap<string, { readonly comparator: \"at-least\" | \"at-most\"; readonly value: number }>,\n name: string,\n value: number,\n): void {\n if (value === 0) return;\n const requirement = limits.get(name);\n if (!requirement || requirement.comparator !== \"at-least\" || requirement.value < value) {\n throw new TypeError(`Shader requirements must declare ${name} at least ${value}.`);\n }\n}\n\ninterface StageResourceCounts {\n sampledTextures: number;\n samplers: number;\n storageBuffers: number;\n storageTextures: number;\n uniformBuffers: number;\n}\n\nfunction emptyResourceCounts(): StageResourceCounts {\n return { sampledTextures: 0, samplers: 0, storageBuffers: 0, storageTextures: 0, uniformBuffers: 0 };\n}\n\nfunction countResource(resource: GpuBindingResourceLayout, counts: StageResourceCounts): void {\n switch (resource.kind) {\n case \"buffer\":\n if (resource.addressSpace === \"uniform\") counts.uniformBuffers += 1;\n else counts.storageBuffers += 1;\n return;\n case \"sampler\": counts.samplers += 1; return;\n case \"texture\": counts.sampledTextures += 1; return;\n case \"storage-texture\": counts.storageTextures += 1; return;\n case \"external-texture\":\n // WebGPU expands one external texture into four sampled-texture slots,\n // one sampler slot, and one uniform-buffer slot.\n counts.sampledTextures += 4;\n counts.samplers += 1;\n counts.uniformBuffers += 1;\n }\n}\n\n/**\n * Rejects requirements that understate facts encoded directly in serializable\n * WebGPU pipeline descriptors. This is usable before reflected WGSL is loaded.\n */\nexport function validatePipelineDerivedRequirements(input: {\n readonly requirements: ShaderRequirements;\n readonly pipelines: readonly SerializableGpuPipelineDescriptor[];\n}): void {\n const limits = declaredLimits(input.requirements);\n const features = new Set(input.requirements.features);\n const formats = new Set(input.requirements.formats);\n const requiredFormats = new Set<string>();\n const requiredLimits = new Map<string, number>();\n const recordLimit = (name: string, value: number): void => {\n requiredLimits.set(name, Math.max(requiredLimits.get(name) ?? 0, value));\n };\n\n for (const pipeline of input.pipelines) {\n recordLimit(\"maxBindGroups\", pipeline.layout.bindGroups.length);\n recordLimit(\"maxBindingsPerBindGroup\", Math.max(0, ...pipeline.layout.bindGroups.map((group) => group.entries.length)));\n\n const counts = new Map<GpuShaderStage, StageResourceCounts>(STAGES.map((stage) => [stage, emptyResourceCounts()]));\n for (const group of pipeline.layout.bindGroups) {\n for (const entry of group.entries) {\n for (const stage of entry.visibility) countResource(entry.resource, counts.get(stage)!);\n if (entry.resource.kind === \"storage-texture\") requiredFormats.add(entry.resource.format);\n if (entry.resource.kind === \"buffer\") {\n recordLimit(\n entry.resource.addressSpace === \"uniform\" ? \"maxUniformBufferBindingSize\" : \"maxStorageBufferBindingSize\",\n entry.resource.minimumBindingSize,\n );\n }\n }\n }\n for (const stageCounts of counts.values()) {\n recordLimit(\"maxSampledTexturesPerShaderStage\", stageCounts.sampledTextures);\n recordLimit(\"maxSamplersPerShaderStage\", stageCounts.samplers);\n recordLimit(\"maxStorageBuffersPerShaderStage\", stageCounts.storageBuffers);\n recordLimit(\"maxStorageTexturesPerShaderStage\", stageCounts.storageTextures);\n recordLimit(\"maxUniformBuffersPerShaderStage\", stageCounts.uniformBuffers);\n }\n\n if (pipeline.kind === \"render\") {\n if (pipeline.primitive.unclippedDepth && !features.has(\"depth-clip-control\")) {\n throw new TypeError(\"Shader requirements omit pipeline-derived feature depth-clip-control.\");\n }\n recordLimit(\"maxBindGroupsPlusVertexBuffers\", pipeline.layout.bindGroups.length + pipeline.vertexBuffers.length);\n recordLimit(\"maxVertexBuffers\", pipeline.vertexBuffers.length);\n recordLimit(\"maxVertexAttributes\", pipeline.vertexBuffers.reduce((sum, buffer) => sum + buffer.attributes.length, 0));\n recordLimit(\"maxVertexBufferArrayStride\", Math.max(0, ...pipeline.vertexBuffers.map((buffer) => buffer.arrayStride)));\n recordLimit(\"maxColorAttachments\", pipeline.colorTargets.length);\n pipeline.colorTargets.forEach((target) => requiredFormats.add(target.format));\n if (pipeline.depthStencil) requiredFormats.add(pipeline.depthStencil.format);\n }\n }\n\n for (const format of requiredFormats) {\n if (!formats.has(format)) throw new TypeError(`Shader requirements list omits structurally required format ${format}.`);\n }\n for (const [name, value] of requiredLimits) requireAtLeast(limits, name, value);\n}\n\nfunction constantValue(interfaceManifest: GpuInterfaceManifest, moduleId: string, name: string, constants: Readonly<Record<string, boolean | number>>): number {\n const override = interfaceManifest.overrides.find((candidate) => candidate.moduleId === moduleId && candidate.name === name);\n if (!override) throw new TypeError(`Compute workgroup dimension references missing override ${moduleId}:${name}.`);\n const supplied = constants[name] ?? (override.id === null ? undefined : constants[String(override.id)]);\n const value = supplied ?? override.defaultValue;\n if (typeof value !== \"number\" || !Number.isSafeInteger(value) || value < 1) throw new TypeError(`Compute workgroup override ${moduleId}:${name} must resolve to a positive integer.`);\n return value;\n}\n\nfunction pipelineStages(pipeline: SerializableGpuPipelineDescriptor): readonly {\n readonly moduleId: string;\n readonly entryPoint: string;\n readonly stage: GpuShaderStage;\n}[] {\n return pipeline.kind === \"compute\"\n ? [{ moduleId: pipeline.compute.moduleId, entryPoint: pipeline.compute.entryPoint, stage: \"compute\" }]\n : [\n { moduleId: pipeline.vertex.moduleId, entryPoint: pipeline.vertex.entryPoint, stage: \"vertex\" },\n ...(pipeline.fragment ? [{ moduleId: pipeline.fragment.moduleId, entryPoint: pipeline.fragment.entryPoint, stage: \"fragment\" as const }] : []),\n ];\n}\n\nfunction reflectedEntry(\n gpuInterface: GpuInterfaceManifest,\n stage: { readonly moduleId: string; readonly entryPoint: string; readonly stage: GpuShaderStage },\n pipelineId: string,\n): GpuEntryPointInterface {\n const entry = gpuInterface.entryPoints.find((candidate) => candidate.moduleId === stage.moduleId\n && candidate.name === stage.entryPoint && candidate.stage === stage.stage);\n if (!entry) throw new TypeError(`Pipeline ${pipelineId} lacks reflected ${stage.stage} entry point ${stage.moduleId}:${stage.entryPoint}.`);\n return entry;\n}\n\nfunction orderedStages(stages: Iterable<GpuShaderStage>): readonly GpuShaderStage[] {\n return [...new Set(stages)].sort((left, right) => STAGES.indexOf(left) - STAGES.indexOf(right));\n}\n\nfunction clipDistanceSlots(entry: GpuEntryPointInterface): number {\n const clipDistances = entry.outputs.find((output) => output.locationKind === \"builtin\" && output.location === \"clip_distances\");\n if (!clipDistances) return 0;\n if (clipDistances.type.kind !== \"array\" || clipDistances.type.count === null) {\n throw new TypeError(\"Reflected clip_distances output must be a fixed-size array.\");\n }\n return Math.ceil(clipDistances.type.count / 4);\n}\n\nfunction highestLocationPlusOne(entry: GpuEntryPointInterface, direction: \"inputs\" | \"outputs\"): number {\n return Math.max(0, ...entry[direction]\n .filter((item) => item.locationKind === \"location\")\n .map((item) => Number(item.location) + 1));\n}\n\nfunction requiredInterStageVariables(\n pipeline: Extract<SerializableGpuPipelineDescriptor, { readonly kind: \"render\" }>,\n vertex: GpuEntryPointInterface,\n fragment: GpuEntryPointInterface | undefined,\n): number {\n const vertexOutputs = vertex.outputs.filter((output) => output.locationKind === \"location\").length;\n const reservedVertexSlots = (pipeline.primitive.topology === \"point-list\" ? 1 : 0) + clipDistanceSlots(vertex);\n let required = Math.max(\n vertexOutputs + reservedVertexSlots,\n highestLocationPlusOne(vertex, \"outputs\") + reservedVertexSlots,\n );\n if (fragment) {\n const fragmentInputs = fragment.inputs.filter((input) => input.locationKind === \"location\").length;\n const fragmentBuiltins = fragment.inputs.filter((input) =>\n input.locationKind === \"builtin\" && INTER_STAGE_FRAGMENT_BUILTINS.has(String(input.location))).length;\n required = Math.max(\n required,\n fragmentInputs + fragmentBuiltins,\n highestLocationPlusOne(fragment, \"inputs\"),\n );\n }\n return required;\n}\n\nfunction interStageComponentCount(\n type: GpuTypeLayout,\n gpuInterface: GpuInterfaceManifest,\n activeRecords = new Set<string>(),\n): number {\n switch (type.kind) {\n case \"scalar\":\n case \"atomic\":\n return 1;\n case \"vector\":\n return type.width;\n case \"matrix\":\n return type.columns * type.rows;\n case \"array\":\n if (type.count === null) throw new TypeError(\"Inter-stage IO cannot contain a runtime-sized array.\");\n return type.count * interStageComponentCount(type.element, gpuInterface, activeRecords);\n case \"record\": { // Defensive support for reflectors that retain an IO structure reference.\n if (activeRecords.has(type.recordName)) throw new TypeError(`Inter-stage IO record ${type.recordName} is recursive.`);\n const record = gpuInterface.records.find((candidate) => candidate.name === type.recordName);\n if (!record) throw new TypeError(`Inter-stage IO references missing record ${type.recordName}.`);\n const nested = new Set(activeRecords);\n nested.add(type.recordName);\n return record.members.reduce(\n (sum, member) => sum + interStageComponentCount(member.type, gpuInterface, nested),\n 0,\n );\n }\n }\n}\n\nfunction requiredInterStageComponents(\n vertex: GpuEntryPointInterface,\n fragment: GpuEntryPointInterface | undefined,\n gpuInterface: GpuInterfaceManifest,\n): number {\n const countLocations = (items: GpuEntryPointInterface[\"inputs\"]): number => items\n .filter((item) => item.locationKind === \"location\")\n .reduce((sum, item) => sum + interStageComponentCount(item.type, gpuInterface), 0);\n return Math.max(\n countLocations(vertex.outputs),\n fragment ? countLocations(fragment.inputs) : 0,\n );\n}\n\n/**\n * Rejects interface/pipeline requirements that understate exact reflected ABI\n * semantics, entry-point resource usage, inter-stage IO, or compute workgroups.\n */\nexport function validateShaderInterfaceRequirements(input: {\n readonly manifest: ShaderVersionManifestCore;\n readonly gpuInterface: GpuInterfaceManifest;\n}): void {\n const { manifest, gpuInterface } = input;\n if (manifest.gpuInterface.interfaceId !== gpuInterface.interfaceId\n || manifest.gpuInterface.interfaceVersion !== gpuInterface.interfaceVersion\n || manifest.gpuInterface.interfaceAbiHash !== gpuInterface.interfaceAbiHash\n || manifest.gpuInterface.modelAbiHash !== gpuInterface.modelAbiHash) {\n throw new TypeError(\"Shader GPU interface reference differs from the reflected interface identity.\");\n }\n const manifestModules = [...manifest.modules]\n .map(({ moduleId, sha256 }) => ({ moduleId, sha256 }))\n .sort((left, right) => left.moduleId < right.moduleId ? -1 : left.moduleId > right.moduleId ? 1 : 0);\n const interfaceModules = [...gpuInterface.modules]\n .map(({ moduleId, sha256 }) => ({ moduleId, sha256 }))\n .sort((left, right) => left.moduleId < right.moduleId ? -1 : left.moduleId > right.moduleId ? 1 : 0);\n if (canonicalizeGpuContract(manifestModules) !== canonicalizeGpuContract(interfaceModules)) {\n throw new TypeError(\"Shader modules differ from the exact reflected interface module set.\");\n }\n\n validatePipelineDerivedRequirements({ requirements: manifest.requirements, pipelines: manifest.pipelines });\n const requiredSemantics = new Set(gpuInterface.modelAbi.semantics.map((projection) => projection.semantic));\n const declaredSemantics = new Set(manifest.requirements.semantics);\n for (const semantic of requiredSemantics) {\n if (!declaredSemantics.has(semantic)) throw new TypeError(`Shader requirements omit reflected model semantic ${semantic}.`);\n }\n\n const limits = declaredLimits(manifest.requirements);\n for (const pipeline of manifest.pipelines) {\n const stages = pipelineStages(pipeline);\n const entries = stages.map((stage) => ({ stage, entry: reflectedEntry(gpuInterface, stage, pipeline.pipelineId) }));\n for (const group of pipeline.layout.bindGroups) {\n for (const descriptorEntry of group.entries) {\n const used = entries.filter(({ stage, entry }) =>\n entry.bindingKeys.includes(`${stage.moduleId}:${group.group}:${descriptorEntry.binding}`));\n if (used.length === 0) throw new TypeError(`Pipeline ${pipeline.pipelineId} binding ${group.group}:${descriptorEntry.binding} is absent from its reflected entry points.`);\n if (canonicalizeGpuContract(orderedStages(descriptorEntry.visibility))\n !== canonicalizeGpuContract(orderedStages(used.map(({ stage }) => stage.stage)))) {\n throw new TypeError(`Pipeline ${pipeline.pipelineId} binding ${group.group}:${descriptorEntry.binding} visibility differs from reflected entry-point usage.`);\n }\n for (const { stage } of used) {\n const reflected = gpuInterface.bindings.find((binding) => binding.moduleId === stage.moduleId\n && binding.group === group.group && binding.binding === descriptorEntry.binding);\n if (!reflected || canonicalizeGpuContract(reflected.resource) !== canonicalizeGpuContract(descriptorEntry.resource)) {\n throw new TypeError(`Pipeline ${pipeline.pipelineId} binding ${stage.moduleId}:${group.group}:${descriptorEntry.binding} differs from the reflected interface.`);\n }\n }\n }\n }\n for (const { stage, entry } of entries) {\n for (const key of entry.bindingKeys) {\n const declared = pipeline.layout.bindGroups.some((group) => group.entries.some((descriptorEntry) =>\n key === `${stage.moduleId}:${group.group}:${descriptorEntry.binding}`));\n if (!declared) throw new TypeError(`Pipeline ${pipeline.pipelineId} omits reflected binding ${key}.`);\n }\n }\n\n if (pipeline.kind === \"compute\") {\n const entry = entries[0]?.entry;\n if (!entry?.workgroupSize) throw new TypeError(`Compute pipeline ${pipeline.pipelineId} lacks an exact reflected workgroup size.`);\n if (entry.workgroupStorageSize === null) throw new TypeError(`Compute pipeline ${pipeline.pipelineId} lacks an exact reflected workgroup storage size.`);\n const values = entry.workgroupSize.map((dimension) => dimension.kind === \"literal\" ? dimension.value : constantValue(gpuInterface, entry.moduleId, dimension.name, pipeline.compute.constants)) as [number, number, number];\n const invocations = values[0] * values[1] * values[2];\n if (!Number.isSafeInteger(invocations)) throw new TypeError(`Compute pipeline ${pipeline.pipelineId} workgroup invocation count is outside the safe manifest range.`);\n requireAtLeast(limits, \"maxComputeWorkgroupSizeX\", values[0]);\n requireAtLeast(limits, \"maxComputeWorkgroupSizeY\", values[1]);\n requireAtLeast(limits, \"maxComputeWorkgroupSizeZ\", values[2]);\n requireAtLeast(limits, \"maxComputeInvocationsPerWorkgroup\", invocations);\n requireAtLeast(limits, \"maxComputeWorkgroupStorageSize\", entry.workgroupStorageSize);\n } else {\n const vertex = entries.find(({ stage }) => stage.stage === \"vertex\")?.entry;\n const fragment = entries.find(({ stage }) => stage.stage === \"fragment\")?.entry;\n if (!vertex) throw new TypeError(`Render pipeline ${pipeline.pipelineId} lacks an exact reflected vertex entry point.`);\n requireAtLeast(limits, \"maxInterStageShaderVariables\", requiredInterStageVariables(pipeline, vertex, fragment));\n requireAtLeast(limits, \"maxInterStageShaderComponents\", requiredInterStageComponents(vertex, fragment, gpuInterface));\n }\n }\n}\n\n/** Rejects caller-declared requirements that understate facts derived from exact modules/interfaces. */\nexport function validateShaderDerivedRequirements(input: {\n readonly manifest: ShaderVersionManifestCore;\n readonly gpuInterface: GpuInterfaceManifest;\n readonly moduleSources: ReadonlyMap<string, string>;\n}): void {\n const expectedModuleIds = [...input.manifest.modules.map((module) => module.moduleId)].sort(); const actualModuleIds = [...input.moduleSources.keys()].sort();\n if (expectedModuleIds.join(\"\\n\") !== actualModuleIds.join(\"\\n\")) throw new TypeError(\"Derived-requirement source modules differ from the exact shader manifest module set.\");\n validateShaderInterfaceRequirements(input);\n const features = new Set(input.manifest.requirements.features);\n for (const feature of inferWgslRequiredFeatures([...input.moduleSources.values()])) if (!features.has(feature)) throw new TypeError(`Shader requirements omit WGSL-derived feature ${feature}.`);\n}\n","import type {\n GpuCapabilitySnapshot,\n GpuInterfaceManifest,\n ModelGpuCompatibilityDescriptor,\n ModelShaderCompatibility,\n ShaderDiagnostic,\n ShaderResult,\n ShaderStyleProfileManifest,\n ShaderVersionManifestCore,\n} from \"./contracts.js\";\nimport { validateShaderInterfaceRequirements } from \"./requirements-validation.js\";\n\nfunction error(\n code: ShaderDiagnostic[\"code\"],\n message: string,\n path?: string,\n): ShaderDiagnostic {\n return { code, severity: \"error\", message, ...(path ? { path } : {}) };\n}\n\nfunction interfaceMatches(\n item: { readonly interfaceId: string; readonly interfaceVersion: string; readonly manifestSha256: string; readonly interfaceAbiHash: string; readonly modelAbiHash: string },\n model: ModelGpuCompatibilityDescriptor,\n): boolean {\n return item.interfaceId === model.gpuInterface.interfaceId\n && item.interfaceVersion === model.gpuInterface.interfaceVersion\n && item.manifestSha256 === model.gpuInterface.manifestSha256\n && item.interfaceAbiHash === model.gpuInterface.interfaceAbiHash\n && item.modelAbiHash === model.modelAbiHash;\n}\n\nfunction validateRequirements(\n shader: ShaderVersionManifestCore,\n gpuInterface: GpuInterfaceManifest,\n model: ModelGpuCompatibilityDescriptor,\n capabilities: GpuCapabilitySnapshot | undefined,\n diagnostics: ShaderDiagnostic[],\n): void {\n const semantics = new Set(model.providedSemantics);\n const requiredSemantics = new Set([\n ...shader.requirements.semantics,\n ...gpuInterface.modelAbi.semantics.map((projection) => projection.semantic),\n ]);\n for (const semantic of requiredSemantics) {\n if (!semantics.has(semantic)) {\n diagnostics.push(error(\"missing-semantic\", `Model does not provide required semantic ${semantic}.`, \"requirements.semantics\"));\n }\n }\n if (!capabilities) return;\n const features = new Set(capabilities.features);\n for (const feature of shader.requirements.features) {\n if (!features.has(feature)) {\n diagnostics.push(error(\"missing-feature\", `GPU does not provide required feature ${feature}.`, \"requirements.features\"));\n }\n }\n const formats = new Set(capabilities.formats);\n for (const format of shader.requirements.formats) {\n if (!formats.has(format)) {\n diagnostics.push(error(\"unsupported-format\", `GPU runtime does not expose required format ${format}.`, \"requirements.formats\"));\n }\n }\n for (const requirement of shader.requirements.limits) {\n const available = capabilities.limits[requirement.name];\n const satisfied = available !== undefined && (\n requirement.comparator === \"at-least\"\n ? available >= requirement.value\n : available <= requirement.value\n );\n if (!satisfied) {\n diagnostics.push(error(\n \"limit-not-met\",\n `GPU limit ${requirement.name} does not meet the ${requirement.comparator} requirement.`,\n \"requirements.limits\",\n ));\n }\n }\n}\n\n/** Performs pure manifest/model/device compatibility checks without creating GPU resources. */\nexport function validateModelShaderCompatibility(input: {\n readonly model: ModelGpuCompatibilityDescriptor;\n readonly shader: ShaderVersionManifestCore;\n /** Exact reflected interface referenced by `shader`; required to prevent sidecar understatement. */\n readonly gpuInterface: GpuInterfaceManifest;\n readonly profile?: ShaderStyleProfileManifest;\n readonly capabilities?: GpuCapabilitySnapshot;\n}): ShaderResult<ModelShaderCompatibility> {\n const diagnostics: ShaderDiagnostic[] = [];\n const { model, shader, gpuInterface, profile, capabilities } = input;\n try {\n validateShaderInterfaceRequirements({ manifest: shader, gpuInterface });\n } catch (cause) {\n diagnostics.push(error(\n \"invalid-contract\",\n cause instanceof Error ? cause.message : \"Shader requirements differ from the reflected GPU interface.\",\n \"requirements\",\n ));\n }\n if (model.gpuInterface.modelAbiHash !== model.modelAbiHash) {\n diagnostics.push(error(\"model-abi-mismatch\", \"Model manifest and GPU interface reference disagree on modelAbiHash.\", \"modelAbiHash\"));\n }\n if (shader.gpuInterface.modelAbiHash !== model.modelAbiHash) {\n diagnostics.push(error(\"model-abi-mismatch\", \"Shader GPU interface does not match the model ABI.\", \"gpuInterface.modelAbiHash\"));\n }\n if (!shader.compatibleModelInterfaces.some((item) => interfaceMatches(item, model))) {\n diagnostics.push(error(\"incompatible-model-interface\", \"Shader does not declare this exact model interface as compatible.\"));\n }\n if (profile) {\n if (!profile.compatibleModelInterfaces.some((item) => interfaceMatches(item, model))) {\n diagnostics.push(error(\"incompatible-model-interface\", \"Style profile does not declare this exact model interface as compatible.\"));\n }\n const provided = new Set(model.providedSemantics);\n for (const semantic of profile.requiredSemantics) {\n if (!provided.has(semantic)) {\n diagnostics.push(error(\"missing-semantic\", `Model does not provide profile semantic ${semantic}.`, \"requiredSemantics\"));\n }\n }\n }\n validateRequirements(shader, gpuInterface, model, capabilities, diagnostics);\n if (diagnostics.length > 0) return { ok: false, diagnostics };\n return {\n ok: true,\n value: {\n modelAbiHash: model.modelAbiHash,\n shaderAbiHash: shader.shaderAbiHash,\n matchedInterfaceId: model.gpuInterface.interfaceId,\n },\n };\n}\n","import {\n GPU_INTERFACE_MANIFEST_VERSION,\n SHADER_QUALIFICATION_FIXTURE_VERSION,\n SHADER_STYLE_PROFILE_MANIFEST_VERSION,\n SHADER_VERSION_MANIFEST_VERSION,\n SUPPORTED_ADDITIVE_WEBGPU_MATRIX_POLICIES,\n SUPPORTED_STABLE_WEBGPU_MATRIX_POLICIES,\n type GpuBindingResourceLayout,\n type GpuInterfaceManifest,\n type ModelGpuCompatibilityDescriptor,\n type GpuRecordLayout,\n type GpuTypeLayout,\n type SerializableGpuPipelineDescriptor,\n type ShaderStyleProfileManifest,\n type ShaderQualificationModelCompatibilityFixture,\n type ShaderVersionManifest,\n type ShaderVersionManifestCore,\n} from \"./contracts.js\";\nimport { canonicalizeGpuContract as canonicalizeForValidation } from \"./canonical-json.js\";\nimport { asSha256Hex } from \"./hash.js\";\nimport { validatePipelineDerivedRequirements } from \"./requirements-validation.js\";\n\ntype UnknownRecord = Record<string, unknown>;\nconst stages = [\"vertex\", \"fragment\", \"compute\"] as const;\nconst roles = [\"material\", \"lighting\", \"outline\", \"shadow\", \"post-processing\"] as const;\n\nfunction object(value: unknown, path: string): UnknownRecord {\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) throw new TypeError(`${path} must be an object.`);\n return value as UnknownRecord;\n}\n\nfunction exact(value: UnknownRecord, keys: readonly string[], path: string): void {\n const allowed = new Set(keys);\n for (const key of Object.keys(value)) if (!allowed.has(key)) throw new TypeError(`${path}.${key} is not part of this contract version.`);\n for (const key of keys) if (!(key in value)) throw new TypeError(`${path}.${key} is required.`);\n}\n\nfunction text(value: unknown, path: string, maximum = 512): string {\n if (typeof value !== \"string\" || value.length === 0 || value.length > maximum || [...value].some((character) => character.charCodeAt(0) <= 0x1f)) {\n throw new TypeError(`${path} must be a bounded non-empty string without control characters.`);\n }\n return value;\n}\n\nfunction token(value: unknown, path: string): string {\n const result = text(value, path, 160);\n if (!/^[A-Za-z0-9][A-Za-z0-9._:/-]*$/u.test(result) || result.includes(\"..\")) throw new TypeError(`${path} must be a safe token.`);\n return result;\n}\n\nfunction enumeration<T extends string | number>(value: unknown, values: readonly T[], path: string): T {\n if (!values.includes(value as T)) throw new TypeError(`${path} is invalid.`);\n return value as T;\n}\n\nfunction integer(value: unknown, path: string, minimum = 0, maximum = 0xffff_ffff): number {\n if (!Number.isSafeInteger(value) || (value as number) < minimum || (value as number) > maximum) {\n throw new TypeError(`${path} must be an integer from ${minimum} through ${maximum}.`);\n }\n return value as number;\n}\n\nfunction finite(value: unknown, path: string): number {\n if (typeof value !== \"number\" || !Number.isFinite(value)) throw new TypeError(`${path} must be finite.`);\n return value;\n}\n\nfunction array(value: unknown, path: string, maximum = 4096): readonly unknown[] {\n if (!Array.isArray(value) || value.length > maximum) throw new TypeError(`${path} must be a bounded array.`);\n return value;\n}\n\nfunction nullableInteger(value: unknown, path: string): number | null {\n return value === null ? null : integer(value, path);\n}\n\nfunction nullableToken(value: unknown, path: string): string | null {\n return value === null ? null : token(value, path);\n}\n\nfunction digest(value: unknown, path: string): string {\n try { return asSha256Hex(text(value, path, 64)); }\n catch (cause) { throw new TypeError(`${path} must be a lowercase SHA-256 digest.`, { cause }); }\n}\n\nfunction uri(value: unknown, path: string): string {\n const result = text(value, path, 2048);\n let parsed: URL;\n try { parsed = new URL(result); }\n catch (cause) { throw new TypeError(`${path} must be an absolute immutable asset URI.`, { cause }); }\n if (parsed.protocol !== \"https:\" || parsed.username || parsed.password || parsed.hash) throw new TypeError(`${path} must be credential-free HTTPS without a fragment.`);\n const keys = [...parsed.searchParams.keys()].map((key) => key.toLowerCase());\n const forbidden = new Set([\"sig\", \"se\", \"sp\", \"sv\", \"spr\", \"st\", \"skoid\", \"sktid\", \"skt\", \"ske\", \"sks\", \"skv\"]);\n if (keys.some((key) => forbidden.has(key)) || new Set(keys).size !== keys.length) throw new TypeError(`${path} must not contain SAS credentials or duplicate query parameters.`);\n if (parsed.href !== result) throw new TypeError(`${path} must use its canonical URL serialization.`);\n return result;\n}\n\nfunction unique<T>(values: readonly T[], key: (value: T) => string, path: string): void {\n const seen = new Set<string>();\n for (const value of values) {\n const identity = key(value);\n if (seen.has(identity)) throw new TypeError(`${path} contains duplicate ${identity}.`);\n seen.add(identity);\n }\n}\n\nfunction tokenArray(value: unknown, path: string, maximum = 4096): string[] {\n const result = array(value, path, maximum).map((item, index) => token(item, `${path}[${index}]`));\n unique(result, String, path);\n return result;\n}\n\nfunction typeLayout(value: unknown, path: string, depth = 0): GpuTypeLayout {\n if (depth > 24) throw new TypeError(`${path} exceeds the type nesting limit.`);\n const input = object(value, path);\n const kind = enumeration(input.kind, [\"scalar\", \"atomic\", \"vector\", \"matrix\", \"array\", \"record\"] as const, `${path}.kind`);\n integer(input.alignment, `${path}.alignment`, 1);\n if (kind === \"array\") {\n exact(input, [\"kind\", \"element\", \"count\", \"stride\", \"alignment\", \"byteSize\"], path);\n const element = typeLayout(input.element, `${path}.element`, depth + 1);\n const count = nullableInteger(input.count, `${path}.count`);\n const stride = integer(input.stride, `${path}.stride`, 1);\n const byteSize = nullableInteger(input.byteSize, `${path}.byteSize`);\n if (input.alignment !== element.alignment || stride % element.alignment !== 0\n || element.byteSize === null || stride < element.byteSize\n || (count === null ? byteSize !== null : byteSize !== count * stride)) {\n throw new TypeError(`${path} has inconsistent array layout algebra.`);\n }\n } else if (kind === \"record\") {\n exact(input, [\"kind\", \"recordName\", \"alignment\", \"byteSize\"], path);\n token(input.recordName, `${path}.recordName`);\n nullableInteger(input.byteSize, `${path}.byteSize`);\n } else {\n integer(input.byteSize, `${path}.byteSize`, 1);\n if (kind === \"scalar\") {\n exact(input, [\"kind\", \"scalar\", \"alignment\", \"byteSize\"], path);\n enumeration(input.scalar, [\"i32\", \"u32\", \"f32\", \"f16\", \"bool\"] as const, `${path}.scalar`);\n const size = input.scalar === \"f16\" ? 2 : 4;\n if (input.alignment !== size || input.byteSize !== size) throw new TypeError(`${path} has inconsistent scalar layout.`);\n } else if (kind === \"atomic\") {\n exact(input, [\"kind\", \"scalar\", \"alignment\", \"byteSize\"], path);\n enumeration(input.scalar, [\"i32\", \"u32\"] as const, `${path}.scalar`);\n if (input.alignment !== 4 || input.byteSize !== 4) throw new TypeError(`${path} has inconsistent atomic layout.`);\n } else if (kind === \"vector\") {\n exact(input, [\"kind\", \"scalar\", \"width\", \"alignment\", \"byteSize\"], path);\n enumeration(input.scalar, [\"i32\", \"u32\", \"f32\", \"f16\", \"bool\"] as const, `${path}.scalar`);\n const width = enumeration(input.width, [2, 3, 4] as const, `${path}.width`);\n const scalarSize = input.scalar === \"f16\" ? 2 : 4;\n if (input.alignment !== (width === 2 ? 2 : 4) * scalarSize || input.byteSize !== width * scalarSize) throw new TypeError(`${path} has inconsistent vector layout.`);\n } else {\n exact(input, [\"kind\", \"scalar\", \"columns\", \"rows\", \"columnStride\", \"alignment\", \"byteSize\"], path);\n enumeration(input.scalar, [\"f32\", \"f16\"] as const, `${path}.scalar`);\n const columns = enumeration(input.columns, [2, 3, 4] as const, `${path}.columns`);\n const rows = enumeration(input.rows, [2, 3, 4] as const, `${path}.rows`);\n const stride = integer(input.columnStride, `${path}.columnStride`, 1);\n const scalarSize = input.scalar === \"f16\" ? 2 : 4;\n const alignment = (rows === 2 ? 2 : 4) * scalarSize;\n if (input.alignment !== alignment || stride !== Math.ceil((rows * scalarSize) / alignment) * alignment || input.byteSize !== columns * stride) throw new TypeError(`${path} has inconsistent matrix layout.`);\n }\n }\n return input as unknown as GpuTypeLayout;\n}\n\nfunction recordLayout(value: unknown, path: string): GpuRecordLayout {\n const input = object(value, path);\n exact(input, [\"name\", \"alignment\", \"byteSize\", \"minimumByteSize\", \"runtimeArrayMember\", \"addressSpaces\", \"members\"], path);\n token(input.name, `${path}.name`);\n integer(input.alignment, `${path}.alignment`, 1);\n nullableInteger(input.byteSize, `${path}.byteSize`);\n integer(input.minimumByteSize, `${path}.minimumByteSize`);\n nullableToken(input.runtimeArrayMember, `${path}.runtimeArrayMember`);\n const spaces = array(input.addressSpaces, `${path}.addressSpaces`, 5).map((space, index) =>\n enumeration(space, [\"uniform\", \"storage\", \"function\", \"private\", \"workgroup\"] as const, `${path}.addressSpaces[${index}]`));\n unique(spaces, String, `${path}.addressSpaces`);\n const members = array(input.members, `${path}.members`);\n let priorEnd = 0;\n const names: string[] = [];\n members.forEach((value, index) => {\n const memberPath = `${path}.members[${index}]`;\n const member = object(value, memberPath);\n exact(member, [\"name\", \"offset\", \"alignment\", \"valueByteSize\", \"occupiedByteSize\", \"explicitAlign\", \"explicitSize\", \"type\"], memberPath);\n names.push(token(member.name, `${memberPath}.name`));\n const offset = integer(member.offset, `${memberPath}.offset`);\n const alignment = integer(member.alignment, `${memberPath}.alignment`, 1);\n const valueSize = nullableInteger(member.valueByteSize, `${memberPath}.valueByteSize`);\n const occupied = nullableInteger(member.occupiedByteSize, `${memberPath}.occupiedByteSize`);\n const explicitAlign = member.explicitAlign === null ? null : integer(member.explicitAlign, `${memberPath}.explicitAlign`, 1);\n const explicitSize = member.explicitSize === null ? null : integer(member.explicitSize, `${memberPath}.explicitSize`, 1);\n const type = typeLayout(member.type, `${memberPath}.type`);\n if (explicitAlign !== null && ((explicitAlign & (explicitAlign - 1)) !== 0 || explicitAlign < type.alignment)) {\n throw new TypeError(`${memberPath}.explicitAlign must be a power of two no smaller than the natural alignment.`);\n }\n if (explicitSize !== null && (type.byteSize === null || explicitSize < type.byteSize)) {\n throw new TypeError(`${memberPath}.explicitSize must not shrink a fixed-size WGSL type.`);\n }\n if (offset < priorEnd || offset % alignment !== 0 || alignment !== (explicitAlign ?? type.alignment)\n || valueSize !== type.byteSize || occupied !== (explicitSize ?? type.byteSize)\n || (occupied !== null && valueSize !== null && occupied < valueSize)) {\n throw new TypeError(`${memberPath} has inconsistent member layout algebra.`);\n }\n if (occupied === null && index !== members.length - 1) throw new TypeError(`${memberPath} is a non-final runtime array.`);\n if (occupied !== null) priorEnd = offset + occupied;\n });\n unique(names, String, `${path}.members`);\n if ((input.byteSize === null) !== (input.runtimeArrayMember !== null)) throw new TypeError(`${path} has inconsistent runtime array metadata.`);\n const maximumAlignment = Math.max(1, ...members.map((value) => Number((value as UnknownRecord).alignment)));\n if (input.alignment !== maximumAlignment) throw new TypeError(`${path}.alignment is inconsistent with its members.`);\n const tail = members.at(-1) as UnknownRecord | undefined;\n const expectedMinimum = input.runtimeArrayMember === null\n ? Math.ceil(priorEnd / Number(input.alignment)) * Number(input.alignment)\n : Number(tail?.offset ?? 0);\n if (input.minimumByteSize !== expectedMinimum || (input.byteSize !== null && input.byteSize !== expectedMinimum)\n || (input.runtimeArrayMember !== null && tail?.name !== input.runtimeArrayMember)) {\n throw new TypeError(`${path} has inconsistent fixed/runtime size metadata.`);\n }\n if (input.runtimeArrayMember !== null) {\n const tailType = tail?.type as GpuTypeLayout | undefined;\n if (!tailType || tailType.kind !== \"array\" || tailType.count !== null) throw new TypeError(`${path}.runtimeArrayMember must name a direct trailing runtime-sized array.`);\n }\n return input as unknown as GpuRecordLayout;\n}\n\nfunction bindingResource(value: unknown, path: string): GpuBindingResourceLayout {\n const input = object(value, path);\n const kind = enumeration(input.kind, [\"buffer\", \"sampler\", \"texture\", \"storage-texture\", \"external-texture\"] as const, `${path}.kind`);\n if (kind === \"buffer\") {\n exact(input, [\"kind\", \"addressSpace\", \"access\", \"recordName\", \"minimumBindingSize\"], path);\n enumeration(input.addressSpace, [\"uniform\", \"storage\"] as const, `${path}.addressSpace`);\n enumeration(input.access, [\"read\", \"write\", \"read_write\"] as const, `${path}.access`);\n if (input.addressSpace === \"uniform\" && input.access !== \"read\") throw new TypeError(`${path}.access must be read for uniform buffers.`);\n nullableToken(input.recordName, `${path}.recordName`);\n integer(input.minimumBindingSize, `${path}.minimumBindingSize`);\n } else if (kind === \"sampler\") {\n exact(input, [\"kind\", \"samplerType\"], path);\n enumeration(input.samplerType, [\"filtering\", \"non-filtering\", \"comparison\"] as const, `${path}.samplerType`);\n } else if (kind === \"texture\") {\n exact(input, [\"kind\", \"sampleType\", \"viewDimension\", \"multisampled\"], path);\n enumeration(input.sampleType, [\"float\", \"unfilterable-float\", \"depth\", \"sint\", \"uint\"] as const, `${path}.sampleType`);\n enumeration(input.viewDimension, [\"1d\", \"2d\", \"2d-array\", \"cube\", \"cube-array\", \"3d\"] as const, `${path}.viewDimension`);\n if (typeof input.multisampled !== \"boolean\") throw new TypeError(`${path}.multisampled must be boolean.`);\n } else if (kind === \"storage-texture\") {\n exact(input, [\"kind\", \"access\", \"format\", \"viewDimension\"], path);\n enumeration(input.access, [\"write-only\", \"read-only\", \"read-write\"] as const, `${path}.access`);\n token(input.format, `${path}.format`);\n enumeration(input.viewDimension, [\"1d\", \"2d\", \"2d-array\", \"3d\"] as const, `${path}.viewDimension`);\n } else exact(input, [\"kind\"], path);\n return input as unknown as GpuBindingResourceLayout;\n}\n\nfunction visibility(value: unknown, path: string): (typeof stages)[number][] {\n const result = array(value, path, 3).map((item, index) => enumeration(item, stages, `${path}[${index}]`));\n unique(result, String, path);\n if (result.length === 0) throw new TypeError(`${path} must include at least one shader stage.`);\n return result;\n}\n\nfunction binding(value: unknown, path: string, coordinates = true): UnknownRecord {\n const input = object(value, path);\n exact(input, coordinates\n ? [\"moduleId\", \"variableName\", \"group\", \"binding\", \"resource\", \"visibility\"]\n : [\"source\", \"resource\", \"semantic\"], path);\n if (coordinates) {\n token(input.moduleId, `${path}.moduleId`); token(input.variableName, `${path}.variableName`);\n integer(input.group, `${path}.group`); integer(input.binding, `${path}.binding`);\n visibility(input.visibility, `${path}.visibility`);\n } else {\n const source = object(input.source, `${path}.source`); exact(source, [\"moduleId\", \"group\", \"binding\"], `${path}.source`);\n token(source.moduleId, `${path}.source.moduleId`); integer(source.group, `${path}.source.group`); integer(source.binding, `${path}.source.binding`);\n nullableToken(input.semantic, `${path}.semantic`);\n }\n bindingResource(input.resource, `${path}.resource`);\n return input;\n}\n\nfunction entryIo(value: unknown, path: string): UnknownRecord {\n const input = object(value, path);\n exact(input, [\"name\", \"locationKind\", \"location\", \"interpolation\", \"type\"], path);\n token(input.name, `${path}.name`);\n const kind = enumeration(input.locationKind, [\"location\", \"builtin\"] as const, `${path}.locationKind`);\n if (kind === \"location\") integer(input.location, `${path}.location`); else token(input.location, `${path}.location`);\n if (input.interpolation !== null) token(input.interpolation, `${path}.interpolation`);\n typeLayout(input.type, `${path}.type`);\n return input;\n}\n\nfunction vertexInput(value: unknown, path: string, model = false): UnknownRecord {\n const input = object(value, path);\n if (model) {\n exact(input, [\"source\", \"format\", \"offset\", \"arrayStride\", \"stepMode\", \"semantic\"], path);\n const source = object(input.source, `${path}.source`); exact(source, [\"pipelineId\", \"shaderLocation\"], `${path}.source`);\n token(source.pipelineId, `${path}.source.pipelineId`); integer(source.shaderLocation, `${path}.source.shaderLocation`);\n token(input.semantic, `${path}.semantic`);\n } else {\n exact(input, [\"pipelineId\", \"moduleId\", \"entryPoint\", \"shaderLocation\", \"shaderType\", \"bufferSlot\", \"format\", \"offset\", \"arrayStride\", \"stepMode\", \"semantic\"], path);\n token(input.pipelineId, `${path}.pipelineId`); token(input.moduleId, `${path}.moduleId`); token(input.entryPoint, `${path}.entryPoint`);\n integer(input.shaderLocation, `${path}.shaderLocation`); typeLayout(input.shaderType, `${path}.shaderType`); integer(input.bufferSlot, `${path}.bufferSlot`);\n nullableToken(input.semantic, `${path}.semantic`);\n }\n token(input.format, `${path}.format`); integer(input.offset, `${path}.offset`); integer(input.arrayStride, `${path}.arrayStride`);\n enumeration(input.stepMode, [\"vertex\", \"instance\"] as const, `${path}.stepMode`);\n return input;\n}\n\nfunction semantic(value: unknown, path: string): UnknownRecord {\n const input = object(value, path); exact(input, [\"semantic\", \"source\"], path); token(input.semantic, `${path}.semantic`);\n const source = object(input.source, `${path}.source`);\n const kind = enumeration(source.kind, [\"record-member\", \"vertex-attribute\", \"binding\"] as const, `${path}.source.kind`);\n if (kind === \"record-member\") {\n exact(source, [\"kind\", \"recordName\", \"memberPath\"], `${path}.source`); token(source.recordName, `${path}.source.recordName`);\n tokenArray(source.memberPath, `${path}.source.memberPath`, 24);\n } else if (kind === \"vertex-attribute\") {\n exact(source, [\"kind\", \"pipelineId\", \"shaderLocation\"], `${path}.source`); token(source.pipelineId, `${path}.source.pipelineId`); integer(source.shaderLocation, `${path}.source.shaderLocation`);\n } else {\n exact(source, [\"kind\", \"moduleId\", \"group\", \"binding\"], `${path}.source`); token(source.moduleId, `${path}.source.moduleId`);\n integer(source.group, `${path}.source.group`); integer(source.binding, `${path}.source.binding`);\n }\n return input;\n}\n\nfunction interfaceRef(value: unknown, path: string): UnknownRecord {\n const input = object(value, path); exact(input, [\"interfaceId\", \"interfaceVersion\", \"manifestUri\", \"manifestSha256\", \"interfaceAbiHash\", \"modelAbiHash\"], path);\n token(input.interfaceId, `${path}.interfaceId`); token(input.interfaceVersion, `${path}.interfaceVersion`); uri(input.manifestUri, `${path}.manifestUri`);\n digest(input.manifestSha256, `${path}.manifestSha256`); digest(input.interfaceAbiHash, `${path}.interfaceAbiHash`); digest(input.modelAbiHash, `${path}.modelAbiHash`);\n return input;\n}\n\nfunction programmable(value: unknown, path: string, moduleIds: ReadonlySet<string>): UnknownRecord {\n const input = object(value, path); exact(input, [\"moduleId\", \"entryPoint\", \"constants\"], path);\n const moduleId = token(input.moduleId, `${path}.moduleId`); if (!moduleIds.has(moduleId)) throw new TypeError(`${path}.moduleId is not in modules.`);\n token(input.entryPoint, `${path}.entryPoint`);\n const constants = object(input.constants, `${path}.constants`);\n for (const [name, value] of Object.entries(constants)) { token(name, `${path}.constants key`); if (typeof value !== \"boolean\") finite(value, `${path}.constants.${name}`); }\n return input;\n}\n\nfunction pipeline(value: unknown, path: string, moduleIds: ReadonlySet<string>): SerializableGpuPipelineDescriptor {\n const input = object(value, path); const kind = enumeration(input.kind, [\"compute\", \"render\"] as const, `${path}.kind`);\n const common = kind === \"compute\" ? [\"kind\", \"pipelineId\", \"layout\", \"compute\"] : [\"kind\", \"pipelineId\", \"layout\", \"vertex\", \"fragment\", \"vertexBuffers\", \"primitive\", \"colorTargets\", \"depthStencil\", \"multisample\"];\n exact(input, common, path); token(input.pipelineId, `${path}.pipelineId`);\n const layout = object(input.layout, `${path}.layout`); exact(layout, [\"bindGroups\"], `${path}.layout`);\n const groups = array(layout.bindGroups, `${path}.layout.bindGroups`);\n const groupIds: number[] = [];\n groups.forEach((value, groupIndex) => {\n const groupPath = `${path}.layout.bindGroups[${groupIndex}]`; const group = object(value, groupPath); exact(group, [\"group\", \"entries\"], groupPath);\n const groupId = integer(group.group, `${groupPath}.group`); groupIds.push(groupId);\n const entries = array(group.entries, `${groupPath}.entries`); const bindingIds: number[] = [];\n entries.forEach((entryValue, entryIndex) => {\n const entryPath = `${groupPath}.entries[${entryIndex}]`; const entry = object(entryValue, entryPath);\n exact(entry, [\"group\", \"binding\", \"resource\", \"visibility\"], entryPath);\n if (integer(entry.group, `${entryPath}.group`) !== groupId) throw new TypeError(`${entryPath}.group differs from its parent.`);\n bindingIds.push(integer(entry.binding, `${entryPath}.binding`)); bindingResource(entry.resource, `${entryPath}.resource`); visibility(entry.visibility, `${entryPath}.visibility`);\n });\n unique(bindingIds, String, `${groupPath}.entries`);\n });\n unique(groupIds, String, `${path}.layout.bindGroups`);\n [...groupIds].sort((a, b) => a - b).forEach((group, index) => { if (group !== index) throw new TypeError(`${path}.layout.bindGroups must be contiguous from zero.`); });\n if (kind === \"compute\") programmable(input.compute, `${path}.compute`, moduleIds);\n else {\n programmable(input.vertex, `${path}.vertex`, moduleIds); if (input.fragment !== null) programmable(input.fragment, `${path}.fragment`, moduleIds);\n array(input.vertexBuffers, `${path}.vertexBuffers`, 16).forEach((value, bufferIndex) => {\n const bufferPath = `${path}.vertexBuffers[${bufferIndex}]`; const buffer = object(value, bufferPath); exact(buffer, [\"arrayStride\", \"stepMode\", \"attributes\"], bufferPath);\n integer(buffer.arrayStride, `${bufferPath}.arrayStride`, 0, 2048); enumeration(buffer.stepMode, [\"vertex\", \"instance\"] as const, `${bufferPath}.stepMode`);\n array(buffer.attributes, `${bufferPath}.attributes`, 16).forEach((value, attributeIndex) => {\n const attributePath = `${bufferPath}.attributes[${attributeIndex}]`; const attribute = object(value, attributePath); exact(attribute, [\"format\", \"offset\", \"shaderLocation\", \"semantic\"], attributePath);\n token(attribute.format, `${attributePath}.format`); integer(attribute.offset, `${attributePath}.offset`); integer(attribute.shaderLocation, `${attributePath}.shaderLocation`); nullableToken(attribute.semantic, `${attributePath}.semantic`);\n });\n });\n const primitive = object(input.primitive, `${path}.primitive`); exact(primitive, [\"topology\", \"stripIndexFormat\", \"frontFace\", \"cullMode\", \"unclippedDepth\"], `${path}.primitive`);\n const topology = enumeration(primitive.topology, [\"point-list\", \"line-list\", \"line-strip\", \"triangle-list\", \"triangle-strip\"] as const, `${path}.primitive.topology`);\n if (primitive.stripIndexFormat !== null) enumeration(primitive.stripIndexFormat, [\"uint16\", \"uint32\"] as const, `${path}.primitive.stripIndexFormat`);\n if (primitive.stripIndexFormat !== null && topology !== \"line-strip\" && topology !== \"triangle-strip\") throw new TypeError(`${path}.primitive.stripIndexFormat is only valid for strip topologies.`);\n enumeration(primitive.frontFace, [\"ccw\", \"cw\"] as const, `${path}.primitive.frontFace`); enumeration(primitive.cullMode, [\"none\", \"front\", \"back\"] as const, `${path}.primitive.cullMode`); if (typeof primitive.unclippedDepth !== \"boolean\") throw new TypeError(`${path}.primitive.unclippedDepth must be boolean.`);\n const compare = [\"never\", \"less\", \"equal\", \"less-equal\", \"greater\", \"not-equal\", \"greater-equal\", \"always\"] as const;\n const operations = [\"keep\", \"zero\", \"replace\", \"invert\", \"increment-clamp\", \"decrement-clamp\", \"increment-wrap\", \"decrement-wrap\"] as const;\n const factors = [\"zero\", \"one\", \"src\", \"one-minus-src\", \"src-alpha\", \"one-minus-src-alpha\", \"dst\", \"one-minus-dst\", \"dst-alpha\", \"one-minus-dst-alpha\", \"src-alpha-saturated\", \"constant\", \"one-minus-constant\"] as const;\n const parseBlend = (value: unknown, label: string): void => { const component = object(value, label); exact(component, [\"operation\", \"srcFactor\", \"dstFactor\"], label); enumeration(component.operation, [\"add\", \"subtract\", \"reverse-subtract\", \"min\", \"max\"] as const, `${label}.operation`); enumeration(component.srcFactor, factors, `${label}.srcFactor`); enumeration(component.dstFactor, factors, `${label}.dstFactor`); };\n const colorTargets = array(input.colorTargets, `${path}.colorTargets`, 8); if (input.fragment === null && colorTargets.length !== 0) throw new TypeError(`${path}.colorTargets must be empty when fragment is null.`); colorTargets.forEach((value, index) => { const label = `${path}.colorTargets[${index}]`; const target = object(value, label); exact(target, [\"format\", \"blend\", \"writeMask\"], label); token(target.format, `${label}.format`); integer(target.writeMask, `${label}.writeMask`, 0, 15); if (target.blend !== null) { const blend = object(target.blend, `${label}.blend`); exact(blend, [\"color\", \"alpha\"], `${label}.blend`); parseBlend(blend.color, `${label}.blend.color`); parseBlend(blend.alpha, `${label}.blend.alpha`); } });\n const parseStencil = (value: unknown, label: string): void => { const stencil = object(value, label); exact(stencil, [\"compare\", \"failOp\", \"depthFailOp\", \"passOp\"], label); enumeration(stencil.compare, compare, `${label}.compare`); enumeration(stencil.failOp, operations, `${label}.failOp`); enumeration(stencil.depthFailOp, operations, `${label}.depthFailOp`); enumeration(stencil.passOp, operations, `${label}.passOp`); };\n if (input.depthStencil !== null) { const depth = object(input.depthStencil, `${path}.depthStencil`); exact(depth, [\"format\", \"depthWriteEnabled\", \"depthCompare\", \"stencilFront\", \"stencilBack\", \"stencilReadMask\", \"stencilWriteMask\", \"depthBias\", \"depthBiasSlopeScale\", \"depthBiasClamp\"], `${path}.depthStencil`); token(depth.format, `${path}.depthStencil.format`); if (typeof depth.depthWriteEnabled !== \"boolean\") throw new TypeError(`${path}.depthStencil.depthWriteEnabled must be boolean.`); enumeration(depth.depthCompare, compare, `${path}.depthStencil.depthCompare`); parseStencil(depth.stencilFront, `${path}.depthStencil.stencilFront`); parseStencil(depth.stencilBack, `${path}.depthStencil.stencilBack`); integer(depth.stencilReadMask, `${path}.depthStencil.stencilReadMask`); integer(depth.stencilWriteMask, `${path}.depthStencil.stencilWriteMask`); integer(depth.depthBias, `${path}.depthStencil.depthBias`, -0x8000_0000, 0x7fff_ffff); finite(depth.depthBiasSlopeScale, `${path}.depthStencil.depthBiasSlopeScale`); finite(depth.depthBiasClamp, `${path}.depthStencil.depthBiasClamp`); }\n const multisample = object(input.multisample, `${path}.multisample`); exact(multisample, [\"count\", \"mask\", \"alphaToCoverageEnabled\"], `${path}.multisample`); enumeration(multisample.count, [1, 4] as const, `${path}.multisample.count`); integer(multisample.mask, `${path}.multisample.mask`); if (typeof multisample.alphaToCoverageEnabled !== \"boolean\") throw new TypeError(`${path}.multisample.alphaToCoverageEnabled must be boolean.`); if (multisample.alphaToCoverageEnabled && multisample.count === 1) throw new TypeError(`${path}.multisample.alphaToCoverageEnabled requires multisampling.`);\n }\n return input as unknown as SerializableGpuPipelineDescriptor;\n}\n\nexport function parseSerializableGpuPipelineDescriptors(\n value: unknown,\n moduleIds: readonly string[],\n path = \"pipelines\",\n): readonly SerializableGpuPipelineDescriptor[] {\n const parsed = array(value, path).map((item, index) => pipeline(item, `${path}[${index}]`, new Set(moduleIds)));\n unique(parsed, (item) => item.pipelineId, path);\n return freeze(parsed);\n}\n\nfunction compatibleModel(value: unknown, path: string): UnknownRecord {\n const input = object(value, path); exact(input, [\"interfaceId\", \"interfaceVersion\", \"manifestSha256\", \"interfaceAbiHash\", \"modelAbiHash\"], path);\n token(input.interfaceId, `${path}.interfaceId`); token(input.interfaceVersion, `${path}.interfaceVersion`); digest(input.manifestSha256, `${path}.manifestSha256`); digest(input.interfaceAbiHash, `${path}.interfaceAbiHash`); digest(input.modelAbiHash, `${path}.modelAbiHash`); return input;\n}\n\nfunction validationEvidenceRef(value: unknown, path: string): UnknownRecord {\n const evidence = object(value, path);\n exact(evidence, [\"evidenceId\", \"uri\", \"sha256\", \"matrixId\", \"matrixVersion\", \"matrixSha256\", \"attestationRef\"], path);\n token(evidence.evidenceId, `${path}.evidenceId`);\n uri(evidence.uri, `${path}.uri`);\n digest(evidence.sha256, `${path}.sha256`);\n token(evidence.matrixId, `${path}.matrixId`);\n token(evidence.matrixVersion, `${path}.matrixVersion`);\n digest(evidence.matrixSha256, `${path}.matrixSha256`);\n const attestation = object(evidence.attestationRef, `${path}.attestationRef`);\n exact(attestation, [\"uri\", \"sha256\"], `${path}.attestationRef`);\n uri(attestation.uri, `${path}.attestationRef.uri`);\n digest(attestation.sha256, `${path}.attestationRef.sha256`);\n if (evidence.uri === attestation.uri || evidence.sha256 === attestation.sha256) {\n throw new TypeError(`${path} evidence and attestation artifacts must have distinct URIs and digests.`);\n }\n return evidence;\n}\n\nfunction freeze<T>(value: T): T {\n if (typeof value !== \"object\" || value === null || Object.isFrozen(value)) return value;\n for (const child of Object.values(value as Record<string, unknown>)) freeze(child);\n return Object.freeze(value);\n}\n\nfunction reflectedRecordBindingSize(record: GpuRecordLayout): number {\n if (record.byteSize !== null) return record.byteSize;\n if (record.runtimeArrayMember === null) throw new TypeError(`Record ${record.name} has inconsistent runtime-array metadata.`);\n const member = record.members.find((candidate) => candidate.name === record.runtimeArrayMember);\n if (!member || member.type.kind !== \"array\" || member.type.count !== null) {\n throw new TypeError(`Record ${record.name} has invalid trailing runtime-array metadata.`);\n }\n const unrounded = member.offset + member.type.stride;\n return Math.ceil(unrounded / record.alignment) * record.alignment;\n}\n\n/** Strictly parses untrusted reflected interface JSON and validates all nested references. */\nexport function parseGpuInterfaceManifest(value: unknown): GpuInterfaceManifest {\n const input = object(value, \"GpuInterfaceManifest\");\n exact(input, [\"contractVersion\", \"interfaceId\", \"interfaceVersion\", \"modules\", \"records\", \"bindings\", \"entryPoints\", \"vertexInputs\", \"overrides\", \"modelAbi\", \"modelAbiHash\", \"interfaceAbiHash\", \"generatedBy\"], \"GpuInterfaceManifest\");\n if (input.contractVersion !== GPU_INTERFACE_MANIFEST_VERSION) throw new TypeError(\"Unsupported GPU interface contract version.\");\n token(input.interfaceId, \"GpuInterfaceManifest.interfaceId\"); token(input.interfaceVersion, \"GpuInterfaceManifest.interfaceVersion\");\n const moduleValues = array(input.modules, \"GpuInterfaceManifest.modules\");\n if (moduleValues.length === 0) throw new TypeError(\"GpuInterfaceManifest.modules must not be empty.\");\n const moduleIds = moduleValues.map((value, index) => { const path = `GpuInterfaceManifest.modules[${index}]`; const module = object(value, path); exact(module, [\"moduleId\", \"sha256\"], path); digest(module.sha256, `${path}.sha256`); return token(module.moduleId, `${path}.moduleId`); });\n unique(moduleIds, String, \"GpuInterfaceManifest.modules\"); const moduleSet = new Set(moduleIds);\n const recordValues = array(input.records, \"GpuInterfaceManifest.records\"); const parsedRecords = recordValues.map((item, index) => recordLayout(item, `GpuInterfaceManifest.records[${index}]`));\n unique(parsedRecords, (item) => item.name, \"GpuInterfaceManifest.records\"); const records = new Map(parsedRecords.map((item) => [item.name, item]));\n for (const record of parsedRecords) for (const member of record.members) {\n const visit = (type: GpuTypeLayout): void => { if (type.kind === \"record\") { const referenced = records.get(type.recordName); if (!referenced) throw new TypeError(`Record ${record.name} references missing ${type.recordName}.`); if (type.alignment !== referenced.alignment || type.byteSize !== referenced.byteSize) throw new TypeError(`Record reference ${record.name}.${member.name} has stale layout metadata.`); } if (type.kind === \"array\") visit(type.element); };\n visit(member.type);\n }\n const bindingValues = array(input.bindings, \"GpuInterfaceManifest.bindings\"); const bindingKeys: string[] = [];\n bindingValues.forEach((item, index) => { const path = `GpuInterfaceManifest.bindings[${index}]`; const parsed = binding(item, path); const moduleId = String(parsed.moduleId); if (!moduleSet.has(moduleId)) throw new TypeError(`${path}.moduleId is missing.`); bindingKeys.push(`${moduleId}:${parsed.group}:${parsed.binding}`); const resource = parsed.resource as GpuBindingResourceLayout; if (resource.kind === \"buffer\" && resource.recordName) { const record = records.get(resource.recordName); if (!record) throw new TypeError(`${path} references missing record.`); if (resource.minimumBindingSize !== reflectedRecordBindingSize(record)) throw new TypeError(`${path}.resource.minimumBindingSize differs from its reflected record.`); if (record.runtimeArrayMember !== null && resource.addressSpace !== \"storage\") throw new TypeError(`${path} exposes a runtime-sized array outside storage.`); } });\n unique(bindingKeys, String, \"GpuInterfaceManifest.bindings\"); const bindingSet = new Set(bindingKeys);\n const overrideValues = array(input.overrides, \"GpuInterfaceManifest.overrides\"); const overrideKeys: string[] = []; const overrideIds: string[] = [];\n overrideValues.forEach((item, index) => { const path = `GpuInterfaceManifest.overrides[${index}]`; const override = object(item, path); exact(override, [\"moduleId\", \"name\", \"id\", \"type\", \"defaultValue\"], path); const moduleId = token(override.moduleId, `${path}.moduleId`); if (!moduleSet.has(moduleId)) throw new TypeError(`${path}.moduleId is missing.`); const name = token(override.name, `${path}.name`); overrideKeys.push(`${moduleId}:${name}`); if (override.id !== null) overrideIds.push(`${moduleId}:${integer(override.id, `${path}.id`)}`); enumeration(override.type, [\"bool\", \"i32\", \"u32\", \"f32\", \"f16\"] as const, `${path}.type`); if (override.defaultValue !== null && typeof override.defaultValue !== \"boolean\") finite(override.defaultValue, `${path}.defaultValue`); });\n unique(overrideKeys, String, \"GpuInterfaceManifest.overrides\"); unique(overrideIds, String, \"GpuInterfaceManifest.overrides ids\"); const overrideSet = new Set(overrideKeys);\n const entryValues = array(input.entryPoints, \"GpuInterfaceManifest.entryPoints\"); const entryKeys: string[] = [];\n if (entryValues.length === 0) throw new TypeError(\"GpuInterfaceManifest.entryPoints must not be empty.\");\n entryValues.forEach((item, index) => { const path = `GpuInterfaceManifest.entryPoints[${index}]`; const entry = object(item, path); exact(entry, [\"moduleId\", \"name\", \"stage\", \"inputs\", \"outputs\", \"bindingKeys\", \"overrideNames\", \"workgroupSize\", \"workgroupStorageSize\"], path); const moduleId = token(entry.moduleId, `${path}.moduleId`); if (!moduleSet.has(moduleId)) throw new TypeError(`${path}.moduleId is missing.`); const stage = enumeration(entry.stage, stages, `${path}.stage`); entryKeys.push(`${moduleId}:${stage}:${token(entry.name, `${path}.name`)}`); for (const ioKey of [\"inputs\", \"outputs\"] as const) { const ios = array(entry[ioKey], `${path}.${ioKey}`).map((value, ioIndex) => entryIo(value, `${path}.${ioKey}[${ioIndex}]`)); unique(ios, (io) => `${io.locationKind}:${io.location}`, `${path}.${ioKey}`); } const resources = tokenArray(entry.bindingKeys, `${path}.bindingKeys`); resources.forEach((key) => { if (!bindingSet.has(key)) throw new TypeError(`${path}.bindingKeys references missing ${key}.`); }); const names = tokenArray(entry.overrideNames, `${path}.overrideNames`); names.forEach((name) => { if (!overrideSet.has(`${moduleId}:${name}`)) throw new TypeError(`${path}.overrideNames references missing ${name}.`); }); if (stage === \"compute\") { const dimensions = array(entry.workgroupSize, `${path}.workgroupSize`, 3); if (dimensions.length !== 3) throw new TypeError(`${path}.workgroupSize must have three dimensions.`); dimensions.forEach((value, dimensionIndex) => { const dimensionPath = `${path}.workgroupSize[${dimensionIndex}]`; const dimension = object(value, dimensionPath); const kind = enumeration(dimension.kind, [\"literal\", \"override\"] as const, `${dimensionPath}.kind`); if (kind === \"literal\") { exact(dimension, [\"kind\", \"value\"], dimensionPath); integer(dimension.value, `${dimensionPath}.value`, 1); } else { exact(dimension, [\"kind\", \"name\"], dimensionPath); const name = token(dimension.name, `${dimensionPath}.name`); if (!overrideSet.has(`${moduleId}:${name}`)) throw new TypeError(`${dimensionPath} references missing override.`); } }); integer(entry.workgroupStorageSize, `${path}.workgroupStorageSize`); } else if (entry.workgroupSize !== null || entry.workgroupStorageSize !== null) throw new TypeError(`${path} workgroup metadata is only valid for compute.`); });\n unique(entryKeys, String, \"GpuInterfaceManifest.entryPoints\"); const entrySet = new Set(entryKeys);\n const vertexValues = array(input.vertexInputs, \"GpuInterfaceManifest.vertexInputs\"); const vertexKeys: string[] = []; const parsedVertices: UnknownRecord[] = [];\n vertexValues.forEach((item, index) => { const path = `GpuInterfaceManifest.vertexInputs[${index}]`; const vertex = vertexInput(item, path); parsedVertices.push(vertex); if (!entrySet.has(`${vertex.moduleId}:vertex:${vertex.entryPoint}`)) throw new TypeError(`${path} references missing vertex entry point.`); vertexKeys.push(`${vertex.pipelineId}:${vertex.shaderLocation}`); }); unique(vertexKeys, String, \"GpuInterfaceManifest.vertexInputs\");\n const model = object(input.modelAbi, \"GpuInterfaceManifest.modelAbi\"); exact(model, [\"recordNames\", \"bindings\", \"vertexInputs\", \"semantics\"], \"GpuInterfaceManifest.modelAbi\");\n tokenArray(model.recordNames, \"GpuInterfaceManifest.modelAbi.recordNames\").forEach((name) => { if (!records.has(name)) throw new TypeError(`Model ABI references missing record ${name}.`); });\n const modelBindings = array(model.bindings, \"GpuInterfaceManifest.modelAbi.bindings\").map((item, index) => binding(item, `GpuInterfaceManifest.modelAbi.bindings[${index}]`, false));\n for (const [index, projected] of modelBindings.entries()) { const source = projected.source as UnknownRecord; const reflectedIndex = bindingKeys.indexOf(`${source.moduleId}:${source.group}:${source.binding}`); const reflected = reflectedIndex < 0 ? null : object(bindingValues[reflectedIndex], `GpuInterfaceManifest.bindings[${reflectedIndex}]`); if (!reflected || canonicalizeForValidation(reflected.resource) !== canonicalizeForValidation(projected.resource)) throw new TypeError(`GpuInterfaceManifest.modelAbi.bindings[${index}] differs from its reflected source.`); const resource = projected.resource as GpuBindingResourceLayout; if (resource.kind === \"buffer\" && resource.recordName === null) throw new TypeError(`GpuInterfaceManifest.modelAbi.bindings[${index}] must use a named WGSL record root.`); }\n const modelBindingSemantics = modelBindings.filter((item) => item.semantic !== null).map((item) => String(item.semantic)); unique(modelBindingSemantics, String, \"GpuInterfaceManifest.modelAbi.bindings semantics\");\n const modelVertices = array(model.vertexInputs, \"GpuInterfaceManifest.modelAbi.vertexInputs\"); const parsedModelVertices = modelVertices.map((item, index) => vertexInput(item, `GpuInterfaceManifest.modelAbi.vertexInputs[${index}]`, true)); const modelVertexSemantics = parsedModelVertices.map((item) => String(item.semantic)); unique(modelVertexSemantics, String, \"GpuInterfaceManifest.modelAbi.vertexInputs\");\n for (const [index, projected] of parsedModelVertices.entries()) { const source = projected.source as UnknownRecord; const reflected = parsedVertices.find((candidate) => candidate.pipelineId === source.pipelineId && candidate.shaderLocation === source.shaderLocation); if (!reflected || [\"format\", \"offset\", \"arrayStride\", \"stepMode\", \"semantic\"].some((key) => reflected[key] !== projected[key])) throw new TypeError(`GpuInterfaceManifest.modelAbi.vertexInputs[${index}] differs from its reflected source.`); }\n const semantics = array(model.semantics, \"GpuInterfaceManifest.modelAbi.semantics\").map((item, index) => semantic(item, `GpuInterfaceManifest.modelAbi.semantics[${index}]`)); unique(semantics, (item) => String(item.semantic), \"GpuInterfaceManifest.modelAbi.semantics\");\n for (const projection of semantics) {\n const source = projection.source as UnknownRecord; const semanticName = String(projection.semantic);\n if (source.kind === \"record-member\") {\n let current = records.get(String(source.recordName)); if (!current) throw new TypeError(`Semantic ${semanticName} references missing record.`);\n for (const [index, memberName] of (source.memberPath as string[]).entries()) { const member = current.members.find((candidate) => candidate.name === memberName); if (!member) throw new TypeError(`Semantic ${semanticName} references missing member ${memberName}.`); if (index < (source.memberPath as string[]).length - 1) { if (member.type.kind !== \"record\") throw new TypeError(`Semantic ${semanticName} traverses a non-record member.`); current = records.get(member.type.recordName); if (!current) throw new TypeError(`Semantic ${semanticName} references missing nested record.`); } }\n } else if (source.kind === \"vertex-attribute\") {\n const vertex = parsedVertices.find((candidate) => candidate.pipelineId === source.pipelineId && candidate.shaderLocation === source.shaderLocation);\n const modelVertex = parsedModelVertices.find((candidate) => candidate.semantic === semanticName);\n const modelVertexSource = modelVertex?.source as UnknownRecord | undefined;\n if (!vertex || vertex.semantic !== semanticName || modelVertexSemantics.filter((item) => item === semanticName).length !== 1\n || !modelVertexSource || modelVertexSource.pipelineId !== source.pipelineId || modelVertexSource.shaderLocation !== source.shaderLocation) throw new TypeError(`Semantic ${semanticName} does not resolve to exactly one matching model vertex stream.`);\n } else {\n const key = `${source.moduleId}:${source.group}:${source.binding}`; if (!bindingSet.has(key)) throw new TypeError(`Semantic ${semanticName} references missing binding ${key}.`);\n const modelBinding = modelBindings.find((candidate) => candidate.semantic === semanticName);\n if (modelBindingSemantics.filter((item) => item === semanticName).length !== 1 || !modelBinding\n || canonicalizeForValidation(modelBinding.source) !== canonicalizeForValidation({ moduleId: source.moduleId, group: source.group, binding: source.binding })) throw new TypeError(`Semantic ${semanticName} does not resolve to exactly one matching model binding.`);\n }\n }\n for (const semanticName of [...modelVertexSemantics, ...modelBindingSemantics]) if (semantics.filter((item) => item.semantic === semanticName).length !== 1) throw new TypeError(`Model semantic ${semanticName} requires exactly one projection.`);\n digest(input.modelAbiHash, \"GpuInterfaceManifest.modelAbiHash\"); digest(input.interfaceAbiHash, \"GpuInterfaceManifest.interfaceAbiHash\");\n const generated = object(input.generatedBy, \"GpuInterfaceManifest.generatedBy\"); exact(generated, [\"packageVersion\", \"reflector\", \"reflectorVersion\"], \"GpuInterfaceManifest.generatedBy\"); token(generated.packageVersion, \"GpuInterfaceManifest.generatedBy.packageVersion\"); if (generated.reflector !== \"wgsl_reflect\" || generated.reflectorVersion !== \"1.5.0\") throw new TypeError(\"Unsupported reflector provenance.\");\n return freeze(input as unknown as GpuInterfaceManifest);\n}\n\n/** Strictly parses an immutable shader-version manifest. */\nexport function parseShaderVersionManifest(value: unknown): ShaderVersionManifest {\n const input = object(value, \"ShaderVersionManifest\"); exact(input, [\"contractVersion\", \"shaderId\", \"version\", \"modules\", \"gpuInterface\", \"pipelines\", \"renderRoles\", \"compatibleModelInterfaces\", \"requirements\", \"shaderAbiHash\", \"validationEvidence\", \"additionalValidationEvidence\"], \"ShaderVersionManifest\");\n if (input.contractVersion !== SHADER_VERSION_MANIFEST_VERSION) throw new TypeError(\"Unsupported shader manifest contract version.\");\n token(input.shaderId, \"ShaderVersionManifest.shaderId\"); token(input.version, \"ShaderVersionManifest.version\");\n const moduleValues = array(input.modules, \"ShaderVersionManifest.modules\"); if (moduleValues.length === 0) throw new TypeError(\"ShaderVersionManifest.modules must not be empty.\"); const moduleIds = moduleValues.map((item, index) => { const path = `ShaderVersionManifest.modules[${index}]`; const module = object(item, path); exact(module, [\"moduleId\", \"uri\", \"byteLength\", \"sha256\", \"contentType\"], path); uri(module.uri, `${path}.uri`); integer(module.byteLength, `${path}.byteLength`, 1); digest(module.sha256, `${path}.sha256`); if (module.contentType !== \"text/wgsl; charset=utf-8\") throw new TypeError(`${path}.contentType is not canonical WGSL.`); return token(module.moduleId, `${path}.moduleId`); }); unique(moduleIds, String, \"ShaderVersionManifest.modules\"); const moduleSet = new Set(moduleIds);\n const shaderInterface = interfaceRef(input.gpuInterface, \"ShaderVersionManifest.gpuInterface\");\n const pipelines = array(input.pipelines, \"ShaderVersionManifest.pipelines\").map((item, index) => pipeline(item, `ShaderVersionManifest.pipelines[${index}]`, moduleSet)); if (pipelines.length === 0) throw new TypeError(\"ShaderVersionManifest.pipelines must not be empty.\"); unique(pipelines, (item) => item.pipelineId, \"ShaderVersionManifest.pipelines\"); const pipelineIds = new Set(pipelines.map((item) => item.pipelineId));\n const roleValues = array(input.renderRoles, \"ShaderVersionManifest.renderRoles\", 5); if (roleValues.length === 0) throw new TypeError(\"ShaderVersionManifest.renderRoles must not be empty.\"); const roleNames: string[] = []; const assigned = new Set<string>(); roleValues.forEach((item, index) => { const path = `ShaderVersionManifest.renderRoles[${index}]`; const role = object(item, path); exact(role, [\"role\", \"pipelineIds\"], path); roleNames.push(enumeration(role.role, roles, `${path}.role`)); const ids = tokenArray(role.pipelineIds, `${path}.pipelineIds`); if (ids.length === 0) throw new TypeError(`${path}.pipelineIds must not be empty.`); ids.forEach((id) => { if (!pipelineIds.has(id)) throw new TypeError(`${path} references missing pipeline ${id}.`); assigned.add(id); }); }); unique(roleNames, String, \"ShaderVersionManifest.renderRoles\"); if (assigned.size !== pipelineIds.size) throw new TypeError(\"Every pipeline must belong to at least one render role.\");\n const compatible = array(input.compatibleModelInterfaces, \"ShaderVersionManifest.compatibleModelInterfaces\").map((item, index) => compatibleModel(item, `ShaderVersionManifest.compatibleModelInterfaces[${index}]`)); if (compatible.length === 0) throw new TypeError(\"ShaderVersionManifest.compatibleModelInterfaces must not be empty.\"); unique(compatible, (item) => `${item.interfaceId}:${item.interfaceVersion}:${item.manifestSha256}:${item.interfaceAbiHash}:${item.modelAbiHash}`, \"ShaderVersionManifest.compatibleModelInterfaces\"); if (compatible.some((item) => item.modelAbiHash !== shaderInterface.modelAbiHash)) throw new TypeError(\"ShaderVersionManifest compatible model ABI hashes must equal gpuInterface.modelAbiHash.\");\n const requirements = object(input.requirements, \"ShaderVersionManifest.requirements\"); exact(requirements, [\"semantics\", \"features\", \"limits\", \"formats\"], \"ShaderVersionManifest.requirements\"); tokenArray(requirements.semantics, \"ShaderVersionManifest.requirements.semantics\"); tokenArray(requirements.features, \"ShaderVersionManifest.requirements.features\"); tokenArray(requirements.formats, \"ShaderVersionManifest.requirements.formats\"); const limits = array(requirements.limits, \"ShaderVersionManifest.requirements.limits\"); const limitNames: string[] = []; limits.forEach((item, index) => { const path = `ShaderVersionManifest.requirements.limits[${index}]`; const limit = object(item, path); exact(limit, [\"name\", \"comparator\", \"value\"], path); const name = token(limit.name, `${path}.name`); limitNames.push(name); enumeration(limit.comparator, [\"at-least\", \"at-most\"] as const, `${path}.comparator`); const value = finite(limit.value, `${path}.value`); if (!Number.isSafeInteger(value) || value < 0) throw new TypeError(`${path}.value must be a non-negative safe integer.`); }); unique(limitNames, String, \"ShaderVersionManifest.requirements.limits\");\n validatePipelineDerivedRequirements({\n requirements: input.requirements as unknown as ShaderVersionManifest[\"requirements\"],\n pipelines,\n });\n digest(input.shaderAbiHash, \"ShaderVersionManifest.shaderAbiHash\");\n const universalEvidence = validationEvidenceRef(input.validationEvidence, \"ShaderVersionManifest.validationEvidence\");\n if (!SUPPORTED_STABLE_WEBGPU_MATRIX_POLICIES.some((policy) =>\n universalEvidence.matrixId === policy.matrixId\n && universalEvidence.matrixVersion === policy.matrixVersion\n && universalEvidence.matrixSha256 === policy.matrixSha256)) {\n throw new TypeError(\"ShaderVersionManifest.validationEvidence is not bound to a supported universal stable-WebGPU matrix policy.\");\n }\n const additionalEvidence = array(input.additionalValidationEvidence, \"ShaderVersionManifest.additionalValidationEvidence\");\n const scopedEvidence = additionalEvidence.map((item, index) => {\n const path = `ShaderVersionManifest.additionalValidationEvidence[${index}]`;\n const scoped = object(item, path);\n exact(scoped, [\"scope\", \"evidence\"], path);\n const scope = token(scoped.scope, `${path}.scope`);\n if (scope === \"universal\") throw new TypeError(`${path}.scope universal is reserved for validationEvidence.`);\n const evidence = validationEvidenceRef(scoped.evidence, `${path}.evidence`);\n if (evidence.matrixSha256 === universalEvidence.matrixSha256) {\n throw new TypeError(`${path}.evidence must use an additive matrix policy, not the universal matrix policy.`);\n }\n return { scope, evidence };\n });\n unique(scopedEvidence, (item) => item.scope, \"ShaderVersionManifest.additionalValidationEvidence scopes\");\n unique(scopedEvidence, (item) => String(item.evidence.matrixSha256), \"ShaderVersionManifest.additionalValidationEvidence matrix policies\");\n const evidenceIds = new Set([String(universalEvidence.evidenceId)]);\n const artifactUris = new Set([\n String(universalEvidence.uri),\n String((universalEvidence.attestationRef as UnknownRecord).uri),\n ]);\n const artifactDigests = new Set([\n String(universalEvidence.sha256),\n String((universalEvidence.attestationRef as UnknownRecord).sha256),\n ]);\n for (const [index, item] of scopedEvidence.entries()) {\n const path = `ShaderVersionManifest.additionalValidationEvidence[${index}].evidence`;\n if (evidenceIds.has(String(item.evidence.evidenceId))) throw new TypeError(`${path} reuses a universal or supplemental evidence ID.`);\n evidenceIds.add(String(item.evidence.evidenceId));\n const attestation = item.evidence.attestationRef as UnknownRecord;\n for (const candidate of [item.evidence.uri, attestation.uri]) {\n if (artifactUris.has(String(candidate))) throw new TypeError(`${path} reuses a universal or supplemental evidence/attestation URI.`);\n artifactUris.add(String(candidate));\n }\n for (const candidate of [item.evidence.sha256, attestation.sha256]) {\n if (artifactDigests.has(String(candidate))) throw new TypeError(`${path} reuses a universal or supplemental evidence/attestation digest.`);\n artifactDigests.add(String(candidate));\n }\n }\n for (const [index, item] of scopedEvidence.entries()) if (!SUPPORTED_ADDITIVE_WEBGPU_MATRIX_POLICIES.some((policy) =>\n item.scope === policy.scope\n && item.evidence.matrixId === policy.matrixId\n && item.evidence.matrixVersion === policy.matrixVersion\n && item.evidence.matrixSha256 === policy.matrixSha256)) {\n throw new TypeError(`ShaderVersionManifest.additionalValidationEvidence[${index}].evidence is not bound to a supported additive WebGPU matrix policy.`);\n }\n return freeze(input as unknown as ShaderVersionManifest);\n}\n\n/** Strictly parses the cycle-free shader manifest qualified before evidence attachment. */\nexport function parseShaderVersionManifestCore(value: unknown): ShaderVersionManifestCore {\n const input = object(value, \"ShaderVersionManifestCore\");\n if (\"validationEvidence\" in input || \"additionalValidationEvidence\" in input) {\n throw new TypeError(\"ShaderVersionManifestCore must not contain validationEvidence or additionalValidationEvidence.\");\n }\n const parsed = parseShaderVersionManifest({\n ...input,\n validationEvidence: {\n evidenceId: \"pending\",\n uri: \"https://catalog.invalid/evidence/pending.json\",\n sha256: \"0\".repeat(64),\n matrixId: SUPPORTED_STABLE_WEBGPU_MATRIX_POLICIES[0].matrixId,\n matrixVersion: SUPPORTED_STABLE_WEBGPU_MATRIX_POLICIES[0].matrixVersion,\n matrixSha256: SUPPORTED_STABLE_WEBGPU_MATRIX_POLICIES[0].matrixSha256,\n attestationRef: {\n uri: \"https://catalog.invalid/evidence/pending.attestation-ref.json\",\n sha256: \"1\".repeat(64),\n },\n },\n additionalValidationEvidence: [],\n });\n const { validationEvidence, additionalValidationEvidence, ...core } = parsed;\n void validationEvidence;\n void additionalValidationEvidence;\n return freeze(core);\n}\n\n/** Strictly parses a rendering-style profile with exact immutable shader references. */\nexport function parseShaderStyleProfileManifest(value: unknown): ShaderStyleProfileManifest {\n const input = object(value, \"ShaderStyleProfileManifest\"); exact(input, [\"contractVersion\", \"profileId\", \"version\", \"style\", \"roles\", \"compatibleModelInterfaces\", \"requiredSemantics\", \"requiredValidationScopes\"], \"ShaderStyleProfileManifest\");\n if (input.contractVersion !== SHADER_STYLE_PROFILE_MANIFEST_VERSION) throw new TypeError(\"Unsupported style-profile contract version.\");\n token(input.profileId, \"ShaderStyleProfileManifest.profileId\"); token(input.version, \"ShaderStyleProfileManifest.version\"); token(input.style, \"ShaderStyleProfileManifest.style\");\n const roleValues = array(input.roles, \"ShaderStyleProfileManifest.roles\", 5); if (roleValues.length === 0) throw new TypeError(\"ShaderStyleProfileManifest.roles must not be empty.\"); const roleNames: string[] = []; roleValues.forEach((item, index) => { const path = `ShaderStyleProfileManifest.roles[${index}]`; const role = object(item, path); exact(role, [\"role\", \"shader\"], path); roleNames.push(enumeration(role.role, roles, `${path}.role`)); const shader = object(role.shader, `${path}.shader`); exact(shader, [\"shaderId\", \"version\", \"manifestUri\", \"manifestSha256\"], `${path}.shader`); token(shader.shaderId, `${path}.shader.shaderId`); token(shader.version, `${path}.shader.version`); uri(shader.manifestUri, `${path}.shader.manifestUri`); digest(shader.manifestSha256, `${path}.shader.manifestSha256`); }); unique(roleNames, String, \"ShaderStyleProfileManifest.roles\");\n const compatible = array(input.compatibleModelInterfaces, \"ShaderStyleProfileManifest.compatibleModelInterfaces\").map((item, index) => compatibleModel(item, `ShaderStyleProfileManifest.compatibleModelInterfaces[${index}]`)); if (compatible.length === 0) throw new TypeError(\"ShaderStyleProfileManifest.compatibleModelInterfaces must not be empty.\"); unique(compatible, (item) => `${item.interfaceId}:${item.interfaceVersion}:${item.manifestSha256}:${item.interfaceAbiHash}:${item.modelAbiHash}`, \"ShaderStyleProfileManifest.compatibleModelInterfaces\"); tokenArray(input.requiredSemantics, \"ShaderStyleProfileManifest.requiredSemantics\");\n const requiredValidationScopes = array(input.requiredValidationScopes, \"ShaderStyleProfileManifest.requiredValidationScopes\").map((item, index) => {\n const path = `ShaderStyleProfileManifest.requiredValidationScopes[${index}]`;\n const requirement = object(item, path);\n exact(requirement, [\"scope\", \"matrixId\", \"matrixVersion\", \"matrixSha256\"], path);\n const scope = token(requirement.scope, `${path}.scope`);\n if (scope === \"universal\") throw new TypeError(`${path}.scope must not use the reserved universal scope.`);\n token(requirement.matrixId, `${path}.matrixId`);\n token(requirement.matrixVersion, `${path}.matrixVersion`);\n const matrixSha256 = digest(requirement.matrixSha256, `${path}.matrixSha256`);\n if (SUPPORTED_STABLE_WEBGPU_MATRIX_POLICIES.some((policy) => policy.matrixSha256 === matrixSha256)) {\n throw new TypeError(`${path} must require an additive matrix policy, not the universal matrix policy.`);\n }\n if (!SUPPORTED_ADDITIVE_WEBGPU_MATRIX_POLICIES.some((policy) =>\n scope === policy.scope\n && requirement.matrixId === policy.matrixId\n && requirement.matrixVersion === policy.matrixVersion\n && matrixSha256 === policy.matrixSha256)) {\n throw new TypeError(`${path} is not a supported additive WebGPU matrix policy.`);\n }\n return requirement;\n });\n unique(requiredValidationScopes, (item) => String(item.scope), \"ShaderStyleProfileManifest.requiredValidationScopes scopes\");\n unique(requiredValidationScopes, (item) => String(item.matrixSha256), \"ShaderStyleProfileManifest.requiredValidationScopes matrix policies\");\n return freeze(input as unknown as ShaderStyleProfileManifest);\n}\n\n/** Strictly parses the model-facing GPU compatibility fields published with a model version. */\nexport function parseModelGpuCompatibilityDescriptor(value: unknown): ModelGpuCompatibilityDescriptor {\n const input = object(value, \"ModelGpuCompatibilityDescriptor\");\n exact(input, [\"modelId\", \"version\", \"gpuInterface\", \"modelAbiHash\", \"providedSemantics\", \"defaultStyleProfile\"], \"ModelGpuCompatibilityDescriptor\");\n token(input.modelId, \"ModelGpuCompatibilityDescriptor.modelId\");\n token(input.version, \"ModelGpuCompatibilityDescriptor.version\");\n const gpuInterface = interfaceRef(input.gpuInterface, \"ModelGpuCompatibilityDescriptor.gpuInterface\");\n const modelAbiHash = digest(input.modelAbiHash, \"ModelGpuCompatibilityDescriptor.modelAbiHash\");\n if (gpuInterface.modelAbiHash !== modelAbiHash) throw new TypeError(\"ModelGpuCompatibilityDescriptor.gpuInterface.modelAbiHash differs from modelAbiHash.\");\n tokenArray(input.providedSemantics, \"ModelGpuCompatibilityDescriptor.providedSemantics\");\n if (input.defaultStyleProfile !== null) { const profile = object(input.defaultStyleProfile, \"ModelGpuCompatibilityDescriptor.defaultStyleProfile\"); exact(profile, [\"profileId\", \"version\", \"manifestUri\", \"manifestSha256\"], \"ModelGpuCompatibilityDescriptor.defaultStyleProfile\"); token(profile.profileId, \"ModelGpuCompatibilityDescriptor.defaultStyleProfile.profileId\"); token(profile.version, \"ModelGpuCompatibilityDescriptor.defaultStyleProfile.version\"); uri(profile.manifestUri, \"ModelGpuCompatibilityDescriptor.defaultStyleProfile.manifestUri\"); digest(profile.manifestSha256, \"ModelGpuCompatibilityDescriptor.defaultStyleProfile.manifestSha256\"); }\n return freeze(input as unknown as ModelGpuCompatibilityDescriptor);\n}\n\n/** Strictly parses a qualification fixture that binds one immutable model descriptor. */\nexport function parseShaderQualificationModelCompatibilityFixture(value: unknown): ShaderQualificationModelCompatibilityFixture {\n const input = object(value, \"ShaderQualificationModelCompatibilityFixture\");\n exact(input, [\"contractVersion\", \"fixtureId\", \"model\"], \"ShaderQualificationModelCompatibilityFixture\");\n if (input.contractVersion !== SHADER_QUALIFICATION_FIXTURE_VERSION) throw new TypeError(\"Unsupported model compatibility fixture version.\");\n token(input.fixtureId, \"ShaderQualificationModelCompatibilityFixture.fixtureId\");\n parseModelGpuCompatibilityDescriptor(input.model);\n return freeze(input as unknown as ShaderQualificationModelCompatibilityFixture);\n}\n\nexport function parseJsonBytes(bytes: Uint8Array, label: string): unknown {\n try { return JSON.parse(new TextDecoder(\"utf-8\", { fatal: true }).decode(bytes)); }\n catch (cause) { throw new TypeError(`${label} is not valid UTF-8 JSON.`, { cause }); }\n}\n","import type {\n GpuInterfaceManifest,\n LoadedShaderStyleProfile,\n LoadedShaderVersion,\n PreparedShaderStyleProfile,\n ShaderRenderRole,\n ShaderStyleProfileManifest,\n ShaderStyleProfileRef,\n ShaderVersionManifest,\n ShaderVersionRef,\n} from \"../contracts.js\";\n\n/** Internal immutable data retained independently from caller-visible runtime values. */\nexport interface TrustedLoadedShaderVersion {\n readonly publicValue: LoadedShaderVersion;\n readonly ref: ShaderVersionRef;\n readonly manifest: ShaderVersionManifest;\n readonly gpuInterface: GpuInterfaceManifest;\n readonly modules: ReadonlyMap<string, Uint8Array>;\n}\n\n/** Internal immutable profile state created only at the catalog-loading boundary. */\nexport interface TrustedLoadedShaderStyleProfile {\n readonly publicValue: LoadedShaderStyleProfile;\n readonly ref: ShaderStyleProfileRef;\n readonly manifest: ShaderStyleProfileManifest;\n readonly shaders: ReadonlyMap<ShaderRenderRole, TrustedLoadedShaderVersion>;\n}\n\nclass ReadonlyMapView<K, V> implements ReadonlyMap<K, V> {\n readonly #source: ReadonlyMap<K, V>;\n\n constructor(source: ReadonlyMap<K, V>) {\n this.#source = source;\n Object.freeze(this);\n }\n\n get size(): number { return this.#source.size; }\n get(key: K): V | undefined { return this.#source.get(key); }\n has(key: K): boolean { return this.#source.has(key); }\n entries(): MapIterator<[K, V]> { return this.#source.entries(); }\n keys(): MapIterator<K> { return this.#source.keys(); }\n values(): MapIterator<V> { return this.#source.values(); }\n [Symbol.iterator](): MapIterator<[K, V]> { return this.#source[Symbol.iterator](); }\n\n forEach(\n callbackfn: (value: V, key: K, map: ReadonlyMap<K, V>) => void,\n thisArg?: unknown,\n ): void {\n for (const [key, value] of this.#source) callbackfn.call(thisArg, value, key, this);\n }\n}\n\nconst loadedProfiles = new WeakMap<object, TrustedLoadedShaderStyleProfile>();\nconst preparedProfiles = new WeakSet<object>();\n\nfunction immutableSnapshot<T>(value: T): T {\n if (Array.isArray(value)) {\n return Object.freeze(value.map((item) => immutableSnapshot(item))) as T;\n }\n if (typeof value !== \"object\" || value === null) return value;\n const output: Record<string, unknown> = {};\n for (const [key, item] of Object.entries(value as Record<string, unknown>)) {\n output[key] = immutableSnapshot(item);\n }\n return Object.freeze(output) as T;\n}\n\n/** Creates a mutation-isolated public map facade over private runtime state. */\nexport function readonlyMapView<K, V>(source: ReadonlyMap<K, V>): ReadonlyMap<K, V> {\n return new ReadonlyMapView(source);\n}\n\n/**\n * Copies and brands a catalog-loaded profile. This module is intentionally not a\n * package export; public callers can obtain branded values only through loading.\n */\nexport function trustLoadedShaderStyleProfile(\n raw: LoadedShaderStyleProfile,\n): LoadedShaderStyleProfile {\n const shaderMemo = new Map<LoadedShaderVersion, TrustedLoadedShaderVersion>();\n const trustedShaders = new Map<ShaderRenderRole, TrustedLoadedShaderVersion>();\n const publicShaders = new Map<ShaderRenderRole, LoadedShaderVersion>();\n\n for (const [role, rawShader] of raw.shaders) {\n let trusted = shaderMemo.get(rawShader);\n if (!trusted) {\n const ref = immutableSnapshot(rawShader.ref);\n const manifest = immutableSnapshot(rawShader.manifest);\n const gpuInterface = immutableSnapshot(rawShader.gpuInterface);\n const privateModules = new Map<string, Uint8Array>();\n const publicModules = new Map<string, Uint8Array>();\n for (const [moduleId, bytes] of rawShader.modules) {\n const privateBytes = new Uint8Array(bytes);\n privateModules.set(moduleId, privateBytes);\n publicModules.set(moduleId, new Uint8Array(privateBytes));\n }\n const publicValue = Object.freeze({\n ref,\n manifest,\n gpuInterface,\n modules: readonlyMapView(publicModules),\n } satisfies LoadedShaderVersion);\n trusted = Object.freeze({\n publicValue,\n ref,\n manifest,\n gpuInterface,\n modules: readonlyMapView(privateModules),\n });\n shaderMemo.set(rawShader, trusted);\n }\n trustedShaders.set(role, trusted);\n publicShaders.set(role, trusted.publicValue);\n }\n\n const ref = immutableSnapshot(raw.ref);\n const manifest = immutableSnapshot(raw.manifest);\n const publicValue = Object.freeze({\n ref,\n manifest,\n shaders: readonlyMapView(publicShaders),\n } satisfies LoadedShaderStyleProfile);\n loadedProfiles.set(publicValue, Object.freeze({\n publicValue,\n ref,\n manifest,\n shaders: readonlyMapView(trustedShaders),\n }));\n return publicValue;\n}\n\n/** Rejects values that did not cross the promoted catalog loading boundary. */\nexport function requireTrustedLoadedShaderStyleProfile(\n value: LoadedShaderStyleProfile,\n): TrustedLoadedShaderStyleProfile {\n const trusted = loadedProfiles.get(value as object);\n if (!trusted) {\n throw new TypeError(\"loaded must be returned by loadShaderStyleProfile.\");\n }\n return trusted;\n}\n\n/** Brands and freezes a successfully prepared profile for controller admission. */\nexport function trustPreparedShaderStyleProfile<T extends PreparedShaderStyleProfile>(value: T): T {\n preparedProfiles.add(value as object);\n return Object.freeze(value);\n}\n\n/** Rejects structurally forged prepared profiles before frame-boundary activation. */\nexport function requireTrustedPreparedShaderStyleProfile(value: PreparedShaderStyleProfile): void {\n if (!preparedProfiles.has(value as object)) {\n throw new TypeError(\"prepared must be returned by prepareStyleProfile.\");\n }\n}\n","import type {\n GpuInterfaceRef,\n LoadedShaderStyleProfile,\n LoadedShaderVersion,\n PromotedShaderCatalogResolver,\n ShaderDiagnostic,\n ShaderRenderRole,\n ShaderResult,\n ShaderStyleProfileRef,\n ShaderValidationEvidenceRef,\n ShaderVersionRef,\n} from \"../contracts.js\";\nimport { canonicalizeGpuContract } from \"../canonical-json.js\";\nimport { computeGpuAbiHash, computeSha256 } from \"../hash.js\";\nimport {\n parseGpuInterfaceManifest,\n parseJsonBytes,\n parseShaderStyleProfileManifest,\n parseShaderVersionManifest,\n} from \"../manifest-validation.js\";\nimport { validateShaderDerivedRequirements } from \"../requirements-validation.js\";\nimport { trustLoadedShaderStyleProfile } from \"./trusted-values.js\";\n\nfunction diagnostic(code: ShaderDiagnostic[\"code\"], message: string, path?: string): ShaderDiagnostic {\n return { code, severity: \"error\", message, ...(path ? { path } : {}) };\n}\n\nasync function verifyBytes(bytes: Uint8Array, expected: string, label: string): Promise<void> {\n const actual = await computeSha256(bytes);\n if (actual !== expected) throw new TypeError(`${label} digest does not match its immutable reference.`);\n}\n\nfunction copyBytes(bytes: Uint8Array): Uint8Array {\n return new Uint8Array(bytes);\n}\n\nfunction throwIfAborted(signal?: AbortSignal): void {\n if (signal?.aborted) throw signal.reason instanceof Error ? signal.reason : new DOMException(\"Aborted\", \"AbortError\");\n}\n\nfunction exactShaderRefKey(ref: ShaderVersionRef): string {\n return `${ref.shaderId}\\u0000${ref.version}\\u0000${ref.manifestUri}\\u0000${ref.manifestSha256}`;\n}\n\nfunction evidenceArtifacts(evidence: ShaderValidationEvidenceRef): readonly [string, string, string, string, string] {\n return [\n evidence.evidenceId,\n evidence.uri,\n evidence.sha256,\n evidence.attestationRef.uri,\n evidence.attestationRef.sha256,\n ];\n}\n\nfunction assertDistinctEvidenceOwnership(shaders: readonly LoadedShaderVersion[]): void {\n const uniqueShaders = new Map<string, LoadedShaderVersion>();\n for (const shader of shaders) uniqueShaders.set(exactShaderRefKey(shader.ref), shader);\n const evidenceIds = new Map<string, string>();\n const artifactUris = new Map<string, string>();\n const artifactDigests = new Map<string, string>();\n for (const [shaderKey, shader] of uniqueShaders) {\n const evidenceValues = [\n shader.manifest.validationEvidence,\n ...shader.manifest.additionalValidationEvidence.map((item) => item.evidence),\n ];\n for (const evidence of evidenceValues) {\n const [evidenceId, evidenceUri, evidenceSha256, attestationUri, attestationSha256] = evidenceArtifacts(evidence);\n for (const [kind, value, owners] of [\n [\"evidence ID\", evidenceId, evidenceIds],\n [\"evidence/attestation URI\", evidenceUri, artifactUris],\n [\"evidence/attestation URI\", attestationUri, artifactUris],\n [\"evidence/attestation digest\", evidenceSha256, artifactDigests],\n [\"evidence/attestation digest\", attestationSha256, artifactDigests],\n ] as const) {\n const owner = owners.get(value);\n if (owner !== undefined && owner !== shaderKey) {\n throw new TypeError(`Distinct shader versions in one style profile reuse the same ${kind}.`);\n }\n owners.set(value, shaderKey);\n }\n }\n }\n}\n\nasync function mapLimit<T, U>(\n values: readonly T[],\n limit: number,\n operation: (value: T, index: number) => Promise<U>,\n signal?: AbortSignal,\n): Promise<U[]> {\n const results = new Array<U>(values.length);\n let next = 0;\n const worker = async (): Promise<void> => {\n while (next < values.length) {\n throwIfAborted(signal);\n const index = next++;\n const value = values[index];\n if (value !== undefined) { throwIfAborted(signal); results[index] = await operation(value, index); }\n }\n };\n await Promise.all(Array.from({ length: Math.min(limit, values.length) }, () => worker()));\n return results;\n}\n\nasync function loadInterface(\n catalog: PromotedShaderCatalogResolver,\n ref: GpuInterfaceRef,\n signal?: AbortSignal,\n) {\n throwIfAborted(signal);\n if (!catalog.isCatalogAssetUri(ref.manifestUri)) throw new TypeError(\"GPU interface URI is outside the promoted catalog root.\");\n const loaded = await catalog.loadInterface(ref, signal);\n const bytes = copyBytes(loaded.bytes);\n const promoted = loaded.promoted;\n throwIfAborted(signal);\n if (!promoted) throw new TypeError(\"GPU interface is not promoted.\");\n await verifyBytes(bytes, ref.manifestSha256, \"GPU interface manifest\");\n const manifest = parseGpuInterfaceManifest(parseJsonBytes(bytes, \"GPU interface manifest\"));\n if (\n manifest.interfaceId !== ref.interfaceId\n || manifest.interfaceVersion !== ref.interfaceVersion\n || manifest.interfaceAbiHash !== ref.interfaceAbiHash\n || manifest.modelAbiHash !== ref.modelAbiHash\n ) {\n throw new TypeError(\"GPU interface manifest identity does not match its exact reference.\");\n }\n const modelAbiHash = await computeGpuAbiHash({ kind: \"model\", interface: manifest });\n const interfaceAbiHash = await computeGpuAbiHash({ kind: \"interface\", interface: manifest });\n if (modelAbiHash !== manifest.modelAbiHash || interfaceAbiHash !== manifest.interfaceAbiHash) {\n throw new TypeError(\"GPU interface ABI hashes do not match regenerated structural hashes.\");\n }\n return manifest;\n}\n\nasync function loadShader(\n catalog: PromotedShaderCatalogResolver,\n ref: ShaderVersionRef,\n signal?: AbortSignal,\n): Promise<LoadedShaderVersion> {\n throwIfAborted(signal);\n if (!catalog.isCatalogAssetUri(ref.manifestUri)) throw new TypeError(\"Shader manifest URI is outside the promoted catalog root.\");\n const loaded = await catalog.loadShader(ref, signal);\n const bytes = copyBytes(loaded.bytes);\n const promoted = loaded.promoted;\n throwIfAborted(signal);\n if (!promoted) throw new TypeError(\"Shader version is not promoted.\");\n await verifyBytes(bytes, ref.manifestSha256, \"Shader manifest\");\n const manifest = parseShaderVersionManifest(parseJsonBytes(bytes, \"Shader manifest\"));\n if (manifest.shaderId !== ref.shaderId || manifest.version !== ref.version) {\n throw new TypeError(\"Shader manifest identity does not match its exact reference.\");\n }\n for (const evidence of [\n manifest.validationEvidence,\n ...manifest.additionalValidationEvidence.map((item) => item.evidence),\n ]) {\n if (!catalog.isCatalogAssetUri(evidence.uri)) throw new TypeError(\"Shader validation evidence URI is outside the promoted catalog root.\");\n if (!catalog.isCatalogAssetUri(evidence.attestationRef.uri)) throw new TypeError(\"Shader validation evidence attestation URI is outside the promoted catalog root.\");\n }\n const gpuInterface = await loadInterface(catalog, manifest.gpuInterface, signal);\n const normalizeModules = (values: readonly { readonly moduleId: string; readonly sha256: string }[]) =>\n [...values].sort((left, right) => left.moduleId < right.moduleId ? -1 : left.moduleId > right.moduleId ? 1 : 0)\n .map(({ moduleId, sha256 }) => ({ moduleId, sha256 }));\n if (canonicalizeGpuContract(normalizeModules(gpuInterface.modules)) !== canonicalizeGpuContract(normalizeModules(manifest.modules))) {\n throw new TypeError(\"Shader modules differ from the exact reflected GPU interface module set.\");\n }\n const shaderAbiHash = await computeGpuAbiHash({\n kind: \"shader\",\n interface: gpuInterface,\n pipelines: manifest.pipelines,\n requirements: manifest.requirements,\n });\n if (shaderAbiHash !== manifest.shaderAbiHash) throw new TypeError(\"Shader ABI hash differs from regenerated pipeline/interface ABI.\");\n const modulePairs = await mapLimit(manifest.modules, 4, async (module) => {\n throwIfAborted(signal);\n if (!catalog.isCatalogAssetUri(module.uri)) throw new TypeError(`Shader module ${module.moduleId} URI is outside the promoted catalog root.`);\n const asset = await catalog.loadModule(ref, module.moduleId, module.uri, signal);\n const moduleBytes = copyBytes(asset.bytes);\n const promoted = asset.promoted;\n throwIfAborted(signal);\n if (!promoted) throw new TypeError(`Shader module ${module.moduleId} is not promoted.`);\n if (moduleBytes.byteLength !== module.byteLength) {\n throw new TypeError(`Shader module ${module.moduleId} byte length does not match its manifest.`);\n }\n await verifyBytes(moduleBytes, module.sha256, `Shader module ${module.moduleId}`);\n return [module.moduleId, moduleBytes] as const;\n }, signal);\n const decoder = new TextDecoder(\"utf-8\", { fatal: true });\n validateShaderDerivedRequirements({ manifest, gpuInterface, moduleSources: new Map(modulePairs.map(([moduleId, bytes]) => [moduleId, decoder.decode(bytes)])) });\n return { ref, manifest, gpuInterface, modules: new Map(modulePairs) };\n}\n\n/** Loads only exact, promoted profile/shader/interface/module assets and verifies every digest. */\nexport async function loadShaderStyleProfile(input: {\n readonly ref: ShaderStyleProfileRef;\n readonly catalog: PromotedShaderCatalogResolver;\n readonly signal?: AbortSignal;\n}): Promise<ShaderResult<LoadedShaderStyleProfile>> {\n try {\n throwIfAborted(input.signal);\n if (!input.catalog.isCatalogAssetUri(input.ref.manifestUri)) throw new TypeError(\"Style profile URI is outside the promoted catalog root.\");\n const loaded = await input.catalog.loadProfile(input.ref, input.signal);\n const profileBytes = copyBytes(loaded.bytes);\n const promoted = loaded.promoted;\n throwIfAborted(input.signal);\n if (!promoted) {\n return { ok: false, diagnostics: [diagnostic(\"unpromoted-asset\", \"Style profile is not promoted.\")] };\n }\n await verifyBytes(profileBytes, input.ref.manifestSha256, \"Style profile manifest\");\n const manifest = parseShaderStyleProfileManifest(parseJsonBytes(profileBytes, \"Style profile manifest\"));\n if (manifest.profileId !== input.ref.profileId || manifest.version !== input.ref.version) {\n return { ok: false, diagnostics: [diagnostic(\"invalid-contract\", \"Style profile identity does not match its exact reference.\")] };\n }\n const cache = new Map<string, Promise<LoadedShaderVersion>>();\n const pairs = await mapLimit(manifest.roles, 4, async (binding) => {\n throwIfAborted(input.signal);\n const cacheKey = exactShaderRefKey(binding.shader);\n let shader = cache.get(cacheKey);\n if (!shader) {\n shader = loadShader(input.catalog, binding.shader, input.signal);\n cache.set(cacheKey, shader);\n }\n const resolved = await shader;\n if (!resolved.manifest.renderRoles.some((role) => role.role === binding.role)) {\n throw new TypeError(`Shader ${resolved.manifest.shaderId} does not implement role ${binding.role}.`);\n }\n const validationScopes = new Map(\n resolved.manifest.additionalValidationEvidence.map((item) => [item.scope, item.evidence]),\n );\n for (const requirement of manifest.requiredValidationScopes) {\n const evidence = validationScopes.get(requirement.scope);\n if (!evidence) {\n throw new TypeError(`Shader ${resolved.manifest.shaderId} lacks required validation scope ${requirement.scope}.`);\n }\n if (\n evidence.matrixId !== requirement.matrixId\n || evidence.matrixVersion !== requirement.matrixVersion\n || evidence.matrixSha256 !== requirement.matrixSha256\n ) {\n throw new TypeError(\n `Shader ${resolved.manifest.shaderId} validation scope ${requirement.scope} is bound to a different matrix policy.`,\n );\n }\n }\n return [binding.role, resolved] as const;\n }, input.signal);\n assertDistinctEvidenceOwnership(pairs.map(([, shader]) => shader));\n return {\n ok: true,\n value: trustLoadedShaderStyleProfile({\n ref: input.ref,\n manifest,\n shaders: new Map<ShaderRenderRole, LoadedShaderVersion>(pairs),\n }),\n };\n } catch (cause) {\n if (input.signal?.aborted) throw cause;\n const code = cause instanceof TypeError && /digest/u.test(cause.message)\n ? \"digest-mismatch\"\n : \"invalid-contract\";\n return {\n ok: false,\n diagnostics: [diagnostic(code, cause instanceof Error ? cause.message : \"Style profile loading failed.\")],\n };\n }\n}\n","import type {\n GpuCapabilitySnapshot,\n GpuDeviceLike,\n LoadedShaderStyleProfile,\n ModelGpuCompatibilityDescriptor,\n PreparedShaderStyleProfile,\n SerializableGpuBindGroupLayout,\n SerializableGpuPipelineDescriptor,\n ShaderDiagnostic,\n ShaderResult,\n} from \"../contracts.js\";\nimport { validateModelShaderCompatibility } from \"../compatibility.js\";\nimport { computeSha256 } from \"../hash.js\";\nimport {\n readonlyMapView,\n requireTrustedLoadedShaderStyleProfile,\n trustPreparedShaderStyleProfile,\n} from \"./trusted-values.js\";\n\nfunction error(code: ShaderDiagnostic[\"code\"], message: string): ShaderDiagnostic {\n return { code, severity: \"error\", message };\n}\n\nclass DeviceLostError extends Error {}\n\nasync function boundedGpuWait<T>(\n promise: Promise<T>,\n device: GpuDeviceLike,\n timeoutMs: number,\n signal?: AbortSignal,\n): Promise<T> {\n let timer: ReturnType<typeof setTimeout> | undefined;\n let abort: (() => void) | undefined;\n const timeout = new Promise<never>((_, reject) => { timer = setTimeout(() => reject(new Error(\"GPU operation timed out.\")), timeoutMs); });\n const lost = device.lost?.then((info) => { throw new DeviceLostError(info.message ?? info.reason ?? \"GPU device was lost.\"); });\n const aborted = signal ? new Promise<never>((_, reject) => {\n abort = () => reject(signal.reason instanceof Error ? signal.reason : new DOMException(\"Aborted\", \"AbortError\"));\n if (signal.aborted) abort(); else signal.addEventListener(\"abort\", abort, { once: true });\n }) : undefined;\n try { return await Promise.race([promise, timeout, ...(lost ? [lost] : []), ...(aborted ? [aborted] : [])]); }\n finally { if (timer) clearTimeout(timer); if (abort && signal) signal.removeEventListener(\"abort\", abort); }\n}\n\nfunction closeErrorScopeBestEffort(device: GpuDeviceLike, timeoutMs: number): void {\n if (!device.popErrorScope) return;\n const cleanupTimeout = Number.isFinite(timeoutMs) && timeoutMs > 0\n ? Math.min(timeoutMs, 1_000)\n : 1_000;\n try {\n const pending = device.popErrorScope();\n void boundedGpuWait(pending, device, cleanupTimeout).catch(() => undefined);\n } catch {\n // A cleanup failure cannot replace or indefinitely delay the primary diagnostic.\n }\n}\n\nfunction visibilityMask(stages: readonly string[]): number {\n return stages.reduce((mask, stage) => mask | (stage === \"vertex\" ? 1 : stage === \"fragment\" ? 2 : 4), 0);\n}\n\nfunction bindGroupEntry(entry: SerializableGpuBindGroupLayout[\"entries\"][number]): unknown {\n const common = { binding: entry.binding, visibility: visibilityMask(entry.visibility) };\n switch (entry.resource.kind) {\n case \"buffer\":\n return {\n ...common,\n buffer: {\n type: entry.resource.addressSpace === \"uniform\"\n ? \"uniform\"\n : entry.resource.access === \"read\" ? \"read-only-storage\" : \"storage\",\n minBindingSize: entry.resource.minimumBindingSize,\n },\n };\n case \"sampler\":\n return { ...common, sampler: { type: entry.resource.samplerType } };\n case \"texture\":\n return {\n ...common,\n texture: {\n sampleType: entry.resource.sampleType,\n viewDimension: entry.resource.viewDimension,\n multisampled: entry.resource.multisampled,\n },\n };\n case \"storage-texture\":\n return {\n ...common,\n storageTexture: {\n access: entry.resource.access,\n format: entry.resource.format,\n viewDimension: entry.resource.viewDimension,\n },\n };\n case \"external-texture\":\n return { ...common, externalTexture: {} };\n }\n}\n\nfunction pipelineLayout(device: GpuDeviceLike, pipeline: SerializableGpuPipelineDescriptor): unknown {\n const ordered = [...pipeline.layout.bindGroups].sort((left, right) => left.group - right.group);\n ordered.forEach((group, index) => {\n if (group.group !== index) throw new TypeError(`Pipeline ${pipeline.pipelineId} bind groups must be contiguous from zero.`);\n });\n const groups = ordered.map((group) => device.createBindGroupLayout({\n entries: group.entries.map(bindGroupEntry),\n }));\n return device.createPipelineLayout({ bindGroupLayouts: groups });\n}\n\nasync function createPipeline(\n device: GpuDeviceLike,\n pipeline: SerializableGpuPipelineDescriptor,\n modules: ReadonlyMap<string, unknown>,\n timeoutMs: number,\n signal?: AbortSignal,\n): Promise<unknown> {\n const layout = pipelineLayout(device, pipeline);\n const module = (moduleId: string): unknown => { const resolved = modules.get(moduleId); if (!resolved) throw new TypeError(`Pipeline ${pipeline.pipelineId} references missing module ${moduleId}.`); return resolved; };\n const constants = (values: Readonly<Record<string, boolean | number>>): Readonly<Record<string, number>> => Object.fromEntries(Object.entries(values).map(([name, value]) => [name, typeof value === \"boolean\" ? Number(value) : value]));\n if (pipeline.kind === \"compute\") {\n const descriptor = {\n label: pipeline.pipelineId,\n layout,\n compute: {\n module: module(pipeline.compute.moduleId),\n entryPoint: pipeline.compute.entryPoint,\n constants: constants(pipeline.compute.constants),\n },\n };\n return device.createComputePipelineAsync\n ? boundedGpuWait(device.createComputePipelineAsync(descriptor), device, timeoutMs, signal)\n : device.createComputePipeline?.(descriptor);\n }\n const descriptor = {\n label: pipeline.pipelineId,\n layout,\n vertex: {\n module: module(pipeline.vertex.moduleId),\n entryPoint: pipeline.vertex.entryPoint,\n constants: constants(pipeline.vertex.constants),\n buffers: pipeline.vertexBuffers.map((buffer) => ({\n arrayStride: buffer.arrayStride,\n stepMode: buffer.stepMode,\n attributes: buffer.attributes.map((attribute) => ({ format: attribute.format, offset: attribute.offset, shaderLocation: attribute.shaderLocation })),\n })),\n },\n fragment: pipeline.fragment ? {\n module: module(pipeline.fragment.moduleId),\n entryPoint: pipeline.fragment.entryPoint,\n constants: constants(pipeline.fragment.constants),\n targets: pipeline.colorTargets,\n } : undefined,\n primitive: {\n topology: pipeline.primitive.topology,\n ...(pipeline.primitive.stripIndexFormat ? { stripIndexFormat: pipeline.primitive.stripIndexFormat } : {}),\n frontFace: pipeline.primitive.frontFace,\n cullMode: pipeline.primitive.cullMode,\n unclippedDepth: pipeline.primitive.unclippedDepth,\n },\n depthStencil: pipeline.depthStencil ?? undefined,\n multisample: pipeline.multisample,\n };\n return device.createRenderPipelineAsync\n ? boundedGpuWait(device.createRenderPipelineAsync(descriptor), device, timeoutMs, signal)\n : device.createRenderPipeline?.(descriptor);\n}\n\n/** Validates, compiles, and creates every replacement pipeline before activation. */\nexport async function prepareStyleProfile(input: {\n readonly loaded: LoadedShaderStyleProfile;\n readonly model: ModelGpuCompatibilityDescriptor;\n readonly capabilities: GpuCapabilitySnapshot;\n readonly device: GpuDeviceLike;\n readonly now?: () => number;\n readonly timeoutMs?: number;\n readonly signal?: AbortSignal;\n}): Promise<ShaderResult<PreparedShaderStyleProfile>> {\n const loaded = requireTrustedLoadedShaderStyleProfile(input.loaded);\n const diagnostics: ShaderDiagnostic[] = [];\n const actualCapabilities: GpuCapabilitySnapshot = {\n features: [...input.device.features],\n limits: input.device.limits,\n formats: input.capabilities.formats,\n };\n for (const shader of loaded.shaders.values()) {\n const compatibility = validateModelShaderCompatibility({\n model: input.model,\n shader: shader.manifest,\n gpuInterface: shader.gpuInterface,\n profile: loaded.manifest,\n capabilities: actualCapabilities,\n });\n if (!compatibility.ok) diagnostics.push(...compatibility.diagnostics);\n }\n if (diagnostics.length > 0) return { ok: false, diagnostics };\n\n const modules = new Map<string, unknown>();\n const pipelines = new Map<string, unknown>();\n let errorScopeOpen = false;\n try {\n if (input.device.pushErrorScope && input.device.popErrorScope) {\n input.device.pushErrorScope(\"validation\");\n errorScopeOpen = true;\n }\n for (const [role, shader] of loaded.shaders) {\n const shaderModules = new Map<string, unknown>();\n for (const moduleManifest of shader.manifest.modules) {\n const bytes = shader.modules.get(moduleManifest.moduleId);\n if (!bytes) throw new TypeError(`Module ${moduleManifest.moduleId} is missing after verified loading.`);\n if (bytes.byteLength !== moduleManifest.byteLength) {\n throw new TypeError(`Module ${moduleManifest.moduleId} byte length changed after verified loading.`);\n }\n if (await computeSha256(bytes) !== moduleManifest.sha256) {\n throw new TypeError(`Module ${moduleManifest.moduleId} digest changed after verified loading.`);\n }\n const source = new TextDecoder(\"utf-8\", { fatal: true }).decode(bytes);\n const module = input.device.createShaderModule({\n label: `${shader.manifest.shaderId}:${moduleManifest.moduleId}`,\n code: source,\n });\n const information = await boundedGpuWait(module.getCompilationInfo(), input.device, input.timeoutMs ?? 30_000, input.signal);\n const failures = information.messages.filter((message) => message.type === \"error\");\n if (failures.length > 0) {\n throw new TypeError(`WGSL compilation failed for ${shader.manifest.shaderId}:${moduleManifest.moduleId}: ${failures[0]?.message ?? \"unknown error\"}`);\n }\n modules.set(`${role}:${moduleManifest.moduleId}`, module);\n shaderModules.set(moduleManifest.moduleId, module);\n }\n const roleManifest = shader.manifest.renderRoles.find((item) => item.role === role);\n if (!roleManifest) throw new TypeError(`Shader role ${role} disappeared during preparation.`);\n for (const pipelineId of roleManifest.pipelineIds) {\n const descriptor = shader.manifest.pipelines.find((item) => item.pipelineId === pipelineId);\n if (!descriptor) throw new TypeError(`Pipeline ${pipelineId} is missing from its shader manifest.`);\n const pipeline = await createPipeline(input.device, descriptor, shaderModules, input.timeoutMs ?? 30_000, input.signal);\n if (!pipeline) throw new TypeError(`GPU implementation did not create pipeline ${pipelineId}.`);\n pipelines.set(`${role}:${pipelineId}`, pipeline);\n }\n }\n let scopedError: { readonly message?: string } | null = null;\n if (input.device.popErrorScope) {\n errorScopeOpen = false;\n scopedError = await boundedGpuWait(input.device.popErrorScope(), input.device, input.timeoutMs ?? 30_000, input.signal);\n }\n if (scopedError) throw new TypeError(scopedError.message ?? \"GPU validation error while preparing style profile.\");\n let disposed = false;\n const publicPipelines = readonlyMapView(pipelines);\n const prepared = trustPreparedShaderStyleProfile({\n loaded: loaded.publicValue,\n pipelines: publicPipelines,\n preparedAt: (input.now ?? Date.now)(),\n dispose() {\n if (disposed) return;\n disposed = true;\n pipelines.clear();\n modules.clear();\n },\n });\n return {\n ok: true,\n value: prepared,\n };\n } catch (cause) {\n pipelines.clear();\n modules.clear();\n if (errorScopeOpen) {\n closeErrorScopeBestEffort(input.device, input.timeoutMs ?? 30_000);\n }\n return {\n ok: false,\n diagnostics: [error(\n cause instanceof DeviceLostError ? \"device-lost\"\n : cause instanceof TypeError && /digest|byte length/u.test(cause.message) ? \"digest-mismatch\"\n : cause instanceof TypeError && /compilation/u.test(cause.message) ? \"compilation-error\"\n : cause instanceof Error && /timed out/u.test(cause.message) ? \"timeout\" : \"pipeline-error\",\n cause instanceof Error ? cause.message : \"Style profile preparation failed.\",\n )],\n };\n }\n}\n","import type {\n ActiveShaderStyleProfile,\n FrameBoundaryScheduler,\n PreparedShaderStyleProfile,\n ShaderDiagnostic,\n ShaderResult,\n ShaderStyleController,\n} from \"../contracts.js\";\nimport { requireTrustedPreparedShaderStyleProfile } from \"./trusted-values.js\";\n\ninterface ControllerState {\n current: ActiveShaderStyleProfile | null;\n readonly scheduler: FrameBoundaryScheduler;\n readonly now: () => number;\n activationTail: Promise<void>;\n}\n\nconst controllers = new WeakMap<object, ControllerState>();\n\n/** Creates an atomic frame-boundary style-profile controller. */\nexport function createShaderStyleController(input: {\n readonly scheduler: FrameBoundaryScheduler;\n readonly initial?: PreparedShaderStyleProfile;\n readonly now?: () => number;\n}): ShaderStyleController {\n if (input.initial) requireTrustedPreparedShaderStyleProfile(input.initial);\n const now = input.now ?? Date.now;\n const state: ControllerState = {\n current: input.initial ? Object.freeze({ prepared: input.initial, activatedAt: now() }) : null,\n scheduler: input.scheduler,\n now,\n activationTail: Promise.resolve(),\n };\n const controller = Object.freeze({\n get current(): ActiveShaderStyleProfile | null { return state.current; },\n } satisfies ShaderStyleController);\n controllers.set(controller, state);\n return controller;\n}\n\n/** Atomically swaps a fully prepared profile; failure preserves the active profile. */\nexport async function activateStyleProfile(input: {\n readonly controller: ShaderStyleController;\n readonly prepared: PreparedShaderStyleProfile;\n readonly retire?: (previous: PreparedShaderStyleProfile) => void | Promise<void>;\n}): Promise<ShaderResult<ActiveShaderStyleProfile>> {\n const controller = controllers.get(input.controller as object);\n if (!controller) {\n throw new TypeError(\"controller must be created by createShaderStyleController.\");\n }\n requireTrustedPreparedShaderStyleProfile(input.prepared);\n const operation = controller.activationTail.then(async (): Promise<ShaderResult<ActiveShaderStyleProfile>> => {\n const previous = controller.current;\n let callbackOpen = true;\n let callbackInvoked = false;\n let callbackViolation: TypeError | null = null;\n const next = Object.freeze({ prepared: input.prepared, activatedAt: controller.now() });\n try {\n await controller.scheduler.schedule(() => {\n if (!callbackOpen || callbackInvoked) {\n callbackViolation ??= new TypeError(\"Frame-boundary scheduler invoked an activation callback more than once or after completion.\");\n throw callbackViolation;\n }\n callbackInvoked = true;\n controller.current = next;\n });\n callbackOpen = false;\n if (callbackViolation) throw callbackViolation;\n if (!callbackInvoked) throw new TypeError(\"Frame-boundary scheduler completed without invoking the activation callback.\");\n } catch (cause) {\n callbackOpen = false;\n if (controller.current === next) controller.current = previous;\n if (!previous || previous.prepared !== input.prepared) {\n try { input.prepared.dispose(); } catch { /* disposal cannot replace activation failure */ }\n }\n const diagnostic: ShaderDiagnostic = {\n code: \"activation-error\",\n severity: \"error\",\n message: cause instanceof Error ? cause.message : \"Frame-boundary activation failed.\",\n };\n return { ok: false, diagnostics: [diagnostic] };\n }\n if (previous && previous.prepared !== input.prepared) {\n try {\n if (input.retire) await input.retire(previous.prepared);\n else previous.prepared.dispose();\n } catch {\n // The frame-boundary switch is already complete; retirement is best-effort cleanup.\n }\n }\n return { ok: true, value: next };\n });\n controller.activationTail = operation.then(() => undefined, () => undefined);\n return operation;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACCO,IAAM,iCAAiC;AACvC,IAAM,kCAAkC;AACxC,IAAM,wCAAwC;AAC9C,IAAM,8BAA8B;AACpC,IAAM,qCAAqC;AAC3C,IAAM,+BAA+B;AACrC,IAAM,uCAAuC;AAC7C,IAAM,sCAAsC;AAE5C,IAAM,gCAAgC;AAEtC,IAAM,wCAAwC;AAM9C,IAAM,0CAA0C;AAAA,EACrD,OAAO,OAAO;AAAA,IACZ,UAAU;AAAA,IACV,eAAe;AAAA,IACf,cA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kB;AAClB,mBAAW,UAAU;AAAA,MACvB,CAAC;AACD,qBAAe;AACf,UAAI,kBAAmB,OAAM;AAC7B,UAAI,CAAC,gBAAiB,OAAM,IAAI,UAAU,8EAA8E;AAAA,IAC1H,SAAS,OAAO;AACd,qBAAe;AACf,UAAI,WAAW,YAAY,KAAM,YAAW,UAAU;AACtD,UAAI,CAAC,YAAY,SAAS,aAAa,MAAM,UAAU;AACrD,YAAI;AAAE,gBAAM,SAAS,QAAQ;AAAA,QAAG,QAAQ;AAAA,QAAmD;AAAA,MAC7F;AACA,YAAMK,cAA+B;AAAA,QACnC,MAAM;AAAA,QACN,UAAU;AAAA,QACV,SAAS,iBAAiB,QAAQ,MAAM,UAAU;AAAA,MACpD;AACA,aAAO,EAAE,IAAI,OAAO,aAAa,CAACA,WAAU,EAAE;AAAA,IAChD;AACA,QAAI,YAAY,SAAS,aAAa,MAAM,UAAU;AACpD,UAAI;AACF,YAAI,MAAM,OAAQ,OAAM,MAAM,OAAO,SAAS,QAAQ;AAAA,YACjD,UAAS,SAAS,QAAQ;AAAA,MACjC,QAAQ;AAAA,MAER;AAAA,IACF;AACA,WAAO,EAAE,IAAI,MAAM,OAAO,KAAK;AAAA,EACjC,CAAC;AACD,aAAW,iBAAiB,UAAU,KAAK,MAAM,QAAW,MAAM,MAAS;AAC3E,SAAO;AACT;","names":["digest","binding","semantic","significand","_","pipeline","stages","semantic","binding","module","semantic","integer","value","value","module","integer","ref","manifest","publicValue","module","promoted","bytes","binding","error","stages","pipeline","module","descriptor","diagnostic"]}
1
+ {"version":3,"sources":["../src/index.ts","../src/contracts.ts","../src/asset-version.ts","../src/canonical-json.ts","../src/hash.ts","../src/codec/codec.ts","../src/requirements-validation.ts","../src/manifest-validation.ts","../src/compatibility.ts","../src/runtime/trusted-values.ts","../src/runtime/catalog-loader.ts","../src/runtime/profile-preparer.ts","../src/runtime/style-controller.ts"],"sourcesContent":["export * from \"./contracts.js\";\nexport { assertImmutableAssetVersion } from \"./asset-version.js\";\nexport { canonicalizeGpuContract, parseCanonicalJson } from \"./canonical-json.js\";\nexport { asSha256Hex, computeGpuAbiHash, computeSha256, computeShaderManifestCoreSha256 } from \"./hash.js\";\nexport { createGpuRecordCodec } from \"./codec/codec.js\";\nexport { validateModelShaderCompatibility } from \"./compatibility.js\";\nexport { parseGpuInterfaceManifest, parseJsonBytes, parseModelGpuCompatibilityDescriptor, parseShaderStyleProfileManifest, parseShaderVersionManifest, parseShaderVersionManifestCore } from \"./manifest-validation.js\";\nexport { loadShaderStyleProfile } from \"./runtime/catalog-loader.js\";\nexport { prepareStyleProfile } from \"./runtime/profile-preparer.js\";\nexport { activateStyleProfile, createShaderStyleController } from \"./runtime/style-controller.js\";\n","/** Contract version shared by the first reflection-first manifest family. */\nexport const GPU_INTERFACE_MANIFEST_VERSION = \"1.0.0\" as const;\nexport const SHADER_VERSION_MANIFEST_VERSION = \"1.0.0\" as const;\nexport const SHADER_STYLE_PROFILE_MANIFEST_VERSION = \"1.0.0\" as const;\nexport const SHADER_COMPILE_UNIT_VERSION = \"1.0.0\" as const;\nexport const SHADER_VALIDATION_EVIDENCE_VERSION = \"1.0.0\" as const;\nexport const STABLE_WEBGPU_MATRIX_VERSION = \"1.0.0\" as const;\nexport const SHADER_QUALIFICATION_FIXTURE_VERSION = \"1.0.0\" as const;\nexport const SHADER_QUALIFICATION_BUNDLE_VERSION = \"1.0.0\" as const;\n/** Remotely controlled rollout gate owned by the asset service. */\nexport const GPU_SHADER_STORE_FEATURE_FLAG = \"asset.pipeline.shader-store.enabled\" as const;\n/** User-visible style discovery/selection entitlement owned by the capability service. */\nexport const GPU_SHADER_STYLE_SELECTION_CAPABILITY = \"gpu.shader.style.select\" as const;\n\n/** Lowercase hexadecimal SHA-256 value. Runtime parsers enforce its shape. */\nexport type Sha256Hex = string & { readonly __sha256Hex: unique symbol };\n\n/** Stable universal policies accepted by this contract implementation. */\nexport const SUPPORTED_STABLE_WEBGPU_MATRIX_POLICIES = [\n Object.freeze({\n matrixId: \"stable-webgpu\",\n matrixVersion: \"2026-07-13\",\n matrixSha256: \"4620eca44fd03004ee7650cfe9fcf42934493611a5097da5525f71578980b016\",\n }),\n] as const satisfies readonly {\n readonly matrixId: string;\n readonly matrixVersion: string;\n readonly matrixSha256: string;\n}[];\nObject.freeze(SUPPORTED_STABLE_WEBGPU_MATRIX_POLICIES);\n\n/**\n * Exact additive policies accepted by this release. Empty means supplemental\n * qualification fails closed until reviewed policy bytes and lanes are added.\n */\nexport const SUPPORTED_ADDITIVE_WEBGPU_MATRIX_POLICIES: readonly Readonly<{\n scope: string;\n matrixId: string;\n matrixVersion: string;\n matrixSha256: string;\n}>[] = Object.freeze([]);\n\nexport interface GitObjectId {\n readonly algorithm: \"sha1\" | \"sha256\";\n readonly hex: string;\n}\n\nexport type JsonPrimitive = string | number | boolean | null;\nexport type JsonValue =\n | JsonPrimitive\n | readonly JsonValue[]\n | { readonly [key: string]: JsonValue };\n\nexport type ShaderDiagnosticSeverity = \"error\" | \"warning\" | \"info\";\nexport type ShaderDiagnosticCode =\n | \"invalid-contract\"\n | \"digest-mismatch\"\n | \"model-abi-mismatch\"\n | \"interface-abi-mismatch\"\n | \"shader-abi-mismatch\"\n | \"incompatible-model-interface\"\n | \"missing-semantic\"\n | \"missing-feature\"\n | \"limit-not-met\"\n | \"unsupported-format\"\n | \"unpromoted-asset\"\n | \"compilation-error\"\n | \"pipeline-error\"\n | \"device-lost\"\n | \"activation-error\"\n | \"stale-evidence\"\n | \"incomplete-matrix\"\n | \"uncovered-fragment\"\n | \"timeout\"\n | \"runner-unavailable\"\n | \"adapter-unavailable\";\n\nexport interface ShaderDiagnostic {\n readonly code: ShaderDiagnosticCode;\n readonly severity: ShaderDiagnosticSeverity;\n readonly message: string;\n readonly path?: string;\n readonly expected?: JsonValue;\n readonly actual?: JsonValue;\n}\n\nexport type ShaderResult<T> =\n | { readonly ok: true; readonly value: T }\n | { readonly ok: false; readonly diagnostics: readonly ShaderDiagnostic[] };\n\nexport type GpuScalarKind = \"i32\" | \"u32\" | \"f32\" | \"f16\" | \"bool\";\nexport type GpuHostAddressSpace = \"uniform\" | \"storage\";\nexport type GpuAddressSpace =\n | GpuHostAddressSpace\n | \"function\"\n | \"private\"\n | \"workgroup\";\n\nexport interface GpuScalarLayout {\n readonly kind: \"scalar\";\n readonly scalar: GpuScalarKind;\n readonly alignment: number;\n readonly byteSize: number;\n}\n\nexport interface GpuAtomicLayout {\n readonly kind: \"atomic\";\n readonly scalar: \"i32\" | \"u32\";\n readonly alignment: number;\n readonly byteSize: number;\n}\n\nexport interface GpuVectorLayout {\n readonly kind: \"vector\";\n readonly scalar: GpuScalarKind;\n readonly width: 2 | 3 | 4;\n readonly alignment: number;\n readonly byteSize: number;\n}\n\nexport interface GpuMatrixLayout {\n readonly kind: \"matrix\";\n readonly scalar: \"f32\" | \"f16\";\n readonly columns: 2 | 3 | 4;\n readonly rows: 2 | 3 | 4;\n readonly columnStride: number;\n readonly alignment: number;\n readonly byteSize: number;\n}\n\nexport interface GpuArrayLayout {\n readonly kind: \"array\";\n readonly element: GpuTypeLayout;\n /** Null represents a WGSL runtime-sized array. */\n readonly count: number | null;\n readonly stride: number;\n readonly alignment: number;\n readonly byteSize: number | null;\n}\n\nexport interface GpuRecordReferenceLayout {\n readonly kind: \"record\";\n readonly recordName: string;\n readonly alignment: number;\n readonly byteSize: number | null;\n}\n\nexport type GpuTypeLayout =\n | GpuScalarLayout\n | GpuAtomicLayout\n | GpuVectorLayout\n | GpuMatrixLayout\n | GpuArrayLayout\n | GpuRecordReferenceLayout;\n\nexport interface GpuRecordMemberLayout {\n readonly name: string;\n readonly offset: number;\n /** Effective alignment after applying an optional WGSL `@align`. */\n readonly alignment: number;\n /** Logical size of the value, excluding a member-level `@size`. */\n readonly valueByteSize: number | null;\n /** Occupied member span, including a member-level `@size`. */\n readonly occupiedByteSize: number | null;\n readonly explicitAlign: number | null;\n readonly explicitSize: number | null;\n readonly type: GpuTypeLayout;\n}\n\nexport interface GpuRecordLayout {\n readonly name: string;\n readonly alignment: number;\n /** Null for records ending in a runtime-sized array. */\n readonly byteSize: number | null;\n /** Fixed prefix before any runtime-sized array. */\n readonly minimumByteSize: number;\n readonly runtimeArrayMember: string | null;\n readonly addressSpaces: readonly GpuAddressSpace[];\n /** WGSL declaration order; constructor and codec order depend on it. */\n readonly members: readonly GpuRecordMemberLayout[];\n}\n\nexport type GpuShaderStage = \"vertex\" | \"fragment\" | \"compute\";\nexport type GpuBindingAccess = \"read\" | \"write\" | \"read_write\";\n\nexport type GpuBindingResourceLayout =\n | {\n readonly kind: \"buffer\";\n readonly addressSpace: GpuHostAddressSpace;\n readonly access: GpuBindingAccess;\n readonly recordName: string | null;\n readonly minimumBindingSize: number;\n }\n | {\n readonly kind: \"sampler\";\n readonly samplerType: \"filtering\" | \"non-filtering\" | \"comparison\";\n }\n | {\n readonly kind: \"texture\";\n readonly sampleType: \"float\" | \"unfilterable-float\" | \"depth\" | \"sint\" | \"uint\";\n readonly viewDimension: \"1d\" | \"2d\" | \"2d-array\" | \"cube\" | \"cube-array\" | \"3d\";\n readonly multisampled: boolean;\n }\n | {\n readonly kind: \"storage-texture\";\n readonly access: \"write-only\" | \"read-only\" | \"read-write\";\n readonly format: string;\n readonly viewDimension: \"1d\" | \"2d\" | \"2d-array\" | \"3d\";\n }\n | { readonly kind: \"external-texture\" };\n\nexport interface GpuBindingLayout {\n readonly moduleId: string;\n readonly variableName: string;\n readonly group: number;\n readonly binding: number;\n readonly resource: GpuBindingResourceLayout;\n readonly visibility: readonly GpuShaderStage[];\n}\n\nexport interface GpuEntryPointIo {\n readonly name: string;\n readonly locationKind: \"location\" | \"builtin\";\n readonly location: number | string;\n readonly interpolation: string | null;\n readonly type: GpuTypeLayout;\n}\n\nexport type GpuWorkgroupDimension =\n | { readonly kind: \"literal\"; readonly value: number }\n | { readonly kind: \"override\"; readonly name: string };\n\nexport interface GpuEntryPointInterface {\n readonly moduleId: string;\n readonly name: string;\n readonly stage: GpuShaderStage;\n readonly inputs: readonly GpuEntryPointIo[];\n readonly outputs: readonly GpuEntryPointIo[];\n readonly bindingKeys: readonly string[];\n readonly overrideNames: readonly string[];\n readonly workgroupSize: readonly [\n GpuWorkgroupDimension,\n GpuWorkgroupDimension,\n GpuWorkgroupDimension,\n ] | null;\n /**\n * WebGPU workgroup-storage bytes statically used by a compute entry point.\n * This is null for non-compute entry points.\n */\n readonly workgroupStorageSize: number | null;\n}\n\nexport interface GpuVertexInputLayout {\n readonly pipelineId: string;\n readonly moduleId: string;\n readonly entryPoint: string;\n readonly shaderLocation: number;\n readonly shaderType: GpuTypeLayout;\n readonly bufferSlot: number;\n readonly format: string;\n readonly offset: number;\n readonly arrayStride: number;\n readonly stepMode: \"vertex\" | \"instance\";\n readonly semantic: string | null;\n}\n\n/** Shader-independent vertex bytes consumed from a model buffer. */\nexport interface GpuModelVertexInputLayout {\n readonly source: {\n readonly pipelineId: string;\n readonly shaderLocation: number;\n };\n readonly format: string;\n readonly offset: number;\n readonly arrayStride: number;\n readonly stepMode: \"vertex\" | \"instance\";\n readonly semantic: string;\n}\n\n/** A reflected model-facing resource projection; shader coordinates and visibility are excluded. */\nexport interface GpuModelBindingLayout {\n readonly source: {\n readonly moduleId: string;\n readonly group: number;\n readonly binding: number;\n };\n readonly resource: GpuBindingResourceLayout;\n readonly semantic: string | null;\n}\n\nexport interface GpuOverrideLayout {\n readonly moduleId: string;\n readonly name: string;\n readonly id: number | null;\n readonly type: \"bool\" | \"i32\" | \"u32\" | \"f32\" | \"f16\";\n readonly defaultValue: boolean | number | null;\n}\n\nexport type GpuSemanticSource =\n | {\n readonly kind: \"record-member\";\n readonly recordName: string;\n readonly memberPath: readonly string[];\n }\n | {\n readonly kind: \"vertex-attribute\";\n readonly pipelineId: string;\n readonly shaderLocation: number;\n }\n | {\n readonly kind: \"binding\";\n readonly moduleId: string;\n readonly group: number;\n readonly binding: number;\n };\n\nexport interface GpuSemanticProjection {\n readonly semantic: string;\n readonly source: GpuSemanticSource;\n}\n\nexport interface GpuModelAbiProjection {\n readonly recordNames: readonly string[];\n readonly bindings: readonly GpuModelBindingLayout[];\n readonly vertexInputs: readonly GpuModelVertexInputLayout[];\n readonly semantics: readonly GpuSemanticProjection[];\n}\n\nexport interface GpuInterfaceManifest {\n readonly contractVersion: typeof GPU_INTERFACE_MANIFEST_VERSION;\n readonly interfaceId: string;\n readonly interfaceVersion: string;\n readonly modules: readonly {\n readonly moduleId: string;\n readonly sha256: Sha256Hex;\n }[];\n readonly records: readonly GpuRecordLayout[];\n readonly bindings: readonly GpuBindingLayout[];\n readonly entryPoints: readonly GpuEntryPointInterface[];\n readonly vertexInputs: readonly GpuVertexInputLayout[];\n readonly overrides: readonly GpuOverrideLayout[];\n readonly modelAbi: GpuModelAbiProjection;\n readonly modelAbiHash: Sha256Hex;\n readonly interfaceAbiHash: Sha256Hex;\n readonly generatedBy: {\n readonly packageVersion: string;\n readonly reflector: \"wgsl_reflect\";\n readonly reflectorVersion: \"1.5.0\";\n };\n}\n\nexport interface GpuInterfaceRef {\n readonly interfaceId: string;\n readonly interfaceVersion: string;\n readonly manifestUri: string;\n readonly manifestSha256: Sha256Hex;\n readonly interfaceAbiHash: Sha256Hex;\n readonly modelAbiHash: Sha256Hex;\n}\n\nexport interface ShaderVersionRef {\n readonly shaderId: string;\n readonly version: string;\n readonly manifestUri: string;\n readonly manifestSha256: Sha256Hex;\n}\n\nexport interface ShaderStyleProfileRef {\n readonly profileId: string;\n readonly version: string;\n readonly manifestUri: string;\n readonly manifestSha256: Sha256Hex;\n}\n\nexport interface SerializableGpuProgrammableStage {\n readonly moduleId: string;\n readonly entryPoint: string;\n readonly constants: Readonly<Record<string, boolean | number>>;\n}\n\nexport interface SerializableGpuBindGroupLayout {\n readonly group: number;\n readonly entries: readonly Omit<GpuBindingLayout, \"moduleId\" | \"variableName\">[];\n}\n\nexport interface SerializableGpuPipelineLayout {\n readonly bindGroups: readonly SerializableGpuBindGroupLayout[];\n}\n\nexport interface SerializableGpuComputePipelineDescriptor {\n readonly kind: \"compute\";\n readonly pipelineId: string;\n readonly layout: SerializableGpuPipelineLayout;\n readonly compute: SerializableGpuProgrammableStage;\n}\n\nexport interface SerializableGpuRenderPipelineDescriptor {\n readonly kind: \"render\";\n readonly pipelineId: string;\n readonly layout: SerializableGpuPipelineLayout;\n readonly vertex: SerializableGpuProgrammableStage;\n readonly fragment: SerializableGpuProgrammableStage | null;\n readonly vertexBuffers: readonly {\n readonly arrayStride: number;\n readonly stepMode: \"vertex\" | \"instance\";\n readonly attributes: readonly {\n readonly format: string;\n readonly offset: number;\n readonly shaderLocation: number;\n readonly semantic: string | null;\n }[];\n }[];\n readonly primitive: {\n readonly topology: \"point-list\" | \"line-list\" | \"line-strip\" | \"triangle-list\" | \"triangle-strip\";\n readonly stripIndexFormat: \"uint16\" | \"uint32\" | null;\n readonly frontFace: \"ccw\" | \"cw\";\n readonly cullMode: \"none\" | \"front\" | \"back\";\n readonly unclippedDepth: boolean;\n };\n readonly colorTargets: readonly {\n readonly format: string;\n readonly blend: {\n readonly color: SerializableGpuBlendComponent;\n readonly alpha: SerializableGpuBlendComponent;\n } | null;\n readonly writeMask: number;\n }[];\n readonly depthStencil: {\n readonly format: string;\n readonly depthWriteEnabled: boolean;\n readonly depthCompare: GpuCompareFunction;\n readonly stencilFront: SerializableGpuStencilFaceState;\n readonly stencilBack: SerializableGpuStencilFaceState;\n readonly stencilReadMask: number;\n readonly stencilWriteMask: number;\n readonly depthBias: number;\n readonly depthBiasSlopeScale: number;\n readonly depthBiasClamp: number;\n } | null;\n readonly multisample: {\n readonly count: 1 | 4;\n readonly mask: number;\n readonly alphaToCoverageEnabled: boolean;\n };\n}\n\nexport type GpuCompareFunction = \"never\" | \"less\" | \"equal\" | \"less-equal\" | \"greater\" | \"not-equal\" | \"greater-equal\" | \"always\";\n\nexport interface SerializableGpuBlendComponent {\n readonly operation: \"add\" | \"subtract\" | \"reverse-subtract\" | \"min\" | \"max\";\n readonly srcFactor: \"zero\" | \"one\" | \"src\" | \"one-minus-src\" | \"src-alpha\" | \"one-minus-src-alpha\" | \"dst\" | \"one-minus-dst\" | \"dst-alpha\" | \"one-minus-dst-alpha\" | \"src-alpha-saturated\" | \"constant\" | \"one-minus-constant\";\n readonly dstFactor: \"zero\" | \"one\" | \"src\" | \"one-minus-src\" | \"src-alpha\" | \"one-minus-src-alpha\" | \"dst\" | \"one-minus-dst\" | \"dst-alpha\" | \"one-minus-dst-alpha\" | \"src-alpha-saturated\" | \"constant\" | \"one-minus-constant\";\n}\n\nexport interface SerializableGpuStencilFaceState {\n readonly compare: GpuCompareFunction;\n readonly failOp: \"keep\" | \"zero\" | \"replace\" | \"invert\" | \"increment-clamp\" | \"decrement-clamp\" | \"increment-wrap\" | \"decrement-wrap\";\n readonly depthFailOp: \"keep\" | \"zero\" | \"replace\" | \"invert\" | \"increment-clamp\" | \"decrement-clamp\" | \"increment-wrap\" | \"decrement-wrap\";\n readonly passOp: \"keep\" | \"zero\" | \"replace\" | \"invert\" | \"increment-clamp\" | \"decrement-clamp\" | \"increment-wrap\" | \"decrement-wrap\";\n}\n\nexport type SerializableGpuPipelineDescriptor =\n | SerializableGpuComputePipelineDescriptor\n | SerializableGpuRenderPipelineDescriptor;\n\nexport interface GpuLimitRequirement {\n readonly name: string;\n readonly comparator: \"at-least\" | \"at-most\";\n readonly value: number;\n}\n\nexport interface ShaderRequirements {\n readonly semantics: readonly string[];\n readonly features: readonly string[];\n readonly limits: readonly GpuLimitRequirement[];\n readonly formats: readonly string[];\n}\n\nexport type ShaderRenderRole =\n | \"material\"\n | \"lighting\"\n | \"outline\"\n | \"shadow\"\n | \"post-processing\";\n\nexport interface ShaderValidationEvidenceRef {\n readonly evidenceId: string;\n readonly uri: string;\n readonly sha256: Sha256Hex;\n readonly matrixId: string;\n readonly matrixVersion: string;\n /** Digest of the exact versioned matrix-policy bytes used to produce the evidence. */\n readonly matrixSha256: Sha256Hex;\n /** Exact external GitHub build-provenance reference artifact for the evidence bytes. */\n readonly attestationRef: {\n readonly uri: string;\n readonly sha256: Sha256Hex;\n };\n}\n\n/** Additional qualification required beyond the stable universal matrix. */\nexport interface ScopedShaderValidationEvidenceRef {\n /** Stable, profile-selectable scope such as `xr`; `universal` is reserved. */\n readonly scope: string;\n readonly evidence: ShaderValidationEvidenceRef;\n}\n\n/** Exact supplemental matrix policy a style profile requires for every role. */\nexport interface ShaderValidationScopeRequirement {\n /** Stable policy scope such as `xr`; `universal` is reserved. */\n readonly scope: string;\n readonly matrixId: string;\n readonly matrixVersion: string;\n readonly matrixSha256: Sha256Hex;\n}\n\nexport interface ShaderVersionManifest {\n readonly contractVersion: typeof SHADER_VERSION_MANIFEST_VERSION;\n readonly shaderId: string;\n readonly version: string;\n readonly modules: readonly {\n readonly moduleId: string;\n readonly uri: string;\n readonly byteLength: number;\n readonly sha256: Sha256Hex;\n readonly contentType: \"text/wgsl; charset=utf-8\";\n }[];\n readonly gpuInterface: GpuInterfaceRef;\n readonly pipelines: readonly SerializableGpuPipelineDescriptor[];\n readonly renderRoles: readonly {\n readonly role: ShaderRenderRole;\n readonly pipelineIds: readonly string[];\n }[];\n readonly compatibleModelInterfaces: readonly {\n readonly interfaceId: string;\n readonly interfaceVersion: string;\n readonly manifestSha256: Sha256Hex;\n readonly interfaceAbiHash: Sha256Hex;\n readonly modelAbiHash: Sha256Hex;\n }[];\n readonly requirements: ShaderRequirements;\n readonly shaderAbiHash: Sha256Hex;\n /** Passing evidence for the universal stable-WebGPU matrix. */\n readonly validationEvidence: ShaderValidationEvidenceRef;\n /** Passing evidence for additive matrices, for example XR device lanes. */\n readonly additionalValidationEvidence: readonly ScopedShaderValidationEvidenceRef[];\n}\n\n/** Immutable shader manifest fields qualified before external evidence is attached. */\nexport type ShaderVersionManifestCore = Omit<ShaderVersionManifest, \"validationEvidence\" | \"additionalValidationEvidence\">;\n\nexport interface ShaderStyleRoleBinding {\n readonly role: ShaderRenderRole;\n readonly shader: ShaderVersionRef;\n}\n\nexport interface ShaderStyleProfileManifest {\n readonly contractVersion: typeof SHADER_STYLE_PROFILE_MANIFEST_VERSION;\n readonly profileId: string;\n readonly version: string;\n readonly style: string;\n readonly roles: readonly ShaderStyleRoleBinding[];\n readonly compatibleModelInterfaces: readonly {\n readonly interfaceId: string;\n readonly interfaceVersion: string;\n readonly manifestSha256: Sha256Hex;\n readonly interfaceAbiHash: Sha256Hex;\n readonly modelAbiHash: Sha256Hex;\n }[];\n readonly requiredSemantics: readonly string[];\n /** Exact supplemental matrix policies every referenced shader must provide. */\n readonly requiredValidationScopes: readonly ShaderValidationScopeRequirement[];\n}\n\nexport interface ModelGpuCompatibilityDescriptor {\n readonly modelId: string;\n readonly version: string;\n readonly gpuInterface: GpuInterfaceRef;\n readonly modelAbiHash: Sha256Hex;\n readonly providedSemantics: readonly string[];\n readonly defaultStyleProfile: ShaderStyleProfileRef | null;\n}\n\nexport interface GpuCapabilitySnapshot {\n readonly features: readonly string[];\n readonly limits: Readonly<Record<string, number>>;\n readonly formats: readonly string[];\n}\n\nexport interface ModelShaderCompatibility {\n readonly modelAbiHash: Sha256Hex;\n readonly shaderAbiHash: Sha256Hex;\n readonly matchedInterfaceId: string;\n}\n\nexport type GpuScalarValue = number;\nexport type GpuVectorValue = readonly number[];\nexport type GpuMatrixValue = readonly (readonly number[])[];\nexport type GpuRecordValue = Readonly<Record<string, unknown>>;\n\nexport interface GpuRecordCodec<T = GpuRecordValue> {\n readonly record: GpuRecordLayout;\n readonly minimumByteLength: number;\n byteLength(value: T): number;\n encode(value: T): ArrayBuffer;\n encodeInto(\n value: T,\n destination: ArrayBuffer | ArrayBufferView,\n byteOffset?: number,\n ): number;\n decode(\n source: ArrayBuffer | ArrayBufferView,\n options?: { readonly byteOffset?: number; readonly byteLength?: number },\n ): T;\n}\n\nexport interface PromotedShaderCatalogResolver {\n /** Must prove the URI belongs to the configured promoted catalog root and exact immutable identity. */\n isCatalogAssetUri(uri: string): boolean;\n loadProfile(\n ref: ShaderStyleProfileRef,\n signal?: AbortSignal,\n ): Promise<{ readonly bytes: Uint8Array; readonly promoted: boolean }>;\n loadShader(\n ref: ShaderVersionRef,\n signal?: AbortSignal,\n ): Promise<{ readonly bytes: Uint8Array; readonly promoted: boolean }>;\n loadInterface(\n ref: GpuInterfaceRef,\n signal?: AbortSignal,\n ): Promise<{ readonly bytes: Uint8Array; readonly promoted: boolean }>;\n loadModule(\n shader: ShaderVersionRef,\n moduleId: string,\n uri: string,\n signal?: AbortSignal,\n ): Promise<{ readonly bytes: Uint8Array; readonly promoted: boolean }>;\n}\n\nexport interface LoadedShaderVersion {\n readonly ref: ShaderVersionRef;\n readonly manifest: ShaderVersionManifest;\n readonly gpuInterface: GpuInterfaceManifest;\n readonly modules: ReadonlyMap<string, Uint8Array>;\n}\n\nexport interface LoadedShaderStyleProfile {\n readonly ref: ShaderStyleProfileRef;\n readonly manifest: ShaderStyleProfileManifest;\n readonly shaders: ReadonlyMap<ShaderRenderRole, LoadedShaderVersion>;\n}\n\nexport interface GpuCompilationMessageLike {\n readonly type: \"error\" | \"warning\" | \"info\";\n readonly message: string;\n readonly lineNum?: number;\n readonly linePos?: number;\n}\n\nexport interface GpuShaderModuleLike {\n getCompilationInfo(): Promise<{ readonly messages: readonly GpuCompilationMessageLike[] }>;\n}\n\nexport interface GpuDeviceLike {\n readonly features: Iterable<string>;\n readonly limits: Readonly<Record<string, number>>;\n readonly lost?: Promise<{ readonly reason?: string; readonly message?: string }>;\n createShaderModule(descriptor: { readonly label?: string; readonly code: string }): GpuShaderModuleLike;\n createBindGroupLayout(descriptor: unknown): unknown;\n createPipelineLayout(descriptor: { readonly bindGroupLayouts: readonly unknown[] }): unknown;\n createComputePipelineAsync?(descriptor: unknown): Promise<unknown>;\n createRenderPipelineAsync?(descriptor: unknown): Promise<unknown>;\n createComputePipeline?(descriptor: unknown): unknown;\n createRenderPipeline?(descriptor: unknown): unknown;\n pushErrorScope?(filter: \"validation\"): void;\n popErrorScope?(): Promise<{ readonly message?: string } | null>;\n}\n\nexport interface PreparedShaderStyleProfile {\n readonly loaded: LoadedShaderStyleProfile;\n readonly pipelines: ReadonlyMap<string, unknown>;\n readonly preparedAt: number;\n dispose(): void;\n}\n\nexport interface ActiveShaderStyleProfile {\n readonly prepared: PreparedShaderStyleProfile;\n readonly activatedAt: number;\n}\n\nexport interface FrameBoundaryScheduler {\n schedule(operation: () => void): Promise<void>;\n}\n\nexport interface ShaderStyleController {\n readonly current: ActiveShaderStyleProfile | null;\n}\n\nexport interface AssembledWgslModule {\n readonly moduleId: string;\n readonly source: string;\n}\n\nexport type GpuSemanticSelector = GpuSemanticProjection;\n\n/** Selects a reflected binding. Callers cannot supply its resource layout. */\nexport interface GpuModelBindingSelector {\n readonly moduleId: string;\n readonly group: number;\n readonly binding: number;\n readonly semantic?: string | null;\n}\n\nexport interface ReflectGpuInterfaceInput {\n readonly interfaceId: string;\n readonly interfaceVersion: string;\n readonly modules: readonly AssembledWgslModule[];\n readonly pipelines: readonly SerializableGpuPipelineDescriptor[];\n readonly modelFacingRecordNames: readonly string[];\n readonly modelFacingBindings: readonly GpuModelBindingSelector[];\n readonly semantics: readonly GpuSemanticSelector[];\n}\n\nexport interface GeneratedGpuInterfaceArtifacts {\n readonly manifestJson: string;\n readonly jsonSchemas: string;\n readonly typescriptTypes: string;\n readonly byteConstants: string;\n readonly codecs: string;\n}\n\nexport interface ShaderCompileUnitManifest {\n readonly contractVersion: typeof SHADER_COMPILE_UNIT_VERSION;\n readonly compileUnitId: string;\n readonly fragmentIds: readonly string[];\n readonly modules: readonly {\n readonly moduleId: string;\n readonly sha256: Sha256Hex;\n readonly assembly: {\n /** UTF-8 fragment bytes joined by one LF byte, with no executable transforms. */\n readonly kind: \"concat-v1\";\n readonly fragmentIds: readonly string[];\n };\n }[];\n readonly entryPoints: readonly {\n readonly moduleId: string;\n readonly name: string;\n readonly stage: GpuShaderStage;\n }[];\n readonly pipelines: readonly SerializableGpuPipelineDescriptor[];\n readonly interfaceRef: GpuInterfaceRef;\n readonly overrideValues: Readonly<Record<string, boolean | number>>;\n readonly qualificationFixture: {\n readonly fixtureId: string;\n readonly path: string;\n readonly sha256: Sha256Hex;\n };\n}\n\nexport interface ShaderCompileUnitInventory {\n readonly contractVersion: typeof SHADER_COMPILE_UNIT_VERSION;\n readonly fragments: readonly {\n readonly fragmentId: string;\n readonly path: string;\n readonly sha256: Sha256Hex;\n }[];\n readonly compileUnits: readonly ShaderCompileUnitManifest[];\n}\n\nexport type ShaderMatrixBrowserName = \"chromium\" | \"chrome\" | \"edge\" | \"firefox\" | \"safari\";\nexport type ShaderMatrixOsName =\n | \"ubuntu\"\n | \"windows\"\n | \"macos\"\n | \"chromeos\"\n | \"android\"\n | \"ios\"\n | \"ipados\"\n | \"visionos\";\n\nexport interface StableWebGpuMatrixCell {\n readonly cellId: string;\n readonly runnerLabels: readonly string[];\n readonly browser: {\n readonly name: ShaderMatrixBrowserName;\n readonly channel: \"stable\" | \"playwright-bundled\";\n };\n readonly os: {\n readonly name: ShaderMatrixOsName;\n readonly versionRequirement:\n | { readonly kind: \"exact\"; readonly value: string }\n | { readonly kind: \"major\"; readonly value: number }\n | { readonly kind: \"minimum-major\"; readonly value: number }\n | { readonly kind: \"stable-channel\"; readonly channel: \"stable\" };\n readonly architecture: \"x64\" | \"arm64\";\n };\n readonly adapter: {\n readonly kind: \"software\" | \"physical\";\n readonly vendor: string;\n readonly family: string;\n readonly backend: \"swiftshader\" | \"d3d12\" | \"metal\" | \"vulkan\";\n };\n readonly automation: {\n readonly kind: \"playwright\" | \"webdriver\" | \"device-farm\" | \"safari-webdriver\";\n };\n readonly timeoutMs: number;\n readonly blocking: boolean;\n readonly countsTowardStableCoverage: boolean;\n}\n\nexport interface StableWebGpuMatrixManifest {\n readonly contractVersion: typeof STABLE_WEBGPU_MATRIX_VERSION;\n readonly matrixId: string;\n readonly version: string;\n readonly policy: {\n readonly coverage: \"all-cells-required\";\n readonly unavailable: \"fail\";\n readonly skipped: \"fail\";\n readonly timeout: \"fail\";\n readonly deviceLoss: \"fail\";\n readonly requiredPhysicalCellCount: 15;\n readonly requiredBlockingCellCount: 16;\n };\n readonly cells: readonly StableWebGpuMatrixCell[];\n}\n\nexport type ShaderQualificationStatus =\n | \"passed\"\n | \"failed\"\n | \"skipped\"\n | \"timeout\"\n | \"device-lost\"\n | \"runner-unavailable\"\n | \"adapter-unavailable\";\n\nexport type ShaderQualificationPhaseName =\n | \"assembly\"\n | \"reflection-schema\"\n | \"shader-compilation\"\n | \"pipeline-layout\"\n | \"pipeline-creation\"\n | \"bind-group-creation\"\n | \"cpu-to-gpu-layout\"\n | \"gpu-to-cpu-layout\"\n | \"bounded-execution\"\n | \"semantic-readback\";\n\nexport type ShaderQualificationPhaseEvidence =\n | {\n readonly name: Exclude<ShaderQualificationPhaseName, \"shader-compilation\" | \"semantic-readback\">;\n readonly status: \"passed\" | \"failed\";\n readonly durationMs: number;\n readonly evidenceSha256: Sha256Hex;\n }\n | {\n readonly name: \"shader-compilation\";\n readonly status: \"passed\" | \"failed\";\n readonly durationMs: number;\n readonly compilationMessagesSha256: Sha256Hex;\n readonly errorCount: number;\n }\n | {\n readonly name: \"semantic-readback\";\n readonly status: \"passed\" | \"failed\";\n readonly durationMs: number;\n readonly expectedSha256: Sha256Hex;\n readonly actualSha256: Sha256Hex;\n };\n\nexport interface ShaderQualificationResult {\n readonly compileUnitId: string;\n readonly cellId: string;\n readonly status: ShaderQualificationStatus;\n readonly startedAt: string;\n readonly completedAt: string;\n readonly observed: {\n readonly runner: { readonly id: string; readonly labels: readonly string[] };\n readonly os: { readonly name: string; readonly version: string; readonly channel: string | null; readonly architecture: string };\n readonly browser: { readonly name: string; readonly version: string; readonly channel: string };\n readonly adapter: {\n readonly physical: boolean;\n readonly vendor: string;\n readonly family: string;\n readonly architecture: string;\n readonly device: string;\n readonly description: string;\n readonly backend: string;\n readonly driver: string;\n };\n readonly features: readonly string[];\n readonly limits: Readonly<Record<string, number>>;\n };\n readonly phases: readonly ShaderQualificationPhaseEvidence[];\n readonly diagnostics: readonly ShaderDiagnostic[];\n}\n\n/** Candidate claims that can be serialized inside the candidate archive without a self-digest. */\nexport interface ShaderQualificationCandidateSubject {\n /** Digest of the ShaderVersionManifest projection with validationEvidence omitted. */\n readonly shaderManifestCore: {\n readonly shaderId: string;\n readonly version: string;\n readonly sha256: Sha256Hex;\n };\n readonly compileUnitInventorySha256: Sha256Hex;\n readonly shaderAbiHash: Sha256Hex;\n readonly interfaceManifestSha256: Sha256Hex;\n readonly modelAbiHashes: readonly Sha256Hex[];\n readonly modules: readonly { readonly moduleId: string; readonly sha256: Sha256Hex }[];\n readonly requiredCompileUnitIds: readonly string[];\n readonly requiredCellIds: readonly string[];\n}\n\nexport interface ShaderValidationEvidenceSubject extends ShaderQualificationCandidateSubject {\n /** Verified externally over the complete immutable archive; never embedded in that archive. */\n readonly dataBundleSha256: Sha256Hex;\n}\n\nexport interface ShaderTrustedWorkflowProvenance {\n readonly repository: string;\n readonly commit: GitObjectId;\n readonly ref: string;\n readonly workflowRef: string;\n readonly workflowSha: GitObjectId;\n readonly runId: string;\n readonly runAttempt: number;\n readonly job: string;\n readonly eventName: string;\n readonly oidcAttestation: {\n readonly issuer: \"https://token.actions.githubusercontent.com\";\n readonly subject: string;\n readonly audience: string;\n readonly verifiedClaimsSha256: Sha256Hex;\n readonly verifiedAt: string;\n readonly source: \"trusted-runner-preflight\";\n };\n}\n\n/** Identifies the workflow job and runner that produced a qualification-cell artifact. */\nexport interface ShaderQualificationExecutionProducer {\n readonly repository: string;\n readonly commit: GitObjectId;\n readonly ref: string;\n readonly runId: string;\n readonly runAttempt: number;\n readonly job: \"swiftshader\" | \"physical\" | \"physical-runner-preflight\";\n readonly trustedWorkflowRepository: \"Plasius-LTD/gpu-shader\";\n readonly trustedWorkflowRef: string;\n readonly trustedWorkflowSha: GitObjectId;\n readonly runner: {\n readonly name: string;\n readonly environment: \"github-hosted\" | \"self-hosted\" | \"device-farm\";\n readonly os: string;\n readonly architecture: string;\n };\n}\n\nexport interface ShaderValidationEvidence {\n readonly contractVersion: typeof SHADER_VALIDATION_EVIDENCE_VERSION;\n readonly evidenceId: string;\n readonly status: \"passed\" | \"failed\";\n readonly generatedAt: string;\n readonly subjectBindingSha256: Sha256Hex;\n readonly subject: ShaderValidationEvidenceSubject;\n readonly matrixRef: {\n readonly matrixId: string;\n readonly version: string;\n readonly sha256: Sha256Hex;\n };\n readonly toolchain: {\n readonly packageVersion: string;\n readonly reflectorVersion: \"1.5.0\";\n readonly harness: {\n readonly id: string;\n readonly version: string;\n readonly sha256: Sha256Hex;\n };\n };\n readonly qualificationPreflightProvenance: ShaderTrustedWorkflowProvenance;\n readonly counts: {\n readonly compileUnits: number;\n readonly cells: number;\n readonly expectedResults: number;\n readonly passedResults: number;\n };\n readonly cellRuns: readonly ShaderValidationCellRun[];\n readonly results: readonly ShaderQualificationResult[];\n}\n\nexport type ShaderQualificationResource =\n | {\n readonly kind: \"buffer\";\n readonly resourceId: string;\n readonly byteLength: number;\n readonly usage: readonly string[];\n readonly initialData: { readonly path: string; readonly sha256: Sha256Hex } | null;\n }\n | {\n readonly kind: \"texture\";\n readonly resourceId: string;\n readonly dimension: \"1d\" | \"2d\" | \"3d\";\n readonly size: readonly [number, number, number];\n readonly mipLevelCount: number;\n readonly sampleCount: 1 | 4;\n readonly format: string;\n readonly usage: readonly string[];\n readonly initialData: {\n readonly path: string;\n readonly sha256: Sha256Hex;\n readonly bytesPerRow: number;\n readonly rowsPerImage: number;\n readonly mipLevel: number;\n readonly origin: readonly [number, number, number];\n readonly aspect: \"all\" | \"depth-only\" | \"stencil-only\";\n } | null;\n }\n | {\n readonly kind: \"sampler\";\n readonly resourceId: string;\n readonly descriptor: Readonly<Record<string, JsonPrimitive>>;\n };\n\nexport type ShaderQualificationCommand =\n | {\n readonly kind: \"dispatch\";\n readonly pipelineId: string;\n readonly bindGroupIds: readonly string[];\n readonly workgroups: readonly [number, number, number];\n }\n | {\n readonly kind: \"draw\";\n readonly pipelineId: string;\n readonly bindGroupIds: readonly string[];\n readonly vertexBuffers: readonly {\n readonly slot: number;\n readonly resourceId: string;\n readonly offset: number;\n readonly size: number;\n }[];\n readonly colorAttachments: readonly {\n readonly resourceId: string;\n readonly view: ShaderQualificationTextureViewDescriptor;\n readonly clearValue: readonly [number, number, number, number];\n readonly loadOp: \"clear\" | \"load\";\n readonly storeOp: \"store\" | \"discard\";\n }[];\n readonly depthStencilAttachment: {\n readonly resourceId: string;\n readonly view: ShaderQualificationTextureViewDescriptor;\n readonly depthClearValue: number;\n readonly depthLoadOp: \"clear\" | \"load\";\n readonly depthStoreOp: \"store\" | \"discard\";\n readonly stencilClearValue: number;\n readonly stencilLoadOp: \"clear\" | \"load\" | null;\n readonly stencilStoreOp: \"store\" | \"discard\" | null;\n } | null;\n readonly vertexCount: number;\n readonly instanceCount: number;\n readonly firstVertex: number;\n readonly firstInstance: number;\n }\n | {\n readonly kind: \"copy-buffer\";\n readonly source: string;\n readonly destination: string;\n readonly byteLength: number;\n }\n | {\n readonly kind: \"copy-texture-to-buffer\";\n readonly source: {\n readonly resourceId: string;\n readonly mipLevel: number;\n readonly origin: readonly [number, number, number];\n readonly aspect: \"all\" | \"depth-only\" | \"stencil-only\";\n };\n readonly destination: {\n readonly resourceId: string;\n readonly offset: number;\n readonly bytesPerRow: number;\n readonly rowsPerImage: number;\n };\n readonly extent: readonly [number, number, number];\n };\n\nexport interface ShaderQualificationTextureViewDescriptor {\n readonly format: string | null;\n readonly dimension: \"1d\" | \"2d\" | \"2d-array\" | \"cube\" | \"cube-array\" | \"3d\" | null;\n readonly aspect: \"all\" | \"depth-only\" | \"stencil-only\";\n readonly baseMipLevel: number;\n readonly mipLevelCount: number | null;\n readonly baseArrayLayer: number;\n readonly arrayLayerCount: number | null;\n}\n\nexport type ShaderQualificationBindGroupResource =\n | { readonly kind: \"buffer\"; readonly resourceId: string; readonly offset: number; readonly size: number }\n | { readonly kind: \"texture-view\"; readonly resourceId: string; readonly view: ShaderQualificationTextureViewDescriptor }\n | { readonly kind: \"sampler\"; readonly resourceId: string };\n\n/** A declarative host-codec ↔ final-WGSL record-layout probe. */\nexport interface ShaderQualificationBufferRecordLayoutProbe {\n readonly kind: \"buffer-record\";\n readonly probeId: string;\n readonly source: {\n readonly moduleId: string;\n readonly group: number;\n readonly binding: number;\n readonly recordName: string;\n };\n readonly pipelineId: string;\n readonly commandIndex: number;\n readonly input: {\n readonly resourceId: string;\n readonly byteOffset: number;\n readonly byteLength: number;\n /** Encoded with createGpuRecordCodec and compared byte-for-byte with admitted initialData. */\n readonly value: JsonValue;\n };\n readonly output: {\n readonly readbackIndex: number;\n readonly recordName: string;\n /** GPU output is decoded with the reflected codec and compared to this value. */\n readonly expectedValue: JsonValue;\n };\n}\n\n/** A declarative host vertex-format encoder ↔ final-WGSL vertex-fetch probe. */\nexport interface ShaderQualificationVertexInputLayoutProbe {\n readonly kind: \"vertex-input\";\n readonly probeId: string;\n readonly source: {\n readonly pipelineId: string;\n readonly shaderLocation: number;\n readonly semantic: string;\n };\n readonly commandIndex: number;\n readonly input: {\n readonly resourceId: string;\n readonly vertexBufferSlot: number;\n /** Absolute vertex or instance element selected by the draw command. */\n readonly elementIndex: number;\n /** Encoded from the reflected GPUVertexFormat and compared with admitted bytes. */\n readonly value: JsonValue;\n };\n readonly output: {\n readonly readbackIndex: number;\n readonly recordName: string;\n /** GPU-observed vertex value encoded through this reflected output record. */\n readonly expectedValue: JsonValue;\n };\n}\n\nexport type ShaderQualificationLayoutProbe =\n | ShaderQualificationBufferRecordLayoutProbe\n | ShaderQualificationVertexInputLayoutProbe;\n\nexport interface ShaderQualificationFixtureManifest {\n readonly contractVersion: typeof SHADER_QUALIFICATION_FIXTURE_VERSION;\n readonly fixtureId: string;\n readonly resources: readonly ShaderQualificationResource[];\n readonly bindGroups: readonly {\n readonly bindGroupId: string;\n readonly group: number;\n readonly entries: readonly { readonly binding: number; readonly resource: ShaderQualificationBindGroupResource }[];\n }[];\n readonly commands: readonly ShaderQualificationCommand[];\n readonly layoutProbes: readonly ShaderQualificationLayoutProbe[];\n readonly readbacks: readonly {\n readonly resourceId: string;\n readonly byteOffset: number;\n readonly byteLength: number;\n readonly expectedSha256: Sha256Hex;\n }[];\n readonly bounds: {\n readonly maxBufferBytes: number;\n readonly maxTextureTexels: number;\n readonly maxCommands: number;\n readonly timeoutMs: number;\n };\n}\n\nexport interface ShaderQualificationBundleManifest {\n readonly contractVersion: typeof SHADER_QUALIFICATION_BUNDLE_VERSION;\n readonly inventory: ShaderCompileUnitInventory;\n readonly subject: ShaderQualificationCandidateSubject;\n readonly shaderManifestCorePath: string;\n readonly gpuInterfaceManifest: { readonly path: string; readonly sha256: Sha256Hex };\n readonly modelCompatibilityFixtures: readonly {\n readonly fixtureId: string;\n readonly path: string;\n readonly sha256: Sha256Hex;\n }[];\n readonly modules: readonly { readonly moduleId: string; readonly path: string; readonly sha256: Sha256Hex }[];\n readonly fixtures: readonly {\n readonly fixtureId: string;\n readonly path: string;\n readonly sha256: Sha256Hex;\n readonly kind: \"qualification-fixture\";\n }[];\n}\n\nexport interface ShaderQualificationModelCompatibilityFixture {\n readonly contractVersion: typeof SHADER_QUALIFICATION_FIXTURE_VERSION;\n readonly fixtureId: string;\n readonly model: ModelGpuCompatibilityDescriptor;\n}\n\nexport interface ShaderCellEvidence {\n readonly contractVersion: typeof SHADER_VALIDATION_EVIDENCE_VERSION;\n readonly qualificationId: string;\n readonly matrixId: string;\n readonly matrixVersion: string;\n readonly matrixSha256: Sha256Hex;\n readonly cellId: string;\n readonly dataBundleSha256: Sha256Hex;\n readonly compileUnitInventorySha256: Sha256Hex;\n readonly harness: {\n readonly id: string;\n readonly version: string;\n readonly sha256: Sha256Hex;\n };\n readonly automation: {\n readonly kind: \"playwright\" | \"webdriver\" | \"device-farm\" | \"safari-webdriver\";\n readonly driver: string;\n readonly version: string;\n readonly sha256: Sha256Hex;\n };\n /** `sha256(\"plasius.gpu.qualification-subject/v1\\n\" + canonical(subject,digests))`. */\n readonly subjectBindingSha256: Sha256Hex;\n readonly qualificationPreflightProvenance: ShaderTrustedWorkflowProvenance;\n readonly producer: ShaderQualificationExecutionProducer;\n readonly results: readonly ShaderQualificationResult[];\n}\n\nexport interface ShaderRunnerCellPreflightEvidence {\n readonly contractVersion: typeof SHADER_VALIDATION_EVIDENCE_VERSION;\n readonly kind: \"shader-runner-cell-preflight-evidence\";\n readonly qualificationId: string;\n readonly cellId: string;\n readonly status: \"available\" | \"runner-unavailable\";\n readonly matrixSha256: Sha256Hex;\n readonly runnerLabels: readonly string[];\n /** API-observed self-hosted/device labels, or hosted image labels derived from the actual OS/architecture environment. */\n readonly matchedRunners: readonly {\n readonly name: string;\n readonly labels: readonly string[];\n }[];\n /** Independently verified adapter package/code identity, or null when inventory cannot observe it. */\n readonly adapterHarness: {\n readonly id: string;\n readonly version: string;\n readonly sha256: Sha256Hex;\n } | null;\n readonly qualificationPreflightProvenance: ShaderTrustedWorkflowProvenance;\n readonly producer: ShaderQualificationExecutionProducer;\n}\n\nexport interface ShaderValidationCellRun {\n readonly cellId: string;\n readonly source: \"cell-evidence\" | \"runner-preflight\" | \"workflow-diagnostic\";\n readonly sourceArtifactSha256: Sha256Hex;\n readonly resultsSha256: Sha256Hex;\n readonly qualificationPreflightProvenance: ShaderTrustedWorkflowProvenance;\n readonly producer: ShaderQualificationExecutionProducer;\n readonly harness: {\n readonly id: string;\n readonly version: string;\n readonly sha256: Sha256Hex;\n };\n /** Null when no adapter actually executed (runner-unavailable/workflow diagnostic). */\n readonly automation: {\n readonly kind: \"playwright\" | \"webdriver\" | \"device-farm\" | \"safari-webdriver\";\n readonly driver: string;\n readonly version: string;\n readonly sha256: Sha256Hex;\n } | null;\n readonly resultCount: number;\n readonly status: ShaderQualificationStatus;\n}\n\n/** Non-secret claims emitted by the trusted prepare job after Blob version and OIDC verification. */\nexport interface ShaderQualificationPreflightManifest {\n readonly contractVersion: typeof SHADER_VALIDATION_EVIDENCE_VERSION;\n readonly kind: \"shader-qualification-preflight\";\n readonly qualificationId: string;\n readonly sourceBlob: {\n readonly host: string;\n readonly versionId: string;\n readonly uri: string;\n };\n readonly dataBundleSha256: Sha256Hex;\n readonly compileUnitInventorySha256: Sha256Hex;\n readonly matrixSha256: Sha256Hex;\n readonly harnessSha256: Sha256Hex;\n readonly subjectBindingSha256: Sha256Hex;\n readonly provenance: ShaderTrustedWorkflowProvenance;\n}\n\nexport interface ShaderNonQualifyingWorkflowDiagnostic {\n readonly contractVersion: typeof SHADER_VALIDATION_EVIDENCE_VERSION;\n readonly kind: \"non-qualifying-workflow-diagnostic\";\n readonly qualificationId: string;\n readonly cellId: string;\n readonly status: \"timeout\" | \"failed\";\n readonly matrixSha256: Sha256Hex;\n readonly message: string;\n readonly qualificationPreflightProvenance: ShaderTrustedWorkflowProvenance;\n readonly producer: ShaderQualificationExecutionProducer;\n}\n\n/** External GitHub build-provenance reference; verified outside the evidence JSON digest. */\nexport interface ShaderValidationEvidenceAttestationRef {\n readonly contractVersion: typeof SHADER_VALIDATION_EVIDENCE_VERSION;\n readonly kind: \"shader-validation-evidence-attestation-ref\";\n readonly evidence: { readonly name: string; readonly sha256: Sha256Hex };\n readonly attestation: {\n readonly id: string;\n readonly url: string;\n readonly bundle: { readonly name: string; readonly sha256: Sha256Hex };\n };\n readonly producer: {\n readonly repository: string;\n readonly runId: string;\n readonly runAttempt: number;\n readonly trustedWorkflowRepository: \"Plasius-LTD/gpu-shader\";\n readonly trustedWorkflowRef: string;\n readonly trustedWorkflowSha: GitObjectId;\n };\n}\n\nexport interface ShaderCompileFixture {\n /** Local/hosted testing only. Callback fixtures can never produce trusted physical evidence. */\n readonly qualificationEligible: false;\n readonly fixtureId: string;\n setup(context: ShaderCompileContext): Promise<void>;\n encode(context: ShaderCompileContext): Promise<void>;\n verify(context: ShaderCompileContext): Promise<void>;\n cleanup(context: ShaderCompileContext): Promise<void>;\n}\n\nexport interface ShaderCompileContext {\n readonly device: GpuDeviceLike;\n readonly unit: ShaderCompileUnitManifest;\n readonly modules: ReadonlyMap<string, GpuShaderModuleLike>;\n readonly state: Map<string, unknown>;\n}\n","const ASSET_VERSION_PATTERN = /^[0-9A-Za-z][0-9A-Za-z._-]{0,127}$/u;\n\nconst MUTABLE_VERSION_ALIASES = new Set([\n \"latest\",\n \"current\",\n \"stable\",\n \"preview\",\n \"default\",\n \"production\",\n \"canary\",\n \"next\",\n \"head\",\n \"main\",\n]);\n\nconst X_WILDCARD_SEGMENT_PATTERN = /^(?:[vV])?[xX](?:\\.|-|$)|\\.[xX](?:\\.|-|$)/u;\nconst IMMUTABLE_VERSION_ERROR_MESSAGE =\n \"Immutable asset version must be an exact token up to 128 characters; mutable aliases, ranges, wildcards, and URLs are not allowed.\";\n\n/**\n * Validates an immutable, reproducible model, interface, shader, or profile\n * version before catalog access.\n *\n * The diagnostic is deliberately constant and never interpolates untrusted\n * input, keeping runtime and storage-boundary failures bounded.\n */\nexport function assertImmutableAssetVersion(value: unknown): string {\n if (\n typeof value !== \"string\"\n || !ASSET_VERSION_PATTERN.test(value)\n || MUTABLE_VERSION_ALIASES.has(value.toLowerCase())\n || X_WILDCARD_SEGMENT_PATTERN.test(value)\n ) {\n throw new TypeError(IMMUTABLE_VERSION_ERROR_MESSAGE);\n }\n return value;\n}\n","import type { JsonValue } from \"./contracts.js\";\n\nfunction isPlainObject(value: object): value is Record<string, unknown> {\n const prototype = Object.getPrototypeOf(value);\n return prototype === Object.prototype || prototype === null;\n}\n\nfunction assertUnicodeScalarString(value: string, path: string): void {\n for (let index = 0; index < value.length; index += 1) {\n const code = value.charCodeAt(index);\n if (code >= 0xd800 && code <= 0xdbff) {\n const next = value.charCodeAt(index + 1);\n if (!(next >= 0xdc00 && next <= 0xdfff)) throw new TypeError(`${path} contains an unpaired UTF-16 surrogate.`);\n index += 1;\n } else if (code >= 0xdc00 && code <= 0xdfff) throw new TypeError(`${path} contains an unpaired UTF-16 surrogate.`);\n }\n}\n\n/**\n * Canonicalizes contract data using the JSON Canonicalization Scheme ordering\n * rules. Unsupported JavaScript values are rejected rather than silently lost.\n */\nexport function canonicalizeGpuContract(value: unknown): string {\n const ancestors = new Set<object>();\n\n const visit = (current: unknown, path: string): string => {\n if (current === null) return \"null\";\n if (typeof current === \"string\" || typeof current === \"boolean\") {\n if (typeof current === \"string\") assertUnicodeScalarString(current, path);\n return JSON.stringify(current);\n }\n if (typeof current === \"number\") {\n if (!Number.isFinite(current)) {\n throw new TypeError(`${path} contains a non-finite number.`);\n }\n return Object.is(current, -0) ? \"0\" : JSON.stringify(current);\n }\n if (typeof current !== \"object\") {\n throw new TypeError(`${path} contains a value that JSON cannot represent.`);\n }\n if (ancestors.has(current)) {\n throw new TypeError(`${path} contains a circular reference.`);\n }\n\n ancestors.add(current);\n try {\n if (Array.isArray(current)) {\n return `[${current.map((item, index) => visit(item, `${path}[${index}]`)).join(\",\")}]`;\n }\n if (!isPlainObject(current)) {\n throw new TypeError(`${path} must contain only plain JSON objects.`);\n }\n const keys = Object.keys(current).sort();\n const properties = keys.map((key) => {\n assertUnicodeScalarString(key, `${path} key`);\n const member = current[key];\n if (member === undefined) {\n throw new TypeError(`${path}.${key} is undefined.`);\n }\n return `${JSON.stringify(key)}:${visit(member, `${path}.${key}`)}`;\n });\n return `{${properties.join(\",\")}}`;\n } finally {\n ancestors.delete(current);\n }\n };\n\n return visit(value, \"$root\");\n}\n\n/** Parses and verifies exact JCS canonical JSON while preserving its JSON-only type. */\nexport function parseCanonicalJson(value: string): JsonValue {\n const parsed = JSON.parse(value) as JsonValue;\n if (canonicalizeGpuContract(parsed) !== value) throw new TypeError(\"JSON input is valid but not in canonical form.\");\n return parsed;\n}\n","import { canonicalizeGpuContract } from \"./canonical-json.js\";\nimport type {\n GpuInterfaceManifest,\n SerializableGpuPipelineDescriptor,\n Sha256Hex,\n ShaderRequirements,\n ShaderVersionManifest,\n} from \"./contracts.js\";\n\nconst SHA256_PATTERN = /^[a-f0-9]{64}$/u;\n\nexport function asSha256Hex(value: string): Sha256Hex {\n if (!SHA256_PATTERN.test(value)) {\n throw new TypeError(\"SHA-256 values must be lowercase 64-character hexadecimal strings.\");\n }\n return value as Sha256Hex;\n}\n\n/** Computes a SHA-256 digest using the browser-safe Web Crypto API. */\nexport async function computeSha256(value: Uint8Array | string): Promise<Sha256Hex> {\n const subtle = globalThis.crypto?.subtle;\n if (!subtle) {\n throw new Error(\"Web Crypto SHA-256 support is required.\");\n }\n const bytes = typeof value === \"string\" ? new TextEncoder().encode(value) : value;\n const digest = await subtle.digest(\"SHA-256\", bytes as BufferSource);\n return asSha256Hex(\n Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, \"0\")).join(\"\"),\n );\n}\n\nfunction sorted<T>(items: readonly T[], compare: (left: T, right: T) => number): T[] {\n return [...items].sort(compare);\n}\n\nfunction compareString(left: string, right: string): number {\n return left < right ? -1 : left > right ? 1 : 0;\n}\n\nfunction interfaceProjection(manifest: GpuInterfaceManifest): unknown {\n return {\n contractVersion: manifest.contractVersion,\n records: sorted(manifest.records, (left, right) => compareString(left.name, right.name)),\n bindings: sorted(manifest.bindings, (left, right) =>\n compareString(left.moduleId, right.moduleId) || left.group - right.group || left.binding - right.binding),\n entryPoints: sorted(manifest.entryPoints, (left, right) =>\n compareString(left.moduleId, right.moduleId)\n || compareString(left.stage, right.stage)\n || compareString(left.name, right.name)),\n vertexInputs: sorted(manifest.vertexInputs, (left, right) =>\n compareString(left.pipelineId, right.pipelineId) || left.shaderLocation - right.shaderLocation),\n overrides: sorted(manifest.overrides, (left, right) =>\n compareString(left.moduleId, right.moduleId) || compareString(left.name, right.name)),\n };\n}\n\nfunction modelProjection(manifest: GpuInterfaceManifest): unknown {\n const recordsByName = new Map(manifest.records.map((record) => [record.name, record]));\n const names = new Set<string>();\n const includeRecord = (name: string): void => {\n if (names.has(name)) return;\n const record = recordsByName.get(name);\n if (!record) throw new TypeError(`Model ABI references missing record ${name}.`);\n names.add(name);\n const visitType = (type: typeof record.members[number][\"type\"]): void => {\n if (type.kind === \"record\") includeRecord(type.recordName);\n if (type.kind === \"array\") visitType(type.element);\n };\n for (const member of record.members) visitType(member.type);\n };\n for (const name of manifest.modelAbi.recordNames) includeRecord(name);\n for (const binding of manifest.modelAbi.bindings) {\n if (binding.resource.kind === \"buffer\" && binding.resource.recordName) includeRecord(binding.resource.recordName);\n }\n for (const semantic of manifest.modelAbi.semantics) {\n if (semantic.source.kind === \"record-member\") includeRecord(semantic.source.recordName);\n }\n const semanticProjection = manifest.modelAbi.semantics.map((projection) => ({\n semantic: projection.semantic,\n source: projection.source.kind === \"record-member\"\n ? {\n kind: projection.source.kind,\n recordName: projection.source.recordName,\n memberPath: projection.source.memberPath,\n }\n : { kind: projection.source.kind },\n }));\n return {\n contractVersion: manifest.contractVersion,\n records: sorted(\n manifest.records.filter((record) => names.has(record.name)),\n (left, right) => compareString(left.name, right.name),\n ).map(({ addressSpaces: _shaderUsage, ...record }) => record),\n bindings: sorted(manifest.modelAbi.bindings, (left, right) =>\n compareString(left.semantic ?? \"\", right.semantic ?? \"\")\n || compareString(canonicalizeGpuContract(left.resource), canonicalizeGpuContract(right.resource)))\n .map(({ source: _selector, ...binding }) => binding),\n vertexInputs: sorted(manifest.modelAbi.vertexInputs, (left, right) =>\n compareString(left.semantic ?? \"\", right.semantic ?? \"\")\n || left.offset - right.offset)\n .map(({ source: _selector, ...vertex }) => vertex),\n semantics: sorted(semanticProjection, (left, right) =>\n compareString(left.semantic, right.semantic),\n ),\n };\n}\n\nexport type ComputeGpuAbiHashInput =\n | { readonly kind: \"model\"; readonly interface: GpuInterfaceManifest }\n | { readonly kind: \"interface\"; readonly interface: GpuInterfaceManifest }\n | {\n readonly kind: \"shader\";\n readonly interface: GpuInterfaceManifest;\n readonly pipelines: readonly SerializableGpuPipelineDescriptor[];\n readonly requirements: ShaderRequirements;\n };\n\n/** Computes a domain-separated ABI digest over normalized structural data. */\nexport async function computeGpuAbiHash(input: ComputeGpuAbiHashInput): Promise<Sha256Hex> {\n if (input.kind === \"model\") {\n return computeSha256(\n `plasius.gpu.model-abi/v1\\n${canonicalizeGpuContract(modelProjection(input.interface))}`,\n );\n }\n if (input.kind === \"interface\") {\n return computeSha256(\n `plasius.gpu.interface-abi/v1\\n${canonicalizeGpuContract(interfaceProjection(input.interface))}`,\n );\n }\n const pipelines = sorted(input.pipelines, (left, right) =>\n compareString(left.pipelineId, right.pipelineId),\n );\n const requirements = {\n semantics: [...input.requirements.semantics].sort(),\n features: [...input.requirements.features].sort(),\n limits: sorted(input.requirements.limits, (left, right) => compareString(left.name, right.name)),\n formats: [...input.requirements.formats].sort(),\n };\n return computeSha256(\n `plasius.gpu.shader-abi/v1\\n${canonicalizeGpuContract({\n interface: interfaceProjection(input.interface),\n pipelines,\n requirements,\n })}`,\n );\n}\n\n/** Breaks the manifest/evidence digest cycle by omitting only the evidence reference. */\nexport async function computeShaderManifestCoreSha256(\n manifest: Omit<ShaderVersionManifest, \"validationEvidence\" | \"additionalValidationEvidence\"> | ShaderVersionManifest,\n): Promise<Sha256Hex> {\n const core = Object.fromEntries(Object.entries(manifest).filter(\n ([key]) => key !== \"validationEvidence\" && key !== \"additionalValidationEvidence\",\n ));\n return computeSha256(\n `plasius.gpu.shader-manifest-core/v1\\n${canonicalizeGpuContract(core)}`,\n );\n}\n","import type {\n GpuArrayLayout,\n GpuRecordCodec,\n GpuRecordLayout,\n GpuRecordValue,\n GpuScalarKind,\n GpuTypeLayout,\n} from \"../contracts.js\";\n\ninterface BufferRegion {\n readonly buffer: ArrayBuffer;\n readonly byteOffset: number;\n readonly byteLength: number;\n}\n\nfunction bufferRegion(value: ArrayBuffer | ArrayBufferView): BufferRegion {\n if (value instanceof ArrayBuffer) {\n return { buffer: value, byteOffset: 0, byteLength: value.byteLength };\n }\n if (!(value.buffer instanceof ArrayBuffer)) {\n throw new TypeError(\"SharedArrayBuffer-backed views are not supported by the codec.\");\n }\n return { buffer: value.buffer, byteOffset: value.byteOffset, byteLength: value.byteLength };\n}\n\nfunction integer(value: unknown, minimum: number, maximum: number, path: string): number {\n if (typeof value !== \"number\" || !Number.isInteger(value) || value < minimum || value > maximum) {\n throw new TypeError(`${path} must be an integer from ${minimum} to ${maximum}.`);\n }\n return value;\n}\n\nfunction numeric(value: unknown, path: string): number {\n if (typeof value !== \"number\" || !Number.isFinite(value)) {\n throw new TypeError(`${path} must be a finite number.`);\n }\n return value;\n}\n\nfunction scalarByteSize(scalar: GpuScalarKind): number {\n if (scalar === \"f16\") return 2;\n return 4;\n}\n\nfunction roundTiesToEven(value: number): number {\n const lower = Math.floor(value);\n const fraction = value - lower;\n if (fraction < 0.5) return lower;\n if (fraction > 0.5) return lower + 1;\n return lower % 2 === 0 ? lower : lower + 1;\n}\n\n/** Converts a finite JavaScript number to IEEE 754 binary16 using round-to-nearest, ties-to-even. */\nexport function encodeFloat16Bits(value: unknown, path: string): number {\n const input = numeric(value, path);\n const negative = input < 0 || Object.is(input, -0);\n const magnitude = Math.abs(input);\n if (magnitude > 65_504) throw new TypeError(`${path} is outside the finite f16 range.`);\n const sign = negative ? 0x8000 : 0;\n if (magnitude === 0) return sign;\n\n if (magnitude < 2 ** -14) {\n const significand = roundTiesToEven(magnitude / 2 ** -24);\n return sign | significand;\n }\n\n let exponent = Math.floor(Math.log2(magnitude));\n let significand = roundTiesToEven(magnitude / 2 ** (exponent - 10));\n if (significand === 2048) {\n exponent += 1;\n significand = 1024;\n }\n if (exponent > 15) throw new TypeError(`${path} is outside the finite f16 range.`);\n return sign | ((exponent + 15) << 10) | (significand - 1024);\n}\n\nexport function decodeFloat16Bits(bits: number, path: string): number {\n const sign = (bits & 0x8000) === 0 ? 1 : -1;\n const exponent = (bits >>> 10) & 0x1f;\n const fraction = bits & 0x03ff;\n if (exponent === 0x1f) throw new TypeError(`${path} contains a non-finite f16 value.`);\n if (exponent === 0) return sign * fraction * 2 ** -24;\n return sign * (1 + fraction / 1024) * 2 ** (exponent - 15);\n}\n\nfunction writeScalar(view: DataView, offset: number, scalar: GpuScalarKind, value: unknown, path: string): void {\n switch (scalar) {\n case \"u32\":\n view.setUint32(offset, integer(value, 0, 0xffff_ffff, path), true);\n return;\n case \"i32\":\n view.setInt32(offset, integer(value, -0x8000_0000, 0x7fff_ffff, path), true);\n return;\n case \"f32\":\n {\n const rounded = Math.fround(numeric(value, path));\n if (!Number.isFinite(rounded)) throw new TypeError(`${path} is outside the finite f32 range.`);\n view.setFloat32(offset, rounded, true);\n }\n return;\n case \"f16\":\n view.setUint16(offset, encodeFloat16Bits(value, path), true);\n return;\n case \"bool\":\n throw new TypeError(`${path} uses bool, which is not host-shareable.`);\n }\n}\n\nfunction readScalar(view: DataView, offset: number, scalar: GpuScalarKind, path: string): number {\n switch (scalar) {\n case \"u32\":\n return view.getUint32(offset, true);\n case \"i32\":\n return view.getInt32(offset, true);\n case \"f32\":\n return view.getFloat32(offset, true);\n case \"f16\":\n return decodeFloat16Bits(view.getUint16(offset, true), path);\n case \"bool\":\n throw new TypeError(`${path} uses bool, which is not host-shareable.`);\n }\n}\n\nfunction arrayValue(value: unknown, expected: number | null, path: string): readonly unknown[] {\n if (!Array.isArray(value)) {\n throw new TypeError(`${path} must be an array.`);\n }\n if (expected !== null && value.length !== expected) {\n throw new RangeError(`${path} must contain exactly ${expected} values.`);\n }\n return value;\n}\n\nfunction assertRecordValue(\n value: unknown,\n record: GpuRecordLayout,\n path: string,\n): asserts value is Record<string, unknown> {\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n throw new TypeError(`${path} must be an object.`);\n }\n const expected = new Set(record.members.map((member) => member.name));\n for (const key of Object.keys(value)) {\n if (!expected.has(key)) throw new TypeError(`${path}.${key} is not a reflected WGSL member.`);\n }\n for (const member of record.members) {\n if (!Object.prototype.hasOwnProperty.call(value, member.name)) {\n throw new TypeError(`${path}.${member.name} is required.`);\n }\n }\n}\n\nfunction runtimeMember(record: GpuRecordLayout): { name: string; offset: number; type: GpuArrayLayout } | null {\n if (record.runtimeArrayMember === null) return null;\n const member = record.members.find((candidate) => candidate.name === record.runtimeArrayMember);\n if (!member || member.type.kind !== \"array\" || member.type.count !== null) {\n throw new TypeError(`${record.name} has an invalid runtimeArrayMember declaration.`);\n }\n if (record.members.at(-1) !== member) {\n throw new TypeError(`${record.name}.${member.name} must be the trailing member.`);\n }\n return { name: member.name, offset: member.offset, type: member.type };\n}\n\n/** Creates a strict, little-endian codec directly from reflected record layouts. */\nexport function createGpuRecordCodec<T = GpuRecordValue>(\n record: GpuRecordLayout,\n records: readonly GpuRecordLayout[] = [record],\n): GpuRecordCodec<T> {\n const byName = new Map(records.map((candidate) => [candidate.name, candidate]));\n if (!byName.has(record.name)) byName.set(record.name, record);\n const runtime = runtimeMember(record);\n\n const resolveRecord = (name: string): GpuRecordLayout => {\n const resolved = byName.get(name);\n if (!resolved) throw new TypeError(`Reflected record ${name} is unavailable to the codec.`);\n return resolved;\n };\n\n const writeType = (\n view: DataView,\n offset: number,\n type: GpuTypeLayout,\n value: unknown,\n path: string,\n ): void => {\n switch (type.kind) {\n case \"scalar\":\n writeScalar(view, offset, type.scalar, value, path);\n return;\n case \"atomic\":\n writeScalar(view, offset, type.scalar, value, path);\n return;\n case \"vector\": {\n const values = arrayValue(value, type.width, path);\n const width = scalarByteSize(type.scalar);\n values.forEach((item, index) => writeScalar(view, offset + index * width, type.scalar, item, `${path}[${index}]`));\n return;\n }\n case \"matrix\": {\n const columns = arrayValue(value, type.columns, path);\n columns.forEach((column, columnIndex) => {\n const values = arrayValue(column, type.rows, `${path}[${columnIndex}]`);\n values.forEach((item, rowIndex) =>\n writeScalar(\n view,\n offset + columnIndex * type.columnStride + rowIndex * scalarByteSize(type.scalar),\n type.scalar,\n item,\n `${path}[${columnIndex}][${rowIndex}]`,\n ),\n );\n });\n return;\n }\n case \"array\": {\n const values = arrayValue(value, type.count, path);\n values.forEach((item, index) =>\n writeType(view, offset + index * type.stride, type.element, item, `${path}[${index}]`),\n );\n return;\n }\n case \"record\":\n writeRecord(view, offset, resolveRecord(type.recordName), value, path);\n }\n };\n\n const writeRecord = (\n view: DataView,\n offset: number,\n target: GpuRecordLayout,\n value: unknown,\n path: string,\n ): void => {\n assertRecordValue(value, target, path);\n for (const member of target.members) {\n writeType(view, offset + member.offset, member.type, value[member.name], `${path}.${member.name}`);\n }\n };\n\n const readType = (\n view: DataView,\n offset: number,\n type: GpuTypeLayout,\n path: string,\n runtimeCount?: number,\n ): unknown => {\n switch (type.kind) {\n case \"scalar\":\n return readScalar(view, offset, type.scalar, path);\n case \"atomic\":\n return readScalar(view, offset, type.scalar, path);\n case \"vector\":\n return Array.from({ length: type.width }, (_, index) =>\n readScalar(view, offset + index * scalarByteSize(type.scalar), type.scalar, `${path}[${index}]`),\n );\n case \"matrix\":\n return Array.from({ length: type.columns }, (_, column) =>\n Array.from({ length: type.rows }, (_, row) =>\n readScalar(\n view,\n offset + column * type.columnStride + row * scalarByteSize(type.scalar),\n type.scalar,\n `${path}[${column}][${row}]`,\n ),\n ),\n );\n case \"array\": {\n const count = type.count ?? runtimeCount;\n if (count === undefined) throw new TypeError(`${path} requires a bounded runtime-array length.`);\n return Array.from({ length: count }, (_, index) =>\n readType(view, offset + index * type.stride, type.element, `${path}[${index}]`),\n );\n }\n case \"record\":\n return readRecord(view, offset, resolveRecord(type.recordName), path);\n }\n };\n\n const readRecord = (\n view: DataView,\n offset: number,\n target: GpuRecordLayout,\n path: string,\n rootRuntimeCount?: number,\n ): GpuRecordValue => {\n const result: Record<string, unknown> = {};\n for (const member of target.members) {\n const count = member.name === target.runtimeArrayMember ? rootRuntimeCount : undefined;\n result[member.name] = readType(view, offset + member.offset, member.type, `${path}.${member.name}`, count);\n }\n return result;\n };\n\n const byteLength = (value: T): number => {\n assertRecordValue(value, record, record.name);\n if (!runtime) {\n if (record.byteSize === null) throw new TypeError(`${record.name} is missing a fixed byte size.`);\n return record.byteSize;\n }\n const values = arrayValue(value[runtime.name], null, `${record.name}.${runtime.name}`);\n const tail = values.length * runtime.type.stride;\n const total = runtime.offset + tail;\n if (!Number.isSafeInteger(tail) || !Number.isSafeInteger(total) || total > 0xffff_ffff) {\n throw new RangeError(`${record.name}.${runtime.name} exceeds the bounded GPU buffer size.`);\n }\n return total;\n };\n\n const encodeInto = (\n value: T,\n destination: ArrayBuffer | ArrayBufferView,\n byteOffset = 0,\n ): number => {\n if (!Number.isSafeInteger(byteOffset) || byteOffset < 0) {\n throw new RangeError(\"byteOffset must be a non-negative safe integer.\");\n }\n const length = byteLength(value);\n const region = bufferRegion(destination);\n if (byteOffset + length > region.byteLength) {\n throw new RangeError(`Destination needs ${length} bytes from byteOffset ${byteOffset}.`);\n }\n const absoluteOffset = region.byteOffset + byteOffset;\n new Uint8Array(region.buffer, absoluteOffset, length).fill(0);\n writeRecord(new DataView(region.buffer), absoluteOffset, record, value, record.name);\n return length;\n };\n\n return {\n record,\n minimumByteLength: record.minimumByteSize,\n byteLength,\n encode(value: T): ArrayBuffer {\n const output = new ArrayBuffer(byteLength(value));\n encodeInto(value, output);\n return output;\n },\n encodeInto,\n decode(source, options = {}): T {\n const region = bufferRegion(source);\n const relativeOffset = options.byteOffset ?? 0;\n if (!Number.isSafeInteger(relativeOffset) || relativeOffset < 0) {\n throw new RangeError(\"byteOffset must be a non-negative safe integer.\");\n }\n const available = options.byteLength ?? region.byteLength - relativeOffset;\n if (!Number.isSafeInteger(available) || available < record.minimumByteSize) {\n throw new RangeError(`Source must provide at least ${record.minimumByteSize} bytes.`);\n }\n if (relativeOffset + available > region.byteLength) {\n throw new RangeError(\"Requested source region exceeds the supplied buffer.\");\n }\n let count: number | undefined;\n if (runtime) {\n const tailLength = available - runtime.offset;\n if (tailLength < 0 || tailLength % runtime.type.stride !== 0) {\n throw new RangeError(`${record.name}.${runtime.name} byte length is not stride-aligned.`);\n }\n count = tailLength / runtime.type.stride;\n if (!Number.isSafeInteger(count) || count > 0xffff_ffff) throw new RangeError(`${record.name}.${runtime.name} runtime count is unsafe.`);\n } else if (record.byteSize !== available) {\n throw new RangeError(`${record.name} requires exactly ${record.byteSize} bytes.`);\n }\n const absoluteOffset = region.byteOffset + relativeOffset;\n return readRecord(new DataView(region.buffer), absoluteOffset, record, record.name, count) as T;\n },\n };\n}\n","import { canonicalizeGpuContract } from \"./canonical-json.js\";\nimport type {\n GpuBindingResourceLayout,\n GpuEntryPointInterface,\n GpuInterfaceManifest,\n GpuShaderStage,\n GpuTypeLayout,\n SerializableGpuPipelineDescriptor,\n ShaderRequirements,\n ShaderVersionManifestCore,\n} from \"./contracts.js\";\n\nconst ENABLED_FEATURES: Readonly<Record<string, string>> = Object.freeze({\n f16: \"shader-f16\",\n clip_distances: \"clip-distances\",\n dual_source_blending: \"dual-source-blending\",\n subgroups: \"subgroups\",\n primitive_index: \"primitive-index\",\n subgroup_size_control: \"subgroup-size-control\",\n});\n\nconst STAGES: readonly GpuShaderStage[] = [\"vertex\", \"fragment\", \"compute\"];\nconst INTER_STAGE_FRAGMENT_BUILTINS = new Set([\n \"front_facing\",\n \"sample_index\",\n \"sample_mask\",\n \"primitive_index\",\n \"subgroup_invocation_id\",\n \"subgroup_size\",\n]);\n\nfunction commentFree(source: string): string {\n let result = \"\"; let index = 0; let blockDepth = 0; let line = false;\n while (index < source.length) {\n const pair = source.slice(index, index + 2);\n if (line) { if (source[index] === \"\\n\") { line = false; result += \"\\n\"; } else result += \" \"; index += 1; continue; }\n if (blockDepth > 0) { if (pair === \"/*\") { blockDepth += 1; result += \" \"; index += 2; continue; } if (pair === \"*/\") { blockDepth -= 1; result += \" \"; index += 2; continue; } result += source[index] === \"\\n\" ? \"\\n\" : \" \"; index += 1; continue; }\n if (pair === \"//\") { line = true; result += \" \"; index += 2; continue; }\n if (pair === \"/*\") { blockDepth = 1; result += \" \"; index += 2; continue; }\n result += source[index]; index += 1;\n }\n if (blockDepth !== 0) throw new TypeError(\"WGSL contains an unterminated block comment.\");\n return result;\n}\n\n/** Infers WebGPU device features from exact comment-free WGSL enable directives. */\nexport function inferWgslRequiredFeatures(sources: readonly string[]): readonly string[] {\n const result = new Set<string>();\n for (const source of sources) {\n const stripped = commentFree(source); const consumed = stripped.replace(/\\benable\\s+([^;]+);/gu, (_match, list: string) => {\n const names = list.split(\",\").map((item) => item.trim());\n if (names.length === 0 || names.some((name) => !/^[A-Za-z_][A-Za-z0-9_]*$/u.test(name))) throw new TypeError(\"WGSL contains a malformed enable directive.\");\n for (const name of names) { const feature = ENABLED_FEATURES[name]; if (!feature) throw new TypeError(`WGSL enable ${name} has no stable WebGPU feature mapping.`); result.add(feature); }\n return \" \".repeat(_match.length);\n });\n if (/\\benable\\b/u.test(consumed)) throw new TypeError(\"WGSL contains an unterminated or malformed enable directive.\");\n }\n return [...result].sort();\n}\n\nfunction declaredLimits(requirements: ShaderRequirements): ReadonlyMap<string, { readonly comparator: \"at-least\" | \"at-most\"; readonly value: number }> {\n return new Map(requirements.limits.map((limit) => [limit.name, limit]));\n}\n\nfunction requireAtLeast(\n limits: ReadonlyMap<string, { readonly comparator: \"at-least\" | \"at-most\"; readonly value: number }>,\n name: string,\n value: number,\n): void {\n if (value === 0) return;\n const requirement = limits.get(name);\n if (!requirement || requirement.comparator !== \"at-least\" || requirement.value < value) {\n throw new TypeError(`Shader requirements must declare ${name} at least ${value}.`);\n }\n}\n\ninterface StageResourceCounts {\n sampledTextures: number;\n samplers: number;\n storageBuffers: number;\n storageTextures: number;\n uniformBuffers: number;\n}\n\nfunction emptyResourceCounts(): StageResourceCounts {\n return { sampledTextures: 0, samplers: 0, storageBuffers: 0, storageTextures: 0, uniformBuffers: 0 };\n}\n\nfunction countResource(resource: GpuBindingResourceLayout, counts: StageResourceCounts): void {\n switch (resource.kind) {\n case \"buffer\":\n if (resource.addressSpace === \"uniform\") counts.uniformBuffers += 1;\n else counts.storageBuffers += 1;\n return;\n case \"sampler\": counts.samplers += 1; return;\n case \"texture\": counts.sampledTextures += 1; return;\n case \"storage-texture\": counts.storageTextures += 1; return;\n case \"external-texture\":\n // WebGPU expands one external texture into four sampled-texture slots,\n // one sampler slot, and one uniform-buffer slot.\n counts.sampledTextures += 4;\n counts.samplers += 1;\n counts.uniformBuffers += 1;\n }\n}\n\n/**\n * Rejects requirements that understate facts encoded directly in serializable\n * WebGPU pipeline descriptors. This is usable before reflected WGSL is loaded.\n */\nexport function validatePipelineDerivedRequirements(input: {\n readonly requirements: ShaderRequirements;\n readonly pipelines: readonly SerializableGpuPipelineDescriptor[];\n}): void {\n const limits = declaredLimits(input.requirements);\n const features = new Set(input.requirements.features);\n const formats = new Set(input.requirements.formats);\n const requiredFormats = new Set<string>();\n const requiredLimits = new Map<string, number>();\n const recordLimit = (name: string, value: number): void => {\n requiredLimits.set(name, Math.max(requiredLimits.get(name) ?? 0, value));\n };\n\n for (const pipeline of input.pipelines) {\n recordLimit(\"maxBindGroups\", pipeline.layout.bindGroups.length);\n recordLimit(\"maxBindingsPerBindGroup\", Math.max(0, ...pipeline.layout.bindGroups.map((group) => group.entries.length)));\n\n const counts = new Map<GpuShaderStage, StageResourceCounts>(STAGES.map((stage) => [stage, emptyResourceCounts()]));\n for (const group of pipeline.layout.bindGroups) {\n for (const entry of group.entries) {\n for (const stage of entry.visibility) countResource(entry.resource, counts.get(stage)!);\n if (entry.resource.kind === \"storage-texture\") requiredFormats.add(entry.resource.format);\n if (entry.resource.kind === \"buffer\") {\n recordLimit(\n entry.resource.addressSpace === \"uniform\" ? \"maxUniformBufferBindingSize\" : \"maxStorageBufferBindingSize\",\n entry.resource.minimumBindingSize,\n );\n }\n }\n }\n for (const stageCounts of counts.values()) {\n recordLimit(\"maxSampledTexturesPerShaderStage\", stageCounts.sampledTextures);\n recordLimit(\"maxSamplersPerShaderStage\", stageCounts.samplers);\n recordLimit(\"maxStorageBuffersPerShaderStage\", stageCounts.storageBuffers);\n recordLimit(\"maxStorageTexturesPerShaderStage\", stageCounts.storageTextures);\n recordLimit(\"maxUniformBuffersPerShaderStage\", stageCounts.uniformBuffers);\n }\n\n if (pipeline.kind === \"render\") {\n if (pipeline.primitive.unclippedDepth && !features.has(\"depth-clip-control\")) {\n throw new TypeError(\"Shader requirements omit pipeline-derived feature depth-clip-control.\");\n }\n recordLimit(\"maxBindGroupsPlusVertexBuffers\", pipeline.layout.bindGroups.length + pipeline.vertexBuffers.length);\n recordLimit(\"maxVertexBuffers\", pipeline.vertexBuffers.length);\n recordLimit(\"maxVertexAttributes\", pipeline.vertexBuffers.reduce((sum, buffer) => sum + buffer.attributes.length, 0));\n recordLimit(\"maxVertexBufferArrayStride\", Math.max(0, ...pipeline.vertexBuffers.map((buffer) => buffer.arrayStride)));\n recordLimit(\"maxColorAttachments\", pipeline.colorTargets.length);\n pipeline.colorTargets.forEach((target) => requiredFormats.add(target.format));\n if (pipeline.depthStencil) requiredFormats.add(pipeline.depthStencil.format);\n }\n }\n\n for (const format of requiredFormats) {\n if (!formats.has(format)) throw new TypeError(`Shader requirements list omits structurally required format ${format}.`);\n }\n for (const [name, value] of requiredLimits) requireAtLeast(limits, name, value);\n}\n\nfunction constantValue(interfaceManifest: GpuInterfaceManifest, moduleId: string, name: string, constants: Readonly<Record<string, boolean | number>>): number {\n const override = interfaceManifest.overrides.find((candidate) => candidate.moduleId === moduleId && candidate.name === name);\n if (!override) throw new TypeError(`Compute workgroup dimension references missing override ${moduleId}:${name}.`);\n const supplied = constants[name] ?? (override.id === null ? undefined : constants[String(override.id)]);\n const value = supplied ?? override.defaultValue;\n if (typeof value !== \"number\" || !Number.isSafeInteger(value) || value < 1) throw new TypeError(`Compute workgroup override ${moduleId}:${name} must resolve to a positive integer.`);\n return value;\n}\n\nfunction pipelineStages(pipeline: SerializableGpuPipelineDescriptor): readonly {\n readonly moduleId: string;\n readonly entryPoint: string;\n readonly stage: GpuShaderStage;\n}[] {\n return pipeline.kind === \"compute\"\n ? [{ moduleId: pipeline.compute.moduleId, entryPoint: pipeline.compute.entryPoint, stage: \"compute\" }]\n : [\n { moduleId: pipeline.vertex.moduleId, entryPoint: pipeline.vertex.entryPoint, stage: \"vertex\" },\n ...(pipeline.fragment ? [{ moduleId: pipeline.fragment.moduleId, entryPoint: pipeline.fragment.entryPoint, stage: \"fragment\" as const }] : []),\n ];\n}\n\nfunction reflectedEntry(\n gpuInterface: GpuInterfaceManifest,\n stage: { readonly moduleId: string; readonly entryPoint: string; readonly stage: GpuShaderStage },\n pipelineId: string,\n): GpuEntryPointInterface {\n const entry = gpuInterface.entryPoints.find((candidate) => candidate.moduleId === stage.moduleId\n && candidate.name === stage.entryPoint && candidate.stage === stage.stage);\n if (!entry) throw new TypeError(`Pipeline ${pipelineId} lacks reflected ${stage.stage} entry point ${stage.moduleId}:${stage.entryPoint}.`);\n return entry;\n}\n\nfunction orderedStages(stages: Iterable<GpuShaderStage>): readonly GpuShaderStage[] {\n return [...new Set(stages)].sort((left, right) => STAGES.indexOf(left) - STAGES.indexOf(right));\n}\n\nfunction clipDistanceSlots(entry: GpuEntryPointInterface): number {\n const clipDistances = entry.outputs.find((output) => output.locationKind === \"builtin\" && output.location === \"clip_distances\");\n if (!clipDistances) return 0;\n if (clipDistances.type.kind !== \"array\" || clipDistances.type.count === null) {\n throw new TypeError(\"Reflected clip_distances output must be a fixed-size array.\");\n }\n return Math.ceil(clipDistances.type.count / 4);\n}\n\nfunction highestLocationPlusOne(entry: GpuEntryPointInterface, direction: \"inputs\" | \"outputs\"): number {\n return Math.max(0, ...entry[direction]\n .filter((item) => item.locationKind === \"location\")\n .map((item) => Number(item.location) + 1));\n}\n\nfunction requiredInterStageVariables(\n pipeline: Extract<SerializableGpuPipelineDescriptor, { readonly kind: \"render\" }>,\n vertex: GpuEntryPointInterface,\n fragment: GpuEntryPointInterface | undefined,\n): number {\n const vertexOutputs = vertex.outputs.filter((output) => output.locationKind === \"location\").length;\n const reservedVertexSlots = (pipeline.primitive.topology === \"point-list\" ? 1 : 0) + clipDistanceSlots(vertex);\n let required = Math.max(\n vertexOutputs + reservedVertexSlots,\n highestLocationPlusOne(vertex, \"outputs\") + reservedVertexSlots,\n );\n if (fragment) {\n const fragmentInputs = fragment.inputs.filter((input) => input.locationKind === \"location\").length;\n const fragmentBuiltins = fragment.inputs.filter((input) =>\n input.locationKind === \"builtin\" && INTER_STAGE_FRAGMENT_BUILTINS.has(String(input.location))).length;\n required = Math.max(\n required,\n fragmentInputs + fragmentBuiltins,\n highestLocationPlusOne(fragment, \"inputs\"),\n );\n }\n return required;\n}\n\nfunction interStageComponentCount(\n type: GpuTypeLayout,\n gpuInterface: GpuInterfaceManifest,\n activeRecords = new Set<string>(),\n): number {\n switch (type.kind) {\n case \"scalar\":\n case \"atomic\":\n return 1;\n case \"vector\":\n return type.width;\n case \"matrix\":\n return type.columns * type.rows;\n case \"array\":\n if (type.count === null) throw new TypeError(\"Inter-stage IO cannot contain a runtime-sized array.\");\n return type.count * interStageComponentCount(type.element, gpuInterface, activeRecords);\n case \"record\": { // Defensive support for reflectors that retain an IO structure reference.\n if (activeRecords.has(type.recordName)) throw new TypeError(`Inter-stage IO record ${type.recordName} is recursive.`);\n const record = gpuInterface.records.find((candidate) => candidate.name === type.recordName);\n if (!record) throw new TypeError(`Inter-stage IO references missing record ${type.recordName}.`);\n const nested = new Set(activeRecords);\n nested.add(type.recordName);\n return record.members.reduce(\n (sum, member) => sum + interStageComponentCount(member.type, gpuInterface, nested),\n 0,\n );\n }\n }\n}\n\nfunction requiredInterStageComponents(\n vertex: GpuEntryPointInterface,\n fragment: GpuEntryPointInterface | undefined,\n gpuInterface: GpuInterfaceManifest,\n): number {\n const countLocations = (items: GpuEntryPointInterface[\"inputs\"]): number => items\n .filter((item) => item.locationKind === \"location\")\n .reduce((sum, item) => sum + interStageComponentCount(item.type, gpuInterface), 0);\n return Math.max(\n countLocations(vertex.outputs),\n fragment ? countLocations(fragment.inputs) : 0,\n );\n}\n\n/**\n * Rejects interface/pipeline requirements that understate exact reflected ABI\n * semantics, entry-point resource usage, inter-stage IO, or compute workgroups.\n */\nexport function validateShaderInterfaceRequirements(input: {\n readonly manifest: ShaderVersionManifestCore;\n readonly gpuInterface: GpuInterfaceManifest;\n}): void {\n const { manifest, gpuInterface } = input;\n if (manifest.gpuInterface.interfaceId !== gpuInterface.interfaceId\n || manifest.gpuInterface.interfaceVersion !== gpuInterface.interfaceVersion\n || manifest.gpuInterface.interfaceAbiHash !== gpuInterface.interfaceAbiHash\n || manifest.gpuInterface.modelAbiHash !== gpuInterface.modelAbiHash) {\n throw new TypeError(\"Shader GPU interface reference differs from the reflected interface identity.\");\n }\n const manifestModules = [...manifest.modules]\n .map(({ moduleId, sha256 }) => ({ moduleId, sha256 }))\n .sort((left, right) => left.moduleId < right.moduleId ? -1 : left.moduleId > right.moduleId ? 1 : 0);\n const interfaceModules = [...gpuInterface.modules]\n .map(({ moduleId, sha256 }) => ({ moduleId, sha256 }))\n .sort((left, right) => left.moduleId < right.moduleId ? -1 : left.moduleId > right.moduleId ? 1 : 0);\n if (canonicalizeGpuContract(manifestModules) !== canonicalizeGpuContract(interfaceModules)) {\n throw new TypeError(\"Shader modules differ from the exact reflected interface module set.\");\n }\n\n validatePipelineDerivedRequirements({ requirements: manifest.requirements, pipelines: manifest.pipelines });\n const requiredSemantics = new Set(gpuInterface.modelAbi.semantics.map((projection) => projection.semantic));\n const declaredSemantics = new Set(manifest.requirements.semantics);\n for (const semantic of requiredSemantics) {\n if (!declaredSemantics.has(semantic)) throw new TypeError(`Shader requirements omit reflected model semantic ${semantic}.`);\n }\n\n const limits = declaredLimits(manifest.requirements);\n for (const pipeline of manifest.pipelines) {\n const stages = pipelineStages(pipeline);\n const entries = stages.map((stage) => ({ stage, entry: reflectedEntry(gpuInterface, stage, pipeline.pipelineId) }));\n for (const group of pipeline.layout.bindGroups) {\n for (const descriptorEntry of group.entries) {\n const used = entries.filter(({ stage, entry }) =>\n entry.bindingKeys.includes(`${stage.moduleId}:${group.group}:${descriptorEntry.binding}`));\n if (used.length === 0) throw new TypeError(`Pipeline ${pipeline.pipelineId} binding ${group.group}:${descriptorEntry.binding} is absent from its reflected entry points.`);\n if (canonicalizeGpuContract(orderedStages(descriptorEntry.visibility))\n !== canonicalizeGpuContract(orderedStages(used.map(({ stage }) => stage.stage)))) {\n throw new TypeError(`Pipeline ${pipeline.pipelineId} binding ${group.group}:${descriptorEntry.binding} visibility differs from reflected entry-point usage.`);\n }\n for (const { stage } of used) {\n const reflected = gpuInterface.bindings.find((binding) => binding.moduleId === stage.moduleId\n && binding.group === group.group && binding.binding === descriptorEntry.binding);\n if (!reflected || canonicalizeGpuContract(reflected.resource) !== canonicalizeGpuContract(descriptorEntry.resource)) {\n throw new TypeError(`Pipeline ${pipeline.pipelineId} binding ${stage.moduleId}:${group.group}:${descriptorEntry.binding} differs from the reflected interface.`);\n }\n }\n }\n }\n for (const { stage, entry } of entries) {\n for (const key of entry.bindingKeys) {\n const declared = pipeline.layout.bindGroups.some((group) => group.entries.some((descriptorEntry) =>\n key === `${stage.moduleId}:${group.group}:${descriptorEntry.binding}`));\n if (!declared) throw new TypeError(`Pipeline ${pipeline.pipelineId} omits reflected binding ${key}.`);\n }\n }\n\n if (pipeline.kind === \"compute\") {\n const entry = entries[0]?.entry;\n if (!entry?.workgroupSize) throw new TypeError(`Compute pipeline ${pipeline.pipelineId} lacks an exact reflected workgroup size.`);\n if (entry.workgroupStorageSize === null) throw new TypeError(`Compute pipeline ${pipeline.pipelineId} lacks an exact reflected workgroup storage size.`);\n const values = entry.workgroupSize.map((dimension) => dimension.kind === \"literal\" ? dimension.value : constantValue(gpuInterface, entry.moduleId, dimension.name, pipeline.compute.constants)) as [number, number, number];\n const invocations = values[0] * values[1] * values[2];\n if (!Number.isSafeInteger(invocations)) throw new TypeError(`Compute pipeline ${pipeline.pipelineId} workgroup invocation count is outside the safe manifest range.`);\n requireAtLeast(limits, \"maxComputeWorkgroupSizeX\", values[0]);\n requireAtLeast(limits, \"maxComputeWorkgroupSizeY\", values[1]);\n requireAtLeast(limits, \"maxComputeWorkgroupSizeZ\", values[2]);\n requireAtLeast(limits, \"maxComputeInvocationsPerWorkgroup\", invocations);\n requireAtLeast(limits, \"maxComputeWorkgroupStorageSize\", entry.workgroupStorageSize);\n } else {\n const vertex = entries.find(({ stage }) => stage.stage === \"vertex\")?.entry;\n const fragment = entries.find(({ stage }) => stage.stage === \"fragment\")?.entry;\n if (!vertex) throw new TypeError(`Render pipeline ${pipeline.pipelineId} lacks an exact reflected vertex entry point.`);\n requireAtLeast(limits, \"maxInterStageShaderVariables\", requiredInterStageVariables(pipeline, vertex, fragment));\n requireAtLeast(limits, \"maxInterStageShaderComponents\", requiredInterStageComponents(vertex, fragment, gpuInterface));\n }\n }\n}\n\n/** Rejects caller-declared requirements that understate facts derived from exact modules/interfaces. */\nexport function validateShaderDerivedRequirements(input: {\n readonly manifest: ShaderVersionManifestCore;\n readonly gpuInterface: GpuInterfaceManifest;\n readonly moduleSources: ReadonlyMap<string, string>;\n}): void {\n const expectedModuleIds = [...input.manifest.modules.map((module) => module.moduleId)].sort(); const actualModuleIds = [...input.moduleSources.keys()].sort();\n if (expectedModuleIds.join(\"\\n\") !== actualModuleIds.join(\"\\n\")) throw new TypeError(\"Derived-requirement source modules differ from the exact shader manifest module set.\");\n validateShaderInterfaceRequirements(input);\n const features = new Set(input.manifest.requirements.features);\n for (const feature of inferWgslRequiredFeatures([...input.moduleSources.values()])) if (!features.has(feature)) throw new TypeError(`Shader requirements omit WGSL-derived feature ${feature}.`);\n}\n","import {\n GPU_INTERFACE_MANIFEST_VERSION,\n SHADER_QUALIFICATION_FIXTURE_VERSION,\n SHADER_STYLE_PROFILE_MANIFEST_VERSION,\n SHADER_VERSION_MANIFEST_VERSION,\n SUPPORTED_ADDITIVE_WEBGPU_MATRIX_POLICIES,\n SUPPORTED_STABLE_WEBGPU_MATRIX_POLICIES,\n type GpuBindingResourceLayout,\n type GpuInterfaceManifest,\n type ModelGpuCompatibilityDescriptor,\n type GpuRecordLayout,\n type GpuTypeLayout,\n type SerializableGpuPipelineDescriptor,\n type ShaderStyleProfileManifest,\n type ShaderQualificationModelCompatibilityFixture,\n type ShaderVersionManifest,\n type ShaderVersionManifestCore,\n} from \"./contracts.js\";\nimport { canonicalizeGpuContract as canonicalizeForValidation } from \"./canonical-json.js\";\nimport { assertImmutableAssetVersion } from \"./asset-version.js\";\nimport { asSha256Hex } from \"./hash.js\";\nimport { validatePipelineDerivedRequirements } from \"./requirements-validation.js\";\n\ntype UnknownRecord = Record<string, unknown>;\nconst stages = [\"vertex\", \"fragment\", \"compute\"] as const;\nconst roles = [\"material\", \"lighting\", \"outline\", \"shadow\", \"post-processing\"] as const;\n\nfunction detachedJson(value: unknown, path: string): unknown {\n try {\n return JSON.parse(canonicalizeForValidation(value)) as unknown;\n } catch (cause) {\n const detail = cause instanceof Error ? cause.message : \"Contract snapshot failed.\";\n const boundedDetail = [...detail].slice(0, 512).join(\"\");\n throw new TypeError(`${path} must contain detached JSON contract data: ${boundedDetail}`, { cause });\n }\n}\n\nfunction object(value: unknown, path: string): UnknownRecord {\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) throw new TypeError(`${path} must be an object.`);\n return value as UnknownRecord;\n}\n\nfunction exact(value: UnknownRecord, keys: readonly string[], path: string): void {\n const allowed = new Set(keys);\n for (const key of Object.keys(value)) if (!allowed.has(key)) throw new TypeError(`${path}.${key} is not part of this contract version.`);\n for (const key of keys) if (!(key in value)) throw new TypeError(`${path}.${key} is required.`);\n}\n\nfunction text(value: unknown, path: string, maximum = 512): string {\n if (typeof value !== \"string\" || value.length === 0 || value.length > maximum || [...value].some((character) => character.charCodeAt(0) <= 0x1f)) {\n throw new TypeError(`${path} must be a bounded non-empty string without control characters.`);\n }\n return value;\n}\n\nfunction token(value: unknown, path: string): string {\n const result = text(value, path, 160);\n if (!/^[A-Za-z0-9][A-Za-z0-9._:/-]*$/u.test(result) || result.includes(\"..\")) throw new TypeError(`${path} must be a safe token.`);\n return result;\n}\n\nfunction immutableVersion(value: unknown, path: string): string {\n try {\n return assertImmutableAssetVersion(value);\n } catch (cause) {\n throw new TypeError(\n `${path} must be an immutable asset version: exact token required; mutable aliases, ranges, wildcards, and URLs are not allowed.`,\n { cause },\n );\n }\n}\n\nfunction enumeration<T extends string | number>(value: unknown, values: readonly T[], path: string): T {\n if (!values.includes(value as T)) throw new TypeError(`${path} is invalid.`);\n return value as T;\n}\n\nfunction integer(value: unknown, path: string, minimum = 0, maximum = 0xffff_ffff): number {\n if (!Number.isSafeInteger(value) || (value as number) < minimum || (value as number) > maximum) {\n throw new TypeError(`${path} must be an integer from ${minimum} through ${maximum}.`);\n }\n return value as number;\n}\n\nfunction finite(value: unknown, path: string): number {\n if (typeof value !== \"number\" || !Number.isFinite(value)) throw new TypeError(`${path} must be finite.`);\n return value;\n}\n\nfunction array(value: unknown, path: string, maximum = 4096): readonly unknown[] {\n if (!Array.isArray(value) || value.length > maximum) throw new TypeError(`${path} must be a bounded array.`);\n return value;\n}\n\nfunction nullableInteger(value: unknown, path: string): number | null {\n return value === null ? null : integer(value, path);\n}\n\nfunction nullableToken(value: unknown, path: string): string | null {\n return value === null ? null : token(value, path);\n}\n\nfunction digest(value: unknown, path: string): string {\n try { return asSha256Hex(text(value, path, 64)); }\n catch (cause) { throw new TypeError(`${path} must be a lowercase SHA-256 digest.`, { cause }); }\n}\n\nfunction uri(value: unknown, path: string): string {\n const result = text(value, path, 2048);\n let parsed: URL;\n try { parsed = new URL(result); }\n catch (cause) { throw new TypeError(`${path} must be an absolute immutable asset URI.`, { cause }); }\n if (parsed.protocol !== \"https:\" || parsed.username || parsed.password || parsed.hash) throw new TypeError(`${path} must be credential-free HTTPS without a fragment.`);\n const keys = [...parsed.searchParams.keys()].map((key) => key.toLowerCase());\n const forbidden = new Set([\"sig\", \"se\", \"sp\", \"sv\", \"spr\", \"st\", \"skoid\", \"sktid\", \"skt\", \"ske\", \"sks\", \"skv\"]);\n if (keys.some((key) => forbidden.has(key)) || new Set(keys).size !== keys.length) throw new TypeError(`${path} must not contain SAS credentials or duplicate query parameters.`);\n if (parsed.href !== result) throw new TypeError(`${path} must use its canonical URL serialization.`);\n return result;\n}\n\nfunction unique<T>(values: readonly T[], key: (value: T) => string, path: string): void {\n const seen = new Set<string>();\n for (const value of values) {\n const identity = key(value);\n if (seen.has(identity)) throw new TypeError(`${path} contains duplicate ${identity}.`);\n seen.add(identity);\n }\n}\n\nfunction tokenArray(value: unknown, path: string, maximum = 4096): string[] {\n const result = array(value, path, maximum).map((item, index) => token(item, `${path}[${index}]`));\n unique(result, String, path);\n return result;\n}\n\nfunction typeLayout(value: unknown, path: string, depth = 0): GpuTypeLayout {\n if (depth > 24) throw new TypeError(`${path} exceeds the type nesting limit.`);\n const input = object(value, path);\n const kind = enumeration(input.kind, [\"scalar\", \"atomic\", \"vector\", \"matrix\", \"array\", \"record\"] as const, `${path}.kind`);\n integer(input.alignment, `${path}.alignment`, 1);\n if (kind === \"array\") {\n exact(input, [\"kind\", \"element\", \"count\", \"stride\", \"alignment\", \"byteSize\"], path);\n const element = typeLayout(input.element, `${path}.element`, depth + 1);\n const count = nullableInteger(input.count, `${path}.count`);\n const stride = integer(input.stride, `${path}.stride`, 1);\n const byteSize = nullableInteger(input.byteSize, `${path}.byteSize`);\n if (input.alignment !== element.alignment || stride % element.alignment !== 0\n || element.byteSize === null || stride < element.byteSize\n || (count === null ? byteSize !== null : byteSize !== count * stride)) {\n throw new TypeError(`${path} has inconsistent array layout algebra.`);\n }\n } else if (kind === \"record\") {\n exact(input, [\"kind\", \"recordName\", \"alignment\", \"byteSize\"], path);\n token(input.recordName, `${path}.recordName`);\n nullableInteger(input.byteSize, `${path}.byteSize`);\n } else {\n integer(input.byteSize, `${path}.byteSize`, 1);\n if (kind === \"scalar\") {\n exact(input, [\"kind\", \"scalar\", \"alignment\", \"byteSize\"], path);\n enumeration(input.scalar, [\"i32\", \"u32\", \"f32\", \"f16\", \"bool\"] as const, `${path}.scalar`);\n const size = input.scalar === \"f16\" ? 2 : 4;\n if (input.alignment !== size || input.byteSize !== size) throw new TypeError(`${path} has inconsistent scalar layout.`);\n } else if (kind === \"atomic\") {\n exact(input, [\"kind\", \"scalar\", \"alignment\", \"byteSize\"], path);\n enumeration(input.scalar, [\"i32\", \"u32\"] as const, `${path}.scalar`);\n if (input.alignment !== 4 || input.byteSize !== 4) throw new TypeError(`${path} has inconsistent atomic layout.`);\n } else if (kind === \"vector\") {\n exact(input, [\"kind\", \"scalar\", \"width\", \"alignment\", \"byteSize\"], path);\n enumeration(input.scalar, [\"i32\", \"u32\", \"f32\", \"f16\", \"bool\"] as const, `${path}.scalar`);\n const width = enumeration(input.width, [2, 3, 4] as const, `${path}.width`);\n const scalarSize = input.scalar === \"f16\" ? 2 : 4;\n if (input.alignment !== (width === 2 ? 2 : 4) * scalarSize || input.byteSize !== width * scalarSize) throw new TypeError(`${path} has inconsistent vector layout.`);\n } else {\n exact(input, [\"kind\", \"scalar\", \"columns\", \"rows\", \"columnStride\", \"alignment\", \"byteSize\"], path);\n enumeration(input.scalar, [\"f32\", \"f16\"] as const, `${path}.scalar`);\n const columns = enumeration(input.columns, [2, 3, 4] as const, `${path}.columns`);\n const rows = enumeration(input.rows, [2, 3, 4] as const, `${path}.rows`);\n const stride = integer(input.columnStride, `${path}.columnStride`, 1);\n const scalarSize = input.scalar === \"f16\" ? 2 : 4;\n const alignment = (rows === 2 ? 2 : 4) * scalarSize;\n if (input.alignment !== alignment || stride !== Math.ceil((rows * scalarSize) / alignment) * alignment || input.byteSize !== columns * stride) throw new TypeError(`${path} has inconsistent matrix layout.`);\n }\n }\n return input as unknown as GpuTypeLayout;\n}\n\nfunction recordLayout(value: unknown, path: string): GpuRecordLayout {\n const input = object(value, path);\n exact(input, [\"name\", \"alignment\", \"byteSize\", \"minimumByteSize\", \"runtimeArrayMember\", \"addressSpaces\", \"members\"], path);\n token(input.name, `${path}.name`);\n integer(input.alignment, `${path}.alignment`, 1);\n nullableInteger(input.byteSize, `${path}.byteSize`);\n integer(input.minimumByteSize, `${path}.minimumByteSize`);\n nullableToken(input.runtimeArrayMember, `${path}.runtimeArrayMember`);\n const spaces = array(input.addressSpaces, `${path}.addressSpaces`, 5).map((space, index) =>\n enumeration(space, [\"uniform\", \"storage\", \"function\", \"private\", \"workgroup\"] as const, `${path}.addressSpaces[${index}]`));\n unique(spaces, String, `${path}.addressSpaces`);\n const members = array(input.members, `${path}.members`);\n let priorEnd = 0;\n const names: string[] = [];\n members.forEach((value, index) => {\n const memberPath = `${path}.members[${index}]`;\n const member = object(value, memberPath);\n exact(member, [\"name\", \"offset\", \"alignment\", \"valueByteSize\", \"occupiedByteSize\", \"explicitAlign\", \"explicitSize\", \"type\"], memberPath);\n names.push(token(member.name, `${memberPath}.name`));\n const offset = integer(member.offset, `${memberPath}.offset`);\n const alignment = integer(member.alignment, `${memberPath}.alignment`, 1);\n const valueSize = nullableInteger(member.valueByteSize, `${memberPath}.valueByteSize`);\n const occupied = nullableInteger(member.occupiedByteSize, `${memberPath}.occupiedByteSize`);\n const explicitAlign = member.explicitAlign === null ? null : integer(member.explicitAlign, `${memberPath}.explicitAlign`, 1);\n const explicitSize = member.explicitSize === null ? null : integer(member.explicitSize, `${memberPath}.explicitSize`, 1);\n const type = typeLayout(member.type, `${memberPath}.type`);\n if (explicitAlign !== null && ((explicitAlign & (explicitAlign - 1)) !== 0 || explicitAlign < type.alignment)) {\n throw new TypeError(`${memberPath}.explicitAlign must be a power of two no smaller than the natural alignment.`);\n }\n if (explicitSize !== null && (type.byteSize === null || explicitSize < type.byteSize)) {\n throw new TypeError(`${memberPath}.explicitSize must not shrink a fixed-size WGSL type.`);\n }\n if (offset < priorEnd || offset % alignment !== 0 || alignment !== (explicitAlign ?? type.alignment)\n || valueSize !== type.byteSize || occupied !== (explicitSize ?? type.byteSize)\n || (occupied !== null && valueSize !== null && occupied < valueSize)) {\n throw new TypeError(`${memberPath} has inconsistent member layout algebra.`);\n }\n if (occupied === null && index !== members.length - 1) throw new TypeError(`${memberPath} is a non-final runtime array.`);\n if (occupied !== null) priorEnd = offset + occupied;\n });\n unique(names, String, `${path}.members`);\n if ((input.byteSize === null) !== (input.runtimeArrayMember !== null)) throw new TypeError(`${path} has inconsistent runtime array metadata.`);\n const maximumAlignment = Math.max(1, ...members.map((value) => Number((value as UnknownRecord).alignment)));\n if (input.alignment !== maximumAlignment) throw new TypeError(`${path}.alignment is inconsistent with its members.`);\n const tail = members.at(-1) as UnknownRecord | undefined;\n const expectedMinimum = input.runtimeArrayMember === null\n ? Math.ceil(priorEnd / Number(input.alignment)) * Number(input.alignment)\n : Number(tail?.offset ?? 0);\n if (input.minimumByteSize !== expectedMinimum || (input.byteSize !== null && input.byteSize !== expectedMinimum)\n || (input.runtimeArrayMember !== null && tail?.name !== input.runtimeArrayMember)) {\n throw new TypeError(`${path} has inconsistent fixed/runtime size metadata.`);\n }\n if (input.runtimeArrayMember !== null) {\n const tailType = tail?.type as GpuTypeLayout | undefined;\n if (!tailType || tailType.kind !== \"array\" || tailType.count !== null) throw new TypeError(`${path}.runtimeArrayMember must name a direct trailing runtime-sized array.`);\n }\n return input as unknown as GpuRecordLayout;\n}\n\nfunction bindingResource(value: unknown, path: string): GpuBindingResourceLayout {\n const input = object(value, path);\n const kind = enumeration(input.kind, [\"buffer\", \"sampler\", \"texture\", \"storage-texture\", \"external-texture\"] as const, `${path}.kind`);\n if (kind === \"buffer\") {\n exact(input, [\"kind\", \"addressSpace\", \"access\", \"recordName\", \"minimumBindingSize\"], path);\n enumeration(input.addressSpace, [\"uniform\", \"storage\"] as const, `${path}.addressSpace`);\n enumeration(input.access, [\"read\", \"write\", \"read_write\"] as const, `${path}.access`);\n if (input.addressSpace === \"uniform\" && input.access !== \"read\") throw new TypeError(`${path}.access must be read for uniform buffers.`);\n nullableToken(input.recordName, `${path}.recordName`);\n integer(input.minimumBindingSize, `${path}.minimumBindingSize`);\n } else if (kind === \"sampler\") {\n exact(input, [\"kind\", \"samplerType\"], path);\n enumeration(input.samplerType, [\"filtering\", \"non-filtering\", \"comparison\"] as const, `${path}.samplerType`);\n } else if (kind === \"texture\") {\n exact(input, [\"kind\", \"sampleType\", \"viewDimension\", \"multisampled\"], path);\n enumeration(input.sampleType, [\"float\", \"unfilterable-float\", \"depth\", \"sint\", \"uint\"] as const, `${path}.sampleType`);\n enumeration(input.viewDimension, [\"1d\", \"2d\", \"2d-array\", \"cube\", \"cube-array\", \"3d\"] as const, `${path}.viewDimension`);\n if (typeof input.multisampled !== \"boolean\") throw new TypeError(`${path}.multisampled must be boolean.`);\n } else if (kind === \"storage-texture\") {\n exact(input, [\"kind\", \"access\", \"format\", \"viewDimension\"], path);\n enumeration(input.access, [\"write-only\", \"read-only\", \"read-write\"] as const, `${path}.access`);\n token(input.format, `${path}.format`);\n enumeration(input.viewDimension, [\"1d\", \"2d\", \"2d-array\", \"3d\"] as const, `${path}.viewDimension`);\n } else exact(input, [\"kind\"], path);\n return input as unknown as GpuBindingResourceLayout;\n}\n\nfunction visibility(value: unknown, path: string): (typeof stages)[number][] {\n const result = array(value, path, 3).map((item, index) => enumeration(item, stages, `${path}[${index}]`));\n unique(result, String, path);\n if (result.length === 0) throw new TypeError(`${path} must include at least one shader stage.`);\n return result;\n}\n\nfunction binding(value: unknown, path: string, coordinates = true): UnknownRecord {\n const input = object(value, path);\n exact(input, coordinates\n ? [\"moduleId\", \"variableName\", \"group\", \"binding\", \"resource\", \"visibility\"]\n : [\"source\", \"resource\", \"semantic\"], path);\n if (coordinates) {\n token(input.moduleId, `${path}.moduleId`); token(input.variableName, `${path}.variableName`);\n integer(input.group, `${path}.group`); integer(input.binding, `${path}.binding`);\n visibility(input.visibility, `${path}.visibility`);\n } else {\n const source = object(input.source, `${path}.source`); exact(source, [\"moduleId\", \"group\", \"binding\"], `${path}.source`);\n token(source.moduleId, `${path}.source.moduleId`); integer(source.group, `${path}.source.group`); integer(source.binding, `${path}.source.binding`);\n nullableToken(input.semantic, `${path}.semantic`);\n }\n bindingResource(input.resource, `${path}.resource`);\n return input;\n}\n\nfunction entryIo(value: unknown, path: string): UnknownRecord {\n const input = object(value, path);\n exact(input, [\"name\", \"locationKind\", \"location\", \"interpolation\", \"type\"], path);\n token(input.name, `${path}.name`);\n const kind = enumeration(input.locationKind, [\"location\", \"builtin\"] as const, `${path}.locationKind`);\n if (kind === \"location\") integer(input.location, `${path}.location`); else token(input.location, `${path}.location`);\n if (input.interpolation !== null) token(input.interpolation, `${path}.interpolation`);\n typeLayout(input.type, `${path}.type`);\n return input;\n}\n\nfunction vertexInput(value: unknown, path: string, model = false): UnknownRecord {\n const input = object(value, path);\n if (model) {\n exact(input, [\"source\", \"format\", \"offset\", \"arrayStride\", \"stepMode\", \"semantic\"], path);\n const source = object(input.source, `${path}.source`); exact(source, [\"pipelineId\", \"shaderLocation\"], `${path}.source`);\n token(source.pipelineId, `${path}.source.pipelineId`); integer(source.shaderLocation, `${path}.source.shaderLocation`);\n token(input.semantic, `${path}.semantic`);\n } else {\n exact(input, [\"pipelineId\", \"moduleId\", \"entryPoint\", \"shaderLocation\", \"shaderType\", \"bufferSlot\", \"format\", \"offset\", \"arrayStride\", \"stepMode\", \"semantic\"], path);\n token(input.pipelineId, `${path}.pipelineId`); token(input.moduleId, `${path}.moduleId`); token(input.entryPoint, `${path}.entryPoint`);\n integer(input.shaderLocation, `${path}.shaderLocation`); typeLayout(input.shaderType, `${path}.shaderType`); integer(input.bufferSlot, `${path}.bufferSlot`);\n nullableToken(input.semantic, `${path}.semantic`);\n }\n token(input.format, `${path}.format`); integer(input.offset, `${path}.offset`); integer(input.arrayStride, `${path}.arrayStride`);\n enumeration(input.stepMode, [\"vertex\", \"instance\"] as const, `${path}.stepMode`);\n return input;\n}\n\nfunction semantic(value: unknown, path: string): UnknownRecord {\n const input = object(value, path); exact(input, [\"semantic\", \"source\"], path); token(input.semantic, `${path}.semantic`);\n const source = object(input.source, `${path}.source`);\n const kind = enumeration(source.kind, [\"record-member\", \"vertex-attribute\", \"binding\"] as const, `${path}.source.kind`);\n if (kind === \"record-member\") {\n exact(source, [\"kind\", \"recordName\", \"memberPath\"], `${path}.source`); token(source.recordName, `${path}.source.recordName`);\n tokenArray(source.memberPath, `${path}.source.memberPath`, 24);\n } else if (kind === \"vertex-attribute\") {\n exact(source, [\"kind\", \"pipelineId\", \"shaderLocation\"], `${path}.source`); token(source.pipelineId, `${path}.source.pipelineId`); integer(source.shaderLocation, `${path}.source.shaderLocation`);\n } else {\n exact(source, [\"kind\", \"moduleId\", \"group\", \"binding\"], `${path}.source`); token(source.moduleId, `${path}.source.moduleId`);\n integer(source.group, `${path}.source.group`); integer(source.binding, `${path}.source.binding`);\n }\n return input;\n}\n\nfunction interfaceRef(value: unknown, path: string): UnknownRecord {\n const input = object(value, path); exact(input, [\"interfaceId\", \"interfaceVersion\", \"manifestUri\", \"manifestSha256\", \"interfaceAbiHash\", \"modelAbiHash\"], path);\n token(input.interfaceId, `${path}.interfaceId`); immutableVersion(input.interfaceVersion, `${path}.interfaceVersion`); uri(input.manifestUri, `${path}.manifestUri`);\n digest(input.manifestSha256, `${path}.manifestSha256`); digest(input.interfaceAbiHash, `${path}.interfaceAbiHash`); digest(input.modelAbiHash, `${path}.modelAbiHash`);\n return input;\n}\n\nfunction programmable(value: unknown, path: string, moduleIds: ReadonlySet<string>): UnknownRecord {\n const input = object(value, path); exact(input, [\"moduleId\", \"entryPoint\", \"constants\"], path);\n const moduleId = token(input.moduleId, `${path}.moduleId`); if (!moduleIds.has(moduleId)) throw new TypeError(`${path}.moduleId is not in modules.`);\n token(input.entryPoint, `${path}.entryPoint`);\n const constants = object(input.constants, `${path}.constants`);\n for (const [name, value] of Object.entries(constants)) { token(name, `${path}.constants key`); if (typeof value !== \"boolean\") finite(value, `${path}.constants.${name}`); }\n return input;\n}\n\nfunction pipeline(value: unknown, path: string, moduleIds: ReadonlySet<string>): SerializableGpuPipelineDescriptor {\n const input = object(value, path); const kind = enumeration(input.kind, [\"compute\", \"render\"] as const, `${path}.kind`);\n const common = kind === \"compute\" ? [\"kind\", \"pipelineId\", \"layout\", \"compute\"] : [\"kind\", \"pipelineId\", \"layout\", \"vertex\", \"fragment\", \"vertexBuffers\", \"primitive\", \"colorTargets\", \"depthStencil\", \"multisample\"];\n exact(input, common, path); token(input.pipelineId, `${path}.pipelineId`);\n const layout = object(input.layout, `${path}.layout`); exact(layout, [\"bindGroups\"], `${path}.layout`);\n const groups = array(layout.bindGroups, `${path}.layout.bindGroups`);\n const groupIds: number[] = [];\n groups.forEach((value, groupIndex) => {\n const groupPath = `${path}.layout.bindGroups[${groupIndex}]`; const group = object(value, groupPath); exact(group, [\"group\", \"entries\"], groupPath);\n const groupId = integer(group.group, `${groupPath}.group`); groupIds.push(groupId);\n const entries = array(group.entries, `${groupPath}.entries`); const bindingIds: number[] = [];\n entries.forEach((entryValue, entryIndex) => {\n const entryPath = `${groupPath}.entries[${entryIndex}]`; const entry = object(entryValue, entryPath);\n exact(entry, [\"group\", \"binding\", \"resource\", \"visibility\"], entryPath);\n if (integer(entry.group, `${entryPath}.group`) !== groupId) throw new TypeError(`${entryPath}.group differs from its parent.`);\n bindingIds.push(integer(entry.binding, `${entryPath}.binding`)); bindingResource(entry.resource, `${entryPath}.resource`); visibility(entry.visibility, `${entryPath}.visibility`);\n });\n unique(bindingIds, String, `${groupPath}.entries`);\n });\n unique(groupIds, String, `${path}.layout.bindGroups`);\n [...groupIds].sort((a, b) => a - b).forEach((group, index) => { if (group !== index) throw new TypeError(`${path}.layout.bindGroups must be contiguous from zero.`); });\n if (kind === \"compute\") programmable(input.compute, `${path}.compute`, moduleIds);\n else {\n programmable(input.vertex, `${path}.vertex`, moduleIds); if (input.fragment !== null) programmable(input.fragment, `${path}.fragment`, moduleIds);\n array(input.vertexBuffers, `${path}.vertexBuffers`, 16).forEach((value, bufferIndex) => {\n const bufferPath = `${path}.vertexBuffers[${bufferIndex}]`; const buffer = object(value, bufferPath); exact(buffer, [\"arrayStride\", \"stepMode\", \"attributes\"], bufferPath);\n integer(buffer.arrayStride, `${bufferPath}.arrayStride`, 0, 2048); enumeration(buffer.stepMode, [\"vertex\", \"instance\"] as const, `${bufferPath}.stepMode`);\n array(buffer.attributes, `${bufferPath}.attributes`, 16).forEach((value, attributeIndex) => {\n const attributePath = `${bufferPath}.attributes[${attributeIndex}]`; const attribute = object(value, attributePath); exact(attribute, [\"format\", \"offset\", \"shaderLocation\", \"semantic\"], attributePath);\n token(attribute.format, `${attributePath}.format`); integer(attribute.offset, `${attributePath}.offset`); integer(attribute.shaderLocation, `${attributePath}.shaderLocation`); nullableToken(attribute.semantic, `${attributePath}.semantic`);\n });\n });\n const primitive = object(input.primitive, `${path}.primitive`); exact(primitive, [\"topology\", \"stripIndexFormat\", \"frontFace\", \"cullMode\", \"unclippedDepth\"], `${path}.primitive`);\n const topology = enumeration(primitive.topology, [\"point-list\", \"line-list\", \"line-strip\", \"triangle-list\", \"triangle-strip\"] as const, `${path}.primitive.topology`);\n if (primitive.stripIndexFormat !== null) enumeration(primitive.stripIndexFormat, [\"uint16\", \"uint32\"] as const, `${path}.primitive.stripIndexFormat`);\n if (primitive.stripIndexFormat !== null && topology !== \"line-strip\" && topology !== \"triangle-strip\") throw new TypeError(`${path}.primitive.stripIndexFormat is only valid for strip topologies.`);\n enumeration(primitive.frontFace, [\"ccw\", \"cw\"] as const, `${path}.primitive.frontFace`); enumeration(primitive.cullMode, [\"none\", \"front\", \"back\"] as const, `${path}.primitive.cullMode`); if (typeof primitive.unclippedDepth !== \"boolean\") throw new TypeError(`${path}.primitive.unclippedDepth must be boolean.`);\n const compare = [\"never\", \"less\", \"equal\", \"less-equal\", \"greater\", \"not-equal\", \"greater-equal\", \"always\"] as const;\n const operations = [\"keep\", \"zero\", \"replace\", \"invert\", \"increment-clamp\", \"decrement-clamp\", \"increment-wrap\", \"decrement-wrap\"] as const;\n const factors = [\"zero\", \"one\", \"src\", \"one-minus-src\", \"src-alpha\", \"one-minus-src-alpha\", \"dst\", \"one-minus-dst\", \"dst-alpha\", \"one-minus-dst-alpha\", \"src-alpha-saturated\", \"constant\", \"one-minus-constant\"] as const;\n const parseBlend = (value: unknown, label: string): void => { const component = object(value, label); exact(component, [\"operation\", \"srcFactor\", \"dstFactor\"], label); enumeration(component.operation, [\"add\", \"subtract\", \"reverse-subtract\", \"min\", \"max\"] as const, `${label}.operation`); enumeration(component.srcFactor, factors, `${label}.srcFactor`); enumeration(component.dstFactor, factors, `${label}.dstFactor`); };\n const colorTargets = array(input.colorTargets, `${path}.colorTargets`, 8); if (input.fragment === null && colorTargets.length !== 0) throw new TypeError(`${path}.colorTargets must be empty when fragment is null.`); colorTargets.forEach((value, index) => { const label = `${path}.colorTargets[${index}]`; const target = object(value, label); exact(target, [\"format\", \"blend\", \"writeMask\"], label); token(target.format, `${label}.format`); integer(target.writeMask, `${label}.writeMask`, 0, 15); if (target.blend !== null) { const blend = object(target.blend, `${label}.blend`); exact(blend, [\"color\", \"alpha\"], `${label}.blend`); parseBlend(blend.color, `${label}.blend.color`); parseBlend(blend.alpha, `${label}.blend.alpha`); } });\n const parseStencil = (value: unknown, label: string): void => { const stencil = object(value, label); exact(stencil, [\"compare\", \"failOp\", \"depthFailOp\", \"passOp\"], label); enumeration(stencil.compare, compare, `${label}.compare`); enumeration(stencil.failOp, operations, `${label}.failOp`); enumeration(stencil.depthFailOp, operations, `${label}.depthFailOp`); enumeration(stencil.passOp, operations, `${label}.passOp`); };\n if (input.depthStencil !== null) { const depth = object(input.depthStencil, `${path}.depthStencil`); exact(depth, [\"format\", \"depthWriteEnabled\", \"depthCompare\", \"stencilFront\", \"stencilBack\", \"stencilReadMask\", \"stencilWriteMask\", \"depthBias\", \"depthBiasSlopeScale\", \"depthBiasClamp\"], `${path}.depthStencil`); token(depth.format, `${path}.depthStencil.format`); if (typeof depth.depthWriteEnabled !== \"boolean\") throw new TypeError(`${path}.depthStencil.depthWriteEnabled must be boolean.`); enumeration(depth.depthCompare, compare, `${path}.depthStencil.depthCompare`); parseStencil(depth.stencilFront, `${path}.depthStencil.stencilFront`); parseStencil(depth.stencilBack, `${path}.depthStencil.stencilBack`); integer(depth.stencilReadMask, `${path}.depthStencil.stencilReadMask`); integer(depth.stencilWriteMask, `${path}.depthStencil.stencilWriteMask`); integer(depth.depthBias, `${path}.depthStencil.depthBias`, -0x8000_0000, 0x7fff_ffff); finite(depth.depthBiasSlopeScale, `${path}.depthStencil.depthBiasSlopeScale`); finite(depth.depthBiasClamp, `${path}.depthStencil.depthBiasClamp`); }\n const multisample = object(input.multisample, `${path}.multisample`); exact(multisample, [\"count\", \"mask\", \"alphaToCoverageEnabled\"], `${path}.multisample`); enumeration(multisample.count, [1, 4] as const, `${path}.multisample.count`); integer(multisample.mask, `${path}.multisample.mask`); if (typeof multisample.alphaToCoverageEnabled !== \"boolean\") throw new TypeError(`${path}.multisample.alphaToCoverageEnabled must be boolean.`); if (multisample.alphaToCoverageEnabled && multisample.count === 1) throw new TypeError(`${path}.multisample.alphaToCoverageEnabled requires multisampling.`);\n }\n return input as unknown as SerializableGpuPipelineDescriptor;\n}\n\nexport function parseSerializableGpuPipelineDescriptors(\n value: unknown,\n moduleIds: readonly string[],\n path = \"pipelines\",\n): readonly SerializableGpuPipelineDescriptor[] {\n const parsed = array(detachedJson(value, path), path).map((item, index) => pipeline(item, `${path}[${index}]`, new Set(moduleIds)));\n unique(parsed, (item) => item.pipelineId, path);\n return freeze(parsed);\n}\n\nfunction compatibleModel(value: unknown, path: string): UnknownRecord {\n const input = object(value, path); exact(input, [\"interfaceId\", \"interfaceVersion\", \"manifestSha256\", \"interfaceAbiHash\", \"modelAbiHash\"], path);\n token(input.interfaceId, `${path}.interfaceId`); immutableVersion(input.interfaceVersion, `${path}.interfaceVersion`); digest(input.manifestSha256, `${path}.manifestSha256`); digest(input.interfaceAbiHash, `${path}.interfaceAbiHash`); digest(input.modelAbiHash, `${path}.modelAbiHash`); return input;\n}\n\nfunction validationEvidenceRef(value: unknown, path: string): UnknownRecord {\n const evidence = object(value, path);\n exact(evidence, [\"evidenceId\", \"uri\", \"sha256\", \"matrixId\", \"matrixVersion\", \"matrixSha256\", \"attestationRef\"], path);\n token(evidence.evidenceId, `${path}.evidenceId`);\n uri(evidence.uri, `${path}.uri`);\n digest(evidence.sha256, `${path}.sha256`);\n token(evidence.matrixId, `${path}.matrixId`);\n immutableVersion(evidence.matrixVersion, `${path}.matrixVersion`);\n digest(evidence.matrixSha256, `${path}.matrixSha256`);\n const attestation = object(evidence.attestationRef, `${path}.attestationRef`);\n exact(attestation, [\"uri\", \"sha256\"], `${path}.attestationRef`);\n uri(attestation.uri, `${path}.attestationRef.uri`);\n digest(attestation.sha256, `${path}.attestationRef.sha256`);\n if (evidence.uri === attestation.uri || evidence.sha256 === attestation.sha256) {\n throw new TypeError(`${path} evidence and attestation artifacts must have distinct URIs and digests.`);\n }\n return evidence;\n}\n\nfunction freeze<T>(value: T): T {\n if (typeof value !== \"object\" || value === null || Object.isFrozen(value)) return value;\n for (const child of Object.values(value as Record<string, unknown>)) freeze(child);\n return Object.freeze(value);\n}\n\nfunction reflectedRecordBindingSize(record: GpuRecordLayout): number {\n if (record.byteSize !== null) return record.byteSize;\n if (record.runtimeArrayMember === null) throw new TypeError(`Record ${record.name} has inconsistent runtime-array metadata.`);\n const member = record.members.find((candidate) => candidate.name === record.runtimeArrayMember);\n if (!member || member.type.kind !== \"array\" || member.type.count !== null) {\n throw new TypeError(`Record ${record.name} has invalid trailing runtime-array metadata.`);\n }\n const unrounded = member.offset + member.type.stride;\n return Math.ceil(unrounded / record.alignment) * record.alignment;\n}\n\n/** Strictly parses untrusted reflected interface JSON and validates all nested references. */\nexport function parseGpuInterfaceManifest(value: unknown): GpuInterfaceManifest {\n const input = object(detachedJson(value, \"GpuInterfaceManifest\"), \"GpuInterfaceManifest\");\n exact(input, [\"contractVersion\", \"interfaceId\", \"interfaceVersion\", \"modules\", \"records\", \"bindings\", \"entryPoints\", \"vertexInputs\", \"overrides\", \"modelAbi\", \"modelAbiHash\", \"interfaceAbiHash\", \"generatedBy\"], \"GpuInterfaceManifest\");\n if (input.contractVersion !== GPU_INTERFACE_MANIFEST_VERSION) throw new TypeError(\"Unsupported GPU interface contract version.\");\n token(input.interfaceId, \"GpuInterfaceManifest.interfaceId\"); immutableVersion(input.interfaceVersion, \"GpuInterfaceManifest.interfaceVersion\");\n const moduleValues = array(input.modules, \"GpuInterfaceManifest.modules\");\n if (moduleValues.length === 0) throw new TypeError(\"GpuInterfaceManifest.modules must not be empty.\");\n const moduleIds = moduleValues.map((value, index) => { const path = `GpuInterfaceManifest.modules[${index}]`; const module = object(value, path); exact(module, [\"moduleId\", \"sha256\"], path); digest(module.sha256, `${path}.sha256`); return token(module.moduleId, `${path}.moduleId`); });\n unique(moduleIds, String, \"GpuInterfaceManifest.modules\"); const moduleSet = new Set(moduleIds);\n const recordValues = array(input.records, \"GpuInterfaceManifest.records\"); const parsedRecords = recordValues.map((item, index) => recordLayout(item, `GpuInterfaceManifest.records[${index}]`));\n unique(parsedRecords, (item) => item.name, \"GpuInterfaceManifest.records\"); const records = new Map(parsedRecords.map((item) => [item.name, item]));\n for (const record of parsedRecords) for (const member of record.members) {\n const visit = (type: GpuTypeLayout): void => { if (type.kind === \"record\") { const referenced = records.get(type.recordName); if (!referenced) throw new TypeError(`Record ${record.name} references missing ${type.recordName}.`); if (type.alignment !== referenced.alignment || type.byteSize !== referenced.byteSize) throw new TypeError(`Record reference ${record.name}.${member.name} has stale layout metadata.`); } if (type.kind === \"array\") visit(type.element); };\n visit(member.type);\n }\n const bindingValues = array(input.bindings, \"GpuInterfaceManifest.bindings\"); const bindingKeys: string[] = [];\n bindingValues.forEach((item, index) => { const path = `GpuInterfaceManifest.bindings[${index}]`; const parsed = binding(item, path); const moduleId = String(parsed.moduleId); if (!moduleSet.has(moduleId)) throw new TypeError(`${path}.moduleId is missing.`); bindingKeys.push(`${moduleId}:${parsed.group}:${parsed.binding}`); const resource = parsed.resource as GpuBindingResourceLayout; if (resource.kind === \"buffer\" && resource.recordName) { const record = records.get(resource.recordName); if (!record) throw new TypeError(`${path} references missing record.`); if (resource.minimumBindingSize !== reflectedRecordBindingSize(record)) throw new TypeError(`${path}.resource.minimumBindingSize differs from its reflected record.`); if (record.runtimeArrayMember !== null && resource.addressSpace !== \"storage\") throw new TypeError(`${path} exposes a runtime-sized array outside storage.`); } });\n unique(bindingKeys, String, \"GpuInterfaceManifest.bindings\"); const bindingSet = new Set(bindingKeys);\n const overrideValues = array(input.overrides, \"GpuInterfaceManifest.overrides\"); const overrideKeys: string[] = []; const overrideIds: string[] = [];\n overrideValues.forEach((item, index) => { const path = `GpuInterfaceManifest.overrides[${index}]`; const override = object(item, path); exact(override, [\"moduleId\", \"name\", \"id\", \"type\", \"defaultValue\"], path); const moduleId = token(override.moduleId, `${path}.moduleId`); if (!moduleSet.has(moduleId)) throw new TypeError(`${path}.moduleId is missing.`); const name = token(override.name, `${path}.name`); overrideKeys.push(`${moduleId}:${name}`); if (override.id !== null) overrideIds.push(`${moduleId}:${integer(override.id, `${path}.id`)}`); enumeration(override.type, [\"bool\", \"i32\", \"u32\", \"f32\", \"f16\"] as const, `${path}.type`); if (override.defaultValue !== null && typeof override.defaultValue !== \"boolean\") finite(override.defaultValue, `${path}.defaultValue`); });\n unique(overrideKeys, String, \"GpuInterfaceManifest.overrides\"); unique(overrideIds, String, \"GpuInterfaceManifest.overrides ids\"); const overrideSet = new Set(overrideKeys);\n const entryValues = array(input.entryPoints, \"GpuInterfaceManifest.entryPoints\"); const entryKeys: string[] = [];\n if (entryValues.length === 0) throw new TypeError(\"GpuInterfaceManifest.entryPoints must not be empty.\");\n entryValues.forEach((item, index) => { const path = `GpuInterfaceManifest.entryPoints[${index}]`; const entry = object(item, path); exact(entry, [\"moduleId\", \"name\", \"stage\", \"inputs\", \"outputs\", \"bindingKeys\", \"overrideNames\", \"workgroupSize\", \"workgroupStorageSize\"], path); const moduleId = token(entry.moduleId, `${path}.moduleId`); if (!moduleSet.has(moduleId)) throw new TypeError(`${path}.moduleId is missing.`); const stage = enumeration(entry.stage, stages, `${path}.stage`); entryKeys.push(`${moduleId}:${stage}:${token(entry.name, `${path}.name`)}`); for (const ioKey of [\"inputs\", \"outputs\"] as const) { const ios = array(entry[ioKey], `${path}.${ioKey}`).map((value, ioIndex) => entryIo(value, `${path}.${ioKey}[${ioIndex}]`)); unique(ios, (io) => `${io.locationKind}:${io.location}`, `${path}.${ioKey}`); } const resources = tokenArray(entry.bindingKeys, `${path}.bindingKeys`); resources.forEach((key) => { if (!bindingSet.has(key)) throw new TypeError(`${path}.bindingKeys references missing ${key}.`); }); const names = tokenArray(entry.overrideNames, `${path}.overrideNames`); names.forEach((name) => { if (!overrideSet.has(`${moduleId}:${name}`)) throw new TypeError(`${path}.overrideNames references missing ${name}.`); }); if (stage === \"compute\") { const dimensions = array(entry.workgroupSize, `${path}.workgroupSize`, 3); if (dimensions.length !== 3) throw new TypeError(`${path}.workgroupSize must have three dimensions.`); dimensions.forEach((value, dimensionIndex) => { const dimensionPath = `${path}.workgroupSize[${dimensionIndex}]`; const dimension = object(value, dimensionPath); const kind = enumeration(dimension.kind, [\"literal\", \"override\"] as const, `${dimensionPath}.kind`); if (kind === \"literal\") { exact(dimension, [\"kind\", \"value\"], dimensionPath); integer(dimension.value, `${dimensionPath}.value`, 1); } else { exact(dimension, [\"kind\", \"name\"], dimensionPath); const name = token(dimension.name, `${dimensionPath}.name`); if (!overrideSet.has(`${moduleId}:${name}`)) throw new TypeError(`${dimensionPath} references missing override.`); } }); integer(entry.workgroupStorageSize, `${path}.workgroupStorageSize`); } else if (entry.workgroupSize !== null || entry.workgroupStorageSize !== null) throw new TypeError(`${path} workgroup metadata is only valid for compute.`); });\n unique(entryKeys, String, \"GpuInterfaceManifest.entryPoints\"); const entrySet = new Set(entryKeys);\n const vertexValues = array(input.vertexInputs, \"GpuInterfaceManifest.vertexInputs\"); const vertexKeys: string[] = []; const parsedVertices: UnknownRecord[] = [];\n vertexValues.forEach((item, index) => { const path = `GpuInterfaceManifest.vertexInputs[${index}]`; const vertex = vertexInput(item, path); parsedVertices.push(vertex); if (!entrySet.has(`${vertex.moduleId}:vertex:${vertex.entryPoint}`)) throw new TypeError(`${path} references missing vertex entry point.`); vertexKeys.push(`${vertex.pipelineId}:${vertex.shaderLocation}`); }); unique(vertexKeys, String, \"GpuInterfaceManifest.vertexInputs\");\n const model = object(input.modelAbi, \"GpuInterfaceManifest.modelAbi\"); exact(model, [\"recordNames\", \"bindings\", \"vertexInputs\", \"semantics\"], \"GpuInterfaceManifest.modelAbi\");\n tokenArray(model.recordNames, \"GpuInterfaceManifest.modelAbi.recordNames\").forEach((name) => { if (!records.has(name)) throw new TypeError(`Model ABI references missing record ${name}.`); });\n const modelBindings = array(model.bindings, \"GpuInterfaceManifest.modelAbi.bindings\").map((item, index) => binding(item, `GpuInterfaceManifest.modelAbi.bindings[${index}]`, false));\n for (const [index, projected] of modelBindings.entries()) { const source = projected.source as UnknownRecord; const reflectedIndex = bindingKeys.indexOf(`${source.moduleId}:${source.group}:${source.binding}`); const reflected = reflectedIndex < 0 ? null : object(bindingValues[reflectedIndex], `GpuInterfaceManifest.bindings[${reflectedIndex}]`); if (!reflected || canonicalizeForValidation(reflected.resource) !== canonicalizeForValidation(projected.resource)) throw new TypeError(`GpuInterfaceManifest.modelAbi.bindings[${index}] differs from its reflected source.`); const resource = projected.resource as GpuBindingResourceLayout; if (resource.kind === \"buffer\" && resource.recordName === null) throw new TypeError(`GpuInterfaceManifest.modelAbi.bindings[${index}] must use a named WGSL record root.`); }\n const modelBindingSemantics = modelBindings.filter((item) => item.semantic !== null).map((item) => String(item.semantic)); unique(modelBindingSemantics, String, \"GpuInterfaceManifest.modelAbi.bindings semantics\");\n const modelVertices = array(model.vertexInputs, \"GpuInterfaceManifest.modelAbi.vertexInputs\"); const parsedModelVertices = modelVertices.map((item, index) => vertexInput(item, `GpuInterfaceManifest.modelAbi.vertexInputs[${index}]`, true)); const modelVertexSemantics = parsedModelVertices.map((item) => String(item.semantic)); unique(modelVertexSemantics, String, \"GpuInterfaceManifest.modelAbi.vertexInputs\");\n for (const [index, projected] of parsedModelVertices.entries()) { const source = projected.source as UnknownRecord; const reflected = parsedVertices.find((candidate) => candidate.pipelineId === source.pipelineId && candidate.shaderLocation === source.shaderLocation); if (!reflected || [\"format\", \"offset\", \"arrayStride\", \"stepMode\", \"semantic\"].some((key) => reflected[key] !== projected[key])) throw new TypeError(`GpuInterfaceManifest.modelAbi.vertexInputs[${index}] differs from its reflected source.`); }\n const semantics = array(model.semantics, \"GpuInterfaceManifest.modelAbi.semantics\").map((item, index) => semantic(item, `GpuInterfaceManifest.modelAbi.semantics[${index}]`)); unique(semantics, (item) => String(item.semantic), \"GpuInterfaceManifest.modelAbi.semantics\");\n for (const projection of semantics) {\n const source = projection.source as UnknownRecord; const semanticName = String(projection.semantic);\n if (source.kind === \"record-member\") {\n let current = records.get(String(source.recordName)); if (!current) throw new TypeError(`Semantic ${semanticName} references missing record.`);\n for (const [index, memberName] of (source.memberPath as string[]).entries()) { const member = current.members.find((candidate) => candidate.name === memberName); if (!member) throw new TypeError(`Semantic ${semanticName} references missing member ${memberName}.`); if (index < (source.memberPath as string[]).length - 1) { if (member.type.kind !== \"record\") throw new TypeError(`Semantic ${semanticName} traverses a non-record member.`); current = records.get(member.type.recordName); if (!current) throw new TypeError(`Semantic ${semanticName} references missing nested record.`); } }\n } else if (source.kind === \"vertex-attribute\") {\n const vertex = parsedVertices.find((candidate) => candidate.pipelineId === source.pipelineId && candidate.shaderLocation === source.shaderLocation);\n const modelVertex = parsedModelVertices.find((candidate) => candidate.semantic === semanticName);\n const modelVertexSource = modelVertex?.source as UnknownRecord | undefined;\n if (!vertex || vertex.semantic !== semanticName || modelVertexSemantics.filter((item) => item === semanticName).length !== 1\n || !modelVertexSource || modelVertexSource.pipelineId !== source.pipelineId || modelVertexSource.shaderLocation !== source.shaderLocation) throw new TypeError(`Semantic ${semanticName} does not resolve to exactly one matching model vertex stream.`);\n } else {\n const key = `${source.moduleId}:${source.group}:${source.binding}`; if (!bindingSet.has(key)) throw new TypeError(`Semantic ${semanticName} references missing binding ${key}.`);\n const modelBinding = modelBindings.find((candidate) => candidate.semantic === semanticName);\n if (modelBindingSemantics.filter((item) => item === semanticName).length !== 1 || !modelBinding\n || canonicalizeForValidation(modelBinding.source) !== canonicalizeForValidation({ moduleId: source.moduleId, group: source.group, binding: source.binding })) throw new TypeError(`Semantic ${semanticName} does not resolve to exactly one matching model binding.`);\n }\n }\n for (const semanticName of [...modelVertexSemantics, ...modelBindingSemantics]) if (semantics.filter((item) => item.semantic === semanticName).length !== 1) throw new TypeError(`Model semantic ${semanticName} requires exactly one projection.`);\n digest(input.modelAbiHash, \"GpuInterfaceManifest.modelAbiHash\"); digest(input.interfaceAbiHash, \"GpuInterfaceManifest.interfaceAbiHash\");\n const generated = object(input.generatedBy, \"GpuInterfaceManifest.generatedBy\"); exact(generated, [\"packageVersion\", \"reflector\", \"reflectorVersion\"], \"GpuInterfaceManifest.generatedBy\"); token(generated.packageVersion, \"GpuInterfaceManifest.generatedBy.packageVersion\"); if (generated.reflector !== \"wgsl_reflect\" || generated.reflectorVersion !== \"1.5.0\") throw new TypeError(\"Unsupported reflector provenance.\");\n return freeze(input as unknown as GpuInterfaceManifest);\n}\n\n/** Strictly parses an immutable shader-version manifest. */\nexport function parseShaderVersionManifest(value: unknown): ShaderVersionManifest {\n const input = object(detachedJson(value, \"ShaderVersionManifest\"), \"ShaderVersionManifest\"); exact(input, [\"contractVersion\", \"shaderId\", \"version\", \"modules\", \"gpuInterface\", \"pipelines\", \"renderRoles\", \"compatibleModelInterfaces\", \"requirements\", \"shaderAbiHash\", \"validationEvidence\", \"additionalValidationEvidence\"], \"ShaderVersionManifest\");\n if (input.contractVersion !== SHADER_VERSION_MANIFEST_VERSION) throw new TypeError(\"Unsupported shader manifest contract version.\");\n token(input.shaderId, \"ShaderVersionManifest.shaderId\"); immutableVersion(input.version, \"ShaderVersionManifest.version\");\n const moduleValues = array(input.modules, \"ShaderVersionManifest.modules\"); if (moduleValues.length === 0) throw new TypeError(\"ShaderVersionManifest.modules must not be empty.\"); const moduleIds = moduleValues.map((item, index) => { const path = `ShaderVersionManifest.modules[${index}]`; const module = object(item, path); exact(module, [\"moduleId\", \"uri\", \"byteLength\", \"sha256\", \"contentType\"], path); uri(module.uri, `${path}.uri`); integer(module.byteLength, `${path}.byteLength`, 1); digest(module.sha256, `${path}.sha256`); if (module.contentType !== \"text/wgsl; charset=utf-8\") throw new TypeError(`${path}.contentType is not canonical WGSL.`); return token(module.moduleId, `${path}.moduleId`); }); unique(moduleIds, String, \"ShaderVersionManifest.modules\"); const moduleSet = new Set(moduleIds);\n const shaderInterface = interfaceRef(input.gpuInterface, \"ShaderVersionManifest.gpuInterface\");\n const pipelines = array(input.pipelines, \"ShaderVersionManifest.pipelines\").map((item, index) => pipeline(item, `ShaderVersionManifest.pipelines[${index}]`, moduleSet)); if (pipelines.length === 0) throw new TypeError(\"ShaderVersionManifest.pipelines must not be empty.\"); unique(pipelines, (item) => item.pipelineId, \"ShaderVersionManifest.pipelines\"); const pipelineIds = new Set(pipelines.map((item) => item.pipelineId));\n const roleValues = array(input.renderRoles, \"ShaderVersionManifest.renderRoles\", 5); if (roleValues.length === 0) throw new TypeError(\"ShaderVersionManifest.renderRoles must not be empty.\"); const roleNames: string[] = []; const assigned = new Set<string>(); roleValues.forEach((item, index) => { const path = `ShaderVersionManifest.renderRoles[${index}]`; const role = object(item, path); exact(role, [\"role\", \"pipelineIds\"], path); roleNames.push(enumeration(role.role, roles, `${path}.role`)); const ids = tokenArray(role.pipelineIds, `${path}.pipelineIds`); if (ids.length === 0) throw new TypeError(`${path}.pipelineIds must not be empty.`); ids.forEach((id) => { if (!pipelineIds.has(id)) throw new TypeError(`${path} references missing pipeline ${id}.`); assigned.add(id); }); }); unique(roleNames, String, \"ShaderVersionManifest.renderRoles\"); if (assigned.size !== pipelineIds.size) throw new TypeError(\"Every pipeline must belong to at least one render role.\");\n const compatible = array(input.compatibleModelInterfaces, \"ShaderVersionManifest.compatibleModelInterfaces\").map((item, index) => compatibleModel(item, `ShaderVersionManifest.compatibleModelInterfaces[${index}]`)); if (compatible.length === 0) throw new TypeError(\"ShaderVersionManifest.compatibleModelInterfaces must not be empty.\"); unique(compatible, (item) => `${item.interfaceId}:${item.interfaceVersion}:${item.manifestSha256}:${item.interfaceAbiHash}:${item.modelAbiHash}`, \"ShaderVersionManifest.compatibleModelInterfaces\"); if (compatible.some((item) => item.modelAbiHash !== shaderInterface.modelAbiHash)) throw new TypeError(\"ShaderVersionManifest compatible model ABI hashes must equal gpuInterface.modelAbiHash.\");\n const requirements = object(input.requirements, \"ShaderVersionManifest.requirements\"); exact(requirements, [\"semantics\", \"features\", \"limits\", \"formats\"], \"ShaderVersionManifest.requirements\"); tokenArray(requirements.semantics, \"ShaderVersionManifest.requirements.semantics\"); tokenArray(requirements.features, \"ShaderVersionManifest.requirements.features\"); tokenArray(requirements.formats, \"ShaderVersionManifest.requirements.formats\"); const limits = array(requirements.limits, \"ShaderVersionManifest.requirements.limits\"); const limitNames: string[] = []; limits.forEach((item, index) => { const path = `ShaderVersionManifest.requirements.limits[${index}]`; const limit = object(item, path); exact(limit, [\"name\", \"comparator\", \"value\"], path); const name = token(limit.name, `${path}.name`); limitNames.push(name); enumeration(limit.comparator, [\"at-least\", \"at-most\"] as const, `${path}.comparator`); const value = finite(limit.value, `${path}.value`); if (!Number.isSafeInteger(value) || value < 0) throw new TypeError(`${path}.value must be a non-negative safe integer.`); }); unique(limitNames, String, \"ShaderVersionManifest.requirements.limits\");\n validatePipelineDerivedRequirements({\n requirements: input.requirements as unknown as ShaderVersionManifest[\"requirements\"],\n pipelines,\n });\n digest(input.shaderAbiHash, \"ShaderVersionManifest.shaderAbiHash\");\n const universalEvidence = validationEvidenceRef(input.validationEvidence, \"ShaderVersionManifest.validationEvidence\");\n if (!SUPPORTED_STABLE_WEBGPU_MATRIX_POLICIES.some((policy) =>\n universalEvidence.matrixId === policy.matrixId\n && universalEvidence.matrixVersion === policy.matrixVersion\n && universalEvidence.matrixSha256 === policy.matrixSha256)) {\n throw new TypeError(\"ShaderVersionManifest.validationEvidence is not bound to a supported universal stable-WebGPU matrix policy.\");\n }\n const additionalEvidence = array(input.additionalValidationEvidence, \"ShaderVersionManifest.additionalValidationEvidence\");\n const scopedEvidence = additionalEvidence.map((item, index) => {\n const path = `ShaderVersionManifest.additionalValidationEvidence[${index}]`;\n const scoped = object(item, path);\n exact(scoped, [\"scope\", \"evidence\"], path);\n const scope = token(scoped.scope, `${path}.scope`);\n if (scope === \"universal\") throw new TypeError(`${path}.scope universal is reserved for validationEvidence.`);\n const evidence = validationEvidenceRef(scoped.evidence, `${path}.evidence`);\n if (evidence.matrixSha256 === universalEvidence.matrixSha256) {\n throw new TypeError(`${path}.evidence must use an additive matrix policy, not the universal matrix policy.`);\n }\n return { scope, evidence };\n });\n unique(scopedEvidence, (item) => item.scope, \"ShaderVersionManifest.additionalValidationEvidence scopes\");\n unique(scopedEvidence, (item) => String(item.evidence.matrixSha256), \"ShaderVersionManifest.additionalValidationEvidence matrix policies\");\n const evidenceIds = new Set([String(universalEvidence.evidenceId)]);\n const artifactUris = new Set([\n String(universalEvidence.uri),\n String((universalEvidence.attestationRef as UnknownRecord).uri),\n ]);\n const artifactDigests = new Set([\n String(universalEvidence.sha256),\n String((universalEvidence.attestationRef as UnknownRecord).sha256),\n ]);\n for (const [index, item] of scopedEvidence.entries()) {\n const path = `ShaderVersionManifest.additionalValidationEvidence[${index}].evidence`;\n if (evidenceIds.has(String(item.evidence.evidenceId))) throw new TypeError(`${path} reuses a universal or supplemental evidence ID.`);\n evidenceIds.add(String(item.evidence.evidenceId));\n const attestation = item.evidence.attestationRef as UnknownRecord;\n for (const candidate of [item.evidence.uri, attestation.uri]) {\n if (artifactUris.has(String(candidate))) throw new TypeError(`${path} reuses a universal or supplemental evidence/attestation URI.`);\n artifactUris.add(String(candidate));\n }\n for (const candidate of [item.evidence.sha256, attestation.sha256]) {\n if (artifactDigests.has(String(candidate))) throw new TypeError(`${path} reuses a universal or supplemental evidence/attestation digest.`);\n artifactDigests.add(String(candidate));\n }\n }\n for (const [index, item] of scopedEvidence.entries()) if (!SUPPORTED_ADDITIVE_WEBGPU_MATRIX_POLICIES.some((policy) =>\n item.scope === policy.scope\n && item.evidence.matrixId === policy.matrixId\n && item.evidence.matrixVersion === policy.matrixVersion\n && item.evidence.matrixSha256 === policy.matrixSha256)) {\n throw new TypeError(`ShaderVersionManifest.additionalValidationEvidence[${index}].evidence is not bound to a supported additive WebGPU matrix policy.`);\n }\n return freeze(input as unknown as ShaderVersionManifest);\n}\n\n/** Strictly parses the cycle-free shader manifest qualified before evidence attachment. */\nexport function parseShaderVersionManifestCore(value: unknown): ShaderVersionManifestCore {\n const input = object(detachedJson(value, \"ShaderVersionManifestCore\"), \"ShaderVersionManifestCore\");\n if (\"validationEvidence\" in input || \"additionalValidationEvidence\" in input) {\n throw new TypeError(\"ShaderVersionManifestCore must not contain validationEvidence or additionalValidationEvidence.\");\n }\n const parsed = parseShaderVersionManifest({\n ...input,\n validationEvidence: {\n evidenceId: \"pending\",\n uri: \"https://catalog.invalid/evidence/pending.json\",\n sha256: \"0\".repeat(64),\n matrixId: SUPPORTED_STABLE_WEBGPU_MATRIX_POLICIES[0].matrixId,\n matrixVersion: SUPPORTED_STABLE_WEBGPU_MATRIX_POLICIES[0].matrixVersion,\n matrixSha256: SUPPORTED_STABLE_WEBGPU_MATRIX_POLICIES[0].matrixSha256,\n attestationRef: {\n uri: \"https://catalog.invalid/evidence/pending.attestation-ref.json\",\n sha256: \"1\".repeat(64),\n },\n },\n additionalValidationEvidence: [],\n });\n const { validationEvidence, additionalValidationEvidence, ...core } = parsed;\n void validationEvidence;\n void additionalValidationEvidence;\n return freeze(core);\n}\n\n/** Strictly parses a rendering-style profile with exact immutable shader references. */\nexport function parseShaderStyleProfileManifest(value: unknown): ShaderStyleProfileManifest {\n const input = object(detachedJson(value, \"ShaderStyleProfileManifest\"), \"ShaderStyleProfileManifest\"); exact(input, [\"contractVersion\", \"profileId\", \"version\", \"style\", \"roles\", \"compatibleModelInterfaces\", \"requiredSemantics\", \"requiredValidationScopes\"], \"ShaderStyleProfileManifest\");\n if (input.contractVersion !== SHADER_STYLE_PROFILE_MANIFEST_VERSION) throw new TypeError(\"Unsupported style-profile contract version.\");\n token(input.profileId, \"ShaderStyleProfileManifest.profileId\"); immutableVersion(input.version, \"ShaderStyleProfileManifest.version\"); token(input.style, \"ShaderStyleProfileManifest.style\");\n const roleValues = array(input.roles, \"ShaderStyleProfileManifest.roles\", 5); if (roleValues.length === 0) throw new TypeError(\"ShaderStyleProfileManifest.roles must not be empty.\"); const roleNames: string[] = []; roleValues.forEach((item, index) => { const path = `ShaderStyleProfileManifest.roles[${index}]`; const role = object(item, path); exact(role, [\"role\", \"shader\"], path); roleNames.push(enumeration(role.role, roles, `${path}.role`)); const shader = object(role.shader, `${path}.shader`); exact(shader, [\"shaderId\", \"version\", \"manifestUri\", \"manifestSha256\"], `${path}.shader`); token(shader.shaderId, `${path}.shader.shaderId`); immutableVersion(shader.version, `${path}.shader.version`); uri(shader.manifestUri, `${path}.shader.manifestUri`); digest(shader.manifestSha256, `${path}.shader.manifestSha256`); }); unique(roleNames, String, \"ShaderStyleProfileManifest.roles\");\n const compatible = array(input.compatibleModelInterfaces, \"ShaderStyleProfileManifest.compatibleModelInterfaces\").map((item, index) => compatibleModel(item, `ShaderStyleProfileManifest.compatibleModelInterfaces[${index}]`)); if (compatible.length === 0) throw new TypeError(\"ShaderStyleProfileManifest.compatibleModelInterfaces must not be empty.\"); unique(compatible, (item) => `${item.interfaceId}:${item.interfaceVersion}:${item.manifestSha256}:${item.interfaceAbiHash}:${item.modelAbiHash}`, \"ShaderStyleProfileManifest.compatibleModelInterfaces\"); tokenArray(input.requiredSemantics, \"ShaderStyleProfileManifest.requiredSemantics\");\n const requiredValidationScopes = array(input.requiredValidationScopes, \"ShaderStyleProfileManifest.requiredValidationScopes\").map((item, index) => {\n const path = `ShaderStyleProfileManifest.requiredValidationScopes[${index}]`;\n const requirement = object(item, path);\n exact(requirement, [\"scope\", \"matrixId\", \"matrixVersion\", \"matrixSha256\"], path);\n const scope = token(requirement.scope, `${path}.scope`);\n if (scope === \"universal\") throw new TypeError(`${path}.scope must not use the reserved universal scope.`);\n token(requirement.matrixId, `${path}.matrixId`);\n immutableVersion(requirement.matrixVersion, `${path}.matrixVersion`);\n const matrixSha256 = digest(requirement.matrixSha256, `${path}.matrixSha256`);\n if (SUPPORTED_STABLE_WEBGPU_MATRIX_POLICIES.some((policy) => policy.matrixSha256 === matrixSha256)) {\n throw new TypeError(`${path} must require an additive matrix policy, not the universal matrix policy.`);\n }\n if (!SUPPORTED_ADDITIVE_WEBGPU_MATRIX_POLICIES.some((policy) =>\n scope === policy.scope\n && requirement.matrixId === policy.matrixId\n && requirement.matrixVersion === policy.matrixVersion\n && matrixSha256 === policy.matrixSha256)) {\n throw new TypeError(`${path} is not a supported additive WebGPU matrix policy.`);\n }\n return requirement;\n });\n unique(requiredValidationScopes, (item) => String(item.scope), \"ShaderStyleProfileManifest.requiredValidationScopes scopes\");\n unique(requiredValidationScopes, (item) => String(item.matrixSha256), \"ShaderStyleProfileManifest.requiredValidationScopes matrix policies\");\n return freeze(input as unknown as ShaderStyleProfileManifest);\n}\n\n/** Strictly parses the model-facing GPU compatibility fields published with a model version. */\nexport function parseModelGpuCompatibilityDescriptor(value: unknown): ModelGpuCompatibilityDescriptor {\n const input = object(detachedJson(value, \"ModelGpuCompatibilityDescriptor\"), \"ModelGpuCompatibilityDescriptor\");\n exact(input, [\"modelId\", \"version\", \"gpuInterface\", \"modelAbiHash\", \"providedSemantics\", \"defaultStyleProfile\"], \"ModelGpuCompatibilityDescriptor\");\n token(input.modelId, \"ModelGpuCompatibilityDescriptor.modelId\");\n immutableVersion(input.version, \"ModelGpuCompatibilityDescriptor.version\");\n const gpuInterface = interfaceRef(input.gpuInterface, \"ModelGpuCompatibilityDescriptor.gpuInterface\");\n const modelAbiHash = digest(input.modelAbiHash, \"ModelGpuCompatibilityDescriptor.modelAbiHash\");\n if (gpuInterface.modelAbiHash !== modelAbiHash) throw new TypeError(\"ModelGpuCompatibilityDescriptor.gpuInterface.modelAbiHash differs from modelAbiHash.\");\n tokenArray(input.providedSemantics, \"ModelGpuCompatibilityDescriptor.providedSemantics\");\n if (input.defaultStyleProfile !== null) { const profile = object(input.defaultStyleProfile, \"ModelGpuCompatibilityDescriptor.defaultStyleProfile\"); exact(profile, [\"profileId\", \"version\", \"manifestUri\", \"manifestSha256\"], \"ModelGpuCompatibilityDescriptor.defaultStyleProfile\"); token(profile.profileId, \"ModelGpuCompatibilityDescriptor.defaultStyleProfile.profileId\"); immutableVersion(profile.version, \"ModelGpuCompatibilityDescriptor.defaultStyleProfile.version\"); uri(profile.manifestUri, \"ModelGpuCompatibilityDescriptor.defaultStyleProfile.manifestUri\"); digest(profile.manifestSha256, \"ModelGpuCompatibilityDescriptor.defaultStyleProfile.manifestSha256\"); }\n return freeze(input as unknown as ModelGpuCompatibilityDescriptor);\n}\n\n/** Strictly parses a qualification fixture that binds one immutable model descriptor. */\nexport function parseShaderQualificationModelCompatibilityFixture(value: unknown): ShaderQualificationModelCompatibilityFixture {\n const input = object(\n detachedJson(value, \"ShaderQualificationModelCompatibilityFixture\"),\n \"ShaderQualificationModelCompatibilityFixture\",\n );\n exact(input, [\"contractVersion\", \"fixtureId\", \"model\"], \"ShaderQualificationModelCompatibilityFixture\");\n if (input.contractVersion !== SHADER_QUALIFICATION_FIXTURE_VERSION) throw new TypeError(\"Unsupported model compatibility fixture version.\");\n token(input.fixtureId, \"ShaderQualificationModelCompatibilityFixture.fixtureId\");\n parseModelGpuCompatibilityDescriptor(input.model);\n return freeze(input as unknown as ShaderQualificationModelCompatibilityFixture);\n}\n\nexport function parseJsonBytes(bytes: Uint8Array, label: string): unknown {\n try { return JSON.parse(new TextDecoder(\"utf-8\", { fatal: true }).decode(bytes)); }\n catch (cause) { throw new TypeError(`${label} is not valid UTF-8 JSON.`, { cause }); }\n}\n","import type {\n GpuCapabilitySnapshot,\n GpuInterfaceManifest,\n ModelGpuCompatibilityDescriptor,\n ModelShaderCompatibility,\n ShaderDiagnostic,\n ShaderResult,\n ShaderStyleProfileManifest,\n ShaderVersionManifestCore,\n} from \"./contracts.js\";\nimport { canonicalizeGpuContract } from \"./canonical-json.js\";\nimport {\n parseGpuInterfaceManifest,\n parseModelGpuCompatibilityDescriptor,\n parseShaderStyleProfileManifest,\n parseShaderVersionManifest,\n parseShaderVersionManifestCore,\n} from \"./manifest-validation.js\";\nimport { validateShaderInterfaceRequirements } from \"./requirements-validation.js\";\n\nfunction error(\n code: ShaderDiagnostic[\"code\"],\n message: string,\n path?: string,\n): ShaderDiagnostic {\n const bounded = [...message]\n .map((character) => {\n const codePoint = character.codePointAt(0) as number;\n return codePoint <= 0x1f || codePoint === 0x7f ? \" \" : character;\n })\n .slice(0, 512)\n .join(\"\");\n return { code, severity: \"error\", message: bounded, ...(path ? { path } : {}) };\n}\n\nfunction interfaceMatches(\n item: { readonly interfaceId: string; readonly interfaceVersion: string; readonly manifestSha256: string; readonly interfaceAbiHash: string; readonly modelAbiHash: string },\n model: ModelGpuCompatibilityDescriptor,\n): boolean {\n return item.interfaceId === model.gpuInterface.interfaceId\n && item.interfaceVersion === model.gpuInterface.interfaceVersion\n && item.manifestSha256 === model.gpuInterface.manifestSha256\n && item.interfaceAbiHash === model.gpuInterface.interfaceAbiHash\n && item.modelAbiHash === model.modelAbiHash;\n}\n\nfunction detachedContract(value: unknown): unknown {\n return JSON.parse(canonicalizeGpuContract(value)) as unknown;\n}\n\nfunction hasValidationEvidence(value: unknown): boolean {\n return typeof value === \"object\"\n && value !== null\n && !Array.isArray(value)\n && (Object.hasOwn(value, \"validationEvidence\") || Object.hasOwn(value, \"additionalValidationEvidence\"));\n}\n\nfunction validateRequirements(\n shader: ShaderVersionManifestCore,\n gpuInterface: GpuInterfaceManifest,\n model: ModelGpuCompatibilityDescriptor,\n capabilities: GpuCapabilitySnapshot | undefined,\n diagnostics: ShaderDiagnostic[],\n): void {\n const semantics = new Set(model.providedSemantics);\n const requiredSemantics = new Set([\n ...shader.requirements.semantics,\n ...gpuInterface.modelAbi.semantics.map((projection) => projection.semantic),\n ]);\n for (const semantic of requiredSemantics) {\n if (!semantics.has(semantic)) {\n diagnostics.push(error(\"missing-semantic\", `Model does not provide required semantic ${semantic}.`, \"requirements.semantics\"));\n }\n }\n if (!capabilities) return;\n const features = new Set(capabilities.features);\n for (const feature of shader.requirements.features) {\n if (!features.has(feature)) {\n diagnostics.push(error(\"missing-feature\", `GPU does not provide required feature ${feature}.`, \"requirements.features\"));\n }\n }\n const formats = new Set(capabilities.formats);\n for (const format of shader.requirements.formats) {\n if (!formats.has(format)) {\n diagnostics.push(error(\"unsupported-format\", `GPU runtime does not expose required format ${format}.`, \"requirements.formats\"));\n }\n }\n for (const requirement of shader.requirements.limits) {\n const available = capabilities.limits[requirement.name];\n const satisfied = available !== undefined && (\n requirement.comparator === \"at-least\"\n ? available >= requirement.value\n : available <= requirement.value\n );\n if (!satisfied) {\n diagnostics.push(error(\n \"limit-not-met\",\n `GPU limit ${requirement.name} does not meet the ${requirement.comparator} requirement.`,\n \"requirements.limits\",\n ));\n }\n }\n}\n\n/** Performs pure manifest/model/device compatibility checks without creating GPU resources. */\nexport function validateModelShaderCompatibility(input: {\n readonly model: ModelGpuCompatibilityDescriptor;\n readonly shader: ShaderVersionManifestCore;\n /** Exact reflected interface referenced by `shader`; required to prevent sidecar understatement. */\n readonly gpuInterface: GpuInterfaceManifest;\n readonly profile?: ShaderStyleProfileManifest;\n readonly capabilities?: GpuCapabilitySnapshot;\n}): ShaderResult<ModelShaderCompatibility> {\n const diagnostics: ShaderDiagnostic[] = [];\n let model: ModelGpuCompatibilityDescriptor;\n let shader: ShaderVersionManifestCore;\n let gpuInterface: GpuInterfaceManifest;\n let profile: ShaderStyleProfileManifest | undefined;\n let capabilities: GpuCapabilitySnapshot | undefined;\n try {\n const modelSnapshot = detachedContract(input.model);\n const shaderSnapshot = detachedContract(input.shader);\n const gpuInterfaceSnapshot = detachedContract(input.gpuInterface);\n const profileValue = input.profile;\n const profileSnapshot = profileValue === undefined ? undefined : detachedContract(profileValue);\n\n model = parseModelGpuCompatibilityDescriptor(modelSnapshot);\n shader = hasValidationEvidence(shaderSnapshot)\n ? parseShaderVersionManifest(shaderSnapshot)\n : parseShaderVersionManifestCore(shaderSnapshot);\n gpuInterface = parseGpuInterfaceManifest(gpuInterfaceSnapshot);\n profile = profileSnapshot === undefined\n ? undefined\n : parseShaderStyleProfileManifest(profileSnapshot);\n capabilities = input.capabilities;\n } catch (cause) {\n return {\n ok: false,\n diagnostics: [error(\n \"invalid-contract\",\n cause instanceof Error ? cause.message : \"GPU compatibility contract snapshot failed.\",\n )],\n };\n }\n try {\n validateShaderInterfaceRequirements({ manifest: shader, gpuInterface });\n } catch (cause) {\n diagnostics.push(error(\n \"invalid-contract\",\n cause instanceof Error ? cause.message : \"Shader requirements differ from the reflected GPU interface.\",\n \"requirements\",\n ));\n }\n if (model.gpuInterface.modelAbiHash !== model.modelAbiHash) {\n diagnostics.push(error(\"model-abi-mismatch\", \"Model manifest and GPU interface reference disagree on modelAbiHash.\", \"modelAbiHash\"));\n }\n if (shader.gpuInterface.modelAbiHash !== model.modelAbiHash) {\n diagnostics.push(error(\"model-abi-mismatch\", \"Shader GPU interface does not match the model ABI.\", \"gpuInterface.modelAbiHash\"));\n }\n if (!shader.compatibleModelInterfaces.some((item) => interfaceMatches(item, model))) {\n diagnostics.push(error(\"incompatible-model-interface\", \"Shader does not declare this exact model interface as compatible.\"));\n }\n if (profile) {\n if (!profile.compatibleModelInterfaces.some((item) => interfaceMatches(item, model))) {\n diagnostics.push(error(\"incompatible-model-interface\", \"Style profile does not declare this exact model interface as compatible.\"));\n }\n const provided = new Set(model.providedSemantics);\n for (const semantic of profile.requiredSemantics) {\n if (!provided.has(semantic)) {\n diagnostics.push(error(\"missing-semantic\", `Model does not provide profile semantic ${semantic}.`, \"requiredSemantics\"));\n }\n }\n }\n try {\n validateRequirements(shader, gpuInterface, model, capabilities, diagnostics);\n } catch (cause) {\n diagnostics.push(error(\n \"invalid-contract\",\n cause instanceof Error ? cause.message : \"GPU capability snapshot validation failed.\",\n \"capabilities\",\n ));\n }\n if (diagnostics.length > 0) return { ok: false, diagnostics };\n return {\n ok: true,\n value: {\n modelAbiHash: model.modelAbiHash,\n shaderAbiHash: shader.shaderAbiHash,\n matchedInterfaceId: model.gpuInterface.interfaceId,\n },\n };\n}\n","import type {\n GpuInterfaceManifest,\n LoadedShaderStyleProfile,\n LoadedShaderVersion,\n PreparedShaderStyleProfile,\n ShaderRenderRole,\n ShaderStyleProfileManifest,\n ShaderStyleProfileRef,\n ShaderVersionManifest,\n ShaderVersionRef,\n} from \"../contracts.js\";\n\n/** Internal immutable data retained independently from caller-visible runtime values. */\nexport interface TrustedLoadedShaderVersion {\n readonly publicValue: LoadedShaderVersion;\n readonly ref: ShaderVersionRef;\n readonly manifest: ShaderVersionManifest;\n readonly gpuInterface: GpuInterfaceManifest;\n readonly modules: ReadonlyMap<string, Uint8Array>;\n}\n\n/** Internal immutable profile state created only at the catalog-loading boundary. */\nexport interface TrustedLoadedShaderStyleProfile {\n readonly publicValue: LoadedShaderStyleProfile;\n readonly ref: ShaderStyleProfileRef;\n readonly manifest: ShaderStyleProfileManifest;\n readonly shaders: ReadonlyMap<ShaderRenderRole, TrustedLoadedShaderVersion>;\n}\n\nclass ReadonlyMapView<K, V> implements ReadonlyMap<K, V> {\n readonly #source: ReadonlyMap<K, V>;\n\n constructor(source: ReadonlyMap<K, V>) {\n this.#source = source;\n Object.freeze(this);\n }\n\n get size(): number { return this.#source.size; }\n get(key: K): V | undefined { return this.#source.get(key); }\n has(key: K): boolean { return this.#source.has(key); }\n entries(): MapIterator<[K, V]> { return this.#source.entries(); }\n keys(): MapIterator<K> { return this.#source.keys(); }\n values(): MapIterator<V> { return this.#source.values(); }\n [Symbol.iterator](): MapIterator<[K, V]> { return this.#source[Symbol.iterator](); }\n\n forEach(\n callbackfn: (value: V, key: K, map: ReadonlyMap<K, V>) => void,\n thisArg?: unknown,\n ): void {\n for (const [key, value] of this.#source) callbackfn.call(thisArg, value, key, this);\n }\n}\n\nconst loadedProfiles = new WeakMap<object, TrustedLoadedShaderStyleProfile>();\nconst preparedProfiles = new WeakSet<object>();\n\nfunction immutableSnapshot<T>(value: T): T {\n if (Array.isArray(value)) {\n return Object.freeze(value.map((item) => immutableSnapshot(item))) as T;\n }\n if (typeof value !== \"object\" || value === null) return value;\n const output: Record<string, unknown> = {};\n for (const [key, item] of Object.entries(value as Record<string, unknown>)) {\n output[key] = immutableSnapshot(item);\n }\n return Object.freeze(output) as T;\n}\n\n/** Creates a mutation-isolated public map facade over private runtime state. */\nexport function readonlyMapView<K, V>(source: ReadonlyMap<K, V>): ReadonlyMap<K, V> {\n return new ReadonlyMapView(source);\n}\n\n/**\n * Copies and brands a catalog-loaded profile. This module is intentionally not a\n * package export; public callers can obtain branded values only through loading.\n */\nexport function trustLoadedShaderStyleProfile(\n raw: LoadedShaderStyleProfile,\n): LoadedShaderStyleProfile {\n const shaderMemo = new Map<LoadedShaderVersion, TrustedLoadedShaderVersion>();\n const trustedShaders = new Map<ShaderRenderRole, TrustedLoadedShaderVersion>();\n const publicShaders = new Map<ShaderRenderRole, LoadedShaderVersion>();\n\n for (const [role, rawShader] of raw.shaders) {\n let trusted = shaderMemo.get(rawShader);\n if (!trusted) {\n const ref = immutableSnapshot(rawShader.ref);\n const manifest = immutableSnapshot(rawShader.manifest);\n const gpuInterface = immutableSnapshot(rawShader.gpuInterface);\n const privateModules = new Map<string, Uint8Array>();\n const publicModules = new Map<string, Uint8Array>();\n for (const [moduleId, bytes] of rawShader.modules) {\n const privateBytes = new Uint8Array(bytes);\n privateModules.set(moduleId, privateBytes);\n publicModules.set(moduleId, new Uint8Array(privateBytes));\n }\n const publicValue = Object.freeze({\n ref,\n manifest,\n gpuInterface,\n modules: readonlyMapView(publicModules),\n } satisfies LoadedShaderVersion);\n trusted = Object.freeze({\n publicValue,\n ref,\n manifest,\n gpuInterface,\n modules: readonlyMapView(privateModules),\n });\n shaderMemo.set(rawShader, trusted);\n }\n trustedShaders.set(role, trusted);\n publicShaders.set(role, trusted.publicValue);\n }\n\n const ref = immutableSnapshot(raw.ref);\n const manifest = immutableSnapshot(raw.manifest);\n const publicValue = Object.freeze({\n ref,\n manifest,\n shaders: readonlyMapView(publicShaders),\n } satisfies LoadedShaderStyleProfile);\n loadedProfiles.set(publicValue, Object.freeze({\n publicValue,\n ref,\n manifest,\n shaders: readonlyMapView(trustedShaders),\n }));\n return publicValue;\n}\n\n/** Rejects values that did not cross the promoted catalog loading boundary. */\nexport function requireTrustedLoadedShaderStyleProfile(\n value: LoadedShaderStyleProfile,\n): TrustedLoadedShaderStyleProfile {\n const trusted = loadedProfiles.get(value as object);\n if (!trusted) {\n throw new TypeError(\"loaded must be returned by loadShaderStyleProfile.\");\n }\n return trusted;\n}\n\n/** Brands and freezes a successfully prepared profile for controller admission. */\nexport function trustPreparedShaderStyleProfile<T extends PreparedShaderStyleProfile>(value: T): T {\n preparedProfiles.add(value as object);\n return Object.freeze(value);\n}\n\n/** Rejects structurally forged prepared profiles before frame-boundary activation. */\nexport function requireTrustedPreparedShaderStyleProfile(value: PreparedShaderStyleProfile): void {\n if (!preparedProfiles.has(value as object)) {\n throw new TypeError(\"prepared must be returned by prepareStyleProfile.\");\n }\n}\n","import type {\n GpuInterfaceRef,\n LoadedShaderStyleProfile,\n LoadedShaderVersion,\n PromotedShaderCatalogResolver,\n ShaderDiagnostic,\n ShaderRenderRole,\n ShaderResult,\n ShaderStyleProfileRef,\n ShaderValidationEvidenceRef,\n ShaderVersionRef,\n} from \"../contracts.js\";\nimport { canonicalizeGpuContract } from \"../canonical-json.js\";\nimport { assertImmutableAssetVersion } from \"../asset-version.js\";\nimport { computeGpuAbiHash, computeSha256 } from \"../hash.js\";\nimport {\n parseGpuInterfaceManifest,\n parseJsonBytes,\n parseShaderStyleProfileManifest,\n parseShaderVersionManifest,\n} from \"../manifest-validation.js\";\nimport { validateShaderDerivedRequirements } from \"../requirements-validation.js\";\nimport { trustLoadedShaderStyleProfile } from \"./trusted-values.js\";\n\nfunction diagnostic(code: ShaderDiagnostic[\"code\"], message: string, path?: string): ShaderDiagnostic {\n return { code, severity: \"error\", message, ...(path ? { path } : {}) };\n}\n\nasync function verifyBytes(bytes: Uint8Array, expected: string, label: string): Promise<void> {\n const actual = await computeSha256(bytes);\n if (actual !== expected) throw new TypeError(`${label} digest does not match its immutable reference.`);\n}\n\nfunction copyBytes(bytes: Uint8Array): Uint8Array {\n return new Uint8Array(bytes);\n}\n\nfunction snapshotProfileRef(ref: ShaderStyleProfileRef): ShaderStyleProfileRef {\n const profileId = ref.profileId;\n const version = ref.version;\n const manifestUri = ref.manifestUri;\n const manifestSha256 = ref.manifestSha256;\n return Object.freeze({ profileId, version, manifestUri, manifestSha256 });\n}\n\nfunction snapshotShaderRef(ref: ShaderVersionRef): ShaderVersionRef {\n const shaderId = ref.shaderId;\n const version = ref.version;\n const manifestUri = ref.manifestUri;\n const manifestSha256 = ref.manifestSha256;\n return Object.freeze({ shaderId, version, manifestUri, manifestSha256 });\n}\n\nfunction snapshotInterfaceRef(ref: GpuInterfaceRef): GpuInterfaceRef {\n const interfaceId = ref.interfaceId;\n const interfaceVersion = ref.interfaceVersion;\n const manifestUri = ref.manifestUri;\n const manifestSha256 = ref.manifestSha256;\n const interfaceAbiHash = ref.interfaceAbiHash;\n const modelAbiHash = ref.modelAbiHash;\n return Object.freeze({\n interfaceId,\n interfaceVersion,\n manifestUri,\n manifestSha256,\n interfaceAbiHash,\n modelAbiHash,\n });\n}\n\nfunction throwIfAborted(signal?: AbortSignal): void {\n if (signal?.aborted) throw signal.reason instanceof Error ? signal.reason : new DOMException(\"Aborted\", \"AbortError\");\n}\n\nfunction exactShaderRefKey(ref: ShaderVersionRef): string {\n return `${ref.shaderId}\\u0000${ref.version}\\u0000${ref.manifestUri}\\u0000${ref.manifestSha256}`;\n}\n\nfunction evidenceArtifacts(evidence: ShaderValidationEvidenceRef): readonly [string, string, string, string, string] {\n return [\n evidence.evidenceId,\n evidence.uri,\n evidence.sha256,\n evidence.attestationRef.uri,\n evidence.attestationRef.sha256,\n ];\n}\n\nfunction assertDistinctEvidenceOwnership(shaders: readonly LoadedShaderVersion[]): void {\n const uniqueShaders = new Map<string, LoadedShaderVersion>();\n for (const shader of shaders) uniqueShaders.set(exactShaderRefKey(shader.ref), shader);\n const evidenceIds = new Map<string, string>();\n const artifactUris = new Map<string, string>();\n const artifactDigests = new Map<string, string>();\n for (const [shaderKey, shader] of uniqueShaders) {\n const evidenceValues = [\n shader.manifest.validationEvidence,\n ...shader.manifest.additionalValidationEvidence.map((item) => item.evidence),\n ];\n for (const evidence of evidenceValues) {\n const [evidenceId, evidenceUri, evidenceSha256, attestationUri, attestationSha256] = evidenceArtifacts(evidence);\n for (const [kind, value, owners] of [\n [\"evidence ID\", evidenceId, evidenceIds],\n [\"evidence/attestation URI\", evidenceUri, artifactUris],\n [\"evidence/attestation URI\", attestationUri, artifactUris],\n [\"evidence/attestation digest\", evidenceSha256, artifactDigests],\n [\"evidence/attestation digest\", attestationSha256, artifactDigests],\n ] as const) {\n const owner = owners.get(value);\n if (owner !== undefined && owner !== shaderKey) {\n throw new TypeError(`Distinct shader versions in one style profile reuse the same ${kind}.`);\n }\n owners.set(value, shaderKey);\n }\n }\n }\n}\n\nasync function mapLimit<T, U>(\n values: readonly T[],\n limit: number,\n operation: (value: T, index: number) => Promise<U>,\n signal?: AbortSignal,\n): Promise<U[]> {\n const results = new Array<U>(values.length);\n let next = 0;\n const worker = async (): Promise<void> => {\n while (next < values.length) {\n throwIfAborted(signal);\n const index = next++;\n const value = values[index];\n if (value !== undefined) { throwIfAborted(signal); results[index] = await operation(value, index); }\n }\n };\n await Promise.all(Array.from({ length: Math.min(limit, values.length) }, () => worker()));\n return results;\n}\n\nasync function loadInterface(\n catalog: PromotedShaderCatalogResolver,\n ref: GpuInterfaceRef,\n signal?: AbortSignal,\n) {\n throwIfAborted(signal);\n assertImmutableAssetVersion(ref.interfaceVersion);\n if (!catalog.isCatalogAssetUri(ref.manifestUri)) throw new TypeError(\"GPU interface URI is outside the promoted catalog root.\");\n const loaded = await catalog.loadInterface(ref, signal);\n const bytes = copyBytes(loaded.bytes);\n const promoted = loaded.promoted;\n throwIfAborted(signal);\n if (!promoted) throw new TypeError(\"GPU interface is not promoted.\");\n await verifyBytes(bytes, ref.manifestSha256, \"GPU interface manifest\");\n const manifest = parseGpuInterfaceManifest(parseJsonBytes(bytes, \"GPU interface manifest\"));\n if (\n manifest.interfaceId !== ref.interfaceId\n || manifest.interfaceVersion !== ref.interfaceVersion\n || manifest.interfaceAbiHash !== ref.interfaceAbiHash\n || manifest.modelAbiHash !== ref.modelAbiHash\n ) {\n throw new TypeError(\"GPU interface manifest identity does not match its exact reference.\");\n }\n const modelAbiHash = await computeGpuAbiHash({ kind: \"model\", interface: manifest });\n const interfaceAbiHash = await computeGpuAbiHash({ kind: \"interface\", interface: manifest });\n if (modelAbiHash !== manifest.modelAbiHash || interfaceAbiHash !== manifest.interfaceAbiHash) {\n throw new TypeError(\"GPU interface ABI hashes do not match regenerated structural hashes.\");\n }\n return manifest;\n}\n\nasync function loadShader(\n catalog: PromotedShaderCatalogResolver,\n ref: ShaderVersionRef,\n signal?: AbortSignal,\n): Promise<LoadedShaderVersion> {\n throwIfAborted(signal);\n assertImmutableAssetVersion(ref.version);\n if (!catalog.isCatalogAssetUri(ref.manifestUri)) throw new TypeError(\"Shader manifest URI is outside the promoted catalog root.\");\n const loaded = await catalog.loadShader(ref, signal);\n const bytes = copyBytes(loaded.bytes);\n const promoted = loaded.promoted;\n throwIfAborted(signal);\n if (!promoted) throw new TypeError(\"Shader version is not promoted.\");\n await verifyBytes(bytes, ref.manifestSha256, \"Shader manifest\");\n const manifest = parseShaderVersionManifest(parseJsonBytes(bytes, \"Shader manifest\"));\n if (manifest.shaderId !== ref.shaderId || manifest.version !== ref.version) {\n throw new TypeError(\"Shader manifest identity does not match its exact reference.\");\n }\n for (const evidence of [\n manifest.validationEvidence,\n ...manifest.additionalValidationEvidence.map((item) => item.evidence),\n ]) {\n if (!catalog.isCatalogAssetUri(evidence.uri)) throw new TypeError(\"Shader validation evidence URI is outside the promoted catalog root.\");\n if (!catalog.isCatalogAssetUri(evidence.attestationRef.uri)) throw new TypeError(\"Shader validation evidence attestation URI is outside the promoted catalog root.\");\n }\n const interfaceRef = snapshotInterfaceRef(manifest.gpuInterface);\n const gpuInterface = await loadInterface(catalog, interfaceRef, signal);\n const normalizeModules = (values: readonly { readonly moduleId: string; readonly sha256: string }[]) =>\n [...values].sort((left, right) => left.moduleId < right.moduleId ? -1 : left.moduleId > right.moduleId ? 1 : 0)\n .map(({ moduleId, sha256 }) => ({ moduleId, sha256 }));\n if (canonicalizeGpuContract(normalizeModules(gpuInterface.modules)) !== canonicalizeGpuContract(normalizeModules(manifest.modules))) {\n throw new TypeError(\"Shader modules differ from the exact reflected GPU interface module set.\");\n }\n const shaderAbiHash = await computeGpuAbiHash({\n kind: \"shader\",\n interface: gpuInterface,\n pipelines: manifest.pipelines,\n requirements: manifest.requirements,\n });\n if (shaderAbiHash !== manifest.shaderAbiHash) throw new TypeError(\"Shader ABI hash differs from regenerated pipeline/interface ABI.\");\n const modulePairs = await mapLimit(manifest.modules, 4, async (module) => {\n throwIfAborted(signal);\n if (!catalog.isCatalogAssetUri(module.uri)) throw new TypeError(`Shader module ${module.moduleId} URI is outside the promoted catalog root.`);\n const asset = await catalog.loadModule(ref, module.moduleId, module.uri, signal);\n const moduleBytes = copyBytes(asset.bytes);\n const promoted = asset.promoted;\n throwIfAborted(signal);\n if (!promoted) throw new TypeError(`Shader module ${module.moduleId} is not promoted.`);\n if (moduleBytes.byteLength !== module.byteLength) {\n throw new TypeError(`Shader module ${module.moduleId} byte length does not match its manifest.`);\n }\n await verifyBytes(moduleBytes, module.sha256, `Shader module ${module.moduleId}`);\n return [module.moduleId, moduleBytes] as const;\n }, signal);\n const decoder = new TextDecoder(\"utf-8\", { fatal: true });\n validateShaderDerivedRequirements({ manifest, gpuInterface, moduleSources: new Map(modulePairs.map(([moduleId, bytes]) => [moduleId, decoder.decode(bytes)])) });\n return { ref, manifest, gpuInterface, modules: new Map(modulePairs) };\n}\n\n/** Loads only exact, promoted profile/shader/interface/module assets and verifies every digest. */\nexport async function loadShaderStyleProfile(input: {\n readonly ref: ShaderStyleProfileRef;\n readonly catalog: PromotedShaderCatalogResolver;\n readonly signal?: AbortSignal;\n}): Promise<ShaderResult<LoadedShaderStyleProfile>> {\n const signal = input.signal;\n try {\n throwIfAborted(signal);\n const ref = snapshotProfileRef(input.ref);\n assertImmutableAssetVersion(ref.version);\n if (!input.catalog.isCatalogAssetUri(ref.manifestUri)) throw new TypeError(\"Style profile URI is outside the promoted catalog root.\");\n const loaded = await input.catalog.loadProfile(ref, signal);\n const profileBytes = copyBytes(loaded.bytes);\n const promoted = loaded.promoted;\n throwIfAborted(signal);\n if (!promoted) {\n return { ok: false, diagnostics: [diagnostic(\"unpromoted-asset\", \"Style profile is not promoted.\")] };\n }\n await verifyBytes(profileBytes, ref.manifestSha256, \"Style profile manifest\");\n const manifest = parseShaderStyleProfileManifest(parseJsonBytes(profileBytes, \"Style profile manifest\"));\n if (manifest.profileId !== ref.profileId || manifest.version !== ref.version) {\n return { ok: false, diagnostics: [diagnostic(\"invalid-contract\", \"Style profile identity does not match its exact reference.\")] };\n }\n const cache = new Map<string, Promise<LoadedShaderVersion>>();\n const pairs = await mapLimit(manifest.roles, 4, async (binding) => {\n throwIfAborted(signal);\n const shaderRef = snapshotShaderRef(binding.shader);\n const cacheKey = exactShaderRefKey(shaderRef);\n let shader = cache.get(cacheKey);\n if (!shader) {\n shader = loadShader(input.catalog, shaderRef, signal);\n cache.set(cacheKey, shader);\n }\n const resolved = await shader;\n if (!resolved.manifest.renderRoles.some((role) => role.role === binding.role)) {\n throw new TypeError(`Shader ${resolved.manifest.shaderId} does not implement role ${binding.role}.`);\n }\n const validationScopes = new Map(\n resolved.manifest.additionalValidationEvidence.map((item) => [item.scope, item.evidence]),\n );\n for (const requirement of manifest.requiredValidationScopes) {\n const evidence = validationScopes.get(requirement.scope);\n if (!evidence) {\n throw new TypeError(`Shader ${resolved.manifest.shaderId} lacks required validation scope ${requirement.scope}.`);\n }\n if (\n evidence.matrixId !== requirement.matrixId\n || evidence.matrixVersion !== requirement.matrixVersion\n || evidence.matrixSha256 !== requirement.matrixSha256\n ) {\n throw new TypeError(\n `Shader ${resolved.manifest.shaderId} validation scope ${requirement.scope} is bound to a different matrix policy.`,\n );\n }\n }\n return [binding.role, resolved] as const;\n }, signal);\n assertDistinctEvidenceOwnership(pairs.map(([, shader]) => shader));\n return {\n ok: true,\n value: trustLoadedShaderStyleProfile({\n ref,\n manifest,\n shaders: new Map<ShaderRenderRole, LoadedShaderVersion>(pairs),\n }),\n };\n } catch (cause) {\n if (signal?.aborted) throw cause;\n const code = cause instanceof TypeError && /digest/u.test(cause.message)\n ? \"digest-mismatch\"\n : \"invalid-contract\";\n return {\n ok: false,\n diagnostics: [diagnostic(code, cause instanceof Error ? cause.message : \"Style profile loading failed.\")],\n };\n }\n}\n","import type {\n GpuCapabilitySnapshot,\n GpuDeviceLike,\n LoadedShaderStyleProfile,\n ModelGpuCompatibilityDescriptor,\n PreparedShaderStyleProfile,\n SerializableGpuBindGroupLayout,\n SerializableGpuPipelineDescriptor,\n ShaderDiagnostic,\n ShaderResult,\n} from \"../contracts.js\";\nimport { validateModelShaderCompatibility } from \"../compatibility.js\";\nimport { computeSha256 } from \"../hash.js\";\nimport {\n readonlyMapView,\n requireTrustedLoadedShaderStyleProfile,\n trustPreparedShaderStyleProfile,\n} from \"./trusted-values.js\";\n\nfunction error(code: ShaderDiagnostic[\"code\"], message: string): ShaderDiagnostic {\n return { code, severity: \"error\", message };\n}\n\nclass DeviceLostError extends Error {}\n\nasync function boundedGpuWait<T>(\n promise: Promise<T>,\n device: GpuDeviceLike,\n timeoutMs: number,\n signal?: AbortSignal,\n): Promise<T> {\n let timer: ReturnType<typeof setTimeout> | undefined;\n let abort: (() => void) | undefined;\n const timeout = new Promise<never>((_, reject) => { timer = setTimeout(() => reject(new Error(\"GPU operation timed out.\")), timeoutMs); });\n const lost = device.lost?.then((info) => { throw new DeviceLostError(info.message ?? info.reason ?? \"GPU device was lost.\"); });\n const aborted = signal ? new Promise<never>((_, reject) => {\n abort = () => reject(signal.reason instanceof Error ? signal.reason : new DOMException(\"Aborted\", \"AbortError\"));\n if (signal.aborted) abort(); else signal.addEventListener(\"abort\", abort, { once: true });\n }) : undefined;\n try { return await Promise.race([promise, timeout, ...(lost ? [lost] : []), ...(aborted ? [aborted] : [])]); }\n finally { if (timer) clearTimeout(timer); if (abort && signal) signal.removeEventListener(\"abort\", abort); }\n}\n\nfunction closeErrorScopeBestEffort(device: GpuDeviceLike, timeoutMs: number): void {\n if (!device.popErrorScope) return;\n const cleanupTimeout = Number.isFinite(timeoutMs) && timeoutMs > 0\n ? Math.min(timeoutMs, 1_000)\n : 1_000;\n try {\n const pending = device.popErrorScope();\n void boundedGpuWait(pending, device, cleanupTimeout).catch(() => undefined);\n } catch {\n // A cleanup failure cannot replace or indefinitely delay the primary diagnostic.\n }\n}\n\nfunction visibilityMask(stages: readonly string[]): number {\n return stages.reduce((mask, stage) => mask | (stage === \"vertex\" ? 1 : stage === \"fragment\" ? 2 : 4), 0);\n}\n\nfunction bindGroupEntry(entry: SerializableGpuBindGroupLayout[\"entries\"][number]): unknown {\n const common = { binding: entry.binding, visibility: visibilityMask(entry.visibility) };\n switch (entry.resource.kind) {\n case \"buffer\":\n return {\n ...common,\n buffer: {\n type: entry.resource.addressSpace === \"uniform\"\n ? \"uniform\"\n : entry.resource.access === \"read\" ? \"read-only-storage\" : \"storage\",\n minBindingSize: entry.resource.minimumBindingSize,\n },\n };\n case \"sampler\":\n return { ...common, sampler: { type: entry.resource.samplerType } };\n case \"texture\":\n return {\n ...common,\n texture: {\n sampleType: entry.resource.sampleType,\n viewDimension: entry.resource.viewDimension,\n multisampled: entry.resource.multisampled,\n },\n };\n case \"storage-texture\":\n return {\n ...common,\n storageTexture: {\n access: entry.resource.access,\n format: entry.resource.format,\n viewDimension: entry.resource.viewDimension,\n },\n };\n case \"external-texture\":\n return { ...common, externalTexture: {} };\n }\n}\n\nfunction pipelineLayout(device: GpuDeviceLike, pipeline: SerializableGpuPipelineDescriptor): unknown {\n const ordered = [...pipeline.layout.bindGroups].sort((left, right) => left.group - right.group);\n ordered.forEach((group, index) => {\n if (group.group !== index) throw new TypeError(`Pipeline ${pipeline.pipelineId} bind groups must be contiguous from zero.`);\n });\n const groups = ordered.map((group) => device.createBindGroupLayout({\n entries: group.entries.map(bindGroupEntry),\n }));\n return device.createPipelineLayout({ bindGroupLayouts: groups });\n}\n\nasync function createPipeline(\n device: GpuDeviceLike,\n pipeline: SerializableGpuPipelineDescriptor,\n modules: ReadonlyMap<string, unknown>,\n timeoutMs: number,\n signal?: AbortSignal,\n): Promise<unknown> {\n const layout = pipelineLayout(device, pipeline);\n const module = (moduleId: string): unknown => { const resolved = modules.get(moduleId); if (!resolved) throw new TypeError(`Pipeline ${pipeline.pipelineId} references missing module ${moduleId}.`); return resolved; };\n const constants = (values: Readonly<Record<string, boolean | number>>): Readonly<Record<string, number>> => Object.fromEntries(Object.entries(values).map(([name, value]) => [name, typeof value === \"boolean\" ? Number(value) : value]));\n if (pipeline.kind === \"compute\") {\n const descriptor = {\n label: pipeline.pipelineId,\n layout,\n compute: {\n module: module(pipeline.compute.moduleId),\n entryPoint: pipeline.compute.entryPoint,\n constants: constants(pipeline.compute.constants),\n },\n };\n return device.createComputePipelineAsync\n ? boundedGpuWait(device.createComputePipelineAsync(descriptor), device, timeoutMs, signal)\n : device.createComputePipeline?.(descriptor);\n }\n const descriptor = {\n label: pipeline.pipelineId,\n layout,\n vertex: {\n module: module(pipeline.vertex.moduleId),\n entryPoint: pipeline.vertex.entryPoint,\n constants: constants(pipeline.vertex.constants),\n buffers: pipeline.vertexBuffers.map((buffer) => ({\n arrayStride: buffer.arrayStride,\n stepMode: buffer.stepMode,\n attributes: buffer.attributes.map((attribute) => ({ format: attribute.format, offset: attribute.offset, shaderLocation: attribute.shaderLocation })),\n })),\n },\n fragment: pipeline.fragment ? {\n module: module(pipeline.fragment.moduleId),\n entryPoint: pipeline.fragment.entryPoint,\n constants: constants(pipeline.fragment.constants),\n targets: pipeline.colorTargets,\n } : undefined,\n primitive: {\n topology: pipeline.primitive.topology,\n ...(pipeline.primitive.stripIndexFormat ? { stripIndexFormat: pipeline.primitive.stripIndexFormat } : {}),\n frontFace: pipeline.primitive.frontFace,\n cullMode: pipeline.primitive.cullMode,\n unclippedDepth: pipeline.primitive.unclippedDepth,\n },\n depthStencil: pipeline.depthStencil ?? undefined,\n multisample: pipeline.multisample,\n };\n return device.createRenderPipelineAsync\n ? boundedGpuWait(device.createRenderPipelineAsync(descriptor), device, timeoutMs, signal)\n : device.createRenderPipeline?.(descriptor);\n}\n\n/** Validates, compiles, and creates every replacement pipeline before activation. */\nexport async function prepareStyleProfile(input: {\n readonly loaded: LoadedShaderStyleProfile;\n readonly model: ModelGpuCompatibilityDescriptor;\n readonly capabilities: GpuCapabilitySnapshot;\n readonly device: GpuDeviceLike;\n readonly now?: () => number;\n readonly timeoutMs?: number;\n readonly signal?: AbortSignal;\n}): Promise<ShaderResult<PreparedShaderStyleProfile>> {\n const loaded = requireTrustedLoadedShaderStyleProfile(input.loaded);\n const diagnostics: ShaderDiagnostic[] = [];\n const actualCapabilities: GpuCapabilitySnapshot = {\n features: [...input.device.features],\n limits: input.device.limits,\n formats: input.capabilities.formats,\n };\n for (const shader of loaded.shaders.values()) {\n const compatibility = validateModelShaderCompatibility({\n model: input.model,\n shader: shader.manifest,\n gpuInterface: shader.gpuInterface,\n profile: loaded.manifest,\n capabilities: actualCapabilities,\n });\n if (!compatibility.ok) diagnostics.push(...compatibility.diagnostics);\n }\n if (diagnostics.length > 0) return { ok: false, diagnostics };\n\n const modules = new Map<string, unknown>();\n const pipelines = new Map<string, unknown>();\n let errorScopeOpen = false;\n try {\n if (input.device.pushErrorScope && input.device.popErrorScope) {\n input.device.pushErrorScope(\"validation\");\n errorScopeOpen = true;\n }\n for (const [role, shader] of loaded.shaders) {\n const shaderModules = new Map<string, unknown>();\n for (const moduleManifest of shader.manifest.modules) {\n const bytes = shader.modules.get(moduleManifest.moduleId);\n if (!bytes) throw new TypeError(`Module ${moduleManifest.moduleId} is missing after verified loading.`);\n if (bytes.byteLength !== moduleManifest.byteLength) {\n throw new TypeError(`Module ${moduleManifest.moduleId} byte length changed after verified loading.`);\n }\n if (await computeSha256(bytes) !== moduleManifest.sha256) {\n throw new TypeError(`Module ${moduleManifest.moduleId} digest changed after verified loading.`);\n }\n const source = new TextDecoder(\"utf-8\", { fatal: true }).decode(bytes);\n const module = input.device.createShaderModule({\n label: `${shader.manifest.shaderId}:${moduleManifest.moduleId}`,\n code: source,\n });\n const information = await boundedGpuWait(module.getCompilationInfo(), input.device, input.timeoutMs ?? 30_000, input.signal);\n const failures = information.messages.filter((message) => message.type === \"error\");\n if (failures.length > 0) {\n throw new TypeError(`WGSL compilation failed for ${shader.manifest.shaderId}:${moduleManifest.moduleId}: ${failures[0]?.message ?? \"unknown error\"}`);\n }\n modules.set(`${role}:${moduleManifest.moduleId}`, module);\n shaderModules.set(moduleManifest.moduleId, module);\n }\n const roleManifest = shader.manifest.renderRoles.find((item) => item.role === role);\n if (!roleManifest) throw new TypeError(`Shader role ${role} disappeared during preparation.`);\n for (const pipelineId of roleManifest.pipelineIds) {\n const descriptor = shader.manifest.pipelines.find((item) => item.pipelineId === pipelineId);\n if (!descriptor) throw new TypeError(`Pipeline ${pipelineId} is missing from its shader manifest.`);\n const pipeline = await createPipeline(input.device, descriptor, shaderModules, input.timeoutMs ?? 30_000, input.signal);\n if (!pipeline) throw new TypeError(`GPU implementation did not create pipeline ${pipelineId}.`);\n pipelines.set(`${role}:${pipelineId}`, pipeline);\n }\n }\n let scopedError: { readonly message?: string } | null = null;\n if (input.device.popErrorScope) {\n errorScopeOpen = false;\n scopedError = await boundedGpuWait(input.device.popErrorScope(), input.device, input.timeoutMs ?? 30_000, input.signal);\n }\n if (scopedError) throw new TypeError(scopedError.message ?? \"GPU validation error while preparing style profile.\");\n let disposed = false;\n const publicPipelines = readonlyMapView(pipelines);\n const prepared = trustPreparedShaderStyleProfile({\n loaded: loaded.publicValue,\n pipelines: publicPipelines,\n preparedAt: (input.now ?? Date.now)(),\n dispose() {\n if (disposed) return;\n disposed = true;\n pipelines.clear();\n modules.clear();\n },\n });\n return {\n ok: true,\n value: prepared,\n };\n } catch (cause) {\n pipelines.clear();\n modules.clear();\n if (errorScopeOpen) {\n closeErrorScopeBestEffort(input.device, input.timeoutMs ?? 30_000);\n }\n return {\n ok: false,\n diagnostics: [error(\n cause instanceof DeviceLostError ? \"device-lost\"\n : cause instanceof TypeError && /digest|byte length/u.test(cause.message) ? \"digest-mismatch\"\n : cause instanceof TypeError && /compilation/u.test(cause.message) ? \"compilation-error\"\n : cause instanceof Error && /timed out/u.test(cause.message) ? \"timeout\" : \"pipeline-error\",\n cause instanceof Error ? cause.message : \"Style profile preparation failed.\",\n )],\n };\n }\n}\n","import type {\n ActiveShaderStyleProfile,\n FrameBoundaryScheduler,\n PreparedShaderStyleProfile,\n ShaderDiagnostic,\n ShaderResult,\n ShaderStyleController,\n} from \"../contracts.js\";\nimport { requireTrustedPreparedShaderStyleProfile } from \"./trusted-values.js\";\n\ninterface ControllerState {\n current: ActiveShaderStyleProfile | null;\n readonly scheduler: FrameBoundaryScheduler;\n readonly now: () => number;\n activationTail: Promise<void>;\n}\n\nconst controllers = new WeakMap<object, ControllerState>();\n\n/** Creates an atomic frame-boundary style-profile controller. */\nexport function createShaderStyleController(input: {\n readonly scheduler: FrameBoundaryScheduler;\n readonly initial?: PreparedShaderStyleProfile;\n readonly now?: () => number;\n}): ShaderStyleController {\n if (input.initial) requireTrustedPreparedShaderStyleProfile(input.initial);\n const now = input.now ?? Date.now;\n const state: ControllerState = {\n current: input.initial ? Object.freeze({ prepared: input.initial, activatedAt: now() }) : null,\n scheduler: input.scheduler,\n now,\n activationTail: Promise.resolve(),\n };\n const controller = Object.freeze({\n get current(): ActiveShaderStyleProfile | null { return state.current; },\n } satisfies ShaderStyleController);\n controllers.set(controller, state);\n return controller;\n}\n\n/** Atomically swaps a fully prepared profile; failure preserves the active profile. */\nexport async function activateStyleProfile(input: {\n readonly controller: ShaderStyleController;\n readonly prepared: PreparedShaderStyleProfile;\n readonly retire?: (previous: PreparedShaderStyleProfile) => void | Promise<void>;\n}): Promise<ShaderResult<ActiveShaderStyleProfile>> {\n const controller = controllers.get(input.controller as object);\n if (!controller) {\n throw new TypeError(\"controller must be created by createShaderStyleController.\");\n }\n requireTrustedPreparedShaderStyleProfile(input.prepared);\n const operation = controller.activationTail.then(async (): Promise<ShaderResult<ActiveShaderStyleProfile>> => {\n const previous = controller.current;\n let callbackOpen = true;\n let callbackInvoked = false;\n let callbackViolation: TypeError | null = null;\n const next = Object.freeze({ prepared: input.prepared, activatedAt: controller.now() });\n try {\n await controller.scheduler.schedule(() => {\n if (!callbackOpen || callbackInvoked) {\n callbackViolation ??= new TypeError(\"Frame-boundary scheduler invoked an activation callback more than once or after completion.\");\n throw callbackViolation;\n }\n callbackInvoked = true;\n controller.current = next;\n });\n callbackOpen = false;\n if (callbackViolation) throw callbackViolation;\n if (!callbackInvoked) throw new TypeError(\"Frame-boundary scheduler completed without invoking the activation callback.\");\n } catch (cause) {\n callbackOpen = false;\n if (controller.current === next) controller.current = previous;\n if (!previous || previous.prepared !== input.prepared) {\n try { input.prepared.dispose(); } catch { /* disposal cannot replace activation failure */ }\n }\n const diagnostic: ShaderDiagnostic = {\n code: \"activation-error\",\n severity: \"error\",\n message: cause instanceof Error ? cause.message : \"Frame-boundary activation failed.\",\n };\n return { ok: false, diagnostics: [diagnostic] };\n }\n if (previous && previous.prepared !== input.prepared) {\n try {\n if (input.retire) await input.retire(previous.prepared);\n else previous.prepared.dispose();\n } catch {\n // The frame-boundary switch is already complete; retirement is best-effort cleanup.\n }\n }\n return { ok: true, value: next };\n });\n controller.activationTail = operation.then(() => undefined, () => undefined);\n return operation;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACCO,IAAM,iCAAiC;AACvC,IAAM,kCAAkC;AACxC,IAAM,wCAAwC;AAC9C,IAAM,8BAA8B;AACpC,IAAM,qCAAqC;AAC3C,IAAM,+BAA+B;AACrC,IAAM,uCAAuC;AAC7C,IAAM,sCAAsC;AAE5C,IAAM,gCAAgC;AAEtC,IAAM,wCAAwC;AAM9C,IAAM,0CAA0C;AAAA,EACrD,OAAO,OAAO;AAAA,IACZ,UAAU;AAAA,IACV,eAAe;AAAA,IACf,cAAc;AAAA,EAChB,CAAC;AACH;AAKA,OAAO,OAAO,uCAAuC;AAM9C,IAAM,4CAKN,OAAO,OAAO,CAAC,CAAC;;;ACxCvB,IAAM,wBAAwB;AAE9B,IAAM,0BAA0B,oBAAI,IAAI;AAAA,EACtC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,CAAC;AAED,IAAM,6BAA6B;AACnC,IAAM,kCACJ;AASK,SAAS,4BAA4B,OAAwB;AAClE,MACE,OAAO,UAAU,YACd,CAAC,sBAAsB,KAAK,KAAK,KACjC,wBAAwB,IAAI,MAAM,YAAY,CAAC,KAC/C,2BAA2B,KAAK,KAAK,GACxC;AACA,UAAM,IAAI,UAAU,+BAA+B;AAAA,EACrD;AACA,SAAO;AACT;;;AClCA,SAAS,cAAc,OAAiD;AACtE,QAAM,YAAY,OAAO,eAAe,KAAK;AAC7C,SAAO,cAAc,OAAO,aAAa,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;AACf,UAAI,kBAAmB,OAAM;AAC7B,UAAI,CAAC,gBAAiB,OAAM,IAAI,UAAU,8EAA8E;AAAA,IAC1H,SAAS,OAAO;AACd,qBAAe;AACf,UAAI,WAAW,YAAY,KAAM,YAAW,UAAU;AACtD,UAAI,CAAC,YAAY,SAAS,aAAa,MAAM,UAAU;AACrD,YAAI;AAAE,gBAAM,SAAS,QAAQ;AAAA,QAAG,QAAQ;AAAA,QAAmD;AAAA,MAC7F;AACA,YAAMK,cAA+B;AAAA,QACnC,MAAM;AAAA,QACN,UAAU;AAAA,QACV,SAAS,iBAAiB,QAAQ,MAAM,UAAU;AAAA,MACpD;AACA,aAAO,EAAE,IAAI,OAAO,aAAa,CAACA,WAAU,EAAE;AAAA,IAChD;AACA,QAAI,YAAY,SAAS,aAAa,MAAM,UAAU;AACpD,UAAI;AACF,YAAI,MAAM,OAAQ,OAAM,MAAM,OAAO,SAAS,QAAQ;AAAA,YACjD,UAAS,SAAS,QAAQ;AAAA,MACjC,QAAQ;AAAA,MAER;AAAA,IACF;AACA,WAAO,EAAE,IAAI,MAAM,OAAO,KAAK;AAAA,EACjC,CAAC;AACD,aAAW,iBAAiB,UAAU,KAAK,MAAM,QAAW,MAAM,MAAS;AAC3E,SAAO;AACT;","names":["digest","binding","semantic","significand","_","pipeline","stages","semantic","binding","module","integer","value","value","module","integer","semantic","ref","manifest","publicValue","interfaceRef","module","promoted","bytes","binding","error","stages","pipeline","module","descriptor","diagnostic"]}