@alexify/metaschema 3.4.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.
package/CHANGELOG.md CHANGED
@@ -7,6 +7,70 @@ 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
+
10
74
  ## [3.4.0] - 2026-10-16
11
75
 
12
76
  3.4 makes the snapshot a contract a program can build on and the language complete for the
@@ -1578,7 +1642,8 @@ published.
1578
1642
 
1579
1643
  ### [metaschema 0.x][upstream-0.x] - First generation of metaschema
1580
1644
 
1581
- [unreleased]: https://github.com/Alexis-Technologies/metaschema/compare/v3.4.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
1582
1647
  [3.4.0]: https://github.com/Alexis-Technologies/metaschema/compare/v3.3.0...v3.4.0
1583
1648
  [3.3.0]: https://github.com/Alexis-Technologies/metaschema/compare/v3.2.0...v3.3.0
1584
1649
  [3.2.0]: https://github.com/Alexis-Technologies/metaschema/compare/v3.1.0...v3.2.0
package/README.md CHANGED
@@ -110,13 +110,13 @@ event.parse({ name: 'deploy', when: '2026-10-10T12:00:00.000Z' }).value;
110
110
  schemas (`merge`) and infers a definition from the values that exist (`infer`); `aliases` and
111
111
  `deprecated` let a model carry its history, and `fromJSONSchema` of the generators reads a
112
112
  JSON Schema document back.
113
- - **Zero dependencies, 21.3 KB min+gzip.** CommonJS with ESM named imports, no build step,
113
+ - **Zero dependencies, 21.7 KB min+gzip.** CommonJS with ESM named imports, no build step,
114
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.7 KB, the record tools 0.9 KB, the string formats 3.9 KB, the derive tools
116
- 2.2 KB, the converters of coercion 1.9 KB and the MongoDB tools 3.6 KB (on top of 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
117
  converters, which they require) where they are imported. A program that reads schemas
118
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.3 KB.
119
+ `@alexify/metaschema/definition`, the half of the core that builds them: 10.5 KB.
120
120
 
121
121
  ## Benchmarks
122
122
 
@@ -225,7 +225,7 @@ interactive.
225
225
  | Effect Schema<br><sub>decodeUnknownResult() · is() · v4.0.3</sub> | 72.9 KB | 24.4 KB | |
226
226
  | Zod<br><sub>safeParse() · v4.6.6</sub> | 88.4 KB | 25.7 KB | |
227
227
  | TypeBox<br><sub>Value.Check() · v1.3.36</sub> | 146.7 KB | 37.5 KB | |
228
- | 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 | |
229
229
  | TypeBox<br><sub>Compile(…).Check() · v1.3.36</sub> | 161.5 KB | 40.8 KB | |
230
230
  | ArkType<br><sub>type(value) · allows() · v2.2.8</sub> | 151.9 KB | 46.4 KB | |
231
231
  | Joi<br><sub>validate(), convert: false · v18.2.9</sub> | 169.5 KB | 53.3 KB | |
@@ -497,7 +497,9 @@ TypeScript 5.0 or newer.
497
497
  | Any object | `payload: 'json'` | any non-null object |
498
498
  | Calculated | `ratio: (file) => file.compressed / file.size` | a function, never validated |
499
499
 
500
- The first key of an object decides what it is. Built-in types: `string`, `number`, `integer`,
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`,
501
503
  `bigint`, `boolean`, `date`, `bytes`, `null`, `any`/`unknown`, `enum`, `flags`, `array`, `set`,
502
504
  `object`, `map`, `tuple`, `union`, `json`. Rules: `length` (with `unicode: true` for code
503
505
  points), `pattern` and `format` for strings, `length` for collections, `min`/`max` for numbers,
@@ -508,7 +510,7 @@ can have a top-level `validate` for rules across fields. `check(value, options)`
508
510
  `{ Struct: { unknown: 'ignore' } }` makes it the schema's default), `references` (`'kind'`,
509
511
  `'embed'` or `'id'`) and `messages` (a locale); the result has `issues`, `errors`, `summary`,
510
512
  `flatten()`, `tree()` and `toJSON()`. `schema.warnings` lints the definition (a mistyped option, a `pattern`
511
- 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),
512
514
  [Types](https://metaschema.vercel.app/guide/types),
513
515
  [Unions, nullable and null](https://metaschema.vercel.app/guide/unions),
514
516
  [References](https://metaschema.vercel.app/guide/references) and
@@ -569,7 +571,8 @@ interface User {
569
571
  `register()` adds `model.dts`, `model.toTypeScript` and `schema.toInterface` as methods. The first
570
572
  key of a definition sets
571
573
  its kind and metadata (`Entity`, `Registry`, `Dictionary`, `Journal`, `Details`, `Relation`,
572
- `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
573
576
  `scope: 'application'` and `store: 'persistent'`, and they get an id field; a reference to a
574
577
  stored kind holds its id, a reference to a memory kind embeds the record, in `check` and in the
575
578
  generated types alike. See
package/index.d.ts CHANGED
@@ -981,6 +981,9 @@ export interface StandardConverter {
981
981
  // `enum`, `tuple`, `union`, `schema`, `one`, `many`) is that shorthand, and
982
982
  // anything else is a struct. A struct with a field named like one of those
983
983
  // says so with a kind (`{ Struct: {}, ... }`), as the runtime needs it to.
984
+ // A kind key is what the runtime takes for one (`KindKey` below): a name like
985
+ // `Entity` or `Settings` holding an object, never `PORT` or `Name: 'string'`,
986
+ // which are fields.
984
987
  // ---------------------------------------------------------------------------
985
988
 
986
989
  // The value types of custom types, by type name, for module augmentation:
@@ -1049,7 +1052,7 @@ type ScalarOf<N extends string> = N extends 'string'
1049
1052
  : unknown;
1050
1053
 
1051
1054
  // Whether the first character is an uppercase letter: a reference when it is
1052
- // the first character of a type name, a kind when it is the first of a key.
1055
+ // the first character of a type name, and what a kind key starts with.
1053
1056
  type IsCapitalized<K> = K extends `${infer C}${string}`
1054
1057
  ? C extends Uppercase<C>
1055
1058
  ? C extends Lowercase<C>
@@ -1067,7 +1070,46 @@ type StoredKind =
1067
1070
  | 'relation'
1068
1071
  | 'view';
1069
1072
 
1070
- type KindKey<D> = { [K in keyof D]: IsCapitalized<K> extends true ? K : never }[keyof D];
1073
+ // A kind key, as the runtime reads one (`isKindKey` of src/kinds.js): a
1074
+ // capital letter, then letters and digits, one of them lowercase (`Entity`,
1075
+ // `Settings`, never `PORT` or `DATABASE_URL`), holding the metadata of the
1076
+ // kind, an object that is no list, function or Schema. Any other capitalized
1077
+ // key is a field.
1078
+ type KnownKindKey = Capitalize<KnownKind>;
1079
+
1080
+ // The characters of a string as a union, gathered in an accumulator so that
1081
+ // the recursion is a tail call (62 levels of a union are too deep otherwise).
1082
+ type CharsOf<S, A = never> = S extends `${infer C}${infer R}` ? CharsOf<R, A | C> : A;
1083
+
1084
+ type WordChar = CharsOf<'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'>;
1085
+
1086
+ type IsWord<S> = S extends `${infer C}${infer R}` ? (C extends WordChar ? IsWord<R> : false) : true;
1087
+
1088
+ // Read for a capitalized key only, so the walk over its characters is paid
1089
+ // by the few keys that may be kinds.
1090
+ type IsKindName<K> =
1091
+ IsCapitalized<K> extends true ? (K extends Uppercase<K & string> ? false : IsWord<K>) : false;
1092
+
1093
+ type IsKindMeta<V> =
1094
+ IsAny<V> extends true
1095
+ ? false
1096
+ : [V] extends [object]
1097
+ ? [V] extends [readonly unknown[] | Fn | Schema<any>]
1098
+ ? false
1099
+ : true
1100
+ : false;
1101
+
1102
+ type KindCandidates<D> = {
1103
+ [K in keyof D]: IsKindName<K> extends true ? (IsKindMeta<D[K]> extends true ? K : never) : never;
1104
+ }[keyof D];
1105
+
1106
+ // The runtime takes the first key; the keys of a type have no order, so
1107
+ // among the keys that may be the kind a built-in one is it (the others are
1108
+ // fields then, as `{ Struct: {}, Address: { ... } }` says), and without one
1109
+ // every candidate is read as a kind.
1110
+ type KindKey<D> = [Extract<KindCandidates<D>, KnownKindKey>] extends [never]
1111
+ ? KindCandidates<D>
1112
+ : Extract<KindCandidates<D>, KnownKindKey>;
1071
1113
 
1072
1114
  // The store of an entity definition: its kind metadata, else the default of
1073
1115
  // its kind; a definition without a kind is a struct, held in memory.
@@ -1147,7 +1189,8 @@ type UnionOf<T extends readonly unknown[], E, M extends Mode> = {
1147
1189
  }[number];
1148
1190
 
1149
1191
  // A one-key object holding a type name names a tuple element (`{ x: 'number'
1150
- // }`); the key must not itself be `type`, a type name or a kind.
1192
+ // }`); the key must not itself be `type` or a type name (a string is no
1193
+ // metadata of a kind, so a capitalized key names an element too).
1151
1194
  type NamedKey<T> = keyof T extends infer K
1152
1195
  ? [K] extends [string]
1153
1196
  ? IsUnion<K> extends true
@@ -1155,14 +1198,10 @@ type NamedKey<T> = keyof T extends infer K
1155
1198
  : K extends `${infer F}?`
1156
1199
  ? F extends TypeName | 'type'
1157
1200
  ? never
1158
- : IsCapitalized<F> extends true
1159
- ? never
1160
- : K
1201
+ : K
1161
1202
  : K extends TypeName | 'type'
1162
1203
  ? never
1163
- : IsCapitalized<K> extends true
1164
- ? never
1165
- : K
1204
+ : K
1166
1205
  : never
1167
1206
  : never;
1168
1207
 
@@ -1360,20 +1399,17 @@ type Projection<D, E, M extends Mode> = D extends {
1360
1399
  : unknown
1361
1400
  : unknown;
1362
1401
 
1363
- type WithKind<D, K extends keyof D, E, M extends Mode> = K extends 'Projection'
1402
+ type WithKind<D, K extends keyof D, E, M extends Mode> = [K] extends ['Projection']
1364
1403
  ? Projection<D, E, M>
1365
1404
  : Struct<Omit<D, K>, E, M>;
1366
1405
 
1367
- type ObjectDef<D, E, M extends Mode> =
1368
- KindKey<D> extends infer K
1369
- ? [K] extends [never]
1370
- ? D extends { type: infer T extends string }
1371
- ? LongForm<T, D, E, M>
1372
- : Shorthand<D, E, M>
1373
- : K extends keyof D
1374
- ? Decoded<WithKind<D, K, E, M>, D, M>
1375
- : never
1376
- : never;
1406
+ // The kind keys are taken as one set, never one by one: a union of structs,
1407
+ // each without one key, is what distributing over them gave.
1408
+ type ObjectDef<D, E, M extends Mode> = [KindKey<D>] extends [never]
1409
+ ? D extends { type: infer T extends string }
1410
+ ? LongForm<T, D, E, M>
1411
+ : Shorthand<D, E, M>
1412
+ : Decoded<WithKind<D, KindKey<D> & keyof D, E, M>, D, M>;
1377
1413
 
1378
1414
  // The id field a stored kind adds, named after the entity.
1379
1415
  type IdOf<Name extends string, Def> =
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@alexify/metaschema",
3
- "version": "3.4.0",
3
+ "version": "3.4.1",
4
4
  "description": "Fast, zero-dependency metadata schema and interface definition language (IDL) for Node.js and browsers — validation and parsing with a JIT backend, domain models, TypeScript and JSON Schema",
5
5
  "license": "MIT",
6
6
  "author": "Alex Dolid <dolid.sasha@gmail.com>",
@@ -6,10 +6,10 @@
6
6
  // too), so the source is never touched and every rule of a field comes along.
7
7
  // `register()` installs the functions as methods of Schema, so they chain.
8
8
  const { hasBrand, define, formatters } = require('../util.js');
9
- const { isFirstUpper, firstKey } = require('../metautil.js');
9
+ const { firstKey } = require('../metautil.js');
10
10
  const { Schema } = require('../schema.js');
11
11
  const { isStruct } = require('../struct.js');
12
- const { idFieldOf } = require('../kinds.js');
12
+ const { idFieldOf, isKindKey } = require('../kinds.js');
13
13
  const { SchemaDefinitionError, invalidTarget, invalidOption } = require('../errors.js');
14
14
  const {
15
15
  structDefinitionOf,
@@ -188,9 +188,12 @@ const extend = (schema, extension, options) => {
188
188
  sources.push(extension);
189
189
  } else if (extension === null || typeof extension !== 'object' || Array.isArray(extension)) {
190
190
  throw invalidTarget('An extension is a Schema of a struct or an object of fields');
191
- } else if (isFirstUpper(firstKey(extension))) {
192
- const reason = 'An extension has fields only; the kind is options.metadata';
193
- throw atSchema(new SchemaDefinitionError('ERR_INVALID_DEFINITION', reason), schema.name);
191
+ } else {
192
+ const first = firstKey(extension);
193
+ if (isKindKey(first, extension[first])) {
194
+ const reason = 'An extension has fields only; the kind is options.metadata';
195
+ throw atSchema(new SchemaDefinitionError('ERR_INVALID_DEFINITION', reason), schema.name);
196
+ }
194
197
  }
195
198
  const keys = new Map();
196
199
  for (const key of Object.keys(additions)) keys.set(formatters.key(key).field, key);
package/src/kinds.js CHANGED
@@ -1,4 +1,5 @@
1
1
  const { toLowerCamel } = require('./metautil.js');
2
+ const { hasBrand } = require('./util.js');
2
3
  const { SchemaDefinitionError } = require('./errors.js');
3
4
 
4
5
  const projectionError = (name, reason) =>
@@ -10,6 +11,24 @@ const KIND_STORED = [...KIND_ENT, ...KIND_AUX];
10
11
  const KIND_MEMORY = ['struct', 'scalar', 'form', 'projection'];
11
12
  const KIND = [...KIND_MEMORY, ...KIND_STORED];
12
13
 
14
+ // A key is a kind when its name is one a kind may have (a capital letter,
15
+ // then letters and digits, one of them lowercase: `Entity`, `Settings`,
16
+ // never `PORT` or `DATABASE_URL`) and its value is the metadata of a kind:
17
+ // a plain object of any realm, not a string, a list, a function or anything
18
+ // built (a Schema, a field, a struct). Any other capitalized key is a field.
19
+ // The one rule: the preprocessor reads the first key by it, what writes a
20
+ // definition (derive, merge, fromJSON) holds a kind to it, and `KindKey` of
21
+ // the typings mirrors it.
22
+ const KIND_NAME = /^[A-Z][A-Z\d]*[a-z][A-Za-z\d]*$/;
23
+
24
+ const isMetadata = (value) => {
25
+ if (value === null || typeof value !== 'object' || hasBrand(value, 'Struct')) return false;
26
+ const proto = Object.getPrototypeOf(value);
27
+ return proto === null || Object.getPrototypeOf(proto) === null;
28
+ };
29
+
30
+ const isKindKey = (key, meta) => KIND_NAME.test(key) && isMetadata(meta);
31
+
13
32
  const SCOPE = ['application', 'global', 'local'];
14
33
  const STORE = ['persistent', 'memory'];
15
34
  const ALLOW = ['write', 'append', 'read'];
@@ -74,4 +93,4 @@ const getKindMetadata = (kind, meta = {}, root) => {
74
93
 
75
94
  const constants = { KIND, KIND_STORED, KIND_MEMORY, SCOPE, STORE, ALLOW };
76
95
 
77
- module.exports = { constants, getKindMetadata, idFieldOf };
96
+ module.exports = { constants, getKindMetadata, idFieldOf, isKindKey };
package/src/lint.js CHANGED
@@ -2,7 +2,8 @@
2
2
  // what the author meant either. A contradiction that can never validate
3
3
  // (an enum without values, a min above max) is a SchemaDefinitionError at
4
4
  // build time; these are warnings, as `Warning [code]: text` strings.
5
- const { hasBrand } = require('./util.js');
5
+ const { hasBrand, formatters, KINDS } = require('./util.js');
6
+ const { firstKey } = require('./metautil.js');
6
7
  const { embeds } = require('./prototypes/reference.js');
7
8
 
8
9
  const warning = (code, text) => `Warning [${code}]: ${text}`;
@@ -134,11 +135,58 @@ const lintIndexes = (schema, warnings) => {
134
135
  }
135
136
  };
136
137
 
138
+ // Whether the first key of an object makes it the long form or the
139
+ // shorthand of a type.
140
+ const startsField = (def, types) => {
141
+ const first = firstKey(def);
142
+ if (first === undefined) return false;
143
+ const { field } = formatters.key(first);
144
+ return field === 'type' || types[field] !== undefined;
145
+ };
146
+
147
+ // Whether a value under a key reads as the definition of a field: the name
148
+ // of a type, or an object its first key makes one.
149
+ const readsAsField = (value, types) => {
150
+ if (typeof value === 'string') return types[formatters.type(value).type] !== undefined;
151
+ if (value === null || typeof value !== 'object' || Array.isArray(value)) return false;
152
+ return startsField(value, types);
153
+ };
154
+
155
+ // A kind of the program's own (`{ Settings: { theme: 'dark' }, ... }`) whose
156
+ // metadata reads as a field or holds fields: most likely a field with a name
157
+ // like `Address`, first in its struct, that the first key made a kind, so
158
+ // the struct has no such field. The kinds are the ones the definition named
159
+ // at any depth, as the preprocessor kept them. `unknown` is a type name and
160
+ // a key of the metadata of every kind, where it is the policy.
161
+ const lintKinds = (schema, warnings) => {
162
+ const kinds = schema[KINDS];
163
+ if (!kinds) return;
164
+ const { name, types } = schema;
165
+ for (const pair of kinds) {
166
+ const key = pair[0];
167
+ const meta = pair[1];
168
+ let suspect = firstKey(meta) !== 'unknown' && startsField(meta, types);
169
+ if (!suspect) {
170
+ for (const option of Object.keys(meta)) {
171
+ if (!readsAsField(meta[option], types)) continue;
172
+ suspect = true;
173
+ break;
174
+ }
175
+ }
176
+ if (!suspect) continue;
177
+ const text =
178
+ `"${key}" of "${name}" is read as a kind, and its metadata reads as field definitions: ` +
179
+ `a field of that name needs a kind before it ({ Struct: {}, ${key}: ... })`;
180
+ warnings.push(warning('ambiguous-kind', text));
181
+ }
182
+ };
183
+
137
184
  // The warnings of one schema on its own: everything that needs no model.
138
185
  const lintSchema = (schema) => {
139
186
  const warnings = [];
140
187
  lintStruct(schema.fields, schema.name, warnings);
141
188
  lintIndexes(schema, warnings);
189
+ lintKinds(schema, warnings);
142
190
  return warnings;
143
191
  };
144
192
 
package/src/model/data.js CHANGED
@@ -7,6 +7,7 @@ const { hasBrand, define, isDate, isRegExp } = require('../util.js');
7
7
  const { FORMAT } = require('../snapshot.js');
8
8
  const { SchemaDefinitionError } = require('../errors.js');
9
9
  const { isStruct } = require('../struct.js');
10
+ const { isKindKey } = require('../kinds.js');
10
11
 
11
12
  // How deep the walks over a snapshot go: a definition nested deeper is not
12
13
  // one a program wrote.
@@ -88,6 +89,16 @@ const isFunctionMarker = (value) => isObject(value) && value.$function === true;
88
89
 
89
90
  const capitalize = (name) => name.charAt(0).toUpperCase() + name.slice(1);
90
91
 
92
+ // The key a kind is written under as the first key of a definition (`entity`
93
+ // is `Entity`), null for a name that key would not be read back as a kind
94
+ // from (`dTO`, `api_config`: `isKindKey` of kinds.js): the fields after it
95
+ // would read as something else.
96
+ const kindKeyOf = (kind) => {
97
+ if (typeof kind !== 'string' || kind === '') return null;
98
+ const key = capitalize(kind);
99
+ return isKindKey(key, {}) ? key : null;
100
+ };
101
+
91
102
  // The definition a built field was made from, with its nested fields as
92
103
  // definitions and its functions kept: what `merge` unifies and `Schema`
93
104
  // takes back.
@@ -128,7 +139,12 @@ const metadataOf = (schema) => {
128
139
  // its first key, so the fields after it read as a struct whatever their names.
129
140
  const structDefinition = (base, metadata, fields) => {
130
141
  const { kind = base.kind, ...rest } = { ...base, ...metadata };
131
- const definition = { [capitalize(kind)]: rest };
142
+ const kindKey = kindKeyOf(kind);
143
+ if (kindKey === null) {
144
+ const reason = `Metadata "kind" must be the name of a kind, got ${JSON.stringify(kind)}`;
145
+ throw new SchemaDefinitionError('ERR_INVALID_OPTIONS', reason);
146
+ }
147
+ const definition = { [kindKey]: rest };
132
148
  for (const key of Object.keys(fields)) define(definition, key, fields[key]);
133
149
  return definition;
134
150
  };
@@ -171,6 +187,7 @@ module.exports = {
171
187
  same,
172
188
  isFunctionMarker,
173
189
  capitalize,
190
+ kindKeyOf,
174
191
  definitionOf,
175
192
  structDefinitionOf,
176
193
  metadataOf,
@@ -15,7 +15,7 @@ const { readsAsStruct } = require('../types.js');
15
15
  const { FORMATS } = require('../rules.js');
16
16
  const { toDotPath, finalize } = require('../issues.js');
17
17
  const en = require('../locales/en.js');
18
- const { DEPTH, capitalize } = require('./data.js');
18
+ const { DEPTH, kindKeyOf } = require('./data.js');
19
19
 
20
20
  const invalid = (code, reason) => new SchemaDefinitionError(code, reason);
21
21
 
@@ -416,7 +416,7 @@ const optionsOf = (options) => {
416
416
  } = options;
417
417
  if (as !== 'definition' && as !== 'schema') throw option('as', '"definition" or "schema"');
418
418
  if (typeof name !== 'string') throw option('name', 'a string');
419
- if (typeof kind !== 'string' || kind === '') throw option('kind', 'the name of a kind');
419
+ if (kindKeyOf(kind) === null) throw option('kind', 'the name of a kind');
420
420
  if (cap !== false && (!Number.isInteger(cap) || cap < 0)) {
421
421
  throw option('enum', 'an integer of at least 0, or false');
422
422
  }
@@ -475,7 +475,7 @@ const infer = (samples, options = {}) => {
475
475
  if (form === null) definition = bareOf(root.bits, (root.bits & UNDEF) !== 0);
476
476
  else if (form.struct === undefined) definition = written(form, presence);
477
477
  else if (presence === REQUIRED) {
478
- definition = { [capitalize(state.kind)]: {} };
478
+ definition = { [kindKeyOf(state.kind)]: {} };
479
479
  for (const key of Object.keys(form.struct)) define(definition, key, form.struct[key]);
480
480
  } else definition = written({ def: { union: [written(form, REQUIRED)] } }, presence);
481
481
  const schema = new Schema(state.name, definition);
@@ -24,7 +24,7 @@ const {
24
24
  isSnapshot,
25
25
  checkRoot,
26
26
  isFunctionMarker,
27
- capitalize,
27
+ kindKeyOf,
28
28
  } = require('./data.js');
29
29
 
30
30
  const nothing = () => undefined;
@@ -146,6 +146,13 @@ const entityDef = (name, entity, context) => {
146
146
  if (!isObject(entity) || typeof entity.kind !== 'string' || !isFirstLower(entity.kind)) {
147
147
  throw invalidSnapshot('An entity of a snapshot needs a kind');
148
148
  }
149
+ // A kind is written as the first key of the definition: one that would not
150
+ // be read back as a kind from there would turn into a field.
151
+ const kindKey = kindKeyOf(entity.kind);
152
+ if (kindKey === null) {
153
+ const kind = JSON.stringify(shorten(entity.kind));
154
+ throw invalidSnapshot(`The kind ${kind} of an entity is not the name of a kind`);
155
+ }
149
156
  const { scope, store, allow, unknown, parent, custom, fields, indexes } = entity;
150
157
  if (parent !== undefined && typeof parent !== 'string') {
151
158
  throw invalidSnapshot('The parent of an entity must be a name');
@@ -160,7 +167,7 @@ const entityDef = (name, entity, context) => {
160
167
  // `unknown` through its metadata.
161
168
  const revived = revive(custom, 'custom', `${name}.custom`, 0, context);
162
169
  const meta = { ...revived, scope, store, allow, unknown, parent };
163
- const def = { [capitalize(entity.kind)]: meta };
170
+ const def = { [kindKey]: meta };
164
171
  const struct = structDef(fields, name, 0, context);
165
172
  for (const key of Object.keys(struct)) define(def, key, struct[key]);
166
173
  for (const key of Object.keys(indexes ?? {})) {
@@ -1,11 +1,14 @@
1
1
  const { isFirstUpper, toLowerCamel, firstKey } = require('./metautil.js');
2
2
 
3
3
  const { hasBrand, formatters, typeOf } = require('./util.js');
4
+ const { constants, isKindKey } = require('./kinds.js');
4
5
  const { SchemaDefinitionError } = require('./errors.js');
5
6
 
6
7
  // The first key of an object decides what it is: a Schema or a built field is
7
- // used as it is, a capitalized key is a kind, `type` is the long form, a type
8
- // name is that type's shorthand, and anything else is a nested struct.
8
+ // used as it is, a kind key (`isKindKey` of kinds.js: a name like `Entity`
9
+ // holding the metadata object) is a kind, `type` is the long form, a type
10
+ // name is that type's shorthand, and anything else is a nested struct, a
11
+ // capitalized key that is no kind (`PORT`, `Name: 'string'`) included.
9
12
  const PARSERS = Object.assign(Object.create(null), {
10
13
  string: ['stringShorthand'],
11
14
  object: [
@@ -31,6 +34,7 @@ class Preprocessor {
31
34
  this.Schema = root.constructor;
32
35
  this.root = root;
33
36
  this.types = root.types;
37
+ this.kinds = null;
34
38
  }
35
39
 
36
40
  // The first key of an object is read once here and handed to the parsers
@@ -102,9 +106,15 @@ class Preprocessor {
102
106
 
103
107
  schemaWithKind(source, first) {
104
108
  const { types, root } = this;
105
- if (!isFirstUpper(first)) return null;
109
+ if (!isKindKey(first, source[first])) return null;
106
110
  const { [first]: meta, ...fields } = source;
107
111
  const kind = toLowerCamel(first);
112
+ // A kind of the program's own is kept for the lint: metadata that reads
113
+ // as field definitions is most likely a field that was read as a kind.
114
+ if (!constants.KIND.includes(kind)) {
115
+ if (this.kinds === null) this.kinds = [];
116
+ this.kinds.push([first, meta]);
117
+ }
108
118
  const kindMeta = { kind, meta, root };
109
119
  const defs = { schema: fields };
110
120
  return { Type: types.schema, defs, kindMeta };
@@ -1,18 +1,18 @@
1
- const { isFirstUpper } = require('../metautil.js');
2
1
  const { formatters } = require('../util.js');
3
2
  const { SchemaDefinitionError } = require('../errors.js');
4
3
 
5
4
  const invalidTuple = (reason) => new SchemaDefinitionError('ERR_INVALID_TUPLE', `Tuple ${reason}`);
6
5
 
7
- // A named element is `{ name: 'type' }`: one key that is not `type`, a type
8
- // name or a kind, holding a type name. Anything else is a definition of its
9
- // own (a nested struct, a collection, a tuple).
6
+ // A named element is `{ name: 'type' }`: one key that is not `type` or a type
7
+ // name, holding a type name (a string is no metadata of a kind, so `{ X:
8
+ // 'number' }` is a name too). Anything else is a definition of its own (a
9
+ // nested struct, a collection, a tuple).
10
10
  const nameOf = (element, types) => {
11
11
  if (element === null || typeof element !== 'object' || Array.isArray(element)) return null;
12
12
  const keys = Object.keys(element);
13
13
  if (keys.length !== 1 || typeof element[keys[0]] !== 'string') return null;
14
14
  const { field } = formatters.key(keys[0]);
15
- if (field === 'type' || types[field] || isFirstUpper(field)) return null;
15
+ if (field === 'type' || types[field]) return null;
16
16
  return keys[0];
17
17
  };
18
18
 
package/src/schema.js CHANGED
@@ -7,6 +7,7 @@ const {
7
7
  COERCES,
8
8
  CODEC,
9
9
  STANDARD,
10
+ KINDS,
10
11
  hasBrand,
11
12
  } = require('./util.js');
12
13
  const { TYPES } = require('./types.js');
@@ -83,11 +84,13 @@ class Schema extends SchemaMetadata {
83
84
  // the cycle detection (only a struct with references can reach it
84
85
  // again), whether parse coerces unless the call says otherwise (the
85
86
  // `coerce` of the kind metadata, read once: an own property would shadow
86
- // the method the `./coerce` subpath installs), and its caches.
87
+ // the method the `./coerce` subpath installs), its caches, and the kinds
88
+ // of the program's own the definition named, for the lint.
87
89
  this[TRACKED] = isSchemaType && this.relations.size > 0;
88
90
  this[COERCES] = Object.hasOwn(this.custom, 'coerce') && this.custom.coerce === true;
89
91
  this[CODEC] = null;
90
92
  this[STANDARD] = null;
93
+ this[KINDS] = preprocessor.kinds;
91
94
  this[RUN] = lazyRun(this);
92
95
  const hook = Schema[HOOK];
93
96
  if (hook !== undefined) hook(this);
package/src/types.js CHANGED
@@ -79,10 +79,13 @@ const TYPES = createTypes(PROTOTYPES);
79
79
  const createRegistry = () => createTypes(PROTOTYPES);
80
80
 
81
81
  // Whether a dictionary of fields reads as a struct under the first-key rule
82
- // (`preprocessor.js`): the first key that starts with a letter is a kind
83
- // when capitalized, the long form when it is `type` and a shorthand when it
84
- // is a type name of the registry; a struct that reads otherwise needs the
85
- // `schema` shorthand around it. What generates a definition asks here.
82
+ // (`preprocessor.js`): the first key that starts with a letter may be a kind
83
+ // when capitalized, is the long form when it is `type` and a shorthand when
84
+ // it is a type name of the registry; a struct that reads otherwise needs the
85
+ // `schema` shorthand around it. What generates a definition asks here, and
86
+ // the answer for a capitalized key is the careful one on purpose (whatever
87
+ // the key holds, where `isKindKey` of kinds.js looks at it): the definition
88
+ // then reads the same for `Infer`, which sees no key order, and for 3.4.0.
86
89
  const readsAsStruct = (fields, types = TYPES) => {
87
90
  const first = firstKey(fields);
88
91
  if (first === undefined) return true;
package/src/util.js CHANGED
@@ -82,6 +82,10 @@ const TRACKED = Symbol('tracked');
82
82
  const COERCES = Symbol('coerces');
83
83
  const CODEC = Symbol('codec');
84
84
  const STANDARD = Symbol('standard');
85
+ // The kinds of the program's own a definition named, at any depth, as
86
+ // [key, metadata] pairs (null when there is none): the lint of the
87
+ // validation half reads them for `ambiguous-kind`.
88
+ const KINDS = Symbol('kinds');
85
89
  // The recursive dependencies a model met while ordering its entities, as
86
90
  // [entity, reference] pairs: the validation half writes the warnings.
87
91
  const CYCLES = Symbol('cycles');
@@ -141,6 +145,7 @@ module.exports = {
141
145
  COERCES,
142
146
  CODEC,
143
147
  STANDARD,
148
+ KINDS,
144
149
  CYCLES,
145
150
  ENUM_SET_SIZE,
146
151
  shorten,