[go: up one dir, main page]

dotschema

dotschema

Import JSON Schemas into TypeScript. Fully typed, scary fast.

If you have a JSON Schema like this:

user.schema.jsonc
{
  "type": "object",
  "properties": {
    "name": { "type": "string", "minLength": 1 },
    "role": { "enum": ["admin", "member"] }
  },
  "required": ["name"],
  "additionalProperties": false
}

You can import it directly from a TypeScript file, and get its type and a validator:

main.ts
import  from "./user.schema.jsonc";

const  = await request.json();

if (.is()) {
  ; // hover over data to see its type
}

It's powered by TypeScript's content mappers (introduced in TypeScript 7.1), which let a package give tsc the types of a file it imports. The validator is compiled by ajv when the module is built, so a bundle carries the validator and no validator library.

Setup

Install dotschema, then add it to TypeScript and to each tool that loads your code.

Install

You'll need:

  • TypeScript 7.1 (currently in beta). The first release with content mappers.
  • Node 24 or later.
npm install -D dotschema typescript@beta

If your app runs under the preload, not as a bundle, dotschema builds each schema's module at run time, so install it as a dependency:

npm install dotschema
npm install -D typescript@beta

TypeScript

Add dotschema to tsconfig.json as a content mapper:

tsconfig.json
{
  "compilerOptions": { /* ... */ },
  "contentMappers": [
    {
      "package": "dotschema",
      "extensions": [".schema.jsonc"]
    }
  ]
}

Then type-check with --runExternalCode, which lets tsc run content mappers:

package.json
{
  "scripts": {
    "typecheck": "tsc --noEmit --runExternalCode"
  }
}

Plugins

Install the plugin for your runtime or framework of choice:

Load dotschema's preload with --import, which turns each schema file into a module as it loads:

node --import dotschema/register main.ts

Add the preload to bunfig.toml, and under [test] for bun test:

bunfig.toml
preload = ["dotschema/register"]

[test]
preload = ["dotschema/register"]

For Bun's bundler, use the esbuild plugin:

build.ts
import dotschema from "dotschema/esbuild";

await Bun.build({
  entrypoints: ["main.ts"],
  target: "bun",
  plugins: [dotschema()],
  outdir: "dist",
});

Add the preload to nub.jsonc, for nub main.ts and nub --test:

nub.jsonc
{
  "preload": ["dotschema/register"]
}

Add the plugin to your Vite config, which builds each schema's module in the dev server and in the build, for the browser and for the server:

vite.config.ts
import { defineConfig } from "vite";
import dotschema from "dotschema/vite";

export default defineConfig({
  plugins: [dotschema()],
});

For Vitest, this plugin is all you need. Rollup and Rolldown take it too:

rollup.config.mjs
import dotschema from "dotschema/vite";

export default {
  input: "main.js",
  plugins: [dotschema()],
  output: { file: "dist/main.mjs", format: "es" },
};

Wrap your Next.js config with withDotschema:

next.config.ts
import type { NextConfig } from "next";
import { withDotschema } from "dotschema/next";

const nextConfig: NextConfig = {
  // ...
};

export default withDotschema(nextConfig);

Your server and client components can now import schemas, with Turbopack or webpack, and next build fails on a type error.

To type-check without building, run next typegen first, which writes the route types:

next typegen && tsc --noEmit --runExternalCode
How the build checks the types

Next.js type-checks without --runExternalCode, so withDotschema turns that check off and runs tsc --noEmit --runExternalCode inside next build in its place.

Beside Motherload or Reylo

Beside Motherload's withMotherload or Reylo's withReylo, the wrappers nest in either order:

next.config.ts
export default withMotherload(withDotschema(nextConfig));

Add the esbuild plugin, which builds each schema's module at build time, so a bundled app needs no preload:

build.mjs
import * as esbuild from "esbuild";
import dotschema from "dotschema/esbuild";

await esbuild.build({
  entryPoints: ["main.ts"],
  bundle: true,
  platform: "node",
  format: "esm",
  plugins: [dotschema()],
  outfile: "dist/main.mjs",
});

Load schema files with dotschema's loader:

webpack.config.mjs
export default {
  // ...
  module: {
    rules: [
      {
        test: /\.schema\.jsonc$/,
        use: "dotschema/webpack",
      },
    ],
  },
};

Load schema files with dotschema's loader:

rspack.config.mjs
export default {
  // ...
  module: {
    rules: [
      {
        test: /\.schema\.jsonc$/,
        use: "dotschema/webpack",
      },
    ],
  },
};

Add dotschema's Vite plugin beside Cloudflare's:

vite.config.ts
import { cloudflare } from "@cloudflare/vite-plugin";
import { defineConfig } from "vite";
import dotschema from "dotschema/vite";

export default defineConfig({
  plugins: [dotschema(), cloudflare()],
});

Deploy with wrangler deploy after vite build: Wrangler's own bundler takes no plugin.

Add dotschema's transformer to your Jest config:

jest.config.js
export default {
  transform: {
    "\\.schema\\.jsonc$": "dotschema/jest",
  },
  extensionsToTreatAsEsm: [".jsonc"],
};
# Jest runs ES modules only behind this Node flag
NODE_OPTIONS=--experimental-vm-modules npx jest
Beside another transformer for .jsonc

Jest runs the first pattern that matches a file, so beside another transformer for .jsonc, such as Motherload's, dotschema's pattern comes first:

jest.config.js
export default {
  transform: {
    "\\.schema\\.jsonc$": "dotschema/jest",
    "\\.jsonc$": "motherload/jest",
  },
};

Editors

Set up your editor to use the TypeScript 7.1 language server, with content mappers on.

  1. Install the TypeScript 7 extension (TypeScriptTeam.native-preview).

  2. Point it at the project's TypeScript: the extension's own copy is TypeScript 7.0, which has no content mappers.

    .vscode/settings.json
    {
      "js/ts.experimental.useTsgo": true,
      "js/ts.tsdk.path": "./node_modules/typescript"
    }
  3. Trust the workspace, and click Allow when the extension asks to use the workspace's TypeScript. Content mappers run in a trusted workspace only.

  1. Install the TypeScript 7 extension (TypeScriptTeam.native-preview).

  2. Point it at the project's TypeScript: the extension's own copy is TypeScript 7.0, which has no content mappers.

    .vscode/settings.json
    {
      "js/ts.experimental.useTsgo": true,
      "js/ts.tsdk.path": "./node_modules/typescript"
    }
  3. Trust the workspace, and click Allow when the extension asks to use the workspace's TypeScript. Content mappers run in a trusted workspace only.

  1. Install the TypeScript Language Server extension by Zed Industries (search for "tsgo").

  2. Point it at the project's TypeScript, with content mappers on:

    .zed/settings.json
    {
      "languages": {
        "TypeScript": {
          "language_servers": [
            "typescript-ls",
            "!vtsls",
            "!typescript-language-server",
            "..."
          ]
        },
        "TSX": {
          "language_servers": [
            "typescript-ls",
            "!vtsls",
            "!typescript-language-server",
            "..."
          ]
        }
      },
      "lsp": {
        "typescript-ls": {
          // the extension's own download is TypeScript 7.0,
          // which has no content mappers
          "binary": {
            "path": "node_modules/typescript/bin/tsc",
            "arguments": ["--lsp", "--stdio"]
          },
          "initialization_options": { "runExternalCode": true }
        }
      }
    }
  3. Trust the folder.

Zed doesn't send schema files to the language server, so an error inside one shows only in the type check.

Usage

A schema file's default import is its validator, compiled by ajv when the module is built. Nothing on it throws.

.validate()

The .validate() method returns the value, or every issue, each with its message, its path and the keyword that failed:

main.ts
import  from "./user.schema.jsonc";

const  = .();
if (.) {
  .(.);
  // for { name: "" }:
  // [{
  //   message: "must NOT have fewer than 1 characters",
  //   path: ["name"],
  //   keyword: "minLength",
  // }]
} else {
  .value;
value: {
    name: string;
    role?: "admin" | "member";
}
}

Defaults

A property's default is filled in where the value leaves it out:

settings.schema.jsonc
{
  "type": "object",
  "properties": {
    "theme": {
      "enum": ["light", "dark"],
      "default": "light"
    }
  },
  "additionalProperties": false
}
main.ts
import  from "./settings.schema.jsonc";

.({});
// { value: { theme: "light" } }

A default its own schema refuses is a type error:

settings.schema.jsonc
{
  "type": "object",
  "properties": {
    "theme": {
      "enum": ["light", "dark"],
      "default": "blue"
The default "blue" does not pass its own schema: must be equal to one of the allowed values. dotschema(4)
} } }

Transforms

The transform keyword changes a string before it's checked:

handle.schema.jsonc
{
  "type": "string",
  "pattern": "^[a-z_]+$",
  "transform": ["trim", "toLowerCase"]
}
main.ts
import  from "./handle.schema.jsonc";

.("  Ada_L ");
// { value: "ada_l" }

The transforms are trim, trimStart, trimEnd, toLowerCase, toUpperCase and toEnumCase, which gives an enum's own spelling:

role.schema.jsonc
{
  "enum": ["Admin", "Member"],
  "transform": ["toEnumCase"]
}
main.ts
import  from "./role.schema.jsonc";

.("admin");
// { value: "Admin" }

Unlisted keys

A key the schema doesn't list is dropped from the value:

visitor.schema.jsonc
{
  "type": "object",
  "properties": {
    "name": { "type": "string" }
  }
}
main.ts
import  from "./visitor.schema.jsonc";

.({ : "Ada", : true });
// { value: { name: "Ada" } }

An object whose additionalProperties says what its other keys may be keeps them:

labels.schema.jsonc
{
  "type": "object",
  "properties": {
    "name": { "type": "string" }
  },
  "additionalProperties": { "type": "string" }
}
main.ts
import  from "./labels.schema.jsonc";

.({ : "Ada", : "core" });
// { value: { name: "Ada", team: "core" } }

Copies

The value given is never changed, since .validate() copies what it fills in, transforms or drops:

main.ts
import  from "./visitor.schema.jsonc";

const  = { : "Ada", : true };
.();
// { value: { name: "Ada" } }
;
// { name: "Ada", admin: true }

Where nothing changes, the value is the one given:

main.ts
import  from "./visitor.schema.jsonc";

const  = { : "Ada" };
.();
// { value: input }, the same object

.is()

The .is() method is a type guard, which stops at the first failure:

main.ts
import  from "./user.schema.jsonc";

if (.()) {
  input;
const input: {
    name: string;
    role?: "admin" | "member";
}
}

.output

The .output type is the value .validate() returns:

main.ts
import  from "./user.schema.jsonc";

const  = .();
if (!.) {
  const : user. = .;
}

.input

The .input type is the value the schema accepts, which may leave out a property with a default:

main.ts
import  from "./settings.schema.jsonc";

const : settings. = {};
const loaded: settings. = {};
Property 'theme' is missing in type '{}' but required in type 'Settings'. ts(2741)

The .is() method narrows to it, since the value it checks is left as it was:

main.ts
import  from "./settings.schema.jsonc";

if (.()) {
  input;
const input: {
    theme?: "light" | "dark";
}
}

.pick()

The .pick() method gives the schema with only the properties named:

main.ts
import  from "./user.schema.jsonc";

const  = .("name");
.({ : "Ada", : "admin" });
// { issues: [{
//   message: "must NOT have additional properties",
//   path: ["role"],
//   keyword: "additionalProperties",
// }] }

.omit()

The .omit() method gives the schema without the properties named:

main.ts
import  from "./user.schema.jsonc";

const  = .("name");
if (.()) {
  input;
const input: {
    role?: "admin" | "member" | undefined;
}
}

.partial()

The .partial() method makes the properties named optional, or every property when none is named:

main.ts
import  from "./user.schema.jsonc";

.().({});
// { value: {} }

.required()

The .required() method makes the properties named required, or every property when none is named:

main.ts
import  from "./user.schema.jsonc";

.("role").({ : "Ada" });
// { issues: [{
//   message: "must have required property 'role'",
//   path: ["role"],
//   keyword: "required",
// }] }

.keyof()

The .keyof() method gives a schema of the property names:

main.ts
import  from "./user.schema.jsonc";

if (.().()) {
  input;
const input: "name" | "role"
}

A schema that is more than an object of properties, such as a oneOf, has none of these methods.

$defs

Each entry of $defs is a validator of its own, imported by its key:

place.schema.jsonc
{
  "type": "object",
  "properties": { "home": { "$ref": "#/$defs/address" } },
  "$defs": {
    "address": {
      "type": "object",
      "properties": { "city": { "type": "string" } },
      "required": ["city"],
      "additionalProperties": false
    }
  }
}
main.ts
import {  } from "./place.schema.jsonc";

if (.()) {
  input;
const input: {
    city: string;
}
}

~standard

The module is a Standard Schema, so a library that accepts one accepts it:

main.ts
import  from "./user.schema.jsonc";

// the same function as user.validate
["~standard"].();

It's a Standard JSON Schema too, which gives the schema as one document in draft-07 or 2020-12, with every file it refers to folded in:

main.ts
import  from "./team.schema.jsonc";

["~standard"]..({
  : "draft-2020-12",
});
// {
//   $schema:
//     "https://json-schema.org/draft/2020-12/schema",
//   type: "object",
//   properties: {
//     members: {
//       type: "array",
//       items: { $ref: "#/$defs/user" },
//     },
//   },
//   required: ["members"],
//   additionalProperties: false,
//   $defs: {
//     user: { type: "object", properties: { ... }, ... },
//   },
// }

Inference

Each schema file's type is written from its schema at the type check, as the type of the value .validate() gives.

Objects

An object's properties are its keys, optional unless required lists them:

Schema
{
  "type": "object",
  "properties": {
    "name": { "type": "string" },
    "age": { "type": "integer" }
  },
  "required": ["name"],
  "additionalProperties": false
}
Type
{
  name: string;
  age?: number;
}

The type is .output on the import:

main.ts
import  from "./profile.schema.jsonc";

const : profile. = { : "Ada", : 36 };
const : profile. = { : "Bob", age: "old" };
Type 'string' is not assignable to type 'number'. ts(2322)

A readOnly property is readonly:

Schema
{
  "type": "object",
  "properties": {
    "id": { "type": "string", "readOnly": true },
    "title": { "type": "string" }
  },
  "required": ["id", "title"],
  "additionalProperties": false
}
Type
{
  readonly id: string;
  title: string;
}

Null

A list of types is a union, null among them:

Schema
{
  "type": "object",
  "properties": {
    "phone": { "type": ["string", "null"] }
  },
  "required": ["phone"],
  "additionalProperties": false
}
Type
{
  phone: string | null;
}

Literals

An enum or a const is a literal type:

Schema
{
  "type": "object",
  "properties": {
    "status": { "enum": ["draft", "published"] },
    "version": { "const": 1 }
  },
  "required": ["status", "version"],
  "additionalProperties": false
}
Type
{
  status: "draft" | "published";
  version: 1;
}

Records

A schema in additionalProperties types every other key:

Schema
{
  "type": "object",
  "additionalProperties": { "type": "number" }
}
Type
{
  [key: string]: number;
}

A schema in patternProperties types the keys it matches:

Schema
{
  "type": "object",
  "patternProperties": {
    "^x-": { "type": "string" }
  },
  "additionalProperties": false
}
Type
{
  [key: string]: string;
}

Arrays

A schema in items types every item:

Schema
{
  "type": "array",
  "items": { "type": "string" },
  "uniqueItems": true
}
Type
string[]

Tuples

A prefixItems list is a tuple, each item required up to minItems:

Schema
{
  "$schema": "https://json-schema.org/draft/2020-12/schema",
  "type": "array",
  "prefixItems": [
    { "type": "number" },
    { "type": "number" }
  ],
  "minItems": 2,
  "items": false
}
Type
[number, number]

A schema in items beside it types the rest:

Schema
{
  "$schema": "https://json-schema.org/draft/2020-12/schema",
  "type": "array",
  "prefixItems": [{ "type": "string" }],
  "minItems": 1,
  "items": { "type": "boolean" }
}
Type
[string, ...boolean[]]

Unions

An anyOf or a oneOf is a union:

Schema
{
  "anyOf": [
    { "type": "string" },
    { "type": "integer" }
  ]
}
Type
string | number

A oneOf whose variants a const tells apart is a discriminated union:

Schema
{
  "oneOf": [
    {
      "type": "object",
      "properties": {
        "kind": { "const": "click" },
        "x": { "type": "number" }
      },
      "required": ["kind", "x"],
      "additionalProperties": false
    },
    {
      "type": "object",
      "properties": {
        "kind": { "const": "visit" },
        "url": { "type": "string" }
      },
      "required": ["kind", "url"],
      "additionalProperties": false
    }
  ]
}
Type
{
  kind: "click";
  x: number;
} | {
  kind: "visit";
  url: string;
}

Intersections

An allOf is an intersection:

Schema
{
  "allOf": [
    {
      "type": "object",
      "properties": { "name": { "type": "string" } },
      "required": ["name"]
    },
    {
      "type": "object",
      "properties": { "team": { "type": "string" } },
      "required": ["team"]
    }
  ]
}
Type
{
  name: string;
} & {
  team: string;
}

With unevaluatedProperties: false beside it, the intersection allows no other key:

Schema
{
  "$schema": "https://json-schema.org/draft/2020-12/schema",
  "allOf": [
    {
      "type": "object",
      "properties": { "name": { "type": "string" } },
      "required": ["name"]
    }
  ],
  "properties": { "reports": { "type": "integer" } },
  "unevaluatedProperties": false
}
Type
{
  reports?: number;
} & {
  name: string;
}

Conditionals

An if that tests a const makes then and else a union:

Schema
{
  "type": "object",
  "properties": { "method": { "enum": ["card", "bank"] } },
  "required": ["method"],
  "if": {
    "properties": { "method": { "const": "card" } }
  },
  "then": {
    "properties": { "card": { "type": "string" } },
    "required": ["card"]
  },
  "else": {
    "properties": { "iban": { "type": "string" } },
    "required": ["iban"]
  }
}
Type
{
  method: "card" | "bank";
} & (({ method: "card" } & {
  card: string;
}) | ({ method: "bank" } & {
  iban: string;
}))

Recursion

A $ref back into its own file is a type that refers to itself:

Schema
{
  "type": "object",
  "properties": {
    "name": { "type": "string" },
    "children": {
      "type": "array",
      "items": { "$ref": "#" }
    }
  },
  "required": ["name"],
  "additionalProperties": false
}
Type
interface Tree {
  name: string;
  children?: Tree[];
}

Two schemas of one file that refer to each other are two types that do:

Schema
{
  "type": "object",
  "properties": {
    "name": { "type": "string" },
    "pets": {
      "type": "array",
      "items": { "$ref": "#/$defs/pet" }
    }
  },
  "required": ["name"],
  "additionalProperties": false,
  "$defs": {
    "pet": {
      "type": "object",
      "properties": {
        "name": { "type": "string" },
        "owner": { "$ref": "#" }
      },
      "required": ["name"],
      "additionalProperties": false
    }
  }
}
Type
interface Person {
  name: string;
  pets?: Pet[];
}

interface Pet {
  name: string;
  owner?: Person;
}

References

A $ref can point to another schema file, by a path relative to this one:

{
  "type": "object",
  "properties": {
    "members": {
      "type": "array",
      "items": { "$ref": "./user.schema.jsonc" }
    }
  },
  "required": ["members"],
  "additionalProperties": false
}
{
  "type": "object",
  "properties": {
    "name": { "type": "string", "minLength": 1 },
    "role": { "enum": ["admin", "member"] }
  },
  "required": ["name"],
  "additionalProperties": false
}

The type imports the other file's, by its name:

main.ts
import  from "./team.schema.jsonc";

type Members = team.["members"];
type Members = User[]

A $ref with a fragment points into the other file, to a definition or an anchor:

{ "$ref": "./place.schema.jsonc#/$defs/address" }

Never

A false schema allows no value, and neither does { "not": {} }, so the type of each is never:

Schema
{
  "type": "object",
  "properties": {
    "email": { "type": "string" },
    "password": false,
    "admin": { "not": {} }
  },
  "required": ["email"]
}
Type
{
  email: string;
  password?: never;
  admin?: never;
}

Checks

A keyword no TypeScript type can express leaves the type as it is, and the validator checks it:

Schema
{
  "type": "string",
  "format": "email",
  "maxLength": 254
}
Type
string

Formats

Zod's string formats are checked as Zod checks them, jwt among them:

session.schema.jsonc
{
  "type": "object",
  "properties": {
    "token": { "type": "string", "format": "jwt" }
  }
}
main.ts
import  from "./session.schema.jsonc";

.({ : "not a token" });
// { issues: [{
//   message: "must match format \"jwt\"",
//   path: ["token"],
//   keyword: "format",
// }] }

JSON Schema's own formats, each passing every 2020-12 format test of the JSON Schema Test Suite:

FormatA value it accepts
date-time2026-10-27T09:30:00Z
date2026-10-27
time09:30:00+01:00
durationP1DT12H
emailada@example.com
idn-emailada@bücher.example
hostnameapi.example.com
idn-hostnamebücher.example
ipv4192.168.0.1
ipv62001:db8::1
urihttps://example.com/a?b=c
uri-reference../a?b=c
irihttps://bücher.example/straße
iri-reference/straße
uri-templatehttps://example.com/{user}
uuidf81d4fae-7dec-11d0-a765-00a0c91e6bf6
json-pointer/properties/name
relative-json-pointer1/name
regex^[a-z]+$

Zod's formats, in kebab case like JSON Schema's own, and by the names z.toJSONSchema gives them too (credit_card):

FormatA value it accepts
jwteyJhbGciOiJIUzI1NiJ9.e30.c2ln
credit-card4242424242424242
ibanGB82WEST12345698765432
base64aGVsbG8=
base64urlaGVsbG8
cidrv4192.168.0.0/24
cidrv62001:db8::/32
mac00:1a:2b:3c:4d:5e
e164+14155550123
emoji🦕
nanoidV1StGXR8_Z5jdHi6B-myT
cuidcjld2cjxh0000qzrmn831i7rn
cuid2tz4a98xxat96iws9zmbrgj3a
ulid01ARZ3NDEKTSV4RRFFQ69G5FAV
xid9m4e2mr0ui3e8a215n4g
ksuid0ujtsYcgvSTl8PAuAdqWYSMnLOv
hexdeadbeef
currency-codeUSD
lowercasedotschema
uppercaseDOTSCHEMA
md5-hex, md5-base64, md5-base64urlAn MD5 digest, in hex, base64 or base64url
sha1-hex, sha1-base64, sha1-base64urlA SHA-1 digest
sha256-hex, sha256-base64, sha256-base64urlA SHA-256 digest
sha384-hex, sha384-base64, sha384-base64urlA SHA-384 digest
sha512-hex, sha512-base64, sha512-base64urlA SHA-512 digest

OpenAPI's formats, and four more of ajv-formats':

FormatA value it accepts
int322147483647
int649007199254740991
float1.5
double1.5
byteaGVsbG8=
password, binaryAny string: they check nothing
iso-date-time2026-10-27T09:30:00
iso-time09:30:00
urlhttps://example.com
json-pointer-uri-fragment#/properties/name

A format no table names is not checked.

Unrecognized keywords

A keyword the schema's draft doesn't define is ignored, by the type and by the validator, so a schema written for another validator still compiles:

account.schema.jsonc
{
  "type": "object",
  "properties": {
    "id": {
      "type": "string",
      "x-internal": true,
      "tsType": "AccountId"
    }
  },
  "required": ["id"],
  "additionalProperties": false
}
main.ts
import  from "./account.schema.jsonc";

type Id = account.["id"];
type Id = string

Doc comments

A schema's doc comments are the type's, which an editor shows on hover.

Comments

A /** */ comment above a property is its doc comment:

Schema
{
  "type": "object",
  "properties": {
    /** The name the user signs in with. */
    "name": { "type": "string", "minLength": 1 },
    "role": { "enum": ["admin", "member"] }
  },
  "required": ["name"],
  "additionalProperties": false
}
Type
{
  /** The name the user signs in with. */
  name: string;
  role?: "admin" | "member";
}

Descriptions

A description is a doc comment too:

Schema
{
  "description": "An amount in cents.",
  "type": "integer",
  "minimum": 0
}
Type
/** An amount in cents. */
type Price = number;

Tags

The deprecated, default and examples keywords are tags of the doc comment:

Schema
{
  "type": "object",
  "properties": {
    "plan": {
      "enum": ["free", "pro"],
      "default": "free",
      "examples": ["pro"]
    },
    "legacyId": { "type": "string", "deprecated": true }
  },
  "additionalProperties": false
}
Type
{
  /**
   * @default "free"
   * @example "pro"
   */
  plan: "free" | "pro";
  /** @deprecated */
  legacyId?: string;
}

Errors

An invalid schema is a type error, at its place in the file:

team.schema.jsonc
{
  "type": "object",
  "properties": {
    "members": {
      "type": "array",
      "items": { "$ref": "./member.schema.jsonc" }
The $ref "./member.schema.jsonc" names a file that does not exist. dotschema(4)
} }, "required": ["members"] }

The type check prints it with its line and column:

Terminal
$ tsc --noEmit --runExternalCode
team.schema.jsonc:6:27 - error dotschema4: The $ref "./member.schema.jsonc" names a file that does not exist.

6       "items": { "$ref": "./member.schema.jsonc" }
                            ~~~~~~~~~~~~~~~~~~~~~


Found 1 error in team.schema.jsonc:6

The errorMessage keyword, ajv-errors', gives an issue a message of the schema's own:

signup.schema.jsonc
{
  "type": "object",
  "properties": {
    "age": {
      "type": "integer",
      "minimum": 13,
      "errorMessage": "must be 13 or older"
    }
  }
}

The issue keeps its path and the keyword that failed:

main.ts
import  from "./signup.schema.jsonc";

.({ : 9 });
// { issues: [{
//   message: "must be 13 or older",
//   path: ["age"],
//   keyword: "minimum",
// }] }

Reference

Keywords

dotschema reads every keyword of draft-06, draft-07, 2019-09 and 2020-12, and the validator checks each one that says something about a value. What each one does to the type:

KeywordThe type
typeIts type, and a list of types a union
enum, constA literal type
propertiesThe object's keys
requiredThe keys that are not optional
additionalPropertiesThe type of every other key, and false no other key
patternPropertiesThe type of the keys it matches
unevaluatedPropertiesThe type of every key no other keyword evaluates, and false no other key
itemsThe type of every item, or of the items after prefixItems, and a list of schemas a tuple
prefixItemsA tuple
additionalItemsThe items after a tuple's
minItemsThe tuple's items that are not optional
allOfAn intersection
anyOf, oneOfA union
if, then, elseA union of then and else, when if tests a const
$refThe type it refers to
$defs, definitionsA type of its own, exported by its key
$idA URI for a $ref to refer to, and the base of each $ref inside it
$anchor, $dynamicAnchorA name for a $ref to refer to
$dynamicRef, $recursiveRefThe type it refers to, where it resolves as a $ref would, and otherwise unknown
descriptionA doc comment
deprecatedA @deprecated tag, which an editor strikes through
defaultA @default tag, as JSON, and in .output a property that is not optional, since .validate() fills it in
examplesAn @example tag for each, as JSON
readOnlyA readonly property
notnever when it allows every value ({}, true), and otherwise nothing: the validator checks it
multipleOf, minimum, maximum, exclusiveMinimum, exclusiveMaximum, minLength, maxLength, pattern, format, maxItems, uniqueItems, contains, minContains, maxContains, unevaluatedItems, minProperties, maxProperties, propertyNames, dependentRequired, dependentSchemas, dependenciesNothing: the validator checks it
$schema, $vocabulary, $recursiveAnchor, $comment, title, writeOnly, contentEncoding, contentMediaType, contentSchemaNothing

Drafts

The $schema keyword picks the draft, 06, 07, 2019-09 or 2020-12, and a schema without it is draft-07:

{
  "$schema": "https://json-schema.org/draft/2020-12/schema",
  "type": "string"
}

FAQ

Yes. A schema file is JSONC, so it can hold comments and trailing commas:

user.schema.jsonc
{
  // who can sign in
  "type": "object",
  "properties": {
    "name": { "type": "string", "minLength": 1 },
    "role": { "enum": ["admin", "member"] },
  },
  "required": ["name"],
  "additionalProperties": false,
}

Draft-06, draft-07, 2019-09 and 2020-12. The $schema keyword picks one, and a schema without it is draft-07. A draft-04 or older schema is an error at the type check.

No. Each schema's module is built with its validator compiled, so it imports nothing, and a bundle carries the validator and no validator library. A bundled app needs dotschema only to build, as a devDependency.

The opening example's main.ts, bundled and minified by esbuild, has two inputs:

esbuild's analysis
  dist/main.mjs         7.2kb  100.0%
   ├ user.schema.jsonc  7.2kb   99.5%
   └ main.ts             35b     0.5%

A module carries the code of only the formats it uses, and esbuild leaves out a definition nothing imports.

Each of these is an error at the type check:

RefusedInstead
A $ref to a URL (https:, urn:)Save the schema as a .schema.jsonc file in the project, and $ref the file
A $dynamicRef to an anchor that two schema resources declare, when its own resource's root does notDeclare the anchor at the root of its resource, or write a $ref
In 2020-12, a contains that an unevaluatedItems sees through anyOf, oneOf, a conditional, dependentSchemas or a $refMove the contains beside the unevaluatedItems, or into its allOf
An $anchor at a file's root, or inside prefixItemsWrite "#", or the pointer, in the $ref
A draft-04 or draft-03 schemaDeclare draft-06 or a later draft in $schema
Released under the MIT License. Copyright © 2026 Colin McDonnell.

On this page

GitHub