zztaeha

Functions

48 functions in kokyu 0.1.0, as the compiler exports them, filed by area. Each says what it does, what comes back and what it fails with, with an example that was type-checked and run against 0.1.0.

Every one of them takes and returns Uint8Arrays, and every failure kokyu raises itself is aKokyuError with acode to branch on. An async function's failures come back through its promise.

Deflate and zlib

Raw deflate (RFC 1951) and zlib (RFC 1950), whole or as streams. zlib wraps deflate in a 2-byte header and an Adler-32 trailer, and can name a preset dictionary. Each decoder takes a maxSize, and has an …Into form that decodes into a buffer you already own.

deflate
function deflate(data: Uint8Array, opts?: DeflateOptions): Uint8Array<ArrayBuffer>

Compresses bytes to raw deflate (RFC 1951), the format inside zlib, gzip and zip.

It comes back as a new Uint8Array that owns its whole ArrayBuffer. The input is only read: never changed, and not kept once the call returns.

Raw deflate has no header and no checksum, so nothing in it says what it is or how long it decodes to: a reader has to know to decode it with inflate, and decompress falls back to it. Use zlib or gzip where the data has to identify itself.

Each block goes out the smallest of three ways: stored as it is, with deflate's fixed codes, or with codes built for it. So data that doesn't compress grows by only a few bytes for every 16 KB. The same bytes, level and dictionary always give the same output, and deflateStream gives it too, however you split the input, unless you flush the stream. At level 0 a stream can end in one more empty block.

It fails only with invalid-option: when the input isn't a readable Uint8Array (a Node Buffer is one), the level isn't a whole number from 0 to 9, or the dictionary isn't a Uint8Array. deflateAsync does the same off the main thread.

import { deflate, encodeText, inflate } from 'kokyu'

const text = encodeText('hello, hello, hello, hello') // 26 bytes
const packed = deflate(text) // 11 bytes
inflate(packed) // the 26 bytes again

deflate(text, { level: 0 }) // 31 bytes: the text as it is, with 5 bytes of framing
deflate(new Uint8Array(0)) // 2 bytes: one empty block
  • Fails with: invalid-option.
inflate
function inflate(data: Uint8Array, opts?: InflateOptions): Uint8Array<ArrayBuffer>

Decompresses raw deflate data.

It comes back as a new Uint8Array that owns its whole ArrayBuffer. Decoding stops where the deflate data ends, after its last block, and any bytes after that are ignored.

It fails with truncated when the data ends before its last block does, invalid-data when it breaks the format's rules, and too-large once the output would pass InflateOptions.maxSize. Raw deflate carries no checksum, so damage that still follows the rules decodes to wrong bytes without failing.

Set maxSize for input you don't trust: a few kilobytes of deflate can decode to gigabytes. With a cap the decode stops as soon as the output would pass it, so memory stays on the order of the cap, whatever the data would decode to. There is no cap by default.

Data compressed with a dictionary needs the same one in InflateOptions.dictionary. To decode into a buffer you already have, use inflateInto; for data that arrives in pieces, inflateStream; off the main thread, inflateAsync.

import { KokyuError, decodeText, deflate, encodeText, inflate } from 'kokyu'

const packed = deflate(encodeText('hello, hello, hello, hello'))
decodeText(inflate(packed)) // 'hello, hello, hello, hello'

try {
  inflate(packed, { maxSize: 20 })
} catch (e) {
  if (e instanceof KokyuError) e.code // 'too-large': the output is 26 bytes
}
  • Fails with: truncated, invalid-data, too-large, invalid-option.
inflateInto
function inflateInto<B extends ArrayBufferLike>(data: Uint8Array, out: Uint8Array<B>, opts?: InflateOptions): Uint8Array<B>

Decompresses raw deflate data into a buffer you own, and returns the part of it that holds the output.

The result is a view of out from its start, as long as the output, and typed by out's buffer: a view of a SharedArrayBuffer comes back typed as one. Nothing past the output's end is written. The next decode into the same buffer overwrites it, so copy a result you need to keep.

Output that doesn't fit in out fails with too-large, and so does output past InflateOptions.maxSize: the smaller of the two is the cap. A call that fails may already have written part of the output into out. Every other failure is the same as for inflate.

out has to be a readable Uint8Array. Anything else, a missing one included, fails with invalid-option rather than falling back to allocating. Input that shares memory with out is copied first, so it still decodes right.

Without a dictionary the output is decoded straight into out. With one it is decoded into a buffer of kokyu's own and copied into out at the end, still capped at its length.

import { deflate, encodeText, inflateInto } from 'kokyu'

const buffer = new Uint8Array(64 * 1024) // reused for every decode
const packed = deflate(encodeText('hello, hello, hello, hello'))
const view = inflateInto(packed, buffer) // 26 bytes: the start of buffer, nothing copied

try {
  inflateInto(packed, new Uint8Array(16))
} catch {
  // KokyuError 'too-large': 26 bytes don't fit in 16
}
  • Fails with: truncated, invalid-data, too-large, invalid-option.
zlib
function zlib(data: Uint8Array, opts?: DeflateOptions): Uint8Array<ArrayBuffer>

Compresses bytes to zlib (RFC 1950): raw deflate between a 2-byte header and the Adler-32 of the input.

It comes back as a new Uint8Array that owns its whole ArrayBuffer: the header, the same bytes deflate gives for the input and options, then the input's adler32 in 4 bytes, big-endian. So it is 6 bytes longer than raw deflate, or 10 with a dictionary.

The header records a rough level, which no decoder needs: 78 01 for levels 0 and 1, 78 5E for 2 to 5, 78 9C for 6 and 78 DA for 7 to 9.

With a DeflateOptions.dictionary that isn't empty, the header grows to 6 bytes and carries the dictionary's Adler-32, and unzlib needs the same dictionary to read the data. An empty dictionary counts as none.

It fails only with invalid-option, as deflate does. zlibStream makes the same bytes from input in pieces, and zlibAsync off the main thread.

import { adler32, deflate, encodeText, zlib } from 'kokyu'

const text = encodeText('hello, hello, hello, hello')
const packed = zlib(text) // 17 bytes: a 2-byte header, 11 of deflate, a 4-byte Adler-32
packed.subarray(0, 2) // 78 9C, the header for level 6

const trailer = new DataView(packed.buffer).getUint32(packed.length - 4) // adler32(text)
  • Fails with: invalid-option.
unzlib
function unzlib(data: Uint8Array, opts?: InflateOptions): Uint8Array<ArrayBuffer>

Decompresses zlib data.

It comes back as a new Uint8Array that owns its whole ArrayBuffer. Bytes after the 4-byte trailer are ignored.

The header is checked: data that doesn't start with a valid zlib header fails with invalid-header. The trailer has to be there, or the call fails with truncated, but its Adler-32 isn't checked. Call adler32 on the output to verify it yourself.

Data compressed with a preset dictionary names it in its header. Without InflateOptions.dictionary, or with a different one, the call fails with invalid-option. A dictionary handed in for data that names none is ignored.

Otherwise it fails as inflate does, too-large included once the output would pass InflateOptions.maxSize. unzlibInto decodes into a buffer you already have, unzlibStream decodes data that arrives in pieces, and unzlibAsync works off the main thread.

import { adler32, encodeText, unzlib, zlib } from 'kokyu'

const packed = zlib(encodeText('hello, hello, hello, hello'))
const text = unzlib(packed, { maxSize: 1 << 20 }) // 26 bytes

// The trailer isn't checked: compare it yourself where it matters
const trailer = new DataView(packed.buffer).getUint32(packed.length - 4)
trailer === adler32(text) // true
  • Fails with: truncated, invalid-data, invalid-header, too-large, invalid-option.
unzlibInto
function unzlibInto<B extends ArrayBufferLike>(data: Uint8Array, out: Uint8Array<B>, opts?: InflateOptions): Uint8Array<B>

Decompresses zlib data into a buffer you own, and returns the part of it that holds the output.

It reads zlib as unzlib does, and writes the output as inflateInto does: the result is a view of out from its start, as long as the output, and the next decode into the same buffer overwrites it.

Output that doesn't fit in out fails with too-large, and so does output past InflateOptions.maxSize: the smaller of the two is the cap. A call that fails may already have written part of the output into out. An out that isn't a readable Uint8Array fails with invalid-option. Input that shares memory with out is copied first, so it still decodes right.

import { decodeText, encodeText, unzlibInto, zlib } from 'kokyu'

const buffer = new Uint8Array(1024)
for (const word of ['hello', 'world']) {
  const view = unzlibInto(zlib(encodeText(word)), buffer) // the first 5 bytes of buffer
  decodeText(view) // 'hello', then 'world'
}
  • Fails with: truncated, invalid-data, invalid-header, too-large, invalid-option.
deflateStream
function deflateStream(opts?: DeflateOptions): CompressStream

Compresses to raw deflate as a stream: push input in pieces, and take output as it is ready.

Each CompressStream.push returns the output its input completed, and that is often nothing: output waits until a block fills, which can take hundreds of kilobytes of input that compresses well. CompressStream.flush returns everything pushed so far as output a decoder can read in full, without ending the stream. CompressStream.finish takes an optional last chunk and returns the rest.

Every array it returns is new and never written to again. Each chunk is copied in, so you can reuse its buffer once push returns. Put together, the outputs are the bytes deflate gives for all the input at once, however you split it, unless you flushed. At level 0 they can end in one more empty block, 5 bytes.

The level and dictionary are checked and taken when the stream is made, and fail there with invalid-option. A chunk that isn't a readable Uint8Array fails with invalid-option and leaves the stream as it was. After finish, every call fails with invalid-state, flush included.

toTransformStream turns it into a web TransformStream, and deflateStreamAsync runs one in a worker.

import { decodeText, deflateStream, encodeText, inflateStream } from 'kokyu'

const writer = deflateStream()
const reader = inflateStream()

const first = writer.push(encodeText('first line\n')) // 0 bytes: output waits for a full block
const flushed = writer.flush() // everything pushed so far, decodable now
decodeText(reader.push(flushed)) // 'first line\n'

const last = writer.finish(encodeText('last line\n'))
decodeText(reader.finish(last)) // 'last line\n'
  • Fails with: invalid-option, invalid-state.
inflateStream
function inflateStream(opts?: InflateOptions): Stream

Decompresses raw deflate as a stream: push compressed pieces of any size, and get back what each completes.

Each Stream.push returns the output its chunk completed, possibly none, as a new array that is never written to again. A piece of deflate cut off by the end of a chunk is decoded again from its start when the next one arrives. Only that cut-off part is kept, as a copy, so you can reuse a chunk's buffer once push returns.

Once the last block ends, later bytes are ignored and pushes return empty arrays. Stream.finish takes an optional last chunk, and fails with truncated if the data still hasn't ended.

The stream holds the last 32 KB of output, which later matches may refer back to, besides any cut-off input. InflateOptions.maxSize counts all the output, across every push. The dictionary is copied when the stream is made.

A call that fails on the data, with invalid-data, too-large or truncated, breaks the stream: every later call throws that same error. A chunk that isn't a readable Uint8Array fails with invalid-option and leaves the stream as it was. After a finish that succeeded, every call fails with invalid-state.

import { deflate, inflateStream } from 'kokyu'

const packed = deflate(new Uint8Array(100_000).fill(65)) // 100,000 bytes of 'A'
const stream = inflateStream({ maxSize: 1_000_000 })
let size = 0
for (let at = 0; at < packed.length; at += 16) size += stream.push(packed.subarray(at, at + 16)).length
size += stream.finish().length
size // 100000
  • Fails with: truncated, invalid-data, too-large, invalid-option, invalid-state.
zlibStream
function zlibStream(opts?: DeflateOptions): CompressStream

Compresses to zlib as a stream.

It works as deflateStream does, with the zlib header in front of the first output and the Adler-32 of all the input after the last. So the first push returns at least the 2-byte header, even when the data in it waits for a full block.

Put together, the outputs are the bytes zlib gives for all the input at once, however you split it, with the same exceptions as for deflateStream: a flush, or one more empty block at level 0. CompressStream.flush returns everything so far as zlib a decoder can read up to that point.

The level and dictionary are checked and taken when the stream is made, and the header is built from them then. It fails as deflateStream does.

import { encodeText, unzlib, zlib, zlibStream } from 'kokyu'

const stream = zlibStream()
const head = stream.push(encodeText('hello, ')) // 2 bytes: the header, while the data waits
const rest = stream.finish(encodeText('hello, hello, hello'))
const whole = new Uint8Array([...head, ...rest]) // what zlib() gives for all 26 bytes
unzlib(whole) // the 26 bytes
  • Fails with: invalid-option, invalid-state.
unzlibStream
function unzlibStream(opts?: InflateOptions): Stream

Decompresses zlib as a stream.

It reads the header once its bytes are in, 2 of them or 6 when it names a dictionary, and checks it as unzlib does: a bad header fails with invalid-header, and a missing or different dictionary with invalid-option, from the call that completes it. Then it decodes as inflateStream does, with the same rules for what each push returns and what it keeps.

The 4-byte trailer has to arrive before Stream.finish, which otherwise fails with truncated. Its Adler-32 isn't checked, and bytes after it are ignored.

The dictionary is copied when the stream is made. A failed call breaks the stream as it does inflateStream, and after finish every call fails with invalid-state.

import { decodeText, encodeText, unzlibStream, zlib } from 'kokyu'

const dictionary = encodeText('hello, ')
const packed = zlib(encodeText('hello, hello, hello, hello'), { dictionary })
const stream = unzlibStream({ dictionary })
const head = stream.push(packed.subarray(0, 4)) // 0 bytes: the 6-byte header isn't all there yet
decodeText(stream.finish(packed.subarray(4))) // 'hello, hello, hello, hello'
  • Fails with: truncated, invalid-data, invalid-header, too-large, invalid-option, invalid-state.

Gzip

gzip (RFC 1952), whole or as streams: deflate inside a header that can hold a file name and a time, and a trailer with a CRC-32 and the length. The decoders read every member of a file, one after another.

gzip
function gzip(data: Uint8Array, opts?: GzipOptions): Uint8Array<ArrayBuffer>

Compresses bytes to gzip (RFC 1952), the format of .gz files and of Content-Encoding: gzip.

It returns a new buffer of its own: a 10-byte header followed by the file name if you gave one, the deflate data, and an 8-byte trailer holding the CRC-32 and the length of the input. data is only read.

The header records no name and a time of 0 unless GzipOptions.filename or GzipOptions.mtime sets them, and it names no operating system (its OS byte is 255, unknown). So the same input and options always give the same bytes.

It fails with invalid-option when data isn't a Uint8Array or an option is out of range: a GzipOptions.level that isn't a whole number from 0 to 9, a file name with a NUL or a character past U+00FF, or a time outside 1970 to 2106 or not a date at all.

gzipStream compresses input that arrives in pieces, and gzipAsync compresses off the main thread.

import { gzip, gunzip, encodeText, decodeText } from 'kokyu'

const data = encodeText('the same text, gzipped twice')
const packed = gzip(data, { level: 9, filename: 'note.txt' })
decodeText(gunzip(packed)) // 'the same text, gzipped twice'

// No time is stored by default, so the bytes never change between runs
gzip(data, { level: 9, filename: 'note.txt' }) // the same bytes as packed
  • Fails with: invalid-option.
gunzip
function gunzip(data: Uint8Array, opts?: GunzipOptions): Uint8Array<ArrayBuffer>

Decompresses gzip data, every member of it, into a new Uint8Array.

It returns the output of every member in order, as one buffer of its own. A file of several members, as joining .gz files makes, reads as their contents joined. After the last member, bytes that don't start another (0x1f 0x8b) are ignored; bytes that do are read as a member, and must be one.

The header's file name, time, comment and extra field are skipped: none of them comes back. Each member's stored length is checked against what it decoded to. Its CRC-32 is not, nor the header's own CRC: to verify a single-member file, compare crc32 of the output with the 4 bytes that start 8 from the end, read little-endian.

It fails with truncated when the data ends early, an empty input included, invalid-header when it doesn't start as gzip or sets reserved flags, unsupported for a member not compressed with deflate, invalid-data for corrupt deflate data or a wrong length, and too-large once the output would pass GunzipOptions.maxSize. When data isn't a Uint8Array, or maxSize isn't a whole number of bytes, it fails with invalid-option.

With no maxSize there is no cap, and 10 KB of input can decode to 10 MB: set one for data you don't trust. gunzipInto decodes into a buffer you already have, and gunzipStream decodes data that arrives in pieces.

import { gzip, gunzip, encodeText, decodeText, KokyuError } from 'kokyu'

const one = gzip(encodeText('first, ')), two = gzip(encodeText('then second'))
const both = new Uint8Array([...one, ...two])
decodeText(gunzip(both)) // 'first, then second': every member, in order

// From an untrusted source, cap the output
try {
  gunzip(both, { maxSize: 10 })
} catch (e) {
  if (e instanceof KokyuError) e.code // 'too-large'
}
  • Fails with: truncated, invalid-header, unsupported, invalid-data, too-large, invalid-option.
gunzipInto
function gunzipInto<B extends ArrayBufferLike>(data: Uint8Array, out: Uint8Array<B>, opts?: GunzipOptions): Uint8Array<B>

Decompresses gzip data into a buffer you own, and returns the part of it that holds the output.

It returns out.subarray(0, n) for n bytes of output, every member included: a view of out's memory, not a copy. Bytes of out past the result are left as they were.

Output that doesn't fit in out fails with too-large, as does output past GunzipOptions.maxSize. On a failure out may already hold part of the output.

When data overlaps out in memory, it is read from a copy, since the output would otherwise overwrite input not yet read.

It reads and fails as gunzip does, and fails with invalid-option when out isn't a Uint8Array.

import { gzip, gunzipInto, encodeText, decodeText } from 'kokyu'

const packed = gzip(encodeText('fits in the buffer'))
const buffer = new Uint8Array(1024)
const view = gunzipInto(packed, buffer)
decodeText(view) // 'fits in the buffer'
view.length // 18
view.buffer === buffer.buffer // true: a view of buffer, not a copy
  • Fails with: truncated, invalid-header, unsupported, invalid-data, too-large, invalid-option.
gzipStream
function gzipStream(opts?: GzipOptions): CompressStream

Compresses to gzip as a stream: push input in pieces and get back the bytes each completes.

It returns a CompressStream. The options are read once, when the stream is made, so a bad GzipOptions.level, file name or time fails with invalid-option here rather than on a later call.

The first call's output starts with the header, even for an empty chunk, and Stream.finish returns the last of the data with the trailer. In between, output trails input: the compressor holds data back to compress it better, so a Stream.push often returns no bytes. CompressStream.flush sends everything pushed so far without ending the stream.

At levels 1 to 9, and with no flush, the bytes are exactly those gzip gives for the same input and options, however the input was split.

A chunk that isn't a Uint8Array fails with invalid-option and leaves the stream as it was, and any call after Stream.finish fails with invalid-state.

import { gzipStream, gzip, gunzip, encodeText, decodeText } from 'kokyu'

const stream = gzipStream({ filename: 'log.txt' })
const parts = [stream.push(encodeText('first entry, ')), stream.push(encodeText('second entry'))]
parts.push(stream.finish())
parts[0]!.length // 18: the header and its file name, nothing compressed yet

const packed = new Uint8Array(await new Blob(parts).arrayBuffer())
decodeText(gunzip(packed)) // 'first entry, second entry'
  • Fails with: invalid-option, invalid-state.
gunzipStream
function gunzipStream(opts?: GunzipOptions): Stream

Decompresses gzip as a stream: push the compressed bytes in pieces and get back the output each completes.

It returns a Stream. Like gunzip it reads every member, one after another, and ignores what follows the last one unless it starts another. Chunks can split the data anywhere, headers and trailers included. A header's file name and comment are skipped as they arrive rather than held, so even an endless one costs no memory.

Data that doesn't start as gzip fails with invalid-header on the first byte that shows it. Each member's length is checked as its trailer arrives, with invalid-data on a mismatch; its CRC-32 is not. Stream.finish fails with truncated when the data stops inside a member, or before any member at all.

GunzipOptions.maxSize caps the output of all members together, with too-large, and a bad one fails with invalid-option when the stream is made. Once a call has failed partway, every later call rethrows its error.

import { gzip, gunzipStream, decodeTextStream, encodeText } from 'kokyu'

const packed = gzip(encodeText('déjà vu, streamed back out'))
const stream = gunzipStream({ maxSize: 1 << 20 })
const text = decodeTextStream()
let out = ''
for (let i = 0; i < packed.length; i += 8) out += text.push(stream.push(packed.subarray(i, i + 8)))
out += text.finish(stream.finish())
out // 'déjà vu, streamed back out'
  • Fails with: truncated, invalid-header, unsupported, invalid-data, too-large, invalid-option, invalid-state.

Any format

For data that could be any of the three: gzip and zlib are told apart by their headers, and anything else is read as raw deflate.

decompress
function decompress(data: Uint8Array, opts?: InflateOptions): Uint8Array<ArrayBuffer>

Decompresses gzip, zlib or raw deflate, whichever the data turns out to be.

It looks at the first 2 bytes. 1F 8B is gzip, read as gunzip reads it, every member included. A valid zlib header is zlib, read as unzlib reads it. Anything else is read as raw deflate, which has no header to recognize. So data that is none of the three is decoded as raw deflate too: it nearly always fails, with invalid-data or truncated, but now and then random bytes are valid deflate and decode to something.

It comes back as a new Uint8Array that owns its whole ArrayBuffer, and fails as the decoder it picked does. So invalid-header and unsupported can come from a gzip header, and invalid-option from zlib data whose dictionary is missing or different. Checksums aren't checked; a gzip member's length is.

InflateOptions.maxSize caps the output in every format, all the members of a gzip file together. InflateOptions.dictionary applies to zlib and raw deflate. Gzip has no use for one, but a dictionary that isn't a Uint8Array is refused whatever the format.

decompressInto decodes into a buffer you already have, decompressStream decodes data that arrives in pieces, and decompressAsync works off the main thread.

import { decodeText, decompress, deflate, encodeText, gzip, zlib } from 'kokyu'

const text = encodeText('hello, hello, hello, hello')
for (const packed of [gzip(text), zlib(text), deflate(text)]) {
  decodeText(decompress(packed, { maxSize: 1 << 20 })) // 'hello, hello, hello, hello', each time
}
  • Fails with: truncated, invalid-data, invalid-header, too-large, unsupported, invalid-option.
decompressInto
function decompressInto<B extends ArrayBufferLike>(data: Uint8Array, out: Uint8Array<B>, opts?: InflateOptions): Uint8Array<B>

Decompresses gzip, zlib or raw deflate into a buffer you own, and returns the part of it that holds the output.

It tells the formats apart as decompress does, and writes the output as inflateInto does: the result is a view of out from its start, as long as the output, and the next decode into the same buffer overwrites it. A gzip file's members land one after another.

Output that doesn't fit in out fails with too-large, and so does output past InflateOptions.maxSize: the smaller of the two is the cap. A call that fails may already have written part of the output into out. An out that isn't a readable Uint8Array fails with invalid-option. Input that shares memory with out is copied first, so it still decodes right.

import { decodeText, decompressInto, encodeText, gzip } from 'kokyu'

// Two gzip members, one after the other, as two .gz files joined together are
const packed = new Uint8Array([...gzip(encodeText('hello, ')), ...gzip(encodeText('world'))])
const buffer = new Uint8Array(1024)
decodeText(decompressInto(packed, buffer)) // 'hello, world'
  • Fails with: truncated, invalid-data, invalid-header, too-large, unsupported, invalid-option.
decompressStream
function decompressStream(opts?: InflateOptions): Stream

Decompresses gzip, zlib or raw deflate as a stream, whichever its first 2 bytes show.

It waits for 2 bytes before it picks a format, so a first push of 1 byte returns nothing. From then on it works as gunzipStream, unzlibStream or inflateStream does, with the same rules for what each push returns, what it keeps and what fails. A Stream.finish that leaves it fewer than 2 bytes in all reads them as raw deflate, so an empty stream fails with truncated.

InflateOptions.maxSize counts all the output, across every push and every gzip member. The dictionary is copied when the stream is made, though only zlib and raw deflate read it.

A call that fails on the data breaks the stream: every later call throws that same error. A chunk that isn't a readable Uint8Array fails with invalid-option and leaves the stream as it was. After a finish that succeeded, every call fails with invalid-state. toTransformStream turns it into a web TransformStream, and decompressStreamAsync runs one in a worker.

import { decodeText, decompressStream, encodeText, toTransformStream, zlib } from 'kokyu'

const packed = zlib(encodeText('hello, hello, hello, hello'))
const stream = decompressStream({ maxSize: 1 << 20 })
const first = stream.push(packed.subarray(0, 1)) // 0 bytes: one byte doesn't show the format yet
decodeText(stream.finish(packed.subarray(1))) // 'hello, hello, hello, hello'

// As a web TransformStream, for a body whose format you don't know
const body = new Blob([packed]).stream().pipeThrough(toTransformStream(decompressStream()))
await new Response(body).text() // 'hello, hello, hello, hello'
  • Fails with: truncated, invalid-data, invalid-header, too-large, unsupported, invalid-option, invalid-state.

Zip

Zip archives: written from an object of paths, or entry by entry as a stream, and read whole, listed, or as a stream of entries. Entries are stored or deflated. ZIP64, data descriptors and names that aren't UTF-8 are all read.

zip
function zip(input: ZipInput, opts?: ZipOptions): Uint8Array<ArrayBuffer>

Builds a zip archive from an object that maps paths to their bytes.

It returns the whole archive as a new array: the entries in the order Object.entries lists the input, then the central directory and the end record. Every byte is copied, so the result shares no memory with your input. A path maps to its bytes, to [bytes, options] with ZipEntryOptions for that entry alone, or to a nested object, which is a folder. ZipInput has the rules for names.

Each entry is deflated at its level, 6 unless you set one, and stored as it is when deflate doesn't make it smaller, as with data that is already compressed, very small files, empty files and folders. Level 0 stores every entry.

An entry left to the defaults is marked as made on Unix with mode 0o644, or 0o755 for a folder, and gets the current time, which zip stores in local time to 2 seconds. An entry whose name or comment isn't plain ASCII gets the UTF-8 flag.

It fails with invalid-option for input that isn't a plain object of bytes, [bytes, options] pairs and folders, for a name ZipInput refuses, and for an option out of range. kokyu writes no ZIP64, so more than 65,534 entries, or a size or offset of 2³² − 1 bytes (just under 4 GiB) or more, fails with too-large. kokyu does read the ZIP64 archives other tools write.

zipAsync builds the same archive off the main thread, and zipStream writes one entry at a time.

import { decodeText, encodeText, unzip, zip, zipEntries } from 'kokyu'

const archive = zip({
  'readme.txt': encodeText('Hello, zip'),
  src: { 'main.ts': encodeText('console.log(1)\n'.repeat(50)), lib: {} },
  'run.sh': [encodeText('#!/bin/sh\necho hi\n'), { mode: 0o755 }],
}, { mtime: new Date(2024, 4, 1, 9, 30) })

zipEntries(archive).map((e) => [e.name, e.compression, e.mode?.toString(8)])
// [['readme.txt', 0, '644'], ['src/main.ts', 8, '644'], ['src/lib/', 0, '755'], ['run.sh', 0, '755']]
// 0 is stored: deflate couldn't make readme.txt or run.sh smaller. 8 is deflated.
decodeText(unzip(archive)['readme.txt']!) // 'Hello, zip'
  • Fails with: invalid-option, too-large.
unzip
function unzip(data: Uint8Array, opts?: UnzipOptions): Record<string, Uint8Array<ArrayBuffer>>

Extracts a zip archive into an object of paths and their bytes.

It returns a plain object with one key per entry, its full name, in the order the central directory lists them. Each value is a new array of the entry's data, never a view of data. A folder's entry appears with its name ending in / and empty data. Where an archive lists one name twice, the later entry's data is kept, and zipEntries lists both. Names are defined as own keys, so an entry named __proto__ is just a key.

It reads the central directory, as zipEntries does, so it needs the whole archive. ZIP64 and data descriptors are read. A name or comment without the UTF-8 flag is read as UTF-8 when it is valid UTF-8, and as code page 437 otherwise. Names are returned as the archive holds them: check one before you use it as a file path, since another tool's archive can hold .. or a leading /.

Nothing is decoded until every entry has been checked. UnzipOptions.filter sees each entry first, and only the entries it keeps go on: each must be one kokyu can read, the sizes they state must add up to no more than UnzipOptions.maxSize, and no two may share bytes. Entries that overlap would decode the same data again and again, the trick of an overlapping zip bomb, so they fail with invalid-data. Each entry must then decode to exactly the size it states.

It fails with invalid-data for data that isn't a zip archive, a broken central directory or local header, overlapping entries, corrupt deflate data, and an entry whose data comes out shorter than it states, or longer for a stored one; with truncated for an entry whose data runs past the end; with unsupported for an encrypted entry, a compression method other than stored and deflate, and one part of an archive split into several; with too-large past maxSize, and as soon as a deflated entry decodes past the size it states; and with invalid-option when data isn't a Uint8Array or maxSize isn't a byte count. An error your filter throws comes out as it is.

CRC-32s aren't checked: call crc32 on an entry's data to verify it. unzipAsync does the same work off the main thread, and unzipStream reads an archive as it arrives.

import { decodeText, encodeText, unzip, zip } from 'kokyu'

const archive = zip({
  'notes.txt': encodeText('Buy milk'),
  photos: { 'cat.jpg': new Uint8Array(2048) },
  empty: {},
})

const files = unzip(archive)
Object.keys(files) // ['notes.txt', 'photos/cat.jpg', 'empty/']
decodeText(files['notes.txt']!) // 'Buy milk'
files['empty/']!.length // 0

// Only the text files, and no more than 1 MiB of them
const text = unzip(archive, { filter: (e) => e.name.endsWith('.txt'), maxSize: 1 << 20 })
Object.keys(text) // ['notes.txt']
  • Fails with: invalid-data, truncated, unsupported, too-large, invalid-option.
zipEntries
function zipEntries(data: Uint8Array): ZipEntry[]

Lists a zip archive's entries without decompressing anything.

It returns a new ZipEntry for every record in the central directory, in its order: the name, both sizes, the compression method, the time, the comment and, for an entry made on Unix, its mode. A name listed twice appears twice.

Only the end record and the central directory are read. No entry's data is decoded or checked, so it lists entries unzip would refuse too: one with another compression method, which ZipEntryInfo.compression shows, and an encrypted one, which nothing in a ZipEntry marks. The ZipEntry.originalSize values add up to what unzip would decode, so you can judge an archive before you extract it.

It fails with invalid-data for data that isn't a zip archive or whose central directory is broken, with unsupported for one part of an archive split into several, and with invalid-option when data isn't a Uint8Array. The archive's comment and the entries' extra fields aren't returned, here or by any of kokyu's readers.

import { encodeText, zip, zipEntries } from 'kokyu'

const archive = zip({
  'a.txt': encodeText('a'.repeat(1000)),
  docs: { 'b.txt': [encodeText('b'), { comment: 'tiny' }] },
}, { mtime: new Date(2024, 0, 15, 8, 0) })

const entries = zipEntries(archive)
entries.map((e) => [e.name, e.size, e.originalSize]) // [['a.txt', 10, 1000], ['docs/b.txt', 1, 1]]
entries[1]!.comment // 'tiny'
entries[0]!.mtime.getHours() // 8, in local time
entries.reduce((n, e) => n + e.originalSize, 0) // 1001 bytes, if you extract it all
  • Fails with: invalid-data, unsupported, invalid-option.
zipStream
function zipStream(opts?: ZipOptions): ZipStream

Starts a zip archive that you write one entry at a time, as a stream.

It returns a ZipStream. For each entry, ZipStream.file returns a stream: push the entry's data through it, then finish it before you start the next. ZipStream.finish ends the archive. Every push and finish returns the bytes of the archive it completes, possibly none, and those bytes in the order they came are the archive. Until the end, the stream keeps each finished entry's central directory record, never its data.

No entry's size or CRC-32 is known when its header goes out, so they follow its data, in a data descriptor. Every entry is deflated, even at level 0, which writes deflate's stored blocks: those mark their own end, so a stream reader can't take data that looks like a descriptor for the end of the entry. An entry finished empty on its first call is stored. unzip and unzipStream read both.

It takes its options when you call it, so changing them later changes nothing. ZipOptions.mtime applies to every entry without its own, and without either an entry gets the time of its ZipStream.file call. Names follow the rules of ZipInput, and a second name for a path the archive already has fails with invalid-option. Entries get the same defaults as in zip.

Calling zipStream fails only with invalid-option, for a ZipOptions.comment it refuses; a level or time out of range fails when an entry starts. The other codes come from the calls on the stream: invalid-option for a bad name or ZipEntryOptions, invalid-state for a call out of order, and too-large once the archive needs ZIP64, which kokyu doesn't write.

zipStreamAsync deflates off the main thread, and toTransformStream lets a web stream pipe into an entry.

import { encodeText, unzip, zipStream } from 'kokyu'

const zs = zipStream({ mtime: new Date(2024, 4, 1) })
const parts: Uint8Array<ArrayBuffer>[] = []

const log = zs.file('log.txt')
for (const line of ['one\n', 'two\n', 'three\n']) parts.push(log.push(encodeText(line)))
parts.push(log.finish())
parts.push(zs.file('raw.bin', { level: 0 }).finish(new Uint8Array(100)))
parts.push(zs.finish()) // the central directory and the end record

const archive = new Uint8Array(await new Blob(parts).arrayBuffer())
Object.keys(unzip(archive)) // ['log.txt', 'raw.bin']
  • Fails with: invalid-option, invalid-state, too-large.
unzipStream
function unzipStream(opts?: UnzipStreamOptions): UnzipStream

Starts reading a zip archive as a stream, front to back, without needing all of it.

It returns an UnzipStream. Push the archive's bytes in chunks of any size, and each call returns the UnzipChunks of entry data it completes, possibly none. An entry's chunks come in order and end with one whose UnzipChunk.final is true, all before the next entry's. finish takes the last bytes, and fails with truncated if the archive ended before its central directory, so entries cut off at the end can't go missing unnoticed.

It reads each entry from its local header, and stops at the central directory, ignoring anything after it. So it never sees comments or Unix modes, which only the central directory holds, and an entry whose sizes follow its data, as zipStream writes every one, comes without sizes (see ZipEntryInfo.size). A name that appears twice comes twice. A stored entry whose sizes follow its data ends where a data descriptor matching the CRC-32 and size of the bytes so far appears.

UnzipStreamOptions.filter decides on each entry as its header arrives. A skipped entry returns no chunks, and isn't decoded when its header states its size. When its sizes follow its data, a deflated entry is decoded anyway and the output thrown away, since only that finds where it ends, so it must be one kokyu can read.

It fails with truncated for an archive that ends early; with invalid-data for bytes between entries that aren't a header, corrupt deflate data, and an entry of another size than it states; with unsupported for an encrypted entry or another compression method, in an entry it has to read; with too-large past UnzipStreamOptions.maxSize; with invalid-state for a call after finish or from inside its own filter; and with invalid-option for a chunk that isn't a Uint8Array or a bad maxSize. Once the data or the filter has made a call throw, every later call throws the same error. A call refused before it reads anything, such as one with a chunk that isn't bytes, leaves the stream as it was.

CRC-32s aren't checked, except to find where such a stored entry ends. unzipStreamAsync decodes off the main thread, and toTransformStream turns the stream into a web TransformStream.

import { encodeText, unzipStream, zip } from 'kokyu'

const archive = zip({
  'a.txt': encodeText('alpha '.repeat(2000)),
  'b.bin': new Uint8Array(10),
  'c.txt': encodeText('gamma'),
})

const reader = unzipStream({ filter: (e) => e.name.endsWith('.txt') })
const done: [string, number][] = []
let size = 0
// The archive arriving 100 bytes at a time, as from a network
for (let i = 0; i < archive.length; i += 100) {
  for (const { entry, data, final } of reader.push(archive.subarray(i, i + 100))) {
    size += data.length
    if (final) { done.push([entry.name, size]); size = 0 }
  }
}
const rest = reader.finish() // no chunks left, and no error: the central directory arrived
done // [['a.txt', 12000], ['c.txt', 5]]
  • Fails with: truncated, invalid-data, unsupported, too-large, invalid-state, invalid-option.

Streams

What every sync stream shares, the compressors' flush, and toTransformStream, which turns any kokyu stream, sync or async, into a web TransformStream.

toTransformStream
function toTransformStream<In, Out>(stream: {
    push(chunk: In): Out | Promise<Out>;
    finish(): Out | Promise<Out>;
}): TransformStream<In, Element<Out>>

Wraps a kokyu stream, sync or async, as a web TransformStream for pipeThrough.

Each chunk written goes to Stream.push, and closing the writable side calls Stream.finish. An async stream's promises are awaited one call at a time, so output keeps its order. A result goes on to the readable side as one chunk, unless it is empty; an array, as unzipStream returns, goes on as one chunk per item. It takes any object with push and finish, a stream of your own included.

A pipe that fails or is canceled finishes the stream and drops what that returns: a chunk refused for its type would otherwise leave it open, and an open async stream keeps its worker. Later calls on it fail with invalid-state, or rethrow the error that broke it. When the stream itself throws, the pipe rejects with that error. A cancel reaches the stream in runtimes that implement a transformer's cancel.

A zip entry from ZipStream.file or AsyncZipStream.file is the exception. A failed or canceled pipe leaves it open, since finishing it would write a cut-off entry into an archive you may still finish, and the archive refuses to finish, with invalid-state, until you finish the entry yourself. If a cancel threw away bytes the entry had returned and nothing had read, the archive refuses to finish at all. For an entry the result is a readable and writable pair, which sees every cancel, rather than a TransformStream instance.

Bytes the readable side has handed out are out of its sight: an aborted pipeTo can drop some its destination hadn't written yet, so don't finish an archive whose output pipe was aborted.

import { toTransformStream, gzipStream, gunzipStreamAsync, encodeText } from 'kokyu'

const file = new Blob([encodeText('a line of a log file\n'.repeat(1000))])
const gz = file.stream().pipeThrough(toTransformStream(gzipStream()))
const packed = new Uint8Array(await new Response(gz).arrayBuffer())
packed.length // 105, from 21,000 bytes

// An async stream pipes the same way, and its output pipes on like any other
const back = new Blob([packed]).stream().pipeThrough(toTransformStream(gunzipStreamAsync()))
await new Response(back).text() // 'a line of a log file\n', 1,000 times

Async

Every format off the main thread. One-shot inputs under 16 KB run on the calling thread, and larger ones in a pool of workers that start on first use. An async stream runs in a worker unless the whole stream is under 16 KB and finished at once. Every call takes a signal and transfer.

deflateAsync
function deflateAsync(data: Uint8Array, opts?: DeflateOptions & AsyncOptions): Promise<Uint8Array<ArrayBuffer>>

deflate as a promise, compressed in a pool worker when the input is 16 KB or more.

It resolves to the bytes deflate returns for the same input and options. An input under 16 KB is compressed on the calling thread before the call returns, and a larger one goes to the worker pool that AsyncOptions describes.

Its input can be reused as soon as the call returns: a worker gets a copy taken at the call, unless AsyncOptions.transfer hands it the buffer itself. Nothing throws: a bad argument rejects the promise with the code deflate would throw, and a worker that fails rejects it with worker.

import { deflate, deflateAsync, encodeText } from 'kokyu'

const text = encodeText('Every format comes four ways. '.repeat(2000)) // 60,000 bytes: a worker compresses it
const original = text.slice()
const pending = deflateAsync(text, { level: 9 })
text.fill(0) // safe: the input was copied as the call was made
const packed = await pending // the same bytes as deflate(original, { level: 9 })
packed.length // 194
  • Fails with: invalid-option, worker.
inflateAsync
function inflateAsync(data: Uint8Array, opts?: InflateOptions & AsyncOptions): Promise<Uint8Array<ArrayBuffer>>

inflate as a promise, decoded in a pool worker when the input is 16 KB or more.

It resolves to what inflate returns, and rejects with the code it would throw. The 16 KB is measured on the compressed input, not the output: a few kilobytes that inflate to many megabytes are decoded on the calling thread, before the call returns. InflateOptions.maxSize bounds that work.

Its input can be reused as soon as the call returns: a worker gets a copy taken at the call, unless AsyncOptions.transfer moves the buffer, and a dictionary is always copied. Every failure rejects the promise; a worker that fails rejects it with worker.

import { deflate, inflateAsync } from 'kokyu'
import type { KokyuError } from 'kokyu'

const packed = deflate(new Uint8Array(1 << 20)) // 1 MB of zeros packs into 1,069 bytes
const data = await inflateAsync(packed) // decoded on this thread: the input is under 16 KB
data.length // 1048576

const code = await inflateAsync(packed, { maxSize: 64 << 10 }).catch((e: KokyuError) => e.code) // 'too-large'
  • Fails with: truncated, invalid-data, too-large, invalid-option, worker.
zlibAsync
function zlibAsync(data: Uint8Array, opts?: DeflateOptions & AsyncOptions): Promise<Uint8Array<ArrayBuffer>>

zlib as a promise, compressed in a pool worker when the input is 16 KB or more.

It resolves to the bytes zlib returns for the same input and options. An input under 16 KB is compressed on the calling thread before the call returns, and a larger one goes to the worker pool that AsyncOptions describes.

Its input can be reused as soon as the call returns: a worker gets a copy taken at the call, unless AsyncOptions.transfer hands it the buffer itself, and a dictionary is always copied. Nothing throws: a bad argument rejects the promise with the code zlib would throw, and a worker that fails rejects it with worker.

import { encodeText, unzlib, zlib, zlibAsync } from 'kokyu'

const rows = Array.from({ length: 2000 }, (_, id) => ({ id, name: 'user ' + id }))
const json = encodeText(JSON.stringify(rows)) // 59,781 bytes
const expected = zlib(json)
const pending = zlibAsync(json, { transfer: true })
json.length // 0: the worker took the buffer instead of a copy
const packed = await pending
packed.length // 10179
  • Fails with: invalid-option, worker.
unzlibAsync
function unzlibAsync(data: Uint8Array, opts?: InflateOptions & AsyncOptions): Promise<Uint8Array<ArrayBuffer>>

unzlib as a promise, decoded in a pool worker when the input is 16 KB or more.

It resolves to what unzlib returns, and rejects with the code it would throw. The 16 KB is measured on the compressed input, so a small input that expands a long way is decoded on the calling thread; InflateOptions.maxSize bounds it.

Its input can be reused as soon as the call returns: a worker gets a copy taken at the call, unless AsyncOptions.transfer moves the buffer, and a dictionary is always copied. Every failure rejects the promise; a worker that fails rejects it with worker.

import { unzlibAsync, zlib } from 'kokyu'

const packed = zlib(new Uint8Array(512 << 10).map((_, i) => i % 251))
const controller = new AbortController()
const pending = unzlibAsync(packed, { signal: controller.signal })
// An abort that lands before the promise settles wins, whatever the call would have settled with
controller.abort(new Error('the user left'))
const message = await pending.catch((e: Error) => e.message) // 'the user left'
  • Fails with: truncated, invalid-data, invalid-header, too-large, invalid-option, worker.
gzipAsync
function gzipAsync(data: Uint8Array, opts?: GzipOptions & AsyncOptions): Promise<Uint8Array<ArrayBuffer>>

gzip as a promise, compressed in a pool worker when the input is 16 KB or more.

It resolves to the bytes gzip returns for the same input and options. An input under 16 KB is compressed on the calling thread before the call returns, and a larger one goes to the worker pool that AsyncOptions describes. Calls made together run side by side, as many at once as the pool has workers.

Its input can be reused as soon as the call returns: a worker gets a copy taken at the call, unless AsyncOptions.transfer hands it the buffer itself, and an mtime is read then too. Nothing throws: a bad argument rejects the promise with the code gzip would throw, and a worker that fails rejects it with worker.

import { encodeText, gunzip, gzip, gzipAsync } from 'kokyu'

// Each page is 16 KB or more, so the pool's workers compress them side by side
const pages = ['index', 'about', 'docs'].map(name => encodeText(('<h1>' + name + '</h1>').repeat(5000)))
const gzipped = await Promise.all(pages.map(page => gzipAsync(page, { level: 9 })))
gzipped.map(gz => gz.length) // [187, 186, 176]
  • Fails with: invalid-option, worker.
gunzipAsync
function gunzipAsync(data: Uint8Array, opts?: GunzipOptions & AsyncOptions): Promise<Uint8Array<ArrayBuffer>>

gunzip as a promise, decoded in a pool worker when the input is 16 KB or more.

It resolves to what gunzip returns, every member of the file included, and rejects with the code it would throw. The 16 KB is measured on the compressed input, so a small file that expands a long way is decoded on the calling thread; GunzipOptions.maxSize bounds it.

Its input can be reused as soon as the call returns: a worker gets a copy taken at the call, unless AsyncOptions.transfer moves the buffer. Every failure rejects the promise, never a synchronous throw; a worker that fails rejects it with worker.

import { decodeText, encodeText, gunzipAsync, gzip } from 'kokyu'
import type { KokyuError } from 'kokyu'

const gz = gzip(encodeText('hello, world; '.repeat(4000)))
decodeText(await gunzipAsync(gz)).length // 56000

// A bad input doesn't throw: the promise rejects with the code gunzip would throw
const cut = gunzipAsync(gz.subarray(0, gz.length - 4))
const code = await cut.catch((e: KokyuError) => e.code) // 'truncated'
  • Fails with: truncated, invalid-data, invalid-header, too-large, unsupported, invalid-option, worker.
decompressAsync
function decompressAsync(data: Uint8Array, opts?: InflateOptions & AsyncOptions): Promise<Uint8Array<ArrayBuffer>>

decompress as a promise: gzip, zlib or raw deflate, decoded in a pool worker when the input is 16 KB or more.

It resolves to what decompress returns, and rejects with the code it would throw. The 16 KB is measured on the compressed input, so a small input that expands a long way is decoded on the calling thread; InflateOptions.maxSize bounds it.

Its input can be reused as soon as the call returns: a worker gets a copy taken at the call, unless AsyncOptions.transfer moves the buffer, and a dictionary is always copied. Every failure rejects the promise; a worker that fails rejects it with worker.

import { decodeText, decompressAsync, deflate, encodeText, gzip, zlib } from 'kokyu'

const text = encodeText('any of the three. '.repeat(1000))
const inputs = [gzip(text), zlib(text), deflate(text)]
const decoded = await Promise.all(inputs.map(input => decompressAsync(input)))
decoded.map(bytes => decodeText(bytes) === decodeText(text)) // [true, true, true]
  • Fails with: truncated, invalid-data, invalid-header, too-large, unsupported, invalid-option, worker.
zipAsync
function zipAsync(input: ZipInput, opts?: ZipOptions & AsyncOptions): Promise<Uint8Array<ArrayBuffer>>

zip as a promise, built in a pool worker when the entries add up to 16 KB or more.

It resolves to the archive zip builds from the same input and options. The 16 KB counts every entry's bytes together. Entry options are read as the call is made and a worker gets copies of the bytes taken then, so the input can change right after. An entry with no mtime is stamped with the time of the call, not when a worker gets to it.

With AsyncOptions.transfer, a call bound for a worker moves every entry that is a whole buffer, each buffer once, and copies views of part of a buffer first. Nothing throws: a bad input or option rejects the promise with the code zip would throw, and a worker that fails rejects it with worker.

import { encodeText, zip, zipAsync, zipEntries } from 'kokyu'

const mtime = new Date(2026, 0, 1)
const archive = await zipAsync({
  'report.csv': encodeText('day,visits; ' + 'mon,1200; '.repeat(3000)),
  images: { 'logo.svg': encodeText('<svg/>') },
  'notes.txt': [encodeText('kept as is'), { level: 0 }],
}, { mtime })
zipEntries(archive).map(entry => entry.name) // ['report.csv', 'images/logo.svg', 'notes.txt']
  • Fails with: too-large, invalid-option, worker.
unzipAsync
function unzipAsync(data: Uint8Array, opts?: UnzipOptions & AsyncOptions): Promise<Record<string, Uint8Array<ArrayBuffer>>>

unzip as a promise, decoded in a pool worker when the archive is 16 KB or more.

It resolves to what unzip returns, an object of paths to bytes, and rejects with the code it would throw. The 16 KB is the archive's size, so a small archive that expands a long way is decoded on the calling thread; UnzipOptions.maxSize bounds it.

The filter always runs on the calling thread, once per entry, so it can use anything in scope. For an archive bound for a worker, the entry list is read on the calling thread first, and the worker decodes only the entries the filter kept. An error the filter throws rejects the promise as it is.

The archive can be reused as soon as the call returns: a worker gets a copy taken at the call, unless AsyncOptions.transfer moves the buffer. A worker that fails rejects the promise with worker.

import { encodeText, unzipAsync, zip } from 'kokyu'

const archive = zip({
  'src/main.ts': encodeText('export {}'),
  'src/data.json': encodeText(JSON.stringify(Array.from({ length: 5000 }, (_, id) => ({ id })))),
  'notes.md': encodeText('# Notes'),
}, { level: 0 })
// The filter runs on this thread, so it can use anything in scope
const wanted = new Set(['src/main.ts', 'notes.md'])
const files = await unzipAsync(archive, { filter: entry => wanted.has(entry.name) })
Object.keys(files) // ['src/main.ts', 'notes.md']
  • Fails with: truncated, invalid-data, too-large, unsupported, invalid-option, worker.
deflateStreamAsync
function deflateStreamAsync(opts?: DeflateOptions & AsyncOptions): AsyncCompressStream

deflateStream with promises: a raw deflate AsyncCompressStream.

Its calls give the output deflateStream's would, each as a promise, and can be queued without awaiting. A stream whose chunks add up to under 16 KB, finished in the same synchronous run of code as its first call, runs on the calling thread; any other opens a session in a pool worker. AsyncStream has the details.

Options are read once, when the stream is made. The function never throws: a bad option rejects every call on the stream.

import { deflateStreamAsync, inflate } from 'kokyu'

const stream = deflateStreamAsync()
const parts: Promise<Uint8Array<ArrayBuffer>>[] = []
const chunk = new Uint8Array(32 << 10)
for (let i = 0; i < 8; i++) {
  chunk.fill(i) // one buffer refilled for every push: each push copied it
  parts.push(stream.push(chunk))
}
parts.push(stream.finish())
const packed = new Uint8Array(await new Blob(await Promise.all(parts)).arrayBuffer())
const data = inflate(packed)
data.length // 262144, every 32 KB holding its own fill
  • Fails with: invalid-option, invalid-state, worker.
inflateStreamAsync
function inflateStreamAsync(opts?: InflateOptions & AsyncOptions): AsyncStream

inflateStream with promises: an AsyncStream that decodes raw deflate as it arrives.

Its calls give the output inflateStream's would, each as a promise, and can be queued without awaiting. A stream whose chunks add up to under 16 KB, finished in the same synchronous run of code as its first call, runs on the calling thread; any other opens a session in a pool worker. AsyncStream has the details.

Options are read once, when the stream is made, and a dictionary is copied. Once a call fails, every later call rejects with the same error. The function never throws: a bad option rejects every call on the stream.

import { deflate, encodeText, inflateStreamAsync } from 'kokyu'

const rows = Array.from({ length: 2000 }, (_, id) => ({ id, name: 'user ' + id }))
const packed = deflate(encodeText(JSON.stringify(rows)))
// Decoded as each piece arrives, with the output capped at 1 MB
const stream = inflateStreamAsync({ maxSize: 1 << 20 })
let total = 0
for (let at = 0; at < packed.length; at += 4096) {
  total += (await stream.push(packed.subarray(at, at + 4096))).length
}
total += (await stream.finish()).length
total // 59781
  • Fails with: truncated, invalid-data, too-large, invalid-option, invalid-state, worker.
zlibStreamAsync
function zlibStreamAsync(opts?: DeflateOptions & AsyncOptions): AsyncCompressStream

zlibStream with promises: a zlib AsyncCompressStream.

Its calls give the output zlibStream's would, each as a promise, and can be queued without awaiting. A stream whose chunks add up to under 16 KB, finished in the same synchronous run of code as its first call, runs on the calling thread; any other opens a session in a pool worker. AsyncStream has the details.

Options are read once, when the stream is made, and a dictionary is copied. With AsyncOptions.transfer, each chunk of 16 KB or more moves to the worker and smaller ones are copied. The function never throws: a bad option rejects every call on the stream.

import { unzlib, zlibStreamAsync } from 'kokyu'

const stream = zlibStreamAsync({ transfer: true })
const large = new Uint8Array(64 << 10).fill(7)
const small = new Uint8Array(1000).fill(9)
const parts = Promise.all([stream.push(large), stream.push(small), stream.finish()])
large.length // 0: a chunk of 16 KB or more moves to the worker
small.length // 1000: a smaller one is copied
const packed = new Uint8Array(await new Blob(await parts).arrayBuffer())
unzlib(packed).length // 66536
  • Fails with: invalid-option, invalid-state, worker.
unzlibStreamAsync
function unzlibStreamAsync(opts?: InflateOptions & AsyncOptions): AsyncStream

unzlibStream with promises: an AsyncStream that decodes zlib as it arrives.

Its calls give the output unzlibStream's would, each as a promise, and can be queued without awaiting. A stream whose chunks add up to under 16 KB, finished in the same synchronous run of code as its first call, runs on the calling thread; any other opens a session in a pool worker. AsyncStream has the details.

Options are read once, when the stream is made, and a dictionary is copied. Once a call fails, every later call rejects with the same error, the calls already queued behind it included. The function never throws: a bad option rejects every call on the stream.

import { encodeText, unzlibStreamAsync } from 'kokyu'

const stream = unzlibStreamAsync()
// Queued together: the push fails, and the finish behind it fails with the same error
const results = await Promise.allSettled([stream.push(encodeText('not zlib at all')), stream.finish()])
results.map(result => result.status === 'rejected' && result.reason.code)
// ['invalid-header', 'invalid-header']
  • Fails with: truncated, invalid-data, invalid-header, too-large, invalid-option, invalid-state, worker.
gzipStreamAsync
function gzipStreamAsync(opts?: GzipOptions & AsyncOptions): AsyncCompressStream

gzipStream with promises: a gzip AsyncCompressStream.

Its calls give the output gzipStream's would, each as a promise, and can be queued without awaiting. A stream whose chunks add up to under 16 KB, finished in the same synchronous run of code as its first call, runs on the calling thread; any other opens a session in a pool worker. AsyncStream has the details.

Options are read once, when the stream is made, an mtime included. toTransformStream turns it into a web TransformStream. The function never throws: a bad option rejects every call on the stream.

import { gunzip, gzipStreamAsync, toTransformStream } from 'kokyu'

const body = new Blob(['a line of log output; '.repeat(10000)]).stream()
const gzipped = body.pipeThrough(toTransformStream(gzipStreamAsync({ level: 9 })))
const gz = new Uint8Array(await new Response(gzipped).arrayBuffer())
gunzip(gz).length // 220000
  • Fails with: invalid-option, invalid-state, worker.
gunzipStreamAsync
function gunzipStreamAsync(opts?: GunzipOptions & AsyncOptions): AsyncStream

gunzipStream with promises: an AsyncStream that decodes gzip as it arrives.

Its calls give the output gunzipStream's would, each as a promise, and can be queued without awaiting. A stream whose chunks add up to under 16 KB, finished in the same synchronous run of code as its first call, runs on the calling thread; any other opens a session in a pool worker. AsyncStream has the details.

Options are read once, when the stream is made. Once a call fails, every later call rejects with the same error. The function never throws: a bad option rejects every call on the stream.

import { gunzipStreamAsync, gzip } from 'kokyu'

const gz = gzip(new Uint8Array(400_000).map((_, i) => (i * i) % 251))
const controller = new AbortController()
const stream = gunzipStreamAsync({ signal: controller.signal })
await stream.push(gz.subarray(0, gz.length >> 1))
const pending = stream.push(gz.subarray(gz.length >> 1))
controller.abort(new Error('download canceled'))
await pending.catch((e: Error) => e.message) // 'download canceled'
await stream.finish().catch((e: Error) => e.message) // 'download canceled', as will every later call
  • Fails with: truncated, invalid-data, invalid-header, too-large, unsupported, invalid-option, invalid-state, worker.
decompressStreamAsync
function decompressStreamAsync(opts?: InflateOptions & AsyncOptions): AsyncStream

decompressStream with promises: an AsyncStream that decodes gzip, zlib or raw deflate as it arrives.

Its calls give the output decompressStream's would, each as a promise, and can be queued without awaiting. A stream whose chunks add up to under 16 KB, finished in the same synchronous run of code as its first call, runs on the calling thread; any other opens a session in a pool worker. AsyncStream has the details.

Options are read once, when the stream is made, and a dictionary is copied. Once a call fails, every later call rejects with the same error. The function never throws: a bad option rejects every call on the stream.

import { decodeText, decompressStreamAsync, encodeText, gzip, zlib } from 'kokyu'

const text = encodeText('one stream, any of the formats. '.repeat(1000))
for (const packed of [gzip(text), zlib(text)]) {
  const stream = decompressStreamAsync()
  const parts = await Promise.all([
    stream.push(packed.subarray(0, 1)), // the format is known once two bytes are in
    stream.push(packed.subarray(1)),
    stream.finish(),
  ])
  decodeText(new Uint8Array(await new Blob(parts).arrayBuffer())) === decodeText(text) // true
}
  • Fails with: truncated, invalid-data, invalid-header, too-large, unsupported, invalid-option, invalid-state, worker.
zipStreamAsync
function zipStreamAsync(opts?: ZipOptions & AsyncOptions): AsyncZipStream

zipStream with promises: an AsyncZipStream that writes a zip archive entry by entry.

Its calls give the bytes zipStream's would, each as a promise, and every one settles in the order it was made, so the pieces can be written as they come. It runs on the calling thread when its entries' data adds up to under 16 KB and the archive is finished in the same synchronous run of code as the first AsyncZipStream.file; otherwise it runs in a pool worker.

Archive options are read when the stream is made, and an entry's when AsyncZipStream.file opens it; an entry with no mtime of its own or the archive's is stamped then. A call refused for being out of turn, a bad name or a bad chunk leaves the archive usable. The function never throws: a bad option is reported by the calls that use it, through their promises.

import { encodeText, unzip, zipStreamAsync } from 'kokyu'

const archive = zipStreamAsync({ comment: 'nightly export' })
const pieces: Promise<Uint8Array<ArrayBuffer>>[] = []
for (const [name, text] of Object.entries({ 'a.csv': 'id,name; 1,ada', 'b.csv': 'id,name; 2,lin' })) {
  const entry = archive.file(name)
  pieces.push(entry.push(encodeText(text)), entry.finish())
}
pieces.push(archive.finish())
// Every call settles in the order it was made, so the pieces join into the archive
const zipped = new Uint8Array(await new Blob(await Promise.all(pieces)).arrayBuffer())
Object.keys(unzip(zipped)) // ['a.csv', 'b.csv']
  • Fails with: too-large, invalid-option, invalid-state, worker.
unzipStreamAsync
function unzipStreamAsync(opts?: UnzipStreamOptions & AsyncOptions): AsyncUnzipStream

unzipStream with promises: an AsyncUnzipStream that reads a zip archive as its bytes arrive.

Its calls resolve to the chunks unzipStream's would return, each as a promise, and can be queued without awaiting. Without a filter it runs where any async stream does: on the calling thread when its chunks add up to under 16 KB and it's finished in the same synchronous run of code as its first call, otherwise in a pool worker.

The filter runs on the calling thread. With one, the worker stops at each entry's header until the filter's answer comes back, a round trip per entry, and each call is sent only once the one before has settled. Such a stream runs on the calling thread only when its first call is a finish holding the whole archive, under 16 KB.

An error the filter throws fails the stream: that call and every later one reject with it. The function never throws: a bad option rejects every call on the stream.

import { encodeText, unzipStreamAsync, zip } from 'kokyu'
import type { UnzipChunk } from 'kokyu'

const archive = zip({
  'server.log': encodeText('GET / 200; '.repeat(5000)),
  'README.txt': encodeText('read me'),
})
// The filter runs on this thread, and the entries it turns down never come back
const stream = unzipStreamAsync({ filter: entry => entry.name.endsWith('.txt') })
const chunks: UnzipChunk[] = []
for (let at = 0; at < archive.length; at += 1024) {
  chunks.push(...await stream.push(archive.subarray(at, at + 1024)))
}
chunks.push(...await stream.finish())
chunks.filter(chunk => chunk.final).map(chunk => chunk.entry.name) // ['README.txt']
  • Fails with: truncated, invalid-data, too-large, unsupported, invalid-option, invalid-state, worker.

Text

Text to UTF-8 or latin1 bytes and back, whole or as streams that keep a character split across two chunks whole.

encodeText
function encodeText(text: string, opts?: TextOptions): Uint8Array<ArrayBuffer>

Encodes a string as UTF-8 bytes, or as latin1 with { latin1: true }.

It returns a new buffer of its own. In UTF-8 it encodes as TextEncoder does, so it never fails: a lone surrogate, half of a pair without the other half, becomes U+FFFD, the bytes EF BF BD.

In latin1 each character becomes one byte, its own code. A character past U+00FF fails with invalid-option rather than being replaced, since latin1 can't hold it.

decodeText with the same option reads the bytes back. In UTF-8 two things don't come back as they were: a lone surrogate returns as U+FFFD, and a U+FEFF at the very start is dropped as a byte order mark. For text that arrives in pieces, encodeTextStream keeps a character split between two of them whole.

import { encodeText } from 'kokyu'

encodeText('héllo') // Uint8Array [0x68, 0xC3, 0xA9, 0x6C, 0x6C, 0x6F]: é takes 2 bytes
encodeText('héllo', { latin1: true }) // Uint8Array [0x68, 0xE9, 0x6C, 0x6C, 0x6F]
// encodeText('€', { latin1: true }) fails with invalid-option: € is U+20AC
  • Fails with: invalid-option.
decodeText
function decodeText(data: Uint8Array, opts?: TextOptions): string

Decodes UTF-8 bytes to a string, or latin1 with { latin1: true }.

In UTF-8 it decodes as TextDecoder does: bytes that aren't valid UTF-8 become U+FFFD and never fail, and a byte order mark (EF BB BF) at the very start is dropped. One anywhere else is kept.

In latin1 each byte becomes the character with its value, U+0000 to U+00FF, so any bytes decode, and encodeText with the same option gives them back. A leading byte order mark stays, as the three characters its bytes are.

It fails only with invalid-option, when data isn't a Uint8Array. For bytes that arrive in pieces, decodeTextStream keeps a character split between two of them whole, where decoding each piece here would turn both halves into U+FFFD.

import { decodeText } from 'kokyu'

const bytes = Uint8Array.of(0x68, 0xC3, 0xA9, 0xFF)
decodeText(bytes) // 'hé\uFFFD': 0xFF is never valid UTF-8
decodeText(bytes, { latin1: true }) // 'héÿ': a character for every byte
decodeText(Uint8Array.of(0xEF, 0xBB, 0xBF, 0x68)) // 'h': the leading byte order mark is dropped
  • Fails with: invalid-option.
encodeTextStream
function encodeTextStream(opts?: TextOptions): Stream<string, Uint8Array<ArrayBuffer>>

Encodes text pushed in pieces, as UTF-8 or latin1, keeping a character split between two pieces whole.

It returns a Stream that takes strings and gives bytes. In UTF-8 a piece that ends in the first half of a surrogate pair holds that half back for the next push, so an emoji split between two pushes encodes as its 4 bytes, not as two U+FFFD. Otherwise a push returns all of its bytes at once. Stream.finish encodes a half still held as U+FFFD, as encodeText would.

In latin1 each push encodes as encodeText with { latin1: true } does, and nothing is held back. A character past U+00FF fails with invalid-option, and since it fails partway through a call, every later call rethrows that error.

The encoding is fixed when the stream is made: changing the options object afterward does nothing. Any call after Stream.finish fails with invalid-state.

import { encodeTextStream } from 'kokyu'

const stream = encodeTextStream()
const party = '🎉' // one character, two UTF-16 code units
stream.push('ok ' + party.slice(0, 1)) // the bytes of 'ok ', with the half held back
stream.push(party.slice(1)) // Uint8Array [0xF0, 0x9F, 0x8E, 0x89]: the whole character
stream.finish() // Uint8Array []
  • Fails with: invalid-option, invalid-state.
decodeTextStream
function decodeTextStream(opts?: TextOptions): Stream<Uint8Array, string>

Decodes bytes pushed in pieces to text, as UTF-8 or latin1, keeping a character split between two pieces whole.

It returns a Stream that takes Uint8Array chunks and gives strings. In UTF-8 a chunk that ends partway through a character holds those bytes back until the next chunk completes it, so a push can return an empty string. Invalid bytes become U+FFFD, as in decodeText, and Stream.finish decodes a character still incomplete as U+FFFD.

A byte order mark at the start of the stream is dropped, even one split between chunks; one later in the text is kept. In latin1 each chunk decodes on its own, one character per byte, and nothing is held back.

A chunk that isn't a Uint8Array fails with invalid-option and leaves the stream as it was. Any call after Stream.finish fails with invalid-state.

import { decodeTextStream, encodeText } from 'kokyu'

const bytes = encodeText('naïve') // ï takes 2 bytes, C3 AF
const stream = decodeTextStream()
stream.push(bytes.subarray(0, 3)) // 'na', with the C3 held back
stream.push(bytes.subarray(3)) // 'ïve'
stream.finish() // ''
  • Fails with: invalid-option, invalid-state.

Checksums

CRC-32, as gzip and zip use it, and Adler-32, as zlib does. Each continues over more data when handed its previous result.

crc32
function crc32(data: Uint8Array, crc?: number): number

The CRC-32 of the bytes, as gzip and zip store it.

It comes back as a whole number from 0 to 2³² − 1, never negative, so it compares directly with a value read from a header. The CRC-32 of no bytes at all is 0.

To checksum data that arrives in pieces, hand each piece the result of the one before as crc. Over any split of the bytes the last result is the CRC-32 of all of them, and nothing is held between calls.

kokyu writes a CRC-32 into every gzip file and zip entry it makes. Its decoders don't check the one they read: call crc32 on the output to verify it yourself.

import { crc32, encodeText } from 'kokyu'

const data = encodeText('123456789')
crc32(data) // 0xCBF43926, the standard check value

// The same over two pieces: each call continues from the last
let crc = crc32(data.subarray(0, 4))
crc = crc32(data.subarray(4), crc)
  • Fails with: invalid-option.
adler32
function adler32(data: Uint8Array, adler?: number): number

The Adler-32 of the bytes, as zlib stores it.

It comes back as a whole number from 0 to 2³² − 1. The Adler-32 of no bytes at all is 1, which is also where a running one starts.

To checksum data that arrives in pieces, hand each piece the result of the one before as adler. Over any split of the bytes the last result is the Adler-32 of all of them.

kokyu writes an Adler-32 into every zlib stream it makes, and its decoders don't check the one they read.

import { adler32, encodeText } from 'kokyu'

const data = encodeText('123456789')
adler32(data) // 0x091E01DE

let sum = adler32(data.subarray(0, 4))
sum = adler32(data.subarray(4), sum)
  • Fails with: invalid-option.

Type to search.