@ruby/wasm-wasi 2.4.1 → 2.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +69 -3
- package/dist/browser.script.umd.js +143 -110
- package/dist/browser.umd.js +1339 -1306
- package/dist/cjs/browser.d.ts +1 -1
- package/dist/cjs/browser.js +4 -3
- package/dist/cjs/index.d.ts +1 -195
- package/dist/cjs/index.js +2 -641
- package/dist/cjs/node.d.ts +1 -1
- package/dist/cjs/node.js +2 -2
- package/dist/cjs/vm.d.ts +216 -0
- package/dist/cjs/vm.js +677 -0
- package/dist/esm/browser.d.ts +1 -1
- package/dist/esm/browser.js +2 -1
- package/dist/esm/index.d.ts +1 -195
- package/dist/esm/index.js +1 -636
- package/dist/esm/node.d.ts +1 -1
- package/dist/esm/node.js +1 -1
- package/dist/esm/vm.d.ts +216 -0
- package/dist/esm/vm.js +669 -0
- package/dist/index.umd.js +1317 -1284
- package/package.json +7 -9
package/dist/esm/vm.js
ADDED
|
@@ -0,0 +1,669 @@
|
|
|
1
|
+
import * as RbAbi from "./bindgen/rb-abi-guest.js";
|
|
2
|
+
import { addRbJsAbiHostToImports, } from "./bindgen/rb-js-abi-host.js";
|
|
3
|
+
/**
|
|
4
|
+
* A Ruby VM instance
|
|
5
|
+
*
|
|
6
|
+
* @example
|
|
7
|
+
*
|
|
8
|
+
* const wasi = new WASI();
|
|
9
|
+
* const vm = new RubyVM();
|
|
10
|
+
* const imports = {
|
|
11
|
+
* wasi_snapshot_preview1: wasi.wasiImport,
|
|
12
|
+
* };
|
|
13
|
+
*
|
|
14
|
+
* vm.addToImports(imports);
|
|
15
|
+
*
|
|
16
|
+
* const instance = await WebAssembly.instantiate(rubyModule, imports);
|
|
17
|
+
* await vm.setInstance(instance);
|
|
18
|
+
* wasi.initialize(instance);
|
|
19
|
+
* vm.initialize();
|
|
20
|
+
*
|
|
21
|
+
*/
|
|
22
|
+
export class RubyVM {
|
|
23
|
+
constructor() {
|
|
24
|
+
this.instance = null;
|
|
25
|
+
this.interfaceState = {
|
|
26
|
+
hasJSFrameAfterRbFrame: false,
|
|
27
|
+
};
|
|
28
|
+
// Wrap exported functions from Ruby VM to prohibit nested VM operation
|
|
29
|
+
// if the call stack has sandwitched JS frames like JS -> Ruby -> JS -> Ruby.
|
|
30
|
+
const proxyExports = (exports) => {
|
|
31
|
+
const excludedMethods = [
|
|
32
|
+
"addToImports",
|
|
33
|
+
"instantiate",
|
|
34
|
+
"rbSetShouldProhibitRewind",
|
|
35
|
+
"rbGcDisable",
|
|
36
|
+
"rbGcEnable",
|
|
37
|
+
];
|
|
38
|
+
const excluded = ["constructor"].concat(excludedMethods);
|
|
39
|
+
// wrap all methods in RbAbi.RbAbiGuest class
|
|
40
|
+
for (const key of Object.getOwnPropertyNames(RbAbi.RbAbiGuest.prototype)) {
|
|
41
|
+
if (excluded.includes(key)) {
|
|
42
|
+
continue;
|
|
43
|
+
}
|
|
44
|
+
const value = exports[key];
|
|
45
|
+
if (typeof value === "function") {
|
|
46
|
+
exports[key] = (...args) => {
|
|
47
|
+
const isNestedVMCall = this.interfaceState.hasJSFrameAfterRbFrame;
|
|
48
|
+
if (isNestedVMCall) {
|
|
49
|
+
const oldShouldProhibitRewind = this.guest.rbSetShouldProhibitRewind(true);
|
|
50
|
+
const oldIsDisabledGc = this.guest.rbGcDisable();
|
|
51
|
+
const result = Reflect.apply(value, exports, args);
|
|
52
|
+
this.guest.rbSetShouldProhibitRewind(oldShouldProhibitRewind);
|
|
53
|
+
if (!oldIsDisabledGc) {
|
|
54
|
+
this.guest.rbGcEnable();
|
|
55
|
+
}
|
|
56
|
+
return result;
|
|
57
|
+
}
|
|
58
|
+
else {
|
|
59
|
+
return Reflect.apply(value, exports, args);
|
|
60
|
+
}
|
|
61
|
+
};
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
return exports;
|
|
65
|
+
};
|
|
66
|
+
this.guest = proxyExports(new RbAbi.RbAbiGuest());
|
|
67
|
+
this.transport = new JsValueTransport();
|
|
68
|
+
this.exceptionFormatter = new RbExceptionFormatter();
|
|
69
|
+
}
|
|
70
|
+
/**
|
|
71
|
+
* Initialize the Ruby VM with the given command line arguments
|
|
72
|
+
* @param args The command line arguments to pass to Ruby. Must be
|
|
73
|
+
* an array of strings starting with the Ruby program name.
|
|
74
|
+
*/
|
|
75
|
+
initialize(args = ["ruby.wasm", "-EUTF-8", "-e_=0"]) {
|
|
76
|
+
const c_args = args.map((arg) => arg + "\0");
|
|
77
|
+
this.guest.rubyInit();
|
|
78
|
+
this.guest.rubySysinit(c_args);
|
|
79
|
+
this.guest.rubyOptions(c_args);
|
|
80
|
+
this.eval(`require "/bundle/setup"`);
|
|
81
|
+
}
|
|
82
|
+
/**
|
|
83
|
+
* Set a given instance to interact JavaScript and Ruby's
|
|
84
|
+
* WebAssembly instance. This method must be called before calling
|
|
85
|
+
* Ruby API.
|
|
86
|
+
*
|
|
87
|
+
* @param instance The WebAssembly instance to interact with. Must
|
|
88
|
+
* be instantiated from a Ruby built with JS extension, and built
|
|
89
|
+
* with Reactor ABI instead of command line.
|
|
90
|
+
*/
|
|
91
|
+
async setInstance(instance) {
|
|
92
|
+
this.instance = instance;
|
|
93
|
+
await this.guest.instantiate(instance);
|
|
94
|
+
}
|
|
95
|
+
/**
|
|
96
|
+
* Add intrinsic import entries, which is necessary to interact JavaScript
|
|
97
|
+
* and Ruby's WebAssembly instance.
|
|
98
|
+
* @param imports The import object to add to the WebAssembly instance
|
|
99
|
+
*/
|
|
100
|
+
addToImports(imports) {
|
|
101
|
+
this.guest.addToImports(imports);
|
|
102
|
+
function wrapTry(f) {
|
|
103
|
+
return (...args) => {
|
|
104
|
+
try {
|
|
105
|
+
return { tag: "success", val: f(...args) };
|
|
106
|
+
}
|
|
107
|
+
catch (e) {
|
|
108
|
+
if (e instanceof RbFatalError) {
|
|
109
|
+
// RbFatalError should not be caught by Ruby because it Ruby VM
|
|
110
|
+
// can be already in an inconsistent state.
|
|
111
|
+
throw e;
|
|
112
|
+
}
|
|
113
|
+
return { tag: "failure", val: e };
|
|
114
|
+
}
|
|
115
|
+
};
|
|
116
|
+
}
|
|
117
|
+
imports["rb-js-abi-host"] = {
|
|
118
|
+
rb_wasm_throw_prohibit_rewind_exception: (messagePtr, messageLen) => {
|
|
119
|
+
const memory = this.instance.exports.memory;
|
|
120
|
+
const str = new TextDecoder().decode(new Uint8Array(memory.buffer, messagePtr, messageLen));
|
|
121
|
+
throw new RbFatalError("Ruby APIs that may rewind the VM stack are prohibited under nested VM operation " +
|
|
122
|
+
`(${str})\n` +
|
|
123
|
+
"Nested VM operation means that the call stack has sandwitched JS frames like JS -> Ruby -> JS -> Ruby " +
|
|
124
|
+
"caused by something like `window.rubyVM.eval(\"JS.global[:rubyVM].eval('Fiber.yield')\")`\n" +
|
|
125
|
+
"\n" +
|
|
126
|
+
"Please check your call stack and make sure that you are **not** doing any of the following inside the nested Ruby frame:\n" +
|
|
127
|
+
" 1. Switching fibers (e.g. Fiber#resume, Fiber.yield, and Fiber#transfer)\n" +
|
|
128
|
+
" Note that `evalAsync` JS API switches fibers internally\n" +
|
|
129
|
+
" 2. Raising uncaught exceptions\n" +
|
|
130
|
+
" Please catch all exceptions inside the nested operation\n" +
|
|
131
|
+
" 3. Calling Continuation APIs\n");
|
|
132
|
+
},
|
|
133
|
+
};
|
|
134
|
+
// NOTE: The GC may collect objects that are still referenced by Wasm
|
|
135
|
+
// locals because Asyncify cannot scan the Wasm stack above the JS frame.
|
|
136
|
+
// So we need to keep track whether the JS frame is sandwitched by Ruby
|
|
137
|
+
// frames or not, and prohibit nested VM operation if it is.
|
|
138
|
+
const proxyImports = (imports) => {
|
|
139
|
+
for (const [key, value] of Object.entries(imports)) {
|
|
140
|
+
if (typeof value === "function") {
|
|
141
|
+
imports[key] = (...args) => {
|
|
142
|
+
const oldValue = this.interfaceState.hasJSFrameAfterRbFrame;
|
|
143
|
+
this.interfaceState.hasJSFrameAfterRbFrame = true;
|
|
144
|
+
const result = Reflect.apply(value, imports, args);
|
|
145
|
+
this.interfaceState.hasJSFrameAfterRbFrame = oldValue;
|
|
146
|
+
return result;
|
|
147
|
+
};
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
return imports;
|
|
151
|
+
};
|
|
152
|
+
addRbJsAbiHostToImports(imports, proxyImports({
|
|
153
|
+
evalJs: wrapTry((code) => {
|
|
154
|
+
return Function(code)();
|
|
155
|
+
}),
|
|
156
|
+
isJs: (value) => {
|
|
157
|
+
// Just for compatibility with the old JS API
|
|
158
|
+
return true;
|
|
159
|
+
},
|
|
160
|
+
globalThis: () => {
|
|
161
|
+
if (typeof globalThis !== "undefined") {
|
|
162
|
+
return globalThis;
|
|
163
|
+
}
|
|
164
|
+
else if (typeof global !== "undefined") {
|
|
165
|
+
return global;
|
|
166
|
+
}
|
|
167
|
+
else if (typeof window !== "undefined") {
|
|
168
|
+
return window;
|
|
169
|
+
}
|
|
170
|
+
throw new Error("unable to locate global object");
|
|
171
|
+
},
|
|
172
|
+
intToJsNumber: (value) => {
|
|
173
|
+
return value;
|
|
174
|
+
},
|
|
175
|
+
floatToJsNumber: (value) => {
|
|
176
|
+
return value;
|
|
177
|
+
},
|
|
178
|
+
stringToJsString: (value) => {
|
|
179
|
+
return value;
|
|
180
|
+
},
|
|
181
|
+
boolToJsBool: (value) => {
|
|
182
|
+
return value;
|
|
183
|
+
},
|
|
184
|
+
procToJsFunction: (rawRbAbiValue) => {
|
|
185
|
+
const rbValue = this.rbValueOfPointer(rawRbAbiValue);
|
|
186
|
+
return (...args) => {
|
|
187
|
+
rbValue.call("call", ...args.map((arg) => this.wrap(arg)));
|
|
188
|
+
};
|
|
189
|
+
},
|
|
190
|
+
rbObjectToJsRbValue: (rawRbAbiValue) => {
|
|
191
|
+
return this.rbValueOfPointer(rawRbAbiValue);
|
|
192
|
+
},
|
|
193
|
+
jsValueToString: (value) => {
|
|
194
|
+
// According to the [spec](https://tc39.es/ecma262/multipage/text-processing.html#sec-string-constructor-string-value)
|
|
195
|
+
// `String(value)` always returns a string.
|
|
196
|
+
return String(value);
|
|
197
|
+
},
|
|
198
|
+
jsValueToInteger(value) {
|
|
199
|
+
if (typeof value === "number") {
|
|
200
|
+
return { tag: "f64", val: value };
|
|
201
|
+
}
|
|
202
|
+
else if (typeof value === "bigint") {
|
|
203
|
+
return { tag: "bignum", val: BigInt(value).toString(10) + "\0" };
|
|
204
|
+
}
|
|
205
|
+
else if (typeof value === "string") {
|
|
206
|
+
return { tag: "bignum", val: value + "\0" };
|
|
207
|
+
}
|
|
208
|
+
else if (typeof value === "undefined") {
|
|
209
|
+
return { tag: "f64", val: 0 };
|
|
210
|
+
}
|
|
211
|
+
else {
|
|
212
|
+
return { tag: "f64", val: Number(value) };
|
|
213
|
+
}
|
|
214
|
+
},
|
|
215
|
+
exportJsValueToHost: (value) => {
|
|
216
|
+
// See `JsValueExporter` for the reason why we need to do this
|
|
217
|
+
this.transport.takeJsValue(value);
|
|
218
|
+
},
|
|
219
|
+
importJsValueFromHost: () => {
|
|
220
|
+
return this.transport.consumeJsValue();
|
|
221
|
+
},
|
|
222
|
+
instanceOf: (value, klass) => {
|
|
223
|
+
if (typeof klass === "function") {
|
|
224
|
+
return value instanceof klass;
|
|
225
|
+
}
|
|
226
|
+
else {
|
|
227
|
+
return false;
|
|
228
|
+
}
|
|
229
|
+
},
|
|
230
|
+
jsValueTypeof(value) {
|
|
231
|
+
return typeof value;
|
|
232
|
+
},
|
|
233
|
+
jsValueEqual(lhs, rhs) {
|
|
234
|
+
return lhs == rhs;
|
|
235
|
+
},
|
|
236
|
+
jsValueStrictlyEqual(lhs, rhs) {
|
|
237
|
+
return lhs === rhs;
|
|
238
|
+
},
|
|
239
|
+
reflectApply: wrapTry((target, thisArgument, args) => {
|
|
240
|
+
return Reflect.apply(target, thisArgument, args);
|
|
241
|
+
}),
|
|
242
|
+
reflectConstruct: function (target, args) {
|
|
243
|
+
throw new Error("Function not implemented.");
|
|
244
|
+
},
|
|
245
|
+
reflectDeleteProperty: function (target, propertyKey) {
|
|
246
|
+
throw new Error("Function not implemented.");
|
|
247
|
+
},
|
|
248
|
+
reflectGet: wrapTry((target, propertyKey) => {
|
|
249
|
+
return target[propertyKey];
|
|
250
|
+
}),
|
|
251
|
+
reflectGetOwnPropertyDescriptor: function (target, propertyKey) {
|
|
252
|
+
throw new Error("Function not implemented.");
|
|
253
|
+
},
|
|
254
|
+
reflectGetPrototypeOf: function (target) {
|
|
255
|
+
throw new Error("Function not implemented.");
|
|
256
|
+
},
|
|
257
|
+
reflectHas: function (target, propertyKey) {
|
|
258
|
+
throw new Error("Function not implemented.");
|
|
259
|
+
},
|
|
260
|
+
reflectIsExtensible: function (target) {
|
|
261
|
+
throw new Error("Function not implemented.");
|
|
262
|
+
},
|
|
263
|
+
reflectOwnKeys: function (target) {
|
|
264
|
+
throw new Error("Function not implemented.");
|
|
265
|
+
},
|
|
266
|
+
reflectPreventExtensions: function (target) {
|
|
267
|
+
throw new Error("Function not implemented.");
|
|
268
|
+
},
|
|
269
|
+
reflectSet: wrapTry((target, propertyKey, value) => {
|
|
270
|
+
return Reflect.set(target, propertyKey, value);
|
|
271
|
+
}),
|
|
272
|
+
reflectSetPrototypeOf: function (target, prototype) {
|
|
273
|
+
throw new Error("Function not implemented.");
|
|
274
|
+
},
|
|
275
|
+
}), (name) => {
|
|
276
|
+
return this.instance.exports[name];
|
|
277
|
+
});
|
|
278
|
+
}
|
|
279
|
+
/**
|
|
280
|
+
* Print the Ruby version to stdout
|
|
281
|
+
*/
|
|
282
|
+
printVersion() {
|
|
283
|
+
this.guest.rubyShowVersion();
|
|
284
|
+
}
|
|
285
|
+
/**
|
|
286
|
+
* Runs a string of Ruby code from JavaScript
|
|
287
|
+
* @param code The Ruby code to run
|
|
288
|
+
* @returns the result of the last expression
|
|
289
|
+
*
|
|
290
|
+
* @example
|
|
291
|
+
* vm.eval("puts 'hello world'");
|
|
292
|
+
* const result = vm.eval("1 + 2");
|
|
293
|
+
* console.log(result.toString()); // 3
|
|
294
|
+
*
|
|
295
|
+
*/
|
|
296
|
+
eval(code) {
|
|
297
|
+
return evalRbCode(this, this.privateObject(), code);
|
|
298
|
+
}
|
|
299
|
+
/**
|
|
300
|
+
* Runs a string of Ruby code with top-level `JS::Object#await`
|
|
301
|
+
* Returns a promise that resolves when execution completes.
|
|
302
|
+
* @param code The Ruby code to run
|
|
303
|
+
* @returns a promise that resolves to the result of the last expression
|
|
304
|
+
*
|
|
305
|
+
* @example
|
|
306
|
+
* const text = await vm.evalAsync(`
|
|
307
|
+
* require 'js'
|
|
308
|
+
* response = JS.global.fetch('https://example.com').await
|
|
309
|
+
* response.text.await
|
|
310
|
+
* `);
|
|
311
|
+
* console.log(text.toString()); // <html>...</html>
|
|
312
|
+
*/
|
|
313
|
+
evalAsync(code) {
|
|
314
|
+
const JS = this.eval("require 'js'; JS");
|
|
315
|
+
return newRbPromise(this, this.privateObject(), (future) => {
|
|
316
|
+
JS.call("__eval_async_rb", this.wrap(code), future);
|
|
317
|
+
});
|
|
318
|
+
}
|
|
319
|
+
/**
|
|
320
|
+
* Wrap a JavaScript value into a Ruby JS::Object
|
|
321
|
+
* @param value The value to convert to RbValue
|
|
322
|
+
* @returns the RbValue object representing the given JS value
|
|
323
|
+
*
|
|
324
|
+
* @example
|
|
325
|
+
* const hash = vm.eval(`Hash.new`)
|
|
326
|
+
* hash.call("store", vm.eval(`"key1"`), vm.wrap(new Object()));
|
|
327
|
+
*/
|
|
328
|
+
wrap(value) {
|
|
329
|
+
return this.transport.importJsValue(value, this);
|
|
330
|
+
}
|
|
331
|
+
/** @private */
|
|
332
|
+
privateObject() {
|
|
333
|
+
return {
|
|
334
|
+
transport: this.transport,
|
|
335
|
+
exceptionFormatter: this.exceptionFormatter,
|
|
336
|
+
};
|
|
337
|
+
}
|
|
338
|
+
/** @private */
|
|
339
|
+
rbValueOfPointer(pointer) {
|
|
340
|
+
const abiValue = new RbAbi.RbAbiValue(pointer, this.guest);
|
|
341
|
+
return new RbValue(abiValue, this, this.privateObject());
|
|
342
|
+
}
|
|
343
|
+
}
|
|
344
|
+
/**
|
|
345
|
+
* Export a JS value held by the Ruby VM to the JS environment.
|
|
346
|
+
* This is implemented in a dirty way since wit cannot reference resources
|
|
347
|
+
* defined in other interfaces.
|
|
348
|
+
* In our case, we can't express `function(v: rb-abi-value) -> js-abi-value`
|
|
349
|
+
* because `rb-js-abi-host.wit`, that defines `js-abi-value`, is implemented
|
|
350
|
+
* by embedder side (JS) but `rb-abi-guest.wit`, that defines `rb-abi-value`
|
|
351
|
+
* is implemented by guest side (Wasm).
|
|
352
|
+
*
|
|
353
|
+
* This class is a helper to export by:
|
|
354
|
+
* 1. Call `function __export_to_js(v: rb-abi-value)` defined in guest from embedder side.
|
|
355
|
+
* 2. Call `function takeJsValue(v: js-abi-value)` defined in embedder from guest side with
|
|
356
|
+
* underlying JS value of given `rb-abi-value`.
|
|
357
|
+
* 3. Then `takeJsValue` implementation escapes the given JS value to the `_takenJsValues`
|
|
358
|
+
* stored in embedder side.
|
|
359
|
+
* 4. Finally, embedder side can take `_takenJsValues`.
|
|
360
|
+
*
|
|
361
|
+
* Note that `exportJsValue` is not reentrant.
|
|
362
|
+
*
|
|
363
|
+
* @private
|
|
364
|
+
*/
|
|
365
|
+
class JsValueTransport {
|
|
366
|
+
constructor() {
|
|
367
|
+
this._takenJsValue = null;
|
|
368
|
+
}
|
|
369
|
+
takeJsValue(value) {
|
|
370
|
+
this._takenJsValue = value;
|
|
371
|
+
}
|
|
372
|
+
consumeJsValue() {
|
|
373
|
+
return this._takenJsValue;
|
|
374
|
+
}
|
|
375
|
+
exportJsValue(value) {
|
|
376
|
+
value.call("__export_to_js");
|
|
377
|
+
return this._takenJsValue;
|
|
378
|
+
}
|
|
379
|
+
importJsValue(value, vm) {
|
|
380
|
+
this._takenJsValue = value;
|
|
381
|
+
return vm.eval('require "js"; JS::Object').call("__import_from_js");
|
|
382
|
+
}
|
|
383
|
+
}
|
|
384
|
+
/**
|
|
385
|
+
* A RbValue is an object that represents a value in Ruby
|
|
386
|
+
*/
|
|
387
|
+
export class RbValue {
|
|
388
|
+
/**
|
|
389
|
+
* @hideconstructor
|
|
390
|
+
*/
|
|
391
|
+
constructor(inner, vm, privateObject) {
|
|
392
|
+
this.inner = inner;
|
|
393
|
+
this.vm = vm;
|
|
394
|
+
this.privateObject = privateObject;
|
|
395
|
+
}
|
|
396
|
+
/**
|
|
397
|
+
* Call a given method with given arguments
|
|
398
|
+
*
|
|
399
|
+
* @param callee name of the Ruby method to call
|
|
400
|
+
* @param args arguments to pass to the method. Must be an array of RbValue
|
|
401
|
+
* @returns The result of the method call as a new RbValue.
|
|
402
|
+
*
|
|
403
|
+
* @example
|
|
404
|
+
* const ary = vm.eval("[1, 2, 3]");
|
|
405
|
+
* ary.call("push", 4);
|
|
406
|
+
* console.log(ary.call("sample").toString());
|
|
407
|
+
*/
|
|
408
|
+
call(callee, ...args) {
|
|
409
|
+
const innerArgs = args.map((arg) => arg.inner);
|
|
410
|
+
return new RbValue(callRbMethod(this.vm, this.privateObject, this.inner, callee, innerArgs), this.vm, this.privateObject);
|
|
411
|
+
}
|
|
412
|
+
/**
|
|
413
|
+
* Call a given method that may call `JS::Object#await` with given arguments
|
|
414
|
+
*
|
|
415
|
+
* @param callee name of the Ruby method to call
|
|
416
|
+
* @param args arguments to pass to the method. Must be an array of RbValue
|
|
417
|
+
* @returns A Promise that resolves to the result of the method call as a new RbValue.
|
|
418
|
+
*
|
|
419
|
+
* @example
|
|
420
|
+
* const client = vm.eval(`
|
|
421
|
+
* require 'js'
|
|
422
|
+
* class HttpClient
|
|
423
|
+
* def get(url)
|
|
424
|
+
* JS.global.fetch(url).await
|
|
425
|
+
* end
|
|
426
|
+
* end
|
|
427
|
+
* HttpClient.new
|
|
428
|
+
* `);
|
|
429
|
+
* const response = await client.callAsync("get", vm.eval(`"https://example.com"`));
|
|
430
|
+
*/
|
|
431
|
+
callAsync(callee, ...args) {
|
|
432
|
+
const JS = this.vm.eval("require 'js'; JS");
|
|
433
|
+
return newRbPromise(this.vm, this.privateObject, (future) => {
|
|
434
|
+
JS.call("__call_async_method", this, this.vm.wrap(callee), future, ...args);
|
|
435
|
+
});
|
|
436
|
+
}
|
|
437
|
+
/**
|
|
438
|
+
* @see {@link https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Global_Objects/Symbol/toPrimitive}
|
|
439
|
+
* @param hint Preferred type of the result primitive value. `"number"`, `"string"`, or `"default"`.
|
|
440
|
+
*/
|
|
441
|
+
[Symbol.toPrimitive](hint) {
|
|
442
|
+
if (hint === "string" || hint === "default") {
|
|
443
|
+
return this.toString();
|
|
444
|
+
}
|
|
445
|
+
else if (hint === "number") {
|
|
446
|
+
return null;
|
|
447
|
+
}
|
|
448
|
+
return null;
|
|
449
|
+
}
|
|
450
|
+
/**
|
|
451
|
+
* Returns a string representation of the value by calling `to_s`
|
|
452
|
+
*/
|
|
453
|
+
toString() {
|
|
454
|
+
const rbString = callRbMethod(this.vm, this.privateObject, this.inner, "to_s", []);
|
|
455
|
+
return this.vm.guest.rstringPtr(rbString);
|
|
456
|
+
}
|
|
457
|
+
/**
|
|
458
|
+
* Returns a JavaScript object representation of the value
|
|
459
|
+
* by calling `to_js`.
|
|
460
|
+
*
|
|
461
|
+
* Returns null if the value is not convertible to a JavaScript object.
|
|
462
|
+
*/
|
|
463
|
+
toJS() {
|
|
464
|
+
const JS = this.vm.eval("JS");
|
|
465
|
+
const jsValue = JS.call("try_convert", this);
|
|
466
|
+
if (jsValue.call("nil?").toString() === "true") {
|
|
467
|
+
return null;
|
|
468
|
+
}
|
|
469
|
+
return this.privateObject.transport.exportJsValue(jsValue);
|
|
470
|
+
}
|
|
471
|
+
}
|
|
472
|
+
var ruby_tag_type;
|
|
473
|
+
(function (ruby_tag_type) {
|
|
474
|
+
ruby_tag_type[ruby_tag_type["None"] = 0] = "None";
|
|
475
|
+
ruby_tag_type[ruby_tag_type["Return"] = 1] = "Return";
|
|
476
|
+
ruby_tag_type[ruby_tag_type["Break"] = 2] = "Break";
|
|
477
|
+
ruby_tag_type[ruby_tag_type["Next"] = 3] = "Next";
|
|
478
|
+
ruby_tag_type[ruby_tag_type["Retry"] = 4] = "Retry";
|
|
479
|
+
ruby_tag_type[ruby_tag_type["Redo"] = 5] = "Redo";
|
|
480
|
+
ruby_tag_type[ruby_tag_type["Raise"] = 6] = "Raise";
|
|
481
|
+
ruby_tag_type[ruby_tag_type["Throw"] = 7] = "Throw";
|
|
482
|
+
ruby_tag_type[ruby_tag_type["Fatal"] = 8] = "Fatal";
|
|
483
|
+
ruby_tag_type[ruby_tag_type["Mask"] = 15] = "Mask";
|
|
484
|
+
})(ruby_tag_type || (ruby_tag_type = {}));
|
|
485
|
+
class RbExceptionFormatter {
|
|
486
|
+
constructor() {
|
|
487
|
+
this.literalsCache = null;
|
|
488
|
+
this.isFormmatting = false;
|
|
489
|
+
}
|
|
490
|
+
format(error, vm, privateObject) {
|
|
491
|
+
// All Ruby exceptions raised during formatting exception message should
|
|
492
|
+
// be caught and return a fallback message.
|
|
493
|
+
// Therefore, we don't need to worry about infinite recursion here ideally
|
|
494
|
+
// but checking re-entrancy just in case.
|
|
495
|
+
class RbExceptionFormatterError extends Error {
|
|
496
|
+
}
|
|
497
|
+
if (this.isFormmatting) {
|
|
498
|
+
throw new RbExceptionFormatterError("Unexpected exception occurred during formatting exception message");
|
|
499
|
+
}
|
|
500
|
+
this.isFormmatting = true;
|
|
501
|
+
try {
|
|
502
|
+
return this._format(error, vm, privateObject);
|
|
503
|
+
}
|
|
504
|
+
finally {
|
|
505
|
+
this.isFormmatting = false;
|
|
506
|
+
}
|
|
507
|
+
}
|
|
508
|
+
_format(error, vm, privateObject) {
|
|
509
|
+
const [zeroLiteral, oneLiteral, newLineLiteral] = (() => {
|
|
510
|
+
if (this.literalsCache == null) {
|
|
511
|
+
const zeroOneNewLine = [
|
|
512
|
+
evalRbCode(vm, privateObject, "0"),
|
|
513
|
+
evalRbCode(vm, privateObject, "1"),
|
|
514
|
+
evalRbCode(vm, privateObject, `"\n"`),
|
|
515
|
+
];
|
|
516
|
+
this.literalsCache = zeroOneNewLine;
|
|
517
|
+
return zeroOneNewLine;
|
|
518
|
+
}
|
|
519
|
+
else {
|
|
520
|
+
return this.literalsCache;
|
|
521
|
+
}
|
|
522
|
+
})();
|
|
523
|
+
let className;
|
|
524
|
+
let backtrace;
|
|
525
|
+
let message;
|
|
526
|
+
try {
|
|
527
|
+
className = error.call("class").toString();
|
|
528
|
+
}
|
|
529
|
+
catch (e) {
|
|
530
|
+
className = "unknown";
|
|
531
|
+
}
|
|
532
|
+
try {
|
|
533
|
+
message = error.toString();
|
|
534
|
+
}
|
|
535
|
+
catch (e) {
|
|
536
|
+
message = "unknown";
|
|
537
|
+
}
|
|
538
|
+
try {
|
|
539
|
+
backtrace = error.call("backtrace");
|
|
540
|
+
}
|
|
541
|
+
catch (e) {
|
|
542
|
+
return this.formatString(className, message);
|
|
543
|
+
}
|
|
544
|
+
if (backtrace.call("nil?").toString() === "true") {
|
|
545
|
+
return this.formatString(className, message);
|
|
546
|
+
}
|
|
547
|
+
try {
|
|
548
|
+
const firstLine = backtrace.call("at", zeroLiteral);
|
|
549
|
+
const restLines = backtrace
|
|
550
|
+
.call("drop", oneLiteral)
|
|
551
|
+
.call("join", newLineLiteral);
|
|
552
|
+
return this.formatString(className, message, [
|
|
553
|
+
firstLine.toString(),
|
|
554
|
+
restLines.toString(),
|
|
555
|
+
]);
|
|
556
|
+
}
|
|
557
|
+
catch (e) {
|
|
558
|
+
return this.formatString(className, message);
|
|
559
|
+
}
|
|
560
|
+
}
|
|
561
|
+
formatString(klass, message, backtrace) {
|
|
562
|
+
if (backtrace) {
|
|
563
|
+
return `${backtrace[0]}: ${message} (${klass})\n${backtrace[1]}`;
|
|
564
|
+
}
|
|
565
|
+
else {
|
|
566
|
+
return `${klass}: ${message}`;
|
|
567
|
+
}
|
|
568
|
+
}
|
|
569
|
+
}
|
|
570
|
+
const checkStatusTag = (rawTag, vm, privateObject) => {
|
|
571
|
+
switch (rawTag & ruby_tag_type.Mask) {
|
|
572
|
+
case ruby_tag_type.None:
|
|
573
|
+
break;
|
|
574
|
+
case ruby_tag_type.Return:
|
|
575
|
+
throw new RbError("unexpected return");
|
|
576
|
+
case ruby_tag_type.Next:
|
|
577
|
+
throw new RbError("unexpected next");
|
|
578
|
+
case ruby_tag_type.Break:
|
|
579
|
+
throw new RbError("unexpected break");
|
|
580
|
+
case ruby_tag_type.Redo:
|
|
581
|
+
throw new RbError("unexpected redo");
|
|
582
|
+
case ruby_tag_type.Retry:
|
|
583
|
+
throw new RbError("retry outside of rescue clause");
|
|
584
|
+
case ruby_tag_type.Throw:
|
|
585
|
+
throw new RbError("unexpected throw");
|
|
586
|
+
case ruby_tag_type.Raise:
|
|
587
|
+
case ruby_tag_type.Fatal:
|
|
588
|
+
const error = new RbValue(vm.guest.rbErrinfo(), vm, privateObject);
|
|
589
|
+
if (error.call("nil?").toString() === "true") {
|
|
590
|
+
throw new RbError("no exception object");
|
|
591
|
+
}
|
|
592
|
+
// clear errinfo if got exception due to no rb_jump_tag
|
|
593
|
+
vm.guest.rbClearErrinfo();
|
|
594
|
+
throw new RbError(privateObject.exceptionFormatter.format(error, vm, privateObject));
|
|
595
|
+
default:
|
|
596
|
+
throw new RbError(`unknown error tag: ${rawTag}`);
|
|
597
|
+
}
|
|
598
|
+
};
|
|
599
|
+
function wrapRbOperation(vm, body) {
|
|
600
|
+
try {
|
|
601
|
+
return body();
|
|
602
|
+
}
|
|
603
|
+
catch (e) {
|
|
604
|
+
if (e instanceof RbError) {
|
|
605
|
+
throw e;
|
|
606
|
+
}
|
|
607
|
+
// All JS exceptions triggered by Ruby code are translated to Ruby exceptions,
|
|
608
|
+
// so non-RbError exceptions are unexpected.
|
|
609
|
+
vm.guest.rbVmBugreport();
|
|
610
|
+
if (e instanceof WebAssembly.RuntimeError && e.message === "unreachable") {
|
|
611
|
+
const error = new RbError(`Something went wrong in Ruby VM: ${e}`);
|
|
612
|
+
error.stack = e.stack;
|
|
613
|
+
throw error;
|
|
614
|
+
}
|
|
615
|
+
else {
|
|
616
|
+
throw e;
|
|
617
|
+
}
|
|
618
|
+
}
|
|
619
|
+
}
|
|
620
|
+
const callRbMethod = (vm, privateObject, recv, callee, args) => {
|
|
621
|
+
const mid = vm.guest.rbIntern(callee + "\0");
|
|
622
|
+
return wrapRbOperation(vm, () => {
|
|
623
|
+
const [value, status] = vm.guest.rbFuncallvProtect(recv, mid, args);
|
|
624
|
+
checkStatusTag(status, vm, privateObject);
|
|
625
|
+
return value;
|
|
626
|
+
});
|
|
627
|
+
};
|
|
628
|
+
const evalRbCode = (vm, privateObject, code) => {
|
|
629
|
+
return wrapRbOperation(vm, () => {
|
|
630
|
+
const [value, status] = vm.guest.rbEvalStringProtect(code + "\0");
|
|
631
|
+
checkStatusTag(status, vm, privateObject);
|
|
632
|
+
return new RbValue(value, vm, privateObject);
|
|
633
|
+
});
|
|
634
|
+
};
|
|
635
|
+
function newRbPromise(vm, privateObject, body) {
|
|
636
|
+
return new Promise((resolve, reject) => {
|
|
637
|
+
const future = vm.wrap({
|
|
638
|
+
resolve,
|
|
639
|
+
reject: (error) => {
|
|
640
|
+
const rbError = new RbError(privateObject.exceptionFormatter.format(error, vm, privateObject));
|
|
641
|
+
reject(rbError);
|
|
642
|
+
},
|
|
643
|
+
});
|
|
644
|
+
body(future);
|
|
645
|
+
});
|
|
646
|
+
}
|
|
647
|
+
/**
|
|
648
|
+
* Error class thrown by Ruby execution
|
|
649
|
+
*/
|
|
650
|
+
export class RbError extends Error {
|
|
651
|
+
/**
|
|
652
|
+
* @hideconstructor
|
|
653
|
+
*/
|
|
654
|
+
constructor(message) {
|
|
655
|
+
super(message);
|
|
656
|
+
}
|
|
657
|
+
}
|
|
658
|
+
/**
|
|
659
|
+
* Error class thrown by Ruby execution when it is not possible to recover.
|
|
660
|
+
* This is usually caused when Ruby VM is in an inconsistent state.
|
|
661
|
+
*/
|
|
662
|
+
export class RbFatalError extends RbError {
|
|
663
|
+
/**
|
|
664
|
+
* @hideconstructor
|
|
665
|
+
*/
|
|
666
|
+
constructor(message) {
|
|
667
|
+
super("Ruby Fatal Error: " + message);
|
|
668
|
+
}
|
|
669
|
+
}
|