@componentor/quickjs-emscripten-core 0.31.2 → 0.31.4

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.
@@ -2,6 +2,6 @@ var __defProp=Object.defineProperty;var __export=(target,all)=>{for(var name in
2
2
  ${this._constructorStack}
3
3
  Lifetime used`):new QuickJSUseAfterFree("Lifetime not alive")}},StaticLifetime=class extends Lifetime{constructor(value,owner){super(value,void 0,void 0,owner)}get dupable(){return!0}dup(){return this}dispose(){}},WeakLifetime=class extends Lifetime{constructor(value,copier,disposer,owner){super(value,copier,disposer,owner)}dispose(){this._alive=!1}};function scopeFinally(scope,blockError){let disposeError;try{scope.dispose()}catch(error){disposeError=error}if(blockError&&disposeError)throw Object.assign(blockError,{message:`${blockError.message}
4
4
  Then, failed to dispose scope: ${disposeError.message}`,disposeError}),blockError;if(blockError||disposeError)throw blockError||disposeError}var Scope=class _Scope extends UsingDisposable{constructor(){super(...arguments);this._disposables=new Lifetime(new Set);this.manage=lifetime=>(this._disposables.value.add(lifetime),lifetime)}static withScope(block){let scope=new _Scope,blockError;try{return block(scope)}catch(error){throw blockError=error,error}finally{scopeFinally(scope,blockError)}}static withScopeMaybeAsync(_this,block){return maybeAsync(void 0,function*(awaited){let scope=new _Scope,blockError;try{return yield*awaited.of(block.call(_this,awaited,scope))}catch(error){throw blockError=error,error}finally{scopeFinally(scope,blockError)}})}static async withScopeAsync(block){let scope=new _Scope,blockError;try{return await block(scope)}catch(error){throw blockError=error,error}finally{scopeFinally(scope,blockError)}}get alive(){return this._disposables.alive}dispose(){let lifetimes=Array.from(this._disposables.value.values()).reverse();for(let lifetime of lifetimes)lifetime.alive&&lifetime.dispose();this._disposables.dispose()}};function createDisposableArray(items){let array=items?Array.from(items):[];function disposeAlive(){return array.forEach(disposable=>disposable.alive?disposable.dispose():void 0)}function someIsAlive(){return array.some(disposable=>disposable.alive)}return Object.defineProperty(array,SymbolDispose,{configurable:!0,enumerable:!1,value:disposeAlive}),Object.defineProperty(array,"dispose",{configurable:!0,enumerable:!1,value:disposeAlive}),Object.defineProperty(array,"alive",{configurable:!0,enumerable:!1,get:someIsAlive}),array}function isDisposable(value){return!!(value&&(typeof value=="object"||typeof value=="function")&&"alive"in value&&typeof value.alive=="boolean"&&"dispose"in value&&typeof value.dispose=="function")}var AbstractDisposableResult=class _AbstractDisposableResult extends UsingDisposable{static success(value){return new DisposableSuccess(value)}static fail(error,onUnwrap){return new DisposableFail(error,onUnwrap)}static is(result){return result instanceof _AbstractDisposableResult}},DisposableSuccess=class extends AbstractDisposableResult{constructor(value){super();this.value=value}get alive(){return isDisposable(this.value)?this.value.alive:!0}dispose(){isDisposable(this.value)&&this.value.dispose()}unwrap(){return this.value}unwrapOr(_fallback){return this.value}},DisposableFail=class extends AbstractDisposableResult{constructor(error,onUnwrap){super();this.error=error;this.onUnwrap=onUnwrap}get alive(){return isDisposable(this.error)?this.error.alive:!0}dispose(){isDisposable(this.error)&&this.error.dispose()}unwrap(){throw this.onUnwrap(this),this.error}unwrapOr(fallback){return fallback}},DisposableResult=AbstractDisposableResult;import{IsEqualOp,JSPromiseStateEnum}from"@componentor/quickjs-ffi-types";var QuickJSDeferredPromise=class extends UsingDisposable{constructor(args){super();this.resolve=value=>{this.resolveHandle.alive&&(this.context.unwrapResult(this.context.callFunction(this.resolveHandle,this.context.undefined,value||this.context.undefined)).dispose(),this.disposeResolvers(),this.onSettled())};this.reject=value=>{this.rejectHandle.alive&&(this.context.unwrapResult(this.context.callFunction(this.rejectHandle,this.context.undefined,value||this.context.undefined)).dispose(),this.disposeResolvers(),this.onSettled())};this.dispose=()=>{this.handle.alive&&this.handle.dispose(),this.disposeResolvers()};this.context=args.context,this.owner=args.context.runtime,this.handle=args.promiseHandle,this.settled=new Promise(resolve=>{this.onSettled=resolve}),this.resolveHandle=args.resolveHandle,this.rejectHandle=args.rejectHandle}get alive(){return this.handle.alive||this.resolveHandle.alive||this.rejectHandle.alive}disposeResolvers(){this.resolveHandle.alive&&this.resolveHandle.dispose(),this.rejectHandle.alive&&this.rejectHandle.dispose()}};var ModuleMemory=class{constructor(module){this.module=module}toPointerArray(handleArray){let typedArray=new Int32Array(handleArray.map(handle=>handle.value)),numBytes=typedArray.length*typedArray.BYTES_PER_ELEMENT,ptr=this.module._malloc(numBytes);return new Uint8Array(this.module.HEAPU8.buffer,ptr,numBytes).set(new Uint8Array(typedArray.buffer)),new Lifetime(ptr,void 0,ptr2=>this.module._free(ptr2))}newTypedArray(kind,length){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);return typedArray.set(zeros),new Lifetime({typedArray,ptr},void 0,value=>this.module._free(value.ptr))}newMutablePointerArray(length){return this.newTypedArray(Int32Array,length)}newHeapCharPointer(string){let strlen=this.module.lengthBytesUTF8(string),dataBytes=strlen+1,ptr=this.module._malloc(dataBytes);return this.module.stringToUTF8(string,ptr,dataBytes),new Lifetime({ptr,strlen},void 0,value=>this.module._free(value.ptr))}newHeapBufferPointer(buffer){let numBytes=buffer.byteLength,ptr=this.module._malloc(numBytes);return this.module.HEAPU8.set(buffer,ptr),new Lifetime({pointer:ptr,numBytes},void 0,value=>this.module._free(value.pointer))}consumeHeapCharPointer(ptr){let str=this.module.UTF8ToString(ptr);return this.module._free(ptr),str}};import{EvalFlags,GetOwnPropertyNamesFlags,IntrinsicsFlags}from"@componentor/quickjs-ffi-types";var DefaultIntrinsics=Object.freeze({BaseObjects:!0,Date:!0,Eval:!0,StringNormalize:!0,RegExp:!0,JSON:!0,Proxy:!0,MapSet:!0,TypedArrays:!0,Promise:!0});function intrinsicsToFlags(intrinsics){if(!intrinsics)return 0;let result=0;for(let[maybeIntrinsicName,enabled]of Object.entries(intrinsics)){if(!(maybeIntrinsicName in IntrinsicsFlags))throw new QuickJSUnknownIntrinsic(maybeIntrinsicName);enabled&&(result|=IntrinsicsFlags[maybeIntrinsicName])}return result}function evalOptionsToFlags(evalOptions){if(typeof evalOptions=="number")return evalOptions;if(evalOptions===void 0)return 0;let{type,strict,strip,compileOnly,backtraceBarrier}=evalOptions,flags=0;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}function getOwnPropertyNamesOptionsToFlags(options){if(typeof options=="number")return options;if(options===void 0)return 0;let{strings:includeStrings,symbols:includeSymbols,quickjsPrivate:includePrivate,onlyEnumerable,numbers:includeNumbers,numbersAsStrings}=options,flags=0;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}function concat(...values){let result=[];for(let value of values)value!==void 0&&(result=result.concat(value));return result}var QuickJSIterator=class extends UsingDisposable{constructor(handle,context){super();this.handle=handle;this.context=context;this._isDone=!1;this.owner=context.runtime}[Symbol.iterator](){return this}next(value){if(!this.alive||this._isDone)return{done:!0,value:void 0};let nextMethod=this._next??(this._next=this.context.getProp(this.handle,"next"));return this.callIteratorMethod(nextMethod,value)}return(value){if(!this.alive)return{done:!0,value:void 0};let returnMethod=this.context.getProp(this.handle,"return");if(returnMethod===this.context.undefined&&value===void 0)return this.dispose(),{done:!0,value:void 0};let result=this.callIteratorMethod(returnMethod,value);return returnMethod.dispose(),this.dispose(),result}throw(e){if(!this.alive)return{done:!0,value:void 0};let errorHandle=e instanceof Lifetime?e:this.context.newError(e),throwMethod=this.context.getProp(this.handle,"throw"),result=this.callIteratorMethod(throwMethod,e);return errorHandle.alive&&errorHandle.dispose(),throwMethod.dispose(),this.dispose(),result}get alive(){return this.handle.alive}dispose(){this._isDone=!0,this.handle.dispose(),this._next?.dispose()}callIteratorMethod(method,input){let callResult=input?this.context.callFunction(method,this.handle,input):this.context.callFunction(method,this.handle);if(callResult.error)return this.dispose(),{value:callResult};let done=this.context.getProp(callResult.value,"done").consume(v=>this.context.dump(v));if(done)return callResult.value.dispose(),this.dispose(),{done,value:void 0};let value=this.context.getProp(callResult.value,"value");return callResult.value.dispose(),{value:DisposableResult.success(value),done}}};var ContextMemory=class extends ModuleMemory{constructor(args){super(args.module);this.scope=new Scope;this.copyJSValue=ptr=>this.ffi.QTS_DupValuePointer(this.ctx.value,ptr);this.freeJSValue=ptr=>{this.ffi.QTS_FreeValuePointer(this.ctx.value,ptr)};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)}get alive(){return this.scope.alive}dispose(){return this.scope.dispose()}[Symbol.dispose](){return this.dispose()}manage(lifetime){return this.scope.manage(lifetime)}consumeJSCharPointer(ptr){let str=this.module.UTF8ToString(ptr);return this.ffi.QTS_FreeCString(this.ctx.value,ptr),str}heapValueHandle(ptr){return new Lifetime(ptr,this.copyJSValue,this.freeJSValue,this.owner)}staticHeapValueHandle(ptr){return this.manage(this.heapValueHandle(ptr)),new StaticLifetime(ptr,this.owner)}},QuickJSContext=class extends UsingDisposable{constructor(args){super();this._undefined=void 0;this._null=void 0;this._false=void 0;this._true=void 0;this._global=void 0;this._BigInt=void 0;this._Symbol=void 0;this._SymbolIterator=void 0;this._SymbolAsyncIterator=void 0;this.fnNextId=-32768;this.fnMaps=new Map;this.cToHostCallbacks={callFunction:(ctx,this_ptr,argc,argv,fn_id)=>{if(ctx!==this.ctx.value)throw new Error("QuickJSContext instance received C -> JS call with mismatched ctx");let fn=this.getFunction(fn_id);if(!fn)throw new Error(`QuickJSContext had no callback with id ${fn_id}`);return Scope.withScopeMaybeAsync(this,function*(awaited,scope){let thisHandle=scope.manage(new WeakLifetime(this_ptr,this.memory.copyJSValue,this.memory.freeJSValue,this.runtime)),argHandles=new Array(argc);for(let i=0;i<argc;i++){let ptr=this.ffi.QTS_ArgvGetJSValueConstPointer(argv,i);argHandles[i]=scope.manage(new WeakLifetime(ptr,this.memory.copyJSValue,this.memory.freeJSValue,this.runtime))}try{let result=yield*awaited(fn.apply(thisHandle,argHandles));if(result){if("error"in result&&result.error)throw this.runtime.debugLog("throw error",result.error),result.error;let handle=scope.manage(result instanceof Lifetime?result:result.value);return this.ffi.QTS_DupValuePointer(this.ctx.value,handle.value)}return 0}catch(error){return this.errorToHandle(error).consume(errorHandle=>this.ffi.QTS_Throw(this.ctx.value,errorHandle.value))}})}};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))}get alive(){return this.memory.alive}dispose(){this.memory.dispose()}get undefined(){if(this._undefined)return this._undefined;let ptr=this.ffi.QTS_GetUndefined();return this._undefined=new StaticLifetime(ptr)}get null(){if(this._null)return this._null;let ptr=this.ffi.QTS_GetNull();return this._null=new StaticLifetime(ptr)}get true(){if(this._true)return this._true;let ptr=this.ffi.QTS_GetTrue();return this._true=new StaticLifetime(ptr)}get false(){if(this._false)return this._false;let ptr=this.ffi.QTS_GetFalse();return this._false=new StaticLifetime(ptr)}get global(){if(this._global)return this._global;let ptr=this.ffi.QTS_GetGlobalObject(this.ctx.value);return this._global=this.memory.staticHeapValueHandle(ptr),this._global}newNumber(num){return this.memory.heapValueHandle(this.ffi.QTS_NewFloat64(this.ctx.value,num))}newString(str){let ptr=this.memory.newHeapCharPointer(str).consume(charHandle=>this.ffi.QTS_NewString(this.ctx.value,charHandle.value.ptr));return this.memory.heapValueHandle(ptr)}newUniqueSymbol(description){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));return this.memory.heapValueHandle(ptr)}newSymbolFor(key){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));return this.memory.heapValueHandle(ptr)}getWellKnownSymbol(name){return this._Symbol??(this._Symbol=this.memory.manage(this.getProp(this.global,"Symbol"))),this.getProp(this._Symbol,name)}newBigInt(num){if(!this._BigInt){let bigIntHandle2=this.getProp(this.global,"BigInt");this.memory.manage(bigIntHandle2),this._BigInt=new StaticLifetime(bigIntHandle2.value,this.runtime)}let bigIntHandle=this._BigInt,asString=String(num);return this.newString(asString).consume(handle=>this.unwrapResult(this.callFunction(bigIntHandle,this.undefined,handle)))}newObject(prototype){prototype&&this.runtime.assertOwned(prototype);let ptr=prototype?this.ffi.QTS_NewObjectProto(this.ctx.value,prototype.value):this.ffi.QTS_NewObject(this.ctx.value);return this.memory.heapValueHandle(ptr)}newArray(){let ptr=this.ffi.QTS_NewArray(this.ctx.value);return this.memory.heapValueHandle(ptr)}newArrayBuffer(buffer){let array=new Uint8Array(buffer),handle=this.memory.newHeapBufferPointer(array),ptr=this.ffi.QTS_NewArrayBuffer(this.ctx.value,handle.value.pointer,array.length);return this.memory.heapValueHandle(ptr)}newPromise(value){let deferredPromise=Scope.withScope(scope=>{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));return new QuickJSDeferredPromise({context:this,promiseHandle,resolveHandle,rejectHandle})});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}newFunction(name,fn){let fnId=++this.fnNextId;return this.setFunction(fnId,fn),this.memory.heapValueHandle(this.ffi.QTS_NewFunction(this.ctx.value,fnId,name))}newError(error){let errorHandle=this.memory.heapValueHandle(this.ffi.QTS_NewError(this.ctx.value));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}typeof(handle){return this.runtime.assertOwned(handle),this.memory.consumeHeapCharPointer(this.ffi.QTS_Typeof(this.ctx.value,handle.value))}getNumber(handle){return this.runtime.assertOwned(handle),this.ffi.QTS_GetFloat64(this.ctx.value,handle.value)}getString(handle){return this.runtime.assertOwned(handle),this.memory.consumeJSCharPointer(this.ffi.QTS_GetString(this.ctx.value,handle.value))}getSymbol(handle){this.runtime.assertOwned(handle);let key=this.memory.consumeJSCharPointer(this.ffi.QTS_GetSymbolDescriptionOrKey(this.ctx.value,handle.value));return this.ffi.QTS_IsGlobalSymbol(this.ctx.value,handle.value)?Symbol.for(key):Symbol(key)}getBigInt(handle){this.runtime.assertOwned(handle);let asString=this.getString(handle);return BigInt(asString)}getArrayBuffer(handle){this.runtime.assertOwned(handle);let len=this.ffi.QTS_GetArrayBufferLength(this.ctx.value,handle.value),ptr=this.ffi.QTS_GetArrayBuffer(this.ctx.value,handle.value);if(!ptr)throw new Error("Couldn't allocate memory to get ArrayBuffer");return new Lifetime(this.module.HEAPU8.subarray(ptr,ptr+len),void 0,()=>this.module._free(ptr))}getPromiseState(handle){this.runtime.assertOwned(handle);let state=this.ffi.QTS_PromiseState(this.ctx.value,handle.value);if(state<0)return{type:"fulfilled",value:handle,notAPromise:!0};if(state===JSPromiseStateEnum.Pending)return{type:"pending",get error(){return new QuickJSPromisePending("Cannot unwrap a pending promise")}};let ptr=this.ffi.QTS_PromiseResult(this.ctx.value,handle.value),result=this.memory.heapValueHandle(ptr);if(state===JSPromiseStateEnum.Fulfilled)return{type:"fulfilled",value:result};if(state===JSPromiseStateEnum.Rejected)return{type:"rejected",error:result};throw result.dispose(),new Error(`Unknown JSPromiseStateEnum: ${state}`)}resolvePromise(promiseLikeHandle){this.runtime.assertOwned(promiseLikeHandle);let vmResolveResult=Scope.withScope(scope=>{let vmPromise=scope.manage(this.getProp(this.global,"Promise")),vmPromiseResolve=scope.manage(this.getProp(vmPromise,"resolve"));return this.callFunction(vmPromiseResolve,vmPromise,promiseLikeHandle)});return vmResolveResult.error?Promise.resolve(vmResolveResult):new Promise(resolve=>{Scope.withScope(scope=>{let resolveHandle=scope.manage(this.newFunction("resolve",value=>{resolve(this.success(value&&value.dup()))})),rejectHandle=scope.manage(this.newFunction("reject",error=>{resolve(this.fail(error&&error.dup()))})),promiseHandle=scope.manage(vmResolveResult.value),promiseThenHandle=scope.manage(this.getProp(promiseHandle,"then"));this.callFunction(promiseThenHandle,promiseHandle,resolveHandle,rejectHandle).unwrap().dispose()})})}isEqual(a,b,equalityType=IsEqualOp.IsStrictlyEqual){if(a===b)return!0;this.runtime.assertOwned(a),this.runtime.assertOwned(b);let result=this.ffi.QTS_IsEqual(this.ctx.value,a.value,b.value,equalityType);if(result===-1)throw new QuickJSNotImplemented("WASM variant does not expose equality");return!!result}eq(handle,other){return this.isEqual(handle,other,IsEqualOp.IsStrictlyEqual)}sameValue(handle,other){return this.isEqual(handle,other,IsEqualOp.IsSameValue)}sameValueZero(handle,other){return this.isEqual(handle,other,IsEqualOp.IsSameValueZero)}getProp(handle,key){this.runtime.assertOwned(handle);let ptr;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)}getLength(handle){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]}getOwnPropertyNames(handle,options={strings:!0,numbersAsStrings:!0}){this.runtime.assertOwned(handle),handle.value;let flags=getOwnPropertyNamesOptionsToFlags(options);if(flags===0)throw new QuickJSEmptyGetOwnPropertyNames("No options set, will return an empty array");return Scope.withScope(scope=>{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);if(errorPtr)return this.fail(this.memory.heapValueHandle(errorPtr));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));return this.ffi.QTS_FreeVoidPointer(this.ctx.value,ptr),this.success(createDisposableArray(handles))})}getIterator(iterableHandle){let SymbolIterator=this._SymbolIterator??(this._SymbolIterator=this.memory.manage(this.getWellKnownSymbol("iterator")));return Scope.withScope(scope=>{let methodHandle=scope.manage(this.getProp(iterableHandle,SymbolIterator)),iteratorCallResult=this.callFunction(methodHandle,iterableHandle);return iteratorCallResult.error?iteratorCallResult:this.success(new QuickJSIterator(iteratorCallResult.value,this))})}setProp(handle,key,value){this.runtime.assertOwned(handle),this.borrowPropertyKey(key).consume(quickJSKey=>this.ffi.QTS_SetProp(this.ctx.value,handle.value,quickJSKey.value,value.value))}defineProp(handle,key,descriptor){this.runtime.assertOwned(handle),Scope.withScope(scope=>{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;this.ffi.QTS_DefineProp(this.ctx.value,handle.value,quickJSKey.value,value.value,get.value,set.value,configurable,enumerable,hasValue)})}callFunction(func,thisVal,...restArgs){this.runtime.assertOwned(func);let args,firstArg=restArgs[0];firstArg===void 0||Array.isArray(firstArg)?args=firstArg??[]:args=restArgs;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);return errorPtr?(this.ffi.QTS_FreeValuePointer(this.ctx.value,resultPtr),this.fail(this.memory.heapValueHandle(errorPtr))):this.success(this.memory.heapValueHandle(resultPtr))}callMethod(thisHandle,key,args=[]){return this.getProp(thisHandle,key).consume(func=>this.callFunction(func,thisHandle,args))}evalCode(code,filename="eval.js",options){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);return errorPtr?(this.ffi.QTS_FreeValuePointer(this.ctx.value,resultPtr),this.fail(this.memory.heapValueHandle(errorPtr))):this.success(this.memory.heapValueHandle(resultPtr))}throw(error){return this.errorToHandle(error).consume(handle=>this.ffi.QTS_Throw(this.ctx.value,handle.value))}borrowPropertyKey(key){return typeof key=="number"?this.newNumber(key):typeof key=="string"?this.newString(key):new StaticLifetime(key.value,this.runtime)}getMemory(rt){if(rt===this.rt.value)return this.memory;throw new Error("Private API. Cannot get memory from a different runtime")}dump(handle){this.runtime.assertOwned(handle);let type=this.typeof(handle);if(type==="string")return this.getString(handle);if(type==="number")return this.getNumber(handle);if(type==="bigint")return this.getBigInt(handle);if(type==="undefined")return;if(type==="symbol")return this.getSymbol(handle);let asPromiseState=this.getPromiseState(handle);if(asPromiseState.type==="fulfilled"&&!asPromiseState.notAPromise)return handle.dispose(),{type:asPromiseState.type,value:asPromiseState.value.consume(this.dump)};if(asPromiseState.type==="pending")return handle.dispose(),{type:asPromiseState.type};if(asPromiseState.type==="rejected")return handle.dispose(),{type:asPromiseState.type,error:asPromiseState.error.consume(this.dump)};let str=this.memory.consumeJSCharPointer(this.ffi.QTS_Dump(this.ctx.value,handle.value));try{return JSON.parse(str)}catch{return str}}unwrapResult(result){if(result.error){let context="context"in result.error?result.error.context:this,cause=result.error.consume(error=>this.dump(error));if(cause&&typeof cause=="object"&&typeof cause.message=="string"){let{message,name,stack,...rest}=cause,exception=new QuickJSUnwrapError(cause,context);typeof name=="string"&&(exception.name=cause.name),exception.message=message;let hostStack=exception.stack;throw typeof stack=="string"&&(exception.stack=`${name}: ${message}
5
- ${cause.stack}Host: ${hostStack}`),Object.assign(exception,rest),exception}throw new QuickJSUnwrapError(cause)}return result.value}[Symbol.for("nodejs.util.inspect.custom")](){return this.alive?`${this.constructor.name} { ctx: ${this.ctx.value} rt: ${this.rt.value} }`:`${this.constructor.name} { disposed }`}getFunction(fn_id){let map_id=fn_id>>8,fnMap=this.fnMaps.get(map_id);if(fnMap)return fnMap.get(fn_id)}setFunction(fn_id,handle){let map_id=fn_id>>8,fnMap=this.fnMaps.get(map_id);return fnMap||(fnMap=new Map,this.fnMaps.set(map_id,fnMap)),fnMap.set(fn_id,handle)}errorToHandle(error){return error instanceof Lifetime?error:this.newError(error)}encodeBinaryJSON(handle){let ptr=this.ffi.QTS_bjson_encode(this.ctx.value,handle.value);return this.memory.heapValueHandle(ptr)}decodeBinaryJSON(handle){let ptr=this.ffi.QTS_bjson_decode(this.ctx.value,handle.value);return this.memory.heapValueHandle(ptr)}compileCode(code,filename="eval.js",options){return this.evalCode(code,filename,{...options,compileOnly:!0})}evalBytecode(handle){this.runtime.assertOwned(handle);let resultPtr=this.ffi.QTS_EvalFunction(this.ctx.value,handle.value),errorPtr=this.ffi.QTS_ResolveException(this.ctx.value,resultPtr);return errorPtr?(this.ffi.QTS_FreeValuePointer(this.ctx.value,resultPtr),this.fail(this.memory.heapValueHandle(errorPtr))):this.success(this.memory.heapValueHandle(resultPtr))}encodeBytecode(handle){this.runtime.assertOwned(handle);let ptr=this.ffi.QTS_EncodeBytecode(this.ctx.value,handle.value);return this.memory.heapValueHandle(ptr)}decodeBytecode(handle){this.runtime.assertOwned(handle);let ptr=this.ffi.QTS_DecodeBytecode(this.ctx.value,handle.value);return this.memory.heapValueHandle(ptr)}success(value){return DisposableResult.success(value)}fail(error){return DisposableResult.fail(error,error2=>this.unwrapResult(error2))}};var QuickJSRuntime=class extends UsingDisposable{constructor(args){super();this.scope=new Scope;this.contextMap=new Map;this._debugMode=!1;this.cToHostCallbacks={shouldInterrupt:rt=>{if(rt!==this.rt.value)throw new Error("QuickJSContext instance received C -> JS interrupt with mismatched rt");let fn=this.interruptHandler;if(!fn)throw new Error("QuickJSContext had no interrupt handler");return fn(this)?1:0},loadModuleSource:maybeAsyncFn(this,function*(awaited,rt,ctx,moduleName){let moduleLoader=this.moduleLoader;if(!moduleLoader)throw new Error("Runtime has no module loader");if(rt!==this.rt.value)throw new Error("Runtime pointer mismatch");let context=this.contextMap.get(ctx)??this.newContext({contextPointer:ctx});try{let result=yield*awaited(moduleLoader(moduleName,context));if(typeof result=="object"&&"error"in result&&result.error)throw this.debugLog("cToHostLoadModule: loader returned error",result.error),result.error;let moduleSource=typeof result=="string"?result:"value"in result?result.value:result;return this.memory.newHeapCharPointer(moduleSource).value.ptr}catch(error){return this.debugLog("cToHostLoadModule: caught error",error),context.throw(error),0}}),normalizeModule:maybeAsyncFn(this,function*(awaited,rt,ctx,baseModuleName,moduleNameRequest){let moduleNormalizer=this.moduleNormalizer;if(!moduleNormalizer)throw new Error("Runtime has no module normalizer");if(rt!==this.rt.value)throw new Error("Runtime pointer mismatch");let context=this.contextMap.get(ctx)??this.newContext({contextPointer:ctx});try{let result=yield*awaited(moduleNormalizer(baseModuleName,moduleNameRequest,context));if(typeof result=="object"&&"error"in result&&result.error)throw this.debugLog("cToHostNormalizeModule: normalizer returned error",result.error),result.error;let name=typeof result=="string"?result:result.value;return context.getMemory(this.rt.value).newHeapCharPointer(name).value.ptr}catch(error){return this.debugLog("normalizeModule: caught error",error),context.throw(error),0}})};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)}get alive(){return this.scope.alive}dispose(){return this.scope.dispose()}newContext(options={}){let intrinsics=intrinsicsToFlags(options.intrinsics),ctx=new Lifetime(options.contextPointer||this.ffi.QTS_NewContext(this.rt.value,intrinsics),void 0,ctx_ptr=>{this.contextMap.delete(ctx_ptr),this.callbacks.deleteContext(ctx_ptr),this.ffi.QTS_FreeContext(ctx_ptr)}),context=new QuickJSContext({module:this.module,ctx,ffi:this.ffi,rt:this.rt,ownedLifetimes:options.ownedLifetimes,runtime:this,callbacks:this.callbacks});return this.contextMap.set(ctx.value,context),context}setModuleLoader(moduleLoader,moduleNormalizer){this.moduleLoader=moduleLoader,this.moduleNormalizer=moduleNormalizer,this.ffi.QTS_RuntimeEnableModuleLoader(this.rt.value,this.moduleNormalizer?1:0)}removeModuleLoader(){this.moduleLoader=void 0,this.ffi.QTS_RuntimeDisableModuleLoader(this.rt.value)}hasPendingJob(){return!!this.ffi.QTS_IsJobPending(this.rt.value)}setInterruptHandler(cb){let prevInterruptHandler=this.interruptHandler;this.interruptHandler=cb,prevInterruptHandler||this.ffi.QTS_RuntimeEnableInterruptHandler(this.rt.value)}removeInterruptHandler(){this.interruptHandler&&(this.ffi.QTS_RuntimeDisableInterruptHandler(this.rt.value),this.interruptHandler=void 0)}executePendingJobs(maxJobsToExecute=-1){let ctxPtrOut=this.memory.newMutablePointerArray(1),valuePtr=this.ffi.QTS_ExecutePendingJob(this.rt.value,maxJobsToExecute??-1,ctxPtrOut.value.ptr),ctxPtr=ctxPtrOut.value.typedArray[0];if(ctxPtrOut.dispose(),ctxPtr===0)return this.ffi.QTS_FreeValuePointerRuntime(this.rt.value,valuePtr),DisposableResult.success(0);let context=this.contextMap.get(ctxPtr)??this.newContext({contextPointer:ctxPtr}),resultValue=context.getMemory(this.rt.value).heapValueHandle(valuePtr);if(context.typeof(resultValue)==="number"){let executedJobs=context.getNumber(resultValue);return resultValue.dispose(),DisposableResult.success(executedJobs)}else{let error=Object.assign(resultValue,{context});return DisposableResult.fail(error,error2=>context.unwrapResult(error2))}}setMemoryLimit(limitBytes){if(limitBytes<0&&limitBytes!==-1)throw new Error("Cannot set memory limit to negative number. To unset, pass -1");this.ffi.QTS_RuntimeSetMemoryLimit(this.rt.value,limitBytes)}computeMemoryUsage(){let serviceContextMemory=this.getSystemContext().getMemory(this.rt.value);return serviceContextMemory.heapValueHandle(this.ffi.QTS_RuntimeComputeMemoryUsage(this.rt.value,serviceContextMemory.ctx.value))}dumpMemoryUsage(){return this.memory.consumeHeapCharPointer(this.ffi.QTS_RuntimeDumpMemoryUsage(this.rt.value))}setMaxStackSize(stackSize){if(stackSize<0)throw new Error("Cannot set memory limit to negative number. To unset, pass 0.");this.ffi.QTS_RuntimeSetMaxStackSize(this.rt.value,stackSize)}assertOwned(handle){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}`)}setDebugMode(enabled){this._debugMode=enabled,this.ffi.DEBUG&&this.rt.alive&&this.ffi.QTS_SetDebugLogEnabled(this.rt.value,enabled?1:0)}isDebugMode(){return this._debugMode}debugLog(...msg){this._debugMode&&console.log("quickjs-emscripten:",...msg)}[Symbol.for("nodejs.util.inspect.custom")](){return this.alive?`${this.constructor.name} { rt: ${this.rt.value} }`:`${this.constructor.name} { disposed }`}getSystemContext(){return this.context||(this.context=this.scope.manage(this.newContext())),this.context}};var QuickJSEmscriptenModuleCallbacks=class{constructor(args){this.callFunction=args.callFunction,this.shouldInterrupt=args.shouldInterrupt,this.loadModuleSource=args.loadModuleSource,this.normalizeModule=args.normalizeModule}},QuickJSModuleCallbacks=class{constructor(module){this.contextCallbacks=new Map;this.runtimeCallbacks=new Map;this.suspendedCount=0;this.cToHostCallbacks=new QuickJSEmscriptenModuleCallbacks({callFunction:(asyncify,ctx,this_ptr,argc,argv,fn_id)=>this.handleAsyncify(asyncify,()=>{try{let vm=this.contextCallbacks.get(ctx);if(!vm)throw new Error(`QuickJSContext(ctx = ${ctx}) not found for C function call "${fn_id}"`);return vm.callFunction(ctx,this_ptr,argc,argv,fn_id)}catch(error){return console.error("[C to host error: returning null]",error),0}}),shouldInterrupt:(asyncify,rt)=>this.handleAsyncify(asyncify,()=>{try{let vm=this.runtimeCallbacks.get(rt);if(!vm)throw new Error(`QuickJSRuntime(rt = ${rt}) not found for C interrupt`);return vm.shouldInterrupt(rt)}catch(error){return console.error("[C to host interrupt: returning error]",error),1}}),loadModuleSource:(asyncify,rt,ctx,moduleName)=>this.handleAsyncify(asyncify,()=>{try{let runtimeCallbacks=this.runtimeCallbacks.get(rt);if(!runtimeCallbacks)throw new Error(`QuickJSRuntime(rt = ${rt}) not found for C module loader`);let loadModule=runtimeCallbacks.loadModuleSource;if(!loadModule)throw new Error(`QuickJSRuntime(rt = ${rt}) does not support module loading`);return loadModule(rt,ctx,moduleName)}catch(error){return console.error("[C to host module loader error: returning null]",error),0}}),normalizeModule:(asyncify,rt,ctx,moduleBaseName,moduleName)=>this.handleAsyncify(asyncify,()=>{try{let runtimeCallbacks=this.runtimeCallbacks.get(rt);if(!runtimeCallbacks)throw new Error(`QuickJSRuntime(rt = ${rt}) not found for C module loader`);let normalizeModule=runtimeCallbacks.normalizeModule;if(!normalizeModule)throw new Error(`QuickJSRuntime(rt = ${rt}) does not support module loading`);return normalizeModule(rt,ctx,moduleBaseName,moduleName)}catch(error){return console.error("[C to host module loader error: returning null]",error),0}})});this.module=module,this.module.callbacks=this.cToHostCallbacks}setRuntimeCallbacks(rt,callbacks){this.runtimeCallbacks.set(rt,callbacks)}deleteRuntime(rt){this.runtimeCallbacks.delete(rt)}setContextCallbacks(ctx,callbacks){this.contextCallbacks.set(ctx,callbacks)}deleteContext(ctx){this.contextCallbacks.delete(ctx)}handleAsyncify(asyncify,fn){if(asyncify)return asyncify.handleSleep(done=>{try{let result=fn();if(!(result instanceof Promise)){debugLog("asyncify.handleSleep: not suspending:",result),done(result);return}if(this.suspended)throw new QuickJSAsyncifyError(`Already suspended at: ${this.suspended.stack}
6
- Attempted to suspend at:`);this.suspended=new QuickJSAsyncifySuspended(`(${this.suspendedCount++})`),debugLog("asyncify.handleSleep: suspending:",this.suspended),result.then(resolvedResult=>{this.suspended=void 0,debugLog("asyncify.handleSleep: resolved:",resolvedResult),done(resolvedResult)},error=>{debugLog("asyncify.handleSleep: rejected:",error),console.error("QuickJS: cannot handle error in suspended function",error),this.suspended=void 0})}catch(error){throw debugLog("asyncify.handleSleep: error:",error),this.suspended=void 0,error}});let value=fn();if(value instanceof Promise)throw new Error("Promise return value not supported in non-asyncify context.");return value}};function applyBaseRuntimeOptions(runtime,options){options.interruptHandler&&runtime.setInterruptHandler(options.interruptHandler),options.maxStackSizeBytes!==void 0&&runtime.setMaxStackSize(options.maxStackSizeBytes),options.memoryLimitBytes!==void 0&&runtime.setMemoryLimit(options.memoryLimitBytes)}function applyModuleEvalRuntimeOptions(runtime,options){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)}var QuickJSWASMModule=class{constructor(module,ffi){this.module=module,this.ffi=ffi,this.callbacks=new QuickJSModuleCallbacks(module)}newRuntime(options={}){let rt=new Lifetime(this.ffi.QTS_NewRuntime(),void 0,rt_ptr=>{this.callbacks.deleteRuntime(rt_ptr),this.ffi.QTS_FreeRuntime(rt_ptr)}),runtime=new QuickJSRuntime({module:this.module,callbacks:this.callbacks,ffi:this.ffi,rt});return applyBaseRuntimeOptions(runtime,options),options.moduleLoader&&runtime.setModuleLoader(options.moduleLoader),runtime}newContext(options={}){let runtime=this.newRuntime(),context=runtime.newContext({...options,ownedLifetimes:concat(runtime,options.ownedLifetimes)});return runtime.context=context,context}evalCode(code,options={}){return Scope.withScope(scope=>{let vm=scope.manage(this.newContext());applyModuleEvalRuntimeOptions(vm.runtime,options);let result=vm.evalCode(code,"eval.js");if(options.memoryLimitBytes!==void 0&&vm.runtime.setMemoryLimit(-1),result.error)throw vm.dump(scope.manage(result.error));return vm.dump(scope.manage(result.value))})}getWasmMemory(){let memory=this.module.quickjsEmscriptenInit?.(()=>{})?.getWasmMemory?.();if(!memory)throw new Error("Variant does not support getting WebAssembly.Memory");return memory}getFFI(){return this.ffi}};export{setDebugMode,debugLog,QuickJSNotImplemented,QuickJSMemoryLeakDetected,QuickJSEmscriptenModuleError,errors_exports,UsingDisposable,Lifetime,StaticLifetime,WeakLifetime,Scope,createDisposableArray,DisposableSuccess,DisposableFail,DisposableResult,QuickJSDeferredPromise,DefaultIntrinsics,intrinsicsToFlags,evalOptionsToFlags,QuickJSContext,QuickJSRuntime,QuickJSModuleCallbacks,applyBaseRuntimeOptions,applyModuleEvalRuntimeOptions,QuickJSWASMModule};
7
- //# sourceMappingURL=chunk-IBRLVSKW.mjs.map
5
+ ${cause.stack}Host: ${hostStack}`),Object.assign(exception,rest),exception}throw new QuickJSUnwrapError(cause)}return result.value}[Symbol.for("nodejs.util.inspect.custom")](){return this.alive?`${this.constructor.name} { ctx: ${this.ctx.value} rt: ${this.rt.value} }`:`${this.constructor.name} { disposed }`}getFunction(fn_id){let map_id=fn_id>>8,fnMap=this.fnMaps.get(map_id);if(fnMap)return fnMap.get(fn_id)}setFunction(fn_id,handle){let map_id=fn_id>>8,fnMap=this.fnMaps.get(map_id);return fnMap||(fnMap=new Map,this.fnMaps.set(map_id,fnMap)),fnMap.set(fn_id,handle)}errorToHandle(error){return error instanceof Lifetime?error:this.newError(error)}encodeBinaryJSON(handle){let ptr=this.ffi.QTS_bjson_encode(this.ctx.value,handle.value);return this.memory.heapValueHandle(ptr)}decodeBinaryJSON(handle){let ptr=this.ffi.QTS_bjson_decode(this.ctx.value,handle.value);return this.memory.heapValueHandle(ptr)}compileCode(code,filename="eval.js",options){return this.evalCode(code,filename,{...options,compileOnly:!0})}evalBytecode(handle){this.runtime.assertOwned(handle);let resultPtr=this.ffi.QTS_EvalFunction(this.ctx.value,handle.value),errorPtr=this.ffi.QTS_ResolveException(this.ctx.value,resultPtr);return errorPtr?(this.ffi.QTS_FreeValuePointer(this.ctx.value,resultPtr),this.fail(this.memory.heapValueHandle(errorPtr))):this.success(this.memory.heapValueHandle(resultPtr))}encodeBytecode(handle){this.runtime.assertOwned(handle);let ptr=this.ffi.QTS_EncodeBytecode(this.ctx.value,handle.value);return this.memory.heapValueHandle(ptr)}decodeBytecode(handle){this.runtime.assertOwned(handle);let ptr=this.ffi.QTS_DecodeBytecode(this.ctx.value,handle.value);return this.memory.heapValueHandle(ptr)}resolveModule(handle){if(this.runtime.assertOwned(handle),this.ffi.QTS_ResolveModule(this.ctx.value,handle.value)<0){let errorPtr=this.ffi.QTS_GetException(this.ctx.value);return this.fail(this.memory.heapValueHandle(errorPtr))}return this.success(void 0)}success(value){return DisposableResult.success(value)}fail(error){return DisposableResult.fail(error,error2=>this.unwrapResult(error2))}};var QuickJSRuntime=class extends UsingDisposable{constructor(args){super();this.scope=new Scope;this.contextMap=new Map;this._debugMode=!1;this.cToHostCallbacks={shouldInterrupt:rt=>{if(rt!==this.rt.value)throw new Error("QuickJSContext instance received C -> JS interrupt with mismatched rt");let fn=this.interruptHandler;if(!fn)throw new Error("QuickJSContext had no interrupt handler");return fn(this)?1:0},loadModuleSource:maybeAsyncFn(this,function*(awaited,rt,ctx,moduleName){let moduleLoader=this.moduleLoader;if(!moduleLoader)throw new Error("Runtime has no module loader");if(rt!==this.rt.value)throw new Error("Runtime pointer mismatch");let context=this.contextMap.get(ctx)??this.newContext({contextPointer:ctx});try{let result=yield*awaited(moduleLoader(moduleName,context));if(typeof result=="object"&&"error"in result&&result.error)throw this.debugLog("cToHostLoadModule: loader returned error",result.error),result.error;let moduleSource=typeof result=="string"?result:"value"in result?result.value:result;return this.memory.newHeapCharPointer(moduleSource).value.ptr}catch(error){return this.debugLog("cToHostLoadModule: caught error",error),context.throw(error),0}}),normalizeModule:maybeAsyncFn(this,function*(awaited,rt,ctx,baseModuleName,moduleNameRequest){let moduleNormalizer=this.moduleNormalizer;if(!moduleNormalizer)throw new Error("Runtime has no module normalizer");if(rt!==this.rt.value)throw new Error("Runtime pointer mismatch");let context=this.contextMap.get(ctx)??this.newContext({contextPointer:ctx});try{let result=yield*awaited(moduleNormalizer(baseModuleName,moduleNameRequest,context));if(typeof result=="object"&&"error"in result&&result.error)throw this.debugLog("cToHostNormalizeModule: normalizer returned error",result.error),result.error;let name=typeof result=="string"?result:result.value;return context.getMemory(this.rt.value).newHeapCharPointer(name).value.ptr}catch(error){return this.debugLog("normalizeModule: caught error",error),context.throw(error),0}})};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)}get alive(){return this.scope.alive}dispose(){return this.scope.dispose()}newContext(options={}){let intrinsics=intrinsicsToFlags(options.intrinsics),ctx=new Lifetime(options.contextPointer||this.ffi.QTS_NewContext(this.rt.value,intrinsics),void 0,ctx_ptr=>{this.contextMap.delete(ctx_ptr),this.callbacks.deleteContext(ctx_ptr),this.ffi.QTS_FreeContext(ctx_ptr)}),context=new QuickJSContext({module:this.module,ctx,ffi:this.ffi,rt:this.rt,ownedLifetimes:options.ownedLifetimes,runtime:this,callbacks:this.callbacks});return this.contextMap.set(ctx.value,context),context}setModuleLoader(moduleLoader,moduleNormalizer){this.moduleLoader=moduleLoader,this.moduleNormalizer=moduleNormalizer,this.ffi.QTS_RuntimeEnableModuleLoader(this.rt.value,this.moduleNormalizer?1:0)}removeModuleLoader(){this.moduleLoader=void 0,this.ffi.QTS_RuntimeDisableModuleLoader(this.rt.value)}hasPendingJob(){return!!this.ffi.QTS_IsJobPending(this.rt.value)}setInterruptHandler(cb){let prevInterruptHandler=this.interruptHandler;this.interruptHandler=cb,prevInterruptHandler||this.ffi.QTS_RuntimeEnableInterruptHandler(this.rt.value)}removeInterruptHandler(){this.interruptHandler&&(this.ffi.QTS_RuntimeDisableInterruptHandler(this.rt.value),this.interruptHandler=void 0)}executePendingJobs(maxJobsToExecute=-1){let ctxPtrOut=this.memory.newMutablePointerArray(1),valuePtr=this.ffi.QTS_ExecutePendingJob(this.rt.value,maxJobsToExecute??-1,ctxPtrOut.value.ptr),ctxPtr=ctxPtrOut.value.typedArray[0];if(ctxPtrOut.dispose(),ctxPtr===0)return this.ffi.QTS_FreeValuePointerRuntime(this.rt.value,valuePtr),DisposableResult.success(0);let context=this.contextMap.get(ctxPtr)??this.newContext({contextPointer:ctxPtr}),resultValue=context.getMemory(this.rt.value).heapValueHandle(valuePtr);if(context.typeof(resultValue)==="number"){let executedJobs=context.getNumber(resultValue);return resultValue.dispose(),DisposableResult.success(executedJobs)}else{let error=Object.assign(resultValue,{context});return DisposableResult.fail(error,error2=>context.unwrapResult(error2))}}setMemoryLimit(limitBytes){if(limitBytes<0&&limitBytes!==-1)throw new Error("Cannot set memory limit to negative number. To unset, pass -1");this.ffi.QTS_RuntimeSetMemoryLimit(this.rt.value,limitBytes)}computeMemoryUsage(){let serviceContextMemory=this.getSystemContext().getMemory(this.rt.value);return serviceContextMemory.heapValueHandle(this.ffi.QTS_RuntimeComputeMemoryUsage(this.rt.value,serviceContextMemory.ctx.value))}dumpMemoryUsage(){return this.memory.consumeHeapCharPointer(this.ffi.QTS_RuntimeDumpMemoryUsage(this.rt.value))}setMaxStackSize(stackSize){if(stackSize<0)throw new Error("Cannot set memory limit to negative number. To unset, pass 0.");this.ffi.QTS_RuntimeSetMaxStackSize(this.rt.value,stackSize)}assertOwned(handle){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}`)}setDebugMode(enabled){this._debugMode=enabled,this.ffi.DEBUG&&this.rt.alive&&this.ffi.QTS_SetDebugLogEnabled(this.rt.value,enabled?1:0)}isDebugMode(){return this._debugMode}debugLog(...msg){this._debugMode&&console.log("quickjs-emscripten:",...msg)}[Symbol.for("nodejs.util.inspect.custom")](){return this.alive?`${this.constructor.name} { rt: ${this.rt.value} }`:`${this.constructor.name} { disposed }`}getSystemContext(){return this.context||(this.context=this.scope.manage(this.newContext())),this.context}};var QuickJSEmscriptenModuleCallbacks=class{constructor(args){this.callFunction=args.callFunction,this.shouldInterrupt=args.shouldInterrupt,this.loadModuleSource=args.loadModuleSource,this.normalizeModule=args.normalizeModule}},QuickJSModuleCallbacks=class{constructor(module){this.contextCallbacks=new Map;this.runtimeCallbacks=new Map;this.suspendedCount=0;this.cToHostCallbacks=new QuickJSEmscriptenModuleCallbacks({callFunction:(asyncify,ctx,this_ptr,argc,argv,fn_id)=>this.handleAsyncify(asyncify,()=>{try{let vm=this.contextCallbacks.get(ctx);if(!vm)throw new Error(`QuickJSContext(ctx = ${ctx}) not found for C function call "${fn_id}"`);return vm.callFunction(ctx,this_ptr,argc,argv,fn_id)}catch(error){return console.error("[C to host error: returning null]",error),0}}),shouldInterrupt:(asyncify,rt)=>this.handleAsyncify(asyncify,()=>{try{let vm=this.runtimeCallbacks.get(rt);if(!vm)throw new Error(`QuickJSRuntime(rt = ${rt}) not found for C interrupt`);return vm.shouldInterrupt(rt)}catch(error){return console.error("[C to host interrupt: returning error]",error),1}}),loadModuleSource:(asyncify,rt,ctx,moduleName)=>this.handleAsyncify(asyncify,()=>{try{let runtimeCallbacks=this.runtimeCallbacks.get(rt);if(!runtimeCallbacks)throw new Error(`QuickJSRuntime(rt = ${rt}) not found for C module loader`);let loadModule=runtimeCallbacks.loadModuleSource;if(!loadModule)throw new Error(`QuickJSRuntime(rt = ${rt}) does not support module loading`);return loadModule(rt,ctx,moduleName)}catch(error){return console.error("[C to host module loader error: returning null]",error),0}}),normalizeModule:(asyncify,rt,ctx,moduleBaseName,moduleName)=>this.handleAsyncify(asyncify,()=>{try{let runtimeCallbacks=this.runtimeCallbacks.get(rt);if(!runtimeCallbacks)throw new Error(`QuickJSRuntime(rt = ${rt}) not found for C module loader`);let normalizeModule=runtimeCallbacks.normalizeModule;if(!normalizeModule)throw new Error(`QuickJSRuntime(rt = ${rt}) does not support module loading`);return normalizeModule(rt,ctx,moduleBaseName,moduleName)}catch(error){return console.error("[C to host module loader error: returning null]",error),0}})});this.module=module,this.module.callbacks=this.cToHostCallbacks}setRuntimeCallbacks(rt,callbacks){this.runtimeCallbacks.set(rt,callbacks)}deleteRuntime(rt){this.runtimeCallbacks.delete(rt)}setContextCallbacks(ctx,callbacks){this.contextCallbacks.set(ctx,callbacks)}deleteContext(ctx){this.contextCallbacks.delete(ctx)}handleAsyncify(asyncify,fn){if(asyncify)return asyncify.handleSleep(done=>{try{let result=fn();if(!(result instanceof Promise)){debugLog("asyncify.handleSleep: not suspending:",result),done(result);return}if(this.suspended)throw new QuickJSAsyncifyError(`Already suspended at: ${this.suspended.stack}
6
+ Attempted to suspend at:`);this.suspended=new QuickJSAsyncifySuspended(`(${this.suspendedCount++})`),debugLog("asyncify.handleSleep: suspending:",this.suspended),result.then(resolvedResult=>{this.suspended=void 0,debugLog("asyncify.handleSleep: resolved:",resolvedResult),done(resolvedResult)},error=>{debugLog("asyncify.handleSleep: rejected:",error),console.error("QuickJS: cannot handle error in suspended function",error),this.suspended=void 0})}catch(error){throw debugLog("asyncify.handleSleep: error:",error),this.suspended=void 0,error}});let value=fn();if(value instanceof Promise)throw new Error("Promise return value not supported in non-asyncify context.");return value}};function applyBaseRuntimeOptions(runtime,options){options.interruptHandler&&runtime.setInterruptHandler(options.interruptHandler),options.maxStackSizeBytes!==void 0&&runtime.setMaxStackSize(options.maxStackSizeBytes),options.memoryLimitBytes!==void 0&&runtime.setMemoryLimit(options.memoryLimitBytes)}function applyModuleEvalRuntimeOptions(runtime,options){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)}var QuickJSWASMModule=class{constructor(module,ffi){this.module=module,this.ffi=ffi,this.callbacks=new QuickJSModuleCallbacks(module)}getWasmModule(){return this.module}newRuntime(options={}){let rt=new Lifetime(this.ffi.QTS_NewRuntime(),void 0,rt_ptr=>{this.callbacks.deleteRuntime(rt_ptr),this.ffi.QTS_FreeRuntime(rt_ptr)}),runtime=new QuickJSRuntime({module:this.module,callbacks:this.callbacks,ffi:this.ffi,rt});return applyBaseRuntimeOptions(runtime,options),options.moduleLoader&&runtime.setModuleLoader(options.moduleLoader),runtime}newContext(options={}){let runtime=this.newRuntime(),context=runtime.newContext({...options,ownedLifetimes:concat(runtime,options.ownedLifetimes)});return runtime.context=context,context}evalCode(code,options={}){return Scope.withScope(scope=>{let vm=scope.manage(this.newContext());applyModuleEvalRuntimeOptions(vm.runtime,options);let result=vm.evalCode(code,"eval.js");if(options.memoryLimitBytes!==void 0&&vm.runtime.setMemoryLimit(-1),result.error)throw vm.dump(scope.manage(result.error));return vm.dump(scope.manage(result.value))})}getWasmMemory(){let memory=this.module.quickjsEmscriptenInit?.(()=>{})?.getWasmMemory?.();if(!memory)throw new Error("Variant does not support getting WebAssembly.Memory");return memory}getFFI(){return this.ffi}};export{setDebugMode,debugLog,QuickJSNotImplemented,QuickJSMemoryLeakDetected,QuickJSEmscriptenModuleError,errors_exports,UsingDisposable,Lifetime,StaticLifetime,WeakLifetime,Scope,createDisposableArray,DisposableSuccess,DisposableFail,DisposableResult,QuickJSDeferredPromise,DefaultIntrinsics,intrinsicsToFlags,evalOptionsToFlags,QuickJSContext,QuickJSRuntime,QuickJSModuleCallbacks,applyBaseRuntimeOptions,applyModuleEvalRuntimeOptions,QuickJSWASMModule};
7
+ //# sourceMappingURL=chunk-ARBNLGDU.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/debug.ts","../src/errors.ts","../src/asyncify-helpers.ts","../src/lifetime.ts","../src/context.ts","../src/deferred-promise.ts","../src/memory.ts","../src/types.ts","../src/QuickJSIterator.ts","../src/runtime.ts","../src/module.ts"],"sourcesContent":["/**\n * @private\n * Mutable variable. Use {@link setDebugMode} to enable.\n */\nexport let QTS_DEBUG = false\n\n/**\n * Enable (or disable) debug logging and object creation tracking globally.\n * This setting is inherited by newly created QuickJSRuntime instances.\n * To get debug logging in the WebAssembly module, you need to use a debug build variant.\n * See [the quickjs-emscripten-core README](https://github.com/justjake/quickjs-emscripten/tree/main/doc/quickjs-emscripten-core) for more about build variants.\n */\nexport function setDebugMode(enabled: boolean = true) {\n QTS_DEBUG = enabled\n}\n\n/** Get the global debug mode */\nexport function isDebugMode() {\n return QTS_DEBUG\n}\n\n/**\n * @private\n */\nexport function debugLog(...args: any[]) {\n if (QTS_DEBUG) {\n console.log(\"quickjs-emscripten:\", ...args)\n }\n}\n","import type { QuickJSContext } from \"./context\"\n\n/**\n * Error thrown if {@link QuickJSContext#unwrapResult} unwraps an error value that isn't an object.\n */\nexport class QuickJSUnwrapError extends Error {\n name = \"QuickJSUnwrapError\"\n constructor(\n public cause: unknown,\n public context?: QuickJSContext,\n ) {\n const message =\n typeof cause === \"object\" && cause && \"message\" in cause\n ? String(cause.message)\n : String(cause)\n super(message)\n }\n}\n\nexport class QuickJSWrongOwner extends Error {\n name = \"QuickJSWrongOwner\"\n}\n\nexport class QuickJSUseAfterFree extends Error {\n name = \"QuickJSUseAfterFree\"\n}\n\nexport class QuickJSNotImplemented extends Error {\n name = \"QuickJSNotImplemented\"\n}\n\nexport class QuickJSAsyncifyError extends Error {\n name = \"QuickJSAsyncifyError\"\n}\n\nexport class QuickJSAsyncifySuspended extends Error {\n name = \"QuickJSAsyncifySuspended\"\n}\n\nexport class QuickJSMemoryLeakDetected extends Error {\n name = \"QuickJSMemoryLeakDetected\"\n}\n\nexport class QuickJSEmscriptenModuleError extends Error {\n name = \"QuickJSEmscriptenModuleError\"\n}\n\nexport class QuickJSUnknownIntrinsic extends TypeError {\n name = \"QuickJSUnknownIntrinsic\"\n}\n\nexport class QuickJSPromisePending extends Error {\n name = \"QuickJSPromisePending\"\n}\n\nexport class QuickJSEmptyGetOwnPropertyNames extends Error {\n name = \"QuickJSEmptyGetOwnPropertyNames\"\n}\n","function* awaitYield<T>(value: T | Promise<T>) {\n return (yield value) as T\n}\n\nfunction awaitYieldOf<T, Yielded>(\n generator: Generator<Yielded | Promise<Yielded>, T, Yielded>,\n): Generator<T | Promise<T>, T, T> {\n return awaitYield(awaitEachYieldedPromise(generator))\n}\n\nexport type AwaitYield = typeof awaitYield & {\n of: typeof awaitYieldOf\n}\n\nconst AwaitYield: AwaitYield = awaitYield as AwaitYield\nAwaitYield.of = awaitYieldOf\n\n/**\n * Create a function that may or may not be async, using a generator\n *\n * Within the generator, call `yield* awaited(maybePromise)` to await a value\n * that may or may not be a promise.\n *\n * If the inner function never yields a promise, it will return synchronously.\n */\nexport function maybeAsyncFn<\n /** Function arguments */\n Args extends any[],\n This,\n /** Function return type */\n Return,\n /** Yields to unwrap */\n Yielded,\n>(\n that: This,\n fn: (\n this: This,\n awaited: AwaitYield,\n ...args: Args\n ) => Generator<Yielded | Promise<Yielded>, Return, Yielded>,\n): (...args: Args) => Return | Promise<Return> {\n return (...args: Args) => {\n const generator = fn.call(that, AwaitYield, ...args)\n return awaitEachYieldedPromise(generator)\n }\n}\n\n// class Example {\n// private maybeAsyncMethod = maybeAsyncFn(this, function* (awaited, a: number) {\n// yield* awaited(new Promise((resolve) => setTimeout(resolve, a)))\n// return 5\n// })\n// }\n\nexport type MaybeAsyncBlock<Return, This, Yielded, Args extends any[] = []> = (\n this: This,\n awaited: AwaitYield,\n ...args: Args\n) => Generator<Yielded | Promise<Yielded>, Return, Yielded>\n\nexport function maybeAsync<Return, This, Yielded>(\n that: This,\n startGenerator: (\n this: This,\n await: AwaitYield,\n ) => Generator<Yielded | Promise<Yielded>, Return, Yielded>,\n): Return | Promise<Return> {\n const generator = startGenerator.call(that, AwaitYield)\n return awaitEachYieldedPromise(generator)\n}\n\nexport function awaitEachYieldedPromise<Yielded, Returned>(\n gen: Generator<Yielded | Promise<Yielded>, Returned, Yielded>,\n): Returned | Promise<Returned> {\n type NextResult = ReturnType<typeof gen.next>\n\n function handleNextStep(step: NextResult): Returned | Promise<Returned> {\n if (step.done) {\n return step.value\n }\n\n if (step.value instanceof Promise) {\n return step.value.then(\n (value) => handleNextStep(gen.next(value)),\n (error) => handleNextStep(gen.throw(error)),\n )\n }\n\n return handleNextStep(gen.next(step.value))\n }\n\n return handleNextStep(gen.next())\n}\n","import type { SuccessOrFail } from \"./vm-interface\"\nimport type { MaybeAsyncBlock } from \"./asyncify-helpers\"\nimport { maybeAsync } from \"./asyncify-helpers\"\nimport { QTS_DEBUG } from \"./debug\"\nimport { QuickJSUseAfterFree } from \"./errors\"\nimport type { QuickJSHandle } from \"./types\"\n\n/**\n * An object that can be disposed.\n * {@link Lifetime} is the canonical implementation of Disposable.\n * Use {@link Scope} to manage cleaning up multiple disposables.\n */\nexport interface Disposable {\n /**\n * Dispose of the underlying resources used by this object.\n */\n dispose(): void\n\n /**\n * @returns true if the object is alive\n * @returns false after the object has been {@link dispose}d\n */\n alive: boolean\n\n /**\n * A method that is used to release resources held by an object. Called by the semantics of the `using` statement.\n */\n [Symbol.dispose](): void\n}\n\n/**\n * Base abstract class that helps implement {@link Disposable} by providing a default implementation of {@link Symbol.dispose}.\n */\nexport abstract class UsingDisposable implements Disposable {\n /**\n * @returns true if the object is alive\n * @returns false after the object has been {@link dispose}d\n */\n declare abstract readonly alive: boolean\n /**\n * Dispose of the underlying resources used by this object.\n */\n abstract dispose(): void\n /**\n * Just calls the standard .dispose() method of this class.\n */\n [Symbol.dispose]() {\n return this.dispose()\n }\n}\n\n// Polyfill as needed if Symbol.dispose is not available.\n// This polyfill matches ESBuild's behavior.\nconst SymbolDispose = Symbol.dispose ?? Symbol.for(\"Symbol.dispose\")\nconst prototypeAsAny = UsingDisposable.prototype as any\nif (!prototypeAsAny[SymbolDispose]) {\n prototypeAsAny[SymbolDispose] = function () {\n return this.dispose()\n }\n}\n\n/**\n * A lifetime prevents access to a value after the lifetime has been\n * {@link dispose}ed.\n *\n * Typically, quickjs-emscripten uses Lifetimes to protect C memory pointers.\n */\nexport class Lifetime<T, TCopy = never, Owner = never>\n extends UsingDisposable\n implements Disposable\n{\n protected _alive: boolean = true\n protected _constructorStack = QTS_DEBUG ? new Error(\"Lifetime constructed\").stack : undefined\n\n /**\n * When the Lifetime is disposed, it will call `disposer(_value)`. Use the\n * disposer function to implement whatever cleanup needs to happen at the end\n * of `value`'s lifetime.\n *\n * `_owner` is not used or controlled by the lifetime. It's just metadata for\n * the creator.\n */\n constructor(\n protected readonly _value: T,\n protected readonly copier?: (value: T | TCopy) => TCopy,\n protected readonly disposer?: (value: T | TCopy) => void,\n protected readonly _owner?: Owner,\n ) {\n super()\n }\n\n get alive() {\n return this._alive\n }\n\n /**\n * The value this Lifetime protects. You must never retain the value - it\n * may become invalid, leading to memory errors.\n *\n * @throws If the lifetime has been {@link dispose}d already.\n */\n get value() {\n this.assertAlive()\n return this._value\n }\n\n get owner() {\n return this._owner\n }\n\n get dupable() {\n return !!this.copier\n }\n\n /**\n * Create a new handle pointing to the same {@link value}.\n */\n dup() {\n this.assertAlive()\n if (!this.copier) {\n throw new Error(\"Non-dupable lifetime\")\n }\n return new Lifetime<TCopy, TCopy, Owner>(\n this.copier(this._value),\n this.copier,\n this.disposer,\n this._owner,\n )\n }\n\n /**\n * Call `map` with this lifetime, then dispose the lifetime.\n * @return the result of `map(this)`.\n */\n consume<O>(map: (lifetime: this) => O): O\n // A specific type definition is needed for our common use-case\n // https://github.com/microsoft/TypeScript/issues/30271\n consume<O>(map: (lifetime: QuickJSHandle) => O): O\n consume<O>(map: (lifetime: any) => O): O {\n this.assertAlive()\n const result = map(this)\n this.dispose()\n return result\n }\n\n /**\n * Call `map` with this lifetime, returning the result.\n * Does not dispose the lifetime.\n * @return the result of `map(this)`.\n */\n map<O>(map: (lifetime: this) => O): O\n map<O>(map: (lifetime: QuickJSHandle) => O): O\n map<O>(map: (lifetime: any) => O): O {\n this.assertAlive()\n return map(this)\n }\n\n /**\n * Call `fn` with this lifetime, then return `this`. Does not dispose the\n * lifetime. Useful for imperative operations within an expression, like when\n * you're building up objects, or to add logging in the middle of a call chain.\n * @returns this\n */\n tap(fn: (lifetime: this) => void): this\n tap(fn: (lifetime: QuickJSHandle) => void): QuickJSHandle\n tap(fn: (lifetime: any) => void): any {\n fn(this)\n return this\n }\n\n /**\n * Dispose of {@link value} and perform cleanup.\n */\n dispose() {\n this.assertAlive()\n if (this.disposer) {\n this.disposer(this._value)\n }\n this._alive = false\n }\n\n private assertAlive() {\n if (!this.alive) {\n if (this._constructorStack) {\n throw new QuickJSUseAfterFree(\n `Lifetime not alive\\n${this._constructorStack}\\nLifetime used`,\n )\n }\n throw new QuickJSUseAfterFree(\"Lifetime not alive\")\n }\n }\n}\n\n/**\n * A Lifetime that lives forever. Used for constants.\n */\nexport class StaticLifetime<T, Owner = never> extends Lifetime<T, T, Owner> {\n constructor(value: T, owner?: Owner) {\n super(value, undefined, undefined, owner)\n }\n\n // Static lifetime doesn't need a copier to be copiable\n get dupable() {\n return true\n }\n\n // Copy returns the same instance.\n dup() {\n return this\n }\n\n // Dispose does nothing.\n dispose() {}\n}\n\n/**\n * A Lifetime that does not own its `value`. A WeakLifetime never calls its\n * `disposer` function, but can be `dup`ed to produce regular lifetimes that\n * do.\n *\n * Used for function arguments.\n */\nexport class WeakLifetime<T, TCopy = never, Owner = never> extends Lifetime<T, TCopy, Owner> {\n constructor(\n value: T,\n copier?: (value: T | TCopy) => TCopy,\n disposer?: (value: TCopy) => void,\n owner?: Owner,\n ) {\n // We don't care if the disposer doesn't support freeing T\n super(value, copier, disposer as (value: T | TCopy) => void, owner)\n }\n\n dispose() {\n this._alive = false\n }\n}\n\nfunction scopeFinally(scope: Scope, blockError: Error | undefined) {\n // console.log('scopeFinally', scope, blockError)\n let disposeError: Error | undefined\n try {\n scope.dispose()\n } catch (error) {\n disposeError = error as any\n }\n\n if (blockError && disposeError) {\n Object.assign(blockError, {\n message: `${blockError.message}\\n Then, failed to dispose scope: ${disposeError.message}`,\n disposeError,\n })\n throw blockError\n }\n\n if (blockError || disposeError) {\n throw blockError || disposeError\n }\n}\n\n/**\n * Scope helps reduce the burden of manually tracking and disposing of\n * Lifetimes. See {@link withScope}. and {@link withScopeAsync}.\n */\nexport class Scope extends UsingDisposable implements Disposable {\n /**\n * Run `block` with a new Scope instance that will be disposed after the block returns.\n * Inside `block`, call `scope.manage` on each lifetime you create to have the lifetime\n * automatically disposed after the block returns.\n *\n * @warning Do not use with async functions. Instead, use {@link withScopeAsync}.\n */\n static withScope<R>(block: (scope: Scope) => R): R {\n const scope = new Scope()\n let blockError: Error | undefined\n try {\n return block(scope)\n } catch (error) {\n blockError = error as any\n throw error\n } finally {\n scopeFinally(scope, blockError)\n }\n }\n\n static withScopeMaybeAsync<Return, This, Yielded>(\n _this: This,\n block: MaybeAsyncBlock<Return, This, Yielded, [Scope]>,\n ): Return | Promise<Return> {\n return maybeAsync(undefined, function* (awaited) {\n const scope = new Scope()\n let blockError: Error | undefined\n try {\n return yield* awaited.of(block.call(_this, awaited, scope))\n } catch (error) {\n blockError = error as any\n throw error\n } finally {\n scopeFinally(scope, blockError)\n }\n })\n }\n\n /**\n * Run `block` with a new Scope instance that will be disposed after the\n * block's returned promise settles. Inside `block`, call `scope.manage` on each\n * lifetime you create to have the lifetime automatically disposed after the\n * block returns.\n */\n static async withScopeAsync<R>(block: (scope: Scope) => Promise<R>): Promise<R> {\n const scope = new Scope()\n let blockError: Error | undefined\n try {\n return await block(scope)\n } catch (error) {\n blockError = error as any\n throw error\n } finally {\n scopeFinally(scope, blockError)\n }\n }\n\n private _disposables: Lifetime<Set<Disposable>> = new Lifetime(new Set())\n\n /**\n * Track `lifetime` so that it is disposed when this scope is disposed.\n */\n manage = <T extends Disposable>(lifetime: T): T => {\n this._disposables.value.add(lifetime)\n return lifetime\n }\n\n get alive() {\n return this._disposables.alive\n }\n\n dispose() {\n const lifetimes = Array.from(this._disposables.value.values()).reverse()\n for (const lifetime of lifetimes) {\n if (lifetime.alive) {\n lifetime.dispose()\n }\n }\n this._disposables.dispose()\n }\n}\n\n/**\n * An `Array` that also implements {@link Disposable}:\n *\n * - Considered {@link Disposable#alive} if any of its elements are `alive`.\n * - When {@link Disposable#dispose}d, it will dispose of all its elements that are `alive`.\n */\nexport type DisposableArray<T> = T[] & Disposable\n\n/**\n * Create an array that also implements {@link Disposable}.\n */\nexport function createDisposableArray<T extends Disposable>(\n items?: Iterable<T>,\n): DisposableArray<T> {\n const array = items ? Array.from(items) : []\n\n function disposeAlive() {\n return array.forEach((disposable) => (disposable.alive ? disposable.dispose() : undefined))\n }\n\n function someIsAlive() {\n return array.some((disposable) => disposable.alive)\n }\n\n Object.defineProperty(array, SymbolDispose, {\n configurable: true,\n enumerable: false,\n value: disposeAlive,\n })\n\n Object.defineProperty(array, \"dispose\", {\n configurable: true,\n enumerable: false,\n value: disposeAlive,\n })\n\n Object.defineProperty(array, \"alive\", {\n configurable: true,\n enumerable: false,\n get: someIsAlive,\n })\n\n return array as T[] & Disposable\n}\n\nfunction isDisposable(value: unknown): value is { alive: boolean; dispose(): unknown } {\n return Boolean(\n value &&\n (typeof value === \"object\" || typeof value === \"function\") &&\n \"alive\" in value &&\n typeof value.alive === \"boolean\" &&\n \"dispose\" in value &&\n typeof value.dispose === \"function\",\n )\n}\n\nabstract class AbstractDisposableResult extends UsingDisposable implements Disposable {\n static success<S, F>(value: S): DisposableSuccess<S> {\n return new DisposableSuccess(value) satisfies SuccessOrFail<S, F>\n }\n\n static fail<S, F>(error: F, onUnwrap: (status: SuccessOrFail<S, F>) => void): DisposableFail<F> {\n return new DisposableFail(\n error,\n onUnwrap as (status: SuccessOrFail<never, F>) => void,\n ) satisfies SuccessOrFail<S, F>\n }\n\n static is<S, F>(result: SuccessOrFail<S, F>): result is DisposableResult<S, F> {\n return result instanceof AbstractDisposableResult\n }\n\n abstract get alive(): boolean\n abstract dispose(): void\n}\n\nexport class DisposableSuccess<S> extends AbstractDisposableResult {\n declare error?: undefined\n\n constructor(readonly value: S) {\n super()\n }\n\n override get alive() {\n return isDisposable(this.value) ? this.value.alive : true\n }\n\n override dispose(): void {\n if (isDisposable(this.value)) {\n this.value.dispose()\n }\n }\n\n unwrap(): S {\n return this.value\n }\n\n unwrapOr<T>(_fallback: T): S | T {\n return this.value\n }\n}\n\nexport class DisposableFail<F> extends AbstractDisposableResult {\n constructor(\n readonly error: F,\n private readonly onUnwrap: (status: SuccessOrFail<never, F>) => void,\n ) {\n super()\n }\n\n override get alive(): boolean {\n return isDisposable(this.error) ? this.error.alive : true\n }\n\n override dispose(): void {\n if (isDisposable(this.error)) {\n this.error.dispose()\n }\n }\n\n unwrap(): never {\n this.onUnwrap(this)\n throw this.error\n }\n\n unwrapOr<T>(fallback: T): T {\n return fallback\n }\n}\n\nexport type DisposableResult<S, F> = DisposableSuccess<S> | DisposableFail<F>\nexport const DisposableResult = AbstractDisposableResult\n","import { IsEqualOp, JSPromiseStateEnum } from \"@componentor/quickjs-ffi-types\"\nimport type {\n EvalFlags,\n EitherModule,\n EvalDetectModule,\n JSBorrowedCharPointer,\n JSContextPointer,\n JSRuntimePointer,\n JSValueConstPointer,\n JSValuePointer,\n JSValuePointerPointer,\n EitherFFI,\n UInt32Pointer,\n JSValuePointerPointerPointer,\n JSVoidPointer,\n} from \"@componentor/quickjs-ffi-types\"\nimport type { JSPromiseState } from \"./deferred-promise\"\nimport { QuickJSDeferredPromise } from \"./deferred-promise\"\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nimport type { shouldInterruptAfterDeadline } from \"./interrupt-helpers\"\nimport {\n QuickJSEmptyGetOwnPropertyNames,\n QuickJSNotImplemented,\n QuickJSPromisePending,\n QuickJSUnwrapError,\n} from \"./errors\"\nimport type { Disposable, DisposableArray, DisposableFail, DisposableSuccess } from \"./lifetime\"\nimport {\n DisposableResult,\n Lifetime,\n Scope,\n StaticLifetime,\n UsingDisposable,\n WeakLifetime,\n createDisposableArray,\n} from \"./lifetime\"\nimport type { HeapTypedArray } from \"./memory\"\nimport { ModuleMemory } from \"./memory\"\nimport type { ContextCallbacks, QuickJSModuleCallbacks } from \"./module\"\nimport type {\n QuickJSRuntime,\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n ExecutePendingJobsResult,\n} from \"./runtime\"\nimport type {\n ContextEvalOptions,\n GetOwnPropertyNamesOptions,\n JSValue,\n PromiseExecutor,\n QuickJSHandle,\n StaticJSValue,\n} from \"./types\"\nimport { evalOptionsToFlags, getOwnPropertyNamesOptionsToFlags } from \"./types\"\nimport type {\n LowLevelJavascriptVm,\n SuccessOrFail,\n VmFunctionImplementation,\n VmPropertyDescriptor,\n} from \"./vm-interface\"\nimport { QuickJSIterator } from \"./QuickJSIterator\"\n\nexport type QuickJSContextResult<S> = DisposableResult<S, QuickJSHandle>\n\n/**\n * Property key for getting or setting a property on a handle with\n * {@link QuickJSContext#getProp}, {@link QuickJSContext#setProp}, or {@link QuickJSContext#defineProp}.\n */\nexport type QuickJSPropertyKey = number | string | QuickJSHandle\n\n/**\n * @private\n */\nclass ContextMemory extends ModuleMemory implements Disposable {\n readonly owner: QuickJSRuntime\n readonly ctx: Lifetime<JSContextPointer>\n readonly rt: Lifetime<JSRuntimePointer>\n readonly module: EitherModule\n readonly ffi: EitherFFI\n readonly scope = new Scope()\n\n /** @private */\n constructor(args: {\n owner: QuickJSRuntime\n module: EitherModule\n ffi: EitherFFI\n ctx: Lifetime<JSContextPointer>\n rt: Lifetime<JSRuntimePointer>\n ownedLifetimes?: Disposable[]\n }) {\n super(args.module)\n args.ownedLifetimes?.forEach((lifetime) => this.scope.manage(lifetime))\n this.owner = args.owner\n this.module = args.module\n this.ffi = args.ffi\n this.rt = args.rt\n this.ctx = this.scope.manage(args.ctx)\n }\n\n get alive() {\n return this.scope.alive\n }\n\n dispose() {\n return this.scope.dispose()\n }\n\n [Symbol.dispose]() {\n return this.dispose()\n }\n\n /**\n * Track `lifetime` so that it is disposed when this scope is disposed.\n */\n manage<T extends Disposable>(lifetime: T): T {\n return this.scope.manage(lifetime)\n }\n\n copyJSValue = (ptr: JSValuePointer | JSValueConstPointer) => {\n return this.ffi.QTS_DupValuePointer(this.ctx.value, ptr)\n }\n\n freeJSValue = (ptr: JSValuePointer) => {\n this.ffi.QTS_FreeValuePointer(this.ctx.value, ptr)\n }\n\n consumeJSCharPointer(ptr: JSBorrowedCharPointer): string {\n const str = this.module.UTF8ToString(ptr)\n this.ffi.QTS_FreeCString(this.ctx.value, ptr)\n return str\n }\n\n heapValueHandle(ptr: JSValuePointer): JSValue {\n return new Lifetime(ptr, this.copyJSValue, this.freeJSValue, this.owner)\n }\n\n /** Manage a heap pointer with the lifetime of the context */\n staticHeapValueHandle(ptr: JSValuePointer | JSValueConstPointer): StaticJSValue {\n this.manage(this.heapValueHandle(ptr as JSValuePointer))\n // This isn't technically a static lifetime, but since it has the same\n // lifetime as the VM, it's okay to fake one since when the VM is\n // disposed, no other functions will accept the value.\n return new StaticLifetime(ptr as JSValueConstPointer, this.owner) as StaticJSValue\n }\n}\n\n/**\n * QuickJSContext wraps a QuickJS Javascript context (JSContext*) within a\n * runtime. The contexts within the same runtime may exchange objects freely.\n * You can think of separate runtimes like different domains in a browser, and\n * the contexts within a runtime like the different windows open to the same\n * domain. The {@link runtime} references the context's runtime.\n *\n * This class's methods return {@link QuickJSHandle}, which wrap C pointers (JSValue*).\n * It's the caller's responsibility to call `.dispose()` on any\n * handles you create to free memory once you're done with the handle.\n *\n * Use {@link QuickJSRuntime#newContext} or {@link QuickJSWASMModule#newContext}\n * to create a new QuickJSContext.\n *\n * Create QuickJS values inside the interpreter with methods like\n * {@link newNumber}, {@link newString}, {@link newArray}, {@link newObject},\n * {@link newFunction}, and {@link newPromise}.\n *\n * Call {@link setProp} or {@link defineProp} to customize objects. Use those methods\n * with {@link global} to expose the values you create to the interior of the\n * interpreter, so they can be used in {@link evalCode}.\n *\n * Use {@link evalCode} or {@link callFunction} to execute Javascript inside the VM. If\n * you're using asynchronous code inside the QuickJSContext, you may need to also\n * call {@link QuickJSRuntime#executePendingJobs}. Executing code inside the runtime returns a\n * result object representing successful execution or an error. You must dispose\n * of any such results to avoid leaking memory inside the VM.\n *\n * Implement memory and CPU constraints at the runtime level, using {@link runtime}.\n * See {@link QuickJSRuntime} for more information.\n *\n */\n// TODO: Manage own callback registration\nexport class QuickJSContext\n extends UsingDisposable\n implements LowLevelJavascriptVm<QuickJSHandle>, Disposable\n{\n /**\n * The runtime that created this context.\n */\n public readonly runtime: QuickJSRuntime\n\n /** @private */\n protected readonly ctx: Lifetime<JSContextPointer>\n /** @private */\n protected readonly rt: Lifetime<JSRuntimePointer>\n /** @private */\n protected readonly module: EitherModule\n /** @private */\n protected readonly ffi: EitherFFI\n /** @private */\n protected memory: ContextMemory\n\n /** @private */\n protected _undefined: QuickJSHandle | undefined = undefined\n /** @private */\n protected _null: QuickJSHandle | undefined = undefined\n /** @private */\n protected _false: QuickJSHandle | undefined = undefined\n /** @private */\n protected _true: QuickJSHandle | undefined = undefined\n /** @private */\n protected _global: QuickJSHandle | undefined = undefined\n /** @private */\n protected _BigInt: QuickJSHandle | undefined = undefined\n /** @private */\n protected uint32Out: HeapTypedArray<Uint32Array<ArrayBuffer>, UInt32Pointer>\n /** @private */\n protected _Symbol: QuickJSHandle | undefined = undefined\n /** @private */\n protected _SymbolIterator: QuickJSHandle | undefined = undefined\n /** @private */\n protected _SymbolAsyncIterator: QuickJSHandle | undefined = undefined\n\n /**\n * Use {@link QuickJSRuntime#newContext} or {@link QuickJSWASMModule#newContext}\n * to create a new QuickJSContext.\n */\n constructor(args: {\n module: EitherModule\n ffi: EitherFFI\n ctx: Lifetime<JSContextPointer>\n rt: Lifetime<JSRuntimePointer>\n runtime: QuickJSRuntime\n ownedLifetimes?: Disposable[]\n callbacks: QuickJSModuleCallbacks\n }) {\n super()\n this.runtime = args.runtime\n this.module = args.module\n this.ffi = args.ffi\n this.rt = args.rt\n this.ctx = args.ctx\n this.memory = new ContextMemory({\n ...args,\n owner: this.runtime,\n })\n args.callbacks.setContextCallbacks(this.ctx.value, this.cToHostCallbacks)\n this.dump = this.dump.bind(this)\n this.getString = this.getString.bind(this)\n this.getNumber = this.getNumber.bind(this)\n this.resolvePromise = this.resolvePromise.bind(this)\n this.uint32Out = this.memory.manage(\n this.memory.newTypedArray<Uint32Array<ArrayBuffer>, UInt32Pointer>(Uint32Array, 1),\n )\n }\n\n // @implement Disposable ----------------------------------------------------\n\n get alive() {\n return this.memory.alive\n }\n\n /**\n * Dispose of this VM's underlying resources.\n *\n * @throws Calling this method without disposing of all created handles\n * will result in an error.\n */\n dispose() {\n this.memory.dispose()\n }\n\n // Globals ------------------------------------------------------------------\n\n /**\n * [`undefined`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/undefined).\n */\n get undefined(): QuickJSHandle {\n if (this._undefined) {\n return this._undefined\n }\n\n // Undefined is a constant, immutable value in QuickJS.\n const ptr = this.ffi.QTS_GetUndefined()\n return (this._undefined = new StaticLifetime(ptr))\n }\n\n /**\n * [`null`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/null).\n */\n get null(): QuickJSHandle {\n if (this._null) {\n return this._null\n }\n\n // Null is a constant, immutable value in QuickJS.\n const ptr = this.ffi.QTS_GetNull()\n return (this._null = new StaticLifetime(ptr))\n }\n\n /**\n * [`true`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/true).\n */\n get true(): QuickJSHandle {\n if (this._true) {\n return this._true\n }\n\n // True is a constant, immutable value in QuickJS.\n const ptr = this.ffi.QTS_GetTrue()\n return (this._true = new StaticLifetime(ptr))\n }\n\n /**\n * [`false`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/false).\n */\n get false(): QuickJSHandle {\n if (this._false) {\n return this._false\n }\n\n // False is a constant, immutable value in QuickJS.\n const ptr = this.ffi.QTS_GetFalse()\n return (this._false = new StaticLifetime(ptr))\n }\n\n /**\n * [`global`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects).\n * A handle to the global object inside the interpreter.\n * You can set properties to create global variables.\n */\n get global(): QuickJSHandle {\n if (this._global) {\n return this._global\n }\n\n // The global is a JSValue, but since it's lifetime is as long as the VM's,\n // we should manage it.\n const ptr = this.ffi.QTS_GetGlobalObject(this.ctx.value)\n\n // Automatically clean up this reference when we dispose\n this._global = this.memory.staticHeapValueHandle(ptr)\n return this._global\n }\n\n // New values ---------------------------------------------------------------\n\n /**\n * Converts a Javascript number into a QuickJS value.\n */\n newNumber(num: number): QuickJSHandle {\n return this.memory.heapValueHandle(this.ffi.QTS_NewFloat64(this.ctx.value, num))\n }\n\n /**\n * Create a QuickJS [string](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String) value.\n */\n newString(str: string): QuickJSHandle {\n const ptr = this.memory\n .newHeapCharPointer(str)\n .consume((charHandle) => this.ffi.QTS_NewString(this.ctx.value, charHandle.value.ptr))\n return this.memory.heapValueHandle(ptr)\n }\n\n /**\n * Create a QuickJS [symbol](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol) value.\n * No two symbols created with this function will be the same value.\n */\n newUniqueSymbol(description: string | symbol): QuickJSHandle {\n const key = (typeof description === \"symbol\" ? description.description : description) ?? \"\"\n const ptr = this.memory\n .newHeapCharPointer(key)\n .consume((charHandle) => this.ffi.QTS_NewSymbol(this.ctx.value, charHandle.value.ptr, 0))\n return this.memory.heapValueHandle(ptr)\n }\n\n /**\n * Get a symbol from the [global registry](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol#shared_symbols_in_the_global_symbol_registry) for the given key.\n * All symbols created with the same key will be the same value.\n */\n newSymbolFor(key: string | symbol): QuickJSHandle {\n const description = (typeof key === \"symbol\" ? key.description : key) ?? \"\"\n const ptr = this.memory\n .newHeapCharPointer(description)\n .consume((charHandle) => this.ffi.QTS_NewSymbol(this.ctx.value, charHandle.value.ptr, 1))\n return this.memory.heapValueHandle(ptr)\n }\n\n /**\n * Access a well-known symbol that is a property of the global Symbol object, like `Symbol.iterator`.\n */\n getWellKnownSymbol(name: string): QuickJSHandle {\n this._Symbol ??= this.memory.manage(this.getProp(this.global, \"Symbol\"))\n return this.getProp(this._Symbol, name)\n }\n\n /**\n * Create a QuickJS [bigint](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt) value.\n */\n newBigInt(num: bigint): QuickJSHandle {\n if (!this._BigInt) {\n const bigIntHandle = this.getProp(this.global, \"BigInt\")\n this.memory.manage(bigIntHandle)\n this._BigInt = new StaticLifetime(bigIntHandle.value as JSValueConstPointer, this.runtime)\n }\n\n const bigIntHandle = this._BigInt\n const asString = String(num)\n return this.newString(asString).consume((handle) =>\n this.unwrapResult(this.callFunction(bigIntHandle, this.undefined, handle)),\n )\n }\n\n /**\n * `{}`.\n * Create a new QuickJS [object](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer).\n *\n * @param prototype - Like [`Object.create`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/create).\n */\n newObject(prototype?: QuickJSHandle): QuickJSHandle {\n if (prototype) {\n this.runtime.assertOwned(prototype)\n }\n const ptr = prototype\n ? this.ffi.QTS_NewObjectProto(this.ctx.value, prototype.value)\n : this.ffi.QTS_NewObject(this.ctx.value)\n return this.memory.heapValueHandle(ptr)\n }\n\n /**\n * `[]`.\n * Create a new QuickJS [array](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array).\n */\n newArray(): QuickJSHandle {\n const ptr = this.ffi.QTS_NewArray(this.ctx.value)\n return this.memory.heapValueHandle(ptr)\n }\n\n /**\n * Create a new QuickJS [ArrayBuffer](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer).\n */\n newArrayBuffer(buffer: ArrayBufferLike): QuickJSHandle {\n const array = new Uint8Array(buffer)\n const handle = this.memory.newHeapBufferPointer(array)\n const ptr = this.ffi.QTS_NewArrayBuffer(this.ctx.value, handle.value.pointer, array.length)\n return this.memory.heapValueHandle(ptr)\n }\n\n /**\n * Create a new {@link QuickJSDeferredPromise}. Use `deferred.resolve(handle)` and\n * `deferred.reject(handle)` to fulfill the promise handle available at `deferred.handle`.\n * Note that you are responsible for calling `deferred.dispose()` to free the underlying\n * resources; see the documentation on {@link QuickJSDeferredPromise} for details.\n */\n newPromise(): QuickJSDeferredPromise\n /**\n * Create a new {@link QuickJSDeferredPromise} that resolves when the\n * given native Promise<QuickJSHandle> resolves. Rejections will be coerced\n * to a QuickJS error.\n *\n * You can still resolve/reject the created promise \"early\" using its methods.\n */\n newPromise(promise: Promise<QuickJSHandle>): QuickJSDeferredPromise\n /**\n * Construct a new native Promise<QuickJSHandle>, and then convert it into a\n * {@link QuickJSDeferredPromise}.\n *\n * You can still resolve/reject the created promise \"early\" using its methods.\n */\n newPromise(\n newPromiseFn: PromiseExecutor<QuickJSHandle, Error | QuickJSHandle>,\n ): QuickJSDeferredPromise\n newPromise(\n value?: PromiseExecutor<QuickJSHandle, Error | QuickJSHandle> | Promise<QuickJSHandle>,\n ): QuickJSDeferredPromise {\n const deferredPromise = Scope.withScope((scope) => {\n const mutablePointerArray = scope.manage(\n this.memory.newMutablePointerArray<JSValuePointerPointer>(2),\n )\n const promisePtr = this.ffi.QTS_NewPromiseCapability(\n this.ctx.value,\n mutablePointerArray.value.ptr,\n )\n const promiseHandle = this.memory.heapValueHandle(promisePtr)\n const [resolveHandle, rejectHandle] = Array.from(mutablePointerArray.value.typedArray).map(\n (jsvaluePtr) => this.memory.heapValueHandle(jsvaluePtr as any),\n )\n return new QuickJSDeferredPromise({\n context: this,\n promiseHandle,\n resolveHandle,\n rejectHandle,\n })\n })\n\n if (value && typeof value === \"function\") {\n value = new Promise(value)\n }\n\n if (value) {\n Promise.resolve(value).then(deferredPromise.resolve, (error) =>\n error instanceof Lifetime\n ? deferredPromise.reject(error)\n : this.newError(error).consume(deferredPromise.reject),\n )\n }\n\n return deferredPromise\n }\n\n /**\n * Convert a Javascript function into a QuickJS function value.\n * See {@link VmFunctionImplementation} for more details.\n *\n * A {@link VmFunctionImplementation} should not free its arguments or its return\n * value. A VmFunctionImplementation should also not retain any references to\n * its return value.\n *\n * The function argument handles are automatically disposed when the function\n * returns. If you want to retain a handle beyond the end of the function, you\n * can call {@link Lifetime#dup} to create a copy of the handle that you own\n * and must dispose manually. For example, you need to use this API and do some\n * extra book keeping to implement `setInterval`:\n *\n * ```typescript\n * // This won't work because `callbackHandle` expires when the function returns,\n * // so when the interval fires, the callback handle is already disposed.\n * const WRONG_setIntervalHandle = context.newFunction(\"setInterval\", (callbackHandle, delayHandle) => {\n * const delayMs = context.getNumber(delayHandle)\n * const intervalId = globalThis.setInterval(() => {\n * // ERROR: callbackHandle is already disposed here.\n * context.callFunction(callbackHandle)\n * }, intervalId)\n * return context.newNumber(intervalId)\n * })\n *\n * // This works since we dup the callbackHandle.\n * // We just need to make sure we clean it up manually when the interval is cleared --\n * // so we need to keep track of those interval IDs, and make sure we clean all\n * // of them up when we dispose the owning context.\n *\n * const setIntervalHandle = context.newFunction(\"setInterval\", (callbackHandle, delayHandle) => {\n * // Ensure the guest can't overload us by scheduling too many intervals.\n * if (QuickJSInterval.INTERVALS.size > 100) {\n * throw new Error(`Too many intervals scheduled already`)\n * }\n *\n * const delayMs = context.getNumber(delayHandle)\n * const longLivedCallbackHandle = callbackHandle.dup()\n * const intervalId = globalThis.setInterval(() => {\n * context.callFunction(longLivedCallbackHandle)\n * }, intervalId)\n * const disposable = new QuickJSInterval(longLivedCallbackHandle, context, intervalId)\n * QuickJSInterval.INTERVALS.set(intervalId, disposable)\n * return context.newNumber(intervalId)\n * })\n *\n * const clearIntervalHandle = context.newFunction(\"clearInterval\", (intervalIdHandle) => {\n * const intervalId = context.getNumber(intervalIdHandle)\n * const disposable = QuickJSInterval.INTERVALS.get(intervalId)\n * disposable?.dispose()\n * })\n *\n * class QuickJSInterval extends UsingDisposable {\n * static INTERVALS = new Map<number, QuickJSInterval>()\n *\n * static disposeContext(context: QuickJSContext) {\n * for (const interval of QuickJSInterval.INTERVALS.values()) {\n * if (interval.context === context) {\n * interval.dispose()\n * }\n * }\n * }\n *\n * constructor(\n * public fnHandle: QuickJSHandle,\n * public context: QuickJSContext,\n * public intervalId: number,\n * ) {\n * super()\n * }\n *\n * dispose() {\n * globalThis.clearInterval(this.intervalId)\n * this.fnHandle.dispose()\n * QuickJSInterval.INTERVALS.delete(this.fnHandle.value)\n * }\n *\n * get alive() {\n * return this.fnHandle.alive\n * }\n * }\n * ```\n *\n * To implement an async function, create a promise with {@link newPromise}, then\n * return the deferred promise handle from `deferred.handle` from your\n * function implementation:\n *\n * ```typescript\n * const deferred = vm.newPromise()\n * someNativeAsyncFunction().then(deferred.resolve)\n * return deferred.handle\n * ```\n */\n newFunction(name: string, fn: VmFunctionImplementation<QuickJSHandle>): QuickJSHandle {\n const fnId = ++this.fnNextId\n this.setFunction(fnId, fn)\n return this.memory.heapValueHandle(this.ffi.QTS_NewFunction(this.ctx.value, fnId, name))\n }\n\n newError(error: { name: string; message: string }): QuickJSHandle\n newError(message: string): QuickJSHandle\n newError(): QuickJSHandle\n newError(error?: string | { name: string; message: string }): QuickJSHandle {\n const errorHandle = this.memory.heapValueHandle(this.ffi.QTS_NewError(this.ctx.value))\n\n if (error && typeof error === \"object\") {\n if (error.name !== undefined) {\n this.newString(error.name).consume((handle) => this.setProp(errorHandle, \"name\", handle))\n }\n\n if (error.message !== undefined) {\n this.newString(error.message).consume((handle) =>\n this.setProp(errorHandle, \"message\", handle),\n )\n }\n } else if (typeof error === \"string\") {\n this.newString(error).consume((handle) => this.setProp(errorHandle, \"message\", handle))\n } else if (error !== undefined) {\n // This isn't supported in the type signature but maybe it will make life easier.\n this.newString(String(error)).consume((handle) =>\n this.setProp(errorHandle, \"message\", handle),\n )\n }\n\n return errorHandle\n }\n\n // Read values --------------------------------------------------------------\n\n /**\n * `typeof` operator. **Not** [standards compliant](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/typeof).\n *\n * @remarks\n * Does not support BigInt values correctly.\n */\n typeof(handle: QuickJSHandle) {\n this.runtime.assertOwned(handle)\n return this.memory.consumeHeapCharPointer(this.ffi.QTS_Typeof(this.ctx.value, handle.value))\n }\n\n /**\n * Converts `handle` into a Javascript number.\n * @returns `NaN` on error, otherwise a `number`.\n */\n getNumber(handle: QuickJSHandle): number {\n this.runtime.assertOwned(handle)\n return this.ffi.QTS_GetFloat64(this.ctx.value, handle.value)\n }\n\n /**\n * Converts `handle` to a Javascript string.\n */\n getString(handle: QuickJSHandle): string {\n this.runtime.assertOwned(handle)\n return this.memory.consumeJSCharPointer(this.ffi.QTS_GetString(this.ctx.value, handle.value))\n }\n\n /**\n * Converts `handle` into a Javascript symbol. If the symbol is in the global\n * registry in the guest, it will be created with Symbol.for on the host.\n */\n getSymbol(handle: QuickJSHandle): symbol {\n this.runtime.assertOwned(handle)\n const key = this.memory.consumeJSCharPointer(\n this.ffi.QTS_GetSymbolDescriptionOrKey(this.ctx.value, handle.value),\n )\n const isGlobal = this.ffi.QTS_IsGlobalSymbol(this.ctx.value, handle.value)\n return isGlobal ? Symbol.for(key) : Symbol(key)\n }\n\n /**\n * Converts `handle` to a Javascript bigint.\n */\n getBigInt(handle: QuickJSHandle): bigint {\n this.runtime.assertOwned(handle)\n const asString = this.getString(handle)\n return BigInt(asString)\n }\n\n /**\n * Coverts `handle` to a JavaScript ArrayBuffer\n */\n getArrayBuffer(handle: QuickJSHandle): Lifetime<Uint8Array> {\n this.runtime.assertOwned(handle)\n const len = this.ffi.QTS_GetArrayBufferLength(this.ctx.value, handle.value)\n const ptr = this.ffi.QTS_GetArrayBuffer(this.ctx.value, handle.value)\n if (!ptr) {\n throw new Error(\"Couldn't allocate memory to get ArrayBuffer\")\n }\n return new Lifetime(this.module.HEAPU8.subarray(ptr, ptr + len), undefined, () =>\n this.module._free(ptr),\n )\n }\n\n /**\n * Get the current state of a QuickJS promise, see {@link JSPromiseState} for the possible states.\n * This can be used to expect a promise to be fulfilled when combined with {@link unwrapResult}:\n *\n * ```typescript\n * const promiseHandle = context.evalCode(`Promise.resolve(42)`);\n * const resultHandle = context.unwrapResult(\n * context.getPromiseState(promiseHandle)\n * );\n * context.getNumber(resultHandle) === 42; // true\n * resultHandle.dispose();\n * ```\n */\n getPromiseState(handle: QuickJSHandle): JSPromiseState {\n this.runtime.assertOwned(handle)\n const state = this.ffi.QTS_PromiseState(this.ctx.value, handle.value)\n if (state < 0) {\n // Not a promise, but act like `await` would with non-promise, and just return the value.\n return { type: \"fulfilled\", value: handle, notAPromise: true }\n }\n\n if (state === JSPromiseStateEnum.Pending) {\n return {\n type: \"pending\",\n get error() {\n return new QuickJSPromisePending(`Cannot unwrap a pending promise`)\n },\n }\n }\n\n const ptr = this.ffi.QTS_PromiseResult(this.ctx.value, handle.value)\n const result = this.memory.heapValueHandle(ptr)\n if (state === JSPromiseStateEnum.Fulfilled) {\n return { type: \"fulfilled\", value: result }\n }\n if (state === JSPromiseStateEnum.Rejected) {\n return { type: \"rejected\", error: result }\n }\n result.dispose()\n throw new Error(`Unknown JSPromiseStateEnum: ${state}`)\n }\n\n /**\n * `Promise.resolve(value)`.\n * Convert a handle containing a Promise-like value inside the VM into an\n * actual promise on the host.\n *\n * @remarks\n * You may need to call {@link runtime}.{@link QuickJSRuntime#executePendingJobs} to ensure that the promise is resolved.\n *\n * @param promiseLikeHandle - A handle to a Promise-like value with a `.then(onSuccess, onError)` method.\n */\n resolvePromise(promiseLikeHandle: QuickJSHandle): Promise<QuickJSContextResult<QuickJSHandle>> {\n this.runtime.assertOwned(promiseLikeHandle)\n const vmResolveResult = Scope.withScope((scope) => {\n const vmPromise = scope.manage(this.getProp(this.global, \"Promise\"))\n const vmPromiseResolve = scope.manage(this.getProp(vmPromise, \"resolve\"))\n return this.callFunction(vmPromiseResolve, vmPromise, promiseLikeHandle)\n })\n if (vmResolveResult.error) {\n return Promise.resolve(vmResolveResult)\n }\n\n return new Promise<QuickJSContextResult<QuickJSHandle>>((resolve) => {\n Scope.withScope((scope) => {\n const resolveHandle = scope.manage(\n this.newFunction(\"resolve\", (value) => {\n resolve(this.success(value && value.dup()))\n }),\n )\n\n const rejectHandle = scope.manage(\n this.newFunction(\"reject\", (error) => {\n resolve(this.fail(error && error.dup()))\n }),\n )\n\n const promiseHandle = scope.manage(vmResolveResult.value)\n const promiseThenHandle = scope.manage(this.getProp(promiseHandle, \"then\"))\n this.callFunction(promiseThenHandle, promiseHandle, resolveHandle, rejectHandle)\n .unwrap()\n .dispose()\n })\n })\n }\n\n // Compare -----------------------------------------------------------\n\n private isEqual(\n a: QuickJSHandle,\n b: QuickJSHandle,\n equalityType: IsEqualOp = IsEqualOp.IsStrictlyEqual,\n ): boolean {\n if (a === b) {\n return true\n }\n this.runtime.assertOwned(a)\n this.runtime.assertOwned(b)\n const result = this.ffi.QTS_IsEqual(this.ctx.value, a.value, b.value, equalityType)\n if (result === -1) {\n throw new QuickJSNotImplemented(\"WASM variant does not expose equality\")\n }\n return Boolean(result)\n }\n\n /**\n * `handle === other` - IsStrictlyEqual.\n * See [Equality comparisons and sameness](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Equality_comparisons_and_sameness).\n */\n eq(handle: QuickJSHandle, other: QuickJSHandle): boolean {\n return this.isEqual(handle, other, IsEqualOp.IsStrictlyEqual)\n }\n\n /**\n * `Object.is(a, b)`\n * See [Equality comparisons and sameness](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Equality_comparisons_and_sameness).\n */\n sameValue(handle: QuickJSHandle, other: QuickJSHandle): boolean {\n return this.isEqual(handle, other, IsEqualOp.IsSameValue)\n }\n\n /**\n * SameValueZero comparison.\n * See [Equality comparisons and sameness](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Equality_comparisons_and_sameness).\n */\n sameValueZero(handle: QuickJSHandle, other: QuickJSHandle): boolean {\n return this.isEqual(handle, other, IsEqualOp.IsSameValueZero)\n }\n\n // Properties ---------------------------------------------------------------\n\n /**\n * `handle[key]`.\n * Get a property from a JSValue.\n *\n * @param key - The property may be specified as a JSValue handle, or as a\n * Javascript string (which will be converted automatically).\n */\n getProp(handle: QuickJSHandle, key: QuickJSPropertyKey): QuickJSHandle {\n this.runtime.assertOwned(handle)\n let ptr: JSValuePointer\n if (typeof key === \"number\" && key >= 0) {\n // Index access fast path\n ptr = this.ffi.QTS_GetPropNumber(this.ctx.value, handle.value, key)\n } else {\n ptr = this.borrowPropertyKey(key).consume((quickJSKey) =>\n this.ffi.QTS_GetProp(this.ctx.value, handle.value, quickJSKey.value),\n )\n }\n const result = this.memory.heapValueHandle(ptr)\n\n return result\n }\n\n /**\n * `handle.length` as a host number.\n *\n * Example use:\n * ```typescript\n * const length = context.getLength(arrayHandle) ?? 0\n * for (let i = 0; i < length; i++) {\n * using value = context.getProp(arrayHandle, i)\n * console.log(`array[${i}] =`, context.dump(value))\n * }\n * ```\n *\n * @returns a number if the handle has a numeric length property, otherwise `undefined`.\n */\n getLength(handle: QuickJSHandle): number | undefined {\n this.runtime.assertOwned(handle)\n const status = this.ffi.QTS_GetLength(this.ctx.value, this.uint32Out.value.ptr, handle.value)\n if (status < 0) {\n return undefined\n }\n return this.uint32Out.value.typedArray[0]\n }\n\n /**\n * `Object.getOwnPropertyNames(handle)`.\n * Similar to the [standard semantics](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/getOwnPropertyNames),\n * but with extra, non-standard options for:\n *\n * - fetching array indexes as numbers (`numbers: true`)\n * - including symbols (`symbols: true`)\n * - only iterating over enumerable properties (`onlyEnumerable: true`)\n *\n * The default behavior is to emulate the standard:\n * ```typescript\n * context.getOwnPropertyNames(handle, { strings: true, numbersAsStrings: true })\n * ```\n *\n * Note when passing an explicit options object, you must set at least one\n * option, and `strings` are not included unless specified.\n *\n * Example use:\n * ```typescript\n * for (using prop of context.getOwnPropertyNames(objectHandle).unwrap()) {\n * using value = context.getProp(handle, prop)\n * console.log(context.dump(prop), '->', context.dump(value))\n * }\n * ```\n *\n * @returns an an array of handles of the property names. The array itself is disposable for your convenience.\n * @throws QuickJSEmptyGetOwnPropertyNames if no options are set.\n */\n getOwnPropertyNames(\n handle: QuickJSHandle,\n options: GetOwnPropertyNamesOptions = {\n strings: true,\n numbersAsStrings: true,\n },\n ): QuickJSContextResult<DisposableArray<QuickJSHandle>> {\n this.runtime.assertOwned(handle)\n handle.value // assert alive\n const flags = getOwnPropertyNamesOptionsToFlags(options)\n if (flags === 0) {\n throw new QuickJSEmptyGetOwnPropertyNames(\"No options set, will return an empty array\")\n }\n return Scope.withScope((scope) => {\n const outPtr = scope.manage(\n this.memory.newMutablePointerArray<JSValuePointerPointerPointer>(1),\n )\n const errorPtr = this.ffi.QTS_GetOwnPropertyNames(\n this.ctx.value,\n outPtr.value.ptr,\n this.uint32Out.value.ptr,\n handle.value,\n flags,\n )\n if (errorPtr) {\n return this.fail(this.memory.heapValueHandle(errorPtr))\n }\n const len = this.uint32Out.value.typedArray[0]\n const ptr = outPtr.value.typedArray[0]\n const pointerArray = new Uint32Array(this.module.HEAP8.buffer, ptr, len)\n const handles = Array.from(pointerArray).map((ptr) =>\n this.memory.heapValueHandle(ptr as JSValuePointer),\n )\n this.ffi.QTS_FreeVoidPointer(this.ctx.value, ptr as JSVoidPointer)\n return this.success(createDisposableArray(handles))\n })\n }\n\n /**\n * `handle[Symbol.iterator]()`. See {@link QuickJSIterator}.\n * Returns a host iterator that wraps and proxies calls to a guest iterator handle.\n * Each step of the iteration returns a result, either an error or a handle to the next value.\n * Once the iterator is done, the handle is automatically disposed, and the iterator\n * is considered done if the handle is disposed.\n *\n * ```typescript\n * for (using entriesHandle of context.getIterator(mapHandle).unwrap()) {\n * using keyHandle = context.getProp(entriesHandle, 0)\n * using valueHandle = context.getProp(entriesHandle, 1)\n * console.log(context.dump(keyHandle), '->', context.dump(valueHandle))\n * }\n * ```\n */\n getIterator(iterableHandle: QuickJSHandle): QuickJSContextResult<QuickJSIterator> {\n const SymbolIterator = (this._SymbolIterator ??= this.memory.manage(\n this.getWellKnownSymbol(\"iterator\"),\n ))\n return Scope.withScope((scope) => {\n const methodHandle = scope.manage(this.getProp(iterableHandle, SymbolIterator))\n const iteratorCallResult = this.callFunction(methodHandle, iterableHandle)\n if (iteratorCallResult.error) {\n return iteratorCallResult\n }\n return this.success(new QuickJSIterator(iteratorCallResult.value, this))\n })\n }\n\n /**\n * `handle[key] = value`.\n * Set a property on a JSValue.\n *\n * @remarks\n * Note that the QuickJS authors recommend using {@link defineProp} to define new\n * properties.\n *\n * @param key - The property may be specified as a JSValue handle, or as a\n * Javascript string or number (which will be converted automatically to a JSValue).\n */\n setProp(handle: QuickJSHandle, key: QuickJSPropertyKey, value: QuickJSHandle) {\n this.runtime.assertOwned(handle)\n // free newly allocated value if key was a string or number. No-op if string was already\n // a QuickJS handle.\n this.borrowPropertyKey(key).consume((quickJSKey) =>\n this.ffi.QTS_SetProp(this.ctx.value, handle.value, quickJSKey.value, value.value),\n )\n }\n\n /**\n * [`Object.defineProperty(handle, key, descriptor)`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty).\n *\n * @param key - The property may be specified as a JSValue handle, or as a\n * Javascript string or number (which will be converted automatically to a JSValue).\n */\n defineProp(\n handle: QuickJSHandle,\n key: QuickJSPropertyKey,\n descriptor: VmPropertyDescriptor<QuickJSHandle>,\n ): void {\n this.runtime.assertOwned(handle)\n Scope.withScope((scope) => {\n const quickJSKey = scope.manage(this.borrowPropertyKey(key))\n\n const value = descriptor.value || this.undefined\n const configurable = Boolean(descriptor.configurable)\n const enumerable = Boolean(descriptor.enumerable)\n const hasValue = Boolean(descriptor.value)\n const get = descriptor.get\n ? scope.manage(this.newFunction(descriptor.get.name, descriptor.get))\n : this.undefined\n const set = descriptor.set\n ? scope.manage(this.newFunction(descriptor.set.name, descriptor.set))\n : this.undefined\n\n this.ffi.QTS_DefineProp(\n this.ctx.value,\n handle.value,\n quickJSKey.value,\n value.value,\n get.value,\n set.value,\n configurable,\n enumerable,\n hasValue,\n )\n })\n }\n\n // Evaluation ---------------------------------------------------------------\n\n /**\n * [`func.call(thisVal, ...args)`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/call) or\n * [`func.apply(thisVal, args)`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/apply).\n * Call a JSValue as a function.\n *\n * See {@link unwrapResult}, which will throw if the function returned an error, or\n * return the result handle directly. If evaluation returned a handle containing\n * a promise, use {@link resolvePromise} to convert it to a native promise and\n * {@link runtime}.{@link QuickJSRuntime#executePendingJobs} to finish evaluating the promise.\n *\n * @returns A result. If the function threw synchronously, `result.error` be a\n * handle to the exception. Otherwise `result.value` will be a handle to the\n * value.\n *\n * Example:\n *\n * ```typescript\n * using parseIntHandle = context.getProp(global, \"parseInt\")\n * using stringHandle = context.newString(\"42\")\n * using resultHandle = context.callFunction(parseIntHandle, context.undefined, stringHandle).unwrap()\n * console.log(context.dump(resultHandle)) // 42\n * ```\n */\n callFunction(\n func: QuickJSHandle,\n thisVal: QuickJSHandle,\n args?: QuickJSHandle[],\n ): QuickJSContextResult<QuickJSHandle>\n callFunction(\n func: QuickJSHandle,\n thisVal: QuickJSHandle,\n ...args: QuickJSHandle[]\n ): QuickJSContextResult<QuickJSHandle>\n callFunction(\n func: QuickJSHandle,\n thisVal: QuickJSHandle,\n ...restArgs: Array<QuickJSHandle | QuickJSHandle[] | undefined>\n ): QuickJSContextResult<QuickJSHandle> {\n this.runtime.assertOwned(func)\n let args\n const firstArg = restArgs[0]\n if (firstArg === undefined || Array.isArray(firstArg)) {\n args = firstArg ?? []\n } else {\n args = restArgs as QuickJSHandle[]\n }\n\n const resultPtr = this.memory\n .toPointerArray(args)\n .consume((argsArrayPtr) =>\n this.ffi.QTS_Call(\n this.ctx.value,\n func.value,\n thisVal.value,\n args.length,\n argsArrayPtr.value,\n ),\n )\n\n const errorPtr = this.ffi.QTS_ResolveException(this.ctx.value, resultPtr)\n if (errorPtr) {\n this.ffi.QTS_FreeValuePointer(this.ctx.value, resultPtr)\n return this.fail(this.memory.heapValueHandle(errorPtr))\n }\n\n return this.success(this.memory.heapValueHandle(resultPtr))\n }\n\n /**\n * `handle[key](...args)`\n *\n * Call a method on a JSValue. This is a convenience method that calls {@link getProp} and {@link callFunction}.\n *\n * @returns A result. If the function threw synchronously, `result.error` be a\n * handle to the exception. Otherwise `result.value` will be a handle to the\n * value.\n */\n callMethod(\n thisHandle: QuickJSHandle,\n key: QuickJSPropertyKey,\n args: QuickJSHandle[] = [],\n ): QuickJSContextResult<QuickJSHandle> {\n return this.getProp(thisHandle, key).consume((func) =>\n this.callFunction(func, thisHandle, args),\n )\n }\n\n /**\n * Like [`eval(code)`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval#Description).\n *\n * Evaluates `code`, as though it's in a file named `filename`, with options `options`.\n *\n * - When `options.type` is `\"global\"`, the code is evaluated in the global\n * scope of the QuickJSContext, and the return value is the result of the last\n * expression.\n * - When `options.type` is `\"module\"`, the code is evaluated is a module scope.\n * It may use `import` and `export` if {@link runtime}.{@link QuickJSRuntime#setModuleLoader} was called.\n * It may use top-level await if supported by the underlying QuickJS library.\n * The return value is the module's exports, or a promise for the module's exports.\n * - When `options.type` is unset, the code is evaluated as a module if it\n * contains an `import` or `export` statement, otherwise it is evaluated in\n * the global scope.\n *\n * When working with async code, you many need to call {@link runtime}.{@link QuickJSRuntime#executePendingJobs}\n * to execute callbacks pending after synchronous evaluation returns.\n *\n * See {@link unwrapResult}, which will throw if the function returned an error, or\n * return the result handle directly. If evaluation returned a handle containing\n * a promise, use {@link resolvePromise} to convert it to a native promise and\n * {@link QuickJSRuntime#executePendingJobs} to finish evaluating the promise.\n *\n * *Note*: to protect against infinite loops, provide an interrupt handler to\n * {@link QuickJSRuntime#setInterruptHandler}. You can use {@link shouldInterruptAfterDeadline} to\n * create a time-based deadline.\n *\n * @returns The last statement's value. If the code threw synchronously,\n * `result.error` will be a handle to the exception. If execution was\n * interrupted, the error will have name `InternalError` and message\n * `interrupted`.\n */\n evalCode(\n code: string,\n filename: string = \"eval.js\",\n /**\n * If no options are passed, a heuristic will be used to detect if `code` is\n * an ES module.\n *\n * See {@link EvalFlags} for number semantics.\n */\n options?: number | ContextEvalOptions,\n ): QuickJSContextResult<QuickJSHandle> {\n const detectModule = (options === undefined ? 1 : 0) as EvalDetectModule\n const flags = evalOptionsToFlags(options) as EvalFlags\n const resultPtr = this.memory\n .newHeapCharPointer(code)\n .consume((charHandle) =>\n this.ffi.QTS_Eval(\n this.ctx.value,\n charHandle.value.ptr,\n charHandle.value.strlen,\n filename,\n detectModule,\n flags,\n ),\n )\n const errorPtr = this.ffi.QTS_ResolveException(this.ctx.value, resultPtr)\n if (errorPtr) {\n this.ffi.QTS_FreeValuePointer(this.ctx.value, resultPtr)\n return this.fail(this.memory.heapValueHandle(errorPtr))\n }\n return this.success(this.memory.heapValueHandle(resultPtr))\n }\n\n /**\n * Throw an error in the VM, interrupted whatever current execution is in progress when execution resumes.\n * @experimental\n */\n throw(error: Error | QuickJSHandle) {\n return this.errorToHandle(error).consume((handle) =>\n this.ffi.QTS_Throw(this.ctx.value, handle.value),\n )\n }\n\n /**\n * @private\n */\n protected borrowPropertyKey(key: QuickJSPropertyKey): QuickJSHandle {\n if (typeof key === \"number\") {\n return this.newNumber(key)\n }\n\n if (typeof key === \"string\") {\n return this.newString(key)\n }\n\n // key is already a JSValue, but we're borrowing it. Return a static handle\n // for internal use only.\n return new StaticLifetime(key.value as JSValueConstPointer, this.runtime)\n }\n\n /**\n * @private\n */\n getMemory(rt: JSRuntimePointer): ContextMemory {\n if (rt === this.rt.value) {\n return this.memory\n } else {\n throw new Error(\"Private API. Cannot get memory from a different runtime\")\n }\n }\n\n // Utilities ----------------------------------------------------------------\n\n /**\n * Dump a JSValue to Javascript in a best-effort fashion.\n * If the value is a promise, dumps the promise's state.\n * Returns `handle.toString()` if it cannot be serialized to JSON.\n */\n dump(handle: QuickJSHandle): any {\n this.runtime.assertOwned(handle)\n const type = this.typeof(handle)\n if (type === \"string\") {\n return this.getString(handle)\n } else if (type === \"number\") {\n return this.getNumber(handle)\n } else if (type === \"bigint\") {\n return this.getBigInt(handle)\n } else if (type === \"undefined\") {\n return undefined\n } else if (type === \"symbol\") {\n return this.getSymbol(handle)\n }\n\n // It's confusing if we dump(promise) and just get back {} because promise\n // has no properties, so dump promise state.\n const asPromiseState = this.getPromiseState(handle)\n if (asPromiseState.type === \"fulfilled\" && !asPromiseState.notAPromise) {\n handle.dispose()\n return { type: asPromiseState.type, value: asPromiseState.value.consume(this.dump) }\n } else if (asPromiseState.type === \"pending\") {\n handle.dispose()\n return { type: asPromiseState.type }\n } else if (asPromiseState.type === \"rejected\") {\n handle.dispose()\n return { type: asPromiseState.type, error: asPromiseState.error.consume(this.dump) }\n }\n\n const str = this.memory.consumeJSCharPointer(this.ffi.QTS_Dump(this.ctx.value, handle.value))\n try {\n return JSON.parse(str)\n } catch (_err) {\n return str\n }\n }\n\n /**\n * Unwrap a SuccessOrFail result such as a {@link VmCallResult} or a\n * {@link ExecutePendingJobsResult}, where the fail branch contains a handle to a QuickJS error value.\n * If the result is a success, returns the value.\n * If the result is an error, converts the error to a native object and throws the error.\n */\n unwrapResult<T>(result: SuccessOrFail<T, QuickJSHandle>): T {\n if (result.error) {\n const context: QuickJSContext =\n \"context\" in result.error ? (result.error as { context: QuickJSContext }).context : this\n const cause = result.error.consume((error) => this.dump(error))\n\n if (cause && typeof cause === \"object\" && typeof cause.message === \"string\") {\n const { message, name, stack, ...rest } = cause\n const exception = new QuickJSUnwrapError(cause, context)\n\n if (typeof name === \"string\") {\n exception.name = cause.name\n }\n\n exception.message = message\n const hostStack = exception.stack\n if (typeof stack === \"string\") {\n exception.stack = `${name}: ${message}\\n${cause.stack}Host: ${hostStack}`\n }\n\n Object.assign(exception, rest)\n throw exception\n }\n\n throw new QuickJSUnwrapError(cause)\n }\n\n return result.value\n }\n\n /** @private */\n [Symbol.for(\"nodejs.util.inspect.custom\")]() {\n if (!this.alive) {\n return `${this.constructor.name} { disposed }`\n }\n return `${this.constructor.name} { ctx: ${this.ctx.value} rt: ${this.rt.value} }`\n }\n\n /** @private */\n protected fnNextId = -32768 // min value of signed 16bit int used by Quickjs\n /** @private */\n protected fnMaps = new Map<number, Map<number, VmFunctionImplementation<QuickJSHandle>>>()\n\n /** @private */\n protected getFunction(fn_id: number): VmFunctionImplementation<QuickJSHandle> | undefined {\n const map_id = fn_id >> 8\n const fnMap = this.fnMaps.get(map_id)\n if (!fnMap) {\n return undefined\n }\n return fnMap.get(fn_id)\n }\n\n /** @private */\n protected setFunction(fn_id: number, handle: VmFunctionImplementation<QuickJSHandle>) {\n const map_id = fn_id >> 8\n let fnMap = this.fnMaps.get(map_id)\n if (!fnMap) {\n fnMap = new Map<number, VmFunctionImplementation<QuickJSHandle>>()\n this.fnMaps.set(map_id, fnMap)\n }\n return fnMap.set(fn_id, handle)\n }\n\n /**\n * @hidden\n */\n private cToHostCallbacks: ContextCallbacks = {\n callFunction: (ctx, this_ptr, argc, argv, fn_id) => {\n if (ctx !== this.ctx.value) {\n throw new Error(\"QuickJSContext instance received C -> JS call with mismatched ctx\")\n }\n\n const fn = this.getFunction(fn_id)\n if (!fn) {\n // this \"throw\" is not catch-able from the TS side. could we somehow handle this higher up?\n throw new Error(`QuickJSContext had no callback with id ${fn_id}`)\n }\n\n return Scope.withScopeMaybeAsync(this, function* (awaited, scope) {\n const thisHandle = scope.manage(\n new WeakLifetime(\n this_ptr,\n this.memory.copyJSValue,\n this.memory.freeJSValue,\n this.runtime,\n ),\n )\n const argHandles = new Array<QuickJSHandle>(argc)\n for (let i = 0; i < argc; i++) {\n const ptr = this.ffi.QTS_ArgvGetJSValueConstPointer(argv, i)\n argHandles[i] = scope.manage(\n new WeakLifetime(ptr, this.memory.copyJSValue, this.memory.freeJSValue, this.runtime),\n )\n }\n\n try {\n const result = yield* awaited(fn.apply(thisHandle, argHandles))\n if (result) {\n if (\"error\" in result && result.error) {\n this.runtime.debugLog(\"throw error\", result.error)\n throw result.error\n }\n const handle = scope.manage(result instanceof Lifetime ? result : result.value)\n return this.ffi.QTS_DupValuePointer(this.ctx.value, handle.value)\n }\n return 0 as JSValuePointer\n } catch (error) {\n return this.errorToHandle(error as Error).consume((errorHandle) =>\n this.ffi.QTS_Throw(this.ctx.value, errorHandle.value),\n )\n }\n }) as JSValuePointer\n },\n }\n\n private errorToHandle(error: Error | QuickJSHandle): QuickJSHandle {\n if (error instanceof Lifetime) {\n return error\n }\n\n return this.newError(error)\n }\n\n /**\n * Outputs QuickJS Objects in binary form\n *\n * **WARNING**: QuickJS's binary JSON doesn't have a standard so expect it to change between version\n *\n * ```ts\n * // imagine sending data to another via IPC\n * let dataLifetime = context.newString(\"This is an example\")\n * ?.consume(handle => context.encodeBinaryJSON(handle))\n * ?.consume(handle => context.getArrayBuffer(handle))\n * socket.write(dataLifetime?.value)\n * ```\n */\n encodeBinaryJSON(handle: QuickJSHandle): QuickJSHandle {\n const ptr = this.ffi.QTS_bjson_encode(this.ctx.value, handle.value)\n return this.memory.heapValueHandle(ptr)\n }\n\n /**\n * Outputs Handle of the given QuickJS Object in binary form\n *\n * ```ts\n * // imagine receiving data from another via IPC\n * socket.on(\"data\", chunk => {\n * context.newArrayBuffer(chunk)\n * ?.consume(handle => context.decodeBinaryJSON(handle))\n * ?.consume(handle => console.log(context.dump(handle)))\n * })\n * ```\n */\n decodeBinaryJSON(handle: QuickJSHandle): QuickJSHandle {\n const ptr = this.ffi.QTS_bjson_decode(this.ctx.value, handle.value)\n return this.memory.heapValueHandle(ptr)\n }\n\n // Bytecode compilation and caching -----------------------------------------\n\n /**\n * Compile code to bytecode without executing it.\n * The bytecode can be serialized with {@link encodeBytecode} and later\n * restored with {@link decodeBytecode} and executed with {@link evalBytecode}.\n *\n * This enables bytecode caching for faster startup (~2x improvement).\n *\n * ```ts\n * // Compile code to bytecode\n * const bytecodeHandle = context.compileCode(`\n * function hello() { return \"world\"; }\n * hello();\n * `, \"example.js\").unwrap()\n *\n * // Serialize to ArrayBuffer for caching\n * const serialized = context.encodeBytecode(bytecodeHandle)\n * .consume(handle => context.getArrayBuffer(handle))\n *\n * // Later: restore and execute\n * const restored = context.newArrayBuffer(serialized.value)\n * .consume(handle => context.decodeBytecode(handle))\n * const result = context.evalBytecode(restored).unwrap()\n * ```\n */\n compileCode(\n code: string,\n filename: string = \"eval.js\",\n options?: Omit<ContextEvalOptions, \"compileOnly\">,\n ): QuickJSContextResult<QuickJSHandle> {\n return this.evalCode(code, filename, { ...options, compileOnly: true })\n }\n\n /**\n * Execute a bytecode function that was previously compiled with\n * {@link compileCode} or `evalCode({ compileOnly: true })`, or restored\n * from serialized bytecode via {@link decodeBytecode}.\n *\n * @returns A result. If execution threw synchronously, `result.error` will be\n * a handle to the exception. Otherwise `result.value` will be a handle to the\n * return value.\n */\n evalBytecode(handle: QuickJSHandle): QuickJSContextResult<QuickJSHandle> {\n this.runtime.assertOwned(handle)\n const resultPtr = this.ffi.QTS_EvalFunction(this.ctx.value, handle.value)\n const errorPtr = this.ffi.QTS_ResolveException(this.ctx.value, resultPtr)\n if (errorPtr) {\n this.ffi.QTS_FreeValuePointer(this.ctx.value, resultPtr)\n return this.fail(this.memory.heapValueHandle(errorPtr))\n }\n return this.success(this.memory.heapValueHandle(resultPtr))\n }\n\n /**\n * Serialize a bytecode function to binary format.\n * The bytecode can be stored/cached and later restored with {@link decodeBytecode}.\n *\n * This is more efficient than {@link encodeBinaryJSON} for bytecode because it\n * uses the `JS_WRITE_OBJ_BYTECODE` flag optimized for function serialization.\n *\n * **WARNING**: The bytecode format is not standardized and may change between\n * QuickJS versions.\n *\n * @param handle - A handle to a bytecode function (from {@link compileCode} or\n * `evalCode({ compileOnly: true })`)\n * @returns A handle to an ArrayBuffer containing the serialized bytecode\n */\n encodeBytecode(handle: QuickJSHandle): QuickJSHandle {\n this.runtime.assertOwned(handle)\n const ptr = this.ffi.QTS_EncodeBytecode(this.ctx.value, handle.value)\n return this.memory.heapValueHandle(ptr)\n }\n\n /**\n * Deserialize bytecode from binary format.\n * The bytecode must have been serialized with {@link encodeBytecode}.\n *\n * After decoding, use {@link evalBytecode} to execute the bytecode.\n *\n * **WARNING**: The bytecode format is not standardized and may change between\n * QuickJS versions.\n *\n * @param handle - A handle to an ArrayBuffer containing serialized bytecode\n * @returns A handle to the deserialized bytecode function\n */\n decodeBytecode(handle: QuickJSHandle): QuickJSHandle {\n this.runtime.assertOwned(handle)\n const ptr = this.ffi.QTS_DecodeBytecode(this.ctx.value, handle.value)\n return this.memory.heapValueHandle(ptr)\n }\n\n /**\n * Resolve module dependencies after loading module bytecode.\n *\n * When loading ES module bytecode via {@link decodeBytecode}, the module's\n * import dependencies are not automatically resolved. Call this method\n * after decoding module bytecode and before {@link evalBytecode} to resolve\n * all imports.\n *\n * For non-module bytecode (scripts), this is a no-op.\n *\n * @param handle - A handle to a module (from {@link decodeBytecode})\n * @returns A result. If resolution failed, `result.error` will be a handle\n * to the exception. Otherwise `result.value` will be undefined.\n */\n resolveModule(handle: QuickJSHandle): QuickJSContextResult<void> {\n this.runtime.assertOwned(handle)\n const result = this.ffi.QTS_ResolveModule(this.ctx.value, handle.value)\n if (result < 0) {\n const errorPtr = this.ffi.QTS_GetException(this.ctx.value)\n return this.fail(this.memory.heapValueHandle(errorPtr))\n }\n return this.success(undefined)\n }\n\n protected success<S>(value: S): DisposableSuccess<S> {\n return DisposableResult.success(value)\n }\n\n protected fail(error: QuickJSHandle): DisposableFail<QuickJSHandle> {\n return DisposableResult.fail(error, (error) => this.unwrapResult(error))\n }\n}\n","import { UsingDisposable, type Disposable } from \"./lifetime\"\nimport type { QuickJSHandle } from \"./types\"\nimport type { QuickJSRuntime } from \"./runtime\"\nimport type { QuickJSContext } from \"./context\"\nexport type { PromiseExecutor } from \"./types\"\n\n/**\n * A promise state inside QuickJS, which can be pending, fulfilled, or rejected.\n * You can unwrap a JSPromiseState with {@link QuickJSContext#unwrapResult}.\n */\nexport type JSPromiseState =\n | JSPromiseStatePending\n | JSPromiseStateFulfilled\n | JSPromiseStateRejected\n\n/**\n * Pending promise state.\n * See {@link JSPromiseState}.\n */\nexport interface JSPromiseStatePending {\n type: \"pending\"\n /**\n * The error property here allows unwrapping a JSPromiseState with {@link QuickJSContext#unwrapResult}.\n * Unwrapping a pending promise will throw a {@link QuickJSPromisePending} error.\n */\n get error(): Error\n}\n\n/**\n * Fulfilled promise state.\n * See {@link JSPromiseState}.\n */\nexport interface JSPromiseStateFulfilled {\n type: \"fulfilled\"\n value: QuickJSHandle\n error?: undefined\n /** Trying to get the promise state of a non-Promise value returns a fulfilled state with the original value, and `notAPromise: true`. */\n notAPromise?: boolean\n}\n\n/**\n * Rejected promise state.\n * See {@link JSPromiseState}.\n */\nexport interface JSPromiseStateRejected {\n type: \"rejected\"\n error: QuickJSHandle\n}\n\n/**\n * QuickJSDeferredPromise wraps a QuickJS promise {@link handle} and allows\n * {@link resolve}ing or {@link reject}ing that promise. Use it to bridge asynchronous\n * code on the host to APIs inside a QuickJSContext.\n *\n * Managing the lifetime of promises is tricky. There are three\n * {@link QuickJSHandle}s inside of each deferred promise object: (1) the promise\n * itself, (2) the `resolve` callback, and (3) the `reject` callback.\n *\n * - If the promise will be fulfilled before the end of it's {@link owner}'s lifetime,\n * the only cleanup necessary is `deferred.handle.dispose()`, because\n * calling {@link resolve} or {@link reject} will dispose of both callbacks automatically.\n *\n * - As the return value of a {@link VmFunctionImplementation}, return {@link handle},\n * and ensure that either {@link resolve} or {@link reject} will be called. No other\n * clean-up is necessary.\n *\n * - In other cases, call {@link dispose}, which will dispose {@link handle} as well as the\n * QuickJS handles that back {@link resolve} and {@link reject}. For this object,\n * {@link dispose} is idempotent.\n */\nexport class QuickJSDeferredPromise extends UsingDisposable implements Disposable {\n public owner: QuickJSRuntime\n public context: QuickJSContext\n\n /**\n * A handle of the Promise instance inside the QuickJSContext.\n * You must dispose {@link handle} or the entire QuickJSDeferredPromise once you\n * are finished with it.\n */\n public handle: QuickJSHandle\n\n /**\n * A native promise that will resolve once this deferred is settled.\n */\n public settled: Promise<void>\n\n private resolveHandle: QuickJSHandle\n private rejectHandle: QuickJSHandle\n private onSettled!: () => void\n\n /**\n * Use {@link QuickJSContext#newPromise} to create a new promise instead of calling\n * this constructor directly.\n */\n constructor(args: {\n context: QuickJSContext\n promiseHandle: QuickJSHandle\n resolveHandle: QuickJSHandle\n rejectHandle: QuickJSHandle\n }) {\n super()\n this.context = args.context\n this.owner = args.context.runtime\n this.handle = args.promiseHandle\n this.settled = new Promise((resolve) => {\n this.onSettled = resolve\n })\n this.resolveHandle = args.resolveHandle\n this.rejectHandle = args.rejectHandle\n }\n\n /**\n * Resolve {@link handle} with the given value, if any.\n * Calling this method after calling {@link dispose} is a no-op.\n *\n * Note that after resolving a promise, you may need to call\n * {@link QuickJSRuntime#executePendingJobs} to propagate the result to the promise's\n * callbacks.\n */\n resolve = (value?: QuickJSHandle) => {\n if (!this.resolveHandle.alive) {\n return\n }\n\n this.context\n .unwrapResult(\n this.context.callFunction(\n this.resolveHandle,\n this.context.undefined,\n value || this.context.undefined,\n ),\n )\n .dispose()\n\n this.disposeResolvers()\n this.onSettled()\n }\n\n /**\n * Reject {@link handle} with the given value, if any.\n * Calling this method after calling {@link dispose} is a no-op.\n *\n * Note that after rejecting a promise, you may need to call\n * {@link QuickJSRuntime#executePendingJobs} to propagate the result to the promise's\n * callbacks.\n */\n reject = (value?: QuickJSHandle) => {\n if (!this.rejectHandle.alive) {\n return\n }\n\n this.context\n .unwrapResult(\n this.context.callFunction(\n this.rejectHandle,\n this.context.undefined,\n value || this.context.undefined,\n ),\n )\n .dispose()\n\n this.disposeResolvers()\n this.onSettled()\n }\n\n get alive() {\n return this.handle.alive || this.resolveHandle.alive || this.rejectHandle.alive\n }\n\n dispose = () => {\n if (this.handle.alive) {\n this.handle.dispose()\n }\n this.disposeResolvers()\n }\n\n private disposeResolvers() {\n if (this.resolveHandle.alive) {\n this.resolveHandle.dispose()\n }\n\n if (this.rejectHandle.alive) {\n this.rejectHandle.dispose()\n }\n }\n}\n","import type {\n EitherModule,\n OwnedHeapCharPointer,\n JSValueConstPointerPointer,\n JSVoidPointer,\n} from \"@componentor/quickjs-ffi-types\"\nimport { Lifetime } from \"./lifetime\"\nimport type { QuickJSHandle } from \"./types\"\n\n/**\n * @private\n */\nexport type HeapUint8Array = {\n pointer: JSVoidPointer\n numBytes: number\n}\n\n/**\n * Add more types as needed.\n * @private\n */\nexport type TypedArray = Int32Array<ArrayBuffer> | Uint32Array<ArrayBuffer>\n\n/** @private */\nexport interface TypedArrayConstructor<T> {\n new (length: number): T\n new (array: ArrayLike<number> | ArrayBufferLike): T\n new (buffer: ArrayBufferLike, byteOffset?: number, length?: number): T\n BYTES_PER_ELEMENT: number\n}\n\n/** @private */\nexport type HeapTypedArray<JS extends TypedArray, C extends number> = Lifetime<{\n typedArray: JS\n ptr: C\n}>\n\n/**\n * @private\n */\nexport class ModuleMemory {\n constructor(public module: EitherModule) {}\n\n toPointerArray(handleArray: QuickJSHandle[]): Lifetime<JSValueConstPointerPointer> {\n const typedArray = new Int32Array(handleArray.map((handle) => handle.value))\n const numBytes = typedArray.length * typedArray.BYTES_PER_ELEMENT\n const ptr = this.module._malloc(numBytes) as JSValueConstPointerPointer\n const heapBytes = new Uint8Array(this.module.HEAPU8.buffer, ptr, numBytes)\n heapBytes.set(new Uint8Array(typedArray.buffer))\n return new Lifetime(ptr, undefined, (ptr) => this.module._free(ptr))\n }\n\n newTypedArray<JS extends TypedArray, C extends number>(\n kind: TypedArrayConstructor<JS>,\n length: number,\n ): HeapTypedArray<JS, C> {\n const zeros = new kind(new Array(length).fill(0))\n const numBytes = zeros.length * zeros.BYTES_PER_ELEMENT\n const ptr = this.module._malloc(numBytes) as C\n const typedArray = new kind(this.module.HEAPU8.buffer, ptr, length)\n typedArray.set(zeros)\n return new Lifetime({ typedArray, ptr }, undefined, (value) => this.module._free(value.ptr))\n }\n\n // TODO: shouldn't this be Uint32 instead of Int32?\n newMutablePointerArray<T extends number>(\n length: number,\n ): HeapTypedArray<Int32Array<ArrayBuffer>, T> {\n return this.newTypedArray(Int32Array, length)\n }\n\n newHeapCharPointer(string: string): Lifetime<{ ptr: OwnedHeapCharPointer; strlen: number }> {\n const strlen = this.module.lengthBytesUTF8(string)\n const dataBytes = strlen + 1\n const ptr: OwnedHeapCharPointer = this.module._malloc(dataBytes) as OwnedHeapCharPointer\n this.module.stringToUTF8(string, ptr, dataBytes)\n return new Lifetime({ ptr, strlen }, undefined, (value) => this.module._free(value.ptr))\n }\n\n newHeapBufferPointer(buffer: Uint8Array): Lifetime<HeapUint8Array> {\n const numBytes = buffer.byteLength\n const ptr: JSVoidPointer = this.module._malloc(numBytes) as JSVoidPointer\n this.module.HEAPU8.set(buffer, ptr)\n return new Lifetime({ pointer: ptr, numBytes }, undefined, (value) =>\n this.module._free(value.pointer),\n )\n }\n\n consumeHeapCharPointer(ptr: OwnedHeapCharPointer): string {\n const str = this.module.UTF8ToString(ptr)\n this.module._free(ptr)\n return str\n }\n}\n","import type {\n JSContextPointer,\n JSValueConstPointer,\n JSValuePointer,\n} from \"@componentor/quickjs-ffi-types\"\nimport {\n EvalFlags,\n GetOwnPropertyNamesFlags,\n IntrinsicsFlags,\n} from \"@componentor/quickjs-ffi-types\"\nimport type { QuickJSContext } from \"./context\"\nimport type { SuccessOrFail, VmFunctionImplementation } from \"./vm-interface\"\nimport type { Disposable, Lifetime } from \"./lifetime\"\nimport type { QuickJSAsyncContext } from \"./context-asyncify\"\nimport type { InterruptHandler, QuickJSRuntime } from \"./runtime\"\nimport { QuickJSUnknownIntrinsic } from \"./errors\"\n\n/**\n * A QuickJSHandle to a constant that will never change, and does not need to\n * be disposed.\n */\nexport type StaticJSValue = Lifetime<JSValueConstPointer, JSValueConstPointer, QuickJSRuntime>\n\n/**\n * A QuickJSHandle to a borrowed value that does not need to be disposed.\n *\n * In QuickJS, a JSValueConst is a \"borrowed\" reference that isn't owned by the\n * current scope. That means that the current scope should not `JS_FreeValue`\n * it, or retain a reference to it after the scope exits, because it may be\n * freed by its owner.\n *\n * quickjs-emscripten takes care of disposing JSValueConst references.\n */\nexport type JSValueConst = Lifetime<JSValueConstPointer, JSValuePointer, QuickJSRuntime>\n\n/**\n * A owned QuickJSHandle that should be disposed or returned.\n *\n * The QuickJS interpreter passes Javascript values between functions as\n * `JSValue` structs that references some internal data. Because passing\n * structs cross the Empscripten FFI interfaces is bothersome, we use pointers\n * to these structs instead.\n *\n * A JSValue reference is \"owned\" in its scope. before exiting the scope, it\n * should be freed, by calling `JS_FreeValue(ctx, js_value)`) or returned from\n * the scope. We extend that contract - a JSValuePointer (`JSValue*`) must also\n * be `free`d.\n *\n * You can do so from Javascript by calling the .dispose() method.\n */\nexport type JSValue = Lifetime<JSValuePointer, JSValuePointer, QuickJSRuntime>\n// | Lifetime<JSValueUInt8Array, JSValueUInt8Array, QuickJSRuntime>\n\n/**\n * Wraps a C pointer to a QuickJS JSValue, which represents a Javascript value inside\n * a QuickJS virtual machine.\n *\n * Values must not be shared between QuickJSContext instances.\n * You must dispose of any handles you create by calling the `.dispose()` method.\n */\nexport type QuickJSHandle = StaticJSValue | JSValue | JSValueConst\n\nexport type JSModuleExport =\n | {\n type: \"function\"\n name: string\n implementation: (vm: QuickJSContext) => VmFunctionImplementation<QuickJSHandle>\n }\n | { type: \"value\"; name: string; value: (vm: QuickJSContext) => QuickJSHandle }\n\nexport interface JSModuleDefinition {\n name: string\n exports: JSModuleExport[]\n}\n\nexport type JSModuleLoadSuccess = string\nexport type JSModuleLoadFailure = Error | QuickJSHandle\nexport type JSModuleLoadResult =\n | JSModuleLoadSuccess\n | SuccessOrFail<JSModuleLoadSuccess, JSModuleLoadFailure>\n\nexport interface JSModuleLoaderAsync {\n /** Load module (async) */\n (\n moduleName: string,\n context: QuickJSAsyncContext,\n ): JSModuleLoadResult | Promise<JSModuleLoadResult>\n}\nexport interface JSModuleLoader {\n /** Load module (sync) */\n (moduleName: string, context: QuickJSContext): JSModuleLoadResult\n}\n\nexport type JSModuleNormalizeSuccess = string\nexport type JSModuleNormalizeFailure = Error | QuickJSHandle\nexport type JSModuleNormalizeResult =\n | JSModuleNormalizeSuccess\n | SuccessOrFail<JSModuleNormalizeSuccess, JSModuleNormalizeFailure>\n\nexport interface JSModuleNormalizerAsync {\n (\n baseModuleName: string,\n requestedName: string,\n vm: QuickJSAsyncContext,\n ): JSModuleNormalizeResult | Promise<JSModuleNormalizeResult>\n}\nexport interface JSModuleNormalizer extends JSModuleNormalizerAsync {\n (baseModuleName: string, requestedName: string, vm: QuickJSContext): JSModuleNormalizeResult\n}\n\ntype TODO<hint extends string = \"?\", typeHint = unknown> = hint & typeHint & never\n\nconst UnstableSymbol = Symbol(\"Unstable\")\n\nexport type PartiallyImplemented<T> = never &\n T & {\n [UnstableSymbol]: \"This feature may unimplemented, broken, throw errors, etc.\"\n }\n\nexport interface RuntimeOptionsBase {\n interruptHandler?: InterruptHandler\n maxStackSizeBytes?: number\n memoryLimitBytes?: number\n\n promiseRejectionHandler?: TODO<\"JSHostPromiseRejectionTracker\">\n runtimeInfo?: TODO<\"JS_SetRuntimeInfo\", string>\n gcThreshold?: TODO<\"JS_SetGCThreshold\", number>\n sharedArrayBufferFunctions?: TODO<\n \"JS_SetJSSharedArrayBufferFunctions\",\n { sab_alloc: TODO; sab_free: TODO; sab_dup: TODO; sab_opaque: TODO }\n >\n\n /**\n * Extra lifetimes the runtime should dispose of after it is destroyed.\n * @private\n */\n ownedLifetimes?: Disposable[]\n}\n\nexport interface RuntimeOptions extends RuntimeOptionsBase {\n moduleLoader?: JSModuleLoader\n}\n\nexport interface AsyncRuntimeOptions extends RuntimeOptionsBase {\n moduleLoader?: JSModuleLoaderAsync | JSModuleLoader\n}\n\n// This guy could be declared as Partial<Record<keyof typeof IntrinsicsFlags, boolean>>,\n// but it leads to bad docs.\n/**\n * Language features that can be enabled or disabled in a QuickJSContext.\n * @see {@link ContextOptions}\n */\nexport type Intrinsics = {\n BaseObjects?: boolean\n Date?: boolean\n Eval?: boolean\n StringNormalize?: boolean\n RegExp?: boolean\n RegExpCompiler?: boolean\n JSON?: boolean\n Proxy?: boolean\n MapSet?: boolean\n TypedArrays?: boolean\n Promise?: boolean\n BigInt?: boolean\n BigFloat?: boolean\n BigDecimal?: boolean\n OperatorOverloading?: boolean\n BignumExt?: boolean\n}\n\ntype _Assert<T, U extends T> = U\ntype _intrinsicsHasKeysOfIntrinsicFlags = _Assert<keyof Intrinsics, keyof typeof IntrinsicsFlags>\ntype _intrinsicsHasKeysOfIntrinsicFlags2 = _Assert<keyof typeof IntrinsicsFlags, keyof Intrinsics>\n\n/**\n * The default {@link Intrinsics} language features enabled in a QuickJSContext.\n * @see {@link ContextOptions}\n */\nexport const DefaultIntrinsics = Object.freeze({\n BaseObjects: true,\n Date: true,\n Eval: true,\n StringNormalize: true,\n RegExp: true,\n JSON: true,\n Proxy: true,\n MapSet: true,\n TypedArrays: true,\n Promise: true,\n} as const satisfies Intrinsics)\n\n/**\n * @private\n */\nexport function intrinsicsToFlags(intrinsics: Intrinsics | undefined): IntrinsicsFlags {\n if (!intrinsics) {\n return 0 as IntrinsicsFlags\n }\n\n let result = 0\n for (const [maybeIntrinsicName, enabled] of Object.entries(intrinsics)) {\n if (!(maybeIntrinsicName in IntrinsicsFlags)) {\n throw new QuickJSUnknownIntrinsic(maybeIntrinsicName)\n }\n const intrinsicName = maybeIntrinsicName as keyof typeof IntrinsicsFlags\n\n if (enabled) {\n result |= IntrinsicsFlags[intrinsicName]\n }\n }\n return result as IntrinsicsFlags\n}\n\n/**\n * Options for creating a {@link QuickJSContext} or {@link QuickJSAsyncContext}\n * Pass to {@link QuickJSRuntime#newContext}.\n */\nexport interface ContextOptions {\n /**\n * What built-in objects and language features to enable?\n * If unset, the default intrinsics will be used.\n * To omit all intrinsics, pass an empty array.\n *\n * To remove a specific intrinsic, but retain the other defaults,\n * override it from {@link DefaultIntrinsics}\n * ```ts\n * const contextWithoutDateOrEval = runtime.newContext({\n * intrinsics: {\n * ...DefaultIntrinsics,\n * Date: false,\n * }\n * })\n * ```\n */\n intrinsics?: Intrinsics\n\n /**\n * Wrap the provided context instead of constructing a new one.\n * @private\n */\n contextPointer?: JSContextPointer\n\n /**\n * Extra lifetimes the context should dispose of after it is destroyed.\n * @private\n */\n ownedLifetimes?: Disposable[]\n}\n\nexport interface ContextEvalOptions {\n /**\n * Global code (default), or \"module\" code?\n *\n * - When type is `\"global\"`, the code is evaluated in the global scope of the QuickJSContext, and the return value is the result of the last expression.\n * - When type is `\"module\"`, the code is evaluated is a module scope, may use `import`, `export`, and top-level `await`. The return value is the module's exports, or a promise for the module's exports.\n */\n type?: \"global\" | \"module\"\n /** Force \"strict\" mode */\n strict?: boolean\n /** Force \"strip\" mode */\n strip?: boolean\n /**\n * compile but do not run. The result is an object with a\n * JS_TAG_FUNCTION_BYTECODE or JS_TAG_MODULE tag. It can be executed\n * with JS_EvalFunction().\n */\n compileOnly?: boolean\n /** don't include the stack frames before this eval in the Error() backtraces */\n backtraceBarrier?: boolean\n}\n\n/** Convert {@link ContextEvalOptions} to a bitfield flags */\nexport function evalOptionsToFlags(evalOptions: ContextEvalOptions | number | undefined): number {\n if (typeof evalOptions === \"number\") {\n return evalOptions\n }\n\n if (evalOptions === undefined) {\n return 0\n }\n\n const { type, strict, strip, compileOnly, backtraceBarrier } = evalOptions\n let flags = 0\n if (type === \"global\") flags |= EvalFlags.JS_EVAL_TYPE_GLOBAL\n if (type === \"module\") flags |= EvalFlags.JS_EVAL_TYPE_MODULE\n if (strict) flags |= EvalFlags.JS_EVAL_FLAG_STRICT\n if (strip) flags |= EvalFlags.JS_EVAL_FLAG_STRIP\n if (compileOnly) flags |= EvalFlags.JS_EVAL_FLAG_COMPILE_ONLY\n if (backtraceBarrier) flags |= EvalFlags.JS_EVAL_FLAG_BACKTRACE_BARRIER\n return flags\n}\n\nexport interface GetOwnPropertyNamesOptions {\n /** Include number properties like array indexes *as numbers* in the result. This is not standards-compliant */\n numbers?: boolean\n /** Enable standards-compliant number properties. When set, `includeNumbers` is ignored. */\n numbersAsStrings?: boolean\n /** Include strings in the result */\n strings?: boolean\n /** Include symbols in the result */\n symbols?: boolean\n /** Include implementation-specific private properties in the result */\n quickjsPrivate?: boolean\n /** Only include the enumerable properties */\n onlyEnumerable?: boolean\n}\n\n/** Convert {@link GetOwnPropertyNamesOptions} to bitfield flags */\nexport function getOwnPropertyNamesOptionsToFlags(\n options: GetOwnPropertyNamesOptions | GetOwnPropertyNamesFlags | undefined,\n): GetOwnPropertyNamesFlags {\n if (typeof options === \"number\") {\n return options\n }\n\n if (options === undefined) {\n return 0 as GetOwnPropertyNamesFlags\n }\n\n const {\n strings: includeStrings,\n symbols: includeSymbols,\n quickjsPrivate: includePrivate,\n onlyEnumerable,\n numbers: includeNumbers,\n numbersAsStrings,\n } = options\n let flags = 0\n if (includeStrings) flags |= GetOwnPropertyNamesFlags.JS_GPN_STRING_MASK\n if (includeSymbols) flags |= GetOwnPropertyNamesFlags.JS_GPN_SYMBOL_MASK\n if (includePrivate) flags |= GetOwnPropertyNamesFlags.JS_GPN_PRIVATE_MASK\n if (onlyEnumerable) flags |= GetOwnPropertyNamesFlags.JS_GPN_ENUM_ONLY\n if (includeNumbers) flags |= GetOwnPropertyNamesFlags.QTS_GPN_NUMBER_MASK\n if (numbersAsStrings) flags |= GetOwnPropertyNamesFlags.QTS_STANDARD_COMPLIANT_NUMBER\n\n return flags as GetOwnPropertyNamesFlags\n}\n\nexport type PromiseExecutor<ResolveT, RejectT> = (\n resolve: (value: ResolveT | PromiseLike<ResolveT>) => void,\n reject: (reason: RejectT) => void,\n) => void\n\nexport function concat<T>(...values: Array<T[] | T | undefined>): T[] {\n let result: T[] = []\n for (const value of values) {\n if (value !== undefined) {\n result = result.concat(value)\n }\n }\n return result\n}\n","import type { QuickJSContextResult, QuickJSContext } from \"./context\"\nimport { DisposableResult, Lifetime, UsingDisposable } from \"./lifetime\"\nimport type { QuickJSRuntime } from \"./runtime\"\nimport type { QuickJSHandle } from \"./types\"\n\n/**\n * Proxies the iteration protocol from the host to a guest iterator.\n * The guest iterator is a QuickJS object with a `next` method.\n * See [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols).\n *\n * If calling the `next` method or any other method of the iteration protocol throws an error,\n * the iterator is disposed after returning the exception as the final value.\n *\n * When the iterator is done, the handle is disposed automatically.\n * The caller is responsible for disposing each successive value.\n *\n * ```typescript\n * for (const nextResult of context.unwrapResult(context.getIterator(arrayHandle)) {\n * const nextHandle = context.unwrapResult(nextResult)\n * try {\n * // Do something with nextHandle\n * console.log(context.dump(nextHandle))\n * } finally {\n * nextHandle.dispose()\n * }\n * }\n * ```\n */\nexport class QuickJSIterator\n extends UsingDisposable\n implements Disposable, IterableIterator<QuickJSContextResult<QuickJSHandle>>\n{\n public owner: QuickJSRuntime\n private _next: QuickJSHandle | undefined\n private _isDone = false\n\n constructor(\n public handle: QuickJSHandle,\n public context: QuickJSContext,\n ) {\n super()\n this.owner = context.runtime\n }\n\n [Symbol.iterator]() {\n return this\n }\n\n next(value?: QuickJSHandle): IteratorResult<QuickJSContextResult<QuickJSHandle>, any> {\n if (!this.alive || this._isDone) {\n return {\n done: true,\n value: undefined,\n }\n }\n\n const nextMethod = (this._next ??= this.context.getProp(this.handle, \"next\"))\n return this.callIteratorMethod(nextMethod, value)\n }\n\n return(value?: QuickJSHandle): IteratorResult<QuickJSContextResult<QuickJSHandle>, any> {\n if (!this.alive) {\n return {\n done: true,\n value: undefined,\n }\n }\n\n const returnMethod = this.context.getProp(this.handle, \"return\")\n if (returnMethod === this.context.undefined && value === undefined) {\n // This may be an automatic call by the host Javascript engine,\n // but the guest iterator doesn't have a `return` method.\n // Don't call it then.\n this.dispose()\n return {\n done: true,\n value: undefined,\n }\n }\n\n const result = this.callIteratorMethod(returnMethod, value)\n returnMethod.dispose()\n this.dispose()\n return result\n }\n\n throw(e?: any): IteratorResult<QuickJSContextResult<QuickJSHandle>, any> {\n if (!this.alive) {\n return {\n done: true,\n value: undefined,\n }\n }\n\n const errorHandle = e instanceof Lifetime ? e : this.context.newError(e)\n const throwMethod = this.context.getProp(this.handle, \"throw\")\n const result = this.callIteratorMethod(throwMethod, e)\n if (errorHandle.alive) {\n errorHandle.dispose()\n }\n throwMethod.dispose()\n this.dispose()\n return result\n }\n\n get alive() {\n return this.handle.alive\n }\n\n dispose() {\n this._isDone = true\n this.handle.dispose()\n this._next?.dispose()\n }\n\n private callIteratorMethod(\n method: QuickJSHandle,\n input?: QuickJSHandle,\n ): IteratorResult<QuickJSContextResult<QuickJSHandle>, any> {\n const callResult = input\n ? this.context.callFunction(method, this.handle, input)\n : this.context.callFunction(method, this.handle)\n if (callResult.error) {\n this.dispose()\n return {\n value: callResult,\n }\n }\n\n const done = this.context.getProp(callResult.value, \"done\").consume((v) => this.context.dump(v))\n if (done) {\n callResult.value.dispose()\n this.dispose()\n return {\n done,\n value: undefined,\n }\n }\n\n const value = this.context.getProp(callResult.value, \"value\")\n callResult.value.dispose()\n return {\n value: DisposableResult.success(value),\n done: done as false,\n }\n }\n}\n","import type {\n BorrowedHeapCharPointer,\n JSContextPointer,\n JSContextPointerPointer,\n JSRuntimePointer,\n EitherFFI,\n EitherModule,\n} from \"@componentor/quickjs-ffi-types\"\nimport { maybeAsyncFn } from \"./asyncify-helpers\"\nimport { QuickJSContext } from \"./context\"\nimport { QTS_DEBUG } from \"./debug\"\nimport { QuickJSWrongOwner } from \"./errors\"\nimport type { Disposable } from \"./lifetime\"\nimport { DisposableResult, Lifetime, Scope, UsingDisposable } from \"./lifetime\"\nimport { ModuleMemory } from \"./memory\"\nimport type { QuickJSModuleCallbacks, RuntimeCallbacks } from \"./module\"\nimport type { ContextOptions, JSModuleLoader, JSModuleNormalizer, QuickJSHandle } from \"./types\"\nimport { intrinsicsToFlags } from \"./types\"\n\n/**\n * Callback called regularly while the VM executes code.\n * Determines if a VM's execution should be interrupted.\n *\n * @returns `true` to interrupt JS execution inside the VM.\n * @returns `false` or `undefined` to continue JS execution inside the VM.\n */\nexport type InterruptHandler = (runtime: QuickJSRuntime) => boolean | undefined | void\n\n/**\n * Used as an optional for the results of executing pendingJobs.\n * On success, `value` contains the number of async jobs executed\n * by the runtime.\n * @source\n */\nexport type ExecutePendingJobsResult = DisposableResult<\n /** Number of jobs successfully executed. */\n number,\n /** The error that occurred. */\n QuickJSHandle & {\n /** The context where the error occurred. */\n context: QuickJSContext\n }\n>\n\n/**\n * A runtime represents a Javascript runtime corresponding to an object heap.\n * Several runtimes can exist at the same time but they cannot exchange objects.\n * Inside a given runtime, no multi-threading is supported.\n *\n * You can think of separate runtimes like different domains in a browser, and\n * the contexts within a runtime like the different windows open to the same\n * domain.\n *\n * Create a runtime via {@link QuickJSWASMModule.newRuntime}.\n *\n * You should create separate runtime instances for untrusted code from\n * different sources for isolation. However, stronger isolation is also\n * available (at the cost of memory usage), by creating separate WebAssembly\n * modules to further isolate untrusted code.\n * See {@link newQuickJSWASMModule}.\n *\n * Implement memory and CPU constraints with {@link setInterruptHandler}\n * (called regularly while the interpreter runs), {@link setMemoryLimit}, and\n * {@link setMaxStackSize}.\n * Use {@link computeMemoryUsage} or {@link dumpMemoryUsage} to guide memory limit\n * tuning.\n *\n * Configure ES module loading with {@link setModuleLoader}.\n */\nexport class QuickJSRuntime extends UsingDisposable implements Disposable {\n /**\n * If this runtime was created as as part of a context, points to the context\n * associated with the runtime.\n *\n * If this runtime was created stand-alone, this may or may not contain a context.\n * A context here may be allocated if one is needed by the runtime, eg for {@link computeMemoryUsage}.\n */\n public context: QuickJSContext | undefined\n\n /** @private */\n protected module: EitherModule\n /** @private */\n protected memory: ModuleMemory\n /** @private */\n protected ffi: EitherFFI\n /** @private */\n protected rt: Lifetime<JSRuntimePointer>\n /** @private */\n protected callbacks: QuickJSModuleCallbacks\n /** @private */\n protected scope = new Scope()\n\n /** @private */\n protected contextMap = new Map<JSContextPointer, QuickJSContext>()\n /** @private */\n protected moduleLoader: JSModuleLoader | undefined\n /** @private */\n protected moduleNormalizer: JSModuleNormalizer | undefined\n\n /** @private */\n constructor(args: {\n module: EitherModule\n ffi: EitherFFI\n rt: Lifetime<JSRuntimePointer>\n callbacks: QuickJSModuleCallbacks\n ownedLifetimes?: Disposable[]\n }) {\n super()\n args.ownedLifetimes?.forEach((lifetime) => this.scope.manage(lifetime))\n this.module = args.module\n this.memory = new ModuleMemory(this.module)\n this.ffi = args.ffi\n this.rt = args.rt\n this.callbacks = args.callbacks\n this.scope.manage(this.rt)\n this.callbacks.setRuntimeCallbacks(this.rt.value, this.cToHostCallbacks)\n\n this.executePendingJobs = this.executePendingJobs.bind(this)\n\n if (QTS_DEBUG) {\n this.setDebugMode(true)\n }\n }\n\n get alive() {\n return this.scope.alive\n }\n\n dispose() {\n return this.scope.dispose()\n }\n\n /**\n * Create a new context within this runtime. Contexts have isolated globals,\n * but you can explicitly share objects between contexts with the same\n * runtime.\n *\n * You should dispose a created context before disposing this runtime.\n */\n newContext(options: ContextOptions = {}): QuickJSContext {\n const intrinsics = intrinsicsToFlags(options.intrinsics)\n const ctx = new Lifetime(\n options.contextPointer || this.ffi.QTS_NewContext(this.rt.value, intrinsics),\n undefined,\n (ctx_ptr) => {\n this.contextMap.delete(ctx_ptr)\n this.callbacks.deleteContext(ctx_ptr)\n this.ffi.QTS_FreeContext(ctx_ptr)\n },\n )\n\n const context = new QuickJSContext({\n module: this.module,\n ctx,\n ffi: this.ffi,\n rt: this.rt,\n ownedLifetimes: options.ownedLifetimes,\n runtime: this,\n callbacks: this.callbacks,\n })\n this.contextMap.set(ctx.value, context)\n\n return context\n }\n\n /**\n * Set the loader for EcmaScript modules requested by any context in this\n * runtime.\n *\n * The loader can be removed with {@link removeModuleLoader}.\n */\n setModuleLoader(moduleLoader: JSModuleLoader, moduleNormalizer?: JSModuleNormalizer): void {\n this.moduleLoader = moduleLoader\n this.moduleNormalizer = moduleNormalizer\n this.ffi.QTS_RuntimeEnableModuleLoader(this.rt.value, this.moduleNormalizer ? 1 : 0)\n }\n\n /**\n * Remove the the loader set by {@link setModuleLoader}. This disables module loading.\n */\n removeModuleLoader(): void {\n this.moduleLoader = undefined\n this.ffi.QTS_RuntimeDisableModuleLoader(this.rt.value)\n }\n\n // Runtime management -------------------------------------------------------\n\n /**\n * In QuickJS, promises and async functions create pendingJobs. These do not execute\n * immediately and need to be run by calling {@link executePendingJobs}.\n *\n * @return true if there is at least one pendingJob queued up.\n */\n hasPendingJob(): boolean {\n return Boolean(this.ffi.QTS_IsJobPending(this.rt.value))\n }\n\n private interruptHandler: InterruptHandler | undefined\n\n /**\n * Set a callback which is regularly called by the QuickJS engine when it is\n * executing code. This callback can be used to implement an execution\n * timeout.\n *\n * The interrupt handler can be removed with {@link removeInterruptHandler}.\n */\n setInterruptHandler(cb: InterruptHandler) {\n const prevInterruptHandler = this.interruptHandler\n this.interruptHandler = cb\n if (!prevInterruptHandler) {\n this.ffi.QTS_RuntimeEnableInterruptHandler(this.rt.value)\n }\n }\n\n /**\n * Remove the interrupt handler, if any.\n * See {@link setInterruptHandler}.\n */\n removeInterruptHandler() {\n if (this.interruptHandler) {\n this.ffi.QTS_RuntimeDisableInterruptHandler(this.rt.value)\n this.interruptHandler = undefined\n }\n }\n\n /**\n * Execute pendingJobs on the runtime until `maxJobsToExecute` jobs are\n * executed (default all pendingJobs), the queue is exhausted, or the runtime\n * encounters an exception.\n *\n * In QuickJS, promises and async functions *inside the runtime* create\n * pendingJobs. These do not execute immediately and need to triggered to run.\n *\n * @param maxJobsToExecute - When negative, run all pending jobs. Otherwise execute\n * at most `maxJobsToExecute` before returning.\n *\n * @return On success, the number of executed jobs. On error, the exception\n * that stopped execution, and the context it occurred in. Note that\n * executePendingJobs will not normally return errors thrown inside async\n * functions or rejected promises. Those errors are available by calling\n * {@link QuickJSContext#resolvePromise} on the promise handle returned by the async function.\n */\n executePendingJobs(maxJobsToExecute: number | void = -1): ExecutePendingJobsResult {\n const ctxPtrOut = this.memory.newMutablePointerArray<JSContextPointerPointer>(1)\n const valuePtr = this.ffi.QTS_ExecutePendingJob(\n this.rt.value,\n maxJobsToExecute ?? -1,\n ctxPtrOut.value.ptr,\n )\n\n const ctxPtr = ctxPtrOut.value.typedArray[0] as JSContextPointer\n ctxPtrOut.dispose()\n if (ctxPtr === 0) {\n // No jobs executed.\n this.ffi.QTS_FreeValuePointerRuntime(this.rt.value, valuePtr)\n return DisposableResult.success(0)\n }\n\n const context =\n this.contextMap.get(ctxPtr) ??\n this.newContext({\n contextPointer: ctxPtr,\n })\n\n const resultValue = context.getMemory(this.rt.value).heapValueHandle(valuePtr)\n const typeOfRet = context.typeof(resultValue)\n if (typeOfRet === \"number\") {\n const executedJobs = context.getNumber(resultValue)\n resultValue.dispose()\n return DisposableResult.success(executedJobs)\n } else {\n const error = Object.assign(resultValue as QuickJSHandle, { context })\n return DisposableResult.fail(error, (error) => context.unwrapResult(error))\n }\n }\n\n /**\n * Set the max memory this runtime can allocate.\n * To remove the limit, set to `-1`.\n */\n setMemoryLimit(limitBytes: number) {\n if (limitBytes < 0 && limitBytes !== -1) {\n throw new Error(\"Cannot set memory limit to negative number. To unset, pass -1\")\n }\n\n this.ffi.QTS_RuntimeSetMemoryLimit(this.rt.value, limitBytes)\n }\n\n /**\n * Compute memory usage for this runtime. Returns the result as a handle to a\n * JSValue object. Use {@link QuickJSContext#dump} to convert to a native object.\n * Calling this method will allocate more memory inside the runtime. The information\n * is accurate as of just before the call to `computeMemoryUsage`.\n * For a human-digestible representation, see {@link dumpMemoryUsage}.\n */\n computeMemoryUsage(): QuickJSHandle {\n const serviceContextMemory = this.getSystemContext().getMemory(this.rt.value)\n return serviceContextMemory.heapValueHandle(\n this.ffi.QTS_RuntimeComputeMemoryUsage(this.rt.value, serviceContextMemory.ctx.value),\n )\n }\n\n /**\n * @returns a human-readable description of memory usage in this runtime.\n * For programmatic access to this information, see {@link computeMemoryUsage}.\n */\n dumpMemoryUsage(): string {\n return this.memory.consumeHeapCharPointer(this.ffi.QTS_RuntimeDumpMemoryUsage(this.rt.value))\n }\n\n /**\n * Set the max stack size for this runtime, in bytes.\n * To remove the limit, set to `0`.\n */\n setMaxStackSize(stackSize: number) {\n if (stackSize < 0) {\n throw new Error(\"Cannot set memory limit to negative number. To unset, pass 0.\")\n }\n\n this.ffi.QTS_RuntimeSetMaxStackSize(this.rt.value, stackSize)\n }\n\n /**\n * Assert that `handle` is owned by this runtime.\n * @throws QuickJSWrongOwner if owned by a different runtime.\n */\n assertOwned(handle: QuickJSHandle) {\n if (handle.owner && handle.owner.rt !== this.rt) {\n throw new QuickJSWrongOwner(\n `Handle is not owned by this runtime: ${handle.owner.rt.value} != ${this.rt.value}`,\n )\n }\n }\n\n private _debugMode = false\n\n /**\n * Enable or disable debug logging.\n *\n * If this module is a DEBUG variant, more logs will be printed from the C\n * code.\n */\n setDebugMode(enabled: boolean) {\n this._debugMode = enabled\n if (this.ffi.DEBUG && this.rt.alive) {\n this.ffi.QTS_SetDebugLogEnabled(this.rt.value, enabled ? 1 : 0)\n }\n }\n\n /**\n * @returns true if debug logging is enabled\n */\n isDebugMode(): boolean {\n return this._debugMode\n }\n\n /**\n * In debug mode, log the result of calling `msg()`.\n *\n * We take a function instead of a log message to avoid expensive string\n * manipulation if debug logging is disabled.\n */\n debugLog(...msg: unknown[]) {\n if (this._debugMode) {\n console.log(\"quickjs-emscripten:\", ...msg)\n }\n }\n\n /** @private */\n [Symbol.for(\"nodejs.util.inspect.custom\")]() {\n if (!this.alive) {\n return `${this.constructor.name} { disposed }`\n }\n return `${this.constructor.name} { rt: ${this.rt.value} }`\n }\n\n private getSystemContext() {\n if (!this.context) {\n // We own this context and should dispose of it.\n this.context = this.scope.manage(this.newContext())\n }\n return this.context\n }\n\n private cToHostCallbacks: RuntimeCallbacks = {\n shouldInterrupt: (rt) => {\n if (rt !== this.rt.value) {\n throw new Error(\"QuickJSContext instance received C -> JS interrupt with mismatched rt\")\n }\n\n const fn = this.interruptHandler\n if (!fn) {\n throw new Error(\"QuickJSContext had no interrupt handler\")\n }\n\n return fn(this) ? 1 : 0\n },\n\n loadModuleSource: maybeAsyncFn(this, function* (awaited, rt, ctx, moduleName) {\n const moduleLoader = this.moduleLoader\n if (!moduleLoader) {\n throw new Error(\"Runtime has no module loader\")\n }\n\n if (rt !== this.rt.value) {\n throw new Error(\"Runtime pointer mismatch\")\n }\n\n const context =\n this.contextMap.get(ctx) ??\n this.newContext({\n contextPointer: ctx,\n })\n\n try {\n const result = yield* awaited(moduleLoader(moduleName, context))\n\n if (typeof result === \"object\" && \"error\" in result && result.error) {\n this.debugLog(\"cToHostLoadModule: loader returned error\", result.error)\n throw result.error\n }\n\n const moduleSource =\n typeof result === \"string\" ? result : \"value\" in result ? result.value : result\n\n return this.memory.newHeapCharPointer(moduleSource).value.ptr\n } catch (error) {\n this.debugLog(\"cToHostLoadModule: caught error\", error)\n context.throw(error as any)\n return 0 as BorrowedHeapCharPointer\n }\n }),\n\n normalizeModule: maybeAsyncFn(\n this,\n function* (awaited, rt, ctx, baseModuleName, moduleNameRequest) {\n const moduleNormalizer = this.moduleNormalizer\n if (!moduleNormalizer) {\n throw new Error(\"Runtime has no module normalizer\")\n }\n\n if (rt !== this.rt.value) {\n throw new Error(\"Runtime pointer mismatch\")\n }\n\n const context: QuickJSContext =\n this.contextMap.get(ctx) ??\n this.newContext({\n /* TODO: Does this happen? Are we responsible for disposing? I don't think so */\n contextPointer: ctx,\n })\n\n try {\n const result = yield* awaited(\n moduleNormalizer(baseModuleName, moduleNameRequest, context),\n )\n\n if (typeof result === \"object\" && \"error\" in result && result.error) {\n this.debugLog(\"cToHostNormalizeModule: normalizer returned error\", result.error)\n throw result.error\n }\n\n const name = typeof result === \"string\" ? result : result.value\n return context.getMemory(this.rt.value).newHeapCharPointer(name).value.ptr\n } catch (error) {\n this.debugLog(\"normalizeModule: caught error\", error)\n context.throw(error as any)\n return 0 as BorrowedHeapCharPointer\n }\n },\n ),\n }\n}\n","import type {\n Asyncify,\n AsyncifySleepResult,\n EitherModule,\n EmscriptenModuleCallbacks,\n BorrowedHeapCharPointer,\n JSContextPointer,\n JSRuntimePointer,\n JSValuePointer,\n EitherFFI,\n} from \"@componentor/quickjs-ffi-types\"\nimport type { QuickJSContext } from \"./context\"\nimport { debugLog } from \"./debug\"\nimport { QuickJSAsyncifyError, QuickJSAsyncifySuspended } from \"./errors\"\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nimport type { CustomizeVariantOptions } from \"./from-variant\"\nimport { Lifetime, Scope } from \"./lifetime\"\nimport type { InterruptHandler } from \"./runtime\"\nimport { QuickJSRuntime } from \"./runtime\"\nimport type { ContextOptions, JSModuleLoader, RuntimeOptions, RuntimeOptionsBase } from \"./types\"\nimport { concat } from \"./types\"\n\ntype EmscriptenCallback<BaseArgs extends any[], Result> = (\n ...args: [Asyncify | undefined, ...BaseArgs]\n) => Result | AsyncifySleepResult<Result>\ntype MaybeAsyncEmscriptenCallback<T extends EmscriptenCallback<any, any>> =\n T extends EmscriptenCallback<infer Args, infer Result>\n ? (...args: Args) => Result | Promise<Result>\n : never\ntype MaybeAsyncEmscriptenCallbacks = {\n [K in keyof EmscriptenModuleCallbacks]: MaybeAsyncEmscriptenCallback<EmscriptenModuleCallbacks[K]>\n}\n\n/**\n * @private\n */\nexport interface ContextCallbacks {\n callFunction: MaybeAsyncEmscriptenCallbacks[\"callFunction\"]\n}\n\n/**\n * @private\n */\nexport interface RuntimeCallbacks {\n shouldInterrupt: MaybeAsyncEmscriptenCallbacks[\"shouldInterrupt\"]\n loadModuleSource: MaybeAsyncEmscriptenCallbacks[\"loadModuleSource\"]\n normalizeModule: MaybeAsyncEmscriptenCallbacks[\"normalizeModule\"]\n}\n\nclass QuickJSEmscriptenModuleCallbacks implements EmscriptenModuleCallbacks {\n public callFunction: EmscriptenModuleCallbacks[\"callFunction\"]\n public shouldInterrupt: EmscriptenModuleCallbacks[\"shouldInterrupt\"]\n public loadModuleSource: EmscriptenModuleCallbacks[\"loadModuleSource\"]\n public normalizeModule: EmscriptenModuleCallbacks[\"normalizeModule\"]\n constructor(args: EmscriptenModuleCallbacks) {\n this.callFunction = args.callFunction\n this.shouldInterrupt = args.shouldInterrupt\n this.loadModuleSource = args.loadModuleSource\n this.normalizeModule = args.normalizeModule\n }\n}\n\n/**\n * Options for {@link QuickJSWASMModule#evalCode}.\n */\nexport interface ModuleEvalOptions {\n /**\n * Interrupt evaluation if `shouldInterrupt` returns `true`.\n * See {@link shouldInterruptAfterDeadline}.\n */\n shouldInterrupt?: InterruptHandler\n\n /**\n * Memory limit, in bytes, of WebAssembly heap memory used by the QuickJS VM.\n */\n memoryLimitBytes?: number\n\n /**\n * Stack size limit for this vm, in bytes\n * To remove the limit, set to `0`.\n */\n maxStackSizeBytes?: number\n\n /**\n * Module loader for any `import` statements or expressions.\n */\n moduleLoader?: JSModuleLoader\n}\n\n/**\n * We use static functions per module to dispatch runtime or context calls from\n * C to the host. This class manages the indirection from a specific runtime or\n * context pointer to the appropriate callback handler.\n *\n * @private\n */\nexport class QuickJSModuleCallbacks {\n private module: EitherModule\n private contextCallbacks = new Map<JSContextPointer, ContextCallbacks>()\n private runtimeCallbacks = new Map<JSRuntimePointer, RuntimeCallbacks>()\n\n constructor(module: EitherModule) {\n this.module = module\n this.module.callbacks = this.cToHostCallbacks\n }\n\n setRuntimeCallbacks(rt: JSRuntimePointer, callbacks: RuntimeCallbacks) {\n this.runtimeCallbacks.set(rt, callbacks)\n }\n\n deleteRuntime(rt: JSRuntimePointer) {\n this.runtimeCallbacks.delete(rt)\n }\n\n setContextCallbacks(ctx: JSContextPointer, callbacks: ContextCallbacks) {\n this.contextCallbacks.set(ctx, callbacks)\n }\n\n deleteContext(ctx: JSContextPointer) {\n this.contextCallbacks.delete(ctx)\n }\n\n private suspendedCount = 0\n private suspended: QuickJSAsyncifySuspended | undefined\n\n private handleAsyncify<T>(\n asyncify: Asyncify | undefined,\n fn: () => T | Promise<T>,\n ): T | AsyncifySleepResult<T> {\n if (asyncify) {\n // We must always call asyncify.handleSync around our function.\n // This allows asyncify to resume suspended execution on the second call.\n // Asyncify internally can detect sync behavior, and avoid suspending.\n return asyncify.handleSleep((done) => {\n try {\n const result = fn()\n if (!(result instanceof Promise)) {\n debugLog(\"asyncify.handleSleep: not suspending:\", result)\n done(result)\n return\n }\n\n // Is promise, we intend to suspend.\n if (this.suspended) {\n throw new QuickJSAsyncifyError(\n `Already suspended at: ${this.suspended.stack}\\nAttempted to suspend at:`,\n )\n } else {\n this.suspended = new QuickJSAsyncifySuspended(`(${this.suspendedCount++})`)\n debugLog(\"asyncify.handleSleep: suspending:\", this.suspended)\n }\n\n result.then(\n (resolvedResult) => {\n this.suspended = undefined\n debugLog(\"asyncify.handleSleep: resolved:\", resolvedResult)\n done(resolvedResult)\n },\n (error) => {\n debugLog(\"asyncify.handleSleep: rejected:\", error)\n console.error(\"QuickJS: cannot handle error in suspended function\", error)\n this.suspended = undefined\n },\n )\n } catch (error) {\n debugLog(\"asyncify.handleSleep: error:\", error)\n this.suspended = undefined\n throw error\n }\n })\n }\n\n // No asyncify - we should never return a promise.\n const value = fn()\n if (value instanceof Promise) {\n throw new Error(\"Promise return value not supported in non-asyncify context.\")\n }\n return value\n }\n\n private cToHostCallbacks = new QuickJSEmscriptenModuleCallbacks({\n callFunction: (asyncify, ctx, this_ptr, argc, argv, fn_id) =>\n this.handleAsyncify(asyncify, () => {\n try {\n const vm = this.contextCallbacks.get(ctx)\n if (!vm) {\n throw new Error(`QuickJSContext(ctx = ${ctx}) not found for C function call \"${fn_id}\"`)\n }\n return vm.callFunction(ctx, this_ptr, argc, argv, fn_id)\n } catch (error) {\n console.error(\"[C to host error: returning null]\", error)\n return 0 as JSValuePointer\n }\n }),\n\n shouldInterrupt: (asyncify, rt) =>\n this.handleAsyncify(asyncify, () => {\n try {\n const vm = this.runtimeCallbacks.get(rt)\n if (!vm) {\n throw new Error(`QuickJSRuntime(rt = ${rt}) not found for C interrupt`)\n }\n return vm.shouldInterrupt(rt)\n } catch (error) {\n console.error(\"[C to host interrupt: returning error]\", error)\n return 1\n }\n }),\n\n loadModuleSource: (asyncify, rt, ctx, moduleName) =>\n this.handleAsyncify(asyncify, () => {\n try {\n const runtimeCallbacks = this.runtimeCallbacks.get(rt)\n if (!runtimeCallbacks) {\n throw new Error(`QuickJSRuntime(rt = ${rt}) not found for C module loader`)\n }\n\n const loadModule = runtimeCallbacks.loadModuleSource\n if (!loadModule) {\n throw new Error(`QuickJSRuntime(rt = ${rt}) does not support module loading`)\n }\n return loadModule(rt, ctx, moduleName)\n } catch (error) {\n console.error(\"[C to host module loader error: returning null]\", error)\n return 0 as BorrowedHeapCharPointer\n }\n }),\n\n normalizeModule: (asyncify, rt, ctx, moduleBaseName, moduleName) =>\n this.handleAsyncify(asyncify, () => {\n try {\n const runtimeCallbacks = this.runtimeCallbacks.get(rt)\n if (!runtimeCallbacks) {\n throw new Error(`QuickJSRuntime(rt = ${rt}) not found for C module loader`)\n }\n\n const normalizeModule = runtimeCallbacks.normalizeModule\n if (!normalizeModule) {\n throw new Error(`QuickJSRuntime(rt = ${rt}) does not support module loading`)\n }\n return normalizeModule(rt, ctx, moduleBaseName, moduleName)\n } catch (error) {\n console.error(\"[C to host module loader error: returning null]\", error)\n return 0 as BorrowedHeapCharPointer\n }\n }),\n })\n}\n\n/**\n * Process RuntimeOptions and apply them to a QuickJSRuntime.\n * @private\n */\nexport function applyBaseRuntimeOptions(\n runtime: QuickJSRuntime,\n options: RuntimeOptionsBase,\n): void {\n if (options.interruptHandler) {\n runtime.setInterruptHandler(options.interruptHandler)\n }\n\n if (options.maxStackSizeBytes !== undefined) {\n runtime.setMaxStackSize(options.maxStackSizeBytes)\n }\n\n if (options.memoryLimitBytes !== undefined) {\n runtime.setMemoryLimit(options.memoryLimitBytes)\n }\n}\n\n/**\n * Process ModuleEvalOptions and apply them to a QuickJSRuntime.\n * @private\n */\nexport function applyModuleEvalRuntimeOptions<T extends QuickJSRuntime>(\n runtime: T,\n options: ModuleEvalOptions,\n) {\n if (options.moduleLoader) {\n runtime.setModuleLoader(options.moduleLoader)\n }\n\n if (options.shouldInterrupt) {\n runtime.setInterruptHandler(options.shouldInterrupt)\n }\n\n if (options.memoryLimitBytes !== undefined) {\n runtime.setMemoryLimit(options.memoryLimitBytes)\n }\n\n if (options.maxStackSizeBytes !== undefined) {\n runtime.setMaxStackSize(options.maxStackSizeBytes)\n }\n}\n\n/**\n * This class presents a Javascript interface to QuickJS, a Javascript interpreter\n * that supports EcmaScript 2020 (ES2020).\n *\n * It wraps a single WebAssembly module containing the QuickJS library and\n * associated helper C code. WebAssembly modules are completely isolated from\n * each other by the host's WebAssembly runtime. Separate WebAssembly modules\n * have the most isolation guarantees possible with this library.\n *\n * The simplest way to start running code is {@link evalCode}. This shortcut\n * method will evaluate Javascript safely and return the result as a native\n * Javascript value.\n *\n * For more control over the execution environment, or to interact with values\n * inside QuickJS, create a context with {@link newContext} or a runtime with\n * {@link newRuntime}.\n */\nexport class QuickJSWASMModule {\n /** @private */\n protected ffi: EitherFFI\n /** @private */\n protected callbacks: QuickJSModuleCallbacks\n /** @private */\n protected module: EitherModule\n\n /** @private */\n constructor(module: EitherModule, ffi: EitherFFI) {\n this.module = module\n this.ffi = ffi\n this.callbacks = new QuickJSModuleCallbacks(module)\n }\n\n /**\n * Get the underlying Emscripten WASM module.\n *\n * For WasmFS variants, this provides access to the FS API:\n * ```typescript\n * const wasmModule = quickjs.getWasmModule();\n * // Access WasmFS filesystem\n * wasmModule.FS.readFile('/path/to/file');\n * wasmModule.FS.writeFile('/path/to/file', data);\n * // Mount OPFS (browser only)\n * await wasmModule.mountOPFS?.('/opfs');\n * ```\n */\n getWasmModule(): EitherModule {\n return this.module\n }\n\n /**\n * Create a runtime.\n * Use the runtime to set limits on CPU and memory usage and configure module\n * loading for one or more {@link QuickJSContext}s inside the runtime.\n */\n newRuntime(options: RuntimeOptions = {}): QuickJSRuntime {\n const rt = new Lifetime(this.ffi.QTS_NewRuntime(), undefined, (rt_ptr) => {\n this.callbacks.deleteRuntime(rt_ptr)\n this.ffi.QTS_FreeRuntime(rt_ptr)\n })\n\n const runtime = new QuickJSRuntime({\n module: this.module,\n callbacks: this.callbacks,\n ffi: this.ffi,\n rt,\n })\n\n applyBaseRuntimeOptions(runtime, options)\n\n if (options.moduleLoader) {\n runtime.setModuleLoader(options.moduleLoader)\n }\n\n return runtime\n }\n\n /**\n * A simplified API to create a new {@link QuickJSRuntime} and a\n * {@link QuickJSContext} inside that runtime at the same time. The runtime will\n * be disposed when the context is disposed.\n */\n newContext(options: ContextOptions = {}): QuickJSContext {\n const runtime = this.newRuntime()\n const context = runtime.newContext({\n ...options,\n ownedLifetimes: concat(runtime, options.ownedLifetimes),\n })\n runtime.context = context\n return context\n }\n\n /**\n * One-off evaluate code without needing to create a {@link QuickJSRuntime} or\n * {@link QuickJSContext} explicitly.\n *\n * To protect against infinite loops, use the `shouldInterrupt` option. The\n * {@link shouldInterruptAfterDeadline} function will create a time-based deadline.\n *\n * If you need more control over how the code executes, create a\n * {@link QuickJSRuntime} (with {@link newRuntime}) or a {@link QuickJSContext} (with\n * {@link newContext} or {@link QuickJSRuntime#newContext}), and use its\n * {@link QuickJSContext#evalCode} method.\n *\n * Asynchronous callbacks may not run during the first call to `evalCode`. If\n * you need to work with async code inside QuickJS, create a runtime and use\n * {@link QuickJSRuntime#executePendingJobs}.\n *\n * @returns The result is coerced to a native Javascript value using JSON\n * serialization, so properties and values unsupported by JSON will be dropped.\n *\n * @throws If `code` throws during evaluation, the exception will be\n * converted into a native Javascript value and thrown.\n *\n * @throws if `options.shouldInterrupt` interrupted execution, will throw a Error\n * with name `\"InternalError\"` and message `\"interrupted\"`.\n */\n evalCode(code: string, options: ModuleEvalOptions = {}): unknown {\n return Scope.withScope((scope) => {\n const vm = scope.manage(this.newContext())\n\n applyModuleEvalRuntimeOptions(vm.runtime, options)\n const result = vm.evalCode(code, \"eval.js\")\n\n if (options.memoryLimitBytes !== undefined) {\n // Remove memory limit so we can dump the result without exceeding it.\n vm.runtime.setMemoryLimit(-1)\n }\n\n if (result.error) {\n const error = vm.dump(scope.manage(result.error))\n throw error\n }\n\n const value = vm.dump(scope.manage(result.value))\n return value\n })\n }\n\n /**\n * Retrieve the WebAssembly memory used by this QuickJS module.\n * Use this access very carefully - you are responsible for safe interaction with the memory.\n *\n * To supply a custom, pre-initialized memory to QuickJS, create a new variant\n * and provide the {@link CustomizeVariantOptions#wasmMemory} option.\n *\n * @experimental\n */\n getWasmMemory(): WebAssembly.Memory {\n const extensions = this.module.quickjsEmscriptenInit?.(() => {})\n const memory = extensions?.getWasmMemory?.()\n if (!memory) {\n throw new Error(`Variant does not support getting WebAssembly.Memory`)\n }\n return memory\n }\n\n /**\n * Get a low-level interface to the QuickJS functions in this WebAssembly\n * module.\n * @experimental\n * @unstable No warranty is provided with this API. It could change at any time.\n * @private\n */\n getFFI(): EitherFFI {\n return this.ffi\n }\n}\n"],"mappings":"0IAIO,IAAI,UAAY,GAQhB,SAAS,aAAa,QAAmB,GAAM,CACpD,UAAY,OACd,CAUO,SAAS,YAAY,KAAa,CACnC,WACF,QAAQ,IAAI,sBAAuB,GAAG,IAAI,CAE9C,CC5BA,imBAKO,IAAM,mBAAN,cAAiC,KAAM,CAE5C,YACS,MACA,QACP,CACA,IAAM,QACJ,OAAO,OAAU,UAAY,OAAS,YAAa,MAC/C,OAAO,MAAM,OAAO,EACpB,OAAO,KAAK,EAClB,MAAM,OAAO,EAPN,iBACA,qBAHT,UAAO,oBAUP,CACF,EAEa,kBAAN,cAAgC,KAAM,CAAtC,kCACL,UAAO,oBACT,EAEa,oBAAN,cAAkC,KAAM,CAAxC,kCACL,UAAO,sBACT,EAEa,sBAAN,cAAoC,KAAM,CAA1C,kCACL,UAAO,wBACT,EAEa,qBAAN,cAAmC,KAAM,CAAzC,kCACL,UAAO,uBACT,EAEa,yBAAN,cAAuC,KAAM,CAA7C,kCACL,UAAO,2BACT,EAEa,0BAAN,cAAwC,KAAM,CAA9C,kCACL,UAAO,4BACT,EAEa,6BAAN,cAA2C,KAAM,CAAjD,kCACL,UAAO,+BACT,EAEa,wBAAN,cAAsC,SAAU,CAAhD,kCACL,UAAO,0BACT,EAEa,sBAAN,cAAoC,KA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AAM,EACnC,KAAK,IAAI,gBAAgB,MAAM,CACjC,CAAC,EAEK,QAAU,IAAI,eAAe,CACjC,OAAQ,KAAK,OACb,UAAW,KAAK,UAChB,IAAK,KAAK,IACV,EACF,CAAC,EAED,+BAAwB,QAAS,OAAO,EAEpC,QAAQ,cACV,QAAQ,gBAAgB,QAAQ,YAAY,EAGvC,OACT,CAOA,WAAW,QAA0B,CAAC,EAAmB,CACvD,IAAM,QAAU,KAAK,WAAW,EAC1B,QAAU,QAAQ,WAAW,CACjC,GAAG,QACH,eAAgB,OAAO,QAAS,QAAQ,cAAc,CACxD,CAAC,EACD,eAAQ,QAAU,QACX,OACT,CA2BA,SAAS,KAAc,QAA6B,CAAC,EAAY,CAC/D,OAAO,MAAM,UAAW,OAAU,CAChC,IAAM,GAAK,MAAM,OAAO,KAAK,WAAW,CAAC,EAEzC,8BAA8B,GAAG,QAAS,OAAO,EACjD,IAAM,OAAS,GAAG,SAAS,KAAM,SAAS,EAO1C,GALI,QAAQ,mBAAqB,QAE/B,GAAG,QAAQ,eAAe,EAAE,EAG1B,OAAO,MAET,MADc,GAAG,KAAK,MAAM,OAAO,OAAO,KAAK,CAAC,EAKlD,OADc,GAAG,KAAK,MAAM,OAAO,OAAO,KAAK,CAAC,CAElD,CAAC,CACH,CAWA,eAAoC,CAElC,IAAM,OADa,KAAK,OAAO,wBAAwB,IAAM,CAAC,CAAC,GACpC,gBAAgB,EAC3C,GAAI,CAAC,OACH,MAAM,IAAI,MAAM,qDAAqD,EAEvE,OAAO,MACT,CASA,QAAoB,CAClB,OAAO,KAAK,GACd,CACF","names":["ptr","bigIntHandle","ptr","error","error"]}
@@ -1,2 +1,2 @@
1
- import{Lifetime,QuickJSContext,QuickJSNotImplemented,QuickJSRuntime,QuickJSWASMModule,Scope,applyBaseRuntimeOptions,applyModuleEvalRuntimeOptions,evalOptionsToFlags,intrinsicsToFlags}from"./chunk-IBRLVSKW.mjs";var QuickJSAsyncContext=class extends QuickJSContext{async evalCodeAsync(code,filename="eval.js",options){let detectModule=options===void 0?1:0,flags=evalOptionsToFlags(options),resultPtr=0;try{resultPtr=await this.memory.newHeapCharPointer(code).consume(charHandle=>this.ffi.QTS_Eval_MaybeAsync(this.ctx.value,charHandle.value.ptr,charHandle.value.strlen,filename,detectModule,flags))}catch(error){throw this.runtime.debugLog("QTS_Eval_MaybeAsync threw",error),error}let errorPtr=this.ffi.QTS_ResolveException(this.ctx.value,resultPtr);return errorPtr?(this.ffi.QTS_FreeValuePointer(this.ctx.value,resultPtr),this.fail(this.memory.heapValueHandle(errorPtr))):this.success(this.memory.heapValueHandle(resultPtr))}newAsyncifiedFunction(name,fn){return this.newFunction(name,fn)}};var QuickJSAsyncRuntime=class extends QuickJSRuntime{constructor(args){super(args)}newContext(options={}){let intrinsics=intrinsicsToFlags(options.intrinsics),ctx=new Lifetime(this.ffi.QTS_NewContext(this.rt.value,intrinsics),void 0,ctx_ptr=>{this.contextMap.delete(ctx_ptr),this.callbacks.deleteContext(ctx_ptr),this.ffi.QTS_FreeContext(ctx_ptr)}),context=new QuickJSAsyncContext({module:this.module,ctx,ffi:this.ffi,rt:this.rt,ownedLifetimes:[],runtime:this,callbacks:this.callbacks});return this.contextMap.set(ctx.value,context),context}setModuleLoader(moduleLoader,moduleNormalizer){super.setModuleLoader(moduleLoader,moduleNormalizer)}setMaxStackSize(stackSize){return super.setMaxStackSize(stackSize)}};var QuickJSAsyncWASMModule=class extends QuickJSWASMModule{constructor(module,ffi){super(module,ffi),this.ffi=ffi,this.module=module}newRuntime(options={}){let rt=new Lifetime(this.ffi.QTS_NewRuntime(),void 0,rt_ptr=>{this.callbacks.deleteRuntime(rt_ptr),this.ffi.QTS_FreeRuntime(rt_ptr)}),runtime=new QuickJSAsyncRuntime({module:this.module,ffi:this.ffi,rt,callbacks:this.callbacks});return applyBaseRuntimeOptions(runtime,options),options.moduleLoader&&runtime.setModuleLoader(options.moduleLoader),runtime}newContext(options={}){let runtime=this.newRuntime(),lifetimes=options.ownedLifetimes?options.ownedLifetimes.concat([runtime]):[runtime],context=runtime.newContext({...options,ownedLifetimes:lifetimes});return runtime.context=context,context}evalCode(){throw new QuickJSNotImplemented("QuickJSWASMModuleAsyncify.evalCode: use evalCodeAsync instead")}evalCodeAsync(code,options){return Scope.withScopeAsync(async scope=>{let vm=scope.manage(this.newContext());applyModuleEvalRuntimeOptions(vm.runtime,options);let result=await vm.evalCodeAsync(code,"eval.js");if(options.memoryLimitBytes!==void 0&&vm.runtime.setMemoryLimit(-1),result.error)throw vm.dump(scope.manage(result.error));return vm.dump(scope.manage(result.value))})}};export{QuickJSAsyncContext,QuickJSAsyncRuntime,QuickJSAsyncWASMModule};
2
- //# sourceMappingURL=chunk-TKX7BUWH.mjs.map
1
+ import{Lifetime,QuickJSContext,QuickJSNotImplemented,QuickJSRuntime,QuickJSWASMModule,Scope,applyBaseRuntimeOptions,applyModuleEvalRuntimeOptions,evalOptionsToFlags,intrinsicsToFlags}from"./chunk-ARBNLGDU.mjs";var QuickJSAsyncContext=class extends QuickJSContext{async evalCodeAsync(code,filename="eval.js",options){let detectModule=options===void 0?1:0,flags=evalOptionsToFlags(options),resultPtr=0;try{resultPtr=await this.memory.newHeapCharPointer(code).consume(charHandle=>this.ffi.QTS_Eval_MaybeAsync(this.ctx.value,charHandle.value.ptr,charHandle.value.strlen,filename,detectModule,flags))}catch(error){throw this.runtime.debugLog("QTS_Eval_MaybeAsync threw",error),error}let errorPtr=this.ffi.QTS_ResolveException(this.ctx.value,resultPtr);return errorPtr?(this.ffi.QTS_FreeValuePointer(this.ctx.value,resultPtr),this.fail(this.memory.heapValueHandle(errorPtr))):this.success(this.memory.heapValueHandle(resultPtr))}newAsyncifiedFunction(name,fn){return this.newFunction(name,fn)}};var QuickJSAsyncRuntime=class extends QuickJSRuntime{constructor(args){super(args)}newContext(options={}){let intrinsics=intrinsicsToFlags(options.intrinsics),ctx=new Lifetime(this.ffi.QTS_NewContext(this.rt.value,intrinsics),void 0,ctx_ptr=>{this.contextMap.delete(ctx_ptr),this.callbacks.deleteContext(ctx_ptr),this.ffi.QTS_FreeContext(ctx_ptr)}),context=new QuickJSAsyncContext({module:this.module,ctx,ffi:this.ffi,rt:this.rt,ownedLifetimes:[],runtime:this,callbacks:this.callbacks});return this.contextMap.set(ctx.value,context),context}setModuleLoader(moduleLoader,moduleNormalizer){super.setModuleLoader(moduleLoader,moduleNormalizer)}setMaxStackSize(stackSize){return super.setMaxStackSize(stackSize)}};var QuickJSAsyncWASMModule=class extends QuickJSWASMModule{constructor(module,ffi){super(module,ffi),this.ffi=ffi,this.module=module}newRuntime(options={}){let rt=new Lifetime(this.ffi.QTS_NewRuntime(),void 0,rt_ptr=>{this.callbacks.deleteRuntime(rt_ptr),this.ffi.QTS_FreeRuntime(rt_ptr)}),runtime=new QuickJSAsyncRuntime({module:this.module,ffi:this.ffi,rt,callbacks:this.callbacks});return applyBaseRuntimeOptions(runtime,options),options.moduleLoader&&runtime.setModuleLoader(options.moduleLoader),runtime}newContext(options={}){let runtime=this.newRuntime(),lifetimes=options.ownedLifetimes?options.ownedLifetimes.concat([runtime]):[runtime],context=runtime.newContext({...options,ownedLifetimes:lifetimes});return runtime.context=context,context}evalCode(){throw new QuickJSNotImplemented("QuickJSWASMModuleAsyncify.evalCode: use evalCodeAsync instead")}evalCodeAsync(code,options){return Scope.withScopeAsync(async scope=>{let vm=scope.manage(this.newContext());applyModuleEvalRuntimeOptions(vm.runtime,options);let result=await vm.evalCodeAsync(code,"eval.js");if(options.memoryLimitBytes!==void 0&&vm.runtime.setMemoryLimit(-1),result.error)throw vm.dump(scope.manage(result.error));return vm.dump(scope.manage(result.value))})}};export{QuickJSAsyncContext,QuickJSAsyncRuntime,QuickJSAsyncWASMModule};
2
+ //# sourceMappingURL=chunk-HS5GHCLP.mjs.map