@alexify/metaschema 3.3.0 → 3.4.1

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.
Files changed (53) hide show
  1. package/CHANGELOG.md +251 -1
  2. package/README.md +31 -20
  3. package/SECURITY.md +24 -1
  4. package/index.d.ts +280 -48
  5. package/package.json +13 -3
  6. package/src/checks.js +789 -0
  7. package/src/codec.js +37 -13
  8. package/src/coerce/index.js +34 -1
  9. package/src/compile/emit.js +87 -28
  10. package/src/compile/index.js +9 -4
  11. package/src/definition/index.d.ts +19 -0
  12. package/src/definition/index.js +27 -0
  13. package/src/derive/index.js +23 -13
  14. package/src/errors.js +23 -0
  15. package/src/generators/fromjsonschema.js +14 -0
  16. package/src/generators/index.js +1 -1
  17. package/src/generators/jsonschema.js +44 -7
  18. package/src/generators/typescript.js +11 -0
  19. package/src/index.js +3 -2
  20. package/src/issues.js +9 -7
  21. package/src/kinds.js +24 -2
  22. package/src/lint.js +64 -2
  23. package/src/locales/en.js +6 -0
  24. package/src/locales/uk.js +6 -0
  25. package/src/metadata.js +2 -24
  26. package/src/model/data.js +68 -11
  27. package/src/model/diff.js +7 -4
  28. package/src/model/index.js +1 -1
  29. package/src/model/infer.js +13 -6
  30. package/src/model/merge.js +7 -3
  31. package/src/model/restore.js +60 -8
  32. package/src/model/sample.js +26 -1
  33. package/src/model.js +25 -53
  34. package/src/mongodb/bson.js +15 -3
  35. package/src/mongodb/document.js +10 -2
  36. package/src/preprocessor.js +14 -5
  37. package/src/prototypes/abstract.js +32 -64
  38. package/src/prototypes/collections.js +3 -90
  39. package/src/prototypes/flags.js +34 -0
  40. package/src/prototypes/json.js +0 -11
  41. package/src/prototypes/reference.js +0 -76
  42. package/src/prototypes/scalars.js +17 -96
  43. package/src/prototypes/schema.js +1 -10
  44. package/src/prototypes/tuple.js +5 -31
  45. package/src/prototypes/union.js +12 -82
  46. package/src/rules.js +33 -157
  47. package/src/schema.js +108 -233
  48. package/src/snapshot.js +216 -41
  49. package/src/stream/index.js +1 -1
  50. package/src/struct.js +6 -91
  51. package/src/types.js +31 -10
  52. package/src/util.js +48 -0
  53. package/src/validation.js +313 -0
package/CHANGELOG.md CHANGED
@@ -7,6 +7,254 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
7
7
 
8
8
  ## [Unreleased]
9
9
 
10
+ ## [3.4.1] - 2026-11-24
11
+
12
+ 3.4.1 settles what a capitalized key is. Until now the first key of an object was a kind
13
+ whenever it began with a capital letter, whatever it was called and whatever it held, so a
14
+ struct that began with `DATABASE_URL: 'string'` lost that field without a word (a schema of
15
+ environment variables lost its first variable), and `Infer` took every capitalized key for a
16
+ kind and left it out of the type. A kind is now a **kind name holding its metadata**: a capital
17
+ letter, then letters and digits, at least one of them lowercase (`Entity`, `Settings`), holding
18
+ a plain object. Every other capitalized key is a field, for the runtime and for the types alike,
19
+ and the one case the first key still cannot tell apart is a warning.
20
+
21
+ ### Fixed
22
+
23
+ - **A capitalized first key that is no kind is a field.** `Schema.from({ DATABASE_URL: 'string',
24
+ PORT: 'number' })` was the kind `dATABASE_URL` with the string spread into `custom`
25
+ (`{ 0: 's', 1: 't', … }`) over a struct of `PORT` alone, with no warning, and a value that
26
+ carried `DATABASE_URL` was rejected for an unexpected key. It is a struct of both fields now,
27
+ and so is every first key in upper case (`PORT: { type: 'number', default: 3000 }`,
28
+ `NODE_ENV: { enum: […] }`), every name with a character that is no letter or digit
29
+ (`Api_key`), and a kind name that holds no metadata: a type name (`Name: 'string'`), a tuple,
30
+ a function, a `Schema`, a built field. The same holds wherever a definition is read: a nested
31
+ struct, an element of a collection or a tuple, a branch of a union, an entity of a `Model` and
32
+ its snapshot.
33
+ - **`Infer` reads a kind key as the runtime does.** `Infer<{ host: 'string', PORT: 'number' }>`
34
+ was `{ host: string }`, `Infer<{ HOST: 'string' }>` was `{}`, and a struct with a kind and
35
+ capitalized fields (`{ Struct: {}, DATABASE_URL: 'string', PORT: 'number' }`) was a union of
36
+ structs, each without one of its keys. A kind key of the types is a kind name holding an
37
+ object now, the keys are taken as one set instead of one by one, and where several keys could
38
+ be the kind a built-in one is it (`{ Struct: {}, Address: { … }, name: 'string' }` infers with
39
+ `Address`). `InferOutput`, `InferEntity`, a projection and the types of `./derive` read the
40
+ same keys, so `pick(env, ['DATABASE_URL'])` compiles.
41
+ - **`extend` of `./derive` takes capitalized fields.** `extend(schema, { REDIS_URL: 'string' })`
42
+ threw "An extension has fields only"; an extension is refused for a kind only.
43
+ - **A capitalized key holding a type name names a tuple element**: `[{ X: 'number' }, { Y:
44
+ 'number' }]` is two numbers named `X` and `Y`, as `{ x: 'number' }` always was (it was an
45
+ empty struct of the kind `x`), for `check` and for `Infer`.
46
+
47
+ ### Changed
48
+
49
+ - **A custom kind is a kind name.** `{ DTO: {}, … }`, `{ X: {}, … }` and `{ Api_config: {}, … }`
50
+ were the kinds `dTO`, `x` and `api_config`; they are structs with a field of that name now.
51
+ Name the kind with a lowercase letter and nothing but letters and digits (`Dto`,
52
+ `ApiConfig`). The built-in kinds and the custom kinds of the documentation
53
+ (`{ Settings: { theme: 'dark' }, … }`) read as they did.
54
+ - **A kind that would not read back is refused where it is written**: `fromJSON` of a snapshot
55
+ whose entity has such a kind (`dTO`, or the `dATABASE_URL` that 3.4.0 wrote for the struct
56
+ above) is `ERR_INVALID_SNAPSHOT` located at the entity, and `metadata: { kind }` of `./derive`
57
+ and `merge` and the `kind` option of `infer` are `ERR_INVALID_OPTIONS`. Each writes the kind
58
+ as the first key of a definition, where it would have become a field.
59
+
60
+ ### Added
61
+
62
+ - **`ambiguous-kind` in `schema.warnings`.** A field with a name like a kind's that holds a
63
+ nested struct or a long form, first in its struct (`{ Address: { street: 'string' }, name:
64
+ 'string' }`), is still read as the custom kind `address`: the first key decides, and such
65
+ metadata is what a custom kind looks like. The warning names every custom kind, at any depth,
66
+ whose metadata names a type or reads as a field definition; a kind before the field settles
67
+ it (`{ Struct: {}, Address: { … }, name: 'string' }`). `{ Settings: { theme: 'dark' } }` has
68
+ no warning.
69
+
70
+ The core measures 21.7 KB (22224 / 22233 bytes, under its 22 KB gate), `./definition` 10.5 KB,
71
+ the model subpath 12.8 KB and the derive subpath 2.3 KB; building a schema and checking with it
72
+ are at parity with 3.4.0.
73
+
74
+ ## [3.4.0] - 2026-10-16
75
+
76
+ 3.4 makes the snapshot a contract a program can build on and the language complete for the
77
+ programs that encode from it. A schema writes its own snapshot (`schema.toSnapshot()`, with the
78
+ entities it reaches and its name as `root`), the guarantees of format 1 are written down, and
79
+ the typings narrow a field of a snapshot on its type; a schema names itself without a model;
80
+ binary data (`bytes`), named switches (`flags`) and a number of decimals (`decimals`) are built
81
+ in. The checks are compiled on their first use, which makes building a schema 13 to 15% faster,
82
+ and the core is split into two halves over the same classes, so that a client that reads
83
+ schemas without validating them imports `@alexify/metaschema/definition`, 10.3 KB, about half
84
+ of the core. The two new type names change what a struct whose first key is `bytes` or `flags`
85
+ reads as, and a program that registered either as a custom type of its own (protoarray 1.2's
86
+ `types`) drops that entry: see Changed. The review of the release before its tag kept bundlers
87
+ from dropping the import that installs validation, made the snapshot of a schema whole (what a
88
+ reused schema reaches, the values that have no JSON form, copies of the metadata) and its
89
+ restore strict, bounded binary data by a `length`, and moved the gates to 22 KB for the core
90
+ and 11 KB for `./definition`.
91
+
92
+ ### Added
93
+
94
+ - **`schema.toSnapshot()`.** The snapshot of format 1 for one schema: the schema and every
95
+ entity it reaches through its references (the parent of a projection included), each after
96
+ the ones it references in the order a walk from the schema meets them, with the name of the
97
+ schema as the new optional key `root` (`''` for an anonymous schema) and no `database`
98
+ metadata. `fromJSON` restores it (`model.entities.get(snapshot.root)`
99
+ is the schema again, and `toSnapshot()` of it writes the same text), and `fromJSON` and `diff`
100
+ check that `root` names one of its entities (`ERR_INVALID_SNAPSHOT`). Two schemas of one name
101
+ in what a schema reaches (one derived from an entity keeps its name) cannot be one snapshot:
102
+ `ERR_UNREPRESENTABLE`, and so are two custom types of one name from two registries. A Schema
103
+ reused as a field (`{ inner: Inner }`) resolves its references and types through itself, as its
104
+ fields do, and an anonymous schema of a model is the entity of the name the model gives it.
105
+ `snapshot.js` shares the walk between the two writers, a loop rather than a recursion, so a
106
+ chain of entities of any length orders; `model.toJSON()` does not change.
107
+ - **What format 1 guarantees**, written down in the model guide: the fields of a struct in the
108
+ order of the definition, the id field of a stored kind after them, the entities each after the
109
+ ones they reference (`model.order` for a model), the tags as they are, and keys only ever
110
+ added. A change of any of them is a
111
+ major release.
112
+ - **A typed snapshot.** `FieldSnapshot` is a union that narrows on `type`: a string with its
113
+ rules, a number with its bounds and `decimals`, the scalars, an enum with `enum`, `flags`
114
+ with `flags`, a list or a dictionary with `value` (and `key`), a tuple with its elements, a
115
+ nested struct with `schema`, a union with `union` and `discriminator`, a reference by the
116
+ capitalized name of its entity with `one`/`many` and `embed`, a custom type by the names of
117
+ `CustomTypes`, `bytes` with its `length` (`BytesFieldSnapshot`). `SchemaSnapshot` is what
118
+ `toSnapshot()` returns; `BytesSnapshot`, `MapSnapshot` and `SetSnapshot` type the new tags.
119
+ - **Bytes, a Map and a Set are tagged in a snapshot** (`{ $bytes: 'AQL/' }`, `{ $map: [[k, v]] }`,
120
+ `{ $set: [v] }`), beside `$date` and `$bigint`, and `fromJSON` reads them back into their
121
+ values: a `default` or the `examples` of such a field restore as values of the field (a Map
122
+ and a Set were written as `{}`, bytes as an object of indices). A tag that does not read is
123
+ `ERR_INVALID_SNAPSHOT`.
124
+ - **`bytes`**, a built-in type: a `Uint8Array` of any realm, a `Buffer` included, told by the
125
+ name the engine keeps in the view (`isBytes` of `util.js`), never by `instanceof` or a key of
126
+ the value. `length` counts its bytes, on both backends. `Uint8Array` in TypeScript and
127
+ `Infer`; base64 text on the input side of a JSON Schema (`format: 'byte'` for OpenAPI 3.0,
128
+ `length` as `minLength`/`maxLength` of the text; the strict profile keeps the type only),
129
+ unrepresentable on its output side (as a `date`), `binData` for mongodb; random bytes within
130
+ the length in `sample`; `bytes` in `infer` for the views of the samples; canonical base64 read into bytes by `./coerce` (padded, the unused bits at zero;
131
+ `''`, the text of no bytes, as an empty `Uint8Array`, the one exception to the rule that `''`
132
+ is never converted; a scan of the text, linear and without the stack of a repeated group, so
133
+ a valid text of megabytes converts; a text whose bytes would be over `length.max` is left
134
+ undecoded, for the check to reject); a generic Binary of the driver (subtype 0, or 2) read
135
+ back into a copy of its bytes by `fromDocument` of `./mongodb`, any other subtype (a UUID, an
136
+ encrypted value) left for the check, so that it is never written back as generic binary
137
+ data.
138
+ - **`flags`**, a built-in type: `{ flags: ['read', 'write'] }` is an object of those names,
139
+ each a boolean, any left out. A name the list does not have is `unexpected` under the
140
+ unknown-keys policy of the check, ignored under `unknown: 'ignore'`, left out by `parse`
141
+ under `strip`; a list that is not one of distinct names is `ERR_INVALID_DEFINITION`. An
142
+ object of optional booleans in TypeScript and `Infer`, an object of boolean properties in
143
+ JSON Schema (closed with the document; every name required under the strict profile), a
144
+ random set of switches in `sample`; `merge` keeps the names both have, and `compatibility`
145
+ reads them as the values of an enum. The list is a frozen copy of the program's.
146
+ - **`decimals`**, a rule of `number` (0 to 15): the value times 10ⁿ is a whole number to
147
+ within 256 units in the last place, so `0.1 + 0.2` has two decimals and `12345678.123` does
148
+ not; NaN and the infinities have none to count. A new issue code, `decimals` (`{ decimals }`,
149
+ and `received` naming NaN or an infinity), with a renderer in both locales; a new warning,
150
+ `unenforceable-decimals`, where the bounds of the field reach 2⁴³ units of the last decimal,
151
+ past which every number passes (thirteen decimals or more without bounds, two with
152
+ `max: 1e12`); `multipleOf` in JSON Schema (read back by `fromJSONSchema`);
153
+ drawn with its decimals by `sample`; the fewer of the two in `merge`; an upper bound in
154
+ `compatibility`.
155
+ - **`@alexify/metaschema/definition`**, the half of the core that builds schemas and models and
156
+ reads them (fields, metadata, `toJSON`, `toSnapshot`), on its own: 10.3 KB min+gzip, gated at
157
+ 11 KB. Its `Schema` and `Model` are the core's; a schema it builds says `ERR_NOT_REGISTERED`
158
+ (with the `method`) when it is asked to validate (`check`, `parse`, `serialize`, `validate`,
159
+ the async pair, the `check` of a field, the warnings) until the program loads the core entry,
160
+ and validates from then on, the schemas built before and a method taken from them before
161
+ (`const { check } = schema`) included; it has no `~standard` until then. A schema of another
162
+ copy of the package (two versions installed side by side) says that the core loaded is
163
+ another copy. `./derive` and `./formats` work beside it alone; a bundle of it and the core
164
+ carries each module once, and `import '@alexify/metaschema'` for the validation it installs
165
+ survives a bundler (`sideEffects` lists the entries and `src/validation.js`).
166
+ - `pnpm size` measures `./definition` on its own (`--max-gzip-definition`); `graph.test.js`
167
+ pins that the definition half, `./derive` and `./formats` reach no module of the validation
168
+ half. `pnpm run size:gate` is `pnpm size` with the budgets as gates, the one place they are
169
+ written, which CI and `prepublishOnly` run.
170
+
171
+ ### Changed
172
+
173
+ - **The checks are compiled on their first use**: a field on the first read of its `check`, a
174
+ struct on its first check (`checkOf`, kept beside its frozen plan, whose entries no longer
175
+ hold the checks), a schema through a stub of `Schema[RUN]` that takes the closures' place. A
176
+ schema that is only read never compiles them: `Schema.from` is 13 to 15% faster, `new Model`
177
+ 5%, and `check` and `parse` are at parity on both backends. What a definition must reject is
178
+ still found when it is built (a `max` below `min`, a format not registered), and the test of
179
+ a format is the one named when the field was built.
180
+ - **The core is two halves.** The definition half (`schema.js`, `model.js`, `types.js`, the
181
+ prototypes, `struct.js`, `rules.js`, `snapshot.js`) builds; the validation half
182
+ (`validation.js`, `checks.js`, `codec.js`, `context.js`, `issues.js`, `result.js`,
183
+ `lint.js`, the locale) installs `check`, `parse` and their kin, `~standard`, the warnings and
184
+ `checkConsistency` on the classes, and the type check of every built-in on the prototype
185
+ object the classes of the type inherit from. The core entry loads both; nothing changes for a
186
+ program that imports it. The state the validation half keeps on a schema is held under
187
+ symbols, and `fields[STRUCT]` is `{ plan, known, calculated }` (the check is `checkOf`).
188
+ - **`bytes` and `flags` are type names**, so a struct whose first key is one of them
189
+ (`{ flags: ['a'], name: 'string' }`) reads as that type now, as `{ date, place }` reads as a
190
+ date: give it a kind (`{ Struct: {}, flags: … }`). A table of custom types of the program
191
+ under either name (`bytes` and `flags` of protoarray 1.2's `types`, for one) is
192
+ `ERR_TYPE_REGISTERED`: leave those entries out, the built-ins check the same values (only
193
+ `{ metadata }` may still be added). `infer` writes `bytes` for a `Uint8Array` among the
194
+ samples (it wrote a dictionary of its indices).
195
+ - **The core gate is 22 KB** (was 19): `toSnapshot`, the two types and the rule cost the core
196
+ about 1.0 KB, the lazy checks and the split about 0.8 KB, the review about 0.9 KB; the core
197
+ measures 21.3 KB. The generators gate is 8 KB (was 7.5; the two types and the rule took the
198
+ subpath to 7.7 KB); a new gate of 11 KB for `./definition` (10.3 KB).
199
+ - **The `compile` of a custom type of its own runs on the first check** of its field, as every
200
+ check is compiled now (when the schema is built under the JIT): what it throws is
201
+ `ERR_INVALID_CUSTOM_TYPE` located at the schema, with the error as the cause.
202
+ - **What a snapshot holds is a copy.** The `custom` metadata of a kind, the index definitions
203
+ and the `database` metadata were the model's own objects inside the snapshot; they are written
204
+ as any value is now, their functions, bigints and dates tagged.
205
+ - **A discriminator field that is optional or nullable is `ERR_INVALID_UNION`**
206
+ (`'kind?'`, `required: false`, `nullable: true` on the field a `discriminator` names), as a
207
+ `default` on it already was: a value without the tag or with `null` is in no branch, so such a
208
+ branch could never be picked. A definition of that kind built until now and rejected every
209
+ value without the tag; it throws when it is built now, a snapshot that says so does not
210
+ restore, and an OpenAPI document whose branch does not require its discriminator does not
211
+ build. protoarray holds the same rule.
212
+ - **`prepublishOnly` runs both backends and the bundle budgets** (`test:jit`, `test:nojit`,
213
+ `size:gate`) besides the gates it ran, so that a release from a machine is held to what CI
214
+ holds; the release process tags the squash commit on `main`.
215
+ - The warnings of a schema and of a model (`schema.warnings`, `schema.checkConsistency()`,
216
+ `model.warnings`) are computed by the validation half, kept in a WeakMap, and the cycles a
217
+ model meets while ordering its entities are recorded as data; their text is the same.
218
+ - `compiled()` of `./compile` tells a generated check by a set of the functions it built, since
219
+ the closures of a schema may now be compiled after the JIT was turned off.
220
+
221
+ ### Fixed
222
+
223
+ - **A schema resolves its own name without a model.** `new Schema('Category', { name:
224
+ 'string', parent: '?Category' })` checked `parent` as `Entity "Category" is not found`; the
225
+ schema is now the fallback of `findReference` after the attached models (which come first,
226
+ so a schema that shares the name of their entity still reaches the entity). A projection of
227
+ its own name is `ERR_PROJECTION`, not a crash.
228
+ - **A snapshot of a model whose alias type names another alias** (`cents: { js: 'money' }`)
229
+ left out the type it names, so `fromJSON` could not restore it (`ERR_UNKNOWN_JS_TYPE`); the
230
+ custom types down the chain of an alias are written now.
231
+ - `types.md` said the formats subpath registers nine formats; it registers 35.
232
+ - **A Schema reused as a field is consistent.** `checkConsistency()` and `model.warnings`
233
+ resolved the references of a schema reused as a field (`{ inner: Inner }`) through the schema
234
+ that reuses it, and warned that they were missing; a snapshot of a model left out the custom
235
+ types of such a schema from another registry. They resolve as the fields do now.
236
+ - **A snapshot is data where it names a Date or a RegExp.** A value of a snapshot such as
237
+ `{ "constructor": { "name": "Date" } }` passed `fromJSON`, and `toJSON`, `toSnapshot` and
238
+ `diff` then threw a bare `TypeError`; a Date and a RegExp are told by their shape, as the
239
+ checks tell them since 3.2.
240
+ - **`fromJSON` refuses what a model cannot be built from**: a field key `root` (a reserved key of
241
+ a definition now, which replaced the schema of the field and made every later read of it
242
+ throw), a kind that is no lowercase name, an entity named like the ones a model skips (`.x`),
243
+ a parent that is no name; anything else the model cannot build is `ERR_INVALID_SNAPSHOT` with
244
+ the cause. The parent of a kind other than a projection is restored, so such a model reads
245
+ back to the same text.
246
+ - **A model of a chain of a few thousand entities** overflowed the stack while ordering them (a
247
+ bare `RangeError` out of `new Model` and `fromJSON`); the order is a loop.
248
+ - **A schema derived or merged from one that names itself** reaches it: `partial(category)`
249
+ checked the parent as a partial category, `pick()` under another name did not find it, and
250
+ `extend()` and `merge()` lost the self-reference of the second schema.
251
+ - **The JSON Schema of an anonymous schema of a model** was defined under `''`; it is defined
252
+ under the name the model gives it.
253
+ - **The TypeScript of a field with a `flags` option** of another type (`{ type: 'string', flags:
254
+ 'gi' }`) was an object of switches; a field is flags by its type.
255
+ - **The JIT wrote the numbers of `decimals` into the generated source** as they were; they are
256
+ literals of the code builder now, and both backends run one test (`decimalsOff`).
257
+
10
258
  ## [3.3.0] - 2026-10-14
11
259
 
12
260
  3.3 closes the gaps the comparison with the alternatives showed. `parse` converts the text of a
@@ -1394,7 +1642,9 @@ published.
1394
1642
 
1395
1643
  ### [metaschema 0.x][upstream-0.x] - First generation of metaschema
1396
1644
 
1397
- [unreleased]: https://github.com/Alexis-Technologies/metaschema/compare/v3.3.0...HEAD
1645
+ [unreleased]: https://github.com/Alexis-Technologies/metaschema/compare/v3.4.1...HEAD
1646
+ [3.4.1]: https://github.com/Alexis-Technologies/metaschema/compare/v3.4.0...v3.4.1
1647
+ [3.4.0]: https://github.com/Alexis-Technologies/metaschema/compare/v3.3.0...v3.4.0
1398
1648
  [3.3.0]: https://github.com/Alexis-Technologies/metaschema/compare/v3.2.0...v3.3.0
1399
1649
  [3.2.0]: https://github.com/Alexis-Technologies/metaschema/compare/v3.1.0...v3.2.0
1400
1650
  [3.1.0]: https://github.com/Alexis-Technologies/metaschema/compare/v3.0.0...v3.1.0
package/README.md CHANGED
@@ -95,24 +95,28 @@ event.parse({ name: 'deploy', when: '2026-10-10T12:00:00.000Z' }).value;
95
95
  LLM structured outputs; `~standard.jsonSchema` is the Standard JSON Schema converter. The
96
96
  generators live in the `@alexify/metaschema/generators` subpath, so a program that only
97
97
  validates does not carry them.
98
- - **Fast.** Every check is compiled into a closure when the schema is built and runs in a context
98
+ - **Fast.** Every check is compiled into a closure on its first use and runs in a context
99
99
  of its own: about 10 million validations a second of a flat struct on Node 24, and about 30
100
100
  million through the JIT backend of `@alexify/metaschema/compile`, which generates the same
101
101
  check where `new Function` is allowed and keeps the closures where it is not. Against ten other
102
102
  validators see [Benchmarks](#benchmarks); how the core gets there is on the
103
103
  [Performance](https://metaschema.vercel.app/guide/performance) page.
104
104
  - **The model as data.** `model.toJSON()` is a snapshot other programs read the model through
105
- (a migration tool, an introspecting service, a committed baseline), and
105
+ (a migration tool, an introspecting service, a committed baseline), `schema.toSnapshot()` the
106
+ same document for one schema and the entities it reaches (a codec built from it), with the
107
+ guarantees of format 1 written down, and
106
108
  `@alexify/metaschema/model` tells two versions apart (`diff`), classifies the change by the
107
109
  Confluent rules (`compatibility`), draws a value every schema accepts (`sample`), unifies two
108
110
  schemas (`merge`) and infers a definition from the values that exist (`infer`); `aliases` and
109
111
  `deprecated` let a model carry its history, and `fromJSONSchema` of the generators reads a
110
112
  JSON Schema document back.
111
- - **Zero dependencies, 18.6 KB min+gzip.** CommonJS with ESM named imports, no build step,
112
- one package for Node.js and browsers; the generators add 7.3 KB, the JIT backend 4.2 KB, the
113
- model tools 12.0 KB, the record tools 1.0 KB, the string formats 4.0 KB, the derive tools
114
- 1.9 KB, the converters of coercion 1.7 KB and the MongoDB tools 3.5 KB (on top of the
115
- converters, which they require) where they are imported.
113
+ - **Zero dependencies, 21.7 KB min+gzip.** CommonJS with ESM named imports, no build step,
114
+ one package for Node.js and browsers; the generators add 7.7 KB, the JIT backend 4.3 KB, the
115
+ model tools 12.8 KB, the record tools 1.0 KB, the string formats 3.8 KB, the derive tools
116
+ 2.3 KB, the converters of coercion 1.9 KB and the MongoDB tools 3.6 KB (on top of the
117
+ converters, which they require) where they are imported. A program that reads schemas
118
+ without validating them (a client that encodes from their snapshots) imports
119
+ `@alexify/metaschema/definition`, the half of the core that builds them: 10.5 KB.
116
120
 
117
121
  ## Benchmarks
118
122
 
@@ -221,7 +225,7 @@ interactive.
221
225
  | Effect Schema<br><sub>decodeUnknownResult() · is() · v4.0.3</sub> | 72.9 KB | 24.4 KB | |
222
226
  | Zod<br><sub>safeParse() · v4.6.6</sub> | 88.4 KB | 25.7 KB | |
223
227
  | TypeBox<br><sub>Value.Check() · v1.3.36</sub> | 146.7 KB | 37.5 KB | |
224
- | Ajv<br><sub>compile(…)(value), draft 2020-12 · v8.20.0</sub> | 130.9 KB | 39.5 KB | |
228
+ | Ajv<br><sub>compile(…)(value), draft 2020-12 · v8.20.0</sub> | 131.0 KB | 39.5 KB | |
225
229
  | TypeBox<br><sub>Compile(…).Check() · v1.3.36</sub> | 161.5 KB | 40.8 KB | |
226
230
  | ArkType<br><sub>type(value) · allows() · v2.2.8</sub> | 151.9 KB | 46.4 KB | |
227
231
  | Joi<br><sub>validate(), convert: false · v18.2.9</sub> | 169.5 KB | 53.3 KB | |
@@ -317,7 +321,7 @@ pinned.
317
321
  </thead>
318
322
  <tbody>
319
323
  <tr class="ms-matrix-group"><td colspan="22"><strong>Package</strong></td></tr>
320
- <tr><td>Version compared</td><td>3.2.0</td><td>2.2.2</td><td>4.6.6</td><td>1.5.0</td><td>2.2.8</td><td>4.0.3</td><td>2.0.2<sup>1</sup></td><td>2.2.22</td><td>7.0.5</td><td>1.12.1<sup>2</sup></td><td>0.5.5</td><td>1.7.1</td><td>18.2.9</td><td>4.4.0</td><td>0.15.1</td><td>8.20.0</td><td>1.3.36<sup>3</sup></td><td>15.1.0</td><td>5.7.9</td><td>8.8.1</td><td>9.11.1</td></tr>
324
+ <tr><td>Version compared</td><td>3.4.0</td><td>2.2.2</td><td>4.6.6</td><td>1.5.0</td><td>2.2.8</td><td>4.0.3</td><td>2.0.2<sup>1</sup></td><td>2.2.22</td><td>7.0.5</td><td>1.12.1<sup>2</sup></td><td>0.5.5</td><td>1.7.1</td><td>18.2.9</td><td>4.4.0</td><td>0.15.1</td><td>8.20.0</td><td>1.3.36<sup>3</sup></td><td>15.1.0</td><td>5.7.9</td><td>8.8.1</td><td>9.11.1</td></tr>
321
325
  <tr><td>Latest release</td><td>2026-10 (this release)</td><td>2025-05</td><td>2026-10</td><td>2026-09</td><td>2026-10</td><td>2026-10</td><td>2024-07</td><td>2024-12</td><td>2026-08</td><td>2025-02</td><td>2026-10</td><td>2025-09</td><td>2026-09</td><td>2026-04</td><td>2026-02</td><td>2026-04</td><td>2026-10</td><td>2026-10</td><td>2025-07</td><td>2026-10</td><td>2026-10</td></tr>
322
326
  <tr><td>Runtime dependencies</td><td>✅ 0</td><td>2: metautil, metavm</td><td>✅ 0</td><td>✅ 0</td><td>3: @ark/schema, @ark/util, arkregex</td><td>✅ 0</td><td>✅ 0</td><td>0 + peer fp-ts</td><td>✅ 0</td><td>✅ 0</td><td>✅ 0</td><td>4: property-expr, tiny-case, toposort, type-fest</td><td>7 (@hapi/*, …)</td><td>10 (validator.js, dayjs, …)</td><td>3 (validator.js, libphonenumber-js, …)</td><td>4</td><td>✅ 0</td><td>3: randexp, @typia/interface, @typia/utils</td><td>✅ 0</td><td>1: long</td><td>7, incl. mongodb driver</td></tr>
323
327
  <tr><td>License</td><td>MIT</td><td>MIT</td><td>MIT</td><td>MIT</td><td>MIT</td><td>MIT</td><td>MIT</td><td>MIT</td><td>MIT</td><td>MIT</td><td>MIT</td><td>MIT</td><td>BSD-3-Clause</td><td>MIT</td><td>MIT</td><td>MIT</td><td>MIT</td><td>MIT</td><td>MIT</td><td>BSD-3-Clause</td><td>MIT</td></tr>
@@ -332,11 +336,11 @@ pinned.
332
336
  <tr><td>Optional vs nullable</td><td>✅ <code>'?x'</code>, <code>'key?'</code>, <code>nullable: true</code></td><td>⚠️ '?type' = absent/undefined/null</td><td>✅ optional, exactOptional, nullable, nullish</td><td>✅ optional, exactOptional, nullable, nullish, undefinedable</td><td>✅ 'key?' (no undefined), '| null', '| undefined'</td><td>✅ optionalKey, optional, NullOr, UndefinedOr, NullishOr</td><td>✅ optional(), nullable()</td><td>✅ t.partial vs t.union([X, t.null])</td><td>✅ optional(), nullable(), undefinedable()</td><td>✅ optional(), nullable()</td><td>✅ optional(), nullable()</td><td>✅ optional() / nullable() / defined()</td><td>✅ optional default; allow(null); required()</td><td>⚠️ optional() also accepts null<sup>14</sup></td><td>⚠️ IsOptional() skips null and undefined</td><td>✅ <code>required</code> vs type null / <code>nullable</code></td><td>✅ Optional, Union with Null, Undefined</td><td>✅ TS <code>?:</code>, <code>| null</code>, <code>| undefined</code></td><td>⚠️ ['null', T] union; absent needs default</td><td>⚠️ presence only; null = unset</td><td>⚠️ optional = absent/undefined/null</td></tr>
333
337
  <tr><td>Unions, discriminated</td><td>✅ <code>union</code>, <code>discriminator</code></td><td>❌ none</td><td>✅ union, discriminatedUnion, xor</td><td>✅ union, variant (discriminated)</td><td>✅ 'a | b', .or(); auto-discriminated</td><td>✅ Union, Literals, TaggedUnion</td><td>⚠️ union(); no discriminated union</td><td>✅ union(), tag detected automatically</td><td>⚠️ Union(...); no discriminator</td><td>⚠️ union([..]) / or(); no discriminator</td><td>✅ union(), auto-discriminated</td><td>❌ no union type</td><td>✅ alternatives(); conditional() switch</td><td>✅ union() with if(), unionOfTypes()</td><td>⚠️ class-transformer discriminator</td><td>✅ anyOf / oneOf; <code>discriminator</code> opt-in</td><td>✅ Type.Union (anyOf); no discriminator</td><td>✅ TS unions; discriminant detected</td><td>✅ unions; wrapped = tagged by name</td><td>✅ oneof (virtual discriminator)</td><td>✅ Schema.Types.Union; discriminators</td></tr>
334
338
  <tr><td>Tuples</td><td>✅ <code>['number', 'string']</code></td><td>⚠️ array shorthand, scalars only</td><td>✅ z.tuple with rest</td><td>✅ tuple, strictTuple, tupleWithRest</td><td>✅ ['string', 'number'], variadic '...'</td><td>✅ Tuple, TupleWithRest</td><td>✅ tuple([..])</td><td>⚠️ tuple([..]) strips extra items<sup>15</sup></td><td>✅ Tuple(...), with Spread rest</td><td>✅ tuple([..])</td><td>✅ tuple([..]), variadic via concat<sup>16</sup></td><td>✅ tuple()</td><td>✅ array().ordered()</td><td>✅ vine.tuple()</td><td>❌ none</td><td>✅ prefixItems + items: false</td><td>✅ Type.Tuple</td><td>✅ TS tuples</td><td>❌ none</td><td>❌ none</td><td>❌ none</td></tr>
335
- <tr><td>Recursive schemas</td><td>✅ by name, cycles tracked</td><td>✅ by entity name in a Model</td><td>✅ getters or z.lazy</td><td>✅ v.lazy</td><td>✅ scope names, 'this'</td><td>✅ Schema.suspend</td><td>✅ lazy(() =&gt; S)</td><td>✅ t.recursion(name, f)</td><td>✅ Lazy(() =&gt; R)</td><td>✅ lazy(() =&gt; S)</td><td>✅ lazy(() =&gt; T)</td><td>✅ lazy()</td><td>✅ link('#id')</td><td>❌ none</td><td>✅ @ValidateNested + @Type(() =&gt; Self)</td><td>✅ $ref, $dynamicRef</td><td>✅ Type.Cyclic, Type.Module</td><td>✅ recursive TS types</td><td>✅ named types</td><td>✅ self-referencing messages</td><td>✅ schema.add({ self: schema })</td></tr>
339
+ <tr><td>Recursive schemas</td><td>✅ by name, a schema its own without a model; cycles tracked</td><td>✅ by entity name in a Model</td><td>✅ getters or z.lazy</td><td>✅ v.lazy</td><td>✅ scope names, 'this'</td><td>✅ Schema.suspend</td><td>✅ lazy(() =&gt; S)</td><td>✅ t.recursion(name, f)</td><td>✅ Lazy(() =&gt; R)</td><td>✅ lazy(() =&gt; S)</td><td>✅ lazy(() =&gt; T)</td><td>✅ lazy()</td><td>✅ link('#id')</td><td>❌ none</td><td>✅ @ValidateNested + @Type(() =&gt; Self)</td><td>✅ $ref, $dynamicRef</td><td>✅ Type.Cyclic, Type.Module</td><td>✅ recursive TS types</td><td>✅ named types</td><td>✅ self-referencing messages</td><td>✅ schema.add({ self: schema })</td></tr>
336
340
  <tr><td>Schemas referenced by name</td><td>✅ capitalized names in a <code>Model</code></td><td>✅ capitalized names via Model</td><td>❌ JS variables only</td><td>❌ JS variables only</td><td>✅ scope({ User, Group }) by name</td><td>❌ JS variables only</td><td>❌ none</td><td>❌ none</td><td>❌ none</td><td>❌ none</td><td>❌ none</td><td>❌ none (ref() is a value ref)</td><td>✅ id() + link('#id'), shared()</td><td>❌ none</td><td>❌ none</td><td>✅ $ref by $id; ajv.addSchema</td><td>✅ Type.Ref + context, Module, $id</td><td>✅ TS type names</td><td>✅ names + namespaces, registry</td><td>✅ full names via Root</td><td>⚠️ ref: 'Model' for populate</td></tr>
337
341
  <tr><td>Custom types registered by name</td><td>✅ registered by name</td><td>✅ Model types: js alias or checkType</td><td>❌ z.custom() values, no name registry</td><td>❌ v.custom() values, no name registry</td><td>✅ scope aliases, generics, keywords</td><td>⚠️ Schema.declare; reviver ids for restore</td><td>⚠️ define(name, fn); no registry</td><td>⚠️ new t.Type(name, is, validate, encode); no registry</td><td>⚠️ withBrand/withConstraint; no registry</td><td>⚠️ withPredicate/map on a base type; no registry</td><td>⚠️ unknown().assert()/chain(); no registry</td><td>⚠️ addMethod(), mixed(check)</td><td>✅ Joi.extend({ type })</td><td>⚠️ createRule(), macro() methods</td><td>✅ registerDecorator(), @ValidatorConstraint</td><td>⚠️ addKeyword / addSchema, not types</td><td>⚠️ Unsafe + Refine; Script/Module names</td><td>✅ custom tags (tags.TagBase)</td><td>✅ logicalTypes classes, typeHook</td><td>❌ messages and enums only</td><td>✅ Schema.Types.Name = class</td></tr>
338
342
  <tr><td>String formats</td><td>✅ 35 + your own (<code>./formats</code>)</td><td>❌ none</td><td>✅ 30+ (email, uuid, url, ip, iso.datetime…)</td><td>✅ ~37 actions (email, uuid, url, isoDateTime…)</td><td>✅ ~18 string.* (email, uuid, url, ip…)</td><td>✅ uuid, ulid, base64, URL, IP; no email</td><td>❌ none (pattern() only)</td><td>⚠️ io-ts-types: UUID, ISO dates</td><td>❌ none (Template literals)</td><td>❌ none (pattern() only)</td><td>❌ none</td><td>✅ 4: email, url, uuid, datetime<sup>17</sup></td><td>✅ 14: email, uri, uuid, ip, isoDate...</td><td>✅ 18: email, url, uuid, ulid, ip, iban, jwt...</td><td>✅ 50+ via validator.js (IsEmail, IsUUID, IsUrl...)</td><td>✅ ajv-formats: 26<sup>18</sup></td><td>✅ 21 built in<sup>19</sup></td><td>✅ 22 via tags.Format</td><td>❌ none</td><td>❌ none</td><td>❌ none (match: RegExp)</td></tr>
339
- <tr><td>Date, BigInt, Map, Set</td><td>✅ Date, BigInt, Map, Set; BSON (<code>./mongodb</code>)</td><td>⚠️ BigInt, Map, Set; no Date</td><td>✅ Date, BigInt, Map, Set, Symbol, File</td><td>✅ Date, BigInt, Map, Set, Blob, File</td><td>✅ Date, bigint, Map, Set, symbol, Blob, File…</td><td>✅ Date, BigInt, ReadonlyMap, ReadonlySet, Symbol…</td><td>✅ Date, BigInt, Map, Set</td><td>⚠️ BigInt; Date/Map/Set via io-ts-types</td><td>⚠️ BigInt, Symbol; Date/Map/Set via InstanceOf</td><td>⚠️ Date, BigInt</td><td>⚠️ BigInt only</td><td>⚠️ Date</td><td>⚠️ Date, Buffer, symbol, function</td><td>⚠️ Date (output), File</td><td>⚠️ Date; Set/Map via each</td><td>⚠️ Date via ajv-keywords or JTD</td><td>⚠️ BigInt, Symbol, Undefined; no Date/Map/Set<sup>20</sup></td><td>✅ Date, bigint, Map, Set, typed arrays<sup>21</sup></td><td>⚠️ Buffer; Date, BigInt via custom types<sup>22</sup></td><td>⚠️ Uint8Array, Long; BigInt via fromObject<sup>23</sup></td><td>✅ Date, BigInt, Map, Buffer</td></tr>
343
+ <tr><td>Date, BigInt, Map, Set</td><td>✅ Date, BigInt, Map, Set, Uint8Array; BSON (<code>./mongodb</code>)</td><td>⚠️ BigInt, Map, Set; no Date</td><td>✅ Date, BigInt, Map, Set, Symbol, File</td><td>✅ Date, BigInt, Map, Set, Blob, File</td><td>✅ Date, bigint, Map, Set, symbol, Blob, File…</td><td>✅ Date, BigInt, ReadonlyMap, ReadonlySet, Symbol…</td><td>✅ Date, BigInt, Map, Set</td><td>⚠️ BigInt; Date/Map/Set via io-ts-types</td><td>⚠️ BigInt, Symbol; Date/Map/Set via InstanceOf</td><td>⚠️ Date, BigInt</td><td>⚠️ BigInt only</td><td>⚠️ Date</td><td>⚠️ Date, Buffer, symbol, function</td><td>⚠️ Date (output), File</td><td>⚠️ Date; Set/Map via each</td><td>⚠️ Date via ajv-keywords or JTD</td><td>⚠️ BigInt, Symbol, Undefined; no Date/Map/Set<sup>20</sup></td><td>✅ Date, bigint, Map, Set, typed arrays<sup>21</sup></td><td>⚠️ Buffer; Date, BigInt via custom types<sup>22</sup></td><td>⚠️ Uint8Array, Long; BigInt via fromObject<sup>23</sup></td><td>✅ Date, BigInt, Map, Buffer</td></tr>
340
344
  <tr><td>Custom validators</td><td>✅ <code>validate</code> on a field and a schema</td><td>✅ field and schema validate<sup>24</sup></td><td>✅ .refine / .superRefine / .check</td><td>✅ check (field), forward+partialCheck (object)</td><td>✅ .narrow() on fields and objects</td><td>✅ .check(makeFilter), refine</td><td>✅ refine(struct, name, fn)</td><td>✅ refinement(), brand()</td><td>✅ withConstraint, withGuard, withAssertion</td><td>✅ withPredicate(fn, msg)</td><td>✅ assert(fn, msg), chain()</td><td>✅ test() on fields and objects</td><td>✅ custom() on any schema</td><td>✅ createRule() + use(), any level</td><td>⚠️ custom decorators per property</td><td>✅ custom keywords (addKeyword)</td><td>✅ Type.Refine on any type</td><td>⚠️ TagBase validate expressions (strings)</td><td>⚠️ only via a LogicalType</td><td>❌ none</td><td>✅ validate; pre('validate') + invalidate</td></tr>
341
345
  <tr><td>Async validators</td><td>✅ <code>checkAsync</code>, run concurrently</td><td>❌ none</td><td>✅ parseAsync; concurrent</td><td>✅ *Async schemas; concurrent<sup>25</sup></td><td>❌ not supported (by design)<sup>26</sup></td><td>✅ Effect getters; concurrency option</td><td>❌ none</td><td>⚠️ experimental TaskDecoder, concurrent<sup>27</sup></td><td>❌ none</td><td>❌ none<sup>28</sup></td><td>❌ none (non-goal)<sup>29</sup></td><td>✅ async test(), concurrent</td><td>⚠️ external(): sequential, after sync rules<sup>30</sup></td><td>⚠️ async rules, in sequence</td><td>✅ async constraints, concurrent<sup>31</sup></td><td>⚠️ $async schemas; awaited one by one</td><td>❌ sync only<sup>32</sup></td><td>❌ none</td><td>❌ none</td><td>❌ none</td><td>✅ async validators, concurrent</td></tr>
342
346
  <tr class="ms-matrix-group"><td colspan="22"><strong>Validation results</strong></td></tr>
@@ -369,7 +373,7 @@ pinned.
369
373
  <tr><td>Derive a schema: pick, omit, partial, extend</td><td>✅ pick, omit, partial (deep), required, extend, keyof (<code>./derive</code>)</td><td>⚠️ Projection kind (pick fields)</td><td>✅ pick, omit, partial, required, extend, deepPartial</td><td>✅ pick, omit, partial, required</td><td>✅ pick, omit, partial, required, merge</td><td>✅ mapFields + Struct.pick/omit/map</td><td>✅ pick, omit, partial, assign</td><td>⚠️ partial, exact, intersection; no pick/omit</td><td>✅ pick, omit, extend, asPartial</td><td>✅ pick, omit, partial (deep), required</td><td>✅ pick, omit, partial, extend, rest</td><td>✅ pick, omit, partial, shape, concat</td><td>✅ keys, append, fork, tailor, concat</td><td>✅ pick, omit, partial, merge(group)</td><td>⚠️ class extends; @nestjs/mapped-types</td><td>⚠️ allOf; ajv-merge-patch $merge/$patch</td><td>✅ Pick, Omit, Partial, Required, Mapped</td><td>✅ TS Pick, Omit, Partial</td><td>❌ none</td><td>❌ none</td><td>✅ pick, omit, add, clone, discriminator</td></tr>
370
374
  <tr><td>A model of many schemas</td><td>✅ <code>Model</code>: order, missing references</td><td>✅ Model: order, missing refs</td><td>❌ none</td><td>❌ none</td><td>⚠️ scope(): resolves names, errors on missing</td><td>❌ none</td><td>❌ none</td><td>❌ none</td><td>❌ none</td><td>❌ none</td><td>❌ none</td><td>❌ none</td><td>❌ none</td><td>❌ none</td><td>❌ none</td><td>⚠️ Ajv instance as $ref registry</td><td>⚠️ Type.Module (named types)</td><td>❌ none</td><td>⚠️ protocols, shared registry</td><td>⚠️ Root: lookup, resolveAll()</td><td>⚠️ mongoose.model() registry</td></tr>
371
375
  <tr class="ms-matrix-group"><td colspan="22"><strong>Evolution</strong></td></tr>
372
- <tr><td>Snapshot of a schema or model</td><td>✅ <code>model.toJSON()</code>, <code>fromJSON</code></td><td>⚠️ schema.toJSON(), fields only</td><td>⚠️ via JSON Schema round trip</td><td>❌ export only, no restore</td><td>✅ .json → type.schema()</td><td>✅ SchemaRepresentation toJson / fromJson</td><td>❌ none</td><td>❌ none</td><td>❌ none</td><td>❌ none</td><td>❌ none</td><td>⚠️ describe(), no restore</td><td>✅ describe() / Joi.build()</td><td>⚠️ toJSON(), no restore</td><td>❌ none</td><td>✅ schemas are JSON</td><td>✅ JSON.stringify; Compile reads it back</td><td>⚠️ export only (json.schema, reflect.schema)</td><td>✅ schema(), JSON.stringify(type)</td><td>✅ root.toJSON() / Root.fromJSON()</td><td>❌ none</td></tr>
376
+ <tr><td>Snapshot of a schema or model</td><td>✅ <code>model.toJSON()</code>, <code>schema.toSnapshot()</code>, <code>fromJSON</code></td><td>⚠️ schema.toJSON(), fields only</td><td>⚠️ via JSON Schema round trip</td><td>❌ export only, no restore</td><td>✅ .json → type.schema()</td><td>✅ SchemaRepresentation toJson / fromJson</td><td>❌ none</td><td>❌ none</td><td>❌ none</td><td>❌ none</td><td>❌ none</td><td>⚠️ describe(), no restore</td><td>✅ describe() / Joi.build()</td><td>⚠️ toJSON(), no restore</td><td>❌ none</td><td>✅ schemas are JSON</td><td>✅ JSON.stringify; Compile reads it back</td><td>⚠️ export only (json.schema, reflect.schema)</td><td>✅ schema(), JSON.stringify(type)</td><td>✅ root.toJSON() / Root.fromJSON()</td><td>❌ none</td></tr>
373
377
  <tr><td>Diff of two versions</td><td>✅ <code>diff</code></td><td>🔜 issue #251 (migrations)</td><td>❌ none</td><td>❌ none</td><td>❌ none</td><td>❌ none</td><td>❌ none</td><td>❌ none</td><td>❌ none</td><td>❌ none</td><td>❌ none</td><td>❌ none</td><td>❌ none</td><td>❌ none</td><td>❌ none</td><td>❌ none</td><td>⚠️ Value.Diff (generic JSON edits)</td><td>❌ none</td><td>❌ none</td><td>❌ none</td><td>❌ none</td></tr>
374
378
  <tr><td>Compatibility of a change</td><td>✅ backward / forward / full</td><td>❌ none</td><td>❌ none</td><td>❌ none</td><td>⚠️ via .extends() / .equals()</td><td>❌ none</td><td>❌ none</td><td>❌ none</td><td>❌ none</td><td>❌ none</td><td>❌ none</td><td>❌ none</td><td>❌ none</td><td>❌ none</td><td>❌ none</td><td>❌ none</td><td>⚠️ Type.Extends (assignability)</td><td>❌ none</td><td>✅ reader/writer resolution<sup>67</sup></td><td>❌ none</td><td>❌ none</td></tr>
375
379
  <tr><td>Field aliases (renames)</td><td>✅ <code>aliases</code>, renamed by <code>parse</code></td><td>❌ none</td><td>❌ none</td><td>❌ none</td><td>❌ none</td><td>⚠️ Schema.encodeKeys (one encoded name)</td><td>❌ none</td><td>❌ none</td><td>❌ none</td><td>❌ none</td><td>❌ none</td><td>✅ object.from(old, new, alias)</td><td>✅ rename(old, new, { alias })</td><td>❌ none</td><td>⚠️ @Expose({ name }) (class-transformer)</td><td>❌ none</td><td>❌ none</td><td>❌ none</td><td>✅ type and field aliases</td><td>⚠️ renames free on the wire</td><td>✅ alias option (virtual)</td></tr>
@@ -481,27 +485,32 @@ TypeScript 5.0 or newer.
481
485
  | Optional | `subtitle: '?string'` or `'subtitle?': 'string'` | the key may be absent, `undefined` or `null` |
482
486
  | Nullable | `parent: { type: 'string', nullable: true }` | the key is required, the value may be `null` |
483
487
  | Long form | `login: { type: 'string', length: [3, 32] }` | a type with options, `type` first |
484
- | Rules | `{ type: 'integer', min: 18, max: 120 }`, `{ type: 'string', pattern: '^[a-z]+$', length: { max: 32 } }` | `min`/`max` for numbers, `length`/`pattern`/`format` for strings, `length` for collections |
488
+ | Rules | `{ type: 'integer', min: 18, max: 120 }`, `{ type: 'string', pattern: '^[a-z]+$', length: { max: 32 } }`, `{ type: 'number', decimals: 2 }` | `min`/`max` for numbers, `decimals` for a number, `length`/`pattern`/`format` for strings, `length` for collections |
485
489
  | Collections | `{ array: 'number' }`, `{ set: 'string' }`, `{ object: { string: 'number' } }`, `{ map: { string: 'string' } }` | |
486
490
  | Enum | `{ enum: ['admin', 'user'] }` | one of the values |
491
+ | Flags | `perms: { flags: ['read', 'write'] }` | an object of those names, each `true` or `false` |
492
+ | Bytes | `avatar: 'bytes'` | a `Uint8Array` (a `Buffer` too) |
487
493
  | Tuple | `point: ['number', 'number']` | a fixed-length array, each element its own definition |
488
494
  | Union | `id: { union: ['string', 'number'] }`, `{ union: [...], discriminator: 'kind' }` | one of several definitions |
489
495
  | Nested struct | `name: { first: 'string', last: 'string' }` | an object whose first key is none of the above |
490
- | Reference | `company: 'Company'`, `{ many: 'Address' }` | another schema in the model: its id for a stored kind, the record for a memory kind |
496
+ | Reference | `company: 'Company'`, `{ many: 'Address' }` | another schema in the model (or the schema itself, by its own name): its id for a stored kind, the record for a memory kind |
491
497
  | Any object | `payload: 'json'` | any non-null object |
492
498
  | Calculated | `ratio: (file) => file.compressed / file.size` | a function, never validated |
493
499
 
494
- The first key of an object decides what it is. Built-in types: `string`, `number`, `integer`,
495
- `bigint`, `boolean`, `date`, `null`, `any`/`unknown`, `enum`, `array`, `set`, `object`, `map`,
496
- `tuple`, `union`, `json`. Rules: `length` (with `unicode: true` for code points), `pattern` and
497
- `format` for strings, `length` for collections, `min`/`max` for numbers; a rule on a type that does not
500
+ The first key of an object decides what it is: a kind when it is a name like `Entity` holding an
501
+ object, so a struct may begin with a capitalized field (`{ DATABASE_URL: 'string', PORT: 'number' }`
502
+ is a struct of two fields). Built-in types: `string`, `number`, `integer`,
503
+ `bigint`, `boolean`, `date`, `bytes`, `null`, `any`/`unknown`, `enum`, `flags`, `array`, `set`,
504
+ `object`, `map`, `tuple`, `union`, `json`. Rules: `length` (with `unicode: true` for code
505
+ points), `pattern` and `format` for strings, `length` for collections, `min`/`max` for numbers,
506
+ `decimals` for a number; a rule on a type that does not
498
507
  take it is a definition error. Fields can add a `validate(value, path)` function, and a schema
499
508
  can have a top-level `validate` for rules across fields. `check(value, options)` takes `root`
500
509
  (the label of the error lines), `maxErrors`, `unknown: 'ignore'` (keys the schema does not have;
501
510
  `{ Struct: { unknown: 'ignore' } }` makes it the schema's default), `references` (`'kind'`,
502
511
  `'embed'` or `'id'`) and `messages` (a locale); the result has `issues`, `errors`, `summary`,
503
512
  `flatten()`, `tree()` and `toJSON()`. `schema.warnings` lints the definition (a mistyped option, a `pattern`
504
- without `length.max`). See [Schema Syntax](https://metaschema.vercel.app/guide/schema-syntax),
513
+ without `length.max`, a field that was read as a kind). See [Schema Syntax](https://metaschema.vercel.app/guide/schema-syntax),
505
514
  [Types](https://metaschema.vercel.app/guide/types),
506
515
  [Unions, nullable and null](https://metaschema.vercel.app/guide/unions),
507
516
  [References](https://metaschema.vercel.app/guide/references) and
@@ -562,7 +571,8 @@ interface User {
562
571
  `register()` adds `model.dts`, `model.toTypeScript` and `schema.toInterface` as methods. The first
563
572
  key of a definition sets
564
573
  its kind and metadata (`Entity`, `Registry`, `Dictionary`, `Journal`, `Details`, `Relation`,
565
- `View`, `Struct`, `Form`, `Projection`, or any custom kind). Stored kinds default to
574
+ `View`, `Struct`, `Form`, `Projection`, or any custom kind: a capitalized name with a lowercase
575
+ letter in it, holding the metadata object). Stored kinds default to
566
576
  `scope: 'application'` and `store: 'persistent'`, and they get an id field; a reference to a
567
577
  stored kind holds its id, a reference to a memory kind embeds the record, in `check` and in the
568
578
  generated types alike. See
@@ -818,6 +828,7 @@ const { FORMATS, register: registerFormats } = require('@alexify/metaschema/form
818
828
  const { pick, omit, partial, required, extend, keyof } = require('@alexify/metaschema/derive'); // and its own register()
819
829
  const { COERCIONS, coerce, register: registerCoercion } = require('@alexify/metaschema/coerce'); // the converters parse runs
820
830
  const { types, toDocument, fromDocument, fromDocumentAsync, indexesOf, checkUpdate, toUpdate } = require('@alexify/metaschema/mongodb'); // and register({ bson })
831
+ const { Schema: Definition } = require('@alexify/metaschema/definition'); // the core's Schema and Model, built and read without validation
821
832
 
822
833
  const en = require('@alexify/metaschema/locales/en'); // the built-in messages
823
834
  const uk = require('@alexify/metaschema/locales/uk'); // schema.check(value, { messages: uk })
package/SECURITY.md CHANGED
@@ -53,7 +53,9 @@ Some things work as intended and are not vulnerabilities:
53
53
  `canEval()` runs `new Function('')` once; under a CSP with a `report-uri` that one violation
54
54
  is reported, and under a report-only policy the probe succeeds and every build is reported. A
55
55
  check the generator cannot build is reported (`compile().error`, `register({ onFallback })`),
56
- never installed. The core entry never calls `new Function`.
56
+ never installed. The core entry never calls `new Function`. The checks are compiled on their
57
+ first use (3.4), so a rule changed on a built field after construction reaches the generator
58
+ too; it reaches the source as a literal or a name of the scope all the same.
57
59
  - **Input shape is checked strictly.** Every key that is not in the schema is reported as
58
60
  unexpected (`has unexpected keys: ...`, the first ten of them), including `constructor`,
59
61
  `__proto__` and `toString`, unless the schema or the call says `unknown: 'ignore'`. Fields
@@ -73,6 +75,27 @@ Some things work as intended and are not vulnerabilities:
73
75
  all the same: those documents are untrusted input for their structure (a keyword outside the
74
76
  subset, a key named `__proto__`, a depth past the limit are errors, never a looser schema),
75
77
  but a pattern in them is the importer's to review or to bound.
78
+ - **A snapshot is data, both ways.** What `schema.toSnapshot()` and `model.toJSON()` return is
79
+ a copy (the `custom` metadata of a kind, the indexes and the `database` metadata included):
80
+ no function, no object of the model, a function as `{ $function: true }`. Read back by
81
+ `fromJSON`, a snapshot is untrusted input: its tags (`$date`, `$bigint`, `$bytes`, `$map`,
82
+ `$set`) are read into values and a tag that does not read is `ERR_INVALID_SNAPSHOT`; a value
83
+ shaped like a `Date` or a `RegExp` (`{ "constructor": { "name": "Date" } }`) is data; its
84
+ `root` names one of its entities; a field key `root` is refused like the methods of a field;
85
+ the walks are bounded (128 levels, and a chain of entities of any length orders without
86
+ recursion). A model restored from a snapshot validates its structure with placeholders for the
87
+ functions, which `model.placeholders` lists.
88
+ - **Binary data is bounded by its `length`.** The `bytes` converter of `./coerce` decodes
89
+ canonical base64 only, in linear time, and leaves a text whose bytes would be over
90
+ `length.max` undecoded, so a field with a `length` caps what a request can make it allocate;
91
+ a `bytes` field without one decodes a text of any size, like a string field without
92
+ `length.max` holds one. `fromDocument` of `./mongodb` reads a generic Binary (subtype 0 or
93
+ 2) into a copy of its bytes and leaves any other subtype to the check.
94
+ - **The definition entry does not validate.** A schema built through
95
+ `@alexify/metaschema/definition` throws `ERR_NOT_REGISTERED` from every way to validate until
96
+ the core entry of the same copy of the package is loaded, and has no `~standard`, so a
97
+ consumer of Standard Schema never takes it for a validator. A schema of another copy (two
98
+ versions of the package installed) does not validate with this copy's core and says so.
76
99
  - **Samples are input.** `infer` of the model subpath walks the values it is given with a depth
77
100
  limit, trusts no key (`__proto__`, `constructor` and the names of the methods of a field are
78
101
  keys of the definition, written as own properties), and checks the definition it built