@alexify/metaschema 2.0.0 → 3.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +443 -1
- package/README.md +124 -12
- package/SECURITY.md +27 -8
- package/index.d.ts +537 -84
- package/package.json +25 -6
- package/src/codec.js +544 -0
- package/src/compile/code.js +92 -0
- package/src/compile/emit.js +540 -0
- package/src/compile/index.d.ts +38 -0
- package/src/compile/index.js +176 -0
- package/src/context.js +68 -19
- package/src/errors.js +19 -1
- package/src/generators/fromjsonschema.js +520 -0
- package/src/generators/index.d.ts +46 -0
- package/src/generators/index.js +95 -0
- package/src/generators/jsonschema.js +535 -0
- package/src/generators/typescript.js +237 -0
- package/src/index.js +0 -2
- package/src/issues.js +117 -22
- package/src/kinds.js +9 -12
- package/src/lint.js +31 -14
- package/src/locales/en.js +10 -2
- package/src/locales/uk.js +7 -2
- package/src/metadata.js +41 -44
- package/src/metautil.js +8 -1
- package/src/model/data.js +122 -0
- package/src/model/diff.js +438 -0
- package/src/model/index.d.ts +56 -0
- package/src/model/index.js +42 -0
- package/src/model/merge.js +254 -0
- package/src/model/pattern.js +322 -0
- package/src/model/restore.js +226 -0
- package/src/model/sample.js +394 -0
- package/src/model.js +18 -15
- package/src/preprocessor.js +9 -11
- package/src/prototypes/abstract.js +14 -1
- package/src/prototypes/collections.js +20 -3
- package/src/prototypes/reference.js +17 -3
- package/src/prototypes/scalars.js +1 -3
- package/src/prototypes/schema.js +15 -2
- package/src/prototypes/tuple.js +14 -9
- package/src/prototypes/union.js +57 -18
- package/src/result.js +5 -14
- package/src/rules.js +55 -26
- package/src/runtime/browser.js +2 -2
- package/src/runtime/node.js +4 -2
- package/src/schema.js +129 -101
- package/src/snapshot.js +111 -0
- package/src/struct.js +80 -23
- package/src/types.js +5 -11
- package/src/util.js +39 -0
package/CHANGELOG.md
CHANGED
|
@@ -7,6 +7,446 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|
|
7
7
|
|
|
8
8
|
## [Unreleased]
|
|
9
9
|
|
|
10
|
+
## [3.1.0] - 2026-10-11
|
|
11
|
+
|
|
12
|
+
3.1 makes the model data. `model.toJSON()` writes a snapshot of a model, the contract other
|
|
13
|
+
programs read it through, and the new `@alexify/metaschema/model` subpath builds on it:
|
|
14
|
+
`fromJSON` restores a model from a snapshot, `diff` and `compatibility` compare two versions by
|
|
15
|
+
the rules of schema evolution, `sample` draws a value a schema accepts, and `merge` unifies two
|
|
16
|
+
schemas. A field may carry `aliases`, read by `check` and renamed by `parse`, and
|
|
17
|
+
`fromJSONSchema` of the generators reads a JSON Schema document back into a definition. Nothing
|
|
18
|
+
breaks: the core, the generators and the compile subpath keep their 3.0 behaviour, with the
|
|
19
|
+
fixes listed below.
|
|
20
|
+
|
|
21
|
+
### Added
|
|
22
|
+
|
|
23
|
+
- **The snapshot.** `model.toJSON()` (what `JSON.stringify(model)` writes) is the model as
|
|
24
|
+
data, format 1: the entities in dependency order with their metadata, fields (each
|
|
25
|
+
`{ type, required, ...sorted keys }`), indexes and relations, and the types the entities use;
|
|
26
|
+
a function is `{ $function: true }` wherever it stands, a bigint and a Date are tagged, a
|
|
27
|
+
RegExp is its source. `tests/fixtures/snapshot.json` pins the format.
|
|
28
|
+
- **`aliases` on a field.** `check` reads a field from an alias the value carries when it has
|
|
29
|
+
nothing under the field's own key, reporting under the key it found the value under; `parse`
|
|
30
|
+
fills no default over it and writes the value under the field's own key, in the place of the
|
|
31
|
+
alias, and only after a check that read an alias (a value without one comes back as it is,
|
|
32
|
+
the same reference); `serialize` never reads an alias. The JIT emits the same lookup. An
|
|
33
|
+
alias is a key of the struct (not a field, a calculated field or another alias:
|
|
34
|
+
`ERR_INVALID_DEFINITION`); the generators and `Infer` name the field's own key only.
|
|
35
|
+
- **`@alexify/metaschema/model`**, a subpath of 9.5 KB min+gzip on top of the core:
|
|
36
|
+
`fromJSON(snapshot, options)` restores a model from its snapshot (placeholders for the
|
|
37
|
+
functions, listed by path in `model.placeholders`; the real custom types through
|
|
38
|
+
`options.types`; an isolated registry unless `options.registry` says otherwise, and a shared
|
|
39
|
+
one refuses a placeholder type). A snapshot is untrusted input: what does not read (a
|
|
40
|
+
bigint, a date, a pattern, an entity without a kind, a nesting deeper than 128 levels, an
|
|
41
|
+
index named like a field, a `custom` key that would override the kind metadata) is
|
|
42
|
+
`ERR_INVALID_SNAPSHOT` with the entity and the field, and a key of the snapshot is defined,
|
|
43
|
+
never assigned, so `__proto__` is a field. `diff(prev, next)` lists the changes between two
|
|
44
|
+
models or snapshots as `{ kind, op, entity, name, from, to, detail }` (a field renamed
|
|
45
|
+
through its aliases is `renamed`, a removed `deprecated` field carries `detail.deprecated`);
|
|
46
|
+
`compatibility(changes)` classifies them as `full`, `backward`, `forward` or `none` by the
|
|
47
|
+
rules of the Confluent Schema Registry (the table is in the Model evolution guide), and
|
|
48
|
+
`compatibilityOf(change)` is the class of one change;
|
|
49
|
+
`sample(schema, { seed, locale, references, maxDepth })` is a value the schema accepts, the
|
|
50
|
+
same for a seed, drawn from the definition and verified field by field (a pattern from the
|
|
51
|
+
subset of alternatives, groups, classes, escapes, control escapes and quantifiers, the
|
|
52
|
+
letters of `.` and `\p{L}` those of the locale of the call; a custom type through
|
|
53
|
+
`metadata.sample`; a union draws another branch when one cannot be satisfied; `maxDepth` 0
|
|
54
|
+
to 32), with `ERR_UNSATISFIABLE`, `ERR_SAMPLE_PATTERN` and `ERR_SAMPLE_TYPE` for what cannot
|
|
55
|
+
be drawn, each naming the seed (`error.seed`): a repetition over 10000, a pattern whose
|
|
56
|
+
minimal length exceeds `length.max` (found before a string is built), groups nested deeper
|
|
57
|
+
than 64; `merge(a, b, { name, metadata })` is the schema both schemas describe,
|
|
58
|
+
by unification, with `ERR_MERGE_CONFLICT` for what no value can satisfy, located like a
|
|
59
|
+
definition error (`error.field`, the message ending `in "Name.address.city"`; an alias that
|
|
60
|
+
is a field of the other schema is a conflict too); `register()` installs `Model.fromJSON`,
|
|
61
|
+
`Model.diff`, `Model.compatibility`, `Model.compatibilityOf`, `Schema.merge` and
|
|
62
|
+
`schema.sample`.
|
|
63
|
+
- **`fromJSONSchema(document, { name, as, references, unsupported })`** of the generators
|
|
64
|
+
subpath: a definition (or a Schema) from the subset of JSON Schema a validation schema is
|
|
65
|
+
made of, the other direction of `toJSONSchema` (types and type lists, properties and
|
|
66
|
+
required, enum and const, items, tuples and uniqueItems, anyOf/oneOf with OpenAPI's
|
|
67
|
+
discriminator, `$ref` into the definitions, the rules, null, the annotations, the root's
|
|
68
|
+
`additionalProperties` as the unknown-keys policy); a keyword outside the subset is
|
|
69
|
+
`ERR_UNSUPPORTED_SCHEMA` with its place as a JSON pointer, and so are a `$ref` that is not
|
|
70
|
+
`#` or `#/…` over own keys, a bad escape in one, a nesting deeper than 128 levels, a
|
|
71
|
+
pattern that does not compile under the `u` flag and an unknown name in a type list;
|
|
72
|
+
`onUnsupported(reason, pointer)` tells what `unsupported: 'ignore'` dropped. A `$ref` is
|
|
73
|
+
converted once per pointer and shared where it is inlined, so a diamond of definitions is
|
|
74
|
+
linear. `register()` adds `Schema.fromJSONSchema`. The subpath is 7.1 KB on top of the core
|
|
75
|
+
now.
|
|
76
|
+
- The types `ModelSnapshot`, `EntitySnapshot`, `FieldSnapshot`, `FieldsSnapshot`,
|
|
77
|
+
`FunctionSnapshot`, `TypeSnapshot`, `RestoreOptions`, `RestoredModel`, `SchemaChange`,
|
|
78
|
+
`ChangeKind`, `ChangeOp`, `Compatibility`, `SampleOptions`, `SampleHook`, `TypeMetadata`
|
|
79
|
+
(the `sample` hook of a custom type), `MergeOptions` and `FromJSONSchemaOptions`;
|
|
80
|
+
`aliases` on `FieldType`; the codes `ERR_INVALID_SNAPSHOT`, `ERR_UNSATISFIABLE`,
|
|
81
|
+
`ERR_SAMPLE_PATTERN`, `ERR_SAMPLE_TYPE`, `ERR_MERGE_CONFLICT` and `ERR_UNSUPPORTED_SCHEMA`.
|
|
82
|
+
- A `dead-aliases` warning for `aliases` anywhere but on a field of a struct (an element, a
|
|
83
|
+
branch, a schema of one type), where nothing reads them.
|
|
84
|
+
|
|
85
|
+
### Changed
|
|
86
|
+
|
|
87
|
+
- Two fields of a struct with one key (`{ a: 'string', 'a?': 'number' }`, or a calculated
|
|
88
|
+
field and a field of one name) are `ERR_INVALID_DEFINITION` ("is a field or an alias
|
|
89
|
+
already"); the second silently replaced the first before.
|
|
90
|
+
- `aliases` is a key the struct reads: `{ type: 'string', aliases: 'old' }` is
|
|
91
|
+
`ERR_INVALID_DEFINITION` where it was an `unknown-option` warning, and a custom type does not
|
|
92
|
+
see an option of that name.
|
|
93
|
+
- `JSON.stringify(model)` writes the snapshot; it wrote the `Model` instance's own enumerable
|
|
94
|
+
properties before.
|
|
95
|
+
- A function of a subpath given something other than what it takes (`toJSONSchema`,
|
|
96
|
+
`toTypeScript`, `compile`, `sample`, `merge`, `compatibility`, `fromJSONSchema`) throws a
|
|
97
|
+
`TypeError` with `code: 'ERR_INVALID_TARGET'` (the `RuntimeErrorCode` of `ERR_ASYNC_VALIDATOR`);
|
|
98
|
+
the message is the same, and `fromJSONSchema` of a non-object document, which was
|
|
99
|
+
`ERR_INVALID_OPTIONS`, is that error too.
|
|
100
|
+
|
|
101
|
+
### Fixed
|
|
102
|
+
|
|
103
|
+
- A `many` reference re-parsed from its built field (a projection copies its parent's fields
|
|
104
|
+
that way, and the long form `{ type: 'Address', many: 'Address' }` reads the same) came back
|
|
105
|
+
with both ends and validated as a single reference.
|
|
106
|
+
- The name of a named tuple element (`[{ x: 'number' }]`) was an `unknown-option` warning.
|
|
107
|
+
- A `validate` given on a `schema` field (`{ type: 'schema', schema, validate }`) was replaced
|
|
108
|
+
by the one of the definition it holds; the field's own wins now, as its `parse` and
|
|
109
|
+
`serialize` did.
|
|
110
|
+
|
|
111
|
+
### Tooling
|
|
112
|
+
|
|
113
|
+
- `pnpm size` has a fourth row and gate, `--max-gzip-model`; the CI gates are 17.5 KB per
|
|
114
|
+
core entry, 7.5 KB for `./generators`, 4.25 KB for `./compile` and 10 KB for `./model` (the
|
|
115
|
+
core, the compile and the model gates moved from 17 KB, 4 KB and 8.5 KB during the review
|
|
116
|
+
of 3.1: the first two had 14 and 15 bytes of headroom left, the third did not hold the
|
|
117
|
+
hardening of the subpath).
|
|
118
|
+
- The bench has a sparse-struct scenario and two alias scenarios of `parse`, and
|
|
119
|
+
`bench/baseline.json` is re-saved after the review.
|
|
120
|
+
- The coverage job runs under `shell: bash`, so the c8 thresholds fail CI through the pipe
|
|
121
|
+
into `tee`; before, the job took the status of `tee`.
|
|
122
|
+
- New suites: `snapshot`, `aliases`, `evolution`, `sample`, `fromjsonschema` and `merge`, on
|
|
123
|
+
all three backends; the bundle test bundles the model subpath with the core.
|
|
124
|
+
- New guides: Model evolution (`diff`, `compatibility`, `aliases`, `deprecated`, the rules
|
|
125
|
+
table), Sample values; the snapshot and `fromJSON` in Domain Models, the import in JSON
|
|
126
|
+
Schema, merging in Schema Syntax.
|
|
127
|
+
|
|
128
|
+
## [3.0.0] - 2026-10-11
|
|
129
|
+
|
|
130
|
+
3.0 moves the generators of JSON Schema and TypeScript from the core entry to the
|
|
131
|
+
`@alexify/metaschema/generators` subpath, which takes `model.dts`, `schema.toInterface()`
|
|
132
|
+
and `saveTypes` with them (a breaking change, hence the major), and `schema['~standard'].validate`
|
|
133
|
+
is `parse` rather than `check` (a second one). The rest is additive: `parse`, `serialize`,
|
|
134
|
+
`checkAsync` and `parseAsync` in the core, the JIT backend of the new
|
|
135
|
+
`@alexify/metaschema/compile` subpath, the JSON Schema export with its four targets and the
|
|
136
|
+
strict profile, Standard JSON Schema, JSDoc and named types in the generated TypeScript, and a
|
|
137
|
+
fix in `check`.
|
|
138
|
+
|
|
139
|
+
### Upgrading from 2.0
|
|
140
|
+
|
|
141
|
+
The same guide with before-and-after examples is
|
|
142
|
+
[Migrating from 2.x](https://metaschema.vercel.app/guide/migrating-from-2).
|
|
143
|
+
|
|
144
|
+
- **`schema['~standard'].validate` is `parse`.** A consumer of Standard Schema (tRPC, TanStack
|
|
145
|
+
Form, Hono, …) gets the value `parse` gives: the `default` of a missing key filled in and the
|
|
146
|
+
`parse` function of every field applied, with the schema's own `unknown` metadata as the
|
|
147
|
+
policy for other keys (`libraryOptions` are the options of `parse`, `unknown: 'strip'`
|
|
148
|
+
included). A schema without defaults and decoders returns the value it was given, the same
|
|
149
|
+
reference, as 2.0 did. A schema with an `async function` among its validators, decoders and
|
|
150
|
+
custom `checkType`s (in it or in an entity it references) returns a promise of the result,
|
|
151
|
+
which the specification allows and its consumers await; the typings of `validate` say
|
|
152
|
+
`StandardResult<T> | Promise<StandardResult<T>>` now, with `types.input` as `Infer<D>` and
|
|
153
|
+
`types.output` as `InferOutput<D>`.
|
|
154
|
+
- **`Infer<D>` leaves out a key with a `default`.** A field with a `default` is an optional
|
|
155
|
+
property on the input side, because `parse` fills it; `InferOutput<D>` has it present. The
|
|
156
|
+
generated TypeScript interfaces are unchanged (every field present), so a value typed from the
|
|
157
|
+
dts is still assignable to `Infer`, and the output type to the dts.
|
|
158
|
+
- **`CheckContext` has `async`, `source`, `scratch`, `depth` and `maxDepth` slots** (`async`
|
|
159
|
+
is `null` in a synchronous check), and `issues.exception` takes the key of the field, for
|
|
160
|
+
code that builds on the internals.
|
|
161
|
+
- **A graph nested deeper than 128 embedded records is invalid.** `check`, `parse` and
|
|
162
|
+
`serialize({ check: true })` record a `depth` issue at the first record past `maxDepth`
|
|
163
|
+
(128 by default, an option of the call) instead of overflowing the stack; a program that
|
|
164
|
+
validates deeper graphs passes a larger `maxDepth`.
|
|
165
|
+
- **A struct rejects an array** (see Fixed), and **the synchronous `check` and `parse` throw
|
|
166
|
+
`ERR_ASYNC_VALIDATOR`** for a validator, a custom `checkType` or a decoder that returns a
|
|
167
|
+
promise: use `checkAsync` and `parseAsync`.
|
|
168
|
+
- **Definitions that could never work are errors now:** an `object` or `map` without a key type
|
|
169
|
+
of `'string'` or `'number'` (`ERR_INVALID_DEFINITION`), a `default` on the discriminator field
|
|
170
|
+
of a union (`ERR_INVALID_UNION`). `maxErrors` must be a whole number (or `Infinity`).
|
|
171
|
+
- **The `validate`, `parse` and `serialize` of a nested struct are not keys of the value.** A
|
|
172
|
+
value carrying `inner: { parse: ... }` was accepted under `unknown: 'reject'` and kept under
|
|
173
|
+
`strip`; the key is `unexpected`, as it is at the root.
|
|
174
|
+
- **`compile()` reports what stopped the JIT:** `{ accelerated: false, error }` where a check
|
|
175
|
+
could not be generated (the `ERR_JIT_BUILD` error, the generator's error as its `cause`), and
|
|
176
|
+
`compile(target, { jit: false })` puts the closures back.
|
|
177
|
+
- **The generators moved to `@alexify/metaschema/generators`.** `model.dts`,
|
|
178
|
+
`schema.toInterface()` and `saveTypes` are no longer in the core entry: the subpath exports
|
|
179
|
+
`toTypeScript(target, options)` (a `Schema` or a `Model`), `saveTypes(outputFile, target,
|
|
180
|
+
options)` and `toJSONSchema(target, options)`, and its `register()` installs the methods on
|
|
181
|
+
the classes (`model.dts`, `model.toTypeScript`, `schema.toInterface`, `schema.toJSONSchema`,
|
|
182
|
+
`model.toJSONSchema`) once per process. Replace `model.dts` with `toTypeScript(model)` or call
|
|
183
|
+
`register()` at startup; import `saveTypes` from the subpath. The core entry no longer carries
|
|
184
|
+
the generators (4.5 KB min+gzip in the subpath) nor any Node runtime; the browser entry is the
|
|
185
|
+
same.
|
|
186
|
+
|
|
187
|
+
### Added
|
|
188
|
+
|
|
189
|
+
- **`parse`.** `schema.parse(value, options)` validates a value and builds the value of the
|
|
190
|
+
program from it: `{ valid, value, issues }`, where `issues` is always an array and `value`
|
|
191
|
+
is `undefined` for an invalid value. The pipeline is the `default` of every missing or
|
|
192
|
+
`undefined` struct key (a value, or a function called on every parse, at any depth: nested
|
|
193
|
+
structs, the elements of collections, the records a reference embeds), the check of the
|
|
194
|
+
schema (whichever backend installed it: the passes validate nothing, so a compiled schema
|
|
195
|
+
parses through its generated code), `unknown: 'strip'` (a third policy, of `parse` alone:
|
|
196
|
+
the keys the schema does not have are accepted and left out of every struct of the output),
|
|
197
|
+
the `parse` function of every field on its validated value, from the parts of a value up to
|
|
198
|
+
the value (elements before the collection, the fields of a nested struct before its own
|
|
199
|
+
`parse`, an embedded record through its entity), and the schema's own `parse` last. A
|
|
200
|
+
decoder's exception is an `exception` issue at the field and makes the result invalid.
|
|
201
|
+
`default` is applied by `parse` only: `check` still reports a missing required key. The value
|
|
202
|
+
given is never written to, and it is the output itself when nothing was applied; otherwise
|
|
203
|
+
the containers on the way to a change are new and the rest is shared. The options are those
|
|
204
|
+
of `check`, with `unknown` also `'strip'`.
|
|
205
|
+
- **`serialize`.** `schema.serialize(value, options)` is the other direction: the schema's own
|
|
206
|
+
`serialize`, then the `serialize` function of every field from the value down to its parts,
|
|
207
|
+
through the same collections, tuples, nested structs and embedded references; `{ value }`
|
|
208
|
+
without validation, or `{ valid, value, issues }` with `options.check`, the other options
|
|
209
|
+
being those of `check`. `format` stays collected and uncalled. `parse` and `serialize` are
|
|
210
|
+
known keys of every field for the lint, and a non-function one is `ERR_INVALID_DEFINITION`.
|
|
211
|
+
- **`checkAsync` and `parseAsync`.** A `validate` function (of a field or of the schema), a
|
|
212
|
+
custom type's `checkType` and a decoder may return a promise. The walk of the value is
|
|
213
|
+
synchronous; a validator that returns a promise is set aside with its path, and every
|
|
214
|
+
validator met after it with it, so that a validator still runs only when nothing under it
|
|
215
|
+
failed; after the walk they are settled one after the other, in field order, each recording
|
|
216
|
+
at its path, and `maxErrors` stops the list. The synchronous `check` and `parse` throw a
|
|
217
|
+
`TypeError` with the new code `ERR_ASYNC_VALIDATOR` for such a promise (`RuntimeErrorCode`
|
|
218
|
+
in the typings). Both backends go through the same helper, so the JIT needed no change.
|
|
219
|
+
- **Typings for parse.** `InferOutput<D, E>` is the type of the value `parse` gives: `Infer`
|
|
220
|
+
with the result of every `parse` function (`Awaited`) in place of the value it decodes and
|
|
221
|
+
every defaulted key present (`null` stays where the key was optional); `ParseResult<T>`,
|
|
222
|
+
`ParseOptions`, `SerializeOptions`, `Serialized<T>` and `SerializeChecked<T>` type the new
|
|
223
|
+
methods, `FieldType` declares `parse`, `serialize` and `default`, and `Validator` and
|
|
224
|
+
`TypeEntry.checkType` may return a promise.
|
|
225
|
+
- **The JIT backend.** `compile(target, options)` of the new `@alexify/metaschema/compile`
|
|
226
|
+
subpath replaces the check of a schema, or of every entity of a model, with one straight-line
|
|
227
|
+
function generated from the plan the closures walk and built with `new Function`; it records
|
|
228
|
+
exactly the issues the closures record (codes, paths, params, order and messages) and returns
|
|
229
|
+
`{ accelerated }`. `register(options)` compiles every schema built from then on (a later call
|
|
230
|
+
replaces the options, `{ jit: false }` stops it; a schema built before is not touched), and
|
|
231
|
+
`canEval()` says whether the environment allows code generation from strings. The `jit`
|
|
232
|
+
option is `'auto'` (the default: where `new Function` is not allowed, under a Content
|
|
233
|
+
Security Policy, in Cloudflare Workers or under `node --disallow-code-generation-from-strings`,
|
|
234
|
+
the closures stay silently), `true` (throw `SchemaDefinitionError` with the new code
|
|
235
|
+
`ERR_NO_EVAL` instead; `register` throws at the call) or `false` (never generate code).
|
|
236
|
+
Nothing happens on import. The generated source holds identifiers, numbers, booleans and JSON
|
|
237
|
+
strings only; regular expressions, enum sets, validate functions, custom types, references and
|
|
238
|
+
the issue constructors reach it through a scope. Structs, every scalar with its rules, enums,
|
|
239
|
+
collections, tuples, unions, `nullable` and optional fields and the limits of a check are
|
|
240
|
+
inlined; a reference, a custom type's `checkType` and a `validate` function are the same
|
|
241
|
+
calls as before. Measured on Node 24 (`bench/baseline.json`): 30.0 M checks a second of a flat
|
|
242
|
+
struct (10.4 M on the closures), 17.4 M of a nested one (2.5 M), 5.6 M for a flat value with
|
|
243
|
+
four problems (3.4 M), 24–33 M on the moltar scenarios (4–7 M). The subpath is 3.9 KB min+gzip
|
|
244
|
+
on top of the core and
|
|
245
|
+
has typings of its own (`CompileOptions`, `Compiled`); the core gains one internal slot,
|
|
246
|
+
`Schema[Symbol.for('alexify.metaschema.hook')]`, that `register()` fills.
|
|
247
|
+
- **JSON Schema export.** `toJSONSchema(schema, options)` of the generators subpath renders the
|
|
248
|
+
rules of `check` as a JSON Schema document and `toJSONSchema(model, options)` every entity of
|
|
249
|
+
a model as a definition (`$defs`, `definitions` or `components.schemas` by target), or the
|
|
250
|
+
document of `options.root`. Targets: `draft-2020-12` (the default), `draft-07`, `openapi-3.0`
|
|
251
|
+
(a schema object: `nullable`, no type lists, `oneOf` with `discriminator` for a discriminated
|
|
252
|
+
union) and `mongodb` (a `$jsonSchema` validator: `bsonType`, references inlined, no `$ref`,
|
|
253
|
+
`format` or `default`, `_id` allowed at the root). A struct is a closed object with its
|
|
254
|
+
required keys (open when the root says `unknown: 'ignore'`), an optional or nullable field
|
|
255
|
+
accepts `null`, `length`/`pattern`/`min`/`max` are the matching keywords, a required
|
|
256
|
+
`object` or `map` has `minProperties: 1` as `check` requires, a tuple is `prefixItems` (an
|
|
257
|
+
`items` list before 2020-12), a union is `anyOf`, an enum of one value is `const`, and a
|
|
258
|
+
reference follows the kind of its target (an id for a stored kind, a `$ref` for a memory
|
|
259
|
+
kind; `references: 'kind' | 'embed' | 'id'` as in `check`). `title`, `description`,
|
|
260
|
+
`default`, `examples` and `deprecated` pass through where the dialect has them; a custom type
|
|
261
|
+
renders through `metadata.jsonSchema` (`metadata.bson` for mongodb) or the built-in it
|
|
262
|
+
aliases. `io: 'input'` (the default) describes the JSON a value is parsed from (a `date` is a
|
|
263
|
+
`date-time` string, a `set` an array of unique items, a `map` an object); `io: 'output'`
|
|
264
|
+
describes the value itself, where those three have no form. What has no form in the target
|
|
265
|
+
(`bigint`, a tuple for openapi-3.0, a cycle for mongodb, a custom type without metadata)
|
|
266
|
+
throws `SchemaDefinitionError` with the new code `ERR_UNREPRESENTABLE`, located in the
|
|
267
|
+
schema and the field, or renders as `{}` with `unrepresentable: 'any'`. `validate`
|
|
268
|
+
functions, custom `checkType`s, calculated fields, indexes and kind metadata are not
|
|
269
|
+
exported.
|
|
270
|
+
- **The strict profile.** `toJSONSchema(schema, { profile: 'strict' })` renders the dialect of
|
|
271
|
+
LLM structured outputs (OpenAI, Anthropic): an object at the root, every property listed as
|
|
272
|
+
required (an optional one as `['T', 'null']`, an optional `$ref` as an `anyOf` with null),
|
|
273
|
+
`additionalProperties: false` on every object, and the structure only: `minLength`,
|
|
274
|
+
`maxLength`, `pattern`, `minimum`, `maximum`, `minItems`, `maxItems`, `uniqueItems` and
|
|
275
|
+
`minProperties` are left out, and a value without a type (`any`, `json`, an `object` or
|
|
276
|
+
`map` of free keys) has no form. For the `draft-2020-12` and `draft-07` targets.
|
|
277
|
+
- **Standard JSON Schema.** After `register()` of the generators, `schema['~standard'].jsonSchema`
|
|
278
|
+
is the converter of the specification: `input(options)` and `output(options)` are
|
|
279
|
+
`toJSONSchema` for the `target` the consumer names (`draft-2020-12`, `draft-07` or
|
|
280
|
+
`openapi-3.0`; anything else throws, as the specification asks) with `libraryOptions` as the
|
|
281
|
+
other options. A `Schema<D>` is a `StandardJSONSchemaV1<Infer<D>, Infer<D>>`; the typings
|
|
282
|
+
add `StandardConverter` and `StandardJSONSchemaOptions`.
|
|
283
|
+
- **JSDoc and named types in the generated TypeScript.** The `description` of a field is the
|
|
284
|
+
JSDoc of its member and `deprecated: true` adds `@deprecated`. `toTypeScript(target, { named:
|
|
285
|
+
true })` gives every enum a `type` and every nested struct an `interface`, named after the
|
|
286
|
+
entity and the field (`type UserRole`, `interface UserName`) and rendered before the
|
|
287
|
+
interface that uses them; `saveTypes(file, target, options)` passes the options on.
|
|
288
|
+
`InterfaceOptions` is the type of the options.
|
|
289
|
+
- **`maxDepth`.** An option of `check`, `checkAsync`, `parse`, `parseAsync` and `serialize`
|
|
290
|
+
(an integer of at least 1, 128 by default): how deep a value may nest through embedded
|
|
291
|
+
references. A record past that depth is a `depth` issue (`{ max }` as params, `is nested
|
|
292
|
+
deeper than 128 references`, rendered by both locales) instead of a `RangeError` from the
|
|
293
|
+
stack; the passes of parse leave the record as it is for the check to report. The type
|
|
294
|
+
`IssueCode` has `'depth'`.
|
|
295
|
+
- **`compile()` returns `{ accelerated, error }` and `register()` takes `onFallback`.** In the
|
|
296
|
+
default mode a check that could not be generated keeps its closures and the reason comes
|
|
297
|
+
back as `error` (a `SchemaDefinitionError` with the new code `ERR_JIT_BUILD`, the
|
|
298
|
+
generator's error as its `cause`), or reaches `register({ onFallback(schema, error) })` for
|
|
299
|
+
every such schema; with `jit: true` that error is thrown and nothing of a model is installed.
|
|
300
|
+
`compile(target, { jit: false })` restores the closures a schema was built with. The
|
|
301
|
+
generated source is strict and ends with a `sourceURL` named after the schema, so a stack
|
|
302
|
+
trace through a compiled check names it.
|
|
303
|
+
- **Typings** for the generators: `JSONSchema` (`Record<string, unknown>`), `JSONSchemaOptions`,
|
|
304
|
+
`ModelJSONSchemaOptions`, `JSONSchemaTarget`, `InterfaceOptions` in the core,
|
|
305
|
+
`src/generators/index.d.ts` for the subpath, and `ERR_UNREPRESENTABLE` in
|
|
306
|
+
`DefinitionErrorCode`. The methods `register()` installs are declared on `Schema` and `Model`.
|
|
307
|
+
|
|
308
|
+
### Changed
|
|
309
|
+
|
|
310
|
+
- **The core entry is 16.1 KB min+gzip** (2.0 was 12.6 KB: the TypeScript generator left it,
|
|
311
|
+
3.9 KB; the array check of a struct and the hook of the compile subpath joined it; `parse`,
|
|
312
|
+
`serialize` and the async calls added 3.1 KB, in the core rather than a subpath because
|
|
313
|
+
`~standard.validate` is `parse` and every schema is a Standard Schema; the fixes of the
|
|
314
|
+
review below, `maxDepth` and the lazy cycle set added about 1 KB and the loops, the shared
|
|
315
|
+
tables and the trims gave 0.3 KB back), the generators subpath adds 4.5 KB and the compile
|
|
316
|
+
subpath 3.9 KB. CI gates at 17 KB per core entry, 5 KB for the generators and 4 KB for the
|
|
317
|
+
compile subpath (`pnpm size --max-gzip 17 --max-gzip-generators 5 --max-gzip-compile 4`).
|
|
318
|
+
- **Fewer allocations on the hot path.** The root value joins the cycle set only when a record
|
|
319
|
+
is actually embedded (a check of an entity with references in the storage view allocated a
|
|
320
|
+
`Set` each time); a validator or a custom `checkType` is called without a closure made per
|
|
321
|
+
call, and the params of a failing `checkType` are built only when it fails; the pass over an
|
|
322
|
+
`object` field iterates its own keys instead of allocating `Object.entries`; the trial that
|
|
323
|
+
picks the branch of a plain union in `parse` uses one scratch context per parse instead of
|
|
324
|
+
one per union value; the length of a value is measured by what the value is (an object with a
|
|
325
|
+
`size` key is an object) and an object's keys are counted without listing them; the
|
|
326
|
+
discriminator table of a union is built once and shared by the check, the passes and the JIT.
|
|
327
|
+
- **Loops instead of `forEach`, `map` and spreads** wherever a pass could be saved or a closure
|
|
328
|
+
or a list per call avoided, and null-prototype dictionaries wherever a definition key or a
|
|
329
|
+
code a validator makes up is looked up (the schema's `indexes` and `options`, the metadata of
|
|
330
|
+
a type, the rule formatters, the parsers, the locale tables).
|
|
331
|
+
|
|
332
|
+
### Fixed
|
|
333
|
+
|
|
334
|
+
- **A struct rejects an array.** `check` accepted `[]` for a struct whose fields are all
|
|
335
|
+
optional (`typeof [] === 'object'`, no keys to look at) and reported the missing keys of
|
|
336
|
+
any other struct; an array is now `not of expected type: object`, whatever the fields.
|
|
337
|
+
Found by the differential test against ajv.
|
|
338
|
+
- **A failed branch of a plain union left its deferred validators behind** in `checkAsync` and
|
|
339
|
+
`parseAsync`, so a value that matched a later branch was reported invalid by the validators
|
|
340
|
+
of a branch it did not match. Both backends drop them with the issues of the branch. A plain
|
|
341
|
+
union picks the first branch whose synchronous checks pass; an async validator of that branch
|
|
342
|
+
settles after the walk and may still fail the value, but no further branch is tried: use a
|
|
343
|
+
`discriminator` where branches carry async validators.
|
|
344
|
+
- **A thenable in the data was taken for a promise.** Under `unknown: 'strip'`, and at a field
|
|
345
|
+
with a decoder, any value with a `then` function was awaited: a synchronous `parse` returned a
|
|
346
|
+
`Promise` as the valid value, and `parseAsync` ran the `then` of the data, which could replace
|
|
347
|
+
the value. Only a `Promise` instance made by a decoder in an async parse is pending now, and
|
|
348
|
+
the promises of the passes resolve to a box around the value, so a field called `then` is
|
|
349
|
+
never adopted.
|
|
350
|
+
- **Unhandled rejections.** The synchronous `check` and `parse` threw `ERR_ASYNC_VALIDATOR` and
|
|
351
|
+
dropped the promise; `settle` stopped at `maxErrors` before the promises it held; the trial of
|
|
352
|
+
a union branch in `parseAsync` set validators aside it never ran. Every such promise is
|
|
353
|
+
observed before it is left behind.
|
|
354
|
+
- **Async decoders respect `maxErrors`**, and the trial of a plain union branch in `parse` runs
|
|
355
|
+
under the path and root of the parse (a validator met in it saw `"n"` instead of
|
|
356
|
+
`"Doc.u.n"`), tolerates an async validator (`serialize` threw `ERR_ASYNC_VALIDATOR` for one
|
|
357
|
+
inside a union with a serializer) and uses one context per parse.
|
|
358
|
+
- **`compile(target, { jit: false })` returned `{ accelerated: false }` and left the generated
|
|
359
|
+
check installed;** it restores the closures. With `jit: true` a model is compiled all or
|
|
360
|
+
nothing. An `object` or `map` without a valid key type made the JIT fail with a raw
|
|
361
|
+
`TypeError` at construction under `register({ jit: true })`; the definition is rejected when
|
|
362
|
+
the field is built.
|
|
363
|
+
- **The `validate`, `parse` and `serialize` of a nested struct were keys a value could carry**
|
|
364
|
+
(see Upgrading). A calculated field declared as `'x?'` is stored under `x`.
|
|
365
|
+
- **`toJSONSchema`** lost a field called `__proto__`, wrote the segments of the `definitions`
|
|
366
|
+
pointer onto the document the same way, left the name of an entity unescaped inside a `$ref`
|
|
367
|
+
(RFC 6901: `A/b~c` is `#/$defs/A~1b~0c`), looked renderers up on a plain object (a custom type
|
|
368
|
+
called `constructor` resolved to `Object`), pushed the null branch into the `anyOf` of a custom
|
|
369
|
+
type's metadata on every export, and copied `deprecated: 'a note'` through (a boolean in every
|
|
370
|
+
dialect). The `definitions` pointer merges into an object already on its path.
|
|
371
|
+
- **`toTypeScript`** wrote keys that are no identifiers bare (`a-b: string;`), let `*/` in a
|
|
372
|
+
`description` close the JSDoc, dropped the note of a `deprecated` string (it is
|
|
373
|
+
`@deprecated <note>` now), gave two nested types one name (`aB` and `AB` both `TAB`; the
|
|
374
|
+
second is `TAB2`, and a nested type never takes the name of an entity of the model),
|
|
375
|
+
stringified `NaN` and BigInt enum values through JSON (`number` and `10n` now), rendered an
|
|
376
|
+
entity or an embedded reference whose name is no identifier (`ERR_UNREPRESENTABLE` now), and
|
|
377
|
+
declared the alias of a one-type schema twice under `named`. `saveTypes` rejects instead of
|
|
378
|
+
throwing, as its typing says.
|
|
379
|
+
- **An object with a `size` or `length` key was measured as a collection** by the `length`
|
|
380
|
+
rule; a value is measured by what it is.
|
|
381
|
+
- **A validator's own code could break the rendering:** a code such as `'constructor'` or
|
|
382
|
+
`'__proto__'` is rendered with the validator's message; what a validator throws or returns is
|
|
383
|
+
rendered whatever it is (a symbol, an object without a prototype).
|
|
384
|
+
- **An index or a top-level option called like a method broke construction** (`indexes` and
|
|
385
|
+
`options` were instances with an `extract` method); they are dictionaries. The metadata of a
|
|
386
|
+
type is a dictionary too, so `__proto__` is a key of it.
|
|
387
|
+
- **`schema['~standard']` kept the first answer of `hasAsync`** after `attach` or `detach`; the
|
|
388
|
+
props are rebuilt. **`schema.validate(value, path)`** ran the schema-level function without
|
|
389
|
+
the schema as `this` and turned a promise into `"[object Promise]"`; it throws
|
|
390
|
+
`ERR_ASYNC_VALIDATOR` for a promise. **`maxErrors: 1.5`** gave two issues and a bigint broke
|
|
391
|
+
the option's error message.
|
|
392
|
+
|
|
393
|
+
### Removed
|
|
394
|
+
|
|
395
|
+
- `model.dts`, `schema.toInterface()` and `saveTypes` from the core entry: they are in
|
|
396
|
+
`@alexify/metaschema/generators` (see Upgrading).
|
|
397
|
+
|
|
398
|
+
### Tooling
|
|
399
|
+
|
|
400
|
+
- `forEach` and `reduce` are lint errors everywhere oxlint runs (`no-restricted-properties`),
|
|
401
|
+
`no-var` and `object-shorthand` errors rather than warnings; lint and format cover `index.js`
|
|
402
|
+
and `browser.js`; `check:dts` compiles the typings of the generators and compile subpaths;
|
|
403
|
+
`ci-success` fails on a skipped job; `pnpm bench --compare --fail-under=<percent>` exits
|
|
404
|
+
non-zero on a scenario slower than the baseline by more than that.
|
|
405
|
+
- New tests: the async union, thenable data, the unhandled rejections (through an
|
|
406
|
+
`unhandledRejection` listener), the union trial's path, `maxDepth` over a 3000-level chain on
|
|
407
|
+
both backends, `jit: false` and the atomic model compile, the compile `error`/`onFallback`,
|
|
408
|
+
the strict source, the key type of collections, the nested codec keys, the generator
|
|
409
|
+
hardening cases (`__proto__` fields, odd `definitions` pointers, escaped `$ref`s, shared
|
|
410
|
+
metadata, quoted keys, JSDoc, name collisions), `lengthOf` on objects with `size` keys,
|
|
411
|
+
dictionaries called like methods, codes a validator makes up, and `maxErrors` as a whole number.
|
|
412
|
+
- `pnpm bench` has `parse — flat struct, valid`, `parse — nested struct, valid` and `parse —
|
|
413
|
+
flat struct, defaults and a decoder` on both backends, measured as `check` is (through a
|
|
414
|
+
megamorphic call site); `bench/baseline.json` is re-saved, and the performance guide quotes
|
|
415
|
+
the rows.
|
|
416
|
+
- New test suites `parse`, `serialize` and `async`, the Standard Schema suite extended for
|
|
417
|
+
`validate` as parse and for a promise, the compile suite holding `parse`, `parseAsync`,
|
|
418
|
+
`checkAsync` and `serialize` to the same results on both backends, the bundle test running
|
|
419
|
+
them through the minified bundles, and `tests/types/parse.test-d.ts` for the typings; all
|
|
420
|
+
under `test`, `test:jit` and `test:nojit`.
|
|
421
|
+
- `pnpm run test:jit` runs the whole suite with every schema compiled by the JIT
|
|
422
|
+
(`tests/helpers/jit.js` registers it before the suites) and `pnpm run test:nojit` the same
|
|
423
|
+
under `--disallow-code-generation-from-strings`, through the fallback; CI runs both on Node
|
|
424
|
+
22. `tests/unit/compile.test.js` holds the two backends to the same issues over every form of
|
|
425
|
+
the language, the fixture model, every check option and keys and values that look like code,
|
|
426
|
+
and covers the modes, the errors, `register()` and the no-eval environment in a child process;
|
|
427
|
+
`tests/types/compile.test-d.ts` pins the typings. The bundle test, the export-parity test and
|
|
428
|
+
the size script (`pnpm size --max-gzip-compile`) cover the subpath; the ajv differential test
|
|
429
|
+
is skipped where ajv cannot generate code.
|
|
430
|
+
- **The moltar scenarios of `pnpm bench` measure a struct now.** The first key of their schema,
|
|
431
|
+
`number`, made it a `number` field under the first-key rule of 2.0, so every check failed at
|
|
432
|
+
the root, and the 14 M ops/s the 2.0 notes quoted for those rows measured that; marked as a
|
|
433
|
+
struct, the closures do 7.1–7.4 M (flat) and 4.2–4.4 M (nested). Every `check` scenario runs
|
|
434
|
+
on both backends (`check (jit) — …`), and `pnpm bench --compare-libs` runs the moltar
|
|
435
|
+
scenarios through zod 4, valibot, ajv and @sinclair/typebox (devDependencies, `bench/libs.js`);
|
|
436
|
+
the tables are in the performance guide, and `bench/baseline.json` is re-saved.
|
|
437
|
+
- `ajv` and `ajv-formats` are devDependencies, used by `tests/unit/jsonschema-ajv.test.js`: for
|
|
438
|
+
values a deterministic generator produces from the schemas (every form of the language, the
|
|
439
|
+
fixture model, references by kind, embedded and as ids), `check` and ajv over `toJSONSchema`
|
|
440
|
+
must agree on every verdict, for draft 2020-12 and draft-07. The known differences (UTF-16
|
|
441
|
+
units against code points, instances on the output side, number keys) are documented in the
|
|
442
|
+
file and in the guide.
|
|
443
|
+
- New test suites: `generators` (the subpath: the functions, `register()`, the core without it),
|
|
444
|
+
`jsonschema` (every form by target, the strict profile, the mongodb target, the fixture model,
|
|
445
|
+
the Standard converter), `jsonschema-ajv`, `dts` (JSDoc and named types),
|
|
446
|
+
`tests/types/jsonschema.test-d.ts`; the bundle test builds the core entry with the subpath,
|
|
447
|
+
the export-parity test covers the subpath, `pnpm size` reports the generators on top of the
|
|
448
|
+
core.
|
|
449
|
+
|
|
10
450
|
## [2.0.0] - 2026-10-10
|
|
11
451
|
|
|
12
452
|
2.0 rewrites the validation core and settles the semantics of the schema language. Every check
|
|
@@ -643,7 +1083,9 @@ published.
|
|
|
643
1083
|
|
|
644
1084
|
### [metaschema 0.x][upstream-0.x] - First generation of metaschema
|
|
645
1085
|
|
|
646
|
-
[unreleased]: https://github.com/Alexis-Technologies/metaschema/compare/
|
|
1086
|
+
[unreleased]: https://github.com/Alexis-Technologies/metaschema/compare/v3.1.0...HEAD
|
|
1087
|
+
[3.1.0]: https://github.com/Alexis-Technologies/metaschema/compare/v3.0.0...v3.1.0
|
|
1088
|
+
[3.0.0]: https://github.com/Alexis-Technologies/metaschema/compare/v2.0.0...v3.0.0
|
|
647
1089
|
[2.0.0]: https://github.com/Alexis-Technologies/metaschema/compare/v1.0.0...v2.0.0
|
|
648
1090
|
[1.0.0]: https://github.com/Alexis-Technologies/metaschema/releases/tag/v1.0.0
|
|
649
1091
|
[upstream-2.2.2]: https://github.com/metarhia/metaschema/compare/v2.2.1...v2.2.2
|