|
| 1 | +// The structure is from the MDN docs: https://developer.mozilla.org/en-US/docs/Web/API/TransformStream |
| 2 | + |
| 3 | +import type { CompressStream, BrotliWasmType } from 'brotli-wasm' |
| 4 | + |
| 5 | +interface BrotliCompressTransformer extends Transformer<Uint8Array, Uint8Array> { |
| 6 | + brotliWasm: BrotliWasmType |
| 7 | + outputSize: number |
| 8 | + stream: CompressStream |
| 9 | +} |
| 10 | + |
| 11 | +const brotliCompressTransformerBuilder: ( |
| 12 | + brotliWasm: BrotliWasmType, |
| 13 | + outputSize: number, |
| 14 | + quality?: number |
| 15 | +) => BrotliCompressTransformer = (brotliWasm, outputSize, quality) => ({ |
| 16 | + brotliWasm, |
| 17 | + outputSize, |
| 18 | + stream: new brotliWasm.CompressStream(quality), |
| 19 | + start() {}, |
| 20 | + transform(chunk, controller) { |
| 21 | + do { |
| 22 | + const inputOffset = this.stream.last_input_offset() |
| 23 | + const input = chunk.slice(inputOffset) |
| 24 | + const output = this.stream.compress(input, this.outputSize) |
| 25 | + controller.enqueue(output) |
| 26 | + } while (this.stream.result() === brotliWasm.BrotliStreamResult.NeedsMoreOutput) |
| 27 | + if (this.stream.result() !== brotliWasm.BrotliStreamResult.NeedsMoreInput) { |
| 28 | + controller.error(`Brotli compression failed when transforming with error code ${this.stream.result()}`) |
| 29 | + } |
| 30 | + }, |
| 31 | + flush(controller) { |
| 32 | + do { |
| 33 | + const output = this.stream.compress(undefined, this.outputSize) |
| 34 | + controller.enqueue(output) |
| 35 | + } while (this.stream.result() === brotliWasm.BrotliStreamResult.NeedsMoreOutput) |
| 36 | + if (this.stream.result() !== brotliWasm.BrotliStreamResult.ResultSuccess) { |
| 37 | + controller.error(`Brotli compression failed when flushing with error code ${this.stream.result()}`) |
| 38 | + } |
| 39 | + }, |
| 40 | +}) |
| 41 | + |
| 42 | +export class BrotliCompressTransformStream extends TransformStream<Uint8Array, Uint8Array> { |
| 43 | + constructor(brotliWasm: BrotliWasmType, outputSize: number, quality?: number) { |
| 44 | + super(brotliCompressTransformerBuilder(brotliWasm, outputSize, quality)) |
| 45 | + } |
| 46 | +} |
0 commit comments