-
Notifications
You must be signed in to change notification settings - Fork 369
Expand file tree
/
Copy pathwabtHandler.ts
More file actions
99 lines (87 loc) · 2.65 KB
/
Copy pathwabtHandler.ts
File metadata and controls
99 lines (87 loc) · 2.65 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
import type { FileData, FileFormat, FormatHandler } from "../FormatHandler.ts";
import { Category } from "../CommonFormats.ts";
import wabt from "wabt";
// WabtModule is not exported
type WabtModule = Awaited<ReturnType<typeof wabt>>;
export default class wabtHandler implements FormatHandler {
public name: string = "wabt";
public supportedFormats?: FileFormat[];
public ready: boolean = false;
private wabtModule?: WabtModule;
wasm2wat(bytes: Uint8Array): Uint8Array {
const wasmModule = this.wabtModule!.readWasm(bytes, {});
const str = wasmModule.toText({});
const encoder = new TextEncoder();
const encoded = encoder.encode(str);
wasmModule.destroy();
return encoded;
}
wat2wasm(filename: string, bytes: Uint8Array): Uint8Array {
const wasmModule = this.wabtModule!.parseWat(filename, bytes);
const outBytes = wasmModule.toBinary({});
const buffer = outBytes.buffer;
wasmModule.destroy();
return buffer;
}
async init() {
this.supportedFormats = [
{
name: "WebAssembly Binary (Wasm)",
format: "wasm",
extension: "wasm",
mime: "application/wasm",
from: true,
to: true,
internal: "wasm",
category: Category.CODE,
lossless: true,
},
{
name: "WebAssembly Text Format (WAT)",
format: "wat",
extension: "wat",
// https://github.com/WebAssembly/spec/issues/1347
mime: "text/plain",
from: true,
to: true,
internal: "wat",
category: Category.CODE,
lossless: true,
},
];
this.wabtModule = await wabt();
this.ready = true;
}
async doConvert(
inputFiles: FileData[],
inputFormat: FileFormat,
outputFormat: FileFormat,
): Promise<FileData[]> {
const outputFiles: FileData[] = [];
if (inputFormat.internal == "wasm" && outputFormat.internal == "wat") {
for (const file of inputFiles) {
outputFiles.push({
name:
file.name.split(".").slice(0, -1).join(".") +
`.${outputFormat.extension}`,
bytes: this.wasm2wat(file.bytes),
});
}
return outputFiles;
}
if (inputFormat.internal == "wat" && outputFormat.internal == "wasm") {
for (const file of inputFiles) {
outputFiles.push({
name:
file.name.split(".").slice(0, -1).join(".") +
`.${outputFormat.extension}`,
bytes: this.wat2wasm(file.name, file.bytes),
});
}
return outputFiles;
}
throw new TypeError(
`wabtHandler does not support route: ${inputFormat.internal} -> ${outputFormat.internal}`,
);
}
}