@alexify/metaschema 1.0.0 → 3.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 +551 -1
- package/README.md +235 -34
- package/SECURITY.md +32 -11
- package/index.d.ts +798 -23
- package/package.json +30 -6
- package/src/codec.js +490 -0
- package/src/compile/code.js +92 -0
- package/src/compile/emit.js +512 -0
- package/src/compile/index.d.ts +38 -0
- package/src/compile/index.js +176 -0
- package/src/context.js +141 -0
- package/src/errors.js +10 -1
- package/src/generators/index.d.ts +29 -0
- package/src/generators/index.js +90 -0
- package/src/generators/jsonschema.js +535 -0
- package/src/generators/typescript.js +237 -0
- package/src/index.js +1 -3
- package/src/issues.js +291 -0
- package/src/kinds.js +9 -12
- package/src/lint.js +98 -0
- package/src/locales/en.d.ts +5 -0
- package/src/locales/en.js +66 -0
- package/src/locales/uk.d.ts +5 -0
- package/src/locales/uk.js +62 -0
- package/src/metadata.js +65 -119
- package/src/metautil.js +8 -1
- package/src/model.js +31 -20
- package/src/preprocessor.js +45 -27
- package/src/prototypes/abstract.js +101 -51
- package/src/prototypes/collections.js +106 -41
- package/src/prototypes/json.js +9 -5
- package/src/prototypes/reference.js +91 -20
- package/src/prototypes/scalars.js +124 -16
- package/src/prototypes/schema.js +31 -6
- package/src/prototypes/tuple.js +57 -29
- package/src/prototypes/union.js +139 -0
- package/src/result.js +115 -0
- package/src/rules.js +185 -0
- package/src/runtime/browser.js +2 -2
- package/src/runtime/node.js +4 -2
- package/src/schema.js +181 -68
- package/src/struct.js +101 -33
- package/src/types.js +14 -14
- package/src/util.js +41 -50
package/README.md
CHANGED
|
@@ -21,12 +21,29 @@ 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
|
+
// ]
|
|
39
|
+
|
|
40
|
+
const event = Schema.from({
|
|
41
|
+
name: 'string',
|
|
42
|
+
'level?': { type: 'integer', default: 1 },
|
|
43
|
+
when: { type: 'string', parse: (text) => new Date(text) },
|
|
44
|
+
});
|
|
45
|
+
event.parse({ name: 'deploy', when: '2026-10-10T12:00:00.000Z' }).value;
|
|
46
|
+
// { name: 'deploy', when: 2026-10-10T12:00:00.000Z, level: 1 }
|
|
30
47
|
```
|
|
31
48
|
|
|
32
49
|
### 📖 [Read the documentation →](https://metaschema.vercel.app/)
|
|
@@ -36,14 +53,35 @@ user.check({ name: { first: 'Marcus' }, email: 'm@r', roles: ['owner'] }).errors
|
|
|
36
53
|
- **Compact syntax.** `'?string'` is an optional string, `'tags?'` an optional key,
|
|
37
54
|
`{ array: 'number' }` an array, `['number', 'number']` a tuple, `'Company'` a reference. The
|
|
38
55
|
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
|
|
56
|
+
- **Errors, not exceptions.** `check` walks the whole value and returns every problem as data:
|
|
57
|
+
a code, the path as an array of keys, the params it was made from, and a message rendered through
|
|
58
|
+
a locale (English built in, `@alexify/metaschema/locales/uk` shipped). Only a broken definition
|
|
59
|
+
throws.
|
|
60
|
+
- **Parse, not only a verdict.** `parse` runs the same check and gives the value of the program:
|
|
61
|
+
defaults filled in, unknown keys stripped on request, a field's `parse` function decoding its
|
|
62
|
+
value (a date-time string into a `Date`) and `serialize` the way back; `checkAsync` and
|
|
63
|
+
`parseAsync` await validators and decoders that return promises.
|
|
41
64
|
- **Domain models.** Entities, registries, dictionaries and projections, with references,
|
|
42
65
|
relations and indexes, ordered by dependency and checked for missing references.
|
|
43
|
-
- **TypeScript.**
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
66
|
+
- **TypeScript.** `InferSchema<typeof schema>` is the type of a value the schema accepts,
|
|
67
|
+
computed from the definition with nothing generated, and a model renders its entities as
|
|
68
|
+
interfaces. The package ships hand-written typings for its own API.
|
|
69
|
+
- **Standard Schema.** Every schema implements [Standard Schema v1](https://standardschema.dev)
|
|
70
|
+
(`schema['~standard']`, which is `parse`), so tRPC, TanStack Form, Hono and any other consumer
|
|
71
|
+
of the interface take it as they take a zod or valibot schema.
|
|
72
|
+
- **JSON Schema.** `toJSONSchema` renders a schema or a whole model as JSON Schema draft 2020-12
|
|
73
|
+
or draft-07, an OpenAPI 3.0 schema object or a MongoDB `$jsonSchema`, with a strict profile for
|
|
74
|
+
LLM structured outputs; `~standard.jsonSchema` is the Standard JSON Schema converter. The
|
|
75
|
+
generators live in the `@alexify/metaschema/generators` subpath, so a program that only
|
|
76
|
+
validates does not carry them.
|
|
77
|
+
- **Fast.** Every check is compiled into a closure when the schema is built and runs in a context
|
|
78
|
+
of its own: about 10 million validations a second of a flat struct on Node 24, and about 30
|
|
79
|
+
million through the JIT backend of `@alexify/metaschema/compile`, which generates the same
|
|
80
|
+
check where `new Function` is allowed and keeps the closures where it is not (`pnpm bench`,
|
|
81
|
+
see [Performance](https://metaschema.vercel.app/guide/performance)).
|
|
82
|
+
- **Zero dependencies, 16.1 KB min+gzip.** CommonJS with ESM named imports, no build step,
|
|
83
|
+
one package for Node.js and browsers; the generators add 4.5 KB and the JIT backend 3.9 KB
|
|
84
|
+
where they are imported.
|
|
47
85
|
|
|
48
86
|
## Installation
|
|
49
87
|
|
|
@@ -53,27 +91,41 @@ pnpm add @alexify/metaschema
|
|
|
53
91
|
npm install @alexify/metaschema
|
|
54
92
|
```
|
|
55
93
|
|
|
56
|
-
Requires Node.js 18 or newer. Works in browsers through any bundler.
|
|
94
|
+
Requires Node.js 18 or newer. Works in browsers through any bundler. The typings need
|
|
95
|
+
TypeScript 5.0 or newer.
|
|
57
96
|
|
|
58
97
|
## Schema syntax
|
|
59
98
|
|
|
60
99
|
| Form | Example | Meaning |
|
|
61
100
|
| --- | --- | --- |
|
|
62
101
|
| Type name | `title: 'string'` | a required string |
|
|
63
|
-
| Optional | `subtitle: '?string'` or `'subtitle?': 'string'` | `undefined`
|
|
64
|
-
|
|
|
102
|
+
| Optional | `subtitle: '?string'` or `'subtitle?': 'string'` | the key may be absent, `undefined` or `null` |
|
|
103
|
+
| Nullable | `parent: { type: 'string', nullable: true }` | the key is required, the value may be `null` |
|
|
104
|
+
| Long form | `login: { type: 'string', length: [3, 32] }` | a type with options, `type` first |
|
|
105
|
+
| 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
106
|
| Collections | `{ array: 'number' }`, `{ set: 'string' }`, `{ object: { string: 'number' } }`, `{ map: { string: 'string' } }` | |
|
|
66
107
|
| Enum | `{ enum: ['admin', 'user'] }` | one of the values |
|
|
67
|
-
| Tuple | `point: ['number', 'number']` | a fixed-length array
|
|
68
|
-
|
|
|
69
|
-
|
|
|
108
|
+
| Tuple | `point: ['number', 'number']` | a fixed-length array, each element its own definition |
|
|
109
|
+
| Union | `id: { union: ['string', 'number'] }`, `{ union: [...], discriminator: 'kind' }` | one of several definitions |
|
|
110
|
+
| Nested struct | `name: { first: 'string', last: 'string' }` | an object whose first key is none of the above |
|
|
111
|
+
| Reference | `company: 'Company'`, `{ many: 'Address' }` | another schema in the model: its id for a stored kind, the record for a memory kind |
|
|
70
112
|
| Any object | `payload: 'json'` | any non-null object |
|
|
71
113
|
| Calculated | `ratio: (file) => file.compressed / file.size` | a function, never validated |
|
|
72
114
|
|
|
73
|
-
Built-in types: `string`, `number`, `
|
|
74
|
-
`
|
|
75
|
-
|
|
76
|
-
|
|
115
|
+
The first key of an object decides what it is. Built-in types: `string`, `number`, `integer`,
|
|
116
|
+
`bigint`, `boolean`, `date`, `null`, `any`/`unknown`, `enum`, `array`, `set`, `object`, `map`,
|
|
117
|
+
`tuple`, `union`, `json`. Rules: `length` (with `unicode: true` for code points) and `pattern`
|
|
118
|
+
for strings, `length` for collections, `min`/`max` for numbers; a rule on a type that does not
|
|
119
|
+
take it is a definition error. Fields can add a `validate(value, path)` function, and a schema
|
|
120
|
+
can have a top-level `validate` for rules across fields. `check(value, options)` takes `root`
|
|
121
|
+
(the label of the error lines), `maxErrors`, `unknown: 'ignore'` (keys the schema does not have;
|
|
122
|
+
`{ Struct: { unknown: 'ignore' } }` makes it the schema's default), `references` (`'kind'`,
|
|
123
|
+
`'embed'` or `'id'`) and `messages` (a locale); the result has `issues`, `errors`, `summary`,
|
|
124
|
+
`flatten()` and `tree()`. `schema.warnings` lints the definition (a mistyped option, a `pattern`
|
|
125
|
+
without `length.max`). See [Schema Syntax](https://metaschema.vercel.app/guide/schema-syntax),
|
|
126
|
+
[Types](https://metaschema.vercel.app/guide/types),
|
|
127
|
+
[Unions, nullable and null](https://metaschema.vercel.app/guide/unions),
|
|
128
|
+
[References](https://metaschema.vercel.app/guide/references) and
|
|
77
129
|
[Validation](https://metaschema.vercel.app/guide/validation).
|
|
78
130
|
|
|
79
131
|
## Domain models
|
|
@@ -96,8 +148,12 @@ const entities = new Map([
|
|
|
96
148
|
const model = new Model(types, entities);
|
|
97
149
|
|
|
98
150
|
model.order; // Set { 'Address', 'Company', 'User' }
|
|
99
|
-
model.warnings; // [] (
|
|
100
|
-
|
|
151
|
+
model.warnings; // [] (lint and consistency warnings, `Warning [code]: text`, end up here)
|
|
152
|
+
model.entities.get('User').check({ login: 'ab', company: 'c1', active: true }).errors;
|
|
153
|
+
// [ 'Field "User.login" value is too short' ]
|
|
154
|
+
|
|
155
|
+
const { toTypeScript } = require('@alexify/metaschema/generators');
|
|
156
|
+
console.log(toTypeScript(model));
|
|
101
157
|
```
|
|
102
158
|
|
|
103
159
|
```ts
|
|
@@ -122,48 +178,193 @@ interface User {
|
|
|
122
178
|
}
|
|
123
179
|
```
|
|
124
180
|
|
|
125
|
-
`saveTypes(outputFile, model)`
|
|
181
|
+
`saveTypes(outputFile, model, options?)` of the same subpath writes the interfaces to a file
|
|
182
|
+
(`{ named: true }` names enums and nested structs, and a field's `description` is its JSDoc); its
|
|
183
|
+
`register()` adds `model.dts`, `model.toTypeScript` and `schema.toInterface` as methods. The first
|
|
184
|
+
key of a definition sets
|
|
126
185
|
its kind and metadata (`Entity`, `Registry`, `Dictionary`, `Journal`, `Details`, `Relation`,
|
|
127
186
|
`View`, `Struct`, `Form`, `Projection`, or any custom kind). Stored kinds default to
|
|
128
|
-
`scope: 'application'` and `store: 'persistent'`, and they get an id field
|
|
187
|
+
`scope: 'application'` and `store: 'persistent'`, and they get an id field; a reference to a
|
|
188
|
+
stored kind holds its id, a reference to a memory kind embeds the record, in `check` and in the
|
|
189
|
+
generated types alike. See
|
|
129
190
|
[Kinds and Metadata](https://metaschema.vercel.app/guide/kinds-and-metadata),
|
|
130
191
|
[Custom Types](https://metaschema.vercel.app/guide/custom-types) and
|
|
131
192
|
[Domain Models](https://metaschema.vercel.app/guide/model).
|
|
132
193
|
|
|
194
|
+
## TypeScript
|
|
195
|
+
|
|
196
|
+
A schema keeps its definition as a type parameter, and `InferSchema` turns it into the type of
|
|
197
|
+
a value `check` accepts; `Infer<typeof definition>` does the same for a definition declared
|
|
198
|
+
`as const`:
|
|
199
|
+
|
|
200
|
+
```ts
|
|
201
|
+
import { Schema, type InferSchema } from '@alexify/metaschema';
|
|
202
|
+
|
|
203
|
+
const user = Schema.from({
|
|
204
|
+
name: 'string',
|
|
205
|
+
age: '?number',
|
|
206
|
+
role: { enum: ['admin', 'user'] },
|
|
207
|
+
tags: { array: 'string' },
|
|
208
|
+
address: { city: 'string', 'street?': 'string' },
|
|
209
|
+
point: ['number', 'number'],
|
|
210
|
+
});
|
|
211
|
+
|
|
212
|
+
type User = InferSchema<typeof user>;
|
|
213
|
+
// {
|
|
214
|
+
// name: string;
|
|
215
|
+
// age?: number | null | undefined;
|
|
216
|
+
// role: 'admin' | 'user';
|
|
217
|
+
// tags: string[];
|
|
218
|
+
// address: { city: string; street?: string | null | undefined };
|
|
219
|
+
// point: [number, number];
|
|
220
|
+
// }
|
|
221
|
+
```
|
|
222
|
+
|
|
223
|
+
Every form of the language is covered: optional and nullable fields, collections, enums,
|
|
224
|
+
tuples, unions, nested structs, references (an id, or the record through an entity map with
|
|
225
|
+
`Infer<D, E>` and `InferEntity<E, 'Name'>`) and custom types declared through module
|
|
226
|
+
augmentation of `CustomTypes`. A model renders its entities as interfaces with `toTypeScript`. See
|
|
227
|
+
[TypeScript](https://metaschema.vercel.app/guide/typescript).
|
|
228
|
+
|
|
229
|
+
A `Schema<D>` is also a `StandardSchemaV1<Infer<D>, Infer<D>>` of `@standard-schema/spec`:
|
|
230
|
+
`schema['~standard']` is typed as `StandardProps<D>`, with `StandardResult<T>` and
|
|
231
|
+
`StandardOptions` beside it. See
|
|
232
|
+
[Standard Schema](https://metaschema.vercel.app/guide/standard-schema).
|
|
233
|
+
|
|
234
|
+
## JSON Schema
|
|
235
|
+
|
|
236
|
+
`toJSONSchema(schema, options)` of `@alexify/metaschema/generators` renders the rules of `check`
|
|
237
|
+
as a JSON Schema document, and `toJSONSchema(model, options)` every entity of a model as a
|
|
238
|
+
definition:
|
|
239
|
+
|
|
240
|
+
```js
|
|
241
|
+
const { toJSONSchema } = require('@alexify/metaschema/generators');
|
|
242
|
+
|
|
243
|
+
toJSONSchema(user, { target: 'draft-07' });
|
|
244
|
+
// {
|
|
245
|
+
// $schema: 'http://json-schema.org/draft-07/schema#',
|
|
246
|
+
// type: 'object',
|
|
247
|
+
// properties: {
|
|
248
|
+
// name: { type: 'object', properties: { first: { type: 'string' }, last: { type: 'string' } }, required: ['first', 'last'], additionalProperties: false },
|
|
249
|
+
// email: { type: 'string', minLength: 5, maxLength: 64 },
|
|
250
|
+
// age: { type: ['number', 'null'] },
|
|
251
|
+
// roles: { type: 'array', items: { enum: ['admin', 'editor', 'viewer'] } }
|
|
252
|
+
// },
|
|
253
|
+
// required: ['name', 'email', 'roles'],
|
|
254
|
+
// additionalProperties: false
|
|
255
|
+
// }
|
|
256
|
+
|
|
257
|
+
toJSONSchema(answer, { profile: 'strict' }); // the dialect of OpenAI and Anthropic structured outputs
|
|
258
|
+
toJSONSchema(model, { target: 'mongodb' }); // one $jsonSchema validator per entity
|
|
259
|
+
```
|
|
260
|
+
|
|
261
|
+
The targets are `draft-2020-12` (the default), `draft-07`, `openapi-3.0` and `mongodb`; an
|
|
262
|
+
optional field accepts `null`, a reference to a stored kind is its id and a reference to a memory
|
|
263
|
+
kind a `$ref`, `validate` functions are not exported, and a type with no form in the target
|
|
264
|
+
(`bigint`, a `Date` on the way out) throws unless the call says `unrepresentable: 'any'`. The
|
|
265
|
+
export is checked against ajv for every form of the language. `register()` of the subpath turns
|
|
266
|
+
the functions into methods (`schema.toJSONSchema`, `model.toJSONSchema`) and adds the Standard
|
|
267
|
+
JSON Schema converter to `schema['~standard']`. See
|
|
268
|
+
[JSON Schema](https://metaschema.vercel.app/guide/json-schema).
|
|
269
|
+
|
|
270
|
+
## Compiled checks
|
|
271
|
+
|
|
272
|
+
`compile(schema)` of `@alexify/metaschema/compile` replaces the check of a schema, or of every
|
|
273
|
+
entity of a model, with one function generated from the same plan the closures walk and built
|
|
274
|
+
with `new Function`; `register()` does it for every schema built from then on. The issues are
|
|
275
|
+
the ones the closures record, only sooner: about three times faster on a flat struct, six on a
|
|
276
|
+
nested one. Where code generation from strings is not allowed (a Content Security Policy,
|
|
277
|
+
Cloudflare Workers, `node --disallow-code-generation-from-strings`) nothing changes: the
|
|
278
|
+
closures stay, silently unless `{ jit: true }` asks for an error.
|
|
279
|
+
|
|
280
|
+
```js
|
|
281
|
+
const { compile, register, canEval } = require('@alexify/metaschema/compile');
|
|
282
|
+
|
|
283
|
+
compile(user); // { accelerated: true }: user.check runs generated code now
|
|
284
|
+
compile(model); // every entity; { accelerated: false } where there is no eval
|
|
285
|
+
register(); // every schema built from here on is compiled as it is built
|
|
286
|
+
canEval(); // whether this environment builds functions from source
|
|
287
|
+
```
|
|
288
|
+
|
|
289
|
+
The generated source holds identifiers, numbers and JSON strings only; regular expressions, enum
|
|
290
|
+
sets, validate functions and nested schemas reach it through a scope, never through the source
|
|
291
|
+
text. See [The JIT backend](https://metaschema.vercel.app/guide/compile).
|
|
292
|
+
|
|
133
293
|
## Exports
|
|
134
294
|
|
|
135
295
|
```js
|
|
136
296
|
const {
|
|
137
297
|
KIND, KIND_STORED, KIND_MEMORY, SCOPE, STORE, ALLOW,
|
|
138
|
-
getKindMetadata,
|
|
298
|
+
getKindMetadata, Schema, Model, SchemaDefinitionError, ValidationResult,
|
|
139
299
|
} = require('@alexify/metaschema');
|
|
300
|
+
|
|
301
|
+
const { toJSONSchema, toTypeScript, saveTypes, register } = require('@alexify/metaschema/generators');
|
|
302
|
+
const { compile, canEval } = require('@alexify/metaschema/compile'); // and its own register()
|
|
303
|
+
|
|
304
|
+
const en = require('@alexify/metaschema/locales/en'); // the built-in messages
|
|
305
|
+
const uk = require('@alexify/metaschema/locales/uk'); // schema.check(value, { messages: uk })
|
|
140
306
|
```
|
|
141
307
|
|
|
142
308
|
```js
|
|
143
309
|
import { Schema, Model } from '@alexify/metaschema';
|
|
310
|
+
import type { Infer, InferSchema, InferEntity, CustomTypes, ValidationIssue } from '@alexify/metaschema';
|
|
144
311
|
```
|
|
145
312
|
|
|
146
|
-
In the browser every export works the same, except `saveTypes
|
|
147
|
-
file system
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
313
|
+
In the browser every export works the same, except `saveTypes` of the generators, which rejects
|
|
314
|
+
because there is no file system, and `compile`, which keeps the closures where a Content
|
|
315
|
+
Security Policy forbids `new Function`. The [API reference](https://metaschema.vercel.app/api/exports) lists every member
|
|
316
|
+
and every exported type.
|
|
317
|
+
|
|
318
|
+
## Migrating
|
|
319
|
+
|
|
320
|
+
### From 2.x
|
|
321
|
+
|
|
322
|
+
3.0 has two breaking changes. The generators left the core entry: `model.dts`,
|
|
323
|
+
`schema.toInterface()` and `saveTypes` are `toTypeScript(target, options)` and
|
|
324
|
+
`saveTypes(file, target, options)` of `@alexify/metaschema/generators`, whose `register()` puts
|
|
325
|
+
the methods back on the classes once per process. And `schema['~standard'].validate` is `parse`
|
|
326
|
+
rather than `check`: a consumer of Standard Schema gets the defaults filled in and the `parse`
|
|
327
|
+
functions applied, and a promise for a schema with an `async function`. The smaller changes: a
|
|
328
|
+
struct rejects an array, the synchronous `check` and `parse` throw `ERR_ASYNC_VALIDATOR` for a
|
|
329
|
+
promise, a graph deeper than 128 embedded records is a `depth` issue (`maxDepth` raises it),
|
|
330
|
+
`Infer` makes a defaulted key optional, and a few definitions that could never work throw when
|
|
331
|
+
the schema is built. Everything else is additive: `parse`, `serialize`, `checkAsync` and
|
|
332
|
+
`parseAsync`, the JSON Schema export, the JIT backend of `@alexify/metaschema/compile`, JSDoc
|
|
333
|
+
and named types. The step-by-step guide with before-and-after examples is
|
|
334
|
+
[Migrating from 2.x](https://metaschema.vercel.app/guide/migrating-from-2); the full list is
|
|
335
|
+
under "Upgrading from 2.0" in the [CHANGELOG](./CHANGELOG.md).
|
|
336
|
+
|
|
337
|
+
### From 1.x
|
|
338
|
+
|
|
339
|
+
2.0 changes the shape of a result (`issue.path` is an array of keys, `issue.message` has no
|
|
340
|
+
location, unknown keys are one issue per struct), the signature of `check`
|
|
341
|
+
(`check(value, { root, maxErrors, unknown, references, messages })`), and a few rules of the
|
|
342
|
+
language: the first key of an object decides what it is, numbers are bounded by `min`/`max`
|
|
343
|
+
instead of `length`, a reference to a stored kind is its id, a `set` renders as `Set<T>`, the
|
|
344
|
+
`relations` labels follow the referencing side, and a type failure cancels the rules and
|
|
345
|
+
`validate` of the field. Everything else is additive: `integer`, `date`, `null`, `any`, `union`,
|
|
346
|
+
`nullable`, `pattern`, locales, the lint, `Infer` and Standard Schema. The step-by-step guide
|
|
347
|
+
with before-and-after examples is
|
|
348
|
+
[Migrating from 1.x](https://metaschema.vercel.app/guide/migrating-from-1); the full list is
|
|
349
|
+
under "Upgrading from 1.x" in the [CHANGELOG](./CHANGELOG.md).
|
|
350
|
+
|
|
351
|
+
### From `metaschema` (metarhia)
|
|
352
|
+
|
|
353
|
+
`@alexify/metaschema` is a fork of [`metaschema`](https://github.com/metarhia/metaschema) 2.2 with
|
|
354
|
+
the same schema language. What changed in 1.0:
|
|
153
355
|
|
|
154
356
|
- **No loader.** `createSchema`, `loadSchema`, `readDirectory` and `loadModel` are removed along
|
|
155
357
|
with the `metavm` sandbox. Use `new Schema(name, require('./schemas/User.js'))` and
|
|
156
358
|
`new Model(types, new Map([...]), database)`. Schema files written as `({ ... })` become modules
|
|
157
359
|
(`module.exports = { ... }`).
|
|
158
360
|
- **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".
|
|
361
|
+
- **Fixed messages, no old text kept:** `Field "..."` instead of `Filed "..."` and
|
|
362
|
+
`not of expected type: object` instead of `is not a object`.
|
|
162
363
|
- **`detouch` is renamed to `detach`**, with no alias.
|
|
163
364
|
- **`browser.js`** replaces `dist.js`, and an `exports` map closes deep imports.
|
|
164
365
|
|
|
165
|
-
The full list is in [Migrating from metarhia](https://metaschema.vercel.app/guide/migrating-from-metarhia)
|
|
166
|
-
and the
|
|
366
|
+
The full list is in [Migrating from metarhia](https://metaschema.vercel.app/guide/migrating-from-metarhia),
|
|
367
|
+
and the 2.0 and 3.0 changes above apply on top of it.
|
|
167
368
|
|
|
168
369
|
## Changelog
|
|
169
370
|
|
package/SECURITY.md
CHANGED
|
@@ -6,7 +6,9 @@ Only the latest published version receives fixes.
|
|
|
6
6
|
|
|
7
7
|
| Version | Supported |
|
|
8
8
|
|---|---|
|
|
9
|
-
|
|
|
9
|
+
| 3.x | ✅ |
|
|
10
|
+
| 2.x | ❌ (upgrade: the CHANGELOG has the notes) |
|
|
11
|
+
| 1.x | ❌ |
|
|
10
12
|
| `metaschema` (metarhia) 2.x | ❌ (report upstream) |
|
|
11
13
|
|
|
12
14
|
## Reporting a vulnerability
|
|
@@ -31,18 +33,37 @@ timeline once the report is confirmed.
|
|
|
31
33
|
Some things work as intended and are not vulnerabilities:
|
|
32
34
|
|
|
33
35
|
- **Schemas are code.** A schema is a JavaScript value supplied by the application. Field and
|
|
34
|
-
schema `validate` functions, custom types' `construct` / `checkType`,
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
36
|
+
schema `validate` functions, custom types' `construct` / `checkType`, calculated fields, the
|
|
37
|
+
`parse` and `serialize` functions of a field and of a schema (decoders and serializers), and
|
|
38
|
+
`default` factories are live functions that run with the privileges of your process; a
|
|
39
|
+
decoder's exception is an issue, a serializer's or a default factory's exception is yours. A
|
|
40
|
+
getter on the value under check is the program's code too, and an exception from it leaves
|
|
41
|
+
`check`. Build schemas only from definitions you trust, the same as any other module you
|
|
42
|
+
`require`.
|
|
43
|
+
- **metaschema never loads or evaluates code it did not write.** Since 1.0 it has no loader: it
|
|
44
|
+
does not read schema files, evaluate source strings or run a sandbox. Turning untrusted input
|
|
45
|
+
into a schema definition is the application's decision and responsibility. The one place that
|
|
46
|
+
builds a function from source is the `@alexify/metaschema/compile` subpath (3.0), and only when
|
|
47
|
+
the application calls its `compile()` or `register()`: the source is generated by the package
|
|
48
|
+
from the schema's plan, nothing taken from a schema or from a value under check reaches it
|
|
49
|
+
except as a JSON string literal (regular expressions, enum values, functions and nested schemas
|
|
50
|
+
are passed by reference through a scope), the generated code is strict and named in a
|
|
51
|
+
`sourceURL`, and where `new Function` is not allowed (a Content Security Policy, Cloudflare
|
|
52
|
+
Workers, `node --disallow-code-generation-from-strings`) the closure backend stays. The probe
|
|
53
|
+
`canEval()` runs `new Function('')` once; under a CSP with a `report-uri` that one violation
|
|
54
|
+
is reported, and under a report-only policy the probe succeeds and every build is reported. A
|
|
55
|
+
check the generator cannot build is reported (`compile().error`, `register({ onFallback })`),
|
|
56
|
+
never installed. The core entry never calls `new Function`.
|
|
40
57
|
- **Input shape is checked strictly.** Every key that is not in the schema is reported as
|
|
41
|
-
`
|
|
58
|
+
unexpected (`has unexpected keys: ...`), including `constructor`, `__proto__` and `toString`,
|
|
59
|
+
unless the schema or the call says `unknown: 'ignore'`. Fields live in a
|
|
42
60
|
null-prototype dictionary, so nothing on `Object.prototype` is ever read as a field, and
|
|
43
|
-
metaschema never writes to the value it checks.
|
|
44
|
-
|
|
45
|
-
|
|
61
|
+
metaschema never writes to the value it checks. A value with a `then` function is data: the
|
|
62
|
+
passes of `parse` and `parseAsync` await only the promises their own decoders make, never a
|
|
63
|
+
thenable of the value. A graph nested deeper than `maxDepth` embedded records (128 by
|
|
64
|
+
default) is a `depth` issue, not a stack overflow.
|
|
65
|
+
- **Validation errors are data.** `check` collects problems as issues (a code, a path and params,
|
|
66
|
+
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
67
|
truncated to 100 characters) and, for `enum`, the allowed values; they never contain the
|
|
47
68
|
rejected values themselves. A message
|
|
48
69
|
from a custom `validate` function, or from an exception it throws, is passed through as written.
|