@stdex/validator 0.0.0-stage → 1.0.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.
- package/LICENSE +21 -0
- package/README.md +1 -3
- package/dist/array.d.ts +30 -0
- package/dist/array.js +47 -0
- package/dist/base.d.ts +82 -0
- package/dist/base.js +42 -0
- package/dist/boolean.d.ts +3 -0
- package/dist/boolean.js +22 -0
- package/dist/datetime.d.ts +9 -0
- package/dist/datetime.js +30 -0
- package/dist/factory.d.ts +70 -0
- package/dist/factory.js +122 -0
- package/dist/index.d.ts +15 -0
- package/dist/index.js +15 -0
- package/dist/number.d.ts +19 -0
- package/dist/number.js +27 -0
- package/dist/object.d.ts +28 -0
- package/dist/object.js +49 -0
- package/dist/one-of.d.ts +10 -0
- package/dist/one-of.js +15 -0
- package/dist/string.d.ts +22 -0
- package/dist/string.js +35 -0
- package/package.json +44 -3
- package/src/array.ts +97 -0
- package/src/base.ts +145 -0
- package/src/boolean.ts +21 -0
- package/src/datetime.ts +39 -0
- package/src/factory.ts +248 -0
- package/src/index.ts +15 -0
- package/src/number.ts +55 -0
- package/src/object.ts +101 -0
- package/src/one-of.ts +33 -0
- package/src/string.ts +72 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 安坚实
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
package/dist/array.d.ts
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import { type CommonOptions, type Validator, type Validated } from './base.js';
|
|
2
|
+
/** 验证元素数量任意、元素类型相同的数组 */
|
|
3
|
+
export interface ArrayOptions extends CommonOptions {
|
|
4
|
+
/** 验证数组各元素 */
|
|
5
|
+
item: Validator<unknown, CommonOptions>;
|
|
6
|
+
/** 数组最小长度 */
|
|
7
|
+
min?: number;
|
|
8
|
+
/** 数组最大长度 */
|
|
9
|
+
max?: number;
|
|
10
|
+
/** 是否对数组元素进行去重 @defaults false */
|
|
11
|
+
unique?: boolean;
|
|
12
|
+
/** 如果传入的不是数组,是否要将其视为数组内元素,包裹成数组 */
|
|
13
|
+
toArray?: boolean;
|
|
14
|
+
}
|
|
15
|
+
type ArrayValues<Options extends ArrayOptions> = Validated<Options extends {
|
|
16
|
+
item: Validator<infer T, CommonOptions>;
|
|
17
|
+
} ? T : never, Options extends {
|
|
18
|
+
item: Validator<unknown, infer T>;
|
|
19
|
+
} ? T : never>[];
|
|
20
|
+
export declare function getArrayValidator<Options extends ArrayOptions>(options: Options): Validator<ArrayValues<Options>, Options>;
|
|
21
|
+
/** 验证元素数量固定、类型可以不同的数组 */
|
|
22
|
+
export interface TupleOptions extends CommonOptions {
|
|
23
|
+
/** 验证数组各元素(validator 与元素一一对应) */
|
|
24
|
+
tuple: Validator<unknown, CommonOptions>[];
|
|
25
|
+
}
|
|
26
|
+
type TupleValues<Options extends TupleOptions> = {
|
|
27
|
+
[Key in keyof Options['tuple']]: Options['tuple'][Key] extends Validator<infer Value, infer Options> ? Validated<Value, Options> : never;
|
|
28
|
+
};
|
|
29
|
+
export declare function getTupleValidator<const Options extends TupleOptions>(options: Options): Validator<TupleValues<Options>, Options>;
|
|
30
|
+
export {};
|
package/dist/array.js
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
import { success, failure } from '@stdex/utils/result.js';
|
|
2
|
+
import { getValidatorGenerator, } from './base.js';
|
|
3
|
+
export function getArrayValidator(options) {
|
|
4
|
+
return getValidatorGenerator(function validate(field, value, options) {
|
|
5
|
+
if (!Array.isArray(value)) {
|
|
6
|
+
if (options.toArray)
|
|
7
|
+
value = [value];
|
|
8
|
+
else
|
|
9
|
+
return failure(`${field} should be an array`);
|
|
10
|
+
}
|
|
11
|
+
let formatted = [];
|
|
12
|
+
if (typeof options.min === 'number' && value.length < options.min)
|
|
13
|
+
return failure(`array ${field}'s length should >= ${options.min}`);
|
|
14
|
+
if (typeof options.max === 'number' && value.length > options.max)
|
|
15
|
+
return failure(`array ${field}'s length should <= ${options.max}`);
|
|
16
|
+
const itemValidator = options.item;
|
|
17
|
+
for (let i = 0; i < value.length; i++) {
|
|
18
|
+
const itemResult = itemValidator(`${field}[${i}]`, value[i]);
|
|
19
|
+
if (itemResult.success)
|
|
20
|
+
formatted.push(itemResult.data);
|
|
21
|
+
else
|
|
22
|
+
return itemResult;
|
|
23
|
+
}
|
|
24
|
+
if (options.unique === true)
|
|
25
|
+
formatted = [...new Set(formatted)];
|
|
26
|
+
return success(formatted);
|
|
27
|
+
})(options);
|
|
28
|
+
}
|
|
29
|
+
export function getTupleValidator(options) {
|
|
30
|
+
return getValidatorGenerator(function validate(field, value, options) {
|
|
31
|
+
if (!Array.isArray(value))
|
|
32
|
+
return failure(`${field} should be an array`);
|
|
33
|
+
if (value.length > options.tuple.length)
|
|
34
|
+
return failure(`${field} should be a tuple with ${options.tuple.length} items`);
|
|
35
|
+
const formatted = [];
|
|
36
|
+
// 这种情况不能遍历 value,因为它的长度可能小于 opt.tuple
|
|
37
|
+
for (let i = 0; i < options.tuple.length; i++) {
|
|
38
|
+
const itemValidator = options.tuple[i];
|
|
39
|
+
const itemResult = itemValidator(`${field}[${i}]`, value[i]);
|
|
40
|
+
if (itemResult.success)
|
|
41
|
+
formatted.push(itemResult.data);
|
|
42
|
+
else
|
|
43
|
+
return itemResult;
|
|
44
|
+
}
|
|
45
|
+
return success(formatted);
|
|
46
|
+
})(options);
|
|
47
|
+
}
|
package/dist/base.d.ts
ADDED
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
import { type Result } from '@stdex/utils/result.js';
|
|
2
|
+
/**
|
|
3
|
+
* 支持传入进行验证的值类型
|
|
4
|
+
*/
|
|
5
|
+
export type AllowedInputValue = PrimitiveType | null | undefined;
|
|
6
|
+
/**
|
|
7
|
+
* JavaScript 基础值类型
|
|
8
|
+
*/
|
|
9
|
+
export type PrimitiveType = string | boolean | number | PrimitiveType[] | [...PrimitiveType[]] | {
|
|
10
|
+
[key: string]: PrimitiveType;
|
|
11
|
+
};
|
|
12
|
+
/**
|
|
13
|
+
* validator 通用参数
|
|
14
|
+
*/
|
|
15
|
+
export interface CommonOptions<Value = any> {
|
|
16
|
+
/** 是否允许 null 值 @default false */
|
|
17
|
+
null?: boolean;
|
|
18
|
+
/** 字段是否必须有值(不能是 undefined) @default true */
|
|
19
|
+
required?: boolean;
|
|
20
|
+
/**
|
|
21
|
+
* 默认值,字段无值(或值为 undefined)时生效,值为 null 不会生效。
|
|
22
|
+
* 指定后 required 选项将失去作用。
|
|
23
|
+
*/
|
|
24
|
+
defaults?: Value;
|
|
25
|
+
custom?: (input: Value) => Result<Value>;
|
|
26
|
+
[key: string]: unknown;
|
|
27
|
+
}
|
|
28
|
+
/**
|
|
29
|
+
* 补全了的 Options
|
|
30
|
+
*/
|
|
31
|
+
type FullfiledOptions<Options extends Partial<CommonOptions>> = Omit<Options, keyof CommonOptions> & {
|
|
32
|
+
null: Options['null'] extends true ? true : false;
|
|
33
|
+
required: Options['required'] extends false ? false : true;
|
|
34
|
+
defaults: Options extends {
|
|
35
|
+
defaults: infer T;
|
|
36
|
+
} ? T : undefined;
|
|
37
|
+
custom: Options extends {
|
|
38
|
+
custom: infer T;
|
|
39
|
+
} ? T : undefined;
|
|
40
|
+
};
|
|
41
|
+
/**
|
|
42
|
+
* 验证完成后能得到的值类型
|
|
43
|
+
*/
|
|
44
|
+
export type Validated<Value, InputOptions extends CommonOptions> = FullfiledOptions<InputOptions> extends {
|
|
45
|
+
defaults: undefined;
|
|
46
|
+
} ? FullfiledOptions<InputOptions> extends {
|
|
47
|
+
required: false;
|
|
48
|
+
null: false;
|
|
49
|
+
} ? Value | undefined : FullfiledOptions<InputOptions> extends {
|
|
50
|
+
required: false;
|
|
51
|
+
null: true;
|
|
52
|
+
} ? Value | undefined | null : FullfiledOptions<InputOptions> extends {
|
|
53
|
+
required: true;
|
|
54
|
+
null: false;
|
|
55
|
+
} ? Value : FullfiledOptions<InputOptions> extends {
|
|
56
|
+
required: true;
|
|
57
|
+
null: true;
|
|
58
|
+
} ? Value | null : Value : FullfiledOptions<InputOptions> extends {
|
|
59
|
+
defaults: infer T;
|
|
60
|
+
null: false;
|
|
61
|
+
} ? Value | T : FullfiledOptions<InputOptions> extends {
|
|
62
|
+
defaults: infer T;
|
|
63
|
+
null: true;
|
|
64
|
+
} ? Value | T | null : never;
|
|
65
|
+
/**
|
|
66
|
+
* 最终生成的 validator 函数类型
|
|
67
|
+
*/
|
|
68
|
+
export interface Validator<Value, InputOptions extends CommonOptions> {
|
|
69
|
+
(input: AllowedInputValue): Result<Validated<Value, InputOptions>>;
|
|
70
|
+
(field: string, input: AllowedInputValue): Result<Validated<Value, InputOptions>>;
|
|
71
|
+
}
|
|
72
|
+
/**
|
|
73
|
+
* 返回支持指定格式的 options、并按照传入的逻辑进行验证的 validator 的生成器。
|
|
74
|
+
* 对 CommonOptions 相关内容的验证以自动包含在里面,只需要传入额外的验证逻辑即可。
|
|
75
|
+
*/
|
|
76
|
+
export declare function getValidatorGenerator<Value, Options extends CommonOptions>(validate: (field: string, input: PrimitiveType | Validated<Value, Options>, options: Options) => Result<Value>): <const InputOptions extends Options>(inputOptions: InputOptions) => Validator<Value, InputOptions>;
|
|
77
|
+
/**
|
|
78
|
+
* 返回只进行基本检查,不带定制的验证逻辑的 validator。
|
|
79
|
+
* 同时也是定制 validator 最小化实现的例子。
|
|
80
|
+
*/
|
|
81
|
+
export declare const getAnyValidator: <const InputOptions extends CommonOptions<any>>(inputOptions: InputOptions) => Validator<unknown, InputOptions>;
|
|
82
|
+
export {};
|
package/dist/base.js
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import { success, failure } from '@stdex/utils/result.js';
|
|
2
|
+
// -----------------------------------
|
|
3
|
+
/**
|
|
4
|
+
* 返回支持指定格式的 options、并按照传入的逻辑进行验证的 validator 的生成器。
|
|
5
|
+
* 对 CommonOptions 相关内容的验证以自动包含在里面,只需要传入额外的验证逻辑即可。
|
|
6
|
+
*/
|
|
7
|
+
export function getValidatorGenerator(validate) {
|
|
8
|
+
return function validatorGenerator(inputOptions) {
|
|
9
|
+
function validator(field, input) {
|
|
10
|
+
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
|
|
11
|
+
const { null: allowNull = false, required = true, defaults, custom } = inputOptions;
|
|
12
|
+
if (typeof field !== 'string') {
|
|
13
|
+
input = field;
|
|
14
|
+
field = 'value';
|
|
15
|
+
}
|
|
16
|
+
let value = input;
|
|
17
|
+
if (typeof value === 'undefined') {
|
|
18
|
+
if (typeof defaults !== 'undefined') {
|
|
19
|
+
value = defaults;
|
|
20
|
+
}
|
|
21
|
+
else if (required) {
|
|
22
|
+
return failure(`${field} is required`);
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
if (value === null && !allowNull)
|
|
26
|
+
return failure(`${field} cannot be null`);
|
|
27
|
+
if (value === null || value === undefined)
|
|
28
|
+
return success(value);
|
|
29
|
+
const validated = validate(field, value, inputOptions);
|
|
30
|
+
return validated.success && custom ? custom(validated.data) : validated;
|
|
31
|
+
}
|
|
32
|
+
return validator;
|
|
33
|
+
};
|
|
34
|
+
}
|
|
35
|
+
// -----------------------------------
|
|
36
|
+
/**
|
|
37
|
+
* 返回只进行基本检查,不带定制的验证逻辑的 validator。
|
|
38
|
+
* 同时也是定制 validator 最小化实现的例子。
|
|
39
|
+
*/
|
|
40
|
+
export const getAnyValidator = getValidatorGenerator(function validate(field, input) {
|
|
41
|
+
return success(input);
|
|
42
|
+
});
|
package/dist/boolean.js
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import { success, failure } from '@stdex/utils/result.js';
|
|
2
|
+
import { getValidatorGenerator } from './base.js';
|
|
3
|
+
export const getBooleanValidator = getValidatorGenerator(function validate(field, input) {
|
|
4
|
+
let value = null;
|
|
5
|
+
if (typeof input === 'boolean') {
|
|
6
|
+
value = input;
|
|
7
|
+
}
|
|
8
|
+
else if (typeof input === 'string') {
|
|
9
|
+
const str = input.trim().toLowerCase();
|
|
10
|
+
if (['1', 'true', 'on', 'yes'].includes(str))
|
|
11
|
+
value = true;
|
|
12
|
+
else if (['0', 'false', 'off', 'no'].includes(str))
|
|
13
|
+
value = false;
|
|
14
|
+
}
|
|
15
|
+
else if (typeof input === 'number') {
|
|
16
|
+
if (input === 1)
|
|
17
|
+
value = true;
|
|
18
|
+
else if (input === 0)
|
|
19
|
+
value = false;
|
|
20
|
+
}
|
|
21
|
+
return value === null ? failure(`${field} must be true or false`) : success(value);
|
|
22
|
+
});
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import { type Dayjs } from 'dayjs';
|
|
2
|
+
import { type CommonOptions } from './base.js';
|
|
3
|
+
export interface DatetimeOptions extends CommonOptions<number> {
|
|
4
|
+
dayjs?: boolean;
|
|
5
|
+
}
|
|
6
|
+
export type DatetimeValue<Options extends DatetimeOptions> = Options extends {
|
|
7
|
+
dayjs: true;
|
|
8
|
+
} ? Dayjs : Date;
|
|
9
|
+
export declare function getDatetimeValidator<const Options extends DatetimeOptions>(options?: Options): import("./base.js").Validator<DatetimeValue<Options>, Options>;
|
package/dist/datetime.js
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 验证日期时间类型的值,依赖 dayjs
|
|
3
|
+
*/
|
|
4
|
+
import { success, failure } from '@stdex/utils/result.js';
|
|
5
|
+
import dayjs from 'dayjs';
|
|
6
|
+
import { getValidatorGenerator } from './base.js';
|
|
7
|
+
export function getDatetimeValidator(options = {}) {
|
|
8
|
+
return getValidatorGenerator(function validate(field, value) {
|
|
9
|
+
let dayjsValue;
|
|
10
|
+
if (typeof value === 'number') {
|
|
11
|
+
dayjsValue = dayjs.unix(value);
|
|
12
|
+
if (!dayjsValue.isValid())
|
|
13
|
+
return failure(`${field} must be a valid unix timestamp`);
|
|
14
|
+
}
|
|
15
|
+
else if (typeof value === 'string') {
|
|
16
|
+
dayjsValue = dayjs(value);
|
|
17
|
+
if (!dayjsValue.isValid())
|
|
18
|
+
return failure(`${field} must be a valid datetime string`);
|
|
19
|
+
}
|
|
20
|
+
else if (value instanceof Date || dayjs.isDayjs(value)) {
|
|
21
|
+
dayjsValue = dayjs(value);
|
|
22
|
+
if (!dayjsValue.isValid())
|
|
23
|
+
return failure(`${field} must be a valid Date or Dayjs object`);
|
|
24
|
+
}
|
|
25
|
+
else {
|
|
26
|
+
return failure(`${field} must be a datetime string or unix timestamp`);
|
|
27
|
+
}
|
|
28
|
+
return success((options.dayjs ? dayjsValue : dayjsValue.toDate()));
|
|
29
|
+
})(options);
|
|
30
|
+
}
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 实现创建 validator 的快捷方式
|
|
3
|
+
*/
|
|
4
|
+
import { type ArrayOptions, type TupleOptions } from './array.js';
|
|
5
|
+
import { type Validator, type CommonOptions, type Validated } from './base.js';
|
|
6
|
+
import { type BooleanOptions } from './boolean.js';
|
|
7
|
+
import { type DatetimeOptions, type DatetimeValue } from './datetime.js';
|
|
8
|
+
import { type NumberOptions, type NumberValueWithChoices } from './number.js';
|
|
9
|
+
import { type RecordOptions, type StructOptions } from './object.js';
|
|
10
|
+
import { type OneOfOptions } from './one-of.js';
|
|
11
|
+
import { type StringOptions, type StringValueWithChoices } from './string.js';
|
|
12
|
+
export interface AnyDefinition extends CommonOptions {
|
|
13
|
+
type: 'any';
|
|
14
|
+
}
|
|
15
|
+
export interface BooleanDefinition extends BooleanOptions {
|
|
16
|
+
type: 'boolean';
|
|
17
|
+
}
|
|
18
|
+
export interface NumberDefinition extends NumberOptions {
|
|
19
|
+
type: 'number';
|
|
20
|
+
}
|
|
21
|
+
export interface StringDefinition extends StringOptions {
|
|
22
|
+
type: 'string';
|
|
23
|
+
}
|
|
24
|
+
export interface DatetimeDefinition extends DatetimeOptions {
|
|
25
|
+
type: 'datetime';
|
|
26
|
+
}
|
|
27
|
+
export interface ArrayDefinition extends Omit<ArrayOptions, 'item'> {
|
|
28
|
+
type: 'array';
|
|
29
|
+
item: Definition;
|
|
30
|
+
}
|
|
31
|
+
export interface TupleDefinition extends Omit<TupleOptions, 'tuple'> {
|
|
32
|
+
type: 'tuple';
|
|
33
|
+
tuple: Definition[];
|
|
34
|
+
}
|
|
35
|
+
export interface StructDefinition extends Omit<StructOptions, 'struct'> {
|
|
36
|
+
type: 'struct';
|
|
37
|
+
struct: Record<string, Definition>;
|
|
38
|
+
}
|
|
39
|
+
export interface RecordDefinition extends Omit<RecordOptions, 'record'> {
|
|
40
|
+
type: 'record';
|
|
41
|
+
record: Definition;
|
|
42
|
+
}
|
|
43
|
+
export interface OneOfDefinition extends Omit<OneOfOptions, 'validators'> {
|
|
44
|
+
type: 'oneOf';
|
|
45
|
+
validators: Definition[];
|
|
46
|
+
}
|
|
47
|
+
export type Definition = AnyDefinition | BooleanDefinition | NumberDefinition | StringDefinition | DatetimeDefinition | ArrayDefinition | TupleDefinition | StructDefinition | RecordDefinition | OneOfDefinition;
|
|
48
|
+
export type ValueOfDefinition<Def extends Definition> = Def extends AnyDefinition ? unknown : Def extends BooleanDefinition ? boolean : Def extends NumberDefinition ? NumberValueWithChoices<Def> : Def extends StringDefinition ? StringValueWithChoices<Def> : Def extends DatetimeDefinition ? DatetimeValue<Def> : Def extends ArrayDefinition ? Validated<ValueOfDefinition<Def['item']>, Def['item']>[] : Def extends TupleDefinition ? {
|
|
49
|
+
[Key in keyof Def['tuple']]: Def['tuple'][Key] extends Definition ? Validated<ValueOfDefinition<Def['tuple'][Key]>, Def['tuple'][Key]> : Def['tuple'][Key];
|
|
50
|
+
} : Def extends StructDefinition ? {
|
|
51
|
+
[Key in keyof Def['struct']]: Validated<ValueOfDefinition<Def['struct'][Key]>, Def['struct'][Key]>;
|
|
52
|
+
} : Def extends RecordDefinition ? Record<string, Validated<ValueOfDefinition<Def['record']>, Def['record']>> : Def extends OneOfDefinition ? {
|
|
53
|
+
[Key in keyof Def['validators']]: Def['validators'][Key] extends Definition ? Validated<ValueOfDefinition<Def['validators'][Key]>, Def['validators'][Key]> : Def['validators'][Key];
|
|
54
|
+
}[number] : never;
|
|
55
|
+
export type OptionsFromDefinition<Def extends Definition> = Def extends ArrayDefinition ? Omit<Def, 'item'> & {
|
|
56
|
+
item: ValidatorForDefinition<Def['item']>;
|
|
57
|
+
} : Def extends TupleDefinition ? Omit<Def, 'tuple'> & {
|
|
58
|
+
tuple: {
|
|
59
|
+
[Key in keyof Def['tuple']]: Def['tuple'][Key] extends Definition ? ValidatorForDefinition<Def['tuple'][Key]> : never;
|
|
60
|
+
};
|
|
61
|
+
} : Def extends StructDefinition ? Omit<Def, 'struct'> & {
|
|
62
|
+
struct: {
|
|
63
|
+
[Key in keyof Def['struct']]: ValidatorForDefinition<Def['struct'][Key]>;
|
|
64
|
+
};
|
|
65
|
+
} : Def extends RecordDefinition ? Omit<Def, 'record'> & {
|
|
66
|
+
record: ValidatorForDefinition<Def['record']>;
|
|
67
|
+
} : Def;
|
|
68
|
+
export type ValidatorForDefinition<Def extends Definition> = Validator<ValueOfDefinition<Def>, OptionsFromDefinition<Def>>;
|
|
69
|
+
export type ResultForDefinition<Def extends Definition> = ReturnType<ValidatorForDefinition<Def>>;
|
|
70
|
+
export declare function getValidator<const InputDefinition extends Definition>(definition: InputDefinition): ValidatorForDefinition<InputDefinition>;
|
package/dist/factory.js
ADDED
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 实现创建 validator 的快捷方式
|
|
3
|
+
*/
|
|
4
|
+
import { getArrayValidator, getTupleValidator, } from './array.js';
|
|
5
|
+
import { getAnyValidator } from './base.js';
|
|
6
|
+
import { getBooleanValidator } from './boolean.js';
|
|
7
|
+
import { getDatetimeValidator } from './datetime.js';
|
|
8
|
+
import { getNumberValidator } from './number.js';
|
|
9
|
+
import { getRecordValidator, getStructValidator, } from './object.js';
|
|
10
|
+
import { getOneOfValidator } from './one-of.js';
|
|
11
|
+
import { getStringValidator } from './string.js';
|
|
12
|
+
export function getValidator(definition) {
|
|
13
|
+
switch (definition.type) {
|
|
14
|
+
case 'any':
|
|
15
|
+
return getAnyValidator(definition);
|
|
16
|
+
case 'boolean':
|
|
17
|
+
return getBooleanValidator(definition);
|
|
18
|
+
case 'number':
|
|
19
|
+
return getNumberValidator(definition);
|
|
20
|
+
case 'string':
|
|
21
|
+
return getStringValidator(definition);
|
|
22
|
+
case 'datetime':
|
|
23
|
+
return getDatetimeValidator(definition);
|
|
24
|
+
case 'array':
|
|
25
|
+
// @ts-ignore 允许递归类型推断
|
|
26
|
+
return getArrayValidator({
|
|
27
|
+
// @ts-ignore 允许递归类型推断
|
|
28
|
+
...definition,
|
|
29
|
+
item: getValidator(definition.item),
|
|
30
|
+
});
|
|
31
|
+
case 'tuple':
|
|
32
|
+
return getTupleValidator({
|
|
33
|
+
...definition,
|
|
34
|
+
tuple: definition.tuple.map(def => getValidator(def)),
|
|
35
|
+
});
|
|
36
|
+
case 'struct': {
|
|
37
|
+
const struct = {};
|
|
38
|
+
for (const [key, def] of Object.entries(definition.struct))
|
|
39
|
+
struct[key] = getValidator(def);
|
|
40
|
+
// @ts-ignore 允许递归类型推断
|
|
41
|
+
return getStructValidator({ ...definition, struct });
|
|
42
|
+
}
|
|
43
|
+
case 'record':
|
|
44
|
+
return getRecordValidator({
|
|
45
|
+
...definition,
|
|
46
|
+
record: getValidator(definition.record),
|
|
47
|
+
});
|
|
48
|
+
case 'oneOf':
|
|
49
|
+
return getOneOfValidator({
|
|
50
|
+
...definition,
|
|
51
|
+
validators: definition.validators.map(def => getValidator(def)),
|
|
52
|
+
});
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
// ---------------- 测试用例 -----------------
|
|
56
|
+
// const v1 = getValidator({ type: 'string' })(1)
|
|
57
|
+
// const v2 = getValidator({ type: 'string', null: true })(1)
|
|
58
|
+
// const v3 = getValidator({ type: 'string', null: true, required: false })(1)
|
|
59
|
+
// const v4 = getValidator({ type: 'string', null: true, required: false, choices: ['a', 'b', 'c'] })(
|
|
60
|
+
// 1,
|
|
61
|
+
// )
|
|
62
|
+
// const v5 = getValidator({
|
|
63
|
+
// type: 'string',
|
|
64
|
+
// null: true,
|
|
65
|
+
// required: false,
|
|
66
|
+
// choices: ['a', 'b', 'c'],
|
|
67
|
+
// defaults: 'd',
|
|
68
|
+
// })(1)
|
|
69
|
+
// const v6 = getValidator({
|
|
70
|
+
// type: 'array',
|
|
71
|
+
// null: true,
|
|
72
|
+
// required: false,
|
|
73
|
+
// item: { type: 'string', null: true, choices: ['a', 'b', 'c'] },
|
|
74
|
+
// })(1)
|
|
75
|
+
// const v7 = getValidator({
|
|
76
|
+
// type: 'tuple',
|
|
77
|
+
// tuple: [
|
|
78
|
+
// { type: 'string', choices: ['a', 'b', 'c'] },
|
|
79
|
+
// { type: 'string', null: true },
|
|
80
|
+
// ],
|
|
81
|
+
// })(1)
|
|
82
|
+
// if (v7.success) {
|
|
83
|
+
// const [a, b] = v7.data
|
|
84
|
+
// }
|
|
85
|
+
// const v8 = getValidator({
|
|
86
|
+
// type: 'struct',
|
|
87
|
+
// struct: {
|
|
88
|
+
// x: { type: 'string', choices: ['a', 'b', 'c'] },
|
|
89
|
+
// y: { type: 'string', null: true },
|
|
90
|
+
// },
|
|
91
|
+
// })(1)
|
|
92
|
+
// if (v8.success) {
|
|
93
|
+
// const { x, y } = v8.data
|
|
94
|
+
// }
|
|
95
|
+
// const v9 = getValidator({
|
|
96
|
+
// type: 'record',
|
|
97
|
+
// record: { type: 'string', null: true, choices: ['a', 'b', 'c'] },
|
|
98
|
+
// })(1)
|
|
99
|
+
// const v10 = getValidator({
|
|
100
|
+
// type: 'oneOf',
|
|
101
|
+
// validators: [
|
|
102
|
+
// { type: 'string', choices: ['a', 'b', 'c'] },
|
|
103
|
+
// { type: 'number', null: true },
|
|
104
|
+
// ],
|
|
105
|
+
// defaults: true,
|
|
106
|
+
// })(1)
|
|
107
|
+
// const v11 = getValidator({
|
|
108
|
+
// type: 'string',
|
|
109
|
+
// custom(value) {
|
|
110
|
+
// return { success: true, data: value }
|
|
111
|
+
// },
|
|
112
|
+
// defaults: 'some text',
|
|
113
|
+
// })(1)
|
|
114
|
+
// const v12 = getValidator({
|
|
115
|
+
// type: 'datetime',
|
|
116
|
+
// null: true,
|
|
117
|
+
// required: false,
|
|
118
|
+
// })(1)
|
|
119
|
+
// const v13 = getValidator({
|
|
120
|
+
// type: 'datetime',
|
|
121
|
+
// raw: true,
|
|
122
|
+
// })(1)
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 通用验证器实现
|
|
3
|
+
*
|
|
4
|
+
* 使用前提:
|
|
5
|
+
* - 因为涉及时间对象解析,需安装 dayjs 依赖
|
|
6
|
+
*/
|
|
7
|
+
export * from './base.js';
|
|
8
|
+
export * from './boolean.js';
|
|
9
|
+
export * from './number.js';
|
|
10
|
+
export * from './string.js';
|
|
11
|
+
export * from './datetime.js';
|
|
12
|
+
export * from './array.js';
|
|
13
|
+
export * from './object.js';
|
|
14
|
+
export * from './one-of.js';
|
|
15
|
+
export * from './factory.js';
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 通用验证器实现
|
|
3
|
+
*
|
|
4
|
+
* 使用前提:
|
|
5
|
+
* - 因为涉及时间对象解析,需安装 dayjs 依赖
|
|
6
|
+
*/
|
|
7
|
+
export * from './base.js';
|
|
8
|
+
export * from './boolean.js';
|
|
9
|
+
export * from './number.js';
|
|
10
|
+
export * from './string.js';
|
|
11
|
+
export * from './datetime.js';
|
|
12
|
+
export * from './array.js';
|
|
13
|
+
export * from './object.js';
|
|
14
|
+
export * from './one-of.js';
|
|
15
|
+
export * from './factory.js';
|
package/dist/number.d.ts
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import { type CommonOptions } from './base.js';
|
|
2
|
+
export interface NumberOptions extends CommonOptions<number> {
|
|
3
|
+
/** 数值最小值 */
|
|
4
|
+
min?: number;
|
|
5
|
+
/** 数值最大值 */
|
|
6
|
+
max?: number;
|
|
7
|
+
/** 是否允许小数 @default false */
|
|
8
|
+
float?: boolean;
|
|
9
|
+
/**
|
|
10
|
+
* 指定可选值
|
|
11
|
+
* 若指定,前几个选项将不再生效 */
|
|
12
|
+
choices?: number[] | Record<number, string>;
|
|
13
|
+
}
|
|
14
|
+
export type NumberValueWithChoices<Options extends NumberOptions> = Options extends {
|
|
15
|
+
choices: (infer T)[];
|
|
16
|
+
} ? T : Options extends {
|
|
17
|
+
choices: Record<number, string>;
|
|
18
|
+
} ? Options['choices'][keyof Options['choices']] : number;
|
|
19
|
+
export declare function getNumberValidator<const Options extends NumberOptions>(options?: Options): import("./base.js").Validator<NumberValueWithChoices<Options>, Options>;
|
package/dist/number.js
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import { success, failure } from '@stdex/utils/result.js';
|
|
2
|
+
import { truthy } from '@stdex/utils/types.js';
|
|
3
|
+
import { getValidatorGenerator } from './base.js';
|
|
4
|
+
export function getNumberValidator(options = {}) {
|
|
5
|
+
return getValidatorGenerator(function validate(field, value) {
|
|
6
|
+
if (typeof value === 'string')
|
|
7
|
+
value = parseFloat(value);
|
|
8
|
+
if (typeof value !== 'number' || !isFinite(value))
|
|
9
|
+
return failure(`${field} must be a valid number`);
|
|
10
|
+
if ('choices' in options && options.choices) {
|
|
11
|
+
const choices = Array.isArray(options.choices)
|
|
12
|
+
? options.choices
|
|
13
|
+
: Object.values(options.choices).map(v => parseInt(v, 10));
|
|
14
|
+
if (!choices.includes(value))
|
|
15
|
+
return failure(`${field} can only be one of ${choices.join(', ')}.`);
|
|
16
|
+
}
|
|
17
|
+
else {
|
|
18
|
+
if (!truthy(options.float) && value % 1 !== 0)
|
|
19
|
+
return failure(`${field} must be a integer`);
|
|
20
|
+
if (typeof options.min === 'number' && value < options.min)
|
|
21
|
+
return failure(`${field} must >= ${options.min}`);
|
|
22
|
+
if (typeof options.max === 'number' && value > options.max)
|
|
23
|
+
return failure(`${field} must <= ${options.max}`);
|
|
24
|
+
}
|
|
25
|
+
return success(value);
|
|
26
|
+
})(options);
|
|
27
|
+
}
|
package/dist/object.d.ts
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import { type CommonOptions, type Validator, type Validated } from './base.js';
|
|
2
|
+
/** 验证有明确键值对结构的对象 */
|
|
3
|
+
export interface StructOptions extends CommonOptions {
|
|
4
|
+
/** 定义对象结构,及各个值的验证规则 */
|
|
5
|
+
struct: Record<string, Validator<unknown, CommonOptions>>;
|
|
6
|
+
}
|
|
7
|
+
type StructValues<Options extends StructOptions> = {
|
|
8
|
+
[Key in keyof Options['struct']]: Options['struct'][Key] extends Validator<infer Value, infer Options> ? Validated<Value, Options> : never;
|
|
9
|
+
};
|
|
10
|
+
export declare function getStructValidator<const Options extends StructOptions>(options: Options): Validator<StructValues<Options>, Options>;
|
|
11
|
+
/**
|
|
12
|
+
* 验证有任意多个 key,但值的类型固定的对象
|
|
13
|
+
*/
|
|
14
|
+
export interface RecordOptions extends CommonOptions {
|
|
15
|
+
/** 验证单个值 */
|
|
16
|
+
record: Validator<unknown, CommonOptions>;
|
|
17
|
+
/** 对象至少要有几项 */
|
|
18
|
+
min?: number;
|
|
19
|
+
/** 对象最多有几项 */
|
|
20
|
+
max?: number;
|
|
21
|
+
}
|
|
22
|
+
type RecordValues<Options extends RecordOptions> = Record<string, Validated<Options extends {
|
|
23
|
+
record: Validator<infer T, CommonOptions>;
|
|
24
|
+
} ? T : never, Options extends {
|
|
25
|
+
record: Validator<unknown, infer T>;
|
|
26
|
+
} ? T : never>>;
|
|
27
|
+
export declare function getRecordValidator<Options extends RecordOptions>(options: Options): Validator<RecordValues<Options>, Options>;
|
|
28
|
+
export {};
|
package/dist/object.js
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
import { success, failure } from '@stdex/utils/result.js';
|
|
2
|
+
import isPlainObject from 'lodash/isPlainObject.js';
|
|
3
|
+
import { getValidatorGenerator, } from './base.js';
|
|
4
|
+
export function getStructValidator(options) {
|
|
5
|
+
return getValidatorGenerator(function validate(field, value, options) {
|
|
6
|
+
if (!isPlainObject(value))
|
|
7
|
+
return failure(`${field} should be a plain object`);
|
|
8
|
+
const formatted = {};
|
|
9
|
+
for (const [key, itemValidator] of Object.entries(options.struct)) {
|
|
10
|
+
const itemResult = itemValidator(`${field}["${key}"]`, value[key]);
|
|
11
|
+
if (itemResult.success) {
|
|
12
|
+
if (itemResult.data !== undefined)
|
|
13
|
+
formatted[key] = itemResult.data;
|
|
14
|
+
}
|
|
15
|
+
else {
|
|
16
|
+
return itemResult;
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
return success(formatted);
|
|
20
|
+
})(options);
|
|
21
|
+
}
|
|
22
|
+
export function getRecordValidator(options) {
|
|
23
|
+
return getValidatorGenerator(function validate(field, value, options) {
|
|
24
|
+
if (!isPlainObject(value))
|
|
25
|
+
return failure(`${field} should be a plain object`);
|
|
26
|
+
const formatted = {};
|
|
27
|
+
for (const [key, itemValue] of Object.entries(value)) {
|
|
28
|
+
// record 场景下,值为 undefined 的项目视为不存在,不保留在验证结果里,
|
|
29
|
+
// 不然一些因为不想赋值而填充了 undefined 值的项目可能意外触发验证失败,或意外得到了默认值。
|
|
30
|
+
// (因此 validator 的 required 选项和 defaults 选项也没有意义了)
|
|
31
|
+
if (itemValue === undefined)
|
|
32
|
+
continue;
|
|
33
|
+
const itemResult = options.record(`${field}["${key}"]`, itemValue);
|
|
34
|
+
if (itemResult.success) {
|
|
35
|
+
if (itemResult.data !== undefined)
|
|
36
|
+
formatted[key] = itemResult.data;
|
|
37
|
+
}
|
|
38
|
+
else {
|
|
39
|
+
return itemResult;
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
const length = Object.keys(formatted).length;
|
|
43
|
+
if (typeof options.min === 'number' && length < options.min)
|
|
44
|
+
return failure(`size of ${field} should >= ${options.min}`);
|
|
45
|
+
if (typeof options.max === 'number' && length > options.max)
|
|
46
|
+
return failure(`size of ${field} should <= ${options.max}`);
|
|
47
|
+
return success(formatted);
|
|
48
|
+
})(options);
|
|
49
|
+
}
|