|
| 1 | +// Build script for UTF-8 wasm module |
| 2 | +// Invoked by `npm run build:wasm` |
| 3 | + |
| 4 | +/* eslint-disable no-console */ |
| 5 | + |
| 6 | +import fs from "node:fs"; |
| 7 | +import path from "node:path"; |
| 8 | +import { fileURLToPath } from "node:url"; |
| 9 | +import binaryen from "binaryen"; |
| 10 | +import binaryenMetadata from "binaryen/package.json" with { type: "json" }; |
| 11 | + |
| 12 | + |
| 13 | +const dirname = path.dirname(fileURLToPath(import.meta.url)); |
| 14 | + |
| 15 | +const watPath = path.join(dirname, "utf8.wat"); |
| 16 | +const wasmPath = path.join(dirname, "utf8.wasm"); |
| 17 | +const tsOutputPath = path.join(dirname, "..", "src", "utils", "utf8-wasm-binary.ts"); |
| 18 | + |
| 19 | +console.log(`Compiling utf8.wat -> utf8.wasm with Binaryen v${binaryenMetadata.version}...`); |
| 20 | + |
| 21 | +// Read WAT source |
| 22 | +const watSource = fs.readFileSync(watPath, "utf-8"); |
| 23 | + |
| 24 | +// Parse WAT to module |
| 25 | +const mod = binaryen.parseText(watSource); |
| 26 | + |
| 27 | +// Enable required features |
| 28 | +mod.setFeatures(binaryen.Features.ReferenceTypes | binaryen.Features.GC | binaryen.Features.Strings); |
| 29 | + |
| 30 | +// Optimize (equivalent to wasm-opt -O4) |
| 31 | +mod.optimize(); |
| 32 | + |
| 33 | +// Emit binary |
| 34 | +const wasmBinary = mod.emitBinary(); |
| 35 | + |
| 36 | +// Write wasm file |
| 37 | +fs.writeFileSync(wasmPath, wasmBinary); |
| 38 | + |
| 39 | +console.log("Generating base64 TypeScript module..."); |
| 40 | + |
| 41 | +// Convert to base64 with line breaks (like base64 -b 78) |
| 42 | +const base64 = Buffer.from(wasmBinary).toString("base64"); |
| 43 | +const base64WithLineBreaks = base64.match(/.{1,78}/g)?.join("\n") ?? base64; |
| 44 | + |
| 45 | +// Generate TypeScript file |
| 46 | +const tsContent = `// Auto-generated by wasm/build.mts - DO NOT EDIT MANUALLY |
| 47 | +// Source: wasm/utf8.wat |
| 48 | +
|
| 49 | +export const wasmBinary = \` |
| 50 | +${base64WithLineBreaks} |
| 51 | +\`; |
| 52 | +`; |
| 53 | + |
| 54 | +fs.writeFileSync(tsOutputPath, tsContent); |
| 55 | + |
| 56 | +// Clean up |
| 57 | +mod.dispose(); |
| 58 | + |
| 59 | +console.log("Done! Generated:"); |
| 60 | +console.log(` - wasm/utf8.wasm (${wasmBinary.length} bytes)`); |
| 61 | +console.log(` - src/utils/utf8-wasm-binary.ts (${Buffer.byteLength(tsContent)} bytes)`); |
0 commit comments