All files index.js

85.1% Statements 120/141
77.77% Branches 42/54
87.09% Functions 27/31
87.78% Lines 115/131

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 2761x 1x 1x 1x   1x 1x 1x 1x 1x 1x 1x   1x 1x   1x   1x       1x 1x 1x         1x 1x           21x   21x 21x 21x 21x   21x 21x     21x 5x 16x 1x 1x 1x         21x 21x 21x             21x 17x 17x 1x 1x     17x     21x       7x 7x   7x         7x             16x   16x 16x 16x   16x 5x 11x 1x 1x 1x         16x 16x 16x             16x 12x 12x         12x     16x 12x           7x 7x   7x         7x                 8x       4x 4x         3x       4x 4x                             5x 5x 5x 5x 5x   5x   5x 1x   5x 1x 1x 1x     5x     9x 9x     4x 4x       5x     9x 9x     4x 4x       5x 5x                         5x 5x 5x 5x       2x 2x       3x 3x 3x       2x 2x       3x 3x 3x       1x              
const fs = require('node:fs');
const { writeFile } = require('node:fs/promises');
const { Readable, pipeline } = require('node:stream');
const util = require('node:util');
 
const ProcessStream = require('process-streams');
const { execSync } = require('node:child_process');
const isZst = require('is-zst');
const peek = require('peek-stream');
const through = require('through2');
const { file } = require('tmp-promise');
const debug = require('debug')('SimpleZSTD');
 
const Oven = require('./oven');
const BufferWritable = require('./buffer-writable');
 
const pipelineAsync = util.promisify(pipeline);
 
const find = (process.platform === 'win32') ? 'where zstd.exe' : 'which zstd';
 
let bin;
 
try {
  bin = execSync(find, { env: process.env }).toString().replace(/\n$/, '').replace(/\r$/, '');
  debug(bin);
} catch (err) {
  throw new Error('Can not access zstd! Is it installed?');
}
 
try {
  fs.accessSync(bin, fs.constants.X_OK);
} catch (err) {
  throw new Error('zstd is not executable');
}
 
async function CreateCompressStream(compLevel, spawnOptions, streamOptions, zstdOptions, dictionary) {
  const ps = new ProcessStream();
 
  let lvl = compLevel;
  let opts = zstdOptions || [];
  let path = null;
  let cleanup = null;
 
  if (!lvl) lvl = 3;
  Iif (lvl < 1 || lvl > 22) lvl = 3;
 
  // Dictionary
  if (dictionary && dictionary.path) {
    opts = [...opts, '-D', `${dictionary.path}`]; //eslint-disable-line
  } else if (Buffer.isBuffer(dictionary)) {
    ({ path, cleanup } = await file());
    await writeFile(path, dictionary);
    opts = [...opts, '-D', `${path}`]; //eslint-disable-line
  }
 
  let c;
 
  try {
    debug(bin, ['-c', `-l${lvl}`, ...opts], spawnOptions, streamOptions);
    c = ps.spawn(bin, [`-${lvl}`, ...opts], spawnOptions, streamOptions);
  } catch (err) {
    // cleanup if error;
    if (cleanup) cleanup();
    throw err;
  }
 
  c.on('exit', (code, signal) => {
    debug('exit', code, signal);
    if (code !== 0) {
      setTimeout(() => {
        c.destroy(new Error(`zstd exited non zero. code: ${code} signal: ${signal}`));
      }, 1);
    }
    if (cleanup) cleanup();
  });
 
  return c;
}
 
function CompressBuffer(buffer, c) {
  return new Promise((resolve, reject) => {
    const w = new BufferWritable();
 
    pipelineAsync(
      Readable.from(buffer),
      c,
      w,
    )
      .then(() => resolve(w.buffer))
      .catch((err) => reject(err));
  });
}
 
async function CreateDecompressStream(spawnOptions, streamOptions, zstdOptions, dictionary) {
  // Dictionary
  const ps = new ProcessStream();
 
  let opts = zstdOptions || [];
  let path = null;
  let cleanup = null;
 
  if (dictionary && dictionary.path) {
    opts = [...opts, '-D', `${dictionary.path}`]; //eslint-disable-line
  } else if (Buffer.isBuffer(dictionary)) {
    ({ path, cleanup } = await file());
    await writeFile(path, dictionary);
    opts = [...opts, '-D', `${path}`]; //eslint-disable-line
  }
 
  let d;
 
  try {
    debug(bin, ['-d', ...opts], spawnOptions, streamOptions);
    d = ps.spawn(bin, ['-d', ...opts], spawnOptions, streamOptions);
  } catch (err) {
    // cleanup if error
    if (cleanup) cleanup();
    throw err;
  }
 
  d.on('exit', (code, signal) => {
    debug('exit', code, signal);
    Iif (code !== 0) {
      setTimeout(() => {
        d.destroy(new Error(`zstd exited non zero. code: ${code} signal: ${signal}`));
      }, 1);
    }
    if (cleanup) cleanup();
  });
 
  return peek({ newline: false, maxBuffer: 10 }, (data, swap) => {
    Eif (isZst(data)) return swap(null, d);
    return swap(null, through());
  });
}
 
function DecompressBuffer(buffer, d) {
  return new Promise((resolve, reject) => {
    const w = new BufferWritable();
 
    pipelineAsync(
      Readable.from(buffer),
      d,
      w,
    )
      .then(() => resolve(w.buffer))
      .catch((err) => reject(err));
  });
}
 
// Standalone Functions
 
function compress(compLevel, spawnOptions, streamOptions, zstdOptions, dictionary) {
  // Returns a promise
  return CreateCompressStream(compLevel, spawnOptions, streamOptions, zstdOptions, dictionary);
}
 
async function compressBuffer(buffer, compLevel, spawnOptions, streamOptions, zstdOptions, dictionary) {
  const c = await CreateCompressStream(compLevel, spawnOptions, streamOptions, zstdOptions, dictionary);
  return CompressBuffer(buffer, c);
}
 
function decompress(spawnOptions, streamOptions, zstdOptions, dictionary) {
  // Returns a promise
  return CreateDecompressStream(spawnOptions, streamOptions, zstdOptions, dictionary);
}
 
async function decompressBuffer(buffer, spawnOptions, streamOptions, zstdOptions, dictionary) {
  const d = await CreateDecompressStream(spawnOptions, streamOptions, zstdOptions, dictionary);
  return DecompressBuffer(buffer, d);
}
 
// SimpleZSTD Class
class SimpleZSTD {
  #compressOven;
 
  #decompressOven;
 
  #bufferFileCleanup;
 
  #ready;
 
  constructor(poolOptions, compLevel, spawnOptions, streamOptions, zstdOptions, dictionary) {
    // Use a guard in all function to complete the async dictionary loading
    debug('constructor', poolOptions, compLevel, spawnOptions, streamOptions, zstdOptions, dictionary);
    const poolOpts = poolOptions || {};
    this.#ready = new Promise(async (resolve, reject) => {
      let path = null;
      let cleanup = null;
 
      try {
        // Convert buffer or dictionary.path to path
        if (dictionary && dictionary.path) {
          path = dictionary.path;
        }
        if (dictionary && Buffer.isBuffer(dictionary)) {
          ({ path, cleanup } = await file());
          this.#bufferFileCleanup = cleanup;
          await writeFile(path, dictionary);
        }
 
        this.#compressOven = new Oven(
          poolOpts.compressQueueSize,
          (() => {
            debug('compress factory');
            return CreateCompressStream(compLevel, spawnOptions, streamOptions, zstdOptions, { path });
          }),
          async (p) => {
            debug('compress cleanup');
            (await p).kill();
          },
        );
 
        this.#decompressOven = new Oven(
          poolOpts.decompressQueueSize,
          (() => {
            debug('decompress factory');
            return CreateDecompressStream(spawnOptions, streamOptions, zstdOptions, { path });
          }),
          async (p) => {
            debug('decompress cleanup');
            (await p).kill();
          },
        );
 
        debug('READY');
        resolve();
      } catch (err) {
        if (cleanup) cleanup();
        reject(err);
      }
    }).catch((err) => {
      debug('ready error', err);
      if (this.#bufferFileCleanup) this.#bufferFileCleanup();
      this.#bufferFileCleanup = null;
    });
  }
 
  destroy() {
    this.#compressOven.destroy();
    this.#decompressOven.destroy();
    if (this.#bufferFileCleanup) this.#bufferFileCleanup();
    this.#bufferFileCleanup = null;
  }
 
  async compress() {
    await this.#ready;
    return this.#compressOven.acquire();
  }
 
  async compressBuffer(buffer) {
    await this.#ready;
    const c = await this.#compressOven.acquire();
    return CompressBuffer(buffer, c);
  }
 
  async decompress() {
    await this.#ready;
    return this.#decompressOven.acquire();
  }
 
  async decompressBuffer(buffer) {
    await this.#ready;
    const d = await this.#decompressOven.acquire();
    return DecompressBuffer(buffer, d);
  }
}
 
module.exports = {
  SimpleZSTD,
  compress,
  compressBuffer,
  decompress,
  decompressBuffer,
};