From 6b5b62e44f3e346add9625999571d66311c18e80 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?D=C3=A1vid=20Istv=C3=A1n=20B=C3=ADr=C3=B3?= Date: Tue, 24 Nov 2026 19:37:46 +0000 Subject: [PATCH 1/5] Add optional zstd support [skip ci] --- README.md | 14 +- crates/wasm-rquickjs/skeleton/Cargo.lock | 32 +++ crates/wasm-rquickjs/skeleton/Cargo.toml_ | 6 +- .../skeleton/src/builtin/zlib.js | 191 ++++++++++++++ .../skeleton/src/builtin/zlib.rs | 74 ++++++ .../skeleton/src/builtin/zlib/zstd.rs | 249 ++++++++++++++++++ examples/runtime/zlib/src/zlib.js | 95 +++++++ examples/runtime/zlib/wit/zlib.wit | 2 + .../generated_types_zlib_exports.d.ts | 2 + tests/node_compat/config.jsonc | 42 ++- tests/node_compat/report.md | 32 +-- tests/runtime/zlib.rs | 25 ++ 12 files changed, 716 insertions(+), 48 deletions(-) create mode 100644 crates/wasm-rquickjs/skeleton/src/builtin/zlib/zstd.rs diff --git a/README.md b/README.md index 0d6b24107..c9782d81e 100644 --- a/README.md +++ b/README.md @@ -102,11 +102,11 @@ the user's WIT world: - `logging`: enables the `wasi:logging` import to be used for the JavaScript `console` API - `sqlite`: enables the `node:sqlite` module with an embedded SQLite database engine -- `crypto`, `crypto-full`, `zlib`, `brotli`, `encoding`, `timezone`, `websocket` and `golem` +- `crypto`, `crypto-full`, `zlib`, `brotli`, `zstd`, `encoding`, `timezone`, `websocket` and `golem` enable the corresponding builtin capabilities The default `normal-p3` tier enables `logging`, `crypto`, `zlib` and `encoding`; `full-p3` adds -`crypto-full`, `brotli`, `sqlite` and `timezone`, and `full-no-logging-p3` is `full-p3` without +`crypto-full`, `brotli`, `zstd`, `sqlite` and `timezone`, and `full-no-logging-p3` is `full-p3` without `logging`. `fetch` and `node:http` always use `wasi:http`. Keep the `p3` feature in custom feature lists: it enables the `wit-bindgen-p3` dependency, which a `--dependency wit-bindgen-p3=...` replacement must therefore declare with `optional = true`. @@ -1257,11 +1257,13 @@ throws immediately. Environment-data APIs are unavailable.
node:zlib -- **Classes:** `Deflate`, `Inflate`, `Gzip`, `Gunzip`, `DeflateRaw`, `InflateRaw`, `Unzip`, `BrotliCompress`, `BrotliDecompress` -- **Factory:** `createGzip`, `createGunzip`, `createDeflate`, `createInflate`, `createDeflateRaw`, `createInflateRaw`, `createUnzip`, `createBrotliCompress`, `createBrotliDecompress` -- **Async:** `gzip`, `gunzip`, `deflate`, `inflate`, `deflateRaw`, `inflateRaw`, `unzip`, `brotliCompress`, `brotliDecompress` -- **Sync:** `gzipSync`, `gunzipSync`, `deflateSync`, `inflateSync`, `deflateRawSync`, `inflateRawSync`, `unzipSync`, `brotliCompressSync`, `brotliDecompressSync` +- **Classes:** `Deflate`, `Inflate`, `Gzip`, `Gunzip`, `DeflateRaw`, `InflateRaw`, `Unzip`, `BrotliCompress`, `BrotliDecompress`, `ZstdCompress`, `ZstdDecompress` +- **Factory:** `createGzip`, `createGunzip`, `createDeflate`, `createInflate`, `createDeflateRaw`, `createInflateRaw`, `createUnzip`, `createBrotliCompress`, `createBrotliDecompress`, `createZstdCompress`, `createZstdDecompress` +- **Async:** `gzip`, `gunzip`, `deflate`, `inflate`, `deflateRaw`, `inflateRaw`, `unzip`, `brotliCompress`, `brotliDecompress`, `zstdCompress`, `zstdDecompress` +- **Sync:** `gzipSync`, `gunzipSync`, `deflateSync`, `inflateSync`, `deflateRawSync`, `inflateRawSync`, `unzipSync`, `brotliCompressSync`, `brotliDecompressSync`, `zstdCompressSync`, `zstdDecompressSync` - `crc32`, `constants`, `codes` +- Zstandard requires the optional `zstd` feature (included in the full tiers). It uses the reference + zstd codec with worker threads disabled for WASI; `normal-p3` does not include that codec.
diff --git a/crates/wasm-rquickjs/skeleton/Cargo.lock b/crates/wasm-rquickjs/skeleton/Cargo.lock index 859ffd2da..f448cb390 100644 --- a/crates/wasm-rquickjs/skeleton/Cargo.lock +++ b/crates/wasm-rquickjs/skeleton/Cargo.lock @@ -305,6 +305,8 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e228eec9be7c17ccb640b59b36a5cd805ea2a564a4c5e162c2f659fea30d3b96" dependencies = [ "find-msvc-tools", + "jobserver", + "libc", "shlex 2.0.1", ] @@ -1253,6 +1255,16 @@ version = "1.0.18" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" +[[package]] +name = "jobserver" +version = "0.1.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9afb3de4395d6b3e67a780b6de64b51c978ecf11cb9a462c66be7d4ca9039d33" +dependencies = [ + "getrandom 0.3.4", + "libc", +] + [[package]] name = "js-sys" version = "0.3.103" @@ -1983,6 +1995,7 @@ dependencies = [ "wasip3", "whirlpool", "wit-bindgen 0.63.0", + "zstd-safe", ] [[package]] @@ -3495,3 +3508,22 @@ name = "zmij" version = "1.0.21" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b8848ee67ecc8aedbaf3e4122217aff892639231befc6a1b58d29fff4c2cabaa" + +[[package]] +name = "zstd-safe" +version = "7.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f49c4d5f0abb602a93fb8736af2a4f4dd9512e36f7f570d66e65ff867ed3b9d" +dependencies = [ + "zstd-sys", +] + +[[package]] +name = "zstd-sys" +version = "2.0.16+zstd.1.5.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "91e19ebc2adc8f83e43039e79776e3fda8ca919132d68a1fed6a5faca2683748" +dependencies = [ + "cc", + "pkg-config", +] diff --git a/crates/wasm-rquickjs/skeleton/Cargo.toml_ b/crates/wasm-rquickjs/skeleton/Cargo.toml_ index 801b523e4..b700a0d03 100644 --- a/crates/wasm-rquickjs/skeleton/Cargo.toml_ +++ b/crates/wasm-rquickjs/skeleton/Cargo.toml_ @@ -38,13 +38,14 @@ internal-test-execution = ["test-observability"] # Capability tiers (cumulative). The runtime ships its own `wasi:http@0.3` based fetch and # node:http unconditionally. normal-p3 = ["p3", "crypto", "zlib", "logging", "encoding"] -full-p3 = ["normal-p3", "crypto-full", "brotli", "sqlite", "timezone"] -full-no-logging-p3 = ["p3", "crypto", "zlib", "encoding", "crypto-full", "brotli", "sqlite", "timezone"] +full-p3 = ["normal-p3", "crypto-full", "brotli", "zstd", "sqlite", "timezone"] +full-no-logging-p3 = ["p3", "crypto", "zlib", "encoding", "crypto-full", "brotli", "zstd", "sqlite", "timezone"] logging = ["dep:wasi-logging"] encoding = ["dep:encoding_rs"] zlib = ["dep:flate2", "dep:crc32fast"] brotli = ["dep:brotli"] +zstd = ["zlib", "dep:zstd-safe"] # Crypto: common subset crypto = [ @@ -152,6 +153,7 @@ sec1 = { version = "0.7", default-features = false, features = ["der", "alloc", base64ct = { version = "1", features = ["alloc"] } flate2 = { version = "1", default-features = false, features = ["rust_backend"], optional = true } brotli = { version = "7", default-features = false, features = ["std"], optional = true } +zstd-safe = { version = "7.2.4", default-features = false, features = ["std"], optional = true } crc32fast = { version = "1", optional = true } # WASI Preview 2 bindings for the residual synchronous interfaces (see the `p3` feature). wasip2 = "1.0" diff --git a/crates/wasm-rquickjs/skeleton/src/builtin/zlib.js b/crates/wasm-rquickjs/skeleton/src/builtin/zlib.js index 1a8ea2900..44518b2ca 100644 --- a/crates/wasm-rquickjs/skeleton/src/builtin/zlib.js +++ b/crates/wasm-rquickjs/skeleton/src/builtin/zlib.js @@ -17,6 +17,10 @@ import { brotli_stream_push, brotli_stream_pull, brotli_stream_close, + zstd_stream_new, + zstd_stream_push, + zstd_stream_reset, + zstd_stream_close, } from '__wasm_rquickjs_builtin/zlib_native'; const setPrototypeOf = Object.setPrototypeOf; @@ -193,7 +197,37 @@ const BROTLI_DECODER_ERROR_UNREACHABLE = -31; const ZLIB_VERNUM = 4816; +const zstdConstants = { + ZSTD_COMPRESS: 10, ZSTD_DECOMPRESS: 11, + ZSTD_e_continue: 0, ZSTD_e_flush: 1, ZSTD_e_end: 2, + ZSTD_fast: 1, ZSTD_dfast: 2, ZSTD_greedy: 3, ZSTD_lazy: 4, ZSTD_lazy2: 5, + ZSTD_btlazy2: 6, ZSTD_btopt: 7, ZSTD_btultra: 8, ZSTD_btultra2: 9, + ZSTD_c_compressionLevel: 100, ZSTD_c_windowLog: 101, ZSTD_c_hashLog: 102, + ZSTD_c_chainLog: 103, ZSTD_c_searchLog: 104, ZSTD_c_minMatch: 105, + ZSTD_c_targetLength: 106, ZSTD_c_strategy: 107, + ZSTD_c_enableLongDistanceMatching: 160, ZSTD_c_ldmHashLog: 161, + ZSTD_c_ldmMinMatch: 162, ZSTD_c_ldmBucketSizeLog: 163, ZSTD_c_ldmHashRateLog: 164, + ZSTD_c_contentSizeFlag: 200, ZSTD_c_checksumFlag: 201, ZSTD_c_dictIDFlag: 202, + ZSTD_c_nbWorkers: 400, ZSTD_c_jobSize: 401, ZSTD_c_overlapLog: 402, + ZSTD_d_windowLogMax: 100, ZSTD_CLEVEL_DEFAULT: 3, + ZSTD_error_no_error: 0, ZSTD_error_GENERIC: 1, ZSTD_error_prefix_unknown: 10, + ZSTD_error_version_unsupported: 12, ZSTD_error_frameParameter_unsupported: 14, + ZSTD_error_frameParameter_windowTooLarge: 16, ZSTD_error_corruption_detected: 20, + ZSTD_error_checksum_wrong: 22, ZSTD_error_literals_headerWrong: 24, + ZSTD_error_dictionary_corrupted: 30, ZSTD_error_dictionary_wrong: 32, + ZSTD_error_dictionaryCreation_failed: 34, ZSTD_error_parameter_unsupported: 40, + ZSTD_error_parameter_combination_unsupported: 41, ZSTD_error_parameter_outOfBound: 42, + ZSTD_error_tableLog_tooLarge: 44, ZSTD_error_maxSymbolValue_tooLarge: 46, + ZSTD_error_maxSymbolValue_tooSmall: 48, ZSTD_error_stabilityCondition_notRespected: 50, + ZSTD_error_stage_wrong: 60, ZSTD_error_init_missing: 62, + ZSTD_error_memory_allocation: 64, ZSTD_error_workSpace_tooSmall: 66, + ZSTD_error_dstSize_tooSmall: 70, ZSTD_error_srcSize_wrong: 72, + ZSTD_error_dstBuffer_null: 74, ZSTD_error_noForwardProgress_destFull: 80, + ZSTD_error_noForwardProgress_inputEmpty: 82, +}; + export const constants = Object.freeze({ + ...zstdConstants, Z_NO_FLUSH, Z_PARTIAL_FLUSH, Z_SYNC_FLUSH, @@ -1092,6 +1126,130 @@ export const Unzip = makeZlibWrapper(_Unzip); export const BrotliCompress = makeZlibWrapper(_BrotliCompress); export const BrotliDecompress = makeZlibWrapper(_BrotliDecompress); +const zstdCleanup = new FinalizationRegistry(zstd_stream_close); + +class Zstd extends ZlibBase { + constructor(opts, decompress) { + opts = opts || {}; + const params = []; + const seen = new Set(); + for (const key of Object.keys(opts.params || {})) { + const number = +key; + if (!Number.isInteger(number) || number < 0 || number > (decompress ? 100 : 402) || seen.has(number)) { + throw makeRangeError('ERR_ZSTD_INVALID_PARAM', `${key} is not a valid zstd parameter`); + } + const value = opts.params[key]; + if (typeof value !== 'number' && typeof value !== 'boolean') { + throw makeTypeError('ERR_INVALID_ARG_TYPE', + 'The "options.params[key]" argument must be of type number.' + invalidArgTypeHelper(value)); + } + if ((value | 0) !== -1) { + seen.add(number); + params.push([number, value | 0]); + } + } + const flush = opts.flush === undefined ? 0 : opts.flush; + const finishFlush = opts.finishFlush === undefined ? 2 : opts.finishFlush; + validateRangeInt(flush, 'options.flush', 0, 2); + validateRangeInt(finishFlush, 'options.finishFlush', 0, 2); + if (opts.chunkSize !== undefined) validateRangeInt(opts.chunkSize, 'options.chunkSize', Z_MIN_CHUNK, Infinity); + if (opts.maxOutputLength !== undefined) validateRangeInt(opts.maxOutputLength, 'options.maxOutputLength', 1, _getKMaxLength()); + const pledged = opts.pledgedSrcSize; + if (pledged !== undefined) { + if (typeof pledged !== 'number') throw makeTypeError('ERR_INVALID_ARG_TYPE', 'pledgedSrcSize must be a number'); + if (pledged < 0) throw makeRangeError('ERR_OUT_OF_RANGE', 'pledgedSrcSize must be non-negative'); + if (!Number.isSafeInteger(pledged)) throw makeRangeError('ERR_OUT_OF_RANGE', 'pledgedSrcSize must be a safe integer'); + } + let dictionary = opts.dictionary; + if (dictionary === undefined) dictionary = new Uint8Array(0); + else if (!isArrayBufferView(dictionary) && !(dictionary instanceof ArrayBuffer) && + !(typeof SharedArrayBuffer !== 'undefined' && dictionary instanceof SharedArrayBuffer)) { + throw makeTypeError('ERR_INVALID_ARG_TYPE', + 'The "options.dictionary" argument must be an instance of Buffer, TypedArray, DataView, or ArrayBuffer.' + invalidArgTypeHelper(dictionary)); + } + const rejectGarbage = opts.rejectGarbageAfterEnd; + if (rejectGarbage !== undefined && typeof rejectGarbage !== 'boolean') { + throw makeTypeError('ERR_INVALID_ARG_TYPE', + 'The "options.rejectGarbageAfterEnd" property must be of type boolean.' + invalidArgTypeHelper(rejectGarbage)); + } + const handle = zstd_stream_new(decompress, JSON.stringify(params), toUint8Array(toBuffer(dictionary)), pledged, + rejectGarbage === true); + if (handle == null) throw makeError('ERR_ZLIB_INITIALIZATION_FAILED', 'Setting parameter failed'); + try { super(opts, decompress ? 11 : 10); } + catch (error) { zstd_stream_close(handle); throw error; } + this._finishFlush = finishFlush; + this._flushFlag = flush; + this._setNativeHandle(handle); + zstdCleanup.register(this, handle, this); + } + + _closeNativeHandle() { + if (this._nativeHandle !== null) zstd_stream_close(this._nativeHandle); + zstdCleanup.unregister(this); + this._nativeHandle = null; + } + + reset() { + if (this._nativeHandle !== null && !zstd_stream_reset(this._nativeHandle)) { + this.destroy(makeError('ERR_ZLIB_INCOMPLETE_FRAME', 'Cannot reset an incomplete zstd frame')); + } + } + + flush(kind, callback) { + if (typeof kind === 'function') { callback = kind; kind = 1; } + if (kind === undefined) kind = 1; + validateRangeInt(kind, 'kind', 0, 2); + super.flush(kind, callback); + } + + _processChunk(chunk, flush, limit = _getKMaxLength()) { + const data = toUint8Array(toBuffer(chunk)); + this._bytesWritten += data.length; + const [bytes, message, errno] = zstd_stream_push(this._nativeHandle, data, flush, limit); + if (errno === -6) throw makeRangeError('ERR_BUFFER_TOO_LARGE', `Cannot create a Buffer larger than ${limit} bytes`); + if (errno === -7) throw makeTypeError('ERR_TRAILING_JUNK_AFTER_STREAM_END', message); + if (errno !== 0) { + const code = errno === -5 ? 'Z_BUF_ERROR' : + Object.keys(zstdConstants).find(key => key.startsWith('ZSTD_error_') && zstdConstants[key] === errno); + const error = makeError(code, message); + error.errno = errno; + throw error; + } + return bufferFromNativeBytes(bytes); + } + + _transform(chunk, encoding, callback) { + try { + const flush = chunk.length === 0 && this._pendingFlushes.length > 0 ? + this._pendingFlushes.shift() : this._flushFlag; + const output = this._processChunk(chunk, flush); + if (output.length) this.push(output); + queueMicrotask(callback); + } catch (error) { callback(error); } + } + + _flush(callback) { + try { + if (this._nativeHandle !== null) { + const output = this._processChunk(Buffer.alloc(0), this._finishFlush); + if (output.length) this.push(output); + } + this._closeHandle(); + callback(); + } catch (error) { + this._closeHandle(); + callback(error); + } + } +} + +export class ZstdCompress extends Zstd { + constructor(opts) { super(opts, false); } +} +export class ZstdDecompress extends Zstd { + constructor(opts) { super(opts, true); } +} + // ===== Factory functions ===== export function createGzip(opts) { return new _Gzip(opts); } @@ -1103,6 +1261,8 @@ export function createInflateRaw(opts) { return new _InflateRaw(opts); } export function createUnzip(opts) { return new _Unzip(opts); } export function createBrotliCompress(opts) { return new _BrotliCompress(opts); } export function createBrotliDecompress(opts) { return new _BrotliDecompress(opts); } +export function createZstdCompress(opts) { return new ZstdCompress(opts); } +export function createZstdDecompress(opts) { return new ZstdDecompress(opts); } // ===== Sync convenience functions ===== @@ -1230,6 +1390,27 @@ export function brotliDecompressSync(data, opts) { // ===== Async convenience functions ===== +function zstdSync(data, opts, engine) { + try { + const buffer = engine._processChunk(data, engine._finishFlush, opts?.maxOutputLength ?? _getKMaxLength()); + return opts?.info ? { buffer, engine } : buffer; + } finally { engine._closeHandle(); } +} + +export function zstdCompressSync(data, opts) { return zstdSync(data, opts, new ZstdCompress(opts)); } +export function zstdDecompressSync(data, opts) { return zstdSync(data, opts, new ZstdDecompress(opts)); } + +function zstdAsync(data, opts, callback, Engine) { + if (typeof opts === 'function') { callback = opts; opts = {}; } + // Construction and input validation throw synchronously; codec failures go + // to the callback. Do not turn invalid options into asynchronous errors. + const engine = new Engine(opts); + try { + const input = toBuffer(data); + asyncConvenience(() => zstdSync(input, opts, engine), input, opts, callback); + } catch (error) { engine._closeHandle(); throw error; } +} + function asyncConvenience(syncFn, data, opts, callback) { if (typeof opts === 'function') { callback = opts; @@ -1256,6 +1437,8 @@ export function inflateRaw(data, opts, callback) { asyncConvenience(inflateRawSy export function unzip(data, opts, callback) { asyncConvenience(unzipSync, data, opts, callback); } export function brotliCompress(data, opts, callback) { asyncConvenience(brotliCompressSync, data, opts, callback); } export function brotliDecompress(data, opts, callback) { asyncConvenience(brotliDecompressSync, data, opts, callback); } +export function zstdCompress(data, opts, callback) { zstdAsync(data, opts, callback, ZstdCompress); } +export function zstdDecompress(data, opts, callback) { zstdAsync(data, opts, callback, ZstdDecompress); } // ===== CRC32 ===== @@ -1295,6 +1478,8 @@ const _default = { Unzip, BrotliCompress, BrotliDecompress, + ZstdCompress, + ZstdDecompress, // Factory functions createGzip, @@ -1306,6 +1491,8 @@ const _default = { createUnzip, createBrotliCompress, createBrotliDecompress, + createZstdCompress, + createZstdDecompress, // Sync gzipSync, @@ -1317,6 +1504,8 @@ const _default = { unzipSync, brotliCompressSync, brotliDecompressSync, + zstdCompressSync, + zstdDecompressSync, // Async gzip, @@ -1328,6 +1517,8 @@ const _default = { unzip, brotliCompress, brotliDecompress, + zstdCompress, + zstdDecompress, // Constants (directly accessible like Node.js) Z_NO_FLUSH, diff --git a/crates/wasm-rquickjs/skeleton/src/builtin/zlib.rs b/crates/wasm-rquickjs/skeleton/src/builtin/zlib.rs index 4fcd90437..69559e461 100644 --- a/crates/wasm-rquickjs/skeleton/src/builtin/zlib.rs +++ b/crates/wasm-rquickjs/skeleton/src/builtin/zlib.rs @@ -5,6 +5,9 @@ use std::sync::{LazyLock, Mutex}; use flate2::{Compression, Decompress, FlushDecompress, Status}; +#[cfg(feature = "zstd")] +mod zstd; + // ===== Handle ID generation ===== static NEXT_HANDLE: AtomicU32 = AtomicU32::new(1); @@ -1287,6 +1290,77 @@ pub mod native_module { pub fn brotli_stream_bytes_written(id: u32) -> u32 { super::brotli_stream_bytes_written_impl(id) } + + #[rquickjs::function] + pub fn zstd_stream_new<'js>( + decompress: bool, + params: String, + dictionary: TypedArray<'js, u8>, + pledged: Option, + reject_garbage: bool, + ) -> Option { + #[cfg(feature = "zstd")] + { + // SAFETY: Codec initialization consumes the rooted dictionary without JS re-entry. + let dictionary = unsafe { dictionary.as_bytes() }.unwrap_or_default(); + super::zstd::new(decompress, ¶ms, dictionary, pledged, reject_garbage) + } + #[cfg(not(feature = "zstd"))] + { + let _ = (decompress, params, dictionary, pledged, reject_garbage); + None + } + } + + #[rquickjs::function] + pub fn zstd_stream_push<'js>( + ctx: Ctx<'js>, + id: u32, + data: TypedArray<'js, u8>, + flush: u8, + limit: u32, + ) -> rquickjs::Result> { + #[cfg(feature = "zstd")] + { + // SAFETY: Codec processing consumes the rooted input without JS re-entry. + let input = unsafe { data.as_bytes() }.unwrap_or_default(); + match super::zstd::push(id, input, flush, limit as usize) { + Ok(bytes) => Ok(List((Some(TypedArray::new(ctx, bytes)?), None, 0))), + Err((code, message)) => Ok(List((None, Some(message), code))), + } + } + #[cfg(not(feature = "zstd"))] + { + let _ = (ctx, id, data, flush, limit); + Ok(List((None, None, 0))) + } + } + + #[rquickjs::function] + pub fn zstd_stream_reset(id: u32) -> bool { + #[cfg(feature = "zstd")] + { + super::zstd::reset(id) + } + #[cfg(not(feature = "zstd"))] + { + let _ = id; + false + } + } + + #[rquickjs::function] + pub fn zstd_stream_close(id: u32) -> bool { + #[cfg(feature = "zstd")] + { + super::zstd::close(id) + } + #[cfg(not(feature = "zstd"))] + { + let _ = id; + false + } + } } pub const ZLIB_JS: &str = include_str!("zlib.js"); diff --git a/crates/wasm-rquickjs/skeleton/src/builtin/zlib/zstd.rs b/crates/wasm-rquickjs/skeleton/src/builtin/zlib/zstd.rs new file mode 100644 index 000000000..3f1bf007b --- /dev/null +++ b/crates/wasm-rquickjs/skeleton/src/builtin/zlib/zstd.rs @@ -0,0 +1,249 @@ +//! Stateful zstd backend. Every handle owns its own codec context. + +use std::collections::HashMap; +use std::sync::{LazyLock, Mutex}; +use zstd_safe::{ + CCtx, CParameter, DCtx, DParameter, InBuffer, OutBuffer, ResetDirective, Strategy, +}; + +enum Codec { + Compress(CCtx<'static>, Option), + Decompress(DCtx<'static>), +} + +struct Stream { + codec: Codec, + complete: bool, + emitted: bool, + input_size: u64, + pending: Vec, + garbage: bool, + reject_garbage: bool, +} + +static STREAMS: LazyLock>> = + LazyLock::new(|| Mutex::new(HashMap::new())); + +fn compression_parameter(key: u32, value: i32) -> Option { + Some(match key { + 100 => CParameter::CompressionLevel(value), + 101 => CParameter::WindowLog(value as u32), + 102 => CParameter::HashLog(value as u32), + 103 => CParameter::ChainLog(value as u32), + 104 => CParameter::SearchLog(value as u32), + 105 => CParameter::MinMatch(value as u32), + 106 => CParameter::TargetLength(value as u32), + 107 => CParameter::Strategy(match value { + 1 => Strategy::ZSTD_fast, + 2 => Strategy::ZSTD_dfast, + 3 => Strategy::ZSTD_greedy, + 4 => Strategy::ZSTD_lazy, + 5 => Strategy::ZSTD_lazy2, + 6 => Strategy::ZSTD_btlazy2, + 7 => Strategy::ZSTD_btopt, + 8 => Strategy::ZSTD_btultra, + 9 => Strategy::ZSTD_btultra2, + _ => return None, + }), + 160 => CParameter::EnableLongDistanceMatching(value != 0), + 161 => CParameter::LdmHashLog(value as u32), + 162 => CParameter::LdmMinMatch(value as u32), + 163 => CParameter::LdmBucketSizeLog(value as u32), + 164 => CParameter::LdmHashRateLog(value as u32), + 200 => CParameter::ContentSizeFlag(value != 0), + 201 => CParameter::ChecksumFlag(value != 0), + 202 => CParameter::DictIdFlag(value != 0), + 400 => CParameter::NbWorkers(value as u32), + 401 => CParameter::JobSize(value as u32), + 402 => CParameter::OverlapSizeLog(value as u32), + _ => return None, + }) +} + +pub(super) fn new( + decompress: bool, + params: &str, + dictionary: &[u8], + pledged: Option, + reject_garbage: bool, +) -> Option { + let params: Vec<(u32, i32)> = serde_json::from_str(params).ok()?; + let codec = if decompress { + let mut ctx = DCtx::create(); + ctx.load_dictionary(dictionary).ok()?; + for (key, value) in params { + if key != 100 { + return None; + } + ctx.set_parameter(DParameter::WindowLogMax(value as u32)) + .ok()?; + } + Codec::Decompress(ctx) + } else { + let mut ctx = CCtx::create(); + ctx.load_dictionary(dictionary).ok()?; + for (key, value) in params { + if key == 107 && value == 0 { + continue; + } + ctx.set_parameter(compression_parameter(key, value)?).ok()?; + } + let pledged = pledged.map(|v| v as u64); + ctx.set_pledged_src_size(pledged).ok()?; + Codec::Compress(ctx, pledged) + }; + let id = super::next_id(); + STREAMS.lock().unwrap().insert( + id, + Stream { + codec, + complete: false, + emitted: false, + input_size: 0, + pending: Vec::new(), + garbage: false, + reject_garbage, + }, + ); + Some(id) +} + +fn native_error(code: usize) -> (i32, String) { + ( + code.wrapping_neg() as i32, + zstd_safe::get_error_name(code).to_string(), + ) +} + +fn frame_prefix(bytes: &[u8]) -> bool { + let length = bytes.len().min(4); + bytes[..length] == [0x28, 0xb5, 0x2f, 0xfd][..length] + || (0x50..=0x5f).any(|first| bytes[..length] == [first, 0x2a, 0x4d, 0x18][..length]) +} + +pub(super) fn push( + id: u32, + bytes: &[u8], + flush: u8, + limit: usize, +) -> Result, (i32, String)> { + let mut streams = STREAMS.lock().unwrap(); + let stream = streams.get_mut(&id).ok_or_else(|| { + ( + 60, + "Operation not authorized at current processing stage".to_string(), + ) + })?; + if let Codec::Compress(_, pledged) = stream.codec { + if stream.complete && bytes.is_empty() { + return Ok(Vec::new()); + } + if stream.complete { + stream.input_size = 0; + } + stream.input_size += bytes.len() as u64; + // A single compressStream2(end) call infers the input size even when the + // caller supplied a pledge. Node validates that explicit contract too. + if flush == 2 && pledged.is_some_and(|size| size != stream.input_size) { + return Err((72, "Src size is incorrect".to_string())); + } + } + let mut data = std::mem::take(&mut stream.pending); + data.extend_from_slice(bytes); + let mut input = InBuffer::around(&data); + let mut result = Vec::new(); + loop { + if matches!(stream.codec, Codec::Decompress(_)) && stream.complete { + let remaining = &data[input.pos..]; + if stream.garbage || (!remaining.is_empty() && !frame_prefix(remaining)) { + stream.garbage = true; + if stream.reject_garbage { + return Err(( + -7, + "Trailing junk found after the end of the compressed stream".to_string(), + )); + } + break; + } + if remaining.len() < 4 { + if flush == 2 && !remaining.is_empty() && stream.reject_garbage { + return Err(( + -7, + "Trailing junk found after the end of the compressed stream".to_string(), + )); + } + stream.pending.extend_from_slice(remaining); + break; + } + } + let before = input.pos; + let mut chunk = vec![0; 16_384.min(limit.saturating_sub(result.len()).saturating_add(1))]; + let mut output = OutBuffer::around(&mut chunk[..]); + let remaining = match &mut stream.codec { + Codec::Compress(ctx, _) => { + let directive = match flush { + 1 => zstd_safe::zstd_sys::ZSTD_EndDirective::ZSTD_e_flush, + 2 => zstd_safe::zstd_sys::ZSTD_EndDirective::ZSTD_e_end, + _ => zstd_safe::zstd_sys::ZSTD_EndDirective::ZSTD_e_continue, + }; + ctx.compress_stream2(&mut output, &mut input, directive) + } + Codec::Decompress(ctx) => ctx.decompress_stream(&mut output, &mut input), + } + .map_err(native_error)?; + let written = output.pos(); + result.extend_from_slice(&chunk[..written]); + if result.len() > limit { + return Err((-6, "output exceeds maxOutputLength".to_string())); + } + match stream.codec { + Codec::Compress(_, _) => { + stream.emitted |= written > 0; + stream.complete = flush == 2 && remaining == 0; + if input.pos == data.len() && (flush == 0 || remaining == 0) { + break; + } + } + Codec::Decompress(_) => { + stream.complete = remaining == 0; + if input.pos == data.len() && written < chunk.len() { + if flush == 2 && !stream.complete { + return Err((-5, "unexpected end of file".to_string())); + } + break; + } + } + } + if input.pos == before && written == 0 { + break; + } + } + Ok(result) +} + +pub(super) fn reset(id: u32) -> bool { + let mut streams = STREAMS.lock().unwrap(); + let Some(stream) = streams.get_mut(&id) else { + return false; + }; + let result = match &mut stream.codec { + Codec::Compress(ctx, pledged) => { + if stream.emitted && !stream.complete { + return false; + } + ctx.reset(ResetDirective::SessionOnly) + .and_then(|_| ctx.set_pledged_src_size(*pledged)) + } + Codec::Decompress(ctx) => ctx.reset(ResetDirective::SessionOnly), + }; + stream.complete = false; + stream.emitted = false; + stream.input_size = 0; + stream.garbage = false; + stream.pending.clear(); + result.is_ok() +} + +pub(super) fn close(id: u32) -> bool { + STREAMS.lock().unwrap().remove(&id).is_some() +} diff --git a/examples/runtime/zlib/src/zlib.js b/examples/runtime/zlib/src/zlib.js index 450e76b93..aaf20a0db 100644 --- a/examples/runtime/zlib/src/zlib.js +++ b/examples/runtime/zlib/src/zlib.js @@ -1,4 +1,6 @@ import { Buffer } from 'node:buffer'; +import assert from 'node:assert/strict'; +import * as zlib from 'node:zlib'; import { brotliCompressSync, brotliDecompressSync, @@ -401,3 +403,96 @@ export async function testByteTransfer() { } return true; } + +export async function testZstd() { + const external = Buffer.from('KLUv/SAgAQEATm9kZSAyNiBleHRlcm5hbCB2ZWN0b3I6IDEzICsgMjk=', 'base64'); + assert.equal(zlib.zstdDecompressSync(external).toString(), 'Node 26 external vector: 13 + 29'); + for (const create of [zlib.createZstdCompress, zlib.createZstdDecompress]) { + for (const rejectGarbageAfterEnd of [1, 'true', null]) { + assert.throws(() => create({ rejectGarbageAfterEnd }), { + name: 'TypeError', code: 'ERR_INVALID_ARG_TYPE', + }); + } + } + const source = Buffer.from('Ξ© asymmetric compression: 13|29 '.repeat(3000)); + for (const input of [Buffer.alloc(0), source, new DataView(source.buffer, source.byteOffset + 7, 29)]) { + const bytes = Buffer.isBuffer(input) ? input : Buffer.from(input.buffer, input.byteOffset, input.byteLength); + const compressed = zlib.zstdCompressSync(input, { params: { [constants.ZSTD_c_checksumFlag]: true } }); + assert.deepEqual(zlib.zstdDecompressSync(compressed), bytes); + await new Promise((resolve, reject) => { + zlib.zstdCompress(input, (error, output) => { + if (error) return reject(error); + zlib.zstdDecompress(output, (error, result) => { + if (error) return reject(error); + try { assert.deepEqual(result, bytes); resolve(); } catch (error) { reject(error); } + }); + }); + }); + } + const compressed = zlib.zstdCompressSync(source); + const trailingJunkError = { name: 'TypeError', code: 'ERR_TRAILING_JUNK_AFTER_STREAM_END' }; + for (const trailing of [Buffer.from('junk'), compressed.subarray(0, 3)]) { + const withJunk = Buffer.concat([compressed, trailing]); + assert.deepEqual(zlib.zstdDecompressSync(withJunk), source); + assert.throws(() => zlib.zstdDecompressSync(withJunk, { rejectGarbageAfterEnd: true }), trailingJunkError); + await assert.rejects(new Promise((resolve, reject) => { + zlib.zstdDecompress(withJunk, { rejectGarbageAfterEnd: true }, (error, result) => { + if (error) reject(error); else resolve(result); + }); + }), trailingJunkError); + for (const rejectGarbageAfterEnd of [false, true]) { + const decoder = zlib.createZstdDecompress({ rejectGarbageAfterEnd }); + const chunks = []; + const done = new Promise((resolve, reject) => { + decoder.on('data', chunk => chunks.push(chunk)); + decoder.on('end', resolve); + decoder.on('error', reject); + }); + decoder.write(compressed); + decoder.end(trailing); + if (rejectGarbageAfterEnd) await assert.rejects(done, trailingJunkError); + else { + await done; + assert.deepEqual(Buffer.concat(chunks), source); + } + } + } + assert.throws(() => zlib.zstdDecompressSync(compressed.subarray(0, compressed.length - 1)), { + code: 'Z_BUF_ERROR', message: 'unexpected end of file', + }); + const partial = zlib.zstdDecompressSync(compressed.subarray(0, compressed.length - 1), { finishFlush: 1 }); + assert.deepEqual(partial, source.subarray(0, partial.length)); + assert.throws(() => zlib.zstdCompressSync(source, { pledgedSrcSize: source.length - 1 }), { + code: 'ZSTD_error_srcSize_wrong', errno: 72, + }); + assert.throws(() => zlib.zstdDecompressSync(compressed, { maxOutputLength: source.length - 1 }), { + code: 'ERR_BUFFER_TOO_LARGE', + }); + const info = zlib.zstdCompressSync(source, { info: true }); + assert.ok(info.engine instanceof zlib.ZstdCompress); + assert.deepEqual(zlib.zstdDecompressSync(info.buffer), source); + await streamRoundTrip(source, zlib.createZstdCompress(), zlib.createZstdDecompress()); + const decoder = zlib.createZstdDecompress({ chunkSize: 64 }); + const chunks = []; + const done = new Promise((resolve, reject) => { + decoder.on('data', chunk => chunks.push(chunk)); + decoder.on('end', resolve); + decoder.on('error', reject); + }); + for (const byte of Buffer.concat([external, compressed, external])) decoder.write(Buffer.from([byte])); + decoder.end(); + await done; + assert.deepEqual(Buffer.concat(chunks), Buffer.concat([ + Buffer.from('Node 26 external vector: 13 + 29'), source, Buffer.from('Node 26 external vector: 13 + 29'), + ])); + return true; +} + +export function testZstdDisabled() { + const source = Buffer.from('normal tier: gzip stays available, zstd does not'); + assert.deepEqual(gunzipSync(gzipSync(source)), source); + for (const operation of [zlib.zstdCompressSync, zlib.zstdDecompressSync]) { + assert.throws(() => operation(source), { code: 'ERR_ZLIB_INITIALIZATION_FAILED' }); + } + return true; +} diff --git a/examples/runtime/zlib/wit/zlib.wit b/examples/runtime/zlib/wit/zlib.wit index d426ee1f4..2e71bc869 100644 --- a/examples/runtime/zlib/wit/zlib.wit +++ b/examples/runtime/zlib/wit/zlib.wit @@ -2,4 +2,6 @@ package quickjs:zlib; world zlib { export test-byte-transfer: func() -> bool; + export test-zstd: func() -> bool; + export test-zstd-disabled: func() -> bool; } diff --git a/tests/goldenfiles/generated_types_zlib_exports.d.ts b/tests/goldenfiles/generated_types_zlib_exports.d.ts index c2b0130cc..9c73a5510 100644 --- a/tests/goldenfiles/generated_types_zlib_exports.d.ts +++ b/tests/goldenfiles/generated_types_zlib_exports.d.ts @@ -1,3 +1,5 @@ declare module 'zlib' { export function testByteTransfer(): boolean; + export function testZstd(): boolean; + export function testZstdDisabled(): boolean; } diff --git a/tests/node_compat/config.jsonc b/tests/node_compat/config.jsonc index e0675ffb3..76ae36001 100644 --- a/tests/node_compat/config.jsonc +++ b/tests/node_compat/config.jsonc @@ -4052,7 +4052,7 @@ } }, "parallel/test-worker-message-port-close-while-receiving.js": {}, - "parallel/test-zlib-zero-byte.js": { "category": "known-gap", "reason": "zlib zstd compression APIs (zstdCompress, ZstdCompress) are not implemented" }, + "parallel/test-zlib-zero-byte.js": {}, "parallel/test-async-hooks-vm-gc.js": {}, "parallel/test-finalization-registry-shutdown.js": {}, "parallel/test-heapdump-async-hooks-init-promise.js": { "category": "engine-difference", "reason": "v8.getHeapSnapshot is V8-specific and unavailable in QuickJS" }, @@ -4198,10 +4198,10 @@ } }, "parallel/test-zlib-flush-flags.js": {}, - "parallel/test-zlib-convenience-methods.js": { "category": "known-gap", "reason": "zlib zstd compression APIs (zstdCompress, ZstdCompress) are not implemented" }, + "parallel/test-zlib-convenience-methods.js": {}, "parallel/test-zlib-from-string.js": {}, "parallel/test-zlib-brotli-from-string.js": {}, - "parallel/test-zlib-empty-buffer.js": { "category": "known-gap", "reason": "zlib zstd compression APIs (zstdCompress, ZstdCompress) are not implemented" }, + "parallel/test-zlib-empty-buffer.js": {}, "parallel/test-zlib-deflate-constructors.js": {}, "parallel/test-zlib-not-string-or-buffer.js": {}, "parallel/test-zlib-sync-no-event.js": {}, @@ -4252,20 +4252,20 @@ "parallel/test-zlib-kmaxlength-rangeerror.js": {}, "parallel/test-zlib-maxOutputLength.js": {}, "parallel/test-zlib-params.js": {}, - "parallel/test-zlib-random-byte-pipes.js": { "category": "known-gap", "reason": "zlib zstd compression APIs (zstdCompress, ZstdCompress) are not implemented" }, + "parallel/test-zlib-random-byte-pipes.js": {}, "parallel/test-zlib-reset-before-write.js": {}, "parallel/test-zlib-truncated.js": { "split": true, "subtests": { - "block_00_value_as_truncated_input": { "category": "known-gap", "reason": "zlib zstd compression APIs (zstdCompress, ZstdCompress) are not implemented" }, - "block_01_mistaken_for_an_empty_truncated_frame": { "category": "known-gap", "reason": "zlib zstd compression APIs (zstdCompress, ZstdCompress) are not implemented" }, - "block_02_must_report_that_the_frame_is_incomplete": { "category": "known-gap", "reason": "zlib zstd compression APIs (zstdCompress, ZstdCompress) are not implemented" } + "block_00_value_as_truncated_input": {}, + "block_01_mistaken_for_an_empty_truncated_frame": {}, + "block_02_must_report_that_the_frame_is_incomplete": {} } }, "parallel/test-zlib-unused-weak.js": { "category": "node-internals", "reason": "asserts internal zlib native-handle weak-reference/external-memory behavior" }, "parallel/test-zlib-write-after-close.js": {}, "parallel/test-zlib-write-after-end.js": {}, - "parallel/test-zlib-write-after-flush.js": { "category": "known-gap", "reason": "zlib zstd compression APIs (zstdCompress, ZstdCompress) are not implemented" }, + "parallel/test-zlib-write-after-flush.js": {}, "parallel/test-zlib-close-after-error.js": { "category": "node-internals", "reason": "asserts private zlib stream _closed state after error" }, "parallel/test-zlib-close-in-ondata.js": {}, "parallel/test-zlib-destroy.js": { @@ -10665,8 +10665,8 @@ "parallel/test-zlib.js": { "split": true, "subtests": { - "block_00_block_00": { "category": "known-gap", "reason": "zlib zstd compression APIs (zstdCompress, ZstdCompress) are not implemented" }, - "block_01_block_01": { "category": "known-gap", "reason": "zlib zstd compression APIs (zstdCompress, ZstdCompress) are not implemented" } + "block_00_block_00": {}, + "block_01_block_01": {} } }, "sequential/test-async-wrap-getasyncid.js": { @@ -16835,8 +16835,8 @@ "parallel/test-zlib-decode-strings.js": { "category": "unevaluated", "reason": "newly discovered, not yet evaluated" }, "parallel/test-zlib-negative-zero.js": { "category": "unevaluated", "reason": "newly discovered, not yet evaluated" }, "parallel/test-zlib-reject-garbage-after-end.js": { - "category": "unevaluated", - "reason": "newly discovered, not yet evaluated", + "category": "known-gap", + "reason": "shared non-zstd rejectGarbageAfterEnd assertions fail before complete subtest qualification", "split": true, "subtests": { "test_00_zstd_decompresses_concatenated_frames_regardless_of_chunking": {}, @@ -17211,15 +17211,13 @@ "test_10_a_deflate_and_a_zstd_member_each_stream_back_through_content": {} } }, - "parallel/test-zlib-zstd-dictionary.js": { "category": "unevaluated", "reason": "newly discovered, not yet evaluated" }, - "parallel/test-zlib-zstd-flush.js": { "category": "unevaluated", "reason": "newly discovered, not yet evaluated" }, - "parallel/test-zlib-zstd-from-string.js": { "category": "unevaluated", "reason": "newly discovered, not yet evaluated" }, - "parallel/test-zlib-zstd-from-zstd.js": { "category": "unevaluated", "reason": "newly discovered, not yet evaluated" }, - "parallel/test-zlib-zstd-kmaxlength-rangeerror.js": { "category": "unevaluated", "reason": "newly discovered, not yet evaluated" }, - "parallel/test-zlib-zstd-pledged-src-size.js": { "category": "unevaluated", "reason": "newly discovered, not yet evaluated" }, + "parallel/test-zlib-zstd-dictionary.js": {}, + "parallel/test-zlib-zstd-flush.js": {}, + "parallel/test-zlib-zstd-from-string.js": {}, + "parallel/test-zlib-zstd-from-zstd.js": {}, + "parallel/test-zlib-zstd-kmaxlength-rangeerror.js": {}, + "parallel/test-zlib-zstd-pledged-src-size.js": {}, "parallel/test-zlib-zstd-reset-incomplete-frame.js": { - "category": "unevaluated", - "reason": "newly discovered, not yet evaluated", "split": true, "subtests": { "test_00_zstdcompress_reset_throws_when_an_incomplete_frame_has_emitt": {}, @@ -17230,8 +17228,6 @@ } }, "parallel/test-zlib-zstd-reset.js": { - "category": "unevaluated", - "reason": "newly discovered, not yet evaluated", "split": true, "subtests": { "test_00_zstdcompress_reset_preserves_its_initial_options": {}, @@ -17240,8 +17236,6 @@ } }, "parallel/test-zlib-zstd.js": { - "category": "unevaluated", - "reason": "newly discovered, not yet evaluated", "split": true, "subtests": { "block_00_block_00": {}, diff --git a/tests/node_compat/report.md b/tests/node_compat/report.md index 6f7382f6a..b3d182180 100644 --- a/tests/node_compat/report.md +++ b/tests/node_compat/report.md @@ -8,21 +8,21 @@ This report is generated from `config.jsonc` and the pinned vendored Node.js sou Primary compatibility is measured over the public API surface we can provide: CI-enforced passing (`runnable`) plus `known-gap`. WASI-impossible tests, engine differences, unevaluated tests, and Node.js-internals tests are acknowledged separately and excluded from the primary percentage. -**Primary compatibility (CI-enforced):** 3163/4461 (70.9%) +**Primary compatibility (CI-enforced):** 3190/4484 (71.1%) When comparing revisions, read the runnable count and secondary full-public percentage alongside the primary percentage. Reclassifying a test into an excluded category can increase the primary percentage without increasing runnable coverage. | Classification | Count | Primary % | Public inventory % | All listed % | |----------------|-------|-----------|--------------------|--------------| -| βœ… passing (runnable) | 3163 | 70.9% | 32.9% | 29.3% | -| 🧩 known gap | 1298 | 29.1% | 13.5% | 12.0% | +| βœ… passing (runnable) | 3190 | 71.1% | 33.2% | 29.6% | +| 🧩 known gap | 1294 | 28.9% | 13.5% | 12.0% | | 🚫 WASI-impossible (excluded) | 1148 | β€” | 11.9% | 10.6% | | βš™οΈ engine difference (excluded) | 167 | β€” | 1.7% | 1.5% | -| ❔ unevaluated (excluded) | 3841 | β€” | 39.9% | 35.6% | +| ❔ unevaluated (excluded) | 3818 | β€” | 39.7% | 35.4% | | πŸ”’ Node.js internals (excluded) | 1177 | β€” | β€” | 10.9% | | **Total** | **10794** | | | **100.0%** | -Secondary full-public compatibility, including public tests that are currently excluded from primary: **3163/9617 (32.9%)**. +Secondary full-public compatibility, including public tests that are currently excluded from primary: **3190/9617 (33.2%)**. ## Inventory by Module @@ -88,7 +88,7 @@ Secondary full-public compatibility, including public tests that are currently e | webstreams | 89 | 66 | 1 | 0 | 0 | 21 | 1 | 98.5% | 75.0% | | whatwg | 319 | 43 | 32 | 0 | 0 | 56 | 188 | 57.3% | 32.8% | | worker_threads | 202 | 25 | 29 | 127 | 0 | 13 | 8 | 46.3% | 12.9% | -| zlib | 324 | 45 | 15 | 0 | 0 | 260 | 4 | 75.0% | 14.1% | +| zlib | 324 | 72 | 11 | 0 | 0 | 237 | 4 | 86.7% | 22.5% | ## Split Test Summary @@ -1040,9 +1040,9 @@ Secondary full-public compatibility, including public tests that are currently e | `test-zlib-dictionary-fail.js` | 3 | 3 | 0 | 0 | 0 | 0 | 0 | | `test-zlib-failed-init.js` | 2 | 2 | 0 | 0 | 0 | 0 | 0 | | `test-zlib-invalid-input.js` | 2 | 0 | 2 | 0 | 0 | 0 | 0 | -| `test-zlib-reject-garbage-after-end.js` | 6 | 0 | 0 | 0 | 0 | 6 | 0 | +| `test-zlib-reject-garbage-after-end.js` | 6 | 0 | 6 | 0 | 0 | 0 | 0 | | `test-zlib-reset-incomplete-output.js` | 7 | 0 | 0 | 0 | 0 | 7 | 0 | -| `test-zlib-truncated.js` | 3 | 0 | 3 | 0 | 0 | 0 | 0 | +| `test-zlib-truncated.js` | 3 | 3 | 0 | 0 | 0 | 0 | 0 | | `test-zlib-type-error.js` | 4 | 0 | 0 | 0 | 0 | 4 | 0 | | `test-zlib-zero-windowBits.js` | 2 | 2 | 0 | 0 | 0 | 0 | 0 | | `test-zlib-zip-coverage.js` | 65 | 0 | 0 | 0 | 0 | 65 | 0 | @@ -1063,10 +1063,10 @@ Secondary full-public compatibility, including public tests that are currently e | `test-zlib-zip-writable.js` | 13 | 0 | 0 | 0 | 0 | 13 | 0 | | `test-zlib-zip-zip64.js` | 2 | 0 | 0 | 0 | 0 | 2 | 0 | | `test-zlib-zip.js` | 11 | 0 | 0 | 0 | 0 | 11 | 0 | -| `test-zlib-zstd-reset-incomplete-frame.js` | 5 | 0 | 0 | 0 | 0 | 5 | 0 | -| `test-zlib-zstd-reset.js` | 3 | 0 | 0 | 0 | 0 | 3 | 0 | -| `test-zlib-zstd.js` | 3 | 0 | 0 | 0 | 0 | 3 | 0 | -| `test-zlib.js` | 2 | 0 | 2 | 0 | 0 | 0 | 0 | +| `test-zlib-zstd-reset-incomplete-frame.js` | 5 | 5 | 0 | 0 | 0 | 0 | 0 | +| `test-zlib-zstd-reset.js` | 3 | 3 | 0 | 0 | 0 | 0 | 0 | +| `test-zlib-zstd.js` | 3 | 3 | 0 | 0 | 0 | 0 | 0 | +| `test-zlib.js` | 2 | 2 | 0 | 0 | 0 | 0 | 0 | | `test-async-wrap-getasyncid.js` | 18 | 0 | 0 | 0 | 0 | 0 | 18 | | `test-benchmark-node-bench-tools.js` | 16 | 0 | 0 | 0 | 0 | 16 | 0 | | `test-child-process-execsync.js` | 7 | 0 | 0 | 7 | 0 | 0 | 0 | @@ -1090,7 +1090,7 @@ Secondary full-public compatibility, including public tests that are currently e ## Classified Non-Runnable Tests -### known gap (1298) +### known gap (1294) | Reason | Count | Example entries | |--------|-------|-----------------| @@ -1113,7 +1113,6 @@ Secondary full-public compatibility, including public tests that are currently e | rooted symlink targets cannot be resolved inside a WASI preopen; the adapter rejects them at creation, while persistent relative symlinks are covered by runtime tests | 11 | `es-module/test-esm-preserve-symlinks-main.js`, `es-module/test-esm-preserve-symlinks.js`, `es-module/test-esm-symlink-main.js`, ... (+8) | | wasi:sockets UDP implementation hangs in wasmtime | 11 | `parallel/test-dgram-implicit-bind.js`, `parallel/test-dgram-multicast-set-interface.js#block_00_block_00`, `parallel/test-dgram-multicast-set-interface.js#block_02_block_02`, ... (+8) | | dgram multicast membership APIs are not implemented (ENOSYS) | 10 | `parallel/test-dgram-membership.js#block_02_addmembership_with_no_argument_should_throw`, `parallel/test-dgram-membership.js#block_03_dropmembership_with_no_argument_should_throw`, `parallel/test-dgram-membership.js#block_04_addmembership_with_invalid_multicast_address_should_throw`, ... (+7) | -| zlib zstd compression APIs (zstdCompress, ZstdCompress) are not implemented | 10 | `parallel/test-zlib-convenience-methods.js`, `parallel/test-zlib-empty-buffer.js`, `parallel/test-zlib-random-byte-pipes.js`, ... (+7) | | async_hooks not fully implemented | 9 | `parallel/test-async-hooks-destroy-on-gc.js`, `parallel/test-async-hooks-disable-during-promise.js`, `parallel/test-async-hooks-disable-gc-tracking.js`, ... (+6) | | net.js TCP implementation incomplete - needs event handling and API fixes | 9 | `parallel/test-net-connect-nodelay.js`, `parallel/test-net-connect-paused-connection.js`, `parallel/test-net-during-close.js`, ... (+6) | | spawn() AbortSignal handling is incomplete (exit code/signal/error semantics differ from Node) | 9 | `parallel/test-child-process-spawn-controller.js#block_00_block_00`, `parallel/test-child-process-spawn-controller.js#block_01_block_01`, `parallel/test-child-process-spawn-controller.js#block_02_block_02`, ... (+6) | @@ -1129,6 +1128,7 @@ Secondary full-public compatibility, including public tests that are currently e | inherited: common.canCreateSymLink shim always returns false, so symlink permission tests are skipped | 6 | `parallel/test-permission-fs-symlink-target-write.js#block_00_block_00`, `parallel/test-permission-fs-symlink-target-write.js#block_01_block_01`, `parallel/test-permission-fs-symlink.js#block_00_block_00`, ... (+3) | | inherited: perf_hooks createHistogram/monitorEventLoopDelay are not implemented | 6 | `parallel/test-perf-hooks-histogram.js#block_00_block_00`, `parallel/test-perf-hooks-histogram.js#block_01_block_01`, `parallel/test-perf-hooks-histogram.js#block_02_block_02`, ... (+3) | | same-process import.meta.resolve behavior is covered by runtime tests; remaining vendored failure requires child_process execPath emulation for --input-type/--import ESM CLI modes | 6 | `es-module/test-esm-import-meta-resolve.mjs#block_00_block_00`, `es-module/test-esm-import-meta-resolve.mjs#block_01_block_01`, `es-module/test-esm-import-meta-resolve.mjs#block_02_block_02`, ... (+3) | +| shared non-zstd rejectGarbageAfterEnd assertions fail before complete subtest qualification | 6 | `parallel/test-zlib-reject-garbage-after-end.js#test_00_zstd_decompresses_concatenated_frames_regardless_of_chunking`, `parallel/test-zlib-reject-garbage-after-end.js#test_01_zstd_trailing_junk_handling_is_independent_of_chunking`, `parallel/test-zlib-reject-garbage-after-end.js#test_02_zstd_handles_incomplete_trailing_frame_identifiers_as_junk`, ... (+3) | | the test's meaningful body requires rooted symlink targets; common.canCreateSymLink skips it under the supported relative-only WASI boundary | 6 | `parallel/test-fs-options-immutable.js#block_00_block_00`, `parallel/test-fs-options-immutable.js#block_01_block_01`, `parallel/test-fs-options-immutable.js#block_02_block_02`, ... (+3) | | common-shim spawnPromisified child emulation does not support --experimental-webstorage/--localstorage-file flags | 5 | `parallel/test-webstorage.js#test_00_storage_instances_cannot_be_created_in_userland`, `parallel/test-webstorage.js#test_02_sessionstorage_is_not_persisted`, `parallel/test-webstorage.js#test_05_localstorage_is_not_persisted_if_it_is_unused`, ... (+2) | | inherited: buffer.transcode and ICU transcoding are not implemented | 5 | `parallel/test-icu-transcode.js#block_00_block_00`, `parallel/test-icu-transcode.js#block_01_block_01`, `parallel/test-icu-transcode.js#block_02_test_that_uint8array_arguments_are_okay`, ... (+2) | @@ -1956,11 +1956,11 @@ Secondary full-public compatibility, including public tests that are currently e | vm.Script.createCachedData relies on V8 code cache internals unavailable in QuickJS | 1 | `parallel/test-vm-createcacheddata.js` | | vm.SourceTextModule dynamic import referrer realm semantics depend on Node VM realm behavior not modeled by the QuickJS host | 1 | `parallel/test-vm-module-referrer-realm.mjs` | -### unevaluated (3841) +### unevaluated (3818) | Reason | Count | Example entries | |--------|-------|-----------------| -| newly discovered, not yet evaluated | 3639 | `es-module/test-cjs-defer-static-import-eval.mjs`, `es-module/test-defer-import-builtin-module.mjs`, `es-module/test-defer-import-eval-with-tla.mjs`, ... (+3636) | +| newly discovered, not yet evaluated | 3616 | `es-module/test-cjs-defer-static-import-eval.mjs`, `es-module/test-defer-import-builtin-module.mjs`, `es-module/test-defer-import-eval-with-tla.mjs`, ... (+3613) | | newly discovered subtest, not yet evaluated | 202 | `es-module/test-esm-json.mjs#test_01_should_load_json_with_import_calls`, `parallel/test-assert-deep.js#test_01_loose_deepequal`, `parallel/test-assert-deep.js#test_08_deepstrictequal_handles_shared_expected_array_elements_after`, ... (+199) | ### Node.js internals (1177) diff --git a/tests/runtime/zlib.rs b/tests/runtime/zlib.rs index f77918f8f..d0cc66850 100644 --- a/tests/runtime/zlib.rs +++ b/tests/runtime/zlib.rs @@ -22,3 +22,28 @@ async fn zlib_byte_transfer(#[tagged_as("zlib")] compiled: &CompiledTest) -> any assert_eq!(result?, Some(Val::Bool(true))); Ok(()) } + +#[test] +async fn zlib_zstd(#[tagged_as("zlib")] compiled: &CompiledTest) -> anyhow::Result<()> { + let (result, output) = + invoke_and_capture_output(compiled.wasm_path(), None, "test-zstd", &[]).await; + println!("Output:\n{}", output); + assert_eq!(result?, Some(Val::Bool(true))); + Ok(()) +} + +#[test] +async fn zlib_zstd_disabled() -> anyhow::Result<()> { + // Keep this component's Cargo output separate from the full-tier dependency. + let compiled = CompiledTest::new_with_features( + Utf8Path::new("examples/runtime/zlib"), + false, + FeatureCombination::Normal, + ) + .await?; + let (result, output) = + invoke_and_capture_output(compiled.wasm_path(), None, "test-zstd-disabled", &[]).await; + println!("Output:\n{}", output); + assert_eq!(result?, Some(Val::Bool(true))); + Ok(()) +} From 167e3aba3061f79492bd42f8123cd78958a74635 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?D=C3=A1vid=20Istv=C3=A1n=20B=C3=ADr=C3=B3?= Date: Tue, 24 Nov 2026 19:59:40 +0000 Subject: [PATCH 2/5] Fix zstd frame accounting [skip ci] --- .../skeleton/src/builtin/zlib/zstd.rs | 32 ++++++++++----- examples/runtime/zlib/src/zlib.js | 40 +++++++++++++++++++ 2 files changed, 61 insertions(+), 11 deletions(-) diff --git a/crates/wasm-rquickjs/skeleton/src/builtin/zlib/zstd.rs b/crates/wasm-rquickjs/skeleton/src/builtin/zlib/zstd.rs index 3f1bf007b..cbd4d01b4 100644 --- a/crates/wasm-rquickjs/skeleton/src/builtin/zlib/zstd.rs +++ b/crates/wasm-rquickjs/skeleton/src/builtin/zlib/zstd.rs @@ -15,7 +15,7 @@ struct Stream { codec: Codec, complete: bool, emitted: bool, - input_size: u64, + input_size: Option, pending: Vec, garbage: bool, reject_garbage: bool, @@ -92,6 +92,10 @@ pub(super) fn new( ctx.set_pledged_src_size(pledged).ok()?; Codec::Compress(ctx, pledged) }; + let input_size = match &codec { + Codec::Compress(_, pledged) => pledged.map(|_| 0), + Codec::Decompress(_) => None, + }; let id = super::next_id(); STREAMS.lock().unwrap().insert( id, @@ -99,7 +103,7 @@ pub(super) fn new( codec, complete: false, emitted: false, - input_size: 0, + input_size, pending: Vec::new(), garbage: false, reject_garbage, @@ -138,14 +142,13 @@ pub(super) fn push( if stream.complete && bytes.is_empty() { return Ok(Vec::new()); } - if stream.complete { - stream.input_size = 0; - } - stream.input_size += bytes.len() as u64; - // A single compressStream2(end) call infers the input size even when the - // caller supplied a pledge. Node validates that explicit contract too. - if flush == 2 && pledged.is_some_and(|size| size != stream.input_size) { - return Err((72, "Src size is incorrect".to_string())); + if let Some(input_size) = &mut stream.input_size { + *input_size += bytes.len() as u64; + // A single compressStream2(end) call infers the input size even when + // the caller supplied a pledge. Validate only the active pledge. + if flush == 2 && Some(*input_size) != pledged { + return Err((72, "Src size is incorrect".to_string())); + } } } let mut data = std::mem::take(&mut stream.pending); @@ -200,6 +203,10 @@ pub(super) fn push( Codec::Compress(_, _) => { stream.emitted |= written > 0; stream.complete = flush == 2 && remaining == 0; + if stream.complete { + stream.emitted = false; + stream.input_size = None; + } if input.pos == data.len() && (flush == 0 || remaining == 0) { break; } @@ -238,7 +245,10 @@ pub(super) fn reset(id: u32) -> bool { }; stream.complete = false; stream.emitted = false; - stream.input_size = 0; + stream.input_size = match stream.codec { + Codec::Compress(_, pledged) => pledged.map(|_| 0), + Codec::Decompress(_) => None, + }; stream.garbage = false; stream.pending.clear(); result.is_ok() diff --git a/examples/runtime/zlib/src/zlib.js b/examples/runtime/zlib/src/zlib.js index aaf20a0db..714252b9d 100644 --- a/examples/runtime/zlib/src/zlib.js +++ b/examples/runtime/zlib/src/zlib.js @@ -485,6 +485,46 @@ export async function testZstd() { assert.deepEqual(Buffer.concat(chunks), Buffer.concat([ Buffer.from('Node 26 external vector: 13 + 29'), source, Buffer.from('Node 26 external vector: 13 + 29'), ])); + const frameResults = []; + for (const scenario of ['buffered-reset', 'next-frame', 'reset-pledge']) { + const compressor = zlib.createZstdCompress( + scenario === 'buffered-reset' ? {} : { pledgedSrcSize: 5 }, + ); + const chunks = []; + const completed = new Promise(resolve => { + compressor.on('data', chunk => chunks.push(chunk)); + compressor.on('end', () => resolve(null)); + compressor.on('error', resolve); + }); + const write = data => new Promise((resolve, reject) => { + compressor.write(data, error => error ? reject(error) : resolve()); + }); + try { + await write('hello'); + await new Promise((resolve, reject) => { + compressor.flush(constants.ZSTD_e_end, error => error ? reject(error) : resolve()); + }); + if (scenario === 'buffered-reset') { + const completedChunks = chunks.length; + await write('x'); + assert.equal(chunks.length, completedChunks); + compressor.reset(); + compressor.end('world'); + } else { + if (scenario === 'reset-pledge') compressor.reset(); + compressor.end('x'); + } + const error = await completed; + if (error) throw error; + frameResults.push(zlib.zstdDecompressSync(Buffer.concat(chunks)).toString()); + } catch (error) { + compressor.destroy(); + frameResults.push({ code: error.code, errno: error.errno }); + } + } + assert.deepEqual(frameResults, [ + 'helloworld', 'hellox', { code: 'ZSTD_error_srcSize_wrong', errno: 72 }, + ]); return true; } From 56480bc6a9fcdb7643d45fea20cf263c7f52b30b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?D=C3=A1vid=20Istv=C3=A1n=20B=C3=ADr=C3=B3?= Date: Thu, 26 Nov 2026 10:00:20 +0000 Subject: [PATCH 3/5] Fix zstd stream contracts --- README.md | 3 + .../skeleton/src/builtin/zlib.js | 194 ++++++++++-- .../skeleton/src/builtin/zlib.rs | 21 +- .../skeleton/src/builtin/zlib/zstd.rs | 298 +++++++++++------- .../src/module-resolution.js | 6 +- examples/runtime/zlib/src/zlib.js | 245 ++++++++++++++ examples/runtime/zlib/wit/zlib.wit | 1 + .../generated_types_zlib_exports.d.ts | 1 + tests/node_compat/config.jsonc | 2 +- tests/node_compat/report.md | 14 +- tests/runtime/zlib.rs | 9 + 11 files changed, 624 insertions(+), 170 deletions(-) diff --git a/README.md b/README.md index c9782d81e..571b2b88b 100644 --- a/README.md +++ b/README.md @@ -1264,6 +1264,9 @@ throws immediately. Environment-data APIs are unavailable. - `crc32`, `constants`, `codes` - Zstandard requires the optional `zstd` feature (included in the full tiers). It uses the reference zstd codec with worker threads disabled for WASI; `normal-p3` does not include that codec. + The APIs remain discoverable without the feature, but calls throw `ERR_ZLIB_INITIALIZATION_FAILED`. + This generic initialization error can also indicate invalid codec parameters; check the build's + enabled features before diagnosing a parameter failure. diff --git a/crates/wasm-rquickjs/skeleton/src/builtin/zlib.js b/crates/wasm-rquickjs/skeleton/src/builtin/zlib.js index 44518b2ca..db3063fd4 100644 --- a/crates/wasm-rquickjs/skeleton/src/builtin/zlib.js +++ b/crates/wasm-rquickjs/skeleton/src/builtin/zlib.js @@ -1,5 +1,5 @@ // node:zlib implementation -import { Transform } from 'node:stream'; +import { Transform, addAbortSignal } from 'node:stream'; import { Buffer } from 'node:buffer'; import bufferModule from 'node:buffer'; import { @@ -50,6 +50,8 @@ const getDataViewByteLength = Function.prototype.call.bind( const getArrayBufferDetached = Function.prototype.call.bind( Object.getOwnPropertyDescriptor(ArrayBuffer.prototype, 'detached').get, ); +const registerFinalizer = Function.prototype.call.bind(FinalizationRegistry.prototype.register); +const unregisterFinalizer = Function.prototype.call.bind(FinalizationRegistry.prototype.unregister); function bufferFromNativeBytes(bytes) { setPrototypeOf(bytes, BufferPrototype); @@ -1141,7 +1143,7 @@ class Zstd extends ZlibBase { const value = opts.params[key]; if (typeof value !== 'number' && typeof value !== 'boolean') { throw makeTypeError('ERR_INVALID_ARG_TYPE', - 'The "options.params[key]" argument must be of type number.' + invalidArgTypeHelper(value)); + 'The "options.params[key]" property must be of type number.' + invalidArgTypeHelper(value)); } if ((value | 0) !== -1) { seen.add(number); @@ -1152,7 +1154,8 @@ class Zstd extends ZlibBase { const finishFlush = opts.finishFlush === undefined ? 2 : opts.finishFlush; validateRangeInt(flush, 'options.flush', 0, 2); validateRangeInt(finishFlush, 'options.finishFlush', 0, 2); - if (opts.chunkSize !== undefined) validateRangeInt(opts.chunkSize, 'options.chunkSize', Z_MIN_CHUNK, Infinity); + const chunkSize = opts.chunkSize; + if (chunkSize !== undefined) validateRangeInt(chunkSize, 'options.chunkSize', Z_MIN_CHUNK, _getKMaxLength()); if (opts.maxOutputLength !== undefined) validateRangeInt(opts.maxOutputLength, 'options.maxOutputLength', 1, _getKMaxLength()); const pledged = opts.pledgedSrcSize; if (pledged !== undefined) { @@ -1165,27 +1168,44 @@ class Zstd extends ZlibBase { else if (!isArrayBufferView(dictionary) && !(dictionary instanceof ArrayBuffer) && !(typeof SharedArrayBuffer !== 'undefined' && dictionary instanceof SharedArrayBuffer)) { throw makeTypeError('ERR_INVALID_ARG_TYPE', - 'The "options.dictionary" argument must be an instance of Buffer, TypedArray, DataView, or ArrayBuffer.' + invalidArgTypeHelper(dictionary)); + 'The "options.dictionary" property must be an instance of Buffer, TypedArray, DataView, or ArrayBuffer.' + invalidArgTypeHelper(dictionary)); + } + if (typeof SharedArrayBuffer !== 'undefined' && dictionary instanceof SharedArrayBuffer) { + dictionary = new Uint8Array(dictionary); } const rejectGarbage = opts.rejectGarbageAfterEnd; if (rejectGarbage !== undefined && typeof rejectGarbage !== 'boolean') { throw makeTypeError('ERR_INVALID_ARG_TYPE', 'The "options.rejectGarbageAfterEnd" property must be of type boolean.' + invalidArgTypeHelper(rejectGarbage)); } + const signal = opts.signal; const handle = zstd_stream_new(decompress, JSON.stringify(params), toUint8Array(toBuffer(dictionary)), pledged, rejectGarbage === true); if (handle == null) throw makeError('ERR_ZLIB_INITIALIZATION_FAILED', 'Setting parameter failed'); - try { super(opts, decompress ? 11 : 10); } + // An already-aborted signal may destroy the stream during super(). Attach + // it only after the native owner and its finalizer are installed. + try { super(signal ? { ...opts, signal: undefined } : opts, decompress ? 11 : 10); } catch (error) { zstd_stream_close(handle); throw error; } - this._finishFlush = finishFlush; - this._flushFlag = flush; - this._setNativeHandle(handle); - zstdCleanup.register(this, handle, this); + try { + this._finishFlush = finishFlush; + this._flushFlag = flush; + this._chunkSize = chunkSize ?? Z_DEFAULT_CHUNK; + this._zstdResume = null; + this._setNativeHandle(handle); + registerFinalizer(zstdCleanup, this, handle, this); + if (signal) addAbortSignal(signal, this); + } + catch (error) { + zstd_stream_close(handle); + unregisterFinalizer(zstdCleanup, this); + this._nativeHandle = null; + throw error; + } } _closeNativeHandle() { if (this._nativeHandle !== null) zstd_stream_close(this._nativeHandle); - zstdCleanup.unregister(this); + unregisterFinalizer(zstdCleanup, this); this._nativeHandle = null; } @@ -1202,44 +1222,89 @@ class Zstd extends ZlibBase { super.flush(kind, callback); } - _processChunk(chunk, flush, limit = _getKMaxLength()) { - const data = toUint8Array(toBuffer(chunk)); - this._bytesWritten += data.length; - const [bytes, message, errno] = zstd_stream_push(this._nativeHandle, data, flush, limit); - if (errno === -6) throw makeRangeError('ERR_BUFFER_TOO_LARGE', `Cannot create a Buffer larger than ${limit} bytes`); + _processStep(data, flush, capacity) { + const [bytes, message, errno, consumed, done] = zstd_stream_push(this._nativeHandle, data, flush, capacity); if (errno === -7) throw makeTypeError('ERR_TRAILING_JUNK_AFTER_STREAM_END', message); if (errno !== 0) { const code = errno === -5 ? 'Z_BUF_ERROR' : - Object.keys(zstdConstants).find(key => key.startsWith('ZSTD_error_') && zstdConstants[key] === errno); + Object.keys(zstdConstants).find(key => stringStartsWith(key, 'ZSTD_error_') && zstdConstants[key] === errno); const error = makeError(code, message); error.errno = errno; throw error; } - return bufferFromNativeBytes(bytes); + return [bufferFromNativeBytes(bytes), consumed, done]; + } + + _processChunk(chunk, flush, limit = _getKMaxLength()) { + const data = toUint8Array(toBuffer(chunk)); + this._bytesWritten += data.length; + const chunks = []; + let offset = 0, total = 0, done; + do { + const [output, consumed, complete] = this._processStep( + data.subarray(offset), flush, Math.min(this._chunkSize, limit - total + 1)); + offset += consumed; + total += output.length; + if (total > limit) throw makeRangeError('ERR_BUFFER_TOO_LARGE', `Cannot create a Buffer larger than ${limit} bytes`); + if (output.length) chunks.push(output); + done = complete; + } while (!done); + return Buffer.concat(chunks, total); + } + + _processStream(chunk, flush, callback) { + const data = toUint8Array(toBuffer(chunk)); + this._bytesWritten += data.length; + let offset = 0; + const resume = error => { + if (error) { callback(error); return; } + try { + while (this._nativeHandle !== null) { + const [output, consumed, done] = this._processStep(data.subarray(offset), flush, this._chunkSize); + offset += consumed; + const ready = output.length === 0 || this.push(output); + if (this._nativeHandle === null) break; + if (!ready) { + this._zstdResume = done ? error => queueMicrotask(() => callback(error)) : resume; + return; + } + if (done) break; + } + queueMicrotask(callback); + } catch (error) { callback(error); } + }; + resume(); + } + + _read(size) { + const resume = this._zstdResume; + this._zstdResume = null; + if (resume) resume(); + super._read(size); } _transform(chunk, encoding, callback) { try { const flush = chunk.length === 0 && this._pendingFlushes.length > 0 ? this._pendingFlushes.shift() : this._flushFlag; - const output = this._processChunk(chunk, flush); - if (output.length) this.push(output); - queueMicrotask(callback); + this._processStream(typeof chunk === 'string' ? Buffer.from(chunk, encoding) : chunk, flush, callback); } catch (error) { callback(error); } } _flush(callback) { - try { - if (this._nativeHandle !== null) { - const output = this._processChunk(Buffer.alloc(0), this._finishFlush); - if (output.length) this.push(output); - } - this._closeHandle(); - callback(); - } catch (error) { + if (this._nativeHandle === null) { callback(); return; } + this._processStream(Buffer.alloc(0), this._finishFlush, error => { this._closeHandle(); callback(error); - } + }); + } + + _destroy(error, callback) { + this._closeHandle(); + const resume = this._zstdResume; + this._zstdResume = null; + if (resume) resume(error || makeError('ERR_STREAM_DESTROYED', 'Cannot call write after a stream was destroyed')); + callback(error); } } @@ -1397,18 +1462,79 @@ function zstdSync(data, opts, engine) { } finally { engine._closeHandle(); } } -export function zstdCompressSync(data, opts) { return zstdSync(data, opts, new ZstdCompress(opts)); } -export function zstdDecompressSync(data, opts) { return zstdSync(data, opts, new ZstdDecompress(opts)); } +// Node's synchronous convenience calls complete even with an aborted signal. +export function zstdCompressSync(data, opts) { + return zstdSync(data, opts, new ZstdCompress({ ...opts, signal: undefined })); +} +export function zstdDecompressSync(data, opts) { + return zstdSync(data, opts, new ZstdDecompress({ ...opts, signal: undefined })); +} function zstdAsync(data, opts, callback, Engine) { if (typeof opts === 'function') { callback = opts; opts = {}; } + if (Engine === ZstdCompress && opts?.pledgedSrcSize === undefined) { + let pledgedSrcSize; + if (typeof data === 'string') { + const encoding = opts?.defaultEncoding; + // Match Node's default pledge only when the UTF-8 size is known to be + // the encoded size. Other encodings retain ordinary streaming behavior. + if (encoding == null || encoding === 'utf8' || encoding === 'utf-8') { + pledgedSrcSize = Buffer.byteLength(data); + } + } else if (isArrayBufferView(data) || data instanceof ArrayBuffer || + (typeof SharedArrayBuffer !== 'undefined' && data instanceof SharedArrayBuffer)) { + pledgedSrcSize = data.byteLength; + } + if (pledgedSrcSize !== undefined) opts = { ...opts, pledgedSrcSize }; + } // Construction and input validation throw synchronously; codec failures go // to the callback. Do not turn invalid options into asynchronous errors. const engine = new Engine(opts); + let input; + try { + input = typeof data === 'string' ? Buffer.from(data, engine._writableState.defaultEncoding) : toBuffer(data); + if (typeof callback !== 'function') { + throw makeTypeError('ERR_INVALID_ARG_TYPE', + 'The "callback" argument must be of type function. Received ' + (callback === undefined ? 'undefined' : typeof callback)); + } + } catch (error) { + // This private engine cannot deliver errors after validation throws. + engine.on('error', () => {}); + engine.destroy(); + throw error; + } + const chunks = []; + const limit = opts?.maxOutputLength ?? _getKMaxLength(); + let total = 0, settled = false; + const done = (error, result) => { + if (settled) return; + settled = true; + chunks.length = 0; + engine.destroy(); + callback(error, result); + }; + engine.once('error', done); + engine.on('data', chunk => { + total += chunk.length; + if (total > limit) { + engine.destroy(makeRangeError('ERR_BUFFER_TOO_LARGE', `Cannot create a Buffer larger than ${limit} bytes`)); + } else { + chunks.push(chunk); + } + }); + engine.once('end', () => { + let buffer; + try { buffer = Buffer.concat(chunks, total); } + catch (error) { done(error); return; } + done(null, opts?.info ? { buffer, engine } : buffer); + }); try { - const input = toBuffer(data); - asyncConvenience(() => zstdSync(input, opts, engine), input, opts, callback); - } catch (error) { engine._closeHandle(); throw error; } + engine.end(input); + } catch (error) { + engine._closeHandle(); + engine.destroy(); + throw error; + } } function asyncConvenience(syncFn, data, opts, callback) { diff --git a/crates/wasm-rquickjs/skeleton/src/builtin/zlib.rs b/crates/wasm-rquickjs/skeleton/src/builtin/zlib.rs index 69559e461..86f13336a 100644 --- a/crates/wasm-rquickjs/skeleton/src/builtin/zlib.rs +++ b/crates/wasm-rquickjs/skeleton/src/builtin/zlib.rs @@ -1120,6 +1120,7 @@ pub mod native_module { use rquickjs::{Ctx, TypedArray}; type DecompressOutcome<'js> = List<(Option>, Option, i32)>; + type ZstdOutcome<'js> = List<(Option>, Option, i32, u32, bool)>; // ===== One-shot functions ===== @@ -1318,21 +1319,27 @@ pub mod native_module { id: u32, data: TypedArray<'js, u8>, flush: u8, - limit: u32, - ) -> rquickjs::Result> { + capacity: u32, + ) -> rquickjs::Result> { #[cfg(feature = "zstd")] { // SAFETY: Codec processing consumes the rooted input without JS re-entry. let input = unsafe { data.as_bytes() }.unwrap_or_default(); - match super::zstd::push(id, input, flush, limit as usize) { - Ok(bytes) => Ok(List((Some(TypedArray::new(ctx, bytes)?), None, 0))), - Err((code, message)) => Ok(List((None, Some(message), code))), + match super::zstd::push(id, input, flush, capacity as usize) { + Ok((bytes, consumed, done)) => Ok(List(( + Some(TypedArray::new(ctx, bytes)?), + None, + 0, + consumed as u32, + done, + ))), + Err((code, message)) => Ok(List((None, Some(message), code, 0, true))), } } #[cfg(not(feature = "zstd"))] { - let _ = (ctx, id, data, flush, limit); - Ok(List((None, None, 0))) + let _ = (ctx, id, data, flush, capacity); + Ok(List((None, None, 0, 0, true))) } } diff --git a/crates/wasm-rquickjs/skeleton/src/builtin/zlib/zstd.rs b/crates/wasm-rquickjs/skeleton/src/builtin/zlib/zstd.rs index cbd4d01b4..e79ad84f6 100644 --- a/crates/wasm-rquickjs/skeleton/src/builtin/zlib/zstd.rs +++ b/crates/wasm-rquickjs/skeleton/src/builtin/zlib/zstd.rs @@ -1,16 +1,30 @@ //! Stateful zstd backend. Every handle owns its own codec context. +use std::borrow::Cow; use std::collections::HashMap; +use std::ptr::NonNull; use std::sync::{LazyLock, Mutex}; -use zstd_safe::{ - CCtx, CParameter, DCtx, DParameter, InBuffer, OutBuffer, ResetDirective, Strategy, -}; +use zstd_safe::{DCtx, DParameter, InBuffer, OutBuffer, ResetDirective, zstd_sys}; enum Codec { - Compress(CCtx<'static>, Option), + // zstd-safe 7's boolean LDM setter cannot represent ZSTD_ps_disable. + // Own the C context directly so libzstd receives the original integers. + Compress(NonNull, Option), Decompress(DCtx<'static>), } +// SAFETY: Each context has one owner; STREAMS serializes every access. +unsafe impl Send for Codec {} + +impl Drop for Codec { + fn drop(&mut self) { + if let Self::Compress(ctx, _) = self { + // SAFETY: This is the sole owner, and no codec call can outlive it. + unsafe { zstd_sys::ZSTD_freeCCtx(ctx.as_ptr()) }; + } + } +} + struct Stream { codec: Codec, complete: bool, @@ -24,38 +38,28 @@ struct Stream { static STREAMS: LazyLock>> = LazyLock::new(|| Mutex::new(HashMap::new())); -fn compression_parameter(key: u32, value: i32) -> Option { +fn compression_parameter(key: u32) -> Option { + use zstd_sys::ZSTD_cParameter::*; Some(match key { - 100 => CParameter::CompressionLevel(value), - 101 => CParameter::WindowLog(value as u32), - 102 => CParameter::HashLog(value as u32), - 103 => CParameter::ChainLog(value as u32), - 104 => CParameter::SearchLog(value as u32), - 105 => CParameter::MinMatch(value as u32), - 106 => CParameter::TargetLength(value as u32), - 107 => CParameter::Strategy(match value { - 1 => Strategy::ZSTD_fast, - 2 => Strategy::ZSTD_dfast, - 3 => Strategy::ZSTD_greedy, - 4 => Strategy::ZSTD_lazy, - 5 => Strategy::ZSTD_lazy2, - 6 => Strategy::ZSTD_btlazy2, - 7 => Strategy::ZSTD_btopt, - 8 => Strategy::ZSTD_btultra, - 9 => Strategy::ZSTD_btultra2, - _ => return None, - }), - 160 => CParameter::EnableLongDistanceMatching(value != 0), - 161 => CParameter::LdmHashLog(value as u32), - 162 => CParameter::LdmMinMatch(value as u32), - 163 => CParameter::LdmBucketSizeLog(value as u32), - 164 => CParameter::LdmHashRateLog(value as u32), - 200 => CParameter::ContentSizeFlag(value != 0), - 201 => CParameter::ChecksumFlag(value != 0), - 202 => CParameter::DictIdFlag(value != 0), - 400 => CParameter::NbWorkers(value as u32), - 401 => CParameter::JobSize(value as u32), - 402 => CParameter::OverlapSizeLog(value as u32), + 100 => ZSTD_c_compressionLevel, + 101 => ZSTD_c_windowLog, + 102 => ZSTD_c_hashLog, + 103 => ZSTD_c_chainLog, + 104 => ZSTD_c_searchLog, + 105 => ZSTD_c_minMatch, + 106 => ZSTD_c_targetLength, + 107 => ZSTD_c_strategy, + 160 => ZSTD_c_enableLongDistanceMatching, + 161 => ZSTD_c_ldmHashLog, + 162 => ZSTD_c_ldmMinMatch, + 163 => ZSTD_c_ldmBucketSizeLog, + 164 => ZSTD_c_ldmHashRateLog, + 200 => ZSTD_c_contentSizeFlag, + 201 => ZSTD_c_checksumFlag, + 202 => ZSTD_c_dictIDFlag, + 400 => ZSTD_c_nbWorkers, + 401 => ZSTD_c_jobSize, + 402 => ZSTD_c_overlapLog, _ => return None, }) } @@ -80,17 +84,37 @@ pub(super) fn new( } Codec::Decompress(ctx) } else { - let mut ctx = CCtx::create(); - ctx.load_dictionary(dictionary).ok()?; + // SAFETY: The new context is immediately placed in its owning Codec, + // including on every initialization failure below. + let ctx = NonNull::new(unsafe { zstd_sys::ZSTD_createCCtx() })?; + let pledged = pledged.map(|v| v as u64); + let codec = Codec::Compress(ctx, pledged); for (key, value) in params { - if key == 107 && value == 0 { - continue; - } - ctx.set_parameter(compression_parameter(key, value)?).ok()?; + let parameter = compression_parameter(key)?; + // SAFETY: The context is owned, and the parameter enum is valid. + native_result(unsafe { + zstd_sys::ZSTD_CCtx_setParameter(ctx.as_ptr(), parameter, value) + }) + .ok()?; } - let pledged = pledged.map(|v| v as u64); - ctx.set_pledged_src_size(pledged).ok()?; - Codec::Compress(ctx, pledged) + // SAFETY: loadDictionary copies the borrowed bytes; neither call retains + // a Rust reference. Parameters precede dictionary table construction. + native_result(unsafe { + zstd_sys::ZSTD_CCtx_loadDictionary( + ctx.as_ptr(), + dictionary.as_ptr().cast(), + dictionary.len(), + ) + }) + .ok()?; + native_result(unsafe { + zstd_sys::ZSTD_CCtx_setPledgedSrcSize( + ctx.as_ptr(), + pledged.unwrap_or(zstd_safe::CONTENTSIZE_UNKNOWN), + ) + }) + .ok()?; + codec }; let input_size = match &codec { Codec::Compress(_, pledged) => pledged.map(|_| 0), @@ -119,6 +143,15 @@ fn native_error(code: usize) -> (i32, String) { ) } +fn native_result(code: usize) -> Result { + // SAFETY: ZSTD_isError only inspects the numeric result. + if unsafe { zstd_sys::ZSTD_isError(code) } != 0 { + Err(native_error(code)) + } else { + Ok(code) + } +} + fn frame_prefix(bytes: &[u8]) -> bool { let length = bytes.len().min(4); bytes[..length] == [0x28, 0xb5, 0x2f, 0xfd][..length] @@ -129,8 +162,8 @@ pub(super) fn push( id: u32, bytes: &[u8], flush: u8, - limit: usize, -) -> Result, (i32, String)> { + capacity: usize, +) -> Result<(Vec, usize, bool), (i32, String)> { let mut streams = STREAMS.lock().unwrap(); let stream = streams.get_mut(&id).ok_or_else(|| { ( @@ -140,92 +173,107 @@ pub(super) fn push( })?; if let Codec::Compress(_, pledged) = stream.codec { if stream.complete && bytes.is_empty() { - return Ok(Vec::new()); + return Ok((Vec::new(), 0, true)); } - if let Some(input_size) = &mut stream.input_size { - *input_size += bytes.len() as u64; + if let Some(input_size) = stream.input_size { // A single compressStream2(end) call infers the input size even when // the caller supplied a pledge. Validate only the active pledge. - if flush == 2 && Some(*input_size) != pledged { + if flush == 2 && Some(input_size + bytes.len() as u64) != pledged { return Err((72, "Src size is incorrect".to_string())); } } } - let mut data = std::mem::take(&mut stream.pending); - data.extend_from_slice(bytes); + let prefix = std::mem::take(&mut stream.pending); + let prefix_len = prefix.len(); + let data = if prefix.is_empty() { + Cow::Borrowed(bytes) + } else { + let mut data = prefix; + data.extend_from_slice(bytes); + Cow::Owned(data) + }; let mut input = InBuffer::around(&data); - let mut result = Vec::new(); - loop { - if matches!(stream.codec, Codec::Decompress(_)) && stream.complete { - let remaining = &data[input.pos..]; - if stream.garbage || (!remaining.is_empty() && !frame_prefix(remaining)) { - stream.garbage = true; - if stream.reject_garbage { - return Err(( - -7, - "Trailing junk found after the end of the compressed stream".to_string(), - )); - } - break; - } - if remaining.len() < 4 { - if flush == 2 && !remaining.is_empty() && stream.reject_garbage { - return Err(( - -7, - "Trailing junk found after the end of the compressed stream".to_string(), - )); - } - stream.pending.extend_from_slice(remaining); - break; + if matches!(stream.codec, Codec::Decompress(_)) && stream.complete { + if stream.garbage || (!data.is_empty() && !frame_prefix(&data)) { + stream.garbage = true; + if stream.reject_garbage { + return Err(( + -7, + "Trailing junk found after the end of the compressed stream".to_string(), + )); } + return Ok((Vec::new(), bytes.len(), true)); } - let before = input.pos; - let mut chunk = vec![0; 16_384.min(limit.saturating_sub(result.len()).saturating_add(1))]; - let mut output = OutBuffer::around(&mut chunk[..]); - let remaining = match &mut stream.codec { - Codec::Compress(ctx, _) => { - let directive = match flush { - 1 => zstd_safe::zstd_sys::ZSTD_EndDirective::ZSTD_e_flush, - 2 => zstd_safe::zstd_sys::ZSTD_EndDirective::ZSTD_e_end, - _ => zstd_safe::zstd_sys::ZSTD_EndDirective::ZSTD_e_continue, - }; - ctx.compress_stream2(&mut output, &mut input, directive) + if data.len() < 4 { + if flush == 2 && !data.is_empty() && stream.reject_garbage { + return Err(( + -7, + "Trailing junk found after the end of the compressed stream".to_string(), + )); } - Codec::Decompress(ctx) => ctx.decompress_stream(&mut output, &mut input), + stream.pending.extend_from_slice(&data); + return Ok((Vec::new(), bytes.len(), true)); } - .map_err(native_error)?; - let written = output.pos(); - result.extend_from_slice(&chunk[..written]); - if result.len() > limit { - return Err((-6, "output exceeds maxOutputLength".to_string())); + } + // One call produces at most capacity bytes. The caller retains unconsumed + // input and resumes only when the readable side has demand. + let mut chunk = vec![0; capacity]; + let (remaining, written) = match &mut stream.codec { + Codec::Compress(ctx, _) => { + let directive = match flush { + 1 => zstd_sys::ZSTD_EndDirective::ZSTD_e_flush, + 2 => zstd_sys::ZSTD_EndDirective::ZSTD_e_end, + _ => zstd_sys::ZSTD_EndDirective::ZSTD_e_continue, + }; + let mut raw_input = zstd_sys::ZSTD_inBuffer { + src: data.as_ptr().cast(), + size: data.len(), + pos: 0, + }; + let mut output = zstd_sys::ZSTD_outBuffer { + dst: chunk.as_mut_ptr().cast(), + size: chunk.len(), + pos: 0, + }; + // SAFETY: Both buffers stay alive for this synchronous call, + // and the exclusively owned context retains neither pointer. + let remaining = native_result(unsafe { + zstd_sys::ZSTD_compressStream2(ctx.as_ptr(), &mut output, &mut raw_input, directive) + })?; + input.pos = raw_input.pos; + (remaining, output.pos) } - match stream.codec { - Codec::Compress(_, _) => { - stream.emitted |= written > 0; - stream.complete = flush == 2 && remaining == 0; - if stream.complete { - stream.emitted = false; - stream.input_size = None; - } - if input.pos == data.len() && (flush == 0 || remaining == 0) { - break; - } + Codec::Decompress(ctx) => { + let mut output = OutBuffer::around(&mut chunk[..]); + let remaining = ctx + .decompress_stream(&mut output, &mut input) + .map_err(native_error)?; + (remaining, output.pos()) + } + }; + let done = match stream.codec { + Codec::Compress(_, _) => { + if let Some(size) = &mut stream.input_size { + *size += input.pos as u64; } - Codec::Decompress(_) => { - stream.complete = remaining == 0; - if input.pos == data.len() && written < chunk.len() { - if flush == 2 && !stream.complete { - return Err((-5, "unexpected end of file".to_string())); - } - break; - } + stream.emitted |= written > 0; + stream.complete = flush == 2 && remaining == 0; + if stream.complete { + stream.emitted = false; + stream.input_size = None; } + input.pos == data.len() && (flush == 0 || remaining == 0) } - if input.pos == before && written == 0 { - break; + Codec::Decompress(_) => { + stream.complete = remaining == 0; + if input.pos == data.len() && written < capacity && flush == 2 && !stream.complete { + return Err((-5, "unexpected end of file".to_string())); + } + input.pos == data.len() && (written < capacity || stream.complete) } - } - Ok(result) + }; + chunk.truncate(written); + Ok((chunk, input.pos.saturating_sub(prefix_len), done)) } pub(super) fn reset(id: u32) -> bool { @@ -238,10 +286,24 @@ pub(super) fn reset(id: u32) -> bool { if stream.emitted && !stream.complete { return false; } - ctx.reset(ResetDirective::SessionOnly) - .and_then(|_| ctx.set_pledged_src_size(*pledged)) + // SAFETY: Session reset and pledge update use the exclusively owned context. + native_result(unsafe { + zstd_sys::ZSTD_CCtx_reset( + ctx.as_ptr(), + zstd_sys::ZSTD_ResetDirective::ZSTD_reset_session_only, + ) + }) + .and_then(|_| { + native_result(unsafe { + zstd_sys::ZSTD_CCtx_setPledgedSrcSize( + ctx.as_ptr(), + pledged.unwrap_or(zstd_safe::CONTENTSIZE_UNKNOWN), + ) + }) + }) + .map_err(|_| ()) } - Codec::Decompress(ctx) => ctx.reset(ResetDirective::SessionOnly), + Codec::Decompress(ctx) => ctx.reset(ResetDirective::SessionOnly).map_err(|_| ()), }; stream.complete = false; stream.emitted = false; diff --git a/examples/runtime/module-resolution/src/module-resolution.js b/examples/runtime/module-resolution/src/module-resolution.js index 3dd3892b5..18e8b383f 100644 --- a/examples/runtime/module-resolution/src/module-resolution.js +++ b/examples/runtime/module-resolution/src/module-resolution.js @@ -43,13 +43,13 @@ export async function testBuiltinDiscovery(testCase) { for (const id of ['node:test', 'node:sqlite']) { assert.strictEqual(get(id), require(id), id); } - // Actual package capability probes: keep absent SEA/zstd capabilities - // absent, so callers can take their ordinary-runtime/uncompressed path. + // Package probes retain the absent SEA fallback and discover the same + // supported codec APIs as the ordinary zlib module. assert.strictEqual(get('node:sea'), undefined); assert.strictEqual(get('node:sea')?.isSea() ?? false, false); const zlib = get('node:zlib'); assert.strictEqual(zlib, require('zlib')); - assert.strictEqual(zlib.zstdCompressSync, undefined); + assert.strictEqual(typeof zlib.zstdCompressSync, 'function'); assert.strictEqual(typeof zlib.gzipSync, 'function'); } else if (testCase === 1) { const originalLoad = module._load; diff --git a/examples/runtime/zlib/src/zlib.js b/examples/runtime/zlib/src/zlib.js index 714252b9d..d93af44a2 100644 --- a/examples/runtime/zlib/src/zlib.js +++ b/examples/runtime/zlib/src/zlib.js @@ -1,5 +1,6 @@ import { Buffer } from 'node:buffer'; import assert from 'node:assert/strict'; +import { getEventListeners } from 'node:events'; import * as zlib from 'node:zlib'; import { brotliCompressSync, @@ -528,6 +529,250 @@ export async function testZstd() { return true; } +export async function testZstdContracts() { + const failures = []; + for (const [name, check] of [ + ['callback source pledge', async () => { + const bytes = Buffer.from('hΓ©llo wΓΆrld πŸš€ '.repeat(1000)); + const padded = Buffer.concat([Buffer.alloc(7), bytes, Buffer.alloc(11)]); + const mismatches = []; + for (const [input, options, normalized] of [ + ['', {}, Buffer.alloc(0)], + ['hello', {}, Buffer.from('hello')], + [bytes.toString(), {}, bytes], + [new DataView(padded.buffer, padded.byteOffset + 7, bytes.length), {}, bytes], + [Buffer.alloc(131073, 65), { chunkSize: 64 }, Buffer.alloc(131073, 65)], + [bytes.toString(), { defaultEncoding: 'utf-8' }, bytes], + ]) { + const opts = { ...options, params: { [zlib.constants.ZSTD_c_compressionLevel]: 9 } }; + const compressed = await new Promise((resolve, reject) => zlib.zstdCompress(input, opts, + (error, output) => error ? reject(error) : resolve(output))); + const expected = zlib.zstdCompressSync(normalized, opts); + console.log(`pledge ${normalized.length}: ${compressed.toString('hex')} sync: ${expected.toString('hex')}`); + if (!compressed.equals(expected)) mismatches.push(`${typeof input}/${normalized.length}`); + assert.equal(opts.pledgedSrcSize, undefined); + } + const latin1 = await new Promise((resolve, reject) => zlib.zstdCompress('Γ©', + { defaultEncoding: 'latin1', params: { [zlib.constants.ZSTD_c_compressionLevel]: 9 } }, + (error, output) => error ? reject(error) : resolve(output))); + // Node deliberately leaves non-UTF-8 strings unpledged; their frame is + // not byte-identical to synchronous compression of the encoded bytes. + console.log(`latin1 unpledged: ${latin1.toString('hex')}`); + assert.equal(latin1[4] & 0xe0, 0); + assert.deepEqual(zlib.zstdDecompressSync(latin1), Buffer.from([0xe9])); + const mismatch = await new Promise(resolve => zlib.zstdCompress(Buffer.from('hello'), + { pledgedSrcSize: 1 }, error => resolve(error))); + assert.equal(mismatch?.code, 'ZSTD_error_srcSize_wrong'); + assert.equal(mismatch?.errno, 72); + assert.deepEqual(mismatches, []); + }], + ['constructor option ownership', async () => { + let reads = 0; + const compressor = zlib.createZstdCompress({ + get chunkSize() { + if (++reads > 2) throw new Error('unowned third chunkSize read'); + return 64; + }, + }); + await streamRoundTrip(Buffer.from('constructor ownership 13|29'), compressor, zlib.createZstdDecompress()); + assert.throws(() => zlib.createZstdCompress({ signal: {} }), { code: 'ERR_INVALID_ARG_TYPE' }); + }], + ['error intrinsic capture', async () => { + const original = String.prototype.startsWith; + try { + String.prototype.startsWith = () => { throw new Error('mutable startsWith'); }; + assert.throws(() => zlib.zstdDecompressSync(Buffer.from([1, 2, 3, 4])), + { code: 'ZSTD_error_prefix_unknown', errno: 10 }); + } finally { String.prototype.startsWith = original; } + }], + ['callback encoding', async () => { + for (const pledgedSrcSize of [undefined, 1]) { + const compressed = await new Promise((resolve, reject) => { + zlib.zstdCompress('Γ©', { defaultEncoding: 'latin1', pledgedSrcSize }, + (error, result) => error ? reject(error) : resolve(result)); + }); + assert.deepEqual(zlib.zstdDecompressSync(compressed), Buffer.from([0xe9])); + } + }], + ['shared dictionaries', async () => { + const shared = new SharedArrayBuffer(128); + const dictionary = Buffer.from('dictionary asymmetric 13|29 '.repeat(3)); + new Uint8Array(shared).set(dictionary, 7); + const source = Buffer.from('dictionary asymmetric 13|29 '.repeat(100)); + for (const value of [shared, new Uint8Array(shared, 7, dictionary.length), + new DataView(shared, 7, dictionary.length)]) { + const compressed = zlib.zstdCompressSync(source, { dictionary: value }); + assert.deepEqual(zlib.zstdDecompressSync(compressed, { dictionary: value }), source); + await streamRoundTrip(source, zlib.createZstdCompress({ dictionary: value }), + zlib.createZstdDecompress({ dictionary: value })); + } + }], + ['numeric parameters', async () => { + for (const value of [-2, 3, 100]) { + assert.throws(() => zlib.createZstdCompress({ params: { 160: value } }), + { code: 'ERR_ZLIB_INITIALIZATION_FAILED' }); + } + const source = Buffer.from('numeric control 13|29'); + for (const value of [0, 1, 2]) { + assert.deepEqual(zlib.zstdDecompressSync(zlib.zstdCompressSync(source, { params: { 160: value } })), source); + } + for (const key of [200, 201, 202]) { + const enabled = zlib.zstdCompressSync(source, { params: { [key]: 1 } }); + for (const value of [-2, 2, 3, 100]) { + assert.deepEqual(zlib.zstdCompressSync(source, { params: { [key]: value } }), enabled); + } + } + }], + ['stream backpressure', async () => { + assert.throws(() => zlib.createZstdDecompress({ chunkSize: Number.MAX_SAFE_INTEGER + 1 }), + { code: 'ERR_OUT_OF_RANGE' }); + const source = Buffer.alloc(1024 * 1024, 0x61); + const decoder = zlib.createZstdDecompress({ chunkSize: 64, readableHighWaterMark: 64 }); + const chunks = []; + let written = false; + const done = new Promise((resolve, reject) => { + decoder.on('error', reject); + decoder.on('end', resolve); + }); + decoder.write(zlib.zstdCompressSync(source), error => { + if (error) decoder.destroy(error); + written = true; + }); + await new Promise(resolve => setTimeout(resolve, 0)); + const buffered = decoder.readableLength; + const writeCompleted = written; + decoder.on('data', chunk => chunks.push(chunk)); + decoder.end(); + await done; + assert.deepEqual(Buffer.concat(chunks), source); + assert.equal(writeCompleted, false); + assert.ok(buffered <= 64, `paused decoder buffered ${buffered} bytes`); + assert.ok(chunks.every(chunk => chunk.length <= 64), 'output exceeds chunkSize'); + + const random = Buffer.alloc(300000); + let seed = 0x12345678; + for (let i = 0; i < random.length; i++) { + seed ^= seed << 13; seed ^= seed >>> 17; seed ^= seed << 5; + random[i] = seed & 255; + } + const encoder = zlib.createZstdCompress({ chunkSize: 64, readableHighWaterMark: 64 }); + const encoded = []; + const encodedDone = new Promise((resolve, reject) => { + encoder.on('error', reject); encoder.on('end', resolve); + }); + encoder.write(random); + encoder.end(); + await new Promise(resolve => setTimeout(resolve, 0)); + const encodedBuffered = encoder.readableLength; + encoder.on('data', chunk => encoded.push(chunk)); + await encodedDone; + assert.ok(encodedBuffered <= 64, `paused encoder buffered ${encodedBuffered} bytes`); + assert.ok(encoded.every(chunk => chunk.length <= 64), 'encoded output exceeds chunkSize'); + assert.deepEqual(zlib.zstdDecompressSync(Buffer.concat(encoded)), random); + + const frame = zlib.zstdCompressSync(source); + assert.deepEqual(zlib.zstdDecompressSync(frame, { chunkSize: 64, maxOutputLength: source.length }), source); + assert.throws(() => zlib.zstdDecompressSync(frame, { chunkSize: 64, maxOutputLength: source.length - 1 }), + { code: 'ERR_BUFFER_TOO_LARGE' }); + }], + ['paused stream destruction', async () => { + const decoder = zlib.createZstdDecompress({ chunkSize: 64, readableHighWaterMark: 64 }); + const failure = new Error('cancel paused decoder'); + let callbacks = 0; + const closed = new Promise(resolve => decoder.on('close', resolve)); + decoder.on('error', error => assert.equal(error, failure)); + decoder.write(zlib.zstdCompressSync(Buffer.alloc(1024 * 1024)), () => callbacks++); + await new Promise(resolve => setTimeout(resolve, 0)); + decoder.destroy(failure); + await closed; + await new Promise(resolve => setTimeout(resolve, 0)); + assert.equal(decoder.destroyed, true); + assert.ok(callbacks <= 1); + }], + ['stream string encodings', async () => { + const source = Buffer.from('base64 decoder control 13|29'); + const frame = zlib.zstdCompressSync(source); + for (const [decode, input, encoding, defaultEncoding, expected] of [ + [false, 'Γ©', 'latin1', undefined, Buffer.from([0xe9])], + [false, 'Γ©', undefined, 'latin1', Buffer.from([0xe9])], + [true, frame.toString('base64'), 'base64', undefined, source], + ]) { + const engine = decode ? zlib.createZstdDecompress({ decodeStrings: false }) : + zlib.createZstdCompress({ decodeStrings: false, defaultEncoding }); + const chunks = []; + const done = new Promise((resolve, reject) => { + engine.on('error', reject); engine.on('end', resolve); + }); + engine.on('data', chunk => chunks.push(chunk)); + engine.end(input, encoding); + await done; + const output = Buffer.concat(chunks); + assert.deepEqual(decode ? output : zlib.zstdDecompressSync(output), expected); + } + }], + ['finalizer method capture', async () => { + const { register, unregister } = FinalizationRegistry.prototype; + try { + FinalizationRegistry.prototype.register = () => { throw new Error('mutable register'); }; + FinalizationRegistry.prototype.unregister = () => { throw new Error('mutable unregister'); }; + const source = Buffer.from('captured cleanup methods 13|29'); + assert.deepEqual(zlib.zstdDecompressSync(zlib.zstdCompressSync(source)), source); + await streamRoundTrip(source, zlib.createZstdCompress(), zlib.createZstdDecompress()); + } finally { + FinalizationRegistry.prototype.register = register; + FinalizationRegistry.prototype.unregister = unregister; + } + }], + ['callback cancellation and completion', async () => { + const source = Buffer.from('callback lifecycle control 13|29'); + const frame = zlib.zstdCompressSync(source); + const aborted = new AbortController(); + aborted.abort(); + for (const create of [zlib.createZstdCompress, zlib.createZstdDecompress]) { + const engine = create({ signal: aborted.signal }); + const closed = new Promise(resolve => engine.on('close', resolve)); + const error = await new Promise(resolve => engine.on('error', resolve)); + await closed; + assert.equal(error.code, 'ABORT_ERR'); + } + assert.deepEqual(zlib.zstdDecompressSync(zlib.zstdCompressSync(source, + { signal: aborted.signal }), { signal: aborted.signal }), source); + for (const [operation, input] of [[zlib.zstdCompress, source], [zlib.zstdDecompress, frame]]) { + for (const initiallyAborted of [false, true]) { + const controller = new AbortController(); + if (initiallyAborted) controller.abort(); + let callbacks = 0; + const done = new Promise(resolve => operation(input, { signal: controller.signal }, error => { + callbacks++; resolve(error); + })); + if (!initiallyAborted) controller.abort(); + assert.equal((await done)?.code, 'ABORT_ERR'); + await new Promise(resolve => setTimeout(resolve, 0)); + assert.equal(callbacks, 1); + assert.equal(getEventListeners(controller.signal, 'abort').length, 0); + } + const controller = new AbortController(); + const result = await new Promise((resolve, reject) => operation(input, + { signal: controller.signal, info: true }, (error, value) => error ? reject(error) : resolve(value))); + assert.ok(Buffer.isBuffer(result.buffer)); + assert.deepEqual(operation === zlib.zstdCompress ? zlib.zstdDecompressSync(result.buffer) : result.buffer, source); + await new Promise(resolve => setTimeout(resolve, 0)); + assert.equal(getEventListeners(controller.signal, 'abort').length, 0); + } + const error = await new Promise(resolve => zlib.zstdDecompress(frame, + { maxOutputLength: source.length - 1 }, error => resolve(error))); + assert.equal(error?.code, 'ERR_BUFFER_TOO_LARGE'); + const invalid = await new Promise(resolve => zlib.zstdDecompress(Buffer.from([1, 2]), error => resolve(error))); + assert.ok(invalid); + }], + ]) { + try { await check(); console.log(`${name}: PASS`); } + catch (error) { failures.push(name); console.log(`${name}: FAIL ${error.message}`); } + } + assert.deepEqual(failures, []); + return true; +} + export function testZstdDisabled() { const source = Buffer.from('normal tier: gzip stays available, zstd does not'); assert.deepEqual(gunzipSync(gzipSync(source)), source); diff --git a/examples/runtime/zlib/wit/zlib.wit b/examples/runtime/zlib/wit/zlib.wit index 2e71bc869..1fe357d79 100644 --- a/examples/runtime/zlib/wit/zlib.wit +++ b/examples/runtime/zlib/wit/zlib.wit @@ -3,5 +3,6 @@ package quickjs:zlib; world zlib { export test-byte-transfer: func() -> bool; export test-zstd: func() -> bool; + export test-zstd-contracts: func() -> bool; export test-zstd-disabled: func() -> bool; } diff --git a/tests/goldenfiles/generated_types_zlib_exports.d.ts b/tests/goldenfiles/generated_types_zlib_exports.d.ts index 9c73a5510..32e7e71bb 100644 --- a/tests/goldenfiles/generated_types_zlib_exports.d.ts +++ b/tests/goldenfiles/generated_types_zlib_exports.d.ts @@ -1,5 +1,6 @@ declare module 'zlib' { export function testByteTransfer(): boolean; export function testZstd(): boolean; + export function testZstdContracts(): boolean; export function testZstdDisabled(): boolean; } diff --git a/tests/node_compat/config.jsonc b/tests/node_compat/config.jsonc index 76ae36001..90e819818 100644 --- a/tests/node_compat/config.jsonc +++ b/tests/node_compat/config.jsonc @@ -16832,7 +16832,7 @@ "test_01_brotlidecompress_reset_preserves_its_dictionary": {} } }, - "parallel/test-zlib-decode-strings.js": { "category": "unevaluated", "reason": "newly discovered, not yet evaluated" }, + "parallel/test-zlib-decode-strings.js": {}, "parallel/test-zlib-negative-zero.js": { "category": "unevaluated", "reason": "newly discovered, not yet evaluated" }, "parallel/test-zlib-reject-garbage-after-end.js": { "category": "known-gap", diff --git a/tests/node_compat/report.md b/tests/node_compat/report.md index b3d182180..317fcfcaf 100644 --- a/tests/node_compat/report.md +++ b/tests/node_compat/report.md @@ -8,21 +8,21 @@ This report is generated from `config.jsonc` and the pinned vendored Node.js sou Primary compatibility is measured over the public API surface we can provide: CI-enforced passing (`runnable`) plus `known-gap`. WASI-impossible tests, engine differences, unevaluated tests, and Node.js-internals tests are acknowledged separately and excluded from the primary percentage. -**Primary compatibility (CI-enforced):** 3190/4484 (71.1%) +**Primary compatibility (CI-enforced):** 3191/4485 (71.1%) When comparing revisions, read the runnable count and secondary full-public percentage alongside the primary percentage. Reclassifying a test into an excluded category can increase the primary percentage without increasing runnable coverage. | Classification | Count | Primary % | Public inventory % | All listed % | |----------------|-------|-----------|--------------------|--------------| -| βœ… passing (runnable) | 3190 | 71.1% | 33.2% | 29.6% | +| βœ… passing (runnable) | 3191 | 71.1% | 33.2% | 29.6% | | 🧩 known gap | 1294 | 28.9% | 13.5% | 12.0% | | 🚫 WASI-impossible (excluded) | 1148 | β€” | 11.9% | 10.6% | | βš™οΈ engine difference (excluded) | 167 | β€” | 1.7% | 1.5% | -| ❔ unevaluated (excluded) | 3818 | β€” | 39.7% | 35.4% | +| ❔ unevaluated (excluded) | 3817 | β€” | 39.7% | 35.4% | | πŸ”’ Node.js internals (excluded) | 1177 | β€” | β€” | 10.9% | | **Total** | **10794** | | | **100.0%** | -Secondary full-public compatibility, including public tests that are currently excluded from primary: **3190/9617 (33.2%)**. +Secondary full-public compatibility, including public tests that are currently excluded from primary: **3191/9617 (33.2%)**. ## Inventory by Module @@ -88,7 +88,7 @@ Secondary full-public compatibility, including public tests that are currently e | webstreams | 89 | 66 | 1 | 0 | 0 | 21 | 1 | 98.5% | 75.0% | | whatwg | 319 | 43 | 32 | 0 | 0 | 56 | 188 | 57.3% | 32.8% | | worker_threads | 202 | 25 | 29 | 127 | 0 | 13 | 8 | 46.3% | 12.9% | -| zlib | 324 | 72 | 11 | 0 | 0 | 237 | 4 | 86.7% | 22.5% | +| zlib | 324 | 73 | 11 | 0 | 0 | 236 | 4 | 86.9% | 22.8% | ## Split Test Summary @@ -1956,11 +1956,11 @@ Secondary full-public compatibility, including public tests that are currently e | vm.Script.createCachedData relies on V8 code cache internals unavailable in QuickJS | 1 | `parallel/test-vm-createcacheddata.js` | | vm.SourceTextModule dynamic import referrer realm semantics depend on Node VM realm behavior not modeled by the QuickJS host | 1 | `parallel/test-vm-module-referrer-realm.mjs` | -### unevaluated (3818) +### unevaluated (3817) | Reason | Count | Example entries | |--------|-------|-----------------| -| newly discovered, not yet evaluated | 3616 | `es-module/test-cjs-defer-static-import-eval.mjs`, `es-module/test-defer-import-builtin-module.mjs`, `es-module/test-defer-import-eval-with-tla.mjs`, ... (+3613) | +| newly discovered, not yet evaluated | 3615 | `es-module/test-cjs-defer-static-import-eval.mjs`, `es-module/test-defer-import-builtin-module.mjs`, `es-module/test-defer-import-eval-with-tla.mjs`, ... (+3612) | | newly discovered subtest, not yet evaluated | 202 | `es-module/test-esm-json.mjs#test_01_should_load_json_with_import_calls`, `parallel/test-assert-deep.js#test_01_loose_deepequal`, `parallel/test-assert-deep.js#test_08_deepstrictequal_handles_shared_expected_array_elements_after`, ... (+199) | ### Node.js internals (1177) diff --git a/tests/runtime/zlib.rs b/tests/runtime/zlib.rs index d0cc66850..2603333e5 100644 --- a/tests/runtime/zlib.rs +++ b/tests/runtime/zlib.rs @@ -32,6 +32,15 @@ async fn zlib_zstd(#[tagged_as("zlib")] compiled: &CompiledTest) -> anyhow::Resu Ok(()) } +#[test] +async fn zlib_zstd_contracts(#[tagged_as("zlib")] compiled: &CompiledTest) -> anyhow::Result<()> { + let (result, output) = + invoke_and_capture_output(compiled.wasm_path(), None, "test-zstd-contracts", &[]).await; + println!("Output:\n{}", output); + assert_eq!(result?, Some(Val::Bool(true))); + Ok(()) +} + #[test] async fn zlib_zstd_disabled() -> anyhow::Result<()> { // Keep this component's Cargo output separate from the full-tier dependency. From dc2b6803e035523297206a90ea07b67ba4f69cd5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?D=C3=A1vid=20Istv=C3=A1n=20B=C3=ADr=C3=B3?= Date: Thu, 26 Nov 2026 11:49:55 +0000 Subject: [PATCH 4/5] Fix zstd public contracts --- README.md | 1 + .../skeleton/src/builtin/zlib.js | 30 +++++++-- examples/runtime/zlib/src/zlib.js | 62 ++++++++++++++++++- 3 files changed, 84 insertions(+), 9 deletions(-) diff --git a/README.md b/README.md index 23d8a387b..6506c4f2e 100644 --- a/README.md +++ b/README.md @@ -1304,6 +1304,7 @@ throws immediately. Environment-data APIs are unavailable. - **Async:** `gzip`, `gunzip`, `deflate`, `inflate`, `deflateRaw`, `inflateRaw`, `unzip`, `brotliCompress`, `brotliDecompress`, `zstdCompress`, `zstdDecompress` - **Sync:** `gzipSync`, `gunzipSync`, `deflateSync`, `inflateSync`, `deflateRawSync`, `inflateRawSync`, `unzipSync`, `brotliCompressSync`, `brotliDecompressSync`, `zstdCompressSync`, `zstdDecompressSync` - `crc32`, `constants`, `codes` +- Zstandard constants are available through `constants` and direct `ZSTD_*` aliases on the default/CommonJS export. - Zstandard requires the optional `zstd` feature (included in the full tiers). It uses the reference zstd codec with worker threads disabled for WASI; `normal-p3` does not include that codec. The APIs remain discoverable without the feature, but calls throw `ERR_ZLIB_INITIALIZATION_FAILED`. diff --git a/crates/wasm-rquickjs/skeleton/src/builtin/zlib.js b/crates/wasm-rquickjs/skeleton/src/builtin/zlib.js index db3063fd4..d3d2259dd 100644 --- a/crates/wasm-rquickjs/skeleton/src/builtin/zlib.js +++ b/crates/wasm-rquickjs/skeleton/src/builtin/zlib.js @@ -228,6 +228,11 @@ const zstdConstants = { ZSTD_error_noForwardProgress_inputEmpty: 82, }; +const zstdErrorCodes = Object.create(null); +for (const key of Object.keys(zstdConstants)) { + if (stringStartsWith(key, 'ZSTD_error_')) zstdErrorCodes[zstdConstants[key]] = key; +} + export const constants = Object.freeze({ ...zstdConstants, Z_NO_FLUSH, @@ -1184,12 +1189,17 @@ class Zstd extends ZlibBase { if (handle == null) throw makeError('ERR_ZLIB_INITIALIZATION_FAILED', 'Setting parameter failed'); // An already-aborted signal may destroy the stream during super(). Attach // it only after the native owner and its finalizer are installed. - try { super(signal ? { ...opts, signal: undefined } : opts, decompress ? 11 : 10); } + try { + // Codec output stays binary; constructor encoding is not a setEncoding call. + if (opts.encoding) opts = { ...opts, encoding: null }; + super(signal ? { ...opts, signal: undefined } : opts, decompress ? 11 : 10); + } catch (error) { zstd_stream_close(handle); throw error; } try { this._finishFlush = finishFlush; this._flushFlag = flush; this._chunkSize = chunkSize ?? Z_DEFAULT_CHUNK; + this._info = opts.info; this._zstdResume = null; this._setNativeHandle(handle); registerFinalizer(zstdCleanup, this, handle, this); @@ -1226,8 +1236,7 @@ class Zstd extends ZlibBase { const [bytes, message, errno, consumed, done] = zstd_stream_push(this._nativeHandle, data, flush, capacity); if (errno === -7) throw makeTypeError('ERR_TRAILING_JUNK_AFTER_STREAM_END', message); if (errno !== 0) { - const code = errno === -5 ? 'Z_BUF_ERROR' : - Object.keys(zstdConstants).find(key => stringStartsWith(key, 'ZSTD_error_') && zstdConstants[key] === errno); + const code = errno === -5 ? 'Z_BUF_ERROR' : zstdErrorCodes[errno]; const error = makeError(code, message); error.errno = errno; throw error; @@ -1458,7 +1467,7 @@ export function brotliDecompressSync(data, opts) { function zstdSync(data, opts, engine) { try { const buffer = engine._processChunk(data, engine._finishFlush, opts?.maxOutputLength ?? _getKMaxLength()); - return opts?.info ? { buffer, engine } : buffer; + return engine._info ? { buffer, engine } : buffer; } finally { engine._closeHandle(); } } @@ -1492,11 +1501,11 @@ function zstdAsync(data, opts, callback, Engine) { const engine = new Engine(opts); let input; try { - input = typeof data === 'string' ? Buffer.from(data, engine._writableState.defaultEncoding) : toBuffer(data); if (typeof callback !== 'function') { throw makeTypeError('ERR_INVALID_ARG_TYPE', 'The "callback" argument must be of type function. Received ' + (callback === undefined ? 'undefined' : typeof callback)); } + input = typeof data === 'string' ? Buffer.from(data, engine._writableState.defaultEncoding) : toBuffer(data); } catch (error) { // This private engine cannot deliver errors after validation throws. engine.on('error', () => {}); @@ -1526,7 +1535,7 @@ function zstdAsync(data, opts, callback, Engine) { let buffer; try { buffer = Buffer.concat(chunks, total); } catch (error) { done(error); return; } - done(null, opts?.info ? { buffer, engine } : buffer); + done(null, engine._info ? { buffer, engine } : buffer); }); try { engine.end(input); @@ -1699,6 +1708,15 @@ const _default = { ZLIB_VERNUM, }; +for (const key of Object.keys(zstdConstants)) { + Object.defineProperty(_default, key, { + value: zstdConstants[key], + writable: false, + configurable: false, + enumerable: false, + }); +} + Object.defineProperty(_default, 'constants', { value: constants, writable: false, diff --git a/examples/runtime/zlib/src/zlib.js b/examples/runtime/zlib/src/zlib.js index d93af44a2..14dd4cd87 100644 --- a/examples/runtime/zlib/src/zlib.js +++ b/examples/runtime/zlib/src/zlib.js @@ -532,6 +532,48 @@ export async function testZstd() { export async function testZstdContracts() { const failures = []; for (const [name, check] of [ + ['binary output despite constructor encoding', async () => { + const source = Buffer.from([0, 255, 13, 29, 128, 65]); + const options = { encoding: 'hex' }; + const frame = await new Promise((resolve, reject) => zlib.zstdCompress(source, options, + (error, value) => error ? reject(error) : resolve(value))); + assert.ok(Buffer.isBuffer(frame)); + const decoded = await new Promise((resolve, reject) => zlib.zstdDecompress(frame, options, + (error, value) => error ? reject(error) : resolve(value))); + assert.ok(Buffer.isBuffer(decoded)); + assert.deepEqual(decoded, source); + await streamRoundTrip(source, zlib.createZstdCompress(options), zlib.createZstdDecompress(options)); + assert.deepEqual(options, { encoding: 'hex' }); + }], + ['callback info snapshot', async () => { + const source = Buffer.from('callback shape 13|29'); + const frame = zlib.zstdCompressSync(source); + for (const info of [false, true]) { + const options = { info }; + const result = new Promise((resolve, reject) => zlib.zstdDecompress(frame, options, + (error, value) => error ? reject(error) : resolve(value))); + options.info = !info; + const value = await result; + assert.deepEqual(info ? value.buffer : value, source); + assert.equal(Buffer.isBuffer(value), !info); + if (info) assert.ok(value.engine instanceof zlib.ZstdDecompress); + } + }], + ['direct constant aliases', async () => { + assert.equal(zlib.default.ZSTD_c_compressionLevel, 100); + assert.equal(zlib.default.ZSTD_e_end, 2); + assert.throws(() => { zlib.default.ZSTD_e_end = 99; }, TypeError); + const source = Buffer.from('direct constant parameter 13|29'); + const frame = zlib.zstdCompressSync(source, + { params: { [zlib.default.ZSTD_c_compressionLevel]: 9 } }); + assert.deepEqual(zlib.zstdDecompressSync(frame), source); + }], + ['callback validation precedence', async () => { + for (const operation of [zlib.zstdCompress, zlib.zstdDecompress]) { + assert.throws(() => operation(123), + { code: 'ERR_INVALID_ARG_TYPE', message: /callback/ }); + } + }], ['callback source pledge', async () => { const bytes = Buffer.from('hΓ©llo wΓΆrld πŸš€ '.repeat(1000)); const padded = Buffer.concat([Buffer.alloc(7), bytes, Buffer.alloc(11)]); @@ -579,11 +621,25 @@ export async function testZstdContracts() { }], ['error intrinsic capture', async () => { const original = String.prototype.startsWith; + const find = Array.prototype.find; + const keys = Object.keys; + let error; + // Construct first: parameter enumeration is not the error-mapping path. + const decoder = zlib.createZstdDecompress(); + const failed = new Promise(resolve => decoder.on('error', resolve)); try { String.prototype.startsWith = () => { throw new Error('mutable startsWith'); }; - assert.throws(() => zlib.zstdDecompressSync(Buffer.from([1, 2, 3, 4])), - { code: 'ZSTD_error_prefix_unknown', errno: 10 }); - } finally { String.prototype.startsWith = original; } + Array.prototype.find = () => { throw new Error('mutable find'); }; + Object.keys = () => { throw new Error('mutable keys'); }; + decoder.end(Buffer.from([1, 2, 3, 4])); + error = await failed; + } finally { + String.prototype.startsWith = original; + Array.prototype.find = find; + Object.keys = keys; + } + assert.equal(error?.code, 'ZSTD_error_prefix_unknown'); + assert.equal(error?.errno, 10); }], ['callback encoding', async () => { for (const pledgedSrcSize of [undefined, 1]) { From df468ecda2b89ccdbd717082fab40101a9293e0b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?D=C3=A1vid=20Istv=C3=A1n=20B=C3=ADr=C3=B3?= Date: Thu, 26 Nov 2026 13:48:03 +0000 Subject: [PATCH 5/5] Fix zstd consumed byte accounting --- .../skeleton/src/builtin/zlib.js | 4 +- .../skeleton/src/builtin/zlib/zstd.rs | 3 +- examples/runtime/zlib/src/zlib.js | 48 +++++++++++++++++++ 3 files changed, 52 insertions(+), 3 deletions(-) diff --git a/crates/wasm-rquickjs/skeleton/src/builtin/zlib.js b/crates/wasm-rquickjs/skeleton/src/builtin/zlib.js index d3d2259dd..b081034d5 100644 --- a/crates/wasm-rquickjs/skeleton/src/builtin/zlib.js +++ b/crates/wasm-rquickjs/skeleton/src/builtin/zlib.js @@ -1246,13 +1246,13 @@ class Zstd extends ZlibBase { _processChunk(chunk, flush, limit = _getKMaxLength()) { const data = toUint8Array(toBuffer(chunk)); - this._bytesWritten += data.length; const chunks = []; let offset = 0, total = 0, done; do { const [output, consumed, complete] = this._processStep( data.subarray(offset), flush, Math.min(this._chunkSize, limit - total + 1)); offset += consumed; + this._bytesWritten += consumed; total += output.length; if (total > limit) throw makeRangeError('ERR_BUFFER_TOO_LARGE', `Cannot create a Buffer larger than ${limit} bytes`); if (output.length) chunks.push(output); @@ -1263,7 +1263,6 @@ class Zstd extends ZlibBase { _processStream(chunk, flush, callback) { const data = toUint8Array(toBuffer(chunk)); - this._bytesWritten += data.length; let offset = 0; const resume = error => { if (error) { callback(error); return; } @@ -1271,6 +1270,7 @@ class Zstd extends ZlibBase { while (this._nativeHandle !== null) { const [output, consumed, done] = this._processStep(data.subarray(offset), flush, this._chunkSize); offset += consumed; + this._bytesWritten += consumed; const ready = output.length === 0 || this.push(output); if (this._nativeHandle === null) break; if (!ready) { diff --git a/crates/wasm-rquickjs/skeleton/src/builtin/zlib/zstd.rs b/crates/wasm-rquickjs/skeleton/src/builtin/zlib/zstd.rs index e79ad84f6..ccfe19e1a 100644 --- a/crates/wasm-rquickjs/skeleton/src/builtin/zlib/zstd.rs +++ b/crates/wasm-rquickjs/skeleton/src/builtin/zlib/zstd.rs @@ -202,7 +202,8 @@ pub(super) fn push( "Trailing junk found after the end of the compressed stream".to_string(), )); } - return Ok((Vec::new(), bytes.len(), true)); + // Stop this write without counting discarded input as consumed. + return Ok((Vec::new(), 0, true)); } if data.len() < 4 { if flush == 2 && !data.is_empty() && stream.reject_garbage { diff --git a/examples/runtime/zlib/src/zlib.js b/examples/runtime/zlib/src/zlib.js index 14dd4cd87..83e2835a7 100644 --- a/examples/runtime/zlib/src/zlib.js +++ b/examples/runtime/zlib/src/zlib.js @@ -532,6 +532,54 @@ export async function testZstd() { export async function testZstdContracts() { const failures = []; for (const [name, check] of [ + ['decompression byte accounting', async () => { + // Node 26 frame for "hello", independent of this runtime's compressor. + const frame = Buffer.from('28b52ffd200529000068656c6c6f', 'hex'); + const junk = Buffer.from('junk'); + const skippable = Buffer.from('502a4d1803000000616263', 'hex'); + for (const [suffix, expectedBytes, expectedOutput] of [ + [Buffer.alloc(0), 14, 'hello'], + [junk, 14, 'hello'], + [frame.subarray(0, 2), 16, 'hello'], + [Buffer.from([0x28, 0xb5, 0, 0]), 14, 'hello'], + [frame, 28, 'hellohello'], + [Buffer.concat([skippable, frame, junk]), 39, 'hellohello'], + ]) { + const input = Buffer.concat([frame, suffix]); + const sync = zlib.zstdDecompressSync(input, { info: true, chunkSize: 64 }); + assert.equal(sync.buffer.toString(), expectedOutput); + assert.equal(sync.engine.bytesWritten, expectedBytes); + const callback = await new Promise((resolve, reject) => zlib.zstdDecompress(input, + { info: true, chunkSize: 64 }, (error, value) => error ? reject(error) : resolve(value))); + assert.equal(callback.buffer.toString(), expectedOutput); + assert.equal(callback.engine.bytesWritten, expectedBytes); + } + for (const [parts, expectedBytes, expectedOutput] of [ + [[Buffer.concat([frame, junk])], 14, 'hello'], + [[frame, junk], 14, 'hello'], + [[Buffer.concat([frame, frame.subarray(0, 1)]), junk], 15, 'hello'], + [[frame, frame.subarray(0, 1), junk], 15, 'hello'], + [[frame, frame.subarray(0, 2)], 16, 'hello'], + [[frame, frame.subarray(0, 1), frame.subarray(1), junk], 28, 'hellohello'], + [[frame, skippable.subarray(0, 3), skippable.subarray(3), frame, junk], 39, 'hellohello'], + ]) { + const decoder = zlib.createZstdDecompress({ chunkSize: 64 }); + const chunks = []; + const done = new Promise((resolve, reject) => { + decoder.on('data', chunk => chunks.push(chunk)); + decoder.on('end', resolve); + decoder.on('error', reject); + }); + for (const part of parts) { + await new Promise((resolve, reject) => decoder.write(part, + error => error ? reject(error) : resolve())); + } + decoder.end(); + await done; + assert.equal(Buffer.concat(chunks).toString(), expectedOutput); + assert.equal(decoder.bytesWritten, expectedBytes); + } + }], ['binary output despite constructor encoding', async () => { const source = Buffer.from([0, 255, 13, 29, 128, 65]); const options = { encoding: 'hex' };