@aomex/cron 0.0.34 → 1.0.1
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/CHANGELOG.md +21 -57
- package/LICENSE +1 -1
- package/dist/index.d.ts +63 -60
- package/dist/index.js +464 -315
- package/dist/index.js.map +1 -1
- package/package.json +17 -16
package/CHANGELOG.md
CHANGED
|
@@ -1,74 +1,38 @@
|
|
|
1
1
|
# @aomex/cron
|
|
2
2
|
|
|
3
|
-
##
|
|
3
|
+
## 1.0.1
|
|
4
4
|
|
|
5
5
|
### Patch Changes
|
|
6
6
|
|
|
7
|
-
-
|
|
8
|
-
- @aomex/core@0.0.28
|
|
9
|
-
- @aomex/commander@0.0.35
|
|
10
|
-
- @aomex/console@0.0.33
|
|
11
|
-
- @aomex/memory-cache@0.0.28
|
|
7
|
+
- [`36effe0`](https://github.com/aomex/aomex/commit/36effe077722d9405c52405e8d5fe1bfe8fdcb33) Thanks [@geekact](https://github.com/geekact)! - fix(cron): 重叠执行失败
|
|
12
8
|
|
|
13
|
-
|
|
9
|
+
- [`a91c073`](https://github.com/aomex/aomex/commit/a91c073f9c4bc546a5d6de793631295a07da4afc) Thanks [@geekact](https://github.com/geekact)! - fix(cron): 使用指令关闭任务时,实时状态无法连接
|
|
14
10
|
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
- [`00bafbb`](https://github.com/aomex/aomex/commit/00bafbbac2d32205b63a6bf561fb0a69c38a54bb) Thanks [@geekact](https://github.com/geekact)! - refactor(core): 缓存迁移到新的包@aomex/internal-cache
|
|
18
|
-
|
|
19
|
-
- [`8becf8e`](https://github.com/aomex/aomex/commit/8becf8ee5ef86a5909783d0654e536db7be9bf5b) Thanks [@geekact](https://github.com/geekact)! - refactor(core): 工具移动到新的包@aomex/internal-tools
|
|
20
|
-
|
|
21
|
-
- [`0776719`](https://github.com/aomex/aomex/commit/077671963401f1dafb5b03722899452d45df13fc) Thanks [@geekact](https://github.com/geekact)! - refactor: 文件搜索转移到新的包@aomex/internal-file-import
|
|
11
|
+
- [`e469c0f`](https://github.com/aomex/aomex/commit/e469c0f6c42fdf84830c2c9746f29c6c1c864400) Thanks [@geekact](https://github.com/geekact)! - feat(cron): toCrontab()列表取消npx前缀
|
|
22
12
|
|
|
23
|
-
-
|
|
24
|
-
- @aomex/memory-cache@0.0.27
|
|
25
|
-
- @aomex/core@0.0.27
|
|
26
|
-
- @aomex/internal-tools@0.0.27
|
|
27
|
-
- @aomex/commander@0.0.34
|
|
28
|
-
- @aomex/console@0.0.32
|
|
29
|
-
- @aomex/internal-file-import@0.0.27
|
|
13
|
+
- [`5deddf5`](https://github.com/aomex/aomex/commit/5deddf59b083cf16f5a57f99fc5a074a5612d303) Thanks [@geekact](https://github.com/geekact)! - fix(cron): 优化监控面板输出文字
|
|
30
14
|
|
|
31
|
-
|
|
15
|
+
- [`8fc16f1`](https://github.com/aomex/aomex/commit/8fc16f10bfc60f4c900e270d2d93fd627ab04421) Thanks [@geekact](https://github.com/geekact)! - fix(cron): 定时任务未启动时,stop和stats不需要抛出异常
|
|
32
16
|
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
- Updated dependencies [[`fbcea3d`](https://github.com/aomex/aomex/commit/fbcea3d68ff033e6861130c645c8e5ad7336193f)]:
|
|
36
|
-
- @aomex/core@0.0.26
|
|
37
|
-
- @aomex/commander@0.0.33
|
|
38
|
-
- @aomex/console@0.0.31
|
|
17
|
+
- [`26ba93c`](https://github.com/aomex/aomex/commit/26ba93c3a9600b278cae98bb52a457f7b68f19dd) Thanks [@geekact](https://github.com/geekact)! - feat(cron)!: 删除cron函数的参数concurrent和overlap
|
|
39
18
|
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
19
|
+
- Updated dependencies []:
|
|
20
|
+
- @aomex/internal-file-import@1.0.1
|
|
21
|
+
- @aomex/internal-tools@1.0.1
|
|
22
|
+
- @aomex/memory-cache@1.0.1
|
|
43
23
|
|
|
44
|
-
|
|
45
|
-
- @aomex/commander@0.0.32
|
|
46
|
-
- @aomex/core@0.0.25
|
|
47
|
-
- @aomex/console@0.0.30
|
|
48
|
-
|
|
49
|
-
## 0.0.30
|
|
50
|
-
|
|
51
|
-
### Patch Changes
|
|
52
|
-
|
|
53
|
-
- Updated dependencies [[`2ac62fd`](https://github.com/aomex/aomex/commit/2ac62fd28166a1d9dd60b3c6d5a6508a6f9ee82b), [`4258410`](https://github.com/aomex/aomex/commit/42584107ad9f7e34492ae1053fef83aa2d9d747a), [`4177cba`](https://github.com/aomex/aomex/commit/4177cba7877e38120842bd8d287eaed54e4926ca)]:
|
|
54
|
-
- @aomex/core@0.0.24
|
|
55
|
-
- @aomex/commander@0.0.31
|
|
56
|
-
- @aomex/console@0.0.29
|
|
57
|
-
|
|
58
|
-
## 0.0.29
|
|
59
|
-
|
|
60
|
-
### Patch Changes
|
|
24
|
+
## 1.0.0
|
|
61
25
|
|
|
62
|
-
|
|
63
|
-
- @aomex/core@0.0.23
|
|
64
|
-
- @aomex/console@0.0.28
|
|
65
|
-
- @aomex/commander@0.0.30
|
|
26
|
+
### Minor Changes
|
|
66
27
|
|
|
67
|
-
|
|
28
|
+
- [`11103a2`](https://github.com/aomex/aomex/commit/11103a2aff4e081754c56b0ff18fa5130ca252e8) Thanks [@geekact](https://github.com/geekact)! - 重新制作
|
|
68
29
|
|
|
69
30
|
### Patch Changes
|
|
70
31
|
|
|
71
|
-
- Updated dependencies [[`
|
|
72
|
-
- @aomex/
|
|
73
|
-
- @aomex/
|
|
74
|
-
- @aomex/
|
|
32
|
+
- Updated dependencies [[`11103a2`](https://github.com/aomex/aomex/commit/11103a2aff4e081754c56b0ff18fa5130ca252e8)]:
|
|
33
|
+
- @aomex/commander@1.0.0
|
|
34
|
+
- @aomex/console@1.0.0
|
|
35
|
+
- @aomex/core@1.0.0
|
|
36
|
+
- @aomex/internal-file-import@1.0.0
|
|
37
|
+
- @aomex/internal-tools@1.0.0
|
|
38
|
+
- @aomex/memory-cache@1.0.0
|
package/LICENSE
CHANGED
package/dist/index.d.ts
CHANGED
|
@@ -1,31 +1,35 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
3
|
-
import {
|
|
1
|
+
import { I18nFormat } from '@aomex/core';
|
|
2
|
+
import { ConsoleMiddlewareChain, ConsoleMiddleware } from '@aomex/console';
|
|
3
|
+
import { GlobPathOptions } from '@aomex/internal-file-import';
|
|
4
|
+
|
|
5
|
+
declare module '@aomex/core' {
|
|
6
|
+
namespace I18n {
|
|
7
|
+
interface Definition {
|
|
8
|
+
cron: {
|
|
9
|
+
eject: I18nFormat;
|
|
10
|
+
start: I18nFormat;
|
|
11
|
+
stop: I18nFormat;
|
|
12
|
+
stats: I18nFormat;
|
|
13
|
+
not_started: I18nFormat<{
|
|
14
|
+
port: number;
|
|
15
|
+
}>;
|
|
16
|
+
use_stop: I18nFormat;
|
|
17
|
+
};
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
}
|
|
4
21
|
|
|
5
22
|
interface CronOptions {
|
|
6
|
-
path:
|
|
23
|
+
path: GlobPathOptions;
|
|
7
24
|
/**
|
|
8
|
-
*
|
|
25
|
+
* 集群服务共享状态。默认值:`MemoryCache`
|
|
9
26
|
*/
|
|
10
|
-
|
|
27
|
+
store?: CronStore;
|
|
11
28
|
/**
|
|
12
|
-
*
|
|
13
|
-
* - true: 竞赛,只有一个服务可获得某个任务
|
|
14
|
-
* - false: 每个服务都可以获得某个任务
|
|
29
|
+
* 服务端口。默认值:`9786`
|
|
15
30
|
*/
|
|
16
|
-
|
|
17
|
-
/**
|
|
18
|
-
* 任务重叠执行。默认值:`true`
|
|
19
|
-
* - true: 某个任务触发后立即执行。适合允许并发操作的场景
|
|
20
|
-
*
|
|
21
|
-
* - false: 当前被触发的任务,需要等上一次被触发的任务执行完毕后才能执行。场景:
|
|
22
|
-
* 防止数据相互覆盖,防止重复生成数据,防止重复发送通知
|
|
23
|
-
*
|
|
24
|
-
*/
|
|
25
|
-
overlap?: boolean;
|
|
31
|
+
port?: number;
|
|
26
32
|
}
|
|
27
|
-
declare const cron: (options: string | CronOptions) => ConsoleChain;
|
|
28
|
-
|
|
29
33
|
interface ScheduleTimeObject {
|
|
30
34
|
/**
|
|
31
35
|
* 0-59
|
|
@@ -56,6 +60,8 @@ interface ScheduleTimeObject {
|
|
|
56
60
|
}
|
|
57
61
|
interface ScheduleTimeString {
|
|
58
62
|
/**
|
|
63
|
+
* 如果想验证时间表达式,可访问 https://crontab.guru
|
|
64
|
+
*
|
|
59
65
|
类似linux下cron的时间格式,并支持秒级时间
|
|
60
66
|
```
|
|
61
67
|
┌────────────── second (optional)
|
|
@@ -70,7 +76,8 @@ interface ScheduleTimeString {
|
|
|
70
76
|
*/
|
|
71
77
|
time: string;
|
|
72
78
|
}
|
|
73
|
-
|
|
79
|
+
type ScheduleTime = ScheduleTimeObject | ScheduleTimeString;
|
|
80
|
+
type ScheduleOptions = (ScheduleTimeObject | ScheduleTimeString) & {
|
|
74
81
|
/**
|
|
75
82
|
* 执行时附带的参数,使用`options`接收
|
|
76
83
|
*
|
|
@@ -78,55 +85,51 @@ interface ScheduleBaseOptions {
|
|
|
78
85
|
*/
|
|
79
86
|
args?: (string | number)[];
|
|
80
87
|
/**
|
|
81
|
-
*
|
|
82
|
-
* - true: 竞赛,只有一个服务可获得某个任务
|
|
83
|
-
* - false: 每个服务都可以获得某个任务
|
|
88
|
+
* 同一个时间点的任务能被并发执行的数量。默认值:`1`
|
|
84
89
|
*
|
|
85
|
-
*
|
|
90
|
+
* 注意:一个服务只能执行一次。并发数量 <= 集群数量。
|
|
91
|
+
*
|
|
92
|
+
* 如果想在所有集群上都执行,则设置为`Infinity`
|
|
86
93
|
*/
|
|
87
|
-
|
|
94
|
+
concurrent?: number;
|
|
88
95
|
/**
|
|
89
|
-
*
|
|
90
|
-
* - true: 某个任务触发后立即执行。适合允许并发操作的场景
|
|
91
|
-
*
|
|
92
|
-
* - false: 当前被触发的任务,需要等上一次被触发的任务执行完毕后才能执行。场景:
|
|
93
|
-
* 防止数据相互覆盖,防止重复生成数据,防止重复发送通知
|
|
96
|
+
* 任务能否重叠执行。默认值:`false`
|
|
94
97
|
*
|
|
95
|
-
*
|
|
98
|
+
* - `true`,当前时间点任务无需等待上一个任务完成,即允许重叠。
|
|
99
|
+
* - `false`,当前时间点任务被触发时,如果上一个时间点任务尚未完成,则当前时间点任务会被忽略。
|
|
96
100
|
*/
|
|
97
|
-
overlap?:
|
|
101
|
+
overlap?: boolean;
|
|
102
|
+
};
|
|
103
|
+
interface CronStore {
|
|
104
|
+
get(key: string): Promise<string | null>;
|
|
105
|
+
set(key: string, value: string, duration?: number): Promise<boolean>;
|
|
106
|
+
add(key: string, value: string, duration?: number): Promise<boolean>;
|
|
107
|
+
increment(key: string): Promise<number>;
|
|
108
|
+
decrement(key: string): Promise<number>;
|
|
109
|
+
expires(key: string, duration: number): Promise<boolean>;
|
|
98
110
|
}
|
|
99
|
-
type
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
protected _argv?: string[];
|
|
107
|
-
constructor(options: ScheduleOptions & {
|
|
108
|
-
command: string;
|
|
109
|
-
});
|
|
110
|
-
get overlap(): CronOptions['overlap'] | undefined;
|
|
111
|
-
get race(): CronOptions['race'] | undefined;
|
|
112
|
-
get time(): string;
|
|
113
|
-
get argv(): string[];
|
|
114
|
-
get seconds(): number[];
|
|
115
|
-
toCrontab(): string[];
|
|
116
|
-
toJSON(): {
|
|
117
|
-
time: string;
|
|
118
|
-
seconds: number[];
|
|
111
|
+
type ServerWriteData = {
|
|
112
|
+
list: string[];
|
|
113
|
+
} | {
|
|
114
|
+
done: string;
|
|
115
|
+
} | {
|
|
116
|
+
runners: {
|
|
117
|
+
pid: string;
|
|
119
118
|
argv: string[];
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
119
|
+
}[];
|
|
120
|
+
};
|
|
121
|
+
|
|
122
|
+
declare const cron: (options: string | CronOptions) => ConsoleMiddlewareChain;
|
|
124
123
|
|
|
125
124
|
declare class ScheduleMiddleware extends ConsoleMiddleware<object> {
|
|
126
125
|
protected readonly options: ScheduleOptions;
|
|
127
126
|
constructor(options: ScheduleOptions);
|
|
128
|
-
getSchedule(command: string): Schedule;
|
|
129
127
|
}
|
|
128
|
+
/**
|
|
129
|
+
* 创建一个定时任务
|
|
130
|
+
*
|
|
131
|
+
* 如果传递字符串,则为cron时间表达式(支持秒)。如:`1-10,20 * * * *`
|
|
132
|
+
*/
|
|
130
133
|
declare const schedule: (options: ScheduleOptions | string) => ScheduleMiddleware;
|
|
131
134
|
|
|
132
|
-
export { CronOptions, ScheduleMiddleware, cron, schedule };
|
|
135
|
+
export { type CronOptions, type CronStore, ScheduleMiddleware, type ScheduleOptions, type ScheduleTime, type ScheduleTimeObject, type ScheduleTimeString, type ServerWriteData, cron, schedule };
|
package/dist/index.js
CHANGED
|
@@ -1,150 +1,139 @@
|
|
|
1
|
-
// src/
|
|
2
|
-
import {
|
|
1
|
+
// src/i18n/locales/zh-cn.ts
|
|
2
|
+
import { i18n } from "@aomex/core";
|
|
3
|
+
i18n.register("zh_CN", "cron", {
|
|
4
|
+
eject: "\u5BFC\u51FA\u5B9A\u65F6\u4EFB\u52A1\u5217\u8868",
|
|
5
|
+
start: "\u542F\u52A8\u5B9A\u65F6\u4EFB\u52A1",
|
|
6
|
+
stop: "\u9000\u51FA\u5B9A\u65F6\u4EFB\u52A1",
|
|
7
|
+
stats: "\u67E5\u770B\u5B9A\u65F6\u4EFB\u52A1\u6267\u884C\u72B6\u6001",
|
|
8
|
+
not_started: "\u5B9A\u65F6\u4EFB\u52A1\u672A\u542F\u52A8\uFF0C\u7AEF\u53E3\uFF1A{{port}}",
|
|
9
|
+
use_stop: '\u6267\u884C\u4E2D\u7684\u4EFB\u52A1\u4E5F\u4F1A\u88AB\u5F3A\u5236\u4E2D\u65AD\uFF0C\u56E0\u6B64\u63A8\u8350\u4F7F\u7528\u6307\u4EE4 "aomex cron:stop" \u7ED3\u675F\u5B9A\u65F6\u4EFB\u52A1'
|
|
10
|
+
});
|
|
11
|
+
|
|
12
|
+
// src/i18n/locales/en-us.ts
|
|
13
|
+
import { i18n as i18n2 } from "@aomex/core";
|
|
14
|
+
i18n2.register("en_US", "cron", {
|
|
15
|
+
eject: "Eject cron jobs list",
|
|
16
|
+
start: "Start cron jobs",
|
|
17
|
+
stop: "Stop cron jobs",
|
|
18
|
+
stats: "Show cron jobs stats",
|
|
19
|
+
not_started: "cron not started with port: {{port}}",
|
|
20
|
+
use_stop: 'Recommend using command "aomex cron:stop" to stop cron in favor of waiting executing jobs'
|
|
21
|
+
});
|
|
22
|
+
|
|
23
|
+
// src/middleware/cron.middleware.ts
|
|
24
|
+
import { mdchain } from "@aomex/core";
|
|
3
25
|
|
|
4
|
-
// src/middleware/
|
|
5
|
-
import {
|
|
6
|
-
import { chain, middleware as middleware2, rule } from "@aomex/core";
|
|
7
|
-
import { mkdir, writeFile } from "node:fs/promises";
|
|
8
|
-
import path, { dirname } from "node:path";
|
|
26
|
+
// src/middleware/start.middleware.ts
|
|
27
|
+
import { i18n as i18n3, middleware } from "@aomex/core";
|
|
9
28
|
|
|
10
|
-
// src/lib/
|
|
29
|
+
// src/lib/collect-schedule.ts
|
|
11
30
|
import { Commander } from "@aomex/commander";
|
|
12
|
-
import {
|
|
13
|
-
import {
|
|
14
|
-
fileToModules,
|
|
15
|
-
pathToFiles
|
|
16
|
-
} from "@aomex/internal-file-import";
|
|
31
|
+
import { pathToFiles, getFileValues } from "@aomex/internal-file-import";
|
|
17
32
|
|
|
18
|
-
// src/middleware/schedule.ts
|
|
33
|
+
// src/middleware/schedule.middleware.ts
|
|
19
34
|
import { ConsoleMiddleware } from "@aomex/console";
|
|
35
|
+
var ScheduleMiddleware = class extends ConsoleMiddleware {
|
|
36
|
+
constructor(options) {
|
|
37
|
+
super(async (_, next) => next());
|
|
38
|
+
this.options = options;
|
|
39
|
+
}
|
|
40
|
+
};
|
|
41
|
+
var schedule = (options) => {
|
|
42
|
+
return new ScheduleMiddleware(
|
|
43
|
+
typeof options === "string" ? { time: options } : options
|
|
44
|
+
);
|
|
45
|
+
};
|
|
20
46
|
|
|
21
|
-
// src/lib/schedule.ts
|
|
47
|
+
// src/lib/schedule-parser.ts
|
|
22
48
|
import { scriptName } from "@aomex/console";
|
|
23
|
-
import
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
49
|
+
import { MemoryCache } from "@aomex/memory-cache";
|
|
50
|
+
import cronParser from "cron-parser";
|
|
51
|
+
var ScheduleParser = class {
|
|
52
|
+
constructor(options) {
|
|
53
|
+
this.options = options;
|
|
27
54
|
}
|
|
28
55
|
_time;
|
|
29
56
|
_seconds;
|
|
30
57
|
_argv;
|
|
58
|
+
_store;
|
|
59
|
+
get command() {
|
|
60
|
+
return this.options.command;
|
|
61
|
+
}
|
|
31
62
|
get overlap() {
|
|
32
|
-
return this.options.overlap;
|
|
63
|
+
return this.options.overlap ?? false;
|
|
64
|
+
}
|
|
65
|
+
get concurrent() {
|
|
66
|
+
return Math.max(1, this.options.concurrent || 1);
|
|
33
67
|
}
|
|
34
|
-
get
|
|
35
|
-
return this.options.
|
|
68
|
+
get store() {
|
|
69
|
+
return this._store ??= this.options.store || new MemoryCache();
|
|
36
70
|
}
|
|
37
71
|
get time() {
|
|
38
72
|
return this._time ??= (() => {
|
|
39
|
-
const { options
|
|
40
|
-
if ("time" in
|
|
41
|
-
const
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
default:
|
|
49
|
-
throw new Error(`Invalid cron time: "${options2.time}"`);
|
|
73
|
+
const { options } = this;
|
|
74
|
+
if ("time" in options) {
|
|
75
|
+
const expression = options.time;
|
|
76
|
+
try {
|
|
77
|
+
const handle = cronParser.parseExpression(expression);
|
|
78
|
+
const arr2 = expression.split(/\s+/);
|
|
79
|
+
return arr2.length < 5 ? handle.stringify(false) : arr2.join(" ");
|
|
80
|
+
} catch {
|
|
81
|
+
throw new Error(`\u65F6\u95F4\u8868\u8FBE\u5F0F\u4E0D\u5408\u6CD5\uFF1A${expression}`);
|
|
50
82
|
}
|
|
51
83
|
}
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
]
|
|
84
|
+
const arr = [
|
|
85
|
+
options.minute ?? "*",
|
|
86
|
+
options.hour ?? "*",
|
|
87
|
+
options.dayOfMonth ?? "*",
|
|
88
|
+
options.month ?? "*",
|
|
89
|
+
options.dayOfWeek ?? "*"
|
|
90
|
+
];
|
|
91
|
+
options.second && arr.unshift(options.second);
|
|
92
|
+
return arr.join(" ");
|
|
59
93
|
})();
|
|
60
94
|
}
|
|
61
95
|
get argv() {
|
|
62
|
-
return this._argv ??= [
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
].map(String);
|
|
66
|
-
}
|
|
67
|
-
get seconds() {
|
|
68
|
-
return this._seconds ??= (() => {
|
|
69
|
-
const { options: options2 } = this;
|
|
70
|
-
let second;
|
|
71
|
-
if ("time" in options2) {
|
|
72
|
-
const timeList = options2.time.split(/\s+/);
|
|
73
|
-
if (timeList.length === 6) {
|
|
74
|
-
second = timeList[0];
|
|
75
|
-
}
|
|
76
|
-
} else {
|
|
77
|
-
second = options2.second?.toString();
|
|
78
|
-
}
|
|
79
|
-
if (!second)
|
|
80
|
-
return [];
|
|
81
|
-
const seconds = [];
|
|
82
|
-
const interval = parser.parseExpression(`${second} * * * *`);
|
|
83
|
-
while (true) {
|
|
84
|
-
const nextSecond = interval.next().getMinutes();
|
|
85
|
-
if (seconds.includes(nextSecond))
|
|
86
|
-
break;
|
|
87
|
-
seconds.push(nextSecond);
|
|
88
|
-
}
|
|
89
|
-
return seconds.sort((a, b) => a - b);
|
|
90
|
-
})();
|
|
96
|
+
return this._argv ??= [this.options.command, ...this.options.args || []].map(
|
|
97
|
+
String
|
|
98
|
+
);
|
|
91
99
|
}
|
|
92
100
|
toCrontab() {
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
if (crons.length === 0) {
|
|
99
|
-
crons.push(script);
|
|
100
|
-
}
|
|
101
|
-
return crons.map((time) => {
|
|
102
|
-
const argv = this.argv.map(
|
|
103
|
-
(value) => value.includes(" ") ? `"${value}"` : value
|
|
104
|
-
);
|
|
105
|
-
return time.concat(["npx", scriptName, ...argv]).join(" ");
|
|
106
|
-
});
|
|
101
|
+
return [
|
|
102
|
+
this.time,
|
|
103
|
+
scriptName,
|
|
104
|
+
...this.argv.map((value) => value.includes(" ") ? `"${value}"` : value)
|
|
105
|
+
].join(" ");
|
|
107
106
|
}
|
|
108
107
|
toJSON() {
|
|
109
108
|
return {
|
|
109
|
+
command: this.command,
|
|
110
110
|
time: this.time,
|
|
111
|
-
seconds: this.seconds,
|
|
112
111
|
argv: this.argv,
|
|
113
|
-
|
|
112
|
+
concurrent: this.concurrent,
|
|
114
113
|
overlap: this.overlap
|
|
115
114
|
};
|
|
116
115
|
}
|
|
117
116
|
};
|
|
118
117
|
|
|
119
|
-
// src/
|
|
120
|
-
var
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
this.options = options2;
|
|
124
|
-
}
|
|
125
|
-
getSchedule(command) {
|
|
126
|
-
return new Schedule({ ...this.options, command });
|
|
127
|
-
}
|
|
128
|
-
};
|
|
129
|
-
var schedule = (options2) => {
|
|
130
|
-
return new ScheduleMiddleware(
|
|
131
|
-
typeof options2 === "string" ? { time: options2 } : options2
|
|
132
|
-
);
|
|
133
|
-
};
|
|
134
|
-
|
|
135
|
-
// src/lib/get-middleware-schedule.ts
|
|
136
|
-
var getMiddlewareSchedule = async (paths) => {
|
|
137
|
-
const files = await pathToFiles(paths);
|
|
138
|
-
const commanders = await fileToModules(
|
|
118
|
+
// src/lib/collect-schedule.ts
|
|
119
|
+
var collectSchedules = async (opts) => {
|
|
120
|
+
const files = await pathToFiles(opts.path);
|
|
121
|
+
const commanders = await getFileValues(
|
|
139
122
|
files,
|
|
140
123
|
(item) => !!item && item instanceof Commander
|
|
141
124
|
);
|
|
142
125
|
const schedules = [];
|
|
143
126
|
for (const commander of commanders) {
|
|
144
127
|
for (const builder of commander["builders"]) {
|
|
145
|
-
for (const middleware5 of
|
|
128
|
+
for (const middleware5 of builder["middlewareList"]) {
|
|
146
129
|
if (middleware5 instanceof ScheduleMiddleware) {
|
|
147
|
-
schedules.push(
|
|
130
|
+
schedules.push(
|
|
131
|
+
new ScheduleParser({
|
|
132
|
+
...opts,
|
|
133
|
+
...middleware5["options"],
|
|
134
|
+
command: builder.commands[0]
|
|
135
|
+
})
|
|
136
|
+
);
|
|
148
137
|
}
|
|
149
138
|
}
|
|
150
139
|
}
|
|
@@ -152,243 +141,403 @@ var getMiddlewareSchedule = async (paths) => {
|
|
|
152
141
|
return schedules;
|
|
153
142
|
};
|
|
154
143
|
|
|
155
|
-
// src/middleware/eject-to-help.ts
|
|
156
|
-
import { scriptName as scriptName2 } from "@aomex/console";
|
|
157
|
-
import { middleware } from "@aomex/core";
|
|
158
|
-
import { chalk } from "@aomex/internal-tools";
|
|
159
|
-
var ejectToHelp = (commandName) => middleware.help(async (ctx, next) => {
|
|
160
|
-
return ctx.cli.config({
|
|
161
|
-
all(yargs) {
|
|
162
|
-
yargs.command(chalk.yellow(commandName), "Create cron-compatibly list");
|
|
163
|
-
},
|
|
164
|
-
detail(yargs) {
|
|
165
|
-
yargs.usage(`${scriptName2} ${commandName} [options]`);
|
|
166
|
-
ejectRule.toHelp(yargs);
|
|
167
|
-
},
|
|
168
|
-
next,
|
|
169
|
-
detailCommand: commandName
|
|
170
|
-
});
|
|
171
|
-
});
|
|
172
|
-
|
|
173
|
-
// src/middleware/eject.ts
|
|
174
|
-
import { chalk as chalk2 } from "@aomex/internal-tools";
|
|
175
|
-
var exportCron = "cron:eject";
|
|
176
|
-
var ejectRule = options(
|
|
177
|
-
{
|
|
178
|
-
output: rule.string().optional().docs({
|
|
179
|
-
description: "Export to specific file"
|
|
180
|
-
})
|
|
181
|
-
},
|
|
182
|
-
{
|
|
183
|
-
output: ["o"]
|
|
184
|
-
}
|
|
185
|
-
);
|
|
186
|
-
var eject = (paths) => chain.console.mount(ejectToHelp(exportCron)).mount(ejectRule).mount(
|
|
187
|
-
middleware2.console(
|
|
188
|
-
async (ctx, next) => {
|
|
189
|
-
if (ctx.request.command !== exportCron) {
|
|
190
|
-
Reflect.deleteProperty(ctx, "options");
|
|
191
|
-
return next();
|
|
192
|
-
}
|
|
193
|
-
ctx.response.commandMatched = true;
|
|
194
|
-
const schedules = await getMiddlewareSchedule(paths);
|
|
195
|
-
const crons = schedules.map((schedule2) => schedule2.toCrontab()).flat();
|
|
196
|
-
const { output: outputToFile } = ctx.options;
|
|
197
|
-
if (outputToFile) {
|
|
198
|
-
const file = path.resolve(outputToFile);
|
|
199
|
-
await mkdir(dirname(file), { recursive: true });
|
|
200
|
-
await writeFile(file, crons.join("\n"), {});
|
|
201
|
-
console.log(`Crontab has been created: ${chalk2.blue(file)}`);
|
|
202
|
-
} else {
|
|
203
|
-
console.log(crons.join("\n"));
|
|
204
|
-
}
|
|
205
|
-
}
|
|
206
|
-
)
|
|
207
|
-
);
|
|
208
|
-
|
|
209
|
-
// src/middleware/run.ts
|
|
210
|
-
import { middleware as middleware4, chain as chain2 } from "@aomex/core";
|
|
211
|
-
import { MemoryCache } from "@aomex/memory-cache";
|
|
212
|
-
|
|
213
|
-
// src/middleware/run-to-help.ts
|
|
214
|
-
import { middleware as middleware3 } from "@aomex/core";
|
|
215
|
-
import { chalk as chalk3 } from "@aomex/internal-tools";
|
|
216
|
-
import { scriptName as scriptName3 } from "@aomex/console";
|
|
217
|
-
var runToHelp = (commandName) => middleware3.help(async (ctx, next) => {
|
|
218
|
-
ctx.cli.config({
|
|
219
|
-
all(yargs) {
|
|
220
|
-
yargs.command(chalk3.yellow(commandName), "Star cron jobs");
|
|
221
|
-
},
|
|
222
|
-
detail(yargs) {
|
|
223
|
-
yargs.usage(`${scriptName3} ${commandName} [options]`);
|
|
224
|
-
},
|
|
225
|
-
detailCommand: commandName,
|
|
226
|
-
next
|
|
227
|
-
});
|
|
228
|
-
});
|
|
229
|
-
|
|
230
144
|
// src/lib/job.ts
|
|
231
|
-
import
|
|
232
|
-
import {
|
|
145
|
+
import cronParser2 from "cron-parser";
|
|
146
|
+
import { spawn } from "node:child_process";
|
|
233
147
|
var Job = class {
|
|
234
|
-
constructor(
|
|
235
|
-
this.app = app;
|
|
148
|
+
constructor(schedule2) {
|
|
236
149
|
this.schedule = schedule2;
|
|
237
|
-
this.
|
|
238
|
-
this.
|
|
150
|
+
this.cronExpression = cronParser2.parseExpression(this.schedule.time);
|
|
151
|
+
this.store = schedule2.store;
|
|
152
|
+
this.processData = {
|
|
153
|
+
execArgv: [...process.execArgv],
|
|
154
|
+
node: process.argv0,
|
|
155
|
+
filePath: process.argv[1],
|
|
156
|
+
cwd: process.cwd(),
|
|
157
|
+
env: process.env
|
|
158
|
+
};
|
|
239
159
|
}
|
|
240
|
-
|
|
160
|
+
runningLevel = 0;
|
|
161
|
+
cronExpression;
|
|
162
|
+
store;
|
|
163
|
+
handle = null;
|
|
164
|
+
stopping = false;
|
|
165
|
+
processData;
|
|
166
|
+
childPIDs = /* @__PURE__ */ new Set();
|
|
241
167
|
async start() {
|
|
242
|
-
|
|
168
|
+
if (!this.cronExpression.hasNext())
|
|
169
|
+
return;
|
|
170
|
+
const nextTime = this.cronExpression.next().getTime();
|
|
243
171
|
while (true) {
|
|
244
|
-
const
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
this.winJob(uniqueKey).then((isWinner) => {
|
|
251
|
-
isWinner && (++this.jobAmount, this.consume());
|
|
252
|
-
});
|
|
253
|
-
}
|
|
254
|
-
if (!handle.hasNext())
|
|
172
|
+
const delta = Math.min(36e5, nextTime - Date.now());
|
|
173
|
+
await this.delay(delta);
|
|
174
|
+
if (this.stopping)
|
|
175
|
+
return;
|
|
176
|
+
if (nextTime - Date.now() <= 0) {
|
|
177
|
+
this.consume(nextTime);
|
|
255
178
|
break;
|
|
256
|
-
}
|
|
257
|
-
}
|
|
258
|
-
emitBySeconds(key) {
|
|
259
|
-
const nowSecond = (/* @__PURE__ */ new Date()).getSeconds();
|
|
260
|
-
for (const nextSecond of this.schedule.seconds) {
|
|
261
|
-
const delay = nextSecond - nowSecond;
|
|
262
|
-
if (delay >= 0) {
|
|
263
|
-
sleep(delay * 1e3).then(async () => {
|
|
264
|
-
const isWinner = await this.winJob(key + `second:${nextSecond};`);
|
|
265
|
-
isWinner && (++this.jobAmount, this.consume());
|
|
266
|
-
});
|
|
267
179
|
}
|
|
268
180
|
}
|
|
181
|
+
return this.start();
|
|
269
182
|
}
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
183
|
+
delay(delta) {
|
|
184
|
+
return new Promise((resolve) => {
|
|
185
|
+
const timer = setTimeout(() => {
|
|
186
|
+
this.handle = null;
|
|
187
|
+
resolve(void 0);
|
|
188
|
+
}, delta);
|
|
189
|
+
this.handle = { timer, resolve };
|
|
190
|
+
});
|
|
276
191
|
}
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
if (this.
|
|
280
|
-
|
|
192
|
+
stop() {
|
|
193
|
+
this.stopping = true;
|
|
194
|
+
if (this.handle) {
|
|
195
|
+
clearTimeout(this.handle.timer);
|
|
196
|
+
this.handle.resolve();
|
|
281
197
|
}
|
|
282
|
-
return cronParser.parseExpression(this.schedule.time, {
|
|
283
|
-
currentDate: now
|
|
284
|
-
});
|
|
285
198
|
}
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
return;
|
|
289
|
-
await this.app.run(...this.schedule.argv);
|
|
290
|
-
--this.jobAmount;
|
|
199
|
+
getPIDs() {
|
|
200
|
+
return [...this.childPIDs];
|
|
291
201
|
}
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
if (this.jobAmount === 0)
|
|
306
|
-
return;
|
|
307
|
-
await this.ping();
|
|
308
|
-
if (await this.winQueue()) {
|
|
309
|
-
let pingTimer;
|
|
310
|
-
try {
|
|
311
|
-
pingTimer = setInterval(() => this.ping(), THREE_SECOND);
|
|
312
|
-
await super.consume();
|
|
313
|
-
} finally {
|
|
314
|
-
clearInterval(pingTimer);
|
|
315
|
-
await this.releaseQueue();
|
|
316
|
-
this.waiting();
|
|
202
|
+
async consume(nextTime) {
|
|
203
|
+
try {
|
|
204
|
+
++this.runningLevel;
|
|
205
|
+
const jobKey = this.getUniqueKey(nextTime);
|
|
206
|
+
const isWinner = await this.win(jobKey);
|
|
207
|
+
if (isWinner) {
|
|
208
|
+
const pong = this.ping(jobKey);
|
|
209
|
+
try {
|
|
210
|
+
await this.runChildProcess();
|
|
211
|
+
} finally {
|
|
212
|
+
pong();
|
|
213
|
+
await this.done(jobKey);
|
|
214
|
+
}
|
|
317
215
|
}
|
|
318
|
-
}
|
|
319
|
-
this.
|
|
216
|
+
} finally {
|
|
217
|
+
--this.runningLevel;
|
|
320
218
|
}
|
|
321
219
|
}
|
|
322
|
-
async
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
{
|
|
333
|
-
const winnerJobId = await this.driver.get(this.jobKey);
|
|
334
|
-
if (winnerJobId === null)
|
|
335
|
-
return this.winQueue();
|
|
336
|
-
const winnerNotDead = await this.driver.exists(
|
|
337
|
-
this.getPingKey(winnerJobId)
|
|
220
|
+
async runChildProcess() {
|
|
221
|
+
return new Promise((resolve) => {
|
|
222
|
+
const childProcess = spawn(
|
|
223
|
+
this.processData.node,
|
|
224
|
+
[...this.processData.execArgv, this.processData.filePath, ...this.schedule.argv],
|
|
225
|
+
{
|
|
226
|
+
cwd: this.processData.cwd,
|
|
227
|
+
env: this.processData.env,
|
|
228
|
+
stdio: "pipe"
|
|
229
|
+
}
|
|
338
230
|
);
|
|
339
|
-
|
|
231
|
+
const pid = childProcess.pid?.toString();
|
|
232
|
+
pid && this.childPIDs.add(pid);
|
|
233
|
+
childProcess.stdout.pipe(process.stdout);
|
|
234
|
+
childProcess.stderr.pipe(process.stderr);
|
|
235
|
+
childProcess.on("close", () => {
|
|
236
|
+
pid && this.childPIDs.delete(pid);
|
|
237
|
+
resolve(void 0);
|
|
238
|
+
});
|
|
239
|
+
});
|
|
240
|
+
}
|
|
241
|
+
async win(jobKey) {
|
|
242
|
+
if (!this.schedule.overlap) {
|
|
243
|
+
let runningJobKey = await this.store.get(this.runningKey);
|
|
244
|
+
if (!runningJobKey) {
|
|
245
|
+
await this.store.add(this.runningKey, jobKey, 1e4);
|
|
246
|
+
runningJobKey = await this.store.get(this.runningKey);
|
|
247
|
+
}
|
|
248
|
+
if (runningJobKey !== jobKey)
|
|
340
249
|
return false;
|
|
341
250
|
}
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
);
|
|
348
|
-
|
|
349
|
-
|
|
251
|
+
const index = await this.store.increment(jobKey);
|
|
252
|
+
return index <= this.schedule.concurrent;
|
|
253
|
+
}
|
|
254
|
+
ping(jobKey) {
|
|
255
|
+
const timer = setInterval(() => {
|
|
256
|
+
this.store.set(this.runningKey, jobKey, 1e4);
|
|
257
|
+
}, 3e3);
|
|
258
|
+
return () => clearInterval(timer);
|
|
259
|
+
}
|
|
260
|
+
async done(jobKey) {
|
|
261
|
+
const doneKey = jobKey + ":done";
|
|
262
|
+
const count = await this.store.increment(doneKey);
|
|
263
|
+
if (count === this.schedule.concurrent) {
|
|
264
|
+
await Promise.all([
|
|
265
|
+
this.store.expires(this.runningKey, -1),
|
|
266
|
+
this.store.expires(jobKey, 72e5),
|
|
267
|
+
this.store.expires(doneKey, 72e5)
|
|
268
|
+
]);
|
|
350
269
|
}
|
|
351
270
|
}
|
|
352
|
-
|
|
353
|
-
|
|
271
|
+
getUniqueKey(timestamp) {
|
|
272
|
+
return `cron-job|argv:${this.schedule.argv};expression:${this.schedule.time};now:${timestamp};`;
|
|
354
273
|
}
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
return;
|
|
358
|
-
this.queueTimer ??= setTimeout(() => {
|
|
359
|
-
this.queueTimer = null;
|
|
360
|
-
this.consume();
|
|
361
|
-
}, 500);
|
|
274
|
+
get runningKey() {
|
|
275
|
+
return this.getUniqueKey(-1);
|
|
362
276
|
}
|
|
363
277
|
};
|
|
364
278
|
|
|
365
|
-
// src/middleware/
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
279
|
+
// src/middleware/start.middleware.ts
|
|
280
|
+
import net from "node:net";
|
|
281
|
+
|
|
282
|
+
// src/lib/constant.ts
|
|
283
|
+
var DEFAULT_PORT = 9786;
|
|
284
|
+
var CONNECT_REFUSED = "ECONNREFUSED";
|
|
285
|
+
|
|
286
|
+
// src/middleware/start.middleware.ts
|
|
287
|
+
import { chalk } from "@aomex/internal-tools";
|
|
288
|
+
var commandName = "cron:start";
|
|
289
|
+
var start = (opts) => {
|
|
290
|
+
return middleware.console({
|
|
291
|
+
fn: async (ctx, next) => {
|
|
292
|
+
if (ctx.input.command !== commandName)
|
|
293
|
+
return next();
|
|
294
|
+
ctx.commandMatched = true;
|
|
295
|
+
const schedules = await collectSchedules(opts);
|
|
296
|
+
if (!schedules.length)
|
|
297
|
+
return;
|
|
298
|
+
const jobs = schedules.map((schedule2) => new Job(schedule2));
|
|
299
|
+
const stopJobs = async (callback) => {
|
|
300
|
+
jobs.forEach((job) => job.stop());
|
|
301
|
+
let remain = jobs.length;
|
|
302
|
+
await Promise.all(
|
|
303
|
+
jobs.map((job) => {
|
|
304
|
+
return new Promise((resolve) => {
|
|
305
|
+
const timer = setInterval(() => {
|
|
306
|
+
if (!job.runningLevel) {
|
|
307
|
+
clearInterval(timer);
|
|
308
|
+
resolve(void 0);
|
|
309
|
+
callback(job, --remain);
|
|
310
|
+
}
|
|
311
|
+
}, 300);
|
|
312
|
+
});
|
|
313
|
+
})
|
|
314
|
+
);
|
|
315
|
+
};
|
|
316
|
+
const sendStopMessages = async (socket) => {
|
|
317
|
+
socket.write(
|
|
318
|
+
JSON.stringify({
|
|
319
|
+
list: schedules.map((item) => item.toCrontab())
|
|
320
|
+
}) + "\n"
|
|
321
|
+
);
|
|
322
|
+
await stopJobs((job) => {
|
|
323
|
+
socket.write(
|
|
324
|
+
JSON.stringify({
|
|
325
|
+
done: job.schedule.toCrontab()
|
|
326
|
+
}) + "\n"
|
|
327
|
+
);
|
|
328
|
+
});
|
|
329
|
+
socket.destroy();
|
|
330
|
+
};
|
|
331
|
+
const sendStatsMessage = (socket) => {
|
|
332
|
+
socket.write(
|
|
333
|
+
JSON.stringify({
|
|
334
|
+
runners: jobs.reduce(
|
|
335
|
+
(carry, job) => carry.concat(
|
|
336
|
+
job.getPIDs().map((pid) => ({
|
|
337
|
+
pid,
|
|
338
|
+
argv: job.schedule.argv
|
|
339
|
+
}))
|
|
340
|
+
),
|
|
341
|
+
[]
|
|
342
|
+
)
|
|
343
|
+
}) + "\n"
|
|
344
|
+
);
|
|
345
|
+
};
|
|
346
|
+
const server = net.createServer(async (socket) => {
|
|
347
|
+
socket.on("data", async (data) => {
|
|
348
|
+
switch (data.toString()) {
|
|
349
|
+
case "cron:stop":
|
|
350
|
+
await sendStopMessages(socket);
|
|
351
|
+
break;
|
|
352
|
+
case "cron:stats":
|
|
353
|
+
sendStatsMessage(socket);
|
|
354
|
+
break;
|
|
355
|
+
}
|
|
356
|
+
});
|
|
357
|
+
});
|
|
358
|
+
server.listen(opts.port || DEFAULT_PORT);
|
|
359
|
+
process.once("SIGINT", async () => {
|
|
360
|
+
console.warn(chalk.yellowBright(i18n3.t("cron.use_stop")));
|
|
361
|
+
stopJobs(() => {
|
|
362
|
+
});
|
|
363
|
+
});
|
|
364
|
+
await Promise.all(jobs.map((job) => job.start()));
|
|
365
|
+
await stopJobs((_, remain) => {
|
|
366
|
+
if (!remain)
|
|
367
|
+
server.close();
|
|
368
|
+
});
|
|
369
|
+
},
|
|
370
|
+
help: {
|
|
371
|
+
onDocument(doc) {
|
|
372
|
+
doc[commandName] = { summary: i18n3.t("cron.start") };
|
|
373
|
+
}
|
|
378
374
|
}
|
|
379
|
-
})
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
375
|
+
});
|
|
376
|
+
};
|
|
377
|
+
|
|
378
|
+
// src/middleware/eject.middleware.ts
|
|
379
|
+
import { i18n as i18n4, middleware as middleware2 } from "@aomex/core";
|
|
380
|
+
var commandName2 = "cron:eject";
|
|
381
|
+
var eject = (opts) => {
|
|
382
|
+
return middleware2.console({
|
|
383
|
+
fn: async (ctx, next) => {
|
|
384
|
+
if (ctx.input.command !== commandName2)
|
|
385
|
+
return next();
|
|
386
|
+
ctx.commandMatched = true;
|
|
387
|
+
const schedules = await collectSchedules(opts);
|
|
388
|
+
const taskList = schedules.map((schedule2) => schedule2.toCrontab()).flat();
|
|
389
|
+
console.log(taskList.join("\n"));
|
|
390
|
+
},
|
|
391
|
+
help: {
|
|
392
|
+
onDocument(doc) {
|
|
393
|
+
doc[commandName2] = {
|
|
394
|
+
summary: i18n4.t("cron.eject")
|
|
395
|
+
};
|
|
396
|
+
}
|
|
397
|
+
}
|
|
398
|
+
});
|
|
399
|
+
};
|
|
400
|
+
|
|
401
|
+
// src/middleware/stop.middleware.ts
|
|
402
|
+
import "@aomex/console";
|
|
403
|
+
import { i18n as i18n5, middleware as middleware3 } from "@aomex/core";
|
|
404
|
+
import net2 from "node:net";
|
|
405
|
+
import Spinnies from "spinnies";
|
|
406
|
+
import { chalk as chalk2 } from "@aomex/internal-tools";
|
|
407
|
+
var commandName3 = "cron:stop";
|
|
408
|
+
var stop = (opts) => {
|
|
409
|
+
return middleware3.console({
|
|
410
|
+
fn: async (ctx, next) => {
|
|
411
|
+
if (ctx.input.command !== commandName3)
|
|
412
|
+
return next();
|
|
413
|
+
ctx.commandMatched = true;
|
|
414
|
+
const PORT = opts.port || DEFAULT_PORT;
|
|
415
|
+
const client = net2.createConnection({ port: PORT }, () => {
|
|
416
|
+
client.write(commandName3);
|
|
417
|
+
});
|
|
418
|
+
const spinner = new Spinnies();
|
|
419
|
+
await new Promise((resolve, reject) => {
|
|
420
|
+
client.on("close", resolve);
|
|
421
|
+
client.on("error", (err) => {
|
|
422
|
+
if (err.code === CONNECT_REFUSED) {
|
|
423
|
+
console.warn(chalk2.yellow(i18n5.t("cron.not_started", { port: PORT })));
|
|
424
|
+
resolve(void 0);
|
|
425
|
+
} else {
|
|
426
|
+
reject(err);
|
|
427
|
+
}
|
|
428
|
+
});
|
|
429
|
+
client.on("data", (data) => {
|
|
430
|
+
data.toString().split("\n").filter(Boolean).forEach((stringifyData) => {
|
|
431
|
+
const json = JSON.parse(stringifyData);
|
|
432
|
+
if ("list" in json) {
|
|
433
|
+
json.list.forEach((item) => {
|
|
434
|
+
spinner.add(item, { text: item });
|
|
435
|
+
});
|
|
436
|
+
} else if ("done" in json) {
|
|
437
|
+
spinner.succeed(json.done);
|
|
438
|
+
if (!spinner.hasActiveSpinners()) {
|
|
439
|
+
client.destroy();
|
|
440
|
+
}
|
|
441
|
+
}
|
|
442
|
+
});
|
|
443
|
+
});
|
|
444
|
+
});
|
|
445
|
+
},
|
|
446
|
+
help: {
|
|
447
|
+
onDocument(doc) {
|
|
448
|
+
doc[commandName3] = { summary: i18n5.t("cron.stop") };
|
|
449
|
+
}
|
|
450
|
+
}
|
|
451
|
+
});
|
|
452
|
+
};
|
|
453
|
+
|
|
454
|
+
// src/middleware/stats.middleware.ts
|
|
455
|
+
import "@aomex/console";
|
|
456
|
+
import { i18n as i18n6, middleware as middleware4 } from "@aomex/core";
|
|
457
|
+
import net3 from "node:net";
|
|
458
|
+
import Spinnies2 from "spinnies";
|
|
459
|
+
import pidusage from "pidusage";
|
|
460
|
+
import { bytes, chalk as chalk3 } from "@aomex/internal-tools";
|
|
461
|
+
var commandName4 = "cron:stats";
|
|
462
|
+
var stats = (opts) => {
|
|
463
|
+
return middleware4.console({
|
|
464
|
+
fn: async (ctx, next) => {
|
|
465
|
+
if (ctx.input.command !== commandName4)
|
|
466
|
+
return next();
|
|
467
|
+
ctx.commandMatched = true;
|
|
468
|
+
const PORT = opts.port || DEFAULT_PORT;
|
|
469
|
+
const client = net3.createConnection({ port: PORT }, () => {
|
|
470
|
+
client.write(commandName4);
|
|
471
|
+
const timer = setInterval(() => {
|
|
472
|
+
client.write(commandName4);
|
|
473
|
+
}, 800);
|
|
474
|
+
client.on("error", () => {
|
|
475
|
+
clearInterval(timer);
|
|
476
|
+
});
|
|
477
|
+
client.on("close", () => {
|
|
478
|
+
clearInterval(timer);
|
|
479
|
+
});
|
|
480
|
+
});
|
|
481
|
+
const spinner = new Spinnies2();
|
|
482
|
+
spinner.add("default", { text: "Running jobs count: 0" });
|
|
483
|
+
let lastPIDs = [];
|
|
484
|
+
await new Promise((resolve, reject) => {
|
|
485
|
+
client.on("close", resolve);
|
|
486
|
+
client.on("error", (err) => {
|
|
487
|
+
if (err.code === CONNECT_REFUSED) {
|
|
488
|
+
console.warn(chalk3.yellow(i18n6.t("cron.not_started", { port: PORT })));
|
|
489
|
+
resolve(void 0);
|
|
490
|
+
} else {
|
|
491
|
+
reject(err);
|
|
492
|
+
}
|
|
493
|
+
});
|
|
494
|
+
client.on("data", async (data) => {
|
|
495
|
+
for (const stringifyData of data.toString().split("\n").filter(Boolean)) {
|
|
496
|
+
const json = JSON.parse(stringifyData);
|
|
497
|
+
if (!("runners" in json))
|
|
498
|
+
return;
|
|
499
|
+
spinner.update("default", {
|
|
500
|
+
text: `Running jobs count: ${json.runners.length}`
|
|
501
|
+
});
|
|
502
|
+
const pids = json.runners.map((item) => item.pid);
|
|
503
|
+
lastPIDs.forEach((pid) => {
|
|
504
|
+
if (!pids.includes(pid)) {
|
|
505
|
+
spinner.remove("pid-" + pid);
|
|
506
|
+
}
|
|
507
|
+
});
|
|
508
|
+
let stats2;
|
|
509
|
+
try {
|
|
510
|
+
stats2 = await pidusage([...pids]);
|
|
511
|
+
} catch {
|
|
512
|
+
stats2 = {};
|
|
513
|
+
}
|
|
514
|
+
json.runners.forEach(({ pid, argv }) => {
|
|
515
|
+
const stat = stats2[pid] || { cpu: 0, memory: 0, elapsed: 0 };
|
|
516
|
+
const msg = argv.join(" ") + // 使用中文会导致文字显示不全
|
|
517
|
+
` (cpu: ${Math.round(stat.cpu * 1e3) / 1e3}%, memory: ${bytes(stat.memory)}, time: ${stat.elapsed / 1e3}s, pid: ${pid})`;
|
|
518
|
+
if (lastPIDs.includes(pid)) {
|
|
519
|
+
spinner.update("pid-" + pid, { text: msg, status: "non-spinnable" });
|
|
520
|
+
} else {
|
|
521
|
+
spinner.add("pid-" + pid, { text: msg, status: "non-spinnable" });
|
|
522
|
+
}
|
|
523
|
+
});
|
|
524
|
+
lastPIDs = pids;
|
|
525
|
+
}
|
|
526
|
+
});
|
|
527
|
+
});
|
|
528
|
+
},
|
|
529
|
+
help: {
|
|
530
|
+
onDocument(doc) {
|
|
531
|
+
doc[commandName4] = { summary: i18n6.t("cron.stats") };
|
|
532
|
+
}
|
|
533
|
+
}
|
|
534
|
+
});
|
|
386
535
|
};
|
|
387
536
|
|
|
388
|
-
// src/middleware/cron.ts
|
|
389
|
-
var cron = (
|
|
390
|
-
const opts = typeof
|
|
391
|
-
return
|
|
537
|
+
// src/middleware/cron.middleware.ts
|
|
538
|
+
var cron = (options) => {
|
|
539
|
+
const opts = typeof options === "string" ? { path: options } : options;
|
|
540
|
+
return mdchain.console.mount(start(opts)).mount(eject(opts)).mount(stop(opts)).mount(stats(opts));
|
|
392
541
|
};
|
|
393
542
|
export {
|
|
394
543
|
ScheduleMiddleware,
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/middleware/cron.ts","../src/middleware/eject.ts","../src/lib/get-middleware-schedule.ts","../src/middleware/schedule.ts","../src/lib/schedule.ts","../src/middleware/eject-to-help.ts","../src/middleware/run.ts","../src/middleware/run-to-help.ts","../src/lib/job.ts","../src/lib/job-in-order.ts"],"sourcesContent":["import type { ConsoleChain } from '@aomex/console';\nimport { Caching, chain } from '@aomex/core';\nimport { eject } from './eject';\nimport { run } from './run';\nimport type { PathToFileOptions } from '@aomex/internal-file-import';\n\nexport interface CronOptions {\n path: PathToFileOptions;\n /**\n * 设置集群服务,任务共享。默认值:`MemoryCache`\n */\n driver?: Caching;\n /**\n * 任务分配模式。默认值:`false`\n * - true: 竞赛,只有一个服务可获得某个任务\n * - false: 每个服务都可以获得某个任务\n */\n race?: boolean;\n /**\n * 任务重叠执行。默认值:`true`\n * - true: 某个任务触发后立即执行。适合允许并发操作的场景\n *\n * - false: 当前被触发的任务,需要等上一次被触发的任务执行完毕后才能执行。场景:\n * 防止数据相互覆盖,防止重复生成数据,防止重复发送通知\n *\n */\n overlap?: boolean;\n}\n\nexport const cron = (options: string | CronOptions): ConsoleChain => {\n const opts: CronOptions =\n typeof options === 'string' ? { path: options } : options;\n return chain.console.mount(run(opts)).mount(eject(opts.path));\n};\n","import { options } from '@aomex/console';\nimport { chain, Middleware, middleware, rule } from '@aomex/core';\nimport { type PathToFileOptions } from '@aomex/internal-file-import';\nimport { mkdir, writeFile } from 'node:fs/promises';\nimport path, { dirname } from 'node:path';\nimport { getMiddlewareSchedule } from '../lib/get-middleware-schedule';\nimport { ejectToHelp } from './eject-to-help';\nimport { chalk } from '@aomex/internal-tools';\n\nconst exportCron = 'cron:eject';\n\nexport const ejectRule = options(\n {\n output: rule.string().optional().docs({\n description: 'Export to specific file',\n }),\n },\n {\n output: ['o'],\n },\n);\n\nexport const eject = (paths: PathToFileOptions) =>\n chain.console\n .mount(ejectToHelp(exportCron))\n .mount(ejectRule)\n .mount(\n middleware.console<Middleware.Infer<typeof ejectRule>>(\n async (ctx, next) => {\n if (ctx.request.command !== exportCron) {\n Reflect.deleteProperty(ctx, 'options');\n return next();\n }\n\n ctx.response.commandMatched = true;\n\n const schedules = await getMiddlewareSchedule(paths);\n const crons = schedules\n .map((schedule) => schedule.toCrontab())\n .flat();\n\n const { output: outputToFile } = ctx.options;\n if (outputToFile) {\n const file = path.resolve(outputToFile);\n await mkdir(dirname(file), { recursive: true });\n await writeFile(file, crons.join('\\n'), {});\n console.log(`Crontab has been created: ${chalk.blue(file)}`);\n } else {\n console.log(crons.join('\\n'));\n }\n },\n ),\n );\n","import { Commander } from '@aomex/commander';\nimport { Chain } from '@aomex/core';\nimport {\n type PathToFileOptions,\n fileToModules,\n pathToFiles,\n} from '@aomex/internal-file-import';\nimport { ScheduleMiddleware } from '../middleware/schedule';\nimport type { Schedule } from './schedule';\n\nexport const getMiddlewareSchedule = async (paths: PathToFileOptions) => {\n const files = await pathToFiles(paths);\n const commanders = await fileToModules<Commander>(\n files,\n (item) => !!item && item instanceof Commander,\n );\n const schedules: Schedule[] = [];\n for (const commander of commanders) {\n for (const builder of commander['builders']) {\n for (const middleware of Chain.flatten(builder.chain)) {\n if (middleware instanceof ScheduleMiddleware) {\n schedules.push(middleware.getSchedule(builder.commands[0]!));\n }\n }\n }\n }\n return schedules;\n};\n","import { ConsoleMiddleware } from '@aomex/console';\nimport { Schedule, type ScheduleOptions } from '../lib/schedule';\n\nexport class ScheduleMiddleware extends ConsoleMiddleware<object> {\n constructor(protected readonly options: ScheduleOptions) {\n super(async (_, next) => next());\n }\n\n getSchedule(command: string): Schedule {\n return new Schedule({ ...this.options, command });\n }\n}\n\nexport const schedule = (\n options: ScheduleOptions | string,\n): ScheduleMiddleware => {\n return new ScheduleMiddleware(\n typeof options === 'string' ? { time: options } : options,\n );\n};\n","import { scriptName } from '@aomex/console';\nimport parser from 'cron-parser';\nimport type { CronOptions } from '../middleware/cron';\n\ninterface ScheduleTimeObject {\n /**\n * 0-59\n */\n second?: string | number;\n /**\n * 0-59\n */\n minute?: string | number;\n /**\n * 0-23\n */\n hour?: string | number;\n /**\n * 1-31\n */\n dayOfMonth?: string | number;\n /**\n * 0-11\n */\n month?: string | number;\n /**\n * 0-6\n * - 周末: 0\n * - 周一: 1\n */\n dayOfWeek?: string | number;\n}\n\ninterface ScheduleTimeString {\n /**\n 类似linux下cron的时间格式,并支持秒级时间\n ```\n ┌────────────── second (optional)\n │ ┌──────────── minute \n │ │ ┌────────── hour\n │ │ │ ┌──────── day of month\n │ │ │ │ ┌────── month\n │ │ │ │ │ ┌──── day of week\n │ │ │ │ │ │\n `* * * * * *`\n ```\n */\n time: string;\n}\n\ninterface ScheduleBaseOptions {\n /**\n * 执行时附带的参数,使用`options`接收\n *\n * 例子:`['--hello', 'world', '-it', '-o', 'file.txt']`\n */\n args?: (string | number)[];\n /**\n * 任务分配模式。默认值:`cron.race`\n * - true: 竞赛,只有一个服务可获得某个任务\n * - false: 每个服务都可以获得某个任务\n *\n * @see CronOptions.race\n */\n race?: boolean;\n /**\n * 任务重叠执行。默认值:`cron.overlap`\n * - true: 某个任务触发后立即执行。适合允许并发操作的场景\n *\n * - false: 当前被触发的任务,需要等上一次被触发的任务执行完毕后才能执行。场景:\n * 防止数据相互覆盖,防止重复生成数据,防止重复发送通知\n *\n * @see CronOptions.overlap\n */\n overlap?: CronOptions['overlap'];\n}\n\nexport type ScheduleOptions = (ScheduleTimeObject | ScheduleTimeString) &\n ScheduleBaseOptions;\n\nexport class Schedule {\n protected _time?: string;\n protected _seconds?: number[];\n protected _argv?: string[];\n\n constructor(\n protected readonly options: ScheduleOptions & { command: string },\n ) {}\n\n public get overlap(): CronOptions['overlap'] | undefined {\n return this.options.overlap;\n }\n\n public get race(): CronOptions['race'] | undefined {\n return this.options.race;\n }\n\n public get time(): string {\n return (this._time ??= (() => {\n const { options } = this;\n if ('time' in options) {\n const timeList = options.time.split(/\\s+/);\n switch (timeList.length) {\n case 6:\n timeList.shift();\n return timeList.join(' ');\n case 5:\n return timeList.join(' ');\n default:\n throw new Error(`Invalid cron time: \"${options.time}\"`);\n }\n }\n\n return [\n options.minute ?? '*',\n options.hour ?? '*',\n options.dayOfMonth ?? '*',\n options.month ?? '*',\n options.dayOfWeek ?? '*',\n ].join(' ');\n })());\n }\n\n public get argv(): string[] {\n return (this._argv ??= [\n this.options.command,\n ...(this.options.args || []),\n ].map(String));\n }\n\n public get seconds(): number[] {\n return (this._seconds ??= (() => {\n const { options } = this;\n let second: string | undefined;\n\n if ('time' in options) {\n const timeList = options.time.split(/\\s+/);\n if (timeList.length === 6) {\n second = timeList[0]!;\n }\n } else {\n second = options.second?.toString();\n }\n\n if (!second) return [];\n const seconds: number[] = [];\n // second and minute are both 0-59\n const interval = parser.parseExpression(`${second} * * * *`);\n while (true) {\n const nextSecond = interval.next().getMinutes();\n if (seconds.includes(nextSecond)) break;\n seconds.push(nextSecond);\n }\n return seconds.sort((a, b) => a - b);\n })());\n }\n\n public toCrontab(): string[] {\n const script = [this.time];\n const crons: string[][] = [];\n\n for (const second of this.seconds) {\n crons.push(script.concat(`sleep ${second};`));\n }\n\n if (crons.length === 0) {\n crons.push(script);\n }\n\n return crons.map((time) => {\n const argv = this.argv.map((value) =>\n value.includes(' ') ? `\"${value}\"` : value,\n );\n return time.concat(['npx', scriptName, ...argv]).join(' ');\n });\n }\n\n toJSON() {\n return {\n time: this.time,\n seconds: this.seconds,\n argv: this.argv,\n race: this.race,\n overlap: this.overlap,\n };\n }\n}\n","import { HelpMiddleware, scriptName } from '@aomex/console';\nimport { middleware } from '@aomex/core';\nimport { ejectRule } from './eject';\nimport { chalk } from '@aomex/internal-tools';\n\nexport const ejectToHelp = (commandName: string): HelpMiddleware =>\n middleware.help(async (ctx, next) => {\n return ctx.cli.config({\n all(yargs) {\n yargs.command(chalk.yellow(commandName), 'Create cron-compatibly list');\n },\n detail(yargs) {\n yargs.usage(`${scriptName} ${commandName} [options]`);\n ejectRule.toHelp(yargs);\n },\n next,\n detailCommand: commandName,\n });\n });\n","import { middleware, chain } from '@aomex/core';\nimport { MemoryCache } from '@aomex/memory-cache';\nimport { runToHelp } from './run-to-help';\nimport type { CronOptions } from './cron';\nimport { Job } from '../lib/job';\nimport { getMiddlewareSchedule } from '../lib/get-middleware-schedule';\nimport { JobInOrder } from '../lib/job-in-order';\nimport { Schedule } from '../lib/schedule';\nimport { ConsoleApp } from '@aomex/console';\n\nconst runCron = 'cron:run';\n\nexport const run = (cron: CronOptions, forever: boolean = true) =>\n chain.console.mount(runToHelp(runCron)).mount(\n middleware.console(async (ctx, next) => {\n if (ctx.request.command !== runCron) return next();\n ctx.response.commandMatched = true;\n const schedules = await getMiddlewareSchedule(cron.path);\n const promises = schedules.map((schedule) => {\n return createJob(ctx.app, schedule, cron).start();\n });\n // Almost never exit\n if (forever) {\n await Promise.all(promises);\n }\n }),\n );\n\nexport const createJob = (\n app: ConsoleApp,\n schedule: Schedule,\n cron: CronOptions,\n) => {\n const race = schedule.race ?? cron.race ?? false;\n const driver = cron.driver || new MemoryCache();\n const overlap = schedule.overlap ?? cron.overlap ?? true;\n return overlap\n ? new Job(app, schedule, driver, race)\n : new JobInOrder(app, schedule, driver, race);\n};\n","import { middleware } from '@aomex/core';\nimport { chalk } from '@aomex/internal-tools';\nimport { HelpMiddleware, scriptName } from '@aomex/console';\n\nexport const runToHelp = (commandName: string): HelpMiddleware =>\n middleware.help(async (ctx, next) => {\n ctx.cli.config({\n all(yargs) {\n yargs.command(chalk.yellow(commandName), 'Star cron jobs');\n },\n detail(yargs) {\n yargs.usage(`${scriptName} ${commandName} [options]`);\n },\n detailCommand: commandName,\n next,\n });\n });\n","import type { ConsoleApp } from '@aomex/console';\nimport cronParser from 'cron-parser';\nimport { Caching } from '@aomex/core';\nimport { Schedule } from './schedule';\nimport { sleep } from '@aomex/internal-tools';\n\nexport class Job {\n public jobAmount: number = 0;\n\n constructor(\n protected readonly app: ConsoleApp,\n protected readonly schedule: Schedule,\n protected readonly driver: Caching,\n protected readonly race: boolean,\n ) {}\n\n async start(): Promise<void> {\n const handle = this.getCronHandle();\n\n while (true) {\n const nextTime = handle.next().getTime();\n const uniqueKey = `cron-job-win-argv:${this.schedule.argv};pattern:${this.schedule.time};time:${nextTime};`;\n await sleep(nextTime - Date.now());\n if (this.schedule.seconds.length) {\n this.emitBySeconds(uniqueKey);\n } else {\n // 不要使用`await`语法,因为需要立即进入下一个循环\n this.winJob(uniqueKey).then((isWinner) => {\n isWinner && (++this.jobAmount, this.consume());\n });\n }\n if (!handle.hasNext()) break;\n }\n }\n\n emitBySeconds(key: string) {\n const nowSecond = new Date().getSeconds();\n for (const nextSecond of this.schedule.seconds) {\n const delay = nextSecond - nowSecond;\n if (delay >= 0) {\n sleep(delay * 1000).then(async () => {\n const isWinner = await this.winJob(key + `second:${nextSecond};`);\n isWinner && (++this.jobAmount, this.consume());\n });\n }\n }\n }\n\n async winJob(key: string): Promise<boolean> {\n if (this.race) {\n await sleep(this.jobAmount * 5);\n return this.driver.add(key, 1, 100 * 1000);\n }\n return true;\n }\n\n getCronHandle() {\n const now = new Date();\n if (this.schedule.seconds.length) {\n now.setMinutes(now.getMinutes() - 1);\n }\n return cronParser.parseExpression(this.schedule.time, {\n currentDate: now,\n });\n }\n\n async consume() {\n if (this.jobAmount <= 0) return;\n await this.app.run(...this.schedule.argv);\n --this.jobAmount;\n }\n}\n","import { hostname } from 'node:os';\nimport { Job } from './job';\nimport { Caching } from '@aomex/core';\nimport { sleep } from '@aomex/internal-tools';\n\nconst THREE_SECOND = 3 * 1000;\nconst TEN_SECOND = 10 * 1000;\nconst ONE_DAY = 3600 * 24 * 1000;\n\nexport class JobInOrder extends Job {\n protected declare readonly driver: Caching;\n\n queueTimer: NodeJS.Timeout | null = null;\n protected readonly jobId =\n hostname() + Date.now() + Math.random() + ':' + process.pid;\n protected readonly jobKey = `cron-job-queue-argv:${this.schedule.argv};pattern:${this.schedule.time};`;\n\n override async consume() {\n if (this.jobAmount === 0) return;\n await this.ping();\n if (await this.winQueue()) {\n let pingTimer!: NodeJS.Timeout;\n try {\n pingTimer = setInterval(() => this.ping(), THREE_SECOND);\n await super.consume();\n } finally {\n clearInterval(pingTimer);\n await this.releaseQueue();\n this.waiting();\n }\n } else {\n this.waiting();\n }\n }\n\n async ping() {\n await this.driver.set(this.getPingKey(this.jobId), 'pong', TEN_SECOND);\n }\n\n getPingKey(jobId: string) {\n return this.jobKey + ':ping:' + jobId;\n }\n\n async winQueue(): Promise<boolean> {\n const win = await this.driver.add(this.jobKey, this.jobId, ONE_DAY);\n if (win) return true;\n {\n const winnerJobId = await this.driver.get<string>(this.jobKey);\n // Job is expired or deleted\n if (winnerJobId === null) return this.winQueue();\n const winnerNotDead = await this.driver.exists(\n this.getPingKey(winnerJobId),\n );\n if (winnerNotDead) return false;\n }\n {\n // Avoid other servers deleting valid key.\n const hasPermissionToReleaseQueue = await this.driver.add(\n this.jobKey + ':delete:',\n this.jobId,\n TEN_SECOND,\n );\n await (hasPermissionToReleaseQueue ? this.releaseQueue() : sleep(100));\n return this.winQueue();\n }\n }\n\n async releaseQueue(): Promise<void> {\n await this.driver.delete(this.jobKey);\n }\n\n waiting() {\n if (this.jobAmount === 0) return;\n this.queueTimer ??= setTimeout(() => {\n this.queueTimer = null;\n this.consume();\n }, 500);\n }\n}\n"],"mappings":";AACA,SAAkB,SAAAA,cAAa;;;ACD/B,SAAS,eAAe;AACxB,SAAS,OAAmB,cAAAC,aAAY,YAAY;AAEpD,SAAS,OAAO,iBAAiB;AACjC,OAAO,QAAQ,eAAe;;;ACJ9B,SAAS,iBAAiB;AAC1B,SAAS,aAAa;AACtB;AAAA,EAEE;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AAM,WAAW,UAAU,IAAI,CAACG,cAAa;AAC3C,aAAO,UAAU,IAAI,KAAKA,WAAUH,KAAI,EAAE,MAAM;AAAA,IAClD,CAAC;AAED,QAAI,SAAS;AACX,YAAM,QAAQ,IAAI,QAAQ;AAAA,IAC5B;AAAA,EACF,CAAC;AACH;AAEK,IAAM,YAAY,CACvB,KACAG,WACAH,UACG;AACH,QAAM,OAAOG,UAAS,QAAQH,MAAK,QAAQ;AAC3C,QAAM,SAASA,MAAK,UAAU,IAAI,YAAY;AAC9C,QAAM,UAAUG,UAAS,WAAWH,MAAK,WAAW;AACpD,SAAO,UACH,IAAI,IAAI,KAAKG,WAAU,QAAQ,IAAI,IACnC,IAAI,WAAW,KAAKA,WAAU,QAAQ,IAAI;AAChD;;;ANVO,IAAM,OAAO,CAACC,aAAgD;AACnE,QAAM,OACJ,OAAOA,aAAY,WAAW,EAAE,MAAMA,SAAQ,IAAIA;AACpD,SAAOC,OAAM,QAAQ,MAAM,IAAI,IAAI,CAAC,EAAE,MAAM,MAAM,KAAK,IAAI,CAAC;AAC9D;","names":["chain","middleware","options","options","middleware","scriptName","scriptName","chalk","middleware","schedule","middleware","chain","middleware","chalk","scriptName","schedule","sleep","cron","chain","middleware","schedule","options","chain"]}
|
|
1
|
+
{"version":3,"sources":["../src/i18n/locales/zh-cn.ts","../src/i18n/locales/en-us.ts","../src/middleware/cron.middleware.ts","../src/middleware/start.middleware.ts","../src/lib/collect-schedule.ts","../src/middleware/schedule.middleware.ts","../src/lib/schedule-parser.ts","../src/lib/job.ts","../src/lib/constant.ts","../src/middleware/eject.middleware.ts","../src/middleware/stop.middleware.ts","../src/middleware/stats.middleware.ts"],"sourcesContent":["import { i18n } from '@aomex/core';\n\ni18n.register('zh_CN', 'cron', {\n eject: '导出定时任务列表',\n start: '启动定时任务',\n stop: '退出定时任务',\n stats: '查看定时任务执行状态',\n not_started: '定时任务未启动,端口:{{port}}',\n use_stop: '执行中的任务也会被强制中断,因此推荐使用指令 \"aomex cron:stop\" 结束定时任务',\n});\n","import { i18n } from '@aomex/core';\n\ni18n.register('en_US', 'cron', {\n eject: 'Eject cron jobs list',\n start: 'Start cron jobs',\n stop: 'Stop cron jobs',\n stats: 'Show cron jobs stats',\n not_started: 'cron not started with port: {{port}}',\n use_stop:\n 'Recommend using command \"aomex cron:stop\" to stop cron in favor of waiting executing jobs',\n});\n","import { mdchain } from '@aomex/core';\nimport type { ConsoleMiddlewareChain } from '@aomex/console';\nimport { start } from './start.middleware';\nimport { eject } from './eject.middleware';\nimport type { CronOptions } from '../lib/type';\nimport { stop } from './stop.middleware';\nimport { stats } from './stats.middleware';\n\nexport const cron = (options: string | CronOptions): ConsoleMiddlewareChain => {\n const opts: CronOptions = typeof options === 'string' ? { path: options } : options;\n return mdchain.console\n .mount(start(opts))\n .mount(eject(opts))\n .mount(stop(opts))\n .mount(stats(opts));\n};\n","import { i18n, middleware } from '@aomex/core';\nimport { collectSchedules } from '../lib/collect-schedule';\nimport { Job } from '../lib/job';\nimport type { CronOptions, ServerWriteData } from '../lib/type';\nimport net, { Socket } from 'node:net';\nimport { DEFAULT_PORT } from '../lib/constant';\nimport { chalk } from '@aomex/internal-tools';\n\nconst commandName = 'cron:start';\n\nexport const start = (opts: CronOptions) => {\n return middleware.console({\n fn: async (ctx, next) => {\n if (ctx.input.command !== commandName) return next();\n\n ctx.commandMatched = true;\n const schedules = await collectSchedules(opts);\n\n if (!schedules.length) return;\n\n const jobs = schedules.map((schedule) => new Job(schedule));\n\n const stopJobs = async (callback: (job: Job, remain: number) => void) => {\n jobs.forEach((job) => job.stop());\n let remain = jobs.length;\n await Promise.all(\n jobs.map((job) => {\n return new Promise((resolve) => {\n const timer = setInterval(() => {\n if (!job.runningLevel) {\n clearInterval(timer);\n resolve(void 0);\n callback(job, --remain);\n }\n }, 300);\n });\n }),\n );\n };\n\n const sendStopMessages = async (socket: Socket) => {\n socket.write(\n JSON.stringify({\n list: schedules.map((item) => item.toCrontab()),\n } satisfies ServerWriteData) + '\\n',\n );\n await stopJobs((job) => {\n socket.write(\n JSON.stringify({\n done: job.schedule.toCrontab(),\n } satisfies ServerWriteData) + '\\n',\n );\n });\n socket.destroy();\n };\n\n const sendStatsMessage = (socket: Socket) => {\n socket.write(\n JSON.stringify({\n runners: jobs.reduce<{ pid: string; argv: string[] }[]>(\n (carry, job) =>\n carry.concat(\n job.getPIDs().map((pid) => ({\n pid,\n argv: job.schedule.argv,\n })),\n ),\n [],\n ),\n } satisfies ServerWriteData) + '\\n',\n );\n };\n\n const server = net.createServer(async (socket) => {\n socket.on('data', async (data) => {\n switch (data.toString()) {\n case 'cron:stop':\n await sendStopMessages(socket);\n break;\n case 'cron:stats':\n sendStatsMessage(socket);\n break;\n }\n });\n });\n server.listen(opts.port || DEFAULT_PORT);\n\n // CTRL + C\n // 子进程也会被立即杀死,但是job.start仍然在生产任务\n process.once('SIGINT', async () => {\n console.warn(chalk.yellowBright(i18n.t('cron.use_stop')));\n stopJobs(() => {});\n });\n\n await Promise.all(jobs.map((job) => job.start()));\n // 确保执行中的任务已经完成\n await stopJobs((_, remain) => {\n if (!remain) server.close();\n });\n },\n help: {\n onDocument(doc) {\n doc[commandName] = { summary: i18n.t('cron.start') };\n },\n },\n });\n};\n","import { Commander } from '@aomex/commander';\nimport { pathToFiles, getFileValues } from '@aomex/internal-file-import';\nimport { ScheduleMiddleware } from '../middleware/schedule.middleware';\nimport { ScheduleParser } from './schedule-parser';\nimport type { CronOptions } from './type';\n\nexport const collectSchedules = async (opts: CronOptions) => {\n const files = await pathToFiles(opts.path);\n const commanders = await getFileValues<Commander>(\n files,\n (item) => !!item && item instanceof Commander,\n );\n const schedules: ScheduleParser[] = [];\n for (const commander of commanders) {\n for (const builder of commander['builders']) {\n for (const middleware of builder['middlewareList']) {\n if (middleware instanceof ScheduleMiddleware) {\n schedules.push(\n new ScheduleParser({\n ...opts,\n ...middleware['options'],\n command: builder.commands[0]!,\n }),\n );\n }\n }\n }\n }\n return schedules;\n};\n","import { ConsoleMiddleware } from '@aomex/console';\nimport type { ScheduleOptions } from '../lib/type';\n\nexport class ScheduleMiddleware extends ConsoleMiddleware<object> {\n constructor(protected readonly options: ScheduleOptions) {\n super(async (_, next) => next());\n }\n}\n\n/**\n * 创建一个定时任务\n *\n * 如果传递字符串,则为cron时间表达式(支持秒)。如:`1-10,20 * * * *`\n */\nexport const schedule = (options: ScheduleOptions | string): ScheduleMiddleware => {\n return new ScheduleMiddleware(\n typeof options === 'string' ? { time: options } : options,\n );\n};\n","import { scriptName } from '@aomex/console';\nimport { MemoryCache } from '@aomex/memory-cache';\nimport type { CronOptions, CronStore, ScheduleOptions } from './type';\nimport cronParser from 'cron-parser';\n\nexport class ScheduleParser {\n protected _time?: string;\n protected _seconds?: number[];\n protected _argv?: string[];\n protected _store?: CronStore;\n\n constructor(\n protected readonly options: ScheduleOptions & CronOptions & { command: string },\n ) {}\n\n public get command(): string {\n return this.options.command;\n }\n\n public get overlap(): boolean {\n return this.options.overlap ?? false;\n }\n\n public get concurrent(): number {\n return Math.max(1, this.options.concurrent || 1);\n }\n\n public get store(): CronStore {\n return (this._store ??= this.options.store || new MemoryCache());\n }\n\n public get time(): string {\n return (this._time ??= (() => {\n const { options } = this;\n if ('time' in options) {\n const expression = options.time;\n try {\n const handle = cronParser.parseExpression(expression);\n const arr = expression.split(/\\s+/);\n return arr.length < 5 ? handle.stringify(false) : arr.join(' ');\n } catch {\n throw new Error(`时间表达式不合法:${expression}`);\n }\n }\n\n const arr = [\n options.minute ?? '*',\n options.hour ?? '*',\n options.dayOfMonth ?? '*',\n options.month ?? '*',\n options.dayOfWeek ?? '*',\n ];\n options.second && arr.unshift(options.second);\n return arr.join(' ');\n })());\n }\n\n public get argv(): string[] {\n return (this._argv ??= [this.options.command, ...(this.options.args || [])].map(\n String,\n ));\n }\n\n public toCrontab(): string {\n return [\n this.time,\n scriptName,\n ...this.argv.map((value) => (value.includes(' ') ? `\"${value}\"` : value)),\n ].join(' ');\n }\n\n toJSON() {\n return {\n command: this.command,\n time: this.time,\n argv: this.argv,\n concurrent: this.concurrent,\n overlap: this.overlap,\n };\n }\n}\n","import cronParser from 'cron-parser';\nimport type { ScheduleParser } from './schedule-parser';\nimport type { CronStore } from './type';\nimport { spawn } from 'node:child_process';\n\nexport class Job {\n public runningLevel: number = 0;\n public readonly cronExpression: cronParser.CronExpression;\n public readonly store: CronStore;\n public handle: { timer: NodeJS.Timeout; resolve: (data: void) => void } | null = null;\n public stopping = false;\n public readonly processData: {\n execArgv: string[];\n node: string;\n filePath: string;\n cwd: string;\n env: NodeJS.ProcessEnv;\n };\n protected childPIDs = new Set<string>();\n\n constructor(public readonly schedule: ScheduleParser) {\n this.cronExpression = cronParser.parseExpression(this.schedule.time);\n this.store = schedule.store;\n this.processData = {\n execArgv: [...process.execArgv],\n node: process.argv0,\n filePath: process.argv[1]!,\n cwd: process.cwd(),\n env: process.env,\n };\n }\n\n async start(): Promise<void> {\n if (!this.cronExpression.hasNext()) return;\n const nextTime = this.cronExpression.next().getTime();\n\n while (true) {\n /**\n * setTimeout的最大延时值是 `2^31-1`(约为24.85天) ,超过这个值会被立即执行。\n * 拆分延时值可让执行时机更精确。\n */\n const delta = Math.min(3600_000, nextTime - Date.now());\n await this.delay(delta);\n if (this.stopping) return;\n if (nextTime - Date.now() <= 0) {\n // 不要使用`await`语法,因为需要立即进入下一个循环\n this.consume(nextTime);\n break;\n }\n }\n\n return this.start();\n }\n\n delay(delta: number) {\n return new Promise((resolve) => {\n const timer = setTimeout(() => {\n this.handle = null;\n resolve(undefined);\n }, delta);\n this.handle = { timer, resolve };\n });\n }\n\n stop() {\n this.stopping = true;\n if (this.handle) {\n clearTimeout(this.handle.timer);\n this.handle.resolve();\n }\n }\n\n getPIDs() {\n return [...this.childPIDs];\n }\n\n async consume(nextTime: number) {\n try {\n ++this.runningLevel;\n const jobKey = this.getUniqueKey(nextTime);\n const isWinner = await this.win(jobKey);\n if (isWinner) {\n const pong = this.ping(jobKey);\n try {\n await this.runChildProcess();\n } finally {\n pong();\n await this.done(jobKey);\n }\n }\n } finally {\n --this.runningLevel;\n }\n }\n\n async runChildProcess() {\n return new Promise((resolve) => {\n const childProcess = spawn(\n this.processData.node,\n [...this.processData.execArgv, this.processData.filePath, ...this.schedule.argv],\n {\n cwd: this.processData.cwd,\n env: this.processData.env,\n stdio: 'pipe',\n },\n );\n\n const pid = childProcess.pid?.toString();\n pid && this.childPIDs.add(pid);\n\n childProcess.stdout.pipe(process.stdout);\n childProcess.stderr.pipe(process.stderr);\n childProcess.on('close', () => {\n pid && this.childPIDs.delete(pid);\n resolve(undefined);\n });\n });\n }\n\n async win(jobKey: string): Promise<boolean> {\n if (!this.schedule.overlap) {\n let runningJobKey = await this.store.get(this.runningKey);\n if (!runningJobKey) {\n await this.store.add(this.runningKey, jobKey, 10_000);\n runningJobKey = await this.store.get(this.runningKey);\n }\n if (runningJobKey !== jobKey) return false;\n }\n\n const index = await this.store.increment(jobKey);\n return index <= this.schedule.concurrent;\n }\n\n ping(jobKey: string) {\n const timer = setInterval(() => {\n this.store.set(this.runningKey, jobKey, 10_000);\n }, 3_000);\n return () => clearInterval(timer);\n }\n\n async done(jobKey: string) {\n const doneKey = jobKey + ':done';\n const count = await this.store.increment(doneKey);\n // 当前时间点任务已全部结束\n if (count === this.schedule.concurrent) {\n await Promise.all([\n this.store.expires(this.runningKey, -1),\n this.store.expires(jobKey, 7200_000),\n this.store.expires(doneKey, 7200_000),\n ]);\n }\n }\n\n getUniqueKey(timestamp: number) {\n return `cron-job|argv:${this.schedule.argv};expression:${this.schedule.time};now:${timestamp};`;\n }\n\n get runningKey() {\n return this.getUniqueKey(-1);\n }\n}\n","export const DEFAULT_PORT = 9786;\nexport const CONNECT_REFUSED = 'ECONNREFUSED';\n","import { i18n, middleware } from '@aomex/core';\nimport type { ConsoleMiddleware } from '@aomex/console';\nimport { collectSchedules } from '../lib/collect-schedule';\nimport type { CronOptions } from '../lib/type';\n\nconst commandName = 'cron:eject';\n\nexport const eject = (opts: CronOptions): ConsoleMiddleware => {\n return middleware.console({\n fn: async (ctx, next) => {\n if (ctx.input.command !== commandName) return next();\n\n ctx.commandMatched = true;\n const schedules = await collectSchedules(opts);\n const taskList = schedules.map((schedule) => schedule.toCrontab()).flat();\n console.log(taskList.join('\\n'));\n },\n help: {\n onDocument(doc) {\n doc[commandName] = {\n summary: i18n.t('cron.eject'),\n };\n },\n },\n });\n};\n","import { type ConsoleMiddleware } from '@aomex/console';\nimport { i18n, middleware } from '@aomex/core';\nimport type { CronOptions, ServerWriteData } from '../lib/type';\nimport net from 'node:net';\nimport Spinnies from 'spinnies';\nimport { CONNECT_REFUSED, DEFAULT_PORT } from '../lib/constant';\nimport { chalk } from '@aomex/internal-tools';\n\nconst commandName = 'cron:stop';\n\nexport const stop = (opts: CronOptions): ConsoleMiddleware => {\n return middleware.console({\n fn: async (ctx, next) => {\n if (ctx.input.command !== commandName) return next();\n ctx.commandMatched = true;\n\n const PORT = opts.port || DEFAULT_PORT;\n const client = net.createConnection({ port: PORT }, () => {\n client.write(commandName);\n });\n\n const spinner = new Spinnies();\n\n await new Promise((resolve, reject): void => {\n // 多次resolve不会报错\n client.on('close', resolve);\n client.on('error', (err) => {\n // @ts-expect-error\n if (err.code === CONNECT_REFUSED) {\n console.warn(chalk.yellow(i18n.t('cron.not_started', { port: PORT })));\n resolve(undefined);\n } else {\n reject(err);\n }\n });\n client.on('data', (data) => {\n // 数据可能会堆积下发,直接用JSON.parse容易出错\n data\n .toString()\n .split('\\n')\n .filter(Boolean)\n .forEach((stringifyData) => {\n const json = JSON.parse(stringifyData) as ServerWriteData;\n if ('list' in json) {\n json.list.forEach((item) => {\n spinner.add(item, { text: item });\n });\n } else if ('done' in json) {\n spinner.succeed(json.done);\n if (!spinner.hasActiveSpinners()) {\n client.destroy();\n }\n }\n });\n });\n });\n },\n help: {\n onDocument(doc) {\n doc[commandName] = { summary: i18n.t('cron.stop') };\n },\n },\n });\n};\n","import { type ConsoleMiddleware } from '@aomex/console';\nimport { i18n, middleware } from '@aomex/core';\nimport type { CronOptions, ServerWriteData } from '../lib/type';\nimport net from 'node:net';\nimport Spinnies from 'spinnies';\nimport pidusage from 'pidusage';\nimport { bytes, chalk } from '@aomex/internal-tools';\nimport { CONNECT_REFUSED, DEFAULT_PORT } from '../lib/constant';\n\nconst commandName = 'cron:stats';\n\nexport const stats = (opts: CronOptions): ConsoleMiddleware => {\n return middleware.console({\n fn: async (ctx, next) => {\n if (ctx.input.command !== commandName) return next();\n ctx.commandMatched = true;\n\n const PORT = opts.port || DEFAULT_PORT;\n const client = net.createConnection({ port: PORT }, () => {\n client.write(commandName);\n const timer = setInterval(() => {\n client.write(commandName);\n }, 800);\n client.on('error', () => {\n clearInterval(timer);\n });\n client.on('close', () => {\n clearInterval(timer);\n });\n });\n\n const spinner = new Spinnies();\n spinner.add('default', { text: 'Running jobs count: 0' });\n\n let lastPIDs: string[] = [];\n\n await new Promise((resolve, reject): void => {\n // 多次resolve不会报错\n client.on('close', resolve);\n client.on('error', (err) => {\n // @ts-expect-error\n if (err.code === CONNECT_REFUSED) {\n console.warn(chalk.yellow(i18n.t('cron.not_started', { port: PORT })));\n resolve(undefined);\n } else {\n reject(err);\n }\n });\n client.on('data', async (data) => {\n // 数据可能会堆积下发,直接用JSON.parse容易出错\n for (const stringifyData of data.toString().split('\\n').filter(Boolean)) {\n const json = JSON.parse(stringifyData) as ServerWriteData;\n if (!('runners' in json)) return;\n\n spinner.update('default', {\n text: `Running jobs count: ${json.runners.length}`,\n });\n\n const pids = json.runners.map((item) => item.pid);\n lastPIDs.forEach((pid) => {\n if (!pids.includes(pid)) {\n spinner.remove('pid-' + pid);\n }\n });\n let stats: Awaited<ReturnType<typeof pidusage>>;\n try {\n // 传入后会对原数组进行toNumber()处理,因此需要使用新数组\n stats = await pidusage([...pids]);\n } catch {\n stats = {};\n }\n\n json.runners.forEach(({ pid, argv }) => {\n const stat = stats[pid] || { cpu: 0, memory: 0, elapsed: 0 };\n const msg =\n argv.join(' ') +\n // 使用中文会导致文字显示不全\n ` (cpu: ${Math.round(stat.cpu * 1000) / 1000}%, memory: ${bytes(stat.memory)}, time: ${stat.elapsed / 1000}s, pid: ${pid})`;\n\n if (lastPIDs.includes(pid)) {\n spinner.update('pid-' + pid, { text: msg, status: 'non-spinnable' });\n } else {\n // 直接使用数字作为key会导致排序不正确\n spinner.add('pid-' + pid, { text: msg, status: 'non-spinnable' });\n }\n });\n\n lastPIDs = pids;\n }\n });\n });\n },\n help: {\n onDocument(doc) {\n doc[commandName] = { summary: i18n.t('cron.stats') };\n },\n },\n });\n};\n"],"mappings":";AAAA,SAAS,YAAY;AAErB,KAAK,SAAS,SAAS,QAAQ;AAAA,EAC7B,OAAO;AAAA,EACP,OAAO;AAAA,EACP,MAAM;AAAA,EACN,OAAO;AAAA,EACP,aAAa;AAAA,EACb,UAAU;AACZ,CAAC;;;ACTD,SAAS,QAAAA,aAAY;AAErBA,MAAK,SAAS,SAAS,QAAQ;AAAA,EAC7B,OAAO;AAAA,EACP,OAAO;AAAA,EACP,MAAM;AAAA,EACN,OAAO;AAAA,EACP,aAAa;AAAA,EACb,UACE;AACJ,CAAC;;;ACVD,SAAS,eAAe;;;ACAxB,SAAS,QAAAC,OAAM,kBAAkB;;;ACAjC,SAAS,iBAAiB;AAC1B,SAAS,aAAa,qBAAqB;;;ACD3C,SAAS,yBAAyB;AAG3B,IAAM,qBAAN,cAAiC,kBAA0B;AAAA,EAChE,YAA+B,SAA0B;AACvD,UAAM,OAAO,GAAG,SAAS,KAAK,CAAC;AADF;AAAA,EAE/B;AACF;AAOO,IAAM,WAAW,CAAC,YAA0D;AACjF,SAAO,IAAI;AAAA,IACT,OAAO,YAAY,WAAW,EAAE,MAAM,QAAQ,IAAI;AAAA,EACpD;AACF;;;AClBA,SAAS,kBAAkB;AAC3B,SAAS,mBAAmB;AAE5B,OAAO,gBAAgB;AAEhB,IAAM,iBAAN,MAAqB;AAAA,EAM1B,YACqB,SACnB;AADmB;AAAA,EAClB;AAA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AAY,WAAW,EAAE,MAAM,QAAQ,IAAI;AAC5E,SAAO,QAAQ,QACZ,MAAM,MAAM,IAAI,CAAC,EACjB,MAAM,MAAM,IAAI,CAAC,EACjB,MAAM,KAAK,IAAI,CAAC,EAChB,MAAM,MAAM,IAAI,CAAC;AACtB;","names":["i18n","i18n","arr","middleware","cronParser","schedule","schedule","i18n","i18n","middleware","commandName","middleware","schedule","i18n","i18n","middleware","net","chalk","commandName","middleware","net","i18n","i18n","middleware","net","Spinnies","chalk","commandName","middleware","net","Spinnies","chalk","i18n","stats"]}
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@aomex/cron",
|
|
3
|
-
"version": "
|
|
4
|
-
"description": "",
|
|
3
|
+
"version": "1.0.1",
|
|
4
|
+
"description": "定时任务",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"types": "dist/index.d.ts",
|
|
7
7
|
"exports": {
|
|
@@ -26,23 +26,24 @@
|
|
|
26
26
|
"homepage": "https://aomex.js.org",
|
|
27
27
|
"license": "MIT",
|
|
28
28
|
"peerDependencies": {
|
|
29
|
-
"@aomex/commander": "^0.0
|
|
30
|
-
"@aomex/console": "^0.0
|
|
31
|
-
"@aomex/core": "^0.0
|
|
29
|
+
"@aomex/commander": "^1.0.0",
|
|
30
|
+
"@aomex/console": "^1.0.0",
|
|
31
|
+
"@aomex/core": "^1.0.0"
|
|
32
32
|
},
|
|
33
33
|
"dependencies": {
|
|
34
|
-
"cron-parser": "^4.
|
|
35
|
-
"
|
|
36
|
-
"
|
|
37
|
-
"@aomex/internal-file-import": "^
|
|
34
|
+
"cron-parser": "^4.9.0",
|
|
35
|
+
"pidusage": "^3.0.2",
|
|
36
|
+
"spinnies": "^0.5.1",
|
|
37
|
+
"@aomex/internal-file-import": "^1.0.1",
|
|
38
|
+
"@aomex/internal-tools": "^1.0.1",
|
|
39
|
+
"@aomex/memory-cache": "^1.0.1"
|
|
38
40
|
},
|
|
39
41
|
"devDependencies": {
|
|
40
|
-
"@
|
|
41
|
-
"@
|
|
42
|
-
"@aomex/
|
|
43
|
-
"
|
|
42
|
+
"@types/pidusage": "^2.0.5",
|
|
43
|
+
"@types/spinnies": "^0.5.3",
|
|
44
|
+
"@aomex/commander": "^1.0.1",
|
|
45
|
+
"@aomex/console": "^1.0.1",
|
|
46
|
+
"@aomex/core": "^1.0.1"
|
|
44
47
|
},
|
|
45
|
-
"scripts": {
|
|
46
|
-
"test": "vitest"
|
|
47
|
-
}
|
|
48
|
+
"scripts": {}
|
|
48
49
|
}
|