-
Notifications
You must be signed in to change notification settings - Fork 133
Expand file tree
/
Copy pathcontext.ts
More file actions
1542 lines (1418 loc) · 53.3 KB
/
Copy pathcontext.ts
File metadata and controls
1542 lines (1418 loc) · 53.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { IsEqualOp, JSPromiseStateEnum } from "@jitl/quickjs-ffi-types"
import type {
EvalFlags,
EitherModule,
EvalDetectModule,
JSBorrowedCharPointer,
JSContextPointer,
JSRuntimePointer,
JSValueConstPointer,
JSValuePointer,
JSValuePointerPointer,
EitherFFI,
UInt32Pointer,
JSValuePointerPointerPointer,
JSVoidPointer,
HostRefId,
} from "@jitl/quickjs-ffi-types"
import type { JSPromiseState } from "./deferred-promise"
import { QuickJSDeferredPromise } from "./deferred-promise"
// eslint-disable-next-line @typescript-eslint/no-unused-vars
import type { shouldInterruptAfterDeadline } from "./interrupt-helpers"
import {
QuickJSEmptyGetOwnPropertyNames,
QuickJSHostRefInvalid,
QuickJSNotImplemented,
QuickJSPromisePending,
QuickJSUnwrapError,
} from "./errors"
import type { Disposable, DisposableArray, DisposableFail, DisposableSuccess } from "./lifetime"
import {
DisposableResult,
Lifetime,
Scope,
StaticLifetime,
UsingDisposable,
WeakLifetime,
createDisposableArray,
} from "./lifetime"
import type { HeapTypedArray } from "./memory"
import { ModuleMemory } from "./memory"
import type { ContextCallbacks, QuickJSModuleCallbacks } from "./module"
import type {
QuickJSRuntime,
// eslint-disable-next-line @typescript-eslint/no-unused-vars
ExecutePendingJobsResult,
} from "./runtime"
import type {
ContextEvalOptions,
GetOwnPropertyNamesOptions,
JSValue,
PromiseExecutor,
QuickJSHandle,
StaticJSValue,
} from "./types"
import { evalOptionsToFlags, getOwnPropertyNamesOptionsToFlags } from "./types"
import type {
LowLevelJavascriptVm,
SuccessOrFail,
VmFunctionImplementation,
VmPropertyDescriptor,
} from "./vm-interface"
import { QuickJSIterator } from "./QuickJSIterator"
import { HostRef } from "./host-ref"
export type QuickJSContextResult<S> = DisposableResult<S, QuickJSHandle>
/**
* Property key for getting or setting a property on a handle with
* {@link QuickJSContext#getProp}, {@link QuickJSContext#setProp}, or {@link QuickJSContext#defineProp}.
*/
export type QuickJSPropertyKey = number | string | QuickJSHandle
/**
* @private
*/
class ContextMemory extends ModuleMemory implements Disposable {
readonly owner: QuickJSRuntime
readonly ctx: Lifetime<JSContextPointer>
readonly rt: Lifetime<JSRuntimePointer>
readonly module: EitherModule
readonly ffi: EitherFFI
readonly scope = new Scope()
/** @private */
constructor(args: {
owner: QuickJSRuntime
module: EitherModule
ffi: EitherFFI
ctx: Lifetime<JSContextPointer>
rt: Lifetime<JSRuntimePointer>
ownedLifetimes?: Disposable[]
}) {
super(args.module)
args.ownedLifetimes?.forEach((lifetime) => this.scope.manage(lifetime))
this.owner = args.owner
this.module = args.module
this.ffi = args.ffi
this.rt = args.rt
this.ctx = this.scope.manage(args.ctx)
}
get alive() {
return this.scope.alive
}
dispose() {
return this.scope.dispose()
}
[Symbol.dispose]() {
return this.dispose()
}
/**
* Track `lifetime` so that it is disposed when this scope is disposed.
*/
manage<T extends Disposable>(lifetime: T): T {
return this.scope.manage(lifetime)
}
copyJSValue = (ptr: JSValuePointer | JSValueConstPointer) => {
return this.ffi.QTS_DupValuePointer(this.ctx.value, ptr)
}
freeJSValue = (ptr: JSValuePointer) => {
this.ffi.QTS_FreeValuePointer(this.ctx.value, ptr)
}
consumeJSCharPointer(ptr: JSBorrowedCharPointer): string {
const str = this.module.UTF8ToString(ptr)
this.ffi.QTS_FreeCString(this.ctx.value, ptr)
return str
}
heapValueHandle(ptr: JSValuePointer, extraDispose?: () => void): JSValue {
const dispose: typeof this.freeJSValue = extraDispose
? (val) => {
extraDispose()
this.freeJSValue(val)
}
: this.freeJSValue
return new Lifetime(ptr, this.copyJSValue, dispose, this.owner)
}
/** Manage a heap pointer with the lifetime of the context */
staticHeapValueHandle(ptr: JSValuePointer | JSValueConstPointer): StaticJSValue {
this.manage(this.heapValueHandle(ptr as JSValuePointer))
// This isn't technically a static lifetime, but since it has the same
// lifetime as the VM, it's okay to fake one since when the VM is
// disposed, no other functions will accept the value.
return new StaticLifetime(ptr as JSValueConstPointer, this.owner) as StaticJSValue
}
}
/**
* 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 {@link runtime} references the context's runtime.
*
* This class's methods return {@link QuickJSHandle}, 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 {@link QuickJSRuntime#newContext} or {@link QuickJSWASMModule#newContext}
* to create a new QuickJSContext.
*
* Create QuickJS values inside the interpreter with methods like
* {@link newNumber}, {@link newString}, {@link newArray}, {@link newObject},
* {@link newFunction}, and {@link newPromise}.
*
* Call {@link setProp} or {@link defineProp} to customize objects. Use those methods
* with {@link global} to expose the values you create to the interior of the
* interpreter, so they can be used in {@link evalCode}.
*
* Use {@link evalCode} or {@link callFunction} to execute Javascript inside the VM. If
* you're using asynchronous code inside the QuickJSContext, you may need to also
* call {@link QuickJSRuntime#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 {@link runtime}.
* See {@link QuickJSRuntime} for more information.
*
*/
// TODO: Manage own callback registration
export class QuickJSContext
extends UsingDisposable
implements LowLevelJavascriptVm<QuickJSHandle>, Disposable
{
/**
* The runtime that created this context.
*/
public readonly runtime: QuickJSRuntime
/** @private */
protected readonly ctx: Lifetime<JSContextPointer>
/** @private */
protected readonly rt: Lifetime<JSRuntimePointer>
/** @private */
protected readonly module: EitherModule
/** @private */
protected readonly ffi: EitherFFI
/** @private */
protected memory: ContextMemory
/** @private */
protected _undefined: QuickJSHandle | undefined = undefined
/** @private */
protected _null: QuickJSHandle | undefined = undefined
/** @private */
protected _false: QuickJSHandle | undefined = undefined
/** @private */
protected _true: QuickJSHandle | undefined = undefined
/** @private */
protected _global: QuickJSHandle | undefined = undefined
/** @private */
protected _BigInt: QuickJSHandle | undefined = undefined
/** @private */
protected uint32Out: HeapTypedArray<Uint32Array, UInt32Pointer>
/** @private */
protected _Symbol: QuickJSHandle | undefined = undefined
/** @private */
protected _SymbolIterator: QuickJSHandle | undefined = undefined
/** @private */
protected _SymbolAsyncIterator: QuickJSHandle | undefined = undefined
/**
* Use {@link QuickJSRuntime#newContext} or {@link QuickJSWASMModule#newContext}
* to create a new QuickJSContext.
*/
constructor(args: {
module: EitherModule
ffi: EitherFFI
ctx: Lifetime<JSContextPointer>
rt: Lifetime<JSRuntimePointer>
runtime: QuickJSRuntime
ownedLifetimes?: Disposable[]
callbacks: QuickJSModuleCallbacks
}) {
super()
this.runtime = args.runtime
this.module = args.module
this.ffi = args.ffi
this.rt = args.rt
this.ctx = args.ctx
this.memory = new ContextMemory({
...args,
owner: this.runtime,
})
args.callbacks.setContextCallbacks(this.ctx.value, this.cToHostCallbacks)
this.dump = this.dump.bind(this)
this.getString = this.getString.bind(this)
this.getNumber = this.getNumber.bind(this)
this.resolvePromise = this.resolvePromise.bind(this)
this.uint32Out = this.memory.manage(
this.memory.newTypedArray<Uint32Array, UInt32Pointer>(Uint32Array, 1),
)
}
// @implement Disposable ----------------------------------------------------
get alive() {
return this.memory.alive
}
/**
* Dispose of this VM's underlying resources.
*
* @throws Calling this method without disposing of all created handles
* will result in an error.
*/
dispose() {
this.memory.dispose()
}
// Globals ------------------------------------------------------------------
/**
* [`undefined`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/undefined).
*/
get undefined(): QuickJSHandle {
if (this._undefined) {
return this._undefined
}
// Undefined is a constant, immutable value in QuickJS.
const ptr = this.ffi.QTS_GetUndefined()
return (this._undefined = new StaticLifetime(ptr))
}
/**
* [`null`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/null).
*/
get null(): QuickJSHandle {
if (this._null) {
return this._null
}
// Null is a constant, immutable value in QuickJS.
const ptr = this.ffi.QTS_GetNull()
return (this._null = new StaticLifetime(ptr))
}
/**
* [`true`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/true).
*/
get true(): QuickJSHandle {
if (this._true) {
return this._true
}
// True is a constant, immutable value in QuickJS.
const ptr = this.ffi.QTS_GetTrue()
return (this._true = new StaticLifetime(ptr))
}
/**
* [`false`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/false).
*/
get false(): QuickJSHandle {
if (this._false) {
return this._false
}
// False is a constant, immutable value in QuickJS.
const ptr = this.ffi.QTS_GetFalse()
return (this._false = new StaticLifetime(ptr))
}
/**
* [`global`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects).
* A handle to the global object inside the interpreter.
* You can set properties to create global variables.
*/
get global(): QuickJSHandle {
if (this._global) {
return this._global
}
// The global is a JSValue, but since it's lifetime is as long as the VM's,
// we should manage it.
const ptr = this.ffi.QTS_GetGlobalObject(this.ctx.value)
// Automatically clean up this reference when we dispose
this._global = this.memory.staticHeapValueHandle(ptr)
return this._global
}
// New values ---------------------------------------------------------------
/**
* Converts a Javascript number into a QuickJS value.
*/
newNumber(num: number): QuickJSHandle {
return this.memory.heapValueHandle(this.ffi.QTS_NewFloat64(this.ctx.value, num))
}
/**
* Create a QuickJS [string](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String) value.
*/
newString(str: string): QuickJSHandle {
const ptr = this.memory
.newHeapCharPointer(str)
.consume((charHandle) => this.ffi.QTS_NewString(this.ctx.value, charHandle.value.ptr))
return this.memory.heapValueHandle(ptr)
}
/**
* Create a QuickJS [symbol](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol) value.
* No two symbols created with this function will be the same value.
*/
newUniqueSymbol(description: string | symbol): QuickJSHandle {
const key = (typeof description === "symbol" ? description.description : description) ?? ""
const ptr = this.memory
.newHeapCharPointer(key)
.consume((charHandle) => this.ffi.QTS_NewSymbol(this.ctx.value, charHandle.value.ptr, 0))
return this.memory.heapValueHandle(ptr)
}
/**
* Get a symbol from the [global registry](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol#shared_symbols_in_the_global_symbol_registry) for the given key.
* All symbols created with the same key will be the same value.
*/
newSymbolFor(key: string | symbol): QuickJSHandle {
const description = (typeof key === "symbol" ? key.description : key) ?? ""
const ptr = this.memory
.newHeapCharPointer(description)
.consume((charHandle) => this.ffi.QTS_NewSymbol(this.ctx.value, charHandle.value.ptr, 1))
return this.memory.heapValueHandle(ptr)
}
/**
* Access a well-known symbol that is a property of the global Symbol object, like `Symbol.iterator`.
*/
getWellKnownSymbol(name: string): QuickJSHandle {
this._Symbol ??= this.memory.manage(this.getProp(this.global, "Symbol"))
return this.getProp(this._Symbol, name)
}
/**
* Create a QuickJS [bigint](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt) value.
*/
newBigInt(num: bigint): QuickJSHandle {
if (!this._BigInt) {
const bigIntHandle = this.getProp(this.global, "BigInt")
this.memory.manage(bigIntHandle)
this._BigInt = new StaticLifetime(bigIntHandle.value as JSValueConstPointer, this.runtime)
}
const bigIntHandle = this._BigInt
const asString = String(num)
return this.newString(asString).consume((handle) =>
this.unwrapResult(this.callFunction(bigIntHandle, this.undefined, handle)),
)
}
/**
* `{}`.
* Create a new QuickJS [object](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer).
*
* @param prototype - Like [`Object.create`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/create).
*/
newObject(prototype?: QuickJSHandle): QuickJSHandle {
if (prototype) {
this.runtime.assertOwned(prototype)
}
const ptr = prototype
? this.ffi.QTS_NewObjectProto(this.ctx.value, prototype.value)
: this.ffi.QTS_NewObject(this.ctx.value)
return this.memory.heapValueHandle(ptr)
}
/**
* `[]`.
* Create a new QuickJS [array](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array).
*/
newArray(): QuickJSHandle {
const ptr = this.ffi.QTS_NewArray(this.ctx.value)
return this.memory.heapValueHandle(ptr)
}
/**
* Create a new QuickJS [ArrayBuffer](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer).
*/
newArrayBuffer(buffer: ArrayBufferLike): QuickJSHandle {
const array = new Uint8Array(buffer)
const handle = this.memory.newHeapBufferPointer(array)
const ptr = this.ffi.QTS_NewArrayBuffer(this.ctx.value, handle.value.pointer, array.length)
return this.memory.heapValueHandle(ptr)
}
/**
* Create a new {@link QuickJSDeferredPromise}. Use `deferred.resolve(handle)` and
* `deferred.reject(handle)` to fulfill the promise handle available at `deferred.handle`.
* Note that you are responsible for calling `deferred.dispose()` to free the underlying
* resources; see the documentation on {@link QuickJSDeferredPromise} for details.
*/
newPromise(): QuickJSDeferredPromise
/**
* Create a new {@link QuickJSDeferredPromise} that resolves when the
* given native Promise<QuickJSHandle> resolves. Rejections will be coerced
* to a QuickJS error.
*
* You can still resolve/reject the created promise "early" using its methods.
*/
newPromise(promise: Promise<QuickJSHandle>): QuickJSDeferredPromise
/**
* Construct a new native Promise<QuickJSHandle>, and then convert it into a
* {@link QuickJSDeferredPromise}.
*
* You can still resolve/reject the created promise "early" using its methods.
*/
newPromise(
newPromiseFn: PromiseExecutor<QuickJSHandle, Error | QuickJSHandle>,
): QuickJSDeferredPromise
newPromise(
value?: PromiseExecutor<QuickJSHandle, Error | QuickJSHandle> | Promise<QuickJSHandle>,
): QuickJSDeferredPromise {
const deferredPromise = Scope.withScope((scope) => {
const mutablePointerArray = scope.manage(
this.memory.newMutablePointerArray<JSValuePointerPointer>(2),
)
const promisePtr = this.ffi.QTS_NewPromiseCapability(
this.ctx.value,
mutablePointerArray.value.ptr,
)
const promiseHandle = this.memory.heapValueHandle(promisePtr)
const [resolveHandle, rejectHandle] = Array.from(
mutablePointerArray.value.typedArray.value,
).map((jsvaluePtr) => this.memory.heapValueHandle(jsvaluePtr as any))
return new QuickJSDeferredPromise({
context: this,
promiseHandle,
resolveHandle,
rejectHandle,
})
})
if (value && typeof value === "function") {
value = new Promise(value)
}
if (value) {
Promise.resolve(value).then(deferredPromise.resolve, (error) =>
error instanceof Lifetime
? deferredPromise.reject(error)
: this.newError(error).consume(deferredPromise.reject),
)
}
return deferredPromise
}
/**
* Convert a Javascript function into a QuickJS function value.
* See {@link VmFunctionImplementation} for more details.
*
* A {@link VmFunctionImplementation} should not free its arguments or its return
* value. A VmFunctionImplementation should also not retain any references to
* its return value.
*
* For constructors (functions that will be called with `new ...`), use {@link newConstructorFunction}.
*
* The function argument handles are automatically disposed when the function
* returns. If you want to retain a handle beyond the end of the function, you
* can call {@link Lifetime#dup} to create a copy of the handle that you own
* and must dispose manually. For example, you need to use this API and do some
* extra book keeping to implement `setInterval`:
*
* ```typescript
* // This won't work because `callbackHandle` expires when the function returns,
* // so when the interval fires, the callback handle is already disposed.
* const WRONG_setIntervalHandle = context.newFunction("setInterval", (callbackHandle, delayHandle) => {
* const delayMs = context.getNumber(delayHandle)
* const intervalId = globalThis.setInterval(() => {
* // ERROR: callbackHandle is already disposed here.
* context.callFunction(callbackHandle)
* }, intervalId)
* return context.newNumber(intervalId)
* })
*
* // This works since we dup the callbackHandle.
* // We just need to make sure we clean it up manually when the interval is cleared --
* // so we need to keep track of those interval IDs, and make sure we clean all
* // of them up when we dispose the owning context.
*
* const setIntervalHandle = context.newFunction("setInterval", (callbackHandle, delayHandle) => {
* // Ensure the guest can't overload us by scheduling too many intervals.
* if (QuickJSInterval.INTERVALS.size > 100) {
* throw new Error(`Too many intervals scheduled already`)
* }
*
* const delayMs = context.getNumber(delayHandle)
* const longLivedCallbackHandle = callbackHandle.dup()
* const intervalId = globalThis.setInterval(() => {
* context.callFunction(longLivedCallbackHandle)
* }, intervalId)
* const disposable = new QuickJSInterval(longLivedCallbackHandle, context, intervalId)
* QuickJSInterval.INTERVALS.set(intervalId, disposable)
* return context.newNumber(intervalId)
* })
*
* const clearIntervalHandle = context.newFunction("clearInterval", (intervalIdHandle) => {
* const intervalId = context.getNumber(intervalIdHandle)
* const disposable = QuickJSInterval.INTERVALS.get(intervalId)
* disposable?.dispose()
* })
*
* class QuickJSInterval extends UsingDisposable {
* static INTERVALS = new Map<number, QuickJSInterval>()
*
* static disposeContext(context: QuickJSContext) {
* for (const interval of QuickJSInterval.INTERVALS.values()) {
* if (interval.context === context) {
* interval.dispose()
* }
* }
* }
*
* constructor(
* public fnHandle: QuickJSHandle,
* public context: QuickJSContext,
* public intervalId: number,
* ) {
* super()
* }
*
* dispose() {
* globalThis.clearInterval(this.intervalId)
* this.fnHandle.dispose()
* QuickJSInterval.INTERVALS.delete(this.fnHandle.value)
* }
*
* get alive() {
* return this.fnHandle.alive
* }
* }
* ```
*
* To implement an async function, create a promise with {@link newPromise}, then
* return the deferred promise handle from `deferred.handle` from your
* function implementation:
*
* ```typescript
* const deferred = vm.newPromise()
* someNativeAsyncFunction().then(deferred.resolve)
* return deferred.handle
* ```
*/
newFunction(fn: VmFunctionImplementation<QuickJSHandle>): QuickJSHandle
newFunction(name: string | undefined, fn: VmFunctionImplementation<QuickJSHandle>): QuickJSHandle
newFunction(
nameOrFn: string | undefined | VmFunctionImplementation<QuickJSHandle>,
maybeFn?: VmFunctionImplementation<QuickJSHandle>,
): QuickJSHandle {
const fn = typeof nameOrFn === "function" ? nameOrFn : maybeFn
if (!fn) {
throw new TypeError("Expected a function")
}
return this.newFunctionWithOptions({
name: typeof nameOrFn === "string" ? nameOrFn : undefined,
length: fn.length,
isConstructor: false,
fn,
})
}
/**
* Convert a Javascript function into a QuickJS constructor function.
* See {@link newFunction} for more details.
*/
newConstructorFunction(fn: VmFunctionImplementation<QuickJSHandle>): QuickJSHandle
newConstructorFunction(
name: string | undefined,
fn: VmFunctionImplementation<QuickJSHandle>,
): QuickJSHandle
newConstructorFunction(
nameOrFn: string | undefined | VmFunctionImplementation<QuickJSHandle>,
maybeFn?: VmFunctionImplementation<QuickJSHandle>,
): QuickJSHandle {
const fn = typeof nameOrFn === "function" ? nameOrFn : maybeFn
if (!fn) {
throw new TypeError("Expected a function")
}
return this.newFunctionWithOptions({
name: typeof nameOrFn === "string" ? nameOrFn : undefined,
length: fn.length,
isConstructor: true,
fn,
})
}
/**
* Lower-level API for creating functions.
* See {@link newFunction} for more details on how to use functions.
*/
newFunctionWithOptions(args: {
name: string | undefined
length: number
isConstructor: boolean
fn: VmFunctionImplementation<QuickJSHandle>
}): QuickJSHandle {
const { name, length, isConstructor, fn } = args
const refId = this.runtime.hostRefs.put(fn)
try {
return this.memory.heapValueHandle(
this.ffi.QTS_NewFunction(this.ctx.value, name ?? "", length, isConstructor, refId),
)
} catch (error) {
this.runtime.hostRefs.delete(refId)
throw error
}
}
newError(error: { name: string; message: string }): QuickJSHandle
newError(message: string): QuickJSHandle
newError(): QuickJSHandle
newError(error?: string | { name: string; message: string }): QuickJSHandle {
const errorHandle = this.memory.heapValueHandle(this.ffi.QTS_NewError(this.ctx.value))
if (error && typeof error === "object") {
if (error.name !== undefined) {
this.newString(error.name).consume((handle) => this.setProp(errorHandle, "name", handle))
}
if (error.message !== undefined) {
this.newString(error.message).consume((handle) =>
this.setProp(errorHandle, "message", handle),
)
}
} else if (typeof error === "string") {
this.newString(error).consume((handle) => this.setProp(errorHandle, "message", handle))
} else if (error !== undefined) {
// This isn't supported in the type signature but maybe it will make life easier.
this.newString(String(error)).consume((handle) =>
this.setProp(errorHandle, "message", handle),
)
}
return errorHandle
}
/**
* Create an opaque handle object that stores a reference to a host JavaScript object.
*
* The guest cannot access the host object directly, but you may use
* {@link getHostRef} to convert a HostRef handle back into a HostRef<T> from
* inside a function implementation.
*
* You must call {@link HostRef#dispose} or otherwise consume the {@link HostRef#handle} to ensure the handle is not leaked.
*/
newHostRef<T extends object>(value: T): HostRef<T> {
const id = this.runtime.hostRefs.put(value)
try {
const handle = this.memory.heapValueHandle(this.ffi.QTS_NewHostRef(this.ctx.value, id))
return new HostRef(this.runtime, handle, id)
} catch (error) {
this.runtime.hostRefs.delete(id)
throw error
}
}
/**
* If `handle` is a `HostRef<T>.handle`, return a new `HostRef<T>` instance wrapping the handle.
*
* You must call {@link HostRef#dispose} or otherwise consume the {@link HostRef#handle} to ensure the handle is not leaked.
*/
toHostRef<T extends object>(handle: QuickJSHandle): HostRef<T> | undefined {
const id = this.ffi.QTS_GetHostRefId(handle.value)
if (id === 0) {
return undefined
}
// Assert id is valid
this.runtime.hostRefs.get(id) as T
return new HostRef(this.runtime, handle.dup(), id)
}
/**
* If `handle` is a `HostRef<T>.handle`, return the host value `T`.
* @throws {@link QuickJSHostRefInvalid} if `handle` is not a `HostRef<T>.handle`
*/
unwrapHostRef<T extends object>(handle: QuickJSHandle): T {
const id = this.ffi.QTS_GetHostRefId(handle.value)
if (id === 0) {
throw new QuickJSHostRefInvalid("handle is not a HostRef")
}
return this.runtime.hostRefs.get(id) as T
}
// Read values --------------------------------------------------------------
/**
* `typeof` operator. **Not** [standards compliant](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/typeof).
*
* @remarks
* Does not support BigInt values correctly.
*/
typeof(handle: QuickJSHandle) {
this.runtime.assertOwned(handle)
return this.memory.consumeHeapCharPointer(this.ffi.QTS_Typeof(this.ctx.value, handle.value))
}
/**
* Converts `handle` into a Javascript number.
* @returns `NaN` on error, otherwise a `number`.
*/
getNumber(handle: QuickJSHandle): number {
this.runtime.assertOwned(handle)
return this.ffi.QTS_GetFloat64(this.ctx.value, handle.value)
}
/**
* Converts `handle` to a Javascript string.
*/
getString(handle: QuickJSHandle): string {
this.runtime.assertOwned(handle)
return this.memory.consumeJSCharPointer(this.ffi.QTS_GetString(this.ctx.value, handle.value))
}
/**
* Converts `handle` into a Javascript symbol. If the symbol is in the global
* registry in the guest, it will be created with Symbol.for on the host.
*/
getSymbol(handle: QuickJSHandle): symbol {
this.runtime.assertOwned(handle)
const key = this.memory.consumeJSCharPointer(
this.ffi.QTS_GetSymbolDescriptionOrKey(this.ctx.value, handle.value),
)
const isGlobal = this.ffi.QTS_IsGlobalSymbol(this.ctx.value, handle.value)
return isGlobal ? Symbol.for(key) : Symbol(key)
}
/**
* Converts `handle` to a Javascript bigint.
*/
getBigInt(handle: QuickJSHandle): bigint {
this.runtime.assertOwned(handle)
const asString = this.getString(handle)
return BigInt(asString)
}
/**
* Coverts `handle` to a JavaScript ArrayBuffer
*/
getArrayBuffer(handle: QuickJSHandle): Lifetime<Uint8Array> {
this.runtime.assertOwned(handle)
const len = this.ffi.QTS_GetArrayBufferLength(this.ctx.value, handle.value)
const ptr = this.ffi.QTS_GetArrayBuffer(this.ctx.value, handle.value)
if (!ptr) {
throw new Error("Couldn't allocate memory to get ArrayBuffer")
}
return new Lifetime(this.module.HEAPU8.subarray(ptr, ptr + len), undefined, () =>
this.module._free(ptr),
)
}
/**
* Get the current state of a QuickJS promise, see {@link JSPromiseState} for the possible states.
* This can be used to expect a promise to be fulfilled when combined with {@link unwrapResult}:
*
* ```typescript
* const promiseHandle = context.evalCode(`Promise.resolve(42)`);
* const resultHandle = context.unwrapResult(
* context.getPromiseState(promiseHandle)
* );
* context.getNumber(resultHandle) === 42; // true
* resultHandle.dispose();
* ```
*/
getPromiseState(handle: QuickJSHandle): JSPromiseState {
this.runtime.assertOwned(handle)
const state = this.ffi.QTS_PromiseState(this.ctx.value, handle.value)
if (state < 0) {
// Not a promise, but act like `await` would with non-promise, and just return the value.
return { type: "fulfilled", value: handle, notAPromise: true }
}
if (state === JSPromiseStateEnum.Pending) {
return {
type: "pending",
get error() {
return new QuickJSPromisePending(`Cannot unwrap a pending promise`)
},
}
}
const ptr = this.ffi.QTS_PromiseResult(this.ctx.value, handle.value)
const result = this.memory.heapValueHandle(ptr)
if (state === JSPromiseStateEnum.Fulfilled) {
return { type: "fulfilled", value: result }
}
if (state === JSPromiseStateEnum.Rejected) {
return { type: "rejected", error: result }
}
result.dispose()
throw new Error(`Unknown JSPromiseStateEnum: ${state}`)
}
/**
* `Promise.resolve(value)`.
* Convert a handle containing a Promise-like value inside the VM into an
* actual promise on the host.
*
* @remarks
* You may need to call {@link runtime}.{@link QuickJSRuntime#executePendingJobs} to ensure that the promise is resolved.
*
* @param promiseLikeHandle - A handle to a Promise-like value with a `.then(onSuccess, onError)` method.
*/
resolvePromise(promiseLikeHandle: QuickJSHandle): Promise<QuickJSContextResult<QuickJSHandle>> {
this.runtime.assertOwned(promiseLikeHandle)
const vmResolveResult = Scope.withScope((scope) => {
const vmPromise = scope.manage(this.getProp(this.global, "Promise"))
const vmPromiseResolve = scope.manage(this.getProp(vmPromise, "resolve"))
return this.callFunction(vmPromiseResolve, vmPromise, promiseLikeHandle)
})
if (vmResolveResult.error) {
return Promise.resolve(vmResolveResult)
}
return new Promise<QuickJSContextResult<QuickJSHandle>>((resolve) => {
Scope.withScope((scope) => {
const resolveHandle = scope.manage(
this.newFunction("resolve", (value) => {
resolve(this.success(value && value.dup()))
}),
)
const rejectHandle = scope.manage(
this.newFunction("reject", (error) => {
resolve(this.fail(error && error.dup()))
}),
)
const promiseHandle = scope.manage(vmResolveResult.value)
const promiseThenHandle = scope.manage(this.getProp(promiseHandle, "then"))
this.callFunction(promiseThenHandle, promiseHandle, resolveHandle, rejectHandle)
.unwrap()
.dispose()
})
})
}
// Compare -----------------------------------------------------------
private isEqual(
a: QuickJSHandle,
b: QuickJSHandle,
equalityType: IsEqualOp = IsEqualOp.IsStrictlyEqual,
): boolean {
if (a === b) {
return true
}
this.runtime.assertOwned(a)
this.runtime.assertOwned(b)
const result = this.ffi.QTS_IsEqual(this.ctx.value, a.value, b.value, equalityType)
if (result === -1) {
throw new QuickJSNotImplemented("WASM variant does not expose equality")
}
return Boolean(result)
}
/**
* `handle === other` - IsStrictlyEqual.
* See [Equality comparisons and sameness](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Equality_comparisons_and_sameness).
*/
eq(handle: QuickJSHandle, other: QuickJSHandle): boolean {
return this.isEqual(handle, other, IsEqualOp.IsStrictlyEqual)
}
/**
* `Object.is(a, b)`
* See [Equality comparisons and sameness](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Equality_comparisons_and_sameness).
*/
sameValue(handle: QuickJSHandle, other: QuickJSHandle): boolean {
return this.isEqual(handle, other, IsEqualOp.IsSameValue)
}
/**
* SameValueZero comparison.
* See [Equality comparisons and sameness](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Equality_comparisons_and_sameness).
*/
sameValueZero(handle: QuickJSHandle, other: QuickJSHandle): boolean {
return this.isEqual(handle, other, IsEqualOp.IsSameValueZero)
}
// Properties ---------------------------------------------------------------
/**
* `handle[key]`.
* Get a property from a JSValue.
*
* @param key - The property may be specified as a JSValue handle, or as a
* Javascript string (which will be converted automatically).
*/
getProp(handle: QuickJSHandle, key: QuickJSPropertyKey): QuickJSHandle {
this.runtime.assertOwned(handle)
let ptr: JSValuePointer
if (typeof key === "number" && key >= 0) {
// Index access fast path
ptr = this.ffi.QTS_GetPropNumber(this.ctx.value, handle.value, key)
} else {
ptr = this.borrowPropertyKey(key).consume((quickJSKey) =>
this.ffi.QTS_GetProp(this.ctx.value, handle.value, quickJSKey.value),
)
}
const result = this.memory.heapValueHandle(ptr)
return result
}
/**
* `handle.length` as a host number.
*
* Example use:
* ```typescript
* const length = context.getLength(arrayHandle) ?? 0
* for (let i = 0; i < length; i++) {
* using value = context.getProp(arrayHandle, i)
* console.log(`array[${i}] =`, context.dump(value))
* }
* ```
*
* @returns a number if the handle has a numeric length property, otherwise `undefined`.
*/
getLength(handle: QuickJSHandle): number | undefined {
this.runtime.assertOwned(handle)
const status = this.ffi.QTS_GetLength(this.ctx.value, this.uint32Out.value.ptr, handle.value)
if (status < 0) {
return undefined
}
return this.uint32Out.value.typedArray.value[0]
}
/**