@alpaca-headless/dynamic-renderings-engine 1.0.4694

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,1915 @@
1
+ import { createRequire as __parheliaCreateRequire } from "node:module"; const require = __parheliaCreateRequire(import.meta.url);
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropNames = Object.getOwnPropertyNames;
4
+ var __esm = (fn, res, err) => function __init() {
5
+ if (err) throw err[0];
6
+ try {
7
+ return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
8
+ } catch (e) {
9
+ throw err = [e], e;
10
+ }
11
+ };
12
+ var __export = (target, all) => {
13
+ for (var name in all)
14
+ __defProp(target, name, { get: all[name], enumerable: true });
15
+ };
16
+
17
+ // ../node_modules/@jitl/quickjs-ffi-types/dist/index.mjs
18
+ var EvalFlags, IntrinsicsFlags, JSPromiseStateEnum, GetOwnPropertyNamesFlags, IsEqualOp;
19
+ var init_dist = __esm({
20
+ "../node_modules/@jitl/quickjs-ffi-types/dist/index.mjs"() {
21
+ EvalFlags = { JS_EVAL_TYPE_GLOBAL: 0, JS_EVAL_TYPE_MODULE: 1, JS_EVAL_TYPE_DIRECT: 2, JS_EVAL_TYPE_INDIRECT: 3, JS_EVAL_TYPE_MASK: 3, JS_EVAL_FLAG_STRICT: 8, JS_EVAL_FLAG_STRIP: 16, JS_EVAL_FLAG_COMPILE_ONLY: 32, JS_EVAL_FLAG_BACKTRACE_BARRIER: 64 };
22
+ IntrinsicsFlags = { BaseObjects: 1, Date: 2, Eval: 4, StringNormalize: 8, RegExp: 16, RegExpCompiler: 32, JSON: 64, Proxy: 128, MapSet: 256, TypedArrays: 512, Promise: 1024, BigInt: 2048, BigFloat: 4096, BigDecimal: 8192, OperatorOverloading: 16384, BignumExt: 32768 };
23
+ JSPromiseStateEnum = { Pending: 0, Fulfilled: 1, Rejected: 2 };
24
+ GetOwnPropertyNamesFlags = { JS_GPN_STRING_MASK: 1, JS_GPN_SYMBOL_MASK: 2, JS_GPN_PRIVATE_MASK: 4, JS_GPN_ENUM_ONLY: 16, JS_GPN_SET_ENUM: 32, QTS_GPN_NUMBER_MASK: 64, QTS_STANDARD_COMPLIANT_NUMBER: 128 };
25
+ IsEqualOp = { IsStrictlyEqual: 0, IsSameValue: 1, IsSameValueZero: 2 };
26
+ }
27
+ });
28
+
29
+ // ../node_modules/quickjs-emscripten-core/dist/chunk-V2S4ZYJR.mjs
30
+ function debugLog(...args) {
31
+ QTS_DEBUG && console.log("quickjs-emscripten:", ...args);
32
+ }
33
+ function* awaitYield(value) {
34
+ return yield value;
35
+ }
36
+ function awaitYieldOf(generator) {
37
+ return awaitYield(awaitEachYieldedPromise(generator));
38
+ }
39
+ function maybeAsyncFn(that, fn) {
40
+ return (...args) => {
41
+ let generator = fn.call(that, AwaitYield, ...args);
42
+ return awaitEachYieldedPromise(generator);
43
+ };
44
+ }
45
+ function maybeAsync(that, startGenerator) {
46
+ let generator = startGenerator.call(that, AwaitYield);
47
+ return awaitEachYieldedPromise(generator);
48
+ }
49
+ function awaitEachYieldedPromise(gen) {
50
+ function handleNextStep(step) {
51
+ return step.done ? step.value : step.value instanceof Promise ? step.value.then((value) => handleNextStep(gen.next(value)), (error) => handleNextStep(gen.throw(error))) : handleNextStep(gen.next(step.value));
52
+ }
53
+ return handleNextStep(gen.next());
54
+ }
55
+ function scopeFinally(scope, blockError) {
56
+ let disposeError;
57
+ try {
58
+ scope.dispose();
59
+ } catch (error) {
60
+ disposeError = error;
61
+ }
62
+ if (blockError && disposeError) throw Object.assign(blockError, { message: `${blockError.message}
63
+ Then, failed to dispose scope: ${disposeError.message}`, disposeError }), blockError;
64
+ if (blockError || disposeError) throw blockError || disposeError;
65
+ }
66
+ function createDisposableArray(items) {
67
+ let array = items ? Array.from(items) : [];
68
+ function disposeAlive() {
69
+ return array.forEach((disposable) => disposable.alive ? disposable.dispose() : void 0);
70
+ }
71
+ function someIsAlive() {
72
+ return array.some((disposable) => disposable.alive);
73
+ }
74
+ return Object.defineProperty(array, SymbolDispose, { configurable: true, enumerable: false, value: disposeAlive }), Object.defineProperty(array, "dispose", { configurable: true, enumerable: false, value: disposeAlive }), Object.defineProperty(array, "alive", { configurable: true, enumerable: false, get: someIsAlive }), array;
75
+ }
76
+ function isDisposable(value) {
77
+ return !!(value && (typeof value == "object" || typeof value == "function") && "alive" in value && typeof value.alive == "boolean" && "dispose" in value && typeof value.dispose == "function");
78
+ }
79
+ function intrinsicsToFlags(intrinsics) {
80
+ if (!intrinsics) return 0;
81
+ let result = 0;
82
+ for (let [maybeIntrinsicName, enabled] of Object.entries(intrinsics)) {
83
+ if (!(maybeIntrinsicName in IntrinsicsFlags)) throw new QuickJSUnknownIntrinsic(maybeIntrinsicName);
84
+ enabled && (result |= IntrinsicsFlags[maybeIntrinsicName]);
85
+ }
86
+ return result;
87
+ }
88
+ function evalOptionsToFlags(evalOptions) {
89
+ if (typeof evalOptions == "number") return evalOptions;
90
+ if (evalOptions === void 0) return 0;
91
+ let { type, strict, strip, compileOnly, backtraceBarrier } = evalOptions, flags = 0;
92
+ return type === "global" && (flags |= EvalFlags.JS_EVAL_TYPE_GLOBAL), type === "module" && (flags |= EvalFlags.JS_EVAL_TYPE_MODULE), strict && (flags |= EvalFlags.JS_EVAL_FLAG_STRICT), strip && (flags |= EvalFlags.JS_EVAL_FLAG_STRIP), compileOnly && (flags |= EvalFlags.JS_EVAL_FLAG_COMPILE_ONLY), backtraceBarrier && (flags |= EvalFlags.JS_EVAL_FLAG_BACKTRACE_BARRIER), flags;
93
+ }
94
+ function getOwnPropertyNamesOptionsToFlags(options) {
95
+ if (typeof options == "number") return options;
96
+ if (options === void 0) return 0;
97
+ let { strings: includeStrings, symbols: includeSymbols, quickjsPrivate: includePrivate, onlyEnumerable, numbers: includeNumbers, numbersAsStrings } = options, flags = 0;
98
+ return includeStrings && (flags |= GetOwnPropertyNamesFlags.JS_GPN_STRING_MASK), includeSymbols && (flags |= GetOwnPropertyNamesFlags.JS_GPN_SYMBOL_MASK), includePrivate && (flags |= GetOwnPropertyNamesFlags.JS_GPN_PRIVATE_MASK), onlyEnumerable && (flags |= GetOwnPropertyNamesFlags.JS_GPN_ENUM_ONLY), includeNumbers && (flags |= GetOwnPropertyNamesFlags.QTS_GPN_NUMBER_MASK), numbersAsStrings && (flags |= GetOwnPropertyNamesFlags.QTS_STANDARD_COMPLIANT_NUMBER), flags;
99
+ }
100
+ function concat(...values) {
101
+ let result = [];
102
+ for (let value of values) value !== void 0 && (result = result.concat(value));
103
+ return result;
104
+ }
105
+ function getGroupId(id) {
106
+ return id >> 8;
107
+ }
108
+ function applyBaseRuntimeOptions(runtime2, options) {
109
+ options.interruptHandler && runtime2.setInterruptHandler(options.interruptHandler), options.maxStackSizeBytes !== void 0 && runtime2.setMaxStackSize(options.maxStackSizeBytes), options.memoryLimitBytes !== void 0 && runtime2.setMemoryLimit(options.memoryLimitBytes);
110
+ }
111
+ function applyModuleEvalRuntimeOptions(runtime2, options) {
112
+ options.moduleLoader && runtime2.setModuleLoader(options.moduleLoader), options.shouldInterrupt && runtime2.setInterruptHandler(options.shouldInterrupt), options.memoryLimitBytes !== void 0 && runtime2.setMemoryLimit(options.memoryLimitBytes), options.maxStackSizeBytes !== void 0 && runtime2.setMaxStackSize(options.maxStackSizeBytes);
113
+ }
114
+ var __defProp2, __export2, QTS_DEBUG, errors_exports, QuickJSUnwrapError, QuickJSWrongOwner, QuickJSUseAfterFree, QuickJSNotImplemented, QuickJSAsyncifyError, QuickJSAsyncifySuspended, QuickJSMemoryLeakDetected, QuickJSEmscriptenModuleError, QuickJSUnknownIntrinsic, QuickJSPromisePending, QuickJSEmptyGetOwnPropertyNames, QuickJSHostRefRangeExceeded, QuickJSHostRefInvalid, AwaitYield, UsingDisposable, SymbolDispose, prototypeAsAny, Lifetime, StaticLifetime, WeakLifetime, Scope, AbstractDisposableResult, DisposableSuccess, DisposableFail, DisposableResult, QuickJSDeferredPromise, ModuleMemory, DefaultIntrinsics, QuickJSIterator, INT32_MIN, INT32_MAX, INVALID_HOST_REF_ID, HostRefMap, HostRef, ContextMemory, QuickJSContext, QuickJSRuntime, QuickJSEmscriptenModuleCallbacks, QuickJSModuleCallbacks, QuickJSWASMModule;
115
+ var init_chunk_V2S4ZYJR = __esm({
116
+ "../node_modules/quickjs-emscripten-core/dist/chunk-V2S4ZYJR.mjs"() {
117
+ init_dist();
118
+ init_dist();
119
+ __defProp2 = Object.defineProperty;
120
+ __export2 = (target, all) => {
121
+ for (var name in all) __defProp2(target, name, { get: all[name], enumerable: true });
122
+ };
123
+ QTS_DEBUG = false;
124
+ errors_exports = {};
125
+ __export2(errors_exports, { QuickJSAsyncifyError: () => QuickJSAsyncifyError, QuickJSAsyncifySuspended: () => QuickJSAsyncifySuspended, QuickJSEmptyGetOwnPropertyNames: () => QuickJSEmptyGetOwnPropertyNames, QuickJSEmscriptenModuleError: () => QuickJSEmscriptenModuleError, QuickJSHostRefInvalid: () => QuickJSHostRefInvalid, QuickJSHostRefRangeExceeded: () => QuickJSHostRefRangeExceeded, QuickJSMemoryLeakDetected: () => QuickJSMemoryLeakDetected, QuickJSNotImplemented: () => QuickJSNotImplemented, QuickJSPromisePending: () => QuickJSPromisePending, QuickJSUnknownIntrinsic: () => QuickJSUnknownIntrinsic, QuickJSUnwrapError: () => QuickJSUnwrapError, QuickJSUseAfterFree: () => QuickJSUseAfterFree, QuickJSWrongOwner: () => QuickJSWrongOwner });
126
+ QuickJSUnwrapError = class extends Error {
127
+ constructor(cause, context2) {
128
+ let message = typeof cause == "object" && cause && "message" in cause ? String(cause.message) : String(cause);
129
+ super(message);
130
+ this.cause = cause;
131
+ this.context = context2;
132
+ this.name = "QuickJSUnwrapError";
133
+ }
134
+ };
135
+ QuickJSWrongOwner = class extends Error {
136
+ constructor() {
137
+ super(...arguments);
138
+ this.name = "QuickJSWrongOwner";
139
+ }
140
+ };
141
+ QuickJSUseAfterFree = class extends Error {
142
+ constructor() {
143
+ super(...arguments);
144
+ this.name = "QuickJSUseAfterFree";
145
+ }
146
+ };
147
+ QuickJSNotImplemented = class extends Error {
148
+ constructor() {
149
+ super(...arguments);
150
+ this.name = "QuickJSNotImplemented";
151
+ }
152
+ };
153
+ QuickJSAsyncifyError = class extends Error {
154
+ constructor() {
155
+ super(...arguments);
156
+ this.name = "QuickJSAsyncifyError";
157
+ }
158
+ };
159
+ QuickJSAsyncifySuspended = class extends Error {
160
+ constructor() {
161
+ super(...arguments);
162
+ this.name = "QuickJSAsyncifySuspended";
163
+ }
164
+ };
165
+ QuickJSMemoryLeakDetected = class extends Error {
166
+ constructor() {
167
+ super(...arguments);
168
+ this.name = "QuickJSMemoryLeakDetected";
169
+ }
170
+ };
171
+ QuickJSEmscriptenModuleError = class extends Error {
172
+ constructor() {
173
+ super(...arguments);
174
+ this.name = "QuickJSEmscriptenModuleError";
175
+ }
176
+ };
177
+ QuickJSUnknownIntrinsic = class extends TypeError {
178
+ constructor() {
179
+ super(...arguments);
180
+ this.name = "QuickJSUnknownIntrinsic";
181
+ }
182
+ };
183
+ QuickJSPromisePending = class extends Error {
184
+ constructor() {
185
+ super(...arguments);
186
+ this.name = "QuickJSPromisePending";
187
+ }
188
+ };
189
+ QuickJSEmptyGetOwnPropertyNames = class extends Error {
190
+ constructor() {
191
+ super(...arguments);
192
+ this.name = "QuickJSEmptyGetOwnPropertyNames";
193
+ }
194
+ };
195
+ QuickJSHostRefRangeExceeded = class extends Error {
196
+ constructor() {
197
+ super(...arguments);
198
+ this.name = "QuickJSHostRefRangeExceeded";
199
+ }
200
+ };
201
+ QuickJSHostRefInvalid = class extends Error {
202
+ constructor() {
203
+ super(...arguments);
204
+ this.name = "QuickJSHostRefInvalid";
205
+ }
206
+ };
207
+ AwaitYield = awaitYield;
208
+ AwaitYield.of = awaitYieldOf;
209
+ UsingDisposable = class {
210
+ [Symbol.dispose]() {
211
+ return this.dispose();
212
+ }
213
+ };
214
+ SymbolDispose = Symbol.dispose ?? /* @__PURE__ */ Symbol.for("Symbol.dispose");
215
+ prototypeAsAny = UsingDisposable.prototype;
216
+ prototypeAsAny[SymbolDispose] || (prototypeAsAny[SymbolDispose] = function() {
217
+ return this.dispose();
218
+ });
219
+ Lifetime = class _Lifetime extends UsingDisposable {
220
+ constructor(_value, copier, disposer, _owner) {
221
+ super();
222
+ this._value = _value;
223
+ this.copier = copier;
224
+ this.disposer = disposer;
225
+ this._owner = _owner;
226
+ this._alive = true;
227
+ this._constructorStack = QTS_DEBUG ? new Error("Lifetime constructed").stack : void 0;
228
+ }
229
+ get alive() {
230
+ return this._alive;
231
+ }
232
+ get value() {
233
+ return this.assertAlive(), this._value;
234
+ }
235
+ get owner() {
236
+ return this._owner;
237
+ }
238
+ get dupable() {
239
+ return !!this.copier;
240
+ }
241
+ dup() {
242
+ if (this.assertAlive(), !this.copier) throw new Error("Non-dupable lifetime");
243
+ return new _Lifetime(this.copier(this._value), this.copier, this.disposer, this._owner);
244
+ }
245
+ consume(map) {
246
+ this.assertAlive();
247
+ let result = map(this);
248
+ return this.dispose(), result;
249
+ }
250
+ map(map) {
251
+ return this.assertAlive(), map(this);
252
+ }
253
+ tap(fn) {
254
+ return fn(this), this;
255
+ }
256
+ dispose() {
257
+ this.assertAlive(), this.disposer && this.disposer(this._value), this._alive = false;
258
+ }
259
+ assertAlive() {
260
+ if (!this.alive) throw this._constructorStack ? new QuickJSUseAfterFree(`Lifetime not alive
261
+ ${this._constructorStack}
262
+ Lifetime used`) : new QuickJSUseAfterFree("Lifetime not alive");
263
+ }
264
+ };
265
+ StaticLifetime = class extends Lifetime {
266
+ constructor(value, owner) {
267
+ super(value, void 0, void 0, owner);
268
+ }
269
+ get dupable() {
270
+ return true;
271
+ }
272
+ dup() {
273
+ return this;
274
+ }
275
+ dispose() {
276
+ }
277
+ };
278
+ WeakLifetime = class extends Lifetime {
279
+ constructor(value, copier, disposer, owner) {
280
+ super(value, copier, disposer, owner);
281
+ }
282
+ dispose() {
283
+ this._alive = false;
284
+ }
285
+ };
286
+ Scope = class _Scope extends UsingDisposable {
287
+ constructor() {
288
+ super(...arguments);
289
+ this._disposables = new Lifetime(/* @__PURE__ */ new Set());
290
+ this.manage = (lifetime) => (this._disposables.value.add(lifetime), lifetime);
291
+ }
292
+ static withScope(block) {
293
+ let scope = new _Scope(), blockError;
294
+ try {
295
+ return block(scope);
296
+ } catch (error) {
297
+ throw blockError = error, error;
298
+ } finally {
299
+ scopeFinally(scope, blockError);
300
+ }
301
+ }
302
+ static withScopeMaybeAsync(_this, block) {
303
+ return maybeAsync(void 0, function* (awaited) {
304
+ let scope = new _Scope(), blockError;
305
+ try {
306
+ return yield* awaited.of(block.call(_this, awaited, scope));
307
+ } catch (error) {
308
+ throw blockError = error, error;
309
+ } finally {
310
+ scopeFinally(scope, blockError);
311
+ }
312
+ });
313
+ }
314
+ static async withScopeAsync(block) {
315
+ let scope = new _Scope(), blockError;
316
+ try {
317
+ return await block(scope);
318
+ } catch (error) {
319
+ throw blockError = error, error;
320
+ } finally {
321
+ scopeFinally(scope, blockError);
322
+ }
323
+ }
324
+ get alive() {
325
+ return this._disposables.alive;
326
+ }
327
+ dispose() {
328
+ let lifetimes = Array.from(this._disposables.value.values()).reverse();
329
+ for (let lifetime of lifetimes) lifetime.alive && lifetime.dispose();
330
+ this._disposables.dispose();
331
+ }
332
+ };
333
+ AbstractDisposableResult = class _AbstractDisposableResult extends UsingDisposable {
334
+ static success(value) {
335
+ return new DisposableSuccess(value);
336
+ }
337
+ static fail(error, onUnwrap) {
338
+ return new DisposableFail(error, onUnwrap);
339
+ }
340
+ static is(result) {
341
+ return result instanceof _AbstractDisposableResult;
342
+ }
343
+ };
344
+ DisposableSuccess = class extends AbstractDisposableResult {
345
+ constructor(value) {
346
+ super();
347
+ this.value = value;
348
+ }
349
+ get alive() {
350
+ return isDisposable(this.value) ? this.value.alive : true;
351
+ }
352
+ dispose() {
353
+ isDisposable(this.value) && this.value.dispose();
354
+ }
355
+ unwrap() {
356
+ return this.value;
357
+ }
358
+ unwrapOr(_fallback) {
359
+ return this.value;
360
+ }
361
+ };
362
+ DisposableFail = class extends AbstractDisposableResult {
363
+ constructor(error, onUnwrap) {
364
+ super();
365
+ this.error = error;
366
+ this.onUnwrap = onUnwrap;
367
+ }
368
+ get alive() {
369
+ return isDisposable(this.error) ? this.error.alive : true;
370
+ }
371
+ dispose() {
372
+ isDisposable(this.error) && this.error.dispose();
373
+ }
374
+ unwrap() {
375
+ throw this.onUnwrap(this), this.error;
376
+ }
377
+ unwrapOr(fallback) {
378
+ return fallback;
379
+ }
380
+ };
381
+ DisposableResult = AbstractDisposableResult;
382
+ QuickJSDeferredPromise = class extends UsingDisposable {
383
+ constructor(args) {
384
+ super();
385
+ this.resolve = (value) => {
386
+ this.resolveHandle.alive && (this.context.unwrapResult(this.context.callFunction(this.resolveHandle, this.context.undefined, value || this.context.undefined)).dispose(), this.disposeResolvers(), this.onSettled());
387
+ };
388
+ this.reject = (value) => {
389
+ this.rejectHandle.alive && (this.context.unwrapResult(this.context.callFunction(this.rejectHandle, this.context.undefined, value || this.context.undefined)).dispose(), this.disposeResolvers(), this.onSettled());
390
+ };
391
+ this.dispose = () => {
392
+ this.handle.alive && this.handle.dispose(), this.disposeResolvers();
393
+ };
394
+ this.context = args.context, this.owner = args.context.runtime, this.handle = args.promiseHandle, this.settled = new Promise((resolve) => {
395
+ this.onSettled = resolve;
396
+ }), this.resolveHandle = args.resolveHandle, this.rejectHandle = args.rejectHandle;
397
+ }
398
+ get alive() {
399
+ return this.handle.alive || this.resolveHandle.alive || this.rejectHandle.alive;
400
+ }
401
+ disposeResolvers() {
402
+ this.resolveHandle.alive && this.resolveHandle.dispose(), this.rejectHandle.alive && this.rejectHandle.dispose();
403
+ }
404
+ };
405
+ ModuleMemory = class {
406
+ constructor(module) {
407
+ this.module = module;
408
+ }
409
+ toPointerArray(handleArray) {
410
+ let typedArray = new Int32Array(handleArray.map((handle) => handle.value)), numBytes = typedArray.length * typedArray.BYTES_PER_ELEMENT, ptr = this.module._malloc(numBytes);
411
+ return new Uint8Array(this.module.HEAPU8.buffer, ptr, numBytes).set(new Uint8Array(typedArray.buffer)), new Lifetime(ptr, void 0, (ptr2) => this.module._free(ptr2));
412
+ }
413
+ newTypedArray(kind, length) {
414
+ let zeros = new kind(new Array(length).fill(0)), numBytes = zeros.length * zeros.BYTES_PER_ELEMENT, ptr = this.module._malloc(numBytes), typedArray = new kind(this.module.HEAPU8.buffer, ptr, length);
415
+ return typedArray.set(zeros), new Lifetime({ typedArray, ptr }, void 0, (value) => this.module._free(value.ptr));
416
+ }
417
+ newMutablePointerArray(length) {
418
+ return this.newTypedArray(Int32Array, length);
419
+ }
420
+ newHeapCharPointer(string) {
421
+ let strlen = this.module.lengthBytesUTF8(string), dataBytes = strlen + 1, ptr = this.module._malloc(dataBytes);
422
+ return this.module.stringToUTF8(string, ptr, dataBytes), new Lifetime({ ptr, strlen }, void 0, (value) => this.module._free(value.ptr));
423
+ }
424
+ newHeapBufferPointer(buffer) {
425
+ let numBytes = buffer.byteLength, ptr = this.module._malloc(numBytes);
426
+ return this.module.HEAPU8.set(buffer, ptr), new Lifetime({ pointer: ptr, numBytes }, void 0, (value) => this.module._free(value.pointer));
427
+ }
428
+ consumeHeapCharPointer(ptr) {
429
+ let str = this.module.UTF8ToString(ptr);
430
+ return this.module._free(ptr), str;
431
+ }
432
+ };
433
+ DefaultIntrinsics = Object.freeze({ BaseObjects: true, Date: true, Eval: true, StringNormalize: true, RegExp: true, JSON: true, Proxy: true, MapSet: true, TypedArrays: true, Promise: true });
434
+ QuickJSIterator = class extends UsingDisposable {
435
+ constructor(handle, context2) {
436
+ super();
437
+ this.handle = handle;
438
+ this.context = context2;
439
+ this._isDone = false;
440
+ this.owner = context2.runtime;
441
+ }
442
+ [Symbol.iterator]() {
443
+ return this;
444
+ }
445
+ next(value) {
446
+ if (!this.alive || this._isDone) return { done: true, value: void 0 };
447
+ let nextMethod = this._next ?? (this._next = this.context.getProp(this.handle, "next"));
448
+ return this.callIteratorMethod(nextMethod, value);
449
+ }
450
+ return(value) {
451
+ if (!this.alive) return { done: true, value: void 0 };
452
+ let returnMethod = this.context.getProp(this.handle, "return");
453
+ if (returnMethod === this.context.undefined && value === void 0) return this.dispose(), { done: true, value: void 0 };
454
+ let result = this.callIteratorMethod(returnMethod, value);
455
+ return returnMethod.dispose(), this.dispose(), result;
456
+ }
457
+ throw(e) {
458
+ if (!this.alive) return { done: true, value: void 0 };
459
+ let errorHandle = e instanceof Lifetime ? e : this.context.newError(e), throwMethod = this.context.getProp(this.handle, "throw"), result = this.callIteratorMethod(throwMethod, e);
460
+ return errorHandle.alive && errorHandle.dispose(), throwMethod.dispose(), this.dispose(), result;
461
+ }
462
+ get alive() {
463
+ return this.handle.alive;
464
+ }
465
+ dispose() {
466
+ this._isDone = true, this.handle.dispose(), this._next?.dispose();
467
+ }
468
+ callIteratorMethod(method, input) {
469
+ let callResult = input ? this.context.callFunction(method, this.handle, input) : this.context.callFunction(method, this.handle);
470
+ if (callResult.error) return this.dispose(), { value: callResult };
471
+ let done = this.context.getProp(callResult.value, "done").consume((v) => this.context.dump(v)), value = this.context.getProp(callResult.value, "value");
472
+ return callResult.value.dispose(), done && this.dispose(), { value: DisposableResult.success(value), done };
473
+ }
474
+ };
475
+ INT32_MIN = -2147483648;
476
+ INT32_MAX = 2147483647;
477
+ INVALID_HOST_REF_ID = 0;
478
+ HostRefMap = class {
479
+ constructor() {
480
+ this.nextId = INT32_MIN;
481
+ this.freelist = [];
482
+ this.groups = /* @__PURE__ */ new Map();
483
+ }
484
+ put(value) {
485
+ let id = this.allocateId(), groupId = getGroupId(id), group = this.groups.get(groupId);
486
+ return group || (group = /* @__PURE__ */ new Map(), this.groups.set(groupId, group)), group.set(id, value), id;
487
+ }
488
+ get(id) {
489
+ if (id === INVALID_HOST_REF_ID) throw new QuickJSHostRefInvalid("no host reference id defined");
490
+ let groupId = getGroupId(id), group = this.groups.get(groupId);
491
+ if (!group) throw new QuickJSHostRefInvalid(`host reference id ${id} is not defined`);
492
+ let value = group.get(id);
493
+ if (!value) throw new QuickJSHostRefInvalid(`host reference id ${id} is not defined`);
494
+ return value;
495
+ }
496
+ delete(id) {
497
+ if (id === INVALID_HOST_REF_ID) throw new QuickJSHostRefInvalid("no host reference id defined");
498
+ let groupId = getGroupId(id), group = this.groups.get(groupId);
499
+ if (!group) throw new QuickJSHostRefInvalid(`host reference id ${id} is not defined`);
500
+ group.delete(id), group.size === 0 && this.groups.delete(groupId), this.freelist.push(id);
501
+ }
502
+ allocateId() {
503
+ if (this.freelist.length > 0) return this.freelist.shift();
504
+ if (this.nextId === INVALID_HOST_REF_ID && this.nextId++, this.nextId > INT32_MAX) throw new QuickJSHostRefRangeExceeded(`HostRefMap: too many host refs created without disposing. Max simultaneous host refs: ${INT32_MAX - INT32_MIN}`);
505
+ return this.nextId++;
506
+ }
507
+ };
508
+ HostRef = class extends UsingDisposable {
509
+ constructor(runtime2, handle, id) {
510
+ if (id === INVALID_HOST_REF_ID) throw new QuickJSHostRefInvalid("cannot create HostRef with undefined id");
511
+ super();
512
+ this.runtime = runtime2;
513
+ this.handle = handle;
514
+ this.id = id;
515
+ }
516
+ get alive() {
517
+ return this.handle.alive;
518
+ }
519
+ dispose() {
520
+ this.handle.dispose();
521
+ }
522
+ get value() {
523
+ return this.runtime.hostRefs.get(this.id);
524
+ }
525
+ };
526
+ ContextMemory = class extends ModuleMemory {
527
+ constructor(args) {
528
+ super(args.module);
529
+ this.scope = new Scope();
530
+ this.copyJSValue = (ptr) => this.ffi.QTS_DupValuePointer(this.ctx.value, ptr);
531
+ this.freeJSValue = (ptr) => {
532
+ this.ffi.QTS_FreeValuePointer(this.ctx.value, ptr);
533
+ };
534
+ args.ownedLifetimes?.forEach((lifetime) => this.scope.manage(lifetime)), this.owner = args.owner, this.module = args.module, this.ffi = args.ffi, this.rt = args.rt, this.ctx = this.scope.manage(args.ctx);
535
+ }
536
+ get alive() {
537
+ return this.scope.alive;
538
+ }
539
+ dispose() {
540
+ return this.scope.dispose();
541
+ }
542
+ [Symbol.dispose]() {
543
+ return this.dispose();
544
+ }
545
+ manage(lifetime) {
546
+ return this.scope.manage(lifetime);
547
+ }
548
+ consumeJSCharPointer(ptr) {
549
+ let str = this.module.UTF8ToString(ptr);
550
+ return this.ffi.QTS_FreeCString(this.ctx.value, ptr), str;
551
+ }
552
+ heapValueHandle(ptr, extraDispose) {
553
+ let dispose2 = extraDispose ? (val) => {
554
+ extraDispose(), this.freeJSValue(val);
555
+ } : this.freeJSValue;
556
+ return new Lifetime(ptr, this.copyJSValue, dispose2, this.owner);
557
+ }
558
+ staticHeapValueHandle(ptr) {
559
+ return this.manage(this.heapValueHandle(ptr)), new StaticLifetime(ptr, this.owner);
560
+ }
561
+ };
562
+ QuickJSContext = class extends UsingDisposable {
563
+ constructor(args) {
564
+ super();
565
+ this._undefined = void 0;
566
+ this._null = void 0;
567
+ this._false = void 0;
568
+ this._true = void 0;
569
+ this._global = void 0;
570
+ this._BigInt = void 0;
571
+ this._Symbol = void 0;
572
+ this._SymbolIterator = void 0;
573
+ this._SymbolAsyncIterator = void 0;
574
+ this.cToHostCallbacks = { callFunction: (ctx, this_ptr, argc, argv, fn_id) => {
575
+ if (ctx !== this.ctx.value) throw new Error("QuickJSContext instance received C -> JS call with mismatched ctx");
576
+ let fn = this.getFunction(fn_id);
577
+ return Scope.withScopeMaybeAsync(this, function* (awaited, scope) {
578
+ let thisHandle = scope.manage(new WeakLifetime(this_ptr, this.memory.copyJSValue, this.memory.freeJSValue, this.runtime)), argHandles = new Array(argc);
579
+ for (let i = 0; i < argc; i++) {
580
+ let ptr = this.ffi.QTS_ArgvGetJSValueConstPointer(argv, i);
581
+ argHandles[i] = scope.manage(new WeakLifetime(ptr, this.memory.copyJSValue, this.memory.freeJSValue, this.runtime));
582
+ }
583
+ try {
584
+ let result = yield* awaited(fn.apply(thisHandle, argHandles));
585
+ if (result) {
586
+ if ("error" in result && result.error) throw this.runtime.debugLog("throw error", result.error), result.error;
587
+ let handle = scope.manage(result instanceof Lifetime ? result : result.value);
588
+ return this.ffi.QTS_DupValuePointer(this.ctx.value, handle.value);
589
+ }
590
+ return 0;
591
+ } catch (error) {
592
+ return this.errorToHandle(error).consume((errorHandle) => this.ffi.QTS_Throw(this.ctx.value, errorHandle.value));
593
+ }
594
+ });
595
+ } };
596
+ this.runtime = args.runtime, this.module = args.module, this.ffi = args.ffi, this.rt = args.rt, this.ctx = args.ctx, this.memory = new ContextMemory({ ...args, owner: this.runtime }), args.callbacks.setContextCallbacks(this.ctx.value, this.cToHostCallbacks), this.dump = this.dump.bind(this), this.getString = this.getString.bind(this), this.getNumber = this.getNumber.bind(this), this.resolvePromise = this.resolvePromise.bind(this), this.uint32Out = this.memory.manage(this.memory.newTypedArray(Uint32Array, 1));
597
+ }
598
+ get alive() {
599
+ return this.memory.alive;
600
+ }
601
+ dispose() {
602
+ this.memory.dispose();
603
+ }
604
+ get undefined() {
605
+ if (this._undefined) return this._undefined;
606
+ let ptr = this.ffi.QTS_GetUndefined();
607
+ return this._undefined = new StaticLifetime(ptr);
608
+ }
609
+ get null() {
610
+ if (this._null) return this._null;
611
+ let ptr = this.ffi.QTS_GetNull();
612
+ return this._null = new StaticLifetime(ptr);
613
+ }
614
+ get true() {
615
+ if (this._true) return this._true;
616
+ let ptr = this.ffi.QTS_GetTrue();
617
+ return this._true = new StaticLifetime(ptr);
618
+ }
619
+ get false() {
620
+ if (this._false) return this._false;
621
+ let ptr = this.ffi.QTS_GetFalse();
622
+ return this._false = new StaticLifetime(ptr);
623
+ }
624
+ get global() {
625
+ if (this._global) return this._global;
626
+ let ptr = this.ffi.QTS_GetGlobalObject(this.ctx.value);
627
+ return this._global = this.memory.staticHeapValueHandle(ptr), this._global;
628
+ }
629
+ newNumber(num) {
630
+ return this.memory.heapValueHandle(this.ffi.QTS_NewFloat64(this.ctx.value, num));
631
+ }
632
+ newString(str) {
633
+ let ptr = this.memory.newHeapCharPointer(str).consume((charHandle) => this.ffi.QTS_NewString(this.ctx.value, charHandle.value.ptr));
634
+ return this.memory.heapValueHandle(ptr);
635
+ }
636
+ newUniqueSymbol(description) {
637
+ let key = (typeof description == "symbol" ? description.description : description) ?? "", ptr = this.memory.newHeapCharPointer(key).consume((charHandle) => this.ffi.QTS_NewSymbol(this.ctx.value, charHandle.value.ptr, 0));
638
+ return this.memory.heapValueHandle(ptr);
639
+ }
640
+ newSymbolFor(key) {
641
+ let description = (typeof key == "symbol" ? key.description : key) ?? "", ptr = this.memory.newHeapCharPointer(description).consume((charHandle) => this.ffi.QTS_NewSymbol(this.ctx.value, charHandle.value.ptr, 1));
642
+ return this.memory.heapValueHandle(ptr);
643
+ }
644
+ getWellKnownSymbol(name) {
645
+ return this._Symbol ?? (this._Symbol = this.memory.manage(this.getProp(this.global, "Symbol"))), this.getProp(this._Symbol, name);
646
+ }
647
+ newBigInt(num) {
648
+ if (!this._BigInt) {
649
+ let bigIntHandle2 = this.getProp(this.global, "BigInt");
650
+ this.memory.manage(bigIntHandle2), this._BigInt = new StaticLifetime(bigIntHandle2.value, this.runtime);
651
+ }
652
+ let bigIntHandle = this._BigInt, asString = String(num);
653
+ return this.newString(asString).consume((handle) => this.unwrapResult(this.callFunction(bigIntHandle, this.undefined, handle)));
654
+ }
655
+ newObject(prototype) {
656
+ prototype && this.runtime.assertOwned(prototype);
657
+ let ptr = prototype ? this.ffi.QTS_NewObjectProto(this.ctx.value, prototype.value) : this.ffi.QTS_NewObject(this.ctx.value);
658
+ return this.memory.heapValueHandle(ptr);
659
+ }
660
+ newArray() {
661
+ let ptr = this.ffi.QTS_NewArray(this.ctx.value);
662
+ return this.memory.heapValueHandle(ptr);
663
+ }
664
+ newArrayBuffer(buffer) {
665
+ let array = new Uint8Array(buffer), handle = this.memory.newHeapBufferPointer(array), ptr = this.ffi.QTS_NewArrayBuffer(this.ctx.value, handle.value.pointer, array.length);
666
+ return this.memory.heapValueHandle(ptr);
667
+ }
668
+ newPromise(value) {
669
+ let deferredPromise = Scope.withScope((scope) => {
670
+ let mutablePointerArray = scope.manage(this.memory.newMutablePointerArray(2)), promisePtr = this.ffi.QTS_NewPromiseCapability(this.ctx.value, mutablePointerArray.value.ptr), promiseHandle = this.memory.heapValueHandle(promisePtr), [resolveHandle, rejectHandle] = Array.from(mutablePointerArray.value.typedArray).map((jsvaluePtr) => this.memory.heapValueHandle(jsvaluePtr));
671
+ return new QuickJSDeferredPromise({ context: this, promiseHandle, resolveHandle, rejectHandle });
672
+ });
673
+ return value && typeof value == "function" && (value = new Promise(value)), value && Promise.resolve(value).then(deferredPromise.resolve, (error) => error instanceof Lifetime ? deferredPromise.reject(error) : this.newError(error).consume(deferredPromise.reject)), deferredPromise;
674
+ }
675
+ newFunction(nameOrFn, maybeFn) {
676
+ let fn = typeof nameOrFn == "function" ? nameOrFn : maybeFn;
677
+ if (!fn) throw new TypeError("Expected a function");
678
+ return this.newFunctionWithOptions({ name: typeof nameOrFn == "string" ? nameOrFn : void 0, length: fn.length, isConstructor: false, fn });
679
+ }
680
+ newConstructorFunction(nameOrFn, maybeFn) {
681
+ let fn = typeof nameOrFn == "function" ? nameOrFn : maybeFn;
682
+ if (!fn) throw new TypeError("Expected a function");
683
+ return this.newFunctionWithOptions({ name: typeof nameOrFn == "string" ? nameOrFn : void 0, length: fn.length, isConstructor: true, fn });
684
+ }
685
+ newFunctionWithOptions(args) {
686
+ let { name, length, isConstructor, fn } = args, refId = this.runtime.hostRefs.put(fn);
687
+ try {
688
+ return this.memory.heapValueHandle(this.ffi.QTS_NewFunction(this.ctx.value, name ?? "", length, isConstructor, refId));
689
+ } catch (error) {
690
+ throw this.runtime.hostRefs.delete(refId), error;
691
+ }
692
+ }
693
+ newError(error) {
694
+ let errorHandle = this.memory.heapValueHandle(this.ffi.QTS_NewError(this.ctx.value));
695
+ return error && typeof error == "object" ? (error.name !== void 0 && this.newString(error.name).consume((handle) => this.setProp(errorHandle, "name", handle)), error.message !== void 0 && this.newString(error.message).consume((handle) => this.setProp(errorHandle, "message", handle))) : typeof error == "string" ? this.newString(error).consume((handle) => this.setProp(errorHandle, "message", handle)) : error !== void 0 && this.newString(String(error)).consume((handle) => this.setProp(errorHandle, "message", handle)), errorHandle;
696
+ }
697
+ newHostRef(value) {
698
+ let id = this.runtime.hostRefs.put(value);
699
+ try {
700
+ let handle = this.memory.heapValueHandle(this.ffi.QTS_NewHostRef(this.ctx.value, id));
701
+ return new HostRef(this.runtime, handle, id);
702
+ } catch (error) {
703
+ throw this.runtime.hostRefs.delete(id), error;
704
+ }
705
+ }
706
+ toHostRef(handle) {
707
+ let id = this.ffi.QTS_GetHostRefId(handle.value);
708
+ if (id !== 0) return this.runtime.hostRefs.get(id), new HostRef(this.runtime, handle.dup(), id);
709
+ }
710
+ unwrapHostRef(handle) {
711
+ let id = this.ffi.QTS_GetHostRefId(handle.value);
712
+ if (id === 0) throw new QuickJSHostRefInvalid("handle is not a HostRef");
713
+ return this.runtime.hostRefs.get(id);
714
+ }
715
+ typeof(handle) {
716
+ return this.runtime.assertOwned(handle), this.memory.consumeHeapCharPointer(this.ffi.QTS_Typeof(this.ctx.value, handle.value));
717
+ }
718
+ getNumber(handle) {
719
+ return this.runtime.assertOwned(handle), this.ffi.QTS_GetFloat64(this.ctx.value, handle.value);
720
+ }
721
+ getString(handle) {
722
+ return this.runtime.assertOwned(handle), this.memory.consumeJSCharPointer(this.ffi.QTS_GetString(this.ctx.value, handle.value));
723
+ }
724
+ getSymbol(handle) {
725
+ this.runtime.assertOwned(handle);
726
+ let key = this.memory.consumeJSCharPointer(this.ffi.QTS_GetSymbolDescriptionOrKey(this.ctx.value, handle.value));
727
+ return this.ffi.QTS_IsGlobalSymbol(this.ctx.value, handle.value) ? Symbol.for(key) : Symbol(key);
728
+ }
729
+ getBigInt(handle) {
730
+ this.runtime.assertOwned(handle);
731
+ let asString = this.getString(handle);
732
+ return BigInt(asString);
733
+ }
734
+ getArrayBuffer(handle) {
735
+ this.runtime.assertOwned(handle);
736
+ let len = this.ffi.QTS_GetArrayBufferLength(this.ctx.value, handle.value), ptr = this.ffi.QTS_GetArrayBuffer(this.ctx.value, handle.value);
737
+ if (!ptr) throw new Error("Couldn't allocate memory to get ArrayBuffer");
738
+ return new Lifetime(this.module.HEAPU8.subarray(ptr, ptr + len), void 0, () => this.module._free(ptr));
739
+ }
740
+ getPromiseState(handle) {
741
+ this.runtime.assertOwned(handle);
742
+ let state = this.ffi.QTS_PromiseState(this.ctx.value, handle.value);
743
+ if (state < 0) return { type: "fulfilled", value: handle, notAPromise: true };
744
+ if (state === JSPromiseStateEnum.Pending) return { type: "pending", get error() {
745
+ return new QuickJSPromisePending("Cannot unwrap a pending promise");
746
+ } };
747
+ let ptr = this.ffi.QTS_PromiseResult(this.ctx.value, handle.value), result = this.memory.heapValueHandle(ptr);
748
+ if (state === JSPromiseStateEnum.Fulfilled) return { type: "fulfilled", value: result };
749
+ if (state === JSPromiseStateEnum.Rejected) return { type: "rejected", error: result };
750
+ throw result.dispose(), new Error(`Unknown JSPromiseStateEnum: ${state}`);
751
+ }
752
+ resolvePromise(promiseLikeHandle) {
753
+ this.runtime.assertOwned(promiseLikeHandle);
754
+ let vmResolveResult = Scope.withScope((scope) => {
755
+ let vmPromise = scope.manage(this.getProp(this.global, "Promise")), vmPromiseResolve = scope.manage(this.getProp(vmPromise, "resolve"));
756
+ return this.callFunction(vmPromiseResolve, vmPromise, promiseLikeHandle);
757
+ });
758
+ return vmResolveResult.error ? Promise.resolve(vmResolveResult) : new Promise((resolve) => {
759
+ Scope.withScope((scope) => {
760
+ let resolveHandle = scope.manage(this.newFunction("resolve", (value) => {
761
+ resolve(this.success(value && value.dup()));
762
+ })), rejectHandle = scope.manage(this.newFunction("reject", (error) => {
763
+ resolve(this.fail(error && error.dup()));
764
+ })), promiseHandle = scope.manage(vmResolveResult.value), promiseThenHandle = scope.manage(this.getProp(promiseHandle, "then"));
765
+ this.callFunction(promiseThenHandle, promiseHandle, resolveHandle, rejectHandle).unwrap().dispose();
766
+ });
767
+ });
768
+ }
769
+ isEqual(a, b, equalityType = IsEqualOp.IsStrictlyEqual) {
770
+ if (a === b) return true;
771
+ this.runtime.assertOwned(a), this.runtime.assertOwned(b);
772
+ let result = this.ffi.QTS_IsEqual(this.ctx.value, a.value, b.value, equalityType);
773
+ if (result === -1) throw new QuickJSNotImplemented("WASM variant does not expose equality");
774
+ return !!result;
775
+ }
776
+ eq(handle, other) {
777
+ return this.isEqual(handle, other, IsEqualOp.IsStrictlyEqual);
778
+ }
779
+ sameValue(handle, other) {
780
+ return this.isEqual(handle, other, IsEqualOp.IsSameValue);
781
+ }
782
+ sameValueZero(handle, other) {
783
+ return this.isEqual(handle, other, IsEqualOp.IsSameValueZero);
784
+ }
785
+ getProp(handle, key) {
786
+ this.runtime.assertOwned(handle);
787
+ let ptr;
788
+ return typeof key == "number" && key >= 0 ? ptr = this.ffi.QTS_GetPropNumber(this.ctx.value, handle.value, key) : ptr = this.borrowPropertyKey(key).consume((quickJSKey) => this.ffi.QTS_GetProp(this.ctx.value, handle.value, quickJSKey.value)), this.memory.heapValueHandle(ptr);
789
+ }
790
+ getLength(handle) {
791
+ if (this.runtime.assertOwned(handle), !(this.ffi.QTS_GetLength(this.ctx.value, this.uint32Out.value.ptr, handle.value) < 0)) return this.uint32Out.value.typedArray[0];
792
+ }
793
+ getOwnPropertyNames(handle, options = { strings: true, numbersAsStrings: true }) {
794
+ this.runtime.assertOwned(handle), handle.value;
795
+ let flags = getOwnPropertyNamesOptionsToFlags(options);
796
+ if (flags === 0) throw new QuickJSEmptyGetOwnPropertyNames("No options set, will return an empty array");
797
+ return Scope.withScope((scope) => {
798
+ let outPtr = scope.manage(this.memory.newMutablePointerArray(1)), errorPtr = this.ffi.QTS_GetOwnPropertyNames(this.ctx.value, outPtr.value.ptr, this.uint32Out.value.ptr, handle.value, flags);
799
+ if (errorPtr) return this.fail(this.memory.heapValueHandle(errorPtr));
800
+ let len = this.uint32Out.value.typedArray[0], ptr = outPtr.value.typedArray[0], pointerArray = new Uint32Array(this.module.HEAP8.buffer, ptr, len), handles = Array.from(pointerArray).map((ptr2) => this.memory.heapValueHandle(ptr2));
801
+ return this.ffi.QTS_FreeVoidPointer(this.ctx.value, ptr), this.success(createDisposableArray(handles));
802
+ });
803
+ }
804
+ getIterator(iterableHandle) {
805
+ let SymbolIterator = this._SymbolIterator ?? (this._SymbolIterator = this.memory.manage(this.getWellKnownSymbol("iterator")));
806
+ return Scope.withScope((scope) => {
807
+ let methodHandle = scope.manage(this.getProp(iterableHandle, SymbolIterator)), iteratorCallResult = this.callFunction(methodHandle, iterableHandle);
808
+ return iteratorCallResult.error ? iteratorCallResult : this.success(new QuickJSIterator(iteratorCallResult.value, this));
809
+ });
810
+ }
811
+ setProp(handle, key, value) {
812
+ this.runtime.assertOwned(handle), this.borrowPropertyKey(key).consume((quickJSKey) => this.ffi.QTS_SetProp(this.ctx.value, handle.value, quickJSKey.value, value.value));
813
+ }
814
+ defineProp(handle, key, descriptor) {
815
+ this.runtime.assertOwned(handle), Scope.withScope((scope) => {
816
+ let quickJSKey = scope.manage(this.borrowPropertyKey(key)), value = descriptor.value || this.undefined, configurable = !!descriptor.configurable, enumerable = !!descriptor.enumerable, hasValue = !!descriptor.value, get = descriptor.get ? scope.manage(this.newFunction(descriptor.get.name, descriptor.get)) : this.undefined, set = descriptor.set ? scope.manage(this.newFunction(descriptor.set.name, descriptor.set)) : this.undefined;
817
+ this.ffi.QTS_DefineProp(this.ctx.value, handle.value, quickJSKey.value, value.value, get.value, set.value, configurable, enumerable, hasValue);
818
+ });
819
+ }
820
+ callFunction(func, thisVal, ...restArgs) {
821
+ this.runtime.assertOwned(func);
822
+ let args, firstArg = restArgs[0];
823
+ firstArg === void 0 || Array.isArray(firstArg) ? args = firstArg ?? [] : args = restArgs;
824
+ let resultPtr = this.memory.toPointerArray(args).consume((argsArrayPtr) => this.ffi.QTS_Call(this.ctx.value, func.value, thisVal.value, args.length, argsArrayPtr.value)), errorPtr = this.ffi.QTS_ResolveException(this.ctx.value, resultPtr);
825
+ return errorPtr ? (this.ffi.QTS_FreeValuePointer(this.ctx.value, resultPtr), this.fail(this.memory.heapValueHandle(errorPtr))) : this.success(this.memory.heapValueHandle(resultPtr));
826
+ }
827
+ callMethod(thisHandle, key, args = []) {
828
+ return this.getProp(thisHandle, key).consume((func) => this.callFunction(func, thisHandle, args));
829
+ }
830
+ evalCode(code, filename = "eval.js", options) {
831
+ let detectModule = options === void 0 ? 1 : 0, flags = evalOptionsToFlags(options), resultPtr = this.memory.newHeapCharPointer(code).consume((charHandle) => this.ffi.QTS_Eval(this.ctx.value, charHandle.value.ptr, charHandle.value.strlen, filename, detectModule, flags)), errorPtr = this.ffi.QTS_ResolveException(this.ctx.value, resultPtr);
832
+ return errorPtr ? (this.ffi.QTS_FreeValuePointer(this.ctx.value, resultPtr), this.fail(this.memory.heapValueHandle(errorPtr))) : this.success(this.memory.heapValueHandle(resultPtr));
833
+ }
834
+ throw(error) {
835
+ return this.errorToHandle(error).consume((handle) => this.ffi.QTS_Throw(this.ctx.value, handle.value));
836
+ }
837
+ borrowPropertyKey(key) {
838
+ return typeof key == "number" ? this.newNumber(key) : typeof key == "string" ? this.newString(key) : new StaticLifetime(key.value, this.runtime);
839
+ }
840
+ getMemory(rt) {
841
+ if (rt === this.rt.value) return this.memory;
842
+ throw new Error("Private API. Cannot get memory from a different runtime");
843
+ }
844
+ dump(handle) {
845
+ this.runtime.assertOwned(handle);
846
+ let type = this.typeof(handle);
847
+ if (type === "string") return this.getString(handle);
848
+ if (type === "number") return this.getNumber(handle);
849
+ if (type === "bigint") return this.getBigInt(handle);
850
+ if (type === "undefined") return;
851
+ if (type === "symbol") return this.getSymbol(handle);
852
+ let asPromiseState = this.getPromiseState(handle);
853
+ if (asPromiseState.type === "fulfilled" && !asPromiseState.notAPromise) return handle.dispose(), { type: asPromiseState.type, value: asPromiseState.value.consume(this.dump) };
854
+ if (asPromiseState.type === "pending") return handle.dispose(), { type: asPromiseState.type };
855
+ if (asPromiseState.type === "rejected") return handle.dispose(), { type: asPromiseState.type, error: asPromiseState.error.consume(this.dump) };
856
+ let str = this.memory.consumeJSCharPointer(this.ffi.QTS_Dump(this.ctx.value, handle.value));
857
+ try {
858
+ return JSON.parse(str);
859
+ } catch {
860
+ return str;
861
+ }
862
+ }
863
+ unwrapResult(result) {
864
+ if (result.error) {
865
+ let context2 = "context" in result.error ? result.error.context : this, cause = result.error.consume((error) => this.dump(error));
866
+ if (cause && typeof cause == "object" && typeof cause.message == "string") {
867
+ let { message, name, stack, ...rest } = cause, exception = new QuickJSUnwrapError(cause, context2);
868
+ typeof name == "string" && (exception.name = cause.name), exception.message = message;
869
+ let hostStack = exception.stack;
870
+ throw typeof stack == "string" && (exception.stack = `${name}: ${message}
871
+ ${cause.stack}Host: ${hostStack}`), Object.assign(exception, rest), exception;
872
+ }
873
+ throw new QuickJSUnwrapError(cause);
874
+ }
875
+ return result.value;
876
+ }
877
+ [/* @__PURE__ */ Symbol.for("nodejs.util.inspect.custom")]() {
878
+ return this.alive ? `${this.constructor.name} { ctx: ${this.ctx.value} rt: ${this.rt.value} }` : `${this.constructor.name} { disposed }`;
879
+ }
880
+ getFunction(fn_id) {
881
+ let fn = this.runtime.hostRefs.get(fn_id);
882
+ if (typeof fn != "function") throw new Error(`Host reference ${fn_id} is not a function`);
883
+ return fn;
884
+ }
885
+ errorToHandle(error) {
886
+ return error instanceof Lifetime ? error : this.newError(error);
887
+ }
888
+ encodeBinaryJSON(handle) {
889
+ let ptr = this.ffi.QTS_bjson_encode(this.ctx.value, handle.value);
890
+ return this.memory.heapValueHandle(ptr);
891
+ }
892
+ decodeBinaryJSON(handle) {
893
+ let ptr = this.ffi.QTS_bjson_decode(this.ctx.value, handle.value);
894
+ return this.memory.heapValueHandle(ptr);
895
+ }
896
+ success(value) {
897
+ return DisposableResult.success(value);
898
+ }
899
+ fail(error) {
900
+ return DisposableResult.fail(error, (error2) => this.unwrapResult(error2));
901
+ }
902
+ };
903
+ QuickJSRuntime = class extends UsingDisposable {
904
+ constructor(args) {
905
+ super();
906
+ this.scope = new Scope();
907
+ this.contextMap = /* @__PURE__ */ new Map();
908
+ this.hostRefs = new HostRefMap();
909
+ this._debugMode = false;
910
+ this.cToHostCallbacks = { freeHostRef: (rt, host_ref_id) => {
911
+ if (rt !== this.rt.value) throw new Error("Runtime pointer mismatch");
912
+ this.hostRefs.delete(host_ref_id);
913
+ }, shouldInterrupt: (rt) => {
914
+ if (rt !== this.rt.value) throw new Error("QuickJSContext instance received C -> JS interrupt with mismatched rt");
915
+ let fn = this.interruptHandler;
916
+ if (!fn) throw new Error("QuickJSContext had no interrupt handler");
917
+ return fn(this) ? 1 : 0;
918
+ }, loadModuleSource: maybeAsyncFn(this, function* (awaited, rt, ctx, moduleName) {
919
+ let moduleLoader = this.moduleLoader;
920
+ if (!moduleLoader) throw new Error("Runtime has no module loader");
921
+ if (rt !== this.rt.value) throw new Error("Runtime pointer mismatch");
922
+ let context2 = this.contextMap.get(ctx) ?? this.newContext({ contextPointer: ctx });
923
+ try {
924
+ let result = yield* awaited(moduleLoader(moduleName, context2));
925
+ if (typeof result == "object" && "error" in result && result.error) throw this.debugLog("cToHostLoadModule: loader returned error", result.error), result.error;
926
+ let moduleSource = typeof result == "string" ? result : "value" in result ? result.value : result;
927
+ return this.memory.newHeapCharPointer(moduleSource).value.ptr;
928
+ } catch (error) {
929
+ return this.debugLog("cToHostLoadModule: caught error", error), context2.throw(error), 0;
930
+ }
931
+ }), normalizeModule: maybeAsyncFn(this, function* (awaited, rt, ctx, baseModuleName, moduleNameRequest) {
932
+ let moduleNormalizer = this.moduleNormalizer;
933
+ if (!moduleNormalizer) throw new Error("Runtime has no module normalizer");
934
+ if (rt !== this.rt.value) throw new Error("Runtime pointer mismatch");
935
+ let context2 = this.contextMap.get(ctx) ?? this.newContext({ contextPointer: ctx });
936
+ try {
937
+ let result = yield* awaited(moduleNormalizer(baseModuleName, moduleNameRequest, context2));
938
+ if (typeof result == "object" && "error" in result && result.error) throw this.debugLog("cToHostNormalizeModule: normalizer returned error", result.error), result.error;
939
+ let name = typeof result == "string" ? result : result.value;
940
+ return context2.getMemory(this.rt.value).newHeapCharPointer(name).value.ptr;
941
+ } catch (error) {
942
+ return this.debugLog("normalizeModule: caught error", error), context2.throw(error), 0;
943
+ }
944
+ }) };
945
+ args.ownedLifetimes?.forEach((lifetime) => this.scope.manage(lifetime)), this.module = args.module, this.memory = new ModuleMemory(this.module), this.ffi = args.ffi, this.rt = args.rt, this.callbacks = args.callbacks, this.scope.manage(this.rt), this.callbacks.setRuntimeCallbacks(this.rt.value, this.cToHostCallbacks), this.executePendingJobs = this.executePendingJobs.bind(this), QTS_DEBUG && this.setDebugMode(true);
946
+ }
947
+ get alive() {
948
+ return this.scope.alive;
949
+ }
950
+ dispose() {
951
+ return this.scope.dispose();
952
+ }
953
+ newContext(options = {}) {
954
+ let intrinsics = intrinsicsToFlags(options.intrinsics), ctx = new Lifetime(options.contextPointer || this.ffi.QTS_NewContext(this.rt.value, intrinsics), void 0, (ctx_ptr) => {
955
+ this.contextMap.delete(ctx_ptr), this.callbacks.deleteContext(ctx_ptr), this.ffi.QTS_FreeContext(ctx_ptr);
956
+ }), context2 = new QuickJSContext({ module: this.module, ctx, ffi: this.ffi, rt: this.rt, ownedLifetimes: options.ownedLifetimes, runtime: this, callbacks: this.callbacks });
957
+ return this.contextMap.set(ctx.value, context2), context2;
958
+ }
959
+ setModuleLoader(moduleLoader, moduleNormalizer) {
960
+ this.moduleLoader = moduleLoader, this.moduleNormalizer = moduleNormalizer, this.ffi.QTS_RuntimeEnableModuleLoader(this.rt.value, this.moduleNormalizer ? 1 : 0);
961
+ }
962
+ removeModuleLoader() {
963
+ this.moduleLoader = void 0, this.ffi.QTS_RuntimeDisableModuleLoader(this.rt.value);
964
+ }
965
+ hasPendingJob() {
966
+ return !!this.ffi.QTS_IsJobPending(this.rt.value);
967
+ }
968
+ setInterruptHandler(cb) {
969
+ let prevInterruptHandler = this.interruptHandler;
970
+ this.interruptHandler = cb, prevInterruptHandler || this.ffi.QTS_RuntimeEnableInterruptHandler(this.rt.value);
971
+ }
972
+ removeInterruptHandler() {
973
+ this.interruptHandler && (this.ffi.QTS_RuntimeDisableInterruptHandler(this.rt.value), this.interruptHandler = void 0);
974
+ }
975
+ executePendingJobs(maxJobsToExecute = -1) {
976
+ let ctxPtrOut = this.memory.newMutablePointerArray(1), valuePtr = this.ffi.QTS_ExecutePendingJob(this.rt.value, maxJobsToExecute ?? -1, ctxPtrOut.value.ptr), ctxPtr = ctxPtrOut.value.typedArray[0];
977
+ if (ctxPtrOut.dispose(), ctxPtr === 0) return this.ffi.QTS_FreeValuePointerRuntime(this.rt.value, valuePtr), DisposableResult.success(0);
978
+ let context2 = this.contextMap.get(ctxPtr) ?? this.newContext({ contextPointer: ctxPtr }), resultValue = context2.getMemory(this.rt.value).heapValueHandle(valuePtr);
979
+ if (context2.typeof(resultValue) === "number") {
980
+ let executedJobs = context2.getNumber(resultValue);
981
+ return resultValue.dispose(), DisposableResult.success(executedJobs);
982
+ } else {
983
+ let error = Object.assign(resultValue, { context: context2 });
984
+ return DisposableResult.fail(error, (error2) => context2.unwrapResult(error2));
985
+ }
986
+ }
987
+ setMemoryLimit(limitBytes) {
988
+ if (limitBytes < 0 && limitBytes !== -1) throw new Error("Cannot set memory limit to negative number. To unset, pass -1");
989
+ this.ffi.QTS_RuntimeSetMemoryLimit(this.rt.value, limitBytes);
990
+ }
991
+ computeMemoryUsage() {
992
+ let serviceContextMemory = this.getSystemContext().getMemory(this.rt.value);
993
+ return serviceContextMemory.heapValueHandle(this.ffi.QTS_RuntimeComputeMemoryUsage(this.rt.value, serviceContextMemory.ctx.value));
994
+ }
995
+ dumpMemoryUsage() {
996
+ return this.memory.consumeHeapCharPointer(this.ffi.QTS_RuntimeDumpMemoryUsage(this.rt.value));
997
+ }
998
+ setMaxStackSize(stackSize) {
999
+ if (stackSize < 0) throw new Error("Cannot set memory limit to negative number. To unset, pass 0.");
1000
+ this.ffi.QTS_RuntimeSetMaxStackSize(this.rt.value, stackSize);
1001
+ }
1002
+ assertOwned(handle) {
1003
+ if (handle.owner && handle.owner.rt !== this.rt) throw new QuickJSWrongOwner(`Handle is not owned by this runtime: ${handle.owner.rt.value} != ${this.rt.value}`);
1004
+ }
1005
+ setDebugMode(enabled) {
1006
+ this._debugMode = enabled, this.ffi.DEBUG && this.rt.alive && this.ffi.QTS_SetDebugLogEnabled(this.rt.value, enabled ? 1 : 0);
1007
+ }
1008
+ isDebugMode() {
1009
+ return this._debugMode;
1010
+ }
1011
+ debugLog(...msg) {
1012
+ this._debugMode && console.log("quickjs-emscripten:", ...msg);
1013
+ }
1014
+ [/* @__PURE__ */ Symbol.for("nodejs.util.inspect.custom")]() {
1015
+ return this.alive ? `${this.constructor.name} { rt: ${this.rt.value} }` : `${this.constructor.name} { disposed }`;
1016
+ }
1017
+ getSystemContext() {
1018
+ return this.context || (this.context = this.scope.manage(this.newContext())), this.context;
1019
+ }
1020
+ };
1021
+ QuickJSEmscriptenModuleCallbacks = class {
1022
+ constructor(args) {
1023
+ this.freeHostRef = args.freeHostRef, this.callFunction = args.callFunction, this.shouldInterrupt = args.shouldInterrupt, this.loadModuleSource = args.loadModuleSource, this.normalizeModule = args.normalizeModule;
1024
+ }
1025
+ };
1026
+ QuickJSModuleCallbacks = class {
1027
+ constructor(module) {
1028
+ this.contextCallbacks = /* @__PURE__ */ new Map();
1029
+ this.runtimeCallbacks = /* @__PURE__ */ new Map();
1030
+ this.suspendedCount = 0;
1031
+ this.cToHostCallbacks = new QuickJSEmscriptenModuleCallbacks({ freeHostRef: (_asyncify, rt, host_ref_id) => {
1032
+ let runtimeCallbacks = this.runtimeCallbacks.get(rt);
1033
+ if (!runtimeCallbacks) throw new Error(`QuickJSRuntime(rt = ${rt}) not found when trying to free HostRef(id = ${host_ref_id})`);
1034
+ runtimeCallbacks.freeHostRef(rt, host_ref_id);
1035
+ }, callFunction: (asyncify, ctx, this_ptr, argc, argv, fn_id) => this.handleAsyncify(asyncify, () => {
1036
+ try {
1037
+ let vm = this.contextCallbacks.get(ctx);
1038
+ if (!vm) throw new Error(`QuickJSContext(ctx = ${ctx}) not found for C function call "${fn_id}"`);
1039
+ return vm.callFunction(ctx, this_ptr, argc, argv, fn_id);
1040
+ } catch (error) {
1041
+ return console.error("[C to host error: returning null]", error), 0;
1042
+ }
1043
+ }), shouldInterrupt: (asyncify, rt) => this.handleAsyncify(asyncify, () => {
1044
+ try {
1045
+ let vm = this.runtimeCallbacks.get(rt);
1046
+ if (!vm) throw new Error(`QuickJSRuntime(rt = ${rt}) not found for C interrupt`);
1047
+ return vm.shouldInterrupt(rt);
1048
+ } catch (error) {
1049
+ return console.error("[C to host interrupt: returning error]", error), 1;
1050
+ }
1051
+ }), loadModuleSource: (asyncify, rt, ctx, moduleName) => this.handleAsyncify(asyncify, () => {
1052
+ try {
1053
+ let runtimeCallbacks = this.runtimeCallbacks.get(rt);
1054
+ if (!runtimeCallbacks) throw new Error(`QuickJSRuntime(rt = ${rt}) not found for C module loader`);
1055
+ let loadModule = runtimeCallbacks.loadModuleSource;
1056
+ if (!loadModule) throw new Error(`QuickJSRuntime(rt = ${rt}) does not support module loading`);
1057
+ return loadModule(rt, ctx, moduleName);
1058
+ } catch (error) {
1059
+ return console.error("[C to host module loader error: returning null]", error), 0;
1060
+ }
1061
+ }), normalizeModule: (asyncify, rt, ctx, moduleBaseName, moduleName) => this.handleAsyncify(asyncify, () => {
1062
+ try {
1063
+ let runtimeCallbacks = this.runtimeCallbacks.get(rt);
1064
+ if (!runtimeCallbacks) throw new Error(`QuickJSRuntime(rt = ${rt}) not found for C module loader`);
1065
+ let normalizeModule = runtimeCallbacks.normalizeModule;
1066
+ if (!normalizeModule) throw new Error(`QuickJSRuntime(rt = ${rt}) does not support module loading`);
1067
+ return normalizeModule(rt, ctx, moduleBaseName, moduleName);
1068
+ } catch (error) {
1069
+ return console.error("[C to host module loader error: returning null]", error), 0;
1070
+ }
1071
+ }) });
1072
+ this.module = module, this.module.callbacks = this.cToHostCallbacks;
1073
+ }
1074
+ setRuntimeCallbacks(rt, callbacks) {
1075
+ this.runtimeCallbacks.set(rt, callbacks);
1076
+ }
1077
+ deleteRuntime(rt) {
1078
+ this.runtimeCallbacks.delete(rt);
1079
+ }
1080
+ setContextCallbacks(ctx, callbacks) {
1081
+ this.contextCallbacks.set(ctx, callbacks);
1082
+ }
1083
+ deleteContext(ctx) {
1084
+ this.contextCallbacks.delete(ctx);
1085
+ }
1086
+ handleAsyncify(asyncify, fn) {
1087
+ if (asyncify) return asyncify.handleSleep((done) => {
1088
+ try {
1089
+ let result = fn();
1090
+ if (!(result instanceof Promise)) {
1091
+ debugLog("asyncify.handleSleep: not suspending:", result), done(result);
1092
+ return;
1093
+ }
1094
+ if (this.suspended) throw new QuickJSAsyncifyError(`Already suspended at: ${this.suspended.stack}
1095
+ Attempted to suspend at:`);
1096
+ this.suspended = new QuickJSAsyncifySuspended(`(${this.suspendedCount++})`), debugLog("asyncify.handleSleep: suspending:", this.suspended), result.then((resolvedResult) => {
1097
+ this.suspended = void 0, debugLog("asyncify.handleSleep: resolved:", resolvedResult), done(resolvedResult);
1098
+ }, (error) => {
1099
+ debugLog("asyncify.handleSleep: rejected:", error), console.error("QuickJS: cannot handle error in suspended function", error), this.suspended = void 0;
1100
+ });
1101
+ } catch (error) {
1102
+ throw debugLog("asyncify.handleSleep: error:", error), this.suspended = void 0, error;
1103
+ }
1104
+ });
1105
+ let value = fn();
1106
+ if (value instanceof Promise) throw new Error("Promise return value not supported in non-asyncify context.");
1107
+ return value;
1108
+ }
1109
+ };
1110
+ QuickJSWASMModule = class {
1111
+ constructor(module, ffi) {
1112
+ this.module = module, this.ffi = ffi, this.callbacks = new QuickJSModuleCallbacks(module);
1113
+ }
1114
+ newRuntime(options = {}) {
1115
+ let rt = new Lifetime(this.ffi.QTS_NewRuntime(), void 0, (rt_ptr) => {
1116
+ this.ffi.QTS_FreeRuntime(rt_ptr), this.callbacks.deleteRuntime(rt_ptr);
1117
+ }), runtime2 = new QuickJSRuntime({ module: this.module, callbacks: this.callbacks, ffi: this.ffi, rt });
1118
+ return applyBaseRuntimeOptions(runtime2, options), options.moduleLoader && runtime2.setModuleLoader(options.moduleLoader), runtime2;
1119
+ }
1120
+ newContext(options = {}) {
1121
+ let runtime2 = this.newRuntime(), context2 = runtime2.newContext({ ...options, ownedLifetimes: concat(runtime2, options.ownedLifetimes) });
1122
+ return runtime2.context = context2, context2;
1123
+ }
1124
+ evalCode(code, options = {}) {
1125
+ return Scope.withScope((scope) => {
1126
+ let vm = scope.manage(this.newContext());
1127
+ applyModuleEvalRuntimeOptions(vm.runtime, options);
1128
+ let result = vm.evalCode(code, "eval.js");
1129
+ if (options.memoryLimitBytes !== void 0 && vm.runtime.setMemoryLimit(-1), result.error) throw vm.dump(scope.manage(result.error));
1130
+ return vm.dump(scope.manage(result.value));
1131
+ });
1132
+ }
1133
+ getWasmMemory() {
1134
+ let memory = this.module.quickjsEmscriptenInit?.(() => {
1135
+ })?.getWasmMemory?.();
1136
+ if (!memory) throw new Error("Variant does not support getting WebAssembly.Memory");
1137
+ return memory;
1138
+ }
1139
+ getFFI() {
1140
+ return this.ffi;
1141
+ }
1142
+ };
1143
+ }
1144
+ });
1145
+
1146
+ // ../node_modules/quickjs-emscripten-core/dist/module-ES6BEMUI.mjs
1147
+ var module_ES6BEMUI_exports = {};
1148
+ __export(module_ES6BEMUI_exports, {
1149
+ QuickJSModuleCallbacks: () => QuickJSModuleCallbacks,
1150
+ QuickJSWASMModule: () => QuickJSWASMModule,
1151
+ applyBaseRuntimeOptions: () => applyBaseRuntimeOptions,
1152
+ applyModuleEvalRuntimeOptions: () => applyModuleEvalRuntimeOptions
1153
+ });
1154
+ var init_module_ES6BEMUI = __esm({
1155
+ "../node_modules/quickjs-emscripten-core/dist/module-ES6BEMUI.mjs"() {
1156
+ init_chunk_V2S4ZYJR();
1157
+ }
1158
+ });
1159
+
1160
+ // ../node_modules/@jitl/quickjs-wasmfile-release-sync/dist/ffi.mjs
1161
+ var ffi_exports = {};
1162
+ __export(ffi_exports, {
1163
+ QuickJSFFI: () => QuickJSFFI
1164
+ });
1165
+ var QuickJSFFI;
1166
+ var init_ffi = __esm({
1167
+ "../node_modules/@jitl/quickjs-wasmfile-release-sync/dist/ffi.mjs"() {
1168
+ QuickJSFFI = class {
1169
+ constructor(module) {
1170
+ this.module = module;
1171
+ this.DEBUG = false;
1172
+ this.QTS_Throw = this.module.cwrap("QTS_Throw", "number", ["number", "number"]);
1173
+ this.QTS_NewError = this.module.cwrap("QTS_NewError", "number", ["number"]);
1174
+ this.QTS_RuntimeSetMemoryLimit = this.module.cwrap("QTS_RuntimeSetMemoryLimit", null, ["number", "number"]);
1175
+ this.QTS_RuntimeComputeMemoryUsage = this.module.cwrap("QTS_RuntimeComputeMemoryUsage", "number", ["number", "number"]);
1176
+ this.QTS_RuntimeDumpMemoryUsage = this.module.cwrap("QTS_RuntimeDumpMemoryUsage", "number", ["number"]);
1177
+ this.QTS_RecoverableLeakCheck = this.module.cwrap("QTS_RecoverableLeakCheck", "number", []);
1178
+ this.QTS_BuildIsSanitizeLeak = this.module.cwrap("QTS_BuildIsSanitizeLeak", "number", []);
1179
+ this.QTS_RuntimeSetMaxStackSize = this.module.cwrap("QTS_RuntimeSetMaxStackSize", null, ["number", "number"]);
1180
+ this.QTS_GetUndefined = this.module.cwrap("QTS_GetUndefined", "number", []);
1181
+ this.QTS_GetNull = this.module.cwrap("QTS_GetNull", "number", []);
1182
+ this.QTS_GetFalse = this.module.cwrap("QTS_GetFalse", "number", []);
1183
+ this.QTS_GetTrue = this.module.cwrap("QTS_GetTrue", "number", []);
1184
+ this.QTS_NewHostRef = this.module.cwrap("QTS_NewHostRef", "number", ["number", "number"]);
1185
+ this.QTS_GetHostRefId = this.module.cwrap("QTS_GetHostRefId", "number", ["number"]);
1186
+ this.QTS_NewRuntime = this.module.cwrap("QTS_NewRuntime", "number", []);
1187
+ this.QTS_FreeRuntime = this.module.cwrap("QTS_FreeRuntime", null, ["number"]);
1188
+ this.QTS_NewContext = this.module.cwrap("QTS_NewContext", "number", ["number", "number"]);
1189
+ this.QTS_FreeContext = this.module.cwrap("QTS_FreeContext", null, ["number"]);
1190
+ this.QTS_FreeValuePointer = this.module.cwrap("QTS_FreeValuePointer", null, ["number", "number"]);
1191
+ this.QTS_FreeValuePointerRuntime = this.module.cwrap("QTS_FreeValuePointerRuntime", null, ["number", "number"]);
1192
+ this.QTS_FreeVoidPointer = this.module.cwrap("QTS_FreeVoidPointer", null, ["number", "number"]);
1193
+ this.QTS_FreeCString = this.module.cwrap("QTS_FreeCString", null, ["number", "number"]);
1194
+ this.QTS_DupValuePointer = this.module.cwrap("QTS_DupValuePointer", "number", ["number", "number"]);
1195
+ this.QTS_NewObject = this.module.cwrap("QTS_NewObject", "number", ["number"]);
1196
+ this.QTS_NewObjectProto = this.module.cwrap("QTS_NewObjectProto", "number", ["number", "number"]);
1197
+ this.QTS_NewArray = this.module.cwrap("QTS_NewArray", "number", ["number"]);
1198
+ this.QTS_NewArrayBuffer = this.module.cwrap("QTS_NewArrayBuffer", "number", ["number", "number", "number"]);
1199
+ this.QTS_NewFloat64 = this.module.cwrap("QTS_NewFloat64", "number", ["number", "number"]);
1200
+ this.QTS_GetFloat64 = this.module.cwrap("QTS_GetFloat64", "number", ["number", "number"]);
1201
+ this.QTS_NewString = this.module.cwrap("QTS_NewString", "number", ["number", "number"]);
1202
+ this.QTS_GetString = this.module.cwrap("QTS_GetString", "number", ["number", "number"]);
1203
+ this.QTS_GetArrayBuffer = this.module.cwrap("QTS_GetArrayBuffer", "number", ["number", "number"]);
1204
+ this.QTS_GetArrayBufferLength = this.module.cwrap("QTS_GetArrayBufferLength", "number", ["number", "number"]);
1205
+ this.QTS_NewSymbol = this.module.cwrap("QTS_NewSymbol", "number", ["number", "number", "number"]);
1206
+ this.QTS_GetSymbolDescriptionOrKey = this.module.cwrap("QTS_GetSymbolDescriptionOrKey", "number", ["number", "number"]);
1207
+ this.QTS_IsGlobalSymbol = this.module.cwrap("QTS_IsGlobalSymbol", "number", ["number", "number"]);
1208
+ this.QTS_IsJobPending = this.module.cwrap("QTS_IsJobPending", "number", ["number"]);
1209
+ this.QTS_ExecutePendingJob = this.module.cwrap("QTS_ExecutePendingJob", "number", ["number", "number", "number"]);
1210
+ this.QTS_GetProp = this.module.cwrap("QTS_GetProp", "number", ["number", "number", "number"]);
1211
+ this.QTS_GetPropNumber = this.module.cwrap("QTS_GetPropNumber", "number", ["number", "number", "number"]);
1212
+ this.QTS_SetProp = this.module.cwrap("QTS_SetProp", null, ["number", "number", "number", "number"]);
1213
+ this.QTS_DefineProp = this.module.cwrap("QTS_DefineProp", null, ["number", "number", "number", "number", "number", "number", "boolean", "boolean", "boolean"]);
1214
+ this.QTS_GetOwnPropertyNames = this.module.cwrap("QTS_GetOwnPropertyNames", "number", ["number", "number", "number", "number", "number"]);
1215
+ this.QTS_Call = this.module.cwrap("QTS_Call", "number", ["number", "number", "number", "number", "number"]);
1216
+ this.QTS_ResolveException = this.module.cwrap("QTS_ResolveException", "number", ["number", "number"]);
1217
+ this.QTS_Dump = this.module.cwrap("QTS_Dump", "number", ["number", "number"]);
1218
+ this.QTS_Eval = this.module.cwrap("QTS_Eval", "number", ["number", "number", "number", "string", "number", "number"]);
1219
+ this.QTS_GetModuleNamespace = this.module.cwrap("QTS_GetModuleNamespace", "number", ["number", "number"]);
1220
+ this.QTS_Typeof = this.module.cwrap("QTS_Typeof", "number", ["number", "number"]);
1221
+ this.QTS_GetLength = this.module.cwrap("QTS_GetLength", "number", ["number", "number", "number"]);
1222
+ this.QTS_IsEqual = this.module.cwrap("QTS_IsEqual", "number", ["number", "number", "number", "number"]);
1223
+ this.QTS_GetGlobalObject = this.module.cwrap("QTS_GetGlobalObject", "number", ["number"]);
1224
+ this.QTS_NewPromiseCapability = this.module.cwrap("QTS_NewPromiseCapability", "number", ["number", "number"]);
1225
+ this.QTS_PromiseState = this.module.cwrap("QTS_PromiseState", "number", ["number", "number"]);
1226
+ this.QTS_PromiseResult = this.module.cwrap("QTS_PromiseResult", "number", ["number", "number"]);
1227
+ this.QTS_TestStringArg = this.module.cwrap("QTS_TestStringArg", null, ["string"]);
1228
+ this.QTS_GetDebugLogEnabled = this.module.cwrap("QTS_GetDebugLogEnabled", "number", ["number"]);
1229
+ this.QTS_SetDebugLogEnabled = this.module.cwrap("QTS_SetDebugLogEnabled", null, ["number", "number"]);
1230
+ this.QTS_BuildIsDebug = this.module.cwrap("QTS_BuildIsDebug", "number", []);
1231
+ this.QTS_BuildIsAsyncify = this.module.cwrap("QTS_BuildIsAsyncify", "number", []);
1232
+ this.QTS_NewFunction = this.module.cwrap("QTS_NewFunction", "number", ["number", "string", "number", "boolean", "number"]);
1233
+ this.QTS_ArgvGetJSValueConstPointer = this.module.cwrap("QTS_ArgvGetJSValueConstPointer", "number", ["number", "number"]);
1234
+ this.QTS_RuntimeEnableInterruptHandler = this.module.cwrap("QTS_RuntimeEnableInterruptHandler", null, ["number"]);
1235
+ this.QTS_RuntimeDisableInterruptHandler = this.module.cwrap("QTS_RuntimeDisableInterruptHandler", null, ["number"]);
1236
+ this.QTS_RuntimeEnableModuleLoader = this.module.cwrap("QTS_RuntimeEnableModuleLoader", null, ["number", "number"]);
1237
+ this.QTS_RuntimeDisableModuleLoader = this.module.cwrap("QTS_RuntimeDisableModuleLoader", null, ["number"]);
1238
+ this.QTS_bjson_encode = this.module.cwrap("QTS_bjson_encode", "number", ["number", "number"]);
1239
+ this.QTS_bjson_decode = this.module.cwrap("QTS_bjson_decode", "number", ["number", "number"]);
1240
+ }
1241
+ };
1242
+ }
1243
+ });
1244
+
1245
+ // ../node_modules/@jitl/quickjs-wasmfile-release-sync/dist/emscripten-module.mjs
1246
+ var emscripten_module_exports = {};
1247
+ __export(emscripten_module_exports, {
1248
+ default: () => emscripten_module_default
1249
+ });
1250
+ async function QuickJSRaw(moduleArg = {}) {
1251
+ var moduleRtn;
1252
+ var d = moduleArg, aa = !!globalThis.window, n = !!globalThis.WorkerGlobalScope, q = globalThis.process?.versions?.node && "renderer" != globalThis.process?.type;
1253
+ if (q) {
1254
+ const { createRequire: a } = await import("node:module");
1255
+ var require2 = a(import.meta.url);
1256
+ }
1257
+ function r(a) {
1258
+ a = { log: a || function() {
1259
+ } };
1260
+ for (const c of r.Pa) c(a);
1261
+ return d.quickJSEmscriptenExtensions = a;
1262
+ }
1263
+ r.Pa = [];
1264
+ d.quickjsEmscriptenInit = r;
1265
+ r.Pa.push((a) => {
1266
+ a.getWasmMemory = function() {
1267
+ return t;
1268
+ };
1269
+ });
1270
+ var u = "./this.program", v = (a, c) => {
1271
+ throw c;
1272
+ }, w = import.meta.url, y = "", z, A;
1273
+ if (q) {
1274
+ var fs = require2("node:fs");
1275
+ w.startsWith("file:") && (y = require2("node:path").dirname(require2("node:url").fileURLToPath(w)) + "/");
1276
+ A = (a) => {
1277
+ a = B(a) ? new URL(a) : a;
1278
+ return fs.readFileSync(a);
1279
+ };
1280
+ z = async (a) => {
1281
+ a = B(a) ? new URL(a) : a;
1282
+ return fs.readFileSync(a, void 0);
1283
+ };
1284
+ 1 < process.argv.length && (u = process.argv[1].replace(/\\/g, "/"));
1285
+ process.argv.slice(2);
1286
+ v = (a, c) => {
1287
+ process.exitCode = a;
1288
+ throw c;
1289
+ };
1290
+ } else if (aa || n) {
1291
+ try {
1292
+ y = new URL(".", w).href;
1293
+ } catch {
1294
+ }
1295
+ n && (A = (a) => {
1296
+ var c = new XMLHttpRequest();
1297
+ c.open("GET", a, false);
1298
+ c.responseType = "arraybuffer";
1299
+ c.send(null);
1300
+ return new Uint8Array(c.response);
1301
+ });
1302
+ z = async (a) => {
1303
+ if (B(a)) return new Promise((b, e) => {
1304
+ var f = new XMLHttpRequest();
1305
+ f.open("GET", a, true);
1306
+ f.responseType = "arraybuffer";
1307
+ f.onload = () => {
1308
+ 200 == f.status || 0 == f.status && f.response ? b(f.response) : e(f.status);
1309
+ };
1310
+ f.onerror = e;
1311
+ f.send(null);
1312
+ });
1313
+ var c = await fetch(a, { credentials: "same-origin" });
1314
+ if (c.ok) return c.arrayBuffer();
1315
+ throw Error(c.status + " : " + c.url);
1316
+ };
1317
+ }
1318
+ var C = console.log.bind(console), D = console.error.bind(console), E, F = false, G, B = (a) => a.startsWith("file://"), H, I, J, K, L, M, ba = false;
1319
+ function ca() {
1320
+ var a = t.buffer;
1321
+ d.HEAP8 = J = new Int8Array(a);
1322
+ new Int16Array(a);
1323
+ d.HEAPU8 = K = new Uint8Array(a);
1324
+ new Uint16Array(a);
1325
+ L = new Int32Array(a);
1326
+ M = new Uint32Array(a);
1327
+ new Float32Array(a);
1328
+ new Float64Array(a);
1329
+ new BigInt64Array(a);
1330
+ new BigUint64Array(a);
1331
+ }
1332
+ function N(a) {
1333
+ d.onAbort?.(a);
1334
+ a = "Aborted(" + a + ")";
1335
+ D(a);
1336
+ F = true;
1337
+ a = new WebAssembly.RuntimeError(a + ". Build with -sASSERTIONS for more info.");
1338
+ I?.(a);
1339
+ throw a;
1340
+ }
1341
+ var O;
1342
+ async function da(a) {
1343
+ if (!E) try {
1344
+ var c = await z(a);
1345
+ return new Uint8Array(c);
1346
+ } catch {
1347
+ }
1348
+ if (a == O && E) a = new Uint8Array(E);
1349
+ else if (A) a = A(a);
1350
+ else throw "both async and sync fetching of the wasm failed";
1351
+ return a;
1352
+ }
1353
+ async function ea(a, c) {
1354
+ try {
1355
+ var b = await da(a);
1356
+ return await WebAssembly.instantiate(b, c);
1357
+ } catch (e) {
1358
+ D(`failed to asynchronously prepare wasm: ${e}`), N(e);
1359
+ }
1360
+ }
1361
+ async function fa(a) {
1362
+ var c = O;
1363
+ if (!E && !B(c) && !q) try {
1364
+ var b = fetch(c, { credentials: "same-origin" });
1365
+ return await WebAssembly.instantiateStreaming(b, a);
1366
+ } catch (e) {
1367
+ D(`wasm streaming compile failed: ${e}`), D("falling back to ArrayBuffer instantiation");
1368
+ }
1369
+ return ea(c, a);
1370
+ }
1371
+ class P {
1372
+ name = "ExitStatus";
1373
+ constructor(a) {
1374
+ this.message = `Program terminated with exit(${a})`;
1375
+ this.status = a;
1376
+ }
1377
+ }
1378
+ var ha = (a) => {
1379
+ for (; 0 < a.length; ) a.shift()(d);
1380
+ }, ia = [], ja = [], ka = () => {
1381
+ var a = d.preRun.shift();
1382
+ ja.push(a);
1383
+ }, Q = true, t, la = new TextDecoder(), ma = (a, c, b, e) => {
1384
+ b = c + b;
1385
+ if (e) return b;
1386
+ for (; a[c] && !(c >= b); ) ++c;
1387
+ return c;
1388
+ }, R = (a, c, b) => a ? la.decode(K.subarray(a, ma(K, a, c, b))) : "", S = 0, na = [0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335], oa = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334], T = {}, pa = (a) => {
1389
+ G = a;
1390
+ Q || 0 < S || (d.onExit?.(a), F = true);
1391
+ v(a, new P(a));
1392
+ }, qa = (a) => {
1393
+ if (!F) try {
1394
+ a();
1395
+ } catch (c) {
1396
+ c instanceof P || "unwind" == c || v(1, c);
1397
+ } finally {
1398
+ if (!(Q || 0 < S)) try {
1399
+ G = a = G, pa(a);
1400
+ } catch (c) {
1401
+ c instanceof P || "unwind" == c || v(1, c);
1402
+ }
1403
+ }
1404
+ }, U = (a, c, b) => {
1405
+ var e = K;
1406
+ if (!(0 < b)) return 0;
1407
+ var f = c;
1408
+ b = c + b - 1;
1409
+ for (var g = 0; g < a.length; ++g) {
1410
+ var h = a.codePointAt(g);
1411
+ if (127 >= h) {
1412
+ if (c >= b) break;
1413
+ e[c++] = h;
1414
+ } else if (2047 >= h) {
1415
+ if (c + 1 >= b) break;
1416
+ e[c++] = 192 | h >> 6;
1417
+ e[c++] = 128 | h & 63;
1418
+ } else if (65535 >= h) {
1419
+ if (c + 2 >= b) break;
1420
+ e[c++] = 224 | h >> 12;
1421
+ e[c++] = 128 | h >> 6 & 63;
1422
+ e[c++] = 128 | h & 63;
1423
+ } else {
1424
+ if (c + 3 >= b) break;
1425
+ e[c++] = 240 | h >> 18;
1426
+ e[c++] = 128 | h >> 12 & 63;
1427
+ e[c++] = 128 | h >> 6 & 63;
1428
+ e[c++] = 128 | h & 63;
1429
+ g++;
1430
+ }
1431
+ }
1432
+ e[c] = 0;
1433
+ return c - f;
1434
+ }, V = {}, ra = () => {
1435
+ if (!W) {
1436
+ var a = {
1437
+ USER: "web_user",
1438
+ LOGNAME: "web_user",
1439
+ PATH: "/",
1440
+ PWD: "/",
1441
+ HOME: "/home/web_user",
1442
+ LANG: (globalThis.navigator?.language ?? "C").replace("-", "_") + ".UTF-8",
1443
+ _: u || "./this.program"
1444
+ }, c;
1445
+ for (c in V) void 0 === V[c] ? delete a[c] : a[c] = V[c];
1446
+ var b = [];
1447
+ for (c in a) b.push(`${c}=${a[c]}`);
1448
+ W = b;
1449
+ }
1450
+ return W;
1451
+ }, W, X = (a) => {
1452
+ for (var c = 0, b = 0; b < a.length; ++b) {
1453
+ var e = a.charCodeAt(b);
1454
+ 127 >= e ? c++ : 2047 >= e ? c += 2 : 55296 <= e && 57343 >= e ? (c += 4, ++b) : c += 3;
1455
+ }
1456
+ return c;
1457
+ }, sa = [null, [], []], va = (a, c, b, e) => {
1458
+ var f = { string: (k) => {
1459
+ var l = 0;
1460
+ if (null !== k && void 0 !== k && 0 !== k) {
1461
+ l = X(k) + 1;
1462
+ var p = Y(l);
1463
+ U(
1464
+ k,
1465
+ p,
1466
+ l
1467
+ );
1468
+ l = p;
1469
+ }
1470
+ return l;
1471
+ }, array: (k) => {
1472
+ var l = Y(k.length);
1473
+ J.set(k, l);
1474
+ return l;
1475
+ } };
1476
+ a = d["_" + a];
1477
+ var g = [], h = 0;
1478
+ if (e) for (var m = 0; m < e.length; m++) {
1479
+ var x = f[b[m]];
1480
+ x ? (0 === h && (h = ta()), g[m] = x(e[m])) : g[m] = e[m];
1481
+ }
1482
+ b = a(...g);
1483
+ return b = (function(k) {
1484
+ 0 !== h && ua(h);
1485
+ return "string" === c ? R(k) : "boolean" === c ? !!k : k;
1486
+ })(b);
1487
+ };
1488
+ d.wasmMemory ? t = d.wasmMemory : t = new WebAssembly.Memory({ initial: (d.INITIAL_MEMORY || 16777216) / 65536, maximum: 32768 });
1489
+ ca();
1490
+ d.noExitRuntime && (Q = d.noExitRuntime);
1491
+ d.print && (C = d.print);
1492
+ d.printErr && (D = d.printErr);
1493
+ d.wasmBinary && (E = d.wasmBinary);
1494
+ d.thisProgram && (u = d.thisProgram);
1495
+ if (d.preInit) for ("function" == typeof d.preInit && (d.preInit = [d.preInit]); 0 < d.preInit.length; ) d.preInit.shift()();
1496
+ d.cwrap = (a, c, b, e) => {
1497
+ var f = !b || b.every((g) => "number" === g || "boolean" === g);
1498
+ return "string" !== c && f && !e ? d["_" + a] : (...g) => va(a, c, b, g);
1499
+ };
1500
+ d.UTF8ToString = R;
1501
+ d.stringToUTF8 = (a, c, b) => U(a, c, b);
1502
+ d.lengthBytesUTF8 = X;
1503
+ var wa, ua, Y, ta, xa = { b: (a, c, b, e) => N(`Assertion failed: ${R(a)}, at: ` + [c ? R(c) : "unknown filename", b, e ? R(e) : "unknown function"]), q: () => N(""), l: () => {
1504
+ Q = false;
1505
+ S = 0;
1506
+ }, m: function(a, c) {
1507
+ a = -9007199254740992 > a || 9007199254740992 < a ? NaN : Number(a);
1508
+ a = new Date(1e3 * a);
1509
+ L[c >> 2] = a.getSeconds();
1510
+ L[c + 4 >> 2] = a.getMinutes();
1511
+ L[c + 8 >> 2] = a.getHours();
1512
+ L[c + 12 >> 2] = a.getDate();
1513
+ L[c + 16 >> 2] = a.getMonth();
1514
+ L[c + 20 >> 2] = a.getFullYear() - 1900;
1515
+ L[c + 24 >> 2] = a.getDay();
1516
+ var b = a.getFullYear();
1517
+ L[c + 28 >> 2] = (0 !== b % 4 || 0 === b % 100 && 0 !== b % 400 ? oa : na)[a.getMonth()] + a.getDate() - 1 | 0;
1518
+ L[c + 36 >> 2] = -(60 * a.getTimezoneOffset());
1519
+ b = new Date(a.getFullYear(), 6, 1).getTimezoneOffset();
1520
+ var e = new Date(a.getFullYear(), 0, 1).getTimezoneOffset();
1521
+ L[c + 32 >> 2] = (b != e && a.getTimezoneOffset() == Math.min(e, b)) | 0;
1522
+ }, j: (a, c) => {
1523
+ T[a] && (clearTimeout(T[a].id), delete T[a]);
1524
+ if (!c) return 0;
1525
+ var b = setTimeout(() => {
1526
+ delete T[a];
1527
+ qa(() => wa(a, performance.now()));
1528
+ }, c);
1529
+ T[a] = { id: b, Qa: c };
1530
+ return 0;
1531
+ }, n: (a, c, b, e) => {
1532
+ var f = (/* @__PURE__ */ new Date()).getFullYear(), g = new Date(f, 0, 1).getTimezoneOffset();
1533
+ f = new Date(f, 6, 1).getTimezoneOffset();
1534
+ M[a >> 2] = 60 * Math.max(g, f);
1535
+ L[c >> 2] = Number(g != f);
1536
+ c = (h) => {
1537
+ var m = Math.abs(h);
1538
+ return `UTC${0 <= h ? "-" : "+"}${String(Math.floor(m / 60)).padStart(2, "0")}${String(m % 60).padStart(2, "0")}`;
1539
+ };
1540
+ a = c(g);
1541
+ c = c(f);
1542
+ f < g ? (U(a, b, 17), U(c, e, 17)) : (U(a, e, 17), U(c, b, 17));
1543
+ }, p: () => Date.now(), k: (a) => {
1544
+ var c = K.length;
1545
+ a >>>= 0;
1546
+ if (2147483648 < a) return false;
1547
+ for (var b = 1; 4 >= b; b *= 2) {
1548
+ var e = c * (1 + 0.2 / b);
1549
+ e = Math.min(e, a + 100663296);
1550
+ a: {
1551
+ e = (Math.min(2147483648, 65536 * Math.ceil(Math.max(a, e) / 65536)) - t.buffer.byteLength + 65535) / 65536 | 0;
1552
+ try {
1553
+ t.grow(e);
1554
+ ca();
1555
+ var f = 1;
1556
+ break a;
1557
+ } catch (g) {
1558
+ }
1559
+ f = void 0;
1560
+ }
1561
+ if (f) return true;
1562
+ }
1563
+ return false;
1564
+ }, e: (a, c) => {
1565
+ var b = 0, e = 0, f;
1566
+ for (f of ra()) {
1567
+ var g = c + b;
1568
+ M[a + e >> 2] = g;
1569
+ b += U(f, g, Infinity) + 1;
1570
+ e += 4;
1571
+ }
1572
+ return 0;
1573
+ }, f: (a, c) => {
1574
+ var b = ra();
1575
+ M[a >> 2] = b.length;
1576
+ a = 0;
1577
+ for (var e of b) a += X(e) + 1;
1578
+ M[c >> 2] = a;
1579
+ return 0;
1580
+ }, d: () => 52, o: function() {
1581
+ return 70;
1582
+ }, c: (a, c, b, e) => {
1583
+ for (var f = 0, g = 0; g < b; g++) {
1584
+ var h = M[c >> 2], m = M[c + 4 >> 2];
1585
+ c += 8;
1586
+ for (var x = 0; x < m; x++) {
1587
+ var k = a, l = K[h + x], p = sa[k];
1588
+ 0 === l || 10 === l ? (k = 1 === k ? C : D, l = ma(p, 0), l = la.decode(p.buffer ? p.subarray(0, l) : new Uint8Array(p.slice(0, l))), k(l), p.length = 0) : p.push(l);
1589
+ }
1590
+ f += m;
1591
+ }
1592
+ M[e >> 2] = f;
1593
+ return 0;
1594
+ }, a: t, r: pa, s: function(a, c, b, e, f) {
1595
+ return d.callbacks.callFunction(void 0, a, c, b, e, f);
1596
+ }, i: function(a) {
1597
+ return d.callbacks.shouldInterrupt(void 0, a);
1598
+ }, h: function(a, c, b) {
1599
+ b = R(b);
1600
+ return d.callbacks.loadModuleSource(void 0, a, c, b);
1601
+ }, g: function(a, c, b, e) {
1602
+ b = R(b);
1603
+ e = R(e);
1604
+ return d.callbacks.normalizeModule(void 0, a, c, b, e);
1605
+ }, t: function(a, c) {
1606
+ d.callbacks.freeHostRef(void 0, a, c);
1607
+ } }, Z;
1608
+ Z = await (async function() {
1609
+ function a(b) {
1610
+ b = Z = b.exports;
1611
+ d._malloc = b.v;
1612
+ d._QTS_Throw = b.w;
1613
+ d._QTS_NewError = b.x;
1614
+ d._QTS_RuntimeSetMemoryLimit = b.y;
1615
+ d._QTS_RuntimeComputeMemoryUsage = b.z;
1616
+ d._QTS_RuntimeDumpMemoryUsage = b.A;
1617
+ d._QTS_RecoverableLeakCheck = b.B;
1618
+ d._QTS_BuildIsSanitizeLeak = b.C;
1619
+ d._QTS_RuntimeSetMaxStackSize = b.D;
1620
+ d._QTS_GetUndefined = b.E;
1621
+ d._QTS_GetNull = b.F;
1622
+ d._QTS_GetFalse = b.G;
1623
+ d._QTS_GetTrue = b.H;
1624
+ d._QTS_NewHostRef = b.I;
1625
+ d._QTS_GetHostRefId = b.J;
1626
+ d._QTS_NewRuntime = b.K;
1627
+ d._QTS_FreeRuntime = b.L;
1628
+ d._free = b.M;
1629
+ d._QTS_NewContext = b.N;
1630
+ d._QTS_FreeContext = b.O;
1631
+ d._QTS_FreeValuePointer = b.P;
1632
+ d._QTS_FreeValuePointerRuntime = b.Q;
1633
+ d._QTS_FreeVoidPointer = b.R;
1634
+ d._QTS_FreeCString = b.S;
1635
+ d._QTS_DupValuePointer = b.T;
1636
+ d._QTS_NewObject = b.U;
1637
+ d._QTS_NewObjectProto = b.V;
1638
+ d._QTS_NewArray = b.W;
1639
+ d._QTS_NewArrayBuffer = b.X;
1640
+ d._QTS_NewFloat64 = b.Y;
1641
+ d._QTS_GetFloat64 = b.Z;
1642
+ d._QTS_NewString = b._;
1643
+ d._QTS_GetString = b.$;
1644
+ d._QTS_GetArrayBuffer = b.aa;
1645
+ d._QTS_GetArrayBufferLength = b.ba;
1646
+ d._QTS_NewSymbol = b.ca;
1647
+ d._QTS_GetSymbolDescriptionOrKey = b.da;
1648
+ d._QTS_IsGlobalSymbol = b.ea;
1649
+ d._QTS_IsJobPending = b.fa;
1650
+ d._QTS_ExecutePendingJob = b.ga;
1651
+ d._QTS_GetProp = b.ha;
1652
+ d._QTS_GetPropNumber = b.ia;
1653
+ d._QTS_SetProp = b.ja;
1654
+ d._QTS_DefineProp = b.ka;
1655
+ d._QTS_GetOwnPropertyNames = b.la;
1656
+ d._QTS_Call = b.ma;
1657
+ d._QTS_ResolveException = b.na;
1658
+ d._QTS_Dump = b.oa;
1659
+ d._QTS_Eval = b.pa;
1660
+ d._QTS_GetModuleNamespace = b.qa;
1661
+ d._QTS_Typeof = b.ra;
1662
+ d._QTS_GetLength = b.sa;
1663
+ d._QTS_IsEqual = b.ta;
1664
+ d._QTS_GetGlobalObject = b.ua;
1665
+ d._QTS_NewPromiseCapability = b.va;
1666
+ d._QTS_PromiseState = b.wa;
1667
+ d._QTS_PromiseResult = b.xa;
1668
+ d._QTS_TestStringArg = b.ya;
1669
+ d._QTS_GetDebugLogEnabled = b.za;
1670
+ d._QTS_SetDebugLogEnabled = b.Aa;
1671
+ d._QTS_BuildIsDebug = b.Ba;
1672
+ d._QTS_BuildIsAsyncify = b.Ca;
1673
+ d._QTS_NewFunction = b.Da;
1674
+ d._QTS_ArgvGetJSValueConstPointer = b.Ea;
1675
+ d._QTS_RuntimeEnableInterruptHandler = b.Fa;
1676
+ d._QTS_RuntimeDisableInterruptHandler = b.Ga;
1677
+ d._QTS_RuntimeEnableModuleLoader = b.Ha;
1678
+ d._QTS_RuntimeDisableModuleLoader = b.Ia;
1679
+ d._QTS_bjson_encode = b.Ja;
1680
+ d._QTS_bjson_decode = b.Ka;
1681
+ wa = b.La;
1682
+ ua = b.Ma;
1683
+ Y = b.Na;
1684
+ ta = b.Oa;
1685
+ return Z;
1686
+ }
1687
+ var c = { a: xa };
1688
+ if (d.instantiateWasm) return new Promise((b) => {
1689
+ d.instantiateWasm(c, (e, f) => {
1690
+ b(a(e, f));
1691
+ });
1692
+ });
1693
+ O ??= d.locateFile ? d.locateFile ? d.locateFile("emscripten-module.wasm", y) : y + "emscripten-module.wasm" : new URL("emscripten-module.wasm", import.meta.url).href;
1694
+ return a((await fa(c)).instance);
1695
+ })();
1696
+ (function() {
1697
+ function a() {
1698
+ d.calledRun = true;
1699
+ if (!F) {
1700
+ ba = true;
1701
+ Z.u();
1702
+ H?.(d);
1703
+ d.onRuntimeInitialized?.();
1704
+ if (d.postRun) for ("function" == typeof d.postRun && (d.postRun = [d.postRun]); d.postRun.length; ) {
1705
+ var c = d.postRun.shift();
1706
+ ia.push(c);
1707
+ }
1708
+ ha(ia);
1709
+ }
1710
+ }
1711
+ if (d.preRun) for ("function" == typeof d.preRun && (d.preRun = [d.preRun]); d.preRun.length; ) ka();
1712
+ ha(ja);
1713
+ d.setStatus ? (d.setStatus("Running..."), setTimeout(() => {
1714
+ setTimeout(() => d.setStatus(""), 1);
1715
+ a();
1716
+ }, 1)) : a();
1717
+ })();
1718
+ ba ? moduleRtn = d : moduleRtn = new Promise((a, c) => {
1719
+ H = a;
1720
+ I = c;
1721
+ });
1722
+ ;
1723
+ return moduleRtn;
1724
+ }
1725
+ var emscripten_module_default;
1726
+ var init_emscripten_module = __esm({
1727
+ "../node_modules/@jitl/quickjs-wasmfile-release-sync/dist/emscripten-module.mjs"() {
1728
+ emscripten_module_default = QuickJSRaw;
1729
+ }
1730
+ });
1731
+
1732
+ // src/render-thread.mjs
1733
+ import { parentPort, workerData } from "node:worker_threads";
1734
+ import { readFileSync } from "node:fs";
1735
+
1736
+ // ../node_modules/quickjs-emscripten-core/dist/index.mjs
1737
+ init_chunk_V2S4ZYJR();
1738
+ init_dist();
1739
+ async function newQuickJSWASMModuleFromVariant(variantOrPromise) {
1740
+ let variant2 = smartUnwrap(await variantOrPromise), [wasmModuleLoader, QuickJSFFI2, { QuickJSWASMModule: QuickJSWASMModule2 }] = await Promise.all([variant2.importModuleLoader().then(smartUnwrap), variant2.importFFI(), Promise.resolve().then(() => (init_module_ES6BEMUI(), module_ES6BEMUI_exports)).then(smartUnwrap)]), wasmModule2 = await wasmModuleLoader();
1741
+ wasmModule2.type = "sync";
1742
+ let ffi = new QuickJSFFI2(wasmModule2);
1743
+ return new QuickJSWASMModule2(wasmModule2, ffi);
1744
+ }
1745
+ function smartUnwrap(val) {
1746
+ return val && "default" in val && val.default ? val.default && "default" in val.default && val.default.default ? val.default.default : val.default : val;
1747
+ }
1748
+ function newVariant(baseVariant, options) {
1749
+ return { ...baseVariant, async importModuleLoader() {
1750
+ let moduleLoader = smartUnwrap(await baseVariant.importModuleLoader());
1751
+ return async function() {
1752
+ let moduleLoaderArg = options.emscriptenModule ? { ...options.emscriptenModule } : {}, log = options.log ?? ((...args) => debugLog("newVariant moduleLoader:", ...args)), tapValue = (message, val) => (log(...message, val), val), force = (val) => typeof val == "function" ? val() : val;
1753
+ (options.wasmLocation || options.wasmSourceMapLocation || options.locateFile) && (moduleLoaderArg.locateFile = (fileName, relativeTo) => {
1754
+ let args = { fileName, relativeTo };
1755
+ if (fileName.endsWith(".wasm") && options.wasmLocation !== void 0) return tapValue(["locateFile .wasm: provide wasmLocation", args], options.wasmLocation);
1756
+ if (fileName.endsWith(".map")) {
1757
+ if (options.wasmSourceMapLocation !== void 0) return tapValue(["locateFile .map: provide wasmSourceMapLocation", args], options.wasmSourceMapLocation);
1758
+ if (options.wasmLocation && !options.locateFile) return tapValue(["locateFile .map: infer from wasmLocation", args], options.wasmLocation + ".map");
1759
+ }
1760
+ return options.locateFile ? tapValue(["locateFile: use provided fn", args], options.locateFile(fileName, relativeTo)) : tapValue(["locateFile: unhandled, passthrough", args], fileName);
1761
+ }), options.wasmBinary && (moduleLoaderArg.wasmBinary = await force(options.wasmBinary)), options.wasmMemory && (moduleLoaderArg.wasmMemory = await force(options.wasmMemory));
1762
+ let optionsWasmModule = options.wasmModule, modulePromise;
1763
+ optionsWasmModule && (moduleLoaderArg.instantiateWasm = async (imports, onSuccess) => {
1764
+ modulePromise ?? (modulePromise = Promise.resolve(force(optionsWasmModule)));
1765
+ let wasmModule2 = await modulePromise;
1766
+ if (!wasmModule2) throw new QuickJSEmscriptenModuleError(`options.wasmModule returned ${String(wasmModule2)}`);
1767
+ let instance = await WebAssembly.instantiate(wasmModule2, imports);
1768
+ return onSuccess(instance), instance.exports;
1769
+ }), moduleLoaderArg.monitorRunDependencies = (left) => {
1770
+ log("monitorRunDependencies:", left);
1771
+ }, moduleLoaderArg.quickjsEmscriptenInit = () => newMockExtensions(log);
1772
+ let resultPromise = moduleLoader(moduleLoaderArg), extensions = moduleLoaderArg.quickjsEmscriptenInit?.(log);
1773
+ if (optionsWasmModule && extensions?.receiveWasmOffsetConverter && !extensions.existingWasmOffsetConverter) {
1774
+ let wasmBinary = await force(options.wasmBinary) ?? new ArrayBuffer(0);
1775
+ modulePromise ?? (modulePromise = Promise.resolve(force(optionsWasmModule)));
1776
+ let wasmModule2 = await modulePromise;
1777
+ if (!wasmModule2) throw new QuickJSEmscriptenModuleError(`options.wasmModule returned ${String(wasmModule2)}`);
1778
+ extensions.receiveWasmOffsetConverter(wasmBinary, wasmModule2);
1779
+ }
1780
+ if (extensions?.receiveSourceMapJSON) {
1781
+ let loadedSourceMapData = await force(options.wasmSourceMapData);
1782
+ typeof loadedSourceMapData == "string" ? extensions.receiveSourceMapJSON(JSON.parse(loadedSourceMapData)) : loadedSourceMapData ? extensions.receiveSourceMapJSON(loadedSourceMapData) : extensions.receiveSourceMapJSON({ version: 3, names: [], sources: [], mappings: "" });
1783
+ }
1784
+ return resultPromise;
1785
+ };
1786
+ } };
1787
+ }
1788
+ function newMockExtensions(log) {
1789
+ let mockMessage = "mock called, emscripten module may not be initialized yet";
1790
+ return { mock: true, removeRunDependency(name) {
1791
+ log(`${mockMessage}: removeRunDependency called:`, name);
1792
+ }, receiveSourceMapJSON(data) {
1793
+ log(`${mockMessage}: receiveSourceMapJSON called:`, data);
1794
+ }, WasmOffsetConverter: void 0, receiveWasmOffsetConverter(bytes, mod) {
1795
+ log(`${mockMessage}: receiveWasmOffsetConverter called:`, bytes, mod);
1796
+ } };
1797
+ }
1798
+ function shouldInterruptAfterDeadline(deadline) {
1799
+ let deadlineAsNumber = typeof deadline == "number" ? deadline : deadline.getTime();
1800
+ return function() {
1801
+ return Date.now() > deadlineAsNumber;
1802
+ };
1803
+ }
1804
+
1805
+ // ../node_modules/@jitl/quickjs-wasmfile-release-sync/dist/index.mjs
1806
+ var variant = { type: "sync", importFFI: () => Promise.resolve().then(() => (init_ffi(), ffi_exports)).then((mod) => mod.QuickJSFFI), importModuleLoader: () => Promise.resolve().then(() => (init_emscripten_module(), emscripten_module_exports)).then((mod) => mod.default) };
1807
+ var src_default = variant;
1808
+
1809
+ // src/render-thread.mjs
1810
+ var { limits } = workerData;
1811
+ var runtimeSource = readFileSync(new URL("./runtime.js", import.meta.url), "utf8");
1812
+ var wasmModule = new WebAssembly.Module(readFileSync(new URL("./assets/quickjs.wasm", import.meta.url)));
1813
+ var QuickJS = await newQuickJSWASMModuleFromVariant(newVariant(src_default, { wasmModule }));
1814
+ var runtime = null;
1815
+ var context = null;
1816
+ var loaded = /* @__PURE__ */ new Set();
1817
+ var QuickJSError = class extends Error {
1818
+ };
1819
+ function evaluate(code, filename, ms) {
1820
+ runtime.setInterruptHandler(shouldInterruptAfterDeadline(Date.now() + ms));
1821
+ const result = context.evalCode(code, filename);
1822
+ if (result.error) {
1823
+ const detail = context.dump(result.error);
1824
+ result.error.dispose();
1825
+ const message = detail && typeof detail === "object" ? String(detail.message ?? "") : String(detail);
1826
+ throw new QuickJSError(message);
1827
+ }
1828
+ const out = context.typeof(result.value) === "string" ? context.getString(result.value) : void 0;
1829
+ result.value.dispose();
1830
+ return out;
1831
+ }
1832
+ function dispose() {
1833
+ try {
1834
+ context?.dispose();
1835
+ runtime?.dispose();
1836
+ } catch {
1837
+ }
1838
+ context = null;
1839
+ runtime = null;
1840
+ loaded = /* @__PURE__ */ new Set();
1841
+ }
1842
+ function fresh() {
1843
+ dispose();
1844
+ runtime = QuickJS.newRuntime();
1845
+ runtime.setMemoryLimit(limits.runtimeMemoryMb * 1024 * 1024);
1846
+ runtime.setMaxStackSize(1024 * 1024);
1847
+ context = runtime.newContext();
1848
+ evaluate(runtimeSource, "parhelia-runtime.js", 1e4);
1849
+ }
1850
+ function define(buildId, module) {
1851
+ const id = JSON.stringify(buildId);
1852
+ evaluate(`__parhelia.define(${id}, "server", function (module, exports, require) {
1853
+ ${module.server}
1854
+ });`, "rendering.js", limits.componentMs);
1855
+ if (typeof module.client === "string") {
1856
+ const exportNames = JSON.stringify(JSON.stringify(module.clientExports || []));
1857
+ evaluate(`__parhelia.define(${id}, "client", function (module, exports, require) {
1858
+ ${module.client}
1859
+ }, ${exportNames});`, "client.js", limits.componentMs);
1860
+ }
1861
+ loaded.add(buildId);
1862
+ }
1863
+ function classify(message, elapsedMs) {
1864
+ if (/interrupted/i.test(message) || elapsedMs >= limits.componentMs * 0.9) return "timeout";
1865
+ if (/out of memory/i.test(message)) return "oom";
1866
+ return "render-error";
1867
+ }
1868
+ function renderOne(component, modules) {
1869
+ if (!context) fresh();
1870
+ const started = Date.now();
1871
+ try {
1872
+ if (!loaded.has(component.buildId)) {
1873
+ const module = modules[component.buildId];
1874
+ if (!module) return { key: component.key, ok: false, code: "module-missing", message: "Module source not provided." };
1875
+ define(component.buildId, module);
1876
+ }
1877
+ const request = JSON.stringify({ buildId: component.buildId, dto: component.dto });
1878
+ const out = evaluate(`__parhelia.render(${JSON.stringify(request)})`, "render.js", limits.componentMs);
1879
+ if (typeof out !== "string") {
1880
+ return { key: component.key, ok: false, code: "render-error", message: "The runtime returned a non-string result." };
1881
+ }
1882
+ if (out.length > limits.treeBytes + 1024) {
1883
+ return { key: component.key, ok: false, code: "too-large", message: `The render tree exceeds ${limits.treeBytes} bytes.` };
1884
+ }
1885
+ if (out.startsWith('{"ok":false') && out.includes("out of memory")) {
1886
+ dispose();
1887
+ return { key: component.key, ok: false, code: "oom", message: `The rendering used more than ${limits.runtimeMemoryMb} MB.`, ms: Date.now() - started };
1888
+ }
1889
+ return { key: component.key, json: out, ms: Date.now() - started };
1890
+ } catch (err) {
1891
+ const elapsed = Date.now() - started;
1892
+ const code = classify(err instanceof QuickJSError ? err.message : "", elapsed);
1893
+ dispose();
1894
+ return {
1895
+ key: component.key,
1896
+ ok: false,
1897
+ code,
1898
+ message: code === "timeout" ? `The rendering ran longer than ${limits.componentMs} ms.` : code === "oom" ? `The rendering used more than ${limits.runtimeMemoryMb} MB.` : "The rendering failed outside the runtime.",
1899
+ ms: elapsed
1900
+ };
1901
+ }
1902
+ }
1903
+ parentPort.on("message", (message) => {
1904
+ if (message.type !== "render") return;
1905
+ if (message.fresh) dispose();
1906
+ for (const component of message.components) {
1907
+ parentPort.postMessage({ type: "start", jobId: message.jobId, key: component.key });
1908
+ const result = renderOne(component, message.modules || {});
1909
+ parentPort.postMessage({ type: "result", jobId: message.jobId, ...result });
1910
+ }
1911
+ if (message.fresh) dispose();
1912
+ parentPort.postMessage({ type: "done", jobId: message.jobId, loaded: [...loaded] });
1913
+ });
1914
+ fresh();
1915
+ parentPort.postMessage({ type: "ready" });