Skip to content

Instantly share code, notes, and snippets.

@andy0130tw
Last active July 19, 2026 16:41
Show Gist options
  • Select an option

  • Save andy0130tw/1e563a1480db1d1810876b143a6be7a0 to your computer and use it in GitHub Desktop.

Select an option

Save andy0130tw/1e563a1480db1d1810876b143a6be7a0 to your computer and use it in GitHub Desktop.
WTF am I doing
type U8Arr = Uint8Array<ArrayBuffer>
class MaybeUnzipGzipTransformer implements Transformer<U8Arr, U8Arr> {
nbytes = 0
isGzip: boolean | null = null
static expectedHeader = new Uint8Array([0x1f, 0x8b, 0x08])
sink: WritableStreamDefaultWriter<U8Arr> | undefined
transform(chunk: U8Arr, controller: TransformStreamDefaultController<U8Arr>) {
if (this.isGzip == null) {
let i = 0
while (this.nbytes < 3 && i < chunk.length) {
if (MaybeUnzipGzipTransformer.expectedHeader[this.nbytes] != chunk[i]) {
this.isGzip = false
break
}
this.nbytes++
i++
}
if (this.nbytes >= 3) {
this.isGzip = true
const ds = new DecompressionStream('gzip')
this.sink = ds.writable.getWriter()
this.sink.write(MaybeUnzipGzipTransformer.expectedHeader)
this.sink.write(chunk.subarray(i))
;(async () => {
const reader = ds.readable.getReader()
while (true) {
const data = await reader.read()
if (data.done) break
controller.enqueue(data.value)
}
})
} else if (this.isGzip === false) {
controller.enqueue(MaybeUnzipGzipTransformer.expectedHeader.subarray(0, this.nbytes))
controller.enqueue(chunk.subarray(i))
}
} else if (this.isGzip) {
this.sink!.write(chunk)
} else {
controller.enqueue(chunk)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment