napi 0.25.0
napi: ^0.25.0 copied to clipboard
Dart bindings to Node-API for implementing native Node.js addons.
napi #
Node-API bindings for Dart.
Native compilation #
Annotate functions in lib/addon.dart:
import 'package:napi/napi.dart';
@NAPI()
int add(int a, int b) => a + b;
Build it with your own Dart script:
import 'dart:io';
import 'package:napi/compiler.dart';
final compiler = Compiler([
NativeTarget(
entry: File('lib/addon.dart'),
output: File('dist/addon.node'),
declarations: File('dist/addon.d.cts'),
node: '^24.0.0',
),
]);
Future<void> main(List<String> args) => compiler.run(args);
Load the result directly in Node.js:
const { add } = require('./dist/addon.node');
console.log(add(20, 22)); // 42
The output is a standalone .node file for the current platform. The package
includes compilers for macOS arm64, Linux arm64 (glibc) and Windows x64; building an
addon does not require SDK sources or a C/C++ toolchain. Business code is compiled
with the bundled Dart 3.13.5 SDK, independently of the SDK running the script.
Include the corresponding SDK NOTICES file when redistributing the addon.
Omit node to infer the minimum requirements from referenced APIs. A supplied
range uses Dart version constraint syntax, with || for alternatives, and must
be compatible with those APIs. Compilation failures preserve an existing output.
Omit declarations to generate only the binary. Declaration output requires
annotated exports. Use .d.cts for CommonJS declarations, or .d.mts when
providing an ESM wrapper. A .d.ts output uses CommonJS declarations and must be
interpreted as CommonJS by the consuming package. PackageBuild generates both
module formats and their declarations.
Functions support positional parameters, named options,
nullable values and Dart defaults. A named parameter group becomes the final JS
options argument. Explicit undefined is a value; it does not select a Dart
default. For optional options fields, enable TypeScript's
exactOptionalPropertyTypes to reject invalid explicit undefined statically.
Use @NAPI(name: 'anotherName') to change an export's name. Exports are selected
from the entry library and its re-exports. An explicitly annotated private
function can be exported. Unsupported declarations and conflicting names produce
a build error.
Constants #
Annotate a top-level const to export its value:
@NAPI()
const defaultPort = 8080;
@NAPI()
const defaults = (host: 'localhost', port: defaultPort);
const { defaultPort, defaults } = require('./dist/addon.node');
defaults.port === defaultPort; // true
The exported property is read-only. Its value uses the same conversions as function results: containers become mutable JS copies, and exported class instances retain their identity. Function and constructor tear-offs are callable and preserve their Dart defaults. Package builds also provide ESM named exports and TypeScript declarations for constants.
Top-level properties #
Annotate a variable, final field or accessor to expose a live property:
@NAPI()
int count = 0;
@NAPI()
final startedAt = DateTime.now().toIso8601String();
@NAPI()
int get doubled => count * 2;
@NAPI()
set doubled(int value) => count = value ~/ 2;
const addon = require('./dist/addon.node');
addon.count = 3;
console.log(addon.doubled); // 6
addon.doubled = 10;
console.log(addon.count); // 5
Reads and writes access the Dart declaration each time. Dart field initializers
remain lazy, getters run on each read, and final fields are read-only. Annotate
both accessors to export both directions; an unmarked getter or setter stays in
Dart. Values use the same conversions as function arguments and results.
With PackageBuild, use the ESM default import for live properties:
import addon from 'my-addon';
addon.count += 1;
Functions, classes and constants also have ESM named exports. Live properties are available on the default package object; destructuring them reads their current value once.
Collections and binary data #
Dart lists map to JS arrays. String-keyed maps map to JS objects:
@NAPI()
List<int> doubleValues(List<int> values) => [for (final value in values) value * 2];
@NAPI()
Map<String, int> scores(Map<String, int> values) => values;
Containers are copied in both directions, including nested lists and maps.
Exported class instances inside a container retain their identity. Map input
reads own enumerable string properties once and ignores inherited and symbol
properties. Missing array elements and explicit undefined still undergo the
declared element type's validation. Map keys must be non-nullable String.
Import dart:typed_data to exchange binary data. Int8List, Uint8List,
Uint8ClampedList, Int16List, Uint16List, Int32List, Uint32List,
Float32List and Float64List map to their corresponding JS TypedArrays.
Int64List and Uint64List use BigInt64Array and BigUint64Array and preserve
all 64 bits. The array kind must match; a Node Buffer is accepted
as Uint8List.
Binary conversion copies only the view's range. Later writes on either side do
not change the copy. A declaration of List<int> always produces a JS Array,
including when its Dart implementation returns a Uint8List.
ByteBuffer maps to JS ArrayBuffer, and ByteData maps to DataView:
@NAPI()
ByteBuffer echoBuffer(ByteBuffer value) => value;
@NAPI()
ByteData echoView(ByteData value) => value;
const source = new Uint8Array([91, 1, 2, 3, 92]);
const result = addon.echoView(new DataView(source.buffer, 1, 3));
console.log([...new Uint8Array(result.buffer)]); // [1, 2, 3]
A returned DataView starts at offset zero in a new buffer containing only its
visible bytes. DataView and TypedArray inputs backed by SharedArrayBuffer are
also copied. ByteBuffer input requires an ordinary ArrayBuffer. Detached
binary inputs throw TypeError; binary input conversion requires Node-API 7.
SIMD values and lists use flat TypedArrays:
| Dart value | Dart list | JavaScript | Lanes per vector |
|---|---|---|---|
Float32x4 |
Float32x4List |
Float32Array |
4 |
Int32x4 |
Int32x4List |
Int32Array |
4 |
Float64x2 |
Float64x2List |
Float64Array |
2 |
@NAPI()
Float32x4 addVectors(Float32x4 a, Float32x4 b) => a + b;
const sum = addon.addVectors(
new Float32Array([1, 2, 3, 4]),
new Float32Array([10, 20, 30, 40]),
); // Float32Array [11, 22, 33, 44]
Vector inputs require exactly one vector's lanes. SIMD list inputs require a
multiple of that lane count, including zero. Conversion copies raw bytes,
preserving NaN payloads and signed zero. Returned lists contain only their
visible range. Ordinary List<Float32x4> uses a JS Array of Float32Arrays.
Sets #
Set<T> maps to a JavaScript Set, with each element converted normally:
@NAPI()
Set<int> echoSet(Set<int> values) => values;
const result = addon.echoSet(new Set([3, 1, 2]));
console.log([...result]); // [3, 1, 2]
Sets are independent copies, populated in source iteration order. Equality
follows the target collection's rules: JS normalizes -0 to 0 and merges NaNs;
Dart uses the converted elements' == and hashCode, so equal dates or records
can merge. Opaque JS values retain their JS identity when returned, while Dart
compares their reference wrappers.
Dates #
Dart DateTime values map to JavaScript Date:
@NAPI()
DateTime addDay(DateTime value) => value.add(const Duration(days: 1));
const result = addon.addDay(new Date('2026-01-01T00:00:00Z'));
console.log(result.toISOString()); // 2026-01-02T00:00:00.000Z
Dates are copied. Inputs become UTC DateTime values; JS Date does not preserve
a Dart local/UTC flag or a time zone. Outputs use millisecondsSinceEpoch,
discarding sub-millisecond precision. This follows Dart's signed timestamp
semantics: -1 microsecond becomes -1 millisecond. Invalid Date inputs throw a
RangeError; other JS types are rejected.
Records #
Use Dart records to exchange structured values:
@NAPI()
({int x, int y}) offset(({int x, int y}) point, int dx, int dy) =>
(x: point.x + dx, y: point.y + dy);
offset({ x: 1, y: 2 }, 3, 4); // { x: 4, y: 6 }
| Dart type | JavaScript shape |
|---|---|
(int, String) |
[1, 'text'] |
({int x, int y}) |
{ x: 1, y: 2 } |
(int, {String label}) |
{ $1: 1, label: 'text' } |
() |
[] |
Positional records require an array of the exact length. Named and mixed
records require their own fields; inherited properties do not fill missing
fields, and unrelated properties are ignored. Each field is read once and
checked against its Dart type. Nullable fields accept null, not undefined.
Records and their containers are copied; exported class instances inside them keep their identity. Record defaults use their actual Dart values, and fields can contain the other supported types, including callbacks, Futures and Streams.
Enums #
Annotate an enum to expose its cases as read-only numeric properties:
@NAPI()
enum Status { ready, done }
@NAPI()
Status toggle(Status value) =>
value == Status.ready ? Status.done : Status.ready;
Status.ready; // 0
toggle(Status.ready) === Status.done; // true
Values use Dart's index, so reordering cases changes their numeric values.
Parameters accept only valid indices; names, fractional numbers and out-of-range
indices are rejected. TypeScript exposes a read-only object and a union of its
values, including with isolatedModules enabled.
Use @NAPI(name: 'anotherName') on the enum or a case to rename it. Private
cases must be explicitly annotated. Enhanced enum fields and methods remain
available to Dart code; expose their behavior through annotated functions.
Classes #
Annotate a Dart class and the members you want to expose:
import 'package:napi/napi.dart';
@NAPI()
class Counter {
@NAPI()
Counter([this.value = 0]);
@NAPI()
int value;
@NAPI()
int increment([int step = 1]) => value += step;
@NAPI()
Counter same() => this;
}
Run the Counter example with
dart run example/build.dart, then:
const { Counter } = require('./build/counter.node');
const counter = new Counter(5);
counter.increment(); // 6
counter.value = 10;
counter.increment(2); // 12
counter.same() === counter; // true
Only annotated members are exported. This includes constructors, named constructors and static members; unannotated members stay in Dart. Without an annotated unnamed constructor, JS cannot construct the class, but functions can still return its instances.
Annotated named constructors become static factories, such as
Counter.named(options). An annotated field provides both accessors; a final
field is read-only. Annotate explicit getters and setters separately to expose
each direction. Private members can be exported by annotating them.
Class export names must also be valid TypeScript class names. Method calls preserve the actual Dart implementation's defaults, including when a function returns an unexported subclass.
Passing a bound instance back to Dart unwraps the original object. Returning that object again reuses its live JS instance. JavaScript collection releases the binding's Dart reference.
Export a subclass to preserve its relationship with an exported Dart superclass:
@NAPI()
class StepCounter extends Counter {
@NAPI()
StepCounter([super.value = 0]);
@override
int increment([int step = 2]) => super.increment(step);
}
const counter = new addon.StepCounter();
counter instanceof addon.Counter; // true
counter.increment(); // 2
counter.same() === counter; // true
An override continues to implement an inherited exported member even without a second annotation. Annotate new members to export them. Dart virtual dispatch and the actual implementation's defaults still apply. Returned objects use their most specific exported class, including when a function's return type is a superclass. Passing the same instance through either type reuses its JS wrapper.
The JS prototype chain follows Dart superclasses, including across unexported intermediate classes. Implementing an exported interface does not establish a JS superclass. Plain-object data classes cannot participate in this prototype chain. Static exports are inherited on the JS constructor. A same-named static export must have matching parameter or property types; factory results may return a subclass.
Data classes as plain objects #
Use @NAPI.object() to exchange a Dart data class as a plain JS object:
@NAPI.object()
class Point {
@NAPI()
const Point({required this.x, this.y = 0});
@NAPI()
final int x;
@NAPI()
final int y;
}
@NAPI()
Point move(Point point) => Point(x: point.x + 1, y: point.y);
move({ x: 1 }); // { x: 2, y: 0 }
The annotated constructor defines the input properties, types and defaults.
Required properties must be present on the input object itself. Omitted optional
properties use the Dart defaults; explicit undefined still undergoes type
validation. Each input property is read once, and unrelated properties are
ignored.
Annotated fields and getters define the output properties. They are read once
to create a new JS object with writable properties. Dart final constrains the
Dart instance; it does not freeze the JS copy. Nested values use their usual
conversions, including identity preservation for bound class instances and JS
references. Field and getter renames apply to output properties; input keys
keep their constructor parameter names.
Input and output shapes may differ: constructor parameters can have defaults or
different types from the output getters. The generated TypeScript describes
each direction separately. The class name is a TypeScript type, available
with import type; it does not create a JS constructor or export instance
methods.
Annotate one constructor, unnamed or named, to enable input conversion. A data class without an annotated constructor can still be returned from Dart. Multiple annotated constructors are ambiguous and produce a build error. Keep methods and static members unannotated, and expose their behavior through annotated functions when needed.
Data-object conversion supports up to 128 nested data objects. Deeper or cyclic
structures throw RangeError.
Data classes can be generic. Concrete type arguments determine the Dart constructor and each property's conversion:
@NAPI.object()
class Envelope<T> {
@NAPI()
Envelope({required this.value});
@NAPI()
final T value;
}
@NAPI()
Envelope<int> addOne(Envelope<int> envelope) =>
Envelope(value: envelope.value + 1);
addon.addOne({ value: 41 }); // { value: 42 }
Type arguments also apply to nested data classes, collections and callbacks. Input and output shapes remain separate, including when an argument is another data class with different constructor and getter types.
Generic callbacks keep those input and output shapes too:
@NAPI.object()
class Amount {
@NAPI()
Amount({required String value}) : value = int.parse(value);
@NAPI()
final int value;
}
@NAPI.object()
class Handler<T> {
@NAPI()
Handler({required this.run});
@NAPI()
final T Function(T) run;
}
@NAPI()
Handler<Amount> handler() => Handler(run: (amount) => amount);
import addon, { type Amount, type Handler } from 'my-addon';
const handler: Handler<Amount> = addon.handler();
const amount: Amount = handler.run({ value: '42' });
amount.value; // 42
Types whose input and output shapes differ carry a private TypeScript identity.
Obtain an Amount from a returned value; { value: 42 } alone cannot be assigned
to Amount. Constructor inputs remain ordinary objects. Symmetric types such as
Handler<number> still accept object literals. The identity adds no JavaScript
properties or symbols.
For function-valued generic arguments with asymmetric conversions, keep the
inferred generated type or derive it with TypeScript's ReturnType. A handwritten
arrow type does not retain the generated input/output association.
Recursive projections that cannot yet be resolved to finite input/output constraints produce a build error.
Generics #
Dart type parameters become TypeScript generics:
@NAPI()
T identity<T>(T value) => value;
@NAPI()
class Box<T> {
@NAPI()
Box(this.value);
@NAPI()
T value;
}
import { Box, identity } from 'my-addon';
const text = identity('hello'); // string
const box = new Box<number>(42);
box.value = 7;
TypeScript infers type arguments from values and checks explicit arguments.
These arguments are erased at runtime; Dart calls use the declaration's default
type arguments. Unconstrained parameters pass scalars directly and retain JS
objects, functions and symbols as owned references, preserving their JS
identity when returned. The same rules apply to elements of List<T>,
Map<String, T> and ordinary callback signatures.
JavaScript type arguments do not select data-class converters. A generic
identity preserves the supplied JS representation. Use a concrete Dart
declaration such as Envelope<Amount> when constructor inputs need conversion.
Bounds support scalars, Object, explicit JsReference types and exported
bound classes. For example, T identity<T extends Counter>(T value) => value
preserves the original instance and its subclass type in TypeScript. Generic
callbacks with a class bound receive the ordinary JS instance; Dart checks their
result against the actual type argument, including a narrower subclass.
When a bound refers to its own parameter, such as T extends Node<T>,
TypeScript type annotations need an explicit argument, such as Reader<Leaf>.
Calls can still infer their type arguments.
Bounds that copy values, such as List<int> or data classes, require a required,
non-null bound-instance parameter that supplies the actual Dart type:
@NAPI()
T replaceNumbers<T extends List<int>>(Box<T> box, T value) => box.value = value;
Passing a Dart-created Box<List<int>> converts arrays; a Box<Uint8List> uses
Uint8Array instead. The instance also determines the result type. Data-class
bounds keep their constructor input and output field shapes. A nullable or
optional instance alone cannot supply this guarantee, and generic callbacks
with copying bounds remain unsupported.
Dart can return concrete bound classes with scalar values, JS references, bound instances, enums, dates, binary types, collections, records, Futures and callbacks. Their members use those types for conversion and validation:
@NAPI()
Box<int> makeIntBox() => Box<int>(42);
@NAPI()
int readIntBox(Box<int> box) => box.value;
const box = makeIntBox(); // Box<number>, backed by Dart Box<int>
box.value = 7;
readIntBox(box); // 7
new Box<number>(42) still constructs Box<dynamic> in Dart. It cannot be
passed to readIntBox: TypeScript's number is erased and does not establish
the required Dart type. Returning the same Dart object through a wider class
type preserves its JS identity. Its members use the most specific exported
specialization that matches the object; incompatible matches produce an error.
Collection members use the same copies as ordinary collection parameters:
@NAPI()
Box<List<int>> numbers() => Box<List<int>>([1, 2]);
const box = numbers();
const values = box.value;
values.push(3); // box.value is still [1, 2]
box.value = values; // stores a Dart list containing [1, 2, 3]
Bound instances keep their JavaScript identity, including inside collections
and other generic classes. For example, a Box<Counter> can hold a Counter
or a subclass; reading its value returns the same JS instance. A plain object
with matching properties is not a Counter.
Generic functions and methods can use a bound instance to select their Dart type arguments. Their generated declarations require TypeScript 5.4 or newer:
@NAPI()
T writeBox<T>(Box<T> box, T value) => box.value = value;
writeBox(numbers(), [3, 4]); // T is List<int>; the array is copied into Dart.
writeBox(makeIntBox(), 7); // T is int; fractional values are rejected.
The same conversion applies to arguments, callbacks and return values. A
Box<Amount> selects Amount's constructor input and output fields. A
JS-created box selects dynamic and preserves opaque values. If several
instances select the same parameter, their actual Dart types must agree;
Box<int> and Box<double> conflict even though both use TypeScript number.
A nullable or optional instance selects a type only when present and non-null.
Otherwise, the declaration's defaults apply, following any selected bound.
For a variable that may be null, inputs must work in both cases; narrow it
first when the native and opaque input shapes differ.
Instance arguments can also contain nested parameters, as in
append<T>(Box<List<T>> box, T value): a Dart Box<List<int>> selects T = int.
Instances inside lists or callbacks do not select type arguments. An occurrence
of T? alone cannot distinguish a nullable T from a non-nullable one; another
occurrence of T is needed to select it.
Typed callbacks can also be stored and replaced:
@NAPI()
Box<int Function(int)> transform() => Box((value) => value + 1);
const box = transform();
box.value(2); // 3
box.value = value => value * 2;
Callback arguments and results use the same conversions as ordinary callback
fields, including optional and named parameters and Future results. Callbacks
can declare their own type parameters, such as Box<T Function<T>(T)>.
Data-class and Stream arguments use their usual input and output conversions,
including inside collections and callbacks:
@NAPI.object()
class Amount {
@NAPI()
Amount({required String value}) : value = int.parse(value);
@NAPI()
final int value;
}
@NAPI()
Box<Amount> amountBox() => Box(Amount(value: '7'));
const nativeBox: Box<Amount> = amountBox();
nativeBox.value = {value: '42'};
const amount = nativeBox.value; // {value: 42}
const jsBox = new Box(amount);
jsBox.value = amount; // stores the same JS object
Box<Amount> describes a Dart instance with Amount conversion. A box created
from JavaScript keeps the supplied value opaquely; when its input and output
shapes differ, keep the inferred type or use typeof jsBox instead of annotating
it as Box<Amount>. Symmetric types such as Box<number> work the same way for
both origins. A Box<Stream<T>> accepts an async iterable and returns an async
iterator with the existing Stream cancellation behavior.
When no bound-instance argument selects a type parameter, generic helpers use
their default Dart type arguments. If such a helper can return either an input
box or a newly constructed box, its inferred result allows only writes supported
by both. Pass a bound instance such as a Box<Amount>, or use a concrete return
type, when the helper requires Amount conversion.
Nested arguments such as Box<List<T>> use the actual Dart element type.
Nested Future arguments such as Box<Future<Future<int>>> use a single
Promise<number> for both reads and writes.
Future arguments follow the Future adoption rules in each
direction. When the value has a callable then, reads return the adopted
value and writes exclude values that Promise resolution would replace:
@NAPI()
class Thenable {
@NAPI()
Thenable(this.value);
@NAPI()
final int value;
@NAPI()
void then(void Function(int) resolve) => resolve(value);
}
@NAPI()
Box<Future<Thenable>> thenableBox() => Box(Future.value(Thenable(7)));
const box = thenableBox();
await box.value; // 7, the adopted value
box.value = Promise.reject(new Error()); // a fulfilled Promise cannot hold a Thenable
These rules apply when the class argument names the Future element, as in
Box<Future<Thenable>>. A member typed with the class's own parameter, such as
Future<T> in FutureBox<T>, uses TypeScript's Awaited for both directions.
Declare the concrete argument when writes must exclude adopted values.
Functions and callbacks #
Use ordinary Dart function types for callbacks and returned closures:
@NAPI()
int apply(int Function(int) transform, int value) => transform(value);
@NAPI()
int Function(int) multiplier(int factor) => (value) => factor * value;
apply(value => value + 1, 41); // 42
multiplier(3)(14); // 42
Callbacks can be stored and called later on the same Dart isolate. Returning a
JS callback preserves its identity for signatures with symmetric conversions,
such as scalar arguments and results. Data classes, dates, ByteBuffer,
ByteData, SIMD types, Sets, Futures and Streams require an adapter, including when
nested in a signature, so a returned function may differ from the original JS
callback. Use JsReference<JsFunction> when passing
the original function without conversion.
Returning the same Dart closure through the same function type reuses its live
JS function. Different function types receive separate adapters. Collecting the
JS function releases its Dart closure and captured values. Optional arguments
keep the actual Dart function's defaults and distinguish omission from null
and undefined.
In TypeScript, use a rest parameter such as (...args) => args[0] when a
callback ignores optional positional arguments. The current declarations reject
a shorter fixed-arity callback in that position.
Arguments and results use the same conversions as other annotated functions, including nested collections and exported classes.
Callbacks can have their own type parameters:
typedef Identity = T Function<T>(T value);
@NAPI()
int applyIdentity(Identity identity) => identity<int>(42);
applyIdentity(value => value); // 42
Dart calls use the actual type arguments and check the callback's result against
them. Scalars and JS references keep their usual representations. Other Dart
values passed as a whole T use opaque handles: JavaScript can keep and return
them, but cannot access their contents. Returning a handle restores its Dart
value. Explicit shapes such as List<T> still become JS arrays, with each T
element following these rules. Calling a generic Dart function from JavaScript
uses the declaration's default type arguments unless a bound-instance parameter
selects them.
A bound class such as Box<T> converts its members using the actual Dart T,
including when the box is a field of a generic data class. For example, its
value is a JS array when T is List<int>. The type does not need to appear in
another exported declaration.
JavaScript values #
Use an owned reference to keep a JS object, function or Symbol in Dart:
@NAPI()
Future<JsReference<JsObject>> returnLater(JsReference<JsObject> value) async {
await Future<void>.delayed(const Duration(milliseconds: 1));
return value;
}
const value = {};
await returnLater(value) === value; // true
JsReference<JsObject>, JsReference<JsFunction> and JsReference<JsSymbol>
preserve JS identity across calls. Returning a reference does not consume it.
Use dispose() when finished; references are also released by Dart collection
and environment cleanup. Cross-heap reference cycles require explicit disposal.
The reference's value is borrowed during a callback or Env.withScope.
Object? accepts any JS value: scalars become Dart values, and objects,
functions and Symbols become owned references. It generates TypeScript unknown;
dynamic generates any. A non-nullable Object rejects null and still accepts
JS undefined, represented by the exported undefined value. Use JsUndefined
when a declaration specifically requires undefined.
Opaque values keep their identity rather than reading object properties. They
can return Dart scalars and JS references; use a concrete supported Dart type
such as List<int> or a record to convert structured Dart results. Hiding a Dart
container or class behind Object? does not serialize it automatically.
Futures #
Return a Future to expose an asynchronous function, or accept one to await a
JavaScript Promise:
@NAPI()
Future<int> addLater(int value) async {
await Future<void>.delayed(const Duration(milliseconds: 1));
return value + 1;
}
@NAPI()
Future<int> addFromPromise(Future<int> value) async => await value + 1;
await addLater(41); // 42
await addFromPromise(Promise.resolve(41)); // 42
Future parameters require a Promise. Its completed value is checked against the
declared Dart type. Completion errors reject the returned Promise, including
errors converting a Dart result; JS rejection reasons retain their identity.
Future<void> resolves to undefined. Use it instead of async void.
Results follow standard Promise resolution: returned thenables are adopted, and
nested Futures are flattened. A nested Future parameter accepts the flattened
Promise value and rebuilds the declared Dart Future layers. For example,
Future<Future<int>> accepts Promise.resolve(7). If an inner Future is nullable,
a fulfilled null becomes null at the outermost nullable layer. Futures inside
lists and maps are supported.
With a nullable then, the return type includes both the unchanged object and
any declared fulfilled value. Thenables without a finite resolved type are
rejected during compilation.
The same rules apply to a callable then entry in a returned string-keyed map.
When an unchanged JavaScript callback can consume resolver arguments outside its
declared signature, the Promise result is unknown.
Result types also include values adopted through an exported subclass's then.
If an exported SettledTicket extends Ticket and its then resolves a
String, Future<Ticket> becomes Promise<Ticket | string>. When a then
member may or may not be callable, such as an Object? field, the result type
is unknown. The result is also unknown when an adopted callback's parameters
depend on a class type argument: Future<Base<Object?>> may contain
Child<String>, whose callback only accepts strings. Narrow or assert the result
before calling it, or declare the callback result directly as
Future<void Function(String)> to expose Promise<(value: string) => void>.
The same restriction applies when the adopted value exposes setters or methods
that consume the hidden type, such as a Box<String> returned through a wider
base class. Read-only results retain their declared types.
Promise inputs exclude values that resolution would adopt, including values
whose then may be callable. A Future<Ticket> parameter does not accept
Promise<SettledTicket>, and a Future<Thenable> parameter accepts
Promise<never>: it can remain pending or reject, but cannot fulfill with a
Thenable. These checks use the static TypeScript type: a SettledTicket
typed as Ticket, or an object typed only by an index signature, is still
adopted, and the conversion rejects with a TypeError. A dynamic then is
any in TypeScript and cannot exclude adopted values.
A Future whose element is a type parameter, such as Future<T> in a generic
function or in FutureBox<T>, keeps TypeScript's own Promise typing for T. It
does not account for exported subclasses or exclude adopted inputs.
Iterables #
Export Iterable<T> for a lazy, synchronous sequence. Each JS iteration obtains
a new Dart iterator; List<T> continues to produce an ordinary JS array.
@NAPI()
Iterable<int> count(int limit) sync* {
for (var value = 0; value < limit; value++) {
yield value;
}
}
@NAPI()
int first(Iterable<int> values) => values.first;
const values = count(3);
[...values]; // [0, 1, 2]
[...values]; // [0, 1, 2], a separate iteration
first(new Set([2, 3])); // 2
Breaking out of for…of, or calling an iterator's return(), closes it and runs
the active Dart sync* finalizers, including nested yield* generators. Values
yielded during this cleanup are discarded. Closing before the first next()
does not start the generator.
In compiled addons, Dart for…in also closes its iterator on exit. Standard
Iterable operations such as first, map, and take propagate this cleanup;
JS input iterators receive return() when available. An existing iteration or
conversion error takes precedence over a cleanup error. Custom Dart iterators
remain responsible for resources they manage themselves.
Elements use the same conversions as other parameters and results, including
data classes and generic values. Use Stream<T> for asynchronous sequences.
Streams #
Use a Dart Stream to produce or consume an async iterable:
@NAPI()
Stream<int> count(int limit) async* {
for (var value = 0; value < limit; value++) {
yield value;
}
}
@NAPI()
Future<int> sum(Stream<int> values) async {
var total = 0;
await for (final value in values) {
total += value;
}
return total;
}
for await (const value of count(3)) {
console.log(value); // 0, 1, 2
}
await sum((async function* () { yield 2; yield 3; })()); // 5
Each returned stream is a single async iterator with next() and return().
Concurrent next() calls are queued. Breaking out of for await or calling
return() cancels the Dart subscription. In-flight requests keep their iterator
alive; collection of an idle iterator also cancels its subscription.
Input streams subscribe once and stop pulling while paused. Cancellation calls
the JS iterator's return() when available. A producer that never completes its
return() can also leave Dart cancellation pending.
Stream events use the same conversions as other values. Promise-valued events
are not flattened. Use next() when handling Stream<Future<T>>: TypeScript
infers an awaited element in for await loops even though a native async
iterator preserves the Promise value.
npm packages #
Use PackageBuild in your Dart build script to produce an installable package:
final compiler = Compiler([
PackageBuild(
entry: File('lib/addon.dart'),
output: Directory('dist/npm'),
name: '@acme/addon',
version: '1.0.0',
),
]);
The output includes the native addon, runtime notices, CJS/ESM entries and
TypeScript declarations. Consumers install it with npm install ./dist/npm:
import { add } from '@acme/addon';
console.log(add(20, 22)); // 42
require('@acme/addon') exposes the same bindings. Package entries require
Node.js 12.22 or later, plus any newer version required by the exported APIs.
No install-time compilation is needed.
For multiple platforms, build on each platform and keep its output directory,
including .napi.json. Assemble the artifacts in a separate build script:
final compiler = Compiler([
PackageBuild.fromArtifacts(
artifacts: [
NativeArtifact(File('macos/.napi.json')),
NativeArtifact(File('linux/.napi.json')),
NativeArtifact(File('windows/.napi.json')),
],
output: Directory('dist/npm'),
name: '@acme/addon',
version: '1.0.0',
),
]);
Assembly does not run the compiler or load foreign addons. Artifacts must expose
the same declarations. Publish the packages under platforms/ before publishing
the root package; npm selects the matching platform dependency. The root package
also loads directly from the complete build directory.
Choose an empty output directory or a previous PackageBuild output. Rebuilds
reject unknown files instead of deleting them. Switching output directories can
briefly make the package unavailable; a failed switch restores the old directory.
Accessing the environment #
Add a required Env parameter to use the current Node environment:
import 'package:napi/env.dart';
import 'package:napi/napi.dart';
@NAPI()
JsReference<JsObject> labeled(Env env, String name) {
final result = env.object();
result.defineValue('name', name);
return result.retain();
}
addon.labeled('Dart'); // { name: 'Dart' }
Env parameters are omitted from JavaScript and TypeScript signatures. They may appear anywhere among required positional parameters, or as required named parameters, including on annotated methods and constructors. They must be non-nullable. Each Worker receives its own environment.
Borrowed JS values are valid during the call. After an await, use
env.withScope for operations that create or access them; retain a value to keep
it beyond that scope. See values and references.
Manual registration #
For low-level bindings, use void register(Env env, JsObject exports) instead:
import 'package:napi/env.dart';
void register(Env env, JsObject exports) {
exports.defineValue('add', env.function('add', (args) {
return args.get<int>(0) + args.get<int>(1);
}));
}
The compiler connects this synchronous entry to the Node environment. Manual
registration and annotation exports are separate entry modes. Raw addons can
also provide the initialize, afterPump and dispose hooks used by the
native experiment.
Use env.defineClass<T> for explicit class bindings. Instance methods and setters
receive (T, JsArguments); instance getters receive T. Constructors, static
methods and static setters receive only JsArguments; static getters take no
arguments. An optional finalize callback can release resources; it must not access
JavaScript during environment cleanup. Class registrations remain live until
their environment ends. Functions created with env.function release their Dart
callbacks when JavaScript collects them.
Values and references #
Arguments use strict conversions without JavaScript coercion:
bool,String,doubleandBigIntmap to their corresponding JS primitives.intaccepts finite integral Numbers within ±9,007,199,254,740,991. Returning a Dart int outside that range throws a RangeError; use BigInt for larger integers.- Nullable types accept
null. JavaScriptundefinedis the Dartundefinedconstant;args.lengthdistinguishes an omitted argument from a supplied one. - Objects, functions and symbols use
JsObject,JsFunctionandJsSymbol.
JS handles are borrowed during register, a registered callback or
env.withScope. To keep an object, function or symbol across calls, use retain()
and read the resulting reference's value within a scope. Call dispose() when
finished; references are also released on Dart collection or environment cleanup.
Cross-heap cycles require explicit disposal. Each Env belongs to its original
Node environment and Dart isolate.
JavaScript exceptions become JsException in Dart; rethrowing one preserves the
original JS value. Dart ArgumentError and TypeError become JS TypeError,
RangeError becomes JS RangeError, and other Dart errors become JS Error.
Raw bindings #
Import the raw FFI bindings with:
import 'package:napi/sys/node.dart' as node;
These bindings expose Node-API handles, status codes and native function signatures. Calls require a valid environment supplied by a Node-API host.
See the native image experiment for the standalone Dart AOT addon prototype.