@nansnunen/sproto-js
v0.1.1
Published
A high-performance TypeScript implementation of cloudwu/sproto with compiled codecs and native path reads.
Readme
@nansnunen/sproto-js
A high-performance TypeScript implementation of the cloudwu/sproto wire format.
This package provides schema parsing, raw encode/decode, sproto pack/unpack, compiled type codecs, and native path reads for reading selected fields without materializing a full object.
Install
npm install @nansnunen/sproto-jsUsage
import * as sproto from "@nansnunen/sproto-js";
const schema = `.Person {
name 0 : string
age 1 : integer
children 2 : *Person
}`;
const sp = sproto.create(schema);
const raw = sp.encode("Person", {
name: "Bob",
age: 40,
children: [{ name: "Alice", age: 13 }]
});
const value = sp.decode("Person", raw);Compiled codecs
Compile a type once when it is used repeatedly. The compiled codec keeps schema lookup work out of encode/decode hot paths.
const person = sp.compile("Person");
const raw = person.encode({ name: "Carol", age: 5 });
const decoded = person.decode(raw);Lazy views
Use view() when field-style lazy reads are more convenient than path arrays.
const personView = person.view(raw);
console.log(personView.name);
console.log(personView.children(0).age);
console.log(personView.children.$length());Scalar fields are read when their getter is accessed. Struct fields and struct array items return lazy views, so nested reads such as personView.children(0).age only read the requested path. Array accessors are callable: field(index) reads one item, $length() counts items without materializing the array, and $value() decodes the full array once and caches it.
Native path reads
read() returns selected fields without fully materializing the payload.
const values = person.read(raw, [
["name"],
["children", 0, "age"]
]);For repeated reads with the same paths, prepare the reader once. This compiles field names into a shared read plan and scans each struct level once for all requested paths.
const reader = person.prepareRead([
["name"],
["children", 0, "age"]
]);
const values = reader.read(raw);Array encoding
Array fields are encoded only when they are explicitly provided. Missing, null, or undefined array fields are skipped and do not appear in decoded output. Pass [] when an empty array should be present on the wire and in decoded results.
Pack and unpack
const packed = sproto.pack(raw);
const unpacked = sproto.unpack(packed);API
create(schema: string | Uint8Array | SprotoSchema): SprotoInstanceparseSchema(schema: string): SprotoSchemapack(bytes: Uint8Array): Uint8Arrayunpack(bytes: Uint8Array): Uint8ArrayunpackInto(input: Uint8Array, output: Uint8Array): numbercodec.view(bytes: Uint8Array): SprotoViewcodec.prepareRead(paths: ReadPath[]): SprotoPreparedReader
Build
npm install
npm run build
npm test
npm run typecheck
npm run benchThe build emits one JavaScript runtime file, dist/sproto.js, plus dist/sproto.d.ts for TypeScript users.
Author
nansnunen
License
MIT. See LICENSE.
