@yingyeothon/codec
v2.0.1
Published
Tiny codec abstraction (Codec interface + JsonCodec) for encoding domain values into strings.
Readme
@yingyeothon/codec
Tiny codec abstraction: a generic Codec<B> interface for encoding domain values into a base representation B (and decoding them back), plus a jsonCodec implementation that uses JSON strings.
Install
npm install @yingyeothon/codecUsage
ESM:
import { jsonCodec, type Codec } from "@yingyeothon/codec";
interface Context {
a: number;
b: string;
}
const codec: Codec<string> = jsonCodec;
const encoded = codec.encode<Context>({ a: 10, b: "hello" });
const decoded = codec.decode<Context>(encoded);CJS:
const { jsonCodec } = require("@yingyeothon/codec");
const encoded = jsonCodec.encode({ a: 10, b: "hello" });
const decoded = jsonCodec.decode(encoded);Public API
Codec<B>— interface withencode<T>(item: T): Banddecode<T>(value: B): T.jsonCodec— statelessCodec<string>singleton backed byJSON.stringify/JSON.parse. Encodingundefinedreturns the literal string"undefined"; decodingundefinedthrows; decoding invalid JSON throws aSyntaxError.
Migrating from the legacy package
The legacy JsonCodec class is replaced by the stateless jsonCodec const: replace new JsonCodec() with jsonCodec. The Codec<B> interface is unchanged; packaging is dual ESM/CJS, Node >= 20.
