Skip to content

sinclairzx81/typedriver

Repository files navigation

TypeDriver

High Performance Driver for Runtime Type System Integration



npm version Downloads License Test

Install

$ npm install typedriver

Example

Multi-Library Type Compiler and Inference System for High Performance Frameworks

import { compile } from 'typedriver'

const Vector3 = compile(`{
  x: number,
  y: number,
  z: number
}`)

declare const value: unknown

const position = Vector3.parse(value)            // const position: {
                                                 //   x: number,
                                                 //   y: number,
                                                 //   z: number
                                                 // } = ...

Supports: TypeScript | JSON Schema | TypeBox | Effect | Zod | ArkType | Valibot | Arri | Sury | ... and more

Overview

TypeDriver is a high-performance validation and type inference middleware designed to integrate JSON Schema and Standard Schema compliant validation into framework interfaces such as HTTP routes and RPC endpoints. It targets type safety at I/O boundaries by providing a unified validation and inference pipeline that can be bound directly to request-receiving interfaces.

This project is designed to unify heterogeneous runtime schema systems based on JSON Schema and Standard Schema into a single system that preserves static type inference, runtime validation, and schema reflection, while remaining compatible with multiple schema ecosystems.

License MIT

Contents

Features

  • Framework Integration
    • Designed for Type-Safe public IO interfaces (Routes)
    • One Function to compile schematics into uniform Validators.
    • One Type to infer schematics into TypeScript types.
    • Extension Model for Framework Specific Runtime Type APIs
  • Schema Support
    • TypeScript DSL feature for TS7-native (supported in TS5+).
    • Scalable JSON Schema type inference.
    • Supports JSON Schema Drafts 3 through 2020-12.
    • Full support for Standard Schema
  • Validation Compiler
    • High-performance JIT compiler for faster application start up.
    • High-performance runtime validation (approx 2x Ajv under comparable workloads)
    • Automatic Acceleration for libraries supporting Standard JSON Schema.
    • Automatic JIT fallback for Content-Security restrictive environments (Cloudflare)
  • Tooling and Interoperability
    • JSON Schema Reflect API for OpenAPI, MCP, and IDL-Based Systems
    • Error Formats for JSON Schema and Standard Schema Based Systems
    • Localized Error Messages (i18n)

Framework

TypeDriver is designed for framework integration. It provides a simple infrastructure to connect type inference and validation to framework interfaces.

Ref: TypeScript | JSON Schema | Standard Schema

// Next Generation Inference System Based on TypeScript DSL (TS7)

route('/', {
  body: `{
    x: number,
    y: number,
    z: number
  }`
}, (request) => {
  const { x, y, z } = request.body // type-safe!
})

The above interface design is achieved with the following TypeScript definitions

Route Interface Definition (Expand)
import { type Static, compile } from 'typedriver'

export interface RouteOptions<Body extends unknown = unknown> {
  body: Body
}
export type RouteCallback<Path extends string, Options extends RouteOptions> = (
  (request: { url: Path, body: Static<Options['body']> }) => void
)
export function route<Path extends string, const Options extends RouteOptions, 
  Callback = RouteCallback<Path, Options>
>(path: Path, options: Options, callback: Callback) {
  const body_validator = compile(options['body'])
  // todo: ... implement route logic
}

Compile

TypeDriver consists of a single compile(...) function that accepts JSON Schema, Standard Schema or TypeScript definition and returns a Validator instance.

import { compile } from 'typedriver'

Ref: TypeScript

const Vector3 = compile(`{
  x: number
  y: number
  z: number
}`)

Ref: JSON Schema

const Vector3 = compile({ 
  type: 'object',
  required: ['x', 'y', 'z'],
  properties: {
    x: { type: 'number' },
    y: { type: 'number' },
    z: { type: 'number' }
  }
})

Ref: Standard Schema

import * as z from 'zod'

const Vector3 = compile(z.object({ 
  x: z.number(),  
  y: z.number(), 
  z: z.number(), 
}))

Validator

The compile(...) function returns Validator instances to Check, Parse and report Errors for JavaScript values.

Check

The check(...) returns a boolean result.

// Vector3.check(value: unknown): value is Vector3

if(Vector3.check(value)) {

  const { x, y, z } = value // safe
}

Parse

The parse(...) function returns if valid, otherwise throws.

// Vector3.parse(value: unknown): Vector3

const { x, y, z } = Vector3.parse(value)                 

Errors

The errors(...) function returns error diagnostics for values (use after failed check only)

// Vector3.errors(value: unknown): TLocalizedValidationError[]

const errors = Vector3.errors(value)              

The errors(...) function can generate both JSON Schema and Standard Schema error formats.

const errors = Vector3.errors({ x: 1, y: true }, {  
  format: 'json-schema'                             
})

const issues = Vector3.errors({ x: 1, y: true }, {  
  format: 'standard-schema'                         
})
Generated Errors and Issues
// TLocalizedValidationError[]

const errors = [{    
  keyword: "required",    
  schemaPath: "#",
  instancePath: "",
  params: { requiredProperties: [ "z" ] },
  message: "must have required properties z"
},
{
  keyword: "type",
  schemaPath: "#/properties/y",
  instancePath: "/y",
  params: { type: "number" },
  message: "must be number"
}]

// StandardSchemaV1.Issue[]

const issues = [
  { path: [], message: "must have required properties z" },
  { path: [ "y" ], message: "must be number" }
]

Locales

TypeDriver has translations for many different languages and locales.

const issues = Vector3.errors({ x: 1, y: true }, {  
  format: 'standard-schema',                        
  locale: 'ko_KR'                                   
})                                                 
Generated Localization
// StandardSchemaV1.Issue[]

const issues = [
  { path: [], message: "필수 속성 z을(를) 가지고 있어야 합니다" },
  { path: [ "y" ], message: "number이어야 합니다" }
]
Supported Locales
type LocaleString = (
  | "ar_001" | "bn_BD"   | "cs_CZ"   | "de_DE"  | "el_GR"  | "en_US" | "es_419" 
  | "es_AR"  | "es_ES"   | "es_MX"   | "fa_IR"  | "fil_PH" | "fr_CA" | "fr_FR" 
  | "ha_NG"  | "hi_IN"   | "hu_HU"   | "id_ID"  | "it_IT"  | "ja_JP" | "ko_KR" 
  | "ms_MY"  | "nl_NL"   | "pl_PL"   | "pt_BR"  | "pt_PT"  | "ro_RO" | "ru_RU" 
  | "sv_SE"  | "sw_TZ"   | "th_TH"   | "tr_TR"  | "uk_UA"  | "ur_PK" | "vi_VN" 
  | "yo_NG"  | "zh_Hans" | "zh_Hant"
)

Localization support is only available for JSON Schema

Static

TypeDriver provides unified type inference for JSON Schema, Standard Schema and TypeScript | Reference

import { type Static } from 'typedriver'

// TypeScript

type A = Static<`{ 
  x: number,
  y: number,
  z: number
}`>

// JSON Schema

type B = Static<{
  type: 'object',
  required: ['x', 'y', 'z'],
  properties: {
    x: { type: 'number' },
    y: { type: 'number' },
    z: { type: 'number' },
  }
}>

// Standard Schema

import * as z from 'zod'

type C = Static<typeof C>
const C = z.object({
  x: z.number(),
  y: z.number(),
  z: z.number(),
})

Localization support is only available for JSON Schema

Script

The TypeScript DSL is a runtime and type-level emulation of TypeScript. This feature is based on TypeBox's ability to transform TypeScript syntax into JSON Schema. The DSL supports most TypeScript definitions, as well as type-level constraints expressed using JSON Schema keywords.

⚠️ The name Options<T> is subject to change. Because Options is a commonly used type name, it may not be appropriate for schema constraint augmentation. As a result, Options should be considered an experimental feature. TypeBox and TypeDriver are open to suggestions for a more suitable name for this type.

const ClampedVector3 = compile(`{
  x: Options<number, { minimum: 0, maximum: 1 }>,
  y: Options<number, { minimum: 0, maximum: 1 }>,
  z: Options<number, { minimum: 0, maximum: 1 }>
}`)

const JsonSchema = ClampedVector3.toJsonSchema()

// const JsonSchema = {
//   type: "object",
//   required: [ "x", "y", "z" ],
//   properties: {
//     x: { type: "number", minimum: 0, maximum: 1 },
//     y: { type: "number", minimum: 0, maximum: 1 },
//     z: { type: "number", minimum: 0, maximum: 1 }
//   }
// }

Refer to TypeBox for additional information on this feature.

Reflect

Validators can reflect back a JSON Schema representation if the underlying type supports it. This is true for all TypeScript and JSON Schema source types. Reflect can be used for OpenAPI metadata publishing, or RPC systems that need to publish JSON based IDL (interface definition language) to remote callers. Validators provide two functions for this.

import { compile, type Static } from 'typedriver'

const validator = compile(...)

validator.isJSONSchema()    // Returns true if the validator can be converted to 
                            // JSON Schema. This is true when the validator was 
                            // compiled with JSON Schema or TypeScript, but false 
                            // if it was compiled with Standard Schema.

validator.toJSONSchema()    // Returns the JSON Schema for the validator. If the 
                            // validator was compiled with Standard Schema, an 
                            // empty {} is returned to indicate an unknown 
                            // runtime schema.

The source type used for compilation can also be returned via

validator.schema()          // will return the schematic used for compile.

Extensions

TypeDriver enables Frameworks to define custom Runtime Types specific to the Framework. This can be achieved by creating functions that return statically observable JSON Schema. These schematics can be passed to compile(...) and Static and used like any other type.

Ref: Framework Types

import { compile, type Static } from 'typedriver'

interface FrameworkString {
  type: 'string'
}
export function number(): FrameworkString { 
  return { type: 'string' }
}

// ... Usage

const T = number()                     // const T: FrameworkString = { type: 'number' }

type T = Static<typeof T>              // type T = number

This is an advanced feature based on TypeBox's extension model for JSON Schema.

Accelerate

TypeDriver provides acceleration support for libraries that implement the upcoming Standard JSON Schema specification. This is a new specification enables remote type libraries to be integrated directly into TypeBox validation infrastructure. This project tracks upstream implementations of this specification and maintains a benchmark measuring compariative performance with and without compile(...).

$ deno task bench

Benchmark 16M Parse Operations of this Structure | We Measure Time To Complete

const Vector3 = compile(`{
  x: number,
  y: number,
  z: number
}`)

Accelerated Indicates Support for Standard JSON Schema

┌────────────┬────────────┬─────────────┬──────────────┬──────────────┬─────────────────┐
│ (idx)      │ iterations │ accelerated │ default(...) │ compile(...) │ result          │
├────────────┼────────────┼─────────────┼──────────────┼──────────────┼─────────────────┤
│ typescript │ 16000000   │ true"  ------""   30 ms""  ------"      │
│ jsonschema │ 16000000   │ true"  ------""   29 ms""  ------"      │
│ arktype    │ 16000000   │ true"  537 ms""   30 ms""94.41% faster" │
│ arri       │ 16000000   │ false" 3086 ms"" 3049 ms""1.20% faster"  │
│ effect     │ 16000000   │ false"24183 ms""23886 ms""1.23% faster"  │
│ sury       │ 16000000   │ false"  153 ms""  166 ms""8.33% slower"  │
│ valibot    │ 16000000   │ false" 3632 ms"" 3515 ms""3.21% faster"  │
│ zod        │ 16000000   │ false"  575 ms""  603 ms""4.93% slower"  │
└────────────┴────────────┴─────────────┴──────────────┴──────────────┴─────────────────┘

Last Run: Thu Dec 04 2025

Compression

TypeDriver is intended for server-side validation in Node, Deno and Bun runtimes, but can be used in Browsers also. TypeDriver depends on most of TypeBox's internal compiler and TS emulation infrastructure. The following shows the compression metrics for bundled, minified and gzipped. TypeDriver uses esbuild for bundling and Deno local gzipped compression.

$ deno task metrics

Compression Rates

┌───────┬─────────────────────────┬─────────────┬─────────────┬────────────┐
│ (idx) │ path                    │ bundled     │ minified    │ gzipped    │
├───────┼─────────────────────────┼─────────────┼─────────────┼────────────┤
│     0 │ "./task/metrics/all.ts""579.74 KB""286.01 KB""55.14 KB" │
└───────┴─────────────────────────┴─────────────┴─────────────┴────────────┘

Contribute

TypeDriver is open to community contribution. Please ensure you submit an issue before submitting a pull request. This project prefers open community discussion before accepting new features.

About

High Performance Driver for Runtime Type System Integration

Topics

Resources

License

Stars

Watchers

Forks

Packages

No packages published