Files: d9ae973728a3a94e651aa65697ce88b319c67c44 / wasmAgent.js
1825 bytesRaw
1 | module.exports = class Wasm { |
2 | /** |
3 | * The interface API is the api the exposed to interfaces. All queries about |
4 | * the enviroment and call to the kernel go through this API |
5 | */ |
6 | constructor (code) { |
7 | this._module = WebAssembly.Module(code) |
8 | } |
9 | /** |
10 | * Runs the core VM with a given environment and imports |
11 | */ |
12 | async run (message, kernel, imports) { |
13 | const responses = {} |
14 | /** |
15 | * Builds a import map with an array of given interfaces |
16 | */ |
17 | function buildImports (opts, imports) { |
18 | const importMap = {} |
19 | for (const Import of imports) { |
20 | opts.response = responses[Import.name] = {} |
21 | const newInterface = new Import(opts) |
22 | importMap[Import.name] = newInterface.exports |
23 | } |
24 | return importMap |
25 | } |
26 | |
27 | let instance |
28 | |
29 | const opts = { |
30 | vm: { |
31 | /** |
32 | * adds an aync operation to the operations queue |
33 | */ |
34 | pushOpsQueue: (promise, callbackIndex, intefaceCallback) => { |
35 | this._opsQueue = Promise.all([this._opsQueue, promise]).then(values => { |
36 | const result = intefaceCallback(values.pop()) |
37 | instance.exports.callback.get(callbackIndex)(result) |
38 | }) |
39 | }, |
40 | memory: () => { |
41 | return instance.exports.memory.buffer |
42 | } |
43 | }, |
44 | kernel: kernel, |
45 | message: message |
46 | } |
47 | const initializedImports = buildImports(opts, imports) |
48 | instance = WebAssembly.Instance(this._module, initializedImports) |
49 | |
50 | if (instance.exports.main) { |
51 | instance.exports.main() |
52 | } |
53 | await this.onDone() |
54 | return responses |
55 | } |
56 | |
57 | /** |
58 | * returns a promise that resolves when the wasm instance is done running |
59 | */ |
60 | async onDone () { |
61 | let prevOps |
62 | while (prevOps !== this._opsQueue) { |
63 | prevOps = this._opsQueue |
64 | await this._opsQueue |
65 | } |
66 | } |
67 | } |
68 |
Built with git-ssb-web