@estype/core
v0.2.0
Published
ESType reference implementation: estype keyword validation, schema compilation, vocabulary meta-schema, definitions document, conversion to native values and reading ECSON or JSON with a schema
Maintainers
Readme
@estype/core
Reference implementation of ESType 0.1.0 (ECMAScript types for JSON Schema): validation of estype values, schema compilation (section 2), vocabulary meta-schema and definitions document (section 3), level Compiler; conversion to native values (section 4, subpath @estype/core/convert), level Converter; and reading ECSON or plain JSON with a schema (CONVERT_ECSON_WITH_SCHEMA, subpath @estype/core/read).
| Entry | Contents |
|---|---|
| @estype/core | compile, checkSchema, checkEstype, definitions document, meta-schemas, EstypeError |
| @estype/core/convert | convert, createConverter, convertValue: estype fields to native values, from the ECSON form or the plain JSON form |
| @estype/core/read | parse, decode, createReader: ECSON (or plain JSON) text or tree to host values, with native values in the estype fields |
import { compile } from '@estype/core';
import { convert } from '@estype/core/convert';
import { parse } from '@estype/core/read';Up to 0.1.x, the two subpaths were the packages @estype/convert and @ecson/schema (in the ECSON repository); both are deprecated on npm.
Runtime-independent TypeScript (standard APIs only), tested on Node 24, Bun and Deno. ESM only, Node >= 24.
Conformance
import { conformance } from '@estype/core';
conformance.level; // 'Compiler'
conformance.types; // the 22 ES types of table 2.1
conformance.applicationTypes; // true: namespaced types, such as 'acme.money'@estype/core/convert exports its own conformance, level Converter (see Conversion).
Installation
npm install @estype/core @ecson/core
# or: bun add @estype/core @ecson/core@ecson/core (^0.2.0) is a peer dependency, used by @estype/core/convert and @estype/core/read: the conversion recognizes EcsonError and UnknownTag by instanceof and takes the codec of the application, so both must come from the same copy. The main entry does not import it.
The npm package contains only dist/ (JS and .d.ts), this README and the license. To develop in this repository, tools that understand the @estype/source condition (for example bun --conditions=@estype/source, node --conditions=@estype/source or customConditions in tsconfig.json) read the TypeScript directly, without a build. The condition points to src/, which is not published, so it only works inside the monorepo.
API
Compile
import { compile } from '@estype/core';
compile({ title: 'Created at', type: 'string', format: 'date-time', estype: 'date' });
// {
// title: 'Created at',
// estype: 'date',
// oneOf: [
// { type: 'object', required: ['$date'], properties: { $date: true }, additionalProperties: false },
// { allOf: [
// { type: 'string', format: 'date-time' },
// { not: { type: 'object', required: ['$date'], properties: { $date: true }, additionalProperties: false } }
// ] }
// ]
// }
compile({ estype: 'bigint' }); // plain branch: allOf of the default { type: 'integer' } and the exclusion of the ECSON form
compile({ estype: 'bigint', type: 'integer', minimum: 0 }); // the declared schema replaces the default
compile(compile(schema)); // same as compile(schema) (COMPILE_IDEMPOTENT)
compile({ estype: 'acme.money' }); // EstypeError COMPILE_NO_DEFAULT: declare the plain formThe compiled schema is ordinary JSON Schema 2020-12: any validator accepts the ECSON form and the declared plain form without knowing ESType. The plain branch is an allOf of the declared schema (or the default) with { not: <ECSON branch> } (COMPILE_PLAIN_BRANCH), so the ECSON form matches exactly one branch of the oneOf, even with a declared schema that has no type. compile never changes its input.
Keywords that stay outside the oneOf: estype, $id, $anchor, $dynamicAnchor, $defs, $comment, title, description, default, deprecated, readOnly, writeOnly, examples, $schema and $vocabulary (COMPILE_OUTSIDE_KEYWORDS).
A subschema with an already compiled estype (COMPILE_DETECT) is left as it is: a oneOf of exactly two branches, the ECSON branch of T and an allOf of a schema with { not: <ECSON branch of T> }, and no keywords other than the ones that stay outside. Any other oneOf belongs to the author and goes to the plain branch.
Compilation moves the declared schema inside the oneOf, so a $ref with a JSON Pointer into a subschema with estype (for example #/properties/a/items) no longer resolves; use $defs or $anchor as the target, which stay outside (note in section 2).
Validate estype values and schemas
import { checkEstype, checkSchema, isEstype } from '@estype/core';
isEstype('date'); // true
isEstype('acme.money'); // true: namespaced application type
checkEstype('$date'); // EstypeError ESTYPE_KEYWORD (without the "$")
checkEstype('class'); // EstypeError ESTYPE_EXCLUDED
checkSchema({ estype: 'date', $ref: 'https://lingodata.dev/estype/defs/0.1#/$defs/date' }); // ESTYPE_SUBSCHEMA
checkSchema({ allOf: [{ estype: 'date' }, { estype: 'bigint' }] }); // ESTYPE_CONFLICT
checkSchema({ anyOf: [{ estype: 'date' }, { estype: 'bigint' }] }); // ok: alternative branches
checkSchema(schema, { schemas: [other] }); // follows $ref to other documents (by $id), without checking themcompile runs the same checkSchema and fails for an invalid estype (COMPILE_INVALID_ESTYPE): a value that does not name an ES type, an excluded type, estype next to a $ref whose target has estype, and two different estype values that apply to the same value (ESTYPE_CONFLICT: the subschema itself and the ones reached through allOf and $ref, repeatedly; the branches of anyOf, oneOf and not are left out). A $ref to the definitions document counts as the estype of the entry.
Definitions document and meta-schemas
import { definitions, definitionRef, vocabularyMetaSchema, dialectMetaSchema } from '@estype/core';
definitions.$id; // 'https://lingodata.dev/estype/defs/0.1' (provisional)
definitions.$defs.date; // compile({ estype: 'date' })
definitionRef('date'); // 'https://lingodata.dev/estype/defs/0.1#/$defs/date'
vocabularyMetaSchema.$id; // 'https://lingodata.dev/estype/meta/0.1' (provisional)
dialectMetaSchema.$id; // 'https://lingodata.dev/estype/schema/0.1': 2020-12 + ESType, to use in $schema
dialectMetaSchema.$vocabulary['https://lingodata.dev/estype/vocab/0.1']; // false (ESTYPE_DIALECT_VOCABULARY)Both meta-schemas declare the vocabulary with false in $vocabulary: a validator that does not know ESType still processes schemas of the dialect and treats estype as an annotation.
Errors
Every failure is an EstypeError with code (rule code: ESTYPE_KEYWORD, ESTYPE_EXCLUDED, ESTYPE_SUBSCHEMA, ESTYPE_CONFLICT, COMPILE_NO_DEFAULT, CONVERT_FAIL; or implementation codes: SCHEMA_INVALID, REF_UNRESOLVED, CONVERT_UNSUPPORTED), category (malformed or unsupported), path (keys and indexes down to the subschema, or down to the value in conversion) and pointer (the path as a JSON Pointer, CONVERT_PATH_POINTER).
Constants and utilities
SPEC_VERSION, VOCABULARY_URI, META_SCHEMA_URI, DIALECT_URI, DEFINITIONS_ID, DEFAULT_PLAIN_SCHEMAS, ES_TYPES, EXCLUDED_TYPES, OUTSIDE_KEYWORDS; ecsonBranch(T), plainBranch(T, plain), isCompiledEstype(S), definitionType(uri); $ref index and resolution (createIndex, indexDocument, resolveRef), used by conversion.
Conversion (@estype/core/convert)
Conversion of fields with estype to native values (ESType 0.1.0, section 4), from the ECSON form and the plain JSON form, with @ecson/core.
import { conformance } from '@estype/core/convert';
conformance.level; // 'Converter'
conformance.types; // date, instant, plaindate, zoneddatetime, plaindatetime, plaintime,
// plainyearmonth, plainmonthday, duration, bigint, number, regexp,
// symbol, set, map, bytes, rel, errorEcsonError, EstypeError and the types Schema, SchemaObject and Path are re-exported.
All ES types compile. rel and error convert with the default codec of @ecson/core (its References and Error type sets are on by default since 0.2.0). binary, oid, numberDecimal, timestamp (BSON, @ecson/bson) and application types convert when the ECSON codec passed in options.codec knows the type; otherwise the conversion fails with CONVERT_UNSUPPORTED. In runtimes without native Temporal (Node 24, Bun), the Temporal types become OpaqueTemporal from @ecson/core.
convert(schema, value, options?)
import { convert } from '@estype/core/convert';
const schema = { properties: { total: { estype: 'bigint' }, at: { estype: 'date' } } };
convert(schema, { total: 42, at: '2026-11-13T10:00:00.000Z' });
// { total: 42n, at: Date }
convert(schema, { total: { $bigint: '42' }, at: { $date: '2026-11-13T10:00:00.000Z' } });
// { total: 42n, at: Date }
convert(schema, { total: { $bigint: '42' }, at: '2026-11-13T10:00:00.000Z' });
// { total: 42n, at: Date }: the form is decided per field (CONVERT_FORM_PER_FIELD)
convert(schema, { total: 'x' });
// EstypeError CONVERT_FAIL, path ['total']
convert(schema, { at: { $date: 'yesterday' } });
// EcsonError TYPEDEF_VALIDATE, path ['at'] (CONVERT_MALFORMED_ECSON)schemamay be compiled or not (estypeis kept in both).valueis a value already read as JSON (for example, fromJSON.parse). Only the values under a subschema withestype(or with$refto an entry of the definitions document,DEFS_EQUIVALENT) change; the rest stays as it is, including keys with$. The input is never changed.- The form is decided per value, only by the value's own form: a document may mix fields in the ECSON form and in the plain JSON form (
CONVERT_FORM_PER_FIELD). - ECSON form (
{ "$bigint": "42" }, a single key equal to the type's tag): decoded by the codec. A malformed ECSON form is an ECSON error, notCONVERT_FAIL(CONVERT_MALFORMED_ECSON). - Nested subschemas (
CONVERT_NESTED): the declared schema applies to the members after the conversion, whether the value comes in the ECSON form, in the plain JSON form or already native. ASetis seen as the array of its members and aMapas the array of[key, value]pairs (its plain JSON form), soitemsof asetanditems: { prefixItems: [<key>, <value>] }of amapconvert the members. In the ECSON form, the members are read first by ECSON ($$keys unescaped, typed values decoded) and the error path of a member includes the tag:{ "days": { "$set": ["x"] } }fails at/days/$set/0. TheSetorMapis rebuilt only when a member changes; other types have no members to convert. - Plain JSON form: converted to the tag's serialized form and decoded by the codec, which validates (ECSON's
TYPEDEF_VALIDATE). Besides ECSON's plain JSON form, the serialized form from inside the tag (CONVERT_ACCEPTED_FORMS):bigintas a digit string,dateas an epoch integer (and expanded year),numberas"NaN"/"Infinity"/"-Infinity"/"-0",regexpas{ source, flags },bytesas{ type, data },binaryas{ base64, subType }. The reading is the inverse of ECSON's plain JSON form (CONVERT_PLAIN_READ): a value already in the serialized form stays as it is, and a form that ECSON rejects givesCONVERT_FAIL. Forms with loss (CONVERT_PLAIN_LOSS):symbolbecomes a new symbol with the description, outside the global registry,bytesin Base64 becomesUint8Arrayandbinaryin Base64 uses subtype00. nullis never converted and staysnull(CONVERT_NULL), including as asetmember; it is valid when the declared schema accepts it. Values that are not JSON (already native, for example read by an ECSON decoder, as@estype/core/readdoes) pass unchanged when they are native to the type, that is, when the codec encodes them with the type's tag; a native of another type (aDatein aninstantfield, abigintin adatefield) fails withCONVERT_FAIL.$ref(CONVERT_REF): a value whose subschema reaches a subschema withestypethrough$ref(local, by$anchor, chained or in another document ofoptions.schemas) is converted as by that subschema; a$refto the definitions document followsDEFS_EQUIVALENT.- Errors:
EstypeErrorwithcodeCONVERT_FAILand the value'spath(keys and indices;pointergives the same path as a JSON Pointer, RFC 6901, the form thatCONVERT_PATH_POINTERrecommends);rulecarries the ECSON rule when the failure comes from ECSON's validation (for exampleTYPE_BIGINT). Malformed ECSON form:EcsonError(from the consumer's@ecson/corecopy, re-exported by the package) with the ECSON code (TYPEDEF_VALIDATE), the value'spath(the path inside the form, whichCONVERT_MALFORMED_DETAILallows attaching, is in thepathof the error incause, for example['$set', 1, '$bigint']) and ECSON'srule; this error has nopointer(usetoPointer(error.path); a gap ofCONVERT_PATH_POINTER,docs/spec-issues.mditem 16).CONVERT_UNSUPPORTED(CONFORMANCE_UNSUPPORTED) when the codec does not know the value's type, including a codec withunknownTags: 'error': the value never passes without conversion.REF_UNRESOLVEDwhen a$refpoints to an unknown document. - Invalid schema: the schema is checked when the converter is created, as in compilation (
checkSchema,COMPILE_INVALID_ESTYPE). An invalidestype, or two differentestypevalues that apply to the same value (ESTYPE_CONFLICT, for exampleallOf: [{ estype: 'date' }, { estype: 'bigint' }]), throwsEstypeErrorbefore any value, with the subschema's path.
Options:
| Option | Use |
|---|---|
| codec | ECSON codec with the types to convert (default: the default codec of @ecson/core: core, References and Error type sets). For example createCodec({ types: [bson, moneyType] }). |
| schemas | Other documents (with $id) that $ref may point to. The definitions document is always available. |
| load(uri) | Called for documents that are not in the index; returns the schema or undefined. |
| validate(schema, value, location) | Decides anyOf, oneOf, if/then/else and contains. location is the subschema's { document, pointer }. Returning undefined falls back to the approximate check. |
Without validate, the conditional applicators use an approximate check (type, const, enum, required, properties, additionalProperties: false, items, prefixItems, allOf, anyOf, oneOf, $ref and ECSON form), enough for nullable fields, unions discriminated by const and simple if. The oneOf produced by compilation is decided by the value's form. The @estype/ajv plugin passes Ajv as validate.
createConverter(schema, options?)
Checks and indexes the schema once and returns (value) => converted value, to convert several values with the same schema. The check (ESTYPE_KEYWORD, ESTYPE_EXCLUDED, ESTYPE_SUBSCHEMA, ESTYPE_CONFLICT) follows $ref into the documents of options.schemas, but not into those that options.load would bring in later.
convertValue(type, value, options?)
Converts a single value to an ES type (ECSON or plain form), without a schema. Options: codec, path (for the error).
import { convertValue } from '@estype/core/convert';
convertValue('date', '2026-11-13T10:00:00.000Z'); // Date
convertValue('bigint', { $bigint: '9007199254740993' }); // 9007199254740993n
convertValue('set', [1, 2]); // Set { 1, 2 }Also exported: isEcsonForm(value, type), isJsonValue(value), toPointer(path), defaultCodec, CORE_CONVERT_TYPES.
Reading ECSON or JSON with a schema (@estype/core/read)
Reading ECSON or plain JSON with a JSON Schema that uses the ESType vocabulary. Every field whose subschema has estype becomes the native value of its ES type, whether it arrives in the ECSON form ({ "$bigint": "42" }) or in the plain JSON form (42): rule CONVERT_ECSON_WITH_SCHEMA (section 4). The conversion is the one of @estype/core/convert, wired to the ECSON codec. Until 0.1.x this was the package @ecson/schema.
import { parse, decode } from '@estype/core/read';
const schema = {
properties: {
total: { estype: 'bigint' },
createdAt: { estype: 'date' },
tags: { estype: 'set', items: { estype: 'date' } },
},
};
parse('{ "total": 42, "createdAt": "2026-11-27T10:00:00.000Z" }', { schema });
// { total: 42n, createdAt: Date }
parse('{ "total": { "$bigint": "42" }, "createdAt": { "$date": "2026-11-27T10:00:00.000Z" } }', { schema });
// the same
decode({ tags: ['2026-11-27T10:00:00.000Z', { $date: '2026-11-28T10:00:00.000Z' }] }, { schema });
// { tags: Set { Date, Date } }: a plain set may mix plain and ECSON membersparse(text, options) reads text; decode(tree, options) reads a JSON value already parsed (for example a member of a larger JSON document). createReader(options) prepares one schema for many documents (its $ref targets are indexed once) and returns { parse, decode }.
The schema may be the original one or the output of compile: both read alike. $ref to the ESType definitions document (https://lingodata.dev/estype/defs/0.1#/$defs/<type>) works without registering it.
Options
schema(required): JSON Schema 2020-12 withestype.codec: an ECSON codec fromcreateCodecof@ecson/core, with the type sets (@ecson/bson), application types, classes and options the document needs. The same codec decodes the document and converts the fields. Default: the default codec of@ecson/core(core, References and Error type sets).input:'ecson'(default) or'json'(see below).json5(inparse): read the text as JSON5 (JSON5_INPUT).schemas,load,validate: passed to the conversion (@estype/core/convert) (other schema documents for$ref, a loader for missing ones, and a validator for conditional applicators; without it,anyOf,oneOf,ifandcontainsare decided by an approximate check).
import { createCodec } from '@ecson/core';
import { bson } from '@ecson/bson';
import { parse } from '@estype/core/read';
const codec = createCodec({ types: [bson] });
parse('{ "id": "507f1f77bcf86cd799439011" }', { schema: { properties: { id: { estype: 'oid' } } }, codec });
// { id: ObjectId }ECSON input and plain JSON input
With input: 'ecson' (default) the text is ECSON. The codec decodes the whole document first: typed values in any position become native values, unknown tags are preserved, and escaped keys are unescaped ("$$price" is the key $price, so properties: { "$price": ... } applies). Then the schema is applied to the host value:
- a field with
estypeT that came in the ECSON form of T is already native and is kept; - a field in the plain JSON form of T is converted; typed values inside a plain form (members of a plain
set, entries of a plainmap, thecauseof a plainerror) are native already and are kept inside the converted value; - nested subschemas apply to the members after conversion, in either form (ESType
CONVERT_NESTED):itemsof asetconverts the members of{ "$set": [...] }and of a plain array, anditems: { prefixItems: [<key>, <value>] }of amapconverts its[key, value]pairs; - anything else in a field with
estypefails withCONVERT_FAIL, including the ECSON form of another type ({ "$date": ... }in abigintfield).
With input: 'json' the text is plain JSON (ECSON section 5.3, PLAIN_FORM_READ): only the fields with estype are converted, from the plain JSON form or from the ECSON form, and everything else stays JSON, keys with $ included. Use it for documents written as plain JSON, where { "$meta": ... } is an ordinary member.
In both modes the form of each field with estype is decided on its own, so one document may mix them (ESType CONVERT_FORM_PER_FIELD): { "createdAt": { "$date": "2026-11-27T10:00:00.000Z" }, "paidAt": "2026-11-27T11:00:00.000Z" } gives two Date values.
A plain JSON document without keys that start with $ reads the same in both modes.
Errors
- When the reader is created (
createReader, and soparseanddecodebefore reading), a schema that ESType rejects fails withEstypeError, before any document:ESTYPE_KEYWORD(anestypethat names no ES type),ESTYPE_CONFLICT(two differentestypevalues apply to the same value),ESTYPE_EXCLUDED(estype: "class"),SCHEMA_INVALID(a subschema that is not an object or a boolean).pathis the path in the schema (['properties', 'a']). EstypeErrorwithcode:CONVERT_FAIL(categorymalformed): a value cannot be converted to the ES type of its field;pathis the path of the value (['orders', 1, 'at']), andpointerthe same path as a JSON Pointer (/orders/1/at). For a member of a set or map (CONVERT_NESTED): in the plain form, the index in the array (['tags', 0]) in both modes; in the ECSON form,['tags', 0]in ECSON input (the document is decoded first, so the path is the index in theSet) and['tags', '$set', 0]in JSON input (the raw form is converted).CONVERT_UNSUPPORTED(categoryunsupported): the codec does not know the type (for exampleoidwithout@ecson/bson, or an application type without its definition;relanderrorare in every codec of@ecson/coreunless turned off withtypeSets), also when the codec fails on unknown tags (unknownTags: 'error', ECSONUNKNOWN_ERROR_MODE).REF_UNRESOLVED: a$refthat cannot be resolved; pass the document inschemasor aloadfunction.
EcsonError(from@ecson/core): the text or tree is not valid ECSON, for exampleJSON_SYNTAX, orTYPEDEF_VALIDATEfor a malformed typed value ({ "$bigint": "x" }). LikeEstypeError, it haspathandpointer, the same path as a JSON Pointer (ESTypeCONVERT_PATH_POINTER).- In a field with
estype(ESTypeCONVERT_MALFORMED_ECSON), in both modes:TYPEDEF_VALIDATEwith the path of the field (['total']), not a path inside the typed value;ruleis the ECSON rule (TYPE_BIGINT) andcausethe error of the ECSON reader. In ECSON input the document is decoded before the schema applies, so the reader fails first; then the conversion runs on the raw tree to find the field, only on this error path. - Elsewhere (ECSON input only; in JSON input it is an ordinary member): the error of the ECSON reader, with its path (
['meta', 'x', '$date']). - Limit: with escaped keys (
"$$total") on the way to the field, the raw tree does not match the schema, and the error keeps the ECSON path.
- In a field with
null in a field with estype is kept (nullable fields, ESType CONVERT_NULL). Besides the plain JSON form, each field accepts the serialized form from inside the tag, such as a bigint as a string of digits or a date as an integer epoch (ESType CONVERT_ACCEPTED_FORMS).
Conformance
@estype/core/read makes an ECSON implementation meet ESType CONVERT_ECSON_WITH_SCHEMA (and CONVERT_PLAIN_SHOULD, CONVERT_FAIL, CONVERT_FORM_PER_FIELD, CONVERT_MALFORMED_ECSON) for the types its codec knows: the core, References and Error types with the default codec of @ecson/core; BSON and application types with a codec that has their set or definition. Vectors: conformance/read/ (bun run conformance:read).
License
Apache 2.0. Copyright 2026 Gustavo Gondim. See LICENSE.
