@naturalcycles/nodejs-lib 15.143.0 → 15.145.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.
@@ -336,6 +336,11 @@ export function createAjv(opt) {
336
336
  keyword: 'enumNames',
337
337
  schemaType: 'array',
338
338
  });
339
+ // Annotation only (the keys are validated by `properties`), registered so strict mode doesn't reject it
340
+ ajv.addKeyword({
341
+ keyword: 'enumKeys',
342
+ schemaType: 'object',
343
+ });
339
344
  // Annotation only (validated by the custom keywords, e.g `IsoDate`).
340
345
  // `true` makes Ajv skip the format check, while unknown formats would throw in strict mode.
341
346
  for (const format of jFormats) {
@@ -3,5 +3,6 @@ export * from './ajvValidationError.js';
3
3
  export * from './from-data/generateJsonSchemaFromData.js';
4
4
  export * from './getAjv.js';
5
5
  export * from './jSchema.js';
6
+ export * from './mock/generateMockFromSchema.js';
6
7
  export { jFormats, type JFormat } from './jsonSchemaBuilder.util.js';
7
8
  export { Ajv };
@@ -3,5 +3,6 @@ export * from './ajvValidationError.js';
3
3
  export * from './from-data/generateJsonSchemaFromData.js';
4
4
  export * from './getAjv.js';
5
5
  export * from './jSchema.js';
6
+ export * from './mock/generateMockFromSchema.js';
6
7
  export { jFormats } from './jsonSchemaBuilder.util.js';
7
8
  export { Ajv };
@@ -204,6 +204,15 @@ export declare class JBuilder<OUT, Opt> extends JSchema<OUT, Opt> {
204
204
  deprecated(deprecated?: boolean): this;
205
205
  type(type: string): this;
206
206
  default(v: any): this;
207
+ /**
208
+ * Gives an example of a valid input value. It is not validated.
209
+ * The example must be a plain value: `build()` does not keep class instances.
210
+ *
211
+ * ```
212
+ * const schema = j.string().regex(/^[A-Z]{3}-\d{4}$/).example('ABC-1234')
213
+ * ```
214
+ */
215
+ example(example: any): this;
207
216
  instanceof(of: string): this;
208
217
  /**
209
218
  * @param optionalValues List of values that should be considered/converted as `undefined`.
@@ -385,6 +394,22 @@ export declare class JObject<OUT extends AnyObject, Opt extends boolean = false>
385
394
  minProperties(minProperties: number): this;
386
395
  maxProperties(maxProperties: number): this;
387
396
  exclusiveProperties(propNames: readonly (keyof OUT & string)[]): this;
397
+ /**
398
+ * For an object that uses values of an enum as keys, with a different schema per key.
399
+ * Keeps the names of those keys in the built schema.
400
+ *
401
+ * ```
402
+ * const schema = j
403
+ * .object<Settings>({
404
+ * [Color.RED]: j.boolean(),
405
+ * [Color.BLUE]: j.array(j.string()),
406
+ * })
407
+ * .enumKeys(Color)
408
+ * ```
409
+ *
410
+ * When every key has the same schema, prefer `j.object.withEnumKeys`!
411
+ */
412
+ enumKeys(keyEnum: StringEnum | NumberEnum | JEnum<any, any>): this;
388
413
  }
389
414
  interface JObjectOpts {
390
415
  hasIsOfTypeCheck?: false;
@@ -437,6 +462,14 @@ declare class JSet2Builder<OUT, Opt> extends JBuilder<Set2<OUT>, Opt> {
437
462
  }
438
463
  export declare class JEnum<OUT extends string | number | boolean | null, Opt extends boolean = false> extends JBuilder<OUT, Opt> {
439
464
  constructor(enumValues: readonly OUT[], baseType: EnumBaseType, opt?: JsonBuilderRuleOpt, enumNames?: readonly string[]);
465
+ /**
466
+ * Keeps only the listed values of the enum.
467
+ *
468
+ * ```
469
+ * const schema = j.enum(Color).only([Color.RED, Color.BLUE])
470
+ * ```
471
+ */
472
+ only<const U extends OUT>(values: readonly U[]): JEnum<U, Opt>;
440
473
  branded<B extends OUT>(): JEnum<B, Opt>;
441
474
  }
442
475
  export declare class JTuple<ITEMS extends JSchema<any, any>[]> extends JBuilder<TupleOut<ITEMS>, false> {
@@ -473,6 +506,11 @@ declare function withEnumKeys<const T extends readonly (string | number)[] | Str
473
506
  } : {
474
507
  [P in K]: SchemaOut<S>;
475
508
  }, false>;
509
+ declare function withEnumKeys<K extends string | number, S extends JSchema<any, any>, Opt extends boolean = SchemaOpt<S>>(keys: JEnum<K, any>, schema: S): JObject<Opt extends true ? {
510
+ [P in `${K}`]?: SchemaOut<S>;
511
+ } : {
512
+ [P in `${K}`]: SchemaOut<S>;
513
+ }, false>;
476
514
  /**
477
515
  * On creation - compiles ajv validation function.
478
516
  * Provides convenient methods, error reporting, etc.
@@ -582,7 +620,12 @@ export interface JsonSchema<OUT = unknown> {
582
620
  additionalProperties?: boolean | JsonSchema<any>;
583
621
  minProperties?: number;
584
622
  maxProperties?: number;
585
- default?: OUT;
623
+ default?: unknown;
624
+ /**
625
+ * Examples of a valid input value.
626
+ * Annotation only (not validated), lets consumers generate e.g a mock value.
627
+ */
628
+ examples?: unknown[];
586
629
  if?: JsonSchema;
587
630
  then?: JsonSchema;
588
631
  else?: JsonSchema;
@@ -613,6 +656,11 @@ export interface JsonSchema<OUT = unknown> {
613
656
  * Annotation only (not validated), lets consumers render `1` as e.g `PREVENT`.
614
657
  */
615
658
  enumNames?: readonly string[];
659
+ /**
660
+ * The enum whose values are the keys of the object, as `j.enum` builds it. Set by `j.object.withEnumKeys`.
661
+ * Annotation only (not validated), lets consumers render the key `1` as e.g `PREVENT`.
662
+ */
663
+ enumKeys?: JsonSchema;
616
664
  hasIsOfTypeCheck?: boolean;
617
665
  email?: JsonSchemaStringEmailOptions;
618
666
  Set2?: JsonSchema;
@@ -1,4 +1,4 @@
1
- import { _isObject, _isUndefined, _numberEnumValues, _stringEnumValues, getEnumType, } from '@naturalcycles/js-lib';
1
+ import { _isObject, _isUndefined, _stringEnumValues, getEnumType } from '@naturalcycles/js-lib';
2
2
  import { _uniq } from '@naturalcycles/js-lib/array';
3
3
  import { _assert, _try } from '@naturalcycles/js-lib/error';
4
4
  import { _deepCopy, _filterNullishValues, _sortObject } from '@naturalcycles/js-lib/object';
@@ -434,6 +434,17 @@ export class JBuilder extends JSchema {
434
434
  default(v) {
435
435
  return this.cloneAndUpdateSchema({ default: v });
436
436
  }
437
+ /**
438
+ * Gives an example of a valid input value. It is not validated.
439
+ * The example must be a plain value: `build()` does not keep class instances.
440
+ *
441
+ * ```
442
+ * const schema = j.string().regex(/^[A-Z]{3}-\d{4}$/).example('ABC-1234')
443
+ * ```
444
+ */
445
+ example(example) {
446
+ return this.cloneAndUpdateSchema({ examples: [example] });
447
+ }
437
448
  instanceof(of) {
438
449
  return this.cloneAndUpdateSchema({ type: 'object', instanceof: of });
439
450
  }
@@ -630,25 +641,25 @@ export class JString extends JBuilder {
630
641
  * Expects the JWT to be signed!
631
642
  */
632
643
  jwt() {
633
- return this.regex(JWT_REGEX, { msg: 'is not a valid JWT format' });
644
+ return this.regex(JWT_REGEX, { msg: 'is not a valid JWT format' }).example('eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJ1c2VyIn0.c2lnbmF0dXJl');
634
645
  }
635
646
  url() {
636
- return this.regex(URL_REGEX, { msg: 'is not a valid URL format' });
647
+ return this.regex(URL_REGEX, { msg: 'is not a valid URL format' }).example('https://example.com');
637
648
  }
638
649
  ipv4() {
639
- return this.regex(IPV4_REGEX, { msg: 'is not a valid IPv4 format' });
650
+ return this.regex(IPV4_REGEX, { msg: 'is not a valid IPv4 format' }).example('192.0.2.1');
640
651
  }
641
652
  ipv6() {
642
- return this.regex(IPV6_REGEX, { msg: 'is not a valid IPv6 format' });
653
+ return this.regex(IPV6_REGEX, { msg: 'is not a valid IPv6 format' }).example('2001:db8::1');
643
654
  }
644
655
  slug() {
645
- return this.regex(SLUG_REGEX, { msg: 'is not a valid slug format' });
656
+ return this.regex(SLUG_REGEX, { msg: 'is not a valid slug format' }).example('my-slug');
646
657
  }
647
658
  /**
648
659
  * Validates the 3-part semver format: `major.minor.patch`, e.g `1.2.3`.
649
660
  */
650
661
  semVer() {
651
- return this.regex(SEMVER_REGEX, { msg: 'is not a valid semver format' });
662
+ return this.regex(SEMVER_REGEX, { msg: 'is not a valid semver format' }).example('1.2.3');
652
663
  }
653
664
  /**
654
665
  * Validates the 4-part version format: `major.minor.patch.build`, e.g `1.2.3.4`.
@@ -656,16 +667,24 @@ export class JString extends JBuilder {
656
667
  * Not a semver by the spec, but is used by e.g .NET and some mobile app versions.
657
668
  */
658
669
  semVer4() {
659
- return this.regex(SEMVER4_REGEX, { msg: 'is not a valid 4-part semver format' });
670
+ return this.regex(SEMVER4_REGEX, {
671
+ msg: 'is not a valid 4-part semver format',
672
+ }).example('1.2.3.4');
660
673
  }
661
674
  languageTag() {
662
- return this.regex(LANGUAGE_TAG_REGEX, { msg: 'is not a valid language format' });
675
+ return this.regex(LANGUAGE_TAG_REGEX, {
676
+ msg: 'is not a valid language format',
677
+ }).example('en-US');
663
678
  }
664
679
  countryCode() {
665
- return this.regex(COUNTRY_CODE_REGEX, { msg: 'is not a valid country code format' });
680
+ return this.regex(COUNTRY_CODE_REGEX, {
681
+ msg: 'is not a valid country code format',
682
+ }).example('US');
666
683
  }
667
684
  currency() {
668
- return this.regex(CURRENCY_REGEX, { msg: 'is not a valid currency format' });
685
+ return this.regex(CURRENCY_REGEX, {
686
+ msg: 'is not a valid currency format',
687
+ }).example('USD');
669
688
  }
670
689
  /**
671
690
  * Validates that the input is a valid IANATimzone value.
@@ -680,10 +699,10 @@ export class JString extends JBuilder {
680
699
  base64Url() {
681
700
  return this.regex(BASE64URL_REGEX, {
682
701
  msg: 'contains characters not allowed in Base64 URL characterset',
683
- });
702
+ }).example('abc-DEF_123');
684
703
  }
685
704
  uuid() {
686
- return this.regex(UUID_REGEX, { msg: 'is an invalid UUID' });
705
+ return this.regex(UUID_REGEX, { msg: 'is an invalid UUID' }).example('123e4567-e89b-12d3-a456-426614174000');
687
706
  }
688
707
  }
689
708
  export class JIsoDate extends JBuilder {
@@ -890,6 +909,28 @@ export class JObject extends JBuilder {
890
909
  const exclusiveProperties = this.schema.exclusiveProperties ?? [];
891
910
  return this.cloneAndUpdateSchema({ exclusiveProperties: [...exclusiveProperties, propNames] });
892
911
  }
912
+ /**
913
+ * For an object that uses values of an enum as keys, with a different schema per key.
914
+ * Keeps the names of those keys in the built schema.
915
+ *
916
+ * ```
917
+ * const schema = j
918
+ * .object<Settings>({
919
+ * [Color.RED]: j.boolean(),
920
+ * [Color.BLUE]: j.array(j.string()),
921
+ * })
922
+ * .enumKeys(Color)
923
+ * ```
924
+ *
925
+ * When every key has the same schema, prefer `j.object.withEnumKeys`!
926
+ */
927
+ enumKeys(keyEnum) {
928
+ const properties = this.schema.properties ?? {};
929
+ const keyEnumSchema = keyEnum instanceof JEnum ? keyEnum : j.enum(keyEnum);
930
+ const enumValues = keyEnumSchema.build().enum;
931
+ const keys = enumValues.filter(value => Object.hasOwn(properties, String(value)));
932
+ return this.cloneAndUpdateSchema({ enumKeys: keyEnumSchema.only(keys).build() });
933
+ }
893
934
  }
894
935
  export class JObjectInfer extends JBuilder {
895
936
  constructor(props) {
@@ -992,6 +1033,24 @@ export class JEnum extends JBuilder {
992
1033
  if (opt?.msg)
993
1034
  this.setErrorMessage('enum', opt.msg);
994
1035
  }
1036
+ /**
1037
+ * Keeps only the listed values of the enum.
1038
+ *
1039
+ * ```
1040
+ * const schema = j.enum(Color).only([Color.RED, Color.BLUE])
1041
+ * ```
1042
+ */
1043
+ only(values) {
1044
+ const enumValues = this.schema.enum;
1045
+ const listedValues = values;
1046
+ const unknownValues = listedValues.filter(value => !enumValues.includes(value));
1047
+ _assert(!unknownValues.length, `Values are not in the enum: ${unknownValues.join(', ')}`);
1048
+ const isListed = enumValues.map(value => listedValues.includes(value));
1049
+ return this.cloneAndUpdateSchema({
1050
+ enum: enumValues.filter((_, index) => isListed[index]),
1051
+ enumNames: this.schema.enumNames?.filter((_, index) => isListed[index]),
1052
+ });
1053
+ }
995
1054
  branded() {
996
1055
  return this;
997
1056
  }
@@ -1048,29 +1107,24 @@ function withRegexKeys(keyRegex, schema) {
1048
1107
  },
1049
1108
  });
1050
1109
  }
1051
- /**
1052
- * Builds the object schema with the indicated `keys` and uses the `schema` for their validation.
1053
- */
1054
1110
  function withEnumKeys(keys, schema) {
1055
- let enumValues;
1056
- if (Array.isArray(keys)) {
1057
- _assert(isEveryItemPrimitive(keys), 'Every item in the key list should be string, number or symbol');
1058
- enumValues = keys;
1111
+ let keyEnum;
1112
+ if (keys instanceof JEnum) {
1113
+ keyEnum = keys;
1114
+ }
1115
+ else if (Array.isArray(keys)) {
1116
+ keyEnum = j.enum(keys);
1059
1117
  }
1060
1118
  else if (typeof keys === 'object') {
1061
1119
  const enumType = getEnumType(keys);
1062
1120
  _assert(enumType === 'NumberEnum' || enumType === 'StringEnum', 'The key list should be StringEnum or NumberEnum');
1063
- if (enumType === 'NumberEnum') {
1064
- enumValues = _numberEnumValues(keys);
1065
- }
1066
- else if (enumType === 'StringEnum') {
1067
- enumValues = _stringEnumValues(keys);
1068
- }
1121
+ keyEnum = j.enum(keys);
1069
1122
  }
1070
- _assert(enumValues, 'The key list should be an array of values, NumberEnum or a StringEnum');
1071
- const typedValues = enumValues;
1072
- const props = Object.fromEntries(typedValues.map(key => [key, schema]));
1073
- return new JObject(props, { hasIsOfTypeCheck: false });
1123
+ _assert(keyEnum, 'The key list should be an array of values, NumberEnum or a StringEnum');
1124
+ const keyValues = keyEnum.build().enum;
1125
+ _assert(isEveryItemPrimitive(keyValues), 'Every item in the key list should be string, number or symbol');
1126
+ const props = Object.fromEntries(keyValues.map(key => [key, schema]));
1127
+ return new JObject(props, { hasIsOfTypeCheck: false }).enumKeys(keyEnum);
1074
1128
  }
1075
1129
  // ==== AjvSchema compat wrapper ====
1076
1130
  /**
@@ -10,6 +10,7 @@ export const JSON_SCHEMA_ORDER = [
10
10
  'writeOnly',
11
11
  'type',
12
12
  'default',
13
+ 'examples',
13
14
  // Object,
14
15
  'properties',
15
16
  'required',
@@ -58,6 +59,7 @@ export function mergeJsonSchemaObjects(schema1, schema2) {
58
59
  }
59
60
  s1.propertyNames = s2.propertyNames || s1.propertyNames;
60
61
  s1.keySchema = s2.keySchema || s1.keySchema;
62
+ s1.enumKeys = s2.enumKeys || s1.enumKeys;
61
63
  s1.minProperties = s2.minProperties ?? s1.minProperties;
62
64
  s1.maxProperties = s2.maxProperties ?? s1.maxProperties;
63
65
  // Merge `required`
@@ -0,0 +1,67 @@
1
+ import type { JSchema } from '../jSchema.js';
2
+ /**
3
+ * Generates a value that passes the schema, e.g for a mock in a test.
4
+ * Uses the example or default of a field when it has one.
5
+ * A string with a pattern needs an example or a default.
6
+ *
7
+ * ```
8
+ * const account = generateMockFromSchema(accountSchema, { allFields: true })
9
+ * ```
10
+ *
11
+ * @experimental
12
+ */
13
+ export declare function generateMockFromSchema<OUT>(schema: JSchema<OUT, any>, opt?: GenerateMockFromSchemaOptions): OUT;
14
+ /**
15
+ * Generates the mock of `generateMockFromSchema` with `allFields`, plus one variant for each other
16
+ * branch of each `j.anyOfThese` and `j.anyOfBy` union, and for each other property of each group
17
+ * of exclusive properties, so every field appears in some variant.
18
+ * `j.anyOf` and `j.oneOf` always take their first branch, since their branches add no fields.
19
+ * With `maxProperties`, only the first fields up to the limit appear,
20
+ * e.g `b` never appears for `{ a?, b? }.maxProperties(1)`. With overlapping groups of exclusive
21
+ * properties, a property shared by two groups may not appear. When an earlier `j.anyOfThese` branch
22
+ * also matches a later branch's value, validation drops the later branch's extra fields, so put the
23
+ * wider branch first.
24
+ *
25
+ * ```
26
+ * const variants = generateMockVariantsFromSchema(accountSchema)
27
+ * // [{ value }, { value, choice: { path: 'address.taxId', option: 1, key: 'mx_rfc' } }]
28
+ * ```
29
+ *
30
+ * @experimental
31
+ */
32
+ export declare function generateMockVariantsFromSchema<OUT>(schema: JSchema<OUT, any>): MockVariant<OUT>[];
33
+ /**
34
+ * @experimental
35
+ */
36
+ export interface GenerateMockFromSchemaOptions {
37
+ /**
38
+ * Fills every optional field, and puts one item in each list and one key in each map.
39
+ * Default: false, only the required fields.
40
+ */
41
+ allFields?: boolean;
42
+ }
43
+ /**
44
+ * @experimental
45
+ */
46
+ export interface MockVariant<OUT> {
47
+ value: OUT;
48
+ /**
49
+ * The choice this variant changes: a branch of a union, or a property of a group of exclusive
50
+ * properties. Absent for the first variant.
51
+ */
52
+ choice?: {
53
+ /**
54
+ * Path of the union, or of the object with the group, e.g `address.taxId`, empty at the root.
55
+ * Two unions can share a path when one is directly inside a branch of the other.
56
+ */
57
+ path: string;
58
+ /**
59
+ * Index of the branch, counting only branches that are not `null`, or of the property in the group.
60
+ */
61
+ option: number;
62
+ /**
63
+ * Key of the branch in a `j.anyOfBy` union, or the property of the group.
64
+ */
65
+ key?: string;
66
+ };
67
+ }