Skip to content

Comments

fix(napi): Add TypeName implementation for ArrayBuffer#3087

Merged
Brooooooklyn merged 1 commit intonapi-rs:mainfrom
richerfu:main
Jan 8, 2026
Merged

fix(napi): Add TypeName implementation for ArrayBuffer#3087
Brooooooklyn merged 1 commit intonapi-rs:mainfrom
richerfu:main

Conversation

@richerfu
Copy link
Contributor

@richerfu richerfu commented Jan 7, 2026

Add TypeName implementation for ArrayBuffer that allow us to use it in ScopeTask

Summary by CodeRabbit

  • New Features

    • Added asyncTaskArraybuffer(): asynchronously converts numeric arrays to ArrayBuffer and returns Promise.
    • Exposed across module exports with TypeScript declarations.
  • Tests

    • Added comprehensive tests covering empty, small, and large binary round-trips.
  • Examples

    • Updated example bindings to include and demonstrate the new asyncTaskArraybuffer export.

✏️ Tip: You can customize this high-level summary in your review settings.

@coderabbitai
Copy link

coderabbitai bot commented Jan 7, 2026

📝 Walkthrough

Walkthrough

Adds a TypeName impl for ArrayBuffer<'_>, a new async task that converts Vec<u8> to ArrayBuffer, exposes asyncTaskArraybuffer across JS/TS bindings, and adds tests and snapshots validating the new API.

Changes

Cohort / File(s) Summary
Core Library Type Metadata
crates/napi/src/bindgen_runtime/js_values/arraybuffer.rs
Implements TypeName for ArrayBuffer<'_>: type_name() -> "ArrayBuffer" and value_type() -> ValueType::Object.
Async Task Implementation
examples/napi/src/task.rs
Adds AsyncTaskArrayBuffer with ScopedTask impl converting Vec<u8> into an ArrayBuffer and constructor async_task_arraybuffer.
Module Exports
examples/napi/index.cjs, examples/napi/index.d.cts, examples/napi/example.wasi.cjs, examples/napi/example.wasi-browser.js
Wires asyncTaskArraybuffer into CommonJS/wasm-wasi/browser bindings and TypeScript declaration.
Tests & Snapshots
examples/napi/__tests__/values.spec.ts, examples/napi/__tests__/__snapshots__/values.spec.ts.md
Adds tests verifying round-trip of byte arrays to ArrayBuffer (small, empty, large) and updates snapshot declarations.

Sequence Diagram(s)

sequenceDiagram
  participant JS as JavaScript caller
  participant CJS as CommonJS/Binding shim
  participant Native as Native binding (napi module)
  participant Task as AsyncTaskArrayBuffer
  participant Env as N-API Env / JS runtime

  JS->>CJS: call asyncTaskArraybuffer(Uint8Array)
  CJS->>Native: forward call with bytes
  Native->>Task: spawn AsyncTaskArrayBuffer with Vec<u8>
  Task->>Task: compute() (simulate work / sleep)
  Task->>Native: resolve with Vec<u8>
  Native->>Env: create ArrayBuffer from Vec<u8>
  Env-->>Native: ArrayBuffer reference
  Native-->>CJS: Promise resolves with ArrayBuffer
  CJS-->>JS: Promise resolves
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

Poem

🐇 I munched on bytes all night,
I nibbled Vecs until they’re tight,
I hop them to Async land,
Resolve with buffer in hand,
Hooray — promises take flight! 🎉

🚥 Pre-merge checks | ✅ 1 | ❌ 2
❌ Failed checks (2 warnings)
Check name Status Explanation Resolution
Title check ⚠️ Warning The title claims to 'Add TypeName implementation' but the changes include much more: a new AsyncTaskArrayBuffer struct, test coverage, and multiple export bindings across example files. Revise the title to reflect the broader scope, such as 'feat(napi): Add AsyncTaskArrayBuffer and TypeName implementation' or 'feat(examples): Add asyncTaskArraybuffer async task example'.
Docstring Coverage ⚠️ Warning Docstring coverage is 28.57% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (1 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing touches
  • 📝 Generate docstrings

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Nitpick comments (1)
examples/napi/src/task.rs (1)

205-209: Consider avoiding the clone for better performance.

The clone() on line 208 copies the entire data vector. Since self.data is owned and won't be used after compute(), you could use std::mem::take(&mut self.data) to move the data without cloning, which would be more efficient for large arrays.

♻️ Proposed optimization
  fn compute(&mut self) -> Result<Self::Output> {
    // Simulate some async computation
    sleep(std::time::Duration::from_millis(10));
-   Ok(self.data.clone())
+   Ok(std::mem::take(&mut self.data))
  }
📜 Review details

Configuration used: defaults

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 87f3831 and 4270f9e.

⛔ Files ignored due to path filters (1)
  • examples/napi/__tests__/__snapshots__/values.spec.ts.snap is excluded by !**/*.snap
📒 Files selected for processing (8)
  • crates/napi/src/bindgen_runtime/js_values/arraybuffer.rs
  • examples/napi/__tests__/__snapshots__/values.spec.ts.md
  • examples/napi/__tests__/values.spec.ts
  • examples/napi/example.wasi-browser.js
  • examples/napi/example.wasi.cjs
  • examples/napi/index.cjs
  • examples/napi/index.d.cts
  • examples/napi/src/task.rs
🧰 Additional context used
🧠 Learnings (4)
📓 Common learnings
Learnt from: CR
Repo: napi-rs/napi-rs PR: 0
File: CLAUDE.md:0-0
Timestamp: 2025-11-25T09:31:23.877Z
Learning: Applies to /crates/**/*.rs : Use `#[napi]` attribute on impl blocks to define classes exported to JavaScript/TypeScript
Learnt from: CR
Repo: napi-rs/napi-rs PR: 0
File: CLAUDE.md:0-0
Timestamp: 2025-11-25T09:31:23.877Z
Learning: Applies to /crates/**/*.rs : Use `#[napi(object)]` attribute for plain objects that should be mapped to TypeScript interfaces
Learnt from: CR
Repo: napi-rs/napi-rs PR: 0
File: CLAUDE.md:0-0
Timestamp: 2025-11-25T09:31:23.877Z
Learning: Applies to /crates/**/*.rs : Use `#[napi(js_name = "...")]` attribute to rename Rust items in JavaScript/TypeScript
📚 Learning: 2025-11-25T09:31:23.877Z
Learnt from: CR
Repo: napi-rs/napi-rs PR: 0
File: CLAUDE.md:0-0
Timestamp: 2025-11-25T09:31:23.877Z
Learning: Applies to /crates/**/*.rs : Use `#[napi]` attribute on impl blocks to define classes exported to JavaScript/TypeScript

Applied to files:

  • examples/napi/example.wasi-browser.js
  • crates/napi/src/bindgen_runtime/js_values/arraybuffer.rs
  • examples/napi/example.wasi.cjs
📚 Learning: 2025-11-25T09:31:23.877Z
Learnt from: CR
Repo: napi-rs/napi-rs PR: 0
File: CLAUDE.md:0-0
Timestamp: 2025-11-25T09:31:23.877Z
Learning: Applies to /crates/**/*.rs : Use `#[napi(js_name = "...")]` attribute to rename Rust items in JavaScript/TypeScript

Applied to files:

  • crates/napi/src/bindgen_runtime/js_values/arraybuffer.rs
📚 Learning: 2025-11-25T09:31:23.877Z
Learnt from: CR
Repo: napi-rs/napi-rs PR: 0
File: CLAUDE.md:0-0
Timestamp: 2025-11-25T09:31:23.877Z
Learning: Applies to /crates/**/*.rs : Use `#[napi(object)]` attribute for plain objects that should be mapped to TypeScript interfaces

Applied to files:

  • crates/napi/src/bindgen_runtime/js_values/arraybuffer.rs
🧬 Code graph analysis (3)
examples/napi/src/task.rs (2)
crates/napi/src/task.rs (6)
  • compute (11-11)
  • compute (33-35)
  • compute (58-58)
  • resolve (14-14)
  • resolve (37-39)
  • resolve (61-61)
crates/napi/src/bindgen_runtime/js_values/arraybuffer.rs (4)
  • env (262-262)
  • env (1792-1792)
  • from_data (157-214)
  • from_data (1671-1742)
examples/napi/index.d.cts (1)
examples/napi/example.wasi-browser.js (2)
  • asyncTaskArraybuffer (146-146)
  • asyncTaskArraybuffer (146-146)
examples/napi/__tests__/values.spec.ts (1)
examples/napi/example.wasi-browser.js (2)
  • asyncTaskArraybuffer (146-146)
  • asyncTaskArraybuffer (146-146)
🔇 Additional comments (9)
examples/napi/index.d.cts (1)

440-440: LGTM! TypeScript declaration matches the Rust implementation.

The function signature correctly maps Vec<u8> to Array<number> and AsyncTask<AsyncTaskArrayBuffer> to Promise<ArrayBuffer>.

crates/napi/src/bindgen_runtime/js_values/arraybuffer.rs (1)

114-122: LGTM! TypeName implementation is correct and consistent.

The implementation correctly returns "ArrayBuffer" as the type name and ValueType::Object as the value type, following the same pattern as other types in the codebase (e.g., TypedArray at lines 366-374).

examples/napi/src/task.rs (1)

216-219: LGTM! Constructor follows established patterns.

The implementation is consistent with other async task constructors in this file and correctly demonstrates using ArrayBuffer with ScopeTask.

examples/napi/example.wasi-browser.js (1)

146-146: LGTM! Export binding is consistent.

The export follows the established pattern used throughout this file.

examples/napi/__tests__/__snapshots__/values.spec.ts.md (1)

480-480: LGTM! Snapshot correctly reflects the new API.

The snapshot update is automatically generated and matches the TypeScript declaration.

examples/napi/index.cjs (1)

659-659: LGTM!

The export wiring follows the established pattern in this auto-generated file.

examples/napi/example.wasi.cjs (1)

191-191: LGTM!

The WASI binding export is consistent with the corresponding export in index.cjs and follows the established pattern.

examples/napi/__tests__/values.spec.ts (2)

97-97: LGTM!

Import is correctly placed within the async task function imports.


1535-1558: Well-structured test coverage.

The test comprehensively covers:

  • Basic functionality with a simple 5-byte array
  • Empty array edge case (important for boundary conditions)
  • Larger data handling (1000 bytes)

The assertions properly verify both the ArrayBuffer type and its contents via Uint8Array view.

@Brooooooklyn Brooooooklyn changed the title feat(napi): Add TypeName implementation for ArrayBuffer fix(napi): Add TypeName implementation for ArrayBuffer Jan 8, 2026
Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Nitpick comments (1)
examples/napi/src/task.rs (1)

196-214: Consider avoiding the clone in compute().

The compute() method currently clones self.data (Line 208), which allocates a new Vec<u8>. Since you have mutable access (&mut self), you could use std::mem::take(&mut self.data) to move the data without cloning:

fn compute(&mut self) -> Result<Self::Output> {
  // Simulate some async computation
  sleep(std::time::Duration::from_millis(10));
  Ok(std::mem::take(&mut self.data))
}

This avoids an unnecessary allocation and is more efficient, especially for large buffers.

♻️ Proposed refactor to eliminate the clone
  fn compute(&mut self) -> Result<Self::Output> {
    // Simulate some async computation
    sleep(std::time::Duration::from_millis(10));
-   Ok(self.data.clone())
+   Ok(std::mem::take(&mut self.data))
  }
📜 Review details

Configuration used: defaults

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 4270f9e and e84b1f1.

⛔ Files ignored due to path filters (1)
  • examples/napi/__tests__/__snapshots__/values.spec.ts.snap is excluded by !**/*.snap
📒 Files selected for processing (8)
  • crates/napi/src/bindgen_runtime/js_values/arraybuffer.rs
  • examples/napi/__tests__/__snapshots__/values.spec.ts.md
  • examples/napi/__tests__/values.spec.ts
  • examples/napi/example.wasi-browser.js
  • examples/napi/example.wasi.cjs
  • examples/napi/index.cjs
  • examples/napi/index.d.cts
  • examples/napi/src/task.rs
🚧 Files skipped from review as they are similar to previous changes (3)
  • crates/napi/src/bindgen_runtime/js_values/arraybuffer.rs
  • examples/napi/index.d.cts
  • examples/napi/tests/values.spec.ts
🧰 Additional context used
🧠 Learnings (2)
📓 Common learnings
Learnt from: CR
Repo: napi-rs/napi-rs PR: 0
File: CLAUDE.md:0-0
Timestamp: 2025-11-25T09:31:23.877Z
Learning: Applies to /crates/**/*.rs : Use `#[napi]` attribute on impl blocks to define classes exported to JavaScript/TypeScript
Learnt from: CR
Repo: napi-rs/napi-rs PR: 0
File: CLAUDE.md:0-0
Timestamp: 2025-11-25T09:31:23.877Z
Learning: Applies to /crates/**/*.rs : Use `#[napi(object)]` attribute for plain objects that should be mapped to TypeScript interfaces
Learnt from: CR
Repo: napi-rs/napi-rs PR: 0
File: CLAUDE.md:0-0
Timestamp: 2025-11-25T09:31:23.877Z
Learning: Applies to /crates/**/*.rs : Use `#[napi(js_name = "...")]` attribute to rename Rust items in JavaScript/TypeScript
📚 Learning: 2025-11-25T09:31:23.877Z
Learnt from: CR
Repo: napi-rs/napi-rs PR: 0
File: CLAUDE.md:0-0
Timestamp: 2025-11-25T09:31:23.877Z
Learning: Applies to /crates/**/*.rs : Use `#[napi]` attribute on impl blocks to define classes exported to JavaScript/TypeScript

Applied to files:

  • examples/napi/example.wasi.cjs
  • examples/napi/example.wasi-browser.js
🧬 Code graph analysis (1)
examples/napi/src/task.rs (2)
crates/napi/src/task.rs (6)
  • compute (11-11)
  • compute (33-35)
  • compute (58-58)
  • resolve (14-14)
  • resolve (37-39)
  • resolve (61-61)
crates/napi/src/bindgen_runtime/js_values/arraybuffer.rs (4)
  • env (262-262)
  • env (1792-1792)
  • from_data (157-214)
  • from_data (1671-1742)
🔇 Additional comments (1)
examples/napi/src/task.rs (1)

216-219: LGTM!

The wrapper function correctly follows the established pattern for async task functions in this file, properly constructing the AsyncTaskArrayBuffer and wrapping it in an AsyncTask.

@richerfu richerfu requested a review from Brooooooklyn January 8, 2026 08:04
@Brooooooklyn Brooooooklyn merged commit aa4ffb2 into napi-rs:main Jan 8, 2026
74 checks passed
@github-actions github-actions bot mentioned this pull request Jan 8, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants