1
import brotliPromise from 'brotli-wasm';
6
export class StrCompressor {
11
compress(buf: Uint8Array, options?: any): Uint8Array;
12
decompress(buf: Uint8Array): Uint8Array;
15
async init(): Promise<void> {
16
this.instance = await brotliPromise;
24
compress(str: string): string {
25
const input = new TextEncoder().encode(str);
27
const compressedData = this.instance.compress(input);
29
return this.urlSafeBase64Encode(compressedData);
37
decompress(str: string): string {
38
const compressedData = this.urlSafeBase64Decode(str);
40
const decompressedData = this.instance.decompress(compressedData);
42
return new TextDecoder().decode(decompressedData);
50
async compressAsync(str: string) {
51
const brotli = await brotliPromise;
53
const input = new TextEncoder().encode(str);
55
const compressedData = brotli.compress(input);
57
return this.urlSafeBase64Encode(compressedData);
65
async decompressAsync(str: string) {
66
const brotli = await brotliPromise;
68
const compressedData = this.urlSafeBase64Decode(str);
70
const decompressedData = brotli.decompress(compressedData);
72
return new TextDecoder().decode(decompressedData);
75
private urlSafeBase64Encode = (data: Uint8Array): string => {
76
const base64Str = btoa(String.fromCharCode(...data));
77
return base64Str.replaceAll('+', '_0_').replaceAll('/', '_').replace(/=+$/, '');
80
private urlSafeBase64Decode = (data: string): Uint8Array => {
81
let after = data.replaceAll('_0_', '+').replaceAll('_', '/');
82
while (after.length % 4) {
86
return new Uint8Array([...atob(after)].map((c) => c.charCodeAt(0)));
90
export const Compressor = new StrCompressor();