@alexify/metaschema 3.0.0 → 3.2.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.
Files changed (47) hide show
  1. package/CHANGELOG.md +312 -1
  2. package/README.md +463 -17
  3. package/SECURITY.md +26 -7
  4. package/index.d.ts +338 -3
  5. package/package.json +42 -5
  6. package/src/codec.js +161 -73
  7. package/src/compile/code.js +1 -1
  8. package/src/compile/emit.js +60 -7
  9. package/src/compile/index.d.ts +6 -0
  10. package/src/compile/index.js +14 -3
  11. package/src/context.js +8 -9
  12. package/src/errors.js +18 -1
  13. package/src/formats/index.d.ts +19 -0
  14. package/src/formats/index.js +146 -0
  15. package/src/generators/fromjsonschema.js +517 -0
  16. package/src/generators/index.d.ts +19 -2
  17. package/src/generators/index.js +16 -10
  18. package/src/generators/jsonschema.js +2 -0
  19. package/src/issues.js +37 -20
  20. package/src/lint.js +12 -3
  21. package/src/locales/en.js +11 -2
  22. package/src/locales/uk.js +10 -2
  23. package/src/metadata.js +3 -2
  24. package/src/model/data.js +122 -0
  25. package/src/model/diff.js +439 -0
  26. package/src/model/index.d.ts +68 -0
  27. package/src/model/index.js +45 -0
  28. package/src/model/infer.js +483 -0
  29. package/src/model/merge.js +255 -0
  30. package/src/model/pattern.js +322 -0
  31. package/src/model/restore.js +226 -0
  32. package/src/model/sample.js +398 -0
  33. package/src/model.js +13 -1
  34. package/src/preprocessor.js +5 -1
  35. package/src/prototypes/collections.js +4 -3
  36. package/src/prototypes/scalars.js +4 -4
  37. package/src/prototypes/schema.js +6 -5
  38. package/src/prototypes/union.js +2 -2
  39. package/src/result.js +6 -0
  40. package/src/rules.js +53 -4
  41. package/src/schema.js +28 -7
  42. package/src/snapshot.js +111 -0
  43. package/src/stream/index.d.ts +68 -0
  44. package/src/stream/index.js +247 -0
  45. package/src/struct.js +64 -18
  46. package/src/types.js +14 -1
  47. package/src/util.js +18 -0
package/SECURITY.md CHANGED
@@ -55,13 +55,32 @@ Some things work as intended and are not vulnerabilities:
55
55
  check the generator cannot build is reported (`compile().error`, `register({ onFallback })`),
56
56
  never installed. The core entry never calls `new Function`.
57
57
  - **Input shape is checked strictly.** Every key that is not in the schema is reported as
58
- unexpected (`has unexpected keys: ...`), including `constructor`, `__proto__` and `toString`,
59
- unless the schema or the call says `unknown: 'ignore'`. Fields live in a
60
- null-prototype dictionary, so nothing on `Object.prototype` is ever read as a field, and
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.
58
+ unexpected (`has unexpected keys: ...`, the first ten of them), including `constructor`,
59
+ `__proto__` and `toString`, unless the schema or the call says `unknown: 'ignore'`. Fields
60
+ live in a null-prototype dictionary, so nothing on `Object.prototype` is ever read as a
61
+ field, and metaschema never writes to the value it checks. A built-in (`Map`, `Set`, `Date`)
62
+ is recognised by the name of its constructor and by its shape (an iterator, `getTime`), so a
63
+ value parsed from JSON that carries `{ "constructor": { "name": "Map" } }` is a type issue,
64
+ not a value the check iterates. A value with a `then` function is data: the passes of
65
+ `parse` and `parseAsync` await only the promises their own decoders make, never a thenable
66
+ of the value. A graph nested deeper than `maxDepth` embedded records (128 by default) is a
67
+ `depth` issue, not a stack overflow.
68
+ - **A `pattern` or a `format` is never run over a string longer than `length.max`.** The bound
69
+ is what keeps a backtracking expression fast, so give every pattern one (the lint says where
70
+ one is missing); the built-in formats are linear and anchored, a custom format's `test` is
71
+ the program's code, like a `validate` function. A pattern taken from a document given to
72
+ `fromJSONSchema` or a snapshot given to `fromJSON` runs as a regular expression in `check`
73
+ all the same: those documents are untrusted input for their structure (a keyword outside the
74
+ subset, a key named `__proto__`, a depth past the limit are errors, never a looser schema),
75
+ but a pattern in them is the importer's to review or to bound.
76
+ - **Samples are input.** `infer` of the model subpath walks the values it is given with a depth
77
+ limit, trusts no key (`__proto__`, `constructor` and the names of the methods of a field are
78
+ keys of the definition, written as own properties), and checks the definition it built
79
+ against every sample before it returns it. A key of a sample that reaches an error message
80
+ is truncated to 100 characters, as a key of a value under check is.
81
+ - **The error a stream ends with carries the record.** `ERR_INVALID_RECORD` of the stream
82
+ subpath has `record` and `result` on it, since the stream carries them no further; a logger
83
+ that serializes error objects writes the record.
65
84
  - **Validation errors are data.** `check` collects problems as issues (a code, a path and params,
66
85
  with a rendered message) instead of throwing on bad input. The messages contain field paths (which can include key names taken from the input,
67
86
  truncated to 100 characters) and, for `enum`, the allowed values; they never contain the
package/index.d.ts CHANGED
@@ -37,6 +37,7 @@ export type IssueCode =
37
37
  | 'length'
38
38
  | 'range'
39
39
  | 'pattern'
40
+ | 'format'
40
41
  | 'union'
41
42
  | 'reference'
42
43
  | 'circular'
@@ -56,6 +57,8 @@ export interface IssueParams {
56
57
  range: { min: number | bigint | undefined; max: number | bigint | undefined; actual: number | bigint };
57
58
  // The source of the pattern the string did not match.
58
59
  pattern: { pattern: string };
60
+ // The name of the format the string is not of.
61
+ format: { format: string };
59
62
  // No branch of a union matched: the branch names, or the discriminator
60
63
  // values when the union has a discriminator (the path then ends with it).
61
64
  union: { expected: unknown[]; discriminator: string | undefined };
@@ -192,6 +195,8 @@ export class ValidationResult {
192
195
  add(error: ValidationReturn, code?: IssueCode): this;
193
196
  flatten(): FlatIssues;
194
197
  tree(): IssueTree;
198
+ // The result as data: what JSON.stringify(result) writes.
199
+ toJSON(): { valid: boolean; issues: ValidationIssue[] };
195
200
  static issuesOf(error: ValidationReturn, path?: PropertyKey[], code?: IssueCode): ValidationIssue[];
196
201
  static isInstance(error: unknown): boolean;
197
202
  }
@@ -220,6 +225,9 @@ export interface CheckContext {
220
225
  async: unknown[] | null;
221
226
  // The context parse tries the branches of a plain union in; null in a check.
222
227
  scratch: CheckContext | null;
228
+ // Whether the check read a field from one of its aliases: the pass after it
229
+ // renames only when it did.
230
+ renamed: boolean;
223
231
  }
224
232
 
225
233
  // A validator may return a promise of its result to checkAsync and parseAsync;
@@ -245,6 +253,11 @@ export interface FieldType {
245
253
  serialize?: (value: any) => unknown;
246
254
  // What parse fills a missing key with: a value, or a function called for one.
247
255
  default?: unknown;
256
+ // The keys the field is also read from, in a struct: check accepts a value
257
+ // under an alias in place of the field's key, parse renames it. The keys
258
+ // of the value the schema accepts (`Infer`) and the generated documents
259
+ // name the field's own key only.
260
+ aliases?: string[];
248
261
  // Records the problems of a value into the context of the current check.
249
262
  check(value: unknown, context: CheckContext): void;
250
263
  toJSON(): object;
@@ -262,11 +275,23 @@ export interface TypeConstructor {
262
275
 
263
276
  export type TypeTable = Record<string, TypeConstructor>;
264
277
 
278
+ // What `sample` of the `@alexify/metaschema/model` subpath draws for a
279
+ // custom type: the value `metadata.sample` holds, or what the function it
280
+ // holds returns for the field and the seeded generator of the draw.
281
+ export type SampleHook = (field: FieldType, random: () => number) => unknown;
282
+
283
+ // The metadata of a type: anything, read by the programs built on the
284
+ // model; `sample` is the one key the package reads (see `SampleHook`).
285
+ export interface TypeMetadata {
286
+ sample?: SampleHook | {} | null;
287
+ [key: string]: unknown;
288
+ }
289
+
265
290
  // An entry of the table passed to Model: metadata for a built-in, an alias
266
291
  // (`js`), or a prototype with its own `construct` and `checkType`.
267
292
  export interface TypeEntry {
268
293
  js?: string;
269
- metadata?: Record<string, unknown>;
294
+ metadata?: TypeMetadata;
270
295
  kind?: 'scalar' | 'struct';
271
296
  // The rules the type accepts in a field definition (`length`, `min`, `max`).
272
297
  rules?: string[];
@@ -316,6 +341,29 @@ export type DefinitionErrorCode =
316
341
  | 'ERR_UNKNOWN_JS_TYPE'
317
342
  | 'ERR_INVALID_OPTIONS'
318
343
  | 'ERR_UNREPRESENTABLE'
344
+ // Thrown by `fromJSONSchema` of the generators subpath for a keyword the
345
+ // subset has no form for.
346
+ | 'ERR_UNSUPPORTED_SCHEMA'
347
+ // Thrown by `fromJSON` and `diff` of the `@alexify/metaschema/model`
348
+ // subpath for a value that is not a snapshot of a model.
349
+ | 'ERR_INVALID_SNAPSHOT'
350
+ // Thrown by `sample` of the same subpath: a field no value satisfies, a
351
+ // pattern it cannot read, a custom type without `metadata.sample`.
352
+ | 'ERR_UNSATISFIABLE'
353
+ | 'ERR_SAMPLE_PATTERN'
354
+ | 'ERR_SAMPLE_TYPE'
355
+ // Thrown by `merge` of the same subpath for what no value can satisfy.
356
+ | 'ERR_MERGE_CONFLICT'
357
+ // Thrown by `infer` of the same subpath: a sample nested deeper than
358
+ // `maxDepth`, and a definition that rejects a sample it was inferred from
359
+ // (a bug of the inference, to report).
360
+ | 'ERR_INFER_DEPTH'
361
+ | 'ERR_INFER_MISMATCH'
362
+ // Thrown by `register` of the `@alexify/metaschema/formats` subpath: an
363
+ // entry that is not a format, and a name registered again with another
364
+ // test.
365
+ | 'ERR_INVALID_FORMAT'
366
+ | 'ERR_FORMAT_REGISTERED'
319
367
  // Thrown by `compile` and `register` of the `@alexify/metaschema/compile`
320
368
  // subpath with `jit: true` where code generation from strings is not allowed.
321
369
  | 'ERR_NO_EVAL'
@@ -335,7 +383,221 @@ export class SchemaDefinitionError extends TypeError {
335
383
  // The code of the TypeError a synchronous check or parse throws when a
336
384
  // validator, a custom checkType or a decoder returns a promise: the call,
337
385
  // not the definition, is wrong, so it is a plain TypeError with `code`.
338
- export type RuntimeErrorCode = 'ERR_ASYNC_VALIDATOR';
386
+ // `ERR_INVALID_TARGET` is the same kind of error from a function of a subpath
387
+ // given something other than what it takes (a Schema, a Model, a snapshot, a
388
+ // list of changes).
389
+ export type RuntimeErrorCode = 'ERR_ASYNC_VALIDATOR' | 'ERR_INVALID_TARGET' | 'ERR_INVALID_RECORD';
390
+
391
+ // ---------------------------------------------------------------------------
392
+ // The snapshot: `model.toJSON()`, what JSON.stringify(model) writes. The
393
+ // entities in dependency order with a fixed key order, the types the
394
+ // entities use, and the `database` metadata as given. A function is
395
+ // `{ $function: true }` wherever it stands, a bigint `{ $bigint }`, a Date
396
+ // `{ $date }`, a RegExp its source (or `{ source, flags }` with flags beyond
397
+ // `u`). `fromJSON` of the `@alexify/metaschema/model` subpath reads it back.
398
+ // ---------------------------------------------------------------------------
399
+
400
+ export interface FunctionSnapshot {
401
+ $function: true;
402
+ }
403
+
404
+ // A field of a snapshot: its type and whether it is required first, then
405
+ // the other keys of its definition, sorted (a nested struct under `schema`,
406
+ // an element under `value`, branches under `union`).
407
+ export interface FieldSnapshot {
408
+ type: string;
409
+ required: boolean;
410
+ [key: string]: unknown;
411
+ }
412
+
413
+ // The fields of a struct in their order: a calculated field, the validate,
414
+ // parse or serialize of the struct are `{ $function: true }`.
415
+ export type FieldsSnapshot = Record<string, FieldSnapshot | FunctionSnapshot>;
416
+
417
+ export interface EntitySnapshot {
418
+ kind: Kind;
419
+ scope: Scope;
420
+ store: Store;
421
+ allow: Allow;
422
+ // The parent of a projection, '' otherwise.
423
+ parent: string;
424
+ unknown: 'reject' | 'ignore';
425
+ // The other keys of the kind metadata, as given.
426
+ custom: Record<string, unknown>;
427
+ // A struct's fields, with the schema-level functions among them, or
428
+ fields?: FieldsSnapshot;
429
+ // the type of a schema of one type.
430
+ type?: FieldSnapshot;
431
+ // The index definitions (`index`, `primary`, `unique` lists), as given.
432
+ indexes: Record<string, object>;
433
+ relations: Relation[];
434
+ }
435
+
436
+ // A type the entities use: an alias of a built-in (`js`), a type with a
437
+ // check of its own (`check: true`, its kind), or a built-in with metadata.
438
+ export interface TypeSnapshot {
439
+ js?: string;
440
+ kind?: 'scalar' | 'struct';
441
+ check?: true;
442
+ metadata: Record<string, unknown>;
443
+ }
444
+
445
+ export interface ModelSnapshot {
446
+ format: 1;
447
+ database: Record<string, unknown> | null;
448
+ types: Record<string, TypeSnapshot>;
449
+ entities: Record<string, EntitySnapshot>;
450
+ }
451
+
452
+ // The options of `fromJSON` of the `@alexify/metaschema/model` subpath.
453
+ export interface RestoreOptions {
454
+ // Entries of the table Model takes, over the types of the snapshot: the
455
+ // real custom types, where the restored model should validate as the
456
+ // original did.
457
+ types?: Record<string, TypeEntry>;
458
+ // 'isolated' (the default) gives the restored model its own registry, so
459
+ // the placeholders of its custom types never reach the shared one; a
460
+ // 'shared' registry takes no placeholder type (`ERR_INVALID_SNAPSHOT`
461
+ // unless `types` brings the real one).
462
+ registry?: 'shared' | 'isolated';
463
+ }
464
+
465
+ // A model restored by `fromJSON`: a Model that lists the paths of the
466
+ // placeholders standing in for the functions of the snapshot (`Order.validate`,
467
+ // `Order.total` for a calculated field, `Order.address.parse`, `Order.when.default`,
468
+ // `types.hex.checkType`), invisibly to `toJSON`.
469
+ export interface RestoredModel extends Model {
470
+ readonly placeholders: string[];
471
+ }
472
+
473
+ // ---------------------------------------------------------------------------
474
+ // The evolution of a model: `diff` and `compatibility` of the
475
+ // `@alexify/metaschema/model` subpath.
476
+ // ---------------------------------------------------------------------------
477
+
478
+ export type ChangeKind = 'entity' | 'field' | 'index' | 'relation' | 'type';
479
+
480
+ export type ChangeOp = 'added' | 'removed' | 'changed' | 'renamed';
481
+
482
+ // One change between two versions of a model: what changed (`kind`), how
483
+ // (`op`), in which entity ('' for a type), under which name (the entity, the
484
+ // field, the index, the target of a relation, the type), what it was
485
+ // (`from`) and is (`to`), and the detail: the keys that differ for a
486
+ // `changed` entity, field, index or type; the old key (`renamed`) and the
487
+ // keys that differ beyond `aliases` for a field renamed through an alias;
488
+ // `deprecated: true` for a removed field that was marked so.
489
+ export interface SchemaChange {
490
+ kind: ChangeKind;
491
+ op: ChangeOp;
492
+ entity: string;
493
+ name: string;
494
+ from?: unknown;
495
+ to?: unknown;
496
+ detail?: { keys?: string[]; renamed?: string; deprecated?: true };
497
+ }
498
+
499
+ // 'backward': a reader with the new model reads data written with the old
500
+ // one; 'forward': a reader with the old model reads data written with the
501
+ // new one; 'full': both; 'none': neither.
502
+ export type Compatibility = 'full' | 'backward' | 'forward' | 'none';
503
+
504
+ // The options of `merge` of the `@alexify/metaschema/model` subpath.
505
+ export interface MergeOptions {
506
+ // The name of the merged schema: the first schema's by default.
507
+ name?: string;
508
+ // The kind metadata of the merged schema, over the first schema's: `kind`,
509
+ // `scope`, `store`, `allow`, `unknown` and any other key.
510
+ metadata?: Partial<KindMetadata>;
511
+ }
512
+
513
+ // The options of `infer` of the `@alexify/metaschema/model` subpath (the
514
+ // name sits beside the type `Infer<D>`: the function reads samples, the type
515
+ // reads a definition).
516
+ export interface InferOptions {
517
+ // What comes back: the definition ('definition', the default), or a Schema
518
+ // built from it ('schema').
519
+ as?: 'definition' | 'schema';
520
+ // The name of the Schema, and of the error locations ('').
521
+ name?: string;
522
+ // The kind of a root that is a struct ('struct'); a stored kind adds its
523
+ // id field, which wins over an inferred field of that name.
524
+ kind?: string;
525
+ // The most distinct strings a place may hold to be an enum (8), each
526
+ // value seen twice on average over at least four samples; 0 or false never.
527
+ enum?: number | false;
528
+ // Whether whole numbers are `integer` (true) rather than `number`.
529
+ integer?: boolean;
530
+ // The distinct keys past which records of a place read as a dictionary
531
+ // (16) when every key is missing from some record and the values are of
532
+ // one kind; keys that are not names are a dictionary from one sample on;
533
+ // false keeps every record a struct.
534
+ map?: number | false;
535
+ // How deep a sample may nest (128, the most); past it `ERR_INFER_DEPTH`.
536
+ maxDepth?: number;
537
+ // Whether a place whose every string passes a registered format is that
538
+ // format (true); the formats subpath registers them, in the order `infer`
539
+ // tries them, and nothing is registered until its `register()` ran.
540
+ formats?: boolean;
541
+ }
542
+
543
+ // The options of `sample` of the `@alexify/metaschema/model` subpath.
544
+ export interface SampleOptions {
545
+ // The seed of the generator (1): the same seed gives the same value.
546
+ seed?: number;
547
+ // The letters of free strings: 'en' (the default) or 'uk'.
548
+ locale?: 'en' | 'uk';
549
+ // How a reference is held, as in check: an id for a stored kind and the
550
+ // record for a memory kind ('kind', the default), always the record
551
+ // ('embed'), always an id ('id').
552
+ references?: 'kind' | 'embed' | 'id';
553
+ // How deep embedded records nest (3): an optional reference deeper than
554
+ // that is left out, a required one is an error.
555
+ maxDepth?: number;
556
+ }
557
+
558
+ // The options of `checkEach` and `checkEachAsync` of the
559
+ // `@alexify/metaschema/stream` subpath: those of `check`, and how many invalid
560
+ // records end the iteration (no limit by default).
561
+ export interface EachOptions extends CheckOptions {
562
+ maxInvalid?: number;
563
+ }
564
+
565
+ // The options of `parseEach` and `parseEachAsync`: those of `parse`, and
566
+ // `maxInvalid`.
567
+ export interface ParseEachOptions extends ParseOptions {
568
+ maxInvalid?: number;
569
+ }
570
+
571
+ // The option of the async pair: how many records are in flight at once (1).
572
+ export interface EachAsyncOptions {
573
+ concurrency?: number;
574
+ }
575
+
576
+ // The options of `transform`: those of `parse` (or of `check`, with
577
+ // `mode: 'check'`), `maxInvalid`, and what the stream does with an invalid
578
+ // record.
579
+ export interface TransformOptions extends ParseOptions {
580
+ // What goes on down the stream: the parsed value ('parse', the default) or
581
+ // the record as it is ('check').
582
+ mode?: 'parse' | 'check';
583
+ // Whether the stream runs `parseAsync`/`checkAsync` (false).
584
+ async?: boolean;
585
+ // Told of every invalid record, which is then dropped; without it the
586
+ // stream ends with the error at the first one.
587
+ onInvalid?: (record: unknown, result: ValidationResult | ParseResult<unknown>, index: number) => void;
588
+ // After that many invalid records the stream ends with the error even with
589
+ // `onInvalid` (no limit by default).
590
+ maxInvalid?: number;
591
+ }
592
+
593
+ // What `checkEach` and its kin yield for a record: its position in the
594
+ // sequence, the record as the source gave it, and the result of `check` or
595
+ // `parse`.
596
+ export interface RecordEntry<T, R> {
597
+ index: number;
598
+ record: T;
599
+ result: R;
600
+ }
339
601
 
340
602
  export const KIND: Array<string>;
341
603
  export const KIND_STORED: Array<string>;
@@ -406,6 +668,27 @@ export interface ModelJSONSchemaOptions extends JSONSchemaOptions {
406
668
  root?: string;
407
669
  }
408
670
 
671
+ // The options of `fromJSONSchema` of the generators subpath.
672
+ export interface FromJSONSchemaOptions {
673
+ // The name of the schema: what `$ref: '#'` refers to, and the name of the
674
+ // Schema built with `as: 'schema'`.
675
+ name?: string;
676
+ // What comes back: the definition (the default), or a Schema built from it.
677
+ as?: 'definition' | 'schema';
678
+ // A `$ref` into the definitions of the document: the definition in place
679
+ // ('inline', the default; a cycle has no form), or a reference to an
680
+ // entity of that name ('name'), to resolve through a Model.
681
+ references?: 'inline' | 'name';
682
+ // A keyword the subset has no form for: `ERR_UNSUPPORTED_SCHEMA` with its
683
+ // place in the document ('throw', the default), or dropped ('ignore').
684
+ unsupported?: 'throw' | 'ignore';
685
+ // Told of every drop of `unsupported: 'ignore'`: what was dropped, as the
686
+ // error of the throw mode names it (`The keyword "multipleOf"`), and its
687
+ // place in the document as a JSON pointer. Not called in the throw mode,
688
+ // where the error carries both.
689
+ onUnsupported?: (reason: string, pointer: string) => void;
690
+ }
691
+
409
692
  // Standard JSON Schema (https://standardschema.dev/json-schema): the converter
410
693
  // `schema['~standard'].jsonSchema`, whose `input` and `output` take the
411
694
  // target and the other options of `toJSONSchema` as `libraryOptions`. The
@@ -869,7 +1152,7 @@ export type InferEntity<E, Name extends keyof E & string> = Simplify<
869
1152
  // consumers of the specification accept it without an adapter. The shape is
870
1153
  // written out here because this file cannot import `@standard-schema/spec` (a
871
1154
  // devDependency); tests/types/standard.test-d.ts pins that a `Schema<D>` is a
872
- // `StandardSchemaV1<Infer<D>, Infer<D>>` of that package.
1155
+ // `StandardSchemaV1<Infer<D>, InferOutput<D>>` of that package.
873
1156
 
874
1157
  // The vendor-specific options of a `validate` call are the options of `parse`.
875
1158
  export interface StandardOptions {
@@ -912,6 +1195,23 @@ export class Schema<const D extends string | object = string | object> {
912
1195
 
913
1196
  static from<const D extends string | object>(raw: D, namespaces?: Array<Model>): Schema<D>;
914
1197
  static extractSchema(def: object): Schema | null;
1198
+ // A definition (or a Schema) from a JSON Schema document: exists once
1199
+ // `register()` of the generators subpath has run; its `fromJSONSchema` is
1200
+ // the same without it.
1201
+ static fromJSONSchema(
1202
+ document: JSONSchema | true,
1203
+ options: FromJSONSchemaOptions & { as: 'schema' },
1204
+ ): Schema;
1205
+ static fromJSONSchema(document: JSONSchema | true, options?: FromJSONSchemaOptions): object | string;
1206
+ // The schema two schemas describe, by unification: exists once `register()`
1207
+ // of the `@alexify/metaschema/model` subpath has run; its `merge(a, b)` is
1208
+ // the same without it.
1209
+ static merge(a: Schema, b: Schema, options?: MergeOptions): Schema;
1210
+ // A definition (or a Schema) that accepts every sample: exists once
1211
+ // `register()` of the `@alexify/metaschema/model` subpath has run; its
1212
+ // `infer(samples, options)` is the same without it.
1213
+ static infer(samples: Iterable<unknown>, options: InferOptions & { as: 'schema' }): Schema;
1214
+ static infer(samples: Iterable<unknown>, options?: InferOptions): object | string;
915
1215
 
916
1216
  kind: Kind;
917
1217
  scope: Scope;
@@ -958,6 +1258,31 @@ export class Schema<const D extends string | object = string | object> {
958
1258
  options: SerializeOptions & { check: true },
959
1259
  ): SerializeChecked<Infer<D>>;
960
1260
  serialize(value: InferOutput<D>, options?: SerializeOptions): Serialized<Infer<D>>;
1261
+ // A value the schema accepts, the same for a seed: exists once `register()`
1262
+ // of the `@alexify/metaschema/model` subpath has run; its `sample(schema,
1263
+ // options)` is the same without it.
1264
+ sample(options?: SampleOptions): Infer<D>;
1265
+ // The five members below exist once `register()` of the
1266
+ // `@alexify/metaschema/stream` subpath has run; its `checkEach(schema,
1267
+ // records, options)` and kin are the same without it.
1268
+ checkEach<T>(
1269
+ records: Iterable<T>,
1270
+ options?: EachOptions,
1271
+ ): Generator<RecordEntry<T, ValidationResult>, void, undefined>;
1272
+ parseEach<T>(
1273
+ records: Iterable<T>,
1274
+ options?: ParseEachOptions,
1275
+ ): Generator<RecordEntry<T, ParseResult<InferOutput<D>>>, void, undefined>;
1276
+ checkEachAsync<T>(
1277
+ records: Iterable<T> | AsyncIterable<T>,
1278
+ options?: EachOptions & EachAsyncOptions,
1279
+ ): AsyncGenerator<RecordEntry<T, ValidationResult>, void, undefined>;
1280
+ parseEachAsync<T>(
1281
+ records: Iterable<T> | AsyncIterable<T>,
1282
+ options?: ParseEachOptions & EachAsyncOptions,
1283
+ ): AsyncGenerator<RecordEntry<T, ParseResult<InferOutput<D>>>, void, undefined>;
1284
+ transform(options: TransformOptions & { mode: 'check' }): TransformStream<unknown, Infer<D>>;
1285
+ transform(options?: TransformOptions): TransformStream<unknown, InferOutput<D>>;
961
1286
  // The two methods below exist once `register()` of the generators subpath
962
1287
  // has run; the subpath's `toJSONSchema(schema)` and `toTypeScript(schema)`
963
1288
  // are the same without it.
@@ -988,6 +1313,16 @@ export class Model {
988
1313
  database?: Record<string, unknown> | null,
989
1314
  options?: ModelOptions,
990
1315
  );
1316
+ // The model as plain JSON, what JSON.stringify(model) writes; see
1317
+ // `ModelSnapshot`.
1318
+ toJSON(): ModelSnapshot;
1319
+ // The four statics below exist once `register()` of the
1320
+ // `@alexify/metaschema/model` subpath has run; its `fromJSON`, `diff`,
1321
+ // `compatibility` and `compatibilityOf` are the same without it.
1322
+ static fromJSON(snapshot: ModelSnapshot, options?: RestoreOptions): RestoredModel;
1323
+ static diff(prev: Model | ModelSnapshot, next: Model | ModelSnapshot): SchemaChange[];
1324
+ static compatibility(changes: SchemaChange[]): Compatibility;
1325
+ static compatibilityOf(change: SchemaChange): Compatibility;
991
1326
  // The members below exist once `register()` of the generators subpath has
992
1327
  // run; the subpath's `toJSONSchema(model)` and `toTypeScript(model)` are the
993
1328
  // same without it.
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@alexify/metaschema",
3
- "version": "3.0.0",
4
- "description": "Zero-dependency metadata schema and interface definition language (IDL) for Node.js and browsers — data validation, domain models and TypeScript generation",
3
+ "version": "3.2.0",
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>",
7
7
  "repository": {
@@ -42,6 +42,18 @@
42
42
  "./compile": {
43
43
  "types": "./src/compile/index.d.ts",
44
44
  "default": "./src/compile/index.js"
45
+ },
46
+ "./model": {
47
+ "types": "./src/model/index.d.ts",
48
+ "default": "./src/model/index.js"
49
+ },
50
+ "./stream": {
51
+ "types": "./src/stream/index.d.ts",
52
+ "default": "./src/stream/index.js"
53
+ },
54
+ "./formats": {
55
+ "types": "./src/formats/index.d.ts",
56
+ "default": "./src/formats/index.js"
45
57
  }
46
58
  },
47
59
  "directories": {
@@ -57,6 +69,7 @@
57
69
  "LICENSE",
58
70
  "SECURITY.md"
59
71
  ],
72
+ "sideEffects": false,
60
73
  "publishConfig": {
61
74
  "access": "public"
62
75
  },
@@ -72,6 +85,11 @@
72
85
  "dsl",
73
86
  "validation",
74
87
  "data-validation",
88
+ "fast",
89
+ "jit",
90
+ "parse",
91
+ "standard-schema",
92
+ "json-schema",
75
93
  "domain-model",
76
94
  "model",
77
95
  "typescript",
@@ -81,21 +99,35 @@
81
99
  "metarhia"
82
100
  ],
83
101
  "devDependencies": {
84
- "@sinclair/typebox": "^0.34.52",
102
+ "@braintree/sanitize-url": "^7.1.2",
85
103
  "@standard-schema/spec": "^1.1.0",
86
104
  "@vercel/analytics": "^2.0.1",
87
105
  "@vercel/speed-insights": "^2.0.0",
88
106
  "ajv": "^8.20.0",
89
107
  "ajv-formats": "^3.0.1",
108
+ "arktype": "^2.2.8",
90
109
  "c8": "^12.0.0",
110
+ "cytoscape": "^3.34.3",
111
+ "cytoscape-cose-bilkent": "^4.1.0",
112
+ "dayjs": "^1.11.23",
113
+ "debug": "^4.4.3",
114
+ "effect": "^4.0.3",
91
115
  "esbuild": "^0.28.2",
116
+ "fastdom": "1.0.12",
117
+ "joi": "^18.2.9",
118
+ "mermaid": "^11.17.2",
119
+ "metaschema": "2.2.2",
92
120
  "oxfmt": "^0.72.0",
93
121
  "oxlint": "^1.75.0",
122
+ "superstruct": "^2.0.2",
94
123
  "tsd": "^0.33.0",
124
+ "typebox": "^1.3.36",
95
125
  "typescript": "^7.0.2",
96
126
  "valibot": "^1.5.0",
97
127
  "vitepress": "^1.6.4",
98
- "zod": "^4.6.5"
128
+ "vitepress-plugin-mermaid": "^2.0.17",
129
+ "yup": "^1.7.1",
130
+ "zod": "^4.6.6"
99
131
  },
100
132
  "scripts": {
101
133
  "test": "node --test tests/unit/*.test.js",
@@ -103,15 +135,20 @@
103
135
  "test:nojit": "node --disallow-code-generation-from-strings --require ./tests/helpers/jit.js --test tests/unit/*.test.js",
104
136
  "test:coverage": "c8 --all --include 'src/**' --check-coverage --lines 98 --statements 98 --branches 90 --functions 100 --reporter text --reporter lcov node --test tests/unit/*.test.js",
105
137
  "test:types": "tsd",
106
- "check:dts": "tsc --noEmit --strict --target es2022 --skipLibCheck false index.d.ts src/locales/en.d.ts src/locales/uk.d.ts src/generators/index.d.ts src/compile/index.d.ts",
138
+ "check:dts": "tsc --noEmit --strict --target es2022 --skipLibCheck false index.d.ts src/locales/en.d.ts src/locales/uk.d.ts src/generators/index.d.ts src/compile/index.d.ts src/model/index.d.ts src/stream/index.d.ts src/formats/index.d.ts",
107
139
  "lint": "oxlint index.js browser.js src tests scripts bench",
108
140
  "format": "oxfmt index.js browser.js src tests scripts bench",
109
141
  "format:check": "oxfmt --check index.js browser.js src tests scripts bench",
110
142
  "size": "node scripts/size.js",
111
143
  "bench": "node bench/bench.js",
144
+ "bench:compare": "node bench/compare.js",
145
+ "bench:releases": "node bench/releases.js",
146
+ "bench:report": "node bench/report.js",
147
+ "size:compare": "node scripts/size-compare.js",
112
148
  "docs:dev": "vitepress dev docs",
113
149
  "docs:build": "vitepress build docs",
114
150
  "docs:preview": "vitepress preview docs",
151
+ "docs:comparison": "node scripts/comparison.js",
115
152
  "release": "pnpm publish"
116
153
  }
117
154
  }