@tola/schema
Declare, compose, inspect, and run validation schemas over metadata and Typst values.
Import
#import "@tola/schema:0.0.0": *Pass a dictionary of field rules to schema(...). Each field accepts a Typst type (such as str or int) or a schema rule (such as array-of(str)). Wrappers evaluate from the inside out: non-empty(trim(str)) trims whitespace first, then rejects empty strings.
Use parse to return the validated value or raise an error; use try-parse to handle (ok:, value:) / (ok:, issues:) directly. For content file metadata, prefer @tola/source#parse-sources so errors point to the source file.
Examples
Validate page metadata with defaults and constraints
#import "@tola/schema:0.0.0": array-of, date, non-empty, optional, parse, schema, trim
#let post-schema = schema((
title: non-empty(trim(str)),
draft: optional(bool, default: false),
published: optional(date),
tags: optional(array-of(non-empty(trim(str))), default: ()),
))
#let meta = parse((title: " Notes "), post-schema)Exports
anyarray-ofat-leastat-mostcheckconvertdatedefaultsdescribedictionary-ofemailenum-oferrformat-issueshttp-urlhttps-urlinspectipipv4ipv6issuelazyliteralmapmatchesmax-lengthmin-lengthnon-emptynullableokone-or-manyoptionalparsepartialpartial-daterefineschematimestamptrimtry-parsetupleunionurl-pathvariant
any
any: value (defined by package)Schema accepting any Typst value unchanged.
array-of
let array-of(
member: type | dictionary,
) = dictionary;Validate an array whose elements each satisfy member.
Positional parameters
membertype | dictionaryrequired: Element type or schema.
at-least
let at-least(
member: type | dictionary,
minimum: int | float,
) = dictionary;Require a numeric value (int or finite float) to be greater than or equal to minimum.
Positional parameters
membertype | dictionaryrequired: Inner numeric schema.minimumint | floatrequired: Inclusive lower bound.
at-most
let at-most(
member: type | dictionary,
maximum: int | float,
) = dictionary;Require a numeric value (int or finite float) to be less than or equal to maximum.
Positional parameters
membertype | dictionaryrequired: Inner numeric schema.maximumint | floatrequired: Inclusive upper bound.
check
let check(
member: type | dictionary,
inspect: function,
on: none | array = none,
) = dictionary;Attach custom multi-issue validation logic to member.
Positional parameters
membertype | dictionaryrequired: Inner type or schema run first.inspectfunctionrequired: Function(value) => arrayreturning zero or moreissue(...)records.
Named parameters
onnone | arraydefault:none: Optional field path or key where reported issues attach.
convert
let convert(
member: type | dictionary,
convert-value: function | type,
output: type | dictionary = any,
) = dictionary;Validate member, then transform it with a fallible converter returning ok(...) or err(...).
Positional parameters
membertype | dictionaryrequired: Inner type or schema run first.convert-valuefunction | typerequired: Function(value) => ok(v) | err(...).
Named parameters
outputtype | dictionarydefault:any: Optional schema describing the converted output type forinspect.
date
date: value (defined by package)Built-in schema parsing a calendar date ("YYYY-MM-DD" or Typst datetime) into a Typst datetime date.
defaults
let defaults(
member: type | dictionary,
) = dictionary;Materialize the default dictionary defined by an object schema (requires every field to be optional or have a default).
Positional parameters
membertype | dictionaryrequired: Object schema whose defaults to resolve.
describe
let describe(
member: type | dictionary,
description: string,
) = dictionary;Attach a human-readable description string to member for inspect.
Positional parameters
membertype | dictionaryrequired: Inner type or schema.descriptionstringrequired: Non-empty description string.
dictionary-of
let dictionary-of(
member: type | dictionary,
) = dictionary;Validate a dictionary whose values each satisfy member.
Positional parameters
membertype | dictionaryrequired: Value type or schema applied to every entry.
email
email: value (defined by package)Built-in string schema validating email address syntax.
enum-of
let enum-of(
values: array,
) = dictionary;Match any value equal to one of the elements in values.
Positional parameters
valuesarrayrequired: Non-empty array of allowed values.
err
let err(
..issues: arguments,
) = dictionary;Wrap one or more validation issues returned from a convert callback.
Rest parameters
..issuesarguments: One or moreissue(...)records (or message strings).
format-issues
let format-issues(
issues: array,
) = string;Format an array of issues from try-parse into readable multi-line text.
Positional parameters
issuesarrayrequired: Array of issue records.
http-url
http-url: value (defined by package)Built-in string schema validating absolute http:// or https:// URLs.
https-url
https-url: value (defined by package)Built-in string schema validating absolute https:// URLs.
inspect
let inspect(
member: type | dictionary,
input: bool = false,
) = dictionary;Return a structured description of a schema’s fields, types, defaults, and descriptions without parsing data.
Positional parameters
membertype | dictionaryrequired: Schema to inspect.
Named parameters
inputbooldefault:false: Whentrue, describe the accepted input shape before conversions;false(default) describes the output shape.
ip
ip: value (defined by package)Built-in string schema accepting either IPv4 or IPv6 addresses.
ipv4
ipv4: value (defined by package)Built-in string schema validating dotted-quad IPv4 addresses.
ipv6
ipv6: value (defined by package)Built-in string schema validating IPv6 addresses (full or ::-compressed).
issue
let issue(
message: string,
code: string = "custom",
notes: array = (),
path: array = (),
) = dictionary;Construct a structured validation issue for check or convert.
Positional parameters
messagestringrequired: Human-readable problem description.
Named parameters
codestringdefault:"custom": Optional machine-readable issue code.patharraydefault:(): Optional array of path segments locating the offending field or index.notesarraydefault:(): Optional array of explanatory note strings.
lazy
let lazy(
factory: function,
) = dictionary;Defer schema construction to support recursive data structures.
Positional parameters
factoryfunctionrequired: Zero-argument function() => schemaevaluated on demand.
literal
let literal(
value: any,
) = dictionary;Match only a single exact Typst value.
Positional parameters
valueanyrequired: Exact expected value.
map
let map(
member: type | dictionary,
convert-value: function | type,
output: type | dictionary = any,
) = dictionary;Transform a validated value with convert-value (cannot fail with schema issues).
Positional parameters
membertype | dictionaryrequired: Inner type or schema run first.convert-valuefunction | typerequired: Function(value) => new-valueapplied aftermembersucceeds.
Named parameters
outputtype | dictionarydefault:any: Optional schema describing the mapped output type forinspect.
matches
let matches(
member: type | dictionary,
expression: regex,
) = dictionary;Require a string value to match a regular expression.
Positional parameters
membertype | dictionaryrequired: Inner string schema.expressionregexrequired: Typstregex(...)or pattern string.
max-length
let max-length(
member: type | dictionary,
maximum: int,
) = dictionary;Require a string, array, dictionary, or bytes value to have length at most maximum.
Positional parameters
membertype | dictionaryrequired: Inner type or schema.maximumintrequired: Non-negative maximum length.
min-length
let min-length(
member: type | dictionary,
minimum: int,
) = dictionary;Require a string, array, dictionary, or bytes value to have length at least minimum.
Positional parameters
membertype | dictionaryrequired: Inner type or schema.minimumintrequired: Non-negative minimum length.
non-empty
let non-empty(
member: type | dictionary,
) = dictionary;Reject empty strings, arrays, dictionaries, or bytes after validating member.
Positional parameters
membertype | dictionaryrequired: Inner type or schema.
nullable
let nullable(
member: type | dictionary,
) = dictionary;Allow none in addition to values matching member.
Positional parameters
membertype | dictionaryrequired: Inner type or schema checked when the value is notnone.
ok
let ok(
value: any,
) = dictionary;Wrap a successful converted value returned from a convert callback.
Positional parameters
valueanyrequired: Converted value.
one-or-many
let one-or-many(
member: type | dictionary,
) = dictionary;Accept either a single member value or an array of member values, normalizing to an array.
Positional parameters
membertype | dictionaryrequired: Element type or schema.
optional
let optional(
member: type | dictionary,
..options: arguments,
) = dictionary;Allow a dictionary field to be omitted, optionally supplying a default value when absent.
Positional parameters
membertype | dictionaryrequired: Inner type or schema validated whenever the key is present.
Rest parameters
..optionsarguments: Optional nameddefault: valueused when the key is missing (must itself satisfymember). Invalid supplied values fail rather than falling back todefault.
parse
let parse(
value: any,
member: type | dictionary,
) = any;Validate value against member and return the parsed result, raising a formatted error on failure.
Positional parameters
valueanyrequired: Input value to validate.membertype | dictionaryrequired: Type or schema declaration.
partial
let partial(
member: type | dictionary,
..fixed: arguments,
) = function;Make all fields of an object schema optional, except any field names listed in fixed.
Positional parameters
membertype | dictionaryrequired: Object schema created withschema(...).
Rest parameters
..fixedarguments: Optional field names that remain required.
partial-date
partial-date: value (defined by package)Built-in schema parsing a year ("YYYY"), year-month ("YYYY-MM"), or full date into (year:, month:, day:, precision:, iso:).
refine
let refine(
member: type | dictionary,
predicate: function,
message: string = none,
) = dictionary;Add a boolean predicate check to member.
Positional parameters
membertype | dictionaryrequired: Inner type or schema run first.predicatefunctionrequired: Function(value) => boolreturningtruewhen valid.
Named parameters
messagestringdefault:none: Optional error message whenpredicatereturnsfalse.
schema
let schema(
fields: dictionary,
unknown: string = "error",
) = dictionary;Declare a dictionary schema mapping field names to types or child schemas.
Positional parameters
fieldsdictionaryrequired: Dictionary mapping field names to Typst types or@tola/schemarules.
Named parameters
unknownstringdefault:"error": How undeclared keys are handled:"error"(default, reject),"strip"(drop), or"keep"(preserve unchanged).
timestamp
timestamp: value (defined by package)Built-in schema parsing an RFC 3339 timestamp string (with timezone offset) into (datetime:, offset:, rfc3339:).
Pass .rfc3339 directly to @tola/feed#feed or @tola/sitemap#sitemap.
trim
let trim(
member: type | dictionary,
) = dictionary;Strip leading and trailing whitespace from a string before passing it to member.
Positional parameters
membertype | dictionaryrequired: Inner string schema (typicallystr).
try-parse
let try-parse(
value: any,
member: type | dictionary,
) = dictionary;Validate value against member without panicking, returning (ok: true, value: ...) or (ok: false, issues: ...) .
Positional parameters
valueanyrequired: Input value to validate.membertype | dictionaryrequired: Type or schema declaration.
tuple
let tuple(
..members: arguments,
rest: none | type | dictionary = none,
) = dictionary;Validate a fixed-position array with per-slot schemas and an optional trailing rest schema.
Rest parameters
..membersarguments: Positional schemas for each required index.
Named parameters
restnone | type | dictionarydefault:none: Optional schema for extra elements aftermembers;none(default) rejects extra elements.
union
let union(
..members: arguments,
) = dictionary;Try candidate schemas in order and accept the first match.
Rest parameters
..membersarguments: Two or more candidate types or schemas tried from left to right.
url-path
url-path: value (defined by package)Built-in schema validating a site-root URL path (such as a permalink) and decoding it for output-of or route-url.
variant
let variant(
tag-key: string,
..branches: arguments,
) = dictionary;Select a branch schema by matching a discriminator field (tag-key).
Positional parameters
tag-keystringrequired: Field name holding the discriminator value.
Rest parameters
..branchesarguments: Candidateschema(...)declarations, each fixingtag-keywithliteral(...)orenum-of(...).