@alexify/metaschema 3.2.0 → 3.4.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 (62) hide show
  1. package/CHANGELOG.md +307 -1
  2. package/README.md +173 -89
  3. package/SECURITY.md +24 -1
  4. package/index.d.ts +601 -29
  5. package/package.json +28 -3
  6. package/src/checks.js +789 -0
  7. package/src/codec.js +201 -46
  8. package/src/coerce/index.d.ts +34 -0
  9. package/src/coerce/index.js +385 -0
  10. package/src/compile/emit.js +87 -28
  11. package/src/compile/index.js +9 -4
  12. package/src/context.js +6 -1
  13. package/src/definition/index.d.ts +19 -0
  14. package/src/definition/index.js +27 -0
  15. package/src/derive/index.d.ts +86 -0
  16. package/src/derive/index.js +273 -0
  17. package/src/errors.js +46 -4
  18. package/src/formats/index.d.ts +20 -8
  19. package/src/formats/index.js +450 -39
  20. package/src/generators/fromjsonschema.js +21 -2
  21. package/src/generators/index.js +1 -1
  22. package/src/generators/jsonschema.js +90 -21
  23. package/src/generators/typescript.js +11 -0
  24. package/src/index.js +3 -2
  25. package/src/issues.js +9 -7
  26. package/src/kinds.js +15 -3
  27. package/src/lint.js +38 -0
  28. package/src/locales/en.js +6 -0
  29. package/src/locales/uk.js +6 -0
  30. package/src/metadata.js +6 -24
  31. package/src/model/data.js +67 -10
  32. package/src/model/diff.js +7 -4
  33. package/src/model/index.js +1 -1
  34. package/src/model/infer.js +10 -3
  35. package/src/model/merge.js +16 -9
  36. package/src/model/restore.js +52 -7
  37. package/src/model/sample.js +28 -4
  38. package/src/model.js +54 -56
  39. package/src/mongodb/bson.js +130 -0
  40. package/src/mongodb/document.js +217 -0
  41. package/src/mongodb/index.d.ts +133 -0
  42. package/src/mongodb/index.js +24 -0
  43. package/src/mongodb/indexes.js +79 -0
  44. package/src/mongodb/update.js +258 -0
  45. package/src/preprocessor.js +1 -2
  46. package/src/prototypes/abstract.js +41 -67
  47. package/src/prototypes/collections.js +3 -90
  48. package/src/prototypes/flags.js +34 -0
  49. package/src/prototypes/json.js +0 -11
  50. package/src/prototypes/reference.js +0 -76
  51. package/src/prototypes/scalars.js +17 -96
  52. package/src/prototypes/schema.js +1 -10
  53. package/src/prototypes/tuple.js +0 -26
  54. package/src/prototypes/union.js +12 -82
  55. package/src/rules.js +33 -157
  56. package/src/schema.js +105 -220
  57. package/src/snapshot.js +216 -41
  58. package/src/stream/index.js +1 -1
  59. package/src/struct.js +6 -91
  60. package/src/types.js +43 -6
  61. package/src/util.js +43 -0
  62. package/src/validation.js +313 -0
package/index.d.ts CHANGED
@@ -38,6 +38,7 @@ export type IssueCode =
38
38
  | 'range'
39
39
  | 'pattern'
40
40
  | 'format'
41
+ | 'decimals'
41
42
  | 'union'
42
43
  | 'reference'
43
44
  | 'circular'
@@ -59,6 +60,9 @@ export interface IssueParams {
59
60
  pattern: { pattern: string };
60
61
  // The name of the format the string is not of.
61
62
  format: { format: string };
63
+ // The decimals the number may have: it has more, or it is not finite
64
+ // (`received` names NaN or the infinity then).
65
+ decimals: { decimals: number; received?: string };
62
66
  // No branch of a union matched: the branch names, or the discriminator
63
67
  // values when the union has a discriminator (the path then ends with it).
64
68
  union: { expected: unknown[]; discriminator: string | undefined };
@@ -142,8 +146,31 @@ export interface CheckOptions {
142
146
  // does not have, which the output then leaves out.
143
147
  export interface ParseOptions extends Omit<CheckOptions, 'unknown'> {
144
148
  unknown?: 'reject' | 'ignore' | 'strip';
149
+ // Whether parse converts the input to the types of the fields before the
150
+ // check (`'42'` to a number, an ISO string to a Date): the schema's
151
+ // `coerce` metadata unless the call says otherwise, a field's own
152
+ // `coerce` key for its subtree. The converters are those `register()` of
153
+ // the `@alexify/metaschema/coerce` subpath installed; `check` never
154
+ // converts.
155
+ coerce?: boolean;
145
156
  }
146
157
 
158
+ // The options of `coerce(schema, value)` of the `@alexify/metaschema/coerce`
159
+ // subpath: how references are followed and how deep, and an array given the
160
+ // path of every key the pass changed (a value converted, a default filled).
161
+ export interface CoerceOptions {
162
+ references?: CheckOptions['references'];
163
+ maxDepth?: number;
164
+ report?: PropertyKey[][];
165
+ }
166
+
167
+ // A converter of coercion: the value of a field of its type read from what
168
+ // the input gave, or the value itself when it cannot be read (the check then
169
+ // reports it as given). Registered process-wide by `register()` of the
170
+ // `@alexify/metaschema/coerce` subpath, or given to a model for its own type
171
+ // names (`ModelOptions.coercions`).
172
+ export type Coercion = (value: unknown, field: FieldType) => unknown;
173
+
147
174
  // What parse returns: the output only for a valid value, the issues always.
148
175
  export type ParseResult<T> =
149
176
  | { valid: true; value: T; issues: [] }
@@ -243,6 +270,9 @@ export interface FieldType {
243
270
  required: boolean;
244
271
  // The value may be null; the key is still required unless `required` is false.
245
272
  nullable?: boolean;
273
+ // Whether parse converts the input of this field and what is under it,
274
+ // whatever the policy of the call or the schema.
275
+ coerce?: boolean;
246
276
  // On a reference: check and render it as the record (true) or its id
247
277
  // (false) whatever the kind of its target.
248
278
  embed?: boolean;
@@ -288,7 +318,12 @@ export interface TypeMetadata {
288
318
  }
289
319
 
290
320
  // An entry of the table passed to Model: metadata for a built-in, an alias
291
- // (`js`), or a prototype with its own `construct` and `checkType`.
321
+ // (`js`), or a prototype with its own `construct` and `checkType`. A
322
+ // prototype may bring a `compile` in place of `checkType` (it returns the
323
+ // check, `(value, context, key) => void`): it runs on the first check of a
324
+ // field, not when the schema is built, so it must not be where the
325
+ // definition is checked (`construct` is); what it throws is
326
+ // ERR_INVALID_CUSTOM_TYPE with the error as the cause.
292
327
  export interface TypeEntry {
293
328
  js?: string;
294
329
  metadata?: TypeMetadata;
@@ -304,6 +339,10 @@ export interface ModelOptions {
304
339
  // 'shared' (the default) registers the types into the process-wide registry;
305
340
  // 'isolated' gives the model its own copy of the built-in types to register into.
306
341
  registry?: 'shared' | 'isolated';
342
+ // The converters of coercion for the model's own type names, read before
343
+ // the process-wide table for the fields of its entities: what an isolated
344
+ // registry is to the types.
345
+ coercions?: Record<string, Coercion>;
307
346
  }
308
347
 
309
348
  export interface KindMetadata {
@@ -314,6 +353,8 @@ export interface KindMetadata {
314
353
  parent?: string;
315
354
  // The default of `check` for keys the schema does not have.
316
355
  unknown?: 'reject' | 'ignore';
356
+ // The default of `parse` (and so of `~standard.validate`) for coercion.
357
+ coerce?: boolean;
317
358
  [key: string]: unknown;
318
359
  }
319
360
 
@@ -364,6 +405,14 @@ export type DefinitionErrorCode =
364
405
  // test.
365
406
  | 'ERR_INVALID_FORMAT'
366
407
  | 'ERR_FORMAT_REGISTERED'
408
+ // Thrown by the functions of the `@alexify/metaschema/derive` subpath for
409
+ // a key the schema has no field of, located in the schema.
410
+ | 'ERR_UNKNOWN_FIELD'
411
+ // Thrown by `register` of the `@alexify/metaschema/coerce` subpath: an
412
+ // entry that is not a converter of a type, and a name registered again
413
+ // with another function.
414
+ | 'ERR_INVALID_COERCION'
415
+ | 'ERR_COERCION_REGISTERED'
367
416
  // Thrown by `compile` and `register` of the `@alexify/metaschema/compile`
368
417
  // subpath with `jit: true` where code generation from strings is not allowed.
369
418
  | 'ERR_NO_EVAL'
@@ -386,15 +435,34 @@ export class SchemaDefinitionError extends TypeError {
386
435
  // `ERR_INVALID_TARGET` is the same kind of error from a function of a subpath
387
436
  // given something other than what it takes (a Schema, a Model, a snapshot, a
388
437
  // list of changes).
389
- export type RuntimeErrorCode = 'ERR_ASYNC_VALIDATOR' | 'ERR_INVALID_TARGET' | 'ERR_INVALID_RECORD';
438
+ export type RuntimeErrorCode =
439
+ | 'ERR_ASYNC_VALIDATOR'
440
+ | 'ERR_INVALID_TARGET'
441
+ // An option of a call that is not what it must be (`maxErrors`, the
442
+ // `coerce` of a parse, the options of the stream, derive and mongodb
443
+ // subpaths): the call is wrong, not the definition.
444
+ | 'ERR_INVALID_OPTION'
445
+ | 'ERR_INVALID_RECORD'
446
+ // A parse that coerces before `register()` of the `@alexify/metaschema/coerce`
447
+ // subpath ran (there is no converter to run), and a document written with
448
+ // ObjectIds before `register({ bson })` of `@alexify/metaschema/mongodb`.
449
+ | 'ERR_NOT_REGISTERED';
390
450
 
391
451
  // ---------------------------------------------------------------------------
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.
452
+ // The snapshot: `model.toJSON()`, what JSON.stringify(model) writes, and
453
+ // `schema.toSnapshot()`, the same for one schema and the entities it
454
+ // reaches. The entities in dependency order with a fixed key order, the
455
+ // types the entities use, and a copy of the `database` metadata. A function
456
+ // is `{ $function: true }` wherever it stands, a bigint `{ $bigint }`, a
457
+ // Date `{ $date }`, bytes `{ $bytes }` (base64), a Map `{ $map }` (its
458
+ // entries), a Set `{ $set }` (its values), a RegExp its source (or
459
+ // `{ source, flags }` with flags beyond `u`). `fromJSON` of the `@alexify/metaschema/model` subpath reads
460
+ // it back. Format 1 is a contract: the fields of a struct come in the order
461
+ // of the definition (the id field a stored kind adds after them, unless the
462
+ // definition has a field of that name), the entities each after the ones
463
+ // they reference (`model.order` for a model, the order a walk from the
464
+ // schema meets them for one schema), and a key is only ever added to it;
465
+ // anything else is a major release.
398
466
  // ---------------------------------------------------------------------------
399
467
 
400
468
  export interface FunctionSnapshot {
@@ -402,14 +470,170 @@ export interface FunctionSnapshot {
402
470
  }
403
471
 
404
472
  // 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;
473
+ // the other keys of its definition, sorted. The type decides what else it
474
+ // holds (narrow on `type`): the rules of its type, the element of a
475
+ // collection, the elements of a tuple, the nested struct, the branches of a
476
+ // union, the entity of a reference (its name is the type, capitalized), or
477
+ // the options of a custom type, whose names are those `CustomTypes` declares
478
+ // (as `Infer` reads them). Any field may carry the keys of
479
+ // `FieldSnapshotBase`; a key the definition gave beyond them is kept too.
480
+ export interface FieldSnapshotBase {
409
481
  required: boolean;
482
+ nullable?: boolean;
483
+ coerce?: boolean;
484
+ // A value, `{ $function: true }` for a factory, `{ $bigint }`, `{ $date }`,
485
+ // `{ $bytes }`, `{ $map }`, `{ $set }` for the values that have no JSON form.
486
+ default?: unknown;
487
+ aliases?: string[];
488
+ deprecated?: boolean | string;
489
+ description?: string;
490
+ examples?: unknown[];
491
+ title?: string;
492
+ validate?: FunctionSnapshot;
493
+ parse?: FunctionSnapshot;
494
+ serialize?: FunctionSnapshot;
410
495
  [key: string]: unknown;
411
496
  }
412
497
 
498
+ export interface BigintSnapshot {
499
+ $bigint: string;
500
+ }
501
+
502
+ export interface DateSnapshot {
503
+ $date: string;
504
+ }
505
+
506
+ // Bytes as base64 text, a Map as its entries and a Set as its values, each
507
+ // value of them written as any value of a snapshot is.
508
+ export interface BytesSnapshot {
509
+ $bytes: string;
510
+ }
511
+
512
+ export interface MapSnapshot {
513
+ $map: [unknown, unknown][];
514
+ }
515
+
516
+ export interface SetSnapshot {
517
+ $set: unknown[];
518
+ }
519
+
520
+ // A `length` rule: the bounds it has.
521
+ export interface LengthSnapshot {
522
+ min?: number;
523
+ max?: number;
524
+ }
525
+
526
+ export interface StringFieldSnapshot extends FieldSnapshotBase {
527
+ type: 'string';
528
+ length?: LengthSnapshot;
529
+ unicode?: boolean;
530
+ // The source of a pattern of the `u` flag alone, else its source and flags.
531
+ pattern?: string | { source: string; flags: string };
532
+ format?: string;
533
+ }
534
+
535
+ export interface NumberFieldSnapshot extends FieldSnapshotBase {
536
+ type: 'number';
537
+ min?: number | BigintSnapshot;
538
+ max?: number | BigintSnapshot;
539
+ decimals?: number;
540
+ }
541
+
542
+ export interface IntegerFieldSnapshot extends FieldSnapshotBase {
543
+ type: 'integer' | 'bigint';
544
+ min?: number | BigintSnapshot;
545
+ max?: number | BigintSnapshot;
546
+ }
547
+
548
+ export interface ScalarFieldSnapshot extends FieldSnapshotBase {
549
+ type: 'boolean' | 'date' | 'null' | 'any' | 'unknown' | 'json';
550
+ }
551
+
552
+ // Binary data, its `length` the number of bytes.
553
+ export interface BytesFieldSnapshot extends FieldSnapshotBase {
554
+ type: 'bytes';
555
+ length?: LengthSnapshot;
556
+ }
557
+
558
+ export interface EnumFieldSnapshot extends FieldSnapshotBase {
559
+ type: 'enum';
560
+ enum: unknown[];
561
+ }
562
+
563
+ export interface FlagsFieldSnapshot extends FieldSnapshotBase {
564
+ type: 'flags';
565
+ flags: string[];
566
+ }
567
+
568
+ export interface ListFieldSnapshot extends FieldSnapshotBase {
569
+ type: 'array' | 'set';
570
+ value: FieldSnapshot;
571
+ length?: LengthSnapshot;
572
+ }
573
+
574
+ export interface KeyedFieldSnapshot extends FieldSnapshotBase {
575
+ type: 'object' | 'map';
576
+ key: 'string' | 'number';
577
+ value: FieldSnapshot;
578
+ length?: LengthSnapshot;
579
+ }
580
+
581
+ // An element of a tuple, `name` the one a named element was given.
582
+ export type TupleElementSnapshot = FieldSnapshot & { name?: string };
583
+
584
+ export interface TupleFieldSnapshot extends FieldSnapshotBase {
585
+ type: 'tuple';
586
+ value: TupleElementSnapshot[];
587
+ }
588
+
589
+ // A nested struct, or a Schema of one type held as a field.
590
+ export interface StructFieldSnapshot extends FieldSnapshotBase {
591
+ type: 'schema';
592
+ schema: FieldsSnapshot | FieldSnapshot;
593
+ }
594
+
595
+ export interface UnionFieldSnapshot extends FieldSnapshotBase {
596
+ type: 'union';
597
+ union: FieldSnapshot[];
598
+ discriminator?: string;
599
+ }
600
+
601
+ type UpperLetter =
602
+ | 'A' | 'B' | 'C' | 'D' | 'E' | 'F' | 'G' | 'H' | 'I' | 'J' | 'K' | 'L' | 'M'
603
+ | 'N' | 'O' | 'P' | 'Q' | 'R' | 'S' | 'T' | 'U' | 'V' | 'W' | 'X' | 'Y' | 'Z';
604
+
605
+ // A reference: the type is the name of the entity, under `one` or `many`.
606
+ export interface ReferenceFieldSnapshot extends FieldSnapshotBase {
607
+ type: `${UpperLetter}${string}`;
608
+ one?: string;
609
+ many?: string;
610
+ embed?: boolean;
611
+ }
612
+
613
+ // A field of a custom type, by the names `CustomTypes` declares: a snapshot
614
+ // of a model whose custom types are not declared there holds fields of type
615
+ // names no member of `FieldSnapshot` has, which an exhaustive `switch` over
616
+ // `type` does not see; give it a `default`.
617
+ export interface CustomFieldSnapshot extends FieldSnapshotBase {
618
+ type: keyof CustomTypes & string;
619
+ }
620
+
621
+ export type FieldSnapshot =
622
+ | StringFieldSnapshot
623
+ | NumberFieldSnapshot
624
+ | IntegerFieldSnapshot
625
+ | ScalarFieldSnapshot
626
+ | BytesFieldSnapshot
627
+ | EnumFieldSnapshot
628
+ | FlagsFieldSnapshot
629
+ | ListFieldSnapshot
630
+ | KeyedFieldSnapshot
631
+ | TupleFieldSnapshot
632
+ | StructFieldSnapshot
633
+ | UnionFieldSnapshot
634
+ | ReferenceFieldSnapshot
635
+ | CustomFieldSnapshot;
636
+
413
637
  // The fields of a struct in their order: a calculated field, the validate,
414
638
  // parse or serialize of the struct are `{ $function: true }`.
415
639
  export type FieldsSnapshot = Record<string, FieldSnapshot | FunctionSnapshot>;
@@ -444,11 +668,21 @@ export interface TypeSnapshot {
444
668
 
445
669
  export interface ModelSnapshot {
446
670
  format: 1;
671
+ // The entity a snapshot of one schema is about (`schema.toSnapshot()`);
672
+ // a model's snapshot has none.
673
+ root?: string;
447
674
  database: Record<string, unknown> | null;
448
675
  types: Record<string, TypeSnapshot>;
449
676
  entities: Record<string, EntitySnapshot>;
450
677
  }
451
678
 
679
+ // `schema.toSnapshot()`: the schema (under its name, '' when anonymous)
680
+ // and every entity it reaches through its references, in dependency order.
681
+ export interface SchemaSnapshot extends ModelSnapshot {
682
+ root: string;
683
+ database: null;
684
+ }
685
+
452
686
  // The options of `fromJSON` of the `@alexify/metaschema/model` subpath.
453
687
  export interface RestoreOptions {
454
688
  // Entries of the table Model takes, over the types of the snapshot: the
@@ -510,6 +744,31 @@ export interface MergeOptions {
510
744
  metadata?: Partial<KindMetadata>;
511
745
  }
512
746
 
747
+ // The options of every function of the `@alexify/metaschema/derive` subpath.
748
+ export interface DeriveOptions {
749
+ // The name of the derived schema: the source's by default.
750
+ name?: string;
751
+ // The kind metadata of the derived schema, over the source's (a stored
752
+ // kind or a projection is a struct, keeping its `unknown`).
753
+ metadata?: Partial<KindMetadata>;
754
+ }
755
+
756
+ // The options of `partial`: the fields to make optional (every one by
757
+ // default), `deep` into nested structs, and `defaults` to keep the defaults
758
+ // a patch would otherwise fill.
759
+ export interface PartialOptions<K extends string = string> extends DeriveOptions {
760
+ keys?: readonly K[];
761
+ deep?: boolean;
762
+ defaults?: boolean;
763
+ }
764
+
765
+ // The options of `required`: the fields to make required (every one by
766
+ // default) and `deep` into nested structs.
767
+ export interface RequiredOptions<K extends string = string> extends DeriveOptions {
768
+ keys?: readonly K[];
769
+ deep?: boolean;
770
+ }
771
+
513
772
  // The options of `infer` of the `@alexify/metaschema/model` subpath (the
514
773
  // name sits beside the type `Infer<D>`: the function reads samples, the type
515
774
  // reads a definition).
@@ -655,6 +914,11 @@ export interface JSONSchemaOptions {
655
914
  // the default: a stored kind as an id, a memory kind as a `$ref` to its
656
915
  // definition), every reference as the record ('embed') or as an id ('id').
657
916
  references?: 'kind' | 'embed' | 'id';
917
+ // The mongodb target only: the ids of stored records as the database holds
918
+ // them ('objectId': `_id` an ObjectId, required at the root, and every
919
+ // reference an ObjectId, as `toDocument` of `@alexify/metaschema/mongodb`
920
+ // writes them), or as the program does ('string', the default).
921
+ ids?: 'string' | 'objectId';
658
922
  // The pointer the `$ref` of a definition starts with, and where the
659
923
  // definitions are placed in the document: '#/$defs/' for draft-2020-12,
660
924
  // '#/definitions/' for draft-07, '#/components/schemas/' for openapi-3.0.
@@ -740,6 +1004,7 @@ type ScalarName =
740
1004
  | 'bigint'
741
1005
  | 'boolean'
742
1006
  | 'date'
1007
+ | 'bytes'
743
1008
  | 'null'
744
1009
  | 'any'
745
1010
  | 'unknown'
@@ -755,6 +1020,7 @@ type CompoundName =
755
1020
  | 'tuple'
756
1021
  | 'union'
757
1022
  | 'schema'
1023
+ | 'flags'
758
1024
  | 'one'
759
1025
  | 'many';
760
1026
 
@@ -770,15 +1036,17 @@ type ScalarOf<N extends string> = N extends 'string'
770
1036
  ? boolean
771
1037
  : N extends 'date'
772
1038
  ? Date
773
- : N extends 'null'
774
- ? null
775
- : N extends 'any'
776
- ? any
777
- : N extends 'unknown' | 'json'
778
- ? unknown
779
- : N extends keyof CustomTypes
780
- ? CustomTypes[N]
781
- : unknown;
1039
+ : N extends 'bytes'
1040
+ ? Uint8Array
1041
+ : N extends 'null'
1042
+ ? null
1043
+ : N extends 'any'
1044
+ ? any
1045
+ : N extends 'unknown' | 'json'
1046
+ ? unknown
1047
+ : N extends keyof CustomTypes
1048
+ ? CustomTypes[N]
1049
+ : unknown;
782
1050
 
783
1051
  // Whether the first character is an uppercase letter: a reference when it is
784
1052
  // the first character of a type name, a kind when it is the first of a key.
@@ -952,13 +1220,17 @@ type TypeOf<N extends string, D, E, M extends Mode> =
952
1220
  ? D extends { many: infer T extends string }
953
1221
  ? Referenced<T, EmbedOf<D>, E, M>[]
954
1222
  : unknown
955
- : N extends keyof CustomTypes
956
- ? CustomTypes[N]
957
- : N extends ScalarName
958
- ? ScalarOf<N>
959
- : D extends { schema: infer S extends object }
960
- ? Value<S, E, M>
961
- : unknown;
1223
+ : N extends 'flags'
1224
+ ? D extends { flags: readonly (infer F extends string)[] }
1225
+ ? { [K in F]?: boolean }
1226
+ : Record<string, boolean>
1227
+ : N extends keyof CustomTypes
1228
+ ? CustomTypes[N]
1229
+ : N extends ScalarName
1230
+ ? ScalarOf<N>
1231
+ : D extends { schema: infer S extends object }
1232
+ ? Value<S, E, M>
1233
+ : unknown;
962
1234
 
963
1235
  // On the output side a decoder (`parse`) gives the value of its field; a
964
1236
  // promise of one is awaited.
@@ -998,7 +1270,9 @@ type Shorthand<D, E, M extends Mode> = D extends { array: unknown }
998
1270
  ? LongForm<'one', D, E, M>
999
1271
  : D extends { many: string }
1000
1272
  ? LongForm<'many', D, E, M>
1001
- : Decoded<Struct<D, E, M>, D, M>;
1273
+ : D extends { flags: readonly string[] }
1274
+ ? LongForm<'flags', D, E, M>
1275
+ : Decoded<Struct<D, E, M>, D, M>;
1002
1276
 
1003
1277
  // What is not a field of a struct: a function (a calculated field, or the
1004
1278
  // schema-level validate/parse/serialize/format) and an index definition.
@@ -1147,6 +1421,254 @@ export type InferEntity<E, Name extends keyof E & string> = Simplify<
1147
1421
  Infer<E[Name], E> & IdOf<Name, E[Name]>
1148
1422
  >;
1149
1423
 
1424
+ // The definitions of derived schemas (the `@alexify/metaschema/derive`
1425
+ // subpath): what `pick`, `omit`, `partial`, `required` and `extend` build,
1426
+ // as a definition `Infer` reads. A derived definition always has a kind as
1427
+ // its first key, so its fields read as a struct whatever their names.
1428
+
1429
+ // The definition a schema type was built from.
1430
+ export type DefinitionOf<S> = S extends Schema<infer D> ? D : never;
1431
+
1432
+ // A schema whose definition is not known (`Schema`, an entity of a model):
1433
+ // what is derived from it is not known either.
1434
+ type IsWide<D> = string extends D ? true : object extends D ? true : false;
1435
+
1436
+ type IsShorthand<D> = D extends { array: unknown }
1437
+ ? true
1438
+ : D extends
1439
+ | { set: unknown }
1440
+ | { object: object }
1441
+ | { map: object }
1442
+ | { enum: readonly unknown[] }
1443
+ | { tuple: readonly unknown[] }
1444
+ | { union: readonly unknown[] }
1445
+ | { schema: object }
1446
+ | { one: string }
1447
+ | { many: string }
1448
+ | { flags: readonly string[] }
1449
+ ? true
1450
+ : false;
1451
+
1452
+ // Whether a definition is a struct, as `Infer` reads it.
1453
+ type IsStructDef<D> = D extends string
1454
+ ? false
1455
+ : D extends readonly unknown[]
1456
+ ? false
1457
+ : D extends Schema<infer X>
1458
+ ? IsStructDef<X>
1459
+ : D extends object
1460
+ ? [KindKey<D>] extends [never]
1461
+ ? D extends { type: string }
1462
+ ? false
1463
+ : IsShorthand<D> extends true
1464
+ ? false
1465
+ : true
1466
+ : true
1467
+ : false;
1468
+
1469
+ // What a derive function takes: a struct, or a schema of an unknown one.
1470
+ export type StructGuardOf<D> =
1471
+ IsWide<D> extends true ? unknown : IsStructDef<D> extends true ? unknown : never;
1472
+
1473
+ type OptionKey = 'validate' | 'parse' | 'serialize' | 'format';
1474
+
1475
+ type Fn = (...args: never[]) => unknown;
1476
+
1477
+ // The keys of the fields of a struct definition, as written ('nick?').
1478
+ type FieldKeyOf<D> = Exclude<FieldKeys<D>, KindKey<D>>;
1479
+
1480
+ // The keys of its calculated fields.
1481
+ type CalculatedKeyOf<D> = {
1482
+ [K in keyof D]: D[K] extends Fn ? (K extends OptionKey ? never : K) : never;
1483
+ }[keyof D];
1484
+
1485
+ // The names a derive function takes: the fields, the calculated fields and,
1486
+ // for a stored kind, its id (named after the entity, which the definition
1487
+ // does not carry).
1488
+ export type DeriveKeyOf<D> =
1489
+ IsWide<D> extends true
1490
+ ? string
1491
+ : Extract<
1492
+ | FieldName<FieldKeyOf<D>>
1493
+ | CalculatedKeyOf<D>
1494
+ | (StoreOf<D> extends 'persistent' ? `${string}Id` | 'id' : never),
1495
+ string
1496
+ >;
1497
+
1498
+ type KindName<D> = [KindKey<D>] extends [never] ? 'Struct' : KindKey<D>;
1499
+
1500
+ // The kind of a derived definition: the one of the options, else a struct
1501
+ // for a kindless definition, a stored kind and a projection, else the
1502
+ // source's kind with its metadata.
1503
+ type DerivedKind<D, O> = O extends { metadata: { kind: infer K extends string } }
1504
+ ? { [P in Capitalize<K>]: {} }
1505
+ : KindName<D> extends 'Struct' | 'Projection'
1506
+ ? { Struct: {} }
1507
+ : Lowercase<KindName<D> & string> extends StoredKind
1508
+ ? { Struct: {} }
1509
+ : { [P in KindName<D> & keyof D]: D[P] };
1510
+
1511
+ // A derived schema: of an unknown definition when the source's is unknown.
1512
+ export type DerivedSchema<D, R> = IsWide<D> extends true ? Schema : Schema<Simplify<R>>;
1513
+
1514
+ type Keep<D, K> = {
1515
+ [P in keyof D as P extends FieldKeyOf<D>
1516
+ ? FieldName<P> extends K
1517
+ ? P
1518
+ : never
1519
+ : P extends CalculatedKeyOf<D>
1520
+ ? P extends K
1521
+ ? P
1522
+ : never
1523
+ : never]: D[P];
1524
+ };
1525
+
1526
+ type Drop<D, K> = {
1527
+ [P in keyof D as P extends FieldKeyOf<D>
1528
+ ? FieldName<P> extends K
1529
+ ? never
1530
+ : P
1531
+ : P extends CalculatedKeyOf<D>
1532
+ ? P extends K
1533
+ ? never
1534
+ : P
1535
+ : never]: D[P];
1536
+ };
1537
+
1538
+ export type PickDefinition<D, K, O = {}> = DerivedKind<D, O> & Keep<D, K>;
1539
+
1540
+ export type OmitDefinition<D, K, O = {}> = DerivedKind<D, O> & Drop<D, K>;
1541
+
1542
+ type KeysOf<O, D> = O extends { keys: readonly (infer K)[] } ? K : FieldName<FieldKeyOf<D>>;
1543
+
1544
+ type IsDeep<O> = O extends { deep: true } ? true : false;
1545
+
1546
+ // The fields of a nested struct as a definition of their own, in each form
1547
+ // a field may hold one in; never for anything else.
1548
+ type NestedOf<X> =
1549
+ X extends Schema<infer S>
1550
+ ? IsStructDef<S> extends true
1551
+ ? S
1552
+ : never
1553
+ : X extends { schema: infer S }
1554
+ ? IsStructDef<S> extends true
1555
+ ? S
1556
+ : never
1557
+ : IsStructDef<X> extends true
1558
+ ? Omit<X, KindKey<X>>
1559
+ : never;
1560
+
1561
+ // A field holding a nested struct with the fields `F` in its place.
1562
+ type Reshaped<X, F> =
1563
+ X extends Schema<any>
1564
+ ? F
1565
+ : X extends { schema: unknown }
1566
+ ? Omit<X, 'schema' | 'validate' | 'parse' | 'serialize'> & { schema: F }
1567
+ : { [K in KindKey<X> & keyof X]: X[K] } & F;
1568
+
1569
+ type NoDefault<X, O> = O extends { defaults: true }
1570
+ ? X
1571
+ : IsStructDef<X> extends true
1572
+ ? X
1573
+ : Omit<X, 'default'>;
1574
+
1575
+ type OptionalDef<X, O> = X extends string
1576
+ ? X
1577
+ : IsDeep<O> extends true
1578
+ ? [NestedOf<X>] extends [never]
1579
+ ? NoDefault<X, O>
1580
+ : Simplify<Reshaped<NoDefault<X, O>, PartialFields<NestedOf<X>, O>>>
1581
+ : NoDefault<X, O>;
1582
+
1583
+ type PartialFields<D, O> = {
1584
+ [P in keyof D as P extends FieldKeyOf<D>
1585
+ ? `${FieldName<P> & string}?`
1586
+ : P extends CalculatedKeyOf<D>
1587
+ ? P
1588
+ : never]: P extends FieldKeyOf<D> ? OptionalDef<D[P], O> : D[P];
1589
+ };
1590
+
1591
+ type PartialOf<D, O> = {
1592
+ [P in keyof D as P extends FieldKeyOf<D>
1593
+ ? FieldName<P> extends KeysOf<O, D>
1594
+ ? `${FieldName<P> & string}?`
1595
+ : P
1596
+ : P extends CalculatedKeyOf<D>
1597
+ ? P
1598
+ : never]: P extends FieldKeyOf<D>
1599
+ ? FieldName<P> extends KeysOf<O, D>
1600
+ ? OptionalDef<D[P], O>
1601
+ : D[P]
1602
+ : D[P];
1603
+ };
1604
+
1605
+ export type PartialDefinition<D, O = {}> = DerivedKind<D, O> & PartialOf<D, O>;
1606
+
1607
+ type RequiredDef<X, O> = X extends `?${infer N}`
1608
+ ? N
1609
+ : X extends string
1610
+ ? X
1611
+ : Simplify<
1612
+ (X extends { type: `?${infer N}` }
1613
+ ? Omit<X, 'type' | 'required'> & { type: N }
1614
+ : IsStructDef<X> extends true
1615
+ ? X
1616
+ : Omit<X, 'required'>) extends infer Y
1617
+ ? IsDeep<O> extends true
1618
+ ? [NestedOf<X>] extends [never]
1619
+ ? Y
1620
+ : X extends { schema: unknown }
1621
+ ? Omit<Y, 'schema'> & { schema: RequiredFields<NestedOf<X>, O> }
1622
+ : X extends Schema<any>
1623
+ ? RequiredFields<NestedOf<X>, O>
1624
+ : { [K in KindKey<X> & keyof X]: X[K] } & RequiredFields<NestedOf<X>, O>
1625
+ : Y
1626
+ : never
1627
+ >;
1628
+
1629
+ type RequiredFields<D, O> = {
1630
+ [P in keyof D as P extends FieldKeyOf<D> ? FieldName<P> : P]: P extends FieldKeyOf<D>
1631
+ ? RequiredDef<D[P], O>
1632
+ : D[P];
1633
+ };
1634
+
1635
+ type RequiredOf<D, O> = {
1636
+ [P in keyof D as P extends FieldKeyOf<D>
1637
+ ? FieldName<P> extends KeysOf<O, D>
1638
+ ? FieldName<P>
1639
+ : P
1640
+ : P extends CalculatedKeyOf<D> | OptionKey
1641
+ ? P
1642
+ : never]: P extends FieldKeyOf<D>
1643
+ ? FieldName<P> extends KeysOf<O, D>
1644
+ ? RequiredDef<D[P], O>
1645
+ : D[P]
1646
+ : D[P];
1647
+ };
1648
+
1649
+ export type RequiredDefinition<D, O = {}> = DerivedKind<D, O> & RequiredOf<D, O>;
1650
+
1651
+ // What an extension adds: its fields (a Schema's, without its kind).
1652
+ type ExtensionOf<X> = X extends Schema<infer S> ? Omit<S, KindKey<S>> : X;
1653
+
1654
+ // An extension whose fields are not known (a `Schema`, an entity of a
1655
+ // model): what it extends is not known either.
1656
+ export type ExtendedSchema<D, X, R> =
1657
+ X extends Schema<infer S> ? (IsWide<S> extends true ? Schema : DerivedSchema<D, R>) : DerivedSchema<D, R>;
1658
+
1659
+ export type ExtendDefinition<D, X, O = {}> = DerivedKind<D, O> & {
1660
+ [P in keyof D as P extends KindKey<D>
1661
+ ? never
1662
+ : P extends FieldKeyOf<D>
1663
+ ? FieldName<P> extends FieldName<keyof ExtensionOf<X>>
1664
+ ? never
1665
+ : P
1666
+ : P]: D[P];
1667
+ } & ExtensionOf<X>;
1668
+
1669
+ // The names of the fields of a struct definition, as a definition of an enum.
1670
+ export type KeyofDefinition<D> = { enum: Array<FieldName<FieldKeyOf<D>>> };
1671
+
1150
1672
  // Standard Schema v1 (https://standardschema.dev): the interface every schema
1151
1673
  // exposes as `schema['~standard']`, so tRPC, TanStack Form, Hono and the other
1152
1674
  // consumers of the specification accept it without an adapter. The shape is
@@ -1262,6 +1784,51 @@ export class Schema<const D extends string | object = string | object> {
1262
1784
  // of the `@alexify/metaschema/model` subpath has run; its `sample(schema,
1263
1785
  // options)` is the same without it.
1264
1786
  sample(options?: SampleOptions): Infer<D>;
1787
+ // The value with the conversions of the schema and its defaults applied,
1788
+ // nothing checked: exists once `register()` of the
1789
+ // `@alexify/metaschema/coerce` subpath has run; its `coerce(schema,
1790
+ // value)` is the same without it.
1791
+ coerce(value: unknown, options?: CoerceOptions): unknown;
1792
+ // The six members below exist once `register()` of the
1793
+ // `@alexify/metaschema/derive` subpath has run; its `pick(schema, keys)`
1794
+ // and kin are the same without it. They are typed through `this`, never
1795
+ // through `D`: a member that maps `D` makes every comparison of two Schema
1796
+ // types instantiate the mapping ("excessively deep").
1797
+ pick<
1798
+ S extends Schema,
1799
+ const K extends readonly DeriveKeyOf<DefinitionOf<S>>[],
1800
+ const O extends DeriveOptions = {},
1801
+ >(
1802
+ this: S & StructGuardOf<DefinitionOf<S>>,
1803
+ keys: K,
1804
+ options?: O,
1805
+ ): DerivedSchema<DefinitionOf<S>, PickDefinition<DefinitionOf<S>, K[number], O>>;
1806
+ omit<
1807
+ S extends Schema,
1808
+ const K extends readonly DeriveKeyOf<DefinitionOf<S>>[],
1809
+ const O extends DeriveOptions = {},
1810
+ >(
1811
+ this: S & StructGuardOf<DefinitionOf<S>>,
1812
+ keys: K,
1813
+ options?: O,
1814
+ ): DerivedSchema<DefinitionOf<S>, OmitDefinition<DefinitionOf<S>, K[number], O>>;
1815
+ partial<S extends Schema, const O extends PartialOptions<DeriveKeyOf<DefinitionOf<S>>> = {}>(
1816
+ this: S & StructGuardOf<DefinitionOf<S>>,
1817
+ options?: O,
1818
+ ): DerivedSchema<DefinitionOf<S>, PartialDefinition<DefinitionOf<S>, O>>;
1819
+ required<S extends Schema, const O extends RequiredOptions<DeriveKeyOf<DefinitionOf<S>>> = {}>(
1820
+ this: S & StructGuardOf<DefinitionOf<S>>,
1821
+ options?: O,
1822
+ ): DerivedSchema<DefinitionOf<S>, RequiredDefinition<DefinitionOf<S>, O>>;
1823
+ extend<S extends Schema, const X extends object, const O extends DeriveOptions = {}>(
1824
+ this: S & StructGuardOf<DefinitionOf<S>>,
1825
+ extension: X,
1826
+ options?: O,
1827
+ ): ExtendedSchema<DefinitionOf<S>, X, ExtendDefinition<DefinitionOf<S>, X, O>>;
1828
+ keyof<S extends Schema>(
1829
+ this: S & StructGuardOf<DefinitionOf<S>>,
1830
+ options?: DeriveOptions,
1831
+ ): DerivedSchema<DefinitionOf<S>, KeyofDefinition<DefinitionOf<S>>>;
1265
1832
  // The five members below exist once `register()` of the
1266
1833
  // `@alexify/metaschema/stream` subpath has run; its `checkEach(schema,
1267
1834
  // records, options)` and kin are the same without it.
@@ -1294,11 +1861,16 @@ export class Schema<const D extends string | object = string | object> {
1294
1861
  detach(...namespaces: Array<Model>): void;
1295
1862
  toString(): string;
1296
1863
  toJSON(): object;
1864
+ // The schema as plain JSON: see `SchemaSnapshot`.
1865
+ toSnapshot(): SchemaSnapshot;
1297
1866
  validate(value: unknown, path?: string): ValidationResult | null;
1298
1867
  }
1299
1868
 
1300
1869
  export class Model {
1301
1870
  types: TypeTable;
1871
+ // The converters of coercion the model was given (`ModelOptions.coercions`),
1872
+ // frozen, or null.
1873
+ readonly coercions: Readonly<Record<string, Coercion>> | null;
1302
1874
  entities: Map<string, Schema>;
1303
1875
  database: Record<string, unknown> | null;
1304
1876
  order: Set<string>;