Skip to content

Serialization ​

Convert models to and from JSON, and change the JSON form of a field.

Convert to and from JSON ​

The JSON form of a value is the value as JSON holds it, also called its JSON value. The API names it "wire" in toWireFormat, fromWireFormat and WireFormat<T>.

These calls convert a named IObject or IModel.

  • stringify<T> and parse<T> use JSON text.
  • toWireFormat<T> and fromWireFormat<T> use a plain object.
ts
import type { IObject } from '@exprtlabs/golem/model';
import type { Pattern } from '@exprtlabs/golem/tags';

// Amounts are decimal strings and currencies are ISO 4217 codes; no float carries money.
export type TMoney = IObject<{
  amount: string & Pattern<'^[0-9]+(?:\\.[0-9]{1,2})?$'>;
  currency: string & Pattern<'^[A-Z]{3}$'>;
}>;
ts
import { parse, stringify } from '@exprtlabs/golem/serde';
import { validate } from '@exprtlabs/golem/validation';
import type { TMoney } from './estimate.model.js';

export function readMoney(text: string): TMoney {
  return parse<TMoney>(text); // plain object, validated
}

export function writeMoney(money: TMoney): string {
  return stringify<TMoney>(money);
}

export function isMoney(value: unknown): value is TMoney {
  return validate<TMoney>(value); // for data you did not parse yourself
}
ts
import { parse } from '@exprtlabs/golem/serde';
import { Task } from './task.model.js';
import type { TTask } from './task.model.js';

export function readTask(text: string): Task {
  return parse<Task>(text); // a Task instance with toggle()
}

export function readTaskData(text: string): TTask {
  return parse<TTask>(text); // a plain object with the same fields
}

The type argument picks the model and the result:

  • parse<TMoney> returns a plain object, and parse<Task> returns a Task.
  • new Task(parse<TTask>(text)) parses an IObject and passes it to the Task constructor. Use it when the constructor takes extra arguments.
  • Nested fields follow the field type, not the root type argument.

Build with golem

parse, stringify, fromWireFormat, toWireFormat, validate and assertValue throw unless a build rewrote them. Choose a build tool in Build tools. tsc does not rewrite them.

  • T must be a named generated IObject or IModel. An inline object type is not enough.
  • Unsupported unions fail generation.
  • Write these calls in your own source files. Golem does not rewrite a call inside a generated *.generated.ts file, so it throws at run time.
  • A class whose model has a dynamic map keeps the extra keys of the input and converts each by the type of the map value.

Do not write stringify(toWireFormat(x)) or fromWireFormat(parse(text)) on the JSON path. stringify writes JSON for the declared fields and applies each TSerde serialize formatter. parse reads that JSON back. JSON.stringify(model) does not run conversion or validation.

Model value and JSON value ​

The model value is what your code holds. The JSON form is what toWireFormat returns and stringify writes. For most fields the two are equal. These differ:

  • A Date is a Date in the model and an ISO string in JSON. The Temporal classes are strings in JSON too. Golem converts them with built-in TSerde functions.
  • A TSerde field has the form that its functions give.

A Date converts in these ways:

  • It decodes a date-time string at every validation level, off included. A value that is not a string, or that is not a date-time string, throws Deserialization with causedByInput: true.
  • It encodes as UTC ISO text with milliseconds. A year outside 0000-9999 throws Serialization.
  • Validation of the model value requires a Date that holds a time. Another value, and new Date(NaN), fail with an instance issue (Check a Date or Temporal field).
  • Put your own rule on a Date with TValidation.

A function, a symbol or an array hole is not a JSON value and fails the JSON check.

WireFormat<T> names the JSON shape of a model (IModel or IObject). For IObject declarations, Golem also generates <Alias>JSON type aliases (such as TMoneyJSON); IModel declarations use WireFormat<T>.

Change the JSON form ​

TSerde<typeof encode, typeof decode> is a serialize formatter. encode turns the model value into its JSON value, and decode turns the JSON value back into the model value. Both are synchronous.

TPermissionInput is an IModel. fromWireFormat<TPermissionInput> returns a plain object, and fromWireFormat<PermissionInput> constructs your class.

ts
import type { Integer, Maximum, Minimum, Pattern, TSerde, TValidation } from '@exprtlabs/golem/tags';

// A project member's access bits: 1 reads, 2 writes, 4 administers.
export function hasReadPermission(value: number): boolean | string {
  return (value & 1) !== 0 ? true : 'Read permission is required.';
}

export type PermissionWire = string & Pattern<'^0x[0-9a-fA-F]+$'>;

// TSerde functions live in their own module: generated files import them, and a model file cannot be imported back.
export function encodePermissions(value: number): PermissionWire {
  return `0x${value.toString(16)}`;
}

export function decodePermissions(value: PermissionWire): number {
  return Number.parseInt(value.slice(2), 16);
}

export type PermissionBits = number
  & Integer
  & Minimum<0>
  & Maximum<255>
  & TValidation<typeof hasReadPermission>
  & TSerde<typeof encodePermissions, typeof decodePermissions>;
ts
import { model, type IModel } from '@exprtlabs/golem/model';
import type { PermissionBits } from './permission-rules.js';
import { fromWireFormat, toWireFormat } from '@exprtlabs/golem/serde';
import { validateInstance } from '@exprtlabs/golem/validation';

export type TPermissionInput = IModel<{
  permissions: PermissionBits;
}>;

export class PermissionInput extends model<TPermissionInput>() {}

export async function checkPermissionInput() {
  const access = fromWireFormat<TPermissionInput>({ permissions: '0x5' });
  const wire = toWireFormat<TPermissionInput>(access);
  const issues = await validateInstance(new PermissionInput({ permissions: 2 }));

  // -> { permissions: 5, wire: { permissions: '0x5' }, deniedMessage: 'Read permission is required.' }
  return { permissions: access.permissions, wire, deniedMessage: issues[0]?.message };
}
  • The same behavior applies when the field is nested.
  • Declare the encoder and decoder in their own module, like a TValidation predicate. The generated file imports them, and the model file imports the generated file. A function in the model file makes the two files import each other, and generation stops with RUNM1065.
  • TSerde functions run during conversion, never during generation.
  • A Deserialize function reads wire input. When it throws, the call throws a LibError with the exception as its cause and causedByInput: true.
  • A Serialize function writes your own value. When it throws, the exception reaches your code unchanged. It is not bad input.
  • An encoder must return JSON-compatible data. Non-finite numbers, cycles and other values that JSON cannot hold still fail with validation disabled.
  • The signature and the failures are in the TSerde reference.

Example: money and priority ​

An order holds an amount as integer cents and a priority as a number, so your code can add and sort them. Its JSON holds decimal text and a word, which people and other systems read.

FieldModel valueJSON form
amount1250, an integer in cents"12.50", decimal text
priority3"high"
remindAta Date"2025-01-02T03:04:05.000Z"

Without TSerde, you write a mapper for each direction and call it wherever JSON enters or leaves your code. With TSerde, golem converts the field in every call and checks the value on both sides.

Write the two functions in their own module. Priority is a number in code and a word in JSON:

ts
const PRIORITY_WORDS = ['low', 'normal', 'high'] as const;
export type PriorityWord = (typeof PRIORITY_WORDS)[number];

export function toPriorityWord(value: number): PriorityWord {
  const word = PRIORITY_WORDS[value - 1];
  if (!word) throw new RangeError('Priority must be 1, 2 or 3.');
  return word;
}

export function fromPriorityWord(word: PriorityWord): number {
  return PRIORITY_WORDS.indexOf(word) + 1;
}

An amount is an integer in cents in code and decimal text in JSON:

ts
import type { Pattern } from '@exprtlabs/golem/tags';

export type DecimalText = string & Pattern<'^[0-9]+(?:\\.[0-9]{2})$'>;

// The model keeps integer minor units (cents); JSON carries the exact decimal text.
export function writeAmount(minorUnits: number): DecimalText {
  return `${Math.trunc(minorUnits / 100)}.${String(minorUnits % 100).padStart(2, '0')}`;
}

export function readAmount(text: DecimalText): number {
  return Number(text.replace('.', ''));
}
  • Export each function. Each function is synchronous and takes one parameter.
  • Type the parameter of the decoder as the JSON value. PriorityWord limits the words, and DecimalText limits the text to a pattern. Golem checks the JSON value against this type before it calls the function (Which type controls validation).

Write typeof each function in TSerde, and import the functions as types:

ts
import { model, type IModel } from '@exprtlabs/golem/model';
import type { Integer, Maximum, Minimum, TSerde } from '@exprtlabs/golem/tags';
import type { readAmount, writeAmount } from './decimal-text.js';
import type { fromPriorityWord, toPriorityWord } from './priority-word.js';

export type TOrder = IModel<{
  // Your code adds cents; the JSON carries decimal text.
  amount: number & Integer & Minimum<0> & TSerde<typeof writeAmount, typeof readAmount>;
  // Your code sorts by a number from 1 to 3; the JSON carries a word.
  priority: number & Integer & Minimum<1> & Maximum<3> & TSerde<typeof toPriorityWord, typeof fromPriorityWord>;
  // A Date needs no TSerde: the JSON carries ISO text.
  remindAt: Date;
}>;

export class Order extends model<TOrder>() {}
  • Integer, Minimum and Maximum check the model values: amount is a whole number of cents, priority is 1 to 3.
  • remindAt is a Date and needs no TSerde tag. Use Date fields shows how golem writes it and how to keep its exact text.

Run npx golem generate, then convert the JSON:

ts
export function readOrder(text: string): Order {
  return parse<Order>(text); // an Order instance: amount is 1250 for "12.50"
}
ts
export function writeOrder(order: Order): string {
  return stringify<TOrder>(order); // '{"amount":"12.50","priority":"high","remindAt":"…"}'
}
  • parse<Order> returns an Order. For "12.50", its amount is 1250. For "high", its priority is 3. parse<TOrder> returns a plain object with the same fields.
  • A JSON value that fails its type makes parse throw a LibError. Examples are a word that is not in the list and a text that does not match the pattern (Errors and issues).
  • stringify calls the encoder of each TSerde. Priority 3 becomes "high", and 1250 becomes "12.50".
  • A model that is not valid makes stringify throw a LibError, so validate the model first.

Which type controls validation ​

Here PermissionWire is a string tagged with a hexadecimal pattern, and the model stores permissions as a number:

Declaration or optionEffect
decodePermissions(value: PermissionWire)JSON validation includes the pattern. Generated validation checks it before decoding and after encoding.
Change the decoder parameter to value: stringJSON validation keeps the string type check but drops the pattern, even if the encoder still returns PermissionWire.
permissions: number & Integer & Minimum<0> & …These are validation constraints on the model value. They run after decoding and before encoding, whether the decoder accepts plain string or not.
{ validate: false }Runs only the TSerde serialize formatter, without checks.
  • The decoder parameter type defines the JSON schema.
  • The encoder return type is checked for TypeScript compatibility. Tags on the return type alone add no JSON validation.
  • A plain string parameter keeps the string check and drops the tagged validation constraints on the JSON value. This also applies to aliases such as ProjectName = string & MinLength<3>.
  • A parameter typed any or unknown fails with RUNM1011 unless allowAny is true, in golem.yaml or in the options of the model. Type the parameter as the JSON value that the decoder reads.
  • Calling encodePermissions() or decodePermissions() directly runs only the function body. Type annotations do not perform runtime checks by themselves.

Class values ​

A TSerde field can hold a class instance, such as Uint8Array, or a bigint. The codec does all the conversion. Validation checks the JSON value, and for a class it checks that the model value is an instance of the class.

ts
import type { Pattern } from '@exprtlabs/golem/tags';

export type Base64 = string & Pattern<'^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$'>;

export function encodeBase64(value: Uint8Array): Base64 {
  let binary = '';
  // Chunks keep the argument list of fromCharCode short for large inputs.
  for (let start = 0; start < value.length; start += 0x8000) {
    binary += String.fromCharCode(...value.subarray(start, start + 0x8000));
  }
  return btoa(binary);
}

export function decodeBase64(value: Base64): Uint8Array {
  return Uint8Array.from(atob(value), char => char.charCodeAt(0));
}
ts
import { model, type IModel } from '@exprtlabs/golem/model';
import type { TSerde } from '@exprtlabs/golem/tags';
import type { decodeBase64, encodeBase64 } from './base64-codec.js';

export type TAttachment = IModel<{
  name: string;
  content: Uint8Array & TSerde<typeof encodeBase64, typeof decodeBase64>;
}>;

export class Attachment extends model<TAttachment>() {}

Converting the model writes the JSON form and restores the instance:

ts
import { fromWireFormat, toWireFormat } from '@exprtlabs/golem/serde';
import { Attachment } from './attachment.model.js';

export function roundTripAttachment() {
  const attachment = new Attachment({ name: 'checksum.bin', content: Uint8Array.of(1, 2, 3) });
  const wire = toWireFormat<Attachment>(attachment);
  const copy = fromWireFormat<Attachment>(wire);

  // -> { wire: { name: 'checksum.bin', content: 'AQID' }, copy }, where copy.content is a Uint8Array
  return { wire, copy };
}
  • The Base64 pattern accepts only well-formed base64. A malformed value fails the JSON check as input, before atob runs.
  • The class must have a name and have no type parameter without a default. A module must export it, under any name or as the default export (RUNM1063).
  • A value that is not an instance of the class fails with one instance issue that names the class. A type with no class behind it at run time, such as an interface, has no instance check.
  • A decoder whose JSON value is a string reads only a string. Another JSON value throws Deserialization at every validation level, off included.
  • Declare the class in its own module. A class of a TSerde field that a *.model.ts file declares stops generation with RUNM1065.
  • Date and the Temporal classes are this kind of field with the codec built in, so they need no tag. A TSerde tag on one of them replaces the built-in codec. The Temporal types have their own tags.

Checks during conversion ​

With validation on, the default, each call checks the value. The JSON value and the model value are checked at separate stages, and each rule runs once. Your decoders only see values that passed the JSON check.

CallChecks JSONConvertsChecks model
parse<T>(text)✓✓✓
parse<T>(text, { validate: false })✓
stringify<T>(value)✓✓✓
stringify<T>(value, { validate: false })✓
fromWireFormat<T>(json)✓✓✓
toWireFormat<T>(value)✓✓✓
validate<T>(value)✓

{ validate: false } skips the check for data you already trust. It does not update stored field errors.

ts
import { fromWireFormat } from '@exprtlabs/golem/serde';
import { validateInstance } from '@exprtlabs/golem/validation';
import { TaskInput } from './task-input.model.js';

export async function loadInvalidTask() {
  const draft = fromWireFormat<TaskInput>({ title: '', done: false }, { validate: false });
  const issues = await validateInstance(draft);

  // -> { message: 'Must be at least 1 character', title: '' }: the trusted conversion did not validate
  return { message: issues[0]?.message, title: draft.title };
}
  • parse, stringify, fromWireFormat and toWireFormat take validate: true | 'sanity' | false. { validate: 'sanity' } checks the shape only: JSON types, required and extra keys, union tags, enums, tuple length and date-time values.
  • Without the option, the call uses the default level of its model (rules for a level).
  • A level above the project level throws a LibError of kind ValidationUnavailable. For these four calls, any other value throws a TypeError.
  • A nested model is checked at the level of the call.
  • After a successful parse or fromWireFormat with validation on, call validateInstance(model) again only after you edit the instance. Call getValidator(model).validate() to store all field errors for display.
  • failFast: false throws with every issue instead of the first one. It does not turn the check off.
  • validate<T>(value) from @exprtlabs/golem/validation narrows value to the model and returns whether it matches, without throwing. validateInstance(model) returns the issues and does not throw for an ordinary invalid value.
  • When validation is off, generated output has no checks. { validate: true } and { validate: 'sanity' } then throw a LibError of kind validation_unavailable. In a project at sanity, { validate: true } throws it too. With validation off, a missing required field is not reported: stringify leaves it out, and toWireFormat returns it as undefined.

Copies and references ​

  • fromWireFormat and parse copy objects, maps (Record<string, V>) and arrays.
  • Values typed unknown or any (the model sets allowAny: true) are carried by reference, including the undeclared properties of an open object. The result holds the same object as the input.
  • Cyclic input throws a LibError of kind deserialization.
  • Encoding a cyclic value throws a LibError of kind serialization.

Full example: examples/models.