@zwa73/utils 1.0.79 → 1.0.81

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 (45) hide show
  1. package/{test/test.js → backup/repeatPromise.test.ts} +0 -1
  2. package/compile.bat +2 -0
  3. package/dist/QuickFunction.d.ts +2 -15
  4. package/dist/QuickFunction.js +21 -19
  5. package/dist/UtilCodecs.js +1 -1
  6. package/dist/UtilCom.js +1 -1
  7. package/dist/UtilDecorators.d.ts +1 -1
  8. package/dist/UtilDecorators.js +4 -3
  9. package/dist/UtilFP.js +1 -1
  10. package/dist/UtilFileTools.js +1 -1
  11. package/dist/UtilFunctions.d.ts +65 -18
  12. package/dist/UtilFunctions.js +143 -31
  13. package/dist/UtilInterfaces.d.ts +25 -15
  14. package/dist/UtilSymbol.d.ts +31 -9
  15. package/dist/UtilSymbol.js +23 -8
  16. package/dist/test/repeatTest.js +1 -1
  17. package/dist/test/test.js +16 -16
  18. package/jest/UtilFunction/queueProc.test.ts +23 -0
  19. package/jest/UtilFunction/repeatPromise.test.ts +38 -0
  20. package/jest/jest.test.ts +46 -0
  21. package/jest.config.js +16 -0
  22. package/package.json +12 -5
  23. package/release.bat +3 -4
  24. package/{postinstall.js → scripts/postinstall.js} +2 -2
  25. package/src/QuickFunction.ts +47 -27
  26. package/src/UtilDecorators.ts +3 -1
  27. package/src/UtilFunctions.ts +185 -46
  28. package/src/UtilInterfaces.ts +55 -13
  29. package/src/UtilSymbol.ts +37 -10
  30. package/src/test/repeatTest.ts +2 -2
  31. package/test.bat +1 -1
  32. package/tsconfig.compile.json +4 -0
  33. package/tsconfig.json +3 -2
  34. package/watch.bat +1 -0
  35. package/test/test.bat +0 -2
  36. package/testAndCompile.bat +0 -4
  37. package/tsCompile.bat +0 -3
  38. package/tsCompileWatch.bat +0 -2
  39. /package/{test.js → backup/SLogger.test.ts} +0 -0
  40. /package/{req_test → backup/req_test}/cjsRmjs.bat +0 -0
  41. /package/{req_test → backup/req_test}/cjsRmjs.cjs +0 -0
  42. /package/{req_test → backup/req_test}/mjsRcjs.bat +0 -0
  43. /package/{req_test → backup/req_test}/mjsRcjs.mjs +0 -0
  44. /package/{req_test → backup/req_test}/req.cjs +0 -0
  45. /package/{req_test → backup/req_test}/req.mjs +0 -0
@@ -7,7 +7,6 @@ let index = 0;
7
7
  // 模拟的异步函数,有一定几率失败
8
8
  async function mockAsyncFunction() {
9
9
  return new Promise((resolve, reject) => {
10
-
11
10
  let delay =timeList[index];
12
11
  let result = resList[index];
13
12
  console.log("延迟: "+delay,"结果: "+result)
package/compile.bat ADDED
@@ -0,0 +1,2 @@
1
+ npm run compile
2
+ pause
@@ -1,15 +1,2 @@
1
- import { ExtractOutcome, Keyable, Outcome } from "./UtilInterfaces";
2
- /**创建一个outcome */
3
- export declare function outcome<K extends Keyable, V>(key: K, value: V): Outcome<K, V>;
4
- /**处理联合 简单值
5
- * @param t - 目标值
6
- * @param procObj - 所有可能的id组成的处理函数映射
7
- * @returns 任意处理函数的返回值
8
- */
9
- export declare function match<T extends Keyable | Outcome<Keyable, unknown>, P extends (T extends Keyable ? {
10
- [K in T]: (k: K) => unknown;
11
- } : T extends Outcome<Keyable, unknown> ? {
12
- [K in T['status']]: (k: K, v: ExtractOutcome<T, K>['result']) => unknown;
13
- } : never)>(t: T, procObj: P): P extends Record<any, (...args: any) => any> ? {
14
- [K in keyof P]: ReturnType<P[K]>;
15
- }[keyof P] : never;
1
+ import { UtilFunc } from "./UtilFunctions";
2
+ export declare const outcome: typeof UtilFunc.outcome, matchProc: typeof UtilFunc.matchProc, sucesProc: typeof UtilFunc.sucesProc, isFailed: typeof UtilFunc.isFailed, isSafeNumber: typeof UtilFunc.isSafeNumber, isSuccess: typeof UtilFunc.isSuccess, assertType: typeof UtilFunc.assertType, assertLiteral: typeof UtilFunc.assertLiteral, deepClone: typeof UtilFunc.deepClone, sleep: typeof UtilFunc.sleep, stringifyJToken: typeof UtilFunc.stringifyJToken, getTime: typeof UtilFunc.getTime, mapEntries: typeof UtilFunc.mapEntries, composeMixinable: typeof UtilFunc.composeMixinable;
@@ -1,27 +1,29 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.match = exports.outcome = void 0;
4
- /**创建一个outcome */
5
- function outcome(key, value) {
6
- return { status: key, result: value };
7
- }
8
- exports.outcome = outcome;
9
- /**处理联合 简单值
10
- * @param t - 目标值
11
- * @param procObj - 所有可能的id组成的处理函数映射
12
- * @returns 任意处理函数的返回值
13
- */
14
- function match(t, procObj) {
15
- if (typeof t === 'string' || typeof t === 'number' || typeof t === 'symbol')
16
- return procObj[t](t);
17
- else
18
- return procObj[t.status](t.status, t.result);
19
- }
20
- exports.match = match;
3
+ exports.composeMixinable = exports.mapEntries = exports.getTime = exports.stringifyJToken = exports.sleep = exports.deepClone = exports.assertLiteral = exports.assertType = exports.isSuccess = exports.isSafeNumber = exports.isFailed = exports.sucesProc = exports.matchProc = exports.outcome = void 0;
4
+ const UtilFunctions_1 = require("./UtilFunctions");
5
+ const UtilSymbol_1 = require("./UtilSymbol");
6
+ exports.outcome = UtilFunctions_1.UtilFunc.outcome, exports.matchProc = UtilFunctions_1.UtilFunc.matchProc, exports.sucesProc = UtilFunctions_1.UtilFunc.sucesProc, exports.isFailed = UtilFunctions_1.UtilFunc.isFailed, exports.isSafeNumber = UtilFunctions_1.UtilFunc.isSafeNumber, exports.isSuccess = UtilFunctions_1.UtilFunc.isSuccess, exports.assertType = UtilFunctions_1.UtilFunc.assertType, exports.assertLiteral = UtilFunctions_1.UtilFunc.assertLiteral, exports.deepClone = UtilFunctions_1.UtilFunc.deepClone, exports.sleep = UtilFunctions_1.UtilFunc.sleep, exports.stringifyJToken = UtilFunctions_1.UtilFunc.stringifyJToken, exports.getTime = UtilFunctions_1.UtilFunc.getTime, exports.mapEntries = UtilFunctions_1.UtilFunc.mapEntries, exports.composeMixinable = UtilFunctions_1.UtilFunc.composeMixinable;
21
7
  if (false) {
8
+ let aaser = (0, exports.assertLiteral)({ a: 1 });
22
9
  let a = null;
23
- const r = match(a, {
10
+ const r = (0, exports.matchProc)(a, {
24
11
  "asd": (a) => "ssa",
25
12
  "dsa": (b) => "ssb",
26
13
  });
14
+ let b = null;
15
+ const r1 = (0, exports.matchProc)(b, {
16
+ "a": (a, s) => "ssa",
17
+ [UtilSymbol_1.None]: (b, s) => "ssb",
18
+ });
19
+ let udt = (0, exports.outcome)("ssa", "None");
20
+ let assa = (0, exports.isFailed)(null);
21
+ let assb = (0, exports.isFailed)(null);
22
+ let assc = (0, exports.isFailed)(null);
23
+ let asssc = (0, exports.isFailed)(null);
24
+ let assa1 = (0, exports.isFailed)(null);
25
+ let assb1 = (0, exports.isFailed)(null);
26
+ let assc1 = (0, exports.isFailed)(null);
27
+ let proct = (0, exports.sucesProc)(null, (s) => "ssa", (f) => "ssad", () => 123);
28
+ let matt = (0, exports.matchProc)(null, {});
27
29
  }
@@ -111,4 +111,4 @@ var UtilCodec;
111
111
  return textDecoder.decode(encoderDavinci?.decode(arr));
112
112
  }
113
113
  UtilCodec.decodeTokenDavinci = decodeTokenDavinci;
114
- })(UtilCodec = exports.UtilCodec || (exports.UtilCodec = {}));
114
+ })(UtilCodec || (exports.UtilCodec = UtilCodec = {}));
package/dist/UtilCom.js CHANGED
@@ -154,4 +154,4 @@ var UtilCom;
154
154
  return sRepeatPost("http", json, options, timeLimit, repeatCount, repeatTime, verifyFn);
155
155
  }
156
156
  UtilCom.shttpRepeatPost = shttpRepeatPost;
157
- })(UtilCom = exports.UtilCom || (exports.UtilCom = {}));
157
+ })(UtilCom || (exports.UtilCom = UtilCom = {}));
@@ -23,7 +23,7 @@ export declare function Defer<T extends (...args: any) => any>(deferLogic: (...a
23
23
  /**异步的try-finally包装 */
24
24
  export declare function DeferAsync<T extends (...args: any) => Promise<any>>(deferLogic: (...args: Parameters<T>) => any | Promise<any>): TDTg<T>;
25
25
  /**try-catch包装 */
26
- export declare function DCatch<T extends (...args: any) => any>(catchLogic: (error: any, ...args: Parameters<T>) => ReturnType<T>): TDTg<T>;
26
+ export declare function Catch<T extends (...args: any) => any>(catchLogic: (error: any, ...args: Parameters<T>) => ReturnType<T>): TDTg<T>;
27
27
  /**异步的try-catch包装 */
28
28
  export declare function CatchAsync<T extends (...args: any) => Promise<any>>(catchLogic: (error: any, ...args: Parameters<T>) => ReturnType<T>): TDTg<T>;
29
29
  export {};
@@ -9,7 +9,7 @@ var __metadata = (this && this.__metadata) || function (k, v) {
9
9
  if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
10
10
  };
11
11
  Object.defineProperty(exports, "__esModule", { value: true });
12
- exports.CatchAsync = exports.DCatch = exports.DeferAsync = exports.Defer = exports.LogErrAsync = exports.LogErr = exports.LogCallAsync = exports.LogCall = exports.LogTimeAsync = exports.LogTime = void 0;
12
+ exports.CatchAsync = exports.Catch = exports.DeferAsync = exports.Defer = exports.LogErrAsync = exports.LogErr = exports.LogCallAsync = exports.LogCall = exports.LogTimeAsync = exports.LogTime = void 0;
13
13
  const UtilFunctions_1 = require("./UtilFunctions");
14
14
  const UtilLogger_1 = require("./UtilLogger");
15
15
  /**用于打印方法运行时间
@@ -146,7 +146,7 @@ function DeferAsync(deferLogic) {
146
146
  }
147
147
  exports.DeferAsync = DeferAsync;
148
148
  /**try-catch包装 */
149
- function DCatch(catchLogic) {
149
+ function Catch(catchLogic) {
150
150
  return function (target, propertyKey, descriptor) {
151
151
  const originalMethod = descriptor.value;
152
152
  descriptor.value = function (...args) {
@@ -162,7 +162,7 @@ function DCatch(catchLogic) {
162
162
  return descriptor;
163
163
  };
164
164
  }
165
- exports.DCatch = DCatch;
165
+ exports.Catch = Catch;
166
166
  /**异步的try-catch包装 */
167
167
  function CatchAsync(catchLogic) {
168
168
  return function (target, propertyKey, descriptor) {
@@ -208,6 +208,7 @@ __decorate([
208
208
  __decorate([
209
209
  LogCall(),
210
210
  Defer((a, b) => null),
211
+ CatchAsync(async (a, b) => 123),
211
212
  __metadata("design:type", Function),
212
213
  __metadata("design:paramtypes", [Number, String]),
213
214
  __metadata("design:returntype", Promise)
package/dist/UtilFP.js CHANGED
@@ -51,4 +51,4 @@ var UtilFP;
51
51
  console.log(sumb(true));
52
52
  console.log(sumc("s",3,false));
53
53
  */
54
- })(UtilFP = exports.UtilFP || (exports.UtilFP = {}));
54
+ })(UtilFP || (exports.UtilFP = UtilFP = {}));
@@ -204,4 +204,4 @@ var UtilFT;
204
204
  throw "请使用 fileSearchRegex 或 fileSearchGlob";
205
205
  }
206
206
  UtilFT.fileSearch = fileSearch;
207
- })(UtilFT = exports.UtilFT || (exports.UtilFT = {}));
207
+ })(UtilFT || (exports.UtilFT = UtilFT = {}));
@@ -1,7 +1,7 @@
1
- import { ComposedClass, ComposedMixinable, IJData, JObject, JToken, Mixinable, Outcome, PromiseVerifyFn } from "./UtilInterfaces";
2
- import { Completed, Timeout } from "./UtilSymbol";
3
- type CompleteCome<T> = Outcome<Completed, T>;
4
- type TimeoutCome<T> = Outcome<Timeout, Promise<T>>;
1
+ import { AnyFunc, ComposedClass, ComposedMixinable, ExtractOutcome, IJData, JObject, JToken, Keyable, LiteralCheck, Matchable, MatchableFlag, Mixinable, Outcome, PromiseVerifyFn, UnionToIntersection } from "./UtilInterfaces";
2
+ import { FailedLike, None, StatusSymbol, Success, SuccessLike, Timeout } from "./UtilSymbol";
3
+ type SuccessOut<T> = Outcome<Success, T>;
4
+ type TimeoutOut<T> = Outcome<Timeout, Promise<T>>;
5
5
  /**常用函数 */
6
6
  export declare class UtilFunc {
7
7
  /**获取当前时间戳
@@ -33,17 +33,6 @@ export declare class UtilFunc {
33
33
  * @returns hash
34
34
  */
35
35
  static calcHash(str: string): string;
36
- /**深克隆 序列化并反序列化
37
- * @template T - JToken类型的泛型
38
- * @param obj - 克隆目标
39
- * @returns 克隆结果
40
- */
41
- static deepClone<T extends JToken>(obj: T): T;
42
- /**是否为安全的数字
43
- * @param num - 所要检测的数字
44
- * @returns 是否安全
45
- */
46
- static isSafeNumber(num: number): boolean;
47
36
  /**等待 timeMs 毫秒
48
37
  * @async
49
38
  * @param timeMs - 等待的毫秒数
@@ -71,7 +60,7 @@ export declare class UtilFunc {
71
60
  * @param procFn - 发起函数
72
61
  * @param verifyFn - 验证函数
73
62
  * @param repeatCount - 重试次数
74
- * @param repeatTime - 超时时间/秒 最小为10
63
+ * @param repeatTime - 超时时间/秒 最小为5
75
64
  * @returns 结果 null 为全部失败/超时
76
65
  */
77
66
  static repeatPromise<T>(procFn: () => Promise<T>, verifyFn?: PromiseVerifyFn<T>, repeatCount?: number, repeatTime?: number): Promise<T | null>;
@@ -80,7 +69,7 @@ export declare class UtilFunc {
80
69
  * @param timeLimit - 毫秒限时
81
70
  * @returns 超时则返回 处理函数委托 完成则返回结果
82
71
  */
83
- static timelimitPromise<T>(func: () => Promise<T> | T, timeLimit?: number): Promise<CompleteCome<T> | TimeoutCome<T>>;
72
+ static timelimitPromise<T>(func: () => Promise<T> | T, timeLimit?: number): Promise<SuccessOut<T> | TimeoutOut<T>>;
84
73
  /**部分类组合
85
74
  * 将mixin的部分字段混入base
86
75
  * @param base - 基础类
@@ -98,12 +87,70 @@ export declare class UtilFunc {
98
87
  * @param mapper - 映射函数,接受一个值和一个键,返回一个新的值
99
88
  * @returns - 一个新的对象,它的属性是原对象的属性经过映射函数处理后的结果
100
89
  */
101
- static mapEntries<T extends Object>(obj: T, mapper: (key: keyof T, value: T[keyof T]) => T[keyof T]): T;
90
+ static mapEntries<T extends object>(obj: T, mapper: (key: keyof T, value: T[keyof T]) => T[keyof T]): T;
102
91
  /**将JToken转换为字符串
103
92
  * @param token - 待转换的Token
104
93
  * @param space - 插入的空格 数字为空格数量 默认为制表符\t
105
94
  * @returns 转换完成的字符串
106
95
  */
107
96
  static stringifyJToken(token: JToken | IJData, space?: string | number | null | undefined): string;
97
+ /**代办表 用于队列处理等待 */
98
+ static pendingMap: Record<Keyable, AnyFunc[]>;
99
+ /**队列处理
100
+ * 等待标签为 flag 的队列
101
+ * 直到排在之前的任务全部完成再处理当前Promise
102
+ * @param flag - 队列标签
103
+ * @param task - 任务逻辑
104
+ * @returns 处理结果
105
+ */
106
+ static queueProc<T>(flag: Keyable, task: (() => Promise<T>) | Promise<T>): Promise<T>;
107
+ /**创建一个Outcome */
108
+ static outcome<K extends Keyable, V>(key: K, value: V): Outcome<K, V>;
109
+ /**处理联合值
110
+ * @param t - 目标值
111
+ * @param procObj - 所有可能的id组成的处理函数映射 (status, result)=>any
112
+ * @returns 任意处理函数的返回值
113
+ */
114
+ static matchProc<T extends Matchable<Keyable>, P extends UnionToIntersection<{
115
+ [K in MatchableFlag<T>]: (k: K, v: ExtractOutcome<T, MatchableFlag<K>>['result']) => unknown;
116
+ }>>(t: T, procObj: P): P extends Record<any, AnyFunc> ? {
117
+ [K in keyof P]: ReturnType<P[K]>;
118
+ }[keyof P] : never;
119
+ /**根据典型的成功或失败状态运行函数
120
+ * @param t - 目标值
121
+ * @param sucessFunc - 成功则运行的函数 (result)=>any
122
+ * @param failedFunc - 失败则运行的函数 (result)=>any
123
+ * @param noneFunc - 无结果或不匹配时运行的函数 ()=>any
124
+ * @returns 非成功或失败时返回 None
125
+ */
126
+ static sucesProc<T extends Matchable<StatusSymbol>, S extends (arg: ExtractOutcome<T, SuccessLike>['result']) => unknown, F extends (arg: ExtractOutcome<T, FailedLike>['result']) => unknown = (arg: ExtractOutcome<T, FailedLike>['result']) => None, N extends () => unknown = () => None>(t: T, sucessFunc: S, failedFunc?: F, noneFunc?: N): ReturnType<S> | ReturnType<F> | ReturnType<N>;
127
+ /**是失败的 */
128
+ static isFailed<T>(tg: T): T extends Matchable<FailedLike> ? true : MatchableFlag<T> extends Exclude<MatchableFlag<T>, FailedLike> ? false : boolean;
129
+ /**是成功的 */
130
+ static isSuccess<T>(tg: T): T extends Matchable<SuccessLike> ? true : MatchableFlag<T> extends Exclude<MatchableFlag<T>, SuccessLike> ? false : boolean;
131
+ /**验证一个变量的类型是否为 T
132
+ * @template T - 验证类型
133
+ * @param t - 验证目标
134
+ */
135
+ static assertType<T>(t: T): T;
136
+ /**验证一个变量的类型是否为字面量
137
+ * 仅限浅层
138
+ * @template T - 验证类型
139
+ * @param t - 验证目标
140
+ */
141
+ static assertLiteral<T>(t: LiteralCheck<T>): T;
142
+ /**深克隆 序列化并反序列化
143
+ * @template T - JToken类型的泛型
144
+ * @param obj - 克隆目标
145
+ * @returns 克隆结果
146
+ */
147
+ static deepClone<T extends JToken>(obj: T): T;
148
+ /**是否为安全的数字
149
+ * 非NaN 非null/undefined
150
+ * 且是数字
151
+ * @param num - 所要检测的数字
152
+ * @returns 是否安全
153
+ */
154
+ static isSafeNumber(num: unknown): boolean;
108
155
  }
109
156
  export {};
@@ -14,7 +14,6 @@ const crypto = require("crypto");
14
14
  const cp = require("child_process");
15
15
  const UtilLogger_1 = require("./UtilLogger");
16
16
  const UtilSymbol_1 = require("./UtilSymbol");
17
- const QuickFunction_1 = require("./QuickFunction");
18
17
  const UtilDecorators_1 = require("./UtilDecorators");
19
18
  /**永不完成的Promise单例 */
20
19
  const NeverResolvedPromise = new Promise(() => { });
@@ -72,25 +71,6 @@ class UtilFunc {
72
71
  static calcHash(str) {
73
72
  return crypto.createHash('md5').update(str).digest('hex');
74
73
  }
75
- /**深克隆 序列化并反序列化
76
- * @template T - JToken类型的泛型
77
- * @param obj - 克隆目标
78
- * @returns 克隆结果
79
- */
80
- static deepClone(obj) {
81
- return JSON.parse(JSON.stringify(obj));
82
- }
83
- /**是否为安全的数字
84
- * @param num - 所要检测的数字
85
- * @returns 是否安全
86
- */
87
- static isSafeNumber(num) {
88
- if (num === undefined || num == null || isNaN(num))
89
- return false;
90
- if (typeof num === 'number')
91
- return true;
92
- return false;
93
- }
94
74
  static async sleep(timeMs, result) {
95
75
  return new Promise(function (resolve, rejecte) {
96
76
  let timer = setTimeout(function () {
@@ -120,18 +100,18 @@ class UtilFunc {
120
100
  * @param procFn - 发起函数
121
101
  * @param verifyFn - 验证函数
122
102
  * @param repeatCount - 重试次数
123
- * @param repeatTime - 超时时间/秒 最小为10
103
+ * @param repeatTime - 超时时间/秒 最小为5
124
104
  * @returns 结果 null 为全部失败/超时
125
105
  */
126
106
  static async repeatPromise(procFn, verifyFn, repeatCount = 3, repeatTime = 180) {
127
107
  /**是否含有超时时间 */
128
- const hasRepeatTime = (repeatTime >= 10);
108
+ const hasRepeatTime = (repeatTime >= 5);
129
109
  //转换为毫秒
130
110
  if (hasRepeatTime)
131
111
  repeatTime *= 1000;
132
112
  //验证处理函数
133
113
  if (verifyFn === undefined)
134
- verifyFn = () => UtilSymbol_1.Completed;
114
+ verifyFn = () => UtilSymbol_1.Success;
135
115
  //进行中的请求
136
116
  const plist = [];
137
117
  //开始处理
@@ -155,7 +135,7 @@ class UtilFunc {
155
135
  //解除timeout替换原参数
156
136
  plist[i] = new Promise(async (rslove) => {
157
137
  const res = await currObj.result;
158
- rslove((0, QuickFunction_1.outcome)(UtilSymbol_1.Completed, res));
138
+ rslove(UtilFunc.outcome(UtilSymbol_1.Success, res));
159
139
  });
160
140
  UtilLogger_1.SLogger.warn(`第 ${i + 1} 次 repeatPromise 超时 ${repeatTime} ms 开始重试`);
161
141
  i++;
@@ -163,8 +143,8 @@ class UtilFunc {
163
143
  }
164
144
  //路由请求状态
165
145
  const postresult = currObj.result;
166
- const result = (0, QuickFunction_1.match)(postresult.stat, {
167
- [UtilSymbol_1.Completed]() {
146
+ const result = UtilFunc.matchProc(postresult.stat, {
147
+ [UtilSymbol_1.Success]() {
168
148
  UtilLogger_1.SLogger.info(`第 ${postresult.index + 1} 次 repeatPromise 成功`);
169
149
  //非当前
170
150
  if (postresult.index != i)
@@ -212,18 +192,18 @@ class UtilFunc {
212
192
  const procer = (async () => await func())();
213
193
  const procerP = new Promise(async (resolve) => {
214
194
  const res = await procer;
215
- resolve((0, QuickFunction_1.outcome)(UtilSymbol_1.Completed, res));
195
+ resolve(UtilFunc.outcome(UtilSymbol_1.Success, res));
216
196
  if (clearTimer)
217
197
  clearTimer();
218
198
  });
219
199
  const timerP = timeLimit
220
200
  ? new Promise((resolve) => {
221
- const timer = setTimeout(() => resolve((0, QuickFunction_1.outcome)(UtilSymbol_1.Timeout, procer)), timeLimit); //无限制则无限时间
201
+ const timer = setTimeout(() => resolve(UtilFunc.outcome(UtilSymbol_1.Timeout, procer)), timeLimit); //无限制则无限时间
222
202
  clearTimer = () => {
223
- resolve((0, QuickFunction_1.outcome)(UtilSymbol_1.Timeout, procer));
203
+ resolve(UtilFunc.outcome(UtilSymbol_1.Timeout, procer));
224
204
  clearInterval(timer);
225
205
  };
226
- })
206
+ }) //未定义时间限制则无限
227
207
  : UtilFunc.getNeverResolvedPromise();
228
208
  const result = Promise.race([procerP, timerP]);
229
209
  reslove(result);
@@ -308,11 +288,143 @@ class UtilFunc {
308
288
  space = undefined;
309
289
  return JSON.stringify(token, null, space);
310
290
  }
291
+ /**代办表 用于队列处理等待 */
292
+ static pendingMap = {};
293
+ /**队列处理
294
+ * 等待标签为 flag 的队列
295
+ * 直到排在之前的任务全部完成再处理当前Promise
296
+ * @param flag - 队列标签
297
+ * @param task - 任务逻辑
298
+ * @returns 处理结果
299
+ */
300
+ static async queueProc(flag, task) {
301
+ this.pendingMap[flag] = this.pendingMap[flag] ?? [];
302
+ const pending = this.pendingMap[flag];
303
+ //尝试解除下个任务的等待
304
+ const tryRes = function () {
305
+ const thispd = pending;
306
+ const resolve = thispd.shift();
307
+ if (resolve)
308
+ resolve();
309
+ };
310
+ //空时直接运行 非空时等待
311
+ if (pending.length <= 0)
312
+ pending.push(() => tryRes());
313
+ else
314
+ await new Promise((resolve) => pending.push(resolve));
315
+ try {
316
+ const result = typeof task === 'function'
317
+ ? await task()
318
+ : await task;
319
+ return result;
320
+ }
321
+ catch (e) {
322
+ UtilLogger_1.SLogger.fatal(`queuePromise 出现错误`, e);
323
+ throw e;
324
+ }
325
+ finally {
326
+ tryRes();
327
+ }
328
+ }
329
+ /**创建一个Outcome */
330
+ static outcome(key, value) {
331
+ return {
332
+ status: key,
333
+ result: value
334
+ };
335
+ }
336
+ /**处理联合值
337
+ * @param t - 目标值
338
+ * @param procObj - 所有可能的id组成的处理函数映射 (status, result)=>any
339
+ * @returns 任意处理函数的返回值
340
+ */
341
+ static matchProc(t, procObj) {
342
+ if (typeof t === 'string' || typeof t === 'number' || typeof t === 'symbol') {
343
+ if (procObj[t])
344
+ return procObj[t](t);
345
+ UtilLogger_1.SLogger.fatal(`matchProc 传入了一个预料之外的值: `, t);
346
+ throw UtilSymbol_1.None;
347
+ }
348
+ else {
349
+ if (procObj[t.status])
350
+ return procObj[t.status](t.status, t.result);
351
+ UtilLogger_1.SLogger.fatal(`matchProc 传入了一个预料之外的值: `, t);
352
+ throw UtilSymbol_1.None;
353
+ }
354
+ }
355
+ /**根据典型的成功或失败状态运行函数
356
+ * @param t - 目标值
357
+ * @param sucessFunc - 成功则运行的函数 (result)=>any
358
+ * @param failedFunc - 失败则运行的函数 (result)=>any
359
+ * @param noneFunc - 无结果或不匹配时运行的函数 ()=>any
360
+ * @returns 非成功或失败时返回 None
361
+ */
362
+ static sucesProc(t, sucessFunc, failedFunc, noneFunc) {
363
+ failedFunc = failedFunc ?? (() => UtilSymbol_1.None);
364
+ noneFunc = noneFunc ?? (() => UtilSymbol_1.None);
365
+ const val = typeof t === 'symbol' ? undefined : t.result;
366
+ if (UtilFunc.isSuccess(t))
367
+ return sucessFunc(val);
368
+ if (UtilFunc.isFailed(t))
369
+ return failedFunc(val);
370
+ if (t !== UtilSymbol_1.None)
371
+ UtilLogger_1.SLogger.warn(`sucesProc 传入了一个不匹配的值, 将作为None运行: `, t);
372
+ return noneFunc();
373
+ }
374
+ /**是失败的 */
375
+ static isFailed(tg) {
376
+ const test = (t) => t === UtilSymbol_1.Failed || t === UtilSymbol_1.Terminated || t === UtilSymbol_1.Timeout;
377
+ if (tg != null && typeof tg === 'object' && 'status' in tg)
378
+ return test(tg.status);
379
+ return test(tg);
380
+ }
381
+ /**是成功的 */
382
+ static isSuccess(tg) {
383
+ const test = (t) => t === UtilSymbol_1.Success || t === UtilSymbol_1.Completed;
384
+ if (tg != null && typeof tg === 'object' && 'status' in tg)
385
+ return test(tg.status);
386
+ return test(tg);
387
+ }
388
+ /**验证一个变量的类型是否为 T
389
+ * @template T - 验证类型
390
+ * @param t - 验证目标
391
+ */
392
+ static assertType(t) { return t; }
393
+ /**验证一个变量的类型是否为字面量
394
+ * 仅限浅层
395
+ * @template T - 验证类型
396
+ * @param t - 验证目标
397
+ */
398
+ static assertLiteral(t) { return t; }
399
+ /**深克隆 序列化并反序列化
400
+ * @template T - JToken类型的泛型
401
+ * @param obj - 克隆目标
402
+ * @returns 克隆结果
403
+ */
404
+ static deepClone(obj) {
405
+ return JSON.parse(JSON.stringify(obj));
406
+ }
407
+ /**是否为安全的数字
408
+ * 非NaN 非null/undefined
409
+ * 且是数字
410
+ * @param num - 所要检测的数字
411
+ * @returns 是否安全
412
+ */
413
+ static isSafeNumber(num) {
414
+ if (num == null)
415
+ return false;
416
+ if (typeof num === 'number') {
417
+ if (isNaN(num))
418
+ return false;
419
+ return true;
420
+ }
421
+ return false;
422
+ }
311
423
  }
424
+ exports.UtilFunc = UtilFunc;
312
425
  __decorate([
313
426
  (0, UtilDecorators_1.LogTimeAsync)("repeatPromise ", true),
314
427
  __metadata("design:type", Function),
315
428
  __metadata("design:paramtypes", [Function, Function, Number, Number]),
316
429
  __metadata("design:returntype", Promise)
317
430
  ], UtilFunc, "repeatPromise", null);
318
- exports.UtilFunc = UtilFunc;
@@ -1,4 +1,4 @@
1
- import { Completed, Failed, Terminated } from "./UtilSymbol";
1
+ import { Failed, Success, Terminated } from "./UtilSymbol";
2
2
  /**可以序列化为JSON文件的对象 */
3
3
  export type JToken = JObject | JArray | JValue | IJData;
4
4
  /**在stringify输出时 undefine 会被转为 null */
@@ -15,8 +15,14 @@ export interface IJData {
15
15
  */
16
16
  toJSON(): JToken;
17
17
  }
18
+ /**任何可能有ReturnType的函数 */
19
+ export type AnyFunc = (...args: any) => any;
18
20
  /**任意可作为键值的类型 */
19
21
  export type Keyable = string | number | symbol;
22
+ /**真子集 */
23
+ export type ProperSubset<B, T = B> = T extends B ? B extends T ? never : T : never;
24
+ /**字面量检测 */
25
+ export type LiteralCheck<L> = ProperSubset<string, L> | ProperSubset<number, L> | ProperSubset<boolean, L> | ProperSubset<symbol, L> | ProperSubset<any[], L> | ProperSubset<Record<any, any>, L> | null | undefined;
20
26
  /**转为可写的 */
21
27
  export type Writeable<T> = {
22
28
  -readonly [P in keyof T]: T[P];
@@ -32,6 +38,11 @@ export type FixedLengthTuple<T, N extends number, R extends unknown[] = []> = R[
32
38
  * (string&String)
33
39
  */
34
40
  export type AnyString = (string & {});
41
+ /**联合类型转为交叉类型
42
+ * 将联合类型映射为联合函数
43
+ * 再取得可以传递给任意联合函数的类型
44
+ */
45
+ export type UnionToIntersection<U> = (U extends any ? (k: U) => void : never) extends ((k: infer I) => void) ? I : never;
35
46
  /**创建一个新的类型,这个新的类型包含了基础类型 B 的所有属性,
36
47
  * 以及一个名为 K[N] 类型为 T 的新属性。
37
48
  * 所有 K 中非 K[N] 的其他属性都是可选的并且不能被赋值(因为它们的类型是 never)。
@@ -56,12 +67,14 @@ export type ExclusiveJObject<B extends JObject, T extends JToken, K extends stri
56
67
  * 终止 将直接返回 null
57
68
  * 失败 将重试
58
69
  */
59
- export type PromiseStat = Completed | Failed | Terminated;
70
+ export type PromiseStat = Success | Failed | Terminated;
60
71
  /**promise验证函数 */
61
72
  export type PromiseVerifyFn<T> = (obj: T) => Promise<PromiseStat> | PromiseStat;
73
+ /**获取Promise的结果类型 */
74
+ export type UnwrapPromise<T> = T extends Promise<infer U> ? U : T;
62
75
  /**类型中任意函数的字符串名称 */
63
76
  export type FuncPropNames<T> = {
64
- [K in keyof T]: T[K] extends (...args: unknown[]) => unknown ? K : never;
77
+ [K in keyof T]: T[K] extends AnyFunc ? K : never;
65
78
  }[keyof T];
66
79
  /**部分组合的类
67
80
  * @template Base - 基类
@@ -91,16 +104,9 @@ export type ComposedMixinable<B, Ms extends unknown[]> = Ms extends [infer M, ..
91
104
  * @template N - 如果为假的返回值
92
105
  */
93
106
  export type ExtendThen<B, T, Y, N = never> = B extends T ? Y : N;
94
- /** 一个联合类型 B 中如果包含 T
95
- * @template B - 基础类型
96
- * @template T - 判断的目标类型
97
- * @template Y - 如果为真的返回值
98
- * @template N - 如果为假的返回值
99
- */
100
- export type UnionInclude<B, T, Y, N = never> = B extends Exclude<B, T> ? Y : N;
101
107
  /**排除可选字段 */
102
108
  export type RequiredOnly<T> = {
103
- [K in keyof T as UnionInclude<T[K], undefined, never, K>]: T[K];
109
+ [K in keyof T as T[K] extends Exclude<T[K], undefined> ? K : never]: T[K];
104
110
  };
105
111
  /**添加前缀 */
106
112
  export type WithPrefix<T, P extends string> = {
@@ -112,10 +118,14 @@ export type WithPrefix<T, P extends string> = {
112
118
  */
113
119
  export type Outcome<K extends Keyable, V> = {
114
120
  /**状态类型 */
115
- status: K;
121
+ readonly status: K;
116
122
  /**值 */
117
- result: V;
123
+ readonly result: V;
118
124
  };
119
- /**从联合 Outcome 中 根据 id 提取对应 value 的 type */
120
- export type ExtractOutcome<T, K extends Keyable> = T extends Outcome<K, unknown> ? T : never;
125
+ /**可进行匹配的 outcome或symbol */
126
+ export type Matchable<T extends Keyable> = T | Outcome<T, unknown>;
127
+ /**可进行匹配的 outcome或symbol 中的状态类型 */
128
+ export type MatchableFlag<T> = T extends infer O | Outcome<infer O, unknown> ? O : never;
129
+ /**从联合 Outcome 中 根据 id 提取对应 Outcome */
130
+ export type ExtractOutcome<T, K extends Keyable> = T extends Outcome<infer O, unknown> ? O extends Exclude<O, K> ? never : T : never;
121
131
  export {};
@@ -1,15 +1,37 @@
1
- /**完成 */
2
- export declare const Completed: unique symbol;
3
- export type Completed = typeof Completed;
4
- /**失败 */
1
+ import { Outcome } from "./UtilInterfaces";
2
+ /**成功 经过验证的结果 */
3
+ export declare const Success: unique symbol;
4
+ export type Success = typeof Success;
5
+ /**失败 可重试的 */
5
6
  export declare const Failed: unique symbol;
6
7
  export type Failed = typeof Failed;
7
- /**终止 */
8
- export declare const Terminated: unique symbol;
9
- export type Terminated = typeof Terminated;
10
- /**不存在 */
8
+ /**不存在 */
11
9
  export declare const None: unique symbol;
12
10
  export type None = typeof None;
13
- /**超时 */
11
+ /**完成 未经验证/未超时的结果
12
+ * Success扩展
13
+ * 仅在Success同时出现时使用
14
+ */
15
+ export declare const Completed: unique symbol;
16
+ export type Completed = typeof Completed;
17
+ /**终止 熔断运行
18
+ * Failed扩展
19
+ * 仅在Failed同时出现时使用
20
+ */
21
+ export declare const Terminated: unique symbol;
22
+ export type Terminated = typeof Terminated;
23
+ /**超时 超时类型的失败
24
+ * Failed扩展
25
+ * 仅在超时时使用
26
+ */
14
27
  export declare const Timeout: unique symbol;
15
28
  export type Timeout = typeof Timeout;
29
+ /**失败及其拓展 */
30
+ export type FailedLike = Failed | Timeout | Terminated;
31
+ /**成功及其拓展 */
32
+ export type SuccessLike = Success | Completed;
33
+ /**任意状态标识符 */
34
+ export type StatusSymbol = FailedLike | SuccessLike | None;
35
+ /**结果为 None 的 Outcome */
36
+ export type NoneOut = Outcome<None, None>;
37
+ export declare const NoneOut: NoneOut;