mirocode 0.0.0-stage → 0.14.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.
@@ -0,0 +1,2762 @@
1
+ // node_modules/@earendil-works/pi-codemode/dist/runtime/worker.js
2
+ import { parentPort, workerData } from "node:worker_threads";
3
+
4
+ // node_modules/quickjs-wasi/dist/wasi-shim.js
5
+ function createWasiShim(memoryAccessor) {
6
+ const ERRNO_SUCCESS = 0;
7
+ const ERRNO_BADF = 8;
8
+ const ERRNO_NOSYS = 52;
9
+ const CLOCK_REALTIME = 0;
10
+ const CLOCK_MONOTONIC = 1;
11
+ return {
12
+ clock_time_get(clockId, _precision, resultPtr) {
13
+ const mem = memoryAccessor();
14
+ const view = new DataView(mem.buffer);
15
+ if (clockId === CLOCK_REALTIME || clockId === CLOCK_MONOTONIC) {
16
+ const timeNs = BigInt(Date.now()) * 1000000n;
17
+ view.setBigUint64(resultPtr, timeNs, true);
18
+ return ERRNO_SUCCESS;
19
+ }
20
+ return ERRNO_NOSYS;
21
+ },
22
+ fd_write(fd, iovsPtr, iovsLen, nwrittenPtr) {
23
+ const mem = memoryAccessor();
24
+ const view = new DataView(mem.buffer);
25
+ const bytes = new Uint8Array(mem.buffer);
26
+ let totalWritten = 0;
27
+ if (fd !== 1 && fd !== 2) {
28
+ return ERRNO_BADF;
29
+ }
30
+ for (let i = 0;i < iovsLen; i++) {
31
+ const bufPtr = view.getUint32(iovsPtr + i * 8, true);
32
+ const bufLen = view.getUint32(iovsPtr + i * 8 + 4, true);
33
+ const chunk = bytes.slice(bufPtr, bufPtr + bufLen);
34
+ const text = new TextDecoder().decode(chunk);
35
+ if (fd === 1) {
36
+ if (typeof process !== "undefined" && process.stdout) {
37
+ process.stdout.write(text);
38
+ } else {
39
+ console.log(text);
40
+ }
41
+ } else {
42
+ if (typeof process !== "undefined" && process.stderr) {
43
+ process.stderr.write(text);
44
+ } else {
45
+ console.error(text);
46
+ }
47
+ }
48
+ totalWritten += bufLen;
49
+ }
50
+ view.setUint32(nwrittenPtr, totalWritten, true);
51
+ return ERRNO_SUCCESS;
52
+ },
53
+ fd_close(_fd) {
54
+ return ERRNO_NOSYS;
55
+ },
56
+ fd_fdstat_get(fd, statPtr) {
57
+ const mem = memoryAccessor();
58
+ const view = new DataView(mem.buffer);
59
+ if (fd === 1 || fd === 2) {
60
+ view.setUint8(statPtr, 2);
61
+ view.setUint16(statPtr + 2, 0, true);
62
+ view.setBigUint64(statPtr + 8, 0n, true);
63
+ view.setBigUint64(statPtr + 16, 0n, true);
64
+ return ERRNO_SUCCESS;
65
+ }
66
+ return ERRNO_BADF;
67
+ },
68
+ fd_seek(_fd, _offset, _whence, _resultPtr) {
69
+ return ERRNO_NOSYS;
70
+ },
71
+ random_get(bufPtr, bufLen) {
72
+ const mem = memoryAccessor();
73
+ const bytes = new Uint8Array(mem.buffer, bufPtr, bufLen);
74
+ if (typeof crypto !== "undefined" && crypto.getRandomValues) {
75
+ crypto.getRandomValues(bytes);
76
+ } else {
77
+ for (let i = 0;i < bufLen; i++) {
78
+ bytes[i] = Math.floor(Math.random() * 256);
79
+ }
80
+ }
81
+ return ERRNO_SUCCESS;
82
+ }
83
+ };
84
+ }
85
+
86
+ // node_modules/quickjs-wasi/dist/extensions.js
87
+ var decoder = new TextDecoder;
88
+ function parseVersionString(memory, ptr) {
89
+ const mem = new Uint8Array(memory.buffer);
90
+ let end = ptr;
91
+ while (mem[end] !== 0)
92
+ end++;
93
+ if (end === ptr)
94
+ return {};
95
+ const str = decoder.decode(mem.slice(ptr, end));
96
+ const result = {};
97
+ for (const line of str.split(`
98
+ `)) {
99
+ const eq = line.indexOf("=");
100
+ if (eq > 0) {
101
+ result[line.slice(0, eq)] = line.slice(eq + 1);
102
+ }
103
+ }
104
+ return result;
105
+ }
106
+ function extractExtensionVersions(ext, memory) {
107
+ const versionsFnName = `qjs_ext_${ext.name.replace(/-/g, "_")}_versions`;
108
+ const versionsFn = ext.instance.exports[versionsFnName];
109
+ if (typeof versionsFn !== "function")
110
+ return;
111
+ const ptr = versionsFn();
112
+ if (ptr === 0)
113
+ return;
114
+ return parseVersionString(memory, ptr);
115
+ }
116
+ function readULEB128(bytes, offset) {
117
+ let result = 0;
118
+ let shift = 0;
119
+ while (offset.value < bytes.length) {
120
+ const byte = bytes[offset.value++];
121
+ result |= (byte & 127) << shift;
122
+ if ((byte & 128) === 0)
123
+ break;
124
+ shift += 7;
125
+ }
126
+ return result;
127
+ }
128
+ function parseDylink(module) {
129
+ const sections = WebAssembly.Module.customSections(module, "dylink.0");
130
+ if (sections.length === 0)
131
+ return null;
132
+ const bytes = new Uint8Array(sections[0]);
133
+ const offset = { value: 0 };
134
+ const info = {
135
+ memorySize: 0,
136
+ memoryAlignment: 0,
137
+ tableSize: 0,
138
+ tableAlignment: 0,
139
+ needed: []
140
+ };
141
+ while (offset.value < bytes.length) {
142
+ const subsectionType = readULEB128(bytes, offset);
143
+ const subsectionSize = readULEB128(bytes, offset);
144
+ const subsectionEnd = offset.value + subsectionSize;
145
+ if (subsectionType === 1) {
146
+ info.memorySize = readULEB128(bytes, offset);
147
+ info.memoryAlignment = readULEB128(bytes, offset);
148
+ info.tableSize = readULEB128(bytes, offset);
149
+ info.tableAlignment = readULEB128(bytes, offset);
150
+ } else if (subsectionType === 2) {
151
+ const count = readULEB128(bytes, offset);
152
+ for (let i = 0;i < count; i++) {
153
+ const len = readULEB128(bytes, offset);
154
+ const name = new TextDecoder().decode(bytes.slice(offset.value, offset.value + len));
155
+ offset.value += len;
156
+ info.needed.push(name);
157
+ }
158
+ }
159
+ offset.value = subsectionEnd;
160
+ }
161
+ return info;
162
+ }
163
+ async function loadExtension(descriptor, mainExports, wasiBuiltins, wasiUserOverrides, memoryProxy, allocBase) {
164
+ let module;
165
+ if (descriptor.wasm instanceof WebAssembly.Module) {
166
+ module = descriptor.wasm;
167
+ } else {
168
+ module = await WebAssembly.compile(descriptor.wasm);
169
+ }
170
+ const dylink = parseDylink(module);
171
+ if (!dylink) {
172
+ throw new Error(`Extension "${descriptor.name}" is not a WASM shared library (missing dylink.0 section)`);
173
+ }
174
+ const memory = mainExports.memory;
175
+ const table = mainExports.__indirect_function_table;
176
+ const stackPointer = mainExports.__stack_pointer;
177
+ const mallocFn = mainExports.malloc;
178
+ if (!memory)
179
+ throw new Error("Main module does not export memory");
180
+ if (!table)
181
+ throw new Error("Main module does not export __indirect_function_table");
182
+ if (!mallocFn)
183
+ throw new Error("Main module does not export malloc");
184
+ let memoryBase;
185
+ let tableBase;
186
+ if (allocBase) {
187
+ memoryBase = allocBase.memoryBase;
188
+ tableBase = allocBase.tableBase;
189
+ } else {
190
+ if (dylink.memorySize > 0) {
191
+ memoryBase = mallocFn(dylink.memorySize);
192
+ if (memoryBase === 0) {
193
+ throw new Error(`Failed to allocate ${dylink.memorySize} bytes for extension "${descriptor.name}"`);
194
+ }
195
+ new Uint8Array(memory.buffer, memoryBase, dylink.memorySize).fill(0);
196
+ } else {
197
+ memoryBase = 0;
198
+ }
199
+ }
200
+ if (allocBase) {
201
+ tableBase = allocBase.tableBase;
202
+ if (tableBase + dylink.tableSize > table.length) {
203
+ table.grow(tableBase + dylink.tableSize - table.length);
204
+ }
205
+ } else {
206
+ tableBase = table.length;
207
+ if (dylink.tableSize > 0) {
208
+ table.grow(dylink.tableSize);
209
+ }
210
+ }
211
+ const extImports = WebAssembly.Module.imports(module);
212
+ const importObj = {
213
+ env: {},
214
+ "GOT.mem": {},
215
+ "GOT.func": {}
216
+ };
217
+ const needsWasi = extImports.some((imp) => imp.module === "wasi_snapshot_preview1");
218
+ if (needsWasi) {
219
+ const extWasi = descriptor.wasi && memoryProxy ? descriptor.wasi(memoryProxy) : undefined;
220
+ importObj["wasi_snapshot_preview1"] = {
221
+ ...wasiBuiltins,
222
+ ...extWasi,
223
+ ...wasiUserOverrides
224
+ };
225
+ }
226
+ const extExportNames = new Set(WebAssembly.Module.exports(module).filter((e) => e.kind === "function").map((e) => e.name));
227
+ const unresolvedFuncs = new Set;
228
+ for (const imp of extImports) {
229
+ if (imp.module === "env") {
230
+ if (imp.name === "memory" && imp.kind === "memory") {
231
+ importObj.env.memory = memory;
232
+ } else if (imp.name === "__indirect_function_table" && imp.kind === "table") {
233
+ importObj.env.__indirect_function_table = table;
234
+ } else if (imp.name === "__memory_base" && imp.kind === "global") {
235
+ importObj.env.__memory_base = new WebAssembly.Global({ value: "i32", mutable: false }, memoryBase);
236
+ } else if (imp.name === "__table_base" && imp.kind === "global") {
237
+ importObj.env.__table_base = new WebAssembly.Global({ value: "i32", mutable: false }, tableBase);
238
+ } else if (imp.name === "__stack_pointer" && imp.kind === "global") {
239
+ importObj.env.__stack_pointer = stackPointer;
240
+ } else if (imp.kind === "function") {
241
+ const resolved = mainExports[imp.name];
242
+ if (resolved && typeof resolved === "function") {
243
+ importObj.env[imp.name] = resolved;
244
+ } else {
245
+ unresolvedFuncs.add(imp.name);
246
+ importObj.env[imp.name] = () => {
247
+ throw new Error(`Extension "${descriptor.name}" called unresolved symbol: env.${imp.name}`);
248
+ };
249
+ }
250
+ } else if (imp.kind === "global") {
251
+ const resolved = mainExports[imp.name];
252
+ if (resolved instanceof WebAssembly.Global) {
253
+ importObj.env[imp.name] = resolved;
254
+ } else {
255
+ importObj.env[imp.name] = new WebAssembly.Global({ value: "i32", mutable: true }, 0);
256
+ }
257
+ }
258
+ } else if (imp.module === "GOT.mem" && imp.kind === "global") {
259
+ importObj["GOT.mem"][imp.name] = new WebAssembly.Global({ value: "i32", mutable: true }, 0);
260
+ } else if (imp.module === "GOT.func" && imp.kind === "global") {
261
+ const resolved = mainExports[imp.name];
262
+ if (resolved && typeof resolved === "function") {
263
+ const idx = table.length;
264
+ table.grow(1);
265
+ table.set(idx, resolved);
266
+ importObj["GOT.func"][imp.name] = new WebAssembly.Global({ value: "i32", mutable: true }, idx);
267
+ } else {
268
+ importObj["GOT.func"][imp.name] = new WebAssembly.Global({ value: "i32", mutable: true }, 0);
269
+ }
270
+ }
271
+ }
272
+ const selfResolvable = [...unresolvedFuncs].filter((name) => extExportNames.has(name));
273
+ const wrappers = {};
274
+ for (const name of selfResolvable) {
275
+ const wrapper = { target: null };
276
+ wrappers[name] = wrapper;
277
+ importObj.env[name] = (...args) => {
278
+ if (!wrapper.target) {
279
+ throw new Error(`Extension "${descriptor.name}" called unresolved symbol during init: env.${name}`);
280
+ }
281
+ return wrapper.target(...args);
282
+ };
283
+ }
284
+ const instance = await WebAssembly.instantiate(module, importObj);
285
+ const extExports = instance.exports;
286
+ for (const name of selfResolvable) {
287
+ const selfExport = extExports[name];
288
+ if (typeof selfExport === "function") {
289
+ wrappers[name].target = selfExport;
290
+ }
291
+ }
292
+ if (typeof extExports.__wasm_apply_data_relocs === "function") {
293
+ extExports.__wasm_apply_data_relocs();
294
+ }
295
+ if (typeof extExports.__wasm_call_ctors === "function") {
296
+ extExports.__wasm_call_ctors();
297
+ }
298
+ const initFn = descriptor.initFn ?? `qjs_ext_${descriptor.name.replace(/-/g, "_")}_init`;
299
+ const ext = {
300
+ name: descriptor.name,
301
+ module,
302
+ instance,
303
+ dylink,
304
+ memoryBase,
305
+ tableBase,
306
+ initFn
307
+ };
308
+ ext.versions = extractExtensionVersions(ext, memory);
309
+ return ext;
310
+ }
311
+ function initExtension(ext, mainExports) {
312
+ const initFunc = ext.instance.exports[ext.initFn];
313
+ if (typeof initFunc !== "function") {
314
+ throw new Error(`Extension "${ext.name}" does not export init function "${ext.initFn}"`);
315
+ }
316
+ const ctxPtr = mainExports.qjs_get_context_ptr();
317
+ const rtPtr = mainExports.qjs_get_runtime_ptr();
318
+ const result = initFunc(ctxPtr, rtPtr);
319
+ if (result !== 0) {
320
+ throw new Error(`Extension "${ext.name}" init function returned error code ${result}`);
321
+ }
322
+ }
323
+ async function restoreExtensions(descriptors, extensionMeta, mainExports, wasiBuiltins, wasiUserOverrides, memoryProxy) {
324
+ const loaded = [];
325
+ for (const meta of extensionMeta) {
326
+ const descriptor = descriptors.find((d) => d.name === meta.name);
327
+ if (!descriptor) {
328
+ throw new Error(`Extension "${meta.name}" required by snapshot but not provided`);
329
+ }
330
+ const ext = await loadExtension(descriptor, mainExports, wasiBuiltins, wasiUserOverrides, memoryProxy, {
331
+ memoryBase: meta.memoryBase,
332
+ tableBase: meta.tableBase
333
+ });
334
+ ext.initFn = meta.initFn;
335
+ loaded.push(ext);
336
+ }
337
+ return loaded;
338
+ }
339
+
340
+ // node_modules/quickjs-wasi/dist/version.js
341
+ var VERSION = "3.6.2";
342
+
343
+ // node_modules/quickjs-wasi/dist/index.js
344
+ var __addDisposableResource = function(env, value, async) {
345
+ if (value !== null && value !== undefined) {
346
+ if (typeof value !== "object" && typeof value !== "function")
347
+ throw new TypeError("Object expected.");
348
+ var dispose, inner;
349
+ if (async) {
350
+ if (!Symbol.asyncDispose)
351
+ throw new TypeError("Symbol.asyncDispose is not defined.");
352
+ dispose = value[Symbol.asyncDispose];
353
+ }
354
+ if (dispose === undefined) {
355
+ if (!Symbol.dispose)
356
+ throw new TypeError("Symbol.dispose is not defined.");
357
+ dispose = value[Symbol.dispose];
358
+ if (async)
359
+ inner = dispose;
360
+ }
361
+ if (typeof dispose !== "function")
362
+ throw new TypeError("Object not disposable.");
363
+ if (inner)
364
+ dispose = function() {
365
+ try {
366
+ inner.call(this);
367
+ } catch (e) {
368
+ return Promise.reject(e);
369
+ }
370
+ };
371
+ env.stack.push({ value, dispose, async });
372
+ } else if (async) {
373
+ env.stack.push({ async: true });
374
+ }
375
+ return value;
376
+ };
377
+ var __disposeResources = function(SuppressedError2) {
378
+ return function(env) {
379
+ function fail(e) {
380
+ env.error = env.hasError ? new SuppressedError2(e, env.error, "An error was suppressed during disposal.") : e;
381
+ env.hasError = true;
382
+ }
383
+ var r, s = 0;
384
+ function next() {
385
+ while (r = env.stack.pop()) {
386
+ try {
387
+ if (!r.async && s === 1)
388
+ return s = 0, env.stack.push(r), Promise.resolve().then(next);
389
+ if (r.dispose) {
390
+ var result = r.dispose.call(r.value);
391
+ if (r.async)
392
+ return s |= 2, Promise.resolve(result).then(next, function(e) {
393
+ fail(e);
394
+ return next();
395
+ });
396
+ } else
397
+ s |= 1;
398
+ } catch (e) {
399
+ fail(e);
400
+ }
401
+ }
402
+ if (s === 1)
403
+ return env.hasError ? Promise.reject(env.error) : Promise.resolve();
404
+ if (env.hasError)
405
+ throw env.error;
406
+ }
407
+ return next();
408
+ };
409
+ }(typeof SuppressedError === "function" ? SuppressedError : function(error, suppressed, message) {
410
+ var e = new Error(message);
411
+ return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
412
+ });
413
+ var MAX_STACK_SIZE = 512 * 1024;
414
+ var EvalFlags = {
415
+ TYPE_GLOBAL: 0,
416
+ TYPE_MODULE: 1 << 0,
417
+ STRICT: 1 << 3,
418
+ COMPILE_ONLY: 1 << 5,
419
+ BACKTRACE_BARRIER: 1 << 6,
420
+ ASYNC: 1 << 7
421
+ };
422
+ var CompileFlags = {
423
+ STRIP_SOURCE: 1 << 4,
424
+ STRIP_DEBUG: 1 << 5
425
+ };
426
+ var Intrinsics = {
427
+ DATE: 1 << 0,
428
+ EVAL: 1 << 1,
429
+ REGEXP: 1 << 2,
430
+ JSON: 1 << 3,
431
+ PROXY: 1 << 4,
432
+ MAP_SET: 1 << 5,
433
+ TYPED_ARRAYS: 1 << 6,
434
+ PROMISE: 1 << 7,
435
+ BIG_INT: 1 << 8,
436
+ WEAK_REF: 1 << 9,
437
+ PERFORMANCE: 1 << 10,
438
+ DOM_EXCEPTION: 1 << 11,
439
+ ATOB_BTOA: 1 << 12,
440
+ ALL: 4294967295
441
+ };
442
+ var SNAPSHOT_MAGIC = 1363825491;
443
+ var SNAPSHOT_VERSION = 2;
444
+ var SNAPSHOT_HEADER_SIZE = 24;
445
+
446
+ class QuickJS {
447
+ exports;
448
+ module;
449
+ instance;
450
+ encoder = new TextEncoder;
451
+ decoder = new TextDecoder;
452
+ disposed = false;
453
+ hostCallbacks = new Map;
454
+ nextInternalId = 1;
455
+ interruptHandler = null;
456
+ unhandledRejectionHandler = null;
457
+ moduleNormalizeHandler = null;
458
+ moduleLoadHandler = null;
459
+ timezoneOffsetHandler = null;
460
+ _global = null;
461
+ _versions = null;
462
+ _undefined = null;
463
+ _null = null;
464
+ _true = null;
465
+ _false = null;
466
+ _ownedHandles = new Set;
467
+ _activeScope = null;
468
+ loadedExtensions = [];
469
+ constructor(module) {
470
+ this.module = module;
471
+ this.instance = null;
472
+ this.exports = null;
473
+ }
474
+ setInstance(instance) {
475
+ this.instance = instance;
476
+ this.exports = instance.exports;
477
+ }
478
+ get versions() {
479
+ this.assertNotDisposed();
480
+ if (!this._versions) {
481
+ const result = {
482
+ "quickjs-wasi": VERSION,
483
+ quickjs: this.readCString(this.exports.qjs_get_quickjs_version())
484
+ };
485
+ for (const ext of this.loadedExtensions) {
486
+ if (ext.versions) {
487
+ Object.assign(result, ext.versions);
488
+ }
489
+ }
490
+ this._versions = result;
491
+ }
492
+ return this._versions;
493
+ }
494
+ get global() {
495
+ if (!this._global) {
496
+ this._global = new JSValueHandle(this, this.exports.qjs_get_global(), true);
497
+ }
498
+ return this._global;
499
+ }
500
+ get undefined() {
501
+ if (!this._undefined) {
502
+ this._undefined = new JSValueHandle(this, this.exports.qjs_get_undefined(), true);
503
+ }
504
+ return this._undefined;
505
+ }
506
+ get null() {
507
+ if (!this._null) {
508
+ this._null = new JSValueHandle(this, this.exports.qjs_get_null(), true);
509
+ }
510
+ return this._null;
511
+ }
512
+ get true() {
513
+ if (!this._true) {
514
+ this._true = new JSValueHandle(this, this.exports.qjs_get_true(), true);
515
+ }
516
+ return this._true;
517
+ }
518
+ get false() {
519
+ if (!this._false) {
520
+ this._false = new JSValueHandle(this, this.exports.qjs_get_false(), true);
521
+ }
522
+ return this._false;
523
+ }
524
+ static async create(options) {
525
+ const opts = QuickJS.normalizeOptions(options);
526
+ const module = await QuickJS.resolveModule(opts.wasm);
527
+ const vm = new QuickJS(module);
528
+ const { instance, wasiBuiltins, wasiUserOverrides, memoryProxy } = await QuickJS.instantiate(module, vm, opts.wasi);
529
+ vm.setInstance(instance);
530
+ vm.exports._initialize();
531
+ const result = opts.intrinsics !== undefined ? vm.exports.qjs_init2(opts.intrinsics) : vm.exports.qjs_init();
532
+ if (result !== 0) {
533
+ throw new Error("Failed to initialize QuickJS runtime");
534
+ }
535
+ if (opts.extensions) {
536
+ const mainExports = instance.exports;
537
+ for (const desc of opts.extensions) {
538
+ const ext = await loadExtension(desc, mainExports, wasiBuiltins, wasiUserOverrides, memoryProxy);
539
+ vm.loadedExtensions.push(ext);
540
+ initExtension(ext, mainExports);
541
+ }
542
+ }
543
+ QuickJS.applyLimits(vm, opts);
544
+ return vm;
545
+ }
546
+ static async restore(snapshot, options) {
547
+ const opts = QuickJS.normalizeOptions(options);
548
+ const module = await QuickJS.resolveModule(opts.wasm);
549
+ const vm = new QuickJS(module);
550
+ const { instance, wasiBuiltins, wasiUserOverrides, memoryProxy } = await QuickJS.instantiate(module, vm, opts.wasi);
551
+ vm.setInstance(instance);
552
+ const mainExports = instance.exports;
553
+ const exportedMemory = vm.exports.memory;
554
+ const currentPages = exportedMemory.buffer.byteLength / 65536;
555
+ const neededPages = Math.ceil(snapshot.memory.byteLength / 65536);
556
+ if (neededPages > currentPages) {
557
+ exportedMemory.grow(neededPages - currentPages);
558
+ }
559
+ if (snapshot.extensions.length > 0) {
560
+ const descriptors = opts.extensions ?? [];
561
+ vm.loadedExtensions = await restoreExtensions(descriptors, snapshot.extensions, mainExports, wasiBuiltins, wasiUserOverrides, memoryProxy);
562
+ }
563
+ const dst = new Uint8Array(exportedMemory.buffer);
564
+ dst.set(snapshot.memory);
565
+ vm.exports.qjs_set_runtime_and_context(snapshot.runtimePtr, snapshot.contextPtr);
566
+ vm.exports.__stack_pointer.value = snapshot.stackPointer;
567
+ QuickJS.applyLimits(vm, opts);
568
+ return vm;
569
+ }
570
+ static serializeSnapshot(snapshot) {
571
+ const textEncoder = new TextEncoder;
572
+ let extMetaSize = 4;
573
+ const extEncodedNames = [];
574
+ const extEncodedInitFns = [];
575
+ for (const ext of snapshot.extensions) {
576
+ const nameBytes = textEncoder.encode(ext.name);
577
+ const initFnBytes = textEncoder.encode(ext.initFn);
578
+ extEncodedNames.push(nameBytes);
579
+ extEncodedInitFns.push(initFnBytes);
580
+ extMetaSize += 4 + nameBytes.length + 4 + 4 + 4 + initFnBytes.length;
581
+ }
582
+ const totalSize = SNAPSHOT_HEADER_SIZE + extMetaSize + snapshot.memory.byteLength;
583
+ const buffer = new ArrayBuffer(totalSize);
584
+ const view = new DataView(buffer);
585
+ const bytes = new Uint8Array(buffer);
586
+ view.setUint32(0, SNAPSHOT_MAGIC, false);
587
+ view.setUint8(4, SNAPSHOT_VERSION);
588
+ view.setUint32(8, snapshot.memory.byteLength, true);
589
+ view.setUint32(12, snapshot.stackPointer, true);
590
+ view.setUint32(16, snapshot.runtimePtr, true);
591
+ view.setUint32(20, snapshot.contextPtr, true);
592
+ let offset = SNAPSHOT_HEADER_SIZE;
593
+ view.setUint32(offset, snapshot.extensions.length, true);
594
+ offset += 4;
595
+ for (let i = 0;i < snapshot.extensions.length; i++) {
596
+ const ext = snapshot.extensions[i];
597
+ const nameBytes = extEncodedNames[i];
598
+ const initFnBytes = extEncodedInitFns[i];
599
+ view.setUint32(offset, nameBytes.length, true);
600
+ offset += 4;
601
+ bytes.set(nameBytes, offset);
602
+ offset += nameBytes.length;
603
+ view.setUint32(offset, ext.memoryBase, true);
604
+ offset += 4;
605
+ view.setUint32(offset, ext.tableBase, true);
606
+ offset += 4;
607
+ view.setUint32(offset, initFnBytes.length, true);
608
+ offset += 4;
609
+ bytes.set(initFnBytes, offset);
610
+ offset += initFnBytes.length;
611
+ }
612
+ bytes.set(snapshot.memory, offset);
613
+ return bytes;
614
+ }
615
+ static deserializeSnapshot(data) {
616
+ if (data.length < SNAPSHOT_HEADER_SIZE) {
617
+ throw new Error("Invalid snapshot: too small");
618
+ }
619
+ const view = new DataView(data.buffer, data.byteOffset, data.byteLength);
620
+ const magic = view.getUint32(0, false);
621
+ if (magic !== SNAPSHOT_MAGIC) {
622
+ throw new Error(`Invalid snapshot: bad magic (expected 0x${SNAPSHOT_MAGIC.toString(16)}, got 0x${magic.toString(16)})`);
623
+ }
624
+ const version = view.getUint8(4);
625
+ if (version !== SNAPSHOT_VERSION && version !== 1) {
626
+ throw new Error(`Unsupported snapshot version: ${version} (expected ${SNAPSHOT_VERSION})`);
627
+ }
628
+ const memorySize = view.getUint32(8, true);
629
+ const stackPointer = view.getUint32(12, true);
630
+ const runtimePtr = view.getUint32(16, true);
631
+ const contextPtr = view.getUint32(20, true);
632
+ let extensions = [];
633
+ let memoryOffset = SNAPSHOT_HEADER_SIZE;
634
+ if (version >= 2) {
635
+ const extCount = view.getUint32(24, true);
636
+ let offset = 28;
637
+ const textDecoder = new TextDecoder;
638
+ for (let i = 0;i < extCount; i++) {
639
+ const nameLen = view.getUint32(offset, true);
640
+ offset += 4;
641
+ const name = textDecoder.decode(data.slice(offset, offset + nameLen));
642
+ offset += nameLen;
643
+ const memBase = view.getUint32(offset, true);
644
+ offset += 4;
645
+ const tblBase = view.getUint32(offset, true);
646
+ offset += 4;
647
+ const initFnLen = view.getUint32(offset, true);
648
+ offset += 4;
649
+ const initFn = textDecoder.decode(data.slice(offset, offset + initFnLen));
650
+ offset += initFnLen;
651
+ extensions.push({ name, memoryBase: memBase, tableBase: tblBase, initFn });
652
+ }
653
+ memoryOffset = offset;
654
+ }
655
+ const expectedSize = memoryOffset + memorySize;
656
+ if (data.length < expectedSize) {
657
+ throw new Error(`Invalid snapshot: expected ${expectedSize} bytes, got ${data.length}`);
658
+ }
659
+ const memory = data.slice(memoryOffset, memoryOffset + memorySize);
660
+ return { memory, stackPointer, runtimePtr, contextPtr, extensions };
661
+ }
662
+ static normalizeOptions(options) {
663
+ if (!options) {
664
+ return { wasm: undefined };
665
+ }
666
+ if (options instanceof WebAssembly.Module)
667
+ return { wasm: options };
668
+ if (typeof options === "object" && (("wasm" in options) || ("wasi" in options) || ("memoryLimit" in options) || ("maxStackSize" in options) || ("interruptHandler" in options) || ("onUnhandledRejection" in options) || ("moduleLoader" in options) || ("intrinsics" in options) || ("extensions" in options) || ("timezoneOffset" in options))) {
669
+ const opts = options;
670
+ if (opts.maxStackSize !== undefined && (!Number.isInteger(opts.maxStackSize) || opts.maxStackSize < 0 || opts.maxStackSize > MAX_STACK_SIZE)) {
671
+ throw new RangeError(`maxStackSize must be an integer between 0 and ${MAX_STACK_SIZE}`);
672
+ }
673
+ return opts;
674
+ }
675
+ return { wasm: options };
676
+ }
677
+ static applyLimits(vm, opts) {
678
+ if (opts.memoryLimit !== undefined) {
679
+ vm.exports.qjs_set_memory_limit(opts.memoryLimit);
680
+ }
681
+ if (opts.maxStackSize !== undefined) {
682
+ vm.exports.qjs_set_max_stack_size(opts.maxStackSize);
683
+ }
684
+ if (opts.interruptHandler) {
685
+ vm.interruptHandler = opts.interruptHandler;
686
+ vm.exports.qjs_set_interrupt_handler(1);
687
+ }
688
+ if (opts.onUnhandledRejection) {
689
+ vm.unhandledRejectionHandler = opts.onUnhandledRejection;
690
+ vm.exports.qjs_set_promise_rejection_handler(1);
691
+ }
692
+ if (opts.moduleLoader) {
693
+ vm.moduleLoadHandler = opts.moduleLoader.load;
694
+ vm.moduleNormalizeHandler = opts.moduleLoader.normalize ?? null;
695
+ vm.exports.qjs_set_module_loader(1);
696
+ }
697
+ const tz = opts.timezoneOffset;
698
+ if (typeof tz === "function") {
699
+ vm.timezoneOffsetHandler = (timeSecs) => -tz(timeSecs) * 60;
700
+ } else if (typeof tz === "number") {
701
+ const offsetSecs = -tz * 60;
702
+ vm.timezoneOffsetHandler = () => offsetSecs;
703
+ } else {
704
+ vm.timezoneOffsetHandler = (timeSecs) => {
705
+ return -new Date(timeSecs * 1000).getTimezoneOffset() * 60;
706
+ };
707
+ }
708
+ }
709
+ static async resolveModule(wasmInput) {
710
+ if (wasmInput instanceof WebAssembly.Module) {
711
+ return wasmInput;
712
+ }
713
+ if (wasmInput) {
714
+ return WebAssembly.compile(wasmInput);
715
+ }
716
+ throw new TypeError("QuickJS: `wasm` option is required. Provide WASM bytes or a compiled " + "`WebAssembly.Module`. The binary is shipped at `quickjs-wasi/quickjs.wasm` " + "and can be loaded via your environment's preferred mechanism (e.g. " + "`fetch()`, `node:fs/promises`, or a bundler import like Vite's `?url`).");
717
+ }
718
+ static async instantiate(module, vm, wasiOptions) {
719
+ let memory = null;
720
+ const memoryProxy = new Proxy({}, {
721
+ get(_target, prop) {
722
+ return memory[prop];
723
+ }
724
+ });
725
+ const wasiBuiltins = createWasiShim(() => memory);
726
+ const wasiUserOverrides = wasiOptions ? wasiOptions(memoryProxy) : undefined;
727
+ const wasiShim = { ...wasiBuiltins, ...wasiUserOverrides };
728
+ const hostCall = (namePtr, nameLen, thisPtr, argc, argvPtr) => {
729
+ return vm.handleHostCall(namePtr, nameLen, thisPtr, argc, argvPtr);
730
+ };
731
+ const hostInterrupt = () => {
732
+ return vm.interruptHandler ? vm.interruptHandler() ? 1 : 0 : 0;
733
+ };
734
+ const hostPromiseRejection = (promisePtr, reasonPtr, isHandled) => {
735
+ if (!vm.unhandledRejectionHandler) {
736
+ vm.exports.qjs_free_value(promisePtr);
737
+ vm.exports.qjs_free_value(reasonPtr);
738
+ return;
739
+ }
740
+ const promise = new JSValueHandle(vm, promisePtr);
741
+ const reason = new JSValueHandle(vm, reasonPtr);
742
+ try {
743
+ vm.unhandledRejectionHandler(promise, reason, isHandled !== 0);
744
+ } finally {
745
+ promise.dispose();
746
+ reason.dispose();
747
+ }
748
+ };
749
+ const throwIntoContext = (err) => {
750
+ const errHandle = vm.newError(err instanceof Error ? err : String(err));
751
+ vm.exports.qjs_throw(errHandle.ptr);
752
+ errHandle.dispose();
753
+ };
754
+ const assertSyncString = (value, callbackName) => {
755
+ if (typeof value === "string")
756
+ return value;
757
+ const got = value !== null && typeof value === "object" && typeof value.then === "function" ? "a Promise" : `type ${typeof value}`;
758
+ throw new TypeError(`moduleLoader.${callbackName} must synchronously return a string (got ${got}). ` + `Async module loading is not supported. Pre-fetch module sources instead ` + `(see the "ES Modules" section of the quickjs-wasi README).`);
759
+ };
760
+ const hostModuleNormalize = (baseNamePtr, namePtr) => {
761
+ if (!vm.moduleNormalizeHandler) {
762
+ const name = vm.readCString(namePtr);
763
+ return vm.writeString(name).ptr;
764
+ }
765
+ const baseName = vm.readCString(baseNamePtr);
766
+ const specifier = vm.readCString(namePtr);
767
+ try {
768
+ const normalized = assertSyncString(vm.moduleNormalizeHandler(baseName, specifier), "normalize");
769
+ return vm.writeString(normalized).ptr;
770
+ } catch (err) {
771
+ throwIntoContext(err);
772
+ return 0;
773
+ }
774
+ };
775
+ const hostModuleLoad = (namePtr, outLenPtr) => {
776
+ if (!vm.moduleLoadHandler)
777
+ return 0;
778
+ const name = vm.readCString(namePtr);
779
+ try {
780
+ const source = assertSyncString(vm.moduleLoadHandler(name), "load");
781
+ const { ptr, len } = vm.writeString(source);
782
+ new Uint32Array(vm.exports.memory.buffer, outLenPtr, 1)[0] = len;
783
+ return ptr;
784
+ } catch (err) {
785
+ throwIntoContext(err);
786
+ return 0;
787
+ }
788
+ };
789
+ const hostGetTimezoneOffset = (hi, lo) => {
790
+ const timeSecs = Number(BigInt(hi) << 32n | BigInt(lo >>> 0));
791
+ return vm.timezoneOffsetHandler ? vm.timezoneOffsetHandler(timeSecs) : 0;
792
+ };
793
+ const instance = await WebAssembly.instantiate(module, {
794
+ env: {
795
+ host_call: hostCall,
796
+ host_interrupt: hostInterrupt,
797
+ host_promise_rejection: hostPromiseRejection,
798
+ host_module_normalize: hostModuleNormalize,
799
+ host_module_load: hostModuleLoad,
800
+ host_get_timezone_offset: hostGetTimezoneOffset
801
+ },
802
+ wasi_snapshot_preview1: wasiShim
803
+ });
804
+ memory = instance.exports.memory;
805
+ return { instance, wasiBuiltins, wasiUserOverrides, memoryProxy };
806
+ }
807
+ handleHostCall(namePtr, nameLen, thisPtr, argc, argvPtr) {
808
+ const name = this.decoder.decode(new Uint8Array(this.exports.memory.buffer, namePtr, nameLen));
809
+ const callback = this.hostCallbacks.get(name);
810
+ if (!callback) {
811
+ const errHandle = this.newError(`Host callback "${name}" is not registered: it was unregistered, ` + "its ephemeral function handle was disposed, or it was never " + "re-registered after a snapshot restore.");
812
+ this.exports.qjs_throw(errHandle.ptr);
813
+ errHandle.dispose();
814
+ return 0;
815
+ }
816
+ const thisHandle = new JSValueHandle(this, thisPtr, false, true);
817
+ const args = [];
818
+ if (argc > 0 && argvPtr !== 0) {
819
+ const view = new DataView(this.exports.memory.buffer);
820
+ for (let i = 0;i < argc; i++) {
821
+ const argPtr = view.getUint32(argvPtr + i * 4, true);
822
+ args.push(new JSValueHandle(this, argPtr, false, true));
823
+ }
824
+ }
825
+ try {
826
+ const result = callback.call(thisHandle, ...args);
827
+ return this.exports.qjs_dup_value(result.ptr);
828
+ } catch (err) {
829
+ const errHandle = this.newError(err instanceof Error ? err : String(err));
830
+ this.exports.qjs_throw(errHandle.ptr);
831
+ errHandle.dispose();
832
+ return 0;
833
+ }
834
+ }
835
+ writeString(str) {
836
+ const encoded = encodeWtf8(str);
837
+ const ptr = this.exports.wasm_malloc(encoded.length + 1);
838
+ if (ptr === 0)
839
+ throw new Error("wasm_malloc failed");
840
+ const mem = new Uint8Array(this.exports.memory.buffer);
841
+ mem.set(encoded, ptr);
842
+ mem[ptr + encoded.length] = 0;
843
+ return { ptr, len: encoded.length };
844
+ }
845
+ readCString(ptr) {
846
+ const mem = new Uint8Array(this.exports.memory.buffer);
847
+ let end = ptr;
848
+ while (mem[end] !== 0)
849
+ end++;
850
+ return this.decoder.decode(mem.slice(ptr, end));
851
+ }
852
+ throwIfException(result) {
853
+ if (this.exports.qjs_is_exception(result.ptr) !== 0) {
854
+ const exc = this.getException();
855
+ result.dispose();
856
+ this._ownedHandles.add(exc);
857
+ throw new JSException(exc);
858
+ }
859
+ return result;
860
+ }
861
+ evalCode(code, filename = "<eval>", flags = 0) {
862
+ this.assertNotDisposed();
863
+ const codeStr = this.writeString(code);
864
+ const fnStr = this.writeString(filename);
865
+ const resultPtr = this.exports.qjs_eval(codeStr.ptr, codeStr.len, fnStr.ptr, flags);
866
+ this.exports.wasm_free(codeStr.ptr);
867
+ this.exports.wasm_free(fnStr.ptr);
868
+ return this.throwIfException(new JSValueHandle(this, resultPtr));
869
+ }
870
+ compile(code, filename = "<compile>", evalFlags = 0, compileFlags = 0) {
871
+ this.assertNotDisposed();
872
+ const codeStr = this.writeString(code);
873
+ const fnStr = this.writeString(filename);
874
+ const outLenPtr = this.exports.wasm_malloc(4);
875
+ const bufPtr = this.exports.qjs_compile(codeStr.ptr, codeStr.len, fnStr.ptr, evalFlags, compileFlags, outLenPtr);
876
+ this.exports.wasm_free(codeStr.ptr);
877
+ this.exports.wasm_free(fnStr.ptr);
878
+ if (bufPtr === 0) {
879
+ this.exports.wasm_free(outLenPtr);
880
+ const exc = this.getException();
881
+ throw new Error(`Compilation error: ${exc.toString()}`);
882
+ }
883
+ const outLen = new Uint32Array(this.exports.memory.buffer, outLenPtr, 1)[0];
884
+ this.exports.wasm_free(outLenPtr);
885
+ const bytecode = new Uint8Array(this.exports.memory.buffer, bufPtr, outLen).slice();
886
+ this.exports.wasm_free(bufPtr);
887
+ return bytecode;
888
+ }
889
+ evalBytecode(bytecode) {
890
+ this.assertNotDisposed();
891
+ const bufPtr = this.exports.wasm_malloc(bytecode.byteLength);
892
+ new Uint8Array(this.exports.memory.buffer, bufPtr, bytecode.byteLength).set(bytecode);
893
+ const resultPtr = this.exports.qjs_eval_bytecode(bufPtr, bytecode.byteLength);
894
+ this.exports.wasm_free(bufPtr);
895
+ return this.throwIfException(new JSValueHandle(this, resultPtr));
896
+ }
897
+ executePendingJobs() {
898
+ this.assertNotDisposed();
899
+ let count = 0;
900
+ while (this.exports.qjs_is_job_pending()) {
901
+ const result = this.exports.qjs_execute_pending_job();
902
+ if (result < 0) {
903
+ const exc = this.getException();
904
+ throw new Error(`Job execution error: ${exc.toString()}`);
905
+ }
906
+ count++;
907
+ }
908
+ return count;
909
+ }
910
+ runGC() {
911
+ this.assertNotDisposed();
912
+ this.exports.qjs_run_gc();
913
+ }
914
+ get gcThreshold() {
915
+ this.assertNotDisposed();
916
+ return this.exports.qjs_get_gc_threshold();
917
+ }
918
+ set gcThreshold(threshold) {
919
+ this.assertNotDisposed();
920
+ this.exports.qjs_set_gc_threshold(threshold);
921
+ }
922
+ getMemoryUsage() {
923
+ this.assertNotDisposed();
924
+ const bufPtr = this.exports.wasm_malloc(26 * 8);
925
+ this.exports.qjs_compute_memory_usage(bufPtr);
926
+ const view = new BigInt64Array(this.exports.memory.buffer, bufPtr, 26);
927
+ const result = {
928
+ mallocSize: Number(view[0]),
929
+ mallocLimit: Number(view[1]),
930
+ memoryUsedSize: Number(view[2]),
931
+ mallocCount: Number(view[3]),
932
+ memoryUsedCount: Number(view[4]),
933
+ atomCount: Number(view[5]),
934
+ atomSize: Number(view[6]),
935
+ strCount: Number(view[7]),
936
+ strSize: Number(view[8]),
937
+ objCount: Number(view[9]),
938
+ objSize: Number(view[10]),
939
+ propCount: Number(view[11]),
940
+ propSize: Number(view[12]),
941
+ shapeCount: Number(view[13]),
942
+ shapeSize: Number(view[14]),
943
+ jsFuncCount: Number(view[15]),
944
+ jsFuncSize: Number(view[16]),
945
+ jsFuncCodeSize: Number(view[17]),
946
+ jsFuncPc2lineCount: Number(view[18]),
947
+ jsFuncPc2lineSize: Number(view[19]),
948
+ cFuncCount: Number(view[20]),
949
+ arrayCount: Number(view[21]),
950
+ fastArrayCount: Number(view[22]),
951
+ fastArrayElements: Number(view[23]),
952
+ binaryObjectCount: Number(view[24]),
953
+ binaryObjectSize: Number(view[25])
954
+ };
955
+ this.exports.wasm_free(bufPtr);
956
+ return result;
957
+ }
958
+ getGlobal() {
959
+ this.assertNotDisposed();
960
+ return new JSValueHandle(this, this.exports.qjs_get_global());
961
+ }
962
+ newString(str) {
963
+ this.assertNotDisposed();
964
+ const { ptr, len } = this.writeString(str);
965
+ const resultPtr = this.exports.qjs_new_string(ptr, len);
966
+ this.exports.wasm_free(ptr);
967
+ return new JSValueHandle(this, resultPtr);
968
+ }
969
+ newNumber(num) {
970
+ this.assertNotDisposed();
971
+ return new JSValueHandle(this, this.exports.qjs_new_number(num));
972
+ }
973
+ newBigInt(val) {
974
+ this.assertNotDisposed();
975
+ const lo = Number(val & 0xffffffffn);
976
+ const hi = Number(val >> 32n & 0xffffffffn);
977
+ return new JSValueHandle(this, this.exports.qjs_new_big_int64(lo, hi));
978
+ }
979
+ newObject() {
980
+ this.assertNotDisposed();
981
+ return new JSValueHandle(this, this.exports.qjs_new_object());
982
+ }
983
+ newArray() {
984
+ this.assertNotDisposed();
985
+ return new JSValueHandle(this, this.exports.qjs_new_array());
986
+ }
987
+ newSymbolFor(description) {
988
+ this.assertNotDisposed();
989
+ const { ptr, len } = this.writeString(description);
990
+ const result = new JSValueHandle(this, this.exports.qjs_new_symbol(ptr, len, 1));
991
+ this.exports.wasm_free(ptr);
992
+ return result;
993
+ }
994
+ newArrayBuffer(data) {
995
+ this.assertNotDisposed();
996
+ const bytes = data instanceof ArrayBuffer ? new Uint8Array(data) : data;
997
+ const ptr = this.exports.wasm_malloc(bytes.length);
998
+ if (ptr === 0)
999
+ throw new Error("wasm_malloc failed");
1000
+ new Uint8Array(this.exports.memory.buffer).set(bytes, ptr);
1001
+ const result = new JSValueHandle(this, this.exports.qjs_new_array_buffer(ptr, bytes.length));
1002
+ this.exports.wasm_free(ptr);
1003
+ return result;
1004
+ }
1005
+ newUint8Array(data) {
1006
+ this.assertNotDisposed();
1007
+ const ptr = this.exports.wasm_malloc(data.length);
1008
+ if (ptr === 0)
1009
+ throw new Error("wasm_malloc failed");
1010
+ new Uint8Array(this.exports.memory.buffer).set(data, ptr);
1011
+ const result = new JSValueHandle(this, this.exports.qjs_new_uint8_array(ptr, data.length));
1012
+ this.exports.wasm_free(ptr);
1013
+ return result;
1014
+ }
1015
+ getUndefined() {
1016
+ this.assertNotDisposed();
1017
+ return new JSValueHandle(this, this.exports.qjs_get_undefined());
1018
+ }
1019
+ getNull() {
1020
+ this.assertNotDisposed();
1021
+ return new JSValueHandle(this, this.exports.qjs_get_null());
1022
+ }
1023
+ getTrue() {
1024
+ this.assertNotDisposed();
1025
+ return new JSValueHandle(this, this.exports.qjs_get_true());
1026
+ }
1027
+ getFalse() {
1028
+ this.assertNotDisposed();
1029
+ return new JSValueHandle(this, this.exports.qjs_get_false());
1030
+ }
1031
+ newFunction(name, fn) {
1032
+ this.assertNotDisposed();
1033
+ if (this.hostCallbacks.has(name)) {
1034
+ throw new Error(`Host callback with name "${name}" is already registered`);
1035
+ }
1036
+ this.hostCallbacks.set(name, fn);
1037
+ const { ptr: namePtr, len: nameLen } = this.writeString(name);
1038
+ const resultPtr = this.exports.qjs_new_host_function(namePtr, nameLen, 0);
1039
+ this.exports.wasm_free(namePtr);
1040
+ return new JSValueHandle(this, resultPtr);
1041
+ }
1042
+ withScope(fn) {
1043
+ this.assertNotDisposed();
1044
+ const enclosing = this._activeScope;
1045
+ const tracked = new Set;
1046
+ this._activeScope = tracked;
1047
+ const scope = {
1048
+ escape: (handle) => {
1049
+ tracked.delete(handle);
1050
+ enclosing?.add(handle);
1051
+ return handle;
1052
+ }
1053
+ };
1054
+ try {
1055
+ return fn(scope);
1056
+ } finally {
1057
+ this._activeScope = enclosing;
1058
+ for (const handle of tracked)
1059
+ handle.dispose();
1060
+ }
1061
+ }
1062
+ exportHandle(handle) {
1063
+ this.assertNotDisposed();
1064
+ if (handle.vm !== this) {
1065
+ throw new Error("exportHandle: handle belongs to a different VM");
1066
+ }
1067
+ if (handle.disposed) {
1068
+ throw new Error("exportHandle: handle is disposed");
1069
+ }
1070
+ if (handle._isBorrowed) {
1071
+ throw new Error("exportHandle: cannot export a borrowed handle (host-callback " + "this/argument); its box is freed when the callback returns. " + "dup() it and export the duplicate.");
1072
+ }
1073
+ return handle.ptr;
1074
+ }
1075
+ importHandle(token) {
1076
+ this.assertNotDisposed();
1077
+ if (!Number.isInteger(token) || token <= 0 || token >= this.exports.memory.buffer.byteLength) {
1078
+ throw new Error(`importHandle: invalid token ${token}`);
1079
+ }
1080
+ return new JSValueHandle(this, this.exports.qjs_dup_value(token));
1081
+ }
1082
+ newEphemeralFunction(fn) {
1083
+ this.assertNotDisposed();
1084
+ const name = `__ephemeral:${this.nextInternalId++}`;
1085
+ this.hostCallbacks.set(name, fn);
1086
+ const { ptr: namePtr, len: nameLen } = this.writeString(name);
1087
+ const resultPtr = this.exports.qjs_new_host_function(namePtr, nameLen, 0);
1088
+ this.exports.wasm_free(namePtr);
1089
+ const handle = new JSValueHandle(this, resultPtr);
1090
+ handle._onDispose = () => {
1091
+ this.hostCallbacks.delete(name);
1092
+ };
1093
+ return handle;
1094
+ }
1095
+ unregisterHostCallback(name) {
1096
+ return this.hostCallbacks.delete(name);
1097
+ }
1098
+ newInternalFunction(name, fn) {
1099
+ this.hostCallbacks.set(name, fn);
1100
+ const { ptr: namePtr, len: nameLen } = this.writeString(name);
1101
+ const resultPtr = this.exports.qjs_new_host_function(namePtr, nameLen, 0);
1102
+ this.exports.wasm_free(namePtr);
1103
+ return new JSValueHandle(this, resultPtr);
1104
+ }
1105
+ newPromise() {
1106
+ this.assertNotDisposed();
1107
+ const resolveOutPtr = this.exports.wasm_malloc(4);
1108
+ const rejectOutPtr = this.exports.wasm_malloc(4);
1109
+ const promisePtr = this.exports.qjs_new_promise(resolveOutPtr, rejectOutPtr);
1110
+ const view = new DataView(this.exports.memory.buffer);
1111
+ const resolvePtr = view.getUint32(resolveOutPtr, true);
1112
+ const rejectPtr = view.getUint32(rejectOutPtr, true);
1113
+ this.exports.wasm_free(resolveOutPtr);
1114
+ this.exports.wasm_free(rejectOutPtr);
1115
+ const promiseHandle = new JSValueHandle(this, promisePtr);
1116
+ const resolveHandle = new JSValueHandle(this, resolvePtr);
1117
+ const rejectHandle = new JSValueHandle(this, rejectPtr);
1118
+ const vm = this;
1119
+ vm._ownedHandles.add(resolveHandle);
1120
+ vm._ownedHandles.add(rejectHandle);
1121
+ let _settled = null;
1122
+ return {
1123
+ handle: promiseHandle,
1124
+ get settled() {
1125
+ if (!_settled) {
1126
+ let settledResolve;
1127
+ _settled = new Promise((res) => {
1128
+ settledResolve = res;
1129
+ });
1130
+ const settleName = `__settle:${vm.nextInternalId++}`;
1131
+ const onSettleFn = vm.newInternalFunction(settleName, () => {
1132
+ settledResolve();
1133
+ vm.hostCallbacks.delete(settleName);
1134
+ return vm.undefined;
1135
+ });
1136
+ vm.promiseThenRaw(promiseHandle, onSettleFn, onSettleFn).dispose();
1137
+ onSettleFn.dispose();
1138
+ }
1139
+ return _settled;
1140
+ },
1141
+ resolve(value) {
1142
+ vm.callFunctionRaw(resolveHandle, vm.undefined, value).dispose();
1143
+ vm._ownedHandles.delete(resolveHandle);
1144
+ resolveHandle.dispose();
1145
+ },
1146
+ reject(value) {
1147
+ vm.callFunctionRaw(rejectHandle, vm.undefined, value).dispose();
1148
+ vm._ownedHandles.delete(rejectHandle);
1149
+ rejectHandle.dispose();
1150
+ }
1151
+ };
1152
+ }
1153
+ resolvePromise(promiseHandle) {
1154
+ this.assertNotDisposed();
1155
+ if (!this.exports.qjs_is_promise(promiseHandle.ptr)) {
1156
+ return Promise.resolve({ value: promiseHandle.dup() });
1157
+ }
1158
+ const state = this.exports.qjs_promise_state(promiseHandle.ptr);
1159
+ if (state === 1) {
1160
+ return Promise.resolve({ value: new JSValueHandle(this, this.exports.qjs_promise_result(promiseHandle.ptr)) });
1161
+ } else if (state === 2) {
1162
+ return Promise.resolve({ error: new JSValueHandle(this, this.exports.qjs_promise_result(promiseHandle.ptr)) });
1163
+ }
1164
+ return new Promise((hostResolve) => {
1165
+ const id = this.nextInternalId++;
1166
+ const fulfilledName = `__onFulfilled:${id}`;
1167
+ const rejectedName = `__onRejected:${id}`;
1168
+ const onFulfilled = this.newInternalFunction(fulfilledName, (...args) => {
1169
+ const val = args[0]?.dup() ?? this.undefined;
1170
+ this.hostCallbacks.delete(fulfilledName);
1171
+ this.hostCallbacks.delete(rejectedName);
1172
+ hostResolve({ value: val });
1173
+ return this.undefined;
1174
+ });
1175
+ const onRejected = this.newInternalFunction(rejectedName, (...args) => {
1176
+ const val = args[0]?.dup() ?? this.undefined;
1177
+ this.hostCallbacks.delete(fulfilledName);
1178
+ this.hostCallbacks.delete(rejectedName);
1179
+ hostResolve({ error: val });
1180
+ return this.undefined;
1181
+ });
1182
+ this.promiseThenRaw(promiseHandle, onFulfilled, onRejected).dispose();
1183
+ onFulfilled.dispose();
1184
+ onRejected.dispose();
1185
+ });
1186
+ }
1187
+ promiseThenRaw(promise, onFulfilled, onRejected) {
1188
+ return new JSValueHandle(this, this.exports.qjs_promise_then(promise.ptr, onFulfilled.ptr, onRejected.ptr));
1189
+ }
1190
+ markPromiseHandled(promise) {
1191
+ this.assertNotDisposed();
1192
+ this.exports.qjs_promise_mark_as_handled(promise.ptr);
1193
+ }
1194
+ callFunction(func, thisVal, ...args) {
1195
+ return this.throwIfException(this.callFunctionRaw(func, thisVal, ...args));
1196
+ }
1197
+ construct(ctor, ...args) {
1198
+ this.assertNotDisposed();
1199
+ const argc = args.length;
1200
+ let argvPtr = 0;
1201
+ if (argc > 0) {
1202
+ argvPtr = this.exports.wasm_malloc(argc * 4);
1203
+ const view = new DataView(this.exports.memory.buffer);
1204
+ for (let i = 0;i < argc; i++) {
1205
+ view.setUint32(argvPtr + i * 4, args[i].ptr, true);
1206
+ }
1207
+ }
1208
+ const resultPtr = this.exports.qjs_call_constructor(ctor.ptr, argc, argvPtr);
1209
+ if (argvPtr)
1210
+ this.exports.wasm_free(argvPtr);
1211
+ return this.throwIfException(new JSValueHandle(this, resultPtr));
1212
+ }
1213
+ callFunctionRaw(func, thisVal, ...args) {
1214
+ this.assertNotDisposed();
1215
+ const argc = args.length;
1216
+ let argvPtr = 0;
1217
+ if (argc > 0) {
1218
+ argvPtr = this.exports.wasm_malloc(argc * 4);
1219
+ const view = new DataView(this.exports.memory.buffer);
1220
+ for (let i = 0;i < argc; i++) {
1221
+ view.setUint32(argvPtr + i * 4, args[i].ptr, true);
1222
+ }
1223
+ }
1224
+ const resultPtr = this.exports.qjs_call(func.ptr, thisVal.ptr, argc, argvPtr);
1225
+ if (argvPtr)
1226
+ this.exports.wasm_free(argvPtr);
1227
+ return new JSValueHandle(this, resultPtr);
1228
+ }
1229
+ setProp(obj, key, value) {
1230
+ this.assertNotDisposed();
1231
+ if (typeof key === "string") {
1232
+ const { ptr: namePtr } = this.writeString(key);
1233
+ this.exports.qjs_set_prop_string(obj.ptr, namePtr, value.ptr);
1234
+ this.exports.wasm_free(namePtr);
1235
+ } else {
1236
+ this.exports.qjs_set_prop_value(obj.ptr, key.ptr, value.ptr);
1237
+ }
1238
+ }
1239
+ defineProp(obj, key, value, descriptor) {
1240
+ this.assertNotDisposed();
1241
+ let flags = 0;
1242
+ if (descriptor?.configurable)
1243
+ flags |= 1;
1244
+ if (descriptor?.writable)
1245
+ flags |= 2;
1246
+ if (descriptor?.enumerable)
1247
+ flags |= 4;
1248
+ if (typeof key === "string") {
1249
+ const { ptr: namePtr } = this.writeString(key);
1250
+ this.exports.qjs_define_prop_string(obj.ptr, namePtr, value.ptr, flags);
1251
+ this.exports.wasm_free(namePtr);
1252
+ } else {
1253
+ this.exports.qjs_define_prop_value(obj.ptr, key.ptr, value.ptr, flags);
1254
+ }
1255
+ }
1256
+ getProp(obj, key) {
1257
+ this.assertNotDisposed();
1258
+ return new JSValueHandle(this, this.exports.qjs_get_prop_value(obj.ptr, key.ptr));
1259
+ }
1260
+ getException() {
1261
+ this.assertNotDisposed();
1262
+ return new JSValueHandle(this, this.exports.qjs_get_exception());
1263
+ }
1264
+ newError(messageOrError) {
1265
+ this.assertNotDisposed();
1266
+ const errPtr = this.exports.qjs_new_error();
1267
+ const errHandle = new JSValueHandle(this, errPtr);
1268
+ if (typeof messageOrError === "string") {
1269
+ const msgHandle = this.newString(messageOrError);
1270
+ errHandle.setProp("message", msgHandle);
1271
+ msgHandle.dispose();
1272
+ } else {
1273
+ const msgHandle = this.newString(messageOrError.message);
1274
+ errHandle.setProp("message", msgHandle);
1275
+ msgHandle.dispose();
1276
+ if (messageOrError.name) {
1277
+ const nameHandle = this.newString(messageOrError.name);
1278
+ errHandle.setProp("name", nameHandle);
1279
+ nameHandle.dispose();
1280
+ }
1281
+ if (messageOrError.stack) {
1282
+ const stackHandle = this.newString(messageOrError.stack);
1283
+ errHandle.setProp("stack", stackHandle);
1284
+ stackHandle.dispose();
1285
+ }
1286
+ }
1287
+ return errHandle;
1288
+ }
1289
+ typeof(handle) {
1290
+ this.assertNotDisposed();
1291
+ const e = this.exports;
1292
+ if (e.qjs_is_undefined(handle.ptr))
1293
+ return "undefined";
1294
+ if (e.qjs_is_null(handle.ptr))
1295
+ return "object";
1296
+ if (e.qjs_is_bool(handle.ptr))
1297
+ return "boolean";
1298
+ if (e.qjs_is_number(handle.ptr))
1299
+ return "number";
1300
+ if (e.qjs_is_big_int(handle.ptr))
1301
+ return "bigint";
1302
+ if (e.qjs_is_string(handle.ptr))
1303
+ return "string";
1304
+ if (e.qjs_is_symbol(handle.ptr))
1305
+ return "symbol";
1306
+ if (e.qjs_is_function(handle.ptr))
1307
+ return "function";
1308
+ if (e.qjs_is_object(handle.ptr))
1309
+ return "object";
1310
+ return "unknown";
1311
+ }
1312
+ dump(handle) {
1313
+ this.assertNotDisposed();
1314
+ return this._dump(handle, new Map);
1315
+ }
1316
+ _dump(handle, visited) {
1317
+ const e = this.exports;
1318
+ if (e.qjs_is_undefined(handle.ptr))
1319
+ return;
1320
+ if (e.qjs_is_null(handle.ptr))
1321
+ return null;
1322
+ if (e.qjs_is_bool(handle.ptr))
1323
+ return e.qjs_get_bool(handle.ptr) !== 0;
1324
+ if (e.qjs_is_number(handle.ptr))
1325
+ return e.qjs_get_float64(handle.ptr);
1326
+ if (e.qjs_is_string(handle.ptr))
1327
+ return handle.toString();
1328
+ if (e.qjs_is_big_int(handle.ptr))
1329
+ return handle.toBigInt();
1330
+ if (e.qjs_is_symbol(handle.ptr)) {
1331
+ const descOutPtr = e.wasm_malloc(4);
1332
+ const kind = e.qjs_get_symbol_description(handle.ptr, descOutPtr);
1333
+ const view = new DataView(e.memory.buffer);
1334
+ const descPtr = view.getUint32(descOutPtr, true);
1335
+ e.wasm_free(descOutPtr);
1336
+ if (kind === 1) {
1337
+ const descHandle = new JSValueHandle(this, descPtr);
1338
+ const description = descHandle.toString();
1339
+ descHandle.dispose();
1340
+ return Symbol.for(description);
1341
+ } else if (kind === 2) {
1342
+ const descHandle = new JSValueHandle(this, descPtr);
1343
+ descHandle.dispose();
1344
+ return;
1345
+ }
1346
+ return;
1347
+ }
1348
+ if (e.qjs_is_array_buffer(handle.ptr))
1349
+ return handle.toArrayBuffer();
1350
+ if (e.qjs_is_exception(handle.ptr)) {
1351
+ const exc = this.getException();
1352
+ const msg = exc.toString();
1353
+ exc.dispose();
1354
+ return new Error(msg);
1355
+ }
1356
+ if (e.qjs_is_function(handle.ptr))
1357
+ return;
1358
+ if (e.qjs_is_object(handle.ptr)) {
1359
+ const objPtr = e.qjs_get_value_ptr(handle.ptr);
1360
+ if (objPtr) {
1361
+ const existing = visited.get(objPtr);
1362
+ if (existing !== undefined)
1363
+ return existing;
1364
+ }
1365
+ }
1366
+ if (e.qjs_is_object(handle.ptr)) {
1367
+ const byteOffsetPtr = e.wasm_malloc(4);
1368
+ const byteLengthPtr = e.wasm_malloc(4);
1369
+ const bytesPerElemPtr = e.wasm_malloc(4);
1370
+ const abPtr = e.qjs_get_typed_array_buffer(handle.ptr, byteOffsetPtr, byteLengthPtr, bytesPerElemPtr);
1371
+ const abHandle = new JSValueHandle(this, abPtr);
1372
+ if (e.qjs_is_exception(abHandle.ptr) === 0) {
1373
+ const view = new DataView(e.memory.buffer);
1374
+ const byteOffset = view.getUint32(byteOffsetPtr, true);
1375
+ const byteLength = view.getUint32(byteLengthPtr, true);
1376
+ const bytesPerElement = view.getUint32(bytesPerElemPtr, true);
1377
+ e.wasm_free(byteOffsetPtr);
1378
+ e.wasm_free(byteLengthPtr);
1379
+ e.wasm_free(bytesPerElemPtr);
1380
+ const abLenPtr = e.wasm_malloc(4);
1381
+ const abDataPtr = e.qjs_get_array_buffer(abHandle.ptr, abLenPtr);
1382
+ e.wasm_free(abLenPtr);
1383
+ abHandle.dispose();
1384
+ if (abDataPtr !== 0) {
1385
+ const rawBytes = new Uint8Array(e.memory.buffer, abDataPtr + byteOffset, byteLength).slice();
1386
+ switch (bytesPerElement) {
1387
+ case 1:
1388
+ return rawBytes;
1389
+ case 2:
1390
+ return new Uint16Array(rawBytes.buffer);
1391
+ case 4:
1392
+ return new Uint32Array(rawBytes.buffer);
1393
+ case 8:
1394
+ return new Float64Array(rawBytes.buffer);
1395
+ default:
1396
+ return rawBytes;
1397
+ }
1398
+ }
1399
+ } else {
1400
+ abHandle.dispose();
1401
+ e.wasm_free(byteOffsetPtr);
1402
+ e.wasm_free(byteLengthPtr);
1403
+ e.wasm_free(bytesPerElemPtr);
1404
+ }
1405
+ }
1406
+ if (e.qjs_is_array(handle.ptr)) {
1407
+ const lenHandle = handle.getProp("length");
1408
+ const len = e.qjs_get_float64(lenHandle.ptr);
1409
+ lenHandle.dispose();
1410
+ const arr = [];
1411
+ const objPtr = e.qjs_get_value_ptr(handle.ptr);
1412
+ if (objPtr)
1413
+ visited.set(objPtr, arr);
1414
+ for (let i = 0;i < len; i++) {
1415
+ const elemPtr = e.qjs_get_prop_uint32(handle.ptr, i);
1416
+ const elemHandle = new JSValueHandle(this, elemPtr);
1417
+ arr.push(this._dump(elemHandle, visited));
1418
+ elemHandle.dispose();
1419
+ }
1420
+ return arr;
1421
+ }
1422
+ if (e.qjs_is_error(handle.ptr)) {
1423
+ const nameHandle = handle.getProp("name");
1424
+ const msgHandle = handle.getProp("message");
1425
+ const stackHandle = handle.getProp("stack");
1426
+ const name = nameHandle.isUndefined ? "Error" : nameHandle.toString();
1427
+ const message = msgHandle.isUndefined ? "" : msgHandle.toString();
1428
+ const stack = stackHandle.isUndefined ? undefined : stackHandle.toString();
1429
+ nameHandle.dispose();
1430
+ msgHandle.dispose();
1431
+ stackHandle.dispose();
1432
+ const err = new Error(message);
1433
+ err.name = name;
1434
+ if (stack !== undefined) {
1435
+ err.stack = stack;
1436
+ }
1437
+ return err;
1438
+ }
1439
+ if (e.qjs_is_object(handle.ptr)) {
1440
+ const keysPtr = e.qjs_get_own_property_names(handle.ptr);
1441
+ const keysHandle = new JSValueHandle(this, keysPtr);
1442
+ if (e.qjs_is_exception(keysHandle.ptr) !== 0) {
1443
+ keysHandle.dispose();
1444
+ return {};
1445
+ }
1446
+ const lenHandle = keysHandle.getProp("length");
1447
+ const len = e.qjs_get_float64(lenHandle.ptr);
1448
+ lenHandle.dispose();
1449
+ const obj = {};
1450
+ const objPtr = e.qjs_get_value_ptr(handle.ptr);
1451
+ if (objPtr)
1452
+ visited.set(objPtr, obj);
1453
+ for (let i = 0;i < len; i++) {
1454
+ const keyPtr = e.qjs_get_prop_uint32(keysHandle.ptr, i);
1455
+ const keyHandle = new JSValueHandle(this, keyPtr);
1456
+ const key = keyHandle.toString();
1457
+ keyHandle.dispose();
1458
+ const valHandle = handle.getProp(key);
1459
+ obj[key] = this._dump(valHandle, visited);
1460
+ valHandle.dispose();
1461
+ }
1462
+ keysHandle.dispose();
1463
+ return obj;
1464
+ }
1465
+ return;
1466
+ }
1467
+ hostToHandle(value) {
1468
+ this.assertNotDisposed();
1469
+ if (value === undefined)
1470
+ return this.undefined;
1471
+ if (value === null)
1472
+ return this.null;
1473
+ if (value === true)
1474
+ return this.true;
1475
+ if (value === false)
1476
+ return this.false;
1477
+ if (typeof value === "number")
1478
+ return this.newNumber(value);
1479
+ if (typeof value === "string")
1480
+ return this.newString(value);
1481
+ if (typeof value === "bigint")
1482
+ return this.newBigInt(value);
1483
+ if (typeof value === "symbol") {
1484
+ const key = Symbol.keyFor(value);
1485
+ if (key !== undefined) {
1486
+ return this.newSymbolFor(key);
1487
+ }
1488
+ throw new Error(`Cannot convert local symbol to QuickJS handle. Use Symbol.for() for cross-boundary symbols.`);
1489
+ }
1490
+ if (value instanceof Promise) {
1491
+ const deferred = this.newPromise();
1492
+ value.then((r) => {
1493
+ deferred.resolve(this.hostToHandle(r));
1494
+ this.executePendingJobs();
1495
+ }, (err) => {
1496
+ deferred.reject(this.hostToHandle(err));
1497
+ this.executePendingJobs();
1498
+ });
1499
+ return deferred.handle;
1500
+ }
1501
+ if (value instanceof Error) {
1502
+ return this.newError(value);
1503
+ }
1504
+ if (value instanceof ArrayBuffer) {
1505
+ return this.newArrayBuffer(value);
1506
+ }
1507
+ if (value instanceof Uint8Array) {
1508
+ return this.newUint8Array(value);
1509
+ }
1510
+ if (ArrayBuffer.isView(value)) {
1511
+ return this.newArrayBuffer(new Uint8Array(value.buffer, value.byteOffset, value.byteLength));
1512
+ }
1513
+ if (Array.isArray(value)) {
1514
+ const arr = this.newArray();
1515
+ for (let i = 0;i < value.length; i++) {
1516
+ const elemHandle = this.hostToHandle(value[i]);
1517
+ this.exports.qjs_set_prop_uint32(arr.ptr, i, elemHandle.ptr);
1518
+ elemHandle.dispose();
1519
+ }
1520
+ return arr;
1521
+ }
1522
+ if (typeof value === "object" && value !== null) {
1523
+ const obj = this.newObject();
1524
+ for (const [key, val] of Object.entries(value)) {
1525
+ const valHandle = this.hostToHandle(val);
1526
+ obj.setProp(key, valHandle);
1527
+ valHandle.dispose();
1528
+ }
1529
+ return obj;
1530
+ }
1531
+ return this.undefined;
1532
+ }
1533
+ snapshot() {
1534
+ this.assertNotDisposed();
1535
+ return {
1536
+ memory: new Uint8Array(this.exports.memory.buffer).slice(),
1537
+ stackPointer: this.exports.__stack_pointer.value,
1538
+ runtimePtr: this.exports.qjs_get_runtime_ptr(),
1539
+ contextPtr: this.exports.qjs_get_context_ptr(),
1540
+ extensions: this.loadedExtensions.map((ext) => ({
1541
+ name: ext.name,
1542
+ memoryBase: ext.memoryBase,
1543
+ tableBase: ext.tableBase,
1544
+ initFn: ext.initFn
1545
+ }))
1546
+ };
1547
+ }
1548
+ registerHostCallback(name, fn) {
1549
+ this.hostCallbacks.set(name, fn);
1550
+ }
1551
+ dispose() {
1552
+ if (!this.disposed) {
1553
+ this.disposed = true;
1554
+ this._global = null;
1555
+ this._undefined = null;
1556
+ this._null = null;
1557
+ this._true = null;
1558
+ this._false = null;
1559
+ this._ownedHandles.clear();
1560
+ this.hostCallbacks.clear();
1561
+ this._activeScope = null;
1562
+ this.exports = null;
1563
+ this.instance = null;
1564
+ this.module = null;
1565
+ }
1566
+ }
1567
+ [Symbol.dispose]() {
1568
+ this.dispose();
1569
+ }
1570
+ assertNotDisposed() {
1571
+ if (this.disposed) {
1572
+ throw new Error("QuickJS instance has been disposed");
1573
+ }
1574
+ }
1575
+ _getExports() {
1576
+ return this.exports;
1577
+ }
1578
+ _getMemory() {
1579
+ return this.exports.memory;
1580
+ }
1581
+ _writeString(str) {
1582
+ return this.writeString(str);
1583
+ }
1584
+ _readCString(ptr) {
1585
+ return this.readCString(ptr);
1586
+ }
1587
+ }
1588
+ function stringKeyNeedsValuePath(key) {
1589
+ return key.includes("\x00") || LONE_SURROGATE_RE.test(key);
1590
+ }
1591
+ var wtf8Decoder = new TextDecoder;
1592
+ var wtf8Encoder = new TextEncoder;
1593
+ var LONE_SURROGATE_RE = /(?:[\uD800-\uDBFF](?![\uDC00-\uDFFF]))|(?:(?<![\uD800-\uDBFF])[\uDC00-\uDFFF])/;
1594
+ function encodeWtf8(str) {
1595
+ if (!LONE_SURROGATE_RE.test(str))
1596
+ return wtf8Encoder.encode(str);
1597
+ const bytes = [];
1598
+ for (let i = 0;i < str.length; i++) {
1599
+ const code = str.charCodeAt(i);
1600
+ if (code < 128) {
1601
+ bytes.push(code);
1602
+ } else if (code < 2048) {
1603
+ bytes.push(192 | code >> 6, 128 | code & 63);
1604
+ } else if (code >= 55296 && code <= 56319 && i + 1 < str.length) {
1605
+ const next = str.charCodeAt(i + 1);
1606
+ if (next >= 56320 && next <= 57343) {
1607
+ const cp = 65536 + (code - 55296 << 10) + (next - 56320);
1608
+ bytes.push(240 | cp >> 18, 128 | cp >> 12 & 63, 128 | cp >> 6 & 63, 128 | cp & 63);
1609
+ i++;
1610
+ continue;
1611
+ }
1612
+ bytes.push(224 | code >> 12, 128 | code >> 6 & 63, 128 | code & 63);
1613
+ } else {
1614
+ bytes.push(224 | code >> 12, 128 | code >> 6 & 63, 128 | code & 63);
1615
+ }
1616
+ }
1617
+ return new Uint8Array(bytes);
1618
+ }
1619
+ function decodeWtf8(bytes) {
1620
+ let hasSurrogateSequence = false;
1621
+ for (let i = 0;i < bytes.length - 1; i++) {
1622
+ if (bytes[i] === 237 && bytes[i + 1] >= 160 && bytes[i + 1] <= 191) {
1623
+ hasSurrogateSequence = true;
1624
+ break;
1625
+ }
1626
+ }
1627
+ if (!hasSurrogateSequence)
1628
+ return wtf8Decoder.decode(bytes);
1629
+ let out = "";
1630
+ let i = 0;
1631
+ while (i < bytes.length) {
1632
+ const b0 = bytes[i];
1633
+ if (b0 < 128) {
1634
+ out += String.fromCharCode(b0);
1635
+ i += 1;
1636
+ } else if (b0 < 224) {
1637
+ out += String.fromCharCode((b0 & 31) << 6 | bytes[i + 1] & 63);
1638
+ i += 2;
1639
+ } else if (b0 < 240) {
1640
+ out += String.fromCharCode((b0 & 15) << 12 | (bytes[i + 1] & 63) << 6 | bytes[i + 2] & 63);
1641
+ i += 3;
1642
+ } else {
1643
+ const cp = (b0 & 7) << 18 | (bytes[i + 1] & 63) << 12 | (bytes[i + 2] & 63) << 6 | bytes[i + 3] & 63;
1644
+ out += String.fromCodePoint(cp);
1645
+ i += 4;
1646
+ }
1647
+ }
1648
+ return out;
1649
+ }
1650
+
1651
+ class JSException extends Error {
1652
+ handle;
1653
+ #name;
1654
+ #message;
1655
+ #stack;
1656
+ constructor(handle) {
1657
+ const env_1 = { stack: [], error: undefined, hasError: false };
1658
+ try {
1659
+ super();
1660
+ this.handle = handle;
1661
+ delete this.stack;
1662
+ const msgHandle = __addDisposableResource(env_1, handle.getProp("message"), false);
1663
+ this.#name = handle.getProp("name").consume((h) => h.isUndefined ? "Error" : h.toString());
1664
+ this.#message = msgHandle.isUndefined ? handle.toString() : msgHandle.toString();
1665
+ this.#stack = handle.getProp("stack").consume((h) => h.isUndefined ? undefined : h.toString());
1666
+ } catch (e_1) {
1667
+ env_1.error = e_1;
1668
+ env_1.hasError = true;
1669
+ } finally {
1670
+ __disposeResources(env_1);
1671
+ }
1672
+ }
1673
+ get name() {
1674
+ return this.#name;
1675
+ }
1676
+ set name(v) {
1677
+ this.#name = v;
1678
+ }
1679
+ get message() {
1680
+ return this.#message;
1681
+ }
1682
+ set message(v) {
1683
+ this.#message = v;
1684
+ }
1685
+ get stack() {
1686
+ return this.#stack;
1687
+ }
1688
+ set stack(v) {
1689
+ this.#stack = v;
1690
+ }
1691
+ dispose() {
1692
+ this.handle.dispose();
1693
+ }
1694
+ [Symbol.dispose]() {
1695
+ this.handle.dispose();
1696
+ }
1697
+ }
1698
+
1699
+ class JSValueHandle {
1700
+ vm;
1701
+ ptr;
1702
+ disposed_ = false;
1703
+ singleton;
1704
+ borrowed;
1705
+ _onDispose;
1706
+ constructor(vm, ptr, singleton = false, borrowed = false) {
1707
+ this.vm = vm;
1708
+ this.ptr = ptr;
1709
+ this.singleton = singleton;
1710
+ this.borrowed = borrowed;
1711
+ if (!singleton && !borrowed)
1712
+ vm._activeScope?.add(this);
1713
+ }
1714
+ get _isBorrowed() {
1715
+ return this.borrowed;
1716
+ }
1717
+ get disposed() {
1718
+ return this.disposed_;
1719
+ }
1720
+ get isUndefined() {
1721
+ return this.vm._getExports().qjs_is_undefined(this.ptr) !== 0;
1722
+ }
1723
+ get isNull() {
1724
+ return this.vm._getExports().qjs_is_null(this.ptr) !== 0;
1725
+ }
1726
+ get isBool() {
1727
+ return this.vm._getExports().qjs_is_bool(this.ptr) !== 0;
1728
+ }
1729
+ get isNumber() {
1730
+ return this.vm._getExports().qjs_is_number(this.ptr) !== 0;
1731
+ }
1732
+ get isString() {
1733
+ return this.vm._getExports().qjs_is_string(this.ptr) !== 0;
1734
+ }
1735
+ get isSymbol() {
1736
+ return this.vm._getExports().qjs_is_symbol(this.ptr) !== 0;
1737
+ }
1738
+ get isBigInt() {
1739
+ return this.vm._getExports().qjs_is_big_int(this.ptr) !== 0;
1740
+ }
1741
+ get isObject() {
1742
+ return this.vm._getExports().qjs_is_object(this.ptr) !== 0;
1743
+ }
1744
+ get isArray() {
1745
+ return this.vm._getExports().qjs_is_array(this.ptr) !== 0;
1746
+ }
1747
+ get isFunction() {
1748
+ return this.vm._getExports().qjs_is_function(this.ptr) !== 0;
1749
+ }
1750
+ get isError() {
1751
+ return this.vm._getExports().qjs_is_error(this.ptr) !== 0;
1752
+ }
1753
+ get isPromise() {
1754
+ return this.vm._getExports().qjs_is_promise(this.ptr) !== 0;
1755
+ }
1756
+ get isArrayBuffer() {
1757
+ return this.vm._getExports().qjs_is_array_buffer(this.ptr) !== 0;
1758
+ }
1759
+ get isProxy() {
1760
+ return this.vm._getExports().qjs_is_proxy(this.ptr) !== 0;
1761
+ }
1762
+ get isMap() {
1763
+ return this.vm._getExports().qjs_is_map(this.ptr) !== 0;
1764
+ }
1765
+ get isSet() {
1766
+ return this.vm._getExports().qjs_is_set(this.ptr) !== 0;
1767
+ }
1768
+ get isDate() {
1769
+ return this.vm._getExports().qjs_is_date(this.ptr) !== 0;
1770
+ }
1771
+ get isRegExp() {
1772
+ return this.vm._getExports().qjs_is_regexp(this.ptr) !== 0;
1773
+ }
1774
+ get isWeakRef() {
1775
+ return this.vm._getExports().qjs_is_weak_ref(this.ptr) !== 0;
1776
+ }
1777
+ get isWeakMap() {
1778
+ return this.vm._getExports().qjs_is_weak_map(this.ptr) !== 0;
1779
+ }
1780
+ get isWeakSet() {
1781
+ return this.vm._getExports().qjs_is_weak_set(this.ptr) !== 0;
1782
+ }
1783
+ get isDataView() {
1784
+ return this.vm._getExports().qjs_is_data_view(this.ptr) !== 0;
1785
+ }
1786
+ get identity() {
1787
+ return this.vm._getExports().qjs_get_value_ptr(this.ptr);
1788
+ }
1789
+ toBoolean() {
1790
+ return this.vm._getExports().qjs_get_bool(this.ptr) !== 0;
1791
+ }
1792
+ get classId() {
1793
+ return this.vm._getExports().qjs_get_class_id(this.ptr);
1794
+ }
1795
+ get className() {
1796
+ const h = new JSValueHandle(this.vm, this.vm._getExports().qjs_get_class_name(this.ptr));
1797
+ if (this.vm._getExports().qjs_is_exception(h.ptr) !== 0) {
1798
+ h.dispose();
1799
+ throw new JSException(this.vm.getException());
1800
+ }
1801
+ try {
1802
+ return h.isUndefined ? undefined : h.toString();
1803
+ } finally {
1804
+ h.dispose();
1805
+ }
1806
+ }
1807
+ get promiseState() {
1808
+ return this.vm._getExports().qjs_promise_state(this.ptr);
1809
+ }
1810
+ get typeof() {
1811
+ return this.vm.typeof(this);
1812
+ }
1813
+ get length() {
1814
+ const h = this.getProp("length");
1815
+ const n = h.toNumber();
1816
+ h.dispose();
1817
+ return n;
1818
+ }
1819
+ get constructorName() {
1820
+ const ctor = this.getProp("constructor");
1821
+ if (ctor.isUndefined || ctor.isNull) {
1822
+ ctor.dispose();
1823
+ return;
1824
+ }
1825
+ const name = ctor.getProp("name");
1826
+ ctor.dispose();
1827
+ if (name.isUndefined || name.isNull) {
1828
+ name.dispose();
1829
+ return;
1830
+ }
1831
+ const result = name.toString();
1832
+ name.dispose();
1833
+ return result;
1834
+ }
1835
+ keys() {
1836
+ const e = this.vm._getExports();
1837
+ const keysPtr = e.qjs_get_own_property_names(this.ptr);
1838
+ const keysHandle = new JSValueHandle(this.vm, keysPtr);
1839
+ if (e.qjs_is_exception(keysHandle.ptr) !== 0) {
1840
+ keysHandle.dispose();
1841
+ return [];
1842
+ }
1843
+ const lenHandle = keysHandle.getProp("length");
1844
+ const len = e.qjs_get_float64(lenHandle.ptr);
1845
+ lenHandle.dispose();
1846
+ const result = [];
1847
+ for (let i = 0;i < len; i++) {
1848
+ const keyPtr = e.qjs_get_prop_uint32(keysHandle.ptr, i);
1849
+ const keyHandle = new JSValueHandle(this.vm, keyPtr);
1850
+ result.push(keyHandle.toString());
1851
+ keyHandle.dispose();
1852
+ }
1853
+ keysHandle.dispose();
1854
+ return result;
1855
+ }
1856
+ getOwnPropertyNames() {
1857
+ const e = this.vm._getExports();
1858
+ const keysPtr = e.qjs_get_own_property_names_all(this.ptr);
1859
+ const keysHandle = new JSValueHandle(this.vm, keysPtr);
1860
+ if (e.qjs_is_exception(keysHandle.ptr) !== 0) {
1861
+ keysHandle.dispose();
1862
+ return [];
1863
+ }
1864
+ const lenHandle = keysHandle.getProp("length");
1865
+ const len = e.qjs_get_float64(lenHandle.ptr);
1866
+ lenHandle.dispose();
1867
+ const result = [];
1868
+ for (let i = 0;i < len; i++) {
1869
+ const keyPtr = e.qjs_get_prop_uint32(keysHandle.ptr, i);
1870
+ const keyHandle = new JSValueHandle(this.vm, keyPtr);
1871
+ result.push(keyHandle.toString());
1872
+ keyHandle.dispose();
1873
+ }
1874
+ keysHandle.dispose();
1875
+ return result;
1876
+ }
1877
+ getOwnPropertyKeys() {
1878
+ const e = this.vm._getExports();
1879
+ const keysPtr = e.qjs_get_own_property_keys(this.ptr);
1880
+ const keysHandle = new JSValueHandle(this.vm, keysPtr);
1881
+ if (e.qjs_is_exception(keysHandle.ptr) !== 0) {
1882
+ keysHandle.dispose();
1883
+ return [];
1884
+ }
1885
+ const lenHandle = keysHandle.getProp("length");
1886
+ const len = e.qjs_get_float64(lenHandle.ptr);
1887
+ lenHandle.dispose();
1888
+ const result = [];
1889
+ for (let i = 0;i < len; i++) {
1890
+ const keyPtr = e.qjs_get_prop_uint32(keysHandle.ptr, i);
1891
+ const keyHandle = new JSValueHandle(this.vm, keyPtr);
1892
+ if (keyHandle.isSymbol) {
1893
+ result.push(keyHandle);
1894
+ } else {
1895
+ result.push(keyHandle.toString());
1896
+ keyHandle.dispose();
1897
+ }
1898
+ }
1899
+ keysHandle.dispose();
1900
+ return result;
1901
+ }
1902
+ getOwnPropertyDescriptor(key) {
1903
+ const env_2 = { stack: [], error: undefined, hasError: false };
1904
+ try {
1905
+ const e = this.vm._getExports();
1906
+ let keyHandle;
1907
+ let keyPtr;
1908
+ if (typeof key === "string") {
1909
+ keyHandle = this.vm.newString(key);
1910
+ keyPtr = keyHandle.ptr;
1911
+ } else {
1912
+ keyPtr = key.ptr;
1913
+ }
1914
+ const descPtr = e.qjs_get_own_property_descriptor(this.ptr, keyPtr);
1915
+ keyHandle?.dispose();
1916
+ if (descPtr === 0)
1917
+ return;
1918
+ const descHandle = __addDisposableResource(env_2, new JSValueHandle(this.vm, descPtr), false);
1919
+ if (e.qjs_is_exception(descHandle.ptr) !== 0) {
1920
+ throw new JSException(this.vm.getException());
1921
+ }
1922
+ const enumerable = descHandle.getProp("enumerable").consume((h) => e.qjs_get_bool(h.ptr) !== 0);
1923
+ const configurable = descHandle.getProp("configurable").consume((h) => e.qjs_get_bool(h.ptr) !== 0);
1924
+ if (descHandle.hasOwnProperty("value")) {
1925
+ return {
1926
+ value: descHandle.getProp("value"),
1927
+ writable: descHandle.getProp("writable").consume((h) => e.qjs_get_bool(h.ptr) !== 0),
1928
+ enumerable,
1929
+ configurable
1930
+ };
1931
+ }
1932
+ return {
1933
+ get: descHandle.getProp("get"),
1934
+ set: descHandle.getProp("set"),
1935
+ enumerable,
1936
+ configurable
1937
+ };
1938
+ } catch (e_2) {
1939
+ env_2.error = e_2;
1940
+ env_2.hasError = true;
1941
+ } finally {
1942
+ __disposeResources(env_2);
1943
+ }
1944
+ }
1945
+ hasOwnProperty(name) {
1946
+ if (stringKeyNeedsValuePath(name)) {
1947
+ const env_3 = { stack: [], error: undefined, hasError: false };
1948
+ try {
1949
+ const keyHandle = __addDisposableResource(env_3, this.vm.newString(name), false);
1950
+ return this.vm._getExports().qjs_has_own_property_value(this.ptr, keyHandle.ptr) === 1;
1951
+ } catch (e_3) {
1952
+ env_3.error = e_3;
1953
+ env_3.hasError = true;
1954
+ } finally {
1955
+ __disposeResources(env_3);
1956
+ }
1957
+ }
1958
+ const { ptr: namePtr } = this.vm._writeString(name);
1959
+ const result = this.vm._getExports().qjs_has_own_property(this.ptr, namePtr);
1960
+ this.vm._getExports().wasm_free(namePtr);
1961
+ return result === 1;
1962
+ }
1963
+ propertyIsEnumerable(name) {
1964
+ if (stringKeyNeedsValuePath(name)) {
1965
+ const env_4 = { stack: [], error: undefined, hasError: false };
1966
+ try {
1967
+ const keyHandle = __addDisposableResource(env_4, this.vm.newString(name), false);
1968
+ return this.vm._getExports().qjs_property_is_enumerable_value(this.ptr, keyHandle.ptr) === 1;
1969
+ } catch (e_4) {
1970
+ env_4.error = e_4;
1971
+ env_4.hasError = true;
1972
+ } finally {
1973
+ __disposeResources(env_4);
1974
+ }
1975
+ }
1976
+ const { ptr: namePtr } = this.vm._writeString(name);
1977
+ const result = this.vm._getExports().qjs_property_is_enumerable(this.ptr, namePtr);
1978
+ this.vm._getExports().wasm_free(namePtr);
1979
+ return result === 1;
1980
+ }
1981
+ getPrototypeOf() {
1982
+ const protoPtr = this.vm._getExports().qjs_get_prototype_of(this.ptr);
1983
+ return new JSValueHandle(this.vm, protoPtr);
1984
+ }
1985
+ getProxyTarget() {
1986
+ const ptr = this.vm._getExports().qjs_get_proxy_target(this.ptr);
1987
+ const handle = new JSValueHandle(this.vm, ptr);
1988
+ if (this.vm._getExports().qjs_is_exception(handle.ptr) !== 0) {
1989
+ handle.dispose();
1990
+ throw new JSException(this.vm.getException());
1991
+ }
1992
+ return handle;
1993
+ }
1994
+ getProxyHandler() {
1995
+ const ptr = this.vm._getExports().qjs_get_proxy_handler(this.ptr);
1996
+ const handle = new JSValueHandle(this.vm, ptr);
1997
+ if (this.vm._getExports().qjs_is_exception(handle.ptr) !== 0) {
1998
+ handle.dispose();
1999
+ throw new JSException(this.vm.getException());
2000
+ }
2001
+ return handle;
2002
+ }
2003
+ getProp(name) {
2004
+ if (stringKeyNeedsValuePath(name)) {
2005
+ const env_5 = { stack: [], error: undefined, hasError: false };
2006
+ try {
2007
+ const keyHandle = __addDisposableResource(env_5, this.vm.newString(name), false);
2008
+ return this.vm.getProp(this, keyHandle);
2009
+ } catch (e_5) {
2010
+ env_5.error = e_5;
2011
+ env_5.hasError = true;
2012
+ } finally {
2013
+ __disposeResources(env_5);
2014
+ }
2015
+ }
2016
+ const { ptr: namePtr } = this.vm._writeString(name);
2017
+ const resultPtr = this.vm._getExports().qjs_get_prop_string(this.ptr, namePtr);
2018
+ this.vm._getExports().wasm_free(namePtr);
2019
+ return new JSValueHandle(this.vm, resultPtr);
2020
+ }
2021
+ setProp(name, value) {
2022
+ if (stringKeyNeedsValuePath(name)) {
2023
+ const env_6 = { stack: [], error: undefined, hasError: false };
2024
+ try {
2025
+ const keyHandle = __addDisposableResource(env_6, this.vm.newString(name), false);
2026
+ this.vm.setProp(this, keyHandle, value);
2027
+ return;
2028
+ } catch (e_6) {
2029
+ env_6.error = e_6;
2030
+ env_6.hasError = true;
2031
+ } finally {
2032
+ __disposeResources(env_6);
2033
+ }
2034
+ }
2035
+ const { ptr: namePtr } = this.vm._writeString(name);
2036
+ this.vm._getExports().qjs_set_prop_string(this.ptr, namePtr, value.ptr);
2037
+ this.vm._getExports().wasm_free(namePtr);
2038
+ }
2039
+ defineProp(key, value, descriptor) {
2040
+ let flags = 0;
2041
+ if (descriptor?.configurable)
2042
+ flags |= 1;
2043
+ if (descriptor?.writable)
2044
+ flags |= 2;
2045
+ if (descriptor?.enumerable)
2046
+ flags |= 4;
2047
+ if (typeof key === "string") {
2048
+ if (stringKeyNeedsValuePath(key)) {
2049
+ const env_7 = { stack: [], error: undefined, hasError: false };
2050
+ try {
2051
+ const keyHandle = __addDisposableResource(env_7, this.vm.newString(key), false);
2052
+ this.vm._getExports().qjs_define_prop_value(this.ptr, keyHandle.ptr, value.ptr, flags);
2053
+ return;
2054
+ } catch (e_7) {
2055
+ env_7.error = e_7;
2056
+ env_7.hasError = true;
2057
+ } finally {
2058
+ __disposeResources(env_7);
2059
+ }
2060
+ }
2061
+ const { ptr: namePtr } = this.vm._writeString(key);
2062
+ this.vm._getExports().qjs_define_prop_string(this.ptr, namePtr, value.ptr, flags);
2063
+ this.vm._getExports().wasm_free(namePtr);
2064
+ } else {
2065
+ this.vm._getExports().qjs_define_prop_value(this.ptr, key.ptr, value.ptr, flags);
2066
+ }
2067
+ }
2068
+ toNumber() {
2069
+ return this.vm._getExports().qjs_get_float64(this.ptr);
2070
+ }
2071
+ toBigInt() {
2072
+ const e = this.vm._getExports();
2073
+ const loPtr = e.wasm_malloc(4);
2074
+ const hiPtr = e.wasm_malloc(4);
2075
+ const ret = e.qjs_get_big_int64(this.ptr, loPtr, hiPtr);
2076
+ if (ret !== 0) {
2077
+ e.wasm_free(loPtr);
2078
+ e.wasm_free(hiPtr);
2079
+ throw new Error("Failed to convert value to BigInt");
2080
+ }
2081
+ const view = new DataView(e.memory.buffer);
2082
+ const lo = view.getUint32(loPtr, true);
2083
+ const hi = view.getInt32(hiPtr, true);
2084
+ e.wasm_free(loPtr);
2085
+ e.wasm_free(hiPtr);
2086
+ return BigInt(hi) << 32n | BigInt(lo);
2087
+ }
2088
+ toArrayBuffer() {
2089
+ const e = this.vm._getExports();
2090
+ const lenOutPtr = e.wasm_malloc(4);
2091
+ if (e.qjs_is_array_buffer(this.ptr)) {
2092
+ const dataPtr = e.qjs_get_array_buffer(this.ptr, lenOutPtr);
2093
+ if (dataPtr === 0) {
2094
+ e.wasm_free(lenOutPtr);
2095
+ throw new Error("Failed to get ArrayBuffer data");
2096
+ }
2097
+ const view = new DataView(e.memory.buffer);
2098
+ const len = view.getUint32(lenOutPtr, true);
2099
+ e.wasm_free(lenOutPtr);
2100
+ return new Uint8Array(e.memory.buffer, dataPtr, len).slice().buffer;
2101
+ }
2102
+ e.wasm_free(lenOutPtr);
2103
+ const byteOffsetPtr = e.wasm_malloc(4);
2104
+ const byteLengthPtr = e.wasm_malloc(4);
2105
+ const bytesPerElemPtr = e.wasm_malloc(4);
2106
+ const abPtr = e.qjs_get_typed_array_buffer(this.ptr, byteOffsetPtr, byteLengthPtr, bytesPerElemPtr);
2107
+ const abHandle = new JSValueHandle(this.vm, abPtr);
2108
+ if (this.vm._getExports().qjs_is_exception(abHandle.ptr) !== 0) {
2109
+ abHandle.dispose();
2110
+ e.wasm_free(byteOffsetPtr);
2111
+ e.wasm_free(byteLengthPtr);
2112
+ e.wasm_free(bytesPerElemPtr);
2113
+ throw new Error("Value is not an ArrayBuffer or typed array");
2114
+ }
2115
+ const view = new DataView(e.memory.buffer);
2116
+ const byteOffset = view.getUint32(byteOffsetPtr, true);
2117
+ const byteLength = view.getUint32(byteLengthPtr, true);
2118
+ e.wasm_free(byteOffsetPtr);
2119
+ e.wasm_free(byteLengthPtr);
2120
+ e.wasm_free(bytesPerElemPtr);
2121
+ const abLenPtr = e.wasm_malloc(4);
2122
+ const abDataPtr = e.qjs_get_array_buffer(abHandle.ptr, abLenPtr);
2123
+ e.wasm_free(abLenPtr);
2124
+ abHandle.dispose();
2125
+ if (abDataPtr === 0) {
2126
+ throw new Error("Failed to get ArrayBuffer data from typed array");
2127
+ }
2128
+ return new Uint8Array(e.memory.buffer, abDataPtr + byteOffset, byteLength).slice().buffer;
2129
+ }
2130
+ toUint8Array() {
2131
+ return new Uint8Array(this.toArrayBuffer());
2132
+ }
2133
+ toString() {
2134
+ const e = this.vm._getExports();
2135
+ const lenPtr = e.wasm_malloc(4);
2136
+ if (lenPtr === 0)
2137
+ throw new Error("wasm_malloc failed");
2138
+ try {
2139
+ const cstrPtr = e.qjs_get_string_len(this.ptr, lenPtr);
2140
+ if (cstrPtr === 0)
2141
+ return "<null>";
2142
+ const len = new DataView(e.memory.buffer).getUint32(lenPtr, true);
2143
+ const bytes = new Uint8Array(e.memory.buffer, cstrPtr, len);
2144
+ const str = decodeWtf8(bytes);
2145
+ e.qjs_free_cstring(cstrPtr);
2146
+ return str;
2147
+ } finally {
2148
+ e.wasm_free(lenPtr);
2149
+ }
2150
+ }
2151
+ consume(fn) {
2152
+ try {
2153
+ return fn(this);
2154
+ } finally {
2155
+ this.dispose();
2156
+ }
2157
+ }
2158
+ dup() {
2159
+ return new JSValueHandle(this.vm, this.vm._getExports().qjs_dup_value(this.ptr));
2160
+ }
2161
+ dispose() {
2162
+ if (this.singleton || this.borrowed)
2163
+ return;
2164
+ if (!this.disposed_) {
2165
+ this.disposed_ = true;
2166
+ this._onDispose?.();
2167
+ this._onDispose = undefined;
2168
+ const exports = this.vm._getExports();
2169
+ if (exports) {
2170
+ exports.qjs_free_value(this.ptr);
2171
+ }
2172
+ }
2173
+ }
2174
+ [Symbol.dispose]() {
2175
+ this.dispose();
2176
+ }
2177
+ }
2178
+
2179
+ // node_modules/@earendil-works/pi-codemode/dist/runtime/prelude-source.js
2180
+ var MAX_STORE_VALUE_CHARS = 256 * 1024;
2181
+ var MAX_STORE_TOTAL_CHARS = 1024 * 1024;
2182
+ var MAX_OUTPUT_CHARS = 16 * 1024 * 1024;
2183
+ var MAX_OUTPUT_ITEMS = 1e5;
2184
+ var IMAGE_HELPER_EXPECTS = "image expects a non-empty image URL string, an object with image_url, or a raw MCP image block";
2185
+ var PRELUDE_SOURCE = `(function (bridge, toolsJson, globalsJson, storeJson) {
2186
+ "use strict";
2187
+
2188
+ // Freeze every object reachable from the built-in globals, plus the intrinsics that are only
2189
+ // reachable from instances (iterator and generator prototypes, %TypedArray%).
2190
+ //
2191
+ // Freezing alone breaks ordinary code through the "override mistake": a data property that is
2192
+ // read-only on a prototype cannot be assigned on an instance either, so
2193
+ // this.name = "MyError" in an Error subclass would throw. Commonly overridden properties
2194
+ // become accessors whose setter defines an own property on the instance instead.
2195
+ (function lockdown() {
2196
+ const OVERRIDABLE = new Set(["constructor", "name", "message", "toString", "toLocaleString", "valueOf", "toJSON"]);
2197
+ const seen = new Set([globalThis]);
2198
+ const queue = [];
2199
+ const add = (value) => {
2200
+ if ((typeof value === "object" && value !== null) || typeof value === "function") {
2201
+ if (!seen.has(value)) {
2202
+ seen.add(value);
2203
+ queue.push(value);
2204
+ }
2205
+ }
2206
+ };
2207
+
2208
+ // Accessors from an object literal have no own prototype object, unlike function expressions,
2209
+ // whose prototype.constructor would be converted again without end.
2210
+ function allowOverride(object, key, value, enumerable) {
2211
+ const { get, set } = Object.getOwnPropertyDescriptor(
2212
+ {
2213
+ get accessor() {
2214
+ return value;
2215
+ },
2216
+ set accessor(next) {
2217
+ if (this === object) {
2218
+ throw new TypeError("Cannot assign to read only property '" + String(key) + "' of a built-in");
2219
+ }
2220
+ if ((typeof this !== "object" || this === null) && typeof this !== "function") return;
2221
+ Object.defineProperty(this, key, { value: next, writable: true, enumerable: true, configurable: true });
2222
+ },
2223
+ },
2224
+ "accessor",
2225
+ );
2226
+ Object.defineProperty(object, key, { get, set, enumerable, configurable: false });
2227
+ add(get);
2228
+ add(set);
2229
+ }
2230
+
2231
+ for (const key of Reflect.ownKeys(globalThis)) {
2232
+ const descriptor = Object.getOwnPropertyDescriptor(globalThis, key);
2233
+ add(descriptor.value);
2234
+ add(descriptor.get);
2235
+ add(descriptor.set);
2236
+ if ("value" in descriptor && descriptor.configurable) {
2237
+ Object.defineProperty(globalThis, key, { writable: false, configurable: false });
2238
+ }
2239
+ }
2240
+ add(Object.getPrototypeOf(function* () {}));
2241
+ add(Object.getPrototypeOf(async function () {}));
2242
+ add(Object.getPrototypeOf(async function* () {}));
2243
+ add(Object.getPrototypeOf(Int8Array));
2244
+ add(Object.getPrototypeOf([][Symbol.iterator]()));
2245
+ add(Object.getPrototypeOf(new Map()[Symbol.iterator]()));
2246
+ add(Object.getPrototypeOf(new Set()[Symbol.iterator]()));
2247
+ add(Object.getPrototypeOf(""[Symbol.iterator]()));
2248
+ add(Object.getPrototypeOf(/a/[Symbol.matchAll]("")));
2249
+ if (typeof Iterator === "function") {
2250
+ if (typeof Iterator.prototype.map === "function") add(Object.getPrototypeOf([].values().map((x) => x)));
2251
+ if (typeof Iterator.from === "function") add(Object.getPrototypeOf(Iterator.from({ next() {} })));
2252
+ }
2253
+
2254
+ while (queue.length > 0) {
2255
+ const object = queue.pop();
2256
+ add(Object.getPrototypeOf(object));
2257
+ const descriptors = Object.getOwnPropertyDescriptors(object);
2258
+ for (const key of Reflect.ownKeys(descriptors)) {
2259
+ const descriptor = descriptors[key];
2260
+ if ("value" in descriptor) {
2261
+ add(descriptor.value);
2262
+ if (
2263
+ descriptor.writable &&
2264
+ descriptor.configurable &&
2265
+ (object === Object.prototype || OVERRIDABLE.has(key))
2266
+ ) {
2267
+ allowOverride(object, key, descriptor.value, descriptor.enumerable);
2268
+ }
2269
+ } else {
2270
+ add(descriptor.get);
2271
+ add(descriptor.set);
2272
+ }
2273
+ }
2274
+ Object.freeze(object);
2275
+ }
2276
+ })();
2277
+ const stringify = JSON.stringify;
2278
+ const parse = JSON.parse;
2279
+ const promiseThen = Promise.prototype.then;
2280
+ const ErrorCtor = Error;
2281
+ const TypeErrorCtor = TypeError;
2282
+ const RangeErrorCtor = RangeError;
2283
+ const pending = new Map();
2284
+ let nextId = 1;
2285
+ let finished = false;
2286
+ // Thrown by exit() to unwind the script after it already reported success.
2287
+ const EXIT = Object.freeze({});
2288
+
2289
+ function done(ok, payload, writes) {
2290
+ if (finished) return;
2291
+ finished = true;
2292
+ bridge("done", ok, payload, writes);
2293
+ }
2294
+
2295
+ function serialize(value) {
2296
+ return value === undefined ? undefined : stringify(value);
2297
+ }
2298
+
2299
+ // QuickJS stacks list frames only. Prefix "Name: message" like V8 so the
2300
+ // text reads the same as a Node error, and drop this prelude's frames.
2301
+ function errorText(error) {
2302
+ const head = error.message ? error.name + ": " + error.message : String(error.name);
2303
+ const frames =
2304
+ typeof error.stack === "string"
2305
+ ? error.stack.split("\\n").filter((line) => line.trim() && !line.includes("codemode-prelude.js"))
2306
+ : [];
2307
+ return [head, ...frames].join("\\n");
2308
+ }
2309
+
2310
+ function format(value) {
2311
+ if (typeof value === "string") return value;
2312
+ if (value instanceof ErrorCtor) return errorText(value);
2313
+ try {
2314
+ const json = stringify(value);
2315
+ return json === undefined ? String(value) : json;
2316
+ } catch {
2317
+ return String(value);
2318
+ }
2319
+ }
2320
+
2321
+ // The host requires string fields. A script can set an error's name or message to anything, so
2322
+ // they are coerced, and a value whose coercion throws gets a placeholder.
2323
+ function describeError(error) {
2324
+ try {
2325
+ if (error instanceof ErrorCtor) {
2326
+ return stringify({ name: String(error.name), message: String(error.message), stack: errorText(error) });
2327
+ }
2328
+ return stringify({ message: String(format(error)) });
2329
+ } catch {
2330
+ return stringify({ message: "The script threw a value that cannot be described" });
2331
+ }
2332
+ }
2333
+
2334
+ function caller(kind, name, spread) {
2335
+ return (...args) =>
2336
+ new Promise((resolve, reject) => {
2337
+ let json;
2338
+ try {
2339
+ json = serialize(spread ? args : args[0]);
2340
+ } catch (error) {
2341
+ reject(error);
2342
+ return;
2343
+ }
2344
+ const id = nextId++;
2345
+ pending.set(id, { resolve, reject });
2346
+ bridge(kind, id, name, json);
2347
+ });
2348
+ }
2349
+
2350
+ const tools = Object.create(null);
2351
+ const allTools = [];
2352
+ for (const { name, jsName, description } of parse(toolsJson)) {
2353
+ const fn = caller("call", name);
2354
+ // The first tool wins when two names normalize to the same identifier.
2355
+ if (!(jsName in tools)) {
2356
+ tools[jsName] = fn;
2357
+ allTools.push(Object.freeze({ name: jsName, description }));
2358
+ }
2359
+ if (!(name in tools)) tools[name] = fn;
2360
+ }
2361
+ Object.freeze(tools);
2362
+ Object.freeze(allTools);
2363
+
2364
+ // Reading a member that does not exist throws an error that names the close matches, instead of
2365
+ // a later "not a function". \`in\` checks still work.
2366
+ const comparable = (name) => name.toLowerCase().replace(/[^a-z0-9]/g, "");
2367
+ function guard(target, label, names, hint) {
2368
+ return new Proxy(target, {
2369
+ get(object, property, receiver) {
2370
+ if (typeof property !== "string" || property in object || property in Object.prototype || property === "then" || property === "toJSON") {
2371
+ return Reflect.get(object, property, receiver);
2372
+ }
2373
+ const wanted = comparable(property);
2374
+ const exact = names.filter((name) => comparable(name) === wanted);
2375
+ const close = exact.length > 0 ? exact : names.filter((name) => wanted && (comparable(name).includes(wanted) || wanted.includes(comparable(name))));
2376
+ let message = label + "." + property + " does not exist.";
2377
+ if (close.length > 0) message += " Did you mean " + close.slice(0, 5).map((name) => label + "." + name).join(", ") + "?";
2378
+ else if (names.length <= 20) message += " Available: " + names.join(", ") + ".";
2379
+ if (hint) message += " " + hint;
2380
+ message += ' Check for a member with "' + property + '" in ' + label + ".";
2381
+ throw new TypeErrorCtor(message);
2382
+ },
2383
+ });
2384
+ }
2385
+ const toolsProxy = guard(
2386
+ tools,
2387
+ "tools",
2388
+ allTools.map((tool) => tool.name),
2389
+ "ALL_TOOLS lists every tool; searchTools(query) finds tools by topic.",
2390
+ );
2391
+
2392
+ const namespaces = new Map();
2393
+ for (const { name, spread } of parse(globalsJson)) {
2394
+ const fn = caller("global", name, spread);
2395
+ const dot = name.indexOf(".");
2396
+ if (dot === -1) {
2397
+ Object.defineProperty(globalThis, name, { value: fn, enumerable: true });
2398
+ continue;
2399
+ }
2400
+ const namespace = name.slice(0, dot);
2401
+ if (!namespaces.has(namespace)) namespaces.set(namespace, Object.create(null));
2402
+ namespaces.get(namespace)[name.slice(dot + 1)] = fn;
2403
+ }
2404
+ for (const [namespace, members] of namespaces) {
2405
+ Object.freeze(members);
2406
+ const value = guard(members, namespace, Object.keys(members));
2407
+ Object.defineProperty(globalThis, namespace, { value, enumerable: true });
2408
+ }
2409
+
2410
+ // key -> JSON text. Sizes count key and JSON characters.
2411
+ const stored = new Map(Object.entries(parse(storeJson)));
2412
+ const writes = new Map();
2413
+ let storedChars = 0;
2414
+ for (const [key, json] of stored) storedChars += key.length + json.length;
2415
+
2416
+ const STORE_HINT =
2417
+ "store() is for small state such as IDs or summaries. Show images with image(), keep large data in variables, or write it to a file with a tool.";
2418
+
2419
+ function checkKey(name, key) {
2420
+ if (typeof key !== "string") throw new TypeError(name + "() key must be a string");
2421
+ }
2422
+
2423
+ function store(key, value) {
2424
+ checkKey("store", key);
2425
+ const previous = stored.has(key) ? key.length + stored.get(key).length : 0;
2426
+ if (value === undefined) {
2427
+ stored.delete(key);
2428
+ storedChars -= previous;
2429
+ writes.set(key, undefined);
2430
+ return;
2431
+ }
2432
+ let json;
2433
+ try {
2434
+ json = stringify(value);
2435
+ } catch (error) {
2436
+ throw new TypeError("store(" + stringify(key) + ") value is not JSON-serializable: " + format(error));
2437
+ }
2438
+ if (json === undefined) {
2439
+ throw new TypeError("store(" + stringify(key) + ") value is not JSON-serializable");
2440
+ }
2441
+ if (json.length > ${MAX_STORE_VALUE_CHARS}) {
2442
+ throw new RangeError(
2443
+ "store(" + stringify(key) + ") value has " + json.length + " characters of JSON, more than the limit of ${MAX_STORE_VALUE_CHARS}. " +
2444
+ STORE_HINT,
2445
+ );
2446
+ }
2447
+ const next = storedChars - previous + key.length + json.length;
2448
+ if (next > ${MAX_STORE_TOTAL_CHARS}) {
2449
+ throw new RangeError(
2450
+ "store is full: stored values would exceed ${MAX_STORE_TOTAL_CHARS} characters of JSON. Delete keys with store(key, undefined). " +
2451
+ STORE_HINT,
2452
+ );
2453
+ }
2454
+ stored.set(key, json);
2455
+ storedChars = next;
2456
+ writes.set(key, json);
2457
+ }
2458
+
2459
+ function load(key) {
2460
+ checkKey("load", key);
2461
+ const json = stored.get(key);
2462
+ return json === undefined ? undefined : parse(json);
2463
+ }
2464
+
2465
+ function serializeWrites() {
2466
+ const entries = [];
2467
+ for (const [key, json] of writes) entries.push(json === undefined ? [key] : [key, json]);
2468
+ return stringify(entries);
2469
+ }
2470
+
2471
+ Object.defineProperty(globalThis, "store", { value: store, enumerable: true });
2472
+ Object.defineProperty(globalThis, "load", { value: load, enumerable: true });
2473
+
2474
+ let outputChars = 0;
2475
+ let outputItems = 0;
2476
+
2477
+ // Past the output limits the script fails: done() reports the error, so catching it does not
2478
+ // resume output, and the host ends the script.
2479
+ function output(kind, data, mimeType) {
2480
+ if (finished) return;
2481
+ outputChars += data.length;
2482
+ outputItems++;
2483
+ if (outputChars > ${MAX_OUTPUT_CHARS} || outputItems > ${MAX_OUTPUT_ITEMS}) {
2484
+ const error = new RangeErrorCtor(
2485
+ "script output exceeded the limit of ${MAX_OUTPUT_CHARS} characters or ${MAX_OUTPUT_ITEMS} text(), image(), and console calls. " +
2486
+ "Print a summary instead, or write large data to a file with a tool.",
2487
+ );
2488
+ done(false, describeError(error));
2489
+ throw error;
2490
+ }
2491
+ bridge("output", kind, data, mimeType);
2492
+ }
2493
+
2494
+ // Primitives become their string form, everything else JSON.
2495
+ function outputText(value) {
2496
+ if (value === undefined || value === null || typeof value !== "object" && typeof value !== "function") {
2497
+ return String(value);
2498
+ }
2499
+ const json = stringify(value);
2500
+ return json === undefined ? String(value) : json;
2501
+ }
2502
+
2503
+ function text(value) {
2504
+ let rendered;
2505
+ try {
2506
+ rendered = outputText(value);
2507
+ } catch (error) {
2508
+ throw new TypeErrorCtor(error instanceof ErrorCtor ? error.message : String(error));
2509
+ }
2510
+ output("text", rendered);
2511
+ }
2512
+
2513
+ function imageUrl(value) {
2514
+ if (typeof value === "string") return value;
2515
+ if (typeof value !== "object" || value === null || Array.isArray(value)) {
2516
+ throw new TypeErrorCtor(${JSON.stringify(IMAGE_HELPER_EXPECTS)});
2517
+ }
2518
+ if (value.image_url !== undefined) {
2519
+ if (typeof value.image_url !== "string") throw new TypeErrorCtor(${JSON.stringify(IMAGE_HELPER_EXPECTS)});
2520
+ return value.image_url;
2521
+ }
2522
+ if (typeof value.type !== "string") throw new TypeErrorCtor(${JSON.stringify(IMAGE_HELPER_EXPECTS)});
2523
+ if (value.type !== "image") {
2524
+ throw new TypeErrorCtor('image only accepts MCP image blocks, got "' + value.type + '"');
2525
+ }
2526
+ if (typeof value.data !== "string" || value.data === "") throw new TypeErrorCtor("image expected MCP image data");
2527
+ if (value.data.toLowerCase().startsWith("data:")) return value.data;
2528
+ return "data:;base64," + value.data;
2529
+ }
2530
+
2531
+ // Base64 of the signatures of the formats providers accept inline (PNG, JPEG except
2532
+ // JPEG-LS, GIF, "RIFF....WEBP"). Signatures start at byte 0, so their encodings are prefixes.
2533
+ const IMAGE_SIGNATURES = [
2534
+ ["image/png", /^iVBORw0KGg/],
2535
+ ["image/jpeg", /^[/]9j[/](?!9)/],
2536
+ ["image/gif", /^R0lGOD[dl]h/],
2537
+ ["image/webp", /^UklG.{8}RUJQ/],
2538
+ ];
2539
+
2540
+ function image(value) {
2541
+ const url = imageUrl(value);
2542
+ if (url === "") throw new TypeErrorCtor(${JSON.stringify(IMAGE_HELPER_EXPECTS)});
2543
+ const colon = url.indexOf(":");
2544
+ const scheme = colon === -1 ? "" : url.slice(0, colon).toLowerCase();
2545
+ if (scheme === "http" || scheme === "https") {
2546
+ throw new TypeErrorCtor("remote image URLs are not supported in tool outputs. Pass a base64 data URI instead");
2547
+ }
2548
+ const comma = url.indexOf(",");
2549
+ const header = comma === -1 ? [] : url.slice(colon + 1, comma).split(";");
2550
+ if (scheme !== "data" || comma === -1 || header.slice(1).every((part) => part.toLowerCase() !== "base64")) {
2551
+ throw new TypeErrorCtor("invalid image output. Pass a base64 data URI instead");
2552
+ }
2553
+ // Providers reject the whole request on a bad image, and a persisted image block would be
2554
+ // resent on every later turn. Line breaks from wrapped base64 are dropped. The declared type
2555
+ // is ignored in favor of the detected one, as providers also reject mismatches.
2556
+ const data = url.slice(comma + 1).replace(/\\s+/g, "");
2557
+ if (data.length % 4 !== 0 || !/^[A-Za-z0-9+/]+={0,2}$/.test(data)) {
2558
+ throw new TypeErrorCtor("invalid image output. The image data is not valid base64 (truncated or corrupted?)");
2559
+ }
2560
+ const head = data.slice(0, 16);
2561
+ const signature = IMAGE_SIGNATURES.find(([, pattern]) => pattern.test(head));
2562
+ if (!signature) {
2563
+ throw new TypeErrorCtor("invalid image output. The image data is not a PNG, JPEG, GIF, or WebP image");
2564
+ }
2565
+ output("image", data, signature[0]);
2566
+ }
2567
+
2568
+ function exit() {
2569
+ let writesJson;
2570
+ try {
2571
+ writesJson = serializeWrites();
2572
+ } catch (error) {
2573
+ done(false, describeError(error));
2574
+ throw EXIT;
2575
+ }
2576
+ done(true, undefined, writesJson);
2577
+ throw EXIT;
2578
+ }
2579
+
2580
+ const console = {};
2581
+ for (const level of ["log", "info", "warn", "error", "debug"]) {
2582
+ console[level] = (...args) => {
2583
+ output("console", args.map(format).join(" "));
2584
+ };
2585
+ }
2586
+ Object.freeze(console);
2587
+
2588
+ Object.defineProperty(globalThis, "tools", { value: toolsProxy, enumerable: true });
2589
+ Object.defineProperty(globalThis, "ALL_TOOLS", { value: allTools, enumerable: true });
2590
+ Object.defineProperty(globalThis, "console", { value: console, enumerable: true });
2591
+ Object.defineProperty(globalThis, "text", { value: text, enumerable: true });
2592
+ Object.defineProperty(globalThis, "image", { value: image, enumerable: true });
2593
+ Object.defineProperty(globalThis, "exit", { value: exit, enumerable: true });
2594
+
2595
+ return {
2596
+ settle(id, ok, payload) {
2597
+ const entry = pending.get(id);
2598
+ if (!entry) return;
2599
+ pending.delete(id);
2600
+ if (!ok) {
2601
+ entry.reject(new ErrorCtor(payload));
2602
+ return;
2603
+ }
2604
+ let value;
2605
+ try {
2606
+ value = payload === undefined ? undefined : parse(payload);
2607
+ } catch (error) {
2608
+ entry.reject(error);
2609
+ return;
2610
+ }
2611
+ entry.resolve(value);
2612
+ },
2613
+ run(fn) {
2614
+ let promise;
2615
+ try {
2616
+ promise = fn(toolsProxy, console);
2617
+ } catch (error) {
2618
+ done(false, describeError(error));
2619
+ return;
2620
+ }
2621
+ promiseThen.call(
2622
+ promise,
2623
+ (value) => {
2624
+ let json;
2625
+ try {
2626
+ json = serialize(value);
2627
+ } catch (error) {
2628
+ done(false, describeError(error));
2629
+ return;
2630
+ }
2631
+ done(true, json, serializeWrites());
2632
+ },
2633
+ (error) => {
2634
+ done(false, describeError(error));
2635
+ },
2636
+ );
2637
+ },
2638
+ stalled() {
2639
+ if (finished || pending.size > 0) return false;
2640
+ done(
2641
+ false,
2642
+ stringify({
2643
+ name: "Error",
2644
+ message:
2645
+ "The script is waiting on a promise that can never settle: no tool call is pending, and timers do not exist here.",
2646
+ }),
2647
+ );
2648
+ return true;
2649
+ },
2650
+ };
2651
+ })`;
2652
+
2653
+ // node_modules/@earendil-works/pi-codemode/dist/runtime/protocol.js
2654
+ function isHostToWorkerMessage(value) {
2655
+ return typeof value === "object" && value !== null && value.type === "result";
2656
+ }
2657
+
2658
+ // node_modules/@earendil-works/pi-codemode/dist/runtime/worker.js
2659
+ function post(message) {
2660
+ parentPort?.postMessage(message);
2661
+ }
2662
+ function crash(error) {
2663
+ post({ type: "crash", message: error instanceof Error ? `${error.name}: ${error.message}` : String(error) });
2664
+ }
2665
+ function discardOutput(memory) {
2666
+ return {
2667
+ fd_write(_fd, iovsPtr, iovsLen, nwrittenPtr) {
2668
+ const view = new DataView(memory.buffer);
2669
+ let written = 0;
2670
+ for (let i = 0;i < iovsLen; i++) {
2671
+ written += view.getUint32(iovsPtr + i * 8 + 4, true);
2672
+ }
2673
+ view.setUint32(nwrittenPtr, written, true);
2674
+ return 0;
2675
+ }
2676
+ };
2677
+ }
2678
+ function describeException(error) {
2679
+ const head = error.message ? `${error.name}: ${error.message}` : error.name;
2680
+ const stack = error.stack?.trimEnd();
2681
+ return JSON.stringify({ name: error.name, message: error.message, stack: stack ? `${head}
2682
+ ${stack}` : head });
2683
+ }
2684
+ async function main(data) {
2685
+ const interrupt = new Int32Array(data.interrupt);
2686
+ const vm = await QuickJS.create({
2687
+ wasm: data.wasm,
2688
+ memoryLimit: data.memoryLimitBytes,
2689
+ maxStackSize: MAX_STACK_SIZE,
2690
+ interruptHandler: () => Atomics.load(interrupt, 0) !== 0,
2691
+ wasi: discardOutput
2692
+ });
2693
+ const bridge = vm.newFunction("bridge", (kind, a, b, c) => {
2694
+ switch (kind.toString()) {
2695
+ case "call":
2696
+ case "global":
2697
+ post({
2698
+ type: "call",
2699
+ id: a.toNumber(),
2700
+ target: kind.toString() === "call" ? "tool" : "global",
2701
+ name: b.toString(),
2702
+ args: c === undefined || c.isUndefined ? undefined : c.toString()
2703
+ });
2704
+ break;
2705
+ case "output":
2706
+ post({
2707
+ type: "output",
2708
+ item: a.toString() === "image" ? { type: "image", data: b.toString(), mimeType: c.toString() } : a.toString() === "console" ? { type: "text", text: b.toString(), console: true } : { type: "text", text: b.toString() }
2709
+ });
2710
+ break;
2711
+ case "done":
2712
+ if (a.toBoolean()) {
2713
+ post({
2714
+ type: "done",
2715
+ ok: true,
2716
+ value: b === undefined || b.isUndefined ? undefined : b.toString(),
2717
+ writes: c.toString()
2718
+ });
2719
+ } else {
2720
+ post({ type: "done", ok: false, error: b.toString() });
2721
+ }
2722
+ break;
2723
+ }
2724
+ return vm.undefined;
2725
+ });
2726
+ const api = vm.withScope((scope) => scope.escape(vm.callFunction(vm.evalCode(PRELUDE_SOURCE, "codemode-prelude.js"), vm.undefined, bridge, vm.newString(JSON.stringify(data.tools)), vm.newString(JSON.stringify(data.globals)), vm.newString(JSON.stringify(data.store)))));
2727
+ const settle = api.getProp("settle");
2728
+ const run = api.getProp("run");
2729
+ const stalled = api.getProp("stalled");
2730
+ const drain = () => {
2731
+ vm.executePendingJobs();
2732
+ vm.callFunction(stalled, api).dispose();
2733
+ };
2734
+ parentPort?.on("message", (message) => {
2735
+ if (!isHostToWorkerMessage(message))
2736
+ return;
2737
+ try {
2738
+ vm.withScope(() => {
2739
+ vm.callFunction(settle, api, vm.newNumber(message.id), message.ok ? vm.true : vm.false, message.payload === undefined ? vm.undefined : vm.newString(message.payload));
2740
+ });
2741
+ drain();
2742
+ } catch (error) {
2743
+ crash(error);
2744
+ }
2745
+ });
2746
+ let fn;
2747
+ try {
2748
+ fn = vm.evalCode(`(async (tools, console) => {${data.code}
2749
+ })`, "codemode.js");
2750
+ } catch (error) {
2751
+ if (!(error instanceof JSException))
2752
+ throw error;
2753
+ post({ type: "done", ok: false, error: describeException(error) });
2754
+ return;
2755
+ }
2756
+ vm.callFunction(run, api, fn).dispose();
2757
+ fn.dispose();
2758
+ drain();
2759
+ }
2760
+ if (parentPort) {
2761
+ main(workerData).catch(crash);
2762
+ }