@pipelab/cli 2.0.0-beta.0 → 2.0.0-beta.2

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,1151 @@
1
+ //#region ../../node_modules/@jitl/quickjs-ffi-types/dist/index.mjs
2
+ var EvalFlags = {
3
+ JS_EVAL_TYPE_GLOBAL: 0,
4
+ JS_EVAL_TYPE_MODULE: 1,
5
+ JS_EVAL_TYPE_DIRECT: 2,
6
+ JS_EVAL_TYPE_INDIRECT: 3,
7
+ JS_EVAL_TYPE_MASK: 3,
8
+ JS_EVAL_FLAG_STRICT: 8,
9
+ JS_EVAL_FLAG_STRIP: 16,
10
+ JS_EVAL_FLAG_COMPILE_ONLY: 32,
11
+ JS_EVAL_FLAG_BACKTRACE_BARRIER: 64
12
+ }, IntrinsicsFlags = {
13
+ BaseObjects: 1,
14
+ Date: 2,
15
+ Eval: 4,
16
+ StringNormalize: 8,
17
+ RegExp: 16,
18
+ RegExpCompiler: 32,
19
+ JSON: 64,
20
+ Proxy: 128,
21
+ MapSet: 256,
22
+ TypedArrays: 512,
23
+ Promise: 1024,
24
+ BigInt: 2048,
25
+ BigFloat: 4096,
26
+ BigDecimal: 8192,
27
+ OperatorOverloading: 16384,
28
+ BignumExt: 32768
29
+ }, JSPromiseStateEnum = {
30
+ Pending: 0,
31
+ Fulfilled: 1,
32
+ Rejected: 2
33
+ }, GetOwnPropertyNamesFlags = {
34
+ JS_GPN_STRING_MASK: 1,
35
+ JS_GPN_SYMBOL_MASK: 2,
36
+ JS_GPN_PRIVATE_MASK: 4,
37
+ JS_GPN_ENUM_ONLY: 16,
38
+ JS_GPN_SET_ENUM: 32,
39
+ QTS_GPN_NUMBER_MASK: 64,
40
+ QTS_STANDARD_COMPLIANT_NUMBER: 128
41
+ }, IsEqualOp = {
42
+ IsStrictlyEqual: 0,
43
+ IsSameValue: 1,
44
+ IsSameValueZero: 2
45
+ };
46
+ //#endregion
47
+ //#region ../../node_modules/quickjs-emscripten-core/dist/chunk-JTKJZQYV.mjs
48
+ var __defProp = Object.defineProperty;
49
+ var __export = (target, all) => {
50
+ for (var name in all) __defProp(target, name, {
51
+ get: all[name],
52
+ enumerable: !0
53
+ });
54
+ };
55
+ var QTS_DEBUG = !1;
56
+ function debugLog(...args) {
57
+ QTS_DEBUG && console.log("quickjs-emscripten:", ...args);
58
+ }
59
+ __export({}, {
60
+ QuickJSAsyncifyError: () => QuickJSAsyncifyError,
61
+ QuickJSAsyncifySuspended: () => QuickJSAsyncifySuspended,
62
+ QuickJSEmptyGetOwnPropertyNames: () => QuickJSEmptyGetOwnPropertyNames,
63
+ QuickJSEmscriptenModuleError: () => QuickJSEmscriptenModuleError,
64
+ QuickJSMemoryLeakDetected: () => QuickJSMemoryLeakDetected,
65
+ QuickJSNotImplemented: () => QuickJSNotImplemented,
66
+ QuickJSPromisePending: () => QuickJSPromisePending,
67
+ QuickJSUnknownIntrinsic: () => QuickJSUnknownIntrinsic,
68
+ QuickJSUnwrapError: () => QuickJSUnwrapError,
69
+ QuickJSUseAfterFree: () => QuickJSUseAfterFree,
70
+ QuickJSWrongOwner: () => QuickJSWrongOwner
71
+ });
72
+ var QuickJSUnwrapError = class extends Error {
73
+ constructor(cause, context) {
74
+ let message = typeof cause == "object" && cause && "message" in cause ? String(cause.message) : String(cause);
75
+ super(message);
76
+ this.cause = cause;
77
+ this.context = context;
78
+ this.name = "QuickJSUnwrapError";
79
+ }
80
+ }, QuickJSWrongOwner = class extends Error {
81
+ constructor() {
82
+ super(...arguments);
83
+ this.name = "QuickJSWrongOwner";
84
+ }
85
+ }, QuickJSUseAfterFree = class extends Error {
86
+ constructor() {
87
+ super(...arguments);
88
+ this.name = "QuickJSUseAfterFree";
89
+ }
90
+ }, QuickJSNotImplemented = class extends Error {
91
+ constructor() {
92
+ super(...arguments);
93
+ this.name = "QuickJSNotImplemented";
94
+ }
95
+ }, QuickJSAsyncifyError = class extends Error {
96
+ constructor() {
97
+ super(...arguments);
98
+ this.name = "QuickJSAsyncifyError";
99
+ }
100
+ }, QuickJSAsyncifySuspended = class extends Error {
101
+ constructor() {
102
+ super(...arguments);
103
+ this.name = "QuickJSAsyncifySuspended";
104
+ }
105
+ }, QuickJSMemoryLeakDetected = class extends Error {
106
+ constructor() {
107
+ super(...arguments);
108
+ this.name = "QuickJSMemoryLeakDetected";
109
+ }
110
+ }, QuickJSEmscriptenModuleError = class extends Error {
111
+ constructor() {
112
+ super(...arguments);
113
+ this.name = "QuickJSEmscriptenModuleError";
114
+ }
115
+ }, QuickJSUnknownIntrinsic = class extends TypeError {
116
+ constructor() {
117
+ super(...arguments);
118
+ this.name = "QuickJSUnknownIntrinsic";
119
+ }
120
+ }, QuickJSPromisePending = class extends Error {
121
+ constructor() {
122
+ super(...arguments);
123
+ this.name = "QuickJSPromisePending";
124
+ }
125
+ }, QuickJSEmptyGetOwnPropertyNames = class extends Error {
126
+ constructor() {
127
+ super(...arguments);
128
+ this.name = "QuickJSEmptyGetOwnPropertyNames";
129
+ }
130
+ };
131
+ function* awaitYield(value) {
132
+ return yield value;
133
+ }
134
+ function awaitYieldOf(generator) {
135
+ return awaitYield(awaitEachYieldedPromise(generator));
136
+ }
137
+ var AwaitYield = awaitYield;
138
+ AwaitYield.of = awaitYieldOf;
139
+ function maybeAsyncFn(that, fn) {
140
+ return (...args) => {
141
+ return awaitEachYieldedPromise(fn.call(that, AwaitYield, ...args));
142
+ };
143
+ }
144
+ function maybeAsync(that, startGenerator) {
145
+ return awaitEachYieldedPromise(startGenerator.call(that, AwaitYield));
146
+ }
147
+ function awaitEachYieldedPromise(gen) {
148
+ function handleNextStep(step) {
149
+ 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));
150
+ }
151
+ return handleNextStep(gen.next());
152
+ }
153
+ var UsingDisposable = class {
154
+ [Symbol.dispose]() {
155
+ return this.dispose();
156
+ }
157
+ }, SymbolDispose = Symbol.dispose ?? Symbol.for("Symbol.dispose"), prototypeAsAny = UsingDisposable.prototype;
158
+ prototypeAsAny[SymbolDispose] || (prototypeAsAny[SymbolDispose] = function() {
159
+ return this.dispose();
160
+ });
161
+ var Lifetime = class _Lifetime extends UsingDisposable {
162
+ constructor(_value, copier, disposer, _owner) {
163
+ super();
164
+ this._value = _value;
165
+ this.copier = copier;
166
+ this.disposer = disposer;
167
+ this._owner = _owner;
168
+ this._alive = !0;
169
+ this._constructorStack = QTS_DEBUG ? (/* @__PURE__ */ new Error("Lifetime constructed")).stack : void 0;
170
+ }
171
+ get alive() {
172
+ return this._alive;
173
+ }
174
+ get value() {
175
+ return this.assertAlive(), this._value;
176
+ }
177
+ get owner() {
178
+ return this._owner;
179
+ }
180
+ get dupable() {
181
+ return !!this.copier;
182
+ }
183
+ dup() {
184
+ if (this.assertAlive(), !this.copier) throw new Error("Non-dupable lifetime");
185
+ return new _Lifetime(this.copier(this._value), this.copier, this.disposer, this._owner);
186
+ }
187
+ consume(map) {
188
+ this.assertAlive();
189
+ let result = map(this);
190
+ return this.dispose(), result;
191
+ }
192
+ map(map) {
193
+ return this.assertAlive(), map(this);
194
+ }
195
+ tap(fn) {
196
+ return fn(this), this;
197
+ }
198
+ dispose() {
199
+ this.assertAlive(), this.disposer && this.disposer(this._value), this._alive = !1;
200
+ }
201
+ assertAlive() {
202
+ if (!this.alive) throw this._constructorStack ? new QuickJSUseAfterFree(`Lifetime not alive
203
+ ${this._constructorStack}
204
+ Lifetime used`) : new QuickJSUseAfterFree("Lifetime not alive");
205
+ }
206
+ }, StaticLifetime = class extends Lifetime {
207
+ constructor(value, owner) {
208
+ super(value, void 0, void 0, owner);
209
+ }
210
+ get dupable() {
211
+ return !0;
212
+ }
213
+ dup() {
214
+ return this;
215
+ }
216
+ dispose() {}
217
+ }, WeakLifetime = class extends Lifetime {
218
+ constructor(value, copier, disposer, owner) {
219
+ super(value, copier, disposer, owner);
220
+ }
221
+ dispose() {
222
+ this._alive = !1;
223
+ }
224
+ };
225
+ function scopeFinally(scope, blockError) {
226
+ let disposeError;
227
+ try {
228
+ scope.dispose();
229
+ } catch (error) {
230
+ disposeError = error;
231
+ }
232
+ if (blockError && disposeError) throw Object.assign(blockError, {
233
+ message: `${blockError.message}
234
+ Then, failed to dispose scope: ${disposeError.message}`,
235
+ disposeError
236
+ }), blockError;
237
+ if (blockError || disposeError) throw blockError || disposeError;
238
+ }
239
+ var Scope = class _Scope extends UsingDisposable {
240
+ constructor() {
241
+ super(...arguments);
242
+ this._disposables = new Lifetime(/* @__PURE__ */ new Set());
243
+ this.manage = (lifetime) => (this._disposables.value.add(lifetime), lifetime);
244
+ }
245
+ static withScope(block) {
246
+ let scope = new _Scope(), blockError;
247
+ try {
248
+ return block(scope);
249
+ } catch (error) {
250
+ throw blockError = error, error;
251
+ } finally {
252
+ scopeFinally(scope, blockError);
253
+ }
254
+ }
255
+ static withScopeMaybeAsync(_this, block) {
256
+ return maybeAsync(void 0, function* (awaited) {
257
+ let scope = new _Scope(), blockError;
258
+ try {
259
+ return yield* awaited.of(block.call(_this, awaited, scope));
260
+ } catch (error) {
261
+ throw blockError = error, error;
262
+ } finally {
263
+ scopeFinally(scope, blockError);
264
+ }
265
+ });
266
+ }
267
+ static async withScopeAsync(block) {
268
+ let scope = new _Scope(), blockError;
269
+ try {
270
+ return await block(scope);
271
+ } catch (error) {
272
+ throw blockError = error, error;
273
+ } finally {
274
+ scopeFinally(scope, blockError);
275
+ }
276
+ }
277
+ get alive() {
278
+ return this._disposables.alive;
279
+ }
280
+ dispose() {
281
+ let lifetimes = Array.from(this._disposables.value.values()).reverse();
282
+ for (let lifetime of lifetimes) lifetime.alive && lifetime.dispose();
283
+ this._disposables.dispose();
284
+ }
285
+ };
286
+ function createDisposableArray(items) {
287
+ let array = items ? Array.from(items) : [];
288
+ function disposeAlive() {
289
+ return array.forEach((disposable) => disposable.alive ? disposable.dispose() : void 0);
290
+ }
291
+ function someIsAlive() {
292
+ return array.some((disposable) => disposable.alive);
293
+ }
294
+ return Object.defineProperty(array, SymbolDispose, {
295
+ configurable: !0,
296
+ enumerable: !1,
297
+ value: disposeAlive
298
+ }), Object.defineProperty(array, "dispose", {
299
+ configurable: !0,
300
+ enumerable: !1,
301
+ value: disposeAlive
302
+ }), Object.defineProperty(array, "alive", {
303
+ configurable: !0,
304
+ enumerable: !1,
305
+ get: someIsAlive
306
+ }), array;
307
+ }
308
+ function isDisposable(value) {
309
+ return !!(value && (typeof value == "object" || typeof value == "function") && "alive" in value && typeof value.alive == "boolean" && "dispose" in value && typeof value.dispose == "function");
310
+ }
311
+ var AbstractDisposableResult = class _AbstractDisposableResult extends UsingDisposable {
312
+ static success(value) {
313
+ return new DisposableSuccess(value);
314
+ }
315
+ static fail(error, onUnwrap) {
316
+ return new DisposableFail(error, onUnwrap);
317
+ }
318
+ static is(result) {
319
+ return result instanceof _AbstractDisposableResult;
320
+ }
321
+ }, DisposableSuccess = class extends AbstractDisposableResult {
322
+ constructor(value) {
323
+ super();
324
+ this.value = value;
325
+ }
326
+ get alive() {
327
+ return isDisposable(this.value) ? this.value.alive : !0;
328
+ }
329
+ dispose() {
330
+ isDisposable(this.value) && this.value.dispose();
331
+ }
332
+ unwrap() {
333
+ return this.value;
334
+ }
335
+ unwrapOr(_fallback) {
336
+ return this.value;
337
+ }
338
+ }, DisposableFail = class extends AbstractDisposableResult {
339
+ constructor(error, onUnwrap) {
340
+ super();
341
+ this.error = error;
342
+ this.onUnwrap = onUnwrap;
343
+ }
344
+ get alive() {
345
+ return isDisposable(this.error) ? this.error.alive : !0;
346
+ }
347
+ dispose() {
348
+ isDisposable(this.error) && this.error.dispose();
349
+ }
350
+ unwrap() {
351
+ throw this.onUnwrap(this), this.error;
352
+ }
353
+ unwrapOr(fallback) {
354
+ return fallback;
355
+ }
356
+ }, DisposableResult = AbstractDisposableResult;
357
+ var QuickJSDeferredPromise = class extends UsingDisposable {
358
+ constructor(args) {
359
+ super();
360
+ this.resolve = (value) => {
361
+ this.resolveHandle.alive && (this.context.unwrapResult(this.context.callFunction(this.resolveHandle, this.context.undefined, value || this.context.undefined)).dispose(), this.disposeResolvers(), this.onSettled());
362
+ };
363
+ this.reject = (value) => {
364
+ this.rejectHandle.alive && (this.context.unwrapResult(this.context.callFunction(this.rejectHandle, this.context.undefined, value || this.context.undefined)).dispose(), this.disposeResolvers(), this.onSettled());
365
+ };
366
+ this.dispose = () => {
367
+ this.handle.alive && this.handle.dispose(), this.disposeResolvers();
368
+ };
369
+ this.context = args.context, this.owner = args.context.runtime, this.handle = args.promiseHandle, this.settled = new Promise((resolve) => {
370
+ this.onSettled = resolve;
371
+ }), this.resolveHandle = args.resolveHandle, this.rejectHandle = args.rejectHandle;
372
+ }
373
+ get alive() {
374
+ return this.handle.alive || this.resolveHandle.alive || this.rejectHandle.alive;
375
+ }
376
+ disposeResolvers() {
377
+ this.resolveHandle.alive && this.resolveHandle.dispose(), this.rejectHandle.alive && this.rejectHandle.dispose();
378
+ }
379
+ };
380
+ var ModuleMemory = class {
381
+ constructor(module) {
382
+ this.module = module;
383
+ }
384
+ toPointerArray(handleArray) {
385
+ let typedArray = new Int32Array(handleArray.map((handle) => handle.value)), numBytes = typedArray.length * typedArray.BYTES_PER_ELEMENT, ptr = this.module._malloc(numBytes);
386
+ return new Uint8Array(this.module.HEAPU8.buffer, ptr, numBytes).set(new Uint8Array(typedArray.buffer)), new Lifetime(ptr, void 0, (ptr2) => this.module._free(ptr2));
387
+ }
388
+ newTypedArray(kind, length) {
389
+ 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);
390
+ return typedArray.set(zeros), new Lifetime({
391
+ typedArray,
392
+ ptr
393
+ }, void 0, (value) => this.module._free(value.ptr));
394
+ }
395
+ newMutablePointerArray(length) {
396
+ return this.newTypedArray(Int32Array, length);
397
+ }
398
+ newHeapCharPointer(string) {
399
+ let strlen = this.module.lengthBytesUTF8(string), dataBytes = strlen + 1, ptr = this.module._malloc(dataBytes);
400
+ return this.module.stringToUTF8(string, ptr, dataBytes), new Lifetime({
401
+ ptr,
402
+ strlen
403
+ }, void 0, (value) => this.module._free(value.ptr));
404
+ }
405
+ newHeapBufferPointer(buffer) {
406
+ let numBytes = buffer.byteLength, ptr = this.module._malloc(numBytes);
407
+ return this.module.HEAPU8.set(buffer, ptr), new Lifetime({
408
+ pointer: ptr,
409
+ numBytes
410
+ }, void 0, (value) => this.module._free(value.pointer));
411
+ }
412
+ consumeHeapCharPointer(ptr) {
413
+ let str = this.module.UTF8ToString(ptr);
414
+ return this.module._free(ptr), str;
415
+ }
416
+ };
417
+ Object.freeze({
418
+ BaseObjects: !0,
419
+ Date: !0,
420
+ Eval: !0,
421
+ StringNormalize: !0,
422
+ RegExp: !0,
423
+ JSON: !0,
424
+ Proxy: !0,
425
+ MapSet: !0,
426
+ TypedArrays: !0,
427
+ Promise: !0
428
+ });
429
+ function intrinsicsToFlags(intrinsics) {
430
+ if (!intrinsics) return 0;
431
+ let result = 0;
432
+ for (let [maybeIntrinsicName, enabled] of Object.entries(intrinsics)) {
433
+ if (!(maybeIntrinsicName in IntrinsicsFlags)) throw new QuickJSUnknownIntrinsic(maybeIntrinsicName);
434
+ enabled && (result |= IntrinsicsFlags[maybeIntrinsicName]);
435
+ }
436
+ return result;
437
+ }
438
+ function evalOptionsToFlags(evalOptions) {
439
+ if (typeof evalOptions == "number") return evalOptions;
440
+ if (evalOptions === void 0) return 0;
441
+ let { type, strict, strip, compileOnly, backtraceBarrier } = evalOptions, flags = 0;
442
+ 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;
443
+ }
444
+ function getOwnPropertyNamesOptionsToFlags(options) {
445
+ if (typeof options == "number") return options;
446
+ if (options === void 0) return 0;
447
+ let { strings: includeStrings, symbols: includeSymbols, quickjsPrivate: includePrivate, onlyEnumerable, numbers: includeNumbers, numbersAsStrings } = options, flags = 0;
448
+ 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;
449
+ }
450
+ function concat(...values) {
451
+ let result = [];
452
+ for (let value of values) value !== void 0 && (result = result.concat(value));
453
+ return result;
454
+ }
455
+ var QuickJSIterator = class extends UsingDisposable {
456
+ constructor(handle, context) {
457
+ super();
458
+ this.handle = handle;
459
+ this.context = context;
460
+ this._isDone = !1;
461
+ this.owner = context.runtime;
462
+ }
463
+ [Symbol.iterator]() {
464
+ return this;
465
+ }
466
+ next(value) {
467
+ if (!this.alive || this._isDone) return {
468
+ done: !0,
469
+ value: void 0
470
+ };
471
+ let nextMethod = this._next ?? (this._next = this.context.getProp(this.handle, "next"));
472
+ return this.callIteratorMethod(nextMethod, value);
473
+ }
474
+ return(value) {
475
+ if (!this.alive) return {
476
+ done: !0,
477
+ value: void 0
478
+ };
479
+ let returnMethod = this.context.getProp(this.handle, "return");
480
+ if (returnMethod === this.context.undefined && value === void 0) return this.dispose(), {
481
+ done: !0,
482
+ value: void 0
483
+ };
484
+ let result = this.callIteratorMethod(returnMethod, value);
485
+ return returnMethod.dispose(), this.dispose(), result;
486
+ }
487
+ throw(e) {
488
+ if (!this.alive) return {
489
+ done: !0,
490
+ value: void 0
491
+ };
492
+ let errorHandle = e instanceof Lifetime ? e : this.context.newError(e), throwMethod = this.context.getProp(this.handle, "throw"), result = this.callIteratorMethod(throwMethod, e);
493
+ return errorHandle.alive && errorHandle.dispose(), throwMethod.dispose(), this.dispose(), result;
494
+ }
495
+ get alive() {
496
+ return this.handle.alive;
497
+ }
498
+ dispose() {
499
+ this._isDone = !0, this.handle.dispose(), this._next?.dispose();
500
+ }
501
+ callIteratorMethod(method, input) {
502
+ let callResult = input ? this.context.callFunction(method, this.handle, input) : this.context.callFunction(method, this.handle);
503
+ if (callResult.error) return this.dispose(), { value: callResult };
504
+ let done = this.context.getProp(callResult.value, "done").consume((v) => this.context.dump(v));
505
+ if (done) return callResult.value.dispose(), this.dispose(), {
506
+ done,
507
+ value: void 0
508
+ };
509
+ let value = this.context.getProp(callResult.value, "value");
510
+ return callResult.value.dispose(), {
511
+ value: DisposableResult.success(value),
512
+ done
513
+ };
514
+ }
515
+ };
516
+ var ContextMemory = class extends ModuleMemory {
517
+ constructor(args) {
518
+ super(args.module);
519
+ this.scope = new Scope();
520
+ this.copyJSValue = (ptr) => this.ffi.QTS_DupValuePointer(this.ctx.value, ptr);
521
+ this.freeJSValue = (ptr) => {
522
+ this.ffi.QTS_FreeValuePointer(this.ctx.value, ptr);
523
+ };
524
+ 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);
525
+ }
526
+ get alive() {
527
+ return this.scope.alive;
528
+ }
529
+ dispose() {
530
+ return this.scope.dispose();
531
+ }
532
+ [Symbol.dispose]() {
533
+ return this.dispose();
534
+ }
535
+ manage(lifetime) {
536
+ return this.scope.manage(lifetime);
537
+ }
538
+ consumeJSCharPointer(ptr) {
539
+ let str = this.module.UTF8ToString(ptr);
540
+ return this.ffi.QTS_FreeCString(this.ctx.value, ptr), str;
541
+ }
542
+ heapValueHandle(ptr) {
543
+ return new Lifetime(ptr, this.copyJSValue, this.freeJSValue, this.owner);
544
+ }
545
+ staticHeapValueHandle(ptr) {
546
+ return this.manage(this.heapValueHandle(ptr)), new StaticLifetime(ptr, this.owner);
547
+ }
548
+ }, QuickJSContext = class extends UsingDisposable {
549
+ constructor(args) {
550
+ super();
551
+ this._undefined = void 0;
552
+ this._null = void 0;
553
+ this._false = void 0;
554
+ this._true = void 0;
555
+ this._global = void 0;
556
+ this._BigInt = void 0;
557
+ this._Symbol = void 0;
558
+ this._SymbolIterator = void 0;
559
+ this._SymbolAsyncIterator = void 0;
560
+ this.fnNextId = -32768;
561
+ this.fnMaps = /* @__PURE__ */ new Map();
562
+ this.cToHostCallbacks = { callFunction: (ctx, this_ptr, argc, argv, fn_id) => {
563
+ if (ctx !== this.ctx.value) throw new Error("QuickJSContext instance received C -> JS call with mismatched ctx");
564
+ let fn = this.getFunction(fn_id);
565
+ if (!fn) throw new Error(`QuickJSContext had no callback with id ${fn_id}`);
566
+ return Scope.withScopeMaybeAsync(this, function* (awaited, scope) {
567
+ let thisHandle = scope.manage(new WeakLifetime(this_ptr, this.memory.copyJSValue, this.memory.freeJSValue, this.runtime)), argHandles = new Array(argc);
568
+ for (let i = 0; i < argc; i++) {
569
+ let ptr = this.ffi.QTS_ArgvGetJSValueConstPointer(argv, i);
570
+ argHandles[i] = scope.manage(new WeakLifetime(ptr, this.memory.copyJSValue, this.memory.freeJSValue, this.runtime));
571
+ }
572
+ try {
573
+ let result = yield* awaited(fn.apply(thisHandle, argHandles));
574
+ if (result) {
575
+ if ("error" in result && result.error) throw this.runtime.debugLog("throw error", result.error), result.error;
576
+ let handle = scope.manage(result instanceof Lifetime ? result : result.value);
577
+ return this.ffi.QTS_DupValuePointer(this.ctx.value, handle.value);
578
+ }
579
+ return 0;
580
+ } catch (error) {
581
+ return this.errorToHandle(error).consume((errorHandle) => this.ffi.QTS_Throw(this.ctx.value, errorHandle.value));
582
+ }
583
+ });
584
+ } };
585
+ this.runtime = args.runtime, this.module = args.module, this.ffi = args.ffi, this.rt = args.rt, this.ctx = args.ctx, this.memory = new ContextMemory({
586
+ ...args,
587
+ owner: this.runtime
588
+ }), 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));
589
+ }
590
+ get alive() {
591
+ return this.memory.alive;
592
+ }
593
+ dispose() {
594
+ this.memory.dispose();
595
+ }
596
+ get undefined() {
597
+ if (this._undefined) return this._undefined;
598
+ return this._undefined = new StaticLifetime(this.ffi.QTS_GetUndefined());
599
+ }
600
+ get null() {
601
+ if (this._null) return this._null;
602
+ return this._null = new StaticLifetime(this.ffi.QTS_GetNull());
603
+ }
604
+ get true() {
605
+ if (this._true) return this._true;
606
+ return this._true = new StaticLifetime(this.ffi.QTS_GetTrue());
607
+ }
608
+ get false() {
609
+ if (this._false) return this._false;
610
+ return this._false = new StaticLifetime(this.ffi.QTS_GetFalse());
611
+ }
612
+ get global() {
613
+ if (this._global) return this._global;
614
+ let ptr = this.ffi.QTS_GetGlobalObject(this.ctx.value);
615
+ return this._global = this.memory.staticHeapValueHandle(ptr), this._global;
616
+ }
617
+ newNumber(num) {
618
+ return this.memory.heapValueHandle(this.ffi.QTS_NewFloat64(this.ctx.value, num));
619
+ }
620
+ newString(str) {
621
+ let ptr = this.memory.newHeapCharPointer(str).consume((charHandle) => this.ffi.QTS_NewString(this.ctx.value, charHandle.value.ptr));
622
+ return this.memory.heapValueHandle(ptr);
623
+ }
624
+ newUniqueSymbol(description) {
625
+ 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));
626
+ return this.memory.heapValueHandle(ptr);
627
+ }
628
+ newSymbolFor(key) {
629
+ 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));
630
+ return this.memory.heapValueHandle(ptr);
631
+ }
632
+ getWellKnownSymbol(name) {
633
+ return this._Symbol ?? (this._Symbol = this.memory.manage(this.getProp(this.global, "Symbol"))), this.getProp(this._Symbol, name);
634
+ }
635
+ newBigInt(num) {
636
+ if (!this._BigInt) {
637
+ let bigIntHandle2 = this.getProp(this.global, "BigInt");
638
+ this.memory.manage(bigIntHandle2), this._BigInt = new StaticLifetime(bigIntHandle2.value, this.runtime);
639
+ }
640
+ let bigIntHandle = this._BigInt, asString = String(num);
641
+ return this.newString(asString).consume((handle) => this.unwrapResult(this.callFunction(bigIntHandle, this.undefined, handle)));
642
+ }
643
+ newObject(prototype) {
644
+ prototype && this.runtime.assertOwned(prototype);
645
+ let ptr = prototype ? this.ffi.QTS_NewObjectProto(this.ctx.value, prototype.value) : this.ffi.QTS_NewObject(this.ctx.value);
646
+ return this.memory.heapValueHandle(ptr);
647
+ }
648
+ newArray() {
649
+ let ptr = this.ffi.QTS_NewArray(this.ctx.value);
650
+ return this.memory.heapValueHandle(ptr);
651
+ }
652
+ newArrayBuffer(buffer) {
653
+ let array = new Uint8Array(buffer), handle = this.memory.newHeapBufferPointer(array), ptr = this.ffi.QTS_NewArrayBuffer(this.ctx.value, handle.value.pointer, array.length);
654
+ return this.memory.heapValueHandle(ptr);
655
+ }
656
+ newPromise(value) {
657
+ let deferredPromise = Scope.withScope((scope) => {
658
+ 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));
659
+ return new QuickJSDeferredPromise({
660
+ context: this,
661
+ promiseHandle,
662
+ resolveHandle,
663
+ rejectHandle
664
+ });
665
+ });
666
+ 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;
667
+ }
668
+ newFunction(name, fn) {
669
+ let fnId = ++this.fnNextId;
670
+ return this.setFunction(fnId, fn), this.memory.heapValueHandle(this.ffi.QTS_NewFunction(this.ctx.value, fnId, name));
671
+ }
672
+ newError(error) {
673
+ let errorHandle = this.memory.heapValueHandle(this.ffi.QTS_NewError(this.ctx.value));
674
+ 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;
675
+ }
676
+ typeof(handle) {
677
+ return this.runtime.assertOwned(handle), this.memory.consumeHeapCharPointer(this.ffi.QTS_Typeof(this.ctx.value, handle.value));
678
+ }
679
+ getNumber(handle) {
680
+ return this.runtime.assertOwned(handle), this.ffi.QTS_GetFloat64(this.ctx.value, handle.value);
681
+ }
682
+ getString(handle) {
683
+ return this.runtime.assertOwned(handle), this.memory.consumeJSCharPointer(this.ffi.QTS_GetString(this.ctx.value, handle.value));
684
+ }
685
+ getSymbol(handle) {
686
+ this.runtime.assertOwned(handle);
687
+ let key = this.memory.consumeJSCharPointer(this.ffi.QTS_GetSymbolDescriptionOrKey(this.ctx.value, handle.value));
688
+ return this.ffi.QTS_IsGlobalSymbol(this.ctx.value, handle.value) ? Symbol.for(key) : Symbol(key);
689
+ }
690
+ getBigInt(handle) {
691
+ this.runtime.assertOwned(handle);
692
+ let asString = this.getString(handle);
693
+ return BigInt(asString);
694
+ }
695
+ getArrayBuffer(handle) {
696
+ this.runtime.assertOwned(handle);
697
+ let len = this.ffi.QTS_GetArrayBufferLength(this.ctx.value, handle.value), ptr = this.ffi.QTS_GetArrayBuffer(this.ctx.value, handle.value);
698
+ if (!ptr) throw new Error("Couldn't allocate memory to get ArrayBuffer");
699
+ return new Lifetime(this.module.HEAPU8.subarray(ptr, ptr + len), void 0, () => this.module._free(ptr));
700
+ }
701
+ getPromiseState(handle) {
702
+ this.runtime.assertOwned(handle);
703
+ let state = this.ffi.QTS_PromiseState(this.ctx.value, handle.value);
704
+ if (state < 0) return {
705
+ type: "fulfilled",
706
+ value: handle,
707
+ notAPromise: !0
708
+ };
709
+ if (state === JSPromiseStateEnum.Pending) return {
710
+ type: "pending",
711
+ get error() {
712
+ return new QuickJSPromisePending("Cannot unwrap a pending promise");
713
+ }
714
+ };
715
+ let ptr = this.ffi.QTS_PromiseResult(this.ctx.value, handle.value), result = this.memory.heapValueHandle(ptr);
716
+ if (state === JSPromiseStateEnum.Fulfilled) return {
717
+ type: "fulfilled",
718
+ value: result
719
+ };
720
+ if (state === JSPromiseStateEnum.Rejected) return {
721
+ type: "rejected",
722
+ error: result
723
+ };
724
+ throw result.dispose(), /* @__PURE__ */ new Error(`Unknown JSPromiseStateEnum: ${state}`);
725
+ }
726
+ resolvePromise(promiseLikeHandle) {
727
+ this.runtime.assertOwned(promiseLikeHandle);
728
+ let vmResolveResult = Scope.withScope((scope) => {
729
+ let vmPromise = scope.manage(this.getProp(this.global, "Promise")), vmPromiseResolve = scope.manage(this.getProp(vmPromise, "resolve"));
730
+ return this.callFunction(vmPromiseResolve, vmPromise, promiseLikeHandle);
731
+ });
732
+ return vmResolveResult.error ? Promise.resolve(vmResolveResult) : new Promise((resolve) => {
733
+ Scope.withScope((scope) => {
734
+ let resolveHandle = scope.manage(this.newFunction("resolve", (value) => {
735
+ resolve(this.success(value && value.dup()));
736
+ })), rejectHandle = scope.manage(this.newFunction("reject", (error) => {
737
+ resolve(this.fail(error && error.dup()));
738
+ })), promiseHandle = scope.manage(vmResolveResult.value), promiseThenHandle = scope.manage(this.getProp(promiseHandle, "then"));
739
+ this.callFunction(promiseThenHandle, promiseHandle, resolveHandle, rejectHandle).unwrap().dispose();
740
+ });
741
+ });
742
+ }
743
+ isEqual(a, b, equalityType = IsEqualOp.IsStrictlyEqual) {
744
+ if (a === b) return !0;
745
+ this.runtime.assertOwned(a), this.runtime.assertOwned(b);
746
+ let result = this.ffi.QTS_IsEqual(this.ctx.value, a.value, b.value, equalityType);
747
+ if (result === -1) throw new QuickJSNotImplemented("WASM variant does not expose equality");
748
+ return !!result;
749
+ }
750
+ eq(handle, other) {
751
+ return this.isEqual(handle, other, IsEqualOp.IsStrictlyEqual);
752
+ }
753
+ sameValue(handle, other) {
754
+ return this.isEqual(handle, other, IsEqualOp.IsSameValue);
755
+ }
756
+ sameValueZero(handle, other) {
757
+ return this.isEqual(handle, other, IsEqualOp.IsSameValueZero);
758
+ }
759
+ getProp(handle, key) {
760
+ this.runtime.assertOwned(handle);
761
+ let ptr;
762
+ 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);
763
+ }
764
+ getLength(handle) {
765
+ 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];
766
+ }
767
+ getOwnPropertyNames(handle, options = {
768
+ strings: !0,
769
+ numbersAsStrings: !0
770
+ }) {
771
+ this.runtime.assertOwned(handle), handle.value;
772
+ let flags = getOwnPropertyNamesOptionsToFlags(options);
773
+ if (flags === 0) throw new QuickJSEmptyGetOwnPropertyNames("No options set, will return an empty array");
774
+ return Scope.withScope((scope) => {
775
+ 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);
776
+ if (errorPtr) return this.fail(this.memory.heapValueHandle(errorPtr));
777
+ 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));
778
+ return this.ffi.QTS_FreeVoidPointer(this.ctx.value, ptr), this.success(createDisposableArray(handles));
779
+ });
780
+ }
781
+ getIterator(iterableHandle) {
782
+ let SymbolIterator = this._SymbolIterator ?? (this._SymbolIterator = this.memory.manage(this.getWellKnownSymbol("iterator")));
783
+ return Scope.withScope((scope) => {
784
+ let methodHandle = scope.manage(this.getProp(iterableHandle, SymbolIterator)), iteratorCallResult = this.callFunction(methodHandle, iterableHandle);
785
+ return iteratorCallResult.error ? iteratorCallResult : this.success(new QuickJSIterator(iteratorCallResult.value, this));
786
+ });
787
+ }
788
+ setProp(handle, key, value) {
789
+ this.runtime.assertOwned(handle), this.borrowPropertyKey(key).consume((quickJSKey) => this.ffi.QTS_SetProp(this.ctx.value, handle.value, quickJSKey.value, value.value));
790
+ }
791
+ defineProp(handle, key, descriptor) {
792
+ this.runtime.assertOwned(handle), Scope.withScope((scope) => {
793
+ 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;
794
+ this.ffi.QTS_DefineProp(this.ctx.value, handle.value, quickJSKey.value, value.value, get.value, set.value, configurable, enumerable, hasValue);
795
+ });
796
+ }
797
+ callFunction(func, thisVal, ...restArgs) {
798
+ this.runtime.assertOwned(func);
799
+ let args, firstArg = restArgs[0];
800
+ firstArg === void 0 || Array.isArray(firstArg) ? args = firstArg ?? [] : args = restArgs;
801
+ 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);
802
+ return errorPtr ? (this.ffi.QTS_FreeValuePointer(this.ctx.value, resultPtr), this.fail(this.memory.heapValueHandle(errorPtr))) : this.success(this.memory.heapValueHandle(resultPtr));
803
+ }
804
+ callMethod(thisHandle, key, args = []) {
805
+ return this.getProp(thisHandle, key).consume((func) => this.callFunction(func, thisHandle, args));
806
+ }
807
+ evalCode(code, filename = "eval.js", options) {
808
+ 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);
809
+ return errorPtr ? (this.ffi.QTS_FreeValuePointer(this.ctx.value, resultPtr), this.fail(this.memory.heapValueHandle(errorPtr))) : this.success(this.memory.heapValueHandle(resultPtr));
810
+ }
811
+ throw(error) {
812
+ return this.errorToHandle(error).consume((handle) => this.ffi.QTS_Throw(this.ctx.value, handle.value));
813
+ }
814
+ borrowPropertyKey(key) {
815
+ return typeof key == "number" ? this.newNumber(key) : typeof key == "string" ? this.newString(key) : new StaticLifetime(key.value, this.runtime);
816
+ }
817
+ getMemory(rt) {
818
+ if (rt === this.rt.value) return this.memory;
819
+ throw new Error("Private API. Cannot get memory from a different runtime");
820
+ }
821
+ dump(handle) {
822
+ this.runtime.assertOwned(handle);
823
+ let type = this.typeof(handle);
824
+ if (type === "string") return this.getString(handle);
825
+ if (type === "number") return this.getNumber(handle);
826
+ if (type === "bigint") return this.getBigInt(handle);
827
+ if (type === "undefined") return;
828
+ if (type === "symbol") return this.getSymbol(handle);
829
+ let asPromiseState = this.getPromiseState(handle);
830
+ if (asPromiseState.type === "fulfilled" && !asPromiseState.notAPromise) return handle.dispose(), {
831
+ type: asPromiseState.type,
832
+ value: asPromiseState.value.consume(this.dump)
833
+ };
834
+ if (asPromiseState.type === "pending") return handle.dispose(), { type: asPromiseState.type };
835
+ if (asPromiseState.type === "rejected") return handle.dispose(), {
836
+ type: asPromiseState.type,
837
+ error: asPromiseState.error.consume(this.dump)
838
+ };
839
+ let str = this.memory.consumeJSCharPointer(this.ffi.QTS_Dump(this.ctx.value, handle.value));
840
+ try {
841
+ return JSON.parse(str);
842
+ } catch {
843
+ return str;
844
+ }
845
+ }
846
+ unwrapResult(result) {
847
+ if (result.error) {
848
+ let context = "context" in result.error ? result.error.context : this, cause = result.error.consume((error) => this.dump(error));
849
+ if (cause && typeof cause == "object" && typeof cause.message == "string") {
850
+ let { message, name, stack, ...rest } = cause, exception = new QuickJSUnwrapError(cause, context);
851
+ typeof name == "string" && (exception.name = cause.name), exception.message = message;
852
+ let hostStack = exception.stack;
853
+ throw typeof stack == "string" && (exception.stack = `${name}: ${message}
854
+ ${cause.stack}Host: ${hostStack}`), Object.assign(exception, rest), exception;
855
+ }
856
+ throw new QuickJSUnwrapError(cause);
857
+ }
858
+ return result.value;
859
+ }
860
+ [Symbol.for("nodejs.util.inspect.custom")]() {
861
+ return this.alive ? `${this.constructor.name} { ctx: ${this.ctx.value} rt: ${this.rt.value} }` : `${this.constructor.name} { disposed }`;
862
+ }
863
+ getFunction(fn_id) {
864
+ let map_id = fn_id >> 8, fnMap = this.fnMaps.get(map_id);
865
+ if (fnMap) return fnMap.get(fn_id);
866
+ }
867
+ setFunction(fn_id, handle) {
868
+ let map_id = fn_id >> 8, fnMap = this.fnMaps.get(map_id);
869
+ return fnMap || (fnMap = /* @__PURE__ */ new Map(), this.fnMaps.set(map_id, fnMap)), fnMap.set(fn_id, handle);
870
+ }
871
+ errorToHandle(error) {
872
+ return error instanceof Lifetime ? error : this.newError(error);
873
+ }
874
+ encodeBinaryJSON(handle) {
875
+ let ptr = this.ffi.QTS_bjson_encode(this.ctx.value, handle.value);
876
+ return this.memory.heapValueHandle(ptr);
877
+ }
878
+ decodeBinaryJSON(handle) {
879
+ let ptr = this.ffi.QTS_bjson_decode(this.ctx.value, handle.value);
880
+ return this.memory.heapValueHandle(ptr);
881
+ }
882
+ success(value) {
883
+ return DisposableResult.success(value);
884
+ }
885
+ fail(error) {
886
+ return DisposableResult.fail(error, (error2) => this.unwrapResult(error2));
887
+ }
888
+ };
889
+ var QuickJSRuntime = class extends UsingDisposable {
890
+ constructor(args) {
891
+ super();
892
+ this.scope = new Scope();
893
+ this.contextMap = /* @__PURE__ */ new Map();
894
+ this._debugMode = !1;
895
+ this.cToHostCallbacks = {
896
+ shouldInterrupt: (rt) => {
897
+ if (rt !== this.rt.value) throw new Error("QuickJSContext instance received C -> JS interrupt with mismatched rt");
898
+ let fn = this.interruptHandler;
899
+ if (!fn) throw new Error("QuickJSContext had no interrupt handler");
900
+ return fn(this) ? 1 : 0;
901
+ },
902
+ loadModuleSource: maybeAsyncFn(this, function* (awaited, rt, ctx, moduleName) {
903
+ let moduleLoader = this.moduleLoader;
904
+ if (!moduleLoader) throw new Error("Runtime has no module loader");
905
+ if (rt !== this.rt.value) throw new Error("Runtime pointer mismatch");
906
+ let context = this.contextMap.get(ctx) ?? this.newContext({ contextPointer: ctx });
907
+ try {
908
+ let result = yield* awaited(moduleLoader(moduleName, context));
909
+ if (typeof result == "object" && "error" in result && result.error) throw this.debugLog("cToHostLoadModule: loader returned error", result.error), result.error;
910
+ let moduleSource = typeof result == "string" ? result : "value" in result ? result.value : result;
911
+ return this.memory.newHeapCharPointer(moduleSource).value.ptr;
912
+ } catch (error) {
913
+ return this.debugLog("cToHostLoadModule: caught error", error), context.throw(error), 0;
914
+ }
915
+ }),
916
+ normalizeModule: maybeAsyncFn(this, function* (awaited, rt, ctx, baseModuleName, moduleNameRequest) {
917
+ let moduleNormalizer = this.moduleNormalizer;
918
+ if (!moduleNormalizer) throw new Error("Runtime has no module normalizer");
919
+ if (rt !== this.rt.value) throw new Error("Runtime pointer mismatch");
920
+ let context = this.contextMap.get(ctx) ?? this.newContext({ contextPointer: ctx });
921
+ try {
922
+ let result = yield* awaited(moduleNormalizer(baseModuleName, moduleNameRequest, context));
923
+ if (typeof result == "object" && "error" in result && result.error) throw this.debugLog("cToHostNormalizeModule: normalizer returned error", result.error), result.error;
924
+ let name = typeof result == "string" ? result : result.value;
925
+ return context.getMemory(this.rt.value).newHeapCharPointer(name).value.ptr;
926
+ } catch (error) {
927
+ return this.debugLog("normalizeModule: caught error", error), context.throw(error), 0;
928
+ }
929
+ })
930
+ };
931
+ 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(!0);
932
+ }
933
+ get alive() {
934
+ return this.scope.alive;
935
+ }
936
+ dispose() {
937
+ return this.scope.dispose();
938
+ }
939
+ newContext(options = {}) {
940
+ let intrinsics = intrinsicsToFlags(options.intrinsics), ctx = new Lifetime(options.contextPointer || this.ffi.QTS_NewContext(this.rt.value, intrinsics), void 0, (ctx_ptr) => {
941
+ this.contextMap.delete(ctx_ptr), this.callbacks.deleteContext(ctx_ptr), this.ffi.QTS_FreeContext(ctx_ptr);
942
+ }), context = new QuickJSContext({
943
+ module: this.module,
944
+ ctx,
945
+ ffi: this.ffi,
946
+ rt: this.rt,
947
+ ownedLifetimes: options.ownedLifetimes,
948
+ runtime: this,
949
+ callbacks: this.callbacks
950
+ });
951
+ return this.contextMap.set(ctx.value, context), context;
952
+ }
953
+ setModuleLoader(moduleLoader, moduleNormalizer) {
954
+ this.moduleLoader = moduleLoader, this.moduleNormalizer = moduleNormalizer, this.ffi.QTS_RuntimeEnableModuleLoader(this.rt.value, this.moduleNormalizer ? 1 : 0);
955
+ }
956
+ removeModuleLoader() {
957
+ this.moduleLoader = void 0, this.ffi.QTS_RuntimeDisableModuleLoader(this.rt.value);
958
+ }
959
+ hasPendingJob() {
960
+ return !!this.ffi.QTS_IsJobPending(this.rt.value);
961
+ }
962
+ setInterruptHandler(cb) {
963
+ let prevInterruptHandler = this.interruptHandler;
964
+ this.interruptHandler = cb, prevInterruptHandler || this.ffi.QTS_RuntimeEnableInterruptHandler(this.rt.value);
965
+ }
966
+ removeInterruptHandler() {
967
+ this.interruptHandler && (this.ffi.QTS_RuntimeDisableInterruptHandler(this.rt.value), this.interruptHandler = void 0);
968
+ }
969
+ executePendingJobs(maxJobsToExecute = -1) {
970
+ let ctxPtrOut = this.memory.newMutablePointerArray(1), valuePtr = this.ffi.QTS_ExecutePendingJob(this.rt.value, maxJobsToExecute ?? -1, ctxPtrOut.value.ptr), ctxPtr = ctxPtrOut.value.typedArray[0];
971
+ if (ctxPtrOut.dispose(), ctxPtr === 0) return this.ffi.QTS_FreeValuePointerRuntime(this.rt.value, valuePtr), DisposableResult.success(0);
972
+ let context = this.contextMap.get(ctxPtr) ?? this.newContext({ contextPointer: ctxPtr }), resultValue = context.getMemory(this.rt.value).heapValueHandle(valuePtr);
973
+ if (context.typeof(resultValue) === "number") {
974
+ let executedJobs = context.getNumber(resultValue);
975
+ return resultValue.dispose(), DisposableResult.success(executedJobs);
976
+ } else {
977
+ let error = Object.assign(resultValue, { context });
978
+ return DisposableResult.fail(error, (error2) => context.unwrapResult(error2));
979
+ }
980
+ }
981
+ setMemoryLimit(limitBytes) {
982
+ if (limitBytes < 0 && limitBytes !== -1) throw new Error("Cannot set memory limit to negative number. To unset, pass -1");
983
+ this.ffi.QTS_RuntimeSetMemoryLimit(this.rt.value, limitBytes);
984
+ }
985
+ computeMemoryUsage() {
986
+ let serviceContextMemory = this.getSystemContext().getMemory(this.rt.value);
987
+ return serviceContextMemory.heapValueHandle(this.ffi.QTS_RuntimeComputeMemoryUsage(this.rt.value, serviceContextMemory.ctx.value));
988
+ }
989
+ dumpMemoryUsage() {
990
+ return this.memory.consumeHeapCharPointer(this.ffi.QTS_RuntimeDumpMemoryUsage(this.rt.value));
991
+ }
992
+ setMaxStackSize(stackSize) {
993
+ if (stackSize < 0) throw new Error("Cannot set memory limit to negative number. To unset, pass 0.");
994
+ this.ffi.QTS_RuntimeSetMaxStackSize(this.rt.value, stackSize);
995
+ }
996
+ assertOwned(handle) {
997
+ 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}`);
998
+ }
999
+ setDebugMode(enabled) {
1000
+ this._debugMode = enabled, this.ffi.DEBUG && this.rt.alive && this.ffi.QTS_SetDebugLogEnabled(this.rt.value, enabled ? 1 : 0);
1001
+ }
1002
+ isDebugMode() {
1003
+ return this._debugMode;
1004
+ }
1005
+ debugLog(...msg) {
1006
+ this._debugMode && console.log("quickjs-emscripten:", ...msg);
1007
+ }
1008
+ [Symbol.for("nodejs.util.inspect.custom")]() {
1009
+ return this.alive ? `${this.constructor.name} { rt: ${this.rt.value} }` : `${this.constructor.name} { disposed }`;
1010
+ }
1011
+ getSystemContext() {
1012
+ return this.context || (this.context = this.scope.manage(this.newContext())), this.context;
1013
+ }
1014
+ };
1015
+ var QuickJSEmscriptenModuleCallbacks = class {
1016
+ constructor(args) {
1017
+ this.callFunction = args.callFunction, this.shouldInterrupt = args.shouldInterrupt, this.loadModuleSource = args.loadModuleSource, this.normalizeModule = args.normalizeModule;
1018
+ }
1019
+ }, QuickJSModuleCallbacks = class {
1020
+ constructor(module) {
1021
+ this.contextCallbacks = /* @__PURE__ */ new Map();
1022
+ this.runtimeCallbacks = /* @__PURE__ */ new Map();
1023
+ this.suspendedCount = 0;
1024
+ this.cToHostCallbacks = new QuickJSEmscriptenModuleCallbacks({
1025
+ callFunction: (asyncify, ctx, this_ptr, argc, argv, fn_id) => this.handleAsyncify(asyncify, () => {
1026
+ try {
1027
+ let vm = this.contextCallbacks.get(ctx);
1028
+ if (!vm) throw new Error(`QuickJSContext(ctx = ${ctx}) not found for C function call "${fn_id}"`);
1029
+ return vm.callFunction(ctx, this_ptr, argc, argv, fn_id);
1030
+ } catch (error) {
1031
+ return console.error("[C to host error: returning null]", error), 0;
1032
+ }
1033
+ }),
1034
+ shouldInterrupt: (asyncify, rt) => this.handleAsyncify(asyncify, () => {
1035
+ try {
1036
+ let vm = this.runtimeCallbacks.get(rt);
1037
+ if (!vm) throw new Error(`QuickJSRuntime(rt = ${rt}) not found for C interrupt`);
1038
+ return vm.shouldInterrupt(rt);
1039
+ } catch (error) {
1040
+ return console.error("[C to host interrupt: returning error]", error), 1;
1041
+ }
1042
+ }),
1043
+ loadModuleSource: (asyncify, rt, ctx, moduleName) => this.handleAsyncify(asyncify, () => {
1044
+ try {
1045
+ let runtimeCallbacks = this.runtimeCallbacks.get(rt);
1046
+ if (!runtimeCallbacks) throw new Error(`QuickJSRuntime(rt = ${rt}) not found for C module loader`);
1047
+ let loadModule = runtimeCallbacks.loadModuleSource;
1048
+ if (!loadModule) throw new Error(`QuickJSRuntime(rt = ${rt}) does not support module loading`);
1049
+ return loadModule(rt, ctx, moduleName);
1050
+ } catch (error) {
1051
+ return console.error("[C to host module loader error: returning null]", error), 0;
1052
+ }
1053
+ }),
1054
+ normalizeModule: (asyncify, rt, ctx, moduleBaseName, moduleName) => this.handleAsyncify(asyncify, () => {
1055
+ try {
1056
+ let runtimeCallbacks = this.runtimeCallbacks.get(rt);
1057
+ if (!runtimeCallbacks) throw new Error(`QuickJSRuntime(rt = ${rt}) not found for C module loader`);
1058
+ let normalizeModule = runtimeCallbacks.normalizeModule;
1059
+ if (!normalizeModule) throw new Error(`QuickJSRuntime(rt = ${rt}) does not support module loading`);
1060
+ return normalizeModule(rt, ctx, moduleBaseName, moduleName);
1061
+ } catch (error) {
1062
+ return console.error("[C to host module loader error: returning null]", error), 0;
1063
+ }
1064
+ })
1065
+ });
1066
+ this.module = module, this.module.callbacks = this.cToHostCallbacks;
1067
+ }
1068
+ setRuntimeCallbacks(rt, callbacks) {
1069
+ this.runtimeCallbacks.set(rt, callbacks);
1070
+ }
1071
+ deleteRuntime(rt) {
1072
+ this.runtimeCallbacks.delete(rt);
1073
+ }
1074
+ setContextCallbacks(ctx, callbacks) {
1075
+ this.contextCallbacks.set(ctx, callbacks);
1076
+ }
1077
+ deleteContext(ctx) {
1078
+ this.contextCallbacks.delete(ctx);
1079
+ }
1080
+ handleAsyncify(asyncify, fn) {
1081
+ if (asyncify) return asyncify.handleSleep((done) => {
1082
+ try {
1083
+ let result = fn();
1084
+ if (!(result instanceof Promise)) {
1085
+ debugLog("asyncify.handleSleep: not suspending:", result), done(result);
1086
+ return;
1087
+ }
1088
+ if (this.suspended) throw new QuickJSAsyncifyError(`Already suspended at: ${this.suspended.stack}
1089
+ Attempted to suspend at:`);
1090
+ this.suspended = new QuickJSAsyncifySuspended(`(${this.suspendedCount++})`), debugLog("asyncify.handleSleep: suspending:", this.suspended), result.then((resolvedResult) => {
1091
+ this.suspended = void 0, debugLog("asyncify.handleSleep: resolved:", resolvedResult), done(resolvedResult);
1092
+ }, (error) => {
1093
+ debugLog("asyncify.handleSleep: rejected:", error), console.error("QuickJS: cannot handle error in suspended function", error), this.suspended = void 0;
1094
+ });
1095
+ } catch (error) {
1096
+ throw debugLog("asyncify.handleSleep: error:", error), this.suspended = void 0, error;
1097
+ }
1098
+ });
1099
+ let value = fn();
1100
+ if (value instanceof Promise) throw new Error("Promise return value not supported in non-asyncify context.");
1101
+ return value;
1102
+ }
1103
+ };
1104
+ function applyBaseRuntimeOptions(runtime, options) {
1105
+ options.interruptHandler && runtime.setInterruptHandler(options.interruptHandler), options.maxStackSizeBytes !== void 0 && runtime.setMaxStackSize(options.maxStackSizeBytes), options.memoryLimitBytes !== void 0 && runtime.setMemoryLimit(options.memoryLimitBytes);
1106
+ }
1107
+ function applyModuleEvalRuntimeOptions(runtime, options) {
1108
+ options.moduleLoader && runtime.setModuleLoader(options.moduleLoader), options.shouldInterrupt && runtime.setInterruptHandler(options.shouldInterrupt), options.memoryLimitBytes !== void 0 && runtime.setMemoryLimit(options.memoryLimitBytes), options.maxStackSizeBytes !== void 0 && runtime.setMaxStackSize(options.maxStackSizeBytes);
1109
+ }
1110
+ var 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.callbacks.deleteRuntime(rt_ptr), this.ffi.QTS_FreeRuntime(rt_ptr);
1117
+ }), runtime = new QuickJSRuntime({
1118
+ module: this.module,
1119
+ callbacks: this.callbacks,
1120
+ ffi: this.ffi,
1121
+ rt
1122
+ });
1123
+ return applyBaseRuntimeOptions(runtime, options), options.moduleLoader && runtime.setModuleLoader(options.moduleLoader), runtime;
1124
+ }
1125
+ newContext(options = {}) {
1126
+ let runtime = this.newRuntime(), context = runtime.newContext({
1127
+ ...options,
1128
+ ownedLifetimes: concat(runtime, options.ownedLifetimes)
1129
+ });
1130
+ return runtime.context = context, context;
1131
+ }
1132
+ evalCode(code, options = {}) {
1133
+ return Scope.withScope((scope) => {
1134
+ let vm = scope.manage(this.newContext());
1135
+ applyModuleEvalRuntimeOptions(vm.runtime, options);
1136
+ let result = vm.evalCode(code, "eval.js");
1137
+ if (options.memoryLimitBytes !== void 0 && vm.runtime.setMemoryLimit(-1), result.error) throw vm.dump(scope.manage(result.error));
1138
+ return vm.dump(scope.manage(result.value));
1139
+ });
1140
+ }
1141
+ getWasmMemory() {
1142
+ let memory = this.module.quickjsEmscriptenInit?.(() => {})?.getWasmMemory?.();
1143
+ if (!memory) throw new Error("Variant does not support getting WebAssembly.Memory");
1144
+ return memory;
1145
+ }
1146
+ getFFI() {
1147
+ return this.ffi;
1148
+ }
1149
+ };
1150
+ //#endregion
1151
+ export { applyModuleEvalRuntimeOptions as i, QuickJSWASMModule as n, applyBaseRuntimeOptions as r, QuickJSModuleCallbacks as t };