-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathnapisys.go
2628 lines (2420 loc) · 117 KB
/
napisys.go
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 napisys
/*
#cgo CXXFLAGS: -std=c++11
#cgo CXXFLAGS: -I./include/
#cgo CFLAGS: -I./include/ -DNAPI_EXPERIMENTAL=1
#cgo LDFLAGS: -L./lib/ -lnode_api
#include <stdlib.h>
#include "gonapi.h"
#include <node_api.h>
*/
import "C"
import (
"bytes"
"unsafe"
)
// ccstring function transforms a Go string into a C string (array of characters)
// and returns the pointer to the first element.
func cstring(s string) unsafe.Pointer {
p := make([]byte, len(s)+1)
copy(p, s)
return unsafe.Pointer(&p[0])
}
// Aliases for JavaScript types
// Basic N-API Data Types
// N-API exposes the following fundamental datatypes as abstractions that are
// consumed by the various APIs. These APIs should be treated as opaque,
// introspectable only with other N-API calls.
// Env is used to represent a context that the underlying N-API
// implementation can use to persist VM-specific state. This structure is passed
// to native functions when they're invoked, and it must be passed back when
// making N-API calls. Specifically, the same napi_env that was passed in when
// the initial native function was called must be passed to any subsequent nested
// N-API calls. Caching the napi_env for the purpose of general reuse is not
// allowed.
type Env = C.napi_env
// Value is an opaque pointer that is used to represent a JavaScript value.
type Value = C.napi_value
// Ref is an abstraction to use to reference a NapiValue. This allows for
// users to manage the lifetimes of JavaScript values, including defining their
// minimum lifetimes explicitly.
type Ref = C.napi_ref
// HandleScope is an abstraction used to control and modify the lifetime of
// objects created within a particular scope. In general, N-API values are
// created within the context of a handle scope. When a native method is called
// from JavaScript, a default handle scope will exist. If the user does not
// explicitly create a new handle scope, N-API values will be created in the
// default handle scope. For any invocations of code outside the execution of a
// native method (for instance, during a libuv callback invocation), the module
// is required to create a scope before invoking any functions that can result
// in the creation of JavaScript values.
// Handle scopes are created using NapiOnpenHandleScope and are destroyed using
// NapiCloseHandleScope. Closing the scope can indicate to the GC that all
// NapiValues created during the lifetime of the handle scope are no longer
// referenced from the current stack frame.
type HandleScope = C.napi_handle_scope
// EscapableHandleScope represents a special type of handle scope to return
// values created within a particular handle scope to a parent scope.
type EscapableHandleScope = C.napi_escapable_handle_scope
// CallbackInfo is an opaque datatype that is passed to a callback function.
// It can be used for getting additional information about the context in which
// the callback was invoked.
type CallbackInfo = C.napi_callback_info
// Deferred known sa "deferred" object is created and returned alongside a
// Promise. The deferred object is bound to the created Promise and is the only
// means to resolve or reject the Promise. The deferred object will be
// automatically freed on rejection or on resolving the Promise.
type Deferred = C.napi_deferred
// This is a struct used as container for types of property atrributes.
// NapiPropertyAttributes represents the flags used to control the behavior of
// properties set on a JavaScript object.
// Other than napi_static they correspond to the attributes listed in
// Section 6.1.7.1 of the ECMAScript Language Specification.
// Currently they can be one or more of the following bitflags:
// napi_default - Used to indicate that no explicit attributes are set on the
// given property. By default, a property is read only, not enumerable and not
// configurable.
// napi_writable - Used to indicate that a given property is writable.
// napi_enumerable - Used to indicate that a given property is enumerable.
// napi_configurable - Used to indicate that a given property is configurable,
// as defined in Section 6.1.7.1 of the ECMAScript Language Specification.
// napi_static - Used to indicate that the property will be defined as a static
// property on a class as opposed to an instance property, which is the default.
// This is used only by NapiDefineClass. It is ignored by NapiDefineProperties.
// type PropertyAttributes = C.napi_property_attributes
type propertyAttributes struct {
Default int
Writable int
Enumerable int
Configurable int
// Used with napi_define_class to distinguish static properties
// from instance properties. Ignored by napi_define_properties.
Static int
}
// PropertyAttributes contains the flags to control the behavior of properties
// set on a JavaScript object. They can be one or more of the following bitflags:
// - NapiDefault - Used to indicate that no explicit attributes are set on the
// given property. By default, a property is read only, not enumerable and not
// configurable.
// - NapiWritable - Used to indicate that a given property is writable.
// - NapiEnumerable - Used to indicate that a given property is enumerable.
// - NapiConfigurable - Used to indicate that a given property is configurable,
// as defined in Section 6.1.7.1 of the ECMAScript Language Specification.
// - NapiStatic - Used to indicate that the property will be defined as a static
// property on a class as opposed to an instance property, which is the default.
// This is used only by NapiDefineClass. It is ignored by NapiDfineProperties.
var PropertyAttributes = &propertyAttributes{
Default: C.napi_default,
Writable: C.napi_writable,
Enumerable: C.napi_enumerable,
Configurable: C.napi_configurable,
Static: C.napi_static,
}
// ValueType describes the type of NapiValue. This generally corresponds to
// the types described in Section 6.1 of the ECMAScript Language Specification.
// In addition to types in that section, NapiValueType can also represent
// Functions and Objects with external data.
// A JavaScript value of type napi_external appears in JavaScript as a plain
// object such that no properties can be set on it, and no prototype.
// Currently the following types are supported:
// napi_undefined,
// napi_null,
// napi_boolean,
// napi_number,
// napi_string,
// napi_symbol,
// napi_object,
// napi_function,
// napi_external,
// napi_bigint,
type ValueType = C.napi_valuetype
type valueTypes struct {
// ES6 types (corresponds to typeof)
Undefined int
Null int
Boolean int
Number int
String int
Symbol int
Object int
Function int
External int
Bigint int
}
// ValueTypes contains the type of a NapiValue. This generally corresponds to the
// types described in Section 6.1 of the ECMAScript Language Specification. In
// addition to types in that section, ValueType can also represent Functions and
// Objects with external data. A JavaScript value of type NapiExternal appears in
// JavaScript as a plain object such that no properties can be set on it, and no
//prototype.
var ValueTypes = &valueTypes{
Undefined: C.napi_undefined,
Null: C.napi_null,
Boolean: C.napi_boolean,
Number: C.napi_number,
String: C.napi_string,
Symbol: C.napi_symbol,
Object: C.napi_object,
Function: C.napi_function,
External: C.napi_external,
Bigint: C.napi_bigint,
}
// This is a struct used as container for types used in TypedArray.
type typedArrayTypes struct {
Int8Array int
UInt8Array int
UInt8ClampedArray int
Int16Array int
UInt16Array int
Int32Array int
UInt32Array int
Float32Array int
Float64Array int
BigInt64Array int
BigUInt64Array int
}
// TypedArrayTypes contains the underlying binary scalar datatype of the
// TypedArray defined in sectiontion 22.2 of the ECMAScript Language
// Specification.
var TypedArrayTypes = &typedArrayTypes{
Int8Array: C.napi_int8_array,
UInt8Array: C.napi_uint8_array,
UInt8ClampedArray: C.napi_uint8_clamped_array,
Int16Array: C.napi_int16_array,
UInt16Array: C.napi_uint16_array,
Int32Array: C.napi_int32_array,
UInt32Array: C.napi_uint32_array,
Float32Array: C.napi_float32_array,
Float64Array: C.napi_float64_array,
BigInt64Array: C.napi_bigint64_array,
BigUInt64Array: C.napi_biguint64_array,
}
// TypedArrayType represents the underlying binary scalar datatype of the
// TypedArray defined in sectiontion 22.2 of the ECMAScript Language
// Specification.
type TypedArrayType C.napi_typedarray_type
// This is a struct used as container for N-API status.
type statuses struct {
OK int
InvalidArg int
ObjectExpected int
StringExpected int
NameExpected int
FunctionExpected int
NumberExpected int
BooleanExpected int
ArrayExpected int
GenericFailure int
PendingException int
Cancelled int
EscapeCalledTwice int
HandleScopeMismatch int
CallbackScopeMismatch int
QueueFull int
Closing int
BigintExpected int
DateExpected int
}
// Statuses contains the status code indicating the success or failure of
// a N-API call. Currently, the following status codes are supported:
// napi_ok
// napi_invalid_arg
// napi_object_expected
// napi_string_expected
// napi_name_expected
// napi_function_expected
// napi_number_expected
// napi_boolean_expected
// napi_array_expected
// napi_generic_failure
// napi_pending_exception
// napi_cancelled
// napi_escape_called_twice
// napi_handle_scope_mismatch
// napi_callback_scope_mismatch
// napi_queue_full
// napi_closing
// napi_bigint_expected
// napi_date_expected
// If additional information is required upon an API returning a failed status,
// it can be obtained by calling NapiGetLastErrorInfo.
var Statuses = &statuses{
OK: C.napi_ok,
InvalidArg: C.napi_invalid_arg,
ObjectExpected: C.napi_object_expected,
StringExpected: C.napi_string_expected,
NameExpected: C.napi_name_expected,
FunctionExpected: C.napi_function_expected,
NumberExpected: C.napi_number_expected,
BooleanExpected: C.napi_boolean_expected,
ArrayExpected: C.napi_array_expected,
GenericFailure: C.napi_generic_failure,
PendingException: C.napi_pending_exception,
Cancelled: C.napi_cancelled,
EscapeCalledTwice: C.napi_escape_called_twice,
HandleScopeMismatch: C.napi_handle_scope_mismatch,
CallbackScopeMismatch: C.napi_callback_scope_mismatch,
QueueFull: C.napi_queue_full,
Closing: C.napi_closing,
BigintExpected: C.napi_bigint_expected,
DateExpected: C.napi_date_expected,
}
// Status represent the status code indicating the success or failure of
// a N-API call. Currently, the following status codes are supported:
// napi_ok
// napi_invalid_arg
// napi_object_expected
// napi_string_expected
// napi_name_expected
// napi_function_expected
// napi_number_expected
// napi_boolean_expected
// napi_array_expected
// napi_generic_failure
// napi_pending_exception
// napi_cancelled
// napi_escape_called_twice
// napi_handle_scope_mismatch
// napi_callback_scope_mismatch
// napi_queue_full
// napi_closing
// napi_bigint_expected
// If additional information is required upon an API returning a failed status,
// it can be obtained by calling NapiGetLastErrorInfo.
type Status = C.napi_status
// Callback represents a function pointer type for user-provided native
// functions which are to be exposed to JavaScript via N-API. Callback functions
// should satisfy the following signature:
// typedef napi_value (*napi_callback)(napi_env, napi_callback_info);
type Callback = C.napi_callback
// Finalize represents a function pointer type for add-on provided functions
// that allow the user to be notified when externally-owned data is ready to be
// cleaned up because the object with which it was associated with, has been
// garbage-collected. The user must provide a function satisfying the following
// signature which would get called upon the object's collection. Currently,
// `napi_finalize` can be used for finding out when objects that have external
// data are collected. Finalize functions hould satisfy the following signature:
// typedef void (*napi_finalize)(napi_env env,
// void* finalize_data,
// void* finalize_hint);
type Finalize = C.napi_finalize
// PropertyDescriptor is a data structure that used to define the properties
// of a JavaScript object.
type PropertyDescriptor = C.napi_property_descriptor
// ExtendedErrorInfo contains additional information about a failed status
// happened on an N-API call.
// The NapiStatus return value provides a VM-independent representation of the
// error which occurred. In some cases it is useful to be able to get more
// detailed information, including a string representing the error as well as
// VM (engine)-specific information.
// error_message: UTF8-encoded string containing a VM-neutral description of the
// error.
// engine_reserved: Reserved for VM-specific error details. This is currently
// not implemented for any VM.
// engine_error_code: VM-specific error code. This is currently not implemented
// for any VM.
// error_code: The N-API status code that originated with the last error.
// Do not rely on the content or format of any of the extended information as it
// is not subject to SemVer and may change at any time. It is intended only for
// logging purposes.
type ExtendedErrorInfo = *C.napi_extended_error_info
// Aliases for types strickly connected with the runtime
// CallbackScope represents
type CallbackScope = C.napi_callback_scope
// AsyncContext represents the context for the async operation that is
// invoking a callback. This should normally be a value previously obtained from
// `napi_async_init`. However `NULL` is also allowed, which indicates the current
// async context (if any) is to be used for the callback.
type AsyncContext = C.napi_async_context
// AsyncWork represents the handle for the newly created asynchronous work
// and it is used to execute logic asynchronously.
type AsyncWork = C.napi_async_work
// ThreadsafeFunction is an opaque pointer that represents a JavaScript
// function which can be called asynchronously from multiple threads.
type ThreadsafeFunction = C.napi_threadsafe_function
// This is a struct used as container for modes to release a
// NapiThreadSafeFunction.
type tsfnReleaseMode struct {
NapiTsfnRelease int
NapiTsfnAbort int
}
// TsfnReleaseMode contains values to be given to NapiReleaseThreadsafeFunction()
// to indicate whether the thread-safe function is to be closed immediately
// (NapiTsfnAbort) or merely released (NapiTsfnRelease) and thus available for
// subsequent use via NapiAcquireThreadsafeFunction() and
// NapiCallThreadsafeFunction().
var TsfnReleaseMode = &tsfnReleaseMode{
NapiTsfnRelease: C.napi_tsfn_release,
NapiTsfnAbort: C.napi_tsfn_abort,
}
// TheradsafeFunctionReleaseMode represents a value to be given to
// NapiReleaseThreadsafeFunction() to indicate whether the thread-safe function
// is to be closed immediately (NapiTsfnAbort) or merely released
// (NapiTsfnRelease) and thus available for subsequent use via
// NapiAcquireThreadsafeFunction() and NapiCallThreadsafeFunction().
type TheradsafeFunctionReleaseMode = C.napi_threadsafe_function_release_mode
// This is a struct used as container for types used to call a
// NapiThreadSafeFunction.
type tsfnCallMode struct {
NapiTsfnNonBlocking int
NapiTsfnBlocking int
}
// TsfnCallMode contains values to be given to NapiCallThreadsafeFunction() to
// indicate whether the call should block whenever the queue associated with the
// thread-safe function is full.
var TsfnCallMode = &tsfnCallMode{
NapiTsfnNonBlocking: C.napi_tsfn_nonblocking,
NapiTsfnBlocking: C.napi_tsfn_blocking,
}
// ThreadsafeFunctionCallMode contains values used to indicate whether the
// call should block whenever the queue associated with the thread-safe function
// is full.
type ThreadsafeFunctionCallMode = C.napi_threadsafe_function_call_mode
// AsyncExecuteCallback is a function pointer used with functions that
// support asynchronous operations. Callback functions must statisfy the
// following signature:
// typedef void (*napi_async_execute_callback)(napi_env env, void* data);
// Implementations of this type of function should avoid making any N-API calls
// that could result in the execution of JavaScript or interaction with
// JavaScript objects.
type AsyncExecuteCallback = C.napi_async_execute_callback
// AsyncCompleteCallback is a function pointer used with functions that
// support asynchronous operations. Callback functions must statisfy the
// following signature:
// typedef void (*napi_async_complete_callback)(napi_env env,
// napi_status status,
// void* data);
type AsyncCompleteCallback = C.napi_async_complete_callback
// ThreadsafeFunctionCallJS is a function pointer used with asynchronous
// thread-safe function calls. The callback will be called on the main thread.
// Its purpose is to use a data item arriving via the queue from one of the
// secondary threads to construct the parameters necessary for a call into
// JavaScript.
// Callback functions must satisfy the following signature:
// typedef void (*napi_threadsafe_function_call_js)(napi_env env,
// napi_value js_callback,
// void* context,
// void* data);
type ThreadsafeFunctionCallJS = C.napi_threadsafe_function_call_js
// NodeVersion is a structure that contains informations about the version
// of Node.js instance.
// Currently, the following fields are exposed:
// major
// minor
// patch
// release
type NodeVersion = *C.napi_node_version
// UVLoop represents the current libuv event loop for a given environment
type UVLoop = *C.struct_uv_loop_s
// Error Handling
// N-API uses both return values and JavaScript exceptions for error handling.
// The following sections explain the approach for each case.
// All of the N-API functions share the same error handling pattern. The return
// type of all API functions is napi_status.
// The return value will be napi_ok if the request was successful and no uncaught
// JavaScript exception was thrown. If an error occurred AND an exception was
// thrown, the napi_status value for the error will be returned. If an exception
// was thrown, and no error occurred, napi_pending_exception will be returned.
// In cases where a return value other than napi_ok or napi_pending_exception is
// returned, napi_is_exception_pending must be called to check if an exception is
// pending. See the section on exceptions for more details.
// The napi_status return value provides a VM-independent representation of the
// error which occurred. In some cases it is useful to be able to get more
// detailed information, including a string representing the error as well as
// VM (engine)-specific information.
// Any N-API function call may result in a pending JavaScript exception. This is
// obviously the case for any function that may cause the execution of
// JavaScript, but N-API specifies that an exception may be pending on return
// from any of the API functions. If the napi_status returned by a function is
// napi_ok then no exception is pending and no additional action is required. If
// the napi_status returned is anything other than napi_ok or
// napi_pending_exception, in order to try to recover and continue instead of
// simply returning immediately, napi_is_exception_pending must be called in
// order to determine if an exception is pending or not. In many cases when an
// N-API function is called and an exception is already pending, the function
// will return immediately with a napi_status of napi_pending_exception.
// However, this is not the case for all functions. N-API allows a subset of the
// functions to be called to allow for some minimal cleanup before returning to
// JavaScript. In that case, napi_status will reflect the status for the
// function. It will not reflect previous pending exceptions. To avoid confusion,
// check the error status after every function call.
// When an exception is pending one of two approaches can be employed.:
// The first approach is to do any appropriate cleanup and then return so that
// execution will return to JavaScript. As part of the transition back to
// JavaScript the exception will be thrown at the point in the JavaScript code
// where the native method was invoked. The behavior of most N-API calls is
// unspecified while an exception is pending, and many will simply return
// napi_pending_exception, so it is important to do as little as possible and
// then return to JavaScript where the exception can be handled.
// The second approach is to try to handle the exception. There will be cases
// where the native code can catch the exception, take the appropriate action,
// and then continue. This is only recommended in specific cases where it is
// known that the exception can be safely handled.
// The Node.js project is adding error codes to all of the errors generated
// internally. The goal is for applications to use these error codes for all
// error checking. The associated error messages will remain, but will only be
// meant to be used for logging and display with the expectation that the message
// can change without SemVer applying. In order to support this model with N-API,
// both in internal functionality and for module specific functionality
// (as its good practice), the throw_ and create_ functions take an optional code
// parameter which is the string for the code to be added to the error object. If
// the optional parameter is NULL then no code will be associated with the error.
// GetLastErrorInfo function returns the information for the last N-API call
// that was made.
// [in] env: The environment that the API is invoked under.
// This API retrieves a napi_extended_error_info structure with information about
// the last error that occurred.
// The content of the napi_extended_error_info returned is only valid up until an
// n-api function is called on the same env.
// Do not rely on the content or format of any of the extended information as it
// is not subject to SemVer and may change at any time. It is intended only for
// logging purposes.
// The function can be called even if there is a pending JavaScript exception.
func GetLastErrorInfo(env Env) (ExtendedErrorInfo, Status) {
var res *C.napi_extended_error_info
var status = C.napi_get_last_error_info(env, &res)
return ExtendedErrorInfo(res), Status(status)
}
// Throw function throws the JavaScript value provided.
// [in] env: The environment that the API is invoked under.
// [in] error: The JavaScript value to be thrown.
// N-API version: 1
func Throw(env Env, error Value) Status {
return Status(C.napi_throw(env, error))
}
// ThrowError function throws a JavaScript Error with the text provided.
// [in] env: The environment that the API is invoked under.
// [in] code: Optional error code to be set on the error.
// [in] msg: C string representing the text to be associated with the error.
// N-API version: 1
func ThrowError(env Env, msg string, code string) Status {
cmsg := C.CString(msg)
defer C.free(unsafe.Pointer(cmsg))
var ccode = C.CString(code)
defer C.free(unsafe.Pointer(ccode))
return Status(C.napi_throw_error(env, ccode, cmsg))
}
// ThrowTypeError function throws a JavaScript TypeError with the text
// provided.
// [in] env: The environment that the API is invoked under.
// [in] code: Optional error code to be set on the error.
// [in] msg: C string representing the text to be associated with the error.
// N-API version: 1
func ThrowTypeError(env Env, msg string, code string) Status {
cmsg := C.CString(msg)
defer C.free(unsafe.Pointer(cmsg))
var ccode = C.CString(code)
defer C.free(unsafe.Pointer(ccode))
return Status(C.napi_throw_type_error(env, ccode, cmsg))
}
// ThrowRangError function throws a JavaScript RangeError with the text
// provided.
// [in] env: The environment that the API is invoked under.
// [in] code: Optional error code to be set on the error.
// [in] msg: C string representing the text to be associated with the error.
// N-API version: 1
func ThrowRangError(env Env, msg string, code string) Status {
cmsg := C.CString(msg)
defer C.free(unsafe.Pointer(cmsg))
var ccode = C.CString(code)
defer C.free(unsafe.Pointer(ccode))
return Status(C.napi_throw_range_error(env, ccode, cmsg))
}
// IsError function queries a napi_value to check if it represents an error
// object.
// [in] env: The environment that the API is invoked under.
// [in] value: The napi_value to be checked.
// Boolean value that is set to true if napi_value represents an error, false
// otherwise.
// N-API version: 1
func IsError(env Env, value Value) (bool, Status) {
var res C.bool
var status = C.napi_is_error(env, value, &res)
return bool(res), Status(status)
}
// CreateError function creates a JavaScript Error with the text provided.
// [in] env: The environment that the API is invoked under.
// [in] code: Optional napi_value with the string for the error code to be
// associated with the error.
// [in] msg: napi_value that references a JavaScript String to be used as the
// message for the Error.
// N-API version: 1
func CreateError(env Env, msg Value, code Value) (Value, Status) {
var res C.napi_value
var status = C.napi_create_error(env, code, msg, &res)
return Value(res), Status(status)
}
// CreateTypeError function creates a JavaScript TypeError with the text
// provided.
// [in] env: The environment that the API is invoked under.
// [in] code: Optional napi_value with the string for the error code to be
// associated with the error.
// [in] msg: napi_value that references a JavaScript String to be used as the
// message for the Error.
// N-API version: 1
func CreateTypeError(env Env, code Value, msg Value) (Value, Status) {
var res C.napi_value
var status = C.napi_create_type_error(env, code, msg, &res)
return Value(res), Status(status)
}
// CreateRangeError function creates a JavaScript RangeError with the text
// provided.
// [in] env: The environment that the API is invoked under.
// [in] code: Optional napi_value with the string for the error code to be
// associated with the error.
// [in] msg: napi_value that references a JavaScript String to be used as the
// message for the Error.
// N-API version: 1
func CreateRangeError(env Env, code Value, msg Value) (Value, Status) {
var res C.napi_value
var status = C.napi_create_range_error(env, code, msg, &res)
return Value(res), Status(status)
}
// GetAndClearLastException function returns true if an exception is pending.
// This function can be called even if there is a pending JavaScript exception.
// [in] env: The environment that the API is invoked under.
// The function returns the exception if one is pending, NULL otherwise.
// N-API version: 1
func GetAndClearLastException(env Env) (Value, Status) {
var res C.napi_value
var status = C.napi_get_and_clear_last_exception(env, &res)
return Value(res), Status(status)
}
// IsExceptionPending function ...
// [in] env: The environment that the API is invoked under.
// Boolean value that is set to true if an exception is pending.
// N-API version: 1
func IsExceptionPending(env Env) (bool, Status) {
var res C.bool
var status = C.napi_is_exception_pending(env, &res)
return bool(res), Status(status)
}
// FatalException function triggers an 'uncaughtException' in JavaScript.
// Useful if an async callback throws an exception with no way to recover.
// [in] env: The environment that the API is invoked under.
// [in] err: The error that is passed to 'uncaughtException'.
// N-API version: 3
func FatalException(env Env, error Value) Status {
return Status(C.napi_fatal_exception(env, error))
}
// FatalError function thrown a fatal error o immediately terminate the
// process.
// [in] location: Optional location at which the error occurred.
// [in] location_len: The length of the location in bytes, or NAPI_AUTO_LENGTH
// if it is null-terminated.
// [in] message: The message associated with the error.
// [in] message_len: The length of the message in bytes, or NAPI_AUTO_LENGTH if
// it is null-terminated.
// This function can be called even if there is a pending JavaScript exception.
// The function call does not return, the process will be terminated.
// N-API version: 1
func FatalError(location string, msg string) {
clocation := C.CString(location)
defer C.free(unsafe.Pointer(clocation))
cmsg := C.CString(msg)
defer C.free(unsafe.Pointer(cmsg))
C.napi_fatal_error(clocation, C.NAPI_AUTO_LENGTH, cmsg, C.NAPI_AUTO_LENGTH)
return
}
// Object Lifetime management
// As N-API calls are made, handles to objects in the heap for the underlying VM
// may be returned as napi_values. These handles must hold the objects 'live'
// until they are no longer required by the native code, otherwise the objects
// could be collected before the native code was finished using them. As object
// handles are returned they are associated with a 'scope'. The lifespan for the
// default scope is tied to the lifespan of the native method call. The result is
// that, by default, handles remain valid and the objects associated with these
// handles will be held live for the lifespan of the native method call. In many
// cases, however, it is necessary that the handles remain valid for either a
// shorter or longer lifespan than that of the native method.
// N-API only supports a single nested hierarchy of scopes. There is only one
// active scope at any time, and all new handles will be associated with that
// scope while it is active. Scopes must be closed in the reverse order from
// which they are opened. In addition, all scopes created within a native method
// must be closed before returning from that method.
// When nesting scopes, there are cases where a handle from an inner scope needs
// to live beyond the lifespan of that scope. N-API supports an 'escapable scope'
// in order to support this case. An escapable scope allows one handle to be
// 'promoted' so that it 'escapes' the current scope and the lifespan of the
// handle changes from the current scope to that of the outer scope.
// OnpenHandleScope function opens a new scope.
// [in] env: The environment that the API is invoked under.
// N-API version: 1
func OnpenHandleScope(env Env) (HandleScope, Status) {
var res C.napi_handle_scope
var status = C.napi_open_handle_scope(env, &res)
return HandleScope(res), Status(status)
}
// CloseHandleScope function closes the scope passed in. Scopes must be
// closed in the reverse order from which they were created.
// [in] env: The environment that the API is invoked under.
// [in] scope: napi_value representing the scope to be closed.
// This function can be called even if there is a pending JavaScript exception.
// N-API version: 1
func CloseHandleScope(env Env, scope HandleScope) Status {
return Status(C.napi_close_handle_scope(env, scope))
}
// OnpenEscapableHandleScope function opens a new scope from which one object
// can be promoted to the outer scope.
// [in] env: The environment that the API is invoked under.
// N-API version: 1
func OnpenEscapableHandleScope(env Env) (EscapableHandleScope, Status) {
var res C.napi_escapable_handle_scope
var status = C.napi_open_escapable_handle_scope(env, &res)
return EscapableHandleScope(res), Status(status)
}
// CloseEscapableHandleScope function closes the scope passed in. Scopes must
// be closed in the reverse order from which they were created.
// [in] env: The environment that the API is invoked under.
// [in] scope: napi_value representing the scope to be closed.
// This function can be called even if there is a pending JavaScript exception.
// N-API version: 1
func CloseEscapableHandleScope(env Env, scope EscapableHandleScope) Status {
return Status(C.napi_close_escapable_handle_scope(env, scope))
}
// EscapeHandle function promotes the handle to the JavaScript object so that
// it is valid for the lifetime of the outer scope. It can only be called once
// per scope. If it is called more than once an error will be returned.
// [in] env: The environment that the API is invoked under.
// [in] scope: napi_value representing the current scope.
// [in] escapee: napi_value representing the JavaScript Object to be escaped.
// This function can be called even if there is a pending JavaScript exception.
// N-API version: 1
func EscapeHandle(env Env, scope EscapableHandleScope, escapee Value) (Value, Status) {
var res C.napi_value
var status = C.napi_escape_handle(env, scope, escapee, &res)
return Value(res), Status(status)
}
// References to objects with a lifespan longer than that of the native method
// In some cases an addon will need to be able to create and reference objects
// with a lifespan longer than that of a single native method invocation.
// For example, to create a constructor and later use that constructor in a
// request to creates instances, it must be possible to reference the constructor
// object across many different instance creation requests. This would not be
// possible with a normal handle returned as a NapiValue as described in the
// earlier section. The lifespan of a normal handle is managed by scopes and all
// scopes must be closed before the end of a native method.
// N-API provides methods to create persistent references to an object. Each
// persistent reference has an associated count with a value of 0 or higher. The
// count determines if the reference will keep the corresponding object live.
// References with a count of 0 do not prevent the object from being collected
// and are often called 'weak' references. Any count greater than 0 will prevent
// the object from being collected.
// References must be deleted once they are no longer required by the addon.
// When a reference is deleted it will no longer prevent the corresponding object
// from being collected. Failure to delete a persistent reference will result in
// a 'memory leak' with both the native memory for the persistent reference and
// the corresponding object on the heap being retained forever.
// There can be multiple persistent references created which refer to the same
// object, each of which will either keep the object live or not based on its
// individual count.
// CreateReference function creates a new reference with the specified
// reference count to the Object passed in.
// [in] env: The environment that the API is invoked under.
// [in] value: napi_value representing the Object to which we want a reference.
// [in] initial_refcount: Initial reference count for the new reference.
// N-API version: 1
func CreateReference(env Env, value Value, refCount uint) (Ref, Status) {
var res C.napi_ref
var status = C.napi_create_reference(env, value, C.uint(refCount), &res)
return Ref(res), Status(status)
}
// DeleteReference function deletes the reference passed in.
// [in] env: The environment that the API is invoked under.
// [in] ref: napi_ref to be deleted.
// This API can be called even if there is a pending JavaScript exception.
// N-API version: 1
func DeleteReference(env Env, ref Ref) Status {
var status = C.napi_delete_reference(env, ref)
return Status(status)
}
// ReferenceRef function increments the reference count for the reference
// passed in and returns the resulting reference count.
// [in] env: The environment that the API is invoked under.
// [in] ref: napi_ref for which the reference count will be incremented.
// N-API version: 1
func ReferenceRef(env Env, ref Ref) (uint, Status) {
var res C.uint
var status = C.napi_reference_ref(env, ref, &res)
return uint(res), Status(status)
}
// ReferenceUnref function ecrements the reference count for the reference
// passed in and returns the resulting reference count.
// [in] env: The environment that the API is invoked under.
// [in] ref: napi_ref for which the reference count will be decremented.
// N-API version: 1
func ReferenceUnref(env Env, ref Ref) (uint, Status) {
var res C.uint
var status = C.napi_reference_unref(env, ref, &res)
return uint(res), Status(status)
}
// GetReferenceValue function returns the NapiValue representing the
// JavaScript Object associated with the NapiRef. Otherwise, result will be
// NULL.
// [in] env: The environment that the API is invoked under.
// [in] ref: napi_ref for which we requesting the corresponding Object.
// N-API version: 1
func GetReferenceValue(env Env, ref Ref) (Value, Status) {
var res C.napi_value
var status = C.napi_get_reference_value(env, ref, &res)
return Value(res), Status(status)
}
// AddEnvCleanupHook function ...
func AddEnvCleanupHook(env Env) (Value, Status) {
var res C.napi_value
var status = C.napi_ok
return Value(res), Status(status)
}
// RemoveCleaupHook function ...
func RemoveCleaupHook(env Env) (Value, Status) {
var res C.napi_value
var status = C.napi_ok
return Value(res), Status(status)
}
// CreateArray function returns an N-API value corresponding to a JavaScript
// Array type. JavaScript arrays are described in Section 22.1 of the ECMAScript
// Language Specification.
// [in] env: The environment that the N-API call is invoked under.
// N-API version: 1
func CreateArray(env Env) (Value, Status) {
var res C.napi_value
var status = C.napi_create_array(env, &res)
return Value(res), Status(status)
}
// CreateArrayWithLength function returns an N-API value corresponding to a
// JavaScript Array type. The Array's length property is set to the passed-in
// length parameter. However, the underlying buffer is not guaranteed to be
// pre-allocated by the VM when the array is created - that behavior is left to
// the underlying VM implementation.
// avaScript arrays are described in Section 22.1 of the ECMAScript Language
// Specification.
// [in] env: The environment that the API is invoked under.
// [in] length: The initial length of the Array.
// N-API version: 1
func CreateArrayWithLength(env Env, length uint) (Value, Status) {
var res C.napi_value
var status = C.napi_create_array_with_length(env, C.size_t(length), &res)
return Value(res), Status(status)
}
// CreateArrayBuffer function returns N-API value corresponding to a
// JavaScript `ArrayBuffer`. ArrayBuffer is a data stucture used to represent
// fixed-length binary data buffers. They are normally used as backing-buffer for
// `TypedArray` objects. The ArrayBuffer allocated will have an underlying byte
// buffer whose size is determined by the length parameter that's passed in. The
// underlying buffer is optionally returned back to the caller in case the caller
// wants to directly manipulate the buffer.
// This buffer can only be written to directly from native code.
// To write to this buffer from JavaScript, a typed array or DataView object
// would need to be created.
// JavaScript ArrayBuffer objects are described in Section 24.1 of the ECMAScript
// Language Specification.
// [in] env: The environment that the API is invoked under.
// [in] length: The length in bytes of the array buffer to create.
// [out] data: Pointer to the underlying byte buffer of the ArrayBuffer.
// [out] result: A napi_value representing a JavaScript ArrayBuffer.
// N-API version: 1
func CreateArrayBuffer(env Env, length uint) (Value, unsafe.Pointer, Status) {
var res C.napi_value
var data unsafe.Pointer
var status = C.napi_create_arraybuffer(env, C.size_t(length), &data, &res)
return Value(res), data, Status(status)
}
// CreateBuffer function returns N-API value that allocates a node::Buffer
// object. While this is still a fully-supported data structure, in most cases
// musing a TypedArray will suffice.
// [in] env: The environment that the API is invoked under.
// [in] size: Size in bytes of the underlying buffer.
// [out] data: Raw pointer to the underlying buffer.
// [out] result: A napi_value representing a node::Buffer.
// N-API version: 1
func CreateBuffer(env Env, length uint) (Value, unsafe.Pointer, Status) {
var res C.napi_value
var data unsafe.Pointer
var status = C.napi_create_buffer(env, C.size_t(length), &data, &res)
return Value(res), data, Status(status)
}
// CreateBufferCopy function allocates a node::Buffer object and initializes
// it with data copied from the passed-in buffer. While this is still a
// fully-supported data structure, in most cases using a TypedArray will suffice.
// [in] env: The environment that the API is invoked under.
// [in] length: Size in bytes of the input buffer (should be the same as the size
// of the new buffer).
// [in] data: Raw pointer to the underlying buffer to copy from.
// [out] result_data: Pointer to the new Buffer's underlying data buffer.
// [out] result: A napi_value representing a node::Buffer.
// N-API version: 1
func CreateBufferCopy(env Env, length uint, raw unsafe.Pointer) (Value, unsafe.Pointer, Status) {
var res C.napi_value
var data unsafe.Pointer
var status = C.napi_create_buffer_copy(env, C.size_t(length), raw, &data, &res)
return Value(res), data, Status(status)
}
// CreateExternal function allocates a JavaScript value with external data
// attached to it. This is used to pass external data through JavaScript code, so
// it can be retrieved later by native code. The API allows the caller to pass in
// a finalize callback, in case the underlying native resource needs to be
// cleaned up when the external JavaScript value gets collected.
// [in] env: The environment that the API is invoked under.
// [in] data: Raw pointer to the external data.
// [in] finalize_cb: Optional callback to call when the external value is being
// collected.
// [in] finalize_hint: Optional hint to pass to the finalize callback during
// collection.
// [out] result: A napi_value representing an external value.
// The created value is not an object, and therefore does not support additional
// properties. It is considered a distinct value type `napi_external`.
// N-API version: 1
func CreateExternal(env Env, raw unsafe.Pointer) (Value, Status) {
var res C.napi_value
// Remember to handle napi_finalize finalize_cb and void* finalize_hint
var status = C.napi_create_external(env, raw, nil, nil, &res)
return Value(res), Status(status)
}
// CreateExternalArrayBuffer function returns an N-API value corresponding to
// a JavaScript ArrayBuffer. The underlying byte buffer of the ArrayBuffer is
// externally allocated and managed. The caller must ensure that the byte buffer
// remains valid until the finalize callback is called.
// [in] env: The environment that the API is invoked under.
// [in] external_data: Pointer to the underlying byte buffer of the ArrayBuffer.
// [in] byte_length: The length in bytes of the underlying buffer.
// [in] finalize_cb: Optional callback to call when the ArrayBuffer is being
// collected.
// [in] finalize_hint: Optional hint to pass to the finalize callback during
// collection.
// [out] result: A napi_value representing a JavaScript ArrayBuffer.
// JavaScript ArrayBuffers are described in Section 24.1 of the ECMAScript
// Language Specification.
// N-API version: 1
func CreateExternalArrayBuffer(env Env, length uint, raw unsafe.Pointer) (Value, Status) {
var res C.napi_value
// Remember to handle napi_finalize finalize_cb and void* finalize_hint
var status = C.napi_create_external_arraybuffer(env, raw, C.size_t(length), nil, nil, &res)
return Value(res), Status(status)
}
// CreateExternalBuffer function allocates a node::Buffer object and
// initializes it with data backed by the passed in buffer. While this is still a
// fully-supported data structure, in most cases using a TypedArray will suffice.
// [in] env: The environment that the API is invoked under.
// [in] length: Size in bytes of the input buffer (should be the same as the size
// of the new buffer).
// [in] data: Raw pointer to the underlying buffer to copy from.
// [in] finalize_cb: Optional callback to call when the ArrayBuffer is being
// collected.
// [in] finalize_hint: Optional hint to pass to the finalize callback during
// collection.
// [out] result: A napi_value representing a node::Buffer.
// Remember that fsor Node.js >=4 Buffers are Uint8Array.
// N-API version: 1
func CreateExternalBuffer(env Env, length uint, raw unsafe.Pointer) (Value, Status) {
var res C.napi_value
// Remember to handle napi_finalize finalize_cb and void* finalize_hint
var status = C.napi_create_external_buffer(env, C.size_t(length), raw, nil, nil, &res)
return Value(res), Status(status)
}
// CreateObject function allocates a default JavaScript Object. It is the
// equivalent of doing new Object() in JavaScript.