├── .gitignore ├── .travis.yml ├── CMakeLists.txt ├── LICENSE.md ├── README.md ├── benchmark ├── README.md ├── children │ ├── alive.js │ └── require-lodash.js ├── fork │ ├── hive-fork-child-process.js │ ├── node-fork-child-process.js │ └── node-spawn-child-process.js ├── require-lodash │ ├── hive-fork-child-process.js │ ├── node-fork-child-process.js │ └── node-spawn-child-process.js └── runner.js ├── binding.gyp ├── cmake ├── FindNodeAddon.cmake └── node-addon-api.cmake ├── deps └── node-addon-api │ ├── .editorconfig │ ├── .gitignore │ ├── .npmignore │ ├── .npmrc │ ├── .travis.yml │ ├── CHANGELOG.md │ ├── CODE_OF_CONDUCT.md │ ├── LICENSE.md │ ├── README.md │ ├── appveyor.yml │ ├── doc │ ├── .gitignore │ ├── Doxyfile │ ├── array_buffer.md │ ├── async_context.md │ ├── async_operations.md │ ├── async_worker.md │ ├── basic_types.md │ ├── bigint.md │ ├── boolean.md │ ├── buffer.md │ ├── callback_scope.md │ ├── callbackinfo.md │ ├── checker-tool.md │ ├── class_property_descriptor.md │ ├── cmake-js.md │ ├── conversion-tool.md │ ├── creating_a_release.md │ ├── dataview.md │ ├── env.md │ ├── error.md │ ├── error_handling.md │ ├── escapable_handle_scope.md │ ├── external.md │ ├── function.md │ ├── function_reference.md │ ├── generator.md │ ├── handle_scope.md │ ├── memory_management.md │ ├── node-gyp.md │ ├── number.md │ ├── object.md │ ├── object_lifetime_management.md │ ├── object_reference.md │ ├── object_wrap.md │ ├── prebuild_tools.md │ ├── promises.md │ ├── property_descriptor.md │ ├── range_error.md │ ├── reference.md │ ├── setup.md │ ├── string.md │ ├── symbol.md │ ├── type_error.md │ ├── typed_array.md │ ├── typed_array_of.md │ ├── value.md │ ├── version_management.md │ └── working_with_javascript_values.md │ ├── external-napi │ └── node_api.h │ ├── index.js │ ├── napi-inl.deprecated.h │ ├── napi-inl.h │ ├── napi.h │ ├── package.json │ ├── src │ ├── .gitignore │ ├── node_api.cc │ ├── node_api.gyp │ ├── node_api.h │ ├── node_api_types.h │ ├── node_internals.cc │ ├── node_internals.h │ ├── nothing.c │ ├── util-inl.h │ └── util.h │ ├── test │ ├── .gitignore │ ├── arraybuffer.cc │ ├── arraybuffer.js │ ├── asynccontext.cc │ ├── asynccontext.js │ ├── asyncworker-persistent.cc │ ├── asyncworker-persistent.js │ ├── asyncworker.cc │ ├── asyncworker.js │ ├── basic_types │ │ ├── array.cc │ │ ├── array.js │ │ ├── boolean.cc │ │ ├── boolean.js │ │ ├── number.cc │ │ ├── number.js │ │ ├── value.cc │ │ └── value.js │ ├── bigint.cc │ ├── bigint.js │ ├── binding.cc │ ├── binding.gyp │ ├── buffer.cc │ ├── buffer.js │ ├── callbackscope.cc │ ├── callbackscope.js │ ├── common │ │ └── index.js │ ├── dataview │ │ ├── dataview.cc │ │ ├── dataview.js │ │ ├── dataview_read_write.cc │ │ └── dataview_read_write.js │ ├── error.cc │ ├── error.js │ ├── external.cc │ ├── external.js │ ├── function.cc │ ├── function.js │ ├── handlescope.cc │ ├── handlescope.js │ ├── index.js │ ├── memory_management.cc │ ├── memory_management.js │ ├── name.cc │ ├── name.js │ ├── napi_child.js │ ├── object │ │ ├── delete_property.cc │ │ ├── delete_property.js │ │ ├── get_property.cc │ │ ├── get_property.js │ │ ├── has_own_property.cc │ │ ├── has_own_property.js │ │ ├── has_property.cc │ │ ├── has_property.js │ │ ├── object.cc │ │ ├── object.js │ │ ├── object_deprecated.cc │ │ ├── object_deprecated.js │ │ ├── set_property.cc │ │ └── set_property.js │ ├── objectreference.cc │ ├── objectreference.js │ ├── objectwrap.cc │ ├── objectwrap.js │ ├── promise.cc │ ├── promise.js │ ├── testUtil.js │ ├── thunking_manual.cc │ ├── thunking_manual.js │ ├── typedarray-bigint.js │ ├── typedarray.cc │ ├── typedarray.js │ ├── version_management.cc │ └── version_management.js │ └── tools │ ├── README.md │ ├── check-napi.js │ └── conversion.js ├── lib └── hive.js ├── package.json ├── script ├── apt-get-install-deps ├── install-shadow-node └── test ├── src ├── hive.cc └── hive.h ├── test ├── child-exit-code.test.skip.js ├── children │ ├── alive.js │ └── exit-next-tick.js ├── fork-child-process.test.js └── helper │ └── index.js └── yarn.lock /.gitignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | 3 | build 4 | out 5 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | stages: 2 | - test 3 | 4 | language: node_js 5 | node_js: 6 | - '10' 7 | 8 | install: 9 | - if [[ "$TRAVIS_OS_NAME" == "linux" ]]; then script/apt-get-install-deps; fi 10 | - script/install-shadow-node 11 | - yarn 12 | 13 | script: 14 | - yarn build 15 | - yarn test 16 | 17 | jobs: 18 | include: 19 | - stage: test 20 | os: linux 21 | dist: trusty 22 | -------------------------------------------------------------------------------- /CMakeLists.txt: -------------------------------------------------------------------------------- 1 | cmake_minimum_required(VERSION 3.0) 2 | project(yoda-hive CXX) 3 | set(CMAKE_CXX_STANDARD 11) 4 | set(CMAKE_MODULE_PATH "${CMAKE_SOURCE_DIR}/cmake;${CMAKE_MODULE_PATH}") 5 | 6 | find_package(NodeAddon REQUIRED) 7 | include(cmake/node-addon-api.cmake) 8 | 9 | add_node_addon(${PROJECT_NAME} SOURCES src/hive.cc) 10 | target_link_libraries(${PROJECT_NAME} node-addon-api) 11 | 12 | if(CMAKE_INSTALL_PREFIX_INITIALIZED_TO_DEFAULT) 13 | set(CMAKE_INSTALL_PREFIX "/usr/lib/hive" CACHE PATH "..." FORCE) 14 | endif() 15 | install(TARGETS ${PROJECT_NAME} DESTINATION "${CMAKE_INSTALL_PREFIX}/out") 16 | install(DIRECTORY lib DESTINATION "${CMAKE_INSTALL_PREFIX}") 17 | install(FILES package.json DESTINATION "${CMAKE_INSTALL_PREFIX}") 18 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Hive 2 | 3 | [![Build Status](https://travis-ci.com/yodaos-project/hive.svg?branch=master)](https://travis-ci.com/yodaos-project/hive) 4 | [![License](https://img.shields.io/badge/licence-apache%202.0-green.svg)](LICENSE.md) 5 | 6 | ## Benchmarks 7 | 8 | Following results were ran on a MacBook Pro (13-inch, 2017, Two Thunderbolt 3 ports) with 2.5 GHz Intel Core i7, 16 GB 2133 MHz LPDDR3. 9 | 10 | ### Node.js v12.4.0 11 | 12 | - fork/hive-fork-child-process.js n=100: 7.649900981841598ms 13 | - fork/node-fork-child-process.js n=100: 46.94695102435441ms 14 | - fork/node-spawn-child-process.js n=100: 42.67337671217151ms 15 | 16 | - require-lodash/hive-fork-child-process.js n=100: 8.122591648174616ms 17 | - require-lodash/node-fork-child-process.js n=100: 59.44227485495386ms 18 | - require-lodash/node-spawn-child-process.js n=100: 57.76666079101686ms 19 | -------------------------------------------------------------------------------- /benchmark/README.md: -------------------------------------------------------------------------------- 1 | # Benchmark 2 | 3 | ## Running Benchmark 4 | 5 | ``` 6 | node benchmark/runner [runtime-program] 7 | ``` 8 | 9 | - `bench-suite` must be directory of benchmark suite in `hive/benchmark`. 10 | - `runtime-program` is an optional argument that specifies alternative Node.js runtime program. 11 | -------------------------------------------------------------------------------- /benchmark/children/alive.js: -------------------------------------------------------------------------------- 1 | console.log('# on child', process.hrtime()) 2 | setInterval(() => { 3 | console.log('Still alive') 4 | }, 1000) 5 | -------------------------------------------------------------------------------- /benchmark/children/require-lodash.js: -------------------------------------------------------------------------------- 1 | require('lodash') 2 | 3 | console.log('# on child', process.hrtime()) 4 | setInterval(() => { 5 | console.log('Still alive') 6 | }, 1000) 7 | -------------------------------------------------------------------------------- /benchmark/fork/hive-fork-child-process.js: -------------------------------------------------------------------------------- 1 | var hive = require('../../lib/hive') 2 | 3 | console.log('# on fork', process.hrtime()) 4 | var pid = hive.fork(__dirname, ['../children/alive']) 5 | if (pid > 0) { 6 | process.on('SIGTERM', () => { 7 | process.kill(pid) 8 | process.exit() 9 | }) 10 | } 11 | -------------------------------------------------------------------------------- /benchmark/fork/node-fork-child-process.js: -------------------------------------------------------------------------------- 1 | var childProcess = require('child_process') 2 | 3 | console.log('# on fork', process.hrtime()) 4 | var cp = childProcess.fork('../children/alive.js', [], { cwd: __dirname, stdio: 'inherit' }) 5 | process.on('SIGTERM', () => { 6 | cp.kill() 7 | process.exit() 8 | }) 9 | -------------------------------------------------------------------------------- /benchmark/fork/node-spawn-child-process.js: -------------------------------------------------------------------------------- 1 | var childProcess = require('child_process') 2 | 3 | console.log('# on fork', process.hrtime()) 4 | var cp = childProcess.spawn(process.argv[0], ['../children/alive'], { cwd: __dirname, stdio: 'inherit' }) 5 | process.on('SIGTERM', () => { 6 | cp.kill() 7 | process.exit() 8 | }) 9 | -------------------------------------------------------------------------------- /benchmark/require-lodash/hive-fork-child-process.js: -------------------------------------------------------------------------------- 1 | require('lodash') 2 | var hive = require('../../lib/hive') 3 | 4 | console.log('# on fork', process.hrtime()) 5 | var pid = hive.fork(__dirname, ['../children/require-lodash']) 6 | if (pid > 0) { 7 | process.on('SIGTERM', () => { 8 | process.kill(pid) 9 | process.exit() 10 | }) 11 | } 12 | -------------------------------------------------------------------------------- /benchmark/require-lodash/node-fork-child-process.js: -------------------------------------------------------------------------------- 1 | var childProcess = require('child_process') 2 | 3 | console.log('# on fork', process.hrtime()) 4 | var cp = childProcess.fork('../children/require-lodash', [], { cwd: __dirname, stdio: 'inherit' }) 5 | process.on('SIGTERM', () => { 6 | cp.kill() 7 | process.exit() 8 | }) 9 | -------------------------------------------------------------------------------- /benchmark/require-lodash/node-spawn-child-process.js: -------------------------------------------------------------------------------- 1 | var childProcess = require('child_process') 2 | 3 | console.log('# on fork', process.hrtime()) 4 | var cp = childProcess.spawn(process.argv[0], ['../children/require-lodash'], { cwd: __dirname, stdio: 'inherit' }) 5 | process.on('SIGTERM', () => { 6 | cp.kill() 7 | process.exit() 8 | }) 9 | -------------------------------------------------------------------------------- /benchmark/runner.js: -------------------------------------------------------------------------------- 1 | const childProcess = require('child_process') 2 | const readline = require('readline') 3 | const path = require('path') 4 | const fs = require('fs') 5 | const NS_PER_SEC = 1e9 6 | const NS_PER_MSEC = 1e6 7 | 8 | function runOnce (argv0, script) { 9 | const cp = childProcess.spawn(argv0, [ script ], { cwd: __dirname, stdio: 'pipe' }) 10 | const rl = readline.createInterface(cp.stdout) 11 | let onFork 12 | let onChild 13 | 14 | return new Promise((resolve) => { 15 | rl.on('line', line => { 16 | let matched = line.match(/^# on fork \[\s?(\d+),\s?(\d+)\s?\]/) 17 | if (matched) { 18 | onFork = [ Number(matched[1]), Number(matched[2]) ] 19 | } 20 | 21 | matched = line.match(/^# on child \[\s?(\d+),\s?(\d+)\s?\]/) 22 | if (matched) { 23 | onChild = [ Number(matched[1]), Number(matched[2]) ] 24 | } 25 | 26 | if (onFork && onChild) { 27 | cp.kill() 28 | end() 29 | } 30 | }) 31 | 32 | function end () { 33 | const consumed = zip(onChild, onFork).map(it => it[0] - it[1]) 34 | if (consumed[1] < 0) { 35 | consumed[0] -= 1 36 | consumed[1] += NS_PER_SEC 37 | } 38 | resolve(consumed) 39 | } 40 | }) 41 | } 42 | 43 | async function runOneBench (program, bench, n = 100) { 44 | let result 45 | for (let times = 0; times < n; ++times) { 46 | const rc = await runOnce(program, bench) 47 | if (result == null) { 48 | result = rc 49 | } else { 50 | result = zip(result, rc).map(it => (it[0] + it[1]) / 2) 51 | } 52 | } 53 | return { n, result } 54 | } 55 | 56 | function zip (arra, arrb) { 57 | return arra.map((it, idx) => [ it, arrb[idx] ]) 58 | } 59 | 60 | async function main () { 61 | const suite = process.argv[2] 62 | const benches = fs.readdirSync(path.join(__dirname, suite)) 63 | .map(it => path.join(__dirname, suite, it)) 64 | const program = process.argv[3] || 'node' 65 | console.log(`using '${program}' as runtime...`) 66 | for (const bench of benches) { 67 | const report = await runOneBench(program, bench) 68 | console.log(`${bench.substring(__dirname.length + 1)} n=${report.n}: ${report.result[1] / NS_PER_MSEC}ms`) 69 | } 70 | } 71 | 72 | main() 73 | -------------------------------------------------------------------------------- /binding.gyp: -------------------------------------------------------------------------------- 1 | { 2 | "targets": [ 3 | { 4 | "target_name": "hive", 5 | "cflags!": [ "-fno-exceptions" ], 6 | "cflags_cc!": [ "-fno-exceptions" ], 7 | "sources": [ "src/hive.cc" ], 8 | "include_dirs": [ 9 | "* 8 | 9 | Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: 10 | 11 | The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 12 | 13 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -------------------------------------------------------------------------------- /deps/node-addon-api/appveyor.yml: -------------------------------------------------------------------------------- 1 | environment: 2 | # https://github.com/jasongin/nvs/blob/master/doc/CI.md 3 | NVS_VERSION: 1.4.2 4 | fast_finish: true 5 | matrix: 6 | - NODEJS_VERSION: node/4 7 | - NODEJS_VERSION: node/6 8 | - NODEJS_VERSION: node/8 9 | - NODEJS_VERSION: node/9 10 | - NODEJS_VERSION: node/10 11 | - NODEJS_VERSION: chakracore/8 12 | - NODEJS_VERSION: chakracore/10 13 | - NODEJS_VERSION: nightly 14 | - NODEJS_VERSION: chakracore-nightly 15 | 16 | matrix: 17 | fast_finish: true 18 | allow_failures: 19 | - NODEJS_VERSION: nightly 20 | - NODEJS_VERSION: chakracore-nightly 21 | 22 | platform: 23 | - x86 24 | - x64 25 | 26 | install: 27 | # nvs 28 | - git clone --branch v%NVS_VERSION% --depth 1 https://github.com/jasongin/nvs %LOCALAPPDATA%\nvs 29 | - set PATH=%LOCALAPPDATA%\nvs;%PATH% 30 | - nvs --version 31 | # node.js 32 | - nvs add %NODEJS_VERSION%/%PLATFORM% 33 | - nvs use %NODEJS_VERSION%/%PLATFORM% 34 | - node --version 35 | - node -p process.arch 36 | - npm --version 37 | # app 38 | - npm install 39 | 40 | test_script: 41 | - npm test 42 | 43 | build: off 44 | 45 | version: "{build}" 46 | 47 | cache: 48 | - node_modules 49 | -------------------------------------------------------------------------------- /deps/node-addon-api/doc/.gitignore: -------------------------------------------------------------------------------- 1 | /html 2 | -------------------------------------------------------------------------------- /deps/node-addon-api/doc/async_context.md: -------------------------------------------------------------------------------- 1 | # AsyncContext 2 | 3 | The [Napi::AsyncWorker](async_worker.md) class may not be appropriate for every 4 | scenario. When using any other async mechanism, introducing a new class 5 | `Napi::AsyncContext` is necessary to ensure an async operation is properly 6 | tracked by the runtime. The `Napi::AsyncContext` class can be passed to 7 | [Napi::Function::MakeCallback()](function.md) method to properly restore the 8 | correct async execution context. 9 | 10 | ## Methods 11 | 12 | ### Constructor 13 | 14 | Creates a new `Napi::AsyncContext`. 15 | 16 | ```cpp 17 | explicit Napi::AsyncContext::AsyncContext(napi_env env, const char* resource_name); 18 | ``` 19 | 20 | - `[in] env`: The environment in which to create the `Napi::AsyncContext`. 21 | - `[in] resource_name`: Null-terminated strings that represents the 22 | identifier for the kind of resource that is being provided for diagnostic 23 | information exposed by the `async_hooks` API. 24 | 25 | ### Constructor 26 | 27 | Creates a new `Napi::AsyncContext`. 28 | 29 | ```cpp 30 | explicit Napi::AsyncContext::AsyncContext(napi_env env, const char* resource_name, const Napi::Object& resource); 31 | ``` 32 | 33 | - `[in] env`: The environment in which to create the `Napi::AsyncContext`. 34 | - `[in] resource_name`: Null-terminated strings that represents the 35 | identifier for the kind of resource that is being provided for diagnostic 36 | information exposed by the `async_hooks` API. 37 | - `[in] resource`: Object associated with the asynchronous operation that 38 | will be passed to possible `async_hooks`. 39 | 40 | ### Destructor 41 | 42 | The `Napi::AsyncContext` to be destroyed. 43 | 44 | ```cpp 45 | virtual Napi::AsyncContext::~AsyncContext(); 46 | ``` 47 | 48 | ## Operator 49 | 50 | ```cpp 51 | Napi::AsyncContext::operator napi_async_context() const; 52 | ``` 53 | 54 | Returns the N-API `napi_async_context` wrapped by the `Napi::AsyncContext` 55 | object. This can be used to mix usage of the C N-API and node-addon-api. 56 | 57 | ## Example 58 | 59 | ```cpp 60 | #include "napi.h" 61 | 62 | void MakeCallbackWithAsyncContext(const Napi::CallbackInfo& info) { 63 | Napi::Function callback = info[0].As(); 64 | Napi::Object resource = info[1].As(); 65 | 66 | // Creat a new async context instance. 67 | Napi::AsyncContext context(info.Env(), "async_context_test", resource); 68 | 69 | // Invoke the callback with the async context instance. 70 | callback.MakeCallback(Napi::Object::New(info.Env()), 71 | std::initializer_list{}, context); 72 | 73 | // The async context instance is automatically destroyed here because it's 74 | // block-scope like `Napi::HandleScope`. 75 | } 76 | ``` 77 | -------------------------------------------------------------------------------- /deps/node-addon-api/doc/async_operations.md: -------------------------------------------------------------------------------- 1 | # Asynchronous operations 2 | 3 | Node.js native add-ons often need to execute long running tasks and to avoid 4 | blocking the **event loop** they have to run them asynchronously from the 5 | **event loop**. 6 | In the Node.js model of execution the event loop thread represents the thread 7 | where JavaScript code is executing. The node.js guidance is to avoid blocking 8 | other work queued on the event loop thread. Therefore, we need to do this work on 9 | another thread. 10 | 11 | All this means that native add-ons need to leverage async helpers from libuv as 12 | part of their implementation. This allows them to schedule work to be executed 13 | asynchronously so that their methods can return in advance of the work being 14 | completed. 15 | 16 | Node Addon API provides an interface to support functions that cover 17 | the most common asynchronous use cases. There is an abstract classes to implement 18 | asynchronous operations: 19 | 20 | - **[`Napi::AsyncWorker`](async_worker.md)** 21 | 22 | These class helps manage asynchronous operations through an abstraction 23 | of the concept of moving data between the **event loop** and **worker threads**. 24 | 25 | Also, the above class may not be appropriate for every scenario. When using any 26 | other asynchronous mechanism, the following API is necessary to ensure an 27 | asynchronous operation is properly tracked by the runtime: 28 | 29 | - **[AsyncContext](async_context.md)** 30 | 31 | - **[CallbackScope](callback_scope.md)** 32 | -------------------------------------------------------------------------------- /deps/node-addon-api/doc/bigint.md: -------------------------------------------------------------------------------- 1 | # BigInt 2 | 3 | A JavaScript BigInt value. 4 | 5 | ## Methods 6 | 7 | ### New 8 | 9 | ```cpp 10 | static Napi::BigInt Napi::BigInt::New(Napi::Env env, int64_t value); 11 | ``` 12 | 13 | - `[in] env`: The environment in which to construct the `Napi::BigInt` object. 14 | - `[in] value`: The value the JavaScript `BigInt` will contain 15 | 16 | These APIs convert the C `int64_t` and `uint64_t` types to the JavaScript 17 | `BigInt` type. 18 | 19 | ```cpp 20 | static Napi::BigInt Napi::BigInt::New(Napi::Env env, 21 | int sign_bit, 22 | size_t word_count, 23 | const uint64_t* words); 24 | ``` 25 | 26 | - `[in] env`: The environment in which to construct the `Napi::BigInt` object. 27 | - `[in] sign_bit`: Determines if the resulting `BigInt` will be positive or negative. 28 | - `[in] word_count`: The length of the words array. 29 | - `[in] words`: An array of `uint64_t` little-endian 64-bit words. 30 | 31 | This API converts an array of unsigned 64-bit words into a single `BigInt` 32 | value. 33 | 34 | The resulting `BigInt` is calculated as: (–1)`sign_bit` (`words[0]` 35 | × (264)0 + `words[1]` × (264)1 + …) 36 | 37 | Returns a new JavaScript `BigInt`. 38 | 39 | ### Constructor 40 | 41 | ```cpp 42 | Napi::BigInt(); 43 | ``` 44 | 45 | Returns a new empty JavaScript `Napi::BigInt`. 46 | 47 | ### Int64Value 48 | 49 | ```cpp 50 | int64_t Napi::BitInt::Int64Value(bool* lossless) const; 51 | ``` 52 | 53 | - `[out] lossless`: Indicates whether the `BigInt` value was converted losslessly. 54 | 55 | Returns the C `int64_t` primitive equivalent of the given JavaScript 56 | `BigInt`. If needed it will truncate the value, setting lossless to false. 57 | 58 | ### Uint64Value 59 | 60 | ```cpp 61 | uint64_t Napi::BigInt::Uint64Value(bool* lossless) const; 62 | ``` 63 | 64 | - `[out] lossless`: Indicates whether the `BigInt` value was converted 65 | losslessly. 66 | 67 | Returns the C `uint64_t` primitive equivalent of the given JavaScript 68 | `BigInt`. If needed it will truncate the value, setting lossless to false. 69 | 70 | ### WordCount 71 | 72 | ```cpp 73 | size_t Napi::BigInt::WordCount() const; 74 | ``` 75 | 76 | Returns the number of words needed to store this `BigInt` value. 77 | 78 | ### ToWords 79 | 80 | ```cpp 81 | void Napi::BigInt::ToWords(size_t* word_count, int* sign_bit, uint64_t* words); 82 | ``` 83 | 84 | - `[out] sign_bit`: Integer representing if the JavaScript `BigInt` is positive 85 | or negative. 86 | - `[in/out] word_count`: Must be initialized to the length of the words array. 87 | Upon return, it will be set to the actual number of words that would be 88 | needed to store this `BigInt`. 89 | - `[out] words`: Pointer to a pre-allocated 64-bit word array. 90 | 91 | Returns a single `BigInt` value into a sign bit, 64-bit little-endian array, 92 | and the number of elements in the array. 93 | -------------------------------------------------------------------------------- /deps/node-addon-api/doc/boolean.md: -------------------------------------------------------------------------------- 1 | # Boolean 2 | 3 | `Napi::Boolean` class is a representation of the JavaScript `Boolean` object. The 4 | `Napi::Boolean` class inherits its behavior from the `Napi::Value` class 5 | (for more info see: [`Napi::Value`](value.md)). 6 | 7 | ## Methods 8 | 9 | ### Constructor 10 | 11 | Creates a new empty instance of an `Napi::Boolean` object. 12 | 13 | ```cpp 14 | Napi::Boolean::Boolean(); 15 | ``` 16 | 17 | Returns a new _empty_ `Napi::Boolean` object. 18 | 19 | ### Contructor 20 | 21 | Creates a new instance of the `Napi::Boolean` object. 22 | 23 | ```cpp 24 | Napi::Boolean(napi_env env, napi_value value); 25 | ``` 26 | 27 | - `[in] env`: The `napi_env` environment in which to construct the `Napi::Boolean` object. 28 | - `[in] value`: The `napi_value` which is a handle for a JavaScript `Boolean`. 29 | 30 | Returns a non-empty `Napi::Boolean` object. 31 | 32 | ### New 33 | 34 | Initializes a new instance of the `Napi::Boolean` object. 35 | 36 | ```cpp 37 | Napi::Boolean Napi::Boolean::New(napi_env env, bool value); 38 | ``` 39 | - `[in] env`: The `napi_env` environment in which to construct the `Napi::Boolean` object. 40 | - `[in] value`: The primitive boolean value (`true` or `false`). 41 | 42 | Returns a new instance of the `Napi::Boolean` object. 43 | 44 | ### Value 45 | 46 | Converts a `Napi::Boolean` value to a boolean primitive. 47 | 48 | ```cpp 49 | bool Napi::Boolean::Value() const; 50 | ``` 51 | 52 | Returns the boolean primitive type of the corresponding `Napi::Boolean` object. 53 | 54 | ## Operators 55 | 56 | ### operator bool 57 | 58 | Converts a `Napi::Boolean` value to a boolean primitive. 59 | 60 | ```cpp 61 | Napi::Boolean::operator bool() const; 62 | ``` 63 | 64 | Returns the boolean primitive type of the corresponding `Napi::Boolean` object. 65 | -------------------------------------------------------------------------------- /deps/node-addon-api/doc/callback_scope.md: -------------------------------------------------------------------------------- 1 | # CallbackScope 2 | 3 | There are cases (for example, resolving promises) where it is necessary to have 4 | the equivalent of the scope associated with a callback in place when making 5 | certain N-API calls. 6 | 7 | ## Methods 8 | 9 | ### Constructor 10 | 11 | Creates a new callback scope on the stack. 12 | 13 | ```cpp 14 | Napi::CallbackScope::CallbackScope(napi_env env, napi_callback_scope scope); 15 | ``` 16 | 17 | - `[in] env`: The environment in which to create the `Napi::CallbackScope`. 18 | - `[in] scope`: The pre-existing `napi_callback_scope` or `Napi::CallbackScope`. 19 | 20 | ### Constructor 21 | 22 | Creates a new callback scope on the stack. 23 | 24 | ```cpp 25 | Napi::CallbackScope::CallbackScope(napi_env env, napi_async_context context); 26 | ``` 27 | 28 | - `[in] env`: The environment in which to create the `Napi::CallbackScope`. 29 | - `[in] async_context`: The pre-existing `napi_async_context` or `Napi::AsyncContext`. 30 | 31 | ### Destructor 32 | 33 | Deletes the instance of `Napi::CallbackScope` object. 34 | 35 | ```cpp 36 | virtual Napi::CallbackScope::~CallbackScope(); 37 | ``` 38 | 39 | ### Env 40 | 41 | ```cpp 42 | Napi::Env Napi::CallbackScope::Env() const; 43 | ``` 44 | 45 | Returns the `Napi::Env` associated with the `Napi::CallbackScope`. 46 | 47 | ## Operator 48 | 49 | ```cpp 50 | Napi::CallbackScope::operator napi_callback_scope() const; 51 | ``` 52 | 53 | Returns the N-API `napi_callback_scope` wrapped by the `Napi::CallbackScope` 54 | object. This can be used to mix usage of the C N-API and node-addon-api. 55 | -------------------------------------------------------------------------------- /deps/node-addon-api/doc/callbackinfo.md: -------------------------------------------------------------------------------- 1 | # CallbackInfo 2 | 3 | The object representing the components of the JavaScript request being made. 4 | 5 | The `Napi::CallbackInfo` object is usually created and passed by the Node.js runtime or node-addon-api infrastructure. 6 | 7 | The `Napi::CallbackInfo` object contains the arguments passed by the caller. The number of arguments is returned by the `Length` method. Each individual argument can be accessed using the `operator[]` method. 8 | 9 | The `SetData` and `Data` methods are used to set and retrieve the data pointer contained in the `Napi::CallbackInfo` object. 10 | 11 | ## Methods 12 | 13 | ### Constructor 14 | 15 | ```cpp 16 | Napi::CallbackInfo::CallbackInfo(napi_env env, napi_callback_info info); 17 | ``` 18 | 19 | - `[in] env`: The `napi_env` environment in which to construct the `Napi::CallbackInfo` object. 20 | - `[in] info`: The `napi_callback_info` data structure from which to construct the `Napi::CallbackInfo` object. 21 | 22 | ### Env 23 | 24 | ```cpp 25 | Napi::Env Napi::CallbackInfo::Env() const; 26 | ``` 27 | 28 | Returns the `Env` object in which the request is being made. 29 | 30 | ### NewTarget 31 | 32 | ```cpp 33 | Napi::Value Napi::CallbackInfo::NewTarget() const; 34 | ``` 35 | 36 | Returns the `new.target` value of the constructor call. If the function that was invoked (and for which the `Napi::NCallbackInfo` was passed) is not a constructor call, a call to `IsEmpty()` on the returned value returns true. 37 | 38 | ### IsConstructCall 39 | 40 | ```cpp 41 | bool Napi::CallbackInfo::IsConstructCall() const; 42 | ``` 43 | 44 | Returns a `bool` indicating if the function that was invoked (and for which the `Napi::CallbackInfo` was passed) is a constructor call. 45 | 46 | ### Length 47 | 48 | ```cpp 49 | size_t Napi::CallbackInfo::Length() const; 50 | ``` 51 | 52 | Returns the number of arguments passed in the `Napi::CallbackInfo` object. 53 | 54 | ### operator [] 55 | 56 | ```cpp 57 | const Napi::Value operator [](size_t index) const; 58 | ``` 59 | 60 | - `[in] index`: The zero-based index of the requested argument. 61 | 62 | Returns a `Napi::Value` object containing the requested argument. 63 | 64 | ### This 65 | 66 | ```cpp 67 | Napi::Value Napi::CallbackInfo::This() const; 68 | ``` 69 | 70 | Returns the JavaScript `this` value for the call 71 | 72 | ### Data 73 | 74 | ```cpp 75 | void* Napi::CallbackInfo::Data() const; 76 | ``` 77 | 78 | Returns the data pointer for the callback. 79 | 80 | ### SetData 81 | 82 | ```cpp 83 | void Napi::CallbackInfo::SetData(void* data); 84 | ``` 85 | 86 | - `[in] data`: The new data pointer to associate with this `Napi::CallbackInfo` object. 87 | 88 | Returns `void`. 89 | 90 | ### Not documented here 91 | 92 | ```cpp 93 | Napi::CallbackInfo::~CallbackInfo(); 94 | // Disallow copying to prevent multiple free of _dynamicArgs 95 | Napi::CallbackInfo::CallbackInfo(CallbackInfo const &) = delete; 96 | void Napi::CallbackInfo::operator=(CallbackInfo const &) = delete; 97 | ``` 98 | -------------------------------------------------------------------------------- /deps/node-addon-api/doc/checker-tool.md: -------------------------------------------------------------------------------- 1 | # Checker Tool 2 | 3 | **node-addon-api** provides a [checker tool][] that will inspect a given 4 | directory tree, identifying all Node.js native addons therein, and further 5 | indicating for each addon whether it is an N-API addon. 6 | 7 | ## To use the checker tool: 8 | 9 | 1. Install the application with `npm install`. 10 | 11 | 2. If the application does not depend on **node-addon-api**, copy the 12 | checker tool into the application's directory. 13 | 14 | 3. If the application does not depend on **node-addon-api**, run the checker 15 | tool from the application's directory: 16 | 17 | ```sh 18 | node ./check-napi.js 19 | ``` 20 | 21 | Otherwise, the checker tool can be run from the application's 22 | `node_modules/` subdirectory: 23 | 24 | ```sh 25 | node ./node_modules/node-addon-api/tools/check-napi.js 26 | ``` 27 | 28 | The tool accepts the root directory from which to start checking for Node.js 29 | native addons as a single optional command line parameter. If ommitted it will 30 | start checking from the current directory (`.`). 31 | 32 | [checker tool]: ../tools/check-napi.js 33 | -------------------------------------------------------------------------------- /deps/node-addon-api/doc/class_property_descriptor.md: -------------------------------------------------------------------------------- 1 | # Class propertry and descriptor 2 | 3 | Property descriptor for use with `Napi::ObjectWrap::DefineClass()`. 4 | This is different from the standalone `Napi::PropertyDescriptor` because it is 5 | specific to each `Napi::ObjectWrap` subclass. 6 | This prevents using descriptors from a different class when defining a new class 7 | (preventing the callbacks from having incorrect `this` pointers). 8 | 9 | ## Methods 10 | 11 | ### Constructor 12 | 13 | Creates new instance of `Napi::ClassPropertyDescriptor` descriptor object. 14 | 15 | ```cpp 16 | Napi::ClassPropertyDescriptor(napi_property_descriptor desc) : _desc(desc) {} 17 | ``` 18 | 19 | - `[in] desc`: The `napi_property_descriptor` 20 | 21 | Returns new instance of `Napi::ClassPropertyDescriptor` that is used as property descriptor 22 | inside the `Napi::ObjectWrap` class. 23 | 24 | ### Operator 25 | 26 | ```cpp 27 | operator napi_property_descriptor&() { return _desc; } 28 | ``` 29 | 30 | Returns the original N-API `napi_property_descriptor` wrapped inside the `Napi::ClassPropertyDescriptor` 31 | 32 | ```cpp 33 | operator const napi_property_descriptor&() const { return _desc; } 34 | ``` 35 | 36 | Returns the original N-API `napi_property_descriptor` wrapped inside the `Napi::ClassPropertyDescriptor` 37 | -------------------------------------------------------------------------------- /deps/node-addon-api/doc/cmake-js.md: -------------------------------------------------------------------------------- 1 | # CMake.js 2 | 3 | **CMake.js** is a build tool that allow native addon developer to compile their 4 | C++ code into executable form. It works like **[node-gyp](node-gyp.md)** but 5 | instead of Google's **gyp** format it is base on **CMake** build system. 6 | 7 | ## **CMake** reference 8 | 9 | - [Installation](https://www.npmjs.com/package/cmake-js#installation) 10 | - [How to use](https://www.npmjs.com/package/cmake-js#usage) 11 | - [Using N-API and node-addon-api](https://github.com/cmake-js/cmake-js#n-api-and-node-addon-api) 12 | - [Tutorials](https://www.npmjs.com/package/cmake-js#tutorials) 13 | - [Use case in the works - ArrayFire.js](https://www.npmjs.com/package/cmake-js#use-case-in-the-works---arrayfirejs) 14 | 15 | Sometimes finding the right settings is not easy so to accomplish at most 16 | complicated task please refer to: 17 | 18 | - [CMake documentation](https://cmake.org/) 19 | - [CMake.js wiki](https://github.com/cmake-js/cmake-js/wiki) -------------------------------------------------------------------------------- /deps/node-addon-api/doc/conversion-tool.md: -------------------------------------------------------------------------------- 1 | # Conversion Tool 2 | 3 | To make the migration to **node-addon-api** easier, we have provided a script to 4 | help complete some tasks. 5 | 6 | ## To use the conversion script: 7 | 8 | 1. Go to your module directory 9 | 10 | ``` 11 | cd [module_path] 12 | ``` 13 | 14 | 2. Install node-addon-api module 15 | 16 | ``` 17 | npm install node-addon-api 18 | ``` 19 | 3. Run node-addon-api conversion script 20 | 21 | ``` 22 | node ./node_modules/node-addon-api/tools/conversion.js ./ 23 | ``` 24 | 25 | 4. While this script makes conversion easier, it still cannot fully convert 26 | the module. The next step is to try to build the module and complete the 27 | remaining conversions necessary to allow it to compile and pass all of the 28 | module's tests. -------------------------------------------------------------------------------- /deps/node-addon-api/doc/creating_a_release.md: -------------------------------------------------------------------------------- 1 | # Creating a release 2 | 3 | Only collaborators in npm for **node-addon-api** can create releases. 4 | If you want to be able to do releases ask one of the existing 5 | collaborators to add you. If necessary you can ask the build 6 | Working Group who manages the Node.js npm user to add you if 7 | there are no other active collaborators. 8 | 9 | ## Prerequisites 10 | 11 | Before to start creating a new release check if you have installed the following 12 | tools: 13 | 14 | * [Changelog maker](https://www.npmjs.com/package/changelog-maker) 15 | 16 | If not please follow the instruction reported in the tool's documentation to 17 | install it. 18 | 19 | ## Publish new release 20 | 21 | These are the steps to follow to create a new release: 22 | 23 | * Open an issue in the **node-addon-api** repo documenting the intent to create a 24 | new release. Give people some time to comment or suggest PRs that should land first. 25 | 26 | * Validate all tests pass by running npm test on master. 27 | 28 | * Update the version in **package.json** appropriately. 29 | 30 | * Update the [README.md](https://github.com/nodejs/node-addon-api/blob/master/README.md) 31 | to show the new version as the latest. 32 | 33 | * Generate the changelog for the new version using **changelog maker** tool. From 34 | the route folder of the repo launch the following command: 35 | 36 | ```bash 37 | > changelog-maker 38 | ``` 39 | * Use the output generated by **changelog maker** to pdate the [CHANGELOG.md](https://github.com/nodejs/node-addon-api/blob/master/CHANGELOG.md) 40 | following the style used in publishing the previous release. 41 | 42 | * Add any new contributors to the "contributors" section in the package.json 43 | 44 | * Validate all tests pass by running npm test on master. 45 | 46 | * Use **[CI](https://ci.nodejs.org/view/x%20-%20Abi%20stable%20module%20API/job/node-test-node-addon-api/)** 47 | to validate tests pass for latest 11, 10, 8, 6 releases (note there are still some issues on SmartOS and 48 | Windows in the testing). 49 | 50 | * Do a clean checkout of node-addon-api. 51 | 52 | * Login and then run `npm publish`. 53 | 54 | * Create a release in Github (look at existing releases for an example). 55 | 56 | * Validate that you can run `npm install node-addon-api` successfully 57 | and that the correct version is installed. 58 | 59 | * Comment on the issue opened in the first step that the release has been created 60 | and close the issue. 61 | 62 | * Tweet that the release has been created. 63 | -------------------------------------------------------------------------------- /deps/node-addon-api/doc/env.md: -------------------------------------------------------------------------------- 1 | # Env 2 | 3 | The opaque data structure containing the environment in which the request is being run. 4 | 5 | The Env object is usually created and passed by the Node.js runtime or node-addon-api infrastructure. 6 | 7 | ## Methods 8 | 9 | ### Constructor 10 | 11 | ```cpp 12 | Napi::Env::Env(napi_env env); 13 | ``` 14 | 15 | - `[in] env`: The `napi_env` environment from which to construct the `Napi::Env` object. 16 | 17 | ### napi_env 18 | 19 | ```cpp 20 | operator napi_env() const; 21 | ``` 22 | 23 | Returns the `napi_env` opaque data structure representing the environment. 24 | 25 | ### Global 26 | 27 | ```cpp 28 | Napi::Object Napi::Env::Global() const; 29 | ``` 30 | 31 | Returns the `Napi::Object` representing the environment's JavaScript Global Object. 32 | 33 | ### Undefined 34 | 35 | ```cpp 36 | Napi::Value Napi::Env::Undefined() const; 37 | ``` 38 | 39 | Returns the `Napi::Value` representing the environment's JavaScript Undefined Object. 40 | 41 | ### Null 42 | 43 | ```cpp 44 | Napi::Value Napi::Env::Null() const; 45 | ``` 46 | 47 | Returns the `Napi::Value` representing the environment's JavaScript Null Object. 48 | 49 | ### IsExceptionPending 50 | 51 | ```cpp 52 | bool Napi::Env::IsExceptionPending() const; 53 | ``` 54 | 55 | Returns a `bool` indicating if an exception is pending in the environment. 56 | 57 | ### GetAndClearPendingException 58 | 59 | ```cpp 60 | Napi::Error Napi::Env::GetAndClearPendingException(); 61 | ``` 62 | 63 | Returns an `Napi::Error` object representing the environment's pending exception, if any. 64 | -------------------------------------------------------------------------------- /deps/node-addon-api/doc/error.md: -------------------------------------------------------------------------------- 1 | # Error 2 | 3 | The `Napi::Error` class is a representation of the JavaScript `Error` object that is thrown 4 | when runtime errors occur. The Error object can also be used as a base object for 5 | user-defined exceptions. 6 | 7 | The `Napi::Error` class is a persistent reference to a JavaScript error object thus 8 | inherits its behavior from the `Napi::ObjectReference` class (for more info see: [`Napi::ObjectReference`](object_reference.md)). 9 | 10 | If C++ exceptions are enabled (for more info see: [Setup](setup.md)), then the 11 | `Napi::Error` class extends `std::exception` and enables integrated 12 | error-handling for C++ exceptions and JavaScript exceptions. 13 | 14 | For more details about error handling refer to the section titled [Error handling](error_handling.md). 15 | 16 | ## Methods 17 | 18 | ### New 19 | 20 | Creates empty instance of an `Napi::Error` object for the specified environment. 21 | 22 | ```cpp 23 | Napi::Error::New(Napi::Env env); 24 | ``` 25 | 26 | - `[in] env`: The environment in which to construct the `Napi::Error` object. 27 | 28 | Returns an instance of `Napi::Error` object. 29 | 30 | ### New 31 | 32 | Creates instance of an `Napi::Error` object. 33 | 34 | ```cpp 35 | Napi::Error::New(Napi::Env env, const char* message); 36 | ``` 37 | 38 | - `[in] env`: The environment in which to construct the `Napi::Error` object. 39 | - `[in] message`: Null-terminated string to be used as the message for the `Napi::Error`. 40 | 41 | Returns instance of an `Napi::Error` object. 42 | 43 | ### New 44 | 45 | Creates instance of an `Napi::Error` object 46 | 47 | ```cpp 48 | Napi::Error::New(Napi::Env env, const std::string& message); 49 | ``` 50 | 51 | - `[in] env`: The environment in which to construct the `Napi::Error` object. 52 | - `[in] message`: Reference string to be used as the message for the `Napi::Error`. 53 | 54 | Returns instance of an `Napi::Error` object. 55 | 56 | ### Fatal 57 | 58 | In case of an unrecoverable error in a native module, a fatal error can be thrown 59 | to immediately terminate the process. 60 | 61 | ```cpp 62 | static NAPI_NO_RETURN void Napi::Error::Fatal(const char* location, const char* message); 63 | ``` 64 | 65 | The function call does not return, the process will be terminated. 66 | 67 | ### Constructor 68 | 69 | Creates empty instance of an `Napi::Error`. 70 | 71 | ```cpp 72 | Napi::Error::Error(); 73 | ``` 74 | 75 | Returns an instance of `Napi::Error` object. 76 | 77 | ### Constructor 78 | 79 | Initializes an `Napi::Error` instance from an existing JavaScript error object. 80 | 81 | ```cpp 82 | Napi::Error::Error(napi_env env, napi_value value); 83 | ``` 84 | 85 | - `[in] env`: The environment in which to construct the error object. 86 | - `[in] value`: The `Napi::Error` reference to wrap. 87 | 88 | Returns instance of an `Napi::Error` object. 89 | 90 | ### Message 91 | 92 | ```cpp 93 | std::string& Napi::Error::Message() const NAPI_NOEXCEPT; 94 | ``` 95 | 96 | Returns the reference to the string that represent the message of the error. 97 | 98 | ### ThrowAsJavaScriptException 99 | 100 | Throw the error as JavaScript exception. 101 | 102 | ```cpp 103 | void Napi::Error::ThrowAsJavaScriptException() const; 104 | ``` 105 | 106 | Throws the error as a JavaScript exception. 107 | 108 | ### what 109 | 110 | ```cpp 111 | const char* Napi::Error::what() const NAPI_NOEXCEPT override; 112 | ``` 113 | 114 | Returns a pointer to a null-terminated string that is used to identify the 115 | exception. This method can be used only if the exception mechanism is enabled. 116 | -------------------------------------------------------------------------------- /deps/node-addon-api/doc/escapable_handle_scope.md: -------------------------------------------------------------------------------- 1 | # EscapableHandleScope 2 | 3 | The `Napi::EscapableHandleScope` class is used to manage the lifetime of object handles 4 | which are created through the use of node-addon-api. These handles 5 | keep an object alive in the heap in order to ensure that the objects 6 | are not collected by the garbage collector while native code is using them. 7 | A handle may be created when any new node-addon-api Value or one 8 | of its subclasses is created or returned. 9 | 10 | The `Napi::EscapableHandleScope` is a special type of `Napi::HandleScope` 11 | which allows a single handle to be "promoted" to an outer scope. 12 | 13 | For more details refer to the section titled 14 | [Object lifetime management](object_lifetime_management.md). 15 | 16 | ## Methods 17 | 18 | ### Constructor 19 | 20 | Creates a new escapable handle scope. 21 | 22 | ```cpp 23 | Napi::EscapableHandleScope Napi::EscapableHandleScope::New(Napi:Env env); 24 | ``` 25 | 26 | - `[in] Env`: The environment in which to construct the `Napi::EscapableHandleScope` object. 27 | 28 | Returns a new `Napi::EscapableHandleScope` 29 | 30 | ### Constructor 31 | 32 | Creates a new escapable handle scope. 33 | 34 | ```cpp 35 | Napi::EscapableHandleScope Napi::EscapableHandleScope::New(napi_env env, napi_handle_scope scope); 36 | ``` 37 | 38 | - `[in] env`: napi_env in which the scope passed in was created. 39 | - `[in] scope`: pre-existing napi_handle_scope. 40 | 41 | Returns a new `Napi::EscapableHandleScope` instance which wraps the 42 | napi_escapable_handle_scope handle passed in. This can be used 43 | to mix usage of the C N-API and node-addon-api. 44 | 45 | operator EscapableHandleScope::napi_escapable_handle_scope 46 | 47 | ```cpp 48 | operator Napi::EscapableHandleScope::napi_escapable_handle_scope() const 49 | ``` 50 | 51 | Returns the N-API napi_escapable_handle_scope wrapped by the `Napi::EscapableHandleScope` object. 52 | This can be used to mix usage of the C N-API and node-addon-api by allowing 53 | the class to be used be converted to a napi_escapable_handle_scope. 54 | 55 | ### Destructor 56 | ```cpp 57 | Napi::EscapableHandleScope::~EscapableHandleScope(); 58 | ``` 59 | 60 | Deletes the `Napi::EscapableHandleScope` instance and allows any objects/handles created 61 | in the scope to be collected by the garbage collector. There is no 62 | guarantee as to when the gargbage collector will do this. 63 | 64 | ### Escape 65 | 66 | ```cpp 67 | napi::Value Napi::EscapableHandleScope::Escape(napi_value escapee); 68 | ``` 69 | 70 | - `[in] escapee`: Napi::Value or napi_env to promote to the outer scope 71 | 72 | Returns `Napi::Value` which can be used in the outer scope. This method can 73 | be called at most once on a given `Napi::EscapableHandleScope`. If it is called 74 | more than once an exception will be thrown. 75 | 76 | ### Env 77 | 78 | ```cpp 79 | Napi::Env Napi::EscapableHandleScope::Env() const; 80 | ``` 81 | 82 | Returns the `Napi::Env` associated with the `Napi::EscapableHandleScope`. 83 | -------------------------------------------------------------------------------- /deps/node-addon-api/doc/external.md: -------------------------------------------------------------------------------- 1 | # External (template) 2 | 3 | The `Napi::External` template class implements the ability to create a `Napi::Value` object with arbitrary C++ data. It is the user's responsibility to manage the memory for the arbitrary C++ data. 4 | 5 | `Napi::External` objects can be created with an optional Finalizer function and optional Hint value. The Finalizer function, if specified, is called when your `Napi::External` object is released by Node's garbage collector. It gives your code the opportunity to free any dynamically created data. If you specify a Hint value, it is passed to your Finalizer function. 6 | 7 | ## Methods 8 | 9 | ### New 10 | 11 | ```cpp 12 | template 13 | static Napi::External Napi::External::New(napi_env env, T* data); 14 | ``` 15 | 16 | - `[in] env`: The `napi_env` environment in which to construct the `Napi::External` object. 17 | - `[in] data`: The arbitrary C++ data to be held by the `Napi::External` object. 18 | 19 | Returns the created `Napi::External` object. 20 | 21 | ### New 22 | 23 | ```cpp 24 | template 25 | static Napi::External Napi::External::New(napi_env env, 26 | T* data, 27 | Finalizer finalizeCallback); 28 | ``` 29 | 30 | - `[in] env`: The `napi_env` environment in which to construct the `Napi::External` object. 31 | - `[in] data`: The arbitrary C++ data to be held by the `Napi::External` object. 32 | - `[in] finalizeCallback`: A function called when the `Napi::External` object is released by the garbage collector accepting a T* and returning void. 33 | 34 | Returns the created `Napi::External` object. 35 | 36 | ### New 37 | 38 | ```cpp 39 | template 40 | static Napi::External Napi::External::New(napi_env env, 41 | T* data, 42 | Finalizer finalizeCallback, 43 | Hint* finalizeHint); 44 | ``` 45 | 46 | - `[in] env`: The `napi_env` environment in which to construct the `Napi::External` object. 47 | - `[in] data`: The arbitrary C++ data to be held by the `Napi::External` object. 48 | - `[in] finalizeCallback`: A function called when the `Napi::External` object is released by the garbage collector accepting T* and Hint* parameters and returning void. 49 | - `[in] finalizeHint`: A hint value passed to the `finalizeCallback` function. 50 | 51 | Returns the created `Napi::External` object. 52 | 53 | ### Data 54 | 55 | ```cpp 56 | T* Napi::External::Data() const; 57 | ``` 58 | 59 | Returns a pointer to the arbitrary C++ data held by the `Napi::External` object. 60 | -------------------------------------------------------------------------------- /deps/node-addon-api/doc/generator.md: -------------------------------------------------------------------------------- 1 | # Generator 2 | 3 | ## What is generator 4 | 5 | **[generator-napi-module](https://www.npmjs.com/package/generator-napi-module)** is a module to quickly generate a skeleton module using 6 | **N-API**, the new API for Native addons. This module automatically sets up your 7 | **gyp file** to use **node-addon-api**, the C++ wrappers for N-API and generates 8 | a wrapper JS module. Optionally, it can even configure the generated project to 9 | use **TypeScript** instead. 10 | 11 | ## **generator-napi-module** reference 12 | 13 | - [Installation and usage](https://www.npmjs.com/package/generator-napi-module#installation) 14 | -------------------------------------------------------------------------------- /deps/node-addon-api/doc/handle_scope.md: -------------------------------------------------------------------------------- 1 | # HandleScope 2 | 3 | The HandleScope class is used to manage the lifetime of object handles 4 | which are created through the use of node-addon-api. These handles 5 | keep an object alive in the heap in order to ensure that the objects 6 | are not collected while native code is using them. 7 | A handle may be created when any new node-addon-api Value or one 8 | of its subclasses is created or returned. For more details refer to 9 | the section titled [Object lifetime management](object_lifetime_management.md). 10 | 11 | ## Methods 12 | 13 | ### Constructor 14 | 15 | Creates a new handle scope on the stack. 16 | 17 | ```cpp 18 | Napi::HandleScope::HandleScope(Napi::Env env); 19 | ``` 20 | 21 | - `[in] env`: The environment in which to construct the `Napi::HandleScope` object. 22 | 23 | Returns a new `Napi::HandleScope` 24 | 25 | ### Constructor 26 | 27 | Creates a new handle scope on the stack. 28 | 29 | ```cpp 30 | Napi::HandleScope::HandleScope(Napi::Env env, Napi::HandleScope scope); 31 | ``` 32 | 33 | - `[in] env`: `Napi::Env` in which the scope passed in was created. 34 | - `[in] scope`: pre-existing `Napi::HandleScope`. 35 | 36 | Returns a new `Napi::HandleScope` instance which wraps the napi_handle_scope 37 | handle passed in. This can be used to mix usage of the C N-API 38 | and node-addon-api. 39 | 40 | operator HandleScope::napi_handle_scope 41 | 42 | ```cpp 43 | operator Napi::HandleScope::napi_handle_scope() const 44 | ``` 45 | 46 | Returns the N-API napi_handle_scope wrapped by the `Napi::EscapableHandleScope` object. 47 | This can be used to mix usage of the C N-API and node-addon-api by allowing 48 | the class to be used be converted to a napi_handle_scope. 49 | 50 | ### Destructor 51 | ```cpp 52 | Napi::HandleScope::~HandleScope(); 53 | ``` 54 | 55 | Deletes the `Napi::HandleScope` instance and allows any objects/handles created 56 | in the scope to be collected by the garbage collector. There is no 57 | guarantee as to when the gargbage collector will do this. 58 | 59 | ### Env 60 | 61 | ```cpp 62 | Napi::Env Napi::HandleScope::Env() const; 63 | ``` 64 | 65 | Returns the `Napi::Env` associated with the `Napi::HandleScope`. 66 | -------------------------------------------------------------------------------- /deps/node-addon-api/doc/memory_management.md: -------------------------------------------------------------------------------- 1 | # MemoryManagement 2 | 3 | The `Napi::MemoryManagement` class contains functions that give the JavaScript engine 4 | an indication of the amount of externally allocated memory that is kept alive by 5 | JavaScript objects. 6 | 7 | ## Methods 8 | 9 | ### AdjustExternalMemory 10 | 11 | The function `AdjustExternalMemory` adjusts the amount of registered external 12 | memory used to give the JavaScript engine an indication of the amount of externally 13 | allocated memory that is kept alive by JavaScript objects. 14 | The JavaScript engine uses this to decide when to perform global garbage collections. 15 | Registering externally allocated memory will trigger global garbage collections 16 | more often than it would otherwise in an attempt to garbage collect the JavaScript 17 | objects that keep the externally allocated memory alive. 18 | 19 | ```cpp 20 | static int64_t Napi::MemoryManagement::AdjustExternalMemory(Napi::Env env, int64_t change_in_bytes); 21 | ``` 22 | 23 | - `[in] env`: The environment in which the API is invoked under. 24 | - `[in] change_in_bytes`: The change in externally allocated memory that is kept 25 | alive by JavaScript objects expressed in bytes. 26 | 27 | Returns the adjusted memory value. 28 | -------------------------------------------------------------------------------- /deps/node-addon-api/doc/node-gyp.md: -------------------------------------------------------------------------------- 1 | # node-gyp 2 | 3 | C++ code needs to be compiled into executable form whether it be as an object 4 | file to linked with others, a shared library, or a standalone executable. 5 | 6 | The main reason for this is that we need to link to the Node.js dependencies and 7 | headers correctly, another reason is that we need a cross platform way to build 8 | C++ source into binary for the target platform. 9 | 10 | Until now **node-gyp** is the **de-facto** standard build tool for writing 11 | Node.js addons. It's based on Google's **gyp** build tool, which abstract away 12 | many of the tedious issues related to cross platform building. 13 | 14 | **node-gyp** uses a file called ```binding.gyp``` that is located on the root of 15 | your addon project. 16 | 17 | ```binding.gyp``` file, contains all building configurations organized with a 18 | JSON like syntax. The most important parameter is the **target** that must be 19 | set to the same value used on the initialization code of the addon as in the 20 | examples reported below: 21 | 22 | ### **binding.gyp** 23 | 24 | ```gyp 25 | { 26 | "targets": [ 27 | { 28 | # myModule is the name of your native addon 29 | "target_name": "myModule", 30 | "sources": ["src/my_module.cc", ...], 31 | ... 32 | ] 33 | } 34 | ``` 35 | 36 | ### **my_module.cc** 37 | 38 | ```cpp 39 | #include 40 | 41 | // ... 42 | 43 | /** 44 | * This code is our entry-point. We receive two arguments here, the first is the 45 | * environment that represent an independent instance of the JavaScript runtime, 46 | * the second is exports, the same as module.exports in a .js file. 47 | * You can either add properties to the exports object passed in or create your 48 | * own exports object. In either case you must return the object to be used as 49 | * the exports for the module when you return from the Init function. 50 | */ 51 | Napi::Object Init(Napi::Env env, Napi::Object exports) { 52 | 53 | // ... 54 | 55 | return exports; 56 | } 57 | 58 | /** 59 | * This code defines the entry-point for the Node addon, it tells Node where to go 60 | * once the library has been loaded into active memory. The first argument must 61 | * match the "target" in our *binding.gyp*. Using NODE_GYP_MODULE_NAME ensures 62 | * that the argument will be correct, as long as the module is built with 63 | * node-gyp (which is the usual way of building modules). The second argument 64 | * points to the function to invoke. The function must not be namespaced. 65 | */ 66 | NODE_API_MODULE(NODE_GYP_MODULE_NAME, Init) 67 | ``` 68 | 69 | ## **node-gyp** reference 70 | 71 | - [Installation](https://www.npmjs.com/package/node-gyp#installation) 72 | - [How to use](https://www.npmjs.com/package/node-gyp#how-to-use) 73 | - [The binding.gyp file](https://www.npmjs.com/package/node-gyp#the-bindinggyp-file) 74 | - [Commands](https://www.npmjs.com/package/node-gyp#commands) 75 | - [Command options](https://www.npmjs.com/package/node-gyp#command-options) 76 | - [Configuration](https://www.npmjs.com/package/node-gyp#configuration) 77 | 78 | Sometimes finding the right settings for ```binding.gyp``` is not easy so to 79 | accomplish at most complicated task please refer to: 80 | 81 | - [GYP documentation](https://gyp.gsrc.io/index.md) 82 | - [node-gyp wiki](https://github.com/nodejs/node-gyp/wiki) 83 | -------------------------------------------------------------------------------- /deps/node-addon-api/doc/object_lifetime_management.md: -------------------------------------------------------------------------------- 1 | # Object lifetime management 2 | 3 | A handle may be created when any new node-addon-api Value and 4 | its subclasses is created or returned. 5 | 6 | As the methods and classes within the node-addon-api are used, 7 | handles to objects in the heap for the underlying 8 | VM may be created. A handle may be created when any new 9 | node-addon-api Value or one of its subclasses is created or returned. 10 | These handles must hold the objects 'live' until they are no 11 | longer required by the native code, otherwise the objects could be 12 | collected by the garbage collector before the native code was 13 | finished using them. 14 | 15 | As handles are created they are associated with a 16 | 'scope'. The lifespan for the default scope is tied to the lifespan 17 | of the native method call. The result is that, by default, handles 18 | remain valid and the objects associated with these handles will be 19 | held live for the lifespan of the native method call. 20 | 21 | In many cases, however, it is necessary that the handles remain valid for 22 | either a shorter or longer lifespan than that of the native method. 23 | The sections which follow describe the node-addon-api classes and 24 | methods that than can be used to change the handle lifespan from 25 | the default. 26 | 27 | ## Making handle lifespan shorter than that of the native method 28 | 29 | It is often necessary to make the lifespan of handles shorter than 30 | the lifespan of a native method. For example, consider a native method 31 | that has a loop which creates a number of values and does something 32 | with each of the values, one at a time: 33 | 34 | ```C++ 35 | for (int i = 0; i < LOOP_MAX; i++) { 36 | std::string name = std::string("inner-scope") + std::to_string(i); 37 | Napi::Value newValue = Napi::String::New(info.Env(), name.c_str()); 38 | // do something with newValue 39 | }; 40 | ``` 41 | 42 | This would result in a large number of handles being created, consuming 43 | substantial resources. In addition, even though the native code could only 44 | use the most recently created value, all of the previously created 45 | values would also be kept alive since they all share the same scope. 46 | 47 | To handle this case, node-addon-api provides the ability to establish 48 | a new 'scope' to which newly created handles will be associated. Once those 49 | handles are no longer required, the scope can be deleted and any handles 50 | associated with the scope are invalidated. The `Napi::HandleScope` 51 | and `Napi::EscapableHandleScope` classes are provided by node-addon-api for 52 | creating additional scopes. 53 | 54 | node-addon-api only supports a single nested hierarchy of scopes. There is 55 | only one active scope at any time, and all new handles will be associated 56 | with that scope while it is active. Scopes must be deleted in the reverse 57 | order from which they are opened. In addition, all scopes created within 58 | a native method must be deleted before returning from that method. Since 59 | `Napi::HandleScopes` are typically stack allocated the compiler will take care of 60 | deletion, however, care must be taken to create the scope in the right 61 | place such that you achieve the desired lifetime. 62 | 63 | Taking the earlier example, creating a `Napi::HandleScope` in the innner loop 64 | would ensure that at most a single new value is held alive throughout the 65 | execution of the loop: 66 | 67 | ```C 68 | for (int i = 0; i < LOOP_MAX; i++) { 69 | Napi::HandleScope scope(info.Env()); 70 | std::string name = std::string("inner-scope") + std::to_string(i); 71 | Napi::Value newValue = Napi::String::New(info.Env(), name.c_str()); 72 | // do something with neValue 73 | }; 74 | ``` 75 | 76 | When nesting scopes, there are cases where a handle from an 77 | inner scope needs to live beyond the lifespan of that scope. node-addon-api 78 | provides the `Napi::EscapableHandleScope` with the `Escape` method 79 | in order to support this case. An escapable scope 80 | allows one object to be 'promoted' so that it 'escapes' the 81 | current scope and the lifespan of the handle changes from the current 82 | scope to that of the outer scope. The `Escape` method can only be called 83 | once for a given `Napi::EscapableHandleScope`. 84 | -------------------------------------------------------------------------------- /deps/node-addon-api/doc/object_reference.md: -------------------------------------------------------------------------------- 1 | # Object Reference 2 | 3 | `Napi::ObjectReference` is a subclass of [`Napi::Reference`](reference.md), and is equivalent to an instance of `Napi::Reference`. This means that a `Napi::ObjectReference` holds a [`Napi::Object`](object.md), and a count of the number of references to that Object. When the count is greater than 0, an ObjectReference is not eligible for garbage collection. This ensures that the Object being held as a value of the ObjectReference will remain accessible, even if the original Object no longer is. However, ObjectReference is unique from a Reference since properties can be set and get to the Object itself that can be accessed through the ObjectReference. 4 | 5 | For more general information on references, please consult [`Napi::Reference`](reference.md). 6 | 7 | ## Example 8 | ```cpp 9 | #include 10 | 11 | using namescape Napi; 12 | 13 | void Init(Env env) { 14 | 15 | // Create an empty ObjectReference that has an initial reference count of 2. 16 | ObjectReference obj_ref = Reference::New(Object::New(env), 2); 17 | 18 | // Set a couple of different properties on the reference. 19 | obj_ref.Set("hello", String::New(env, "world")); 20 | obj_ref.Set(42, "The Answer to Life, the Universe, and Everything"); 21 | 22 | // Get the properties using the keys. 23 | Value val1 = obj_ref.Get("hello"); 24 | Value val2 = obj_ref.Get(42); 25 | } 26 | ``` 27 | 28 | ## Methods 29 | 30 | ### Initialization 31 | 32 | ```cpp 33 | static Napi::ObjectReference Napi::ObjectReference::New(const Napi::Object& value, uint32_t initialRefcount = 0); 34 | ``` 35 | 36 | * `[in] value`: The `Napi::Object` which is to be referenced. 37 | 38 | * `[in] initialRefcount`: The initial reference count. 39 | 40 | Returns the newly created reference. 41 | 42 | ```cpp 43 | static Napi::ObjectReference Napi::Weak(const Napi::Object& value); 44 | ``` 45 | 46 | Creates a "weak" reference to the value, in that the initial count of number of references is set to 0. 47 | 48 | * `[in] value`: The value which is to be referenced. 49 | 50 | Returns the newly created reference. 51 | 52 | ```cpp 53 | static Napi::ObjectReference Napi::Persistent(const Napi::Object& value); 54 | ``` 55 | 56 | Creates a "persistent" reference to the value, in that the initial count of number of references is set to 1. 57 | 58 | * `[in] value`: The value which is to be referenced. 59 | 60 | Returns the newly created reference. 61 | 62 | ### Empty Constructor 63 | 64 | ```cpp 65 | Napi::ObjectReference::ObjectReference(); 66 | ``` 67 | 68 | Returns a new _empty_ `Napi::ObjectReference` instance. 69 | 70 | ### Constructor 71 | 72 | ```cpp 73 | Napi::ObjectReference::ObjectReference(napi_env env, napi_value value); 74 | ``` 75 | 76 | * `[in] env`: The `napi_env` environment in which to construct the `Napi::ObjectReference` object. 77 | 78 | * `[in] value`: The N-API primitive value to be held by the `Napi::ObjectReference`. 79 | 80 | Returns the newly created reference. 81 | 82 | ### Set 83 | ```cpp 84 | void Napi::ObjectReference::Set(___ key, ___ value); 85 | ``` 86 | 87 | * `[in] key`: The name for the property being assigned. 88 | 89 | * `[in] value`: The value being assigned to the property. 90 | 91 | The `key` can be any of the following types: 92 | - `const char*` 93 | - `const std::string` 94 | - `uint32_t` 95 | 96 | The `value` can be any of the following types: 97 | - `napi_value` 98 | - `Napi::Value` 99 | - `const char*` 100 | - `bool` 101 | - `double` 102 | 103 | ### Get 104 | 105 | ```cpp 106 | Napi::Value Napi::ObjectReference::Get(___ key); 107 | ``` 108 | 109 | * `[in] key`: The name of the property to return the value for. 110 | 111 | Returns the [`Napi::Value`](value.md) associated with the key property. Returns NULL if no such key exists. 112 | 113 | The `key` can be any of the following types: 114 | - `const char*` 115 | - `const std::string` 116 | - `uint32_t` 117 | 118 | -------------------------------------------------------------------------------- /deps/node-addon-api/doc/prebuild_tools.md: -------------------------------------------------------------------------------- 1 | # Prebuild tools 2 | 3 | The distribution of a native add-on is just as important as its implementation. 4 | In order to install a native add-on it's important to have all the necessary 5 | dependencies installed and well configured (see the [setup](doc/setum.md) section). 6 | The end-user will need to compile the add-on when they will do an `npm install` 7 | and in some cases this could create problems. To avoid the compilation process it's 8 | possible to ditribute the native add-on in pre-built form for different platform 9 | and architectures. The prebuild tools help to create and distrubute the pre-built 10 | form of a native add-on. 11 | 12 | The following list report two of the tools that are compatible with **N-API**: 13 | 14 | - **[node-pre-gyp](https://www.npmjs.com/package/node-pre-gyp)** 15 | - **[prebuild](https://www.npmjs.com/package/prebuild)** 16 | - **[prebuildify](https://www.npmjs.com/package/prebuildify)** 17 | -------------------------------------------------------------------------------- /deps/node-addon-api/doc/promises.md: -------------------------------------------------------------------------------- 1 | # Promise 2 | 3 | The `Napi::Promise` class, along with its `Napi::Promise::Deferred` class, implement the ability to create, resolve, and reject Promise objects. 4 | 5 | The basic approach is to create a `Napi::Promise::Deferred` object and return to your caller the value returned by the `Napi::Promise::Deferred::Promise` method. For example: 6 | 7 | ```cpp 8 | Napi::Value YourFunction(const Napi::CallbackInfo& info) { 9 | // your code goes here... 10 | Napi::Promise::Deferred deferred = Napi::Promise::Deferred::New(info.Env()); 11 | // deferred needs to survive this call... 12 | return deferred.Promise(); 13 | } 14 | ``` 15 | 16 | Later, when the asynchronous process completes, call either the `Resolve` or `Reject` method on the `Napi::Promise::Deferred` object created earlier: 17 | 18 | ```cpp 19 | deferred.Resolve(String::New(info.Env(), "OK")); 20 | ``` 21 | 22 | ## Promise::Deferred Methods 23 | 24 | ### Factory Method 25 | 26 | ```cpp 27 | static Napi::Promise::Deferred Napi::Promise::Deferred::New(napi_env env); 28 | ``` 29 | 30 | * `[in] env`: The `napi_env` environment in which to create the `Napi::Promise::Deferred` object. 31 | 32 | ### Constructor 33 | 34 | ```cpp 35 | Napi::Promise::Deferred(napi_env env); 36 | ``` 37 | 38 | * `[in] env`: The `napi_env` environment in which to construct the `Napi::Promise::Deferred` object. 39 | 40 | ### Env 41 | 42 | ```cpp 43 | Napi::Env Napi::Promise::Deferred::Env() const; 44 | ``` 45 | 46 | Returns the Env environment this `Napi::Promise::Deferred` object is associated with. 47 | 48 | ### Promise 49 | 50 | ```cpp 51 | Napi::Promise Napi::Promise::Deferred::Promise() const; 52 | ``` 53 | 54 | Returns the `Napi::Promise` object held by the `Napi::Promise::Deferred` object. 55 | 56 | ### Resolve 57 | 58 | ```cpp 59 | void Napi::Promise::Deferred::Resolve(napi_value value) const; 60 | ``` 61 | 62 | Resolves the `Napi::Promise` object held by the `Napi::Promise::Deferred` object. 63 | 64 | * `[in] value`: The N-API primitive value with which to resolve the `Napi::Promise`. 65 | 66 | ### Reject 67 | 68 | ```cpp 69 | void Napi::Promise::Deferred::Reject(napi_value value) const; 70 | ``` 71 | 72 | Rejects the Promise object held by the `Napi::Promise::Deferred` object. 73 | 74 | * `[in] value`: The N-API primitive value with which to reject the `Napi::Promise`. 75 | -------------------------------------------------------------------------------- /deps/node-addon-api/doc/range_error.md: -------------------------------------------------------------------------------- 1 | # RangeError 2 | 3 | The `Napi::RangeError` class is a representation of the JavaScript `RangeError` that is 4 | thrown when trying to pass a value as an argument to a function that does not allow 5 | a range that includes the value. 6 | 7 | The `Napi::RangeError` class inherits its behaviors from the `Napi::Error` class (for 8 | more info see: [`Napi::Error`](error.md)). 9 | 10 | For more details about error handling refer to the section titled [Error handling](error_handling.md). 11 | 12 | ## Methods 13 | 14 | ### New 15 | 16 | Creates a new instance of a `Napi::RangeError` object. 17 | 18 | ```cpp 19 | Napi::RangeError::New(Napi::Env env, const char* message); 20 | ``` 21 | 22 | - `[in] Env`: The environment in which to construct the `Napi::RangeError` object. 23 | - `[in] message`: Null-terminated string to be used as the message for the `Napi::RangeError`. 24 | 25 | Returns an instance of a `Napi::RangeError` object. 26 | 27 | ### New 28 | 29 | Creates a new instance of a `Napi::RangeError` object. 30 | 31 | ```cpp 32 | Napi::RangeError::New(Napi::Env env, const std::string& message); 33 | ``` 34 | 35 | - `[in] Env`: The environment in which to construct the `Napi::RangeError` object. 36 | - `[in] message`: Reference string to be used as the message for the `Napi::RangeError`. 37 | 38 | Returns an instance of a `Napi::RangeError` object. 39 | 40 | ### Constructor 41 | 42 | Creates a new empty instance of a `Napi::RangeError`. 43 | 44 | ```cpp 45 | Napi::RangeError::RangeError(); 46 | ``` 47 | 48 | ### Constructor 49 | 50 | Initializes a `Napi::RangeError` instance from an existing Javascript error object. 51 | 52 | ```cpp 53 | Napi::RangeError::RangeError(napi_env env, napi_value value); 54 | ``` 55 | 56 | - `[in] Env`: The environment in which to construct the `Napi::RangeError` object. 57 | - `[in] value`: The `Napi::Error` reference to wrap. 58 | 59 | Returns an instance of a `Napi::RangeError` object. 60 | -------------------------------------------------------------------------------- /deps/node-addon-api/doc/reference.md: -------------------------------------------------------------------------------- 1 | # Reference (template) 2 | 3 | Holds a counted reference to a [`Napi::Value`](value.md) object; initially a weak reference unless otherwise specified, may be changed to/from a strong reference by adjusting the refcount. 4 | 5 | The referenced `Napi::Value` is not immediately destroyed when the reference count is zero; it is merely then eligible for garbage-collection if there are no other references to the `Napi::Value`. 6 | 7 | `Napi::Reference` objects allocated in static space, such as a global static instance, must call the `SuppressDestruct` method to prevent its destructor, running at program shutdown time, from attempting to reset the reference when the environment is no longer valid. 8 | 9 | The following classes inherit, either directly or indirectly, from `Napi::Reference`: 10 | 11 | * [`Napi::ObjectWrap`](object_wrap.md) 12 | * [`Napi::ObjectReference`](object_reference.md) 13 | * [`Napi::FunctionReference`](function_reference.md) 14 | 15 | ## Methods 16 | 17 | ### Factory Method 18 | 19 | ```cpp 20 | static Napi::Reference Napi::Reference::New(const T& value, uint32_t initialRefcount = 0); 21 | ``` 22 | 23 | * `[in] value`: The value which is to be referenced. 24 | 25 | * `[in] initialRefcount`: The initial reference count. 26 | 27 | ### Empty Constructor 28 | 29 | ```cpp 30 | Napi::Reference::Reference(); 31 | ``` 32 | 33 | Creates a new _empty_ `Napi::Reference` instance. 34 | 35 | ### Constructor 36 | 37 | ```cpp 38 | Napi::Reference::Reference(napi_env env, napi_value value); 39 | ``` 40 | 41 | * `[in] env`: The `napi_env` environment in which to construct the `Napi::Reference` object. 42 | 43 | * `[in] value`: The N-API primitive value to be held by the `Napi::Reference`. 44 | 45 | ### Env 46 | 47 | ```cpp 48 | Napi::Env Napi::Reference::Env() const; 49 | ``` 50 | 51 | Returns the `Napi::Env` value in which the `Napi::Reference` was instantiated. 52 | 53 | ### IsEmpty 54 | 55 | ```cpp 56 | bool Napi::Reference::IsEmpty() const; 57 | ``` 58 | 59 | Determines whether the value held by the `Napi::Reference` is empty. 60 | 61 | ### Value 62 | 63 | ```cpp 64 | T Napi::Reference::Value() const; 65 | ``` 66 | 67 | Returns the value held by the `Napi::Reference`. 68 | 69 | ### Ref 70 | 71 | ```cpp 72 | uint32_t Napi::Reference::Ref(); 73 | ``` 74 | 75 | Increments the reference count for the `Napi::Reference` and returns the resulting reference count. Throws an error if the increment fails. 76 | 77 | ### Unref 78 | 79 | ```cpp 80 | uint32_t Napi::Reference::Unref(); 81 | ``` 82 | 83 | Decrements the reference count for the `Napi::Reference` and returns the resulting reference count. Throws an error if the decrement fails. 84 | 85 | ### Reset (Empty) 86 | 87 | ```cpp 88 | void Napi::Reference::Reset(); 89 | ``` 90 | 91 | Sets the value held by the `Napi::Reference` to be empty. 92 | 93 | ### Reset 94 | 95 | ```cpp 96 | void Napi::Reference::Reset(const T& value, uint32_t refcount = 0); 97 | ``` 98 | 99 | * `[in] value`: The value which is to be referenced. 100 | 101 | * `[in] initialRefcount`: The initial reference count. 102 | 103 | Sets the value held by the `Napi::Reference`. 104 | 105 | ### SuppressDestruct 106 | 107 | ```cpp 108 | void Napi::Reference::SuppressDestruct(); 109 | ``` 110 | 111 | Call this method on a `Napi::Reference` that is declared as static data to prevent its destructor, running at program shutdown time, from attempting to reset the reference when the environment is no longer valid. 112 | -------------------------------------------------------------------------------- /deps/node-addon-api/doc/setup.md: -------------------------------------------------------------------------------- 1 | # Setup 2 | 3 | ## Prerequisites 4 | 5 | Before starting to use **N-API** you need to assure you have the following 6 | prerequisites: 7 | 8 | * **Node.JS** see: [Installing Node.js](https://nodejs.org/) 9 | 10 | * **Node.js native addon build tool** 11 | 12 | - **[node-gyp](node-gyp.md)** 13 | 14 | ## Installation and usage 15 | 16 | To use **N-API** in a native module: 17 | 18 | 1. Add a dependency on this package to `package.json`: 19 | 20 | ```json 21 | "dependencies": { 22 | "node-addon-api": "*", 23 | } 24 | ``` 25 | 26 | 2. Reference this package's include directory and gyp file in `binding.gyp`: 27 | 28 | ```gyp 29 | 'include_dirs': [" 8 || 19 | (versionArray[0] == 8 && versionArray[1] >= 6) || 20 | (versionArray[0] == 6 && versionArray[1] >= 15) || 21 | (versionArray[0] == 6 && versionArray[1] >= 14 && versionArray[2] >= 2)); 22 | 23 | // The flag is not needed when the Node version is not 8, nor if the API is 24 | // built-in, because we removed the flag at the same time as creating the final 25 | // incarnation of the built-in API. 26 | var needsFlag = (!isNodeApiBuiltin && versionArray[0] == 8); 27 | 28 | var include = [__dirname]; 29 | var gyp = path.join(__dirname, 'src', 'node_api.gyp'); 30 | 31 | if (isNodeApiBuiltin) { 32 | gyp += ':nothing'; 33 | } else { 34 | gyp += ':node-api'; 35 | include.unshift(path.join(__dirname, 'external-napi')); 36 | } 37 | 38 | module.exports = { 39 | include: include.map(function(item) { 40 | return '"' + item + '"'; 41 | }).join(' '), 42 | gyp: gyp, 43 | isNodeApiBuiltin: isNodeApiBuiltin, 44 | needsFlag: needsFlag 45 | }; 46 | -------------------------------------------------------------------------------- /deps/node-addon-api/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "bugs": { 3 | "url": "https://github.com/nodejs/node-addon-api/issues" 4 | }, 5 | "contributors": [ 6 | "Abhishek Kumar Singh (https://github.com/abhi11210646)", 7 | "Andrew Petersen (https://github.com/kirbysayshi)", 8 | "Anisha Rohra (https://github.com/anisha-rohra)", 9 | "Anna Henningsen (https://github.com/addaleax)", 10 | "Arnaud Botella (https://github.com/BotellaA)", 11 | "Arunesh Chandra (https://github.com/aruneshchandra)", 12 | "Ben Berman (https://github.com/rivertam)", 13 | "Benjamin Byholm (https://github.com/kkoopa)", 14 | "Bill Gallafent (https://github.com/gallafent)", 15 | "Bruce A. MacNaughton (https://github.com/bmacnaughton)", 16 | "Cory Mickelson (https://github.com/corymickelson)", 17 | "David Halls (https://github.com/davedoesdev)", 18 | "Dongjin Na (https://github.com/nadongguri)", 19 | "Eric Bickle (https://github.com/ebickle)", 20 | "Gabriel Schulhof (https://github.com/gabrielschulhof)", 21 | "Gus Caplan (https://github.com/devsnek)", 22 | "Hitesh Kanwathirtha (https://github.com/digitalinfinity)", 23 | "Jake Barnes (https://github.com/DuBistKomisch)", 24 | "Jake Yoon (https://github.com/yjaeseok)", 25 | "Jason Ginchereau (https://github.com/jasongin)", 26 | "Jim Schlight (https://github.com/jschlight)", 27 | "Jinho Bang (https://github.com/romandev)", 28 | "joshgarde (https://github.com/joshgarde)", 29 | "Konstantin Tarkus (https://github.com/koistya)", 30 | "Kyle Farnung (https://github.com/kfarnung)", 31 | "Luciano Martorella (https://github.com/lmartorella)", 32 | "Matteo Collina (https://github.com/mcollina)", 33 | "Michael Dawson (https://github.com/mhdawson)", 34 | "Michele Campus (https://github.com/kYroL01)", 35 | "Mikhail Cheshkov (https://github.com/mcheshkov)", 36 | "Nicola Del Gobbo (https://github.com/NickNaso)", 37 | "Nick Soggin (https://github.com/iSkore)", 38 | "Philipp Renoth (https://github.com/DaAitch)", 39 | "Rolf Timmermans (https://github.com/rolftimmermans)", 40 | "Ryuichi Okumura (https://github.com/okuryu)", 41 | "Sampson Gao (https://github.com/sampsongao)", 42 | "Sam Roberts (https://github.com/sam-github)", 43 | "Taylor Woll (https://github.com/boingoing)", 44 | "Thomas Gentilhomme (https://github.com/fraxken)" 45 | ], 46 | "dependencies": {}, 47 | "description": "Node.js API (N-API)", 48 | "devDependencies": { 49 | "safe-buffer": "^5.1.1" 50 | }, 51 | "directories": {}, 52 | "homepage": "https://github.com/nodejs/node-addon-api", 53 | "keywords": ["n-api", "napi", "addon", "native", "bindings", "c", "c++", "nan", "node-addon-api"], 54 | "license": "MIT", 55 | "main": "index.js", 56 | "name": "node-addon-api", 57 | "optionalDependencies": {}, 58 | "readme": "README.md", 59 | "repository": { 60 | "type": "git", 61 | "url": "git://github.com/nodejs/node-addon-api.git" 62 | }, 63 | "scripts": { 64 | "pretest": "node-gyp rebuild -C test", 65 | "test": "node test", 66 | "predev": "node-gyp rebuild -C test --debug", 67 | "dev": "node test", 68 | "predev:incremental": "node-gyp configure build -C test --debug", 69 | "dev:incremental": "node test", 70 | "doc": "doxygen doc/Doxyfile" 71 | }, 72 | "version": "1.6.3" 73 | } 74 | -------------------------------------------------------------------------------- /deps/node-addon-api/src/.gitignore: -------------------------------------------------------------------------------- 1 | /Debug 2 | /Release 3 | /*.vcxproj* 4 | /*.sln -------------------------------------------------------------------------------- /deps/node-addon-api/src/node_api.gyp: -------------------------------------------------------------------------------- 1 | { 2 | 'targets': [ 3 | { 4 | 'target_name': 'nothing', 5 | 'type': 'static_library', 6 | 'sources': [ 'nothing.c' ] 7 | }, 8 | { 9 | 'target_name': 'node-api', 10 | 'type': 'static_library', 11 | 'sources': [ 12 | 'node_api.cc', 13 | 'node_internals.cc', 14 | ], 15 | 'defines': [ 16 | 'EXTERNAL_NAPI', 17 | ], 18 | 'cflags_cc': ['-fvisibility=hidden'] 19 | } 20 | ] 21 | } 22 | -------------------------------------------------------------------------------- /deps/node-addon-api/src/node_api_types.h: -------------------------------------------------------------------------------- 1 | #ifndef SRC_NODE_API_TYPES_H_ 2 | #define SRC_NODE_API_TYPES_H_ 3 | 4 | #include 5 | #include 6 | 7 | #if !defined __cplusplus || (defined(_MSC_VER) && _MSC_VER < 1900) 8 | typedef uint16_t char16_t; 9 | #endif 10 | 11 | // JSVM API types are all opaque pointers for ABI stability 12 | // typedef undefined structs instead of void* for compile time type safety 13 | typedef struct napi_env__ *napi_env; 14 | typedef struct napi_value__ *napi_value; 15 | typedef struct napi_ref__ *napi_ref; 16 | typedef struct napi_handle_scope__ *napi_handle_scope; 17 | typedef struct napi_escapable_handle_scope__ *napi_escapable_handle_scope; 18 | typedef struct napi_callback_info__ *napi_callback_info; 19 | typedef struct napi_async_context__ *napi_async_context; 20 | typedef struct napi_async_work__ *napi_async_work; 21 | typedef struct napi_deferred__ *napi_deferred; 22 | 23 | typedef enum { 24 | napi_default = 0, 25 | napi_writable = 1 << 0, 26 | napi_enumerable = 1 << 1, 27 | napi_configurable = 1 << 2, 28 | 29 | // Used with napi_define_class to distinguish static properties 30 | // from instance properties. Ignored by napi_define_properties. 31 | napi_static = 1 << 10, 32 | } napi_property_attributes; 33 | 34 | typedef enum { 35 | // ES6 types (corresponds to typeof) 36 | napi_undefined, 37 | napi_null, 38 | napi_boolean, 39 | napi_number, 40 | napi_string, 41 | napi_symbol, 42 | napi_object, 43 | napi_function, 44 | napi_external, 45 | } napi_valuetype; 46 | 47 | typedef enum { 48 | napi_int8_array, 49 | napi_uint8_array, 50 | napi_uint8_clamped_array, 51 | napi_int16_array, 52 | napi_uint16_array, 53 | napi_int32_array, 54 | napi_uint32_array, 55 | napi_float32_array, 56 | napi_float64_array, 57 | } napi_typedarray_type; 58 | 59 | typedef enum { 60 | napi_ok, 61 | napi_invalid_arg, 62 | napi_object_expected, 63 | napi_string_expected, 64 | napi_name_expected, 65 | napi_function_expected, 66 | napi_number_expected, 67 | napi_boolean_expected, 68 | napi_array_expected, 69 | napi_generic_failure, 70 | napi_pending_exception, 71 | napi_cancelled, 72 | napi_escape_called_twice, 73 | napi_handle_scope_mismatch 74 | } napi_status; 75 | 76 | typedef napi_value (*napi_callback)(napi_env env, 77 | napi_callback_info info); 78 | typedef void (*napi_finalize)(napi_env env, 79 | void* finalize_data, 80 | void* finalize_hint); 81 | typedef void (*napi_async_execute_callback)(napi_env env, 82 | void* data); 83 | typedef void (*napi_async_complete_callback)(napi_env env, 84 | napi_status status, 85 | void* data); 86 | 87 | typedef struct { 88 | // One of utf8name or name should be NULL. 89 | const char* utf8name; 90 | napi_value name; 91 | 92 | napi_callback method; 93 | napi_callback getter; 94 | napi_callback setter; 95 | napi_value value; 96 | 97 | napi_property_attributes attributes; 98 | void* data; 99 | } napi_property_descriptor; 100 | 101 | typedef struct { 102 | const char* error_message; 103 | void* engine_reserved; 104 | uint32_t engine_error_code; 105 | napi_status error_code; 106 | } napi_extended_error_info; 107 | 108 | typedef struct { 109 | uint32_t major; 110 | uint32_t minor; 111 | uint32_t patch; 112 | const char* release; 113 | } napi_node_version; 114 | 115 | #endif // SRC_NODE_API_TYPES_H_ 116 | -------------------------------------------------------------------------------- /deps/node-addon-api/src/nothing.c: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yodaos-project/hive/be272ea306d1e0acc7cfea1f7404f8e737fb4399/deps/node-addon-api/src/nothing.c -------------------------------------------------------------------------------- /deps/node-addon-api/src/util-inl.h: -------------------------------------------------------------------------------- 1 | #ifndef SRC_UTIL_INL_H_ 2 | #define SRC_UTIL_INL_H_ 3 | 4 | #include "util.h" 5 | #include "v8.h" 6 | 7 | namespace node { 8 | 9 | inline v8::Local OneByteString(v8::Isolate* isolate, 10 | const char* data, 11 | int length) { 12 | return v8::String::NewFromOneByte(isolate, 13 | reinterpret_cast(data), 14 | v8::NewStringType::kNormal, 15 | length).ToLocalChecked(); 16 | } 17 | 18 | inline v8::Local OneByteString(v8::Isolate* isolate, 19 | const signed char* data, 20 | int length) { 21 | return v8::String::NewFromOneByte(isolate, 22 | reinterpret_cast(data), 23 | v8::NewStringType::kNormal, 24 | length).ToLocalChecked(); 25 | } 26 | 27 | inline v8::Local OneByteString(v8::Isolate* isolate, 28 | const unsigned char* data, 29 | int length) { 30 | return v8::String::NewFromOneByte(isolate, 31 | reinterpret_cast(data), 32 | v8::NewStringType::kNormal, 33 | length).ToLocalChecked(); 34 | } 35 | 36 | } // namespace node 37 | 38 | #endif // SRC_UTIL_INL_H_ 39 | -------------------------------------------------------------------------------- /deps/node-addon-api/src/util.h: -------------------------------------------------------------------------------- 1 | #ifndef SRC_UTIL_H_ 2 | #define SRC_UTIL_H_ 3 | 4 | #define FIXED_ONE_BYTE_STRING(isolate, string) \ 5 | (node::OneByteString((isolate), (string), sizeof(string) - 1)) 6 | 7 | #endif // SRC_UTIL_H_ 8 | -------------------------------------------------------------------------------- /deps/node-addon-api/test/.gitignore: -------------------------------------------------------------------------------- 1 | build/ 2 | src/ 3 | -------------------------------------------------------------------------------- /deps/node-addon-api/test/arraybuffer.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | const buildType = process.config.target_defaults.default_configuration; 3 | const assert = require('assert'); 4 | const testUtil = require('./testUtil'); 5 | 6 | test(require(`./build/${buildType}/binding.node`)); 7 | test(require(`./build/${buildType}/binding_noexcept.node`)); 8 | 9 | function test(binding) { 10 | testUtil.runGCTests([ 11 | 'Internal ArrayBuffer', 12 | () => { 13 | const test = binding.arraybuffer.createBuffer(); 14 | binding.arraybuffer.checkBuffer(test); 15 | assert.ok(test instanceof ArrayBuffer); 16 | 17 | const test2 = test.slice(0); 18 | binding.arraybuffer.checkBuffer(test2); 19 | }, 20 | 21 | 'External ArrayBuffer', 22 | () => { 23 | const test = binding.arraybuffer.createExternalBuffer(); 24 | binding.arraybuffer.checkBuffer(test); 25 | assert.ok(test instanceof ArrayBuffer); 26 | assert.strictEqual(0, binding.arraybuffer.getFinalizeCount()); 27 | }, 28 | () => { 29 | global.gc(); 30 | assert.strictEqual(0, binding.arraybuffer.getFinalizeCount()); 31 | }, 32 | 33 | 'External ArrayBuffer with finalizer', 34 | () => { 35 | const test = binding.arraybuffer.createExternalBufferWithFinalize(); 36 | binding.arraybuffer.checkBuffer(test); 37 | assert.ok(test instanceof ArrayBuffer); 38 | assert.strictEqual(0, binding.arraybuffer.getFinalizeCount()); 39 | }, 40 | () => { 41 | global.gc(); 42 | assert.strictEqual(1, binding.arraybuffer.getFinalizeCount()); 43 | }, 44 | 45 | 'External ArrayBuffer with finalizer hint', 46 | () => { 47 | const test = binding.arraybuffer.createExternalBufferWithFinalizeHint(); 48 | binding.arraybuffer.checkBuffer(test); 49 | assert.ok(test instanceof ArrayBuffer); 50 | assert.strictEqual(0, binding.arraybuffer.getFinalizeCount()); 51 | }, 52 | () => { 53 | global.gc(); 54 | assert.strictEqual(1, binding.arraybuffer.getFinalizeCount()); 55 | }, 56 | 57 | 'ArrayBuffer with constructor', 58 | () => { 59 | assert.strictEqual(true, binding.arraybuffer.checkEmptyBuffer()); 60 | const test = binding.arraybuffer.createBufferWithConstructor(); 61 | binding.arraybuffer.checkBuffer(test); 62 | assert.ok(test instanceof ArrayBuffer); 63 | }, 64 | ]); 65 | } 66 | -------------------------------------------------------------------------------- /deps/node-addon-api/test/asynccontext.cc: -------------------------------------------------------------------------------- 1 | #include "napi.h" 2 | 3 | using namespace Napi; 4 | 5 | namespace { 6 | 7 | static void MakeCallback(const CallbackInfo& info) { 8 | Function callback = info[0].As(); 9 | Object resource = info[1].As(); 10 | AsyncContext context(info.Env(), "async_context_test", resource); 11 | callback.MakeCallback(Object::New(info.Env()), 12 | std::initializer_list{}, context); 13 | } 14 | 15 | } // end anonymous namespace 16 | 17 | Object InitAsyncContext(Env env) { 18 | Object exports = Object::New(env); 19 | exports["makeCallback"] = Function::New(env, MakeCallback); 20 | return exports; 21 | } 22 | -------------------------------------------------------------------------------- /deps/node-addon-api/test/asynccontext.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | const buildType = process.config.target_defaults.default_configuration; 3 | const assert = require('assert'); 4 | const common = require('./common'); 5 | 6 | // we only check async hooks on 8.x an higher were 7 | // they are closer to working properly 8 | const nodeVersion = process.versions.node.split('.')[0] 9 | let async_hooks = undefined; 10 | function checkAsyncHooks() { 11 | if (nodeVersion >= 8) { 12 | if (async_hooks == undefined) { 13 | async_hooks = require('async_hooks'); 14 | } 15 | return true; 16 | } 17 | return false; 18 | } 19 | 20 | test(require(`./build/${buildType}/binding.node`)); 21 | test(require(`./build/${buildType}/binding_noexcept.node`)); 22 | 23 | function installAsyncHooksForTest() { 24 | return new Promise((resolve, reject) => { 25 | let id; 26 | const events = []; 27 | const hook = async_hooks.createHook({ 28 | init(asyncId, type, triggerAsyncId, resource) { 29 | if (id === undefined && type === 'async_context_test') { 30 | id = asyncId; 31 | events.push({ eventName: 'init', type, triggerAsyncId, resource }); 32 | } 33 | }, 34 | before(asyncId) { 35 | if (asyncId === id) { 36 | events.push({ eventName: 'before' }); 37 | } 38 | }, 39 | after(asyncId) { 40 | if (asyncId === id) { 41 | events.push({ eventName: 'after' }); 42 | } 43 | }, 44 | destroy(asyncId) { 45 | if (asyncId === id) { 46 | events.push({ eventName: 'destroy' }); 47 | hook.disable(); 48 | resolve(events); 49 | } 50 | } 51 | }).enable(); 52 | }); 53 | } 54 | 55 | function test(binding) { 56 | binding.asynccontext.makeCallback(common.mustCall(), { foo: 'foo' }); 57 | if (!checkAsyncHooks()) 58 | return; 59 | 60 | const hooks = installAsyncHooksForTest(); 61 | const triggerAsyncId = async_hooks.executionAsyncId(); 62 | hooks.then(actual => { 63 | assert.deepStrictEqual(actual, [ 64 | { eventName: 'init', 65 | type: 'async_context_test', 66 | triggerAsyncId: triggerAsyncId, 67 | resource: { foo: 'foo' } }, 68 | { eventName: 'before' }, 69 | { eventName: 'after' }, 70 | { eventName: 'destroy' } 71 | ]); 72 | }).catch(common.mustNotCall()); 73 | } 74 | -------------------------------------------------------------------------------- /deps/node-addon-api/test/asyncworker-persistent.cc: -------------------------------------------------------------------------------- 1 | #include "napi.h" 2 | 3 | // A variant of TestWorker wherein destruction is suppressed. That is, instances 4 | // are not destroyed during the `OnOK` callback. They must be explicitly 5 | // destroyed. 6 | 7 | using namespace Napi; 8 | 9 | namespace { 10 | 11 | class PersistentTestWorker : public AsyncWorker { 12 | public: 13 | static PersistentTestWorker* current_worker; 14 | static void DoWork(const CallbackInfo& info) { 15 | bool succeed = info[0].As(); 16 | Function cb = info[1].As(); 17 | 18 | PersistentTestWorker* worker = new PersistentTestWorker(cb, "TestResource"); 19 | current_worker = worker; 20 | 21 | worker->SuppressDestruct(); 22 | worker->_succeed = succeed; 23 | worker->Queue(); 24 | } 25 | 26 | static Value GetWorkerGone(const CallbackInfo& info) { 27 | return Boolean::New(info.Env(), current_worker == nullptr); 28 | } 29 | 30 | static void DeleteWorker(const CallbackInfo& info) { 31 | (void) info; 32 | delete current_worker; 33 | } 34 | 35 | ~PersistentTestWorker() { 36 | current_worker = nullptr; 37 | } 38 | 39 | protected: 40 | void Execute() override { 41 | if (!_succeed) { 42 | SetError("test error"); 43 | } 44 | } 45 | 46 | private: 47 | PersistentTestWorker(Function cb, 48 | const char* resource_name) 49 | : AsyncWorker(cb, resource_name) {} 50 | 51 | bool _succeed; 52 | }; 53 | 54 | PersistentTestWorker* PersistentTestWorker::current_worker = nullptr; 55 | 56 | } // end of anonymous namespace 57 | 58 | Object InitPersistentAsyncWorker(Env env) { 59 | Object exports = Object::New(env); 60 | exports["doWork"] = Function::New(env, PersistentTestWorker::DoWork); 61 | exports.DefineProperty( 62 | PropertyDescriptor::Accessor(env, exports, "workerGone", 63 | PersistentTestWorker::GetWorkerGone)); 64 | exports["deleteWorker"] = 65 | Function::New(env, PersistentTestWorker::DeleteWorker); 66 | return exports; 67 | } 68 | -------------------------------------------------------------------------------- /deps/node-addon-api/test/asyncworker-persistent.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | const buildType = process.config.target_defaults.default_configuration; 3 | const assert = require('assert'); 4 | const common = require('./common'); 5 | const binding = require(`./build/${buildType}/binding.node`); 6 | const noexceptBinding = require(`./build/${buildType}/binding_noexcept.node`); 7 | 8 | function test(binding, succeed) { 9 | return new Promise((resolve) => 10 | // Can't pass an arrow function to doWork because that results in an 11 | // undefined context inside its body when the function gets called. 12 | binding.doWork(succeed, function(e) { 13 | setImmediate(() => { 14 | // If the work is supposed to fail, make sure there's an error. 15 | assert.strictEqual(succeed || e.message === 'test error', true); 16 | assert.strictEqual(binding.workerGone, false); 17 | binding.deleteWorker(); 18 | assert.strictEqual(binding.workerGone, true); 19 | resolve(); 20 | }); 21 | })); 22 | } 23 | 24 | test(binding.persistentasyncworker, false) 25 | .then(() => test(binding.persistentasyncworker, true)) 26 | .then(() => test(noexceptBinding.persistentasyncworker, false)) 27 | .then(() => test(noexceptBinding.persistentasyncworker, true)); 28 | -------------------------------------------------------------------------------- /deps/node-addon-api/test/asyncworker.cc: -------------------------------------------------------------------------------- 1 | #include "napi.h" 2 | 3 | using namespace Napi; 4 | 5 | class TestWorker : public AsyncWorker { 6 | public: 7 | static void DoWork(const CallbackInfo& info) { 8 | bool succeed = info[0].As(); 9 | Object resource = info[1].As(); 10 | Function cb = info[2].As(); 11 | Value data = info[3]; 12 | 13 | TestWorker* worker = new TestWorker(cb, "TestResource", resource); 14 | worker->Receiver().Set("data", data); 15 | worker->_succeed = succeed; 16 | worker->Queue(); 17 | } 18 | 19 | protected: 20 | void Execute() override { 21 | if (!_succeed) { 22 | SetError("test error"); 23 | } 24 | } 25 | 26 | private: 27 | TestWorker(Function cb, const char* resource_name, const Object& resource) 28 | : AsyncWorker(cb, resource_name, resource) {} 29 | bool _succeed; 30 | }; 31 | 32 | Object InitAsyncWorker(Env env) { 33 | Object exports = Object::New(env); 34 | exports["doWork"] = Function::New(env, TestWorker::DoWork); 35 | return exports; 36 | } 37 | -------------------------------------------------------------------------------- /deps/node-addon-api/test/asyncworker.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | const buildType = process.config.target_defaults.default_configuration; 3 | const assert = require('assert'); 4 | const common = require('./common'); 5 | 6 | // we only check async hooks on 8.x an higher were 7 | // they are closer to working properly 8 | const nodeVersion = process.versions.node.split('.')[0] 9 | let async_hooks = undefined; 10 | function checkAsyncHooks() { 11 | if (nodeVersion >=8) { 12 | if (async_hooks == undefined) { 13 | async_hooks = require('async_hooks'); 14 | } 15 | return true; 16 | } 17 | return false; 18 | } 19 | 20 | test(require(`./build/${buildType}/binding.node`)); 21 | test(require(`./build/${buildType}/binding_noexcept.node`)); 22 | 23 | function installAsyncHooksForTest() { 24 | return new Promise((resolve, reject) => { 25 | let id; 26 | const events = []; 27 | const hook = async_hooks.createHook({ 28 | init(asyncId, type, triggerAsyncId, resource) { 29 | if (id === undefined && type === 'TestResource') { 30 | id = asyncId; 31 | events.push({ eventName: 'init', type, triggerAsyncId, resource }); 32 | } 33 | }, 34 | before(asyncId) { 35 | if (asyncId === id) { 36 | events.push({ eventName: 'before' }); 37 | } 38 | }, 39 | after(asyncId) { 40 | if (asyncId === id) { 41 | events.push({ eventName: 'after' }); 42 | } 43 | }, 44 | destroy(asyncId) { 45 | if (asyncId === id) { 46 | events.push({ eventName: 'destroy' }); 47 | hook.disable(); 48 | resolve(events); 49 | } 50 | } 51 | }).enable(); 52 | }); 53 | } 54 | 55 | function test(binding) { 56 | if (!checkAsyncHooks()) { 57 | binding.asyncworker.doWork(true, {}, function (e) { 58 | assert.strictEqual(typeof e, 'undefined'); 59 | assert.strictEqual(typeof this, 'object'); 60 | assert.strictEqual(this.data, 'test data'); 61 | }, 'test data'); 62 | 63 | binding.asyncworker.doWork(false, {}, function (e) { 64 | assert.ok(e instanceof Error); 65 | assert.strictEqual(e.message, 'test error'); 66 | assert.strictEqual(typeof this, 'object'); 67 | assert.strictEqual(this.data, 'test data'); 68 | }, 'test data'); 69 | return; 70 | } 71 | 72 | { 73 | const hooks = installAsyncHooksForTest(); 74 | const triggerAsyncId = async_hooks.executionAsyncId(); 75 | binding.asyncworker.doWork(true, { foo: 'foo' }, function (e) { 76 | assert.strictEqual(typeof e, 'undefined'); 77 | assert.strictEqual(typeof this, 'object'); 78 | assert.strictEqual(this.data, 'test data'); 79 | }, 'test data'); 80 | 81 | hooks.then(actual => { 82 | assert.deepStrictEqual(actual, [ 83 | { eventName: 'init', 84 | type: 'TestResource', 85 | triggerAsyncId: triggerAsyncId, 86 | resource: { foo: 'foo' } }, 87 | { eventName: 'before' }, 88 | { eventName: 'after' }, 89 | { eventName: 'destroy' } 90 | ]); 91 | }).catch(common.mustNotCall()); 92 | } 93 | 94 | { 95 | const hooks = installAsyncHooksForTest(); 96 | const triggerAsyncId = async_hooks.executionAsyncId(); 97 | 98 | binding.asyncworker.doWork(false, { foo: 'foo' }, function (e) { 99 | assert.ok(e instanceof Error); 100 | assert.strictEqual(e.message, 'test error'); 101 | assert.strictEqual(typeof this, 'object'); 102 | assert.strictEqual(this.data, 'test data'); 103 | }, 'test data'); 104 | 105 | hooks.then(actual => { 106 | assert.deepStrictEqual(actual, [ 107 | { eventName: 'init', 108 | type: 'TestResource', 109 | triggerAsyncId: triggerAsyncId, 110 | resource: { foo: 'foo' } }, 111 | { eventName: 'before' }, 112 | { eventName: 'after' }, 113 | { eventName: 'destroy' } 114 | ]); 115 | }).catch(common.mustNotCall()); 116 | } 117 | } 118 | -------------------------------------------------------------------------------- /deps/node-addon-api/test/basic_types/array.cc: -------------------------------------------------------------------------------- 1 | #define NAPI_EXPERIMENTAL 2 | #include "napi.h" 3 | 4 | using namespace Napi; 5 | 6 | Value CreateArray(const CallbackInfo& info) { 7 | if (info.Length() > 0) { 8 | size_t length = info[0].As().Uint32Value(); 9 | return Array::New(info.Env(), length); 10 | } else { 11 | return Array::New(info.Env()); 12 | } 13 | } 14 | 15 | Value GetLength(const CallbackInfo& info) { 16 | Array array = info[0].As(); 17 | return Number::New(info.Env(), static_cast(array.Length())); 18 | } 19 | 20 | Value GetElement(const CallbackInfo& info) { 21 | Array array = info[0].As(); 22 | size_t index = info[1].As().Uint32Value(); 23 | return array[index]; 24 | } 25 | 26 | void SetElement(const CallbackInfo& info) { 27 | Array array = info[0].As(); 28 | size_t index = info[1].As().Uint32Value(); 29 | array[index] = info[2].As(); 30 | } 31 | 32 | Object InitBasicTypesArray(Env env) { 33 | Object exports = Object::New(env); 34 | 35 | exports["createArray"] = Function::New(env, CreateArray); 36 | exports["getLength"] = Function::New(env, GetLength); 37 | exports["get"] = Function::New(env, GetElement); 38 | exports["set"] = Function::New(env, SetElement); 39 | 40 | return exports; 41 | } 42 | -------------------------------------------------------------------------------- /deps/node-addon-api/test/basic_types/array.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | const buildType = process.config.target_defaults.default_configuration; 3 | const assert = require('assert'); 4 | 5 | test(require(`../build/${buildType}/binding.node`)); 6 | test(require(`../build/${buildType}/binding_noexcept.node`)); 7 | 8 | function test(binding) { 9 | 10 | // create empty array 11 | const array = binding.basic_types_array.createArray(); 12 | assert.strictEqual(binding.basic_types_array.getLength(array), 0); 13 | 14 | // create array with length 15 | const arrayWithLength = binding.basic_types_array.createArray(10); 16 | assert.strictEqual(binding.basic_types_array.getLength(arrayWithLength), 10); 17 | 18 | // set function test 19 | binding.basic_types_array.set(array, 0, 10); 20 | binding.basic_types_array.set(array, 1, "test"); 21 | binding.basic_types_array.set(array, 2, 3.0); 22 | 23 | // check length after set data 24 | assert.strictEqual(binding.basic_types_array.getLength(array), 3); 25 | 26 | // get function test 27 | assert.strictEqual(binding.basic_types_array.get(array, 0), 10); 28 | assert.strictEqual(binding.basic_types_array.get(array, 1), "test"); 29 | assert.strictEqual(binding.basic_types_array.get(array, 2), 3.0); 30 | 31 | // overwrite test 32 | binding.basic_types_array.set(array, 0, 5); 33 | assert.strictEqual(binding.basic_types_array.get(array, 0), 5); 34 | 35 | // out of index test 36 | assert.strictEqual(binding.basic_types_array.get(array, 5), undefined); 37 | } 38 | -------------------------------------------------------------------------------- /deps/node-addon-api/test/basic_types/boolean.cc: -------------------------------------------------------------------------------- 1 | #include "napi.h" 2 | 3 | using namespace Napi; 4 | 5 | Value CreateBoolean(const CallbackInfo& info) { 6 | return Boolean::New(info.Env(), info[0].As().Value()); 7 | } 8 | 9 | Value CreateEmptyBoolean(const CallbackInfo& info) { 10 | Boolean* boolean = new Boolean(); 11 | return Boolean::New(info.Env(), boolean->IsEmpty()); 12 | } 13 | 14 | Value CreateBooleanFromExistingValue(const CallbackInfo& info) { 15 | Boolean boolean(info.Env(), info[0].As()); 16 | return Boolean::New(info.Env(), boolean.Value()); 17 | } 18 | 19 | Value CreateBooleanFromPrimitive(const CallbackInfo& info) { 20 | bool boolean = info[0].As(); 21 | return Boolean::New(info.Env(), boolean); 22 | } 23 | 24 | Object InitBasicTypesBoolean(Env env) { 25 | Object exports = Object::New(env); 26 | 27 | exports["createBoolean"] = Function::New(env, CreateBoolean); 28 | exports["createEmptyBoolean"] = Function::New(env, CreateEmptyBoolean); 29 | exports["createBooleanFromExistingValue"] = Function::New(env, CreateBooleanFromExistingValue); 30 | exports["createBooleanFromPrimitive"] = Function::New(env, CreateBooleanFromPrimitive); 31 | return exports; 32 | } 33 | -------------------------------------------------------------------------------- /deps/node-addon-api/test/basic_types/boolean.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | const buildType = process.config.target_defaults.default_configuration; 3 | const assert = require('assert'); 4 | 5 | test(require(`../build/${buildType}/binding.node`)); 6 | test(require(`../build/${buildType}/binding_noexcept.node`)); 7 | 8 | function test(binding) { 9 | const bool1 = binding.basic_types_boolean.createBoolean(true); 10 | assert.strictEqual(bool1, true); 11 | 12 | const bool2 = binding.basic_types_boolean.createBoolean(false); 13 | assert.strictEqual(bool2, false); 14 | 15 | const emptyBoolean = binding.basic_types_boolean.createEmptyBoolean(); 16 | assert.strictEqual(emptyBoolean, true); 17 | 18 | const bool3 = binding.basic_types_boolean.createBooleanFromExistingValue(true); 19 | assert.strictEqual(bool3, true); 20 | 21 | const bool4 = binding.basic_types_boolean.createBooleanFromExistingValue(false); 22 | assert.strictEqual(bool4, false); 23 | 24 | const bool5 = binding.basic_types_boolean.createBooleanFromPrimitive(true); 25 | assert.strictEqual(bool5, true); 26 | 27 | const bool6 = binding.basic_types_boolean.createBooleanFromPrimitive(false); 28 | assert.strictEqual(bool6, false); 29 | 30 | } 31 | -------------------------------------------------------------------------------- /deps/node-addon-api/test/basic_types/number.cc: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | #include "napi.h" 4 | 5 | using namespace Napi; 6 | 7 | Value ToInt32(const CallbackInfo& info) { 8 | return Number::New(info.Env(), info[0].As().Int32Value()); 9 | } 10 | 11 | Value ToUint32(const CallbackInfo& info) { 12 | return Number::New(info.Env(), info[0].As().Uint32Value()); 13 | } 14 | 15 | Value ToInt64(const CallbackInfo& info) { 16 | return Number::New(info.Env(), 17 | static_cast(info[0].As().Int64Value())); 18 | } 19 | 20 | Value ToFloat(const CallbackInfo& info) { 21 | return Number::New(info.Env(), info[0].As().FloatValue()); 22 | } 23 | 24 | Value ToDouble(const CallbackInfo& info) { 25 | return Number::New(info.Env(), info[0].As().DoubleValue()); 26 | } 27 | 28 | Value MinFloat(const CallbackInfo& info) { 29 | return Number::New(info.Env(), FLT_MIN); 30 | } 31 | 32 | Value MaxFloat(const CallbackInfo& info) { 33 | return Number::New(info.Env(), FLT_MAX); 34 | } 35 | 36 | Value MinDouble(const CallbackInfo& info) { 37 | return Number::New(info.Env(), DBL_MIN); 38 | } 39 | 40 | Value MaxDouble(const CallbackInfo& info) { 41 | return Number::New(info.Env(), DBL_MAX); 42 | } 43 | 44 | Value OperatorInt32(const CallbackInfo& info) { 45 | Number number = info[0].As(); 46 | return Boolean::New(info.Env(), number.Int32Value() == static_cast(number)); 47 | } 48 | 49 | Value OperatorUint32(const CallbackInfo& info) { 50 | Number number = info[0].As(); 51 | return Boolean::New(info.Env(), number.Uint32Value() == static_cast(number)); 52 | } 53 | 54 | Value OperatorInt64(const CallbackInfo& info) { 55 | Number number = info[0].As(); 56 | return Boolean::New(info.Env(), number.Int64Value() == static_cast(number)); 57 | } 58 | 59 | Value OperatorFloat(const CallbackInfo& info) { 60 | Number number = info[0].As(); 61 | return Boolean::New(info.Env(), number.FloatValue() == static_cast(number)); 62 | } 63 | 64 | Value OperatorDouble(const CallbackInfo& info) { 65 | Number number = info[0].As(); 66 | return Boolean::New(info.Env(), number.DoubleValue() == static_cast(number)); 67 | } 68 | 69 | Value CreateEmptyNumber(const CallbackInfo& info) { 70 | Number number; 71 | return Boolean::New(info.Env(), number.IsEmpty()); 72 | } 73 | 74 | Value CreateNumberFromExistingValue(const CallbackInfo& info) { 75 | return info[0].As(); 76 | } 77 | 78 | Object InitBasicTypesNumber(Env env) { 79 | Object exports = Object::New(env); 80 | 81 | exports["toInt32"] = Function::New(env, ToInt32); 82 | exports["toUint32"] = Function::New(env, ToUint32); 83 | exports["toInt64"] = Function::New(env, ToInt64); 84 | exports["toFloat"] = Function::New(env, ToFloat); 85 | exports["toDouble"] = Function::New(env, ToDouble); 86 | exports["minFloat"] = Function::New(env, MinFloat); 87 | exports["maxFloat"] = Function::New(env, MaxFloat); 88 | exports["minDouble"] = Function::New(env, MinDouble); 89 | exports["maxDouble"] = Function::New(env, MaxDouble); 90 | exports["operatorInt32"] = Function::New(env, OperatorInt32); 91 | exports["operatorUint32"] = Function::New(env, OperatorUint32); 92 | exports["operatorInt64"] = Function::New(env, OperatorInt64); 93 | exports["operatorFloat"] = Function::New(env, OperatorFloat); 94 | exports["operatorDouble"] = Function::New(env, OperatorDouble); 95 | exports["createEmptyNumber"] = Function::New(env, CreateEmptyNumber); 96 | exports["createNumberFromExistingValue"] = Function::New(env, CreateNumberFromExistingValue); 97 | 98 | return exports; 99 | } 100 | -------------------------------------------------------------------------------- /deps/node-addon-api/test/basic_types/value.cc: -------------------------------------------------------------------------------- 1 | #include "napi.h" 2 | 3 | using namespace Napi; 4 | 5 | namespace { 6 | 7 | int testData = 1; 8 | 9 | // Helpers for testing non-Javascript values. 10 | Value CreateExternal(const CallbackInfo& info) { 11 | return External::New(info.Env(), &testData); 12 | } 13 | 14 | } // end anonymous namespace 15 | 16 | static Value IsEmpty(const CallbackInfo& info) { 17 | Value value; 18 | return Boolean::New(info.Env(), value.IsEmpty()); 19 | } 20 | 21 | static Value IsUndefined(const CallbackInfo& info) { 22 | return Boolean::New(info.Env(), info[0].IsUndefined()); 23 | } 24 | 25 | static Value IsNull(const CallbackInfo& info) { 26 | return Boolean::New(info.Env(), info[0].IsNull()); 27 | } 28 | 29 | static Value IsBoolean(const CallbackInfo& info) { 30 | return Boolean::New(info.Env(), info[0].IsBoolean()); 31 | } 32 | 33 | static Value IsNumber(const CallbackInfo& info) { 34 | return Boolean::New(info.Env(), info[0].IsNumber()); 35 | } 36 | 37 | static Value IsString(const CallbackInfo& info) { 38 | return Boolean::New(info.Env(), info[0].IsString()); 39 | } 40 | 41 | static Value IsSymbol(const CallbackInfo& info) { 42 | return Boolean::New(info.Env(), info[0].IsSymbol()); 43 | } 44 | 45 | static Value IsArray(const CallbackInfo& info) { 46 | return Boolean::New(info.Env(), info[0].IsArray()); 47 | } 48 | 49 | static Value IsArrayBuffer(const CallbackInfo& info) { 50 | return Boolean::New(info.Env(), info[0].IsArrayBuffer()); 51 | } 52 | 53 | static Value IsTypedArray(const CallbackInfo& info) { 54 | return Boolean::New(info.Env(), info[0].IsTypedArray()); 55 | } 56 | 57 | static Value IsObject(const CallbackInfo& info) { 58 | return Boolean::New(info.Env(), info[0].IsObject()); 59 | } 60 | 61 | static Value IsFunction(const CallbackInfo& info) { 62 | return Boolean::New(info.Env(), info[0].IsFunction()); 63 | } 64 | 65 | static Value IsPromise(const CallbackInfo& info) { 66 | return Boolean::New(info.Env(), info[0].IsPromise()); 67 | } 68 | 69 | static Value IsDataView(const CallbackInfo& info) { 70 | return Boolean::New(info.Env(), info[0].IsDataView()); 71 | } 72 | 73 | static Value IsExternal(const CallbackInfo& info) { 74 | return Boolean::New(info.Env(), info[0].IsExternal()); 75 | } 76 | 77 | static Value ToBoolean(const CallbackInfo& info) { 78 | return info[0].ToBoolean(); 79 | } 80 | 81 | static Value ToNumber(const CallbackInfo& info) { 82 | return info[0].ToNumber(); 83 | } 84 | 85 | static Value ToString(const CallbackInfo& info) { 86 | return info[0].ToString(); 87 | } 88 | 89 | static Value ToObject(const CallbackInfo& info) { 90 | return info[0].ToObject(); 91 | } 92 | 93 | Object InitBasicTypesValue(Env env) { 94 | Object exports = Object::New(env); 95 | 96 | exports["isEmpty"] = Function::New(env, IsEmpty); 97 | exports["isUndefined"] = Function::New(env, IsUndefined); 98 | exports["isNull"] = Function::New(env, IsNull); 99 | exports["isBoolean"] = Function::New(env, IsBoolean); 100 | exports["isNumber"] = Function::New(env, IsNumber); 101 | exports["isString"] = Function::New(env, IsString); 102 | exports["isSymbol"] = Function::New(env, IsSymbol); 103 | exports["isArray"] = Function::New(env, IsArray); 104 | exports["isArrayBuffer"] = Function::New(env, IsArrayBuffer); 105 | exports["isTypedArray"] = Function::New(env, IsTypedArray); 106 | exports["isObject"] = Function::New(env, IsObject); 107 | exports["isFunction"] = Function::New(env, IsFunction); 108 | exports["isPromise"] = Function::New(env, IsPromise); 109 | exports["isDataView"] = Function::New(env, IsDataView); 110 | exports["isExternal"] = Function::New(env, IsExternal); 111 | exports["toBoolean"] = Function::New(env, ToBoolean); 112 | exports["toNumber"] = Function::New(env, ToNumber); 113 | exports["toString"] = Function::New(env, ToString); 114 | exports["toObject"] = Function::New(env, ToObject); 115 | 116 | exports["createExternal"] = Function::New(env, CreateExternal); 117 | 118 | return exports; 119 | } 120 | -------------------------------------------------------------------------------- /deps/node-addon-api/test/basic_types/value.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | const buildType = process.config.target_defaults.default_configuration; 4 | const assert = require('assert'); 5 | 6 | test(require(`../build/${buildType}/binding.node`)); 7 | test(require(`../build/${buildType}/binding_noexcept.node`)); 8 | 9 | function test(binding) { 10 | const externalValue = binding.basic_types_value.createExternal(); 11 | 12 | function isObject(value) { 13 | return (typeof value === 'object' && value !== externalValue) || 14 | (typeof value === 'function'); 15 | } 16 | 17 | function detailedTypeOf(value) { 18 | const type = typeof value; 19 | if (type !== 'object') 20 | return type; 21 | 22 | if (value === null) 23 | return 'null'; 24 | 25 | if (Array.isArray(value)) 26 | return 'array'; 27 | 28 | if (value === externalValue) 29 | return 'external'; 30 | 31 | if (!value.constructor) 32 | return type; 33 | 34 | if (value instanceof ArrayBuffer) 35 | return 'arraybuffer'; 36 | 37 | if (ArrayBuffer.isView(value)) { 38 | if (value instanceof DataView) { 39 | return 'dataview'; 40 | } else { 41 | return 'typedarray'; 42 | } 43 | } 44 | 45 | if (value instanceof Promise) 46 | return 'promise'; 47 | 48 | return 'object'; 49 | } 50 | 51 | function typeCheckerTest(typeChecker, expectedType) { 52 | const testValueList = [ 53 | undefined, 54 | null, 55 | true, 56 | 10, 57 | 'string', 58 | Symbol('symbol'), 59 | [], 60 | new ArrayBuffer(10), 61 | new Int32Array(new ArrayBuffer(12)), 62 | {}, 63 | function() {}, 64 | new Promise((resolve, reject) => {}), 65 | new DataView(new ArrayBuffer(12)), 66 | externalValue 67 | ]; 68 | 69 | testValueList.forEach((testValue) => { 70 | if (testValue !== null && expectedType === 'object') { 71 | assert.strictEqual(typeChecker(testValue), isObject(testValue)); 72 | } else { 73 | assert.strictEqual(typeChecker(testValue), detailedTypeOf(testValue) === expectedType); 74 | } 75 | }); 76 | } 77 | 78 | function typeConverterTest(typeConverter, expectedType) { 79 | const testValueList = [ 80 | true, 81 | false, 82 | 0, 83 | 10, 84 | 'string', 85 | [], 86 | new ArrayBuffer(10), 87 | new Int32Array(new ArrayBuffer(12)), 88 | {}, 89 | function() {}, 90 | new Promise((resolve, reject) => {}) 91 | ]; 92 | 93 | testValueList.forEach((testValue) => { 94 | const expected = expectedType(testValue); 95 | const actual = typeConverter(testValue); 96 | 97 | if (isNaN(expected)) { 98 | assert(isNaN(actual)); 99 | } else { 100 | assert.deepStrictEqual(typeConverter(testValue), expectedType(testValue)); 101 | } 102 | }); 103 | } 104 | 105 | const value = binding.basic_types_value; 106 | 107 | typeCheckerTest(value.isUndefined, 'undefined'); 108 | typeCheckerTest(value.isNull, 'null'); 109 | typeCheckerTest(value.isBoolean, 'boolean'); 110 | typeCheckerTest(value.isNumber, 'number'); 111 | typeCheckerTest(value.isString, 'string'); 112 | typeCheckerTest(value.isSymbol, 'symbol'); 113 | typeCheckerTest(value.isArray, 'array'); 114 | typeCheckerTest(value.isArrayBuffer, 'arraybuffer'); 115 | typeCheckerTest(value.isTypedArray, 'typedarray'); 116 | typeCheckerTest(value.isObject, 'object'); 117 | typeCheckerTest(value.isFunction, 'function'); 118 | typeCheckerTest(value.isPromise, 'promise'); 119 | typeCheckerTest(value.isDataView, 'dataview'); 120 | typeCheckerTest(value.isExternal, 'external'); 121 | 122 | typeConverterTest(value.toBoolean, Boolean); 123 | assert.strictEqual(value.toBoolean(undefined), false); 124 | assert.strictEqual(value.toBoolean(null), false); 125 | 126 | typeConverterTest(value.toNumber, Number); 127 | assert(isNaN(value.toNumber(undefined))); 128 | assert.strictEqual(value.toNumber(null), 0); 129 | 130 | typeConverterTest(value.toString, String); 131 | assert.strictEqual(value.toString(undefined), 'undefined'); 132 | assert.strictEqual(value.toString(null), 'null'); 133 | 134 | typeConverterTest(value.toObject, Object); 135 | } 136 | -------------------------------------------------------------------------------- /deps/node-addon-api/test/bigint.cc: -------------------------------------------------------------------------------- 1 | #define NAPI_EXPERIMENTAL 2 | #include "napi.h" 3 | 4 | using namespace Napi; 5 | 6 | // currently experimental guard with version of NAPI_VERSION that it is 7 | // released in once it is no longer experimental 8 | #if (NAPI_VERSION > 2147483646) 9 | namespace { 10 | 11 | Value IsLossless(const CallbackInfo& info) { 12 | Env env = info.Env(); 13 | 14 | BigInt big = info[0].As(); 15 | bool is_signed = info[1].ToBoolean().Value(); 16 | 17 | bool lossless; 18 | if (is_signed) { 19 | big.Int64Value(&lossless); 20 | } else { 21 | big.Uint64Value(&lossless); 22 | } 23 | 24 | return Boolean::New(env, lossless); 25 | } 26 | 27 | Value TestInt64(const CallbackInfo& info) { 28 | bool lossless; 29 | int64_t input = info[0].As().Int64Value(&lossless); 30 | 31 | return BigInt::New(info.Env(), input); 32 | } 33 | 34 | Value TestUint64(const CallbackInfo& info) { 35 | bool lossless; 36 | uint64_t input = info[0].As().Uint64Value(&lossless); 37 | 38 | return BigInt::New(info.Env(), input); 39 | } 40 | 41 | Value TestWords(const CallbackInfo& info) { 42 | BigInt big = info[0].As(); 43 | 44 | size_t expected_word_count = big.WordCount(); 45 | 46 | int sign_bit; 47 | size_t word_count = 10; 48 | uint64_t words[10]; 49 | 50 | big.ToWords(&sign_bit, &word_count, words); 51 | 52 | if (word_count != expected_word_count) { 53 | Error::New(info.Env(), "word count did not match").ThrowAsJavaScriptException(); 54 | return BigInt(); 55 | } 56 | 57 | return BigInt::New(info.Env(), sign_bit, word_count, words); 58 | } 59 | 60 | Value TestTooBigBigInt(const CallbackInfo& info) { 61 | int sign_bit = 0; 62 | size_t word_count = SIZE_MAX; 63 | uint64_t words[10]; 64 | 65 | return BigInt::New(info.Env(), sign_bit, word_count, words); 66 | } 67 | 68 | } // anonymous namespace 69 | 70 | Object InitBigInt(Env env) { 71 | Object exports = Object::New(env); 72 | exports["IsLossless"] = Function::New(env, IsLossless); 73 | exports["TestInt64"] = Function::New(env, TestInt64); 74 | exports["TestUint64"] = Function::New(env, TestUint64); 75 | exports["TestWords"] = Function::New(env, TestWords); 76 | exports["TestTooBigBigInt"] = Function::New(env, TestTooBigBigInt); 77 | 78 | return exports; 79 | } 80 | 81 | #endif 82 | -------------------------------------------------------------------------------- /deps/node-addon-api/test/bigint.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | const buildType = process.config.target_defaults.default_configuration; 4 | const assert = require('assert'); 5 | 6 | test(require(`./build/${buildType}/binding.node`)); 7 | test(require(`./build/${buildType}/binding_noexcept.node`)); 8 | 9 | function test(binding) { 10 | const { 11 | TestInt64, 12 | TestUint64, 13 | TestWords, 14 | IsLossless, 15 | TestTooBigBigInt, 16 | } = binding.bigint; 17 | 18 | [ 19 | 0n, 20 | -0n, 21 | 1n, 22 | -1n, 23 | 100n, 24 | 2121n, 25 | -1233n, 26 | 986583n, 27 | -976675n, 28 | 98765432213456789876546896323445679887645323232436587988766545658n, 29 | -4350987086545760976737453646576078997096876957864353245245769809n, 30 | ].forEach((num) => { 31 | if (num > -(2n ** 63n) && num < 2n ** 63n) { 32 | assert.strictEqual(TestInt64(num), num); 33 | assert.strictEqual(IsLossless(num, true), true); 34 | } else { 35 | assert.strictEqual(IsLossless(num, true), false); 36 | } 37 | 38 | if (num >= 0 && num < 2n ** 64n) { 39 | assert.strictEqual(TestUint64(num), num); 40 | assert.strictEqual(IsLossless(num, false), true); 41 | } else { 42 | assert.strictEqual(IsLossless(num, false), false); 43 | } 44 | 45 | assert.strictEqual(num, TestWords(num)); 46 | }); 47 | 48 | assert.throws(TestTooBigBigInt, { 49 | name: 'RangeError', 50 | message: 'Maximum BigInt size exceeded', 51 | }); 52 | } 53 | -------------------------------------------------------------------------------- /deps/node-addon-api/test/binding.cc: -------------------------------------------------------------------------------- 1 | #define NAPI_EXPERIMENTAL 2 | #include "napi.h" 3 | 4 | using namespace Napi; 5 | 6 | Object InitArrayBuffer(Env env); 7 | Object InitAsyncContext(Env env); 8 | Object InitAsyncWorker(Env env); 9 | Object InitPersistentAsyncWorker(Env env); 10 | Object InitBasicTypesArray(Env env); 11 | Object InitBasicTypesBoolean(Env env); 12 | Object InitBasicTypesNumber(Env env); 13 | Object InitBasicTypesValue(Env env); 14 | // currently experimental guard with version of NAPI_VERSION that it is 15 | // released in once it is no longer experimental 16 | #if (NAPI_VERSION > 2147483646) 17 | Object InitBigInt(Env env); 18 | #endif 19 | Object InitBuffer(Env env); 20 | #if (NAPI_VERSION > 2) 21 | Object InitCallbackScope(Env env); 22 | #endif 23 | Object InitDataView(Env env); 24 | Object InitDataViewReadWrite(Env env); 25 | Object InitError(Env env); 26 | Object InitExternal(Env env); 27 | Object InitFunction(Env env); 28 | Object InitHandleScope(Env env); 29 | Object InitMemoryManagement(Env env); 30 | Object InitName(Env env); 31 | Object InitObject(Env env); 32 | #ifndef NODE_ADDON_API_DISABLE_DEPRECATED 33 | Object InitObjectDeprecated(Env env); 34 | #endif // !NODE_ADDON_API_DISABLE_DEPRECATED 35 | Object InitPromise(Env env); 36 | Object InitTypedArray(Env env); 37 | Object InitObjectWrap(Env env); 38 | Object InitObjectReference(Env env); 39 | Object InitVersionManagement(Env env); 40 | Object InitThunkingManual(Env env); 41 | 42 | Object Init(Env env, Object exports) { 43 | exports.Set("arraybuffer", InitArrayBuffer(env)); 44 | exports.Set("asynccontext", InitAsyncContext(env)); 45 | exports.Set("asyncworker", InitAsyncWorker(env)); 46 | exports.Set("persistentasyncworker", InitPersistentAsyncWorker(env)); 47 | exports.Set("basic_types_array", InitBasicTypesArray(env)); 48 | exports.Set("basic_types_boolean", InitBasicTypesBoolean(env)); 49 | exports.Set("basic_types_number", InitBasicTypesNumber(env)); 50 | exports.Set("basic_types_value", InitBasicTypesValue(env)); 51 | // currently experimental guard with version of NAPI_VERSION that it is 52 | // released in once it is no longer experimental 53 | #if (NAPI_VERSION > 2147483646) 54 | exports.Set("bigint", InitBigInt(env)); 55 | #endif 56 | exports.Set("buffer", InitBuffer(env)); 57 | #if (NAPI_VERSION > 2) 58 | exports.Set("callbackscope", InitCallbackScope(env)); 59 | #endif 60 | exports.Set("dataview", InitDataView(env)); 61 | exports.Set("dataview_read_write", InitDataView(env)); 62 | exports.Set("dataview_read_write", InitDataViewReadWrite(env)); 63 | exports.Set("error", InitError(env)); 64 | exports.Set("external", InitExternal(env)); 65 | exports.Set("function", InitFunction(env)); 66 | exports.Set("name", InitName(env)); 67 | exports.Set("handlescope", InitHandleScope(env)); 68 | exports.Set("memory_management", InitMemoryManagement(env)); 69 | exports.Set("object", InitObject(env)); 70 | #ifndef NODE_ADDON_API_DISABLE_DEPRECATED 71 | exports.Set("object_deprecated", InitObjectDeprecated(env)); 72 | #endif // !NODE_ADDON_API_DISABLE_DEPRECATED 73 | exports.Set("promise", InitPromise(env)); 74 | exports.Set("typedarray", InitTypedArray(env)); 75 | exports.Set("objectwrap", InitObjectWrap(env)); 76 | exports.Set("objectreference", InitObjectReference(env)); 77 | exports.Set("version_management", InitVersionManagement(env)); 78 | exports.Set("thunking_manual", InitThunkingManual(env)); 79 | return exports; 80 | } 81 | 82 | NODE_API_MODULE(addon, Init) 83 | -------------------------------------------------------------------------------- /deps/node-addon-api/test/binding.gyp: -------------------------------------------------------------------------------- 1 | { 2 | 'variables': { 3 | 'NAPI_VERSION%': "", 4 | 'disable_deprecated': " { 14 | const test = binding.buffer.createBuffer(); 15 | binding.buffer.checkBuffer(test); 16 | assert.ok(test instanceof Buffer); 17 | 18 | const test2 = safeBuffer.Buffer.alloc(test.length); 19 | test.copy(test2); 20 | binding.buffer.checkBuffer(test2); 21 | }, 22 | 23 | 'Buffer copy', 24 | () => { 25 | const test = binding.buffer.createBufferCopy(); 26 | binding.buffer.checkBuffer(test); 27 | assert.ok(test instanceof Buffer); 28 | }, 29 | 30 | 'External Buffer', 31 | () => { 32 | const test = binding.buffer.createExternalBuffer(); 33 | binding.buffer.checkBuffer(test); 34 | assert.ok(test instanceof Buffer); 35 | assert.strictEqual(0, binding.buffer.getFinalizeCount()); 36 | }, 37 | () => { 38 | global.gc(); 39 | assert.strictEqual(0, binding.buffer.getFinalizeCount()); 40 | }, 41 | 42 | 'External Buffer with finalizer', 43 | () => { 44 | const test = binding.buffer.createExternalBufferWithFinalize(); 45 | binding.buffer.checkBuffer(test); 46 | assert.ok(test instanceof Buffer); 47 | assert.strictEqual(0, binding.buffer.getFinalizeCount()); 48 | }, 49 | () => { 50 | global.gc(); 51 | assert.strictEqual(1, binding.buffer.getFinalizeCount()); 52 | }, 53 | 54 | 'External Buffer with finalizer hint', 55 | () => { 56 | const test = binding.buffer.createExternalBufferWithFinalizeHint(); 57 | binding.buffer.checkBuffer(test); 58 | assert.ok(test instanceof Buffer); 59 | assert.strictEqual(0, binding.buffer.getFinalizeCount()); 60 | }, 61 | () => { 62 | global.gc(); 63 | assert.strictEqual(1, binding.buffer.getFinalizeCount()); 64 | }, 65 | ]); 66 | } 67 | -------------------------------------------------------------------------------- /deps/node-addon-api/test/callbackscope.cc: -------------------------------------------------------------------------------- 1 | #include "napi.h" 2 | 3 | using namespace Napi; 4 | 5 | #if (NAPI_VERSION > 2) 6 | namespace { 7 | 8 | static void RunInCallbackScope(const CallbackInfo& info) { 9 | Function callback = info[0].As(); 10 | AsyncContext context(info.Env(), "callback_scope_test"); 11 | CallbackScope scope(info.Env(), context); 12 | callback.Call({}); 13 | } 14 | 15 | } // end anonymous namespace 16 | 17 | Object InitCallbackScope(Env env) { 18 | Object exports = Object::New(env); 19 | exports["runInCallbackScope"] = Function::New(env, RunInCallbackScope); 20 | return exports; 21 | } 22 | #endif 23 | -------------------------------------------------------------------------------- /deps/node-addon-api/test/callbackscope.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | const buildType = process.config.target_defaults.default_configuration; 3 | const assert = require('assert'); 4 | const common = require('./common'); 5 | 6 | // we only check async hooks on 8.x an higher were 7 | // they are closer to working properly 8 | const nodeVersion = process.versions.node.split('.')[0] 9 | let async_hooks = undefined; 10 | function checkAsyncHooks() { 11 | if (nodeVersion >= 8) { 12 | if (async_hooks == undefined) { 13 | async_hooks = require('async_hooks'); 14 | } 15 | return true; 16 | } 17 | return false; 18 | } 19 | 20 | test(require(`./build/${buildType}/binding.node`)); 21 | test(require(`./build/${buildType}/binding_noexcept.node`)); 22 | 23 | function test(binding) { 24 | if (!checkAsyncHooks()) 25 | return; 26 | 27 | let id; 28 | let insideHook = false; 29 | async_hooks.createHook({ 30 | init(asyncId, type, triggerAsyncId, resource) { 31 | if (id === undefined && type === 'callback_scope_test') { 32 | id = asyncId; 33 | } 34 | }, 35 | before(asyncId) { 36 | if (asyncId === id) 37 | insideHook = true; 38 | }, 39 | after(asyncId) { 40 | if (asyncId === id) 41 | insideHook = false; 42 | } 43 | }).enable(); 44 | 45 | binding.callbackscope.runInCallbackScope(function() { 46 | assert(insideHook); 47 | }); 48 | } 49 | -------------------------------------------------------------------------------- /deps/node-addon-api/test/common/index.js: -------------------------------------------------------------------------------- 1 | /* Test helpers ported from test/common/index.js in Node.js project. */ 2 | 'use strict'; 3 | const assert = require('assert'); 4 | 5 | const noop = () => {}; 6 | 7 | const mustCallChecks = []; 8 | 9 | function runCallChecks(exitCode) { 10 | if (exitCode !== 0) return; 11 | 12 | const failed = mustCallChecks.filter(function(context) { 13 | if ('minimum' in context) { 14 | context.messageSegment = `at least ${context.minimum}`; 15 | return context.actual < context.minimum; 16 | } else { 17 | context.messageSegment = `exactly ${context.exact}`; 18 | return context.actual !== context.exact; 19 | } 20 | }); 21 | 22 | failed.forEach(function(context) { 23 | console.log('Mismatched %s function calls. Expected %s, actual %d.', 24 | context.name, 25 | context.messageSegment, 26 | context.actual); 27 | console.log(context.stack.split('\n').slice(2).join('\n')); 28 | }); 29 | 30 | if (failed.length) process.exit(1); 31 | } 32 | 33 | exports.mustCall = function(fn, exact) { 34 | return _mustCallInner(fn, exact, 'exact'); 35 | }; 36 | 37 | function _mustCallInner(fn, criteria, field) { 38 | if (typeof fn === 'number') { 39 | criteria = fn; 40 | fn = noop; 41 | } else if (fn === undefined) { 42 | fn = noop; 43 | } 44 | if (criteria === undefined) { 45 | criteria = 1; 46 | } 47 | 48 | if (typeof criteria !== 'number') 49 | throw new TypeError(`Invalid ${field} value: ${criteria}`); 50 | 51 | const context = { 52 | [field]: criteria, 53 | actual: 0, 54 | stack: (new Error()).stack, 55 | name: fn.name || '' 56 | }; 57 | 58 | // add the exit listener only once to avoid listener leak warnings 59 | if (mustCallChecks.length === 0) process.on('exit', runCallChecks); 60 | 61 | mustCallChecks.push(context); 62 | 63 | return function() { 64 | context.actual++; 65 | return fn.apply(this, arguments); 66 | }; 67 | } 68 | 69 | exports.mustNotCall = function(msg) { 70 | return function mustNotCall() { 71 | assert.fail(msg || 'function should not have been called'); 72 | }; 73 | }; 74 | -------------------------------------------------------------------------------- /deps/node-addon-api/test/dataview/dataview.cc: -------------------------------------------------------------------------------- 1 | #include "napi.h" 2 | 3 | using namespace Napi; 4 | 5 | static Value CreateDataView1(const CallbackInfo& info) { 6 | ArrayBuffer arrayBuffer = info[0].As(); 7 | return DataView::New(info.Env(), arrayBuffer); 8 | } 9 | 10 | static Value CreateDataView2(const CallbackInfo& info) { 11 | ArrayBuffer arrayBuffer = info[0].As(); 12 | size_t byteOffset = info[1].As().Uint32Value(); 13 | return DataView::New(info.Env(), arrayBuffer, byteOffset); 14 | } 15 | 16 | static Value CreateDataView3(const CallbackInfo& info) { 17 | ArrayBuffer arrayBuffer = info[0].As(); 18 | size_t byteOffset = info[1].As().Uint32Value(); 19 | size_t byteLength = info[2].As().Uint32Value(); 20 | return DataView::New(info.Env(), arrayBuffer, byteOffset, byteLength); 21 | } 22 | 23 | static Value GetArrayBuffer(const CallbackInfo& info) { 24 | return info[0].As().ArrayBuffer(); 25 | } 26 | 27 | static Value GetByteOffset(const CallbackInfo& info) { 28 | return Number::New(info.Env(), 29 | static_cast(info[0].As().ByteOffset())); 30 | } 31 | 32 | static Value GetByteLength(const CallbackInfo& info) { 33 | return Number::New(info.Env(), 34 | static_cast(info[0].As().ByteLength())); 35 | } 36 | 37 | Object InitDataView(Env env) { 38 | Object exports = Object::New(env); 39 | 40 | exports["createDataView1"] = Function::New(env, CreateDataView1); 41 | exports["createDataView2"] = Function::New(env, CreateDataView2); 42 | exports["createDataView3"] = Function::New(env, CreateDataView3); 43 | exports["getArrayBuffer"] = Function::New(env, GetArrayBuffer); 44 | exports["getByteOffset"] = Function::New(env, GetByteOffset); 45 | exports["getByteLength"] = Function::New(env, GetByteLength); 46 | 47 | return exports; 48 | } 49 | -------------------------------------------------------------------------------- /deps/node-addon-api/test/dataview/dataview.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | const buildType = process.config.target_defaults.default_configuration; 4 | const assert = require('assert'); 5 | 6 | test(require(`../build/${buildType}/binding.node`)); 7 | test(require(`../build/${buildType}/binding_noexcept.node`)); 8 | 9 | function test(binding) { 10 | function testDataViewCreation(factory, arrayBuffer, offset, length) { 11 | const view = factory(arrayBuffer, offset, length); 12 | offset = offset ? offset : 0; 13 | assert.ok(dataview.getArrayBuffer(view) instanceof ArrayBuffer); 14 | assert.strictEqual(dataview.getArrayBuffer(view), arrayBuffer); 15 | assert.strictEqual(dataview.getByteOffset(view), offset); 16 | assert.strictEqual(dataview.getByteLength(view), 17 | length ? length : arrayBuffer.byteLength - offset); 18 | } 19 | 20 | function testInvalidRange(factory, arrayBuffer, offset, length) { 21 | assert.throws(() => { 22 | factory(arrayBuffer, offset, length); 23 | }, RangeError); 24 | } 25 | 26 | const dataview = binding.dataview; 27 | const arrayBuffer = new ArrayBuffer(10); 28 | 29 | testDataViewCreation(dataview.createDataView1, arrayBuffer); 30 | testDataViewCreation(dataview.createDataView2, arrayBuffer, 2); 31 | testDataViewCreation(dataview.createDataView2, arrayBuffer, 10); 32 | testDataViewCreation(dataview.createDataView3, arrayBuffer, 2, 4); 33 | testDataViewCreation(dataview.createDataView3, arrayBuffer, 10, 0); 34 | 35 | testInvalidRange(dataview.createDataView2, arrayBuffer, 11); 36 | testInvalidRange(dataview.createDataView3, arrayBuffer, 11, 0); 37 | testInvalidRange(dataview.createDataView3, arrayBuffer, 6, 5); 38 | } 39 | -------------------------------------------------------------------------------- /deps/node-addon-api/test/dataview/dataview_read_write.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | const buildType = process.config.target_defaults.default_configuration; 4 | const assert = require('assert'); 5 | 6 | test(require(`../build/${buildType}/binding.node`)); 7 | test(require(`../build/${buildType}/binding_noexcept.node`)); 8 | 9 | function test(binding) { 10 | function expected(type, value) { 11 | return eval(`(new ${type}Array([${value}]))[0]`); 12 | } 13 | 14 | function nativeReadDataView(dataview, type, offset, value) { 15 | return eval(`binding.dataview_read_write.get${type}(dataview, offset)`); 16 | } 17 | 18 | function nativeWriteDataView(dataview, type, offset, value) { 19 | eval(`binding.dataview_read_write.set${type}(dataview, offset, value)`); 20 | } 21 | 22 | function isLittleEndian() { 23 | const buffer = new ArrayBuffer(2); 24 | new DataView(buffer).setInt16(0, 256, true /* littleEndian */); 25 | return new Int16Array(buffer)[0] === 256; 26 | } 27 | 28 | function jsReadDataView(dataview, type, offset, value) { 29 | return eval(`dataview.get${type}(offset, isLittleEndian())`); 30 | } 31 | 32 | function jsWriteDataView(dataview, type, offset, value) { 33 | eval(`dataview.set${type}(offset, value, isLittleEndian())`); 34 | } 35 | 36 | function testReadData(dataview, type, offset, value) { 37 | jsWriteDataView(dataview, type, offset, 0); 38 | assert.strictEqual(jsReadDataView(dataview, type, offset), 0); 39 | 40 | jsWriteDataView(dataview, type, offset, value); 41 | assert.strictEqual( 42 | nativeReadDataView(dataview, type, offset), expected(type, value)); 43 | } 44 | 45 | function testWriteData(dataview, type, offset, value) { 46 | jsWriteDataView(dataview, type, offset, 0); 47 | assert.strictEqual(jsReadDataView(dataview, type, offset), 0); 48 | 49 | nativeWriteDataView(dataview, type, offset, value); 50 | assert.strictEqual( 51 | jsReadDataView(dataview, type, offset), expected(type, value)); 52 | } 53 | 54 | function testInvalidOffset(dataview, type, offset, value) { 55 | assert.throws(() => { 56 | nativeReadDataView(dataview, type, offset); 57 | }, RangeError); 58 | 59 | assert.throws(() => { 60 | nativeWriteDataView(dataview, type, offset, value); 61 | }, RangeError); 62 | } 63 | 64 | const dataview = new DataView(new ArrayBuffer(22)); 65 | 66 | testReadData(dataview, 'Float32', 0, 10.2); 67 | testReadData(dataview, 'Float64', 4, 20.3); 68 | testReadData(dataview, 'Int8', 5, 120); 69 | testReadData(dataview, 'Int16', 7, 15000); 70 | testReadData(dataview, 'Int32', 11, 200000); 71 | testReadData(dataview, 'Uint8', 12, 128); 72 | testReadData(dataview, 'Uint16', 14, 32768); 73 | testReadData(dataview, 'Uint32', 18, 1000000); 74 | 75 | testWriteData(dataview, 'Float32', 0, 10.2); 76 | testWriteData(dataview, 'Float64', 4, 20.3); 77 | testWriteData(dataview, 'Int8', 5, 120); 78 | testWriteData(dataview, 'Int16', 7, 15000); 79 | testWriteData(dataview, 'Int32', 11, 200000); 80 | testWriteData(dataview, 'Uint8', 12, 128); 81 | testWriteData(dataview, 'Uint16', 14, 32768); 82 | testWriteData(dataview, 'Uint32', 18, 1000000); 83 | 84 | testInvalidOffset(dataview, 'Float32', 22, 10.2); 85 | testInvalidOffset(dataview, 'Float64', 22, 20.3); 86 | testInvalidOffset(dataview, 'Int8', 22, 120); 87 | testInvalidOffset(dataview, 'Int16', 22, 15000); 88 | testInvalidOffset(dataview, 'Int32', 22, 200000); 89 | testInvalidOffset(dataview, 'Uint8', 22, 128); 90 | testInvalidOffset(dataview, 'Uint16', 22, 32768); 91 | testInvalidOffset(dataview, 'Uint32', 22, 1000000); 92 | } 93 | -------------------------------------------------------------------------------- /deps/node-addon-api/test/error.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | const buildType = process.config.target_defaults.default_configuration; 3 | const assert = require('assert'); 4 | 5 | if (process.argv[2] === 'fatal') { 6 | const binding = require(process.argv[3]); 7 | binding.error.throwFatalError(); 8 | return; 9 | } 10 | 11 | test(`./build/${buildType}/binding.node`); 12 | test(`./build/${buildType}/binding_noexcept.node`); 13 | 14 | function test(bindingPath) { 15 | const binding = require(bindingPath); 16 | 17 | assert.throws(() => binding.error.throwApiError('test'), function(err) { 18 | return err instanceof Error && err.message.includes('Invalid'); 19 | }); 20 | 21 | assert.throws(() => binding.error.throwJSError('test'), function(err) { 22 | return err instanceof Error && err.message === 'test'; 23 | }); 24 | 25 | assert.throws(() => binding.error.throwTypeError('test'), function(err) { 26 | return err instanceof TypeError && err.message === 'test'; 27 | }); 28 | 29 | assert.throws(() => binding.error.throwRangeError('test'), function(err) { 30 | return err instanceof RangeError && err.message === 'test'; 31 | }); 32 | 33 | assert.throws( 34 | () => binding.error.doNotCatch( 35 | () => { 36 | throw new TypeError('test'); 37 | }), 38 | function(err) { 39 | return err instanceof TypeError && err.message === 'test' && !err.caught; 40 | }); 41 | 42 | assert.throws( 43 | () => binding.error.catchAndRethrowError( 44 | () => { 45 | throw new TypeError('test'); 46 | }), 47 | function(err) { 48 | return err instanceof TypeError && err.message === 'test' && err.caught; 49 | }); 50 | 51 | const err = binding.error.catchError( 52 | () => { throw new TypeError('test'); }); 53 | assert(err instanceof TypeError); 54 | assert.strictEqual(err.message, 'test'); 55 | 56 | const msg = binding.error.catchErrorMessage( 57 | () => { throw new TypeError('test'); }); 58 | assert.strictEqual(msg, 'test'); 59 | 60 | assert.throws(() => binding.error.throwErrorThatEscapesScope('test'), function(err) { 61 | return err instanceof Error && err.message === 'test'; 62 | }); 63 | 64 | assert.throws(() => binding.error.catchAndRethrowErrorThatEscapesScope('test'), function(err) { 65 | return err instanceof Error && err.message === 'test' && err.caught; 66 | }); 67 | 68 | const p = require('./napi_child').spawnSync( 69 | process.execPath, [ __filename, 'fatal', bindingPath ]); 70 | assert.ifError(p.error); 71 | assert.ok(p.stderr.toString().includes( 72 | 'FATAL ERROR: Error::ThrowFatalError This is a fatal error')); 73 | } 74 | -------------------------------------------------------------------------------- /deps/node-addon-api/test/external.cc: -------------------------------------------------------------------------------- 1 | #include "napi.h" 2 | 3 | using namespace Napi; 4 | 5 | namespace { 6 | 7 | int testData = 1; 8 | int finalizeCount = 0; 9 | 10 | Value CreateExternal(const CallbackInfo& info) { 11 | finalizeCount = 0; 12 | return External::New(info.Env(), &testData); 13 | } 14 | 15 | Value CreateExternalWithFinalize(const CallbackInfo& info) { 16 | finalizeCount = 0; 17 | return External::New(info.Env(), new int(1), 18 | [](Env /*env*/, int* data) { 19 | delete data; 20 | finalizeCount++; 21 | }); 22 | } 23 | 24 | Value CreateExternalWithFinalizeHint(const CallbackInfo& info) { 25 | finalizeCount = 0; 26 | char* hint = nullptr; 27 | return External::New(info.Env(), new int(1), 28 | [](Env /*env*/, int* data, char* /*hint*/) { 29 | delete data; 30 | finalizeCount++; 31 | }, 32 | hint); 33 | } 34 | 35 | void CheckExternal(const CallbackInfo& info) { 36 | Value arg = info[0]; 37 | if (arg.Type() != napi_external) { 38 | Error::New(info.Env(), "An external argument was expected.").ThrowAsJavaScriptException(); 39 | return; 40 | } 41 | 42 | External external = arg.As>(); 43 | int* externalData = external.Data(); 44 | if (externalData == nullptr || *externalData != 1) { 45 | Error::New(info.Env(), "An external value of 1 was expected.").ThrowAsJavaScriptException(); 46 | return; 47 | } 48 | } 49 | 50 | Value GetFinalizeCount(const CallbackInfo& info) { 51 | return Number::New(info.Env(), finalizeCount); 52 | } 53 | 54 | } // end anonymous namespace 55 | 56 | Object InitExternal(Env env) { 57 | Object exports = Object::New(env); 58 | 59 | exports["createExternal"] = Function::New(env, CreateExternal); 60 | exports["createExternalWithFinalize"] = Function::New(env, CreateExternalWithFinalize); 61 | exports["createExternalWithFinalizeHint"] = Function::New(env, CreateExternalWithFinalizeHint); 62 | exports["checkExternal"] = Function::New(env, CheckExternal); 63 | exports["getFinalizeCount"] = Function::New(env, GetFinalizeCount); 64 | 65 | return exports; 66 | } 67 | -------------------------------------------------------------------------------- /deps/node-addon-api/test/external.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | const buildType = process.config.target_defaults.default_configuration; 3 | const assert = require('assert'); 4 | const testUtil = require('./testUtil'); 5 | 6 | test(require(`./build/${buildType}/binding.node`)); 7 | test(require(`./build/${buildType}/binding_noexcept.node`)); 8 | 9 | function test(binding) { 10 | testUtil.runGCTests([ 11 | 'External without finalizer', 12 | () => { 13 | const test = binding.external.createExternal(); 14 | assert.strictEqual(typeof test, 'object'); 15 | binding.external.checkExternal(test); 16 | assert.strictEqual(0, binding.external.getFinalizeCount()); 17 | }, 18 | () => { 19 | assert.strictEqual(0, binding.external.getFinalizeCount()); 20 | }, 21 | 22 | 'External with finalizer', 23 | () => { 24 | const test = binding.external.createExternalWithFinalize(); 25 | assert.strictEqual(typeof test, 'object'); 26 | binding.external.checkExternal(test); 27 | assert.strictEqual(0, binding.external.getFinalizeCount()); 28 | }, 29 | () => { 30 | assert.strictEqual(1, binding.external.getFinalizeCount()); 31 | }, 32 | 33 | 'External with finalizer hint', 34 | () => { 35 | const test = binding.external.createExternalWithFinalizeHint(); 36 | assert.strictEqual(typeof test, 'object'); 37 | binding.external.checkExternal(test); 38 | assert.strictEqual(0, binding.external.getFinalizeCount()); 39 | }, 40 | () => { 41 | assert.strictEqual(1, binding.external.getFinalizeCount()); 42 | }, 43 | ]); 44 | } 45 | -------------------------------------------------------------------------------- /deps/node-addon-api/test/function.cc: -------------------------------------------------------------------------------- 1 | #include "napi.h" 2 | 3 | using namespace Napi; 4 | 5 | namespace { 6 | 7 | int testData = 1; 8 | 9 | void VoidCallback(const CallbackInfo& info) { 10 | auto env = info.Env(); 11 | Object obj = info[0].As(); 12 | 13 | obj["foo"] = String::New(env, "bar"); 14 | } 15 | 16 | Value ValueCallback(const CallbackInfo& info) { 17 | auto env = info.Env(); 18 | Object obj = Object::New(env); 19 | 20 | obj["foo"] = String::New(env, "bar"); 21 | 22 | return obj; 23 | } 24 | 25 | void VoidCallbackWithData(const CallbackInfo& info) { 26 | auto env = info.Env(); 27 | Object obj = info[0].As(); 28 | 29 | obj["foo"] = String::New(env, "bar"); 30 | 31 | int* data = static_cast(info.Data()); 32 | obj["data"] = Number::New(env, *data); 33 | } 34 | 35 | Value ValueCallbackWithData(const CallbackInfo& info) { 36 | auto env = info.Env(); 37 | Object obj = Object::New(env); 38 | 39 | obj["foo"] = String::New(env, "bar"); 40 | 41 | int* data = static_cast(info.Data()); 42 | obj["data"] = Number::New(env, *data); 43 | 44 | return obj; 45 | } 46 | 47 | Value CallWithArgs(const CallbackInfo& info) { 48 | Function func = info[0].As(); 49 | return func({ info[1], info[2], info[3] }); 50 | } 51 | 52 | Value CallWithVector(const CallbackInfo& info) { 53 | Function func = info[0].As(); 54 | std::vector args; 55 | args.reserve(3); 56 | args.push_back(info[1]); 57 | args.push_back(info[2]); 58 | args.push_back(info[3]); 59 | return func.Call(args); 60 | } 61 | 62 | Value CallWithReceiverAndArgs(const CallbackInfo& info) { 63 | Function func = info[0].As(); 64 | Value receiver = info[1]; 65 | return func.Call(receiver, std::initializer_list{ info[2], info[3], info[4] }); 66 | } 67 | 68 | Value CallWithReceiverAndVector(const CallbackInfo& info) { 69 | Function func = info[0].As(); 70 | Value receiver = info[1]; 71 | std::vector args; 72 | args.reserve(3); 73 | args.push_back(info[2]); 74 | args.push_back(info[3]); 75 | args.push_back(info[4]); 76 | return func.Call(receiver, args); 77 | } 78 | 79 | Value CallWithInvalidReceiver(const CallbackInfo& info) { 80 | Function func = info[0].As(); 81 | return func.Call(Value(), std::initializer_list{}); 82 | } 83 | 84 | Value CallConstructorWithArgs(const CallbackInfo& info) { 85 | Function func = info[0].As(); 86 | return func.New(std::initializer_list{ info[1], info[2], info[3] }); 87 | } 88 | 89 | Value CallConstructorWithVector(const CallbackInfo& info) { 90 | Function func = info[0].As(); 91 | std::vector args; 92 | args.reserve(3); 93 | args.push_back(info[1]); 94 | args.push_back(info[2]); 95 | args.push_back(info[3]); 96 | return func.New(args); 97 | } 98 | 99 | void IsConstructCall(const CallbackInfo& info) { 100 | Function callback = info[0].As(); 101 | bool isConstructCall = info.IsConstructCall(); 102 | callback({Napi::Boolean::New(info.Env(), isConstructCall)}); 103 | } 104 | 105 | } // end anonymous namespace 106 | 107 | Object InitFunction(Env env) { 108 | Object exports = Object::New(env); 109 | exports["voidCallback"] = Function::New(env, VoidCallback, "voidCallback"); 110 | exports["valueCallback"] = Function::New(env, ValueCallback, std::string("valueCallback")); 111 | exports["voidCallbackWithData"] = 112 | Function::New(env, VoidCallbackWithData, nullptr, &testData); 113 | exports["valueCallbackWithData"] = 114 | Function::New(env, ValueCallbackWithData, nullptr, &testData); 115 | exports["callWithArgs"] = Function::New(env, CallWithArgs); 116 | exports["callWithVector"] = Function::New(env, CallWithVector); 117 | exports["callWithReceiverAndArgs"] = Function::New(env, CallWithReceiverAndArgs); 118 | exports["callWithReceiverAndVector"] = Function::New(env, CallWithReceiverAndVector); 119 | exports["callWithInvalidReceiver"] = Function::New(env, CallWithInvalidReceiver); 120 | exports["callConstructorWithArgs"] = Function::New(env, CallConstructorWithArgs); 121 | exports["callConstructorWithVector"] = Function::New(env, CallConstructorWithVector); 122 | exports["isConstructCall"] = Function::New(env, IsConstructCall); 123 | return exports; 124 | } 125 | -------------------------------------------------------------------------------- /deps/node-addon-api/test/function.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | const buildType = process.config.target_defaults.default_configuration; 3 | const assert = require('assert'); 4 | 5 | test(require(`./build/${buildType}/binding.node`)); 6 | test(require(`./build/${buildType}/binding_noexcept.node`)); 7 | 8 | function test(binding) { 9 | let obj = {}; 10 | assert.deepStrictEqual(binding.function.voidCallback(obj), undefined); 11 | assert.deepStrictEqual(obj, { "foo": "bar" }); 12 | 13 | assert.deepStrictEqual(binding.function.valueCallback(), { "foo": "bar" }); 14 | 15 | let args = null; 16 | let ret = null; 17 | let receiver = null; 18 | function testFunction() { 19 | receiver = this; 20 | args = [].slice.call(arguments); 21 | return ret; 22 | } 23 | function testConstructor() { 24 | args = [].slice.call(arguments); 25 | } 26 | 27 | ret = 4; 28 | assert.equal(binding.function.callWithArgs(testFunction, 1, 2, 3), 4); 29 | assert.strictEqual(receiver, undefined); 30 | assert.deepStrictEqual(args, [ 1, 2, 3 ]); 31 | 32 | ret = 5; 33 | assert.equal(binding.function.callWithVector(testFunction, 2, 3, 4), 5); 34 | assert.strictEqual(receiver, undefined); 35 | assert.deepStrictEqual(args, [ 2, 3, 4 ]); 36 | 37 | ret = 6; 38 | assert.equal(binding.function.callWithReceiverAndArgs(testFunction, obj, 3, 4, 5), 6); 39 | assert.deepStrictEqual(receiver, obj); 40 | assert.deepStrictEqual(args, [ 3, 4, 5 ]); 41 | 42 | ret = 7; 43 | assert.equal(binding.function.callWithReceiverAndVector(testFunction, obj, 4, 5, 6), 7); 44 | assert.deepStrictEqual(receiver, obj); 45 | assert.deepStrictEqual(args, [ 4, 5, 6 ]); 46 | 47 | assert.throws(() => { 48 | binding.function.callWithInvalidReceiver(); 49 | }, /Invalid (pointer passed as )?argument/); 50 | 51 | obj = binding.function.callConstructorWithArgs(testConstructor, 5, 6, 7); 52 | assert(obj instanceof testConstructor); 53 | assert.deepStrictEqual(args, [ 5, 6, 7 ]); 54 | 55 | obj = binding.function.callConstructorWithVector(testConstructor, 6, 7, 8); 56 | assert(obj instanceof testConstructor); 57 | assert.deepStrictEqual(args, [ 6, 7, 8 ]); 58 | 59 | obj = {}; 60 | assert.deepStrictEqual(binding.function.voidCallbackWithData(obj), undefined); 61 | assert.deepStrictEqual(obj, { "foo": "bar", "data": 1 }); 62 | 63 | assert.deepStrictEqual(binding.function.valueCallbackWithData(), { "foo": "bar", "data": 1 }); 64 | 65 | assert.equal(binding.function.voidCallback.name, 'voidCallback'); 66 | assert.equal(binding.function.valueCallback.name, 'valueCallback'); 67 | 68 | let testConstructCall = undefined; 69 | binding.function.isConstructCall((result) => { testConstructCall = result; }); 70 | assert.ok(!testConstructCall); 71 | new binding.function.isConstructCall((result) => { testConstructCall = result; }); 72 | assert.ok(testConstructCall); 73 | 74 | // TODO: Function::MakeCallback tests 75 | } 76 | -------------------------------------------------------------------------------- /deps/node-addon-api/test/handlescope.cc: -------------------------------------------------------------------------------- 1 | #include "napi.h" 2 | #include "string.h" 3 | #include 4 | #include 5 | 6 | using namespace Napi; 7 | 8 | Value createScope(const CallbackInfo& info) { 9 | { 10 | HandleScope scope(info.Env()); 11 | String::New(info.Env(), "inner-scope"); 12 | } 13 | return String::New(info.Env(), "scope"); 14 | } 15 | 16 | Value escapeFromScope(const CallbackInfo& info) { 17 | Value result; 18 | { 19 | EscapableHandleScope scope(info.Env()); 20 | result = scope.Escape(String::New(info.Env(), "inner-scope")); 21 | } 22 | return result; 23 | } 24 | 25 | #define LOOP_MAX 1000000 26 | Value stressEscapeFromScope(const CallbackInfo& info) { 27 | Value result; 28 | for (int i = 0; i < LOOP_MAX; i++) { 29 | EscapableHandleScope scope(info.Env()); 30 | char buffer[128]; 31 | snprintf(buffer, 128, "%d", i); 32 | std::string name = std::string("inner-scope") + std::string(buffer); 33 | Value newValue = String::New(info.Env(), name.c_str()); 34 | if (i == (LOOP_MAX -1)) { 35 | result = scope.Escape(newValue); 36 | } 37 | } 38 | return result; 39 | } 40 | 41 | Value doubleEscapeFromScope(const CallbackInfo& info) { 42 | Value result; 43 | { 44 | EscapableHandleScope scope(info.Env()); 45 | result = scope.Escape(String::New(info.Env(), "inner-scope")); 46 | result = scope.Escape(String::New(info.Env(), "inner-scope")); 47 | } 48 | return result; 49 | } 50 | 51 | Object InitHandleScope(Env env) { 52 | Object exports = Object::New(env); 53 | 54 | exports["createScope"] = Function::New(env, createScope); 55 | exports["escapeFromScope"] = Function::New(env, escapeFromScope); 56 | exports["stressEscapeFromScope"] = Function::New(env, stressEscapeFromScope); 57 | exports["doubleEscapeFromScope"] = Function::New(env, doubleEscapeFromScope); 58 | 59 | return exports; 60 | } 61 | -------------------------------------------------------------------------------- /deps/node-addon-api/test/handlescope.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | const buildType = process.config.target_defaults.default_configuration; 3 | const assert = require('assert'); 4 | 5 | test(require(`./build/${buildType}/binding.node`)); 6 | test(require(`./build/${buildType}/binding_noexcept.node`)); 7 | 8 | function test(binding) { 9 | assert.strictEqual(binding.handlescope.createScope(), 'scope'); 10 | assert.strictEqual(binding.handlescope.escapeFromScope(), 'inner-scope'); 11 | assert.strictEqual(binding.handlescope.stressEscapeFromScope(), 'inner-scope999999'); 12 | assert.throws(() => binding.handlescope.doubleEscapeFromScope(), 13 | Error, 14 | ' napi_escape_handle already called on scope'); 15 | } 16 | -------------------------------------------------------------------------------- /deps/node-addon-api/test/index.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | process.config.target_defaults.default_configuration = 4 | require('fs') 5 | .readdirSync(require('path').join(__dirname, 'build')) 6 | .filter((item) => (item === 'Debug' || item === 'Release'))[0]; 7 | 8 | // FIXME: We might need a way to load test modules automatically without 9 | // explicit declaration as follows. 10 | let testModules = [ 11 | 'arraybuffer', 12 | 'asynccontext', 13 | 'asyncworker', 14 | 'asyncworker-persistent', 15 | 'basic_types/array', 16 | 'basic_types/boolean', 17 | 'basic_types/number', 18 | 'basic_types/value', 19 | 'bigint', 20 | 'buffer', 21 | 'callbackscope', 22 | 'dataview/dataview', 23 | 'dataview/dataview_read_write', 24 | 'error', 25 | 'external', 26 | 'function', 27 | 'handlescope', 28 | 'memory_management', 29 | 'name', 30 | 'object/delete_property', 31 | 'object/get_property', 32 | 'object/has_own_property', 33 | 'object/has_property', 34 | 'object/object', 35 | 'object/object_deprecated', 36 | 'object/set_property', 37 | 'promise', 38 | 'typedarray', 39 | 'typedarray-bigint', 40 | 'objectwrap', 41 | 'objectreference', 42 | 'version_management' 43 | ]; 44 | 45 | if ((process.env.npm_config_NAPI_VERSION !== undefined) && 46 | (process.env.npm_config_NAPI_VERSION < 50000)) { 47 | // currently experimental only test if NAPI_VERSION 48 | // is set to experimental. We can't use C max int 49 | // as that is not supported as a number on earlier 50 | // Node.js versions. Once bigint is in a release 51 | // this should be guarded on the napi version 52 | // in which bigint was added. 53 | testModules.splice(testModules.indexOf('bigint'), 1); 54 | testModules.splice(testModules.indexOf('typedarray-bigint'), 1); 55 | } 56 | 57 | if ((process.env.npm_config_NAPI_VERSION !== undefined) && 58 | (process.env.npm_config_NAPI_VERSION < 3)) { 59 | testModules.splice(testModules.indexOf('callbackscope'), 1); 60 | testModules.splice(testModules.indexOf('version_management'), 1); 61 | } 62 | 63 | if (typeof global.gc === 'function') { 64 | console.log('Starting test suite\n'); 65 | 66 | // Requiring each module runs tests in the module. 67 | testModules.forEach(name => { 68 | console.log(`Running test '${name}'`); 69 | require('./' + name); 70 | }); 71 | 72 | console.log('\nAll tests passed!'); 73 | } else { 74 | // Make it easier to run with the correct (version-dependent) command-line args. 75 | const child = require('./napi_child').spawnSync(process.argv[0], [ '--expose-gc', __filename ], { 76 | stdio: 'inherit', 77 | }); 78 | 79 | if (child.signal) { 80 | console.error(`Tests aborted with ${child.signal}`); 81 | process.exitCode = 1; 82 | } else { 83 | process.exitCode = child.status; 84 | } 85 | process.exit(process.exitCode); 86 | } 87 | -------------------------------------------------------------------------------- /deps/node-addon-api/test/memory_management.cc: -------------------------------------------------------------------------------- 1 | #include "napi.h" 2 | 3 | using namespace Napi; 4 | 5 | Value externalAllocatedMemory(const CallbackInfo& info) { 6 | int64_t kSize = 1024 * 1024; 7 | int64_t baseline = MemoryManagement::AdjustExternalMemory(info.Env(), 0); 8 | int64_t tmp = MemoryManagement::AdjustExternalMemory(info.Env(), kSize); 9 | tmp = MemoryManagement::AdjustExternalMemory(info.Env(), -kSize); 10 | return Boolean::New(info.Env(), tmp == baseline); 11 | } 12 | 13 | Object InitMemoryManagement(Env env) { 14 | Object exports = Object::New(env); 15 | exports["externalAllocatedMemory"] = Function::New(env, externalAllocatedMemory); 16 | return exports; 17 | } 18 | -------------------------------------------------------------------------------- /deps/node-addon-api/test/memory_management.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | const buildType = process.config.target_defaults.default_configuration; 3 | const assert = require('assert'); 4 | 5 | test(require(`./build/${buildType}/binding.node`)); 6 | test(require(`./build/${buildType}/binding_noexcept.node`)); 7 | 8 | function test(binding) { 9 | assert.strictEqual(binding.memory_management.externalAllocatedMemory(), true) 10 | } 11 | -------------------------------------------------------------------------------- /deps/node-addon-api/test/name.cc: -------------------------------------------------------------------------------- 1 | #include "napi.h" 2 | 3 | using namespace Napi; 4 | 5 | const char* testValueUtf8 = "123456789"; 6 | const char16_t* testValueUtf16 = NAPI_WIDE_TEXT("123456789"); 7 | 8 | Value EchoString(const CallbackInfo& info) { 9 | String value = info[0].As(); 10 | String encoding = info[1].As(); 11 | 12 | if (encoding.Utf8Value() == "utf8") { 13 | return String::New(info.Env(), value.Utf8Value().c_str()); 14 | } else if (encoding.Utf8Value() == "utf16") { 15 | return String::New(info.Env(), value.Utf16Value().c_str()); 16 | } else { 17 | Error::New(info.Env(), "Invalid encoding.").ThrowAsJavaScriptException(); 18 | return Value(); 19 | } 20 | } 21 | 22 | Value CreateString(const CallbackInfo& info) { 23 | String encoding = info[0].As(); 24 | Number length = info[1].As(); 25 | 26 | if (encoding.Utf8Value() == "utf8") { 27 | if (length.IsUndefined()) { 28 | return String::New(info.Env(), testValueUtf8); 29 | } else { 30 | return String::New(info.Env(), testValueUtf8, length.Uint32Value()); 31 | } 32 | } else if (encoding.Utf8Value() == "utf16") { 33 | if (length.IsUndefined()) { 34 | return String::New(info.Env(), testValueUtf16); 35 | } else { 36 | return String::New(info.Env(), testValueUtf16, length.Uint32Value()); 37 | } 38 | } else { 39 | Error::New(info.Env(), "Invalid encoding.").ThrowAsJavaScriptException(); 40 | return Value(); 41 | } 42 | } 43 | 44 | Value CheckString(const CallbackInfo& info) { 45 | String value = info[0].As(); 46 | String encoding = info[1].As(); 47 | Number length = info[2].As(); 48 | 49 | if (encoding.Utf8Value() == "utf8") { 50 | std::string testValue = testValueUtf8; 51 | if (!length.IsUndefined()) { 52 | testValue = testValue.substr(0, length.Uint32Value()); 53 | } 54 | 55 | std::string stringValue = value; 56 | return Boolean::New(info.Env(), stringValue == testValue); 57 | } else if (encoding.Utf8Value() == "utf16") { 58 | std::u16string testValue = testValueUtf16; 59 | if (!length.IsUndefined()) { 60 | testValue = testValue.substr(0, length.Uint32Value()); 61 | } 62 | 63 | std::u16string stringValue = value; 64 | return Boolean::New(info.Env(), stringValue == testValue); 65 | } else { 66 | Error::New(info.Env(), "Invalid encoding.").ThrowAsJavaScriptException(); 67 | return Value(); 68 | } 69 | } 70 | 71 | Value CreateSymbol(const CallbackInfo& info) { 72 | String description = info[0].As(); 73 | 74 | if (!description.IsUndefined()) { 75 | return Symbol::New(info.Env(), description); 76 | } else { 77 | return Symbol::New(info.Env()); 78 | } 79 | } 80 | 81 | Value CheckSymbol(const CallbackInfo& info) { 82 | return Boolean::New(info.Env(), info[0].Type() == napi_symbol); 83 | } 84 | 85 | Object InitName(Env env) { 86 | Object exports = Object::New(env); 87 | 88 | exports["echoString"] = Function::New(env, EchoString); 89 | exports["createString"] = Function::New(env, CreateString); 90 | exports["checkString"] = Function::New(env, CheckString); 91 | exports["createSymbol"] = Function::New(env, CreateSymbol); 92 | exports["checkSymbol"] = Function::New(env, CheckSymbol); 93 | 94 | return exports; 95 | } 96 | -------------------------------------------------------------------------------- /deps/node-addon-api/test/name.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | const buildType = process.config.target_defaults.default_configuration; 3 | const assert = require('assert'); 4 | 5 | test(require(`./build/${buildType}/binding.node`)); 6 | test(require(`./build/${buildType}/binding_noexcept.node`)); 7 | 8 | function test(binding) { 9 | const expected = '123456789'; 10 | 11 | assert.ok(binding.name.checkString(expected, 'utf8')); 12 | assert.ok(binding.name.checkString(expected, 'utf16')); 13 | assert.ok(binding.name.checkString(expected.substr(0, 3), 'utf8', 3)); 14 | assert.ok(binding.name.checkString(expected.substr(0, 3), 'utf16', 3)); 15 | 16 | const str1 = binding.name.createString('utf8'); 17 | assert.strictEqual(str1, expected); 18 | assert.ok(binding.name.checkString(str1, 'utf8')); 19 | assert.ok(binding.name.checkString(str1, 'utf16')); 20 | 21 | const substr1 = binding.name.createString('utf8', 3); 22 | assert.strictEqual(substr1, expected.substr(0, 3)); 23 | assert.ok(binding.name.checkString(substr1, 'utf8', 3)); 24 | assert.ok(binding.name.checkString(substr1, 'utf16', 3)); 25 | 26 | const str2 = binding.name.createString('utf16'); 27 | assert.strictEqual(str1, expected); 28 | assert.ok(binding.name.checkString(str2, 'utf8')); 29 | assert.ok(binding.name.checkString(str2, 'utf16')); 30 | 31 | const substr2 = binding.name.createString('utf16', 3); 32 | assert.strictEqual(substr1, expected.substr(0, 3)); 33 | assert.ok(binding.name.checkString(substr2, 'utf8', 3)); 34 | assert.ok(binding.name.checkString(substr2, 'utf16', 3)); 35 | 36 | assert.ok(binding.name.checkSymbol(Symbol())); 37 | assert.ok(binding.name.checkSymbol(Symbol('test'))); 38 | 39 | const sym1 = binding.name.createSymbol(); 40 | assert.strictEqual(typeof sym1, 'symbol'); 41 | assert.ok(binding.name.checkSymbol(sym1)); 42 | 43 | const sym2 = binding.name.createSymbol('test'); 44 | assert.strictEqual(typeof sym2, 'symbol'); 45 | assert.ok(binding.name.checkSymbol(sym1)); 46 | 47 | // Check for off-by-one errors which might only appear for strings of certain sizes, 48 | // due to how std::string increments its capacity in chunks. 49 | const longString = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'; 50 | for (let i = 10; i <= longString.length; i++) { 51 | const str = longString.substr(0, i); 52 | assert.strictEqual(binding.name.echoString(str, 'utf8'), str); 53 | assert.strictEqual(binding.name.echoString(str, 'utf16'), str); 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /deps/node-addon-api/test/napi_child.js: -------------------------------------------------------------------------------- 1 | // Makes sure that child processes are spawned appropriately. 2 | exports.spawnSync = function(command, args, options) { 3 | if (require('../index').needsFlag) { 4 | args.splice(0, 0, '--napi-modules'); 5 | } 6 | return require('child_process').spawnSync(command, args, options); 7 | }; 8 | -------------------------------------------------------------------------------- /deps/node-addon-api/test/object/delete_property.cc: -------------------------------------------------------------------------------- 1 | #include "napi.h" 2 | 3 | using namespace Napi; 4 | 5 | Value DeletePropertyWithNapiValue(const CallbackInfo& info) { 6 | Object obj = info[0].As(); 7 | Name key = info[1].As(); 8 | return Boolean::New(info.Env(), obj.Delete(static_cast(key))); 9 | } 10 | 11 | Value DeletePropertyWithNapiWrapperValue(const CallbackInfo& info) { 12 | Object obj = info[0].As(); 13 | Name key = info[1].As(); 14 | return Boolean::New(info.Env(), obj.Delete(key)); 15 | } 16 | 17 | Value DeletePropertyWithCStyleString(const CallbackInfo& info) { 18 | Object obj = info[0].As(); 19 | String jsKey = info[1].As(); 20 | return Boolean::New(info.Env(), obj.Delete(jsKey.Utf8Value().c_str())); 21 | } 22 | 23 | Value DeletePropertyWithCppStyleString(const CallbackInfo& info) { 24 | Object obj = info[0].As(); 25 | String jsKey = info[1].As(); 26 | return Boolean::New(info.Env(), obj.Delete(jsKey.Utf8Value())); 27 | } 28 | -------------------------------------------------------------------------------- /deps/node-addon-api/test/object/delete_property.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | const buildType = process.config.target_defaults.default_configuration; 4 | const assert = require('assert'); 5 | 6 | test(require(`../build/${buildType}/binding.node`)); 7 | test(require(`../build/${buildType}/binding_noexcept.node`)); 8 | 9 | function test(binding) { 10 | function testDeleteProperty(nativeDeleteProperty) { 11 | const obj = { one: 1, two: 2 }; 12 | Object.defineProperty(obj, "three", {configurable: false, value: 3}); 13 | assert.strictEqual(nativeDeleteProperty(obj, 'one'), true); 14 | assert.strictEqual(nativeDeleteProperty(obj, 'missing'), true); 15 | 16 | /* Returns true for all cases except when the property is an own non- 17 | configurable property, in which case, false is returned in non-strict mode. */ 18 | assert.strictEqual(nativeDeleteProperty(obj, 'three'), false); 19 | assert.deepStrictEqual(obj, { two: 2 }); 20 | } 21 | 22 | function testShouldThrowErrorIfKeyIsInvalid(nativeDeleteProperty) { 23 | assert.throws(() => { 24 | nativeDeleteProperty(undefined, 'test'); 25 | }, /object was expected/); 26 | } 27 | 28 | testDeleteProperty(binding.object.deletePropertyWithNapiValue); 29 | testDeleteProperty(binding.object.deletePropertyWithNapiWrapperValue); 30 | testDeleteProperty(binding.object.deletePropertyWithCStyleString); 31 | testDeleteProperty(binding.object.deletePropertyWithCppStyleString); 32 | 33 | testShouldThrowErrorIfKeyIsInvalid(binding.object.deletePropertyWithNapiValue); 34 | testShouldThrowErrorIfKeyIsInvalid(binding.object.deletePropertyWithNapiWrapperValue); 35 | testShouldThrowErrorIfKeyIsInvalid(binding.object.deletePropertyWithCStyleString); 36 | testShouldThrowErrorIfKeyIsInvalid(binding.object.deletePropertyWithCppStyleString); 37 | } 38 | -------------------------------------------------------------------------------- /deps/node-addon-api/test/object/get_property.cc: -------------------------------------------------------------------------------- 1 | #include "napi.h" 2 | 3 | using namespace Napi; 4 | 5 | Value GetPropertyWithNapiValue(const CallbackInfo& info) { 6 | Object obj = info[0].As(); 7 | Name key = info[1].As(); 8 | return obj.Get(static_cast(key)); 9 | } 10 | 11 | Value GetPropertyWithNapiWrapperValue(const CallbackInfo& info) { 12 | Object obj = info[0].As(); 13 | Name key = info[1].As(); 14 | return obj.Get(key); 15 | } 16 | 17 | Value GetPropertyWithCStyleString(const CallbackInfo& info) { 18 | Object obj = info[0].As(); 19 | String jsKey = info[1].As(); 20 | return obj.Get(jsKey.Utf8Value().c_str()); 21 | } 22 | 23 | Value GetPropertyWithCppStyleString(const CallbackInfo& info) { 24 | Object obj = info[0].As(); 25 | String jsKey = info[1].As(); 26 | return obj.Get(jsKey.Utf8Value()); 27 | } 28 | -------------------------------------------------------------------------------- /deps/node-addon-api/test/object/get_property.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | const buildType = process.config.target_defaults.default_configuration; 4 | const assert = require('assert'); 5 | 6 | test(require(`../build/${buildType}/binding.node`)); 7 | test(require(`../build/${buildType}/binding_noexcept.node`)); 8 | 9 | function test(binding) { 10 | function testGetProperty(nativeGetProperty) { 11 | const obj = { test: 1 }; 12 | assert.strictEqual(nativeGetProperty(obj, 'test'), 1); 13 | } 14 | 15 | function testShouldThrowErrorIfKeyIsInvalid(nativeGetProperty) { 16 | assert.throws(() => { 17 | nativeGetProperty(undefined, 'test'); 18 | }, /object was expected/); 19 | } 20 | 21 | testGetProperty(binding.object.getPropertyWithNapiValue); 22 | testGetProperty(binding.object.getPropertyWithNapiWrapperValue); 23 | testGetProperty(binding.object.getPropertyWithCStyleString); 24 | testGetProperty(binding.object.getPropertyWithCppStyleString); 25 | 26 | testShouldThrowErrorIfKeyIsInvalid(binding.object.getPropertyWithNapiValue); 27 | testShouldThrowErrorIfKeyIsInvalid(binding.object.getPropertyWithNapiWrapperValue); 28 | testShouldThrowErrorIfKeyIsInvalid(binding.object.getPropertyWithCStyleString); 29 | testShouldThrowErrorIfKeyIsInvalid(binding.object.getPropertyWithCppStyleString); 30 | } 31 | -------------------------------------------------------------------------------- /deps/node-addon-api/test/object/has_own_property.cc: -------------------------------------------------------------------------------- 1 | #include "napi.h" 2 | 3 | using namespace Napi; 4 | 5 | Value HasOwnPropertyWithNapiValue(const CallbackInfo& info) { 6 | Object obj = info[0].As(); 7 | Name key = info[1].As(); 8 | return Boolean::New(info.Env(), obj.HasOwnProperty(static_cast(key))); 9 | } 10 | 11 | Value HasOwnPropertyWithNapiWrapperValue(const CallbackInfo& info) { 12 | Object obj = info[0].As(); 13 | Name key = info[1].As(); 14 | return Boolean::New(info.Env(), obj.HasOwnProperty(key)); 15 | } 16 | 17 | Value HasOwnPropertyWithCStyleString(const CallbackInfo& info) { 18 | Object obj = info[0].As(); 19 | String jsKey = info[1].As(); 20 | return Boolean::New(info.Env(), obj.HasOwnProperty(jsKey.Utf8Value().c_str())); 21 | } 22 | 23 | Value HasOwnPropertyWithCppStyleString(const CallbackInfo& info) { 24 | Object obj = info[0].As(); 25 | String jsKey = info[1].As(); 26 | return Boolean::New(info.Env(), obj.HasOwnProperty(jsKey.Utf8Value())); 27 | } 28 | -------------------------------------------------------------------------------- /deps/node-addon-api/test/object/has_own_property.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | const buildType = process.config.target_defaults.default_configuration; 4 | const assert = require('assert'); 5 | 6 | test(require(`../build/${buildType}/binding.node`)); 7 | test(require(`../build/${buildType}/binding_noexcept.node`)); 8 | 9 | function test(binding) { 10 | function testHasOwnProperty(nativeHasOwnProperty) { 11 | const obj = { one: 1 }; 12 | 13 | Object.defineProperty(obj, 'two', { value: 2 }); 14 | 15 | assert.strictEqual(nativeHasOwnProperty(obj, 'one'), true); 16 | assert.strictEqual(nativeHasOwnProperty(obj, 'two'), true); 17 | assert.strictEqual('toString' in obj, true); 18 | assert.strictEqual(nativeHasOwnProperty(obj, 'toString'), false); 19 | } 20 | 21 | function testShouldThrowErrorIfKeyIsInvalid(nativeHasOwnProperty) { 22 | assert.throws(() => { 23 | nativeHasOwnProperty(undefined, 'test'); 24 | }, /object was expected/); 25 | } 26 | 27 | testHasOwnProperty(binding.object.hasOwnPropertyWithNapiValue); 28 | testHasOwnProperty(binding.object.hasOwnPropertyWithNapiWrapperValue); 29 | testHasOwnProperty(binding.object.hasOwnPropertyWithCStyleString); 30 | testHasOwnProperty(binding.object.hasOwnPropertyWithCppStyleString); 31 | 32 | testShouldThrowErrorIfKeyIsInvalid(binding.object.hasOwnPropertyWithNapiValue); 33 | testShouldThrowErrorIfKeyIsInvalid(binding.object.hasOwnPropertyWithNapiWrapperValue); 34 | testShouldThrowErrorIfKeyIsInvalid(binding.object.hasOwnPropertyWithCStyleString); 35 | testShouldThrowErrorIfKeyIsInvalid(binding.object.hasOwnPropertyWithCppStyleString); 36 | } 37 | -------------------------------------------------------------------------------- /deps/node-addon-api/test/object/has_property.cc: -------------------------------------------------------------------------------- 1 | #include "napi.h" 2 | 3 | using namespace Napi; 4 | 5 | Value HasPropertyWithNapiValue(const CallbackInfo& info) { 6 | Object obj = info[0].As(); 7 | Name key = info[1].As(); 8 | return Boolean::New(info.Env(), obj.Has(static_cast(key))); 9 | } 10 | 11 | Value HasPropertyWithNapiWrapperValue(const CallbackInfo& info) { 12 | Object obj = info[0].As(); 13 | Name key = info[1].As(); 14 | return Boolean::New(info.Env(), obj.Has(key)); 15 | } 16 | 17 | Value HasPropertyWithCStyleString(const CallbackInfo& info) { 18 | Object obj = info[0].As(); 19 | String jsKey = info[1].As(); 20 | return Boolean::New(info.Env(), obj.Has(jsKey.Utf8Value().c_str())); 21 | } 22 | 23 | Value HasPropertyWithCppStyleString(const CallbackInfo& info) { 24 | Object obj = info[0].As(); 25 | String jsKey = info[1].As(); 26 | return Boolean::New(info.Env(), obj.Has(jsKey.Utf8Value())); 27 | } 28 | -------------------------------------------------------------------------------- /deps/node-addon-api/test/object/has_property.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | const buildType = process.config.target_defaults.default_configuration; 4 | const assert = require('assert'); 5 | 6 | test(require(`../build/${buildType}/binding.node`)); 7 | test(require(`../build/${buildType}/binding_noexcept.node`)); 8 | 9 | function test(binding) { 10 | function testHasProperty(nativeHasProperty) { 11 | const obj = { one: 1 }; 12 | 13 | Object.defineProperty(obj, 'two', { value: 2 }); 14 | 15 | assert.strictEqual(nativeHasProperty(obj, 'one'), true); 16 | assert.strictEqual(nativeHasProperty(obj, 'two'), true); 17 | assert.strictEqual('toString' in obj, true); 18 | assert.strictEqual(nativeHasProperty(obj, 'toString'), true); 19 | } 20 | 21 | function testShouldThrowErrorIfKeyIsInvalid(nativeHasProperty) { 22 | assert.throws(() => { 23 | nativeHasProperty(undefined, 'test'); 24 | }, /object was expected/); 25 | } 26 | 27 | testHasProperty(binding.object.hasPropertyWithNapiValue); 28 | testHasProperty(binding.object.hasPropertyWithNapiWrapperValue); 29 | testHasProperty(binding.object.hasPropertyWithCStyleString); 30 | testHasProperty(binding.object.hasPropertyWithCppStyleString); 31 | 32 | testShouldThrowErrorIfKeyIsInvalid(binding.object.hasPropertyWithNapiValue); 33 | testShouldThrowErrorIfKeyIsInvalid(binding.object.hasPropertyWithNapiWrapperValue); 34 | testShouldThrowErrorIfKeyIsInvalid(binding.object.hasPropertyWithCStyleString); 35 | testShouldThrowErrorIfKeyIsInvalid(binding.object.hasPropertyWithCppStyleString); 36 | } 37 | -------------------------------------------------------------------------------- /deps/node-addon-api/test/object/object_deprecated.cc: -------------------------------------------------------------------------------- 1 | #include "napi.h" 2 | 3 | using namespace Napi; 4 | 5 | static bool testValue = true; 6 | 7 | namespace { 8 | 9 | Value TestGetter(const CallbackInfo& info) { 10 | return Boolean::New(info.Env(), testValue); 11 | } 12 | 13 | void TestSetter(const CallbackInfo& info) { 14 | testValue = info[0].As(); 15 | } 16 | 17 | Value TestFunction(const CallbackInfo& info) { 18 | return Boolean::New(info.Env(), true); 19 | } 20 | 21 | void DefineProperties(const CallbackInfo& info) { 22 | Object obj = info[0].As(); 23 | String nameType = info[1].As(); 24 | Env env = info.Env(); 25 | 26 | if (nameType.Utf8Value() == "literal") { 27 | obj.DefineProperties({ 28 | PropertyDescriptor::Accessor("readonlyAccessor", TestGetter), 29 | PropertyDescriptor::Accessor("readwriteAccessor", TestGetter, TestSetter), 30 | PropertyDescriptor::Function("function", TestFunction), 31 | }); 32 | } else if (nameType.Utf8Value() == "string") { 33 | // VS2013 has lifetime issues when passing temporary objects into the constructor of another 34 | // object. It generates code to destruct the object as soon as the constructor call returns. 35 | // Since this isn't a common case for using std::string objects, I'm refactoring the test to 36 | // work around the issue. 37 | std::string str1("readonlyAccessor"); 38 | std::string str2("readwriteAccessor"); 39 | std::string str7("function"); 40 | 41 | obj.DefineProperties({ 42 | PropertyDescriptor::Accessor(str1, TestGetter), 43 | PropertyDescriptor::Accessor(str2, TestGetter, TestSetter), 44 | PropertyDescriptor::Function(str7, TestFunction), 45 | }); 46 | } else if (nameType.Utf8Value() == "value") { 47 | obj.DefineProperties({ 48 | PropertyDescriptor::Accessor( 49 | Napi::String::New(env, "readonlyAccessor"), TestGetter), 50 | PropertyDescriptor::Accessor( 51 | Napi::String::New(env, "readwriteAccessor"), TestGetter, TestSetter), 52 | PropertyDescriptor::Function( 53 | Napi::String::New(env, "function"), TestFunction), 54 | }); 55 | } 56 | } 57 | 58 | } // end of anonymous namespace 59 | 60 | Object InitObjectDeprecated(Env env) { 61 | Object exports = Object::New(env); 62 | 63 | exports["defineProperties"] = Function::New(env, DefineProperties); 64 | 65 | return exports; 66 | } 67 | -------------------------------------------------------------------------------- /deps/node-addon-api/test/object/object_deprecated.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | const buildType = process.config.target_defaults.default_configuration; 3 | const assert = require('assert'); 4 | 5 | test(require(`../build/${buildType}/binding.node`)); 6 | test(require(`../build/${buildType}/binding_noexcept.node`)); 7 | 8 | function test(binding) { 9 | if (!('object_deprecated' in binding)) { 10 | return; 11 | } 12 | function assertPropertyIs(obj, key, attribute) { 13 | const propDesc = Object.getOwnPropertyDescriptor(obj, key); 14 | assert.ok(propDesc); 15 | assert.ok(propDesc[attribute]); 16 | } 17 | 18 | function assertPropertyIsNot(obj, key, attribute) { 19 | const propDesc = Object.getOwnPropertyDescriptor(obj, key); 20 | assert.ok(propDesc); 21 | assert.ok(!propDesc[attribute]); 22 | } 23 | 24 | function testDefineProperties(nameType) { 25 | const obj = {}; 26 | binding.object.defineProperties(obj, nameType); 27 | 28 | assertPropertyIsNot(obj, 'readonlyAccessor', 'enumerable'); 29 | assertPropertyIsNot(obj, 'readonlyAccessor', 'configurable'); 30 | assert.strictEqual(obj.readonlyAccessor, true); 31 | 32 | assertPropertyIsNot(obj, 'readwriteAccessor', 'enumerable'); 33 | assertPropertyIsNot(obj, 'readwriteAccessor', 'configurable'); 34 | obj.readwriteAccessor = false; 35 | assert.strictEqual(obj.readwriteAccessor, false); 36 | obj.readwriteAccessor = true; 37 | assert.strictEqual(obj.readwriteAccessor, true); 38 | 39 | assertPropertyIsNot(obj, 'function', 'writable'); 40 | assertPropertyIsNot(obj, 'function', 'enumerable'); 41 | assertPropertyIsNot(obj, 'function', 'configurable'); 42 | assert.strictEqual(obj.function(), true); 43 | } 44 | 45 | testDefineProperties('literal'); 46 | testDefineProperties('string'); 47 | testDefineProperties('value'); 48 | } 49 | -------------------------------------------------------------------------------- /deps/node-addon-api/test/object/set_property.cc: -------------------------------------------------------------------------------- 1 | #include "napi.h" 2 | 3 | using namespace Napi; 4 | 5 | void SetPropertyWithNapiValue(const CallbackInfo& info) { 6 | Object obj = info[0].As(); 7 | Name key = info[1].As(); 8 | Value value = info[2]; 9 | obj.Set(static_cast(key), value); 10 | } 11 | 12 | void SetPropertyWithNapiWrapperValue(const CallbackInfo& info) { 13 | Object obj = info[0].As(); 14 | Name key = info[1].As(); 15 | Value value = info[2]; 16 | obj.Set(key, value); 17 | } 18 | 19 | void SetPropertyWithCStyleString(const CallbackInfo& info) { 20 | Object obj = info[0].As(); 21 | String jsKey = info[1].As(); 22 | Value value = info[2]; 23 | obj.Set(jsKey.Utf8Value().c_str(), value); 24 | } 25 | 26 | void SetPropertyWithCppStyleString(const CallbackInfo& info) { 27 | Object obj = info[0].As(); 28 | String jsKey = info[1].As(); 29 | Value value = info[2]; 30 | obj.Set(jsKey.Utf8Value(), value); 31 | } 32 | -------------------------------------------------------------------------------- /deps/node-addon-api/test/object/set_property.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | const buildType = process.config.target_defaults.default_configuration; 4 | const assert = require('assert'); 5 | 6 | test(require(`../build/${buildType}/binding.node`)); 7 | test(require(`../build/${buildType}/binding_noexcept.node`)); 8 | 9 | function test(binding) { 10 | function testSetProperty(nativeSetProperty) { 11 | const obj = {}; 12 | nativeSetProperty(obj, 'test', 1); 13 | assert.strictEqual(obj.test, 1); 14 | } 15 | 16 | function testShouldThrowErrorIfKeyIsInvalid(nativeSetProperty) { 17 | assert.throws(() => { 18 | nativeSetProperty(undefined, 'test', 1); 19 | }, /object was expected/); 20 | } 21 | 22 | testSetProperty(binding.object.setPropertyWithNapiValue); 23 | testSetProperty(binding.object.setPropertyWithNapiWrapperValue); 24 | testSetProperty(binding.object.setPropertyWithCStyleString); 25 | testSetProperty(binding.object.setPropertyWithCppStyleString); 26 | 27 | testShouldThrowErrorIfKeyIsInvalid(binding.object.setPropertyWithNapiValue); 28 | testShouldThrowErrorIfKeyIsInvalid(binding.object.setPropertyWithNapiWrapperValue); 29 | testShouldThrowErrorIfKeyIsInvalid(binding.object.setPropertyWithCStyleString); 30 | testShouldThrowErrorIfKeyIsInvalid(binding.object.setPropertyWithCppStyleString); 31 | } 32 | -------------------------------------------------------------------------------- /deps/node-addon-api/test/promise.cc: -------------------------------------------------------------------------------- 1 | #include "napi.h" 2 | 3 | using namespace Napi; 4 | 5 | Value IsPromise(const CallbackInfo& info) { 6 | return Boolean::New(info.Env(), info[0].IsPromise()); 7 | } 8 | 9 | Value ResolvePromise(const CallbackInfo& info) { 10 | auto deferred = Promise::Deferred::New(info.Env()); 11 | deferred.Resolve(info[0]); 12 | return deferred.Promise(); 13 | } 14 | 15 | Value RejectPromise(const CallbackInfo& info) { 16 | auto deferred = Promise::Deferred::New(info.Env()); 17 | deferred.Reject(info[0]); 18 | return deferred.Promise(); 19 | } 20 | 21 | Object InitPromise(Env env) { 22 | Object exports = Object::New(env); 23 | 24 | exports["isPromise"] = Function::New(env, IsPromise); 25 | exports["resolvePromise"] = Function::New(env, ResolvePromise); 26 | exports["rejectPromise"] = Function::New(env, RejectPromise); 27 | 28 | return exports; 29 | } 30 | -------------------------------------------------------------------------------- /deps/node-addon-api/test/promise.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | const buildType = process.config.target_defaults.default_configuration; 3 | const assert = require('assert'); 4 | const common = require('./common'); 5 | 6 | test(require(`./build/${buildType}/binding.node`)); 7 | test(require(`./build/${buildType}/binding_noexcept.node`)); 8 | 9 | function test(binding) { 10 | assert.strictEqual(binding.promise.isPromise({}), false); 11 | 12 | const resolving = binding.promise.resolvePromise('resolved'); 13 | assert.strictEqual(binding.promise.isPromise(resolving), true); 14 | resolving.then(common.mustCall()).catch(common.mustNotCall()); 15 | 16 | const rejecting = binding.promise.rejectPromise('error'); 17 | assert.strictEqual(binding.promise.isPromise(rejecting), true); 18 | rejecting.then(common.mustNotCall()).catch(common.mustCall()); 19 | } 20 | -------------------------------------------------------------------------------- /deps/node-addon-api/test/testUtil.js: -------------------------------------------------------------------------------- 1 | // Run each test function in sequence, 2 | // with an async delay and GC call between each. 3 | function runGCTests(tests, i, title) { 4 | if (!i) { 5 | i = 0; 6 | } 7 | 8 | if (tests[i]) { 9 | if (typeof tests[i] === 'string') { 10 | title = tests[i]; 11 | runGCTests(tests, i + 1, title); 12 | } else { 13 | try { 14 | tests[i](); 15 | } catch (e) { 16 | console.error('Test failed: ' + title); 17 | throw e; 18 | } 19 | setImmediate(() => { 20 | global.gc(); 21 | runGCTests(tests, i + 1, title); 22 | }); 23 | } 24 | } 25 | } 26 | 27 | module.exports = { 28 | runGCTests, 29 | }; 30 | -------------------------------------------------------------------------------- /deps/node-addon-api/test/thunking_manual.js: -------------------------------------------------------------------------------- 1 | // Flags: --expose-gc 2 | 'use strict'; 3 | const buildType = 'Debug'; 4 | const assert = require('assert'); 5 | 6 | test(require(`./build/${buildType}/binding.node`)); 7 | test(require(`./build/${buildType}/binding_noexcept.node`)); 8 | 9 | function test(binding) { 10 | console.log("Thunking: Performing initial GC"); 11 | global.gc(); 12 | console.log("Thunking: Creating test object"); 13 | let object = binding.thunking_manual.createTestObject(); 14 | object = null; 15 | console.log("Thunking: About to GC\n--------"); 16 | global.gc(); 17 | console.log("--------\nThunking: GC complete"); 18 | } 19 | -------------------------------------------------------------------------------- /deps/node-addon-api/test/typedarray-bigint.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | const buildType = process.config.target_defaults.default_configuration; 3 | const assert = require('assert'); 4 | 5 | test(require(`./build/${buildType}/binding.node`)); 6 | test(require(`./build/${buildType}/binding_noexcept.node`)); 7 | 8 | function test(binding) { 9 | [ 10 | ['bigint64', BigInt64Array], 11 | ['biguint64', BigUint64Array], 12 | ].forEach(([type, Constructor]) => { 13 | try { 14 | const length = 4; 15 | const t = binding.typedarray.createTypedArray(type, length); 16 | assert.ok(t instanceof Constructor); 17 | assert.strictEqual(binding.typedarray.getTypedArrayType(t), type); 18 | assert.strictEqual(binding.typedarray.getTypedArrayLength(t), length); 19 | 20 | t[3] = 11n; 21 | assert.strictEqual(binding.typedarray.getTypedArrayElement(t, 3), 11n); 22 | binding.typedarray.setTypedArrayElement(t, 3, 22n); 23 | assert.strictEqual(binding.typedarray.getTypedArrayElement(t, 3), 22n); 24 | assert.strictEqual(t[3], 22n); 25 | 26 | const b = binding.typedarray.getTypedArrayBuffer(t); 27 | assert.ok(b instanceof ArrayBuffer); 28 | } catch (e) { 29 | console.log(type, Constructor); 30 | throw e; 31 | } 32 | 33 | try { 34 | const length = 4; 35 | const offset = 8; 36 | const b = new ArrayBuffer(offset + 64 * 4); 37 | 38 | const t = binding.typedarray.createTypedArray(type, length, b, offset); 39 | assert.ok(t instanceof Constructor); 40 | assert.strictEqual(binding.typedarray.getTypedArrayType(t), type); 41 | assert.strictEqual(binding.typedarray.getTypedArrayLength(t), length); 42 | 43 | t[3] = 11n; 44 | assert.strictEqual(binding.typedarray.getTypedArrayElement(t, 3), 11n); 45 | binding.typedarray.setTypedArrayElement(t, 3, 22n); 46 | assert.strictEqual(binding.typedarray.getTypedArrayElement(t, 3), 22n); 47 | assert.strictEqual(t[3], 22n); 48 | 49 | assert.strictEqual(binding.typedarray.getTypedArrayBuffer(t), b); 50 | } catch (e) { 51 | console.log(type, Constructor); 52 | throw e; 53 | } 54 | }); 55 | 56 | assert.throws(() => { 57 | binding.typedarray.createInvalidTypedArray(); 58 | }, /Invalid (pointer passed as )?argument/); 59 | } 60 | -------------------------------------------------------------------------------- /deps/node-addon-api/test/typedarray.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | const buildType = process.config.target_defaults.default_configuration; 3 | const assert = require('assert'); 4 | 5 | test(require(`./build/${buildType}/binding.node`)); 6 | test(require(`./build/${buildType}/binding_noexcept.node`)); 7 | 8 | function test(binding) { 9 | const testData = [ 10 | [ 'int8', Int8Array ], 11 | [ 'uint8', Uint8Array ], 12 | [ 'uint8_clamped', Uint8ClampedArray ], 13 | [ 'int16', Int16Array ], 14 | [ 'uint16', Uint16Array ], 15 | [ 'int32', Int32Array ], 16 | [ 'uint32', Uint32Array ], 17 | [ 'float32', Float32Array ], 18 | [ 'float64', Float64Array ], 19 | ]; 20 | 21 | testData.forEach(data => { 22 | try { 23 | const length = 4; 24 | const t = binding.typedarray.createTypedArray(data[0], length); 25 | assert.ok(t instanceof data[1]); 26 | assert.strictEqual(binding.typedarray.getTypedArrayType(t), data[0]); 27 | assert.strictEqual(binding.typedarray.getTypedArrayLength(t), length); 28 | 29 | t[3] = 11; 30 | assert.strictEqual(binding.typedarray.getTypedArrayElement(t, 3), 11); 31 | binding.typedarray.setTypedArrayElement(t, 3, 22); 32 | assert.strictEqual(binding.typedarray.getTypedArrayElement(t, 3), 22); 33 | assert.strictEqual(t[3], 22); 34 | 35 | const b = binding.typedarray.getTypedArrayBuffer(t); 36 | assert.ok(b instanceof ArrayBuffer); 37 | } catch (e) { 38 | console.log(data); 39 | throw e; 40 | } 41 | }); 42 | 43 | testData.forEach(data => { 44 | try { 45 | const length = 4; 46 | const offset = 8; 47 | const b = new ArrayBuffer(offset + 64 * 4); 48 | 49 | const t = binding.typedarray.createTypedArray(data[0], length, b, offset); 50 | assert.ok(t instanceof data[1]); 51 | assert.strictEqual(binding.typedarray.getTypedArrayType(t), data[0]); 52 | assert.strictEqual(binding.typedarray.getTypedArrayLength(t), length); 53 | 54 | t[3] = 11; 55 | assert.strictEqual(binding.typedarray.getTypedArrayElement(t, 3), 11); 56 | binding.typedarray.setTypedArrayElement(t, 3, 22); 57 | assert.strictEqual(binding.typedarray.getTypedArrayElement(t, 3), 22); 58 | assert.strictEqual(t[3], 22); 59 | 60 | assert.strictEqual(binding.typedarray.getTypedArrayBuffer(t), b); 61 | } catch (e) { 62 | console.log(data); 63 | throw e; 64 | } 65 | }); 66 | 67 | assert.throws(() => { 68 | binding.typedarray.createInvalidTypedArray(); 69 | }, /Invalid (pointer passed as )?argument/); 70 | } 71 | -------------------------------------------------------------------------------- /deps/node-addon-api/test/version_management.cc: -------------------------------------------------------------------------------- 1 | #include "napi.h" 2 | 3 | using namespace Napi; 4 | 5 | Value getNapiVersion(const CallbackInfo& info) { 6 | Napi::Env env = info.Env(); 7 | uint32_t napi_version = VersionManagement::GetNapiVersion(env); 8 | return Number::New(env, napi_version); 9 | } 10 | 11 | Value getNodeVersion(const CallbackInfo& info) { 12 | Napi::Env env = info.Env(); 13 | const napi_node_version* node_version = VersionManagement::GetNodeVersion(env); 14 | Object version = Object::New(env); 15 | version.Set("major", Number::New(env, node_version->major)); 16 | version.Set("minor", Number::New(env, node_version->minor)); 17 | version.Set("patch", Number::New(env, node_version->patch)); 18 | version.Set("release", String::New(env, node_version->release)); 19 | return version; 20 | } 21 | 22 | Object InitVersionManagement(Env env) { 23 | Object exports = Object::New(env); 24 | exports["getNapiVersion"] = Function::New(env, getNapiVersion); 25 | exports["getNodeVersion"] = Function::New(env, getNodeVersion); 26 | return exports; 27 | } 28 | -------------------------------------------------------------------------------- /deps/node-addon-api/test/version_management.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | const buildType = process.config.target_defaults.default_configuration; 3 | const assert = require('assert'); 4 | 5 | test(require(`./build/${buildType}/binding.node`)); 6 | test(require(`./build/${buildType}/binding_noexcept.node`)); 7 | 8 | function parseVersion() { 9 | const expected = {}; 10 | expected.napi = parseInt(process.versions.napi); 11 | expected.release = process.release.name; 12 | const nodeVersion = process.versions.node.split('.'); 13 | expected.major = parseInt(nodeVersion[0]); 14 | expected.minor = parseInt(nodeVersion[1]); 15 | expected.patch = parseInt(nodeVersion[2]); 16 | return expected; 17 | } 18 | 19 | function test(binding) { 20 | 21 | const expected = parseVersion(); 22 | 23 | const napiVersion = binding.version_management.getNapiVersion(); 24 | assert.strictEqual(napiVersion, expected.napi); 25 | 26 | const nodeVersion = binding.version_management.getNodeVersion(); 27 | assert.strictEqual(nodeVersion.major, expected.major); 28 | assert.strictEqual(nodeVersion.minor, expected.minor); 29 | assert.strictEqual(nodeVersion.patch, expected.patch); 30 | assert.strictEqual(nodeVersion.release, expected.release); 31 | 32 | } 33 | -------------------------------------------------------------------------------- /deps/node-addon-api/tools/README.md: -------------------------------------------------------------------------------- 1 | # Migration Script 2 | 3 | The migration tool is designed to reduce repetitive work in the migration process. However, the script is not aiming to convert every thing for you. There are usually some small fixes and major reconstruction required. 4 | 5 | ### How To Use 6 | 7 | To run the conversion script, first make sure you have the latest `node-addon-api` in your `node_modules` directory. 8 | ``` 9 | npm install node-addon-api 10 | ``` 11 | 12 | Then run the script passing your project directory 13 | ``` 14 | node ./node_modules/node-addon-api/tools/conversion.js ./ 15 | ``` 16 | 17 | After finish, recompile and debug things that are missed by the script. 18 | 19 | 20 | ### Quick Fixes 21 | Here is the list of things that can be fixed easily. 22 | 1. Change your methods' return value to void if it doesn't return value to JavaScript. 23 | 2. Use `.` to access attribute or to invoke member function in Napi::Object instead of `->`. 24 | 3. `Napi::New(env, value);` to `Napi::[Type]::New(env, value); 25 | 26 | 27 | ### Major Reconstructions 28 | The implementation of `Napi::ObjectWrap` is significantly different from NAN's. `Napi::ObjectWrap` takes a pointer to the wrapped object and creates a reference to the wrapped object inside ObjectWrap constructor. `Napi::ObjectWrap` also associates wrapped object's instance methods to Javascript module instead of static methods like NAN. 29 | 30 | So if you use Nan::ObjectWrap in your module, you will need to execute the following steps. 31 | 32 | 1. Convert your [ClassName]::New function to a constructor function that takes a `Napi::CallbackInfo`. Declare it as 33 | ``` 34 | [ClassName](const Napi::CallbackInfo& info); 35 | ``` 36 | and define it as 37 | ``` 38 | [ClassName]::[ClassName](const Napi::CallbackInfo& info) : Napi::ObjectWrap<[ClassName]>(info){ 39 | ... 40 | } 41 | ``` 42 | This way, the `Napi::ObjectWrap` constructor will be invoked after the object has been instantiated and `Napi::ObjectWrap` can use the `this` pointer to create a reference to the wrapped object. 43 | 44 | 2. Move your original constructor code into the new constructor. Delete your original constructor. 45 | 3. In your class initialization function, associate native methods in the following way. The `&` character before methods is required because they are not static methods but instance methods. 46 | ``` 47 | Napi::FunctionReference constructor; 48 | 49 | void [ClassName]::Init(Napi::Env env, Napi::Object exports, Napi::Object module) { 50 | Napi::HandleScope scope(env); 51 | Napi::Function ctor = DefineClass(env, "Canvas", { 52 | InstanceMethod("Func1", &[ClassName]::Func1), 53 | InstanceMethod("Func2", &[ClassName]::Func2), 54 | InstanceAccessor("Value", &[ClassName]::ValueGetter), 55 | StaticMethod("MethodName", &[ClassName]::StaticMethod), 56 | InstanceValue("Value", Napi::[Type]::New(env, value)), 57 | }); 58 | 59 | constructor = Napi::Persistent(ctor); 60 | constructor .SuppressDestruct(); 61 | exports.Set("[ClassName]", ctor); 62 | } 63 | ``` 64 | 4. In function where you need to Unwrap the ObjectWrap in NAN like `[ClassName]* native = Nan::ObjectWrap::Unwrap<[ClassName]>(info.This());`, use `this` pointer directly as the unwrapped object as each ObjectWrap instance is associated with a unique object instance. 65 | 66 | 67 | If you still find issues after following this guide, please leave us an issue describing your problem and we will try to resolve it. 68 | -------------------------------------------------------------------------------- /deps/node-addon-api/tools/check-napi.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | // Descend into a directory structure and, for each file matching *.node, output 3 | // based on the imports found in the file whether it's an N-API module or not. 4 | 5 | const fs = require('fs'); 6 | const path = require('path'); 7 | const child_process = require('child_process'); 8 | 9 | // Read the output of the command, break it into lines, and use the reducer to 10 | // decide whether the file is an N-API module or not. 11 | function checkFile(file, command, argv, reducer) { 12 | const child = child_process.spawn(command, argv, { 13 | stdio: ['inherit', 'pipe', 'inherit'] 14 | }); 15 | let leftover = ''; 16 | let isNapi = undefined; 17 | child.stdout.on('data', (chunk) => { 18 | if (isNapi === undefined) { 19 | chunk = (leftover + chunk.toString()).split(/[\r\n]+/); 20 | leftover = chunk.pop(); 21 | isNapi = chunk.reduce(reducer, isNapi); 22 | if (isNapi !== undefined) { 23 | child.kill(); 24 | } 25 | } 26 | }); 27 | child.on('close', (code, signal) => { 28 | if ((code === null && signal !== null) || (code !== 0)) { 29 | console.log( 30 | command + ' exited with code: ' + code + ' and signal: ' + signal); 31 | } else { 32 | // Green if it's a N-API module, red otherwise. 33 | console.log( 34 | '\x1b[' + (isNapi ? '42' : '41') + 'm' + 35 | (isNapi ? ' N-API' : 'Not N-API') + 36 | '\x1b[0m: ' + file); 37 | } 38 | }); 39 | } 40 | 41 | // Use nm -a to list symbols. 42 | function checkFileUNIX(file) { 43 | checkFile(file, 'nm', ['-a', file], (soFar, line) => { 44 | if (soFar === undefined) { 45 | line = line.match(/([0-9a-f]*)? ([a-zA-Z]) (.*$)/); 46 | if (line[2] === 'U') { 47 | if (/^napi/.test(line[3])) { 48 | soFar = true; 49 | } 50 | } 51 | } 52 | return soFar; 53 | }); 54 | } 55 | 56 | // Use dumpbin /imports to list symbols. 57 | function checkFileWin32(file) { 58 | checkFile(file, 'dumpbin', ['/imports', file], (soFar, line) => { 59 | if (soFar === undefined) { 60 | line = line.match(/([0-9a-f]*)? +([a-zA-Z0-9]) (.*$)/); 61 | if (line && /^napi/.test(line[line.length - 1])) { 62 | soFar = true; 63 | } 64 | } 65 | return soFar; 66 | }); 67 | } 68 | 69 | // Descend into a directory structure and pass each file ending in '.node' to 70 | // one of the above checks, depending on the OS. 71 | function recurse(top) { 72 | fs.readdir(top, (error, items) => { 73 | if (error) { 74 | throw ("error reading directory " + top + ": " + error); 75 | } 76 | items.forEach((item) => { 77 | item = path.join(top, item); 78 | fs.stat(item, ((item) => (error, stats) => { 79 | if (error) { 80 | throw ("error about " + item + ": " + error); 81 | } 82 | if (stats.isDirectory()) { 83 | recurse(item); 84 | } else if (/[.]node$/.test(item) && 85 | // Explicitly ignore files called 'nothing.node' because they are 86 | // artefacts of node-addon-api having identified a version of 87 | // Node.js that ships with a correct implementation of N-API. 88 | path.basename(item) !== 'nothing.node') { 89 | process.platform === 'win32' ? 90 | checkFileWin32(item) : 91 | checkFileUNIX(item); 92 | } 93 | })(item)); 94 | }); 95 | }); 96 | } 97 | 98 | // Start with the directory given on the command line or the current directory 99 | // if nothing was given. 100 | recurse(process.argv.length > 3 ? process.argv[2] : '.'); 101 | -------------------------------------------------------------------------------- /lib/hive.js: -------------------------------------------------------------------------------- 1 | var native = process.iotjs ? require('../out/yoda-hive.node') : require('../build/Release/hive.node') 2 | var moduleNotFoundRE = /^Module not found:/ 3 | var resolve = process.iotjs 4 | ? function resolve (id, options) { 5 | var paths = [ process.cwd() ] 6 | if (options && options.paths) { 7 | paths = options.paths 8 | } 9 | var path = require('path') 10 | if (path.isAbsolute(id)) { 11 | return id 12 | } 13 | for (var idx in paths) { 14 | var it = paths[idx] 15 | var pp = path.resolve(it, id) 16 | try { 17 | require(pp) 18 | return pp 19 | } catch (e) { 20 | if (!moduleNotFoundRE.test(e.message)) { 21 | throw e 22 | } 23 | } 24 | } 25 | throw new Error('Module not found') 26 | } 27 | : require.resolve 28 | 29 | var onExitCallback 30 | native.onChildExit((pid, code, signal) => { 31 | onExitCallback(pid, code, signal) 32 | }) 33 | 34 | module.exports.fork = fork 35 | module.exports.kill = native.kill 36 | module.exports.onExit = onExit 37 | module.exports.stop = native.stop 38 | 39 | /** 40 | * 41 | * @param {string} cwd 42 | * @param {string[]} argv 43 | * @param {{[name: string]: string}} environs 44 | */ 45 | function fork (cwd, argv, environs) { 46 | var pid = native.fork(process) 47 | if (pid === 0) { 48 | forkMain(cwd, argv, environs) 49 | } 50 | return pid 51 | } 52 | 53 | /** 54 | * 55 | * @param {(pid: number, code: number, signal: number) => void} cb 56 | */ 57 | function onExit (cb) { 58 | onExitCallback = cb 59 | } 60 | 61 | function forkMain (cwd, argv, environs) { 62 | process.chdir(cwd) 63 | process.argv = process.argv.slice(0, 1) 64 | if (Array.isArray(argv)) { 65 | process.argv = process.argv.concat(argv) 66 | } 67 | process.env = Object.assign(process.env, environs) 68 | if (argv[0]) { 69 | var target = resolve(argv[0], { paths: [ cwd ] }) 70 | process.argv[1] = target 71 | require(target) 72 | } 73 | } 74 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "yoda-hive", 3 | "version": "1.0.0", 4 | "description": "", 5 | "main": "index.js", 6 | "scripts": { 7 | "build": "node-gyp rebuild", 8 | "test": "script/test" 9 | }, 10 | "author": "", 11 | "license": "Apache-2.0", 12 | "engines": { 13 | "shadow-node": "0.11.5" 14 | }, 15 | "dependencies": { 16 | "node-addon-api": "^1.6.3" 17 | }, 18 | "devDependencies": { 19 | "lodash": "^4.17.11", 20 | "standard": "^12.0.1" 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /script/apt-get-install-deps: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | set -ex 4 | 5 | sudo apt-key adv --fetch-keys http://dl.yarnpkg.com/debian/pubkey.gpg 6 | echo "deb http://dl.yarnpkg.com/debian/ stable main" | \ 7 | sudo tee /etc/apt/sources.list.d/yarn.list 8 | 9 | # Fingerprint: 6084 F3CF 814B 57C1 CF12 EFD5 15CF 4D18 AF4F 7421 10 | wget -O - https://apt.llvm.org/llvm-snapshot.gpg.key | sudo apt-key add - 11 | echo " 12 | deb http://apt.llvm.org/trusty/ llvm-toolchain-trusty main 13 | deb-src http://apt.llvm.org/trusty/ llvm-toolchain-trusty main 14 | deb http://apt.llvm.org/trusty/ llvm-toolchain-trusty-8 main 15 | deb-src http://apt.llvm.org/trusty/ llvm-toolchain-trusty-8 main 16 | " | sudo tee /etc/apt/sources.list.d/llvm.list 17 | 18 | sudo add-apt-repository -y ppa:ubuntu-toolchain-r/test 19 | 20 | sudo apt-get update -q 21 | sudo apt-get install -q -y --allow-unauthenticated \ 22 | cmake \ 23 | clang-format-8 \ 24 | build-essential \ 25 | jq \ 26 | yarn 27 | 28 | sudo ln -s /usr/bin/clang-format-8 /usr/bin/clang-format-8.0 29 | -------------------------------------------------------------------------------- /script/install-shadow-node: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | set -ex 3 | 4 | shadow_node_version=`cat package.json | jq -r '.engines."shadow-node"'` 5 | url="https://github.com/yodaos-project/ShadowNode/releases/download/v$shadow_node_version/shadow-node-v$shadow_node_version-$(uname)-$(uname -m).tar.gz" 6 | file_name="shadow-node-v$shadow_node_version-$(uname)-$(uname -m).tar.gz" 7 | 8 | cd /tmp 9 | wget $url 10 | tar -xzf $file_name 11 | sudo cp ./usr/bin/iotjs /usr/local/bin 12 | cd - 13 | 14 | type iotjs 15 | iotjs --version || true 16 | -------------------------------------------------------------------------------- /script/test: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | help=" 4 | script/test 5 | 6 | --exec node or node variant executable path 7 | --fail-fast fail immediately on first error 8 | -h,--help show this message 9 | " 10 | 11 | exec="node" 12 | while [ $# -gt 0 ]; do 13 | case "$1" in 14 | --exec) 15 | exec="$2" 16 | shift 17 | ;; 18 | --fail-fast) 19 | set -e 20 | ;; 21 | -h|--help) 22 | printf "$help" 23 | exit 24 | ;; 25 | --*) 26 | echo "Illegal option $1" 27 | ;; 28 | esac 29 | shift $(( $# > 0 ? 1 : 0 )) 30 | done 31 | 32 | set -x 33 | tests=`find . -name '*.test.js'` 34 | failed=0 35 | for it in $tests; do 36 | echo $it 37 | command $exec $it 38 | status=$? 39 | printf "# $it : $status\n" 40 | if test $status -gt 0; then 41 | failed=`expr $failed + 1` 42 | fi 43 | done 44 | 45 | if test $failed -gt 0; then 46 | exit 1 47 | fi 48 | -------------------------------------------------------------------------------- /src/hive.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #define NODE_ADDON_API_DISABLE_DEPRECATED 4 | #define NAPI_EXPERIMENTAL 5 | #define NAPI_VERSION 4 6 | #include "napi.h" 7 | #include "uv.h" 8 | 9 | Napi::Value Fork(const Napi::CallbackInfo& info); 10 | Napi::Value Kill(const Napi::CallbackInfo& info); 11 | Napi::Value OnChildExit(const Napi::CallbackInfo& info); 12 | Napi::Value Stop(const Napi::CallbackInfo& info); 13 | void hive__chld(uv_signal_t* handle, int signal); 14 | -------------------------------------------------------------------------------- /test/child-exit-code.test.skip.js: -------------------------------------------------------------------------------- 1 | var assert = require('assert') 2 | var helper = require('./helper') 3 | 4 | var hive = require('../lib/hive') 5 | 6 | var parent = process.pid 7 | var pid 8 | hive.onExit(helper.mustCall((_pid, code, signal) => { 9 | assert.strictEqual(_pid, pid) 10 | assert.strictEqual(code, 2) 11 | assert.strictEqual(signal, 0) 12 | hive.stop() 13 | }, parent)) 14 | 15 | pid = hive.fork(__dirname, ['./children/exit-next-tick', '2']) 16 | -------------------------------------------------------------------------------- /test/children/alive.js: -------------------------------------------------------------------------------- 1 | setInterval(() => { 2 | console.log('Still alive') 3 | }, 1000) 4 | -------------------------------------------------------------------------------- /test/children/exit-next-tick.js: -------------------------------------------------------------------------------- 1 | var exitCode = Number(process.argv[2]) 2 | if (!Number.isInteger(exitCode)) { 3 | process.abort() 4 | } 5 | process.nextTick(() => { 6 | process.exit(exitCode) 7 | }) 8 | -------------------------------------------------------------------------------- /test/fork-child-process.test.js: -------------------------------------------------------------------------------- 1 | var assert = require('assert') 2 | var helper = require('./helper') 3 | var hive = require('../lib/hive') 4 | 5 | var SIGINT = 2 6 | var pid 7 | 8 | hive.onExit(helper.mustCall((_pid, code, signal) => { 9 | assert.strictEqual(_pid, pid) 10 | assert.strictEqual(code, 0) 11 | assert.strictEqual(signal, SIGINT) 12 | hive.stop() 13 | })) 14 | 15 | pid = hive.fork(__dirname, ['./children/alive']) 16 | if (pid > 0) { 17 | setTimeout(() => { 18 | hive.kill(pid, SIGINT) 19 | }, 2000) 20 | } 21 | -------------------------------------------------------------------------------- /test/helper/index.js: -------------------------------------------------------------------------------- 1 | module.exports.mustCall = mustCall 2 | function mustCall (callback) { 3 | var stack = new Error().stack 4 | var called = false 5 | var pid = process.pid 6 | process.on('exit', () => { 7 | if (process.pid !== pid) { 8 | return 9 | } 10 | if (!called) { 11 | var err = new Error(`Callback was not called on process(${pid})`) 12 | err.stack = stack 13 | throw err 14 | } 15 | }) 16 | 17 | return function wrap () { 18 | called = true 19 | callback.apply(this, arguments) 20 | } 21 | } 22 | --------------------------------------------------------------------------------