api #

a performance-focused schema library for JS

7 modules ยท 153 declarations

Modules
#

AnySchema
#

schema.ts view source

type Schema<any, any, string, any>

A schema of any types, for code that holds or reads one without typing its output. Every schema assigns to it, and to a bare Schema, which types what a run is given and returns as unknown where this types them any.

import type {AnySchema} from '@fuzdev/fuz_schema/schema.ts';

members

readonly

kind

: string
#
readonly

def

: any
#
readonly

run

: (value: any, ctx: SchemaContext, parent?: Record<PropertyKey, unknown>, key?: PropertyKey, entry?: 1) => any
#

A schema that reads parent and key declares them as plain parameters, with no default and not as a rest: nullable, union, pipe, and message pass them on only to a run whose length says it takes them or to a schema of kind 'lazy', read once when each is made. A lazy passes on the object and the key it is called with.

value
: any
#

the value to validate

the state of the parse, where a failure is reported with fail

parent
?: Record<PropertyKey, unknown>
#

the object value was read from, when an object schema is running an entry

key
?: PropertyKey
#

the entry's key in parent, given with it

entry
?: 1
#

1 when this schema is the entry itself, as an object schema hands it and a message around it passes on, and absent where another schema passes the object and the key on

readonly

'~types'

?: { readonly input: any; }
#

Type-only, never set at runtime.

readonly

'~refines'

?: boolean
#

Type-only, never set at runtime. true on a SchemaRefinement, and a boolean here, so a schema typed as one that isn't, a transform included, is not assignable to one, and a pipe step that may be either is typed by its own output.

array
#

schema.ts view source

array<T extends Schema>(schema: T): ArraySchema<T>

Matches an array whose items all match schema. The output is the input itself when no item changed.

import {array} from '@fuzdev/fuz_schema/schema.ts';

ArraySchema
#

schema.ts view source

ArraySchema<T>

The type of array(schema), where T is the type of schema.

import type {ArraySchema} from '@fuzdev/fuz_schema/schema.ts';

generics

ArraySchema<T extends Schema>

T

constraint Schema

inheritance

extends: Schema<Infer<T>[], InferInput<T>[], "array", T>

bigint
#

BigintSchema
#

schema.ts view source

The type of bigint.

import type {BigintSchema} from '@fuzdev/fuz_schema/schema.ts';

inheritance

extends: Schema<bigint, bigint, "bigint", undefined>

boolean
#

schema.ts view source

BooleanSchema

Matches true and false.

import {boolean} from '@fuzdev/fuz_schema/schema.ts';

BooleanSchema
#

schema.ts view source

The type of boolean.

import type {BooleanSchema} from '@fuzdev/fuz_schema/schema.ts';

inheritance

extends: Schema<boolean, boolean, "boolean", undefined>

brand
#

schema.ts view source

brand<T extends AnySchema>(schema: SchemaAction<TOutput, TInput, TKind, TDef>, name: TName): SchemaAction<Branded<TOutput, TName>, TInput, TKind, TDef>

Brands the output type of schema with name, see Branded. The input type is unchanged. The schema is returned as-is, so this adds nothing to a parse and is invisible to introspection: kind and def are the wrapped schema's.

It goes outside a step that changes the value: of pipe(string, uuid, to_lower_case) and not of the uuid in it, as a to_lower_case outputs a new string and drops a brand of the step before it.

import {brand} from '@fuzdev/fuz_schema/schema.ts';

parameters

schema

: SchemaAction<TOutput, TInput, TKind, TDef>
#

the schema to brand

name

: TName
#

the brand's name, which exists only in the types and is not stored

overloads

brand<TInput, TOutput, TKind extends string, TDef, const TName extends string>(schema: SchemaAction<TOutput, TInput, TKind, TDef>, name: TName): SchemaAction<Branded<TOutput, TName>, TInput, TKind, TDef>
brand<T extends Schema, const TName extends string>(schema: T, name: TName): BrandSchema<T, TName>

Brand
#

schema.ts view source

Brand<T>

The marker Branded adds: a required property, so unmarked values don't fit. Its names are keys, each holding itself, so a brand of a brand holds both and a wide name like string matches no particular one.

import type {Brand} from '@fuzdev/fuz_schema/schema.ts';

generics

Brand<T extends string>

T

constraint string

Branded
#

schema.ts view source

Branded<TValue, TName>

type (TValue & Brand<TName>) | (TValue & (Extract<TValue, null | undefined>)) | (TValue & (unknown extends TValue ? null | undefined : never))

Strict nominal typing. A plain value of the base type is not assignable to the branded type, so the only way to get one is through a schema or a cast. Good for values that must have been validated.

type Uuid = Branded<string, 'Uuid'>; const a: Uuid = 'abc'; // error! const b: Uuid = 'abc' as Uuid; // ok

Brands compose: a brand of a branded type carries both, so it is assignable to the brand it refines and not the reverse.

type Path = Branded<string, 'Path'>; type DirPath = Branded<Path, 'DirPath'>; const p: Path = 'a/' as DirPath; // ok const d: DirPath = 'a' as Path; // error!

A union of names marks with every one of them, as a brand of a brand does.

null and undefined pass through unmarked: Branded<string | null, 'Uuid'> is the branded string or null, and a plain null is assignable to it. Branded<unknown, 'Uuid'> is Brand<'Uuid'> | null | undefined.

import type {Branded} from '@fuzdev/fuz_schema/schema.ts';

generics

Branded<TValue, TName extends string>

TValue

TName

constraint string

BrandSchema
#

schema.ts view source

BrandSchema<T, TName>

The type of brand(schema, name) where schema, of type T, is not an action: T with its output branded TName, and its kind and def.

import type {BrandSchema} from '@fuzdev/fuz_schema/schema.ts';

generics

BrandSchema<T extends Schema, TName extends string>

T

constraint Schema

TName

constraint string

inheritance

extends: Schema<Branded<Infer<T>, TName>, InferInput<T>, T['kind'], T['def']>

members

readonly

'~types'

?: { readonly input: InferInput<T>; } & PipeFirstTypes<T>
#

check
#

schema.ts view source

check<V extends T, T = V>(fn: (value: T) => boolean, expected?: string): SchemaRefinement<Uninferred<V>, V, "check", (value: T) => boolean>

Fails when fn returns false.

In a pipe it is typed as the step before it, and fn may take more than that, as check((v: unknown) => ...) after string, whose output is still a string. Outside a pipe it takes what fn does.

to_schema_json refuses it, as it holds a function.

import {check} from '@fuzdev/fuz_schema/schema.ts';

parameters

fn

: (value: T) => boolean
#

returns false for a value that fails

expected

?: string = 'check'
#

describes what was expected, defaulting to 'check'

check_at
#

schema.ts view source

check_at(path: K, fn: (value: T) => boolean, expected?: string): SchemaRefinement<Uninferred<V>, V, "check", (value: T) => boolean>

Fails when fn returns false, as check does, with its issue at path below the value: a check of an object that is about one of its fields, as check_at('confirm', (v) => v.password === v.confirm) is. The issue's path is from the root, as every issue's is, the keys above the value then path.

path is a key of the value, or the keys from the value in, each a key of what the one before leads to, and a typo fails to compile in either form. A key of a union is one of every option's, of a record any string, of an array any number, and of unknown anything; a nullable is read through. It is checked against the value's type and never types it, which comes from the step before in a pipe, as a check's does. Of a value of a generic type, a key is checked against the type's constraint, and a path of keys is refused unless fn names the type of its parameter, which the path is then checked against, as is a key or path typed wider than a literal.

Its received is the type of the value at path, read through the value's keys, own or inherited, as an object schema reads an entry, and undefined where it leads through something that isn't an object. So get_issue_value(issue, input) finds it where the path is of own keys, and refuses otherwise.

It is a check to every reader: its kind is 'check', its def is fn, and path is in neither. A pipe stops at the first step that fails, so of several check_ats one at a time reports its issue.

import {check_at} from '@fuzdev/fuz_schema/schema.ts';

parameters

path

: K
#

a key, or the keys from the value in, outermost first

fn

: (value: T) => boolean
#

returns false for a value that fails

expected

?: string
#

describes what was expected, defaulting to 'check'

overloads

check_at<V extends T, T = V, const K extends SchemaKeyOf<T> = SchemaKeyOf<T>>(path: K, fn: (value: T) => boolean, expected?: string): SchemaRefinement<Uninferred<V>, V, "check", (value: T) => boolean>
check_at<V extends T, T = V, const TPath extends readonly PropertyKey[] = readonly PropertyKey[]>(path: TPath & (SchemaPathOf<T, TPath>), fn: (value: T) => boolean, expected?: string): SchemaRefinement<Uninferred<V>, V, "check", (value: T) => boolean>

compile_guard
#

compile.ts view source

compile_guard<T extends Schema>(schema: T): (value: unknown) => value is InferInput<T>

Compiles schema to a guard: a function that gives is(schema, value), from straight-line code that builds no issue, and no context or output but where a subtree runs in place, a memo_union keeps its verdicts, or a step of a pipe makes the value the next step is given.

Every kind of the library is compiled. A schema of a kind defined outside it, or whose def is not what its kind holds, is run in place by its own run, in probe mode, with the code around it compiled. Where new Function is refused, the function returned calls is.

A user's check, transform, and with_default_fn run as is runs them, and again in is where compiled code ran out of stack, see the module's comment for what may differ from is, what is refused, and the bound of a schema that compiles.

import {compile_guard} from '@fuzdev/fuz_schema/compile.ts';

parameters

schema

: T
#

read at the compile, by its kind and def, and never written to

returns

the guard, which the caller keeps: nothing is kept on the schema

throws

  • Error - naming the path where schema, or what a lazy's function returns, is not a schema, the kind and the path of a schema nested deeper than COMPILE_MAX_DEPTH, through every lazy, and the path of a union or a pipe the library can walk in time exponential in the depth of an input, with what to write instead

examples

const User = s.object({name: s.string, tags: s.array(s.string)}); const is_user = compile_guard(User); is_user({name: 'Ada', tags: []}); // true is_user({name: 'Ada'}); // false

COMPILE_MAX_DEPTH
#

compile.ts view source

127

The most schemas around one, through every lazy, that a compile follows. A schema nested deeper is refused, which is how a lazy whose function makes a new schema each time it is called ends.

import {COMPILE_MAX_DEPTH} from '@fuzdev/fuz_schema/compile.ts';

compile_parse
#

compile.ts view source

compile_parse<T extends Schema>(schema: T): (value: unknown) => SchemaResult<Infer<T>>

Compiles schema to a parse: a function that gives parse(schema, value).

For an input that matches, the result is built by compiled code: the input itself where nothing changed, and a copy only where the library makes one, with the library's keys, in its order. A keyed_record, an object_with_rest, a union that may try an option again without its key, a memo_union that can change a value, and a schema with no code of the compiler's are run in place, by their own run, for their output. For an input that fails, the function calls parse, so the issues are the library's. Where new Function is refused, it calls parse for every input.

A user's check, transform, and with_default_fn that ran before a failure run again in that parse, see the module's comment for what may differ from parse, what is refused, and the bound of a schema that compiles.

import {compile_parse} from '@fuzdev/fuz_schema/compile.ts';

parameters

schema

: T
#

read at the compile, by its kind and def, and never written to

returns

the parse, which the caller keeps: nothing is kept on the schema

throws

  • Error - naming the path where schema, or what a lazy's function returns, is not a schema, the kind and the path of a schema nested deeper than COMPILE_MAX_DEPTH, through every lazy, and the path of a union or a pipe the library can walk in time exponential in the depth of an input, with what to write instead

examples

const Settings = s.object({theme: s.with_default(s.string, 'dark')}); const parse_settings = compile_parse(Settings); parse_settings({}); // {ok: true, value: {theme: 'dark'}} parse_settings({theme: 1}); // {ok: false, issues: [...]}, from `parse`

fail
#

schema.ts view source

fail(ctx: SchemaContext, kind: string, value: unknown, expected?: string): any

Records an issue. Returns value so a run can fail in expression position.

import {fail} from '@fuzdev/fuz_schema/schema.ts';

parameters

the state of the parse the failure is reported to

kind

: string
#

the issue's kind: the schema's, or missing_key or unknown_key. An invalid_key is not passed here: keyed_record sets it on the issue its key schema reported

value

: unknown
#

the value that failed, which the issue names the type of and doesn't hold

expected

?: string = kind
#

describes what was expected, defaulting to kind

mutates

  • ctx โ€” increments ctx.fails, and outside probe mode, for the first hundred failures of a parse, pushes to ctx.issues, creating it on the first

find_schema_meta
#

introspect.ts view source

find_schema_meta<TKey extends keyof SchemaMeta>(schema: AnySchema, key: TKey, options?: FindSchemaMetaOptions): Exclude<SchemaMeta[TKey], undefined>[]

Every value of metadata key other than undefined on any schema reachable from schema, for a key that must not be missed wherever it is attached, as a mark on a shared schema reused deep inside another. The caller decides what several values mean, as which of them is the strongest.

  • It goes through every layer, as get_schema_meta does, and also every schema and action of a pipe, not only its first, every option of a union, a memo_union, and a variant, and with structural the schemas of a value's parts.
  • A layer that has the key as undefined has cleared it for the layers under it, as get_schema_meta reads it, and not for what those hold: the options, the later steps of a pipe, and the parts are read as ever. A schema reached again past no such layer is read there.
  • Each schema object is read once for its value, and walked at most twice, under a layer that cleared the key and under none, a lazy's function called at each, so a recursive schema ends, lazy(() => optional(L)) as L included. A cycle that builds a new lazy each time round, as const f = () => optional(lazy(f)), never meets a schema it has read and ends in a stack overflow, though a parse of a finite value can end on it.
  • The values come depth first, a schema before what it holds, which comes in the order of its def: a pipe's steps, a union's options, an object's entries, then the rest. A value is there once for each schema object it is attached to, so the same value can come more than once.
  • flavor and brand return the schema they were given, and message carries its metadata over to the one it returns, so metadata on the schema given to any of them is found.
  • Nothing but a lazy's function is called, and a kind defined outside the library is read and not looked into.
import {find_schema_meta} from '@fuzdev/fuz_schema/introspect.ts';

parameters

key

: TKey
#

a key of SchemaMeta, description or one added by declaration merging

FindSchemaMetaOptions
#

introspect.ts view source

Options of find_schema_meta.

import type {FindSchemaMetaOptions} from '@fuzdev/fuz_schema/introspect.ts';

members

structural

?: boolean
#

Whether to look into the schemas of a value's parts too: the entries of every object schema, the rest of an object_with_rest, what an array and a record hold for each item, and the key schema and then the value schema of a keyed_record.

flavor
#

schema.ts view source

flavor<T extends AnySchema>(schema: SchemaAction<TOutput, TInput, TKind, TDef>, name: TName): SchemaAction<Flavored<TOutput, TName>, TInput, TKind, TDef>

Flavors the output type of schema with name, see Flavored. The input type is unchanged. The schema is returned as-is, so this adds nothing to a parse and is invisible to introspection: kind and def are the wrapped schema's.

It goes outside a step that changes the value: of pipe(string, uuid, to_lower_case) and not of the uuid in it, as a to_lower_case outputs a new string and drops a flavor of the step before it.

import {flavor} from '@fuzdev/fuz_schema/schema.ts';

parameters

schema

: SchemaAction<TOutput, TInput, TKind, TDef>
#

the schema to flavor

name

: TName
#

the flavor's name, which exists only in the types and is not stored

overloads

flavor<TInput, TOutput, TKind extends string, TDef, const TName extends string>(schema: SchemaAction<TOutput, TInput, TKind, TDef>, name: TName): SchemaAction<Flavored<TOutput, TName>, TInput, TKind, TDef>
flavor<T extends Schema, const TName extends string>(schema: T, name: TName): FlavorSchema<T, TName>

Flavor
#

schema.ts view source

Flavor<T>

The marker Flavored adds: an optional property, so unmarked values still fit. Its names are keys, each holding itself, so a flavor of a flavor holds both and a wide name like string matches no particular one.

import type {Flavor} from '@fuzdev/fuz_schema/schema.ts';

generics

Flavor<T extends string>

T

constraint string

Flavored
#

schema.ts view source

Flavored<TValue, TName>

type (TValue & Flavor<TName>) | (TValue & (Extract<TValue, null | undefined>)) | (TValue & (unknown extends TValue ? unknown : never))

Loose nominal typing. A plain value of the base type is assignable to the flavored type, so producing one needs no cast or parse, but two different flavors of the same base type are not assignable to each other. Good for values like ids and units, where mixing them up is the bug to prevent.

type Email = Flavored<string, 'Email'>; type Address = Flavored<string, 'Address'>; const email: Email = 'a@b.c'; // ok const address: Address = email; // error!

Flavors compose: a flavor of a flavored type is a narrower flavor, assignable to the one it flavors and not the reverse, as a brand of a brand is.

type WorkEmail = Flavored<Email, 'WorkEmail'>; const work: WorkEmail = 'a@b.c'; // ok const e: Email = work; // ok const w: WorkEmail = email; // error!

null and undefined pass through unmarked: Flavored<string | null, 'Email'> is the flavored string or null. Flavored<unknown, 'Email'> is unknown, the one type every plain value assigns to.

Of a type parameter whose constraint rules out null and undefined, as T extends string and T extends {} do, two flavors assign to each other. Generic code that keeps them apart flavors the constraint and intersects it with the parameter, which a plain T still assigns to:

// compiles: the two flavors of `T` mix const f = <T extends string>(x: Flavored<T, 'UserId'>): Flavored<T, 'PostId'> => x; // error! const g = <T extends string>( x: T & Flavored<string, 'UserId'> ): T & Flavored<string, 'PostId'> => x;
import type {Flavored} from '@fuzdev/fuz_schema/schema.ts';

generics

Flavored<TValue, TName extends string>

TValue

TName

constraint string

FlavorSchema
#

schema.ts view source

FlavorSchema<T, TName>

The type of flavor(schema, name) where schema, of type T, is not an action: T with its output flavored TName, and its kind and def.

import type {FlavorSchema} from '@fuzdev/fuz_schema/schema.ts';

generics

FlavorSchema<T extends Schema, TName extends string>

T

constraint Schema

TName

constraint string

inheritance

extends: Schema<Flavored<Infer<T>, TName>, InferInput<T>, T['kind'], T['def']>

members

readonly

'~types'

?: { readonly input: InferInput<T>; } & PipeFirstTypes<T>
#

format_issue
#

schema.ts view source

format_issue(issue: SchemaIssue): string

Formats an issue as path: expected X, received Y, the path's keys joined with ..

A key that isn't only word characters is quoted as JSON, so the text reads one way whatever the input's keys are: a.b is two keys and "a.b" is one, and a key with a newline or carriage return stays on its line. Text set by message is used as it is.

import {format_issue} from '@fuzdev/fuz_schema/schema.ts';

format_issue_with_value
#

schema.ts view source

format_issue_with_value(issue: SchemaIssue, input: unknown): string

Formats an issue as format_issue does, with the value that failed in place of its type where get_issue_value(issue, input) finds it and it is a string, a number, or a boolean: kind: expected "function" | "variable", received "funtion".

  • A string is quoted as JSON, so a \n or \r can't add a line, and only its first 32 code units are written, with โ€ฆ after the closing quote when it has more. JSON's escapes can make those longer: a lone surrogate, as a cut can leave, is six characters. As in a key, U+2028, U+2029, and U+0085 are written as they are.
  • A number is written as String writes it, but -0 as -0.
  • An unknown_key or a missing_key issue is written as format_issue writes it: what failed there is whether the key is present, and an unknown key's value is the field least meant to be sent. An invalid_key issue is written with the key, which is what failed, or with the last key of its path where the key schema added to it with a check_at.
  • Any other value, an issue get_issue_value refuses, and an issue with text set by message read as format_issue writes them.

The text holds part of the input, which no issue and no SchemaError does, so it is built where the input is still held, as at the catch site of parse_or_throw: error.issues.map((issue) => format_issue_with_value(issue, input)). Keep it where the input itself could go.

import {format_issue_with_value} from '@fuzdev/fuz_schema/schema.ts';

parameters

input

: unknown
#

the value given to parse, unchanged since

throws

  • TypeError - where get_issue_value does, on a revoked Proxy on the path, and whatever a trap or a getter there throws

format_schema_type
#

introspect.ts view source

format_schema_type(schema: AnySchema): string

Renders the type schema accepts as TypeScript-like text, for help output: Array<string> | null, {name: string; port?: number}, "a" | "b".

  • A with_default and a with_default_fn render as their schema, leaving the default to be shown apart, and an optional adds | undefined.
  • An entry is marked ? when a layer is an optional, a with_default, or a with_default_fn. A union with an optional option lets the key be missing too, and isn't looked into.
  • The other keys of a loose_object render as [key: string]: unknown, and those of an object_with_rest as its rest, after the entries.
  • A pipe renders as its first schema, what it accepts.
  • A keyed_record renders as Record<K, V>, its key schema as K, a finite one too, whose keys are each optional.
  • A lazy renders as the schema its function returns, once, and one that returns a lazy as what that returns: a lazy inside that renders as ..., recursive or not. So a recursive schema shows one level of itself, whatever its functions build, short of a lazy that only returns a lazy, which a parse can't end either, and a lazy nested in another shows as ... though it would end.
  • A string literal is quoted as JSON, as the expected text of an issue has it, and a bigint ends in n.
  • A kind with no text of its own, an action or one defined outside the library, renders as its kind.
import {format_schema_type} from '@fuzdev/fuz_schema/introspect.ts';

get_issue_value
#

schema.ts view source

get_issue_value(issue: SchemaIssue, input: unknown): { ok: true; value: unknown; } | { ok: false; }

Reads the value issue is about out of input, the value that was parsed, by following issue.path. It refuses where it would have to guess:

  • when the path leads through something that isn't an object or array
  • when what it finds is not of the type the issue received

Only own keys are read. A key that is missing reads as undefined, which is what the schema saw, so a missing required key is found with the value undefined. An inherited value is never returned. An invalid_key issue is about a key, the last of its path, which is returned without reading input: the key, unless the key schema added to the path with a check_at.

The check is by type name, so it can't tell a value from another of the same type. Where an earlier step of a pipe replaced the value with one of its own type (a transform, or a container that applied a default or dropped a key) the issue is about the replacement, and what is returned is the input's value at that path.

import {get_issue_value} from '@fuzdev/fuz_schema/schema.ts';

parameters

input

: unknown
#

the value given to parse, unchanged since

returns

ok with the value, or not ok when it can't be reached

get_meta
#

meta.ts view source

get_meta(schema: AnySchema): Readonly<SchemaMeta> | undefined

Reads the metadata attached to schema by meta, or undefined when it has none. Only that object is looked at, not the schemas inside it.

import {get_meta} from '@fuzdev/fuz_schema/meta.ts';

returns

the stored object, the same one on every call and the one a message built over schema carries, so a change made to it through a cast shows on both

get_schema_entries
#

get_schema_fields
#

introspect.ts view source

get_schema_fields(schema: AnySchema): SchemaField[]

Reads every entry of schema, in order, or none when it isn't an object schema under its wrappers.

import {get_schema_fields} from '@fuzdev/fuz_schema/introspect.ts';

get_schema_meta
#

introspect.ts view source

get_schema_meta<TKey extends keyof SchemaMeta>(schema: AnySchema, key: TKey): SchemaMeta[TKey] | undefined

The value of metadata key on the outermost layer of schema that has the key. A layer that has it as undefined has cleared it, as meta says, and gives undefined whatever a layer under it holds, as to_json_schema reads the layers. The later steps of a pipe are no layers and are not read, where to_json_schema writes what they hold over the first's. get_meta reads the one object it is given.

import {get_schema_meta} from '@fuzdev/fuz_schema/introspect.ts';

parameters

key

: TKey
#

a key of SchemaMeta, description or one added by declaration merging

Infer
#

schema.ts view source

Infer<T>

type T["run"] extends (...args: any) => infer R ? R : any

The output type of a schema, the type its run returns. Infer<Schema> is unknown and Infer<AnySchema> is any.

A helper generic over schemas of this library and of others reads it behind a test, as T extends Schema ? Infer<T> : never. Infer<T & Schema> is unknown for any T, a schema of this library included: the intersection's run is an overload of T's and Schema's, and ReturnType reads the last, Schema's, which returns unknown.

import type {Infer} from '@fuzdev/fuz_schema/schema.ts';

generics

Infer<T extends Schema>

T

constraint Schema

InferInput
#

schema.ts view source

InferInput<T>

type NonNullable<T["~types"]>["input"]

The input type a schema accepts.

import type {InferInput} from '@fuzdev/fuz_schema/schema.ts';

generics

InferInput<T extends Schema>

T

constraint Schema

integer
#

schema.ts view source

SchemaRefinement<number, number, "integer", undefined>

type SchemaRefinement<number, number, "integer", undefined>

Fails a number that isn't an integer: one with a fraction, and alone NaN and the infinities too. An integer past the safe range passes, as it is an integer: safe_integer is the stricter test. In a pipe its output is the type of the step before it: pipe(one_of([1, 2]), integer) gives 1 | 2.

import {integer} from '@fuzdev/fuz_schema/schema.ts';

is
#

schema.ts view source

is<T extends Schema>(schema: T, value: unknown): value is InferInput<T>

Checks whether value matches schema, without building issues and stopping at the first failure. Narrows to the input type because the output is discarded.

A type predicate narrows where it fails too, to what is left of the value's type without the input type. A schema that refuses values of its own input type, as a pipe with a check does, leaves a refused one typed as no such value: past if (is(pipe(string, min_length(3)), value)) return a string | number is typed number, though a short string reaches it.

import {is} from '@fuzdev/fuz_schema/schema.ts';

is_memo_union
#

schema.ts view source

is_memo_union(schema: AnySchema): boolean

Whether schema was made by memo_union, which its kind doesn't say, as it is a union's. For a reader that runs a schema by other code than its run, as compile.ts does, and must keep what a memo_union keeps.

It is told by the schema's def, the options array, which memo_union records in a registry beside the schemas. So a flavor, a brand, a meta, and a message of a memo_union are one too, as each has that def. A union is not one, nor is a schema written by hand with a union's kind and options of its own.

The mark is of the array, so every schema that holds the one array is told alike: a union made from a memo_union's own def, or from an array a memo_union was made from, is told as one. A reader then keeps a memo for a union, which gives the same verdicts and outputs. Give each its own array, as union([...options]), to tell them apart.

The registry is one for the whole JS realm, on globalThis under Symbol.for('@fuzdev/fuz_schema/memo_union'), as the metadata registry of meta.ts is, so a memo_union made through one copy of this module is told through any other. That makes its shape a contract between versions: a WeakSet of the options arrays. A version that changes it takes a new key.

import {is_memo_union} from '@fuzdev/fuz_schema/schema.ts';

is_schema
#

schema.ts view source

is_schema(value: unknown): value is SchemaNode

Checks whether value has the shape of a schema: an object with a string kind, a def, and a run function.

The check is structural and stops there. It doesn't look at whether kind is one SchemaDefs describes or whether def is what that kind holds, so the narrowing is a claim about values this library built, not a validation of ones that came from elsewhere. Keys past the three are ignored.

The narrowed type is for reading a schema as data. A schema typed with its kind keeps its own type, while one typed as a bare Schema or AnySchema (as recursive schemas usually are) reads as SchemaNode, whose output type is unknown.

import {is_schema} from '@fuzdev/fuz_schema/schema.ts';

iso_datetime
#

schema.ts view source

SchemaRefinement<string, string, "iso_datetime", undefined>

type SchemaRefinement<string, string, "iso_datetime", undefined>

Fails a string that isn't a date and time of RFC 3339 in UTC, as 2024-02-29T23:59:59.123Z: a real date of a four-digit year, a T, the time with its seconds, a fraction of 1 to 9 digits or none, and a Z. No offset, no lowercase t or z, and no leap second. Fails any value that isn't a string. In a pipe its output is the type of the step before it.

import {iso_datetime} from '@fuzdev/fuz_schema/schema.ts';

JsonSchema
#

json_schema.ts view source

A JSON Schema document or subschema, typed by the keywords to_json_schema writes. Metadata adds any other key.

import type {JsonSchema} from '@fuzdev/fuz_schema/json_schema.ts';

members

$schema

?: string
#

$ref

?: string
#

$defs

?: Record<string, JsonSchema>
#

const

?: unknown
#

enum

?: unknown[]
#
#

anyOf

?: JsonSchema[]
#

oneOf

?: JsonSchema[]
#

allOf

?: JsonSchema[]
#

properties

?: Record<string, JsonSchema>
#

required

?: string[]
#

additionalProperties

?: JsonSchema | false
#

propertyNames

?: JsonSchema
#

items

?: JsonSchema
#

minLength

?: number
#

maxLength

?: number
#

minItems

?: number
#

maxItems

?: number
#

minimum

?: number
#

maximum

?: number
#

format

?: string
#

pattern

?: string
#

default

?: unknown
#

[key: string]

: unknown

JsonSchemaOptions
#

json_schema.ts view source

Options of to_json_schema.

import type {JsonSchemaOptions} from '@fuzdev/fuz_schema/json_schema.ts';

members

io

?: "input" | "output" = 'output'
#

Which side of a parse to describe: 'output', what it returns, or 'input', what it accepts. They differ where a default fills a key in, which is required of the output and optional in the input, where strip_object drops unknown keys, where a transform runs, which has no output to write and whose input is the steps before it, where a to_lower_case runs, whose steps before it are of the input and those after it of the output, and where a to_integer reads a string, an integer of the output and a pattern of the input.

unrepresentable

?: "throw" | "any" = 'throw'
#

What to do with what JSON Schema can't say: 'throw', or 'any', which writes {} for it, or leaves out the keyword for a step of a pipe.

JsonSchemaType
#

json_schema.ts view source

type "string" | "number" | "integer" | "boolean" | "null" | "object" | "array"

The values of the keyword type.

import type {JsonSchemaType} from '@fuzdev/fuz_schema/json_schema.ts';

keyed_record
#

schema.ts view source

keyed_record<K extends Schema<string, string>, V extends Schema>(key: K, value: V): KeyedRecordSchema<K, V>

Matches an object whose every own enumerable string key matches key and whose every value matches value, as record matches the values: keyed_record(pipe(string, regex(/^[a-z]+$/)), number) matches {a: 1} and refuses {A: 1}, at the key A.

  • No key is needed: a one_of or a literal key types the output's keys as optional, and an object without them matches.
  • What key gives is the output's key, so pipe(string, to_lower_case) writes {A: 1} as {a: 1}. Two keys that give one, as a and A there, are the last one's value in the first one's place, and a key that gives __proto__ is left out, as assigning it would set the prototype.
  • A key that fails is an issue of kind invalid_key, with the expected and received of key, 'string' unless a step of key changed the type, and the key last in its path unless key added to it with a check_at, in the input's order among the values' issues. value is not run on its value. get_issue_value gives the last key of the path for it. A message on key labels it, and its function is handed the key and the issue key reported.
  • Keys are read as record reads them: own enumerable string keys, an own __proto__ key run through key and its value through value, and left out where key gives it as __proto__, an array refused, and a class instance taken.
  • The output is the input itself when every key gives itself and no value changed.
import {keyed_record} from '@fuzdev/fuz_schema/schema.ts';

parameters

key

: K
#

the schema of every key, run on the key as a string

value

: V
#

the schema of every value

KeyedRecordSchema
#

lazy
#

schema.ts view source

lazy<T extends Schema>(get: () => T): LazySchema<T>

Defers to the schema returned by get, for recursive schemas. get is called once, on first use, and again when it threw.

It calls the schema with the arguments it is called with, so as an object entry it hands the schema the object and the key, and a key the schema needs is still needed: lazy(() => unknown) fails a missing key and lazy(() => optional(string)) accepts one.

import {lazy} from '@fuzdev/fuz_schema/schema.ts';

LazySchema
#

schema.ts view source

LazySchema<T>

The type of lazy(get), where get returns a T.

import type {LazySchema} from '@fuzdev/fuz_schema/schema.ts';

generics

LazySchema<T extends Schema>

T

constraint Schema

inheritance

extends: Schema<Infer<T>, InferInput<T>, "lazy", () => T>

literal
#

schema.ts view source

literal<const T extends SchemaLiteral>(value: T): LiteralSchema<T>

Matches a single value by ===, so 0 and -0 match each other, and matches NaN when the value is NaN, which === alone never would.

literal(undefined) as an object entry needs its key, as unknown does and wherever unknown is handed the object and the key: undefined at a key the object has, own or inherited, is accepted, and a key that is missing fails as a missing_key. Write optional(literal(undefined)) to let the key be missing.

import {literal} from '@fuzdev/fuz_schema/schema.ts';

LiteralSchema
#

schema.ts view source

LiteralSchema<T>

The type of literal(value), where T is the type of value.

import type {LiteralSchema} from '@fuzdev/fuz_schema/schema.ts';

generics

LiteralSchema<T extends SchemaLiteral>

T

constraint SchemaLiteral

inheritance

extends: Schema<T, T, "literal", T>

loose_object
#

schema.ts view source

loose_object<T extends SchemaEntries>(entries: T): LooseObjectSchema<T>

Matches an object with entries, keeping unknown keys as they are. The cheapest of the object schemas on input that comes back as it is: unknown keys are never looked at, and the output is the input itself when no entry changed.

When an entry changed the output is a copy: the schema's keys as object copies them, then the input's other own enumerable string keys in the input's order. Of the keys the schema doesn't name, a symbol key, an inherited key, a non-enumerable key, and a __proto__ key are left out of it.

import {loose_object} from '@fuzdev/fuz_schema/schema.ts';

LooseObjectSchema
#

schema.ts view source

LooseObjectSchema<T>

The type of loose_object(entries), where T is the type of entries, extended to name an exported schema as ObjectSchema is.

import type {LooseObjectSchema} from '@fuzdev/fuz_schema/schema.ts';

generics

LooseObjectSchema<T extends SchemaEntries>

T

constraint SchemaEntries

inheritance

extends: Schema<SchemaObjectOutput<T> & Record<string, unknown>, SchemaObjectInput<T> & Record<string, unknown>, "loose_object", T>

max_length
#

schema.ts view source

max_length<T extends { length: number }>(max: number): SchemaRefinement<Uninferred<T>, T, "max_length", number>

Fails a value whose length is more than max, as min_length reads it. In a pipe its output is the type of the step before it.

import {max_length} from '@fuzdev/fuz_schema/schema.ts';

parameters

max

: number
#

the greatest length that passes

max_value
#

schema.ts view source

max_value<T extends number | bigint>(max: T extends bigint ? bigint : number): SchemaRefinement<Uninferred<T>, T, "max_value", number | bigint>

Fails a number or a bigint that is not <= max, so NaN fails. In a pipe its output is the type of the step before it.

import {max_value} from '@fuzdev/fuz_schema/schema.ts';

parameters

max

: T extends bigint ? bigint : number
#

the greatest value that passes, a bigint for a bigint and a number for a number

memo_union
#

schema.ts view source

memo_union<const T extends readonly Schema[]>(options: T): UnionSchema<T>

A union that keeps, for one parse, what it gave for each object or array it is probed with, and gives that back when it is probed with the same one again. A recursive union whose options walk a node's children before an entry rules them out takes time exponential in the input's depth, as each option walks them again at every level; this one reads back what it gave a node, so its options walk a node's children once where every recursive schema they read is a memo_union too. Its kind and def are union's, and so are its verdicts and its issues: a reader of a schema's data, to_schema_json included, takes it as a union, and one that must tell it apart asks is_memo_union.

Use it where two options could take the same object or array and reach a lazy without a literal entry telling them apart first, as in lazy(() => memo_union([object({args: array(Node), op: literal('a')}), ...])). variant is the cheaper way out when the options have a literal discriminator, and so is putting first in each option the literal entries that tell the options apart. The memo is in the union that tries the options again, so on a chain of such unions each link is a memo_union, and where an option reads into another recursive union, as M in L = lazy(() => memo_union([object({x: array(L), t: literal('a')}), loose_object({x: array(M)})])), that union is one too. The memo is by the object: a step before it that returns a new object, as a transform that copies does, leaves it nothing to find, so such a step goes inside an option.

It keeps only what it gives while probing, which is how a union runs its options and how is runs: a union that is itself not probed runs as union does, and what its options hold is probed. What it keeps assumes the answer on an object depends on the object alone, which a getter, a Proxy, or a check with state can break. Where one does, is and parse can differ, as only probing reads the memo: is probes everything, and parse probes only what a union holds. Where a value comes back from the memo:

  • a transform, a check, or a with_default_fn's make beneath the union is not run again for an object the union is probed with again, by another option or where the input holds it twice, where under union it runs each time
  • an input that holds the same object twice gets the same output object in both places
  • a cyclic input still recurses until the stack runs out, as with union

The memo is a WeakMap for each parse, from each object or array probed to what came back, held in a WeakMap by the parse's context and dropped with it, so nothing of one parse reaches another. A context is one parse: a SchemaContext run again keeps its memo, which answers for an object it kept, changed since or not. Each probe of an object or an array looks it up, which costs a union that walks nothing again, and a parse that probes one allocates the map.

import {memo_union} from '@fuzdev/fuz_schema/schema.ts';

message
#

schema.ts view source

message<T extends Schema>(schema: SchemaRefinement<TOutput, TInput, TKind, TDef>, message: string | ((issue: SchemaIssue, value: unknown) => string)): SchemaRefinement<TOutput, TInput, TKind, TDef>

Sets custom text on every issue schema reports that has no message yet, at any path: its own, and its children's. Works on actions too, and the innermost message wins. Nothing is labeled when only whether a value matches is asked. The result is otherwise indistinguishable from schema: as an object entry it hands schema the object and the key when schema takes them, so a key schema needs is still needed under a message.

A function is called with a copy of the issue and with the value schema was given to validate. Around an action that is the action's input, so the output of the pipe's steps before it. Around a whole pipe it is the pipe's input, whichever step failed. For a child's issue it is still the value schema was given, and the issue's path is relative to it, so get_issue_value(issue, value) finds the child's. The issue doesn't hold the value, so text built from it puts input into an issue that otherwise has none.

Metadata meta attached to schema is carried over to the result, the same object, so readers find it there as on schema, which is left as it was.

import {message} from '@fuzdev/fuz_schema/schema.ts';

parameters

message

: string | ((issue: SchemaIssue, value: unknown) => string)
#

the text, or a function that builds it from the issue and the value

overloads

message<TInput, TOutput, TKind extends string, TDef>(schema: SchemaRefinement<TOutput, TInput, TKind, TDef>, message: string | ((issue: SchemaIssue, value: unknown) => string)): SchemaRefinement<TOutput, TInput, TKind, TDef>
message<TInput, TOutput, TKind extends string, TDef>(schema: SchemaAction<TOutput, TInput, TKind, TDef>, message: string | ((issue: SchemaIssue, value: unknown) => string)): SchemaAction<TOutput, TInput, TKind, TDef>
message<T extends Schema>(schema: T, message: string | ((issue: SchemaIssue, value: unknown) => string)): T

meta
#

meta.ts view source

meta<T extends AnySchema>(schema: SchemaRefinement<TOutput, TInput, TKind, TDef>, meta: SchemaMeta): SchemaRefinement<TOutput, TInput, TKind, TDef>

Attaches metadata to a copy of schema, leaving schema as it was: one with no options is a constant every use shares. The copy has the same kind, def, and run, so it is otherwise indistinguishable from schema and can go anywhere schema can.

Metadata schema already has is merged key by key, the new keys winning. A key given as undefined wins too, which is how one is cleared.

import {meta} from '@fuzdev/fuz_schema/meta.ts';

parameters

schema

: SchemaRefinement<TOutput, TInput, TKind, TDef>
#

the schema to copy

#

copied one level deep, so changing its keys afterwards changes nothing

overloads

meta<TInput, TOutput, TKind extends string, TDef>(schema: SchemaRefinement<TOutput, TInput, TKind, TDef>, meta: SchemaMeta): SchemaRefinement<TOutput, TInput, TKind, TDef>
meta<TInput, TOutput, TKind extends string, TDef>(schema: SchemaAction<TOutput, TInput, TKind, TDef>, meta: SchemaMeta): SchemaAction<TOutput, TInput, TKind, TDef>
meta<T extends AnySchema>(schema: T, meta: SchemaMeta): T

min_length
#

schema.ts view source

min_length<T extends { length: number }>(min: number): SchemaRefinement<Uninferred<T>, T, "min_length", number>

Fails a value whose length is less than min: of a string its UTF-16 code units, and of an array its items. In a pipe its output is the type of the step before it.

import {min_length} from '@fuzdev/fuz_schema/schema.ts';

parameters

min

: number
#

the least length that passes

min_value
#

schema.ts view source

min_value<T extends number | bigint>(min: T extends bigint ? bigint : number): SchemaRefinement<Uninferred<T>, T, "min_value", number | bigint>

Fails a number or a bigint that is not >= min, so NaN fails. In a pipe its output is the type of the step before it.

import {min_value} from '@fuzdev/fuz_schema/schema.ts';

parameters

min

: T extends bigint ? bigint : number
#

the least value that passes, a bigint for a bigint and a number for a number

nullable
#

schema.ts view source

nullable<T extends Schema>(schema: T): NullableSchema<T>

Accepts null. As an object entry it hands schema the object and the key when schema takes them, so a key schema needs is still needed: nullable(unknown) fails a missing key and nullable(optional(string)) accepts one.

import {nullable} from '@fuzdev/fuz_schema/schema.ts';

NullableSchema
#

schema.ts view source

NullableSchema<T>

The type of nullable(schema), where T is the type of schema.

import type {NullableSchema} from '@fuzdev/fuz_schema/schema.ts';

generics

NullableSchema<T extends Schema>

T

constraint Schema

inheritance

extends: Schema<Infer<T> | null, InferInput<T> | null, "nullable", SchemaWrapperDef<T>>

number
#

schema.ts view source

NumberSchema

Matches a finite number: rejects NaN and the infinities, with the issue any value that isn't a number gets.

A JSON text can carry an infinity as a number too large for a double, which JSON.parse reads 1e999 as, and JSON.stringify writes one back as null. An integer of any size is a finite number, see integer.

Only number is about which numbers: a literal or a one_of of an infinity still matches it, and a bound of min_value or max_value may be one.

import {number} from '@fuzdev/fuz_schema/schema.ts';

NumberSchema
#

schema.ts view source

The type of number.

import type {NumberSchema} from '@fuzdev/fuz_schema/schema.ts';

inheritance

extends: Schema<number, number, "number", undefined>

object
#

schema.ts view source

object<T extends SchemaEntries>(entries: T): ObjectSchema<T>

Matches an object with entries, failing on unknown keys. The output is the input itself when no entry changed.

A key the input lacks reads as undefined, so it fails unless its entry accepts that. unknown, literal(undefined), and a one_of with undefined among its values accept undefined and still need their key, failing as a missing_key without it. This holds for the entries of the other object schemas too.

import {object} from '@fuzdev/fuz_schema/schema.ts';

object_with_rest
#

schema.ts view source

object_with_rest<T extends SchemaEntries, R extends Schema>(entries: T, rest: R): ObjectWithRestSchema<T, R>

Matches an object with entries, and every other own enumerable string key of it with rest: object_with_rest({_: array(string)}, number) matches {_: [], a: 1} and refuses {_: [], a: 'x'}, at the key a.

  • The entries run first, then rest on each other key in the input's order, and the issues are reported in that order: an entry that fails doesn't stop the keys after it from being validated.
  • A key the input inherits is neither validated nor copied, as Valibot has it, and is still read through an input that comes back. An own key named constructor or prototype is validated as any other, as Zod has it. An array is refused.
  • An own __proto__ key is left out of the output and not validated, as both do: assigning it would set the prototype.
  • The output is the input itself when nothing changed and there is no __proto__ key. A copy has the schema's keys first, as object copies them, then the other own keys in the input's order.

variant can't take it as an option: its types refuse one, as its def is not the entries. One forced through by a cast has its discriminator looked up in that def, so variant throws when it is made, or is made and takes the discriminator's values from that def, not from the entries.

import {object_with_rest} from '@fuzdev/fuz_schema/schema.ts';

parameters

rest

: R
#

the schema of the value of every own key that isn't an entry

ObjectSchema
#

schema.ts view source

ObjectSchema<T>

The type of object(entries), where T is the type of entries.

A library that exports an object schema names its type by extending this with its entries, interface UserSchema extends ObjectSchema<typeof UserEntries> {}, so the declaration of a schema that holds it refers to it by that name.

import type {ObjectSchema} from '@fuzdev/fuz_schema/schema.ts';

generics

ObjectSchema<T extends SchemaEntries>

T

constraint SchemaEntries

inheritance

ObjectWithRestSchema
#

schema.ts view source

ObjectWithRestSchema<T, R>

The type of object_with_rest(entries, rest), where T is the type of entries and R of rest, extended to name an exported schema as ObjectSchema is.

import type {ObjectWithRestSchema} from '@fuzdev/fuz_schema/schema.ts';

generics

ObjectWithRestSchema<T extends SchemaEntries, R extends Schema>

T

constraint SchemaEntries

R

constraint Schema

inheritance

extends: Schema<SchemaObjectOutput<T> & Record<string, ReturnType<R["run"]>>, SchemaObjectInput<T> & Record<string, InferInput<R>>, "object_with_rest", SchemaObjectWithRestDef<T, R>>

one_of
#

schema.ts view source

one_of<const T extends readonly SchemaLiteral[]>(values: T): OneOfSchema<T>

Matches any of values as literal matches one: by ===, so 0 and -0 match each other, and NaN when it is among them.

With undefined among values it needs its key as an object entry, as literal(undefined) does. What it matches is read from values once, when the schema is made: changing the array afterwards changes def and not what the schema matches, though an issue's expected is written from the array as it is at the first failure.

import {one_of} from '@fuzdev/fuz_schema/schema.ts';

OneOfSchema
#

schema.ts view source

OneOfSchema<T>

The type of one_of(values), where T is the type of values.

import type {OneOfSchema} from '@fuzdev/fuz_schema/schema.ts';

generics

OneOfSchema<T extends ReadonlyArray<SchemaLiteral>>

T

constraint readonly SchemaLiteral[]

inheritance

extends: Schema<T[number], T[number], "one_of", T>

optional
#

schema.ts view source

optional<T extends Schema>(schema: T): OptionalSchema<T>

Accepts undefined. As an object entry it makes the key optional: the input may leave it out, and a key left out stays out of the output.

import {optional} from '@fuzdev/fuz_schema/schema.ts';

OptionalSchema
#

schema.ts view source

OptionalSchema<T>

The type of optional(schema), where T is the type of schema.

import type {OptionalSchema} from '@fuzdev/fuz_schema/schema.ts';

generics

OptionalSchema<T extends Schema>

T

constraint Schema

inheritance

extends: Schema<Infer<T> | undefined, InferInput<T> | undefined, "optional", SchemaWrapperDef<T>>

parse
#

schema.ts view source

parse<T extends Schema>(schema: T, value: unknown): SchemaResult<Infer<T>>

Validates value, returning the output or the issues found, the first hundred.

import {parse} from '@fuzdev/fuz_schema/schema.ts';

parse_or_throw
#

schema.ts view source

parse_or_throw<T extends Schema>(schema: T, value: unknown): Infer<T>

Validates value and returns the output.

import {parse_or_throw} from '@fuzdev/fuz_schema/schema.ts';

throws

pipe
#

schema.ts view source

pipe(schema: T, a1: PipeStep<Infer<T>, O1, R1>): PipeSchema<Uninferred<PipeStepOutput<ReturnType<T["run"]>, O1, R1>>, T>

Runs schema then each action on its output, stopping at the first failure. It takes one to four actions, which its types can follow. A pipe of more starts with a pipe of four, pipe(pipe(schema, a, b, c, d), e), which runs as one pipe.

As an object entry it hands schema the object and the key when schema takes them, so pipe(unknown, ...) fails a missing key and runs no action. The actions are handed neither.

As an object entry whose key is missing, a pipe that starts with an optional runs no action, and the key stays out of the output: object({a: pipe(optional(string), check(...))}) accepts {} whatever the check says, and a transform there writes no key. with_default and with_default_fn are what fill a missing key in. With the key there every action runs, on undefined too.

That is of an optional itself, and of a pipe that starts with such a pipe, as the entry itself or under a message. Under a nullable, a lazy, or a union its actions run on the undefined a missing key reads as, and so do a pipe's after a nullable, a lazy, or a union that reaches an optional.

import {pipe} from '@fuzdev/fuz_schema/schema.ts';

overloads

pipe<T extends Schema, O1, R1>(schema: T, a1: PipeStep<Infer<T>, O1, R1>): PipeSchema<Uninferred<PipeStepOutput<ReturnType<T["run"]>, O1, R1>>, T>
pipe<T extends Schema, O1, R1, O2, R2>(schema: T, a1: PipeStep<Infer<T>, O1, R1>, a2: PipeStep<O1, O2, R2>): PipeSchema<Uninferred<PipeStepOutput<PipeStepOutput<ReturnType<T["run"]>, O1, R1>, O2, R2>>, T>
pipe<T extends Schema, O1, R1, O2, R2, O3, R3>(schema: T, a1: PipeStep<Infer<T>, O1, R1>, a2: PipeStep<O1, O2, R2>, a3: PipeStep<O2, O3, R3>): PipeSchema<Uninferred<PipeStepOutput<PipeStepOutput<PipeStepOutput<ReturnType<T["run"]>, O1, R1>, O2, R2>, O3, R3>>, T>
pipe<T extends Schema, O1, R1, O2, R2, O3, R3, O4, R4>(schema: T, a1: PipeStep<Infer<T>, O1, R1>, a2: PipeStep<O1, O2, R2>, a3: PipeStep<O2, O3, R3>, a4: PipeStep<O3, O4, R4>): PipeSchema<Uninferred<PipeStepOutput<PipeStepOutput<PipeStepOutput<PipeStepOutput<ReturnType<T["run"]>, O1, R1>, O2, R2>, O3, R3>, O4, R4>>, T>

PipeSchema
#

schema.ts view source

PipeSchema<TOutput, T>

type Schema<TOutput, InferInput<T>, "pipe", SchemaPipeDef> & { readonly '~types'?: { readonly input: InferInput<T>; readonly first: PipeHead<T>; }; }

A pipe that starts with T. Its type-only ~types holds as first what a value reaches first, T or, where T is a pipe, the first of that, as the runtime reads it, which an object schema reads to tell whether a missing key can match it. So a pipe that starts with a pipe of a string is a PipeSchema of a string too.

import type {PipeSchema} from '@fuzdev/fuz_schema/schema.ts';

generics

PipeSchema<TOutput, T extends Schema>

TOutput

T

constraint Schema

members

readonly

kind

: "pipe"
#
readonly

def

: SchemaPipeDef
#
readonly

run

: (value: any, ctx: SchemaContext, parent?: Record<PropertyKey, unknown>, key?: PropertyKey, entry?: 1) => TOutput
#

A schema that reads parent and key declares them as plain parameters, with no default and not as a rest: nullable, union, pipe, and message pass them on only to a run whose length says it takes them or to a schema of kind 'lazy', read once when each is made. A lazy passes on the object and the key it is called with.

value
: any
#

the value to validate

the state of the parse, where a failure is reported with fail

parent
?: Record<PropertyKey, unknown>
#

the object value was read from, when an object schema is running an entry

key
?: PropertyKey
#

the entry's key in parent, given with it

entry
?: 1
#

1 when this schema is the entry itself, as an object schema hands it and a message around it passes on, and absent where another schema passes the object and the key on

readonly

'~types'

?: { readonly input: InferInput<T>; } & { readonly input: InferInput<T>; readonly first: PipeHead<T>; }
#

Type-only, never set at runtime.

readonly

'~refines'

?: boolean
#

Type-only, never set at runtime. true on a SchemaRefinement, and a boolean here, so a schema typed as one that isn't, a transform included, is not assignable to one, and a pipe step that may be either is typed by its own output.

record
#

schema.ts view source

record<T extends Schema>(schema: T): RecordSchema<T>

Matches an object with string keys whose values all match schema. The output is the input itself when no value changed.

import {record} from '@fuzdev/fuz_schema/schema.ts';

RecordSchema
#

schema.ts view source

RecordSchema<T>

The type of record(schema), where T is the type of schema.

import type {RecordSchema} from '@fuzdev/fuz_schema/schema.ts';

generics

RecordSchema<T extends Schema>

T

constraint Schema

inheritance

extends: Schema<Record<string, Infer<T>>, Record<string, InferInput<T>>, "record", T>

regex
#

schema.ts view source

regex<T extends string>(pattern: RegExp, expected?: string): SchemaRefinement<Uninferred<T>, T, "regex", RegExp>

Fails a string that pattern doesn't match. In a pipe it is typed as the step before it, so a literal or a brand is kept.

to_schema_json refuses it, as it holds a RegExp. For a UUID or a date and time in UTC, use uuid or iso_datetime, which it writes.

import {regex} from '@fuzdev/fuz_schema/schema.ts';

parameters

pattern

: RegExp
#

without the g or y flag, under which a test starts where the last one ended

expected

?: string = String(pattern)
#

describes what was expected, defaulting to the pattern as String writes it

throws

  • TypeError - when pattern has the g or y flag

safe_integer
#

schema.ts view source

SchemaRefinement<number, number, "safe_integer", undefined>

type SchemaRefinement<number, number, "safe_integer", undefined>

Fails a number that isn't a safe integer: an integer from Number.MIN_SAFE_INTEGER to Number.MAX_SAFE_INTEGER, the range in which every integer is a double of its own. In a pipe its output is the type of the step before it, as integer's is.

import {safe_integer} from '@fuzdev/fuz_schema/schema.ts';

Schema
#

schema.ts view source

Schema<TOutput, TInput, TKind, TDef>

A schema or action. run returns the output for value, or reports a failure with fail and returns anything.

All schemas share this exact shape, with kind-specific data in def, so the engine gives every schema one hidden class, which src/test/schema.shape.test.ts asks it for, and a run is read from one shape wherever it is called.

The object schemas call an entry's run with three more arguments, the object being read, the entry's key, and 1, so a schema that accepts undefined can tell a key that is missing from one that is there. nullable, union, memo_union, and message pass the object and the key on to what they hold, and a pipe to its first schema, only to a run that declares more than two parameters or to a lazy, so a run that reads them declares them as plain parameters. A lazy passes on what it was called with. A pipe that starts with an optional reads the key itself and passes them to none. flavor, brand, and meta return a schema with the same run. Only message passes the third, which says that what it holds is the entry itself. Every other call gives the first two only, and a run that takes only those works as an entry.

The input type defaults to the output's, so a parameter typed Schema<string> refuses a schema that changes its value, a transform or a default, and one generic in T, typed Schema<T>, refuses a transform and infers T from the output and the input of a default together. A function generic over the output of whatever schema it is given takes a Schema<T, unknown>.

import type {Schema} from '@fuzdev/fuz_schema/schema.ts';

generics

Schema<TOutput = unknown, TInput = TOutput, TKind extends string = string, TDef = unknown>

TOutput

default unknown

TInput

default TOutput

TKind

constraint string
default string

TDef

default unknown

members

readonly

kind

: TKind
#
readonly

def

: TDef
#
readonly

run

: (value: any, ctx: SchemaContext, parent?: Record<PropertyKey, unknown>, key?: PropertyKey, entry?: 1) => TOutput
#

A schema that reads parent and key declares them as plain parameters, with no default and not as a rest: nullable, union, pipe, and message pass them on only to a run whose length says it takes them or to a schema of kind 'lazy', read once when each is made. A lazy passes on the object and the key it is called with.

value
: any
#

the value to validate

the state of the parse, where a failure is reported with fail

parent
?: Record<PropertyKey, unknown>
#

the object value was read from, when an object schema is running an entry

key
?: PropertyKey
#

the entry's key in parent, given with it

entry
?: 1
#

1 when this schema is the entry itself, as an object schema hands it and a message around it passes on, and absent where another schema passes the object and the key on

readonly

'~types'

?: { readonly input: TInput; }
#

Type-only, never set at runtime.

readonly

'~refines'

?: boolean
#

Type-only, never set at runtime. true on a SchemaRefinement, and a boolean here, so a schema typed as one that isn't, a transform included, is not assignable to one, and a pipe step that may be either is typed by its own output.

SCHEMA_JSON_MAX_DEPTH
#

schema_json.ts view source

127

The deepest that arrays and objects can be nested in a text the crate reads, a document in the interchange form included. The crate's MAX_DEPTH.

import {SCHEMA_JSON_MAX_DEPTH} from '@fuzdev/fuz_schema/schema_json.ts';

SCHEMA_JSON_MAX_NESTING
#

schema_json.ts view source

16

The most wrappers, lazy, union options, and starts of a pipe around one value. The crate's MAX_NESTING.

import {SCHEMA_JSON_MAX_NESTING} from '@fuzdev/fuz_schema/schema_json.ts';

SCHEMA_JSON_REFUSED_KEYS
#

schema_json.ts view source

readonly string[]

The names of the members of Object.prototype. The library reads an object's entries through the prototype, so an entry with one of these names sees the member when the input lacks the key, and is refused. So is a variant whose key is one.

import {SCHEMA_JSON_REFUSED_KEYS} from '@fuzdev/fuz_schema/schema_json.ts';

SCHEMA_JSON_UNSUPPORTED_KINDS
#

schema_json.ts view source

readonly string[]

The kinds that hold a JavaScript value, which the form has no way to write, and which the crate refuses by name. with_default_fn holds one too and is refused the same way here, and the crate refuses it as a kind it doesn't know. The crate refuses object_with_rest, keyed_record, and to_integer as kinds it doesn't know too, as ones it doesn't carry yet, and to_schema_json refuses them as not portable.

import {SCHEMA_JSON_UNSUPPORTED_KINDS} from '@fuzdev/fuz_schema/schema_json.ts';

SchemaAction
#

schema.ts view source

SchemaAction<TOutput, TInput, TKind, TDef>

A schema that refines or transforms an already-typed value, for use in pipe.

Every action the library makes is typed as one. Its ~types holds an action marker, so a pipe checks the step by its ~accepts alone, as a parameter is checked: a pipe refuses an action whose input is narrower than the output of the step before it, so pipe(nullable(number), min_value(0)) is a type error, as null would reach min_value, and takes one whose input is wider, as check((v: unknown) => ...) after string. A step that isn't an action is checked by its input alone, which must be assignable to the output of the step before it, and that includes a lazy or a union that holds an action, or a pipe that starts with one: those keep the action's input and not its ~accepts, so pipe(nullable(string), union([regex(/n/)])) compiles and matches null, which regex reads as 'null'.

import type {SchemaAction} from '@fuzdev/fuz_schema/schema.ts';

generics

SchemaAction<TOutput, TInput = TOutput, TKind extends string = string, TDef = unknown>

TOutput

TInput

default TOutput

TKind

constraint string
default string

TDef

default unknown

inheritance

extends: Schema<TOutput, TInput, TKind, TDef>

members

readonly

'~accepts'

?: (input: TInput) => void
#

Type-only, never set at runtime: what the action takes, read as a parameter.

readonly

'~types'

?: { readonly input: TInput; readonly action: true; }
#

Type-only, never set at runtime: action has a pipe check the step by ~accepts alone.

SchemaContext
#

schema.ts view source

Mutable state threaded through a single parse.

import type {SchemaContext} from '@fuzdev/fuz_schema/schema.ts';

members

issues

: SchemaIssue[] | undefined
#

One per failure up to a hundred, past which a failure is counted in fails and builds none, and in probe mode it stays as it was. undefined until the first, so a parse with no failure allocates none. While the parse runs each path is innermost first: a container pushes its key, and parse and parse_or_throw reverse each path as they return it.

fails

: number
#

How many failures have been reported. A container knows a child failed when this grew. Outside probe mode it equals issues.length up to a hundred, past which a failure is counted and builds no issue, and is 0 while there is no issues. A count taken past the hundredth indexes no issue, so a run that reads issues from a count finds the ones built.

probe

: boolean
#

When true only whether the value matches is wanted: failures are counted without building issues, and containers return at their first failed child. Set by union while trying options and by is.

SchemaDef
#

schema.ts view source

SchemaDef<TKind>

type SchemaDefs[TKind]

The type of def for the kind TKind.

import type {SchemaDef} from '@fuzdev/fuz_schema/schema.ts';

generics

SchemaDef<TKind extends SchemaKind = SchemaKind>

TKind

constraint SchemaKind
default SchemaKind

SchemaDefaultDef
#

schema.ts view source

SchemaDefaultDef<T>

The def of with_default. An interface, as SchemaWrapperDef is, so it is not mistaken for the entries of an object schema when value is a schema or of type any.

import type {SchemaDefaultDef} from '@fuzdev/fuz_schema/schema.ts';

generics

SchemaDefaultDef<T extends Schema>

T

constraint Schema

inheritance

extends: SchemaWrapperDef<T>

members

readonly

value

: Infer<T>
#

SchemaDefaultFnDef
#

SchemaDefaultOutput
#

schema.ts view source

SchemaDefaultOutput<T>

type T extends { readonly kind: "optional"; readonly def: SchemaWrapperDef<infer U extends Schema<unknown, unknown, string, unknown>>; } ? Exclude<ReturnType<T["run"]>, undefined> | Extract<ReturnType<U["run"]>, undefined> : T extends { readonly kind: "nullable"; readonly def: SchemaWrapperDef<{ readonly kind: "optional"; readonly def: SchemaWrapperDef<infer U extends Schema<unknown, unknown, string, unknown>>; } & Schema<unknown, unknown, string, unknown>>; } ? Exclude<ReturnType<T["run"]>, undefined> | Extract<ReturnType<U["run"]>, undefined> : ReturnType<T["run"]>

The output of a default over T, which never hands T an undefined: of an optional, and of a nullable of an optional, its output without the optional's undefined, which keeps a brand or a flavor of it and any undefined what the optional holds can give. Of any other schema its output, as it can give undefined for a value that isn't.

import type {SchemaDefaultOutput} from '@fuzdev/fuz_schema/schema.ts';

generics

SchemaDefaultOutput<T extends Schema>

T

constraint Schema

SchemaDefs
#

schema.ts view source

What the def of each kind of schema holds: the contract for reading a schema as data. kind names an entry here, and def is that entry's type.

A def is as close to plain JSON as its kind allows. A kind that takes no options has undefined, one that takes a single value has that value, and optional, nullable, with_default, and with_default_fn have an object with their schema under schema. The object schemas have their entries, and object_with_rest has an object with them under entries.

message, flavor, brand, and meta have no kind of their own: what they return has the kind and def of the schema they were given. Nor do memo_union, which is a union that is_memo_union tells, void, a literal of undefined, and check_at, a check.

A schema of a kind defined outside this module is typed by adding its entry through declaration merging, which adds it to SchemaNode too.

import type {SchemaDefs} from '@fuzdev/fuz_schema/schema.ts';

members

string

: undefined
#

number

: undefined
#

boolean

: undefined
#

bigint

: undefined
#

unknown

: undefined
#

literal

: SchemaLiteral
#

The value matched.

one_of

: readonly SchemaLiteral[]
#

The values matched, in the order given.

optional

: { readonly schema: SchemaNode; }
#

nullable

: { readonly schema: SchemaNode; }
#

with_default

: { readonly schema: SchemaNode; readonly value: unknown; }
#

value replaces undefined, and is returned as it is.

with_default_fn

: { readonly schema: SchemaNode; readonly make: () => unknown; }
#

make is called for each undefined, and what it returns replaces it.

lazy

: () => SchemaNode
#

The function given, which returns the schema deferred to. It is not a wrapper's schema because nothing is held until it is called, and following it is how a walk of a recursive schema comes back to where it was.

object

: Readonly<Record<string, SchemaNode>>
#

The entries, in the order they run.

loose_object

: Readonly<Record<string, SchemaNode>>
#

strip_object

: Readonly<Record<string, SchemaNode>>
#

object_with_rest

: { readonly entries: Readonly<Record<string, SchemaNode>>; readonly rest: SchemaNode; }
#

The entries, in the order they run, and rest, the schema of every other own key.

record

: SchemaNode
#

The schema of every value.

keyed_record

: { readonly key: SchemaNode; readonly value: SchemaNode; }
#

key, the schema of every key, and value, of every value.

array

: SchemaNode
#

The schema of every item.

union

: readonly SchemaNode[]
#

The options, in the order they are tried.

variant

: { readonly key: string; readonly options: ReadonlyArray<SchemaNode<"object" | "loose_object" | "strip_object">>; }
#

key is the discriminator, a literal entry of every one of options.

pipe

: readonly SchemaNode[]
#

The schema, then the actions run on its output.

min_length

: number
#

max_length

: number
#

min_value

: number | bigint
#

max_value

: number | bigint
#

integer

: undefined
#

safe_integer

: undefined
#

regex

: RegExp
#

uuid

: undefined
#

iso_datetime

: undefined
#

to_lower_case

: undefined
#

to_integer

: SchemaToIntegerDef
#

The grammar read: whether a - is refused, and whether white space around the digits is taken.

check

: (value: any) => boolean
#

transform

: (value: any) => unknown
#

SchemaEntries
#

schema.ts view source

The entries of an object schema: a schema for each key.

A type written out for entries is a type alias and not an interface: an interface has no implicit index signature, so it is not assignable to this.

import type {SchemaEntries} from '@fuzdev/fuz_schema/schema.ts';

members

[key: string]

: Schema<unknown, unknown>

SchemaEntryLeavesMissingOut
#

schema.ts view source

SchemaEntryLeavesMissingOut<T, TEntry>

type 0 extends 1 & T ? true : T extends EntryMayLeaveMissingOut ? T extends { readonly kind: "optional"; } ? true : T extends { readonly kind: "nullable"; readonly def: SchemaWrapperDef<infer U extends Schema<unknown, unknown, string, unknown>>; } ? SchemaEntryLeavesMissingOut<U, false> : T extends { readonly kind: "lazy"; readonly def: () => infer U; } ? SchemaEntryLeavesMissingOut<U, false> : T extends { readonly kind: "union" | "pipe"; readonly run: (...args: any) => infer O; } ? [TEntry] extends [true] ? true extends SchemaPipeStartsOptional<T> ? true : EntryGivesUndefined<T, O> : EntryGivesUndefined<T, O> : false : false

Whether a missing key can stay out of the output of the entry T, which makes the key optional in an object schema's output type. An optional leaves it out and a default fills it in, through a nullable and a lazy. A pipe that starts with an optional runs no step where it is the entry, which TEntry says, as it is as the entry itself and under a message, a meta, a flavor, or a brand, and not under a nullable or a lazy. Any other pipe, and a union, that takes a missing key can leave it out where it can give undefined. A default of undefined leaves it out too, which the types don't say. An entry typed as a union of schemas may leave it out where one of them does, so its key is optional in the output, and so is that of a pipe whose first schema is typed as such a union. A brand or a flavor of a schema typed as one is not read through, and its key is required. Exported for the reason SchemaEntryTakesMissing is.

import type {SchemaEntryLeavesMissingOut} from '@fuzdev/fuz_schema/schema.ts';

generics

SchemaEntryLeavesMissingOut<T, TEntry extends boolean = true>

T

TEntry

constraint boolean
default true

SchemaEntryTakesMissing
#

schema.ts view source

type 0 extends 1 & T ? true : T extends EntryMayTakeMissing ? T extends { readonly kind: "optional" | "with_default" | "with_default_fn"; } ? true : T extends { readonly kind: "nullable"; readonly def: SchemaWrapperDef<infer U extends Schema<unknown, unknown, string, unknown>>; } ? SchemaEntryTakesMissing<U> : T extends { readonly kind: "lazy"; readonly def: () => infer U; } ? SchemaEntryTakesMissing<U> : T extends { readonly kind: "union"; readonly def: readonly (infer U)[]; } ? true extends SchemaEntryTakesMissing<U> ? true : false : T extends { readonly kind: "pipe"; readonly '~types'?: { readonly first: infer U; }; } ? SchemaEntryTakesMissing<U> : false : false

Whether a missing key can match the entry T, as its run reads one, which makes the key optional in an object schema's input type. An optional, a with_default, and a with_default_fn take it, a nullable, a lazy, and a pipe take it where what they start with does, and a union where an option does. message and meta keep the type of what they wrap, and flavor and brand its kind, its def, and the first schema of a pipe. An entry typed as a union of schemas takes it where every one does, and any takes it.

Exported so a declaration emitted for a generic function that builds an object schema can name it: inlined, it would be written out without end.

import type {SchemaEntryTakesMissing} from '@fuzdev/fuz_schema/schema.ts';

generics

SchemaEntryTakesMissing<T>

T

SchemaError
#

schema.ts view source

Thrown by parse_or_throw. The message lists the first ten issues, one per line, as format_issue writes it, and then how many more failures there were, so its length is bounded by ten of its lines however many issues there are. A parse builds at most a hundred issues and counts every failure, and one thrown by parse_or_throw is given that count: an input that failed five hundred times reads and 490 more, with the hundred issues on issues. Like its issues, it holds nothing of the input but the keys in their paths.

It can be made from the issues of a failed parse, and its message set after, for other text. Made so, it counts the issues it is given, as a failed result carries no count of its own.

import {SchemaError} from '@fuzdev/fuz_schema/schema.ts';

inheritance

extends: Error

members

issues

: SchemaIssue[]
#

constructor

(issues: SchemaIssue[], fails?: number)
#
issues
: SchemaIssue[]
#

the issues, the first ten of which the message lists

fails
?: number = issues.length
#

how many failures there were, at least issues.length, which it defaults to. A smaller count, or one that isn't a number, is not guarded against: the message counts what it is given

SchemaField
#

introspect.ts view source

What get_schema_fields reads of one entry of an object schema.

import type {SchemaField} from '@fuzdev/fuz_schema/introspect.ts';

members

name

: string
#

The entry's key.

schema

: SchemaNode
#

The entry as given.

has_default

: boolean
#

Whether the outermost layer that is an optional, a with_default, or a with_default_fn is one of the two defaults: an optional outside one answers undefined before the default is asked. default is then the value of a with_default, even when that is undefined.

default_computed

: boolean
#

Whether that default is a with_default_fn's, made by its make on each parse that fills it in. default is then undefined, as make is not called to read it.

default

: unknown
#

The value of that with_default, before any step of a pipe it starts, and undefined when there is none or it is a with_default_fn.

description

: string | undefined
#

The description metadata, as get_schema_meta finds it.

SchemaIssue
#

schema.ts view source

A validation failure. It holds nothing of the input but the keys in path: the value that failed is described by received and not kept. A message function is handed the value, and get_issue_value reads it back out of the input.

import type {SchemaIssue} from '@fuzdev/fuz_schema/schema.ts';

members

kind

: string
#

The kind of the schema or check that failed, or unknown_key, missing_key, or invalid_key for a failure about a key of an object: an invalid_key is a key a keyed_record's key schema refused, with that schema's expected.

expected

: string
#

Describes what was expected.

received

: string
#

The type of the value that failed: 'null', 'array', 'NaN', 'Infinity', or '-Infinity', or else its typeof.

path

: PropertyKey[]
#

Keys from the root value to the one that failed, outermost first. The keys are the input's: an unknown key or a record's key is whatever the input named it, so treat them as untrusted text.

message

: string | undefined
#

Custom text set by message, used by format_issue in place of the default.

SchemaJson
#

SchemaJsonNode
#

schema_json.ts view source

A node of the interchange form.

import type {SchemaJsonNode} from '@fuzdev/fuz_schema/schema_json.ts';

members

kind

: string
#

def

?: unknown
#

SchemaKeyedRecord
#

schema.ts view source

SchemaKeyedRecord<K, V>

type Partial<Record<K | SchemaKeyedRecordKeys<K>, unknown>> extends Record<K | SchemaKeyedRecordKeys<K>, unknown> ? Record<K | SchemaKeyedRecordKeys<K>, V> : Partial<Record<K | SchemaKeyedRecordKeys<K>, V>>

An object of the keys K and the values V: Record<K, V> where K is every string, or a branded or flavored one, and every key optional where K is a set of literals, as keyed_record needs no key. A literal key loses a brand or a flavor, as a property name can't carry one: keyed_record(brand(one_of(['a', 'b']), 'L'), number) outputs {a?: number; b?: number}, where keyed_record(Uuid, number) outputs Record<Uuid, number>. Only this library's marks are taken off: a literal intersected with any other type is no property name, and gives no key.

import type {SchemaKeyedRecord} from '@fuzdev/fuz_schema/schema.ts';

generics

SchemaKeyedRecord<K extends string, V>

K

constraint string

V

SchemaKeyedRecordDef
#

schema.ts view source

SchemaKeyedRecordDef<K, V>

The def of keyed_record. An interface, as SchemaObjectWithRestDef is, so it is not mistaken for the entries of an object schema.

import type {SchemaKeyedRecordDef} from '@fuzdev/fuz_schema/schema.ts';

generics

SchemaKeyedRecordDef<K extends Schema, V extends Schema>

K

constraint Schema

V

constraint Schema

members

readonly

key

: K
#
readonly

value

: V
#

SchemaKind
#

schema.ts view source

keyof SchemaDefs

type "string" | "number" | "bigint" | "boolean" | "object" | "integer" | "array" | "unknown" | "literal" | "one_of" | "optional" | "nullable" | "with_default" | "with_default_fn" | "lazy" | "loose_object" | "strip_object" | "object_with_rest" | "record" | "keyed_record" | "union" | "variant" | "pipe" | "min_length" | "max_length" | "min_value" | "max_value" | "safe_integer" | "regex" | "uuid" | "iso_datetime" | "to_lower_case" | "to_integer" | "check" | "transform"

The kind of every schema and action SchemaDefs describes.

import type {SchemaKind} from '@fuzdev/fuz_schema/schema.ts';

SchemaLiteral
#

schema.ts view source

type string | number | bigint | boolean | null | undefined

A value literal and one_of match: any primitive but a symbol.

import type {SchemaLiteral} from '@fuzdev/fuz_schema/schema.ts';

SchemaMeta
#

meta.ts view source

What can be attached to a schema. Every key is optional.

Add keys by declaration merging, naming the module as it is imported:

declare module '@fuzdev/fuz_schema/meta.ts' { interface SchemaMeta { aliases?: Array<string>; } }
import type {SchemaMeta} from '@fuzdev/fuz_schema/meta.ts';

members

description

?: string
#

What the value is, for help text and generated docs.

SchemaNode
#

schema.ts view source

SchemaNode<TKind>

type TKind extends unknown ? SchemaOfKind<TKind> : never

A schema read as data: a union of one member per kind, each pairing its kind with its def, so checking kind narrows def. With no argument it is every kind, and with one it is the member of that kind.

The schemas inside a def are typed as this too, so a walk needs no cast:

const count = (schema: SchemaNode): number => { switch (schema.kind) { case 'optional': case 'nullable': case 'with_default': case 'with_default_fn': return 1 + count(schema.def.schema); case 'array': case 'record': return 1 + count(schema.def); default: return 1; } };

A schema whose own type names its kind is assignable to it. One typed as AnySchema or as a bare Schema is not, and gets here through is_schema.

import type {SchemaNode} from '@fuzdev/fuz_schema/schema.ts';

generics

SchemaNode<TKind extends SchemaKind = SchemaKind>

TKind

constraint SchemaKind
default SchemaKind

SchemaObjectInput
#

schema.ts view source

SchemaObjectInput<T>

type T extends unknown ? { [K in keyof ({ -readonly [K in keyof T as [SchemaEntryTakesMissing<T[K]>] extends [true] ? never : K]: InferInput<T[K]>; } & { -readonly [K in keyof T as [SchemaEntryTakesMissing<T[K]>] extends [true] ? K : never]?: InferInput<T[K]> | undefined; })]: ({ -readonly [K in keyof T as [SchemaEntryTakesMissing<T[K]>] extends [true] ? never : K]: InferInput<T[K]>; } & { -readonly [K in keyof T as [SchemaEntryTakesMissing<T[K]>] extends [true] ? K : never]?: InferInput<T[K]> | undefined; })[K]; } : never

The input of an object schema with the entries T, each key optional where a missing key can match its entry, and none readonly. loose_object takes this and Record<string, unknown>. Distributes over a union of entries as SchemaObjectOutput does.

import type {SchemaObjectInput} from '@fuzdev/fuz_schema/schema.ts';

generics

SchemaObjectInput<T extends SchemaEntries>

T

constraint SchemaEntries

SchemaObjectOutput
#

schema.ts view source

SchemaObjectOutput<T>

type T extends unknown ? { [K in keyof ({ -readonly [K in keyof T as true extends SchemaEntryLeavesMissingOut<T[K], true> ? never : K]: ReturnType<T[K]["run"]>; } & { -readonly [K in keyof T as true extends SchemaEntryLeavesMissingOut<T[K], true> ? K : never]?: ReturnType<T[K]["run"]> | undefined; })]: ({ -readonly [K in keyof T as true extends SchemaEntryLeavesMissingOut<T[K], true> ? never : K]: ReturnType<T[K]["run"]>; } & { -readonly [K in keyof T as true extends SchemaEntryLeavesMissingOut<T[K], true> ? K : never]?: ReturnType<T[K]["run"]> | undefined; })[K]; } : never

The output of an object schema with the entries T, each key optional where its entry can leave a missing key out, and none readonly: a readonly on the entries is of the entries object, not of the value parsed. loose_object outputs this and Record<string, unknown>. Distributes over a union of entries, one output for each.

Exported with SchemaObjectInput and the three types below so a consumer can name the output and input of a schema it exports, as an interface that extends one, which keeps the declaration emitted for the schema to references.

import type {SchemaObjectOutput} from '@fuzdev/fuz_schema/schema.ts';

generics

SchemaObjectOutput<T extends SchemaEntries>

T

constraint SchemaEntries

SchemaObjectWithRestDef
#

schema.ts view source

SchemaObjectWithRestDef<T, R>

The def of object_with_rest. An interface, as SchemaWrapperDef is, so it is not mistaken for the entries of an object schema when entries is of type any.

import type {SchemaObjectWithRestDef} from '@fuzdev/fuz_schema/schema.ts';

generics

SchemaObjectWithRestDef<T extends SchemaEntries, R extends Schema>

T

constraint SchemaEntries

R

constraint Schema

members

readonly

entries

: T
#
readonly

rest

: R
#

SchemaOfKind
#

schema.ts view source

SchemaOfKind<TKind>

The member of SchemaNode of one kind. Exported so a declaration emitted for a brand or a flavor of a pipe can name it.

import type {SchemaOfKind} from '@fuzdev/fuz_schema/schema.ts';

generics

SchemaOfKind<TKind extends SchemaKind>

TKind

constraint SchemaKind

inheritance

extends: Schema<unknown, unknown, TKind, SchemaDefs[TKind]>

SchemaPipeDef
#

schema.ts view source

The def of a pipe: its schema, then its actions. An interface, so a declaration that holds one names it and doesn't write out SchemaNode, the union of every kind.

import type {SchemaPipeDef} from '@fuzdev/fuz_schema/schema.ts';

inheritance

extends: readonly SchemaNode[]

SchemaPipeFactory
#

schema.ts view source

The overloads of pipe: a schema and one to four steps, each an action or a schema. A pipe of more starts with a pipe, pipe(pipe(schema, a, b, c, d), e), which runs as one.

import type {SchemaPipeFactory} from '@fuzdev/fuz_schema/schema.ts';

members

<T extends Schema, O1, R1>(schema: T, a1: PipeStep<Infer<T>, O1, R1>): PipeSchema<Uninferred<PipeStepOutput<ReturnType<T["run"]>, O1, R1>>, T>

overloads

<T extends Schema, O1, R1>(schema: T, a1: PipeStep<Infer<T>, O1, R1>): PipeSchema<Uninferred<PipeStepOutput<ReturnType<T["run"]>, O1, R1>>, T>
<T extends Schema, O1, R1, O2, R2>(schema: T, a1: PipeStep<Infer<T>, O1, R1>, a2: PipeStep<O1, O2, R2>): PipeSchema<Uninferred<PipeStepOutput<PipeStepOutput<ReturnType<T["run"]>, O1, R1>, O2, R2>>, T>
<T extends Schema, O1, R1, O2, R2, O3, R3>(schema: T, a1: PipeStep<Infer<T>, O1, R1>, a2: PipeStep<O1, O2, R2>, a3: PipeStep<O2, O3, R3>): PipeSchema<Uninferred<PipeStepOutput<PipeStepOutput<PipeStepOutput<ReturnType<T["run"]>, O1, R1>, O2, R2>, O3, R3>>, T>
<T extends Schema, O1, R1, O2, R2, O3, R3, O4, R4>(schema: T, a1: PipeStep<Infer<T>, O1, R1>, a2: PipeStep<O1, O2, R2>, a3: PipeStep<O2, O3, R3>, a4: PipeStep<O3, O4, R4>): PipeSchema<Uninferred<PipeStepOutput<PipeStepOutput<PipeStepOutput<PipeStepOutput<ReturnType<T["run"]>, O1, R1>, O2, R2>, O3, R3>, O4, R4>>, T>

SchemaPipeStartsOptional
#

schema.ts view source

type T extends { readonly kind: "optional"; } ? true : T extends { readonly kind: "pipe"; readonly '~types'?: { readonly first: infer U; }; } ? SchemaPipeStartsOptional<U> : false

Whether T is an optional, or a pipe that starts with one, through every pipe it starts with: a pipe that runs no step for a missing key. Exported for the reason SchemaEntryTakesMissing is.

import type {SchemaPipeStartsOptional} from '@fuzdev/fuz_schema/schema.ts';

generics

SchemaPipeStartsOptional<T>

T

SchemaRefinement
#

schema.ts view source

SchemaRefinement<TOutput, TInput, TKind, TDef>

An action whose run returns the value it is given or fails, so a pipe types the step's output as the output of the step before it: pipe(one_of([1, 2]), integer) outputs 1 | 2, where integer alone is a number. Every action the library makes but transform, to_lower_case, and to_integer, which change the value, is typed as one. message and meta give one back for one. brand and flavor give a SchemaAction back, so a pipe types a step under them by its own output, branded or flavored.

import type {SchemaRefinement} from '@fuzdev/fuz_schema/schema.ts';

generics

SchemaRefinement<TOutput, TInput = TOutput, TKind extends string = string, TDef = unknown>

TOutput

TInput

default TOutput

TKind

constraint string
default string

TDef

default unknown

inheritance

extends: SchemaAction<TOutput, TInput, TKind, TDef>

members

readonly

'~refines'

?: true
#

Type-only, never set at runtime: says run returns the value it is given.

SchemaResult
#

schema.ts view source

type { ok: true; value: T; } | { ok: false; issues: SchemaIssue[]; }

What parse returns: the output of a value that matches, or the issues of one that doesn't, the first hundred, told apart by ok.

import type {SchemaResult} from '@fuzdev/fuz_schema/schema.ts';

generics

SchemaResult<T>

T

SchemaStrictObjectInput
#

schema.ts view source

SchemaStrictObjectInput<T>

type T extends unknown ? [keyof T] extends [never] ? Record<string, never> : SchemaObjectInput<T> : never

The input of object: SchemaObjectInput of the entries, or Record<string, never> where there are none, as it then refuses every key.

import type {SchemaStrictObjectInput} from '@fuzdev/fuz_schema/schema.ts';

generics

SchemaStrictObjectInput<T extends SchemaEntries>

T

constraint SchemaEntries

SchemaStrictObjectOutput
#

schema.ts view source

SchemaStrictObjectOutput<T>

type T extends unknown ? [keyof T] extends [never] ? Record<string, never> : SchemaObjectOutput<T> : never

The output of object and strip_object: SchemaObjectOutput of the entries, or Record<string, never> where there are none, as both output an object with no keys then, and {} is any value but null and undefined. Distributes over a union of entries, as keyof of a union is only the shared keys.

import type {SchemaStrictObjectOutput} from '@fuzdev/fuz_schema/schema.ts';

generics

SchemaStrictObjectOutput<T extends SchemaEntries>

T

constraint SchemaEntries

SchemaStripObjectInput
#

schema.ts view source

SchemaStripObjectInput<T>

type T extends unknown ? [keyof T] extends [never] ? Record<string, unknown> : SchemaObjectInput<T> : never

The input of strip_object: SchemaObjectInput of the entries, or Record<string, unknown> where there are none, as it then takes any object that isn't an array and drops each of its keys.

import type {SchemaStripObjectInput} from '@fuzdev/fuz_schema/schema.ts';

generics

SchemaStripObjectInput<T extends SchemaEntries>

T

constraint SchemaEntries

SchemaToIntegerDef
#

schema.ts view source

The def of to_integer: the grammar it reads, both options written.

import type {SchemaToIntegerDef} from '@fuzdev/fuz_schema/schema.ts';

members

readonly

unsigned

: boolean
#

Whether a - is refused, so only an optional + comes before the digits.

readonly

trim

: boolean
#

Whether Unicode White_Space before and after the integer is taken and dropped.

SchemaWrapperDef
#

schema.ts view source

SchemaWrapperDef<T>

The def of optional and nullable, and the part of it every wrapper has. An interface, so it has no index signature and is not mistaken for the entries of an object schema.

import type {SchemaWrapperDef} from '@fuzdev/fuz_schema/schema.ts';

generics

SchemaWrapperDef<T extends Schema>

T

constraint Schema

members

readonly

schema

: T
#

StandardSchemaV1
#

standard_schema.ts view source

StandardSchemaV1<TInput, TOutput>

The Standard Schema types for an adapter without JSON Schema output, copied from version 1.1 of the spec as it recommends so there's no dependency on @standard-schema/spec. The spec nests its types in namespaces. Here each is flat, named by its path.

Left out: the spec's JSON Schema interface, which this adapter doesn't produce (to_json_schema is a module of its own), and its inference helpers, which a consumer takes from the spec itself and which work on these types as they are.

import type {StandardSchemaV1} from '@fuzdev/fuz_schema/standard_schema.ts';

generics

StandardSchemaV1<TInput = unknown, TOutput = TInput>

TInput

default unknown

TOutput

default TInput

members

readonly

'~standard'

: StandardSchemaV1Props<TInput, TOutput>
#

StandardSchemaV1Issue
#

standard_schema.ts view source

The spec's StandardSchemaV1.Issue: a failure's text and the keys from the value to where it failed, outermost first, each a key or an object holding one. to_standard_schema writes each key bare.

import type {StandardSchemaV1Issue} from '@fuzdev/fuz_schema/standard_schema.ts';

members

readonly

message

: string
#
readonly

path

?: readonly (PropertyKey | { readonly key: PropertyKey; })[]
#

StandardSchemaV1Options
#

standard_schema.ts view source

The spec's StandardSchemaV1.Options: what validate may be passed.

import type {StandardSchemaV1Options} from '@fuzdev/fuz_schema/standard_schema.ts';

members

readonly

libraryOptions

?: Record<string, unknown>
#

Vendor-specific parameters. to_standard_schema reads none.

StandardSchemaV1Props
#

standard_schema.ts view source

StandardSchemaV1Props<TInput, TOutput>

The spec's StandardSchemaV1.Props: StandardTypedV1Props and validate, which may return its result or a promise of it.

import type {StandardSchemaV1Props} from '@fuzdev/fuz_schema/standard_schema.ts';

generics

StandardSchemaV1Props<TInput = unknown, TOutput = TInput>

TInput

default unknown

TOutput

default TInput

inheritance

extends: StandardTypedV1Props<TInput, TOutput>

members

readonly

validate

: (value: unknown, options?: StandardSchemaV1Options) => StandardSchemaV1Result<TOutput> | Promise<StandardSchemaV1Result<TOutput>>
#

StandardSchemaV1Result
#

standard_schema.ts view source

type { readonly value: TOutput; readonly issues?: undefined; } | { readonly issues: readonly StandardSchemaV1Issue[]; }

The spec's StandardSchemaV1.Result: the output of a value that matches, or the issues of one that doesn't, told apart by issues.

import type {StandardSchemaV1Result} from '@fuzdev/fuz_schema/standard_schema.ts';

generics

StandardSchemaV1Result<TOutput>

TOutput

StandardTypedV1
#

standard_schema.ts view source

StandardTypedV1<TInput, TOutput>

The base the spec's other interfaces extend: a vendor, a version, and types.

import type {StandardTypedV1} from '@fuzdev/fuz_schema/standard_schema.ts';

generics

StandardTypedV1<TInput = unknown, TOutput = TInput>

TInput

default unknown

TOutput

default TInput

members

readonly

'~standard'

: StandardTypedV1Props<TInput, TOutput>
#

StandardTypedV1Props
#

standard_schema.ts view source

StandardTypedV1Props<TInput, TOutput>

The spec's StandardTypedV1.Props: what ~standard holds on every one of its interfaces, the version of the spec, the library's name, and the types.

import type {StandardTypedV1Props} from '@fuzdev/fuz_schema/standard_schema.ts';

generics

StandardTypedV1Props<TInput = unknown, TOutput = TInput>

TInput

default unknown

TOutput

default TInput

members

readonly

version

: 1
#
readonly

vendor

: string
#
readonly

types

?: StandardTypedV1Types<TInput, TOutput>
#

Type-only: to_standard_schema never sets it.

StandardTypedV1Types
#

standard_schema.ts view source

StandardTypedV1Types<TInput, TOutput>

The spec's StandardTypedV1.Types: the input and output types of a schema.

import type {StandardTypedV1Types} from '@fuzdev/fuz_schema/standard_schema.ts';

generics

StandardTypedV1Types<TInput = unknown, TOutput = TInput>

TInput

default unknown

TOutput

default TInput

members

readonly

input

: TInput
#
readonly

output

: TOutput
#

string
#

schema.ts view source

StringSchema

Matches a string.

import {string} from '@fuzdev/fuz_schema/schema.ts';

StringSchema
#

schema.ts view source

The type of string.

import type {StringSchema} from '@fuzdev/fuz_schema/schema.ts';

inheritance

extends: Schema<string, string, "string", undefined>

strip_object
#

schema.ts view source

strip_object<T extends SchemaEntries>(entries: T): StripObjectSchema<T>

Matches an object with entries, dropping unknown keys from the output. Dropping means copying, so where no entry changed this costs more than object or loose_object whenever there is a key to drop. The output is the input itself when no entry changed and there was nothing to drop.

import {strip_object} from '@fuzdev/fuz_schema/schema.ts';

StripObjectSchema
#

to_guard_source
#

compile.ts view source

to_guard_source(schema: Schema, name: string, library?: string): string

Writes schema as the text of an ES module that exports a guard under name: a function that gives is(schema, value), for a build to write to a file, so the guard ships with no new Function and, where the schema holds no format action, without the library.

The text is the code compile_guard makes, with what that captures written out. A regex is written as its pattern and flags. A uuid, an iso_datetime, and a to_integer are imported from library and run as the library's, by their kind and def, so the text holds no copy of a grammar. A memo_union keeps its verdicts for the length of a call. What compile_guard refuses is refused, and so is what has no text: a check, a transform, a with_default_fn, a schema of a kind defined outside the library, and a subtree compile_guard hands to the interpreter.

The text is JavaScript, and starts with `//

import {to_guard_source} from '@fuzdev/fuz_schema/compile.ts';

parameters

schema

: Schema
#

read by its kind and def, and never written to

name

: string
#

what the module exports the guard as: an identifier but then, and default for the default export

library

?: string = '@fuzdev/fuz_schema/schema.js'
#

the specifier the module imports the format actions from, a string

returns

the text of the module

throws

  • Error - where name is no identifier or is then, where library is no string, naming the kind and the path of a schema that can't be written, and all that compile_guard throws

examples

const User = s.object({name: s.string, tags: s.array(s.string)}); to_guard_source(User, 'is_user'); // '//

to_integer
#

schema.ts view source

to_integer(options?: ToIntegerOptions): SchemaAction<number, string, "to_integer", SchemaToIntegerDef>

Replaces a string of decimal digits with the integer it spells, a number, and fails a string that spells none or one past the safe integers. The grammar is Rust's str::parse::<i64>: an optional + or -, then one or more ASCII digits, leading zeros taken, and nothing else, so '', a space, an exponent, a fraction, 0x10, and 1_000 fail. unsigned refuses the -, as str::parse::<u64> does, and trim takes Unicode White_Space around it, as str::trim drops it. A -0 gives 0.

In a pipe it follows a string and outputs a number, so the bounds after it are of the integer: pipe(string, to_integer(), min_value(1), max_value(1000)). Its issue is of kind to_integer, expected `'a safe integer in decimal digits', or 'an unsigned safe integer in decimal digits'`, whether the grammar or the range failed, and received 'string' in a pipe and the type of the value given outside one. Outside a pipe it fails any value that isn't a string, where a test of its grammar alone would convert it.

to_json_schema writes it on the output side as an integer within the bounds after it, and on the input side as a pattern of exactly the strings those bounds take. to_schema_json refuses it, as the Rust crate does not carry it.

import {to_integer} from '@fuzdev/fuz_schema/schema.ts';

parameters

#

unsigned refuses a -, and trim takes white space around the integer

to_json_schema
#

json_schema.ts view source

to_json_schema(schema: AnySchema, options?: JsonSchemaOptions): JsonSchema

Writes schema as a JSON Schema document, with $schema naming draft 2020-12.

  • An object schema is {type: 'object', properties, required}: object closes it with additionalProperties: false, strip_object too on the output side, loose_object writes {} there, and object_with_rest its rest. A key is optional where the parse can do without it: on the input side where a missing key passes, and on the output side where the parse can leave it out, read as the library runs the entry on a missing key, through a nullable, a lazy, a pipe and its steps, and a union's options in the order it tries them.
  • A record is {type: 'object', propertyNames, additionalProperties}, and a keyed_record the same with its key schema's node as propertyNames.
  • A nullable and a union are anyOf, folded into a type array where every option is a bare type, and a variant is oneOf of the options it can pick, or anyOf where a discriminator is written as other than a const.
  • The actions of a pipe are keywords of its first schema's node: lengths, bounds, integer, formats, and patterns, the tightest bound winning. A to_lower_case writes none, and the keyword of a step that reads another string than the document's, after it on the input side or before it on the output side, is unrepresentable, but a uuid's, which holds of both.
  • A to_integer is an integer within the bounds after it on the output side, with nothing of the string, its metadata included, and on the input side a pattern of exactly the strings it reads within them, not: {} where none is. On the output side a step before it that asserts something of the string is unrepresentable, as the output can't be narrowed by it, and on the input side its default is left out, as for a transform.
  • A with_default writes default, unless its schema transforms on the input side. A with_default_fn writes none, as its make is never called, and drops one of the schema it holds.
  • A lazy is written in place, unless the schema comes back to itself, when it is in $defs and referred to, or is # when it is the root.
  • The metadata of every layer is copied into the node it is written in, the outer layer winning, a with_default's default included, and undefined clearing a key. A key that is a keyword of JSON Schema, but an annotation, is refused, as it would change what the document accepts.
import {to_json_schema} from '@fuzdev/fuz_schema/json_schema.ts';

parameters

schema

: AnySchema
#

the schema to write

#

which side of a parse, and what to do with what can't be written

throws

  • Error - naming the kind and the place in the document of what can't be written, or is refused

to_lower_case
#

schema.ts view source

SchemaAction<string, string, "to_lower_case", undefined>

type SchemaAction<string, string, "to_lower_case", undefined>

Replaces a string with value.toLowerCase(), its lowercase by Unicode's mappings and in no locale, and never fails. A step after it in a pipe is given the lowercase: pipe(string, to_lower_case, min_length(2)) reads the length of what toLowerCase gave, which is not always the input's.

In a pipe it outputs a string, as the value is a new one: a literal or a brand of the step before it is not kept, and one around the pipe is, brand(pipe(string, uuid, to_lower_case), 'Uuid'). Outside a pipe it calls toLowerCase on whatever it is given, which throws on a value that has none, as undefined, a missing key included, does.

to_json_schema writes no keyword for it, as Zod writes none for its toLowerCase, and refuses a step but a uuid that reads another string than its document: after it on the input side, and before it on the output side. to_schema_json writes it after a string.

import {to_lower_case} from '@fuzdev/fuz_schema/schema.ts';

to_schema_json
#

schema_json.ts view source

to_schema_json(schema: AnySchema): SchemaJson

Serializes schema to the interchange form.

A lazy is named by what it defers to, $0, $1, and so on in the order they are met, so two lazy that return the same schema share a name. Each function a lazy holds is called once, however many schemas hold it.

import {to_schema_json} from '@fuzdev/fuz_schema/schema_json.ts';

throws

  • Error - naming the kind and the path of anything the Rust crate refuses

to_standard_schema
#

standard_schema.ts view source

to_standard_schema<T extends AnySchema>(schema: T): StandardSchemaV1<InferInput<T>, Infer<T>>

Wraps schema in a Standard Schema, for passing to libraries that accept one. The result is not itself a Schema, so it can't be nested in other schemas.

Its validate is synchronous and ignores the options argument, and types is left unset: the input and output types are carried by the return type.

import {to_standard_schema} from '@fuzdev/fuz_schema/standard_schema.ts';

ToIntegerOptions
#

schema.ts view source

Options of to_integer.

import type {ToIntegerOptions} from '@fuzdev/fuz_schema/schema.ts';

members

unsigned

?: boolean
#

Refuse a -, as Rust's str::parse::<u64> does. Defaults to false.

trim

?: boolean
#

Take Unicode White_Space before and after the integer, the characters Rust's str::trim drops: JavaScript's \s and U+0085, but U+FEFF. Defaults to false.

transform
#

schema.ts view source

transform<T, O>(fn: (value: T) => O): SchemaAction<O, T, "transform", (value: T) => O>

Replaces the value with what fn returns, and reports no failure. It is an action that changes the value, so not a refinement: in a pipe the steps after it are given what fn returns, and the output is typed from it.

to_schema_json refuses it, as it holds a function.

import {transform} from '@fuzdev/fuz_schema/schema.ts';

parameters

fn

: (value: T) => O
#

given the value, and returns the output

Uninferred
#

schema.ts view source

type [T] extends [infer U extends T] ? U : never

Resolves to T, in a form nothing is inferred through. An action's T is the type it is given, which comes from its input in a pipe and never from what the schema around that pipe expects, which is any schema and would make it any. For the same reason the bound of a value action is typed by whether it is a number or a bigint and its def apart from T: either of them typed T would have the bound's literal type inferred as the value's. A pipe writes its output in it too: inferred from what the schema around it expects, the output would be any, and so would the value an unannotated check or transform at its end is given. The extends T bound keeps the result assignable to T while T is still generic, and the tuple keeps it from distributing over a generic T, which would have the check at the end of a pipe of a generic schema typed from the pipe's declared type and not as the schema's output. So a function that pipes its own generic action or schema can return the pipe as its declared type, and inference is blocked all the same.

Exported so a declaration emitted for such a function can name it: inlined, the bound would refer to a type parameter the emitted file doesn't declare.

import type {Uninferred} from '@fuzdev/fuz_schema/schema.ts';

generics

Uninferred<T>

T

union
#

schema.ts view source

union<const T extends readonly Schema[]>(options: T): UnionSchema<T>

Matches the first of options that accepts the value. On failure reports one issue, not the options' own. It names the options as received names values, each part once by its text, where it first appears: a union among them by its own options, at any depth, a pipe by its first schema, a nullable by its schema's and then null, an optional, a with_default, or a with_default_fn by its schema's, a literal or a one_of by each of its values as they write them, any object schema, a record, a keyed_record, and a variant included, as object, and any other schema by its kind, but a kind defined outside the library whose name holds object, record, or variant, which is object too. So union([number, union([nullable(string), pipe(one_of(['a', 'b']), check(..)), loose_object({})])]) expects number | string | null | "a" | "b" | object, and a union with nothing to name, as union([]) has, expects ''.

As an object entry it hands every option the object and the key when any of them takes them. So a missing key matches only where an option lets its key be missing, as an optional does and an unknown doesn't, and with none it fails as any other value does, with the union's issue. The first option that matches is the union's, and a missing key it leaves undefined stays out: union([unknown, optional(string)]) accepts a missing key with the optional. When the option that matches fills a value in, as a with_default or a with_default_fn does, the key is optional and the undefined it reads as is for the options before to match: each of them that takes the object and the key is run again without them, and the first that matches is the union's. So union([pipe(unknown, ...), with_default(...)]) runs the pipe's steps on undefined in place of filling the default in, and union([unknown, with_default(...)]) leaves the key out. The make of a with_default_fn there is called, and what it returns dropped. An option run again runs twice in the parse, and a transform in it that the first run reached runs twice too, once more for each enclosing union that tries it again.

A recursive union whose options walk a node's children before an entry tells them apart takes time exponential in the input's depth, as each option walks them again at every level: with two such options the time doubles with each level. On untrusted input of that shape use variant, which dispatches on a literal discriminator, put each option's literal entries first, or use memo_union.

import {union} from '@fuzdev/fuz_schema/schema.ts';

UnionSchema
#

schema.ts view source

UnionSchema<T>

The type of union(options) and of memo_union(options), where T is the type of options.

import type {UnionSchema} from '@fuzdev/fuz_schema/schema.ts';

generics

UnionSchema<T extends ReadonlyArray<Schema>>

T

constraint readonly Schema[]

inheritance

extends: Schema<Infer<T[number]>, InferInput<T[number]>, "union", T>

unknown
#

schema.ts view source

UnknownSchema

Accepts anything.

As an object entry it needs its key: undefined at a key the object has, own or inherited, is accepted, and a key that is missing fails as a missing_key. Write optional(unknown) to let the key be missing.

It tells the two apart by the object and key the object schema hands it, which reach it as the entry itself and through flavor, brand, meta, message, nullable, lazy, an option of a union or a memo_union, and the first schema of a pipe. Anywhere else it is told nothing of a key and accepts undefined: at the top level, as an array's item, as a record's value, and as a step of a pipe after the first. Under a union whose first option to match a missing key after it fills the key in, as a with_default does, the key is optional, and it accepts the undefined, see union.

import {unknown} from '@fuzdev/fuz_schema/schema.ts';

UnknownSchema
#

schema.ts view source

The type of unknown.

import type {UnknownSchema} from '@fuzdev/fuz_schema/schema.ts';

inheritance

extends: Schema<unknown, unknown, "unknown", undefined>

unwrap_schema
#

introspect.ts view source

unwrap_schema(schema: AnySchema): SchemaNode

The innermost layer of schema, what the value is under its wrappers: string for optional(nullable(string)), and schema itself when it is no wrapper.

import {unwrap_schema} from '@fuzdev/fuz_schema/introspect.ts';

uuid
#

schema.ts view source

SchemaRefinement<string, string, "uuid", undefined>

type SchemaRefinement<string, string, "uuid", undefined>

Fails a string that isn't a UUID of RFC 9562: five groups of hex digits, 8-4-4-4-12, with a version from 1 to 8 and the RFC's variant, or the nil or the max UUID. Either case of hex digit passes, and the output is the string as given. Fails any value that isn't a string, where regex would convert it. In a pipe its output is the type of the step before it.

import {uuid} from '@fuzdev/fuz_schema/schema.ts';

variant
#

schema.ts view source

variant<TKey extends string, const T extends readonly Schema<any, any, string, SchemaEntries>[]>(key: TKey, options: T): VariantSchema<TKey, T>

Matches the object schema in options whose key literal equals the value's, a discriminated union with constant-time dispatch.

An input without the key reads as undefined there, so it selects an option whose literal is undefined, and that option's entry then fails it as a missing_key.

import {variant} from '@fuzdev/fuz_schema/schema.ts';

parameters

key

: TKey
#

the discriminator, which must be a literal entry in every option

VariantSchema
#

schema.ts view source

VariantSchema<TKey, T>

The type of variant(key, options), where TKey is the type of key and T of options. A variant over exported object schemas whose types have names, as ObjectSchema gives them, needs no annotation of its own: its declaration names its options.

import type {VariantSchema} from '@fuzdev/fuz_schema/schema.ts';

generics

VariantSchema<TKey extends string, T extends ReadonlyArray<Schema<any, any, string, SchemaEntries>>>

TKey

constraint string

T

constraint readonly Schema<any, any, string, SchemaEntries>[]

inheritance

extends: Schema<Infer<T[number]>, InferInput<T[number]>, "variant", { readonly key: TKey; readonly options: T; }>

void
#

schema.ts view source

VoidSchema

Matches undefined, typed void in and out, so a function whose parameter is typed from it can be called with no argument: (input: Infer<typeof s.void>) => ... is called as f().

It is literal(undefined) in all but its types: its kind is 'literal' and its def is undefined, so every reader of a schema takes it as that literal, to_schema_json and to_json_schema refusing it as they refuse literal(undefined). As an object entry it needs its key, as that literal does: write optional(s.void) to let the key be missing.

Exported as void, a reserved word, so it is read as s.void through a namespace import.

import {void} from '@fuzdev/fuz_schema/schema.ts';

VoidSchema
#

schema.ts view source

The type of void: a literal of undefined, typed void in and out.

import type {VoidSchema} from '@fuzdev/fuz_schema/schema.ts';

inheritance

extends: Schema<void, void, "literal", undefined>

with_default
#

schema.ts view source

with_default(schema: T, value: SchemaDefaultOutput<T>): WithDefaultSchema<T>

Replaces undefined with value. As an object entry it makes the key optional in the input and required in the output.

value is not validated, and is returned as it is: every parse that fills it in gives the same object, so an array or an object changed by one consumer is changed for every other. with_default_fn makes a new one each time.

schema is never given undefined, which value replaces, so an optional it holds never gives one: with_default(optional(string), 'd') outputs a string, and so does nullable(optional(string)), with its null. Any other schema keeps its output type, undefined and all, as one can give undefined for a value that isn't, as a transform can.

import {with_default} from '@fuzdev/fuz_schema/schema.ts';

parameters

returned as it is, the same reference on every parse

overloads

with_default<T extends Schema>(schema: T, value: SchemaDefaultOutput<T>): WithDefaultSchema<T>
with_default<T extends Schema>(schema: T, value: Infer<T>): WithUndefinedDefaultSchema<T>

with_default_fn
#

schema.ts view source

with_default_fn(schema: T, make: () => SchemaDefaultOutput<T>): WithDefaultFnSchema<T>

Replaces undefined with what make returns, called with no arguments once for each value it fills in. As an object entry it makes the key optional in the input and required in the output, as with_default does.

What make returns is not validated, as with with_default, and as in Zod. It is for a default that must be new on every parse, as a mutable array or object must, or that is computed when it is filled in: with_default_fn(s.array(s.string), () => []).

As an object entry whose key is missing, a make that returns undefined leaves the key out, as with_default with a value of undefined does. Over an optional, one typed to never return undefined makes an output that isn't, as with_default does for its value.

import {with_default_fn} from '@fuzdev/fuz_schema/schema.ts';

parameters

make

: () => SchemaDefaultOutput<T>
#

called for each undefined, with no arguments, and never called otherwise

overloads

with_default_fn<T extends Schema>(schema: T, make: () => SchemaDefaultOutput<T>): WithDefaultFnSchema<T>
with_default_fn<T extends Schema>(schema: T, make: () => Infer<T>): WithUndefinedDefaultFnSchema<T>

WithDefaultFnSchema
#

WithDefaultSchema
#

WithUndefinedDefaultFnSchema
#

WithUndefinedDefaultSchema
#

schema.ts view source

WithUndefinedDefaultSchema<T>

The type of with_default(schema, value) where value may be undefined, as one typed by a generic schema's output may: the output of T as it is.

import type {WithUndefinedDefaultSchema} from '@fuzdev/fuz_schema/schema.ts';

generics

WithUndefinedDefaultSchema<T extends Schema>

T

constraint Schema

inheritance

extends: Schema<Infer<T>, InferInput<T> | undefined, "with_default", SchemaDefaultDef<T>>