libdeflate-wasm 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md ADDED
@@ -0,0 +1,25 @@
1
+ # Changelog
2
+
3
+ All notable changes to this project are documented here. The format follows
4
+ [Keep a Changelog](https://keepachangelog.com/en/1.1.0/) and the project uses
5
+ [Semantic Versioning](https://semver.org/).
6
+
7
+ ## [0.1.0]
8
+
9
+ First release, made for the Compress PDF engine of konvetto.com.
10
+
11
+ ### Added
12
+
13
+ - libdeflate 1.26 compiled to one standalone wasm file (Emscripten 7.0.1, `-O3 -flto`, emmalloc,
14
+ no JS glue, no threads).
15
+ - `init` and `initSync`, sharing one instance even when they race: load from the file next to the module, a URL, a `Response`, bytes or a
16
+ compiled module; Node reads `file:` URLs with `node:fs`.
17
+ - `deflate`, `zlib` and `gzip` at levels 0 to 12 (default 12), one cached compressor per level.
18
+ - `inflate`, `unzlib` and `gunzip`, with an optional exact `size`. Size hints, including the gzip
19
+ trailer, are trusted only up to what the input can decode to. Decoding stops after the first
20
+ stream or gzip member.
21
+ - `MAX_INPUT` (1 GiB) and `MAX_OUTPUT` (2 GiB minus 64 KiB), checked before any allocation.
22
+ - `release` to free the cached compressors.
23
+ - Tests: round trips through node:zlib, byte-for-byte equality with native `libdeflate-gzip` 1.26
24
+ at levels 1 to 12 (CI builds the native reference from `vendor/`), empty and 50 MB inputs, memory
25
+ reuse across calls, corrupt size hints, and an opt-in test past 2 GiB of wasm memory.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Konvetto
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,208 @@
1
- # Temporary Holding Version
1
+ <a href="https://konvetto.com/pdf/compress-pdf"><img src="https://raw.githubusercontent.com/Konvetto/libdeflate-wasm/main/.github/assets/social-preview.png" alt="libdeflate-wasm: smaller zlib and gzip in WebAssembly. Try it free on konvetto.com" width="100%"></a>
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ # libdeflate-wasm
4
+
5
+ **[libdeflate](https://github.com/ebiggers/libdeflate) 1.26 in WebAssembly: DEFLATE, zlib and
6
+ gzip up to level 12, byte for byte the same as the native library. 25 kB brotli, zero
7
+ dependencies.**
8
+
9
+ [![npm](https://img.shields.io/npm/v/libdeflate-wasm)](https://www.npmjs.com/package/libdeflate-wasm)
10
+ [![dependencies](https://img.shields.io/badge/dependencies-0-success)](./package.json)
11
+ [![license](https://img.shields.io/npm/l/libdeflate-wasm)](./LICENSE)
12
+ [![CI](https://github.com/Konvetto/libdeflate-wasm/actions/workflows/ci.yml/badge.svg)](https://github.com/Konvetto/libdeflate-wasm/actions/workflows/ci.yml)
13
+
14
+ libdeflate's level 12 makes standard DEFLATE streams, decoded as usual by zlib, browsers and PDF
15
+ readers, that are noticeably smaller than zlib's best: on the Flate streams of four real PDFs, 9.0 percent
16
+ smaller than fflate at level 9 and 6.3 percent smaller than zlib at level 9. This package is that
17
+ compressor, compiled once to a single-threaded wasm file, with a synchronous API after one
18
+ `await init()`. It runs in browsers, Web Workers, Node, Deno and Bun.
19
+
20
+ > **Try it without installing anything:** the [Compress PDF](https://konvetto.com/pdf/compress-pdf)
21
+ > tool on Konvetto recompresses every Flate stream of your PDF with libdeflate-wasm, in your
22
+ > browser. No upload, no account, your file never leaves the tab.
23
+
24
+ ## Why libdeflate-wasm
25
+
26
+ - **Smaller than zlib level 9**: level 12 is libdeflate's near-optimal parser. See
27
+ [Benchmark](#benchmark) for the numbers on PDF streams.
28
+ - **Faster at the same size**: level 6 already beats fflate and zlib at level 9 on size, at a
29
+ third of their time.
30
+ - **Identical to native libdeflate**: the tests compare every level from 1 to 12 with native
31
+ libdeflate of the same version, byte for byte, up to 50 MB of input (CI builds the native
32
+ reference from `vendor/`).
33
+ - **Deterministic**: the same input and level give the same bytes on every platform.
34
+ - **Small**: 64 kB of wasm (30 kB gzip, 25 kB brotli) and a 2 kB loader. No Emscripten JS glue,
35
+ no threads, no `SharedArrayBuffer`, no special headers.
36
+ - **Memory-safe use of wasm**: one compressor per level is allocated once and reused; buffers are
37
+ freed after every call; output is a plain `Uint8Array` you own.
38
+
39
+ Where it loses: level 12 is about 5 times slower than fflate at level 9. The wasm build runs at
40
+ about 95 percent of native speed. Input is capped at 1 GiB per call and output at 2 GiB: for
41
+ streaming or larger data, use a streaming compressor, libdeflate works on whole buffers.
42
+
43
+ ## Install
44
+
45
+ ```sh
46
+ npm install libdeflate-wasm
47
+ ```
48
+
49
+ Node 20.16 or newer, any browser with WebAssembly, Deno and Bun. ESM only.
50
+
51
+ ## Usage
52
+
53
+ ```ts
54
+ import { init, zlib, deflate, gzip, unzlib } from 'libdeflate-wasm';
55
+
56
+ await init(); // once, loads libdeflate.wasm next to the module
57
+
58
+ const flate = zlib(bytes); // zlib stream at level 12, what PDF /FlateDecode wants
59
+ const raw = deflate(bytes, 6); // raw DEFLATE, level 0 to 12
60
+ const gz = gzip(bytes, 9); // gzip member
61
+ const back = unzlib(flate); // and back
62
+ ```
63
+
64
+ ### In a Web Worker (Vite, webpack 5, Rollup, esbuild)
65
+
66
+ The module finds its wasm with `new URL('./libdeflate.wasm', import.meta.url)`, which bundlers
67
+ turn into an emitted asset:
68
+
69
+ ```ts
70
+ // worker.ts
71
+ import { init, zlib } from 'libdeflate-wasm';
72
+ const ready = init();
73
+ self.onmessage = async ({ data }: MessageEvent<Uint8Array>) => {
74
+ await ready;
75
+ const out = zlib(data, 12);
76
+ self.postMessage(out, [out.buffer]);
77
+ };
78
+ ```
79
+
80
+ Vite 8 handles this in both the dev server and production builds. If your bundler or an older
81
+ Vite dev server answers 404 for the wasm, add the package to `optimizeDeps.exclude` or pass the
82
+ URL yourself:
83
+
84
+ ```ts
85
+ import wasmUrl from 'libdeflate-wasm/libdeflate.wasm?url';
86
+ await init(wasmUrl);
87
+ ```
88
+
89
+ ### Node
90
+
91
+ ```ts
92
+ import { init, zlib } from 'libdeflate-wasm';
93
+ await init(); // reads the file with node:fs, no fetch
94
+ ```
95
+
96
+ ### Other ways to load
97
+
98
+ `init(source)` takes a URL or a string (fetched, or read from disk for `file:`), a `Response`,
99
+ the bytes, or a compiled `WebAssembly.Module`. `initSync(bytesOrModule)` does the same
100
+ synchronously. Once one of them has loaded the module, every further call is a no-op (a different
101
+ `source` is ignored), and `init` and `initSync` racing in the same tick still create one
102
+ instance.
103
+
104
+ `initSync` with raw bytes works in Web Workers, Node, Deno and Bun. On a browser's main thread,
105
+ synchronous compilation of large modules may be refused (Chrome long rejected anything over
106
+ 4 KB), so pass a `WebAssembly.Module` there (for example from `WebAssembly.compileStreaming`) or
107
+ use `init`.
108
+
109
+ **Content Security Policy:** compiling wasm needs `script-src 'wasm-unsafe-eval'` (or
110
+ `'unsafe-eval'`) on pages with a CSP. The package uses no `eval` and no `new Function`.
111
+
112
+ ## API
113
+
114
+ | Function | Returns |
115
+ | ---------------------------- | ------------------------------------------------------------ |
116
+ | `init(source?)` | `Promise<void>`. Loads the wasm. Safe to call many times. |
117
+ | `initSync(source)` | Synchronous `init` from bytes or a `WebAssembly.Module`. |
118
+ | `isReady()` | `true` once loaded. |
119
+ | `deflate(data, level = 12)` | Raw DEFLATE (RFC 1951). |
120
+ | `zlib(data, level = 12)` | zlib stream (RFC 1950): 2-byte header, DEFLATE, Adler-32. |
121
+ | `gzip(data, level = 12)` | gzip member (RFC 1952), no file name, mtime 0. |
122
+ | `inflate(data, size?)` | Raw DEFLATE back to bytes. |
123
+ | `unzlib(data, size?)` | zlib stream back to bytes. |
124
+ | `gunzip(data, size?)` | The first gzip member back to bytes. |
125
+ | `release()` | Frees the cached compressors and decompressor. |
126
+ | `MAX_LEVEL`, `DEFAULT_LEVEL` | `12`, `12`. |
127
+ | `MAX_INPUT`, `MAX_OUTPUT` | 1 GiB per input, 2 GiB minus 64 KiB per decompressed output. |
128
+
129
+ Levels: 0 stores without compression, 1 to 9 are close to zlib's speed steps (and smaller),
130
+ 10 to 12 use libdeflate's near-optimal parser. All functions take a `Uint8Array` (a subarray is
131
+ fine) and return a new `Uint8Array`. They throw `RangeError` for a bad level or when wasm memory
132
+ runs out, `RangeError` for an input over `MAX_INPUT`, `TypeError` for a non-`Uint8Array` and
133
+ `Error` for corrupt data.
134
+
135
+ Pass `size` to the decompressors when you know the exact output length: it is faster and the
136
+ call fails if the length differs. Without it the output buffer starts at four times the input
137
+ (for gzip: the size in the member's trailer) and doubles until the data fits. Size hints are
138
+ trusted only up to what the input can decode to (DEFLATE expands at most about 1032 times), so a
139
+ small corrupt stream cannot make the module reserve gigabytes.
140
+
141
+ Like libdeflate, the decompressors stop at the end of the first stream: bytes after a zlib or
142
+ DEFLATE stream are ignored (PDF streams often end with a line break), and `gunzip` returns only
143
+ the first member of a multi-member file, where `node:zlib` would return all of them.
144
+
145
+ ### Memory
146
+
147
+ Each call copies the input into wasm memory, compresses into a buffer of
148
+ `libdeflate_*_compress_bound` bytes (slightly more than the input), copies the result out and
149
+ frees both. Compressors are cached per level until `release()`: 8.6 MB for each of levels 10 to
150
+ 12, 0.64 MB for levels 2 to 9, 0.19 MB for level 1, about 31 MB if all 13 levels are used. The
151
+ decompressor holds 11 KB. Decompression without `size` needs the input plus up to twice the
152
+ output while it doubles its buffer. wasm memory grows to the largest call and never shrinks, but
153
+ freed space is reused, so a loop of large calls does not leak (tested). Call `release()` between
154
+ jobs, or drop the worker to hand memory back to the system.
155
+
156
+ ## Benchmark
157
+
158
+ Every `/FlateDecode` stream of four public PDFs (a NASA report, a glacier report, a
159
+ newsletter and a JPL slide deck: 641 streams, 10.7 MB inflated, 3.25 MB as stored in the files),
160
+ inflated with node:zlib and compressed again by each contender. Apple M2 Pro, Node 26,
161
+ one thread.
162
+
163
+ | Compressor | Bytes | vs fflate 9 | Time |
164
+ | -------------------------------- | --------: | ----------: | -------: |
165
+ | fflate 0.8.3, level 9 | 3,528,426 | 0.00% | 395 ms |
166
+ | node:zlib, level 9 | 3,428,127 | -2.84% | 496 ms |
167
+ | libdeflate-wasm, level 6 | 3,401,824 | -3.59% | 134 ms |
168
+ | libdeflate-wasm, level 9 | 3,372,073 | -4.43% | 253 ms |
169
+ | libdeflate-wasm, level 12 | 3,211,556 | -8.98% | 1,982 ms |
170
+ | native libdeflate 1.26, level 12 | 3,211,556 | -8.98% | 1,891 ms |
171
+
172
+ Same run as [bench/results.md](./bench/results.md), which has the per-file numbers. The wasm output at level 12 is the native output, byte for byte. Native time is one
173
+ `libdeflate-gzip` process over all streams, including file reads and writes. Reproduce with:
174
+
175
+ ```sh
176
+ pnpm bench -- a.pdf b.pdf # needs @cantoo/pdf-lib in PDF_LIB_FROM and libdeflate-gzip
177
+ ```
178
+
179
+ ### Why no SIMD build
180
+
181
+ libdeflate's SIMD code is hand-written for x86 and ARM (CRC-32, Adler-32, match finder
182
+ initialisation) and is not compiled for wasm. Building with `-msimd128` (auto-vectorisation only)
183
+ gave the same speed within 1 percent and a 25 percent larger file, so one baseline build ships,
184
+ and it runs on every engine with WebAssembly bulk memory (Chrome 75, Firefox 79, Safari 15,
185
+ Node 12 and later).
186
+
187
+ ## Building the wasm
188
+
189
+ The compiled `src/libdeflate.wasm` is committed, so `pnpm build` needs no C toolchain. To rebuild
190
+ it you need Emscripten (7.0.1 is what CI uses):
191
+
192
+ ```sh
193
+ pnpm vendor:verify # vendor/libdeflate matches the pinned release tarball (SHA-256)
194
+ pnpm build:wasm # emcc -O3 -flto, standalone wasm, emmalloc, no JS glue
195
+ ```
196
+
197
+ CI checks `vendor/` against the release tarball and rebuilds the wasm with emsdk 7.0.1. The
198
+ committed file comes from Homebrew's Emscripten 7.0.1 on macOS, so a Linux build may differ in
199
+ bytes; CI reports that as a warning, not a failure. What must never differ is the compressed
200
+ output, which the byte-for-byte tests pin.
201
+
202
+ ## License
203
+
204
+ MIT for this package. The wasm contains libdeflate (MIT, Eric Biggers and Google LLC) and parts of
205
+ the Emscripten system libraries (MIT / NCSA); see
206
+ [THIRD_PARTY_NOTICES.md](./THIRD_PARTY_NOTICES.md), which ships in the package.
207
+
208
+ Made by [Konvetto](https://konvetto.com), free tools that run in your browser.
@@ -0,0 +1,63 @@
1
+ # Third-party notices
2
+
3
+ `dist/libdeflate.wasm` is compiled from libdeflate and from parts of the Emscripten system
4
+ libraries. Both notices below ship with the npm package.
5
+
6
+ ## libdeflate 1.26
7
+
8
+ Source: https://github.com/ebiggers/libdeflate (tag `v1.26`, vendored unmodified in
9
+ `vendor/libdeflate`, SHA-256 of the release tarball in `scripts/fetch-libdeflate.sh`).
10
+
11
+ ```
12
+ Copyright 2016 Eric Biggers
13
+ Copyright 2024 Google LLC
14
+
15
+ Permission is hereby granted, free of charge, to any person
16
+ obtaining a copy of this software and associated documentation files
17
+ (the "Software"), to deal in the Software without restriction,
18
+ including without limitation the rights to use, copy, modify, merge,
19
+ publish, distribute, sublicense, and/or sell copies of the Software,
20
+ and to permit persons to whom the Software is furnished to do so,
21
+ subject to the following conditions:
22
+
23
+ The above copyright notice and this permission notice shall be
24
+ included in all copies or substantial portions of the Software.
25
+
26
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
27
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
28
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
29
+ NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
30
+ BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
31
+ ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
32
+ CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
33
+ SOFTWARE.
34
+ ```
35
+
36
+ ## Emscripten system libraries (emmalloc, musl libc parts, compiler-rt)
37
+
38
+ Linked into the wasm by Emscripten 7.0.1: `malloc`/`free` (emmalloc), `memcpy`/`memset` (musl)
39
+ and compiler builtins. Emscripten is available under the MIT license and the University of
40
+ Illinois/NCSA Open Source License; musl is MIT; compiler-rt is Apache 2.0 with LLVM exceptions.
41
+ See https://github.com/emscripten-core/emscripten/blob/main/LICENSE.
42
+
43
+ ```
44
+ Copyright (c) 2010-2014 Emscripten authors, see AUTHORS file.
45
+
46
+ Permission is hereby granted, free of charge, to any person obtaining a copy
47
+ of this software and associated documentation files (the "Software"), to deal
48
+ in the Software without restriction, including without limitation the rights
49
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
50
+ copies of the Software, and to permit persons to whom the Software is
51
+ furnished to do so, subject to the following conditions:
52
+
53
+ The above copyright notice and this permission notice shall be included in
54
+ all copies or substantial portions of the Software.
55
+
56
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
57
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
58
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
59
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
60
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
61
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
62
+ THE SOFTWARE.
63
+ ```
@@ -0,0 +1,48 @@
1
+ /**
2
+ * libdeflate compiled to WebAssembly: raw DEFLATE, zlib and gzip at levels 0 to 12.
3
+ *
4
+ * Call `init()` once (async), then every function below is synchronous. One compressor per
5
+ * level is allocated on first use and reused; input and output buffers live in wasm memory only
6
+ * for the duration of a call.
7
+ */
8
+ /** What `init` accepts: a URL of the .wasm file, its bytes, a fetch `Response` or a compiled module. */
9
+ type WasmSource = URL | string | Response | BufferSource | WebAssembly.Module;
10
+ /** Highest level libdeflate supports. 12 is its slowest, smallest setting. */
11
+ declare const MAX_LEVEL = 12;
12
+ /** Level used when none is given. */
13
+ declare const DEFAULT_LEVEL = 12;
14
+ /** Largest input any function takes: 1 GiB. Compression needs about twice that in wasm memory. */
15
+ declare const MAX_INPUT = 1073741824;
16
+ /** Largest output the decompressors produce: 2 GiB minus 64 KiB. */
17
+ declare const MAX_OUTPUT = 2147418112;
18
+ /**
19
+ * Loads and instantiates the wasm module. Safe to call many times; later calls return the first
20
+ * promise. Without an argument the file next to this module (`libdeflate.wasm`) is used.
21
+ */
22
+ declare function init(source?: WasmSource): Promise<void>;
23
+ /** Synchronous `init` for callers that already hold the bytes or a compiled module. */
24
+ declare function initSync(source: BufferSource | WebAssembly.Module): void;
25
+ /** True once `init` or `initSync` has finished. */
26
+ declare function isReady(): boolean;
27
+ /** Raw DEFLATE (RFC 1951), no header or checksum. */
28
+ declare function deflate(data: Uint8Array, level?: number): Uint8Array;
29
+ /** zlib stream (RFC 1950): what PDF `/FlateDecode` and PNG `IDAT` expect. */
30
+ declare function zlib(data: Uint8Array, level?: number): Uint8Array;
31
+ /** gzip member (RFC 1952) with an empty header (no name, mtime 0), like `libdeflate-gzip -c`. */
32
+ declare function gzip(data: Uint8Array, level?: number): Uint8Array;
33
+ /**
34
+ * Decompresses raw DEFLATE. Pass `size` when the exact output length is known (faster).
35
+ * Decoding stops at the end of the first stream; bytes after it are ignored.
36
+ */
37
+ declare function inflate(data: Uint8Array, size?: number): Uint8Array;
38
+ /** Decompresses a zlib stream. Bytes after its Adler-32 are ignored (PDF streams often have an EOL). */
39
+ declare function unzlib(data: Uint8Array, size?: number): Uint8Array;
40
+ /** Decompresses the first gzip member; further members and trailing bytes are ignored. */
41
+ declare function gunzip(data: Uint8Array, size?: number): Uint8Array;
42
+ /**
43
+ * Frees the cached compressors and decompressor (levels 10 to 12 hold about 8.6 MB each). wasm
44
+ * memory never shrinks, but freed space is reused by later calls.
45
+ */
46
+ declare function release(): void;
47
+
48
+ export { DEFAULT_LEVEL, MAX_INPUT, MAX_LEVEL, MAX_OUTPUT, type WasmSource, deflate, gunzip, gzip, inflate, init, initSync, isReady, release, unzlib, zlib };
package/dist/index.js ADDED
@@ -0,0 +1,198 @@
1
+ // src/index.ts
2
+ var MAX_LEVEL = 12;
3
+ var DEFAULT_LEVEL = 12;
4
+ var DECOMPRESS_SUCCESS = 0;
5
+ var DECOMPRESS_INSUFFICIENT_SPACE = 3;
6
+ var MAX_INPUT = 1073741824;
7
+ var MAX_OUTPUT = 2147418112;
8
+ var MAX_RATIO = 1032;
9
+ var wasm;
10
+ var pending;
11
+ var compressors = /* @__PURE__ */ new Map();
12
+ var decompressor = 0;
13
+ var imports = {
14
+ // Views on memory are re-created on every call, so growth needs no bookkeeping.
15
+ env: { emscripten_notify_memory_growth: () => void 0 }
16
+ };
17
+ function defaultUrl() {
18
+ return new URL("./libdeflate.wasm", import.meta.url);
19
+ }
20
+ function isNodeFileUrl(url) {
21
+ return url.protocol === "file:";
22
+ }
23
+ async function readFileUrl(url) {
24
+ const proc = globalThis.process;
25
+ const fs = proc?.getBuiltinModule?.("node:fs/promises");
26
+ if (!fs) throw new Error("libdeflate-wasm: cannot read a file: URL without node:fs");
27
+ return fs.readFile(url);
28
+ }
29
+ async function compile(source) {
30
+ if (source instanceof WebAssembly.Module) return source;
31
+ if (typeof source === "string" || source instanceof URL) {
32
+ const url = new URL(source, typeof source === "string" ? defaultUrl() : void 0);
33
+ if (isNodeFileUrl(url)) return WebAssembly.compile(await readFileUrl(url));
34
+ return compile(await fetch(url));
35
+ }
36
+ if (source instanceof Response) {
37
+ if (!source.ok) throw new Error(`libdeflate-wasm: fetching the wasm failed (${source.status})`);
38
+ if (typeof WebAssembly.compileStreaming === "function" && source.headers.get("content-type")?.startsWith("application/wasm")) {
39
+ return WebAssembly.compileStreaming(source);
40
+ }
41
+ return WebAssembly.compile(await source.arrayBuffer());
42
+ }
43
+ return WebAssembly.compile(source);
44
+ }
45
+ function attach(module) {
46
+ if (wasm) return;
47
+ const instance = new WebAssembly.Instance(module, imports);
48
+ const exports = instance.exports;
49
+ exports._initialize();
50
+ wasm = exports;
51
+ }
52
+ function init(source) {
53
+ if (wasm) return Promise.resolve();
54
+ pending ??= compile(source ?? defaultUrl()).then(attach, (error) => {
55
+ if (wasm) return;
56
+ pending = void 0;
57
+ throw error;
58
+ });
59
+ return pending;
60
+ }
61
+ function initSync(source) {
62
+ if (wasm) return;
63
+ attach(source instanceof WebAssembly.Module ? source : new WebAssembly.Module(source));
64
+ pending ??= Promise.resolve();
65
+ }
66
+ function isReady() {
67
+ return wasm !== void 0;
68
+ }
69
+ function api() {
70
+ if (!wasm) throw new Error("libdeflate-wasm: call `await init()` before compressing");
71
+ return wasm;
72
+ }
73
+ function checkInput(data) {
74
+ if (!(data instanceof Uint8Array)) {
75
+ throw new TypeError("libdeflate-wasm: data must be a Uint8Array");
76
+ }
77
+ if (data.length > MAX_INPUT) {
78
+ throw new RangeError(`libdeflate-wasm: input is larger than ${MAX_INPUT} bytes`);
79
+ }
80
+ }
81
+ function compressor(w, level) {
82
+ if (!Number.isInteger(level) || level < 0 || level > MAX_LEVEL) {
83
+ throw new RangeError(`libdeflate-wasm: level must be an integer from 0 to ${MAX_LEVEL}`);
84
+ }
85
+ let c = compressors.get(level);
86
+ if (c === void 0) {
87
+ c = w.libdeflate_alloc_compressor(level) >>> 0;
88
+ if (!c) throw new RangeError("libdeflate-wasm: out of memory allocating the compressor");
89
+ compressors.set(level, c);
90
+ }
91
+ return c;
92
+ }
93
+ function alloc(w, n) {
94
+ const p = w.malloc(Math.max(n, 1)) >>> 0;
95
+ if (!p) throw new RangeError(`libdeflate-wasm: out of memory allocating ${n} bytes`);
96
+ return p;
97
+ }
98
+ function compress(format, data, level) {
99
+ checkInput(data);
100
+ const w = api();
101
+ const c = compressor(w, level);
102
+ const bound = w[`libdeflate_${format}_compress_bound`](c, data.length) >>> 0;
103
+ const input = alloc(w, data.length);
104
+ let output = 0;
105
+ try {
106
+ output = alloc(w, bound);
107
+ new Uint8Array(w.memory.buffer, input, data.length).set(data);
108
+ const size = w[`libdeflate_${format}_compress`](c, input, data.length, output, bound) >>> 0;
109
+ if (size === 0) throw new Error("libdeflate-wasm: compression failed");
110
+ return new Uint8Array(w.memory.buffer, output, size).slice();
111
+ } finally {
112
+ w.free(input);
113
+ if (output) w.free(output);
114
+ }
115
+ }
116
+ function deflate(data, level = DEFAULT_LEVEL) {
117
+ return compress("deflate", data, level);
118
+ }
119
+ function zlib(data, level = DEFAULT_LEVEL) {
120
+ return compress("zlib", data, level);
121
+ }
122
+ function gzip(data, level = DEFAULT_LEVEL) {
123
+ return compress("gzip", data, level);
124
+ }
125
+ function gzipSizeHint(data) {
126
+ if (data.length < 18) return void 0;
127
+ const n = data.length;
128
+ return (data[n - 4] | data[n - 3] << 8 | data[n - 2] << 16 | data[n - 1] << 24) >>> 0;
129
+ }
130
+ function decompress(format, data, size) {
131
+ checkInput(data);
132
+ if (size !== void 0 && (!Number.isInteger(size) || size < 0)) {
133
+ throw new RangeError("libdeflate-wasm: size must be a non-negative integer");
134
+ }
135
+ if (size !== void 0 && size > MAX_OUTPUT) {
136
+ throw new RangeError(`libdeflate-wasm: size must be at most ${MAX_OUTPUT} bytes`);
137
+ }
138
+ const w = api();
139
+ if (!decompressor) {
140
+ decompressor = w.libdeflate_alloc_decompressor() >>> 0;
141
+ if (!decompressor) throw new RangeError("libdeflate-wasm: out of memory");
142
+ }
143
+ const exact = size !== void 0;
144
+ const plausible = Math.min(data.length * MAX_RATIO + 1024, MAX_OUTPUT);
145
+ const limit = exact ? Math.min(size, plausible) : plausible;
146
+ const gzipHint = format === "gzip" ? gzipSizeHint(data) : void 0;
147
+ const hint = size ?? (gzipHint !== void 0 && gzipHint <= plausible ? gzipHint : void 0);
148
+ let avail = Math.min(Math.max(hint ?? data.length * 4, 1024), limit);
149
+ const actualAt = data.length + 3 & -4;
150
+ const input = alloc(w, actualAt + 4);
151
+ const actual = input + actualAt;
152
+ try {
153
+ new Uint8Array(w.memory.buffer, input, data.length).set(data);
154
+ for (; ; ) {
155
+ const output = alloc(w, avail);
156
+ try {
157
+ const run = w[`libdeflate_${format}_decompress`];
158
+ const status = run(decompressor, input, data.length, output, avail, actual);
159
+ if (status === DECOMPRESS_SUCCESS) {
160
+ const n = new DataView(w.memory.buffer).getUint32(actual, true);
161
+ if (exact && n !== size)
162
+ throw new Error(`libdeflate-wasm: expected ${size} bytes, got ${n}`);
163
+ return new Uint8Array(w.memory.buffer, output, n).slice();
164
+ }
165
+ if (status !== DECOMPRESS_INSUFFICIENT_SPACE || avail >= limit) {
166
+ throw new Error(
167
+ status !== DECOMPRESS_INSUFFICIENT_SPACE ? `libdeflate-wasm: invalid ${format} data` : exact ? "libdeflate-wasm: output larger than the given size" : `libdeflate-wasm: output larger than ${limit} bytes`
168
+ );
169
+ }
170
+ } finally {
171
+ w.free(output);
172
+ }
173
+ avail = Math.min(avail * 2, limit);
174
+ }
175
+ } finally {
176
+ w.free(input);
177
+ }
178
+ }
179
+ function inflate(data, size) {
180
+ return decompress("deflate", data, size);
181
+ }
182
+ function unzlib(data, size) {
183
+ return decompress("zlib", data, size);
184
+ }
185
+ function gunzip(data, size) {
186
+ return decompress("gzip", data, size);
187
+ }
188
+ function release() {
189
+ if (!wasm) return;
190
+ for (const c of compressors.values()) wasm.libdeflate_free_compressor(c);
191
+ compressors.clear();
192
+ if (decompressor) wasm.libdeflate_free_decompressor(decompressor);
193
+ decompressor = 0;
194
+ }
195
+
196
+ export { DEFAULT_LEVEL, MAX_INPUT, MAX_LEVEL, MAX_OUTPUT, deflate, gunzip, gzip, inflate, init, initSync, isReady, release, unzlib, zlib };
197
+ //# sourceMappingURL=index.js.map
198
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/index.ts"],"names":[],"mappings":";AAmCO,IAAM,SAAA,GAAY;AAElB,IAAM,aAAA,GAAgB;AAE7B,IAAM,kBAAA,GAAqB,CAAA;AAC3B,IAAM,6BAAA,GAAgC,CAAA;AAE/B,IAAM,SAAA,GAAY;AAElB,IAAM,UAAA,GAAa;AAE1B,IAAM,SAAA,GAAY,IAAA;AAElB,IAAI,IAAA;AACJ,IAAI,OAAA;AACJ,IAAM,WAAA,uBAAkB,GAAA,EAAoB;AAC5C,IAAI,YAAA,GAAe,CAAA;AAEnB,IAAM,OAAA,GAA+B;AAAA;AAAA,EAEnC,GAAA,EAAK,EAAE,+BAAA,EAAiC,MAAM,MAAA;AAChD,CAAA;AAEA,SAAS,UAAA,GAAkB;AACzB,EAAA,OAAO,IAAI,GAAA,CAAI,mBAAA,EAAqB,MAAA,CAAA,IAAA,CAAY,GAAG,CAAA;AACrD;AAEA,SAAS,cAAc,GAAA,EAAmB;AACxC,EAAA,OAAO,IAAI,QAAA,KAAa,OAAA;AAC1B;AAEA,eAAe,YAAY,GAAA,EAA4C;AAErE,EAAA,MAAM,OAAQ,UAAA,CAA4E,OAAA;AAC1F,EAAA,MAAM,EAAA,GAAK,IAAA,EAAM,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A;AAChE,EAAA,YAAA,GAAe,CAAA;AACjB","file":"index.js","sourcesContent":["/**\n * libdeflate compiled to WebAssembly: raw DEFLATE, zlib and gzip at levels 0 to 12.\n *\n * Call `init()` once (async), then every function below is synchronous. One compressor per\n * level is allocated on first use and reused; input and output buffers live in wasm memory only\n * for the duration of a call.\n */\n\n/** What `init` accepts: a URL of the .wasm file, its bytes, a fetch `Response` or a compiled module. */\nexport type WasmSource = URL | string | Response | BufferSource | WebAssembly.Module;\n\ninterface Exports {\n memory: WebAssembly.Memory;\n _initialize: () => void;\n malloc: (n: number) => number;\n free: (p: number) => void;\n libdeflate_alloc_compressor: (level: number) => number;\n libdeflate_free_compressor: (c: number) => void;\n libdeflate_deflate_compress: (c: number, i: number, n: number, o: number, a: number) => number;\n libdeflate_zlib_compress: (c: number, i: number, n: number, o: number, a: number) => number;\n libdeflate_gzip_compress: (c: number, i: number, n: number, o: number, a: number) => number;\n libdeflate_deflate_compress_bound: (c: number, n: number) => number;\n libdeflate_zlib_compress_bound: (c: number, n: number) => number;\n libdeflate_gzip_compress_bound: (c: number, n: number) => number;\n libdeflate_alloc_decompressor: () => number;\n libdeflate_free_decompressor: (d: number) => void;\n libdeflate_deflate_decompress: Decompress;\n libdeflate_zlib_decompress: Decompress;\n libdeflate_gzip_decompress: Decompress;\n}\n\ntype Decompress = (d: number, i: number, n: number, o: number, a: number, actual: number) => number;\ntype Format = 'deflate' | 'zlib' | 'gzip';\n\n/** Highest level libdeflate supports. 12 is its slowest, smallest setting. */\nexport const MAX_LEVEL = 12;\n/** Level used when none is given. */\nexport const DEFAULT_LEVEL = 12;\n\nconst DECOMPRESS_SUCCESS = 0;\nconst DECOMPRESS_INSUFFICIENT_SPACE = 3;\n/** Largest input any function takes: 1 GiB. Compression needs about twice that in wasm memory. */\nexport const MAX_INPUT = 0x40000000;\n/** Largest output the decompressors produce: 2 GiB minus 64 KiB. */\nexport const MAX_OUTPUT = 0x7fff0000;\n/** DEFLATE expands at most about 1032:1, so no valid stream decodes to more than this. */\nconst MAX_RATIO = 1032;\n\nlet wasm: Exports | undefined;\nlet pending: Promise<void> | undefined;\nconst compressors = new Map<number, number>();\nlet decompressor = 0;\n\nconst imports: WebAssembly.Imports = {\n // Views on memory are re-created on every call, so growth needs no bookkeeping.\n env: { emscripten_notify_memory_growth: () => undefined },\n};\n\nfunction defaultUrl(): URL {\n return new URL('./libdeflate.wasm', import.meta.url);\n}\n\nfunction isNodeFileUrl(url: URL): boolean {\n return url.protocol === 'file:';\n}\n\nasync function readFileUrl(url: URL): Promise<Uint8Array<ArrayBuffer>> {\n // `process.getBuiltinModule` (Node 20.16+, Deno, Bun) keeps `node:fs` out of browser bundles.\n const proc = (globalThis as { process?: { getBuiltinModule?: (id: string) => unknown } }).process;\n const fs = proc?.getBuiltinModule?.('node:fs/promises') as\n { readFile: (u: URL) => Promise<Uint8Array<ArrayBuffer>> } | undefined;\n if (!fs) throw new Error('libdeflate-wasm: cannot read a file: URL without node:fs');\n return fs.readFile(url);\n}\n\nasync function compile(source: WasmSource): Promise<WebAssembly.Module> {\n if (source instanceof WebAssembly.Module) return source;\n if (typeof source === 'string' || source instanceof URL) {\n const url = new URL(source, typeof source === 'string' ? defaultUrl() : undefined);\n if (isNodeFileUrl(url)) return WebAssembly.compile(await readFileUrl(url));\n return compile(await fetch(url));\n }\n if (source instanceof Response) {\n if (!source.ok) throw new Error(`libdeflate-wasm: fetching the wasm failed (${source.status})`);\n if (\n typeof WebAssembly.compileStreaming === 'function' &&\n source.headers.get('content-type')?.startsWith('application/wasm')\n ) {\n return WebAssembly.compileStreaming(source);\n }\n return WebAssembly.compile(await source.arrayBuffer());\n }\n return WebAssembly.compile(source);\n}\n\nfunction attach(module: WebAssembly.Module): void {\n // The first instance wins: cached compressor pointers belong to it.\n if (wasm) return;\n const instance = new WebAssembly.Instance(module, imports);\n const exports = instance.exports as unknown as Exports;\n exports._initialize();\n wasm = exports;\n}\n\n/**\n * Loads and instantiates the wasm module. Safe to call many times; later calls return the first\n * promise. Without an argument the file next to this module (`libdeflate.wasm`) is used.\n */\nexport function init(source?: WasmSource): Promise<void> {\n if (wasm) return Promise.resolve();\n pending ??= compile(source ?? defaultUrl()).then(attach, (error: unknown) => {\n if (wasm) return; // `initSync` won the race; this load is no longer needed\n pending = undefined;\n throw error;\n });\n return pending;\n}\n\n/** Synchronous `init` for callers that already hold the bytes or a compiled module. */\nexport function initSync(source: BufferSource | WebAssembly.Module): void {\n if (wasm) return;\n attach(source instanceof WebAssembly.Module ? source : new WebAssembly.Module(source));\n // A later or still pending `init()` resolves without creating a second instance.\n pending ??= Promise.resolve();\n}\n\n/** True once `init` or `initSync` has finished. */\nexport function isReady(): boolean {\n return wasm !== undefined;\n}\n\nfunction api(): Exports {\n if (!wasm) throw new Error('libdeflate-wasm: call `await init()` before compressing');\n return wasm;\n}\n\nfunction checkInput(data: Uint8Array): void {\n if (!(data instanceof Uint8Array)) {\n throw new TypeError('libdeflate-wasm: data must be a Uint8Array');\n }\n if (data.length > MAX_INPUT) {\n throw new RangeError(`libdeflate-wasm: input is larger than ${MAX_INPUT} bytes`);\n }\n}\n\nfunction compressor(w: Exports, level: number): number {\n if (!Number.isInteger(level) || level < 0 || level > MAX_LEVEL) {\n throw new RangeError(`libdeflate-wasm: level must be an integer from 0 to ${MAX_LEVEL}`);\n }\n let c = compressors.get(level);\n if (c === undefined) {\n // Pointers are unsigned: above 2 GiB an i32 result arrives in JS as a negative number.\n c = w.libdeflate_alloc_compressor(level) >>> 0;\n if (!c) throw new RangeError('libdeflate-wasm: out of memory allocating the compressor');\n compressors.set(level, c);\n }\n return c;\n}\n\nfunction alloc(w: Exports, n: number): number {\n const p = w.malloc(Math.max(n, 1)) >>> 0;\n if (!p) throw new RangeError(`libdeflate-wasm: out of memory allocating ${n} bytes`);\n return p;\n}\n\nfunction compress(format: Format, data: Uint8Array, level: number): Uint8Array {\n checkInput(data);\n const w = api();\n const c = compressor(w, level);\n const bound = w[`libdeflate_${format}_compress_bound`](c, data.length) >>> 0;\n const input = alloc(w, data.length);\n let output = 0;\n try {\n output = alloc(w, bound);\n new Uint8Array(w.memory.buffer, input, data.length).set(data);\n const size = w[`libdeflate_${format}_compress`](c, input, data.length, output, bound) >>> 0;\n if (size === 0) throw new Error('libdeflate-wasm: compression failed');\n return new Uint8Array(w.memory.buffer, output, size).slice();\n } finally {\n w.free(input);\n if (output) w.free(output);\n }\n}\n\n/** Raw DEFLATE (RFC 1951), no header or checksum. */\nexport function deflate(data: Uint8Array, level: number = DEFAULT_LEVEL): Uint8Array {\n return compress('deflate', data, level);\n}\n\n/** zlib stream (RFC 1950): what PDF `/FlateDecode` and PNG `IDAT` expect. */\nexport function zlib(data: Uint8Array, level: number = DEFAULT_LEVEL): Uint8Array {\n return compress('zlib', data, level);\n}\n\n/** gzip member (RFC 1952) with an empty header (no name, mtime 0), like `libdeflate-gzip -c`. */\nexport function gzip(data: Uint8Array, level: number = DEFAULT_LEVEL): Uint8Array {\n return compress('gzip', data, level);\n}\n\nfunction gzipSizeHint(data: Uint8Array): number | undefined {\n if (data.length < 18) return undefined;\n const n = data.length;\n return (data[n - 4]! | (data[n - 3]! << 8) | (data[n - 2]! << 16) | (data[n - 1]! << 24)) >>> 0;\n}\n\nfunction decompress(format: Format, data: Uint8Array, size?: number): Uint8Array {\n checkInput(data);\n if (size !== undefined && (!Number.isInteger(size) || size < 0)) {\n throw new RangeError('libdeflate-wasm: size must be a non-negative integer');\n }\n if (size !== undefined && size > MAX_OUTPUT) {\n throw new RangeError(`libdeflate-wasm: size must be at most ${MAX_OUTPUT} bytes`);\n }\n const w = api();\n if (!decompressor) {\n decompressor = w.libdeflate_alloc_decompressor() >>> 0;\n if (!decompressor) throw new RangeError('libdeflate-wasm: out of memory');\n }\n const exact = size !== undefined;\n // Size hints (the caller's `size`, the gzip ISIZE trailer) are trusted only up to what the\n // input can possibly decode to, so a 100-byte corrupt stream cannot reserve gigabytes.\n const plausible = Math.min(data.length * MAX_RATIO + 1024, MAX_OUTPUT);\n const limit = exact ? Math.min(size, plausible) : plausible;\n const gzipHint = format === 'gzip' ? gzipSizeHint(data) : undefined;\n const hint = size ?? (gzipHint !== undefined && gzipHint <= plausible ? gzipHint : undefined);\n let avail = Math.min(Math.max(hint ?? data.length * 4, 1024), limit);\n const actualAt = (data.length + 3) & ~3; // 4-byte slot after the input for the output length\n const input = alloc(w, actualAt + 4);\n const actual = input + actualAt;\n try {\n new Uint8Array(w.memory.buffer, input, data.length).set(data);\n for (;;) {\n const output = alloc(w, avail);\n try {\n const run = w[`libdeflate_${format}_decompress`];\n const status = run(decompressor, input, data.length, output, avail, actual);\n if (status === DECOMPRESS_SUCCESS) {\n const n = new DataView(w.memory.buffer).getUint32(actual, true);\n if (exact && n !== size)\n throw new Error(`libdeflate-wasm: expected ${size} bytes, got ${n}`);\n return new Uint8Array(w.memory.buffer, output, n).slice();\n }\n if (status !== DECOMPRESS_INSUFFICIENT_SPACE || avail >= limit) {\n throw new Error(\n status !== DECOMPRESS_INSUFFICIENT_SPACE\n ? `libdeflate-wasm: invalid ${format} data`\n : exact\n ? 'libdeflate-wasm: output larger than the given size'\n : `libdeflate-wasm: output larger than ${limit} bytes`,\n );\n }\n } finally {\n w.free(output);\n }\n avail = Math.min(avail * 2, limit);\n }\n } finally {\n w.free(input);\n }\n}\n\n/**\n * Decompresses raw DEFLATE. Pass `size` when the exact output length is known (faster).\n * Decoding stops at the end of the first stream; bytes after it are ignored.\n */\nexport function inflate(data: Uint8Array, size?: number): Uint8Array {\n return decompress('deflate', data, size);\n}\n\n/** Decompresses a zlib stream. Bytes after its Adler-32 are ignored (PDF streams often have an EOL). */\nexport function unzlib(data: Uint8Array, size?: number): Uint8Array {\n return decompress('zlib', data, size);\n}\n\n/** Decompresses the first gzip member; further members and trailing bytes are ignored. */\nexport function gunzip(data: Uint8Array, size?: number): Uint8Array {\n return decompress('gzip', data, size);\n}\n\n/**\n * Frees the cached compressors and decompressor (levels 10 to 12 hold about 8.6 MB each). wasm\n * memory never shrinks, but freed space is reused by later calls.\n */\nexport function release(): void {\n if (!wasm) return;\n for (const c of compressors.values()) wasm.libdeflate_free_compressor(c);\n compressors.clear();\n if (decompressor) wasm.libdeflate_free_decompressor(decompressor);\n decompressor = 0;\n}\n"]}
Binary file
package/package.json CHANGED
@@ -1,6 +1,85 @@
1
1
  {
2
2
  "name": "libdeflate-wasm",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "libdeflate compiled to WebAssembly: DEFLATE, zlib and gzip at levels 0 to 12, smaller than zlib level 9 and synchronous after one init. Zero dependencies, browsers, Web Workers and Node.",
5
+ "keywords": [
6
+ "libdeflate",
7
+ "deflate",
8
+ "zlib",
9
+ "gzip",
10
+ "inflate",
11
+ "compression",
12
+ "wasm",
13
+ "webassembly",
14
+ "pdf",
15
+ "flate",
16
+ "browser",
17
+ "worker"
18
+ ],
19
+ "homepage": "https://konvetto.com/pdf/compress-pdf",
20
+ "bugs": {
21
+ "url": "https://github.com/Konvetto/libdeflate-wasm/issues"
22
+ },
23
+ "repository": {
24
+ "type": "git",
25
+ "url": "git+https://github.com/Konvetto/libdeflate-wasm.git"
26
+ },
27
+ "license": "MIT",
28
+ "author": "Konvetto (https://konvetto.com)",
29
+ "type": "module",
30
+ "sideEffects": false,
31
+ "exports": {
32
+ ".": {
33
+ "types": "./dist/index.d.ts",
34
+ "default": "./dist/index.js"
35
+ },
36
+ "./libdeflate.wasm": "./dist/libdeflate.wasm",
37
+ "./package.json": "./package.json"
38
+ },
39
+ "types": "./dist/index.d.ts",
40
+ "files": [
41
+ "dist",
42
+ "CHANGELOG.md",
43
+ "THIRD_PARTY_NOTICES.md"
44
+ ],
45
+ "engines": {
46
+ "node": ">=20.16"
47
+ },
48
+ "packageManager": "pnpm@12.21.0",
49
+ "publishConfig": {
50
+ "access": "public",
51
+ "provenance": true
52
+ },
53
+ "scripts": {
54
+ "build": "tsup",
55
+ "build:wasm": "./scripts/build-wasm.sh",
56
+ "vendor:verify": "./scripts/fetch-libdeflate.sh --verify",
57
+ "typecheck": "tsc --noEmit",
58
+ "lint": "eslint . && prettier --check .",
59
+ "format": "prettier --write .",
60
+ "test": "vitest run",
61
+ "test:coverage": "vitest run --coverage",
62
+ "size": "size-limit",
63
+ "publint": "publint --strict",
64
+ "attw": "attw --pack . --profile esm-only --exclude-entrypoints libdeflate.wasm",
65
+ "check": "pnpm typecheck && pnpm lint && pnpm test && pnpm build && pnpm publint && pnpm attw && pnpm size",
66
+ "bench": "tsx bench/run.ts",
67
+ "prepublishOnly": "pnpm check"
68
+ },
69
+ "devDependencies": {
70
+ "@arethetypeswrong/cli": "0.18.5",
71
+ "@size-limit/preset-small-lib": "14.3.0",
72
+ "@types/node": "24.19.2",
73
+ "@vitest/coverage-v8": "5.1.0",
74
+ "eslint": "10.15.0",
75
+ "fflate": "0.8.3",
76
+ "prettier": "3.10.1",
77
+ "publint": "0.3.25",
78
+ "size-limit": "14.3.0",
79
+ "tsup": "8.5.1",
80
+ "tsx": "4.23.15",
81
+ "typescript": "6.0.3",
82
+ "typescript-eslint": "8.72.2",
83
+ "vitest": "5.1.0"
84
+ }
85
+ }