@atscript/typescript 0.2.3 → 0.2.5

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/dist/utils.d.ts CHANGED
@@ -1,8 +1,210 @@
1
+ /**
2
+ * Validator error codes, their default English templates and the translation helpers.
3
+ *
4
+ * The validator is locale-agnostic: every error it reports carries a stable `code` and the
5
+ * `params` its message needs, and its `message` is the default English text (the code's
6
+ * template filled with the params) or the app's own text from an annotation (`custom: true`).
7
+ * Translate after the fact with {@link localizeErrors}, or per validator with the `translate`
8
+ * option.
9
+ */
10
+ /**
11
+ * Default English templates of the built-in error codes. `{name}` is replaced with
12
+ * `params.name` (see {@link formatValidatorMessage}).
13
+ */
14
+ declare const VALIDATOR_MESSAGES: Readonly<{
15
+ /** A required string is empty (or whitespace only), or a required optional field is `null`. */
16
+ readonly REQUIRED: "Must not be empty";
17
+ /** A required boolean (`@meta.required` on a boolean) is not `true`. */
18
+ readonly REQUIRED_CHECKED: "Must be checked";
19
+ /** Wrong primitive type. `{ expected, actual }`: type names. */
20
+ readonly TYPE: "Expected {expected}, got {actual}";
21
+ /** Not an array. `{ actual }`: the value's type name. */
22
+ readonly TYPE_ARRAY: "Expected array";
23
+ /** Not an object. `{ actual }`: the value's type name. */
24
+ readonly TYPE_OBJECT: "Expected object";
25
+ /** A decimal that is not a string. `{ actual }`: the value's type name. */
26
+ readonly TYPE_DECIMAL: "Expected string (decimal), got {actual}";
27
+ /** `NaN` or an infinity. `{ actual }`: the value as text. */
28
+ readonly NOT_FINITE: "Expected finite number, got {actual}";
29
+ /** A decimal string in the wrong format. `{ value }`: the string. */
30
+ readonly DECIMAL_FORMAT: "Invalid decimal format: \"{value}\"";
31
+ /** A `never` type. */
32
+ readonly NEVER: "This type is impossible, must be an internal problem";
33
+ /** Not the literal value. `{ expected, actual }`: the literal, the value as text. */
34
+ readonly LITERAL: "Expected {expected}, got {actual}";
35
+ /** No union branch matches. `{ expected }`: the branch kinds (`[string(0)], [number(1)]`). */
36
+ readonly UNION: "Value does not match any of the allowed types: {expected}";
37
+ /**
38
+ * The discriminator of an object union holds no branch's value. Reported at the discriminator
39
+ * property. `{ property, allowed, actual }`: its name, the allowed values, the value as text.
40
+ */
41
+ readonly UNION_DISCRIMINATOR: "Expected one of {allowed}, got {actual}";
42
+ /** A property the type does not declare (`unknownProps: 'error'`). `{ property }`. */
43
+ readonly UNEXPECTED_PROPERTY: "Unexpected property";
44
+ /** A tuple of the wrong length. `{ length }`: the expected length. */
45
+ readonly TUPLE_LENGTH: "Expected array of length {length}";
46
+ /** `@expect.minLength` on a string. `{ min, actual }`: lengths. */
47
+ readonly MIN_LENGTH: "Expected minimum length of {min} characters, got {actual} characters";
48
+ /** `@expect.maxLength` on a string. `{ max, actual }`: lengths. */
49
+ readonly MAX_LENGTH: "Expected maximum length of {max} characters, got {actual} characters";
50
+ /** `@expect.minLength` on an array. `{ min, actual }`: item counts. */
51
+ readonly MIN_ITEMS: "Expected minimum length of {min} items, got {actual} items";
52
+ /** `@expect.maxLength` on an array. `{ max, actual }`: item counts. */
53
+ readonly MAX_ITEMS: "Expected maximum length of {max} items, got {actual} items";
54
+ /** `@expect.array.uniqueItems`: a duplicate item (reported at its index). */
55
+ readonly UNIQUE_ITEMS: "Duplicate items are not allowed";
56
+ /** `@expect.minKeys`. `{ min, actual }`: key counts. */
57
+ readonly MIN_KEYS: "Expected at least {min} properties, got {actual}";
58
+ /** `@expect.maxKeys`. `{ max, actual }`: key counts. */
59
+ readonly MAX_KEYS: "Expected at most {max} properties, got {actual}";
60
+ /** `@expect.pattern` without a message. `{ pattern, flags }`. */
61
+ readonly PATTERN: "Value is expected to match pattern \"{pattern}\"";
62
+ /** `@expect.int`. `{ actual }`: the value. */
63
+ readonly INT: "Expected integer, got {actual}";
64
+ /** `@expect.min`. `{ min, actual }`. */
65
+ readonly MIN: "Expected minimum {min}, got {actual}";
66
+ /** `@expect.max`. `{ max, actual }`. */
67
+ readonly MAX: "Expected maximum {max}, got {actual}";
68
+ /** `@expect.exclusiveMin`. `{ min, actual }`. */
69
+ readonly EXCLUSIVE_MIN: "Expected greater than {min}, got {actual}";
70
+ /** `@expect.exclusiveMax`. `{ max, actual }`. */
71
+ readonly EXCLUSIVE_MAX: "Expected less than {max}, got {actual}";
72
+ /** `string.email`. */
73
+ readonly EMAIL: "Invalid email format.";
74
+ /** `string.phone`. */
75
+ readonly PHONE: "Invalid phone number format.";
76
+ /** `string.date`. */
77
+ readonly DATE: "Invalid date format.";
78
+ /** `string.isoDate`. */
79
+ readonly ISO_DATE: "Invalid ISO date format.";
80
+ /** `string.uuid`. */
81
+ readonly UUID: "Invalid UUID format.";
82
+ /** `string.url`. */
83
+ readonly URL: "Invalid URL format.";
84
+ /** `string.ipv4`. */
85
+ readonly IPV4: "Invalid IPv4 address.";
86
+ /** `string.ipv6`. */
87
+ readonly IPV6: "Invalid IPv6 address.";
88
+ /** `string.ip`. */
89
+ readonly IP: "Invalid IP address.";
90
+ }>;
91
+ /** A built-in validator error code (a key of {@link VALIDATOR_MESSAGES}), or `CUSTOM`. */
92
+ type TValidatorErrorCode = keyof typeof VALIDATOR_MESSAGES | 'CUSTOM';
93
+ /**
94
+ * The built-in validator error codes by name (`VALIDATOR_ERROR_CODES.MIN_LENGTH === 'MIN_LENGTH'`).
95
+ * `CUSTOM` is the code of an error a validator plugin reports without a code of its own.
96
+ */
97
+ declare const VALIDATOR_ERROR_CODES: Readonly<{
98
+ readonly URL: "URL";
99
+ readonly REQUIRED: "REQUIRED";
100
+ readonly REQUIRED_CHECKED: "REQUIRED_CHECKED";
101
+ readonly TYPE: "TYPE";
102
+ readonly TYPE_ARRAY: "TYPE_ARRAY";
103
+ readonly TYPE_OBJECT: "TYPE_OBJECT";
104
+ readonly TYPE_DECIMAL: "TYPE_DECIMAL";
105
+ readonly NOT_FINITE: "NOT_FINITE";
106
+ readonly DECIMAL_FORMAT: "DECIMAL_FORMAT";
107
+ readonly NEVER: "NEVER";
108
+ readonly LITERAL: "LITERAL";
109
+ readonly UNION: "UNION";
110
+ readonly UNION_DISCRIMINATOR: "UNION_DISCRIMINATOR";
111
+ readonly UNEXPECTED_PROPERTY: "UNEXPECTED_PROPERTY";
112
+ readonly TUPLE_LENGTH: "TUPLE_LENGTH";
113
+ readonly MIN_LENGTH: "MIN_LENGTH";
114
+ readonly MAX_LENGTH: "MAX_LENGTH";
115
+ readonly MIN_ITEMS: "MIN_ITEMS";
116
+ readonly MAX_ITEMS: "MAX_ITEMS";
117
+ readonly UNIQUE_ITEMS: "UNIQUE_ITEMS";
118
+ readonly MIN_KEYS: "MIN_KEYS";
119
+ readonly MAX_KEYS: "MAX_KEYS";
120
+ readonly PATTERN: "PATTERN";
121
+ readonly INT: "INT";
122
+ readonly MIN: "MIN";
123
+ readonly MAX: "MAX";
124
+ readonly EXCLUSIVE_MIN: "EXCLUSIVE_MIN";
125
+ readonly EXCLUSIVE_MAX: "EXCLUSIVE_MAX";
126
+ readonly EMAIL: "EMAIL";
127
+ readonly PHONE: "PHONE";
128
+ readonly DATE: "DATE";
129
+ readonly ISO_DATE: "ISO_DATE";
130
+ readonly UUID: "UUID";
131
+ readonly IPV4: "IPV4";
132
+ readonly IPV6: "IPV6";
133
+ readonly IP: "IP";
134
+ readonly CUSTOM: "CUSTOM";
135
+ }>;
136
+ /** A validation error. */
1
137
  interface TError {
138
+ /** Dot path of the value (`''`: the root). */
2
139
  path: string;
140
+ /**
141
+ * The message: the code's template filled with `params` (English by default), or the app's
142
+ * own text from an annotation (`custom: true`), translated when a translator is used.
143
+ */
3
144
  message: string;
145
+ /**
146
+ * Stable code (UPPER_SNAKE): a {@link TValidatorErrorCode} for the validator's own errors,
147
+ * a plugin's own code, or `CUSTOM`. Optional only for errors made by hand.
148
+ */
149
+ code?: TValidatorErrorCode | (string & Record<never, never>);
150
+ /** The values the code's message needs (limits, expected type, pattern, …); JSON-safe. */
151
+ params?: Record<string, unknown>;
152
+ /**
153
+ * `true` when `message` is the app's own text (an annotation's message argument,
154
+ * `@expect.message`, a plugin's message) rather than the code's template: a translator
155
+ * gets that text as the message id instead of the code.
156
+ */
157
+ custom?: boolean;
158
+ /** The errors of each union branch (a union error), in branch order. */
4
159
  details?: TError[];
5
160
  }
161
+ /**
162
+ * Translates one error: `id` is the error's `code` for a built-in message, or its message text
163
+ * for app text (`custom`, or no code). Return `undefined` to keep the current message.
164
+ */
165
+ type TValidatorTranslate = (id: string, params: Record<string, unknown>, error: TError) => string | undefined;
166
+ /**
167
+ * Fills a message template: each `{name}` becomes `params.name` (arrays: their items joined
168
+ * with `, `). A placeholder without a param stays as it is.
169
+ */
170
+ declare function formatValidatorMessage(template: string, params: Record<string, unknown> | undefined): string;
171
+ /**
172
+ * Returns `errors` with translated messages (new objects; `details` too): `translate` gets
173
+ * each error's code (or its message text, for app text — see {@link TValidatorTranslate}),
174
+ * params and the error itself. Errors it returns `undefined` for keep their message.
175
+ *
176
+ * @example
177
+ * ```ts
178
+ * const errors = localizeErrors(validator.errors, (id, params) =>
179
+ * i18n.exists(id) ? i18n.t(id, params) : undefined
180
+ * )
181
+ * ```
182
+ */
183
+ declare function localizeErrors(errors: TError[], translate: TValidatorTranslate): TError[];
184
+ /**
185
+ * A {@link TValidatorTranslate} over a map of message templates keyed by code (and, for app
186
+ * text, by the text itself): `{name}` placeholders are filled from the error's params. Ids
187
+ * missing from the map keep their message.
188
+ *
189
+ * @example
190
+ * ```ts
191
+ * // templates served per locale, e.g. { MIN_LENGTH: 'Mindestens {min} Zeichen', … }
192
+ * localizeErrors(errors, messagesTranslator(templates))
193
+ * ```
194
+ */
195
+ declare function messagesTranslator(messages: Record<string, string>): TValidatorTranslate;
196
+
197
+ /**
198
+ * What an error reports besides its message (see {@link Validator.error}): its code (`CUSTOM`
199
+ * when omitted), params and `custom` flag.
200
+ */
201
+ interface TErrorInfo extends Pick<TError, 'code' | 'params'> {
202
+ /**
203
+ * The message is app text (a translator gets it as the id) rather than the code's own
204
+ * message. Default: `true` without a `code`, `false` with one.
205
+ */
206
+ custom?: boolean;
207
+ }
6
208
  /**
7
209
  * A plugin function that can intercept validation.
8
210
  *
@@ -18,6 +220,11 @@ interface TValidatorOptions {
18
220
  unknownProps: 'strip' | 'ignore' | 'error';
19
221
  errorLimit: number;
20
222
  skipList?: Set<string>;
223
+ /**
224
+ * Translates the errors of a failed call (see {@link localizeErrors}) before they are
225
+ * reported (`errors`, the thrown {@link ValidatorError}).
226
+ */
227
+ translate?: TValidatorTranslate;
21
228
  }
22
229
  /** Context exposed to {@link TValidatorPlugin} functions. */
23
230
  interface TValidatorPluginContext {
@@ -101,8 +308,26 @@ declare class Validator<T extends TAtscriptAnnotatedType = TAtscriptAnnotatedTyp
101
308
  protected push(name: string): void;
102
309
  protected pop(saveErrors: boolean): TError[] | null | undefined;
103
310
  protected clear(): void;
104
- protected error(message: string, path?: string, details?: TError[]): TError;
105
- /** Adds `error`, already made, to the errors of the current level (as {@link error} does). */
311
+ /**
312
+ * Reports an error at `path` (default: the current path). `info` gives its code and params;
313
+ * without it the error is app text with code `CUSTOM` (a plugin's own message).
314
+ */
315
+ protected error(message: string, path?: string, details?: TError[], info?: TErrorInfo): TError;
316
+ /**
317
+ * Reports built-in error `code`: `custom` (the app's message from an annotation) when given,
318
+ * else the code's template filled with `params`.
319
+ */
320
+ private fail;
321
+ /** Reports built-in error `code` at `path` (see {@link fail}), with `details` (a union's). */
322
+ private builtin;
323
+ /** {@link fail} of a type mismatch of `def`: its `@expect.message` replaces the message. */
324
+ private mismatch;
325
+ /** The `@meta.required` error of `def` (custom message or the type's default). */
326
+ private required;
327
+ /**
328
+ * Adds `error`, already made, to the errors of the current level (as {@link error} does);
329
+ * `true` once the level holds as many errors as the limit.
330
+ */
106
331
  private report;
107
332
  protected throw(): void;
108
333
  /**
@@ -145,6 +370,19 @@ declare class Validator<T extends TAtscriptAnnotatedType = TAtscriptAnnotatedTyp
145
370
  protected get root(): T;
146
371
  protected validateAnnotatedType(def: TAtscriptAnnotatedType, value: any): boolean;
147
372
  protected validateUnion(def: TAtscriptAnnotatedType<TAtscriptTypeComplex>, value: any): boolean;
373
+ /** Reports the error of union `def` no branch matched (`details`: the branches' errors). */
374
+ private unionError;
375
+ /**
376
+ * The errors of an object union over object `value` with a shared literal discriminator (see
377
+ * {@link unionDiscriminator}), reported in place of the union error: the errors of the branch
378
+ * the value's discriminator picks, or one `UNION_DISCRIMINATOR` error at the discriminator
379
+ * when it picks none. `undefined` (nothing reported) for other unions and values.
380
+ */
381
+ private discriminatedErrors;
382
+ /** Reports `errors`, made already, until the error limit is reached. */
383
+ private reportAll;
384
+ /** Whether missing props are allowed at the current depth (the `partial` option). */
385
+ private partialHere;
148
386
  /** A union branch failed after branches of nested unions over objects did (see `unionMemo`). */
149
387
  private wasteBranch;
150
388
  /** The outcome this call recorded for union `def` over `value` at `path` (see `unionMemo`). */
@@ -181,12 +419,35 @@ declare class Validator<T extends TAtscriptAnnotatedType = TAtscriptAnnotatedTyp
181
419
  protected validateNumber(def: TAtscriptAnnotatedType<TAtscriptTypeFinal>, value: number): boolean;
182
420
  /** `@expect.int` / `min` / `max` / `exclusiveMin` / `exclusiveMax` checks for a number value. */
183
421
  protected validateNumberConstraints(meta: TMetadataMap<AtscriptMetadata>, value: number): boolean;
184
- /** Reports a failed number bound: its custom message, else `Expected <label> <bound>, got <value>`. */
185
- private numberBoundFailed;
186
422
  protected validateBoolean(def: TAtscriptAnnotatedType<TAtscriptTypeFinal>, value: boolean): boolean;
187
423
  /** `@meta.required` check for a boolean value (must be `true`). */
188
424
  protected validateBooleanConstraints(meta: TMetadataMap<AtscriptMetadata>, value: boolean): boolean;
425
+ /**
426
+ * `@expect.minKeys` / `maxKeys` checks for an object value, matched as `shape`: the keys the
427
+ * result keeps are counted (see {@link keptKeyCount}; `skipList`: the skip list keys here).
428
+ */
429
+ protected validateObjectConstraints(meta: TMetadataMap<AtscriptMetadata>, value: object, shape: TAtscriptAnnotatedType, skipList: Set<string> | undefined): boolean;
430
+ /**
431
+ * The keys of object `value` (matched as `shape`) the result keeps: every own key with
432
+ * `unknownProps: 'ignore'`; else (and with 'strip', and 'error', where the others are errors
433
+ * of their own) the keys `shape` declares, its pattern props match or the skip list names.
434
+ * Matched as anything other than an object type, every own key.
435
+ */
436
+ private keptKeyCount;
189
437
  }
438
+ /** A union's discriminator, as the validator reports it (see {@link unionDiscriminator}). */
439
+ interface TValidatorDiscriminator {
440
+ property: string;
441
+ /** Per object branch: its index in the union's items, its literal. */
442
+ branches: Array<[index: number, literal: unknown]>;
443
+ }
444
+ /**
445
+ * The discriminator of a union over objects (see {@link detectDiscriminator}), required in every
446
+ * object branch: the property and, per object branch, its index in `items` and its literal. The
447
+ * other branches must reject any object (scalars, arrays, tuples), so only the object branches
448
+ * can match an object value.
449
+ */
450
+ declare function unionDiscriminator(items: TAtscriptAnnotatedType[]): TValidatorDiscriminator | undefined;
190
451
  /** Error thrown by {@link Validator.validate} when validation fails. Contains structured error details. */
191
452
  declare class ValidatorError extends Error {
192
453
  readonly errors: TError[];
@@ -426,30 +687,61 @@ declare function coerceForType(def: TAtscriptAnnotatedType, value: unknown): unk
426
687
  */
427
688
  declare function coerceScalar(designType: TAtscriptTypeFinal['designType'], value: unknown): unknown;
428
689
 
429
- /** A JSON Schema object (draft-compatible). */
430
- type TJsonSchema = Record<string, any>;
431
690
  /**
432
- * Describes a discriminator property shared by all variants of a union.
691
+ * Normalizes input toward the string forms an annotated type declares with `@normalize.trim`,
692
+ * `@normalize.lowercase` and `@normalize.uppercase`.
433
693
  *
434
- * Returned by {@link detectDiscriminator} when a union qualifies as a
435
- * discriminated (a.k.a. tagged) union — every variant is an object that
436
- * carries the same literal-valued property with a distinct value.
437
- */
438
- type TUnionDiscriminator = {
439
- /** Name of the discriminator property shared by all variants. */
440
- propertyName: string;
441
- /** Maps the literal value of `propertyName` → variant index in `items`. */
442
- indexMapping: Record<string, number>;
443
- };
444
- /**
445
- * Detects a discriminator property across union items.
694
+ * Pure: returns a normalized copy (copy-on-change: untouched objects and arrays are returned as
695
+ * they are) and never mutates `value`. It never validates — run the validator on the result —
696
+ * and does not throw on ordinary input (a cyclic value overflows the stack, as it does in the
697
+ * validator). Only strings change: a string node's normalizers (its own, a type alias's it
698
+ * inherits, a union's it belongs to) apply in a fixed order: trim, then lowercase, then
699
+ * uppercase. Other values (including class instances such as `Date`) and strings without
700
+ * normalizers are returned untouched; a type without normalizers returns `value` at once.
446
701
  *
447
- * Scans all items for object-typed members that share a common property
448
- * with distinct const/literal values. If exactly one such property exists,
449
- * it is returned as the discriminator. Returns `null` when no qualifying
450
- * property exists, or when more than one does (ambiguous).
702
+ * Walks plain objects (props and pattern props; unknown keys are kept as they are), arrays,
703
+ * tuples, intersections and unions. An object whose literal prop (`kind: 'cat'`) holds another
704
+ * value is left as it is. A union normalizes a value only when the result does not depend on
705
+ * which branch takes it:
706
+ * - an object union with a discriminator (a literal prop every object branch requires, see
707
+ * `detectDiscriminator`) uses the branch the value's discriminator names;
708
+ * - otherwise every branch that can take the value is tried (a literal branch can take a string
709
+ * only when the normalized string equals its literal): when they all give the same result it
710
+ * is used; when they differ, the branches whose result their own validator accepts (default
711
+ * options) are kept, and the result is used when they agree; else the value is returned
712
+ * untouched (ambiguous).
713
+ *
714
+ * The intended flow is `coerceForType` → `normalizeForType` → `validate`.
715
+ *
716
+ * @example
717
+ * ```ts
718
+ * // @normalize.trim @normalize.lowercase email: string.email
719
+ * normalizeForType(User, { email: ' Ann@Example.COM ' }) // → { email: 'ann@example.com' }
720
+ * ```
451
721
  */
452
- declare function detectDiscriminator(items: TAtscriptAnnotatedType[]): TUnionDiscriminator | null;
722
+ declare function normalizeForType<T = unknown>(def: TAtscriptAnnotatedType, value: T): T;
723
+
724
+ /** A JSON Schema object (draft-compatible). */
725
+ type TJsonSchema = Record<string, any>;
726
+ /** Options of {@link buildJsonSchema} (and of the `jsonSchemaOptions` plugin option). */
727
+ interface TJsonSchemaOptions {
728
+ /**
729
+ * `additionalProperties: false` on every object schema: the schema rejects keys the type does
730
+ * not declare, as the validator does with its default `unknownProps: 'error'`.
731
+ * *(default: `false`)*
732
+ */
733
+ closed?: boolean;
734
+ /**
735
+ * `@meta.description` → `description` and `@meta.label` → `title`, on the schema of the
736
+ * type or field that carries them. *(default: `true`)*
737
+ */
738
+ annotations?: boolean;
739
+ /**
740
+ * A union of literals (`'a' | 'b'`, also with `null`) → `{ type, enum }` instead of an
741
+ * `anyOf` of `const` schemas. *(default: `true`)*
742
+ */
743
+ enums?: boolean;
744
+ }
453
745
  /**
454
746
  * Builds a JSON Schema from an {@link TAtscriptAnnotatedType}.
455
747
  *
@@ -465,9 +757,10 @@ declare function detectDiscriminator(items: TAtscriptAnnotatedType[]): TUnionDis
465
757
  * ```
466
758
  *
467
759
  * @param type - The annotated type to convert.
760
+ * @param opts - {@link TJsonSchemaOptions}.
468
761
  * @returns A JSON Schema object.
469
762
  */
470
- declare function buildJsonSchema(type: TAtscriptAnnotatedType): TJsonSchema;
763
+ declare function buildJsonSchema(type: TAtscriptAnnotatedType, opts?: TJsonSchemaOptions): TJsonSchema;
471
764
  /**
472
765
  * Converts a JSON Schema object into a {@link TAtscriptAnnotatedType}.
473
766
  *
@@ -500,13 +793,41 @@ declare function fromJsonSchema(schema: TJsonSchema): TAtscriptAnnotatedType;
500
793
  * to it are renamed.
501
794
  *
502
795
  * @param types - Array of annotated types, each with an `id`.
796
+ * @param opts - {@link TJsonSchemaOptions}, for every schema.
503
797
  * @returns An object with `schemas` (keyed by id) and shared `$defs`.
504
798
  */
505
- declare function mergeJsonSchemas(types: TAtscriptAnnotatedType[]): {
799
+ declare function mergeJsonSchemas(types: TAtscriptAnnotatedType[], opts?: TJsonSchemaOptions): {
506
800
  schemas: Record<string, TJsonSchema>;
507
801
  $defs: Record<string, TJsonSchema>;
508
802
  };
509
803
 
804
+ /**
805
+ * Describes a discriminator property shared by all variants of a union.
806
+ *
807
+ * Returned by {@link detectDiscriminator} when a union qualifies as a
808
+ * discriminated (a.k.a. tagged) union — every variant is an object that
809
+ * carries the same literal-valued property with a distinct value.
810
+ */
811
+ type TUnionDiscriminator = {
812
+ /** Name of the discriminator property shared by all variants. */
813
+ propertyName: string;
814
+ /**
815
+ * Maps the literal value of `propertyName` (as a string) → variant index in `items`. An object
816
+ * without a prototype: look a value up directly (`indexMapping[String(tag)]`), a key such as
817
+ * `constructor` finds nothing.
818
+ */
819
+ indexMapping: Record<string, number>;
820
+ };
821
+ /**
822
+ * Detects a discriminator property across union items.
823
+ *
824
+ * Scans all items for object-typed members that share a common property
825
+ * with distinct const/literal values. If exactly one such property exists,
826
+ * it is returned as the discriminator. Returns `null` when no qualifying
827
+ * property exists, or when more than one does (ambiguous).
828
+ */
829
+ declare function detectDiscriminator(items: TAtscriptAnnotatedType[]): TUnionDiscriminator | null;
830
+
510
831
  /**
511
832
  * Type-safe dispatch over `TAtscriptAnnotatedType` by its `type.kind`.
512
833
  *
@@ -576,16 +897,18 @@ declare function throwFeatureDisabled(feature: string, option: string, annotatio
576
897
  /**
577
898
  * The JSON schema of `type` built by the runtime (`jsonSchema: 'lazy'`): built once, again after
578
899
  * a metadata write (a block, a runtime edit: see `metadataWrites`). Called by generated code
579
- * (`static toJsonSchema()`).
900
+ * (`static toJsonSchema()`), with the `jsonSchemaOptions` of the build (the same for every call
901
+ * of a type).
580
902
  */
581
- declare function lazyJsonSchema(type: TAtscriptAnnotatedType): TJsonSchema;
903
+ declare function lazyJsonSchema(type: TAtscriptAnnotatedType, opts?: TJsonSchemaOptions): TJsonSchema;
582
904
  /**
583
905
  * The JSON schema of `type` (`jsonSchema: 'bundle'`): the
584
906
  * bundled `literal` while the modules whose blocks applied are exactly those the build accounted
585
907
  * (`modules`, the realm's applied block modules), else the runtime's (`buildJsonSchema`). Raw
586
- * metadata writes are not seen (as in 0.1.110). Called by generated code.
908
+ * metadata writes are not seen (as in 0.1.110). Called by generated code, with the
909
+ * `jsonSchemaOptions` of the build (the literal was built with them).
587
910
  */
588
- declare function bundledSchemaOf(type: TAtscriptAnnotatedType, literal: () => TJsonSchema, modules?: readonly string[]): TJsonSchema;
911
+ declare function bundledSchemaOf(type: TAtscriptAnnotatedType, literal: () => TJsonSchema, modules?: readonly string[], opts?: TJsonSchemaOptions): TJsonSchema;
589
912
 
590
913
  type TSite = [optional: number, mask: number, def: number, shape: string, slot: number];
591
914
  type TDef = Array<string | number | boolean | string[] | TSite | TSite[]>;
@@ -782,6 +1105,13 @@ declare const SERIALIZE_VERSION = 2;
782
1105
  interface TSerializedAnnotatedType extends TSerializedAnnotatedTypeInner {
783
1106
  /** Format version for forward compatibility */
784
1107
  $v: number;
1108
+ /**
1109
+ * Texts a server serves with the type for the client, in the locale it was translated to
1110
+ * (see `translateServed`): message templates by code (`{name}` placeholders) and translated
1111
+ * texts by their source text — what `messagesTranslator()` takes. Never written by
1112
+ * `serializeAnnotatedType`; `deserializeAnnotatedType` ignores it.
1113
+ */
1114
+ $i18n?: Record<string, string>;
785
1115
  }
786
1116
  /** Serialized annotated type node (used for nested types within the top-level). */
787
1117
  interface TSerializedAnnotatedTypeInner {
@@ -939,6 +1269,40 @@ declare function serializeAnnotatedType(type: TAtscriptAnnotatedType, options?:
939
1269
  */
940
1270
  declare function deserializeAnnotatedType(data: TSerializedAnnotatedType): TAtscriptAnnotatedType;
941
1271
 
1272
+ /**
1273
+ * Translating a serialized type (or any JSON carrying serialized types) before it is served:
1274
+ * the user-facing text of its metadata is replaced, the string literals of its expressions are
1275
+ * collected for the client.
1276
+ */
1277
+ /**
1278
+ * Translates the user-facing text of serialized annotated types (the output of
1279
+ * `serializeAnnotatedType`, or any JSON holding such output) with `t`. Every `metadata` object
1280
+ * found at any depth is read with {@link userTextOf}:
1281
+ *
1282
+ * - a text key's value (each item of a `multiple` list; the named fields of a value object) is
1283
+ * replaced by `t(text)` — except a primitive's built-in format message (`string.email`'s), which
1284
+ * the validator reports by its code (`EMAIL`), translated on the client through `$i18n`;
1285
+ * - an expression key's value (function source evaluated by the client) stays as it is: the
1286
+ * string literals in it (`'…'`, `"…"`, and `` `…` `` templates without `${…}`) are translated,
1287
+ * and `texts` maps each literal translated to its translation — serve it to the client, which
1288
+ * translates the expressions' results by exact match.
1289
+ *
1290
+ * `t` returns `undefined` (anything but a string) to keep a text. The input is never changed: the
1291
+ * result shares every part with no translated text, and is `json` itself when nothing was
1292
+ * translated.
1293
+ *
1294
+ * @example
1295
+ * ```ts
1296
+ * const { value, texts } = translateServed(serializeAnnotatedType(Product), text =>
1297
+ * i18n.exists(text) ? i18n.t(text) : undefined
1298
+ * )
1299
+ * ```
1300
+ */
1301
+ declare function translateServed<T>(json: T, t: (text: string) => string | undefined): {
1302
+ value: T;
1303
+ texts: Record<string, string>;
1304
+ };
1305
+
942
1306
  /**
943
1307
  * Metadata layers: the runtime's one metadata mechanism.
944
1308
  *
@@ -993,11 +1357,17 @@ declare class LayerMap<K = unknown, V = unknown> extends AnnotationMap<K, V> {
993
1357
  /** `get` read through the layers (see the file comment). */
994
1358
  private liveGet;
995
1359
  has(key: K): boolean;
1360
+ /** `has` read through the layers (see the file comment). */
1361
+ private liveHas;
996
1362
  /** An append key: the bases' values (lowest priority first), then the own ones. */
997
1363
  private append;
998
1364
  /** The effective keys: own first, then the bases' in priority order. */
999
1365
  private effectiveKeys;
1000
1366
  private liveKeys;
1367
+ /** Deletes the own value of `key`; a key hidden from the bases (`hideKey`) shows them again. */
1368
+ delete(key: K): boolean;
1369
+ /** Deletes the own values; the keys hidden from the bases (`hideKey`) show them again. */
1370
+ clear(): void;
1001
1371
  keys(): MapIterator<K>;
1002
1372
  values(): MapIterator<V>;
1003
1373
  entries(): MapIterator<[K, V]>;
@@ -1017,6 +1387,40 @@ declare function metaEmpty(m: Map<unknown, unknown>): boolean;
1017
1387
  */
1018
1388
  declare function watchLayer(m: Map<unknown, unknown>, seen?: Set<object>): boolean;
1019
1389
 
1390
+ /**
1391
+ * The annotations holding user-facing text (labels, descriptions, error messages): the arguments
1392
+ * their specs flag `userText`. Core's are known from the start ({@link CORE_USER_TEXT}); a plugin's
1393
+ * are registered by the generated modules that write them (`$ut`), or by the plugin itself
1394
+ * ({@link registerUserText}), so a translator finds them at runtime without the specs.
1395
+ */
1396
+ /**
1397
+ * `true`: the value itself is the text; `'expression'`: the value is the source of a function the
1398
+ * client evaluates, its string literals the texts; a list: those fields of the value object are
1399
+ * (a name ending in `()`: that field is an expression).
1400
+ */
1401
+ type TUserTextFields = true | 'expression' | readonly string[];
1402
+ /**
1403
+ * Registers metadata key `key` as holding user-facing text (see {@link TUserTextFields}; `true` by
1404
+ * default). Fields add up across calls; a whole-value kind replaces a field list, and an
1405
+ * expression wins over text (`name()` over `name`), whatever the order of the calls.
1406
+ * For plugins that write such metadata at runtime; generated modules register what they write.
1407
+ */
1408
+ declare function registerUserText(key: string, fields?: TUserTextFields): void;
1409
+ /**
1410
+ * Registers user-text keys written by a generated module (see {@link registerUserText}): `key` —
1411
+ * the value itself; `key()` — the value is an expression; `key:field` — that field of the value
1412
+ * object; `key:field()` — that field is an expression.
1413
+ */
1414
+ declare function $ut(...entries: string[]): void;
1415
+ /**
1416
+ * Where metadata key `key` holds user-facing text (see {@link TUserTextFields}; for a `multiple`
1417
+ * annotation, each item of its list), `undefined` when it holds none. Core keys are known from the
1418
+ * start; a plugin's once a module writing them is loaded (or the plugin registered them).
1419
+ */
1420
+ declare function userTextOf(key: string): TUserTextFields | undefined;
1421
+ /** Every metadata key holding user-facing text known so far (see {@link userTextOf}). */
1422
+ declare function userTextKeys(): ReadonlyMap<string, TUserTextFields>;
1423
+
1020
1424
  type TNode = TAtscriptAnnotatedType;
1021
1425
  /**
1022
1426
  * The node at `path` below `root` (see {@link child}); `NOT_READY` while it is not built, or
@@ -1121,5 +1525,5 @@ type NavPropsOf<T> = T extends {
1121
1525
  __navProps: infer N extends Record<string, unknown>;
1122
1526
  } ? N : Record<string, never>;
1123
1527
 
1124
- export { $ak, $alias, $blk, $end, $f, $fc, $ft, $nr, $ps, $q, $sh, LayerMap, SERIALIZE_VERSION, Validator, ValidatorError, annotate, appliedBlockModules, buildJsonSchema, bundledSchemaOf, coerceForType, coerceScalar, createAnnotatedTypeNode, createDataFromAnnotatedType, defineAnnotatedType, deserializeAnnotatedType, detectDiscriminator, flattenAnnotatedType, forAnnotatedType, fromJsonSchema, invalidateCompiledValidators, isAnnotatedType, isAnnotatedTypeOfPrimitive, isPhantomType, lazyJsonSchema, mergeJsonSchemas, metaEmpty, pendingStatements, registerCompiledCheck, serializeAnnotatedType, throwFeatureDisabled, watchLayer };
1125
- export type { AtscriptExprNode, AtscriptOrderItem, AtscriptQueryComparison, AtscriptQueryFieldRef, AtscriptQueryNode, AtscriptRef, FlatOf, InferDataType, NavPropsOf, OwnPropsOf, PrimaryKeyOf, TAnnotatedTypeHandle, TAtscriptAnnotatedType, TAtscriptAnnotatedTypeConstructor, TAtscriptDataType, TAtscriptField, TAtscriptTypeArray, TAtscriptTypeComplex, TAtscriptTypeDef, TAtscriptTypeFinal, TAtscriptTypeObject, TCreateDataOptions, TFlattenOptions, TJsonSchema, TMetadataMap, TProcessAnnotationContext, TSerializeOptions, TSerializedAnnotatedType, TSerializedAnnotatedTypeInner, TSerializedTypeArray, TSerializedTypeComplex, TSerializedTypeDef, TSerializedTypeFinal, TSerializedTypeObject, TUnionDiscriminator, TValidatorOptions, TValidatorPlugin, TValidatorPluginContext, TValueResolver };
1528
+ export { $ak, $alias, $blk, $end, $f, $fc, $ft, $nr, $ps, $q, $sh, $ut, LayerMap, SERIALIZE_VERSION, VALIDATOR_ERROR_CODES, VALIDATOR_MESSAGES, Validator, ValidatorError, annotate, appliedBlockModules, buildJsonSchema, bundledSchemaOf, coerceForType, coerceScalar, createAnnotatedTypeNode, createDataFromAnnotatedType, defineAnnotatedType, deserializeAnnotatedType, detectDiscriminator, flattenAnnotatedType, forAnnotatedType, formatValidatorMessage, fromJsonSchema, invalidateCompiledValidators, isAnnotatedType, isAnnotatedTypeOfPrimitive, isPhantomType, lazyJsonSchema, localizeErrors, mergeJsonSchemas, messagesTranslator, metaEmpty, normalizeForType, pendingStatements, registerCompiledCheck, registerUserText, serializeAnnotatedType, throwFeatureDisabled, translateServed, unionDiscriminator, userTextKeys, userTextOf, watchLayer };
1529
+ export type { AtscriptExprNode, AtscriptOrderItem, AtscriptQueryComparison, AtscriptQueryFieldRef, AtscriptQueryNode, AtscriptRef, FlatOf, InferDataType, NavPropsOf, OwnPropsOf, PrimaryKeyOf, TAnnotatedTypeHandle, TAtscriptAnnotatedType, TAtscriptAnnotatedTypeConstructor, TAtscriptDataType, TAtscriptField, TAtscriptTypeArray, TAtscriptTypeComplex, TAtscriptTypeDef, TAtscriptTypeFinal, TAtscriptTypeObject, TCreateDataOptions, TError, TErrorInfo, TFlattenOptions, TJsonSchema, TJsonSchemaOptions, TMetadataMap, TProcessAnnotationContext, TSerializeOptions, TSerializedAnnotatedType, TSerializedAnnotatedTypeInner, TSerializedTypeArray, TSerializedTypeComplex, TSerializedTypeDef, TSerializedTypeFinal, TSerializedTypeObject, TUnionDiscriminator, TUserTextFields, TValidatorDiscriminator, TValidatorErrorCode, TValidatorOptions, TValidatorPlugin, TValidatorPluginContext, TValidatorTranslate, TValueResolver };