lobe-chat

Форк
0
/
compass.ts 
90 строк · 2.3 Кб
1
import brotliPromise from 'brotli-wasm';
2

3
/**
4
 * @title 字符串压缩器
5
 */
6
export class StrCompressor {
7
  /**
8
   * @ignore
9
   */
10
  private instance!: {
11
    compress(buf: Uint8Array, options?: any): Uint8Array;
12
    decompress(buf: Uint8Array): Uint8Array;
13
  };
14

15
  async init(): Promise<void> {
16
    this.instance = await brotliPromise; // Import is async in browsers due to wasm requirements!
17
  }
18

19
  /**
20
   * @title 压缩字符串
21
   * @param str - 要压缩的字符串
22
   * @returns 压缩后的字符串
23
   */
24
  compress(str: string): string {
25
    const input = new TextEncoder().encode(str);
26

27
    const compressedData = this.instance.compress(input);
28

29
    return this.urlSafeBase64Encode(compressedData);
30
  }
31

32
  /**
33
   * @title 解压缩字符串
34
   * @param str - 要解压缩的字符串
35
   * @returns 解压缩后的字符串
36
   */
37
  decompress(str: string): string {
38
    const compressedData = this.urlSafeBase64Decode(str);
39

40
    const decompressedData = this.instance.decompress(compressedData);
41

42
    return new TextDecoder().decode(decompressedData);
43
  }
44

45
  /**
46
   * @title 异步压缩字符串
47
   * @param str - 要压缩的字符串
48
   * @returns Promise
49
   */
50
  async compressAsync(str: string) {
51
    const brotli = await brotliPromise;
52

53
    const input = new TextEncoder().encode(str);
54

55
    const compressedData = brotli.compress(input);
56

57
    return this.urlSafeBase64Encode(compressedData);
58
  }
59

60
  /**
61
   * @title 异步解压缩字符串
62
   * @param str - 要解压缩的字符串
63
   * @returns Promise
64
   */
65
  async decompressAsync(str: string) {
66
    const brotli = await brotliPromise;
67

68
    const compressedData = this.urlSafeBase64Decode(str);
69

70
    const decompressedData = brotli.decompress(compressedData);
71

72
    return new TextDecoder().decode(decompressedData);
73
  }
74

75
  private urlSafeBase64Encode = (data: Uint8Array): string => {
76
    const base64Str = btoa(String.fromCharCode(...data));
77
    return base64Str.replaceAll('+', '_0_').replaceAll('/', '_').replace(/=+$/, '');
78
  };
79

80
  private urlSafeBase64Decode = (data: string): Uint8Array => {
81
    let after = data.replaceAll('_0_', '+').replaceAll('_', '/');
82
    while (after.length % 4) {
83
      after += '=';
84
    }
85

86
    return new Uint8Array([...atob(after)].map((c) => c.charCodeAt(0)));
87
  };
88
}
89

90
export const Compressor = new StrCompressor();
91

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.