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.
deflatefunction 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
Uint8Arraythat owns its wholeArrayBuffer. 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, anddecompressfalls back to it. Usezliborgzipwhere 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
deflateStreamgives 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 readableUint8Array(a NodeBufferis one), the level isn't a whole number from 0 to 9, or the dictionary isn't aUint8Array.deflateAsyncdoes 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.
- Fails with:
inflatefunction inflate(data: Uint8Array, opts?: InflateOptions): Uint8Array<ArrayBuffer>Decompresses raw deflate data.
It comes back as a new
Uint8Arraythat owns its wholeArrayBuffer. Decoding stops where the deflate data ends, after its last block, and any bytes after that are ignored.It fails with
truncatedwhen the data ends before its last block does,invalid-datawhen it breaks the format's rules, andtoo-largeonce the output would passInflateOptions.maxSize. Raw deflate carries no checksum, so damage that still follows the rules decodes to wrong bytes without failing.Set
maxSizefor 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, useinflateInto; 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.
- Fails with:
inflateIntofunction 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
outfrom its start, as long as the output, and typed byout's buffer: a view of aSharedArrayBuffercomes 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
outfails withtoo-large, and so does output pastInflateOptions.maxSize: the smaller of the two is the cap. A call that fails may already have written part of the output intoout. Every other failure is the same as forinflate.outhas to be a readableUint8Array. Anything else, a missing one included, fails withinvalid-optionrather than falling back to allocating. Input that shares memory withoutis 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 intooutat 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.
- Fails with:
zlibfunction 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
Uint8Arraythat owns its wholeArrayBuffer: the header, the same bytesdeflategives for the input and options, then the input'sadler32in 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 01for levels 0 and 1,78 5Efor 2 to 5,78 9Cfor 6 and78 DAfor 7 to 9.With a
DeflateOptions.dictionarythat isn't empty, the header grows to 6 bytes and carries the dictionary's Adler-32, andunzlibneeds the same dictionary to read the data. An empty dictionary counts as none.It fails only with
invalid-option, asdeflatedoes.zlibStreammakes the same bytes from input in pieces, andzlibAsyncoff 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.
- Fails with:
unzlibfunction unzlib(data: Uint8Array, opts?: InflateOptions): Uint8Array<ArrayBuffer>Decompresses zlib data.
It comes back as a new
Uint8Arraythat owns its wholeArrayBuffer. 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 withtruncated, but its Adler-32 isn't checked. Calladler32on 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 withinvalid-option. A dictionary handed in for data that names none is ignored.Otherwise it fails as
inflatedoes,too-largeincluded once the output would passInflateOptions.maxSize.unzlibIntodecodes into a buffer you already have,unzlibStreamdecodes data that arrives in pieces, andunzlibAsyncworks 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.
- Fails with:
unzlibIntofunction 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
unzlibdoes, and writes the output asinflateIntodoes: the result is a view ofoutfrom its start, as long as the output, and the next decode into the same buffer overwrites it.Output that doesn't fit in
outfails withtoo-large, and so does output pastInflateOptions.maxSize: the smaller of the two is the cap. A call that fails may already have written part of the output intoout. Anoutthat isn't a readableUint8Arrayfails withinvalid-option. Input that shares memory withoutis 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.
- Fails with:
deflateStreamfunction deflateStream(opts?: DeflateOptions): CompressStreamCompresses to raw deflate as a stream: push input in pieces, and take output as it is ready.
Each
CompressStream.pushreturns 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.flushreturns everything pushed so far as output a decoder can read in full, without ending the stream.CompressStream.finishtakes 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
pushreturns. Put together, the outputs are the bytesdeflategives 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 readableUint8Arrayfails withinvalid-optionand leaves the stream as it was. Afterfinish, every call fails withinvalid-state,flushincluded.toTransformStreamturns it into a webTransformStream, anddeflateStreamAsyncruns 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.
- Fails with:
inflateStreamfunction inflateStream(opts?: InflateOptions): StreamDecompresses raw deflate as a stream: push compressed pieces of any size, and get back what each completes.
Each
Stream.pushreturns 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 oncepushreturns.Once the last block ends, later bytes are ignored and pushes return empty arrays.
Stream.finishtakes an optional last chunk, and fails withtruncatedif 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.maxSizecounts 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-largeortruncated, breaks the stream: every later call throws that same error. A chunk that isn't a readableUint8Arrayfails withinvalid-optionand leaves the stream as it was. After afinishthat succeeded, every call fails withinvalid-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.
- Fails with:
zlibStreamfunction zlibStream(opts?: DeflateOptions): CompressStreamCompresses to zlib as a stream.
It works as
deflateStreamdoes, 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
zlibgives for all the input at once, however you split it, with the same exceptions as fordeflateStream: a flush, or one more empty block at level 0.CompressStream.flushreturns 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
deflateStreamdoes.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.
- Fails with:
unzlibStreamfunction unzlibStream(opts?: InflateOptions): StreamDecompresses 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
unzlibdoes: a bad header fails withinvalid-header, and a missing or different dictionary withinvalid-option, from the call that completes it. Then it decodes asinflateStreamdoes, 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 withtruncated. 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 afterfinishevery call fails withinvalid-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.
- Fails with:
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.
gzipfunction 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.
datais only read.The header records no name and a time of 0 unless
GzipOptions.filenameorGzipOptions.mtimesets 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-optionwhendataisn't aUint8Arrayor an option is out of range: aGzipOptions.levelthat 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.gzipStreamcompresses input that arrives in pieces, andgzipAsynccompresses 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.
- Fails with:
gunzipfunction 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
crc32of the output with the 4 bytes that start 8 from the end, read little-endian.It fails with
truncatedwhen the data ends early, an empty input included,invalid-headerwhen it doesn't start as gzip or sets reserved flags,unsupportedfor a member not compressed with deflate,invalid-datafor corrupt deflate data or a wrong length, andtoo-largeonce the output would passGunzipOptions.maxSize. Whendataisn't aUint8Array, ormaxSizeisn't a whole number of bytes, it fails withinvalid-option.With no
maxSizethere is no cap, and 10 KB of input can decode to 10 MB: set one for data you don't trust.gunzipIntodecodes into a buffer you already have, andgunzipStreamdecodes 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.
- Fails with:
gunzipIntofunction 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 ofout's memory, not a copy. Bytes ofoutpast the result are left as they were.Output that doesn't fit in
outfails withtoo-large, as does output pastGunzipOptions.maxSize. On a failureoutmay already hold part of the output.When
dataoverlapsoutin memory, it is read from a copy, since the output would otherwise overwrite input not yet read.It reads and fails as
gunzipdoes, and fails withinvalid-optionwhenoutisn't aUint8Array.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.
- Fails with:
gzipStreamfunction gzipStream(opts?: GzipOptions): CompressStreamCompresses 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 badGzipOptions.level, file name or time fails withinvalid-optionhere rather than on a later call.The first call's output starts with the header, even for an empty chunk, and
Stream.finishreturns the last of the data with the trailer. In between, output trails input: the compressor holds data back to compress it better, so aStream.pushoften returns no bytes.CompressStream.flushsends everything pushed so far without ending the stream.At levels 1 to 9, and with no flush, the bytes are exactly those
gzipgives for the same input and options, however the input was split.A chunk that isn't a
Uint8Arrayfails withinvalid-optionand leaves the stream as it was, and any call afterStream.finishfails withinvalid-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.
- Fails with:
gunzipStreamfunction gunzipStream(opts?: GunzipOptions): StreamDecompresses gzip as a stream: push the compressed bytes in pieces and get back the output each completes.
It returns a
Stream. Likegunzipit 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-headeron the first byte that shows it. Each member's length is checked as its trailer arrives, withinvalid-dataon a mismatch; its CRC-32 is not.Stream.finishfails withtruncatedwhen the data stops inside a member, or before any member at all.GunzipOptions.maxSizecaps the output of all members together, withtoo-large, and a bad one fails withinvalid-optionwhen 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.
- Fails with:
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.
decompressfunction 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 8Bis gzip, read asgunzipreads it, every member included. A valid zlib header is zlib, read asunzlibreads 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, withinvalid-dataortruncated, but now and then random bytes are valid deflate and decode to something.It comes back as a new
Uint8Arraythat owns its wholeArrayBuffer, and fails as the decoder it picked does. Soinvalid-headerandunsupportedcan come from a gzip header, andinvalid-optionfrom zlib data whose dictionary is missing or different. Checksums aren't checked; a gzip member's length is.InflateOptions.maxSizecaps the output in every format, all the members of a gzip file together.InflateOptions.dictionaryapplies to zlib and raw deflate. Gzip has no use for one, but a dictionary that isn't aUint8Arrayis refused whatever the format.decompressIntodecodes into a buffer you already have,decompressStreamdecodes data that arrives in pieces, anddecompressAsyncworks 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.
- Fails with:
decompressIntofunction 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
decompressdoes, and writes the output asinflateIntodoes: the result is a view ofoutfrom 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
outfails withtoo-large, and so does output pastInflateOptions.maxSize: the smaller of the two is the cap. A call that fails may already have written part of the output intoout. Anoutthat isn't a readableUint8Arrayfails withinvalid-option. Input that shares memory withoutis 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.
- Fails with:
decompressStreamfunction decompressStream(opts?: InflateOptions): StreamDecompresses 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,unzlibStreamorinflateStreamdoes, with the same rules for what each push returns, what it keeps and what fails. AStream.finishthat leaves it fewer than 2 bytes in all reads them as raw deflate, so an empty stream fails withtruncated.InflateOptions.maxSizecounts 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
Uint8Arrayfails withinvalid-optionand leaves the stream as it was. After afinishthat succeeded, every call fails withinvalid-state.toTransformStreamturns it into a webTransformStream, anddecompressStreamAsyncruns 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.
- Fails with:
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.
zipfunction 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.entrieslists 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]withZipEntryOptionsfor that entry alone, or to a nested object, which is a folder.ZipInputhas 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-optionfor input that isn't a plain object of bytes,[bytes, options]pairs and folders, for a nameZipInputrefuses, 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 withtoo-large. kokyu does read the ZIP64 archives other tools write.zipAsyncbuilds the same archive off the main thread, andzipStreamwrites 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.
- Fails with:
unzipfunction 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, andzipEntrieslists both. Names are defined as own keys, so an entry named__proto__is just a key.It reads the central directory, as
zipEntriesdoes, 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.filtersees 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 thanUnzipOptions.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 withinvalid-data. Each entry must then decode to exactly the size it states.It fails with
invalid-datafor 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; withtruncatedfor an entry whose data runs past the end; withunsupportedfor an encrypted entry, a compression method other than stored and deflate, and one part of an archive split into several; withtoo-largepastmaxSize, and as soon as a deflated entry decodes past the size it states; and withinvalid-optionwhendataisn't aUint8ArrayormaxSizeisn't a byte count. An error your filter throws comes out as it is.CRC-32s aren't checked: call
crc32on an entry's data to verify it.unzipAsyncdoes the same work off the main thread, andunzipStreamreads 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.
- Fails with:
zipEntriesfunction zipEntries(data: Uint8Array): ZipEntry[]Lists a zip archive's entries without decompressing anything.
It returns a new
ZipEntryfor 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
unzipwould refuse too: one with another compression method, whichZipEntryInfo.compressionshows, and an encrypted one, which nothing in aZipEntrymarks. TheZipEntry.originalSizevalues add up to whatunzipwould decode, so you can judge an archive before you extract it.It fails with
invalid-datafor data that isn't a zip archive or whose central directory is broken, withunsupportedfor one part of an archive split into several, and withinvalid-optionwhendataisn't aUint8Array. 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.
- Fails with:
zipStreamfunction zipStream(opts?: ZipOptions): ZipStreamStarts a zip archive that you write one entry at a time, as a stream.
It returns a
ZipStream. For each entry,ZipStream.filereturns a stream: push the entry's data through it, then finish it before you start the next.ZipStream.finishends 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.
unzipandunzipStreamread both.It takes its options when you call it, so changing them later changes nothing.
ZipOptions.mtimeapplies to every entry without its own, and without either an entry gets the time of itsZipStream.filecall. Names follow the rules ofZipInput, and a second name for a path the archive already has fails withinvalid-option. Entries get the same defaults as inzip.Calling
zipStreamfails only withinvalid-option, for aZipOptions.commentit refuses; a level or time out of range fails when an entry starts. The other codes come from the calls on the stream:invalid-optionfor a bad name orZipEntryOptions,invalid-statefor a call out of order, andtoo-largeonce the archive needs ZIP64, which kokyu doesn't write.zipStreamAsyncdeflates off the main thread, andtoTransformStreamlets 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.
- Fails with:
unzipStreamfunction unzipStream(opts?: UnzipStreamOptions): UnzipStreamStarts 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 theUnzipChunks of entry data it completes, possibly none. An entry's chunks come in order and end with one whoseUnzipChunk.finalis true, all before the next entry's.finishtakes the last bytes, and fails withtruncatedif 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
zipStreamwrites every one, comes without sizes (seeZipEntryInfo.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.filterdecides 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
truncatedfor an archive that ends early; withinvalid-datafor bytes between entries that aren't a header, corrupt deflate data, and an entry of another size than it states; withunsupportedfor an encrypted entry or another compression method, in an entry it has to read; withtoo-largepastUnzipStreamOptions.maxSize; withinvalid-statefor a call afterfinishor from inside its own filter; and withinvalid-optionfor a chunk that isn't aUint8Arrayor a badmaxSize. 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.
unzipStreamAsyncdecodes off the main thread, andtoTransformStreamturns the stream into a webTransformStream.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.
- Fails with:
Streams
What every sync stream shares, the compressors' flush, and toTransformStream, which turns any kokyu stream, sync or async, into a web TransformStream.
toTransformStreamfunction 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
TransformStreamforpipeThrough.Each chunk written goes to
Stream.push, and closing the writable side callsStream.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, asunzipStreamreturns, goes on as one chunk per item. It takes any object withpushandfinish, 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'scancel.A zip entry from
ZipStream.fileorAsyncZipStream.fileis 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, withinvalid-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 aTransformStreaminstance.Bytes the readable side has handed out are out of its sight: an aborted
pipeTocan 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.
deflateAsyncfunction deflateAsync(data: Uint8Array, opts?: DeflateOptions & AsyncOptions): Promise<Uint8Array<ArrayBuffer>>deflateas a promise, compressed in a pool worker when the input is 16 KB or more.It resolves to the bytes
deflatereturns 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 thatAsyncOptionsdescribes.Its input can be reused as soon as the call returns: a worker gets a copy taken at the call, unless
AsyncOptions.transferhands it the buffer itself. Nothing throws: a bad argument rejects the promise with the codedeflatewould throw, and a worker that fails rejects it withworker.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.
- Fails with:
inflateAsyncfunction inflateAsync(data: Uint8Array, opts?: InflateOptions & AsyncOptions): Promise<Uint8Array<ArrayBuffer>>inflateas a promise, decoded in a pool worker when the input is 16 KB or more.It resolves to what
inflatereturns, 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.maxSizebounds that work.Its input can be reused as soon as the call returns: a worker gets a copy taken at the call, unless
AsyncOptions.transfermoves the buffer, and adictionaryis always copied. Every failure rejects the promise; a worker that fails rejects it withworker.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.
- Fails with:
zlibAsyncfunction zlibAsync(data: Uint8Array, opts?: DeflateOptions & AsyncOptions): Promise<Uint8Array<ArrayBuffer>>zlibas a promise, compressed in a pool worker when the input is 16 KB or more.It resolves to the bytes
zlibreturns 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 thatAsyncOptionsdescribes.Its input can be reused as soon as the call returns: a worker gets a copy taken at the call, unless
AsyncOptions.transferhands it the buffer itself, and adictionaryis always copied. Nothing throws: a bad argument rejects the promise with the codezlibwould throw, and a worker that fails rejects it withworker.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.
- Fails with:
unzlibAsyncfunction unzlibAsync(data: Uint8Array, opts?: InflateOptions & AsyncOptions): Promise<Uint8Array<ArrayBuffer>>unzlibas a promise, decoded in a pool worker when the input is 16 KB or more.It resolves to what
unzlibreturns, 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.maxSizebounds it.Its input can be reused as soon as the call returns: a worker gets a copy taken at the call, unless
AsyncOptions.transfermoves the buffer, and adictionaryis always copied. Every failure rejects the promise; a worker that fails rejects it withworker.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.
- Fails with:
gzipAsyncfunction gzipAsync(data: Uint8Array, opts?: GzipOptions & AsyncOptions): Promise<Uint8Array<ArrayBuffer>>gzipas a promise, compressed in a pool worker when the input is 16 KB or more.It resolves to the bytes
gzipreturns 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 thatAsyncOptionsdescribes. 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.transferhands it the buffer itself, and anmtimeis read then too. Nothing throws: a bad argument rejects the promise with the codegzipwould throw, and a worker that fails rejects it withworker.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.
- Fails with:
gunzipAsyncfunction gunzipAsync(data: Uint8Array, opts?: GunzipOptions & AsyncOptions): Promise<Uint8Array<ArrayBuffer>>gunzipas a promise, decoded in a pool worker when the input is 16 KB or more.It resolves to what
gunzipreturns, 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.maxSizebounds it.Its input can be reused as soon as the call returns: a worker gets a copy taken at the call, unless
AsyncOptions.transfermoves the buffer. Every failure rejects the promise, never a synchronous throw; a worker that fails rejects it withworker.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.
- Fails with:
decompressAsyncfunction decompressAsync(data: Uint8Array, opts?: InflateOptions & AsyncOptions): Promise<Uint8Array<ArrayBuffer>>decompressas a promise: gzip, zlib or raw deflate, decoded in a pool worker when the input is 16 KB or more.It resolves to what
decompressreturns, 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.maxSizebounds it.Its input can be reused as soon as the call returns: a worker gets a copy taken at the call, unless
AsyncOptions.transfermoves the buffer, and adictionaryis always copied. Every failure rejects the promise; a worker that fails rejects it withworker.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.
- Fails with:
zipAsyncfunction zipAsync(input: ZipInput, opts?: ZipOptions & AsyncOptions): Promise<Uint8Array<ArrayBuffer>>zipas a promise, built in a pool worker when the entries add up to 16 KB or more.It resolves to the archive
zipbuilds 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 nomtimeis 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 codezipwould throw, and a worker that fails rejects it withworker.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.
- Fails with:
unzipAsyncfunction unzipAsync(data: Uint8Array, opts?: UnzipOptions & AsyncOptions): Promise<Record<string, Uint8Array<ArrayBuffer>>>unzipas a promise, decoded in a pool worker when the archive is 16 KB or more.It resolves to what
unzipreturns, 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.maxSizebounds 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.transfermoves the buffer. A worker that fails rejects the promise withworker.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.
- Fails with:
deflateStreamAsyncfunction deflateStreamAsync(opts?: DeflateOptions & AsyncOptions): AsyncCompressStreamdeflateStreamwith promises: a raw deflateAsyncCompressStream.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.AsyncStreamhas 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.
- Fails with:
inflateStreamAsyncfunction inflateStreamAsync(opts?: InflateOptions & AsyncOptions): AsyncStreaminflateStreamwith promises: anAsyncStreamthat 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.AsyncStreamhas the details.Options are read once, when the stream is made, and a
dictionaryis 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.
- Fails with:
zlibStreamAsyncfunction zlibStreamAsync(opts?: DeflateOptions & AsyncOptions): AsyncCompressStreamzlibStreamwith promises: a zlibAsyncCompressStream.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.AsyncStreamhas the details.Options are read once, when the stream is made, and a
dictionaryis copied. WithAsyncOptions.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.
- Fails with:
unzlibStreamAsyncfunction unzlibStreamAsync(opts?: InflateOptions & AsyncOptions): AsyncStreamunzlibStreamwith promises: anAsyncStreamthat 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.AsyncStreamhas the details.Options are read once, when the stream is made, and a
dictionaryis 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.
- Fails with:
gzipStreamAsyncfunction gzipStreamAsync(opts?: GzipOptions & AsyncOptions): AsyncCompressStreamgzipStreamwith promises: a gzipAsyncCompressStream.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.AsyncStreamhas the details.Options are read once, when the stream is made, an
mtimeincluded.toTransformStreamturns it into a webTransformStream. 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.
- Fails with:
gunzipStreamAsyncfunction gunzipStreamAsync(opts?: GunzipOptions & AsyncOptions): AsyncStreamgunzipStreamwith promises: anAsyncStreamthat 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.AsyncStreamhas 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.
- Fails with:
decompressStreamAsyncfunction decompressStreamAsync(opts?: InflateOptions & AsyncOptions): AsyncStreamdecompressStreamwith promises: anAsyncStreamthat 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.AsyncStreamhas the details.Options are read once, when the stream is made, and a
dictionaryis 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.
- Fails with:
zipStreamAsyncfunction zipStreamAsync(opts?: ZipOptions & AsyncOptions): AsyncZipStreamzipStreamwith promises: anAsyncZipStreamthat 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 firstAsyncZipStream.file; otherwise it runs in a pool worker.Archive options are read when the stream is made, and an entry's when
AsyncZipStream.fileopens it; an entry with nomtimeof 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.
- Fails with:
unzipStreamAsyncfunction unzipStreamAsync(opts?: UnzipStreamOptions & AsyncOptions): AsyncUnzipStreamunzipStreamwith promises: anAsyncUnzipStreamthat 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
finishholding 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.
- Fails with:
Text
Text to UTF-8 or latin1 bytes and back, whole or as streams that keep a character split across two chunks whole.
encodeTextfunction 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
TextEncoderdoes, 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-optionrather than being replaced, since latin1 can't hold it.decodeTextwith 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,encodeTextStreamkeeps 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.
- Fails with:
decodeTextfunction decodeText(data: Uint8Array, opts?: TextOptions): stringDecodes UTF-8 bytes to a string, or latin1 with
{ latin1: true }.In UTF-8 it decodes as
TextDecoderdoes: 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
encodeTextwith 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, whendataisn't aUint8Array. For bytes that arrive in pieces,decodeTextStreamkeeps 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.
- Fails with:
encodeTextStreamfunction 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
Streamthat 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.finishencodes a half still held as U+FFFD, asencodeTextwould.In latin1 each push encodes as
encodeTextwith{ latin1: true }does, and nothing is held back. A character past U+00FF fails withinvalid-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.finishfails withinvalid-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.
- Fails with:
decodeTextStreamfunction 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
Streamthat takesUint8Arraychunks 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 indecodeText, andStream.finishdecodes 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
Uint8Arrayfails withinvalid-optionand leaves the stream as it was. Any call afterStream.finishfails withinvalid-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.
- Fails with:
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.
crc32function crc32(data: Uint8Array, crc?: number): numberThe 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
crc32on 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.
- Fails with:
adler32function adler32(data: Uint8Array, adler?: number): numberThe 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.
- Fails with: