/** 压缩数据 * 使用 CompressionStream API 进行数据压缩 * 支持的格式包括 'gzip', 'deflate', 'deflate-raw' */ export async function compressData( data: ArrayBuffer | Uint8Array | Blob | string, options: { format?: CompressionFormat } = {} ): Promise { const format = options.format ?? "gzip" if (typeof CompressionStream === "undefined") { throw new Error( "CompressionStream API is not available in this environment. Please run in a compatible browser or provide a polyfill." ) } const stream = new Response(data as BodyInit).body if (!stream) throw new Error("Stream not available") let compressedStream: ReadableStream try { let cs: CompressionStream try { // 创建 CompressionStream 可能在不支持的格式上抛出 cs = new CompressionStream(format) } catch (err: any) { throw new Error(`Failed to construct CompressionStream for format "${format}": ${err?.message ?? err}`) } try { compressedStream = stream.pipeThrough(cs) } catch (err: any) { throw new Error( `Compression failed while piping through CompressionStream (format="${format}"): ${err?.message ?? err}` ) } } catch (err) { // 统一抛出可读的错误信息 throw err } return new Response(compressedStream).arrayBuffer() } /** 解压数据 * 使用 DecompressionStream API 进行数据解压 * 支持的格式包括 'gzip', 'deflate', 'deflate-raw' */ export async function decompressData( data: ArrayBuffer | Uint8Array | Blob, options: { format?: CompressionFormat } = {} ): Promise { const format = options.format ?? "gzip" if (typeof DecompressionStream === "undefined") { throw new Error( "DecompressionStream API is not available in this environment. Please run in a compatible browser or provide a polyfill." ) } const stream = new Response(data as BodyInit).body if (!stream) throw new Error("Stream not available") let decompressedStream: ReadableStream try { let ds: DecompressionStream try { ds = new DecompressionStream(format) } catch (err: any) { throw new Error(`Failed to construct DecompressionStream for format "${format}": ${err?.message ?? err}`) } try { decompressedStream = stream.pipeThrough(ds) } catch (err: any) { throw new Error( `Decompression failed while piping through DecompressionStream (format="${format}"): ${ err?.message ?? err }` ) } } catch (err) { throw err } return new Response(decompressedStream).arrayBuffer() }