@ohos-ports/quickjs-wasi 3.6.0-beta.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1263 @@
1
+ /**
2
+ * QuickJS WASM - A snapshotable JavaScript runtime via WebAssembly.
3
+ *
4
+ * Provides a clean JavaScript API for running sandboxed JS code in a QuickJS
5
+ * VM compiled to WASM. The key differentiator is the ability to snapshot the
6
+ * entire VM state (including pending promises) and restore it in a fresh
7
+ * WASM instance.
8
+ */
9
+ import { type WasiOptions } from './wasi-shim.js';
10
+ import { type ExtensionDescriptor } from './extensions.js';
11
+ /**
12
+ * Largest supported QuickJS native stack limit for the shipped WASM binary.
13
+ *
14
+ * The binary has a 1 MiB linker-defined stack; reserving half of it leaves
15
+ * headroom for native frames and stack-overflow exception handling.
16
+ */
17
+ export declare const MAX_STACK_SIZE: number;
18
+ export type HostFunction = (this: JSValueHandle, ...args: JSValueHandle[]) => JSValueHandle;
19
+ /**
20
+ * A batch of handles created inside `vm.withScope()`, disposed together when
21
+ * the scope ends.
22
+ */
23
+ export interface HandleScope {
24
+ /**
25
+ * Remove a handle from the scope so that it outlives it. The handle is
26
+ * transferred to the enclosing scope when there is one, otherwise it
27
+ * becomes the caller's responsibility to dispose.
28
+ *
29
+ * Use this for the value you intend to return.
30
+ */
31
+ escape<T extends JSValueHandle>(handle: T): T;
32
+ }
33
+ /** Property descriptor flags for `defineProp()`. */
34
+ export interface JSPropertyDescriptor {
35
+ writable?: boolean;
36
+ enumerable?: boolean;
37
+ configurable?: boolean;
38
+ }
39
+ /**
40
+ * An own-property descriptor returned by
41
+ * {@link JSValueHandle.getOwnPropertyDescriptor}. Mirrors the result of
42
+ * `Object.getOwnPropertyDescriptor()`: a data property carries `value` +
43
+ * `writable`, an accessor property carries `get` + `set`.
44
+ *
45
+ * The `value`/`get`/`set` handles are owned by the caller and must be
46
+ * disposed.
47
+ */
48
+ export interface JSOwnPropertyDescriptor {
49
+ /** Present for data properties. Caller must dispose. */
50
+ value?: JSValueHandle;
51
+ /** Present for accessor properties (may be an `undefined` handle). Caller must dispose. */
52
+ get?: JSValueHandle;
53
+ /** Present for accessor properties (may be an `undefined` handle). Caller must dispose. */
54
+ set?: JSValueHandle;
55
+ /** Present for data properties. */
56
+ writable?: boolean;
57
+ enumerable: boolean;
58
+ configurable: boolean;
59
+ }
60
+ export type { WasiOptions };
61
+ export type { ExtensionDescriptor, LoadedExtension, DylinkInfo, WasiImports } from './extensions.js';
62
+ /**
63
+ * Flags for `evalCode()`, matching the QuickJS `JS_EVAL_*` constants.
64
+ */
65
+ export declare const EvalFlags: {
66
+ /** Global script mode (default). */
67
+ readonly TYPE_GLOBAL: 0;
68
+ /**
69
+ * Module mode. `evalCode()` returns a handle to a Promise that resolves
70
+ * to the module's namespace object (its exports), or rejects if module
71
+ * evaluation throws. Use together with `executePendingJobs()` and
72
+ * `resolvePromise()`.
73
+ */
74
+ readonly TYPE_MODULE: 1;
75
+ /** Force strict mode. */
76
+ readonly STRICT: 8;
77
+ /** Compile only; do not execute. */
78
+ readonly COMPILE_ONLY: 32;
79
+ /** Omit stack frames before this eval from Error backtraces. */
80
+ readonly BACKTRACE_BARRIER: 64;
81
+ /**
82
+ * Allow top-level `await` in global scripts. When used, `evalCode()`
83
+ * returns a handle to a Promise that resolves to the completion value.
84
+ * Use together with `executePendingJobs()` and `resolvePromise()`.
85
+ */
86
+ readonly ASYNC: 128;
87
+ };
88
+ /**
89
+ * Flags for `vm.compile()` controlling what is included in the bytecode output.
90
+ * These can be combined with bitwise OR.
91
+ */
92
+ export declare const CompileFlags: {
93
+ /** Strip source code from the bytecode (smaller output, no source in errors). */
94
+ readonly STRIP_SOURCE: 16;
95
+ /** Strip debug information (line numbers, etc.) from the bytecode. */
96
+ readonly STRIP_DEBUG: 32;
97
+ };
98
+ /**
99
+ * Intrinsic flags for `QuickJSOptions.intrinsics` controlling which
100
+ * built-in JavaScript features are available in the VM.
101
+ *
102
+ * By default all intrinsics are enabled. Pass a bitmask of these flags
103
+ * to create a minimal context. For example, omit `Intrinsics.EVAL` to
104
+ * prevent `eval()` usage, or omit `Intrinsics.PROXY` to disallow `Proxy`.
105
+ *
106
+ * `BaseObjects` (Object, Array, Number, String, Boolean, Error, etc.)
107
+ * is always included and cannot be disabled.
108
+ */
109
+ export declare const Intrinsics: {
110
+ /** `Date` constructor and prototype methods. */
111
+ readonly DATE: 1;
112
+ /** `eval()` and `Function()` constructor. */
113
+ readonly EVAL: 2;
114
+ /** `RegExp` constructor, prototype methods, and regex literals. */
115
+ readonly REGEXP: 4;
116
+ /** `JSON.parse()` and `JSON.stringify()`. */
117
+ readonly JSON: 8;
118
+ /** `Proxy` and `Reflect`. */
119
+ readonly PROXY: 16;
120
+ /** `Map`, `Set`, `WeakMap`, `WeakSet`. */
121
+ readonly MAP_SET: 32;
122
+ /** `ArrayBuffer`, `TypedArray` variants, `DataView`. */
123
+ readonly TYPED_ARRAYS: 64;
124
+ /** `Promise`, `async`/`await`. */
125
+ readonly PROMISE: 128;
126
+ /** `BigInt`. Note: BigInt is part of BaseObjects in quickjs-ng and cannot be fully removed. */
127
+ readonly BIG_INT: 256;
128
+ /** `WeakRef` and `FinalizationRegistry`. */
129
+ readonly WEAK_REF: 512;
130
+ /** `performance.now()`. */
131
+ readonly PERFORMANCE: 1024;
132
+ /** `DOMException` class. */
133
+ readonly DOM_EXCEPTION: 2048;
134
+ /**
135
+ * `atob()` and `btoa()` global functions. Also pulls in `DOMException` as
136
+ * a dependency (errors thrown by these functions are `DOMException`s).
137
+ */
138
+ readonly ATOB_BTOA: 4096;
139
+ /** All intrinsics enabled (default). */
140
+ readonly ALL: 4294967295;
141
+ };
142
+ /** Memory usage statistics from the QuickJS runtime. */
143
+ export interface MemoryUsage {
144
+ /** Total bytes allocated via malloc */
145
+ mallocSize: number;
146
+ /** Current malloc limit (0 for unlimited) */
147
+ mallocLimit: number;
148
+ /** Total memory used (including overhead) */
149
+ memoryUsedSize: number;
150
+ /** Number of malloc calls */
151
+ mallocCount: number;
152
+ /** Number of memory-using objects */
153
+ memoryUsedCount: number;
154
+ /** Number of atoms */
155
+ atomCount: number;
156
+ /** Atom memory size */
157
+ atomSize: number;
158
+ /** Number of strings */
159
+ strCount: number;
160
+ /** String memory size */
161
+ strSize: number;
162
+ /** Number of objects */
163
+ objCount: number;
164
+ /** Object memory size */
165
+ objSize: number;
166
+ /** Number of properties */
167
+ propCount: number;
168
+ /** Property memory size */
169
+ propSize: number;
170
+ /** Number of shapes */
171
+ shapeCount: number;
172
+ /** Shape memory size */
173
+ shapeSize: number;
174
+ /** Number of JS functions */
175
+ jsFuncCount: number;
176
+ /** JS function memory size */
177
+ jsFuncSize: number;
178
+ /** JS function code size */
179
+ jsFuncCodeSize: number;
180
+ /** Number of PC-to-line mappings */
181
+ jsFuncPc2lineCount: number;
182
+ /** PC-to-line mapping memory size */
183
+ jsFuncPc2lineSize: number;
184
+ /** Number of C functions */
185
+ cFuncCount: number;
186
+ /** Number of arrays */
187
+ arrayCount: number;
188
+ /** Number of fast arrays */
189
+ fastArrayCount: number;
190
+ /** Number of fast array elements */
191
+ fastArrayElements: number;
192
+ /** Number of binary objects (ArrayBuffer, etc.) */
193
+ binaryObjectCount: number;
194
+ /** Binary object memory size */
195
+ binaryObjectSize: number;
196
+ }
197
+ export interface QuickJSOptions {
198
+ /**
199
+ * WASM module bytes or pre-compiled module.
200
+ *
201
+ * The caller is responsible for loading the WASM binary using whichever
202
+ * mechanism is appropriate for their environment (e.g. `fetch()`,
203
+ * `node:fs/promises`, a bundler-specific import). For convenience the
204
+ * package ships the binary at the `quickjs-wasi/quickjs.wasm` subpath,
205
+ * which can be resolved by bundlers (e.g. Vite's `?url` loader) or read
206
+ * directly from disk.
207
+ */
208
+ wasm: BufferSource | WebAssembly.Module;
209
+ /** Custom WASI function implementations. */
210
+ wasi?: WasiOptions;
211
+ /**
212
+ * Maximum memory the QuickJS runtime can allocate, in bytes.
213
+ * When exceeded, allocations fail and surface as JS exceptions
214
+ * (e.g. `InternalError: out of memory`).
215
+ */
216
+ memoryLimit?: number;
217
+ /**
218
+ * Maximum native stack space QuickJS may consume, in bytes.
219
+ * Must be an integer between 0 and {@link MAX_STACK_SIZE}. Set to 0 to
220
+ * disable the QuickJS stack guard.
221
+ */
222
+ maxStackSize?: number;
223
+ /**
224
+ * Called periodically during JS execution. Return `true` to interrupt
225
+ * the current execution with an `InternalError: interrupted` exception.
226
+ * Useful for implementing execution timeouts or step limits.
227
+ *
228
+ * The handler is called approximately once per JS bytecode instruction,
229
+ * so it should be fast.
230
+ */
231
+ interruptHandler?: () => boolean;
232
+ /**
233
+ * Called when a promise is rejected without a handler, or when a handler
234
+ * is attached to a previously unhandled rejection.
235
+ *
236
+ * @param promise - The rejected promise
237
+ * @param reason - The rejection reason/value
238
+ * @param isHandled - `true` if a handler was just attached (previously unhandled),
239
+ * `false` if this is a new unhandled rejection
240
+ *
241
+ * Both `promise` and `reason` handles are owned by the caller and will be
242
+ * disposed automatically after the callback returns.
243
+ */
244
+ onUnhandledRejection?: (promise: JSValueHandle, reason: JSValueHandle, isHandled: boolean) => void;
245
+ /**
246
+ * Module loader for ES module `import` statements. When provided, the VM
247
+ * can resolve and load modules.
248
+ *
249
+ * Both callbacks are **synchronous**: they must return their result
250
+ * immediately. The engine calls them from inside the WASM call stack,
251
+ * which cannot be suspended to await a Promise; returning a Promise
252
+ * throws a `TypeError`.
253
+ *
254
+ * For async module sources (e.g. loading over `https://`), either
255
+ * pre-fetch all module sources before evaluating and serve them from a
256
+ * cache, or use the fetch-and-retry pattern: throw from `load` on a
257
+ * cache miss, fetch the missing module on the host, and re-run
258
+ * `evalCode()`. Already-loaded modules are cached by the runtime and
259
+ * are not re-requested. See the "ES Modules" section of the README.
260
+ *
261
+ * Errors thrown by either callback propagate to the guest as the
262
+ * module resolution error.
263
+ */
264
+ moduleLoader?: {
265
+ /**
266
+ * Resolve a module specifier relative to the importing module.
267
+ * Called when an `import` statement is encountered.
268
+ *
269
+ * @param baseName - The name of the module containing the `import` statement
270
+ * @param specifier - The raw specifier string (e.g. `"./foo.js"`, `"lodash"`)
271
+ * @returns The normalized/canonical module name
272
+ *
273
+ * If omitted, specifiers are passed through to `load` unchanged.
274
+ */
275
+ normalize?: (baseName: string, specifier: string) => string;
276
+ /**
277
+ * Load the source code for a module.
278
+ *
279
+ * @param moduleName - The normalized module name (from `normalize`, or the raw specifier)
280
+ * @returns The module source code as a string
281
+ */
282
+ load: (moduleName: string) => string;
283
+ };
284
+ /**
285
+ * Bitmask of `Intrinsics.*` flags controlling which built-in JavaScript
286
+ * features are available. By default all intrinsics are enabled.
287
+ *
288
+ * Example: Create a VM without `eval()` or `Proxy`:
289
+ * ```ts
290
+ * const vm = await QuickJS.create({
291
+ * intrinsics: Intrinsics.ALL & ~Intrinsics.EVAL & ~Intrinsics.PROXY,
292
+ * });
293
+ * ```
294
+ */
295
+ intrinsics?: number;
296
+ /**
297
+ * Native WASM extensions to load. Each extension is a WASM shared library
298
+ * (.so) compiled with wasi-sdk that links against the QuickJS C API.
299
+ *
300
+ * Extensions are loaded in order and their init functions are called
301
+ * after the QuickJS runtime is initialized. The same extensions (in the
302
+ * same order) must be provided when restoring from a snapshot.
303
+ */
304
+ extensions?: ExtensionDescriptor[];
305
+ /**
306
+ * Controls the timezone offset used by `Date` within the QuickJS sandbox.
307
+ *
308
+ * - **`'host'`** (default): mirrors the host environment's timezone.
309
+ * `new Date().getTimezoneOffset()` inside the VM will match the host.
310
+ * - **A number**: a fixed UTC offset in **minutes** (e.g. `-480` for UTC-8,
311
+ * `60` for UTC+1). Note: this follows the `getTimezoneOffset()` sign
312
+ * convention where *west* of UTC is positive.
313
+ * - **A callback `(time: number) => number`**: called with seconds since
314
+ * epoch, must return the UTC offset in minutes for that instant. Useful
315
+ * for DST-aware custom timezone logic. The callback is invoked whenever
316
+ * QuickJS converts between UTC and local time (e.g. `getHours()`,
317
+ * `toString()`, `getTimezoneOffset()`), so it may be called multiple
318
+ * times per Date operation.
319
+ */
320
+ timezoneOffset?: 'host' | number | ((timeSecs: number) => number);
321
+ }
322
+ interface QuickJSExports {
323
+ memory: WebAssembly.Memory;
324
+ __stack_pointer: WebAssembly.Global;
325
+ __indirect_function_table: WebAssembly.Table;
326
+ _initialize(): void;
327
+ qjs_get_quickjs_version(): number;
328
+ qjs_init(): number;
329
+ qjs_init2(intrinsics: number): number;
330
+ qjs_destroy(): void;
331
+ qjs_eval(codePtr: number, codeLen: number, filenamePtr: number, flags: number): number;
332
+ qjs_compile(codePtr: number, codeLen: number, filenamePtr: number, evalFlags: number, writeFlags: number, outLenPtr: number): number;
333
+ qjs_eval_bytecode(bufPtr: number, bufLen: number): number;
334
+ qjs_new_string(strPtr: number, strLen: number): number;
335
+ qjs_new_number(num: number): number;
336
+ qjs_new_object(): number;
337
+ qjs_new_array(): number;
338
+ qjs_get_undefined(): number;
339
+ qjs_get_null(): number;
340
+ qjs_get_true(): number;
341
+ qjs_get_false(): number;
342
+ qjs_new_big_int64(lo: number, hi: number): number;
343
+ qjs_get_big_int64(valPtr: number, loOutPtr: number, hiOutPtr: number): number;
344
+ qjs_get_float64(valPtr: number): number;
345
+ qjs_get_string(valPtr: number): number;
346
+ qjs_free_cstring(strPtr: number): void;
347
+ qjs_typeof(valPtr: number): number;
348
+ qjs_is_exception(valPtr: number): number;
349
+ qjs_is_undefined(valPtr: number): number;
350
+ qjs_is_null(valPtr: number): number;
351
+ qjs_is_bool(valPtr: number): number;
352
+ qjs_is_number(valPtr: number): number;
353
+ qjs_is_string(valPtr: number): number;
354
+ qjs_is_object(valPtr: number): number;
355
+ qjs_is_array(valPtr: number): number;
356
+ qjs_is_function(valPtr: number): number;
357
+ qjs_is_error(valPtr: number): number;
358
+ qjs_is_promise(valPtr: number): number;
359
+ qjs_is_symbol(valPtr: number): number;
360
+ qjs_is_big_int(valPtr: number): number;
361
+ qjs_is_array_buffer(valPtr: number): number;
362
+ qjs_get_bool(valPtr: number): number;
363
+ qjs_is_proxy(valPtr: number): number;
364
+ qjs_is_map(valPtr: number): number;
365
+ qjs_is_set(valPtr: number): number;
366
+ qjs_is_date(valPtr: number): number;
367
+ qjs_is_regexp(valPtr: number): number;
368
+ qjs_is_weak_ref(valPtr: number): number;
369
+ qjs_is_weak_map(valPtr: number): number;
370
+ qjs_is_weak_set(valPtr: number): number;
371
+ qjs_is_data_view(valPtr: number): number;
372
+ qjs_get_class_id(valPtr: number): number;
373
+ qjs_get_class_name(valPtr: number): number;
374
+ qjs_get_proxy_target(valPtr: number): number;
375
+ qjs_get_proxy_handler(valPtr: number): number;
376
+ qjs_new_symbol(descPtr: number, descLen: number, isGlobal: number): number;
377
+ qjs_get_symbol_description(valPtr: number, descOutPtr: number): number;
378
+ qjs_get_prop_value(objPtr: number, keyPtr: number): number;
379
+ qjs_set_prop_value(objPtr: number, keyPtr: number, valPtr: number): number;
380
+ qjs_new_array_buffer(dataPtr: number, len: number): number;
381
+ qjs_get_array_buffer(valPtr: number, lenOutPtr: number): number;
382
+ qjs_new_uint8_array(dataPtr: number, len: number): number;
383
+ qjs_get_typed_array_buffer(valPtr: number, byteOffsetOutPtr: number, byteLengthOutPtr: number, bytesPerElementOutPtr: number): number;
384
+ qjs_dup_value(valPtr: number): number;
385
+ qjs_free_value(valPtr: number): void;
386
+ qjs_get_string_len(valPtr: number, plenPtr: number): number;
387
+ qjs_has_own_property_value(objPtr: number, keyPtr: number): number;
388
+ qjs_property_is_enumerable_value(objPtr: number, keyPtr: number): number;
389
+ qjs_get_global(): number;
390
+ qjs_get_prop_string(objPtr: number, namePtr: number): number;
391
+ qjs_set_prop_string(objPtr: number, namePtr: number, valPtr: number): number;
392
+ qjs_define_prop_string(objPtr: number, namePtr: number, valPtr: number, flags: number): number;
393
+ qjs_define_prop_value(objPtr: number, keyPtr: number, valPtr: number, flags: number): number;
394
+ qjs_get_prop_uint32(objPtr: number, idx: number): number;
395
+ qjs_set_prop_uint32(objPtr: number, idx: number, valPtr: number): number;
396
+ qjs_get_own_property_names(objPtr: number): number;
397
+ qjs_get_own_property_names_all(objPtr: number): number;
398
+ qjs_get_own_property_keys(objPtr: number): number;
399
+ qjs_get_own_property_descriptor(objPtr: number, keyPtr: number): number;
400
+ qjs_has_own_property(objPtr: number, namePtr: number): number;
401
+ qjs_property_is_enumerable(objPtr: number, namePtr: number): number;
402
+ qjs_get_prototype_of(objPtr: number): number;
403
+ qjs_get_value_ptr(valPtr: number): number;
404
+ qjs_call(funcPtr: number, thisPtr: number, argc: number, argvPtr: number): number;
405
+ qjs_call_constructor(ctorPtr: number, argc: number, argvPtr: number): number;
406
+ qjs_new_host_function(namePtr: number, nameLen: number, argCount: number): number;
407
+ qjs_new_promise(resolveOutPtr: number, rejectOutPtr: number): number;
408
+ qjs_promise_state(promisePtr: number): number;
409
+ qjs_promise_result(promisePtr: number): number;
410
+ qjs_promise_then(promisePtr: number, onFulfilledPtr: number, onRejectedPtr: number): number;
411
+ qjs_promise_mark_as_handled(promisePtr: number): void;
412
+ qjs_is_job_pending(): number;
413
+ qjs_execute_pending_job(): number;
414
+ qjs_get_exception(): number;
415
+ qjs_new_error(): number;
416
+ qjs_throw(valPtr: number): number;
417
+ qjs_set_memory_limit(limit: number): void;
418
+ qjs_set_max_stack_size(size: number): void;
419
+ qjs_set_interrupt_handler(enable: number): void;
420
+ qjs_set_promise_rejection_handler(enable: number): void;
421
+ qjs_set_module_loader(enable: number): void;
422
+ qjs_run_gc(): void;
423
+ qjs_set_gc_threshold(threshold: number): void;
424
+ qjs_get_gc_threshold(): number;
425
+ qjs_compute_memory_usage(outPtr: number): void;
426
+ qjs_get_runtime_ptr(): number;
427
+ qjs_get_context_ptr(): number;
428
+ qjs_set_runtime_and_context(rtPtr: number, ctxPtr: number): void;
429
+ malloc(size: number): number;
430
+ free(ptr: number): void;
431
+ wasm_malloc(size: number): number;
432
+ wasm_free(ptr: number): void;
433
+ }
434
+ /** Metadata about an extension saved in a snapshot */
435
+ export interface SnapshotExtension {
436
+ name: string;
437
+ memoryBase: number;
438
+ tableBase: number;
439
+ initFn: string;
440
+ }
441
+ export interface Snapshot {
442
+ /** The raw WASM linear memory contents */
443
+ memory: Uint8Array;
444
+ /** The stack pointer value at snapshot time */
445
+ stackPointer: number;
446
+ /** Pointer to JSRuntime in the WASM memory */
447
+ runtimePtr: number;
448
+ /** Pointer to JSContext in the WASM memory */
449
+ contextPtr: number;
450
+ /** Metadata about loaded extensions (empty if none) */
451
+ extensions: SnapshotExtension[];
452
+ }
453
+ export interface Deferred {
454
+ /** Handle to the QuickJS promise object */
455
+ handle: JSValueHandle;
456
+ /** A host-side Promise that resolves when the QuickJS promise settles */
457
+ settled: Promise<void>;
458
+ /** Resolve the QuickJS promise with a value */
459
+ resolve(value: JSValueHandle): void;
460
+ /** Reject the QuickJS promise with a value */
461
+ reject(value: JSValueHandle): void;
462
+ }
463
+ export declare class QuickJS {
464
+ private exports;
465
+ private module;
466
+ private instance;
467
+ private encoder;
468
+ private decoder;
469
+ private disposed;
470
+ /** Registry of host callbacks, keyed by function name */
471
+ private hostCallbacks;
472
+ /** Counter for internal-only callbacks (e.g. promise settle handlers) */
473
+ private nextInternalId;
474
+ private interruptHandler;
475
+ private unhandledRejectionHandler;
476
+ private moduleNormalizeHandler;
477
+ private moduleLoadHandler;
478
+ private timezoneOffsetHandler;
479
+ private _global;
480
+ private _versions;
481
+ private _undefined;
482
+ private _null;
483
+ private _true;
484
+ private _false;
485
+ private _ownedHandles;
486
+ /**
487
+ * The innermost active `withScope()` batch, if any. New non-singleton
488
+ * handles register themselves here so they can be freed together.
489
+ * @internal
490
+ */
491
+ _activeScope: Set<JSValueHandle> | null;
492
+ /** Loaded extensions in deterministic order */
493
+ private loadedExtensions;
494
+ private constructor();
495
+ private setInstance;
496
+ /**
497
+ * Version information for the runtime and loaded native libraries.
498
+ * Always includes `"quickjs-wasi"` (the npm package version) and
499
+ * `"quickjs"` (the QuickJS engine version). Extensions may contribute
500
+ * additional entries for their native dependencies (e.g. `"ada"`, `"mbedtls"`).
501
+ */
502
+ get versions(): Record<string, string>;
503
+ /** The global object. Cached; do not dispose. */
504
+ get global(): JSValueHandle;
505
+ /** The undefined value. Cached; do not dispose. */
506
+ get undefined(): JSValueHandle;
507
+ /** The null value. Cached; do not dispose. */
508
+ get null(): JSValueHandle;
509
+ /** The true value. Cached; do not dispose. */
510
+ get true(): JSValueHandle;
511
+ /** The false value. Cached; do not dispose. */
512
+ get false(): JSValueHandle;
513
+ /**
514
+ * Create a fresh QuickJS VM instance.
515
+ *
516
+ * @param options - Optional configuration. Can also pass raw WASM bytes
517
+ * directly for backwards compatibility.
518
+ */
519
+ static create(options?: QuickJSOptions | BufferSource | WebAssembly.Module): Promise<QuickJS>;
520
+ /**
521
+ * Restore a QuickJS VM from a snapshot.
522
+ *
523
+ * @param snapshot - The snapshot to restore from.
524
+ * @param options - Optional configuration. Can also pass raw WASM bytes
525
+ * directly for backwards compatibility.
526
+ */
527
+ static restore(snapshot: Snapshot, options?: QuickJSOptions | BufferSource | WebAssembly.Module): Promise<QuickJS>;
528
+ /**
529
+ * Serialize a snapshot to a binary buffer for persistent storage.
530
+ *
531
+ * The format includes a versioned header followed by the raw memory.
532
+ * Apply your own compression (gzip, zstd, etc.) on top for smaller
533
+ * storage. The memory compresses well due to its large zero regions.
534
+ *
535
+ * Format (version 1):
536
+ * ```
537
+ * Offset Size Field
538
+ * 0 4 Magic: "QJSS" (0x514A5353, big-endian)
539
+ * 4 1 Version: 1
540
+ * 5 3 Reserved (zero)
541
+ * 8 4 Memory size in bytes (u32 little-endian)
542
+ * 12 4 Stack pointer (u32 little-endian)
543
+ * 16 4 Runtime pointer (u32 little-endian)
544
+ * 20 4 Context pointer (u32 little-endian)
545
+ * 24 N Memory data (N = memory size from offset 8)
546
+ * ```
547
+ */
548
+ static serializeSnapshot(snapshot: Snapshot): Uint8Array;
549
+ /**
550
+ * Deserialize a snapshot from a binary buffer produced by `serializeSnapshot()`.
551
+ */
552
+ static deserializeSnapshot(data: Uint8Array): Snapshot;
553
+ private static normalizeOptions;
554
+ private static applyLimits;
555
+ private static resolveModule;
556
+ private static instantiate;
557
+ /**
558
+ * Called from WASM when a host function is invoked from QuickJS code.
559
+ */
560
+ private handleHostCall;
561
+ /** Write a JS string into WASM memory, returning the pointer. Caller must free. */
562
+ private writeString;
563
+ /** Read a null-terminated C string from WASM memory */
564
+ private readCString;
565
+ /**
566
+ * Check if a result handle is an exception and throw a JSException if so.
567
+ * Used internally by evalCode and callFunction.
568
+ */
569
+ private throwIfException;
570
+ /**
571
+ * Evaluate JavaScript code and return the result as a handle.
572
+ * If the code throws, a `JSException` (which extends `Error`) is thrown
573
+ * on the host side, matching standard JavaScript semantics.
574
+ *
575
+ * @param code - The JavaScript source code to evaluate.
576
+ * @param filename - Optional filename for error stack traces (default `'<eval>'`).
577
+ * @param flags - Optional bitwise OR of `EvalFlags.*` constants.
578
+ * For example, pass `EvalFlags.ASYNC` to allow top-level `await`; the
579
+ * returned handle will be a Promise that resolves to the completion value.
580
+ * With `EvalFlags.TYPE_MODULE` the returned handle is a Promise that
581
+ * resolves to the module's namespace object (its exports).
582
+ */
583
+ evalCode(code: string, filename?: string, flags?: number): JSValueHandle;
584
+ /**
585
+ * Compile JavaScript source code to bytecode without executing it.
586
+ * The returned `Uint8Array` can be stored, transferred, or later executed
587
+ * with `evalBytecode()`.
588
+ *
589
+ * @param code - The JavaScript source code to compile.
590
+ * @param filename - Optional filename for error stack traces (default `'<compile>'`).
591
+ * @param evalFlags - Optional bitwise OR of `EvalFlags.*` constants.
592
+ * Use `EvalFlags.TYPE_MODULE` to compile as a module.
593
+ * @param compileFlags - Optional bitwise OR of `CompileFlags.*` constants.
594
+ * Use `CompileFlags.STRIP_SOURCE` and/or `CompileFlags.STRIP_DEBUG` to
595
+ * reduce bytecode size.
596
+ */
597
+ compile(code: string, filename?: string, evalFlags?: number, compileFlags?: number): Uint8Array;
598
+ /**
599
+ * Execute previously compiled bytecode (from `compile()`).
600
+ * Returns the evaluation result as a handle.
601
+ *
602
+ * For module bytecode (compiled with `EvalFlags.TYPE_MODULE`), the
603
+ * returned handle is a Promise that resolves to the module's namespace
604
+ * object (its exports).
605
+ *
606
+ * @param bytecode - The bytecode `Uint8Array` from `compile()`.
607
+ */
608
+ evalBytecode(bytecode: Uint8Array): JSValueHandle;
609
+ /**
610
+ * Execute all pending microtask jobs (promise reactions, etc.)
611
+ * Returns the number of jobs executed.
612
+ */
613
+ executePendingJobs(): number;
614
+ /**
615
+ * Explicitly trigger garbage collection. QuickJS runs GC automatically,
616
+ * but this can be useful to reclaim memory at a known point or before
617
+ * taking a snapshot.
618
+ */
619
+ runGC(): void;
620
+ /**
621
+ * The GC threshold in bytes. When allocated memory exceeds this value,
622
+ * garbage collection is triggered automatically. Set to 0 to disable
623
+ * automatic GC.
624
+ */
625
+ get gcThreshold(): number;
626
+ set gcThreshold(threshold: number);
627
+ /**
628
+ * Get detailed memory usage statistics from the QuickJS runtime.
629
+ * Returns counts and sizes for atoms, strings, objects, functions, etc.
630
+ */
631
+ getMemoryUsage(): MemoryUsage;
632
+ /**
633
+ * Get the global object. Prefer the cached `vm.global` property.
634
+ */
635
+ getGlobal(): JSValueHandle;
636
+ /**
637
+ * Create a new QuickJS string value.
638
+ */
639
+ newString(str: string): JSValueHandle;
640
+ /**
641
+ * Create a new QuickJS number value.
642
+ */
643
+ newNumber(num: number): JSValueHandle;
644
+ /**
645
+ * Create a new QuickJS BigInt value.
646
+ */
647
+ newBigInt(val: bigint): JSValueHandle;
648
+ /**
649
+ * Create a new QuickJS object value.
650
+ */
651
+ newObject(): JSValueHandle;
652
+ /**
653
+ * Create a new QuickJS array value.
654
+ */
655
+ newArray(): JSValueHandle;
656
+ /**
657
+ * Create a global symbol (`Symbol.for(description)`).
658
+ * Global symbols with the same description are always the same symbol,
659
+ * even across snapshot/restore.
660
+ */
661
+ newSymbolFor(description: string): JSValueHandle;
662
+ /**
663
+ * Create a new QuickJS ArrayBuffer by copying data from a host buffer.
664
+ */
665
+ newArrayBuffer(data: ArrayBuffer | Uint8Array): JSValueHandle;
666
+ /**
667
+ * Create a new QuickJS Uint8Array by copying data from a host buffer.
668
+ */
669
+ newUint8Array(data: Uint8Array): JSValueHandle;
670
+ /**
671
+ * Get undefined. Prefer the cached `vm.undefined` property.
672
+ */
673
+ getUndefined(): JSValueHandle;
674
+ /**
675
+ * Get null. Prefer the cached `vm.null` property.
676
+ */
677
+ getNull(): JSValueHandle;
678
+ /**
679
+ * Get true. Prefer the cached `vm.true` property.
680
+ */
681
+ getTrue(): JSValueHandle;
682
+ /**
683
+ * Get false. Prefer the cached `vm.false` property.
684
+ */
685
+ getFalse(): JSValueHandle;
686
+ /**
687
+ * Create a new QuickJS function backed by a host callback.
688
+ *
689
+ * When the function is called inside QuickJS, the host callback is invoked
690
+ * with the `this` value and arguments as JSValueHandles.
691
+ */
692
+ newFunction(name: string, fn: HostFunction): JSValueHandle;
693
+ /**
694
+ * Run `fn` with a handle scope: every handle created during the call is
695
+ * disposed when it returns, except those passed to `scope.escape()`.
696
+ *
697
+ * This is the bulk alternative to disposing handles individually, for code
698
+ * that creates many intermediates, such as walking a large value:
699
+ *
700
+ * ```ts
701
+ * const name = vm.withScope((scope) => {
702
+ * const user = root.getProp('user'); // freed automatically
703
+ * const profile = user.getProp('profile'); // freed automatically
704
+ * return scope.escape(profile.getProp('name'));
705
+ * });
706
+ * ```
707
+ *
708
+ * Scopes nest: `escape()` transfers the handle to the enclosing scope when
709
+ * there is one, so it is still cleaned up at the outer boundary.
710
+ *
711
+ * `fn` must be synchronous. Handles created after an `await` are outside
712
+ * the scope, because it closes as soon as `fn` returns.
713
+ *
714
+ * Host callbacks are safe to trigger inside a scope: the `this`/argument
715
+ * handles the trampoline passes to a callback wrap C-owned pointers and
716
+ * are exempt from scope tracking (see `handleHostCall`), so the scope
717
+ * frees only handles the host actually owns. Handles a callback CREATES
718
+ * (including `dup()`s of its arguments) are tracked normally.
719
+ */
720
+ withScope<T>(fn: (scope: HandleScope) => T): T;
721
+ /**
722
+ * Export a handle as a snapshot-portable token.
723
+ *
724
+ * A handle's heap box lives in the VM's linear memory, so a
725
+ * `snapshot()` taken while the handle is alive carries it, and a VM
726
+ * restored from that snapshot has the identical box at the identical
727
+ * offset. `importHandle(token)` on the restored VM (or on this VM)
728
+ * re-materializes an owned handle for the same guest value without
729
+ * evaluating any guest code.
730
+ *
731
+ * Contract:
732
+ * - the handle must stay undisposed until after `snapshot()`; its
733
+ * box (and the reference it holds) must be part of the memory image;
734
+ * - the token is only meaningful to THIS VM and VMs restored from a
735
+ * snapshot of it taken while the handle was alive;
736
+ * - `importHandle` duplicates the underlying value (fresh reference,
737
+ * fresh box), so it can be called any number of times and each
738
+ * returned handle is independently owned and disposable. The
739
+ * exported box's own reference is intentionally never released on
740
+ * restored VMs (one retained reference per VM image, reclaimed
741
+ * with the VM).
742
+ *
743
+ * The intended use is boot-time capture: snapshot a VM after capturing
744
+ * references to pristine intrinsics but BEFORE evaluating untrusted or
745
+ * user code, then restore per task and import the captured handles,
746
+ * guaranteeing the references predate anything user code patched,
747
+ * without re-running capture code in the restored VM (where user-
748
+ * patched globals could observe it). See vercel/workflow's host-side
749
+ * serde for a worked example.
750
+ */
751
+ exportHandle(handle: JSValueHandle): number;
752
+ /**
753
+ * Re-materialize a handle from a token produced by `exportHandle`,
754
+ * on this VM, or on a VM restored from a snapshot taken while the
755
+ * exported handle was alive. Returns a NEW owned handle (the
756
+ * underlying value's refcount is incremented); dispose it like any
757
+ * other handle. See `exportHandle` for the full contract.
758
+ */
759
+ importHandle(token: number): JSValueHandle;
760
+ /**
761
+ * Create a QuickJS function backed by a host callback whose registration is
762
+ * tied to the returned handle: disposing the handle unregisters the
763
+ * callback.
764
+ *
765
+ * Use this for short-lived callbacks (e.g. a visitor passed to
766
+ * `Map.prototype.forEach`) where the name is an implementation detail.
767
+ * `newFunction()` keeps its callback registered for the lifetime of the VM
768
+ * (by design, so that names can be re-registered after a snapshot is
769
+ * restored), which makes it unsuitable for callbacks created in a loop.
770
+ *
771
+ * The guest must not retain the function past disposal: calling it after
772
+ * the handle is disposed throws, because the callback is gone. Ephemeral
773
+ * functions do not survive snapshot/restore.
774
+ */
775
+ newEphemeralFunction(fn: HostFunction): JSValueHandle;
776
+ /**
777
+ * Remove a host callback registered with `newFunction()` or
778
+ * `registerHostCallback()`. Returns true if a callback was removed.
779
+ *
780
+ * Any QuickJS function still referencing the name will throw when called,
781
+ * so only unregister once the guest can no longer reach it.
782
+ */
783
+ unregisterHostCallback(name: string): boolean;
784
+ /**
785
+ * Create an internal host function that bypasses the duplicate-name check.
786
+ * Used for ephemeral callbacks (promise settle handlers, resolvePromise, etc.)
787
+ * that are not intended to survive snapshot/restore.
788
+ */
789
+ private newInternalFunction;
790
+ /**
791
+ * Create a new promise.
792
+ *
793
+ * Returns a Deferred with:
794
+ * - `handle` - the QuickJS promise object
795
+ * - `settled` - a host Promise that resolves when the QuickJS promise settles
796
+ * - `resolve(value)` - resolve the promise with a QuickJS value
797
+ * - `reject(value)` - reject the promise with a QuickJS value
798
+ */
799
+ newPromise(): Deferred;
800
+ /**
801
+ * Resolve a promise handle. Returns a host-side Promise that resolves
802
+ * with the settled value/error of the QuickJS promise.
803
+ *
804
+ * If the handle is not a promise, it is treated as an already-fulfilled value.
805
+ *
806
+ * The returned host Promise resolves to `{ value: JSValueHandle }` on
807
+ * fulfillment or `{ error: JSValueHandle }` on rejection.
808
+ */
809
+ resolvePromise(promiseHandle: JSValueHandle): Promise<{
810
+ value: JSValueHandle;
811
+ } | {
812
+ error: JSValueHandle;
813
+ }>;
814
+ /**
815
+ * Subscribe to a promise without executing guest code, via quickjs-ng's
816
+ * JS_PromiseThen: no Promise.prototype.then lookup, no Symbol.species.
817
+ * Returns the chained promise. Handler handles are borrowed (caller
818
+ * still owns and disposes them).
819
+ * @internal
820
+ */
821
+ promiseThenRaw(promise: JSValueHandle, onFulfilled: JSValueHandle, onRejected: JSValueHandle): JSValueHandle;
822
+ /**
823
+ * Mark a promise as handled: an eventual (or already-recorded) rejection
824
+ * will not be reported to `onUnhandledRejection`. Useful when the host
825
+ * observes a rejection through other means (e.g. `resolvePromise()`) and
826
+ * wants to suppress the unhandled-rejection callback for it.
827
+ *
828
+ * No-op if the handle is not a promise.
829
+ */
830
+ markPromiseHandled(promise: JSValueHandle): void;
831
+ /**
832
+ * Call a QuickJS function. If the function throws, a `JSException`
833
+ * is thrown on the host side.
834
+ */
835
+ callFunction(func: JSValueHandle, thisVal: JSValueHandle, ...args: JSValueHandle[]): JSValueHandle;
836
+ /**
837
+ * Invoke a QuickJS constructor with `new`, i.e. `new ctor(...args)`.
838
+ * If the constructor throws (including when `ctor` is not a constructor),
839
+ * a `JSException` is thrown on the host side.
840
+ *
841
+ * This is the counterpart to `callFunction` for building values inside
842
+ * the VM from the host, e.g. `new Date(iso)` on a constructor captured
843
+ * before any user code ran.
844
+ */
845
+ construct(ctor: JSValueHandle, ...args: JSValueHandle[]): JSValueHandle;
846
+ /**
847
+ * Internal: call a QuickJS function without throwing on exception.
848
+ * Used by promise plumbing where exceptions are handled differently.
849
+ */
850
+ private callFunctionRaw;
851
+ /**
852
+ * Set a property on an object. Accepts string or JSValueHandle as key.
853
+ * JSValueHandle keys support symbols (including `Symbol.for()`).
854
+ */
855
+ setProp(obj: JSValueHandle, key: string | JSValueHandle, value: JSValueHandle): void;
856
+ /**
857
+ * Define a property on an object with explicit property descriptor flags.
858
+ * Unlike `setProp`, this allows controlling `writable`, `enumerable`, and
859
+ * `configurable` attributes, matching `Object.defineProperty()` semantics.
860
+ * Accepts string or JSValueHandle as key (JSValueHandle keys support symbols).
861
+ *
862
+ * All flags default to `false` when not specified.
863
+ */
864
+ defineProp(obj: JSValueHandle, key: string | JSValueHandle, value: JSValueHandle, descriptor?: JSPropertyDescriptor): void;
865
+ /**
866
+ * Get a property from an object using a JSValueHandle key.
867
+ * Supports symbol keys (including `Symbol.for()`).
868
+ */
869
+ getProp(obj: JSValueHandle, key: JSValueHandle): JSValueHandle;
870
+ /**
871
+ * Get the current exception, if any.
872
+ */
873
+ getException(): JSValueHandle;
874
+ /**
875
+ * Create a new QuickJS Error object.
876
+ * Accepts a string message or a native Error object.
877
+ */
878
+ newError(messageOrError: string | Error): JSValueHandle;
879
+ /**
880
+ * Get the typeof a handle as a string.
881
+ */
882
+ typeof(handle: JSValueHandle): string;
883
+ /**
884
+ * Convert a QuickJS handle to a host JavaScript value.
885
+ * Handles strings, numbers, booleans, null, undefined, bigint, arrays,
886
+ * errors, functions, and plain objects. Circular references in objects
887
+ * are returned as `undefined`.
888
+ */
889
+ dump(handle: JSValueHandle): unknown;
890
+ private _dump;
891
+ /**
892
+ * Convert a host JavaScript value to a QuickJS handle.
893
+ */
894
+ hostToHandle(value: unknown): JSValueHandle;
895
+ /**
896
+ * Snapshot the entire VM state.
897
+ *
898
+ * Returns a snapshot containing the full WASM linear memory. Use
899
+ * `QuickJS.serializeSnapshot()` to convert to a versioned binary
900
+ * buffer for persistent storage.
901
+ */
902
+ snapshot(): Snapshot;
903
+ /**
904
+ * Re-register a host callback after restoring from a snapshot.
905
+ * The name must match the name passed to `newFunction()` before the snapshot.
906
+ */
907
+ registerHostCallback(name: string, fn: HostFunction): void;
908
+ /**
909
+ * Dispose the VM, releasing all references to the WASM instance
910
+ * so it can be garbage collected by the host JS engine.
911
+ */
912
+ dispose(): void;
913
+ /**
914
+ * Support for `using` declarations (Explicit Resource Management).
915
+ * Automatically disposes the VM when it goes out of scope.
916
+ *
917
+ * ```typescript
918
+ * using vm = await QuickJS.create(wasmBytes);
919
+ * vm.evalCode('1 + 2');
920
+ * // vm is automatically disposed here
921
+ * ```
922
+ */
923
+ [Symbol.dispose](): void;
924
+ private assertNotDisposed;
925
+ /** @internal */
926
+ _getExports(): QuickJSExports;
927
+ /** @internal */
928
+ _getMemory(): WebAssembly.Memory;
929
+ /** @internal */
930
+ _writeString(str: string): {
931
+ ptr: number;
932
+ len: number;
933
+ };
934
+ /** @internal */
935
+ _readCString(ptr: number): string;
936
+ }
937
+ /**
938
+ * An exception thrown from QuickJS code. Extends `Error` so it works with
939
+ * standard error handling (`instanceof Error`, `.message`, `.stack`), and
940
+ * also exposes a `handle` property, a live `JSValueHandle` to the QuickJS
941
+ * exception value, allowing direct inspection of custom properties.
942
+ *
943
+ * The `handle` must be disposed when you're done with it (or use `using`).
944
+ * If the error propagates uncaught, the handle will be cleaned up when the
945
+ * VM is disposed.
946
+ */
947
+ export declare class JSException extends Error {
948
+ #private;
949
+ /**
950
+ * A live handle to the QuickJS exception value. You can read custom
951
+ * properties, call methods, etc. Must be disposed when done.
952
+ */
953
+ readonly handle: JSValueHandle;
954
+ /** @internal */
955
+ constructor(handle: JSValueHandle);
956
+ get name(): string;
957
+ set name(v: string);
958
+ get message(): string;
959
+ set message(v: string);
960
+ get stack(): string | undefined;
961
+ set stack(v: string | undefined);
962
+ dispose(): void;
963
+ [Symbol.dispose](): void;
964
+ }
965
+ /**
966
+ * A handle to a JSValue inside the QuickJS WASM instance.
967
+ */
968
+ export declare class JSValueHandle {
969
+ /** The QuickJS VM instance this handle belongs to. */
970
+ readonly vm: QuickJS;
971
+ /** @internal */
972
+ readonly ptr: number;
973
+ private disposed_;
974
+ /**
975
+ * When true, this handle is a cached singleton (e.g. `undefined`, `null`,
976
+ * `true`, `false`, the global object) and `dispose()` is a no-op. This
977
+ * prevents code that routinely disposes handles (such as the object/array
978
+ * branches of `hostToHandle`) from freeing the shared heap `JSValue*` that
979
+ * the cached singleton still references, which would corrupt later reads.
980
+ * @internal
981
+ */
982
+ private readonly singleton;
983
+ /**
984
+ * When true, this handle wraps a `JSValue*` OWNED BY THE C CALLER: the
985
+ * `this`/argument handles the host-call trampoline passes to a host
986
+ * callback (`handleHostCall`). The C side frees those values after the
987
+ * call returns, so `dispose()` is a no-op and the handle is never
988
+ * registered with an active `withScope()` (either would double-free
989
+ * the guest value and corrupt the heap). A callback that needs to
990
+ * retain an argument past its own invocation must `dup()` it; the
991
+ * duplicate takes a fresh reference and behaves like any owned handle.
992
+ * @internal
993
+ */
994
+ private readonly borrowed;
995
+ /**
996
+ * Extra cleanup to run when this handle is disposed. Used by
997
+ * `newEphemeralFunction()` to unregister its host callback.
998
+ * @internal
999
+ */
1000
+ _onDispose: (() => void) | undefined;
1001
+ constructor(vm: QuickJS, ptr: number, singleton?: boolean, borrowed?: boolean);
1002
+ /**
1003
+ * Whether this handle wraps a C-owned pointer (host-callback
1004
+ * `this`/arguments). Borrowed handles must never be exported as
1005
+ * snapshot tokens: the trampoline frees their boxes after the
1006
+ * callback returns. @internal
1007
+ */
1008
+ get _isBorrowed(): boolean;
1009
+ /**
1010
+ * Whether `dispose()` has been called on this handle.
1011
+ *
1012
+ * Note that handle methods do not currently guard against use after
1013
+ * disposal: reading from a disposed handle reads freed memory. Check this
1014
+ * when a handle's lifetime is managed elsewhere (e.g. by `withScope()`).
1015
+ */
1016
+ get disposed(): boolean;
1017
+ get isUndefined(): boolean;
1018
+ get isNull(): boolean;
1019
+ /**
1020
+ * Get the promise state: 0 = pending, 1 = fulfilled, 2 = rejected
1021
+ */
1022
+ get isBool(): boolean;
1023
+ get isNumber(): boolean;
1024
+ get isString(): boolean;
1025
+ get isSymbol(): boolean;
1026
+ get isBigInt(): boolean;
1027
+ get isObject(): boolean;
1028
+ get isArray(): boolean;
1029
+ get isFunction(): boolean;
1030
+ get isError(): boolean;
1031
+ get isPromise(): boolean;
1032
+ get isArrayBuffer(): boolean;
1033
+ /**
1034
+ * Whether this value is a Proxy exotic object.
1035
+ *
1036
+ * This is an engine-level check: it never fires proxy traps and cannot
1037
+ * be determined (or spoofed) from within guest JavaScript. Use
1038
+ * {@link getProxyTarget} / {@link getProxyHandler} to introspect a
1039
+ * detected proxy without executing guest code.
1040
+ */
1041
+ get isProxy(): boolean;
1042
+ /**
1043
+ * Whether this value is a Map (engine brand check: trap-free,
1044
+ * spoof-proof, and unaffected by prototype/constructor mutation).
1045
+ * A Proxy wrapping a Map returns false.
1046
+ */
1047
+ get isMap(): boolean;
1048
+ /**
1049
+ * Whether this value is a Set (engine brand check: trap-free,
1050
+ * spoof-proof, and unaffected by prototype/constructor mutation).
1051
+ * A Proxy wrapping a Set returns false.
1052
+ */
1053
+ get isSet(): boolean;
1054
+ /**
1055
+ * Whether this value is a Date (engine brand check: trap-free,
1056
+ * spoof-proof, and unaffected by prototype/constructor mutation).
1057
+ * A Proxy wrapping a Date returns false.
1058
+ */
1059
+ get isDate(): boolean;
1060
+ /**
1061
+ * Whether this value is a RegExp (engine brand check: trap-free,
1062
+ * spoof-proof, and unaffected by prototype/constructor mutation).
1063
+ * A Proxy wrapping a RegExp returns false.
1064
+ */
1065
+ get isRegExp(): boolean;
1066
+ /** Whether this value is a WeakRef (engine brand check). */
1067
+ get isWeakRef(): boolean;
1068
+ /** Whether this value is a WeakMap (engine brand check). */
1069
+ get isWeakMap(): boolean;
1070
+ /** Whether this value is a WeakSet (engine brand check). */
1071
+ get isWeakSet(): boolean;
1072
+ /** Whether this value is a DataView (engine brand check). */
1073
+ get isDataView(): boolean;
1074
+ /**
1075
+ * A numeric identity for the underlying heap value, or 0 for values that
1076
+ * are not heap-allocated (numbers, booleans, `null`, `undefined`).
1077
+ *
1078
+ * Two handles to the same underlying object always report the same
1079
+ * identity, and two live handles to different objects always report
1080
+ * different identities, so this is the value to key a `Map` on when
1081
+ * deduplicating or detecting cycles across handles (`dump()` uses it for
1082
+ * exactly that).
1083
+ *
1084
+ * The identity is only meaningful while the value is alive; it is an
1085
+ * address, so it may be reused after every handle to the value has been
1086
+ * disposed. Do not persist it, and do not treat it as unforgeable: a
1087
+ * number read out of the guest can trivially collide with one.
1088
+ */
1089
+ get identity(): number;
1090
+ /**
1091
+ * Extract the value as a boolean, applying JavaScript truthiness
1092
+ * (equivalent to `!!value` inside the VM).
1093
+ */
1094
+ toBoolean(): boolean;
1095
+ /**
1096
+ * The internal QuickJS class ID of this value, or 0 for non-objects.
1097
+ * Useful as a generic engine-level brand when no dedicated `is*`
1098
+ * getter exists. Class IDs are stable within a VM instance but are an
1099
+ * engine implementation detail, so prefer the dedicated getters.
1100
+ */
1101
+ get classId(): number;
1102
+ /**
1103
+ * The engine-level class name of this value, e.g. `"Object"`, `"Map"`,
1104
+ * `"Date"`, `"RegExp"`, or the registered name of an extension-defined
1105
+ * class like `"URL"`, or `undefined` for non-objects and unnamed
1106
+ * internal classes.
1107
+ *
1108
+ * Unlike `constructorName` (which reads the `constructor` and `name`
1109
+ * properties and can therefore fire getters/proxy traps and be spoofed),
1110
+ * this is trap-free: it reads the engine's class table directly, never
1111
+ * executes guest code, and cannot be forged by reassigning prototypes or
1112
+ * constructors. Note that the engine registers the Proxy class under the
1113
+ * name `"Object"` (mirroring `Object.prototype.toString`), so use `isProxy`
1114
+ * to detect proxies and `getProxyTarget()` to read the target's brand.
1115
+ */
1116
+ get className(): string | undefined;
1117
+ get promiseState(): number;
1118
+ /**
1119
+ * Get the typeof this value as a string.
1120
+ * Returns the same values as the native `typeof` operator.
1121
+ */
1122
+ get typeof(): string;
1123
+ /**
1124
+ * Get the length property of this value (for arrays, strings, etc.).
1125
+ */
1126
+ get length(): number;
1127
+ /**
1128
+ * Get the constructor name of this object, or undefined if unavailable.
1129
+ */
1130
+ get constructorName(): string | undefined;
1131
+ /**
1132
+ * Get the own enumerable string property names (equivalent to Object.keys()).
1133
+ */
1134
+ keys(): string[];
1135
+ /**
1136
+ * Get all own property names including non-enumerable ones
1137
+ * (equivalent to Object.getOwnPropertyNames()).
1138
+ */
1139
+ getOwnPropertyNames(): string[];
1140
+ /**
1141
+ * Get ALL own property keys (strings and symbols), including
1142
+ * non-enumerable (equivalent to Reflect.ownKeys()).
1143
+ *
1144
+ * String keys are returned as strings; symbol keys are returned as
1145
+ * JSValueHandles which the caller must dispose.
1146
+ *
1147
+ * Trap-free for ordinary objects; fires the `ownKeys` trap for a
1148
+ * Proxy (check {@link isProxy} first if that matters).
1149
+ */
1150
+ getOwnPropertyKeys(): Array<string | JSValueHandle>;
1151
+ /**
1152
+ * Get the own property descriptor for a key WITHOUT invoking getters
1153
+ * (equivalent to Object.getOwnPropertyDescriptor()).
1154
+ *
1155
+ * This is the safe way to inspect a property that may be an accessor:
1156
+ * a data property yields `{ value, writable, enumerable, configurable }`,
1157
+ * an accessor property yields `{ get, set, enumerable, configurable }`
1158
+ * where `get`/`set` are handles to the accessor functions themselves
1159
+ * (never invoked). Returns undefined if there is no such own property.
1160
+ *
1161
+ * The `value`/`get`/`set` handles are owned by the caller and must be
1162
+ * disposed.
1163
+ *
1164
+ * Trap-free for ordinary objects; fires the `getOwnPropertyDescriptor`
1165
+ * trap for a Proxy (check {@link isProxy} first if that matters).
1166
+ */
1167
+ getOwnPropertyDescriptor(key: string | JSValueHandle): JSOwnPropertyDescriptor | undefined;
1168
+ /**
1169
+ * Check if a property is an own property (equivalent to Object.prototype.hasOwnProperty).
1170
+ */
1171
+ hasOwnProperty(name: string): boolean;
1172
+ /**
1173
+ * Check if a property is enumerable (equivalent to Object.prototype.propertyIsEnumerable).
1174
+ */
1175
+ propertyIsEnumerable(name: string): boolean;
1176
+ /**
1177
+ * Get the prototype of this object (equivalent to Object.getPrototypeOf()).
1178
+ */
1179
+ getPrototypeOf(): JSValueHandle;
1180
+ /**
1181
+ * Get the `[[ProxyTarget]]` of this Proxy without firing any traps.
1182
+ * Throws {@link JSException} if this value is not a Proxy; check
1183
+ * {@link isProxy} first. Note the target may itself be a Proxy.
1184
+ */
1185
+ getProxyTarget(): JSValueHandle;
1186
+ /**
1187
+ * Get the `[[ProxyHandler]]` of this Proxy without firing any traps.
1188
+ * Throws {@link JSException} if this value is not a Proxy; check
1189
+ * {@link isProxy} first.
1190
+ */
1191
+ getProxyHandler(): JSValueHandle;
1192
+ /**
1193
+ * Get a property by name.
1194
+ */
1195
+ getProp(name: string): JSValueHandle;
1196
+ /**
1197
+ * Set a property by name.
1198
+ */
1199
+ setProp(name: string, value: JSValueHandle): void;
1200
+ /**
1201
+ * Define a property with explicit property descriptor flags.
1202
+ * Unlike `setProp`, this allows controlling `writable`, `enumerable`, and
1203
+ * `configurable` attributes, matching `Object.defineProperty()` semantics.
1204
+ * Accepts string or JSValueHandle as key (JSValueHandle keys support symbols).
1205
+ *
1206
+ * All flags default to `false` when not specified.
1207
+ */
1208
+ defineProp(key: string | JSValueHandle, value: JSValueHandle, descriptor?: JSPropertyDescriptor): void;
1209
+ /**
1210
+ * Extract the value as a number.
1211
+ */
1212
+ toNumber(): number;
1213
+ /**
1214
+ * Extract the value as a BigInt.
1215
+ */
1216
+ toBigInt(): bigint;
1217
+ /**
1218
+ * Extract the value as an ArrayBuffer (copies from WASM memory).
1219
+ * Works on ArrayBuffer values. For typed arrays, gets the underlying buffer.
1220
+ */
1221
+ toArrayBuffer(): ArrayBuffer;
1222
+ /**
1223
+ * Extract the value as a Uint8Array (copies from WASM memory).
1224
+ * Works on Uint8Array, ArrayBuffer, and other typed array values.
1225
+ */
1226
+ toUint8Array(): Uint8Array;
1227
+ /**
1228
+ * Extract the value as a string. Works on any value.
1229
+ *
1230
+ * For values that are not already strings this performs a JavaScript
1231
+ * string conversion, which **executes guest code**: `toString()` /
1232
+ * `valueOf()` / `Symbol.toPrimitive` on the value or its prototype chain,
1233
+ * and proxy traps. Guard with `isString` when the caller must not run guest
1234
+ * code, and call a captured intrinsic (e.g. `URL.prototype.toString` via
1235
+ * `vm.callFunction`) when a specific conversion is wanted.
1236
+ */
1237
+ toString(): string;
1238
+ /**
1239
+ * Use this handle, then dispose it. Returns the callback's return value.
1240
+ */
1241
+ consume<T>(fn: (handle: JSValueHandle) => T): T;
1242
+ /**
1243
+ * Duplicate this handle (increment refcount).
1244
+ */
1245
+ dup(): JSValueHandle;
1246
+ /**
1247
+ * Dispose this handle, freeing the heap-allocated JSValue.
1248
+ * Safe to call after the VM has been disposed (becomes a no-op).
1249
+ */
1250
+ dispose(): void;
1251
+ /**
1252
+ * Support for `using` declarations (Explicit Resource Management).
1253
+ * Automatically disposes the handle when it goes out of scope.
1254
+ *
1255
+ * ```typescript
1256
+ * using result = vm.evalCode('1 + 2');
1257
+ * console.log(result.toNumber()); // 3
1258
+ * // result is automatically disposed here
1259
+ * ```
1260
+ */
1261
+ [Symbol.dispose](): void;
1262
+ }
1263
+ //# sourceMappingURL=index.d.ts.map