@strictly/define 0.0.8 → 0.0.10

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 (34) hide show
  1. package/.out/index.d.ts +2 -0
  2. package/.out/index.js +2 -0
  3. package/.out/transformers/flatteners/flatten_type_to.d.ts +1 -1
  4. package/.out/transformers/flatteners/flatten_type_to.js +1 -1
  5. package/.out/tsconfig.tsbuildinfo +1 -1
  6. package/.out/types/builders.d.ts +1 -2
  7. package/.out/types/builders.js +3 -7
  8. package/.out/validation/validator.d.ts +9 -7
  9. package/.out/validation/validator.js +6 -0
  10. package/.out/validation/validators/minimum_string_length_validator.js +1 -1
  11. package/.out/validation/validators/optional_validator_proxy.d.ts +13 -0
  12. package/.out/validation/validators/optional_validator_proxy.js +26 -0
  13. package/.out/validation/validators/regexp_validator.d.ts +29 -0
  14. package/.out/validation/validators/regexp_validator.js +37 -0
  15. package/.out/validation/validators/specs/minimum_string_length_validator.tests.d.ts +1 -0
  16. package/.out/validation/validators/specs/minimum_string_length_validator.tests.js +69 -0
  17. package/.out/validation/validators/specs/regexp_validator.tests.d.ts +1 -0
  18. package/.out/validation/validators/specs/regexp_validator.tests.js +98 -0
  19. package/.turbo/turbo-build.log +8 -8
  20. package/.turbo/turbo-check-types.log +1 -1
  21. package/dist/index.cjs +87 -8
  22. package/dist/index.d.cts +53 -10
  23. package/dist/index.d.ts +53 -10
  24. package/dist/index.js +83 -8
  25. package/index.ts +2 -0
  26. package/package.json +1 -1
  27. package/transformers/flatteners/flatten_type_to.ts +2 -2
  28. package/types/builders.ts +4 -13
  29. package/validation/validator.ts +13 -4
  30. package/validation/validators/minimum_string_length_validator.ts +1 -1
  31. package/validation/validators/optional_validator_proxy.ts +52 -0
  32. package/validation/validators/regexp_validator.ts +61 -0
  33. package/validation/validators/specs/minimum_string_length_validator.tests.ts +76 -0
  34. package/validation/validators/specs/regexp_validator.tests.ts +108 -0
package/dist/index.d.ts CHANGED
@@ -266,13 +266,14 @@ type InternalFlattenedTypeDefsOfUnionChildren<T extends ValidatingUnionTypeDef,
266
266
  readonly [K in keyof Unions]: InternalFlattenedTypeDefsOfChildren<Unions[K], SegmentOverride, Path, `${Qualifier}${K}:`, Depth>;
267
267
  }[keyof Unions]> : never : never;
268
268
 
269
+ type Annotations = {
270
+ readonly required: boolean;
271
+ readonly readonly: boolean;
272
+ };
269
273
  type FunctionalValidator<V = any, E = any, ValuePath extends string = any, Context = any> = (v: V, valuePath: ValuePath, context: Context) => E | null;
270
274
  type AnnotatedValidator<V = any, E = any, ValuePath extends string = any, Context = any> = {
271
275
  readonly validate: (v: V, valuePath: ValuePath, context: Context) => E | null;
272
- readonly annotations: (valuePath: ValuePath, context: Context) => {
273
- readonly required: boolean;
274
- readonly readonly: boolean;
275
- };
276
+ readonly annotations: (valuePath: ValuePath, context: Context) => Annotations;
276
277
  };
277
278
  type Validator<V = any, E = any, ValuePath extends string = any, Context = any> = FunctionalValidator<V, E, ValuePath, Context> | AnnotatedValidator<V, E, ValuePath, Context>;
278
279
  type ErrorOfValidator<V extends Validator> = V extends Validator<infer _V, infer E> ? E : never;
@@ -282,9 +283,10 @@ type ValidationError<Type extends string, Data = {}> = Simplify<{
282
283
  declare function isFunctionalValidator<V, E, ValuePath extends string, Context>(v: Validator<V, E, ValuePath, Context>): v is FunctionalValidator<V, E, ValuePath, Context>;
283
284
  declare function isAnnotatedValidator<V, E, ValuePath extends string, Context>(v: Validator<V, E, ValuePath, Context>): v is AnnotatedValidator<V, E, ValuePath, Context>;
284
285
  declare function validate<V = any, E = any, ValuePath extends string = any, Context = any>(validator: Validator<V, E, ValuePath, Context>, v: V, valuePath: ValuePath, context: Context): E | null;
285
- declare function annotations<V = any, E = any, ValuePath extends string = any, Context = any>(validator: Validator<V, E, ValuePath, Context>, valuePath: ValuePath, context: Context): {
286
- readonly required: boolean;
287
- readonly readonly: boolean;
286
+ declare function annotations<V = any, E = any, ValuePath extends string = any, Context = any>(validator: Validator<V, E, ValuePath, Context>, valuePath: ValuePath, context: Context): Annotations;
287
+ declare function mergeAnnotations(a1: Annotations, a2: Annotations): {
288
+ readonly: boolean;
289
+ required: boolean;
288
290
  };
289
291
 
290
292
  type ValidatorOfValidatingType<T extends ValidatingTypeDef, ValuePath extends string, Context> = T extends ValidatingTypeDef<infer E> ? Validator<ValueOfTypeDef<ReadonlyOfTypeDef<T>>, E, ValuePath, Context> : never;
@@ -403,8 +405,7 @@ declare class TypeDefBuilder<T extends ValidatingTypeDef> implements ValidatingT
403
405
  readonly definition: T;
404
406
  constructor(definition: T);
405
407
  enforce<E2>(rule: Rule<E2, ValueOfType<Type<T>>> | Validator<ValueOfType<Type<T>>, E2, never, never>): TypeDefBuilder<ValidatingTypeDefWithError<T, E2>>;
406
- required(): TypeDefBuilder<ValidatingTypeDefWithError<T, never>>;
407
- required<RequiredError>(rule: Rule<RequiredError, ValueOfType<typeof this.narrow>>): TypeDefBuilder<ValidatingTypeDefWithError<T, RequiredError>>;
408
+ required(): TypeDefBuilder<T>;
408
409
  readonly(): TypeDefBuilder<T>;
409
410
  get _type(): TypeOfType<Type<T>>;
410
411
  get narrow(): ValidatingType<T>;
@@ -545,8 +546,50 @@ declare class MinimumStringLengthValidator implements AnnotatedValidator<string,
545
546
  };
546
547
  }
547
548
 
549
+ declare class OptionalValidatorProxy<V, V1 extends V, E, ValuePath extends string, Context> implements AnnotatedValidator<V, E, ValuePath, Context> {
550
+ private readonly proxied;
551
+ private readonly isRequired;
552
+ static createNullable<V, E, ValuePath extends string, Context>(proxied: AnnotatedValidator<NonNullable<V>, E, ValuePath, Context>): OptionalValidatorProxy<V, NonNullable<V>, E, ValuePath, Context>;
553
+ static createNullableOrEmptyString<V extends string | null | undefined, E, ValuePath extends string, Context>(proxied: AnnotatedValidator<NonNullable<V>, E, ValuePath, Context>): OptionalValidatorProxy<V, NonNullable<V>, E, ValuePath, Context>;
554
+ constructor(proxied: AnnotatedValidator<V1, E, ValuePath, Context>, isRequired: (v: V) => v is V1);
555
+ validate(v: V, valuePath: ValuePath, context: Context): E | null;
556
+ annotations(valuePath: ValuePath, context: Context): {
557
+ required: boolean;
558
+ readonly: boolean;
559
+ };
560
+ }
561
+
562
+ declare const RegexpValidationErrorType = "regexp";
563
+ type RegexpValidationError<Intent extends string> = {
564
+ type: typeof RegexpValidationErrorType;
565
+ intent: Intent;
566
+ };
567
+ declare class RegexpValidator<Intent extends string> implements AnnotatedValidator<string, RegexpValidationError<Intent>, never, never> {
568
+ private readonly regexp;
569
+ private readonly intent;
570
+ /**
571
+ * Extremely permissive email validator
572
+ */
573
+ static readonly email: RegexpValidator<"email">;
574
+ /**
575
+ * Extremely permissive phone number validator
576
+ */
577
+ static readonly phone: RegexpValidator<"phone">;
578
+ private readonly negate;
579
+ private readonly required;
580
+ constructor(regexp: RegExp, intent: Intent, { negate, required, }?: {
581
+ negate?: boolean;
582
+ required?: boolean;
583
+ });
584
+ validate(value: string): RegexpValidationError<Intent> | null;
585
+ annotations(): {
586
+ required: boolean;
587
+ readonly: boolean;
588
+ };
589
+ }
590
+
548
591
  type ValidatorsOfValues<FlattenedValues extends Readonly<Record<string, any>>, TypePathsToValuePaths extends Readonly<Record<keyof FlattenedValues, string>> = Readonly<Record<keyof FlattenedValues, any>>, Context = any> = {
549
592
  readonly [K in keyof FlattenedValues]: Validator<FlattenedValues[K], any, TypePathsToValuePaths[K], Context>;
550
593
  };
551
594
 
552
- export { type Accessor, type AnnotatedValidator, type AnyValueType, DefinedValidator, type ErrorOfValidator, type FlattenedAccessorsOfType, type FlattenedTypesOfType, type FlattenedValuesOfType, type FunctionalValidator, type InternalJsonPathsOf, type IsStrictUnion, type ListTypeDef, type LiteralTypeDef, type Mapper, type MinimumStringLengthValidationError, MinimumStringLengthValidationErrorType, MinimumStringLengthValidator, type MobxObservable, type MobxValueOfType, type NonMobxObservable, type ObjectFieldKey, type ObjectTypeDef, type ObjectTypeDefFields, type PathsOfType, type ReadonlyOfTypeDef, type ReadonlyTypeOfType, type RecordKeyType, type RecordTypeDef, type Setter, type StrictListTypeDef, type StrictLiteralTypeDef, type StrictObjectTypeDef, type StrictObjectTypeDefFields, type StrictRecordTypeDef, type StrictType, type StrictTypeDef, type StrictUnionTypeDef, type Type, type TypeDef, TypeDefType, type UnionKey, type UnionTypeDef, type ValidationError, type Validator, type ValidatorsOfValues, type ValueOfType, type ValueOfTypeDef, type ValueToTypePathsOfType, type ValueTypesOfDiscriminatedUnion, annotations, booleanType, copy, flattenAccessorsOfType, flattenJsonValueToTypePathsOf, flattenTypesOfType, flattenValidatorsOfValidatingType, flattenValueTo, flattenValuesOfType, getUnionTypeDef, isAnnotatedValidator, isFunctionalValidator, jsonPath, jsonPathPop, list, literal, mobxCopy, nullType, nullable, numberType, object, record, stringType, union, validate, valuePathToTypePath };
595
+ export { type Accessor, type AnnotatedValidator, type Annotations, type AnyValueType, DefinedValidator, type ErrorOfValidator, type FlattenedAccessorsOfType, type FlattenedTypesOfType, type FlattenedValuesOfType, type FunctionalValidator, type InternalJsonPathsOf, type IsStrictUnion, type ListTypeDef, type LiteralTypeDef, type Mapper, type MinimumStringLengthValidationError, MinimumStringLengthValidationErrorType, MinimumStringLengthValidator, type MobxObservable, type MobxValueOfType, type NonMobxObservable, type ObjectFieldKey, type ObjectTypeDef, type ObjectTypeDefFields, OptionalValidatorProxy, type PathsOfType, type ReadonlyOfTypeDef, type ReadonlyTypeOfType, type RecordKeyType, type RecordTypeDef, type RegexpValidationError, RegexpValidationErrorType, RegexpValidator, type Setter, type StrictListTypeDef, type StrictLiteralTypeDef, type StrictObjectTypeDef, type StrictObjectTypeDefFields, type StrictRecordTypeDef, type StrictType, type StrictTypeDef, type StrictUnionTypeDef, type Type, type TypeDef, TypeDefType, type UnionKey, type UnionTypeDef, type ValidationError, type Validator, type ValidatorsOfValues, type ValueOfType, type ValueOfTypeDef, type ValueToTypePathsOfType, type ValueTypesOfDiscriminatedUnion, annotations, booleanType, copy, flattenAccessorsOfType, flattenJsonValueToTypePathsOf, flattenTypesOfType, flattenValidatorsOfValidatingType, flattenValueTo, flattenValuesOfType, getUnionTypeDef, isAnnotatedValidator, isFunctionalValidator, jsonPath, jsonPathPop, list, literal, mergeAnnotations, mobxCopy, nullType, nullable, numberType, object, record, stringType, union, validate, valuePathToTypePath };
package/dist/index.js CHANGED
@@ -392,7 +392,7 @@ function flattenTypeTo({ definition }, mapper2) {
392
392
  return reduce4(
393
393
  typeDefs,
394
394
  function(acc, key, typeDef) {
395
- acc[key] = mapper2(typeDef);
395
+ acc[key] = mapper2(typeDef, key);
396
396
  return acc;
397
397
  },
398
398
  // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
@@ -664,6 +664,12 @@ function annotations(validator, valuePath, context) {
664
664
  };
665
665
  }
666
666
  }
667
+ function mergeAnnotations(a1, a2) {
668
+ return {
669
+ readonly: a1.readonly || a2.readonly,
670
+ required: a1.required || a2.required
671
+ };
672
+ }
667
673
 
668
674
  // types/type_of_type.ts
669
675
  import {
@@ -758,7 +764,7 @@ var TypeDefBuilder = class _TypeDefBuilder {
758
764
  // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
759
765
  {
760
766
  ...this.definition,
761
- ...isAnnotatedValidator(rule) ? rule.annotations(null, null) : {},
767
+ ...isAnnotatedValidator(rule) ? mergeAnnotations(rule.annotations(null, null), this.definition) : {},
762
768
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
763
769
  rule: (value) => {
764
770
  return this.definition.rule(value) ?? validate(rule, value, null, null);
@@ -767,15 +773,11 @@ var TypeDefBuilder = class _TypeDefBuilder {
767
773
  }
768
774
  );
769
775
  }
770
- required(rule) {
776
+ required() {
771
777
  return new _TypeDefBuilder(
772
778
  // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
773
779
  {
774
780
  ...this.definition,
775
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
776
- rule: (v) => {
777
- return this.definition.rule(v) || rule?.(v);
778
- },
779
781
  required: true
780
782
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
781
783
  }
@@ -1017,7 +1019,76 @@ var MinimumStringLengthValidator = class {
1017
1019
  }
1018
1020
  annotations() {
1019
1021
  return {
1020
- required: true,
1022
+ required: this.minimumLength > 0,
1023
+ readonly: false
1024
+ };
1025
+ }
1026
+ };
1027
+
1028
+ // validation/validators/optional_validator_proxy.ts
1029
+ var OptionalValidatorProxy = class _OptionalValidatorProxy {
1030
+ constructor(proxied, isRequired) {
1031
+ this.proxied = proxied;
1032
+ this.isRequired = isRequired;
1033
+ }
1034
+ static createNullable(proxied) {
1035
+ return new _OptionalValidatorProxy(proxied, (v) => v != null);
1036
+ }
1037
+ static createNullableOrEmptyString(proxied) {
1038
+ return new _OptionalValidatorProxy(proxied, (v) => v != null && v !== "");
1039
+ }
1040
+ validate(v, valuePath, context) {
1041
+ if (this.isRequired(v)) {
1042
+ return this.proxied.validate(v, valuePath, context);
1043
+ }
1044
+ return null;
1045
+ }
1046
+ annotations(valuePath, context) {
1047
+ return {
1048
+ ...this.proxied.annotations(valuePath, context),
1049
+ required: false
1050
+ };
1051
+ }
1052
+ };
1053
+
1054
+ // validation/validators/regexp_validator.ts
1055
+ var RegexpValidationErrorType = "regexp";
1056
+ var RegexpValidator = class _RegexpValidator {
1057
+ constructor(regexp, intent, {
1058
+ negate = false,
1059
+ required = false
1060
+ } = {}) {
1061
+ this.regexp = regexp;
1062
+ this.intent = intent;
1063
+ this.negate = negate;
1064
+ this.required = required;
1065
+ }
1066
+ /**
1067
+ * Extremely permissive email validator
1068
+ */
1069
+ static email = new _RegexpValidator(/^[^\s@]+@[^\s@]+\.[^\s@]+$/, "email");
1070
+ /**
1071
+ * Extremely permissive phone number validator
1072
+ */
1073
+ static phone = new _RegexpValidator(
1074
+ /^(\+\d{1,4}[\s]*)?(((\([\d\s-]{1,6}\))|\d)[\s-]*){3,14}(\d|(\(\d+\)))$/,
1075
+ "phone"
1076
+ );
1077
+ negate;
1078
+ required;
1079
+ validate(value) {
1080
+ const passes = this.regexp.test(value);
1081
+ if (!passes && !this.negate || passes && this.negate) {
1082
+ return {
1083
+ type: RegexpValidationErrorType,
1084
+ intent: this.intent
1085
+ };
1086
+ }
1087
+ return null;
1088
+ }
1089
+ annotations() {
1090
+ return {
1091
+ required: this.required,
1021
1092
  readonly: false
1022
1093
  };
1023
1094
  }
@@ -1026,6 +1097,9 @@ export {
1026
1097
  DefinedValidator,
1027
1098
  MinimumStringLengthValidationErrorType,
1028
1099
  MinimumStringLengthValidator,
1100
+ OptionalValidatorProxy,
1101
+ RegexpValidationErrorType,
1102
+ RegexpValidator,
1029
1103
  TypeDefType,
1030
1104
  annotations,
1031
1105
  booleanType,
@@ -1043,6 +1117,7 @@ export {
1043
1117
  jsonPathPop,
1044
1118
  list,
1045
1119
  literal,
1120
+ mergeAnnotations,
1046
1121
  mobxCopy,
1047
1122
  nullType,
1048
1123
  nullable,
package/index.ts CHANGED
@@ -23,4 +23,6 @@ export * from './types/value_types_of_discriminated_union'
23
23
  export * from './validation/validator'
24
24
  export * from './validation/validators/defined_validator'
25
25
  export * from './validation/validators/minimum_string_length_validator'
26
+ export * from './validation/validators/optional_validator_proxy'
27
+ export * from './validation/validators/regexp_validator'
26
28
  export * from './validation/validators_of_values'
package/package.json CHANGED
@@ -35,7 +35,7 @@
35
35
  "test:watch": "vitest"
36
36
  },
37
37
  "type": "module",
38
- "version": "0.0.8",
38
+ "version": "0.0.10",
39
39
  "exports": {
40
40
  ".": {
41
41
  "import": {
@@ -18,7 +18,7 @@ import { jsonPath } from './json_path'
18
18
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
19
19
  export type AnyValueType = any
20
20
 
21
- export type Mapper<R> = (t: StrictTypeDef) => R
21
+ export type Mapper<R> = (t: StrictTypeDef, key: string) => R
22
22
 
23
23
  export function flattenTypeTo<M, R extends Readonly<Record<string, M>>>(
24
24
  { definition }: StrictType,
@@ -29,7 +29,7 @@ export function flattenTypeTo<M, R extends Readonly<Record<string, M>>>(
29
29
  return reduce(
30
30
  typeDefs,
31
31
  function (acc, key, typeDef) {
32
- acc[key] = mapper(typeDef)
32
+ acc[key] = mapper(typeDef, key)
33
33
  return acc
34
34
  },
35
35
  // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
package/types/builders.ts CHANGED
@@ -3,6 +3,7 @@ import {
3
3
  } from '@strictly/base'
4
4
  import {
5
5
  isAnnotatedValidator,
6
+ mergeAnnotations,
6
7
  validate,
7
8
  type Validator,
8
9
  } from 'validation/validator'
@@ -47,7 +48,7 @@ class TypeDefBuilder<T extends ValidatingTypeDef> implements ValidatingType<T> {
47
48
  // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
48
49
  {
49
50
  ...this.definition,
50
- ...(isAnnotatedValidator(rule) ? rule.annotations(null!, null!) : {}),
51
+ ...(isAnnotatedValidator(rule) ? mergeAnnotations(rule.annotations(null!, null!), this.definition) : {}),
51
52
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
52
53
  rule: (value: any) => {
53
54
  return this.definition.rule(value) ?? validate(rule, value, null!, null!)
@@ -57,21 +58,11 @@ class TypeDefBuilder<T extends ValidatingTypeDef> implements ValidatingType<T> {
57
58
  )
58
59
  }
59
60
 
60
- required(): TypeDefBuilder<ValidatingTypeDefWithError<T, never>>
61
- required<
62
- RequiredError,
63
- >(rule: Rule<RequiredError, ValueOfType<typeof this.narrow>>): TypeDefBuilder<
64
- ValidatingTypeDefWithError<T, RequiredError>
65
- >
66
- required<RequiredError = never>(rule?: Rule<RequiredError, ValueOfType<typeof this.narrow>>) {
67
- return new TypeDefBuilder<ValidatingTypeDefWithError<T, RequiredError>>(
61
+ required(): TypeDefBuilder<T> {
62
+ return new TypeDefBuilder<T>(
68
63
  // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
69
64
  {
70
65
  ...this.definition,
71
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
72
- rule: (v: any) => {
73
- return this.definition.rule(v) || rule?.(v)
74
- },
75
66
  required: true,
76
67
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
77
68
  } as any,
@@ -1,5 +1,10 @@
1
1
  import { type Simplify } from 'type-fest'
2
2
 
3
+ export type Annotations = {
4
+ readonly required: boolean,
5
+ readonly readonly: boolean,
6
+ }
7
+
3
8
  export type FunctionalValidator<
4
9
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
5
10
  V = any,
@@ -22,10 +27,7 @@ export type AnnotatedValidator<
22
27
  Context = any,
23
28
  > = {
24
29
  readonly validate: (v: V, valuePath: ValuePath, context: Context) => E | null,
25
- readonly annotations: (valuePath: ValuePath, context: Context) => {
26
- readonly required: boolean,
27
- readonly readonly: boolean,
28
- },
30
+ readonly annotations: (valuePath: ValuePath, context: Context) => Annotations,
29
31
  }
30
32
 
31
33
  export type Validator<
@@ -110,3 +112,10 @@ export function annotations<
110
112
  }
111
113
  }
112
114
  }
115
+
116
+ export function mergeAnnotations(a1: Annotations, a2: Annotations) {
117
+ return {
118
+ readonly: a1.readonly || a2.readonly,
119
+ required: a1.required || a2.required,
120
+ }
121
+ }
@@ -29,7 +29,7 @@ export class MinimumStringLengthValidator
29
29
 
30
30
  annotations() {
31
31
  return {
32
- required: true,
32
+ required: this.minimumLength > 0,
33
33
  readonly: false,
34
34
  }
35
35
  }
@@ -0,0 +1,52 @@
1
+ import { type AnnotatedValidator } from 'validation/validator'
2
+
3
+ export class OptionalValidatorProxy<
4
+ V,
5
+ V1 extends V,
6
+ E,
7
+ ValuePath extends string,
8
+ Context,
9
+ > implements AnnotatedValidator<
10
+ V,
11
+ E,
12
+ ValuePath,
13
+ Context
14
+ > {
15
+ static createNullable<
16
+ V,
17
+ E,
18
+ ValuePath extends string,
19
+ Context,
20
+ >(proxied: AnnotatedValidator<NonNullable<V>, E, ValuePath, Context>) {
21
+ return new OptionalValidatorProxy(proxied, (v: V) => v != null)
22
+ }
23
+
24
+ static createNullableOrEmptyString<
25
+ V extends string | null | undefined,
26
+ E,
27
+ ValuePath extends string,
28
+ Context,
29
+ >(proxied: AnnotatedValidator<NonNullable<V>, E, ValuePath, Context>) {
30
+ return new OptionalValidatorProxy(proxied, (v: V): v is NonNullable<V> => v != null && v !== '')
31
+ }
32
+
33
+ constructor(
34
+ private readonly proxied: AnnotatedValidator<V1, E, ValuePath, Context>,
35
+ private readonly isRequired: (v: V) => v is V1,
36
+ ) {
37
+ }
38
+
39
+ validate(v: V, valuePath: ValuePath, context: Context): E | null {
40
+ if (this.isRequired(v)) {
41
+ return this.proxied.validate(v, valuePath, context)
42
+ }
43
+ return null
44
+ }
45
+
46
+ annotations(valuePath: ValuePath, context: Context) {
47
+ return {
48
+ ...this.proxied.annotations(valuePath, context),
49
+ required: false,
50
+ }
51
+ }
52
+ }
@@ -0,0 +1,61 @@
1
+ import {
2
+ type AnnotatedValidator,
3
+ } from 'validation/validator'
4
+
5
+ export const RegexpValidationErrorType = 'regexp'
6
+
7
+ export type RegexpValidationError<Intent extends string> = {
8
+ type: typeof RegexpValidationErrorType,
9
+ intent: Intent,
10
+ }
11
+
12
+ export class RegexpValidator<Intent extends string>
13
+ implements AnnotatedValidator<string, RegexpValidationError<Intent>, never, never>
14
+ {
15
+ /**
16
+ * Extremely permissive email validator
17
+ */
18
+ static readonly email = new RegexpValidator(/^[^\s@]+@[^\s@]+\.[^\s@]+$/, 'email')
19
+
20
+ /**
21
+ * Extremely permissive phone number validator
22
+ */
23
+ static readonly phone = new RegexpValidator(/^(\+\d{1,4}[\s]*)?(((\([\d\s-]{1,6}\))|\d)[\s-]*){3,14}(\d|(\(\d+\)))$/,
24
+ 'phone')
25
+
26
+ private readonly negate: boolean
27
+ private readonly required: boolean
28
+
29
+ constructor(
30
+ private readonly regexp: RegExp,
31
+ private readonly intent: Intent,
32
+ {
33
+ negate = false,
34
+ required = false,
35
+ }: {
36
+ negate?: boolean,
37
+ required?: boolean,
38
+ } = {},
39
+ ) {
40
+ this.negate = negate
41
+ this.required = required
42
+ }
43
+
44
+ validate(value: string): RegexpValidationError<Intent> | null {
45
+ const passes = this.regexp.test(value)
46
+ if (!passes && !this.negate || passes && this.negate) {
47
+ return {
48
+ type: RegexpValidationErrorType,
49
+ intent: this.intent,
50
+ }
51
+ }
52
+ return null
53
+ }
54
+
55
+ annotations() {
56
+ return {
57
+ required: this.required,
58
+ readonly: false,
59
+ }
60
+ }
61
+ }
@@ -0,0 +1,76 @@
1
+ import {
2
+ MinimumStringLengthValidationErrorType,
3
+ MinimumStringLengthValidator,
4
+ } from 'validation/validators/minimum_string_length_validator'
5
+
6
+ describe('MinimumStringLengthValidator', () => {
7
+ describe('required', () => {
8
+ it.each([
9
+ 1,
10
+ 2,
11
+ 100,
12
+ ])('is required when the string length is %s', (minimumLength) => {
13
+ const validator = new MinimumStringLengthValidator(minimumLength)
14
+ expect(validator.annotations().required).toBeTruthy()
15
+ })
16
+
17
+ it('is not required when the string length is zero', () => {
18
+ const validator = new MinimumStringLengthValidator(0)
19
+ expect(validator.annotations().required).toBeFalsy()
20
+ })
21
+ })
22
+
23
+ describe('validation', () => {
24
+ it.each([
25
+ [
26
+ 1,
27
+ 'a',
28
+ ],
29
+ [
30
+ 2,
31
+ 'asdf',
32
+ ],
33
+ [
34
+ 0,
35
+ '',
36
+ ],
37
+ [
38
+ 20,
39
+ '12345678901234567890',
40
+ ],
41
+ ])('passes validation with minimum length %s and value "%s"', (minimumLength, value) => {
42
+ const validator = new MinimumStringLengthValidator(minimumLength)
43
+ expect(validator.validate(value)).toBeNull()
44
+ })
45
+
46
+ it.each([
47
+ [
48
+ 1,
49
+ '',
50
+ 0,
51
+ ],
52
+ [
53
+ 2,
54
+ 'a',
55
+ 1,
56
+ ],
57
+ [
58
+ 20,
59
+ '1234567890123456789',
60
+ 19,
61
+ ],
62
+ [
63
+ 100,
64
+ '',
65
+ 0,
66
+ ],
67
+ ])('fails validation with minimum length %s and value "%s', (minimumLength, value, receivedLength) => {
68
+ const validator = new MinimumStringLengthValidator(minimumLength)
69
+ expect(validator.validate(value)).toEqual({
70
+ type: MinimumStringLengthValidationErrorType,
71
+ minimumLength,
72
+ receivedLength,
73
+ })
74
+ })
75
+ })
76
+ })
@@ -0,0 +1,108 @@
1
+ import {
2
+ RegexpValidationErrorType,
3
+ RegexpValidator,
4
+ } from 'validation/validators/regexp_validator'
5
+
6
+ describe('RegexpValidator', () => {
7
+ describe('phone', () => {
8
+ it.each([
9
+ '0403545000',
10
+ '+12 (1800) 000 000',
11
+ '1-2-3-4-5-6',
12
+ '+1 394 3234 000 (2)',
13
+ '1234',
14
+ ])('accepts "%s"', (phoneNumber) => {
15
+ expect(RegexpValidator.phone.validate(phoneNumber)).toBeNull()
16
+ })
17
+
18
+ it.each([
19
+ '',
20
+ 'ABC',
21
+ '1',
22
+ ' 0412345678',
23
+ '----1245456',
24
+ '1 2',
25
+ '234234+234',
26
+ ])('rejects "%s"', (phoneNumber) => {
27
+ expect(RegexpValidator.phone.validate(phoneNumber)).toEqual({
28
+ type: RegexpValidationErrorType,
29
+ intent: 'phone',
30
+ })
31
+ })
32
+ })
33
+
34
+ describe('email', () => {
35
+ it.each([
36
+ 'x@y.z',
37
+ 'support@company.com',
38
+ '...@......',
39
+ '1234@3454.23',
40
+ ])('accepts "%s"', (email) => {
41
+ expect(RegexpValidator.email.validate(email)).toBeNull()
42
+ })
43
+
44
+ it.each([
45
+ '',
46
+ '@@@@',
47
+ 'email',
48
+ '@bee.com',
49
+ 'aaa@bbb',
50
+ 'a a@b b.c c',
51
+ ])('rejects "%s"', (email) => {
52
+ expect(RegexpValidator.email.validate(email)).toEqual({
53
+ type: RegexpValidationErrorType,
54
+ intent: 'email',
55
+ })
56
+ })
57
+ })
58
+
59
+ describe('required', () => {
60
+ it.each([
61
+ true,
62
+ false,
63
+ ])('exposes required %s', (required) => {
64
+ const validator = new RegexpValidator(/a/, 'test', {
65
+ required,
66
+ })
67
+ expect(validator.annotations().required).toBe(required)
68
+ })
69
+ })
70
+
71
+ describe('general', () => {
72
+ // not here to test if regexp works
73
+ it.each([
74
+ [
75
+ '^a$',
76
+ 'a',
77
+ ],
78
+ [
79
+ '^\\w+$',
80
+ 'asdf',
81
+ ],
82
+ ])('passes validation with regexp "%s" and value "%s"', (regexpString, value) => {
83
+ const regexp = new RegExp(regexpString)
84
+ const validator = new RegexpValidator(regexp, 'test')
85
+ expect(validator.validate(value)).toBeNull()
86
+ })
87
+
88
+ it.each([
89
+ [
90
+ '^$',
91
+ 'something',
92
+ 'empty',
93
+ ],
94
+ [
95
+ '^\\w+$',
96
+ '',
97
+ 'non-empty',
98
+ ],
99
+ ])('fails validation with regexp "%s" and value "%s', (regexpString, value, intent) => {
100
+ const regexp = new RegExp(regexpString)
101
+ const validator = new RegexpValidator(regexp, intent)
102
+ expect(validator.validate(value)).toEqual({
103
+ type: RegexpValidationErrorType,
104
+ intent,
105
+ })
106
+ })
107
+ })
108
+ })