Commit ·
2a98d06
0
Parent(s):
SpawnGen Studio (only the current build is kept)
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- .gitattributesAdded+93
- 404.htmlAdded+182
- README.mdAdded+48
- SpawnDev.SpawnJS.mztdn6kbtg.lib.module.jsAdded+1542
- _content/SpawnDev.Blazor.BootRecovery/SpawnDev.Blazor.BootRecovery.7rjy3ukk5v.lib.module.jsAdded+83
- _content/SpawnDev.ILGPU/glWorker.jsAdded+1019
- _content/SpawnDev.ILGPU/webgpuDispatchPlan.jsAdded+408
- _framework/BouncyCastle.Cryptography.6qnbenkd0k.wasm.gzAdded+3
- _framework/Concentus.u3fdhpcxzf.wasm.gzAdded+3
- _framework/DnsClient.7sic17ztch.wasm.gzAdded+3
- _framework/ILGPU.33e2ya2ho1.wasm.gzAdded+3
- _framework/ILGPU.Algorithms.yrlf7k7l3q.wasm.gzAdded+3
- _framework/Microsoft.AspNetCore.Components.741isu8jim.wasm.gzAdded+3
- _framework/Microsoft.AspNetCore.Components.Web.cmuc7bdjac.wasm.gzAdded+3
- _framework/Microsoft.AspNetCore.Components.WebAssembly.iea6k79bon.wasm.gzAdded+3
- _framework/Microsoft.Extensions.Configuration.Abstractions.wslsrredsq.wasm.gzAdded+3
- _framework/Microsoft.Extensions.Configuration.Json.dmmcgk01r0.wasm.gzAdded+3
- _framework/Microsoft.Extensions.Configuration.rgjmp347zf.wasm.gzAdded+3
- _framework/Microsoft.Extensions.DependencyInjection.Abstractions.d95iifg76m.wasm.gzAdded+3
- _framework/Microsoft.Extensions.DependencyInjection.mvfec3p7kh.wasm.gzAdded+3
- _framework/Microsoft.Extensions.Logging.5w9ia7xlgq.wasm.gzAdded+3
- _framework/Microsoft.Extensions.Logging.Abstractions.u5liytfkkx.wasm.gzAdded+3
- _framework/Microsoft.Extensions.Options.espvvlqak1.wasm.gzAdded+3
- _framework/Microsoft.Extensions.Primitives.crxdkm6t9l.wasm.gzAdded+3
- _framework/Microsoft.JSInterop.0523xs2ej1.wasm.gzAdded+3
- _framework/Microsoft.JSInterop.WebAssembly.5ql0ra5mpq.wasm.gzAdded+3
- _framework/Microsoft.Win32.Primitives.l7c9kh4jg2.wasm.gzAdded+3
- _framework/Microsoft.Win32.Registry.z3jfhs3ftx.wasm.gzAdded+3
- _framework/SIPSorcery.q0z987ykki.wasm.gzAdded+3
- _framework/SIPSorceryMedia.Abstractions.evfg4tvmuu.wasm.gzAdded+3
- _framework/SpawnDev.BackgroundServices.1yeryblw74.wasm.gzAdded+3
- _framework/SpawnDev.Blazor.BootRecovery.wqj5nz7x99.wasm.gzAdded+3
- _framework/SpawnDev.Codecs.xofv24znhd.wasm.gzAdded+3
- _framework/SpawnDev.EBML.xdne5e0w64.wasm.gzAdded+3
- _framework/SpawnDev.Hive.gqpmdb8qak.wasm.gzAdded+3
- _framework/SpawnDev.ILGPU.ML.Kernels.aaonp64y5i.wasm.gzAdded+3
- _framework/SpawnDev.ILGPU.ML.gl95ev2a6h.wasm.gzAdded+3
- _framework/SpawnDev.ILGPU.s6t0mte45z.wasm.gzAdded+3
- _framework/SpawnDev.MultiMedia.omfwfbvzp1.wasm.gzAdded+3
- _framework/SpawnDev.PatchStreams.fa7qoyfxjz.wasm.gzAdded+3
- _framework/SpawnDev.Phonemizer.14wgzuo4bh.wasm.gzAdded+3
- _framework/SpawnDev.RTC.81gkkaaqp5.wasm.gzAdded+3
- _framework/SpawnDev.SpawnJS.2vggiktbfh.wasm.gzAdded+3
- _framework/SpawnDev.SpawnJS.Blazor.fjgrmuuz8e.wasm.gzAdded+3
- _framework/SpawnDev.SpawnJS.Cryptography.7qr4csn3ju.wasm.gzAdded+3
- _framework/SpawnDev.Swarm.odr4m0zgu9.wasm.gzAdded+3
- _framework/SpawnGen.Editor.k93krt25j7.wasm.gzAdded+3
- _framework/SpawnGen.Engine.thstywld11.wasm.gzAdded+3
- _framework/SpawnGen.Glsl.psh6zi3uqm.wasm.gzAdded+3
- _framework/SpawnGen.Hive.vkttvp8xo4.wasm.gzAdded+3
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293*.7z filter=lfs diff=lfs merge=lfs -text*.arrow filter=lfs diff=lfs merge=lfs -text*.bin filter=lfs diff=lfs merge=lfs -text*.bz2 filter=lfs diff=lfs merge=lfs -text*.ckpt filter=lfs diff=lfs merge=lfs -text*.ftz filter=lfs diff=lfs merge=lfs -text*.gz filter=lfs diff=lfs merge=lfs -text*.h5 filter=lfs diff=lfs merge=lfs -text*.joblib filter=lfs diff=lfs merge=lfs -text*.lfs.* filter=lfs diff=lfs merge=lfs -text*.mlmodel filter=lfs diff=lfs merge=lfs -text*.model filter=lfs diff=lfs merge=lfs -text*.msgpack filter=lfs diff=lfs merge=lfs -text*.npy filter=lfs diff=lfs merge=lfs -text*.npz filter=lfs diff=lfs merge=lfs -text*.onnx filter=lfs diff=lfs merge=lfs -text*.ot filter=lfs diff=lfs merge=lfs -text*.parquet filter=lfs diff=lfs merge=lfs -text*.pb filter=lfs diff=lfs merge=lfs -text*.pickle filter=lfs diff=lfs merge=lfs -text*.pkl filter=lfs diff=lfs merge=lfs -text*.pt filter=lfs diff=lfs merge=lfs -text*.pth filter=lfs diff=lfs merge=lfs -text*.rar filter=lfs diff=lfs merge=lfs -text*.safetensors filter=lfs diff=lfs merge=lfs -textsaved_model/**/* filter=lfs diff=lfs merge=lfs -text*.tar.* filter=lfs diff=lfs merge=lfs -text*.tar filter=lfs diff=lfs merge=lfs -text*.tflite filter=lfs diff=lfs merge=lfs -text*.tgz filter=lfs diff=lfs merge=lfs -text*.wasm filter=lfs diff=lfs merge=lfs -text*.xz filter=lfs diff=lfs merge=lfs -text*.zip filter=lfs diff=lfs merge=lfs -text*.zst filter=lfs diff=lfs merge=lfs -text*tfevents* filter=lfs diff=lfs merge=lfs -text_framework/dotnet.native.rtfjaicvhp.wasm.br filter=lfs diff=lfs merge=lfs -text_framework/icudt_CJK.tjcz0u77k5.dat filter=lfs diff=lfs merge=lfs -text_framework/icudt_CJK.tjcz0u77k5.dat.br filter=lfs diff=lfs merge=lfs -text_framework/icudt_EFIGS.tptq2av103.dat filter=lfs diff=lfs merge=lfs -text_framework/icudt_EFIGS.tptq2av103.dat.br filter=lfs diff=lfs merge=lfs -text_framework/icudt_no_CJK.lfu7j35m59.dat filter=lfs diff=lfs merge=lfs -text_framework/icudt_no_CJK.lfu7j35m59.dat.br filter=lfs diff=lfs merge=lfs -text_framework/ILGPU.hh469695zc.wasm.br filter=lfs diff=lfs merge=lfs -text_framework/SpawnDev.Codecs.4az1el8ia6.wasm.br filter=lfs diff=lfs merge=lfs -text_framework/SpawnDev.EBML.xdne5e0w64.wasm.br filter=lfs diff=lfs merge=lfs -text_framework/SpawnDev.ILGPU.fuxb6lz6el.wasm.br filter=lfs diff=lfs merge=lfs -text_framework/SpawnDev.ILGPU.ML.9usgbtl1ls.wasm.br filter=lfs diff=lfs merge=lfs -text_framework/SpawnDev.ILGPU.ML.Kernels.32rqe3oaz7.wasm.br filter=lfs diff=lfs merge=lfs -text_framework/SpawnDev.MultiMedia.omfwfbvzp1.wasm.br filter=lfs diff=lfs merge=lfs -text_framework/SpawnDev.Phonemizer.14wgzuo4bh.wasm.br filter=lfs diff=lfs merge=lfs -text_framework/SpawnDev.SpawnJS.li761i2n6z.wasm.br filter=lfs diff=lfs merge=lfs -text_framework/SpawnGen.Nodes.Core.b7k44ae8kb.wasm.br filter=lfs diff=lfs merge=lfs -text_framework/SpawnGen.Nodes.ML.ula38wzxn6.wasm.br filter=lfs diff=lfs merge=lfs -text_framework/SpawnGen.Studio.dobkx6cxzg.wasm.br filter=lfs diff=lfs merge=lfs -text_framework/System.Private.CoreLib.jxzjjd418f.wasm.br filter=lfs diff=lfs merge=lfs -text_framework/System.Private.Xml.u94bl2dvp8.wasm.br filter=lfs diff=lfs merge=lfs -text_framework/System.Text.Json.wmn8nrdgsp.wasm.br filter=lfs diff=lfs merge=lfs -text_framework/System.Text.RegularExpressions.5f6os8d0wv.wasm.br filter=lfs diff=lfs merge=lfs -textexamples/example.png filter=lfs diff=lfs merge=lfs -textexamples/example_inpaint.png filter=lfs diff=lfs merge=lfs -text_framework/dotnet.native.a8ztq4aqg2.wasm.br filter=lfs diff=lfs merge=lfs -text_framework/SpawnGen.Nodes.Core.abygs8i0pv.wasm.br filter=lfs diff=lfs merge=lfs -text_framework/SpawnGen.Nodes.ML.rbb9gtli8o.wasm.br filter=lfs diff=lfs merge=lfs -text_framework/SpawnGen.Studio.x6iftgse6j.wasm.br filter=lfs diff=lfs merge=lfs -text_framework/dotnet.native.mm6f5lm5eg.wasm.br filter=lfs diff=lfs merge=lfs -text_framework/SpawnGen.Nodes.Core.dxdnt8bcer.wasm.br filter=lfs diff=lfs merge=lfs -text_framework/SpawnGen.Nodes.ML.c1dhxhtvmm.wasm.br filter=lfs diff=lfs merge=lfs -text_framework/SpawnGen.Studio.q24o3uygaw.wasm.br filter=lfs diff=lfs merge=lfs -text_framework/dotnet.native.81lj8ak7g0.wasm.br filter=lfs diff=lfs merge=lfs -text_framework/SpawnGen.Nodes.Core.euk05e5wt9.wasm.br filter=lfs diff=lfs merge=lfs -text_framework/SpawnGen.Nodes.ML.shgf6ekwmw.wasm.br filter=lfs diff=lfs merge=lfs -text_framework/SpawnGen.Studio.o9zz1ggm9e.wasm.br filter=lfs diff=lfs merge=lfs -text_framework/dotnet.native.6948hfs75e.wasm.br filter=lfs diff=lfs merge=lfs -text_framework/ILGPU.lbeymlaqbz.wasm.br filter=lfs diff=lfs merge=lfs -text_framework/SpawnDev.Codecs.hf0tdrr42b.wasm.br filter=lfs diff=lfs merge=lfs -text_framework/SpawnDev.ILGPU.ML.j1zfb2mr3k.wasm.br filter=lfs diff=lfs merge=lfs -text_framework/SpawnDev.ILGPU.ML.Kernels.391q7al9vs.wasm.br filter=lfs diff=lfs merge=lfs -text_framework/SpawnDev.ILGPU.v7r0292kmo.wasm.br filter=lfs diff=lfs merge=lfs -text_framework/SpawnDev.SpawnJS.7rauvzflz1.wasm.br filter=lfs diff=lfs merge=lfs -text_framework/SpawnGen.Nodes.Core.i10j5fm6p6.wasm.br filter=lfs diff=lfs merge=lfs -text_framework/SpawnGen.Nodes.ML.jwcp2dhqic.wasm.br filter=lfs diff=lfs merge=lfs -text_framework/SpawnGen.Studio.sgcz28bkwh.wasm.br filter=lfs diff=lfs merge=lfs -text_framework/dotnet.native.qa5b69bgaq.wasm.br filter=lfs diff=lfs merge=lfs -text_framework/ILGPU.obaeemdvxg.wasm.br filter=lfs diff=lfs merge=lfs -text_framework/SpawnDev.Codecs.9u5l43fglr.wasm.br filter=lfs diff=lfs merge=lfs -text_framework/SpawnDev.ILGPU.17m3tmnaun.wasm.br filter=lfs diff=lfs merge=lfs -text_framework/SpawnDev.ILGPU.ML.Kernels.hdha89l645.wasm.br filter=lfs diff=lfs merge=lfs -text_framework/SpawnDev.ILGPU.ML.pdvwzvdu6e.wasm.br filter=lfs diff=lfs merge=lfs -text_framework/SpawnDev.SpawnJS.686kwtpghu.wasm.br filter=lfs diff=lfs merge=lfs -text_framework/SpawnGen.Nodes.Core.johaj1vmk0.wasm.br filter=lfs diff=lfs merge=lfs -text_framework/SpawnGen.Nodes.ML.a38jpktpf1.wasm.br filter=lfs diff=lfs merge=lfs -text_framework/SpawnGen.Studio.gq9yb704d0.wasm.br filter=lfs diff=lfs merge=lfs -text_framework/System.Private.CoreLib.fha1ivutny.wasm.br filter=lfs diff=lfs merge=lfs -text123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182<!DOCTYPE html><html lang="en">
<head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>SpawnGen Studio</title> <base href="/" /> <link rel="icon" href="data:," /> <link rel="stylesheet" href="css/app.css" /></head>
<body> <div id="app"> <div class="boot">Loading SpawnGen Studio...</div> </div> <div id="blazor-error-ui"> An unhandled error has occurred. <a href="." class="reload">Reload</a> <span class="dismiss">x</span> </div> <script> // A node dragged out of the library carries its class name. document.addEventListener("dragstart", e => { const n = e.target.closest && e.target.closest("[data-node]"); if (n) { e.dataTransfer.setData("text/spawngen-node", n.dataset.node); e.dataTransfer.effectAllowed = "copy"; } }); // Browser storage for the open workflows (tabs, autosave). It can be missing or full: every call is allowed to fail quietly. window.spawngenStoreGet = function (key) { try { return localStorage.getItem(key); } catch (e) { return null; } }; window.spawngenSetTheme = function (id) { document.documentElement.dataset.theme = id === 'light' ? 'light' : 'dark'; }; // Applied before the app boots, so a light page does not flash dark first. try { window.spawngenSetTheme(JSON.parse(localStorage.getItem('spawngen.settings') || '{}').Palette); } catch (e) { } window.spawngenStoreSet = function (key, value) { try { localStorage.setItem(key, value); return true; } catch (e) { return false; } }; // The workflow library when no server serves the Studio: files in IndexedDB (database spawngen-userdata, store files, {path, text, modified, // created}). Each call is one transaction; results are strings ("done", "exists", "missing") or JSON text. window.spawngenFiles = (function () { let db = null; function open() { return db ??= new Promise((resolve, reject) => { const r = indexedDB.open("spawngen-userdata", 1); r.onupgradeneeded = () => r.result.createObjectStore("files", { keyPath: "path" }); r.onsuccess = () => resolve(r.result); r.onerror = () => { db = null; reject(r.error); }; }); } async function run(mode, body) { const store = (await open()).transaction("files", mode).objectStore("files"); return new Promise((resolve, reject) => { store.transaction.onerror = () => reject(store.transaction.error); body(store, resolve); }); } const get = (store, path, then) => { const r = store.get(path); r.onsuccess = () => then(r.result ?? null); }; return { list: () => run("readonly", (s, done) => { const r = s.getAll(); r.onsuccess = () => done(JSON.stringify(r.result.map(f => ({ path: f.path, size: new Blob([f.text]).size, modified: f.modified })))); }), read: path => run("readonly", (s, done) => get(s, path, f => done(f ? f.text : null))), write: (path, text, overwrite) => run("readwrite", (s, done) => get(s, path, old => { if (old && !overwrite) { done("exists"); return; } const now = Date.now(); s.put({ path, text, modified: now, created: old ? old.created : now }).onsuccess = () => done("done"); })), move: (from, to, overwrite) => run("readwrite", (s, done) => get(s, from, f => { if (!f) { done("missing"); return; } if (from === to) { done("done"); return; } get(s, to, old => { if (old && !overwrite) { done("exists"); return; } s.put({ ...f, path: to }); s.delete(from).onsuccess = () => done("done"); }); })), remove: path => run("readwrite", (s, done) => get(s, path, f => { if (!f) { done("missing"); return; } s.delete(path).onsuccess = () => done("done"); })), }; })(); // Ctrl+O: the toolbar's Open file picker (called while the key press still counts as the user's action). window.spawngenOpenWorkflowFile = function () { const input = document.querySelector('.toolbar input[type=file][accept=".json,.png"]'); if (input) input.click(); }; // Plays an animated picture (Save Animated WEBP / PNG, a GIF) on a canvas of its own, which the node canvas draws every frame: a canvas // drawImage of an animated <img> shows only its first frame (the HTML spec's rule; TJ 2026-11-19: the LTX example's WEBP sat still). // WebCodecs' ImageDecoder decodes one frame at a time, so only one frame is held. Returns null where ImageDecoder is missing; the canvas // stays 0 x 0 for a still picture or a type the browser cannot decode (the caller then shows the <img> as before). window.spawngenAnimate = function (url) { if (typeof ImageDecoder === "undefined") return null; const canvas = document.createElement("canvas"); canvas.width = 0; canvas.height = 0; (async () => { const blob = await (await fetch(url)).blob(); if (!blob.type || !(await ImageDecoder.isTypeSupported(blob.type))) return; const decoder = new ImageDecoder({ data: blob.stream(), type: blob.type }); try { await decoder.tracks.ready; const track = decoder.tracks.selectedTrack; if (!track || !track.animated) return; await decoder.completed; const ctx = canvas.getContext("2d"); for (let index = 0; !canvas.spawngenStop; index = (index + 1) % track.frameCount) { const frame = (await decoder.decode({ frameIndex: index })).image; if (canvas.width !== frame.displayWidth || canvas.height !== frame.displayHeight) { canvas.width = frame.displayWidth; canvas.height = frame.displayHeight; } ctx.drawImage(frame, 0, 0); const ms = frame.duration ? frame.duration / 1000 : 100; frame.close(); await new Promise(r => setTimeout(r, Math.max(16, ms))); } } finally { decoder.close(); } })().catch(e => console.warn("spawngenAnimate", e)); return canvas; }; window.spawngenAnimateStop = function (canvas) { if (canvas) canvas.spawngenStop = true; }; // Saves a picture (a data, blob or same-origin URL) as a file download. window.spawngenDownloadUrl = function (name, url) { const a = document.createElement("a"); a.href = url; a.download = name; document.body.appendChild(a); a.click(); a.remove(); }; // Saves text as a file download (the workflow JSON). window.spawngenDownload = function (name, text) { const url = URL.createObjectURL(new Blob([text], { type: "application/json" })); const a = document.createElement("a"); a.href = url; a.download = name; document.body.appendChild(a); a.click(); a.remove(); setTimeout(() => URL.revokeObjectURL(url), 1000); }; </script> <script src="js/glbviewer.js"></script> <script src="_framework/blazor.webassembly.js" autostart="false"></script> <script> // The site ships ONE copy of each file. gzboot.json (written at deploy time by tools/gzboot.sh; the source's copy lists nothing) says // which runtime files exist only as <name>.gz: all of them on a host that sends files uncompressed (the Hugging Face Space: the AOT // runtime is 91 MB raw, 24 MB gzipped), or the few over a host's file size limit. Those are fetched as .gz and inflated by the // browser's own DecompressionStream; everything else loads the default way (GitHub Pages gzips what it serves by itself). (async function () { let gz = null; try { const r = await fetch('gzboot.json', { cache: 'no-cache' }); if (r.ok) gz = await r.json(); } catch (e) { } const listed = name => !!gz && typeof DecompressionStream !== 'undefined' && (gz.all ? !/\.(js|json)$/.test(name) : (gz.files || []).indexOf(name) >= 0); Blazor.start({ loadBootResource: function (type, name, defaultUri, integrity) { if (type === 'dotnetjs' || type === 'configuration' || type === 'manifest' || !listed(name)) return null; // Our own fetch of a <name>.gz copy, held to what the runtime's own loader gives the other files: // - cache: 'force-cache', the runtime's mode for its fingerprinted files. A wrong answer the browser stored for the // URL (a host's 503 page during an outage) would otherwise be served again on every load; a failed force-cache // request is sent once more past the cache by SpawnDev.Blazor.BootRecovery (dotnet/runtime#135090), which the // Studio references: it covers the runtime's own fetches, and this one because it asks the same way. // - the integrity check, which the runtime's fetch does and a hand-made Response would skip: the inflated bytes // must hash to the file's integrity value. Bytes that do not inflate or do not match (an error page answered // with 200, a damaged upload) are asked for once more, past the cache, and then fail the start as they should. return (async function () { const contentType = type === 'dotnetwasm' ? 'application/wasm' : 'application/octet-stream'; const load = async function (cacheMode) { const r = await fetch(defaultUri + '.gz', { cache: cacheMode }); if (r.status === 404) return null; // no compressed copy after all if (!r.ok) throw new Error('HTTP ' + r.status); // a server that already sent it with Content-Encoding: gzip had the browser inflate it const body = r.headers.get('content-encoding') ? r.body : r.body.pipeThrough(new DecompressionStream('gzip')); const bytes = await new Response(body).arrayBuffer(); if (integrity && integrity.indexOf('sha256-') === 0 && window.crypto && crypto.subtle) { const hash = new Uint8Array(await crypto.subtle.digest('SHA-256', bytes)); let text = ''; for (let i = 0; i < hash.length; i++) text += String.fromCharCode(hash[i]); if ('sha256-' + btoa(text) !== integrity) throw new Error('the file does not match its integrity value'); } return new Response(bytes, { headers: { 'content-type': contentType } }); }; let response; try { response = await load('force-cache'); } catch (e) { console.warn('[boot] ' + name + '.gz did not load (' + (e && e.message) + '): asking again, past the cache'); response = await load('reload'); } return response || fetch(defaultUri, { cache: 'force-cache', integrity: integrity }); // the original })(); } }); })(); </script></body>
</html>123456789101112131415161718192021222324252627282930313233343536373839404142434445464748---title: SpawnGenemoji: 🧩colorFrom: indigocolorTo: purplesdk: staticapp_file: index.htmlpinned: falselicense: mitshort_description: ComfyUI-style node graphs, run on your GPU in the browsertags: - webgpu - comfyui - node-graph - text-to-image - text-to-video - image-to-video - image-to-3d - blazormodels: - stabilityai/sd-turbo - stabilityai/sdxl-turbo - LostBeard/FLUX.2-klein-4B-q4-ILGPU - LostBeard/flux-3-image-klein-q4-ILGPU - Lightricks/LTX-2 - Comfy-Org/Z-Image-Turbo - Comfy-Org/ltx-2 - onnx-community/depth-anything-v2-small - onnx-community/Kokoro-82M-v1.0-ONNX - istupakov/parakeet-tdt-0.6b-v3-onnx - briaai/RMBG-1.4 - Xenova/movenet-singlepose-lightning - salim4n/yolov8n-detect-onnx - Qwen/Qwen3-4B---
# SpawnGen
A ComfyUI-class node-graph studio written in C#, running **entirely in your browser on your GPU** (WebGPU): no server does the inference.ComfyUI workflows and templates open and run as they do in ComfyUI; models download on first use (from Hugging Face) and stay cached inthe browser.
- **Examples**: text to image (SD-Turbo, SD 1.5, FLUX.2 / FLUX 3 Klein), image to image, inpainting, text to video and picture to video (LTX-Video 2B), image to 3D (TRELLIS.2), depth, pose and object detection, background removal, speech.- **Templates**: ComfyUI's template catalog, each marked with what this browser can run.- Needs a browser with WebGPU (Chrome or Edge). Large models need a GPU with enough memory; the first run downloads the weights.
Source: [github.com/LostBeard/SpawnGen](https://github.com/LostBeard/SpawnGen) (MIT). Built on SpawnDev.ILGPU and SpawnDev.ILGPU.ML.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542'strict';
// SpawnJSInterop - the Javascript half of SpawnJS.//// Architecture: every JS value that .Net needs to reference is kept in an id-keyed table// (spawnJSObjects) and addressed from .Net by that numeric id. .Net never receives a live JS object// handle (no Microsoft JSObject), only ids and primitives - which is what lets the .Net side avoid// JSObject and its disposal quirk entirely. .Net "holds" a value (spawnJSObjectHold -> id) and later// "releases" it (spawnJSObjectRelease) so it can be garbage-collected.//// Negative ids are reserved sentinels resolved without a table lookup:// -1 globalThis, -2 undefined, -3 null, -4 the spawnJSObjects table, SpawnJSInterop.//// Calls flow through _spawnJSInteropCall (sync) / _spawnJSInteropCallAsync (async). The whole call - which static// method here, the returnType code (see ReturnType.cs), every argument - is written by .Net onto its call tape// (JSTape.cs) in .Net memory and crosses ONCE: the call reads it straight off the WASM heap and writes the result// back over the same frame. Each call carries its dotnetId and frame address, so nothing here is shared between// .Net instances beyond this class.(function () { if (globalThis.SpawnJSInterop) return; class SpawnJSInterop { // enables verbose logging static verbose = globalThis.spawnJSInteropVerbose; // ArrayBufferView constructors static HeapViewCtors = [ globalThis.BigInt64Array, // 0: BigInt64Array globalThis.BigUint64Array, // 1: BigUInt64Array globalThis.Float16Array, // 2: Float16Array globalThis.Float32Array, // 3: Float32Array globalThis.Float64Array, // 4: Float64Array globalThis.Int16Array, // 5: Int16Array globalThis.Int32Array, // 6: Int32Array globalThis.Int8Array, // 7: Int8Array globalThis.Uint16Array, // 8: Uint16Array globalThis.Uint32Array, // 9: Uint32Array globalThis.Uint8Array, // 10: Uint8Array globalThis.Uint8ClampedArray, // 11: Uint8ClampedArray globalThis.DataView // 12: DataView ]; static _revivers = []; static _replacers = []; // method names for index based calling as an alternative to string static _methodMapNames = []; // methods mapped by index for index based calling as an alternative to string static _methodMap = []; // The id -> JS value table. Holds every value .Net currently references. static spawnJSObjects = {}; // Monotonic id source; never reused, so a stale .Net id can never collide with a live value. static _sjsObjectIdNext = 0; // .Net Wasm app instance infos static _instances = {}; // .Net callbacks static _callbacks = {}; static _detachedSentinelId = null; // static constructor static { // SpawnJSInterop.registerReviver('__reviverTest', (key, value) => { // if (SpawnJSInterop.verbose) console.log('[SpawnJSInterop] reviver test', key, value); // return value; // }); // SpawnJSInterop.registerReplacer('__replacerTest', (key, value) => { // if (SpawnJSInterop.verbose) console.log('[SpawnJSInterop] replacer test', key, value); // return value; // }); SpawnJSInterop.refreshMethodMap(); // detachedHeap sentinel this._detachedSentinelId = setInterval(() => SpawnJSInterop.detachedEventCheck(), 500); }
// JSImports // Methods accessed via JSImport only send and recieve basic // data types and are used to support the marshalling framework // that allows working with much more advanced data types.
// JSImport // double _registerInstance( // JSObject dotnetInstance, // [JSMarshalAs<JSType.Function>] Action onMethodAdded, // [JSMarshalAs<JSType.Function<JSType.Number, JSType.String>>] Action<double, string> onAsyncResolvedVoid, // [JSMarshalAs<JSType.Function<JSType.Number, JSType.Number, JSType.String>>] Action<double, double, string> onAsyncResolvedDouble, // [JSMarshalAs<JSType.Function<JSType.Number, JSType.Boolean, JSType.String>>] Action<double, bool, string> onAsyncResolvedBool, // [JSMarshalAs<JSType.Function<JSType.Number, JSType.String, JSType.String>>] Action<double, string, string> onAsyncResolvedString, // [JSMarshalAs<JSType.Function<JSType.Number, JSType.Any, JSType.String>>] Action<double, object, string> onAsyncResolvedDoubleNullable, // [JSMarshalAs<JSType.Function<JSType.Number, JSType.Any, JSType.String>>] Action<double, object, string> onAsyncResolvedBooleanNullable, // [JSMarshalAs<JSType.Function<JSType.Number, JSType.Number, JSType.String>>] Action<double, int, string> onAsyncResolvedInt32, // [JSMarshalAs<JSType.Function<JSType.Number, JSType.Any, JSType.String>>] Action<double, object, string> onAsyncResolvedInt32Nullable, // [JSMarshalAs<JSType.Function<JSType.Number, JSType.Number>>] Action<long, long> onDetachedHeap, // [JSMarshalAs<JSType.Function<JSType.Number, JSType.Number, JSType.Number>>] Action<double, double, double> onCallback, // [JSMarshalAs<JSType.Function<JSType.Number, JSType.Number, JSType.String>>] Action<double, int, string> onAsyncResolvedTape) static _registerInstance( dotnet, onMethodAdded, resolveVoid, resolveDouble, resolveBoolean, resolveString, resolveDoubleNullable, resolveBooleanNullable, resolveInt32, resolveInt32Nullable, onDetachedHeap, handleCallback, resolveTape ) { if (!dotnet) throw new Error('dotnet not set'); var instanceInfo = SpawnJSInterop._getInstaceFromDotNet(dotnet); if (instanceInfo) return instanceInfo.dotnetId;
var dotnetId = SpawnJSInterop.spawnJSObjectHold(dotnet);
// attach the heap buffer to instanceInfo so it can be monitored for detach events var heapBuffer = SpawnJSInterop.wasmMemoryBuffer(dotnet);
var instanceInfo = { heapBuffer, dotnet, dotnetId, onMethodAdded, resolveVoid, resolveDouble, resolveBoolean, resolveString, resolveDoubleNullable, resolveBooleanNullable, resolveInt32, resolveInt32Nullable, handleCallback, onDetachedHeap, resolveTape }; SpawnJSInterop._instances[dotnetId] = instanceInfo;
instanceInfo.heapBufferSize = heapBuffer.byteLength; instanceInfo.getHeap = () => { if (instanceInfo.heapBuffer.detached) { if (SpawnJSInterop.verbose) console.log(`Detached heap detected for: ${dotnetId}`); // get the new heap buffer instanceInfo.heapBuffer = SpawnJSInterop.wasmMemoryBuffer(dotnet); const oldSize = instanceInfo.heapBufferSize; instanceInfo.heapBufferSize = instanceInfo.heapBuffer.byteLength; // notify the instance instanceInfo.onDetachedHeap(oldSize, instanceInfo.heapBuffer.byteLength); } return instanceInfo.heapBuffer; };
if (SpawnJSInterop.verbose) console.log('[SpawnJSInterop] Instance registered', instanceInfo); return dotnetId; } // Call tape value tags - JSTape.Tag* in JSTape.cs must match static TapeTag = { Undefined: 0, Null: 1, Number: 2, Boolean: 3, String: 4, Ref: 5, Callback: 6, Absent: 8, Object: 9, Shape: 10, Array: 11, Numbers: 12, HeapView: 13, Record: 14, Revive: 15 }; // TagNumbers kinds - JSTape.NumberKind must match static TapeNumberCtors = [Int8Array, Uint8Array, Int16Array, Uint16Array, Int32Array, Uint32Array, Float32Array, Float64Array]; // what a member written as TagAbsent reads as: the property is not assigned static _tapeAbsent = Object.freeze({});
// Main .Net to JS entrypoint (synchronous) // The frame at address holds the whole call (see JSTape.cs). The result is written back over the frame and // the return value is its byte length - or minus the bytes it needs when it does not fit in capacity, in // which case it is kept on the instance for _spawnJSInteropCallResult. // JSImport // int _spawnJSInteropCall(double dotnetId, double address, int length, int capacity); static _spawnJSInteropCall(dotnetId, address, length, capacity) { // no detachedEventCheck(): _tapeViews checks this instance's heap, and walking every OTHER instance on // every call was redundant - each is checked on its own calls and by the 500 ms timer var instance = SpawnJSInterop.getInstace(dotnetId); var call = SpawnJSInterop._tapeReadCall(instance, address, length, dotnetId); var ret = call.target(...call.args); ret = SpawnJSInterop.replaceValue(null, ret, false); return SpawnJSInterop._tapeWriteResult(instance, call.returnType, ret, address, capacity); } // The result that did not fit behind its frame // JSImport // int _spawnJSInteropCallResult(double dotnetId, double address, int capacity); static _spawnJSInteropCallResult(dotnetId, address, capacity) { var instance = SpawnJSInterop.getInstace(dotnetId); var bytes = instance.tapePendingResult; instance.tapePendingResult = undefined; if (!bytes) throw new Error('SpawnJSInterop: no tape result is being held'); if (bytes.byteLength > capacity) throw new Error(`SpawnJSInterop: a held tape result of ${bytes.byteLength} bytes does not fit in ${capacity}`); var views = SpawnJSInterop._tapeViews(instance, address + bytes.byteLength); new Uint8Array(views.buffer, address, bytes.byteLength).set(bytes); return bytes.byteLength; } // Main .Net to JS entrypoint (asynchronous) // Reads the frame and starts the call before returning, because .Net releases the frame as soon as this returns. // Returns 1 when the frame was read and the call started, 0 when it could not be read - that failure has already // gone to the resolver, so the awaiting Task fails rather than hanging. // JSImport // int _spawnJSInteropCallAsync(double dotnetId, double asyncCallId, double address, int length); static _spawnJSInteropCallAsync(dotnetId, asyncCallId, address, length) { var instance = SpawnJSInterop.getInstace(dotnetId); var returnType = SpawnJSInterop._tapeViews(instance, address + length).f64[(address >>> 3) + 1]; var call; try { call = SpawnJSInterop._tapeReadCall(instance, address, length, dotnetId); } catch (ex) { SpawnJSInterop._resolveAsync(instance, returnType, asyncCallId, null, SpawnJSInterop.errorToString(ex)); return 0; } SpawnJSInterop._runAsync(instance, returnType, asyncCallId, call); return 1; } static async _runAsync(instance, returnType, asyncCallId, call) { var error = null; var ret = null; var heldBytes = -1; try { ret = call.target(...call.args); ret = await ret; ret = SpawnJSInterop.replaceValue(null, ret, false); if (returnType > 10) { // a composite schema: encoded here and held; .Net fetches it with _spawnJSInteropCallResult heldBytes = SpawnJSInterop._tapeHoldResult(instance, SpawnJSInterop._tapeSchema(instance, returnType), ret); } else { // prepare using returnType ret = SpawnJSInterop._serializeToNet(returnType, ret); } } catch (ex) { error = SpawnJSInterop.errorToString(ex); ret = null; } if (heldBytes >= 0) instance.resolveTape(asyncCallId, heldBytes, null); else SpawnJSInterop._resolveAsync(instance, returnType, asyncCallId, ret, error); } static _resolveAsync(instance, returnType, asyncCallId, ret, error) { if (returnType > 10) { // a composite schema that failed: nothing is held instance.resolveTape(asyncCallId, 0, error ?? 'SpawnJSInterop: the call produced no result'); return; } switch (returnType) { case 0: // void instance.resolveVoid(asyncCallId, error); break; case 1: // Double instance.resolveDouble(asyncCallId, ret, error); break; case 2: // Boolean instance.resolveBoolean(asyncCallId, ret, error); break; case 3: // DoubleNullable instance.resolveDoubleNullable(asyncCallId, ret, error); break; case 4: // BooleanNullable instance.resolveBooleanNullable(asyncCallId, ret, error); break; case 5: // String instance.resolveString(asyncCallId, ret, error); break; case 6: // SpawnJSObject instance.resolveDouble(asyncCallId, ret, error); break; case 7: // SpawnJSObjectNonNullable instance.resolveDouble(asyncCallId, ret, error); break; case 8: // Json instance.resolveString(asyncCallId, ret, error); break; case 9: // Int32 instance.resolveInt32(asyncCallId, ret, error); break; case 10: // Int32Nullable instance.resolveInt32Nullable(asyncCallId, ret, error); break; default: throw new Error(`Unsupported returnType ${returnType}`); break; } } // The heap views a tape is read through. Kept on the instance - never a page global - and rebuilt when the // heap buffer changes: growth detaches it, and a shared (threaded) heap's buffer does not detach but can be // shorter than the memory, so end is checked too. static _tapeViews(instance, end) { var buffer = instance.getHeap(); if (buffer.byteLength < end) { buffer = instance.heapBuffer = SpawnJSInterop.wasmMemoryBuffer(instance.dotnet); instance.heapBufferSize = buffer.byteLength; } var views = instance.tapeViews; if (!views || views.buffer !== buffer) { views = instance.tapeViews = { buffer, f64: new Float64Array(buffer), i32: new Int32Array(buffer), u16: new Uint16Array(buffer) }; } return views; } // Reads a call frame: header, then one tagged value per argument, each passed through the revivers as the // v2 argument array was. static _tapeReadCall(instance, address, length, dotnetId) { var views = SpawnJSInterop._tapeViews(instance, address + length); var f64 = views.f64; var p = address >>> 3; var methodIndex = f64[p]; var returnType = f64[p + 1]; var argCount = f64[p + 2]; // one reader per call: a nested call (a reviver can run .Net) gets its own var reader = { instance, dotnetId, address, length, views, p: p + 3 }; var args = new Array(argCount); for (var i = 0; i < argCount; i++) { var value = SpawnJSInterop._tapeRead(reader); args[i] = SpawnJSInterop.reviveValue(i, value === SpawnJSInterop._tapeAbsent ? undefined : value, false); } // then the definitions of any schema the result is written by (JSTape.WriteSchemaDefinitions) var end = (address + length) >>> 3; while (reader.p < end) SpawnJSInterop._tapeReadSchemaDefinition(reader); var target = SpawnJSInterop._methodMap[methodIndex]; if (!target) throw new Error(`SpawnJSInterop: no method at index ${methodIndex}`); return { target, returnType, args }; } // Reads one tagged value at reader.p and advances it. Object members and array elements go through the // revivers with their key, as v2's per-property set did. static _tapeRead(reader) { // a reviver can run .Net (a heap view refresh reports the detach), which can grow the heap if (reader.views.buffer.detached) reader.views = SpawnJSInterop._tapeViews(reader.instance, reader.address + reader.length); var f64 = reader.views.f64; var tag = f64[reader.p++]; switch (tag) { case 0: return undefined; case 1: return null; case 2: return f64[reader.p++]; case 3: return f64[reader.p++] !== 0; case 4: return SpawnJSInterop._tapeReadChars(reader); case 5: return SpawnJSInterop.spawnJSObjectGet(f64[reader.p++]); case 6: { var callbackId = f64[reader.p++]; var once = f64[reader.p++] !== 0; // the schemas its arguments are written by (defined after this frame's arguments when new) var argumentCount = f64[reader.p++]; var argumentSchemas = new Array(argumentCount); for (var i = 0; i < argumentCount; i++) argumentSchemas[i] = f64[reader.p++]; return SpawnJSInterop._callbackFunction(reader.dotnetId, callbackId, once, argumentSchemas); } case 8: return SpawnJSInterop._tapeAbsent; case 9: { var names = reader.instance.tapeShapes?.[f64[reader.p]]; if (!names) throw new Error(`SpawnJSInterop: unknown tape shape ${f64[reader.p]}`); reader.p++; var obj = {}; for (var i = 0; i < names.length; i++) { var value = SpawnJSInterop._tapeRead(reader); if (value !== SpawnJSInterop._tapeAbsent) obj[names[i]] = SpawnJSInterop.reviveValue(names[i], value, false); } return obj; } case 10: { // a shape definition - kept per instance, since each runtime numbers its own - then the value it // precedes. The same definition can arrive again until .Net knows a call carrying it completed. var shapeId = f64[reader.p++]; var count = f64[reader.p++]; var names = new Array(count); for (var i = 0; i < count; i++) names[i] = SpawnJSInterop._tapeReadChars(reader); (reader.instance.tapeShapes ??= [])[shapeId] = names; return SpawnJSInterop._tapeRead(reader); } case 11: { var count = f64[reader.p++]; var array = new Array(count); for (var i = 0; i < count; i++) { var value = SpawnJSInterop._tapeRead(reader); array[i] = SpawnJSInterop.reviveValue(i, value === SpawnJSInterop._tapeAbsent ? undefined : value, false); } return array; } case 12: { var ctor = SpawnJSInterop.TapeNumberCtors[f64[reader.p++]]; var count = f64[reader.p++]; var view = new ctor(reader.views.buffer, reader.p * 8, count); reader.p += (count * ctor.BYTES_PER_ELEMENT + 7) >>> 3; // a plain Array, as element-by-element writing produced; a TypedArray stays opt in return Array.from(view); } case 14: { var count = reader.views.f64[reader.p++]; var record = {}; for (var i = 0; i < count; i++) { var key = SpawnJSInterop._tapeReadChars(reader); var value = SpawnJSInterop._tapeRead(reader); record[key] = SpawnJSInterop.reviveValue(key, value === SpawnJSInterop._tapeAbsent ? undefined : value, false); } return record; } case 15: { var reviver = SpawnJSInterop._methodMap[reader.views.f64[reader.p++]]; if (!reviver) throw new Error('SpawnJSInterop: tape reviver not found'); // (key, value, directCall) - the v2 property reviver convention; there is no property key here return reviver(null, SpawnJSInterop._tapeRead(reader), true); } case 13: { var f = reader.views.f64; var viewType = f[reader.p], offset = f[reader.p + 1], count = f[reader.p + 2], copy = f[reader.p + 3] !== 0; reader.p += 4; return SpawnJSInterop._heapView(reader.dotnetId, viewType, offset, count, copy); } default: throw new Error(`SpawnJSInterop: unknown tape tag ${tag} at cell ${reader.p - 1}`); } } // length, then UTF-16 code units padded to a cell static _tapeReadChars(reader) { var length = reader.views.f64[reader.p++]; var value = SpawnJSInterop._tapeString(reader.views.u16, reader.p * 4, length); reader.p += (length + 3) >>> 2; return value; } // String.fromCharCode keeps every UTF-16 code unit exactly - a lone surrogate included, which a TextDecoder // would replace. Chunked, because apply() has an argument count limit. static _tapeString(u16, index, length) { if (length <= 1024) return String.fromCharCode.apply(null, u16.subarray(index, index + length)); var parts = []; for (var i = 0; i < length; i += 1024) { parts.push(String.fromCharCode.apply(null, u16.subarray(index + i, index + Math.min(i + 1024, length)))); } return parts.join(''); } // ---- results: written back by the schema .Net reads them with (JSSchema.cs, JSTapeReader.cs) ---- // Ids 0-10 are the built-in ReturnType kinds; composite schemas are defined per instance, after a call's arguments. static _builtinSchemas = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10].map(kind => Object.freeze({ kind })); // thrown by a writer over .Net memory that is out of room (only a string can be; it is written again) static _tapeOverflow = Object.freeze({ tapeOverflow: true }); static _tapeSchema(instance, id) { if (id <= 10) return SpawnJSInterop._builtinSchemas[id]; var schema = instance.tapeSchemas?.[id]; if (!schema) throw new Error(`SpawnJSInterop: unknown tape schema ${id}`); return schema; } // TagSchema, id, kind, then per kind - member / element schemas are ids, resolved when a value is written, so a // schema can refer to one defined after it, or to itself static _tapeReadSchemaDefinition(reader) { if (reader.views.buffer.detached) reader.views = SpawnJSInterop._tapeViews(reader.instance, reader.address + reader.length); var f64 = reader.views.f64; var tag = f64[reader.p++]; if (tag !== 16) throw new Error(`SpawnJSInterop: expected a tape schema definition, found tag ${tag}`); var id = f64[reader.p++]; var schema = { kind: f64[reader.p++] }; switch (schema.kind) { case 16: { var count = f64[reader.p++]; schema.names = new Array(count); for (var i = 0; i < count; i++) schema.names[i] = SpawnJSInterop._tapeReadChars(reader); schema.members = new Array(count); for (var i = 0; i < count; i++) schema.members[i] = reader.views.f64[reader.p++]; break; } case 20: { var count = f64[reader.p++]; schema.members = new Array(count); for (var i = 0; i < count; i++) schema.members[i] = f64[reader.p++]; break; } case 17: case 19: schema.element = f64[reader.p++]; break; case 18: schema.numberKind = f64[reader.p++]; break; } (reader.instance.tapeSchemas ??= [])[id] = schema; } // Writes a call's result back over its own frame. A built-in kind goes straight into .Net memory (only a string // can outgrow the frame's segment); a composite is written into Javascript memory first, then copied - it can // hold references and run getters, so it is written exactly once. A result that does not fit is held for // _spawnJSInteropCallResult, and the return value is minus its size. static _tapeWriteResult(instance, schemaId, ret, address, capacity) { var schema = SpawnJSInterop._tapeSchema(instance, schemaId); if (schema.kind === 0) return 0; if (schemaId <= 10) { var views = SpawnJSInterop._tapeViews(instance, address + capacity); var w = { buffer: views.buffer, f64: views.f64, i32: views.i32, u16: views.u16, p: address >>> 3, end: (address + capacity) >>> 3, scratch: false }; try { SpawnJSInterop._tapeEncode(instance, w, schema, ret); return (w.p - (address >>> 3)) * 8; } catch (ex) { if (ex !== SpawnJSInterop._tapeOverflow) throw ex; } } var s = SpawnJSInterop._tapeScratchWriter(instance); try { SpawnJSInterop._tapeEncode(instance, s, schema, ret); var bytes = s.p * 8; if (bytes <= capacity) { var heap = SpawnJSInterop._tapeViews(instance, address + bytes); new Uint8Array(heap.buffer, address, bytes).set(new Uint8Array(s.buffer, 0, bytes)); return bytes; } instance.tapePendingResult = new Uint8Array(s.buffer.slice(0, bytes)); return -bytes; } finally { SpawnJSInterop._tapeScratchRelease(instance, s); } } // encodes a result and holds it for _spawnJSInteropCallResult; returns its size static _tapeHoldResult(instance, schema, value) { var s = SpawnJSInterop._tapeScratchWriter(instance); try { SpawnJSInterop._tapeEncode(instance, s, schema, value); instance.tapePendingResult = new Uint8Array(s.buffer.slice(0, s.p * 8)); return s.p * 8; } finally { SpawnJSInterop._tapeScratchRelease(instance, s); } } // Javascript-side result buffers, pooled per instance (a nested call's result uses its own) static _tapeScratchWriter(instance) { var w = instance.tapeScratch?.pop(); if (!w) { w = { scratch: true, p: 0 }; SpawnJSInterop._tapeScratchResize(w, 512); } w.p = 0; return w; } static _tapeScratchRelease(instance, w) { // a very large one is dropped rather than kept for the life of the page if (w.end <= 1 << 20) (instance.tapeScratch ??= []).push(w); } static _tapeScratchResize(w, cells) { var buffer = new ArrayBuffer(cells * 8); if (w.buffer) new Uint8Array(buffer).set(new Uint8Array(w.buffer, 0, w.p * 8)); w.buffer = buffer; w.f64 = new Float64Array(buffer); w.i32 = new Int32Array(buffer); w.u16 = new Uint16Array(buffer); w.end = cells; } static _tapeNeed(w, cells) { if (w.p + cells <= w.end) return; if (!w.scratch) throw SpawnJSInterop._tapeOverflow; SpawnJSInterop._tapeScratchResize(w, Math.max(w.end * 2, w.p + cells)); } // One value by its schema. The built-in kinds convert exactly as v2's typed returns did: null/undefined read // as 0 / false, a number is stored through a Float64Array (ToNumber) and an int through an Int32Array (ToInt32). // A composite reads each member / element with that member's schema - what v2's per-property Get<T> read. static _tapeEncode(instance, w, schema, v) { var isNull = v === null || v === undefined; switch (schema.kind) { case 0: return; case 1: SpawnJSInterop._tapeNeed(w, 1); w.f64[w.p++] = isNull ? 0 : v; return; case 2: SpawnJSInterop._tapeNeed(w, 1); w.f64[w.p++] = v ? 1 : 0; return; case 3: if (isNull) { SpawnJSInterop._tapeNeed(w, 1); w.f64[w.p++] = 1; return; } SpawnJSInterop._tapeNeed(w, 2); w.f64[w.p++] = 2; w.f64[w.p++] = v; return; case 4: if (isNull) { SpawnJSInterop._tapeNeed(w, 1); w.f64[w.p++] = 1; return; } SpawnJSInterop._tapeNeed(w, 2); w.f64[w.p++] = 3; w.f64[w.p++] = v ? 1 : 0; return; case 5: if (!isNull && typeof v !== 'string') v = Object(v).toString(); SpawnJSInterop._tapeEncodeString(w, isNull ? null : v); return; case 6: case 7: SpawnJSInterop._tapeNeed(w, 1); w.f64[w.p++] = SpawnJSInterop.spawnJSObjectHold(v); return; case 8: SpawnJSInterop._tapeEncodeString(w, JSON.stringify(v)); return; case 9: SpawnJSInterop._tapeNeed(w, 1); w.i32[w.p * 2] = isNull ? 0 : v; w.p++; return; case 10: if (isNull) { SpawnJSInterop._tapeNeed(w, 1); w.f64[w.p++] = 1; return; } SpawnJSInterop._tapeNeed(w, 2); w.f64[w.p] = 2; w.i32[(w.p + 1) * 2] = v; w.p += 2; return; case 16: { if (isNull) { SpawnJSInterop._tapeNeed(w, 1); w.f64[w.p++] = 1; return; } SpawnJSInterop._tapeNeed(w, 1); w.f64[w.p++] = 9; var names = schema.names, members = schema.members; for (var i = 0; i < names.length; i++) SpawnJSInterop._tapeEncode(instance, w, SpawnJSInterop._tapeSchema(instance, members[i]), v[names[i]]); return; } case 17: { if (isNull) { SpawnJSInterop._tapeNeed(w, 1); w.f64[w.p++] = 1; return; } var count = Number(v.length) || 0; SpawnJSInterop._tapeNeed(w, 2); w.f64[w.p++] = 11; w.f64[w.p++] = count; var element = SpawnJSInterop._tapeSchema(instance, schema.element); for (var i = 0; i < count; i++) SpawnJSInterop._tapeEncode(instance, w, element, v[i]); return; } case 18: { if (isNull) { SpawnJSInterop._tapeNeed(w, 1); w.f64[w.p++] = 1; return; } var count = Number(v.length) || 0; var int32 = schema.numberKind === 9; var cells = int32 ? (count + 1) >>> 1 : count; SpawnJSInterop._tapeNeed(w, 2 + cells); w.f64[w.p++] = 12; w.f64[w.p++] = count; // element by element, not typedArray.set(): an undefined element must read as 0, as Get<T> read it if (int32) { var view = new Int32Array(w.buffer, w.p * 8, count); for (var i = 0; i < count; i++) { var e = v[i]; view[i] = e === null || e === undefined ? 0 : e; } } else { var view = new Float64Array(w.buffer, w.p * 8, count); for (var i = 0; i < count; i++) { var e = v[i]; view[i] = e === null || e === undefined ? 0 : e; } } w.p += cells; return; } case 19: { if (isNull) { SpawnJSInterop._tapeNeed(w, 1); w.f64[w.p++] = 1; return; } // own enumerable keys - inherited ones belong to the prototype chain, not the record var keys = Object.keys(v); SpawnJSInterop._tapeNeed(w, 2); w.f64[w.p++] = 14; w.f64[w.p++] = keys.length; var element = SpawnJSInterop._tapeSchema(instance, schema.element); for (var i = 0; i < keys.length; i++) { SpawnJSInterop._tapeEncodeChars(w, keys[i]); SpawnJSInterop._tapeEncode(instance, w, element, v[keys[i]]); } return; } case 20: { if (isNull) { SpawnJSInterop._tapeNeed(w, 1); w.f64[w.p++] = 1; return; } var members = schema.members; SpawnJSInterop._tapeNeed(w, 2); w.f64[w.p++] = 11; w.f64[w.p++] = members.length; for (var i = 0; i < members.length; i++) SpawnJSInterop._tapeEncode(instance, w, SpawnJSInterop._tapeSchema(instance, members[i]), v[i]); return; } case 21: { if (isNull) { SpawnJSInterop._tapeNeed(w, 1); w.f64[w.p++] = 1; return; } var bytes = v instanceof ArrayBuffer ? new Uint8Array(v) : ArrayBuffer.isView(v) ? new Uint8Array(v.buffer, v.byteOffset, v.byteLength) : null; if (!bytes) throw new TypeError('SpawnJSInterop: expected an ArrayBuffer or ArrayBufferView'); var cells = (bytes.length + 7) >>> 3; SpawnJSInterop._tapeNeed(w, 2 + cells); w.f64[w.p++] = 12; w.f64[w.p++] = bytes.length; new Uint8Array(w.buffer, w.p * 8, bytes.length).set(bytes); w.p += cells; return; } } throw new Error(`SpawnJSInterop: unsupported tape schema kind ${schema.kind}`); } // null, or tag, length, UTF-16 code units static _tapeEncodeString(w, value) { if (value === null || value === undefined) { SpawnJSInterop._tapeNeed(w, 1); w.f64[w.p++] = 1; return; } SpawnJSInterop._tapeNeed(w, 1); w.f64[w.p++] = 4; SpawnJSInterop._tapeEncodeChars(w, value); } // length, UTF-16 code units padded to a cell static _tapeEncodeChars(w, value) { var length = value.length; SpawnJSInterop._tapeNeed(w, 1 + ((length + 3) >>> 2)); w.f64[w.p++] = length; var u16 = w.u16; var index = w.p * 4; for (var i = 0; i < length; i++) u16[index + i] = value.charCodeAt(i); w.p += (length + 3) >>> 2; } // refreshes the method map by looking for any new methods and adds them // JSImport // string[] _refreshMethodMap(); static refreshMethodMap() { var changed = false; var keys = Reflect.ownKeys(SpawnJSInterop); for (const pName of keys) { if (SpawnJSInterop._methodMapNames.indexOf(pName) !== -1) continue; var propVal = SpawnJSInterop[pName]; if (typeof propVal === 'function') { var fn = propVal.bind(SpawnJSInterop); changed = true; SpawnJSInterop._methodMap.push(fn); SpawnJSInterop._methodMapNames.push(pName); if (pName.indexOf('__reviver') === 0) { SpawnJSInterop._revivers.push(fn); } else if (pName.indexOf('__replacer') === 0) { SpawnJSInterop._replacers.push(fn); } } } if (changed) { // notify existing instances for (const dotnetIdExisting in SpawnJSInterop._instances) { if (Object.hasOwn(SpawnJSInterop._instances, dotnetIdExisting)) { var existingInfo = SpawnJSInterop._instances[dotnetIdExisting]; try { existingInfo.onMethodAdded(); } catch { } } } } return SpawnJSInterop._methodMapNames; } // JSImport // void _releaseCallback(double dotnetId, double callbackId); static releaseCallback(dotnetId, callbackId) { var callbackIdPair = `${dotnetId}_${callbackId}`; delete SpawnJSInterop._callbacks[callbackIdPair]; } // removes the object from the hold and returns it // JSImport // void SpawnJSObjectRelease(double sjsId); // bool SpawnJSObjectReleaseBoolean(double sjsId); // double SpawnJSObjectReleaseDouble(double sjsId); // int SpawnJSObjectReleaseInt32(double sjsId); // bool? SpawnJSObjectReleaseBooleanNullable(double sjsId); // int? SpawnJSObjectReleaseInt32Nullable(double sjsId); // double? SpawnJSObjectReleaseDoubleNullable(double sjsId); static spawnJSObjectRelease(sjsId) { var ret = SpawnJSInterop.spawnJSObjectGet(sjsId); delete SpawnJSInterop.spawnJSObjects[sjsId]; if (SpawnJSInterop.verbose) console.log('spawnJSObjectRelease. Count:', Object.keys(SpawnJSInterop.spawnJSObjects).length, 'Id:', sjsId); return ret; } // removes the object from the hold, JSON.stringifies it and returns it // JSImport // string SpawnJSObjectReleaseJson(double sjsId); static spawnJSObjectReleaseAsJson(sjsId) { var ret = SpawnJSInterop.spawnJSObjectGet(sjsId); delete SpawnJSInterop.spawnJSObjects[sjsId]; return JSON.stringify(ret); } // returns true if the item id exists in the hold // JSImport // bool SpawnJSObjectHoldExists(double sjsId); static spawnJSObjectHoldExists(sjsId) { switch (sjsId) { case -1: return true; case -2: return true; case -3: return true; case -4: return true; case -5: return true; } return sjsId in SpawnJSInterop.spawnJSObjects; } // returns string // JSImport // string _getTypeInfo(double sjsId); static getTypeInfo(sjsId) { var obj = SpawnJSInterop.spawnJSObjectGet(sjsId); var jsClass = Object.prototype.toString.call(obj).split(' ')[1].slice(0, -1); var jsType = typeof (obj); return `${jsType} ${jsClass}`; }
// ************************************************************************************** // SpawnJSObjectReference imports // Note: only `string key` imports shown. Also exists: `double key`, `int key` // **************************************************************************************
// property info // returns string or null if the property was not found // JSImport // string _propertyTypeInfo(double sjsId, string key); static propertyTypeInfo(sjsId, key) { var obj = SpawnJSInterop.spawnJSObjectGet(sjsId); var { parent, propertyName, shortCircuit } = SpawnJSInterop.pathObjectInfo(obj, key); if (shortCircuit) return null; if (!SpawnJSInterop._in(propertyName, parent)) return null; var value = parent[propertyName]; var jsClass = Object.prototype.toString.call(value).split(' ')[1].slice(0, -1); var jsType = typeof (value); return `${jsType} ${jsClass}`; } // deletes property // JSImport // bool _propertyDelete(double sjsId, string key); static propertyDelete(sjsId, key) { var obj = SpawnJSInterop.spawnJSObjectGet(sjsId); if (obj === void 0 || obj === null) throw new Error('obj null or undefined'); var { parent, propertyName, shortCircuit } = SpawnJSInterop.pathObjectInfo(obj, key); if (shortCircuit) return true; return delete parent[propertyName]; } // returns bool if the key is in the target // JSImport // bool _propertyIn(double sjsId, string key); static propertyIn(sjsId, key) { var obj = SpawnJSInterop.spawnJSObjectGet(sjsId); if (obj === void 0 || obj === null) throw new Error('obj null or undefined'); var { parent, propertyName, shortCircuit } = SpawnJSInterop.pathObjectInfo(obj, key); if (shortCircuit) return false; return SpawnJSInterop._in(propertyName, parent); } // get a property // InteropCall (dispatched through the call tape) static propertyGet(sjsId, key) { var ret = undefined; var obj = SpawnJSInterop.spawnJSObjectGet(sjsId); var pathInfo = SpawnJSInterop.pathObjectInfo(obj, key); if (pathInfo.shortCircuit) return ret; if (typeof pathInfo.target === 'function') { ret = pathInfo.target.bind(pathInfo.parent); } else { ret = pathInfo.target; } return ret; } // set property // InteropCall (dispatched through the call tape) static propertySet(sjsId, key, value) { var obj = SpawnJSInterop.spawnJSObjectGet(sjsId); if (obj === void 0 || obj === null) throw new Error('obj null or undefined'); var { parent, propertyName, shortCircuit } = SpawnJSInterop.pathObjectInfo(obj, key); if (shortCircuit) return; // revivers value = SpawnJSInterop.reviveValue(propertyName, value, false); parent[propertyName] = value; } // A view of - or with copy, a copy of - .Net memory. A live view carries its _heapViewInfo so the heap view // reviver can rebuild it after the heap grows. Built when the tape reads a TagHeapView. static _heapView(dotnetId, viewType, offset, length, copy) { // create the heapView meta data var heapViewInfo = { dotnetId, viewType, offset, length, copy }; // viewType is an INDEX into HeapViewCtors, and index 0 (BigInt64Array) is a real value - a // falsy check would read it as "missing" and silently rewrite it. The default is the // Uint8Array index, not its name: this value is used as an index, never as a lookup key. if (heapViewInfo.viewType === undefined || heapViewInfo.viewType === null) heapViewInfo.viewType = 10; heapViewInfo.instance = SpawnJSInterop.getInstace(heapViewInfo.dotnetId); heapViewInfo.dotnet = SpawnJSInterop.spawnJSObjectGet(heapViewInfo.dotnetId); heapViewInfo.sizeHistory = []; heapViewInfo.ctor = SpawnJSInterop.getArrayBufferViewConstructor(heapViewInfo.viewType); // refresh the heapView return SpawnJSInterop.heapViewRefresh(heapViewInfo); } // The Javascript function that invokes a .Net Callback, created once per callback and reused // .Net gives each instance a pinned buffer that a callback's arguments are written into before it calls .Net // JSImport // void _registerInbound(double dotnetId, double address, int cells); static _registerInbound(dotnetId, address, cells) { // cell 0 carries the offset of the arguments of the callback being called SpawnJSInterop.getInstace(dotnetId).inbound = { address, cells, top: 1 }; } // Writes a callback's arguments by their schemas into the instance's inbound buffer, as a stack (a callback can // run inside another), and puts their offset in cell 0. Arguments too large for the space left are held for // _spawnJSInteropCallResult instead, and cell 0 is minus their size. Returns the top to restore afterwards. static _tapeWriteInbound(instance, argumentSchemas, args) { var inbound = instance.inbound; var top = inbound.top; var s = SpawnJSInterop._tapeScratchWriter(instance); try { for (var i = 0; i < argumentSchemas.length; i++) { SpawnJSInterop._tapeEncode(instance, s, SpawnJSInterop._tapeSchema(instance, argumentSchemas[i]), args[i]); } var views = SpawnJSInterop._tapeViews(instance, inbound.address + inbound.cells * 8); var offset; if (top + s.p <= inbound.cells) { new Uint8Array(views.buffer, inbound.address + top * 8, s.p * 8).set(new Uint8Array(s.buffer, 0, s.p * 8)); offset = top; inbound.top = top + s.p; } else { instance.tapePendingResult = new Uint8Array(s.buffer.slice(0, s.p * 8)); offset = -(s.p * 8); } views.f64[inbound.address >>> 3] = offset; } finally { SpawnJSInterop._tapeScratchRelease(instance, s); } return top; } static _callbackFunction(dotnetId, callbackId, once, argumentSchemas) { if (!callbackId || !dotnetId) { return null; } // get callback id that is globally unique var callbackIdPair = `${dotnetId}_${callbackId}`; // check if it exists and createa new function if not var value = SpawnJSInterop._callbacks[callbackIdPair]; if (!value) { value = function (...args) { // check if the callback has been removed if (!SpawnJSInterop._callbacks[callbackIdPair]) { return; } // get the SpawnJSRuntime instance's method that is used to report the callback var instance = SpawnJSInterop.getInstace(dotnetId); var { handleCallback } = instance; // get argsCnt because after when we call handleCallback .Net will write // the return value to at the end of the array after the last argument (index argsCnt) // unless the return value should be undefined var argsCnt = args.length; // get a temporary hold of the args (released after we notify SpawnJSRuntime) var argsId = SpawnJSInterop.spawnJSObjectHold(args); // ⚠️ try/finally, NOT straight-line. .Net deliberately does not release this slot // itself - that would cost an extra crossing per callback - so the ONLY release is // here. If handleCallback throws (any exception escaping the .Net handler crosses // back through here) a straight-line release is SKIPPED and the args array is // stranded in spawnJSObjects for the life of the page. Same for the `once` cleanup: // a one-shot callback that threw would never be removed and would keep firing. // MEASURED 2026-09-02: dumping the table mid-run in the ML demo showed ~30 stranded // empty arrays alongside the retained adapters. // the arguments go to .Net memory now, so the call below is the only crossing they need var inboundTop = SpawnJSInterop._tapeWriteInbound(instance, argumentSchemas ?? [], args); try { // notify SpawnJSRuntime with the argsId and the cnt handleCallback(callbackId, argsId, argsCnt); } finally { instance.inbound.top = inboundTop; // release the args SpawnJSInterop.spawnJSObjectRelease(argsId); // if it was a 1 time use callback, release it if (once) delete SpawnJSInterop._callbacks[callbackIdPair]; } // return what is in index argsCnt (the designated place .Net will write to if there is a return value) return args[argsCnt]; }; SpawnJSInterop._callbacks[callbackIdPair] = value; } return value; }
// Interop Calls // Interop calls are calls made indirectly via _spawnJSInteropCall and _spawnJSInteropCallAsync. // Because they go through those methods they can return and recieve any data type the marshallers support
// call a property constructor // InteropCall // SpawnJSObjectReference // <double, string, object?[]?, SpawnJSObjectReference> static propertyNewApply(sjsId, key, args) { var ret = undefined; var obj = SpawnJSInterop.spawnJSObjectGet(sjsId); var pathInfo = SpawnJSInterop.pathObjectInfo(obj, key); if (pathInfo.shortCircuit) return ret; var ret = !args ? new pathInfo.target() : new pathInfo.target(...args); return ret; } // call a property constructor // InteropCall // SpawnJSObjectReference // <double, string, ..., T> static propertyNew(sjsId, key, ...args) { var ret = undefined; var obj = SpawnJSInterop.spawnJSObjectGet(sjsId); var pathInfo = SpawnJSInterop.pathObjectInfo(obj, key); if (pathInfo.shortCircuit) return ret; var ret = !args ? new pathInfo.target() : new pathInfo.target(...args); return ret; } // call a property // InteropCall // SpawnJSObjectReference // <double, string, object?[]?, T> static propertyCallApply(sjsId, key, args) { var ret = undefined; var obj = SpawnJSInterop.spawnJSObjectGet(sjsId); var pathInfo = SpawnJSInterop.pathObjectInfo(obj, key); if (pathInfo.shortCircuit) return ret; var ret = pathInfo.target.apply(pathInfo.parent, args); if (typeof ret === 'function') { ret = ret.bind(pathInfo.parent); } return ret; } // call a property // InteropCall // SpawnJSObjectReference // <double, string, ..., T> static propertyCall(sjsId, key, ...args) { var ret = undefined; var obj = SpawnJSInterop.spawnJSObjectGet(sjsId); var pathInfo = SpawnJSInterop.pathObjectInfo(obj, key); if (pathInfo.shortCircuit) return ret; var ret = pathInfo.target.apply(pathInfo.parent, args); if (typeof ret === 'function') { ret = ret.bind(pathInfo.parent); } return ret; } // useful when .Net Wasm wants to clonme a JSObjectReference or simply convert from one type to another // InteropCall // SpawnJSObjectReference // <TIn, TResult> static returnMe(value) { return value; } // InteropCall // ByteArrayMarshaller // <double, SpawnJSObjectReference, double, double, double, VoidType> static writeArrayBufferViewToHeap(dotnetId, arrayBufferView, srcOffset, destOffset, byteLength) { if (!arrayBufferView) throw new Error('writeArrayBufferViewToHeap arrayBufferView is required'); if (byteLength === 0) return 0; var srcLength = arrayBufferView.byteLength; if (byteLength == -1) byteLength = srcLength; if (byteLength < -1) throw new Error('Invalid byteLength'); // get the .Net heap var instance = SpawnJSInterop.getInstace(dotnetId); var buffer = instance.getHeap(); var bufferView = new Uint8Array(buffer, destOffset, byteLength); // get a view of the exact source we want var offset = arrayBufferView.byteOffset + srcOffset; var sourceView = new Uint8Array(arrayBufferView.buffer, offset, byteLength); // copy to the .Net heap bufferView.set(sourceView); // return the bytes copied return byteLength; } // called using Call<> // InteropCall // TaskMarshaller // <double, int, SpawnJSObjectReference> static propertySetNewPromise(sjsId, key) { var obj = SpawnJSInterop.spawnJSObjectGet(sjsId); if (obj === void 0 || obj === null) throw new Error('obj null or undefined'); var { parent, propertyName, shortCircuit } = SpawnJSInterop.pathObjectInfo(obj, key); if (shortCircuit) return; var promise = SpawnJSInterop.newEasyPromise(); parent[propertyName] = promise; return promise; } // called using Call<> // InteropCall // TaskMarshaller // <double, string, VoidType> static propertySetResolvedPromise(sjsId, key, value) { var obj = SpawnJSInterop.spawnJSObjectGet(sjsId); if (obj === void 0 || obj === null) throw new Error('obj null or undefined'); var { parent, propertyName, shortCircuit } = SpawnJSInterop.pathObjectInfo(obj, key); if (shortCircuit) return; parent[propertyName] = Promise.resolve(value); } // called using Call<> // InteropCall // TaskMarshaller // <double, string, string, VoidType> static propertySetRejectedPromise(sjsId, key, value) { var obj = SpawnJSInterop.spawnJSObjectGet(sjsId); if (obj === void 0 || obj === null) throw new Error('obj null or undefined'); var { parent, propertyName, shortCircuit } = SpawnJSInterop.pathObjectInfo(obj, key); if (shortCircuit) return; parent[propertyName] = Promise.reject(value); } // InteropCall // SpawnJSRuntime // <double, long> static getHeapSize(dotnetId) { var instance = SpawnJSInterop.getInstace(dotnetId); var buffer = instance.getHeap(); return buffer.byteLength; } // full ? strict equality : loose equality // InteropCall // SpawnJSRuntime // <T1, T2, bool, bool> static objectEquals(obj1, obj2, full) { return full ? obj1 === obj2 : obj1 == obj2; }
static detachedEventCheck() { for (const dotnetIdExisting in SpawnJSInterop._instances) { if (Object.hasOwn(SpawnJSInterop._instances, dotnetIdExisting)) { var instanceInfo = SpawnJSInterop._instances[dotnetIdExisting]; instanceInfo.getHeap(); } } } static getInstace(dotnetId) { return SpawnJSInterop._instances[dotnetId]; } static _getInstaceFromDotNet(dotnet) { for (const dotnetIdExisting in SpawnJSInterop._instances) { if (Object.hasOwn(SpawnJSInterop._instances, dotnetIdExisting)) { var existingInfo = SpawnJSInterop._instances[dotnetIdExisting]; if (existingInfo.dotnet == dotnet) { return existingInfo; } } } } static __replacerJson(key, value, directCall) { if (directCall) value = JSON.stringify(value); return value; } static __reviverJson(key, value, directCall) { if (directCall) value = JSON.parse(value); return value; } static _unregisterInstance(dotnetId) { delete SpawnJSInterop._instances[dotnetId]; } static _getMappedMethodNames() { return SpawnJSInterop._methodMapNames; } // array of { name, reviver } static registerReplacers(replacers) { var cnt = 0; if (!replacers) return cnt; for (var replacerObj of replacers) { var succ = SpawnJSInterop.registerReplacer(replacerObj.name, replacerObj.replacer); if (succ) cnt++; } return cnt; } static registerReplacer(name, replacer) { if (name.indexOf('__replacer') !== 0) throw new Error('Replacer names must start with __replacer'); if (SpawnJSInterop[name]) { // already exists. fail quitely as it could just mean another app loaded that uses the same replacers return false; } SpawnJSInterop[name] = replacer; SpawnJSInterop.refreshMethodMap(); return true; } // array of { name, reviver } static registerRevivers(revivers) { var cnt = 0; if (!revivers) return cnt; for (var reviverObj of revivers) { var succ = SpawnJSInterop.registerReviver(reviverObj.name, reviverObj.reviver); if (succ) cnt++; } return cnt; } static registerReviver(name, reviver) { if (name.indexOf('__reviver') !== 0) throw new Error('Reviver names must start with __reviver'); if (SpawnJSInterop[name]) { // already exists. fail quitely as it could just mean another app loaded that uses the same revivers return false; } SpawnJSInterop[name] = reviver; SpawnJSInterop.refreshMethodMap(); return true; } // puts objectToHold (value of ANY type) into spawnJSObjects and returns the id // the object will stay held until released and it must be released to prevent memory leaks static spawnJSObjectHold(objectToHold) { if (objectToHold === globalThis) return -1; if (objectToHold === undefined) return -2; if (objectToHold === null) return -3; if (objectToHold === SpawnJSInterop.spawnJSObjects) return -4; if (objectToHold === SpawnJSInterop) return -5; var sjsId = ++SpawnJSInterop._sjsObjectIdNext; SpawnJSInterop.spawnJSObjects[sjsId] = objectToHold; if (SpawnJSInterop.verbose) console.log('spawnJSObjectHold. Count:', Object.keys(SpawnJSInterop.spawnJSObjects).length, 'Id:', sjsId, 'Object:', objectToHold); return sjsId; } // get an object from the hold static spawnJSObjectGet(sjsId) { switch (sjsId) { case -1: return globalThis; case -2: return undefined; case -3: return null; case -4: return SpawnJSInterop.spawnJSObjects; case -5: return SpawnJSInterop; } if (!SpawnJSInterop.spawnJSObjectHoldExists(sjsId)) { throw new Error('SpawnJSObjectGet object not found.'); } var ret = SpawnJSInterop.spawnJSObjects[sjsId]; // passive revive (allows things like refreshing heap views) ret = SpawnJSInterop.reviveValue(null, ret, false); return ret; }// get an obejct from the hold and replace it with a new one static spawnJSObjectGetAndReplace(sjsId, newValue) { switch (sjsId) { case -1: return globalThis; case -2: return undefined; case -3: return null; case -4: return SpawnJSInterop.spawnJSObjects; case -5: return SpawnJSInterop; } if (!SpawnJSInterop.spawnJSObjectHoldExists(sjsId)) { throw new Error('SpawnJSObjectGet object not found.'); } var ret = SpawnJSInterop.spawnJSObjects[sjsId]; SpawnJSInterop.spawnJSObjects[sjsId] = newValue; return ret; } static heapViewRefresh(heapViewInfo) { var needsCreate = !heapViewInfo.buffer; var needsRefresh = !heapViewInfo.buffer || heapViewInfo.buffer.detached; if (needsRefresh) { var instance = SpawnJSInterop.getInstace(heapViewInfo.dotnetId); heapViewInfo.buffer = instance.getHeap(); var value = null; var length = heapViewInfo.length === -1 ? /* entire buffer */ heapViewInfo.buffer.byteLength - heapViewInfo.offset : heapViewInfo.length; if (heapViewInfo.viewType === 13) { // ArrayBuffer requested if (heapViewInfo.copy) { // create a copy value = heapViewInfo.buffer.slice(heapViewInfo.offset, heapViewInfo.offset + length); } else { // can't use offet and length when not copying the heap asn ArrayBuffer view if (heapViewInfo.offset != 0) throw new Error('Offset and length not supported creating an ArrayBuffer heap view without a copy'); value = heapViewInfo.buffer; } } else if (heapViewInfo.viewType === 14) { // SharedArrayBuffer requested if (heapViewInfo.copy) { // create a copy var uint8ArrayHeap = new Uint8Array(heapViewInfo.buffer, heapViewInfo.offset, length); value = new globalThis.SharedArrayBuffer(length); var uint8ArrayDest = new Uint8Array(value); value.set(uint8ArrayHeap); } else { // can't get a live SharedArrayBuffer view of the heap throw new Error('Cannot get a live SharedArrayBuffer view of the heap'); } } else { // ArrayBufferView (TypedArray or DataView) var liveView = new heapViewInfo.ctor(heapViewInfo.buffer, heapViewInfo.offset, length); value = heapViewInfo.copy ? liveView.slice() : liveView; } // copies do not get (or need) their view refreshed as it will not detach if (!heapViewInfo.copy) value._heapViewInfo = heapViewInfo; heapViewInfo.bufferLength = heapViewInfo.buffer.byteLength; heapViewInfo.sizeHistory.push(heapViewInfo.bufferLength); heapViewInfo.value = value; if (SpawnJSInterop.verbose) { if (!needsCreate) console.log('Heapview refreshed:', heapViewInfo); else console.log('Heapview created:', heapViewInfo); } } return heapViewInfo.value; } static getArrayBufferViewConstructor(viewType) { var ctor = SpawnJSInterop.HeapViewCtors[viewType]; if (viewType === 13 || viewType === 14) return null; // ArrayBuffer if (!ctor) throw new Error(`Unsupported or missing ArrayBufferView constructor for enum index: ${viewType}`); return ctor; } static __replacerHeapView(key, value, directCall, reviverConfig) { if (directCall) { if (value && typeof value === 'object' && SpawnJSInterop._in('_heapViewInfo', value)) { // .Net wants HeapViewDescriptor //SpawnJSInterop.heapViewRefresh(heapViewInfo); } } return value; } static __reviverHeapView(key, value, directCall, reviverConfig) { if (!directCall && value && typeof value === 'object' && SpawnJSInterop._in('_heapViewInfo', value)) { // auto-reattach if needed // this allows creating a fresh HeapView if needed on `set` and `call` (with the exception of call reattach only working if the view is in teh root args list. no object walking is done) var heapViewInfo = value._heapViewInfo; value = SpawnJSInterop.heapViewRefresh(heapViewInfo); } return value; } // tape revivers (JSTape.WriteRevived) for a Task that completed before it was written static promiseResolved(key, value) { return Promise.resolve(value); } static promiseRejected(key, value) { return Promise.reject(value); } // create a new Promsie with the resolve and reject methods attached to the promise for easy calling from .Net static newEasyPromise() { var _resolve = null; var _reject = null; var promise = new Promise((resolve, reject) => { _resolve = resolve; _reject = reject; }); promise.resolve = _resolve; promise.reject = _reject; return promise } // Reviver used by BigIntegerMarshaller: a BigInteger crosses as its decimal string, because a JS // number cannot hold one exactly, and is revived into a real BigInt here. // Revivers are called as (key, value, directCall) by the tape (TagRevive, JSTape.WriteRevived) - a plain // (value) signature would silently revive the PROPERTY NAME instead of the value. static stringToBigInt(key, value) { if (!globalThis.BigInt) throw new Error('BigInt not supported on this platform'); return value === undefined || value === null ? null : globalThis.BigInt(value); } // object constructor names // returns string[] static getConstructorNames(obj) { var constructorNames = []; if (obj === void 0 || obj === null) return constructorNames; var o = obj; var cName; while (1) { o = Object.getPrototypeOf(o); cName = o?.constructor?.name; if (!cName) break; if (constructorNames.indexOf(cName) !== -1) continue; constructorNames.push(cName); } return constructorNames; } // returns string[] of the target's property names. // hasOwnProperty true restricts to the object's own enumerable keys (Object.keys); false walks the // prototype chain too, which is what you need to enumerate a DOM object's API rather than just the // handful of own properties it happens to carry. static objectKeys(target, hasOwnProperty) { if (target === void 0 || target === null) return []; if (hasOwnProperty) return Object.keys(target); var keys = []; for (var key in target) { if (keys.indexOf(key) === -1) keys.push(key); } return keys; } // Pipe the value through each reviver sequentially; a reviver that drops the value (undefined) skips the rest. // A plain loop: this runs for every argument of every call, and reduce() allocated a closure each time. static reviveValue(key, value, directCall) { var revivers = SpawnJSInterop._revivers; for (var i = 0; i < revivers.length && value !== undefined; i++) { value = revivers[i](key, value, directCall); // directCall tells the reviver this is a call revive as opposed to a propertySet revive } return value; } static replaceValue(key, value, directCall) { var replacers = SpawnJSInterop._replacers; for (var i = 0; i < replacers.length && value !== undefined; i++) { value = replacers[i](key, value, directCall); } return value; } // returns the types the object inherits from // returns string[] static getPropertyConstructorNames(parent, key) { return SpawnJSInterop.getConstructorNames(parent[key]); } // converts to an error string or returns a generic error string. // A NAMED error (Error subclasses, DOMException - NotFoundError, NotAllowedError, AbortError ... - // and OverconstrainedError, which often has an EMPTY message) is sent as // "\u0001" + name + "\u0002" + message so .Net can rebuild a JSException with its Name // (JSException.FromInteropError). Only the message used to be sent: the name was lost, and an // empty-message OverconstrainedError from getUserMedia arrived as a blank exception. static errorToString(error) { if (!error) return "Unknown error"; if (typeof error === 'string') return error; let name = null; let message = null; if (typeof error === 'object') { try { if (typeof error.name === 'string' && error.name) name = error.name; } catch { } try { if (typeof error.message === 'string') message = error.message; } catch { } if (message === null && !(error instanceof Error)) { try { message = JSON.stringify(error); } catch { message = String(error); } } // OverconstrainedError reports the failing constraint separately try { if (typeof error.constraint === 'string' && error.constraint) message = (message ? message + ' ' : '') + '(constraint: ' + error.constraint + ')'; } catch { } } else { message = String(error); } if (!message) message = name ? '' : 'Unknown error'; return name ? '\u0001' + name + '\u0002' + message : message; } // Main .Net to JS entrypoint static async _spawnJSInteropLoadExportsAsync(dotnetId, assemblyName) { var dotnet = SpawnJSInterop.spawnJSObjectGet(dotnetId); var assemblyExports = await dotnet.getAssemblyExports(assemblyName); var spawnJSExports = assemblyName.split('.').reduce((acc, key) => acc[key], assemblyExports); dotnet.spawnJSExports = spawnJSExports; } // prepares the variable for .Net based on returnType static _serializeToNet(returnType, ret) { switch (returnType) { case 0: // void return; case 6: // SpawnJSObject - Number case 7: // SpawnJSObjectNonNullable - Number return SpawnJSInterop.spawnJSObjectHold(ret); case 8: // Json return JSON.stringify(ret); case 1: // Double case 2: // Boolean case 3: // DoubleNullable case 4: // BooleanNullable case 9: // Int32 case 10: // Int32Nullable return ret; case 5: // String if (ret && typeof ret !== 'string') { ret = Object(ret).toString(); } return ret; } // the default is to return as is return ret; } static wasmMemoryBuffer(dotnet) { var found = SpawnJSInterop.#findWasmMemory(dotnet); if (!found) throw new Error('SpawnJSInterop: could not reach the WebAssembly memory buffer'); return found.buffer; } // returns the name of the path the memory buffer was found under, or '' if it was not found static wasmMemoryBufferSource(dotnet) { var found = SpawnJSInterop.#findWasmMemory(dotnet); return found ? found.source : ''; } static #findWasmMemory(dotnet) { var rt = dotnet; if (!rt) return null; var candidates = [ ['Module.HEAPU8.buffer', () => rt.Module?.HEAPU8?.buffer], ['Module.wasmMemory.buffer', () => rt.Module?.wasmMemory?.buffer], ['localHeapViewU8().buffer', () => rt.localHeapViewU8?.()?.buffer], ['getHeapU8().buffer', () => rt.getHeapU8?.()?.buffer], ]; for (var i = 0; i < candidates.length; i++) { var buffer; try { buffer = candidates[i][1](); } catch (ex) { continue; } if (buffer && typeof buffer.byteLength === 'number' && buffer.byteLength > 0) { return { buffer: buffer, source: candidates[i][0] }; } } return null; } // safely checks for a property existence // safely means will not throw, which is needed as simply checking for a // a proeprty can throw an exception (notably on cross-origin windows) static _in(key, obj) { if (obj === null || obj === void 0) return false; try { return key in Object(obj); } catch { } return false; } // returns the path info based on a base object and a property path: `window?.location.href` static pathObjectInfo(rootObject, path) { if (rootObject === null || rootObject === void 0) { // callers must call with the globalThis if they wish to use it as the rootObject. throw new Error('spawnJSInterop.pathObjectInfo error: rootObject cannot be null'); } var parent = rootObject; var target; var propertyName; var shortCircuit = false; if (typeof path === 'string' && !(SpawnJSInterop._in(path, parent))) { var parts = path.split('.'); propertyName = parts[parts.length - 1]; var part; for (var i = 0; i < parts.length - 1; i++) { part = parts[i]; if (part[part.length - 1] === '?') { // ? null conditonal found // if parent does not exist allow undefined/null parent instead of throwing exception part = part.substring(0, part.length - 1); parent = parent[part]; if (parent === void 0 || parent === null) { shortCircuit = true; break; } } else { parent = parent[part]; } } if (!shortCircuit) { target = parent[propertyName]; } } else { propertyName = path; target = parent[propertyName]; } return { shortCircuit, // bool - true if the pathfinding short circuited due to a null-conditional parent, // any - only null or undefined if short circuited due to a null-conditional propertyName, // any target, // any }; }
// The URL this app was LOADED from - the origin of its own main.* / _framework, NOT the host // page's document.baseURI. Under a CDN load the page and the app live at different URLs, and every // worker entry (main.classic.js / main.module.js / _framework/*) must resolve against the APP's // origin. document.baseURI is a page-coupled Blazor-ism that hands back the page root instead. // // Derived per-runtime from THIS app's OWN dotnetRuntime, so two SpawnJS apps loaded from different // origins on one page each get their own base - a module-scope import.meta.url could not, because // the class-definition guard means app B's lib.module.js body never re-runs. // // Fail-loud multi-candidate, the same shape as #findWasmMemory: the runtime exposes its origin // under different shapes across scopes/versions, so every known shape is tried and the one that // worked is reportable via appBaseUriSource(). Returns '' if none resolve, so the caller can fall // back rather than silently build worker URLs against a wrong base. static appBaseUri(dotnet) { var found = this.#findAppBaseUri(dotnet); return found ? found.uri : ''; } // Which candidate produced appBaseUri(), or '' - diagnostic, mirrors wasmMemoryBufferSource(). static appBaseUriSource(dotnet) { var found = this.#findAppBaseUri(dotnet); return found ? found.source : ''; } static import(src) { return import(src); } // The app-root normalizer, exposed so it is diagnosable and testable directly. The test suite // drives THIS function rather than a copy of the logic, so the production path is what is covered. static appRootFromLoadUrl(raw) { return this.#appRootFromLoadUrl(raw); } // Normalizes a URL some runtime artifact was loaded from into the app root, with a trailing slash. // // Every boot artifact - the runtime entry (dotnet.js / dotnet.<fingerprint>.js) and every resource // in the boot manifest (.wasm/.dll assemblies, ICU .dat/.blat, .pdb symbols) - lives in the app's // framework folder, so the app root is that folder's PARENT. Anything else was loaded from the app // root itself: a bundled entrypoint (main.classic.js / main.module.js) sits beside index.html, and // that is what SpawnDev.SpawnJS.WebWorkers bundles before 2.1.9 reported here. // // The framework folder is identified by WHAT was loaded, never by what the folder is NAMED. It is // "_framework" in a normal publish, but a published app may rename it - WebWorkers' // SpawnJSWebWorkersFrameworkFolderName does exactly that, because a browser extension may not have // a root folder starting with '_'. Matching the literal name returned the framework folder itself // as the app root there, and every URL built on it (worker entrypoints above all) resolved one // level too deep. static #appRootFromLoadUrl(raw) { if (typeof raw !== 'string' || raw.length === 0) return ''; if (raw.startsWith('blob:')) return ''; var url; // `self` is not declared at all under Node (a .NET WebAssembly console app), and `?.` does not guard an // undeclared name: read the page/worker location only where one exists. var base = typeof self !== 'undefined' ? self.location?.href : undefined; try { url = new URL(raw, base); } catch (ex) { return ''; } var segments = url.pathname.split('/'); // leading '' from the root slash var file = segments.pop(); // '' when the url already names a directory // A boot artifact is one level below the app root, whatever its folder is called. Guarded on // length so an artifact served from the origin root cannot walk above it. if (file && this.#isBootArtifact(file) && segments.length > 1) segments.pop(); // Resolved against the url itself, not built from url.origin: a file: url (Node loads the app from disk) has // the origin "null". For http(s) this is the same string as origin + path (query and fragment dropped). return new URL(segments.join('/') + '/', url).href; } // True for the runtime entry and for boot-manifest resources - the files that only ever live in // the app's framework folder. Deliberately does NOT match a bundled entrypoint (main.*.js), which // sits at the app root. static #isBootArtifact(fileName) { return /^dotnet(\..+)?\.m?js$/i.test(fileName) || /\.(wasm|dll|dat|blat|pdb)$/i.test(fileName); } static #findAppBaseUri(dotnet) { if (!dotnet) return null; var candidates = [ // PROVEN primary (measured across scopes): dotnet.js's own module URL, i.e. // appRoot/_framework/dotnet.<fp>.js - itself import.meta-derived, so it is the real CDN // origin under a CDN load, not the host page. Can be a blob: URL in some worker configs, // which #appRootFromLoadUrl rejects so the resolver falls through to the next candidate. ['Module.mainScriptUrlOrBlob', () => dotnet.Module?.mainScriptUrlOrBlob], // Robust backup: every boot resource carries an absolute resolvedUrl (appRoot/_framework/*), // always populated even when mainScriptUrlOrBlob is a blob. ['getConfig().resources.assembly[0].resolvedUrl', () => dotnet.getConfig?.()?.resources?.assembly?.[0]?.resolvedUrl], ]; for (var i = 0; i < candidates.length; i++) { var raw; try { raw = candidates[i][1](); } catch (ex) { continue; } var uri = this.#appRootFromLoadUrl(raw); if (uri) return { uri: uri, source: candidates[i][0] }; } return null; } } globalThis.SpawnJSInterop = SpawnJSInterop;})();1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283// SpawnDev.Blazor.BootRecovery//// WORKAROUND: dotnet/runtime#135090 (https://github.com/dotnet/runtime/issues/135090). TEMPORARY: remove this package once the// .NET runtime retries failed boot resources with cache: "reload" itself.//// THE BUG: the .NET WebAssembly loader fetches every fingerprinted boot resource (assemblies, dotnet.native.wasm, ICU, pdb) with// fetch(url, { cache: "force-cache", integrity }). If the browser's HTTP cache ever stored an error for one of those URLs (a 503 from// the host during a deploy or outage, a 404, an empty 200), "force-cache" returns that stored response on every later load, without// asking the server again. The integrity check rejects it, the app fails to boot, and it keeps failing after the server is healthy:// a hard reload does not help (the explicit cache mode wins over the reload's cache bypass), and Blazor sets// enableDownloadRetry: false, so nothing retries. A visitor is stuck until the browser evicts the entry.//// THE FIX: while this initializer is loaded, a fetch that was sent with cache: "force-cache" and failed (rejected, e.g. the// integrity check, or answered with a non-2xx status) is sent ONCE more with cache: "reload". Everything else the runtime chose// (integrity, credentials, headers) is kept, so a resource is still verified against its hash. "reload" goes to the network and// replaces the bad cache entry, so the next load is a normal cache hit again. A healthy cached start does not change at all: a// successful force-cache response is returned untouched. If the retry fails too (the server really is down) its result is// returned and the app fails exactly as it would have.//// HOW IT LOADS: Blazor imports every referenced package's <AssemblyName>.lib.module.js ("JS initializer") from onConfigLoaded,// before the runtime starts downloading its boot resources, and the runtime calls globalThis.fetch at call time. So referencing// this package is enough: no Program.cs or index.html change. The wrapper is installed when this module is evaluated, and the// initializer hooks below only make sure of it.
const STATE_KEY = Symbol.for('SpawnDev.Blazor.BootRecovery');
function urlOf(input) { if (typeof input === 'string') return input; if (input && typeof input.url === 'string') return input.url; // Request return String(input); // URL or anything with toString()}
// ⚠️ The installer is a plain, NON-exported function declaration, and nothing in this module calls an exported function by name.// SpawnDev.BlazorJS.WebWorkers (when a worker cannot use dynamic import, or the app has an import map, i.e. every .NET 10 template app)// rewrites this module's source: `export function X()` becomes `_exportsOverride.X = function X()`, a function EXPRESSION, which// leaves no `X` binding in the module scope. 1.0.0 called its exported installBootRecovery() at the top level, so in such a worker the// module threw "ReferenceError: installBootRecovery is not defined" and the worker failed to boot (found by Data, 2026-11-22). A// plain declaration is not rewritten and stays hoisted, so this works with that patcher and without it.function install() { const g = globalThis; if (g[STATE_KEY]) return g[STATE_KEY]; const originalFetch = g.fetch; if (typeof originalFetch !== 'function') return null; const state = { originalFetch, recovered: [] };
const recoveringFetch = async function (input, init) { // Only requests that explicitly asked for "force-cache" can be pinned to a stored error. Everything else goes straight // through, unchanged (same arguments, same this-binding as a plain fetch call). if (!init || init.cache !== 'force-cache') return originalFetch.call(g, input, init); let reason; try { const response = await originalFetch.call(g, input, init); if (response.ok) return response; reason = `HTTP ${response.status}`; } catch (e) { reason = (e && e.message) || String(e); // integrity mismatch / network failure: TypeError "Failed to fetch" } const url = urlOf(input); // One retry, from the network, keeping every other option (integrity included). Its outcome is final either way. const retried = await originalFetch.call(g, input, { ...init, cache: 'reload' }); state.recovered.push({ url, reason, status: retried.status }); if (retried.ok) console.warn(`[SpawnDev.Blazor.BootRecovery] recovered '${url}' (cached response failed: ${reason}); re-fetched with cache: "reload" (dotnet/runtime#135090).`); return retried; }; g.fetch = recoveringFetch; g[STATE_KEY] = state; return state;}
/** * Installs the recovering fetch wrapper on globalThis once (idempotent, also across copies of this module). * @returns {{ originalFetch: Function, recovered: Array<{url: string, reason: string, status: number}> } | null} */export function installBootRecovery() { return install(); }
// Install as soon as Blazor imports this module.install();
// Blazor initializer hooks. Blazor calls the WebAssembly-specific hook when present, the classic one otherwise; both only ensure// the wrapper is installed (for example if something replaced fetch between the import and the start).export function beforeWebAssemblyStart() { install(); }export function beforeStart() { install(); }12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019'use strict';
let gl = null;
let canvas = null;
const programCache = {};
// programId -> the compile or link error of a program that failed. The accelerator sends a program's source and
// varying names with its FIRST dispatch only, so a later dispatch of a failed program must repeat that error.
const failedPrograms = {};
// ---- GPU-resident buffer registry ----
// Maps bufferId → { texture, width, height, glslType, byteSize, data: Uint8Array }
const bufferRegistry = {};
// ---- float scalar uniform decode ----
// float/double scalar uniforms arrive as their int32 BIT PATTERN (WebGLAccelerator.EncodeUniformScalarValue):
// the .NET→JS dispatch message is JSON-marshaled and System.Text.Json rejects float ±inf/NaN, so the bits
// travel as a JSON-safe int and we reconstruct the exact float here. ±inf/NaN round-trip bit-perfectly.
const _f32rein = new Float32Array(1);
const _i32rein = new Int32Array(_f32rein.buffer);
function _bitsToFloat(bits) { _i32rein[0] = bits | 0; return _f32rein[0]; }
// ---- Cached GL objects (reused across dispatches) ----
let cachedTFBuffer = null;
let cachedTFBufferSize = 0;
let cachedTFObject = null;
let cachedDummyVBO = null;
let cachedDummyVBOSize = 0;
let cachedDummyVAO = null;
self.onmessage = function (e) {
const msg = e.data;
switch (msg.type) {
case 'init':
canvas = msg.canvas;
if (!canvas) {
console.error('[GLWorker] INIT FAILED: No canvas received');
return;
}
gl = canvas.getContext('webgl2');
if (!gl) {
console.error('[GLWorker] INIT FAILED: Could not create WebGL2 context');
} else {
// Required to render to R32F/RGBA32F color attachments (GPGPU scatter of float buffers).
// Integer formats (R32I/R32UI) are color-renderable in core WebGL2 without this.
gl.getExtension('EXT_color_buffer_float');
}
// Monitor context loss/restoration
canvas.addEventListener('webglcontextlost', function (ev) {
ev.preventDefault(); // allows potential context restoration
self.postMessage({ type: 'contextlost' });
});
canvas.addEventListener('webglcontextrestored', function () {
gl = canvas.getContext('webgl2');
// programs and the cached GL objects belonged to the lost context; the accelerator re-sends sources
for (const id in programCache) delete programCache[id];
for (const id in failedPrograms) delete failedPrograms[id];
for (const t in scatterPrograms) delete scatterPrograms[t];
scatterFBO = null;
maxTexSizeCache = 0;
cachedTFBuffer = null;
cachedTFBufferSize = 0;
cachedTFObject = null;
cachedDummyVBO = null;
cachedDummyVBOSize = 0;
cachedDummyVAO = null;
self.postMessage({ type: 'contextrestored' });
});
break;
case 'allocBuffer':
handleAllocBuffer(msg);
break;
case 'uploadBuffer':
handleUploadBuffer(msg);
break;
case 'readbackBuffer':
handleReadbackBuffer(msg);
break;
case 'freeBuffer':
handleFreeBuffer(msg);
break;
case 'copyBuffer':
handleCopyBuffer(msg);
break;
case 'retypeBuffer':
handleRetypeBuffer(msg);
break;
case 'dispatch':
try {
const result = dispatchKernel(msg);
self.postMessage(result.message, result.transferList);
} catch (err) {
console.error('[GLWorker] dispatch error:', err.message, err.stack);
self.postMessage({
done: false, dispatchId: msg.dispatchId,
error: err.message + '\n' + err.stack
});
}
break;
case 'blitBuffer':
handleBlitBuffer(msg);
break;
case 'scatter':
try {
handleScatter(msg);
} catch (err) {
console.error('[GLWorker] scatter error:', err.message, err.stack);
self.postMessage({ done: false, dispatchId: msg.dispatchId, error: err.message + '\n' + err.stack });
}
break;
}
};
// ---- GPGPU scatter (render points to a texture; dst[destIdx[i]] = src[i]) ----
// WebGL2 transform feedback is gather-only (an invocation writes only its own output slot).
// Scatter writes to a COMPUTED position by rasterizing one GL_POINT per element at the dest texel
// and letting the fragment shader write the value to the dst texture (the render target). This stays
// GPU-side: the result lives in the dst buffer's texture; we mark the CPU mirror stale and read it
// back lazily only if the host actually reads the buffer (handleReadbackBuffer).
const scatterPrograms = {}; // glslType -> { program, locs }
let scatterFBO = null;
function getOrCompileScatterProgram(glslType) {
if (scatterPrograms[glslType]) return scatterPrograms[glslType];
const isInt = glslType === 'int';
const isUint = glslType === 'uint';
const samp = isInt ? 'isampler2D' : isUint ? 'usampler2D' : 'sampler2D';
const valType = isInt ? 'int' : isUint ? 'uint' : 'float';
const vs = `#version 300 es
precision highp float; precision highp int;
uniform highp ${samp} u_src;
uniform highp isampler2D u_dest;
uniform int u_srcTileW; uniform int u_destTileW; uniform int u_dstW; uniform int u_dstH; uniform int u_cpe;
flat out ${valType} v_val;
void main() {
// i is the int-SLOT index (0..n*cpe-1). cpe=1 -> one texel per element (32-bit). cpe=2 -> two
// texels per element (i64/f64 stored as [lo,hi] pairs): element = i/cpe, component = i%cpe.
int i = gl_VertexID;
int sx = i % u_srcTileW; int sy = i / u_srcTileW;
${valType} val = texelFetch(u_src, ivec2(sx, sy), 0).r;
int element = i / u_cpe;
int comp = i - element * u_cpe;
int di = element % u_destTileW; int dj = element / u_destTileW;
int destElem = texelFetch(u_dest, ivec2(di, dj), 0).r;
int dest = destElem * u_cpe + comp;
int tx = dest % u_dstW; int ty = dest / u_dstW;
float ndcx = (float(tx) + 0.5) / float(u_dstW) * 2.0 - 1.0;
float ndcy = (float(ty) + 0.5) / float(u_dstH) * 2.0 - 1.0;
gl_Position = vec4(ndcx, ndcy, 0.0, 1.0);
gl_PointSize = 1.0;
v_val = val;
}`;
const vec4Type = isInt ? 'ivec4' : isUint ? 'uvec4' : 'vec4';
const zero = isInt ? '0' : isUint ? '0u' : '0.0';
const fs = `#version 300 es
precision highp float; precision highp int;
flat in ${valType} v_val;
layout(location = 0) out highp ${vec4Type} o_val;
void main() { o_val = ${vec4Type}(v_val, ${zero}, ${zero}, ${zero}); }`;
function compile(type, src) {
const s = gl.createShader(type);
gl.shaderSource(s, src); gl.compileShader(s);
if (!gl.getShaderParameter(s, gl.COMPILE_STATUS))
throw new Error('[scatter ' + glslType + '] shader compile: ' + gl.getShaderInfoLog(s) + '\n' + src);
return s;
}
const program = gl.createProgram();
gl.attachShader(program, compile(gl.VERTEX_SHADER, vs));
gl.attachShader(program, compile(gl.FRAGMENT_SHADER, fs));
gl.linkProgram(program);
if (!gl.getProgramParameter(program, gl.LINK_STATUS))
throw new Error('[scatter ' + glslType + '] link: ' + gl.getProgramInfoLog(program));
const locs = {
u_src: gl.getUniformLocation(program, 'u_src'),
u_dest: gl.getUniformLocation(program, 'u_dest'),
u_srcTileW: gl.getUniformLocation(program, 'u_srcTileW'),
u_destTileW: gl.getUniformLocation(program, 'u_destTileW'),
u_dstW: gl.getUniformLocation(program, 'u_dstW'),
u_dstH: gl.getUniformLocation(program, 'u_dstH'),
u_cpe: gl.getUniformLocation(program, 'u_cpe'),
};
const entry = { program, locs };
scatterPrograms[glslType] = entry;
return entry;
}
function handleScatter(msg) {
const { dstBufferId, srcBufferId, destBufferId, n } = msg;
const cpe = msg.cpe || 1; // texels per element: 1 for 32-bit, 2 for i64/f64
while (gl.getError() !== 0) { }
const dst = bufferRegistry[dstBufferId];
const src = bufferRegistry[srcBufferId];
const dest = bufferRegistry[destBufferId];
if (!dst || !src || !dest) throw new Error('scatter: unknown buffer(s)');
const glslType = dst.glslType || 'float';
const sp = getOrCompileScatterProgram(glslType);
gl.useProgram(sp.program);
gl.activeTexture(gl.TEXTURE0); gl.bindTexture(gl.TEXTURE_2D, src.texture); gl.uniform1i(sp.locs.u_src, 0);
gl.activeTexture(gl.TEXTURE1); gl.bindTexture(gl.TEXTURE_2D, dest.texture); gl.uniform1i(sp.locs.u_dest, 1);
gl.uniform1i(sp.locs.u_srcTileW, src.width);
gl.uniform1i(sp.locs.u_destTileW, dest.width);
gl.uniform1i(sp.locs.u_dstW, dst.width);
gl.uniform1i(sp.locs.u_dstH, dst.height);
gl.uniform1i(sp.locs.u_cpe, cpe);
// Render directly into the dst buffer's texture (the next op reads this — zero-copy).
if (!scatterFBO) scatterFBO = gl.createFramebuffer();
gl.bindFramebuffer(gl.FRAMEBUFFER, scatterFBO);
gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, dst.texture, 0);
const fbStatus = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
if (fbStatus !== gl.FRAMEBUFFER_COMPLETE) {
gl.bindFramebuffer(gl.FRAMEBUFFER, null);
throw new Error('scatter: incomplete FBO status=' + fbStatus + ' glslType=' + glslType +
' (R32F render targets need EXT_color_buffer_float; R32I/R32UI are core-renderable)');
}
gl.drawBuffers([gl.COLOR_ATTACHMENT0]);
gl.viewport(0, 0, dst.width, dst.height);
gl.disable(gl.RASTERIZER_DISCARD);
gl.disable(gl.BLEND); // blending is illegal for integer color buffers
gl.disable(gl.DEPTH_TEST);
gl.disable(gl.SCISSOR_TEST);
gl.disable(gl.CULL_FACE);
gl.colorMask(true, true, true, true);
gl.drawArrays(gl.POINTS, 0, n * cpe); // n*cpe int-slots (one point per texel)
gl.bindFramebuffer(gl.FRAMEBUFFER, null);
// Result lives in dst.texture (zero-copy); refresh the CPU mirror lazily on host readback.
dst.dataStale = true;
}
// ---- Buffer Registry Operations ----
// The widest texture this device takes (gl.MAX_TEXTURE_SIZE), at most 16384. It was a fixed 16384: on a device whose limit is
// lower every buffer over that many texels got an illegal texture (INVALID_VALUE) and no kernel could read it - Chrome with
// --disable-gpu (SwiftShader, MAX_TEXTURE_SIZE 8192), SD-Turbo in SpawnGen (Lore, 2026-11-20). Kernels take the width as the
// u_paramN_tileW uniform, so any width works. Reset on context restore.
let maxTexSizeCache = 0;
function maxTextureSize() {
if (!maxTexSizeCache) {
const reported = gl ? gl.getParameter(gl.MAX_TEXTURE_SIZE) : 0;
maxTexSizeCache = Math.min(16384, reported > 0 ? reported : 4096); // 4096: WebGL2's guaranteed minimum is 2048, 4096 is universal
}
return maxTexSizeCache;
}
function computeTiling(byteSize) {
const texelCount = Math.ceil(byteSize / 4);
const maxTexSize = maxTextureSize();
let width, height;
if (texelCount > maxTexSize) {
width = maxTexSize;
height = Math.ceil(texelCount / width);
} else {
width = texelCount;
height = 1;
}
return { width, height, totalTexels: width * height };
}
function createTextureForEntry(entry) {
const tex = gl.createTexture();
gl.bindTexture(gl.TEXTURE_2D, tex);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
uploadTextureData(tex, entry);
return tex;
}
// GL error codes by name, for messages a person can act on.
function glErrorName(e) {
switch (e) {
case 0x0500: return 'INVALID_ENUM';
case 0x0501: return 'INVALID_VALUE';
case 0x0502: return 'INVALID_OPERATION';
case 0x0505: return 'OUT_OF_MEMORY';
case 0x0506: return 'INVALID_FRAMEBUFFER_OPERATION';
case 0x9242: return 'CONTEXT_LOST_WEBGL';
default: return '0x' + e.toString(16);
}
}
// Every pending GL error, as names (empty when there are none). getError returns one flag per call until none is left.
function drainGlErrors() {
const names = [];
for (let e = gl.getError(), guard = 0; e !== 0 && guard < 16; e = gl.getError(), guard++) names.push(glErrorName(e));
return names;
}
function uploadTextureData(tex, entry) {
gl.bindTexture(gl.TEXTURE_2D, tex);
const totalTexels = entry.width * entry.height;
if (entry.glslType === 'int') {
gl.texImage2D(gl.TEXTURE_2D, 0, gl.R32I, entry.width, entry.height, 0,
gl.RED_INTEGER, gl.INT, new Int32Array(entry.data.buffer, 0, totalTexels));
} else if (entry.glslType === 'uint') {
gl.texImage2D(gl.TEXTURE_2D, 0, gl.R32UI, entry.width, entry.height, 0,
gl.RED_INTEGER, gl.UNSIGNED_INT, new Uint32Array(entry.data.buffer, 0, totalTexels));
} else {
gl.texImage2D(gl.TEXTURE_2D, 0, gl.R32F, entry.width, entry.height, 0,
gl.RED, gl.FLOAT, new Float32Array(entry.data.buffer, 0, totalTexels));
}
// A failed upload (OUT_OF_MEMORY when many large textures are alive) leaves the texture without valid contents, and nothing used to
// say so: the error flag was discarded by the next dispatch's drain and kernels read the texture as if it were the buffer
// (DeviceVectorIndex after growth, 2026-11-01). Record it on the buffer; a dispatch that binds the buffer throws with it.
const errs = drainGlErrors();
entry.glError = errs.length > 0 ? errs.join(', ') + ' uploading its ' + entry.width + 'x' + entry.height + ' ' + (entry.glslType || 'float') + ' texture' +
(entry.height > maxTextureSize()
? ' (taller than the MAX_TEXTURE_SIZE of this device, ' + maxTextureSize() + ': one buffer holds at most ' + (maxTextureSize() * maxTextureSize() * 4) + ' bytes on it)'
: '') : null;
}
function handleAllocBuffer(msg) {
const { bufferId, byteSize, glslType } = msg;
const { width, height, totalTexels } = computeTiling(byteSize);
const data = new Uint8Array(totalTexels * 4); // zero-filled
const entry = { texture: null, width, height, glslType: glslType || 'float', byteSize, data };
entry.texture = createTextureForEntry(entry);
bufferRegistry[bufferId] = entry;
}
function handleUploadBuffer(msg) {
const { bufferId, buffer, byteOffset, byteLength, dstByteOffset } = msg;
const entry = bufferRegistry[bufferId];
if (!entry) {
console.error('[GLWorker] uploadBuffer: unknown bufferId', bufferId);
return;
}
const srcData = new Uint8Array(buffer, byteOffset || 0, byteLength || buffer.byteLength);
if (dstByteOffset !== undefined && dstByteOffset !== null) {
// PARTIAL host write (MemSet / CopyFromCPU / CopyFromJS on a range) into a buffer that already lives
// here. Only that range changes: the rest of entry.data is the post-kernel state, which the host's
// own mirror does not have. A whole-buffer upload of the host mirror is what used to wipe it.
ensureCpuFresh(entry);
entry.data.set(srcData, dstByteOffset);
uploadTextureData(entry.texture, entry);
entry.dataStale = false;
return;
}
entry.data.set(srcData);
// Zero-fill padding
if (srcData.length < entry.data.length) {
entry.data.fill(0, srcData.length);
}
uploadTextureData(entry.texture, entry);
entry.dataStale = false; // CPU mirror + GPU texture now consistent
}
// Lazily refresh the CPU mirror (entry.data) from the GPU texture when it was last written by a
// scatter (render-to-texture) and not yet read back. This is the ONLY readPixels — intermediate
// scatter results stay GPU-side and are never read back.
// A buffer created before any kernel bound it (by a device copy, a scatter, a memset) got the default 'float' texture; a kernel that
// then reads it as int / uint binds an isampler2D / usampler2D to an R32F texture, and the draw fails with INVALID_OPERATION, which used
// to read back as "nothing stored" (DeviceVectorIndex's grown valid buffer, 2026-11-01). Re-create the texture in the type the kernel
// declares, from the same raw bytes: entry.data holds the 32-bit words whatever the format, so no value changes.
function handleRetypeBuffer(msg) {
const entry = bufferRegistry[msg.bufferId];
if (!entry) { console.error('[GLWorker] retypeBuffer: unknown bufferId', msg.bufferId); return; }
if (entry.glslType === msg.glslType) return;
ensureCpuFresh(entry); // a scatter may have left the newest bytes only in the texture
entry.glslType = msg.glslType;
uploadTextureData(entry.texture, entry);
}
function ensureCpuFresh(entry) {
if (!entry || !entry.dataStale) return;
if (!scatterFBO) scatterFBO = gl.createFramebuffer();
gl.bindFramebuffer(gl.FRAMEBUFFER, scatterFBO);
gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, entry.texture, 0);
const total = entry.width * entry.height;
let format, type, view;
if (entry.glslType === 'int') { format = gl.RED_INTEGER; type = gl.INT; view = new Int32Array(entry.data.buffer, 0, total); }
else if (entry.glslType === 'uint') { format = gl.RED_INTEGER; type = gl.UNSIGNED_INT; view = new Uint32Array(entry.data.buffer, 0, total); }
else { format = gl.RED; type = gl.FLOAT; view = new Float32Array(entry.data.buffer, 0, total); }
gl.readPixels(0, 0, entry.width, entry.height, format, type, view);
gl.bindFramebuffer(gl.FRAMEBUFFER, null);
entry.dataStale = false;
}
function handleReadbackBuffer(msg) {
const { bufferId, requestId } = msg;
const entry = bufferRegistry[bufferId];
if (!entry) {
self.postMessage({ type: 'readbackResult', requestId, bufferId, error: 'unknown bufferId' });
return;
}
ensureCpuFresh(entry); // pull a scattered result back to the CPU mirror only when actually read
// Create a copy of the data to transfer back
const copy = new ArrayBuffer(entry.byteSize);
new Uint8Array(copy).set(new Uint8Array(entry.data.buffer, 0, entry.byteSize));
self.postMessage({ type: 'readbackResult', requestId, bufferId, buffer: copy }, [copy]);
}
function handleFreeBuffer(msg) {
const { bufferId } = msg;
const entry = bufferRegistry[bufferId];
if (entry) {
if (entry.texture) gl.deleteTexture(entry.texture);
delete bufferRegistry[bufferId];
}
}
// Worker-side GPU->GPU copy. The CPU-side _backingArray is never refreshed
// after a kernel TF write (only the worker's entry.data is), so routing
// CopyTo/CopyFrom GPU->GPU through the main thread reads stale zeros from
// _backingArray and produces a destination of zeros. By doing the copy
// here (worker's entry.data -> worker's entry.data) the canonical
// post-kernel state is preserved, then we re-upload the destination
// texture so subsequent dispatches see the new data.
function handleCopyBuffer(msg) {
const { srcBufferId, srcByteOffset, dstBufferId, dstByteOffset, byteLength } = msg;
const srcEntry = bufferRegistry[srcBufferId];
const dstEntry = bufferRegistry[dstBufferId];
if (!srcEntry || !dstEntry) {
console.error('[GLWorker] copyBuffer: unknown bufferId(s)', srcBufferId, dstBufferId);
return;
}
ensureCpuFresh(srcEntry); // a scattered source must be pulled back before a CPU-side copy
const srcOff = srcByteOffset | 0;
const dstOff = dstByteOffset | 0;
const len = byteLength | 0;
// Bounds clamp - never overrun either typed array.
const srcEnd = Math.min(srcOff + len, srcEntry.data.length);
const copyLen = Math.max(0, srcEnd - srcOff);
if (copyLen <= 0) return;
if (dstOff + copyLen > dstEntry.data.length) {
console.error('[GLWorker] copyBuffer: destination overrun', dstOff, copyLen, dstEntry.data.length);
return;
}
dstEntry.data.set(srcEntry.data.subarray(srcOff, srcOff + copyLen), dstOff);
// Push the new bytes to the destination texture so subsequent kernel
// dispatches reading via texelFetch see the updated values.
uploadTextureData(dstEntry.texture, dstEntry);
dstEntry.dataStale = false; // CPU mirror + GPU texture now consistent
}
// ---- Shader Compilation ----
// source / varyingNames are null after a program's first dispatch: the cached entry (or the cached error) answers.
function getOrCompileProgram(programId, source, varyingNames) {
const cached = programCache[programId];
if (cached && !cached.disposed && (source == null || cached.source === source)) {
return cached;
}
if (source == null) {
if (programId in failedPrograms) throw new Error(failedPrograms[programId]);
throw new Error('GL worker: program ' + programId + ' is not compiled and its source was not sent');
}
try {
return compileProgram(programId, source, varyingNames || []);
} catch (e) {
failedPrograms[programId] = e.message;
throw e;
}
}
function compileProgram(programId, source, varyingNames) {
const cached = programCache[programId];
if (cached && !cached.disposed) {
gl.deleteProgram(cached.program);
gl.deleteShader(cached.vs);
gl.deleteShader(cached.fs);
cached.disposed = true;
}
const vs = gl.createShader(gl.VERTEX_SHADER);
gl.shaderSource(vs, source);
gl.compileShader(vs);
if (!gl.getShaderParameter(vs, gl.COMPILE_STATUS)) {
const log = gl.getShaderInfoLog(vs);
gl.deleteShader(vs);
throw new Error('Vertex shader compile error: ' + log);
}
const fsSource = '#version 300 es\nprecision mediump float;\nvoid main() {}\n';
const fs = gl.createShader(gl.FRAGMENT_SHADER);
gl.shaderSource(fs, fsSource);
gl.compileShader(fs);
if (!gl.getShaderParameter(fs, gl.COMPILE_STATUS)) {
const log = gl.getShaderInfoLog(fs);
gl.deleteShader(vs);
gl.deleteShader(fs);
throw new Error('Fragment shader compile error: ' + log);
}
const program = gl.createProgram();
gl.attachShader(program, vs);
gl.attachShader(program, fs);
if (varyingNames && varyingNames.length > 0) {
gl.transformFeedbackVaryings(program, varyingNames, gl.INTERLEAVED_ATTRIBS);
}
gl.linkProgram(program);
if (!gl.getProgramParameter(program, gl.LINK_STATUS)) {
const log = gl.getProgramInfoLog(program);
gl.deleteShader(vs);
gl.deleteShader(fs);
gl.deleteProgram(program);
throw new Error('Program link error: ' + log);
}
const entry = { program, vs, fs, uniformCache: {}, disposed: false, source, varyingNames };
programCache[programId] = entry;
return entry;
}
function getUniformLoc(cached, name) {
if (name in cached.uniformCache) return cached.uniformCache[name];
const loc = gl.getUniformLocation(cached.program, name);
cached.uniformCache[name] = loc;
return loc;
}
// ---- Kernel Dispatch ----
function dispatchKernel(msg) {
const { dispatchId, programId, source, varyingNames, totalVertices, dimX, dimY, dimZ, strides, outputs } = msg;
const kernelParams = msg.params;
// Errors left by earlier GL calls: they used to be discarded here without a trace. A failed texture upload is recorded on its buffer
// (and refuses the dispatch that binds it, below); anything else is reported so it cannot hide.
const staleErrors = drainGlErrors();
if (staleErrors.length > 0) console.error('[GLWorker] GL error(s) pending before dispatch ' + dispatchId + ': ' + staleErrors.join(', '));
// ---- Step 1: Get or compile program ----
const cached = getOrCompileProgram(programId, source, varyingNames);
gl.useProgram(cached.program);
// ---- ANGLE f64 workaround: set u_one = 1.0 ----
const uOneLoc = getUniformLoc(cached, 'u_one');
if (uOneLoc !== null) gl.uniform1f(uOneLoc, 1.0);
// ---- Loop guard: every generated loop runs `_loopN < u_loopLimit` (GLSLCodeGenerator). A uniform so
// D3D's FXC cannot see a trip count (its loop analysis is superlinear in the body); int max so no
// real loop is ever cut short. Absent (null) when the shader has no loops.
const uLoopLimitLoc = getUniformLoc(cached, 'u_loopLimit');
if (uLoopLimitLoc !== null) gl.uniform1i(uLoopLimitLoc, 2147483647);
// ---- Step 2: Dimension uniforms ----
const dimWLoc = getUniformLoc(cached, 'u_dimWidth');
if (dimWLoc) gl.uniform1i(dimWLoc, dimX);
const dimHLoc = getUniformLoc(cached, 'u_dimHeight');
if (dimHLoc) gl.uniform1i(dimHLoc, dimY);
// Grid size in groups and group size in threads, X/Y/Z (Grid.Idx/Dim, Group.Idx/Dim: the shader decodes
// gl_VertexID as groupLinear * groupSize + localLinear, X fastest). A uniform the compiler removed is null.
for (const name of ['gridDimX', 'gridDimY', 'gridDimZ', 'groupDimX', 'groupDimY', 'groupDimZ']) {
const loc = getUniformLoc(cached, 'u_' + name);
if (loc) gl.uniform1i(loc, msg[name] || 1);
}
// ---- Step 3: Bind parameters ----
let textureUnit = 0;
const bufferParamMap = []; // Track which params map to which bufferIds
// Resolve a param index to its uniform-name prefix.
// Direct param: paramIndex < 1000 -> "u_param{N}".
// Body-struct synthetic field: paramIndex >= 1000 -> "u_param{realN}_f{fi}"
// where realN = floor(paramIndex/1000)-1 and fi = paramIndex % 1000. Matches
// GLSLKernelFunctionGenerator.GetParamBindingName.
function resolveParamPrefix(paramIndex) {
if (paramIndex >= 1000) {
const realN = Math.floor(paramIndex / 1000) - 1;
const fi = paramIndex % 1000;
return 'u_param' + realN + '_f' + fi;
}
return 'u_param' + paramIndex;
}
for (const p of kernelParams) {
if (p.kind === 'buffer_ref') {
// GPU-resident buffer — bind existing texture from registry
const entry = bufferRegistry[p.bufferId];
if (!entry) throw new Error('Unknown bufferId: ' + p.bufferId);
if (entry.glError)
throw new Error('WebGL: buffer ' + p.bufferId + ' (kernel parameter ' + p.paramIndex + ') has no valid GPU texture (' + entry.glError
+ '), so this kernel cannot read it. Too many large buffers alive at once? Dispose buffers that are no longer needed.');
const texUnit = textureUnit++;
const uniformPrefix = resolveParamPrefix(p.paramIndex);
const uniformLoc = getUniformLoc(cached, uniformPrefix);
if (uniformLoc !== null) {
gl.activeTexture(gl.TEXTURE0 + texUnit);
gl.bindTexture(gl.TEXTURE_2D, entry.texture);
gl.uniform1i(uniformLoc, texUnit);
// Tile width uniform
const tileWLoc = getUniformLoc(cached, uniformPrefix + '_tileW');
if (tileWLoc) gl.uniform1i(tileWLoc, entry.width);
}
// Element count uniform for GetViewLength support
if (p.elementCount !== undefined) {
const lenLoc = getUniformLoc(cached, uniformPrefix + '_length');
if (lenLoc !== null) gl.uniform1i(lenLoc, p.elementCount | 0);
}
// SubView element offset — added to texelFetch indices when buffer is a SubView.
// Always set the uniform (including 0) so a prior dispatch's non-zero value
// doesn't leak across dispatches. WebGL uniforms persist on the program object
// across draw calls; if the previous dispatch with the same kernel had
// elementOffset=N (non-zero), the next dispatch with elementOffset=0 would
// read at offset N. Surfaced 2026-05-04 by Data's StyleMosaic Gather
// first-divergent-node trace where node 55 Gather output was 0 on WebGL while
// matching WebGPU exactly through node 54 (which read SubView(0, ...) and
// set the offset uniform to 0 implicitly via default; subsequent ops that
// read SubView(non-zero, ...) leaked their offset back into Gather's read).
const offsetLoc = getUniformLoc(cached, uniformPrefix + '_offset');
if (offsetLoc !== null) gl.uniform1i(offsetLoc, (p.elementOffset | 0));
// Stride uniforms for ArrayView2D/3D
if (strides && strides[p.paramIndex]) {
const dims = strides[p.paramIndex];
const strideLoc = getUniformLoc(cached, uniformPrefix + '_stride[0]');
if (strideLoc !== null) {
gl.uniform1iv(strideLoc, new Int32Array(dims));
}
}
bufferParamMap.push({ bufferId: p.bufferId, paramIndex: p.paramIndex });
} else if (p.kind === 'scalar') {
const uniformName = resolveParamPrefix(p.paramIndex);
const loc = getUniformLoc(cached, uniformName);
if (loc !== null) {
if (p.scalarType === 'int' || p.scalarType === 'bool' || p.scalarType === 'byte'
|| p.scalarType === 'sbyte' || p.scalarType === 'short' || p.scalarType === 'ushort'
|| p.scalarType === 'long') {
gl.uniform1i(loc, p.value | 0);
} else if (p.scalarType === 'uint' || p.scalarType === 'ulong') {
gl.uniform1ui(loc, p.value >>> 0);
} else if (p.scalarType === 'float' || p.scalarType === 'double') {
gl.uniform1f(loc, _bitsToFloat(p.value)); // value is the float's int32 bit pattern
} else {
console.warn('[GLWorker] Unknown scalar type:', p.scalarType, 'param:', p.paramIndex);
}
}
} else if (p.kind === 'scalar_emu64') {
const emuPrefix = resolveParamPrefix(p.paramIndex);
const loLoc = getUniformLoc(cached, emuPrefix + '_lo');
const hiLoc = getUniformLoc(cached, emuPrefix + '_hi');
if (loLoc !== null) gl.uniform1ui(loLoc, p.lo >>> 0);
if (hiLoc !== null) gl.uniform1ui(hiLoc, p.hi >>> 0);
} else if (p.kind === 'struct') {
for (const f of p.fields) {
const fieldLoc = getUniformLoc(cached, 'u_param' + p.paramIndex + '.' + f.path);
if (fieldLoc !== null) {
if (f.scalarType === 'int' || f.scalarType === 'bool') {
gl.uniform1i(fieldLoc, f.value | 0);
} else if (f.scalarType === 'uint') {
gl.uniform1ui(fieldLoc, f.value >>> 0);
} else {
gl.uniform1f(fieldLoc, _bitsToFloat(f.value)); // float field: int32 bit pattern
}
}
}
}
}
// ---- Step 4: Transform Feedback setup ----
let tfBuffer = null;
let transformFeedback = null;
// from the program cache: the message carries varying names with the program's first dispatch only
const vNames = cached.varyingNames || [];
if (vNames.length > 0) {
const tfFloatCount = totalVertices * vNames.length;
const tfByteSize = tfFloatCount * 4;
if (!cachedTFBuffer || cachedTFBufferSize < tfByteSize) {
if (cachedTFBuffer) gl.deleteBuffer(cachedTFBuffer);
cachedTFBuffer = gl.createBuffer();
cachedTFBufferSize = tfByteSize;
gl.bindBuffer(gl.TRANSFORM_FEEDBACK_BUFFER, cachedTFBuffer);
gl.bufferData(gl.TRANSFORM_FEEDBACK_BUFFER, tfByteSize, gl.DYNAMIC_READ);
} else {
gl.bindBuffer(gl.TRANSFORM_FEEDBACK_BUFFER, cachedTFBuffer);
}
tfBuffer = cachedTFBuffer;
if (!cachedTFObject) {
cachedTFObject = gl.createTransformFeedback();
}
transformFeedback = cachedTFObject;
gl.bindTransformFeedback(gl.TRANSFORM_FEEDBACK, transformFeedback);
gl.bindBufferBase(gl.TRANSFORM_FEEDBACK_BUFFER, 0, tfBuffer);
}
// ---- Step 5: Dispatch via DrawArrays ----
if (!cachedDummyVAO) {
cachedDummyVAO = gl.createVertexArray();
}
gl.bindVertexArray(cachedDummyVAO);
if (!cachedDummyVBO || cachedDummyVBOSize < totalVertices * 4) {
if (cachedDummyVBO) gl.deleteBuffer(cachedDummyVBO);
cachedDummyVBO = gl.createBuffer();
cachedDummyVBOSize = totalVertices * 4;
gl.bindBuffer(gl.ARRAY_BUFFER, cachedDummyVBO);
gl.bufferData(gl.ARRAY_BUFFER, cachedDummyVBOSize, gl.STATIC_DRAW);
gl.enableVertexAttribArray(0);
gl.vertexAttribPointer(0, 1, gl.FLOAT, false, 0, 0);
} else {
gl.bindBuffer(gl.ARRAY_BUFFER, cachedDummyVBO);
}
gl.enable(gl.RASTERIZER_DISCARD);
if (transformFeedback) gl.beginTransformFeedback(gl.POINTS);
gl.drawArrays(gl.POINTS, 0, totalVertices);
if (transformFeedback) gl.endTransformFeedback();
gl.disable(gl.RASTERIZER_DISCARD);
// A draw that FAILED wrote nothing, and its transform feedback buffer reads back as "no store site stored", so every output kept
// its old value and the dispatch looked successful (DeviceVectorIndex scores: all the fresh buffer's zeros, 2026-11-01).
const drawErrors = drainGlErrors();
// Unbind TF before readback (WebGL2 spec requirement)
if (transformFeedback) {
gl.bindBufferBase(gl.TRANSFORM_FEEDBACK_BUFFER, 0, null);
gl.bindTransformFeedback(gl.TRANSFORM_FEEDBACK, null);
}
// ---- Step 6: TF Readback → update GPU-resident buffers ----
// A readback that refuses the dispatch (a store site with two elements, an address out of bounds) must still
// finish the GL state below: the error used to skip it, the TF buffer stayed bound, and the NEXT dispatch read this
// dispatch's records (StoreAddress_OffSlotStore after StoreAddress_OneSiteManyElements).
let readbackError = null;
if (drawErrors.length > 0) {
const src = cached.source || '';
const bound = bufferParamMap.map(function (b) {
const e = bufferRegistry[b.bufferId];
const m = src.match(new RegExp('uniform\\s+(?:highp\\s+|mediump\\s+|lowp\\s+)?(\\w*sampler2D)\\s+' + resolveParamPrefix(b.paramIndex) + '\\s*;'));
return resolveParamPrefix(b.paramIndex) + ': ' + (m ? m[1] : '?') + ' over ' + (e ? (e.glslType || 'float') + ' ' + e.width + 'x' + e.height : 'no buffer');
});
readbackError = new Error('WebGL: the kernel draw failed (' + drawErrors.join(', ') + ' over ' + totalVertices + ' vertices); its results were not written. '
+ 'Bound buffers (shader sampler over texture format): ' + bound.join('; '));
}
if (!readbackError && tfBuffer && vNames.length > 0 && outputs && outputs.length > 0) {
// gl.finish() blocks until all submitted GL commands (including TF) complete.
// Note: ANGLE emits a cosmetic "READ-usage buffer" warning here because it
// doesn't track gl.finish() as a fence. This warning is harmless — the GPU
// has completed all writes before we read. Using async fenceSync would
// eliminate the warning but adds unacceptable scheduling overhead for
// real-time rendering (~4-50ms per dispatch).
gl.finish();
gl.bindBuffer(gl.TRANSFORM_FEEDBACK_BUFFER, tfBuffer);
const tfElemCount = totalVertices * vNames.length;
// Read as raw bytes via Uint8Array — passing Float32Array as the destination
// makes Chrome canonicalize specific bit patterns through the float view
// (observed 2026-05-04: writing 0x80000000u via TF reads back as 0x80000001
// when getBufferSubData destination is Float32Array; Uint8Array preserves
// the bit pattern exactly). Tests23_BareUintShift / NormalizeShape_BareCondition
// surfaced this — see _DevComms/SpawnDev.ILGPU.
const readbackBytes = new Uint8Array(tfElemCount * 4);
gl.getBufferSubData(gl.TRANSFORM_FEEDBACK_BUFFER, 0, readbackBytes);
const readbackFloat = new Float32Array(readbackBytes.buffer);
const varyingCount = vNames.length;
const strideBytes = varyingCount * 4;
// Set of bufferIds that were modified (need texture re-upload)
const modifiedBufferIds = new Set();
// The element vertex v's store of output `out` targets, or -1 when that store site did not store in v. A store
// site's value lands at its group base + siteConst (GLSLKernelFunctionGenerator.EmitStoreAddressVaryings); a
// varying without a base (baseIndex < 0) is the vertex's own element (slot within a positional record).
// Plans/webgl-store-addresses-2026-10-26.md: before this every value landed at the vertex's own element.
const int32All = new Int32Array(readbackBytes.buffer);
const strideWords = varyingCount;
// Elements a dispatch does not store keep the values in the CPU mirror, which is then re-uploaded whole: a
// mirror a scatter left stale must be read back first, or that upload would revert the scatter's results.
for (let oi = 0; oi < outputs.length; oi++) {
if (!outputs[oi].isAtomicVote) ensureCpuFresh(bufferRegistry[outputs[oi].bufferId]);
}
function storeElement(out, v, elemCount) {
if (out.baseIndex < 0) {
const own = v * (out.storeCount || 1) + (out.storeSlot >= 0 ? out.storeSlot : 0);
return own < elemCount ? own : -1;
}
if ((int32All[v * strideWords + out.maskIndex] & out.maskBit) === 0) return -1;
const base = int32All[v * strideWords + out.baseIndex];
if (base === -2)
throw new Error('WebGL: a store site of output ' + out.varyingName + ' wrote two different elements in one thread (vertex ' + v +
'). Transform feedback captures one element per store site per thread; a kernel that scatters several elements from one store needs WebGPU/Wasm/desktop (AcceleratorRequirements.RequiresScatterStores).');
const e = base + out.siteConst;
if (e < 0 || e >= elemCount)
throw new Error('WebGL: output ' + out.varyingName + ' stored element ' + e + ' outside its view of ' + elemCount + ' elements (vertex ' + v + ')');
return e;
}
try {
for (let oi = 0; oi < outputs.length; oi++) {
const out = outputs[oi];
// Atomic vote: each thread emitted its increment amount; sum all and add to buffer[element].
// This emulates Atomic.Add without true GPU atomics (WebGL2 vertex shader limitation).
if (out.isAtomicVote) {
const entry = bufferRegistry[out.bufferId];
if (!entry) continue;
const destView = entry.data;
const writeOffset = out.writeByteOffset;
// Sum all per-vertex vote values (stored as int in the TF buffer)
const int32TF = new Int32Array(readbackFloat.buffer);
let sum = 0;
for (let v = 0; v < totalVertices; v++) {
sum += int32TF[(v * strideBytes + out.outputIndex * 4) >> 2];
}
// Accumulate (not replace) the target buffer element using Int32 arithmetic
const destInt32 = new Int32Array(destView.buffer);
const destIdx = writeOffset >> 2;
destInt32[destIdx] = destInt32[destIdx] + sum;
modifiedBufferIds.add(out.bufferId);
continue;
}
// Skip 'hi' emulated varyings (read with their 'lo' counterpart)
if (out.isEmulated && out.emulatedSuffix === 'hi') continue;
// Find the registry entry for this output
const entry = bufferRegistry[out.bufferId];
if (!entry) continue;
const destView = entry.data;
const writeOffset = out.writeByteOffset;
if (out.fieldIndex >= 0) {
// Struct field output - either a plain scalar field, or the 'lo' half of a
// 64-bit emulated field ('hi' halves were already skipped above). Checked
// BEFORE the plain isEmulated/'lo' branch below because a struct field's
// lo varying also has isEmulated=true, but must NOT go through the flat
// (non-struct) 8-bytes-per-vertex reconstruction - it's one field of a
// larger per-vertex struct record, at its own byte offset within it.
//
// Run the whole-struct reconstruction exactly once, triggered by the first
// (lowest outputIndex) struct-field varying for this param.
const structVaryings = outputs.filter(o => o.paramIndex === out.paramIndex && o.fieldIndex >= 0);
if (structVaryings[0].outputIndex !== out.outputIndex) continue;
// One representative varying per logical field (its 'lo' half for an
// emulated 64-bit field, the field itself otherwise), in field order. Each
// carries the field's REAL byte offset and size inside the element and the
// element size, from ILGPU's struct layout (GLSLKernelFunctionGenerator
// StructLeaf) - alignment padding included, so { int; long; } puts the long at
// byte 8. Only the field's own bytes are written: a sub-4-byte field copies the
// low bytes of its 32-bit varying and never touches its neighbours.
const maxFieldIndex = Math.max(...structVaryings.map(o => o.fieldIndex));
const fieldsInOrder = [];
for (let f = 0; f <= maxFieldIndex; f++) {
const forField = structVaryings.filter(o => o.fieldIndex === f);
fieldsInOrder.push(forField.find(o => o.emulatedSuffix === 'lo') || forField[0]);
}
const fieldByteWidths = fieldsInOrder.map(o => o.fieldByteSize);
const structElemSize = fieldsInOrder[0].structByteSize;
const fieldByteOffsets = fieldsInOrder.map(o => o.fieldByteOffset);
const viewElems = Math.floor(out.writeLengthBytes / structElemSize);
for (let v = 0; v < totalVertices; v++) {
const e = storeElement(fieldsInOrder[0], v, viewElems);
if (e < 0) continue;
for (let fi = 0; fi < fieldsInOrder.length; fi++) {
const fieldOut = fieldsInOrder[fi];
const dstOff = writeOffset + e * structElemSize + fieldByteOffsets[fi];
const srcOff = v * strideBytes + fieldOut.outputIndex * 4;
if (srcOff + 4 > readbackBytes.length) continue;
const loBytes = Math.min(fieldByteWidths[fi], 4);
for (let b = 0; b < loBytes; b++) destView[dstOff + b] = readbackBytes[srcOff + b];
if (fieldByteWidths[fi] === 8) {
const hiSrc = v * strideBytes + (fieldOut.outputIndex + 1) * 4;
destView[dstOff + 4] = readbackBytes[hiSrc];
destView[dstOff + 5] = readbackBytes[hiSrc + 1];
destView[dstOff + 6] = readbackBytes[hiSrc + 2];
destView[dstOff + 7] = readbackBytes[hiSrc + 3];
}
}
}
} else if (out.isEmulated && out.emulatedSuffix === 'lo') {
// A thread that stores MULTIPLE emulated-64-bit elements into this buffer
// (positional multi-store, e.g. digest[base+0..3] = o0..o3, each 8 bytes) gets
// one lo/hi varying PAIR per slot (EmitOutputVaryings' emuStoreCount branch) -
// place each slot at its own offset within the per-vertex record instead of
// always writeOffset + v*8 (which only ever wrote slot 0's storage location,
// repeatedly, for every slot - the actual root cause of the "Compress ref
// write-back" symptom: every store after the first silently overwrote the same
// 8 bytes, so only the LAST store's value ever reached the host, discovered and
// fixed 2026-09-22 with a minimal repro that reproduced it standalone, no ref
// params or fn-def calls needed at all).
const hiOutIdx = out.outputIndex + 1;
const viewElems = Math.floor(out.writeLengthBytes / 8);
for (let v = 0; v < totalVertices; v++) {
const e = storeElement(out, v, viewElems);
if (e < 0) continue;
const loSrc = v * strideBytes + out.outputIndex * 4;
const hiSrc = v * strideBytes + hiOutIdx * 4;
const dst = writeOffset + e * 8;
destView[dst] = readbackBytes[loSrc];
destView[dst + 1] = readbackBytes[loSrc + 1];
destView[dst + 2] = readbackBytes[loSrc + 2];
destView[dst + 3] = readbackBytes[loSrc + 3];
destView[dst + 4] = readbackBytes[hiSrc];
destView[dst + 5] = readbackBytes[hiSrc + 1];
destView[dst + 6] = readbackBytes[hiSrc + 2];
destView[dst + 7] = readbackBytes[hiSrc + 3];
}
} else if (out.fieldIndex < 0) {
// Sub-word packing: TF outputs one i32 per element, but the destination
// buffer stores packed sub-word values (e.g. 2 shorts per i32).
// Pack by reading each TF i32 and writing only the sub-word portion.
if (out.subWordElementSize && out.subWordElementSize < 4) {
const swSize = out.subWordElementSize;
const viewElems = Math.floor(out.writeLengthBytes / swSize);
for (let v = 0; v < totalVertices; v++) {
const e = storeElement(out, v, viewElems);
if (e < 0) continue;
const srcIdx = (v * strideBytes + out.outputIndex * 4) >> 2;
const val = int32All[srcIdx];
const dstOff = writeOffset + e * swSize;
if (swSize === 2) {
// Pack as 16-bit (little-endian)
destView[dstOff] = val & 0xFF;
destView[dstOff + 1] = (val >> 8) & 0xFF;
} else if (swSize === 1) {
destView[dstOff] = val & 0xFF;
}
}
} else if (out.baseIndex < 0 && (out.storeCount || 1) === 1 && ((destView.byteOffset + writeOffset) & 3) === 0) {
// Vertex v's value is element v (an own-element output, GLSLKernelFunctionGenerator
// _ownElementOutputs): one typed copy instead of a per-element call and four byte copies,
// which cost as much as the readback itself (WebGL 1.4M radix sort: 5.7 s of 800 dispatches).
const n = Math.min(totalVertices, Math.floor(out.writeLengthBytes / 4));
const dst32 = new Int32Array(destView.buffer, destView.byteOffset + writeOffset, n);
if (strideWords === 1) dst32.set(int32All.subarray(0, n));
else {
const o = out.outputIndex;
for (let v = 0; v < n; v++) dst32[v] = int32All[v * strideWords + o];
}
} else {
const viewElems = Math.floor(out.writeLengthBytes / 4);
for (let v = 0; v < totalVertices; v++) {
const e = storeElement(out, v, viewElems);
if (e < 0) continue;
const srcOff = v * strideBytes + out.outputIndex * 4;
const dstOff = writeOffset + e * 4;
if (srcOff + 4 <= readbackBytes.length) {
destView[dstOff] = readbackBytes[srcOff];
destView[dstOff + 1] = readbackBytes[srcOff + 1];
destView[dstOff + 2] = readbackBytes[srcOff + 2];
destView[dstOff + 3] = readbackBytes[srcOff + 3];
}
}
}
}
modifiedBufferIds.add(out.bufferId);
}
} catch (err) {
readbackError = err;
}
gl.bindBuffer(gl.TRANSFORM_FEEDBACK_BUFFER, null);
// Re-upload modified buffers to their GPU textures (GPU-resident update; also after a refused readback, so
// the CPU mirror and the texture agree)
for (const bid of modifiedBufferIds) {
const entry = bufferRegistry[bid];
if (entry) {
uploadTextureData(entry.texture, entry);
}
}
}
gl.useProgram(null);
// A context lost DURING the dispatch (driver reset, GPU hang) reads back an all-zero transform feedback buffer: no
// store-site bit set, so every element kept its old value and the dispatch looked successful (SpawnDev.Codecs
// VorbisResidueAccumulateGpu_Type2: target came back untouched, nothing refused). The webglcontextlost event comes
// later, asynchronously; isContextLost() is the synchronous answer.
if (!readbackError && gl.isContextLost())
readbackError = new Error('WebGL: the context was lost during this dispatch (GPU reset or driver crash); its results were not written.');
if (readbackError) throw readbackError;
// No ArrayBuffer transfers — data stays GPU-resident in the worker
return {
message: { done: true, dispatchId },
transferList: []
};
}
// ---- ImageBitmap blit ----
// Creates an ImageBitmap from an RGBA pixel buffer and transfers it to the main thread.
// The browser compositor manages the bitmap as a GPU texture — no pixel copy on transfer.
function handleBlitBuffer(msg) {
const { bufferId, width, height, requestId } = msg;
const entry = bufferRegistry[bufferId];
if (!entry) {
self.postMessage({ type: 'blitResult', requestId, error: 'unknown bufferId' });
return;
}
// entry.data is always current after dispatch (TF readback keeps it in sync).
// Wrap as Uint8ClampedArray for ImageData — no copy, just a typed view.
const rgba = new Uint8ClampedArray(entry.data.buffer, 0, width * height * 4);
const imageData = new ImageData(rgba, width, height);
createImageBitmap(imageData).then(function(bitmap) {
self.postMessage({ type: 'blitResult', requestId, bitmap }, [bitmap]);
}).catch(function(err) {
self.postMessage({ type: 'blitResult', requestId, error: err.message });
});
}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408'use strict';// SpawnDev.ILGPU WebGPU dispatch-plan replay helper (loaded on demand via dynamic import of// _content/SpawnDev.ILGPU/webgpuDispatchPlan.js - the glWorker.js static-asset pattern).//// A dispatch plan is a flat JS array of 7-element tagged records:// [0, pipeline, bindGroup, x, y, z, submitAfter] - compute dispatch (submitAfter 1 = end the// command buffer right after it: the NVIDIA// large-function-array WORKAROUND,// https://github.com/LostBeard/SpawnDev.ILGPU/issues/10)// [1, srcBuffer, srcOffset, dstBuffer, dstOffset, size, 0] - copyBufferToBuffer// [2, buffer, offset, size, 0, 0, 0] - clearBuffer (zero-fill)// It is recorded ONCE by WebGPUDispatchPlan during a capture forward (the plan array holding the// GPU objects is what keeps them alive - .NET-side wrapper disposal is irrelevant), then replayed// here with a SINGLE .NET->JS interop crossing per forward: this loop re-encodes every operation// into one command encoder in pure JS (microseconds per entry) and submits one command buffer.// This is the browser twin of CUDA graph replay - WebGPU has no graph API, but the command encoder// IS the graph recorder, and WebGPU guarantees ordering with implicit synchronization between// passes/copies on the same queue.(() => { // Bind-group cache generation size (per device). Two generations: a lookup that misses the current one but hits the // previous one promotes the group; when the current generation passes this size it becomes the previous one and the // old previous one is dropped. So a group used at least once per generation is never dropped, while groups of a // shape no longer in use age out. MEASURED 2026-10-02 (Anaglyphohol DAv3 video): one input shape is ~2.8k distinct // groups, but the adaptive depth level cycles through many shapes (55k groups in all) - a single map cleared at a // cap kept dropping the hot shape (20% hits); with generations the hot shapes stay. const BG_GEN_MAX = 8192; const api = { // JS-side timing of the most recent replay() call on this page: encodeMs = the re-encode // loop (createCommandEncoder .. last op), submitMs = enc.finish() + queue.submit(). GPU // EXECUTION is not included - it completes asynchronously after submit (await // onSubmittedWorkDone / SynchronizeAsync for that). Reading performance.now() is ~free, // so this records unconditionally; .NET fetches it on demand only. last: { ops: 0, encodeMs: 0, submitMs: 0 }, // Per-device staging buffer for submitBatch's ordered host uploads (tag 4). Grows, never shrinks. _staging: new WeakMap(), // Per-device bind-group cache for submitBatch (api.bindGroupReuse): key = layout id + every entry's // (binding, buffer id, offset, size) -> GPUBindGroup, in two generations of up to BG_GEN_MAX (see there), so a // workload whose buffers churn costs a bounded amount of memory. bgHits/bgMisses are cumulative counters. _bindGroups: new WeakMap(), bgHits: 0, bgMisses: 0, bgDrops: 0, // generations started (first use per device, then one per rotation) bgLastKey: '', // the most recent miss's key (diagnostic) // ── Interop cost probes ───────────────────────────────────────────────────────────────── // These do NOTHING on purpose. device.createBindGroup measured 1.14 ms per call in a Kokoro // pass (2,117 ms of 2,128 ms of the whole bind-group phase), and "1.14 ms" has three possible // owners with three different fixes: the .NET->JS crossing itself, MARSHALLING the descriptor // (its members are walked and rebuilt as a JS object per call - a layout reference, an entries // array, and a nested resource object per entry - so the cost scales with members), or Dawn's // own validation. A no-op crossing brackets the first; a no-op crossing that still marshals the // descriptor brackets the first two; whatever the real call costs beyond that is Dawn's. // noopDescriptor touches .entries.length so the marshalled object cannot be optimised away. noop(x) { return x | 0; }, // WebGPUBackend.BatchSinglePass -> submitBatch (see there). Set from C# when the switch changes. setSinglePass(v) { api.singlePass = !!v; return 0; }, // WebGPUBackend.BatchBindGroupReuse -> submitBatch's bind-group cache. Turning it off drops every cached group. setBindGroupReuse(v) { api.bindGroupReuse = !!v; if (!api.bindGroupReuse) api._bindGroups = new WeakMap(); return 0; }, // DIAGNOSTIC ABLATION (WebGPUBackend.DiagSubmitAblation; results are garbage while set): 2 = skip createBindGroup // + the dispatch encode, 3 = return without doing anything. (A "skip only the scalar writes" mode ran every // kernel on stale loop bounds and HUNG the GPU - DXGI_ERROR_DEVICE_HUNG; 2 vs 3 measures the writes safely.) setAblation(v) { api.ablation = v | 0; return 0; }, noopDescriptor(desc) { return desc && desc.entries ? desc.entries.length : 0; },
// The SpawnJS instance whose wasm heap submitHeader reads (C# passes SpawnJSRuntime.DotnetInstance.Id once). // getHeap() returns the CURRENT heap buffer - it re-fetches it after memory growth detached the old one. setHeapSource(dotnetId) { api._heapInst = globalThis.SpawnJSInterop.getInstace(dotnetId); return 0; }, // The batch submit's entry from WebGPUStream.SubmitBatch: ONE number crosses - the heap address of a pinned // Float64 header - and everything else is read from the wasm heap here: // [0] device id [1] records addr [2] record count [3] data addr [4] data byte length // [5] maxPassesPerSubmit [6] upload bytes [7..10] arenaR id, bytes, arenaW id, bytes // [11] single pass (0/1) [12] ablation [13] bind-group reuse (0/1) // The records and data arrays are pinned C# arrays (never moved), so views over the heap at their // addresses ARE the arrays - nothing is copied and no HeapView object is created per submit. submitHeader(hdrAddr) { const heap = api._heapInst.getHeap(); const h = new Float64Array(heap, hdrAddr, 14); api.singlePass = h[11] !== 0; api.ablation = h[12] | 0; const reuse = h[13] !== 0; if (reuse !== (api.bindGroupReuse !== false)) api.setBindGroupReuse(reuse); const device = globalThis.SpawnJSInterop.spawnJSObjects[h[0]]; if (!device) throw new Error(`ilgpuWebGPUPlan.submitHeader: device (SpawnJS id ${h[0]}) is not held`); const n = h[2]; const rec = new Float64Array(heap, h[1], n); const data = new Uint8Array(heap, h[3], h[4]); return api.submitBatch(device, rec, n, data, h[5], h[6], h[7], h[8], h[9], h[10]); },
// Rewrite the dstOffset (slot [i*7+4]) of copy entries in place - the patch surface for // parameterized replay (e.g. a KV-cache append whose destination row advances per decode // token). Entries must be tag-1 copies; throws otherwise (a wrong index would silently // corrupt a dispatch record). patchCopyDst(plan, entryIndices, newDstOffsets) { for (let k = 0; k < entryIndices.length; k++) { const i = entryIndices[k] * 7; if (plan[i] !== 1) throw new Error(`patchCopyDst: entry ${entryIndices[k]} is tag ${plan[i]}, not a copy`); plan[i + 4] = newDstOffsets[k]; } }, // Submits the accelerator's PLAIN (uncaptured) dispatch batch: WebGPUStream appends numeric // records while kernels are dispatched and hands the whole batch over in ONE crossing here, where // the bind groups are created and every op is encoded. Every GPU object is named by its SpawnJS // hold id and resolved from SpawnJSInterop.spawnJSObjects, so no descriptor is ever marshalled - // SpawnJS builds a nested .NET object one property Set per member, ~40 crossings for a bind-group // descriptor, which is what made createBindGroup the largest host cost of a graph forward. // Records (Float64Array `rec`, first `n` values): // [0, pipelineId, layoutId, nEntries, x, y, z, (binding, bufferId, offset, size) * nEntries] // [1, srcId, srcOffset, dstId, dstOffset, size] copyBufferToBuffer // [2, bufferId, offset, size] clearBuffer // [3, bufferId, bufferOffset, dataOffset, size] queue.writeBuffer from `data` (Uint8Array) // [4, bufferId, bufferOffset, dataOffset, size] ORDERED host upload: copyBufferToBuffer from the // staging copy of `data`, encoded in record order // A tag-3 write is issued when it is reached, so it precedes the submit of the command buffer holding // the dispatch that reads it - the same order as the per-dispatch path (write now, submit later). It // is only for buffers the batch alone uses (per-dispatch scalar/stride/lock buffers). // A tag-4 upload targets an ordinary buffer that earlier records in the batch may still read, so it // must land exactly where it sits in the batch: `data` is written ONCE into a persistent staging // buffer and each upload is a copyBufferToBuffer in record order. Reusing the staging buffer across // batches is safe because queue.writeBuffer executes after all previously submitted work. // Command buffers are split every maxPassesPerSubmit dispatches (see replay() for why). // SCALAR ARENAS (WebGPUBackend.BatchScalarArena): the batch's per-dispatch scalars are 256-byte slots of two // arena buffers (arenaRId: read-only bindings, arenaWId: read_write struct scalars; 0 = unused). Their used // prefixes are the LAST arenaRBytes + arenaWBytes bytes of `data` and are written FIRST, before any command // buffer of this batch is submitted - every slot is used once per batch, so one write per arena is exact. // BIND-GROUP REUSE (api.bindGroupReuse): a bind group is immutable and SpawnJS hold ids are never reused, so // two dispatch records with equal layout + entries can share one; with the arenas the keys repeat every frame. // ONE COMPUTE PASS FOR A RUN OF DISPATCHES (api.singlePass, set from WebGPUBackend.BatchSinglePass - default // true): consecutive dispatch records share an open pass; it is ended before an encoder-level command (copy, // clear, upload) and at every submit, and setPipeline is skipped when the pipeline repeats. Ordering is the // spec's, not ours: every dispatch in a compute pass is its OWN usage scope, so a storage write by one dispatch // is visible to the next exactly as across passes - the implementation inserts the barrier. What a pass per // dispatch added was a beginComputePass/end pair (and a fresh pass state) for each of ~800 dispatches a frame. // Returns the number of records processed. submitBatch(device, rec, n, data, maxPassesPerSubmit, uploadBytes, arenaRId, arenaRBytes, arenaWId, arenaWBytes) { const ablation = api.ablation | 0; if (ablation === 3) return 0; const objs = globalThis.SpawnJSInterop.spawnJSObjects; const obj = (id, what, at) => { const o = objs[id]; if (o === undefined || o === null) throw new Error(`ilgpuWebGPUPlan.submitBatch: ${what} (SpawnJS id ${id}) at record ${at} is not held - it was disposed while a dispatch still referenced it`); return o; }; const cap = (maxPassesPerSubmit > 0) ? (maxPassesPerSubmit | 0) : 0x7fffffff; const queue = device.queue; let staging = null; if (uploadBytes > 0) { staging = api._staging.get(device); if (!staging || staging.size < uploadBytes) { if (staging) staging.destroy(); // its last readers were submitted; destroy waits for them let size = 65536; while (size < uploadBytes) size *= 2; staging = device.createBuffer({ label: 'ilgpu-batch-upload-staging', size, usage: GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST }); api._staging.set(device, staging); } queue.writeBuffer(staging, 0, data, 0, uploadBytes); } const arenaOff = data.length - (arenaRBytes | 0) - (arenaWBytes | 0); if (arenaRBytes > 0) queue.writeBuffer(obj(arenaRId, 'scalar arena', -1), 0, data, arenaOff, arenaRBytes); if (arenaWBytes > 0) queue.writeBuffer(obj(arenaWId, 'scalar arena (read_write)', -1), 0, data, arenaOff + arenaRBytes, arenaWBytes); let bgCache = null; if (api.bindGroupReuse !== false) { bgCache = api._bindGroups.get(device); if (!bgCache) { bgCache = { cur: new Map(), prev: new Map() }; api._bindGroups.set(device, bgCache); api.bgDrops++; } else if (bgCache.cur.size > BG_GEN_MAX) { bgCache.prev = bgCache.cur; bgCache.cur = new Map(); api.bgDrops++; } } const single = api.singlePass !== false; let enc = null, passes = 0, ops = 0; let pass = null, passPipeline = null; const endPass = () => { if (pass !== null) { pass.end(); pass = null; passPipeline = null; } }; for (let i = 0; i < n; ops++) { const tag = rec[i]; if (tag === 0 && ablation === 2) { i += 7 + 4 * rec[i + 3]; } else if (tag === 0) { const ne = rec[i + 3]; const j0 = i + 7, jEnd = j0 + 4 * ne; let bindGroup, key; if (bgCache !== null) { key = '' + rec[i + 2]; for (let j = j0; j < jEnd; j++) key += ',' + rec[j]; bindGroup = bgCache.cur.get(key); if (bindGroup === undefined) { bindGroup = bgCache.prev.get(key); if (bindGroup !== undefined) bgCache.cur.set(key, bindGroup); } } if (bindGroup === undefined) { const entries = new Array(ne); for (let e = 0, j = j0; e < ne; e++, j += 4) entries[e] = { binding: rec[j], resource: { buffer: obj(rec[j + 1], 'buffer', i), offset: rec[j + 2], size: rec[j + 3] } }; bindGroup = device.createBindGroup({ layout: obj(rec[i + 2], 'bind group layout', i), entries }); if (bgCache !== null) { bgCache.cur.set(key, bindGroup); api.bgMisses++; api.bgLastKey = key; } } else api.bgHits++; const j = jEnd; if (enc === null) enc = device.createCommandEncoder(); const pipeline = obj(rec[i + 1], 'pipeline', i); if (single) { if (pass === null) pass = enc.beginComputePass(); if (pipeline !== passPipeline) { pass.setPipeline(pipeline); passPipeline = pipeline; } pass.setBindGroup(0, bindGroup); pass.dispatchWorkgroups(rec[i + 4], rec[i + 5], rec[i + 6]); } else { const p1 = enc.beginComputePass(); p1.setPipeline(pipeline); p1.setBindGroup(0, bindGroup); p1.dispatchWorkgroups(rec[i + 4], rec[i + 5], rec[i + 6]); p1.end(); } i = j; if (++passes >= cap) { endPass(); queue.submit([enc.finish()]); enc = null; passes = 0; } } else if (tag === 1) { endPass(); if (enc === null) enc = device.createCommandEncoder(); enc.copyBufferToBuffer(obj(rec[i + 1], 'copy source', i), rec[i + 2], obj(rec[i + 3], 'copy destination', i), rec[i + 4], rec[i + 5]); i += 6; } else if (tag === 2) { endPass(); if (enc === null) enc = device.createCommandEncoder(); enc.clearBuffer(obj(rec[i + 1], 'clear target', i), rec[i + 2], rec[i + 3]); i += 4; } else if (tag === 3) { queue.writeBuffer(obj(rec[i + 1], 'write target', i), rec[i + 2], data, rec[i + 3], rec[i + 4]); i += 5; } else if (tag === 4) { endPass(); if (enc === null) enc = device.createCommandEncoder(); enc.copyBufferToBuffer(staging, rec[i + 3], obj(rec[i + 1], 'upload target', i), rec[i + 2], rec[i + 4]); i += 5; } else { throw new Error(`ilgpuWebGPUPlan.submitBatch: bad record tag ${tag} at ${i}`); } } endPass(); if (enc !== null) queue.submit([enc.finish()]); return ops; },
// Replays a recorded plan on the given device: one pass per dispatch (pass-per-dispatch keeps // storage-buffer write->read ordering guarantees airtight), copies/clears encoded inline in // captured order, submitted in BATCHES of maxPassesPerSubmit compute passes. // Returns the number of operations encoded. // // 🔴 WHY THIS BATCHES INSTEAD OF SUBMITTING ONCE. It used to encode the whole plan into a // single command encoder and issue one queue.submit(). That is fine for a small plan and it // LOSES THE DEVICE for a large one: MEASURED 2026-09-15, Kokoro at input_ids[1,360] replayed // and Chrome came back "WebGPU device has been lost and cannot accept commands" - the GPU // watchdog killing a single command buffer that ran too long. A 35-token Kokoro plan is // already 3,155 dispatches; the 360-token one is several times that, in ONE buffer, with no // point at which the driver can preempt. // // The uncaptured path never had this problem because WebGPUStream flushes as it goes - the // library's own documented rule is "if dispatching many kernels (>50), call Flush() every // 16-32 dispatches". Capture replay was the one path that ignored it. Splitting into several // command buffers changes nothing about ordering: buffers submitted to the same queue execute // in submission order, and the implicit inter-pass synchronization is per-queue, not // per-buffer. replay(device, plan, maxPassesPerSubmit) { const t0 = performance.now(); const cap = (maxPassesPerSubmit > 0) ? (maxPassesPerSubmit | 0) : 0x7fffffff; const n = plan.length; let enc = device.createCommandEncoder(); let passesInBatch = 0; let submitMs = 0; const flush = () => { const s0 = performance.now(); device.queue.submit([enc.finish()]); submitMs += performance.now() - s0; passesInBatch = 0; }; for (let i = 0; i < n; i += 7) { const tag = plan[i]; if (tag === 0) { const pass = enc.beginComputePass(); pass.setPipeline(plan[i + 1]); pass.setBindGroup(0, plan[i + 2]); pass.dispatchWorkgroups(plan[i + 3], plan[i + 4], plan[i + 5]); pass.end(); // Close the batch only BETWEEN operations, never inside a pass. A dispatch marked submitAfter // (WORKAROUND, issue #10) must not share its command buffer with anything after it. ++passesInBatch; if (plan[i + 6] === 1 || passesInBatch >= cap) { flush(); enc = device.createCommandEncoder(); } } else if (tag === 1) { enc.copyBufferToBuffer(plan[i + 1], plan[i + 2], plan[i + 3], plan[i + 4], plan[i + 5]); } else if (tag === 2) { enc.clearBuffer(plan[i + 1], plan[i + 2], plan[i + 3]); } } const t1 = performance.now(); flush(); // the tail (a no-op encoder submits an empty buffer, which is legal) api.last.ops = n / 7; api.last.encodeMs = (t1 - t0) - submitMs; api.last.submitMs = submitMs; return n / 7; }, // Replays the plan with per-pass GPU timestamps and returns a JSON string aggregating GPU // time by pipeline label (the kernel name). Requires the device to have 'timestamp-query' // (requested by ILGPU device init when the adapter supports it) - returns // {"supported":false} otherwise. One timestamp at the START of each compute pass plus the // END of the last pass: passes execute back-to-back on the queue, so t[k+1]-t[k] is pass // k's duration (encoder-level copies/clears between passes are attributed to the preceding // pass - negligible). Chunked across query sets (4096 timestamps max each). NOTE: Chrome // quantizes timestamps to 100us unless --enable-webgpu-developer-features - the total // (last-first) telescopes exactly either way, but fine per-kernel attribution wants the // flag. Waits for GPU completion internally (the resolve readback maps after the work). async replayTimed(device, plan) { if (!device.features.has('timestamp-query')) return JSON.stringify({ supported: false, reason: "device lacks timestamp-query" }); const n = plan.length; const passIdx = []; // plan record offset of each compute pass for (let i = 0; i < n; i += 7) if (plan[i] === 0) passIdx.push(i); const passes = passIdx.length; if (passes === 0) return JSON.stringify({ supported: false, reason: "plan has no compute passes" }); const QS_CAP = 4096; const stamps = passes + 1; const querySets = []; for (let remaining = stamps; remaining > 0; remaining -= QS_CAP) querySets.push(device.createQuerySet({ type: 'timestamp', count: Math.min(remaining, QS_CAP) })); const qsOf = k => querySets[Math.floor(k / QS_CAP)]; const qiOf = k => k % QS_CAP;
let enc = device.createCommandEncoder(); // The last pass also writes the closing timestamp (its end). timestampWrites targets ONE // query set, so if that end index would land in the next chunk (passes ≡ 0 mod 4096), // skip it - the last pass then simply has no duration row (correct, just one row short). const hasClosingStamp = Math.floor(passes / QS_CAP) === Math.floor((passes - 1) / QS_CAP); const measuredPasses = hasClosingStamp ? passes : passes - 1; let k = 0; for (let i = 0; i < n; i += 7) { const tag = plan[i]; if (tag === 0) { const tw = { querySet: qsOf(k), beginningOfPassWriteIndex: qiOf(k) }; if (k === passes - 1 && hasClosingStamp) tw.endOfPassWriteIndex = qiOf(k + 1); const pass = enc.beginComputePass({ timestampWrites: tw }); pass.setPipeline(plan[i + 1]); pass.setBindGroup(0, plan[i + 2]); pass.dispatchWorkgroups(plan[i + 3], plan[i + 4], plan[i + 5]); pass.end(); k++; // WORKAROUND (issue #10): keep the live path's submit boundary. Query sets are device objects, so // the resolve in the final command buffer still reads every timestamp written before it. if (plan[i + 6] === 1) { device.queue.submit([enc.finish()]); enc = device.createCommandEncoder(); } } else if (tag === 1) { enc.copyBufferToBuffer(plan[i + 1], plan[i + 2], plan[i + 3], plan[i + 4], plan[i + 5]); } else if (tag === 2) { enc.clearBuffer(plan[i + 1], plan[i + 2], plan[i + 3]); } } // Resolve every query set into one buffer, then copy to a mappable readback buffer. const resolveBuf = device.createBuffer({ size: stamps * 8, usage: GPUBufferUsage.QUERY_RESOLVE | GPUBufferUsage.COPY_SRC }); const readBuf = device.createBuffer({ size: stamps * 8, usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ }); for (let s = 0, ofs = 0; s < querySets.length; s++) { enc.resolveQuerySet(querySets[s], 0, querySets[s].count, resolveBuf, ofs); ofs += querySets[s].count * 8; } enc.copyBufferToBuffer(resolveBuf, 0, readBuf, 0, stamps * 8); device.queue.submit([enc.finish()]); await readBuf.mapAsync(GPUMapMode.READ); const t = new BigUint64Array(readBuf.getMappedRange().slice(0)); readBuf.unmap(); readBuf.destroy(); resolveBuf.destroy(); for (const qs of querySets) qs.destroy();
// Aggregate pass durations by pipeline label, and keep each pass as a row in plan order with its workgroup // counts (which SHAPE of a kernel is slow: e.g. a GEMM's late small layers launching too few workgroups). const byLabel = new Map(); const dispatches = []; let totalNs = 0; for (let p = 0; p < measuredPasses; p++) { const durNs = Number(t[p + 1] - t[p]); const at = passIdx[p]; const label = plan[at + 1].label || '(unlabeled)'; const valid = durNs >= 0; // guard against wrap/invalid dispatches.push({ label, ms: valid ? +(durNs / 1e6).toFixed(4) : null, wg: [plan[at + 3], plan[at + 4], plan[at + 5]] }); if (!valid) continue; totalNs += durNs; const e = byLabel.get(label) || { ms: 0, count: 0, maxMs: 0 }; e.ms += durNs / 1e6; e.count++; e.maxMs = Math.max(e.maxMs, durNs / 1e6); byLabel.set(label, e); } const kernels = [...byLabel.entries()] .map(([label, e]) => ({ label, ms: +e.ms.toFixed(3), count: e.count, maxMs: +e.maxMs.toFixed(3) })) .sort((a, b) => b.ms - a.ms); return JSON.stringify({ supported: true, passes, ops: n / 7, totalMs: +(totalNs / 1e6).toFixed(3), spanMs: +(Number(t[measuredPasses] - t[0]) / 1e6).toFixed(3), kernels, dispatches }); } }; // Register - but never downgrade. A second copy of this module (another URL, an old cached file) must not // replace a newer one already in use: the library looks up ilgpuWebGPUPlan.submitBatch on every flush. // Bump HELPER_VERSION whenever the api's surface changes. const HELPER_VERSION = 6; // 2: submitBatch (plain-dispatch record batches, ordered uploads); 3: single-pass runs, setSinglePass; 4: scalar arenas, bind-group reuse; 5: submitHeader (pinned heap header); 6: replayTimed per-pass rows (dispatches) api.version = HELPER_VERSION; const existing = globalThis.ilgpuWebGPUPlan; if (!existing || !(existing.version >= HELPER_VERSION)) globalThis.ilgpuWebGPUPlan = api;})();123version https://git-lfs.github.com/spec/v1oid sha256:1be8beb60d00854684479fe9ea18c05a38bc69ae4e27c420a8f1983cf31a74bdsize 2527321123version https://git-lfs.github.com/spec/v1oid sha256:a64190eb11859ea912d172c7a55b9818f611f3931803370e12e892050fe4d05esize 143326123version https://git-lfs.github.com/spec/v1oid sha256:b7aec9f7d6f9775ab611896dc25b00d5b5c404c287662c6aab8fc818ab67fa47size 66679123version https://git-lfs.github.com/spec/v1oid sha256:88ddf5bf3b27852290b29025132065ea42f2de2e0b932aba7c193e7432feafe1size 507644123version https://git-lfs.github.com/spec/v1oid sha256:3befdc691d6e283ce8826d8195b9f4803ade4dc30cd52ffb081698f847e06273size 22402123version https://git-lfs.github.com/spec/v1oid sha256:23152f2d13d38c5cdc65d47ffe8e34059b391b30e8f1c41d8f16ee52693fc88csize 110832123version https://git-lfs.github.com/spec/v1oid sha256:86b3dd578ae8e46a7b89c68f103e9c14a85fb76e223920cff6ac86bedd55a441size 28231123version https://git-lfs.github.com/spec/v1oid sha256:73f479308561f11f6c7727f7e383f46055b8e6cfa2a6452c1b646e12bca490fdsize 49972123version https://git-lfs.github.com/spec/v1oid sha256:0d162efb609ea061afb94d43d914c9afd6bfd06506e32c3e6124f8a9f8a2ef99size 2698123version https://git-lfs.github.com/spec/v1oid sha256:d77f10dc1fb571eac1225471953dd41e4a1ed23c22192ecadf1cbb615dbd1181size 4762123version https://git-lfs.github.com/spec/v1oid sha256:f2fb72ff395eb03c95f070729077a2c0e6f8ad96508a28d2a8232e87cbbf8326size 4167123version https://git-lfs.github.com/spec/v1oid sha256:55d3d29f507b7624fa2fab78056ed21a306e0065804b8ecaf9a5e0771689d8f1size 13206123version https://git-lfs.github.com/spec/v1oid sha256:fbdf1b10cd968650d7c5f54b9794025581adb7ea79cb1adde6650b90005fe526size 22442123version https://git-lfs.github.com/spec/v1oid sha256:aae8809175f256fefd479894e0ff6006b3b3eae0e27aa1692207ee07e31972fesize 8627123version https://git-lfs.github.com/spec/v1oid sha256:16e9e965e149d551f409228ca3d87e4c579b84da31749ab78ee11bc9c4337a4esize 14134123version https://git-lfs.github.com/spec/v1oid sha256:4b086d423f7b99db8bbf606b353d3b5b9358e2bf51c349e055285f8838e117fbsize 8150123version https://git-lfs.github.com/spec/v1oid sha256:aca61a0f270479230d4b1270e796a7cd81d4080de862fda359033fc259dfd49asize 5158123version https://git-lfs.github.com/spec/v1oid sha256:213c66b5c20b7faa0a2ddca7ad0ec0658a8fb6cc30cef90ea5bcd1ed926f1233size 21422123version https://git-lfs.github.com/spec/v1oid sha256:252ab1c7b0b3a7c67d65f641f5ec942f3fcfcc39ca39fb901304e26593445a7asize 5636123version https://git-lfs.github.com/spec/v1oid sha256:bf55064b26da4aa0e88da782f211f47c1a47e21e914ece4f7e19161997205fb2size 1893123version https://git-lfs.github.com/spec/v1oid sha256:82c814518f3204eb130319a138f12785fdc62b3ae31d620fdc411ada16044a45size 2256123version https://git-lfs.github.com/spec/v1oid sha256:d29374961714c1cfae11fe024e370bdcea548c354cdf7d676aacf7b49cd8c35dsize 3531809123version https://git-lfs.github.com/spec/v1oid sha256:807fac9d958b0a88cdd7d0aaa0644944841b9c94cdade3a9ad0c9d95ddb2a221size 13039123version https://git-lfs.github.com/spec/v1oid sha256:947d1c299d5a6ddce9201ca017fbc8df7278245fbfdec97ac0c89b4a898cb7dfsize 32526123version https://git-lfs.github.com/spec/v1oid sha256:284efa3bfea1ca5a0d9882c29cfc49260bcb725c9cb07087bbae12d6dde66c42size 9673123version https://git-lfs.github.com/spec/v1oid sha256:ee0a1ef3aab5032d05465cf821290911f1356db1755545b66073e851fad87de7size 3650706123version https://git-lfs.github.com/spec/v1oid sha256:2aea025ec965d9c5e22a6a07e5dfa14c07859fc0c70ebe97b979a04c560df9fdsize 154241123version https://git-lfs.github.com/spec/v1oid sha256:e1768521fd157f97f7d1185dcdf2aa3805d4d0b1665fb592d542712a885b1cd4size 63141123version https://git-lfs.github.com/spec/v1oid sha256:a61d913d28d0b41aea75e3caa73a029686849c891d613d613c444de56a1f4c7fsize 755830123version https://git-lfs.github.com/spec/v1oid sha256:52d070e3b6adf020b69a787aad9722f2169c242326421866ce27982425a214a4size 4290871123version https://git-lfs.github.com/spec/v1oid sha256:46d9a401fc59b8d498a64fcb0ae1db2dc0d7d051c5fb73578b71a2be2bca1ac8size 1949584123version https://git-lfs.github.com/spec/v1oid sha256:b25b3c09bb6a2bd050dd9864a3936953e02b14e3fc104fa3935a8712e7692a2dsize 164220123version https://git-lfs.github.com/spec/v1oid sha256:28904938ed8d93ca4eae855d612c3da7a2128b769a475a50366d54d28a182a32size 39873123version https://git-lfs.github.com/spec/v1oid sha256:8c58fe5d9d3545cb8e124cd91aea1aee3b667338d681b4a664f05e450bd22a2fsize 1474813123version https://git-lfs.github.com/spec/v1oid sha256:f3e5a2de83d40a7ca0ff0e65fad17afaac10c9bd030041191f12ea36eff170afsize 205286123version https://git-lfs.github.com/spec/v1oid sha256:eb09f3ca08b0c2a4fa8d4ddb6245f8c82f7b455e1f0b9e97b08b5ddb8152c6a1size 1489063123version https://git-lfs.github.com/spec/v1oid sha256:1989f1674f41aaf692b65b5a12d76a48ecbcb8a58463c901e7320360cbe07ca2size 15778123version https://git-lfs.github.com/spec/v1oid sha256:0124f53012c1c6031ac586eddcc77991cb4c1cbadc5a22768079926a61e91040size 76888123version https://git-lfs.github.com/spec/v1oid sha256:215155134ccdd1faa28b1412525141fcd3ade1cf52fc0cc5b71eed246f1a8452size 97044123version https://git-lfs.github.com/spec/v1oid sha256:22e9105f6ae985425b011469c39aa830dd4225a08618079c4ae1745cb6ebfab0size 131112123version https://git-lfs.github.com/spec/v1oid sha256:afa20a3d1e7dffc32d70d37b9cefa173c60b80a58a77a88097b537c645161cb7size 81872123version https://git-lfs.github.com/spec/v1oid sha256:de99f21e32f7cf7c8df05ee0d7d33a4de908e28cff0e6603c3a793dfc7a6f0d6size 54426123version https://git-lfs.github.com/spec/v1oid sha256:6ee479adfb736753da7b8feddc8766198327b9c0424a354a5f70ee928d7ad24bsize 53957.gitattributesAdded+93
404.htmlAdded+182
README.mdAdded+48
SpawnDev.SpawnJS.mztdn6kbtg.lib.module.jsAdded+1542
_content/SpawnDev.Blazor.BootRecovery/SpawnDev.Blazor.BootRecovery.7rjy3ukk5v.lib.module.jsAdded+83
_content/SpawnDev.ILGPU/glWorker.jsAdded+1019
_content/SpawnDev.ILGPU/webgpuDispatchPlan.jsAdded+408
_framework/BouncyCastle.Cryptography.6qnbenkd0k.wasm.gzAdded+3
_framework/Concentus.u3fdhpcxzf.wasm.gzAdded+3
_framework/DnsClient.7sic17ztch.wasm.gzAdded+3
_framework/ILGPU.33e2ya2ho1.wasm.gzAdded+3
_framework/ILGPU.Algorithms.yrlf7k7l3q.wasm.gzAdded+3
_framework/Microsoft.AspNetCore.Components.741isu8jim.wasm.gzAdded+3
_framework/Microsoft.AspNetCore.Components.Web.cmuc7bdjac.wasm.gzAdded+3
_framework/Microsoft.AspNetCore.Components.WebAssembly.iea6k79bon.wasm.gzAdded+3
_framework/Microsoft.Extensions.Configuration.Abstractions.wslsrredsq.wasm.gzAdded+3
_framework/Microsoft.Extensions.Configuration.Json.dmmcgk01r0.wasm.gzAdded+3
_framework/Microsoft.Extensions.Configuration.rgjmp347zf.wasm.gzAdded+3
_framework/Microsoft.Extensions.DependencyInjection.Abstractions.d95iifg76m.wasm.gzAdded+3
_framework/Microsoft.Extensions.DependencyInjection.mvfec3p7kh.wasm.gzAdded+3
_framework/Microsoft.Extensions.Logging.5w9ia7xlgq.wasm.gzAdded+3
_framework/Microsoft.Extensions.Logging.Abstractions.u5liytfkkx.wasm.gzAdded+3
_framework/Microsoft.Extensions.Options.espvvlqak1.wasm.gzAdded+3
_framework/Microsoft.Extensions.Primitives.crxdkm6t9l.wasm.gzAdded+3
_framework/Microsoft.JSInterop.0523xs2ej1.wasm.gzAdded+3
_framework/Microsoft.JSInterop.WebAssembly.5ql0ra5mpq.wasm.gzAdded+3
_framework/Microsoft.Win32.Primitives.l7c9kh4jg2.wasm.gzAdded+3
_framework/Microsoft.Win32.Registry.z3jfhs3ftx.wasm.gzAdded+3
_framework/SIPSorcery.q0z987ykki.wasm.gzAdded+3
_framework/SIPSorceryMedia.Abstractions.evfg4tvmuu.wasm.gzAdded+3
_framework/SpawnDev.BackgroundServices.1yeryblw74.wasm.gzAdded+3
_framework/SpawnDev.Blazor.BootRecovery.wqj5nz7x99.wasm.gzAdded+3
_framework/SpawnDev.Codecs.xofv24znhd.wasm.gzAdded+3
_framework/SpawnDev.EBML.xdne5e0w64.wasm.gzAdded+3
_framework/SpawnDev.Hive.gqpmdb8qak.wasm.gzAdded+3
_framework/SpawnDev.ILGPU.ML.Kernels.aaonp64y5i.wasm.gzAdded+3
_framework/SpawnDev.ILGPU.ML.gl95ev2a6h.wasm.gzAdded+3
_framework/SpawnDev.ILGPU.s6t0mte45z.wasm.gzAdded+3
_framework/SpawnDev.MultiMedia.omfwfbvzp1.wasm.gzAdded+3
_framework/SpawnDev.PatchStreams.fa7qoyfxjz.wasm.gzAdded+3
_framework/SpawnDev.Phonemizer.14wgzuo4bh.wasm.gzAdded+3
_framework/SpawnDev.RTC.81gkkaaqp5.wasm.gzAdded+3
_framework/SpawnDev.SpawnJS.2vggiktbfh.wasm.gzAdded+3
_framework/SpawnDev.SpawnJS.Blazor.fjgrmuuz8e.wasm.gzAdded+3
_framework/SpawnDev.SpawnJS.Cryptography.7qr4csn3ju.wasm.gzAdded+3
_framework/SpawnDev.Swarm.odr4m0zgu9.wasm.gzAdded+3
_framework/SpawnGen.Editor.k93krt25j7.wasm.gzAdded+3
_framework/SpawnGen.Engine.thstywld11.wasm.gzAdded+3
_framework/SpawnGen.Glsl.psh6zi3uqm.wasm.gzAdded+3
_framework/SpawnGen.Hive.vkttvp8xo4.wasm.gzAdded+3