tosijs-schema is a schema-first type library

tosijs-schema owl

Like a lot of folks right now, I'm suddenly interested in using RAG with LLMs to produce structured output. And the way the OpenAI and Google APIs work, you define your output structure using JSON schema.

Interesting.

Wouldn't it be nice to have a language-neutral single source of truth for data structures?

Some time in 2018, I wrote a javascript library that became type-by-example. The goal was to create a type system that would be serializable as JSON (e.g. allowing self-documenting services), did fast validation, and let you write typesafe code using plain Javascript.

I did some spelunking in my old code, and my type library was originally part of b8rjs and it was called examplar.

The basic idea was that for most purposes, an example of a type would serve as the type definition, much as occurs with type inference in TypeScript. It seemed to me then, and still seems to me now, that this was simply the most intuitive way to define types in Javascript.

// a number
exemplar(1) 

// an object with properties x, y that are expected to be numbers
exemplar({x: 0, y: 16})

// an array of x,y coordinates or lat/long/alt coordinates.
exemplar([{x: 0. y: -1}, {lat: 0, long: 0, alt: 0}]) 

It also supported magic string values that allowed more refined types, such as numbers within ranges, enums, unions, and on and on. And, all the types were transmissible as JSON. None of this matters, you aren't going to suddenly start using it. It was one of my "too far ahead of its time" ideas if you want to be charitable, or yet another example of me trying to tilt at windmills while boiling the ocean if you prefer.

type-by-example never took off, although on one memorable occasion it helped find a hard to replicate bug that had been annoying a colleague for months. We simply inserted it deep in the service calling pipeline of an app and had it compare payloads to correct examples and complain about anything that wasn't right. The bug was fixed in minutes.

Anyway, apparently there's now an emerging standard, i.e. JSON schema, that does much of what type-by-example did and has the same virtues, and it's actually being used, so I decided to start using it.

Schema types are more complicated than "exemplars", but it's a fundamentally more robust architecture. For one thing it supports helpful metadata such as descriptions and examples.

It looks like the most popular library for working with JSON schema is called zod. Zod seems pretty nice, but it's TypeScript-first and I'd like to be schema-first. It's one thing to be language-specific, but TypeScript isn't even really a language so much as a preprocessor for a real language.

JSON schemas work at runtime, are language-neutral, are becoming a de-facto standard thanks to their use with LLMs, and can be safely transmitted and consumed as JSON. TypeScript type declarations don't, aren't, aren't really, and can't.

So with that in mind, Gemini 3 Thinking and I have written tosijs-schema.

Creating a schema using tosijs-schema:

import { s, type Infer } from 'tosijs-schema'

const Person = s.object({
  id: s.string.uuid,
  name: s.string.min(2).title("Full Name"),
  age: s.integer.min(0).max(120),
  email: s.string.email.optional,
  tags: s.array(s.string).min(1)
}).meta({
  $schema: 'http://json-schema.org/draft-07/schema#',
  $id: 'https://example.com/schemas/person',
  title: 'Person',
  description: 'A human being record'
})

// Inferring the type from the schema object:
type PersonType = Infer<typeof Person>

JSON Schema Output

This is what you get from Person.schema.

{
  "$schema": "http://json-schema.org/draft-07/schema#",
  "$id": "https://example.com/schemas/person",
  "title": "Person",
  "description": "A human being record",
  "type": "object",
  "properties": {
    "id": {
      "type": "string",
      "format": "uuid"
    },
    "name": {
      "type": "string",
      "minLength": 2,
      "title": "Full Name"
    },
    "age": {
      "type": "integer",
      "minimum": 0,
      "maximum": 120
    },
    "email": {
      "type": [
        "string",
        "null"
      ],
      "format": "email"
    },
    "tags": {
      "type": "array",
      "items": {
        "type": "string"
      },
      "minItems": 1
    }
  },
  "required": [
    "id",
    "name",
    "age",
    "email",
    "tags"
  ],
  "additionalProperties": false
}

My goal was to be as small as Zod (which claims to be 2kB), evaluate data structures in O(1) time (by sub-sampling arrays beyond a certain size, which is a trick I used in type-by-example), and have no external dependencies.

So, does it blend?

📦 GENERATING DATA...

❄️  PHASE 1: COLD START (Simulating Serverless / CLI) ❄️

👉 Cold Run
   [Array 1M] Tosi (Skip): 0.6508 ms
   [Array 1M] Tosi (Full): 192.7280 ms
   [Array 1M] Zod:         334.6354 ms
   ----------------------------------
   🚀 vs Zod: 514.2x faster (Optimized)
   🏎  vs Zod: 1.7x faster (Raw Speed)

   [Dict 100k] Tosi (Skip): 5.3925 ms
   [Dict 100k] Tosi (Full): 26.7653 ms
   [Dict 100k] Zod:         53.1865 ms
   ----------------------------------
   🚀 vs Zod: 9.9x faster (Optimized)
   🏎  vs Zod: 2.0x faster (Raw Speed)


👟 WARMING UP JIT...
   (Engine is hot)


🔥 PHASE 2: HOT JIT (Simulating Long-Running Server) 🔥

👉 Hot Run
   [Array 1M] Tosi (Skip): 0.3252 ms
   [Array 1M] Tosi (Full): 182.1119 ms
   [Array 1M] Zod:         366.4793 ms
   ----------------------------------
   🚀 vs Zod: 1126.9x faster (Optimized)
   🏎  vs Zod: 2.0x faster (Raw Speed)

   [Dict 100k] Tosi (Skip): 2.7027 ms
   [Dict 100k] Tosi (Full): 18.9588 ms
   [Dict 100k] Zod:         57.8862 ms
   ----------------------------------
   🚀 vs Zod: 21.4x faster (Optimized)
   🏎  vs Zod: 3.1x faster (Raw Speed)

The core engine is simply faster than Zod, and when it's allowed to subsample large arrays the difference is ridiculous. And once tosijs-schema actually gets fully JITed it pulls further ahead.

So, in summary:

zod bundled on bundlejs

Also, zod is not 2kB unless you don't actually use any of it.

— Tonio Loewald,