@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/dist/index.umd.js CHANGED
@@ -1,1346 +1,1379 @@
1
1
  (function (global, factory) {
2
- typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
3
- typeof define === 'function' && define.amd ? define(['exports'], factory) :
4
- (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global["ruby-wasm-wasi"] = {}));
2
+ typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
3
+ typeof define === 'function' && define.amd ? define(['exports'], factory) :
4
+ (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global["ruby-wasm-wasi"] = {}));
5
5
  })(this, (function (exports) { 'use strict';
6
6
 
7
- let DATA_VIEW = new DataView(new ArrayBuffer());
8
-
9
- function data_view(mem) {
10
- if (DATA_VIEW.buffer !== mem.buffer) DATA_VIEW = new DataView(mem.buffer);
11
- return DATA_VIEW;
12
- }
13
-
14
- function to_uint32(val) {
15
- return val >>> 0;
16
- }
17
- const UTF8_DECODER = new TextDecoder('utf-8');
7
+ /**
8
+ * Create a console printer that can be used as an overlay of WASI imports.
9
+ * See the example below for how to use it.
10
+ *
11
+ * ```javascript
12
+ * const imports = {
13
+ * "wasi_snapshot_preview1": wasi.wasiImport,
14
+ * }
15
+ * const printer = consolePrinter();
16
+ * printer.addToImports(imports);
17
+ *
18
+ * const instance = await WebAssembly.instantiate(module, imports);
19
+ * printer.setMemory(instance.exports.memory);
20
+ * ```
21
+ *
22
+ * Note that the `stdout` and `stderr` functions are called with text, not
23
+ * bytes. This means that bytes written to stdout/stderr will be decoded as
24
+ * UTF-8 and then passed to the `stdout`/`stderr` functions every time a write
25
+ * occurs without buffering.
26
+ *
27
+ * @param stdout A function that will be called when stdout is written to.
28
+ * Defaults to `console.log`.
29
+ * @param stderr A function that will be called when stderr is written to.
30
+ * Defaults to `console.warn`.
31
+ * @returns An object that can be used as an overlay of WASI imports.
32
+ */
33
+ function consolePrinter({ stdout, stderr, } = {
34
+ stdout: console.log,
35
+ stderr: console.warn,
36
+ }) {
37
+ let memory = undefined;
38
+ let _view = undefined;
39
+ function getMemoryView() {
40
+ if (typeof memory === "undefined") {
41
+ throw new Error("Memory is not set");
42
+ }
43
+ if (_view === undefined || _view.buffer.byteLength === 0) {
44
+ _view = new DataView(memory.buffer);
45
+ }
46
+ return _view;
47
+ }
48
+ const decoder = new TextDecoder();
49
+ return {
50
+ addToImports(imports) {
51
+ const wasiImport = imports.wasi_snapshot_preview1;
52
+ const original_fd_write = wasiImport.fd_write;
53
+ wasiImport.fd_write = (fd, iovs, iovsLen, nwritten) => {
54
+ if (fd !== 1 && fd !== 2) {
55
+ return original_fd_write(fd, iovs, iovsLen, nwritten);
56
+ }
57
+ const view = getMemoryView();
58
+ const buffers = Array.from({ length: iovsLen }, (_, i) => {
59
+ const ptr = iovs + i * 8;
60
+ const buf = view.getUint32(ptr, true);
61
+ const bufLen = view.getUint32(ptr + 4, true);
62
+ return new Uint8Array(memory.buffer, buf, bufLen);
63
+ });
64
+ let written = 0;
65
+ let str = "";
66
+ for (const buffer of buffers) {
67
+ str += decoder.decode(buffer);
68
+ written += buffer.byteLength;
69
+ }
70
+ view.setUint32(nwritten, written, true);
71
+ const log = fd === 1 ? stdout : stderr;
72
+ log(str);
73
+ return 0;
74
+ };
75
+ const original_fd_filestat_get = wasiImport.fd_filestat_get;
76
+ wasiImport.fd_filestat_get = (fd, filestat) => {
77
+ if (fd !== 1 && fd !== 2) {
78
+ return original_fd_filestat_get(fd, filestat);
79
+ }
80
+ const view = getMemoryView();
81
+ const result = original_fd_filestat_get(fd, filestat);
82
+ if (result !== 0) {
83
+ return result;
84
+ }
85
+ const filetypePtr = filestat + 0;
86
+ view.setUint8(filetypePtr, 2); // FILETYPE_CHARACTER_DEVICE
87
+ return 0;
88
+ };
89
+ const original_fd_fdstat_get = wasiImport.fd_fdstat_get;
90
+ wasiImport.fd_fdstat_get = (fd, fdstat) => {
91
+ if (fd !== 1 && fd !== 2) {
92
+ return original_fd_fdstat_get(fd, fdstat);
93
+ }
94
+ const view = getMemoryView();
95
+ const fs_filetypePtr = fdstat + 0;
96
+ view.setUint8(fs_filetypePtr, 2); // FILETYPE_CHARACTER_DEVICE
97
+ const fs_rights_basePtr = fdstat + 8;
98
+ view.setBigUint64(fs_rights_basePtr, BigInt(1)); // RIGHTS_FD_WRITE
99
+ return 0;
100
+ };
101
+ },
102
+ setMemory(m) {
103
+ memory = m;
104
+ },
105
+ };
106
+ }
18
107
 
19
- const UTF8_ENCODER = new TextEncoder('utf-8');
108
+ let DATA_VIEW = new DataView(new ArrayBuffer());
20
109
 
21
- function utf8_encode(s, realloc, memory) {
22
- if (typeof s !== 'string') throw new TypeError('expected a string');
23
-
24
- if (s.length === 0) {
25
- UTF8_ENCODED_LEN = 0;
26
- return 1;
110
+ function data_view(mem) {
111
+ if (DATA_VIEW.buffer !== mem.buffer) DATA_VIEW = new DataView(mem.buffer);
112
+ return DATA_VIEW;
27
113
  }
28
-
29
- let alloc_len = 0;
30
- let ptr = 0;
31
- let writtenTotal = 0;
32
- while (s.length > 0) {
33
- ptr = realloc(ptr, alloc_len, 1, alloc_len + s.length);
34
- alloc_len += s.length;
35
- const { read, written } = UTF8_ENCODER.encodeInto(
36
- s,
37
- new Uint8Array(memory.buffer, ptr + writtenTotal, alloc_len - writtenTotal),
38
- );
39
- writtenTotal += written;
40
- s = s.slice(read);
41
- }
42
- if (alloc_len > writtenTotal)
43
- ptr = realloc(ptr, alloc_len, 1, writtenTotal);
44
- UTF8_ENCODED_LEN = writtenTotal;
45
- return ptr;
46
- }
47
- let UTF8_ENCODED_LEN = 0;
48
114
 
49
- class Slab {
50
- constructor() {
51
- this.list = [];
52
- this.head = 0;
53
- }
54
-
55
- insert(val) {
56
- if (this.head >= this.list.length) {
57
- this.list.push({
58
- next: this.list.length + 1,
59
- val: undefined,
60
- });
61
- }
62
- const ret = this.head;
63
- const slot = this.list[ret];
64
- this.head = slot.next;
65
- slot.next = -1;
66
- slot.val = val;
67
- return ret;
115
+ function to_uint32(val) {
116
+ return val >>> 0;
68
117
  }
69
-
70
- get(idx) {
71
- if (idx >= this.list.length)
72
- throw new RangeError('handle index not valid');
73
- const slot = this.list[idx];
74
- if (slot.next === -1)
75
- return slot.val;
76
- throw new RangeError('handle index not valid');
77
- }
78
-
79
- remove(idx) {
80
- const ret = this.get(idx); // validate the slot
81
- const slot = this.list[idx];
82
- slot.val = undefined;
83
- slot.next = this.head;
84
- this.head = idx;
85
- return ret;
86
- }
87
- }
118
+ const UTF8_DECODER = new TextDecoder('utf-8');
88
119
 
89
- function throw_invalid_bool() {
90
- throw new RangeError("invalid variant discriminant for bool");
91
- }
120
+ const UTF8_ENCODER = new TextEncoder('utf-8');
92
121
 
93
- class RbAbiGuest {
94
- constructor() {
95
- this._resource0_slab = new Slab();
96
- this._resource1_slab = new Slab();
97
- }
98
- addToImports(imports) {
99
- if (!("canonical_abi" in imports)) imports["canonical_abi"] = {};
122
+ function utf8_encode(s, realloc, memory) {
123
+ if (typeof s !== 'string') throw new TypeError('expected a string');
100
124
 
101
- imports.canonical_abi['resource_drop_rb-iseq'] = i => {
102
- this._resource0_slab.remove(i).drop();
103
- };
104
- imports.canonical_abi['resource_clone_rb-iseq'] = i => {
105
- const obj = this._resource0_slab.get(i);
106
- return this._resource0_slab.insert(obj.clone())
107
- };
108
- imports.canonical_abi['resource_get_rb-iseq'] = i => {
109
- return this._resource0_slab.get(i)._wasm_val;
110
- };
111
- imports.canonical_abi['resource_new_rb-iseq'] = i => {
112
- this._registry0;
113
- return this._resource0_slab.insert(new RbIseq(i, this));
114
- };
115
-
116
- imports.canonical_abi['resource_drop_rb-abi-value'] = i => {
117
- this._resource1_slab.remove(i).drop();
118
- };
119
- imports.canonical_abi['resource_clone_rb-abi-value'] = i => {
120
- const obj = this._resource1_slab.get(i);
121
- return this._resource1_slab.insert(obj.clone())
122
- };
123
- imports.canonical_abi['resource_get_rb-abi-value'] = i => {
124
- return this._resource1_slab.get(i)._wasm_val;
125
- };
126
- imports.canonical_abi['resource_new_rb-abi-value'] = i => {
127
- this._registry1;
128
- return this._resource1_slab.insert(new RbAbiValue(i, this));
129
- };
130
- }
131
-
132
- async instantiate(module, imports) {
133
- imports = imports || {};
134
- this.addToImports(imports);
125
+ if (s.length === 0) {
126
+ UTF8_ENCODED_LEN = 0;
127
+ return 1;
128
+ }
135
129
 
136
- if (module instanceof WebAssembly.Instance) {
137
- this.instance = module;
138
- } else if (module instanceof WebAssembly.Module) {
139
- this.instance = await WebAssembly.instantiate(module, imports);
140
- } else if (module instanceof ArrayBuffer || module instanceof Uint8Array) {
141
- const { instance } = await WebAssembly.instantiate(module, imports);
142
- this.instance = instance;
143
- } else {
144
- const { instance } = await WebAssembly.instantiateStreaming(module, imports);
145
- this.instance = instance;
130
+ let alloc_len = 0;
131
+ let ptr = 0;
132
+ let writtenTotal = 0;
133
+ while (s.length > 0) {
134
+ ptr = realloc(ptr, alloc_len, 1, alloc_len + s.length);
135
+ alloc_len += s.length;
136
+ const { read, written } = UTF8_ENCODER.encodeInto(
137
+ s,
138
+ new Uint8Array(memory.buffer, ptr + writtenTotal, alloc_len - writtenTotal),
139
+ );
140
+ writtenTotal += written;
141
+ s = s.slice(read);
146
142
  }
147
- this._exports = this.instance.exports;
148
- this._registry0 = new FinalizationRegistry(this._exports['canonical_abi_drop_rb-iseq']);
149
- this._registry1 = new FinalizationRegistry(this._exports['canonical_abi_drop_rb-abi-value']);
150
- }
151
- rubyShowVersion() {
152
- this._exports['ruby-show-version: func() -> ()']();
143
+ if (alloc_len > writtenTotal)
144
+ ptr = realloc(ptr, alloc_len, 1, writtenTotal);
145
+ UTF8_ENCODED_LEN = writtenTotal;
146
+ return ptr;
153
147
  }
154
- rubyInit() {
155
- this._exports['ruby-init: func() -> ()']();
156
- }
157
- rubySysinit(arg0) {
158
- const memory = this._exports.memory;
159
- const realloc = this._exports["cabi_realloc"];
160
- const vec1 = arg0;
161
- const len1 = vec1.length;
162
- const result1 = realloc(0, 0, 4, len1 * 8);
163
- for (let i = 0; i < vec1.length; i++) {
164
- const e = vec1[i];
165
- const base = result1 + i * 8;
166
- const ptr0 = utf8_encode(e, realloc, memory);
167
- const len0 = UTF8_ENCODED_LEN;
168
- data_view(memory).setInt32(base + 4, len0, true);
169
- data_view(memory).setInt32(base + 0, ptr0, true);
148
+ let UTF8_ENCODED_LEN = 0;
149
+
150
+ class Slab {
151
+ constructor() {
152
+ this.list = [];
153
+ this.head = 0;
170
154
  }
171
- this._exports['ruby-sysinit: func(args: list<string>) -> ()'](result1, len1);
172
- }
173
- rubyOptions(arg0) {
174
- const memory = this._exports.memory;
175
- const realloc = this._exports["cabi_realloc"];
176
- const vec1 = arg0;
177
- const len1 = vec1.length;
178
- const result1 = realloc(0, 0, 4, len1 * 8);
179
- for (let i = 0; i < vec1.length; i++) {
180
- const e = vec1[i];
181
- const base = result1 + i * 8;
182
- const ptr0 = utf8_encode(e, realloc, memory);
183
- const len0 = UTF8_ENCODED_LEN;
184
- data_view(memory).setInt32(base + 4, len0, true);
185
- data_view(memory).setInt32(base + 0, ptr0, true);
155
+
156
+ insert(val) {
157
+ if (this.head >= this.list.length) {
158
+ this.list.push({
159
+ next: this.list.length + 1,
160
+ val: undefined,
161
+ });
162
+ }
163
+ const ret = this.head;
164
+ const slot = this.list[ret];
165
+ this.head = slot.next;
166
+ slot.next = -1;
167
+ slot.val = val;
168
+ return ret;
186
169
  }
187
- const ret = this._exports['ruby-options: func(args: list<string>) -> handle<rb-iseq>'](result1, len1);
188
- return this._resource0_slab.remove(ret);
189
- }
190
- rubyScript(arg0) {
191
- const memory = this._exports.memory;
192
- const realloc = this._exports["cabi_realloc"];
193
- const ptr0 = utf8_encode(arg0, realloc, memory);
194
- const len0 = UTF8_ENCODED_LEN;
195
- this._exports['ruby-script: func(name: string) -> ()'](ptr0, len0);
196
- }
197
- rubyInitLoadpath() {
198
- this._exports['ruby-init-loadpath: func() -> ()']();
199
- }
200
- rbEvalStringProtect(arg0) {
201
- const memory = this._exports.memory;
202
- const realloc = this._exports["cabi_realloc"];
203
- const ptr0 = utf8_encode(arg0, realloc, memory);
204
- const len0 = UTF8_ENCODED_LEN;
205
- const ret = this._exports['rb-eval-string-protect: func(str: string) -> tuple<handle<rb-abi-value>, s32>'](ptr0, len0);
206
- return [this._resource1_slab.remove(data_view(memory).getInt32(ret + 0, true)), data_view(memory).getInt32(ret + 4, true)];
207
- }
208
- rbFuncallvProtect(arg0, arg1, arg2) {
209
- const memory = this._exports.memory;
210
- const realloc = this._exports["cabi_realloc"];
211
- const obj0 = arg0;
212
- if (!(obj0 instanceof RbAbiValue)) throw new TypeError('expected instance of RbAbiValue');
213
- const vec2 = arg2;
214
- const len2 = vec2.length;
215
- const result2 = realloc(0, 0, 4, len2 * 4);
216
- for (let i = 0; i < vec2.length; i++) {
217
- const e = vec2[i];
218
- const base = result2 + i * 4;
219
- const obj1 = e;
220
- if (!(obj1 instanceof RbAbiValue)) throw new TypeError('expected instance of RbAbiValue');
221
- data_view(memory).setInt32(base + 0, this._resource1_slab.insert(obj1.clone()), true);
170
+
171
+ get(idx) {
172
+ if (idx >= this.list.length)
173
+ throw new RangeError('handle index not valid');
174
+ const slot = this.list[idx];
175
+ if (slot.next === -1)
176
+ return slot.val;
177
+ throw new RangeError('handle index not valid');
178
+ }
179
+
180
+ remove(idx) {
181
+ const ret = this.get(idx); // validate the slot
182
+ const slot = this.list[idx];
183
+ slot.val = undefined;
184
+ slot.next = this.head;
185
+ this.head = idx;
186
+ return ret;
222
187
  }
223
- const ret = this._exports['rb-funcallv-protect: func(recv: handle<rb-abi-value>, mid: u32, args: list<handle<rb-abi-value>>) -> tuple<handle<rb-abi-value>, s32>'](this._resource1_slab.insert(obj0.clone()), to_uint32(arg1), result2, len2);
224
- return [this._resource1_slab.remove(data_view(memory).getInt32(ret + 0, true)), data_view(memory).getInt32(ret + 4, true)];
225
- }
226
- rbIntern(arg0) {
227
- const memory = this._exports.memory;
228
- const realloc = this._exports["cabi_realloc"];
229
- const ptr0 = utf8_encode(arg0, realloc, memory);
230
- const len0 = UTF8_ENCODED_LEN;
231
- const ret = this._exports['rb-intern: func(name: string) -> u32'](ptr0, len0);
232
- return ret >>> 0;
233
- }
234
- rbErrinfo() {
235
- const ret = this._exports['rb-errinfo: func() -> handle<rb-abi-value>']();
236
- return this._resource1_slab.remove(ret);
237
- }
238
- rbClearErrinfo() {
239
- this._exports['rb-clear-errinfo: func() -> ()']();
240
- }
241
- rstringPtr(arg0) {
242
- const memory = this._exports.memory;
243
- const obj0 = arg0;
244
- if (!(obj0 instanceof RbAbiValue)) throw new TypeError('expected instance of RbAbiValue');
245
- const ret = this._exports['rstring-ptr: func(value: handle<rb-abi-value>) -> string'](this._resource1_slab.insert(obj0.clone()));
246
- const ptr1 = data_view(memory).getInt32(ret + 0, true);
247
- const len1 = data_view(memory).getInt32(ret + 4, true);
248
- const result1 = UTF8_DECODER.decode(new Uint8Array(memory.buffer, ptr1, len1));
249
- this._exports["cabi_post_rstring-ptr"](ret);
250
- return result1;
251
- }
252
- rbVmBugreport() {
253
- this._exports['rb-vm-bugreport: func() -> ()']();
254
- }
255
- rbGcEnable() {
256
- const ret = this._exports['rb-gc-enable: func() -> bool']();
257
- const bool0 = ret;
258
- return bool0 == 0 ? false : (bool0 == 1 ? true : throw_invalid_bool());
259
- }
260
- rbGcDisable() {
261
- const ret = this._exports['rb-gc-disable: func() -> bool']();
262
- const bool0 = ret;
263
- return bool0 == 0 ? false : (bool0 == 1 ? true : throw_invalid_bool());
264
- }
265
- rbSetShouldProhibitRewind(arg0) {
266
- const ret = this._exports['rb-set-should-prohibit-rewind: func(new-value: bool) -> bool'](arg0 ? 1 : 0);
267
- const bool0 = ret;
268
- return bool0 == 0 ? false : (bool0 == 1 ? true : throw_invalid_bool());
269
- }
270
- }
271
-
272
- class RbIseq {
273
- constructor(wasm_val, obj) {
274
- this._wasm_val = wasm_val;
275
- this._obj = obj;
276
- this._refcnt = 1;
277
- obj._registry0.register(this, wasm_val, this);
278
- }
279
-
280
- clone() {
281
- this._refcnt += 1;
282
- return this;
283
- }
284
-
285
- drop() {
286
- this._refcnt -= 1;
287
- if (this._refcnt !== 0)
288
- return;
289
- this._obj._registry0.unregister(this);
290
- const dtor = this._obj._exports['canonical_abi_drop_rb-iseq'];
291
- const wasm_val = this._wasm_val;
292
- delete this._obj;
293
- delete this._refcnt;
294
- delete this._wasm_val;
295
- dtor(wasm_val);
296
188
  }
297
- }
298
189
 
299
- class RbAbiValue {
300
- constructor(wasm_val, obj) {
301
- this._wasm_val = wasm_val;
302
- this._obj = obj;
303
- this._refcnt = 1;
304
- obj._registry1.register(this, wasm_val, this);
305
- }
306
-
307
- clone() {
308
- this._refcnt += 1;
309
- return this;
190
+ function throw_invalid_bool() {
191
+ throw new RangeError("invalid variant discriminant for bool");
310
192
  }
311
-
312
- drop() {
313
- this._refcnt -= 1;
314
- if (this._refcnt !== 0)
315
- return;
316
- this._obj._registry1.unregister(this);
317
- const dtor = this._obj._exports['canonical_abi_drop_rb-abi-value'];
318
- const wasm_val = this._wasm_val;
319
- delete this._obj;
320
- delete this._refcnt;
321
- delete this._wasm_val;
322
- dtor(wasm_val);
323
- }
324
- }
325
193
 
326
- function addRbJsAbiHostToImports(imports, obj, get_export) {
327
- if (!("rb-js-abi-host" in imports)) imports["rb-js-abi-host"] = {};
328
- imports["rb-js-abi-host"]["eval-js: func(code: string) -> variant { success(handle<js-abi-value>), failure(handle<js-abi-value>) }"] = function(arg0, arg1, arg2) {
329
- const memory = get_export("memory");
330
- const ptr0 = arg0;
331
- const len0 = arg1;
332
- const result0 = UTF8_DECODER.decode(new Uint8Array(memory.buffer, ptr0, len0));
333
- const ret0 = obj.evalJs(result0);
334
- const variant1 = ret0;
335
- switch (variant1.tag) {
336
- case "success": {
337
- const e = variant1.val;
338
- data_view(memory).setInt8(arg2 + 0, 0, true);
339
- data_view(memory).setInt32(arg2 + 4, resources0.insert(e), true);
340
- break;
341
- }
342
- case "failure": {
343
- const e = variant1.val;
344
- data_view(memory).setInt8(arg2 + 0, 1, true);
345
- data_view(memory).setInt32(arg2 + 4, resources0.insert(e), true);
346
- break;
347
- }
348
- default:
349
- throw new RangeError("invalid variant specified for JsAbiResult");
350
- }
351
- };
352
- imports["rb-js-abi-host"]["is-js: func(value: handle<js-abi-value>) -> bool"] = function(arg0) {
353
- const ret0 = obj.isJs(resources0.get(arg0));
354
- return ret0 ? 1 : 0;
355
- };
356
- imports["rb-js-abi-host"]["instance-of: func(value: handle<js-abi-value>, klass: handle<js-abi-value>) -> bool"] = function(arg0, arg1) {
357
- const ret0 = obj.instanceOf(resources0.get(arg0), resources0.get(arg1));
358
- return ret0 ? 1 : 0;
359
- };
360
- imports["rb-js-abi-host"]["global-this: func() -> handle<js-abi-value>"] = function() {
361
- const ret0 = obj.globalThis();
362
- return resources0.insert(ret0);
363
- };
364
- imports["rb-js-abi-host"]["int-to-js-number: func(value: s32) -> handle<js-abi-value>"] = function(arg0) {
365
- const ret0 = obj.intToJsNumber(arg0);
366
- return resources0.insert(ret0);
367
- };
368
- imports["rb-js-abi-host"]["float-to-js-number: func(value: float64) -> handle<js-abi-value>"] = function(arg0) {
369
- const ret0 = obj.floatToJsNumber(arg0);
370
- return resources0.insert(ret0);
371
- };
372
- imports["rb-js-abi-host"]["string-to-js-string: func(value: string) -> handle<js-abi-value>"] = function(arg0, arg1) {
373
- const memory = get_export("memory");
374
- const ptr0 = arg0;
375
- const len0 = arg1;
376
- const result0 = UTF8_DECODER.decode(new Uint8Array(memory.buffer, ptr0, len0));
377
- const ret0 = obj.stringToJsString(result0);
378
- return resources0.insert(ret0);
379
- };
380
- imports["rb-js-abi-host"]["bool-to-js-bool: func(value: bool) -> handle<js-abi-value>"] = function(arg0) {
381
- const bool0 = arg0;
382
- const ret0 = obj.boolToJsBool(bool0 == 0 ? false : (bool0 == 1 ? true : throw_invalid_bool()));
383
- return resources0.insert(ret0);
384
- };
385
- imports["rb-js-abi-host"]["proc-to-js-function: func(value: u32) -> handle<js-abi-value>"] = function(arg0) {
386
- const ret0 = obj.procToJsFunction(arg0 >>> 0);
387
- return resources0.insert(ret0);
388
- };
389
- imports["rb-js-abi-host"]["rb-object-to-js-rb-value: func(raw-rb-abi-value: u32) -> handle<js-abi-value>"] = function(arg0) {
390
- const ret0 = obj.rbObjectToJsRbValue(arg0 >>> 0);
391
- return resources0.insert(ret0);
392
- };
393
- imports["rb-js-abi-host"]["js-value-to-string: func(value: handle<js-abi-value>) -> string"] = function(arg0, arg1) {
394
- const memory = get_export("memory");
395
- const realloc = get_export("cabi_realloc");
396
- const ret0 = obj.jsValueToString(resources0.get(arg0));
397
- const ptr0 = utf8_encode(ret0, realloc, memory);
398
- const len0 = UTF8_ENCODED_LEN;
399
- data_view(memory).setInt32(arg1 + 4, len0, true);
400
- data_view(memory).setInt32(arg1 + 0, ptr0, true);
401
- };
402
- imports["rb-js-abi-host"]["js-value-to-integer: func(value: handle<js-abi-value>) -> variant { f64(float64), bignum(string) }"] = function(arg0, arg1) {
403
- const memory = get_export("memory");
404
- const realloc = get_export("cabi_realloc");
405
- const ret0 = obj.jsValueToInteger(resources0.get(arg0));
406
- const variant1 = ret0;
407
- switch (variant1.tag) {
408
- case "f64": {
409
- const e = variant1.val;
410
- data_view(memory).setInt8(arg1 + 0, 0, true);
411
- data_view(memory).setFloat64(arg1 + 8, +e, true);
412
- break;
413
- }
414
- case "bignum": {
415
- const e = variant1.val;
416
- data_view(memory).setInt8(arg1 + 0, 1, true);
417
- const ptr0 = utf8_encode(e, realloc, memory);
418
- const len0 = UTF8_ENCODED_LEN;
419
- data_view(memory).setInt32(arg1 + 12, len0, true);
420
- data_view(memory).setInt32(arg1 + 8, ptr0, true);
421
- break;
422
- }
423
- default:
424
- throw new RangeError("invalid variant specified for RawInteger");
194
+ class RbAbiGuest {
195
+ constructor() {
196
+ this._resource0_slab = new Slab();
197
+ this._resource1_slab = new Slab();
425
198
  }
426
- };
427
- imports["rb-js-abi-host"]["export-js-value-to-host: func(value: handle<js-abi-value>) -> ()"] = function(arg0) {
428
- obj.exportJsValueToHost(resources0.get(arg0));
429
- };
430
- imports["rb-js-abi-host"]["import-js-value-from-host: func() -> handle<js-abi-value>"] = function() {
431
- const ret0 = obj.importJsValueFromHost();
432
- return resources0.insert(ret0);
433
- };
434
- imports["rb-js-abi-host"]["js-value-typeof: func(value: handle<js-abi-value>) -> string"] = function(arg0, arg1) {
435
- const memory = get_export("memory");
436
- const realloc = get_export("cabi_realloc");
437
- const ret0 = obj.jsValueTypeof(resources0.get(arg0));
438
- const ptr0 = utf8_encode(ret0, realloc, memory);
439
- const len0 = UTF8_ENCODED_LEN;
440
- data_view(memory).setInt32(arg1 + 4, len0, true);
441
- data_view(memory).setInt32(arg1 + 0, ptr0, true);
442
- };
443
- imports["rb-js-abi-host"]["js-value-equal: func(lhs: handle<js-abi-value>, rhs: handle<js-abi-value>) -> bool"] = function(arg0, arg1) {
444
- const ret0 = obj.jsValueEqual(resources0.get(arg0), resources0.get(arg1));
445
- return ret0 ? 1 : 0;
446
- };
447
- imports["rb-js-abi-host"]["js-value-strictly-equal: func(lhs: handle<js-abi-value>, rhs: handle<js-abi-value>) -> bool"] = function(arg0, arg1) {
448
- const ret0 = obj.jsValueStrictlyEqual(resources0.get(arg0), resources0.get(arg1));
449
- return ret0 ? 1 : 0;
450
- };
451
- imports["rb-js-abi-host"]["reflect-apply: func(target: handle<js-abi-value>, this-argument: handle<js-abi-value>, arguments: list<handle<js-abi-value>>) -> variant { success(handle<js-abi-value>), failure(handle<js-abi-value>) }"] = function(arg0, arg1, arg2, arg3, arg4) {
452
- const memory = get_export("memory");
453
- const len0 = arg3;
454
- const base0 = arg2;
455
- const result0 = [];
456
- for (let i = 0; i < len0; i++) {
457
- const base = base0 + i * 4;
458
- result0.push(resources0.get(data_view(memory).getInt32(base + 0, true)));
199
+ addToImports(imports) {
200
+ if (!("canonical_abi" in imports)) imports["canonical_abi"] = {};
201
+
202
+ imports.canonical_abi['resource_drop_rb-iseq'] = i => {
203
+ this._resource0_slab.remove(i).drop();
204
+ };
205
+ imports.canonical_abi['resource_clone_rb-iseq'] = i => {
206
+ const obj = this._resource0_slab.get(i);
207
+ return this._resource0_slab.insert(obj.clone())
208
+ };
209
+ imports.canonical_abi['resource_get_rb-iseq'] = i => {
210
+ return this._resource0_slab.get(i)._wasm_val;
211
+ };
212
+ imports.canonical_abi['resource_new_rb-iseq'] = i => {
213
+ this._registry0;
214
+ return this._resource0_slab.insert(new RbIseq(i, this));
215
+ };
216
+
217
+ imports.canonical_abi['resource_drop_rb-abi-value'] = i => {
218
+ this._resource1_slab.remove(i).drop();
219
+ };
220
+ imports.canonical_abi['resource_clone_rb-abi-value'] = i => {
221
+ const obj = this._resource1_slab.get(i);
222
+ return this._resource1_slab.insert(obj.clone())
223
+ };
224
+ imports.canonical_abi['resource_get_rb-abi-value'] = i => {
225
+ return this._resource1_slab.get(i)._wasm_val;
226
+ };
227
+ imports.canonical_abi['resource_new_rb-abi-value'] = i => {
228
+ this._registry1;
229
+ return this._resource1_slab.insert(new RbAbiValue(i, this));
230
+ };
459
231
  }
460
- const ret0 = obj.reflectApply(resources0.get(arg0), resources0.get(arg1), result0);
461
- const variant1 = ret0;
462
- switch (variant1.tag) {
463
- case "success": {
464
- const e = variant1.val;
465
- data_view(memory).setInt8(arg4 + 0, 0, true);
466
- data_view(memory).setInt32(arg4 + 4, resources0.insert(e), true);
467
- break;
468
- }
469
- case "failure": {
470
- const e = variant1.val;
471
- data_view(memory).setInt8(arg4 + 0, 1, true);
472
- data_view(memory).setInt32(arg4 + 4, resources0.insert(e), true);
473
- break;
232
+
233
+ async instantiate(module, imports) {
234
+ imports = imports || {};
235
+ this.addToImports(imports);
236
+
237
+ if (module instanceof WebAssembly.Instance) {
238
+ this.instance = module;
239
+ } else if (module instanceof WebAssembly.Module) {
240
+ this.instance = await WebAssembly.instantiate(module, imports);
241
+ } else if (module instanceof ArrayBuffer || module instanceof Uint8Array) {
242
+ const { instance } = await WebAssembly.instantiate(module, imports);
243
+ this.instance = instance;
244
+ } else {
245
+ const { instance } = await WebAssembly.instantiateStreaming(module, imports);
246
+ this.instance = instance;
474
247
  }
475
- default:
476
- throw new RangeError("invalid variant specified for JsAbiResult");
248
+ this._exports = this.instance.exports;
249
+ this._registry0 = new FinalizationRegistry(this._exports['canonical_abi_drop_rb-iseq']);
250
+ this._registry1 = new FinalizationRegistry(this._exports['canonical_abi_drop_rb-abi-value']);
477
251
  }
478
- };
479
- imports["rb-js-abi-host"]["reflect-construct: func(target: handle<js-abi-value>, arguments: list<handle<js-abi-value>>) -> handle<js-abi-value>"] = function(arg0, arg1, arg2) {
480
- const memory = get_export("memory");
481
- const len0 = arg2;
482
- const base0 = arg1;
483
- const result0 = [];
484
- for (let i = 0; i < len0; i++) {
485
- const base = base0 + i * 4;
486
- result0.push(resources0.get(data_view(memory).getInt32(base + 0, true)));
252
+ rubyShowVersion() {
253
+ this._exports['ruby-show-version: func() -> ()']();
487
254
  }
488
- const ret0 = obj.reflectConstruct(resources0.get(arg0), result0);
489
- return resources0.insert(ret0);
490
- };
491
- imports["rb-js-abi-host"]["reflect-delete-property: func(target: handle<js-abi-value>, property-key: string) -> bool"] = function(arg0, arg1, arg2) {
492
- const memory = get_export("memory");
493
- const ptr0 = arg1;
494
- const len0 = arg2;
495
- const result0 = UTF8_DECODER.decode(new Uint8Array(memory.buffer, ptr0, len0));
496
- const ret0 = obj.reflectDeleteProperty(resources0.get(arg0), result0);
497
- return ret0 ? 1 : 0;
498
- };
499
- imports["rb-js-abi-host"]["reflect-get: func(target: handle<js-abi-value>, property-key: string) -> variant { success(handle<js-abi-value>), failure(handle<js-abi-value>) }"] = function(arg0, arg1, arg2, arg3) {
500
- const memory = get_export("memory");
501
- const ptr0 = arg1;
502
- const len0 = arg2;
503
- const result0 = UTF8_DECODER.decode(new Uint8Array(memory.buffer, ptr0, len0));
504
- const ret0 = obj.reflectGet(resources0.get(arg0), result0);
505
- const variant1 = ret0;
506
- switch (variant1.tag) {
507
- case "success": {
508
- const e = variant1.val;
509
- data_view(memory).setInt8(arg3 + 0, 0, true);
510
- data_view(memory).setInt32(arg3 + 4, resources0.insert(e), true);
511
- break;
512
- }
513
- case "failure": {
514
- const e = variant1.val;
515
- data_view(memory).setInt8(arg3 + 0, 1, true);
516
- data_view(memory).setInt32(arg3 + 4, resources0.insert(e), true);
517
- break;
518
- }
519
- default:
520
- throw new RangeError("invalid variant specified for JsAbiResult");
521
- }
522
- };
523
- imports["rb-js-abi-host"]["reflect-get-own-property-descriptor: func(target: handle<js-abi-value>, property-key: string) -> handle<js-abi-value>"] = function(arg0, arg1, arg2) {
524
- const memory = get_export("memory");
525
- const ptr0 = arg1;
526
- const len0 = arg2;
527
- const result0 = UTF8_DECODER.decode(new Uint8Array(memory.buffer, ptr0, len0));
528
- const ret0 = obj.reflectGetOwnPropertyDescriptor(resources0.get(arg0), result0);
529
- return resources0.insert(ret0);
530
- };
531
- imports["rb-js-abi-host"]["reflect-get-prototype-of: func(target: handle<js-abi-value>) -> handle<js-abi-value>"] = function(arg0) {
532
- const ret0 = obj.reflectGetPrototypeOf(resources0.get(arg0));
533
- return resources0.insert(ret0);
534
- };
535
- imports["rb-js-abi-host"]["reflect-has: func(target: handle<js-abi-value>, property-key: string) -> bool"] = function(arg0, arg1, arg2) {
536
- const memory = get_export("memory");
537
- const ptr0 = arg1;
538
- const len0 = arg2;
539
- const result0 = UTF8_DECODER.decode(new Uint8Array(memory.buffer, ptr0, len0));
540
- const ret0 = obj.reflectHas(resources0.get(arg0), result0);
541
- return ret0 ? 1 : 0;
542
- };
543
- imports["rb-js-abi-host"]["reflect-is-extensible: func(target: handle<js-abi-value>) -> bool"] = function(arg0) {
544
- const ret0 = obj.reflectIsExtensible(resources0.get(arg0));
545
- return ret0 ? 1 : 0;
546
- };
547
- imports["rb-js-abi-host"]["reflect-own-keys: func(target: handle<js-abi-value>) -> list<handle<js-abi-value>>"] = function(arg0, arg1) {
548
- const memory = get_export("memory");
549
- const realloc = get_export("cabi_realloc");
550
- const ret0 = obj.reflectOwnKeys(resources0.get(arg0));
551
- const vec0 = ret0;
552
- const len0 = vec0.length;
553
- const result0 = realloc(0, 0, 4, len0 * 4);
554
- for (let i = 0; i < vec0.length; i++) {
555
- const e = vec0[i];
556
- const base = result0 + i * 4;
557
- data_view(memory).setInt32(base + 0, resources0.insert(e), true);
255
+ rubyInit() {
256
+ this._exports['ruby-init: func() -> ()']();
558
257
  }
559
- data_view(memory).setInt32(arg1 + 4, len0, true);
560
- data_view(memory).setInt32(arg1 + 0, result0, true);
561
- };
562
- imports["rb-js-abi-host"]["reflect-prevent-extensions: func(target: handle<js-abi-value>) -> bool"] = function(arg0) {
563
- const ret0 = obj.reflectPreventExtensions(resources0.get(arg0));
564
- return ret0 ? 1 : 0;
565
- };
566
- imports["rb-js-abi-host"]["reflect-set: func(target: handle<js-abi-value>, property-key: string, value: handle<js-abi-value>) -> variant { success(handle<js-abi-value>), failure(handle<js-abi-value>) }"] = function(arg0, arg1, arg2, arg3, arg4) {
567
- const memory = get_export("memory");
568
- const ptr0 = arg1;
569
- const len0 = arg2;
570
- const result0 = UTF8_DECODER.decode(new Uint8Array(memory.buffer, ptr0, len0));
571
- const ret0 = obj.reflectSet(resources0.get(arg0), result0, resources0.get(arg3));
572
- const variant1 = ret0;
573
- switch (variant1.tag) {
574
- case "success": {
575
- const e = variant1.val;
576
- data_view(memory).setInt8(arg4 + 0, 0, true);
577
- data_view(memory).setInt32(arg4 + 4, resources0.insert(e), true);
578
- break;
579
- }
580
- case "failure": {
581
- const e = variant1.val;
582
- data_view(memory).setInt8(arg4 + 0, 1, true);
583
- data_view(memory).setInt32(arg4 + 4, resources0.insert(e), true);
584
- break;
258
+ rubySysinit(arg0) {
259
+ const memory = this._exports.memory;
260
+ const realloc = this._exports["cabi_realloc"];
261
+ const vec1 = arg0;
262
+ const len1 = vec1.length;
263
+ const result1 = realloc(0, 0, 4, len1 * 8);
264
+ for (let i = 0; i < vec1.length; i++) {
265
+ const e = vec1[i];
266
+ const base = result1 + i * 8;
267
+ const ptr0 = utf8_encode(e, realloc, memory);
268
+ const len0 = UTF8_ENCODED_LEN;
269
+ data_view(memory).setInt32(base + 4, len0, true);
270
+ data_view(memory).setInt32(base + 0, ptr0, true);
585
271
  }
586
- default:
587
- throw new RangeError("invalid variant specified for JsAbiResult");
588
- }
589
- };
590
- imports["rb-js-abi-host"]["reflect-set-prototype-of: func(target: handle<js-abi-value>, prototype: handle<js-abi-value>) -> bool"] = function(arg0, arg1) {
591
- const ret0 = obj.reflectSetPrototypeOf(resources0.get(arg0), resources0.get(arg1));
592
- return ret0 ? 1 : 0;
593
- };
594
- if (!("canonical_abi" in imports)) imports["canonical_abi"] = {};
595
-
596
- const resources0 = new Slab();
597
- imports.canonical_abi["resource_drop_js-abi-value"] = (i) => {
598
- const val = resources0.remove(i);
599
- if (obj.dropJsAbiValue)
600
- obj.dropJsAbiValue(val);
601
- };
602
- }
603
-
604
- /**
605
- * Create a console printer that can be used as an overlay of WASI imports.
606
- * See the example below for how to use it.
607
- *
608
- * ```javascript
609
- * const imports = {
610
- * "wasi_snapshot_preview1": wasi.wasiImport,
611
- * }
612
- * const printer = consolePrinter();
613
- * printer.addToImports(imports);
614
- *
615
- * const instance = await WebAssembly.instantiate(module, imports);
616
- * printer.setMemory(instance.exports.memory);
617
- * ```
618
- *
619
- * Note that the `stdout` and `stderr` functions are called with text, not
620
- * bytes. This means that bytes written to stdout/stderr will be decoded as
621
- * UTF-8 and then passed to the `stdout`/`stderr` functions every time a write
622
- * occurs without buffering.
623
- *
624
- * @param stdout A function that will be called when stdout is written to.
625
- * Defaults to `console.log`.
626
- * @param stderr A function that will be called when stderr is written to.
627
- * Defaults to `console.warn`.
628
- * @returns An object that can be used as an overlay of WASI imports.
629
- */
630
- function consolePrinter({ stdout, stderr, } = {
631
- stdout: console.log,
632
- stderr: console.warn,
633
- }) {
634
- let memory = undefined;
635
- let _view = undefined;
636
- function getMemoryView() {
637
- if (typeof memory === "undefined") {
638
- throw new Error("Memory is not set");
639
- }
640
- if (_view === undefined || _view.buffer.byteLength === 0) {
641
- _view = new DataView(memory.buffer);
642
- }
643
- return _view;
272
+ this._exports['ruby-sysinit: func(args: list<string>) -> ()'](result1, len1);
644
273
  }
645
- const decoder = new TextDecoder();
646
- return {
647
- addToImports(imports) {
648
- const wasiImport = imports.wasi_snapshot_preview1;
649
- const original_fd_write = wasiImport.fd_write;
650
- wasiImport.fd_write = (fd, iovs, iovsLen, nwritten) => {
651
- if (fd !== 1 && fd !== 2) {
652
- return original_fd_write(fd, iovs, iovsLen, nwritten);
653
- }
654
- const view = getMemoryView();
655
- const buffers = Array.from({ length: iovsLen }, (_, i) => {
656
- const ptr = iovs + i * 8;
657
- const buf = view.getUint32(ptr, true);
658
- const bufLen = view.getUint32(ptr + 4, true);
659
- return new Uint8Array(memory.buffer, buf, bufLen);
660
- });
661
- let written = 0;
662
- let str = "";
663
- for (const buffer of buffers) {
664
- str += decoder.decode(buffer);
665
- written += buffer.byteLength;
666
- }
667
- view.setUint32(nwritten, written, true);
668
- const log = fd === 1 ? stdout : stderr;
669
- log(str);
670
- return 0;
671
- };
672
- const original_fd_filestat_get = wasiImport.fd_filestat_get;
673
- wasiImport.fd_filestat_get = (fd, filestat) => {
674
- if (fd !== 1 && fd !== 2) {
675
- return original_fd_filestat_get(fd, filestat);
676
- }
677
- const view = getMemoryView();
678
- const result = original_fd_filestat_get(fd, filestat);
679
- if (result !== 0) {
680
- return result;
681
- }
682
- const filetypePtr = filestat + 0;
683
- view.setUint8(filetypePtr, 2); // FILETYPE_CHARACTER_DEVICE
684
- return 0;
685
- };
686
- const original_fd_fdstat_get = wasiImport.fd_fdstat_get;
687
- wasiImport.fd_fdstat_get = (fd, fdstat) => {
688
- if (fd !== 1 && fd !== 2) {
689
- return original_fd_fdstat_get(fd, fdstat);
690
- }
691
- const view = getMemoryView();
692
- const fs_filetypePtr = fdstat + 0;
693
- view.setUint8(fs_filetypePtr, 2); // FILETYPE_CHARACTER_DEVICE
694
- const fs_rights_basePtr = fdstat + 8;
695
- view.setBigUint64(fs_rights_basePtr, BigInt(1)); // RIGHTS_FD_WRITE
696
- return 0;
697
- };
698
- },
699
- setMemory(m) {
700
- memory = m;
701
- },
702
- };
703
- }
704
-
705
- /**
706
- * A Ruby VM instance
707
- *
708
- * @example
709
- *
710
- * const wasi = new WASI();
711
- * const vm = new RubyVM();
712
- * const imports = {
713
- * wasi_snapshot_preview1: wasi.wasiImport,
714
- * };
715
- *
716
- * vm.addToImports(imports);
717
- *
718
- * const instance = await WebAssembly.instantiate(rubyModule, imports);
719
- * await vm.setInstance(instance);
720
- * wasi.initialize(instance);
721
- * vm.initialize();
722
- *
723
- */
724
- class RubyVM {
725
- constructor() {
726
- this.instance = null;
727
- this.interfaceState = {
728
- hasJSFrameAfterRbFrame: false,
729
- };
730
- // Wrap exported functions from Ruby VM to prohibit nested VM operation
731
- // if the call stack has sandwitched JS frames like JS -> Ruby -> JS -> Ruby.
732
- const proxyExports = (exports) => {
733
- const excludedMethods = [
734
- "addToImports",
735
- "instantiate",
736
- "rbSetShouldProhibitRewind",
737
- "rbGcDisable",
738
- "rbGcEnable",
739
- ];
740
- const excluded = ["constructor"].concat(excludedMethods);
741
- // wrap all methods in RbAbi.RbAbiGuest class
742
- for (const key of Object.getOwnPropertyNames(RbAbiGuest.prototype)) {
743
- if (excluded.includes(key)) {
744
- continue;
745
- }
746
- const value = exports[key];
747
- if (typeof value === "function") {
748
- exports[key] = (...args) => {
749
- const isNestedVMCall = this.interfaceState.hasJSFrameAfterRbFrame;
750
- if (isNestedVMCall) {
751
- const oldShouldProhibitRewind = this.guest.rbSetShouldProhibitRewind(true);
752
- const oldIsDisabledGc = this.guest.rbGcDisable();
753
- const result = Reflect.apply(value, exports, args);
754
- this.guest.rbSetShouldProhibitRewind(oldShouldProhibitRewind);
755
- if (!oldIsDisabledGc) {
756
- this.guest.rbGcEnable();
757
- }
758
- return result;
759
- }
760
- else {
761
- return Reflect.apply(value, exports, args);
762
- }
763
- };
764
- }
765
- }
766
- return exports;
767
- };
768
- this.guest = proxyExports(new RbAbiGuest());
769
- this.transport = new JsValueTransport();
770
- this.exceptionFormatter = new RbExceptionFormatter();
771
- }
772
- /**
773
- * Initialize the Ruby VM with the given command line arguments
774
- * @param args The command line arguments to pass to Ruby. Must be
775
- * an array of strings starting with the Ruby program name.
776
- */
777
- initialize(args = ["ruby.wasm", "--disable-gems", "-EUTF-8", "-e_=0"]) {
778
- const c_args = args.map((arg) => arg + "\0");
779
- this.guest.rubyInit();
780
- this.guest.rubySysinit(c_args);
781
- this.guest.rubyOptions(c_args);
782
- }
783
- /**
784
- * Set a given instance to interact JavaScript and Ruby's
785
- * WebAssembly instance. This method must be called before calling
786
- * Ruby API.
787
- *
788
- * @param instance The WebAssembly instance to interact with. Must
789
- * be instantiated from a Ruby built with JS extension, and built
790
- * with Reactor ABI instead of command line.
791
- */
792
- async setInstance(instance) {
793
- this.instance = instance;
794
- await this.guest.instantiate(instance);
795
- }
796
- /**
797
- * Add intrinsic import entries, which is necessary to interact JavaScript
798
- * and Ruby's WebAssembly instance.
799
- * @param imports The import object to add to the WebAssembly instance
800
- */
801
- addToImports(imports) {
802
- this.guest.addToImports(imports);
803
- function wrapTry(f) {
804
- return (...args) => {
805
- try {
806
- return { tag: "success", val: f(...args) };
807
- }
808
- catch (e) {
809
- if (e instanceof RbFatalError) {
810
- // RbFatalError should not be caught by Ruby because it Ruby VM
811
- // can be already in an inconsistent state.
812
- throw e;
813
- }
814
- return { tag: "failure", val: e };
815
- }
816
- };
817
- }
818
- imports["rb-js-abi-host"] = {
819
- rb_wasm_throw_prohibit_rewind_exception: (messagePtr, messageLen) => {
820
- const memory = this.instance.exports.memory;
821
- const str = new TextDecoder().decode(new Uint8Array(memory.buffer, messagePtr, messageLen));
822
- throw new RbFatalError("Ruby APIs that may rewind the VM stack are prohibited under nested VM operation " +
823
- `(${str})\n` +
824
- "Nested VM operation means that the call stack has sandwitched JS frames like JS -> Ruby -> JS -> Ruby " +
825
- "caused by something like `window.rubyVM.eval(\"JS.global[:rubyVM].eval('Fiber.yield')\")`\n" +
826
- "\n" +
827
- "Please check your call stack and make sure that you are **not** doing any of the following inside the nested Ruby frame:\n" +
828
- " 1. Switching fibers (e.g. Fiber#resume, Fiber.yield, and Fiber#transfer)\n" +
829
- " Note that `evalAsync` JS API switches fibers internally\n" +
830
- " 2. Raising uncaught exceptions\n" +
831
- " Please catch all exceptions inside the nested operation\n" +
832
- " 3. Calling Continuation APIs\n");
833
- },
834
- };
835
- // NOTE: The GC may collect objects that are still referenced by Wasm
836
- // locals because Asyncify cannot scan the Wasm stack above the JS frame.
837
- // So we need to keep track whether the JS frame is sandwitched by Ruby
838
- // frames or not, and prohibit nested VM operation if it is.
839
- const proxyImports = (imports) => {
840
- for (const [key, value] of Object.entries(imports)) {
841
- if (typeof value === "function") {
842
- imports[key] = (...args) => {
843
- const oldValue = this.interfaceState.hasJSFrameAfterRbFrame;
844
- this.interfaceState.hasJSFrameAfterRbFrame = true;
845
- const result = Reflect.apply(value, imports, args);
846
- this.interfaceState.hasJSFrameAfterRbFrame = oldValue;
847
- return result;
848
- };
849
- }
850
- }
851
- return imports;
852
- };
853
- addRbJsAbiHostToImports(imports, proxyImports({
854
- evalJs: wrapTry((code) => {
855
- return Function(code)();
856
- }),
857
- isJs: (value) => {
858
- // Just for compatibility with the old JS API
859
- return true;
860
- },
861
- globalThis: () => {
862
- if (typeof globalThis !== "undefined") {
863
- return globalThis;
864
- }
865
- else if (typeof global !== "undefined") {
866
- return global;
867
- }
868
- else if (typeof window !== "undefined") {
869
- return window;
870
- }
871
- throw new Error("unable to locate global object");
872
- },
873
- intToJsNumber: (value) => {
874
- return value;
875
- },
876
- floatToJsNumber: (value) => {
877
- return value;
878
- },
879
- stringToJsString: (value) => {
880
- return value;
881
- },
882
- boolToJsBool: (value) => {
883
- return value;
884
- },
885
- procToJsFunction: (rawRbAbiValue) => {
886
- const rbValue = this.rbValueOfPointer(rawRbAbiValue);
887
- return (...args) => {
888
- rbValue.call("call", ...args.map((arg) => this.wrap(arg)));
889
- };
890
- },
891
- rbObjectToJsRbValue: (rawRbAbiValue) => {
892
- return this.rbValueOfPointer(rawRbAbiValue);
893
- },
894
- jsValueToString: (value) => {
895
- // According to the [spec](https://tc39.es/ecma262/multipage/text-processing.html#sec-string-constructor-string-value)
896
- // `String(value)` always returns a string.
897
- return String(value);
898
- },
899
- jsValueToInteger(value) {
900
- if (typeof value === "number") {
901
- return { tag: "f64", val: value };
902
- }
903
- else if (typeof value === "bigint") {
904
- return { tag: "bignum", val: BigInt(value).toString(10) + "\0" };
905
- }
906
- else if (typeof value === "string") {
907
- return { tag: "bignum", val: value + "\0" };
908
- }
909
- else if (typeof value === "undefined") {
910
- return { tag: "f64", val: 0 };
911
- }
912
- else {
913
- return { tag: "f64", val: Number(value) };
914
- }
915
- },
916
- exportJsValueToHost: (value) => {
917
- // See `JsValueExporter` for the reason why we need to do this
918
- this.transport.takeJsValue(value);
919
- },
920
- importJsValueFromHost: () => {
921
- return this.transport.consumeJsValue();
922
- },
923
- instanceOf: (value, klass) => {
924
- if (typeof klass === "function") {
925
- return value instanceof klass;
926
- }
927
- else {
928
- return false;
929
- }
930
- },
931
- jsValueTypeof(value) {
932
- return typeof value;
933
- },
934
- jsValueEqual(lhs, rhs) {
935
- return lhs == rhs;
936
- },
937
- jsValueStrictlyEqual(lhs, rhs) {
938
- return lhs === rhs;
939
- },
940
- reflectApply: wrapTry((target, thisArgument, args) => {
941
- return Reflect.apply(target, thisArgument, args);
942
- }),
943
- reflectConstruct: function (target, args) {
944
- throw new Error("Function not implemented.");
945
- },
946
- reflectDeleteProperty: function (target, propertyKey) {
947
- throw new Error("Function not implemented.");
948
- },
949
- reflectGet: wrapTry((target, propertyKey) => {
950
- return target[propertyKey];
951
- }),
952
- reflectGetOwnPropertyDescriptor: function (target, propertyKey) {
953
- throw new Error("Function not implemented.");
954
- },
955
- reflectGetPrototypeOf: function (target) {
956
- throw new Error("Function not implemented.");
957
- },
958
- reflectHas: function (target, propertyKey) {
959
- throw new Error("Function not implemented.");
960
- },
961
- reflectIsExtensible: function (target) {
962
- throw new Error("Function not implemented.");
963
- },
964
- reflectOwnKeys: function (target) {
965
- throw new Error("Function not implemented.");
966
- },
967
- reflectPreventExtensions: function (target) {
968
- throw new Error("Function not implemented.");
969
- },
970
- reflectSet: wrapTry((target, propertyKey, value) => {
971
- return Reflect.set(target, propertyKey, value);
972
- }),
973
- reflectSetPrototypeOf: function (target, prototype) {
974
- throw new Error("Function not implemented.");
975
- },
976
- }), (name) => {
977
- return this.instance.exports[name];
978
- });
274
+ rubyOptions(arg0) {
275
+ const memory = this._exports.memory;
276
+ const realloc = this._exports["cabi_realloc"];
277
+ const vec1 = arg0;
278
+ const len1 = vec1.length;
279
+ const result1 = realloc(0, 0, 4, len1 * 8);
280
+ for (let i = 0; i < vec1.length; i++) {
281
+ const e = vec1[i];
282
+ const base = result1 + i * 8;
283
+ const ptr0 = utf8_encode(e, realloc, memory);
284
+ const len0 = UTF8_ENCODED_LEN;
285
+ data_view(memory).setInt32(base + 4, len0, true);
286
+ data_view(memory).setInt32(base + 0, ptr0, true);
287
+ }
288
+ const ret = this._exports['ruby-options: func(args: list<string>) -> handle<rb-iseq>'](result1, len1);
289
+ return this._resource0_slab.remove(ret);
979
290
  }
980
- /**
981
- * Print the Ruby version to stdout
982
- */
983
- printVersion() {
984
- this.guest.rubyShowVersion();
291
+ rubyScript(arg0) {
292
+ const memory = this._exports.memory;
293
+ const realloc = this._exports["cabi_realloc"];
294
+ const ptr0 = utf8_encode(arg0, realloc, memory);
295
+ const len0 = UTF8_ENCODED_LEN;
296
+ this._exports['ruby-script: func(name: string) -> ()'](ptr0, len0);
985
297
  }
986
- /**
987
- * Runs a string of Ruby code from JavaScript
988
- * @param code The Ruby code to run
989
- * @returns the result of the last expression
990
- *
991
- * @example
992
- * vm.eval("puts 'hello world'");
993
- * const result = vm.eval("1 + 2");
994
- * console.log(result.toString()); // 3
995
- *
996
- */
997
- eval(code) {
998
- return evalRbCode(this, this.privateObject(), code);
298
+ rubyInitLoadpath() {
299
+ this._exports['ruby-init-loadpath: func() -> ()']();
999
300
  }
1000
- /**
1001
- * Runs a string of Ruby code with top-level `JS::Object#await`
1002
- * Returns a promise that resolves when execution completes.
1003
- * @param code The Ruby code to run
1004
- * @returns a promise that resolves to the result of the last expression
1005
- *
1006
- * @example
1007
- * const text = await vm.evalAsync(`
1008
- * require 'js'
1009
- * response = JS.global.fetch('https://example.com').await
1010
- * response.text.await
1011
- * `);
1012
- * console.log(text.toString()); // <html>...</html>
1013
- */
1014
- evalAsync(code) {
1015
- const JS = this.eval("require 'js'; JS");
1016
- return new Promise((resolve, reject) => {
1017
- JS.call("__eval_async_rb", this.wrap(code), this.wrap({
1018
- resolve,
1019
- reject: (error) => {
1020
- reject(new RbError(this.exceptionFormatter.format(error, this, this.privateObject())));
1021
- },
1022
- }));
1023
- });
301
+ rbEvalStringProtect(arg0) {
302
+ const memory = this._exports.memory;
303
+ const realloc = this._exports["cabi_realloc"];
304
+ const ptr0 = utf8_encode(arg0, realloc, memory);
305
+ const len0 = UTF8_ENCODED_LEN;
306
+ const ret = this._exports['rb-eval-string-protect: func(str: string) -> tuple<handle<rb-abi-value>, s32>'](ptr0, len0);
307
+ return [this._resource1_slab.remove(data_view(memory).getInt32(ret + 0, true)), data_view(memory).getInt32(ret + 4, true)];
1024
308
  }
1025
- /**
1026
- * Wrap a JavaScript value into a Ruby JS::Object
1027
- * @param value The value to convert to RbValue
1028
- * @returns the RbValue object representing the given JS value
1029
- *
1030
- * @example
1031
- * const hash = vm.eval(`Hash.new`)
1032
- * hash.call("store", vm.eval(`"key1"`), vm.wrap(new Object()));
1033
- */
1034
- wrap(value) {
1035
- return this.transport.importJsValue(value, this);
309
+ rbFuncallvProtect(arg0, arg1, arg2) {
310
+ const memory = this._exports.memory;
311
+ const realloc = this._exports["cabi_realloc"];
312
+ const obj0 = arg0;
313
+ if (!(obj0 instanceof RbAbiValue)) throw new TypeError('expected instance of RbAbiValue');
314
+ const vec2 = arg2;
315
+ const len2 = vec2.length;
316
+ const result2 = realloc(0, 0, 4, len2 * 4);
317
+ for (let i = 0; i < vec2.length; i++) {
318
+ const e = vec2[i];
319
+ const base = result2 + i * 4;
320
+ const obj1 = e;
321
+ if (!(obj1 instanceof RbAbiValue)) throw new TypeError('expected instance of RbAbiValue');
322
+ data_view(memory).setInt32(base + 0, this._resource1_slab.insert(obj1.clone()), true);
323
+ }
324
+ const ret = this._exports['rb-funcallv-protect: func(recv: handle<rb-abi-value>, mid: u32, args: list<handle<rb-abi-value>>) -> tuple<handle<rb-abi-value>, s32>'](this._resource1_slab.insert(obj0.clone()), to_uint32(arg1), result2, len2);
325
+ return [this._resource1_slab.remove(data_view(memory).getInt32(ret + 0, true)), data_view(memory).getInt32(ret + 4, true)];
1036
326
  }
1037
- /** @private */
1038
- privateObject() {
1039
- return {
1040
- transport: this.transport,
1041
- exceptionFormatter: this.exceptionFormatter,
1042
- };
327
+ rbIntern(arg0) {
328
+ const memory = this._exports.memory;
329
+ const realloc = this._exports["cabi_realloc"];
330
+ const ptr0 = utf8_encode(arg0, realloc, memory);
331
+ const len0 = UTF8_ENCODED_LEN;
332
+ const ret = this._exports['rb-intern: func(name: string) -> u32'](ptr0, len0);
333
+ return ret >>> 0;
1043
334
  }
1044
- /** @private */
1045
- rbValueOfPointer(pointer) {
1046
- const abiValue = new RbAbiValue(pointer, this.guest);
1047
- return new RbValue(abiValue, this, this.privateObject());
335
+ rbErrinfo() {
336
+ const ret = this._exports['rb-errinfo: func() -> handle<rb-abi-value>']();
337
+ return this._resource1_slab.remove(ret);
1048
338
  }
1049
- }
1050
- /**
1051
- * Export a JS value held by the Ruby VM to the JS environment.
1052
- * This is implemented in a dirty way since wit cannot reference resources
1053
- * defined in other interfaces.
1054
- * In our case, we can't express `function(v: rb-abi-value) -> js-abi-value`
1055
- * because `rb-js-abi-host.wit`, that defines `js-abi-value`, is implemented
1056
- * by embedder side (JS) but `rb-abi-guest.wit`, that defines `rb-abi-value`
1057
- * is implemented by guest side (Wasm).
1058
- *
1059
- * This class is a helper to export by:
1060
- * 1. Call `function __export_to_js(v: rb-abi-value)` defined in guest from embedder side.
1061
- * 2. Call `function takeJsValue(v: js-abi-value)` defined in embedder from guest side with
1062
- * underlying JS value of given `rb-abi-value`.
1063
- * 3. Then `takeJsValue` implementation escapes the given JS value to the `_takenJsValues`
1064
- * stored in embedder side.
1065
- * 4. Finally, embedder side can take `_takenJsValues`.
1066
- *
1067
- * Note that `exportJsValue` is not reentrant.
1068
- *
1069
- * @private
1070
- */
1071
- class JsValueTransport {
1072
- constructor() {
1073
- this._takenJsValue = null;
339
+ rbClearErrinfo() {
340
+ this._exports['rb-clear-errinfo: func() -> ()']();
1074
341
  }
1075
- takeJsValue(value) {
1076
- this._takenJsValue = value;
342
+ rstringPtr(arg0) {
343
+ const memory = this._exports.memory;
344
+ const obj0 = arg0;
345
+ if (!(obj0 instanceof RbAbiValue)) throw new TypeError('expected instance of RbAbiValue');
346
+ const ret = this._exports['rstring-ptr: func(value: handle<rb-abi-value>) -> string'](this._resource1_slab.insert(obj0.clone()));
347
+ const ptr1 = data_view(memory).getInt32(ret + 0, true);
348
+ const len1 = data_view(memory).getInt32(ret + 4, true);
349
+ const result1 = UTF8_DECODER.decode(new Uint8Array(memory.buffer, ptr1, len1));
350
+ this._exports["cabi_post_rstring-ptr"](ret);
351
+ return result1;
1077
352
  }
1078
- consumeJsValue() {
1079
- return this._takenJsValue;
353
+ rbVmBugreport() {
354
+ this._exports['rb-vm-bugreport: func() -> ()']();
1080
355
  }
1081
- exportJsValue(value) {
1082
- value.call("__export_to_js");
1083
- return this._takenJsValue;
356
+ rbGcEnable() {
357
+ const ret = this._exports['rb-gc-enable: func() -> bool']();
358
+ const bool0 = ret;
359
+ return bool0 == 0 ? false : (bool0 == 1 ? true : throw_invalid_bool());
1084
360
  }
1085
- importJsValue(value, vm) {
1086
- this._takenJsValue = value;
1087
- return vm.eval('require "js"; JS::Object').call("__import_from_js");
361
+ rbGcDisable() {
362
+ const ret = this._exports['rb-gc-disable: func() -> bool']();
363
+ const bool0 = ret;
364
+ return bool0 == 0 ? false : (bool0 == 1 ? true : throw_invalid_bool());
1088
365
  }
1089
- }
1090
- /**
1091
- * A RbValue is an object that represents a value in Ruby
1092
- */
1093
- class RbValue {
1094
- /**
1095
- * @hideconstructor
1096
- */
1097
- constructor(inner, vm, privateObject) {
1098
- this.inner = inner;
1099
- this.vm = vm;
1100
- this.privateObject = privateObject;
366
+ rbSetShouldProhibitRewind(arg0) {
367
+ const ret = this._exports['rb-set-should-prohibit-rewind: func(new-value: bool) -> bool'](arg0 ? 1 : 0);
368
+ const bool0 = ret;
369
+ return bool0 == 0 ? false : (bool0 == 1 ? true : throw_invalid_bool());
1101
370
  }
1102
- /**
1103
- * Call a given method with given arguments
1104
- *
1105
- * @param callee name of the Ruby method to call
1106
- * @param args arguments to pass to the method. Must be an array of RbValue
1107
- *
1108
- * @example
1109
- * const ary = vm.eval("[1, 2, 3]");
1110
- * ary.call("push", 4);
1111
- * console.log(ary.call("sample").toString());
1112
- *
1113
- */
1114
- call(callee, ...args) {
1115
- const innerArgs = args.map((arg) => arg.inner);
1116
- return new RbValue(callRbMethod(this.vm, this.privateObject, this.inner, callee, innerArgs), this.vm, this.privateObject);
371
+ }
372
+
373
+ class RbIseq {
374
+ constructor(wasm_val, obj) {
375
+ this._wasm_val = wasm_val;
376
+ this._obj = obj;
377
+ this._refcnt = 1;
378
+ obj._registry0.register(this, wasm_val, this);
1117
379
  }
1118
- /**
1119
- * @see {@link https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Global_Objects/Symbol/toPrimitive}
1120
- * @param hint Preferred type of the result primitive value. `"number"`, `"string"`, or `"default"`.
1121
- */
1122
- [Symbol.toPrimitive](hint) {
1123
- if (hint === "string" || hint === "default") {
1124
- return this.toString();
1125
- }
1126
- else if (hint === "number") {
1127
- return null;
1128
- }
1129
- return null;
380
+
381
+ clone() {
382
+ this._refcnt += 1;
383
+ return this;
1130
384
  }
1131
- /**
1132
- * Returns a string representation of the value by calling `to_s`
1133
- */
1134
- toString() {
1135
- const rbString = callRbMethod(this.vm, this.privateObject, this.inner, "to_s", []);
1136
- return this.vm.guest.rstringPtr(rbString);
385
+
386
+ drop() {
387
+ this._refcnt -= 1;
388
+ if (this._refcnt !== 0)
389
+ return;
390
+ this._obj._registry0.unregister(this);
391
+ const dtor = this._obj._exports['canonical_abi_drop_rb-iseq'];
392
+ const wasm_val = this._wasm_val;
393
+ delete this._obj;
394
+ delete this._refcnt;
395
+ delete this._wasm_val;
396
+ dtor(wasm_val);
1137
397
  }
1138
- /**
1139
- * Returns a JavaScript object representation of the value
1140
- * by calling `to_js`.
1141
- *
1142
- * Returns null if the value is not convertible to a JavaScript object.
1143
- */
1144
- toJS() {
1145
- const JS = this.vm.eval("JS");
1146
- const jsValue = JS.call("try_convert", this);
1147
- if (jsValue.call("nil?").toString() === "true") {
1148
- return null;
1149
- }
1150
- return this.privateObject.transport.exportJsValue(jsValue);
398
+ }
399
+
400
+ class RbAbiValue {
401
+ constructor(wasm_val, obj) {
402
+ this._wasm_val = wasm_val;
403
+ this._obj = obj;
404
+ this._refcnt = 1;
405
+ obj._registry1.register(this, wasm_val, this);
1151
406
  }
1152
- }
1153
- var ruby_tag_type;
1154
- (function (ruby_tag_type) {
1155
- ruby_tag_type[ruby_tag_type["None"] = 0] = "None";
1156
- ruby_tag_type[ruby_tag_type["Return"] = 1] = "Return";
1157
- ruby_tag_type[ruby_tag_type["Break"] = 2] = "Break";
1158
- ruby_tag_type[ruby_tag_type["Next"] = 3] = "Next";
1159
- ruby_tag_type[ruby_tag_type["Retry"] = 4] = "Retry";
1160
- ruby_tag_type[ruby_tag_type["Redo"] = 5] = "Redo";
1161
- ruby_tag_type[ruby_tag_type["Raise"] = 6] = "Raise";
1162
- ruby_tag_type[ruby_tag_type["Throw"] = 7] = "Throw";
1163
- ruby_tag_type[ruby_tag_type["Fatal"] = 8] = "Fatal";
1164
- ruby_tag_type[ruby_tag_type["Mask"] = 15] = "Mask";
1165
- })(ruby_tag_type || (ruby_tag_type = {}));
1166
- class RbExceptionFormatter {
1167
- constructor() {
1168
- this.literalsCache = null;
1169
- this.isFormmatting = false;
407
+
408
+ clone() {
409
+ this._refcnt += 1;
410
+ return this;
1170
411
  }
1171
- format(error, vm, privateObject) {
1172
- // All Ruby exceptions raised during formatting exception message should
1173
- // be caught and return a fallback message.
1174
- // Therefore, we don't need to worry about infinite recursion here ideally
1175
- // but checking re-entrancy just in case.
1176
- class RbExceptionFormatterError extends Error {
1177
- }
1178
- if (this.isFormmatting) {
1179
- throw new RbExceptionFormatterError("Unexpected exception occurred during formatting exception message");
1180
- }
1181
- this.isFormmatting = true;
1182
- try {
1183
- return this._format(error, vm, privateObject);
1184
- }
1185
- finally {
1186
- this.isFormmatting = false;
1187
- }
412
+
413
+ drop() {
414
+ this._refcnt -= 1;
415
+ if (this._refcnt !== 0)
416
+ return;
417
+ this._obj._registry1.unregister(this);
418
+ const dtor = this._obj._exports['canonical_abi_drop_rb-abi-value'];
419
+ const wasm_val = this._wasm_val;
420
+ delete this._obj;
421
+ delete this._refcnt;
422
+ delete this._wasm_val;
423
+ dtor(wasm_val);
1188
424
  }
1189
- _format(error, vm, privateObject) {
1190
- const [zeroLiteral, oneLiteral, newLineLiteral] = (() => {
1191
- if (this.literalsCache == null) {
1192
- const zeroOneNewLine = [
1193
- evalRbCode(vm, privateObject, "0"),
1194
- evalRbCode(vm, privateObject, "1"),
1195
- evalRbCode(vm, privateObject, `"\n"`),
1196
- ];
1197
- this.literalsCache = zeroOneNewLine;
1198
- return zeroOneNewLine;
1199
- }
1200
- else {
1201
- return this.literalsCache;
1202
- }
1203
- })();
1204
- let className;
1205
- let backtrace;
1206
- let message;
1207
- try {
1208
- className = error.call("class").toString();
1209
- }
1210
- catch (e) {
1211
- className = "unknown";
1212
- }
1213
- try {
1214
- message = error.toString();
1215
- }
1216
- catch (e) {
1217
- message = "unknown";
425
+ }
426
+
427
+ function addRbJsAbiHostToImports(imports, obj, get_export) {
428
+ if (!("rb-js-abi-host" in imports)) imports["rb-js-abi-host"] = {};
429
+ imports["rb-js-abi-host"]["eval-js: func(code: string) -> variant { success(handle<js-abi-value>), failure(handle<js-abi-value>) }"] = function(arg0, arg1, arg2) {
430
+ const memory = get_export("memory");
431
+ const ptr0 = arg0;
432
+ const len0 = arg1;
433
+ const result0 = UTF8_DECODER.decode(new Uint8Array(memory.buffer, ptr0, len0));
434
+ const ret0 = obj.evalJs(result0);
435
+ const variant1 = ret0;
436
+ switch (variant1.tag) {
437
+ case "success": {
438
+ const e = variant1.val;
439
+ data_view(memory).setInt8(arg2 + 0, 0, true);
440
+ data_view(memory).setInt32(arg2 + 4, resources0.insert(e), true);
441
+ break;
1218
442
  }
1219
- try {
1220
- backtrace = error.call("backtrace");
443
+ case "failure": {
444
+ const e = variant1.val;
445
+ data_view(memory).setInt8(arg2 + 0, 1, true);
446
+ data_view(memory).setInt32(arg2 + 4, resources0.insert(e), true);
447
+ break;
1221
448
  }
1222
- catch (e) {
1223
- return this.formatString(className, message);
449
+ default:
450
+ throw new RangeError("invalid variant specified for JsAbiResult");
451
+ }
452
+ };
453
+ imports["rb-js-abi-host"]["is-js: func(value: handle<js-abi-value>) -> bool"] = function(arg0) {
454
+ const ret0 = obj.isJs(resources0.get(arg0));
455
+ return ret0 ? 1 : 0;
456
+ };
457
+ imports["rb-js-abi-host"]["instance-of: func(value: handle<js-abi-value>, klass: handle<js-abi-value>) -> bool"] = function(arg0, arg1) {
458
+ const ret0 = obj.instanceOf(resources0.get(arg0), resources0.get(arg1));
459
+ return ret0 ? 1 : 0;
460
+ };
461
+ imports["rb-js-abi-host"]["global-this: func() -> handle<js-abi-value>"] = function() {
462
+ const ret0 = obj.globalThis();
463
+ return resources0.insert(ret0);
464
+ };
465
+ imports["rb-js-abi-host"]["int-to-js-number: func(value: s32) -> handle<js-abi-value>"] = function(arg0) {
466
+ const ret0 = obj.intToJsNumber(arg0);
467
+ return resources0.insert(ret0);
468
+ };
469
+ imports["rb-js-abi-host"]["float-to-js-number: func(value: float64) -> handle<js-abi-value>"] = function(arg0) {
470
+ const ret0 = obj.floatToJsNumber(arg0);
471
+ return resources0.insert(ret0);
472
+ };
473
+ imports["rb-js-abi-host"]["string-to-js-string: func(value: string) -> handle<js-abi-value>"] = function(arg0, arg1) {
474
+ const memory = get_export("memory");
475
+ const ptr0 = arg0;
476
+ const len0 = arg1;
477
+ const result0 = UTF8_DECODER.decode(new Uint8Array(memory.buffer, ptr0, len0));
478
+ const ret0 = obj.stringToJsString(result0);
479
+ return resources0.insert(ret0);
480
+ };
481
+ imports["rb-js-abi-host"]["bool-to-js-bool: func(value: bool) -> handle<js-abi-value>"] = function(arg0) {
482
+ const bool0 = arg0;
483
+ const ret0 = obj.boolToJsBool(bool0 == 0 ? false : (bool0 == 1 ? true : throw_invalid_bool()));
484
+ return resources0.insert(ret0);
485
+ };
486
+ imports["rb-js-abi-host"]["proc-to-js-function: func(value: u32) -> handle<js-abi-value>"] = function(arg0) {
487
+ const ret0 = obj.procToJsFunction(arg0 >>> 0);
488
+ return resources0.insert(ret0);
489
+ };
490
+ imports["rb-js-abi-host"]["rb-object-to-js-rb-value: func(raw-rb-abi-value: u32) -> handle<js-abi-value>"] = function(arg0) {
491
+ const ret0 = obj.rbObjectToJsRbValue(arg0 >>> 0);
492
+ return resources0.insert(ret0);
493
+ };
494
+ imports["rb-js-abi-host"]["js-value-to-string: func(value: handle<js-abi-value>) -> string"] = function(arg0, arg1) {
495
+ const memory = get_export("memory");
496
+ const realloc = get_export("cabi_realloc");
497
+ const ret0 = obj.jsValueToString(resources0.get(arg0));
498
+ const ptr0 = utf8_encode(ret0, realloc, memory);
499
+ const len0 = UTF8_ENCODED_LEN;
500
+ data_view(memory).setInt32(arg1 + 4, len0, true);
501
+ data_view(memory).setInt32(arg1 + 0, ptr0, true);
502
+ };
503
+ imports["rb-js-abi-host"]["js-value-to-integer: func(value: handle<js-abi-value>) -> variant { f64(float64), bignum(string) }"] = function(arg0, arg1) {
504
+ const memory = get_export("memory");
505
+ const realloc = get_export("cabi_realloc");
506
+ const ret0 = obj.jsValueToInteger(resources0.get(arg0));
507
+ const variant1 = ret0;
508
+ switch (variant1.tag) {
509
+ case "f64": {
510
+ const e = variant1.val;
511
+ data_view(memory).setInt8(arg1 + 0, 0, true);
512
+ data_view(memory).setFloat64(arg1 + 8, +e, true);
513
+ break;
1224
514
  }
1225
- if (backtrace.call("nil?").toString() === "true") {
1226
- return this.formatString(className, message);
515
+ case "bignum": {
516
+ const e = variant1.val;
517
+ data_view(memory).setInt8(arg1 + 0, 1, true);
518
+ const ptr0 = utf8_encode(e, realloc, memory);
519
+ const len0 = UTF8_ENCODED_LEN;
520
+ data_view(memory).setInt32(arg1 + 12, len0, true);
521
+ data_view(memory).setInt32(arg1 + 8, ptr0, true);
522
+ break;
1227
523
  }
1228
- try {
1229
- const firstLine = backtrace.call("at", zeroLiteral);
1230
- const restLines = backtrace
1231
- .call("drop", oneLiteral)
1232
- .call("join", newLineLiteral);
1233
- return this.formatString(className, message, [
1234
- firstLine.toString(),
1235
- restLines.toString(),
1236
- ]);
524
+ default:
525
+ throw new RangeError("invalid variant specified for RawInteger");
526
+ }
527
+ };
528
+ imports["rb-js-abi-host"]["export-js-value-to-host: func(value: handle<js-abi-value>) -> ()"] = function(arg0) {
529
+ obj.exportJsValueToHost(resources0.get(arg0));
530
+ };
531
+ imports["rb-js-abi-host"]["import-js-value-from-host: func() -> handle<js-abi-value>"] = function() {
532
+ const ret0 = obj.importJsValueFromHost();
533
+ return resources0.insert(ret0);
534
+ };
535
+ imports["rb-js-abi-host"]["js-value-typeof: func(value: handle<js-abi-value>) -> string"] = function(arg0, arg1) {
536
+ const memory = get_export("memory");
537
+ const realloc = get_export("cabi_realloc");
538
+ const ret0 = obj.jsValueTypeof(resources0.get(arg0));
539
+ const ptr0 = utf8_encode(ret0, realloc, memory);
540
+ const len0 = UTF8_ENCODED_LEN;
541
+ data_view(memory).setInt32(arg1 + 4, len0, true);
542
+ data_view(memory).setInt32(arg1 + 0, ptr0, true);
543
+ };
544
+ imports["rb-js-abi-host"]["js-value-equal: func(lhs: handle<js-abi-value>, rhs: handle<js-abi-value>) -> bool"] = function(arg0, arg1) {
545
+ const ret0 = obj.jsValueEqual(resources0.get(arg0), resources0.get(arg1));
546
+ return ret0 ? 1 : 0;
547
+ };
548
+ imports["rb-js-abi-host"]["js-value-strictly-equal: func(lhs: handle<js-abi-value>, rhs: handle<js-abi-value>) -> bool"] = function(arg0, arg1) {
549
+ const ret0 = obj.jsValueStrictlyEqual(resources0.get(arg0), resources0.get(arg1));
550
+ return ret0 ? 1 : 0;
551
+ };
552
+ imports["rb-js-abi-host"]["reflect-apply: func(target: handle<js-abi-value>, this-argument: handle<js-abi-value>, arguments: list<handle<js-abi-value>>) -> variant { success(handle<js-abi-value>), failure(handle<js-abi-value>) }"] = function(arg0, arg1, arg2, arg3, arg4) {
553
+ const memory = get_export("memory");
554
+ const len0 = arg3;
555
+ const base0 = arg2;
556
+ const result0 = [];
557
+ for (let i = 0; i < len0; i++) {
558
+ const base = base0 + i * 4;
559
+ result0.push(resources0.get(data_view(memory).getInt32(base + 0, true)));
560
+ }
561
+ const ret0 = obj.reflectApply(resources0.get(arg0), resources0.get(arg1), result0);
562
+ const variant1 = ret0;
563
+ switch (variant1.tag) {
564
+ case "success": {
565
+ const e = variant1.val;
566
+ data_view(memory).setInt8(arg4 + 0, 0, true);
567
+ data_view(memory).setInt32(arg4 + 4, resources0.insert(e), true);
568
+ break;
1237
569
  }
1238
- catch (e) {
1239
- return this.formatString(className, message);
570
+ case "failure": {
571
+ const e = variant1.val;
572
+ data_view(memory).setInt8(arg4 + 0, 1, true);
573
+ data_view(memory).setInt32(arg4 + 4, resources0.insert(e), true);
574
+ break;
1240
575
  }
1241
- }
1242
- formatString(klass, message, backtrace) {
1243
- if (backtrace) {
1244
- return `${backtrace[0]}: ${message} (${klass})\n${backtrace[1]}`;
576
+ default:
577
+ throw new RangeError("invalid variant specified for JsAbiResult");
578
+ }
579
+ };
580
+ imports["rb-js-abi-host"]["reflect-construct: func(target: handle<js-abi-value>, arguments: list<handle<js-abi-value>>) -> handle<js-abi-value>"] = function(arg0, arg1, arg2) {
581
+ const memory = get_export("memory");
582
+ const len0 = arg2;
583
+ const base0 = arg1;
584
+ const result0 = [];
585
+ for (let i = 0; i < len0; i++) {
586
+ const base = base0 + i * 4;
587
+ result0.push(resources0.get(data_view(memory).getInt32(base + 0, true)));
588
+ }
589
+ const ret0 = obj.reflectConstruct(resources0.get(arg0), result0);
590
+ return resources0.insert(ret0);
591
+ };
592
+ imports["rb-js-abi-host"]["reflect-delete-property: func(target: handle<js-abi-value>, property-key: string) -> bool"] = function(arg0, arg1, arg2) {
593
+ const memory = get_export("memory");
594
+ const ptr0 = arg1;
595
+ const len0 = arg2;
596
+ const result0 = UTF8_DECODER.decode(new Uint8Array(memory.buffer, ptr0, len0));
597
+ const ret0 = obj.reflectDeleteProperty(resources0.get(arg0), result0);
598
+ return ret0 ? 1 : 0;
599
+ };
600
+ imports["rb-js-abi-host"]["reflect-get: func(target: handle<js-abi-value>, property-key: string) -> variant { success(handle<js-abi-value>), failure(handle<js-abi-value>) }"] = function(arg0, arg1, arg2, arg3) {
601
+ const memory = get_export("memory");
602
+ const ptr0 = arg1;
603
+ const len0 = arg2;
604
+ const result0 = UTF8_DECODER.decode(new Uint8Array(memory.buffer, ptr0, len0));
605
+ const ret0 = obj.reflectGet(resources0.get(arg0), result0);
606
+ const variant1 = ret0;
607
+ switch (variant1.tag) {
608
+ case "success": {
609
+ const e = variant1.val;
610
+ data_view(memory).setInt8(arg3 + 0, 0, true);
611
+ data_view(memory).setInt32(arg3 + 4, resources0.insert(e), true);
612
+ break;
1245
613
  }
1246
- else {
1247
- return `${klass}: ${message}`;
614
+ case "failure": {
615
+ const e = variant1.val;
616
+ data_view(memory).setInt8(arg3 + 0, 1, true);
617
+ data_view(memory).setInt32(arg3 + 4, resources0.insert(e), true);
618
+ break;
1248
619
  }
1249
- }
1250
- }
1251
- const checkStatusTag = (rawTag, vm, privateObject) => {
1252
- switch (rawTag & ruby_tag_type.Mask) {
1253
- case ruby_tag_type.None:
1254
- break;
1255
- case ruby_tag_type.Return:
1256
- throw new RbError("unexpected return");
1257
- case ruby_tag_type.Next:
1258
- throw new RbError("unexpected next");
1259
- case ruby_tag_type.Break:
1260
- throw new RbError("unexpected break");
1261
- case ruby_tag_type.Redo:
1262
- throw new RbError("unexpected redo");
1263
- case ruby_tag_type.Retry:
1264
- throw new RbError("retry outside of rescue clause");
1265
- case ruby_tag_type.Throw:
1266
- throw new RbError("unexpected throw");
1267
- case ruby_tag_type.Raise:
1268
- case ruby_tag_type.Fatal:
1269
- const error = new RbValue(vm.guest.rbErrinfo(), vm, privateObject);
1270
- if (error.call("nil?").toString() === "true") {
1271
- throw new RbError("no exception object");
1272
- }
1273
- // clear errinfo if got exception due to no rb_jump_tag
1274
- vm.guest.rbClearErrinfo();
1275
- throw new RbError(privateObject.exceptionFormatter.format(error, vm, privateObject));
1276
620
  default:
1277
- throw new RbError(`unknown error tag: ${rawTag}`);
1278
- }
1279
- };
1280
- function wrapRbOperation(vm, body) {
1281
- try {
1282
- return body();
1283
- }
1284
- catch (e) {
1285
- if (e instanceof RbError) {
1286
- throw e;
1287
- }
1288
- // All JS exceptions triggered by Ruby code are translated to Ruby exceptions,
1289
- // so non-RbError exceptions are unexpected.
1290
- vm.guest.rbVmBugreport();
1291
- if (e instanceof WebAssembly.RuntimeError && e.message === "unreachable") {
1292
- const error = new RbError(`Something went wrong in Ruby VM: ${e}`);
1293
- error.stack = e.stack;
1294
- throw error;
621
+ throw new RangeError("invalid variant specified for JsAbiResult");
622
+ }
623
+ };
624
+ imports["rb-js-abi-host"]["reflect-get-own-property-descriptor: func(target: handle<js-abi-value>, property-key: string) -> handle<js-abi-value>"] = function(arg0, arg1, arg2) {
625
+ const memory = get_export("memory");
626
+ const ptr0 = arg1;
627
+ const len0 = arg2;
628
+ const result0 = UTF8_DECODER.decode(new Uint8Array(memory.buffer, ptr0, len0));
629
+ const ret0 = obj.reflectGetOwnPropertyDescriptor(resources0.get(arg0), result0);
630
+ return resources0.insert(ret0);
631
+ };
632
+ imports["rb-js-abi-host"]["reflect-get-prototype-of: func(target: handle<js-abi-value>) -> handle<js-abi-value>"] = function(arg0) {
633
+ const ret0 = obj.reflectGetPrototypeOf(resources0.get(arg0));
634
+ return resources0.insert(ret0);
635
+ };
636
+ imports["rb-js-abi-host"]["reflect-has: func(target: handle<js-abi-value>, property-key: string) -> bool"] = function(arg0, arg1, arg2) {
637
+ const memory = get_export("memory");
638
+ const ptr0 = arg1;
639
+ const len0 = arg2;
640
+ const result0 = UTF8_DECODER.decode(new Uint8Array(memory.buffer, ptr0, len0));
641
+ const ret0 = obj.reflectHas(resources0.get(arg0), result0);
642
+ return ret0 ? 1 : 0;
643
+ };
644
+ imports["rb-js-abi-host"]["reflect-is-extensible: func(target: handle<js-abi-value>) -> bool"] = function(arg0) {
645
+ const ret0 = obj.reflectIsExtensible(resources0.get(arg0));
646
+ return ret0 ? 1 : 0;
647
+ };
648
+ imports["rb-js-abi-host"]["reflect-own-keys: func(target: handle<js-abi-value>) -> list<handle<js-abi-value>>"] = function(arg0, arg1) {
649
+ const memory = get_export("memory");
650
+ const realloc = get_export("cabi_realloc");
651
+ const ret0 = obj.reflectOwnKeys(resources0.get(arg0));
652
+ const vec0 = ret0;
653
+ const len0 = vec0.length;
654
+ const result0 = realloc(0, 0, 4, len0 * 4);
655
+ for (let i = 0; i < vec0.length; i++) {
656
+ const e = vec0[i];
657
+ const base = result0 + i * 4;
658
+ data_view(memory).setInt32(base + 0, resources0.insert(e), true);
659
+ }
660
+ data_view(memory).setInt32(arg1 + 4, len0, true);
661
+ data_view(memory).setInt32(arg1 + 0, result0, true);
662
+ };
663
+ imports["rb-js-abi-host"]["reflect-prevent-extensions: func(target: handle<js-abi-value>) -> bool"] = function(arg0) {
664
+ const ret0 = obj.reflectPreventExtensions(resources0.get(arg0));
665
+ return ret0 ? 1 : 0;
666
+ };
667
+ imports["rb-js-abi-host"]["reflect-set: func(target: handle<js-abi-value>, property-key: string, value: handle<js-abi-value>) -> variant { success(handle<js-abi-value>), failure(handle<js-abi-value>) }"] = function(arg0, arg1, arg2, arg3, arg4) {
668
+ const memory = get_export("memory");
669
+ const ptr0 = arg1;
670
+ const len0 = arg2;
671
+ const result0 = UTF8_DECODER.decode(new Uint8Array(memory.buffer, ptr0, len0));
672
+ const ret0 = obj.reflectSet(resources0.get(arg0), result0, resources0.get(arg3));
673
+ const variant1 = ret0;
674
+ switch (variant1.tag) {
675
+ case "success": {
676
+ const e = variant1.val;
677
+ data_view(memory).setInt8(arg4 + 0, 0, true);
678
+ data_view(memory).setInt32(arg4 + 4, resources0.insert(e), true);
679
+ break;
1295
680
  }
1296
- else {
1297
- throw e;
681
+ case "failure": {
682
+ const e = variant1.val;
683
+ data_view(memory).setInt8(arg4 + 0, 1, true);
684
+ data_view(memory).setInt32(arg4 + 4, resources0.insert(e), true);
685
+ break;
1298
686
  }
1299
- }
1300
- }
1301
- const callRbMethod = (vm, privateObject, recv, callee, args) => {
1302
- const mid = vm.guest.rbIntern(callee + "\0");
1303
- return wrapRbOperation(vm, () => {
1304
- const [value, status] = vm.guest.rbFuncallvProtect(recv, mid, args);
1305
- checkStatusTag(status, vm, privateObject);
1306
- return value;
1307
- });
1308
- };
1309
- const evalRbCode = (vm, privateObject, code) => {
1310
- return wrapRbOperation(vm, () => {
1311
- const [value, status] = vm.guest.rbEvalStringProtect(code + "\0");
1312
- checkStatusTag(status, vm, privateObject);
1313
- return new RbValue(value, vm, privateObject);
1314
- });
1315
- };
1316
- /**
1317
- * Error class thrown by Ruby execution
1318
- */
1319
- class RbError extends Error {
1320
- /**
1321
- * @hideconstructor
1322
- */
1323
- constructor(message) {
1324
- super(message);
1325
- }
1326
- }
1327
- /**
1328
- * Error class thrown by Ruby execution when it is not possible to recover.
1329
- * This is usually caused when Ruby VM is in an inconsistent state.
1330
- */
1331
- class RbFatalError extends RbError {
1332
- /**
1333
- * @hideconstructor
1334
- */
1335
- constructor(message) {
1336
- super("Ruby Fatal Error: " + message);
1337
- }
1338
- }
687
+ default:
688
+ throw new RangeError("invalid variant specified for JsAbiResult");
689
+ }
690
+ };
691
+ imports["rb-js-abi-host"]["reflect-set-prototype-of: func(target: handle<js-abi-value>, prototype: handle<js-abi-value>) -> bool"] = function(arg0, arg1) {
692
+ const ret0 = obj.reflectSetPrototypeOf(resources0.get(arg0), resources0.get(arg1));
693
+ return ret0 ? 1 : 0;
694
+ };
695
+ if (!("canonical_abi" in imports)) imports["canonical_abi"] = {};
696
+
697
+ const resources0 = new Slab();
698
+ imports.canonical_abi["resource_drop_js-abi-value"] = (i) => {
699
+ const val = resources0.remove(i);
700
+ if (obj.dropJsAbiValue)
701
+ obj.dropJsAbiValue(val);
702
+ };
703
+ }
704
+
705
+ /**
706
+ * A Ruby VM instance
707
+ *
708
+ * @example
709
+ *
710
+ * const wasi = new WASI();
711
+ * const vm = new RubyVM();
712
+ * const imports = {
713
+ * wasi_snapshot_preview1: wasi.wasiImport,
714
+ * };
715
+ *
716
+ * vm.addToImports(imports);
717
+ *
718
+ * const instance = await WebAssembly.instantiate(rubyModule, imports);
719
+ * await vm.setInstance(instance);
720
+ * wasi.initialize(instance);
721
+ * vm.initialize();
722
+ *
723
+ */
724
+ class RubyVM {
725
+ constructor() {
726
+ this.instance = null;
727
+ this.interfaceState = {
728
+ hasJSFrameAfterRbFrame: false,
729
+ };
730
+ // Wrap exported functions from Ruby VM to prohibit nested VM operation
731
+ // if the call stack has sandwitched JS frames like JS -> Ruby -> JS -> Ruby.
732
+ const proxyExports = (exports) => {
733
+ const excludedMethods = [
734
+ "addToImports",
735
+ "instantiate",
736
+ "rbSetShouldProhibitRewind",
737
+ "rbGcDisable",
738
+ "rbGcEnable",
739
+ ];
740
+ const excluded = ["constructor"].concat(excludedMethods);
741
+ // wrap all methods in RbAbi.RbAbiGuest class
742
+ for (const key of Object.getOwnPropertyNames(RbAbiGuest.prototype)) {
743
+ if (excluded.includes(key)) {
744
+ continue;
745
+ }
746
+ const value = exports[key];
747
+ if (typeof value === "function") {
748
+ exports[key] = (...args) => {
749
+ const isNestedVMCall = this.interfaceState.hasJSFrameAfterRbFrame;
750
+ if (isNestedVMCall) {
751
+ const oldShouldProhibitRewind = this.guest.rbSetShouldProhibitRewind(true);
752
+ const oldIsDisabledGc = this.guest.rbGcDisable();
753
+ const result = Reflect.apply(value, exports, args);
754
+ this.guest.rbSetShouldProhibitRewind(oldShouldProhibitRewind);
755
+ if (!oldIsDisabledGc) {
756
+ this.guest.rbGcEnable();
757
+ }
758
+ return result;
759
+ }
760
+ else {
761
+ return Reflect.apply(value, exports, args);
762
+ }
763
+ };
764
+ }
765
+ }
766
+ return exports;
767
+ };
768
+ this.guest = proxyExports(new RbAbiGuest());
769
+ this.transport = new JsValueTransport();
770
+ this.exceptionFormatter = new RbExceptionFormatter();
771
+ }
772
+ /**
773
+ * Initialize the Ruby VM with the given command line arguments
774
+ * @param args The command line arguments to pass to Ruby. Must be
775
+ * an array of strings starting with the Ruby program name.
776
+ */
777
+ initialize(args = ["ruby.wasm", "-EUTF-8", "-e_=0"]) {
778
+ const c_args = args.map((arg) => arg + "\0");
779
+ this.guest.rubyInit();
780
+ this.guest.rubySysinit(c_args);
781
+ this.guest.rubyOptions(c_args);
782
+ this.eval(`require "/bundle/setup"`);
783
+ }
784
+ /**
785
+ * Set a given instance to interact JavaScript and Ruby's
786
+ * WebAssembly instance. This method must be called before calling
787
+ * Ruby API.
788
+ *
789
+ * @param instance The WebAssembly instance to interact with. Must
790
+ * be instantiated from a Ruby built with JS extension, and built
791
+ * with Reactor ABI instead of command line.
792
+ */
793
+ async setInstance(instance) {
794
+ this.instance = instance;
795
+ await this.guest.instantiate(instance);
796
+ }
797
+ /**
798
+ * Add intrinsic import entries, which is necessary to interact JavaScript
799
+ * and Ruby's WebAssembly instance.
800
+ * @param imports The import object to add to the WebAssembly instance
801
+ */
802
+ addToImports(imports) {
803
+ this.guest.addToImports(imports);
804
+ function wrapTry(f) {
805
+ return (...args) => {
806
+ try {
807
+ return { tag: "success", val: f(...args) };
808
+ }
809
+ catch (e) {
810
+ if (e instanceof RbFatalError) {
811
+ // RbFatalError should not be caught by Ruby because it Ruby VM
812
+ // can be already in an inconsistent state.
813
+ throw e;
814
+ }
815
+ return { tag: "failure", val: e };
816
+ }
817
+ };
818
+ }
819
+ imports["rb-js-abi-host"] = {
820
+ rb_wasm_throw_prohibit_rewind_exception: (messagePtr, messageLen) => {
821
+ const memory = this.instance.exports.memory;
822
+ const str = new TextDecoder().decode(new Uint8Array(memory.buffer, messagePtr, messageLen));
823
+ throw new RbFatalError("Ruby APIs that may rewind the VM stack are prohibited under nested VM operation " +
824
+ `(${str})\n` +
825
+ "Nested VM operation means that the call stack has sandwitched JS frames like JS -> Ruby -> JS -> Ruby " +
826
+ "caused by something like `window.rubyVM.eval(\"JS.global[:rubyVM].eval('Fiber.yield')\")`\n" +
827
+ "\n" +
828
+ "Please check your call stack and make sure that you are **not** doing any of the following inside the nested Ruby frame:\n" +
829
+ " 1. Switching fibers (e.g. Fiber#resume, Fiber.yield, and Fiber#transfer)\n" +
830
+ " Note that `evalAsync` JS API switches fibers internally\n" +
831
+ " 2. Raising uncaught exceptions\n" +
832
+ " Please catch all exceptions inside the nested operation\n" +
833
+ " 3. Calling Continuation APIs\n");
834
+ },
835
+ };
836
+ // NOTE: The GC may collect objects that are still referenced by Wasm
837
+ // locals because Asyncify cannot scan the Wasm stack above the JS frame.
838
+ // So we need to keep track whether the JS frame is sandwitched by Ruby
839
+ // frames or not, and prohibit nested VM operation if it is.
840
+ const proxyImports = (imports) => {
841
+ for (const [key, value] of Object.entries(imports)) {
842
+ if (typeof value === "function") {
843
+ imports[key] = (...args) => {
844
+ const oldValue = this.interfaceState.hasJSFrameAfterRbFrame;
845
+ this.interfaceState.hasJSFrameAfterRbFrame = true;
846
+ const result = Reflect.apply(value, imports, args);
847
+ this.interfaceState.hasJSFrameAfterRbFrame = oldValue;
848
+ return result;
849
+ };
850
+ }
851
+ }
852
+ return imports;
853
+ };
854
+ addRbJsAbiHostToImports(imports, proxyImports({
855
+ evalJs: wrapTry((code) => {
856
+ return Function(code)();
857
+ }),
858
+ isJs: (value) => {
859
+ // Just for compatibility with the old JS API
860
+ return true;
861
+ },
862
+ globalThis: () => {
863
+ if (typeof globalThis !== "undefined") {
864
+ return globalThis;
865
+ }
866
+ else if (typeof global !== "undefined") {
867
+ return global;
868
+ }
869
+ else if (typeof window !== "undefined") {
870
+ return window;
871
+ }
872
+ throw new Error("unable to locate global object");
873
+ },
874
+ intToJsNumber: (value) => {
875
+ return value;
876
+ },
877
+ floatToJsNumber: (value) => {
878
+ return value;
879
+ },
880
+ stringToJsString: (value) => {
881
+ return value;
882
+ },
883
+ boolToJsBool: (value) => {
884
+ return value;
885
+ },
886
+ procToJsFunction: (rawRbAbiValue) => {
887
+ const rbValue = this.rbValueOfPointer(rawRbAbiValue);
888
+ return (...args) => {
889
+ rbValue.call("call", ...args.map((arg) => this.wrap(arg)));
890
+ };
891
+ },
892
+ rbObjectToJsRbValue: (rawRbAbiValue) => {
893
+ return this.rbValueOfPointer(rawRbAbiValue);
894
+ },
895
+ jsValueToString: (value) => {
896
+ // According to the [spec](https://tc39.es/ecma262/multipage/text-processing.html#sec-string-constructor-string-value)
897
+ // `String(value)` always returns a string.
898
+ return String(value);
899
+ },
900
+ jsValueToInteger(value) {
901
+ if (typeof value === "number") {
902
+ return { tag: "f64", val: value };
903
+ }
904
+ else if (typeof value === "bigint") {
905
+ return { tag: "bignum", val: BigInt(value).toString(10) + "\0" };
906
+ }
907
+ else if (typeof value === "string") {
908
+ return { tag: "bignum", val: value + "\0" };
909
+ }
910
+ else if (typeof value === "undefined") {
911
+ return { tag: "f64", val: 0 };
912
+ }
913
+ else {
914
+ return { tag: "f64", val: Number(value) };
915
+ }
916
+ },
917
+ exportJsValueToHost: (value) => {
918
+ // See `JsValueExporter` for the reason why we need to do this
919
+ this.transport.takeJsValue(value);
920
+ },
921
+ importJsValueFromHost: () => {
922
+ return this.transport.consumeJsValue();
923
+ },
924
+ instanceOf: (value, klass) => {
925
+ if (typeof klass === "function") {
926
+ return value instanceof klass;
927
+ }
928
+ else {
929
+ return false;
930
+ }
931
+ },
932
+ jsValueTypeof(value) {
933
+ return typeof value;
934
+ },
935
+ jsValueEqual(lhs, rhs) {
936
+ return lhs == rhs;
937
+ },
938
+ jsValueStrictlyEqual(lhs, rhs) {
939
+ return lhs === rhs;
940
+ },
941
+ reflectApply: wrapTry((target, thisArgument, args) => {
942
+ return Reflect.apply(target, thisArgument, args);
943
+ }),
944
+ reflectConstruct: function (target, args) {
945
+ throw new Error("Function not implemented.");
946
+ },
947
+ reflectDeleteProperty: function (target, propertyKey) {
948
+ throw new Error("Function not implemented.");
949
+ },
950
+ reflectGet: wrapTry((target, propertyKey) => {
951
+ return target[propertyKey];
952
+ }),
953
+ reflectGetOwnPropertyDescriptor: function (target, propertyKey) {
954
+ throw new Error("Function not implemented.");
955
+ },
956
+ reflectGetPrototypeOf: function (target) {
957
+ throw new Error("Function not implemented.");
958
+ },
959
+ reflectHas: function (target, propertyKey) {
960
+ throw new Error("Function not implemented.");
961
+ },
962
+ reflectIsExtensible: function (target) {
963
+ throw new Error("Function not implemented.");
964
+ },
965
+ reflectOwnKeys: function (target) {
966
+ throw new Error("Function not implemented.");
967
+ },
968
+ reflectPreventExtensions: function (target) {
969
+ throw new Error("Function not implemented.");
970
+ },
971
+ reflectSet: wrapTry((target, propertyKey, value) => {
972
+ return Reflect.set(target, propertyKey, value);
973
+ }),
974
+ reflectSetPrototypeOf: function (target, prototype) {
975
+ throw new Error("Function not implemented.");
976
+ },
977
+ }), (name) => {
978
+ return this.instance.exports[name];
979
+ });
980
+ }
981
+ /**
982
+ * Print the Ruby version to stdout
983
+ */
984
+ printVersion() {
985
+ this.guest.rubyShowVersion();
986
+ }
987
+ /**
988
+ * Runs a string of Ruby code from JavaScript
989
+ * @param code The Ruby code to run
990
+ * @returns the result of the last expression
991
+ *
992
+ * @example
993
+ * vm.eval("puts 'hello world'");
994
+ * const result = vm.eval("1 + 2");
995
+ * console.log(result.toString()); // 3
996
+ *
997
+ */
998
+ eval(code) {
999
+ return evalRbCode(this, this.privateObject(), code);
1000
+ }
1001
+ /**
1002
+ * Runs a string of Ruby code with top-level `JS::Object#await`
1003
+ * Returns a promise that resolves when execution completes.
1004
+ * @param code The Ruby code to run
1005
+ * @returns a promise that resolves to the result of the last expression
1006
+ *
1007
+ * @example
1008
+ * const text = await vm.evalAsync(`
1009
+ * require 'js'
1010
+ * response = JS.global.fetch('https://example.com').await
1011
+ * response.text.await
1012
+ * `);
1013
+ * console.log(text.toString()); // <html>...</html>
1014
+ */
1015
+ evalAsync(code) {
1016
+ const JS = this.eval("require 'js'; JS");
1017
+ return newRbPromise(this, this.privateObject(), (future) => {
1018
+ JS.call("__eval_async_rb", this.wrap(code), future);
1019
+ });
1020
+ }
1021
+ /**
1022
+ * Wrap a JavaScript value into a Ruby JS::Object
1023
+ * @param value The value to convert to RbValue
1024
+ * @returns the RbValue object representing the given JS value
1025
+ *
1026
+ * @example
1027
+ * const hash = vm.eval(`Hash.new`)
1028
+ * hash.call("store", vm.eval(`"key1"`), vm.wrap(new Object()));
1029
+ */
1030
+ wrap(value) {
1031
+ return this.transport.importJsValue(value, this);
1032
+ }
1033
+ /** @private */
1034
+ privateObject() {
1035
+ return {
1036
+ transport: this.transport,
1037
+ exceptionFormatter: this.exceptionFormatter,
1038
+ };
1039
+ }
1040
+ /** @private */
1041
+ rbValueOfPointer(pointer) {
1042
+ const abiValue = new RbAbiValue(pointer, this.guest);
1043
+ return new RbValue(abiValue, this, this.privateObject());
1044
+ }
1045
+ }
1046
+ /**
1047
+ * Export a JS value held by the Ruby VM to the JS environment.
1048
+ * This is implemented in a dirty way since wit cannot reference resources
1049
+ * defined in other interfaces.
1050
+ * In our case, we can't express `function(v: rb-abi-value) -> js-abi-value`
1051
+ * because `rb-js-abi-host.wit`, that defines `js-abi-value`, is implemented
1052
+ * by embedder side (JS) but `rb-abi-guest.wit`, that defines `rb-abi-value`
1053
+ * is implemented by guest side (Wasm).
1054
+ *
1055
+ * This class is a helper to export by:
1056
+ * 1. Call `function __export_to_js(v: rb-abi-value)` defined in guest from embedder side.
1057
+ * 2. Call `function takeJsValue(v: js-abi-value)` defined in embedder from guest side with
1058
+ * underlying JS value of given `rb-abi-value`.
1059
+ * 3. Then `takeJsValue` implementation escapes the given JS value to the `_takenJsValues`
1060
+ * stored in embedder side.
1061
+ * 4. Finally, embedder side can take `_takenJsValues`.
1062
+ *
1063
+ * Note that `exportJsValue` is not reentrant.
1064
+ *
1065
+ * @private
1066
+ */
1067
+ class JsValueTransport {
1068
+ constructor() {
1069
+ this._takenJsValue = null;
1070
+ }
1071
+ takeJsValue(value) {
1072
+ this._takenJsValue = value;
1073
+ }
1074
+ consumeJsValue() {
1075
+ return this._takenJsValue;
1076
+ }
1077
+ exportJsValue(value) {
1078
+ value.call("__export_to_js");
1079
+ return this._takenJsValue;
1080
+ }
1081
+ importJsValue(value, vm) {
1082
+ this._takenJsValue = value;
1083
+ return vm.eval('require "js"; JS::Object').call("__import_from_js");
1084
+ }
1085
+ }
1086
+ /**
1087
+ * A RbValue is an object that represents a value in Ruby
1088
+ */
1089
+ class RbValue {
1090
+ /**
1091
+ * @hideconstructor
1092
+ */
1093
+ constructor(inner, vm, privateObject) {
1094
+ this.inner = inner;
1095
+ this.vm = vm;
1096
+ this.privateObject = privateObject;
1097
+ }
1098
+ /**
1099
+ * Call a given method with given arguments
1100
+ *
1101
+ * @param callee name of the Ruby method to call
1102
+ * @param args arguments to pass to the method. Must be an array of RbValue
1103
+ * @returns The result of the method call as a new RbValue.
1104
+ *
1105
+ * @example
1106
+ * const ary = vm.eval("[1, 2, 3]");
1107
+ * ary.call("push", 4);
1108
+ * console.log(ary.call("sample").toString());
1109
+ */
1110
+ call(callee, ...args) {
1111
+ const innerArgs = args.map((arg) => arg.inner);
1112
+ return new RbValue(callRbMethod(this.vm, this.privateObject, this.inner, callee, innerArgs), this.vm, this.privateObject);
1113
+ }
1114
+ /**
1115
+ * Call a given method that may call `JS::Object#await` with given arguments
1116
+ *
1117
+ * @param callee name of the Ruby method to call
1118
+ * @param args arguments to pass to the method. Must be an array of RbValue
1119
+ * @returns A Promise that resolves to the result of the method call as a new RbValue.
1120
+ *
1121
+ * @example
1122
+ * const client = vm.eval(`
1123
+ * require 'js'
1124
+ * class HttpClient
1125
+ * def get(url)
1126
+ * JS.global.fetch(url).await
1127
+ * end
1128
+ * end
1129
+ * HttpClient.new
1130
+ * `);
1131
+ * const response = await client.callAsync("get", vm.eval(`"https://example.com"`));
1132
+ */
1133
+ callAsync(callee, ...args) {
1134
+ const JS = this.vm.eval("require 'js'; JS");
1135
+ return newRbPromise(this.vm, this.privateObject, (future) => {
1136
+ JS.call("__call_async_method", this, this.vm.wrap(callee), future, ...args);
1137
+ });
1138
+ }
1139
+ /**
1140
+ * @see {@link https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Global_Objects/Symbol/toPrimitive}
1141
+ * @param hint Preferred type of the result primitive value. `"number"`, `"string"`, or `"default"`.
1142
+ */
1143
+ [Symbol.toPrimitive](hint) {
1144
+ if (hint === "string" || hint === "default") {
1145
+ return this.toString();
1146
+ }
1147
+ else if (hint === "number") {
1148
+ return null;
1149
+ }
1150
+ return null;
1151
+ }
1152
+ /**
1153
+ * Returns a string representation of the value by calling `to_s`
1154
+ */
1155
+ toString() {
1156
+ const rbString = callRbMethod(this.vm, this.privateObject, this.inner, "to_s", []);
1157
+ return this.vm.guest.rstringPtr(rbString);
1158
+ }
1159
+ /**
1160
+ * Returns a JavaScript object representation of the value
1161
+ * by calling `to_js`.
1162
+ *
1163
+ * Returns null if the value is not convertible to a JavaScript object.
1164
+ */
1165
+ toJS() {
1166
+ const JS = this.vm.eval("JS");
1167
+ const jsValue = JS.call("try_convert", this);
1168
+ if (jsValue.call("nil?").toString() === "true") {
1169
+ return null;
1170
+ }
1171
+ return this.privateObject.transport.exportJsValue(jsValue);
1172
+ }
1173
+ }
1174
+ var ruby_tag_type;
1175
+ (function (ruby_tag_type) {
1176
+ ruby_tag_type[ruby_tag_type["None"] = 0] = "None";
1177
+ ruby_tag_type[ruby_tag_type["Return"] = 1] = "Return";
1178
+ ruby_tag_type[ruby_tag_type["Break"] = 2] = "Break";
1179
+ ruby_tag_type[ruby_tag_type["Next"] = 3] = "Next";
1180
+ ruby_tag_type[ruby_tag_type["Retry"] = 4] = "Retry";
1181
+ ruby_tag_type[ruby_tag_type["Redo"] = 5] = "Redo";
1182
+ ruby_tag_type[ruby_tag_type["Raise"] = 6] = "Raise";
1183
+ ruby_tag_type[ruby_tag_type["Throw"] = 7] = "Throw";
1184
+ ruby_tag_type[ruby_tag_type["Fatal"] = 8] = "Fatal";
1185
+ ruby_tag_type[ruby_tag_type["Mask"] = 15] = "Mask";
1186
+ })(ruby_tag_type || (ruby_tag_type = {}));
1187
+ class RbExceptionFormatter {
1188
+ constructor() {
1189
+ this.literalsCache = null;
1190
+ this.isFormmatting = false;
1191
+ }
1192
+ format(error, vm, privateObject) {
1193
+ // All Ruby exceptions raised during formatting exception message should
1194
+ // be caught and return a fallback message.
1195
+ // Therefore, we don't need to worry about infinite recursion here ideally
1196
+ // but checking re-entrancy just in case.
1197
+ class RbExceptionFormatterError extends Error {
1198
+ }
1199
+ if (this.isFormmatting) {
1200
+ throw new RbExceptionFormatterError("Unexpected exception occurred during formatting exception message");
1201
+ }
1202
+ this.isFormmatting = true;
1203
+ try {
1204
+ return this._format(error, vm, privateObject);
1205
+ }
1206
+ finally {
1207
+ this.isFormmatting = false;
1208
+ }
1209
+ }
1210
+ _format(error, vm, privateObject) {
1211
+ const [zeroLiteral, oneLiteral, newLineLiteral] = (() => {
1212
+ if (this.literalsCache == null) {
1213
+ const zeroOneNewLine = [
1214
+ evalRbCode(vm, privateObject, "0"),
1215
+ evalRbCode(vm, privateObject, "1"),
1216
+ evalRbCode(vm, privateObject, `"\n"`),
1217
+ ];
1218
+ this.literalsCache = zeroOneNewLine;
1219
+ return zeroOneNewLine;
1220
+ }
1221
+ else {
1222
+ return this.literalsCache;
1223
+ }
1224
+ })();
1225
+ let className;
1226
+ let backtrace;
1227
+ let message;
1228
+ try {
1229
+ className = error.call("class").toString();
1230
+ }
1231
+ catch (e) {
1232
+ className = "unknown";
1233
+ }
1234
+ try {
1235
+ message = error.toString();
1236
+ }
1237
+ catch (e) {
1238
+ message = "unknown";
1239
+ }
1240
+ try {
1241
+ backtrace = error.call("backtrace");
1242
+ }
1243
+ catch (e) {
1244
+ return this.formatString(className, message);
1245
+ }
1246
+ if (backtrace.call("nil?").toString() === "true") {
1247
+ return this.formatString(className, message);
1248
+ }
1249
+ try {
1250
+ const firstLine = backtrace.call("at", zeroLiteral);
1251
+ const restLines = backtrace
1252
+ .call("drop", oneLiteral)
1253
+ .call("join", newLineLiteral);
1254
+ return this.formatString(className, message, [
1255
+ firstLine.toString(),
1256
+ restLines.toString(),
1257
+ ]);
1258
+ }
1259
+ catch (e) {
1260
+ return this.formatString(className, message);
1261
+ }
1262
+ }
1263
+ formatString(klass, message, backtrace) {
1264
+ if (backtrace) {
1265
+ return `${backtrace[0]}: ${message} (${klass})\n${backtrace[1]}`;
1266
+ }
1267
+ else {
1268
+ return `${klass}: ${message}`;
1269
+ }
1270
+ }
1271
+ }
1272
+ const checkStatusTag = (rawTag, vm, privateObject) => {
1273
+ switch (rawTag & ruby_tag_type.Mask) {
1274
+ case ruby_tag_type.None:
1275
+ break;
1276
+ case ruby_tag_type.Return:
1277
+ throw new RbError("unexpected return");
1278
+ case ruby_tag_type.Next:
1279
+ throw new RbError("unexpected next");
1280
+ case ruby_tag_type.Break:
1281
+ throw new RbError("unexpected break");
1282
+ case ruby_tag_type.Redo:
1283
+ throw new RbError("unexpected redo");
1284
+ case ruby_tag_type.Retry:
1285
+ throw new RbError("retry outside of rescue clause");
1286
+ case ruby_tag_type.Throw:
1287
+ throw new RbError("unexpected throw");
1288
+ case ruby_tag_type.Raise:
1289
+ case ruby_tag_type.Fatal:
1290
+ const error = new RbValue(vm.guest.rbErrinfo(), vm, privateObject);
1291
+ if (error.call("nil?").toString() === "true") {
1292
+ throw new RbError("no exception object");
1293
+ }
1294
+ // clear errinfo if got exception due to no rb_jump_tag
1295
+ vm.guest.rbClearErrinfo();
1296
+ throw new RbError(privateObject.exceptionFormatter.format(error, vm, privateObject));
1297
+ default:
1298
+ throw new RbError(`unknown error tag: ${rawTag}`);
1299
+ }
1300
+ };
1301
+ function wrapRbOperation(vm, body) {
1302
+ try {
1303
+ return body();
1304
+ }
1305
+ catch (e) {
1306
+ if (e instanceof RbError) {
1307
+ throw e;
1308
+ }
1309
+ // All JS exceptions triggered by Ruby code are translated to Ruby exceptions,
1310
+ // so non-RbError exceptions are unexpected.
1311
+ vm.guest.rbVmBugreport();
1312
+ if (e instanceof WebAssembly.RuntimeError && e.message === "unreachable") {
1313
+ const error = new RbError(`Something went wrong in Ruby VM: ${e}`);
1314
+ error.stack = e.stack;
1315
+ throw error;
1316
+ }
1317
+ else {
1318
+ throw e;
1319
+ }
1320
+ }
1321
+ }
1322
+ const callRbMethod = (vm, privateObject, recv, callee, args) => {
1323
+ const mid = vm.guest.rbIntern(callee + "\0");
1324
+ return wrapRbOperation(vm, () => {
1325
+ const [value, status] = vm.guest.rbFuncallvProtect(recv, mid, args);
1326
+ checkStatusTag(status, vm, privateObject);
1327
+ return value;
1328
+ });
1329
+ };
1330
+ const evalRbCode = (vm, privateObject, code) => {
1331
+ return wrapRbOperation(vm, () => {
1332
+ const [value, status] = vm.guest.rbEvalStringProtect(code + "\0");
1333
+ checkStatusTag(status, vm, privateObject);
1334
+ return new RbValue(value, vm, privateObject);
1335
+ });
1336
+ };
1337
+ function newRbPromise(vm, privateObject, body) {
1338
+ return new Promise((resolve, reject) => {
1339
+ const future = vm.wrap({
1340
+ resolve,
1341
+ reject: (error) => {
1342
+ const rbError = new RbError(privateObject.exceptionFormatter.format(error, vm, privateObject));
1343
+ reject(rbError);
1344
+ },
1345
+ });
1346
+ body(future);
1347
+ });
1348
+ }
1349
+ /**
1350
+ * Error class thrown by Ruby execution
1351
+ */
1352
+ class RbError extends Error {
1353
+ /**
1354
+ * @hideconstructor
1355
+ */
1356
+ constructor(message) {
1357
+ super(message);
1358
+ }
1359
+ }
1360
+ /**
1361
+ * Error class thrown by Ruby execution when it is not possible to recover.
1362
+ * This is usually caused when Ruby VM is in an inconsistent state.
1363
+ */
1364
+ class RbFatalError extends RbError {
1365
+ /**
1366
+ * @hideconstructor
1367
+ */
1368
+ constructor(message) {
1369
+ super("Ruby Fatal Error: " + message);
1370
+ }
1371
+ }
1339
1372
 
1340
- exports.RbError = RbError;
1341
- exports.RbFatalError = RbFatalError;
1342
- exports.RbValue = RbValue;
1343
- exports.RubyVM = RubyVM;
1344
- exports.consolePrinter = consolePrinter;
1373
+ exports.RbError = RbError;
1374
+ exports.RbFatalError = RbFatalError;
1375
+ exports.RbValue = RbValue;
1376
+ exports.RubyVM = RubyVM;
1377
+ exports.consolePrinter = consolePrinter;
1345
1378
 
1346
1379
  }));