@gasm-compiler/core 0.6.0 → 0.8.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.
@@ -1,9 +1,9 @@
1
- import{a as L,c as q,e as W,f as _,k as j,l as Z,m as D,n as E,o as N,p as A,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 E(r.instance.exports)}function U(n=T()){return J??=ye(n),J}function be(n=T()){let e=xe(n),r=new WebAssembly.Module(Y(e)),t=new WebAssembly.Instance(r,{});return E(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 xe(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 Me(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]=v(e,s);s+=a;let[c,l]=v(e,s);s+=l;let u=s+c;switch(i){case 0:{let[g,m]=B(e,s);r.moduleName=g,s+=m}break;case 1:{let[g,m]=v(e,s);s+=m;for(let f=0;f<g;f++){let[d,h]=v(e,s);s+=h;let[y,x]=B(e,s);s+=x,r.functionNames.set(d,y)}}break;case 2:{let[g,m]=v(e,s);s+=m;for(let f=0;f<g;f++){let[d,h]=v(e,s);s+=h;let[y,x]=v(e,s);s+=x;let M=new Map;for(let S=0;S<y;S++){let[I,P]=v(e,s);s+=P;let[o,p]=B(e,s);s+=p,M.set(I,o)}r.localNames.set(d,M)}}break;case 7:{let[g,m]=v(e,s);s+=m;for(let f=0;f<g;f++){let[d,h]=v(e,s);s+=h;let[y,x]=B(e,s);s+=x,r.globalNames.set(d,y)}}break;default:s=u;break}s<u&&(s=u)}return r}function te(n){let e=se(n,"producers");if(!e)return null;let r={},t=0,[s,i]=v(e,t);t+=i;for(let a=0;a<s;a++){let[c,l]=B(e,t);t+=l;let[u,g]=v(e,t);t+=g;let m=[];for(let f=0;f<u;f++){let[d,h]=B(e,t);t+=h;let[y,x]=B(e,t);t+=x,m.push(y?`${d} ${y}`:d)}switch(c){case"language":r.languages=m;break;case"processed-by":r.processedBy=m;break;case"sdk":r.sdks=m;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]=v(n,t);t+=a;let c=t+i;if(s===0){let[l,u]=B(n,t);if(l===e)return n.subarray(t+u,c)}t=c}return null}function v(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]=v(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=Me(e);return new z(n,r)}var k=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 k.has(r)}function oe(n){if(k.has(n))return n;let e=n.match(/^(.+)_v([234])f32(?:_v)?$/);if(e)return e[1];let r=n.match(/^(.+)_f32$/);return r&&k.has(r[1])?r[1]:n}function ae(n){let e=oe(n);return k.get(e)}function Se(n){return ae(n)?.wgslBuiltin}function Re(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(k.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=ke(s,e);r.push(`${t}${i}`)}return r}function ke(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],u=t[1],g=[];return u!==0&&g.push(`offset=${u}`),l!==void 0&&g.push(`align=${1<<l}`),`${s}${g.length>0?" "+g.join(" "):""}`;case"memory.size":case"memory.grow":return s;default:if(s.startsWith("v128.")){if(s.includes("load")||s.includes("store")){let m=t[0],f=t[1],d=[];return f!==0&&d.push(`offset=${f}`),m!==void 0&&d.push(`align=${1<<m}`),`${s}${d.length>0?" "+d.join(" "):""}`}if(s.includes("const")){let m=t.join(" ");return`${s} ${m}`}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,Ae=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 Ae?.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(u){throw i.destroy(),new w(`Failed to map staging buffer: ${u instanceof Error?u.message:String(u)}`,"readback",String(u))}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 b=p.messages.filter($=>$.type==="error");if(b.length>0){let $=b.map(R=>`${R.message} at ${R.lineNum}:${R.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 u=[],g=0,m=new Map,f=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:b}]of f){let $=this.createBuffer(`input_${o}`,p,140);m.set(o,$),u.push({binding:g++,resource:{buffer:$}})}let d=new Map,h=new Map;for(let o of t){if(m.has(o)){let we=m.get(o),G=r[o];d.set(o,we),h.set(o,{size:G.data.byteLength,type:G.type});continue}let p=s.outputBuffers?.[o]??{type:"f32",size:1},b=p.size??1,$=b*4,R=this.device.createBuffer({label:`output_${o}`,size:$,usage:140}),C;p.type==="f32"?C=new Float32Array(b).fill(0):p.type==="i32"?C=new Int32Array(b).fill(0):C=new Uint32Array(b).fill(0),this.queue.writeBuffer(R,0,C.buffer,C.byteOffset,C.byteLength),d.set(o,R),h.set(o,{size:$,type:p.type}),u.push({binding:g++,resource:{buffer:R}})}let y=Object.keys(r).length,x=this.device.createBindGroupLayout({entries:u.map((o,p)=>{let b=p===0&&r.memory!==void 0,$=p>=y;return{binding:p,visibility:4,buffer:{type:!b&&!$?"read-only-storage":"storage"}}})}),M=this.device.createBindGroup({layout:x,entries:u}),S=this.device.createPipelineLayout({bindGroupLayouts:[x]}),I;try{I=this.device.createComputePipeline({layout:S,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(I),p.setBindGroup(0,M),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),b=h.get(o);if(!p||!b)throw new w(`Output buffer "${o}" not found`,"readback");P[o]=await this.readBuffer(p,b.size,b.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;m.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 D(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 Pt(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 Ct(){await U()}async function _e(n,e={}){let r=await De(n,e);return D(r.diagnostics),r}function ce(n,e,r){let t=X(n,e);if(!t.ok)return{ok:!1,diagnostics:A(t)};let s=ue(n);r?.(s);let i=A(t);return pe(i,s,e),{ok:!0,wgsl:me(t.wgsl,e,n,s),diagnostics:i,dispatchInfo:N(t.dispatchInfo)}}async function De(n,e){let t=(await U()).compile(n,e);if(!t.ok)return{ok:!1,diagnostics:A(t)};let s=ue(n),i=A(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(_(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;if(s=Ee(s,e,r,t),e.compilerMetadata&&(s=s.replace(/(\/\/ Generated: .*\n)/,`$1// Metadata: ${e.compilerMetadata}
3
- `)),e.workgroupSize){let[i,a,c]=e.workgroupSize;s=s.replace(/@compute @workgroup_size\(\d+, \d+, \d+\)/g,`@compute @workgroup_size(${i}, ${a}, ${c})`)}return s}function Ee(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,(u,g)=>{let m=t.functions[l],f=i.commentForFunction(m?.index??l,g);if(l+=1,!f)return u;let d=e.sourceMapping==="minimal"?"":`
5
- // [WAT] rust backend instruction mapping`;return`${f}${d}
6
- ${u}`}),c}function kt(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 _e(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=!1,denyF64Demotion:a=!1,allowI64Demotion:c=!1,warningsAsErrors:l=!1}=e;try{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 m=u.endsWith(".wasm");!m&&!u.endsWith(".as")&&!u.endsWith(".ts")&&console.warn("Warning: Input file does not have .as, .ts, or .wasm extension");let f=u.replace(/\.(as|ts)$/,".wasm");if(m)t&&console.log("[2/4] Input is WASM, skipping compilation..."),f=u;else{t&&console.log("[2/4] Compiling AssemblyScript to WASM...");let M=await qe(),{success:S,stdout:I,stderr:P}=await Ge(M,[u,"-o",f]);if(!S)throw new Error(`AssemblyScript compilation failed:
8
- ${P}`);t&&I&&console.log(I)}t&&console.log("[3/4] Reading WASM binary...");let d=await Ne(f);t&&(console.log(` WASM size: ${d.length} bytes`),console.log("[4/4] Compiling WASM to WGSL using Gasm..."));let h={};a&&(h.f64="deny"),c&&(h.i64="allow-lossy");let y=V(d,{optimize:i,demotionPolicy:h,warningsAsErrors:l});if(ge(y.diagnostics,t),!y.ok){let M=y.diagnostics.errors[0];throw new Error(M?.message??"Compilation failed")}let x=y.wgsl;if(r){let M=fe(r),S=Fe(M);await Te(S,{recursive:!0}),await Oe(M,x,"utf-8"),console.log(t?`
9
- \u2713 Successfully compiled to: ${M}`:`\u2713 Compiled to: ${r}`)}if(!s&&!m)try{await Ue(f),t&&console.log(" Cleaned up intermediate WASM file")}catch{}return x}catch(u){throw u instanceof Error?u:new Error(`Unknown error: ${String(u)}`)}}function Le(n,e={}){let{verbose:r=!1,optimize:t=!1,denyF64Demotion:s=!1,allowI64Demotion:i=!1,warningsAsErrors:a=!1}=e,c={};s&&(c.f64="deny"),i&&(c.i64="allow-lossy");let l=V(n,{optimize:t,demotionPolicy:c,warningsAsErrors:a});if(ge(l.diagnostics,r),!l.ok){let u=l.diagnostics.errors[0];throw new Error(u?.message??"Compilation failed")}return l.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,k as e,$e as f,ae as g,Se as h,Re as i,Be as j,Ie as k,F as l,Ve as m,Le as n,V as o,We as p,Pt as q,Ct as r,_e as s,kt as t,At as u};
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};
@@ -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{m as a,n as b}from"./chunk-7JF6MVMW.js";import"./chunk-CYV3E4CZ.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 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-7JF6MVMW.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};
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,6 +1,6 @@
1
1
  {
2
2
  "name": "@gasm-compiler/core",
3
- "version": "0.6.0",
3
+ "version": "0.8.0",
4
4
  "description": "Rust/Wasm Gasm compiler for WebAssembly to WGSL (WebGPU Shading Language)",
5
5
  "type": "module",
6
6
  "main": "./dist/mod.js",