Building schemas

Adding the keywords

import Ajv2020 from "ajv/dist/2020.js";
import { addJsontron } from "@devlooped/jsontron";

const ajv = addJsontron(new Ajv2020({ allErrors: true }));

addJsontron adds the four keywords to the Ajv instance and returns it, typed as it was, so it can wrap the constructor. Do it once per Ajv instance, before compiling a schema that uses them. Strict mode does not need to be relaxed: the keywords are known to Ajv.

Compiling

ajv.compile(schema) does, for every schema object with Jsontron keywords:

  1. checks the keywords against their syntax (a test that is not a string, a blank id, a let named root, both flag and role on an item...);
  2. compiles each context, test, let and message expression on its own;
  3. lowers the merged rule set to one jq program (ยง7 of the specification) and compiles it.

Each schema object is lowered once, even when Ajv compiles it several times, and the program is reused for every document. The whole document is handed to jq only when an expression reads $root.

Build errors

A schema whose keywords are invalid is not compiled: ajv.compile throws a JsontronSchemaError, whose message says which keyword or expression is wrong.

import { JsontronSchemaError } from "@devlooped/jsontron";

try {
  ajv.compile({ assert: ".total >" });
} catch (error) {
  if (error instanceof JsontronSchemaError) console.log(error.message);
}
Invalid jq in 'rules[0].asserts[0].test': Unexpected end of program at line 1, column 9

The location names the expression in the merged rule set: the assert sugar is the first rule, whose context is ..

An undefined $name is not a build error: it fails when it is evaluated (see jq in Jsontron).

The meta-schema

metaSchema is the Jsontron 0.2 meta-schema, https://www.schemastore.org/jsontron-0.2.json, as an object: the syntax of the four keywords, for tools that check schemas. Editors that read SchemaStore find it from a schema's $schema.