zstd.ts

1.1 KB · raw

1/**2 * Thin wrapper around @bokuweb/zstd-wasm that defers WASM load until the3 * first compress/decompress call and memoises the init promise.4 *5 * The WASM binary lives alongside the package's ESM entrypoint, so Vite's6 * default asset handling picks it up. The extension's CSP already allows7 * `wasm-unsafe-eval` for the existing hash-wasm Argon2id module.8 */910import {11  compress as zstdCompress,12  decompress as zstdDecompress,13  init as zstdInit,14} from "@bokuweb/zstd-wasm";1516let initPromise: Promise<void> | null = null;1718function ensureInit(): Promise<void> {19  if (!initPromise) {20    initPromise = zstdInit().catch((err) => {21      initPromise = null;22      throw err;23    });24  }25  return initPromise;26}2728/** Compress bytes with zstd at the given level (default 19 per spec §4.1). */29export async function compressZstd(bytes: Uint8Array, level = 19): Promise<Uint8Array> {30  await ensureInit();31  return zstdCompress(bytes, level);32}3334/** Decompress a zstd frame. Throws if the frame is malformed. */35export async function decompressZstd(bytes: Uint8Array): Promise<Uint8Array> {36  await ensureInit();37  return zstdDecompress(bytes);38}