@alexify/metaschema 0.0.0-stage → 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/LICENSE ADDED
@@ -0,0 +1,22 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2017-2025 Metarhia contributors
4
+ Copyright (c) 2026 Alexis Technologies
5
+
6
+ Permission is hereby granted, free of charge, to any person obtaining a copy
7
+ of this software and associated documentation files (the "Software"), to deal
8
+ in the Software without restriction, including without limitation the rights
9
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10
+ copies of the Software, and to permit persons to whom the Software is
11
+ furnished to do so, subject to the following conditions:
12
+
13
+ The above copyright notice and this permission notice shall be included in all
14
+ copies or substantial portions of the Software.
15
+
16
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,275 @@
1
- # Temporary Holding Version
1
+ # metaschema
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ [![npm](https://img.shields.io/npm/v/%40alexify%2Fmetaschema)](https://www.npmjs.com/package/@alexify/metaschema)
4
+ [![CI](https://github.com/Alexis-Technologies/metaschema/actions/workflows/ci.yml/badge.svg)](https://github.com/Alexis-Technologies/metaschema/actions/workflows/ci.yml)
5
+ [![node](https://img.shields.io/node/v/%40alexify%2Fmetaschema)](#installation)
6
+ [![dependencies](https://img.shields.io/badge/runtime_dependencies-0-brightgreen)](#why-metaschema)
7
+ [![docs](https://img.shields.io/badge/docs-online-blue)](https://metaschema.vercel.app/)
8
+ [![license](https://img.shields.io/npm/l/%40alexify%2Fmetaschema)](./LICENSE)
9
+
10
+ **Metadata schema and interface definition language for JavaScript.** Declare data structures and
11
+ domain models once as plain objects, validate data against them, and generate TypeScript
12
+ interfaces. Zero dependencies, Node.js and browsers.
13
+
14
+ ```js
15
+ const { Schema } = require('@alexify/metaschema');
16
+
17
+ const user = new Schema('User', {
18
+ name: { first: 'string', last: 'string' },
19
+ email: { type: 'string', length: { min: 5, max: 64 } },
20
+ age: '?number',
21
+ roles: { array: { enum: ['admin', 'editor', 'viewer'] } },
22
+ });
23
+
24
+ const result = user.check({ name: { first: 'Marcus' }, email: 'm@r', roles: ['owner'] });
25
+
26
+ result.errors;
27
+ // [
28
+ // 'Field "User.name.last" is required',
29
+ // 'Field "User.email" value is too short',
30
+ // 'Field "User.roles[0]" value is not of enum: admin, editor, viewer'
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
+
41
+ ### 📖 [Read the documentation →](https://metaschema.vercel.app/)
42
+
43
+ ## Why metaschema
44
+
45
+ - **Compact syntax.** `'?string'` is an optional string, `'tags?'` an optional key,
46
+ `{ array: 'number' }` an array, `['number', 'number']` a tuple, `'Company'` a reference. The
47
+ long form (`{ type: 'string', length: [3, 32] }`) is there when a field needs options.
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.
52
+ - **Domain models.** Entities, registries, dictionaries and projections, with references,
53
+ relations and indexes, ordered by dependency and checked for missing references.
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.
65
+
66
+ ## Installation
67
+
68
+ ```bash
69
+ pnpm add @alexify/metaschema
70
+ # or
71
+ npm install @alexify/metaschema
72
+ ```
73
+
74
+ Requires Node.js 18 or newer. Works in browsers through any bundler. The typings need
75
+ TypeScript 5.0 or newer.
76
+
77
+ ## Schema syntax
78
+
79
+ | Form | Example | Meaning |
80
+ | --- | --- | --- |
81
+ | Type name | `title: 'string'` | a required string |
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 |
86
+ | Collections | `{ array: 'number' }`, `{ set: 'string' }`, `{ object: { string: 'number' } }`, `{ map: { string: 'string' } }` | |
87
+ | Enum | `{ enum: ['admin', 'user'] }` | one of the values |
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 |
92
+ | Any object | `payload: 'json'` | any non-null object |
93
+ | Calculated | `ratio: (file) => file.compressed / file.size` | a function, never validated |
94
+
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
109
+ [Validation](https://metaschema.vercel.app/guide/validation).
110
+
111
+ ## Domain models
112
+
113
+ ```js
114
+ const { Model } = require('@alexify/metaschema');
115
+
116
+ const types = {
117
+ string: { metadata: { pg: 'varchar' } },
118
+ number: { metadata: { pg: 'integer' } },
119
+ boolean: { metadata: { pg: 'boolean' } },
120
+ };
121
+
122
+ const entities = new Map([
123
+ ['Company', { Dictionary: {}, name: { type: 'string', unique: true }, addresses: { many: 'Address' } }],
124
+ ['Address', { Entity: {}, city: 'string', street: 'string', building: '?string' }],
125
+ ['User', { Registry: {}, login: { type: 'string', length: { min: 3, max: 32 } }, company: 'Company', active: 'boolean' }],
126
+ ]);
127
+
128
+ const model = new Model(types, entities);
129
+
130
+ model.order; // Set { 'Address', 'Company', 'User' }
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' ]
134
+ console.log(model.dts);
135
+ ```
136
+
137
+ ```ts
138
+ interface Address {
139
+ city: string;
140
+ street: string;
141
+ building?: string;
142
+ addressId?: string;
143
+ }
144
+
145
+ interface Company {
146
+ name: string;
147
+ addressesId: string[];
148
+ companyId?: string;
149
+ }
150
+
151
+ interface User {
152
+ login: string;
153
+ companyId: string;
154
+ active: boolean;
155
+ userId?: string;
156
+ }
157
+ ```
158
+
159
+ `saveTypes(outputFile, model)` writes `model.dts` to a file. The first key of a definition sets
160
+ its kind and metadata (`Entity`, `Registry`, `Dictionary`, `Journal`, `Details`, `Relation`,
161
+ `View`, `Struct`, `Form`, `Projection`, or any custom kind). Stored kinds default to
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
165
+ [Kinds and Metadata](https://metaschema.vercel.app/guide/kinds-and-metadata),
166
+ [Custom Types](https://metaschema.vercel.app/guide/custom-types) and
167
+ [Domain Models](https://metaschema.vercel.app/guide/model).
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
+
209
+ ## Exports
210
+
211
+ ```js
212
+ const {
213
+ KIND, KIND_STORED, KIND_MEMORY, SCOPE, STORE, ALLOW,
214
+ getKindMetadata, saveTypes, Schema, Model, SchemaDefinitionError, ValidationResult,
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 })
219
+ ```
220
+
221
+ ```js
222
+ import { Schema, Model } from '@alexify/metaschema';
223
+ import type { Infer, InferSchema, InferEntity, CustomTypes, ValidationIssue } from '@alexify/metaschema';
224
+ ```
225
+
226
+ In the browser every export works the same, except `saveTypes`, which rejects because there is no
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).
245
+
246
+ ### From `metaschema` (metarhia)
247
+
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:
250
+
251
+ - **No loader.** `createSchema`, `loadSchema`, `readDirectory` and `loadModel` are removed along
252
+ with the `metavm` sandbox. Use `new Schema(name, require('./schemas/User.js'))` and
253
+ `new Model(types, new Map([...]), database)`. Schema files written as `({ ... })` become modules
254
+ (`module.exports = { ... }`).
255
+ - **No runtime dependencies:** `metautil`, `metavm` and `metaskills` are gone.
256
+ - **Fixed messages, no old text kept:** `Field "..."` instead of `Filed "..."` and
257
+ `not of expected type: object` instead of `is not a object`.
258
+ - **`detouch` is renamed to `detach`**, with no alias.
259
+ - **`browser.js`** replaces `dist.js`, and an `exports` map closes deep imports.
260
+
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.
263
+
264
+ ## Changelog
265
+
266
+ See [CHANGELOG.md](./CHANGELOG.md).
267
+
268
+ ## License
269
+
270
+ [MIT](./LICENSE) © Alexis Technologies
271
+
272
+ `@alexify/metaschema` is a fork of [`metaschema`](https://github.com/metarhia/metaschema) by the
273
+ [Metarhia contributors](https://github.com/metarhia/metaschema/graphs/contributors), originally
274
+ part of the [Metarhia](https://github.com/metarhia) technology stack. Their copyright is kept in
275
+ [LICENSE](./LICENSE).
package/SECURITY.md ADDED
@@ -0,0 +1,62 @@
1
+ # Security Policy
2
+
3
+ ## Supported versions
4
+
5
+ Only the latest published version receives fixes.
6
+
7
+ | Version | Supported |
8
+ |---|---|
9
+ | 2.x | ✅ |
10
+ | 1.x | ❌ |
11
+ | `metaschema` (metarhia) 2.x | ❌ (report upstream) |
12
+
13
+ ## Reporting a vulnerability
14
+
15
+ **Please do not open a public issue for a security problem.**
16
+
17
+ Report it privately through
18
+ [GitHub's private vulnerability reporting](https://github.com/Alexis-Technologies/metaschema/security/advisories/new),
19
+ or by email to <dolid.sasha@gmail.com>.
20
+
21
+ Include, as far as you can:
22
+
23
+ - what an attacker can do, and what they need in order to do it;
24
+ - the affected version and Node.js version (or browser);
25
+ - a minimal reproduction.
26
+
27
+ You can expect an acknowledgement within a few days, and an assessment of severity and a fix
28
+ timeline once the report is confirmed.
29
+
30
+ ## Threat model
31
+
32
+ Some things work as intended and are not vulnerabilities:
33
+
34
+ - **Schemas are code.** A schema is a JavaScript value supplied by the application. Field and
35
+ schema `validate` functions, custom types' `construct` / `checkType`, and calculated fields are
36
+ live functions that run with the privileges of your process. Build schemas only from definitions
37
+ you trust, the same as any other module you `require`.
38
+ - **metaschema never loads or evaluates code.** Since 1.0 it has no loader: it does not read schema
39
+ files, evaluate source strings or run a sandbox. Turning untrusted input into a schema definition
40
+ is the application's decision and responsibility.
41
+ - **Input shape is checked strictly.** Every key that is not in the schema is reported as
42
+ unexpected (`has unexpected keys: ...`), including `constructor`, `__proto__` and `toString`,
43
+ unless the schema or the call says `unknown: 'ignore'`. Fields live in a
44
+ null-prototype dictionary, so nothing on `Object.prototype` is ever read as a field, and
45
+ metaschema never writes to the value it checks.
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,
48
+ truncated to 100 characters) and, for `enum`, the allowed values; they never contain the
49
+ rejected values themselves. A message
50
+ from a custom `validate` function, or from an exception it throws, is passed through as written.
51
+ - **Type registration is process-wide.** Custom types registered by one `Model` are visible to
52
+ every schema in the process. Register them once, from trusted code.
53
+ - **`saveTypes` writes where it is told.** The output path is the caller's argument; metaschema
54
+ does not sanitize it.
55
+ - **Bundled and minified builds validate exactly like the source.** Internal identity checks use a
56
+ global symbol brand, not class names, and `tests/unit/bundle.test.js` validates through esbuild
57
+ bundles of both entry points, minified and not. A build in which `check` accepts invalid data is a
58
+ bug; please report it.
59
+
60
+ Things that *are* in scope: input data that makes `check` throw, hang or consume unbounded
61
+ resources (a circular value is reported as `is a circular reference`, not recursed into); input
62
+ data that changes a schema or the type registry; and a message that leaks a value it should not.
package/browser.js ADDED
@@ -0,0 +1,4 @@
1
+ // Intentionally mirrors index.js: bundlers resolve this file through the
2
+ // package.json `browser` field and `exports` condition, and the same map swaps
3
+ // src/runtime/node.js for src/runtime/browser.js. Do not deduplicate.
4
+ module.exports = require('./src/index.js');