@gasm-compiler/core 0.5.0 → 0.7.0

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.
@@ -0,0 +1,9 @@
1
+ import{a as L,c as q,e as W,f as D,k as j,l as Z,m as E,n as _,o as N,p as k,r as O,v as H,w as K}from"./chunk-CYV3E4CZ.js";import{a as w}from"./chunk-STDXBN5E.js";import{resolve as fe}from"node:path";import{stat as de,readFile as Ne,writeFile as Oe,unlink as Ue,mkdir as Te}from"node:fs/promises";import{spawn as ze}from"node:child_process";import{dirname as Fe}from"node:path";import{readFileSync as he}from"node:fs";var Q,J;async function ye(n=T()){let e=await ve(n),r=await WebAssembly.instantiate(Y(e),{});return _(r.instance.exports)}function U(n=T()){return J??=ye(n),J}function be(n=T()){let e=Me(n),r=new WebAssembly.Module(Y(e)),t=new WebAssembly.Instance(r,{});return _(t.exports)}function X(n,e={}){return Q??=be(),Q.compile(n,e)}function T(){let n=globalThis.Deno,e=new URL("./gasm_core_rs.wasm",import.meta.url);if(n){let r=new URL("../../core-rs/target/wasm32-unknown-unknown/debug/gasm_core_rs.wasm",import.meta.url);try{return n.statSync(r),r}catch{}let t=new URL("../../core-rs/target/wasm32-unknown-unknown/release/gasm_core_rs.wasm",import.meta.url);try{return n.statSync(t),t}catch{}try{return n.statSync(e),e}catch{}}return new URL("../../core-rs/target/wasm32-unknown-unknown/debug/gasm_core_rs.wasm",import.meta.url)}async function ve(n){let e=globalThis.Deno;return e?await e.readFile(n):await(await import("node:fs/promises")).readFile(n)}function Me(n){let e=globalThis.Deno;return e?e.readFileSync(n):he(n)}function Y(n){return n.buffer.slice(n.byteOffset,n.byteOffset+n.byteLength)}function xe(n){return n===!0?n="normal":n===!1&&(n="none"),{level:n,includeWasmOffsets:n==="detailed"||n==="verbose",includeSemanticInfo:n!=="none"&&n!=="minimal",includeIRInfo:n==="verbose",includeLanguageTag:n!=="none"}}function ee(n){let e=se(n,"name");if(!e)return null;let r={functionNames:new Map,localNames:new Map,globalNames:new Map,labelNames:new Map},t=new DataView(e.buffer,e.byteOffset,e.byteLength),s=0;for(;s<e.length;){let[i,a]=M(e,s);s+=a;let[c,l]=M(e,s);s+=l;let m=s+c;switch(i){case 0:{let[u,f]=B(e,s);r.moduleName=u,s+=f}break;case 1:{let[u,f]=M(e,s);s+=f;for(let g=0;g<u;g++){let[d,y]=M(e,s);s+=y;let[b,h]=B(e,s);s+=h,r.functionNames.set(d,b)}}break;case 2:{let[u,f]=M(e,s);s+=f;for(let g=0;g<u;g++){let[d,y]=M(e,s);s+=y;let[b,h]=M(e,s);s+=h;let I=new Map;for(let x=0;x<b;x++){let[R,P]=M(e,s);s+=P;let[o,p]=B(e,s);s+=p,I.set(R,o)}r.localNames.set(d,I)}}break;case 7:{let[u,f]=M(e,s);s+=f;for(let g=0;g<u;g++){let[d,y]=M(e,s);s+=y;let[b,h]=B(e,s);s+=h,r.globalNames.set(d,b)}}break;default:s=m;break}s<m&&(s=m)}return r}function te(n){let e=se(n,"producers");if(!e)return null;let r={},t=0,[s,i]=M(e,t);t+=i;for(let a=0;a<s;a++){let[c,l]=B(e,t);t+=l;let[m,u]=M(e,t);t+=u;let f=[];for(let g=0;g<m;g++){let[d,y]=B(e,t);t+=y;let[b,h]=B(e,t);t+=h,f.push(b?`${d} ${b}`:d)}switch(c){case"language":r.languages=f;break;case"processed-by":r.processedBy=f;break;case"sdk":r.sdks=f;break}}return r}function se(n,e){if(n.length<8||(n[0]<<0|n[1]<<8|n[2]<<16|n[3]<<24)!==1836278016)return null;let t=8;for(;t<n.length;){let s=n[t++],[i,a]=M(n,t);t+=a;let c=t+i;if(s===0){let[l,m]=B(n,t);if(l===e)return n.subarray(t+m,c)}t=c}return null}function M(n,e){let r=0,t=0,s=0;for(;;){let i=n[e+s];if(s++,r|=(i&127)<<t,(i&128)===0)break;t+=7}return[r,s]}function B(n,e){let[r,t]=M(n,e),s=n.subarray(e+t,e+t+r);return[new TextDecoder().decode(s),t+r]}function ne(n,e,r){if(r?.languages)for(let t of r.languages){let s=t.toLowerCase();if(s.includes("assemblyscript"))return"assemblyscript";if(s.includes("rust"))return"rust";if(s.includes("c")&&!s.includes("script"))return"c"}if(r?.processedBy)for(let t of r.processedBy){let s=t.toLowerCase();if(s.includes("assemblyscript")||s.includes("asc"))return"assemblyscript";if(s.includes("rustc"))return"rust";if(s.includes("clang")||s.includes("emscripten"))return"c"}if(e)for(let t of e.functionNames.values()){if(t.includes("~lib/")||t.includes("assembly/"))return"assemblyscript";if(t.includes("core::")||t.includes("alloc::")||t.includes("__rust"))return"rust";if(t.startsWith("__")||t.includes("emscripten"))return"c"}return e&&e.functionNames.size>0&&!r?"wat":"unknown"}function re(n){let e=ee(n),r=te(n),t=ne(n,e,r),s="low";return e&&(e.functionNames.size>0&&e.localNames.size>0?s="high":e.functionNames.size>0&&(s="medium")),{language:t,quality:s,functionNames:e?.functionNames??new Map,localNames:e?.localNames??new Map,globalNames:e?.globalNames??new Map,blockLabels:e?.labelNames??new Map,producers:r??void 0}}var z=class{options;debugInfo;constructor(e,r){this.options=r,this.debugInfo=re(e)}getLanguage(){return this.debugInfo.language}getQuality(){return this.debugInfo.quality}generateHeaderComment(){if(this.options.level==="none")return null;let e=[];if(this.options.includeLanguageTag){let r=this.formatLanguageName(this.debugInfo.language);e.push(`Source Language: ${r}`)}return(this.options.level==="detailed"||this.options.level==="verbose")&&(e.push(`Debug Info: ${this.debugInfo.quality}`),this.debugInfo.producers?.processedBy&&e.push(`Processed By: ${this.debugInfo.producers.processedBy.join(", ")}`)),e.length>0?`// ${e.join(" | ")}`:null}commentForFunction(e,r){if(this.options.level==="none")return null;let t=[],s=this.debugInfo.functionNames.get(e),i=r||s||`func_${e}`;return t.push(`Function ${e}: "${i}"`),s&&s!==r&&s!==i&&t.push(`(debug: ${s})`),`// ${t.join(" ")}`}commentForVariable(e,r,t){if(this.options.level==="none"||this.options.level==="minimal")return null;let i=this.debugInfo.localNames.get(e)?.get(r);return i?` // ${i}${t?" (param)":""}`:null}commentForGlobal(e){if(this.options.level==="none"||this.options.level==="minimal")return null;let r=this.debugInfo.globalNames.get(e);return r?` // ${r}`:null}commentForInstruction(e,r){if(this.options.level==="none"||this.options.level==="minimal")return null;let t=[];if(t.push(`[WAT] ${e.opcode}`),e.opcode==="local.get"||e.opcode==="local.set"||e.opcode==="local.tee"){let s=e.immediates?.[0];if(s!==void 0){let a=this.debugInfo.localNames.get(r)?.get(s);a&&t.push(`(${a})`)}}if(e.opcode==="global.get"||e.opcode==="global.set"){let s=e.immediates?.[0];if(s!==void 0){let i=this.debugInfo.globalNames.get(s);i&&t.push(`(${i})`)}}return this.options.includeIRInfo&&e.id!==void 0&&t.push(`[IR] v${e.id}`),`// ${t.join(" ")}`}commentForStatement(e,r,t=0){if(this.options.level==="none")return null;let s=[];switch(e.kind){case"loop":s.push("[LOOP]"),e.label&&s.push(`${e.label}`);break;case"parallel_loop":s.push("[PARALLEL]");break;case"block":if(e.label)s.push(`[BLOCK] ${e.label}`);else if(this.options.level==="detailed"||this.options.level==="verbose")return null;break;case"if":if(this.options.level!=="minimal")s.push("[IF]");else return null;break;default:return null}return s.length>0?`// ${s.join(" ")}`:null}commentForEndBlock(e){return this.options.level!=="detailed"&&this.options.level!=="verbose"?null:e?`// End: ${e}`:null}formatLanguageName(e){switch(e){case"wat":return"WAT (WebAssembly Text)";case"assemblyscript":return"AssemblyScript";case"c":return"C/C++";case"rust":return"Rust";default:return"Unknown"}}};function ie(n,e){if(!e||e==="none")return null;let r=xe(e);return new z(n,r)}var A=new Map([["sin",{name:"sin",level:"M0",wasmParams:["f32"],wasmResults:["f32"],wgslBuiltin:"sin",supportsVector:!0,description:"Sine of angle in radians"}],["cos",{name:"cos",level:"M0",wasmParams:["f32"],wasmResults:["f32"],wgslBuiltin:"cos",supportsVector:!0,description:"Cosine of angle in radians"}],["tan",{name:"tan",level:"M0",wasmParams:["f32"],wasmResults:["f32"],wgslBuiltin:"tan",supportsVector:!0,description:"Tangent of angle in radians"}],["asin",{name:"asin",level:"M0",wasmParams:["f32"],wasmResults:["f32"],wgslBuiltin:"asin",supportsVector:!0,description:"Arc sine, returns radians"}],["acos",{name:"acos",level:"M0",wasmParams:["f32"],wasmResults:["f32"],wgslBuiltin:"acos",supportsVector:!0,description:"Arc cosine, returns radians"}],["atan",{name:"atan",level:"M0",wasmParams:["f32"],wasmResults:["f32"],wgslBuiltin:"atan",supportsVector:!0,description:"Arc tangent, returns radians"}],["atan2",{name:"atan2",level:"M0",wasmParams:["f32","f32"],wasmResults:["f32"],wgslBuiltin:"atan2",supportsVector:!0,description:"Arc tangent of y/x, returns radians"}],["sinh",{name:"sinh",level:"M0",wasmParams:["f32"],wasmResults:["f32"],wgslBuiltin:"sinh",supportsVector:!0,description:"Hyperbolic sine"}],["cosh",{name:"cosh",level:"M0",wasmParams:["f32"],wasmResults:["f32"],wgslBuiltin:"cosh",supportsVector:!0,description:"Hyperbolic cosine"}],["tanh",{name:"tanh",level:"M0",wasmParams:["f32"],wasmResults:["f32"],wgslBuiltin:"tanh",supportsVector:!0,description:"Hyperbolic tangent"}],["asinh",{name:"asinh",level:"M0",wasmParams:["f32"],wasmResults:["f32"],wgslBuiltin:"asinh",supportsVector:!0,description:"Inverse hyperbolic sine"}],["acosh",{name:"acosh",level:"M0",wasmParams:["f32"],wasmResults:["f32"],wgslBuiltin:"acosh",supportsVector:!0,description:"Inverse hyperbolic cosine"}],["atanh",{name:"atanh",level:"M0",wasmParams:["f32"],wasmResults:["f32"],wgslBuiltin:"atanh",supportsVector:!0,description:"Inverse hyperbolic tangent"}],["exp",{name:"exp",level:"M0",wasmParams:["f32"],wasmResults:["f32"],wgslBuiltin:"exp",supportsVector:!0,description:"e raised to the power of x"}],["exp2",{name:"exp2",level:"M0",wasmParams:["f32"],wasmResults:["f32"],wgslBuiltin:"exp2",supportsVector:!0,description:"2 raised to the power of x"}],["log",{name:"log",level:"M0",wasmParams:["f32"],wasmResults:["f32"],wgslBuiltin:"log",supportsVector:!0,description:"Natural logarithm"}],["log2",{name:"log2",level:"M0",wasmParams:["f32"],wasmResults:["f32"],wgslBuiltin:"log2",supportsVector:!0,description:"Base-2 logarithm"}],["pow",{name:"pow",level:"M0",wasmParams:["f32","f32"],wasmResults:["f32"],wgslBuiltin:"pow",supportsVector:!0,description:"x raised to the power of y"}],["sqrt",{name:"sqrt",level:"M0",wasmParams:["f32"],wasmResults:["f32"],wgslBuiltin:"sqrt",supportsVector:!0,description:"Square root"}],["inverseSqrt",{name:"inverseSqrt",level:"M0",wasmParams:["f32"],wasmResults:["f32"],wgslBuiltin:"inverseSqrt",supportsVector:!0,description:"Inverse square root (1/sqrt(x))"}],["abs",{name:"abs",level:"M0",wasmParams:["f32"],wasmResults:["f32"],wgslBuiltin:"abs",supportsVector:!0,description:"Absolute value"}],["sign",{name:"sign",level:"M0",wasmParams:["f32"],wasmResults:["f32"],wgslBuiltin:"sign",supportsVector:!0,description:"Sign of x (-1, 0, or 1)"}],["floor",{name:"floor",level:"M0",wasmParams:["f32"],wasmResults:["f32"],wgslBuiltin:"floor",supportsVector:!0,description:"Floor (round toward negative infinity)"}],["ceil",{name:"ceil",level:"M0",wasmParams:["f32"],wasmResults:["f32"],wgslBuiltin:"ceil",supportsVector:!0,description:"Ceiling (round toward positive infinity)"}],["trunc",{name:"trunc",level:"M0",wasmParams:["f32"],wasmResults:["f32"],wgslBuiltin:"trunc",supportsVector:!0,description:"Truncate (round toward zero)"}],["round",{name:"round",level:"M0",wasmParams:["f32"],wasmResults:["f32"],wgslBuiltin:"round",supportsVector:!0,description:"Round to nearest integer"}],["fract",{name:"fract",level:"M0",wasmParams:["f32"],wasmResults:["f32"],wgslBuiltin:"fract",supportsVector:!0,description:"Fractional part (x - floor(x))"}],["min",{name:"min",level:"M0",wasmParams:["f32","f32"],wasmResults:["f32"],wgslBuiltin:"min",supportsVector:!0,description:"Minimum of two values"}],["max",{name:"max",level:"M0",wasmParams:["f32","f32"],wasmResults:["f32"],wgslBuiltin:"max",supportsVector:!0,description:"Maximum of two values"}],["clamp",{name:"clamp",level:"M0",wasmParams:["f32","f32","f32"],wasmResults:["f32"],wgslBuiltin:"clamp",supportsVector:!0,description:"Clamp value between min and max"}],["saturate",{name:"saturate",level:"M0",wasmParams:["f32"],wasmResults:["f32"],wgslBuiltin:"saturate",supportsVector:!0,description:"Clamp to [0, 1]"}],["mix",{name:"mix",level:"M0",wasmParams:["f32","f32","f32"],wasmResults:["f32"],wgslBuiltin:"mix",supportsVector:!0,description:"Linear interpolation"}],["step",{name:"step",level:"M0",wasmParams:["f32","f32"],wasmResults:["f32"],wgslBuiltin:"step",supportsVector:!0,description:"Step function (0 if x < edge, else 1)"}],["smoothstep",{name:"smoothstep",level:"M0",wasmParams:["f32","f32","f32"],wasmResults:["f32"],wgslBuiltin:"smoothstep",supportsVector:!0,description:"Smooth Hermite interpolation"}],["fma",{name:"fma",level:"M0",wasmParams:["f32","f32","f32"],wasmResults:["f32"],wgslBuiltin:"fma",supportsVector:!0,description:"Fused multiply-add (a * b + c)"}],["length",{name:"length",level:"M1",wasmParams:["v128"],wasmResults:["f32"],wgslBuiltin:"length",supportsVector:!1,description:"Vector length (magnitude)"}],["distance",{name:"distance",level:"M1",wasmParams:["v128","v128"],wasmResults:["f32"],wgslBuiltin:"distance",supportsVector:!1,description:"Distance between two points"}],["dot",{name:"dot",level:"M1",wasmParams:["v128","v128"],wasmResults:["f32"],wgslBuiltin:"dot",supportsVector:!1,description:"Dot product"}],["cross",{name:"cross",level:"M1",wasmParams:["v128","v128"],wasmResults:["v128"],wgslBuiltin:"cross",supportsVector:!1,description:"Cross product (vec3 only)"}],["normalize",{name:"normalize",level:"M1",wasmParams:["v128"],wasmResults:["v128"],wgslBuiltin:"normalize",supportsVector:!1,description:"Normalize vector to unit length"}],["reflect",{name:"reflect",level:"M1",wasmParams:["v128","v128"],wasmResults:["v128"],wgslBuiltin:"reflect",supportsVector:!1,description:"Reflect incident vector off surface"}],["refract",{name:"refract",level:"M1",wasmParams:["v128","v128","f32"],wasmResults:["v128"],wgslBuiltin:"refract",supportsVector:!1,description:"Refract vector through surface"}],["faceForward",{name:"faceForward",level:"M1",wasmParams:["v128","v128","v128"],wasmResults:["v128"],wgslBuiltin:"faceForward",supportsVector:!1,description:"Flip normal to face forward"}],["modf",{name:"modf",level:"M2",wasmParams:["f32"],wasmResults:["f32","f32"],wgslBuiltin:"modf",supportsVector:!0,description:"Split into fractional and integer parts",flags:{returnsStruct:!0,structTypeName:"__modf_result_f32"}}],["frexp",{name:"frexp",level:"M2",wasmParams:["f32"],wasmResults:["f32","i32"],wgslBuiltin:"frexp",supportsVector:!0,description:"Extract significand and exponent",flags:{returnsStruct:!0,structTypeName:"__frexp_result_f32"}}],["ldexp",{name:"ldexp",level:"M2",wasmParams:["f32","i32"],wasmResults:["f32"],wgslBuiltin:"ldexp",supportsVector:!0,description:"Construct value from significand and exponent"}],["degrees",{name:"degrees",level:"M2",wasmParams:["f32"],wasmResults:["f32"],wgslBuiltin:"degrees",supportsVector:!0,description:"Convert radians to degrees"}],["radians",{name:"radians",level:"M2",wasmParams:["f32"],wasmResults:["f32"],wgslBuiltin:"radians",supportsVector:!0,description:"Convert degrees to radians"}],["abs_i32",{name:"abs_i32",level:"M0",wasmParams:["i32"],wasmResults:["i32"],wgslBuiltin:"abs",supportsVector:!1,description:"Absolute value (integer)"}],["min_i32",{name:"min_i32",level:"M0",wasmParams:["i32","i32"],wasmResults:["i32"],wgslBuiltin:"min",supportsVector:!1,description:"Minimum of two integers"}],["max_i32",{name:"max_i32",level:"M0",wasmParams:["i32","i32"],wasmResults:["i32"],wgslBuiltin:"max",supportsVector:!1,description:"Maximum of two integers"}],["clamp_i32",{name:"clamp_i32",level:"M0",wasmParams:["i32","i32","i32"],wasmResults:["i32"],wgslBuiltin:"clamp",supportsVector:!1,description:"Clamp integer between min and max"}],["countOneBits",{name:"countOneBits",level:"M2",wasmParams:["i32"],wasmResults:["i32"],wgslBuiltin:"countOneBits",supportsVector:!1,description:"Count number of 1 bits (popcount)"}],["countLeadingZeros",{name:"countLeadingZeros",level:"M2",wasmParams:["i32"],wasmResults:["i32"],wgslBuiltin:"countLeadingZeros",supportsVector:!1,description:"Count leading zero bits"}],["countTrailingZeros",{name:"countTrailingZeros",level:"M2",wasmParams:["i32"],wasmResults:["i32"],wgslBuiltin:"countTrailingZeros",supportsVector:!1,description:"Count trailing zero bits"}],["firstLeadingBit",{name:"firstLeadingBit",level:"M2",wasmParams:["i32"],wasmResults:["i32"],wgslBuiltin:"firstLeadingBit",supportsVector:!1,description:"Position of first leading 1 bit"}],["firstTrailingBit",{name:"firstTrailingBit",level:"M2",wasmParams:["i32"],wasmResults:["i32"],wgslBuiltin:"firstTrailingBit",supportsVector:!1,description:"Position of first trailing 1 bit"}],["reverseBits",{name:"reverseBits",level:"M2",wasmParams:["i32"],wasmResults:["i32"],wgslBuiltin:"reverseBits",supportsVector:!1,description:"Reverse bit order"}],["extractBits",{name:"extractBits",level:"M2",wasmParams:["i32","i32","i32"],wasmResults:["i32"],wgslBuiltin:"extractBits",supportsVector:!1,description:"Extract bits from value"}],["insertBits",{name:"insertBits",level:"M2",wasmParams:["i32","i32","i32","i32"],wasmResults:["i32"],wgslBuiltin:"insertBits",supportsVector:!1,description:"Insert bits into value"}]]);function $e(n,e){if(n!=="gasm")return!1;let r=oe(e);return A.has(r)}function oe(n){if(A.has(n))return n;let e=n.match(/^(.+)_v([234])f32(?:_v)?$/);if(e)return e[1];let r=n.match(/^(.+)_f32$/);return r&&A.has(r[1])?r[1]:n}function ae(n){let e=oe(n);return A.get(e)}function Re(n){return ae(n)?.wgslBuiltin}function Se(n){let e=n.match(/_v([234])f32(?:_v)?$/);return e?parseInt(e[1],10):4}function Be(n){let e=["M0","M1","M2"],r=e.indexOf(n);return Array.from(A.values()).filter(t=>e.indexOf(t.level)<=r)}var le={};for(let[n,e]of Object.entries(q))le[e]=n.replace(/_/g,".");function Ie(n){let e=[];e.push("(module");for(let t of n.memories)e.push(` (memory ${t.min}${t.max!==void 0?` ${t.max}`:""})`);for(let t of n.imports)if(t.kind==="func"&&t.typeIndex!==void 0){let s=n.types[t.typeIndex];if(s){let i=s.params.map((c,l)=>`(param $${l} ${c})`).join(" "),a=s.results.map(c=>`(result ${c})`).join(" ");e.push(` (import "${t.module}" "${t.name}" (func ${i}${a?" "+a:""}))`)}}let r=new Set;for(let t of n.globals){if(t.kind==="import")continue;let s=t.mutable?"(mut ":"",i=t.mutable?")":"",a="";t.initValue!==void 0&&(t.type==="i32"||t.type==="i64"?a=`${t.type}.const ${t.initValue}`:(t.type==="f32"||t.type==="f64")&&(a=`${t.type}.const ${t.initValue}`)),e.push(` (global $${t.index} ${s}${t.type}${i} ${a?`(${a})`:""})`)}for(let t of n.data){let s=Array.from(t.data.slice(0,Math.min(32,t.data.length))).map(a=>`\\${a.toString(16).padStart(2,"0")}`).join(""),i=t.data.length>32?"...":"";e.push(` (data (i32.const ${t.memoryIndex}) "${s}${i}") ;; ${t.data.length} bytes`)}for(let t of n.functions)e.push(""),e.push(...Pe(t,n));if(n.exports.length>0){e.push("");for(let t of n.exports)t.kind==="func"?e.push(` (export "${t.name}" (func $${t.index}))`):t.kind==="mem"?e.push(` (export "${t.name}" (memory ${t.index}))`):t.kind==="global"&&e.push(` (export "${t.name}" (global ${t.index}))`)}return n.startFunctionIndex!==void 0&&e.push(` (start $${n.startFunctionIndex})`),e.push(")"),e.join(`
2
+ `)}function Pe(n,e){let r=[],t=n.params.map((a,c)=>`(param $${c} ${a})`).join(" "),s=n.results.map(a=>`(result ${a})`).join(" ");if(r.push(` (func $${n.index} ${t}${s?" "+s:""}`),n.locals.length>0){let a=new Map;for(let c of n.locals)a.set(c.type,(a.get(c.type)||0)+1);for(let[c,l]of a)r.push(` (local ${c} (;${l}x;))`)}let i=Ce(n.body,2);return r.push(...i),r.push(" )"),r}function Ce(n,e){let r=[],t=" ".repeat(e);for(let s of n){let i=Ae(s,e);r.push(`${t}${i}`)}return r}function Ae(n,e){if(!n||typeof n!="object")return";; Error: Invalid instruction";let{opcode:r,immediates:t}=n,s=le[r]||`unknown_0x${r.toString(16)}`;if(!t||t.length===0)return s;switch(s){case"local.get":case"local.set":case"local.tee":return`${s} $${t[0]}`;case"global.get":case"global.set":return`${s} $${t[0]}`;case"i32.const":case"i64.const":return`${s} ${t[0]}`;case"f32.const":case"f64.const":return`${s} ${t[0]}`;case"call":return`${s} $${t[0]}`;case"call_indirect":return`${s} (type ${t[0]})`;case"br":case"br_if":return`${s} ${t[0]}`;case"br_table":let i=t[0].join(" "),a=t[1];return`${s} ${i} ${a}`;case"if":case"block":case"loop":let c=t[0];return`${s} ${c!==void 0&&c!=="void"?`(result ${c})`:""}`;case"i32.load":case"i64.load":case"f32.load":case"f64.load":case"i32.load8_s":case"i32.load8_u":case"i32.load16_s":case"i32.load16_u":case"i64.load8_s":case"i64.load8_u":case"i64.load16_s":case"i64.load16_u":case"i64.load32_s":case"i64.load32_u":case"i32.store":case"i64.store":case"f32.store":case"f64.store":case"i32.store8":case"i32.store16":case"i64.store8":case"i64.store16":case"i64.store32":let l=t[0],m=t[1],u=[];return m!==0&&u.push(`offset=${m}`),l!==void 0&&u.push(`align=${1<<l}`),`${s}${u.length>0?" "+u.join(" "):""}`;case"memory.size":case"memory.grow":return s;default:if(s.startsWith("v128.")){if(s.includes("load")||s.includes("store")){let f=t[0],g=t[1],d=[];return g!==0&&d.push(`offset=${g}`),f!==void 0&&d.push(`align=${1<<f}`),`${s}${d.length>0?" "+d.join(" "):""}`}if(s.includes("const")){let f=t.join(" ");return`${s} ${f}`}return s.includes("extract_lane")||s.includes("replace_lane")?`${s} ${t[0]}`:`${s}${t.length>0?" "+t.join(" "):""}`}return`${s}${t.length>0?" "+t.join(" "):""}`}}var it=globalThis.gpu,ke=globalThis.navigator?.gpu,F=class{constructor(e={}){this.config=e}device=null;queue=null;initialized=!1;buffers=new Map;async ensureInitialized(){if(!this.initialized)try{let e=await ke?.requestAdapter?.();if(!e)throw new w("No GPU adapter available","compilation","navigator.gpu.requestAdapter() returned null");if(this.device=await e.requestDevice?.(),!this.device)throw new w("Failed to request GPU device","compilation","adapter.requestDevice() returned null");this.queue=this.device.queue,this.initialized=!0}catch(e){throw e instanceof w?e:new w(`GPU initialization failed: ${e instanceof Error?e.message:String(e)}`,"compilation",String(e))}}createBuffer(e,r,t){if(!this.device)throw new w("Device not initialized","binding","Call ensureInitialized() first");let s=this.device.createBuffer({label:e,size:r.byteLength,usage:t});return this.queue.writeBuffer(s,0,r.buffer,r.byteOffset,r.byteLength),s}async readBuffer(e,r,t){if(!this.device||!this.queue)throw new w("Device not initialized","readback","Call ensureInitialized() first");let s=Math.max(4,Math.ceil(r/4)*4),i=this.device.createBuffer({size:s,usage:9}),a=this.device.createCommandEncoder();a.copyBufferToBuffer(e,0,i,0,Math.min(r,s)),this.queue.submit([a.finish()]);try{await i.mapAsync(1)}catch(m){throw i.destroy(),new w(`Failed to map staging buffer: ${m instanceof Error?m.message:String(m)}`,"readback",String(m))}let c=i.getMappedRange(),l;return t==="f32"?l=new Float32Array(new Uint8Array(c).buffer).slice():t==="i32"?l=new Int32Array(new Uint8Array(c).buffer).slice():l=new Uint32Array(new Uint8Array(c).buffer).slice(),i.unmap(),i.destroy(),{data:l,type:t}}async execute(e,r,t,s={}){let i=s.workgroupSize??[1,1,1],a=s.workgroupCount??[1,1,1],c=s.timeout??5e3;if(await this.ensureInitialized(),!this.device||!this.queue)throw new w("Device initialization failed","compilation");try{let l;try{let o=s.shaderLabel||"Gasm Compiler Compute Shader";l=this.device.createShaderModule({code:e,label:o});let p=await l.getCompilationInfo?.();if(p&&p.messages.length>0){let v=p.messages.filter($=>$.type==="error");if(v.length>0){let $=v.map(S=>`${S.message} at ${S.lineNum}:${S.linePos}`).join("; ");throw new w(`WGSL compilation failed: ${$}`,"compilation")}}}catch(o){throw o instanceof w?o:new w(`Failed to create shader module: ${o instanceof Error?o.message:String(o)}`,"compilation",String(o))}let m=[],u=0,f=new Map,g=Object.entries(r).sort((o,p)=>o[0]==="memory"?-1:p[0]==="memory"?1:o[0].localeCompare(p[0]));for(let[o,{data:p,type:v}]of g){let $=this.createBuffer(`input_${o}`,p,140);f.set(o,$),m.push({binding:u++,resource:{buffer:$}})}let d=new Map,y=new Map;for(let o of t){if(f.has(o)){let we=f.get(o),G=r[o];d.set(o,we),y.set(o,{size:G.data.byteLength,type:G.type});continue}let p=s.outputBuffers?.[o]??{type:"f32",size:1},v=p.size??1,$=v*4,S=this.device.createBuffer({label:`output_${o}`,size:$,usage:140}),C;p.type==="f32"?C=new Float32Array(v).fill(0):p.type==="i32"?C=new Int32Array(v).fill(0):C=new Uint32Array(v).fill(0),this.queue.writeBuffer(S,0,C.buffer,C.byteOffset,C.byteLength),d.set(o,S),y.set(o,{size:$,type:p.type}),m.push({binding:u++,resource:{buffer:S}})}let b=Object.keys(r).length,h=this.device.createBindGroupLayout({entries:m.map((o,p)=>{let v=p===0&&r.memory!==void 0,$=p>=b;return{binding:p,visibility:4,buffer:{type:!v&&!$?"read-only-storage":"storage"}}})}),I=this.device.createBindGroup({layout:h,entries:m}),x=this.device.createPipelineLayout({bindGroupLayouts:[h]}),R;try{R=this.device.createComputePipeline({layout:x,compute:{module:l,entryPoint:"main"}})}catch(o){throw new w(`Failed to create compute pipeline: ${o instanceof Error?o.message:String(o)}`,"binding",String(o))}try{let o=this.device.createCommandEncoder(),p=o.beginComputePass();p.setPipeline(R),p.setBindGroup(0,I),p.dispatchWorkgroups(a[0],a[1],a[2]),p.end(),this.queue.submit([o.finish()])}catch(o){throw new w(`Compute shader dispatch failed: ${o instanceof Error?o.message:String(o)}`,"dispatch",String(o))}let P={};try{for(let o of t){let p=d.get(o),v=y.get(o);if(!p||!v)throw new w(`Output buffer "${o}" not found`,"readback");P[o]=await this.readBuffer(p,v.size,v.type)}}catch(o){throw o instanceof w?o:new w(`Failed to read back results: ${o instanceof Error?o.message:String(o)}`,"readback",String(o))}finally{let o=new Set;f.forEach(p=>{p.destroy(),o.add(p)}),d.forEach(p=>{o.has(p)||p.destroy()})}return P}catch(l){throw l instanceof w?l:new w(`Unexpected error during execution: ${l instanceof Error?l.message:String(l)}`,"dispatch",String(l))}}async destroy(){this.buffers.forEach(e=>e.destroy()),this.buffers.clear(),this.device&&typeof this.device.destroy=="function"&&this.device.destroy(),this.device=null,this.queue=null,this.initialized=!1}};function V(n,e={}){let r=ce(n,e);return E(r.diagnostics),r}function We(n,e={}){let r,s=ce(n,e,i=>{r=i});if(!s.ok)return s;if(!r)throw new Error("Compiler succeeded without a validated Wasm module");return{...s,metadata:O(r,{options:e,dispatchInfo:s.dispatchInfo})}}function It(n,e={}){let r=K(n,e);if(r.errors.length>0){let s=Z();return s.advisories.push(...r.advisories),s.errors.push(...r.errors),{ok:!1,diagnostics:s}}let t=We(r.wasmBytes,r.compileOptions);return t.diagnostics.advisories.push(...r.advisories),t.ok?{...t,bindings:t.metadata.bindings,...r.mutableGlobalsInit?{mutableGlobalsInit:r.mutableGlobalsInit}:{}}:t}async function Pt(){await U()}async function De(n,e={}){let r=await Ee(n,e);return E(r.diagnostics),r}function ce(n,e,r){let t=X(n,e);if(!t.ok)return{ok:!1,diagnostics:k(t)};let s=ue(n);r?.(s);let i=k(t);return pe(i,s,e),{ok:!0,wgsl:me(t.wgsl,e,n,s),diagnostics:i,dispatchInfo:N(t.dispatchInfo)}}async function Ee(n,e){let t=(await U()).compile(n,e);if(!t.ok)return{ok:!1,diagnostics:k(t)};let s=ue(n),i=k(t);return pe(i,s,e),{ok:!0,wgsl:me(t.wgsl,e,n,s),diagnostics:i,dispatchInfo:N(t.dispatchInfo)}}function ue(n){let e=W(n);if(D(e))throw new Error(`Rust accepted a module the artifact adapter could not parse: ${e.message}`);return e}function pe(n,e,r){j(r)&&H(e,r)&&(n.warnings.some(t=>t.code==="WARN_WORKGROUP_SIZE_OVERRIDE")||n.warnings.push({severity:"warning",code:"WARN_WORKGROUP_SIZE_OVERRIDE",message:"CompileOptions.workgroupSize overrides gasm.workgroup_size custom-section declarations"}))}function me(n,e,r,t){let s=n;return s=_e(s,e,r,t),e.compilerMetadata&&(s=s.replace(/(\/\/ Generated: .*\n)/,`$1// Metadata: ${e.compilerMetadata}
3
+ `)),s}function _e(n,e,r,t){if(e.stripComments||e.releaseMode)return n;let i=ie(r,e.sourceMapping);if(!i)return n;let a=i.generateHeaderComment(),c=a?n.replace(/(\/\/ Generated: .*\n)/,`$1${a}
4
+ `):n,l=0;return c=c.replace(/^fn ([A-Za-z_][A-Za-z0-9_]*)\(/gm,(m,u)=>{let f=t.functions[l],g=i.commentForFunction(f?.index??l,u);if(l+=1,!g)return m;let d=e.sourceMapping==="minimal"?"":`
5
+ // [WAT] rust backend instruction mapping`;return`${g}${d}
6
+ ${m}`}),c}function Ct(n,e={}){let r=V(n,e);if(!r.ok){let t=r.diagnostics.errors[0];throw L(t?.message??"Compilation failed",{functionName:t?.functionName,instructionName:t?.code,code:t?.code})}return r.wgsl}async function At(n,e={}){let r=await De(n,e);if(!r.ok){let t=r.diagnostics.errors[0];throw L(t?.message??"Compilation failed",{functionName:t?.functionName,instructionName:t?.code,code:t?.code})}return r.wgsl}function ge(n,e){for(let r of n.warnings){let t=r.functionName?` (${r.functionName})`:"";console.error(`warning${t}: ${r.message}`)}if(e&&n.demotions.length>0){let r=new Map;for(let s of n.demotions)r.set(s.kind,(r.get(s.kind)??0)+1);let t=[...r.entries()].map(([s,i])=>`${s} (${i})`);console.error(`demotions: ${t.join(", ")}`)}}function Ge(n,e){return new Promise(r=>{let t=ze(n,e,{stdio:["ignore","pipe","pipe"]}),s="",i="";t.stdout.on("data",a=>{s+=String(a)}),t.stderr.on("data",a=>{i+=String(a)}),t.on("close",a=>{r({success:a===0,stdout:s,stderr:i})}),t.on("error",a=>{r({success:!1,stdout:s,stderr:`${i}
7
+ ${a.message}`})})})}async function Ve(n,e={}){let{output:r,verbose:t=!1,keepWasm:s=!1,optimize:i,minify:a=!1,denyF64Demotion:c=!1,allowI64Demotion:l=!1,warningsAsErrors:m=!1}=e;try{if(a&&i===!1)throw new Error("minify cannot be combined with optimize: false");t&&console.log(`[1/4] Validating input file: ${n}`);let u=fe(n);if(!(await de(u)).isFile())throw new Error(`Not a file: ${n}`);let g=u.endsWith(".wasm");!g&&!u.endsWith(".as")&&!u.endsWith(".ts")&&console.warn("Warning: Input file does not have .as, .ts, or .wasm extension");let d=u.replace(/\.(as|ts)$/,".wasm");if(g)t&&console.log("[2/4] Input is WASM, skipping compilation..."),d=u;else{t&&console.log("[2/4] Compiling AssemblyScript to WASM...");let x=await qe(),{success:R,stdout:P,stderr:o}=await Ge(x,[u,"-o",d]);if(!R)throw new Error(`AssemblyScript compilation failed:
8
+ ${o}`);t&&P&&console.log(P)}t&&console.log("[3/4] Reading WASM binary...");let y=await Ne(d);t&&(console.log(` WASM size: ${y.length} bytes`),console.log("[4/4] Compiling WASM to WGSL using Gasm..."));let b={};c&&(b.f64="deny"),l&&(b.i64="allow-lossy");let h=V(y,{optimize:a?!0:i??!1,minify:a,demotionPolicy:b,warningsAsErrors:m});if(ge(h.diagnostics,t),!h.ok){let x=h.diagnostics.errors[0];throw new Error(x?.message??"Compilation failed")}let I=h.wgsl;if(r){let x=fe(r),R=Fe(x);await Te(R,{recursive:!0}),await Oe(x,I,"utf-8"),console.log(t?`
9
+ \u2713 Successfully compiled to: ${x}`:`\u2713 Compiled to: ${r}`)}if(!s&&!g)try{await Ue(d),t&&console.log(" Cleaned up intermediate WASM file")}catch{}return I}catch(u){throw u instanceof Error?u:new Error(`Unknown error: ${String(u)}`)}}function Le(n,e={}){let{verbose:r=!1,optimize:t,minify:s=!1,denyF64Demotion:i=!1,allowI64Demotion:a=!1,warningsAsErrors:c=!1}=e;if(s&&t===!1)throw new Error("minify cannot be combined with optimize: false");let l={};i&&(l.f64="deny"),a&&(l.i64="allow-lossy");let m=V(n,{optimize:s?!0:t??!1,minify:s,demotionPolicy:l,warningsAsErrors:c});if(ge(m.diagnostics,r),!m.ok){let u=m.diagnostics.errors[0];throw new Error(u?.message??"Compilation failed")}return m.wgsl}async function qe(){let n=["node_modules/.bin/asc","./examples/node_modules/.bin/asc","../app/node_modules/.bin/asc","./node_modules/assemblyscript/bin/asc.js"];for(let e of n)try{if((await de(e)).isFile())return e}catch{}return"asc"}export{ee as a,te as b,ne as c,re as d,A as e,$e as f,ae as g,Re as h,Se as i,Be as j,Ie as k,F as l,Ve as m,Le as n,V as o,We as p,It as q,Pt as r,De as s,Ct as t,At as u};
@@ -0,0 +1 @@
1
+ function p(e,t){let n=new Error(e);return n.name="CompileError",t&&(n.functionName=t.functionName,n.instructionName=t.instructionName,n.offset=t.offset,n.code=t.code),n}function st(e){return e instanceof Error&&e.name==="CompileError"}var o={unreachable:0,nop:1,block:2,loop:3,if:4,else:5,end:11,br:12,br_if:13,br_table:14,return:15,call:16,call_indirect:17,drop:26,select:27,local_get:32,local_set:33,local_tee:34,global_get:35,global_set:36,i32_load:40,i64_load:41,f32_load:42,f64_load:43,i32_store:54,i64_store:55,f32_store:56,f64_store:57,memory_size:63,memory_grow:64,i32_const:65,i64_const:66,f32_const:67,f64_const:68,i32_eqz:69,i32_eq:70,i32_ne:71,i32_lt_s:72,i32_lt_u:73,i32_gt_s:74,i32_gt_u:75,i32_le_s:76,i32_le_u:77,i32_ge_s:78,i32_ge_u:79,i64_eqz:80,i64_eq:81,i64_ne:82,i64_lt_s:83,i64_lt_u:84,i64_gt_s:85,i64_gt_u:86,i64_le_s:87,i64_le_u:88,i64_ge_s:89,i64_ge_u:90,i32_add:106,i32_sub:107,i32_mul:108,i32_div_s:109,i32_div_u:110,i32_rem_s:111,i32_rem_u:112,i32_and:113,i32_or:114,i32_xor:115,i32_shl:116,i32_shr_s:117,i32_shr_u:118,i32_rotl:119,i32_rotr:120,i32_clz:103,i32_ctz:104,i32_popcnt:105,i64_add:124,i64_sub:125,i64_mul:126,i64_div_s:127,i64_div_u:128,i64_rem_s:129,i64_rem_u:130,i64_and:131,i64_or:132,i64_xor:133,i64_shl:134,i64_shr_s:135,i64_shr_u:136,i64_rotl:137,i64_rotr:138,i64_clz:121,i64_ctz:122,i64_popcnt:123,f32_abs:139,f32_neg:140,f32_ceil:141,f32_floor:142,f32_trunc:143,f32_nearest:144,f32_sqrt:145,f32_add:146,f32_sub:147,f32_mul:148,f32_div:149,f32_min:150,f32_max:151,f32_copysign:152,f32_eq:91,f32_ne:92,f32_lt:93,f32_gt:94,f32_le:95,f32_ge:96,f64_abs:153,f64_neg:154,f64_ceil:155,f64_floor:156,f64_trunc:157,f64_nearest:158,f64_sqrt:159,f64_add:160,f64_sub:161,f64_mul:162,f64_div:163,f64_min:164,f64_max:165,f64_copysign:166,f64_eq:97,f64_ne:98,f64_lt:99,f64_gt:100,f64_le:101,f64_ge:102,i32_load8_s:44,i32_load8_u:45,i32_load16_s:46,i32_load16_u:47,i32_store8:58,i32_store16:59,i64_load8_s:48,i64_load8_u:49,i64_load16_s:50,i64_load16_u:51,i64_load32_s:52,i64_load32_u:53,i64_store8:60,i64_store16:61,i64_store32:62,i32_wrap_i64:167,i32_trunc_f32_s:168,i32_trunc_f32_u:169,i32_trunc_f64_s:170,i32_trunc_f64_u:171,i64_extend_i32_s:172,i64_extend_i32_u:173,i64_trunc_f32_s:174,i64_trunc_f32_u:175,i64_trunc_f64_s:176,i64_trunc_f64_u:177,f32_convert_i32_s:178,f32_convert_i32_u:179,f32_convert_i64_s:180,f32_convert_i64_u:181,f32_demote_f64:182,f64_convert_i32_s:183,f64_convert_i32_u:184,f64_convert_i64_s:185,f64_convert_i64_u:186,f64_promote_f32:187,i32_reinterpret_f32:188,i64_reinterpret_f64:189,f32_reinterpret_i32:190,f64_reinterpret_i64:191,i32_extend8_s:192,i32_extend16_s:193,i64_extend8_s:194,i64_extend16_s:195,i64_extend32_s:196,i32_trunc_sat_f32_s:64512,i32_trunc_sat_f32_u:64513,i32_trunc_sat_f64_s:64514,i32_trunc_sat_f64_u:64515,i64_trunc_sat_f32_s:64516,i64_trunc_sat_f32_u:64517,i64_trunc_sat_f64_s:64518,i64_trunc_sat_f64_u:64519,memory_init:64520,data_drop:64521,memory_copy:64522,memory_fill:64523,table_init:64524,elem_drop:64525,table_copy:64526,table_grow:64527,table_size:64528,table_fill:64529,atomic_fence:65027,i32_atomic_load:65040,i64_atomic_load:65041,i32_atomic_store:65047,v128_const:12,i8x16_splat:13,i16x8_splat:14,i32x4_splat:15,i64x2_splat:16,f32x4_splat:17,f64x2_splat:18,i8x16_extract_lane_s:21,i8x16_extract_lane_u:22,i8x16_replace_lane:23,i16x8_extract_lane_s:24,i16x8_extract_lane_u:25,i16x8_replace_lane:26,i32x4_extract_lane:27,i32x4_replace_lane:28,i64x2_extract_lane:29,i64x2_replace_lane:30,f32x4_extract_lane:31,f32x4_replace_lane:32,f64x2_extract_lane:33,f64x2_replace_lane:34,i8x16_add:35,i8x16_sub:36,i16x8_add:37,i16x8_sub:38,i16x8_mul:39,i32x4_add:40,i32x4_sub:41,i32x4_mul:42,i64x2_add:43,i64x2_sub:44,i64x2_mul:45,f32x4_add:46,f32x4_sub:47,f32x4_mul:48,f32x4_div:49,f64x2_add:50,f64x2_sub:51,f64x2_mul:52,f64x2_div:53,i32x4_eq:54,i32x4_ne:55,i32x4_lt_s:56,i32x4_lt_u:57,i32x4_gt_s:58,i32x4_gt_u:59,i32x4_le_s:60,i32x4_le_u:61,i32x4_ge_s:62,i32x4_ge_u:63,f32x4_eq:64,f32x4_ne:65,f32x4_lt:66,f32x4_gt:67,f32x4_le:68,f32x4_ge:69,f64x2_eq:70,f64x2_ne:71,f64x2_lt:72,f64x2_gt:73,f64x2_le:74,f64x2_ge:75,i8x16_eq:76,i8x16_ne:77,i16x8_eq:78,i16x8_ne:79,i64x2_eq:80,i64x2_ne:81,v128_and:82,v128_or:83,v128_xor:84,v128_not:85,v128_andnot:86,v128_bitselect:87,i8x16_shl:88,i8x16_shr_s:89,i8x16_shr_u:90,i16x8_shl:91,i16x8_shr_s:92,i16x8_shr_u:93,i32x4_shl:94,i32x4_shr_s:95,i32x4_shr_u:96,i64x2_shl:97,i64x2_shr_s:98,i64x2_shr_u:99,v128_any_true:100,i8x16_all_true:101,i8x16_bitmask:102,i16x8_all_true:103,i16x8_bitmask:104,i32x4_all_true:105,i32x4_bitmask:106,i64x2_all_true:107,i64x2_bitmask:108,i8x16_shuffle:109,i8x16_swizzle:110,f32x4_abs:111,f32x4_neg:112,f32x4_sqrt:113,f32x4_ceil:114,f32x4_floor:115,f32x4_trunc:116,f32x4_nearest:117,f32x4_min:118,f32x4_max:119,f64x2_abs:120,f64x2_neg:121,f64x2_sqrt:122,f64x2_ceil:123,f64x2_floor:124,f64x2_trunc:125,f64x2_nearest:126,f64x2_min:127,f64x2_max:128,v128_load:0,v128_store:11};var f={ERR_MEMORY_COUNT:"ERR_MEMORY_COUNT",ERR_MEMORY_GROW:"ERR_MEMORY_GROW",ERR_TABLE_PRESENT:"ERR_TABLE_PRESENT",ERR_INDIRECT_CALL:"ERR_INDIRECT_CALL",ERR_START_FUNCTION:"ERR_START_FUNCTION",ERR_FUNCTION_IMPORT:"ERR_FUNCTION_IMPORT",ERR_NO_ENTRY_POINT:"ERR_NO_ENTRY_POINT",ERR_MUTABLE_GLOBAL:"ERR_MUTABLE_GLOBAL",ERR_MULTI_MEMORY:"ERR_MULTI_MEMORY",ERR_PASSIVE_SEGMENT:"ERR_PASSIVE_SEGMENT",ERR_WORKGROUP_MEMORY_SIZE:"ERR_WORKGROUP_MEMORY_SIZE",ERR_RECURSION:"ERR_RECURSION",ERR_NON_UNIFORM_BARRIER:"ERR_NON_UNIFORM_BARRIER",ERR_UNALIGNED_ACCESS:"ERR_UNALIGNED_ACCESS",ERR_OFFSET_OVERFLOW:"ERR_OFFSET_OVERFLOW",ERR_FUNCREF:"ERR_FUNCREF",ERR_EXTERNREF:"ERR_EXTERNREF",ERR_F64_DEMOTION_REQUIRED:"ERR_F64_DEMOTION_REQUIRED",ERR_ATOMIC_REGION_MISSING:"ERR_ATOMIC_REGION_MISSING",ERR_ATOMIC_REGION_UNALIGNED:"ERR_ATOMIC_REGION_UNALIGNED",ERR_ATOMIC_REGION_OVERFLOW:"ERR_ATOMIC_REGION_OVERFLOW",ERR_ATOMIC_REGION_UNKNOWN_ADDRESS:"ERR_ATOMIC_REGION_UNKNOWN_ADDRESS",ERR_UNSUPPORTED_INSTR:"ERR_UNSUPPORTED_INSTR",ERR_UNKNOWN_EXTENSION:"ERR_UNKNOWN_EXTENSION",ERR_DUPLICATE_EXTENSION:"ERR_DUPLICATE_EXTENSION",ERR_DUPLICATE_CUSTOM_SECTION:"ERR_DUPLICATE_CUSTOM_SECTION",ERR_DUPLICATE_WORKGROUP_SIZE:"ERR_DUPLICATE_WORKGROUP_SIZE",ERR_METADATA_SCHEMA:"ERR_METADATA_SCHEMA",ERR_PARSE:"ERR_PARSE",ERR_VALIDATION:"ERR_VALIDATION"},at=new Set([f.ERR_MEMORY_COUNT,f.ERR_MEMORY_GROW,f.ERR_TABLE_PRESENT,f.ERR_INDIRECT_CALL,f.ERR_START_FUNCTION,f.ERR_FUNCTION_IMPORT,f.ERR_NO_ENTRY_POINT,f.ERR_MUTABLE_GLOBAL,f.ERR_MULTI_MEMORY,f.ERR_PASSIVE_SEGMENT,f.ERR_WORKGROUP_MEMORY_SIZE,f.ERR_RECURSION,f.ERR_NON_UNIFORM_BARRIER,f.ERR_UNALIGNED_ACCESS,f.ERR_OFFSET_OVERFLOW,f.ERR_FUNCREF,f.ERR_EXTERNREF,f.ERR_F64_DEMOTION_REQUIRED,f.ERR_ATOMIC_REGION_MISSING,f.ERR_ATOMIC_REGION_UNALIGNED,f.ERR_ATOMIC_REGION_OVERFLOW,f.ERR_ATOMIC_REGION_UNKNOWN_ADDRESS,f.ERR_UNSUPPORTED_INSTR,f.ERR_UNKNOWN_EXTENSION,f.ERR_DUPLICATE_EXTENSION,f.ERR_DUPLICATE_CUSTOM_SECTION,f.ERR_DUPLICATE_WORKGROUP_SIZE,f.ERR_METADATA_SCHEMA]);var ee=new Set(["gasm:simd:1.0","gasm:relaxed-simd:1.0","gasm:atomics:1.0","gasm:sign-extension:1.0","gasm:nontrapping-fptoint:1.0","gasm:multi-value:1.0","gasm:math:1.0","gasm:demote-f64:1.0","gasm:relaxed-fp-minmax:1.0","gasm:bulk-memory:1.0","gasm:mutable-globals:1.0","gasm:workgroup-memory:1.0"]),T=class{constructor(t){this.bytes=t}offset=0;get done(){return this.offset>=this.bytes.length}readUleb(){let t=0,n=0;for(;this.offset<this.bytes.length;){let i=this.bytes[this.offset++];if(t|=(i&127)<<n,(i&128)===0)return t>>>0;if(n+=7,n>35)throw new Error("ULEB128 value is too large")}throw new Error("Unexpected end of custom section")}readString(){let t=this.readUleb();if(this.offset+t>this.bytes.length)throw new Error("Unexpected end of custom section string");let n=this.bytes.slice(this.offset,this.offset+t);return this.offset+=t,new TextDecoder().decode(n)}};function A(e){let t=[],n=[],i=new Map,r,s=!1,a=!1;for(let c of e??[])try{if(c.name==="gasm.extensions"){if(s){t.push({code:f.ERR_DUPLICATE_CUSTOM_SECTION,message:"Duplicate gasm.extensions custom section"});continue}s=!0,te(c.data,n,t)}else if(c.name==="gasm.workgroup_size")ne(c.data,i,t);else if(c.name==="gasm.atomic_region"){if(a){t.push({code:f.ERR_DUPLICATE_CUSTOM_SECTION,message:"Duplicate gasm.atomic_region custom section"});continue}a=!0,r=oe(c.data,t)}}catch(m){t.push({code:f.ERR_PARSE,message:m instanceof Error?m.message:String(m)})}return{extensions:n,workgroupSizes:i,atomicRegion:r,diagnostics:t}}function G(e){let t=A(e.customSections);e.extensions=t.extensions,e.workgroupSizes=t.workgroupSizes,e.atomicRegion=t.atomicRegion}function W(e,t){if(e.length<8||e[0]!==0||e[1]!==97||e[2]!==115||e[3]!==109)throw new Error("Invalid WebAssembly header");let n=[...new Set(t)].sort(),i=[...e.subarray(0,8)],r=8;for(;r<e.length;){let s=r,a=e[r++],c=P(e,r);r=c.nextOffset;let m=r,d=m+c.value;if(d>e.length)throw new Error("WebAssembly section exceeds module length");let _=!1;if(a===0){let l=P(e,m),u=l.nextOffset,g=u+l.value;if(g>d)throw new Error("WebAssembly custom section name exceeds section");_=new TextDecoder().decode(e.subarray(u,g))==="gasm.extensions"}_||i.push(...e.subarray(s,d)),r=d}if(n.length>0){let s=B("gasm.extensions"),a=n.flatMap(B),c=[...s,...a];i.push(0,...L(c.length),...c)}return new Uint8Array(i)}function te(e,t,n){let i=new T(e),r=new Set;for(;!i.done;){let s=i.readString();if(r.has(s)){n.push({code:f.ERR_DUPLICATE_EXTENSION,message:`Duplicate extension declaration: ${s}`});continue}r.add(s),t.push(s),ee.has(s)||n.push({code:f.ERR_UNKNOWN_EXTENSION,message:`Unknown Gasm extension: ${s}`})}}function P(e,t){let n=0,i=0,r=t;for(;r<e.length;){let s=e[r++];if(n|=(s&127)<<i,(s&128)===0)return{value:n>>>0,nextOffset:r};if(i+=7,i>35)throw new Error("ULEB128 value is too large")}throw new Error("Unexpected end of WebAssembly module")}function L(e){let t=[];do{let n=e&127;e>>>=7,e!==0&&(n|=128),t.push(n)}while(e!==0);return t}function B(e){let t=new TextEncoder().encode(e);return[...L(t.length),...t]}function ne(e,t,n){let i=new T(e);for(;!i.done;){let r=i.readUleb(),s=i.readUleb(),a=i.readUleb(),c=i.readUleb();if(t.has(r)){n.push({code:f.ERR_DUPLICATE_WORKGROUP_SIZE,message:`Duplicate gasm.workgroup_size entry for function ${r}`});continue}t.set(r,[s,a,c])}}function oe(e,t){let n=new T(e),i=n.readUleb(),r=n.readUleb(),s=n.readUleb();if(!n.done)throw new Error("Trailing bytes in gasm.atomic_region custom section");return(r%4!==0||s%4!==0)&&t.push({code:f.ERR_ATOMIC_REGION_UNALIGNED,message:"gasm.atomic_region offset and length must be 4-byte aligned"}),{memoryIndex:i,offset:r,length:s}}var F=class{view;offset=0;bytes;constructor(t){this.bytes=t,this.view=new DataView(t.buffer,t.byteOffset,t.byteLength)}get pos(){return this.offset}set pos(t){this.offset=t}get length(){return this.bytes.length}isEOF(){return this.offset>=this.bytes.length}readByte(){if(this.offset>=this.bytes.length)throw p("Unexpected EOF",{offset:this.offset});return this.bytes[this.offset++]}peekByte(){return this.bytes[this.offset]}readBytes(t){if(this.offset+t>this.bytes.length)throw p("Unexpected EOF",{offset:this.offset});let n=this.bytes.subarray(this.offset,this.offset+t);return this.offset+=t,n}readUint32(){let t=this.view.getUint32(this.offset,!0);return this.offset+=4,t}readF32(){let t=this.view.getFloat32(this.offset,!0);return this.offset+=4,t}readF64(){let t=this.view.getFloat64(this.offset,!0);return this.offset+=8,t}readVarUint32(){let t=0,n=0;for(;;){let i=this.readByte();if(t|=(i&127)<<n,(i&128)===0)break;n+=7}return t}readVarInt32(){let t=0,n=0,i;for(;i=this.readByte(),t|=(i&127)<<n,n+=7,(i&128)!==0;);return n<32&&(i&64)!==0&&(t|=-1<<n),t}readVarInt64(){let t=0n,n=0n,i;for(;i=this.readByte(),t|=BigInt(i&127)<<n,n+=7n,(i&128)!==0;);return n<64&&(i&64)!==0&&(t|=~0n<<n),t}readString(){let t=this.readVarUint32(),n=this.readBytes(t);return new TextDecoder("utf-8").decode(n)}readType(){let t=this.readByte();switch(t){case 127:return"i32";case 126:return"i64";case 125:return"f32";case 124:return"f64";case 123:return"v128";case 112:return"funcref";case 111:return"externref";case 64:return"void";default:throw p(`Unknown value type: 0x${t.toString(16)}`,{offset:this.offset-1})}}};function U(e){let t=new F(e);if(t.readByte()!==0||t.readByte()!==97||t.readByte()!==115||t.readByte()!==109)return p("Invalid magic bytes",{offset:0});if(t.readByte()!==1||t.readByte()!==0||t.readByte()!==0||t.readByte()!==0)return p("Unsupported Wasm version",{offset:4});let n={types:[],functions:[],globals:[],memories:[],data:[],exports:[],imports:[],customSections:[],hasTableSection:!1,hasElementSection:!1},i=[];for(;!t.isEOF();){let r=t.readByte(),s=t.readVarUint32(),a=t.pos+s;switch(r){case 0:try{let c=t.readString(),m=t.readBytes(a-t.pos),d={name:c,data:m};n.customSections.push(d)}catch{t.pos=a}break;case 1:{let c=t.readVarUint32();for(let m=0;m<c;m++){if(t.readByte()!==96)throw p("Expected 0x60 for func type",{offset:t.pos-1});let _=t.readVarUint32(),l=[];for(let E=0;E<_;E++)l.push(t.readType());let u=t.readVarUint32(),g=[];for(let E=0;E<u;E++)g.push(t.readType());n.types.push({params:l,results:g})}}break;case 2:{let c=t.readVarUint32();for(let m=0;m<c;m++){let d=t.readString(),_=t.readString(),l=t.readByte(),u={module:d,name:_,kind:"func"};switch(l){case 0:u.kind="func",u.typeIndex=t.readVarUint32();break;case 1:u.kind="table",t.readByte();{let E=t.readByte();t.readVarUint32(),E&1&&t.readVarUint32()}break;case 2:u.kind="mem";{let E=t.readByte();u.memoryMin=t.readVarUint32(),E&1&&(u.memoryMax=t.readVarUint32())}break;case 3:u.kind="global",u.globalType=t.readType(),u.globalMutable=t.readByte()===1;let g=n.globals.length;n.globals.push({kind:"import",index:g,module:d,name:_,type:u.globalType,mutable:u.globalMutable});break}n.imports.push(u)}}break;case 3:{let c=t.readVarUint32();for(let m=0;m<c;m++)i.push(t.readVarUint32())}break;case 4:n.hasTableSection=!0,t.pos=a;break;case 5:{let c=t.readVarUint32();for(let m=0;m<c;m++){let d=t.readByte(),_=t.readVarUint32(),l=d&1?t.readVarUint32():void 0;n.memories.push({index:m,min:_,max:l})}}break;case 6:{let c=t.readVarUint32();for(let m=0;m<c;m++){let d=t.readType(),_=t.readByte()===1,l=w(t),u=n.globals.length,g;if(l.length>=1){let E=l[0];(E.opcode===o.i32_const||E.opcode===o.f32_const||E.opcode===o.i64_const||E.opcode===o.f64_const)&&(g=E.immediates?.[0])}n.globals.push({kind:"definition",index:u,type:d,mutable:_,initExpr:l,initValue:g})}}break;case 7:{let c=t.readVarUint32();for(let m=0;m<c;m++){let d=t.readString(),_=t.readByte(),l=t.readVarUint32(),u;switch(_){case 0:u="func";break;case 1:u="table";break;case 2:u="mem";break;case 3:u="global";break;default:throw p("Unknown export kind",{offset:t.pos})}n.exports.push({name:d,kind:u,index:l})}}break;case 8:{let c=t.readVarUint32();n.startFunctionIndex=c}break;case 9:n.hasElementSection=!0,t.pos=a;break;case 10:{let c=t.readVarUint32();i.length;for(let m=0;m<c;m++){let d=t.readVarUint32(),_=t.pos+d,l=i[m],u=n.types[l],g=t.readVarUint32(),E=[],x=0;for(let y=0;y<g;y++){let S=t.readVarUint32(),b=t.readType();for(let M=0;M<S;M++)E.push({index:x++,type:b,mutable:!0})}let h=w(t);n.functions.push({index:n.imports.filter(y=>y.kind==="func").length+m,params:u.params,results:u.results,locals:E,body:h}),t.pos!==_&&(t.pos=_)}}break;case 11:{let c=t.readVarUint32();for(let m=0;m<c;m++){let d=t.readVarUint32(),_="active",l=0,u=[];if(d===0)u=w(t);else if(d===1)_="passive";else if(d===2)l=t.readVarUint32(),u=w(t);else return p(`Unsupported data segment mode: ${d}`,{offset:t.pos});let g=t.readVarUint32(),E=t.readBytes(g);n.data.push({mode:_,memoryIndex:l,offset:u,data:E})}}break;default:t.pos=a;break}}return G(n),n}function w(e){let t=[],n=0;for(;;){let i=e.pos,r=e.readByte(),s,a={opcode:r,name:"",offset:i,immediates:[]},c=!1,m,d=!1,_=!1;if(r===253){let l=e.pos,u=e.readByte();(u&128)!==0&&e.peekByte()!==253&&e.peekByte()!==252?(e.pos=l,m=e.readVarUint32()):m=u,r=m<=255?64768|m:253<<16|m,a.opcode=r,c=!0}else r===252?(r=64512|e.readVarUint32(),a.opcode=r,d=!0):r===254&&(r=65024|e.readVarUint32(),a.opcode=r,_=!0);if(s=ie(r),a.name=s,r===o.block||r===o.loop||r===o.if)n++;else if(r===11){if(n===0){t.push(a);break}n--}switch(r){case o.block:case o.loop:case o.if:{let l=e.readByte();a.immediates.push(l)}break;case o.br:case o.br_if:a.immediates.push(e.readVarUint32());break;case o.br_table:{let l=e.readVarUint32(),u=[];for(let g=0;g<l;g++)u.push(e.readVarUint32());u.push(e.readVarUint32()),a.immediates.push(u)}break;case o.call:case o.call_indirect:a.immediates.push(e.readVarUint32()),r===o.call_indirect&&a.immediates.push(e.readVarUint32());break;case o.local_get:case o.local_set:case o.local_tee:case o.global_get:case o.global_set:a.immediates.push(e.readVarUint32());break;case o.i32_const:a.immediates.push(e.readVarInt32());break;case o.i64_const:a.immediates.push(e.readVarInt64());break;case o.f32_const:a.immediates.push(e.readF32());break;case o.f64_const:a.immediates.push(e.readF64());break;case o.i32_load:case o.i64_load:case o.f32_load:case o.f64_load:case o.i32_load8_s:case o.i32_load8_u:case o.i32_load16_s:case o.i32_load16_u:case o.i64_load8_s:case o.i64_load8_u:case o.i64_load16_s:case o.i64_load16_u:case o.i64_load32_s:case o.i64_load32_u:case o.i32_store:case o.i64_store:case o.f32_store:case o.f64_store:case o.i32_store8:case o.i32_store16:case o.i64_store8:case o.i64_store16:case o.i64_store32:{let l=e.readVarUint32(),u=0;l>=64&&l<128&&(l-=64,u=e.readVarUint32()),a.immediates.push(l),a.immediates.push(e.readVarUint32()),u!==0&&a.immediates.push(u)}break;case 63:case 64:e.readByte();break}if(c)switch(m){case 12:a.immediates.push(Array.from(e.readBytes(16)));break;case 21:case 22:case 23:case 24:case 25:case 26:case 27:case 28:case 29:case 30:case 31:case 32:case 33:case 34:a.immediates.push(e.readByte());break;case 13:a.immediates.push(Array.from(e.readBytes(16)));break;case 0:a.immediates.push(e.readVarUint32()),a.immediates.push(e.readVarUint32());break;case 11:a.immediates.push(e.readVarUint32()),a.immediates.push(e.readVarUint32());break}if(d){let l=r&255;switch(r){case o.memory_init:a.immediates.push(e.readVarUint32()),e.readByte();break;case o.data_drop:a.immediates.push(e.readVarUint32());break;case o.memory_copy:e.readByte(),e.readByte();break;case o.memory_fill:e.readByte();break;case o.table_init:a.immediates.push(e.readVarUint32()),a.immediates.push(e.readVarUint32());break;case o.elem_drop:a.immediates.push(e.readVarUint32());break;case o.table_copy:a.immediates.push(e.readVarUint32()),a.immediates.push(e.readVarUint32());break;case o.table_grow:case o.table_size:case o.table_fill:a.immediates.push(e.readVarUint32());break}}if(_){let l=r&255;l>=16&&l<=78&&(a.immediates.push(e.readVarUint32()),a.immediates.push(e.readVarUint32()))}t.push(a)}return t}function k(e){return e?.name==="CompileError"}function ie(e){let t=Object.entries(o).find(([,n])=>n===e);return t?t[0]:`0x${e.toString(16)}`}var Ot="0.1",Nt="0.2",Mt="0.2",se;function O(e){return e?.specVersion??se??"0.2"}function $(e){return O(e)==="0.2"}function v(){return{advisories:[],warnings:[],errors:[],demotions:[],featuresUsed:{usesF64:!1,usesI64:!1,usesF64Memory:!1,usesI64Memory:!1,usesSimdF64x2:!1,usesSimdI64x2:!1,usesSimdEmulation:!1}}}function Tt(e){for(let t of[...e.advisories,...e.warnings,...e.errors])t.recovery??=ae(t);return e}function re(){return{f64:"allow",i64:"deny"}}function z(e){let t=re(),n=e?.demotionPolicy;return{f64:n?.f64??t.f64,i64:n?.i64??t.i64}}function ae(e){switch(e.code){case"ERR_F64_DEMOTION_REQUIRED":return{action:"add_extension",extension:"gasm:demote-f64:1.0"};case"ERR_MUTABLE_GLOBAL":return e.message.toLowerCase().includes("imported")?{action:"refactor_source"}:{action:"add_extension",extension:"gasm:mutable-globals:1.0"};case"ERR_SIMD_EXTENSION_REQUIRED":return{action:"add_extension",extension:"gasm:simd:1.0"};case"ERR_RELAXED_SIMD_EXTENSION_REQUIRED":return{action:"add_extension",extension:"gasm:relaxed-simd:1.0"};case"ERR_PASSIVE_SEGMENT":return{action:"add_extension",extension:"gasm:bulk-memory:1.0"};case"ERR_F64_DEMOTION_DENIED":return{action:"set_demotion_policy",demotionPolicy:{f64:"allow"}};case"ERR_I64_UNSUPPORTED":case"ERR_I64_MEMORY_UNSUPPORTED":case"ERR_I64_CONST_OUT_OF_RANGE":return{action:"set_demotion_policy",demotionPolicy:{i64:"allow-lossy"}};default:return}}function wt(e){return e?{workItemsX:e.workItemsX,workItemsY:e.workItemsY,workItemsZ:e.workItemsZ,workgroupSizeX:e.workgroupSizeX,workgroupSizeY:e.workgroupSizeY,workgroupSizeZ:e.workgroupSizeZ,isParallelized:e.isParallelized}:{workItemsX:1,workItemsY:1,workItemsZ:1,workgroupSizeX:1,workgroupSizeY:1,workgroupSizeZ:1,isParallelized:!1}}function ce(e){let t=v();for(let n of e){let i={severity:n.severity,code:n.code,message:n.message,functionName:n.functionName??void 0};n.severity==="warning"?t.warnings.push(i):t.errors.push(i)}return t}function vt(e){let t=ce(e.diagnostics);return t.demotions.push(...(e.demotions??[]).map(n=>({kind:n.kind,functionIndex:n.functionIndex??void 0,functionName:n.functionName??void 0}))),e.featuresUsed&&(t.featuresUsed=e.featuresUsed),t}var me=new Set(["global_invocation_id_x","global_invocation_id_y","global_invocation_id_z","local_invocation_id_x","local_invocation_id_y","local_invocation_id_z","workgroup_id_x","workgroup_id_y","workgroup_id_z","num_workgroups_x","num_workgroups_y","num_workgroups_z"]);function C(e){let t=[{group:0,binding:0,kind:"storage",rw:"read_write",role:"memory",wgslName:"memory"}],n=1,i=0;for(let a of e.imports){if(a.kind!=="global")continue;let c=i++;a.module==="gasm"&&me.has(a.name)||t.push({group:0,binding:n++,kind:"uniform",role:"imported_global",wasmName:`${a.module}.${a.name}`,wgslName:`global_${c}`,type:de(a.globalType)})}return new Set(e.extensions??[]).has("gasm:mutable-globals:1.0")&&e.globals.some(a=>a.kind==="definition"&&a.mutable)&&t.push({group:0,binding:n++,kind:"storage",rw:"read_write",role:"mutable_globals",wgslName:"mutable_globals"}),e.atomicRegion&&t.push({group:0,binding:n++,kind:"storage",rw:"read_write",role:"atomic_region",wgslName:"atomic_region",atomic:!0}),ue(t),t}function ue(e){let t=new Set;for(let n of e){let i=`${n.group}:${n.binding}`;if(t.has(i))throw new Error(`Duplicate Gasm binding: ${i}`);t.add(i)}}function de(e){if(e==="i32"||e==="i64"||e==="f32"||e==="f64")return e;if(e==="v128")return"vec4<u32>"}function Pt(e,t={}){let n=C(e),i=n.find(d=>d.role==="atomic_region"),r=ye(e),s={specVersion:O(t.options),extensions:[...e.extensions??[]],memory:{sizeBytes:pe(e),atomicRegion:Ee(e.atomicRegion,i)},entryPoints:X(e).map(d=>({name:d.name,wgslName:fe(d.name),workgroupSize:_e(e,d.index,t)})),bindings:n,dataSegments:r.memorySegments},a=xe(e);a!==void 0&&(s.memory.workgroupMemoryBytes=a),r.atomicSegments.length>0&&(s.atomicDataSegments=r.atomicSegments);let c=e.data.map((d,_)=>({segment:d,index:_})).filter(({segment:d})=>d.mode==="passive").map(({segment:d,index:_})=>Se(d,_));c.length>0&&(s.passiveDataSegments=c);let m=ge(e);return m.length>0&&(s.mutableGlobals=m),s}function Bt(e){let t=[],n=I(e);if(!n)return{valid:!1,errors:["metadata must be an object"]};let i=["specVersion","extensions","memory","entryPoints","bindings","dataSegments"];for(let l of i)l in n||t.push(`missing required property: ${l}`);for(let l of Object.keys(n))[...i,"mutableGlobals","passiveDataSegments","atomicDataSegments","extras"].includes(l)||t.push(`unexpected property: ${l}`);n.specVersion!=="0.1"&&n.specVersion!=="0.2"&&t.push("specVersion must be 0.1 or 0.2"),Array.isArray(n.extensions)||t.push("extensions must be an array"),I(n.memory)||t.push("memory must be an object"),(!Array.isArray(n.entryPoints)||n.entryPoints.length===0)&&t.push("entryPoints must be a non-empty array"),Array.isArray(n.bindings)||t.push("bindings must be an array"),Array.isArray(n.dataSegments)||t.push("dataSegments must be an array");let r=Array.isArray(n.bindings)?n.bindings:[],s=new Set;for(let l of r){let u=I(l);if(!u){t.push("binding must be an object");continue}R(u.group)||t.push("binding.group invalid"),R(u.binding)||t.push("binding.binding invalid"),typeof u.kind!="string"&&t.push("binding.kind invalid"),typeof u.role!="string"&&t.push("binding.role invalid");let g=`${u.group}:${u.binding}`;s.has(g)&&t.push(`duplicate binding: ${g}`),s.add(g)}let a=Array.isArray(n.entryPoints)?n.entryPoints:[];for(let l of a){let u=I(l);if(!u){t.push("entryPoint must be an object");continue}(typeof u.name!="string"||u.name.length===0)&&t.push("entryPoint.name invalid"),(typeof u.wgslName!="string"||u.wgslName.length===0)&&t.push("entryPoint.wgslName invalid"),(!Array.isArray(u.workgroupSize)||u.workgroupSize.length!==3||!u.workgroupSize.every(g=>Oe(g)))&&t.push("entryPoint.workgroupSize invalid")}let c=I(n.memory);c&&!R(c.sizeBytes)&&t.push("memory.sizeBytes invalid"),c&&"workgroupMemoryBytes"in c&&!R(c.workgroupMemoryBytes)&&t.push("memory.workgroupMemoryBytes invalid");let m=Array.isArray(n.dataSegments)?n.dataSegments:[];for(let l of m){let u=I(l);if(!u){t.push("dataSegment must be an object");continue}R(u.memory)||t.push("dataSegment.memory invalid"),R(u.offset)||t.push("dataSegment.offset invalid"),R(u.byteLength)||t.push("dataSegment.byteLength invalid"),typeof u.dataB64!="string"&&t.push("dataSegment.dataB64 invalid")}let d=Array.isArray(n.passiveDataSegments)?n.passiveDataSegments:[];for(let l of d){let u=I(l);if(!u){t.push("passiveDataSegment must be an object");continue}R(u.index)||t.push("passiveDataSegment.index invalid"),R(u.byteLength)||t.push("passiveDataSegment.byteLength invalid"),typeof u.dataB64!="string"&&t.push("passiveDataSegment.dataB64 invalid"),typeof u.dropped!="boolean"&&t.push("passiveDataSegment.dropped invalid")}let _=Array.isArray(n.atomicDataSegments)?n.atomicDataSegments:[];for(let l of _){let u=I(l);if(!u){t.push("atomicDataSegment must be an object");continue}R(u.memory)||t.push("atomicDataSegment.memory invalid"),R(u.offset)||t.push("atomicDataSegment.offset invalid"),R(u.byteLength)||t.push("atomicDataSegment.byteLength invalid"),typeof u.dataB64!="string"&&t.push("atomicDataSegment.dataB64 invalid")}return t.length===0?{valid:!0}:{valid:!1,errors:t}}function Gt(e,t){let n=[...e.extensions??[]].sort(),i=[...t.extensions].sort();q(n,i,"extensions");for(let[r,s]of e.workgroupSizes??new Map){let a=X(e).find(m=>m.index===r);if(!a)continue;let c=t.entryPoints.find(m=>m.name===a.name);if(!c)throw new Error(`metadata missing entry point ${a.name}`);q(s,c.workgroupSize,"workgroupSize")}if(e.atomicRegion){let r=t.memory.atomicRegion;if(!r)throw new Error("metadata missing atomicRegion");Ne(e.atomicRegion,r)}}function X(e){return e.exports.filter(t=>{if(t.kind!=="func")return!1;let n=le(e,t.index);return!!n&&n.params.length===0&&n.results.length===0})}function fe(e){let t=Ie(e);return t==="main"?"main":`${t}_entry`}function Wt(e,t){return!!t.workgroupSize&&(e.workgroupSizes?.size??0)>0}function le(e,t){let n=e.imports.filter(r=>r.kind==="func");if(t<n.length){let r=n[t].typeIndex;return r===void 0?void 0:e.types[r]}let i=e.functions.find(r=>r.index===t);if(i)return{params:i.params,results:i.results}}function _e(e,t,n){if(n.options?.workgroupSize)return n.options.workgroupSize;let i=e.workgroupSizes?.get(t);if(i)return i;let r=n.dispatchInfo;return r?.isParallelized?[r.workgroupSizeX,r.workgroupSizeY,r.workgroupSizeZ]:O(n.options)==="0.2"?[64,1,1]:[1,1,1]}function pe(e){let t=e.memories[0];return t?t.min*65536:(e.imports.find(i=>i.kind==="mem"&&!(i.module==="gasm"&&i.name==="workgroup_memory"))?.memoryMin??0)*65536}function xe(e){if(!new Set(e.extensions??[]).has("gasm:workgroup-memory:1.0"))return;let n=e.imports.find(i=>i.kind==="mem"&&i.module==="gasm"&&i.name==="workgroup_memory");if(n)return n.memoryMax??n.memoryMin??0}function ge(e){if(!(e.extensions??[]).includes("gasm:mutable-globals:1.0"))return[];let t=[],n=0;for(let i of e.globals){if(i.kind!=="definition"||!i.mutable)continue;let r=be(i.type);t.push({index:i.index,type:i.type,offset:n,byteLength:r,...i.initValue!==void 0?{initialValue:i.initValue.toString()}:{}}),n+=r}return t}function be(e){return e==="i64"||e==="f64"?8:4}function Ee(e,t){return e?{offset:e.offset,length:e.length,binding:{group:t?.group??0,binding:t?.binding??0}}:null}function ye(e){let t=[],n=[];for(let i of e.data)i.mode==="active"&&Re(i,e.atomicRegion).forEach(r=>{r.atomic?n.push(r.metadata):t.push(r.metadata)});return{memorySegments:t,atomicSegments:n}}function Re(e,t){let n=he(e.offset);if(!t||e.memoryIndex!==t.memoryIndex)return[D(e,n,e.data,!1)];let i=n+e.data.length,r=t.offset,s=t.offset+t.length,a=[];if(n<Math.min(i,r)){let d=Math.min(i,r);a.push(D(e,n,e.data.subarray(0,d-n),!1))}let c=Math.max(n,r),m=Math.min(i,s);if(c<m&&a.push(D(e,c,e.data.subarray(c-n,m-n),!0)),Math.max(n,s)<i){let d=Math.max(n,s);a.push(D(e,d,e.data.subarray(d-n),!1))}return a.length===0&&a.push(D(e,n,e.data,!1)),a}function D(e,t,n,i){return{atomic:i,metadata:{memory:e.memoryIndex,offset:t,byteLength:n.length,dataB64:Y(n)}}}function Se(e,t){return{index:t,byteLength:e.data.length,dataB64:Y(e.data),dropped:!1}}function he(e){let n=e.find(i=>i.opcode===o.i32_const)?.immediates[0];return typeof n=="number"?n:0}function Y(e){let t="";for(let n of e)t+=String.fromCharCode(n);return btoa(t)}function Ie(e){let t="";for(let n=0;n<e.length;n++){let i=e[n],r=i==="_"||/[A-Za-z]/.test(i)||n>0&&/[0-9]/.test(i);t+=r?i:"_"}return(t.length===0||/^[0-9]/.test(t))&&(t=`_${t}`),t}function I(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)?e:void 0}function R(e){return Number.isInteger(e)&&e>=0}function Oe(e){return Number.isInteger(e)&&e>=1}function q(e,t,n){if(JSON.stringify(e)!==JSON.stringify(t))throw new Error(`${n} mismatch: ${JSON.stringify(e)} != ${JSON.stringify(t)}`)}function Ne(e,t){if(e.offset!==t.offset||e.length!==t.length)throw new Error("atomicRegion mismatch")}function K(e,t={}){try{if(t.strictConformance){let r=A(e.customSections).diagnostics;if(r.length>0){let x=r[0];throw p(x.message,{code:x.code})}let s=new Set(e.extensions??[]),a=s.has("gasm:workgroup-memory:1.0"),c=s.has("gasm:mutable-globals:1.0"),m=s.has("gasm:bulk-memory:1.0"),d=s.has("gasm:atomics:1.0"),_=s.has("gasm:demote-f64:1.0"),l=e.memories.length,u=0;for(let x of e.imports){if(x.kind!=="mem")continue;if(x.module==="gasm"&&x.name==="workgroup_memory"&&a){if(u++,(x.memoryMax??x.memoryMin??0)>16*1024)throw p("Imported workgroup memory exceeds the portable 16 KiB limit (M011: ERR_WORKGROUP_MEMORY_SIZE)",{code:f.ERR_WORKGROUP_MEMORY_SIZE})}else l++}if(l===0)throw p("Module must declare exactly one primary memory (M001: ERR_MEMORY_COUNT)",{code:f.ERR_MEMORY_COUNT});if(l>1)throw p("Module must not declare more than one primary memory (M009: ERR_MULTI_MEMORY)",{code:f.ERR_MULTI_MEMORY});if(u>1)throw p("Module must not declare more than one workgroup memory import (M009: ERR_MULTI_MEMORY)",{code:f.ERR_MULTI_MEMORY});if(Te(e,o.call_indirect))throw p("Invalid instruction: call_indirect",{code:f.ERR_INDIRECT_CALL});if(e.hasTableSection||e.hasElementSection||e.imports.some(x=>x.kind==="table")||e.exports.some(x=>x.kind==="table"))throw p("Tables and element segments are forbidden in Gasm v0.2 (M003: ERR_TABLE_PRESENT)",{code:f.ERR_TABLE_PRESENT});for(let x of e.imports)if(x.kind==="func"&&x.module!=="gasm")throw p(`Function import from "${x.module}" is forbidden; only "gasm" imports are allowed (M006: ERR_FUNCTION_IMPORT)`,{functionName:`${x.module}.${x.name}`,code:f.ERR_FUNCTION_IMPORT});for(let x of e.globals){if(x.kind==="import"&&x.mutable)throw p("Mutable imported globals are forbidden (M008: ERR_MUTABLE_GLOBAL)",{code:f.ERR_MUTABLE_GLOBAL});if(x.kind==="definition"&&x.mutable&&!c)throw p("Mutable globals require gasm:mutable-globals:1.0 (M008: ERR_MUTABLE_GLOBAL)",{code:f.ERR_MUTABLE_GLOBAL})}if(!m&&e.data.some(x=>x.mode==="passive"))throw p("Passive data segments require gasm:bulk-memory:1.0 (M010: ERR_PASSIVE_SEGMENT)",{code:f.ERR_PASSIVE_SEGMENT});Ae(e,d),Fe(e,_);let g=e.imports.filter(x=>x.kind==="func").length;if(!e.exports.some(x=>{if(x.kind!=="func")return!1;let h=x.index;if(h<g){let S=e.imports.filter(b=>b.kind==="func")[h];if(S?.typeIndex!==void 0){let b=e.types[S.typeIndex];return b&&b.params.length===0&&b.results.length===0}return!1}let y=e.functions.find(S=>S.index===h);return y?y.params.length===0&&y.results.length===0:!1}))throw p("Module must export at least one () -> () function as an entry point (M007: ERR_NO_ENTRY_POINT)",{code:f.ERR_NO_ENTRY_POINT})}let n=new Set(e.extensions??[]).has("gasm:bulk-memory:1.0"),i=new Set(e.extensions??[]).has("gasm:atomics:1.0");for(let r of e.functions)Me(e,r,n,i);if(Be(e),e.startFunctionIndex!==void 0)throw p("Start section not allowed",{functionName:"start",code:f.ERR_START_FUNCTION});return e}catch(n){if(V(n))return n;throw n}}function V(e){return e?.name==="CompileError"}function Me(e,t,n=!1,i=!1){let r=[];for(let s of t.body){let a=(s.opcode&65280)===64768;if(s.opcode===o.call_indirect)throw p("Invalid instruction: call_indirect",{functionName:t.name||`func${t.index}`,instructionName:s.name,offset:s.offset,code:f.ERR_INDIRECT_CALL});if(s.opcode===o.memory_grow)throw p(`Invalid instruction: ${s.name}`,{functionName:t.name||`func${t.index}`,instructionName:s.name,offset:s.offset,code:f.ERR_MEMORY_GROW});if(s.opcode>=208&&s.opcode<=210)throw p("Invalid instruction: Reference types not allowed",{functionName:t.name||`func${t.index}`,instructionName:s.name,offset:s.offset,code:f.ERR_UNSUPPORTED_INSTR});if(s.opcode===37||s.opcode===38)throw p("Invalid instruction: Table operations not allowed",{functionName:t.name||`func${t.index}`,instructionName:s.name,offset:s.offset,code:f.ERR_UNSUPPORTED_INSTR});if(ke(s.opcode,n))throw p(`Invalid instruction: ${s.name} not supported`,{functionName:t.name||`func${t.index}`,instructionName:s.name,offset:s.offset,code:f.ERR_UNSUPPORTED_INSTR});if(Ve(s.opcode)&&ve(e,t,s,r,i),Ue(s.opcode)){let c=s.immediates[0];if(![o.i32_load,o.i32_store,o.f32_load,o.f32_store,o.i64_load,o.i64_store,o.f64_load,o.f64_store,o.i32_load8_s,o.i32_load8_u,o.i32_load16_s,o.i32_load16_u,o.i32_store8,o.i32_store16,o.i64_load8_s,o.i64_load8_u,o.i64_load16_s,o.i64_load16_u,o.i64_load32_s,o.i64_load32_u,o.i64_store8,o.i64_store16,o.i64_store32].includes(s.opcode))throw p(`Invalid instruction: ${s.name} (only 32-bit and full 64-bit load/store allowed)`,{functionName:t.name||`func${t.index}`,instructionName:s.name,offset:s.offset,code:f.ERR_UNSUPPORTED_INSTR});let d=2;if([o.i32_load8_s,o.i32_load8_u,o.i32_store8,o.i64_load8_s,o.i64_load8_u,o.i64_store8].includes(s.opcode)?d=0:[o.i32_load16_s,o.i32_load16_u,o.i32_store16,o.i64_load16_s,o.i64_load16_u,o.i64_store16].includes(s.opcode)?d=1:[o.i64_load32_s,o.i64_load32_u,o.i64_store32].includes(s.opcode)?d=2:[o.i64_load,o.i64_store,o.f64_load,o.f64_store].includes(s.opcode)&&(d=3),c<d)throw p(`Misaligned memory access: ${s.name} (must be aligned)`,{functionName:t.name||`func${t.index}`,instructionName:s.name,offset:s.offset,code:f.ERR_UNALIGNED_ACCESS});let _=s.immediates[1],l=c>=32?2**32:2**c;if(_!==void 0&&_+l-1>4294967295)throw p(`Memory access offset plus alignment overflows u32: ${s.name} (A003: ERR_OFFSET_OVERFLOW)`,{functionName:t.name||`func${t.index}`,instructionName:s.name,offset:s.offset,code:f.ERR_OFFSET_OVERFLOW})}s.opcode,o.loop,we(r,s)}}function Te(e,t){return e.functions.some(n=>n.body.some(i=>i.opcode===t))}function Ae(e,t){if(!t)return;if(!e.atomicRegion)throw p("gasm:atomics:1.0 requires a gasm.atomic_region custom section",{code:f.ERR_ATOMIC_REGION_MISSING});let n=e.atomicRegion;if(n.offset%4!==0||n.length%4!==0)throw p("gasm.atomic_region offset and length must be 4-byte aligned",{code:f.ERR_ATOMIC_REGION_UNALIGNED});let i=(De(e,n.memoryIndex)??0)*65536;if(n.offset+n.length>i)throw p("gasm.atomic_region exceeds the declared memory minimum",{code:f.ERR_ATOMIC_REGION_OVERFLOW})}function De(e,t){let n=0;for(let i of e.imports)if(i.kind==="mem"){if(n===t)return i.module==="gasm"&&i.name==="workgroup_memory"?void 0:i.memoryMin;n++}for(let i of e.memories){if(n===t)return i.min;n++}}function we(e,t){switch(t.opcode){case o.i32_const:e.push(t.immediates[0]);return;case o.drop:e.pop();return;case o.i32_atomic_load:case o.i32_load:case o.i32_load8_s:case o.i32_load8_u:case o.i32_load16_s:case o.i32_load16_u:e.pop(),e.push(void 0);return;case o.i32_atomic_store:case o.i32_store:case o.i32_store8:case o.i32_store16:e.pop(),e.pop();return;case o.local_get:case o.global_get:e.push(void 0);return;case o.local_set:case o.global_set:e.pop();return;default:t.opcode===o.i32_eqz?(e.pop(),e.push(void 0)):(t.opcode>=o.i32_eq&&t.opcode<=o.i32_ge_u||t.opcode>=o.i32_add&&t.opcode<=o.i32_rotr)&&(e.pop(),e.pop(),e.push(void 0))}}function ve(e,t,n,i,r){if(!r||!Pe(n.opcode))throw p(`Invalid instruction: ${n.name} not supported`,{functionName:t.name||`func${t.index}`,instructionName:n.name,offset:n.offset,code:f.ERR_UNSUPPORTED_INSTR});if(!e.atomicRegion)throw p("Atomic instructions require a gasm.atomic_region custom section",{functionName:t.name||`func${t.index}`,instructionName:n.name,offset:n.offset,code:f.ERR_ATOMIC_REGION_MISSING});let s=Ce(n,i),a=n.immediates[1]??0;if(s===void 0)throw p("Atomic instruction address must resolve to the declared atomic region",{functionName:t.name||`func${t.index}`,instructionName:n.name,offset:n.offset,code:f.ERR_ATOMIC_REGION_UNKNOWN_ADDRESS});let c=s+a,m=e.atomicRegion;if(c<m.offset||c+4>m.offset+m.length)throw p("Atomic instruction address is outside the declared atomic region",{functionName:t.name||`func${t.index}`,instructionName:n.name,offset:n.offset,code:f.ERR_ATOMIC_REGION_UNKNOWN_ADDRESS})}function Ce(e,t){if(e.opcode===o.i32_atomic_load)return t.at(-1);if(e.opcode===o.i32_atomic_store)return t.at(-2)}function Fe(e,t){let n=i=>{if(i==="funcref")throw p("funcref is forbidden in Gasm v0.2 (T001: ERR_FUNCREF)",{code:f.ERR_FUNCREF});if(i==="externref")throw p("externref is forbidden in Gasm v0.2 (T002: ERR_EXTERNREF)",{code:f.ERR_EXTERNREF});if(i==="f64"&&!t)throw p("f64 requires gasm:demote-f64:1.0 in Gasm v0.2 (T003: ERR_F64_DEMOTION_REQUIRED)",{code:f.ERR_F64_DEMOTION_REQUIRED})};for(let i of e.types){for(let r of i.params)n(r);for(let r of i.results)n(r)}for(let i of e.imports)i.kind==="global"&&i.globalType&&n(i.globalType);for(let i of e.globals)n(i.type);for(let i of e.functions){for(let r of i.params)n(r);for(let r of i.results)n(r);for(let r of i.locals)n(r.type)}}function Ue(e){return e>=40&&e<=62}function ke(e,t){return(e&65280)!==64512||t&&e>=o.memory_init&&e<=o.memory_fill?!1:e>=o.memory_init}function Ve(e){return(e&65280)===65024}function Pe(e){return e===o.i32_atomic_load||e===o.i32_atomic_store}function Be(e){let t=new Map;for(let s of e.functions){let a=new Set;for(let c of s.body)if(c.opcode===o.call){let m=c.immediates[0];a.add(m)}t.set(s.index,a)}let n=new Set,i=new Set;function r(s){n.add(s),i.add(s);let a=t.get(s);if(a){for(let c of a)if(n.has(c)){if(i.has(c))return!0}else if(r(c))return!0}return i.delete(s),!1}for(let s of e.functions)if(!n.has(s.index)&&r(s.index))throw p("Recursion detected",{functionName:s.name||`func${s.index}`,code:f.ERR_RECURSION})}function N(e){return(e&65280)===64768}function Ge(e){return e&255}var We=new Set([o.f64_const,o.f64_abs,o.f64_neg,o.f64_ceil,o.f64_floor,o.f64_trunc,o.f64_nearest,o.f64_sqrt,o.f64_add,o.f64_sub,o.f64_mul,o.f64_div,o.f64_min,o.f64_max,o.f64_copysign,o.f64_eq,o.f64_ne,o.f64_lt,o.f64_gt,o.f64_le,o.f64_ge,o.i32_trunc_f64_s,o.i32_trunc_f64_u,o.i64_trunc_f64_s,o.i64_trunc_f64_u,o.i32_trunc_sat_f64_s,o.i32_trunc_sat_f64_u,o.i64_trunc_sat_f64_s,o.i64_trunc_sat_f64_u,o.f32_demote_f64,o.f64_convert_i32_s,o.f64_convert_i32_u,o.f64_convert_i64_s,o.f64_convert_i64_u,o.f64_promote_f32,o.i64_reinterpret_f64,o.f64_reinterpret_i64,o.f64_load,o.f64_store]),j=new Set([o.i64_const,o.i64_eqz,o.i64_eq,o.i64_ne,o.i64_lt_s,o.i64_lt_u,o.i64_gt_s,o.i64_gt_u,o.i64_le_s,o.i64_le_u,o.i64_ge_s,o.i64_ge_u,o.i64_add,o.i64_sub,o.i64_mul,o.i64_div_s,o.i64_div_u,o.i64_rem_s,o.i64_rem_u,o.i64_and,o.i64_or,o.i64_xor,o.i64_shl,o.i64_shr_s,o.i64_shr_u,o.i64_rotl,o.i64_rotr,o.i64_clz,o.i64_ctz,o.i64_popcnt,o.i64_extend_i32_s,o.i64_extend_i32_u,o.i64_trunc_f32_s,o.i64_trunc_f32_u,o.i64_trunc_f64_s,o.i64_trunc_f64_u,o.i64_trunc_sat_f32_s,o.i64_trunc_sat_f32_u,o.i64_trunc_sat_f64_s,o.i64_trunc_sat_f64_u,o.f32_convert_i64_s,o.f32_convert_i64_u,o.f64_convert_i64_s,o.f64_convert_i64_u,o.i64_reinterpret_f64,o.f64_reinterpret_i64,o.i32_wrap_i64,o.i64_load,o.i64_store]),Z=new Set([o.i64_load,o.i64_store,o.i64_load8_s,o.i64_load8_u,o.i64_load16_s,o.i64_load16_u,o.i64_load32_s,o.i64_load32_u,o.i64_store8,o.i64_store16,o.i64_store32]),Le=new Set([o.f64_load,o.f64_store]),$e=new Set([20,33,34,71,72,73,74,75,76,236,237,239,240,241,242,243,244,245,246,247]),ze=new Set([18,29,30,192,193,195,196,203,204,205,206,209,213,214,215,216,217,218,219]);function qe(e){let t=e.params.includes("i64")||e.results.includes("i64")||e.locals.some(c=>c.type==="i64"),n=t,i=!1,r=!1,s=!1,a=t;for(let c=0;c<e.body.length;c++){let m=e.body[c];if(!N(m.opcode)){if(m.opcode===o.i64_const){let d=e.body[c+1];if(d&&N(d.opcode))continue}if(Z.has(m.opcode)){n=!0,i=!0,a=!0;continue}if(j.has(m.opcode)&&(n=!0,a=!0,m.opcode===o.i64_const)){let d=m.immediates[0];typeof d=="bigint"&&(d<-2147483648n||d>2147483647n)&&(s=!0)}}}for(let c=0;c<e.body.length;c++){let m=e.body[c];if(N(m.opcode)||!j.has(m.opcode)&&!Z.has(m.opcode))continue;if(m.opcode===o.i64_const){let _=e.body[c+1];if(_&&N(_.opcode))continue}m.opcode===o.i64_const||m.opcode===o.i32_wrap_i64||(r=!0)}return{usesI64:n,usesI64Memory:i,usesI64ParamOrResultOrLocal:t,hasDisallowedI64Op:r,hasI64ConstOutOfRange:s,usesAnyScalarI64:a}}function Xe(e){let t=e.params.includes("f64")||e.results.includes("f64")||e.locals.some(s=>s.type==="f64"),n=t,i=!1,r=t;for(let s of e.body)if(!N(s.opcode)){if(Le.has(s.opcode)){n=!0,i=!0,r=!0;continue}We.has(s.opcode)&&(n=!0,r=!0)}return{usesF64:n,usesF64Memory:i,usesF64ParamOrResultOrLocal:t,usesAnyScalarF64:r}}function Ye(e){let t=!1,n=!1,i=!1;for(let r of e.body){if(!N(r.opcode))continue;let s=Ge(r.opcode);$e.has(s)&&(t=!0),ze.has(s)&&(n=!0)}return{usesSimdF64x2:t,usesSimdI64x2:n,usesSimdEmulation:i}}function Q(e,t){let n=v(),i=z(t),r=$(t),s=new Set,a=new Set;for(let c of e.functions){let m=c.index,d=c.name??`func_${m}`,_=qe(c),l=Xe(c),u=Ye(c);n.featuresUsed.usesI64||=_.usesI64,n.featuresUsed.usesI64Memory||=_.usesI64Memory,n.featuresUsed.usesF64||=l.usesF64,n.featuresUsed.usesF64Memory||=l.usesF64Memory,n.featuresUsed.usesSimdF64x2||=u.usesSimdF64x2,n.featuresUsed.usesSimdI64x2||=u.usesSimdI64x2,n.featuresUsed.usesSimdEmulation||=u.usesSimdEmulation,(l.usesF64||u.usesSimdF64x2)&&(l.usesF64Memory?n.errors.push({severity:"error",code:"ERR_F64_MEMORY_UNSUPPORTED",message:`Function ${d} uses f64 load/store; memory encoding for f64 is not defined.`,functionIndex:m,functionName:d}):i.f64==="deny"?n.errors.push({severity:"error",code:"ERR_F64_DEMOTION_DENIED",message:`Function ${d} uses f64; demotion to f32 is denied by policy.`,functionIndex:m,functionName:d}):s.has(m)||(n.warnings.push({severity:"warning",code:"WARN_F64_DEMOTED",message:`Function ${d} uses f64; lowering to f32 (precision loss).`,functionIndex:m,functionName:d}),n.demotions.push({kind:"f64->f32",functionIndex:m,functionName:d}),s.add(m))),!r&&(i.i64==="deny"?(_.usesI64Memory&&n.errors.push({severity:"error",code:"ERR_I64_MEMORY_UNSUPPORTED",message:`Function ${d} uses i64 load/store; memory encoding for i64 is not defined. Enable lossy i64 demotion to allow.`,functionIndex:m,functionName:d}),_.usesI64ParamOrResultOrLocal&&n.errors.push({severity:"error",code:"ERR_I64_UNSUPPORTED",message:`Function ${d} uses scalar i64 parameters/results/locals; i64 is unsupported by default.`,functionIndex:m,functionName:d}),_.hasI64ConstOutOfRange&&n.errors.push({severity:"error",code:"ERR_I64_CONST_OUT_OF_RANGE",message:`Function ${d} uses i64.const outside signed i32 range; enable lossy i64 demotion to allow.`,functionIndex:m,functionName:d}),_.hasDisallowedI64Op&&n.errors.push({severity:"error",code:"ERR_I64_UNSUPPORTED",message:`Function ${d} uses scalar i64 operations; enable lossy i64 demotion to allow.`,functionIndex:m,functionName:d})):_.usesAnyScalarI64&&(a.has(m)||(n.warnings.push({severity:"warning",code:"WARN_I64_DEMOTED_LOSSY",message:`Function ${d} uses i64; lowering to i32 (lossy, modulo 2^32). Shift operations are masked to 31 bits, changing semantics for shift amounts >= 32.`,functionIndex:m,functionName:d}),n.demotions.push({kind:"i64->i32-lossy",functionIndex:m,functionName:d}),a.add(m))))}if(t.warningsAsErrors&&n.warnings.length>0)for(let c of n.warnings)n.errors.push({severity:"error",code:"ERR_WARNINGS_AS_ERRORS",message:c.message,functionIndex:c.functionIndex,functionName:c.functionName});return{diagnostics:n,policy:i}}var Ke={f64:"allow",i64:"allow-lossy"},je={f64:"deny",i64:"deny"};function Sn(e,t={}){let n=t.mode??"integrator",i=n==="integrator"&&(t.patchWasm??!0),r=Ze(n,t),s=[],a=[],c=U(e);if(k(c))return a.push({severity:"error",code:c.code??f.ERR_PARSE,message:c.message,functionName:c.functionName,instructionName:c.instructionName,offset:c.offset}),it(e,r,s,a);let m=c;Je(m,a);let d=new Set(m.extensions??[]),_=m.globals.some(b=>b.kind==="definition"&&b.mutable);n==="integrator"&&r.specVersion==="0.2"&&_&&!d.has("gasm:mutable-globals:1.0")&&(r.specVersion="0.1",s.push({severity:"advisory",code:"GASM_ADVISORY_MUTABLE_GLOBALS_V01_COMPAT",message:'Mutable defined globals detected; selected specVersion "0.1" for per-invocation private semantics.',recovery:{action:"refactor_source"}}));let l=Qe(m,r),u=new Set(d);for(let b of l){if(u.add(b.extension),d.has(b.extension))continue;let M={action:"add_extension",extension:b.extension};n==="strict"?a.push({severity:"error",code:b.code,message:b.message,recovery:M}):s.push({severity:"advisory",code:"GASM_ADVISORY_EXTENSION_ADDED",message:`Added required extension ${b.extension}.`,recovery:M})}He(m,r,a);let g=[...u].sort(),E=e;if(i)try{E=W(e,g)}catch(b){a.push({severity:"error",code:f.ERR_PARSE,message:b instanceof Error?b.message:String(b)})}let x=m,h=n==="integrator"&&!i&&l.some(b=>!d.has(b.extension));if(i&&a.length===0){let b=U(E);k(b)?a.push({severity:"error",code:b.code??f.ERR_PARSE,message:b.message}):x=b}else x.extensions=g;if(a.length===0&&!h){let b=K(x,{strictConformance:r.specVersion==="0.2"||r.strictConformance});V(b)&&a.push({severity:"error",code:b.code??f.ERR_VALIDATION,message:b.message,functionName:b.functionName,instructionName:b.instructionName,offset:b.offset})}let y=C(x),S=y.some(b=>b.role==="mutable_globals")?ot(x):void 0;return{wasmBytes:E,compileOptions:r,bindings:y,...S?{mutableGlobalsInit:S}:{},extensions:g,advisories:s,errors:a}}function Ze(e,t){let{mode:n,patchWasm:i,...r}=t,s=e==="integrator"?Ke:je;return{...r,specVersion:t.specVersion??"0.2",demotionPolicy:{...s,...t.demotionPolicy}}}function Qe(e,t){if(t.specVersion!=="0.2")return[];let n=new Map,i=s=>{n.set(s.extension,s)},r=e.functions.flatMap(s=>s.body);return(J(e,"f64")||r.some(et))&&i({extension:"gasm:demote-f64:1.0",code:f.ERR_F64_DEMOTION_REQUIRED,message:"f64 usage requires gasm:demote-f64:1.0 in Gasm v0.2."}),e.globals.some(s=>s.kind==="definition"&&s.mutable)&&i({extension:"gasm:mutable-globals:1.0",code:f.ERR_MUTABLE_GLOBAL,message:"Mutable globals require gasm:mutable-globals:1.0 in Gasm v0.2."}),(J(e,"v128")||r.some(s=>tt(s.opcode)))&&i({extension:"gasm:simd:1.0",code:"ERR_SIMD_EXTENSION_REQUIRED",message:"SIMD usage requires gasm:simd:1.0 in Gasm v0.2."}),r.some(s=>nt(s.opcode))&&i({extension:"gasm:relaxed-simd:1.0",code:"ERR_RELAXED_SIMD_EXTENSION_REQUIRED",message:"Relaxed SIMD usage requires gasm:relaxed-simd:1.0 in Gasm v0.2."}),(e.data.some(s=>s.mode==="passive")||r.some(s=>s.opcode>=o.memory_init&&s.opcode<=o.memory_fill))&&i({extension:"gasm:bulk-memory:1.0",code:f.ERR_PASSIVE_SEGMENT,message:"Bulk memory usage requires gasm:bulk-memory:1.0."}),r.some(s=>(s.opcode&65280)===65024)&&i({extension:"gasm:atomics:1.0",code:f.ERR_UNSUPPORTED_INSTR,message:"Atomic instructions require gasm:atomics:1.0."}),e.imports.some(s=>s.kind==="mem"&&s.module==="gasm"&&s.name==="workgroup_memory")&&i({extension:"gasm:workgroup-memory:1.0",code:f.ERR_MULTI_MEMORY,message:"The gasm.workgroup_memory import requires gasm:workgroup-memory:1.0."}),t.mathExtension&&i({extension:"gasm:math:1.0",code:"ERR_MATH_EXTENSION_REQUIRED",message:"The math extension option requires gasm:math:1.0."}),r.some(s=>s.opcode>=o.i32_extend8_s&&s.opcode<=o.i64_extend32_s)&&i({extension:"gasm:sign-extension:1.0",code:"ERR_SIGN_EXTENSION_REQUIRED",message:"Sign-extension instructions require gasm:sign-extension:1.0."}),r.some(s=>s.opcode>=o.i32_trunc_sat_f32_s&&s.opcode<=o.i64_trunc_sat_f64_u)&&i({extension:"gasm:nontrapping-fptoint:1.0",code:"ERR_NONTRAPPING_FPTOINT_REQUIRED",message:"Non-trapping float-to-int instructions require gasm:nontrapping-fptoint:1.0."}),e.types.some(s=>s.results.length>1)&&i({extension:"gasm:multi-value:1.0",code:"ERR_MULTI_VALUE_EXTENSION_REQUIRED",message:"Multi-value function types require gasm:multi-value:1.0."}),[...n.values()].sort((s,a)=>s.extension.localeCompare(a.extension))}function Je(e,t){for(let n of A(e.customSections).diagnostics)t.push({severity:"error",code:n.code,message:n.message})}function He(e,t,n){let i=Q(e,t);for(let r of i.diagnostics.errors)n.push({...r,recovery:r.code==="ERR_F64_DEMOTION_DENIED"?{action:"set_demotion_policy",demotionPolicy:{f64:"allow"}}:r.code.startsWith("ERR_I64")?{action:"set_demotion_policy",demotionPolicy:{i64:"allow-lossy"}}:r.recovery})}function J(e,t){return e.types.some(n=>n.params.includes(t)||n.results.includes(t))||e.globals.some(n=>n.type===t)||e.functions.some(n=>n.params.includes(t)||n.results.includes(t)||n.locals.some(i=>i.type===t))}function et(e){return e.name.startsWith("f64.")||e.opcode===o.f32_demote_f64||e.opcode===o.f64_promote_f32||e.opcode===o.i32_trunc_f64_s||e.opcode===o.i32_trunc_f64_u||e.opcode===o.i64_trunc_f64_s||e.opcode===o.i64_trunc_f64_u||e.opcode===o.f64_convert_i32_s||e.opcode===o.f64_convert_i32_u||e.opcode===o.f64_convert_i64_s||e.opcode===o.f64_convert_i64_u}function tt(e){return(e&65280)===64768||e>>>16===253}function nt(e){return e>>>16===253&&(e&65535)>=256}function ot(e){let t=e.globals.filter(a=>a.kind==="definition"&&a.mutable);if(t.length===0)return;let n=t.reduce((a,c)=>a+H(c.type),0),i=new ArrayBuffer(n),r=new DataView(i),s=0;for(let a of t){let c=a.initValue??0;switch(a.type){case"i32":r.setInt32(s,Number(c),!0);break;case"f32":r.setFloat32(s,Number(c),!0);break;case"i64":r.setBigInt64(s,BigInt(c),!0);break;case"f64":r.setFloat64(s,Number(c),!0);break}s+=H(a.type)}return{byteLength:n,data:new Uint32Array(i)}}function H(e){return e==="i64"||e==="f64"?8:4}function it(e,t,n,i){return{wasmBytes:e,compileOptions:t,bindings:[],extensions:[],advisories:n,errors:i}}function On(e){let t=e.gasm_core_rs_version_major,n=e.gasm_core_rs_smoke_compile,i=e.gasm_core_rs_alloc,r=e.gasm_core_rs_dealloc,s=e.gasm_core_rs_compile,a=e.gasm_core_rs_result_ptr,c=e.gasm_core_rs_result_len,m=e.memory;if(typeof t!="function"||typeof n!="function"||typeof i!="function"||typeof r!="function"||typeof s!="function"||typeof a!="function"||typeof c!="function"||!(m instanceof WebAssembly.Memory))throw new Error("Invalid gasm-core-rs Wasm exports");let d=()=>{let _=a(),l=c(),u=new TextDecoder().decode(new Uint8Array(m.buffer,_,l));return JSON.parse(u)};return{versionMajor:()=>t(),smokeCompile:_=>n(_),compile:(_,l={})=>{let u=i(_.length),g=new TextEncoder().encode(JSON.stringify({abiVersion:1,options:{...l,specVersion:O(l)}})),E=i(g.length);try{return new Uint8Array(m.buffer,u,_.length).set(_),new Uint8Array(m.buffer,E,g.length).set(g),s(u,_.length,E,g.length),d()}finally{r(u,_.length),r(E,g.length)}}}}export{p as a,st as b,o as c,f as d,U as e,k as f,Ot as g,Nt as h,Mt as i,O as j,$ as k,v as l,Tt as m,On as n,wt as o,vt as p,C as q,Pt as r,Bt as s,Gt as t,fe as u,Wt as v,Sn as w};
@@ -10,6 +10,7 @@ interface CompileOptions {
10
10
  verbose?: boolean;
11
11
  keepWasm?: boolean;
12
12
  optimize?: boolean;
13
+ minify?: boolean;
13
14
  denyF64Demotion?: boolean;
14
15
  allowI64Demotion?: boolean;
15
16
  warningsAsErrors?: boolean;
package/dist/compiler.js CHANGED
@@ -1 +1 @@
1
- import{c as a,d as b}from"./chunk-TICBJF7F.js";import"./chunk-MBWDLAL5.js";import"./chunk-IZGS3OS2.js";import"./chunk-STDXBN5E.js";export{a as compileAssemblyScriptToWGSL,b as compileWasmToWGSL};
1
+ import{m as a,n as b}from"./chunk-63X76LAZ.js";import"./chunk-CYV3E4CZ.js";import"./chunk-IZGS3OS2.js";import"./chunk-STDXBN5E.js";export{a as compileAssemblyScriptToWGSL,b as compileWasmToWGSL};
@@ -336,6 +336,12 @@ declare function isV02Mode(options?: CompileOptions): boolean;
336
336
  interface CompileOptions {
337
337
  workgroupSize?: [number, number, number];
338
338
  optimize?: boolean;
339
+ /**
340
+ * Emit the smallest practical WGSL representation.
341
+ * Enables optimization and compact backend code generation.
342
+ * Cannot be combined with optimize: false, sourceMapping, or compilerMetadata.
343
+ */
344
+ minify?: boolean;
339
345
  verbose?: boolean;
340
346
  demotionPolicy?: Partial<DemotionPolicy>;
341
347
  warningsAsErrors?: boolean;
Binary file
package/dist/mod.d.ts CHANGED
@@ -1,5 +1,5 @@
1
- import { W as WasmModule, C as CompileDiagnostics, D as DispatchInfo, G as GasmMetadata, a as GasmBinding, P as PreparedModule, b as CompileOptions, c as PrepareModuleOptions } from './error_codes-5zCZDwFZ.js';
2
- export { d as CompileError, h as DEFAULT_SPEC_VERSION, K as DebugInfo, e as DemotionPolicy, f as Diagnostic, g as DiagnosticRecovery, o as ErrorCode, E as ErrorCodes, u as GasmMetadataEntryPoint, J as MATH_INTRINSICS, y as MathIntrinsicSpec, z as MathLevel, M as MutableGlobalsInit, x as PrepareMode, j as SPEC_VERSION_V01, k as SPEC_VERSION_V02, L as SourceLanguage, N as SourceMappingLevel, S as SpecVersion, V as VectorDimension, q as assertCustomSectionsAndMetadataAgree, w as buildBindingTable, s as buildGasmMetadata, O as detectSourceLanguage, t as entryWrapperName, Q as extractDebugInfo, A as getIntrinsicsAtLevel, B as getMathSpec, F as getVectorDimension, H as getWgslMapping, l as isCompileError, I as isMathIntrinsic, n as isParseError, i as isV02Mode, R as parseNamesSection, T as parseProducersSection, m as parseWasmModule, p as prepareModule, r as resolveSpecVersion, v as validateGasmMetadataSchema } from './error_codes-5zCZDwFZ.js';
1
+ import { W as WasmModule, C as CompileDiagnostics, D as DispatchInfo, G as GasmMetadata, a as GasmBinding, P as PreparedModule, b as CompileOptions, c as PrepareModuleOptions } from './error_codes-xePrg-T0.js';
2
+ export { d as CompileError, h as DEFAULT_SPEC_VERSION, K as DebugInfo, e as DemotionPolicy, f as Diagnostic, g as DiagnosticRecovery, o as ErrorCode, E as ErrorCodes, u as GasmMetadataEntryPoint, J as MATH_INTRINSICS, y as MathIntrinsicSpec, z as MathLevel, M as MutableGlobalsInit, x as PrepareMode, j as SPEC_VERSION_V01, k as SPEC_VERSION_V02, L as SourceLanguage, N as SourceMappingLevel, S as SpecVersion, V as VectorDimension, q as assertCustomSectionsAndMetadataAgree, w as buildBindingTable, s as buildGasmMetadata, O as detectSourceLanguage, t as entryWrapperName, Q as extractDebugInfo, A as getIntrinsicsAtLevel, B as getMathSpec, F as getVectorDimension, H as getWgslMapping, l as isCompileError, I as isMathIntrinsic, n as isParseError, i as isV02Mode, R as parseNamesSection, T as parseProducersSection, m as parseWasmModule, p as prepareModule, r as resolveSpecVersion, v as validateGasmMetadataSchema } from './error_codes-xePrg-T0.js';
3
3
  import { IGPUExecutor, ExecutorConfig, BufferData, ExecuteOptions } from './executor.js';
4
4
  export { ExecutionError, OutputBufferSpec, isExecutionError } from './executor.js';
5
5
  export { BrowserGPUExecutor } from './browser-executor.js';
package/dist/mod.js CHANGED
@@ -1 +1 @@
1
- import{a as z,b as D,c as E,d as F,e as G,f as H,g as I,h as J,i as K,j as L,k as M}from"./chunk-TICBJF7F.js";import{D as o,E as p,F as q,G as r,H as s,O as t,P as u,Q as v,R as w,S as x,U as y,b as a,d as b,e as c,f as d,i as e,j as f,k as g,l as h,m as i,o as j,u as k,v as l,w as m,x as n}from"./chunk-MBWDLAL5.js";import{a as C}from"./chunk-IZGS3OS2.js";import{a as A,b as B}from"./chunk-STDXBN5E.js";export{C as BrowserGPUExecutor,q as DEFAULT_SPEC_VERSION,D as DenoGPUExecutor,b as ErrorCodes,A as ExecutionError,e as MATH_INTRINSICS,o as SPEC_VERSION_V01,p as SPEC_VERSION_V02,w as assertCustomSectionsAndMetadataAgree,t as buildBindingTable,u as buildGasmMetadata,L as compile,E as compileAssemblyScriptToWGSL,M as compileAsync,H as compileToArtifact,F as compileWasmToWGSL,G as compileWithDiagnostics,K as compileWithDiagnosticsAsync,I as compileWithRuntimeInfo,m as detectSourceLanguage,z as disassembleToWAT,x as entryWrapperName,n as extractDebugInfo,j as getIntrinsicsAtLevel,g as getMathSpec,i as getVectorDimension,h as getWgslMapping,a as isCompileError,B as isExecutionError,f as isMathIntrinsic,d as isParseError,s as isV02Mode,k as parseNamesSection,l as parseProducersSection,c as parseWasmModule,J as preloadCompiler,y as prepareModule,r as resolveSpecVersion,v as validateGasmMetadataSchema};
1
+ import{a as j,b as k,c as l,d as m,e as t,f as u,g as v,h as w,i as x,j as y,k as z,l as D,m as E,n as F,o as G,p as H,q as I,r as J,s as K,t as L,u as M}from"./chunk-63X76LAZ.js";import{b as a,d as b,e as c,f as d,g as e,h as f,i as g,j as h,k as i,q as n,r as o,s as p,t as q,u as r,w as s}from"./chunk-CYV3E4CZ.js";import{a as C}from"./chunk-IZGS3OS2.js";import{a as A,b as B}from"./chunk-STDXBN5E.js";export{C as BrowserGPUExecutor,g as DEFAULT_SPEC_VERSION,D as DenoGPUExecutor,b as ErrorCodes,A as ExecutionError,t as MATH_INTRINSICS,e as SPEC_VERSION_V01,f as SPEC_VERSION_V02,q as assertCustomSectionsAndMetadataAgree,n as buildBindingTable,o as buildGasmMetadata,L as compile,E as compileAssemblyScriptToWGSL,M as compileAsync,H as compileToArtifact,F as compileWasmToWGSL,G as compileWithDiagnostics,K as compileWithDiagnosticsAsync,I as compileWithRuntimeInfo,l as detectSourceLanguage,z as disassembleToWAT,r as entryWrapperName,m as extractDebugInfo,y as getIntrinsicsAtLevel,v as getMathSpec,x as getVectorDimension,w as getWgslMapping,a as isCompileError,B as isExecutionError,u as isMathIntrinsic,d as isParseError,i as isV02Mode,j as parseNamesSection,k as parseProducersSection,c as parseWasmModule,J as preloadCompiler,s as prepareModule,h as resolveSpecVersion,p as validateGasmMetadataSchema};
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@gasm-compiler/core",
3
- "version": "0.5.0",
4
- "description": "Gasm Compiler compile WebAssembly to WGSL (WebGPU Shading Language)",
3
+ "version": "0.7.0",
4
+ "description": "Rust/Wasm Gasm compiler for WebAssembly to WGSL (WebGPU Shading Language)",
5
5
  "type": "module",
6
6
  "main": "./dist/mod.js",
7
7
  "types": "./dist/mod.d.ts",
@@ -56,9 +56,6 @@
56
56
  "gasm",
57
57
  "shader"
58
58
  ],
59
- "peerDependencies": {
60
- "typescript": "^5.0.0"
61
- },
62
59
  "dependencies": {
63
60
  "wabt": "^1.0.39"
64
61
  },
@@ -68,7 +65,7 @@
68
65
  },
69
66
  "scripts": {
70
67
  "build": "pnpm --dir ../.. core-rs:build:wasm:release && deno run --allow-read --allow-write ../../scripts/generate_core_rs_wasm_embed.ts --release && tsup && deno run --allow-read --allow-write ../../scripts/fix_node_builtin_imports.ts && deno run --allow-read --allow-write --allow-run --allow-env ../../scripts/copy_core_rs_wasm.ts --release",
71
- "test": "pnpm --dir ../.. core-rs:build:wasm && GASM_CORE_BACKEND=rust deno test --allow-all",
68
+ "test": "pnpm --dir ../.. core-rs:build:wasm && deno test --allow-all",
72
69
  "test:e2e": "deno test --allow-all --unstable-webgpu --no-check tests/e2e_execution_test.ts",
73
70
  "test:e2e:gpu": "ENABLE_GPU_TESTS=1 deno test --allow-all --unstable-webgpu --no-check tests/e2e_execution_test.ts",
74
71
  "lint": "biome lint .",