* Helper function to compress data sent over the network.
(data: object)
| 133 | * Helper function to compress data sent over the network. |
| 134 | */ |
| 135 | async function compressData(data: object): Promise<Uint8Array | string> { |
| 136 | if (compressionMethod === 'none') { |
| 137 | // If no compression is used, we just stringify the data, |
| 138 | // PeerJS will compress it to binary data. |
| 139 | const jsonString = JSON.stringify(data); |
| 140 | return jsonString; |
| 141 | } |
| 142 | |
| 143 | const compressionStreamFormat = |
| 144 | compressionMethod === 'cs:gzip' ? 'gzip' : 'deflate'; |
| 145 | |
| 146 | const jsonString = JSON.stringify(data); |
| 147 | const encoder = new TextEncoder(); |
| 148 | const array = encoder.encode(jsonString); |
| 149 | |
| 150 | // @ts-ignore - We checked that CompressionStream is available in the browser. |
| 151 | const cs = new CompressionStream(compressionStreamFormat); |
| 152 | const writer = cs.writable.getWriter(); |
| 153 | writer.write(array); |
| 154 | writer.close(); |
| 155 | |
| 156 | const compressedStream = cs.readable; |
| 157 | const reader = compressedStream.getReader(); |
| 158 | const chunks: any[] = []; |
| 159 | |
| 160 | while (true) { |
| 161 | const { done, value } = await reader.read(); |
| 162 | if (done) break; |
| 163 | chunks.push(value); |
| 164 | } |
| 165 | |
| 166 | const compressedData = new Uint8Array( |
| 167 | chunks.reduce((acc, chunk) => acc.concat(Array.from(chunk)), []) |
| 168 | ); |
| 169 | return compressedData; |
| 170 | } |
| 171 | |
| 172 | /** |
| 173 | * Helper function to decompress data received over the network. |