-
Notifications
You must be signed in to change notification settings - Fork 77
Expand file tree
/
Copy pathJSValue.cs
More file actions
1733 lines (1506 loc) · 70.2 KB
/
JSValue.cs
File metadata and controls
1733 lines (1506 loc) · 70.2 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
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using System;
using System.Buffers;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Numerics;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using Microsoft.JavaScript.NodeApi.Interop;
using Microsoft.JavaScript.NodeApi.Runtime;
using static Microsoft.JavaScript.NodeApi.JSValueScope;
using static Microsoft.JavaScript.NodeApi.Runtime.JSRuntime;
namespace Microsoft.JavaScript.NodeApi;
public readonly struct JSValue : IJSValue<JSValue>
{
private readonly napi_value _handle = default;
private readonly JSValueScope? _scope = null;
public readonly JSValueScope Scope => _scope ?? JSValueScope.Current;
internal JSRuntime Runtime => Scope.Runtime;
/// <summary>
/// Creates an empty instance of <see cref="JSValue" />, which implicitly converts to
/// <see cref="JSValue.Undefined" /> when used in any scope.
/// </summary>
public JSValue()
{
_handle = default;
_scope = null;
}
/// <summary>
/// Creates a new instance of <see cref="JSValue" /> from a handle in the current scope.
/// </summary>
/// <exception cref="ArgumentNullException">Thrown when the handle is null.</exception>
/// <remarks>
/// WARNING: A JS value handle is a pointer to a location in memory, so an invalid handle here
/// may cause an attempt to access an invalid memory location.
/// </remarks>
public JSValue(napi_value handle) : this(handle, Current) { }
/// <summary>
/// Creates a new instance of <see cref="JSValue" /> from a handle in the specified scope.
/// </summary>
/// <exception cref="ArgumentNullException">Thrown when the handle is null</exception>
/// <remarks>
/// WARNING: A JS value handle is a pointer to a location in memory, so an invalid handle here
/// may cause an attempt to access an invalid memory location.
/// </remarks>
public JSValue(napi_value handle, JSValueScope scope)
{
if (handle.IsNull) throw new ArgumentNullException(nameof(handle));
_handle = handle;
_scope = scope;
}
/// <summary>
/// Gets the value handle, or throws an exception if the value scope is disposed or
/// access from the current thread is invalid.
/// </summary>
/// <exception cref="JSValueScopeClosedException">The scope has been closed.</exception>
/// <exception cref="JSInvalidThreadAccessException">The scope is not valid on the current
/// thread.</exception>
public napi_value Handle
{
get
{
if (_scope == null)
{
// If the scope is null, this is an empty (uninitialized) instance.
// Implicitly convert to the JS `undefined` value.
return GetCurrentRuntime(out napi_env env)
.GetUndefined(env, out napi_value result).ThrowIfFailed(result);
}
// Ensure the scope is valid and on the current thread (environment).
_scope.ThrowIfDisposed();
_scope.ThrowIfInvalidThreadAccess();
// The handle must be non-null when the scope is non-null.
return _handle;
}
}
public static implicit operator JSValue(napi_value handle) => new(handle);
public static implicit operator JSValue?(napi_value handle) => handle.Handle != default ? new(handle) : default;
public static explicit operator napi_value(JSValue value) => value.Handle;
public static explicit operator napi_value(JSValue? value) => value?.Handle ?? default;
public static JSValue Undefined => default;
public static JSValue Null => GetCurrentRuntime(out napi_env env)
.GetNull(env, out napi_value result).ThrowIfFailed(result);
public static JSValue Global => GetCurrentRuntime(out napi_env env)
.GetGlobal(env, out napi_value result).ThrowIfFailed(result);
public static JSValue True => GetBoolean(true);
public static JSValue False => GetBoolean(false);
public static JSValue GetBoolean(bool value) => GetCurrentRuntime(out napi_env env)
.GetBoolean(env, value, out napi_value result).ThrowIfFailed(result);
public JSObject Properties => (JSObject)this;
public JSArray Items => (JSArray)this;
public JSValue this[JSValue name]
{
get => GetProperty(name);
set => SetProperty(name, value);
}
public JSValue this[string name]
{
get => GetProperty(name);
set => SetProperty(name, value);
}
public JSValue this[int index]
{
get => GetElement(index);
set => SetElement(index, value);
}
public static JSValue CreateObject() => GetCurrentRuntime(out napi_env env)
.CreateObject(env, out napi_value result).ThrowIfFailed(result);
public static JSValue CreateArray() => GetCurrentRuntime(out napi_env env)
.CreateArray(env, out napi_value result).ThrowIfFailed(result);
public static JSValue CreateArray(uint length) => GetCurrentRuntime(out napi_env env)
.CreateArray(env, length, out napi_value result).ThrowIfFailed(result);
public static JSValue CreateNumber(double value) => GetCurrentRuntime(out napi_env env)
.CreateNumber(env, value, out napi_value result).ThrowIfFailed(result);
public static JSValue CreateNumber(int value) => GetCurrentRuntime(out napi_env env)
.CreateNumber(env, value, out napi_value result).ThrowIfFailed(result);
public static JSValue CreateNumber(uint value) => GetCurrentRuntime(out napi_env env)
.CreateNumber(env, value, out napi_value result).ThrowIfFailed(result);
public static JSValue CreateNumber(long value) => GetCurrentRuntime(out napi_env env)
.CreateNumber(env, value, out napi_value result).ThrowIfFailed(result);
public static unsafe JSValue CreateStringUtf8(ReadOnlySpan<byte> value)
{
fixed (byte* spanPtr = value)
{
return GetCurrentRuntime(out napi_env env)
.CreateString(env, value, out napi_value result).ThrowIfFailed(result);
}
}
public static unsafe JSValue CreateStringUtf16(ReadOnlySpan<char> value)
{
fixed (char* spanPtr = value)
{
return GetCurrentRuntime(out napi_env env)
.CreateString(env, value, out napi_value result).ThrowIfFailed(result);
}
}
public static unsafe JSValue CreateStringUtf16(string value)
{
fixed (char* spanPtr = value)
{
return GetCurrentRuntime(out napi_env env)
.CreateString(env, value.AsSpan(), out napi_value result).ThrowIfFailed(result);
}
}
public static JSValue CreateSymbol(JSValue description) => GetCurrentRuntime(out napi_env env)
.CreateSymbol(env, (napi_value)description, out napi_value result).ThrowIfFailed(result);
public static JSValue SymbolFor(string name) => GetCurrentRuntime(out napi_env env)
.GetSymbolFor(env, name, out napi_value result).ThrowIfFailed(result);
public static JSValue CreateFunction(
string? name,
napi_callback callback,
nint data)
{
return GetCurrentRuntime(out napi_env env)
.CreateFunction(env, name, callback, data, out napi_value result).ThrowIfFailed(result);
}
public static unsafe JSValue CreateFunction(
string? name, JSCallback callback, object? callbackData = null)
{
GCHandle descriptorHandle = JSRuntimeContext.Current.AllocGCHandle(
new JSCallbackDescriptor(name, callback, callbackData));
JSValue func = CreateFunction(
name,
new napi_callback(
JSValueScope.Current?.ScopeType == JSValueScopeType.NoContext ?
s_invokeJSCallbackNC : s_invokeJSCallback),
(nint)descriptorHandle);
func.AddGCHandleFinalizer((nint)descriptorHandle);
return func;
}
public static JSValue CreateError(JSValue? code, JSValue message)
=> GetCurrentRuntime(out napi_env env)
.CreateError(env, (napi_value)code, (napi_value)message, out napi_value result)
.ThrowIfFailed(result);
public static JSValue CreateTypeError(JSValue? code, JSValue message)
=> GetCurrentRuntime(out napi_env env)
.CreateTypeError(env, (napi_value)code, (napi_value)message, out napi_value result)
.ThrowIfFailed(result);
public static JSValue CreateRangeError(JSValue? code, JSValue message)
=> GetCurrentRuntime(out napi_env env)
.CreateRangeError(env, (napi_value)code, (napi_value)message, out napi_value result)
.ThrowIfFailed(result);
public static JSValue CreateSyntaxError(JSValue? code, JSValue message)
=> GetCurrentRuntime(out napi_env env)
.CreateSyntaxError(env, (napi_value)code, (napi_value)message, out napi_value result)
.ThrowIfFailed(result);
public static unsafe JSValue CreateExternal(object value)
{
JSValueScope currentScope = JSValueScope.Current;
GCHandle valueHandle = currentScope.RuntimeContext.AllocGCHandle(value);
return currentScope.Runtime.CreateExternal(
currentScope.UncheckedEnvironmentHandle,
(nint)valueHandle,
new napi_finalize(s_finalizeGCHandle),
currentScope.RuntimeContextHandle,
out napi_value result)
.ThrowIfFailed(result);
}
public static JSValue CreateArrayBuffer(nuint byteLength)
=> GetCurrentRuntime(out napi_env env)
.CreateArrayBuffer(env, byteLength, out nint _, out napi_value result)
.ThrowIfFailed(result);
public static unsafe JSValue CreateArrayBuffer(ReadOnlySpan<byte> data)
{
GetCurrentRuntime(out napi_env env)
.CreateArrayBuffer(env, (nuint)data.Length, out nint buffer, out napi_value result)
.ThrowIfFailed();
data.CopyTo(new Span<byte>((void*)buffer, data.Length));
return result;
}
public static unsafe JSValue CreateExternalArrayBuffer<T>(
Memory<T> memory, object? external = null) where T : struct
{
var pinnedMemory = new PinnedMemory<T>(memory, external);
return GetCurrentRuntime(out napi_env env).CreateArrayBuffer(
env,
(nint)pinnedMemory.Pointer,
(nuint)pinnedMemory.Length,
// We pass object to finalize as a hint parameter
new napi_finalize(s_finalizeGCHandleToPinnedMemory),
(nint)pinnedMemory.RuntimeContext.AllocGCHandle(pinnedMemory),
out napi_value result)
.ThrowIfFailed(result);
}
public static JSValue CreateDataView(nuint length, JSValue arrayBuffer, nuint byteOffset)
=> GetCurrentRuntime(out napi_env env)
.CreateDataView(env, length, (napi_value)arrayBuffer, byteOffset, out napi_value result)
.ThrowIfFailed(result);
public static JSValue CreateTypedArray(
JSTypedArrayType type, nuint length, JSValue arrayBuffer, nuint byteOffset)
=> GetCurrentRuntime(out napi_env env).CreateTypedArray(
env,
(napi_typedarray_type)type,
length,
(napi_value)arrayBuffer,
byteOffset,
out napi_value result)
.ThrowIfFailed(result);
public static JSValue CreatePromise(out JSPromise.Deferred deferred)
{
GetCurrentRuntime(out napi_env env)
.CreatePromise(env, out napi_deferred deferred_, out napi_value promise)
.ThrowIfFailed();
deferred = new JSPromise.Deferred(deferred_);
return promise;
}
public static JSValue CreateDate(double time) => GetCurrentRuntime(out napi_env env)
.CreateDate(env, time, out napi_value result).ThrowIfFailed(result);
public static JSValue CreateBigInt(long value) => GetCurrentRuntime(out napi_env env)
.CreateBigInt(env, value, out napi_value result).ThrowIfFailed(result);
public static JSValue CreateBigInt(ulong value) => GetCurrentRuntime(out napi_env env)
.CreateBigInt(env, value, out napi_value result).ThrowIfFailed(result);
public static JSValue CreateBigInt(int signBit, ReadOnlySpan<ulong> words)
=> GetCurrentRuntime(out napi_env env)
.CreateBigInt(env, signBit, words, out napi_value result).ThrowIfFailed(result);
public static unsafe JSValue CreateBigInt(BigInteger value)
{
// .Net Framework 4.7.2 does not support Span-related methods for BigInteger.
int sign = value.Sign == -1 ? 1 : 0;
if (value.Sign == -1)
{
value = -value;
}
#if !(NETFRAMEWORK || NETSTANDARD)
int byteCount = value.GetByteCount(isUnsigned: true);
#else
byte[] bytes = value.ToByteArray();
int byteCount = bytes.Length;
#endif
int wordCount = (byteCount + sizeof(ulong) - 1) / sizeof(ulong);
Span<byte> byteSpan = stackalloc byte[wordCount * sizeof(ulong)];
#if !(NETFRAMEWORK || NETSTANDARD)
if (!value.TryWriteBytes(byteSpan, out int bytesWritten, isUnsigned: true))
{
throw new Exception("Cannot write BigInteger bytes");
}
#endif
fixed (byte* bytePtr = byteSpan)
{
#if NETFRAMEWORK || NETSTANDARD
Marshal.Copy(bytes, 0, (nint)bytePtr, bytes.Length);
#endif
ReadOnlySpan<ulong> words = new(bytePtr, wordCount);
return CreateBigInt(sign, words);
}
}
public unsafe BigInteger ToBigInteger()
{
JSRuntime runtime = GetRuntime(out napi_env env, out napi_value handle);
runtime.GetBigIntWordCount(env, handle, out nuint wordCount).ThrowIfFailed();
Span<ulong> words = stackalloc ulong[(int)(wordCount > 0 ? wordCount : 1)];
int byteCount = (int)wordCount * sizeof(ulong);
runtime.GetBigIntWords(env, handle, out int sign, words, out _).ThrowIfFailed();
fixed (ulong* wordPtr = words)
{
#if !(NETFRAMEWORK || NETSTANDARD)
BigInteger result = new(new ReadOnlySpan<byte>(wordPtr, byteCount), isUnsigned: true);
#else
byte[] bytes = new byte[byteCount];
Marshal.Copy((nint)wordPtr, bytes, 0, byteCount);
BigInteger result = new(bytes);
#endif
return sign == 1 ? -result : result;
}
}
public JSValueType TypeOf() => _handle.IsNull
? JSValueType.Undefined
: GetRuntime(out napi_env env).GetValueType(env, _handle, out napi_valuetype result)
.ThrowIfFailed((JSValueType)result);
public bool IsUndefined() => TypeOf() == JSValueType.Undefined;
public bool IsNull() => TypeOf() == JSValueType.Null;
public bool IsNullOrUndefined() => TypeOf() switch
{
JSValueType.Null => true,
JSValueType.Undefined => true,
_ => false,
};
public bool IsBoolean() => TypeOf() == JSValueType.Boolean;
public bool IsNumber() => TypeOf() == JSValueType.Number;
public bool IsString() => TypeOf() == JSValueType.String;
public bool IsSymbol() => TypeOf() == JSValueType.Symbol;
public bool IsObject() => TypeOf() switch
{
JSValueType.Object => true,
JSValueType.Function => true,
_ => false,
};
public bool IsFunction() => TypeOf() == JSValueType.Function;
public bool IsExternal() => TypeOf() == JSValueType.External;
public bool IsBigInt() => TypeOf() == JSValueType.BigInt;
#region IJSValue<JSValue> implementation
/// <summary>
/// Checks if the T struct can be created from this `JSValue`.
/// </summary>
/// <typeparam name="T">A struct that implements IJSValue interface.</typeparam>
/// <returns>
/// `true` if the T struct can be created from this `JSValue`. Otherwise it returns `false`.
/// </returns>
public bool Is<T>() where T : struct, IJSValue<T>
#if NET7_0_OR_GREATER
=> T.CanCreateFrom(this);
#else
=> IJSValueShim<T>.CanCreateFrom(this);
#endif
/// <summary>
/// Tries to create a T struct from this `JSValue`.
/// It returns `null` if the T struct cannot be created.
/// </summary>
/// <typeparam name="T">A struct that implements IJSValue interface.</typeparam>
/// <returns>
/// Nullable value that contains T struct if it was successfully created
/// or `null` if it was failed.
/// </returns>
public T? As<T>() where T : struct, IJSValue<T>
=> Is<T>() ? AsUnchecked<T>() : default(T?);
/// <summary>
/// Creates a T struct from this `JSValue` without checking the enclosed handle type.
/// It must be used only when the handle type is known to be correct.
/// </summary>
/// <typeparam name="T">A struct that implements IJSValue interface.</typeparam>
/// <returns>T struct created based on this `JSValue`.</returns>
public T AsUnchecked<T>() where T : struct, IJSValue<T>
#if NET7_0_OR_GREATER
=> T.CreateUnchecked(this);
#else
=> IJSValueShim<T>.CreateUnchecked(this);
#endif
/// <summary>
/// Creates a T struct from this `JSValue`.
/// It throws `InvalidCastException` in case of failure.
/// </summary>
/// <typeparam name="T">A struct that implements IJSValue interface.</typeparam>
/// <returns>T struct created based on this `JSValue`.</returns>
/// <exception cref="InvalidCastException">
/// Thrown when the T struct cannot be crated based on this `JSValue`.
/// </exception>
public T CastTo<T>() where T : struct, IJSValue<T>
=> As<T>()
?? throw new InvalidCastException(
$"JSValue cannot be casted to target type {typeof(T).Name}.");
#if NET7_0_OR_GREATER
static bool IJSValue<JSValue>.CanCreateFrom(JSValue _)
#else
#pragma warning disable IDE0051 // It is used by the IJSValueShim<T> class through reflection.
private static bool CanCreateFrom(JSValue _)
#pragma warning restore IDE0051
#endif
=> true;
#if NET7_0_OR_GREATER
static JSValue IJSValue<JSValue>.CreateUnchecked(JSValue value) => value;
#else
#pragma warning disable IDE0051 // It is used by the IJSValueShim<T> class through reflection.
private static JSValue CreateUnchecked(JSValue value) => value;
#pragma warning restore IDE0051
#endif
#endregion
public double GetValueDouble() => GetRuntime(out napi_env env, out napi_value handle)
.GetValueDouble(env, handle, out double result).ThrowIfFailed(result);
public int GetValueInt32() => GetRuntime(out napi_env env, out napi_value handle)
.GetValueInt32(env, handle, out int result).ThrowIfFailed(result);
public uint GetValueUInt32() => GetRuntime(out napi_env env, out napi_value handle)
.GetValueUInt32(env, handle, out uint result).ThrowIfFailed(result);
public long GetValueInt64() => GetRuntime(out napi_env env, out napi_value handle)
.GetValueInt64(env, handle, out long result).ThrowIfFailed(result);
public bool GetValueBool() => GetRuntime(out napi_env env, out napi_value handle)
.GetValueBool(env, handle, out bool result).ThrowIfFailed(result);
public int GetValueStringUtf8(Span<byte> buffer)
=> (int)GetRuntime(out napi_env env, out napi_value handle)
.GetValueStringUtf8(env, handle, buffer, out nuint result)
.ThrowIfFailed(result);
public byte[] GetValueStringUtf8()
{
JSRuntime runtime = GetRuntime(out napi_env env, out napi_value handle);
runtime.GetValueStringUtf8(env, handle, [], out nuint length).ThrowIfFailed();
byte[] result = new byte[length + 1];
runtime.GetValueStringUtf8(env, handle, new Span<byte>(result), out _).ThrowIfFailed();
// Remove the zero terminating character
Array.Resize(ref result, (int)length);
return result;
}
public unsafe int GetValueStringUtf16(Span<char> buffer)
=> (int)GetRuntime(out napi_env env, out napi_value handle)
.GetValueStringUtf16(env, handle, buffer, out nuint result)
.ThrowIfFailed(result);
public char[] GetValueStringUtf16AsCharArray()
{
JSRuntime runtime = GetRuntime(out napi_env env, out napi_value handle);
runtime.GetValueStringUtf16(env, handle, [], out nuint length).ThrowIfFailed();
char[] result = new char[length + 1];
runtime.GetValueStringUtf16(env, handle, new Span<char>(result), out _).ThrowIfFailed();
// Remove the zero terminating character
Array.Resize(ref result, (int)length);
return result;
}
public unsafe string GetValueStringUtf16()
{
#if NETFRAMEWORK || NETSTANDARD
return new string(GetValueStringUtf16AsCharArray());
#else
JSRuntime runtime = GetRuntime(out napi_env env, out napi_value handle);
runtime.GetValueStringUtf16(env, handle, [], out nuint length).ThrowIfFailed();
return string.Create((int)length, runtime, (span, runtime) =>
{
fixed (void* ptr = span)
{
runtime.GetValueStringUtf16(
env, handle, new Span<char>(ptr, span.Length + 1), out _).ThrowIfFailed();
}
});
#endif
}
public JSValue CoerceToBoolean() => GetRuntime(out napi_env env, out napi_value handle)
.CoerceToBool(env, handle, out napi_value result).ThrowIfFailed(result);
public JSValue CoerceToNumber() => GetRuntime(out napi_env env, out napi_value handle)
.CoerceToNumber(env, handle, out napi_value result).ThrowIfFailed(result);
public JSValue CoerceToObject() => GetRuntime(out napi_env env, out napi_value handle)
.CoerceToObject(env, handle, out napi_value result).ThrowIfFailed(result);
public JSValue CoerceToString() => GetRuntime(out napi_env env, out napi_value handle)
.CoerceToString(env, handle, out napi_value result).ThrowIfFailed(result);
public JSValue GetPrototype() => GetRuntime(out napi_env env, out napi_value handle)
.GetPrototype(env, handle, out napi_value result).ThrowIfFailed(result);
public JSValue GetPropertyNames() => GetRuntime(out napi_env env, out napi_value handle)
.GetPropertyNames(env, handle, out napi_value result).ThrowIfFailed(result);
public void SetProperty(JSValue key, JSValue value)
=> GetRuntime(out napi_env env, out napi_value handle)
.SetProperty(env, handle, key.Handle, value.Handle).ThrowIfFailed();
public bool HasProperty(JSValue key)
=> GetRuntime(out napi_env env, out napi_value handle)
.HasProperty(env, handle, key.Handle, out bool result).ThrowIfFailed(result);
public JSValue GetProperty(JSValue key)
=> GetRuntime(out napi_env env, out napi_value handle)
.GetProperty(env, handle, key.Handle, out napi_value result).ThrowIfFailed(result);
public bool DeleteProperty(JSValue key)
=> GetRuntime(out napi_env env, out napi_value handle)
.DeleteProperty(env, handle, key.Handle, out bool result).ThrowIfFailed(result);
public bool HasOwnProperty(JSValue key)
=> GetRuntime(out napi_env env, out napi_value handle)
.HasOwnProperty(env, handle, key.Handle, out bool result).ThrowIfFailed(result);
public void SetElement(int index, JSValue value)
=> GetRuntime(out napi_env env, out napi_value handle)
.SetElement(env, handle, (uint)index, value.Handle).ThrowIfFailed();
public bool HasElement(int index)
=> GetRuntime(out napi_env env, out napi_value handle)
.HasElement(env, handle, (uint)index, out bool result).ThrowIfFailed(result);
public JSValue GetElement(int index)
=> GetRuntime(out napi_env env, out napi_value handle)
.GetElement(env, handle, (uint)index, out napi_value result).ThrowIfFailed(result);
public bool DeleteElement(int index)
=> GetRuntime(out napi_env env, out napi_value handle)
.DeleteElement(env, handle, (uint)index, out bool result).ThrowIfFailed(result);
public unsafe void DefineProperties(IReadOnlyCollection<JSPropertyDescriptor> descriptors)
{
JSRuntime runtime = GetRuntime(out napi_env env, out napi_value handle);
nint[] descriptorHandles = ToUnmanagedPropertyDescriptors(
string.Empty,
descriptors,
(_, descriptorsPtr) => runtime.DefineProperties(env, handle, descriptorsPtr)
.ThrowIfFailed());
foreach (nint descriptorHandle in descriptorHandles)
{
AddGCHandleFinalizer(descriptorHandle);
}
}
public unsafe void DefineProperties(params JSPropertyDescriptor[] descriptors)
{
JSRuntime runtime = GetRuntime(out napi_env env, out napi_value handle);
nint[] descriptorHandles = ToUnmanagedPropertyDescriptors(
string.Empty,
descriptors,
(_, descriptorsPtr) => runtime.DefineProperties(env, handle, descriptorsPtr)
.ThrowIfFailed());
foreach (nint descriptorHandle in descriptorHandles)
{
AddGCHandleFinalizer(descriptorHandle);
}
}
public bool IsArray() => GetRuntime(out napi_env env, out napi_value handle)
.IsArray(env, handle, out bool result).ThrowIfFailed(result);
public int GetArrayLength() => (int)GetRuntime(out napi_env env, out napi_value handle)
.GetArrayLength(env, handle, out uint result).ThrowIfFailed(result);
// Internal because JSValue structs all implement IEquatable<JSValue>, which calls this method.
internal bool StrictEquals(JSValue other) => GetRuntime(out napi_env env, out napi_value handle)
.StrictEquals(env, handle, other.Handle, out bool result).ThrowIfFailed(result);
public unsafe JSValue Call()
=> GetRuntime(out napi_env env, out napi_value handle, out JSRuntime runtime)
.CallFunction(
env,
GetUndefined(runtime, env),
handle,
new ReadOnlySpan<napi_value>(),
out napi_value result).ThrowIfFailed(result);
public unsafe JSValue Call(JSValue thisArg)
=> GetRuntime(out napi_env env, out napi_value handle)
.CallFunction(env, thisArg.Handle, handle, [], out napi_value result)
.ThrowIfFailed(result);
public unsafe JSValue Call(JSValue thisArg, JSValue arg0)
{
Span<napi_value> args = stackalloc napi_value[] { arg0.Handle };
JSRuntime runtime = GetRuntime(out napi_env env, out napi_value handle);
return runtime.CallFunction(env, thisArg.Handle, handle, args, out napi_value result)
.ThrowIfFailed(result);
}
public unsafe JSValue Call(JSValue thisArg, JSValue arg0, JSValue arg1)
{
Span<napi_value> args = stackalloc napi_value[] { arg0.Handle, arg1.Handle };
JSRuntime runtime = GetRuntime(out napi_env env, out napi_value handle);
return runtime.CallFunction(env, thisArg.Handle, handle, args, out napi_value result)
.ThrowIfFailed(result);
}
public unsafe JSValue Call(JSValue thisArg, JSValue arg0, JSValue arg1, JSValue arg2)
{
Span<napi_value> args = stackalloc napi_value[]
{
arg0.Handle,
arg1.Handle,
arg2.Handle
};
JSRuntime runtime = GetRuntime(out napi_env env, out napi_value handle);
return runtime.CallFunction(env, thisArg.Handle, handle, args, out napi_value result)
.ThrowIfFailed(result);
}
public unsafe JSValue Call(JSValue thisArg, params JSValue[] args)
=> Call(thisArg, new ReadOnlySpan<JSValue>(args));
public unsafe JSValue Call(JSValue thisArg, ReadOnlySpan<JSValue> args)
{
int argc = args.Length;
Span<napi_value> argv = stackalloc napi_value[argc];
for (int i = 0; i < argc; ++i)
{
argv[i] = args[i].Handle;
}
JSRuntime runtime = GetRuntime(out napi_env env, out napi_value handle);
return runtime.CallFunction(
env,
thisArg.Handle,
handle,
argv,
out napi_value result)
.ThrowIfFailed(result);
}
public unsafe JSValue Call(napi_value thisArg, ReadOnlySpan<napi_value> args)
{
JSRuntime runtime = GetRuntime(out napi_env env, out napi_value handle);
return runtime.CallFunction(
env,
thisArg,
handle,
args,
out napi_value result)
.ThrowIfFailed(result);
}
public unsafe JSValue CallAsConstructor()
=> GetRuntime(out napi_env env, out napi_value handle)
.NewInstance(env, handle, [], out napi_value result)
.ThrowIfFailed(result);
public unsafe JSValue CallAsConstructor(JSValue arg0)
{
napi_value argValue0 = arg0.Handle;
Span<napi_value> args = stackalloc napi_value[1] { argValue0 };
JSRuntime runtime = GetRuntime(out napi_env env, out napi_value handle);
return runtime.NewInstance(env, handle, args, out napi_value result)
.ThrowIfFailed(result);
}
public unsafe JSValue CallAsConstructor(JSValue arg0, JSValue arg1)
{
Span<napi_value> args = stackalloc napi_value[2] { arg0.Handle, arg1.Handle };
JSRuntime runtime = GetRuntime(out napi_env env, out napi_value handle);
return runtime.NewInstance(env, handle, args, out napi_value result)
.ThrowIfFailed(result);
}
public unsafe JSValue CallAsConstructor(JSValue arg0, JSValue arg1, JSValue arg2)
{
Span<napi_value> args = stackalloc napi_value[3] {
arg0.Handle,
arg1.Handle,
arg2.Handle
};
JSRuntime runtime = GetRuntime(out napi_env env, out napi_value handle);
return runtime.NewInstance(env, handle, args, out napi_value result)
.ThrowIfFailed(result);
}
public unsafe JSValue CallAsConstructor(params JSValue[] args)
=> CallAsConstructor(new ReadOnlySpan<JSValue>(args));
public unsafe JSValue CallAsConstructor(ReadOnlySpan<JSValue> args)
{
int argc = args.Length;
Span<napi_value> argv = stackalloc napi_value[argc];
for (int i = 0; i < argc; ++i)
{
argv[i] = args[i].Handle;
}
JSRuntime runtime = GetRuntime(out napi_env env, out napi_value handle);
return runtime.NewInstance(env, handle, argv, out napi_value result)
.ThrowIfFailed(result);
}
public unsafe JSValue CallAsConstructor(ReadOnlySpan<napi_value> args)
{
JSRuntime runtime = GetRuntime(out napi_env env, out napi_value handle);
return runtime.NewInstance(env, handle, args, out napi_value result)
.ThrowIfFailed(result);
}
public JSValue CallMethod(JSValue methodName)
=> GetProperty(methodName).Call(this);
public JSValue CallMethod(JSValue methodName, JSValue arg0)
=> GetProperty(methodName).Call(this, arg0);
public JSValue CallMethod(
JSValue methodName, JSValue arg0, JSValue arg1)
=> GetProperty(methodName).Call(this, arg0, arg1);
public JSValue CallMethod(JSValue methodName, JSValue arg0, JSValue arg1, JSValue arg2)
=> GetProperty(methodName).Call(this, arg0, arg1, arg2);
public JSValue CallMethod(JSValue methodName, params JSValue[] args)
=> GetProperty(methodName).Call(this, args);
public JSValue CallMethod(JSValue methodName, ReadOnlySpan<JSValue> args)
=> GetProperty(methodName).Call(this, args);
public JSValue CallMethod(JSValue methodName, ReadOnlySpan<napi_value> args)
=> GetProperty(methodName).Call(Handle, args);
public bool InstanceOf(JSValue constructor)
=> GetRuntime(out napi_env env, out napi_value handle)
.InstanceOf(env, handle, constructor.Handle, out bool result)
.ThrowIfFailed(result);
public static unsafe JSValue DefineClass(
string name,
napi_callback callback,
nint data,
ReadOnlySpan<napi_property_descriptor> descriptors)
=> GetCurrentRuntime(out napi_env env)
.DefineClass(env, name, callback, data, descriptors, out napi_value result)
.ThrowIfFailed(result);
public static unsafe JSValue DefineClass(
string name,
JSCallbackDescriptor constructorDescriptor,
params JSPropertyDescriptor[] propertyDescriptors)
{
GCHandle descriptorHandle = JSRuntimeContext.Current.AllocGCHandle(constructorDescriptor);
JSValue? func = null;
napi_callback callback = new(
Current?.ScopeType == JSValueScopeType.NoContext
? s_invokeJSCallbackNC : s_invokeJSCallback);
nint[] handles = ToUnmanagedPropertyDescriptors(
name, propertyDescriptors, (name, descriptorsPtr) =>
{
func = DefineClass(name, callback, (nint)descriptorHandle, descriptorsPtr);
});
func!.Value.AddGCHandleFinalizer((nint)descriptorHandle);
Array.ForEach(handles, handle => func!.Value.AddGCHandleFinalizer(handle));
return func!.Value;
}
/// <summary>
/// Attaches an object to this JSValue.
/// </summary>
/// <param name="value">The object to be wrapped.</param>
/// <returns>Copy of this JSValue struct.</returns>
public unsafe JSValue Wrap(object value)
{
JSRuntime runtime = GetRuntime(out napi_env env, out napi_value handle);
GCHandle valueHandle = _scope!.RuntimeContext.AllocGCHandle(value);
runtime.Wrap(
env,
handle,
(nint)valueHandle,
new napi_finalize(s_finalizeGCHandle),
_scope!.RuntimeContextHandle).ThrowIfFailed();
return this;
}
/// <summary>
/// Attaches an object to this JSValue.
/// </summary>
/// <param name="value">The object to be wrapped.</param>
/// <param name="wrapperWeakRef">Returns a weak reference to the JS wrapper.</param>
/// <returns>The JS wrapper.</returns>
public unsafe JSValue Wrap(object value, out JSReference wrapperWeakRef)
{
JSRuntime runtime = GetRuntime(out napi_env env, out napi_value handle);
GCHandle valueHandle = _scope!.RuntimeContext.AllocGCHandle(value);
runtime.Wrap(
env,
handle,
(nint)valueHandle,
new napi_finalize(s_finalizeGCHandle),
_scope!.RuntimeContextHandle,
out napi_ref weakRef).ThrowIfFailed();
wrapperWeakRef = new JSReference(weakRef, isWeak: true);
return this;
}
/// <summary>
/// Attempts to get the object that was previously attached to this JSValue.
/// </summary>
/// <returns>The unwrapped object, or null if nothing was wrapped.</returns>
public object? TryUnwrap()
{
JSRuntime runtime = GetRuntime(out napi_env env, out napi_value handle);
napi_status status = runtime.Unwrap(env, handle, out nint result);
// The invalid arg error code is returned if there was nothing to unwrap. It doesn't
// distinguish from an invalid handle, but either way the unwrap failed.
if (status == napi_status.napi_invalid_arg)
{
return null;
}
status.ThrowIfFailed();
return GCHandle.FromIntPtr(result).Target;
}
/// <summary>
/// Gets the object that was previously attached to this JSValue.
/// (Throws an exception if unwrapping failed.)
/// </summary>
public object Unwrap(string? unwrapType = null)
{
JSRuntime runtime = GetRuntime(out napi_env env, out napi_value handle);
napi_status status = runtime.Unwrap(env, handle, out nint result);
if (status == napi_status.napi_invalid_arg && unwrapType != null)
{
throw new JSException(new JSError($"Failed to unwrap object of type '{unwrapType}'"));
}
status.ThrowIfFailed();
return GCHandle.FromIntPtr(result).Target!;
}
/// <summary>
/// Detaches an object from this JSValue.
/// </summary>
/// <param name="value">Returns the wrapped object, or null if nothing was wrapped.</param>
/// <returns>True if a wrapped object was found and removed, else false.</returns>
public bool RemoveWrap(out object? value)
{
JSRuntime runtime = GetRuntime(out napi_env env, out napi_value handle);
napi_status status = runtime.RemoveWrap(env, handle, out nint result);
// The invalid arg error code is returned if there was nothing to remove.
if (status == napi_status.napi_invalid_arg)
{
value = null;
return false;
}
status.ThrowIfFailed();
value = GCHandle.FromIntPtr(result).Target;
return true;
}
/// <summary>
/// Gets the object that is represented as an external value.
/// (Throws if the JS value is not an external value.)
/// </summary>
public unsafe object GetValueExternal()
{
JSRuntime runtime = GetRuntime(out napi_env env, out napi_value handle);
runtime.GetValueExternal(env, handle, out nint result).ThrowIfFailed();
return GCHandle.FromIntPtr(result).Target!;
}
/// <summary>
/// Gets the object that is represented as an external value, or null if the JS value
/// is not an external value.
/// </summary>
public unsafe object? TryGetValueExternal()
{
JSRuntime runtime = GetRuntime(out napi_env env, out napi_value handle);
napi_status status = runtime.GetValueExternal(env, handle, out nint result);
// The invalid arg error code is returned if there was no external value.
if (status == napi_status.napi_invalid_arg)
{
return null;
}
status.ThrowIfFailed();
return GCHandle.FromIntPtr(result).Target!;
}
/// <summary>
/// Gets the .NET external value or primitive object value (string, boolean, or double)
/// for a JS value, or null if the JS value is not convertible to one of those types.
/// </summary>
/// <remarks>
/// This is useful when marshalling where a JS value must be converted to some .NET type,
/// but the target type is unknown (object).
/// </remarks>
public object? GetValueExternalOrPrimitive()
{
return TypeOf() switch
{
JSValueType.String => GetValueStringUtf16(),
JSValueType.Boolean => GetValueBool(),
JSValueType.Number => GetValueDouble(),
JSValueType.External => GetValueExternal(),
_ => null,
};
}
public bool IsError() => GetRuntime(out napi_env env, out napi_value handle)
.IsError(env, handle, out bool result).ThrowIfFailed(result);
public bool IsArrayBuffer() => GetRuntime(out napi_env env, out napi_value handle)
.IsArrayBuffer(env, handle, out bool result).ThrowIfFailed(result);
public unsafe Span<byte> GetArrayBufferInfo()
{
JSRuntime runtime = GetRuntime(out napi_env env, out napi_value handle);
runtime.GetArrayBufferInfo(env, handle, out nint data, out nuint length).ThrowIfFailed();
return new Span<byte>((void*)data, (int)length);
}
public bool IsTypedArray() => GetRuntime(out napi_env env, out napi_value handle)
.IsTypedArray(env, handle, out bool result).ThrowIfFailed(result);
public unsafe int GetTypedArrayLength(out JSTypedArrayType type)
{
JSRuntime runtime = GetRuntime(out napi_env env, out napi_value handle);
runtime.GetTypedArrayInfo(
env,
handle,
out napi_typedarray_type arrayType,
out nuint length,
out nint _,
out napi_value _,
out nuint _).ThrowIfFailed();
type = (JSTypedArrayType)(int)arrayType;
return (int)length;
}
public unsafe Span<T> GetTypedArrayData<T>() where T : struct
{
JSRuntime runtime = GetRuntime(out napi_env env, out napi_value handle);