Skip to content

Ahead-of-time Compiler

Beta

The @paseri/compiler package compiles a Paseri schema ahead of time into a TypeScript module containing the parser, for faster validation.

The @paseri/compiler package is a companion to Paseri; install both.

Terminal window
deno add jsr:@paseri/paseri jsr:@paseri/compiler

Import @paseri/paseri/introspect, then pass schema.toIR() to toSource, which returns the module source as a string:

import * as p from '@paseri/paseri';
import '@paseri/paseri/introspect';
import { toSource } from '@paseri/compiler';
const schema = p.object({
hello: p.string(),
});
const source = toSource(schema.toIR(), { name: 'Greeting' });
// Write `source` to a file (e.g. `greeting.ts`) as part of your build.

The generated module exports safeParseGreeting — a drop-in for the runtime schema that returns the same ParseResult:

import { en } from '@paseri/paseri/locales';
import { safeParseGreeting } from './greeting.ts';
const data = { hello: 'world' };
const result = safeParseGreeting(data);
if (result.ok) {
console.log(`Hello ${result.value.hello}!`);
} else {
const messages = result.messages(en);
throw new Error(`Parsing failed: ${messages}`);
}

It also exports a throwing parseGreeting — the counterpart of the runtime schema’s parse, returning the value or throwing a PaseriError:

import { parseGreeting } from './greeting.ts';
const greeting = parseGreeting({ hello: 'world' });
console.log(`Hello ${greeting.hello}!`);