import { plugin, $, type BunPlugin } from "bun"; import path from 'path'; import fs from 'fs/promises'; interface WasmLoaderConfig { production?: boolean; portable?: boolean; } interface CompilerWithFlags { cc: string; flags: string[]; } const wasiArchiveURL = 'https://github.com/WebAssembly/wasi-sdk/releases/download/wasi-sdk-25/wasi-sdk-25.0-x86_64-linux.tar.gz'; const rtURL = 'https://github.com/WebAssembly/wasi-sdk/releases/download/wasi-sdk-25/libclang_rt.builtins-wasm32-wasi-25.0.tar.gz'; const getCompiler = async (): Promise => { const wasiDir = path.resolve(import.meta.dir, '..', 'dist', 'wasi'); const cc: CompilerWithFlags = { cc: 'clang', flags: [ '--target=wasm32', '--no-standard-libraries', '-fno-builtin', ], }; await fs.mkdir(wasiDir, { recursive: true }); if (!await Bun.file(path.resolve(wasiDir, 'VERSION')).exists()) { const response = await fetch(wasiArchiveURL); if (!response.ok) { return cc; } const bytes = await response.bytes(); await $`tar -xzv -C ${wasiDir} --strip-components=1 < ${bytes}`; const rtResponse = await fetch(rtURL); if (!rtResponse.ok) { return cc; } const rtBytes = await rtResponse.bytes(); await $`tar -xzv -C ${wasiDir} --strip-components=1 < ${rtBytes}`; } cc.cc = `${path.resolve(wasiDir, 'bin', 'clang')}`; cc.flags = [ '--target=wasm32-wasi', `--sysroot=${path.resolve(wasiDir, 'share', 'wasi-sysroot')}`, ]; return cc; } const wasmPlugin = ({ production, portable }: WasmLoaderConfig = {}): BunPlugin => { const p: BunPlugin = { name: "WASM loader", async setup(build) { build.onLoad({ filter: /\.(c(pp)?|wasm)$/ }, async (args) => { let wasmPath = path.resolve(import.meta.dir, '..', 'dist', 'tmp.wasm'); let jsContent: string = ` async function instantiate(url) { const memory = new WebAssembly.Memory({ initial: 32, }); let data = new DataView(memory.buffer); const decoder = new TextDecoder(); const getString = (ptr) => { const view = new Uint8Array(memory.buffer, ptr); const start = ptr; const end = ptr + view.indexOf(0); return decoder.decode(memory.buffer.slice(start, end)); }; let buf = ''; Math.fmod = (x, y) => x % y; const { instance } = await WebAssembly.instantiateStreaming(fetch(url), { env: { memory, log(format, argsPtr) { let bufLen = buf.length; let count = 0; format = getString(format); let isFormat = false; let w = 4; const align = (a) => argsPtr += (argsPtr % a); for (const c of format) { if (!isFormat) { if (c === '%') { isFormat = true; } else if (c === '\\n') { console.log('[wasm]', buf); count += buf.length - bufLen + 1; bufLen = 0; buf = ''; } else { buf += c; } } else switch(c) { case '%': buf += '%'; isFormat = false; break; case 's': align(4); buf += getString(data.getInt32(argsPtr, true)); argsPtr += 4; isFormat = false; break; case 'd': align(w); buf += data[w === 4 ? 'getInt32': 'getBigInt64'](argsPtr, true); argsPtr += w; isFormat = false; break; case 'x': align(w); buf += data[w === 4 ? 'getUint32': 'getBigUint64'](argsPtr, true).toString(16); argsPtr += w; isFormat = false; break; case 'o': align(w); buf += data[w === 4 ? 'getUint32': 'getBigUint64'](argsPtr, true).toString(8); argsPtr += w; isFormat = false; break; case 'u': align(w); buf += data[w === 4 ? 'getUint32': 'getBigUint64'](argsPtr, true); argsPtr += w; isFormat = false; break; case 'f': align(8); buf += data.getFloat64(argsPtr, true); argsPtr += 8; isFormat = false; break; case 'c': align(4); buf += String.fromCharCode(data.getInt32(argsPtr, true)); argsPtr += 4; isFormat = false; break; case 'l': w = 8; break; default: buf += '%' + c; isFormat = false; break; } } count += buf.length - bufLen; return count; }, grow(blocks) { if (blocks > 0) { memory.grow(blocks); data = new DataView(memory.buffer); } }, }, Math: Math, wasi_snapshot_preview1: { random_get: (ptr, length) => { for (let i=0; i < length; i++) { data.setUint8(ptr + i, Math.random() * 256); } }, environ_sizes_get(){ return 0; }, environ_get() { return 0; }, } }); return { ...instance.exports, memory, get data() { return data; }, }; } const module = await instantiate(new URL($WASM$)); if (typeof module.__srand === 'function') module.__srand(BigInt(Date.now())); export default module; `; if (args.path.endsWith('.wasm')) { wasmPath = args.path; } else { const buildAssets = path.resolve(import.meta.dir, 'assets'); const include = `${buildAssets}/include`; const glob = new Bun.Glob(`${buildAssets}/lib/**/*.c`); const stdlib = await Array.fromAsync(glob.scan()); const objPath = wasmPath + '.o'; const cc = await getCompiler(); const features = [ 'bulk-memory', 'extended-const', 'relaxed-simd', 'simd128', 'tail-call', 'sign-ext', 'nontrapping-fptoint', 'reference-types', 'multivalue', ].map(f => `-m${f}`); const flags = [ ...cc.flags, production ? '-O3' : '-O0', '-flto', '-fno-exceptions', '-Wall', '-Wextra', '-Wpedantic', '-Werror', '-Wshadow', ...features, ]; const std = args.path.endsWith('.cpp') ? '-std=gnu++23' : '-std=gnu23'; const compileResult = await $`${cc.cc} -c ${flags} ${std} -I ${include} -o ${objPath} ${args.path}`; if (compileResult.exitCode !== 0) { throw new Error('Compile failed, check output'); } const linkFlags = [ '--lto-O3', '--no-entry', '--import-memory', ].map(f => `-Wl,${f}`); const linkResult = await $`${cc.cc} ${flags} -std=gnu23 -I ${include} ${linkFlags} -lstdc++ -nostartfiles -o ${wasmPath} ${objPath} ${stdlib}`; if (linkResult.exitCode !== 0) { throw new Error('Link failed, check output'); } } const wasmContent = await Bun.file(wasmPath).arrayBuffer(); const wasmBuffer = Buffer.from(wasmContent).toString('base64'); const wasmURL = `data:application/wasm;base64,${wasmBuffer}`; return { loader: 'js', contents: jsContent.replace(/new URL\([^)]*\)/, `new URL(${JSON.stringify(wasmURL)})`), }; }); } }; plugin(p); return p; }; export default wasmPlugin;