@alexify/metaschema 1.0.0 → 2.0.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 +228 -1
- package/README.md +124 -28
- package/SECURITY.md +6 -4
- package/index.d.ts +558 -19
- package/package.json +11 -2
- package/src/context.js +95 -0
- package/src/index.js +1 -1
- package/src/issues.js +196 -0
- package/src/lint.js +90 -0
- package/src/locales/en.d.ts +5 -0
- package/src/locales/en.js +58 -0
- package/src/locales/uk.d.ts +5 -0
- package/src/locales/uk.js +57 -0
- package/src/metadata.js +25 -76
- package/src/model.js +23 -7
- package/src/preprocessor.js +42 -19
- package/src/prototypes/abstract.js +86 -49
- package/src/prototypes/collections.js +86 -38
- package/src/prototypes/json.js +9 -5
- package/src/prototypes/reference.js +77 -20
- package/src/prototypes/scalars.js +126 -16
- package/src/prototypes/schema.js +19 -6
- package/src/prototypes/tuple.js +52 -29
- package/src/prototypes/union.js +100 -0
- package/src/result.js +124 -0
- package/src/rules.js +156 -0
- package/src/schema.js +133 -39
- package/src/struct.js +89 -32
- package/src/types.js +9 -3
- package/src/util.js +5 -53
package/CHANGELOG.md
CHANGED
|
@@ -7,6 +7,232 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|
|
7
7
|
|
|
8
8
|
## [Unreleased]
|
|
9
9
|
|
|
10
|
+
## [2.0.0] - 2026-10-10
|
|
11
|
+
|
|
12
|
+
2.0 rewrites the validation core and settles the semantics of the schema language. Every check
|
|
13
|
+
is compiled into a closure when the schema is built and runs in a context of its own; issues
|
|
14
|
+
are data (a code, the path as an array of keys, the params the message is made from), messages
|
|
15
|
+
are rendered through a locale at the end of a check, and `check` takes an options object. The
|
|
16
|
+
first key of a definition decides what it is, numbers are bounded by `min` and `max`, a
|
|
17
|
+
reference follows the kind of its target, and `integer`, `date`, `null`, `any`, `union`,
|
|
18
|
+
`nullable` and `pattern` join the language. TypeScript infers the type of a value from the
|
|
19
|
+
definition (`Infer`), and every schema is a Standard Schema. Everything that changes the shape
|
|
20
|
+
of a result or the meaning of a definition is listed under Upgrading; the rest is additive.
|
|
21
|
+
|
|
22
|
+
### Upgrading from 1.x
|
|
23
|
+
|
|
24
|
+
The same guide with before-and-after examples is
|
|
25
|
+
[Migrating from 1.x](https://metaschema.vercel.app/guide/migrating-from-1).
|
|
26
|
+
|
|
27
|
+
**Validation**
|
|
28
|
+
|
|
29
|
+
- **`check(value, path, options)` → `check(value, options)`.** The root label of the error
|
|
30
|
+
lines is `options.root`: `schema.check(value, 'body', { maxErrors: 1 })` becomes
|
|
31
|
+
`schema.check(value, { root: 'body', maxErrors: 1 })`, and a string in place of the options
|
|
32
|
+
throws a `TypeError` that says so. The options are `root`, `maxErrors`, `unknown`,
|
|
33
|
+
`references` and `messages`.
|
|
34
|
+
- **`issue.path` is an array of keys** (`['tags', 1, 'name']`, what Standard Schema expects),
|
|
35
|
+
not a string, and it never includes the root. `issue.message` describes the problem without
|
|
36
|
+
its location (`is required`) and `issue.params` carries what it was made from
|
|
37
|
+
(`{ expected: 'number', received: 'string' }`); the line with the location is
|
|
38
|
+
`result.errors[i]` (`Field "User.name" is required`), rendered on first use. A key that is
|
|
39
|
+
not an identifier is bracketed (`o["a.b"]`, was `o.a.b`) and a tuple element is addressed by
|
|
40
|
+
index (`point[1]`, was `point(item1)` or `point(y1)` for a named element). A `validate`
|
|
41
|
+
function may return `{ code, message, path, params }` of its own; its `path` (a key or an
|
|
42
|
+
array of keys) is relative to the field (`{ message, path: 'x' }` on `a` reports `a.x`; 1.x
|
|
43
|
+
ignored it).
|
|
44
|
+
- **Unknown keys are one issue per struct**: `{ code: 'unexpected', params: { keys } }` at the
|
|
45
|
+
path of the struct, rendered as `Field "" has unexpected keys: b, c` (was one
|
|
46
|
+
`Field "b" is not expected` per key), and `maxErrors` counts them as one.
|
|
47
|
+
`check(value, { unknown: 'ignore' })` accepts them, and `{ Form: { unknown: 'ignore' }, ... }`
|
|
48
|
+
makes that the default of the schema.
|
|
49
|
+
- **A type failure cancels the rules and `validate` of the field.** A field is checked in the
|
|
50
|
+
order type, rules, `validate`, each step only when the one before it passed; 1.x reported
|
|
51
|
+
`not of expected type: string`, the `length` message and the validator's message together.
|
|
52
|
+
The schema-level `validate` runs after the fields and only when every field passed (it used
|
|
53
|
+
to run first, and always).
|
|
54
|
+
- **`new ValidationResult(path)` → `new ValidationResult(options?)`** (`{ root, messages }`). A
|
|
55
|
+
result a `validate` function returns is relative to its field, so build it with no arguments
|
|
56
|
+
and `add` messages. `ValidationResult.format` is gone;
|
|
57
|
+
`ValidationResult.issuesOf(error, path?, code?)` takes the path as keys.
|
|
58
|
+
- **Cycle detection lives at references.** A value that refers back to itself is reported as
|
|
59
|
+
`circular` where a reference (`'Category'`, `{ many }`) meets it again, as before; a schema
|
|
60
|
+
without references cannot recurse, so such a value is walked as far as the schema goes and
|
|
61
|
+
reported for what it is (unexpected keys, wrong types, or nothing) instead of as `circular`.
|
|
62
|
+
- **The tuple length message** is `exceeds the maximum length` with `params: { max, actual }`
|
|
63
|
+
(was `value length is more than expected in tuple`). The wording of every other message is
|
|
64
|
+
unchanged.
|
|
65
|
+
- **Warnings carry a code**: `Warning [missing-reference]: "Customer" referenced by "Order" is
|
|
66
|
+
not found` (was `Warning: "Customer" ...`), `Warning [recursive-reference]: ...`, and the new
|
|
67
|
+
lint adds `unknown-option`, `unbounded-pattern` and `missing-index-field` to `model.warnings`,
|
|
68
|
+
which is computed on first use.
|
|
69
|
+
- **`field.check(value, context, key)`** is the compiled check of a field and records into the
|
|
70
|
+
context of a check; call `schema.check`. `compile` joins the reserved keys of a field
|
|
71
|
+
definition (`ERR_RESERVED_KEY`).
|
|
72
|
+
|
|
73
|
+
**The schema language**
|
|
74
|
+
|
|
75
|
+
- **The first key of an object decides what it is.** The long form is read only when `type` is
|
|
76
|
+
the first key; a capitalized first key is a kind, a type name is that type's shorthand, and
|
|
77
|
+
any other first key is a nested struct. `{ name: 'string', type: 'string' }` is a struct with
|
|
78
|
+
two fields (1.x read it as a string); `{ required: false, type: 'string' }` throws
|
|
79
|
+
`ERR_INVALID_DEFINITION`. A struct whose first field is called `type`, or named like a type
|
|
80
|
+
(`date`, `null`, `any`, `unknown`, `integer` and `union` are type names now), needs a kind
|
|
81
|
+
(`{ Struct: {}, ... }`) or the `schema` shorthand; `schema.warnings` reports the options such
|
|
82
|
+
a struct would otherwise leave on the type.
|
|
83
|
+
- **`length` on a number is an error.** `number`, `bigint` and the new `integer` are bounded by
|
|
84
|
+
`min` and `max`: `{ type: 'number', length: [18, 120] }` becomes
|
|
85
|
+
`{ type: 'integer', min: 18, max: 120 }`. A `length` there throws `ERR_INVALID_RULE` with
|
|
86
|
+
that hint, and a failed bound is a `range` issue (`is greater than 120`), not `length`
|
|
87
|
+
(`exceeds the maximum length`). Every type lists the rules it accepts, so `min` on a string
|
|
88
|
+
or `length` on a boolean throws too; a custom type opts in with `rules: [...]`, and an alias
|
|
89
|
+
takes the rules of its base. A `length` whose `min` is above its `max` throws
|
|
90
|
+
`ERR_INVALID_LENGTH` (1.x accepted it).
|
|
91
|
+
- **A reference follows the kind of its target.** A reference to a stored kind (`Entity`,
|
|
92
|
+
`Registry`, ...) validates as an id (`employer: 'c1'`, `addresses: ['a1']`) and a reference
|
|
93
|
+
to a memory kind (`Struct`, `Form`, ...) as the record; 1.x always expected the record and
|
|
94
|
+
rejected an id as `not of expected type: object`. Validate a whole graph with
|
|
95
|
+
`check(value, { references: 'embed' })`, rows with `{ references: 'id' }`, or fix one field
|
|
96
|
+
with `embed: true`/`false`. An id never recurses, so a cyclic value through stored kinds is a
|
|
97
|
+
type error, not `circular`. The generated TypeScript follows the same rule, so a memory-kind
|
|
98
|
+
reference renders as its interface (`label: Tag`) instead of `labelId: string`.
|
|
99
|
+
- **`set` renders as `Set<T>`** in the generated TypeScript (it was `T[]` while `check`
|
|
100
|
+
accepted only a `Set`; `map` was already `Map<K, V>`).
|
|
101
|
+
- **The `relations` labels are swapped** to the conventional direction, read from the
|
|
102
|
+
referencing side: a `many` field is `'one-to-many'` and a single reference `'many-to-one'`.
|
|
103
|
+
- **A tuple element may be any definition**, not only a scalar. `[{ x: 'number' }]` is still a
|
|
104
|
+
named number (one key holding a type name); `[{ x: 'number', y: 'number' }]` is a struct
|
|
105
|
+
element (1.x read it as the named number `x` and reported `t(x0)`). `ERR_INVALID_TUPLE` is
|
|
106
|
+
for a definition that is not an array or an element that is a function.
|
|
107
|
+
- **A `Schema` instance as a field keeps its schema-level `validate`** in every form (bare,
|
|
108
|
+
`{ schema }`, the long form); 1.x dropped it, so a value that passed may now fail.
|
|
109
|
+
|
|
110
|
+
**Tooling**
|
|
111
|
+
|
|
112
|
+
- **The typings need TypeScript 5.0 or later.** `Schema` is generic over its definition
|
|
113
|
+
(`Schema<D>`, a const type parameter); `Schema` written on its own is still any schema, and
|
|
114
|
+
`Model.entities` is still a `Map<string, Schema>`.
|
|
115
|
+
- **The bundle is 12.6 KB min+gzip** (1.0 was under 8 KB), and CI gates at 13 KB.
|
|
116
|
+
|
|
117
|
+
### Added
|
|
118
|
+
|
|
119
|
+
- **Static inference.** `Infer<D>` is the TypeScript type of a value `check` accepts for the
|
|
120
|
+
definition type `D`, over every form of the language: scalars (`integer` → `number`, `date`
|
|
121
|
+
→ `Date`, `json` → `unknown`), `'?T'`, `'key?'` and `required: false` as optional properties
|
|
122
|
+
that accept `null`, `nullable: true` as `T | null`, the long form, `array`/`set`/`object`/`map`,
|
|
123
|
+
`enum` as a union of literals, tuples (named elements included), nested structs, `schema`
|
|
124
|
+
and `Schema` instances, `union`, and references as ids (`string`, `string[]`). A kind key,
|
|
125
|
+
index definitions, calculated fields and the schema-level options are not fields. `Schema` is
|
|
126
|
+
`Schema<D>` with a const type parameter, so `Schema.from({ ... })` keeps the literal types of
|
|
127
|
+
an inline definition and `InferSchema<typeof schema>` reads them; a definition declared apart
|
|
128
|
+
needs `as const`. `Infer<D, E>` takes an entity map and resolves a reference to a memory kind
|
|
129
|
+
(or `embed: true`) as the record and a projection as its parent's fields;
|
|
130
|
+
`InferEntity<E, 'Name'>` adds the id field of a stored kind. Custom types are declared for
|
|
131
|
+
inference through module augmentation of `CustomTypes`; an unknown name infers as `unknown`.
|
|
132
|
+
- **Standard Schema v1.** Every `Schema` exposes `schema['~standard']`
|
|
133
|
+
(`{ version: 1, vendor: 'alexify.metaschema', validate }`), the interface tRPC, TanStack Form,
|
|
134
|
+
Hono and the other consumers of [standardschema.dev](https://standardschema.dev) accept
|
|
135
|
+
without an adapter. `validate(value)` is `check(value)` read as the specification does:
|
|
136
|
+
`{ value }` (the same reference) or `{ issues }`, the issues of the result themselves
|
|
137
|
+
(`message` and an array `path`, plus `code` and `params`); the `libraryOptions` of a call are
|
|
138
|
+
the options of `check`. The accessor lives on the prototype and stays out of `toJSON` and
|
|
139
|
+
`Object.keys`. The typings declare it as `StandardProps<D>` (with `StandardResult<T>` and
|
|
140
|
+
`StandardOptions`), and a `Schema<D>` is a `StandardSchemaV1<Infer<D>, Infer<D>>` of
|
|
141
|
+
`@standard-schema/spec`, which the package does not depend on.
|
|
142
|
+
- **New built-in types.** `integer` (`Number.isInteger`), `date` (a `Date` with a valid time),
|
|
143
|
+
`null`, `any` and `unknown` (one type under two names, differing in the TypeScript they
|
|
144
|
+
render), and `union`: `{ union: ['string', 'number'] }` keeps the first branch that reports
|
|
145
|
+
nothing; `{ union: [...], discriminator: 'kind' }` picks the branch from an enum field in one
|
|
146
|
+
lookup, built when the schema is built, and reports an unknown value as one `union` issue at
|
|
147
|
+
the discriminator's path. A definition that cannot discriminate throws `ERR_INVALID_UNION`.
|
|
148
|
+
- **`nullable: true`**: a required key whose value may be `null`, apart from optional (`'?type'`,
|
|
149
|
+
`undefined` or `null`). It applies to any type, skips the rules and `validate` for `null`,
|
|
150
|
+
and renders as `T | null`.
|
|
151
|
+
- **`min` and `max`** for `number`, `integer` and `bigint`, as numbers or bigints compared
|
|
152
|
+
exactly (never through `Number`), with the `range` issue `{ min, max, actual }`.
|
|
153
|
+
- **`pattern`** for strings, a string or a `RegExp` compiled once with the `u` flag (and without
|
|
154
|
+
`g`/`y`), with the `pattern` issue `{ pattern }`; the validation guide has a section on ReDoS.
|
|
155
|
+
- **`unicode: true`** measures a string's `length` in code points instead of UTF-16 units.
|
|
156
|
+
- **The unknown-keys policy as metadata**: `{ Form: { unknown: 'ignore' }, ... }` is the default
|
|
157
|
+
of that schema's `check`; the option of a call still wins.
|
|
158
|
+
- **`check` options** `root`, `maxErrors`, `unknown` (`'reject'` | `'ignore'`), `references`
|
|
159
|
+
(`'kind'`, `'embed'`, `'id'`) and `messages`, validated when the check starts, and the field
|
|
160
|
+
option `embed` on a reference.
|
|
161
|
+
- **Issues with params.** `result.issues` is `{ code, path, message, params }`:
|
|
162
|
+
`type { expected, received }` (plus `key` for a wrong key type in an `object` or `map`),
|
|
163
|
+
`unexpected { keys }`, `enum { values }`, `length { min, max, actual }`,
|
|
164
|
+
`range { min, max, actual }`, `pattern { pattern }`, `union { expected, discriminator }`,
|
|
165
|
+
`reference { entity }`, `exception { error }`.
|
|
166
|
+
- **Locales.** Messages are rendered once, at the end of a check, from the code and params of
|
|
167
|
+
each issue through `options.messages`: a locale table (partial tables fall back to English) or
|
|
168
|
+
a function. English is built in, Ukrainian is exported as `@alexify/metaschema/locales/uk`
|
|
169
|
+
(and English as `@alexify/metaschema/locales/en`).
|
|
170
|
+
- **`result.summary`, `result.flatten()` and `result.tree()`** for CLIs and forms, and
|
|
171
|
+
`result.errors` as a lazy view rendered on first use.
|
|
172
|
+
- **Definition lint.** `schema.warnings` reports an option the field's type does not read
|
|
173
|
+
(`unknown-option`; `default`, `unique`, `index`, `primary`, `title`, `description`, `examples`
|
|
174
|
+
and `deprecated` are known annotations), a `pattern` without `length.max`
|
|
175
|
+
(`unbounded-pattern`) and an index over a missing field (`missing-index-field`);
|
|
176
|
+
`model.warnings` adds `missing-reference`, `missing-type` and `recursive-reference`. Both are
|
|
177
|
+
computed on first use.
|
|
178
|
+
- **Definition error codes** `ERR_INVALID_RULE` and `ERR_INVALID_UNION`.
|
|
179
|
+
- **Types**: `Infer`, `InferSchema`, `InferEntity`, `CustomTypes`, `StandardProps`,
|
|
180
|
+
`StandardResult`, `StandardOptions`, `IssueParams`, `IssueOf<Code>`, `Locale`, `Messages`,
|
|
181
|
+
`ResultOptions`, `FlatIssues`, `IssueTree` and `CheckContext`; `ValidationIssue` is a union by
|
|
182
|
+
code; `FieldType.nullable` and `embed`, `Schema.unknown` and `warnings`,
|
|
183
|
+
`CheckOptions.references` and `KindMetadata.unknown`.
|
|
184
|
+
- **Benchmarks**: the four modes of the typescript-runtime-type-benchmarks suite (`parseSafe`,
|
|
185
|
+
`parseStrict`, `assertLoose`, `assertStrict`) over its object, flat and nested, next to the
|
|
186
|
+
`check`, `Schema.from` and `Model` scenarios.
|
|
187
|
+
|
|
188
|
+
### Changed
|
|
189
|
+
|
|
190
|
+
- **Validation is compiled.** `createStruct` builds a frozen plan and a dictionary of known keys
|
|
191
|
+
and compiles the struct check as an index loop over the plan; every field's `check` is a
|
|
192
|
+
closure chosen when the field is built (one `typeof` for a scalar without rules, a `Set` for
|
|
193
|
+
an `enum` with more than eight values, `Map` and `Set` iterated directly, `object` through
|
|
194
|
+
`for...in`, a lookup plus cycle tracking for a reference), and `Object.hasOwn` is consulted
|
|
195
|
+
only for a required field set to `undefined` or a field named after a member of
|
|
196
|
+
`Object.prototype`. A check runs in a context of its own
|
|
197
|
+
(`{ issues, count, limit, path, seen, unknown, references, root, messages }`) instead of
|
|
198
|
+
module globals, so two checks can no longer interfere and a validator may run another check.
|
|
199
|
+
On the benchmark of the repository (Node 24, the same machine) `check` goes from 2.1 M to
|
|
200
|
+
10.7 M ops/s for a valid flat value and from 0.87 M to 3.5 M for an invalid one, nested from
|
|
201
|
+
0.33 M to 2.7 M; construction stays where it was. See
|
|
202
|
+
[Performance](https://metaschema.vercel.app/guide/performance).
|
|
203
|
+
- **Generated TypeScript** follows the language: `integer` → `number`, `date` → `Date`, `null`,
|
|
204
|
+
`any`, `unknown`, a `union` as `A | B`, a nullable field as `T | null`, a `set` as `Set<T>`, a
|
|
205
|
+
reference by the kind of its target (see Upgrading).
|
|
206
|
+
- **Construction** reads the first key of a definition once, re-parses a projection's fields
|
|
207
|
+
from their definitions so the copies belong to the projection, and lints on first use of
|
|
208
|
+
`warnings`.
|
|
209
|
+
|
|
210
|
+
### Removed
|
|
211
|
+
|
|
212
|
+
- **The positional root path of `check`** and **`ValidationResult.format`** (see Upgrading).
|
|
213
|
+
- **`length` on `number` and `bigint`**, replaced by `min` and `max` (see Upgrading).
|
|
214
|
+
- **Module-level validation state.** Nothing in the package is global to a check any more; the
|
|
215
|
+
type registry is still process-wide, as before.
|
|
216
|
+
|
|
217
|
+
### Fixed
|
|
218
|
+
|
|
219
|
+
- **A `Schema` instance used as a field lost its schema-level `validate`** (see Upgrading).
|
|
220
|
+
- **A `length` whose `min` is above its `max`**, which could never pass, is rejected when the
|
|
221
|
+
schema is built instead of failing every value.
|
|
222
|
+
- **A `bigint` bound is compared exactly.** `length` on a `bigint` went through `Number` and
|
|
223
|
+
lost precision past 2^53; `min` and `max` compare a bigint bound as a bigint.
|
|
224
|
+
|
|
225
|
+
### Tooling
|
|
226
|
+
|
|
227
|
+
- `pnpm size --max-gzip 13` is the CI gate (the entries are 12.6 KB min+gzip).
|
|
228
|
+
- `pnpm bench` reads the clock once per hundred calls and calls `check` through a megamorphic
|
|
229
|
+
site, so it is measured as a callee instead of being inlined into the measuring loop;
|
|
230
|
+
`bench/baseline.json` is the snapshot of this branch.
|
|
231
|
+
- `@standard-schema/spec` is a devDependency, used only by `tests/types/standard.test-d.ts`.
|
|
232
|
+
- New test suites: `context`, `issues`, `result`, `check-options`, `syntax`, `numbers`,
|
|
233
|
+
`pattern`, `nullable`, `values`, `union`, `references`, `lint`, `standard`, and
|
|
234
|
+
`tests/types/infer.test-d.ts`, which also compiles the examples of the TypeScript guide.
|
|
235
|
+
|
|
10
236
|
## [1.0.0] - 2026-10-09
|
|
11
237
|
|
|
12
238
|
The first release of `@alexify/metaschema`. It is a fork of
|
|
@@ -417,7 +643,8 @@ published.
|
|
|
417
643
|
|
|
418
644
|
### [metaschema 0.x][upstream-0.x] - First generation of metaschema
|
|
419
645
|
|
|
420
|
-
[unreleased]: https://github.com/Alexis-Technologies/metaschema/compare/
|
|
646
|
+
[unreleased]: https://github.com/Alexis-Technologies/metaschema/compare/v2.0.0...HEAD
|
|
647
|
+
[2.0.0]: https://github.com/Alexis-Technologies/metaschema/compare/v1.0.0...v2.0.0
|
|
421
648
|
[1.0.0]: https://github.com/Alexis-Technologies/metaschema/releases/tag/v1.0.0
|
|
422
649
|
[upstream-2.2.2]: https://github.com/metarhia/metaschema/compare/v2.2.1...v2.2.2
|
|
423
650
|
[upstream-2.2.1]: https://github.com/metarhia/metaschema/compare/v2.2.0...v2.2.1
|
package/README.md
CHANGED
|
@@ -21,12 +21,21 @@ const user = new Schema('User', {
|
|
|
21
21
|
roles: { array: { enum: ['admin', 'editor', 'viewer'] } },
|
|
22
22
|
});
|
|
23
23
|
|
|
24
|
-
user.check({ name: { first: 'Marcus' }, email: 'm@r', roles: ['owner'] })
|
|
24
|
+
const result = user.check({ name: { first: 'Marcus' }, email: 'm@r', roles: ['owner'] });
|
|
25
|
+
|
|
26
|
+
result.errors;
|
|
25
27
|
// [
|
|
26
28
|
// 'Field "User.name.last" is required',
|
|
27
29
|
// 'Field "User.email" value is too short',
|
|
28
30
|
// 'Field "User.roles[0]" value is not of enum: admin, editor, viewer'
|
|
29
31
|
// ]
|
|
32
|
+
|
|
33
|
+
result.issues;
|
|
34
|
+
// [
|
|
35
|
+
// { code: 'required', path: ['name', 'last'], message: 'is required', params: {} },
|
|
36
|
+
// { code: 'length', path: ['email'], message: 'value is too short', params: { min: 5, max: 64, actual: 3 } },
|
|
37
|
+
// { code: 'enum', path: ['roles', 0], message: 'value is not of enum: admin, editor, viewer', params: { values: ['admin', 'editor', 'viewer'] } }
|
|
38
|
+
// ]
|
|
30
39
|
```
|
|
31
40
|
|
|
32
41
|
### 📖 [Read the documentation →](https://metaschema.vercel.app/)
|
|
@@ -36,14 +45,23 @@ user.check({ name: { first: 'Marcus' }, email: 'm@r', roles: ['owner'] }).errors
|
|
|
36
45
|
- **Compact syntax.** `'?string'` is an optional string, `'tags?'` an optional key,
|
|
37
46
|
`{ array: 'number' }` an array, `['number', 'number']` a tuple, `'Company'` a reference. The
|
|
38
47
|
long form (`{ type: 'string', length: [3, 32] }`) is there when a field needs options.
|
|
39
|
-
- **Errors, not exceptions.** `check` walks the whole value and returns every problem
|
|
40
|
-
path
|
|
48
|
+
- **Errors, not exceptions.** `check` walks the whole value and returns every problem as data:
|
|
49
|
+
a code, the path as an array of keys, the params it was made from, and a message rendered through
|
|
50
|
+
a locale (English built in, `@alexify/metaschema/locales/uk` shipped). Only a broken definition
|
|
51
|
+
throws.
|
|
41
52
|
- **Domain models.** Entities, registries, dictionaries and projections, with references,
|
|
42
53
|
relations and indexes, ordered by dependency and checked for missing references.
|
|
43
|
-
- **TypeScript.**
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
54
|
+
- **TypeScript.** `InferSchema<typeof schema>` is the type of a value the schema accepts,
|
|
55
|
+
computed from the definition with nothing generated, and a model renders its entities as
|
|
56
|
+
interfaces. The package ships hand-written typings for its own API.
|
|
57
|
+
- **Standard Schema.** Every schema implements [Standard Schema v1](https://standardschema.dev)
|
|
58
|
+
(`schema['~standard']`), so tRPC, TanStack Form, Hono and any other consumer of the interface
|
|
59
|
+
take it as they take a zod or valibot schema.
|
|
60
|
+
- **Fast.** Every check is compiled into a closure when the schema is built and runs in a context
|
|
61
|
+
of its own: about 10 million validations a second of a flat struct on Node 24 (`pnpm bench`,
|
|
62
|
+
see [Performance](https://metaschema.vercel.app/guide/performance)).
|
|
63
|
+
- **Zero dependencies, 12.6 KB min+gzip.** CommonJS with ESM named imports, no build step,
|
|
64
|
+
one package for Node.js and browsers.
|
|
47
65
|
|
|
48
66
|
## Installation
|
|
49
67
|
|
|
@@ -53,27 +71,41 @@ pnpm add @alexify/metaschema
|
|
|
53
71
|
npm install @alexify/metaschema
|
|
54
72
|
```
|
|
55
73
|
|
|
56
|
-
Requires Node.js 18 or newer. Works in browsers through any bundler.
|
|
74
|
+
Requires Node.js 18 or newer. Works in browsers through any bundler. The typings need
|
|
75
|
+
TypeScript 5.0 or newer.
|
|
57
76
|
|
|
58
77
|
## Schema syntax
|
|
59
78
|
|
|
60
79
|
| Form | Example | Meaning |
|
|
61
80
|
| --- | --- | --- |
|
|
62
81
|
| Type name | `title: 'string'` | a required string |
|
|
63
|
-
| Optional | `subtitle: '?string'` or `'subtitle?': 'string'` | `undefined`
|
|
64
|
-
|
|
|
82
|
+
| Optional | `subtitle: '?string'` or `'subtitle?': 'string'` | the key may be absent, `undefined` or `null` |
|
|
83
|
+
| Nullable | `parent: { type: 'string', nullable: true }` | the key is required, the value may be `null` |
|
|
84
|
+
| Long form | `login: { type: 'string', length: [3, 32] }` | a type with options, `type` first |
|
|
85
|
+
| Rules | `{ type: 'integer', min: 18, max: 120 }`, `{ type: 'string', pattern: '^[a-z]+$', length: { max: 32 } }` | `min`/`max` for numbers, `length`/`pattern` for strings, `length` for collections |
|
|
65
86
|
| Collections | `{ array: 'number' }`, `{ set: 'string' }`, `{ object: { string: 'number' } }`, `{ map: { string: 'string' } }` | |
|
|
66
87
|
| Enum | `{ enum: ['admin', 'user'] }` | one of the values |
|
|
67
|
-
| Tuple | `point: ['number', 'number']` | a fixed-length array
|
|
68
|
-
|
|
|
69
|
-
|
|
|
88
|
+
| Tuple | `point: ['number', 'number']` | a fixed-length array, each element its own definition |
|
|
89
|
+
| Union | `id: { union: ['string', 'number'] }`, `{ union: [...], discriminator: 'kind' }` | one of several definitions |
|
|
90
|
+
| Nested struct | `name: { first: 'string', last: 'string' }` | an object whose first key is none of the above |
|
|
91
|
+
| Reference | `company: 'Company'`, `{ many: 'Address' }` | another schema in the model: its id for a stored kind, the record for a memory kind |
|
|
70
92
|
| Any object | `payload: 'json'` | any non-null object |
|
|
71
93
|
| Calculated | `ratio: (file) => file.compressed / file.size` | a function, never validated |
|
|
72
94
|
|
|
73
|
-
Built-in types: `string`, `number`, `
|
|
74
|
-
`
|
|
75
|
-
|
|
76
|
-
|
|
95
|
+
The first key of an object decides what it is. Built-in types: `string`, `number`, `integer`,
|
|
96
|
+
`bigint`, `boolean`, `date`, `null`, `any`/`unknown`, `enum`, `array`, `set`, `object`, `map`,
|
|
97
|
+
`tuple`, `union`, `json`. Rules: `length` (with `unicode: true` for code points) and `pattern`
|
|
98
|
+
for strings, `length` for collections, `min`/`max` for numbers; a rule on a type that does not
|
|
99
|
+
take it is a definition error. Fields can add a `validate(value, path)` function, and a schema
|
|
100
|
+
can have a top-level `validate` for rules across fields. `check(value, options)` takes `root`
|
|
101
|
+
(the label of the error lines), `maxErrors`, `unknown: 'ignore'` (keys the schema does not have;
|
|
102
|
+
`{ Struct: { unknown: 'ignore' } }` makes it the schema's default), `references` (`'kind'`,
|
|
103
|
+
`'embed'` or `'id'`) and `messages` (a locale); the result has `issues`, `errors`, `summary`,
|
|
104
|
+
`flatten()` and `tree()`. `schema.warnings` lints the definition (a mistyped option, a `pattern`
|
|
105
|
+
without `length.max`). See [Schema Syntax](https://metaschema.vercel.app/guide/schema-syntax),
|
|
106
|
+
[Types](https://metaschema.vercel.app/guide/types),
|
|
107
|
+
[Unions, nullable and null](https://metaschema.vercel.app/guide/unions),
|
|
108
|
+
[References](https://metaschema.vercel.app/guide/references) and
|
|
77
109
|
[Validation](https://metaschema.vercel.app/guide/validation).
|
|
78
110
|
|
|
79
111
|
## Domain models
|
|
@@ -96,7 +128,9 @@ const entities = new Map([
|
|
|
96
128
|
const model = new Model(types, entities);
|
|
97
129
|
|
|
98
130
|
model.order; // Set { 'Address', 'Company', 'User' }
|
|
99
|
-
model.warnings; // [] (
|
|
131
|
+
model.warnings; // [] (lint and consistency warnings, `Warning [code]: text`, end up here)
|
|
132
|
+
model.entities.get('User').check({ login: 'ab', company: 'c1', active: true }).errors;
|
|
133
|
+
// [ 'Field "User.login" value is too short' ]
|
|
100
134
|
console.log(model.dts);
|
|
101
135
|
```
|
|
102
136
|
|
|
@@ -125,11 +159,53 @@ interface User {
|
|
|
125
159
|
`saveTypes(outputFile, model)` writes `model.dts` to a file. The first key of a definition sets
|
|
126
160
|
its kind and metadata (`Entity`, `Registry`, `Dictionary`, `Journal`, `Details`, `Relation`,
|
|
127
161
|
`View`, `Struct`, `Form`, `Projection`, or any custom kind). Stored kinds default to
|
|
128
|
-
`scope: 'application'` and `store: 'persistent'`, and they get an id field
|
|
162
|
+
`scope: 'application'` and `store: 'persistent'`, and they get an id field; a reference to a
|
|
163
|
+
stored kind holds its id, a reference to a memory kind embeds the record, in `check` and in the
|
|
164
|
+
generated types alike. See
|
|
129
165
|
[Kinds and Metadata](https://metaschema.vercel.app/guide/kinds-and-metadata),
|
|
130
166
|
[Custom Types](https://metaschema.vercel.app/guide/custom-types) and
|
|
131
167
|
[Domain Models](https://metaschema.vercel.app/guide/model).
|
|
132
168
|
|
|
169
|
+
## TypeScript
|
|
170
|
+
|
|
171
|
+
A schema keeps its definition as a type parameter, and `InferSchema` turns it into the type of
|
|
172
|
+
a value `check` accepts; `Infer<typeof definition>` does the same for a definition declared
|
|
173
|
+
`as const`:
|
|
174
|
+
|
|
175
|
+
```ts
|
|
176
|
+
import { Schema, type InferSchema } from '@alexify/metaschema';
|
|
177
|
+
|
|
178
|
+
const user = Schema.from({
|
|
179
|
+
name: 'string',
|
|
180
|
+
age: '?number',
|
|
181
|
+
role: { enum: ['admin', 'user'] },
|
|
182
|
+
tags: { array: 'string' },
|
|
183
|
+
address: { city: 'string', 'street?': 'string' },
|
|
184
|
+
point: ['number', 'number'],
|
|
185
|
+
});
|
|
186
|
+
|
|
187
|
+
type User = InferSchema<typeof user>;
|
|
188
|
+
// {
|
|
189
|
+
// name: string;
|
|
190
|
+
// age?: number | null | undefined;
|
|
191
|
+
// role: 'admin' | 'user';
|
|
192
|
+
// tags: string[];
|
|
193
|
+
// address: { city: string; street?: string | null | undefined };
|
|
194
|
+
// point: [number, number];
|
|
195
|
+
// }
|
|
196
|
+
```
|
|
197
|
+
|
|
198
|
+
Every form of the language is covered: optional and nullable fields, collections, enums,
|
|
199
|
+
tuples, unions, nested structs, references (an id, or the record through an entity map with
|
|
200
|
+
`Infer<D, E>` and `InferEntity<E, 'Name'>`) and custom types declared through module
|
|
201
|
+
augmentation of `CustomTypes`. A model renders its entities as interfaces with `model.dts`. See
|
|
202
|
+
[TypeScript](https://metaschema.vercel.app/guide/typescript).
|
|
203
|
+
|
|
204
|
+
A `Schema<D>` is also a `StandardSchemaV1<Infer<D>, Infer<D>>` of `@standard-schema/spec`:
|
|
205
|
+
`schema['~standard']` is typed as `StandardProps<D>`, with `StandardResult<T>` and
|
|
206
|
+
`StandardOptions` beside it. See
|
|
207
|
+
[Standard Schema](https://metaschema.vercel.app/guide/standard-schema).
|
|
208
|
+
|
|
133
209
|
## Exports
|
|
134
210
|
|
|
135
211
|
```js
|
|
@@ -137,33 +213,53 @@ const {
|
|
|
137
213
|
KIND, KIND_STORED, KIND_MEMORY, SCOPE, STORE, ALLOW,
|
|
138
214
|
getKindMetadata, saveTypes, Schema, Model, SchemaDefinitionError, ValidationResult,
|
|
139
215
|
} = require('@alexify/metaschema');
|
|
216
|
+
|
|
217
|
+
const en = require('@alexify/metaschema/locales/en'); // the built-in messages
|
|
218
|
+
const uk = require('@alexify/metaschema/locales/uk'); // schema.check(value, { messages: uk })
|
|
140
219
|
```
|
|
141
220
|
|
|
142
221
|
```js
|
|
143
222
|
import { Schema, Model } from '@alexify/metaschema';
|
|
223
|
+
import type { Infer, InferSchema, InferEntity, CustomTypes, ValidationIssue } from '@alexify/metaschema';
|
|
144
224
|
```
|
|
145
225
|
|
|
146
226
|
In the browser every export works the same, except `saveTypes`, which rejects because there is no
|
|
147
|
-
file system. The [API reference](https://metaschema.vercel.app/api/exports) lists every member
|
|
227
|
+
file system. The [API reference](https://metaschema.vercel.app/api/exports) lists every member
|
|
228
|
+
and every exported type.
|
|
229
|
+
|
|
230
|
+
## Migrating
|
|
231
|
+
|
|
232
|
+
### From 1.x
|
|
233
|
+
|
|
234
|
+
2.0 changes the shape of a result (`issue.path` is an array of keys, `issue.message` has no
|
|
235
|
+
location, unknown keys are one issue per struct), the signature of `check`
|
|
236
|
+
(`check(value, { root, maxErrors, unknown, references, messages })`), and a few rules of the
|
|
237
|
+
language: the first key of an object decides what it is, numbers are bounded by `min`/`max`
|
|
238
|
+
instead of `length`, a reference to a stored kind is its id, a `set` renders as `Set<T>`, the
|
|
239
|
+
`relations` labels follow the referencing side, and a type failure cancels the rules and
|
|
240
|
+
`validate` of the field. Everything else is additive: `integer`, `date`, `null`, `any`, `union`,
|
|
241
|
+
`nullable`, `pattern`, locales, the lint, `Infer` and Standard Schema. The step-by-step guide
|
|
242
|
+
with before-and-after examples is
|
|
243
|
+
[Migrating from 1.x](https://metaschema.vercel.app/guide/migrating-from-1); the full list is
|
|
244
|
+
under "Upgrading from 1.x" in the [CHANGELOG](./CHANGELOG.md).
|
|
148
245
|
|
|
149
|
-
|
|
246
|
+
### From `metaschema` (metarhia)
|
|
150
247
|
|
|
151
|
-
`@alexify/metaschema` is a fork of [`metaschema`](https://github.com/metarhia/metaschema) 2.2
|
|
152
|
-
|
|
248
|
+
`@alexify/metaschema` is a fork of [`metaschema`](https://github.com/metarhia/metaschema) 2.2 with
|
|
249
|
+
the same schema language. What changed in 1.0:
|
|
153
250
|
|
|
154
251
|
- **No loader.** `createSchema`, `loadSchema`, `readDirectory` and `loadModel` are removed along
|
|
155
252
|
with the `metavm` sandbox. Use `new Schema(name, require('./schemas/User.js'))` and
|
|
156
253
|
`new Model(types, new Map([...]), database)`. Schema files written as `({ ... })` become modules
|
|
157
254
|
(`module.exports = { ... }`).
|
|
158
255
|
- **No runtime dependencies:** `metautil`, `metavm` and `metaskills` are gone.
|
|
159
|
-
- **Fixed messages, no old text kept:** `Field "..."` instead of `Filed "..."
|
|
160
|
-
`not of expected type: object` instead of `is not a object
|
|
161
|
-
"more then".
|
|
256
|
+
- **Fixed messages, no old text kept:** `Field "..."` instead of `Filed "..."` and
|
|
257
|
+
`not of expected type: object` instead of `is not a object`.
|
|
162
258
|
- **`detouch` is renamed to `detach`**, with no alias.
|
|
163
259
|
- **`browser.js`** replaces `dist.js`, and an `exports` map closes deep imports.
|
|
164
260
|
|
|
165
|
-
The full list is in [Migrating from metarhia](https://metaschema.vercel.app/guide/migrating-from-metarhia)
|
|
166
|
-
and the
|
|
261
|
+
The full list is in [Migrating from metarhia](https://metaschema.vercel.app/guide/migrating-from-metarhia),
|
|
262
|
+
and the 2.0 changes above apply on top of it.
|
|
167
263
|
|
|
168
264
|
## Changelog
|
|
169
265
|
|
package/SECURITY.md
CHANGED
|
@@ -6,7 +6,8 @@ Only the latest published version receives fixes.
|
|
|
6
6
|
|
|
7
7
|
| Version | Supported |
|
|
8
8
|
|---|---|
|
|
9
|
-
|
|
|
9
|
+
| 2.x | ✅ |
|
|
10
|
+
| 1.x | ❌ |
|
|
10
11
|
| `metaschema` (metarhia) 2.x | ❌ (report upstream) |
|
|
11
12
|
|
|
12
13
|
## Reporting a vulnerability
|
|
@@ -38,11 +39,12 @@ Some things work as intended and are not vulnerabilities:
|
|
|
38
39
|
files, evaluate source strings or run a sandbox. Turning untrusted input into a schema definition
|
|
39
40
|
is the application's decision and responsibility.
|
|
40
41
|
- **Input shape is checked strictly.** Every key that is not in the schema is reported as
|
|
41
|
-
`
|
|
42
|
+
unexpected (`has unexpected keys: ...`), including `constructor`, `__proto__` and `toString`,
|
|
43
|
+
unless the schema or the call says `unknown: 'ignore'`. Fields live in a
|
|
42
44
|
null-prototype dictionary, so nothing on `Object.prototype` is ever read as a field, and
|
|
43
45
|
metaschema never writes to the value it checks.
|
|
44
|
-
- **Validation errors are data.** `check` collects problems as
|
|
45
|
-
input. The messages contain field paths (which can include key names taken from the input,
|
|
46
|
+
- **Validation errors are data.** `check` collects problems as issues (a code, a path and params,
|
|
47
|
+
with a rendered message) instead of throwing on bad input. The messages contain field paths (which can include key names taken from the input,
|
|
46
48
|
truncated to 100 characters) and, for `enum`, the allowed values; they never contain the
|
|
47
49
|
rejected values themselves. A message
|
|
48
50
|
from a custom `validate` function, or from an exception it throws, is passed through as written.
|