JSON Schema
status: draft
An Ontology can be read from, and written as, a JSON Schema (draft 2020-12).
Every object schema becomes a Class, every entry of its properties becomes a Property, required becomes requires, and the keywords Atomic understands become the Class’s constraints.
This is not a JSON Schema validator and not a complete mapping. Import is strict: a construct Atomic cannot express is an error that names its JSON pointer, never silently dropped.
import { ensureOntology, ontologyFromJsonSchema, ontologyToJsonSchema } from '@tomic/lib';
const ontology = ontologyFromJsonSchema({
title: 'Shop',
'x-atomic-ontology': 'shop',
$defs: {
customer: {
type: 'object',
properties: { name: { type: 'string', minLength: 1 } },
required: ['name'],
},
invoice: {
type: 'object',
properties: {
amount: { type: 'number', minimum: 0 },
customer: { $ref: '#/$defs/customer' },
},
},
},
});
// Find or create the Ontology, its Properties and Classes under `drive`.
const { ontology: subject, classes, properties } = await ensureOntology(store, drive, ontology);
// And back out again.
const schema = await ontologyToJsonSchema(store, subject);
ontologyFromJsonSchema returns the input of ensureOntology: shortname, name, description and classes, each with its properties, requires, recommends and constraints.
ensureOntology is idempotent.
Running it twice changes nothing, and the same input gives the same atomic:prop: Property subjects.
Rust has the same import and ensure_ontology in atomic_lib::schema::json_schema: ontology_from_json_schema_str (keeps the order of the keys; ontology_from_json_schema takes a parsed serde_json::Value, whose keys are alphabetical) and ensure_ontology(store, parent, plan, agent).
Export is TypeScript only.
Both implementations run the cases in lib/tests/fixtures/json-schema-interop.json.
Mapping
| JSON Schema | Atomic |
|---|---|
Object schema in $defs | Class. The shortname is the key as a slug (LineItem becomes line-item), the name is the title, else the key |
Root schema with properties | Class, named after the title |
Root title, description | Ontology name, description |
Root x-atomic-ontology, else slugified title | Ontology shortname |
properties entry | Property, shortname is the key as a slug; title is its name, description its description |
required | Class requires. The other properties are recommends |
type: string | string |
type: string, format: date-time | timestamp |
type: string, format: date | date |
type: string, format: uri | atomicURL |
type: integer | integer |
type: number | float |
type: boolean | boolean |
$ref: "#/$defs/Name" | atomicURL plus a class constraint pointing at that Class |
type: array of $ref | resourceArray plus a class constraint |
type: array of { type: string, format: uri } | resourceArray |
Other type: array, type: object | json |
type: ["string", "null"] (one type plus "null") | the datatype of that type, plus a type constraint that keeps the null |
type: ["string", "integer"], or anyOf without a type | json, plus the type or anyOf constraint |
properties, required, additionalProperties, items, anyOf below a property | json, plus the same keywords as a nested constraint |
enum, const | enum constraint. Without a type the datatype follows the values. On an array, put it on items |
minimum, maximum, exclusiveMinimum, exclusiveMaximum | the same constraint keyword |
minLength, maxLength, pattern | the same constraint keyword |
minItems, maxItems | the same constraint keyword |
The constraints are stored on the Class, keyed by the property’s subject, not on the Property: Properties are immutable and only their shortname and datatype are part of their identity.
That also means two classes that both declare name as a string share one Property and can still constrain it differently.
$comment, examples, default, deprecated, readOnly, writeOnly and a root $id are annotations.
They are read and dropped.
On a class, additionalProperties may be a boolean and is dropped: Atomic classes are open. Inside a property it is kept (see Nested schemas).
What does not map
Each of these is an error on import, naming the keyword’s JSON pointer, for example /$defs/Invoice/properties/status/oneOf.
oneOf,allOf,not,if/then/else,dependentSchemas,patternProperties,propertyNames,unevaluated*,prefixItemsand the other keywords that Atomic has no equivalent for.anyOfon a class (it is only read below a property), and atypeof justnull.- A
$refthat is not a local#/$defs/Nameto an object schema, a$defsentry that is not an object schema, and any keyword next to$refother thantitle,descriptionandenum. - A
$ref(oroneOf,format, …) inside a nested schema, and tuple-formitems. Nested schemas are self-contained. - Nesting deeper than 16 levels.
enumorconston an array. It constrains the whole array in JSON Schema, but a class constraint applies to every item. Put it onitems.- A
formatother thandate-time,dateanduri, and anytypeother thanstring,integer,number,boolean,arrayandobject. - Boolean schemas, a
$schemaother than draft 2020-12, unknownx-keywords, and any other keyword. - A property name that cannot become a slug, two names that become the same shortname, and a shortname used with two datatypes in one Ontology (a Property is identified by shortname and datatype, and an Ontology cannot hold two with one shortname).
{ type: array, items: { type: string } } (items that are plain, with no minLength and the like) still imports as plain json.
Nested schemas
A property whose schema has properties, required, additionalProperties or anyOf, whose items have keywords beyond a type or a link, or whose type is an array, keeps that schema.
The datatype is json (or the type’s own datatype for a nullable string, integer, …), and the schema is stored whole in the Class’s constraint for the property, in the same vocabulary: type, enum, const, the numeric, string and array limits, properties, required, additionalProperties, items and anyOf.
See nested values for what is checked and when.
"pad": {
"type": "object",
"required": ["tune"],
"additionalProperties": false,
"properties": {
"tune": { "type": "number", "minimum": -24, "maximum": 24 },
"label": { "type": ["string", "null"], "maxLength": 8 }
}
}
Inside a nested schema title, description and the annotations are read and dropped; format and $ref are errors.
Export writes the schema back next to x-atomic-datatype: json, so import, ensureOntology and export give the same nested schema again.
x-atomic-* keywords
These carry what JSON Schema cannot say, so that an export imports again as the same Ontology.
| Keyword | Where | Meaning |
|---|---|---|
x-atomic-ontology | root | The Ontology’s shortname |
x-atomic-datatype | property | The exact Atomic datatype, when type and format are not enough: markdown, slug, uri, json, lorodoc, localizedText. Wins over the datatype that type implies |
x-atomic-class | property, or items of an array | The class constraint of a link, for a class outside the schema (a subject), or a class in it (a shortname) |
x-atomic-property | property, export only | The property’s atomic:prop: subject |
x-atomic-subject | root and classes, export only | The Ontology’s or Class’s subject |
x-atomic-property and x-atomic-subject are for readers.
Import ignores them: a Property’s identity follows from its Ontology, shortname and datatype, and is never taken on trust from a document.
Export
ontologyToJsonSchema(store, ontology) writes a draft 2020-12 schema with one $defs entry per Class and properties keyed by shortname.
A class constraint on a Class of the same Ontology becomes a $ref to its entry, any other becomes x-atomic-class.
Import followed by ensureOntology followed by export gives the input back, with these normalisations:
$defskeys are the class name when that is an identifier whose slug is the shortname (LineItem), else the shortname. Property keys are always shortnames:unitPricebecomesunit-price.titleis left out when it equals the key or shortname, anddescriptionwhen it equals the name.- A
jsonproperty is written as{ "x-atomic-datatype": "json" }, without itstype. constbecomes a one-itemenum, and anenumwithout atypegains the type of its values.- Annotations and
additionalPropertiesare gone,required: []is omitted, and$schema,x-atomic-ontology,x-atomic-subjectandx-atomic-propertyare added. - A property shared by two classes has one
titleanddescription: those of the first class that declared it.
An export is a fixed point: importing it and exporting again changes nothing.
Schemas from the command line
Write the schema in your own language, run one command, get a real ontology and a lockfile that pins its property IDs, then generate types.
The file is either a JSON Schema (it has $schema or $defs, or is type: object) or an OntologyInput JSON ({ "shortname": ..., "classes": [...] }).
Both command line tools do the same; the lockfile they write is byte for byte the same.
# Rust CLI (atomic-cli), uses the server and agent in its config
atomic-cli schema push shop.schema.json --parent <drive subject>
atomic-cli schema lock shop.schema.json --ontology <ontology subject> # offline
atomic-cli schema check shop.schema.json # offline
atomic-cli schema diff shop.schema.json # against the server
atomic-cli schema diff shop.schema.json --against old.schema.json # offline
# @tomic/cli, uses atomic.config.json (serverUrl, agentSecret)
npx ad-generate ontology push shop.schema.json --parent <drive subject> --types
npx ad-generate ontology lock shop.schema.json --ontology <ontology subject>
npx ad-generate ontology check shop.schema.json
pushrunsensureOntology: it creates the ontology under--parent, or finds it again, and brings classes in line. It then writes the lockfile.atomic-clitakes the parent from the config’s initial drive when--parentis left out.--types(@tomic/clionly) adds the ontology toatomic.config.jsonand generates the TypeScript types.lockneeds no server. Property IDs follow from the ontology subject, the shortname and the datatype, so the lockfile can be made as soon as you know the ontology’s subject. Class subjects are minted by the server, so they stay empty until apush. Locking again keeps the class subjects of an earlier push of the same ontology.checkfails when the lockfile no longer matches the schema. Changing a property’s shortname or datatype makes a new property with a new ID, andchecksays so. It also fails when the schema’s fingerprint differs from the one in the lockfile. Commit the lockfile and runcheckin CI.diff(atomic-clionly) compares the schema file with the ontology on the server that the lockfile points to, or with an older schema file when you pass--against. It prints every change grouped by level and exits with an error when one is breaking.pushrefuses to run when a property pinned in the existing lockfile changed or is no longer in the schema, so a changed datatype cannot quietly create a second property. A property the lockfile does not know yet is fine: that is what a push adds.--accept-changespushes anyway.atomic-clialso runsdiffagainst the server: it refuses breaking changes unless you pass--allow-breaking, and warns about tightening ones.--shortnameoverrides the ontology’s shortname,--lockfile <path>the lockfile’s location.
The lockfile is <file>.lock.json next to the schema file (shop.schema.json.lock.json). Its keys are sorted, it is indented with two spaces and ends with a newline:
{
"classes": {
"customer": "did:ad:..."
},
"fingerprint": "b3-57e73e03bc27bf401f96ad12f1c4ffa600d846a7b3eba7b0fc48c4d3fbb1159b",
"ontology": "did:ad:...",
"properties": {
"email": "atomic:prop:b4152651d32b39d8d89901323c9673775d2e43bb2ea452db01c8ad5d52432bc1",
"name": "atomic:prop:f04459be53adc3c4904126504db01a55e68a0932d3fd054fa8a5eb4b5bdd5d16"
}
}
atomic-cli finds the ontology of a re-run through the ontology in the lockfile, because it cannot query the server for it. Keep the lockfile, or the next push makes a second ontology. @tomic/cli finds it by shortname under --parent.
Changing a schema
The workflow: edit the schema file, run schema diff, run schema push, regenerate types.
diff sorts every change into one of three levels:
| Level | Meaning | Examples |
|---|---|---|
| compatible | Existing data stays valid and readers keep working. | A new optional property or class. A looser constraint: a lower minimum, a higher maximum, an enum value added, additionalProperties: false removed. Required to recommended. |
| tightening | The property IDs are the same, but existing data may now fail the class constraints. | A new required property. Recommended to required. A higher minimum or lower maximum (also exclusive*, minLength, maxLength, minItems, maxItems). An enum value removed. A const or pattern added. additionalProperties set to false. |
| breaking | Data written under the old schema is no longer read by the new one. | A property removed from a class, or a class removed. A property’s datatype or shortname changed: that is a new property ID, and the old values stay under the old ID. A changed classtype. |
A constraint that changed in a way that has no direction, such as a different pattern or anyOf, is reported as tightening and says the direction is unknown.
Names and descriptions are cosmetic: editing them is not a change.
Pushing a property whose datatype changed (atomic-cli, with --accept-changes --allow-breaking) makes the new property and keeps the old one. @tomic/cli refuses such a push. The new property carries the schema’s localId (schema:property:<shortname>); the old one gets a localId ending in :superseded:<its subject>, stays in the ontology’s property list, and keeps the values written under it.
The lockfile holds a fingerprint, b3- and a blake3 hash of the schema’s contract: the ontology, the property IDs, and per class what it requires and recommends, the classtype of its properties and its constraints.
Reordering classes or properties, or rewording a name or description, does not change it; any other edit does.
check compares it, so CI notices a schema that changed without a new lock or push.
push and lock write the new fingerprint. Lockfiles from before it existed have none and keep working.
In code: lockfileFromInput, schemaFingerprint, serializeLockfile, checkLockfile in @tomic/lib, and Lockfile in atomic_lib::schema::lockfile, and fingerprint and diff in atomic_lib::schema::compat.