-
Notifications
You must be signed in to change notification settings - Fork 23
Expand file tree
/
Copy pathcontext.go
More file actions
1399 lines (1218 loc) · 41.6 KB
/
context.go
File metadata and controls
1399 lines (1218 loc) · 41.6 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
package quickjs
import (
"fmt"
"os"
goruntime "runtime"
"strings"
"sync"
"sync/atomic"
"time"
"unsafe"
)
/*
#include <stdint.h> // for uintptr_t
#include "bridge.h"
*/
import "C"
// Context represents a Javascript context (or Realm). Each JSContext has its own global objects and system objects. There can be several JSContexts per JSRuntime and they can share objects, similar to frames of the same origin sharing Javascript objects in a web browser.
type Context struct {
contextID uint64
runtime *Runtime
ref *C.JSContext
globals *Value
handleStore *handleStore // function handle storage
jobQueue chan func(*Context)
jobClosed chan struct{}
closeOnce sync.Once
}
// hasValidRef reports whether the context still has a valid native handle.
func (ctx *Context) hasValidRef() bool {
if ctx == nil || ctx.ref == nil || ctx.runtime == nil {
return false
}
return ctx.runtime.ensureOwnerAccess()
}
// isAlive reports whether the context can safely reach QuickJS.
func (ctx *Context) isAlive() bool {
if ctx == nil || ctx.ref == nil {
return false
}
if ctx.runtime == nil {
return false
}
return ctx.runtime.isAlive()
}
const defaultJobQueueSize = 1024
// awaitPollInterval is the duration the Await loop sleeps when no JS or Go
// jobs are pending. Keeps CPU usage low while ensuring Go-scheduled work
// (e.g., resolved Promises from goroutines) is picked up promptly.
const awaitPollInterval = time.Millisecond
// awaitPromiseStateHook and awaitExecutePendingJobHook are used only in tests to
// force specific Await code paths; they must remain nil in production.
var (
awaitPromiseStateHook func(ctx *Context, promise *Value, current int) (int, bool)
awaitExecutePendingJobHook func(ctx *Context, promise *Value, current int) (int, bool)
awaitHasPendingGoJobsHook func(ctx *Context, promise *Value, current bool) (bool, bool)
// loadModuleCompileHook is used only in tests to force LoadModule compile failures.
// It must remain nil in production.
loadModuleCompileHook func(ctx *Context, code string, moduleName string) ([]byte, error)
)
func mayContainModuleSyntax(code string) bool {
return strings.Contains(code, "import") ||
strings.Contains(code, "export") ||
strings.Contains(code, "await")
}
func zeroTerminatedBytes(s string) []byte {
b := make([]byte, len(s)+1)
copy(b, s)
return b
}
func (ctx *Context) detectModuleSource(code string, codePtr *C.char) bool {
if !mayContainModuleSyntax(code) || !ctx.hasValidRef() {
return false
}
return C.DetectModuleSourceWithProbe(ctx.ref, codePtr, C.size_t(len(code))) != 0
}
func (ctx *Context) initScheduler() {
ctx.jobQueue = make(chan func(*Context), defaultJobQueueSize)
ctx.jobClosed = make(chan struct{})
}
// Schedule enqueues a job to be executed on the Context's thread.
// Jobs run sequentially via ProcessJobs to keep QuickJS access single-threaded.
func (ctx *Context) Schedule(job func(*Context)) bool {
if ctx == nil || ctx.jobQueue == nil || job == nil {
return false
}
select {
case <-ctx.jobClosed:
return false
default:
}
select {
case ctx.jobQueue <- job:
return true
case <-ctx.jobClosed:
return false
}
}
// ProcessJobs drains all pending scheduled jobs.
// Call this regularly (e.g., inside Loop or Await) to allow resolve/reject handlers to run.
func (ctx *Context) ProcessJobs() {
if ctx == nil || ctx.jobQueue == nil {
return
}
for {
select {
case job := <-ctx.jobQueue:
if job != nil {
job(ctx)
}
default:
return
}
}
}
func (ctx *Context) drainJobs() {
if ctx == nil || ctx.jobQueue == nil {
return
}
for {
select {
case <-ctx.jobQueue:
continue
default:
return
}
}
}
func (ctx *Context) duplicateValue(val *Value) *Value {
if !ctx.hasValidRef() || !val.hasValidContext() || val.ctx != ctx {
return nil
}
return &Value{ctx: ctx, ref: C.JS_DupValue(ctx.ref, val.ref)}
}
func (ctx *Context) wrapPromiseCallback(fn *Value) (func(*Value), func()) {
if fn == nil {
noop := func(*Value) {}
return noop, func() {}
}
fnRef := ctx.duplicateValue(fn)
var consumed atomic.Bool
release := func() {
if !consumed.Swap(true) && fnRef != nil {
fnRef.Free()
}
}
callback := func(arg *Value) {
if consumed.Swap(true) {
return
}
dupArg := ctx.duplicateValue(arg)
job := func(inner *Context) {
defer fnRef.Free()
var callArg *Value
if dupArg != nil {
callArg = dupArg
defer dupArg.Free()
} else {
callArg = inner.NewUndefined()
defer callArg.Free()
}
thisVal := inner.NewUndefined()
defer thisVal.Free()
result := fnRef.Execute(thisVal, callArg)
if result != nil {
result.Free()
}
}
if !ctx.Schedule(job) {
if dupArg != nil {
dupArg.Free()
}
fnRef.Free()
}
}
return callback, release
}
// Runtime returns the runtime of the context.
func (ctx *Context) Runtime() *Runtime {
if ctx == nil {
return nil
}
return ctx.runtime
}
// Free will free context and all associated objects.
func (ctx *Context) Close() {
if ctx == nil {
return
}
ctx.closeOnce.Do(func() {
if ctx.jobClosed != nil {
select {
case <-ctx.jobClosed:
default:
close(ctx.jobClosed)
}
}
ctx.drainJobs()
if ctx.globals != nil {
ctx.globals.Free()
}
// Clean up all registered function handles (critical for memory management)
if ctx.handleStore != nil {
ctx.handleStore.Clear()
}
if ctx.runtime != nil {
ctx.runtime.unregisterOwnedContext(ctx.ref, ctx.contextID)
}
// Remove from global mapping and release C context once.
if ctx.ref != nil {
unregisterContext(ctx.ref)
C.JS_FreeContext(ctx.ref)
}
ctx.ref = nil
ctx.globals = nil
ctx.handleStore = nil
ctx.jobQueue = nil
ctx.jobClosed = nil
ctx.contextID = 0
ctx.runtime = nil
})
}
// NewNull returns a null value.
func (ctx *Context) NewNull() *Value {
return &Value{ctx: ctx, ref: C.JS_NewNull()}
}
// Null return a null value.
// Deprecated: Use NewNull() instead.
func (ctx *Context) Null() *Value {
return ctx.NewNull()
}
// NewUndefined returns a undefined value.
func (ctx *Context) NewUndefined() *Value {
return &Value{ctx: ctx, ref: C.JS_NewUndefined()}
}
// Undefined return a undefined value.
// Deprecated: Use NewUndefined() instead.
func (ctx *Context) Undefined() *Value {
return ctx.NewUndefined()
}
// NewUninitialized returns a uninitialized value.
func (ctx *Context) NewUninitialized() *Value {
return &Value{ctx: ctx, ref: C.JS_NewUninitialized()}
}
// Uninitialized returns a uninitialized value.
// Deprecated: Use NewUninitialized() instead.
func (ctx *Context) Uninitialized() *Value {
return ctx.NewUninitialized()
}
// NewError returns a new exception value with given message.
func (ctx *Context) NewError(err error) *Value {
val := &Value{ctx: ctx, ref: C.JS_NewError(ctx.ref)}
val.Set("message", ctx.NewString(err.Error()))
return val
}
// Error returns a new exception value with given message.
// Deprecated: Use NewError() instead.
func (ctx *Context) Error(err error) *Value {
return ctx.NewError(err)
}
// NewBool returns a bool value with given bool.
func (ctx *Context) NewBool(b bool) *Value {
return &Value{ctx: ctx, ref: C.JS_NewBool(ctx.ref, C.bool(b))}
}
// Bool returns a bool value with given bool.
// Deprecated: Use NewBool() instead.
func (ctx *Context) Bool(b bool) *Value {
return ctx.NewBool(b)
}
// NewInt32 returns a int32 value with given int32.
func (ctx *Context) NewInt32(v int32) *Value {
return &Value{ctx: ctx, ref: C.JS_NewInt32(ctx.ref, C.int32_t(v))}
}
// Int32 returns a int32 value with given int32.
// Deprecated: Use NewInt32() instead.
func (ctx *Context) Int32(v int32) *Value {
return ctx.NewInt32(v)
}
// NewInt64 returns a int64 value with given int64.
func (ctx *Context) NewInt64(v int64) *Value {
return &Value{ctx: ctx, ref: C.JS_NewInt64(ctx.ref, C.int64_t(v))}
}
// Int64 returns a int64 value with given int64.
// Deprecated: Use NewInt64() instead.
func (ctx *Context) Int64(v int64) *Value {
return ctx.NewInt64(v)
}
// NewUint32 returns a uint32 value with given uint32.
func (ctx *Context) NewUint32(v uint32) *Value {
return &Value{ctx: ctx, ref: C.JS_NewUint32(ctx.ref, C.uint32_t(v))}
}
// Uint32 returns a uint32 value with given uint32.
// Deprecated: Use NewUint32() instead.
func (ctx *Context) Uint32(v uint32) *Value {
return ctx.NewUint32(v)
}
// NewBigInt64 returns a int64 value with given uint64.
func (ctx *Context) NewBigInt64(v int64) *Value {
return &Value{ctx: ctx, ref: C.JS_NewBigInt64(ctx.ref, C.int64_t(v))}
}
// BigInt64 returns a int64 value with given uint64.
// Deprecated: Use NewBigInt64() instead.
func (ctx *Context) BigInt64(v int64) *Value {
return ctx.NewBigInt64(v)
}
// NewBigUint64 returns a uint64 value with given uint64.
func (ctx *Context) NewBigUint64(v uint64) *Value {
return &Value{ctx: ctx, ref: C.JS_NewBigUint64(ctx.ref, C.uint64_t(v))}
}
// BigUint64 returns a uint64 value with given uint64.
// Deprecated: Use NewBigUint64() instead.
func (ctx *Context) BigUint64(v uint64) *Value {
return ctx.NewBigUint64(v)
}
// NewFloat64 returns a float64 value with given float64.
func (ctx *Context) NewFloat64(v float64) *Value {
return &Value{ctx: ctx, ref: C.JS_NewFloat64(ctx.ref, C.double(v))}
}
// Float64 returns a float64 value with given float64.
// Deprecated: Use NewFloat64() instead.
func (ctx *Context) Float64(v float64) *Value {
return ctx.NewFloat64(v)
}
// NewString returns a string value with given string.
func (ctx *Context) NewString(v string) *Value {
var ptr *C.char
if len(v) > 0 {
ptr = (*C.char)(unsafe.Pointer(unsafe.StringData(v)))
}
return &Value{ctx: ctx, ref: C.JS_NewStringLen(ctx.ref, ptr, C.size_t(len(v)))}
}
// NewDate returns a JavaScript Date object from epoch milliseconds.
func (ctx *Context) NewDate(epochMS float64) *Value {
if !ctx.hasValidRef() {
return nil
}
return &Value{ctx: ctx, ref: C.JS_NewDate(ctx.ref, C.double(epochMS))}
}
// NewSymbol returns a JavaScript local symbol.
func (ctx *Context) NewSymbol(description string) *Value {
if !ctx.hasValidRef() {
return nil
}
desc := C.CString(description)
defer C.free(unsafe.Pointer(desc))
return &Value{ctx: ctx, ref: C.JS_NewSymbol(ctx.ref, desc, C.bool(false))}
}
// NewGlobalSymbol returns a JavaScript global symbol.
func (ctx *Context) NewGlobalSymbol(description string) *Value {
if !ctx.hasValidRef() {
return nil
}
desc := C.CString(description)
defer C.free(unsafe.Pointer(desc))
return &Value{ctx: ctx, ref: C.JS_NewSymbol(ctx.ref, desc, C.bool(true))}
}
// String returns a string value with given string.
// Deprecated: Use NewString() instead.
func (ctx *Context) String(v string) *Value {
return ctx.NewString(v)
}
// NewArrayBuffer returns a ArrayBuffer value with given binary data.
func (ctx *Context) NewArrayBuffer(binaryData []byte) *Value {
if len(binaryData) == 0 {
return &Value{ctx: ctx, ref: C.JS_NewArrayBufferCopy(ctx.ref, nil, 0)}
}
return &Value{ctx: ctx, ref: C.JS_NewArrayBufferCopy(ctx.ref, (*C.uchar)(&binaryData[0]), C.size_t(len(binaryData)))}
}
// ArrayBuffer returns a ArrayBuffer value with given binary data.
// Deprecated: Use NewArrayBuffer() instead.
func (ctx *Context) ArrayBuffer(binaryData []byte) *Value {
return ctx.NewArrayBuffer(binaryData)
}
// createTypedArray is a helper function to create TypedArray with given data and type.
// It creates an ArrayBuffer first, then constructs a TypedArray from it.
func (ctx *Context) createTypedArray(data unsafe.Pointer, elementCount int, elementSize int, arrayType C.JSTypedArrayEnum) *Value {
// Calculate total bytes needed for the data
totalBytes := elementCount * elementSize
// Convert raw data pointer to Go byte slice using unsafe.Slice (Go 1.17+)
var bytes []byte
if totalBytes > 0 && data != nil {
bytes = unsafe.Slice((*byte)(data), totalBytes)
}
// Create ArrayBuffer from the byte data
buffer := ctx.NewArrayBuffer(bytes)
defer buffer.Free()
// Create TypedArray from ArrayBuffer: new TypedArray(buffer, offset, length)
offset := C.JS_NewInt32(ctx.ref, C.int(0)) // Start from beginning of buffer
length := C.JS_NewInt32(ctx.ref, C.int(elementCount)) // Number of elements (not bytes)
// Pack arguments for JS_NewTypedArray call
args := []C.JSValue{buffer.ref, offset, length}
return &Value{
ctx: ctx,
ref: C.JS_NewTypedArray(ctx.ref, C.int(len(args)), &args[0], arrayType),
}
}
// NewInt8Array returns a Int8Array value with given int8 slice.
func (ctx *Context) NewInt8Array(data []int8) *Value {
if len(data) == 0 {
return ctx.createTypedArray(nil, 0, 1, C.JSTypedArrayEnum(C.JS_TYPED_ARRAY_INT8))
}
return ctx.createTypedArray(unsafe.Pointer(&data[0]), len(data), 1, C.JSTypedArrayEnum(C.JS_TYPED_ARRAY_INT8))
}
// Int8Array returns a Int8Array value with given int8 slice.
// Deprecated: Use NewInt8Array() instead.
func (ctx *Context) Int8Array(data []int8) *Value {
return ctx.NewInt8Array(data)
}
// NewUint8Array returns a Uint8Array value with given uint8 slice.
func (ctx *Context) NewUint8Array(data []uint8) *Value {
if len(data) == 0 {
return ctx.createTypedArray(nil, 0, 1, C.JSTypedArrayEnum(C.JS_TYPED_ARRAY_UINT8))
}
return ctx.createTypedArray(unsafe.Pointer(&data[0]), len(data), 1, C.JSTypedArrayEnum(C.JS_TYPED_ARRAY_UINT8))
}
// Uint8Array returns a Uint8Array value with given uint8 slice.
// Deprecated: Use NewUint8Array() instead.
func (ctx *Context) Uint8Array(data []uint8) *Value {
return ctx.NewUint8Array(data)
}
// NewUint8ClampedArray returns a Uint8ClampedArray value with given uint8 slice.
func (ctx *Context) NewUint8ClampedArray(data []uint8) *Value {
if len(data) == 0 {
return ctx.createTypedArray(nil, 0, 1, C.JSTypedArrayEnum(C.JS_TYPED_ARRAY_UINT8C))
}
return ctx.createTypedArray(unsafe.Pointer(&data[0]), len(data), 1, C.JSTypedArrayEnum(C.JS_TYPED_ARRAY_UINT8C))
}
// Uint8ClampedArray returns a Uint8ClampedArray value with given uint8 slice.
// Deprecated: Use NewUint8ClampedArray() instead.
func (ctx *Context) Uint8ClampedArray(data []uint8) *Value {
return ctx.NewUint8ClampedArray(data)
}
// NewInt16Array returns a Int16Array value with given int16 slice.
func (ctx *Context) NewInt16Array(data []int16) *Value {
if len(data) == 0 {
return ctx.createTypedArray(nil, 0, 2, C.JSTypedArrayEnum(C.JS_TYPED_ARRAY_INT16))
}
return ctx.createTypedArray(unsafe.Pointer(&data[0]), len(data), 2, C.JSTypedArrayEnum(C.JS_TYPED_ARRAY_INT16))
}
// Int16Array returns a Int16Array value with given int16 slice.
// Deprecated: Use NewInt16Array() instead.
func (ctx *Context) Int16Array(data []int16) *Value {
return ctx.NewInt16Array(data)
}
// NewUint16Array returns a Uint16Array value with given uint16 slice.
func (ctx *Context) NewUint16Array(data []uint16) *Value {
if len(data) == 0 {
return ctx.createTypedArray(nil, 0, 2, C.JSTypedArrayEnum(C.JS_TYPED_ARRAY_UINT16))
}
return ctx.createTypedArray(unsafe.Pointer(&data[0]), len(data), 2, C.JSTypedArrayEnum(C.JS_TYPED_ARRAY_UINT16))
}
// Uint16Array returns a Uint16Array value with given uint16 slice.
// Deprecated: Use NewUint16Array() instead.
func (ctx *Context) Uint16Array(data []uint16) *Value {
return ctx.NewUint16Array(data)
}
// NewInt32Array returns a Int32Array value with given int32 slice.
func (ctx *Context) NewInt32Array(data []int32) *Value {
if len(data) == 0 {
return ctx.createTypedArray(nil, 0, 4, C.JSTypedArrayEnum(C.JS_TYPED_ARRAY_INT32))
}
return ctx.createTypedArray(unsafe.Pointer(&data[0]), len(data), 4, C.JSTypedArrayEnum(C.JS_TYPED_ARRAY_INT32))
}
// Int32Array returns a Int32Array value with given int32 slice.
// Deprecated: Use NewInt32Array() instead.
func (ctx *Context) Int32Array(data []int32) *Value {
return ctx.NewInt32Array(data)
}
// NewUint32Array returns a Uint32Array value with given uint32 slice.
func (ctx *Context) NewUint32Array(data []uint32) *Value {
if len(data) == 0 {
return ctx.createTypedArray(nil, 0, 4, C.JSTypedArrayEnum(C.JS_TYPED_ARRAY_UINT32))
}
return ctx.createTypedArray(unsafe.Pointer(&data[0]), len(data), 4, C.JSTypedArrayEnum(C.JS_TYPED_ARRAY_UINT32))
}
// Uint32Array returns a Uint32Array value with given uint32 slice.
// Deprecated: Use NewUint32Array() instead.
func (ctx *Context) Uint32Array(data []uint32) *Value {
return ctx.NewUint32Array(data)
}
// NewFloat32Array returns a Float32Array value with given float32 slice.
func (ctx *Context) NewFloat32Array(data []float32) *Value {
if len(data) == 0 {
return ctx.createTypedArray(nil, 0, 4, C.JSTypedArrayEnum(C.JS_TYPED_ARRAY_FLOAT32))
}
return ctx.createTypedArray(unsafe.Pointer(&data[0]), len(data), 4, C.JSTypedArrayEnum(C.JS_TYPED_ARRAY_FLOAT32))
}
// Float32Array returns a Float32Array value with given float32 slice.
// Deprecated: Use NewFloat32Array() instead.
func (ctx *Context) Float32Array(data []float32) *Value {
return ctx.NewFloat32Array(data)
}
// NewFloat64Array returns a Float64Array value with given float64 slice.
func (ctx *Context) NewFloat64Array(data []float64) *Value {
if len(data) == 0 {
return ctx.createTypedArray(nil, 0, 8, C.JSTypedArrayEnum(C.JS_TYPED_ARRAY_FLOAT64))
}
return ctx.createTypedArray(unsafe.Pointer(&data[0]), len(data), 8, C.JSTypedArrayEnum(C.JS_TYPED_ARRAY_FLOAT64))
}
// Float64Array returns a Float64Array value with given float64 slice.
// Deprecated: Use NewFloat64Array() instead.
func (ctx *Context) Float64Array(data []float64) *Value {
return ctx.NewFloat64Array(data)
}
// NewBigInt64Array returns a BigInt64Array value with given int64 slice.
func (ctx *Context) NewBigInt64Array(data []int64) *Value {
if len(data) == 0 {
return ctx.createTypedArray(nil, 0, 8, C.JSTypedArrayEnum(C.JS_TYPED_ARRAY_BIG_INT64))
}
return ctx.createTypedArray(unsafe.Pointer(&data[0]), len(data), 8, C.JSTypedArrayEnum(C.JS_TYPED_ARRAY_BIG_INT64))
}
// BigInt64Array returns a BigInt64Array value with given int64 slice.
// Deprecated: Use NewBigInt64Array() instead.
func (ctx *Context) BigInt64Array(data []int64) *Value {
return ctx.NewBigInt64Array(data)
}
// NewBigUint64Array returns a BigUint64Array value with given uint64 slice.
func (ctx *Context) NewBigUint64Array(data []uint64) *Value {
if len(data) == 0 {
return ctx.createTypedArray(nil, 0, 8, C.JSTypedArrayEnum(C.JS_TYPED_ARRAY_BIG_UINT64))
}
return ctx.createTypedArray(unsafe.Pointer(&data[0]), len(data), 8, C.JSTypedArrayEnum(C.JS_TYPED_ARRAY_BIG_UINT64))
}
// BigUint64Array returns a BigUint64Array value with given uint64 slice.
// Deprecated: Use NewBigUint64Array() instead.
func (ctx *Context) BigUint64Array(data []uint64) *Value {
return ctx.NewBigUint64Array(data)
}
// NewObject returns a new object value.
func (ctx *Context) NewObject() *Value {
return &Value{ctx: ctx, ref: C.JS_NewObject(ctx.ref)}
}
// Object returns a new object value.
// Deprecated: Use NewObject() instead.
func (ctx *Context) Object() *Value {
return ctx.NewObject()
}
// ParseJson parses given json string and returns a object value.
func (ctx *Context) ParseJSON(v string) *Value {
jsonBuf := zeroTerminatedBytes(v)
ptr := (*C.char)(unsafe.Pointer(&jsonBuf[0]))
filenameBuf := []byte{0}
filenamePtr := (*C.char)(unsafe.Pointer(&filenameBuf[0]))
var pinner goruntime.Pinner
pinner.Pin(&jsonBuf[0])
pinner.Pin(&filenameBuf[0])
defer pinner.Unpin()
parsed := C.JS_ParseJSON(ctx.ref, ptr, C.size_t(len(v)), filenamePtr)
goruntime.KeepAlive(jsonBuf)
goruntime.KeepAlive(filenameBuf)
return &Value{ctx: ctx, ref: parsed}
}
// NewFunction returns a js function value with given function template
// New implementation using HandleStore and JS_NewCFunction2 with magic parameter
func (ctx *Context) NewFunction(fn func(*Context, *Value, []*Value) *Value) *Value {
// Store function in HandleStore and get int32 ID
fnID := ctx.handleStore.Store(fn)
return &Value{
ctx: ctx,
ref: C.JS_NewCFunction2(
ctx.ref,
(*C.JSCFunction)(unsafe.Pointer(C.GoFunctionProxy)),
nil, // name (can be set later)
0, // length (auto-detected)
C.JS_CFUNC_generic_magic, // enable magic parameter support
C.int(fnID), // magic parameter passes function ID
),
}
}
// Function returns a js function value with given function template
// New implementation using HandleStore and JS_NewCFunction2 with magic parameter
// Deprecated: Use NewFunction() instead.
func (ctx *Context) Function(fn func(*Context, *Value, []*Value) *Value) *Value {
return ctx.NewFunction(fn)
}
// NewAsyncFunction returns a js async function value with given function template
//
// Deprecated: Use Context.NewFunction + Context.NewPromise instead for better memory management and thread safety.
// Example:
//
// asyncFn := ctx.NewFunction(func(ctx *quickjs.Context, this *quickjs.Value, args []*quickjs.Value) *quickjs.Value {
// return ctx.NewPromise(func(resolve, reject func(*quickjs.Value)) {
// // async work here
// resolve(ctx.NewString("result"))
// })
// })
func (ctx *Context) NewAsyncFunction(asyncFn func(ctx *Context, this *Value, promise *Value, args []*Value) *Value) *Value {
// New implementation using Function + Promise
return ctx.NewFunction(func(ctx *Context, this *Value, args []*Value) *Value {
return ctx.NewPromise(func(resolve, reject func(*Value)) {
// Create a promise object that has resolve/reject methods
promiseObj := ctx.NewObject()
promiseObj.Set("resolve", ctx.NewFunction(func(ctx *Context, this *Value, args []*Value) *Value {
if len(args) > 0 {
resolve(args[0])
} else {
resolve(ctx.NewUndefined())
}
return ctx.NewUndefined()
}))
promiseObj.Set("reject", ctx.NewFunction(func(ctx *Context, this *Value, args []*Value) *Value {
if len(args) > 0 {
reject(args[0])
} else {
errObj := ctx.NewError(fmt.Errorf("Promise rejected without reason"))
defer errObj.Free() // Free the error object
reject(errObj)
}
return ctx.NewUndefined()
}))
defer promiseObj.Free()
// Call the original async function with the promise object
result := asyncFn(ctx, this, promiseObj, args)
// If the function returned a value directly (not using promise.resolve/reject),
// we resolve with that value
if !result.IsUndefined() {
resolve(result)
result.Free() // Free the result if it's not undefined
}
})
})
}
// AsyncFunction returns a js async function value with given function template
//
// Deprecated: Use Context.NewFunction + Context.NewPromise instead for better memory management and thread safety.
// Example:
//
// asyncFn := ctx.NewFunction(func(ctx *quickjs.Context, this *quickjs.Value, args []*quickjs.Value) *quickjs.Value {
// return ctx.NewPromise(func(resolve, reject func(*quickjs.Value)) {
// // async work here
// resolve(ctx.NewString("result"))
// })
// })
func (ctx *Context) AsyncFunction(asyncFn func(ctx *Context, this *Value, promise *Value, args []*Value) *Value) *Value {
return ctx.NewAsyncFunction(asyncFn)
}
// getFunction gets function from HandleStore (internal use)
func (ctx *Context) loadFunctionFromHandleID(id int32) interface{} {
if ctx == nil || ctx.handleStore == nil || id <= 0 {
return nil
}
fn, _ := ctx.handleStore.Load(id)
return fn
}
// SetInterruptHandler sets a interrupt handler.
//
// Deprecated: Use SetInterruptHandler on runtime instead
func (ctx *Context) SetInterruptHandler(handler InterruptHandler) {
ctx.runtime.SetInterruptHandler(handler)
}
// NewAtom returns a new Atom value with given string.
func (ctx *Context) NewAtom(v string) *Atom {
var ptr *C.char
if len(v) > 0 {
ptr = (*C.char)(unsafe.Pointer(unsafe.StringData(v)))
}
return &Atom{ctx: ctx, ref: C.JS_NewAtomLen(ctx.ref, ptr, C.size_t(len(v)))}
}
// Atom returns a new Atom value with given string.
// Deprecated: Use NewAtom() instead.
func (ctx *Context) Atom(v string) *Atom {
return ctx.NewAtom(v)
}
// NewAtomIdx returns a new Atom value with given idx.
func (ctx *Context) NewAtomIdx(idx uint32) *Atom {
return &Atom{ctx: ctx, ref: C.JS_NewAtomUInt32(ctx.ref, C.uint32_t(idx))}
}
// AtomFromValue converts a value to an atom key.
func (ctx *Context) AtomFromValue(v *Value) *Atom {
if ctx == nil || !ctx.hasValidRef() || !v.belongsTo(ctx) {
return nil
}
atom := C.JS_ValueToAtom(ctx.ref, v.ref)
if atom == C.JS_ATOM_NULL {
return nil
}
return &Atom{ctx: ctx, ref: atom}
}
// AtomIdx returns a new Atom value with given idx.
// Deprecated: Use NewAtomIdx() instead.
func (ctx *Context) AtomIdx(idx uint32) *Atom {
return ctx.NewAtomIdx(idx)
}
// Invoke invokes a function with given this value and arguments.
// Deprecated: Use Value.Execute() instead for better API consistency.
func (ctx *Context) Invoke(fn *Value, this *Value, args ...*Value) *Value {
if ctx == nil || !ctx.hasValidRef() || !fn.belongsTo(ctx) || !this.belongsTo(ctx) {
return nil
}
cargs := []C.JSValue{}
for _, x := range args {
if !x.belongsTo(ctx) {
return nil
}
cargs = append(cargs, x.ref)
}
var val *Value
if len(cargs) == 0 {
val = &Value{ctx: ctx, ref: C.JS_Call(ctx.ref, fn.ref, this.ref, 0, nil)}
} else {
val = &Value{ctx: ctx, ref: C.JS_Call(ctx.ref, fn.ref, this.ref, C.int(len(cargs)), &cargs[0])}
}
return val
}
type EvalOptions struct {
js_eval_type_global bool
js_eval_type_module bool
js_eval_flag_strict bool
js_eval_flag_compile_only bool
filename string
await bool
load_only bool
}
type EvalOption func(*EvalOptions)
func EvalFlagGlobal(global bool) EvalOption {
return func(flags *EvalOptions) {
flags.js_eval_type_global = global
}
}
func EvalFlagModule(module bool) EvalOption {
return func(flags *EvalOptions) {
flags.js_eval_type_module = module
}
}
func EvalFlagStrict(strict bool) EvalOption {
return func(flags *EvalOptions) {
flags.js_eval_flag_strict = strict
}
}
func EvalFlagCompileOnly(compileOnly bool) EvalOption {
return func(flags *EvalOptions) {
flags.js_eval_flag_compile_only = compileOnly
}
}
func EvalFileName(filename string) EvalOption {
return func(flags *EvalOptions) {
flags.filename = filename
}
}
func EvalAwait(await bool) EvalOption {
return func(flags *EvalOptions) {
flags.await = await
}
}
func EvalLoadOnly(loadOnly bool) EvalOption {
return func(flags *EvalOptions) {
flags.load_only = loadOnly
}
}
// Eval returns a js value with given code.
// Need call Free() `quickjs.Value`'s returned by `Eval()` and `EvalFile()` and `EvalBytecode()`.
// func (ctx *Context) Eval(code string) (*Value, error) { return ctx.EvalFile(code, "code") }
func (ctx *Context) Eval(code string, opts ...EvalOption) *Value {
if !ctx.hasValidRef() {
return nil
}
options := EvalOptions{
js_eval_type_global: true,
filename: "<input>",
await: false,
}
for _, fn := range opts {
fn(&options)
}
cFlag := C.int(0)
if options.js_eval_type_global {
cFlag |= C.int(C.JS_EVAL_TYPE_GLOBAL)
}
if options.js_eval_type_module {
cFlag |= C.int(C.JS_EVAL_TYPE_MODULE)
}
if options.js_eval_flag_strict {
cFlag |= C.int(C.JS_EVAL_FLAG_STRICT)
}
if options.js_eval_flag_compile_only {
cFlag |= C.int(C.JS_EVAL_FLAG_COMPILE_ONLY)
}
codeBuf := zeroTerminatedBytes(code)
codePtr := (*C.char)(unsafe.Pointer(&codeBuf[0]))
filenameBuf := zeroTerminatedBytes(options.filename)
filenamePtr := (*C.char)(unsafe.Pointer(&filenameBuf[0]))
var pinner goruntime.Pinner
pinner.Pin(&codeBuf[0])
pinner.Pin(&filenameBuf[0])
defer pinner.Unpin()
if ctx.detectModuleSource(code, codePtr) {
cFlag |= C.int(C.JS_EVAL_TYPE_MODULE)
}
var evalResult C.JSValue
if options.await {
evalResult = C.EvalAndAwait(ctx.ref, codePtr, C.size_t(len(code)), filenamePtr, cFlag)
} else {
evalResult = C.JS_Eval(ctx.ref, codePtr, C.size_t(len(code)), filenamePtr, cFlag)
}
goruntime.KeepAlive(codeBuf)
goruntime.KeepAlive(filenameBuf)
return &Value{ctx: ctx, ref: evalResult}
}
// EvalFile returns a js value with given code and filename.
// Need call Free() `quickjs.Value`'s returned by `Eval()` and `EvalFile()` and `EvalBytecode()`.
func (ctx *Context) EvalFile(filePath string, opts ...EvalOption) *Value {
b, err := os.ReadFile(filePath)
if err != nil {
return ctx.ThrowError(err)
}
opts = append(opts, EvalFileName(filePath))
return ctx.Eval(string(b), opts...)
}
// LoadModule returns a js value with given code and module name.
func (ctx *Context) LoadModule(code string, moduleName string, opts ...EvalOption) *Value {
options := EvalOptions{
load_only: false,
}
for _, fn := range opts {
fn(&options)
}
codeBuf := zeroTerminatedBytes(code)
codePtr := (*C.char)(unsafe.Pointer(&codeBuf[0]))
var pinner goruntime.Pinner
pinner.Pin(&codeBuf[0])
defer pinner.Unpin()
isModule := ctx.detectModuleSource(code, codePtr)
goruntime.KeepAlive(codeBuf)
if !isModule {
return ctx.ThrowSyntaxError("not a module: %s", moduleName)
}
var (
codeByte []byte
err error
)
if loadModuleCompileHook != nil {
codeByte, err = loadModuleCompileHook(ctx, code, moduleName)
} else {
codeByte, err = ctx.Compile(code, EvalFlagModule(true), EvalFlagCompileOnly(true), EvalFileName(moduleName))
}
if err != nil {
return ctx.ThrowError(err)
}
return ctx.LoadModuleBytecode(codeByte, EvalLoadOnly(options.load_only))
}
// LoadModuleFile returns a js value with given file path and module name.
func (ctx *Context) LoadModuleFile(filePath string, moduleName string) *Value {
b, err := os.ReadFile(filePath)
if err != nil {
return ctx.ThrowError(err)
}
return ctx.LoadModule(string(b), moduleName)
}
// CompileModule returns a compiled bytecode with given code and module name.
func (ctx *Context) CompileModule(filePath string, moduleName string, opts ...EvalOption) ([]byte, error) {
opts = append(opts, EvalFileName(moduleName))
return ctx.CompileFile(filePath, opts...)
}
// LoadModuleByteCode returns a js value with given bytecode and module name.
func (ctx *Context) LoadModuleBytecode(buf []byte, opts ...EvalOption) *Value {
if !ctx.hasValidRef() {
return nil
}
if len(buf) == 0 {
return ctx.ThrowSyntaxError("empty bytecode")
}
options := EvalOptions{}
for _, fn := range opts {
fn(&options)