Skip to content

v11.1.0

Latest

Choose a tag to compare

@DZakh DZakh released this 04 Nov 09:05
2ebcac6

Sury 11.1 🚀

The biggest minor release yet. Sury now speaks Protocol Buffers and can generate schemas from .proto files. Validation can report every issue at once, compare sorts your values, and validation failures are up to 10x faster. Most projects upgrade with no changes. The one exception is under Heads up.

Protocol Buffers

Encode and decode the protobuf binary format with an ordinary Sury schema. You don't need a .proto file or a build step, and the same schema still validates, infers types and converts to JSON Schema.

const User = S.schema({
  id: S.int32.with(S.protobufField, 1),
  name: S.string.with(S.protobufField, 2),
  tags: S.array(S.string).with(S.protobufField, 3),
  score: S.optional(S.number).with(S.protobufField, 4),
});

const bytes = S.encodeOrThrow(User, S.protobuf)({ id: 150, name: "Ada", tags: ["ml"] });
// Uint8Array [8, 150, 1, 18, 3, 65, 100, 97, 26, 2, 109, 108]

S.decodeOrThrow(S.protobuf, User)(bytes);
// { id: 150, name: "Ada", tags: ["ml"] }

What you get:

  • All scalar types, repeated fields, maps, enums, oneofs and nested messages
  • Self-referencing messages with S.recursive
  • Google's well-known types: S.date is a Timestamp, S.json is a Value, and Duration, Struct, wrappers and the rest are one option away
  • 64-bit integers decode as bigint, so large ids never lose precision
  • Decoded values are plain objects, not class instances
  • Errors name the field: Failed at addr.street: Protobuf string is not valid UTF-8
  • Passes 696 of 698 binary proto3 cases in Google's official conformance suite

google.protobuf.Any, fully typed

Turn an Any into a union of the messages you expect:

const Payload = S.protobufAny.with(S.to, S.union([
  S.schema({ type: "user", value: User }),
  S.schema({ type: "order", value: Order }),
]));

S.decodeOrThrow(Payload)({ typeUrl: "type.googleapis.com/acme.v1.Order", value: new Uint8Array([8, 5]) });
// { type: "order", value: { total: 5n } }

Share a .proto with other languages

S.toProtoOrThrow(Customer, { package: "acme.v1" });
// syntax = "proto3";
// package acme.v1;
// message Customer { int32 id = 1; }

Or generate schemas from one with protoc-gen-sury

Already have .proto files? protoc-gen-sury ships in the sury package and plugs into buf generate or protoc. It uses the same type names and shapes as protobuf-es, so moving over is mostly an import change.

# buf.gen.yaml
version: v2
plugins:
  - local: protoc-gen-sury
    out: src/gen
    opt: target=ts

Ready-made schemas for Google's well-known types live in sury/protobuf/wkt. ReScript users get them as S.Protobuf.

📖 Protocol Buffers guide for JS · for ReScript · Benchmarks vs protobufjs, protobuf-es and pbf

Every issue at once

A failed parseAsResult now lists every problem, not just the first, so a form can show them all together:

S.parseAsResult(signup, { email: "x", password: "123", tags: ["a", 1] }).issues;
// [
//   { message: 'Expected email, received "x"', path: ["email"] },
//   { message: 'Expected string.length >= 8, received "123"', path: ["password"] },
//   { message: "Expected string, received 1", path: ["tags", 1] },
// ]

Standard Schema validation reports every issue too, so form libraries that accept a Standard Schema get the full list without extra setup. error is still the first issue, the same one parseOrThrow throws.

Sorting with compare

const byDateThenName = S.compareOutput(S.tuple([S.date, S.string]));

events.sort((a, b) => byDateThenName([a.date, a.name], [b.date, b.name]));

compareInput and compareOutput build a comparator you can pass straight to Array.prototype.sort. They work for values with a natural order: strings, numbers, bigints, booleans, dates, URLs, literals, and tuples of these. To sort objects, compare the fields you care about as a tuple, like above. ReScript has them as S.compare and S.compileCompare.

Faster validation failures

Rejecting invalid data got much cheaper, which matters most for unions, parseAsResult and form validation:

Scenario Speedup
parseAsResult with invalid data 8x faster
A union matching a later option 10x faster
Standard Schema validation with invalid data 6x faster
Parsing a recursive tree 35x faster
Async transforms, valid data 13 to 17% faster

Error messages are also built only when you read them, so a failed check no longer copies a large request body into a string nobody looks at.

Better stack traces

  • A compiled operation (const parse = S.parseOrThrow(schema)) now throws errors whose stack starts at the line that called it, not deep inside Sury
  • Firefox and Safari errors now have a stack too, not just Chrome and Node
  • An async operation that fails after an await keeps a stack pointing back at your await

More

  • S.nullish takes a default that replaces both undefined and null:
    S.parseOrThrow(S.nullish(S.string, "fallback"), null); // "fallback"
  • S.arrayBuffer: convert bytes to an ArrayBuffer with S.uint8Array.with(S.to, S.arrayBuffer), without a copy when possible
  • Defaults on transformed arrays: write the default in the shape parsing returns, even when the items are transformed
  • TypeScript exactOptionalPropertyTypes: inferred types work with the flag on, where they used to become never

Fixes

  • Reading an object through S.json leaves missing keys missing, so defaults apply instead of the field becoming null
  • Encoding an object with an optional field through S.shape into S.json no longer crashes
  • A nullable with a default, inside S.optional or a union, no longer rejects values the other options accept
  • S.env handles unset variables correctly for optional and nullable entries that allow an empty string
  • Encoding to a JSON string escapes enum values that weren't checked first, so the output is always valid JSON
  • ReScript: S.option and S.Option.getOr(None) work over nested options and custom transforms

Heads up

A plain string can be JSON text, or a value to store inside JSON, and Sury used to assume the second without asking. Now you choose:

// The string is JSON text: parse it
S.string.with(S.to, S.jsonString.with(S.to, userSchema), "unpack");

// The string is a value: store it as JSON
S.string.with(S.to, S.jsonString, "pack"); // "hi" becomes '"hi"'

Using S.string.with(S.to, S.jsonString) without a choice now throws a clear error that tells you to pick "pack" or "unpack".