@atscript/typescript 0.2.4 → 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
@@ -435,6 +435,19 @@ declare class Validator<T extends TAtscriptAnnotatedType = TAtscriptAnnotatedTyp
435
435
  */
436
436
  private keptKeyCount;
437
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;
438
451
  /** Error thrown by {@link Validator.validate} when validation fails. Contains structured error details. */
439
452
  declare class ValidatorError extends Error {
440
453
  readonly errors: TError[];
@@ -674,8 +687,61 @@ declare function coerceForType(def: TAtscriptAnnotatedType, value: unknown): unk
674
687
  */
675
688
  declare function coerceScalar(designType: TAtscriptTypeFinal['designType'], value: unknown): unknown;
676
689
 
690
+ /**
691
+ * Normalizes input toward the string forms an annotated type declares with `@normalize.trim`,
692
+ * `@normalize.lowercase` and `@normalize.uppercase`.
693
+ *
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.
701
+ *
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
+ * ```
721
+ */
722
+ declare function normalizeForType<T = unknown>(def: TAtscriptAnnotatedType, value: T): T;
723
+
677
724
  /** A JSON Schema object (draft-compatible). */
678
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
+ }
679
745
  /**
680
746
  * Builds a JSON Schema from an {@link TAtscriptAnnotatedType}.
681
747
  *
@@ -691,9 +757,10 @@ type TJsonSchema = Record<string, any>;
691
757
  * ```
692
758
  *
693
759
  * @param type - The annotated type to convert.
760
+ * @param opts - {@link TJsonSchemaOptions}.
694
761
  * @returns A JSON Schema object.
695
762
  */
696
- declare function buildJsonSchema(type: TAtscriptAnnotatedType): TJsonSchema;
763
+ declare function buildJsonSchema(type: TAtscriptAnnotatedType, opts?: TJsonSchemaOptions): TJsonSchema;
697
764
  /**
698
765
  * Converts a JSON Schema object into a {@link TAtscriptAnnotatedType}.
699
766
  *
@@ -726,9 +793,10 @@ declare function fromJsonSchema(schema: TJsonSchema): TAtscriptAnnotatedType;
726
793
  * to it are renamed.
727
794
  *
728
795
  * @param types - Array of annotated types, each with an `id`.
796
+ * @param opts - {@link TJsonSchemaOptions}, for every schema.
729
797
  * @returns An object with `schemas` (keyed by id) and shared `$defs`.
730
798
  */
731
- declare function mergeJsonSchemas(types: TAtscriptAnnotatedType[]): {
799
+ declare function mergeJsonSchemas(types: TAtscriptAnnotatedType[], opts?: TJsonSchemaOptions): {
732
800
  schemas: Record<string, TJsonSchema>;
733
801
  $defs: Record<string, TJsonSchema>;
734
802
  };
@@ -743,7 +811,11 @@ declare function mergeJsonSchemas(types: TAtscriptAnnotatedType[]): {
743
811
  type TUnionDiscriminator = {
744
812
  /** Name of the discriminator property shared by all variants. */
745
813
  propertyName: string;
746
- /** Maps the literal value of `propertyName` → variant index in `items`. */
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
+ */
747
819
  indexMapping: Record<string, number>;
748
820
  };
749
821
  /**
@@ -825,16 +897,18 @@ declare function throwFeatureDisabled(feature: string, option: string, annotatio
825
897
  /**
826
898
  * The JSON schema of `type` built by the runtime (`jsonSchema: 'lazy'`): built once, again after
827
899
  * a metadata write (a block, a runtime edit: see `metadataWrites`). Called by generated code
828
- * (`static toJsonSchema()`).
900
+ * (`static toJsonSchema()`), with the `jsonSchemaOptions` of the build (the same for every call
901
+ * of a type).
829
902
  */
830
- declare function lazyJsonSchema(type: TAtscriptAnnotatedType): TJsonSchema;
903
+ declare function lazyJsonSchema(type: TAtscriptAnnotatedType, opts?: TJsonSchemaOptions): TJsonSchema;
831
904
  /**
832
905
  * The JSON schema of `type` (`jsonSchema: 'bundle'`): the
833
906
  * bundled `literal` while the modules whose blocks applied are exactly those the build accounted
834
907
  * (`modules`, the realm's applied block modules), else the runtime's (`buildJsonSchema`). Raw
835
- * 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).
836
910
  */
837
- 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;
838
912
 
839
913
  type TSite = [optional: number, mask: number, def: number, shape: string, slot: number];
840
914
  type TDef = Array<string | number | boolean | string[] | TSite | TSite[]>;
@@ -1031,6 +1105,13 @@ declare const SERIALIZE_VERSION = 2;
1031
1105
  interface TSerializedAnnotatedType extends TSerializedAnnotatedTypeInner {
1032
1106
  /** Format version for forward compatibility */
1033
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>;
1034
1115
  }
1035
1116
  /** Serialized annotated type node (used for nested types within the top-level). */
1036
1117
  interface TSerializedAnnotatedTypeInner {
@@ -1188,6 +1269,40 @@ declare function serializeAnnotatedType(type: TAtscriptAnnotatedType, options?:
1188
1269
  */
1189
1270
  declare function deserializeAnnotatedType(data: TSerializedAnnotatedType): TAtscriptAnnotatedType;
1190
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
+
1191
1306
  /**
1192
1307
  * Metadata layers: the runtime's one metadata mechanism.
1193
1308
  *
@@ -1278,24 +1393,29 @@ declare function watchLayer(m: Map<unknown, unknown>, seen?: Set<object>): boole
1278
1393
  * are registered by the generated modules that write them (`$ut`), or by the plugin itself
1279
1394
  * ({@link registerUserText}), so a translator finds them at runtime without the specs.
1280
1395
  */
1281
- /** `true`: the value itself is the text; a list: those fields of the value object are. */
1282
- type TUserTextFields = true | readonly string[];
1283
1396
  /**
1284
- * Registers metadata key `key` as holding user-facing text: `true` (default) — its value is the
1285
- * text; a list of field names — those fields of its value object are. Fields add up across calls.
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.
1286
1406
  * For plugins that write such metadata at runtime; generated modules register what they write.
1287
1407
  */
1288
1408
  declare function registerUserText(key: string, fields?: TUserTextFields): void;
1289
1409
  /**
1290
1410
  * Registers user-text keys written by a generated module (see {@link registerUserText}): `key` —
1291
- * the value itself; `key:field` — that field of the value object.
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.
1292
1413
  */
1293
1414
  declare function $ut(...entries: string[]): void;
1294
1415
  /**
1295
- * Where metadata key `key` holds user-facing text: `true` — its value is the text (a string; for
1296
- * a `multiple` annotation, each item of the list); a list of field names — those fields of its
1297
- * value object (each item's, for a list); `undefined` — no user-facing text. Core keys are known
1298
- * from the start; a plugin's once a module writing them is loaded (or the plugin registered them).
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).
1299
1419
  */
1300
1420
  declare function userTextOf(key: string): TUserTextFields | undefined;
1301
1421
  /** Every metadata key holding user-facing text known so far (see {@link userTextOf}). */
@@ -1405,5 +1525,5 @@ type NavPropsOf<T> = T extends {
1405
1525
  __navProps: infer N extends Record<string, unknown>;
1406
1526
  } ? N : Record<string, never>;
1407
1527
 
1408
- 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, pendingStatements, registerCompiledCheck, registerUserText, serializeAnnotatedType, throwFeatureDisabled, userTextKeys, userTextOf, watchLayer };
1409
- 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, TMetadataMap, TProcessAnnotationContext, TSerializeOptions, TSerializedAnnotatedType, TSerializedAnnotatedTypeInner, TSerializedTypeArray, TSerializedTypeComplex, TSerializedTypeDef, TSerializedTypeFinal, TSerializedTypeObject, TUnionDiscriminator, TUserTextFields, TValidatorErrorCode, TValidatorOptions, TValidatorPlugin, TValidatorPluginContext, TValidatorTranslate, 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 };