@pisell/core 0.0.2

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 (296) hide show
  1. package/README.md +1 -0
  2. package/es/app/app.d.ts +101 -0
  3. package/es/app/app.js +177 -0
  4. package/es/app/const.d.ts +4 -0
  5. package/es/app/const.js +6 -0
  6. package/es/app/index.d.ts +14 -0
  7. package/es/app/index.js +52 -0
  8. package/es/applicationManager/application.d.ts +197 -0
  9. package/es/applicationManager/application.js +469 -0
  10. package/es/applicationManager/index.d.ts +19 -0
  11. package/es/applicationManager/index.js +206 -0
  12. package/es/aws/index.d.ts +16 -0
  13. package/es/aws/index.js +76 -0
  14. package/es/cmd/const.d.ts +11 -0
  15. package/es/cmd/const.js +13 -0
  16. package/es/cmd/index.d.ts +13 -0
  17. package/es/cmd/index.js +91 -0
  18. package/es/cmd/type.d.ts +5 -0
  19. package/es/cmd/type.js +1 -0
  20. package/es/communicationManager/index.d.ts +59 -0
  21. package/es/communicationManager/index.js +174 -0
  22. package/es/config.d.ts +3 -0
  23. package/es/config.js +14 -0
  24. package/es/cookie/index.d.ts +13 -0
  25. package/es/cookie/index.js +47 -0
  26. package/es/css/global.less +73 -0
  27. package/es/css/index.less +31 -0
  28. package/es/css/variables.css +84 -0
  29. package/es/data/index.d.ts +8 -0
  30. package/es/data/index.js +16 -0
  31. package/es/history/config.d.ts +24 -0
  32. package/es/history/config.js +43 -0
  33. package/es/history/index.d.ts +26 -0
  34. package/es/history/index.js +80 -0
  35. package/es/history/type.d.ts +2 -0
  36. package/es/history/type.js +1 -0
  37. package/es/hooks/index.d.ts +12 -0
  38. package/es/hooks/index.js +13 -0
  39. package/es/hooks/useDelayedValue/index.d.ts +2 -0
  40. package/es/hooks/useDelayedValue/index.js +26 -0
  41. package/es/hooks/useDispatch/index.d.ts +2 -0
  42. package/es/hooks/useDispatch/index.js +2 -0
  43. package/es/hooks/useLowCode/index.d.ts +13 -0
  44. package/es/hooks/useLowCode/index.js +74 -0
  45. package/es/hooks/useStore/index.d.ts +6 -0
  46. package/es/hooks/useStore/index.js +11 -0
  47. package/es/index.d.ts +8 -0
  48. package/es/index.js +10 -0
  49. package/es/indexDB/index.d.ts +296 -0
  50. package/es/indexDB/index.js +1619 -0
  51. package/es/locales/en.d.ts +3 -0
  52. package/es/locales/en.js +5 -0
  53. package/es/locales/index.d.ts +39 -0
  54. package/es/locales/index.js +199 -0
  55. package/es/locales/original.d.ts +3 -0
  56. package/es/locales/original.js +7 -0
  57. package/es/locales/type.d.ts +19 -0
  58. package/es/locales/type.js +1 -0
  59. package/es/locales/zh-CN.d.ts +3 -0
  60. package/es/locales/zh-CN.js +5 -0
  61. package/es/locales/zh-HK.d.ts +3 -0
  62. package/es/locales/zh-HK.js +5 -0
  63. package/es/logger/feishu.d.ts +11 -0
  64. package/es/logger/feishu.js +50 -0
  65. package/es/logger/index.d.ts +135 -0
  66. package/es/logger/index.js +870 -0
  67. package/es/menuManager/hooks.d.ts +17 -0
  68. package/es/menuManager/hooks.js +136 -0
  69. package/es/menuManager/index.d.ts +28 -0
  70. package/es/menuManager/index.js +165 -0
  71. package/es/models/global.d.ts +32 -0
  72. package/es/models/global.js +66 -0
  73. package/es/models/index.d.ts +45 -0
  74. package/es/models/index.js +65 -0
  75. package/es/models/type.d.ts +2 -0
  76. package/es/models/type.js +1 -0
  77. package/es/plugin/index.d.ts +0 -0
  78. package/es/plugin/index.js +0 -0
  79. package/es/pubsub/example.d.ts +5 -0
  80. package/es/pubsub/example.js +92 -0
  81. package/es/pubsub/index.d.ts +73 -0
  82. package/es/pubsub/index.js +166 -0
  83. package/es/render/index.d.ts +0 -0
  84. package/es/render/index.js +0 -0
  85. package/es/request/cache.d.ts +46 -0
  86. package/es/request/cache.js +372 -0
  87. package/es/request/cancelToken.d.ts +38 -0
  88. package/es/request/cancelToken.js +59 -0
  89. package/es/request/config.d.ts +3 -0
  90. package/es/request/config.js +63 -0
  91. package/es/request/constants.d.ts +2 -0
  92. package/es/request/constants.js +6 -0
  93. package/es/request/index.d.ts +24 -0
  94. package/es/request/index.js +267 -0
  95. package/es/request/pisell2Request.d.ts +6 -0
  96. package/es/request/pisell2Request.js +62 -0
  97. package/es/request/type.d.ts +57 -0
  98. package/es/request/type.js +10 -0
  99. package/es/request/utils.d.ts +46 -0
  100. package/es/request/utils.js +147 -0
  101. package/es/routes/config.d.ts +7 -0
  102. package/es/routes/config.js +17 -0
  103. package/es/routes/index.d.ts +28 -0
  104. package/es/routes/index.js +151 -0
  105. package/es/socket/components/SocketMonitorPage.d.ts +6 -0
  106. package/es/socket/components/SocketMonitorPage.js +485 -0
  107. package/es/socket/components/index.d.ts +2 -0
  108. package/es/socket/components/index.js +2 -0
  109. package/es/socket/constants.d.ts +33 -0
  110. package/es/socket/constants.js +39 -0
  111. package/es/socket/events.d.ts +31 -0
  112. package/es/socket/events.js +19 -0
  113. package/es/socket/heartbeat.d.ts +66 -0
  114. package/es/socket/heartbeat.js +184 -0
  115. package/es/socket/index.d.ts +61 -0
  116. package/es/socket/index.js +246 -0
  117. package/es/socket/monitor.d.ts +169 -0
  118. package/es/socket/monitor.js +448 -0
  119. package/es/socket/reconnect.d.ts +61 -0
  120. package/es/socket/reconnect.js +199 -0
  121. package/es/socket/socket.d.ts +130 -0
  122. package/es/socket/socket.js +613 -0
  123. package/es/socket/types.d.ts +85 -0
  124. package/es/socket/types.js +35 -0
  125. package/es/storage/index.d.ts +17 -0
  126. package/es/storage/index.js +46 -0
  127. package/es/tasks/index.d.ts +127 -0
  128. package/es/tasks/index.js +1119 -0
  129. package/es/tasks/scheduledTasksExample.d.ts +61 -0
  130. package/es/tasks/scheduledTasksExample.js +351 -0
  131. package/es/tasks/type.d.ts +100 -0
  132. package/es/tasks/type.js +1 -0
  133. package/es/tasks/useTasks.d.ts +5 -0
  134. package/es/tasks/useTasks.js +25 -0
  135. package/es/type.d.ts +2 -0
  136. package/es/type.js +1 -0
  137. package/es/utils/adaptiveThrottle/index.d.ts +36 -0
  138. package/es/utils/adaptiveThrottle/index.js +136 -0
  139. package/es/variables/VariablesProvider.d.ts +7 -0
  140. package/es/variables/VariablesProvider.js +12 -0
  141. package/es/variables/config.d.ts +3 -0
  142. package/es/variables/config.js +16 -0
  143. package/es/variables/index.d.ts +6 -0
  144. package/es/variables/index.js +5 -0
  145. package/es/variables/type.d.ts +2 -0
  146. package/es/variables/type.js +1 -0
  147. package/es/website/index.d.ts +6 -0
  148. package/es/website/index.js +65 -0
  149. package/lib/app/app.d.ts +101 -0
  150. package/lib/app/app.js +171 -0
  151. package/lib/app/const.d.ts +4 -0
  152. package/lib/app/const.js +33 -0
  153. package/lib/app/index.d.ts +14 -0
  154. package/lib/app/index.js +76 -0
  155. package/lib/applicationManager/application.d.ts +197 -0
  156. package/lib/applicationManager/application.js +280 -0
  157. package/lib/applicationManager/index.d.ts +19 -0
  158. package/lib/applicationManager/index.js +88 -0
  159. package/lib/aws/index.d.ts +16 -0
  160. package/lib/aws/index.js +67 -0
  161. package/lib/cmd/const.d.ts +11 -0
  162. package/lib/cmd/const.js +39 -0
  163. package/lib/cmd/index.d.ts +13 -0
  164. package/lib/cmd/index.js +96 -0
  165. package/lib/cmd/type.d.ts +5 -0
  166. package/lib/cmd/type.js +17 -0
  167. package/lib/communicationManager/index.d.ts +59 -0
  168. package/lib/communicationManager/index.js +102 -0
  169. package/lib/config.d.ts +3 -0
  170. package/lib/config.js +36 -0
  171. package/lib/cookie/index.d.ts +13 -0
  172. package/lib/cookie/index.js +62 -0
  173. package/lib/css/global.less +73 -0
  174. package/lib/css/index.less +31 -0
  175. package/lib/css/variables.css +84 -0
  176. package/lib/data/index.d.ts +8 -0
  177. package/lib/data/index.js +38 -0
  178. package/lib/history/config.d.ts +24 -0
  179. package/lib/history/config.js +41 -0
  180. package/lib/history/index.d.ts +26 -0
  181. package/lib/history/index.js +99 -0
  182. package/lib/history/type.d.ts +2 -0
  183. package/lib/history/type.js +17 -0
  184. package/lib/hooks/index.d.ts +12 -0
  185. package/lib/hooks/index.js +44 -0
  186. package/lib/hooks/useDelayedValue/index.d.ts +2 -0
  187. package/lib/hooks/useDelayedValue/index.js +36 -0
  188. package/lib/hooks/useDispatch/index.d.ts +2 -0
  189. package/lib/hooks/useDispatch/index.js +26 -0
  190. package/lib/hooks/useLowCode/index.d.ts +13 -0
  191. package/lib/hooks/useLowCode/index.js +75 -0
  192. package/lib/hooks/useStore/index.d.ts +6 -0
  193. package/lib/hooks/useStore/index.js +33 -0
  194. package/lib/index.d.ts +8 -0
  195. package/lib/index.js +58 -0
  196. package/lib/indexDB/index.d.ts +296 -0
  197. package/lib/indexDB/index.js +767 -0
  198. package/lib/locales/en.d.ts +3 -0
  199. package/lib/locales/en.js +29 -0
  200. package/lib/locales/index.d.ts +39 -0
  201. package/lib/locales/index.js +159 -0
  202. package/lib/locales/original.d.ts +3 -0
  203. package/lib/locales/original.js +31 -0
  204. package/lib/locales/type.d.ts +19 -0
  205. package/lib/locales/type.js +17 -0
  206. package/lib/locales/zh-CN.d.ts +3 -0
  207. package/lib/locales/zh-CN.js +29 -0
  208. package/lib/locales/zh-HK.d.ts +3 -0
  209. package/lib/locales/zh-HK.js +29 -0
  210. package/lib/logger/feishu.d.ts +11 -0
  211. package/lib/logger/feishu.js +52 -0
  212. package/lib/logger/index.d.ts +135 -0
  213. package/lib/logger/index.js +476 -0
  214. package/lib/menuManager/hooks.d.ts +17 -0
  215. package/lib/menuManager/hooks.js +135 -0
  216. package/lib/menuManager/index.d.ts +28 -0
  217. package/lib/menuManager/index.js +125 -0
  218. package/lib/models/global.d.ts +32 -0
  219. package/lib/models/global.js +62 -0
  220. package/lib/models/index.d.ts +45 -0
  221. package/lib/models/index.js +69 -0
  222. package/lib/models/type.d.ts +2 -0
  223. package/lib/models/type.js +17 -0
  224. package/lib/plugin/index.d.ts +0 -0
  225. package/lib/plugin/index.js +0 -0
  226. package/lib/pubsub/example.d.ts +5 -0
  227. package/lib/pubsub/example.js +61 -0
  228. package/lib/pubsub/index.d.ts +73 -0
  229. package/lib/pubsub/index.js +141 -0
  230. package/lib/render/index.d.ts +0 -0
  231. package/lib/render/index.js +0 -0
  232. package/lib/request/cache.d.ts +46 -0
  233. package/lib/request/cache.js +195 -0
  234. package/lib/request/cancelToken.d.ts +38 -0
  235. package/lib/request/cancelToken.js +59 -0
  236. package/lib/request/config.d.ts +3 -0
  237. package/lib/request/config.js +69 -0
  238. package/lib/request/constants.d.ts +2 -0
  239. package/lib/request/constants.js +34 -0
  240. package/lib/request/index.d.ts +24 -0
  241. package/lib/request/index.js +210 -0
  242. package/lib/request/pisell2Request.d.ts +6 -0
  243. package/lib/request/pisell2Request.js +75 -0
  244. package/lib/request/type.d.ts +57 -0
  245. package/lib/request/type.js +36 -0
  246. package/lib/request/utils.d.ts +46 -0
  247. package/lib/request/utils.js +113 -0
  248. package/lib/routes/config.d.ts +7 -0
  249. package/lib/routes/config.js +50 -0
  250. package/lib/routes/index.d.ts +28 -0
  251. package/lib/routes/index.js +121 -0
  252. package/lib/socket/components/SocketMonitorPage.d.ts +6 -0
  253. package/lib/socket/components/SocketMonitorPage.js +340 -0
  254. package/lib/socket/components/index.d.ts +2 -0
  255. package/lib/socket/components/index.js +39 -0
  256. package/lib/socket/constants.d.ts +33 -0
  257. package/lib/socket/constants.js +62 -0
  258. package/lib/socket/events.d.ts +31 -0
  259. package/lib/socket/events.js +44 -0
  260. package/lib/socket/heartbeat.d.ts +66 -0
  261. package/lib/socket/heartbeat.js +157 -0
  262. package/lib/socket/index.d.ts +61 -0
  263. package/lib/socket/index.js +198 -0
  264. package/lib/socket/monitor.d.ts +169 -0
  265. package/lib/socket/monitor.js +350 -0
  266. package/lib/socket/reconnect.d.ts +61 -0
  267. package/lib/socket/reconnect.js +157 -0
  268. package/lib/socket/socket.d.ts +130 -0
  269. package/lib/socket/socket.js +426 -0
  270. package/lib/socket/types.d.ts +85 -0
  271. package/lib/socket/types.js +36 -0
  272. package/lib/storage/index.d.ts +17 -0
  273. package/lib/storage/index.js +64 -0
  274. package/lib/tasks/index.d.ts +127 -0
  275. package/lib/tasks/index.js +710 -0
  276. package/lib/tasks/scheduledTasksExample.d.ts +61 -0
  277. package/lib/tasks/scheduledTasksExample.js +267 -0
  278. package/lib/tasks/type.d.ts +100 -0
  279. package/lib/tasks/type.js +17 -0
  280. package/lib/tasks/useTasks.d.ts +5 -0
  281. package/lib/tasks/useTasks.js +37 -0
  282. package/lib/type.d.ts +2 -0
  283. package/lib/type.js +17 -0
  284. package/lib/utils/adaptiveThrottle/index.d.ts +36 -0
  285. package/lib/utils/adaptiveThrottle/index.js +121 -0
  286. package/lib/variables/VariablesProvider.d.ts +7 -0
  287. package/lib/variables/VariablesProvider.js +51 -0
  288. package/lib/variables/config.d.ts +3 -0
  289. package/lib/variables/config.js +38 -0
  290. package/lib/variables/index.d.ts +6 -0
  291. package/lib/variables/index.js +29 -0
  292. package/lib/variables/type.d.ts +2 -0
  293. package/lib/variables/type.js +17 -0
  294. package/lib/website/index.d.ts +6 -0
  295. package/lib/website/index.js +75 -0
  296. package/package.json +49 -0
@@ -0,0 +1,710 @@
1
+ var __create = Object.create;
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __getProtoOf = Object.getPrototypeOf;
6
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
7
+ var __export = (target, all) => {
8
+ for (var name in all)
9
+ __defProp(target, name, { get: all[name], enumerable: true });
10
+ };
11
+ var __copyProps = (to, from, except, desc) => {
12
+ if (from && typeof from === "object" || typeof from === "function") {
13
+ for (let key of __getOwnPropNames(from))
14
+ if (!__hasOwnProp.call(to, key) && key !== except)
15
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
16
+ }
17
+ return to;
18
+ };
19
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
20
+ // If the importer is in node compatibility mode or this is not an ESM
21
+ // file that has been converted to a CommonJS file using a Babel-
22
+ // compatible transform (i.e. "__esModule" has not been set), then set
23
+ // "default" to the CommonJS "module.exports" for node compatibility.
24
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
25
+ mod
26
+ ));
27
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
28
+
29
+ // src/tasks/index.ts
30
+ var tasks_exports = {};
31
+ __export(tasks_exports, {
32
+ TasksManager: () => TasksManager
33
+ });
34
+ module.exports = __toCommonJS(tasks_exports);
35
+ var import_dayjs = __toESM(require("dayjs"));
36
+ var import_utils = require("@pisell/utils");
37
+ var import_useTasks = __toESM(require("./useTasks"));
38
+ var TasksManager = class _TasksManager {
39
+ static instance;
40
+ taskFunctions;
41
+ tasks = {
42
+ // 内置模块, 定时任务专用
43
+ scheduledTasks: {}
44
+ };
45
+ app;
46
+ db;
47
+ useTasks = import_useTasks.default;
48
+ watchTaskCallback = () => {
49
+ };
50
+ timerIds = [];
51
+ constructor(app) {
52
+ if (!app) {
53
+ throw new Error("app is required");
54
+ }
55
+ this.app = app;
56
+ this.taskFunctions = /* @__PURE__ */ new Map();
57
+ this.tasks = {
58
+ scheduledTasks: {}
59
+ };
60
+ this.db = app.dbManager;
61
+ this.timerIds = [];
62
+ }
63
+ // 单例模式
64
+ static getInstance(app) {
65
+ if (!_TasksManager.instance && app) {
66
+ _TasksManager.instance = new _TasksManager(app);
67
+ }
68
+ return _TasksManager.instance;
69
+ }
70
+ // 注册任务函数
71
+ addTaskFunction(name, fun) {
72
+ this.taskFunctions.set(name, fun);
73
+ console.log("Tasks--->", `注册任务函数成功: ${name}`);
74
+ }
75
+ // 注册任务函数列表
76
+ addTaskFunctions(tasks) {
77
+ tasks.forEach(({ name, fun }) => {
78
+ this.taskFunctions.set(name, fun);
79
+ });
80
+ }
81
+ getTasks() {
82
+ return this.tasks;
83
+ }
84
+ // 获取任务函数
85
+ getTaskFunction(name) {
86
+ if (!name) {
87
+ return null;
88
+ }
89
+ return this.taskFunctions.get(name);
90
+ }
91
+ // 初始化任务
92
+ async init() {
93
+ }
94
+ // 将任务队列状态同步到 local
95
+ saveTaskQueueToLocal = async (state) => {
96
+ var _a;
97
+ console.log("saveTaskQueueToLocal", state);
98
+ (_a = this.watchTaskCallback) == null ? void 0 : _a.call(this, this.tasks);
99
+ };
100
+ // 从 local 加载任务队列状态
101
+ loadTaskQueueFromLocal = async () => {
102
+ var _a, _b;
103
+ try {
104
+ const tasks = await this.db.get("tasks", "tasks");
105
+ for (let module2 in tasks) {
106
+ for (let queueId in tasks[module2]) {
107
+ for (let task of ((_b = (_a = tasks == null ? void 0 : tasks[module2]) == null ? void 0 : _a[queueId]) == null ? void 0 : _b.tasks) || []) {
108
+ if (task.destroy) {
109
+ delete tasks[module2][queueId].tasks;
110
+ }
111
+ }
112
+ }
113
+ }
114
+ return tasks;
115
+ } catch (err) {
116
+ console.log("loadTaskQueueFromLocal", err);
117
+ return null;
118
+ }
119
+ };
120
+ /**
121
+ * @title: 执行任务
122
+ * @description:
123
+ * @param {Task} task
124
+ * @return {*}
125
+ * @Author: zhiwei.Wang
126
+ * @Date: 2024-09-26 13:53
127
+ */
128
+ runTask = async (task) => {
129
+ const beforeAction = this.getTaskFunction(task.beforeAction || "");
130
+ const afterAction = this.getTaskFunction(task.afterAction || "");
131
+ const action = this.getTaskFunction(task.action || "");
132
+ let beforeActionRes;
133
+ let afterActionRes;
134
+ let actionRes = { status: "success" };
135
+ try {
136
+ if (beforeAction) {
137
+ beforeActionRes = await beforeAction({ task });
138
+ }
139
+ if (action) {
140
+ actionRes = await action({ task, beforeActionRes });
141
+ }
142
+ if (afterAction) {
143
+ afterActionRes = await afterAction({ task, actionRes, afterActionRes });
144
+ }
145
+ } catch (error) {
146
+ this.app.logger.addLog({
147
+ type: "info",
148
+ title: `任务执行失败-${task.id}`,
149
+ metadata: { error, taskPayload: task == null ? void 0 : task.payload }
150
+ });
151
+ actionRes = { status: "failure" };
152
+ }
153
+ console.log("Tasks--->", `任务执行成功: ${task.id}`);
154
+ return actionRes;
155
+ };
156
+ /**
157
+ * @title: 清除任务定时器
158
+ */
159
+ clearTaskTimer = (params) => {
160
+ const { timerId, taskId } = params;
161
+ const _timerIds = [];
162
+ const needClearTimerIds = [];
163
+ this.timerIds.forEach((id) => {
164
+ const taskIdRult = taskId ? (id == null ? void 0 : id.taskId) === taskId : true;
165
+ const timerIdRult = timerId ? (id == null ? void 0 : id.timerId) === timerId : true;
166
+ if (taskIdRult && timerIdRult) {
167
+ needClearTimerIds.push(id);
168
+ } else {
169
+ _timerIds.push(id);
170
+ }
171
+ });
172
+ if (needClearTimerIds.length) {
173
+ for (let id of needClearTimerIds) {
174
+ clearTimeout(id.timerId);
175
+ }
176
+ }
177
+ this.timerIds = [..._timerIds || []];
178
+ };
179
+ /**
180
+ * @title: 计算下一次执行时间
181
+ * @description: 根据定时任务配置计算下一次执行时间
182
+ * @param {Task} task
183
+ * @return {string | null} 下一次执行时间
184
+ */
185
+ calculateNextExecuteTime = (task) => {
186
+ if (!task.scheduled) {
187
+ return null;
188
+ }
189
+ const { scheduled, scheduledResult } = task;
190
+ const now = (0, import_dayjs.default)();
191
+ if (scheduled.endAt && now.isAfter((0, import_dayjs.default)(scheduled.endAt))) {
192
+ return null;
193
+ }
194
+ if (Array.isArray(scheduled.executeAt)) {
195
+ const futureTime = scheduled.executeAt.map((time) => (0, import_dayjs.default)(time)).filter((time) => time.isAfter(now)).sort((a, b) => a.valueOf() - b.valueOf())[0];
196
+ if (futureTime) {
197
+ return futureTime.format("YYYY-MM-DD HH:mm:ss");
198
+ }
199
+ if (!scheduled.repeat) {
200
+ return null;
201
+ }
202
+ }
203
+ if (scheduled.repeat && (scheduledResult == null ? void 0 : scheduledResult.nextExecuteTime)) {
204
+ const lastExecuteTime = (0, import_dayjs.default)(scheduledResult.nextExecuteTime);
205
+ const interval = scheduled.repeatInterval || 1;
206
+ let nextTime = lastExecuteTime;
207
+ switch (scheduled.repeatType) {
208
+ case "daily":
209
+ nextTime = lastExecuteTime.add(interval, "day");
210
+ break;
211
+ case "weekly":
212
+ nextTime = lastExecuteTime.add(interval, "week");
213
+ break;
214
+ case "monthly":
215
+ nextTime = lastExecuteTime.add(interval, "month");
216
+ break;
217
+ case "yearly":
218
+ nextTime = lastExecuteTime.add(interval, "year");
219
+ break;
220
+ default:
221
+ nextTime = lastExecuteTime.add(interval, "day");
222
+ }
223
+ if (scheduled.endAt && nextTime.isAfter((0, import_dayjs.default)(scheduled.endAt))) {
224
+ return null;
225
+ }
226
+ return nextTime.format("YYYY-MM-DD HH:mm:ss");
227
+ }
228
+ const executeTime = Array.isArray(scheduled.executeAt) ? scheduled.executeAt[0] : scheduled.executeAt;
229
+ return (0, import_dayjs.default)(executeTime).format("YYYY-MM-DD HH:mm:ss");
230
+ };
231
+ /**
232
+ * @title: 启动定时任务
233
+ * @description: 在特定时间点执行任务(仅在 scheduledTasks 模块中生效)
234
+ * @param {Task} task
235
+ * @return {*}
236
+ */
237
+ startScheduledTask = (task) => {
238
+ var _a;
239
+ if (!task.scheduled) {
240
+ console.log("Tasks--->", "不是定时任务");
241
+ return;
242
+ }
243
+ if (task.module !== "scheduledTasks") {
244
+ console.warn("Tasks--->", `定时任务只在 scheduledTasks 模块中生效,任务 ${task.id} 将作为普通任务执行`);
245
+ return;
246
+ }
247
+ const nextExecuteTime = this.calculateNextExecuteTime(task);
248
+ if (!nextExecuteTime) {
249
+ console.log("Tasks--->", "定时任务已完成或无下次执行时间", task);
250
+ this.deleteTask({
251
+ module: task.module,
252
+ queueId: task.queueId,
253
+ taskId: task.id
254
+ });
255
+ return;
256
+ }
257
+ const now = (0, import_dayjs.default)();
258
+ const executeTime = (0, import_dayjs.default)(nextExecuteTime);
259
+ const delay = executeTime.diff(now);
260
+ if (delay < 0) {
261
+ console.log("Tasks--->", "执行时间已过,跳过此次执行");
262
+ if (task.scheduled.repeat) {
263
+ const _task = { ...task };
264
+ _task.scheduledResult = {
265
+ count: ((_a = _task.scheduledResult) == null ? void 0 : _a.count) || 0,
266
+ nextExecuteTime
267
+ };
268
+ const newTask = this.updateTask({
269
+ module: task.module,
270
+ queueId: task.queueId,
271
+ taskId: task.id,
272
+ other: _task
273
+ });
274
+ if (newTask) {
275
+ this.startScheduledTask(newTask);
276
+ }
277
+ } else {
278
+ this.deleteTask({
279
+ module: task.module,
280
+ queueId: task.queueId,
281
+ taskId: task.id
282
+ });
283
+ }
284
+ return;
285
+ }
286
+ console.log("Tasks--->", `定时任务将在 ${nextExecuteTime} 执行 (${delay}ms 后)`, task);
287
+ const timerId = setTimeout(async () => {
288
+ var _a2, _b;
289
+ try {
290
+ await this.runTask(task);
291
+ console.log("Tasks--->", "定时任务执行完成", task);
292
+ let _task = { ...task };
293
+ _task.scheduledResult = {
294
+ count: (((_a2 = _task.scheduledResult) == null ? void 0 : _a2.count) || 0) + 1,
295
+ timerId,
296
+ nextExecuteTime
297
+ };
298
+ if ((_b = task.scheduled) == null ? void 0 : _b.repeat) {
299
+ const newTask = this.updateTask({
300
+ module: task.module,
301
+ queueId: task.queueId,
302
+ taskId: task.id,
303
+ other: _task
304
+ });
305
+ if (newTask) {
306
+ this.startScheduledTask(newTask);
307
+ }
308
+ } else {
309
+ this.deleteTask({
310
+ module: task.module,
311
+ queueId: task.queueId,
312
+ taskId: task.id
313
+ });
314
+ }
315
+ } catch (error) {
316
+ this.clearTaskTimer({ timerId });
317
+ console.error("定时任务执行异常", error);
318
+ }
319
+ }, delay);
320
+ this.timerIds.push({ taskId: task.id, timerId });
321
+ };
322
+ /**
323
+ * @title: 启动轮询
324
+ * @description: 根据轮询间隔定期执行任务
325
+ * @param {Task} task
326
+ * @return {*}
327
+ */
328
+ startPolling = (task) => {
329
+ if (!task.polling || !task.polling.interval) {
330
+ console.log("不是轮询任务");
331
+ return;
332
+ }
333
+ const timerId = setTimeout(async () => {
334
+ var _a;
335
+ try {
336
+ await this.runTask(task);
337
+ console.log("轮询任务", task);
338
+ let _task = { ...task };
339
+ _task.pollingResult = {
340
+ count: (((_a = _task.pollingResult) == null ? void 0 : _a.count) || 0) + 1,
341
+ timerId
342
+ };
343
+ const newTask = this.updateTask({
344
+ module: task.module,
345
+ queueId: task.queueId,
346
+ taskId: task.id,
347
+ other: _task
348
+ });
349
+ if (!newTask) {
350
+ return;
351
+ }
352
+ this.startPolling(newTask);
353
+ } catch (error) {
354
+ this.clearTaskTimer({ timerId });
355
+ console.error("轮询任务异常", error);
356
+ }
357
+ }, task.polling.interval);
358
+ this.timerIds.push({ taskId: task.id, timerId });
359
+ };
360
+ /**
361
+ * @title: 创建任务数据
362
+ * @description:
363
+ * @param {Partial} payload
364
+ * @return {*}
365
+ * @Author: zhiwei.Wang
366
+ * @Date: 2024-09-26 13:54
367
+ */
368
+ createTaskData = (payload) => {
369
+ return {
370
+ id: (0, import_utils.getUniqueId)("task_"),
371
+ create_at: (0, import_dayjs.default)().format("YYYY-MM-DD HH:mm:ss"),
372
+ type: "local",
373
+ retries: 0,
374
+ maxRetries: 3,
375
+ status: "pending",
376
+ // 执行函数
377
+ action: "",
378
+ // 执行参数
379
+ payload: {},
380
+ // 执行前的钩子
381
+ beforeAction: "",
382
+ // 执行前的参数
383
+ beforePayload: {},
384
+ // 执行后的钩子
385
+ afterAction: "",
386
+ // 执行后的参数
387
+ afterPayload: {},
388
+ destroy: true,
389
+ ...payload
390
+ };
391
+ };
392
+ getTaskQueue = (payload) => {
393
+ var _a, _b;
394
+ const { queueId, module: module2 } = payload;
395
+ return (_b = (_a = this.tasks[module2]) == null ? void 0 : _a[queueId]) == null ? void 0 : _b.tasks;
396
+ };
397
+ timeout = (ms) => {
398
+ return new Promise((resolve) => {
399
+ setTimeout(() => {
400
+ resolve(true);
401
+ }, ms || 5e3);
402
+ });
403
+ };
404
+ /**
405
+ * @title: 执行任务队列
406
+ * @description:
407
+ * @return {*}
408
+ * @Author: zhiwei.Wang
409
+ * @Date: 2024-09-26 13:52
410
+ */
411
+ async run(payload) {
412
+ var _a, _b, _c, _d, _e;
413
+ const { queueId, module: module2, callback } = payload;
414
+ const currentQueue = (_a = this.tasks[module2]) == null ? void 0 : _a[queueId];
415
+ if (currentQueue == null ? void 0 : currentQueue.isRunning) {
416
+ console.warn(
417
+ "Tasks--->",
418
+ `任务队列 [${module2}/${queueId}] 正在执行中,已拦截重复调用。`,
419
+ `当前进度: ${((_b = currentQueue.progress) == null ? void 0 : _b.completed) || 0}/${((_c = currentQueue.progress) == null ? void 0 : _c.total) || 0}`,
420
+ `如需重新执行,请等待当前任务队列执行完成。`
421
+ );
422
+ return;
423
+ }
424
+ this.updateQueueRunningState({
425
+ module: module2,
426
+ queueId,
427
+ isRunning: true,
428
+ lastRunAt: (0, import_dayjs.default)().format("YYYY-MM-DD HH:mm:ss")
429
+ });
430
+ console.log("Tasks--->", `任务队列 [${module2}/${queueId}] 开始执行`);
431
+ let taskQueueStatus = "";
432
+ try {
433
+ while (taskQueueStatus !== "completed") {
434
+ const taskQueue = this.getTaskQueue(payload);
435
+ const errorTaskIds = [];
436
+ if (taskQueue && taskQueue.length) {
437
+ const tasksToExecute = taskQueue.filter(
438
+ (task) => (task == null ? void 0 : task.status) === "pending" || (task == null ? void 0 : task.status) === "failure"
439
+ );
440
+ console.log("Tasks--->", "需要执行的任务", tasksToExecute);
441
+ for (let task of tasksToExecute) {
442
+ try {
443
+ if (task.retries !== void 0 && task.maxRetries !== void 0 && task.retries < task.maxRetries) {
444
+ task.status = "in-progress";
445
+ this.updateTask({ module: module2, queueId, taskId: task.id, other: { status: task.status } });
446
+ if (task.scheduled && module2 === "scheduledTasks") {
447
+ this.startScheduledTask(task);
448
+ } else if (task.polling) {
449
+ this.startPolling(task);
450
+ } else {
451
+ const { status } = await this.runTask(task);
452
+ task.status = status;
453
+ }
454
+ if (task.status === "success") {
455
+ if ((_d = task.pollingResult) == null ? void 0 : _d.timerId) {
456
+ }
457
+ this.deleteTask({ module: module2, queueId, taskId: task.id });
458
+ } else {
459
+ let _other = {
460
+ status: task.status
461
+ };
462
+ if (task.status === "failure") {
463
+ _other.retries = task.retries + 1;
464
+ }
465
+ errorTaskIds.push(task.id);
466
+ this.updateTask({ module: module2, queueId, taskId: task.id, other: _other });
467
+ }
468
+ } else {
469
+ console.log("Tasks--->", "任务没有重试次数,需要删除", task);
470
+ this.deleteTask({ module: module2, queueId, taskId: task.id });
471
+ }
472
+ } catch (error) {
473
+ console.error("任务异常", error);
474
+ }
475
+ }
476
+ taskQueueStatus = ((_e = this.getTaskQueue(payload)) == null ? void 0 : _e.some((task) => task.status === "failure")) ? "uncompleted" : "completed";
477
+ this.updateQueueStatus({
478
+ queueId,
479
+ module: module2,
480
+ status: taskQueueStatus
481
+ });
482
+ console.log("Tasks--->", "任务队列执行完成", taskQueue);
483
+ } else {
484
+ taskQueueStatus = "completed";
485
+ }
486
+ if (taskQueueStatus === "uncompleted") {
487
+ this.app.logger.addLog({
488
+ type: "info",
489
+ title: `任务队列执行存在失败-${queueId}`,
490
+ metadata: { taskQueue, errorTaskIds }
491
+ });
492
+ await this.timeout();
493
+ } else if (taskQueueStatus === "completed") {
494
+ console.log("Tasks--->", "任务队列全部执行完成");
495
+ callback == null ? void 0 : callback();
496
+ }
497
+ }
498
+ } finally {
499
+ this.updateQueueRunningState({
500
+ module: module2,
501
+ queueId,
502
+ isRunning: false
503
+ });
504
+ console.log("Tasks--->", `任务队列 [${module2}/${queueId}] 执行结束`);
505
+ }
506
+ }
507
+ deleteTask(payload) {
508
+ var _a, _b, _c, _d;
509
+ const { queueId, module: module2, taskId } = payload;
510
+ this.tasks[module2][queueId].tasks = (_d = (_c = (_b = (_a = this.tasks) == null ? void 0 : _a[module2]) == null ? void 0 : _b[queueId]) == null ? void 0 : _c.tasks) == null ? void 0 : _d.filter((task) => {
511
+ var _a2, _b2;
512
+ if (task.id === taskId) {
513
+ if ((_a2 = task.pollingResult) == null ? void 0 : _a2.timerId) {
514
+ this.clearTaskTimer({ timerId: task.pollingResult.timerId });
515
+ }
516
+ if ((_b2 = task.scheduledResult) == null ? void 0 : _b2.timerId) {
517
+ this.clearTaskTimer({ timerId: task.scheduledResult.timerId });
518
+ }
519
+ return false;
520
+ }
521
+ return true;
522
+ });
523
+ this.saveTaskQueueToLocal(this.tasks);
524
+ console.log("Tasks--->", "删除指定任务", queueId, module2, taskId);
525
+ }
526
+ /**
527
+ * @title: 重试任务
528
+ * @description:
529
+ * @return {*}
530
+ * @Author: zhiwei.Wang
531
+ * @Date: 2024-09-26 13:53
532
+ */
533
+ retryTask(payload) {
534
+ const { queueId, module: module2 } = payload;
535
+ this.run({ queueId, module: module2 });
536
+ }
537
+ // 添加任务
538
+ addTask(payload) {
539
+ var _a, _b, _c;
540
+ const { queueId, module: module2, tasks } = payload;
541
+ const taskQueue = (_b = (_a = this.tasks[module2]) == null ? void 0 : _a[queueId]) == null ? void 0 : _b.tasks;
542
+ let _tasks = [...taskQueue || []];
543
+ let newTasks = (_c = tasks == null ? void 0 : tasks.map) == null ? void 0 : _c.call(tasks, (d) => {
544
+ if (d.scheduled && module2 !== "scheduledTasks") {
545
+ console.warn(
546
+ "Tasks--->",
547
+ `检测到定时任务配置,但模块为 "${module2}"。定时任务功能仅在 "scheduledTasks" 模块中生效。`,
548
+ `该任务将作为普通任务立即执行。如需使用定时功能,请将任务添加到 "scheduledTasks" 模块。`
549
+ );
550
+ }
551
+ return this.createTaskData({ ...d, queueId, module: module2 });
552
+ });
553
+ _tasks = _tasks.concat(newTasks);
554
+ this.setTasks({ queueId, module: module2, tasks: _tasks });
555
+ console.log("Tasks--->", `任务添加成功`, newTasks);
556
+ }
557
+ // 更新任务状态
558
+ updateTask(payload) {
559
+ var _a, _b, _c;
560
+ const { queueId, taskId, other, module: module2 } = payload;
561
+ let newTask = null;
562
+ const taskQueue = ((_b = (_a = this.tasks[module2]) == null ? void 0 : _a[queueId]) == null ? void 0 : _b.tasks) || [];
563
+ const updatedTasks = taskQueue.map((task) => {
564
+ if (task.id === taskId) {
565
+ newTask = { ...task, ...other };
566
+ return newTask;
567
+ }
568
+ return task;
569
+ });
570
+ const newState = {
571
+ ...this.tasks,
572
+ [module2]: {
573
+ ...this.tasks[module2],
574
+ [queueId]: {
575
+ ...(_c = this.tasks[module2]) == null ? void 0 : _c[queueId],
576
+ status: updatedTasks.some((task) => task.status === "failure") ? "uncompleted" : "completed",
577
+ tasks: updatedTasks
578
+ }
579
+ }
580
+ };
581
+ this.saveTaskQueueToLocal(newState);
582
+ this.tasks = newState;
583
+ return newTask;
584
+ }
585
+ updateQueueStatus(payload) {
586
+ const { queueId, status, module: module2 } = payload;
587
+ this.setTasksData({ queueId, module: module2, status });
588
+ }
589
+ /**
590
+ * @title: 更新队列运行状态
591
+ * @description: 标记队列是否正在执行
592
+ */
593
+ updateQueueRunningState(payload) {
594
+ const { queueId, module: module2, isRunning, lastRunAt } = payload;
595
+ this.setTasksData({ queueId, module: module2, isRunning, lastRunAt });
596
+ }
597
+ // 设置任务
598
+ setTasksData(payload) {
599
+ const { queueId, module: module2, ...data } = payload;
600
+ const moduleData = this.tasks[module2] || {};
601
+ const queueIdData = moduleData[queueId] || {};
602
+ const newState = {
603
+ ...this.tasks,
604
+ [module2]: {
605
+ ...moduleData,
606
+ [queueId]: {
607
+ ...queueIdData,
608
+ ...data
609
+ }
610
+ }
611
+ };
612
+ this.saveTaskQueueToLocal(newState);
613
+ this.tasks = newState;
614
+ }
615
+ // 设置任务
616
+ setTasks(payload) {
617
+ const { queueId, module: module2, tasks } = payload;
618
+ this.setTasksData({ queueId, module: module2, tasks });
619
+ }
620
+ clearAllTaskTimer(tasks) {
621
+ for (let task of tasks || []) {
622
+ this.clearTaskTimer({ taskId: task.id });
623
+ }
624
+ }
625
+ // 清空任务
626
+ clearTasks(payload) {
627
+ var _a, _b;
628
+ const { queueId, module: module2 } = payload;
629
+ if (!((_b = (_a = this.tasks) == null ? void 0 : _a[module2]) == null ? void 0 : _b[queueId])) {
630
+ return;
631
+ }
632
+ this.clearAllTaskTimer(this.tasks[module2][queueId].tasks);
633
+ this.tasks[module2][queueId].tasks = [];
634
+ this.saveTaskQueueToLocal(this.tasks);
635
+ console.log("Tasks--->", "清空指定任务", queueId, module2);
636
+ }
637
+ // 清空全部任务
638
+ clearAllTasks() {
639
+ this.tasks = {};
640
+ this.saveTaskQueueToLocal(this.tasks);
641
+ if (this.timerIds.length) {
642
+ for (let timerId of this.timerIds) {
643
+ clearTimeout(timerId);
644
+ }
645
+ this.timerIds = [];
646
+ }
647
+ console.log("Tasks--->", "清空全部任务");
648
+ }
649
+ watchTask(callback) {
650
+ this.watchTaskCallback = callback;
651
+ }
652
+ /**
653
+ * @title: 获取队列执行状态
654
+ * @description: 获取指定队列的执行状态和进度信息
655
+ * @param {string} module - 模块名
656
+ * @param {string} queueId - 队列ID
657
+ * @return {object} 队列状态信息
658
+ */
659
+ getQueueStatus(module2, queueId) {
660
+ var _a, _b;
661
+ const queue = (_a = this.tasks[module2]) == null ? void 0 : _a[queueId];
662
+ if (!queue) {
663
+ return null;
664
+ }
665
+ return {
666
+ isRunning: queue.isRunning || false,
667
+ status: queue.status,
668
+ progress: queue.progress || {
669
+ total: 0,
670
+ completed: 0,
671
+ failed: 0,
672
+ inProgress: 0
673
+ },
674
+ lastRunAt: queue.lastRunAt || null,
675
+ tasksCount: ((_b = queue.tasks) == null ? void 0 : _b.length) || 0
676
+ };
677
+ }
678
+ /**
679
+ * @title: 获取所有队列状态
680
+ * @description: 获取所有任务队列的执行状态概览
681
+ * @return {object} 所有队列的状态信息
682
+ */
683
+ getAllQueuesStatus() {
684
+ var _a;
685
+ const result = {};
686
+ for (const module2 in this.tasks) {
687
+ result[module2] = {};
688
+ for (const queueId in this.tasks[module2]) {
689
+ const queue = this.tasks[module2][queueId];
690
+ result[module2][queueId] = {
691
+ isRunning: queue.isRunning || false,
692
+ status: queue.status,
693
+ progress: queue.progress || {
694
+ total: 0,
695
+ completed: 0,
696
+ failed: 0,
697
+ inProgress: 0
698
+ },
699
+ lastRunAt: queue.lastRunAt || null,
700
+ tasksCount: ((_a = queue.tasks) == null ? void 0 : _a.length) || 0
701
+ };
702
+ }
703
+ }
704
+ return result;
705
+ }
706
+ };
707
+ // Annotate the CommonJS export names for ESM import in node:
708
+ 0 && (module.exports = {
709
+ TasksManager
710
+ });