Streaming encode/decode utilities for Relish serialization
npm install @grounds/streamStreaming encode/decode utilities for Relish serialization.
``bash`
npm install @grounds/stream
`typescript
import { encodeIterable, decodeIterable } from "@grounds/stream";
import { TypeCode } from "@grounds/core";
// Encode values from async iterable
async function* values() {
yield { type: TypeCode.String, value: "hello" };
yield { type: TypeCode.U32, value: 42 };
}
for await (const result of encodeIterable(values())) {
result.match(
(bytes) => {
// Send bytes (Uint8Array) to network/file
},
(err) => console.error("Encode failed:", err)
);
}
// Decode from chunked input
async function* chunks() {
yield await fetchNextChunk();
}
for await (const result of decodeIterable(chunks())) {
result.match(
(value) => console.log(value), // DecodedValue
(err) => console.error("Decode failed:", err)
);
}
`
`typescript
import { createEncoderStream, createDecoderStream } from "@grounds/stream";
// Encode: RelishValue -> Uint8Array
const encoded = valueStream.pipeThrough(createEncoderStream());
// Decode: Uint8Array -> RelishValue
const decoded = byteStream.pipeThrough(createDecoderStream());
`
`typescript
import { createSchemaEncoderStream, createSchemaDecoderStream } from "@grounds/stream";
import { RStruct, RString, field } from "@grounds/schema";
const UserSchema = RStruct({
name: field(0, RString()),
});
// Type-safe encode: User -> Uint8Array
const encoded = userStream.pipeThrough(createSchemaEncoderStream(UserSchema));
// Type-safe decode: Uint8Array -> User
const decoded = byteStream.pipeThrough(createSchemaDecoderStream(UserSchema));
`
Streaming decoders detect incomplete data at end of stream:
`typescript`
for await (const result of decodeIterable(chunks())) {
result.mapErr((error) => {
if (error.code === "TRUNCATED_STREAM") {
console.error("Incomplete value at end of input");
}
});
}
- encodeIterable(values) - Yields ResultdecodeIterable(chunks)
- - Yields Result
- createEncoderStream() - TransformStreamcreateDecoderStream()
- - TransformStreamcreateSchemaEncoderStream(schema)
- - Type-safe encodercreateSchemaDecoderStream(schema)` - Type-safe decoder
-
Apache 2.0