@gasm-compiler/core 0.3.2 → 0.5.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 pe,B as me,C as ge,H as B,I as P,J as j,K as H,L as Z,M as K,N as J,P as Q,T as he,U as ye,a as S,c as oe,d as C,e as D,f as V,g as z,h as T,j as N,k as q,n as ie,p as se,q as ae,r as ce,s as ue,t as le,y as de,z as fe}from"./chunk-MBWDLAL5.js";import{a as h}from"./chunk-STDXBN5E.js";import{resolve as We}from"node:path";import{stat as De,readFile as mt,writeFile as gt,unlink as ht,mkdir as yt}from"node:fs/promises";import{spawn as bt}from"node:child_process";import{dirname as wt}from"node:path";function be(e){let n=e.functions.map(r=>!("parallelLoopInfo"in r)||!r.parallelLoopInfo?r:Pe(r));return{...e,functions:n}}function Pe(e){let n=e.parallelLoopInfo.loopLocalIndex,{writes:r}=Le(e.body,n);if(r>0){let t=M(e.body,n);return{...e,body:t}}return e}function Le(e,n){let r=0,t=0;function o(s){switch(s.kind){case"simple":if(s.instructions)for(let i of s.instructions)i.opcode==="local.get"&&i.immediates?.[0]===n&&r++,(i.opcode==="local.set"||i.opcode==="local.tee")&&i.immediates?.[0]===n&&t++;break;case"block":for(let i of s.children)o(i);break;case"loop":o(s.body);break;case"if":o(s.thenBranch),s.elseBranch&&o(s.elseBranch);break;case"parallel_loop":o(s.body),s.epilogue&&o(s.epilogue);break;case"return":case"break":case"continue":break}}return o(e),{reads:r,writes:t}}function M(e,n){switch(e.kind){case"simple":{if(!e.instructions)return e;let r=e.instructions.filter(t=>!((t.opcode==="local.set"||t.opcode==="local.tee")&&t.immediates?.[0]===n));return r.length===0?{kind:"block",children:[]}:{...e,instructions:r}}case"block":{let r=e.children.map(t=>M(t,n)).filter(t=>!Ue(t));return{...e,children:r}}case"loop":return{...e,body:M(e.body,n)};case"if":return{...e,thenBranch:M(e.thenBranch,n),elseBranch:e.elseBranch?M(e.elseBranch,n):void 0};case"parallel_loop":return{...e,body:M(e.body,n),epilogue:e.epilogue?M(e.epilogue,n):void 0};case"return":case"break":case"continue":return e}}function Ue(e){return e.kind==="block"&&e.children.length===0||e.kind==="simple"&&(!e.instructions||e.instructions.length===0)}function we(e){let n=e.functions.map(r=>Fe(r));return{...e,functions:n}}function Fe(e){let n=E(e.body,e);return{...e,body:n}}function E(e,n){switch(e.kind){case"loop":{let r=Ge(e.body),t=[],o=Se(e.body,r,t,n);return t.length===0?{...e,body:E(e.body,n)}:{kind:"block",children:[{kind:"simple",instructions:t},{...e,body:E(o,n)}],label:void 0}}case"block":return{...e,children:e.children.map(r=>E(r,n))};case"if":return{...e,thenBranch:E(e.thenBranch,n),elseBranch:e.elseBranch?E(e.elseBranch,n):void 0};case"simple":return e;default:return e}}function Ge(e){let n=new Set;function r(t){if(t.kind==="simple"&&t.instructions){for(let o of t.instructions)if(o.id!==void 0&&n.add(o.id),(o.opcode==="local.set"||o.opcode==="local.tee")&&o.immediates){let s=o.immediates[0];n.add(-s-1)}}t.kind==="block"&&t.children.forEach(r),t.kind==="loop"&&r(t.body),t.kind==="if"&&(r(t.thenBranch),t.elseBranch&&r(t.elseBranch))}return r(e),n}function Se(e,n,r,t){switch(e.kind){case"simple":{if(!e.instructions||e.instructions.length===0)return e;let o=[],s=new Set;for(let i of e.instructions)ze(i,n,s)?(r.push(i),i.id!==void 0&&s.add(i.id)):(o.push(i),i.id!==void 0&&s.add(i.id));return{...e,instructions:o}}case"block":{let o=e.children.map(s=>Se(s,n,r,t));return{...e,children:o}}case"loop":return e;case"if":return e;default:return e}}function ze(e,n,r){if(!Te(e.opcode))return!1;if(e.opcode==="local.get"&&e.immediates){let o=-e.immediates[0]-1;if(n.has(o))return!1}if(e.args){for(let t of e.args)if(n.has(t))return!1}return!0}function Te(e){return new Set(["i32.const","i64.const","f32.const","f64.const","local.get","i32.add","i32.sub","i32.mul","i32.div_s","i32.div_u","i32.rem_s","i32.rem_u","i64.add","i64.sub","i64.mul","i64.div_s","i64.div_u","i64.rem_s","i64.rem_u","f32.add","f32.sub","f32.mul","f32.div","f64.add","f64.sub","f64.mul","f64.div","i32.and","i32.or","i32.xor","i32.shl","i32.shr_s","i32.shr_u","i32.rotl","i32.rotr","i64.and","i64.or","i64.xor","i64.shl","i64.shr_s","i64.shr_u","i64.rotl","i64.rotr","i32.eqz","i32.eq","i32.ne","i32.lt_s","i32.lt_u","i32.gt_s","i32.gt_u","i32.le_s","i32.le_u","i32.ge_s","i32.ge_u","i64.eqz","i64.eq","i64.ne","i64.lt_s","i64.lt_u","i64.gt_s","i64.gt_u","i64.le_s","i64.le_u","i64.ge_s","i64.ge_u","f32.eq","f32.ne","f32.lt","f32.gt","f32.le","f32.ge","f64.eq","f64.ne","f64.lt","f64.gt","f64.le","f64.ge","i32.wrap_i64","i64.extend_i32_s","i64.extend_i32_u","f32.convert_i32_s","f32.convert_i32_u","f32.convert_i64_s","f32.convert_i64_u","f32.demote_f64","f64.convert_i32_s","f64.convert_i32_u","f64.convert_i64_s","f64.convert_i64_u","f64.promote_f32","i32.reinterpret_f32","i64.reinterpret_f64","f32.reinterpret_i32","f64.reinterpret_i64","i32.clz","i32.ctz","i32.popcnt","i64.clz","i64.ctz","i64.popcnt","f32.abs","f32.neg","f32.ceil","f32.floor","f32.trunc","f32.nearest","f32.sqrt","f64.abs","f64.neg","f64.ceil","f64.floor","f64.trunc","f64.nearest","f64.sqrt","f32.min","f32.max","f32.copysign","f64.min","f64.max","f64.copysign"]).has(e)}function Ie(e){for(let n of e.functions)Ne(n);return e}function Ne(e){A(e.body,e)}function A(e,n){switch(e.kind){case"simple":qe(e,n);break;case"block":for(let r of e.children)A(r,n);break;case"loop":A(e.body,n);break;case"if":A(e.thenBranch,n),e.elseBranch&&A(e.elseBranch,n);break;case"parallel_loop":A(e.body,n),e.epilogue&&A(e.epilogue,n);break}}function qe(e,n){let r=Ze(e.instructions,n);r.length>0&&Je(e,n,r);let t=Ke(e.instructions,n);t.length>0&&Qe(e,n,t)}function ve(e,n){let r=U(e,n);if(!r)return null;if(r.opcode==="i32.shr_u"&&r.args.length===2){if(L(r.args[1],n)!==2)return null;let o=r.args[0];return je(o,n)}return He(e,n)}function je(e,n){let r=U(e,n);if(!r)return{baseVar:e,wordOffset:0};if(r.opcode==="i32.add"&&r.args.length===2){let t=L(r.args[1],n);if(t!==null&&t>=0&&t%4===0)return{baseVar:r.args[0],wordOffset:t/4};let o=L(r.args[0],n);return o!==null&&o>=0&&o%4===0?{baseVar:r.args[1],wordOffset:o/4}:null}return{baseVar:e,wordOffset:0}}function He(e,n){let r=U(e,n);if(!r)return{baseVar:e,wordOffset:0};if(r.opcode==="i32.add"&&r.args.length===2){let t=L(r.args[1],n);if(t!==null&&t>=0)return{baseVar:r.args[0],wordOffset:t}}return{baseVar:e,wordOffset:0}}function U(e,n){if(n.inlinedExpressionMap){let r=n.inlinedExpressionMap.get(e);if(r)return r}return $(n.body,e)}function $(e,n){switch(e.kind){case"simple":for(let r of e.instructions)if(r.id===n)return r;return null;case"block":for(let r of e.children){let t=$(r,n);if(t)return t}return null;case"loop":return $(e.body,n);case"if":{let r=$(e.thenBranch,n);return r||(e.elseBranch?$(e.elseBranch,n):null)}case"parallel_loop":{let r=$(e.body,n);return r||(e.epilogue?$(e.epilogue,n):null)}default:return null}}function L(e,n){let r=U(e,n);return r&&r.opcode==="i32.const"&&r.immediates&&r.immediates.length>0?r.immediates[0]:null}function Ze(e,n){let r=[],t=[];for(let s=0;s<e.length;s++){let i=e[s];if(i.opcode==="wgsl.store_f32"&&i.args.length===2){let a=ve(i.args[0],n);a&&t.push({index:s,addr:a,valueArg:i.args[1]})}}let o=new Map;for(let s of t){let i=o.get(s.addr.baseVar)||[];i.push(s),o.set(s.addr.baseVar,i)}for(let[s,i]of o){if(i.length<3)continue;i.sort((c,u)=>c.addr.wordOffset-u.addr.wordOffset);let a=0;for(;a<i.length;){let c=a;for(;c+1<i.length&&i[c+1].addr.wordOffset===i[c].addr.wordOffset+1;)c++;let u=c-a+1;if(u>=3){let p=u>=4?4:3,d=i.slice(a,a+p),f=d.map(g=>g.index);ke(f,e)&&r.push({instrIndices:f,baseVar:s,valueArgs:d.map(g=>g.valueArg),components:p})}a=c+1}}return r}function Ke(e,n){let r=[],t=[];for(let s=0;s<e.length;s++){let i=e[s];if(i.opcode==="wgsl.load_f32"&&i.args.length===1&&i.id!==void 0){let a=ve(i.args[0],n);a&&t.push({index:s,addr:a,resultVar:i.id})}}let o=new Map;for(let s of t){let i=o.get(s.addr.baseVar)||[];i.push(s),o.set(s.addr.baseVar,i)}for(let[s,i]of o){if(i.length<3)continue;i.sort((c,u)=>c.addr.wordOffset-u.addr.wordOffset);let a=0;for(;a<i.length;){let c=a;for(;c+1<i.length&&i[c+1].addr.wordOffset===i[c].addr.wordOffset+1;)c++;let u=c-a+1;if(u>=3){let p=u>=4?4:3,d=i.slice(a,a+p),f=d.map(g=>g.index);ke(f,e)&&r.push({instrIndices:f,baseVar:s,resultVars:d.map(g=>g.resultVar),components:p})}a=c+1}}return r}function ke(e,n){if(e.length<3)return!1;let r=Math.min(...e),t=Math.max(...e),o=e.length*4;if(t-r>=o)return!1;for(let s=r;s<=t;s++)if(n[s].opcode.startsWith("wgsl.store")&&!e.includes(s))return!1;return!0}function Je(e,n,r){r.sort((t,o)=>o.instrIndices[0]-t.instrIndices[0]);for(let t of r){let o=t.components===4?"wgsl.store_vec4f":"wgsl.store_vec3f",s=e.instructions[t.instrIndices[0]].args[0],i={type:"instr",opcode:o,args:[s,...t.valueArgs],synthetic:!0},a=[...t.instrIndices].sort((c,u)=>c-u);for(let c=a.length-1;c>=0;c--)e.instructions.splice(a[c],1);e.instructions.splice(a[0],0,i)}}function Qe(e,n,r){r.sort((t,o)=>o.instrIndices[0]-t.instrIndices[0]);for(let t of r){let o=t.components===4?"wgsl.load_vec4f":"wgsl.load_vec3f",s=0;for(let d of n.vars.keys())d>s&&(s=d);let i=s+1;n.vars.set(i,{id:i,type:"v128"});let a=e.instructions[t.instrIndices[0]].args[0],c={type:"instr",id:i,opcode:o,args:[a],synthetic:!0},u=t.resultVars.map((d,f)=>({type:"instr",id:d,opcode:"wgsl.extract_f32",args:[i],immediates:[f],synthetic:!0})),p=[...t.instrIndices].sort((d,f)=>d-f);for(let d=p.length-1;d>=0;d--)e.instructions.splice(p[d],1);e.instructions.splice(p[0],0,c,...u)}}function X(e,n){let r={valid:!0,mathImports:[],errors:[],requiredLevel:null},t=n===!0||n==="M0"||n==="M1"||n==="M2",o=n===!0?"M2":n==="M0"||n==="M1"||n==="M2"?n:null,s=["M0","M1","M2"],i=0;for(let a of e.imports){if(a.kind!=="func")continue;let c=i++;if(!N(a.module,a.name))continue;let u=a.typeIndex;if(u===void 0){r.errors.push(S(`Math import ${a.name} has no type index`,{functionName:a.name})),r.valid=!1;continue}let p=e.types[u];if(!p){r.errors.push(S(`Math import ${a.name} references invalid type index ${u}`,{functionName:a.name})),r.valid=!1;continue}let d=q(a.name);if(!d){r.errors.push(S(`Unknown math intrinsic: ${a.name}`,{functionName:a.name})),r.valid=!1;continue}let f={funcIndex:c,module:a.module,name:a.name,level:d.level,params:p.params,results:p.results};if(r.mathImports.push(f),(r.requiredLevel===null||s.indexOf(d.level)>s.indexOf(r.requiredLevel))&&(r.requiredLevel=d.level),!t){r.errors.push(S(`Math intrinsic ${a.name} requires mathExtension option to be enabled`,{functionName:a.name})),r.valid=!1;continue}if(o&&!ie(a.name,o)){r.errors.push(S(`Math intrinsic ${a.name} requires level ${d.level}, but only ${o} is enabled`,{functionName:a.name})),r.valid=!1;continue}let g=se(a.name,p.params,p.results);g&&(r.errors.push(S(g,{functionName:a.name})),r.valid=!1)}return r}import{readFileSync as Xe}from"node:fs";var xe,Me;async function Ye(e=ee()){let n=await tt(e),r=await WebAssembly.instantiate($e(n),{});return Z(r.instance.exports)}function Y(e=ee()){return Me??=Ye(e),Me}function et(e=ee()){let n=nt(e),r=new WebAssembly.Module($e(n)),t=new WebAssembly.Instance(r,{});return Z(t.exports)}function Ae(e,n={}){return xe??=et(),xe.compile(e,n)}function ee(){let e=globalThis.Deno,n=new URL("./gasm_core_rs.wasm",import.meta.url);if(e){let r=new URL("../../core-rs/target/wasm32-unknown-unknown/debug/gasm_core_rs.wasm",import.meta.url);try{return e.statSync(r),r}catch{}let t=new URL("../../core-rs/target/wasm32-unknown-unknown/release/gasm_core_rs.wasm",import.meta.url);try{return e.statSync(t),t}catch{}try{return e.statSync(n),n}catch{}}return new URL("../../core-rs/target/wasm32-unknown-unknown/debug/gasm_core_rs.wasm",import.meta.url)}async function tt(e){let n=globalThis.Deno;return n?await n.readFile(e):await(await import("node:fs/promises")).readFile(e)}function nt(e){let n=globalThis.Deno;return n?n.readFileSync(e):Xe(e)}function $e(e){return e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength)}var _e={};for(let[e,n]of Object.entries(oe))_e[n]=e.replace(/_/g,".");function rt(e){let n=[];n.push("(module");for(let t of e.memories)n.push(` (memory ${t.min}${t.max!==void 0?` ${t.max}`:""})`);for(let t of e.imports)if(t.kind==="func"&&t.typeIndex!==void 0){let o=e.types[t.typeIndex];if(o){let s=o.params.map((a,c)=>`(param $${c} ${a})`).join(" "),i=o.results.map(a=>`(result ${a})`).join(" ");n.push(` (import "${t.module}" "${t.name}" (func ${s}${i?" "+i:""}))`)}}let r=new Set;for(let t of e.globals){if(t.kind==="import")continue;let o=t.mutable?"(mut ":"",s=t.mutable?")":"",i="";t.initValue!==void 0&&(t.type==="i32"||t.type==="i64"?i=`${t.type}.const ${t.initValue}`:(t.type==="f32"||t.type==="f64")&&(i=`${t.type}.const ${t.initValue}`)),n.push(` (global $${t.index} ${o}${t.type}${s} ${i?`(${i})`:""})`)}for(let t of e.data){let o=Array.from(t.data.slice(0,Math.min(32,t.data.length))).map(i=>`\\${i.toString(16).padStart(2,"0")}`).join(""),s=t.data.length>32?"...":"";n.push(` (data (i32.const ${t.memoryIndex}) "${o}${s}") ;; ${t.data.length} bytes`)}for(let t of e.functions)n.push(""),n.push(...ot(t,e));if(e.exports.length>0){n.push("");for(let t of e.exports)t.kind==="func"?n.push(` (export "${t.name}" (func $${t.index}))`):t.kind==="mem"?n.push(` (export "${t.name}" (memory ${t.index}))`):t.kind==="global"&&n.push(` (export "${t.name}" (global ${t.index}))`)}return e.startFunctionIndex!==void 0&&n.push(` (start $${e.startFunctionIndex})`),n.push(")"),n.join(`
2
+ `)}function ot(e,n){let r=[],t=e.params.map((i,a)=>`(param $${a} ${i})`).join(" "),o=e.results.map(i=>`(result ${i})`).join(" ");if(r.push(` (func $${e.index} ${t}${o?" "+o:""}`),e.locals.length>0){let i=new Map;for(let a of e.locals)i.set(a.type,(i.get(a.type)||0)+1);for(let[a,c]of i)r.push(` (local ${a} (;${c}x;))`)}let s=it(e.body,2);return r.push(...s),r.push(" )"),r}function it(e,n){let r=[],t=" ".repeat(n);for(let o of e){let s=st(o,n);r.push(`${t}${s}`)}return r}function st(e,n){if(!e||typeof e!="object")return";; Error: Invalid instruction";let{opcode:r,immediates:t}=e,o=_e[r]||`unknown_0x${r.toString(16)}`;if(!t||t.length===0)return o;switch(o){case"local.get":case"local.set":case"local.tee":return`${o} $${t[0]}`;case"global.get":case"global.set":return`${o} $${t[0]}`;case"i32.const":case"i64.const":return`${o} ${t[0]}`;case"f32.const":case"f64.const":return`${o} ${t[0]}`;case"call":return`${o} $${t[0]}`;case"call_indirect":return`${o} (type ${t[0]})`;case"br":case"br_if":return`${o} ${t[0]}`;case"br_table":let s=t[0].join(" "),i=t[1];return`${o} ${s} ${i}`;case"if":case"block":case"loop":let a=t[0];return`${o} ${a!==void 0&&a!=="void"?`(result ${a})`:""}`;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 c=t[0],u=t[1],p=[];return u!==0&&p.push(`offset=${u}`),c!==void 0&&p.push(`align=${1<<c}`),`${o}${p.length>0?" "+p.join(" "):""}`;case"memory.size":case"memory.grow":return o;default:if(o.startsWith("v128.")){if(o.includes("load")||o.includes("store")){let d=t[0],f=t[1],g=[];return f!==0&&g.push(`offset=${f}`),d!==void 0&&g.push(`align=${1<<d}`),`${o}${g.length>0?" "+g.join(" "):""}`}if(o.includes("const")){let d=t.join(" ");return`${o} ${d}`}return o.includes("extract_lane")||o.includes("replace_lane")?`${o} ${t[0]}`:`${o}${t.length>0?" "+t.join(" "):""}`}return`${o}${t.length>0?" "+t.join(" "):""}`}}var Ut=globalThis.gpu,at=globalThis.navigator?.gpu,te=class{constructor(n={}){this.config=n}device=null;queue=null;initialized=!1;buffers=new Map;async ensureInitialized(){if(!this.initialized)try{let n=await at?.requestAdapter?.();if(!n)throw new h("No GPU adapter available","compilation","navigator.gpu.requestAdapter() returned null");if(this.device=await n.requestDevice?.(),!this.device)throw new h("Failed to request GPU device","compilation","adapter.requestDevice() returned null");this.queue=this.device.queue,this.initialized=!0}catch(n){throw n instanceof h?n:new h(`GPU initialization failed: ${n instanceof Error?n.message:String(n)}`,"compilation",String(n))}}createBuffer(n,r,t){if(!this.device)throw new h("Device not initialized","binding","Call ensureInitialized() first");let o=this.device.createBuffer({label:n,size:r.byteLength,usage:t});return this.queue.writeBuffer(o,0,r.buffer,r.byteOffset,r.byteLength),o}async readBuffer(n,r,t){if(!this.device||!this.queue)throw new h("Device not initialized","readback","Call ensureInitialized() first");let o=Math.max(4,Math.ceil(r/4)*4),s=this.device.createBuffer({size:o,usage:9}),i=this.device.createCommandEncoder();i.copyBufferToBuffer(n,0,s,0,Math.min(r,o)),this.queue.submit([i.finish()]);try{await s.mapAsync(1)}catch(u){throw s.destroy(),new h(`Failed to map staging buffer: ${u instanceof Error?u.message:String(u)}`,"readback",String(u))}let a=s.getMappedRange(),c;return t==="f32"?c=new Float32Array(new Uint8Array(a).buffer).slice():t==="i32"?c=new Int32Array(new Uint8Array(a).buffer).slice():c=new Uint32Array(new Uint8Array(a).buffer).slice(),s.unmap(),s.destroy(),{data:c,type:t}}async execute(n,r,t,o={}){let s=o.workgroupSize??[1,1,1],i=o.workgroupCount??[1,1,1],a=o.timeout??5e3;if(await this.ensureInitialized(),!this.device||!this.queue)throw new h("Device initialization failed","compilation");try{let c;try{let l=o.shaderLabel||"Gasm Compiler Compute Shader";c=this.device.createShaderModule({code:n,label:l});let m=await c.getCompilationInfo?.();if(m&&m.messages.length>0){let y=m.messages.filter(w=>w.type==="error");if(y.length>0){let w=y.map(x=>`${x.message} at ${x.lineNum}:${x.linePos}`).join("; ");throw new h(`WGSL compilation failed: ${w}`,"compilation")}}}catch(l){throw l instanceof h?l:new h(`Failed to create shader module: ${l instanceof Error?l.message:String(l)}`,"compilation",String(l))}let u=[],p=0,d=new Map,f=Object.entries(r).sort((l,m)=>l[0]==="memory"?-1:m[0]==="memory"?1:l[0].localeCompare(m[0]));for(let[l,{data:m,type:y}]of f){let w=this.createBuffer(`input_${l}`,m,140);d.set(l,w),u.push({binding:p++,resource:{buffer:w}})}let g=new Map,v=new Map;for(let l of t){if(d.has(l)){let Be=d.get(l),re=r[l];g.set(l,Be),v.set(l,{size:re.data.byteLength,type:re.type});continue}let m=o.outputBuffers?.[l]??{type:"f32",size:1},y=m.size??1,w=y*4,x=this.device.createBuffer({label:`output_${l}`,size:w,usage:140}),_;m.type==="f32"?_=new Float32Array(y).fill(0):m.type==="i32"?_=new Int32Array(y).fill(0):_=new Uint32Array(y).fill(0),this.queue.writeBuffer(x,0,_.buffer,_.byteOffset,_.byteLength),g.set(l,x),v.set(l,{size:w,type:m.type}),u.push({binding:p++,resource:{buffer:x}})}let b=Object.keys(r).length,k=this.device.createBindGroupLayout({entries:u.map((l,m)=>{let y=m===0&&r.memory!==void 0,w=m>=b;return{binding:m,visibility:4,buffer:{type:!y&&!w?"read-only-storage":"storage"}}})}),I=this.device.createBindGroup({layout:k,entries:u}),R=this.device.createPipelineLayout({bindGroupLayouts:[k]}),O;try{O=this.device.createComputePipeline({layout:R,compute:{module:c,entryPoint:"main"}})}catch(l){throw new h(`Failed to create compute pipeline: ${l instanceof Error?l.message:String(l)}`,"binding",String(l))}try{let l=this.device.createCommandEncoder(),m=l.beginComputePass();m.setPipeline(O),m.setBindGroup(0,I),m.dispatchWorkgroups(i[0],i[1],i[2]),m.end(),this.queue.submit([l.finish()])}catch(l){throw new h(`Compute shader dispatch failed: ${l instanceof Error?l.message:String(l)}`,"dispatch",String(l))}let W={};try{for(let l of t){let m=g.get(l),y=v.get(l);if(!m||!y)throw new h(`Output buffer "${l}" not found`,"readback");W[l]=await this.readBuffer(m,y.size,y.type)}}catch(l){throw l instanceof h?l:new h(`Failed to read back results: ${l instanceof Error?l.message:String(l)}`,"readback",String(l))}finally{let l=new Set;d.forEach(m=>{m.destroy(),l.add(m)}),g.forEach(m=>{l.has(m)||m.destroy()})}return W}catch(c){throw c instanceof h?c:new h(`Unexpected error during execution: ${c instanceof Error?c.message:String(c)}`,"dispatch",String(c))}}async destroy(){this.buffers.forEach(n=>n.destroy()),this.buffers.clear(),this.device&&typeof this.device.destroy=="function"&&this.device.destroy(),this.device=null,this.queue=null,this.initialized=!1}};function F(e,n={}){let r=G()?Ce(e,n):ne(e,n);return j(r.diagnostics),r}function lt(e,n={}){let r,t=s=>{r=s},o=G()?Ce(e,n,t):ne(e,n,t);if(!o.ok)return o;if(!r)throw new Error("Compiler succeeded without a validated Wasm module");return{...o,metadata:Q(r,{options:n,dispatchInfo:o.dispatchInfo})}}function _n(e,n={}){let r=ye(e,n);if(r.errors.length>0){let o=P();return o.advisories.push(...r.advisories),o.errors.push(...r.errors),{ok:!1,diagnostics:o}}let t=lt(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 Cn(){G()&&await Y()}async function dt(e,n={}){let r=G()?await ft(e,n):ne(e,n);return j(r.diagnostics),r}function ne(e,n={},r){let t=P(),o=B(n),s=n.strictConformance||o,i=D(e);if(V(i))return t.errors.push({severity:"error",code:i.code??C.ERR_PARSE,message:i.message,functionName:i.functionName}),{ok:!1,diagnostics:t};let a=i,c=z(a,{strictConformance:s});if(T(c))return t.errors.push({severity:"error",code:c.code??C.ERR_VALIDATION,message:c.message,functionName:c.functionName}),{ok:!1,diagnostics:t};let u=c;if(Re(t,u,n),n.mathExtension){let b=X(a,n.mathExtension);if(!b.valid){for(let k of b.errors)t.errors.push({severity:"error",code:"ERR_MATH_VALIDATION",message:k.message,functionName:k.functionName});return{ok:!1,diagnostics:t}}}let p=H(u,n);if(t.warnings.push(...p.diagnostics.warnings),t.errors.push(...p.diagnostics.errors),t.demotions.push(...p.diagnostics.demotions),t.featuresUsed=p.diagnostics.featuresUsed,t.errors.length>0)return{ok:!1,diagnostics:t};r?.(u);let d=fe(u);n.optimize!==!1&&(d=me(d,{verbose:n.verbose??!1}));let f=ge(d);f=ae(f),n.optimize!==!1&&(f=ce(f)),n.vectorPromotion&&(f=Ie(f));let g=ue();if(n.optimize!==!1){let b=le(f);f=b.module,g=b.dispatchInfo,f=be(f),f=we(f)}return{ok:!0,wgsl:pe(f,n,e,g),diagnostics:t,dispatchInfo:g}}function G(){let n=globalThis.Deno?.env?.get("GASM_CORE_BACKEND")?.toLowerCase();return n!=="typescript"&&n!=="ts"}function Ce(e,n,r){let t=Ee(e,n);if(!t.ok)return{ok:!1,diagnostics:t.diagnostics};r?.(t.module);let o=Ae(e,n);return o.ok?{ok:!0,wgsl:Oe(o.wgsl,n,e,t.module),diagnostics:t.diagnostics,dispatchInfo:K(o.dispatchInfo)}:(t.diagnostics.errors.push(...J(o.diagnostics).errors),{ok:!1,diagnostics:t.diagnostics})}async function ft(e,n){let r=Ee(e,n);if(!r.ok)return{ok:!1,diagnostics:r.diagnostics};let o=(await Y()).compile(e,n);return o.ok?{ok:!0,wgsl:Oe(o.wgsl,n,e,r.module),diagnostics:r.diagnostics,dispatchInfo:K(o.dispatchInfo)}:(r.diagnostics.errors.push(...J(o.diagnostics).errors),{ok:!1,diagnostics:r.diagnostics})}function Ee(e,n){let r=P(),t=D(e);if(V(t))return r.errors.push({severity:"error",code:t.code??C.ERR_PARSE,message:t.message,functionName:t.functionName}),{ok:!1,diagnostics:r};let o=B(n),s=n.strictConformance||o,i=z(t,{strictConformance:s});if(T(i))return r.errors.push({severity:"error",code:i.code??C.ERR_VALIDATION,message:i.message,functionName:i.functionName}),{ok:!1,diagnostics:r};if(Re(r,i,n),n.mathExtension){let c=X(t,n.mathExtension);if(!c.valid){for(let u of c.errors)r.errors.push({severity:"error",code:"ERR_MATH_VALIDATION",message:u.message,functionName:u.functionName});return{ok:!1,diagnostics:r}}}let a=H(i,n);return r.warnings.push(...a.diagnostics.warnings),r.errors.push(...a.diagnostics.errors),r.demotions.push(...a.diagnostics.demotions),r.featuresUsed=a.diagnostics.featuresUsed,r.errors.length>0?{ok:!1,diagnostics:r}:{ok:!0,diagnostics:r,module:i}}function Re(e,n,r){B(r)&&he(n,r)&&(e.warnings.some(t=>t.code==="WARN_WORKGROUP_SIZE_OVERRIDE")||e.warnings.push({severity:"warning",code:"WARN_WORKGROUP_SIZE_OVERRIDE",message:"CompileOptions.workgroupSize overrides gasm.workgroup_size custom-section declarations"}))}function Oe(e,n,r,t){let o=e;if(o=pt(o,n,r,t),n.compilerMetadata&&(o=o.replace(/(\/\/ Generated: .*\n)/,`$1// Metadata: ${n.compilerMetadata}
3
+ `)),n.workgroupSize){let[s,i,a]=n.workgroupSize;o=o.replace(/@compute @workgroup_size\(\d+, \d+, \d+\)/g,`@compute @workgroup_size(${s}, ${i}, ${a})`)}return o}function pt(e,n,r,t){if(n.stripComments||n.releaseMode)return e;let s=de(r,n.sourceMapping);if(!s)return e;let i=s.generateHeaderComment(),a=i?e.replace(/(\/\/ Generated: .*\n)/,`$1${i}
4
+ `):e,c=0;return a=a.replace(/^fn ([A-Za-z_][A-Za-z0-9_]*)\(/gm,(u,p)=>{let d=t.functions[c],f=s.commentForFunction(d?.index??c,p);if(c+=1,!f)return u;let g=n.sourceMapping==="minimal"?"":`
5
+ // [WAT] rust backend instruction mapping`;return`${f}${g}
6
+ ${u}`}),a}function En(e,n={}){let r=F(e,n);if(!r.ok){let t=r.diagnostics.errors[0];throw S(t?.message??"Compilation failed",{functionName:t?.functionName,instructionName:t?.code,code:t?.code})}return r.wgsl}async function Rn(e,n={}){let r=await dt(e,n);if(!r.ok){let t=r.diagnostics.errors[0];throw S(t?.message??"Compilation failed",{functionName:t?.functionName,instructionName:t?.code,code:t?.code})}return r.wgsl}function Ve(e,n){for(let r of e.warnings){let t=r.functionName?` (${r.functionName})`:"";console.error(`warning${t}: ${r.message}`)}if(n&&e.demotions.length>0){let r=new Map;for(let o of e.demotions)r.set(o.kind,(r.get(o.kind)??0)+1);let t=[...r.entries()].map(([o,s])=>`${o} (${s})`);console.error(`demotions: ${t.join(", ")}`)}}function St(e,n){return new Promise(r=>{let t=bt(e,n,{stdio:["ignore","pipe","pipe"]}),o="",s="";t.stdout.on("data",i=>{o+=String(i)}),t.stderr.on("data",i=>{s+=String(i)}),t.on("close",i=>{r({success:i===0,stdout:o,stderr:s})}),t.on("error",i=>{r({success:!1,stdout:o,stderr:`${s}
7
+ ${i.message}`})})})}async function ct(e,n={}){let{output:r,verbose:t=!1,keepWasm:o=!1,optimize:s=!1,denyF64Demotion:i=!1,allowI64Demotion:a=!1,warningsAsErrors:c=!1}=n;try{t&&console.log(`[1/4] Validating input file: ${e}`);let u=We(e);if(!(await De(u)).isFile())throw new Error(`Not a file: ${e}`);let d=u.endsWith(".wasm");!d&&!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(d)t&&console.log("[2/4] Input is WASM, skipping compilation..."),f=u;else{t&&console.log("[2/4] Compiling AssemblyScript to WASM...");let I=await It(),{success:R,stdout:O,stderr:W}=await St(I,[u,"-o",f]);if(!R)throw new Error(`AssemblyScript compilation failed:
8
+ ${W}`);t&&O&&console.log(O)}t&&console.log("[3/4] Reading WASM binary...");let g=await mt(f);t&&(console.log(` WASM size: ${g.length} bytes`),console.log("[4/4] Compiling WASM to WGSL using Gasm..."));let v={};i&&(v.f64="deny"),a&&(v.i64="allow-lossy");let b=F(g,{optimize:s,demotionPolicy:v,warningsAsErrors:c});if(Ve(b.diagnostics,t),!b.ok){let I=b.diagnostics.errors[0];throw new Error(I?.message??"Compilation failed")}let k=b.wgsl;if(r){let I=We(r),R=wt(I);await yt(R,{recursive:!0}),await gt(I,k,"utf-8"),console.log(t?`
9
+ \u2713 Successfully compiled to: ${I}`:`\u2713 Compiled to: ${r}`)}if(!o&&!d)try{await ht(f),t&&console.log(" Cleaned up intermediate WASM file")}catch{}return k}catch(u){throw u instanceof Error?u:new Error(`Unknown error: ${String(u)}`)}}function ut(e,n={}){let{verbose:r=!1,optimize:t=!1,denyF64Demotion:o=!1,allowI64Demotion:s=!1,warningsAsErrors:i=!1}=n,a={};o&&(a.f64="deny"),s&&(a.i64="allow-lossy");let c=F(e,{optimize:t,demotionPolicy:a,warningsAsErrors:i});if(Ve(c.diagnostics,r),!c.ok){let u=c.diagnostics.errors[0];throw new Error(u?.message??"Compilation failed")}return c.wgsl}async function It(){let e=["node_modules/.bin/asc","./examples/node_modules/.bin/asc","../app/node_modules/.bin/asc","./node_modules/assemblyscript/bin/asc.js"];for(let n of e)try{if((await De(n)).isFile())return n}catch{}return"asc"}export{rt as a,te as b,ct as c,ut as d,F as e,lt as f,_n as g,Cn as h,dt as i,En as j,Rn as k};
package/dist/compiler.js CHANGED
@@ -1 +1 @@
1
- import{c as a,d as b}from"./chunk-VSCQDCQR.js";import"./chunk-PS4NV6ZB.js";import"./chunk-IZGS3OS2.js";import"./chunk-STDXBN5E.js";export{a as compileAssemblyScriptToWGSL,b as compileWasmToWGSL};
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};
@@ -24,6 +24,7 @@ interface ImportedGlobal {
24
24
  module: string;
25
25
  name: string;
26
26
  type: ValueType;
27
+ mutable: boolean;
27
28
  }
28
29
  interface DefinedGlobal {
29
30
  kind: "definition";
@@ -40,10 +41,16 @@ interface WasmMemory {
40
41
  max?: number;
41
42
  }
42
43
  interface WasmDataSegment {
44
+ mode: "active" | "passive";
43
45
  memoryIndex: number;
44
46
  offset: Instruction[];
45
47
  data: Uint8Array;
46
48
  }
49
+ interface AtomicRegionDescriptor {
50
+ memoryIndex: number;
51
+ offset: number;
52
+ length: number;
53
+ }
47
54
  interface WasmExport {
48
55
  name: string;
49
56
  kind: "func" | "table" | "mem" | "global";
@@ -54,6 +61,10 @@ interface WasmImport {
54
61
  name: string;
55
62
  kind: "func" | "table" | "mem" | "global";
56
63
  typeIndex?: number;
64
+ memoryMin?: number;
65
+ memoryMax?: number;
66
+ globalType?: ValueType;
67
+ globalMutable?: boolean;
57
68
  }
58
69
  interface WasmType {
59
70
  params: ValueType[];
@@ -70,6 +81,11 @@ interface WasmModule {
70
81
  startFunctionIndex?: number;
71
82
  /** Custom sections from the WebAssembly module (for graphics extension metadata) */
72
83
  customSections?: CustomSection[];
84
+ extensions?: string[];
85
+ workgroupSizes?: Map<number, [number, number, number]>;
86
+ atomicRegion?: AtomicRegionDescriptor;
87
+ hasTableSection?: boolean;
88
+ hasElementSection?: boolean;
73
89
  }
74
90
  interface CompileError extends Error {
75
91
  functionName?: string;
@@ -218,10 +234,12 @@ declare function extractDebugInfo(wasmBytes: Uint8Array): DebugInfo;
218
234
  * WGSL mappings, vector dimensions, and validation specs.
219
235
  *
220
236
  * Functions are imported from the "gasm" module with names like:
221
- * - "sin" (scalar f32 -> f32)
237
+ * - "sin_f32" (scalar f32 -> f32)
222
238
  * - "sin_v2f32" (vector vec2<f32> -> vec2<f32>)
223
239
  * - "sin_v3f32" (vector vec3<f32> -> vec3<f32>)
224
- * - "sin_v4f32" (vector vec4<f32> -> vec4<f32>, default for vector ops)
240
+ * - "sin_v4f32" (vector vec4<f32> -> vec4<f32>)
241
+ *
242
+ * Unsuffixed scalar names remain accepted as legacy aliases.
225
243
  */
226
244
 
227
245
  /**
@@ -306,14 +324,13 @@ interface DemotionPolicy {
306
324
  /**
307
325
  * Supported Gasm specification versions.
308
326
  *
309
- * - "0.1": Default, current behavior. See spec/gasm-v0.1.md.
310
- * - "0.2": Opt-in v0.2 mode. See spec/gasm-v0.2.md. Until the v0.2
311
- * conformance suite is complete, v0.2 mode is opt-in and existing
312
- * compile() defaults preserve v0.1 behavior.
327
+ * - "0.1": Compatibility mode for the archived TypeScript-era behavior.
328
+ * - "0.2": Default Rust/Wasm compiler behavior. See spec/gasm-v0.2.md.
313
329
  */
314
330
  type SpecVersion = "0.1" | "0.2";
315
331
  declare const SPEC_VERSION_V01: SpecVersion;
316
332
  declare const SPEC_VERSION_V02: SpecVersion;
333
+ declare const DEFAULT_SPEC_VERSION: SpecVersion;
317
334
  declare function resolveSpecVersion(options?: CompileOptions): SpecVersion;
318
335
  declare function isV02Mode(options?: CompileOptions): boolean;
319
336
  interface CompileOptions {
@@ -377,23 +394,30 @@ interface CompileOptions {
377
394
  /**
378
395
  * Target Gasm specification version.
379
396
  *
380
- * - "0.1" (default): Current v0.1 behavior is preserved for existing callers.
381
- * - "0.2": Opt into v0.2 strict validation and lowering. Until the v0.2
382
- * conformance suite is complete, this mode is intentionally opt-in.
397
+ * - "0.1": Explicit compatibility mode for existing v0.1 callers.
398
+ * - "0.2" (default): Strict v0.2 validation and Rust/Wasm lowering.
383
399
  *
384
- * Setting this to "0.2" implicitly activates strict conformance and any
385
- * additional v0.2-only rules added in subsequent PRs. The default WGSL
386
- * header is NOT changed by this flag in PR-0.
400
+ * Setting this to "0.1" preserves the compatibility escape hatch.
387
401
  */
388
402
  specVersion?: SpecVersion;
389
403
  }
390
- type DiagnosticSeverity = "warning" | "error";
404
+ type DiagnosticSeverity = "advisory" | "warning" | "error";
405
+ interface DiagnosticRecovery {
406
+ action: "add_extension" | "set_spec_version" | "set_demotion_policy" | "use_prepare_module" | "refactor_source";
407
+ extension?: string;
408
+ specVersion?: SpecVersion;
409
+ demotionPolicy?: Partial<DemotionPolicy>;
410
+ docsUrl?: string;
411
+ }
391
412
  interface Diagnostic {
392
413
  severity: DiagnosticSeverity;
393
414
  code: string;
394
415
  message: string;
416
+ recovery?: DiagnosticRecovery;
395
417
  functionIndex?: number;
396
418
  functionName?: string;
419
+ instructionName?: string;
420
+ offset?: number;
397
421
  }
398
422
  interface DemotionEvent {
399
423
  kind: "f64->f32" | "i64->i32-lossy";
@@ -410,12 +434,108 @@ interface FeaturesUsed {
410
434
  usesSimdEmulation: boolean;
411
435
  }
412
436
  interface CompileDiagnostics {
437
+ advisories: Diagnostic[];
413
438
  warnings: Diagnostic[];
414
439
  errors: Diagnostic[];
415
440
  demotions: DemotionEvent[];
416
441
  featuresUsed: FeaturesUsed;
417
442
  }
418
443
 
444
+ type GasmBindingRole = "memory" | "atomic_region" | "imported_global" | "mutable_globals" | "workgroup_memory" | "extension_resource";
445
+ interface GasmBinding {
446
+ group: number;
447
+ binding: number;
448
+ kind: "storage" | "uniform" | "texture" | "sampler";
449
+ rw?: "read" | "read_write" | "write";
450
+ role: GasmBindingRole;
451
+ wasmName?: string;
452
+ wgslName?: string;
453
+ type?: "i32" | "i64" | "f32" | "f64" | "u32" | "vec4<u32>" | "external";
454
+ atomic?: boolean;
455
+ }
456
+ declare function buildBindingTable(module: WasmModule): GasmBinding[];
457
+
458
+ interface GasmMetadata {
459
+ specVersion: SpecVersion;
460
+ extensions: string[];
461
+ memory: {
462
+ sizeBytes: number;
463
+ atomicRegion?: {
464
+ offset: number;
465
+ length: number;
466
+ binding: {
467
+ group: number;
468
+ binding: number;
469
+ };
470
+ } | null;
471
+ workgroupMemoryBytes?: number;
472
+ };
473
+ entryPoints: GasmMetadataEntryPoint[];
474
+ bindings: GasmBinding[];
475
+ dataSegments: GasmMetadataDataSegment[];
476
+ atomicDataSegments?: GasmMetadataDataSegment[];
477
+ passiveDataSegments?: GasmMetadataPassiveDataSegment[];
478
+ mutableGlobals?: Array<{
479
+ index: number;
480
+ name?: string;
481
+ type: "i32" | "i64" | "f32" | "f64";
482
+ offset: number;
483
+ byteLength: number;
484
+ initialValue?: string;
485
+ }>;
486
+ extras?: Record<string, unknown>;
487
+ }
488
+ interface GasmMetadataEntryPoint {
489
+ name: string;
490
+ wgslName: string;
491
+ workgroupSize: [number, number, number];
492
+ }
493
+ interface GasmMetadataDataSegment {
494
+ memory: number;
495
+ offset: number;
496
+ byteLength: number;
497
+ dataB64: string;
498
+ }
499
+ interface GasmMetadataPassiveDataSegment {
500
+ index: number;
501
+ byteLength: number;
502
+ dataB64: string;
503
+ dropped: boolean;
504
+ }
505
+ interface MetadataBuildContext {
506
+ options?: CompileOptions;
507
+ dispatchInfo?: DispatchInfo;
508
+ }
509
+ declare function buildGasmMetadata(module: WasmModule, context?: MetadataBuildContext): GasmMetadata;
510
+ declare function validateGasmMetadataSchema(metadata: unknown): {
511
+ valid: true;
512
+ } | {
513
+ valid: false;
514
+ errors: string[];
515
+ };
516
+ declare function assertCustomSectionsAndMetadataAgree(module: WasmModule, metadata: GasmMetadata): void;
517
+ declare function entryWrapperName(exportName: string): string;
518
+
519
+ type PrepareMode = "integrator" | "strict";
520
+ interface PrepareModuleOptions extends CompileOptions {
521
+ mode?: PrepareMode;
522
+ patchWasm?: boolean;
523
+ }
524
+ interface MutableGlobalsInit {
525
+ byteLength: number;
526
+ data: Uint32Array;
527
+ }
528
+ interface PreparedModule {
529
+ wasmBytes: Uint8Array;
530
+ compileOptions: CompileOptions;
531
+ bindings: GasmBinding[];
532
+ mutableGlobalsInit?: MutableGlobalsInit;
533
+ extensions: string[];
534
+ advisories: Diagnostic[];
535
+ errors: Diagnostic[];
536
+ }
537
+ declare function prepareModule(wasmBytes: Uint8Array, options?: PrepareModuleOptions): PreparedModule;
538
+
419
539
  declare function compile(wasmBytes: Uint8Array): WasmModule | ReturnType<typeof createCompileError>;
420
540
  declare function isCompileError(error: unknown): error is ReturnType<typeof createCompileError>;
421
541
 
@@ -464,4 +584,4 @@ declare const ErrorCodes: {
464
584
  };
465
585
  type ErrorCode = typeof ErrorCodes[keyof typeof ErrorCodes];
466
586
 
467
- export { type CompileDiagnostics as C, type DispatchInfo as D, ErrorCodes as E, type MathIntrinsicSpec as M, type SpecVersion as S, type VectorDimension as V, type WasmModule as W, type CompileOptions as a, type CompileError as b, SPEC_VERSION_V01 as c, SPEC_VERSION_V02 as d, isCompileError$1 as e, compile as f, isCompileError as g, type ErrorCode as h, isV02Mode as i, type MathLevel as j, getIntrinsicsAtLevel as k, getMathSpec as l, getVectorDimension as m, getWgslMapping as n, isMathIntrinsic as o, MATH_INTRINSICS as p, type DebugInfo as q, resolveSpecVersion as r, type SourceLanguage as s, type SourceMappingLevel as t, detectSourceLanguage as u, extractDebugInfo as v, parseNamesSection as w, parseProducersSection as x };
587
+ export { getIntrinsicsAtLevel as A, getMathSpec as B, type CompileDiagnostics as C, type DispatchInfo as D, ErrorCodes as E, getVectorDimension as F, type GasmMetadata as G, getWgslMapping as H, isMathIntrinsic as I, MATH_INTRINSICS as J, type DebugInfo as K, type SourceLanguage as L, type MutableGlobalsInit as M, type SourceMappingLevel as N, detectSourceLanguage as O, type PreparedModule as P, extractDebugInfo as Q, parseNamesSection as R, type SpecVersion as S, parseProducersSection as T, type VectorDimension as V, type WasmModule as W, type GasmBinding as a, type CompileOptions as b, type PrepareModuleOptions as c, type CompileError as d, type DemotionPolicy as e, type Diagnostic as f, type DiagnosticRecovery as g, DEFAULT_SPEC_VERSION as h, isV02Mode as i, SPEC_VERSION_V01 as j, SPEC_VERSION_V02 as k, isCompileError$1 as l, compile as m, isCompileError as n, type ErrorCode as o, prepareModule as p, assertCustomSectionsAndMetadataAgree as q, resolveSpecVersion as r, buildGasmMetadata as s, entryWrapperName as t, type GasmMetadataEntryPoint as u, validateGasmMetadataSchema as v, buildBindingTable as w, type PrepareMode as x, type MathIntrinsicSpec as y, type MathLevel as z };
Binary file
package/dist/mod.d.ts CHANGED
@@ -1,5 +1,5 @@
1
- import { W as WasmModule, C as CompileDiagnostics, D as DispatchInfo, a as CompileOptions } from './error_codes-D6RsiZ33.js';
2
- export { b as CompileError, q as DebugInfo, h as ErrorCode, E as ErrorCodes, p as MATH_INTRINSICS, M as MathIntrinsicSpec, j as MathLevel, c as SPEC_VERSION_V01, d as SPEC_VERSION_V02, s as SourceLanguage, t as SourceMappingLevel, S as SpecVersion, V as VectorDimension, u as detectSourceLanguage, v as extractDebugInfo, k as getIntrinsicsAtLevel, l as getMathSpec, m as getVectorDimension, n as getWgslMapping, e as isCompileError, o as isMathIntrinsic, g as isParseError, i as isV02Mode, w as parseNamesSection, x as parseProducersSection, f as parseWasmModule, r as resolveSpecVersion } from './error_codes-D6RsiZ33.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-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';
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';
@@ -85,10 +85,34 @@ type CompileWithDiagnosticsResult = {
85
85
  ok: false;
86
86
  diagnostics: CompileDiagnostics;
87
87
  };
88
+ type CompileArtifactResult = {
89
+ ok: true;
90
+ wgsl: string;
91
+ metadata: GasmMetadata;
92
+ diagnostics: CompileDiagnostics;
93
+ dispatchInfo: DispatchInfo;
94
+ } | {
95
+ ok: false;
96
+ diagnostics: CompileDiagnostics;
97
+ };
98
+ type CompileWithRuntimeInfoResult = {
99
+ ok: true;
100
+ wgsl: string;
101
+ diagnostics: CompileDiagnostics;
102
+ dispatchInfo: DispatchInfo;
103
+ bindings: GasmBinding[];
104
+ metadata: GasmMetadata;
105
+ mutableGlobalsInit?: PreparedModule["mutableGlobalsInit"];
106
+ } | {
107
+ ok: false;
108
+ diagnostics: CompileDiagnostics;
109
+ };
88
110
  declare function compileWithDiagnostics(wasmBytes: Uint8Array, options?: CompileOptions): CompileWithDiagnosticsResult;
111
+ declare function compileToArtifact(wasmBytes: Uint8Array, options?: CompileOptions): CompileArtifactResult;
112
+ declare function compileWithRuntimeInfo(wasmBytes: Uint8Array, options?: PrepareModuleOptions): CompileWithRuntimeInfoResult;
89
113
  declare function preloadCompiler(): Promise<void>;
90
114
  declare function compileWithDiagnosticsAsync(wasmBytes: Uint8Array, options?: CompileOptions): Promise<CompileWithDiagnosticsResult>;
91
115
  declare function compile(wasmBytes: Uint8Array, options?: CompileOptions): string;
92
116
  declare function compileAsync(wasmBytes: Uint8Array, options?: CompileOptions): Promise<string>;
93
117
 
94
- export { BufferData, CompileDiagnostics, CompileOptions, type CompileWithDiagnosticsResult, DenoGPUExecutor, DispatchInfo, ExecuteOptions, ExecutorConfig, IGPUExecutor, compile, compileAsync, compileWithDiagnostics, compileWithDiagnosticsAsync, disassembleToWAT, preloadCompiler };
118
+ export { BufferData, type CompileArtifactResult, CompileDiagnostics, CompileOptions, type CompileWithDiagnosticsResult, type CompileWithRuntimeInfoResult, DenoGPUExecutor, DispatchInfo, ExecuteOptions, ExecutorConfig, GasmBinding, GasmMetadata, IGPUExecutor, PrepareModuleOptions, PreparedModule, compile, compileAsync, compileToArtifact, compileWithDiagnostics, compileWithDiagnosticsAsync, compileWithRuntimeInfo, disassembleToWAT, preloadCompiler };
package/dist/mod.js CHANGED
@@ -1 +1 @@
1
- import{a as s,b as w,c as x,d as y,e as z,f as A,g as B,h as C,i as D}from"./chunk-VSCQDCQR.js";import{D as o,E as p,F as q,G as r,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-PS4NV6ZB.js";import{a as v}from"./chunk-IZGS3OS2.js";import{a as t,b as u}from"./chunk-STDXBN5E.js";export{v as BrowserGPUExecutor,w as DenoGPUExecutor,d as ErrorCodes,t as ExecutionError,e as MATH_INTRINSICS,o as SPEC_VERSION_V01,p as SPEC_VERSION_V02,C as compile,x as compileAssemblyScriptToWGSL,D as compileAsync,y as compileWasmToWGSL,z as compileWithDiagnostics,B as compileWithDiagnosticsAsync,m as detectSourceLanguage,s as disassembleToWAT,n as extractDebugInfo,j as getIntrinsicsAtLevel,g as getMathSpec,i as getVectorDimension,h as getWgslMapping,a as isCompileError,u as isExecutionError,f as isMathIntrinsic,c as isParseError,r as isV02Mode,k as parseNamesSection,l as parseProducersSection,b as parseWasmModule,A as preloadCompiler,q as resolveSpecVersion};
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};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@gasm-compiler/core",
3
- "version": "0.3.2",
3
+ "version": "0.5.0",
4
4
  "description": "Gasm Compiler — compile WebAssembly to WGSL (WebGPU Shading Language)",
5
5
  "type": "module",
6
6
  "main": "./dist/mod.js",
@@ -43,16 +43,6 @@
43
43
  "LICENSE",
44
44
  "README.md"
45
45
  ],
46
- "scripts": {
47
- "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",
48
- "test": "pnpm --dir ../.. core-rs:build:wasm && GASM_CORE_BACKEND=rust deno test --allow-all",
49
- "test:e2e": "deno test --allow-all --unstable-webgpu --no-check tests/e2e_execution_test.ts",
50
- "test:e2e:gpu": "ENABLE_GPU_TESTS=1 deno test --allow-all --unstable-webgpu --no-check tests/e2e_execution_test.ts",
51
- "lint": "biome lint .",
52
- "prepublishOnly": "pnpm run build",
53
- "size": "pnpm --dir ../.. core-rs:size",
54
- "pack:smoke": "pnpm --dir ../.. core-rs:pack-smoke"
55
- },
56
46
  "license": "SEE LICENSE IN LICENSE",
57
47
  "publishConfig": {
58
48
  "access": "public"
@@ -75,5 +65,14 @@
75
65
  "devDependencies": {
76
66
  "tsup": "^8.5.1",
77
67
  "typescript": "^5.9.3"
68
+ },
69
+ "scripts": {
70
+ "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",
72
+ "test:e2e": "deno test --allow-all --unstable-webgpu --no-check tests/e2e_execution_test.ts",
73
+ "test:e2e:gpu": "ENABLE_GPU_TESTS=1 deno test --allow-all --unstable-webgpu --no-check tests/e2e_execution_test.ts",
74
+ "lint": "biome lint .",
75
+ "size": "pnpm --dir ../.. core-rs:size",
76
+ "pack:smoke": "pnpm --dir ../.. core-rs:pack-smoke"
78
77
  }
79
- }
78
+ }