Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 36 additions & 0 deletions .cto-toolkit/learning/patterns.jsonl
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
{
"session_id": "1794959463-1188",
"timestamp": "2026-11-17T23:51:03Z",
"files_modified": 208,
"languages": "javascript,python",
"tests_touched": false,
"security_relevant": true,
"project_root": "/c/Users/nicol/Desktop/QUICKJS-NAPI/quickjs-napi"
}
{
"session_id": "1794961659-432",
"timestamp": "2026-11-18T00:27:39Z",
"files_modified": 5,
"languages": "python",
"tests_touched": false,
"security_relevant": false,
"project_root": "/c/Users/nicol/Desktop/QUICKJS-NAPI/quickjs-napi"
}
{
"session_id": "1794961677-237",
"timestamp": "2026-11-18T00:27:57Z",
"files_modified": 5,
"languages": "python",
"tests_touched": false,
"security_relevant": false,
"project_root": "/c/Users/nicol/Desktop/QUICKJS-NAPI/quickjs-napi"
}
{
"session_id": "1794961714-1861",
"timestamp": "2026-11-18T00:28:34Z",
"files_modified": 5,
"languages": "python",
"tests_touched": false,
"security_relevant": false,
"project_root": "/c/Users/nicol/Desktop/QUICKJS-NAPI/quickjs-napi"
}
18 changes: 17 additions & 1 deletion CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@ option(QJSNAPI_SANITIZE
option(QJSNAPI_TSAN
"Build everything (QuickJS and libuv included) with ThreadSanitizer" OFF)
option(QJSNAPI_BUILD_TESTS "Build the test addons and the test suite" ON)
option(QJSNAPI_NODE_ADDON_API_TESTS
"Build and run the node-addon-api test suite (C++, 8 bindings)" ON)

set(QJSNAPI_QUICKJS_DIR
"${CMAKE_CURRENT_SOURCE_DIR}/../quickjs-build"
Expand Down Expand Up @@ -228,7 +230,7 @@ else()
endif()
set(CMAKE_C_LINK_LIBRARY_USING_QJSNAPI_WHOLE_ARCHIVE_SUPPORTED TRUE)

add_executable(quickjs-napi host/main.c
add_executable(quickjs-napi host/main.c host/spawn.c
"${QJSNAPI_GENERATED_DIR}/bootstrap_js.h")
target_include_directories(quickjs-napi PRIVATE "${QJSNAPI_GENERATED_DIR}")
set_target_properties(quickjs-napi PROPERTIES C_STANDARD 17 ENABLE_EXPORTS ON)
Expand Down Expand Up @@ -423,6 +425,10 @@ if(QJSNAPI_BUILD_TESTS)
include("${QJSNAPI_NODE_TESTS_SRC}/js-native-api/tests.cmake")
include("${QJSNAPI_NODE_TESTS_SRC}/node-api/tests.cmake")

if(QJSNAPI_NODE_ADDON_API_TESTS)
include(cmake/node_addon_api_tests.cmake)
endif()

add_test(NAME js_values
COMMAND quickjs-napi
"${CMAKE_CURRENT_SOURCE_DIR}/test/js/test_values.js"
Expand All @@ -435,6 +441,10 @@ if(QJSNAPI_BUILD_TESTS)
COMMAND quickjs-napi
"${CMAKE_CURRENT_SOURCE_DIR}/test/js/test_node_api.js"
"${QJSNAPI_ADDON_DIR}")
# Host features of the executable (child_process, -e, -r, NODE_OPTIONS).
add_test(NAME js_host
COMMAND quickjs-napi "${CMAKE_CURRENT_SOURCE_DIR}/test/js/test_host.js")
set_tests_properties(js_host PROPERTIES PASS_REGULAR_EXPRESSION "^ok")

add_executable(test_embed test/unit/test_embed.c)
set_target_properties(test_embed PROPERTIES C_STANDARD 17)
Expand All @@ -453,6 +463,12 @@ if(QJSNAPI_BUILD_TESTS)
"${CMAKE_CURRENT_SOURCE_DIR}/test/js/test_${_t}.js"
"${QJSNAPI_ADDON_DIR}")
endforeach()
add_test(NAME node_parity_host
COMMAND "${QJSNAPI_NODE}"
"${CMAKE_CURRENT_SOURCE_DIR}/test/js/test_host.js")
# The NODE_OPTIONS of the environment must not reach Node.js itself.
set_tests_properties(node_parity_host PROPERTIES
PASS_REGULAR_EXPRESSION "^ok" ENVIRONMENT "NODE_OPTIONS=")
endif()

find_package(Python3 COMPONENTS Interpreter)
Expand Down
61 changes: 49 additions & 12 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,24 +6,42 @@ Node-API implementation for QuickJS (2026-06-04, from `../quickjs-build`).
Addons built for Node.js (node-gyp, node-addon-api, napi-rs) are loaded
unchanged: they resolve `napi_*` from the `quickjs-napi` executable.

Status: milestone **M5** (M1 values, strings, objects, properties,
Status: milestone **M6** in progress (M1 values, strings, objects, properties,
functions, classes, errors; M2 references, externals, wrapping, finalizers,
type tags, instance data, `napi_run_script`; M3 ArrayBuffer, TypedArray,
DataView, BigInt, Date, Promise; M4 the synchronous `node_api.h`: Buffer,
async context, `napi_make_callback`, callback scopes,
`napi_fatal_exception`; M5 the libuv event loop: async work, thread-safe
functions, async cleanup hooks, `napi_get_uv_event_loop`). All 155
Node-API functions are implemented and pass 30 tests of the Node.js
`js-native-api` suite and 19 of its `node-api` suite (see
`test/node/README.md`). `NAPI_EXPERIMENTAL` APIs are not provided. See
`PIANO-IMPLEMENTAZIONE.md` in the project for the plan.
functions, async cleanup hooks, `napi_get_uv_event_loop`; M6 real-world
conformance). All 155 Node-API functions are implemented and pass 30 tests
of the Node.js `js-native-api` suite, 19 of its `node-api` suite (see
`test/node/README.md`) and 78 of the 83 test modules of the node-addon-api
8.9.2 suite (the others need `worker_threads`, `npm` or test the npm
package itself), in its four binding variants (C++ exceptions, no exceptions,
`Maybe`, custom namespace; see `test/node-addon-api/harness/README.md`).
`NAPI_EXPERIMENTAL` APIs are not provided. See `PIANO-IMPLEMENTAZIONE.md`
in the project for the plan.

## Lifetime model

- `napi_ref` follows `v8impl::Reference`: strong while its count is > 0; at
count 0 an object, function or local symbol is held through a JS `WeakRef`
(QuickJS reports the target dead as soon as its refcount drops to zero),
other values are released.
- V8 keeps the target of a weak handle until a garbage collection; QuickJS
frees an object when its refcount drops to zero, so an object created by
a native call and only referenced weakly would die when the call returns
(node-addon-api relies on the V8 behaviour: `Napi::Weak(Object::New(env))`
used later in the same synchronous code). When a reference becomes weak its
target is therefore also put on a list of *kept objects*, like the
`[[KeptAlive]]` list of ECMAScript WeakRefs, cleared at the end of every
macrotask (the library's checkpoint), by `gc()` and at teardown;
embedders call `qjsnapi_host_clear_kept_objects` at the end of their own
macrotasks.
- `napi_define_class`: as with V8's prototype template, a later instance
property with the same key replaces an earlier one, whatever its
attributes (static properties are defined like `napi_define_properties`,
where such a redefinition fails, in Node.js too).
- QuickJS has no weak callback in its C API. Each target of a reference, a
wrap or a type tag gets a *holder* object in a `WeakMap` keyed by the
target; QuickJS drops the entry of a dead key during `JS_RunGC`, and the
Expand Down Expand Up @@ -123,6 +141,11 @@ Node-API functions are implemented and pass 30 tests of the Node.js
thread-safe function and async cleanup hook is done, then the reference
finalizers with JavaScript disabled. Async work items and user references
the addon never deleted are freed with the env (Node.js leaks them).
- `process.exit()` and a fatal exception end the executable like Node.js
(`DefaultProcessExitHandlerInternal`): the `exit` event is emitted, the
thread pool is shut down, and the process exits without tearing the
environment down (no cleanup hook or finalizer runs, work in flight is not
waited for). A normal end of the script tears everything down as above.
- `napi_fatal_error` prints `FATAL ERROR: <location> <message>` and aborts
(`_exit(134)` on Windows, as Node.js).

Expand Down Expand Up @@ -178,6 +201,7 @@ Options:
| `QJSNAPI_SANITIZE` | OFF | ASan + UBSan for everything, QuickJS included |
| `QJSNAPI_TSAN` | OFF | ThreadSanitizer for everything (exclusive with `QJSNAPI_SANITIZE`) |
| `QJSNAPI_BUILD_TESTS` | ON | test addons and CTest suite |
| `QJSNAPI_NODE_ADDON_API_TESTS` | ON | the node-addon-api suite (8 C++ bindings, about 2 minutes of build) |

`include/quickjs.h` and `include/quickjs-libc.h` must be identical to the
ones in `quickjs-build`: configuration fails otherwise (JSValue ABI).
Expand Down Expand Up @@ -216,12 +240,18 @@ resolves the `napi_*` imports from the running executable.

```sh
quickjs-napi [options] script.js [args...]
quickjs-napi [options] -e <code> [args...]
```

Options: `--force-node-api-uncaught-exceptions-policy[=true|false]` and
Options: `-e`/`--eval <code>` (run the code instead of a script,
`process.argv` is `[execPath, args...]`), `-r`/`--require <module>`
(loaded before the script, repeatable),
`--force-node-api-uncaught-exceptions-policy[=true|false]` and
`--no-force-node-api-uncaught-exceptions-policy` (see above), `--expose-gc`
(accepted and ignored: `gc()` is always defined). An unknown option exits
with code 9, as Node.js.
with code 9, as Node.js. `NODE_OPTIONS` is read first, with the same
options separated by spaces; the options only Node.js knows are ignored
there (the variable is shared with Node.js).

The script runs as a CommonJS module (`host/bootstrap.js`): `require`
loads `.js`, `.json` and `.node` files with Node.js resolution rules
Expand All @@ -233,7 +263,10 @@ loads `.js`, `.json` and `.node` files with Node.js resolution rules
modules `timers` and `timers/promises`), `Buffer` (also `require('buffer')`),
minimal builtin modules `util` (`promisify`, `types`), `url`
(`pathToFileURL`, `fileURLToPath`) and `vm` (`runInNewContext`, a new realm
of the same runtime), `process.version`, and the quickjs-libc helpers
of the same runtime), `child_process` (`spawnSync` and `spawn` without a
shell; stdio `pipe`, `inherit` or `ignore`, an asynchronous child's stdin is
never a pipe), `events` (a minimal `EventEmitter`), `process.env` (the real
environment), `process.version`, and the quickjs-libc helpers
(`console.log`, `print`, `scriptArgs`). As in Node.js, an exception no
frame catches (a timer, a microtask, a Node-API finalizer) goes to
`process.on('uncaughtException')` or ends the process with exit code 1, and
Expand All @@ -248,7 +281,8 @@ The embedder runs the host's libuv loop (`uv_run`), which also runs the
queued finalizers; it installs `qjsnapi_host_set_uncaught_handler` for
exceptions thrown by native callbacks and may install
`qjsnapi_host_set_checkpoint` to drain microtasks, rejections and its own
timers after each one.
timers after each one, and calls `qjsnapi_host_clear_kept_objects` at the
end of each macrotask it runs itself and before an explicit GC.

## Layout

Expand All @@ -271,11 +305,14 @@ timers after each one.
| `src/tsfn.c` | thread-safe functions |
| `src/loader.c` | `.node` loading: `napi_register_module_v1`, API version, legacy `napi_module_register` |
| `src/stubs_generated.c` | generated by `tools/gen_stubs.py`, do not edit (empty now: every function is implemented) |
| `host/main.c`, `host/bootstrap.js` | the `quickjs-napi` executable: libuv event loop (timers, immediates, `beforeExit`), CommonJS loader, `process` (embedded at build time by `cmake/embed.cmake`), `buffer`, `util`, `url`, `vm` |
| `host/main.c`, `host/bootstrap.js` | the `quickjs-napi` executable: options, libuv event loop (timers, immediates, `beforeExit`), CommonJS loader, `process` (embedded at build time by `cmake/embed.cmake`), `buffer`, `util`, `url`, `vm`, `child_process`, `events` |
| `host/spawn.c` | child processes (`spawnSync` on a private loop, `spawn` on the main one) |
| `test/addons`, `test/js` | our test addons; the JS tests also run under Node.js as reference |
| `test/node` | Node.js conformance tests (vendored, see its README) |
| `test/node-addon-api` | node-addon-api headers and test suite (vendored by `tools/sync_node_addon_api.py`); `harness/` is ours (see its README) |
| `cmake/node_addon_api_tests.cmake` | builds the 8 node-addon-api test bindings, one CTest per test module |
| `test/unit` | C embedding test (teardown order, scopes, error state, finalizer queue) |
| `test/lsan.supp` | LeakSanitizer suppressions for leaks the Node.js tests make by design |
| `test/lsan.supp` | LeakSanitizer suppressions for leaks the Node.js and node-addon-api tests make by design |
| `cmake/expect_abort.cmake` | runs a Node.js test that must abort (`napi_fatal_error`) and checks its output |

After implementing a function, run `python3 tools/gen_stubs.py` to drop its
Expand Down
125 changes: 125 additions & 0 deletions cmake/node_addon_api_tests.cmake
Original file line number Diff line number Diff line change
@@ -0,0 +1,125 @@
# node-addon-api test suite (vendored by tools/sync_node_addon_api.py),
# included from CMakeLists.txt when QJSNAPI_NODE_ADDON_API_TESTS is ON.
#
# Layout in the build tree, as in a node-addon-api checkout:
# node-addon-api-tests/index.js harness/index.js (package stub)
# node-addon-api-tests/test/... the vendored test/ directory
# node-addon-api-tests/test/common/ harness/common (quickjs-napi)
# node-addon-api-tests/test/run.js harness/run.js (one module)
# node-addon-api-tests/test/preload.js harness/preload.js (--require)
# node-addon-api-tests/test/qn_assert.js test/node/common/assert.js
# node-addon-api-tests/test/build/Release/<binding>.node
# Every module is a CTest named naa/<module>:
# NODE_OPTIONS=--require=test/preload.js \
# quickjs-napi --expose-gc test/run.js <module>
# NODE_OPTIONS (not -r) so that the child processes the tests start load
# the preload as well.

set(QJSNAPI_NAA_SRC "${CMAKE_CURRENT_SOURCE_DIR}/test/node-addon-api")
set(QJSNAPI_NAA_BIN "${CMAKE_CURRENT_BINARY_DIR}/node-addon-api-tests")

# The JavaScript side (configure_file re-copies a changed source).
file(GLOB_RECURSE _naa_js RELATIVE "${QJSNAPI_NAA_SRC}/test"
"${QJSNAPI_NAA_SRC}/test/*.js")
foreach(_f ${_naa_js})
configure_file("${QJSNAPI_NAA_SRC}/test/${_f}" "${QJSNAPI_NAA_BIN}/test/${_f}"
COPYONLY)
endforeach()
configure_file("${QJSNAPI_NAA_SRC}/harness/common/index.js"
"${QJSNAPI_NAA_BIN}/test/common/index.js" COPYONLY)
configure_file("${QJSNAPI_NAA_SRC}/harness/run.js"
"${QJSNAPI_NAA_BIN}/test/run.js" COPYONLY)
configure_file("${QJSNAPI_NAA_SRC}/harness/preload.js"
"${QJSNAPI_NAA_BIN}/test/preload.js" COPYONLY)
configure_file("${QJSNAPI_NAA_SRC}/harness/index.js"
"${QJSNAPI_NAA_BIN}/index.js" COPYONLY)
configure_file("${CMAKE_CURRENT_SOURCE_DIR}/test/node/common/assert.js"
"${QJSNAPI_NAA_BIN}/test/qn_assert.js" COPYONLY)

# One binding of test/binding.gyp. The defines are those of
# node_addon_api.gyp (except.gypi / noexcept.gypi) and common.gypi
# (NAPI_VERSION = process.versions.napi of Node.js 22: 10).
function(qjsnapi_naa_binding name exceptions)
cmake_parse_arguments(T "" "" "SOURCES;DEFINES" ${ARGN})
list(TRANSFORM T_SOURCES PREPEND "${QJSNAPI_NAA_SRC}/test/")
add_library(naa_${name} MODULE ${T_SOURCES})
set_target_properties(
naa_${name}
PROPERTIES OUTPUT_NAME "${name}"
PREFIX ""
SUFFIX ".node"
CXX_STANDARD 17
CXX_VISIBILITY_PRESET hidden
LIBRARY_OUTPUT_DIRECTORY "${QJSNAPI_NAA_BIN}/test/build/Release"
RUNTIME_OUTPUT_DIRECTORY "${QJSNAPI_NAA_BIN}/test/build/Release")
target_include_directories(naa_${name} PRIVATE include "${QJSNAPI_NAA_SRC}"
"${QJSNAPI_NAA_SRC}/test/common")
target_compile_definitions(
naa_${name} PRIVATE BUILDING_NODE_EXTENSION NAPI_VERSION=10
NODE_GYP_MODULE_NAME=${name} ${T_DEFINES})
if(exceptions)
target_compile_definitions(naa_${name} PRIVATE NAPI_CPP_EXCEPTIONS)
target_compile_options(naa_${name} PRIVATE -fexceptions)
else()
target_compile_definitions(naa_${name}
PRIVATE NODE_ADDON_API_DISABLE_CPP_EXCEPTIONS)
target_compile_options(naa_${name} PRIVATE -fno-exceptions)
endif()
# As node-gyp in Release: assertions stay.
target_compile_options(naa_${name} PRIVATE -UNDEBUG)
# napi-inl.h reads DataView values through misaligned pointers
# (DataView::ReadData): undefined behaviour of node-addon-api itself, which
# UBSan (QJSNAPI_SANITIZE, zig's Debug default) would report.
target_compile_options(naa_${name} PRIVATE -fno-sanitize=alignment)
if(WIN32)
target_link_libraries(naa_${name} PRIVATE quickjs-napi)
elseif(APPLE)
target_link_options(naa_${name} PRIVATE -undefined dynamic_lookup)
endif()
add_dependencies(quickjs-napi-tests naa_${name})
endfunction()

# One test module (called by the generated tests.cmake).
function(qjsnapi_naa_test module)
add_test(NAME naa/${module}
COMMAND quickjs-napi --expose-gc "${QJSNAPI_NAA_BIN}/test/run.js"
"${module}"
WORKING_DIRECTORY "${QJSNAPI_NAA_BIN}/test")
set_tests_properties(
naa/${module}
PROPERTIES ENVIRONMENT
"NODE_OPTIONS=--require=${QJSNAPI_NAA_BIN}/test/preload.js")
endfunction()

include("${QJSNAPI_NAA_SRC}/tests.cmake")

# Racy upstream: SignalAfterProgressTestWorker calls Send() then Signal()
# from its thread; if the loop thread runs OnWorkProgress between the two,
# the second call sees no data (count 0, "expect 1 count of data"), under
# Node.js as well. The window is a preemption of the worker thread between
# two calls, so the test runs alone to keep the machine unloaded.
if(TEST naa/async_progress_worker)
set_tests_properties(naa/async_progress_worker PROPERTIES RUN_SERIAL ON)
endif()

qjsnapi_naa_binding(binding ON SOURCES ${QJSNAPI_NAA_BUILD_SOURCES}
DEFINES NODE_ADDON_API_ENABLE_TYPE_CHECK_ON_AS)
qjsnapi_naa_binding(binding_noexcept OFF SOURCES ${QJSNAPI_NAA_BUILD_SOURCES})
qjsnapi_naa_binding(binding_noexcept_maybe OFF
SOURCES ${QJSNAPI_NAA_BUILD_SOURCES}
DEFINES NODE_ADDON_API_ENABLE_MAYBE)
qjsnapi_naa_binding(binding_custom_namespace OFF
SOURCES ${QJSNAPI_NAA_BUILD_SOURCES}
DEFINES NAPI_CPP_CUSTOM_NAMESPACE=cstm)
qjsnapi_naa_binding(binding_swallowexcept ON
SOURCES ${QJSNAPI_NAA_SWALLOWEXCEPT_SOURCES}
DEFINES NODE_API_SWALLOW_UNTHROWABLE_EXCEPTIONS)
qjsnapi_naa_binding(binding_swallowexcept_noexcept OFF
SOURCES ${QJSNAPI_NAA_SWALLOWEXCEPT_SOURCES}
DEFINES NODE_API_SWALLOW_UNTHROWABLE_EXCEPTIONS)
qjsnapi_naa_binding(binding_except_all ON
SOURCES ${QJSNAPI_NAA_EXCEPT_ALL_SOURCES}
DEFINES NODE_ADDON_API_CPP_EXCEPTIONS_ALL)
qjsnapi_naa_binding(binding_type_check OFF
SOURCES ${QJSNAPI_NAA_TYPE_CHECK_SOURCES}
DEFINES NODE_ADDON_API_ENABLE_TYPE_CHECK_ON_AS)
Loading
Loading