@anjianshi/utils 2.9.1 → 3.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/README.md +10 -0
- package/eslint.config.cjs +33 -0
- package/package.json +19 -10
- package/publish-prepare.cjs +16 -0
- package/src/env-browser/device.ts +62 -0
- package/src/env-browser/global.ts +21 -0
- package/src/env-browser/load-script.ts +13 -0
- package/src/env-browser/logging.ts +58 -0
- package/src/env-browser/manage-vconsole.ts +54 -0
- package/src/env-node/crypto-random.ts +30 -0
- package/src/env-node/fs.ts +50 -0
- package/src/env-node/index.ts +5 -0
- package/src/env-node/logging/handlers.ts +190 -0
- package/src/env-node/logging/index.ts +16 -0
- package/{env-react/emotion-register-globals.d.ts → src/env-react/emotion-register-globals.ts} +5 -2
- package/src/env-react/emotion.tsx +42 -0
- package/src/env-react/hooks.ts +59 -0
- package/src/env-react/index.ts +1 -0
- package/src/env-react/react-register-globals.ts +53 -0
- package/src/env-service/controllers.ts +93 -0
- package/src/env-service/env-reader.ts +141 -0
- package/src/env-service/index.ts +6 -0
- package/src/env-service/prisma/adapt-logging.ts +39 -0
- package/src/env-service/prisma/extensions/exist.ts +21 -0
- package/src/env-service/prisma/extensions/find-and-count.ts +24 -0
- package/src/env-service/prisma/extensions/soft-delete.ts +162 -0
- package/src/env-service/prisma/extensions/with-transaction.ts +65 -0
- package/src/env-service/prisma/index.ts +6 -0
- package/src/env-service/prisma/transaction-contexted.ts +80 -0
- package/src/env-service/redis-cache.ts +142 -0
- package/src/env-service/tasks.ts +45 -0
- package/src/index.ts +4 -0
- package/src/init-dayjs.ts +8 -0
- package/src/lang/async.ts +47 -0
- package/src/lang/color.ts +119 -0
- package/src/lang/index.ts +8 -0
- package/src/lang/object.ts +39 -0
- package/src/lang/random.ts +25 -0
- package/src/lang/result.ts +78 -0
- package/src/lang/string.ts +95 -0
- package/src/lang/time.ts +19 -0
- package/{lang/types.d.ts → src/lang/types.ts} +43 -23
- package/src/logging/adapt.ts +49 -0
- package/src/logging/formatters.ts +23 -0
- package/src/logging/index.ts +106 -0
- package/src/md5.ts +318 -0
- package/src/safe-request.ts +193 -0
- package/src/url.ts +185 -0
- package/src/validators/array.ts +97 -0
- package/src/validators/base.ts +145 -0
- package/src/validators/boolean.ts +21 -0
- package/src/validators/datetime.ts +39 -0
- package/src/validators/factory.ts +244 -0
- package/src/validators/index.ts +9 -0
- package/src/validators/number.ts +54 -0
- package/src/validators/object.ts +101 -0
- package/src/validators/one-of.ts +33 -0
- package/src/validators/string.ts +72 -0
- package/env-browser/device.d.ts +0 -24
- package/env-browser/device.js +0 -50
- package/env-browser/global.d.ts +0 -10
- package/env-browser/global.js +0 -15
- package/env-browser/load-script.d.ts +0 -5
- package/env-browser/load-script.js +0 -13
- package/env-browser/logging.d.ts +0 -18
- package/env-browser/logging.js +0 -49
- package/env-browser/manage-vconsole.d.ts +0 -16
- package/env-browser/manage-vconsole.js +0 -38
- package/env-node/crypto-random.d.ts +0 -13
- package/env-node/crypto-random.js +0 -28
- package/env-node/fs.d.ts +0 -19
- package/env-node/fs.js +0 -48
- package/env-node/index.d.ts +0 -6
- package/env-node/index.js +0 -6
- package/env-node/logging/handlers.d.ts +0 -58
- package/env-node/logging/handlers.js +0 -154
- package/env-node/logging/index.d.ts +0 -11
- package/env-node/logging/index.js +0 -14
- package/env-node/safe-request.d.ts +0 -26
- package/env-node/safe-request.js +0 -40
- package/env-react/emotion-register-globals.js +0 -5
- package/env-react/emotion.d.ts +0 -20
- package/env-react/emotion.jsx +0 -34
- package/env-react/hooks.d.ts +0 -4
- package/env-react/hooks.js +0 -16
- package/env-react/index.d.ts +0 -1
- package/env-react/index.js +0 -1
- package/env-react/react-register-globals.d.ts +0 -21
- package/env-react/react-register-globals.js +0 -19
- package/env-service/controllers.d.ts +0 -30
- package/env-service/controllers.js +0 -41
- package/env-service/env-reader.d.ts +0 -55
- package/env-service/env-reader.js +0 -79
- package/env-service/index.d.ts +0 -6
- package/env-service/index.js +0 -6
- package/env-service/prisma/adapt-logging.d.ts +0 -21
- package/env-service/prisma/adapt-logging.js +0 -30
- package/env-service/prisma/extensions/exist.d.ts +0 -10
- package/env-service/prisma/extensions/exist.js +0 -16
- package/env-service/prisma/extensions/find-and-count.d.ts +0 -7
- package/env-service/prisma/extensions/find-and-count.js +0 -19
- package/env-service/prisma/extensions/soft-delete.d.ts +0 -52
- package/env-service/prisma/extensions/soft-delete.js +0 -123
- package/env-service/prisma/extensions/with-transaction.d.ts +0 -9
- package/env-service/prisma/extensions/with-transaction.js +0 -54
- package/env-service/prisma/index.d.ts +0 -6
- package/env-service/prisma/index.js +0 -6
- package/env-service/prisma/transaction-contexted.d.ts +0 -11
- package/env-service/prisma/transaction-contexted.js +0 -52
- package/env-service/redis-cache.d.ts +0 -39
- package/env-service/redis-cache.js +0 -116
- package/env-service/tasks.d.ts +0 -12
- package/env-service/tasks.js +0 -37
- package/index.d.ts +0 -3
- package/index.js +0 -3
- package/init-dayjs.d.ts +0 -2
- package/init-dayjs.js +0 -7
- package/lang/async.d.ts +0 -19
- package/lang/async.js +0 -34
- package/lang/color.d.ts +0 -37
- package/lang/color.js +0 -111
- package/lang/index.d.ts +0 -8
- package/lang/index.js +0 -8
- package/lang/may-success.d.ts +0 -40
- package/lang/may-success.js +0 -27
- package/lang/object.d.ts +0 -12
- package/lang/object.js +0 -41
- package/lang/random.d.ts +0 -13
- package/lang/random.js +0 -24
- package/lang/string.d.ts +0 -29
- package/lang/string.js +0 -92
- package/lang/time.d.ts +0 -10
- package/lang/time.js +0 -18
- package/lang/types.js +0 -28
- package/logging/adapt.d.ts +0 -10
- package/logging/adapt.js +0 -43
- package/logging/formatters.d.ts +0 -10
- package/logging/formatters.js +0 -22
- package/logging/index.d.ts +0 -45
- package/logging/index.js +0 -90
- package/md5.d.ts +0 -30
- package/md5.js +0 -308
- package/url.d.ts +0 -77
- package/url.js +0 -149
- package/validators/array.d.ts +0 -30
- package/validators/array.js +0 -47
- package/validators/base.d.ts +0 -82
- package/validators/base.js +0 -42
- package/validators/boolean.d.ts +0 -3
- package/validators/boolean.js +0 -22
- package/validators/datetime.d.ts +0 -12
- package/validators/datetime.js +0 -30
- package/validators/factory.d.ts +0 -70
- package/validators/factory.js +0 -121
- package/validators/index.d.ts +0 -9
- package/validators/index.js +0 -9
- package/validators/number.d.ts +0 -19
- package/validators/number.js +0 -26
- package/validators/object.d.ts +0 -28
- package/validators/object.js +0 -49
- package/validators/one-of.d.ts +0 -10
- package/validators/one-of.js +0 -15
- package/validators/string.d.ts +0 -22
- package/validators/string.js +0 -35
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
import isPlainObject from 'lodash/isPlainObject.js'
|
|
2
|
+
import { success, failed } from '../lang/index.js'
|
|
3
|
+
import {
|
|
4
|
+
getValidatorGenerator,
|
|
5
|
+
type CommonOptions,
|
|
6
|
+
type Validator,
|
|
7
|
+
type Validated,
|
|
8
|
+
type AllowedInputValue,
|
|
9
|
+
} from './base.js'
|
|
10
|
+
|
|
11
|
+
/** 验证有明确键值对结构的对象 */
|
|
12
|
+
export interface StructOptions extends CommonOptions {
|
|
13
|
+
/** 定义对象结构,及各个值的验证规则 */
|
|
14
|
+
struct: Record<string, Validator<unknown, CommonOptions>>
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
type StructValues<Options extends StructOptions> = {
|
|
18
|
+
[Key in keyof Options['struct']]: Options['struct'][Key] extends Validator<
|
|
19
|
+
infer Value,
|
|
20
|
+
infer Options
|
|
21
|
+
>
|
|
22
|
+
? Validated<Value, Options>
|
|
23
|
+
: never
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export function getStructValidator<const Options extends StructOptions>(options: Options) {
|
|
27
|
+
return getValidatorGenerator<StructValues<Options>, Options>(
|
|
28
|
+
function validate(field, value, options) {
|
|
29
|
+
if (!isPlainObject(value)) return failed(`${field} should be a plain object`)
|
|
30
|
+
|
|
31
|
+
const formatted: Record<string, unknown> = {}
|
|
32
|
+
for (const [key, itemValidator] of Object.entries(options.struct)) {
|
|
33
|
+
const itemResult = itemValidator(
|
|
34
|
+
`${field}["${key}"]`,
|
|
35
|
+
(value as Record<string, AllowedInputValue>)[key],
|
|
36
|
+
)
|
|
37
|
+
if (itemResult.success) {
|
|
38
|
+
if (itemResult.data !== undefined) formatted[key] = itemResult.data
|
|
39
|
+
} else {
|
|
40
|
+
return itemResult
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
return success(formatted as StructValues<Options>)
|
|
44
|
+
},
|
|
45
|
+
)(options)
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
// ---------------------------------------------------
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* 验证有任意多个 key,但值的类型固定的对象
|
|
52
|
+
*/
|
|
53
|
+
export interface RecordOptions extends CommonOptions {
|
|
54
|
+
/** 验证单个值 */
|
|
55
|
+
record: Validator<unknown, CommonOptions>
|
|
56
|
+
|
|
57
|
+
/** 对象至少要有几项 */
|
|
58
|
+
min?: number
|
|
59
|
+
|
|
60
|
+
/** 对象最多有几项 */
|
|
61
|
+
max?: number
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
type RecordValues<Options extends RecordOptions> = Record<
|
|
65
|
+
string,
|
|
66
|
+
Validated<
|
|
67
|
+
Options extends { record: Validator<infer T, CommonOptions> } ? T : never,
|
|
68
|
+
Options extends { record: Validator<unknown, infer T> } ? T : never
|
|
69
|
+
>
|
|
70
|
+
>
|
|
71
|
+
|
|
72
|
+
export function getRecordValidator<Options extends RecordOptions>(options: Options) {
|
|
73
|
+
return getValidatorGenerator<RecordValues<Options>, Options>(
|
|
74
|
+
function validate(field, value, options) {
|
|
75
|
+
if (!isPlainObject(value)) return failed(`${field} should be a plain object`)
|
|
76
|
+
|
|
77
|
+
const formatted: Record<string, unknown> = {}
|
|
78
|
+
for (const [key, itemValue] of Object.entries(value as Record<string, AllowedInputValue>)) {
|
|
79
|
+
// record 场景下,值为 undefined 的项目视为不存在,不保留在验证结果里,
|
|
80
|
+
// 不然一些因为不想赋值而填充了 undefined 值的项目可能意外触发验证失败,或意外得到了默认值。
|
|
81
|
+
// (因此 validator 的 required 选项和 defaults 选项也没有意义了)
|
|
82
|
+
if (itemValue === undefined) continue
|
|
83
|
+
|
|
84
|
+
const itemResult = options.record(`${field}["${key}"]`, itemValue)
|
|
85
|
+
if (itemResult.success) {
|
|
86
|
+
if (itemResult.data !== undefined) formatted[key] = itemResult.data
|
|
87
|
+
} else {
|
|
88
|
+
return itemResult
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
const length = Object.keys(formatted).length
|
|
93
|
+
if (typeof options.min === 'number' && length < options.min)
|
|
94
|
+
return failed(`size of ${field} should >= ${options.min}`)
|
|
95
|
+
if (typeof options.max === 'number' && length > options.max)
|
|
96
|
+
return failed(`size of ${field} should <= ${options.max}`)
|
|
97
|
+
|
|
98
|
+
return success(formatted as RecordValues<Options>)
|
|
99
|
+
},
|
|
100
|
+
)(options)
|
|
101
|
+
}
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import { failed, type Result } from '../lang/index.js'
|
|
2
|
+
import {
|
|
3
|
+
getValidatorGenerator,
|
|
4
|
+
type CommonOptions,
|
|
5
|
+
type Validator,
|
|
6
|
+
type AllowedInputValue,
|
|
7
|
+
} from './base.js'
|
|
8
|
+
|
|
9
|
+
/** 要求返回值通过其中一个验证器的检查 */
|
|
10
|
+
export interface OneOfOptions extends CommonOptions {
|
|
11
|
+
/** 验证数组各元素 */
|
|
12
|
+
validators: Validator<unknown, CommonOptions>[]
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
export type OneOfValue<Options extends OneOfOptions> = Options extends {
|
|
16
|
+
validators: Validator<infer T, CommonOptions>[]
|
|
17
|
+
}
|
|
18
|
+
? T
|
|
19
|
+
: never
|
|
20
|
+
|
|
21
|
+
export function getOneOfValidator<const Options extends OneOfOptions>(
|
|
22
|
+
options: Options = {} as Options,
|
|
23
|
+
) {
|
|
24
|
+
return getValidatorGenerator<OneOfValue<Options>, Options>(function validate(field, value) {
|
|
25
|
+
const errors: string[] = []
|
|
26
|
+
for (const validator of options.validators) {
|
|
27
|
+
const result = validator(field, value as AllowedInputValue)
|
|
28
|
+
if (result.success) return result as Result<OneOfValue<Options>>
|
|
29
|
+
else errors.push(result.message)
|
|
30
|
+
}
|
|
31
|
+
return failed(`${field} do not match any valid format:\n- ` + errors.join('\n- '))
|
|
32
|
+
})(options)
|
|
33
|
+
}
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
import { success, failed } from '../lang/index.js'
|
|
2
|
+
import { getValidatorGenerator, type CommonOptions } from './base.js'
|
|
3
|
+
|
|
4
|
+
export interface StringOptions extends CommonOptions<string> {
|
|
5
|
+
/** 字符串最小长度。defaults='' 时默认为 0,否则默认为 1 */
|
|
6
|
+
min?: number
|
|
7
|
+
|
|
8
|
+
/** 字符串最大长度。 */
|
|
9
|
+
max?: number
|
|
10
|
+
|
|
11
|
+
/** 字符串需匹配此正则,也可传入关键词使用预置的正则。正则通常应以 ^ 和 $ 开头结尾。 */
|
|
12
|
+
pattern?: RegExp | 'uuid' | 'mobile'
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* 指定一个数组或 TypeScript enum,字段值必须在此 enum 之中。
|
|
16
|
+
* 若指定,前几个选项将不再生效。
|
|
17
|
+
*/
|
|
18
|
+
choices?: string[] | Record<string, string>
|
|
19
|
+
|
|
20
|
+
/** 验证之前,是否先清除两侧空白字符 @default true */
|
|
21
|
+
trim?: boolean
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export type StringValueWithChoices<Options extends StringOptions> = Options extends {
|
|
25
|
+
choices: (infer T)[]
|
|
26
|
+
}
|
|
27
|
+
? T
|
|
28
|
+
: Options extends { choices: Record<string, infer T> }
|
|
29
|
+
? T
|
|
30
|
+
: string
|
|
31
|
+
|
|
32
|
+
export function getStringValidator<const Options extends StringOptions>(
|
|
33
|
+
options: Options = {} as Options,
|
|
34
|
+
) {
|
|
35
|
+
return getValidatorGenerator<StringValueWithChoices<Options>, Options>(
|
|
36
|
+
function validate(field, value) {
|
|
37
|
+
if (typeof value !== 'string') return failed(`${field} must be a string`)
|
|
38
|
+
|
|
39
|
+
const trim = options.trim ?? true
|
|
40
|
+
const formatted = trim ? value.trim() : value
|
|
41
|
+
|
|
42
|
+
if ('choices' in options && options.choices) {
|
|
43
|
+
const validValues: string[] = Array.isArray(options.choices)
|
|
44
|
+
? options.choices
|
|
45
|
+
: Object.values(options.choices)
|
|
46
|
+
if (!validValues.includes(formatted))
|
|
47
|
+
return failed(`${field} can only be one of ${validValues.join(', ')}.`)
|
|
48
|
+
} else {
|
|
49
|
+
const { min = options.defaults === '' ? 0 : 1, max, pattern } = options
|
|
50
|
+
|
|
51
|
+
if (typeof min === 'number' && formatted.length < min)
|
|
52
|
+
return failed(`${field}'s length must >= ${min}`)
|
|
53
|
+
|
|
54
|
+
if (typeof max === 'number' && formatted.length > max)
|
|
55
|
+
return failed(`${field}'s length must <= ${max}`)
|
|
56
|
+
|
|
57
|
+
if (pattern !== undefined) {
|
|
58
|
+
if (pattern instanceof RegExp && !pattern.exec(formatted))
|
|
59
|
+
return failed(`${field} does not match the pattern`)
|
|
60
|
+
if (pattern === 'mobile' && !/^1\d{10}$/.test(formatted))
|
|
61
|
+
return failed(`${field} is not a valid mobile number`)
|
|
62
|
+
if (pattern === 'uuid') {
|
|
63
|
+
if (!/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(formatted))
|
|
64
|
+
return failed(`${field} is not a valid uuid`)
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
return success(formatted as StringValueWithChoices<Options>)
|
|
70
|
+
},
|
|
71
|
+
)(options)
|
|
72
|
+
}
|
package/env-browser/device.d.ts
DELETED
|
@@ -1,24 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* 自动计算最合适的 rem 大小,应用到页面样式上。
|
|
3
|
-
*
|
|
4
|
-
* rem 的意义是对于大屏幕,适当地同步放大界面元素,以提供更饱满的显示效果。
|
|
5
|
-
* 不过也不是所有地方都原封不动地大就好了,所以还要配合 media query 来实现最佳效果。
|
|
6
|
-
*/
|
|
7
|
-
export declare function autoRem(): void;
|
|
8
|
-
/**
|
|
9
|
-
* 当前设备是否是全面屏
|
|
10
|
-
* 页面刚加载时可能取不到 offsetHeight,因此通过一个函数而不是常量来提供此值
|
|
11
|
-
*/
|
|
12
|
-
export declare function isFullScreen(): boolean;
|
|
13
|
-
/**
|
|
14
|
-
* 当前是否是 iOS 设备
|
|
15
|
-
*/
|
|
16
|
-
export declare const isIOS: boolean;
|
|
17
|
-
/**
|
|
18
|
-
* 当前是否是移动设备
|
|
19
|
-
*/
|
|
20
|
-
export declare const isMobile: boolean;
|
|
21
|
-
/**
|
|
22
|
-
* 当前是否是微信内部浏览器
|
|
23
|
-
*/
|
|
24
|
-
export declare const isWechat: boolean;
|
package/env-browser/device.js
DELETED
|
@@ -1,50 +0,0 @@
|
|
|
1
|
-
/* eslint-disable @typescript-eslint/no-deprecated */
|
|
2
|
-
/**
|
|
3
|
-
* 自动计算最合适的 rem 大小,应用到页面样式上。
|
|
4
|
-
*
|
|
5
|
-
* rem 的意义是对于大屏幕,适当地同步放大界面元素,以提供更饱满的显示效果。
|
|
6
|
-
* 不过也不是所有地方都原封不动地大就好了,所以还要配合 media query 来实现最佳效果。
|
|
7
|
-
*/
|
|
8
|
-
export function autoRem() {
|
|
9
|
-
const resizeEvt = 'orientationchange' in window ? 'orientationchange' : 'resize';
|
|
10
|
-
/**
|
|
11
|
-
* 计算规则:
|
|
12
|
-
* - 微信标准的 375px 宽度下,1rem 为 50px(这个比例的来由是这样的:移动端通常像素比 >= 2,这个 375px 的实际渲染像素是 750px,也就是实际渲染 750px 的情况下,1rem 为 100px)。
|
|
13
|
-
* - 在平板等特大屏幕下,限制 rem 的最大值为 75px,再大就夸张了。
|
|
14
|
-
* - 竖屏时取宽度来适配 rem,横屏时取高度来适配,以保证屏幕朝向不同时,界面元素的放大比例是一致的(这应该更符合人的认知:对于一个同样大小的屏幕,无论什么朝向,上面的文字应该是一样大的)。
|
|
15
|
-
* 注意:此计算方式仅适合“不能任意调整浏览器大小的”移动设备,对于浏览器窗口可能任意尺寸、比例的桌面端,还是应该始终按照宽度来适配。
|
|
16
|
-
*
|
|
17
|
-
* 从 px 到 rem 的换算:
|
|
18
|
-
* 原 px 单位的值换算成 rem,只要除以 50 即可。例如 12px 变成 0.24rem。
|
|
19
|
-
*/
|
|
20
|
-
function updateRem() {
|
|
21
|
-
const { clientWidth, clientHeight } = document.documentElement;
|
|
22
|
-
const refSize = Math.min(clientWidth, clientHeight);
|
|
23
|
-
const rem = Math.min((refSize / 750) * 100, 75);
|
|
24
|
-
document.documentElement.style.fontSize = `${rem}px`;
|
|
25
|
-
}
|
|
26
|
-
window.addEventListener(resizeEvt, updateRem, false);
|
|
27
|
-
document.addEventListener('DOMContentLoaded', updateRem, false);
|
|
28
|
-
}
|
|
29
|
-
/**
|
|
30
|
-
* 当前设备是否是全面屏
|
|
31
|
-
* 页面刚加载时可能取不到 offsetHeight,因此通过一个函数而不是常量来提供此值
|
|
32
|
-
*/
|
|
33
|
-
export function isFullScreen() {
|
|
34
|
-
const rate = document.documentElement.offsetHeight / document.documentElement.offsetWidth;
|
|
35
|
-
const limit = window.screen.height === window.screen.availHeight ? 1.8 : 1.65; // 临界判断值
|
|
36
|
-
return rate > limit;
|
|
37
|
-
}
|
|
38
|
-
/**
|
|
39
|
-
* 当前是否是 iOS 设备
|
|
40
|
-
*/
|
|
41
|
-
export const isIOS = /iPad|iPhone|iPod/.test(navigator.userAgent);
|
|
42
|
-
/**
|
|
43
|
-
* 当前是否是移动设备
|
|
44
|
-
*/
|
|
45
|
-
export const isMobile = /(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino/i.test(navigator.userAgent || navigator.vendor) ||
|
|
46
|
-
/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw-(n|u)|c55\/|capi|ccwa|cdm-|cell|chtm|cldc|cmd-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc-s|devi|dica|dmob|do(c|p)o|ds(12|-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(-|_)|g1 u|g560|gene|gf-5|g-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd-(m|p|t)|hei-|hi(pt|ta)|hp( i|ip)|hs-c|ht(c(-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i-(20|go|ma)|i230|iac( |-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|-[a-w])|libw|lynx|m1-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|-([1-8]|c))|phil|pire|pl(ay|uc)|pn-2|po(ck|rt|se)|prox|psio|pt-g|qa-a|qc(07|12|21|32|60|-[2-7]|i-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h-|oo|p-)|sdk\/|se(c(-|0|1)|47|mc|nd|ri)|sgh-|shar|sie(-|m)|sk-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h-|v-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl-|tdg-|tel(i|m)|tim-|t-mo|to(pl|sh)|ts(70|m-|m3|m5)|tx-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas-|your|zeto|zte-/i.test((navigator.userAgent || navigator.vendor).substr(0, 4));
|
|
47
|
-
/**
|
|
48
|
-
* 当前是否是微信内部浏览器
|
|
49
|
-
*/
|
|
50
|
-
export const isWechat = /micromessenger/i.test(navigator.userAgent);
|
package/env-browser/global.d.ts
DELETED
package/env-browser/global.js
DELETED
|
@@ -1,15 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* 通过此模块注册全局变量以便于调试
|
|
3
|
-
* 变量会注册到 window.app = {} 下
|
|
4
|
-
*/
|
|
5
|
-
// web-worker 环境下不存在 window 变量,无法执行注册
|
|
6
|
-
let hasWindow = false;
|
|
7
|
-
try {
|
|
8
|
-
window.app = {};
|
|
9
|
-
hasWindow = true;
|
|
10
|
-
}
|
|
11
|
-
catch (e) { } // eslint-disable-line no-empty
|
|
12
|
-
export default function registerGlobal(key, content) {
|
|
13
|
-
if (hasWindow)
|
|
14
|
-
window.app[key] = content;
|
|
15
|
-
}
|
|
@@ -1,13 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* 加载脚本文件
|
|
3
|
-
* 返回 Promise,成功则 resolve,失败 reject
|
|
4
|
-
*/
|
|
5
|
-
export default async function loadScript(url) {
|
|
6
|
-
return new Promise((resolve, reject) => {
|
|
7
|
-
const script = document.createElement('script');
|
|
8
|
-
script.src = url;
|
|
9
|
-
script.onload = () => resolve();
|
|
10
|
-
script.onerror = err => reject(err); // eslint-disable-line @typescript-eslint/prefer-promise-reject-errors
|
|
11
|
-
window.document.head.appendChild(script);
|
|
12
|
-
});
|
|
13
|
-
}
|
package/env-browser/logging.d.ts
DELETED
|
@@ -1,18 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* 针对浏览器环境定制 logging
|
|
3
|
-
*/
|
|
4
|
-
import { type Logger, type LogInfo, LogHandler } from '../logging/index.js';
|
|
5
|
-
export * from '../logging/index.js';
|
|
6
|
-
/**
|
|
7
|
-
* 实现向浏览器 console 输出日志
|
|
8
|
-
*/
|
|
9
|
-
export declare class ConsoleHandler extends LogHandler {
|
|
10
|
-
log(info: LogInfo): void;
|
|
11
|
-
private static readonly colors;
|
|
12
|
-
private static readonly colorMap;
|
|
13
|
-
static getColor(name: string): string;
|
|
14
|
-
}
|
|
15
|
-
/**
|
|
16
|
-
* 预设的初始化行为
|
|
17
|
-
*/
|
|
18
|
-
export declare function initLogger(logger?: Logger): void;
|
package/env-browser/logging.js
DELETED
|
@@ -1,49 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* 针对浏览器环境定制 logging
|
|
3
|
-
*/
|
|
4
|
-
import { logger as defaultLogger, LogLevel, LogHandler, formatters, } from '../logging/index.js';
|
|
5
|
-
export * from '../logging/index.js';
|
|
6
|
-
/**
|
|
7
|
-
* 实现向浏览器 console 输出日志
|
|
8
|
-
*/
|
|
9
|
-
export class ConsoleHandler extends LogHandler {
|
|
10
|
-
log(info) {
|
|
11
|
-
const color = (value = 'black') => `color: ${value};`;
|
|
12
|
-
const prefix = '%c' + [formatters.time(info), info.logger].map((v) => (v ? `[${v}]` : '')).join('');
|
|
13
|
-
const prefixColor = info.logger ? color(ConsoleHandler.getColor(info.logger)) : color();
|
|
14
|
-
const values = [prefix, prefixColor, ...info.args];
|
|
15
|
-
if (info.level === LogLevel.Debug)
|
|
16
|
-
console.debug(...values);
|
|
17
|
-
else if (info.level === LogLevel.Info)
|
|
18
|
-
console.log(...values);
|
|
19
|
-
else if (info.level === LogLevel.Warning)
|
|
20
|
-
console.warn(...values);
|
|
21
|
-
else
|
|
22
|
-
console.error(...values);
|
|
23
|
-
}
|
|
24
|
-
// 按顺序给各主题分配颜色(取自 http://chriskempson.com/projects/base16/)
|
|
25
|
-
static colors = [
|
|
26
|
-
'#dc9656',
|
|
27
|
-
'#7cafc2',
|
|
28
|
-
'#ba8baf',
|
|
29
|
-
'#a16946',
|
|
30
|
-
'#ab4642',
|
|
31
|
-
'#86c1b9',
|
|
32
|
-
'#a1b56c',
|
|
33
|
-
'#f7ca88',
|
|
34
|
-
];
|
|
35
|
-
static colorMap = new Map();
|
|
36
|
-
static getColor(name) {
|
|
37
|
-
if (!ConsoleHandler.colorMap.has(name)) {
|
|
38
|
-
const nextIndex = ConsoleHandler.colorMap.size % ConsoleHandler.colors.length;
|
|
39
|
-
ConsoleHandler.colorMap.set(name, ConsoleHandler.colors[nextIndex]);
|
|
40
|
-
}
|
|
41
|
-
return ConsoleHandler.colorMap.get(name);
|
|
42
|
-
}
|
|
43
|
-
}
|
|
44
|
-
/**
|
|
45
|
-
* 预设的初始化行为
|
|
46
|
-
*/
|
|
47
|
-
export function initLogger(logger = defaultLogger) {
|
|
48
|
-
logger.addHandler(new ConsoleHandler());
|
|
49
|
-
}
|
|
@@ -1,16 +0,0 @@
|
|
|
1
|
-
import { type default as VConsole } from 'vconsole';
|
|
2
|
-
export declare function registerVConsoleLib(lib: new () => VConsole): void;
|
|
3
|
-
/**
|
|
4
|
-
* 管理 VConsole 实例
|
|
5
|
-
*/
|
|
6
|
-
declare global {
|
|
7
|
-
interface Window {
|
|
8
|
-
VConsole: VConsole | null;
|
|
9
|
-
}
|
|
10
|
-
}
|
|
11
|
-
export declare function isVConsoleEnabled(): boolean;
|
|
12
|
-
export declare function detectVConsole(): void;
|
|
13
|
-
export declare function enableVConsole(): void;
|
|
14
|
-
export declare function disableVConsole(): void;
|
|
15
|
-
export declare function runVConsole(): void;
|
|
16
|
-
export declare function destoryVConsole(): void;
|
|
@@ -1,38 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* 注册 VConsole 代码
|
|
3
|
-
* 此类库自己并不加载 VConsole,需使用者自行通过依赖或者 CDN 加载 VConsole 然后传给此类库
|
|
4
|
-
*/
|
|
5
|
-
let VConsoleLib;
|
|
6
|
-
export function registerVConsoleLib(lib) {
|
|
7
|
-
VConsoleLib = lib;
|
|
8
|
-
}
|
|
9
|
-
window.VConsole = null;
|
|
10
|
-
export function isVConsoleEnabled() {
|
|
11
|
-
return localStorage.getItem('vconsole') === '1';
|
|
12
|
-
}
|
|
13
|
-
export function detectVConsole() {
|
|
14
|
-
if (isVConsoleEnabled()) {
|
|
15
|
-
runVConsole();
|
|
16
|
-
}
|
|
17
|
-
}
|
|
18
|
-
export function enableVConsole() {
|
|
19
|
-
localStorage.setItem('vconsole', '1');
|
|
20
|
-
runVConsole();
|
|
21
|
-
}
|
|
22
|
-
export function disableVConsole() {
|
|
23
|
-
localStorage.setItem('vconsole', '0');
|
|
24
|
-
destoryVConsole();
|
|
25
|
-
}
|
|
26
|
-
export function runVConsole() {
|
|
27
|
-
if (window.VConsole !== null)
|
|
28
|
-
return;
|
|
29
|
-
if (VConsoleLib === undefined)
|
|
30
|
-
return console.warn('尚未传入 VConsole 对象,无法启动');
|
|
31
|
-
window.VConsole = new VConsoleLib();
|
|
32
|
-
}
|
|
33
|
-
export function destoryVConsole() {
|
|
34
|
-
if (!window.VConsole)
|
|
35
|
-
return;
|
|
36
|
-
window.VConsole.destroy();
|
|
37
|
-
window.VConsole = null;
|
|
38
|
-
}
|
|
@@ -1,13 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* 返回随机数,包含 min 和 max
|
|
3
|
-
*/
|
|
4
|
-
export declare function getCryptoRandomInt(min: number, max: number): number;
|
|
5
|
-
/**
|
|
6
|
-
* 返回随机字符串
|
|
7
|
-
*/
|
|
8
|
-
export declare function getCryptoRandomString(length?: number, seed?: string): string;
|
|
9
|
-
/**
|
|
10
|
-
* 从给定的选择中随机选中一项
|
|
11
|
-
* 如果数组为空,会返回 undefined
|
|
12
|
-
*/
|
|
13
|
-
export declare function cryptoChoiceRandom<T>(choices: T[]): T | undefined;
|
|
@@ -1,28 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* 类似 lang/random.ts,但基于 Node.js 的 crypto 模块,提供密码级的随机数。
|
|
3
|
-
*/
|
|
4
|
-
import crypto from 'node:crypto';
|
|
5
|
-
/**
|
|
6
|
-
* 返回随机数,包含 min 和 max
|
|
7
|
-
*/
|
|
8
|
-
export function getCryptoRandomInt(min, max) {
|
|
9
|
-
// 如果传入的 max 小于 min,把它拉到和 min 一样。不然 crypto.randomInt 无法处理
|
|
10
|
-
const fixedMax = Math.max(min, max);
|
|
11
|
-
return crypto.randomInt(min, fixedMax + 1);
|
|
12
|
-
}
|
|
13
|
-
/**
|
|
14
|
-
* 返回随机字符串
|
|
15
|
-
*/
|
|
16
|
-
export function getCryptoRandomString(length = 6, seed = '0123456789abcdefghijklmnopqrstuvwxyz') {
|
|
17
|
-
let result = '';
|
|
18
|
-
while (result.length < length)
|
|
19
|
-
result += seed[getCryptoRandomInt(0, seed.length - 1)];
|
|
20
|
-
return result;
|
|
21
|
-
}
|
|
22
|
-
/**
|
|
23
|
-
* 从给定的选择中随机选中一项
|
|
24
|
-
* 如果数组为空,会返回 undefined
|
|
25
|
-
*/
|
|
26
|
-
export function cryptoChoiceRandom(choices) {
|
|
27
|
-
return choices[getCryptoRandomInt(0, choices.length - 1)];
|
|
28
|
-
}
|
package/env-node/fs.d.ts
DELETED
|
@@ -1,19 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* 确认一个路径是否存在且是文件
|
|
3
|
-
*/
|
|
4
|
-
export declare function isFileExists(filepath: string): Promise<boolean>;
|
|
5
|
-
/**
|
|
6
|
-
* 确认一个路径是否存在且是文件夹
|
|
7
|
-
*/
|
|
8
|
-
export declare function isDirectoryExists(dirpath: string): Promise<boolean>;
|
|
9
|
-
/**
|
|
10
|
-
* 返回当前文件的绝对路径
|
|
11
|
-
* 需要传入当前文件的 ImportMeta 对象(可通过 import.meta 取得)
|
|
12
|
-
*/
|
|
13
|
-
export declare function getFilePath(fileUrl: string | ImportMeta): string;
|
|
14
|
-
/**
|
|
15
|
-
* 返回文件所处目录的绝对路径
|
|
16
|
-
*/
|
|
17
|
-
export declare function getDirectoryPath(fileUrl: string | ImportMeta): string;
|
|
18
|
-
/** 确保目录存在,如果不存在就创建(会递归创建上级目录) */
|
|
19
|
-
export declare function mkdirp(dirpath: string, mode?: number | string): Promise<void>;
|
package/env-node/fs.js
DELETED
|
@@ -1,48 +0,0 @@
|
|
|
1
|
-
import * as fs from 'node:fs';
|
|
2
|
-
import * as path from 'node:path';
|
|
3
|
-
import { fileURLToPath } from 'node:url';
|
|
4
|
-
/**
|
|
5
|
-
* 确认一个路径是否存在且是文件
|
|
6
|
-
*/
|
|
7
|
-
export async function isFileExists(filepath) {
|
|
8
|
-
try {
|
|
9
|
-
const res = await fs.promises.stat(filepath);
|
|
10
|
-
return res.isFile();
|
|
11
|
-
}
|
|
12
|
-
catch (e) {
|
|
13
|
-
return false;
|
|
14
|
-
}
|
|
15
|
-
}
|
|
16
|
-
/**
|
|
17
|
-
* 确认一个路径是否存在且是文件夹
|
|
18
|
-
*/
|
|
19
|
-
export async function isDirectoryExists(dirpath) {
|
|
20
|
-
try {
|
|
21
|
-
const res = await fs.promises.stat(dirpath);
|
|
22
|
-
return res.isDirectory();
|
|
23
|
-
}
|
|
24
|
-
catch (e) {
|
|
25
|
-
return false;
|
|
26
|
-
}
|
|
27
|
-
}
|
|
28
|
-
/**
|
|
29
|
-
* 返回当前文件的绝对路径
|
|
30
|
-
* 需要传入当前文件的 ImportMeta 对象(可通过 import.meta 取得)
|
|
31
|
-
*/
|
|
32
|
-
export function getFilePath(fileUrl) {
|
|
33
|
-
if (typeof fileUrl !== 'string')
|
|
34
|
-
fileUrl = fileUrl.url;
|
|
35
|
-
return fileURLToPath(new URL(fileUrl));
|
|
36
|
-
}
|
|
37
|
-
/**
|
|
38
|
-
* 返回文件所处目录的绝对路径
|
|
39
|
-
*/
|
|
40
|
-
export function getDirectoryPath(fileUrl) {
|
|
41
|
-
return path.dirname(getFilePath(fileUrl));
|
|
42
|
-
}
|
|
43
|
-
/** 确保目录存在,如果不存在就创建(会递归创建上级目录) */
|
|
44
|
-
export async function mkdirp(dirpath, mode) {
|
|
45
|
-
if (!(await isDirectoryExists(dirpath))) {
|
|
46
|
-
await fs.promises.mkdir(dirpath, { recursive: true, mode });
|
|
47
|
-
}
|
|
48
|
-
}
|
package/env-node/index.d.ts
DELETED
package/env-node/index.js
DELETED
|
@@ -1,58 +0,0 @@
|
|
|
1
|
-
import { type LogInfo, LogHandler } from '../../logging/index.js';
|
|
2
|
-
/**
|
|
3
|
-
* 向 console 输出日志
|
|
4
|
-
*/
|
|
5
|
-
export declare class ConsoleHandler extends LogHandler {
|
|
6
|
-
log(info: LogInfo): void;
|
|
7
|
-
static readonly consoleMethods: {
|
|
8
|
-
1: {
|
|
9
|
-
(...data: any[]): void;
|
|
10
|
-
(message?: any, ...optionalParams: any[]): void;
|
|
11
|
-
};
|
|
12
|
-
2: {
|
|
13
|
-
(...data: any[]): void;
|
|
14
|
-
(message?: any, ...optionalParams: any[]): void;
|
|
15
|
-
};
|
|
16
|
-
3: {
|
|
17
|
-
(...data: any[]): void;
|
|
18
|
-
(message?: any, ...optionalParams: any[]): void;
|
|
19
|
-
};
|
|
20
|
-
4: {
|
|
21
|
-
(...data: any[]): void;
|
|
22
|
-
(message?: any, ...optionalParams: any[]): void;
|
|
23
|
-
};
|
|
24
|
-
};
|
|
25
|
-
static readonly levelColors: {
|
|
26
|
-
1: import("chalk").ChalkInstance;
|
|
27
|
-
2: import("chalk").ChalkInstance;
|
|
28
|
-
3: import("chalk").ChalkInstance;
|
|
29
|
-
4: import("chalk").ChalkInstance;
|
|
30
|
-
};
|
|
31
|
-
private static readonly loggerColors;
|
|
32
|
-
private static readonly loggerColorMap;
|
|
33
|
-
static getLoggerColor(logger: string): "green" | "yellow" | "blue" | "cyan" | "magenta" | "greenBright" | "yellowBright" | "blueBright" | "cyanBright" | "magentaBright";
|
|
34
|
-
}
|
|
35
|
-
/**
|
|
36
|
-
* 写入文件日志
|
|
37
|
-
*/
|
|
38
|
-
export interface FileHandlerOptions {
|
|
39
|
-
dir: string;
|
|
40
|
-
filePrefix: string;
|
|
41
|
-
maxLength: number;
|
|
42
|
-
flushLength: number;
|
|
43
|
-
flushInterval: number;
|
|
44
|
-
}
|
|
45
|
-
export declare class FileHandler extends LogHandler {
|
|
46
|
-
readonly options: FileHandlerOptions;
|
|
47
|
-
constructor(options?: Partial<FileHandlerOptions>);
|
|
48
|
-
log(info: LogInfo): void;
|
|
49
|
-
protected stringifyDataItem(item: unknown): string;
|
|
50
|
-
private buffer;
|
|
51
|
-
private bufferSize;
|
|
52
|
-
private flushTimeoutId;
|
|
53
|
-
protected pushBuffer(...strings: string[]): void;
|
|
54
|
-
protected flush(sync?: boolean): void;
|
|
55
|
-
get filepath(): string;
|
|
56
|
-
protected initLogDir(): void;
|
|
57
|
-
protected write(content: string, sync?: boolean): void;
|
|
58
|
-
}
|