import zlib from "zlib";
import { promisify } from "util";
const gzipAsync = promisify(zlib.gzip);
const gunzipAsync = promisify(zlib.gunzip);
const brotliCompressAsync = promisify(zlib.brotliCompress);
const brotliDecompressAsync = promisify(zlib.brotliDecompress);
var CompressionType = /* @__PURE__ */ ((CompressionType2) => {
  CompressionType2["NONE"] = "none";
  CompressionType2["GZIP"] = "gzip";
  CompressionType2["BROTLI"] = "brotli";
  return CompressionType2;
})(CompressionType || {});
async function compress(data, options = {}) {
  const { type = "gzip" /* GZIP */, level = 6 } = options;
  const input = typeof data === "string" ? Buffer.from(data, "utf8") : data;
  switch (type) {
    case "none" /* NONE */:
      return input;
    case "gzip" /* GZIP */:
      return gzipAsync(input, { level });
    case "brotli" /* BROTLI */:
      return brotliCompressAsync(input, {
        params: {
          [zlib.constants.BROTLI_PARAM_QUALITY]: level
        }
      });
    default:
      throw new Error(`Unknown compression type: ${type}`);
  }
}
async function decompress(data, type = "gzip" /* GZIP */) {
  let decompressed;
  switch (type) {
    case "none" /* NONE */:
      decompressed = data;
      break;
    case "gzip" /* GZIP */:
      decompressed = await gunzipAsync(data);
      break;
    case "brotli" /* BROTLI */:
      decompressed = await brotliDecompressAsync(data);
      break;
    default:
      throw new Error(`Unknown compression type: ${type}`);
  }
  return decompressed.toString("utf8");
}
function compressionRatio(original, compressed) {
  if (original === 0) return 0;
  return (1 - compressed / original) * 100;
}
function detectCompressionType(data) {
  if (data.length >= 2 && data[0] === 31 && data[1] === 139) {
    return "gzip" /* GZIP */;
  }
  if (data.length >= 4 && data[0] === 206 && data[1] === 178) {
    return "brotli" /* BROTLI */;
  }
  return "none" /* NONE */;
}
function chooseOptimalCompression(data, speedPriority = false) {
  const size = typeof data === "string" ? Buffer.byteLength(data) : data.length;
  if (size < 1024) {
    return "none" /* NONE */;
  }
  if (speedPriority || size < 100 * 1024) {
    return "gzip" /* GZIP */;
  }
  return "brotli" /* BROTLI */;
}
export {
  CompressionType,
  chooseOptimalCompression,
  compress,
  compressionRatio,
  decompress,
  detectCompressionType
};
//# sourceMappingURL=compression.js.map
