@alexify/metaschema 2.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/index.d.ts CHANGED
@@ -40,6 +40,7 @@ export type IssueCode =
40
40
  | 'union'
41
41
  | 'reference'
42
42
  | 'circular'
43
+ | 'depth'
43
44
  | 'exception'
44
45
  | 'custom';
45
46
 
@@ -60,6 +61,7 @@ export interface IssueParams {
60
61
  union: { expected: unknown[]; discriminator: string | undefined };
61
62
  reference: { entity: string };
62
63
  circular: {};
64
+ depth: { max: number };
63
65
  exception: { error: unknown };
64
66
  // A validator's own issue carries the params it gave, if any.
65
67
  custom: Record<string, unknown>;
@@ -118,6 +120,9 @@ export interface CheckOptions {
118
120
  root?: string;
119
121
  // Stop collecting after this many issues (at least 1).
120
122
  maxErrors?: number;
123
+ // How deep a value may nest through embedded references (an integer of at
124
+ // least 1, 128 by default): a record deeper than that is a `depth` issue.
125
+ maxDepth?: number;
121
126
  // What to do with keys the schema does not have: report them as one
122
127
  // `unexpected` issue per struct, or ignore them. The default is the
123
128
  // schema's own `unknown` metadata, 'reject' unless it says otherwise.
@@ -130,6 +135,33 @@ export interface CheckOptions {
130
135
  messages?: Messages;
131
136
  }
132
137
 
138
+ // The options of parse: those of check, and `strip` for the keys the schema
139
+ // does not have, which the output then leaves out.
140
+ export interface ParseOptions extends Omit<CheckOptions, 'unknown'> {
141
+ unknown?: 'reject' | 'ignore' | 'strip';
142
+ }
143
+
144
+ // What parse returns: the output only for a valid value, the issues always.
145
+ export type ParseResult<T> =
146
+ | { valid: true; value: T; issues: [] }
147
+ | { valid: false; value: undefined; issues: ValidationIssue[] };
148
+
149
+ // The options of serialize: `check` validates the result with the other
150
+ // options as the options of check.
151
+ export interface SerializeOptions extends CheckOptions {
152
+ check?: boolean;
153
+ }
154
+
155
+ export interface Serialized<T> {
156
+ value: T;
157
+ }
158
+
159
+ export interface SerializeChecked<T> {
160
+ valid: boolean;
161
+ value: T;
162
+ issues: ValidationIssue[];
163
+ }
164
+
133
165
  export interface ResultOptions {
134
166
  // The label the error lines start with (the schema name in a check).
135
167
  root?: string;
@@ -169,15 +201,30 @@ export interface CheckContext {
169
201
  issues: ValidationIssue[];
170
202
  count: number;
171
203
  limit: number;
204
+ // How many embedded records the check is inside, and how many it may be
205
+ // before a record is a `depth` issue (128 by default).
206
+ depth: number;
207
+ maxDepth: number;
172
208
  path: PropertyKey[];
173
209
  seen: Set<object> | null;
174
- unknown: 'reject' | 'ignore';
210
+ // The value the check started from, when the schema can reach it again
211
+ // through a reference; null otherwise.
212
+ source: unknown;
213
+ // 'strip' in a parse, where the check behind it treats it as 'ignore'.
214
+ unknown: 'reject' | 'ignore' | 'strip';
175
215
  references: 'kind' | 'embed' | 'id';
176
216
  root: string;
177
217
  messages: Messages;
218
+ // The validators that returned a promise, settled after the walk by
219
+ // checkAsync and parseAsync; null in a synchronous check.
220
+ async: unknown[] | null;
221
+ // The context parse tries the branches of a plain union in; null in a check.
222
+ scratch: CheckContext | null;
178
223
  }
179
224
 
180
- export type Validator = (value: any, path: string) => ValidationReturn;
225
+ // A validator may return a promise of its result to checkAsync and parseAsync;
226
+ // to check and parse a promise is a TypeError with the code ERR_ASYNC_VALIDATOR.
227
+ export type Validator = (value: any, path: string) => ValidationReturn | Promise<ValidationReturn>;
181
228
 
182
229
  export type CalculatedField = (value: any) => unknown;
183
230
 
@@ -192,6 +239,12 @@ export interface FieldType {
192
239
  // (false) whatever the kind of its target.
193
240
  embed?: boolean;
194
241
  validate?: Validator;
242
+ // The decoder parse runs on the validated value, and the serializer
243
+ // serialize runs on the value of the program, when the definition gave them.
244
+ parse?: (value: any) => unknown;
245
+ serialize?: (value: any) => unknown;
246
+ // What parse fills a missing key with: a value, or a function called for one.
247
+ default?: unknown;
195
248
  // Records the problems of a value into the context of the current check.
196
249
  check(value: unknown, context: CheckContext): void;
197
250
  toJSON(): object;
@@ -218,7 +271,7 @@ export interface TypeEntry {
218
271
  // The rules the type accepts in a field definition (`length`, `min`, `max`).
219
272
  rules?: string[];
220
273
  construct?(def: object, preprocessor: object): void;
221
- checkType?(value: any, path: string): ValidationReturn;
274
+ checkType?(value: any, path: string): ValidationReturn | Promise<ValidationReturn>;
222
275
  [key: string]: unknown;
223
276
  }
224
277
 
@@ -261,7 +314,15 @@ export type DefinitionErrorCode =
261
314
  | 'ERR_RESERVED_KEY'
262
315
  | 'ERR_TYPE_REGISTERED'
263
316
  | 'ERR_UNKNOWN_JS_TYPE'
264
- | 'ERR_INVALID_OPTIONS';
317
+ | 'ERR_INVALID_OPTIONS'
318
+ | 'ERR_UNREPRESENTABLE'
319
+ // Thrown by `compile` and `register` of the `@alexify/metaschema/compile`
320
+ // subpath with `jit: true` where code generation from strings is not allowed.
321
+ | 'ERR_NO_EVAL'
322
+ // The check of a schema could not be generated (the generator's error is the
323
+ // `cause`): thrown with `jit: true`, reported as `error` and to `onFallback`
324
+ // in the default mode.
325
+ | 'ERR_JIT_BUILD';
265
326
 
266
327
  export class SchemaDefinitionError extends TypeError {
267
328
  code: DefinitionErrorCode;
@@ -271,6 +332,11 @@ export class SchemaDefinitionError extends TypeError {
271
332
  locate(schema: string, field: string): this;
272
333
  }
273
334
 
335
+ // The code of the TypeError a synchronous check or parse throws when a
336
+ // validator, a custom checkType or a decoder returns a promise: the call,
337
+ // not the definition, is wrong, so it is a plain TypeError with `code`.
338
+ export type RuntimeErrorCode = 'ERR_ASYNC_VALIDATOR';
339
+
274
340
  export const KIND: Array<string>;
275
341
  export const KIND_STORED: Array<string>;
276
342
  export const KIND_MEMORY: Array<string>;
@@ -283,7 +349,77 @@ export function getKindMetadata(
283
349
  meta?: Record<string, unknown>,
284
350
  root?: Schema,
285
351
  ): { defs: Record<string, unknown>; metadata: KindMetadata };
286
- export function saveTypes(outputFile: string, model: Model): Promise<void>;
352
+ // ---------------------------------------------------------------------------
353
+ // The generators: JSON Schema and TypeScript. The functions live in the
354
+ // `@alexify/metaschema/generators` subpath (`toJSONSchema`, `toTypeScript`,
355
+ // `saveTypes`); its `register()` installs the methods declared on `Schema`
356
+ // and `Model` below and the Standard JSON Schema converter. The option
357
+ // types are here so that the core and the subpath share them.
358
+ // ---------------------------------------------------------------------------
359
+
360
+ // The options of `toTypeScript`, `toInterface` and `saveTypes`.
361
+ export interface InterfaceOptions {
362
+ // Give a nested struct and an enum a type of their own, named after the
363
+ // entity and the field (`interface AccountFullName`, `type IdentifierStorage`),
364
+ // rendered before the interface that uses them.
365
+ named?: boolean;
366
+ }
367
+
368
+ // The JSON Schema export renders the rules of `check` as a document of a
369
+ // target dialect; see the JSON Schema guide for the mapping.
370
+ export type JSONSchemaTarget = 'draft-2020-12' | 'draft-07' | 'openapi-3.0' | 'mongodb';
371
+
372
+ export type JSONSchema = Record<string, unknown>;
373
+
374
+ export interface JSONSchemaOptions {
375
+ // The dialect of the document: JSON Schema draft 2020-12 (the default) or
376
+ // draft-07, an OpenAPI 3.0 schema object, or a MongoDB `$jsonSchema`
377
+ // (`bsonType`, no `$ref`, references inline).
378
+ target?: JSONSchemaTarget;
379
+ // 'strict' renders the dialect of LLM structured outputs (OpenAI, Anthropic):
380
+ // an object at the root, every property listed as required (an optional one
381
+ // accepts null), `additionalProperties: false` on every object, and the
382
+ // structure only (no `length`, `pattern`, `min` or `max`). For the
383
+ // draft-2020-12 and draft-07 targets.
384
+ profile?: 'strict';
385
+ // Which side of the wire the document describes: 'input' (the default) is
386
+ // the JSON a value is parsed from (a `date` is a date-time string), 'output'
387
+ // the value itself (a `date`, `set` or `map` has no JSON form).
388
+ io?: 'input' | 'output';
389
+ // What to do with a type that has no form in the target: throw
390
+ // `ERR_UNREPRESENTABLE` (the default), or render it as `{}`.
391
+ unrepresentable?: 'throw' | 'any';
392
+ // How a reference renders, as in `check`: by the kind of its target ('kind',
393
+ // the default: a stored kind as an id, a memory kind as a `$ref` to its
394
+ // definition), every reference as the record ('embed') or as an id ('id').
395
+ references?: 'kind' | 'embed' | 'id';
396
+ // The pointer the `$ref` of a definition starts with, and where the
397
+ // definitions are placed in the document: '#/$defs/' for draft-2020-12,
398
+ // '#/definitions/' for draft-07, '#/components/schemas/' for openapi-3.0.
399
+ definitions?: string;
400
+ }
401
+
402
+ export interface ModelJSONSchemaOptions extends JSONSchemaOptions {
403
+ // The entity at the root of the document, with the definitions it needs;
404
+ // without it the document holds every entity as a definition, in
405
+ // dependency order (one document per entity for the mongodb target).
406
+ root?: string;
407
+ }
408
+
409
+ // Standard JSON Schema (https://standardschema.dev/json-schema): the converter
410
+ // `schema['~standard'].jsonSchema`, whose `input` and `output` take the
411
+ // target and the other options of `toJSONSchema` as `libraryOptions`. The
412
+ // mongodb target is not a JSON Schema and is refused here. Installed by
413
+ // `register()` of the generators subpath.
414
+ export interface StandardJSONSchemaOptions {
415
+ readonly target: 'draft-2020-12' | 'draft-07' | 'openapi-3.0' | ({} & string);
416
+ readonly libraryOptions?: Omit<JSONSchemaOptions, 'target' | 'io'> | undefined;
417
+ }
418
+
419
+ export interface StandardConverter {
420
+ readonly input: (options: StandardJSONSchemaOptions) => JSONSchema;
421
+ readonly output: (options: StandardJSONSchemaOptions) => JSONSchema;
422
+ }
287
423
 
288
424
  // ---------------------------------------------------------------------------
289
425
  // Static inference: the TypeScript type of a value a definition accepts.
@@ -309,6 +445,11 @@ type IsAny<T> = 0 extends 1 & T ? true : false;
309
445
 
310
446
  type IsUnion<T, U = T> = T extends unknown ? ([U] extends [T] ? false : true) : never;
311
447
 
448
+ // The value a definition describes is read twice: as `check` and `parse`
449
+ // accept it ('input') and as `parse` gives it ('output'), where a decoder
450
+ // replaces the value of its field and a default makes its key present.
451
+ type Mode = 'input' | 'output';
452
+
312
453
  type ScalarName =
313
454
  | 'string'
314
455
  | 'number'
@@ -406,10 +547,10 @@ type Embedded<Name extends string, Embed, E> = Embed extends boolean
406
547
  : true
407
548
  : false;
408
549
 
409
- type Referenced<Name extends string, Embed, E> =
550
+ type Referenced<Name extends string, Embed, E, M extends Mode> =
410
551
  Embedded<Name, Embed, E> extends true
411
552
  ? Name extends keyof E
412
- ? Infer<E[Name], E>
553
+ ? Value<E[Name], E, M>
413
554
  : unknown
414
555
  : string;
415
556
 
@@ -446,9 +587,13 @@ type ArgOf<D, N extends string, Alt extends string> = D extends { [P in N]: infe
446
587
  type ElementsOf<D, N extends string, Alt extends string> =
447
588
  ArgOf<D, N, Alt> extends infer X ? (X extends readonly unknown[] ? X : never) : never;
448
589
 
449
- type TupleOf<T extends readonly unknown[], E> = { -readonly [I in keyof T]: Element<T[I], E> };
590
+ type TupleOf<T extends readonly unknown[], E, M extends Mode> = {
591
+ -readonly [I in keyof T]: Element<T[I], E, M>;
592
+ };
450
593
 
451
- type UnionOf<T extends readonly unknown[], E> = { [I in keyof T]: Infer<T[I], E> }[number];
594
+ type UnionOf<T extends readonly unknown[], E, M extends Mode> = {
595
+ [I in keyof T]: Value<T[I], E, M>;
596
+ }[number];
452
597
 
453
598
  // A one-key object holding a type name names a tuple element (`{ x: 'number'
454
599
  // }`); the key must not itself be `type`, a type name or a kind.
@@ -470,99 +615,107 @@ type NamedKey<T> = keyof T extends infer K
470
615
  : never
471
616
  : never;
472
617
 
473
- type Element<T, E> = T extends string
474
- ? Infer<T, E>
618
+ type Element<T, E, M extends Mode> = T extends string
619
+ ? Value<T, E, M>
475
620
  : T extends readonly unknown[]
476
- ? Infer<T, E>
621
+ ? Value<T, E, M>
477
622
  : T extends object
478
623
  ? NamedKey<T> extends infer K
479
624
  ? [K] extends [never]
480
- ? Infer<T, E>
625
+ ? Value<T, E, M>
481
626
  : K extends keyof T
482
627
  ? T[K] extends string
483
628
  ? K extends `${string}?`
484
- ? Infer<T[K], E> | null | undefined
485
- : Infer<T[K], E>
486
- : Infer<T, E>
487
- : Infer<T, E>
629
+ ? Value<T[K], E, M> | null | undefined
630
+ : Value<T[K], E, M>
631
+ : Value<T, E, M>
632
+ : Value<T, E, M>
488
633
  : never
489
- : Infer<T, E>;
634
+ : Value<T, E, M>;
490
635
 
491
636
  // The value type of a type by name, with the definition it is read from.
492
- type TypeOf<N extends string, D, E> =
637
+ type TypeOf<N extends string, D, E, M extends Mode> =
493
638
  IsCapitalized<N> extends true
494
- ? Referenced<N, EmbedOf<D>, E>
639
+ ? Referenced<N, EmbedOf<D>, E, M>
495
640
  : N extends 'array'
496
- ? Infer<ArgOf<D, 'array', 'value'>, E>[]
641
+ ? Value<ArgOf<D, 'array', 'value'>, E, M>[]
497
642
  : N extends 'set'
498
- ? Set<Infer<ArgOf<D, 'set', 'value'>, E>>
643
+ ? Set<Value<ArgOf<D, 'set', 'value'>, E, M>>
499
644
  : N extends 'object'
500
645
  ? Pair<D, 'object'> extends [infer K, infer V]
501
- ? Record<KeyTypeOf<K> & PropertyKey, Infer<V, E>>
646
+ ? Record<KeyTypeOf<K> & PropertyKey, Value<V, E, M>>
502
647
  : Record<string, unknown>
503
648
  : N extends 'map'
504
649
  ? Pair<D, 'map'> extends [infer K, infer V]
505
- ? Map<KeyTypeOf<K>, Infer<V, E>>
650
+ ? Map<KeyTypeOf<K>, Value<V, E, M>>
506
651
  : Map<unknown, unknown>
507
652
  : N extends 'enum'
508
653
  ? D extends { enum: readonly (infer V)[] }
509
654
  ? V
510
655
  : unknown
511
656
  : N extends 'tuple'
512
- ? TupleOf<ElementsOf<D, 'tuple', 'value'>, E>
657
+ ? TupleOf<ElementsOf<D, 'tuple', 'value'>, E, M>
513
658
  : N extends 'union'
514
- ? UnionOf<ElementsOf<D, 'union', 'union'>, E>
659
+ ? UnionOf<ElementsOf<D, 'union', 'union'>, E, M>
515
660
  : N extends 'schema'
516
661
  ? D extends { schema: infer S }
517
- ? Infer<S, E>
662
+ ? Value<S, E, M>
518
663
  : unknown
519
664
  : N extends 'one'
520
665
  ? D extends { one: infer T extends string }
521
- ? Referenced<T, EmbedOf<D>, E>
666
+ ? Referenced<T, EmbedOf<D>, E, M>
522
667
  : unknown
523
668
  : N extends 'many'
524
669
  ? D extends { many: infer T extends string }
525
- ? Referenced<T, EmbedOf<D>, E>[]
670
+ ? Referenced<T, EmbedOf<D>, E, M>[]
526
671
  : unknown
527
672
  : N extends keyof CustomTypes
528
673
  ? CustomTypes[N]
529
674
  : N extends ScalarName
530
675
  ? ScalarOf<N>
531
676
  : D extends { schema: infer S extends object }
532
- ? Infer<S, E>
677
+ ? Value<S, E, M>
533
678
  : unknown;
534
679
 
680
+ // On the output side a decoder (`parse`) gives the value of its field; a
681
+ // promise of one is awaited.
682
+ type Decoded<T, D, M extends Mode> = M extends 'output'
683
+ ? D extends { parse: (...args: never[]) => infer R }
684
+ ? Awaited<R>
685
+ : T
686
+ : T;
687
+
535
688
  type Nullable<T, D> = D extends { nullable: true } ? T | null : T;
536
689
 
537
690
  type Optional<T, D> = D extends { required: false } ? T | null | undefined : T;
538
691
 
539
692
  // `{ type: 'name', ... }`: the type, `| null` for `nullable: true`, and `|
540
693
  // null | undefined` for `'?name'` or `required: false`.
541
- type LongForm<T extends string, D, E> = T extends `?${infer N}`
542
- ? Nullable<TypeOf<N, D, E>, D> | null | undefined
543
- : Optional<Nullable<TypeOf<T, D, E>, D>, D>;
694
+ type LongForm<T extends string, D, E, M extends Mode> = T extends `?${infer N}`
695
+ ? Nullable<Decoded<TypeOf<N, D, E, M>, D, M>, D> | null | undefined
696
+ : Optional<Nullable<Decoded<TypeOf<T, D, E, M>, D, M>, D>, D>;
544
697
 
545
- type Shorthand<D, E> = D extends { array: unknown }
546
- ? LongForm<'array', D, E>
698
+ type Shorthand<D, E, M extends Mode> = D extends { array: unknown }
699
+ ? LongForm<'array', D, E, M>
547
700
  : D extends { set: unknown }
548
- ? LongForm<'set', D, E>
701
+ ? LongForm<'set', D, E, M>
549
702
  : D extends { object: object }
550
- ? LongForm<'object', D, E>
703
+ ? LongForm<'object', D, E, M>
551
704
  : D extends { map: object }
552
- ? LongForm<'map', D, E>
705
+ ? LongForm<'map', D, E, M>
553
706
  : D extends { enum: readonly unknown[] }
554
- ? LongForm<'enum', D, E>
707
+ ? LongForm<'enum', D, E, M>
555
708
  : D extends { tuple: readonly unknown[] }
556
- ? LongForm<'tuple', D, E>
709
+ ? LongForm<'tuple', D, E, M>
557
710
  : D extends { union: readonly unknown[] }
558
- ? LongForm<'union', D, E>
711
+ ? LongForm<'union', D, E, M>
559
712
  : D extends { schema: object }
560
- ? LongForm<'schema', D, E>
713
+ ? LongForm<'schema', D, E, M>
561
714
  : D extends { one: string }
562
- ? LongForm<'one', D, E>
715
+ ? LongForm<'one', D, E, M>
563
716
  : D extends { many: string }
564
- ? LongForm<'many', D, E>
565
- : Struct<D, E>;
717
+ ? LongForm<'many', D, E, M>
718
+ : Decoded<Struct<D, E, M>, D, M>;
566
719
 
567
720
  // What is not a field of a struct: a function (a calculated field, or the
568
721
  // schema-level validate/parse/serialize/format) and an index definition.
@@ -587,13 +740,44 @@ type IsOptionalDef<X> = X extends `?${string}`
587
740
  ? true
588
741
  : false;
589
742
 
743
+ // Whether a key is optional by its name (`'key?'`) or its definition.
744
+ type IsOptionalKey<K, X> = K extends `${string}?` ? true : IsOptionalDef<X>;
745
+
746
+ // Whether parse fills the key when it is missing.
747
+ type Defaulted<X> = X extends { default: infer V } ? ([V] extends [undefined] ? false : true) : false;
748
+
590
749
  type FieldKeys<D> = { [K in keyof D]: IsField<D[K]> extends true ? K : never }[keyof D];
591
750
 
592
- type OptionalKeys<D> = {
593
- [K in FieldKeys<D>]: K extends `${string}?` ? K : IsOptionalDef<D[K]> extends true ? K : never;
751
+ // The keys that may be left out: the optional ones, and on the input side
752
+ // those with a default, which parse fills; on the output side a defaulted
753
+ // key is always there.
754
+ type OptionalKeys<D, M extends Mode> = {
755
+ [K in FieldKeys<D>]: M extends 'output'
756
+ ? Defaulted<D[K]> extends true
757
+ ? never
758
+ : IsOptionalKey<K, D[K]> extends true
759
+ ? K
760
+ : never
761
+ : IsOptionalKey<K, D[K]> extends true
762
+ ? K
763
+ : Defaulted<D[K]> extends true
764
+ ? K
765
+ : never;
594
766
  }[FieldKeys<D>];
595
767
 
596
- type RequiredKeys<D> = Exclude<FieldKeys<D>, OptionalKeys<D>>;
768
+ type RequiredKeys<D, M extends Mode> = Exclude<FieldKeys<D>, OptionalKeys<D, M>>;
769
+
770
+ // An optional property accepts null and undefined, as check does; a key that
771
+ // is optional only through its default accepts a missing value.
772
+ type OptionalProperty<K, X, E, M extends Mode> =
773
+ IsOptionalKey<K, X> extends true ? Value<X, E, M> | null | undefined : Value<X, E, M>;
774
+
775
+ // On the output side a defaulted key is present: null stays where the key
776
+ // was optional, undefined is gone.
777
+ type RequiredProperty<K, X, E, M extends Mode> =
778
+ Defaulted<X> extends true
779
+ ? Exclude<Value<X, E, M>, undefined> | (IsOptionalKey<K, X> extends true ? null : never)
780
+ : Value<X, E, M>;
597
781
 
598
782
  type FieldName<K> = K extends `${infer F}?` ? F : K;
599
783
 
@@ -602,33 +786,35 @@ type Simplify<T> = { [K in keyof T]: T[K] };
602
786
  // The fields of a struct: optional ones (`'key?'`, `'?type'`, `required:
603
787
  // false`) are optional properties that accept null and undefined, as `check`
604
788
  // does.
605
- type Struct<D, E> = Simplify<
606
- { -readonly [K in RequiredKeys<D>]-?: Infer<D[K], E> } & {
607
- -readonly [K in OptionalKeys<D> as FieldName<K>]?: Infer<D[K], E> | null | undefined;
789
+ type Struct<D, E, M extends Mode> = Simplify<
790
+ {
791
+ -readonly [K in RequiredKeys<D, M> as FieldName<K>]-?: RequiredProperty<K, D[K], E, M>;
792
+ } & {
793
+ -readonly [K in OptionalKeys<D, M> as FieldName<K>]?: OptionalProperty<K, D[K], E, M>;
608
794
  }
609
795
  >;
610
796
 
611
797
  // A projection copies fields from its parent, known only through `E`.
612
- type Projection<D, E> = D extends {
798
+ type Projection<D, E, M extends Mode> = D extends {
613
799
  Projection: { schema: infer S extends string; fields: readonly (infer F)[] };
614
800
  }
615
801
  ? S extends keyof E
616
- ? Pick<Infer<E[S], E>, Extract<F, keyof Infer<E[S], E>>>
802
+ ? Pick<Value<E[S], E, M>, Extract<F, keyof Value<E[S], E, M>>>
617
803
  : unknown
618
804
  : unknown;
619
805
 
620
- type WithKind<D, K extends keyof D, E> = K extends 'Projection'
621
- ? Projection<D, E>
622
- : Struct<Omit<D, K>, E>;
806
+ type WithKind<D, K extends keyof D, E, M extends Mode> = K extends 'Projection'
807
+ ? Projection<D, E, M>
808
+ : Struct<Omit<D, K>, E, M>;
623
809
 
624
- type ObjectDef<D, E> =
810
+ type ObjectDef<D, E, M extends Mode> =
625
811
  KindKey<D> extends infer K
626
812
  ? [K] extends [never]
627
813
  ? D extends { type: infer T extends string }
628
- ? LongForm<T, D, E>
629
- : Shorthand<D, E>
814
+ ? LongForm<T, D, E, M>
815
+ : Shorthand<D, E, M>
630
816
  : K extends keyof D
631
- ? WithKind<D, K, E>
817
+ ? Decoded<WithKind<D, K, E, M>, D, M>
632
818
  : never
633
819
  : never;
634
820
 
@@ -636,30 +822,39 @@ type ObjectDef<D, E> =
636
822
  type IdOf<Name extends string, Def> =
637
823
  StoreOf<Def> extends 'persistent' ? { [K in `${Uncapitalize<Name>}Id`]?: string } : {};
638
824
 
639
- // The type of a value `check` accepts for the definition `D`. `E` is an
640
- // optional map of entity definitions by name (the second argument of `Model`
641
- // as an object): with it a reference to a memory kind is the record and a
642
- // projection has its parent's fields; without it a memory reference is
643
- // `unknown` and a stored one is its id. A stored kind's own id field depends
644
- // on the entity's name, which a definition does not carry: `InferEntity`
645
- // adds it.
646
- export type Infer<D, E = {}> =
825
+ type Value<D, E, M extends Mode> =
647
826
  IsAny<D> extends true
648
827
  ? any
649
828
  : D extends string
650
829
  ? D extends `?${infer N}`
651
- ? Infer<N, E> | null | undefined
830
+ ? Value<N, E, M> | null | undefined
652
831
  : IsCapitalized<D> extends true
653
- ? Referenced<D, undefined, E>
832
+ ? Referenced<D, undefined, E, M>
654
833
  : ScalarOf<D>
655
834
  : D extends Schema<infer X>
656
- ? Infer<X, E>
835
+ ? Value<X, E, M>
657
836
  : D extends readonly unknown[]
658
- ? TupleOf<D, E>
837
+ ? TupleOf<D, E, M>
659
838
  : D extends object
660
- ? ObjectDef<D, E>
839
+ ? ObjectDef<D, E, M>
661
840
  : unknown;
662
841
 
842
+ // The type of a value `check` and `parse` accept for the definition `D` (a
843
+ // key with a `default` may be left out, parse fills it). `E` is an optional
844
+ // map of entity definitions by name (the second argument of `Model` as an
845
+ // object): with it a reference to a memory kind is the record and a
846
+ // projection has its parent's fields; without it a memory reference is
847
+ // `unknown` and a stored one is its id. A stored kind's own id field depends
848
+ // on the entity's name, which a definition does not carry: `InferEntity`
849
+ // adds it.
850
+ export type Infer<D, E = {}> = Value<D, E, 'input'>;
851
+
852
+ // The type of the value `parse` gives for the definition `D`: `Infer<D, E>`
853
+ // with the result of every `parse` function (a decoder of a field, the
854
+ // schema's own) in place of the value it decodes, and every defaulted key
855
+ // present.
856
+ export type InferOutput<D, E = {}> = Value<D, E, 'output'>;
857
+
663
858
  // The value type of a `Schema<D>` instance: `InferSchema<typeof schema>`.
664
859
  export type InferSchema<S> = S extends Schema<infer D> ? Infer<D> : never;
665
860
 
@@ -676,14 +871,15 @@ export type InferEntity<E, Name extends keyof E & string> = Simplify<
676
871
  // devDependency); tests/types/standard.test-d.ts pins that a `Schema<D>` is a
677
872
  // `StandardSchemaV1<Infer<D>, Infer<D>>` of that package.
678
873
 
679
- // The vendor-specific options of a `validate` call are the options of `check`.
874
+ // The vendor-specific options of a `validate` call are the options of `parse`.
680
875
  export interface StandardOptions {
681
- readonly libraryOptions?: CheckOptions | undefined;
876
+ readonly libraryOptions?: ParseOptions | undefined;
682
877
  }
683
878
 
684
- // A verdict, not a transformation: a valid value comes back as it was given,
685
- // and the issues of an invalid one are the result's own (`message` and
686
- // `path`, as the specification reads them, plus `code` and `params`).
879
+ // The result of parse as the specification reads it: the value parse gives
880
+ // (the value given, when there was nothing to apply), or the issues of an
881
+ // invalid one, the result's own (`message` and `path`, as the specification
882
+ // reads them, plus `code` and `params`).
687
883
  export type StandardResult<T> =
688
884
  | { readonly value: T; readonly issues?: undefined }
689
885
  | { readonly issues: ReadonlyArray<ValidationIssue> };
@@ -691,10 +887,18 @@ export type StandardResult<T> =
691
887
  export interface StandardProps<D = string | object> {
692
888
  readonly version: 1;
693
889
  readonly vendor: 'alexify.metaschema';
694
- readonly validate: (value: unknown, options?: StandardOptions) => StandardResult<Infer<D>>;
695
- // Nothing is transformed, so the input type is the output type. Type-level
696
- // only: no property of the object holds it.
697
- readonly types?: { readonly input: Infer<D>; readonly output: Infer<D> } | undefined;
890
+ // `parse` with the policies of the schema; a promise of the result for a
891
+ // schema with an async validator, decoder or custom type.
892
+ readonly validate: (
893
+ value: unknown,
894
+ options?: StandardOptions,
895
+ ) => StandardResult<InferOutput<D>> | Promise<StandardResult<InferOutput<D>>>;
896
+ // Standard JSON Schema: `input(options)` and `output(options)` by target.
897
+ // Present once `register()` of the generators subpath has run.
898
+ readonly jsonSchema: StandardConverter;
899
+ // What parse accepts and what it gives. Type-level only: no property of
900
+ // the object holds it.
901
+ readonly types?: { readonly input: Infer<D>; readonly output: InferOutput<D> } | undefined;
698
902
  }
699
903
 
700
904
  // `D` is the definition the schema was built from, kept as a type only (no
@@ -737,7 +941,30 @@ export class Schema<const D extends string | object = string | object> {
737
941
  checkConsistency(): Array<string>;
738
942
  findReference(name: string): Schema | null;
739
943
  check(value: unknown, options?: CheckOptions): ValidationResult;
740
- toInterface(): string;
944
+ // The same check, with the validators that return a promise settled after
945
+ // the walk, in field order.
946
+ checkAsync(value: unknown, options?: CheckOptions): Promise<ValidationResult>;
947
+ // Validates a value and builds the value of the program from it: defaults,
948
+ // the check, `unknown: 'strip'`, the decoders of the fields (parts before
949
+ // the whole) and the schema's own `parse`. The value given is never
950
+ // written to; it is the output itself when there was nothing to apply.
951
+ parse(value: unknown, options?: ParseOptions): ParseResult<InferOutput<D>>;
952
+ parseAsync(value: unknown, options?: ParseOptions): Promise<ParseResult<InferOutput<D>>>;
953
+ // The other direction: the schema's own `serialize`, then the serializers
954
+ // of the fields, from the value down to its parts; with `check` the
955
+ // verdict of check over the result as well.
956
+ serialize(
957
+ value: InferOutput<D>,
958
+ options: SerializeOptions & { check: true },
959
+ ): SerializeChecked<Infer<D>>;
960
+ serialize(value: InferOutput<D>, options?: SerializeOptions): Serialized<Infer<D>>;
961
+ // The two methods below exist once `register()` of the generators subpath
962
+ // has run; the subpath's `toJSONSchema(schema)` and `toTypeScript(schema)`
963
+ // are the same without it.
964
+ // The schema as a JSON Schema document of the target dialect.
965
+ toJSONSchema(options?: JSONSchemaOptions): JSONSchema;
966
+ // The schema as a TypeScript interface, the description of a field as JSDoc.
967
+ toInterface(options?: InterfaceOptions): string;
741
968
  attach(...namespaces: Array<Model>): void;
742
969
  detach(...namespaces: Array<Model>): void;
743
970
  toString(): string;
@@ -761,5 +988,14 @@ export class Model {
761
988
  database?: Record<string, unknown> | null,
762
989
  options?: ModelOptions,
763
990
  );
991
+ // The members below exist once `register()` of the generators subpath has
992
+ // run; the subpath's `toJSONSchema(model)` and `toTypeScript(model)` are the
993
+ // same without it.
994
+ // Every entity as a JSON Schema definition (`$defs`, `definitions` or
995
+ // `components.schemas` by target), or the document of `options.root`.
996
+ toJSONSchema(options?: ModelJSONSchemaOptions): JSONSchema;
997
+ // The interfaces of every entity in dependency order; `dts` is the same
998
+ // without options.
999
+ toTypeScript(options?: InterfaceOptions): string;
764
1000
  get dts(): string;
765
1001
  }