// src/lib/compression.ts
import { gzipSync, gunzipSync } from "zlib";
var ENVELOPE_VERSION = 1;
var COMPRESSION_ALGOS = {
  NONE: "none",
  GZIP: "gzip",
  BROTLI: "brotli",
  DEFLATE: "deflate"
};
function isEnvelope(obj) {
  return typeof obj === "object" && obj !== null && "v" in obj && "algo" in obj && "payload" in obj && typeof obj.payload === "string";
}
function compressResource(jsonString, options) {
  const algo = options?.algo ?? COMPRESSION_ALGOS.GZIP;
  if (algo === COMPRESSION_ALGOS.NONE) {
    const envelope2 = {
      v: ENVELOPE_VERSION,
      algo: COMPRESSION_ALGOS.NONE,
      payload: jsonString
    };
    return JSON.stringify(envelope2);
  }
  const buf = Buffer.from(jsonString, "utf-8");
  const payload = gzipSync(buf).toString("base64");
  const envelope = {
    v: ENVELOPE_VERSION,
    algo: COMPRESSION_ALGOS.GZIP,
    payload
  };
  return JSON.stringify(envelope);
}
function decompressResource(compressedOrRaw) {
  try {
    const parsed = JSON.parse(compressedOrRaw);
    if (isEnvelope(parsed)) {
      if (parsed.algo === COMPRESSION_ALGOS.GZIP) {
        const buf = Buffer.from(parsed.payload, "base64");
        return gunzipSync(buf).toString("utf-8");
      }
      if (parsed.algo === COMPRESSION_ALGOS.NONE) {
        return parsed.payload;
      }
      return parsed.payload;
    }
  } catch {
  }
  try {
    const buf = Buffer.from(compressedOrRaw, "base64");
    if (buf.length >= 2 && buf[0] === 31 && buf[1] === 139) {
      return gunzipSync(buf).toString("utf-8");
    }
  } catch {
  }
  return compressedOrRaw;
}

export {
  compressResource,
  decompressResource
};
//# sourceMappingURL=chunk-APVVG7BO.mjs.map