import { compress as brotliCompress, decompress as brotliDecompress } from 'brotli-compress'

const textEncoder = new TextEncoder()
const textDecoder = new TextDecoder()

async function compress(value: string): Promise<string> {
  const data = textEncoder.encode(value)
  const compressed = await brotliCompress(data)
  return btoa(String.fromCharCode(...compressed))
}

async function decompress(b: string): Promise<string> {
  const data = atob(b)
  const bytes = Uint8Array.from(data, (c) => c.charCodeAt(0))
  const decompressed = await brotliDecompress(bytes)
  const decoded = textDecoder.decode(decompressed)
  return decoded
}

export { compress, decompress }
