### Install quickjs-emscripten-core and a release sync variant Source: https://github.com/justjake/quickjs-emscripten/blob/main/README.md This command installs the core quickjs-emscripten library and a specific release sync WASM variant, resulting in a smaller total installation size compared to the main package. ```bash yarn add quickjs-emscripten-core @jitl/quickjs-wasmfile-release-sync du -h node_modules # 640K node_modules/@jitl/quickjs-wasmfile-release-sync # 80K node_modules/@jitl/quickjs-ffi-types # 588K node_modules/quickjs-emscripten-core # 1.3M node_modules ``` -------------------------------- ### C Code Example with Exported FFI Function Source: https://github.com/justjake/quickjs-emscripten/blob/main/CLAUDE.md Illustrates C code organization with section comments, forward declarations, internal helper functions, and exported FFI functions. Demonstrates error checking using JS_IsException. ```c // ---------------------------------------------------------------------------- // Section Name // Forward declaration static JSValue qts_helper_function(JSContext *ctx, JSValueConst obj); // Internal helper - not exported static bool qts_check_something(JSContext *ctx, JSValueConst obj) { if (!JS_IsObject(obj)) return false; // ... implementation return true; } // Exported FFI function JSValue *QTS_DoSomething(JSContext *ctx, JSValueConst *obj) { JSValue result = qts_helper_function(ctx, *obj); if (JS_IsException(result)) { return jsvalue_to_heap(JS_EXCEPTION); } return jsvalue_to_heap(result); } ``` -------------------------------- ### Log to stdout with console.log Source: https://github.com/justjake/quickjs-emscripten/blob/main/doc/quickjs-emscripten-core/interfaces/CustomizeVariantOptions.md Example of using console.log to print formatted messages to stdout. ```js const count = 5; console.log('count: %d', count); // Prints: count: 5, to stdout console.log('count:', count); // Prints: count: 5, to stdout ``` -------------------------------- ### Import and Initialize QuickJS Async WASM Module Source: https://github.com/justjake/quickjs-emscripten/blob/main/doc/@jitl/quickjs-singlefile-cjs-release-asyncify/README.md Import the variant and initialize the QuickJS WASM module. This setup is for asynchronous operations and requires `quickjs-emscripten-core`. ```typescript import variant from "@jitl/quickjs-singlefile-cjs-release-asyncify" import { newQuickJSAsyncWASMModuleFromVariant } from "quickjs-emscripten-core" const QuickJS = await newQuickJSAsyncWASMModuleFromVariant(variant) ``` -------------------------------- ### getQuickJS() Source: https://github.com/justjake/quickjs-emscripten/blob/main/doc/quickjs-emscripten/functions/getQuickJS.md Get a shared singleton QuickJSWASMModule. Use this to evaluate code or create Javascript environments. This is the top-level entrypoint for the quickjs-emscripten library. ```APIDOC ## getQuickJS() ### Description Get a shared singleton [QuickJSWASMModule](../classes/QuickJSWASMModule.md). Use this to evaluate code or create Javascript environments. This is the top-level entrypoint for the quickjs-emscripten library. If you need strictest possible isolation guarantees, you may create a separate [QuickJSWASMModule](../classes/QuickJSWASMModule.md) via [newQuickJSWASMModule](newQuickJSWASMModule.md). To work with the asyncified version of this library, see these functions: * [newAsyncRuntime](newAsyncRuntime.md). * [newAsyncContext](newAsyncContext.md). * [newQuickJSAsyncWASMModule](newQuickJSAsyncWASMModule.md). ### Method GET ### Endpoint /getQuickJS ### Returns `Promise`<[`QuickJSWASMModule`](../classes/QuickJSWASMModule.md)> ### Response Example { "example": "Promise" } ``` -------------------------------- ### Import quickjs-wasmfile-release-sync Source: https://github.com/justjake/quickjs-emscripten/blob/main/doc/@jitl/quickjs-wasmfile-release-sync/README.md Import the WASM variant and initialize the QuickJS WASM module. This setup is suitable for environments supporting async module loading. ```typescript import variant from "@jitl/quickjs-wasmfile-release-sync" import { newQuickJSWASMModuleFromVariant } from "quickjs-emscripten-core" const QuickJS = await newQuickJSWASMModuleFromVariant(variant) ``` -------------------------------- ### Import QuickJS WASM Module Source: https://github.com/justjake/quickjs-emscripten/blob/main/doc/@jitl/quickjs-ng-wasmfile-release-sync/README.md Import the WASM variant and initialize the QuickJS WASM module. Ensure quickjs-emscripten-core is installed. ```typescript import variant from "@jitl/quickjs-ng-wasmfile-release-sync" import { newQuickJSWASMModuleFromVariant } from "quickjs-emscripten-core" const QuickJS = await newQuickJSWASMModuleFromVariant(variant) ``` -------------------------------- ### Import and Initialize QuickJS WASM Module Source: https://github.com/justjake/quickjs-emscripten/blob/main/doc/@jitl/quickjs-singlefile-cjs-debug-sync/README.md Import the CommonJS variant and initialize the QuickJS WASM module. This setup is suitable for environments where a single-file module is preferred. ```typescript import variant from "@jitl/quickjs-singlefile-cjs-debug-sync" import { newQuickJSWASMModuleFromVariant } from "quickjs-emscripten-core" const QuickJS = await newQuickJSWASMModuleFromVariant(variant) ``` -------------------------------- ### QuickJS C API Value Ownership Example Source: https://github.com/justjake/quickjs-emscripten/blob/main/CLAUDE.md Illustrates the correct and incorrect ways to handle JSValue ownership in QuickJS C API. Avoid double-freeing by understanding which functions consume or duplicate values. ```c // WRONG - double free! JSValue val = JS_NewString(ctx, "hello"); JS_DefinePropertyValueStr(ctx, obj, "name", val, JS_PROP_CONFIGURABLE); JS_FreeValue(ctx, val); // BUG: val was already consumed! // CORRECT JSValue val = JS_NewString(ctx, "hello"); JS_DefinePropertyValueStr(ctx, obj, "name", val, JS_PROP_CONFIGURABLE); // No JS_FreeValue needed - value is consumed ``` -------------------------------- ### Initialize and execute nested QuickJS context Source: https://github.com/justjake/quickjs-emscripten/blob/main/packages/quickjs-for-quickjs/README.md Demonstrates setting up a host QuickJS context, configuring a module loader to provide the guest library, and executing code within the nested environment. ```javascript // nodejs-host.mjs import fs from "node:fs/promises" import module from "node:module" import { getQuickJS, setUpContext } from "quickjs-for-quickjs" // get quickjs source code const require = module.createRequire(import.meta.url) const quickjsSource = await fs.readFile(require.resolve("quickjs-for-quickjs"), "utf8") // create the host QuickJS context const QuickJS = await getQuickJS() const context = QuickJS.createContext() // inject console.log, which is required for quickjs-for-quickjs to work setUpContext(context) // allow the host QuickJS to import quickjs-for-quickjs module context.runtime.setModuleLoader((name) => { if (name === "quickjs-for-quickjs") { return quickjsSource } throw new Error(`Module not found: ${name}`) }) const quickjsHost = ` // import and create inner QuickJS guest context import { getQuickJS } from "quickjs-for-quickjs" const context = await getQuickJS().then(mod => mod.createContext()) // eval some code in the inner context const innerResult = context.evalCode('1 + 2', "quickjs-guest.mjs").unwrap() // export the result export const result = innerResult.consume(context.dump) ` // eval the quickjs host const handle = context.evalCode(quickjsHost, "quickjs-host.mjs").unwrap() // get the result context.runtime.executePendingJob() const result = context.unwrapResult(context.getPromiseState(handle)) console.log(result.consume(context.dump)) ``` -------------------------------- ### QTS_GetArrayBufferLength Source: https://github.com/justjake/quickjs-emscripten/blob/main/doc/@jitl/quickjs-ffi-types/interfaces/QuickJSAsyncFFI.md Gets the length of an ArrayBuffer. ```APIDOC ## QTS_GetArrayBufferLength ### Description Returns the length of an ArrayBuffer object. ### Parameters #### Path Parameters - **ctx** (JSContextPointer) - Required - The context pointer. - **data** (JSValuePointer | JSValueConstPointer) - Required - The ArrayBuffer JS value pointer. ### Response - **number** - The length of the buffer. ``` -------------------------------- ### Initialize QuickJS Module Source: https://github.com/justjake/quickjs-emscripten/blob/main/packages/quickjs-emscripten-core/README.md Demonstrates importing a variant and creating a QuickJS module instance. ```typescript // 1. Import a QuickJS module constructor function from quickjs-emscripten-core import { newQuickJSWASMModuleFromVariant } from "quickjs-emscripten-core" // 2. Import a variant suitable for your use case. For example, if you only care to // target with the fastest execution speed, import the release build variant import releaseVariant from "@jitl/quickjs-singlefile-cjs-release-sync" // 3. Create the "QuickJS" module that presents the quickjs-emscripten API. // Export and use in other files, or consume directly. const QuickJS = await newQuickJSWASMModuleFromVariant(releaseVariant) ``` -------------------------------- ### Expose host APIs to QuickJS Source: https://github.com/justjake/quickjs-emscripten/blob/main/README.md Demonstrates how to create host-side functions and objects, then attach them to the QuickJS global object. ```typescript const vm = QuickJS.newContext() // `console.log` const logHandle = vm.newFunction("log", (...args) => { const nativeArgs = args.map(vm.dump) console.log("QuickJS:", ...nativeArgs) }) // Partially implement `console` object const consoleHandle = vm.newObject() vm.setProp(consoleHandle, "log", logHandle) vm.setProp(vm.global, "console", consoleHandle) consoleHandle.dispose() logHandle.dispose() vm.unwrapResult(vm.evalCode(`console.log("Hello from QuickJS!")`)).dispose() ``` -------------------------------- ### Get Shared WASM Module with getQuickJS Source: https://context7.com/justjake/quickjs-emscripten/llms.txt The main entry point to get a shared QuickJSWASMModule singleton for evaluating code or creating JavaScript environments. Supports simple one-off evaluations and evaluations with timeout and memory limits. ```typescript import { getQuickJS } from "quickjs-emscripten" async function main() { const QuickJS = await getQuickJS() // Simple one-off evaluation const result = QuickJS.evalCode("1 + 2 + 3") console.log(result) // 6 // With timeout protection const safeResult = QuickJS.evalCode("while(true) {}", { shouldInterrupt: () => Date.now() > deadline, memoryLimitBytes: 1024 * 1024, // 1MB limit }) } main() ``` -------------------------------- ### QTS_Typeof() Source: https://github.com/justjake/quickjs-emscripten/blob/main/doc/quickjs-emscripten/interfaces/QuickJSFFI.md Gets the type of a JavaScript value. ```APIDOC ## QTS_Typeof() ### Description Gets the type of a JavaScript value. ### Method N/A (Function Signature) ### Endpoint N/A ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example N/A ### Response #### Success Response (200) N/A #### Response Example N/A ### Function Signature `QTS_Typeof(ctx, value) => OwnedHeapCharPointer` ### Parameters - **ctx** (`JSContextPointer`) - The JavaScript context. - **value** (`JSValuePointer` | `JSValueConstPointer`) - The JavaScript value to check. ### Returns [`OwnedHeapCharPointer`](../type-aliases/OwnedHeapCharPointer.md) - A pointer to a heap-allocated C string representing the type. ``` -------------------------------- ### RuntimeOptionsBase Interface Source: https://github.com/justjake/quickjs-emscripten/blob/main/doc/quickjs-emscripten-core/interfaces/RuntimeOptionsBase.md Configuration options for initializing a QuickJS runtime. ```APIDOC ## RuntimeOptionsBase Interface ### Description Defines the base configuration options for a QuickJS runtime instance. ### Properties - **gcThreshold** (undefined) - Optional - Garbage collection threshold. - **interruptHandler** (InterruptHandler) - Optional - Function to handle runtime interrupts. - **maxStackSizeBytes** (number) - Optional - Maximum stack size in bytes. - **memoryLimitBytes** (number) - Optional - Memory limit in bytes. - **promiseRejectionHandler** (undefined) - Optional - Handler for unhandled promise rejections. - **runtimeInfo** (undefined) - Optional - Metadata or info about the runtime. - **sharedArrayBufferFunctions** (undefined) - Optional - Functions for SharedArrayBuffer support. ``` -------------------------------- ### GET value Source: https://github.com/justjake/quickjs-emscripten/blob/main/doc/quickjs-emscripten/classes/StaticLifetime.md Retrieves the value protected by the lifetime. ```APIDOC ## GET value ### Description Returns the value protected by this Lifetime. Note that you must not retain this value as it may become invalid. ### Returns - **T** - The protected value. ### Throws - Throws an error if the lifetime has already been disposed. ``` -------------------------------- ### Create and Use a QuickJS Context Source: https://github.com/justjake/quickjs-emscripten/blob/main/README.md Demonstrates creating a new QuickJS context, defining a native function, exposing it to the JavaScript global scope, and evaluating JavaScript code that calls the function. Remember to dispose of handles and the context when done. ```typescript const vm = QuickJS.newContext() let state = 0 const fnHandle = vm.newFunction("nextId", () => { return vm.newNumber(++state) }) vm.setProp(vm.global, "nextId", fnHandle) fnHandle.dispose() const nextId = vm.unwrapResult(vm.evalCode(`nextId(); nextId(); nextId()`)) console.log("vm result:", vm.getNumber(nextId), "native state:", state) nextId.dispose() vm.dispose() ``` -------------------------------- ### QTS_GetHostRefId() Source: https://github.com/justjake/quickjs-emscripten/blob/main/doc/@jitl/quickjs-ffi-types/interfaces/QuickJSAsyncFFI.md Gets the host reference ID for a given JSValue. ```APIDOC ## QTS_GetHostRefId() ### Description Gets the host reference ID for a given JSValue. ### Method N/A (Function Call) ### Endpoint N/A ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example N/A ### Response #### Success Response (200) - **value** (JSValuePointer | JSValueConstPointer) - The JSValue to get the host reference ID for. #### Response Example ```json { "return_type": "HostRefId" } ``` ``` -------------------------------- ### QTS_NewContext Source: https://github.com/justjake/quickjs-emscripten/blob/main/doc/@jitl/quickjs-ffi-types/interfaces/QuickJSAsyncFFI.md Initializes a new JSContext. ```APIDOC ## QTS_NewContext ### Description Creates a new JSContext within the specified runtime. ### Parameters - **rt** (JSRuntimePointer) - Required - **intrinsics** (IntrinsicsFlags) - Required ### Response - **Returns** (JSContextPointer) - Pointer to the new context. ``` -------------------------------- ### Get Undefined Handle Source: https://github.com/justjake/quickjs-emscripten/blob/main/doc/quickjs-emscripten/classes/QuickJSAsyncContext.md Retrieves a handle to the JavaScript undefined value. ```typescript get undefined(): QuickJSHandle ``` -------------------------------- ### Initialize QuickJS WASM Modules Source: https://github.com/justjake/quickjs-emscripten/blob/main/README.md Demonstrates initializing different build variants of QuickJS WASM modules and running a simple evaluation. Use `newQuickJSWASMModule` for sync variants and `newQuickJSAsyncWASMModule` for async variants. Remember to dispose of the VM and module when done. ```typescript import { newQuickJSWASMModule, newQuickJSAsyncWASMModule, RELEASE_SYNC, DEBUG_SYNC, RELEASE_ASYNC, DEBUG_ASYNC, } from "quickjs-emscripten" const QuickJSReleaseSync = await newQuickJSWASMModule(RELEASE_SYNC) const QuickJSDebugSync = await newQuickJSWASMModule(DEBUG_SYNC) const QuickJSReleaseAsync = await newQuickJSAsyncWASMModule(RELEASE_ASYNC) const QuickJSDebugAsync = await newQuickJSAsyncWASMModule(DEBUG_ASYNC) for (const quickjs of [ QuickJSReleaseSync, QuickJSDebugSync, QuickJSReleaseAsync, QuickJSDebugAsync, ]) { const vm = quickjs.newContext() const result = vm.unwrapResult(vm.evalCode("1 + 1")).consume(vm.getNumber) console.log(result) vm.dispose() quickjs.dispose() } ``` -------------------------------- ### Get True Handle Source: https://github.com/justjake/quickjs-emscripten/blob/main/doc/quickjs-emscripten/classes/QuickJSAsyncContext.md Retrieves a handle to the JavaScript true value. ```typescript get true(): QuickJSHandle ``` -------------------------------- ### Get Null Handle Source: https://github.com/justjake/quickjs-emscripten/blob/main/doc/quickjs-emscripten/classes/QuickJSAsyncContext.md Retrieves a handle to the JavaScript null value. ```typescript get null(): QuickJSHandle ``` -------------------------------- ### ContextOptions Interface Source: https://github.com/justjake/quickjs-emscripten/blob/main/doc/quickjs-emscripten-core/interfaces/ContextOptions.md Configuration options for initializing a new QuickJS context, allowing control over built-in objects and language features. ```APIDOC ## ContextOptions Interface ### Description Options for creating a QuickJSContext or QuickJSAsyncContext. Passed to QuickJSRuntime#newContext. ### Properties - **intrinsics** (Intrinsics) - Optional - Defines which built-in objects and language features to enable. If unset, default intrinsics are used. Pass an empty array to omit all intrinsics. ### Usage Example ```ts const contextWithoutDateOrEval = runtime.newContext({ intrinsics: { ...DefaultIntrinsics, Date: false, } }) ``` ``` -------------------------------- ### QTS_NewRuntime Source: https://github.com/justjake/quickjs-emscripten/blob/main/doc/@jitl/quickjs-ffi-types/interfaces/QuickJSAsyncFFI.md Creates a new QuickJS runtime. ```APIDOC ## QTS_NewRuntime ### Description Creates a new QuickJS runtime. ### Response - **Returns** (JSRuntimePointer) - The pointer to the new runtime. ``` -------------------------------- ### Lifetime Value Access Source: https://github.com/justjake/quickjs-emscripten/blob/main/doc/quickjs-emscripten/classes/Lifetime.md Methods to get the protected value or its owner from a Lifetime object. ```APIDOC ## GET /lifetime/value ### Description Retrieves the value protected by this Lifetime. ### Method GET ### Endpoint /lifetime/value ### Parameters None ### Request Body None ### Request Example None ### Response #### Success Response (200) - **value** (T) - The protected value. #### Response Example ```json { "value": "your_value" } ``` ## GET /lifetime/owner ### Description Retrieves the owner of this Lifetime. ### Method GET ### Endpoint /lifetime/owner ### Parameters None ### Request Body None ### Request Example None ### Response #### Success Response (200) - **owner** (Owner) - The owner of the lifetime. #### Response Example ```json { "owner": "owner_object" } ``` ``` -------------------------------- ### Execute JavaScript with QuickJS Source: https://github.com/justjake/quickjs-emscripten/blob/main/examples/iife-global.html Initializes the QuickJS runtime and evaluates a code string. Ensure the environment is ready before calling evalCode. ```javascript QJS.getQuickJS().then((QuickJS) => { console.log(QuickJS.evalCode("1+1")) }) ``` -------------------------------- ### GET /global Source: https://github.com/justjake/quickjs-emscripten/blob/main/doc/quickjs-emscripten-core/classes/QuickJSAsyncContext.md Retrieves a handle to the global object inside the interpreter, allowing for the creation of global variables. ```APIDOC ## GET global ### Description Retrieves a handle to the global object inside the interpreter. You can set properties on this handle to create global variables. ### Method GET ### Endpoint global ### Response #### Success Response (200) - **handle** (QuickJSHandle) - A handle to the global object. ``` -------------------------------- ### QTS_NewHostRef() Source: https://github.com/justjake/quickjs-emscripten/blob/main/doc/quickjs-emscripten/interfaces/QuickJSAsyncFFI.md Creates a new host reference. ```APIDOC ## QTS_NewHostRef(ctx, id) ### Description Creates a new host reference within the specified JavaScript context. ### Method N/A (Function Call) ### Endpoint N/A ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Parameters - **ctx** (JSContextPointer) - Required - The JavaScript context. - **id** (HostRefId) - Required - The identifier for the host reference. ### Request Example N/A ### Response #### Success Response (200) - **JSValuePointer** - A pointer to the newly created host reference value. ``` -------------------------------- ### Initialize QuickJS Async Module Source: https://github.com/justjake/quickjs-emscripten/blob/main/doc/@jitl/quickjs-wasmfile-debug-asyncify/README.md Load the variant and initialize the QuickJS module using the core library's factory function. ```typescript import variant from "@jitl/quickjs-wasmfile-debug-asyncify" import { newQuickJSAsyncWASMModuleFromVariant } from "quickjs-emscripten-core" const QuickJS = await newQuickJSAsyncWASMModuleFromVariant(variant) ``` -------------------------------- ### Property and Value Management Source: https://github.com/justjake/quickjs-emscripten/blob/main/doc/quickjs-emscripten/interfaces/LowLevelJavascriptVm.md Methods for getting, setting, and defining properties, as well as creating new values. ```APIDOC ## Property and Value Management ### Methods - **getProp(handle, key)**: Retrieves a property from an object handle. - **setProp(handle, key, value)**: Sets a property on an object handle. - **defineProp(handle, key, descriptor)**: Defines a property with a descriptor. - **newNumber(value)**: Creates a new number handle. - **newString(value)**: Creates a new string handle. - **getNumber(handle)**: Converts a handle to a number. - **getString(handle)**: Converts a handle to a string. ``` -------------------------------- ### QTS_GetArrayBufferLength API Source: https://github.com/justjake/quickjs-emscripten/blob/main/doc/@jitl/quickjs-ffi-types/interfaces/QuickJSFFI.md Gets the length (in bytes) of a JavaScript ArrayBuffer. This is useful for determining the size of the buffer's data. ```APIDOC ## QTS_GetArrayBufferLength() ### Description Gets the length (in bytes) of a JavaScript ArrayBuffer. ### Method N/A (Function Signature) ### Endpoint N/A ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example N/A ### Response #### Success Response (200) - **Return Value** (`number`) - The length of the ArrayBuffer in bytes. #### Response Example N/A ``` -------------------------------- ### newContext() Source: https://github.com/justjake/quickjs-emscripten/blob/main/doc/_media/QuickJSWASMModule.md Creates a new QuickJSContext and its associated QuickJSRuntime simultaneously. ```APIDOC ## newContext() ### Description A simplified API to create a new QuickJSRuntime and a QuickJSContext inside that runtime at the same time. The runtime is automatically disposed when the context is disposed. ### Parameters - **options** (ContextOptions) - Optional - Configuration options for the new context. ### Returns - **QuickJSContext** - The newly created context instance. ``` -------------------------------- ### QuickJSRuntime Methods Source: https://github.com/justjake/quickjs-emscripten/blob/main/doc/quickjs-emscripten/classes/QuickJSRuntime.md Documentation for the methods available on the QuickJSRuntime class. ```APIDOC ### Methods #### [dispose]() > **[dispose]**(): `void` Defined in: [packages/quickjs-emscripten-core/src/lifetime.ts:47](https://github.com/justjake/quickjs-emscripten/blob/main/packages/quickjs-emscripten-core/src/lifetime.ts#L47) Just calls the standard .dispose() method of this class. #### Returns `void` #### Implementation of [`Disposable`](../interfaces/Disposable.md).[`[dispose]`](../interfaces/Disposable.md#dispose) #### Inherited from [`UsingDisposable`](UsingDisposable.md).[`[dispose]`](UsingDisposable.md#dispose) *** ### assertOwned() > **assertOwned**(`handle`): `void` Defined in: [packages/quickjs-emscripten-core/src/runtime.ts:330](https://github.com/justjake/quickjs-emscripten/blob/main/packages/quickjs-emscripten-core/src/runtime.ts#L330) Assert that `handle` is owned by this runtime. #### Parameters ##### handle [`QuickJSHandle`](../type-aliases/QuickJSHandle.md) #### Returns `void` #### Throws QuickJSWrongOwner if owned by a different runtime. ``` -------------------------------- ### Get Type of Value Source: https://github.com/justjake/quickjs-emscripten/blob/main/doc/quickjs-emscripten-core/interfaces/QuickJSFFI.md Determines the type of a given JavaScript value within the QuickJS runtime. Returns the type as a string. ```APIDOC ## QTS_Typeof() ### Description Determines the type of a given JavaScript value within the QuickJS runtime. ### Method N/A (Function Call) ### Endpoint N/A ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example ``` // Assuming ctx and value are valid JSValuePointers const type_string_ptr = QTS_Typeof(ctx, value); // The result is an OwnedHeapCharPointer, which needs to be managed (e.g., freed) ``` ### Response #### Success Response (200) - **type_string_ptr** (OwnedHeapCharPointer) - A pointer to a heap-allocated string representing the type of the value (e.g., "object", "string", "number"). #### Response Example N/A ``` -------------------------------- ### Import QuickJS Module Source: https://github.com/justjake/quickjs-emscripten/blob/main/packages/quickjs-emscripten-core/README.template.md Import a QuickJS module constructor from quickjs-emscripten-core, a release build variant, and then create the QuickJS module. ```typescript import { newQuickJSWASMModuleFromVariant } from "quickjs-emscripten-core" import releaseVariant from "@jitl/quickjs-singlefile-cjs-release-sync" const QuickJS = await newQuickJSWASMModuleFromVariant(releaseVariant) ``` -------------------------------- ### Import quickjs-emscripten WASM Module Source: https://github.com/justjake/quickjs-emscripten/blob/main/doc/@jitl/quickjs-singlefile-mjs-debug-sync/README.md Import the WASM module variant and initialize it with quickjs-emscripten-core. This setup is required before using the quickjs runtime. ```typescript import variant from "@jitl/quickjs-singlefile-mjs-debug-sync" import { newQuickJSWASMModuleFromVariant } from "quickjs-emscripten-core" const QuickJS = await newQuickJSWASMModuleFromVariant(variant) ``` -------------------------------- ### Runtime Configuration Methods Source: https://github.com/justjake/quickjs-emscripten/blob/main/doc/@jitl/quickjs-ffi-types/interfaces/QuickJSEmscriptenModule.md Hooks for configuring file loading and WASM instantiation. ```APIDOC ## locateFile(fileName, prefix) ### Description Called when the runtime needs to load a file (e.g., .wasm files). Allows overriding the file path, useful for CDN hosting. ### Parameters - **fileName** (string) - Required - The relative path to the file. - **prefix** (string) - Required - The path to the main JavaScript file's directory. ### Returns - (string) - The actual URI or path to the requested file. ## instantiateWasm(imports, onSuccess) ### Description Creates an instance of the WASM module. ### Parameters - **imports** (WebAssembly.Imports) - Required - The imports object for the WASM module. - **onSuccess** (Function) - Required - Callback executed with the instance. ### Returns - (Exports | Promise) - The exports of the WASM module. ``` -------------------------------- ### Iterate Over Object Properties Source: https://github.com/justjake/quickjs-emscripten/blob/main/doc/quickjs-emscripten-core/classes/QuickJSAsyncContext.md Example usage for iterating over an object's properties using getOwnPropertyNames and getProp. Ensure to dispose of handles after use. ```typescript for (using prop of context.getOwnPropertyNames(objectHandle).unwrap()) { using value = context.getProp(handle, prop) console.log(context.dump(prop), '->', context.dump(value)) } ``` -------------------------------- ### QuickJSContext Constructor Source: https://github.com/justjake/quickjs-emscripten/blob/main/doc/quickjs-emscripten/classes/QuickJSContext.md Initializes a new QuickJSContext. It is recommended to use QuickJSRuntime#newContext or QuickJSWASMModule#newContext instead of calling this constructor directly. ```APIDOC ## Constructor: new QuickJSContext() > **new QuickJSContext**(`args`): `QuickJSContext` Defined in: [packages/quickjs-emscripten-core/src/context.ts:233](https://github.com/justjake/quickjs-emscripten/blob/main/packages/quickjs-emscripten-core/src/context.ts#L233) Use [QuickJSRuntime#newContext](QuickJSRuntime.md#newcontext) or [QuickJSWASMModule#newContext](QuickJSWASMModule.md#newcontext) to create a new QuickJSContext. ### Parameters #### args - **callbacks** (`QuickJSModuleCallbacks`) - **ctx** (`Lifetime`) - Required - The lifetime and pointer to the JSContext. ``` -------------------------------- ### newBigInt() Source: https://github.com/justjake/quickjs-emscripten/blob/main/doc/quickjs-emscripten/classes/QuickJSAsyncContext.md Create a QuickJS bigint value. ```APIDOC ## newBigInt() ### Description Create a QuickJS bigint value. ### Parameters #### Path Parameters - **num** (bigint) - Required - The bigint value. ``` -------------------------------- ### instantiateWasm() Source: https://github.com/justjake/quickjs-emscripten/blob/main/doc/quickjs-emscripten/interfaces/QuickJSAsyncEmscriptenModule.md Instantiates the WebAssembly module and calls the onSuccess callback. ```APIDOC ## instantiateWasm() ### Description Instantiates the WebAssembly module and calls the `onSuccess` callback with the instance exports. It can return either the `Exports` object directly or a `Promise` that resolves to it. ### Method `instantiateWasm` ### Parameters - **imports** (WebAssembly.Imports) - The imports object for the WebAssembly instance. - **onSuccess** ((instance) => void) - A callback function that is executed upon successful instantiation, receiving the instance exports. ### Returns Exports | Promise - The WebAssembly instance exports or a Promise resolving to them. ``` -------------------------------- ### Get Property Value - QuickJSContext Source: https://github.com/justjake/quickjs-emscripten/blob/main/doc/quickjs-emscripten/classes/QuickJSAsyncContext.md Retrieves the value of a specific property from a JavaScript object handle. The property key can be provided as a handle or a JavaScript string. ```typescript context.getProp(handle, key) ``` -------------------------------- ### QuickJS vs QuickJS-NG Class ID Creation Source: https://github.com/justjake/quickjs-emscripten/blob/main/CLAUDE.md Demonstrates the difference in creating class IDs between the original QuickJS and quickjs-ng. Use conditional compilation for compatibility. ```c // bellard/quickjs - class ID is global JS_NewClassID(&class_id); // quickjs-ng - class ID is per-runtime JS_NewClassID(rt, &class_id); #ifdef QTS_USE_QUICKJS_NG JS_NewClassID(rt, &class_id); #else JS_NewClassID(&class_id); #endif ``` -------------------------------- ### Get Global Object Handle Source: https://github.com/justjake/quickjs-emscripten/blob/main/doc/quickjs-emscripten/classes/QuickJSAsyncContext.md Retrieves a handle to the global object within the QuickJS interpreter. This can be used to set properties and create global variables. ```typescript get global(): QuickJSHandle ``` -------------------------------- ### Build a QuickJS Variant Source: https://github.com/justjake/quickjs-emscripten/blob/main/CLAUDE.md Steps to build a specific QuickJS variant. Navigate to the variant's directory and run 'make' for C code compilation and 'corepack pnpm build:ts' for the TypeScript wrapper. ```bash cd packages/variant-quickjs- make # builds the C code with emscripten corepack pnpm build:ts # builds the TypeScript wrapper ``` -------------------------------- ### Getting ArrayBuffer view from VM Source: https://github.com/justjake/quickjs-emscripten/blob/main/CHANGELOG.md Use `context.getArrayBuffer(handle)` to create a UInt8Array view on an ArrayBuffer that resides within the QuickJS VM, accessible on the host. ```javascript context.getArrayBuffer(handle) ``` -------------------------------- ### QuickJSContext Methods Source: https://github.com/justjake/quickjs-emscripten/blob/main/doc/quickjs-emscripten/classes/QuickJSContext.md Methods available on a QuickJSContext instance. ```APIDOC ## QuickJSContext Methods ### [dispose]() > **[dispose]**(): `void` Defined in: [packages/quickjs-emscripten-core/src/lifetime.ts:47](https://github.com/justjake/quickjs-emscripten/blob/main/packages/quickjs-emscripten-core/src/lifetime.ts#L47) Just calls the standard .dispose() method of this class. #### Returns `void` #### Implementation of [`Disposable`](../interfaces/Disposable.md).[`[dispose]`](../interfaces/Disposable.md#dispose) #### Inherited from [`UsingDisposable`](UsingDisposable.md).[`[dispose]`](UsingDisposable.md#dispose) *** ### callFunction() ``` -------------------------------- ### newObject Source: https://github.com/justjake/quickjs-emscripten/blob/main/doc/quickjs-emscripten/classes/QuickJSAsyncContext.md Creates a new QuickJS object. ```APIDOC ## newObject(prototype?) ### Description Create a new QuickJS object. ### Parameters - **prototype** (QuickJSHandle) - Optional - The prototype for the new object. ### Returns - **QuickJSHandle** - The new QuickJS object. ``` -------------------------------- ### typeof() - Get the type of a JavaScript value Source: https://github.com/justjake/quickjs-emscripten/blob/main/doc/quickjs-emscripten/classes/QuickJSContext.md The `typeof()` function returns the type of a given JavaScript value represented by a `QuickJSHandle`. Note that this implementation is not fully standards-compliant. ```APIDOC ## typeof() ### Description `typeof` operator. **Not** [standards compliant](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/typeof). ### Method `typeof(handle: QuickJSHandle): string` ### Parameters #### handle - **handle** (QuickJSHandle) - The handle to the JavaScript value. ### Returns - **string** - The type of the JavaScript value. ### Remarks Does not support BigInt values correctly. ### Implementation of [`LowLevelJavascriptVm`](../interfaces/LowLevelJavascriptVm.md).[`typeof`](../interfaces/LowLevelJavascriptVm.md#typeof) ``` -------------------------------- ### QTS_NewHostRef() Source: https://github.com/justjake/quickjs-emscripten/blob/main/doc/quickjs-emscripten/interfaces/QuickJSFFI.md Creates a new host reference in the given context. ```APIDOC ## QTS_NewHostRef() ### Description Creates a new host reference in the given context. ### Method N/A (Function Signature) ### Endpoint N/A ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example N/A ### Response #### Success Response (200) - **Return Value** (`JSValuePointer`) - A pointer to the newly created host reference. #### Response Example N/A ``` -------------------------------- ### typeof() - Get the type of a JavaScript value Source: https://github.com/justjake/quickjs-emscripten/blob/main/doc/quickjs-emscripten-core/classes/QuickJSContext.md Returns the type of a JavaScript value using a `typeof` operator. Note that this implementation is not fully standards-compliant, particularly with BigInt values. ```APIDOC ## typeof() ### Description `typeof` operator. **Not** [standards compliant](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/typeof). ### Method typeof ### Parameters #### handle - **handle** (QuickJSHandle) - The handle to the JavaScript value. ### Returns string - The type of the JavaScript value. ### Remarks Does not support BigInt values correctly. ### Implementation of [`LowLevelJavascriptVm`](../interfaces/LowLevelJavascriptVm.md).[`typeof`](../interfaces/LowLevelJavascriptVm.md#typeof) ``` -------------------------------- ### Configure QuickJS Runtime Limits and Module Loading Source: https://github.com/justjake/quickjs-emscripten/blob/main/README.md Shows how to create a new QuickJS runtime, set memory and stack limits, configure an interrupt handler, and define a module loader. It then creates a context within this runtime, evaluates an ES module, and logs the default export. ```typescript const runtime = QuickJS.newRuntime() // "Should be enough for everyone" -- attributed to B. Gates runtime.setMemoryLimit(1024 * 640) // Limit stack size runtime.setMaxStackSize(1024 * 320) // Interrupt computation after 1024 calls to the interrupt handler let interruptCycles = 0 runtime.setInterruptHandler(() => ++interruptCycles > 1024) // Toy module system that always returns the module name // as the default export runtime.setModuleLoader((moduleName) => `export default '${moduleName}'`) const context = runtime.newContext() const ok = context.evalCode( ` import fooName from './foo.js' globalThis.result = fooName ` ) context.unwrapResult(ok).dispose() // logs "foo.js" console.log(context.getProp(context.global, "result").consume(context.dump)) context.dispose() runtime.dispose() ``` -------------------------------- ### Get Promise State and Unwrap Result - QuickJSContext Source: https://github.com/justjake/quickjs-emscripten/blob/main/doc/quickjs-emscripten/classes/QuickJSAsyncContext.md Retrieves the state of a JavaScript promise and unwraps the result if fulfilled. This is useful for asserting promise outcomes and extracting values. ```typescript const promiseHandle = context.evalCode(`Promise.resolve(42)`) const resultHandle = context.unwrapResult( context.getPromiseState(promiseHandle) ) context.getNumber(resultHandle) === 42; // true resultHandle.dispose() ``` -------------------------------- ### WASM Instantiation Source: https://github.com/justjake/quickjs-emscripten/blob/main/doc/quickjs-emscripten-core/interfaces/QuickJSEmscriptenModule.md Methods for handling WebAssembly module instantiation and file location. ```APIDOC ## instantiateWasm(imports, onSuccess) ### Description Creates an instance of the WASM module, calls the success callback, and returns the exports. ### Parameters - **imports** (WebAssembly.Imports) - Required - The imports for the WASM module. - **onSuccess** (Function) - Required - Callback function executed upon successful instantiation. ### Returns - **exports** (Exports | Promise) - The exported functions and memory from the WASM module. *** ## locateFile(fileName, prefix) ### Description Resolves the URI or path for requested files like .wasm or .mem files. ### Parameters - **fileName** (string) - Required - The relative path to the file. - **prefix** (string) - Required - The path to the main JavaScript file's directory. ### Returns - **path** (string) - The resolved URI or path to the file. ``` -------------------------------- ### Package.json Subpath Imports for Variants Source: https://github.com/justjake/quickjs-emscripten/blob/main/packages/quickjs-emscripten-core/README.template.md Example of using subpath imports in package.json to select the appropriate QuickJS variant for different runtimes (browser, Node ESM, Node CommonJS). ```json { "imports": { "#my-quickjs-variant": { "types": "@jitl/quickjs-wasmfile-release-sync", // In the browser, use the singlefile variant that doesn't need an external file "browser": "@jitl/quickjs-singlefile-browser-release-sync", // Otherwise, use the wasmfile variant, compatible with all environments "default": "@jitl/quickjs-wasmfile-release-sync" } } } ``` -------------------------------- ### Initialize QuickJS Async WASM Module Source: https://github.com/justjake/quickjs-emscripten/blob/main/doc/@jitl/quickjs-wasmfile-release-asyncify/README.md Use this to initialize the QuickJS runtime using the specific variant package. ```typescript import variant from "@jitl/quickjs-wasmfile-release-asyncify" import { newQuickJSAsyncWASMModuleFromVariant } from "quickjs-emscripten-core" const QuickJS = await newQuickJSAsyncWASMModuleFromVariant(variant) ``` -------------------------------- ### Evaluate Javascript with Options Source: https://github.com/justjake/quickjs-emscripten/blob/main/README.md Evaluates Javascript code using QuickJS, with options for interrupt handling and memory limits. This example demonstrates how to set a deadline for execution and a memory limit. ```typescript import { getQuickJS, shouldInterruptAfterDeadline } from "quickjs-emscripten" getQuickJS().then((QuickJS) => { const result = QuickJS.evalCode("1 + 1", { shouldInterrupt: shouldInterruptAfterDeadline(Date.now() + 1000), memoryLimitBytes: 1024 * 1024, }) console.log(result) }) ``` -------------------------------- ### Initialize QuickJS Module Source: https://github.com/justjake/quickjs-emscripten/blob/main/doc/@jitl/quickjs-singlefile-cjs-release-sync/README.md Import the variant and initialize the QuickJS WASM module using the core library. ```typescript import variant from "@jitl/quickjs-singlefile-cjs-release-sync" import { newQuickJSWASMModuleFromVariant } from "quickjs-emscripten-core" const QuickJS = await newQuickJSWASMModuleFromVariant(variant) ``` -------------------------------- ### Detect Memory Leaks with TestQuickJSWASMModule Source: https://context7.com/justjake/quickjs-emscripten/llms.txt Use `DEBUG_SYNC` for accurate leak detection. This example demonstrates how to use `TestQuickJSWASMModule` to test for memory leaks by ensuring all allocated handles are disposed. ```typescript import { newQuickJSWASMModule, TestQuickJSWASMModule, DEBUG_SYNC } from "quickjs-emscripten" // Use DEBUG_SYNC for accurate leak detection const wasmModule = await newQuickJSWASMModule(DEBUG_SYNC) const testModule = new TestQuickJSWASMModule(wasmModule) // Test that properly disposes handles function testNoLeak() { const context = testModule.newContext() const handle = context.newString("test") handle.dispose() context.dispose() testModule.assertNoMemoryAllocated() // Passes } // Test that leaks memory function testWithLeak() { const context = testModule.newContext() const handle = context.newString("leaked") // Not disposed! context.dispose() try { testModule.assertNoMemoryAllocated() // Throws! } catch (e) { console.log("Memory leak detected:", e.message) } } testNoLeak() testWithLeak() ``` -------------------------------- ### QuickJSRuntime Class Overview Source: https://github.com/justjake/quickjs-emscripten/blob/main/doc/quickjs-emscripten/classes/QuickJSRuntime.md Provides an overview of the QuickJSRuntime class, its purpose, and how it relates to JavaScript execution environments. ```APIDOC ## Class: QuickJSRuntime Defined in: [packages/quickjs-emscripten-core/src/runtime.ts:71](https://github.com/justjake/quickjs-emscripten/blob/main/packages/quickjs-emscripten-core/src/runtime.ts#L71) A runtime represents a Javascript runtime corresponding to an object heap. Several runtimes can exist at the same time but they cannot exchange objects. Inside a given runtime, no multi-threading is supported. You can think of separate runtimes like different domains in a browser, and the contexts within a runtime like the different windows open to the same domain. Create a runtime via [QuickJSWASMModule.newRuntime](QuickJSWASMModule.md#newruntime). You should create separate runtime instances for untrusted code from different sources for isolation. However, stronger isolation is also available (at the cost of memory usage), by creating separate WebAssembly modules to further isolate untrusted code. See [newQuickJSWASMModule](../functions/newQuickJSWASMModule.md). Implement memory and CPU constraints with [setInterruptHandler](#setinterrupthandler) (called regularly while the interpreter runs), [setMemoryLimit](#setmemorylimit), and [setMaxStackSize](#setmaxstacksize). Use [computeMemoryUsage](#computememoryusage) or [dumpMemoryUsage](#dumpmemoryusage) to guide memory limit tuning. Configure ES module loading with [setModuleLoader](#setmoduleloader). ``` -------------------------------- ### unwrapHostRef() - Unwrap a HostRef to get the host value Source: https://github.com/justjake/quickjs-emscripten/blob/main/doc/quickjs-emscripten/classes/QuickJSContext.md The `unwrapHostRef()` function extracts the underlying host value from a `HostRef.handle`. This operation will throw an error if the handle is not a valid host reference. ```APIDOC ## unwrapHostRef() ### Description If `handle` is a `HostRef.handle`, return the host value `T`. ### Method `unwrapHostRef(handle: QuickJSHandle): T` ### Type Parameters #### T - **T** (`T` extends `object`) - The type of the host object. ### Parameters #### handle - **handle** (QuickJSHandle) - The handle to unwrap. ### Returns - **T** - The unwrapped host value. ### Throws - **QuickJSHostRefInvalid** - If `handle` is not a `HostRef.handle`. ``` -------------------------------- ### Evaluate ES Module and Get Exports Source: https://github.com/justjake/quickjs-emscripten/blob/main/README.md Evaluates JavaScript code as an ES module and retrieves its exports. The result is a handle to the module's exports, which can be inspected using `context.dump`. Ensure all handles are disposed. ```typescript const context = QuickJS.newContext() const result = context.evalCode( ` export const name = 'Jake' export const favoriteBean = 'wax bean' export default 'potato' `, "jake.js", { type: "module" }, ) const moduleExports = context.unwrapResult(result) console.log(context.dump(moduleExports)) // -> { name: 'Jake', favoriteBean: 'wax bean', default: 'potato' } moduleExports.dispose() ``` -------------------------------- ### QuickJSContext Class Overview Source: https://github.com/justjake/quickjs-emscripten/blob/main/doc/quickjs-emscripten/classes/QuickJSContext.md Overview of the QuickJSContext class, its purpose, and how it relates to QuickJSRuntime. ```APIDOC ## Class: QuickJSContext Defined in: [packages/quickjs-emscripten-core/src/context.ts:188](https://github.com/justjake/quickjs-emscripten/blob/main/packages/quickjs-emscripten-core/src/context.ts#L188) QuickJSContext wraps a QuickJS Javascript context (JSContext*) within a runtime. The contexts within the same runtime may exchange objects freely. You can think of separate runtimes like different domains in a browser, and the contexts within a runtime like the different windows open to the same domain. The [runtime](#runtime) references the context's runtime. This class's methods return [QuickJSHandle](../type-aliases/QuickJSHandle.md), which wrap C pointers (JSValue*). It's the caller's responsibility to call `.dispose()` on any handles you create to free memory once you're done with the handle. Use [QuickJSRuntime#newContext](QuickJSRuntime.md#newcontext) or [QuickJSWASMModule#newContext](QuickJSWASMModule.md#newcontext) to create a new QuickJSContext. Create QuickJS values inside the interpreter with methods like [newNumber](#newnumber), [newString](#newstring), [newArray](#newarray), [newObject](#newobject), [newFunction](#newfunction), and [newPromise](#newpromise). Call [setProp](#setprop) or [defineProp](#defineprop) to customize objects. Use those methods with [global](#global) to expose the values you create to the interior of the interpreter, so they can be used in [evalCode](#evalcode). Use [evalCode](#evalcode) or [callFunction](#callfunction) to execute Javascript inside the VM. If you're using asynchronous code inside the QuickJSContext, you may need to also call [QuickJSRuntime#executePendingJobs](QuickJSRuntime.md#executependingjobs). Executing code inside the runtime returns a result object representing successful execution or an error. You must dispose of any such results to avoid leaking memory inside the VM. Implement memory and CPU constraints at the runtime level, using [runtime](#runtime). See [QuickJSRuntime](QuickJSRuntime.md) for more information. ``` -------------------------------- ### Object Property Access with QuickJSContext.getProp / setProp Source: https://context7.com/justjake/quickjs-emscripten/llms.txt Methods for getting and setting properties on QuickJS objects, including nested properties and array elements. Ensure all created handles are disposed of to prevent memory leaks. ```typescript import { getQuickJS } from "quickjs-emscripten" const QuickJS = await getQuickJS() const context = QuickJS.newContext() // Create an object via evalCode const result = context.evalCode (`({ user: { name: "Alice", age: 30 }, items: [1, 2, 3] })`) const objHandle = context.unwrapResult(result) // Get nested properties const userHandle = context.getProp(objHandle, "user") const nameHandle = context.getProp(userHandle, "name") const ageHandle = context.getProp(userHandle, "age") console.log(context.getString(nameHandle)) // "Alice" console.log(context.getNumber(ageHandle)) // 30 // Get array elements const itemsHandle = context.getProp(objHandle, "items") const length = context.getLength(itemsHandle) ?? 0 for (let i = 0; i < length; i++) { const itemHandle = context.getProp(itemsHandle, i) console.log(`items[${i}] =`, context.getNumber(itemHandle)) itemHandle.dispose() } // Set a new property const emailHandle = context.newString("alice@example.com") context.setProp(userHandle, "email", emailHandle) console.log(context.dump(userHandle)) // { name: "Alice", age: 30, email: "alice@example.com" } // Clean up emailHandle.dispose() nameHandle.dispose() ageHandle.dispose() userHandle.dispose() itemsHandle.dispose() objHandle.dispose() context.dispose() ```