diff --git a/.eslintrc.js b/.eslintrc.js deleted file mode 100644 index edc9cc529..000000000 --- a/.eslintrc.js +++ /dev/null @@ -1,6 +0,0 @@ -module.exports = { - parserOptions: { - sourceType: 'script' - }, - extends: ['semistandard'] -}; diff --git a/.github/dependabot.yml b/.github/dependabot.yml new file mode 100644 index 000000000..a420a61ab --- /dev/null +++ b/.github/dependabot.yml @@ -0,0 +1,28 @@ +version: 2 +updates: + - package-ecosystem: github-actions + directory: / + schedule: + interval: weekly + groups: + all: + patterns: + - '*' + + - package-ecosystem: npm + directory: / + schedule: + interval: weekly + groups: + all: + patterns: + - '*' + + - package-ecosystem: npm + directory: /test/addon_build/tpl + schedule: + interval: weekly + groups: + all: + patterns: + - '*' diff --git a/.github/workflows/ci-win.yml b/.github/workflows/ci-win.yml index 183d29e3b..3bd60207a 100644 --- a/.github/workflows/ci-win.yml +++ b/.github/workflows/ci-win.yml @@ -2,21 +2,57 @@ name: Node.js CI Windows Platform on: [push, pull_request] +env: + PYTHON_VERSION: '3.11' + +permissions: + contents: read + jobs: test: - timeout-minutes: 30 + timeout-minutes: 60 strategy: + fail-fast: false matrix: - node-version: [14.x, 16.x, 18.x] + api_version: + - standard + - experimental + node-version: + - 20.x + - 22.x + - 24.x + - 25.x + - 26.x + architecture: [x64, x86] os: - - windows-2019 + - windows-2022 + - windows-2025 + exclude: + # Skip when node 24.x or 25.x AND architecture is x86 since there is + # no published Node.js x86 build for those versions. + - node-version: 24.x + architecture: x86 + - node-version: 25.x + architecture: x86 + - node-version: 26.x + architecture: x86 runs-on: ${{ matrix.os }} steps: - - uses: actions/checkout@v3 + - name: Harden Runner + uses: step-security/harden-runner@58077d3c7e43986b6b15fba718e8ea69e387dfcc # v2.15.1 + with: + egress-policy: audit + + - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + - name: Set up Python ${{ env.PYTHON_VERSION }} + uses: actions/setup-python@a309ff8b426b58ec0e2a45f0f869d46889d02405 # v6.2.0 + with: + python-version: ${{ env.PYTHON_VERSION }} - name: Use Node.js ${{ matrix.node-version }} - uses: actions/setup-node@v3 + uses: actions/setup-node@53b83947a5a98c8d113130e565377fae1a50d02f # v6.3.0 with: node-version: ${{ matrix.node-version }} + architecture: ${{ matrix.architecture }} - name: Check Node.js installation run: | node --version @@ -24,7 +60,18 @@ jobs: - name: Install dependencies run: | npm install + # node-gyp@12 (from package.json) supports Visual Studio 2026, but only + # node-gyp@13 emits the linker options that Node.js 26 builds require + # (older node-gyp trips LNK1117 on '/opt:lldltojobs'). Upgrade in place for + # Node.js >= 26; other versions keep node-gyp@12. + - name: Use node-gyp@13 for Node.js >= 26 + if: matrix.node-version == '26.x' + run: npm install --no-save node-gyp@13 - name: npm test + shell: bash run: | + if [ "${{ matrix.api_version }}" = "experimental" ]; then + export NAPI_VERSION=2147483647 + fi npm run pretest -- --verbose node test diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 00f3d3aa5..c583b8c8e 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -2,30 +2,50 @@ name: Node.js CI Unix Platform on: [push, pull_request] +env: + PYTHON_VERSION: '3.11' + +permissions: + contents: read + jobs: test: - timeout-minutes: 30 + timeout-minutes: 60 strategy: + fail-fast: false matrix: - node-version: [14.x, 16.x, 18.x] - compiler: - - gcc - - clang + api_version: + - standard + - experimental + node-version: + - 20.x + - 22.x + - 24.x + - 25.x + - 26.x os: - - ubuntu-latest - macos-latest + - ubuntu-latest + compiler: + - clang + - gcc + exclude: + - os: macos-latest + compiler: gcc # GCC is an alias for clang on the MacOS image. runs-on: ${{ matrix.os }} steps: - - uses: actions/checkout@v3 - - name: Install system dependencies - run: | - if [ "${{ matrix.compiler }}" = "gcc" -a "${{ matrix.os }}" = ubuntu-* ]; then - sudo add-apt-repository ppa:ubuntu-toolchain-r/test - sudo apt-get update - sudo apt-get install g++-6.5 - fi + - name: Harden Runner + uses: step-security/harden-runner@58077d3c7e43986b6b15fba718e8ea69e387dfcc # v2.15.1 + with: + egress-policy: audit + + - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + - name: Set up Python ${{ env.PYTHON_VERSION }} + uses: actions/setup-python@a309ff8b426b58ec0e2a45f0f869d46889d02405 # v6.2.0 + with: + python-version: ${{ env.PYTHON_VERSION }} - name: Use Node.js ${{ matrix.node-version }} - uses: actions/setup-node@v3 + uses: actions/setup-node@53b83947a5a98c8d113130e565377fae1a50d02f # v6.3.0 with: node-version: ${{ matrix.node-version }} - name: Check Node.js installation @@ -35,17 +55,27 @@ jobs: - name: Install dependencies run: | npm install + # Node.js >= 26 requires node-gyp@13; older versions keep node-gyp@12 + # (from package.json). + - name: Use node-gyp@13 for Node.js >= 26 + if: matrix.node-version == '26.x' + run: npm install --no-save node-gyp@13 - name: npm test run: | + if [ "${{ matrix.api_version }}" = "experimental" ]; then + export NAPI_VERSION=2147483647 + fi if [ "${{ matrix.compiler }}" = "gcc" ]; then export CC="gcc" CXX="g++" fi - if [ "${{ matrix.compiler }}" = "gcc" -a "${{ matrix.os }}" = ubuntu-* ]; then - export CC="gcc-6.5" CXX="g++-6.5" AR="gcc-ar-6.5" RANLIB="gcc-ranlib-6.5" NM="gcc-nm-6.5" - fi if [ "${{ matrix.compiler }}" = "clang" ]; then export CC="clang" CXX="clang++" fi + echo "CC=\"$CC\" CXX=\"$CXX\"" + echo "$CC --version" + $CC --version + echo "$CXX --version" + $CXX --version export CFLAGS="$CFLAGS -O3 --coverage" LDFLAGS="$LDFLAGS --coverage" echo "CFLAGS=\"$CFLAGS\" LDFLAGS=\"$LDFLAGS\"" npm run pretest -- --verbose diff --git a/.github/workflows/codeql.yml b/.github/workflows/codeql.yml new file mode 100644 index 000000000..8758fdcef --- /dev/null +++ b/.github/workflows/codeql.yml @@ -0,0 +1,85 @@ +# For most projects, this workflow file will not need changing; you simply need +# to commit it to your repository. +# +# You may wish to alter this file to override the set of languages analyzed, +# or to provide custom queries or build logic. +# +# ******** NOTE ******** +# We have attempted to detect the languages in your repository. Please check +# the `language` matrix defined below to confirm you have the correct set of +# supported CodeQL languages. +# +name: "CodeQL" + +on: + push: + branches: ["main"] + pull_request: + # The branches below must be a subset of the branches above + branches: ["main"] + schedule: + - cron: "0 0 * * 1" + +permissions: + contents: read + +jobs: + analyze: + name: Analyze + runs-on: ubuntu-latest + permissions: + actions: read + contents: read + security-events: write + + strategy: + fail-fast: false + matrix: + language: ["cpp", "javascript"] + # CodeQL supports [ $supported-codeql-languages ] + # Learn more about CodeQL language support at https://aka.ms/codeql-docs/language-support + + steps: + - name: Harden Runner + uses: step-security/harden-runner@58077d3c7e43986b6b15fba718e8ea69e387dfcc # v2.15.1 + with: + egress-policy: audit # TODO: change to 'egress-policy: block' after couple of runs + + - name: Checkout repository + uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + + # Initializes the CodeQL tools for scanning. + - name: Initialize CodeQL + uses: github/codeql-action/init@0d579ffd059c29b07949a3cce3983f0780820c98 # v4.32.6 + with: + languages: ${{ matrix.language }} + # If you wish to specify custom queries, you can do so here or in a config file. + # By default, queries listed here will override any specified in a config file. + # Prefix the list here with "+" to use these queries and those in the config file. + + # Autobuild attempts to build any compiled languages (C/C++, C#, or Java). + # If this step fails, then you should remove it and run the build manually (see below) + # - name: Autobuild + # uses: github/codeql-action/autobuild@7df0ce34898d659f95c0c4a09eaa8d4e32ee64db # v2.2.12 + + # ℹ️ Command-line programs to run using the OS shell. + # 📚 See https://docs.github.com/en/actions/using-workflows/workflow-syntax-for-github-actions#jobsjob_idstepsrun + + # If the Autobuild fails above, remove it and uncomment the following three lines. + # modify them (or add more) to build your code if your project, please refer to the EXAMPLE below for guidance. + + - name: Use Node.js v18.x + if: matrix.language == 'cpp' + uses: actions/setup-node@53b83947a5a98c8d113130e565377fae1a50d02f # v6.3.0 + with: + node-version: 18.x + + - name: Build cpp + if: matrix.language == 'cpp' + run: | + npx node-gyp rebuild -C test + + - name: Perform CodeQL Analysis + uses: github/codeql-action/analyze@0d579ffd059c29b07949a3cce3983f0780820c98 # v4.32.6 + with: + category: "/language:${{matrix.language}}" diff --git a/.github/workflows/coverage-linux.yml b/.github/workflows/coverage-linux.yml new file mode 100644 index 000000000..3d116e405 --- /dev/null +++ b/.github/workflows/coverage-linux.yml @@ -0,0 +1,68 @@ +name: Coverage Linux + +on: + pull_request: + types: [opened, synchronize, reopened] + paths-ignore: + - '**.md' + - benchmark/** + - doc/** + - tools/** + - unit-test/** + - .github/** + - '!.github/workflows/coverage-linux.yml' + push: + branches: + - main + paths-ignore: + - '**.md' + - benchmark/** + - doc/** + - tools/** + - unit-test/** + - .github/** + - '!.github/workflows/coverage-linux.yml' + +env: + PYTHON_VERSION: '3.11' + NODE_VERSION: '22.x' + +permissions: + contents: read + +jobs: + coverage-linux: + runs-on: ubuntu-latest + steps: + - name: Harden Runner + uses: step-security/harden-runner@58077d3c7e43986b6b15fba718e8ea69e387dfcc # v2.15.1 + with: + egress-policy: audit + + - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + with: + persist-credentials: false + - name: Set up Python ${{ env.PYTHON_VERSION }} + uses: actions/setup-python@a309ff8b426b58ec0e2a45f0f869d46889d02405 # v6.2.0 + with: + python-version: ${{ env.PYTHON_VERSION }} + - name: Use Node.js ${{ env.NODE_VERSION }} + uses: actions/setup-node@53b83947a5a98c8d113130e565377fae1a50d02f # v6.3.0 + with: + node-version: ${{ env.NODE_VERSION }} + - name: Environment Information + run: npx envinfo + - name: Install gcovr + run: pip install gcovr==6.0 + - name: Install dependencies + run: npm install + - name: Test with coverage + run: | + npm run create-coverage + - name: Generate coverage report (XML) + run: | + npm run report-coverage-xml + - name: Upload + uses: codecov/codecov-action@671740ac38dd9b0130fbe1cec585b89eea48d3de # v5.5.2 + with: + directory: ./coverage-xml diff --git a/.github/workflows/dependency-review.yml b/.github/workflows/dependency-review.yml new file mode 100644 index 000000000..8d6513bed --- /dev/null +++ b/.github/workflows/dependency-review.yml @@ -0,0 +1,27 @@ +# Dependency Review Action +# +# This Action will scan dependency manifest files that change as part of a Pull Request, +# surfacing known-vulnerable versions of the packages declared or updated in the PR. +# Once installed, if the workflow run is marked as required, +# PRs introducing known-vulnerable packages will be blocked from merging. +# +# Source repository: https://github.com/actions/dependency-review-action +name: 'Dependency Review' +on: [pull_request] + +permissions: + contents: read + +jobs: + dependency-review: + runs-on: ubuntu-latest + steps: + - name: Harden Runner + uses: step-security/harden-runner@58077d3c7e43986b6b15fba718e8ea69e387dfcc # v2.15.1 + with: + egress-policy: audit # TODO: change to 'egress-policy: block' after couple of runs + + - name: 'Checkout Repository' + uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + - name: 'Dependency Review' + uses: actions/dependency-review-action@2031cfc080254a8a887f58cffee85186f0e49e48 # v4.9.0 diff --git a/.github/workflows/linter.yml b/.github/workflows/linter.yml index f434d19d9..578223b8e 100644 --- a/.github/workflows/linter.yml +++ b/.github/workflows/linter.yml @@ -2,22 +2,37 @@ name: Style Checks on: [push, pull_request] +env: + PYTHON_VERSION: '3.11' + +permissions: + contents: read + jobs: lint: if: github.repository == 'nodejs/node-addon-api' strategy: matrix: - node-version: [16.x] + node-version: [22.x] os: [ubuntu-latest] runs-on: ${{ matrix.os }} steps: - - uses: actions/checkout@v3 + - name: Harden Runner + uses: step-security/harden-runner@58077d3c7e43986b6b15fba718e8ea69e387dfcc # v2.15.1 + with: + egress-policy: audit + + - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 with: fetch-depth: 0 - run: git branch -a + - name: Set up Python ${{ env.PYTHON_VERSION }} + uses: actions/setup-python@a309ff8b426b58ec0e2a45f0f869d46889d02405 # v6.2.0 + with: + python-version: ${{ env.PYTHON_VERSION }} - name: Use Node.js ${{ matrix.node-version }} - uses: actions/setup-node@v3 + uses: actions/setup-node@53b83947a5a98c8d113130e565377fae1a50d02f # v6.3.0 with: node-version: ${{ matrix.node-version }} - run: npm install diff --git a/.github/workflows/node-api-headers.yml b/.github/workflows/node-api-headers.yml new file mode 100644 index 000000000..59c686348 --- /dev/null +++ b/.github/workflows/node-api-headers.yml @@ -0,0 +1,71 @@ +name: Node.js CI with node-api-headers + +on: [push, pull_request] + +env: + PYTHON_VERSION: '3.11' + +permissions: + contents: read + +jobs: + test: + timeout-minutes: 30 + strategy: + fail-fast: false + matrix: + api_version: + - '9' + node-version: + - 22.x + node-api-headers-version: + - '1.1.0' + - '1.2.0' + - '1.3.0' + os: + - ubuntu-latest + compiler: + - gcc + - clang + runs-on: ${{ matrix.os }} + steps: + - name: Harden Runner + uses: step-security/harden-runner@58077d3c7e43986b6b15fba718e8ea69e387dfcc # v2.15.1 + with: + egress-policy: audit + + - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + - name: Set up Python ${{ env.PYTHON_VERSION }} + uses: actions/setup-python@a309ff8b426b58ec0e2a45f0f869d46889d02405 # v6.2.0 + with: + python-version: ${{ env.PYTHON_VERSION }} + - name: Use Node.js ${{ matrix.node-version }} + uses: actions/setup-node@53b83947a5a98c8d113130e565377fae1a50d02f # v6.3.0 + with: + node-version: ${{ matrix.node-version }} + - name: Check Node.js installation + run: | + node --version + npm --version + - name: Install dependencies + run: | + npm install + npm install "node-api-headers@${{ matrix.node-api-headers-version }}" + - name: npm test + run: | + export NAPI_VERSION=${{ matrix.api_version }} + if [ "${{ matrix.compiler }}" = "gcc" ]; then + export CC="gcc" CXX="g++" + fi + if [ "${{ matrix.compiler }}" = "clang" ]; then + export CC="clang" CXX="clang++" + fi + echo "CC=\"$CC\" CXX=\"$CXX\"" + echo "$CC --version" + $CC --version + echo "$CXX --version" + $CXX --version + export CFLAGS="$CFLAGS -O3 --coverage" LDFLAGS="$LDFLAGS --coverage" + export use_node_api_headers=true + echo "CFLAGS=\"$CFLAGS\" LDFLAGS=\"$LDFLAGS\"" + npm run pretest -- --verbose diff --git a/.github/workflows/release-please.yml b/.github/workflows/release-please.yml new file mode 100644 index 000000000..a6f09719a --- /dev/null +++ b/.github/workflows/release-please.yml @@ -0,0 +1,51 @@ +name: release-please + +on: + push: + branches: + - main + workflow_dispatch: + +permissions: + id-token: write # Required for OIDC + contents: read + +jobs: + release-please: + runs-on: ubuntu-latest + outputs: + release_created: ${{ steps.release.outputs.release_created }} + permissions: + contents: write + pull-requests: write + steps: + - name: Harden Runner + uses: step-security/harden-runner@58077d3c7e43986b6b15fba718e8ea69e387dfcc # v2.15.1 + with: + egress-policy: audit + + - uses: googleapis/release-please-action@16a9c90856f42705d54a6fda1823352bdc62cf38 # v4.4.0 + id: release + with: + config-file: release-please-config.json + manifest-file: .release-please-manifest.json + + npm-publish: + needs: release-please + if: ${{ needs.release-please.outputs.release_created }} + runs-on: ubuntu-latest + permissions: + contents: read + id-token: write + steps: + - name: Harden Runner + uses: step-security/harden-runner@58077d3c7e43986b6b15fba718e8ea69e387dfcc # v2.15.1 + with: + egress-policy: audit + + - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + - uses: actions/setup-node@53b83947a5a98c8d113130e565377fae1a50d02f # v6.3.0 + with: + node-version: 24 # npm >= 11.5.1 + registry-url: 'https://registry.npmjs.org' + - run: npm publish --provenance --access public diff --git a/.github/workflows/scorecards.yml b/.github/workflows/scorecards.yml new file mode 100644 index 000000000..d902982dc --- /dev/null +++ b/.github/workflows/scorecards.yml @@ -0,0 +1,76 @@ +# This workflow uses actions that are not certified by GitHub. They are provided +# by a third-party and are governed by separate terms of service, privacy +# policy, and support documentation. + +name: Scorecard supply-chain security +on: + # For Branch-Protection check. Only the default branch is supported. See + # https://github.com/ossf/scorecard/blob/main/docs/checks.md#branch-protection + branch_protection_rule: + # To guarantee Maintained check is occasionally updated. See + # https://github.com/ossf/scorecard/blob/main/docs/checks.md#maintained + schedule: + - cron: '20 7 * * 2' + push: + branches: ["main"] + +# Declare default permissions as read only. +permissions: read-all + +jobs: + analysis: + name: Scorecard analysis + runs-on: ubuntu-latest + permissions: + # Needed to upload the results to code-scanning dashboard. + security-events: write + # Needed to publish results and get a badge (see publish_results below). + id-token: write + contents: read + actions: read + + steps: + - name: Harden Runner + uses: step-security/harden-runner@58077d3c7e43986b6b15fba718e8ea69e387dfcc # v2.15.1 + with: + egress-policy: audit # TODO: change to 'egress-policy: block' after couple of runs + + - name: "Checkout code" + uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + with: + persist-credentials: false + + - name: "Run analysis" + uses: ossf/scorecard-action@4eaacf0543bb3f2c246792bd56e8cdeffafb205a # v2.4.3 + with: + results_file: results.sarif + results_format: sarif + # (Optional) "write" PAT token. Uncomment the `repo_token` line below if: + # - you want to enable the Branch-Protection check on a *public* repository, or + # - you are installing Scorecards on a *private* repository + # To create the PAT, follow the steps in https://github.com/ossf/scorecard-action#authentication-with-pat. + # repo_token: ${{ secrets.SCORECARD_TOKEN }} + + # Public repositories: + # - Publish results to OpenSSF REST API for easy access by consumers + # - Allows the repository to include the Scorecard badge. + # - See https://github.com/ossf/scorecard-action#publishing-results. + # For private repositories: + # - `publish_results` will always be set to `false`, regardless + # of the value entered here. + publish_results: true + + # Upload the results as artifacts (optional). Commenting out will disable uploads of run results in SARIF + # format to the repository Actions tab. + - name: "Upload artifact" + uses: actions/upload-artifact@bbbca2ddaa5d8feaa63e36b76fdaad77386f024f # v7.0.0 + with: + name: SARIF file + path: results.sarif + retention-days: 5 + + # Upload the results to GitHub's code scanning dashboard. + - name: "Upload to code-scanning" + uses: github/codeql-action/upload-sarif@0d579ffd059c29b07949a3cce3983f0780820c98 # v4.32.6 + with: + sarif_file: results.sarif diff --git a/.github/workflows/stale.yml b/.github/workflows/stale.yml index 10b7d3b2c..7554cf154 100644 --- a/.github/workflows/stale.yml +++ b/.github/workflows/stale.yml @@ -3,16 +3,27 @@ on: schedule: - cron: "0 0 * * *" +permissions: + contents: read + jobs: stale: + permissions: + issues: write # for actions/stale to close stale issues + pull-requests: write # for actions/stale to close stale PRs runs-on: ubuntu-latest steps: - - uses: actions/stale@v5 + - name: Harden Runner + uses: step-security/harden-runner@58077d3c7e43986b6b15fba718e8ea69e387dfcc # v2.15.1 + with: + egress-policy: audit + + - uses: actions/stale@b5d41d4e1d5dceea10e7104786b73624c18a190f # v10.2.0 with: repo-token: ${{ secrets.GITHUB_TOKEN }} stale-issue-message: 'This issue is stale because it has been open many days with no activity. It will be closed soon unless the stale label is removed or a comment is made.' stale-issue-label: 'stale' - exempt-issue-label: 'never stale' + exempt-issue-labels: 'never-stale' days-before-stale: 90 days-before-close: 30 diff --git a/.gitignore b/.gitignore index b1233109f..a154db646 100644 --- a/.gitignore +++ b/.gitignore @@ -3,4 +3,20 @@ /benchmark/build /benchmark/src /test/addon_build/addons +/test/require_basic_finalizers/addons /.vscode + +# ignore node-gyp generated files outside its build directory +/test/*.Makefile +/test/*.mk + +# ignore node-gyp generated Visual Studio files +*.vcxproj +*.vcxproj.filters +*.vcxproj.user +*.vsidx +*.sln +*.suo +/test/.vs/ +/test/Release/ +/test/Debug/ diff --git a/.release-please-manifest.json b/.release-please-manifest.json new file mode 100644 index 000000000..b6df5aa29 --- /dev/null +++ b/.release-please-manifest.json @@ -0,0 +1,3 @@ +{ + ".": "8.9.2" +} diff --git a/CHANGELOG.md b/CHANGELOG.md index 562a2cc3f..afe8fd559 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,415 @@ # node-addon-api Changelog +## [8.9.2](https://github.com/nodejs/node-addon-api/compare/v8.9.1...v8.9.2) (2026-08-10) + + +### Bug Fixes + +* resolve Symbol::For overload ambiguity ([#1742](https://github.com/nodejs/node-addon-api/issues/1742)) ([13c854a](https://github.com/nodejs/node-addon-api/commit/13c854a1f57e754e5082a1961e0d32e8f0f96543)) + +## [8.9.1](https://github.com/nodejs/node-addon-api/compare/v8.9.0...v8.9.1) (2026-07-31) + + +### Bug Fixes + +* fix vs2026 ICE compatibility ([#1739](https://github.com/nodejs/node-addon-api/issues/1739)) ([7223518](https://github.com/nodejs/node-addon-api/commit/722351807e21eaada1df16de1e959006c907a031)) + +## [8.9.0](https://github.com/nodejs/node-addon-api/compare/v8.8.0...v8.9.0) (2026-05-24) + + +### Features + +* add support for SharedArrayBuffer in TypedArray and TypedArrayOf<T> ([#1731](https://github.com/nodejs/node-addon-api/issues/1731)) ([00b95ef](https://github.com/nodejs/node-addon-api/commit/00b95efea6522980e9661a729a59b926ecf5c6b6)) + +## [8.8.0](https://github.com/nodejs/node-addon-api/compare/v8.7.0...v8.8.0) (2026-05-13) + + +### Features + +* add std::string_view overload for Symbol::For ([#1722](https://github.com/nodejs/node-addon-api/issues/1722)) ([f65113b](https://github.com/nodejs/node-addon-api/commit/f65113b6ce54271b0a26f97fc624b5574b64a048)) +* add String::New overload for string_view ([#1706](https://github.com/nodejs/node-addon-api/issues/1706)) ([0add130](https://github.com/nodejs/node-addon-api/commit/0add1306f60b81432da94d13683aa0b06aa52925)) + +## [8.7.0](https://github.com/nodejs/node-addon-api/compare/v8.6.0...v8.7.0) (2026-03-23) + + +### Features + +* add Date::New overload for a std::chrono::system_clock::time_point ([#1705](https://github.com/nodejs/node-addon-api/issues/1705)) ([7fb063d](https://github.com/nodejs/node-addon-api/commit/7fb063d95ff5ef816d1616f9acf4afac854cfd4c)) +* add Object::GetPrototype and Object::SetPrototype ([#1715](https://github.com/nodejs/node-addon-api/issues/1715)) ([967bbd5](https://github.com/nodejs/node-addon-api/commit/967bbd5911c7e90b428d4769b9ab1b1a0cee4451)), closes [#1691](https://github.com/nodejs/node-addon-api/issues/1691) +* add support for SharedArrayBuffer in DataViews ([#1714](https://github.com/nodejs/node-addon-api/issues/1714)) ([7b8d69e](https://github.com/nodejs/node-addon-api/commit/7b8d69e0ba912291aea0b337f7f1814b1032f7f0)) + + +### Bug Fixes + +* add missing const to ObjectReference::Set string parameter ([#1713](https://github.com/nodejs/node-addon-api/issues/1713)) ([845ba8e](https://github.com/nodejs/node-addon-api/commit/845ba8e4b0888ca20ed3f7c95f9d461cbce338c5)) +* fix -Wextra-semi ([#1718](https://github.com/nodejs/node-addon-api/issues/1718)) ([7fef973](https://github.com/nodejs/node-addon-api/commit/7fef9739166ebb89263459e9f4c3363678cd6367)) + +## [8.6.0](https://github.com/nodejs/node-addon-api/compare/v8.5.0...v8.6.0) (2026-01-30) + + +### Features + +* add SharedArrayBuffer ([#1688](https://github.com/nodejs/node-addon-api/issues/1688)) ([220bee2](https://github.com/nodejs/node-addon-api/commit/220bee244fae2e36405bf2bda33cb3985a846912)) +* silence a legitimate vfptr sanitizer warning that is on by default in Android NDK 29 ([#1692](https://github.com/nodejs/node-addon-api/issues/1692)) ([46673f4](https://github.com/nodejs/node-addon-api/commit/46673f403adf799cc73419427dd3cf166badff22)) + +## [8.5.0](https://github.com/nodejs/node-addon-api/compare/v8.4.0...v8.5.0) (2025-07-04) + + +### Features + +* add Then and Catch methods to Promise ([#1668](https://github.com/nodejs/node-addon-api/issues/1668)) ([ab3e5fe](https://github.com/nodejs/node-addon-api/commit/ab3e5fe59570cbb5ed7cc9891b3f25fe373f028f)) + +## [8.4.0](https://github.com/nodejs/node-addon-api/compare/v8.3.1...v8.4.0) (2025-06-11) + + +### Features + +* add sugar method for PropertyLValue ([#1651](https://github.com/nodejs/node-addon-api/issues/1651)) ([#1655](https://github.com/nodejs/node-addon-api/issues/1655)) ([1e57a0a](https://github.com/nodejs/node-addon-api/commit/1e57a0ae82786c320c784ec6b67f357c85733132)) + +## [8.3.1](https://github.com/nodejs/node-addon-api/compare/v8.3.0...v8.3.1) (2025-02-18) + + +### Bug Fixes + +* add missing `stdexcept` include to test ([#1634](https://github.com/nodejs/node-addon-api/issues/1634)) ([14c1a4f](https://github.com/nodejs/node-addon-api/commit/14c1a4f28278c5b02d0ea910061aad4312bb701e)) +* node-api version 10 support ([#1641](https://github.com/nodejs/node-addon-api/issues/1641)) ([932ad15](https://github.com/nodejs/node-addon-api/commit/932ad1503f7a3402716178a91879b5ab850a61b0)) + +## [8.3.0](https://github.com/nodejs/node-addon-api/compare/v8.2.2...v8.3.0) (2024-11-29) + + +### Features + +* allow catching all exceptions ([#1593](https://github.com/nodejs/node-addon-api/issues/1593)) ([c679f6f](https://github.com/nodejs/node-addon-api/commit/c679f6f4c9dc6bf9fc0d99cbe5982bd24a5e2c7b)) + +## [8.2.2](https://github.com/nodejs/node-addon-api/compare/v8.2.1...v8.2.2) (2024-11-07) + + +### Bug Fixes + +* mark external memory and version APIs as basic ([#1597](https://github.com/nodejs/node-addon-api/issues/1597)) ([78da4fa](https://github.com/nodejs/node-addon-api/commit/78da4fa2251af1e4de16efac94d92388f117ae6e)) +* missing napi_delete_reference on ObjectWrap ref ([#1607](https://github.com/nodejs/node-addon-api/issues/1607)) ([98aae33](https://github.com/nodejs/node-addon-api/commit/98aae3343c3af36b4befd6b67c4cb19ba49b8d20)) + +## [8.2.1](https://github.com/nodejs/node-addon-api/compare/v8.2.0...v8.2.1) (2024-10-09) + + +### Bug Fixes + +* failed type cast checks in Symbol::WellKnown ([#1581](https://github.com/nodejs/node-addon-api/issues/1581)) ([d8523a7](https://github.com/nodejs/node-addon-api/commit/d8523a708030a0a3abb9d7832051c70e2dafac3d)) +* missing node_api_nogc_env definition ([#1585](https://github.com/nodejs/node-addon-api/issues/1585)) ([6ba3891](https://github.com/nodejs/node-addon-api/commit/6ba3891954d8b56215d133e54a86cb621e476b9e)) + +## [8.2.0](https://github.com/nodejs/node-addon-api/compare/v8.1.0...v8.2.0) (2024-09-19) + + +### Features + +* add support for nogc types via `BasicEnv` ([#1514](https://github.com/nodejs/node-addon-api/issues/1514)) ([b4aeecb](https://github.com/nodejs/node-addon-api/commit/b4aeecb046480eeaaf1c578a140f71ac0e77094f)) +* add support for requiring basic finalizers ([#1568](https://github.com/nodejs/node-addon-api/issues/1568)) ([7bcb826](https://github.com/nodejs/node-addon-api/commit/7bcb826aa4323f450b3c58f9c7fb34243ff13f77)) + + +### Bug Fixes + +* call base basic finalizer if none defined ([#1574](https://github.com/nodejs/node-addon-api/issues/1574)) ([294a43f](https://github.com/nodejs/node-addon-api/commit/294a43f8c6a4c79b3295a8f1b83d4782d44cfe74)) + +## [8.1.0](https://github.com/nodejs/node-addon-api/compare/node-addon-api-v8.0.0...node-addon-api-v8.1.0) (2024-07-05) + + +### Features + +* Expose version property in public API ([#1479](https://github.com/nodejs/node-addon-api/issues/1479)) ([23bb42b](https://github.com/nodejs/node-addon-api/commit/23bb42b5e47630c9082dddbabea555626571926e)) +* improve messages on CheckCast ([#1507](https://github.com/nodejs/node-addon-api/issues/1507)) ([bf49519](https://github.com/nodejs/node-addon-api/commit/bf49519a4ce08ee5320327c9a0199cd89d5b87b3)) + + +### Bug Fixes + +* fix compilation for Visual Studio 2022 ([#1492](https://github.com/nodejs/node-addon-api/issues/1492)) ([e011720](https://github.com/nodejs/node-addon-api/commit/e011720010af26ed66638ceac822e5f1c5e43cde)) +* restore ability to run under NAPI_EXPERIMENTAL ([#1409](https://github.com/nodejs/node-addon-api/issues/1409)) ([40bcb09](https://github.com/nodejs/node-addon-api/commit/40bcb09e6b82e7a1164cb3de56cb503d9b5a3d37)) + +## 2024-03-01 Version 8.0.0, @legendecas + +### Notable changes + +- Support for Node.js v16.x is no longer maintained. + +### Commits + +* \[[`df2147a2b6`](https://github.com/nodejs/node-addon-api/commit/df2147a2b6)] - build(deps): bump github/codeql-action from 3.24.3 to 3.24.5 (dependabot\[bot]) [#1455](https://github.com/nodejs/node-addon-api/pull/1455) +* \[[`eb4fa9b55a`](https://github.com/nodejs/node-addon-api/commit/eb4fa9b55a)] - build(deps): bump actions/dependency-review-action from 4.1.0 to 4.1.3 (dependabot\[bot]) [#1452](https://github.com/nodejs/node-addon-api/pull/1452) +* \[[`f85e8146bb`](https://github.com/nodejs/node-addon-api/commit/f85e8146bb)] - build(deps): bump github/codeql-action from 3.23.2 to 3.24.3 (dependabot\[bot]) [#1448](https://github.com/nodejs/node-addon-api/pull/1448) +* \[[`b84deb0d2f`](https://github.com/nodejs/node-addon-api/commit/b84deb0d2f)] - build(deps): bump actions/dependency-review-action from 4.0.0 to 4.1.0 (dependabot\[bot]) [#1447](https://github.com/nodejs/node-addon-api/pull/1447) +* \[[`7dcee380cd`](https://github.com/nodejs/node-addon-api/commit/7dcee380cd)] - build(deps): bump actions/setup-node from 4.0.1 to 4.0.2 (dependabot\[bot]) [#1444](https://github.com/nodejs/node-addon-api/pull/1444) +* \[[`a727b629fe`](https://github.com/nodejs/node-addon-api/commit/a727b629fe)] - build(deps): bump actions/upload-artifact from 4.3.0 to 4.3.1 (dependabot\[bot]) [#1443](https://github.com/nodejs/node-addon-api/pull/1443) +* \[[`ea712094e3`](https://github.com/nodejs/node-addon-api/commit/ea712094e3)] - build(deps): bump step-security/harden-runner from 2.6.1 to 2.7.0 (dependabot\[bot]) [#1440](https://github.com/nodejs/node-addon-api/pull/1440) +* \[[`898e5006a5`](https://github.com/nodejs/node-addon-api/commit/898e5006a5)] - build(deps): bump github/codeql-action from 3.23.1 to 3.23.2 (dependabot\[bot]) [#1439](https://github.com/nodejs/node-addon-api/pull/1439) +* \[[`66e6e0e4b6`](https://github.com/nodejs/node-addon-api/commit/66e6e0e4b6)] - build(deps): bump actions/upload-artifact from 4.0.0 to 4.3.0 (dependabot\[bot]) [#1438](https://github.com/nodejs/node-addon-api/pull/1438) +* \[[`f1ca4ccd7f`](https://github.com/nodejs/node-addon-api/commit/f1ca4ccd7f)] - build(deps): bump actions/dependency-review-action from 3.1.5 to 4.0.0 (dependabot\[bot]) [#1433](https://github.com/nodejs/node-addon-api/pull/1433) +* \[[`c58112d52e`](https://github.com/nodejs/node-addon-api/commit/c58112d52e)] - build(deps): bump github/codeql-action from 3.23.0 to 3.23.1 (dependabot\[bot]) [#1430](https://github.com/nodejs/node-addon-api/pull/1430) +* \[[`f1b9c0bc24`](https://github.com/nodejs/node-addon-api/commit/f1b9c0bc24)] - **chore**: remove v16.x regular CI runs (Chengzhong Wu) [#1437](https://github.com/nodejs/node-addon-api/pull/1437) +* \[[`c6561d90d6`](https://github.com/nodejs/node-addon-api/commit/c6561d90d6)] - **chore**: reduce dependabot noise (Chengzhong Wu) [#1436](https://github.com/nodejs/node-addon-api/pull/1436) +* \[[`42931eeba6`](https://github.com/nodejs/node-addon-api/commit/42931eeba6)] - **doc**: reorganize readme (Chengzhong Wu) [#1441](https://github.com/nodejs/node-addon-api/pull/1441) +* \[[`3b9f3db14e`](https://github.com/nodejs/node-addon-api/commit/3b9f3db14e)] - **doc**: update changelog maker commands (Chengzhong Wu) [#1431](https://github.com/nodejs/node-addon-api/pull/1431) +* \[[`034c039298`](https://github.com/nodejs/node-addon-api/commit/034c039298)] - **test**: heed npm\_config\_debug (Gabriel Schulhof) [#1445](https://github.com/nodejs/node-addon-api/pull/1445) + +## 2024-01-18 Version 7.1.0, @legendecas + +### Notable changes + +#### API + +- Add Env::GetModuleFileName +- Add SyntaxError +- Allow NAPI\_VERSION env var and templatize AttachData callback +- Add common gyp dependency targets. + +### Commits + +* \[[`864fed488c`](https://github.com/nodejs/node-addon-api/commit/864fed488c)] - build(deps): bump github/codeql-action from 3.22.12 to 3.23.0 (dependabot\[bot]) [#1428](https://github.com/nodejs/node-addon-api/pull/1428) +* \[[`81a8d43130`](https://github.com/nodejs/node-addon-api/commit/81a8d43130)] - build(deps): bump actions/dependency-review-action from 3.1.4 to 3.1.5 (dependabot\[bot]) [#1427](https://github.com/nodejs/node-addon-api/pull/1427) +* \[[`e20088941b`](https://github.com/nodejs/node-addon-api/commit/e20088941b)] - build(deps): bump github/codeql-action from 3.22.11 to 3.22.12 (dependabot\[bot]) [#1426](https://github.com/nodejs/node-addon-api/pull/1426) +* \[[`76c7b12e4e`](https://github.com/nodejs/node-addon-api/commit/76c7b12e4e)] - build(deps): bump actions/setup-node from 4.0.0 to 4.0.1 (dependabot\[bot]) [#1425](https://github.com/nodejs/node-addon-api/pull/1425) +* \[[`cd58edde1d`](https://github.com/nodejs/node-addon-api/commit/cd58edde1d)] - build(deps): bump actions/upload-artifact from 3.1.3 to 4.0.0 (dependabot\[bot]) [#1424](https://github.com/nodejs/node-addon-api/pull/1424) +* \[[`0fd1b9e0e1`](https://github.com/nodejs/node-addon-api/commit/0fd1b9e0e1)] - build(deps): bump github/codeql-action from 2.22.8 to 3.22.11 (dependabot\[bot]) [#1423](https://github.com/nodejs/node-addon-api/pull/1423) +* \[[`c181b19d68`](https://github.com/nodejs/node-addon-api/commit/c181b19d68)] - build(deps): bump actions/stale from 8.0.0 to 9.0.0 (dependabot\[bot]) [#1418](https://github.com/nodejs/node-addon-api/pull/1418) +* \[[`6fa67791a1`](https://github.com/nodejs/node-addon-api/commit/6fa67791a1)] - build(deps): bump actions/setup-python from 4.7.1 to 5.0.0 (dependabot\[bot]) [#1417](https://github.com/nodejs/node-addon-api/pull/1417) +* \[[`1fff346fa6`](https://github.com/nodejs/node-addon-api/commit/1fff346fa6)] - build(deps): bump actions/dependency-review-action from 3.1.3 to 3.1.4 (dependabot\[bot]) [#1415](https://github.com/nodejs/node-addon-api/pull/1415) +* \[[`ecb9690fe5`](https://github.com/nodejs/node-addon-api/commit/ecb9690fe5)] - build(deps): bump github/codeql-action from 2.22.7 to 2.22.8 (dependabot\[bot]) [#1414](https://github.com/nodejs/node-addon-api/pull/1414) +* \[[`969547b871`](https://github.com/nodejs/node-addon-api/commit/969547b871)] - build(deps): bump github/codeql-action from 2.22.5 to 2.22.7 (dependabot\[bot]) [#1413](https://github.com/nodejs/node-addon-api/pull/1413) +* \[[`183d1522a9`](https://github.com/nodejs/node-addon-api/commit/183d1522a9)] - build(deps): bump step-security/harden-runner from 2.6.0 to 2.6.1 (dependabot\[bot]) [#1412](https://github.com/nodejs/node-addon-api/pull/1412) +* \[[`25f977724a`](https://github.com/nodejs/node-addon-api/commit/25f977724a)] - build(deps): bump actions/dependency-review-action from 3.1.0 to 3.1.3 (dependabot\[bot]) [#1410](https://github.com/nodejs/node-addon-api/pull/1410) +* \[[`f6d125a407`](https://github.com/nodejs/node-addon-api/commit/f6d125a407)] - build(deps): bump actions/setup-python from 4.7.0 to 4.7.1 (dependabot\[bot]) [#1406](https://github.com/nodejs/node-addon-api/pull/1406) +* \[[`ce78a39ec7`](https://github.com/nodejs/node-addon-api/commit/ce78a39ec7)] - build(deps): bump github/codeql-action from 2.22.4 to 2.22.5 (dependabot\[bot]) [#1400](https://github.com/nodejs/node-addon-api/pull/1400) +* \[[`dc211ebb48`](https://github.com/nodejs/node-addon-api/commit/dc211ebb48)] - build(deps): bump actions/setup-node from 3.8.1 to 4.0.0 (dependabot\[bot]) [#1398](https://github.com/nodejs/node-addon-api/pull/1398) +* \[[`cab559e3bd`](https://github.com/nodejs/node-addon-api/commit/cab559e3bd)] - build(deps): bump ossf/scorecard-action from 2.3.0 to 2.3.1 (dependabot\[bot]) [#1397](https://github.com/nodejs/node-addon-api/pull/1397) +* \[[`f71ff5582d`](https://github.com/nodejs/node-addon-api/commit/f71ff5582d)] - build(deps): bump github/codeql-action from 2.22.3 to 2.22.4 (dependabot\[bot]) [#1396](https://github.com/nodejs/node-addon-api/pull/1396) +* \[[`21c1d08680`](https://github.com/nodejs/node-addon-api/commit/21c1d08680)] - build(deps): bump actions/checkout from 4.1.0 to 4.1.1 (dependabot\[bot]) [#1394](https://github.com/nodejs/node-addon-api/pull/1394) +* \[[`e4eec0939c`](https://github.com/nodejs/node-addon-api/commit/e4eec0939c)] - build(deps): bump github/codeql-action from 2.21.9 to 2.22.3 (dependabot\[bot]) [#1393](https://github.com/nodejs/node-addon-api/pull/1393) +* \[[`94f3459474`](https://github.com/nodejs/node-addon-api/commit/94f3459474)] - build(deps): bump ossf/scorecard-action from 2.2.0 to 2.3.0 (dependabot\[bot]) [#1388](https://github.com/nodejs/node-addon-api/pull/1388) +* \[[`90a741ef10`](https://github.com/nodejs/node-addon-api/commit/90a741ef10)] - build(deps): bump step-security/harden-runner from 2.5.1 to 2.6.0 (dependabot\[bot]) [#1386](https://github.com/nodejs/node-addon-api/pull/1386) +* \[[`7e1aa06132`](https://github.com/nodejs/node-addon-api/commit/7e1aa06132)] - Update LICENSE.md (Michael Dawson) [#1385](https://github.com/nodejs/node-addon-api/pull/1385) +* \[[`0a0612362e`](https://github.com/nodejs/node-addon-api/commit/0a0612362e)] - build(deps): bump github/codeql-action from 2.21.7 to 2.21.9 (dependabot\[bot]) [#1384](https://github.com/nodejs/node-addon-api/pull/1384) +* \[[`47bd430da2`](https://github.com/nodejs/node-addon-api/commit/47bd430da2)] - build(deps): bump actions/checkout from 4.0.0 to 4.1.0 (dependabot\[bot]) [#1383](https://github.com/nodejs/node-addon-api/pull/1383) +* \[[`b3f7f73cb9`](https://github.com/nodejs/node-addon-api/commit/b3f7f73cb9)] - build(deps): bump actions/dependency-review-action from 3.0.8 to 3.1.0 (dependabot\[bot]) [#1377](https://github.com/nodejs/node-addon-api/pull/1377) +* \[[`12c1655387`](https://github.com/nodejs/node-addon-api/commit/12c1655387)] - build(deps): bump github/codeql-action from 2.21.6 to 2.21.7 (dependabot\[bot]) [#1380](https://github.com/nodejs/node-addon-api/pull/1380) +* \[[`6abed318e4`](https://github.com/nodejs/node-addon-api/commit/6abed318e4)] - build(deps): bump github/codeql-action from 2.21.5 to 2.21.6 (dependabot\[bot]) [#1378](https://github.com/nodejs/node-addon-api/pull/1378) +* \[[`89eda59930`](https://github.com/nodejs/node-addon-api/commit/89eda59930)] - build(deps): bump actions/upload-artifact from 3.1.2 to 3.1.3 (dependabot\[bot]) [#1376](https://github.com/nodejs/node-addon-api/pull/1376) +* \[[`90870dbffa`](https://github.com/nodejs/node-addon-api/commit/90870dbffa)] - build(deps): bump actions/checkout from 3.6.0 to 4.0.0 (dependabot\[bot]) [#1375](https://github.com/nodejs/node-addon-api/pull/1375) +* \[[`b860793eff`](https://github.com/nodejs/node-addon-api/commit/b860793eff)] - build(deps): bump github/codeql-action from 2.21.2 to 2.21.5 (dependabot\[bot]) [#1372](https://github.com/nodejs/node-addon-api/pull/1372) +* \[[`f9b9974b4a`](https://github.com/nodejs/node-addon-api/commit/f9b9974b4a)] - build(deps): bump actions/checkout from 3.5.3 to 3.6.0 (dependabot\[bot]) [#1371](https://github.com/nodejs/node-addon-api/pull/1371) +* \[[`9596e3de2d`](https://github.com/nodejs/node-addon-api/commit/9596e3de2d)] - build(deps): bump actions/setup-node from 3.7.0 to 3.8.1 (dependabot\[bot]) [#1370](https://github.com/nodejs/node-addon-api/pull/1370) +* \[[`e969210747`](https://github.com/nodejs/node-addon-api/commit/e969210747)] - build(deps): bump actions/dependency-review-action from 3.0.6 to 3.0.8 (dependabot\[bot]) [#1368](https://github.com/nodejs/node-addon-api/pull/1368) +* \[[`13ef96a5a9`](https://github.com/nodejs/node-addon-api/commit/13ef96a5a9)] - build(deps): bump step-security/harden-runner from 2.5.0 to 2.5.1 (dependabot\[bot]) [#1364](https://github.com/nodejs/node-addon-api/pull/1364) +* \[[`9776d148b3`](https://github.com/nodejs/node-addon-api/commit/9776d148b3)] - build(deps): bump github/codeql-action from 2.21.1 to 2.21.2 (dependabot\[bot]) [#1358](https://github.com/nodejs/node-addon-api/pull/1358) +* \[[`59dc6be097`](https://github.com/nodejs/node-addon-api/commit/59dc6be097)] - build(deps): bump github/codeql-action from 2.21.0 to 2.21.1 (dependabot\[bot]) [#1357](https://github.com/nodejs/node-addon-api/pull/1357) +* \[[`5e72796cd5`](https://github.com/nodejs/node-addon-api/commit/5e72796cd5)] - build(deps): bump step-security/harden-runner from 2.4.1 to 2.5.0 (dependabot\[bot]) [#1356](https://github.com/nodejs/node-addon-api/pull/1356) +* \[[`4e62db45e4`](https://github.com/nodejs/node-addon-api/commit/4e62db45e4)] - build(deps): bump github/codeql-action from 2.20.3 to 2.21.0 (dependabot\[bot]) [#1353](https://github.com/nodejs/node-addon-api/pull/1353) +* \[[`0c093a33e8`](https://github.com/nodejs/node-addon-api/commit/0c093a33e8)] - build(deps): bump github/codeql-action from 2.20.1 to 2.20.3 (dependabot\[bot]) [#1349](https://github.com/nodejs/node-addon-api/pull/1349) +* \[[`5523b2d3fa`](https://github.com/nodejs/node-addon-api/commit/5523b2d3fa)] - build(deps): bump actions/setup-node from 3.6.0 to 3.7.0 (dependabot\[bot]) [#1348](https://github.com/nodejs/node-addon-api/pull/1348) +* \[[`afa494ef7f`](https://github.com/nodejs/node-addon-api/commit/afa494ef7f)] - Add Node.js version restrictions (Ingo Fischer) [#1340](https://github.com/nodejs/node-addon-api/pull/1340) +* \[[`ac4c87f660`](https://github.com/nodejs/node-addon-api/commit/ac4c87f660)] - build(deps): bump ossf/scorecard-action from 2.0.6 to 2.2.0 (dependabot\[bot]) [#1344](https://github.com/nodejs/node-addon-api/pull/1344) +* \[[`47aeb6689d`](https://github.com/nodejs/node-addon-api/commit/47aeb6689d)] - build(deps): bump github/codeql-action from 2.2.12 to 2.20.1 (dependabot\[bot]) [#1343](https://github.com/nodejs/node-addon-api/pull/1343) +* \[[`bd45a8fffc`](https://github.com/nodejs/node-addon-api/commit/bd45a8fffc)] - build(deps): bump step-security/harden-runner from 2.3.0 to 2.4.1 (dependabot\[bot]) [#1342](https://github.com/nodejs/node-addon-api/pull/1342) +* \[[`343a1e1708`](https://github.com/nodejs/node-addon-api/commit/343a1e1708)] - build(deps-dev): bump fs-extra from 9.1.0 to 11.1.1 (dependabot\[bot]) [#1335](https://github.com/nodejs/node-addon-api/pull/1335) +* \[[`4168c10182`](https://github.com/nodejs/node-addon-api/commit/4168c10182)] - build(deps): bump actions/stale from 5.2.1 to 8.0.0 (dependabot\[bot]) [#1333](https://github.com/nodejs/node-addon-api/pull/1333) +* \[[`1c182abd1f`](https://github.com/nodejs/node-addon-api/commit/1c182abd1f)] - build(deps): bump actions/dependency-review-action from 2.5.1 to 3.0.6 (dependabot\[bot]) [#1331](https://github.com/nodejs/node-addon-api/pull/1331) +* \[[`717a61931d`](https://github.com/nodejs/node-addon-api/commit/717a61931d)] - build(deps): bump actions/checkout from 3.5.2 to 3.5.3 (dependabot\[bot]) [#1329](https://github.com/nodejs/node-addon-api/pull/1329) +* \[[`d605d62c89`](https://github.com/nodejs/node-addon-api/commit/d605d62c89)] - **chore**: lock python version in actions (Chengzhong Wu) [#1403](https://github.com/nodejs/node-addon-api/pull/1403) +* \[[`734e3f2509`](https://github.com/nodejs/node-addon-api/commit/734e3f2509)] - **doc**: fix rendering of code blocks in list (Tobias Nießen) [#1401](https://github.com/nodejs/node-addon-api/pull/1401) +* \[[`dfdf6eb6e6`](https://github.com/nodejs/node-addon-api/commit/dfdf6eb6e6)] - **doc**: add missing title IsBigInt (Marx) [#1352](https://github.com/nodejs/node-addon-api/pull/1352) +* \[[`8850997f38`](https://github.com/nodejs/node-addon-api/commit/8850997f38)] - **doc**: fix typo AsyncProgressWorker::ExecutionProgress (JerryZhongJ) [#1350](https://github.com/nodejs/node-addon-api/pull/1350) +* \[[`8192a471a1`](https://github.com/nodejs/node-addon-api/commit/8192a471a1)] - **docs**: fixed Broken Links (Ömer AKGÜL) [#1405](https://github.com/nodejs/node-addon-api/pull/1405) +* \[[`16a18c047a`](https://github.com/nodejs/node-addon-api/commit/16a18c047a)] - **fix**: handle c++ exception in TSFN callback (Chengzhong Wu) [#1345](https://github.com/nodejs/node-addon-api/pull/1345) +* \[[`ab14347080`](https://github.com/nodejs/node-addon-api/commit/ab14347080)] - **gyp**: add common targets (Chengzhong Wu) [#1389](https://github.com/nodejs/node-addon-api/pull/1389) +* \[[`fa3518bc08`](https://github.com/nodejs/node-addon-api/commit/fa3518bc08)] - **src**: remove duplicate buffer info calls (Chengzhong Wu) [#1354](https://github.com/nodejs/node-addon-api/pull/1354) +* \[[`b83e453e6e`](https://github.com/nodejs/node-addon-api/commit/b83e453e6e)] - **src**: add Env::GetModuleFileName (Kevin Eady) [#1327](https://github.com/nodejs/node-addon-api/pull/1327) +* \[[`d9828c6264`](https://github.com/nodejs/node-addon-api/commit/d9828c6264)] - **src**: add SyntaxError (Kevin Eady) [#1326](https://github.com/nodejs/node-addon-api/pull/1326) +* \[[`c52e764bb2`](https://github.com/nodejs/node-addon-api/commit/c52e764bb2)] - **src,test,build**: allow NAPI\_VERSION env var and templatize AttachData callback (Gabriel Schulhof) [#1399](https://github.com/nodejs/node-addon-api/pull/1399) +* \[[`8f028d630a`](https://github.com/nodejs/node-addon-api/commit/8f028d630a)] - **test**: remove experimental flag from bigint (Gabriel Schulhof) [#1395](https://github.com/nodejs/node-addon-api/pull/1395) +* \[[`414be9e000`](https://github.com/nodejs/node-addon-api/commit/414be9e000)] - **test**: run interfering tests in their own process (Gabriel Schulhof) [#1325](https://github.com/nodejs/node-addon-api/pull/1325) + +## 2023-06-13 Version 7.0.0, @KevinEady + +### Notable changes + +#### API + +- Drop support for Node.js v14.x and v19.x. +- Ensure native receiver exists when calling instance methods and properties. +- Fix issue when creating `Napi::Error` instances that wrap primitives values. + +#### TEST + +- Added tests for `Napi::AsyncProgressQueueWorker` class. +- Added tests for `Napi::AsyncProgressWorker` class. + +### Documentation + +- Added documentation for `Napi::Value::IsBigInt()`. + +### Commits + +* \[[`de5c899400`](https://github.com/nodejs/node-addon-api/commit/de5c899400)] - **doc,chore**: drop support for Node.js v14, v19 (Kevin Eady) [#1324](https://github.com/nodejs/node-addon-api/pull/1324) +* \[[`3083b7f148`](https://github.com/nodejs/node-addon-api/commit/3083b7f148)] - \[StepSecurity] Apply security best practices (StepSecurity Bot) [#1308](https://github.com/nodejs/node-addon-api/pull/1308) +* \[[`a198e24a15`](https://github.com/nodejs/node-addon-api/commit/a198e24a15)] - \[Test] Add tests for async progress queue worker (Jack) [#1316](https://github.com/nodejs/node-addon-api/pull/1316) +* \[[`665f4aa845`](https://github.com/nodejs/node-addon-api/commit/665f4aa845)] - **doc**: add missing Value::IsBigInt (Kevin Eady) [#1319](https://github.com/nodejs/node-addon-api/pull/1319) +* \[[`358b2d3b4f`](https://github.com/nodejs/node-addon-api/commit/358b2d3b4f)] - **doc**: complete code curly braces in async\_worker.md (wanlu) [#1317](https://github.com/nodejs/node-addon-api/pull/1317) +* \[[`858942ce31`](https://github.com/nodejs/node-addon-api/commit/858942ce31)] - **src**: avoid calling into C++ with a null this (Caleb Hearon) [#1313](https://github.com/nodejs/node-addon-api/pull/1313) +* \[[`64f6515331`](https://github.com/nodejs/node-addon-api/commit/64f6515331)] - **src**: handle failure during error wrap of primitive (Gabriel Schulhof) [#1310](https://github.com/nodejs/node-addon-api/pull/1310) +* \[[`dfad6b45fe`](https://github.com/nodejs/node-addon-api/commit/dfad6b45fe)] - \[test] Add test coverage for AsyncProgressWorker (Jack) [#1307](https://github.com/nodejs/node-addon-api/pull/1307) +* \[[`0e34f22839`](https://github.com/nodejs/node-addon-api/commit/0e34f22839)] - **release**: v6.1.0. (Nicola Del Gobbo) + +## 2023-04-20 Version 6.1.0, @NickNaso + +### Notable changes + +#### API + +- Enforce type checks on `Napi::Value::As()`. +- Added `Napi::TypeTaggable` class. +- Defined `NAPI_HAS_THREADS` to make TSFN available on Emscripten. +- Defined `NODE_API_NO_EXTERNAL_BUFFERS_ALLOWED` and +`Napi::Buffer::NewOrCopy()` to handle the support for external buffers. + +#### TEST + +- Added tests for `Napi::Reference` class. +- Added tests for copy/move semantics. +- Added tests for `Napi::RangeError` and `Napi::TypeError` class. +- Fixed inconsistent failure executing test suite. +- Added tests for `Napi::ObjectReference` class. +- Added tests for `Napi::ObjectWrap` class. + +### Documentation + +- Added documentation for `Napi::TypeTaggable`. +- Some minor fixes all over the documentation. + +### Commits + +- \[[`5adb896782`](https://github.com/nodejs/node-addon-api/commit/5adb896782)] - **src**: enforce type checks on Napi::Value::As() (#1281) (Chengzhong Wu) +- \[[`d9faac7ec2`](https://github.com/nodejs/node-addon-api/commit/d9faac7ec2)] - Fix exits/exists typo in docs for Env::AddCleanupHook() (#1306) (Mathias Stearn) +- \[[`164459ca03`](https://github.com/nodejs/node-addon-api/commit/164459ca03)] - **doc**: update class hierarchy for TypeTaggable (Gabriel Schulhof) [#1303](https://github.com/nodejs/node-addon-api/pull/1303) +- \[[`d01304437c`](https://github.com/nodejs/node-addon-api/commit/d01304437c)] - **src**: interject class TypeTaggable (Gabriel Schulhof) [#1298](https://github.com/nodejs/node-addon-api/pull/1298) +- \[[`d4942ccd4f`](https://github.com/nodejs/node-addon-api/commit/d4942ccd4f)] - **test**: Complete test coverage for Reference\ class (#1277) (Jack) +- \[[`a8ad7e7a7b`](https://github.com/nodejs/node-addon-api/commit/a8ad7e7a7b)] - **test**: Add tests for copy/move semantics (JckXia) [#1295](https://github.com/nodejs/node-addon-api/pull/1295) +- \[[`e484327344`](https://github.com/nodejs/node-addon-api/commit/e484327344)] - Add test coverage for typed and range err (#1280) (Jack) +- \[[`ebc7858593`](https://github.com/nodejs/node-addon-api/commit/ebc7858593)] - **test**: Update wait with a condition (#1297) (Jack) +- \[[`0b53d885f5`](https://github.com/nodejs/node-addon-api/commit/0b53d885f5)] - **src**: define `NAPI_HAS_THREADS` (toyobayashi) [#1283](https://github.com/nodejs/node-addon-api/pull/1283) +- \[[`464610babf`](https://github.com/nodejs/node-addon-api/commit/464610babf)] - **test**: complete objectRefs tests (JckXia) [#1274](https://github.com/nodejs/node-addon-api/pull/1274) +- \[[`b16c762a19`](https://github.com/nodejs/node-addon-api/commit/b16c762a19)] - **src**: handle no support for external buffers (legendecas) [#1273](https://github.com/nodejs/node-addon-api/pull/1273) +- \[[`61b8e28720`](https://github.com/nodejs/node-addon-api/commit/61b8e28720)] - **test**: Add test covg for obj wrap (#1269) (Jack) + +## 2023-02-03 Version 6.0.0, @NickNaso + +### Notable changes + +#### API + +- Added `Napi::Object::TypeTag()` and `Napi::Object::CheckTypeTag()` methods. +- Made operator `napi_callback_info` explicit. + +#### TEST + +- Some minor fixes all over the test suite. +- Added tests related to `Napi::Object::TypeTag()` and `Napi::Object::CheckTypeTag()` methods. +- Added tests related to `Napi::CallbackScope`. +- Added tests related to `Napi::EscapableHandleScope`. +- Added tests related to `Napi::Maybe`. +- Added tests related to `Napi::ThreadSafeFuntion`. +- Changed some tests related to `Napi::AsyncWorker`. + +### Documentation + +- Added documentation for `Napi::Object::TypeTag()` and `Napi::Object::CheckTypeTag()` methods. +- Added documentation about how to run a specific unit test. + +### TOOL + +- Added `x86` architecture to the CI matrix. + +### Commits + +* \[[`e2726193f1`](https://github.com/nodejs/node-addon-api/commit/e2726193f1)] - **src**: remove AsyncWorker move and complete tests (JckXia) [#1266](https://github.com/nodejs/node-addon-api/pull/1266) +* \[[`ff969485ea`](https://github.com/nodejs/node-addon-api/commit/ff969485ea)] - **chore**: build node-addon-api against X86 (JckXia) [#1276](https://github.com/nodejs/node-addon-api/pull/1276) +* \[[`a70564cdfd`](https://github.com/nodejs/node-addon-api/commit/a70564cdfd)] - **test**: add cov for ThreadSafeFunction new overloads (JckXia) [#1251](https://github.com/nodejs/node-addon-api/pull/1251) +* \[[`53f7cf1d48`](https://github.com/nodejs/node-addon-api/commit/53f7cf1d48)] - **src**: make operator napi\_callback\_info explicit (Kevin Eady) [#1275](https://github.com/nodejs/node-addon-api/pull/1275) +* \[[`78b5a15533`](https://github.com/nodejs/node-addon-api/commit/78b5a15533)] - **test**: Add tests for ThreadSafeFunction's NonBlock function overloads (#1249) (Jack) +* \[[`fdc6263034`](https://github.com/nodejs/node-addon-api/commit/fdc6263034)] - **test**: Add test covg for Maybe\ (#1270) (Jack) +* \[[`35d9d669b3`](https://github.com/nodejs/node-addon-api/commit/35d9d669b3)] - **test**: add test covg for handle and escapehandle scopes (JckXia) [#1263](https://github.com/nodejs/node-addon-api/pull/1263) +* \[[`021313409e`](https://github.com/nodejs/node-addon-api/commit/021313409e)] - **test**: add unit test covg for callbackscopes (JckXia) [#1262](https://github.com/nodejs/node-addon-api/pull/1262) +* \[[`b11e4de2cf`](https://github.com/nodejs/node-addon-api/commit/b11e4de2cf)] - **src**: add Object::TypeTag, Object::CheckTypeTag (Kevin Eady) [#1261](https://github.com/nodejs/node-addon-api/pull/1261) + +## 2023-01-13 Version 5.1.0, @NickNaso + +### Notable changes + +#### API + +- Fixed memory leak in `Napi::AsyncProgressWorkerBase`. +- Added api to get `callback_info` from `Napi::CallBackInfo`. +- Fixed erros and warning in VS 2017. +- Made `Npi::Env::CleanupHook` public. +- Removed `Napi::TypedArray::unknown_array_type`. + +#### TEST + +- Some minor fixes all over the test suite. +- Added tests related to `Napi::Env`. +- Added tests related to `Napi::TypedArray`. +- Added tests related to `Napi::AsyncWorker`. +- Added tests related to `Napi::TypedThreadSafeFunction`. +- Added tests related to `Napi::Value`. +- Added test related to `Napi::Promise`. + +### Documentation + +- Some minor fixes all over the documentation. +- Added `Napi::HandleScope` example. +- Added documentation about how to run a specific unit test. + +### TOOL + +- Added Windows with VS 2022 and Node.JS 19.x to the CI matrix. +- Fixed stale workflow. +- Updated Node.js versions on CI component. +- Added condition for Window to find eslint. + +### Commits + +* \[[`79a446fb9c`](https://github.com/nodejs/node-addon-api/commit/79a446fb9c)] - Update contributors (#1265) (Kevin Eady) +* \[[`01c61690c6`](https://github.com/nodejs/node-addon-api/commit/01c61690c6)] - **src**: napi-inl: Fix a memory leak bug in `AsyncProgressWorkerBase` (Ammar Faizi) [#1264](https://github.com/nodejs/node-addon-api/pull/1264) +* \[[`55bd08ee26`](https://github.com/nodejs/node-addon-api/commit/55bd08ee26)] - **src**: api to get callback\_info from CallBackInfo (JckXia) [#1253](https://github.com/nodejs/node-addon-api/pull/1253) +* \[[`ad76256714`](https://github.com/nodejs/node-addon-api/commit/ad76256714)] - **test**: add tests related to env (JckXia) [#1254](https://github.com/nodejs/node-addon-api/pull/1254) +* \[[`5c3937365d`](https://github.com/nodejs/node-addon-api/commit/5c3937365d)] - **chore**: add Windows with VS 2022 and Node.JS 19.x to the CI matrix (#1252) (Vladimir Morozov) +* \[[`97736c93f4`](https://github.com/nodejs/node-addon-api/commit/97736c93f4)] - **src**: fix errors and warnings in VS 2017 (Vladimir Morozov) [#1245](https://github.com/nodejs/node-addon-api/pull/1245) +* \[[`ad7ff92c16`](https://github.com/nodejs/node-addon-api/commit/ad7ff92c16)] - **src**: refactor call js wrapper (#1242) (Jack) +* \[[`39267baf1b`](https://github.com/nodejs/node-addon-api/commit/39267baf1b)] - **src**: make CleanupHook public (Julian Mesa) [#1240](https://github.com/nodejs/node-addon-api/pull/1240) +* \[[`edf630cc79`](https://github.com/nodejs/node-addon-api/commit/edf630cc79)] - **src**: fix implementation of Signal (Kevin Eady) [#1216](https://github.com/nodejs/node-addon-api/pull/1216) +* \[[`de5a502f3c`](https://github.com/nodejs/node-addon-api/commit/de5a502f3c)] - **doc**: Napi::Error is caught (Nicola Del Gobbo) [#1241](https://github.com/nodejs/node-addon-api/pull/1241) +* \[[`10ad762807`](https://github.com/nodejs/node-addon-api/commit/10ad762807)] - **test**: removed the usage of default\_configuration. (Nicola Del Gobbo) [#1226](https://github.com/nodejs/node-addon-api/pull/1226) +* \[[`e9db2adef2`](https://github.com/nodejs/node-addon-api/commit/e9db2adef2)] - **test**: Add test coverage to TSFN::New() overloads (#1201) (Jack) +* \[[`c849ad3f6a`](https://github.com/nodejs/node-addon-api/commit/c849ad3f6a)] - **chore**: fix stale workflow (#1228) (Richard Lau) +* \[[`e408804ad8`](https://github.com/nodejs/node-addon-api/commit/e408804ad8)] - **test**: adding ref for threadsafefunctions (JckXia) [#1222](https://github.com/nodejs/node-addon-api/pull/1222) +* \[[`a8afb2d73c`](https://github.com/nodejs/node-addon-api/commit/a8afb2d73c)] - **src**: remove TypedArray::unknown\_array\_type (Kevin Eady) [#1209](https://github.com/nodejs/node-addon-api/pull/1209) +* \[[`257a52f823`](https://github.com/nodejs/node-addon-api/commit/257a52f823)] - **test**: Add test cased for failed task cancellations (#1214) (Jack) +* \[[`793268c59f`](https://github.com/nodejs/node-addon-api/commit/793268c59f)] - **test**: Add test case for canceling async worker tasks (#1202) (Jack) +* \[[`1331856ef1`](https://github.com/nodejs/node-addon-api/commit/1331856ef1)] - **doc**: add HandleScope example (#1210) (Kevin Eady) +* \[[`d5fc875e5d`](https://github.com/nodejs/node-addon-api/commit/d5fc875e5d)] - **test**: remove update to process.config (#1208) (Michael Dawson) +* \[[`30cd4a37f0`](https://github.com/nodejs/node-addon-api/commit/30cd4a37f0)] - **test**: add tests for .Data method (JckXia) [#1203](https://github.com/nodejs/node-addon-api/pull/1203) +* \[[`225ca35963`](https://github.com/nodejs/node-addon-api/commit/225ca35963)] - **test**: Add test coverage for "TSFN::Ref()" (#1196) (Jack) +* \[[`5a5a213985`](https://github.com/nodejs/node-addon-api/commit/5a5a213985)] - Update CI component versions (#1200) (Vladimir Morozov) +* \[[`fb27e72b0c`](https://github.com/nodejs/node-addon-api/commit/fb27e72b0c)] - **doc**: Update CONTRIBUTING.md (Saint Gabriel) [#1185](https://github.com/nodejs/node-addon-api/pull/1185) +* \[[`e9def3ed72`](https://github.com/nodejs/node-addon-api/commit/e9def3ed72)] - **doc**: Update Readme for filter conditions in unit tests (Deepak Rajamohan) [#1199](https://github.com/nodejs/node-addon-api/pull/1199) +* \[[`efd67876e1`](https://github.com/nodejs/node-addon-api/commit/efd67876e1)] - **doc**: updated npm script for focused tests (Peter Šándor) +* \[[`134961d853`](https://github.com/nodejs/node-addon-api/commit/134961d853)] - **test**: CallbackInfo NewTarget() basic coverage (#1048) (Peter Šándor) +* \[[`1dfd03bdd5`](https://github.com/nodejs/node-addon-api/commit/1dfd03bdd5)] - Update README.md (#1187) (Saint Gabriel) +* \[[`576128fd19`](https://github.com/nodejs/node-addon-api/commit/576128fd19)] - **doc**: fix typo in async\_operations.md (#1189) (Tobias Nießen) +* \[[`63d3c30ec1`](https://github.com/nodejs/node-addon-api/commit/63d3c30ec1)] - **test**: add tests for TypedArray (Dante Calderon) [#1179](https://github.com/nodejs/node-addon-api/pull/1179) +* \[[`358ac2f080`](https://github.com/nodejs/node-addon-api/commit/358ac2f080)] - Fix link to CMake.js documentation (#1180) (Kyle Kovacs) +* \[[`dc4f2bbe4a`](https://github.com/nodejs/node-addon-api/commit/dc4f2bbe4a)] - **test**: Add promise unit test (#1173) (Jenny) +* \[[`f3124ae0ed`](https://github.com/nodejs/node-addon-api/commit/f3124ae0ed)] - **doc**: fix broken `Napi::ThreadSafeFunction` link (#1172) (Feng Yu) +* \[[`10b440fe27`](https://github.com/nodejs/node-addon-api/commit/10b440fe27)] - **src**: reformat all code (Kevin Eady) [#1160](https://github.com/nodejs/node-addon-api/pull/1160) +* \[[`33e402971e`](https://github.com/nodejs/node-addon-api/commit/33e402971e)] - **test**: Add condition for window to find eslint (#1176) (Jack) +* \[[`d53843b83b`](https://github.com/nodejs/node-addon-api/commit/d53843b83b)] - **test**: add missing value tests (JckXia) [#1170](https://github.com/nodejs/node-addon-api/pull/1170) + ## 2022-05-02 Version 5.0.0, @NickNaso ### Notable changes: @@ -16,7 +426,7 @@ of `Napi::Value`'s. - Improved the test framework. Added the possibility to run subsets of tests more easily. - Added test for `Napi::AsyncContext` class. -- Fixed ramdom failure on test for `Napi::ThreadSafeFunction` e +- Fixed ramdom failure on test for `Napi::ThreadSafeFunction` e `Napi::TypedThreadSafeFunction` class. - Fixed compilation problem on debian 8 system. - Added test for `Napi::Object::Set()` method. @@ -142,10 +552,10 @@ more easily. #### API -- `Napi::Reference` updated the default value to reflect the most possible +- `Napi::Reference` updated the default value to reflect the most possible values when there are any errors occurred on `napi_reference_unref`. - Added the check for nullpointer on `Napi::String` initialization. -- Added the wraps for `napi_add_env_cleanup_hook` and +- Added the wraps for `napi_add_env_cleanup_hook` and `napi_remove_env_cleanup_hook`. - Added `Napi::Maybe` class to handle pending exception when cpp exception disabled. @@ -176,9 +586,9 @@ disabled. #### API -- Fixed a crashing issue in `Napi::Error::ThrowAsJavaScriptException` +- Fixed a crashing issue in `Napi::Error::ThrowAsJavaScriptException` introducing the preprocessor directive `NODE_API_SWALLOW_UNTHROWABLE_EXCEPTIONS`. -- Fixed compilation problem for GCC 11 and C++20. +- Fixed compilation problem for GCC 11 and C++20. #### TEST @@ -297,12 +707,12 @@ introducing the preprocessor directive `NODE_API_SWALLOW_UNTHROWABLE_EXCEPTIONS` #### API - Added `Napi::TypedThreadSafeFunction` class that is a new implementation for -thread-safe functions. +thread-safe functions. - Fixed leak on `Napi::AsyncProgressWorkerBase`. -- Fixed empty data on `Napi::AsyncProgressWorker::OnProgress` caused by race +- Fixed empty data on `Napi::AsyncProgressWorker::OnProgress` caused by race conditions of `Napi::AsyncProgressWorker`. - Added `Napi::ArrayBuffer::Detach()` and `Napi::ArrayBuffer::IsDetached()`. -- Fixed problem on `Napi::FinalizeCallback` it needs to create a +- Fixed problem on `Napi::FinalizeCallback` it needs to create a `Napi::HandleScope` when it calls `Napi::ObjectWrap::~ObjectWrap()`. #### Documentation @@ -373,7 +783,7 @@ conditions of `Napi::AsyncProgressWorker`. #### API - Introduced `include_dir` for use with **gyp** in a scalar context. -- Added `Napi::Addon` to help handle the loading of a native add-on into +- Added `Napi::Addon` to help handle the loading of a native add-on into multiple threads and or multiple times in the same thread. - Concentrate callbacks provided to core N-API. - Make sure wrapcallback is used. @@ -912,5 +1322,3 @@ yet backported in the previous Node.js version. * [0a899bf1c5] - doc: update indication of latest version (Michael Dawson) https://github.com/nodejs/node-addon-api/pull/211 * [17c74e5a5e] - n-api: RangeError in napi_create_dataview() (Jinho Bang) https://github.com/nodejs/node-addon-api/pull/214 * [4058a29989] - n-api: fix memory leak in napi_async_destroy() (Jinho Bang) https://github.com/nodejs/node-addon-api/pull/213 - - diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 5c6151d70..663fc2304 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -1,22 +1,41 @@ +# Contributing to **node-addon-api** -# Developer's Certificate of Origin 1.1 +* [Code of Conduct](#code-of-conduct) +* [Developer's Certificate of Origin 1.1](#developers-certificate-of-origin) +* [Tests](#tests) +* [Debug](#debug) +* [Benchmarks](#benchmarks) +* [node-addon-api Contribution Philosophy](#node-addon-api-contribution-philosophy) +## Code of Conduct + +The Node.js project has a +[Code of Conduct](https://github.com/nodejs/admin/blob/HEAD/CODE_OF_CONDUCT.md) +to which all contributors must adhere. + +See [details on our policy on Code of Conduct](https://github.com/nodejs/node/blob/main/doc/contributing/code-of-conduct.md). + + + +## Developer's Certificate of Origin 1.1 + +
 By making a contribution to this project, I certify that:
 
  (a) The contribution was created in whole or in part by me and I
-     have the right to submit it under the open-source license
+     have the right to submit it under the open source license
      indicated in the file; or
 
  (b) The contribution is based upon previous work that, to the best
      of my knowledge, is covered under an appropriate open source
      license and I have the right under that license to submit that
      work with modifications, whether created in whole or in part
-     by me, under the same open-source license (unless I am
+     by me, under the same open source license (unless I am
      permitted to submit under a different license), as indicated
      in the file; or
 
  (c) The contribution was provided directly to me by some other
-     person who certified (a), (b), or (c) and I have not modified
+     person who certified (a), (b) or (c) and I have not modified
      it.
 
  (d) I understand and agree that this project and the contribution
@@ -24,17 +43,118 @@ By making a contribution to this project, I certify that:
      personal information I submit with it, including my sign-off) is
      maintained indefinitely and may be redistributed consistent with
      this project or the open source license(s) involved.
+
+ + +## Tests + +To run the **node-addon-api** tests do: + +``` +npm install +npm test +``` + +To avoid testing the deprecated portions of the API run +``` +npm install +npm test --disable-deprecated +``` + +To run the tests targeting a specific version of Node-API run +``` +npm install +export NAPI_VERSION=X +npm test --NAPI_VERSION=X +``` + +where X is the version of Node-API you want to target. + +To run a subset of the test suite, filter conditions are available. +The `--filter` option limits which JavaScript test modules are executed by +`node test`. The default `pretest` step is still `node-gyp rebuild -C test`, +so `npm test --filter=...` still performs a full rebuild of the test addon +targets before the filtered tests run. + +**Example:** + perform the default test rebuild, then run only the `objectwrap` test module + ``` + npm test --filter=objectwrap + ``` + +Multiple test modules can be selected with wildcards. + +**Example:** +perform the default test rebuild, then run all test modules ending with +`reference`: +`function_reference`, `object_reference`, and `reference` + ``` + npm test --filter=*reference + ``` + +Multiple filter conditions can be joined to broaden the test selection. + +**Example:** + perform the default test rebuild, then run all tests under + `threadsafe_function` and `typed_threadsafe_function`, and also the + `objectwrap` test module + ``` + npm test --filter='*function objectwrap' + ``` -# **node-addon-api** Contribution Philosophy +As an alternative, `ninja` can be used to build the tests. Please +follow the instructions in [Build with ninja](doc/contributing/build_with_ninja.md). + +## Debug + +To run the **node-addon-api** tests with `--debug` option: + +``` +npm run-script dev +``` + +If you want a faster build, you might use the following option: + +``` +npm run-script dev:incremental +``` + +Take a look and get inspired by our **[test suite](https://github.com/nodejs/node-addon-api/tree/HEAD/test)** + +## Benchmarks + +You can run the available benchmarks using the following command: + +``` +npm run-script benchmark +``` + +See [benchmark/README.md](benchmark/README.md) for more details about running and adding benchmarks. + +## **node-addon-api** Contribution Philosophy The **node-addon-api** team loves contributions. There are many ways in which you can contribute to **node-addon-api**: -- Source code fixes +- [New APIs](#new-apis) +- [Source code fixes](#source-changes) - Additional tests - Documentation improvements - Joining the Node-API working group and participating in meetings -## Source changes +### New APIs + +As new APIs are added to Node-API, node-addon-api must be updated to provide +wrappers for those new APIs. For this reason, node-addon-api provides +methods that allow callers to obtain the underlying Node-API handles so +direct calls to Node-API and the use of the objects/methods provided by +node-addon-api can be used together. For example, in order to be able +to use an API for which the node-addon-api does not yet provide a wrapper. + +APIs exposed by node-addon-api are generally used to create and +manipulate JavaScript values. Concepts and operations generally map +to ideas specified in the **ECMA262 Language Specification**. + +### Source changes **node-addon-api** is meant to be a thin convenience wrapper around Node-API. With this in mind, contributions of any new APIs that wrap around a core Node-API API will @@ -56,6 +176,7 @@ idioms while writing native addons with **node-addon-api**. where folks can build on top of it. #### Larger Core + This is probably our simplest option in terms of immediate action needed. It would involve landing any open PRs against **node-addon-api**, and continuing to encourage folks to make PRs for utility helpers against the same repository. @@ -65,6 +186,7 @@ The downside of the approach is the following: - More maintenance burden on the Node-API WG core team. #### Extras Package + This involves us spinning up a new package that contains the utility classes and methods. This has the benefit of having a separate module where helpers make it easier to implement certain patterns and idioms for native addons @@ -78,6 +200,7 @@ belongs in **node-addon-api** vs **node-addon-api-extras**) - Unclear if the maintenance burden on the Node-API WG is reduced or not #### Ecosystem + This doesn't require a ton of up-front work from the Node-API WG. Instead of accepting utility PRs into **node-addon-api** or creating and maintaining a new module, the WG will encourage the creation of an ecosystem of modules that @@ -90,4 +213,3 @@ The downside of this approach is the following: authors might not find the right patterns and instead implement things themselves - There might be greater friction for the Node-API WG in evolving APIs since the ecosystem would have taken dependencies on the API shape of **node-addon-api** - diff --git a/LICENSE.md b/LICENSE.md index e2fad6667..819d91a5b 100644 --- a/LICENSE.md +++ b/LICENSE.md @@ -1,13 +1,9 @@ The MIT License (MIT) -===================== -Copyright (c) 2017 Node.js API collaborators ------------------------------------ - -*Node.js API collaborators listed at * +Copyright (c) 2017 [Node.js API collaborators](https://github.com/nodejs/node-addon-api#collaborators) 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: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. -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. \ No newline at end of file +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. diff --git a/README.md b/README.md index 1ad379205..268c1e70f 100644 --- a/README.md +++ b/README.md @@ -1,265 +1,37 @@ -NOTE: The default branch has been renamed! -master is now named main +# **node-addon-api module** -If you have a local clone, you can update it by running: +[![codecov](https://codecov.io/gh/nodejs/node-addon-api/branch/main/graph/badge.svg)](https://app.codecov.io/gh/nodejs/node-addon-api/tree/main) -```shell -git branch -m master main -git fetch origin -git branch -u origin/main main -``` +[![NPM](https://nodei.co/npm/node-addon-api.png?downloads=true&downloadRank=true)](https://nodei.co/npm/node-addon-api/) [![NPM](https://nodei.co/npm-dl/node-addon-api.png?months=6&height=1)](https://nodei.co/npm/node-addon-api/) -# **node-addon-api module** This module contains **header-only C++ wrapper classes** which simplify the use of the C based [Node-API](https://nodejs.org/dist/latest/docs/api/n-api.html) provided by Node.js when using C++. It provides a C++ object model and exception handling semantics with low overhead. -There are three options for implementing addons: Node-API, nan, or direct -use of internal V8, libuv, and Node.js libraries. Unless there is a need for -direct access to functionality that is not exposed by Node-API as outlined -in [C/C++ addons](https://nodejs.org/dist/latest/docs/api/addons.html) -in Node.js core, use Node-API. Refer to -[C/C++ addons with Node-API](https://nodejs.org/dist/latest/docs/api/n-api.html) -for more information on Node-API. - -Node-API is an ABI stable C interface provided by Node.js for building native -addons. It is independent of the underlying JavaScript runtime (e.g. V8 or ChakraCore) -and is maintained as part of Node.js itself. It is intended to insulate -native addons from changes in the underlying JavaScript engine and allow -modules compiled for one version to run on later versions of Node.js without -recompilation. - -The `node-addon-api` module, which is not part of Node.js, preserves the benefits -of the Node-API as it consists only of inline code that depends only on the stable API -provided by Node-API. As such, modules built against one version of Node.js -using node-addon-api should run without having to be rebuilt with newer versions -of Node.js. - -It is important to remember that *other* Node.js interfaces such as -`libuv` (included in a project via `#include `) are not ABI-stable across -Node.js major versions. Thus, an addon must use Node-API and/or `node-addon-api` -exclusively and build against a version of Node.js that includes an -implementation of Node-API (meaning an active LTS version of Node.js) in -order to benefit from ABI stability across Node.js major versions. Node.js -provides an [ABI stability guide][] containing a detailed explanation of ABI -stability in general, and the Node-API ABI stability guarantee in particular. - -As new APIs are added to Node-API, node-addon-api must be updated to provide -wrappers for those new APIs. For this reason, node-addon-api provides -methods that allow callers to obtain the underlying Node-API handles so -direct calls to Node-API and the use of the objects/methods provided by -node-addon-api can be used together. For example, in order to be able -to use an API for which the node-addon-api does not yet provide a wrapper. - -APIs exposed by node-addon-api are generally used to create and -manipulate JavaScript values. Concepts and operations generally map -to ideas specified in the **ECMA262 Language Specification**. +- [API References](doc/README.md) +- [Badges](#badges) +- [Contributing](#contributing) +- [License](#license) -The [Node-API Resource](https://nodejs.github.io/node-addon-examples/) offers an -excellent orientation and tips for developers just getting started with Node-API -and node-addon-api. +## API References -- **[Setup](#setup)** -- **[API Documentation](#api)** -- **[Examples](#examples)** -- **[Tests](#tests)** -- **[More resource and info about native Addons](#resources)** -- **[Badges](#badges)** -- **[Code of Conduct](CODE_OF_CONDUCT.md)** -- **[Contributors](#contributors)** -- **[License](#license)** +API references are available in the [doc](doc/README.md) directory. -## **Current version: 5.0.0** + +## Current version: 8.9.2 + (See [CHANGELOG.md](CHANGELOG.md) for complete Changelog) -[![NPM](https://nodei.co/npm/node-addon-api.png?downloads=true&downloadRank=true)](https://nodei.co/npm/node-addon-api/) [![NPM](https://nodei.co/npm-dl/node-addon-api.png?months=6&height=1)](https://nodei.co/npm/node-addon-api/) - - - node-addon-api is based on [Node-API](https://nodejs.org/api/n-api.html) and supports using different Node-API versions. This allows addons built with it to run with Node.js versions which support the targeted Node-API version. **However** the node-addon-api support model is to support only the active LTS Node.js versions. This means that every year there will be a new major which drops support for the Node.js LTS version which has gone out of service. -The oldest Node.js version supported by the current version of node-addon-api is Node.js 14.x. - -## Setup - - [Installation and usage](doc/setup.md) - - [node-gyp](doc/node-gyp.md) - - [cmake-js](doc/cmake-js.md) - - [Conversion tool](doc/conversion-tool.md) - - [Checker tool](doc/checker-tool.md) - - [Generator](doc/generator.md) - - [Prebuild tools](doc/prebuild_tools.md) - - - -### **API Documentation** - -The following is the documentation for node-addon-api. - - - [Full Class Hierarchy](doc/hierarchy.md) - - [Addon Structure](doc/addon.md) - - Data Types: - - [Env](doc/env.md) - - [CallbackInfo](doc/callbackinfo.md) - - [Reference](doc/reference.md) - - [Value](doc/value.md) - - [Name](doc/name.md) - - [Symbol](doc/symbol.md) - - [String](doc/string.md) - - [Number](doc/number.md) - - [Date](doc/date.md) - - [BigInt](doc/bigint.md) - - [Boolean](doc/boolean.md) - - [External](doc/external.md) - - [Object](doc/object.md) - - [Array](doc/array.md) - - [ObjectReference](doc/object_reference.md) - - [PropertyDescriptor](doc/property_descriptor.md) - - [Function](doc/function.md) - - [FunctionReference](doc/function_reference.md) - - [ObjectWrap](doc/object_wrap.md) - - [ClassPropertyDescriptor](doc/class_property_descriptor.md) - - [Buffer](doc/buffer.md) - - [ArrayBuffer](doc/array_buffer.md) - - [TypedArray](doc/typed_array.md) - - [TypedArrayOf](doc/typed_array_of.md) - - [DataView](doc/dataview.md) - - [Error Handling](doc/error_handling.md) - - [Error](doc/error.md) - - [TypeError](doc/type_error.md) - - [RangeError](doc/range_error.md) - - [Object Lifetime Management](doc/object_lifetime_management.md) - - [HandleScope](doc/handle_scope.md) - - [EscapableHandleScope](doc/escapable_handle_scope.md) - - [Memory Management](doc/memory_management.md) - - [Async Operations](doc/async_operations.md) - - [AsyncWorker](doc/async_worker.md) - - [AsyncContext](doc/async_context.md) - - [AsyncWorker Variants](doc/async_worker_variants.md) - - [Thread-safe Functions](doc/threadsafe.md) - - [ThreadSafeFunction](doc/threadsafe_function.md) - - [TypedThreadSafeFunction](doc/typed_threadsafe_function.md) - - [Promises](doc/promises.md) - - [Version management](doc/version_management.md) - - - -### **Examples** - -Are you new to **node-addon-api**? Take a look at our **[examples](https://github.com/nodejs/node-addon-examples)** - -- **[Hello World](https://github.com/nodejs/node-addon-examples/tree/HEAD/1_hello_world/node-addon-api)** -- **[Pass arguments to a function](https://github.com/nodejs/node-addon-examples/tree/HEAD/2_function_arguments/node-addon-api)** -- **[Callbacks](https://github.com/nodejs/node-addon-examples/tree/HEAD/3_callbacks/node-addon-api)** -- **[Object factory](https://github.com/nodejs/node-addon-examples/tree/HEAD/4_object_factory/node-addon-api)** -- **[Function factory](https://github.com/nodejs/node-addon-examples/tree/HEAD/5_function_factory/node-addon-api)** -- **[Wrapping C++ Object](https://github.com/nodejs/node-addon-examples/tree/HEAD/6_object_wrap/node-addon-api)** -- **[Factory of wrapped object](https://github.com/nodejs/node-addon-examples/tree/HEAD/7_factory_wrap/node-addon-api)** -- **[Passing wrapped object around](https://github.com/nodejs/node-addon-examples/tree/HEAD/8_passing_wrapped/node-addon-api)** - - - -### **Tests** - -To run the **node-addon-api** tests do: - -``` -npm install -npm test -``` - -To avoid testing the deprecated portions of the API run -``` -npm install -npm test --disable-deprecated -``` - -To run the tests targeting a specific version of Node-API run -``` -npm install -export NAPI_VERSION=X -npm test --NAPI_VERSION=X -``` - -where X is the version of Node-API you want to target. - -To run a specific unit test, filter conditions are available - -**Example:** - compile and run only tests on objectwrap.cc and objectwrap.js - ``` - npm run unit --filter=objectwrap - ``` - -Multiple unit tests cane be selected with wildcards - -**Example:** -compile and run all test files ending with "reference" -> function_reference.cc, object_reference.cc, reference.cc - ``` - npm run unit --filter=*reference - ``` - -Multiple filter conditions can be joined to broaden the test selection +The oldest Node.js version supported by the current version of node-addon-api is Node.js 18.x. -**Example:** - compile and run all tests under folders threadsafe_function and typed_threadsafe_function and also the objectwrap.cc file - npm run unit --filter='*function objectwrap' - -### **Debug** - -To run the **node-addon-api** tests with `--debug` option: - -``` -npm run-script dev -``` - -If you want a faster build, you might use the following option: - -``` -npm run-script dev:incremental -``` - -Take a look and get inspired by our **[test suite](https://github.com/nodejs/node-addon-api/tree/HEAD/test)** - -### **Benchmarks** - -You can run the available benchmarks using the following command: - -``` -npm run-script benchmark -``` - -See [benchmark/README.md](benchmark/README.md) for more details about running and adding benchmarks. - - - -### **More resource and info about native Addons** -- **[C++ Addons](https://nodejs.org/dist/latest/docs/api/addons.html)** -- **[Node-API](https://nodejs.org/dist/latest/docs/api/n-api.html)** -- **[Node-API - Next Generation Node API for Native Modules](https://youtu.be/-Oniup60Afs)** -- **[How We Migrated Realm JavaScript From NAN to Node-API](https://developer.mongodb.com/article/realm-javascript-nan-to-n-api)** - -As node-addon-api's core mission is to expose the plain C Node-API as C++ -wrappers, tools that facilitate n-api/node-addon-api providing more -convenient patterns for developing a Node.js add-on with n-api/node-addon-api -can be published to NPM as standalone packages. It is also recommended to tag -such packages with `node-addon-api` to provide more visibility to the community. - -Quick links to NPM searches: [keywords:node-addon-api](https://www.npmjs.com/search?q=keywords%3Anode-addon-api). - - - -### **Other bindings** - -- **[napi-rs](https://napi.rs)** - (`Rust`) - - - -### **Badges** +## Badges The use of badges is recommended to indicate the minimum version of Node-API required for the module. This helps to determine which Node.js major versions are @@ -275,41 +47,49 @@ available: ![Node-API v6 Badge](https://github.com/nodejs/abi-stable-node/blob/doc/assets/Node-API%20v6%20Badge.svg) ![Node-API v7 Badge](https://github.com/nodejs/abi-stable-node/blob/doc/assets/Node-API%20v7%20Badge.svg) ![Node-API v8 Badge](https://github.com/nodejs/abi-stable-node/blob/doc/assets/Node-API%20v8%20Badge.svg) +![Node-API v9 Badge](https://github.com/nodejs/abi-stable-node/blob/doc/assets/Node-API%20v9%20Badge.svg) ![Node-API Experimental Version Badge](https://github.com/nodejs/abi-stable-node/blob/doc/assets/Node-API%20Experimental%20Version%20Badge.svg) -## **Contributing** +## Contributing We love contributions from the community to **node-addon-api**! See [CONTRIBUTING.md](CONTRIBUTING.md) for more details on our philosophy around extending this module. - - ## Team members ### Active + | Name | GitHub Link | | ------------------- | ----------------------------------------------------- | | Anna Henningsen | [addaleax](https://github.com/addaleax) | | Chengzhong Wu | [legendecas](https://github.com/legendecas) | -| Gabriel Schulhof | [gabrielschulhof](https://github.com/gabrielschulhof) | -| Jim Schlight | [jschlight](https://github.com/jschlight) | +| Jack Xia | [JckXia](https://github.com/JckXia) | +| Kevin Eady | [KevinEady](https://github.com/KevinEady) | | Michael Dawson | [mhdawson](https://github.com/mhdawson) | -| Kevin Eady | [KevinEady](https://github.com/KevinEady) | Nicola Del Gobbo | [NickNaso](https://github.com/NickNaso) | +| Vladimir Morozov | [vmoroz](https://github.com/vmoroz) | + +
+ +Emeritus ### Emeritus + | Name | GitHub Link | | ------------------- | ----------------------------------------------------- | | Arunesh Chandra | [aruneshchandra](https://github.com/aruneshchandra) | | Benjamin Byholm | [kkoopa](https://github.com/kkoopa) | -| Jason Ginchereau | [jasongin](https://github.com/jasongin) | +| Gabriel Schulhof | [gabrielschulhof](https://github.com/gabrielschulhof) | | Hitesh Kanwathirtha | [digitalinfinity](https://github.com/digitalinfinity) | +| Jason Ginchereau | [jasongin](https://github.com/jasongin) | +| Jim Schlight | [jschlight](https://github.com/jschlight) | | Sampson Gao | [sampsongao](https://github.com/sampsongao) | | Taylor Woll | [boingoing](https://github.com/boingoing) | - +
+ +## License Licensed under [MIT](./LICENSE.md) -[ABI stability guide]: https://nodejs.org/en/docs/guides/abi-stability/ -[Node-API support matrix]: https://nodejs.org/dist/latest/docs/api/n-api.html#n_api_n_api_version_matrix +[Node-API support matrix]: https://nodejs.org/dist/latest/docs/api/n-api.html#node-api-version-matrix diff --git a/benchmark/binding.gyp b/benchmark/binding.gyp index 72f68a13e..879d4a569 100644 --- a/benchmark/binding.gyp +++ b/benchmark/binding.gyp @@ -4,22 +4,22 @@ { 'target_name': 'function_args', 'sources': [ 'function_args.cc' ], - 'includes': [ '../except.gypi' ], + 'dependencies': ['../node_addon_api.gyp:node_addon_api_except'], }, { 'target_name': 'function_args_noexcept', 'sources': [ 'function_args.cc' ], - 'includes': [ '../noexcept.gypi' ], + 'dependencies': ['../node_addon_api.gyp:node_addon_api'], }, { 'target_name': 'property_descriptor', 'sources': [ 'property_descriptor.cc' ], - 'includes': [ '../except.gypi' ], + 'dependencies': ['../node_addon_api.gyp:node_addon_api_except'], }, { 'target_name': 'property_descriptor_noexcept', 'sources': [ 'property_descriptor.cc' ], - 'includes': [ '../noexcept.gypi' ], + 'dependencies': ['../node_addon_api.gyp:node_addon_api'], }, ] } diff --git a/common.gypi b/common.gypi index 9be254f0b..5fda7e77a 100644 --- a/common.gypi +++ b/common.gypi @@ -1,10 +1,11 @@ { 'variables': { - 'NAPI_VERSION%': " + +## API Documentation + +The following is the documentation for node-addon-api. + + - [Full Class Hierarchy](hierarchy.md) + - [Addon Structure](addon.md) + - Data Types: + - [BasicEnv](basic_env.md) + - [Env](env.md) + - [CallbackInfo](callbackinfo.md) + - [Reference](reference.md) + - [Value](value.md) + - [Name](name.md) + - [Symbol](symbol.md) + - [String](string.md) + - [Number](number.md) + - [Date](date.md) + - [BigInt](bigint.md) + - [Boolean](boolean.md) + - [External](external.md) + - [Object](object.md) + - [Array](array.md) + - [ObjectReference](object_reference.md) + - [PropertyDescriptor](property_descriptor.md) + - [Function](function.md) + - [FunctionReference](function_reference.md) + - [ObjectWrap](object_wrap.md) + - [ClassPropertyDescriptor](class_property_descriptor.md) + - [Buffer](buffer.md) + - [ArrayBuffer](array_buffer.md) + - [SharedArrayBuffer](shared_array_buffer.md) + - [TypedArray](typed_array.md) + - [TypedArrayOf](typed_array_of.md) + - [DataView](dataview.md) + - [Error Handling](error_handling.md) + - [Error](error.md) + - [TypeError](type_error.md) + - [RangeError](range_error.md) + - [SyntaxError](syntax_error.md) + - [Object Lifetime Management](object_lifetime_management.md) + - [HandleScope](handle_scope.md) + - [EscapableHandleScope](escapable_handle_scope.md) + - [Finalization](finalization.md) + - [Memory Management](memory_management.md) + - [Async Operations](async_operations.md) + - [AsyncWorker](async_worker.md) + - [AsyncContext](async_context.md) + - [AsyncWorker Variants](async_worker_variants.md) + - [Thread-safe Functions](threadsafe.md) + - [ThreadSafeFunction](threadsafe_function.md) + - [TypedThreadSafeFunction](typed_threadsafe_function.md) + - [Promises](promises.md) + - [Version management](version_management.md) + + + +## Examples + +Are you new to **node-addon-api**? Take a look at our **[examples](https://github.com/nodejs/node-addon-examples)** + +- [Hello World](https://github.com/nodejs/node-addon-examples/tree/main/src/1-getting-started/1_hello_world) +- [Pass arguments to a function](https://github.com/nodejs/node-addon-examples/tree/main/src/1-getting-started/2_function_arguments/node-addon-api) +- [Callbacks](https://github.com/nodejs/node-addon-examples/tree/main/src/1-getting-started/3_callbacks/node-addon-api) +- [Object factory](https://github.com/nodejs/node-addon-examples/tree/main/src/1-getting-started/4_object_factory/node-addon-api) +- [Function factory](https://github.com/nodejs/node-addon-examples/tree/main/src/1-getting-started/5_function_factory/node-addon-api) +- [Wrapping C++ Object](https://github.com/nodejs/node-addon-examples/tree/main/src/1-getting-started/6_object_wrap/node-addon-api) +- [Factory of wrapped object](https://github.com/nodejs/node-addon-examples/tree/main/src/1-getting-started/7_factory_wrap/node-addon-api) +- [Passing wrapped object around](https://github.com/nodejs/node-addon-examples/tree/main/src/2-js-to-native-conversion/8_passing_wrapped/node-addon-api) + + + +## ABI Stability Guideline + +It is important to remember that *other* Node.js interfaces such as +`libuv` (included in a project via `#include `) are not ABI-stable across +Node.js major versions. Thus, an addon must use Node-API and/or `node-addon-api` +exclusively and build against a version of Node.js that includes an +implementation of Node-API (meaning an active LTS version of Node.js) in +order to benefit from ABI stability across Node.js major versions. Node.js +provides an [ABI stability guide][] containing a detailed explanation of ABI +stability in general, and the Node-API ABI stability guarantee in particular. + + + +## More resource and info about native Addons + +There are three options for implementing addons: Node-API, nan, or direct +use of internal V8, libuv, and Node.js libraries. Unless there is a need for +direct access to functionality that is not exposed by Node-API as outlined +in [C/C++ addons](https://nodejs.org/dist/latest/docs/api/addons.html) +in Node.js core, use Node-API. Refer to +[C/C++ addons with Node-API](https://nodejs.org/dist/latest/docs/api/n-api.html) +for more information on Node-API. + +- [C++ Addons](https://nodejs.org/dist/latest/docs/api/addons.html) +- [Node-API](https://nodejs.org/dist/latest/docs/api/n-api.html) +- [Node-API - Next Generation Node API for Native Modules](https://youtu.be/-Oniup60Afs) +- [How We Migrated Realm JavaScript From NAN to Node-API](https://developer.mongodb.com/article/realm-javascript-nan-to-n-api) + +As node-addon-api's core mission is to expose the plain C Node-API as C++ +wrappers, tools that facilitate n-api/node-addon-api providing more +convenient patterns for developing a Node.js add-on with n-api/node-addon-api +can be published to NPM as standalone packages. It is also recommended to tag +such packages with `node-addon-api` to provide more visibility to the community. + +Quick links to NPM searches: [keywords:node-addon-api](https://www.npmjs.com/search?q=keywords%3Anode-addon-api). + + + +## Other bindings + +- [napi-rs](https://napi.rs) - (`Rust`) + +[ABI stability guide]: https://nodejs.org/en/docs/guides/abi-stability/ diff --git a/doc/array.md b/doc/array.md index 934808ba4..34badc243 100644 --- a/doc/array.md +++ b/doc/array.md @@ -9,7 +9,7 @@ around `napi_value` representing a JavaScript Array. types such as [`Napi::Int32Array`][] and [`Napi::ArrayBuffer`][], respectively, that can be used for transferring large amounts of data from JavaScript to the native side. An example illustrating the use of a JavaScript-provided -`ArrayBuffer` in native code is available [here](https://github.com/nodejs/node-addon-examples/tree/HEAD/array_buffer_to_native/node-addon-api). +`ArrayBuffer` in native code is available [here](https://github.com/nodejs/node-addon-examples/tree/main/src/2-js-to-native-conversion/array_buffer_to_native/node-addon-api). ## Constructor ```cpp diff --git a/doc/array_buffer.md b/doc/array_buffer.md index 0c12614f3..de05e55b3 100644 --- a/doc/array_buffer.md +++ b/doc/array_buffer.md @@ -23,18 +23,21 @@ Returns a new `Napi::ArrayBuffer` instance. ### New +> When `NODE_API_NO_EXTERNAL_BUFFERS_ALLOWED` is defined, this method is not available. +> See [External Buffer][] for more information. + Wraps the provided external data into a new `Napi::ArrayBuffer` instance. The `Napi::ArrayBuffer` instance does not assume ownership for the data and expects it to be valid for the lifetime of the instance. Since the `Napi::ArrayBuffer` is subject to garbage collection this overload is only -suitable for data which is static and never needs to be freed. -This factory method will not provide the caller with an opportunity to free the -data when the `Napi::ArrayBuffer` gets garbage-collected. If you need to free -the data retained by the `Napi::ArrayBuffer` object please use other -variants of the `Napi::ArrayBuffer::New` factory method that accept -`Napi::Finalizer`, which is a function that will be invoked when the -`Napi::ArrayBuffer` object has been destroyed. +suitable for data which is static and never needs to be freed. This factory +method will not provide the caller with an opportunity to free the data when the +`Napi::ArrayBuffer` gets garbage-collected. If you need to free the data +retained by the `Napi::ArrayBuffer` object please use other variants of the +`Napi::ArrayBuffer::New` factory method that accept `Napi::Finalizer`, which is +a function that will be invoked when the `Napi::ArrayBuffer` object has been +destroyed. See [Finalization][] for more details. ```cpp static Napi::ArrayBuffer Napi::ArrayBuffer::New(napi_env env, void* externalData, size_t byteLength); @@ -48,6 +51,9 @@ Returns a new `Napi::ArrayBuffer` instance. ### New +> When `NODE_API_NO_EXTERNAL_BUFFERS_ALLOWED` is defined, this method is not available. +> See [External Buffer][] for more information. + Wraps the provided external data into a new `Napi::ArrayBuffer` instance. The `Napi::ArrayBuffer` instance does not assume ownership for the data and @@ -66,14 +72,17 @@ static Napi::ArrayBuffer Napi::ArrayBuffer::New(napi_env env, - `[in] env`: The environment in which to create the `Napi::ArrayBuffer` instance. - `[in] externalData`: The pointer to the external data to wrap. - `[in] byteLength`: The length of the `externalData`, in bytes. -- `[in] finalizeCallback`: A function to be called when the `Napi::ArrayBuffer` is - destroyed. It must implement `operator()`, accept an Napi::Env, a `void*` (which is the - `externalData` pointer), and return `void`. +- `[in] finalizeCallback`: A function called when the engine destroys the + `Napi::ArrayBuffer` object, implementing `operator()(Napi::BasicEnv, void*)`. + See [Finalization][] for more details. Returns a new `Napi::ArrayBuffer` instance. ### New +> When `NODE_API_NO_EXTERNAL_BUFFERS_ALLOWED` is defined, this method is not available. +> See [External Buffer][] for more information. + Wraps the provided external data into a new `Napi::ArrayBuffer` instance. The `Napi::ArrayBuffer` instance does not assume ownership for the data and expects it @@ -93,11 +102,10 @@ static Napi::ArrayBuffer Napi::ArrayBuffer::New(napi_env env, - `[in] env`: The environment in which to create the `Napi::ArrayBuffer` instance. - `[in] externalData`: The pointer to the external data to wrap. - `[in] byteLength`: The length of the `externalData`, in bytes. -- `[in] finalizeCallback`: The function to be called when the `Napi::ArrayBuffer` is - destroyed. It must implement `operator()`, accept an Napi::Env, a `void*` (which is the - `externalData` pointer) and `Hint*`, and return `void`. -- `[in] finalizeHint`: The hint to be passed as the second parameter of the - finalize callback. +- `[in] finalizeCallback`: A function called when the engine destroys the + `Napi::ArrayBuffer` object, implementing `operator()(Napi::BasicEnv, void*, + Hint*)`. See [Finalization][] for more details. +- `[in] finalizeHint`: The hint value passed to the `finalizeCallback` function. Returns a new `Napi::ArrayBuffer` instance. @@ -153,3 +161,5 @@ bool Napi::ArrayBuffer::IsDetached() const; Returns `true` if this `ArrayBuffer` has been detached. [`Napi::Object`]: ./object.md +[External Buffer]: ./external_buffer.md +[Finalization]: ./finalization.md diff --git a/doc/async_worker.md b/doc/async_worker.md index 5d495a97c..2250d541d 100644 --- a/doc/async_worker.md +++ b/doc/async_worker.md @@ -418,6 +418,7 @@ Value Echo(const CallbackInfo& info) { EchoWorker* wk = new EchoWorker(cb, in); wk->Queue(); return info.Env().Undefined(); +} ``` Using the implementation of a `Napi::AsyncWorker` is straight forward. You only diff --git a/doc/async_worker_variants.md b/doc/async_worker_variants.md index 591cd8a57..876131aa8 100644 --- a/doc/async_worker_variants.md +++ b/doc/async_worker_variants.md @@ -51,8 +51,11 @@ virtual void Napi::AsyncProgressWorker::OnOK(); ### OnProgress -This method is invoked when the computation in the `Napi::AsyncProgressWorker::ExecutionProcess::Send` -method was called during worker thread execution. +This method is invoked when the computation in the +`Napi::AsyncProgressWorker::ExecutionProgress::Send` method was called during +worker thread execution. This method can also be triggered via a call to +`Napi::AsyncProgress[Queue]Worker::ExecutionProgress::Signal`, in which case the +`data` parameter will be `nullptr`. ```cpp virtual void Napi::AsyncProgressWorker::OnProgress(const T* data, size_t count) @@ -224,7 +227,7 @@ unexpected upcoming thread safe calls. virtual Napi::AsyncProgressWorker::~AsyncProgressWorker(); ``` -# AsyncProgressWorker::ExecutionProcess +# AsyncProgressWorker::ExecutionProgress A bridge class created before the worker thread execution of `Napi::AsyncProgressWorker::Execute`. @@ -232,15 +235,15 @@ A bridge class created before the worker thread execution of `Napi::AsyncProgres ### Send -`Napi::AsyncProgressWorker::ExecutionProcess::Send` takes two arguments, a pointer +`Napi::AsyncProgressWorker::ExecutionProgress::Send` takes two arguments, a pointer to a generic type of data, and a `size_t` to indicate how many items the pointer is pointing to. The data pointed to will be copied to internal slots of `Napi::AsyncProgressWorker` so -after the call to `Napi::AsyncProgressWorker::ExecutionProcess::Send` the data can +after the call to `Napi::AsyncProgressWorker::ExecutionProgress::Send` the data can be safely released. -Note that `Napi::AsyncProgressWorker::ExecutionProcess::Send` merely guarantees +Note that `Napi::AsyncProgressWorker::ExecutionProgress::Send` merely guarantees **eventual** invocation of `Napi::AsyncProgressWorker::OnProgress`, which means multiple send might be coalesced into single invocation of `Napi::AsyncProgressWorker::OnProgress` with latest data. If you would like to guarantee that there is one invocation of @@ -248,7 +251,16 @@ with latest data. If you would like to guarantee that there is one invocation of class instead which is documented further down this page. ```cpp -void Napi::AsyncProgressWorker::ExecutionProcess::Send(const T* data, size_t count) const; +void Napi::AsyncProgressWorker::ExecutionProgress::Send(const T* data, size_t count) const; +``` + +### Signal + +`Napi::AsyncProgressWorker::ExecutionProgress::Signal` triggers an invocation of +`Napi::AsyncProgressWorker::OnProgress` with `nullptr` as the `data` parameter. + +```cpp +void Napi::AsyncProgressWorker::ExecutionProgress::Signal(); ``` ## Example @@ -390,7 +402,7 @@ thread in the order it was committed. For the most basic use, only the `Napi::AsyncProgressQueueWorker::Execute` and `Napi::AsyncProgressQueueWorker::OnProgress` method must be implemented in a subclass. -# AsyncProgressQueueWorker::ExecutionProcess +# AsyncProgressQueueWorker::ExecutionProgress A bridge class created before the worker thread execution of `Napi::AsyncProgressQueueWorker::Execute`. @@ -398,21 +410,30 @@ A bridge class created before the worker thread execution of `Napi::AsyncProgres ### Send -`Napi::AsyncProgressQueueWorker::ExecutionProcess::Send` takes two arguments, a pointer +`Napi::AsyncProgressQueueWorker::ExecutionProgress::Send` takes two arguments, a pointer to a generic type of data, and a `size_t` to indicate how many items the pointer is pointing to. The data pointed to will be copied to internal slots of `Napi::AsyncProgressQueueWorker` so -after the call to `Napi::AsyncProgressQueueWorker::ExecutionProcess::Send` the data can +after the call to `Napi::AsyncProgressQueueWorker::ExecutionProgress::Send` the data can be safely released. -`Napi::AsyncProgressQueueWorker::ExecutionProcess::Send` guarantees invocation +`Napi::AsyncProgressQueueWorker::ExecutionProgress::Send` guarantees invocation of `Napi::AsyncProgressQueueWorker::OnProgress`, which means multiple `Send` call will result in the in-order invocation of `Napi::AsyncProgressQueueWorker::OnProgress` with each data item. ```cpp -void Napi::AsyncProgressQueueWorker::ExecutionProcess::Send(const T* data, size_t count) const; +void Napi::AsyncProgressQueueWorker::ExecutionProgress::Send(const T* data, size_t count) const; +``` + +### Signal + +`Napi::AsyncProgressQueueWorker::ExecutionProgress::Signal` triggers an invocation of +`Napi::AsyncProgressQueueWorker::OnProgress` with `nullptr` as the `data` parameter. + +```cpp +void Napi::AsyncProgressQueueWorker::ExecutionProgress::Signal() const; ``` ## Example diff --git a/doc/basic_env.md b/doc/basic_env.md new file mode 100644 index 000000000..840a5480f --- /dev/null +++ b/doc/basic_env.md @@ -0,0 +1,201 @@ +# BasicEnv + +The data structure containing the environment in which the request is being run. + +The `Napi::BasicEnv` object is usually created and passed by the Node.js runtime +or node-addon-api infrastructure. + +The `Napi::BasicEnv` object represents an environment that has a limited subset +of APIs when compared to `Napi::Env` and can be used in basic finalizers. See +[Finalization][] for more details. + +## Methods + +### Constructor + +```cpp +Napi::BasicEnv::BasicEnv(node_api_nogc_env env); +``` + +- `[in] env`: The `node_api_nogc_env` environment from which to construct the + `Napi::BasicEnv` object. + +### node_api_nogc_env + +```cpp +operator node_api_nogc_env() const; +``` + +Returns the `node_api_nogc_env` opaque data structure representing the +environment. + +### GetInstanceData +```cpp +template T* GetInstanceData() const; +``` + +Returns the instance data that was previously associated with the environment, +or `nullptr` if none was associated. + +### SetInstanceData + + +```cpp +template using Finalizer = void (*)(Env, T*); +template fini = Env::DefaultFini> +void SetInstanceData(T* data) const; +``` + +- `[template] fini`: A function to call when the instance data is to be deleted. +Accepts a function of the form `void CleanupData(Napi::Env env, T* data)`. If +not given, the default finalizer will be used, which simply uses the `delete` +operator to destroy `T*` when the add-on instance is unloaded. +- `[in] data`: A pointer to data that will be associated with the instance of +the add-on for the duration of its lifecycle. + +Associates a data item stored at `T* data` with the current instance of the +add-on. The item will be passed to the function `fini` which gets called when an +instance of the add-on is unloaded. + +### SetInstanceData + +```cpp +template +using FinalizerWithHint = void (*)(Env, DataType*, HintType*); +template fini = + Env::DefaultFiniWithHint> +void SetInstanceData(DataType* data, HintType* hint) const; +``` + +- `[template] fini`: A function to call when the instance data is to be deleted. +Accepts a function of the form `void CleanupData(Napi::Env env, DataType* data, +HintType* hint)`. If not given, the default finalizer will be used, which simply +uses the `delete` operator to destroy `DataType*` when the add-on instance is +unloaded. +- `[in] data`: A pointer to data that will be associated with the instance of +the add-on for the duration of its lifecycle. +- `[in] hint`: A pointer to data that will be associated with the instance of +the add-on for the duration of its lifecycle and will be passed as a hint to +`fini` when the add-on instance is unloaded. + +Associates a data item stored at `DataType* data` with the current instance of +the add-on. The item will be passed to the function `fini` which gets called +when an instance of the add-on is unloaded. This overload accepts an additional +hint to be passed to `fini`. + +### GetModuleFileName + +```cpp +const char* Napi::Env::GetModuleFileName() const; +``` + +Returns a URL containing the absolute path of the location from which the add-on +was loaded. For a file on the local file system it will start with `file://`. +The string is null-terminated and owned by env and must thus not be modified or +freed. It is only valid while the add-on is loaded. + +### AddCleanupHook + +```cpp +template +CleanupHook AddCleanupHook(Hook hook); +``` + +- `[in] hook`: A function to call when the environment exits. Accepts a function + of the form `void ()`. + +Registers `hook` as a function to be run once the current Node.js environment +exits. Unlike the underlying C-based Node-API, providing the same `hook` +multiple times **is** allowed. The hooks will be called in reverse order, i.e. +the most recently added one will be called first. + +Returns an `Env::CleanupHook` object, which can be used to remove the hook via +its `Remove()` method. + +### PostFinalizer + +```cpp +template +inline void PostFinalizer(FinalizerType finalizeCallback) const; +``` + +- `[in] finalizeCallback`: The function to queue for execution outside of the GC + finalization, implementing `operator()(Napi::Env)`. See [Finalization][] for + more details. + +### PostFinalizer + +```cpp +template +inline void PostFinalizer(FinalizerType finalizeCallback, T* data) const; +``` + +- `[in] finalizeCallback`: The function to queue for execution outside of the GC + finalization, implementing `operator()(Napi::Env, T*)`. See [Finalization][] + for more details. +- `[in] data`: The data to associate with the object. + +### PostFinalizer + +```cpp +template +inline void PostFinalizer(FinalizerType finalizeCallback, + T* data, + Hint* finalizeHint) const; +``` + +- `[in] finalizeCallback`: The function to queue for execution outside of the GC + finalization, implementing `operator()(Napi::Env, T*, Hint*)`. See + [Finalization][] for more details. +- `[in] data`: The data to associate with the object. +- `[in] finalizeHint`: The hint value passed to the `finalizeCallback` function. + +### AddCleanupHook + +```cpp +template +CleanupHook AddCleanupHook(Hook hook, Arg* arg); +``` + +- `[in] hook`: A function to call when the environment exits. Accepts a function + of the form `void (Arg* arg)`. +- `[in] arg`: A pointer to data that will be passed as the argument to `hook`. + +Registers `hook` as a function to be run with the `arg` parameter once the +current Node.js environment exits. Unlike the underlying C-based Node-API, +providing the same `hook` and `arg` pair multiple times **is** allowed. The +hooks will be called in reverse order, i.e. the most recently added one will be +called first. + +Returns an `Env::CleanupHook` object, which can be used to remove the hook via +its `Remove()` method. + +# Env::CleanupHook + +The `Env::CleanupHook` object allows removal of the hook added via +`Env::AddCleanupHook()` + +## Methods + +### IsEmpty + +```cpp +bool IsEmpty(); +``` + +Returns `true` if the cleanup hook was **not** successfully registered. + +### Remove + +```cpp +bool Remove(Env env); +``` + +Unregisters the hook from running once the current Node.js environment exits. + +Returns `true` if the hook was successfully removed from the Node.js +environment. + +[Finalization]: ./finalization.md diff --git a/doc/buffer.md b/doc/buffer.md index 1b6a3e1d6..548400481 100644 --- a/doc/buffer.md +++ b/doc/buffer.md @@ -22,18 +22,20 @@ Returns a new `Napi::Buffer` object. ### New +> When `NODE_API_NO_EXTERNAL_BUFFERS_ALLOWED` is defined, this method is not available. +> See [External Buffer][] for more information. + Wraps the provided external data into a new `Napi::Buffer` object. -The `Napi::Buffer` object does not assume ownership for the data and expects it to be -valid for the lifetime of the object. Since the `Napi::Buffer` is subject to garbage -collection this overload is only suitable for data which is static and never -needs to be freed. -This factory method will not provide the caller with an opportunity to free the -data when the `Napi::Buffer` gets garbage-collected. If you need to free the -data retained by the `Napi::Buffer` object please use other variants of the -`Napi::Buffer::New` factory method that accept `Napi::Finalizer`, which is a -function that will be invoked when the `Napi::Buffer` object has been -destroyed. +The `Napi::Buffer` object does not assume ownership for the data and expects it +to be valid for the lifetime of the object. Since the `Napi::Buffer` is subject +to garbage collection this overload is only suitable for data which is static +and never needs to be freed. This factory method will not provide the caller +with an opportunity to free the data when the `Napi::Buffer` gets +garbage-collected. If you need to free the data retained by the `Napi::Buffer` +object please use other variants of the `Napi::Buffer::New` factory method that +accept `Finalizer`, which is a function that will be invoked when the +`Napi::Buffer` object has been destroyed. See [Finalization][] for more details. ```cpp static Napi::Buffer Napi::Buffer::New(napi_env env, T* data, size_t length); @@ -47,6 +49,9 @@ Returns a new `Napi::Buffer` object. ### New +> When `NODE_API_NO_EXTERNAL_BUFFERS_ALLOWED` is defined, this method is not available. +> See [External Buffer][] for more information. + Wraps the provided external data into a new `Napi::Buffer` object. The `Napi::Buffer` object does not assume ownership for the data and expects it @@ -64,14 +69,17 @@ static Napi::Buffer Napi::Buffer::New(napi_env env, - `[in] env`: The environment in which to create the `Napi::Buffer` object. - `[in] data`: The pointer to the external data to expose. - `[in] length`: The number of `T` elements in the external data. -- `[in] finalizeCallback`: The function to be called when the `Napi::Buffer` is - destroyed. It must implement `operator()`, accept an Napi::Env, a `T*` (which is the - external data pointer), and return `void`. +- `[in] finalizeCallback`: The function called when the engine destroys the + `Napi::Buffer` object, implementing `operator()(Napi::BasicEnv, T*)`. See + [Finalization][] for more details. Returns a new `Napi::Buffer` object. ### New +> When `NODE_API_NO_EXTERNAL_BUFFERS_ALLOWED` is defined, this method is not available. +> See [External Buffer][] for more information. + Wraps the provided external data into a new `Napi::Buffer` object. The `Napi::Buffer` object does not assume ownership for the data and expects it to be @@ -90,11 +98,96 @@ static Napi::Buffer Napi::Buffer::New(napi_env env, - `[in] env`: The environment in which to create the `Napi::Buffer` object. - `[in] data`: The pointer to the external data to expose. - `[in] length`: The number of `T` elements in the external data. -- `[in] finalizeCallback`: The function to be called when the `Napi::Buffer` is - destroyed. It must implement `operator()`, accept an Napi::Env, a `T*` (which is the - external data pointer) and `Hint*`, and return `void`. -- `[in] finalizeHint`: The hint to be passed as the second parameter of the - finalize callback. +- `[in] finalizeCallback`: The function called when the engine destroys the + `Napi::Buffer` object, implementing `operator()(Napi::BasicEnv, T*, Hint*)`. + See [Finalization][] for more details. +- `[in] finalizeHint`: The hint value passed to the `finalizeCallback` function. + +Returns a new `Napi::Buffer` object. + +### NewOrCopy + +Wraps the provided external data into a new `Napi::Buffer` object. When the +[external buffer][] is not supported, allocates a new `Napi::Buffer` object and +copies the provided external data into it. + +The `Napi::Buffer` object does not assume ownership for the data and expects it to be +valid for the lifetime of the object. Since the `Napi::Buffer` is subject to garbage +collection this overload is only suitable for data which is static and never +needs to be freed. + +This factory method will not provide the caller with an opportunity to free the +data when the `Napi::Buffer` gets garbage-collected. If you need to free the +data retained by the `Napi::Buffer` object please use other variants of the +`Napi::Buffer::New` factory method that accept `Napi::Finalizer`, which is a +function that will be invoked when the `Napi::Buffer` object has been +destroyed. + +```cpp +static Napi::Buffer Napi::Buffer::NewOrCopy(napi_env env, T* data, size_t length); +``` + +- `[in] env`: The environment in which to create the `Napi::Buffer` object. +- `[in] data`: The pointer to the external data to expose. +- `[in] length`: The number of `T` elements in the external data. + +Returns a new `Napi::Buffer` object. + +### NewOrCopy + +Wraps the provided external data into a new `Napi::Buffer` object. When the +[external buffer][] is not supported, allocates a new `Napi::Buffer` object and +copies the provided external data into it and the `finalizeCallback` is invoked +immediately. + +The `Napi::Buffer` object does not assume ownership for the data and expects it +to be valid for the lifetime of the object. The data can only be freed once the +`finalizeCallback` is invoked to indicate that the `Napi::Buffer` has been released. + +```cpp +template +static Napi::Buffer Napi::Buffer::NewOrCopy(napi_env env, + T* data, + size_t length, + Finalizer finalizeCallback); +``` + +- `[in] env`: The environment in which to create the `Napi::Buffer` object. +- `[in] data`: The pointer to the external data to expose. +- `[in] length`: The number of `T` elements in the external data. +- `[in] finalizeCallback`: The function called when the engine destroys the + `Napi::Buffer` object, implementing `operator()(Napi::BasicEnv, T*)`. See + [Finalization][] for more details. + +Returns a new `Napi::Buffer` object. + +### NewOrCopy + +Wraps the provided external data into a new `Napi::Buffer` object. When the +[external buffer][] is not supported, allocates a new `Napi::Buffer` object and +copies the provided external data into it and the `finalizeCallback` is invoked +immediately. + +The `Napi::Buffer` object does not assume ownership for the data and expects it to be +valid for the lifetime of the object. The data can only be freed once the +`finalizeCallback` is invoked to indicate that the `Napi::Buffer` has been released. + +```cpp +template +static Napi::Buffer Napi::Buffer::NewOrCopy(napi_env env, + T* data, + size_t length, + Finalizer finalizeCallback, + Hint* finalizeHint); +``` + +- `[in] env`: The environment in which to create the `Napi::Buffer` object. +- `[in] data`: The pointer to the external data to expose. +- `[in] length`: The number of `T` elements in the external data. +- `[in] finalizeCallback`: The function called when the engine destroys the + `Napi::Buffer` object, implementing `operator()(Napi::BasicEnv, T*, Hint*)`. + See [Finalization][] for more details. +- `[in] finalizeHint`: The hint value passed to the `finalizeCallback` function. Returns a new `Napi::Buffer` object. @@ -148,3 +241,5 @@ size_t Napi::Buffer::Length() const; Returns the number of `T` elements in the external data. [`Napi::Uint8Array`]: ./typed_array_of.md +[External Buffer]: ./external_buffer.md +[Finalization]: ./finalization.md diff --git a/doc/cmake-js.md b/doc/cmake-js.md index bbd73d687..1d5df91ca 100644 --- a/doc/cmake-js.md +++ b/doc/cmake-js.md @@ -45,13 +45,32 @@ The following line in the `CMakeLists.txt` file will enable Node-API experimenta add_definitions(-DNAPI_EXPERIMENTAL) ``` +### Exception Handling + +To enable C++ exception handling (for more info see: [Setup](setup.md)), define +the corresponding preprocessor directives depending on which exception handling +behavior is desired. + +To enable C++ exception handling with `Napi::Error` objects only: + +``` +add_definitions(-DNODE_ADDON_API_CPP_EXCEPTIONS) +``` + +To enable C++ exception handling for all exceptions thrown: + +``` +add_definitions(-DNODE_ADDON_API_CPP_EXCEPTIONS) +add_definitions(-DNODE_ADDON_API_CPP_EXCEPTIONS_ALL) +``` + ### node-addon-api If your Node-API native add-on uses the optional [**node-addon-api**](https://github.com/nodejs/node-addon-api#node-addon-api-module) C++ wrapper, the `CMakeLists.txt` file requires additional configuration information as described on the [CMake.js README file](https://github.com/cmake-js/cmake-js#node-api-and-node-addon-api). ## Example -A working example of an Node-API native addon built using CMake.js can be found on the [node-addon-examples repository](https://github.com/nodejs/node-addon-examples/tree/HEAD/build_with_cmake#building-n-api-addons-using-cmakejs). +A working example of an Node-API native addon built using CMake.js can be found on the [node-addon-examples repository](https://github.com/nodejs/node-addon-examples/tree/main/src/8-tooling/build_with_cmake#building-node-api-addons-using-cmakejs). ## **CMake** Reference diff --git a/doc/contributing/build_with_ninja.md b/doc/contributing/build_with_ninja.md new file mode 100644 index 000000000..d59e9bbef --- /dev/null +++ b/doc/contributing/build_with_ninja.md @@ -0,0 +1,16 @@ +# Build Test with Ninja + +Ninja can be used to speed up building tests with optimized parallelism. + +To build the tests with ninja and node-gyp, run the following commands: + +```sh +/node-addon-api $ node-gyp configure -C test -- -f ninja +/node-addon-api $ ninja -C test/build/Release +# Run tests +/node-addon-api $ node ./test/index.js + +# Run tests with debug addon +/node-addon-api $ ninja -C test/build/Debug +/node-addon-api $ NODE_API_BUILD_CONFIG=Debug node ./test/index.js +``` diff --git a/doc/creating_a_release.md b/doc/contributing/creating_a_release.md similarity index 57% rename from doc/creating_a_release.md rename to doc/contributing/creating_a_release.md index 5299964ad..02e9cbc53 100644 --- a/doc/creating_a_release.md +++ b/doc/contributing/creating_a_release.md @@ -6,7 +6,17 @@ collaborators to add you. If necessary you can ask the build Working Group who manages the Node.js npm user to add you if there are no other active collaborators. -## Prerequisites +Generally, the release is handled by the +[release-please](https://github.com/nodejs/node-addon-api/blob/main/.github/workflows/release-please.yml) +GitHub action. It will bump the version in `package.json` and publish +node-addon-api to npm. + +In cases that the release-please action is not working, please follow the steps +below to publish node-addon-api manually. + +## Publish new release manually + +### Prerequisites Before to start creating a new release check if you have installed the following tools: @@ -16,7 +26,7 @@ tools: If not please follow the instruction reported in the tool's documentation to install it. -## Publish new release +### Steps These are the steps to follow to create a new release: @@ -34,14 +44,16 @@ to show the new version as the latest. the route folder of the repo launch the following command: ```bash - > changelog-maker + > changelog-maker --md --group --filter-release ``` * Use the output generated by **changelog maker** to update the [CHANGELOG.md](https://github.com/nodejs/node-addon-api/blob/main/CHANGELOG.md) following the style used in publishing the previous release. * Add any new contributors to the "contributors" section in the package.json -* Validate all tests pass by running `npm test` on the `main` branch. +* Commit with a message containing _only_ an x.y.z semver designator. "x.y.z" (so that the commit can be filtered by changelog-maker) + +* Create a release proposal pull request. * Use **[CI](https://ci.nodejs.org/view/x%20-%20Abi%20stable%20module%20API/job/node-test-node-addon-api-new/)** to validate tests pass (note there are still some issues on SmartOS and @@ -60,3 +72,24 @@ and that the correct version is installed. and close the issue. * Tweet that the release has been created. + +## Optional Steps + +Depending on circumstances for the release, additional steps may be required to +support the release process. + +### Major Releases to Drop Support Node.js Versions + +`node-addon-api` provides support for Node.js versions following the same +[release schedule](https://nodejs.dev/en/about/releases/): once a Node.js +version leaves maintenance mode, the next major version of `node-addon-api` +published will drop support for that version. These are the steps to follow to +drop support for a Node.js version: + +* Update minimum version supported in documentation ([README.md](../README.md)) + +* Remove from GitHub actions ([ci.yml](../.github/workflows/ci.yml) and + [ci-win.yml](../.github/workflows/ci-win.yml)) + +* Remove from Jenkins CI ([node-test-node-addon-api-LTS versions + [Jenkins]](https://ci.nodejs.org/view/x%20-%20Abi%20stable%20module%20API/job/node-test-node-addon-api-LTS%20versions/)) diff --git a/doc/dataview.md b/doc/dataview.md index 66fb28919..619ceecca 100644 --- a/doc/dataview.md +++ b/doc/dataview.md @@ -6,6 +6,11 @@ The `Napi::DataView` class corresponds to the [JavaScript `DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) class. +**NOTE**: The support for `Napi::DataView::New()` overloads accepting an +`Napi::SharedArrayBuffer` parameter is only available when using +`NAPI_EXPERIMENTAL` and building against Node.js headers that support this +feature. + ## Methods ### New @@ -50,6 +55,48 @@ static Napi::DataView Napi::DataView::New(napi_env env, Napi::ArrayBuffer arrayB Returns a new `Napi::DataView` instance. +### New + +Allocates a new `Napi::DataView` instance with a given `Napi::SharedArrayBuffer`. + +```cpp +static Napi::DataView Napi::DataView::New(napi_env env, Napi::SharedArrayBuffer sharedArrayBuffer); +``` + +- `[in] env`: The environment in which to create the `Napi::DataView` instance. +- `[in] sharedArrayBuffer` : `Napi::SharedArrayBuffer` underlying the `Napi::DataView`. + +Returns a new `Napi::DataView` instance. + +### New + +Allocates a new `Napi::DataView` instance with a given `Napi::SharedArrayBuffer`. + +```cpp +static Napi::DataView Napi::DataView::New(napi_env env, Napi::SharedArrayBuffer sharedArrayBuffer, size_t byteOffset); +``` + +- `[in] env`: The environment in which to create the `Napi::DataView` instance. +- `[in] sharedArrayBuffer` : `Napi::SharedArrayBuffer` underlying the `Napi::DataView`. +- `[in] byteOffset` : The byte offset within the `Napi::SharedArrayBuffer` from which to start projecting the `Napi::DataView`. + +Returns a new `Napi::DataView` instance. + +### New + +Allocates a new `Napi::DataView` instance with a given `Napi::SharedArrayBuffer`. + +```cpp +static Napi::DataView Napi::DataView::New(napi_env env, Napi::SharedArrayBuffer sharedArrayBuffer, size_t byteOffset, size_t byteLength); +``` + +- `[in] env`: The environment in which to create the `Napi::DataView` instance. +- `[in] sharedArrayBuffer` : `Napi::SharedArrayBuffer` underlying the `Napi::DataView`. +- `[in] byteOffset` : The byte offset within the `Napi::SharedArrayBuffer` from which to start projecting the `Napi::DataView`. +- `[in] byteLength` : Number of elements in the `Napi::DataView`. + +Returns a new `Napi::DataView` instance. + ### Constructor Initializes an empty instance of the `Napi::DataView` class. @@ -75,7 +122,22 @@ Napi::DataView(napi_env env, napi_value value); Napi::ArrayBuffer Napi::DataView::ArrayBuffer() const; ``` -Returns the backing array buffer. +Returns the backing array buffer as an `Napi::ArrayBuffer`. + +**NOTE**: If the `Napi::DataView` is not backed by an `Napi::ArrayBuffer`, this +method will terminate the process with a fatal error when using +`NODE_ADDON_API_ENABLE_TYPE_CHECK_ON_AS` or exhibit undefined behavior +otherwise. Use `Buffer()` instead to get the backing buffer without assuming its +type. + +### Buffer + +```cpp +Napi::Value Napi::DataView::Buffer() const; +``` + +Returns the backing array buffer as a generic `Napi::Value`, allowing optional +type-checking with `Is*()` and type-casting with `As<>()` methods. ### ByteOffset diff --git a/doc/date.md b/doc/date.md index 4c5fefa5e..7131b016f 100644 --- a/doc/date.md +++ b/doc/date.md @@ -37,6 +37,20 @@ static Napi::Date Napi::Date::New(Napi::Env env, double value); Returns a new instance of `Napi::Date` object. +### New + +Creates a new instance of a `Napi::Date` object. + +```cpp +static Napi::Date Napi::Date::New(napi_env env, std::chrono::system_clock::time_point time_point); +``` + + - `[in] env`: The environment in which to construct the `Napi::Date` object. + - `[in] value`: The point in time, represented by an + `std::chrono::system_clock::time_point`. + +Returns a new instance of `Napi::Date` object. + ### ValueOf ```cpp diff --git a/doc/env.md b/doc/env.md index 9842de6bb..7773275ee 100644 --- a/doc/env.md +++ b/doc/env.md @@ -1,8 +1,15 @@ # Env -The opaque data structure containing the environment in which the request is being run. +Class `Napi::Env` inherits from class [`Napi::BasicEnv`][]. -The Env object is usually created and passed by the Node.js runtime or node-addon-api infrastructure. +The data structure containing the environment in which the request is being run. + +The `Napi::Env` object is usually created and passed by the Node.js runtime or +node-addon-api infrastructure. + +The `Napi::Env` object represents an environment that has a superset of APIs +when compared to `Napi::BasicEnv` and therefore _cannot_ be used in basic +finalizers. See [Finalization][] for more details. ## Methods @@ -76,121 +83,5 @@ The `script` can be any of the following types: - `const char *` - `const std::string &` -### GetInstanceData -```cpp -template T* GetInstanceData() const; -``` - -Returns the instance data that was previously associated with the environment, -or `nullptr` if none was associated. - -### SetInstanceData - -```cpp -template using Finalizer = void (*)(Env, T*); -template fini = Env::DefaultFini> -void SetInstanceData(T* data) const; -``` - -- `[template] fini`: A function to call when the instance data is to be deleted. -Accepts a function of the form `void CleanupData(Napi::Env env, T* data)`. If -not given, the default finalizer will be used, which simply uses the `delete` -operator to destroy `T*` when the addon instance is unloaded. -- `[in] data`: A pointer to data that will be associated with the instance of -the addon for the duration of its lifecycle. - -Associates a data item stored at `T* data` with the current instance of the -addon. The item will be passed to the function `fini` which gets called when an -instance of the addon is unloaded. - -### SetInstanceData - -```cpp -template -using FinalizerWithHint = void (*)(Env, DataType*, HintType*); -template fini = - Env::DefaultFiniWithHint> -void SetInstanceData(DataType* data, HintType* hint) const; -``` - -- `[template] fini`: A function to call when the instance data is to be deleted. -Accepts a function of the form -`void CleanupData(Napi::Env env, DataType* data, HintType* hint)`. If not given, -the default finalizer will be used, which simply uses the `delete` operator to -destroy `T*` when the addon instance is unloaded. -- `[in] data`: A pointer to data that will be associated with the instance of -the addon for the duration of its lifecycle. -- `[in] hint`: A pointer to data that will be associated with the instance of -the addon for the duration of its lifecycle and will be passed as a hint to -`fini` when the addon instance is unloaded. - -Associates a data item stored at `T* data` with the current instance of the -addon. The item will be passed to the function `fini` which gets called when an -instance of the addon is unloaded. This overload accepts an additional hint to -be passed to `fini`. - -### AddCleanupHook - -```cpp -template -CleanupHook AddCleanupHook(Hook hook); -``` - -- `[in] hook`: A function to call when the environment exists. Accepts a - function of the form `void ()`. - -Registers `hook` as a function to be run once the current Node.js environment -exits. Unlike the underlying C-based Node-API, providing the same `hook` -multiple times **is** allowed. The hooks will be called in reverse order, i.e. -the most recently added one will be called first. - -Returns an `Env::CleanupHook` object, which can be used to remove the hook via -its `Remove()` method. - -### AddCleanupHook - -```cpp -template -CleanupHook AddCleanupHook(Hook hook, Arg* arg); -``` - -- `[in] hook`: A function to call when the environment exists. Accepts a - function of the form `void (Arg* arg)`. -- `[in] arg`: A pointer to data that will be passed as the argument to `hook`. - -Registers `hook` as a function to be run with the `arg` parameter once the -current Node.js environment exits. Unlike the underlying C-based Node-API, -providing the same `hook` and `arg` pair multiple times **is** allowed. The -hooks will be called in reverse order, i.e. the most recently added one will be -called first. - -Returns an `Env::CleanupHook` object, which can be used to remove the hook via -its `Remove()` method. - -# Env::CleanupHook - -The `Env::CleanupHook` object allows removal of the hook added via -`Env::AddCleanupHook()` - -## Methods - -### IsEmpty - -```cpp -bool IsEmpty(); -``` - -Returns `true` if the cleanup hook was **not** successfully registered. - -### Remove - -```cpp -bool Remove(Env env); -``` - -Unregisters the hook from running once the current Node.js environment exits. - -Returns `true` if the hook was successfully removed from the Node.js -environment. +[`Napi::BasicEnv`]: ./basic_env.md +[Finalization]: ./finalization.md diff --git a/doc/error_handling.md b/doc/error_handling.md index 6882d599f..b4b4ca238 100644 --- a/doc/error_handling.md +++ b/doc/error_handling.md @@ -26,7 +26,7 @@ The following sections explain the approach for each case: In most cases when an error occurs, the addon should do whatever cleanup is possible -and then return to JavaScript so that the error can be propagated. In less frequent +and then return to JavaScript so that the error can be propagated. In less frequent cases the addon may be able to recover from the error, clear the error and then continue. @@ -48,8 +48,20 @@ method. If a C++ exception of type `Napi::Error` escapes from a Node-API C++ callback, then the Node-API wrapper automatically converts and throws it as a JavaScript exception. -On return from a native method, node-addon-api will automatically convert a pending C++ -exception to a JavaScript exception. +If other types of C++ exceptions are thrown, node-addon-api will either abort +the process or wrap the exception in an `Napi::Error` in order to throw it as a +JavaScript exception. This behavior is determined by which node-gyp dependency +used: + +- When using the `node_addon_api_except` dependency, only `Napi::Error` objects + will be handled. +- When using the `node_addon_api_except_all` dependency, all exceptions will be +handled. For exceptions derived from `std::exception`, an `Napi::Error` will be +created with the message of the exception's `what()` member function. For all +other exceptions, an `Napi::Error` will be created with a generic error message. + +On return from a native method, node-addon-api will automatically convert a pending +`Napi::Error` C++ exception to a JavaScript exception. When C++ exceptions are enabled try/catch can be used to catch exceptions thrown from calls to JavaScript and then they can either be handled or rethrown before diff --git a/doc/external.md b/doc/external.md index 814eb037c..1c48560b6 100644 --- a/doc/external.md +++ b/doc/external.md @@ -1,10 +1,21 @@ # External (template) -Class `Napi::External` inherits from class [`Napi::Value`][]. +Class `Napi::External` inherits from class [`Napi::TypeTaggable`][]. 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. -`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. +`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. See [Finalization][] for more details. + +Note that `Napi::Value::IsExternal()` will return `true` for any external value. +It does not differentiate between the templated parameter `T` in +`Napi::External`. It is up to the addon to ensure an `Napi::External` +object holds the correct `T` when retrieving the data via +`Napi::External::Data()`. One method to ensure an object is of a specific +type is through [type tags](./object.md#TypeTag). ## Methods @@ -24,14 +35,15 @@ Returns the created `Napi::External` object. ```cpp template -static Napi::External Napi::External::New(napi_env env, - T* data, - Finalizer finalizeCallback); +template +static External New(napi_env env, T* data, Finalizer finalizeCallback); ``` - `[in] env`: The `napi_env` environment in which to construct the `Napi::External` object. - `[in] data`: The arbitrary C++ data to be held by the `Napi::External` object. -- `[in] finalizeCallback`: A function called when the `Napi::External` object is released by the garbage collector accepting a T* and returning void. +- `[in] finalizeCallback`: The function called when the engine destroys the + `Napi::External` object, implementing `operator()(Napi::BasicEnv, T*)`. See + [Finalization][] for more details. Returns the created `Napi::External` object. @@ -39,7 +51,8 @@ Returns the created `Napi::External` object. ```cpp template -static Napi::External Napi::External::New(napi_env env, +template +static External New(napi_env env, T* data, Finalizer finalizeCallback, Hint* finalizeHint); @@ -47,8 +60,10 @@ static Napi::External Napi::External::New(napi_env env, - `[in] env`: The `napi_env` environment in which to construct the `Napi::External` object. - `[in] data`: The arbitrary C++ data to be held by the `Napi::External` object. -- `[in] finalizeCallback`: A function called when the `Napi::External` object is released by the garbage collector accepting T* and Hint* parameters and returning void. -- `[in] finalizeHint`: A hint value passed to the `finalizeCallback` function. +- `[in] finalizeCallback`: The function called when the engine destroys the + `Napi::External` object, implementing `operator()(Napi::BasicEnv, T*, Hint*)`. + See [Finalization][] for more details. +- `[in] finalizeHint`: The hint value passed to the `finalizeCallback` function. Returns the created `Napi::External` object. @@ -60,4 +75,5 @@ T* Napi::External::Data() const; Returns a pointer to the arbitrary C++ data held by the `Napi::External` object. -[`Napi::Value`]: ./value.md +[Finalization]: ./finalization.md +[`Napi::TypeTaggable`]: ./type_taggable.md diff --git a/doc/external_buffer.md b/doc/external_buffer.md new file mode 100644 index 000000000..25942436a --- /dev/null +++ b/doc/external_buffer.md @@ -0,0 +1,18 @@ +# External Buffer + +**Some runtimes other than Node.js have dropped support for external buffers**. +On runtimes other than Node.js, node-api methods may return +`napi_no_external_buffers_allowed` to indicate that external +buffers are not supported. One such runtime is Electron as +described in this issue +[electron/issues/35801](https://github.com/electron/electron/issues/35801). + +In order to maintain broadest compatibility with all runtimes, +you may define `NODE_API_NO_EXTERNAL_BUFFERS_ALLOWED` in your addon before +includes for the node-api and node-addon-api headers. Doing so will hide the +functions that create external buffers. This will ensure a compilation error +occurs if you accidentally use one of these methods. + +In node-addon-api, the `Napi::Buffer::NewOrCopy` provides a convenient way to +create an external buffer, or allocate a new buffer and copy the data when the +external buffer is not supported. diff --git a/doc/finalization.md b/doc/finalization.md new file mode 100644 index 000000000..3dc4e7860 --- /dev/null +++ b/doc/finalization.md @@ -0,0 +1,153 @@ +# Finalization + +Various node-addon-api methods accept a templated `Finalizer finalizeCallback` +parameter. This parameter represents a native callback function that runs in +response to a garbage collection event. A finalizer is considered a _basic_ +finalizer if the callback only utilizes a certain subset of APIs, which may +provide more efficient memory management, optimizations, improved execution, or +other benefits. + +In general, it is best to use basic finalizers whenever possible (eg. when +access to JavaScript is _not_ needed). The +`NODE_ADDON_API_REQUIRE_BASIC_FINALIZERS` preprocessor directive can be defined +to ensure that all finalizers are basic. + +## Finalizers + +The callback takes `Napi::Env` as its first argument: + +### Example + +```cpp +Napi::External::New(Env(), new int(1), [](Napi::Env env, int* data) { + env.RunScript("console.log('Finalizer called')"); + delete data; +}); +``` + +## Basic Finalizers + +Use of basic finalizers may allow the engine to perform optimizations when +scheduling or executing the callback. For example, V8 does not allow access to +the engine heap during garbage collection. Restricting finalizers from accessing +the engine heap allows the callback to execute during garbage collection, +providing a chance to free native memory eagerly. + +In general, APIs that access engine heap are not allowed in basic finalizers. + +The callback takes `Napi::BasicEnv` as its first argument: + +### Example + +```cpp +Napi::ArrayBuffer::New( + Env(), data, length, [](Napi::BasicEnv /*env*/, void* finalizeData) { + delete[] static_cast(finalizeData); + }); +``` + +## Scheduling Finalizers + +In addition to passing finalizers to `Napi::External`s and other Node-API +constructs, `Napi::BasicEnv::PostFinalize(Napi::BasicEnv, Finalizer)` can be +used to schedule a callback to run outside of the garbage collector +finalization. Since the associated native memory may already be freed by the +basic finalizer, any additional data may be passed eg. via the finalizer's +parameters (`T data*`, `Hint hint*`) or via lambda capture. This allows for +freeing native data in a basic finalizer, while executing any JavaScript code in +an additional finalizer. + +### Example + +```cpp +// Native Add-on + +#include +#include +#include "napi.h" + +using namespace Napi; + +// A structure representing some data that uses a "large" amount of memory. +class LargeData { + public: + LargeData() : id(instances++) {} + size_t id; + + static size_t instances; +}; + +size_t LargeData::instances = 0; + +// Basic finalizer to free `LargeData`. Takes ownership of the pointer and +// frees its memory after use. +void MyBasicFinalizer(Napi::BasicEnv env, LargeData* data) { + std::unique_ptr instance(data); + std::cout << "Basic finalizer for instance " << instance->id + << " called\n"; + + // Register a finalizer. Since the instance will be deleted by + // the time this callback executes, pass the instance's `id` via lambda copy + // capture and _not_ a reference capture that accesses `this`. + env.PostFinalizer([instanceId = instance->id](Napi::Env env) { + env.RunScript("console.log('Finalizer for instance " + + std::to_string(instanceId) + " called');"); + }); + + // Free the `LargeData` held in `data` once `instance` goes out of scope. +} + +Value CreateExternal(const CallbackInfo& info) { + // Create a new instance of LargeData. + auto instance = std::make_unique(); + + // Wrap the instance in an External object, registering a basic + // finalizer that will delete the instance to free the "large" amount of + // memory. + return External::New(info.Env(), instance.release(), MyBasicFinalizer); +} + +Object Init(Napi::Env env, Object exports) { + exports["createExternal"] = Function::New(env, CreateExternal); + return exports; +} + +NODE_API_MODULE(addon, Init) +``` + +```js +// JavaScript + +const { createExternal } = require('./addon.node'); + +for (let i = 0; i < 5; i++) { + const ext = createExternal(); + // ... do something with `ext` .. +} + +console.log('Loop complete'); +await new Promise(resolve => setImmediate(resolve)); +console.log('Next event loop cycle'); +``` + +Possible output: + +``` +Basic finalizer for instance 0 called +Basic finalizer for instance 1 called +Basic finalizer for instance 2 called +Basic finalizer for instance 3 called +Basic finalizer for instance 4 called +Loop complete +Finalizer for instance 3 called +Finalizer for instance 4 called +Finalizer for instance 1 called +Finalizer for instance 2 called +Finalizer for instance 0 called +Next event loop cycle +``` + +If the garbage collector runs during the loop, the basic finalizers execute and +display their logging message synchronously during the loop execution. The +additional finalizers execute at some later point after the garbage collection +cycle. diff --git a/doc/hierarchy.md b/doc/hierarchy.md index 68092ea24..440f7a6c6 100644 --- a/doc/hierarchy.md +++ b/doc/hierarchy.md @@ -20,7 +20,7 @@ | [`Napi::Env`][] | | | [`Napi::Error`][] | [`Napi::ObjectReference`][], [`std::exception`][] | | [`Napi::EscapableHandleScope`][] | | -| [`Napi::External`][] | [`Napi::Value`][] | +| [`Napi::External`][] | [`Napi::TypeTaggable`][] | | [`Napi::Function`][] | [`Napi::Object`][] | | [`Napi::FunctionReference`][] | [`Napi::Reference`][] | | [`Napi::HandleScope`][] | | @@ -28,7 +28,7 @@ | [`Napi::MemoryManagement`][] | | | [`Napi::Name`][] | [`Napi::Value`][] | | [`Napi::Number`][] | [`Napi::Value`][] | -| [`Napi::Object`][] | [`Napi::Value`][] | +| [`Napi::Object`][] | [`Napi::TypeTaggable`][] | | [`Napi::ObjectReference`][] | [`Napi::Reference`][] | | [`Napi::ObjectWrap`][] | [`Napi::InstanceWrap`][], [`Napi::Reference`][] | | [`Napi::Promise`][] | [`Napi::Object`][] | @@ -37,7 +37,9 @@ | [`Napi::Reference`] | | | [`Napi::String`][] | [`Napi::Name`][] | | [`Napi::Symbol`][] | [`Napi::Name`][] | +| [`Napi::SyntaxError`][] | [`Napi::Error`][] | | [`Napi::ThreadSafeFunction`][] | | +| [`Napi::TypeTaggable`][] | [`Napi::Value][] | | [`Napi::TypeError`][] | [`Napi::Error`][] | | [`Napi::TypedArray`][] | [`Napi::Object`][] | | [`Napi::TypedArrayOf`][] | [`Napi::TypedArray`][] | @@ -81,8 +83,10 @@ [`Napi::Reference`]: ./reference.md [`Napi::String`]: ./string.md [`Napi::Symbol`]: ./symbol.md +[`Napi::SyntaxError`]: ./syntax_error.md [`Napi::ThreadSafeFunction`]: ./threadsafe_function.md [`Napi::TypeError`]: ./type_error.md +[`Napi::TypeTaggable`]: ./type_taggable.md [`Napi::TypedArray`]: ./typed_array.md [`Napi::TypedArrayOf`]: ./typed_array_of.md [`Napi::Uint8Array`]: ./typed_array_of.md diff --git a/doc/memory_management.md b/doc/memory_management.md index afa622550..882c0f802 100644 --- a/doc/memory_management.md +++ b/doc/memory_management.md @@ -17,7 +17,7 @@ more often than it would otherwise in an attempt to garbage collect the JavaScri objects that keep the externally allocated memory alive. ```cpp -static int64_t Napi::MemoryManagement::AdjustExternalMemory(Napi::Env env, int64_t change_in_bytes); +static int64_t Napi::MemoryManagement::AdjustExternalMemory(Napi::BasicEnv env, int64_t change_in_bytes); ``` - `[in] env`: The environment in which the API is invoked under. diff --git a/doc/node-gyp.md b/doc/node-gyp.md index 529aa0ea2..a39d5b8c0 100644 --- a/doc/node-gyp.md +++ b/doc/node-gyp.md @@ -4,19 +4,19 @@ C++ code needs to be compiled into executable form whether it be as an object file to linked with others, a shared library, or a standalone executable. The main reason for this is that we need to link to the Node.js dependencies and -headers correctly, another reason is that we need a cross platform way to build +headers correctly. Another reason is that we need a cross-platform way to build C++ source into binary for the target platform. -Until now **node-gyp** is the **de-facto** standard build tool for writing -Node.js addons. It's based on Google's **gyp** build tool, which abstract away -many of the tedious issues related to cross platform building. +**node-gyp** remains the **de-facto** standard build tool for writing +Node.js addons. It's based on Google's **gyp** build tool, which abstracts away +many of the tedious issues related to cross-platform building. -**node-gyp** uses a file called ```binding.gyp``` that is located on the root of +**node-gyp** uses a file called `binding.gyp` that is located in the root of your addon project. -```binding.gyp``` file, contains all building configurations organized with a -JSON like syntax. The most important parameter is the **target** that must be -set to the same value used on the initialization code of the addon as in the +The `binding.gyp` file contains all building configurations organized with a +JSON-like syntax. The most important parameter is the **target** that must be +set to the same value used in the initialization code of the addon, as in the examples reported below: ### **binding.gyp** @@ -41,8 +41,8 @@ examples reported below: // ... /** -* This code is our entry-point. We receive two arguments here, the first is the -* environment that represent an independent instance of the JavaScript runtime, +* This code is our entry point. We receive two arguments here: the first is the +* environment that represent an independent instance of the JavaScript runtime; * the second is exports, the same as module.exports in a .js file. * You can either add properties to the exports object passed in or create your * own exports object. In either case you must return the object to be used as @@ -56,7 +56,7 @@ Napi::Object Init(Napi::Env env, Napi::Object exports) { } /** -* This code defines the entry-point for the Node addon, it tells Node where to go +* This code defines the entry point for the Node addon. It tells Node where to go * once the library has been loaded into active memory. The first argument must * match the "target" in our *binding.gyp*. Using NODE_GYP_MODULE_NAME ensures * that the argument will be correct, as long as the module is built with @@ -75,8 +75,8 @@ NODE_API_MODULE(NODE_GYP_MODULE_NAME, Init) - [Command options](https://www.npmjs.com/package/node-gyp#command-options) - [Configuration](https://www.npmjs.com/package/node-gyp#configuration) -Sometimes finding the right settings for ```binding.gyp``` is not easy so to -accomplish at most complicated task please refer to: +Sometimes finding the right settings for `binding.gyp` is not easy, so to +accomplish the most complicated tasks, please refer to: - [GYP documentation](https://gyp.gsrc.io/index.md) -- [node-gyp wiki](https://github.com/nodejs/node-gyp/wiki) +- [node-gyp wiki](https://github.com/nodejs/node-gyp/tree/main/docs) diff --git a/doc/object.md b/doc/object.md index 8cec358aa..fb7d53ad1 100644 --- a/doc/object.md +++ b/doc/object.md @@ -1,6 +1,6 @@ # Object -Class `Napi::Object` inherits from class [`Napi::Value`][]. +Class `Napi::Object` inherits from class [`Napi::TypeTaggable`][]. The `Napi::Object` class corresponds to a JavaScript object. It is extended by the following node-addon-api classes that you may use when working with more specific types: @@ -241,6 +241,28 @@ from being added to it and marking all existing properties as non-configurable. Values of present properties can still be changed as long as they are writable. +### GetPrototype() + +```cpp +Napi::Object Napi::Object::GetPrototype() const; +``` + +The `Napi::Object::GetPrototype()` method returns the prototype of the object. + +### SetPrototype() + +```cpp +bool Napi::Object::SetPrototype(const Napi::Object& value) const; +``` + +- `[in] value`: The prototype value. + +The `Napi::Object::SetPrototype()` method sets the prototype of the object. + +**NOTE**: The support for `Napi::Object::SetPrototype` is only available when +using `NAPI_EXPERIMENTAL` and building against Node.js headers that support this +feature. + ### operator\[\]() ```cpp @@ -407,5 +429,5 @@ void Increment(const CallbackInfo& info) { } ``` -[`Napi::Value`]: ./value.md +[`Napi::TypeTaggable`]: ./type_taggable.md [`Napi::Value::From`]: ./value.md#from diff --git a/doc/object_wrap.md b/doc/object_wrap.md index 43546646a..40fb3bf12 100644 --- a/doc/object_wrap.md +++ b/doc/object_wrap.md @@ -241,9 +241,24 @@ request being made. ### Finalize -Provides an opportunity to run cleanup code that requires access to the -`Napi::Env` before the wrapped native object instance is freed. Override to -implement. +Provides an opportunity to run cleanup code that only utilizes basic Node APIs, if any. +Override to implement. See [Finalization][] for more details. + +```cpp +virtual void Finalize(Napi::BasicEnv env); +``` + +- `[in] env`: `Napi::Env`. + +### Finalize + +Provides an opportunity to run cleanup code that utilizes non-basic Node APIs. +Override to implement. + +*NOTE*: Defining this method causes the deletion of the underlying `T* data` to +be postponed until _after_ the garbage collection cycle. Since an `Napi::Env` +has access to non-basic Node APIs, it cannot run in the same current tick as the +garbage collector. ```cpp virtual void Finalize(Napi::Env env); @@ -586,3 +601,4 @@ Returns `Napi::PropertyDescriptor` object that represents an static value property of a JavaScript class [`Napi::InstanceWrap`]: ./instance_wrap.md +[Finalization]: ./finalization.md diff --git a/doc/promises.md b/doc/promises.md index 21594c6b8..b4ab83389 100644 --- a/doc/promises.md +++ b/doc/promises.md @@ -75,5 +75,56 @@ Rejects the Promise object held by the `Napi::Promise::Deferred` object. * `[in] value`: The Node-API primitive value with which to reject the `Napi::Promise`. +## Promise Methods + +### Then + +```cpp +Napi::Promise Napi::Promise::Then(napi_value onFulfilled) const; +Napi::Promise Napi::Promise::Then(const Function& onFulfilled) const; +``` + +Attaches a fulfillment handler to the promise and returns a new promise. + +**Parameters:** +* `[in] onFulfilled`: The fulfillment handler for the promise. May be any of: + - `napi_value` – a JavaScript function to be called when the promise is fulfilled. + - `const Function&` – the [`Napi::Function`](function.md) to be called when the promise is fulfilled. + +**Returns:** A new `Napi::Promise` that resolves or rejects based on the handler's result. + +### Then + +```cpp +Napi::Promise Napi::Promise::Then(napi_value onFulfilled, napi_value onRejected) const; +Napi::Promise Napi::Promise::Then(const Function& onFulfilled, + const Function& onRejected) const; +``` + +Attaches a fulfillment and rejection handlers to the promise and returns a new promise. + +**Parameters:** +* `[in] onFulfilled`: The fulfillment handler for the promise. May be any of: + - `napi_value` – a JavaScript function to be called when the promise is fulfilled. + - `const Function&` – the [`Napi::Function`](function.md) to be called when the promise is fulfilled. +* `[in] onRejected` (optional): The rejection handler for the promise. May be any of: + - `napi_value` – a JavaScript function to be called when the promise is rejected. + - `const Function&` – the [`Napi::Function`](function.md) to be called when the promise is rejected. + +### Catch +```cpp +Napi::Promise Napi::Promise::Catch(napi_value onRejected) const; +Napi::Promise Napi::Promise::Catch(const Function& onRejected) const; +``` + +Attaches a rejection handler to the promise and returns a new promise. + +**Parameters:** +* `[in] onRejected`: The rejection handler for the promise. May be any of: + - `napi_value` – a JavaScript function to be called when the promise is rejected. + - `const Function&` – the [`Napi::Function`](function.md) to be called when the promise is rejected. + +**Returns:** A new `Napi::Promise` that handles rejection cases. [`Napi::Object`]: ./object.md +[`Napi::Function`]: ./function.md diff --git a/doc/setup.md b/doc/setup.md index 49e039c8f..b3b7effc6 100644 --- a/doc/setup.md +++ b/doc/setup.md @@ -17,94 +17,99 @@ To use **Node-API** in a native module: 1. Add a dependency on this package to `package.json`: -```json - "dependencies": { - "node-addon-api": "*", - } -``` - - 2. Reference this package's include directory and gyp file in `binding.gyp`: - -```gyp - 'include_dirs': [" +static Napi::Symbol Napi::Symbol::For(napi_env env, T&& description); static Napi::Symbol Napi::Symbol::For(napi_env env, const char* description); -static Napi::Symbol Napi::Symbol::For(napi_env env, String description); +static Napi::Symbol Napi::Symbol::For(napi_env env, Napi::String description); static Napi::Symbol Napi::Symbol::For(napi_env env, napi_value description); ``` - `[in] env`: The `napi_env` environment in which to construct the `Napi::Symbol` object. - `[in] description`: The C++ string representing the `Napi::Symbol` in the global registry to retrieve. + `description` may be any of: + - `const std::string&` - represents a UTF-8 string. + - `std::string_view` - represents a UTF-8 string view. + - `const char*` - represents a UTF-8 string description. + - `Napi::String` - Node-API string description. + - `napi_value` - Node-API `napi_value` description. + +String-like arguments implicitly convertible to both `const std::string&` and +`std::string_view` that do not have a unique best match among the non-template +overloads are resolved through `std::string_view`. Searches in the global registry for existing symbol with the given name. If the symbol already exist it will be returned, otherwise a new symbol will be created in the registry. It's equivalent to Symbol.for() called from JavaScript. -[`Napi::Name`]: ./name.md \ No newline at end of file +[`Napi::Name`]: ./name.md diff --git a/doc/syntax_error.md b/doc/syntax_error.md new file mode 100644 index 000000000..53b09c4a6 --- /dev/null +++ b/doc/syntax_error.md @@ -0,0 +1,66 @@ +# SyntaxError + +The `Napi::SyntaxError` class is a representation of the JavaScript +`SyntaxError` that is thrown when the engine encounters tokens or token order +that does not conform to the syntax of the language when parsing code. + +The `Napi::SyntaxError` class inherits its behaviors from the `Napi::Error` +class (for more info see: [`Napi::Error`](error.md)). + +For more details about error handling refer to the section titled [Error +handling](error_handling.md). + +## Methods + +### New + +Creates a new instance of a `Napi::SyntaxError` object. + +```cpp +Napi::SyntaxError::New(Napi::Env env, const char* message); +``` + +- `[in] Env`: The environment in which to construct the `Napi::SyntaxError` + object. +- `[in] message`: Null-terminated string to be used as the message for the + `Napi::SyntaxError`. + +Returns an instance of a `Napi::SyntaxError` object. + +### New + +Creates a new instance of a `Napi::SyntaxError` object. + +```cpp +Napi::SyntaxError::New(Napi::Env env, const std::string& message); +``` + +- `[in] Env`: The environment in which to construct the `Napi::SyntaxError` + object. +- `[in] message`: Reference string to be used as the message for the + `Napi::SyntaxError`. + +Returns an instance of a `Napi::SyntaxError` object. + +### Constructor + +Creates a new empty instance of a `Napi::SyntaxError`. + +```cpp +Napi::SyntaxError::SyntaxError(); +``` + +### Constructor + +Initializes a `Napi::SyntaxError` instance from an existing Javascript error +object. + +```cpp +Napi::SyntaxError::SyntaxError(napi_env env, napi_value value); +``` + +- `[in] Env`: The environment in which to construct the `Napi::SyntaxError` + object. +- `[in] value`: The `Napi::Error` reference to wrap. + +Returns an instance of a `Napi::SyntaxError` object. diff --git a/doc/threadsafe_function.md b/doc/threadsafe_function.md index fcbc2dff1..9ab404731 100644 --- a/doc/threadsafe_function.md +++ b/doc/threadsafe_function.md @@ -70,9 +70,9 @@ New(napi_env env, opportunity for cleaning up after the threads e.g. by calling `uv_thread_join()`. It is important that, aside from the main loop thread, there be no threads left using the thread-safe function after the finalize - callback completes. Must implement `void operator()(Env env, DataType* data, - ContextType* hint)`, skipping `data` or `hint` if they are not provided. Can - be retrieved via `GetContext()`. + callback completes. Must implement `void operator()(Env env, + FinalizerDataType* data, ContextType* context)`, skipping `data` or `context` + if they are not provided. Can be retrieved via `GetContext()`. - `[optional] data`: Data to be passed to `finalizeCallback`. Returns a non-empty `Napi::ThreadSafeFunction` instance. diff --git a/doc/type_taggable.md b/doc/type_taggable.md new file mode 100644 index 000000000..ebea2344b --- /dev/null +++ b/doc/type_taggable.md @@ -0,0 +1,40 @@ +# TypeTaggable + +Class `Napi::TypeTaggable` inherits from class [`Napi::Value`][]. + +The `Napi::TypeTaggable` class is the base class for [`Napi::Object`][] and +[`Napi::External`][]. It adds type-tagging capabilities to both. It is an +abstract-only base class. + +### TypeTag() + +```cpp +void Napi::TypeTaggable::TypeTag(const napi_type_tag* type_tag) const; +``` + +- `[in] type_tag`: The tag with which this object or external is to be marked. + +The `Napi::TypeTaggable::TypeTag()` method associates the value of the +`type_tag` pointer with this JavaScript object or external. +`Napi::TypeTaggable::CheckTypeTag()` can then be used to compare the tag that +was attached with one owned by the add-on to ensure that this object or external +has the right type. + +### CheckTypeTag() + +```cpp +bool Napi::TypeTaggable::CheckTypeTag(const napi_type_tag* type_tag) const; +``` + +- `[in] type_tag`: The tag with which to compare any tag found on this object or + external. + +The `Napi::TypeTaggable::CheckTypeTag()` method compares the pointer given as +`type_tag` with any that can be found on this JavaScript object or external. If +no tag is found or if a tag is found but it does not match `type_tag`, then the +return value is `false`. If a tag is found and it matches `type_tag`, then the +return value is `true`. + +[`Napi::Value`]: ./value.md +[`Napi::Object`]: ./object.md +[`Napi::External`]: ./external.md diff --git a/doc/typed_array.md b/doc/typed_array.md index c2d3773a0..95aefb2e9 100644 --- a/doc/typed_array.md +++ b/doc/typed_array.md @@ -43,6 +43,21 @@ Napi::ArrayBuffer Napi::TypedArray::ArrayBuffer() const; Returns the backing array buffer. +**NOTE**: If the `Napi::TypedArray` is not backed by an `Napi::ArrayBuffer`, +this method will terminate the process with a fatal error when using +`NODE_ADDON_API_ENABLE_TYPE_CHECK_ON_AS` or exhibit undefined behavior +otherwise. Use `Buffer()` instead to get the backing buffer without assuming its +type. + +### Buffer + +```cpp +Napi::Value Napi::TypedArray::Buffer() const; +``` + +Returns the backing array buffer as a generic `Napi::Value`, allowing optional +type-checking with `Is*()` and type-casting with `As<>()` methods. + ### ElementSize ```cpp diff --git a/doc/typed_array_of.md b/doc/typed_array_of.md index a982b80e5..4ced5841c 100644 --- a/doc/typed_array_of.md +++ b/doc/typed_array_of.md @@ -77,6 +77,34 @@ static Napi::TypedArrayOf Napi::TypedArrayOf::New(napi_env env, Returns a new `Napi::TypedArrayOf` instance. +### New + +Wraps the provided `Napi::SharedArrayBuffer` into a new `Napi::TypedArray` instance. + +The array `type` parameter can normally be omitted (because it is inferred from +the template parameter `T`), except when creating a "clamped" array. + +```cpp +static Napi::TypedArrayOf Napi::TypedArrayOf::New(napi_env env, + size_t elementLength, + Napi::SharedArrayBuffer arrayBuffer, + size_t bufferOffset, + napi_typedarray_type type); +``` + +- `[in] env`: The environment in which to create the `Napi::TypedArrayOf` instance. +- `[in] elementLength`: The length to array, in elements. +- `[in] arrayBuffer`: The backing `Napi::SharedArrayBuffer` instance. +- `[in] bufferOffset`: The offset into the `Napi::SharedArrayBuffer` where the array starts, + in bytes. +- `[in] type`: The type of array to allocate (optional). + +Returns a new `Napi::TypedArrayOf` instance. + +**NOTE**: The support for this overload of `Napi::TypedArrayOf::New()` is only +available when using `NAPI_EXPERIMENTAL` and building against Node.js headers +that supports this feature. + ### Constructor Initializes an empty instance of the `Napi::TypedArrayOf` class. diff --git a/doc/typed_threadsafe_function.md b/doc/typed_threadsafe_function.md index 74d3cc2ed..6dcc0343e 100644 --- a/doc/typed_threadsafe_function.md +++ b/doc/typed_threadsafe_function.md @@ -82,7 +82,7 @@ New(napi_env env, calling `uv_thread_join()`. It is important that, aside from the main loop thread, there be no threads left using the thread-safe function after the finalize callback completes. Must implement `void operator()(Env env, - FinalizerDataType* data, ContextType* hint)`. + FinalizerDataType* data, ContextType* context)`. - `[optional] data`: Data to be passed to `finalizeCallback`. Returns a non-empty `Napi::TypedThreadSafeFunction` instance. diff --git a/doc/value.md b/doc/value.md index 505b7945f..f61a36ecf 100644 --- a/doc/value.md +++ b/doc/value.md @@ -78,7 +78,26 @@ Casts to another type of `Napi::Value`, when the actual type is known or assumed. This conversion does not coerce the type. Calling any methods inappropriate for -the actual value type will throw `Napi::Error`. +the actual value type will throw `Napi::Error`. When C++ exceptions are +disabled, the thrown error will not be reflected before control returns to +JavaScript. + +In order to enforce expected type, use `Napi::Value::Is*()` methods to check +the type before calling `Napi::Value::As()`, or compile with definition +`NODE_ADDON_API_ENABLE_TYPE_CHECK_ON_AS` to enforce type checks. + +### UnsafeAs + +```cpp +template T Napi::Value::UnsafeAs() const; +``` + +Casts to another type of `Napi::Value`, when the actual type is known or +assumed. + +This conversion does not coerce the type. This does not check the type even if +`NODE_ADDON_API_ENABLE_TYPE_CHECK_ON_AS` is defined. This indicates intentional +unsafe type cast. Use `Napi::Value::As()` if possible. ### Env @@ -135,6 +154,15 @@ bool Napi::Value::IsArrayBuffer() const; Returns `true` if the underlying value is a JavaScript `Napi::ArrayBuffer` or `false` otherwise. +### IsBigInt + +```cpp +bool Napi::Value::IsBigInt() const; +``` + +Returns `true` if the underlying value is a JavaScript `Napi::BigInt` or `false` +otherwise. + ### IsBoolean ```cpp @@ -240,6 +268,19 @@ bool Napi::Value::IsPromise() const; Returns `true` if the underlying value is a JavaScript `Napi::Promise` or `false` otherwise. +### IsSharedArrayBuffer + +```cpp +bool Napi::Value::IsSharedArrayBuffer() const; +``` + +Returns `true` if the underlying value is a JavaScript +`Napi::IsSharedArrayBuffer` or `false` otherwise. + +**NOTE**: The support for `Napi::SharedArrayBuffer` is only available when using +`NAPI_EXPERIMENTAL` and building against Node.js headers that support this +feature. + ### IsString ```cpp diff --git a/doc/version_management.md b/doc/version_management.md index 1cdc48321..b289f1b1d 100644 --- a/doc/version_management.md +++ b/doc/version_management.md @@ -11,7 +11,7 @@ important to make decisions based on different versions of the system. Retrieves the highest Node-API version supported by Node.js runtime. ```cpp -static uint32_t Napi::VersionManagement::GetNapiVersion(Env env); +static uint32_t Napi::VersionManagement::GetNapiVersion(Napi::BasicEnv env); ``` - `[in] env`: The environment in which the API is invoked under. @@ -34,7 +34,7 @@ typedef struct { ```` ```cpp -static const napi_node_version* Napi::VersionManagement::GetNodeVersion(Env env); +static const napi_node_version* Napi::VersionManagement::GetNodeVersion(Napi::BasicEnv env); ``` - `[in] env`: The environment in which the API is invoked under. diff --git a/eslint.config.js b/eslint.config.js new file mode 100644 index 000000000..d02c6f529 --- /dev/null +++ b/eslint.config.js @@ -0,0 +1,5 @@ +'use strict'; + +module.exports = require('neostandard')({ + semi: true, +}); diff --git a/index.js b/index.js index 52f53e3c2..e235cc3e9 100644 --- a/index.js +++ b/index.js @@ -1,11 +1,14 @@ const path = require('path'); +const { version } = require('./package.json'); const includeDir = path.relative('.', __dirname); module.exports = { include: `"${__dirname}"`, // deprecated, can be removed as part of 4.0.0 include_dir: includeDir, - gyp: path.join(includeDir, 'node_api.gyp:nothing'), + gyp: path.join(includeDir, 'node_api.gyp:nothing'), // deprecated. + targets: path.join(includeDir, 'node_addon_api.gyp'), + version, isNodeApiBuiltin: true, needsFlag: false }; diff --git a/napi-inl.h b/napi-inl.h index 3b79809c8..4a1c18b6e 100644 --- a/napi-inl.h +++ b/napi-inl.h @@ -9,38 +9,57 @@ //////////////////////////////////////////////////////////////////////////////// // Note: Do not include this file directly! Include "napi.h" instead. +// This should be a no-op and is intended for better IDE integration. +#include "napi.h" #include +#include #include +#if NAPI_HAS_THREADS #include +#endif // NAPI_HAS_THREADS +#include #include #include +#if defined(__clang__) || defined(__GNUC__) +#define NAPI_NO_SANITIZE_VPTR __attribute__((no_sanitize("vptr"))) +#else +#define NAPI_NO_SANITIZE_VPTR +#endif + namespace Napi { #ifdef NAPI_CPP_CUSTOM_NAMESPACE namespace NAPI_CPP_CUSTOM_NAMESPACE { #endif -// Helpers to handle functions exposed from C++. +// Helpers to handle functions exposed from C++ and internal constants. namespace details { +// New napi_status constants not yet available in all supported versions of +// Node.js releases. Only necessary when they are used in napi.h and napi-inl.h. +constexpr int napi_no_external_buffers_allowed = 22; + +template +inline void default_basic_finalizer(node_addon_api_basic_env /*env*/, + void* data, + void* /*hint*/) { + delete static_cast(data); +} + // Attach a data item to an object and delete it when the object gets // garbage-collected. // TODO: Replace this code with `napi_add_finalizer()` whenever it becomes // available on all supported versions of Node.js. -template -static inline napi_status AttachData(napi_env env, - napi_value obj, - FreeType* data, - napi_finalize finalizer = nullptr, - void* hint = nullptr) { +template < + typename FreeType, + node_addon_api_basic_finalize finalizer = default_basic_finalizer> +inline napi_status AttachData(napi_env env, + napi_value obj, + FreeType* data, + void* hint = nullptr) { napi_status status; - if (finalizer == nullptr) { - finalizer = [](napi_env /*env*/, void* data, void* /*hint*/) { - delete static_cast(data); - }; - } #if (NAPI_VERSION < 5) napi_value symbol, external; status = napi_create_symbol(env, nullptr, &symbol); @@ -67,19 +86,33 @@ static inline napi_status AttachData(napi_env env, // For use in JS to C++ callback wrappers to catch any Napi::Error exceptions // and rethrow them as JavaScript exceptions before returning from the callback. template -inline napi_value WrapCallback(Callable callback) { -#ifdef NAPI_CPP_EXCEPTIONS +#ifdef NODE_ADDON_API_CPP_EXCEPTIONS_ALL +inline napi_value WrapCallback(napi_env env, Callable callback) { +#else +inline napi_value WrapCallback(napi_env, Callable callback) { +#endif +#ifdef NODE_ADDON_API_CPP_EXCEPTIONS try { return callback(); } catch (const Error& e) { e.ThrowAsJavaScriptException(); return nullptr; } -#else // NAPI_CPP_EXCEPTIONS +#ifdef NODE_ADDON_API_CPP_EXCEPTIONS_ALL + catch (const std::exception& e) { + Napi::Error::New(env, e.what()).ThrowAsJavaScriptException(); + return nullptr; + } catch (...) { + Napi::Error::New(env, "A native exception was thrown") + .ThrowAsJavaScriptException(); + return nullptr; + } +#endif // NODE_ADDON_API_CPP_EXCEPTIONS_ALL +#else // NODE_ADDON_API_CPP_EXCEPTIONS // When C++ exceptions are disabled, errors are immediately thrown as JS // exceptions, so there is no need to catch and rethrow them here. return callback(); -#endif // NAPI_CPP_EXCEPTIONS +#endif // NODE_ADDON_API_CPP_EXCEPTIONS } // For use in JS to C++ void callback wrappers to catch any Napi::Error @@ -87,7 +120,7 @@ inline napi_value WrapCallback(Callable callback) { // the callback. template inline void WrapVoidCallback(Callable callback) { -#ifdef NAPI_CPP_EXCEPTIONS +#ifdef NODE_ADDON_API_CPP_EXCEPTIONS try { callback(); } catch (const Error& e) { @@ -100,10 +133,41 @@ inline void WrapVoidCallback(Callable callback) { #endif // NAPI_CPP_EXCEPTIONS } +// For use in JS to C++ void callback wrappers to catch _any_ thrown exception +// and rethrow them as JavaScript exceptions before returning from the callback, +// wrapping in an Napi::Error as needed. +template +#ifdef NODE_ADDON_API_CPP_EXCEPTIONS_ALL +inline void WrapVoidCallback(napi_env env, Callable callback) { +#else +inline void WrapVoidCallback(napi_env, Callable callback) { +#endif +#ifdef NODE_ADDON_API_CPP_EXCEPTIONS + try { + callback(); + } catch (const Error& e) { + e.ThrowAsJavaScriptException(); + } +#ifdef NODE_ADDON_API_CPP_EXCEPTIONS_ALL + catch (const std::exception& e) { + Napi::Error::New(env, e.what()).ThrowAsJavaScriptException(); + } catch (...) { + Napi::Error::New(env, "A native exception was thrown") + .ThrowAsJavaScriptException(); + } +#endif // NODE_ADDON_API_CPP_EXCEPTIONS_ALL +#else + // When C++ exceptions are disabled, there is no need to catch and rethrow C++ + // exceptions. JS errors should be thrown with + // `Error::ThrowAsJavaScriptException`. + callback(); +#endif // NODE_ADDON_API_CPP_EXCEPTIONS +} + template struct CallbackData { static inline napi_value Wrapper(napi_env env, napi_callback_info info) { - return details::WrapCallback([&] { + return details::WrapCallback(env, [&] { CallbackInfo callbackInfo(env, info); CallbackData* callbackData = static_cast(callbackInfo.Data()); @@ -119,7 +183,7 @@ struct CallbackData { template struct CallbackData { static inline napi_value Wrapper(napi_env env, napi_callback_info info) { - return details::WrapCallback([&] { + return details::WrapCallback(env, [&] { CallbackInfo callbackInfo(env, info); CallbackData* callbackData = static_cast(callbackInfo.Data()); @@ -134,9 +198,9 @@ struct CallbackData { }; template -static napi_value TemplatedVoidCallback(napi_env env, - napi_callback_info info) NAPI_NOEXCEPT { - return details::WrapCallback([&] { +napi_value TemplatedVoidCallback(napi_env env, + napi_callback_info info) NAPI_NOEXCEPT { + return details::WrapCallback(env, [&] { CallbackInfo cbInfo(env, info); Callback(cbInfo); return nullptr; @@ -144,55 +208,137 @@ static napi_value TemplatedVoidCallback(napi_env env, } template -static napi_value TemplatedCallback(napi_env env, - napi_callback_info info) NAPI_NOEXCEPT { - return details::WrapCallback([&] { +napi_value TemplatedCallback(napi_env env, + napi_callback_info info) NAPI_NOEXCEPT { + return details::WrapCallback(env, [&] { CallbackInfo cbInfo(env, info); - return Callback(cbInfo); + // MSVC requires to copy 'Callback' function pointer to a local variable + // before invoking it. + auto callback = Callback; + return callback(cbInfo); }); } template -static napi_value TemplatedInstanceCallback( - napi_env env, napi_callback_info info) NAPI_NOEXCEPT { - return details::WrapCallback([&] { +napi_value TemplatedInstanceCallback(napi_env env, + napi_callback_info info) NAPI_NOEXCEPT { + return details::WrapCallback(env, [&] { CallbackInfo cbInfo(env, info); T* instance = T::Unwrap(cbInfo.This().As()); - return (instance->*UnwrapCallback)(cbInfo); + return instance ? (instance->*UnwrapCallback)(cbInfo) : Napi::Value(); }); } template -static napi_value TemplatedInstanceVoidCallback( - napi_env env, napi_callback_info info) NAPI_NOEXCEPT { - return details::WrapCallback([&] { +napi_value TemplatedInstanceVoidCallback(napi_env env, napi_callback_info info) + NAPI_NOEXCEPT { + return details::WrapCallback(env, [&] { CallbackInfo cbInfo(env, info); T* instance = T::Unwrap(cbInfo.This().As()); - (instance->*UnwrapCallback)(cbInfo); + if (instance) (instance->*UnwrapCallback)(cbInfo); return nullptr; }); } template struct FinalizeData { - static inline void Wrapper(napi_env env, +#ifdef NODE_API_EXPERIMENTAL_HAS_POST_FINALIZER + template >> +#endif + static inline void Wrapper(node_addon_api_basic_env env, void* data, void* finalizeHint) NAPI_NOEXCEPT { WrapVoidCallback([&] { FinalizeData* finalizeData = static_cast(finalizeHint); - finalizeData->callback(Env(env), static_cast(data)); + finalizeData->callback(env, static_cast(data)); delete finalizeData; }); } - static inline void WrapperWithHint(napi_env env, +#ifdef NODE_API_EXPERIMENTAL_HAS_POST_FINALIZER + template >, + typename = void> + static inline void Wrapper(node_addon_api_basic_env env, + void* data, + void* finalizeHint) NAPI_NOEXCEPT { +#ifdef NODE_ADDON_API_REQUIRE_BASIC_FINALIZERS + static_assert(false, + "NODE_ADDON_API_REQUIRE_BASIC_FINALIZERS defined: Finalizer " + "must be basic."); +#endif + napi_status status = + node_api_post_finalizer(env, WrapperGC, data, finalizeHint); + NAPI_FATAL_IF_FAILED( + status, "FinalizeData::Wrapper", "node_api_post_finalizer failed"); + } +#endif + +#ifdef NODE_API_EXPERIMENTAL_HAS_POST_FINALIZER + template >> +#endif + static inline void WrapperWithHint(node_addon_api_basic_env env, void* data, void* finalizeHint) NAPI_NOEXCEPT { WrapVoidCallback([&] { FinalizeData* finalizeData = static_cast(finalizeHint); - finalizeData->callback( - Env(env), static_cast(data), finalizeData->hint); + finalizeData->callback(env, static_cast(data), finalizeData->hint); + delete finalizeData; + }); + } + +#ifdef NODE_API_EXPERIMENTAL_HAS_POST_FINALIZER + template >, + typename = void> + static inline void WrapperWithHint(node_addon_api_basic_env env, + void* data, + void* finalizeHint) NAPI_NOEXCEPT { +#ifdef NODE_ADDON_API_REQUIRE_BASIC_FINALIZERS + static_assert(false, + "NODE_ADDON_API_REQUIRE_BASIC_FINALIZERS defined: Finalizer " + "must be basic."); +#endif + napi_status status = + node_api_post_finalizer(env, WrapperGCWithHint, data, finalizeHint); + NAPI_FATAL_IF_FAILED( + status, "FinalizeData::Wrapper", "node_api_post_finalizer failed"); + } +#endif + + static inline void WrapperGCWithoutData(napi_env env, + void* /*data*/, + void* finalizeHint) NAPI_NOEXCEPT { + WrapVoidCallback(env, [&] { + FinalizeData* finalizeData = static_cast(finalizeHint); + finalizeData->callback(env); + delete finalizeData; + }); + } + + static inline void WrapperGC(napi_env env, + void* data, + void* finalizeHint) NAPI_NOEXCEPT { + WrapVoidCallback(env, [&] { + FinalizeData* finalizeData = static_cast(finalizeHint); + finalizeData->callback(env, static_cast(data)); + delete finalizeData; + }); + } + + static inline void WrapperGCWithHint(napi_env env, + void* data, + void* finalizeHint) NAPI_NOEXCEPT { + WrapVoidCallback(env, [&] { + FinalizeData* finalizeData = static_cast(finalizeHint); + finalizeData->callback(env, static_cast(data), finalizeData->hint); delete finalizeData; }); } @@ -201,7 +347,7 @@ struct FinalizeData { Hint* hint; }; -#if (NAPI_VERSION > 3 && !defined(__wasm32__)) +#if (NAPI_VERSION > 3 && NAPI_HAS_THREADS) template , typename FinalizerDataType = void> @@ -255,20 +401,27 @@ struct ThreadSafeFinalize { }; template -typename std::enable_if::type static inline CallJsWrapper( - napi_env env, napi_value jsCallback, void* context, void* data) { - call(env, - Function(env, jsCallback), - static_cast(context), - static_cast(data)); +inline typename std::enable_if(nullptr)>::type +CallJsWrapper(napi_env env, napi_value jsCallback, void* context, void* data) { + details::WrapVoidCallback(env, [&]() { + call(env, + Function(env, jsCallback), + static_cast(context), + static_cast(data)); + }); } template -typename std::enable_if::type static inline CallJsWrapper( - napi_env env, napi_value jsCallback, void* /*context*/, void* /*data*/) { - if (jsCallback != nullptr) { - Function(env, jsCallback).Call(0, nullptr); - } +inline typename std::enable_if(nullptr)>::type +CallJsWrapper(napi_env env, + napi_value jsCallback, + void* /*context*/, + void* /*data*/) { + details::WrapVoidCallback(env, [&]() { + if (jsCallback != nullptr) { + Function(env, jsCallback).Call(0, nullptr); + } + }); } #if NAPI_VERSION > 4 @@ -292,13 +445,13 @@ napi_value DefaultCallbackWrapper(napi_env env, Napi::Function cb) { return cb; } #endif // NAPI_VERSION > 4 -#endif // NAPI_VERSION > 3 && !defined(__wasm32__) +#endif // NAPI_VERSION > 3 && NAPI_HAS_THREADS template struct AccessorCallbackData { static inline napi_value GetterWrapper(napi_env env, napi_callback_info info) { - return details::WrapCallback([&] { + return details::WrapCallback(env, [&] { CallbackInfo callbackInfo(env, info); AccessorCallbackData* callbackData = static_cast(callbackInfo.Data()); @@ -309,7 +462,7 @@ struct AccessorCallbackData { static inline napi_value SetterWrapper(napi_env env, napi_callback_info info) { - return details::WrapCallback([&] { + return details::WrapCallback(env, [&] { CallbackInfo callbackInfo(env, info); AccessorCallbackData* callbackData = static_cast(callbackInfo.Data()); @@ -324,6 +477,46 @@ struct AccessorCallbackData { void* data; }; +// Debugging-purpose C++-style variant of sprintf(). +inline std::string StringFormat(const char* format, ...) { + std::string result; + va_list args; + va_start(args, format); + int len = vsnprintf(nullptr, 0, format, args); + result.resize(len); + vsnprintf(&result[0], len + 1, format, args); + va_end(args); + return result; +} + +template +class HasExtendedFinalizer { + private: + template + struct SFINAE {}; + template + static char test(SFINAE*); + template + static int test(...); + + public: + static constexpr bool value = sizeof(test(0)) == sizeof(char); +}; + +template +class HasBasicFinalizer { + private: + template + struct SFINAE {}; + template + static char test(SFINAE*); + template + static int test(...); + + public: + static constexpr bool value = sizeof(test(0)) == sizeof(char); +}; + } // namespace details #ifndef NODE_ADDON_API_DISABLE_DEPRECATED @@ -360,7 +553,7 @@ struct AccessorCallbackData { inline napi_value RegisterModule(napi_env env, napi_value exports, ModuleRegisterCallback registerCallback) { - return details::WrapCallback([&] { + return details::WrapCallback(env, [&] { return napi_value( registerCallback(Napi::Env(env), Napi::Object(env, exports))); }); @@ -433,15 +626,21 @@ inline Maybe Just(const T& t) { } //////////////////////////////////////////////////////////////////////////////// -// Env class +// BasicEnv / Env class //////////////////////////////////////////////////////////////////////////////// -inline Env::Env(napi_env env) : _env(env) {} +inline BasicEnv::BasicEnv(node_addon_api_basic_env env) : _env(env) {} -inline Env::operator napi_env() const { +inline BasicEnv::operator node_addon_api_basic_env() const { return _env; } +inline Env::Env(napi_env env) : BasicEnv(env) {} + +inline Env::operator napi_env() const { + return const_cast(_env); +} + inline Object Env::Global() const { napi_value value; napi_status status = napi_get_global(*this, &value); @@ -465,7 +664,7 @@ inline Value Env::Null() const { inline bool Env::IsExceptionPending() const { bool result; - napi_status status = napi_is_exception_pending(_env, &result); + napi_status status = napi_is_exception_pending(*this, &result); if (status != napi_ok) result = false; // Checking for a pending exception shouldn't throw. return result; @@ -473,16 +672,16 @@ inline bool Env::IsExceptionPending() const { inline Error Env::GetAndClearPendingException() const { napi_value value; - napi_status status = napi_get_and_clear_last_exception(_env, &value); + napi_status status = napi_get_and_clear_last_exception(*this, &value); if (status != napi_ok) { // Don't throw another exception when failing to get the exception! return Error(); } - return Error(_env, value); + return Error(*this, value); } inline MaybeOrValue Env::RunScript(const char* utf8script) const { - String script = String::New(_env, utf8script); + String script = String::New(*this, utf8script); return RunScript(script); } @@ -492,46 +691,46 @@ inline MaybeOrValue Env::RunScript(const std::string& utf8script) const { inline MaybeOrValue Env::RunScript(String script) const { napi_value result; - napi_status status = napi_run_script(_env, script, &result); + napi_status status = napi_run_script(*this, script, &result); NAPI_RETURN_OR_THROW_IF_FAILED( - _env, status, Napi::Value(_env, result), Napi::Value); + *this, status, Napi::Value(*this, result), Napi::Value); } #if NAPI_VERSION > 2 template -void Env::CleanupHook::Wrapper(void* data) NAPI_NOEXCEPT { - auto* cleanupData = - static_cast::CleanupData*>( - data); +void BasicEnv::CleanupHook::Wrapper(void* data) NAPI_NOEXCEPT { + auto* cleanupData = static_cast< + typename Napi::BasicEnv::CleanupHook::CleanupData*>(data); cleanupData->hook(); delete cleanupData; } template -void Env::CleanupHook::WrapperWithArg(void* data) NAPI_NOEXCEPT { - auto* cleanupData = - static_cast::CleanupData*>( - data); +void BasicEnv::CleanupHook::WrapperWithArg(void* data) + NAPI_NOEXCEPT { + auto* cleanupData = static_cast< + typename Napi::BasicEnv::CleanupHook::CleanupData*>(data); cleanupData->hook(static_cast(cleanupData->arg)); delete cleanupData; } #endif // NAPI_VERSION > 2 #if NAPI_VERSION > 5 -template fini> -inline void Env::SetInstanceData(T* data) const { +template fini> +inline void BasicEnv::SetInstanceData(T* data) const { napi_status status = napi_set_instance_data( _env, data, [](napi_env env, void* data, void*) { fini(env, static_cast(data)); }, nullptr); - NAPI_THROW_IF_FAILED_VOID(_env, status); + NAPI_FATAL_IF_FAILED( + status, "BasicEnv::SetInstanceData", "invalid arguments"); } template fini> -inline void Env::SetInstanceData(DataType* data, HintType* hint) const { + Napi::BasicEnv::FinalizerWithHint fini> +inline void BasicEnv::SetInstanceData(DataType* data, HintType* hint) const { napi_status status = napi_set_instance_data( _env, data, @@ -539,30 +738,41 @@ inline void Env::SetInstanceData(DataType* data, HintType* hint) const { fini(env, static_cast(data), static_cast(hint)); }, hint); - NAPI_THROW_IF_FAILED_VOID(_env, status); + NAPI_FATAL_IF_FAILED( + status, "BasicEnv::SetInstanceData", "invalid arguments"); } template -inline T* Env::GetInstanceData() const { +inline T* BasicEnv::GetInstanceData() const { void* data = nullptr; napi_status status = napi_get_instance_data(_env, &data); - NAPI_THROW_IF_FAILED(_env, status, nullptr); + NAPI_FATAL_IF_FAILED( + status, "BasicEnv::GetInstanceData", "invalid arguments"); return static_cast(data); } template -void Env::DefaultFini(Env, T* data) { +void BasicEnv::DefaultFini(Env, T* data) { delete data; } template -void Env::DefaultFiniWithHint(Env, DataType* data, HintType*) { +void BasicEnv::DefaultFiniWithHint(Env, DataType* data, HintType*) { delete data; } #endif // NAPI_VERSION > 5 +#if NAPI_VERSION > 8 +inline const char* BasicEnv::GetModuleFileName() const { + const char* result; + napi_status status = node_api_get_module_file_name(_env, &result); + NAPI_FATAL_IF_FAILED( + status, "BasicEnv::GetModuleFileName", "invalid arguments"); + return result; +} +#endif // NAPI_VERSION > 8 //////////////////////////////////////////////////////////////////////////////// // Value class //////////////////////////////////////////////////////////////////////////////// @@ -731,11 +941,37 @@ inline bool Value::IsExternal() const { return Type() == napi_external; } +#ifdef NODE_API_EXPERIMENTAL_HAS_SHAREDARRAYBUFFER +inline bool Value::IsSharedArrayBuffer() const { + if (IsEmpty()) { + return false; + } + + bool result; + napi_status status = node_api_is_sharedarraybuffer(_env, _value, &result); + NAPI_THROW_IF_FAILED(_env, status, false); + return result; +} +#endif + template inline T Value::As() const { +#ifdef NODE_ADDON_API_ENABLE_TYPE_CHECK_ON_AS + T::CheckCast(_env, _value); +#endif return T(_env, _value); } +template +inline T Value::UnsafeAs() const { + return T(_env, _value); +} + +// static +inline void Value::CheckCast(napi_env /* env */, napi_value value) { + NAPI_CHECK(value != nullptr, "Value::CheckCast", "empty value"); +} + inline MaybeOrValue Value::ToBoolean() const { napi_value result; napi_status status = napi_coerce_to_bool(_env, _value, &result); @@ -775,6 +1011,15 @@ inline Boolean Boolean::New(napi_env env, bool val) { return Boolean(env, value); } +inline void Boolean::CheckCast(napi_env env, napi_value value) { + NAPI_CHECK(value != nullptr, "Boolean::CheckCast", "empty value"); + + napi_valuetype type; + napi_status status = napi_typeof(env, value, &type); + NAPI_CHECK(status == napi_ok, "Boolean::CheckCast", "napi_typeof failed"); + NAPI_INTERNAL_CHECK_EQ(type, napi_boolean, "%d", "Boolean::CheckCast"); +} + inline Boolean::Boolean() : Napi::Value() {} inline Boolean::Boolean(napi_env env, napi_value value) @@ -802,6 +1047,15 @@ inline Number Number::New(napi_env env, double val) { return Number(env, value); } +inline void Number::CheckCast(napi_env env, napi_value value) { + NAPI_CHECK(value != nullptr, "Number::CheckCast", "empty value"); + + napi_valuetype type; + napi_status status = napi_typeof(env, value, &type); + NAPI_CHECK(status == napi_ok, "Number::CheckCast", "napi_typeof failed"); + NAPI_INTERNAL_CHECK_EQ(type, napi_number, "%d", "Number::CheckCast"); +} + inline Number::Number() : Value() {} inline Number::Number(napi_env env, napi_value value) : Value(env, value) {} @@ -888,6 +1142,15 @@ inline BigInt BigInt::New(napi_env env, return BigInt(env, value); } +inline void BigInt::CheckCast(napi_env env, napi_value value) { + NAPI_CHECK(value != nullptr, "BigInt::CheckCast", "empty value"); + + napi_valuetype type; + napi_status status = napi_typeof(env, value, &type); + NAPI_CHECK(status == napi_ok, "BigInt::CheckCast", "napi_typeof failed"); + NAPI_INTERNAL_CHECK_EQ(type, napi_bigint, "%d", "BigInt::CheckCast"); +} + inline BigInt::BigInt() : Value() {} inline BigInt::BigInt(napi_env env, napi_value value) : Value(env, value) {} @@ -937,6 +1200,22 @@ inline Date Date::New(napi_env env, double val) { return Date(env, value); } +inline Date Date::New(napi_env env, std::chrono::system_clock::time_point tp) { + using namespace std::chrono; + auto ms = static_cast( + duration_cast(tp.time_since_epoch()).count()); + return Date::New(env, ms); +} + +inline void Date::CheckCast(napi_env env, napi_value value) { + NAPI_CHECK(value != nullptr, "Date::CheckCast", "empty value"); + + bool result; + napi_status status = napi_is_date(env, value, &result); + NAPI_CHECK(status == napi_ok, "Date::CheckCast", "napi_is_date failed"); + NAPI_CHECK(result, "Date::CheckCast", "value is not date"); +} + inline Date::Date() : Value() {} inline Date::Date(napi_env env, napi_value value) : Value(env, value) {} @@ -956,6 +1235,17 @@ inline double Date::ValueOf() const { //////////////////////////////////////////////////////////////////////////////// // Name class //////////////////////////////////////////////////////////////////////////////// +inline void Name::CheckCast(napi_env env, napi_value value) { + NAPI_CHECK(value != nullptr, "Name::CheckCast", "empty value"); + + napi_valuetype type; + napi_status status = napi_typeof(env, value, &type); + NAPI_CHECK(status == napi_ok, "Name::CheckCast", "napi_typeof failed"); + NAPI_INTERNAL_CHECK(type == napi_string || type == napi_symbol, + "Name::CheckCast", + "value is not napi_string or napi_symbol, got %d.", + type); +} inline Name::Name() : Value() {} @@ -973,6 +1263,10 @@ inline String String::New(napi_env env, const std::u16string& val) { return String::New(env, val.c_str(), val.size()); } +inline String String::New(napi_env env, std::string_view val) { + return String::New(env, val.data(), val.size()); +} + inline String String::New(napi_env env, const char* val) { // TODO(@gabrielschulhof) Remove if-statement when core's error handling is // available in all supported versions. @@ -1015,6 +1309,15 @@ inline String String::New(napi_env env, const char16_t* val, size_t length) { return String(env, value); } +inline void String::CheckCast(napi_env env, napi_value value) { + NAPI_CHECK(value != nullptr, "String::CheckCast", "empty value"); + + napi_valuetype type; + napi_status status = napi_typeof(env, value, &type); + NAPI_CHECK(status == napi_ok, "String::CheckCast", "napi_typeof failed"); + NAPI_INTERNAL_CHECK_EQ(type, napi_string, "%d", "String::CheckCast"); +} + inline String::String() : Name() {} inline String::String(napi_env env, napi_value value) : Name(env, value) {} @@ -1073,6 +1376,11 @@ inline Symbol Symbol::New(napi_env env, const std::string& description) { return Symbol::New(env, descriptionValue); } +inline Symbol Symbol::New(napi_env env, std::string_view description) { + napi_value descriptionValue = String::New(env, description); + return Symbol::New(env, descriptionValue); +} + inline Symbol Symbol::New(napi_env env, String description) { napi_value descriptionValue = description; return Symbol::New(env, descriptionValue); @@ -1087,12 +1395,15 @@ inline Symbol Symbol::New(napi_env env, napi_value description) { inline MaybeOrValue Symbol::WellKnown(napi_env env, const std::string& name) { + // No need to check if the return value is a symbol or undefined. + // Well known symbols are definite and it is an develop time error + // if the symbol does not exist. #if defined(NODE_ADDON_API_ENABLE_MAYBE) Value symbol_obj; Value symbol_value; if (Napi::Env(env).Global().Get("Symbol").UnwrapTo(&symbol_obj) && symbol_obj.As().Get(name).UnwrapTo(&symbol_value)) { - return Just(symbol_value.As()); + return Just(symbol_value.UnsafeAs()); } return Nothing(); #else @@ -1101,7 +1412,7 @@ inline MaybeOrValue Symbol::WellKnown(napi_env env, .Get("Symbol") .As() .Get(name) - .As(); + .UnsafeAs(); #endif } @@ -1111,6 +1422,18 @@ inline MaybeOrValue Symbol::For(napi_env env, return Symbol::For(env, descriptionValue); } +inline MaybeOrValue Symbol::For(napi_env env, + std::string_view description) { + napi_value descriptionValue = String::New(env, description); + return Symbol::For(env, descriptionValue); +} + +template > +inline MaybeOrValue Symbol::For(napi_env env, T&& description) { + std::string_view descriptionView = std::forward(description); + return Symbol::For(env, descriptionView); +} + inline MaybeOrValue Symbol::For(napi_env env, const char* description) { napi_value descriptionValue = String::New(env, description); return Symbol::For(env, descriptionValue); @@ -1142,6 +1465,15 @@ inline MaybeOrValue Symbol::For(napi_env env, napi_value description) { #endif } +inline void Symbol::CheckCast(napi_env env, napi_value value) { + NAPI_CHECK(value != nullptr, "Symbol::CheckCast", "empty value"); + + napi_valuetype type; + napi_status status = napi_typeof(env, value, &type); + NAPI_CHECK(status == napi_ok, "Symbol::CheckCast", "napi_typeof failed"); + NAPI_INTERNAL_CHECK_EQ(type, napi_symbol, "%d", "Symbol::CheckCast"); +} + inline Symbol::Symbol() : Name() {} inline Symbol::Symbol(napi_env env, napi_value value) : Name(env, value) {} @@ -1239,6 +1571,32 @@ String String::From(napi_env env, const T& value) { return Helper::From(env, value); } +//////////////////////////////////////////////////////////////////////////////// +// TypeTaggable class +//////////////////////////////////////////////////////////////////////////////// + +inline TypeTaggable::TypeTaggable() : Value() {} + +inline TypeTaggable::TypeTaggable(napi_env _env, napi_value _value) + : Value(_env, _value) {} + +#if NAPI_VERSION >= 8 + +inline void TypeTaggable::TypeTag(const napi_type_tag* type_tag) const { + napi_status status = napi_type_tag_object(_env, _value, type_tag); + NAPI_THROW_IF_FAILED_VOID(_env, status); +} + +inline bool TypeTaggable::CheckTypeTag(const napi_type_tag* type_tag) const { + bool result; + napi_status status = + napi_check_object_type_tag(_env, _value, type_tag, &result); + NAPI_THROW_IF_FAILED(_env, status, false); + return result; +} + +#endif // NAPI_VERSION >= 8 + //////////////////////////////////////////////////////////////////////////////// // Object class //////////////////////////////////////////////////////////////////////////////// @@ -1267,6 +1625,11 @@ inline Object::PropertyLValue& Object::PropertyLValue::operator=( return *this; } +template +inline Value Object::PropertyLValue::AsValue() const { + return Value(*this); +} + template inline Object::PropertyLValue::PropertyLValue(Object object, Key key) : _env(object.Env()), _object(object), _key(key) {} @@ -1278,9 +1641,22 @@ inline Object Object::New(napi_env env) { return Object(env, value); } -inline Object::Object() : Value() {} +inline void Object::CheckCast(napi_env env, napi_value value) { + NAPI_CHECK(value != nullptr, "Object::CheckCast", "empty value"); + + napi_valuetype type; + napi_status status = napi_typeof(env, value, &type); + NAPI_CHECK(status == napi_ok, "Object::CheckCast", "napi_typeof failed"); + NAPI_INTERNAL_CHECK(type == napi_object || type == napi_function, + "Object::CheckCast", + "Expect napi_object or napi_function, but got %d.", + type); +} + +inline Object::Object() : TypeTaggable() {} -inline Object::Object(napi_env env, napi_value value) : Value(env, value) {} +inline Object::Object(napi_env env, napi_value value) + : TypeTaggable(env, value) {} inline Object::PropertyLValue Object::operator[]( const char* utf8name) { @@ -1506,11 +1882,8 @@ inline void Object::AddFinalizer(Finalizer finalizeCallback, T* data) const { new details::FinalizeData( {std::move(finalizeCallback), nullptr}); napi_status status = - details::AttachData(_env, - *this, - data, - details::FinalizeData::Wrapper, - finalizeData); + details::AttachData::Wrapper>( + _env, *this, data, finalizeData); if (status != napi_ok) { delete finalizeData; NAPI_THROW_IF_FAILED_VOID(_env, status); @@ -1524,19 +1897,16 @@ inline void Object::AddFinalizer(Finalizer finalizeCallback, details::FinalizeData* finalizeData = new details::FinalizeData( {std::move(finalizeCallback), finalizeHint}); - napi_status status = details::AttachData( - _env, - *this, - data, - details::FinalizeData::WrapperWithHint, - finalizeData); + napi_status status = details:: + AttachData::WrapperWithHint>( + _env, *this, data, finalizeData); if (status != napi_ok) { delete finalizeData; NAPI_THROW_IF_FAILED_VOID(_env, status); } } -#ifdef NAPI_CPP_EXCEPTIONS +#ifdef NODE_ADDON_API_CPP_EXCEPTIONS inline Object::const_iterator::const_iterator(const Object* object, const Type type) { _object = object; @@ -1611,7 +1981,7 @@ Object::iterator::operator*() { PropertyLValue value = (*_object)[key]; return {key, value}; } -#endif // NAPI_CPP_EXCEPTIONS +#endif // NODE_ADDON_API_CPP_EXCEPTIONS #if NAPI_VERSION >= 8 inline MaybeOrValue Object::Freeze() const { @@ -1625,6 +1995,19 @@ inline MaybeOrValue Object::Seal() const { } #endif // NAPI_VERSION >= 8 +inline MaybeOrValue Object::GetPrototype() const { + napi_value result; + napi_status status = napi_get_prototype(_env, _value, &result); + NAPI_RETURN_OR_THROW_IF_FAILED(_env, status, Object(_env, result), Object); +} + +#ifdef NODE_API_EXPERIMENTAL_HAS_SET_PROTOTYPE +inline MaybeOrValue Object::SetPrototype(const Object& value) const { + napi_status status = node_api_set_prototype(_env, _value, value); + NAPI_RETURN_OR_THROW_IF_FAILED(_env, status, status == napi_ok, bool); +} +#endif + //////////////////////////////////////////////////////////////////////////////// // External class //////////////////////////////////////////////////////////////////////////////// @@ -1684,11 +2067,21 @@ inline External External::New(napi_env env, } template -inline External::External() : Value() {} +inline void External::CheckCast(napi_env env, napi_value value) { + NAPI_CHECK(value != nullptr, "External::CheckCast", "empty value"); + + napi_valuetype type; + napi_status status = napi_typeof(env, value, &type); + NAPI_CHECK(status == napi_ok, "External::CheckCast", "napi_typeof failed"); + NAPI_INTERNAL_CHECK_EQ(type, napi_external, "%d", "External::CheckCast"); +} + +template +inline External::External() : TypeTaggable() {} template inline External::External(napi_env env, napi_value value) - : Value(env, value) {} + : TypeTaggable(env, value) {} template inline T* External::Data() const { @@ -1716,6 +2109,15 @@ inline Array Array::New(napi_env env, size_t length) { return Array(env, value); } +inline void Array::CheckCast(napi_env env, napi_value value) { + NAPI_CHECK(value != nullptr, "Array::CheckCast", "empty value"); + + bool result; + napi_status status = napi_is_array(env, value, &result); + NAPI_CHECK(status == napi_ok, "Array::CheckCast", "napi_is_array failed"); + NAPI_CHECK(result, "Array::CheckCast", "value is not array"); +} + inline Array::Array() : Object() {} inline Array::Array(napi_env env, napi_value value) : Object(env, value) {} @@ -1727,6 +2129,55 @@ inline uint32_t Array::Length() const { return result; } +#ifdef NODE_API_EXPERIMENTAL_HAS_SHAREDARRAYBUFFER +//////////////////////////////////////////////////////////////////////////////// +// SharedArrayBuffer class +//////////////////////////////////////////////////////////////////////////////// + +inline SharedArrayBuffer::SharedArrayBuffer() : Object() {} + +inline SharedArrayBuffer::SharedArrayBuffer(napi_env env, napi_value value) + : Object(env, value) {} + +inline void SharedArrayBuffer::CheckCast(napi_env env, napi_value value) { + NAPI_CHECK(value != nullptr, "SharedArrayBuffer::CheckCast", "empty value"); + + bool result; + napi_status status = node_api_is_sharedarraybuffer(env, value, &result); + NAPI_CHECK(status == napi_ok, + "SharedArrayBuffer::CheckCast", + "node_api_is_sharedarraybuffer failed"); + NAPI_CHECK( + result, "SharedArrayBuffer::CheckCast", "value is not sharedarraybuffer"); +} + +inline SharedArrayBuffer SharedArrayBuffer::New(napi_env env, + size_t byteLength) { + napi_value value; + void* data; + napi_status status = + node_api_create_sharedarraybuffer(env, byteLength, &data, &value); + NAPI_THROW_IF_FAILED(env, status, SharedArrayBuffer()); + + return SharedArrayBuffer(env, value); +} + +inline void* SharedArrayBuffer::Data() { + void* data; + napi_status status = napi_get_arraybuffer_info(_env, _value, &data, nullptr); + NAPI_THROW_IF_FAILED(_env, status, nullptr); + return data; +} + +inline size_t SharedArrayBuffer::ByteLength() { + size_t length; + napi_status status = + napi_get_arraybuffer_info(_env, _value, nullptr, &length); + NAPI_THROW_IF_FAILED(_env, status, 0); + return length; +} +#endif // NODE_API_EXPERIMENTAL_HAS_SHAREDARRAYBUFFER + //////////////////////////////////////////////////////////////////////////////// // ArrayBuffer class //////////////////////////////////////////////////////////////////////////////// @@ -1740,6 +2191,7 @@ inline ArrayBuffer ArrayBuffer::New(napi_env env, size_t byteLength) { return ArrayBuffer(env, value); } +#ifndef NODE_API_NO_EXTERNAL_BUFFERS_ALLOWED inline ArrayBuffer ArrayBuffer::New(napi_env env, void* externalData, size_t byteLength) { @@ -1799,6 +2251,18 @@ inline ArrayBuffer ArrayBuffer::New(napi_env env, return ArrayBuffer(env, value); } +#endif // NODE_API_NO_EXTERNAL_BUFFERS_ALLOWED + +inline void ArrayBuffer::CheckCast(napi_env env, napi_value value) { + NAPI_CHECK(value != nullptr, "ArrayBuffer::CheckCast", "empty value"); + + bool result; + napi_status status = napi_is_arraybuffer(env, value, &result); + NAPI_CHECK(status == napi_ok, + "ArrayBuffer::CheckCast", + "napi_is_arraybuffer failed"); + NAPI_CHECK(result, "ArrayBuffer::CheckCast", "value is not arraybuffer"); +} inline ArrayBuffer::ArrayBuffer() : Object() {} @@ -1867,6 +2331,49 @@ inline DataView DataView::New(napi_env env, return DataView(env, value); } +#ifdef NODE_API_EXPERIMENTAL_HAS_SHAREDARRAYBUFFER +inline DataView DataView::New(napi_env env, + Napi::SharedArrayBuffer arrayBuffer) { + return New(env, arrayBuffer, 0, arrayBuffer.ByteLength()); +} + +inline DataView DataView::New(napi_env env, + Napi::SharedArrayBuffer arrayBuffer, + size_t byteOffset) { + if (byteOffset > arrayBuffer.ByteLength()) { + NAPI_THROW(RangeError::New( + env, "Start offset is outside the bounds of the buffer"), + DataView()); + } + return New( + env, arrayBuffer, byteOffset, arrayBuffer.ByteLength() - byteOffset); +} + +inline DataView DataView::New(napi_env env, + Napi::SharedArrayBuffer arrayBuffer, + size_t byteOffset, + size_t byteLength) { + if (byteOffset + byteLength > arrayBuffer.ByteLength()) { + NAPI_THROW(RangeError::New(env, "Invalid DataView length"), DataView()); + } + napi_value value; + napi_status status = + napi_create_dataview(env, byteLength, arrayBuffer, byteOffset, &value); + NAPI_THROW_IF_FAILED(env, status, DataView()); + return DataView(env, value); +} +#endif // NODE_API_EXPERIMENTAL_HAS_SHAREDARRAYBUFFER + +inline void DataView::CheckCast(napi_env env, napi_value value) { + NAPI_CHECK(value != nullptr, "DataView::CheckCast", "empty value"); + + bool result; + napi_status status = napi_is_dataview(env, value, &result); + NAPI_CHECK( + status == napi_ok, "DataView::CheckCast", "napi_is_dataview failed"); + NAPI_CHECK(result, "DataView::CheckCast", "value is not dataview"); +} + inline DataView::DataView() : Object() {} inline DataView::DataView(napi_env env, napi_value value) : Object(env, value) { @@ -1880,6 +2387,10 @@ inline DataView::DataView(napi_env env, napi_value value) : Object(env, value) { } inline Napi::ArrayBuffer DataView::ArrayBuffer() const { + return Buffer().As(); +} + +inline Napi::Value DataView::Buffer() const { napi_value arrayBuffer; napi_status status = napi_get_dataview_info(_env, _value /* dataView */, @@ -1887,8 +2398,8 @@ inline Napi::ArrayBuffer DataView::ArrayBuffer() const { nullptr /* data */, &arrayBuffer /* arrayBuffer */, nullptr /* byteOffset */); - NAPI_THROW_IF_FAILED(_env, status, Napi::ArrayBuffer()); - return Napi::ArrayBuffer(_env, arrayBuffer); + NAPI_THROW_IF_FAILED(_env, status, Napi::Value()); + return Napi::Value(_env, arrayBuffer); } inline size_t DataView::ByteOffset() const { @@ -2001,6 +2512,15 @@ inline void DataView::WriteData(size_t byteOffset, T value) const { //////////////////////////////////////////////////////////////////////////////// // TypedArray class //////////////////////////////////////////////////////////////////////////////// +inline void TypedArray::CheckCast(napi_env env, napi_value value) { + NAPI_CHECK(value != nullptr, "TypedArray::CheckCast", "empty value"); + + bool result; + napi_status status = napi_is_typedarray(env, value, &result); + NAPI_CHECK( + status == napi_ok, "TypedArray::CheckCast", "napi_is_typedarray failed"); + NAPI_CHECK(result, "TypedArray::CheckCast", "value is not typedarray"); +} inline TypedArray::TypedArray() : Object(), _type(napi_typedarray_type::napi_int8_array), _length(0) {} @@ -2080,9 +2600,35 @@ inline Napi::ArrayBuffer TypedArray::ArrayBuffer() const { return Napi::ArrayBuffer(_env, arrayBuffer); } +inline Napi::Value TypedArray::Buffer() const { + napi_value arrayBuffer; + napi_status status = napi_get_typedarray_info( + _env, _value, nullptr, nullptr, nullptr, &arrayBuffer, nullptr); + NAPI_THROW_IF_FAILED(_env, status, Napi::Value()); + return Napi::Value(_env, arrayBuffer); +} + //////////////////////////////////////////////////////////////////////////////// // TypedArrayOf class //////////////////////////////////////////////////////////////////////////////// +template +inline void TypedArrayOf::CheckCast(napi_env env, napi_value value) { + TypedArray::CheckCast(env, value); + napi_typedarray_type type; + napi_status status = napi_get_typedarray_info( + env, value, &type, nullptr, nullptr, nullptr, nullptr); + NAPI_CHECK(status == napi_ok, + "TypedArrayOf::CheckCast", + "napi_is_typedarray failed"); + + NAPI_INTERNAL_CHECK( + (type == TypedArrayTypeForPrimitiveType() || + (type == napi_uint8_clamped_array && std::is_same::value)), + "TypedArrayOf::CheckCast", + "Array type must match the template parameter, (Uint8 arrays may " + "optionally have the \"clamped\" array type.), got %d.", + type); +} template inline TypedArrayOf TypedArrayOf::New(napi_env env, @@ -2113,6 +2659,28 @@ inline TypedArrayOf TypedArrayOf::New(napi_env env, bufferOffset)); } +#ifdef NODE_API_EXPERIMENTAL_HAS_SHAREDARRAYBUFFER +template +inline TypedArrayOf TypedArrayOf::New(napi_env env, + size_t elementLength, + Napi::SharedArrayBuffer arrayBuffer, + size_t bufferOffset, + napi_typedarray_type type) { + napi_value value; + napi_status status = napi_create_typedarray( + env, type, elementLength, arrayBuffer, bufferOffset, &value); + NAPI_THROW_IF_FAILED(env, status, TypedArrayOf()); + + return TypedArrayOf( + env, + value, + type, + elementLength, + reinterpret_cast(reinterpret_cast(arrayBuffer.Data()) + + bufferOffset)); +} +#endif + template inline TypedArrayOf::TypedArrayOf() : TypedArray(), _data(nullptr) {} @@ -2174,11 +2742,11 @@ inline const T* TypedArrayOf::Data() const { //////////////////////////////////////////////////////////////////////////////// template -static inline napi_status CreateFunction(napi_env env, - const char* utf8name, - napi_callback cb, - CbData* data, - napi_value* result) { +inline napi_status CreateFunction(napi_env env, + const char* utf8name, + napi_callback cb, + CbData* data, + napi_value* result) { napi_status status = napi_create_function(env, utf8name, NAPI_AUTO_LENGTH, cb, data, result); if (status == napi_ok) { @@ -2256,6 +2824,15 @@ inline Function Function::New(napi_env env, return New(env, cb, utf8name.c_str(), data); } +inline void Function::CheckCast(napi_env env, napi_value value) { + NAPI_CHECK(value != nullptr, "Function::CheckCast", "empty value"); + + napi_valuetype type; + napi_status status = napi_typeof(env, value, &type); + NAPI_CHECK(status == napi_ok, "Function::CheckCast", "napi_typeof failed"); + NAPI_INTERNAL_CHECK_EQ(type, napi_function, "%d", "Function::CheckCast"); +} + inline Function::Function() : Object() {} inline Function::Function(napi_env env, napi_value value) @@ -2388,22 +2965,118 @@ inline Promise Promise::Deferred::Promise() const { return Napi::Promise(_env, _promise); } -inline Napi::Env Promise::Deferred::Env() const { - return Napi::Env(_env); +inline Napi::Env Promise::Deferred::Env() const { + return Napi::Env(_env); +} + +inline void Promise::Deferred::Resolve(napi_value value) const { + napi_status status = napi_resolve_deferred(_env, _deferred, value); + NAPI_THROW_IF_FAILED_VOID(_env, status); +} + +inline void Promise::Deferred::Reject(napi_value value) const { + napi_status status = napi_reject_deferred(_env, _deferred, value); + NAPI_THROW_IF_FAILED_VOID(_env, status); +} + +inline void Promise::CheckCast(napi_env env, napi_value value) { + NAPI_CHECK(value != nullptr, "Promise::CheckCast", "empty value"); + + bool result; + napi_status status = napi_is_promise(env, value, &result); + NAPI_CHECK(status == napi_ok, "Promise::CheckCast", "napi_is_promise failed"); + NAPI_CHECK(result, "Promise::CheckCast", "value is not promise"); +} + +inline Promise::Promise() : Object() {} + +inline Promise::Promise(napi_env env, napi_value value) : Object(env, value) {} + +inline MaybeOrValue Promise::Then(napi_value onFulfilled) const { + EscapableHandleScope scope(_env); +#ifdef NODE_ADDON_API_ENABLE_MAYBE + Value thenMethod; + if (!Get("then").UnwrapTo(&thenMethod)) { + return Nothing(); + } + MaybeOrValue result = + thenMethod.As().Call(*this, {onFulfilled}); + if (result.IsJust()) { + return Just(scope.Escape(result.Unwrap()).As()); + } + return Nothing(); +#else + Function thenMethod = Get("then").As(); + MaybeOrValue result = thenMethod.Call(*this, {onFulfilled}); + if (scope.Env().IsExceptionPending()) { + return Promise(); + } + return scope.Escape(result).As(); +#endif +} + +inline MaybeOrValue Promise::Then(napi_value onFulfilled, + napi_value onRejected) const { + EscapableHandleScope scope(_env); +#ifdef NODE_ADDON_API_ENABLE_MAYBE + Value thenMethod; + if (!Get("then").UnwrapTo(&thenMethod)) { + return Nothing(); + } + MaybeOrValue result = + thenMethod.As().Call(*this, {onFulfilled, onRejected}); + if (result.IsJust()) { + return Just(scope.Escape(result.Unwrap()).As()); + } + return Nothing(); +#else + Function thenMethod = Get("then").As(); + MaybeOrValue result = + thenMethod.Call(*this, {onFulfilled, onRejected}); + if (scope.Env().IsExceptionPending()) { + return Promise(); + } + return scope.Escape(result).As(); +#endif +} + +inline MaybeOrValue Promise::Catch(napi_value onRejected) const { + EscapableHandleScope scope(_env); +#ifdef NODE_ADDON_API_ENABLE_MAYBE + Value catchMethod; + if (!Get("catch").UnwrapTo(&catchMethod)) { + return Nothing(); + } + MaybeOrValue result = + catchMethod.As().Call(*this, {onRejected}); + if (result.IsJust()) { + return Just(scope.Escape(result.Unwrap()).As()); + } + return Nothing(); +#else + Function catchMethod = Get("catch").As(); + MaybeOrValue result = catchMethod.Call(*this, {onRejected}); + if (scope.Env().IsExceptionPending()) { + return Promise(); + } + return scope.Escape(result).As(); +#endif +} + +inline MaybeOrValue Promise::Then(const Function& onFulfilled) const { + return Then(static_cast(onFulfilled)); } -inline void Promise::Deferred::Resolve(napi_value value) const { - napi_status status = napi_resolve_deferred(_env, _deferred, value); - NAPI_THROW_IF_FAILED_VOID(_env, status); +inline MaybeOrValue Promise::Then(const Function& onFulfilled, + const Function& onRejected) const { + return Then(static_cast(onFulfilled), + static_cast(onRejected)); } -inline void Promise::Deferred::Reject(napi_value value) const { - napi_status status = napi_reject_deferred(_env, _deferred, value); - NAPI_THROW_IF_FAILED_VOID(_env, status); +inline MaybeOrValue Promise::Catch(const Function& onRejected) const { + return Catch(static_cast(onRejected)); } -inline Promise::Promise(napi_env env, napi_value value) : Object(env, value) {} - //////////////////////////////////////////////////////////////////////////////// // Buffer class //////////////////////////////////////////////////////////////////////////////// @@ -2415,16 +3088,17 @@ inline Buffer Buffer::New(napi_env env, size_t length) { napi_status status = napi_create_buffer(env, length * sizeof(T), &data, &value); NAPI_THROW_IF_FAILED(env, status, Buffer()); - return Buffer(env, value, length, static_cast(data)); + return Buffer(env, value); } +#ifndef NODE_API_NO_EXTERNAL_BUFFERS_ALLOWED template inline Buffer Buffer::New(napi_env env, T* data, size_t length) { napi_value value; napi_status status = napi_create_external_buffer( env, length * sizeof(T), data, nullptr, nullptr, &value); NAPI_THROW_IF_FAILED(env, status, Buffer()); - return Buffer(env, value, length, data); + return Buffer(env, value); } template @@ -2448,7 +3122,7 @@ inline Buffer Buffer::New(napi_env env, delete finalizeData; NAPI_THROW_IF_FAILED(env, status, Buffer()); } - return Buffer(env, value, length, data); + return Buffer(env, value); } template @@ -2473,7 +3147,95 @@ inline Buffer Buffer::New(napi_env env, delete finalizeData; NAPI_THROW_IF_FAILED(env, status, Buffer()); } - return Buffer(env, value, length, data); + return Buffer(env, value); +} +#endif // NODE_API_NO_EXTERNAL_BUFFERS_ALLOWED + +template +inline Buffer Buffer::NewOrCopy(napi_env env, T* data, size_t length) { +#ifndef NODE_API_NO_EXTERNAL_BUFFERS_ALLOWED + napi_value value; + napi_status status = napi_create_external_buffer( + env, length * sizeof(T), data, nullptr, nullptr, &value); + if (status == details::napi_no_external_buffers_allowed) { +#endif // NODE_API_NO_EXTERNAL_BUFFERS_ALLOWED + // If we can't create an external buffer, we'll just copy the data. + return Buffer::Copy(env, data, length); +#ifndef NODE_API_NO_EXTERNAL_BUFFERS_ALLOWED + } + NAPI_THROW_IF_FAILED(env, status, Buffer()); + return Buffer(env, value); +#endif // NODE_API_NO_EXTERNAL_BUFFERS_ALLOWED +} + +template +template +inline Buffer Buffer::NewOrCopy(napi_env env, + T* data, + size_t length, + Finalizer finalizeCallback) { + details::FinalizeData* finalizeData = + new details::FinalizeData( + {std::move(finalizeCallback), nullptr}); +#ifndef NODE_API_NO_EXTERNAL_BUFFERS_ALLOWED + napi_value value; + napi_status status = + napi_create_external_buffer(env, + length * sizeof(T), + data, + details::FinalizeData::Wrapper, + finalizeData, + &value); + if (status == details::napi_no_external_buffers_allowed) { +#endif // NODE_API_NO_EXTERNAL_BUFFERS_ALLOWED + // If we can't create an external buffer, we'll just copy the data. + Buffer ret = Buffer::Copy(env, data, length); + details::FinalizeData::WrapperGC(env, data, finalizeData); + return ret; +#ifndef NODE_API_NO_EXTERNAL_BUFFERS_ALLOWED + } + if (status != napi_ok) { + delete finalizeData; + NAPI_THROW_IF_FAILED(env, status, Buffer()); + } + return Buffer(env, value); +#endif // NODE_API_NO_EXTERNAL_BUFFERS_ALLOWED +} + +template +template +inline Buffer Buffer::NewOrCopy(napi_env env, + T* data, + size_t length, + Finalizer finalizeCallback, + Hint* finalizeHint) { + details::FinalizeData* finalizeData = + new details::FinalizeData( + {std::move(finalizeCallback), finalizeHint}); +#ifndef NODE_API_NO_EXTERNAL_BUFFERS_ALLOWED + napi_value value; + napi_status status = napi_create_external_buffer( + env, + length * sizeof(T), + data, + details::FinalizeData::WrapperWithHint, + finalizeData, + &value); + if (status == details::napi_no_external_buffers_allowed) { +#endif + // If we can't create an external buffer, we'll just copy the data. + Buffer ret = Buffer::Copy(env, data, length); + details::FinalizeData::WrapperGCWithHint( + env, data, finalizeData); + return ret; +#ifndef NODE_API_NO_EXTERNAL_BUFFERS_ALLOWED + } + if (status != napi_ok) { + delete finalizeData; + NAPI_THROW_IF_FAILED(env, status, Buffer()); + } + return Buffer(env, value); +#endif } template @@ -2486,42 +3248,30 @@ inline Buffer Buffer::Copy(napi_env env, const T* data, size_t length) { } template -inline Buffer::Buffer() : Uint8Array(), _length(0), _data(nullptr) {} +inline void Buffer::CheckCast(napi_env env, napi_value value) { + NAPI_CHECK(value != nullptr, "Buffer::CheckCast", "empty value"); + + bool result; + napi_status status = napi_is_buffer(env, value, &result); + NAPI_CHECK(status == napi_ok, "Buffer::CheckCast", "napi_is_buffer failed"); + NAPI_CHECK(result, "Buffer::CheckCast", "value is not buffer"); +} template -inline Buffer::Buffer(napi_env env, napi_value value) - : Uint8Array(env, value), _length(0), _data(nullptr) {} +inline Buffer::Buffer() : Uint8Array() {} template -inline Buffer::Buffer(napi_env env, napi_value value, size_t length, T* data) - : Uint8Array(env, value), _length(length), _data(data) {} +inline Buffer::Buffer(napi_env env, napi_value value) + : Uint8Array(env, value) {} template inline size_t Buffer::Length() const { - EnsureInfo(); - return _length; + return ByteLength() / sizeof(T); } template inline T* Buffer::Data() const { - EnsureInfo(); - return _data; -} - -template -inline void Buffer::EnsureInfo() const { - // The Buffer instance may have been constructed from a napi_value whose - // length/data are not yet known. Fetch and cache these values just once, - // since they can never change during the lifetime of the Buffer. - if (_data == nullptr) { - size_t byteLength; - void* voidData; - napi_status status = - napi_get_buffer_info(_env, _value, &voidData, &byteLength); - NAPI_THROW_IF_FAILED_VOID(_env, status); - _length = byteLength / sizeof(T); - _data = static_cast(voidData); - } + return reinterpret_cast(const_cast(Uint8Array::Data())); } //////////////////////////////////////////////////////////////////////////////// @@ -2630,6 +3380,22 @@ inline Error::Error(napi_env env, napi_value value) nullptr}; status = napi_define_properties(env, wrappedErrorObj, 1, &wrapObjFlag); +#ifdef NODE_API_SWALLOW_UNTHROWABLE_EXCEPTIONS + if (status == napi_pending_exception) { + // Test if the pending exception was reported because the environment is + // shutting down. We assume that a status of napi_pending_exception + // coupled with the absence of an actual pending exception means that + // the environment is shutting down. If so, we replace the + // napi_pending_exception status with napi_ok. + bool is_exception_pending = false; + status = napi_is_exception_pending(env, &is_exception_pending); + if (status == napi_ok && !is_exception_pending) { + status = napi_ok; + } else { + status = napi_pending_exception; + } + } +#endif // NODE_API_SWALLOW_UNTHROWABLE_EXCEPTIONS NAPI_FATAL_IF_FAILED(status, "Error::Error", "napi_define_properties"); // Create a reference on the newly wrapped object @@ -2707,14 +3473,14 @@ inline Error& Error::operator=(const Error& other) { inline const std::string& Error::Message() const NAPI_NOEXCEPT { if (_message.size() == 0 && _env != nullptr) { -#ifdef NAPI_CPP_EXCEPTIONS +#ifdef NODE_ADDON_API_CPP_EXCEPTIONS try { _message = Get("message").As(); } catch (...) { // Catch all errors here, to include e.g. a std::bad_alloc from // the std::string::operator=, because this method may not throw. } -#else // NAPI_CPP_EXCEPTIONS +#else // NODE_ADDON_API_CPP_EXCEPTIONS #if defined(NODE_ADDON_API_ENABLE_MAYBE) Napi::Value message_val; if (Get("message").UnwrapTo(&message_val)) { @@ -2723,7 +3489,7 @@ inline const std::string& Error::Message() const NAPI_NOEXCEPT { #else _message = Get("message").As(); #endif -#endif // NAPI_CPP_EXCEPTIONS +#endif // NODE_ADDON_API_CPP_EXCEPTIONS } return _message; } @@ -2747,7 +3513,12 @@ inline void Error::ThrowAsJavaScriptException() const { status = napi_throw(_env, Value()); - if (status == napi_pending_exception) { +#if (NAPI_VERSION >= 10) + napi_status expected_failure_mode = napi_cannot_run_js; +#else + napi_status expected_failure_mode = napi_pending_exception; +#endif + if (status == expected_failure_mode) { // The environment must be terminating as we checked earlier and there // was no pending exception. In this case continuing will result // in a fatal error and there is nothing the author has done incorrectly @@ -2765,24 +3536,24 @@ inline void Error::ThrowAsJavaScriptException() const { napi_status status = napi_throw(_env, Value()); #endif -#ifdef NAPI_CPP_EXCEPTIONS +#ifdef NODE_ADDON_API_CPP_EXCEPTIONS if (status != napi_ok) { throw Error::New(_env); } -#else // NAPI_CPP_EXCEPTIONS +#else // NODE_ADDON_API_CPP_EXCEPTIONS NAPI_FATAL_IF_FAILED( status, "Error::ThrowAsJavaScriptException", "napi_throw"); -#endif // NAPI_CPP_EXCEPTIONS +#endif // NODE_ADDON_API_CPP_EXCEPTIONS } } -#ifdef NAPI_CPP_EXCEPTIONS +#ifdef NODE_ADDON_API_CPP_EXCEPTIONS inline const char* Error::what() const NAPI_NOEXCEPT { return Message().c_str(); } -#endif // NAPI_CPP_EXCEPTIONS +#endif // NODE_ADDON_API_CPP_EXCEPTIONS inline const char* Error::ERROR_WRAP_VALUE() NAPI_NOEXCEPT { return "4bda9e7e-4913-4dbc-95de-891cbf66598e-errorVal"; @@ -2834,6 +3605,23 @@ inline RangeError::RangeError() : Error() {} inline RangeError::RangeError(napi_env env, napi_value value) : Error(env, value) {} +#if NAPI_VERSION > 8 +inline SyntaxError SyntaxError::New(napi_env env, const char* message) { + return Error::New( + env, message, std::strlen(message), node_api_create_syntax_error); +} + +inline SyntaxError SyntaxError::New(napi_env env, const std::string& message) { + return Error::New( + env, message.c_str(), message.size(), node_api_create_syntax_error); +} + +inline SyntaxError::SyntaxError() : Error() {} + +inline SyntaxError::SyntaxError(napi_env env, napi_value value) + : Error(env, value) {} +#endif // NAPI_VERSION > 8 + //////////////////////////////////////////////////////////////////////////////// // Reference class //////////////////////////////////////////////////////////////////////////////// @@ -2867,7 +3655,15 @@ template inline Reference::~Reference() { if (_ref != nullptr) { if (!_suppressDestruct) { + // TODO(legendecas): napi_delete_reference should be invoked immediately. + // Fix this when https://github.com/nodejs/node/pull/55620 lands. +#ifdef NODE_API_EXPERIMENTAL_HAS_POST_FINALIZER + Env().PostFinalizer( + [](Napi::Env env, napi_ref ref) { napi_delete_reference(env, ref); }, + _ref); +#else napi_delete_reference(_env, _ref); +#endif } _ref = nullptr; @@ -3122,8 +3918,8 @@ inline MaybeOrValue ObjectReference::Set(const std::string& utf8name, return Value().Set(utf8name, value); } -inline MaybeOrValue ObjectReference::Set(const std::string& utf8name, - std::string& utf8value) const { +inline MaybeOrValue ObjectReference::Set( + const std::string& utf8name, const std::string& utf8value) const { HandleScope scope(_env); return Value().Set(utf8name, utf8value); } @@ -3448,6 +4244,10 @@ inline CallbackInfo::~CallbackInfo() { } } +inline CallbackInfo::operator napi_callback_info() const { + return _info; +} + inline Value CallbackInfo::NewTarget() const { napi_value newTarget; napi_status status = napi_get_new_target(_env, _info, &newTarget); @@ -3887,48 +4687,71 @@ template template ::InstanceVoidMethodCallback method> inline ClassPropertyDescriptor InstanceWrap::InstanceMethod( const char* utf8name, napi_property_attributes attributes, void* data) { +#ifdef _MSC_VER + // MSVC (as of v145 / Visual Studio 2026) raises an internal compiler error + // (C1001) when a pointer-to-member-function is used as a non-type template + // parameter, as the static compile-time dispatch below does. On MSVC, fall + // back to the runtime overload, which passes `method` as a value instead. + return InstanceMethod(utf8name, method, attributes, data); +#else napi_property_descriptor desc = napi_property_descriptor(); desc.utf8name = utf8name; desc.method = details::TemplatedInstanceVoidCallback; desc.data = data; desc.attributes = attributes; return desc; +#endif } template template ::InstanceMethodCallback method> inline ClassPropertyDescriptor InstanceWrap::InstanceMethod( const char* utf8name, napi_property_attributes attributes, void* data) { +#ifdef _MSC_VER + // See the note in the InstanceMethod overload above. + return InstanceMethod(utf8name, method, attributes, data); +#else napi_property_descriptor desc = napi_property_descriptor(); desc.utf8name = utf8name; desc.method = details::TemplatedInstanceCallback; desc.data = data; desc.attributes = attributes; return desc; +#endif } template template ::InstanceVoidMethodCallback method> inline ClassPropertyDescriptor InstanceWrap::InstanceMethod( Symbol name, napi_property_attributes attributes, void* data) { +#ifdef _MSC_VER + // See the note in the InstanceMethod overload above. + return InstanceMethod(name, method, attributes, data); +#else napi_property_descriptor desc = napi_property_descriptor(); desc.name = name; desc.method = details::TemplatedInstanceVoidCallback; desc.data = data; desc.attributes = attributes; return desc; +#endif } template template ::InstanceMethodCallback method> inline ClassPropertyDescriptor InstanceWrap::InstanceMethod( Symbol name, napi_property_attributes attributes, void* data) { +#ifdef _MSC_VER + // See the note in the InstanceMethod overload above. + return InstanceMethod(name, method, attributes, data); +#else napi_property_descriptor desc = napi_property_descriptor(); desc.name = name; desc.method = details::TemplatedInstanceCallback; desc.data = data; desc.attributes = attributes; return desc; +#endif } template @@ -3974,6 +4797,10 @@ template ::InstanceGetterCallback getter, typename InstanceWrap::InstanceSetterCallback setter> inline ClassPropertyDescriptor InstanceWrap::InstanceAccessor( const char* utf8name, napi_property_attributes attributes, void* data) { +#ifdef _MSC_VER + // See the note in the InstanceMethod overload above. + return InstanceAccessor(utf8name, getter, setter, attributes, data); +#else napi_property_descriptor desc = napi_property_descriptor(); desc.utf8name = utf8name; desc.getter = details::TemplatedInstanceCallback; @@ -3981,6 +4808,7 @@ inline ClassPropertyDescriptor InstanceWrap::InstanceAccessor( desc.data = data; desc.attributes = attributes; return desc; +#endif } template @@ -3988,6 +4816,10 @@ template ::InstanceGetterCallback getter, typename InstanceWrap::InstanceSetterCallback setter> inline ClassPropertyDescriptor InstanceWrap::InstanceAccessor( Symbol name, napi_property_attributes attributes, void* data) { +#ifdef _MSC_VER + // See the note in the InstanceMethod overload above. + return InstanceAccessor(name, getter, setter, attributes, data); +#else napi_property_descriptor desc = napi_property_descriptor(); desc.name = name; desc.getter = details::TemplatedInstanceCallback; @@ -3995,6 +4827,7 @@ inline ClassPropertyDescriptor InstanceWrap::InstanceAccessor( desc.data = data; desc.attributes = attributes; return desc; +#endif } template @@ -4022,14 +4855,14 @@ inline ClassPropertyDescriptor InstanceWrap::InstanceValue( template inline napi_value InstanceWrap::InstanceVoidMethodCallbackWrapper( napi_env env, napi_callback_info info) { - return details::WrapCallback([&] { + return details::WrapCallback(env, [&] { CallbackInfo callbackInfo(env, info); InstanceVoidMethodCallbackData* callbackData = reinterpret_cast(callbackInfo.Data()); callbackInfo.SetData(callbackData->data); T* instance = T::Unwrap(callbackInfo.This().As()); auto cb = callbackData->callback; - (instance->*cb)(callbackInfo); + if (instance) (instance->*cb)(callbackInfo); return nullptr; }); } @@ -4037,42 +4870,42 @@ inline napi_value InstanceWrap::InstanceVoidMethodCallbackWrapper( template inline napi_value InstanceWrap::InstanceMethodCallbackWrapper( napi_env env, napi_callback_info info) { - return details::WrapCallback([&] { + return details::WrapCallback(env, [&] { CallbackInfo callbackInfo(env, info); InstanceMethodCallbackData* callbackData = reinterpret_cast(callbackInfo.Data()); callbackInfo.SetData(callbackData->data); T* instance = T::Unwrap(callbackInfo.This().As()); auto cb = callbackData->callback; - return (instance->*cb)(callbackInfo); + return instance ? (instance->*cb)(callbackInfo) : Napi::Value(); }); } template inline napi_value InstanceWrap::InstanceGetterCallbackWrapper( napi_env env, napi_callback_info info) { - return details::WrapCallback([&] { + return details::WrapCallback(env, [&] { CallbackInfo callbackInfo(env, info); InstanceAccessorCallbackData* callbackData = reinterpret_cast(callbackInfo.Data()); callbackInfo.SetData(callbackData->data); T* instance = T::Unwrap(callbackInfo.This().As()); auto cb = callbackData->getterCallback; - return (instance->*cb)(callbackInfo); + return instance ? (instance->*cb)(callbackInfo) : Napi::Value(); }); } template inline napi_value InstanceWrap::InstanceSetterCallbackWrapper( napi_env env, napi_callback_info info) { - return details::WrapCallback([&] { + return details::WrapCallback(env, [&] { CallbackInfo callbackInfo(env, info); InstanceAccessorCallbackData* callbackData = reinterpret_cast(callbackInfo.Data()); callbackInfo.SetData(callbackData->data); T* instance = T::Unwrap(callbackInfo.This().As()); auto cb = callbackData->setterCallback; - (instance->*cb)(callbackInfo, callbackInfo[0]); + if (instance) (instance->*cb)(callbackInfo, callbackInfo[0]); return nullptr; }); } @@ -4081,10 +4914,10 @@ template template ::InstanceSetterCallback method> inline napi_value InstanceWrap::WrappedMethod( napi_env env, napi_callback_info info) NAPI_NOEXCEPT { - return details::WrapCallback([&] { + return details::WrapCallback(env, [&] { const CallbackInfo cbInfo(env, info); T* instance = T::Unwrap(cbInfo.This().As()); - (instance->*method)(cbInfo, cbInfo[0]); + if (instance) (instance->*method)(cbInfo, cbInfo[0]); return nullptr; }); } @@ -4094,7 +4927,8 @@ inline napi_value InstanceWrap::WrappedMethod( //////////////////////////////////////////////////////////////////////////////// template -inline ObjectWrap::ObjectWrap(const Napi::CallbackInfo& callbackInfo) { +inline NAPI_NO_SANITIZE_VPTR ObjectWrap::ObjectWrap( + const Napi::CallbackInfo& callbackInfo) { napi_env env = callbackInfo.Env(); napi_value wrapper = callbackInfo.This(); napi_status status; @@ -4108,10 +4942,10 @@ inline ObjectWrap::ObjectWrap(const Napi::CallbackInfo& callbackInfo) { } template -inline ObjectWrap::~ObjectWrap() { +inline NAPI_NO_SANITIZE_VPTR ObjectWrap::~ObjectWrap() { // If the JS object still exists at this point, remove the finalizer added // through `napi_wrap()`. - if (!IsEmpty()) { + if (!IsEmpty() && !_finalized) { Object object = Value(); // It is not valid to call `napi_remove_wrap()` with an empty `object`. // This happens e.g. during garbage collection. @@ -4121,8 +4955,12 @@ inline ObjectWrap::~ObjectWrap() { } } +// with RTTI turned on, modern compilers check to see if virtual function +// pointers are stripped of RTTI by void casts. this is intrinsic to how Unwrap +// works, so we inject a compiler pragma to turn off that check just for the +// affected methods. this compiler check is on by default in Android NDK 29. template -inline T* ObjectWrap::Unwrap(Object wrapper) { +inline NAPI_NO_SANITIZE_VPTR T* ObjectWrap::Unwrap(Object wrapper) { void* unwrapped; napi_status status = napi_unwrap(wrapper.Env(), wrapper, &unwrapped); NAPI_THROW_IF_FAILED(wrapper.Env(), status, nullptr); @@ -4463,6 +5301,9 @@ inline Value ObjectWrap::OnCalledAsFunction( template inline void ObjectWrap::Finalize(Napi::Env /*env*/) {} +template +inline void ObjectWrap::Finalize(BasicEnv /*env*/) {} + template inline napi_value ObjectWrap::ConstructorCallbackWrapper( napi_env env, napi_callback_info info) { @@ -4473,13 +5314,13 @@ inline napi_value ObjectWrap::ConstructorCallbackWrapper( bool isConstructCall = (new_target != nullptr); if (!isConstructCall) { return details::WrapCallback( - [&] { return T::OnCalledAsFunction(CallbackInfo(env, info)); }); + env, [&] { return T::OnCalledAsFunction(CallbackInfo(env, info)); }); } - napi_value wrapper = details::WrapCallback([&] { + napi_value wrapper = details::WrapCallback(env, [&] { CallbackInfo callbackInfo(env, info); T* instance = new T(callbackInfo); -#ifdef NAPI_CPP_EXCEPTIONS +#ifdef NODE_ADDON_API_CPP_EXCEPTIONS instance->_construction_failed = false; #else if (callbackInfo.Env().IsExceptionPending()) { @@ -4490,7 +5331,7 @@ inline napi_value ObjectWrap::ConstructorCallbackWrapper( } else { instance->_construction_failed = false; } -#endif // NAPI_CPP_EXCEPTIONS +#endif // NODE_ADDON_API_CPP_EXCEPTIONS return callbackInfo.This(); }); @@ -4500,7 +5341,7 @@ inline napi_value ObjectWrap::ConstructorCallbackWrapper( template inline napi_value ObjectWrap::StaticVoidMethodCallbackWrapper( napi_env env, napi_callback_info info) { - return details::WrapCallback([&] { + return details::WrapCallback(env, [&] { CallbackInfo callbackInfo(env, info); StaticVoidMethodCallbackData* callbackData = reinterpret_cast(callbackInfo.Data()); @@ -4513,7 +5354,7 @@ inline napi_value ObjectWrap::StaticVoidMethodCallbackWrapper( template inline napi_value ObjectWrap::StaticMethodCallbackWrapper( napi_env env, napi_callback_info info) { - return details::WrapCallback([&] { + return details::WrapCallback(env, [&] { CallbackInfo callbackInfo(env, info); StaticMethodCallbackData* callbackData = reinterpret_cast(callbackInfo.Data()); @@ -4525,7 +5366,7 @@ inline napi_value ObjectWrap::StaticMethodCallbackWrapper( template inline napi_value ObjectWrap::StaticGetterCallbackWrapper( napi_env env, napi_callback_info info) { - return details::WrapCallback([&] { + return details::WrapCallback(env, [&] { CallbackInfo callbackInfo(env, info); StaticAccessorCallbackData* callbackData = reinterpret_cast(callbackInfo.Data()); @@ -4537,7 +5378,7 @@ inline napi_value ObjectWrap::StaticGetterCallbackWrapper( template inline napi_value ObjectWrap::StaticSetterCallbackWrapper( napi_env env, napi_callback_info info) { - return details::WrapCallback([&] { + return details::WrapCallback(env, [&] { CallbackInfo callbackInfo(env, info); StaticAccessorCallbackData* callbackData = reinterpret_cast(callbackInfo.Data()); @@ -4548,10 +5389,61 @@ inline napi_value ObjectWrap::StaticSetterCallbackWrapper( } template -inline void ObjectWrap::FinalizeCallback(napi_env env, +inline void ObjectWrap::FinalizeCallback(node_addon_api_basic_env env, void* data, void* /*hint*/) { - HandleScope scope(env); + // If the child class does not override _any_ Finalize() method, `env` will be + // unused because of the constexpr guards. Explicitly reference it here to + // bypass compiler warnings. + (void)env; + T* instance = static_cast(data); + + // Prevent ~ObjectWrap from calling napi_remove_wrap. + // The instance->_ref should be deleted with napi_delete_reference in + // ~Reference. + instance->_finalized = true; + + // If class overrides the basic finalizer, execute it. + if constexpr (details::HasBasicFinalizer::value) { +#ifndef NODE_API_EXPERIMENTAL_HAS_POST_FINALIZER + HandleScope scope(env); +#endif + + instance->Finalize(Napi::BasicEnv(env)); + } + + // If class overrides the (extended) finalizer, either schedule it or + // execute it immediately (depending on experimental features enabled). + if constexpr (details::HasExtendedFinalizer::value) { +#ifdef NODE_API_EXPERIMENTAL_HAS_POST_FINALIZER + // In experimental, attach via node_api_post_finalizer. + // `PostFinalizeCallback` is responsible for deleting the `T* instance`, + // after calling the user-provided finalizer. + napi_status status = + node_api_post_finalizer(env, PostFinalizeCallback, data, nullptr); + NAPI_FATAL_IF_FAILED(status, + "ObjectWrap::FinalizeCallback", + "node_api_post_finalizer failed"); +#else + // In non-experimental, this `FinalizeCallback` already executes from a + // non-basic environment. Execute the override directly. + // `PostFinalizeCallback` is responsible for deleting the `T* instance`, + // after calling the user-provided finalizer. + HandleScope scope(env); + PostFinalizeCallback(env, data, static_cast(nullptr)); +#endif + } + // If the instance does _not_ override the (extended) finalizer, delete the + // `T* instance` immediately. + else { + delete instance; + } +} + +template +inline void ObjectWrap::PostFinalizeCallback(napi_env env, + void* data, + void* /*hint*/) { T* instance = static_cast(data); instance->Finalize(Napi::Env(env)); delete instance; @@ -4561,9 +5453,12 @@ template template ::StaticSetterCallback method> inline napi_value ObjectWrap::WrappedMethod( napi_env env, napi_callback_info info) NAPI_NOEXCEPT { - return details::WrapCallback([&] { + return details::WrapCallback(env, [&] { const CallbackInfo cbInfo(env, info); - method(cbInfo, cbInfo[0]); + // MSVC requires to copy 'method' function pointer to a local variable + // before invoking it. + auto m = method; + m(cbInfo, cbInfo[0]); return nullptr; }); } @@ -4713,6 +5608,8 @@ inline Napi::Env AsyncContext::Env() const { // AsyncWorker class //////////////////////////////////////////////////////////////////////////////// +#if NAPI_HAS_THREADS + inline AsyncWorker::AsyncWorker(const Function& callback) : AsyncWorker(callback, "generic") {} @@ -4794,29 +5691,6 @@ inline void AsyncWorker::Destroy() { delete this; } -inline AsyncWorker::AsyncWorker(AsyncWorker&& other) { - _env = other._env; - other._env = nullptr; - _work = other._work; - other._work = nullptr; - _receiver = std::move(other._receiver); - _callback = std::move(other._callback); - _error = std::move(other._error); - _suppress_destruct = other._suppress_destruct; -} - -inline AsyncWorker& AsyncWorker::operator=(AsyncWorker&& other) { - _env = other._env; - other._env = nullptr; - _work = other._work; - other._work = nullptr; - _receiver = std::move(other._receiver); - _callback = std::move(other._callback); - _error = std::move(other._error); - _suppress_destruct = other._suppress_destruct; - return *this; -} - inline AsyncWorker::operator napi_async_work() const { return _work; } @@ -4880,15 +5754,15 @@ inline void AsyncWorker::OnAsyncWorkExecute(napi_env env, void* asyncworker) { // must not run any method that would cause JavaScript to run. In practice, // this means that almost any use of napi_env will be incorrect. inline void AsyncWorker::OnExecute(Napi::Env /*DO_NOT_USE*/) { -#ifdef NAPI_CPP_EXCEPTIONS +#ifdef NODE_ADDON_API_CPP_EXCEPTIONS try { Execute(); } catch (const std::exception& e) { SetError(e.what()); } -#else // NAPI_CPP_EXCEPTIONS +#else // NODE_ADDON_API_CPP_EXCEPTIONS Execute(); -#endif // NAPI_CPP_EXCEPTIONS +#endif // NODE_ADDON_API_CPP_EXCEPTIONS } inline void AsyncWorker::OnAsyncWorkComplete(napi_env env, @@ -4897,10 +5771,10 @@ inline void AsyncWorker::OnAsyncWorkComplete(napi_env env, AsyncWorker* self = static_cast(asyncworker); self->OnWorkComplete(env, status); } -inline void AsyncWorker::OnWorkComplete(Napi::Env /*env*/, napi_status status) { +inline void AsyncWorker::OnWorkComplete(Napi::Env env, napi_status status) { if (status != napi_cancelled) { HandleScope scope(_env); - details::WrapCallback([&] { + details::WrapCallback(env, [&] { if (_error.size() == 0) { OnOK(); } else { @@ -4914,7 +5788,9 @@ inline void AsyncWorker::OnWorkComplete(Napi::Env /*env*/, napi_status status) { } } -#if (NAPI_VERSION > 3 && !defined(__wasm32__)) +#endif // NAPI_HAS_THREADS + +#if (NAPI_VERSION > 3 && NAPI_HAS_THREADS) //////////////////////////////////////////////////////////////////////////////// // TypedThreadSafeFunction class //////////////////////////////////////////////////////////////////////////////// @@ -5012,19 +5888,21 @@ TypedThreadSafeFunction::New( auto* finalizeData = new details:: ThreadSafeFinalize( {data, finalizeCallback}); - napi_status status = napi_create_threadsafe_function( - env, - nullptr, - nullptr, - String::From(env, resourceName), - maxQueueSize, - initialThreadCount, - finalizeData, + auto fini = details::ThreadSafeFinalize:: - FinalizeFinalizeWrapperWithDataAndContext, - context, - CallJsInternal, - &tsfn._tsfn); + FinalizeFinalizeWrapperWithDataAndContext; + napi_status status = + napi_create_threadsafe_function(env, + nullptr, + nullptr, + String::From(env, resourceName), + maxQueueSize, + initialThreadCount, + finalizeData, + fini, + context, + CallJsInternal, + &tsfn._tsfn); if (status != napi_ok) { delete finalizeData; NAPI_THROW_IF_FAILED( @@ -5056,19 +5934,21 @@ TypedThreadSafeFunction::New( auto* finalizeData = new details:: ThreadSafeFinalize( {data, finalizeCallback}); - napi_status status = napi_create_threadsafe_function( - env, - nullptr, - resource, - String::From(env, resourceName), - maxQueueSize, - initialThreadCount, - finalizeData, + auto fini = details::ThreadSafeFinalize:: - FinalizeFinalizeWrapperWithDataAndContext, - context, - CallJsInternal, - &tsfn._tsfn); + FinalizeFinalizeWrapperWithDataAndContext; + napi_status status = + napi_create_threadsafe_function(env, + nullptr, + resource, + String::From(env, resourceName), + maxQueueSize, + initialThreadCount, + finalizeData, + fini, + context, + CallJsInternal, + &tsfn._tsfn); if (status != napi_ok) { delete finalizeData; NAPI_THROW_IF_FAILED( @@ -5172,19 +6052,21 @@ TypedThreadSafeFunction::New( auto* finalizeData = new details:: ThreadSafeFinalize( {data, finalizeCallback}); - napi_status status = napi_create_threadsafe_function( - env, - callback, - nullptr, - String::From(env, resourceName), - maxQueueSize, - initialThreadCount, - finalizeData, + auto fini = details::ThreadSafeFinalize:: - FinalizeFinalizeWrapperWithDataAndContext, - context, - CallJsInternal, - &tsfn._tsfn); + FinalizeFinalizeWrapperWithDataAndContext; + napi_status status = + napi_create_threadsafe_function(env, + callback, + nullptr, + String::From(env, resourceName), + maxQueueSize, + initialThreadCount, + finalizeData, + fini, + context, + CallJsInternal, + &tsfn._tsfn); if (status != napi_ok) { delete finalizeData; NAPI_THROW_IF_FAILED( @@ -5218,6 +6100,9 @@ TypedThreadSafeFunction::New( auto* finalizeData = new details:: ThreadSafeFinalize( {data, finalizeCallback}); + auto fini = + details::ThreadSafeFinalize:: + FinalizeFinalizeWrapperWithDataAndContext; napi_status status = napi_create_threadsafe_function( env, details::DefaultCallbackWrapper< @@ -5229,8 +6114,7 @@ TypedThreadSafeFunction::New( maxQueueSize, initialThreadCount, finalizeData, - details::ThreadSafeFinalize:: - FinalizeFinalizeWrapperWithDataAndContext, + fini, context, CallJsInternal, &tsfn._tsfn); @@ -5802,13 +6686,15 @@ inline void ThreadSafeFunction::CallJS(napi_env env, return; } - if (data != nullptr) { - auto* callbackWrapper = static_cast(data); - (*callbackWrapper)(env, Function(env, jsCallback)); - delete callbackWrapper; - } else if (jsCallback != nullptr) { - Function(env, jsCallback).Call({}); - } + details::WrapVoidCallback(env, [&]() { + if (data != nullptr) { + auto* callbackWrapper = static_cast(data); + (*callbackWrapper)(env, Function(env, jsCallback)); + delete callbackWrapper; + } else if (jsCallback != nullptr) { + Function(env, jsCallback).Call({}); + } + }); } //////////////////////////////////////////////////////////////////////////////// @@ -5882,7 +6768,11 @@ template inline napi_status AsyncProgressWorkerBase::NonBlockingCall( DataType* data) { auto tsd = new AsyncProgressWorkerBase::ThreadSafeData(this, data); - return _tsfn.NonBlockingCall(tsd, OnAsyncWorkProgress); + auto ret = _tsfn.NonBlockingCall(tsd, OnAsyncWorkProgress); + if (ret != napi_ok) { + delete tsd; + } + return ret; } template @@ -5940,7 +6830,8 @@ inline AsyncProgressWorker::AsyncProgressWorker(const Object& receiver, const Object& resource) : AsyncProgressWorkerBase(receiver, callback, resource_name, resource), _asyncdata(nullptr), - _asyncsize(0) {} + _asyncsize(0), + _signaled(false) {} #if NAPI_VERSION > 4 template @@ -5980,12 +6871,15 @@ template inline void AsyncProgressWorker::OnWorkProgress(void*) { T* data; size_t size; + bool signaled; { std::lock_guard lock(this->_mutex); data = this->_asyncdata; size = this->_asyncsize; + signaled = this->_signaled; this->_asyncdata = nullptr; this->_asyncsize = 0; + this->_signaled = false; } /** @@ -5995,7 +6889,7 @@ inline void AsyncProgressWorker::OnWorkProgress(void*) { * the deferring the signal of uv_async_t is been sent again, i.e. potential * not coalesced two calls of the TSFN callback. */ - if (data == nullptr) { + if (data == nullptr && !signaled) { return; } @@ -6014,6 +6908,7 @@ inline void AsyncProgressWorker::SendProgress_(const T* data, size_t count) { old_data = _asyncdata; _asyncdata = new_data; _asyncsize = count; + _signaled = false; } this->NonBlockingCall(nullptr); @@ -6021,13 +6916,17 @@ inline void AsyncProgressWorker::SendProgress_(const T* data, size_t count) { } template -inline void AsyncProgressWorker::Signal() const { +inline void AsyncProgressWorker::Signal() { + { + std::lock_guard lock(this->_mutex); + _signaled = true; + } this->NonBlockingCall(static_cast(nullptr)); } template inline void AsyncProgressWorker::ExecutionProgress::Signal() const { - _worker->Signal(); + this->_worker->Signal(); } template @@ -6130,7 +7029,7 @@ inline void AsyncProgressQueueWorker::SendProgress_(const T* data, template inline void AsyncProgressQueueWorker::Signal() const { - this->NonBlockingCall(nullptr); + this->SendProgress_(static_cast(nullptr), 0); } template @@ -6142,7 +7041,7 @@ inline void AsyncProgressQueueWorker::OnWorkComplete(Napi::Env env, template inline void AsyncProgressQueueWorker::ExecutionProgress::Signal() const { - _worker->Signal(); + _worker->SendProgress_(static_cast(nullptr), 0); } template @@ -6150,18 +7049,20 @@ inline void AsyncProgressQueueWorker::ExecutionProgress::Send( const T* data, size_t count) const { _worker->SendProgress_(data, count); } -#endif // NAPI_VERSION > 3 && !defined(__wasm32__) +#endif // NAPI_VERSION > 3 && NAPI_HAS_THREADS //////////////////////////////////////////////////////////////////////////////// // Memory Management class //////////////////////////////////////////////////////////////////////////////// -inline int64_t MemoryManagement::AdjustExternalMemory(Env env, +inline int64_t MemoryManagement::AdjustExternalMemory(BasicEnv env, int64_t change_in_bytes) { int64_t result; napi_status status = napi_adjust_external_memory(env, change_in_bytes, &result); - NAPI_THROW_IF_FAILED(env, status, 0); + NAPI_FATAL_IF_FAILED(status, + "MemoryManagement::AdjustExternalMemory", + "napi_adjust_external_memory"); return result; } @@ -6169,17 +7070,20 @@ inline int64_t MemoryManagement::AdjustExternalMemory(Env env, // Version Management class //////////////////////////////////////////////////////////////////////////////// -inline uint32_t VersionManagement::GetNapiVersion(Env env) { +inline uint32_t VersionManagement::GetNapiVersion(BasicEnv env) { uint32_t result; napi_status status = napi_get_version(env, &result); - NAPI_THROW_IF_FAILED(env, status, 0); + NAPI_FATAL_IF_FAILED( + status, "VersionManagement::GetNapiVersion", "napi_get_version"); return result; } -inline const napi_node_version* VersionManagement::GetNodeVersion(Env env) { +inline const napi_node_version* VersionManagement::GetNodeVersion( + BasicEnv env) { const napi_node_version* result; napi_status status = napi_get_node_version(env, &result); - NAPI_THROW_IF_FAILED(env, status, 0); + NAPI_FATAL_IF_FAILED( + status, "VersionManagement::GetNodeVersion", "napi_get_node_version"); return result; } @@ -6224,17 +7128,22 @@ inline Napi::Object Addon::DefineProperties( #if NAPI_VERSION > 2 template -Env::CleanupHook Env::AddCleanupHook(Hook hook, Arg* arg) { +Env::CleanupHook BasicEnv::AddCleanupHook(Hook hook, Arg* arg) { return CleanupHook(*this, hook, arg); } template -Env::CleanupHook Env::AddCleanupHook(Hook hook) { +Env::CleanupHook BasicEnv::AddCleanupHook(Hook hook) { return CleanupHook(*this, hook); } template -Env::CleanupHook::CleanupHook(Napi::Env env, Hook hook) +Env::CleanupHook::CleanupHook() { + data = nullptr; +} + +template +Env::CleanupHook::CleanupHook(Napi::BasicEnv env, Hook hook) : wrapper(Env::CleanupHook::Wrapper) { data = new CleanupData{std::move(hook), nullptr}; napi_status status = napi_add_env_cleanup_hook(env, wrapper, data); @@ -6245,7 +7154,9 @@ Env::CleanupHook::CleanupHook(Napi::Env env, Hook hook) } template -Env::CleanupHook::CleanupHook(Napi::Env env, Hook hook, Arg* arg) +Env::CleanupHook::CleanupHook(Napi::BasicEnv env, + Hook hook, + Arg* arg) : wrapper(Env::CleanupHook::WrapperWithArg) { data = new CleanupData{std::move(hook), arg}; napi_status status = napi_add_env_cleanup_hook(env, wrapper, data); @@ -6256,7 +7167,7 @@ Env::CleanupHook::CleanupHook(Napi::Env env, Hook hook, Arg* arg) } template -bool Env::CleanupHook::Remove(Env env) { +bool Env::CleanupHook::Remove(BasicEnv env) { napi_status status = napi_remove_env_cleanup_hook(env, wrapper, data); delete data; data = nullptr; @@ -6269,10 +7180,71 @@ bool Env::CleanupHook::IsEmpty() const { } #endif // NAPI_VERSION > 2 +#ifdef NODE_API_EXPERIMENTAL_HAS_POST_FINALIZER +template +inline void BasicEnv::PostFinalizer(FinalizerType finalizeCallback) const { + using T = void*; + details::FinalizeData* finalizeData = + new details::FinalizeData( + {std::move(finalizeCallback), nullptr}); + + napi_status status = node_api_post_finalizer( + _env, + details::FinalizeData::WrapperGCWithoutData, + static_cast(nullptr), + finalizeData); + if (status != napi_ok) { + delete finalizeData; + NAPI_FATAL_IF_FAILED( + status, "BasicEnv::PostFinalizer", "invalid arguments"); + } +} + +template +inline void BasicEnv::PostFinalizer(FinalizerType finalizeCallback, + T* data) const { + details::FinalizeData* finalizeData = + new details::FinalizeData( + {std::move(finalizeCallback), nullptr}); + + napi_status status = node_api_post_finalizer( + _env, + details::FinalizeData::WrapperGC, + data, + finalizeData); + if (status != napi_ok) { + delete finalizeData; + NAPI_FATAL_IF_FAILED( + status, "BasicEnv::PostFinalizer", "invalid arguments"); + } +} + +template +inline void BasicEnv::PostFinalizer(FinalizerType finalizeCallback, + T* data, + Hint* finalizeHint) const { + details::FinalizeData* finalizeData = + new details::FinalizeData( + {std::move(finalizeCallback), finalizeHint}); + napi_status status = node_api_post_finalizer( + _env, + details::FinalizeData::WrapperGCWithHint, + data, + finalizeData); + if (status != napi_ok) { + delete finalizeData; + NAPI_FATAL_IF_FAILED( + status, "BasicEnv::PostFinalizer", "invalid arguments"); + } +} +#endif // NODE_API_EXPERIMENTAL_HAS_POST_FINALIZER + #ifdef NAPI_CPP_CUSTOM_NAMESPACE } // namespace NAPI_CPP_CUSTOM_NAMESPACE #endif } // namespace Napi +#undef NAPI_NO_SANITIZE_VPTR + #endif // SRC_NAPI_INL_H_ diff --git a/napi.h b/napi.h index 58a0c523b..f35587aa0 100644 --- a/napi.h +++ b/napi.h @@ -1,12 +1,27 @@ #ifndef SRC_NAPI_H_ #define SRC_NAPI_H_ +#ifndef NAPI_HAS_THREADS +#if !defined(__wasm__) || (defined(__EMSCRIPTEN_PTHREADS__) || \ + (defined(__wasi__) && defined(_REENTRANT))) +#define NAPI_HAS_THREADS 1 +#else +#define NAPI_HAS_THREADS 0 +#endif +#endif + #include #include #include #include +#if NAPI_HAS_THREADS #include +#endif // NAPI_HAS_THREADS +#include #include +#include +#include +#include #include // VS2015 RTM has bugs with constexpr, so require min of VS2015 Update 3 (known @@ -26,22 +41,40 @@ static_assert(sizeof(char16_t) == sizeof(wchar_t), #define NAPI_WIDE_TEXT(x) u##x #endif +// Backwards-compatibility to handle the rename of this macro definition, in +// case they are used within userland code. +#ifdef NAPI_CPP_EXCEPTIONS +#define NODE_ADDON_API_CPP_EXCEPTIONS +#endif +#if defined(NODE_ADDON_API_CPP_EXCEPTIONS) && !defined(NAPI_CPP_EXCEPTIONS) +#define NAPI_CPP_EXCEPTIONS +#endif +#ifdef NAPI_DISABLE_CPP_EXCEPTIONS +#define NODE_ADDON_API_DISABLE_CPP_EXCEPTIONS +#endif +#if defined(NODE_ADDON_API_DISABLE_CPP_EXCEPTIONS) && \ + !defined(NAPI_DISABLE_CPP_EXCEPTIONS) +#define NAPI_DISABLE_CPP_EXCEPTIONS +#endif + // If C++ exceptions are not explicitly enabled or disabled, enable them // if exceptions were enabled in the compiler settings. -#if !defined(NAPI_CPP_EXCEPTIONS) && !defined(NAPI_DISABLE_CPP_EXCEPTIONS) +#if !defined(NODE_ADDON_API_CPP_EXCEPTIONS) && \ + !defined(NODE_ADDON_API_DISABLE_CPP_EXCEPTIONS) #if defined(_CPPUNWIND) || defined(__EXCEPTIONS) -#define NAPI_CPP_EXCEPTIONS +#define NODE_ADDON_API_CPP_EXCEPTIONS #else #error Exception support not detected. \ - Define either NAPI_CPP_EXCEPTIONS or NAPI_DISABLE_CPP_EXCEPTIONS. + Define either NODE_ADDON_API_CPP_EXCEPTIONS or NODE_ADDON_API_DISABLE_CPP_EXCEPTIONS. #endif #endif -// If C++ NAPI_CPP_EXCEPTIONS are enabled, NODE_ADDON_API_ENABLE_MAYBE should -// not be set -#if defined(NAPI_CPP_EXCEPTIONS) && defined(NODE_ADDON_API_ENABLE_MAYBE) +// If C++ NODE_ADDON_API_CPP_EXCEPTIONS are enabled, NODE_ADDON_API_ENABLE_MAYBE +// should not be set +#if defined(NODE_ADDON_API_CPP_EXCEPTIONS) && \ + defined(NODE_ADDON_API_ENABLE_MAYBE) #error NODE_ADDON_API_ENABLE_MAYBE should not be set when \ - NAPI_CPP_EXCEPTIONS is defined. + NODE_ADDON_API_CPP_EXCEPTIONS is defined. #endif #ifdef _NOEXCEPT @@ -50,7 +83,7 @@ static_assert(sizeof(char16_t) == sizeof(wchar_t), #define NAPI_NOEXCEPT noexcept #endif -#ifdef NAPI_CPP_EXCEPTIONS +#ifdef NODE_ADDON_API_CPP_EXCEPTIONS // When C++ exceptions are enabled, Errors are thrown directly. There is no need // to return anything after the throw statements. The variadic parameter is an @@ -67,7 +100,7 @@ static_assert(sizeof(char16_t) == sizeof(wchar_t), #define NAPI_THROW_IF_FAILED_VOID(env, status) \ if ((status) != napi_ok) throw Napi::Error::New(env); -#else // NAPI_CPP_EXCEPTIONS +#else // NODE_ADDON_API_CPP_EXCEPTIONS // When C++ exceptions are disabled, Errors are thrown as JavaScript exceptions, // which are pending until the callback returns to JS. The variadic parameter @@ -99,7 +132,7 @@ static_assert(sizeof(char16_t) == sizeof(wchar_t), return; \ } -#endif // NAPI_CPP_EXCEPTIONS +#endif // NODE_ADDON_API_CPP_EXCEPTIONS #ifdef NODE_ADDON_API_ENABLE_MAYBE #define NAPI_MAYBE_THROW_IF_FAILED(env, status, type) \ @@ -131,6 +164,26 @@ static_assert(sizeof(char16_t) == sizeof(wchar_t), } \ } while (0) +// Internal check helper. Be careful that the formatted message length should be +// max 255 size and null terminated. +#define NAPI_INTERNAL_CHECK(expr, location, ...) \ + do { \ + if (!(expr)) { \ + std::string msg = Napi::details::StringFormat(__VA_ARGS__); \ + Napi::Error::Fatal(location, msg.c_str()); \ + } \ + } while (0) + +#define NAPI_INTERNAL_CHECK_EQ(actual, expected, value_format, location) \ + do { \ + auto actual_value = (actual); \ + NAPI_INTERNAL_CHECK(actual_value == (expected), \ + location, \ + "Expected " #actual " to be equal to " #expected \ + ", but got " value_format ".", \ + actual_value); \ + } while (0) + #define NAPI_FATAL_IF_FAILED(status, location, message) \ NAPI_CHECK((status) == napi_ok, location, message) @@ -268,6 +321,14 @@ template using MaybeOrValue = T; #endif +#ifdef NODE_API_EXPERIMENTAL_HAS_POST_FINALIZER +using node_addon_api_basic_env = node_api_nogc_env; +using node_addon_api_basic_finalize = node_api_nogc_finalize; +#else +using node_addon_api_basic_env = napi_env; +using node_addon_api_basic_finalize = napi_finalize; +#endif + /// Environment for Node-API values and operations. /// /// All Node-API values and operations must be associated with an environment. @@ -276,17 +337,13 @@ using MaybeOrValue = T; /// Node-API operations within the callback. (Many methods infer the /// environment from the `this` instance that the method is called on.) /// -/// In the future, multiple environments per process may be supported, -/// although current implementations only support one environment per process. +/// Multiple environments may co-exist in a single process or a thread. /// /// In the V8 JavaScript engine, a Node-API environment approximately /// corresponds to an Isolate. -class Env { +class BasicEnv { private: -#if NAPI_VERSION > 2 - template - class CleanupHook; -#endif // NAPI_VERSION > 2 + node_addon_api_basic_env _env; #if NAPI_VERSION > 5 template static void DefaultFini(Env, T* data); @@ -294,22 +351,27 @@ class Env { static void DefaultFiniWithHint(Env, DataType* data, HintType* hint); #endif // NAPI_VERSION > 5 public: - Env(napi_env env); - - operator napi_env() const; - - Object Global() const; - Value Undefined() const; - Value Null() const; - - bool IsExceptionPending() const; - Error GetAndClearPendingException() const; - - MaybeOrValue RunScript(const char* utf8script) const; - MaybeOrValue RunScript(const std::string& utf8script) const; - MaybeOrValue RunScript(String script) const; + BasicEnv(node_addon_api_basic_env env); + + operator node_addon_api_basic_env() const; + + // Without these operator overloads, the error: + // + // Use of overloaded operator '==' is ambiguous (with operand types + // 'Napi::Env' and 'Napi::Env') + // + // ... occurs when comparing foo.Env() == bar.Env() or foo.Env() == nullptr + bool operator==(const BasicEnv& other) const { + return _env == other._env; + } + bool operator==(std::nullptr_t /*other*/) const { + return _env == nullptr; + } #if NAPI_VERSION > 2 + template + class CleanupHook; + template CleanupHook AddCleanupHook(Hook hook); @@ -323,7 +385,7 @@ class Env { template using Finalizer = void (*)(Env, T*); - template fini = Env::DefaultFini> + template fini = BasicEnv::DefaultFini> void SetInstanceData(T* data) const; template @@ -331,20 +393,18 @@ class Env { template fini = - Env::DefaultFiniWithHint> + BasicEnv::DefaultFiniWithHint> void SetInstanceData(DataType* data, HintType* hint) const; #endif // NAPI_VERSION > 5 - private: - napi_env _env; - #if NAPI_VERSION > 2 template class CleanupHook { public: - CleanupHook(Env env, Hook hook, Arg* arg); - CleanupHook(Env env, Hook hook); - bool Remove(Env env); + CleanupHook(); + CleanupHook(BasicEnv env, Hook hook, Arg* arg); + CleanupHook(BasicEnv env, Hook hook); + bool Remove(BasicEnv env); bool IsEmpty() const; private: @@ -357,9 +417,50 @@ class Env { Arg* arg; } * data; }; -}; #endif // NAPI_VERSION > 2 +#if NAPI_VERSION > 8 + const char* GetModuleFileName() const; +#endif // NAPI_VERSION > 8 + +#ifdef NODE_API_EXPERIMENTAL_HAS_POST_FINALIZER + // FinalizerType must implement `void operator()(Env env)`. + template + inline void PostFinalizer(FinalizerType finalizeCallback) const; + + // FinalizerType must implement `void operator()(Env env, T* data)`. + template + inline void PostFinalizer(FinalizerType finalizeCallback, T* data) const; + + // FinalizerType must implement `void operator()(Env env, T* data, + // Hint* hint)`. + template + inline void PostFinalizer(FinalizerType finalizeCallback, + T* data, + Hint* finalizeHint) const; +#endif // NODE_API_EXPERIMENTAL_HAS_POST_FINALIZER + + friend class Env; +}; + +class Env : public BasicEnv { + public: + Env(napi_env env); + + operator napi_env() const; + + Object Global() const; + Value Undefined() const; + Value Null() const; + + bool IsExceptionPending() const; + Error GetAndClearPendingException() const; + + MaybeOrValue RunScript(const char* utf8script) const; + MaybeOrValue RunScript(const std::string& utf8script) const; + MaybeOrValue RunScript(String script) const; +}; + /// A JavaScript value of unknown type. /// /// For type-specific operations, convert to one of the Value subclasses using a @@ -394,6 +495,8 @@ class Value { template static Value From(napi_env env, const T& value); + static void CheckCast(napi_env env, napi_value value); + /// Converts to a Node-API value primitive. /// /// If the instance is _empty_, this returns `nullptr`. @@ -448,15 +551,25 @@ class Value { bool IsDataView() const; ///< Tests if a value is a JavaScript data view. bool IsBuffer() const; ///< Tests if a value is a Node buffer. bool IsExternal() const; ///< Tests if a value is a pointer to external data. +#ifdef NODE_API_EXPERIMENTAL_HAS_SHAREDARRAYBUFFER + bool IsSharedArrayBuffer() const; +#endif /// Casts to another type of `Napi::Value`, when the actual type is known or /// assumed. /// /// This conversion does NOT coerce the type. Calling any methods /// inappropriate for the actual value type will throw `Napi::Error`. + /// + /// If `NODE_ADDON_API_ENABLE_TYPE_CHECK_ON_AS` is defined, this method + /// asserts that the actual type is the expected type. template T As() const; + // Unsafe Value::As(), should be avoided. + template + T UnsafeAs() const; + MaybeOrValue ToBoolean() const; ///< Coerces a value to a JavaScript boolean. MaybeOrValue ToNumber() @@ -480,6 +593,8 @@ class Boolean : public Value { bool value ///< Boolean value ); + static void CheckCast(napi_env env, napi_value value); + Boolean(); ///< Creates a new _empty_ Boolean instance. Boolean(napi_env env, napi_value value); ///< Wraps a Node-API value primitive. @@ -495,6 +610,8 @@ class Number : public Value { double value ///< Number value ); + static void CheckCast(napi_env env, napi_value value); + Number(); ///< Creates a new _empty_ Number instance. Number(napi_env env, napi_value value); ///< Wraps a Node-API value primitive. @@ -543,6 +660,8 @@ class BigInt : public Value { const uint64_t* words ///< Array of words ); + static void CheckCast(napi_env env, napi_value value); + BigInt(); ///< Creates a new _empty_ BigInt instance. BigInt(napi_env env, napi_value value); ///< Wraps a Node-API value primitive. @@ -574,6 +693,14 @@ class Date : public Value { double value ///< Number value ); + /// Creates a new Date value from a std::chrono::system_clock::time_point. + static Date New( + napi_env env, ///< Node-API environment + std::chrono::system_clock::time_point time_point ///< Time point value + ); + + static void CheckCast(napi_env env, napi_value value); + Date(); ///< Creates a new _empty_ Date instance. Date(napi_env env, napi_value value); ///< Wraps a Node-API value primitive. operator double() const; ///< Converts a Date value to double primitive @@ -585,6 +712,8 @@ class Date : public Value { /// A JavaScript string or symbol value (that can be used as a property name). class Name : public Value { public: + static void CheckCast(napi_env env, napi_value value); + Name(); ///< Creates a new _empty_ Name instance. Name(napi_env env, napi_value value); ///< Wraps a Node-API value primitive. @@ -603,6 +732,11 @@ class String : public Name { const std::u16string& value ///< UTF-16 encoded C++ string ); + /// Creates a new String value from a UTF-8 encoded C++ string view. + static String New(napi_env env, ///< Node-API environment + std::string_view value ///< UTF-8 encoded C++ string view + ); + /// Creates a new String value from a UTF-8 encoded C string. static String New( napi_env env, ///< Node-API environment @@ -642,6 +776,8 @@ class String : public Name { template static String From(napi_env env, const T& value); + static void CheckCast(napi_env env, napi_value value); + String(); ///< Creates a new _empty_ String instance. String(napi_env env, napi_value value); ///< Wraps a Node-API value primitive. @@ -656,6 +792,41 @@ class String : public Name { const; ///< Converts a String value to a UTF-16 encoded C++ string. }; +namespace details { + +// This overload set must mirror the non-template Symbol::For overloads. +struct string_convertible_probe { + static void select(const std::string&); + static void select(std::string_view); + static void select(const char*); + static void select(String); + static void select(napi_value); +}; + +template +struct has_unambiguous_string_convertible_overload : std::false_type {}; + +template +struct has_unambiguous_string_convertible_overload< + T, + std::void_t()))>> + : std::true_type {}; + +// Enable the template overload only for string-like arguments that have no +// unique best match among the non-template Symbol::For overloads. +// +// Exclude nullptr because it matches the pointer overloads equally well and +// cannot safely initialize a std::string_view. +template +using enable_if_ambiguous_string_convertible_t = + std::enable_if_t> && + std::is_convertible_v && + std::is_convertible_v && + !has_unambiguous_string_convertible_overload::value, + int>; + +} // namespace details + /// A JavaScript symbol value. class Symbol : public Name { public: @@ -674,6 +845,13 @@ class Symbol : public Name { description ///< UTF-8 encoded C++ string describing the symbol ); + /// Creates a new Symbol value with a description. + static Symbol New( + napi_env env, ///< Node-API environment + std::string_view + description ///< UTF-8 encoded C++ string view describing the symbol + ); + /// Creates a new Symbol value with a description. static Symbol New(napi_env env, ///< Node-API environment String description ///< String value describing the symbol @@ -691,6 +869,15 @@ class Symbol : public Name { // Create a symbol in the global registry, UTF-8 Encoded cpp string static MaybeOrValue For(napi_env env, const std::string& description); + // Create a symbol in the global registry, UTF-8 encoded cpp string view + static MaybeOrValue For(napi_env env, std::string_view description); + + // Resolve otherwise ambiguous string-like arguments through the + // std::string_view overload + template = 0> + static MaybeOrValue For(napi_env env, T&& description); + // Create a symbol in the global registry, C style string (null terminated) static MaybeOrValue For(napi_env env, const char* description); @@ -700,13 +887,26 @@ class Symbol : public Name { // Create a symbol in the global registry, napi_value describing the symbol static MaybeOrValue For(napi_env env, napi_value description); + static void CheckCast(napi_env env, napi_value value); + Symbol(); ///< Creates a new _empty_ Symbol instance. Symbol(napi_env env, napi_value value); ///< Wraps a Node-API value primitive. }; +class TypeTaggable : public Value { + public: +#if NAPI_VERSION >= 8 + void TypeTag(const napi_type_tag* type_tag) const; + bool CheckTypeTag(const napi_type_tag* type_tag) const; +#endif // NAPI_VERSION >= 8 + protected: + TypeTaggable(); + TypeTaggable(napi_env env, napi_value value); +}; + /// A JavaScript object value. -class Object : public Value { +class Object : public TypeTaggable { public: /// Enables property and element assignments using indexing syntax. /// @@ -733,6 +933,9 @@ class Object : public Value { template PropertyLValue& operator=(ValueType value); + /// Converts an L-value to a value. For convenience. + Value AsValue() const; + private: PropertyLValue() = delete; PropertyLValue(Object object, Key key); @@ -747,6 +950,8 @@ class Object : public Value { static Object New(napi_env env ///< Node-API environment ); + static void CheckCast(napi_env env, napi_value value); + Object(); ///< Creates a new _empty_ Object instance. Object(napi_env env, napi_value value); ///< Wraps a Node-API value primitive. @@ -949,15 +1154,18 @@ class Object : public Value { const Function& constructor ///< Constructor function ) const; + // Finalizer must implement `void operator()(Env env, T* data)`. template inline void AddFinalizer(Finalizer finalizeCallback, T* data) const; + // Finalizer must implement `void operator()(Env env, T* data, + // Hint* hint)`. template inline void AddFinalizer(Finalizer finalizeCallback, T* data, Hint* finalizeHint) const; -#ifdef NAPI_CPP_EXCEPTIONS +#ifdef NODE_ADDON_API_CPP_EXCEPTIONS class const_iterator; inline const_iterator begin() const; @@ -969,7 +1177,7 @@ class Object : public Value { inline iterator begin(); inline iterator end(); -#endif // NAPI_CPP_EXCEPTIONS +#endif // NODE_ADDON_API_CPP_EXCEPTIONS #if NAPI_VERSION >= 8 /// This operation can fail in case of Proxy.[[GetPrototypeOf]] calling into @@ -983,23 +1191,32 @@ class Object : public Value { /// https://tc39.es/ecma262/#sec-proxy-object-internal-methods-and-internal-slots-getprototypeof MaybeOrValue Seal() const; #endif // NAPI_VERSION >= 8 + + MaybeOrValue GetPrototype() const; + +#ifdef NODE_API_EXPERIMENTAL_HAS_SET_PROTOTYPE + MaybeOrValue SetPrototype(const Object& value) const; +#endif }; template -class External : public Value { +class External : public TypeTaggable { public: static External New(napi_env env, T* data); // Finalizer must implement `void operator()(Env env, T* data)`. template static External New(napi_env env, T* data, Finalizer finalizeCallback); - // Finalizer must implement `void operator()(Env env, T* data, Hint* hint)`. + // Finalizer must implement `void operator()(Env env, T* data, + // Hint* hint)`. template static External New(napi_env env, T* data, Finalizer finalizeCallback, Hint* finalizeHint); + static void CheckCast(napi_env env, napi_value value); + External(); External(napi_env env, napi_value value); @@ -1011,13 +1228,15 @@ class Array : public Object { static Array New(napi_env env); static Array New(napi_env env, size_t length); + static void CheckCast(napi_env env, napi_value value); + Array(); Array(napi_env env, napi_value value); uint32_t Length() const; }; -#ifdef NAPI_CPP_EXCEPTIONS +#ifdef NODE_ADDON_API_CPP_EXCEPTIONS class Object::const_iterator { private: enum class Type { BEGIN, END }; @@ -1064,7 +1283,22 @@ class Object::iterator { friend class Object; }; -#endif // NAPI_CPP_EXCEPTIONS +#endif // NODE_ADDON_API_CPP_EXCEPTIONS + +#ifdef NODE_API_EXPERIMENTAL_HAS_SHAREDARRAYBUFFER +class SharedArrayBuffer : public Object { + public: + SharedArrayBuffer(); + SharedArrayBuffer(napi_env env, napi_value value); + + static SharedArrayBuffer New(napi_env env, size_t byteLength); + + static void CheckCast(napi_env env, napi_value value); + + void* Data(); + size_t ByteLength(); +}; +#endif /// A JavaScript array buffer value. class ArrayBuffer : public Object { @@ -1076,6 +1310,7 @@ class ArrayBuffer : public Object { size_t byteLength ///< Length of the buffer to be allocated, in bytes ); +#ifndef NODE_API_NO_EXTERNAL_BUFFERS_ALLOWED /// Creates a new ArrayBuffer instance, using an external buffer with /// specified byte length. static ArrayBuffer New( @@ -1119,6 +1354,9 @@ class ArrayBuffer : public Object { Hint* finalizeHint ///< Hint (second parameter) to be passed to the ///< finalize callback ); +#endif // NODE_API_NO_EXTERNAL_BUFFERS_ALLOWED + + static void CheckCast(napi_env env, napi_value value); ArrayBuffer(); ///< Creates a new _empty_ ArrayBuffer instance. ArrayBuffer(napi_env env, @@ -1144,13 +1382,29 @@ class ArrayBuffer : public Object { /// } class TypedArray : public Object { public: + static void CheckCast(napi_env env, napi_value value); + TypedArray(); ///< Creates a new _empty_ TypedArray instance. TypedArray(napi_env env, napi_value value); ///< Wraps a Node-API value primitive. napi_typedarray_type TypedArrayType() const; ///< Gets the type of this typed-array. - Napi::ArrayBuffer ArrayBuffer() const; ///< Gets the backing array buffer. + + // Gets the backing `ArrayBuffer`. + // + // If this `TypedArray` is not backed by an `ArrayBuffer`, this method will + // terminate the process with a fatal error when using + // `NODE_ADDON_API_ENABLE_TYPE_CHECK_ON_AS` or exhibit undefined behavior + // otherwise. Use `Buffer()` instead to get the backing buffer without + // assuming its type. + Napi::ArrayBuffer ArrayBuffer() const; + + // Gets the backing buffer (an `ArrayBuffer` or `SharedArrayBuffer`). + // + // Use `IsArrayBuffer()` or `IsSharedArrayBuffer()` to check the type of the + // backing buffer prior to casting with `As()`. + Napi::Value Buffer() const; uint8_t ElementSize() const; ///< Gets the size in bytes of one element in the array. @@ -1215,7 +1469,7 @@ class TypedArrayOf : public TypedArray { napi_typedarray_type type = TypedArray::TypedArrayTypeForPrimitiveType() #else - napi_typedarray_type type + napi_typedarray_type type #endif ///< Type of array, if different from the default array type for the ///< template parameter T. @@ -1238,11 +1492,39 @@ class TypedArrayOf : public TypedArray { napi_typedarray_type type = TypedArray::TypedArrayTypeForPrimitiveType() #else - napi_typedarray_type type + napi_typedarray_type type +#endif + ///< Type of array, if different from the default array type for the + ///< template parameter T. + ); + +#ifdef NODE_API_EXPERIMENTAL_HAS_SHAREDARRAYBUFFER + /// Creates a new TypedArray instance over a provided SharedArrayBuffer. + /// + /// The array type parameter can normally be omitted (because it is inferred + /// from the template parameter T), except when creating a "clamped" array: + /// + /// Uint8Array::New(env, length, buffer, 0, napi_uint8_clamped_array) + static TypedArrayOf New( + napi_env env, ///< Node-API environment + size_t elementLength, ///< Length of the created array, as a number of + ///< elements + Napi::SharedArrayBuffer + arrayBuffer, ///< Backing shared array buffer instance to use + size_t bufferOffset, ///< Offset into the array buffer where the + ///< typed-array starts +#if defined(NAPI_HAS_CONSTEXPR) + napi_typedarray_type type = + TypedArray::TypedArrayTypeForPrimitiveType() +#else + napi_typedarray_type type #endif ///< Type of array, if different from the default array type for the ///< template parameter T. ); +#endif + + static void CheckCast(napi_env env, napi_value value); TypedArrayOf(); ///< Creates a new _empty_ TypedArrayOf instance. TypedArrayOf(napi_env env, @@ -1288,11 +1570,37 @@ class DataView : public Object { size_t byteOffset, size_t byteLength); +#ifdef NODE_API_EXPERIMENTAL_HAS_SHAREDARRAYBUFFER + static DataView New(napi_env env, Napi::SharedArrayBuffer arrayBuffer); + static DataView New(napi_env env, + Napi::SharedArrayBuffer arrayBuffer, + size_t byteOffset); + static DataView New(napi_env env, + Napi::SharedArrayBuffer arrayBuffer, + size_t byteOffset, + size_t byteLength); +#endif + + static void CheckCast(napi_env env, napi_value value); + DataView(); ///< Creates a new _empty_ DataView instance. DataView(napi_env env, napi_value value); ///< Wraps a Node-API value primitive. - Napi::ArrayBuffer ArrayBuffer() const; ///< Gets the backing array buffer. + // Gets the backing `ArrayBuffer`. + // + // If this `DataView` is not backed by an `ArrayBuffer`, this method will + // terminate the process with a fatal error when using + // `NODE_ADDON_API_ENABLE_TYPE_CHECK_ON_AS` or exhibit undefined behavior + // otherwise. Use `Buffer()` instead to get the backing buffer without + // assuming its type. + Napi::ArrayBuffer ArrayBuffer() const; + + // Gets the backing buffer (an `ArrayBuffer` or `SharedArrayBuffer`). + // + // Use `IsArrayBuffer()` or `IsSharedArrayBuffer()` to check the type of the + // backing buffer prior to casting with `As()`. + Napi::Value Buffer() const; size_t ByteOffset() const; ///< Gets the offset into the buffer where the array starts. size_t ByteLength() const; ///< Gets the length of the array in bytes. @@ -1324,8 +1632,8 @@ class DataView : public Object { template void WriteData(size_t byteOffset, T value) const; - void* _data; - size_t _length; + void* _data{}; + size_t _length{}; }; class Function : public Object { @@ -1368,6 +1676,8 @@ class Function : public Object { const std::string& utf8name, void* data = nullptr); + static void CheckCast(napi_env env, napi_value value); + Function(); Function(napi_env env, napi_value value); @@ -1424,13 +1734,27 @@ class Promise : public Object { napi_value _promise; }; + static void CheckCast(napi_env env, napi_value value); + + Promise(); Promise(napi_env env, napi_value value); + + MaybeOrValue Then(napi_value onFulfilled) const; + MaybeOrValue Then(napi_value onFulfilled, + napi_value onRejected) const; + MaybeOrValue Catch(napi_value onRejected) const; + + MaybeOrValue Then(const Function& onFulfilled) const; + MaybeOrValue Then(const Function& onFulfilled, + const Function& onRejected) const; + MaybeOrValue Catch(const Function& onRejected) const; }; template class Buffer : public Uint8Array { public: static Buffer New(napi_env env, size_t length); +#ifndef NODE_API_NO_EXTERNAL_BUFFERS_ALLOWED static Buffer New(napi_env env, T* data, size_t length); // Finalizer must implement `void operator()(Env env, T* data)`. @@ -1439,27 +1763,42 @@ class Buffer : public Uint8Array { T* data, size_t length, Finalizer finalizeCallback); - // Finalizer must implement `void operator()(Env env, T* data, Hint* hint)`. + // Finalizer must implement `void operator()(Env env, T* data, + // Hint* hint)`. template static Buffer New(napi_env env, T* data, size_t length, Finalizer finalizeCallback, Hint* finalizeHint); +#endif // NODE_API_NO_EXTERNAL_BUFFERS_ALLOWED + + static Buffer NewOrCopy(napi_env env, T* data, size_t length); + // Finalizer must implement `void operator()(Env env, T* data)`. + template + static Buffer NewOrCopy(napi_env env, + T* data, + size_t length, + Finalizer finalizeCallback); + // Finalizer must implement `void operator()(Env env, T* data, + // Hint* hint)`. + template + static Buffer NewOrCopy(napi_env env, + T* data, + size_t length, + Finalizer finalizeCallback, + Hint* finalizeHint); static Buffer Copy(napi_env env, const T* data, size_t length); + static void CheckCast(napi_env env, napi_value value); + Buffer(); Buffer(napi_env env, napi_value value); size_t Length() const; T* Data() const; private: - mutable size_t _length; - mutable T* _data; - - Buffer(napi_env env, napi_value value, size_t length, T* data); - void EnsureInfo() const; }; /// Holds a counted reference to a value; initially a weak reference unless @@ -1540,7 +1879,7 @@ class ObjectReference : public Reference { MaybeOrValue Set(const std::string& utf8name, napi_value value) const; MaybeOrValue Set(const std::string& utf8name, Napi::Value value) const; MaybeOrValue Set(const std::string& utf8name, - std::string& utf8value) const; + const std::string& utf8value) const; MaybeOrValue Set(const std::string& utf8name, bool boolValue) const; MaybeOrValue Set(const std::string& utf8name, double numberValue) const; @@ -1640,7 +1979,7 @@ FunctionReference Persistent(Function value); /// /// Following C++ statements will not be executed. The exception will bubble /// up as a C++ exception of type `Napi::Error`, until it is either caught -/// while still in C++, or else automatically propataged as a JavaScript +/// while still in C++, or else automatically propagated as a JavaScript /// exception when the callback returns to JavaScript. /// /// #### Example 2A - Propagating a Node-API C++ exception: @@ -1668,14 +2007,15 @@ FunctionReference Persistent(Function value); /// /// ### Handling Errors Without C++ Exceptions /// -/// If C++ exceptions are disabled (by defining `NAPI_DISABLE_CPP_EXCEPTIONS`) -/// then this class does not extend `std::exception`, and APIs in the `Napi` -/// namespace do not throw C++ exceptions when they fail. Instead, they raise -/// _pending_ JavaScript exceptions and return _empty_ `Value`s. Calling code -/// should check `Value::IsEmpty()` before attempting to use a returned value, -/// and may use methods on the `Env` class to check for, get, and clear a -/// pending JavaScript exception. If the pending exception is not cleared, it -/// will be thrown when the native callback returns to JavaScript. +/// If C++ exceptions are disabled (by defining +/// `NODE_ADDON_API_DISABLE_CPP_EXCEPTIONS`) then this class does not extend +/// `std::exception`, and APIs in the `Napi` namespace do not throw C++ +/// exceptions when they fail. Instead, they raise _pending_ JavaScript +/// exceptions and return _empty_ `Value`s. Calling code should check +/// `Value::IsEmpty()` before attempting to use a returned value, and may use +/// methods on the `Env` class to check for, get, and clear a pending JavaScript +/// exception. If the pending exception is not cleared, it will be thrown when +/// the native callback returns to JavaScript. /// /// #### Example 1B - Throwing a JS exception /// @@ -1710,10 +2050,10 @@ FunctionReference Persistent(Function value); /// Since the exception was cleared here, it will not be propagated as a /// JavaScript exception after the native callback returns. class Error : public ObjectReference -#ifdef NAPI_CPP_EXCEPTIONS +#ifdef NODE_ADDON_API_CPP_EXCEPTIONS , public std::exception -#endif // NAPI_CPP_EXCEPTIONS +#endif // NODE_ADDON_API_CPP_EXCEPTIONS { public: static Error New(napi_env env); @@ -1736,9 +2076,9 @@ class Error : public ObjectReference Object Value() const; -#ifdef NAPI_CPP_EXCEPTIONS +#ifdef NODE_ADDON_API_CPP_EXCEPTIONS const char* what() const NAPI_NOEXCEPT override; -#endif // NAPI_CPP_EXCEPTIONS +#endif // NODE_ADDON_API_CPP_EXCEPTIONS protected: /// !cond INTERNAL @@ -1777,6 +2117,17 @@ class RangeError : public Error { RangeError(napi_env env, napi_value value); }; +#if NAPI_VERSION > 8 +class SyntaxError : public Error { + public: + static SyntaxError New(napi_env env, const char* message); + static SyntaxError New(napi_env env, const std::string& message); + + SyntaxError(); + SyntaxError(napi_env env, napi_value value); +}; +#endif // NAPI_VERSION > 8 + class CallbackInfo { public: CallbackInfo(napi_env env, napi_callback_info info); @@ -1793,6 +2144,7 @@ class CallbackInfo { Value This() const; void* Data() const; void SetData(void* data); + explicit operator napi_callback_info() const; private: const size_t _staticArgCount = 6; @@ -1801,7 +2153,7 @@ class CallbackInfo { napi_value _this; size_t _argc; napi_value* _argv; - napi_value _staticArgs[6]; + napi_value _staticArgs[6]{}; napi_value* _dynamicArgs; void* _data; }; @@ -2308,6 +2660,7 @@ class ObjectWrap : public InstanceWrap, public Reference { napi_property_attributes attributes = napi_default); static Napi::Value OnCalledAsFunction(const Napi::CallbackInfo& callbackInfo); virtual void Finalize(Napi::Env env); + virtual void Finalize(BasicEnv env); private: using This = ObjectWrap; @@ -2322,7 +2675,12 @@ class ObjectWrap : public InstanceWrap, public Reference { napi_callback_info info); static napi_value StaticSetterCallbackWrapper(napi_env env, napi_callback_info info); - static void FinalizeCallback(napi_env env, void* data, void* hint); + static void FinalizeCallback(node_addon_api_basic_env env, + void* data, + void* hint); + + static void PostFinalizeCallback(napi_env env, void* data, void* hint); + static Function DefineClass(Napi::Env env, const char* utf8name, const size_t props_count, @@ -2353,6 +2711,7 @@ class ObjectWrap : public InstanceWrap, public Reference { } bool _construction_failed = true; + bool _finalized = false; }; class HandleScope { @@ -2433,13 +2792,11 @@ class AsyncContext { napi_async_context _context; }; +#if NAPI_HAS_THREADS class AsyncWorker { public: virtual ~AsyncWorker(); - // An async worker can be moved but cannot be copied. - AsyncWorker(AsyncWorker&& other); - AsyncWorker& operator=(AsyncWorker&& other); NAPI_DISALLOW_ASSIGN_COPY(AsyncWorker) operator napi_async_work() const; @@ -2498,8 +2855,9 @@ class AsyncWorker { std::string _error; bool _suppress_destruct; }; +#endif // NAPI_HAS_THREADS -#if (NAPI_VERSION > 3 && !defined(__wasm32__)) +#if (NAPI_VERSION > 3 && NAPI_HAS_THREADS) class ThreadSafeFunction { public: // This API may only be called from the main thread. @@ -2520,6 +2878,7 @@ class ThreadSafeFunction { ContextType* context); // This API may only be called from the main thread. + // Finalizer must implement `void operator()(Env env)`. template static ThreadSafeFunction New(napi_env env, const Function& callback, @@ -2529,6 +2888,8 @@ class ThreadSafeFunction { Finalizer finalizeCallback); // This API may only be called from the main thread. + // Finalizer must implement + // `void operator()(Env env, FinalizerDataType* data)`. template @@ -2541,6 +2902,8 @@ class ThreadSafeFunction { FinalizerDataType* data); // This API may only be called from the main thread. + // Finalizer must implement + // `void operator()(Env env, ContextType* context)`. template static ThreadSafeFunction New(napi_env env, const Function& callback, @@ -2551,6 +2914,8 @@ class ThreadSafeFunction { Finalizer finalizeCallback); // This API may only be called from the main thread. + // Finalizer must implement `void operator()(Env env, + // FinalizerDataType* data, ContextType* context)`. template static ThreadSafeFunction New(napi_env env, const Function& callback, @@ -2594,6 +2960,8 @@ class ThreadSafeFunction { Finalizer finalizeCallback); // This API may only be called from the main thread. + // Finalizer must implement + // `void operator()(Env env, FinalizerDataType* data)`. template @@ -2607,6 +2975,8 @@ class ThreadSafeFunction { FinalizerDataType* data); // This API may only be called from the main thread. + // Finalizer must implement + // `void operator()(Env env, ContextType* context)`. template static ThreadSafeFunction New(napi_env env, const Function& callback, @@ -2618,6 +2988,8 @@ class ThreadSafeFunction { Finalizer finalizeCallback); // This API may only be called from the main thread. + // Finalizer must implement `void operator()(Env env, + // FinalizerDataType* data, ContextType* context)`. template @@ -2777,6 +3151,8 @@ class TypedThreadSafeFunction { // This API may only be called from the main thread. // Creates a new threadsafe function with: // Callback [missing] Resource [passed] Finalizer [passed] + // Finalizer must implement `void operator()(Env env, + // FinalizerDataType* data, ContextType* context)`. template @@ -2819,6 +3195,8 @@ class TypedThreadSafeFunction { // This API may only be called from the main thread. // Creates a new threadsafe function with: // Callback [passed] Resource [missing] Finalizer [passed] + // Finalizer must implement `void operator()(Env env, + // FinalizerDataType* data, ContextType* context)`. template @@ -2835,6 +3213,8 @@ class TypedThreadSafeFunction { // This API may only be called from the main thread. // Creates a new threadsafe function with: // Callback [passed] Resource [passed] Finalizer [passed] + // Finalizer must implement `void operator()(Env env, + // FinalizerDataType* data, ContextType* context)`. template { private: void Execute() override; - void Signal() const; + void Signal(); void SendProgress_(const T* data, size_t count); std::mutex _mutex; T* _asyncdata; size_t _asyncsize; + bool _signaled; }; template @@ -3068,19 +3449,19 @@ class AsyncProgressQueueWorker void Signal() const; void SendProgress_(const T* data, size_t count); }; -#endif // NAPI_VERSION > 3 && !defined(__wasm32__) +#endif // NAPI_VERSION > 3 && NAPI_HAS_THREADS // Memory management. class MemoryManagement { public: - static int64_t AdjustExternalMemory(Env env, int64_t change_in_bytes); + static int64_t AdjustExternalMemory(BasicEnv env, int64_t change_in_bytes); }; // Version management class VersionManagement { public: - static uint32_t GetNapiVersion(Env env); - static const napi_node_version* GetNodeVersion(Env env); + static uint32_t GetNapiVersion(BasicEnv env); + static const napi_node_version* GetNodeVersion(BasicEnv env); }; #if NAPI_VERSION > 5 diff --git a/node_addon_api.gyp b/node_addon_api.gyp new file mode 100644 index 000000000..8c099262a --- /dev/null +++ b/node_addon_api.gyp @@ -0,0 +1,42 @@ +{ + 'targets': [ + { + 'target_name': 'node_addon_api', + 'type': 'none', + 'sources': [ 'napi.h', 'napi-inl.h' ], + 'direct_dependent_settings': { + 'include_dirs': [ '.' ], + 'includes': ['noexcept.gypi'], + } + }, + { + 'target_name': 'node_addon_api_except', + 'type': 'none', + 'sources': [ 'napi.h', 'napi-inl.h' ], + 'direct_dependent_settings': { + 'include_dirs': [ '.' ], + 'includes': ['except.gypi'], + } + }, + { + 'target_name': 'node_addon_api_except_all', + 'type': 'none', + 'sources': [ 'napi.h', 'napi-inl.h' ], + 'direct_dependent_settings': { + 'include_dirs': [ '.' ], + 'includes': ['except.gypi'], + 'defines': [ 'NODE_ADDON_API_CPP_EXCEPTIONS_ALL' ] + } + }, + { + 'target_name': 'node_addon_api_maybe', + 'type': 'none', + 'sources': [ 'napi.h', 'napi-inl.h' ], + 'direct_dependent_settings': { + 'include_dirs': [ '.' ], + 'includes': ['noexcept.gypi'], + 'defines': ['NODE_ADDON_API_ENABLE_MAYBE'] + } + }, + ] +} diff --git a/noexcept.gypi b/noexcept.gypi index 404a05f30..83df4ddf0 100644 --- a/noexcept.gypi +++ b/noexcept.gypi @@ -1,5 +1,5 @@ { - 'defines': [ 'NAPI_DISABLE_CPP_EXCEPTIONS' ], + 'defines': [ 'NODE_ADDON_API_DISABLE_CPP_EXCEPTIONS' ], 'cflags': [ '-fno-exceptions' ], 'cflags_cc': [ '-fno-exceptions' ], 'conditions': [ diff --git a/package.json b/package.json index ea24a5775..bc824264d 100644 --- a/package.json +++ b/package.json @@ -15,6 +15,10 @@ "name": "Alexander Floh", "url": "https://github.com/alexanderfloh" }, + { + "name": "Ammar Faizi", + "url": "https://github.com/ammarfaizi2" + }, { "name": "András Timár, Dr", "url": "https://github.com/timarandras" @@ -71,6 +75,10 @@ "name": "Daniel Bevenius", "url": "https://github.com/danbev" }, + { + "name": "Dante Calderón", + "url": "https://github.com/dantehemerson" + }, { "name": "Darshan Sen", "url": "https://github.com/RaisinTen" @@ -103,6 +111,10 @@ "name": "extremeheat", "url": "https://github.com/extremeheat" }, + { + "name": "Feng Yu", + "url": "https://github.com/F3n67u" + }, { "name": "Ferdinand Holzer", "url": "https://github.com/fholzer" @@ -147,6 +159,10 @@ "name": "Jason Ginchereau", "url": "https://github.com/jasongin" }, + { + "name": "Jenny", + "url": "https://github.com/egg-bread" + }, { "name": "Jeroen Janssen", "url": "https://github.com/japj" @@ -167,6 +183,10 @@ "name": "joshgarde", "url": "https://github.com/joshgarde" }, + { + "name": "Julian Mesa", + "url": "https://github.com/julianmesa-gitkraken" + }, { "name": "Kasumi Hanazuki", "url": "https://github.com/hanazuki" @@ -199,6 +219,10 @@ "name": "Kyle Farnung", "url": "https://github.com/kfarnung" }, + { + "name": "Kyle Kovacs", + "url": "https://github.com/nullromo" + }, { "name": "legendecas", "url": "https://github.com/legendecas" @@ -223,6 +247,10 @@ "name": "Mathias Küsel", "url": "https://github.com/mathiask88" }, + { + "name": "Mathias Stearn", + "url": "https://github.com/RedBeard0531" + }, { "name": "Matteo Collina", "url": "https://github.com/mcollina" @@ -267,6 +295,10 @@ "name": "pacop", "url": "https://github.com/pacop" }, + { + "name": "Peter Šándor", + "url": "https://github.com/petersandor" + }, { "name": "Philipp Renoth", "url": "https://github.com/DaAitch" @@ -275,6 +307,10 @@ "name": "rgerd", "url": "https://github.com/rgerd" }, + { + "name": "Richard Lau", + "url": "https://github.com/richardlau" + }, { "name": "Rolf Timmermans", "url": "https://github.com/rolftimmermans" @@ -287,6 +323,10 @@ "name": "Ryuichi Okumura", "url": "https://github.com/okuryu" }, + { + "name": "Saint Gabriel", + "url": "https://github.com/chineduG" + }, { "name": "Sampson Gao", "url": "https://github.com/sampsongao" @@ -319,6 +359,10 @@ "name": "todoroff", "url": "https://github.com/todoroff" }, + { + "name": "Toyo Li", + "url": "https://github.com/toyobayashi" + }, { "name": "Tux3", "url": "https://github.com/tux3" @@ -330,7 +374,6 @@ { "name": "Vladimir Morozov", "url": "https://github.com/vmoroz" - }, { "name": "WenheLI", @@ -355,6 +398,22 @@ { "name": "Feng Yu", "url": "https://github.com/F3n67u" + }, + { + "name": "wanlu wang", + "url": "https://github.com/wanlu" + }, + { + "name": "Caleb Hearon", + "url": "https://github.com/chearon" + }, + { + "name": "Marx", + "url": "https://github.com/MarxJiao" + }, + { + "name": "Ömer AKGÜL", + "url": "https://github.com/tuhalf" } ], "description": "Node.js API (Node-API)", @@ -362,16 +421,12 @@ "benchmark": "^2.1.4", "bindings": "^1.5.0", "clang-format": "^1.4.0", - "eslint": "^7.32.0", - "eslint-config-semistandard": "^16.0.0", - "eslint-config-standard": "^16.0.3", - "eslint-plugin-import": "^2.24.2", - "eslint-plugin-node": "^11.1.0", - "eslint-plugin-promise": "^5.1.0", - "fs-extra": "^9.0.1", - "path": "^0.12.7", + "eslint": "^9.13.0", + "fs-extra": "^11.1.1", + "neostandard": "^0.12.0", + "node-gyp": "^12.4.0", "pre-commit": "^1.2.2", - "safe-buffer": "^5.1.1" + "semver": "^7.6.0" }, "directories": {}, "gypfile": false, @@ -403,17 +458,24 @@ "scripts": { "prebenchmark": "node-gyp rebuild -C benchmark", "benchmark": "node benchmark", + "create-coverage": "npm test --coverage", + "report-coverage-html": "rm -rf coverage-html && mkdir coverage-html && gcovr -e test --merge-mode-functions merge-use-line-max --html-nested ./coverage-html/index.html test", + "report-coverage-xml": "rm -rf coverage-xml && mkdir coverage-xml && gcovr -e test --merge-mode-functions merge-use-line-max --xml -o ./coverage-xml/coverage-cxx.xml test", "pretest": "node-gyp rebuild -C test", "test": "node test", + "test:debug": "node-gyp rebuild -C test --debug && NODE_API_BUILD_CONFIG=Debug node ./test/index.js", "predev": "node-gyp rebuild -C test --debug", "dev": "node test", "predev:incremental": "node-gyp configure build -C test --debug", "dev:incremental": "node test", "doc": "doxygen doc/Doxyfile", - "lint": "node tools/eslint-format && node tools/clang-format", - "lint:fix": "node tools/clang-format --fix && node tools/eslint-format --fix" + "lint": "eslint && node tools/clang-format", + "lint:fix": "eslint --fix && node tools/clang-format --fix" }, "pre-commit": "lint", - "version": "5.0.0", - "support": true + "version": "8.9.2", + "support": true, + "engines": { + "node": "^18 || ^20 || >= 21" + } } diff --git a/release-please-config.json b/release-please-config.json new file mode 100644 index 000000000..63ce659f2 --- /dev/null +++ b/release-please-config.json @@ -0,0 +1,15 @@ +{ + "$schema": "https://raw.githubusercontent.com/googleapis/release-please/main/schemas/config.json", + "release-type": "node", + "pull-request-title-pattern": "chore: release v${version}", + "bootstrap-sha": "bc5acef9dd5298cbbcabd5c01c9590ada683951d", + "packages": { + ".": { + "include-component-in-tag": false, + "extra-files": [ + "README.md" + ], + "changelog-path": "CHANGELOG.md" + } + } +} diff --git a/test/addon.cc b/test/addon.cc index 6940edb6f..1ec9343f0 100644 --- a/test/addon.cc +++ b/test/addon.cc @@ -17,6 +17,8 @@ class TestAddon : public Napi::Addon { {InstanceMethod("decrement", &TestAddon::Decrement)}))}); } + ~TestAddon() { fprintf(stderr, "TestAddon::~TestAddon\n"); } + private: Napi::Value Increment(const Napi::CallbackInfo& info) { return Napi::Number::New(info.Env(), ++value); @@ -29,10 +31,14 @@ class TestAddon : public Napi::Addon { uint32_t value = 42; }; +Napi::Value CreateAddon(const Napi::CallbackInfo& info) { + return TestAddon::Init(info.Env(), Napi::Object::New(info.Env())); +} + } // end of anonymous namespace Napi::Object InitAddon(Napi::Env env) { - return TestAddon::Init(env, Napi::Object::New(env)); + return Napi::Function::New(env, "CreateAddon"); } #endif // (NAPI_VERSION > 5) diff --git a/test/addon.js b/test/addon.js index 78abaf6f7..c326b68e3 100644 --- a/test/addon.js +++ b/test/addon.js @@ -1,11 +1,7 @@ 'use strict'; -const assert = require('assert'); - -module.exports = require('./common').runTest(test); - -function test (binding) { - assert.strictEqual(binding.addon.increment(), 43); - assert.strictEqual(binding.addon.increment(), 44); - assert.strictEqual(binding.addon.subObject.decrement(), 43); -} +module.exports = require('./common').runTestInChildProcess({ + suite: 'addon', + testName: 'workingCode', + expectedStderr: ['TestAddon::~TestAddon'] +}); diff --git a/test/addon_build/tpl/binding.gyp b/test/addon_build/tpl/binding.gyp index aa26f1acb..5b4f9f8ad 100644 --- a/test/addon_build/tpl/binding.gyp +++ b/test/addon_build/tpl/binding.gyp @@ -4,11 +4,12 @@ " { - bindingName = bindingName.split('\\').join('\\\\'); - const child = spawn(process.execPath, [ - '-e', - `require('${bindingName}').addon_data(${hint}).verbose = true;` - ]); - const actual = []; - readline - .createInterface({ input: child.stderr }) - .on('line', (line) => { - if (expected.indexOf(line) >= 0) { - actual.push(line); - } - }) - .on('close', () => { - assert.deepStrictEqual(expected, actual); - resolve(); - }); +async function test () { + await common.runTestInChildProcess({ + suite: 'addon_data', + testName: 'workingCode' }); -} - -async function test (bindingName) { - const binding = require(bindingName).addon_data(0); - // Make sure it is possible to get/set instance data. - assert.strictEqual(binding.verbose.verbose, false); - binding.verbose = true; - assert.strictEqual(binding.verbose.verbose, true); - binding.verbose = false; - assert.strictEqual(binding.verbose.verbose, false); + await common.runTestInChildProcess({ + suite: 'addon_data', + testName: 'cleanupWithoutHint', + expectedStderr: ['addon_data: Addon::~Addon'] + }); - await testFinalizer(bindingName, 0, ['addon_data: Addon::~Addon']); - await testFinalizer(bindingName, 42, - ['addon_data: Addon::~Addon', 'hint: 42']); + await common.runTestInChildProcess({ + suite: 'addon_data', + testName: 'cleanupWithHint', + expectedStderr: ['addon_data: Addon::~Addon', 'hint: 42'] + }); } diff --git a/test/array_buffer.js b/test/array_buffer.js index d6853e50d..08547ed7e 100644 --- a/test/array_buffer.js +++ b/test/array_buffer.js @@ -58,7 +58,7 @@ function test (binding) { 'ArrayBuffer updates data pointer and length when detached', () => { // Detach the ArrayBuffer in JavaScript. - // eslint-disable-next-line no-undef + const mem = new WebAssembly.Memory({ initial: 1 }); binding.arraybuffer.checkDetachUpdatesData(mem.buffer, () => mem.grow(1)); diff --git a/test/async_context.js b/test/async_context.js index 6a4bef662..6cf0418f6 100644 --- a/test/async_context.js +++ b/test/async_context.js @@ -73,7 +73,7 @@ async function makeCallbackWithResource (binding) { { eventName: 'init', type: 'async_context_test', - triggerAsyncId: triggerAsyncId, + triggerAsyncId, resource: { foo: 'foo' } }, { eventName: 'before' }, @@ -95,7 +95,7 @@ async function makeCallbackWithoutResource (binding) { { eventName: 'init', type: 'async_context_no_res_test', - triggerAsyncId: triggerAsyncId, + triggerAsyncId, resource: { } }, { eventName: 'before' }, diff --git a/test/async_progress_queue_worker.cc b/test/async_progress_queue_worker.cc index eec3f9510..90ff881ac 100644 --- a/test/async_progress_queue_worker.cc +++ b/test/async_progress_queue_worker.cc @@ -15,6 +15,158 @@ struct ProgressData { int32_t progress; }; +class TestWorkerWithNoCb : public AsyncProgressQueueWorker { + public: + static void DoWork(const CallbackInfo& info) { + switch (info.Length()) { + case 1: { + Function cb = info[0].As(); + TestWorkerWithNoCb* worker = new TestWorkerWithNoCb(info.Env(), cb); + worker->Queue(); + } break; + + case 2: { + std::string resName = info[0].As(); + Function cb = info[1].As(); + TestWorkerWithNoCb* worker = + new TestWorkerWithNoCb(info.Env(), resName.c_str(), cb); + worker->Queue(); + } break; + + case 3: { + std::string resName = info[0].As(); + Object resObject = info[1].As(); + Function cb = info[2].As(); + TestWorkerWithNoCb* worker = + new TestWorkerWithNoCb(info.Env(), resName.c_str(), resObject, cb); + worker->Queue(); + } break; + + default: + + break; + } + } + + protected: + void Execute(const ExecutionProgress& progress) override { + ProgressData data{1}; + progress.Send(&data, 1); + } + + void OnProgress(const ProgressData*, size_t /* count */) override { + _cb.Call({}); + } + + private: + TestWorkerWithNoCb(Napi::Env env, Function cb) + : AsyncProgressQueueWorker(env) { + _cb.Reset(cb, 1); + } + TestWorkerWithNoCb(Napi::Env env, const char* resourceName, Function cb) + : AsyncProgressQueueWorker(env, resourceName) { + _cb.Reset(cb, 1); + } + TestWorkerWithNoCb(Napi::Env env, + const char* resourceName, + const Object& resourceObject, + Function cb) + : AsyncProgressQueueWorker(env, resourceName, resourceObject) { + _cb.Reset(cb, 1); + } + FunctionReference _cb; +}; + +class TestWorkerWithRecv : public AsyncProgressQueueWorker { + public: + static void DoWork(const CallbackInfo& info) { + switch (info.Length()) { + case 2: { + Object recv = info[0].As(); + Function cb = info[1].As(); + TestWorkerWithRecv* worker = new TestWorkerWithRecv(recv, cb); + worker->Queue(); + } break; + + case 3: { + Object recv = info[0].As(); + Function cb = info[1].As(); + std::string resName = info[2].As(); + TestWorkerWithRecv* worker = + new TestWorkerWithRecv(recv, cb, resName.c_str()); + worker->Queue(); + } break; + + case 4: { + Object recv = info[0].As(); + Function cb = info[1].As(); + std::string resName = info[2].As(); + Object resObject = info[3].As(); + TestWorkerWithRecv* worker = + new TestWorkerWithRecv(recv, cb, resName.c_str(), resObject); + worker->Queue(); + } break; + + default: + + break; + } + } + + protected: + void Execute(const ExecutionProgress&) override {} + + void OnProgress(const ProgressData*, size_t /* count */) override {} + + private: + TestWorkerWithRecv(const Object& recv, const Function& cb) + : AsyncProgressQueueWorker(recv, cb) {} + TestWorkerWithRecv(const Object& recv, + const Function& cb, + const char* resourceName) + : AsyncProgressQueueWorker(recv, cb, resourceName) {} + TestWorkerWithRecv(const Object& recv, + const Function& cb, + const char* resourceName, + const Object& resourceObject) + : AsyncProgressQueueWorker(recv, cb, resourceName, resourceObject) {} +}; + +class TestWorkerWithCb : public AsyncProgressQueueWorker { + public: + static void DoWork(const CallbackInfo& info) { + switch (info.Length()) { + case 1: { + Function cb = info[0].As(); + TestWorkerWithCb* worker = new TestWorkerWithCb(cb); + worker->Queue(); + } break; + + case 2: { + Function cb = info[0].As(); + std::string asyncResName = info[1].As(); + TestWorkerWithCb* worker = + new TestWorkerWithCb(cb, asyncResName.c_str()); + worker->Queue(); + } break; + + default: + + break; + } + } + + protected: + void Execute(const ExecutionProgress&) override {} + + void OnProgress(const ProgressData*, size_t /* count */) override {} + + private: + TestWorkerWithCb(Function cb) : AsyncProgressQueueWorker(cb) {} + TestWorkerWithCb(Function cb, const char* res_name) + : AsyncProgressQueueWorker(cb, res_name) {} +}; + class TestWorker : public AsyncProgressQueueWorker { public: static Napi::Value CreateWork(const CallbackInfo& info) { @@ -41,6 +193,8 @@ class TestWorker : public AsyncProgressQueueWorker { if (_times < 0) { SetError("test error"); + } else { + progress.Signal(); } ProgressData data{0}; for (int32_t idx = 0; idx < _times; idx++) { @@ -49,11 +203,18 @@ class TestWorker : public AsyncProgressQueueWorker { } } - void OnProgress(const ProgressData* data, size_t /* count */) override { + void OnProgress(const ProgressData* data, size_t count) override { Napi::Env env = Env(); + _test_case_count++; if (!_js_progress_cb.IsEmpty()) { - Number progress = Number::New(env, data->progress); - _js_progress_cb.Call(Receiver().Value(), {progress}); + if (_test_case_count == 1) { + if (count != 0) { + SetError("expect 0 count of data on 1st call"); + } + } else { + Number progress = Number::New(env, data->progress); + _js_progress_cb.Call(Receiver().Value(), {progress}); + } } } @@ -68,6 +229,7 @@ class TestWorker : public AsyncProgressQueueWorker { } int32_t _times; + size_t _test_case_count = 0; FunctionReference _js_progress_cb; }; @@ -77,6 +239,9 @@ Object InitAsyncProgressQueueWorker(Env env) { Object exports = Object::New(env); exports["createWork"] = Function::New(env, TestWorker::CreateWork); exports["queueWork"] = Function::New(env, TestWorker::QueueWork); + exports["runWorkerNoCb"] = Function::New(env, TestWorkerWithNoCb::DoWork); + exports["runWorkerWithRecv"] = Function::New(env, TestWorkerWithRecv::DoWork); + exports["runWorkerWithCb"] = Function::New(env, TestWorkerWithCb::DoWork); return exports; } diff --git a/test/async_progress_queue_worker.js b/test/async_progress_queue_worker.js index 14ac31cc2..b72a55c71 100644 --- a/test/async_progress_queue_worker.js +++ b/test/async_progress_queue_worker.js @@ -4,10 +4,144 @@ const common = require('./common'); const assert = require('assert'); module.exports = common.runTest(test); +const nodeVersion = process.versions.node.split('.')[0]; + +let asyncHooks; +function checkAsyncHooks () { + if (nodeVersion >= 8) { + if (asyncHooks === undefined) { + asyncHooks = require('async_hooks'); + } + return true; + } + return false; +} async function test ({ asyncprogressqueueworker }) { await success(asyncprogressqueueworker); await fail(asyncprogressqueueworker); + + await asyncProgressWorkerCallbackOverloads(asyncprogressqueueworker.runWorkerWithCb); + await asyncProgressWorkerRecvOverloads(asyncprogressqueueworker.runWorkerWithRecv); + await asyncProgressWorkerNoCbOverloads(asyncprogressqueueworker.runWorkerNoCb); +} + +async function asyncProgressWorkerCallbackOverloads (bindingFunction) { + bindingFunction(common.mustCall()); + if (!checkAsyncHooks()) { + return; + } + + const hooks = common.installAysncHooks('cbResources'); + + const triggerAsyncId = asyncHooks.executionAsyncId(); + await new Promise((resolve, reject) => { + bindingFunction(common.mustCall(), 'cbResources'); + hooks.then(actual => { + assert.deepStrictEqual(actual, [ + { + eventName: 'init', + type: 'cbResources', + triggerAsyncId, + resource: {} + }, + { eventName: 'before' }, + { eventName: 'after' }, + { eventName: 'destroy' } + ]); + resolve(); + }).catch((err) => reject(err)); + }); +} + +async function asyncProgressWorkerRecvOverloads (bindingFunction) { + const recvObject = { + a: 4 + }; + + function cb () { + assert.strictEqual(this.a, recvObject.a); + } + + bindingFunction(recvObject, common.mustCall(cb)); + if (!checkAsyncHooks()) { + return; + } + const asyncResources = [ + { resName: 'cbRecvResources', resObject: {} }, + { resName: 'cbRecvResourcesObject', resObject: { foo: 'bar' } } + ]; + + for (const asyncResource of asyncResources) { + const asyncResName = asyncResource.resName; + const asyncResObject = asyncResource.resObject; + + const hooks = common.installAysncHooks(asyncResource.resName); + const triggerAsyncId = asyncHooks.executionAsyncId(); + await new Promise((resolve, reject) => { + if (Object.keys(asyncResObject).length === 0) { + bindingFunction(recvObject, common.mustCall(cb), asyncResName); + } else { + bindingFunction(recvObject, common.mustCall(cb), asyncResName, asyncResObject); + } + + hooks.then(actual => { + assert.deepStrictEqual(actual, [ + { + eventName: 'init', + type: asyncResName, + triggerAsyncId, + resource: asyncResObject + }, + { eventName: 'before' }, + { eventName: 'after' }, + { eventName: 'destroy' } + ]); + resolve(); + }).catch((err) => reject(err)); + }); + } +} + +async function asyncProgressWorkerNoCbOverloads (bindingFunction) { + bindingFunction(common.mustCall()); + if (!checkAsyncHooks()) { + return; + } + const asyncResources = [ + { resName: 'noCbResources', resObject: {} }, + { resName: 'noCbResourcesObject', resObject: { foo: 'bar' } } + ]; + + for (const asyncResource of asyncResources) { + const asyncResName = asyncResource.resName; + const asyncResObject = asyncResource.resObject; + + const hooks = common.installAysncHooks(asyncResource.resName); + const triggerAsyncId = asyncHooks.executionAsyncId(); + await new Promise((resolve, reject) => { + if (Object.keys(asyncResObject).length === 0) { + bindingFunction(asyncResName, common.mustCall(() => {})); + } else { + bindingFunction(asyncResName, asyncResObject, common.mustCall(() => {})); + } + + hooks.then(actual => { + assert.deepStrictEqual(actual, [ + { + eventName: 'init', + type: asyncResName, + triggerAsyncId, + resource: asyncResObject + }, + { eventName: 'before' }, + { eventName: 'after' }, + { eventName: 'destroy' } + ]); + resolve(); + }).catch((err) => reject(err)); + }); + } } function success (binding) { diff --git a/test/async_progress_worker.cc b/test/async_progress_worker.cc index 36087e7ca..17aaef3e5 100644 --- a/test/async_progress_worker.cc +++ b/test/async_progress_worker.cc @@ -2,6 +2,7 @@ #include #include +#include #include #include @@ -15,6 +16,157 @@ struct ProgressData { size_t progress; }; +class TestWorkerWithNoCb : public AsyncProgressWorker { + public: + static void DoWork(const CallbackInfo& info) { + switch (info.Length()) { + case 1: { + Function cb = info[0].As(); + TestWorkerWithNoCb* worker = new TestWorkerWithNoCb(info.Env(), cb); + worker->Queue(); + } break; + + case 2: { + std::string resName = info[0].As(); + Function cb = info[1].As(); + TestWorkerWithNoCb* worker = + new TestWorkerWithNoCb(info.Env(), resName.c_str(), cb); + worker->Queue(); + } break; + + case 3: { + std::string resName = info[0].As(); + Object resObject = info[1].As(); + Function cb = info[2].As(); + TestWorkerWithNoCb* worker = + new TestWorkerWithNoCb(info.Env(), resName.c_str(), resObject, cb); + worker->Queue(); + } break; + + default: + + break; + } + } + + protected: + void Execute(const ExecutionProgress& progress) override { + ProgressData data{1}; + progress.Send(&data, 1); + } + + void OnProgress(const ProgressData*, size_t /* count */) override { + _cb.Call({}); + } + + private: + TestWorkerWithNoCb(Napi::Env env, Function cb) : AsyncProgressWorker(env) { + _cb.Reset(cb, 1); + } + TestWorkerWithNoCb(Napi::Env env, const char* resourceName, Function cb) + : AsyncProgressWorker(env, resourceName) { + _cb.Reset(cb, 1); + } + TestWorkerWithNoCb(Napi::Env env, + const char* resourceName, + const Object& resourceObject, + Function cb) + : AsyncProgressWorker(env, resourceName, resourceObject) { + _cb.Reset(cb, 1); + } + FunctionReference _cb; +}; + +class TestWorkerWithRecv : public AsyncProgressWorker { + public: + static void DoWork(const CallbackInfo& info) { + switch (info.Length()) { + case 2: { + Object recv = info[0].As(); + Function cb = info[1].As(); + TestWorkerWithRecv* worker = new TestWorkerWithRecv(recv, cb); + worker->Queue(); + } break; + + case 3: { + Object recv = info[0].As(); + Function cb = info[1].As(); + std::string resName = info[2].As(); + TestWorkerWithRecv* worker = + new TestWorkerWithRecv(recv, cb, resName.c_str()); + worker->Queue(); + } break; + + case 4: { + Object recv = info[0].As(); + Function cb = info[1].As(); + std::string resName = info[2].As(); + Object resObject = info[3].As(); + TestWorkerWithRecv* worker = + new TestWorkerWithRecv(recv, cb, resName.c_str(), resObject); + worker->Queue(); + } break; + + default: + + break; + } + } + + protected: + void Execute(const ExecutionProgress&) override {} + + void OnProgress(const ProgressData*, size_t /* count */) override {} + + private: + TestWorkerWithRecv(const Object& recv, const Function& cb) + : AsyncProgressWorker(recv, cb) {} + TestWorkerWithRecv(const Object& recv, + const Function& cb, + const char* resourceName) + : AsyncProgressWorker(recv, cb, resourceName) {} + TestWorkerWithRecv(const Object& recv, + const Function& cb, + const char* resourceName, + const Object& resourceObject) + : AsyncProgressWorker(recv, cb, resourceName, resourceObject) {} +}; + +class TestWorkerWithCb : public AsyncProgressWorker { + public: + static void DoWork(const CallbackInfo& info) { + switch (info.Length()) { + case 1: { + Function cb = info[0].As(); + TestWorkerWithCb* worker = new TestWorkerWithCb(cb); + worker->Queue(); + } break; + + case 2: { + Function cb = info[0].As(); + std::string asyncResName = info[1].As(); + TestWorkerWithCb* worker = + new TestWorkerWithCb(cb, asyncResName.c_str()); + worker->Queue(); + } break; + + default: + + break; + } + } + + protected: + void Execute(const ExecutionProgress&) override {} + + void OnProgress(const ProgressData*, size_t /* count */) override {} + + private: + TestWorkerWithCb(Function cb) : AsyncProgressWorker(cb) {} + TestWorkerWithCb(Function cb, const char* res_name) + : AsyncProgressWorker(cb, res_name) {} +}; + class TestWorker : public AsyncProgressWorker { public: static void DoWork(const CallbackInfo& info) { @@ -34,11 +186,16 @@ class TestWorker : public AsyncProgressWorker { SetError("test error"); } ProgressData data{0}; - std::unique_lock lock(_cvm); + for (int32_t idx = 0; idx < _times; idx++) { data.progress = idx; progress.Send(&data, 1); - _cv.wait(lock); + + { + std::unique_lock lk(_cvm); + _cv.wait(lk, [this] { return dataSent; }); + dataSent = false; + } } } @@ -48,7 +205,12 @@ class TestWorker : public AsyncProgressWorker { Number progress = Number::New(env, data->progress); _progress.MakeCallback(Receiver().Value(), {progress}); } - _cv.notify_one(); + + { + std::lock_guard lk(_cvm); + dataSent = true; + _cv.notify_one(); + } } private: @@ -59,6 +221,8 @@ class TestWorker : public AsyncProgressWorker { : AsyncProgressWorker(cb, resource_name, resource) { _progress.Reset(progress, 1); } + + bool dataSent = false; std::condition_variable _cv; std::mutex _cvm; int32_t _times; @@ -78,10 +242,17 @@ class MalignWorker : public AsyncProgressWorker { protected: void Execute(const ExecutionProgress& progress) override { - std::unique_lock lock(_cvm); - // Testing a nullptr send is acceptable. - progress.Send(nullptr, 0); - _cv.wait(lock); + { + std::unique_lock lock(_cvm); + // Testing a nullptr send is acceptable. + progress.Send(nullptr, 0); + _cv.wait(lock, [this] { return _test_case_count == 1; }); + } + { + std::unique_lock lock(_cvm); + progress.Signal(); + _cv.wait(lock, [this] { return _test_case_count == 2; }); + } // Testing busy looping on send doesn't trigger unexpected empty data // OnProgress call. for (size_t i = 0; i < 1000000; i++) { @@ -92,16 +263,21 @@ class MalignWorker : public AsyncProgressWorker { void OnProgress(const ProgressData* /* data */, size_t count) override { Napi::Env env = Env(); - _test_case_count++; + { + std::lock_guard lock(_cvm); + _test_case_count++; + } bool error = false; Napi::String reason = Napi::String::New(env, "No error"); - if (_test_case_count == 1 && count != 0) { + if (_test_case_count <= 2 && count != 0) { error = true; - reason = Napi::String::New(env, "expect 0 count of data on 1st call"); + reason = + Napi::String::New(env, "expect 0 count of data on 1st and 2nd call"); } - if (_test_case_count > 1 && count != 1) { + if (_test_case_count > 2 && count != 1) { error = true; - reason = Napi::String::New(env, "expect 1 count of data on non-1st call"); + reason = Napi::String::New( + env, "expect 1 count of data on non-1st and non-2nd call"); } _progress.MakeCallback(Receiver().Value(), {Napi::Boolean::New(env, error), reason}); @@ -122,12 +298,59 @@ class MalignWorker : public AsyncProgressWorker { std::mutex _cvm; FunctionReference _progress; }; + +// Calling a Signal after a SendProgress should not clear progress data +class SignalAfterProgressTestWorker : public AsyncProgressWorker { + public: + static void DoWork(const CallbackInfo& info) { + Function cb = info[0].As(); + Function progress = info[1].As(); + + SignalAfterProgressTestWorker* worker = new SignalAfterProgressTestWorker( + cb, progress, "TestResource", Object::New(info.Env())); + worker->Queue(); + } + + protected: + void Execute(const ExecutionProgress& progress) override { + ProgressData data{0}; + progress.Send(&data, 1); + progress.Signal(); + } + + void OnProgress(const ProgressData* /* data */, size_t count) override { + Napi::Env env = Env(); + bool error = false; + Napi::String reason = Napi::String::New(env, "No error"); + if (count != 1) { + error = true; + reason = Napi::String::New(env, "expect 1 count of data"); + } + _progress.MakeCallback(Receiver().Value(), + {Napi::Boolean::New(env, error), reason}); + } + + private: + SignalAfterProgressTestWorker(Function cb, + Function progress, + const char* resource_name, + const Object& resource) + : AsyncProgressWorker(cb, resource_name, resource) { + _progress.Reset(progress, 1); + } + FunctionReference _progress; +}; } // namespace Object InitAsyncProgressWorker(Env env) { Object exports = Object::New(env); exports["doWork"] = Function::New(env, TestWorker::DoWork); exports["doMalignTest"] = Function::New(env, MalignWorker::DoWork); + exports["doSignalAfterProgressTest"] = + Function::New(env, SignalAfterProgressTestWorker::DoWork); + exports["runWorkerNoCb"] = Function::New(env, TestWorkerWithNoCb::DoWork); + exports["runWorkerWithRecv"] = Function::New(env, TestWorkerWithRecv::DoWork); + exports["runWorkerWithCb"] = Function::New(env, TestWorkerWithCb::DoWork); return exports; } diff --git a/test/async_progress_worker.js b/test/async_progress_worker.js index 5e9940516..d96ab64b8 100644 --- a/test/async_progress_worker.js +++ b/test/async_progress_worker.js @@ -4,11 +4,146 @@ const common = require('./common'); const assert = require('assert'); module.exports = common.runTest(test); +const nodeVersion = process.versions.node.split('.')[0]; + +let asyncHooks; +function checkAsyncHooks () { + if (nodeVersion >= 8) { + if (asyncHooks === undefined) { + asyncHooks = require('async_hooks'); + } + return true; + } + return false; +} async function test ({ asyncprogressworker }) { await success(asyncprogressworker); await fail(asyncprogressworker); - await malignTest(asyncprogressworker); + await signalTest(asyncprogressworker.doMalignTest); + await signalTest(asyncprogressworker.doSignalAfterProgressTest); + + await asyncProgressWorkerCallbackOverloads(asyncprogressworker.runWorkerWithCb); + await asyncProgressWorkerRecvOverloads(asyncprogressworker.runWorkerWithRecv); + await asyncProgressWorkerNoCbOverloads(asyncprogressworker.runWorkerNoCb); +} + +async function asyncProgressWorkerCallbackOverloads (bindingFunction) { + bindingFunction(common.mustCall()); + if (!checkAsyncHooks()) { + return; + } + + const hooks = common.installAysncHooks('cbResources'); + + const triggerAsyncId = asyncHooks.executionAsyncId(); + await new Promise((resolve, reject) => { + bindingFunction(common.mustCall(), 'cbResources'); + hooks.then(actual => { + assert.deepStrictEqual(actual, [ + { + eventName: 'init', + type: 'cbResources', + triggerAsyncId, + resource: {} + }, + { eventName: 'before' }, + { eventName: 'after' }, + { eventName: 'destroy' } + ]); + }).catch(common.mustNotCall()); + resolve(); + }); +} + +async function asyncProgressWorkerRecvOverloads (bindingFunction) { + const recvObject = { + a: 4 + }; + + function cb () { + assert.strictEqual(this.a, recvObject.a); + } + + bindingFunction(recvObject, common.mustCall(cb)); + if (!checkAsyncHooks()) { + return; + } + const asyncResources = [ + { resName: 'cbRecvResources', resObject: {} }, + { resName: 'cbRecvResourcesObject', resObject: { foo: 'bar' } } + ]; + + for (const asyncResource of asyncResources) { + const asyncResName = asyncResource.resName; + const asyncResObject = asyncResource.resObject; + + const hooks = common.installAysncHooks(asyncResource.resName); + const triggerAsyncId = asyncHooks.executionAsyncId(); + await new Promise((resolve, reject) => { + if (Object.keys(asyncResObject).length === 0) { + bindingFunction(recvObject, common.mustCall(cb), asyncResName); + } else { + bindingFunction(recvObject, common.mustCall(cb), asyncResName, asyncResObject); + } + + hooks.then(actual => { + assert.deepStrictEqual(actual, [ + { + eventName: 'init', + type: asyncResName, + triggerAsyncId, + resource: asyncResObject + }, + { eventName: 'before' }, + { eventName: 'after' }, + { eventName: 'destroy' } + ]); + }).catch(common.mustNotCall()); + resolve(); + }); + } +} + +async function asyncProgressWorkerNoCbOverloads (bindingFunction) { + bindingFunction(common.mustCall(() => {})); + if (!checkAsyncHooks()) { + return; + } + const asyncResources = [ + { resName: 'noCbResources', resObject: {} }, + { resName: 'noCbResourcesObject', resObject: { foo: 'bar' } } + ]; + + for (const asyncResource of asyncResources) { + const asyncResName = asyncResource.resName; + const asyncResObject = asyncResource.resObject; + + const hooks = common.installAysncHooks(asyncResource.resName); + const triggerAsyncId = asyncHooks.executionAsyncId(); + await new Promise((resolve, reject) => { + if (Object.keys(asyncResObject).length === 0) { + bindingFunction(asyncResName, common.mustCall(() => {})); + } else { + bindingFunction(asyncResName, asyncResObject, common.mustCall(() => {})); + } + + hooks.then(actual => { + assert.deepStrictEqual(actual, [ + { + eventName: 'init', + type: asyncResName, + triggerAsyncId, + resource: asyncResObject + }, + { eventName: 'before' }, + { eventName: 'after' }, + { eventName: 'destroy' } + ]); + }).catch(common.mustNotCall()); + resolve(); + }); + } } function success (binding) { @@ -44,9 +179,9 @@ function fail (binding) { }); } -function malignTest (binding) { +function signalTest (bindingFunction) { return new Promise((resolve, reject) => { - binding.doMalignTest( + bindingFunction( common.mustCall((err) => { if (err) { return reject(err); @@ -54,7 +189,11 @@ function malignTest (binding) { resolve(); }), common.mustCallAtLeast((error, reason) => { - assert(!error, reason); + try { + assert(!error, reason); + } catch (e) { + reject(e); + } }, 1) ); }); diff --git a/test/async_worker.cc b/test/async_worker.cc index 426b4e8cf..34044e9c8 100644 --- a/test/async_worker.cc +++ b/test/async_worker.cc @@ -7,6 +7,77 @@ using namespace Napi; +class TestWorkerWithUserDefRecv : public AsyncWorker { + public: + static void DoWork(const CallbackInfo& info) { + Object recv = info[0].As(); + Function cb = info[1].As(); + + TestWorkerWithUserDefRecv* worker = new TestWorkerWithUserDefRecv(recv, cb); + worker->Queue(); + } + + static void DoWorkWithAsyncRes(const CallbackInfo& info) { + Object recv = info[0].As(); + Function cb = info[1].As(); + Value resource = info[2]; + + TestWorkerWithUserDefRecv* worker = nullptr; + if (resource == info.Env().Null()) { + worker = new TestWorkerWithUserDefRecv(recv, cb, "TestResource"); + } else { + worker = new TestWorkerWithUserDefRecv( + recv, cb, "TestResource", resource.As()); + } + + worker->Queue(); + } + + protected: + void Execute() override {} + + private: + TestWorkerWithUserDefRecv(const Object& recv, const Function& cb) + : AsyncWorker(recv, cb) {} + TestWorkerWithUserDefRecv(const Object& recv, + const Function& cb, + const char* resource_name) + : AsyncWorker(recv, cb, resource_name) {} + TestWorkerWithUserDefRecv(const Object& recv, + const Function& cb, + const char* resource_name, + const Object& resource) + : AsyncWorker(recv, cb, resource_name, resource) {} +}; + +// Using default std::allocator impl, but assuming user can define their own +// allocate/deallocate methods +class CustomAllocWorker : public AsyncWorker { + using Allocator = std::allocator; + + public: + CustomAllocWorker(Function& cb) : AsyncWorker(cb){}; + static void DoWork(const CallbackInfo& info) { + Function cb = info[0].As(); + Allocator allocator; + CustomAllocWorker* newWorker = allocator.allocate(1); + std::allocator_traits::construct(allocator, newWorker, cb); + newWorker->Queue(); + } + + protected: + void Execute() override {} + void Destroy() override { + assert(this->_secretVal == 24); + Allocator allocator; + std::allocator_traits::destroy(allocator, this); + allocator.deallocate(this, 1); + } + + private: + int _secretVal = 24; +}; + class TestWorker : public AsyncWorker { public: static void DoWork(const CallbackInfo& info) { @@ -15,7 +86,13 @@ class TestWorker : public AsyncWorker { Function cb = info[2].As(); Value data = info[3]; - TestWorker* worker = new TestWorker(cb, "TestResource", resource); + TestWorker* worker = nullptr; + if (resource == info.Env().Null()) { + worker = new TestWorker(cb, "TestResource"); + } else { + worker = new TestWorker(cb, "TestResource", resource); + } + worker->Receiver().Set("data", data); worker->_succeed = succeed; worker->Queue(); @@ -31,7 +108,9 @@ class TestWorker : public AsyncWorker { private: TestWorker(Function cb, const char* resource_name, const Object& resource) : AsyncWorker(cb, resource_name, resource) {} - bool _succeed; + TestWorker(Function cb, const char* resource_name) + : AsyncWorker(cb, resource_name) {} + bool _succeed{}; }; class TestWorkerWithResult : public AsyncWorker { @@ -66,18 +145,31 @@ class TestWorkerWithResult : public AsyncWorker { const char* resource_name, const Object& resource) : AsyncWorker(cb, resource_name, resource) {} - bool _succeed; + bool _succeed{}; }; class TestWorkerNoCallback : public AsyncWorker { public: static Value DoWork(const CallbackInfo& info) { + bool succeed = info[0].As(); + + TestWorkerNoCallback* worker = new TestWorkerNoCallback(info.Env()); + worker->_succeed = succeed; + worker->Queue(); + return worker->_deferred.Promise(); + } + + static Value DoWorkWithAsyncRes(const CallbackInfo& info) { napi_env env = info.Env(); bool succeed = info[0].As(); Object resource = info[1].As(); - TestWorkerNoCallback* worker = - new TestWorkerNoCallback(env, "TestResource", resource); + TestWorkerNoCallback* worker = nullptr; + if (resource == info.Env().Null()) { + worker = new TestWorkerNoCallback(env, "TestResource"); + } else { + worker = new TestWorkerNoCallback(env, "TestResource", resource); + } worker->_succeed = succeed; worker->Queue(); return worker->_deferred.Promise(); @@ -91,13 +183,20 @@ class TestWorkerNoCallback : public AsyncWorker { } private: + TestWorkerNoCallback(Napi::Env env) + : AsyncWorker(env), _deferred(Napi::Promise::Deferred::New(env)) {} + + TestWorkerNoCallback(napi_env env, const char* resource_name) + : AsyncWorker(env, resource_name), + _deferred(Napi::Promise::Deferred::New(env)) {} + TestWorkerNoCallback(napi_env env, const char* resource_name, const Object& resource) : AsyncWorker(env, resource_name, resource), _deferred(Napi::Promise::Deferred::New(env)) {} Promise::Deferred _deferred; - bool _succeed; + bool _succeed{}; }; class EchoWorker : public AsyncWorker { @@ -152,7 +251,7 @@ class FailCancelWorker : public AsyncWorker { #ifdef NAPI_CPP_EXCEPTIONS try { cancelWorker->Cancel(); - } catch (Napi::Error& e) { + } catch (Napi::Error&) { Napi::Error::New(info.Env(), "Unable to cancel async worker tasks") .ThrowAsJavaScriptException(); } @@ -193,7 +292,7 @@ class CancelWorker : public AsyncWorker { #ifdef NAPI_CPP_EXCEPTIONS try { cancelWorker->Cancel(); - } catch (Napi::Error& e) { + } catch (Napi::Error&) { Napi::Error::New(info.Env(), "Unable to cancel async worker tasks") .ThrowAsJavaScriptException(); } @@ -222,7 +321,12 @@ class CancelWorker : public AsyncWorker { Object InitAsyncWorker(Env env) { Object exports = Object::New(env); + exports["doWorkRecv"] = Function::New(env, TestWorkerWithUserDefRecv::DoWork); + exports["doWithRecvAsyncRes"] = + Function::New(env, TestWorkerWithUserDefRecv::DoWorkWithAsyncRes); exports["doWork"] = Function::New(env, TestWorker::DoWork); + exports["doWorkAsyncResNoCallback"] = + Function::New(env, TestWorkerNoCallback::DoWorkWithAsyncRes); exports["doWorkNoCallback"] = Function::New(env, TestWorkerNoCallback::DoWork); exports["doWorkWithResult"] = @@ -231,5 +335,7 @@ Object InitAsyncWorker(Env env) { exports["expectCancelToFail"] = Function::New(env, FailCancelWorker::DoCancel); + exports["expectCustomAllocWorkerToDealloc"] = + Function::New(env, CustomAllocWorker::DoWork); return exports; } diff --git a/test/async_worker.js b/test/async_worker.js index 2f0274026..16e2a8e96 100644 --- a/test/async_worker.js +++ b/test/async_worker.js @@ -76,8 +76,20 @@ async function test (binding) { assert.equal(taskFailed, true, 'We expect task cancellation to fail'); if (!checkAsyncHooks()) { + binding.asyncworker.expectCustomAllocWorkerToDealloc(() => {}); + + await new Promise((resolve) => { + const obj = { data: 'test data' }; + binding.asyncworker.doWorkRecv(obj, function (e) { + assert.strictEqual(typeof e, 'undefined'); + assert.strictEqual(typeof this, 'object'); + assert.strictEqual(this.data, 'test data'); + resolve(); + }); + }); + await new Promise((resolve) => { - binding.asyncworker.doWork(true, {}, function (e) { + binding.asyncworker.doWork(true, null, function (e) { assert.strictEqual(typeof e, 'undefined'); assert.strictEqual(typeof this, 'object'); assert.strictEqual(this.data, 'test data'); @@ -109,6 +121,62 @@ async function test (binding) { return; } + { + const hooks = installAsyncHooksForTest(); + const triggerAsyncId = asyncHooks.executionAsyncId(); + await new Promise((resolve) => { + const recvObj = { data: 'test data' }; + binding.asyncworker.doWithRecvAsyncRes(recvObj, function (e) { + assert.strictEqual(typeof e, 'undefined'); + assert.strictEqual(typeof this, 'object'); + assert.strictEqual(this.data, 'test data'); + resolve(); + }, { foo: 'fooBar' }); + }); + + await hooks.then(actual => { + assert.deepStrictEqual(actual, [ + { + eventName: 'init', + type: 'TestResource', + triggerAsyncId, + resource: { foo: 'fooBar' } + }, + { eventName: 'before' }, + { eventName: 'after' }, + { eventName: 'destroy' } + ]); + }).catch(common.mustNotCall()); + } + + { + const hooks = installAsyncHooksForTest(); + const triggerAsyncId = asyncHooks.executionAsyncId(); + await new Promise((resolve) => { + const recvObj = { data: 'test data' }; + binding.asyncworker.doWithRecvAsyncRes(recvObj, function (e) { + assert.strictEqual(typeof e, 'undefined'); + assert.strictEqual(typeof this, 'object'); + assert.strictEqual(this.data, 'test data'); + resolve(); + }, null); + }); + + await hooks.then(actual => { + assert.deepStrictEqual(actual, [ + { + eventName: 'init', + type: 'TestResource', + triggerAsyncId, + resource: { } + }, + { eventName: 'before' }, + { eventName: 'after' }, + { eventName: 'destroy' } + ]); + }).catch(common.mustNotCall()); + } + { const hooks = installAsyncHooksForTest(); const triggerAsyncId = asyncHooks.executionAsyncId(); @@ -126,7 +194,7 @@ async function test (binding) { { eventName: 'init', type: 'TestResource', - triggerAsyncId: triggerAsyncId, + triggerAsyncId, resource: { foo: 'foo' } }, { eventName: 'before' }, @@ -156,7 +224,7 @@ async function test (binding) { { eventName: 'init', type: 'TestResource', - triggerAsyncId: triggerAsyncId, + triggerAsyncId, resource: { foo: 'foo' } }, { eventName: 'before' }, @@ -184,7 +252,7 @@ async function test (binding) { { eventName: 'init', type: 'TestResource', - triggerAsyncId: triggerAsyncId, + triggerAsyncId, resource: { foo: 'foo' } }, { eventName: 'before' }, diff --git a/test/async_worker_nocallback.js b/test/async_worker_nocallback.js index 8e357772f..2f848c4e9 100644 --- a/test/async_worker_nocallback.js +++ b/test/async_worker_nocallback.js @@ -5,9 +5,15 @@ const common = require('./common'); module.exports = common.runTest(test); async function test (binding) { - await binding.asyncworker.doWorkNoCallback(true, {}) + await binding.asyncworker.doWorkAsyncResNoCallback(true, {}) .then(common.mustCall()).catch(common.mustNotCall()); - await binding.asyncworker.doWorkNoCallback(false, {}) + await binding.asyncworker.doWorkAsyncResNoCallback(false, {}) + .then(common.mustNotCall()).catch(common.mustCall()); + + await binding.asyncworker.doWorkNoCallback(false) + .then(common.mustNotCall()).catch(common.mustCall()); + + await binding.asyncworker.doWorkNoCallback(true) .then(common.mustNotCall()).catch(common.mustCall()); } diff --git a/test/basic_types/value.cc b/test/basic_types/value.cc index 0d19726bb..7ec3b7e04 100644 --- a/test/basic_types/value.cc +++ b/test/basic_types/value.cc @@ -128,6 +128,11 @@ static Value ToObject(const CallbackInfo& info) { return MaybeUnwrap(info[0].ToObject()); } +static Value AccessProp(const CallbackInfo& info) { + Object obj = MaybeUnwrap(info[0].ToObject()); + return obj[info[1]].AsValue(); +} + Object InitBasicTypesValue(Env env) { Object exports = Object::New(env); @@ -150,6 +155,7 @@ Object InitBasicTypesValue(Env env) { exports["toNumber"] = Function::New(env, ToNumber); exports["toString"] = Function::New(env, ToString); exports["toObject"] = Function::New(env, ToObject); + exports["accessProp"] = Function::New(env, AccessProp); exports["strictlyEquals"] = Function::New(env, StrictlyEquals); exports["strictlyEqualsOverload"] = Function::New(env, StrictEqualsOverload); diff --git a/test/basic_types/value.js b/test/basic_types/value.js index 173bcc40a..adf73d39d 100644 --- a/test/basic_types/value.js +++ b/test/basic_types/value.js @@ -117,6 +117,21 @@ function test (binding) { assert(value.assertNonEmptyReturnValOnCast()); } + function accessPropTest (value) { + const testObject = { key: '123' }; + const testSymbol = Symbol('123'); + const testNumber = 123; + const destObj = { + testObject, + testSymbol, + [testNumber]: testNumber + }; + assert.strictEqual(value.accessProp(destObj, 'testObject'), testObject); + assert.strictEqual(value.accessProp(destObj, 'testSymbol'), testSymbol); + assert.strictEqual(value.accessProp(destObj, testNumber), testNumber); + assert.strictEqual(value.accessProp(destObj, 'invalidKey'), undefined); + } + const value = binding.basic_types_value; assertValueStrictlyEqual(value); @@ -153,4 +168,6 @@ function test (binding) { assert.strictEqual(value.toString(null), 'null'); typeConverterTest(value.toObject, Object); + + accessPropTest(value); } diff --git a/test/bigint.cc b/test/bigint.cc index 9032e4aae..4faccddfb 100644 --- a/test/bigint.cc +++ b/test/bigint.cc @@ -1,6 +1,5 @@ #if (NAPI_VERSION > 5) -#define NAPI_EXPERIMENTAL #include "napi.h" #include "test_helper.h" diff --git a/test/binding.cc b/test/binding.cc index b3d9265d4..fa651cc13 100644 --- a/test/binding.cc +++ b/test/binding.cc @@ -22,12 +22,14 @@ Object InitBasicTypesValue(Env env); Object InitBigInt(Env env); #endif Object InitBuffer(Env env); +Object InitBufferNoExternal(Env env); #if (NAPI_VERSION > 2) Object InitCallbackScope(Env env); #endif #if (NAPI_VERSION > 4) Object InitDate(Env env); #endif +Object InitCallbackInfo(Env env); Object InitDataView(Env env); Object InitDataViewReadWrite(Env env); Object InitEnvCleanup(Env env); @@ -48,18 +50,21 @@ Object InitPromise(Env env); Object InitRunScript(Env env); #if (NAPI_VERSION > 3) Object InitThreadSafeFunctionCtx(Env env); +Object InitThreadSafeFunctionException(Env env); Object InitThreadSafeFunctionExistingTsfn(Env env); Object InitThreadSafeFunctionPtr(Env env); Object InitThreadSafeFunctionSum(Env env); Object InitThreadSafeFunctionUnref(Env env); Object InitThreadSafeFunction(Env env); Object InitTypedThreadSafeFunctionCtx(Env env); +Object InitTypedThreadSafeFunctionException(Env env); Object InitTypedThreadSafeFunctionExistingTsfn(Env env); Object InitTypedThreadSafeFunctionPtr(Env env); Object InitTypedThreadSafeFunctionSum(Env env); Object InitTypedThreadSafeFunctionUnref(Env env); Object InitTypedThreadSafeFunction(Env env); #endif +Object InitSharedArrayBuffer(Env env); Object InitSymbol(Env env); Object InitTypedArray(Env env); Object InitGlobalObject(Env env); @@ -74,11 +79,15 @@ Object InitVersionManagement(Env env); Object InitThunkingManual(Env env); #if (NAPI_VERSION > 7) Object InitObjectFreezeSeal(Env env); +Object InitTypeTaggable(Env env); +#endif +#if (NAPI_VERSION > 8) +Object InitEnvMiscellaneous(Env env); #endif - #if defined(NODE_ADDON_API_ENABLE_MAYBE) Object InitMaybeCheck(Env env); #endif +Object InitFinalizerOrder(Env env); Object Init(Env env, Object exports) { #if (NAPI_VERSION > 5) @@ -105,9 +114,11 @@ Object Init(Env env, Object exports) { exports.Set("date", InitDate(env)); #endif exports.Set("buffer", InitBuffer(env)); + exports.Set("bufferNoExternal", InitBufferNoExternal(env)); #if (NAPI_VERSION > 2) exports.Set("callbackscope", InitCallbackScope(env)); #endif + exports.Set("callbackInfo", InitCallbackInfo(env)); exports.Set("dataview", InitDataView(env)); exports.Set("dataview_read_write", InitDataView(env)); exports.Set("dataview_read_write", InitDataViewReadWrite(env)); @@ -130,8 +141,11 @@ Object Init(Env env, Object exports) { exports.Set("promise", InitPromise(env)); exports.Set("run_script", InitRunScript(env)); exports.Set("symbol", InitSymbol(env)); + exports.Set("sharedarraybuffer", InitSharedArrayBuffer(env)); #if (NAPI_VERSION > 3) exports.Set("threadsafe_function_ctx", InitThreadSafeFunctionCtx(env)); + exports.Set("threadsafe_function_exception", + InitThreadSafeFunctionException(env)); exports.Set("threadsafe_function_existing_tsfn", InitThreadSafeFunctionExistingTsfn(env)); exports.Set("threadsafe_function_ptr", InitThreadSafeFunctionPtr(env)); @@ -140,6 +154,8 @@ Object Init(Env env, Object exports) { exports.Set("threadsafe_function", InitThreadSafeFunction(env)); exports.Set("typed_threadsafe_function_ctx", InitTypedThreadSafeFunctionCtx(env)); + exports.Set("typed_threadsafe_function_exception", + InitTypedThreadSafeFunctionException(env)); exports.Set("typed_threadsafe_function_existing_tsfn", InitTypedThreadSafeFunctionExistingTsfn(env)); exports.Set("typed_threadsafe_function_ptr", @@ -164,11 +180,28 @@ Object Init(Env env, Object exports) { exports.Set("thunking_manual", InitThunkingManual(env)); #if (NAPI_VERSION > 7) exports.Set("object_freeze_seal", InitObjectFreezeSeal(env)); + exports.Set("type_taggable", InitTypeTaggable(env)); +#endif +#if (NAPI_VERSION > 8) + exports.Set("env_misc", InitEnvMiscellaneous(env)); #endif #if defined(NODE_ADDON_API_ENABLE_MAYBE) exports.Set("maybe_check", InitMaybeCheck(env)); #endif + + exports.Set("finalizer_order", InitFinalizerOrder(env)); + + exports.Set( + "isExperimental", + Napi::Boolean::New(env, NAPI_VERSION == NAPI_VERSION_EXPERIMENTAL)); + +#ifdef NODE_API_EXPERIMENTAL_HAS_SHAREDARRAYBUFFER + exports.Set("hasSharedArrayBuffer", Napi::Boolean::New(env, true)); +#else + exports.Set("hasSharedArrayBuffer", Napi::Boolean::New(env, false)); +#endif + return exports; } diff --git a/test/binding.gyp b/test/binding.gyp index b6aca5710..9ff334b64 100644 --- a/test/binding.gyp +++ b/test/binding.gyp @@ -17,16 +17,20 @@ 'basic_types/number.cc', 'basic_types/value.cc', 'bigint.cc', + 'callbackInfo.cc', 'date.cc', 'binding.cc', + 'buffer_no_external.cc', 'buffer.cc', 'callbackscope.cc', 'dataview/dataview.cc', 'dataview/dataview_read_write.cc', 'env_cleanup.cc', + 'env_misc.cc', 'error.cc', 'error_handling_for_primitives.cc', 'external.cc', + 'finalizer_order.cc', 'function.cc', 'function_reference.cc', 'handlescope.cc', @@ -50,14 +54,18 @@ 'object/subscript_operator.cc', 'promise.cc', 'run_script.cc', - "symbol.cc", + 'shared_array_buffer.cc', + 'symbol.cc', 'threadsafe_function/threadsafe_function_ctx.cc', + 'threadsafe_function/threadsafe_function_exception.cc', 'threadsafe_function/threadsafe_function_existing_tsfn.cc', 'threadsafe_function/threadsafe_function_ptr.cc', 'threadsafe_function/threadsafe_function_sum.cc', 'threadsafe_function/threadsafe_function_unref.cc', 'threadsafe_function/threadsafe_function.cc', + 'type_taggable.cc', 'typed_threadsafe_function/typed_threadsafe_function_ctx.cc', + 'typed_threadsafe_function/typed_threadsafe_function_exception.cc', 'typed_threadsafe_function/typed_threadsafe_function_existing_tsfn.cc', 'typed_threadsafe_function/typed_threadsafe_function_ptr.cc', 'typed_threadsafe_function/typed_threadsafe_function_sum.cc', @@ -78,45 +86,74 @@ 'binding-swallowexcept.cc', 'error.cc', ], + 'build_sources_except_all': [ + 'except_all.cc', + ], + 'build_sources_type_check': [ + 'value_type_cast.cc' + ], + 'want_coverage': '@(build_sources)'] + 'dependencies': ['../node_addon_api.gyp:node_addon_api_except'], + 'sources': ['>@(build_sources)'], + 'defines': ['NODE_ADDON_API_ENABLE_TYPE_CHECK_ON_AS'] + }, + { + 'target_name': 'binding_except_all', + 'dependencies': ['../node_addon_api.gyp:node_addon_api_except_all'], + 'sources': [ '>@(build_sources_except_all)'] }, { 'target_name': 'binding_noexcept', - 'includes': ['../noexcept.gypi'], + 'dependencies': ['../node_addon_api.gyp:node_addon_api'], 'sources': ['>@(build_sources)'] }, { 'target_name': 'binding_noexcept_maybe', - 'includes': ['../noexcept.gypi'], + 'dependencies': ['../node_addon_api.gyp:node_addon_api_maybe'], 'sources': ['>@(build_sources)'], - 'defines': ['NODE_ADDON_API_ENABLE_MAYBE'] }, { 'target_name': 'binding_swallowexcept', - 'includes': ['../except.gypi'], + 'dependencies': ['../node_addon_api.gyp:node_addon_api_except'], 'sources': [ '>@(build_sources_swallowexcept)'], 'defines': ['NODE_API_SWALLOW_UNTHROWABLE_EXCEPTIONS'] }, { 'target_name': 'binding_swallowexcept_noexcept', - 'includes': ['../noexcept.gypi'], + 'dependencies': ['../node_addon_api.gyp:node_addon_api'], 'sources': ['>@(build_sources_swallowexcept)'], 'defines': ['NODE_API_SWALLOW_UNTHROWABLE_EXCEPTIONS'] }, + { + 'target_name': 'binding_type_check', + 'dependencies': ['../node_addon_api.gyp:node_addon_api'], + 'sources': ['>@(build_sources_type_check)'], + 'defines': ['NODE_ADDON_API_ENABLE_TYPE_CHECK_ON_AS'] + }, { 'target_name': 'binding_custom_namespace', - 'includes': ['../noexcept.gypi'], + 'dependencies': ['../node_addon_api.gyp:node_addon_api'], 'sources': ['>@(build_sources)'], 'defines': ['NAPI_CPP_CUSTOM_NAMESPACE=cstm'] }, diff --git a/test/buffer.cc b/test/buffer.cc index 20ff20f46..c10300dc7 100644 --- a/test/buffer.cc +++ b/test/buffer.cc @@ -1,30 +1,16 @@ +#include "buffer.h" #include "napi.h" using namespace Napi; -namespace { - -const size_t testLength = 4; +namespace test_buffer { uint16_t testData[testLength]; int finalizeCount = 0; +} // namespace test_buffer -template -void InitData(T* data, size_t length) { - for (size_t i = 0; i < length; i++) { - data[i] = static_cast(i); - } -} - -template -bool VerifyData(T* data, size_t length) { - for (size_t i = 0; i < length; i++) { - if (data[i] != static_cast(i)) { - return false; - } - } - return true; -} +using namespace test_buffer; +namespace { Value CreateBuffer(const CallbackInfo& info) { Buffer buffer = Buffer::New(info.Env(), testLength); @@ -146,6 +132,8 @@ Value CreateBufferCopy(const CallbackInfo& info) { return buffer; } +#include "buffer_new_or_copy-inl.h" + void CheckBuffer(const CallbackInfo& info) { if (!info[0].IsBuffer()) { Error::New(info.Env(), "A buffer was expected.") @@ -183,6 +171,12 @@ Object InitBuffer(Env env) { Function::New(env, CreateExternalBufferWithFinalize); exports["createExternalBufferWithFinalizeHint"] = Function::New(env, CreateExternalBufferWithFinalizeHint); + exports["createOrCopyExternalBuffer"] = + Function::New(env, CreateOrCopyExternalBuffer); + exports["createOrCopyExternalBufferWithFinalize"] = + Function::New(env, CreateOrCopyExternalBufferWithFinalize); + exports["createOrCopyExternalBufferWithFinalizeHint"] = + Function::New(env, CreateOrCopyExternalBufferWithFinalizeHint); exports["createBufferCopy"] = Function::New(env, CreateBufferCopy); exports["checkBuffer"] = Function::New(env, CheckBuffer); exports["getFinalizeCount"] = Function::New(env, GetFinalizeCount); diff --git a/test/buffer.h b/test/buffer.h new file mode 100644 index 000000000..ed2a71771 --- /dev/null +++ b/test/buffer.h @@ -0,0 +1,26 @@ +#include +#include + +namespace test_buffer { + +const size_t testLength = 4; +extern uint16_t testData[testLength]; +extern int finalizeCount; + +template +void InitData(T* data, size_t length) { + for (size_t i = 0; i < length; i++) { + data[i] = static_cast(i); + } +} + +template +bool VerifyData(T* data, size_t length) { + for (size_t i = 0; i < length; i++) { + if (data[i] != static_cast(i)) { + return false; + } + } + return true; +} +} // namespace test_buffer diff --git a/test/buffer.js b/test/buffer.js index 8b915bea9..3f49201a7 100644 --- a/test/buffer.js +++ b/test/buffer.js @@ -2,7 +2,6 @@ const assert = require('assert'); const testUtil = require('./testUtil'); -const safeBuffer = require('safe-buffer'); module.exports = require('./common').runTest(test); @@ -14,7 +13,7 @@ function test (binding) { binding.buffer.checkBuffer(test); assert.ok(test instanceof Buffer); - const test2 = safeBuffer.Buffer.alloc(test.length); + const test2 = Buffer.alloc(test.length); test.copy(test2); binding.buffer.checkBuffer(test2); }, @@ -62,6 +61,88 @@ function test (binding) { () => { global.gc(); }, + () => { + assert.strictEqual(1, binding.buffer.getFinalizeCount()); + }, + + 'Create or Copy External Buffer', + () => { + const test = binding.buffer.createOrCopyExternalBuffer(); + binding.buffer.checkBuffer(test); + assert.ok(test instanceof Buffer); + assert.strictEqual(0, binding.buffer.getFinalizeCount()); + }, + () => { + global.gc(); + assert.strictEqual(0, binding.buffer.getFinalizeCount()); + }, + + 'Create or Copy External Buffer with finalizer', + () => { + const test = binding.buffer.createOrCopyExternalBufferWithFinalize(); + binding.buffer.checkBuffer(test); + assert.ok(test instanceof Buffer); + assert.strictEqual(0, binding.buffer.getFinalizeCount()); + }, + () => { + global.gc(); + }, + () => { + assert.strictEqual(1, binding.buffer.getFinalizeCount()); + }, + + 'Create or Copy External Buffer with finalizer hint', + () => { + const test = binding.buffer.createOrCopyExternalBufferWithFinalizeHint(); + binding.buffer.checkBuffer(test); + assert.ok(test instanceof Buffer); + assert.strictEqual(0, binding.buffer.getFinalizeCount()); + }, + () => { + global.gc(); + }, + () => { + assert.strictEqual(1, binding.buffer.getFinalizeCount()); + }, + + 'Create or Copy External Buffer when NODE_API_NO_EXTERNAL_BUFFERS_ALLOWED defined', + () => { + const test = binding.bufferNoExternal.createOrCopyExternalBuffer(); + binding.buffer.checkBuffer(test); + assert.ok(test instanceof Buffer); + assert.strictEqual(0, binding.buffer.getFinalizeCount()); + }, + () => { + global.gc(); + assert.strictEqual(0, binding.buffer.getFinalizeCount()); + }, + + 'Create or Copy External Buffer with finalizer when NODE_API_NO_EXTERNAL_BUFFERS_ALLOWED defined', + () => { + const test = binding.bufferNoExternal.createOrCopyExternalBufferWithFinalize(); + binding.buffer.checkBuffer(test); + assert.ok(test instanceof Buffer); + // finalizer should have been called when the buffer was created. + assert.strictEqual(1, binding.buffer.getFinalizeCount()); + }, + () => { + global.gc(); + }, + () => { + assert.strictEqual(1, binding.buffer.getFinalizeCount()); + }, + + 'Create or Copy External Buffer with finalizer hint when NODE_API_NO_EXTERNAL_BUFFERS_ALLOWED defined', + () => { + const test = binding.bufferNoExternal.createOrCopyExternalBufferWithFinalizeHint(); + binding.buffer.checkBuffer(test); + assert.ok(test instanceof Buffer); + // finalizer should have been called when the buffer was created. + assert.strictEqual(1, binding.buffer.getFinalizeCount()); + }, + () => { + global.gc(); + }, () => { assert.strictEqual(1, binding.buffer.getFinalizeCount()); } diff --git a/test/buffer_new_or_copy-inl.h b/test/buffer_new_or_copy-inl.h new file mode 100644 index 000000000..4d68fbc91 --- /dev/null +++ b/test/buffer_new_or_copy-inl.h @@ -0,0 +1,68 @@ +// Same tests on when NODE_API_NO_EXTERNAL_BUFFERS_ALLOWED is defined or not +// defined. + +Value CreateOrCopyExternalBuffer(const CallbackInfo& info) { + finalizeCount = 0; + + InitData(testData, testLength); + Buffer buffer = + Buffer::NewOrCopy(info.Env(), testData, testLength); + + if (buffer.Length() != testLength) { + Error::New(info.Env(), "Incorrect buffer length.") + .ThrowAsJavaScriptException(); + return Value(); + } + + VerifyData(buffer.Data(), testLength); + return buffer; +} + +Value CreateOrCopyExternalBufferWithFinalize(const CallbackInfo& info) { + finalizeCount = 0; + + uint16_t* data = new uint16_t[testLength]; + InitData(data, testLength); + + Buffer buffer = Buffer::NewOrCopy( + info.Env(), data, testLength, [](Env /*env*/, uint16_t* finalizeData) { + delete[] finalizeData; + finalizeCount++; + }); + + if (buffer.Length() != testLength) { + Error::New(info.Env(), "Incorrect buffer length.") + .ThrowAsJavaScriptException(); + return Value(); + } + + VerifyData(buffer.Data(), testLength); + return buffer; +} + +Value CreateOrCopyExternalBufferWithFinalizeHint(const CallbackInfo& info) { + finalizeCount = 0; + + uint16_t* data = new uint16_t[testLength]; + InitData(data, testLength); + + char* hint = nullptr; + Buffer buffer = Buffer::NewOrCopy( + info.Env(), + data, + testLength, + [](Env /*env*/, uint16_t* finalizeData, char* /*finalizeHint*/) { + delete[] finalizeData; + finalizeCount++; + }, + hint); + + if (buffer.Length() != testLength) { + Error::New(info.Env(), "Incorrect buffer length.") + .ThrowAsJavaScriptException(); + return Value(); + } + + VerifyData(buffer.Data(), testLength); + return buffer; +} diff --git a/test/buffer_no_external.cc b/test/buffer_no_external.cc new file mode 100644 index 000000000..11920bf1c --- /dev/null +++ b/test/buffer_no_external.cc @@ -0,0 +1,24 @@ +#define NODE_API_NO_EXTERNAL_BUFFERS_ALLOWED +// Should compile without errors +#include "buffer.h" +#include "napi.h" + +using namespace Napi; +using namespace test_buffer; + +namespace { +#include "buffer_new_or_copy-inl.h" +} + +Object InitBufferNoExternal(Env env) { + Object exports = Object::New(env); + + exports["createOrCopyExternalBuffer"] = + Function::New(env, CreateOrCopyExternalBuffer); + exports["createOrCopyExternalBufferWithFinalize"] = + Function::New(env, CreateOrCopyExternalBufferWithFinalize); + exports["createOrCopyExternalBufferWithFinalizeHint"] = + Function::New(env, CreateOrCopyExternalBufferWithFinalizeHint); + + return exports; +} diff --git a/test/callbackInfo.cc b/test/callbackInfo.cc new file mode 100644 index 000000000..ad5f72356 --- /dev/null +++ b/test/callbackInfo.cc @@ -0,0 +1,27 @@ +#include +#include "napi.h" +using namespace Napi; + +struct TestCBInfoSetData { + static void Test(napi_env env, napi_callback_info info) { + Napi::CallbackInfo cbInfo(env, info); + int valuePointer = 1220202; + cbInfo.SetData(&valuePointer); + + int* placeHolder = static_cast(cbInfo.Data()); + assert(*(placeHolder) == valuePointer); + assert(placeHolder == &valuePointer); + } +}; + +void TestCallbackInfoSetData(const Napi::CallbackInfo& info) { + napi_callback_info cb_info = static_cast(info); + TestCBInfoSetData::Test(info.Env(), cb_info); +} + +Object InitCallbackInfo(Env env) { + Object exports = Object::New(env); + + exports["testCbSetData"] = Function::New(env, TestCallbackInfoSetData); + return exports; +} diff --git a/test/callbackInfo.js b/test/callbackInfo.js new file mode 100644 index 000000000..ea671a986 --- /dev/null +++ b/test/callbackInfo.js @@ -0,0 +1,9 @@ +'use strict'; + +const common = require('./common'); + +module.exports = common.runTest(test); + +async function test (binding) { + binding.callbackInfo.testCbSetData(); +} diff --git a/test/callbackscope.cc b/test/callbackscope.cc index 5cfa96a87..9554a731a 100644 --- a/test/callbackscope.cc +++ b/test/callbackscope.cc @@ -1,8 +1,9 @@ +#include "assert.h" #include "napi.h" - using namespace Napi; #if (NAPI_VERSION > 2) + namespace { static void RunInCallbackScope(const CallbackInfo& info) { @@ -12,11 +13,27 @@ static void RunInCallbackScope(const CallbackInfo& info) { callback.Call({}); } -} // end anonymous namespace +static void RunInCallbackScopeFromExisting(const CallbackInfo& info) { + Function callback = info[0].As(); + Env env = info.Env(); + + AsyncContext ctx(env, "existing_callback_scope_test"); + napi_callback_scope scope; + napi_open_callback_scope(env, Object::New(env), ctx, &scope); + + CallbackScope existingScope(env, scope); + assert(existingScope.Env() == env); + + callback.Call({}); +} + +} // namespace Object InitCallbackScope(Env env) { Object exports = Object::New(env); exports["runInCallbackScope"] = Function::New(env, RunInCallbackScope); + exports["runInPreExistingCbScope"] = + Function::New(env, RunInCallbackScopeFromExisting); return exports; } #endif diff --git a/test/callbackscope.js b/test/callbackscope.js index 54a3844df..cafb180ca 100644 --- a/test/callbackscope.js +++ b/test/callbackscope.js @@ -24,7 +24,7 @@ function test (binding) { let insideHook = false; const hook = asyncHooks.createHook({ init (asyncId, type, triggerAsyncId, resource) { - if (id === undefined && type === 'callback_scope_test') { + if (id === undefined && (type === 'callback_scope_test' || type === 'existing_callback_scope_test')) { id = asyncId; } }, @@ -39,8 +39,11 @@ function test (binding) { return new Promise(resolve => { binding.callbackscope.runInCallbackScope(function () { assert(insideHook); - hook.disable(); - resolve(); + binding.callbackscope.runInPreExistingCbScope(function () { + assert(insideHook); + hook.disable(); + resolve(); + }); }); }); } diff --git a/test/child_processes/addon.js b/test/child_processes/addon.js new file mode 100644 index 000000000..33e80d798 --- /dev/null +++ b/test/child_processes/addon.js @@ -0,0 +1,11 @@ +'use strict'; +const assert = require('assert'); + +module.exports = { + workingCode: binding => { + const addon = binding.addon(); + assert.strictEqual(addon.increment(), 43); + assert.strictEqual(addon.increment(), 44); + assert.strictEqual(addon.subObject.decrement(), 43); + } +}; diff --git a/test/child_processes/addon_data.js b/test/child_processes/addon_data.js new file mode 100644 index 000000000..82d1aa317 --- /dev/null +++ b/test/child_processes/addon_data.js @@ -0,0 +1,24 @@ +'use strict'; + +const assert = require('assert'); + +// Make sure the instance data finalizer is called at process exit. If the hint +// is non-zero, it will be printed out by the child process. +const cleanupTest = (binding, hint) => { + binding.addon_data(hint).verbose = true; +}; + +module.exports = { + workingCode: binding => { + const addonData = binding.addon_data(0); + + // Make sure it is possible to get/set instance data. + assert.strictEqual(addonData.verbose.verbose, false); + addonData.verbose = true; + assert.strictEqual(addonData.verbose.verbose, true); + addonData.verbose = false; + assert.strictEqual(addonData.verbose.verbose, false); + }, + cleanupWithHint: binding => cleanupTest(binding, 42), + cleanupWithoutHint: binding => cleanupTest(binding, 0) +}; diff --git a/test/child_processes/objectwrap_function.js b/test/child_processes/objectwrap_function.js new file mode 100644 index 000000000..2ee83cb5e --- /dev/null +++ b/test/child_processes/objectwrap_function.js @@ -0,0 +1,22 @@ +'use strict'; + +const assert = require('assert'); +const testUtil = require('../testUtil'); + +module.exports = { + runTest: function (binding) { + return testUtil.runGCTests([ + 'objectwrap function', + () => { + const { FunctionTest } = binding.objectwrap_function(); + const newConstructed = new FunctionTest(); + const functionConstructed = FunctionTest(); + assert(newConstructed instanceof FunctionTest); + assert(functionConstructed instanceof FunctionTest); + assert.throws(() => (FunctionTest(true)), /an exception/); + }, + // Do one gc before returning. + () => {} + ]); + } +}; diff --git a/test/child_processes/threadsafe_function_exception.js b/test/child_processes/threadsafe_function_exception.js new file mode 100644 index 000000000..4fc63d7c8 --- /dev/null +++ b/test/child_processes/threadsafe_function_exception.js @@ -0,0 +1,33 @@ +'use strict'; + +const assert = require('assert'); +const common = require('../common'); + +module.exports = { + testCall: async binding => { + const { testCall } = binding.threadsafe_function_exception; + + await new Promise(resolve => { + process.once('uncaughtException', common.mustCall(err => { + assert.strictEqual(err.message, 'test'); + resolve(); + }, 1)); + + testCall(common.mustCall(() => { + throw new Error('test'); + }, 1)); + }); + }, + testCallWithNativeCallback: async binding => { + const { testCallWithNativeCallback } = binding.threadsafe_function_exception; + + await new Promise(resolve => { + process.once('uncaughtException', common.mustCall(err => { + assert.strictEqual(err.message, 'test-from-native'); + resolve(); + }, 1)); + + testCallWithNativeCallback(); + }); + } +}; diff --git a/test/child_processes/typed_threadsafe_function_exception.js b/test/child_processes/typed_threadsafe_function_exception.js new file mode 100644 index 000000000..5cbfab268 --- /dev/null +++ b/test/child_processes/typed_threadsafe_function_exception.js @@ -0,0 +1,19 @@ +'use strict'; + +const assert = require('assert'); +const common = require('../common'); + +module.exports = { + testCall: async binding => { + const { testCall } = binding.typed_threadsafe_function_exception; + + await new Promise(resolve => { + process.once('uncaughtException', common.mustCall(err => { + assert.strictEqual(err.message, 'test-from-native'); + resolve(); + }, 1)); + + testCall(); + }); + } +}; diff --git a/test/common/index.js b/test/common/index.js index f28121549..2469151ef 100644 --- a/test/common/index.js +++ b/test/common/index.js @@ -2,6 +2,12 @@ 'use strict'; const assert = require('assert'); const path = require('path'); +const { access } = require('node:fs/promises'); +const { spawn } = require('child_process'); +const { EOL } = require('os'); +const readline = require('readline'); + +const escapeBackslashes = (pathString) => pathString.split('\\').join('\\\\'); const noop = () => {}; @@ -25,12 +31,57 @@ function runCallChecks (exitCode) { context.name, context.messageSegment, context.actual); - console.log(context.stack.split('\n').slice(2).join('\n')); + console.log(context.stack.split(EOL).slice(2).join(EOL)); }); if (failed.length) process.exit(1); } +exports.installAysncHooks = function (asyncResName) { + const asyncHooks = require('async_hooks'); + return new Promise((resolve, reject) => { + let id; + const events = []; + /** + * TODO(legendecas): investigate why resolving & disabling hooks in + * destroy callback causing crash with case 'callbackscope.js'. + */ + let destroyed = false; + const hook = asyncHooks.createHook({ + init (asyncId, type, triggerAsyncId, resource) { + if (id === undefined && type === asyncResName) { + id = asyncId; + events.push({ eventName: 'init', type, triggerAsyncId, resource }); + } + }, + before (asyncId) { + if (asyncId === id) { + events.push({ eventName: 'before' }); + } + }, + after (asyncId) { + if (asyncId === id) { + events.push({ eventName: 'after' }); + } + }, + destroy (asyncId) { + if (asyncId === id) { + events.push({ eventName: 'destroy' }); + destroyed = true; + } + } + }).enable(); + + const interval = setInterval(() => { + if (destroyed) { + hook.disable(); + clearInterval(interval); + resolve(events); + } + }, 10); + }); +}; + exports.mustCall = function (fn, exact) { return _mustCallInner(fn, exact, 'exact'); }; @@ -75,9 +126,41 @@ exports.mustNotCall = function (msg) { }; }; -exports.runTest = async function (test, buildType, buildPathRoot = process.env.BUILD_PATH || '') { - buildType = buildType || process.config.target_defaults.default_configuration || 'Release'; +const buildTypes = { + Release: 'Release', + Debug: 'Debug' +}; +async function checkBuildType (buildType) { + try { + await access(path.join(path.resolve('./test/build'), buildType)); + return true; + } catch { + return false; + } +} + +async function whichBuildType () { + let buildType = 'Release'; + const envBuildType = process.env.NODE_API_BUILD_CONFIG || (process.env.npm_config_debug === 'true' ? 'Debug' : 'Release'); + if (envBuildType) { + if (Object.values(buildTypes).includes(envBuildType)) { + if (await checkBuildType(envBuildType)) { + buildType = envBuildType; + } else { + throw new Error(`The ${envBuildType} build doesn't exist.`); + } + } else { + throw new Error('Invalid value for NODE_API_BUILD_CONFIG environment variable. It should be set to Release or Debug.'); + } + } + return buildType; +} + +exports.whichBuildType = whichBuildType; + +exports.runTest = async function (test, buildType, buildPathRoot = process.env.BUILD_PATH || '') { + buildType = buildType || await whichBuildType(); const bindings = [ path.join(buildPathRoot, `../build/${buildType}/binding.node`), path.join(buildPathRoot, `../build/${buildType}/binding_noexcept.node`), @@ -86,13 +169,13 @@ exports.runTest = async function (test, buildType, buildPathRoot = process.env.B ].map(it => require.resolve(it)); for (const item of bindings) { - await Promise.resolve(test(require(item))) + await Promise.resolve(test(require(item), { bindingPath: item })) .finally(exports.mustCall()); } }; exports.runTestWithBindingPath = async function (test, buildType, buildPathRoot = process.env.BUILD_PATH || '') { - buildType = buildType || process.config.target_defaults.default_configuration || 'Release'; + buildType = buildType || await whichBuildType(); const bindings = [ path.join(buildPathRoot, `../build/${buildType}/binding.node`), @@ -107,8 +190,57 @@ exports.runTestWithBindingPath = async function (test, buildType, buildPathRoot }; exports.runTestWithBuildType = async function (test, buildType) { - buildType = buildType || process.config.target_defaults.default_configuration || 'Release'; + buildType = buildType || await whichBuildType(); await Promise.resolve(test(buildType)) .finally(exports.mustCall()); }; + +// Some tests have to run in their own process, otherwise they would interfere +// with each other. Such tests export a factory function rather than the test +// itself so as to avoid automatic instantiation, and therefore interference, +// in the main process. Two examples are addon and addon_data, both of which +// use Napi::Env::SetInstanceData(). This helper function provides a common +// approach for running such tests. +exports.runTestInChildProcess = function ({ suite, testName, expectedStderr, execArgv }) { + return exports.runTestWithBindingPath((bindingName) => { + return new Promise((resolve) => { + bindingName = escapeBackslashes(bindingName); + // Test suites are assumed to be located here. + const suitePath = escapeBackslashes(path.join(__dirname, '..', 'child_processes', suite)); + const child = spawn(process.execPath, [ + '--expose-gc', + ...(execArgv ?? []), + '-e', + `require('${suitePath}').${testName}(require('${bindingName}'))` + ]); + const resultOfProcess = { stderr: [] }; + + // Capture the exit code and signal. + child.on('close', (code, signal) => resolve(Object.assign(resultOfProcess, { code, signal }))); + + // Capture the stderr as an array of lines. + readline + .createInterface({ input: child.stderr }) + .on('line', (line) => { + resultOfProcess.stderr.push(line); + }); + }).then(actual => { + // Back up the stderr in case the assertion fails. + const fullStderr = actual.stderr.map(item => `from child process: ${item}`); + const expected = { stderr: expectedStderr, code: 0, signal: null }; + + if (!expectedStderr) { + // If we don't care about stderr, delete it. + delete actual.stderr; + delete expected.stderr; + } else { + // Otherwise we only care about expected lines in the actual stderr, so + // filter out everything else. + actual.stderr = actual.stderr.filter(line => expectedStderr.includes(line)); + } + + assert.deepStrictEqual(actual, expected, `Assertion for child process test ${suite}.${testName} failed:${EOL}` + fullStderr.join(EOL)); + }); + }); +}; diff --git a/test/dataview/dataview.cc b/test/dataview/dataview.cc index f055d95f1..cbd5933e7 100644 --- a/test/dataview/dataview.cc +++ b/test/dataview/dataview.cc @@ -2,24 +2,51 @@ using namespace Napi; -static Value CreateDataView1(const CallbackInfo& info) { +static Value CreateDataView(const CallbackInfo& info) { ArrayBuffer arrayBuffer = info[0].As(); return DataView::New(info.Env(), arrayBuffer); } -static Value CreateDataView2(const CallbackInfo& info) { +static Value CreateDataViewWithByteOffset(const CallbackInfo& info) { ArrayBuffer arrayBuffer = info[0].As(); size_t byteOffset = info[1].As().Uint32Value(); return DataView::New(info.Env(), arrayBuffer, byteOffset); } -static Value CreateDataView3(const CallbackInfo& info) { +static Value CreateDataViewWithByteOffsetAndByteLength( + const CallbackInfo& info) { ArrayBuffer arrayBuffer = info[0].As(); size_t byteOffset = info[1].As().Uint32Value(); size_t byteLength = info[2].As().Uint32Value(); return DataView::New(info.Env(), arrayBuffer, byteOffset, byteLength); } +#ifdef NODE_API_EXPERIMENTAL_HAS_SHAREDARRAYBUFFER +static Value CreateDataViewOnSharedArrayBuffer(const CallbackInfo& info) { + SharedArrayBuffer arrayBuffer = info[0].As(); + return DataView::New(info.Env(), arrayBuffer); +} + +static Value CreateDataViewOnSharedArrayBufferWithByteOffset( + const CallbackInfo& info) { + SharedArrayBuffer arrayBuffer = info[0].As(); + size_t byteOffset = info[1].As().Uint32Value(); + return DataView::New(info.Env(), arrayBuffer, byteOffset); +} + +static Value CreateDataViewOnSharedArrayBufferWithByteOffsetAndByteLength( + const CallbackInfo& info) { + SharedArrayBuffer arrayBuffer = info[0].As(); + size_t byteOffset = info[1].As().Uint32Value(); + size_t byteLength = info[2].As().Uint32Value(); + return DataView::New(info.Env(), arrayBuffer, byteOffset, byteLength); +} +#endif + +static Value GetBuffer(const CallbackInfo& info) { + return info[0].As().Buffer(); +} + static Value GetArrayBuffer(const CallbackInfo& info) { return info[0].As().ArrayBuffer(); } @@ -37,10 +64,24 @@ static Value GetByteLength(const CallbackInfo& info) { Object InitDataView(Env env) { Object exports = Object::New(env); - exports["createDataView1"] = Function::New(env, CreateDataView1); - exports["createDataView2"] = Function::New(env, CreateDataView2); - exports["createDataView3"] = Function::New(env, CreateDataView3); + exports["createDataView"] = Function::New(env, CreateDataView); + exports["createDataViewWithByteOffset"] = + Function::New(env, CreateDataViewWithByteOffset); + exports["createDataViewWithByteOffsetAndByteLength"] = + Function::New(env, CreateDataViewWithByteOffsetAndByteLength); + +#ifdef NODE_API_EXPERIMENTAL_HAS_SHAREDARRAYBUFFER + exports["createDataViewOnSharedArrayBuffer"] = + Function::New(env, CreateDataViewOnSharedArrayBuffer); + exports["createDataViewOnSharedArrayBufferWithByteOffset"] = + Function::New(env, CreateDataViewOnSharedArrayBufferWithByteOffset); + exports["createDataViewOnSharedArrayBufferWithByteOffsetAndByteLength"] = + Function::New( + env, CreateDataViewOnSharedArrayBufferWithByteOffsetAndByteLength); +#endif + exports["getArrayBuffer"] = Function::New(env, GetArrayBuffer); + exports["getBuffer"] = Function::New(env, GetBuffer); exports["getByteOffset"] = Function::New(env, GetByteOffset); exports["getByteLength"] = Function::New(env, GetByteLength); diff --git a/test/dataview/dataview.js b/test/dataview/dataview.js index 595612856..5916f6b90 100644 --- a/test/dataview/dataview.js +++ b/test/dataview/dataview.js @@ -3,12 +3,19 @@ const assert = require('assert'); module.exports = require('../common').runTest(test); +let runSharedArrayBufferTests = true; + function test (binding) { function testDataViewCreation (factory, arrayBuffer, offset, length) { const view = factory(arrayBuffer, offset, length); offset = offset || 0; - assert.ok(dataview.getArrayBuffer(view) instanceof ArrayBuffer); - assert.strictEqual(dataview.getArrayBuffer(view), arrayBuffer); + if (arrayBuffer instanceof ArrayBuffer) { + assert.ok(dataview.getArrayBuffer(view) instanceof ArrayBuffer); + assert.strictEqual(dataview.getArrayBuffer(view), arrayBuffer); + } else { + assert.ok(dataview.getBuffer(view) instanceof SharedArrayBuffer); + assert.strictEqual(dataview.getBuffer(view), arrayBuffer); + } assert.strictEqual(dataview.getByteOffset(view), offset); assert.strictEqual(dataview.getByteLength(view), length || arrayBuffer.byteLength - offset); @@ -20,16 +27,48 @@ function test (binding) { }, RangeError); } - const dataview = binding.dataview; - const arrayBuffer = new ArrayBuffer(10); + const { hasSharedArrayBuffer, dataview } = binding; + + { + const arrayBuffer = new ArrayBuffer(10); + + testDataViewCreation(dataview.createDataView, arrayBuffer); + testDataViewCreation(dataview.createDataViewWithByteOffset, arrayBuffer, 2); + testDataViewCreation(dataview.createDataViewWithByteOffset, arrayBuffer, 10); + testDataViewCreation(dataview.createDataViewWithByteOffsetAndByteLength, arrayBuffer, 2, 4); + testDataViewCreation(dataview.createDataViewWithByteOffsetAndByteLength, arrayBuffer, 10, 0); + + testInvalidRange(dataview.createDataViewWithByteOffset, arrayBuffer, 11); + testInvalidRange(dataview.createDataViewWithByteOffsetAndByteLength, arrayBuffer, 11, 0); + testInvalidRange(dataview.createDataViewWithByteOffsetAndByteLength, arrayBuffer, 6, 5); + } + + if (hasSharedArrayBuffer && runSharedArrayBufferTests) { + const sab = new SharedArrayBuffer(10); - testDataViewCreation(dataview.createDataView1, arrayBuffer); - testDataViewCreation(dataview.createDataView2, arrayBuffer, 2); - testDataViewCreation(dataview.createDataView2, arrayBuffer, 10); - testDataViewCreation(dataview.createDataView3, arrayBuffer, 2, 4); - testDataViewCreation(dataview.createDataView3, arrayBuffer, 10, 0); + try { + testDataViewCreation(dataview.createDataViewOnSharedArrayBuffer, sab); + } catch (ex) { + // The `napi_create_dataview` API does not have a valid `#define` + // preprocessor guard for SharedArrayBuffer support, so it is + // possible that the API is present but creating a DataView on + // SharedArrayBuffer is not supported in the current version of Node.js. + // In that case, we should skip the test instead of throwing. + if (ex.message === 'Invalid argument') { + console.warn(`The current version of Node.js (${process.version}) does not support creating DataViews on SharedArrayBuffers; skipping tests.`); + runSharedArrayBufferTests = false; + return; + } - testInvalidRange(dataview.createDataView2, arrayBuffer, 11); - testInvalidRange(dataview.createDataView3, arrayBuffer, 11, 0); - testInvalidRange(dataview.createDataView3, arrayBuffer, 6, 5); + throw ex; + } + testDataViewCreation(dataview.createDataViewOnSharedArrayBufferWithByteOffset, sab, 2); + testDataViewCreation(dataview.createDataViewOnSharedArrayBufferWithByteOffset, sab, 10); + testDataViewCreation(dataview.createDataViewOnSharedArrayBufferWithByteOffsetAndByteLength, sab, 2, 4); + testDataViewCreation(dataview.createDataViewOnSharedArrayBufferWithByteOffsetAndByteLength, sab, 10, 0); + + testInvalidRange(dataview.createDataViewOnSharedArrayBufferWithByteOffset, sab, 11); + testInvalidRange(dataview.createDataViewOnSharedArrayBufferWithByteOffsetAndByteLength, sab, 11, 0); + testInvalidRange(dataview.createDataViewOnSharedArrayBufferWithByteOffsetAndByteLength, sab, 6, 5); + } } diff --git a/test/date.cc b/test/date.cc index efd433af4..a446bde22 100644 --- a/test/date.cc +++ b/test/date.cc @@ -11,6 +11,11 @@ Value CreateDate(const CallbackInfo& info) { return Date::New(info.Env(), input); } +Value CreateDateFromTimePoint(const CallbackInfo& info) { + auto input = std::chrono::system_clock::time_point{}; + return Date::New(info.Env(), input); +} + Value IsDate(const CallbackInfo& info) { Date input = info[0].As(); @@ -35,6 +40,8 @@ Value OperatorValue(const CallbackInfo& info) { Object InitDate(Env env) { Object exports = Object::New(env); exports["CreateDate"] = Function::New(env, CreateDate); + exports["CreateDateFromTimePoint"] = + Function::New(env, CreateDateFromTimePoint); exports["IsDate"] = Function::New(env, IsDate); exports["ValueOf"] = Function::New(env, ValueOf); exports["OperatorValue"] = Function::New(env, OperatorValue); diff --git a/test/date.js b/test/date.js index 86c8af6ac..588b741b1 100644 --- a/test/date.js +++ b/test/date.js @@ -9,9 +9,11 @@ function test (binding) { CreateDate, IsDate, ValueOf, - OperatorValue + OperatorValue, + CreateDateFromTimePoint } = binding.date; assert.deepStrictEqual(CreateDate(0), new Date(0)); + assert.deepStrictEqual(CreateDateFromTimePoint(), new Date(0)); assert.strictEqual(IsDate(new Date(0)), true); assert.strictEqual(ValueOf(new Date(42)), 42); assert.strictEqual(OperatorValue(new Date(42)), true); diff --git a/test/env_cleanup.cc b/test/env_cleanup.cc index 44be0d5f7..a0ef62b2c 100644 --- a/test/env_cleanup.cc +++ b/test/env_cleanup.cc @@ -20,6 +20,13 @@ static void cleanupVoid() { static int secret1 = 42; static int secret2 = 43; +class TestClass { + public: + Env::CleanupHook hook; + + void removeHook(Env env) { hook.Remove(env); } +}; + Value AddHooks(const CallbackInfo& info) { auto env = info.Env(); @@ -72,6 +79,11 @@ Value AddHooks(const CallbackInfo& info) { added += !hook5.IsEmpty(); added += !hook6.IsEmpty(); + // Test store a hook in a member class variable + auto myclass = TestClass(); + myclass.hook = env.AddCleanupHook(cleanup, &secret1); + myclass.removeHook(env); + return Number::New(env, added); } diff --git a/test/env_misc.cc b/test/env_misc.cc new file mode 100644 index 000000000..a453e5d0e --- /dev/null +++ b/test/env_misc.cc @@ -0,0 +1,25 @@ +#include "napi.h" +#include "test_helper.h" + +#if (NAPI_VERSION > 8) + +using namespace Napi; + +namespace { + +Value GetModuleFileName(const CallbackInfo& info) { + Env env = info.Env(); + return String::New(env, env.GetModuleFileName()); +} + +} // end anonymous namespace + +Object InitEnvMiscellaneous(Env env) { + Object exports = Object::New(env); + + exports["get_module_file_name"] = Function::New(env, GetModuleFileName); + + return exports; +} + +#endif diff --git a/test/env_misc.js b/test/env_misc.js new file mode 100644 index 000000000..19fc9881e --- /dev/null +++ b/test/env_misc.js @@ -0,0 +1,12 @@ +'use strict'; + +const assert = require('assert'); +const { pathToFileURL } = require('url'); + +module.exports = require('./common').runTest(test); + +function test (binding, { bindingPath } = {}) { + const path = binding.env_misc.get_module_file_name(); + const bindingFileUrl = pathToFileURL(bindingPath).toString(); + assert(bindingFileUrl === path); +} diff --git a/test/error.cc b/test/error.cc index f6a43984a..6c716351b 100644 --- a/test/error.cc +++ b/test/error.cc @@ -1,4 +1,6 @@ +#include #include +#include "assert.h" #include "napi.h" using namespace Napi; @@ -69,6 +71,34 @@ void LastExceptionErrorCode(const CallbackInfo& info) { NAPI_THROW_VOID(Error::New(env)); } +void TestErrorCopySemantics(const Napi::CallbackInfo& info) { + Napi::Error newError = Napi::Error::New(info.Env(), "errorCopyCtor"); + Napi::Error existingErr; + +#ifdef NAPI_CPP_EXCEPTIONS + std::string msg = "errorCopyCtor"; + assert(strcmp(newError.what(), msg.c_str()) == 0); +#endif + + Napi::Error errCopyCtor = newError; + assert(errCopyCtor.Message() == "errorCopyCtor"); + + existingErr = newError; + assert(existingErr.Message() == "errorCopyCtor"); +} + +void TestErrorMoveSemantics(const Napi::CallbackInfo& info) { + std::string errorMsg = "errorMoveCtor"; + Napi::Error newError = Napi::Error::New(info.Env(), errorMsg.c_str()); + Napi::Error errFromMove = std::move(newError); + assert(errFromMove.Message() == "errorMoveCtor"); + + newError = Napi::Error::New(info.Env(), "errorMoveAssign"); + Napi::Error existingErr = std::move(newError); + + assert(existingErr.Message() == "errorMoveAssign"); +} + #ifdef NAPI_CPP_EXCEPTIONS void ThrowJSError(const CallbackInfo& info) { @@ -78,6 +108,13 @@ void ThrowJSError(const CallbackInfo& info) { throw Error::New(info.Env(), message); } +void ThrowTypeErrorCtor(const CallbackInfo& info) { + Napi::Value js_type_error = info[0]; + ReleaseAndWaitForChildProcess(info, 1); + + throw Napi::TypeError(info.Env(), js_type_error); +} + void ThrowTypeError(const CallbackInfo& info) { std::string message = info[0].As().Utf8Value(); @@ -85,6 +122,30 @@ void ThrowTypeError(const CallbackInfo& info) { throw TypeError::New(info.Env(), message); } +void ThrowTypeErrorCStr(const CallbackInfo& info) { + std::string message = info[0].As().Utf8Value(); + + ReleaseAndWaitForChildProcess(info, 1); + throw TypeError::New(info.Env(), message.c_str()); +} + +void ThrowRangeErrorCStr(const CallbackInfo& info) { + std::string message = info[0].As().Utf8Value(); + ReleaseAndWaitForChildProcess(info, 1); + throw RangeError::New(info.Env(), message.c_str()); +} + +void ThrowRangeErrorCtor(const CallbackInfo& info) { + Napi::Value js_range_err = info[0]; + ReleaseAndWaitForChildProcess(info, 1); + throw Napi::RangeError(info.Env(), js_range_err); +} + +void ThrowEmptyRangeError(const CallbackInfo& info) { + ReleaseAndWaitForChildProcess(info, 1); + throw RangeError(); +} + void ThrowRangeError(const CallbackInfo& info) { std::string message = info[0].As().Utf8Value(); @@ -92,6 +153,27 @@ void ThrowRangeError(const CallbackInfo& info) { throw RangeError::New(info.Env(), message); } +#if NAPI_VERSION > 8 +void ThrowSyntaxErrorCStr(const CallbackInfo& info) { + std::string message = info[0].As().Utf8Value(); + ReleaseAndWaitForChildProcess(info, 1); + throw SyntaxError::New(info.Env(), message.c_str()); +} + +void ThrowSyntaxErrorCtor(const CallbackInfo& info) { + Napi::Value js_range_err = info[0]; + ReleaseAndWaitForChildProcess(info, 1); + throw Napi::SyntaxError(info.Env(), js_range_err); +} + +void ThrowSyntaxError(const CallbackInfo& info) { + std::string message = info[0].As().Utf8Value(); + + ReleaseAndWaitForChildProcess(info, 1); + throw SyntaxError::New(info.Env(), message); +} +#endif // NAPI_VERSION > 8 + Value CatchError(const CallbackInfo& info) { Function thrower = info[0].As(); try { @@ -156,6 +238,19 @@ void ThrowTypeError(const CallbackInfo& info) { TypeError::New(info.Env(), message).ThrowAsJavaScriptException(); } +void ThrowTypeErrorCtor(const CallbackInfo& info) { + Napi::Value js_type_error = info[0]; + ReleaseAndWaitForChildProcess(info, 1); + TypeError(info.Env(), js_type_error).ThrowAsJavaScriptException(); +} + +void ThrowTypeErrorCStr(const CallbackInfo& info) { + std::string message = info[0].As().Utf8Value(); + + ReleaseAndWaitForChildProcess(info, 1); + TypeError::New(info.Env(), message.c_str()).ThrowAsJavaScriptException(); +} + void ThrowRangeError(const CallbackInfo& info) { std::string message = info[0].As().Utf8Value(); @@ -163,6 +258,45 @@ void ThrowRangeError(const CallbackInfo& info) { RangeError::New(info.Env(), message).ThrowAsJavaScriptException(); } +void ThrowRangeErrorCtor(const CallbackInfo& info) { + Napi::Value js_range_err = info[0]; + ReleaseAndWaitForChildProcess(info, 1); + RangeError(info.Env(), js_range_err).ThrowAsJavaScriptException(); +} + +void ThrowRangeErrorCStr(const CallbackInfo& info) { + std::string message = info[0].As().Utf8Value(); + ReleaseAndWaitForChildProcess(info, 1); + RangeError::New(info.Env(), message.c_str()).ThrowAsJavaScriptException(); +} + +// TODO: Figure out the correct api for this +void ThrowEmptyRangeError(const CallbackInfo& info) { + ReleaseAndWaitForChildProcess(info, 1); + RangeError().ThrowAsJavaScriptException(); +} + +#if NAPI_VERSION > 8 +void ThrowSyntaxError(const CallbackInfo& info) { + std::string message = info[0].As().Utf8Value(); + + ReleaseAndWaitForChildProcess(info, 1); + SyntaxError::New(info.Env(), message).ThrowAsJavaScriptException(); +} + +void ThrowSyntaxErrorCtor(const CallbackInfo& info) { + Napi::Value js_range_err = info[0]; + ReleaseAndWaitForChildProcess(info, 1); + SyntaxError(info.Env(), js_range_err).ThrowAsJavaScriptException(); +} + +void ThrowSyntaxErrorCStr(const CallbackInfo& info) { + std::string message = info[0].As().Utf8Value(); + ReleaseAndWaitForChildProcess(info, 1); + SyntaxError::New(info.Env(), message.c_str()).ThrowAsJavaScriptException(); +} +#endif // NAPI_VERSION > 8 + Value CatchError(const CallbackInfo& info) { Function thrower = info[0].As(); thrower({}); @@ -266,11 +400,25 @@ void ThrowDefaultError(const CallbackInfo& info) { Object InitError(Env env) { Object exports = Object::New(env); exports["throwApiError"] = Function::New(env, ThrowApiError); + exports["testErrorCopySemantics"] = + Function::New(env, TestErrorCopySemantics); + exports["testErrorMoveSemantics"] = + Function::New(env, TestErrorMoveSemantics); exports["lastExceptionErrorCode"] = Function::New(env, LastExceptionErrorCode); exports["throwJSError"] = Function::New(env, ThrowJSError); exports["throwTypeError"] = Function::New(env, ThrowTypeError); + exports["throwTypeErrorCtor"] = Function::New(env, ThrowTypeErrorCtor); + exports["throwTypeErrorCStr"] = Function::New(env, ThrowTypeErrorCStr); exports["throwRangeError"] = Function::New(env, ThrowRangeError); + exports["throwRangeErrorCtor"] = Function::New(env, ThrowRangeErrorCtor); + exports["throwRangeErrorCStr"] = Function::New(env, ThrowRangeErrorCStr); + exports["throwEmptyRangeError"] = Function::New(env, ThrowEmptyRangeError); +#if NAPI_VERSION > 8 + exports["throwSyntaxError"] = Function::New(env, ThrowSyntaxError); + exports["throwSyntaxErrorCtor"] = Function::New(env, ThrowSyntaxErrorCtor); + exports["throwSyntaxErrorCStr"] = Function::New(env, ThrowSyntaxErrorCStr); +#endif // NAPI_VERSION > 8 exports["catchError"] = Function::New(env, CatchError); exports["catchErrorMessage"] = Function::New(env, CatchErrorMessage); exports["doNotCatch"] = Function::New(env, DoNotCatch); diff --git a/test/error.js b/test/error.js index d1519ec8e..c2a3ad367 100644 --- a/test/error.js +++ b/test/error.js @@ -9,8 +9,12 @@ if (process.argv[2] === 'fatal') { module.exports = require('./common').runTestWithBindingPath(test); +const napiVersion = Number(process.env.NAPI_VERSION ?? process.versions.napi); + function test (bindingPath) { const binding = require(bindingPath); + binding.error.testErrorCopySemantics(); + binding.error.testErrorMoveSemantics(); assert.throws(() => binding.error.throwApiError('test'), function (err) { return err instanceof Error && err.message.includes('Invalid'); @@ -24,14 +28,40 @@ function test (bindingPath) { return err instanceof Error && err.message === 'test'; }); - assert.throws(() => binding.error.throwTypeError('test'), function (err) { + assert.throws(() => binding.error.throwTypeErrorCStr('test'), function (err) { return err instanceof TypeError && err.message === 'test'; }); + assert.throws(() => binding.error.throwRangeErrorCStr('test'), function (err) { + return err instanceof RangeError && err.message === 'test'; + }); + assert.throws(() => binding.error.throwRangeError('test'), function (err) { return err instanceof RangeError && err.message === 'test'; }); + assert.throws(() => binding.error.throwTypeErrorCtor(new TypeError('jsTypeError')), function (err) { + return err instanceof TypeError && err.message === 'jsTypeError'; + }); + + assert.throws(() => binding.error.throwRangeErrorCtor(new RangeError('rangeTypeError')), function (err) { + return err instanceof RangeError && err.message === 'rangeTypeError'; + }); + + if (napiVersion > 8) { + assert.throws(() => binding.error.throwSyntaxErrorCStr('test'), function (err) { + return err instanceof SyntaxError && err.message === 'test'; + }); + + assert.throws(() => binding.error.throwSyntaxError('test'), function (err) { + return err instanceof SyntaxError && err.message === 'test'; + }); + + assert.throws(() => binding.error.throwSyntaxErrorCtor(new SyntaxError('syntaxTypeError')), function (err) { + return err instanceof SyntaxError && err.message === 'syntaxTypeError'; + }); + } + assert.throws( () => binding.error.doNotCatch( () => { diff --git a/test/error_terminating_environment.js b/test/error_terminating_environment.js index 95364d672..df9e8b935 100644 --- a/test/error_terminating_environment.js +++ b/test/error_terminating_environment.js @@ -1,6 +1,7 @@ 'use strict'; -const buildType = process.config.target_defaults.default_configuration; + const assert = require('assert'); +const { whichBuildType } = require('./common'); // These tests ensure that Error types can be used in a terminating // environment without triggering any fatal errors. @@ -63,11 +64,16 @@ if (process.argv[2] === 'runInChildProcess') { assert.fail('This should not be reachable'); } - test(`./build/${buildType}/binding.node`, true); - test(`./build/${buildType}/binding_noexcept.node`, true); - test(`./build/${buildType}/binding_swallowexcept.node`, false); - test(`./build/${buildType}/binding_swallowexcept_noexcept.node`, false); - test(`./build/${buildType}/binding_custom_namespace.node`, true); + wrapTest(); + + async function wrapTest () { + const buildType = await whichBuildType(); + test(`./build/${buildType}/binding.node`, true); + test(`./build/${buildType}/binding_noexcept.node`, true); + test(`./build/${buildType}/binding_swallowexcept.node`, false); + test(`./build/${buildType}/binding_swallowexcept_noexcept.node`, false); + test(`./build/${buildType}/binding_custom_namespace.node`, true); + } function test (bindingPath, processShouldAbort) { const numberOfTestCases = 5; diff --git a/test/except_all.cc b/test/except_all.cc new file mode 100644 index 000000000..e2c230b21 --- /dev/null +++ b/test/except_all.cc @@ -0,0 +1,22 @@ +#include +#include "napi.h" + +using namespace Napi; + +void ThrowStdException(const CallbackInfo& info) { + std::string message = info[0].As().Utf8Value(); + throw std::runtime_error(message); +} + +void ThrowPrimitiveException(const CallbackInfo&) { + throw 0; +} + +Object Init(Env env, Object exports) { + exports.Set("throwStdException", Napi::Function::New(env, ThrowStdException)); + exports.Set("throwPrimitiveException", + Napi::Function::New(env, ThrowPrimitiveException)); + return exports; +} + +NODE_API_MODULE(addon, Init) diff --git a/test/except_all.js b/test/except_all.js new file mode 100644 index 000000000..d650ece6f --- /dev/null +++ b/test/except_all.js @@ -0,0 +1,14 @@ +'use strict'; + +const assert = require('assert'); + +module.exports = require('./common').runTestWithBuildType(test); + +function test (buildType) { + const binding = require(`./build/${buildType}/binding_except_all.node`); + + const message = 'error message'; + assert.throws(binding.throwStdException.bind(undefined, message), { message }); + + assert.throws(binding.throwPrimitiveException.bind(undefined), { message: 'A native exception was thrown' }); +} diff --git a/test/exports.js b/test/exports.js new file mode 100644 index 000000000..1aa39281c --- /dev/null +++ b/test/exports.js @@ -0,0 +1,19 @@ +'use strict'; + +const { strictEqual } = require('assert'); +const { valid } = require('semver'); + +const nodeAddonApi = require('../'); + +module.exports = function test () { + strictEqual(nodeAddonApi.include.startsWith('"'), true); + strictEqual(nodeAddonApi.include.endsWith('"'), true); + strictEqual(nodeAddonApi.include.includes('node-addon-api'), true); + strictEqual(nodeAddonApi.include_dir, ''); + strictEqual(nodeAddonApi.gyp, 'node_api.gyp:nothing'); + strictEqual(nodeAddonApi.targets, 'node_addon_api.gyp'); + strictEqual(valid(nodeAddonApi.version), true); + strictEqual(nodeAddonApi.version, require('../package.json').version); + strictEqual(nodeAddonApi.isNodeApiBuiltin, true); + strictEqual(nodeAddonApi.needsFlag, false); +}; diff --git a/test/finalizer_order.cc b/test/finalizer_order.cc new file mode 100644 index 000000000..0767ced70 --- /dev/null +++ b/test/finalizer_order.cc @@ -0,0 +1,152 @@ +#include + +namespace { +class Test : public Napi::ObjectWrap { + public: + Test(const Napi::CallbackInfo& info) : Napi::ObjectWrap(info) { + basicFinalizerCalled = false; + finalizerCalled = false; + + if (info.Length() > 0) { + finalizeCb_ = Napi::Persistent(info[0].As()); + } + } + + static void Initialize(Napi::Env env, Napi::Object exports) { + exports.Set("Test", + DefineClass(env, + "Test", + { + StaticAccessor("isBasicFinalizerCalled", + &IsBasicFinalizerCalled, + nullptr, + napi_default), + StaticAccessor("isFinalizerCalled", + &IsFinalizerCalled, + nullptr, + napi_default), + })); + } + + void Finalize(Napi::BasicEnv /*env*/) { basicFinalizerCalled = true; } + + void Finalize(Napi::Env /*env*/) { + finalizerCalled = true; + if (!finalizeCb_.IsEmpty()) { + finalizeCb_.Call({}); + } + } + + static Napi::Value IsBasicFinalizerCalled(const Napi::CallbackInfo& info) { + return Napi::Boolean::New(info.Env(), basicFinalizerCalled); + } + + static Napi::Value IsFinalizerCalled(const Napi::CallbackInfo& info) { + return Napi::Boolean::New(info.Env(), finalizerCalled); + } + + private: + Napi::FunctionReference finalizeCb_; + + static bool basicFinalizerCalled; + static bool finalizerCalled; +}; + +bool Test::basicFinalizerCalled = false; +bool Test::finalizerCalled = false; + +bool externalBasicFinalizerCalled = false; +bool externalFinalizerCalled = false; + +Napi::Value CreateExternalBasicFinalizer(const Napi::CallbackInfo& info) { + externalBasicFinalizerCalled = false; + return Napi::External::New( + info.Env(), new int(1), [](Napi::BasicEnv /*env*/, int* data) { + externalBasicFinalizerCalled = true; + delete data; + }); +} + +Napi::Value CreateExternalFinalizer(const Napi::CallbackInfo& info) { + externalFinalizerCalled = false; + return Napi::External::New( + info.Env(), new int(1), [](Napi::Env /*env*/, int* data) { + externalFinalizerCalled = true; + delete data; + }); +} + +Napi::Value isExternalBasicFinalizerCalled(const Napi::CallbackInfo& info) { + return Napi::Boolean::New(info.Env(), externalBasicFinalizerCalled); +} + +Napi::Value IsExternalFinalizerCalled(const Napi::CallbackInfo& info) { + return Napi::Boolean::New(info.Env(), externalFinalizerCalled); +} + +#ifdef NODE_API_EXPERIMENTAL_HAS_POST_FINALIZER +Napi::Value PostFinalizer(const Napi::CallbackInfo& info) { + auto env = info.Env(); + + env.PostFinalizer([callback = Napi::Persistent(info[0].As())]( + Napi::Env /*env*/) { callback.Call({}); }); + + return env.Undefined(); +} + +Napi::Value PostFinalizerWithData(const Napi::CallbackInfo& info) { + auto env = info.Env(); + + env.PostFinalizer( + [callback = Napi::Persistent(info[0].As())]( + Napi::Env /*env*/, Napi::Reference* data) { + callback.Call({data->Value()}); + delete data; + }, + new Napi::Reference(Napi::Persistent(info[1]))); + + return env.Undefined(); +} + +Napi::Value PostFinalizerWithDataAndHint(const Napi::CallbackInfo& info) { + auto env = info.Env(); + + env.PostFinalizer( + [callback = Napi::Persistent(info[0].As())]( + Napi::Env /*env*/, + Napi::Reference* data, + Napi::Reference* hint) { + callback.Call({data->Value(), hint->Value()}); + delete data; + delete hint; + }, + new Napi::Reference(Napi::Persistent(info[1])), + new Napi::Reference(Napi::Persistent(info[2]))); + + return env.Undefined(); +} +#endif + +} // namespace + +Napi::Object InitFinalizerOrder(Napi::Env env) { + Napi::Object exports = Napi::Object::New(env); + Test::Initialize(env, exports); + exports["createExternalBasicFinalizer"] = + Napi::Function::New(env, CreateExternalBasicFinalizer); + exports["createExternalFinalizer"] = + Napi::Function::New(env, CreateExternalFinalizer); + exports["isExternalBasicFinalizerCalled"] = + Napi::Function::New(env, isExternalBasicFinalizerCalled); + exports["isExternalFinalizerCalled"] = + Napi::Function::New(env, IsExternalFinalizerCalled); + +#ifdef NODE_API_EXPERIMENTAL_HAS_POST_FINALIZER + exports["PostFinalizer"] = Napi::Function::New(env, PostFinalizer); + exports["PostFinalizerWithData"] = + Napi::Function::New(env, PostFinalizerWithData); + exports["PostFinalizerWithDataAndHint"] = + Napi::Function::New(env, PostFinalizerWithDataAndHint); +#endif + return exports; +} diff --git a/test/finalizer_order.js b/test/finalizer_order.js new file mode 100644 index 000000000..4b267a0d0 --- /dev/null +++ b/test/finalizer_order.js @@ -0,0 +1,98 @@ +'use strict'; + +/* eslint-disable no-unused-vars */ + +const assert = require('assert'); +const common = require('./common'); +const testUtil = require('./testUtil'); + +module.exports = require('./common').runTest(test); + +function test (binding) { + const { isExperimental } = binding; + + let isCallbackCalled = false; + + const tests = [ + 'Finalizer Order - ObjectWrap', + () => { + let test = new binding.finalizer_order.Test(() => { isCallbackCalled = true; }); + test = null; + + global.gc(); + + if (isExperimental) { + assert.strictEqual(binding.finalizer_order.Test.isBasicFinalizerCalled, true, 'Expected basic finalizer to be called [before ticking]'); + assert.strictEqual(binding.finalizer_order.Test.isFinalizerCalled, false, 'Expected (extended) finalizer to not be called [before ticking]'); + assert.strictEqual(isCallbackCalled, false, 'Expected callback to not be called [before ticking]'); + } else { + assert.strictEqual(binding.finalizer_order.Test.isBasicFinalizerCalled, false, 'Expected basic finalizer to not be called [before ticking]'); + assert.strictEqual(binding.finalizer_order.Test.isFinalizerCalled, false, 'Expected (extended) finalizer to not be called [before ticking]'); + assert.strictEqual(isCallbackCalled, false, 'Expected callback to not be called [before ticking]'); + } + }, + () => { + assert.strictEqual(binding.finalizer_order.Test.isBasicFinalizerCalled, true, 'Expected basic finalizer to be called [after ticking]'); + assert.strictEqual(binding.finalizer_order.Test.isFinalizerCalled, true, 'Expected (extended) finalizer to be called [after ticking]'); + assert.strictEqual(isCallbackCalled, true, 'Expected callback to be called [after ticking]'); + }, + + 'Finalizer Order - External with Basic Finalizer', + () => { + let ext = binding.finalizer_order.createExternalBasicFinalizer(); + ext = null; + global.gc(); + + if (isExperimental) { + assert.strictEqual(binding.finalizer_order.isExternalBasicFinalizerCalled(), true, 'Expected External basic finalizer to be called [before ticking]'); + } else { + assert.strictEqual(binding.finalizer_order.isExternalBasicFinalizerCalled(), false, 'Expected External basic finalizer to not be called [before ticking]'); + } + }, + () => { + assert.strictEqual(binding.finalizer_order.isExternalBasicFinalizerCalled(), true, 'Expected External basic finalizer to be called [after ticking]'); + }, + + 'Finalizer Order - External with Finalizer', + () => { + let ext = binding.finalizer_order.createExternalFinalizer(); + ext = null; + global.gc(); + assert.strictEqual(binding.finalizer_order.isExternalFinalizerCalled(), false, 'Expected External extended finalizer to not be called [before ticking]'); + }, + () => { + assert.strictEqual(binding.finalizer_order.isExternalFinalizerCalled(), true, 'Expected External extended finalizer to be called [after ticking]'); + } + ]; + + if (binding.isExperimental) { + tests.push(...[ + 'PostFinalizer', + () => { + binding.finalizer_order.PostFinalizer(common.mustCall()); + }, + + 'PostFinalizerWithData', + () => { + const data = {}; + const callback = (callbackData) => { + assert.strictEqual(callbackData, data); + }; + binding.finalizer_order.PostFinalizerWithData(common.mustCall(callback), data); + }, + + 'PostFinalizerWithDataAndHint', + () => { + const data = {}; + const hint = {}; + const callback = (callbackData, callbackHint) => { + assert.strictEqual(callbackData, data); + assert.strictEqual(callbackHint, hint); + }; + binding.finalizer_order.PostFinalizerWithDataAndHint(common.mustCall(callback), data, hint); + } + ]); + } + + return testUtil.runGCTests(tests); +} diff --git a/test/function.js b/test/function.js index 04b020394..c5514db36 100644 --- a/test/function.js +++ b/test/function.js @@ -18,7 +18,7 @@ function test (binding) { assert.deepStrictEqual(binding.valueCallback(), { foo: 'bar' }); - /* eslint-disable-next-line no-new, new-cap */ + /* eslint-disable-next-line new-cap */ assert.strictEqual(new binding.newTargetCallback(), binding.newTargetCallback); assert.strictEqual(binding.newTargetCallback(), undefined); @@ -89,7 +89,7 @@ function test (binding) { assert.deepStrictEqual(args, [7, 8, 9]); assert.throws(() => { - binding.callWithInvalidReceiver(); + binding.callWithInvalidReceiver(() => {}); }, /Invalid (pointer passed as )?argument/); obj = binding.callConstructorWithArgs(testConstructor, 5, 6, 7); diff --git a/test/function_reference.cc b/test/function_reference.cc index a25119846..b50eb46fd 100644 --- a/test/function_reference.cc +++ b/test/function_reference.cc @@ -30,17 +30,17 @@ class FuncRefObject : public Napi::ObjectWrap { namespace { Value ConstructRefFromExisitingRef(const CallbackInfo& info) { - HandleScope scope(info.Env()); + EscapableHandleScope scope(info.Env()); FunctionReference ref; FunctionReference movedRef; ref.Reset(info[0].As()); movedRef = std::move(ref); - return MaybeUnwrap(movedRef({})); + return scope.Escape(MaybeUnwrap(movedRef({}))); } Value CallWithVectorArgs(const CallbackInfo& info) { - HandleScope scope(info.Env()); + EscapableHandleScope scope(info.Env()); std::vector newVec; FunctionReference ref; ref.Reset(info[0].As()); @@ -48,27 +48,28 @@ Value CallWithVectorArgs(const CallbackInfo& info) { for (int i = 1; i < (int)info.Length(); i++) { newVec.push_back(info[i]); } - return MaybeUnwrap(ref.Call(newVec)); + return scope.Escape(MaybeUnwrap(ref.Call(newVec))); } Value CallWithInitList(const CallbackInfo& info) { - HandleScope scope(info.Env()); + EscapableHandleScope scope(info.Env()); FunctionReference ref; ref.Reset(info[0].As()); - return MaybeUnwrap(ref.Call({info[1], info[2], info[3]})); + return scope.Escape(MaybeUnwrap(ref.Call({info[1], info[2], info[3]}))); } Value CallWithRecvInitList(const CallbackInfo& info) { - HandleScope scope(info.Env()); + EscapableHandleScope scope(info.Env()); FunctionReference ref; ref.Reset(info[0].As()); - return MaybeUnwrap(ref.Call(info[1], {info[2], info[3], info[4]})); + return scope.Escape( + MaybeUnwrap(ref.Call(info[1], {info[2], info[3], info[4]}))); } Value CallWithRecvVector(const CallbackInfo& info) { - HandleScope scope(info.Env()); + EscapableHandleScope scope(info.Env()); FunctionReference ref; std::vector newVec; ref.Reset(info[0].As()); @@ -76,22 +77,22 @@ Value CallWithRecvVector(const CallbackInfo& info) { for (int i = 2; i < (int)info.Length(); i++) { newVec.push_back(info[i]); } - return MaybeUnwrap(ref.Call(info[1], newVec)); + return scope.Escape(MaybeUnwrap(ref.Call(info[1], newVec))); } Value CallWithRecvArgc(const CallbackInfo& info) { - HandleScope scope(info.Env()); + EscapableHandleScope scope(info.Env()); FunctionReference ref; - int argLength = info.Length() - 2; - napi_value* args = new napi_value[argLength]; ref.Reset(info[0].As()); - int argIdx = 0; - for (int i = 2; i < (int)info.Length(); i++, argIdx++) { - args[argIdx] = info[i]; + size_t argLength = info.Length() > 2 ? info.Length() - 2 : 0; + std::unique_ptr args{argLength > 0 ? new napi_value[argLength] + : nullptr}; + for (size_t i = 0; i < argLength; ++i) { + args[i] = info[i + 2]; } - return MaybeUnwrap(ref.Call(info[1], argLength, args)); + return scope.Escape(MaybeUnwrap(ref.Call(info[1], argLength, args.get()))); } Value MakeAsyncCallbackWithInitList(const Napi::CallbackInfo& info) { @@ -121,17 +122,19 @@ Value MakeAsyncCallbackWithVector(const Napi::CallbackInfo& info) { Value MakeAsyncCallbackWithArgv(const Napi::CallbackInfo& info) { Napi::FunctionReference ref; ref.Reset(info[0].As()); - int argLength = info.Length() - 1; - napi_value* args = new napi_value[argLength]; - int argIdx = 0; - for (int i = 1; i < (int)info.Length(); i++, argIdx++) { - args[argIdx] = info[i]; + size_t argLength = info.Length() > 1 ? info.Length() - 1 : 0; + std::unique_ptr args{argLength > 0 ? new napi_value[argLength] + : nullptr}; + for (size_t i = 0; i < argLength; ++i) { + args[i] = info[i + 1]; } Napi::AsyncContext context(info.Env(), "func_ref_resources", {}); - return MaybeUnwrap(ref.MakeCallback( - Napi::Object::New(info.Env()), argLength, args, context)); + return MaybeUnwrap(ref.MakeCallback(Napi::Object::New(info.Env()), + argLength, + argLength > 0 ? args.get() : nullptr, + context)); } Value CreateFunctionReferenceUsingNew(const Napi::CallbackInfo& info) { @@ -161,19 +164,19 @@ Value CreateFunctionReferenceUsingNewVec(const Napi::CallbackInfo& info) { } Value Call(const CallbackInfo& info) { - HandleScope scope(info.Env()); + EscapableHandleScope scope(info.Env()); FunctionReference ref; ref.Reset(info[0].As()); - return MaybeUnwrapOr(ref.Call({}), Value()); + return scope.Escape(MaybeUnwrapOr(ref.Call({}), Value())); } Value Construct(const CallbackInfo& info) { - HandleScope scope(info.Env()); + EscapableHandleScope scope(info.Env()); FunctionReference ref; ref.Reset(info[0].As()); - return MaybeUnwrapOr(ref.New({}), Object()); + return scope.Escape(MaybeUnwrapOr(ref.New({}), Object())); } } // namespace diff --git a/test/function_reference.js b/test/function_reference.js index 84263fce9..e69fc8e5b 100644 --- a/test/function_reference.js +++ b/test/function_reference.js @@ -95,7 +95,7 @@ async function canCallAsyncFunctionWithDifferentOverloads (binding) { { eventName: 'init', type: 'func_ref_resources', - triggerAsyncId: triggerAsyncId, + triggerAsyncId, resource: {} }, { eventName: 'before' }, @@ -113,7 +113,7 @@ async function canCallAsyncFunctionWithDifferentOverloads (binding) { { eventName: 'init', type: 'func_ref_resources', - triggerAsyncId: triggerAsyncId, + triggerAsyncId, resource: {} }, { eventName: 'before' }, diff --git a/test/globalObject/global_object_delete_property.cc b/test/globalObject/global_object_delete_property.cc index 295ed3f36..70738c2f4 100644 --- a/test/globalObject/global_object_delete_property.cc +++ b/test/globalObject/global_object_delete_property.cc @@ -5,27 +5,27 @@ using namespace Napi; Value DeletePropertyWithCStyleStringAsKey(const CallbackInfo& info) { Object globalObject = info.Env().Global(); - String key = info[0].As(); + String key = info[0].UnsafeAs(); return Boolean::New( info.Env(), MaybeUnwrap(globalObject.Delete(key.Utf8Value().c_str()))); } Value DeletePropertyWithCppStyleStringAsKey(const CallbackInfo& info) { Object globalObject = info.Env().Global(); - String key = info[0].As(); + String key = info[0].UnsafeAs(); return Boolean::New(info.Env(), MaybeUnwrap(globalObject.Delete(key.Utf8Value()))); } Value DeletePropertyWithInt32AsKey(const CallbackInfo& info) { Object globalObject = info.Env().Global(); - Number key = info[0].As(); + Number key = info[0].UnsafeAs(); return Boolean::New(info.Env(), MaybeUnwrap(globalObject.Delete(key.Uint32Value()))); } Value DeletePropertyWithNapiValueAsKey(const CallbackInfo& info) { Object globalObject = info.Env().Global(); - Name key = info[0].As(); + Name key = info[0].UnsafeAs(); return Boolean::New(info.Env(), MaybeUnwrap(globalObject.Delete(key))); } diff --git a/test/globalObject/global_object_get_property.cc b/test/globalObject/global_object_get_property.cc index dd112043c..81f727d91 100644 --- a/test/globalObject/global_object_get_property.cc +++ b/test/globalObject/global_object_get_property.cc @@ -5,25 +5,25 @@ using namespace Napi; Value GetPropertyWithNapiValueAsKey(const CallbackInfo& info) { Object globalObject = info.Env().Global(); - Name key = info[0].As(); + Name key = info[0].UnsafeAs(); return MaybeUnwrap(globalObject.Get(key)); } Value GetPropertyWithInt32AsKey(const CallbackInfo& info) { Object globalObject = info.Env().Global(); - Number key = info[0].As(); + Number key = info[0].UnsafeAs(); return MaybeUnwrapOr(globalObject.Get(key.Uint32Value()), Value()); } Value GetPropertyWithCStyleStringAsKey(const CallbackInfo& info) { Object globalObject = info.Env().Global(); - String cStrkey = info[0].As(); + String cStrkey = info[0].UnsafeAs(); return MaybeUnwrapOr(globalObject.Get(cStrkey.Utf8Value().c_str()), Value()); } Value GetPropertyWithCppStyleStringAsKey(const CallbackInfo& info) { Object globalObject = info.Env().Global(); - String cppStrKey = info[0].As(); + String cppStrKey = info[0].UnsafeAs(); return MaybeUnwrapOr(globalObject.Get(cppStrKey.Utf8Value()), Value()); } diff --git a/test/globalObject/global_object_has_own_property.cc b/test/globalObject/global_object_has_own_property.cc index 89c299913..388788d97 100644 --- a/test/globalObject/global_object_has_own_property.cc +++ b/test/globalObject/global_object_has_own_property.cc @@ -5,7 +5,7 @@ using namespace Napi; Value HasPropertyWithCStyleStringAsKey(const CallbackInfo& info) { Object globalObject = info.Env().Global(); - String key = info[0].As(); + String key = info[0].UnsafeAs(); return Boolean::New( info.Env(), MaybeUnwrapOr(globalObject.HasOwnProperty(key.Utf8Value().c_str()), @@ -14,7 +14,7 @@ Value HasPropertyWithCStyleStringAsKey(const CallbackInfo& info) { Value HasPropertyWithCppStyleStringAsKey(const CallbackInfo& info) { Object globalObject = info.Env().Global(); - String key = info[0].As(); + String key = info[0].UnsafeAs(); return Boolean::New( info.Env(), MaybeUnwrapOr(globalObject.HasOwnProperty(key.Utf8Value()), false)); @@ -22,7 +22,7 @@ Value HasPropertyWithCppStyleStringAsKey(const CallbackInfo& info) { Value HasPropertyWithNapiValueAsKey(const CallbackInfo& info) { Object globalObject = info.Env().Global(); - Name key = info[0].As(); + Name key = info[0].UnsafeAs(); return Boolean::New(info.Env(), MaybeUnwrap(globalObject.HasOwnProperty(key))); } diff --git a/test/globalObject/global_object_set_property.cc b/test/globalObject/global_object_set_property.cc index 7065bee56..06da6315a 100644 --- a/test/globalObject/global_object_set_property.cc +++ b/test/globalObject/global_object_set_property.cc @@ -4,28 +4,28 @@ using namespace Napi; void SetPropertyWithCStyleStringAsKey(const CallbackInfo& info) { Object globalObject = info.Env().Global(); - String key = info[0].As(); + String key = info[0].UnsafeAs(); Value value = info[1]; globalObject.Set(key.Utf8Value().c_str(), value); } void SetPropertyWithCppStyleStringAsKey(const CallbackInfo& info) { Object globalObject = info.Env().Global(); - String key = info[0].As(); + String key = info[0].UnsafeAs(); Value value = info[1]; globalObject.Set(key.Utf8Value(), value); } void SetPropertyWithInt32AsKey(const CallbackInfo& info) { Object globalObject = info.Env().Global(); - Number key = info[0].As(); + Number key = info[0].UnsafeAs(); Value value = info[1]; globalObject.Set(key.Uint32Value(), value); } void SetPropertyWithNapiValueAsKey(const CallbackInfo& info) { Object globalObject = info.Env().Global(); - Name key = info[0].As(); + Name key = info[0].UnsafeAs(); Value value = info[1]; globalObject.Set(key, value); -} \ No newline at end of file +} diff --git a/test/handlescope.cc b/test/handlescope.cc index 1c7bda393..c68c1c3fa 100644 --- a/test/handlescope.cc +++ b/test/handlescope.cc @@ -13,6 +13,16 @@ Value createScope(const CallbackInfo& info) { return String::New(info.Env(), "scope"); } +Value createScopeFromExisting(const CallbackInfo& info) { + { + napi_handle_scope scope; + napi_open_handle_scope(info.Env(), &scope); + HandleScope scope_existing(info.Env(), scope); + String::New(scope_existing.Env(), "inner-existing-scope"); + } + return String::New(info.Env(), "existing_scope"); +} + Value escapeFromScope(const CallbackInfo& info) { Value result; { @@ -22,6 +32,18 @@ Value escapeFromScope(const CallbackInfo& info) { return result; } +Value escapeFromExistingScope(const CallbackInfo& info) { + Value result; + { + napi_escapable_handle_scope scope; + napi_open_escapable_handle_scope(info.Env(), &scope); + EscapableHandleScope scope_existing(info.Env(), scope); + result = scope_existing.Escape( + String::New(scope_existing.Env(), "inner-existing-scope")); + } + return result; +} + #define LOOP_MAX 1000000 Value stressEscapeFromScope(const CallbackInfo& info) { Value result; @@ -52,7 +74,11 @@ Object InitHandleScope(Env env) { Object exports = Object::New(env); exports["createScope"] = Function::New(env, createScope); + exports["createScopeFromExisting"] = + Function::New(env, createScopeFromExisting); exports["escapeFromScope"] = Function::New(env, escapeFromScope); + exports["escapeFromExistingScope"] = + Function::New(env, escapeFromExistingScope); exports["stressEscapeFromScope"] = Function::New(env, stressEscapeFromScope); exports["doubleEscapeFromScope"] = Function::New(env, doubleEscapeFromScope); diff --git a/test/handlescope.js b/test/handlescope.js index e216600ec..ad45f9503 100644 --- a/test/handlescope.js +++ b/test/handlescope.js @@ -6,7 +6,9 @@ module.exports = require('./common').runTest(test); function test (binding) { assert.strictEqual(binding.handlescope.createScope(), 'scope'); + assert.strictEqual(binding.handlescope.createScopeFromExisting(), 'existing_scope'); assert.strictEqual(binding.handlescope.escapeFromScope(), 'inner-scope'); + assert.strictEqual(binding.handlescope.escapeFromExistingScope(), 'inner-existing-scope'); assert.strictEqual(binding.handlescope.stressEscapeFromScope(), 'inner-scope999999'); assert.throws(() => binding.handlescope.doubleEscapeFromScope(), Error, diff --git a/test/index.js b/test/index.js index 8880e4702..f0c034584 100644 --- a/test/index.js +++ b/test/index.js @@ -60,6 +60,7 @@ function loadTestModules (currentDirectory = __dirname, pre = '') { file === 'binding.gyp' || file === 'build' || file === 'common' || + file === 'child_processes' || file === 'napi_child.js' || file === 'testUtil.js' || file === 'thunking_manual.cc' || @@ -134,6 +135,11 @@ if (majorNodeVersion < 12 && !filterConditionsProvided) { if (napiVersion < 8 && !filterConditionsProvided) { testModules.splice(testModules.indexOf('object/object_freeze_seal'), 1); + testModules.splice(testModules.indexOf('type_taggable'), 1); +} + +if (napiVersion < 9 && !filterConditionsProvided) { + testModules.splice(testModules.indexOf('env_misc'), 1); } (async function () { diff --git a/test/maybe/check.cc b/test/maybe/check.cc index d1e2261ed..74acf7e38 100644 --- a/test/maybe/check.cc +++ b/test/maybe/check.cc @@ -1,3 +1,4 @@ +#include "assert.h" #include "napi.h" #if defined(NODE_ADDON_API_ENABLE_MAYBE) @@ -6,11 +7,52 @@ using namespace Napi; namespace { void VoidCallback(const CallbackInfo& info) { - Function fn = info[0].As(); + Napi::Function fn = info[0].As(); + Maybe ret = fn.Call({}); - Maybe it = fn.Call({}); + assert(ret.IsNothing() == true); + assert(ret.IsJust() == false); - it.Check(); + Napi::Value placeHolder = Napi::Number::New(info.Env(), 12345); + Napi::Value unwrappedValue = ret.UnwrapOr(placeHolder); + + assert(unwrappedValue.As().Uint32Value() == 12345); + + assert(ret.UnwrapTo(&placeHolder) == false); + assert(placeHolder.As().Uint32Value() == 12345); + + ret.Check(); +} + +void TestMaybeOperatorOverload(const CallbackInfo& info) { + Napi::Function fn_a = info[0].As(); + Napi::Function fn_b = info[1].As(); + + assert(fn_a.Call({}) == fn_a.Call({})); + assert(fn_a.Call({}) != fn_b.Call({})); +} + +void NormalJsCallback(const CallbackInfo& info) { + Napi::Function fn = info[0].As(); + uint32_t magic_number = info[1].As().Uint32Value(); + + Maybe ret = fn.Call({}); + + assert(ret.IsNothing() == false); + assert(ret.IsJust() == true); + + Napi::Value unwrappedValue = ret.Unwrap(); + assert(unwrappedValue.IsNumber() == true); + + assert(unwrappedValue.As().Uint32Value() == magic_number); + + unwrappedValue = + ret.UnwrapOr(Napi::Number::New(info.Env(), magic_number - 1)); + assert(unwrappedValue.As().Uint32Value() == magic_number); + + Napi::Value placeHolder = Napi::Number::New(info.Env(), magic_number - 1); + assert(ret.UnwrapTo(&placeHolder) == true); + assert(placeHolder.As().Uint32Value() == magic_number); } } // end anonymous namespace @@ -18,6 +60,10 @@ void VoidCallback(const CallbackInfo& info) { Object InitMaybeCheck(Env env) { Object exports = Object::New(env); exports.Set("voidCallback", Function::New(env, VoidCallback)); + exports.Set("normalJsCallback", Function::New(env, NormalJsCallback)); + exports.Set("testMaybeOverloadOp", + Function::New(env, TestMaybeOperatorOverload)); return exports; } + #endif diff --git a/test/maybe/index.js b/test/maybe/index.js index dcd062d35..65f8643c2 100644 --- a/test/maybe/index.js +++ b/test/maybe/index.js @@ -1,11 +1,14 @@ 'use strict'; -const buildType = process.config.target_defaults.default_configuration; const assert = require('assert'); +const { whichBuildType } = require('../common'); const napiChild = require('../napi_child'); -module.exports = test(require(`../build/${buildType}/binding_noexcept_maybe.node`).maybe_check); +module.exports = async function wrapTest () { + const buildType = await whichBuildType(); + test(require(`../build/${buildType}/binding_noexcept_maybe.node`).maybe_check); +}; function test (binding) { if (process.argv.includes('child')) { @@ -31,6 +34,16 @@ function test (binding) { } function child (binding) { + const MAGIC_NUMBER = 12459062; + binding.normalJsCallback(() => { + return MAGIC_NUMBER; + }, MAGIC_NUMBER); + + binding.testMaybeOverloadOp( + () => { return MAGIC_NUMBER; }, + () => { throw Error('Foobar'); } + ); + binding.voidCallback(() => { throw new Error('foobar'); }); diff --git a/test/name.cc b/test/name.cc index d8556e154..d94a3937f 100644 --- a/test/name.cc +++ b/test/name.cc @@ -1,5 +1,7 @@ #include "napi.h" +#include + using namespace Napi; const char* testValueUtf8 = "123456789"; @@ -21,19 +23,21 @@ Value EchoString(const CallbackInfo& info) { Value CreateString(const CallbackInfo& info) { String encoding = info[0].As(); - Number length = info[1].As(); + Value length = info[1]; if (encoding.Utf8Value() == "utf8") { if (length.IsUndefined()) { return String::New(info.Env(), testValueUtf8); } else { - return String::New(info.Env(), testValueUtf8, length.Uint32Value()); + return String::New( + info.Env(), testValueUtf8, length.As().Uint32Value()); } } else if (encoding.Utf8Value() == "utf16") { if (length.IsUndefined()) { return String::New(info.Env(), testValueUtf16); } else { - return String::New(info.Env(), testValueUtf16, length.Uint32Value()); + return String::New( + info.Env(), testValueUtf16, length.As().Uint32Value()); } } else { Error::New(info.Env(), "Invalid encoding.").ThrowAsJavaScriptException(); @@ -41,15 +45,19 @@ Value CreateString(const CallbackInfo& info) { } } +Value CreateStringFromStringView(const CallbackInfo& info) { + return String::New(info.Env(), std::string_view("hello1")); +} + Value CheckString(const CallbackInfo& info) { String value = info[0].As(); String encoding = info[1].As(); - Number length = info[2].As(); + Value length = info[2]; if (encoding.Utf8Value() == "utf8") { std::string testValue = testValueUtf8; if (!length.IsUndefined()) { - testValue = testValue.substr(0, length.Uint32Value()); + testValue = testValue.substr(0, length.As().Uint32Value()); } std::string stringValue = value; @@ -57,7 +65,7 @@ Value CheckString(const CallbackInfo& info) { } else if (encoding.Utf8Value() == "utf16") { std::u16string testValue = testValueUtf16; if (!length.IsUndefined()) { - testValue = testValue.substr(0, length.Uint32Value()); + testValue = testValue.substr(0, length.As().Uint32Value()); } std::u16string stringValue = value; @@ -69,15 +77,19 @@ Value CheckString(const CallbackInfo& info) { } Value CreateSymbol(const CallbackInfo& info) { - String description = info[0].As(); + Value description = info[0]; if (!description.IsUndefined()) { - return Symbol::New(info.Env(), description); + return Symbol::New(info.Env(), description.As()); } else { return Symbol::New(info.Env()); } } +Value CreateSymbolFromStringView(const CallbackInfo& info) { + return Symbol::New(info.Env(), std::string_view("hello2")); +} + Value CheckSymbol(const CallbackInfo& info) { return Boolean::New(info.Env(), info[0].Type() == napi_symbol); } @@ -97,11 +109,15 @@ Object InitName(Env env) { exports["echoString"] = Function::New(env, EchoString); exports["createString"] = Function::New(env, CreateString); + exports["createStringFromStringView"] = + Function::New(env, CreateStringFromStringView); exports["nullStringShouldThrow"] = Function::New(env, NullStringShouldThrow); exports["nullString16ShouldThrow"] = Function::New(env, NullString16ShouldThrow); exports["checkString"] = Function::New(env, CheckString); exports["createSymbol"] = Function::New(env, CreateSymbol); + exports["createSymbolFromStringView"] = + Function::New(env, CreateSymbolFromStringView); exports["checkSymbol"] = Function::New(env, CheckSymbol); return exports; diff --git a/test/name.js b/test/name.js index 406c533e3..8113565c8 100644 --- a/test/name.js +++ b/test/name.js @@ -56,4 +56,9 @@ function test (binding) { assert.strictEqual(binding.name.echoString(str, 'utf8'), str); assert.strictEqual(binding.name.echoString(str, 'utf16'), str); } + + assert.strictEqual(binding.name.createStringFromStringView(), 'hello1'); + const symFromStringView = binding.name.createSymbolFromStringView(); + assert.strictEqual(typeof symFromStringView, 'symbol'); + assert.strictEqual(symFromStringView.description, 'hello2'); } diff --git a/test/object/delete_property.cc b/test/object/delete_property.cc index ca69e5387..b05af20cc 100644 --- a/test/object/delete_property.cc +++ b/test/object/delete_property.cc @@ -4,13 +4,13 @@ using namespace Napi; Value DeletePropertyWithUint32(const CallbackInfo& info) { - Object obj = info[0].As(); + Object obj = info[0].UnsafeAs(); Number key = info[1].As(); return Boolean::New(info.Env(), MaybeUnwrap(obj.Delete(key.Uint32Value()))); } Value DeletePropertyWithNapiValue(const CallbackInfo& info) { - Object obj = info[0].As(); + Object obj = info[0].UnsafeAs(); Name key = info[1].As(); return Boolean::New( info.Env(), @@ -18,20 +18,20 @@ Value DeletePropertyWithNapiValue(const CallbackInfo& info) { } Value DeletePropertyWithNapiWrapperValue(const CallbackInfo& info) { - Object obj = info[0].As(); + Object obj = info[0].UnsafeAs(); Name key = info[1].As(); return Boolean::New(info.Env(), MaybeUnwrapOr(obj.Delete(key), false)); } Value DeletePropertyWithCStyleString(const CallbackInfo& info) { - Object obj = info[0].As(); + Object obj = info[0].UnsafeAs(); String jsKey = info[1].As(); return Boolean::New( info.Env(), MaybeUnwrapOr(obj.Delete(jsKey.Utf8Value().c_str()), false)); } Value DeletePropertyWithCppStyleString(const CallbackInfo& info) { - Object obj = info[0].As(); + Object obj = info[0].UnsafeAs(); String jsKey = info[1].As(); return Boolean::New(info.Env(), MaybeUnwrapOr(obj.Delete(jsKey.Utf8Value()), false)); diff --git a/test/object/get_property.cc b/test/object/get_property.cc index 523f99199..2791ad2aa 100644 --- a/test/object/get_property.cc +++ b/test/object/get_property.cc @@ -4,31 +4,31 @@ using namespace Napi; Value GetPropertyWithNapiValue(const CallbackInfo& info) { - Object obj = info[0].As(); + Object obj = info[0].UnsafeAs(); Name key = info[1].As(); return MaybeUnwrapOr(obj.Get(static_cast(key)), Value()); } Value GetPropertyWithNapiWrapperValue(const CallbackInfo& info) { - Object obj = info[0].As(); + Object obj = info[0].UnsafeAs(); Name key = info[1].As(); return MaybeUnwrapOr(obj.Get(key), Value()); } Value GetPropertyWithUint32(const CallbackInfo& info) { - Object obj = info[0].As(); + Object obj = info[0].UnsafeAs(); Number key = info[1].As(); return MaybeUnwrap(obj.Get(key.Uint32Value())); } Value GetPropertyWithCStyleString(const CallbackInfo& info) { - Object obj = info[0].As(); + Object obj = info[0].UnsafeAs(); String jsKey = info[1].As(); return MaybeUnwrapOr(obj.Get(jsKey.Utf8Value().c_str()), Value()); } Value GetPropertyWithCppStyleString(const CallbackInfo& info) { - Object obj = info[0].As(); + Object obj = info[0].UnsafeAs(); String jsKey = info[1].As(); return MaybeUnwrapOr(obj.Get(jsKey.Utf8Value()), Value()); } diff --git a/test/object/has_own_property.cc b/test/object/has_own_property.cc index d7fbde98b..b566fefbb 100644 --- a/test/object/has_own_property.cc +++ b/test/object/has_own_property.cc @@ -4,7 +4,7 @@ using namespace Napi; Value HasOwnPropertyWithNapiValue(const CallbackInfo& info) { - Object obj = info[0].As(); + Object obj = info[0].UnsafeAs(); Name key = info[1].As(); return Boolean::New( info.Env(), @@ -12,14 +12,14 @@ Value HasOwnPropertyWithNapiValue(const CallbackInfo& info) { } Value HasOwnPropertyWithNapiWrapperValue(const CallbackInfo& info) { - Object obj = info[0].As(); + Object obj = info[0].UnsafeAs(); Name key = info[1].As(); return Boolean::New(info.Env(), MaybeUnwrapOr(obj.HasOwnProperty(key), false)); } Value HasOwnPropertyWithCStyleString(const CallbackInfo& info) { - Object obj = info[0].As(); + Object obj = info[0].UnsafeAs(); String jsKey = info[1].As(); return Boolean::New( info.Env(), @@ -27,7 +27,7 @@ Value HasOwnPropertyWithCStyleString(const CallbackInfo& info) { } Value HasOwnPropertyWithCppStyleString(const CallbackInfo& info) { - Object obj = info[0].As(); + Object obj = info[0].UnsafeAs(); String jsKey = info[1].As(); return Boolean::New( info.Env(), MaybeUnwrapOr(obj.HasOwnProperty(jsKey.Utf8Value()), false)); diff --git a/test/object/has_property.cc b/test/object/has_property.cc index fa410833f..46c13de30 100644 --- a/test/object/has_property.cc +++ b/test/object/has_property.cc @@ -4,34 +4,34 @@ using namespace Napi; Value HasPropertyWithNapiValue(const CallbackInfo& info) { - Object obj = info[0].As(); + Object obj = info[0].UnsafeAs(); Name key = info[1].As(); return Boolean::New( info.Env(), MaybeUnwrapOr(obj.Has(static_cast(key)), false)); } Value HasPropertyWithNapiWrapperValue(const CallbackInfo& info) { - Object obj = info[0].As(); + Object obj = info[0].UnsafeAs(); Name key = info[1].As(); return Boolean::New(info.Env(), MaybeUnwrapOr(obj.Has(key), false)); } Value HasPropertyWithCStyleString(const CallbackInfo& info) { - Object obj = info[0].As(); + Object obj = info[0].UnsafeAs(); String jsKey = info[1].As(); return Boolean::New(info.Env(), MaybeUnwrapOr(obj.Has(jsKey.Utf8Value().c_str()), false)); } Value HasPropertyWithUint32(const CallbackInfo& info) { - Object obj = info[0].As(); + Object obj = info[0].UnsafeAs(); Number jsKey = info[1].As(); return Boolean::New(info.Env(), MaybeUnwrapOr(obj.Has(jsKey.Uint32Value()), false)); } Value HasPropertyWithCppStyleString(const CallbackInfo& info) { - Object obj = info[0].As(); + Object obj = info[0].UnsafeAs(); String jsKey = info[1].As(); return Boolean::New(info.Env(), MaybeUnwrapOr(obj.Has(jsKey.Utf8Value()), false)); diff --git a/test/object/object.cc b/test/object/object.cc index f6f0bd98b..60aae768f 100644 --- a/test/object/object.cc +++ b/test/object/object.cc @@ -338,11 +338,24 @@ void Increment(const CallbackInfo& info) { #endif // NAPI_CPP_EXCEPTIONS Value InstanceOf(const CallbackInfo& info) { - Object obj = info[0].As(); + Object obj = info[0].UnsafeAs(); Function constructor = info[1].As(); return Boolean::New(info.Env(), MaybeUnwrap(obj.InstanceOf(constructor))); } +Value GetPrototype(const CallbackInfo& info) { + Object obj = info[0].UnsafeAs(); + return MaybeUnwrap(obj.GetPrototype()); +} + +#ifdef NODE_API_EXPERIMENTAL_HAS_SET_PROTOTYPE +Value SetPrototype(const CallbackInfo& info) { + Object obj = info[0].UnsafeAs(); + Object prototype = info[1].UnsafeAs(); + return Boolean::New(info.Env(), MaybeUnwrap(obj.SetPrototype(prototype))); +} +#endif // NODE_API_EXPERIMENTAL_HAS_SET_PROTOTYPE + Object InitObject(Env env) { Object exports = Object::New(env); @@ -426,5 +439,10 @@ Object InitObject(Env env) { Function::New(env, SubscriptSetWithCppStyleString); exports["subscriptSetAtIndex"] = Function::New(env, SubscriptSetAtIndex); + exports["getPrototype"] = Function::New(env, GetPrototype); +#ifdef NODE_API_EXPERIMENTAL_HAS_SET_PROTOTYPE + exports["setPrototype"] = Function::New(env, SetPrototype); +#endif // NODE_API_EXPERIMENTAL_HAS_SET_PROTOTYPE + return exports; } diff --git a/test/object/object.js b/test/object/object.js index 6cd9735e9..13488940c 100644 --- a/test/object/object.js +++ b/test/object/object.js @@ -215,4 +215,16 @@ function test (binding) { c: 3 }); } + + for (const prototype of [null, {}, Object.prototype]) { + const obj = Object.create(prototype); + assert.strictEqual(binding.object.getPrototype(obj), prototype); + } + + if ('setPrototype' in binding.object) { + const prototype = {}; + const obj = Object.create(null); + assert.strictEqual(binding.object.setPrototype(obj, prototype), true); + assert.strictEqual(Object.getPrototypeOf(obj), prototype); + } } diff --git a/test/object/set_property.cc b/test/object/set_property.cc index 8171568d6..da8c93bbd 100644 --- a/test/object/set_property.cc +++ b/test/object/set_property.cc @@ -4,7 +4,7 @@ using namespace Napi; Value SetPropertyWithNapiValue(const CallbackInfo& info) { - Object obj = info[0].As(); + Object obj = info[0].UnsafeAs(); Name key = info[1].As(); Value value = info[2]; return Boolean::New( @@ -13,14 +13,14 @@ Value SetPropertyWithNapiValue(const CallbackInfo& info) { } Value SetPropertyWithNapiWrapperValue(const CallbackInfo& info) { - Object obj = info[0].As(); + Object obj = info[0].UnsafeAs(); Name key = info[1].As(); Value value = info[2]; return Boolean::New(info.Env(), MaybeUnwrapOr(obj.Set(key, value), false)); } Value SetPropertyWithUint32(const CallbackInfo& info) { - Object obj = info[0].As(); + Object obj = info[0].UnsafeAs(); Number key = info[1].As(); Value value = info[2]; return Boolean::New(info.Env(), @@ -28,7 +28,7 @@ Value SetPropertyWithUint32(const CallbackInfo& info) { } Value SetPropertyWithCStyleString(const CallbackInfo& info) { - Object obj = info[0].As(); + Object obj = info[0].UnsafeAs(); String jsKey = info[1].As(); Value value = info[2]; return Boolean::New( @@ -37,7 +37,7 @@ Value SetPropertyWithCStyleString(const CallbackInfo& info) { } Value SetPropertyWithCppStyleString(const CallbackInfo& info) { - Object obj = info[0].As(); + Object obj = info[0].UnsafeAs(); String jsKey = info[1].As(); Value value = info[2]; return Boolean::New(info.Env(), diff --git a/test/object/subscript_operator.cc b/test/object/subscript_operator.cc index 7f94b2dd3..15bb74620 100644 --- a/test/object/subscript_operator.cc +++ b/test/object/subscript_operator.cc @@ -8,7 +8,7 @@ Value SubscriptGetWithCStyleString(const CallbackInfo& info) { // make sure const case compiles const Object obj2 = info[0].As(); - MaybeUnwrap(obj2[jsKey.Utf8Value().c_str()]).As(); + MaybeUnwrap(obj2[jsKey.Utf8Value().c_str()]).As(); Object obj = info[0].As(); return obj[jsKey.Utf8Value().c_str()]; @@ -19,7 +19,7 @@ Value SubscriptGetWithCppStyleString(const CallbackInfo& info) { // make sure const case compiles const Object obj2 = info[0].As(); - MaybeUnwrap(obj2[jsKey.Utf8Value()]).As(); + MaybeUnwrap(obj2[jsKey.Utf8Value()]).As(); Object obj = info[0].As(); return obj[jsKey.Utf8Value()]; @@ -30,7 +30,7 @@ Value SubscriptGetAtIndex(const CallbackInfo& info) { // make sure const case compiles const Object obj2 = info[0].As(); - MaybeUnwrap(obj2[index]).As(); + MaybeUnwrap(obj2[index]).As(); Object obj = info[0].As(); return obj[index]; diff --git a/test/object_reference.cc b/test/object_reference.cc index 34f952088..691b5f63d 100644 --- a/test/object_reference.cc +++ b/test/object_reference.cc @@ -2,7 +2,7 @@ are not Objects by creating a blank Object and setting Values to it. Subclasses of Objects can only be set using an ObjectReference by first casting it as an Object. */ - +#include "assert.h" #include "napi.h" #include "test_helper.h" @@ -16,11 +16,165 @@ ObjectReference casted_weak; ObjectReference casted_persistent; ObjectReference casted_reference; -// info[0] is the key, which can be either a string or a number. -// info[1] is the value. -// info[2] is a flag that differentiates whether the key is a -// C string or a JavaScript string. -void SetObjects(const CallbackInfo& info) { +// Set keys can be one of: +// C style string, std::string& utf8, and const char * + +// Set values can be one of: +// Napi::Value +// napi_value (req static_cast) +// const char* (c style string) +// boolean +// double + +enum VAL_TYPES { JS = 0, C_STR, CPP_STR, BOOL, INT, DOUBLE, JS_CAST }; + +// Test that Set() with std::string key and value accepts temporaries (rvalues). +// This verifies that the parameter is `const std::string&` rather than +// `std::string&`. +void SetWithTempString(const Napi::CallbackInfo& info) { + Env env = info.Env(); + HandleScope scope(env); + + Napi::ObjectReference ref = Persistent(Object::New(env)); + ref.SuppressDestruct(); + + ref.Set(std::string("tempKey"), std::string("tempValue")); + ref.Set(std::string("anotherKey"), info[0].As().Utf8Value()); + + assert(MaybeUnwrap(ref.Get("tempKey")).As().Utf8Value() == + "tempValue"); + assert(MaybeUnwrap(ref.Get("anotherKey")).As().Utf8Value() == + info[0].As().Utf8Value()); +} + +void MoveOperatorsTest(const Napi::CallbackInfo& info) { + Napi::ObjectReference existingRef; + Napi::ObjectReference existingRef2; + Napi::Object testObject = Napi::Object::New(info.Env()); + testObject.Set("testProp", "tProp"); + + // ObjectReference(Reference&& other); + Napi::Reference refObj = + Napi::Reference::New(testObject); + Napi::ObjectReference objRef = std::move(refObj); + std::string prop = MaybeUnwrap(objRef.Get("testProp")).As(); + assert(prop == "tProp"); + + // ObjectReference& operator=(Reference&& other); + Napi::Reference refObj2 = + Napi::Reference::New(testObject); + existingRef = std::move(refObj2); + prop = MaybeUnwrap(existingRef.Get("testProp")).As(); + assert(prop == "tProp"); + + // ObjectReference(ObjectReference&& other); + Napi::ObjectReference objRef3 = std::move(existingRef); + prop = MaybeUnwrap(objRef3.Get("testProp")).As(); + assert(prop == "tProp"); + + // ObjectReference& operator=(ObjectReference&& other); + existingRef2 = std::move(objRef3); + prop = MaybeUnwrap(objRef.Get("testProp")).As(); + assert(prop == "tProp"); +} + +void SetObjectWithCStringKey(Napi::ObjectReference& obj, + Napi::Value key, + Napi::Value val, + int valType) { + std::string c_key = key.As().Utf8Value(); + switch (valType) { + case JS: + obj.Set(c_key.c_str(), val); + break; + + case JS_CAST: + obj.Set(c_key.c_str(), static_cast(val)); + break; + + case C_STR: { + std::string c_val = val.As().Utf8Value(); + obj.Set(c_key.c_str(), c_val.c_str()); + break; + } + + case BOOL: + obj.Set(c_key.c_str(), val.As().Value()); + break; + + case DOUBLE: + obj.Set(c_key.c_str(), val.As().DoubleValue()); + break; + } +} + +void SetObjectWithCppStringKey(Napi::ObjectReference& obj, + Napi::Value key, + Napi::Value val, + int valType) { + std::string c_key = key.As(); + switch (valType) { + case JS: + obj.Set(c_key, val); + break; + + case JS_CAST: + obj.Set(c_key, static_cast(val)); + break; + + case CPP_STR: { + std::string c_val = val.As(); + obj.Set(c_key, c_val); + break; + } + + case BOOL: + obj.Set(c_key, val.As().Value()); + break; + + case DOUBLE: + obj.Set(c_key, val.As().DoubleValue()); + break; + } +} + +void SetObjectWithIntKey(Napi::ObjectReference& obj, + Napi::Value key, + Napi::Value val, + int valType) { + uint32_t c_key = key.As().Uint32Value(); + switch (valType) { + case JS: + obj.Set(c_key, val); + break; + + case JS_CAST: + obj.Set(c_key, static_cast(val)); + break; + + case C_STR: { + std::string c_val = val.As(); + obj.Set(c_key, c_val.c_str()); + break; + } + + case CPP_STR: { + std::string cpp_val = val.As(); + obj.Set(c_key, cpp_val); + break; + } + + case BOOL: + obj.Set(c_key, val.As().Value()); + break; + + case DOUBLE: + obj.Set(c_key, val.As().DoubleValue()); + break; + } +} + +void SetObject(const Napi::CallbackInfo& info) { Env env = info.Env(); HandleScope scope(env); @@ -33,20 +187,35 @@ void SetObjects(const CallbackInfo& info) { reference = Reference::New(Object::New(env), 2); reference.SuppressDestruct(); - if (info[0].IsString()) { - if (info[2].As() == String::New(env, "javascript")) { - weak.Set(info[0].As(), info[1]); - persistent.Set(info[0].As(), info[1]); - reference.Set(info[0].As(), info[1]); - } else { - weak.Set(info[0].As().Utf8Value(), info[1]); - persistent.Set(info[0].As().Utf8Value(), info[1]); - reference.Set(info[0].As().Utf8Value(), info[1]); - } - } else if (info[0].IsNumber()) { - weak.Set(info[0].As(), info[1]); - persistent.Set(info[0].As(), info[1]); - reference.Set(info[0].As(), info[1]); + Napi::Object configObject = info[0].As(); + + int keyType = + MaybeUnwrap(configObject.Get("keyType")).As().Uint32Value(); + int valType = + MaybeUnwrap(configObject.Get("valType")).As().Uint32Value(); + Napi::Value key = MaybeUnwrap(configObject.Get("key")); + Napi::Value val = MaybeUnwrap(configObject.Get("val")); + + switch (keyType) { + case CPP_STR: + SetObjectWithCppStringKey(weak, key, val, valType); + SetObjectWithCppStringKey(persistent, key, val, valType); + SetObjectWithCppStringKey(reference, key, val, valType); + break; + + case C_STR: + SetObjectWithCStringKey(weak, key, val, valType); + SetObjectWithCStringKey(persistent, key, val, valType); + SetObjectWithCStringKey(reference, key, val, valType); + break; + + case INT: + SetObjectWithIntKey(weak, key, val, valType); + SetObjectWithIntKey(persistent, key, val, valType); + SetObjectWithIntKey(reference, key, val, valType); + + default: + break; } } @@ -74,26 +243,73 @@ void SetCastedObjects(const CallbackInfo& info) { Value GetFromValue(const CallbackInfo& info) { Env env = info.Env(); - if (info[0].As() == String::New(env, "weak")) { + if (info[0] == String::New(env, "weak")) { if (weak.IsEmpty()) { return String::New(env, "No Referenced Value"); } else { return weak.Value(); } - } else if (info[0].As() == String::New(env, "persistent")) { + } else if (info[0] == String::New(env, "persistent")) { return persistent.Value(); } else { return reference.Value(); } } +Value GetHelper(ObjectReference& ref, + Object& configObject, + const Napi::Env& env) { + int keyType = + MaybeUnwrap(configObject.Get("keyType")).As().Uint32Value(); + if (ref.IsEmpty()) { + return String::New(env, "No referenced Value"); + } + + switch (keyType) { + case C_STR: { + std::string c_key = + MaybeUnwrap(configObject.Get("key")).As().Utf8Value(); + return MaybeUnwrap(ref.Get(c_key.c_str())); + break; + } + case CPP_STR: { + std::string cpp_key = + MaybeUnwrap(configObject.Get("key")).As().Utf8Value(); + return MaybeUnwrap(ref.Get(cpp_key)); + break; + } + case INT: { + uint32_t key = + MaybeUnwrap(configObject.Get("key")).As().Uint32Value(); + return MaybeUnwrap(ref.Get(key)); + break; + } + + default: + return String::New(env, "Error: Reached end of getter"); + break; + } +} + +Value GetFromGetters(const CallbackInfo& info) { + std::string object_req = info[0].As(); + Object configObject = info[1].As(); + if (object_req == "weak") { + return GetHelper(weak, configObject, info.Env()); + } else if (object_req == "persistent") { + return GetHelper(persistent, configObject, info.Env()); + } + + return GetHelper(reference, configObject, info.Env()); +} + // info[0] is a flag to determine if the weak, persistent, or // multiple reference ObjectReference is being requested. // info[1] is the key, and it be either a String or a Number. Value GetFromGetter(const CallbackInfo& info) { Env env = info.Env(); - if (info[0].As() == String::New(env, "weak")) { + if (info[0] == String::New(env, "weak")) { if (weak.IsEmpty()) { return String::New(env, "No Referenced Value"); } else { @@ -103,7 +319,7 @@ Value GetFromGetter(const CallbackInfo& info) { return MaybeUnwrap(weak.Get(info[1].As().Uint32Value())); } } - } else if (info[0].As() == String::New(env, "persistent")) { + } else if (info[0] == String::New(env, "persistent")) { if (info[1].IsString()) { return MaybeUnwrap(persistent.Get(info[1].As().Utf8Value())); } else if (info[1].IsNumber()) { @@ -125,13 +341,13 @@ Value GetFromGetter(const CallbackInfo& info) { Value GetCastedFromValue(const CallbackInfo& info) { Env env = info.Env(); - if (info[0].As() == String::New(env, "weak")) { + if (info[0] == String::New(env, "weak")) { if (casted_weak.IsEmpty()) { return String::New(env, "No Referenced Value"); } else { return casted_weak.Value(); } - } else if (info[0].As() == String::New(env, "persistent")) { + } else if (info[0] == String::New(env, "persistent")) { return casted_persistent.Value(); } else { return casted_reference.Value(); @@ -144,13 +360,13 @@ Value GetCastedFromValue(const CallbackInfo& info) { Value GetCastedFromGetter(const CallbackInfo& info) { Env env = info.Env(); - if (info[0].As() == String::New(env, "weak")) { + if (info[0] == String::New(env, "weak")) { if (casted_weak.IsEmpty()) { return String::New(env, "No Referenced Value"); } else { return MaybeUnwrap(casted_weak.Get(info[1].As())); } - } else if (info[0].As() == String::New(env, "persistent")) { + } else if (info[0] == String::New(env, "persistent")) { return MaybeUnwrap(casted_persistent.Get(info[1].As())); } else { return MaybeUnwrap(casted_reference.Get(info[1].As())); @@ -163,15 +379,15 @@ Number UnrefObjects(const CallbackInfo& info) { Env env = info.Env(); uint32_t num; - if (info[0].As() == String::New(env, "weak")) { + if (info[0] == String::New(env, "weak")) { num = weak.Unref(); - } else if (info[0].As() == String::New(env, "persistent")) { + } else if (info[0] == String::New(env, "persistent")) { num = persistent.Unref(); - } else if (info[0].As() == String::New(env, "references")) { + } else if (info[0] == String::New(env, "references")) { num = reference.Unref(); - } else if (info[0].As() == String::New(env, "casted weak")) { + } else if (info[0] == String::New(env, "casted weak")) { num = casted_weak.Unref(); - } else if (info[0].As() == String::New(env, "casted persistent")) { + } else if (info[0] == String::New(env, "casted persistent")) { num = casted_persistent.Unref(); } else { num = casted_reference.Unref(); @@ -186,15 +402,15 @@ Number RefObjects(const CallbackInfo& info) { Env env = info.Env(); uint32_t num; - if (info[0].As() == String::New(env, "weak")) { + if (info[0] == String::New(env, "weak")) { num = weak.Ref(); - } else if (info[0].As() == String::New(env, "persistent")) { + } else if (info[0] == String::New(env, "persistent")) { num = persistent.Ref(); - } else if (info[0].As() == String::New(env, "references")) { + } else if (info[0] == String::New(env, "references")) { num = reference.Ref(); - } else if (info[0].As() == String::New(env, "casted weak")) { + } else if (info[0] == String::New(env, "casted weak")) { num = casted_weak.Ref(); - } else if (info[0].As() == String::New(env, "casted persistent")) { + } else if (info[0] == String::New(env, "casted persistent")) { num = casted_persistent.Ref(); } else { num = casted_reference.Ref(); @@ -207,13 +423,15 @@ Object InitObjectReference(Env env) { Object exports = Object::New(env); exports["setCastedObjects"] = Function::New(env, SetCastedObjects); - exports["setObjects"] = Function::New(env, SetObjects); + exports["setObject"] = Function::New(env, SetObject); exports["getCastedFromValue"] = Function::New(env, GetCastedFromValue); - exports["getFromGetter"] = Function::New(env, GetFromGetter); + exports["getFromGetters"] = Function::New(env, GetFromGetters); exports["getCastedFromGetter"] = Function::New(env, GetCastedFromGetter); exports["getFromValue"] = Function::New(env, GetFromValue); exports["unrefObjects"] = Function::New(env, UnrefObjects); exports["refObjects"] = Function::New(env, RefObjects); + exports["moveOpTest"] = Function::New(env, MoveOperatorsTest); + exports["setWithTempString"] = Function::New(env, SetWithTempString); return exports; } diff --git a/test/object_reference.js b/test/object_reference.js index c1e730813..5b713dce8 100644 --- a/test/object_reference.js +++ b/test/object_reference.js @@ -16,7 +16,39 @@ const testUtil = require('./testUtil'); module.exports = require('./common').runTest(test); +const enumType = { + JS: 0, // Napi::Value + C_STR: 1, // const char * + CPP_STR: 2, // std::string + BOOL: 3, // bool + INT: 4, // uint32_t + DOUBLE: 5, // double + JS_CAST: 6 // napi_value +}; + +const configObjects = [ + { keyType: enumType.C_STR, valType: enumType.JS, key: 'hello', val: 'worlds' }, + { keyType: enumType.C_STR, valType: enumType.C_STR, key: 'hello', val: 'worldd' }, + { keyType: enumType.C_STR, valType: enumType.BOOL, key: 'hello', val: false }, + { keyType: enumType.C_STR, valType: enumType.DOUBLE, key: 'hello', val: 3.56 }, + { keyType: enumType.C_STR, valType: enumType.JS_CAST, key: 'hello_cast', val: 'world' }, + { keyType: enumType.CPP_STR, valType: enumType.JS, key: 'hello_cpp', val: 'world_js' }, + { keyType: enumType.CPP_STR, valType: enumType.JS_CAST, key: 'hello_cpp', val: 'world_js_cast' }, + { keyType: enumType.CPP_STR, valType: enumType.CPP_STR, key: 'hello_cpp', val: 'world_cpp_str' }, + { keyType: enumType.CPP_STR, valType: enumType.BOOL, key: 'hello_cpp', val: true }, + { keyType: enumType.CPP_STR, valType: enumType.DOUBLE, key: 'hello_cpp', val: 3.58 }, + { keyType: enumType.INT, valType: enumType.JS, key: 1, val: 'hello world' }, + { keyType: enumType.INT, valType: enumType.JS_CAST, key: 2, val: 'hello world' }, + { keyType: enumType.INT, valType: enumType.C_STR, key: 3, val: 'hello world' }, + { keyType: enumType.INT, valType: enumType.CPP_STR, key: 8, val: 'hello world' }, + { keyType: enumType.INT, valType: enumType.BOOL, key: 3, val: false }, + { keyType: enumType.INT, valType: enumType.DOUBLE, key: 4, val: 3.14159 } +]; + function test (binding) { + binding.objectreference.moveOpTest(); + binding.objectreference.setWithTempString('testValue'); + function testCastedEqual (testToCompare) { const compareTest = ['hello', 'world', '!']; if (testToCompare instanceof Array) { @@ -74,45 +106,32 @@ function test (binding) { 'Weak', () => { - binding.objectreference.setObjects('hello', 'world'); - const test = binding.objectreference.getFromValue('weak'); - const test2 = binding.objectreference.getFromGetter('weak', 'hello'); - - assert.deepEqual({ hello: 'world' }, test); - assert.equal('world', test2); - assert.equal(test.hello, test2); - }, - () => { - binding.objectreference.setObjects('hello', 'world', 'javascript'); - const test = binding.objectreference.getFromValue('weak'); - const test2 = binding.objectreference.getFromValue('weak', 'hello'); + for (const configObject of configObjects) { + binding.objectreference.setObject(configObject); + const test = binding.objectreference.getFromValue('weak'); + const test2 = binding.objectreference.getFromGetters('weak', configObject); - assert.deepEqual({ hello: 'world' }, test); - assert.deepEqual({ hello: 'world' }, test2); - assert.equal(test, test2); - }, - () => { - binding.objectreference.setObjects(1, 'hello world'); - const test = binding.objectreference.getFromValue('weak'); - const test2 = binding.objectreference.getFromGetter('weak', 1); + const assertObject = { + [configObject.key]: configObject.val + }; + assert.deepEqual(assertObject, test); + assert.equal(configObject.val, test2); + } + }, () => { + const configObjA = { keyType: enumType.INT, valType: enumType.JS, key: 0, val: 'hello' }; + const configObjB = { keyType: enumType.INT, valType: enumType.JS, key: 1, val: 'world' }; + binding.objectreference.setObject(configObjA); + binding.objectreference.setObject(configObjB); - assert.deepEqual({ 1: 'hello world' }, test); - assert.equal('hello world', test2); - assert.equal(test[1], test2); - }, - () => { - binding.objectreference.setObjects(0, 'hello'); - binding.objectreference.setObjects(1, 'world'); const test = binding.objectreference.getFromValue('weak'); - const test2 = binding.objectreference.getFromGetter('weak', 0); - const test3 = binding.objectreference.getFromGetter('weak', 1); - + const test2 = binding.objectreference.getFromGetters('weak', configObjA); + const test3 = binding.objectreference.getFromGetters('weak', configObjB); assert.deepEqual({ 1: 'world' }, test); assert.equal(undefined, test2); assert.equal('world', test3); }, () => { - binding.objectreference.setObjects('hello', 'world'); + binding.objectreference.setObject({ keyType: enumType.JS, valType: enumType.JS, key: 'hello', val: 'world' }); assert.doesNotThrow( () => { let rcount = binding.objectreference.refObjects('weak'); @@ -132,16 +151,20 @@ function test (binding) { 'Persistent', () => { - binding.objectreference.setObjects('hello', 'world'); - const test = binding.objectreference.getFromValue('persistent'); - const test2 = binding.objectreference.getFromGetter('persistent', 'hello'); + for (const configObject of configObjects) { + binding.objectreference.setObject(configObject); + const test = binding.objectreference.getFromValue('persistent'); + const test2 = binding.objectreference.getFromGetters('persistent', configObject); + const assertObject = { + [configObject.key]: configObject.val + }; - assert.deepEqual({ hello: 'world' }, test); - assert.equal('world', test2); - assert.equal(test.hello, test2); + assert.deepEqual(assertObject, test); + assert.equal(configObject.val, test2); + } }, () => { - binding.objectreference.setObjects('hello', 'world', 'javascript'); + binding.objectreference.setObject({ keyType: enumType.CPP_STR, valType: enumType.JS, key: 'hello', val: 'world' }); const test = binding.objectreference.getFromValue('persistent'); const test2 = binding.objectreference.getFromValue('persistent', 'hello'); @@ -150,27 +173,21 @@ function test (binding) { assert.deepEqual(test, test2); }, () => { - binding.objectreference.setObjects(1, 'hello world'); - const test = binding.objectreference.getFromValue('persistent'); - const test2 = binding.objectreference.getFromGetter('persistent', 1); + const configObjA = { keyType: enumType.INT, valType: enumType.JS, key: 0, val: 'hello' }; + const configObjB = { keyType: enumType.INT, valType: enumType.JS, key: 1, val: 'world' }; + binding.objectreference.setObject(configObjA); + binding.objectreference.setObject(configObjB); - assert.deepEqual({ 1: 'hello world' }, test); - assert.equal('hello world', test2); - assert.equal(test[1], test2); - }, - () => { - binding.objectreference.setObjects(0, 'hello'); - binding.objectreference.setObjects(1, 'world'); const test = binding.objectreference.getFromValue('persistent'); - const test2 = binding.objectreference.getFromGetter('persistent', 0); - const test3 = binding.objectreference.getFromGetter('persistent', 1); + const test2 = binding.objectreference.getFromGetters('persistent', configObjA); + const test3 = binding.objectreference.getFromGetters('persistent', configObjB); assert.deepEqual({ 1: 'world' }, test); assert.equal(undefined, test2); assert.equal('world', test3); }, () => { - binding.objectreference.setObjects('hello', 'world'); + binding.objectreference.setObject({ keyType: enumType.CPP_STR, valType: enumType.JS, key: 'hello', val: 'world' }); assert.doesNotThrow( () => { let rcount = binding.objectreference.unrefObjects('persistent'); @@ -196,45 +213,33 @@ function test (binding) { 'References', () => { - binding.objectreference.setObjects('hello', 'world'); - const test = binding.objectreference.getFromValue(); - const test2 = binding.objectreference.getFromGetter('hello'); - - assert.deepEqual({ hello: 'world' }, test); - assert.equal('world', test2); - assert.equal(test.hello, test2); + for (const configObject of configObjects) { + binding.objectreference.setObject(configObject); + const test = binding.objectreference.getFromValue(); + const test2 = binding.objectreference.getFromGetters('reference', configObject); + const assertObject = { + [configObject.key]: configObject.val + }; + assert.deepEqual(assertObject, test); + assert.equal(configObject.val, test2); + } }, () => { - binding.objectreference.setObjects('hello', 'world', 'javascript'); + const configObjA = { keyType: enumType.INT, valType: enumType.JS, key: 0, val: 'hello' }; + const configObjB = { keyType: enumType.INT, valType: enumType.JS, key: 1, val: 'world' }; + binding.objectreference.setObject(configObjA); + binding.objectreference.setObject(configObjB); const test = binding.objectreference.getFromValue(); - const test2 = binding.objectreference.getFromValue('hello'); - assert.deepEqual({ hello: 'world' }, test); - assert.deepEqual({ hello: 'world' }, test2); - assert.deepEqual(test, test2); - }, - () => { - binding.objectreference.setObjects(1, 'hello world'); - const test = binding.objectreference.getFromValue(); - const test2 = binding.objectreference.getFromGetter(1); - - assert.deepEqual({ 1: 'hello world' }, test); - assert.equal('hello world', test2); - assert.equal(test[1], test2); - }, - () => { - binding.objectreference.setObjects(0, 'hello'); - binding.objectreference.setObjects(1, 'world'); - const test = binding.objectreference.getFromValue(); - const test2 = binding.objectreference.getFromGetter(0); - const test3 = binding.objectreference.getFromGetter(1); + const test2 = binding.objectreference.getFromGetters('reference', configObjA); + const test3 = binding.objectreference.getFromGetters('reference', configObjB); assert.deepEqual({ 1: 'world' }, test); assert.equal(undefined, test2); assert.equal('world', test3); }, () => { - binding.objectreference.setObjects('hello', 'world'); + binding.objectreference.setObject({ keyType: enumType.CPP_STR, valType: enumType.JS, key: 'hello', val: 'world' }); assert.doesNotThrow( () => { let rcount = binding.objectreference.unrefObjects('references'); diff --git a/test/objectwrap.cc b/test/objectwrap.cc index aa9389678..1ee0c9ad7 100644 --- a/test/objectwrap.cc +++ b/test/objectwrap.cc @@ -12,6 +12,10 @@ void StaticSetter(const Napi::CallbackInfo& /*info*/, testStaticContextRef.Value().Set("value", value); } +void StaticMethodVoidCb(const Napi::CallbackInfo& info) { + StaticSetter(info, info[0].As()); +} + Napi::Value TestStaticMethod(const Napi::CallbackInfo& info) { std::string str = MaybeUnwrap(info[0].ToString()); return Napi::String::New(info.Env(), str + " static"); @@ -53,6 +57,15 @@ class Test : public Napi::ObjectWrap { return static_cast(info.Data())->Getter(info); } + static Napi::Value CanUnWrap(const Napi::CallbackInfo& info) { + Napi::Object wrappedObject = info[0].As(); + std::string expectedString = info[1].As(); + Test* nativeObject = Test::Unwrap(wrappedObject); + std::string strVal = MaybeUnwrap(nativeObject->Getter(info).ToString()); + + return Napi::Boolean::New(info.Env(), strVal == expectedString); + } + void Setter(const Napi::CallbackInfo& /*info*/, const Napi::Value& value) { value_ = MaybeUnwrap(value.ToString()); } @@ -115,7 +128,8 @@ class Test : public Napi::ObjectWrap { Napi::Symbol::New(env, "kTestStaticMethodTInternal"); Napi::Symbol kTestStaticVoidMethodTInternal = Napi::Symbol::New(env, "kTestStaticVoidMethodTInternal"); - + Napi::Symbol kTestStaticVoidMethodInternal = + Napi::Symbol::New(env, "kTestStaticVoidMethodInternal"); Napi::Symbol kTestValueInternal = Napi::Symbol::New(env, "kTestValueInternal"); Napi::Symbol kTestAccessorInternal = @@ -147,6 +161,8 @@ class Test : public Napi::ObjectWrap { kTestStaticMethodInternal), StaticValue("kTestStaticMethodTInternal", kTestStaticMethodTInternal), + StaticValue("kTestStaticVoidMethodInternal", + kTestStaticVoidMethodInternal), StaticValue("kTestStaticVoidMethodTInternal", kTestStaticVoidMethodTInternal), StaticValue("kTestValueInternal", kTestValueInternal), @@ -184,7 +200,11 @@ class Test : public Napi::ObjectWrap { "testStaticGetSetT"), StaticAccessor<&StaticGetter, &StaticSetter>( kTestStaticAccessorTInternal), - + StaticMethod( + "testStaticVoidMethod", &StaticMethodVoidCb, napi_default), + StaticMethod(kTestStaticVoidMethodInternal, + &StaticMethodVoidCb, + napi_default), StaticMethod( "testStaticMethod", &TestStaticMethod, napi_enumerable), StaticMethod(kTestStaticMethodInternal, @@ -195,7 +215,7 @@ class Test : public Napi::ObjectWrap { StaticMethod<&TestStaticVoidMethodT>( kTestStaticVoidMethodTInternal), StaticMethod<&TestStaticMethodT>(kTestStaticMethodTInternal), - + StaticMethod("canUnWrap", &CanUnWrap, napi_enumerable), InstanceValue("testValue", Napi::Boolean::New(env, true), napi_enumerable), diff --git a/test/objectwrap.js b/test/objectwrap.js index 553df1da9..a0d278062 100644 --- a/test/objectwrap.js +++ b/test/objectwrap.js @@ -24,6 +24,9 @@ async function test (binding) { obj.testSetter = 'instance getter 2'; assert.strictEqual(obj.testGetter, 'instance getter 2'); assert.strictEqual(obj.testGetterT, 'instance getter 2'); + + assert.throws(() => clazz.prototype.testGetter, /Invalid argument/); + assert.throws(() => clazz.prototype.testGetterT, /Invalid argument/); } // read write-only @@ -61,6 +64,9 @@ async function test (binding) { obj.testGetSetT = 'instance getset 4'; assert.strictEqual(obj.testGetSetT, 'instance getset 4'); + + assert.throws(() => { clazz.prototype.testGetSet = 'instance getset'; }, /Invalid argument/); + assert.throws(() => { clazz.prototype.testGetSetT = 'instance getset'; }, /Invalid argument/); } // rw symbol @@ -98,6 +104,9 @@ async function test (binding) { assert.strictEqual(obj.testMethodT(), 'method<>(const char*)'); obj[clazz.kTestVoidMethodTInternal]('method<>(Symbol)'); assert.strictEqual(obj[clazz.kTestMethodTInternal](), 'method<>(Symbol)'); + assert.throws(() => clazz.prototype.testMethod('method')); + assert.throws(() => clazz.prototype.testMethodT()); + assert.throws(() => clazz.prototype.testVoidMethodT('method<>(const char*)')); }; const testEnumerables = (obj, clazz) => { @@ -210,6 +219,10 @@ async function test (binding) { }; const testStaticMethod = (clazz) => { + clazz.testStaticVoidMethod(52); + assert.strictEqual(clazz.testStaticGetter, 52); + clazz[clazz.kTestStaticVoidMethodInternal](94); + assert.strictEqual(clazz.testStaticGetter, 94); assert.strictEqual(clazz.testStaticMethod('method'), 'method static'); assert.strictEqual(clazz[clazz.kTestStaticMethodInternal]('method'), 'method static internal'); clazz.testStaticVoidMethodT('static method<>(const char*)'); @@ -224,7 +237,8 @@ async function test (binding) { 'testStaticValue', 'testStaticGetter', 'testStaticGetSet', - 'testStaticMethod' + 'testStaticMethod', + 'canUnWrap' ]); // for..in @@ -238,7 +252,8 @@ async function test (binding) { 'testStaticValue', 'testStaticGetter', 'testStaticGetSet', - 'testStaticMethod' + 'testStaticMethod', + 'canUnWrap' ]); } }; @@ -260,6 +275,11 @@ async function test (binding) { ]); } + const testUnwrap = (obj, clazz) => { + obj.testSetter = 'unwrapTest'; + assert(clazz.canUnWrap(obj, 'unwrapTest')); + }; + const testObj = (obj, clazz) => { testValue(obj, clazz); testAccessor(obj, clazz); @@ -268,6 +288,7 @@ async function test (binding) { testEnumerables(obj, clazz); testConventions(obj, clazz); + testUnwrap(obj, clazz); }; async function testClass (clazz) { diff --git a/test/objectwrap_function.cc b/test/objectwrap_function.cc index 4c2e1bbe2..0ce074c68 100644 --- a/test/objectwrap_function.cc +++ b/test/objectwrap_function.cc @@ -18,28 +18,26 @@ class FunctionTest : public Napi::ObjectWrap { return MaybeUnwrap(GetConstructor(info.Env()).New(args)); } - // Constructor-per-env map in a static member because env.SetInstanceData() - // would interfere with Napi::Addon - static std::unordered_map constructors; - static void Initialize(Napi::Env env, Napi::Object exports) { const char* name = "FunctionTest"; Napi::Function func = DefineClass(env, name, {}); - constructors[env] = Napi::Persistent(func); - env.AddCleanupHook([env] { constructors.erase(env); }); + Napi::FunctionReference* ctor = new Napi::FunctionReference(); + *ctor = Napi::Persistent(func); + env.SetInstanceData(ctor); exports.Set(name, func); } static Napi::Function GetConstructor(Napi::Env env) { - return constructors[env].Value(); + return env.GetInstanceData()->Value(); } }; -std::unordered_map - FunctionTest::constructors; +Napi::Value ObjectWrapFunctionFactory(const Napi::CallbackInfo& info) { + Napi::Object exports = Napi::Object::New(info.Env()); + FunctionTest::Initialize(info.Env(), exports); + return exports; +} Napi::Object InitObjectWrapFunction(Napi::Env env) { - Napi::Object exports = Napi::Object::New(env); - FunctionTest::Initialize(env, exports); - return exports; + return Napi::Function::New(env, "FunctionFactory"); } diff --git a/test/objectwrap_function.js b/test/objectwrap_function.js index 7bcf6c087..671833911 100644 --- a/test/objectwrap_function.js +++ b/test/objectwrap_function.js @@ -1,22 +1,6 @@ 'use strict'; -const assert = require('assert'); -const testUtil = require('./testUtil'); - -function test (binding) { - return testUtil.runGCTests([ - 'objectwrap function', - () => { - const { FunctionTest } = binding.objectwrap_function; - const newConstructed = new FunctionTest(); - const functionConstructed = FunctionTest(); - assert(newConstructed instanceof FunctionTest); - assert(functionConstructed instanceof FunctionTest); - assert.throws(() => (FunctionTest(true)), /an exception/); - }, - // Do on gc before returning. - () => {} - ]); -} - -module.exports = require('./common').runTest(test); +module.exports = require('./common').runTestInChildProcess({ + suite: 'objectwrap_function', + testName: 'runTest' +}); diff --git a/test/objectwrap_worker_thread.js b/test/objectwrap_worker_thread.js index 8b47e9ac9..59dfb9c0b 100644 --- a/test/objectwrap_worker_thread.js +++ b/test/objectwrap_worker_thread.js @@ -1,12 +1,13 @@ 'use strict'; const path = require('path'); const { Worker, isMainThread } = require('worker_threads'); +const { runTestWithBuildType, whichBuildType } = require('./common'); -module.exports = require('./common').runTestWithBuildType(test); +module.exports = runTestWithBuildType(test); -async function test (buildType) { +async function test () { if (isMainThread) { - const buildType = process.config.target_defaults.default_configuration; + const buildType = await whichBuildType(); const worker = new Worker(__filename, { workerData: buildType }); return new Promise((resolve, reject) => { worker.on('exit', () => { diff --git a/test/promise.cc b/test/promise.cc index f25600283..06ba22b86 100644 --- a/test/promise.cc +++ b/test/promise.cc @@ -1,4 +1,5 @@ #include "napi.h" +#include "test_helper.h" using namespace Napi; @@ -23,6 +24,74 @@ Value PromiseReturnsCorrectEnv(const CallbackInfo& info) { return Boolean::New(info.Env(), deferred.Env() == info.Env()); } +Value ThenMethodOnFulfilled(const CallbackInfo& info) { + auto deferred = Promise::Deferred::New(info.Env()); + Function onFulfilled = info[0].As(); + + Promise resultPromise = MaybeUnwrap(deferred.Promise().Then(onFulfilled)); + + bool isPromise = resultPromise.IsPromise(); + deferred.Resolve(Number::New(info.Env(), 42)); + + Object result = Object::New(info.Env()); + result["isPromise"] = Boolean::New(info.Env(), isPromise); + result["promise"] = resultPromise; + + return result; +} + +Value ThenMethodOnFulfilledOnRejectedResolve(const CallbackInfo& info) { + auto deferred = Promise::Deferred::New(info.Env()); + Function onFulfilled = info[0].As(); + Function onRejected = info[1].As(); + + Promise resultPromise = + MaybeUnwrap(deferred.Promise().Then(onFulfilled, onRejected)); + + bool isPromise = resultPromise.IsPromise(); + deferred.Resolve(Number::New(info.Env(), 42)); + + Object result = Object::New(info.Env()); + result["isPromise"] = Boolean::New(info.Env(), isPromise); + result["promise"] = resultPromise; + + return result; +} + +Value ThenMethodOnFulfilledOnRejectedReject(const CallbackInfo& info) { + auto deferred = Promise::Deferred::New(info.Env()); + Function onFulfilled = info[0].As(); + Function onRejected = info[1].As(); + + Promise resultPromise = + MaybeUnwrap(deferred.Promise().Then(onFulfilled, onRejected)); + + bool isPromise = resultPromise.IsPromise(); + deferred.Reject(String::New(info.Env(), "Rejected")); + + Object result = Object::New(info.Env()); + result["isPromise"] = Boolean::New(info.Env(), isPromise); + result["promise"] = resultPromise; + + return result; +} + +Value CatchMethod(const CallbackInfo& info) { + auto deferred = Promise::Deferred::New(info.Env()); + Function onRejected = info[0].As(); + + Promise resultPromise = MaybeUnwrap(deferred.Promise().Catch(onRejected)); + + bool isPromise = resultPromise.IsPromise(); + deferred.Reject(String::New(info.Env(), "Rejected")); + + Object result = Object::New(info.Env()); + result["isPromise"] = Boolean::New(info.Env(), isPromise); + result["promise"] = resultPromise; + + return result; +} + Object InitPromise(Env env) { Object exports = Object::New(env); @@ -31,6 +100,12 @@ Object InitPromise(Env env) { exports["rejectPromise"] = Function::New(env, RejectPromise); exports["promiseReturnsCorrectEnv"] = Function::New(env, PromiseReturnsCorrectEnv); + exports["thenMethodOnFulfilled"] = Function::New(env, ThenMethodOnFulfilled); + exports["thenMethodOnFulfilledOnRejectedResolve"] = + Function::New(env, ThenMethodOnFulfilledOnRejectedResolve); + exports["thenMethodOnFulfilledOnRejectedReject"] = + Function::New(env, ThenMethodOnFulfilledOnRejectedReject); + exports["catchMethod"] = Function::New(env, CatchMethod); return exports; } diff --git a/test/promise.js b/test/promise.js index 63b20cef8..e61a783ce 100644 --- a/test/promise.js +++ b/test/promise.js @@ -17,4 +17,27 @@ async function test (binding) { rejecting.then(common.mustNotCall()).catch(common.mustCall()); assert(binding.promise.promiseReturnsCorrectEnv()); + + const onFulfilled = (value) => value * 2; + const onRejected = (reason) => reason + '!'; + + const thenOnFulfilled = binding.promise.thenMethodOnFulfilled(onFulfilled); + assert.strictEqual(thenOnFulfilled.isPromise, true); + const onFulfilledValue = await thenOnFulfilled.promise; + assert.strictEqual(onFulfilledValue, 84); + + const thenResolve = binding.promise.thenMethodOnFulfilledOnRejectedResolve(onFulfilled, onRejected); + assert.strictEqual(thenResolve.isPromise, true); + const thenResolveValue = await thenResolve.promise; + assert.strictEqual(thenResolveValue, 84); + + const thenRejected = binding.promise.thenMethodOnFulfilledOnRejectedReject(onFulfilled, onRejected); + assert.strictEqual(thenRejected.isPromise, true); + const rejectedValue = await thenRejected.promise; + assert.strictEqual(rejectedValue, 'Rejected!'); + + const catchMethod = binding.promise.catchMethod(onRejected); + assert.strictEqual(catchMethod.isPromise, true); + const catchValue = await catchMethod.promise; + assert.strictEqual(catchValue, 'Rejected!'); } diff --git a/test/reference.cc b/test/reference.cc index 9b8f81563..b83c434a4 100644 --- a/test/reference.cc +++ b/test/reference.cc @@ -1,9 +1,60 @@ +#include "assert.h" #include "napi.h" - +#include "test_helper.h" using namespace Napi; static Reference> weak; +static void RefMoveAssignTests(const Napi::CallbackInfo& info) { + Napi::Object obj = Napi::Object::New(info.Env()); + obj.Set("tPro", "tTEST"); + Napi::Reference ref = Napi::Reference::New(obj); + ref.SuppressDestruct(); + + napi_ref obj_ref = static_cast(ref); + Napi::Reference existingRef = + Napi::Reference(info.Env(), obj_ref); + assert(ref == existingRef); + assert(!(ref != existingRef)); + + std::string val = + MaybeUnwrap(existingRef.Value().Get("tPro")).As(); + assert(val == "tTEST"); + // ------------------------------------------------------------ // + Napi::Reference copyMoveRef = std::move(existingRef); + assert(copyMoveRef == ref); + + Napi::Reference copyAssignRef; + copyAssignRef = std::move(copyMoveRef); + assert(copyAssignRef == ref); +} + +static void ReferenceRefTests(const Napi::CallbackInfo& info) { + Napi::Object obj = Napi::Object::New(info.Env()); + Napi::Reference ref = Napi::Reference::New(obj); + + assert(ref.Ref() == 1); + assert(ref.Unref() == 0); +} + +static void ReferenceResetTests(const Napi::CallbackInfo& info) { + Napi::Object obj = Napi::Object::New(info.Env()); + Napi::Reference ref = Napi::Reference::New(obj); + assert(!ref.IsEmpty()); + + ref.Reset(); + assert(ref.IsEmpty()); + + Napi::Object newObject = Napi::Object::New(info.Env()); + newObject.Set("n-api", "node"); + + ref.Reset(newObject, 1); + assert(!ref.IsEmpty()); + + std::string val = MaybeUnwrap(ref.Value().Get("n-api")).As(); + assert(val == "node"); +} + void CreateWeakArray(const CallbackInfo& info) { weak = Weak(Buffer::New(info.Env(), 1)); weak.SuppressDestruct(); @@ -20,5 +71,8 @@ Object InitReference(Env env) { exports["createWeakArray"] = Function::New(env, CreateWeakArray); exports["accessWeakArrayEmpty"] = Function::New(env, AccessWeakArrayEmpty); + exports["refMoveAssignTest"] = Function::New(env, RefMoveAssignTests); + exports["referenceRefTest"] = Function::New(env, ReferenceRefTests); + exports["refResetTest"] = Function::New(env, ReferenceResetTests); return exports; } diff --git a/test/reference.js b/test/reference.js index 34fe85172..2b4c4037f 100644 --- a/test/reference.js +++ b/test/reference.js @@ -9,6 +9,12 @@ function test (binding) { return testUtil.runGCTests([ 'test reference', () => binding.reference.createWeakArray(), - () => assert.strictEqual(true, binding.reference.accessWeakArrayEmpty()) + () => assert.strictEqual(true, binding.reference.accessWeakArrayEmpty()), + 'test reference move op', + () => binding.reference.refMoveAssignTest(), + 'test reference ref', + () => binding.reference.referenceRefTest(), + 'test reference reset', + () => binding.reference.refResetTest() ]); } diff --git a/test/require_basic_finalizers/index.js b/test/require_basic_finalizers/index.js new file mode 100644 index 000000000..31ee4f00b --- /dev/null +++ b/test/require_basic_finalizers/index.js @@ -0,0 +1,38 @@ +'use strict'; + +const { promisify } = require('util'); +const exec = promisify(require('child_process').exec); +const { copy, remove } = require('fs-extra'); +const path = require('path'); +const assert = require('assert'); + +async function test () { + const addon = 'require-basic-finalizers'; + const ADDON_FOLDER = path.join(__dirname, 'addons', addon); + + await remove(ADDON_FOLDER); + await copy(path.join(__dirname, 'tpl'), ADDON_FOLDER); + + console.log(' >Building addon'); + + // Fail when NODE_ADDON_API_REQUIRE_BASIC_FINALIZERS is enabled + await assert.rejects(exec('npm --require-basic-finalizers install', { + cwd: ADDON_FOLDER + }), 'Addon unexpectedly compiled successfully'); + + // Succeed when NODE_ADDON_API_REQUIRE_BASIC_FINALIZERS is not enabled + return assert.doesNotReject(exec('npm install', { + cwd: ADDON_FOLDER + })); +} + +module.exports = (function () { + // This test will only run under an experimental version test. + const isExperimental = Number(process.env.NAPI_VERSION) === 2147483647; + + if (isExperimental) { + return test(); + } else { + console.log(' >Skipped (non-experimental test run)'); + } +})(); diff --git a/test/require_basic_finalizers/tpl/.npmrc b/test/require_basic_finalizers/tpl/.npmrc new file mode 100644 index 000000000..43c97e719 --- /dev/null +++ b/test/require_basic_finalizers/tpl/.npmrc @@ -0,0 +1 @@ +package-lock=false diff --git a/test/require_basic_finalizers/tpl/addon.cc b/test/require_basic_finalizers/tpl/addon.cc new file mode 100644 index 000000000..f4277ac74 --- /dev/null +++ b/test/require_basic_finalizers/tpl/addon.cc @@ -0,0 +1,12 @@ +#include + +Napi::Object Init(Napi::Env env, Napi::Object exports) { + exports.Set( + "external", + Napi::External::New( + env, new int(1), [](Napi::Env /*env*/, int* data) { delete data; })); + + return exports; +} + +NODE_API_MODULE(NODE_GYP_MODULE_NAME, Init) diff --git a/test/require_basic_finalizers/tpl/binding.gyp b/test/require_basic_finalizers/tpl/binding.gyp new file mode 100644 index 000000000..caf99d21f --- /dev/null +++ b/test/require_basic_finalizers/tpl/binding.gyp @@ -0,0 +1,48 @@ +{ + 'target_defaults': { + 'include_dirs': [ + "()), Value()); + return MaybeUnwrapOr(env.RunScript(info[0].UnsafeAs()), Value()); } Value RunWithContext(const CallbackInfo& info) { diff --git a/test/shared_array_buffer.cc b/test/shared_array_buffer.cc new file mode 100644 index 000000000..57f66495a --- /dev/null +++ b/test/shared_array_buffer.cc @@ -0,0 +1,104 @@ +#include "napi.h" + +using namespace Napi; + +namespace { + +#ifdef NODE_API_EXPERIMENTAL_HAS_SHAREDARRAYBUFFER +Value TestIsSharedArrayBuffer(const CallbackInfo& info) { + if (info.Length() < 1) { + Error::New(info.Env(), "Wrong number of arguments") + .ThrowAsJavaScriptException(); + return Value(); + } + + return Boolean::New(info.Env(), info[0].IsSharedArrayBuffer()); +} + +Value TestCreateSharedArrayBuffer(const CallbackInfo& info) { + if (info.Length() < 1) { + Error::New(info.Env(), "Wrong number of arguments") + .ThrowAsJavaScriptException(); + return Value(); + } else if (!info[0].IsNumber()) { + Error::New(info.Env(), + "Wrong type of arguments. Expects a number as first argument.") + .ThrowAsJavaScriptException(); + return Value(); + } + + auto byte_length = info[0].As().Uint32Value(); + if (byte_length == 0) { + Error::New(info.Env(), + "Invalid byte length. Expects a non-negative integer.") + .ThrowAsJavaScriptException(); + return Value(); + } + + return SharedArrayBuffer::New(info.Env(), byte_length); +} + +Value TestGetSharedArrayBufferInfo(const CallbackInfo& info) { + if (info.Length() < 1) { + Error::New(info.Env(), "Wrong number of arguments") + .ThrowAsJavaScriptException(); + return Value(); + } else if (!info[0].IsSharedArrayBuffer()) { + Error::New(info.Env(), + "Wrong type of arguments. Expects a SharedArrayBuffer as first " + "argument.") + .ThrowAsJavaScriptException(); + return Value(); + } + + auto byte_length = info[0].As().ByteLength(); + + return Number::New(info.Env(), byte_length); +} + +Value TestSharedArrayBufferData(const CallbackInfo& info) { + if (info.Length() < 1) { + Error::New(info.Env(), "Wrong number of arguments") + .ThrowAsJavaScriptException(); + return Value(); + } else if (!info[0].IsSharedArrayBuffer()) { + Error::New(info.Env(), + "Wrong type of arguments. Expects a SharedArrayBuffer as first " + "argument.") + .ThrowAsJavaScriptException(); + return Value(); + } + + auto byte_length = info[0].As().ByteLength(); + void* data = info[0].As().Data(); + + if (byte_length > 0 && data != nullptr) { + uint8_t* bytes = static_cast(data); + for (size_t i = 0; i < byte_length; i++) { + bytes[i] = i % 256; + } + + return Boolean::New(info.Env(), true); + } + + return Boolean::New(info.Env(), false); +} +#endif +} // end anonymous namespace + +Object InitSharedArrayBuffer(Env env) { + Object exports = Object::New(env); + +#ifdef NODE_API_EXPERIMENTAL_HAS_SHAREDARRAYBUFFER + exports["testIsSharedArrayBuffer"] = + Function::New(env, TestIsSharedArrayBuffer); + exports["testCreateSharedArrayBuffer"] = + Function::New(env, TestCreateSharedArrayBuffer); + exports["testGetSharedArrayBufferInfo"] = + Function::New(env, TestGetSharedArrayBufferInfo); + exports["testSharedArrayBufferData"] = + Function::New(env, TestSharedArrayBufferData); +#endif + + return exports; +} diff --git a/test/shared_array_buffer.js b/test/shared_array_buffer.js new file mode 100644 index 000000000..018021ace --- /dev/null +++ b/test/shared_array_buffer.js @@ -0,0 +1,55 @@ +'use strict'; + +const assert = require('assert'); + +module.exports = require('./common').runTest(test); + +let skippedMessageShown = false; + +function test ({ hasSharedArrayBuffer, sharedarraybuffer }) { + if (!hasSharedArrayBuffer) { + if (!skippedMessageShown) { + console.log(' >Skipped (no SharedArrayBuffer support)'); + skippedMessageShown = true; + } + return; + } + + { + const sab = new SharedArrayBuffer(16); + const ab = new ArrayBuffer(16); + const obj = {}; + const arr = []; + + assert.strictEqual(sharedarraybuffer.testIsSharedArrayBuffer(sab), true); + assert.strictEqual(sharedarraybuffer.testIsSharedArrayBuffer(ab), false); + assert.strictEqual(sharedarraybuffer.testIsSharedArrayBuffer(obj), false); + assert.strictEqual(sharedarraybuffer.testIsSharedArrayBuffer(arr), false); + assert.strictEqual(sharedarraybuffer.testIsSharedArrayBuffer(null), false); + assert.strictEqual(sharedarraybuffer.testIsSharedArrayBuffer(undefined), false); + } + + { + const sab = sharedarraybuffer.testCreateSharedArrayBuffer(16); + assert(sab instanceof SharedArrayBuffer); + assert.strictEqual(sab.byteLength, 16); + } + + { + const sab = new SharedArrayBuffer(32); + const byteLength = sharedarraybuffer.testGetSharedArrayBufferInfo(sab); + assert.strictEqual(byteLength, 32); + } + + { + const sab = new SharedArrayBuffer(8); + const result = sharedarraybuffer.testSharedArrayBufferData(sab); + assert.strictEqual(result, true); + + // Check if data was written correctly + const view = new Uint8Array(sab); + for (let i = 0; i < 8; i++) { + assert.strictEqual(view[i], i % 256); + } + } +} diff --git a/test/symbol.cc b/test/symbol.cc index 08ea80393..e7c8b7447 100644 --- a/test/symbol.cc +++ b/test/symbol.cc @@ -1,7 +1,62 @@ #include + +#include +#include + #include "test_helper.h" using namespace Napi; +namespace { + +struct StringLike { + operator std::string() const { return "unexpected-string-key"; } + operator std::string_view() const { return value; } + + std::string value; +}; + +struct RvalueStringLike { + operator std::string() && { return "unexpected-rvalue-string-key"; } + operator std::string_view() && { return value; } + + std::string value; +}; + +struct StringOnlyLike { + operator std::string() const { return value; } + + std::string value; +}; + +struct BothBases : std::string, std::string_view {}; + +struct ViewAndNapiString : std::string_view, Napi::String {}; + +struct StringReferenceLike { + operator std::string&() const { return stringValue; } + operator std::string&&() const { return std::move(stringValue); } + operator std::string_view() const { return viewValue; } + + mutable std::string stringValue; + std::string_view viewValue; +}; + +struct ImplicitAndExplicitStringViewLike { + operator std::string() const { return "unexpected-string-key"; } + + // Copy-initialization must ignore the explicit conversion below. + // Direct-initialization would prefer it for a non-const lvalue. + operator std::string_view() const& { return value; } + + explicit operator std::string_view() & { + return "unexpected-explicit-string-view-key"; + } + + std::string_view value; +}; + +} // namespace + Symbol CreateNewSymbolWithNoArgs(const Napi::CallbackInfo&) { return Napi::Symbol(); } @@ -37,6 +92,65 @@ Symbol FetchSymbolFromGlobalRegistryWithCppKey(const Napi::CallbackInfo& info) { return MaybeUnwrap(Napi::Symbol::For(info.Env(), cppStringKey.Utf8Value())); } +Symbol FetchSymbolFromGlobalRegistryWithStringViewKey( + const Napi::CallbackInfo& info) { + String cppStringKey = info[0].As(); + std::string key = cppStringKey.Utf8Value(); + return MaybeUnwrap(Napi::Symbol::For(info.Env(), std::string_view(key))); +} + +Symbol FetchSymbolFromGlobalRegistryWithStringLikeKey( + const Napi::CallbackInfo& info) { + StringLike key{info[0].As().Utf8Value()}; + return MaybeUnwrap(Napi::Symbol::For(info.Env(), key)); +} + +Symbol FetchSymbolFromGlobalRegistryWithRvalueStringLikeKey( + const Napi::CallbackInfo& info) { + return MaybeUnwrap(Napi::Symbol::For( + info.Env(), RvalueStringLike{info[0].As().Utf8Value()})); +} + +Symbol FetchSymbolFromGlobalRegistryWithStringOnlyLikeKey( + const Napi::CallbackInfo& info) { + StringOnlyLike key{info[0].As().Utf8Value()}; + return MaybeUnwrap(Napi::Symbol::For(info.Env(), key)); +} + +Symbol FetchSymbolFromGlobalRegistryWithBothBasesKey( + const Napi::CallbackInfo& info) { + std::string value = info[0].As().Utf8Value(); + BothBases key; + static_cast(key) = "unexpected-string-key"; + static_cast(key) = value; + return MaybeUnwrap(Symbol::For(info.Env(), key)); +} + +Symbol FetchSymbolFromGlobalRegistryWithViewAndNapiStringKey( + const Napi::CallbackInfo& info) { + Env env = info.Env(); + std::string value = info[0].As().Utf8Value(); + ViewAndNapiString key; + static_cast(key) = value; + static_cast(key) = + Napi::String::New(env, "unexpected-napi-string-key"); + return MaybeUnwrap(Symbol::For(env, key)); +} + +Symbol FetchSymbolFromGlobalRegistryWithStringReferenceKey( + const Napi::CallbackInfo& info) { + std::string value = info[0].As().Utf8Value(); + StringReferenceLike key{"unexpected-string-reference-key", value}; + return MaybeUnwrap(Symbol::For(info.Env(), key)); +} + +Symbol FetchSymbolFromGlobalRegistryWithImplicitViewKey( + const Napi::CallbackInfo& info) { + std::string value = info[0].As().Utf8Value(); + ImplicitAndExplicitStringViewLike key{value}; + return MaybeUnwrap(Symbol::For(info.Env(), key)); +} + Symbol FetchSymbolFromGlobalRegistryWithCKey(const Napi::CallbackInfo& info) { String cppStringKey = info[0].As(); return MaybeUnwrap( @@ -71,6 +185,22 @@ Object InitSymbol(Env env) { Function::New(env, FetchSymbolFromGlobalRegistryWithCKey); exports["getSymbolFromGlobalRegistryWithCppKey"] = Function::New(env, FetchSymbolFromGlobalRegistryWithCppKey); + exports["getSymbolFromGlobalRegistryWithStringViewKey"] = + Function::New(env, FetchSymbolFromGlobalRegistryWithStringViewKey); + exports["getSymbolFromGlobalRegistryWithStringLikeKey"] = + Function::New(env, FetchSymbolFromGlobalRegistryWithStringLikeKey); + exports["getSymbolFromGlobalRegistryWithRvalueStringLikeKey"] = + Function::New(env, FetchSymbolFromGlobalRegistryWithRvalueStringLikeKey); + exports["getSymbolFromGlobalRegistryWithStringOnlyLikeKey"] = + Function::New(env, FetchSymbolFromGlobalRegistryWithStringOnlyLikeKey); + exports["getSymbolFromGlobalRegistryWithBothBasesKey"] = + Function::New(env, FetchSymbolFromGlobalRegistryWithBothBasesKey); + exports["getSymbolFromGlobalRegistryWithViewAndNapiStringKey"] = + Function::New(env, FetchSymbolFromGlobalRegistryWithViewAndNapiStringKey); + exports["getSymbolFromGlobalRegistryWithStringReferenceKey"] = + Function::New(env, FetchSymbolFromGlobalRegistryWithStringReferenceKey); + exports["getSymbolFromGlobalRegistryWithImplicitViewKey"] = + Function::New(env, FetchSymbolFromGlobalRegistryWithImplicitViewKey); exports["testUndefinedSymbolCanBeCreated"] = Function::New(env, TestUndefinedSymbolsCanBeCreated); exports["testNullSymbolCanBeCreated"] = diff --git a/test/symbol.js b/test/symbol.js index bd2e3c83e..6ecbb90d3 100644 --- a/test/symbol.js +++ b/test/symbol.js @@ -42,6 +42,7 @@ function test (binding) { const symbTwo = fetchFunction(symbol); assert(symbOne && symbTwo); assert(symbOne === symbTwo); + assert(symbOne === Symbol.for(symbol)); } assertCanCreateSymbol('testing'); @@ -54,6 +55,28 @@ function test (binding) { assertCanCreateOrFetchGlobalSymbols('data', binding.symbol.getSymbolFromGlobalRegistry); assertCanCreateOrFetchGlobalSymbols('CppKey', binding.symbol.getSymbolFromGlobalRegistryWithCppKey); + assertCanCreateOrFetchGlobalSymbols('StringViewKey', binding.symbol.getSymbolFromGlobalRegistryWithStringViewKey); + assertCanCreateOrFetchGlobalSymbols( + 'StringLikeKey', + binding.symbol.getSymbolFromGlobalRegistryWithStringLikeKey); + assertCanCreateOrFetchGlobalSymbols( + 'RvalueStringLikeKey', + binding.symbol.getSymbolFromGlobalRegistryWithRvalueStringLikeKey); + assertCanCreateOrFetchGlobalSymbols( + 'StringOnlyLikeKey', + binding.symbol.getSymbolFromGlobalRegistryWithStringOnlyLikeKey); + assertCanCreateOrFetchGlobalSymbols( + 'BothBasesKey', + binding.symbol.getSymbolFromGlobalRegistryWithBothBasesKey); + assertCanCreateOrFetchGlobalSymbols( + 'ViewAndNapiStringKey', + binding.symbol.getSymbolFromGlobalRegistryWithViewAndNapiStringKey); + assertCanCreateOrFetchGlobalSymbols( + 'StringReferenceKey', + binding.symbol.getSymbolFromGlobalRegistryWithStringReferenceKey); + assertCanCreateOrFetchGlobalSymbols( + 'ImplicitViewKey', + binding.symbol.getSymbolFromGlobalRegistryWithImplicitViewKey); assertCanCreateOrFetchGlobalSymbols('CKey', binding.symbol.getSymbolFromGlobalRegistryWithCKey); assert(binding.symbol.createNewSymbolWithNoArgs() === undefined); diff --git a/test/threadsafe_function/threadsafe_function.cc b/test/threadsafe_function/threadsafe_function.cc index c6eddc4de..8902b73c5 100644 --- a/test/threadsafe_function/threadsafe_function.cc +++ b/test/threadsafe_function/threadsafe_function.cc @@ -12,10 +12,16 @@ constexpr size_t ARRAY_LENGTH = 10; constexpr size_t MAX_QUEUE_SIZE = 2; static std::thread threads[2]; -static ThreadSafeFunction tsfn; +static ThreadSafeFunction s_tsfn; struct ThreadSafeFunctionInfo { - enum CallType { DEFAULT, BLOCKING, NON_BLOCKING } type; + enum CallType { + DEFAULT, + BLOCKING, + NON_BLOCKING, + NON_BLOCKING_DEFAULT, + NON_BLOCKING_SINGLE_ARG + } type; bool abort; bool startSecondary; FunctionReference jsFinalizeCallback; @@ -29,44 +35,57 @@ struct ThreadSafeFunctionInfo { static int ints[ARRAY_LENGTH]; static void SecondaryThread() { - if (tsfn.Release() != napi_ok) { + if (s_tsfn.Release() != napi_ok) { Error::Fatal("SecondaryThread", "ThreadSafeFunction.Release() failed"); } } // Source thread producing the data static void DataSourceThread() { - ThreadSafeFunctionInfo* info = tsfn.GetContext(); + ThreadSafeFunctionInfo* info = s_tsfn.GetContext(); if (info->startSecondary) { - if (tsfn.Acquire() != napi_ok) { + if (s_tsfn.Acquire() != napi_ok) { Error::Fatal("DataSourceThread", "ThreadSafeFunction.Acquire() failed"); } - threads[1] = std::thread(SecondaryThread); } bool queueWasFull = false; bool queueWasClosing = false; + for (int index = ARRAY_LENGTH - 1; index > -1 && !queueWasClosing; index--) { napi_status status = napi_generic_failure; + auto callback = [](Env env, Function jsCallback, int* data) { jsCallback.Call({Number::New(env, *data)}); }; + auto noArgCallback = [](Env env, Function jsCallback) { + jsCallback.Call({Number::New(env, 42)}); + }; + switch (info->type) { case ThreadSafeFunctionInfo::DEFAULT: - status = tsfn.BlockingCall(); + status = s_tsfn.BlockingCall(); break; case ThreadSafeFunctionInfo::BLOCKING: - status = tsfn.BlockingCall(&ints[index], callback); + status = s_tsfn.BlockingCall(&ints[index], callback); break; case ThreadSafeFunctionInfo::NON_BLOCKING: - status = tsfn.NonBlockingCall(&ints[index], callback); + status = s_tsfn.NonBlockingCall(&ints[index], callback); + break; + case ThreadSafeFunctionInfo::NON_BLOCKING_DEFAULT: + status = s_tsfn.NonBlockingCall(); + break; + + case ThreadSafeFunctionInfo::NON_BLOCKING_SINGLE_ARG: + status = s_tsfn.NonBlockingCall(noArgCallback); break; } - if (info->abort && info->type != ThreadSafeFunctionInfo::NON_BLOCKING) { + if (info->abort && (info->type == ThreadSafeFunctionInfo::BLOCKING || + info->type == ThreadSafeFunctionInfo::DEFAULT)) { // Let's make this thread really busy to give the main thread a chance to // abort / close. std::unique_lock lk(info->protect); @@ -101,7 +120,7 @@ static void DataSourceThread() { Error::Fatal("DataSourceThread", "Queue was never closing"); } - if (!queueWasClosing && tsfn.Release() != napi_ok) { + if (!queueWasClosing && s_tsfn.Release() != napi_ok) { Error::Fatal("DataSourceThread", "ThreadSafeFunction.Release() failed"); } } @@ -110,9 +129,9 @@ static Value StopThread(const CallbackInfo& info) { tsfnInfo.jsFinalizeCallback = Napi::Persistent(info[0].As()); bool abort = info[1].As(); if (abort) { - tsfn.Abort(); + s_tsfn.Abort(); } else { - tsfn.Release(); + s_tsfn.Release(); } { std::lock_guard _(tsfnInfo.protect); @@ -143,14 +162,14 @@ static Value StartThreadInternal(const CallbackInfo& info, tsfnInfo.maxQueueSize = info[3].As().Uint32Value(); tsfnInfo.closeCalledFromJs = false; - tsfn = ThreadSafeFunction::New(info.Env(), - info[0].As(), - "Test", - tsfnInfo.maxQueueSize, - 2, - &tsfnInfo, - JoinTheThreads, - threads); + s_tsfn = ThreadSafeFunction::New(info.Env(), + info[0].As(), + "Test", + tsfnInfo.maxQueueSize, + 2, + &tsfnInfo, + JoinTheThreads, + threads); threads[0] = std::thread(DataSourceThread); @@ -158,7 +177,7 @@ static Value StartThreadInternal(const CallbackInfo& info, } static Value Release(const CallbackInfo& /* info */) { - if (tsfn.Release() != napi_ok) { + if (s_tsfn.Release() != napi_ok) { Error::Fatal("Release", "ThreadSafeFunction.Release() failed"); } return Value(); @@ -176,6 +195,16 @@ static Value StartThreadNoNative(const CallbackInfo& info) { return StartThreadInternal(info, ThreadSafeFunctionInfo::DEFAULT); } +static Value StartThreadNonblockingNoNative(const CallbackInfo& info) { + return StartThreadInternal(info, + ThreadSafeFunctionInfo::NON_BLOCKING_DEFAULT); +} + +static Value StartThreadNonBlockingSingleArg(const CallbackInfo& info) { + return StartThreadInternal(info, + ThreadSafeFunctionInfo::NON_BLOCKING_SINGLE_ARG); +} + Object InitThreadSafeFunction(Env env) { for (size_t index = 0; index < ARRAY_LENGTH; index++) { ints[index] = index; @@ -186,8 +215,12 @@ Object InitThreadSafeFunction(Env env) { exports["MAX_QUEUE_SIZE"] = Number::New(env, MAX_QUEUE_SIZE); exports["startThread"] = Function::New(env, StartThread); exports["startThreadNoNative"] = Function::New(env, StartThreadNoNative); + exports["startThreadNonblockingNoNative"] = + Function::New(env, StartThreadNonblockingNoNative); exports["startThreadNonblocking"] = Function::New(env, StartThreadNonblocking); + exports["startThreadNonblockSingleArg"] = + Function::New(env, StartThreadNonBlockingSingleArg); exports["stopThread"] = Function::New(env, StopThread); exports["release"] = Function::New(env, Release); diff --git a/test/threadsafe_function/threadsafe_function.js b/test/threadsafe_function/threadsafe_function.js index 573c33649..b29dfadb1 100644 --- a/test/threadsafe_function/threadsafe_function.js +++ b/test/threadsafe_function/threadsafe_function.js @@ -5,6 +5,7 @@ const common = require('../common'); module.exports = common.runTest(test); +// Main test body async function test (binding) { const expectedArray = (function (arrayLength) { const result = []; @@ -14,6 +15,8 @@ async function test (binding) { return result; })(binding.threadsafe_function.ARRAY_LENGTH); + const expectedDefaultArray = Array.from({ length: binding.threadsafe_function.ARRAY_LENGTH }, (_, i) => 42); + function testWithJSMarshaller ({ threadStarter, quitAfter, @@ -31,7 +34,7 @@ async function test (binding) { }), !!abort); } }, !!abort, !!launchSecondary, maxQueueSize); - if (threadStarter === 'startThreadNonblocking') { + if ((threadStarter === 'startThreadNonblocking' || threadStarter === 'startThreadNonblockSingleArg')) { // Let's make this thread really busy for a short while to ensure that // the queue fills and the thread receives a napi_queue_full. const start = Date.now(); @@ -40,23 +43,28 @@ async function test (binding) { }); } - await new Promise(function testWithoutJSMarshaller (resolve) { - let callCount = 0; - binding.threadsafe_function.startThreadNoNative(function testCallback () { - callCount++; + function testWithoutJSMarshallers (nativeFunction) { + return new Promise((resolve) => { + let callCount = 0; + nativeFunction(function testCallback () { + callCount++; + + // The default call-into-JS implementation passes no arguments. + assert.strictEqual(arguments.length, 0); + if (callCount === binding.threadsafe_function.ARRAY_LENGTH) { + setImmediate(() => { + binding.threadsafe_function.stopThread(common.mustCall(() => { + resolve(); + }), false); + }); + } + }, false /* abort */, false /* launchSecondary */, + binding.threadsafe_function.MAX_QUEUE_SIZE); + }); + } - // The default call-into-JS implementation passes no arguments. - assert.strictEqual(arguments.length, 0); - if (callCount === binding.threadsafe_function.ARRAY_LENGTH) { - setImmediate(() => { - binding.threadsafe_function.stopThread(common.mustCall(() => { - resolve(); - }), false); - }); - } - }, false /* abort */, false /* launchSecondary */, - binding.threadsafe_function.MAX_QUEUE_SIZE); - }); + await testWithoutJSMarshallers(binding.threadsafe_function.startThreadNoNative); + await testWithoutJSMarshallers(binding.threadsafe_function.startThreadNonblockingNoNative); // Start the thread in blocking mode, and assert that all values are passed. // Quit after it's done. @@ -124,6 +132,15 @@ async function test (binding) { expectedArray ); + assert.deepStrictEqual( + await testWithJSMarshaller({ + threadStarter: 'startThreadNonblockSingleArg', + maxQueueSize: binding.threadsafe_function.MAX_QUEUE_SIZE, + quitAfter: 1 + }), + expectedDefaultArray + ); + // Start the thread in blocking mode, and assert that all values are passed. // Quit early, but let the thread finish. Launch a secondary thread to test // the reference counter incrementing functionality. @@ -150,6 +167,16 @@ async function test (binding) { expectedArray ); + assert.deepStrictEqual( + await testWithJSMarshaller({ + threadStarter: 'startThreadNonblockSingleArg', + maxQueueSize: binding.threadsafe_function.MAX_QUEUE_SIZE, + quitAfter: 1, + launchSecondary: true + }), + expectedDefaultArray + ); + // Start the thread in blocking mode, and assert that it could not finish. // Quit early by aborting. assert.strictEqual( @@ -185,4 +212,14 @@ async function test (binding) { })).indexOf(0), -1 ); + + assert.strictEqual( + (await testWithJSMarshaller({ + threadStarter: 'startThreadNonblockSingleArg', + quitAfter: 1, + maxQueueSize: binding.threadsafe_function.MAX_QUEUE_SIZE, + abort: true + })).indexOf(0), + -1 + ); } diff --git a/test/threadsafe_function/threadsafe_function_ctx.cc b/test/threadsafe_function/threadsafe_function_ctx.cc index 470de12fd..abe92fdf0 100644 --- a/test/threadsafe_function/threadsafe_function_ctx.cc +++ b/test/threadsafe_function/threadsafe_function_ctx.cc @@ -1,3 +1,4 @@ +#include #include "napi.h" #if (NAPI_VERSION > 3) @@ -8,7 +9,7 @@ namespace { class TSFNWrap : public ObjectWrap { public: - static Object Init(Napi::Env env, Object exports); + static Function Init(Napi::Env env); TSFNWrap(const CallbackInfo& info); Napi::Value GetContext(const CallbackInfo& /*info*/) { @@ -28,15 +29,13 @@ class TSFNWrap : public ObjectWrap { std::unique_ptr _deferred; }; -Object TSFNWrap::Init(Napi::Env env, Object exports) { +Function TSFNWrap::Init(Napi::Env env) { Function func = DefineClass(env, "TSFNWrap", {InstanceMethod("getContext", &TSFNWrap::GetContext), InstanceMethod("release", &TSFNWrap::Release)}); - - exports.Set("TSFNWrap", func); - return exports; + return func; } TSFNWrap::TSFNWrap(const CallbackInfo& info) : ObjectWrap(info) { @@ -59,11 +58,98 @@ TSFNWrap::TSFNWrap(const CallbackInfo& info) : ObjectWrap(info) { delete ctx; }); } +struct SimpleTestContext { + SimpleTestContext(int val) : _val(val) {} + int _val = -1; +}; + +void AssertGetContextFromVariousTSOverloads(const CallbackInfo& info) { + Env env = info.Env(); + Function emptyFunc; + + SimpleTestContext* ctx = new SimpleTestContext(42); + ThreadSafeFunction fn = + ThreadSafeFunction::New(env, emptyFunc, "testResource", 1, 1, ctx); + + assert(fn.GetContext() == ctx); + delete ctx; + fn.Release(); + + fn = ThreadSafeFunction::New(env, emptyFunc, "testRes", 1, 1, [](Env) {}); + fn.Release(); + + ctx = new SimpleTestContext(42); + fn = ThreadSafeFunction::New(env, + emptyFunc, + Object::New(env), + "resStrObj", + 1, + 1, + ctx, + [](Env, SimpleTestContext*) {}); + assert(fn.GetContext() == ctx); + delete ctx; + fn.Release(); + + fn = ThreadSafeFunction::New( + env, emptyFunc, Object::New(env), "resStrObj", 1, 1); + fn.Release(); + + ctx = new SimpleTestContext(42); + fn = ThreadSafeFunction::New( + env, emptyFunc, Object::New(env), "resStrObj", 1, 1, ctx); + assert(fn.GetContext() == ctx); + delete ctx; + fn.Release(); + + using FinalizerDataType = int; + FinalizerDataType* finalizerData = new int(42); + fn = ThreadSafeFunction::New( + env, + emptyFunc, + Object::New(env), + "resObject", + 1, + 1, + [](Env, FinalizerDataType* data) { + assert(*data == 42); + delete data; + }, + finalizerData); + fn.Release(); + + ctx = new SimpleTestContext(42); + FinalizerDataType* finalizerDataB = new int(42); + + fn = ThreadSafeFunction::New( + env, + emptyFunc, + Object::New(env), + "resObject", + 1, + 1, + ctx, + [](Env, FinalizerDataType* _data, SimpleTestContext* _ctx) { + assert(*_data == 42); + assert(_ctx->_val == 42); + delete _data; + delete _ctx; + }, + finalizerDataB); + assert(fn.GetContext() == ctx); + fn.Release(); +} } // namespace Object InitThreadSafeFunctionCtx(Env env) { - return TSFNWrap::Init(env, Object::New(env)); + Object exports = Object::New(env); + Function tsfnWrap = TSFNWrap::Init(env); + exports.Set("TSFNWrap", tsfnWrap); + exports.Set("AssertFnReturnCorrectCxt", + Function::New(env, AssertGetContextFromVariousTSOverloads)); + + return exports; } #endif diff --git a/test/threadsafe_function/threadsafe_function_ctx.js b/test/threadsafe_function/threadsafe_function_ctx.js index 258e220b1..4ba707b79 100644 --- a/test/threadsafe_function/threadsafe_function_ctx.js +++ b/test/threadsafe_function/threadsafe_function_ctx.js @@ -9,4 +9,5 @@ async function test (binding) { const tsfn = new binding.threadsafe_function_ctx.TSFNWrap(ctx); assert(tsfn.getContext() === ctx); await tsfn.release(); + binding.threadsafe_function_ctx.AssertFnReturnCorrectCxt(); } diff --git a/test/threadsafe_function/threadsafe_function_exception.cc b/test/threadsafe_function/threadsafe_function_exception.cc new file mode 100644 index 000000000..9ffe703ec --- /dev/null +++ b/test/threadsafe_function/threadsafe_function_exception.cc @@ -0,0 +1,50 @@ +#include +#include "napi.h" +#include "test_helper.h" + +#if (NAPI_VERSION > 3) + +using namespace Napi; + +namespace { + +void CallJS(napi_env env, napi_value /* callback */, void* /*data*/) { + Napi::Error error = Napi::Error::New(env, "test-from-native"); + NAPI_THROW_VOID(error); +} + +void TestCall(const CallbackInfo& info) { + Napi::Env env = info.Env(); + + ThreadSafeFunction wrapped = + ThreadSafeFunction::New(env, + info[0].As(), + Object::New(env), + String::New(env, "Test"), + 0, + 1); + wrapped.BlockingCall(static_cast(nullptr)); + wrapped.Release(); +} + +void TestCallWithNativeCallback(const CallbackInfo& info) { + Napi::Env env = info.Env(); + + ThreadSafeFunction wrapped = ThreadSafeFunction::New( + env, Napi::Function(), Object::New(env), String::New(env, "Test"), 0, 1); + wrapped.BlockingCall(static_cast(nullptr), CallJS); + wrapped.Release(); +} + +} // namespace + +Object InitThreadSafeFunctionException(Env env) { + Object exports = Object::New(env); + exports["testCall"] = Function::New(env, TestCall); + exports["testCallWithNativeCallback"] = + Function::New(env, TestCallWithNativeCallback); + + return exports; +} + +#endif diff --git a/test/threadsafe_function/threadsafe_function_exception.js b/test/threadsafe_function/threadsafe_function_exception.js new file mode 100644 index 000000000..688a53bcf --- /dev/null +++ b/test/threadsafe_function/threadsafe_function_exception.js @@ -0,0 +1,20 @@ +'use strict'; + +const common = require('../common'); + +module.exports = common.runTest(test); + +const execArgv = ['--force-node-api-uncaught-exceptions-policy=true']; +async function test () { + await common.runTestInChildProcess({ + suite: 'threadsafe_function_exception', + testName: 'testCall', + execArgv + }); + + await common.runTestInChildProcess({ + suite: 'threadsafe_function_exception', + testName: 'testCallWithNativeCallback', + execArgv + }); +} diff --git a/test/threadsafe_function/threadsafe_function_unref.cc b/test/threadsafe_function/threadsafe_function_unref.cc index 6c278e7ad..5fcc5dd60 100644 --- a/test/threadsafe_function/threadsafe_function_unref.cc +++ b/test/threadsafe_function/threadsafe_function_unref.cc @@ -31,11 +31,24 @@ static Value TestUnref(const CallbackInfo& info) { return info.Env().Undefined(); } +static Value TestRef(const CallbackInfo& info) { + Function cb = info[1].As(); + + auto tsfn = ThreadSafeFunction::New(info.Env(), cb, "testRes", 1, 1); + + tsfn.BlockingCall(); + tsfn.Unref(info.Env()); + tsfn.Ref(info.Env()); + + return info.Env().Undefined(); +} + } // namespace Object InitThreadSafeFunctionUnref(Env env) { Object exports = Object::New(env); exports["testUnref"] = Function::New(env, TestUnref); + exports["testRef"] = Function::New(env, TestRef); return exports; } diff --git a/test/threadsafe_function/threadsafe_function_unref.js b/test/threadsafe_function/threadsafe_function_unref.js index e041e82d9..1f0e96b87 100644 --- a/test/threadsafe_function/threadsafe_function_unref.js +++ b/test/threadsafe_function/threadsafe_function_unref.js @@ -11,43 +11,88 @@ const isMainProcess = process.argv[1] !== __filename; * - Child process: creates TSFN. Native module Unref's via setTimeout after some time but does NOT call Release. * * Main process should expect child process to exit. + * + * We also added a new test case for `Ref`. The idea being, if a TSFN is active, the event loop that it belongs to should not exit + * Our setup is similar to the test for the `Unref` case, with the difference being now we are expecting the child process to hang */ if (isMainProcess) { module.exports = require('../common').runTestWithBindingPath(test); } else { - test(process.argv[2]); + const isTestingRef = (process.argv[3] === 'true'); + + if (isTestingRef) { + execTSFNRefTest(process.argv[2]); + } else { + execTSFNUnrefTest(process.argv[2]); + } +} + +function testUnRefCallback (resolve, reject, bindingFile) { + const child = require('../napi_child').spawn(process.argv[0], [ + '--expose-gc', __filename, bindingFile, false + ], { stdio: 'inherit' }); + + let timeout = setTimeout(function () { + child.kill(); + timeout = 0; + reject(new Error('Expected child to die')); + }, 5000); + + child.on('error', (err) => { + clearTimeout(timeout); + timeout = 0; + reject(new Error(err)); + }); + + child.on('close', (code) => { + if (timeout) clearTimeout(timeout); + assert.strictEqual(code, 0, 'Expected return value 0'); + resolve(); + }); +} + +function testRefCallback (resolve, reject, bindingFile) { + const child = require('../napi_child').spawn(process.argv[0], [ + '--expose-gc', __filename, bindingFile, true + ], { stdio: 'inherit' }); + + let timeout = setTimeout(function () { + child.kill(); + timeout = 0; + resolve(); + }, 1000); + + child.on('error', (err) => { + clearTimeout(timeout); + timeout = 0; + reject(new Error(err)); + }); + + child.on('close', (code) => { + if (timeout) clearTimeout(timeout); + + reject(new Error('We expected Child to hang')); + }); } function test (bindingFile) { - if (isMainProcess) { - // Main process + // Main process + return new Promise((resolve, reject) => { + testUnRefCallback(resolve, reject, bindingFile); + }).then(() => { return new Promise((resolve, reject) => { - const child = require('../napi_child').spawn(process.argv[0], [ - '--expose-gc', __filename, bindingFile - ], { stdio: 'inherit' }); - - let timeout = setTimeout(function () { - child.kill(); - timeout = 0; - reject(new Error('Expected child to die')); - }, 5000); - - child.on('error', (err) => { - clearTimeout(timeout); - timeout = 0; - reject(new Error(err)); - }); - - child.on('close', (code) => { - if (timeout) clearTimeout(timeout); - assert.strictEqual(code, 0, 'Expected return value 0'); - resolve(); - }); + testRefCallback(resolve, reject, bindingFile); }); - } else { - // Child process - const binding = require(bindingFile); - binding.threadsafe_function_unref.testUnref({}, () => { }); - } + }); +} + +function execTSFNUnrefTest (bindingFile) { + const binding = require(bindingFile); + binding.threadsafe_function_unref.testUnref({}, () => { }); +} + +function execTSFNRefTest (bindingFile) { + const binding = require(bindingFile); + binding.threadsafe_function_unref.testRef({}, () => { }); } diff --git a/test/type_taggable.cc b/test/type_taggable.cc new file mode 100644 index 000000000..ac58f9281 --- /dev/null +++ b/test/type_taggable.cc @@ -0,0 +1,66 @@ +#include "napi.h" + +#if (NAPI_VERSION > 7) + +using namespace Napi; + +static const napi_type_tag type_tags[5] = { + {0xdaf987b3cc62481a, 0xb745b0497f299531}, + {0xbb7936c374084d9b, 0xa9548d0762eeedb9}, + {0xa5ed9ce2e4c00c38, 0}, + {0, 0}, + {0xa5ed9ce2e4c00c38, 0xdaf987b3cc62481a}, +}; + +template +class TestTypeTaggable { + public: + static Value TypeTaggedInstance(const CallbackInfo& info) { + TypeTaggable instance = Factory(info.Env()); + uint32_t type_index = info[0].As().Int32Value(); + + instance.TypeTag(&type_tags[type_index]); + + return instance; + } + + static Value CheckTypeTag(const CallbackInfo& info) { + uint32_t type_index = info[0].As().Int32Value(); + TypeTaggable instance = info[1].UnsafeAs(); + + return Boolean::New(info.Env(), + instance.CheckTypeTag(&type_tags[type_index])); + } +}; + +TypeTaggable ObjectFactory(Env env) { + return Object::New(env); +} + +TypeTaggable ExternalFactory(Env env) { + // External does not accept a nullptr for its data. + return External::New(env, reinterpret_cast(0x1)); +} + +using TestObject = TestTypeTaggable; +using TestExternal = TestTypeTaggable>; + +Object InitTypeTaggable(Env env) { + Object exports = Object::New(env); + + Object external = Object::New(env); + exports["external"] = external; + external["checkTypeTag"] = Function::New(env, &TestExternal::CheckTypeTag); + external["typeTaggedInstance"] = + Function::New(env, &TestExternal::TypeTaggedInstance); + + Object object = Object::New(env); + exports["object"] = object; + object["checkTypeTag"] = Function::New(env, &TestObject::CheckTypeTag); + object["typeTaggedInstance"] = + Function::New(env, &TestObject::TypeTaggedInstance); + + return exports; +} + +#endif diff --git a/test/type_taggable.js b/test/type_taggable.js new file mode 100644 index 000000000..7bc843cf6 --- /dev/null +++ b/test/type_taggable.js @@ -0,0 +1,59 @@ +'use strict'; + +const assert = require('assert'); + +module.exports = require('./common').runTest(test); + +function testTypeTaggable ({ typeTaggedInstance, checkTypeTag }) { + const obj1 = typeTaggedInstance(0); + const obj2 = typeTaggedInstance(1); + + // Verify that type tags are correctly accepted. + assert.strictEqual(checkTypeTag(0, obj1), true); + assert.strictEqual(checkTypeTag(1, obj2), true); + + // Verify that wrongly tagged objects are rejected. + assert.strictEqual(checkTypeTag(0, obj2), false); + assert.strictEqual(checkTypeTag(1, obj1), false); + + // Verify that untagged objects are rejected. + assert.strictEqual(checkTypeTag(0, {}), false); + assert.strictEqual(checkTypeTag(1, {}), false); + + // Node v14 and v16 have an issue checking type tags if the `upper` in + // `napi_type_tag` is 0, so these tests can only be performed on Node version + // >=18. See: + // - https://github.com/nodejs/node/issues/43786 + // - https://github.com/nodejs/node/pull/43788 + const nodeVersion = parseInt(process.versions.node.split('.')[0]); + if (nodeVersion < 18) { + return; + } + + const obj3 = typeTaggedInstance(2); + const obj4 = typeTaggedInstance(3); + + // Verify that untagged objects are rejected. + assert.strictEqual(checkTypeTag(0, {}), false); + assert.strictEqual(checkTypeTag(1, {}), false); + + // Verify that type tags are correctly accepted. + assert.strictEqual(checkTypeTag(0, obj1), true); + assert.strictEqual(checkTypeTag(1, obj2), true); + assert.strictEqual(checkTypeTag(2, obj3), true); + assert.strictEqual(checkTypeTag(3, obj4), true); + + // Verify that wrongly tagged objects are rejected. + assert.strictEqual(checkTypeTag(0, obj2), false); + assert.strictEqual(checkTypeTag(1, obj1), false); + assert.strictEqual(checkTypeTag(0, obj3), false); + assert.strictEqual(checkTypeTag(1, obj4), false); + assert.strictEqual(checkTypeTag(2, obj4), false); + assert.strictEqual(checkTypeTag(3, obj3), false); + assert.strictEqual(checkTypeTag(4, obj3), false); +} + +function test (binding) { + testTypeTaggable(binding.type_taggable.external); + testTypeTaggable(binding.type_taggable.object); +} diff --git a/test/typed_threadsafe_function/typed_threadsafe_function.cc b/test/typed_threadsafe_function/typed_threadsafe_function.cc index c25268aaf..ce345b8f0 100644 --- a/test/typed_threadsafe_function/typed_threadsafe_function.cc +++ b/test/typed_threadsafe_function/typed_threadsafe_function.cc @@ -40,23 +40,23 @@ static void TSFNCallJS(Env env, } using TSFN = TypedThreadSafeFunction; -static TSFN tsfn; +static TSFN s_tsfn; // Thread data to transmit to JS static int ints[ARRAY_LENGTH]; static void SecondaryThread() { - if (tsfn.Release() != napi_ok) { + if (s_tsfn.Release() != napi_ok) { Error::Fatal("TypedSecondaryThread", "ThreadSafeFunction.Release() failed"); } } // Source thread producing the data static void DataSourceThread() { - ThreadSafeFunctionInfo* info = tsfn.GetContext(); + ThreadSafeFunctionInfo* info = s_tsfn.GetContext(); if (info->startSecondary) { - if (tsfn.Acquire() != napi_ok) { + if (s_tsfn.Acquire() != napi_ok) { Error::Fatal("TypedDataSourceThread", "ThreadSafeFunction.Acquire() failed"); } @@ -71,13 +71,13 @@ static void DataSourceThread() { switch (info->type) { case ThreadSafeFunctionInfo::DEFAULT: - status = tsfn.BlockingCall(); + status = s_tsfn.BlockingCall(); break; case ThreadSafeFunctionInfo::BLOCKING: - status = tsfn.BlockingCall(&ints[index]); + status = s_tsfn.BlockingCall(&ints[index]); break; case ThreadSafeFunctionInfo::NON_BLOCKING: - status = tsfn.NonBlockingCall(&ints[index]); + status = s_tsfn.NonBlockingCall(&ints[index]); break; } @@ -117,7 +117,7 @@ static void DataSourceThread() { Error::Fatal("TypedDataSourceThread", "Queue was never closing"); } - if (!queueWasClosing && tsfn.Release() != napi_ok) { + if (!queueWasClosing && s_tsfn.Release() != napi_ok) { Error::Fatal("TypedDataSourceThread", "ThreadSafeFunction.Release() failed"); } @@ -127,9 +127,9 @@ static Value StopThread(const CallbackInfo& info) { tsfnInfo.jsFinalizeCallback = Napi::Persistent(info[0].As()); bool abort = info[1].As(); if (abort) { - tsfn.Abort(); + s_tsfn.Abort(); } else { - tsfn.Release(); + s_tsfn.Release(); } { std::lock_guard _(tsfnInfo.protect); @@ -160,15 +160,15 @@ static Value StartThreadInternal(const CallbackInfo& info, tsfnInfo.maxQueueSize = info[3].As().Uint32Value(); tsfnInfo.closeCalledFromJs = false; - tsfn = TSFN::New(info.Env(), - info[0].As(), - Object::New(info.Env()), - "Test", - tsfnInfo.maxQueueSize, - 2, - &tsfnInfo, - JoinTheThreads, - threads); + s_tsfn = TSFN::New(info.Env(), + info[0].As(), + Object::New(info.Env()), + "Test", + tsfnInfo.maxQueueSize, + 2, + &tsfnInfo, + JoinTheThreads, + threads); threads[0] = std::thread(DataSourceThread); @@ -176,7 +176,7 @@ static Value StartThreadInternal(const CallbackInfo& info, } static Value Release(const CallbackInfo& /* info */) { - if (tsfn.Release() != napi_ok) { + if (s_tsfn.Release() != napi_ok) { Error::Fatal("Release", "TypedThreadSafeFunction.Release() failed"); } return Value(); diff --git a/test/typed_threadsafe_function/typed_threadsafe_function_ctx.cc b/test/typed_threadsafe_function/typed_threadsafe_function_ctx.cc index ee70bb352..7cf2209dc 100644 --- a/test/typed_threadsafe_function/typed_threadsafe_function_ctx.cc +++ b/test/typed_threadsafe_function/typed_threadsafe_function_ctx.cc @@ -1,3 +1,4 @@ +#include #include "napi.h" #if (NAPI_VERSION > 3) @@ -11,7 +12,7 @@ namespace { class TSFNWrap : public ObjectWrap { public: - static Object Init(Napi::Env env, Object exports); + static Function Init(Napi::Env env); TSFNWrap(const CallbackInfo& info); Napi::Value GetContext(const CallbackInfo& /*info*/) { @@ -31,15 +32,14 @@ class TSFNWrap : public ObjectWrap { std::unique_ptr _deferred; }; -Object TSFNWrap::Init(Napi::Env env, Object exports) { +Function TSFNWrap::Init(Napi::Env env) { Function func = DefineClass(env, "TSFNWrap", {InstanceMethod("getContext", &TSFNWrap::GetContext), InstanceMethod("release", &TSFNWrap::Release)}); - exports.Set("TSFNWrap", func); - return exports; + return func; } TSFNWrap::TSFNWrap(const CallbackInfo& info) : ObjectWrap(info) { @@ -61,8 +61,60 @@ TSFNWrap::TSFNWrap(const CallbackInfo& info) : ObjectWrap(info) { } // namespace +struct SimpleTestContext { + SimpleTestContext(int val) : _val(val) {} + int _val = -1; +}; + +// A simple test to check that the context has been set successfully +void AssertGetContextFromTSFNNoFinalizerIsCorrect(const CallbackInfo& info) { + // Test the overload where we provide a resource name but no finalizer + using TSFN = TypedThreadSafeFunction; + SimpleTestContext* ctx = new SimpleTestContext(42); + TSFN tsfn = TSFN::New(info.Env(), "testRes", 1, 1, ctx); + + assert(tsfn.GetContext() == ctx); + delete ctx; + tsfn.Release(); + + // Test the other overload where we provide a async resource object, res name + // but no finalizer + ctx = new SimpleTestContext(52); + tsfn = TSFN::New( + info.Env(), Object::New(info.Env()), "testResourceObject", 1, 1, ctx); + + assert(tsfn.GetContext() == ctx); + delete ctx; + tsfn.Release(); + + ctx = new SimpleTestContext(52); + tsfn = TSFN::New(info.Env(), + "resStrings", + 1, + 1, + ctx, + [](Napi::Env, void*, SimpleTestContext*) {}); + + assert(tsfn.GetContext() == ctx); + delete ctx; + tsfn.Release(); + + ctx = new SimpleTestContext(52); + Function emptyFunc; + tsfn = TSFN::New(info.Env(), emptyFunc, "resString", 1, 1, ctx); + assert(tsfn.GetContext() == ctx); + delete ctx; + tsfn.Release(); +} + Object InitTypedThreadSafeFunctionCtx(Env env) { - return TSFNWrap::Init(env, Object::New(env)); + Object exports = Object::New(env); + Function tsfnWrap = TSFNWrap::Init(env); + + exports.Set("TSFNWrap", tsfnWrap); + exports.Set("AssertTSFNReturnCorrectCxt", + Function::New(env, AssertGetContextFromTSFNNoFinalizerIsCorrect)); + return exports; } #endif diff --git a/test/typed_threadsafe_function/typed_threadsafe_function_ctx.js b/test/typed_threadsafe_function/typed_threadsafe_function_ctx.js index b8c842bc6..ddbddccb9 100644 --- a/test/typed_threadsafe_function/typed_threadsafe_function_ctx.js +++ b/test/typed_threadsafe_function/typed_threadsafe_function_ctx.js @@ -9,4 +9,6 @@ async function test (binding) { const tsfn = new binding.typed_threadsafe_function_ctx.TSFNWrap(ctx); assert(tsfn.getContext() === ctx); await tsfn.release(); + + binding.typed_threadsafe_function_ctx.AssertTSFNReturnCorrectCxt(); } diff --git a/test/typed_threadsafe_function/typed_threadsafe_function_exception.cc b/test/typed_threadsafe_function/typed_threadsafe_function_exception.cc new file mode 100644 index 000000000..c55ca23a4 --- /dev/null +++ b/test/typed_threadsafe_function/typed_threadsafe_function_exception.cc @@ -0,0 +1,39 @@ +#include +#include "napi.h" +#include "test_helper.h" + +#if (NAPI_VERSION > 3) + +using namespace Napi; + +namespace { + +void CallJS(Napi::Env env, + Napi::Function /* callback */, + std::nullptr_t* /* context */, + void* /*data*/) { + Napi::Error error = Napi::Error::New(env, "test-from-native"); + NAPI_THROW_VOID(error); +} + +using TSFN = TypedThreadSafeFunction; + +void TestCall(const CallbackInfo& info) { + Napi::Env env = info.Env(); + + TSFN wrapped = TSFN::New( + env, Napi::Function(), Object::New(env), String::New(env, "Test"), 0, 1); + wrapped.BlockingCall(static_cast(nullptr)); + wrapped.Release(); +} + +} // namespace + +Object InitTypedThreadSafeFunctionException(Env env) { + Object exports = Object::New(env); + exports["testCall"] = Function::New(env, TestCall); + + return exports; +} + +#endif diff --git a/test/typed_threadsafe_function/typed_threadsafe_function_exception.js b/test/typed_threadsafe_function/typed_threadsafe_function_exception.js new file mode 100644 index 000000000..60ff67363 --- /dev/null +++ b/test/typed_threadsafe_function/typed_threadsafe_function_exception.js @@ -0,0 +1,13 @@ +'use strict'; + +const common = require('../common'); + +module.exports = common.runTest(test); + +async function test () { + await common.runTestInChildProcess({ + suite: 'typed_threadsafe_function_exception', + testName: 'testCall', + execArgv: ['--force-node-api-uncaught-exceptions-policy=true'] + }); +} diff --git a/test/typed_threadsafe_function/typed_threadsafe_function_ptr.cc b/test/typed_threadsafe_function/typed_threadsafe_function_ptr.cc index 891fd560c..a4da743e1 100644 --- a/test/typed_threadsafe_function/typed_threadsafe_function_ptr.cc +++ b/test/typed_threadsafe_function/typed_threadsafe_function_ptr.cc @@ -16,12 +16,16 @@ static Value Test(const CallbackInfo& info) { return info.Env().Undefined(); } +static Value ExtractEnvNullValue(const CallbackInfo& info) { + return info.Env().Null(); +} + } // namespace Object InitTypedThreadSafeFunctionPtr(Env env) { Object exports = Object::New(env); exports["test"] = Function::New(env, Test); - + exports["null"] = Function::New(env, ExtractEnvNullValue); return exports; } diff --git a/test/typed_threadsafe_function/typed_threadsafe_function_ptr.js b/test/typed_threadsafe_function/typed_threadsafe_function_ptr.js index d0e82d213..e91921755 100644 --- a/test/typed_threadsafe_function/typed_threadsafe_function_ptr.js +++ b/test/typed_threadsafe_function/typed_threadsafe_function_ptr.js @@ -1,7 +1,8 @@ 'use strict'; - +const assert = require('assert'); module.exports = require('../common').runTest(test); function test (binding) { - binding.typed_threadsafe_function_ptr.test({}, () => {}); + assert(binding.typed_threadsafe_function_ptr.test({}, () => {}) === undefined); + assert(binding.typed_threadsafe_function_ptr.null() === null); } diff --git a/test/typedarray.cc b/test/typedarray.cc index 3ee9f3f2a..795f2819e 100644 --- a/test/typedarray.cc +++ b/test/typedarray.cc @@ -21,7 +21,7 @@ namespace { Value CreateTypedArray(const CallbackInfo& info) { std::string arrayType = info[0].As(); size_t length = info[1].As().Uint32Value(); - ArrayBuffer buffer = info[2].As(); + Value buffer = info[2]; size_t bufferOffset = info[3].IsUndefined() ? 0 : info[3].As().Uint32Value(); @@ -32,7 +32,7 @@ Value CreateTypedArray(const CallbackInfo& info) { : NAPI_TYPEDARRAY_NEW_BUFFER(Int8Array, info.Env(), length, - buffer, + buffer.As(), bufferOffset, napi_int8_array); } else if (arrayType == "uint8") { @@ -42,7 +42,7 @@ Value CreateTypedArray(const CallbackInfo& info) { : NAPI_TYPEDARRAY_NEW_BUFFER(Uint8Array, info.Env(), length, - buffer, + buffer.As(), bufferOffset, napi_uint8_array); } else if (arrayType == "uint8_clamped") { @@ -50,7 +50,7 @@ Value CreateTypedArray(const CallbackInfo& info) { ? Uint8Array::New(info.Env(), length, napi_uint8_clamped_array) : Uint8Array::New(info.Env(), length, - buffer, + buffer.As(), bufferOffset, napi_uint8_clamped_array); } else if (arrayType == "int16") { @@ -60,7 +60,7 @@ Value CreateTypedArray(const CallbackInfo& info) { : NAPI_TYPEDARRAY_NEW_BUFFER(Int16Array, info.Env(), length, - buffer, + buffer.As(), bufferOffset, napi_int16_array); } else if (arrayType == "uint16") { @@ -70,7 +70,7 @@ Value CreateTypedArray(const CallbackInfo& info) { : NAPI_TYPEDARRAY_NEW_BUFFER(Uint16Array, info.Env(), length, - buffer, + buffer.As(), bufferOffset, napi_uint16_array); } else if (arrayType == "int32") { @@ -80,7 +80,7 @@ Value CreateTypedArray(const CallbackInfo& info) { : NAPI_TYPEDARRAY_NEW_BUFFER(Int32Array, info.Env(), length, - buffer, + buffer.As(), bufferOffset, napi_int32_array); } else if (arrayType == "uint32") { @@ -90,7 +90,7 @@ Value CreateTypedArray(const CallbackInfo& info) { : NAPI_TYPEDARRAY_NEW_BUFFER(Uint32Array, info.Env(), length, - buffer, + buffer.As(), bufferOffset, napi_uint32_array); } else if (arrayType == "float32") { @@ -100,7 +100,7 @@ Value CreateTypedArray(const CallbackInfo& info) { : NAPI_TYPEDARRAY_NEW_BUFFER(Float32Array, info.Env(), length, - buffer, + buffer.As(), bufferOffset, napi_float32_array); } else if (arrayType == "float64") { @@ -110,7 +110,7 @@ Value CreateTypedArray(const CallbackInfo& info) { : NAPI_TYPEDARRAY_NEW_BUFFER(Float64Array, info.Env(), length, - buffer, + buffer.As(), bufferOffset, napi_float64_array); #if (NAPI_VERSION > 5) @@ -121,7 +121,7 @@ Value CreateTypedArray(const CallbackInfo& info) { : NAPI_TYPEDARRAY_NEW_BUFFER(BigInt64Array, info.Env(), length, - buffer, + buffer.As(), bufferOffset, napi_bigint64_array); } else if (arrayType == "biguint64") { @@ -131,7 +131,7 @@ Value CreateTypedArray(const CallbackInfo& info) { : NAPI_TYPEDARRAY_NEW_BUFFER(BigUint64Array, info.Env(), length, - buffer, + buffer.As(), bufferOffset, napi_biguint64_array); #endif @@ -208,8 +208,8 @@ Value CheckBufferContent(const CallbackInfo& info) { case napi_uint8_array: return Boolean::New( info.Env(), - TypedArrayDataIsEquivalent(info[0].As(), - info[1].As())); + TypedArrayDataIsEquivalent(info[0].As(), + info[1].As())); case napi_uint8_clamped_array: return Boolean::New( @@ -297,6 +297,11 @@ Value GetTypedArrayBuffer(const CallbackInfo& info) { return array.ArrayBuffer(); } +Value GetTypedArrayBufferValue(const CallbackInfo& info) { + TypedArray array = info[0].As(); + return array.Buffer(); +} + Value GetTypedArrayElement(const CallbackInfo& info) { TypedArray array = info[0].As(); size_t index = info[1].As().Uint32Value(); @@ -335,35 +340,39 @@ Value GetTypedArrayElement(const CallbackInfo& info) { void SetTypedArrayElement(const CallbackInfo& info) { TypedArray array = info[0].As(); size_t index = info[1].As().Uint32Value(); - Number value = info[2].As(); + Value value = info[2]; switch (array.TypedArrayType()) { case napi_int8_array: - array.As()[index] = static_cast(value.Int32Value()); + array.As()[index] = + static_cast(value.As().Int32Value()); break; case napi_uint8_array: - array.As()[index] = static_cast(value.Uint32Value()); + array.As()[index] = + static_cast(value.As().Uint32Value()); break; case napi_uint8_clamped_array: - array.As()[index] = static_cast(value.Uint32Value()); + array.As()[index] = + static_cast(value.As().Uint32Value()); break; case napi_int16_array: - array.As()[index] = static_cast(value.Int32Value()); + array.As()[index] = + static_cast(value.As().Int32Value()); break; case napi_uint16_array: array.As()[index] = - static_cast(value.Uint32Value()); + static_cast(value.As().Uint32Value()); break; case napi_int32_array: - array.As()[index] = value.Int32Value(); + array.As()[index] = value.As().Int32Value(); break; case napi_uint32_array: - array.As()[index] = value.Uint32Value(); + array.As()[index] = value.As().Uint32Value(); break; case napi_float32_array: - array.As()[index] = value.FloatValue(); + array.As()[index] = value.As().FloatValue(); break; case napi_float64_array: - array.As()[index] = value.DoubleValue(); + array.As()[index] = value.As().DoubleValue(); break; #if (NAPI_VERSION > 5) case napi_bigint64_array: { @@ -385,12 +394,30 @@ void SetTypedArrayElement(const CallbackInfo& info) { } } +#ifdef NODE_API_EXPERIMENTAL_HAS_SHAREDARRAYBUFFER +Value CreateInt8TypedArrayFromSharedArrayBuffer(const CallbackInfo& info) { + auto buffer = info[0].As(); + size_t length = buffer.ByteLength(); + + return NAPI_TYPEDARRAY_NEW_BUFFER(Int8Array, + info.Env(), + length, + buffer.As(), + 0, + napi_int8_array); +} +#endif + } // end anonymous namespace Object InitTypedArray(Env env) { Object exports = Object::New(env); exports["createTypedArray"] = Function::New(env, CreateTypedArray); +#ifdef NODE_API_EXPERIMENTAL_HAS_SHAREDARRAYBUFFER + exports["createInt8TypedArrayFromSharedArrayBuffer"] = + Function::New(env, CreateInt8TypedArrayFromSharedArrayBuffer); +#endif exports["createInvalidTypedArray"] = Function::New(env, CreateInvalidTypedArray); exports["getTypedArrayType"] = Function::New(env, GetTypedArrayType); @@ -401,6 +428,8 @@ Object InitTypedArray(Env env) { exports["getTypedArrayByteLength"] = Function::New(env, GetTypedArrayByteLength); exports["getTypedArrayBuffer"] = Function::New(env, GetTypedArrayBuffer); + exports["getTypedArrayBufferValue"] = + Function::New(env, GetTypedArrayBufferValue); exports["getTypedArrayElement"] = Function::New(env, GetTypedArrayElement); exports["setTypedArrayElement"] = Function::New(env, SetTypedArrayElement); exports["checkBufferContent"] = Function::New(env, CheckBufferContent); diff --git a/test/typedarray.js b/test/typedarray.js index f7224efb7..b6ae4a7f7 100644 --- a/test/typedarray.js +++ b/test/typedarray.js @@ -2,6 +2,8 @@ const assert = require('assert'); +let runSharedArrayBufferTests = true; + module.exports = require('./common').runTest(test); function test (binding) { @@ -61,6 +63,9 @@ function test (binding) { const b = binding.typedarray.getTypedArrayBuffer(t); assert.ok(b instanceof ArrayBuffer); + const bAsValue = binding.typedarray.getTypedArrayBufferValue(t); + assert.ok(bAsValue instanceof ArrayBuffer); + assert.strictEqual(b, bAsValue); } catch (e) { console.log(data); throw e; @@ -100,4 +105,35 @@ function test (binding) { assert.throws(() => { binding.typedarray.createInvalidTypedArray(); }, /Invalid (pointer passed as )?argument/); + + if (binding.hasSharedArrayBuffer && runSharedArrayBufferTests) { + const length = 4; + const sab = new SharedArrayBuffer(length); + /** @type {Int8Array} */ + let t; + + try { + t = binding.typedarray.createInt8TypedArrayFromSharedArrayBuffer(sab); + } catch (ex) { + if (ex.message === 'Invalid argument') { + console.warn(`The current version of Node.js (${process.version}) does not support creating TypedArrays on SharedArrayBuffers; skipping tests.`); + runSharedArrayBufferTests = false; + return; + } + + throw ex; + } + + assert.ok(t instanceof Int8Array); + assert.strictEqual(binding.typedarray.getTypedArrayType(t), 'int8'); + assert.strictEqual(binding.typedarray.getTypedArrayLength(t), length); + for (let i = 0; i < length; i++) { + const value = 2 ** (i + 1); + t[i] = value; + assert.strictEqual(binding.typedarray.getTypedArrayElement(t, i), value); + } + const bAsValue = binding.typedarray.getTypedArrayBufferValue(t); + assert.ok(bAsValue instanceof SharedArrayBuffer); + assert.strictEqual(bAsValue, sab); + } } diff --git a/test/value_type_cast.cc b/test/value_type_cast.cc new file mode 100644 index 000000000..dfc03b38b --- /dev/null +++ b/test/value_type_cast.cc @@ -0,0 +1,70 @@ +#include "common/test_helper.h" +#include "napi.h" + +using namespace Napi; + +#define TYPE_CAST_TYPES(V) \ + V(Boolean) \ + V(Number) \ + V(BigInt) \ + V(Date) \ + V(String) \ + V(Symbol) \ + V(Object) \ + V(Array) \ + V(ArrayBuffer) \ + V(TypedArray) \ + V(DataView) \ + V(Function) \ + V(Promise) + +// The following types are tested individually. +// External +// TypedArrayOf +// Buffer + +namespace { +#define V(Type) \ + void TypeCast##Type(const CallbackInfo& info) { USE(info[0].As()); } +TYPE_CAST_TYPES(V) + +#ifdef NODE_API_EXPERIMENTAL_HAS_SHAREDARRAYBUFFER +V(SharedArrayBuffer) +#endif + +#undef V + +void TypeCastBuffer(const CallbackInfo& info) { + USE(info[0].As>()); +} + +void TypeCastExternal(const CallbackInfo& info) { + USE(info[0].As>()); +} + +void TypeCastTypeArrayOfUint8(const CallbackInfo& info) { + USE(info[0].As>()); +} +} // namespace + +Object InitValueTypeCast(Env env, Object exports) { + exports["external"] = External::New(env, nullptr); + +#define V(Type) exports["typeCast" #Type] = Function::New(env, TypeCast##Type); + TYPE_CAST_TYPES(V) + +#ifdef NODE_API_EXPERIMENTAL_HAS_SHAREDARRAYBUFFER + V(SharedArrayBuffer) +#endif + +#undef V + + exports["typeCastBuffer"] = Function::New(env, TypeCastBuffer); + exports["typeCastExternal"] = Function::New(env, TypeCastExternal); + exports["typeCastTypeArrayOfUint8"] = + Function::New(env, TypeCastTypeArrayOfUint8); + + return exports; +} + +NODE_API_MODULE(addon, InitValueTypeCast) diff --git a/test/value_type_cast.js b/test/value_type_cast.js new file mode 100644 index 000000000..274dd278b --- /dev/null +++ b/test/value_type_cast.js @@ -0,0 +1,113 @@ +'use strict'; + +const assert = require('assert'); +const napiChild = require('./napi_child'); + +module.exports = require('./common').runTestWithBuildType(test); + +function test (buildType) { + const binding = require(`./build/${buildType}/binding_type_check.node`); + const testTable = { + typeCastBoolean: { + positiveValues: [true, false], + negativeValues: [{}, [], 1, 1n, 'true', null, undefined] + }, + typeCastNumber: { + positiveValues: [1, NaN], + negativeValues: [{}, [], true, 1n, '1', null, undefined] + }, + typeCastBigInt: { + positiveValues: [1n], + negativeValues: [{}, [], true, 1, '1', null, undefined] + }, + typeCastDate: { + positiveValues: [new Date()], + negativeValues: [{}, [], true, 1, 1n, '1', null, undefined] + }, + typeCastString: { + positiveValues: ['', '1'], + negativeValues: [{}, [], true, 1, 1n, null, undefined] + }, + typeCastSymbol: { + positiveValues: [Symbol('1')], + negativeValues: [{}, [], true, 1, 1n, '1', null, undefined] + }, + typeCastObject: { + positiveValues: [{}, new Date(), []], + negativeValues: [true, 1, 1n, '1', null, undefined] + }, + typeCastArray: { + positiveValues: [[1]], + negativeValues: [{}, true, 1, 1n, '1', null, undefined] + }, + typeCastArrayBuffer: { + positiveValues: [new ArrayBuffer(0)], + negativeValues: [new Uint8Array(1), new SharedArrayBuffer(0), {}, [], null, undefined] + }, + typeCastTypedArray: { + positiveValues: [new Uint8Array(0)], + negativeValues: [new ArrayBuffer(1), {}, [], null, undefined] + }, + typeCastDataView: { + positiveValues: [new DataView(new ArrayBuffer(0))], + negativeValues: [new ArrayBuffer(1), null, undefined] + }, + typeCastFunction: { + positiveValues: [() => {}], + negativeValues: [{}, null, undefined] + }, + typeCastPromise: { + positiveValues: [Promise.resolve()], + // napi_is_promise distinguishes Promise and thenable. + negativeValues: [{ then: () => {} }, null, undefined] + }, + typeCastBuffer: { + positiveValues: [Buffer.from('')], + // napi_is_buffer doesn't distinguish between Buffer and TypedArrays. + negativeValues: [new ArrayBuffer(1), null, undefined] + }, + typeCastExternal: { + positiveValues: [binding.external], + negativeValues: [{}, null, undefined] + }, + typeCastTypeArrayOfUint8: { + // TypedArrayOf::CheckCast doesn't distinguish between Uint8ClampedArray and Uint8Array. + positiveValues: [new Uint8Array(0), new Uint8ClampedArray(0)], + negativeValues: [new Int8Array(1), null, undefined] + } + }; + + if ('typeCastSharedArrayBuffer' in binding) { + testTable.typeCastSharedArrayBuffer = { + positiveValues: [new SharedArrayBuffer(0)], + negativeValues: [new Uint8Array(1), new ArrayBuffer(0), {}, [], null, undefined] + }; + } + + if (process.argv[2] === 'child') { + child(binding, testTable, process.argv[3], process.argv[4], parseInt(process.argv[5])); + return; + } + + for (const [methodName, { positiveValues, negativeValues }] of Object.entries(testTable)) { + for (const idx of positiveValues.keys()) { + const { status } = napiChild.spawnSync(process.execPath, [__filename, 'child', methodName, 'positiveValues', idx]); + assert.strictEqual(status, 0, `${methodName} positive value ${idx} test failed`); + } + for (const idx of negativeValues.keys()) { + const { status, signal, stderr } = napiChild.spawnSync(process.execPath, [__filename, 'child', methodName, 'negativeValues', idx], { + encoding: 'utf8' + }); + if (process.platform === 'win32') { + assert.strictEqual(status, 128 + 6 /* SIGABRT */, `${methodName} negative value ${idx} test failed`); + } else { + assert.strictEqual(signal, 'SIGABRT', `${methodName} negative value ${idx} test failed`); + } + assert.ok(stderr.match(/FATAL ERROR: .*::CheckCast.*/)); + } + } +} + +async function child (binding, testTable, methodName, type, idx) { + binding[methodName](testTable[methodName][type][idx]); +} diff --git a/tools/README.md b/tools/README.md index 6b80e94f5..7fab9ab61 100644 --- a/tools/README.md +++ b/tools/README.md @@ -4,6 +4,11 @@ The clang-format checking tools is designed to check changed lines of code compared to given git-refs. +The tool requires Python 3 to run `git-clang-format`. It first tries the +executable specified by the `PYTHON` environment variable, when set. On +Windows it then tries the Python launcher (`py -3`), followed by `python3` and +`python`. On other platforms it tries `python3` and then `python`. + ## Migration Script 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. diff --git a/tools/clang-format.js b/tools/clang-format.js index e4bb4f52e..60cbbc514 100644 --- a/tools/clang-format.js +++ b/tools/clang-format.js @@ -1,10 +1,52 @@ #!/usr/bin/env node -const spawn = require('child_process').spawnSync; +const spawnSync = require('child_process').spawnSync; const path = require('path'); const filesToCheck = ['*.h', '*.cc']; const FORMAT_START = process.env.FORMAT_START || 'main'; +const pythonVersionCheck = [ + '-c', + 'import sys; raise SystemExit(sys.version_info[0] != 3)' +]; + +function findPython () { + const candidates = []; + + if (process.env.PYTHON) { + candidates.push({ + command: process.env.PYTHON, + args: [], + name: process.env.PYTHON + }); + } + + if (process.platform === 'win32') { + candidates.push({ command: 'py', args: ['-3'], name: 'py -3' }); + } + + candidates.push( + { command: 'python3', args: [], name: 'python3' }, + { command: 'python', args: [], name: 'python' } + ); + + for (const candidate of candidates) { + const result = spawnSync( + candidate.command, + [...candidate.args, ...pythonVersionCheck], + { stdio: 'ignore' } + ); + if (!result.error && result.status === 0) { + return candidate; + } + } + + throw new Error([ + 'Could not find a usable Python 3 executable.', + `Tried: ${candidates.map(({ name }) => name).join(', ')}.`, + 'Set the PYTHON environment variable to the path of a Python 3 executable.' + ].join('\n')); +} function main (args) { let fix = false; @@ -31,17 +73,46 @@ function main (args) { } const gitClangFormatPath = path.join(clangFormatPath, 'bin/git-clang-format'); - const result = spawn( - 'python', - [gitClangFormatPath, ...options, '--', ...filesToCheck], + let python; + try { + python = findPython(); + } catch (error) { + console.error(error.message); + return 2; + } + + const result = spawnSync( + python.command, + [ + ...python.args, + gitClangFormatPath, + ...options, + '--', + ...filesToCheck + ], { encoding: 'utf-8' } ); - if (result.stderr) { - console.error('Error running git-clang-format:', result.stderr); + if (result.error) { + console.error('Error running git-clang-format:', result.error.message); return 2; } + if (result.status !== 0 && result.status !== 1) { + const message = ( + result.stderr || + result.stdout || + result.signal || + `exit code ${result.status}` + ).trim(); + console.error(`Error running git-clang-format: ${message}`); + return 2; + } + + if (result.stderr) { + process.stderr.write(result.stderr); + } + const clangFormatOutput = result.stdout.trim(); // Bail fast if in fix mode. if (fix) { diff --git a/tools/conversion.js b/tools/conversion.js index f89245ac6..e92a03a26 100755 --- a/tools/conversion.js +++ b/tools/conversion.js @@ -12,7 +12,7 @@ if (!dir) { process.exit(1); } -const NodeApiVersion = require('../package.json').version; +const NodeApiVersion = require('../').version; const disable = args[1]; let ConfigFileOperations; diff --git a/tools/eslint-format.js b/tools/eslint-format.js deleted file mode 100644 index 1dda44495..000000000 --- a/tools/eslint-format.js +++ /dev/null @@ -1,79 +0,0 @@ -#!/usr/bin/env node - -const spawn = require('child_process').spawnSync; - -const filesToCheck = '*.js'; -const FORMAT_START = process.env.FORMAT_START || 'main'; -const IS_WIN = process.platform === 'win32'; -const ESLINT_PATH = IS_WIN ? 'node_modules\\.bin\\eslint.cmd' : 'node_modules/.bin/eslint'; - -function main (args) { - let fix = false; - while (args.length > 0) { - switch (args[0]) { - case '-f': - case '--fix': - fix = true; - break; - default: - } - args.shift(); - } - - // Check js files that change on unstaged file - const fileUnStaged = spawn( - 'git', - ['diff', '--name-only', FORMAT_START, filesToCheck], - { - encoding: 'utf-8' - } - ); - - // Check js files that change on staged file - const fileStaged = spawn( - 'git', - ['diff', '--name-only', '--cached', FORMAT_START, filesToCheck], - { - encoding: 'utf-8' - } - ); - - const options = [ - ...fileStaged.stdout.split('\n').filter((f) => f !== ''), - ...fileUnStaged.stdout.split('\n').filter((f) => f !== '') - ]; - - if (fix) { - options.push('--fix'); - } - - const result = spawn(ESLINT_PATH, [...options], { - encoding: 'utf-8' - }); - - if (result.error && result.error.errno === 'ENOENT') { - console.error('Eslint not found! Eslint is supposed to be found at ', ESLINT_PATH); - return 2; - } - - if (result.status === 1) { - console.error('Eslint error:', result.stdout); - const fixCmd = 'npm run lint:fix'; - console.error(`ERROR: please run "${fixCmd}" to format changes in your commit - Note that when running the command locally, please keep your local - main branch and working branch up to date with nodejs/node-addon-api - to exclude un-related complains. - Or you can run "env FORMAT_START=upstream/main ${fixCmd}". - Also fix JS files by yourself if necessary.`); - return 1; - } - - if (result.stderr) { - console.error('Error running eslint:', result.stderr); - return 2; - } -} - -if (require.main === module) { - process.exitCode = main(process.argv.slice(2)); -} diff --git a/unit-test/README.md b/unit-test/README.md index e10b1c448..2dfd5abfb 100644 --- a/unit-test/README.md +++ b/unit-test/README.md @@ -1,11 +1,17 @@ # Enable running tests with specific filter conditions: +The `--filter` option limits which test modules are executed by `node test`. +The default `pretest` step is still `node-gyp rebuild -C test`, so +`npm test --filter=...` still performs a full rebuild of the test addon +targets before the filtered tests run. + ### Example: - - compile and run only tests on objectwrap.cc and objectwrap.js + - perform the default test rebuild, then run only the `objectwrap` + test module ``` - npm run test --filter=objectwrap + npm test --filter=objectwrap ``` @@ -13,16 +19,20 @@ ### Example: - - compile and run all tests files ending with reference -> function_reference.cc object_reference.cc reference.cc + - perform the default test rebuild, then run all test modules ending + with `reference` + (`function_reference`, `object_reference`, and `reference`) ``` - npm run test --filter=*reference + npm test --filter=*reference ``` # Multiple filter conditions are also allowed ### Example: - - compile and run all tests under folders threadsafe_function and typed_threadsafe_function and also the objectwrap.cc file + - perform the default test rebuild, then run all tests under + `threadsafe_function` and `typed_threadsafe_function`, and also the + `objectwrap` test module ``` - npm run test --filter='*function objectwrap' + npm test --filter='*function objectwrap' ```