@mp-assistant/cli 0.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.
Files changed (41) hide show
  1. package/LICENSE +21 -0
  2. package/dist/bin/index.d.ts +3 -0
  3. package/dist/bin/index.d.ts.map +1 -0
  4. package/dist/bin/index.js +22 -0
  5. package/dist/event/WSMessageEvent.d.ts +7 -0
  6. package/dist/event/WSMessageEvent.d.ts.map +1 -0
  7. package/dist/event/WSMessageEvent.js +20 -0
  8. package/dist/hooks/useLocalStore.d.ts +7 -0
  9. package/dist/hooks/useLocalStore.d.ts.map +1 -0
  10. package/dist/hooks/useLocalStore.js +23 -0
  11. package/dist/pathManage.d.ts +2 -0
  12. package/dist/pathManage.d.ts.map +1 -0
  13. package/dist/pathManage.js +7 -0
  14. package/dist/server/api/index.d.ts +3 -0
  15. package/dist/server/api/index.d.ts.map +1 -0
  16. package/dist/server/api/index.js +8 -0
  17. package/dist/server/api/modules/common.d.ts +3 -0
  18. package/dist/server/api/modules/common.d.ts.map +1 -0
  19. package/dist/server/api/modules/common.js +30 -0
  20. package/dist/server/api/modules/config.d.ts +3 -0
  21. package/dist/server/api/modules/config.d.ts.map +1 -0
  22. package/dist/server/api/modules/config.js +13 -0
  23. package/dist/server/api/modules/worker.d.ts +3 -0
  24. package/dist/server/api/modules/worker.d.ts.map +1 -0
  25. package/dist/server/api/modules/worker.js +138 -0
  26. package/dist/server/ws/index.d.ts +3 -0
  27. package/dist/server/ws/index.d.ts.map +1 -0
  28. package/dist/server/ws/index.js +7 -0
  29. package/dist/start.d.ts +5 -0
  30. package/dist/start.d.ts.map +1 -0
  31. package/dist/start.js +72 -0
  32. package/dist/store/ConfigStore.d.ts +10 -0
  33. package/dist/store/ConfigStore.d.ts.map +1 -0
  34. package/dist/store/ConfigStore.js +32 -0
  35. package/dist/store/WSStore.d.ts +20 -0
  36. package/dist/store/WSStore.d.ts.map +1 -0
  37. package/dist/store/WSStore.js +76 -0
  38. package/dist/store/WorkerStore.d.ts +11 -0
  39. package/dist/store/WorkerStore.d.ts.map +1 -0
  40. package/dist/store/WorkerStore.js +38 -0
  41. package/package.json +37 -0
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2024 Taozi
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,3 @@
1
+ #!/usr/bin/env node
2
+ export {};
3
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/bin/index.ts"],"names":[],"mappings":""}
@@ -0,0 +1,22 @@
1
+ #!/usr/bin/env node
2
+ import { program } from 'commander';
3
+ import fs from 'fs';
4
+ import path from 'path';
5
+ import { getRootDir } from '../pathManage.js';
6
+ import { ConfigStore } from '../store/ConfigStore.js';
7
+ import { start } from '../start.js';
8
+ const rootPackageJson = JSON.parse(fs.readFileSync(path.join(getRootDir(), 'package.json')).toString());
9
+ program
10
+ .version(rootPackageJson.version)
11
+ .description('小程序助手')
12
+ //
13
+ .command('start')
14
+ .action(() => {
15
+ ConfigStore.instance.setConfig({
16
+ executablePath: 'C:/Program Files/Google/Chrome/Application/chrome.exe',
17
+ headless: false,
18
+ port: 3001,
19
+ });
20
+ start();
21
+ });
22
+ program.parse(process.argv);
@@ -0,0 +1,7 @@
1
+ import { WSMessage } from "@mp-assistant/common/dist/ws/index.js";
2
+ export declare class WSMessageEvent extends WSMessage.Event {
3
+ private static __instance;
4
+ static get instance(): WSMessageEvent;
5
+ constructor();
6
+ }
7
+ //# sourceMappingURL=WSMessageEvent.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"WSMessageEvent.d.ts","sourceRoot":"","sources":["../../src/event/WSMessageEvent.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,MAAM,uCAAuC,CAAC;AAGlE,qBAAa,cAAe,SAAQ,SAAS,CAAC,KAAK;IAC/C,OAAO,CAAC,MAAM,CAAC,UAAU,CAA+B;IACxD,WAAkB,QAAQ,mBAEzB;;CAeJ"}
@@ -0,0 +1,20 @@
1
+ import { WSMessage } from "@mp-assistant/common/dist/ws/index.js";
2
+ import { WSStore } from "../store/WSStore.js";
3
+ export class WSMessageEvent extends WSMessage.Event {
4
+ static __instance = null;
5
+ static get instance() {
6
+ return this.__instance ?? (this.__instance = new WSMessageEvent());
7
+ }
8
+ constructor() {
9
+ super();
10
+ /**
11
+ * 转发消息
12
+ */
13
+ this.on('*', (type, event) => {
14
+ WSStore.instance.broadcast({
15
+ type,
16
+ data: event
17
+ });
18
+ });
19
+ }
20
+ }
@@ -0,0 +1,7 @@
1
+ export declare function useLocalStore<T>(name: string, defaultValue: T, options: {
2
+ storeDir?: string;
3
+ }): {
4
+ get: () => T;
5
+ set: (value: T) => void;
6
+ };
7
+ //# sourceMappingURL=useLocalStore.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"useLocalStore.d.ts","sourceRoot":"","sources":["../../src/hooks/useLocalStore.ts"],"names":[],"mappings":"AAGA,wBAAgB,aAAa,CAAC,CAAC,EAAE,IAAI,EAAE,MAAM,EAAE,YAAY,EAAE,CAAC,EAAE,OAAO,EAAE;IACrE,QAAQ,CAAC,EAAE,MAAM,CAAC;CACrB;;iBAcuB,CAAC;EAQxB"}
@@ -0,0 +1,23 @@
1
+ import path from "path";
2
+ import fs from "fs";
3
+ export function useLocalStore(name, defaultValue, options) {
4
+ const { storeDir = './' } = options;
5
+ const localStorePath = path.join(storeDir, `${name}.json`);
6
+ const get = () => {
7
+ try {
8
+ const localStore = JSON.parse(fs.readFileSync(localStorePath, 'utf-8'));
9
+ return localStore;
10
+ }
11
+ catch (error) {
12
+ set(defaultValue);
13
+ return defaultValue;
14
+ }
15
+ };
16
+ const set = (value) => {
17
+ fs.writeFileSync(localStorePath, JSON.stringify(value, null, 2));
18
+ };
19
+ return {
20
+ get,
21
+ set,
22
+ };
23
+ }
@@ -0,0 +1,2 @@
1
+ export declare function getRootDir(): string;
2
+ //# sourceMappingURL=pathManage.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"pathManage.d.ts","sourceRoot":"","sources":["../src/pathManage.ts"],"names":[],"mappings":"AAMA,wBAAgB,UAAU,WAEzB"}
@@ -0,0 +1,7 @@
1
+ import { fileURLToPath } from "url";
2
+ import path from "path";
3
+ const __filename = fileURLToPath(import.meta.url);
4
+ const __dirname = path.dirname(__filename);
5
+ export function getRootDir() {
6
+ return path.join(__dirname, "..");
7
+ }
@@ -0,0 +1,3 @@
1
+ import { FastifyInstance } from "fastify";
2
+ export declare const registerApi: (fastify: FastifyInstance) => void;
3
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/server/api/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,eAAe,EAAE,MAAM,SAAS,CAAC;AAK1C,eAAO,MAAM,WAAW,GAAI,SAAS,eAAe,SAInD,CAAA"}
@@ -0,0 +1,8 @@
1
+ import { registerConfigApi } from "./modules/config.js";
2
+ import { registerWorkerApi } from "./modules/worker.js";
3
+ import { registerCommonApi } from "./modules/common.js";
4
+ export const registerApi = (fastify) => {
5
+ registerCommonApi(fastify);
6
+ registerConfigApi(fastify);
7
+ registerWorkerApi(fastify);
8
+ };
@@ -0,0 +1,3 @@
1
+ import { FastifyInstance } from "fastify";
2
+ export declare const registerCommonApi: (fastify: FastifyInstance) => void;
3
+ //# sourceMappingURL=common.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"common.d.ts","sourceRoot":"","sources":["../../../../src/server/api/modules/common.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,eAAe,EAAE,MAAM,SAAS,CAAC;AAW1C,eAAO,MAAM,iBAAiB,GAAI,SAAS,eAAe,SA4BzD,CAAC"}
@@ -0,0 +1,30 @@
1
+ import { Api } from "@mp-assistant/common/dist/api/index.js";
2
+ import { getErrorApiResponse, getSuccessApiResponse } from "@mp-assistant/common/dist/api/utils.js";
3
+ import { pipeline } from "node:stream/promises";
4
+ import fs from "node:fs";
5
+ import path from "node:path";
6
+ import dayjs from "dayjs";
7
+ import { getUUID } from "@mp-assistant/common/dist/utils/index.js";
8
+ import { getFilesDir } from "@mp-assistant/common/dist/pathManage.js";
9
+ import { pathNormalize } from "@mp-assistant/common/dist/utils/node.js";
10
+ export const registerCommonApi = (fastify) => {
11
+ fastify.post(Api.Common.UploadFile.url, async function (req, reply) {
12
+ const data = await req.file();
13
+ if (!data) {
14
+ return getErrorApiResponse('Worker not found', 404);
15
+ }
16
+ const fileDir = path.join(getFilesDir(), dayjs().format('YYYY/MM/DD'));
17
+ const fileName = `${getUUID()}.${data.filename.split('.')?.[1] || ''}`;
18
+ if (!fs.existsSync(fileDir)) {
19
+ fs.mkdirSync(fileDir, { recursive: true });
20
+ }
21
+ await pipeline(data.file, fs.createWriteStream(path.join(fileDir, fileName)));
22
+ return getSuccessApiResponse(pathNormalize(path.join(fileDir, fileName)));
23
+ });
24
+ fastify.get(Api.Common.GetFile.url, async function (req, reply) {
25
+ const { filePath } = req.query;
26
+ const fileDir = path.dirname(decodeURIComponent(filePath));
27
+ const fileName = path.basename(decodeURIComponent(filePath));
28
+ return reply.sendFile(fileName, fileDir);
29
+ });
30
+ };
@@ -0,0 +1,3 @@
1
+ import { FastifyInstance } from "fastify";
2
+ export declare const registerConfigApi: (fastify: FastifyInstance) => void;
3
+ //# sourceMappingURL=config.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"config.d.ts","sourceRoot":"","sources":["../../../../src/server/api/modules/config.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,eAAe,EAAE,MAAM,SAAS,CAAC;AAM1C,eAAO,MAAM,iBAAiB,GAAI,SAAS,eAAe,SAWzD,CAAA"}
@@ -0,0 +1,13 @@
1
+ import { ConfigStore } from "../../../store/ConfigStore.js";
2
+ import { Api } from "@mp-assistant/common/dist/api/index.js";
3
+ import { getSuccessApiResponse } from "@mp-assistant/common/dist/api/utils.js";
4
+ export const registerConfigApi = (fastify) => {
5
+ fastify.get(Api.Config.GetConfig.url, async (request, reply) => {
6
+ return getSuccessApiResponse(ConfigStore.instance.config);
7
+ });
8
+ fastify.post(Api.Config.SetConfig.url, async (request, reply) => {
9
+ const config = request.body;
10
+ ConfigStore.instance.setConfig(config);
11
+ return getSuccessApiResponse(ConfigStore.instance.config);
12
+ });
13
+ };
@@ -0,0 +1,3 @@
1
+ import { FastifyInstance } from "fastify";
2
+ export declare const registerWorkerApi: (fastify: FastifyInstance) => void;
3
+ //# sourceMappingURL=worker.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"worker.d.ts","sourceRoot":"","sources":["../../../../src/server/api/modules/worker.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,eAAe,EAAE,MAAM,SAAS,CAAC;AAW1C,eAAO,MAAM,iBAAiB,GAAI,SAAS,eAAe,SA2JzD,CAAA"}
@@ -0,0 +1,138 @@
1
+ import { WorkerStore } from "../../../store/WorkerStore.js";
2
+ import { Api } from "@mp-assistant/common/dist/api/index.js";
3
+ import { createWorker, isWXWorker } from "@mp-assistant/core/dist/worker/index.js";
4
+ import { ConfigStore } from "../../../store/ConfigStore.js";
5
+ import { createTask } from "@mp-assistant/core/dist/worker/wx/task/index.js";
6
+ import { getSuccessApiResponse, getErrorApiResponse } from "@mp-assistant/common/dist/api/utils.js";
7
+ import { WSStore } from "../../../store/WSStore.js";
8
+ import { WSMessage } from "@mp-assistant/common/dist/ws/message.js";
9
+ import { WSMessageEvent } from "../../../event/WSMessageEvent.js";
10
+ export const registerWorkerApi = (fastify) => {
11
+ fastify.get(Api.Worker.GetWorkerList.url, async (request, reply) => {
12
+ const workerInfos = WorkerStore.instance.workerList.map(item => {
13
+ return item.info();
14
+ });
15
+ return getSuccessApiResponse(workerInfos);
16
+ });
17
+ fastify.get(Api.Worker.GetWorkerDetail.url, async (request, reply) => {
18
+ const { key } = request.query;
19
+ const worker = WorkerStore.instance.workerList.find(item => item.key === key);
20
+ if (!worker) {
21
+ return getErrorApiResponse('Worker not found', 404);
22
+ }
23
+ return getSuccessApiResponse(worker.info());
24
+ });
25
+ fastify.post(Api.Worker.AddWorker.url, async (request, reply) => {
26
+ const { type, name } = request.body;
27
+ const worker = createWorker(type, {
28
+ name,
29
+ wsMessageEventHandler: WSMessageEvent.instance,
30
+ });
31
+ await worker.init({
32
+ executablePath: ConfigStore.instance.config.executablePath,
33
+ headless: ConfigStore.instance.config.headless,
34
+ });
35
+ WorkerStore.instance.addWorker(worker);
36
+ WSStore.instance.broadcast(WSMessage.Worker.ListChange.createMessage());
37
+ return getSuccessApiResponse(worker.info());
38
+ });
39
+ fastify.delete(Api.Worker.RemoveWorker.url, async (request, reply) => {
40
+ const { key } = request.query;
41
+ const worker = WorkerStore.instance.workerList.find(item => item.key === key);
42
+ if (!worker) {
43
+ return getErrorApiResponse('Worker not found', 404);
44
+ }
45
+ await worker.destroy();
46
+ WorkerStore.instance.removeWorker(worker);
47
+ WSStore.instance.broadcast(WSMessage.Worker.ListChange.createMessage());
48
+ return getSuccessApiResponse(undefined);
49
+ });
50
+ fastify.put(Api.Worker.UpdateWorker.url, async (request, reply) => {
51
+ const { key } = request.query;
52
+ const { name } = request.body;
53
+ const worker = WorkerStore.instance.workerList.find(item => item.key === key);
54
+ if (!worker) {
55
+ return getErrorApiResponse('Worker not found', 404);
56
+ }
57
+ worker.name = name || worker.name;
58
+ WSStore.instance.broadcast(WSMessage.Worker.DetailChange.createMessage({ key }));
59
+ return getSuccessApiResponse(worker.info());
60
+ });
61
+ fastify.post(Api.Worker.WorkerLogin.url, async (request, reply) => {
62
+ const { key } = request.query;
63
+ const worker = WorkerStore.instance.workerList.find(item => item.key === key);
64
+ if (!worker) {
65
+ return getErrorApiResponse('Worker not found', 404);
66
+ }
67
+ if (isWXWorker(worker)) {
68
+ worker.login();
69
+ return getSuccessApiResponse(undefined);
70
+ }
71
+ else {
72
+ return getErrorApiResponse('Worker type not supported', 400);
73
+ }
74
+ });
75
+ fastify.post(Api.Worker.WorkerLogout.url, async (request, reply) => {
76
+ const { key } = request.query;
77
+ const worker = WorkerStore.instance.workerList.find(item => item.key === key);
78
+ if (!worker) {
79
+ return getErrorApiResponse('Worker not found', 404);
80
+ }
81
+ if (isWXWorker(worker)) {
82
+ worker.logout();
83
+ return getSuccessApiResponse(undefined);
84
+ }
85
+ else {
86
+ return getErrorApiResponse('Worker type not supported', 400);
87
+ }
88
+ });
89
+ fastify.get(Api.Worker.WorkerUpdateWxaList.url, async (request, reply) => {
90
+ const { key } = request.query;
91
+ const worker = WorkerStore.instance.workerList.find(item => item.key === key);
92
+ if (!worker) {
93
+ return getErrorApiResponse('Worker not found', 404);
94
+ }
95
+ if (isWXWorker(worker)) {
96
+ worker.updateWxaList();
97
+ return getSuccessApiResponse(undefined);
98
+ }
99
+ else {
100
+ return getErrorApiResponse('Worker type not supported', 400);
101
+ }
102
+ });
103
+ fastify.post(Api.Worker.AddTask.url, async (request, reply) => {
104
+ const { key } = request.query;
105
+ const { type, options } = request.body;
106
+ const worker = WorkerStore.instance.workerList.find(item => item.key === key);
107
+ if (!worker) {
108
+ return getErrorApiResponse('Worker not found', 404);
109
+ }
110
+ const task = createTask(type, options);
111
+ if (!task) {
112
+ return getErrorApiResponse('Task not found', 400);
113
+ }
114
+ worker.addTask(task);
115
+ return getSuccessApiResponse(worker.info());
116
+ });
117
+ fastify.delete(Api.Worker.RemoveTask.url, async (request, reply) => {
118
+ const { key, taskKey } = request.query;
119
+ const worker = WorkerStore.instance.workerList.find(item => item.key === key);
120
+ if (!worker) {
121
+ return getErrorApiResponse('Worker not found', 404);
122
+ }
123
+ await worker.removeTask(taskKey);
124
+ return getSuccessApiResponse(worker.info());
125
+ });
126
+ fastify.get(Api.Worker.TaskDetail.url, async (request, reply) => {
127
+ const { key, taskKey } = request.query;
128
+ const worker = WorkerStore.instance.workerList.find(item => item.key === key);
129
+ if (!worker) {
130
+ return getErrorApiResponse('Worker not found', 404);
131
+ }
132
+ const task = worker.taskList.find(item => item.key === taskKey);
133
+ if (!task) {
134
+ return getErrorApiResponse('Task not found', 404);
135
+ }
136
+ return getSuccessApiResponse(task.info());
137
+ });
138
+ };
@@ -0,0 +1,3 @@
1
+ import { FastifyInstance } from "fastify";
2
+ export declare const registerWebSocket: (fastify: FastifyInstance) => Promise<void>;
3
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/server/ws/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,eAAe,EAAE,MAAM,SAAS,CAAC;AAI1C,eAAO,MAAM,iBAAiB,GAAU,SAAS,eAAe,kBAK/D,CAAA"}
@@ -0,0 +1,7 @@
1
+ import { WSStore } from "../../store/WSStore.js";
2
+ import { WSUrl } from "@mp-assistant/common/dist/ws/index.js";
3
+ export const registerWebSocket = async (fastify) => {
4
+ fastify.get(WSUrl, { websocket: true }, (socket, request) => {
5
+ WSStore.instance.connection(socket);
6
+ });
7
+ };
@@ -0,0 +1,5 @@
1
+ /**
2
+ * Run the server!
3
+ */
4
+ export declare const start: () => Promise<void>;
5
+ //# sourceMappingURL=start.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"start.d.ts","sourceRoot":"","sources":["../src/start.ts"],"names":[],"mappings":"AAiBA;;GAEG;AACH,eAAO,MAAM,KAAK,qBAYjB,CAAA"}
package/dist/start.js ADDED
@@ -0,0 +1,72 @@
1
+ import path from 'path';
2
+ import { createRequire } from 'module';
3
+ import Fastify from 'fastify';
4
+ import fastifyStatic from '@fastify/static';
5
+ import fastifyWebsocket from '@fastify/websocket';
6
+ import { ConfigStore } from './store/ConfigStore.js';
7
+ import { registerWebSocket } from './server/ws/index.js';
8
+ import { registerApi } from './server/api/index.js';
9
+ import { ApiPrefix } from '@mp-assistant/common/dist/api/index.js';
10
+ import { getErrorApiResponse } from '@mp-assistant/common/dist/api/utils.js';
11
+ import { WorkerStore } from './store/WorkerStore.js';
12
+ import fastifyCors from '@fastify/cors';
13
+ import multipart from '@fastify/multipart';
14
+ const require = createRequire(import.meta.url);
15
+ /**
16
+ * Run the server!
17
+ */
18
+ export const start = async () => {
19
+ startServer();
20
+ /**
21
+ * 初始化worker
22
+ */
23
+ for (const worker of WorkerStore.instance.workerList) {
24
+ await worker.init({
25
+ executablePath: ConfigStore.instance.config.executablePath,
26
+ headless: ConfigStore.instance.config.headless,
27
+ });
28
+ }
29
+ };
30
+ const startServer = async () => {
31
+ const fastify = Fastify({
32
+ // logger: true
33
+ });
34
+ // 注册 WebSocket 插件
35
+ await fastify.register(fastifyWebsocket);
36
+ fastify.register(multipart, {
37
+ //
38
+ });
39
+ // 设置跨域
40
+ fastify.register(fastifyCors, {
41
+ origin: '*',
42
+ methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],
43
+ allowedHeaders: ['Content-Type', 'Authorization'],
44
+ });
45
+ // 注册静态目录,指向 @mp-assistant/dashboard 包的 dist 目录
46
+ const dashboardDir = path.join(path.dirname(require.resolve('@mp-assistant/dashboard/package.json')), 'dist');
47
+ await fastify.register(fastifyStatic, {
48
+ root: dashboardDir,
49
+ prefix: '/',
50
+ });
51
+ // WebSocket 路由
52
+ await fastify.register(registerWebSocket);
53
+ // api 路由
54
+ await fastify.register(registerApi, { prefix: ApiPrefix });
55
+ // 统一错误响应格式
56
+ fastify.setErrorHandler((error, request, reply) => {
57
+ const statusCode = error.statusCode ?? 500;
58
+ reply.status(200).send(getErrorApiResponse(error.message || 'Internal Server Error', ([400, 401, 403, 404, 500].includes(statusCode) ? statusCode : 500)));
59
+ });
60
+ // 统一 404 响应格式
61
+ fastify.setNotFoundHandler((request, reply) => {
62
+ reply.status(200).send(getErrorApiResponse(`Route ${request.method} ${request.url} not found`, 404));
63
+ });
64
+ try {
65
+ await fastify.listen({ port: ConfigStore.instance.config.port });
66
+ console.log(`Server is running on http://localhost:${ConfigStore.instance.config.port}`);
67
+ }
68
+ catch (err) {
69
+ fastify.log.error(err);
70
+ process.exit(1);
71
+ }
72
+ };
@@ -0,0 +1,10 @@
1
+ import { Config } from "@mp-assistant/common/dist/types/config.js";
2
+ export declare class ConfigStore {
3
+ private static __instance;
4
+ static get instance(): ConfigStore;
5
+ private __config;
6
+ get config(): Config;
7
+ constructor();
8
+ setConfig(config: Partial<Config>): void;
9
+ }
10
+ //# sourceMappingURL=ConfigStore.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ConfigStore.d.ts","sourceRoot":"","sources":["../../src/store/ConfigStore.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,MAAM,EAAE,MAAM,2CAA2C,CAAC;AAanE,qBAAa,WAAW;IACpB,OAAO,CAAC,MAAM,CAAC,UAAU,CAA4B;IACrD,WAAkB,QAAQ,gBAEzB;IAED,OAAO,CAAC,QAAQ,CAEf;IAED,IAAI,MAAM,WAET;;IAMD,SAAS,CAAC,MAAM,EAAE,OAAO,CAAC,MAAM,CAAC;CAOpC"}
@@ -0,0 +1,32 @@
1
+ import { useLocalStore } from "../hooks/useLocalStore.js";
2
+ import { getStoreDir } from "@mp-assistant/common/dist/pathManage.js";
3
+ const DEFAULT_CONFIG = {
4
+ executablePath: '',
5
+ headless: true,
6
+ port: 3001,
7
+ };
8
+ const { get: getConfigLocalStore, set: setConfigLocalStore } = useLocalStore('config', DEFAULT_CONFIG, {
9
+ storeDir: getStoreDir(),
10
+ });
11
+ export class ConfigStore {
12
+ static __instance = null;
13
+ static get instance() {
14
+ return this.__instance ?? (this.__instance = new ConfigStore());
15
+ }
16
+ __config = {
17
+ ...DEFAULT_CONFIG,
18
+ };
19
+ get config() {
20
+ return this.__config;
21
+ }
22
+ constructor() {
23
+ this.__config = getConfigLocalStore();
24
+ }
25
+ setConfig(config) {
26
+ this.__config = {
27
+ ...this.__config,
28
+ ...config,
29
+ };
30
+ setConfigLocalStore(this.__config);
31
+ }
32
+ }
@@ -0,0 +1,20 @@
1
+ import { WebSocket } from "ws";
2
+ import { EventEmitter } from "@mp-assistant/common/dist/event/EventEmitter.js";
3
+ import { WSMessageFormat } from "@mp-assistant/common/dist/ws/index.js";
4
+ export interface EventMap {
5
+ /** 收到ws消息 */
6
+ message: WSMessageFormat<any>;
7
+ }
8
+ export declare class WSStore extends EventEmitter<EventMap> {
9
+ private static __instance;
10
+ static get instance(): WSStore;
11
+ private __connectionWsList;
12
+ constructor();
13
+ connection(ws: WebSocket): void;
14
+ /**
15
+ * 广播消息
16
+ * @param message
17
+ */
18
+ broadcast(message: WSMessageFormat<any>): Promise<void>;
19
+ }
20
+ //# sourceMappingURL=WSStore.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"WSStore.d.ts","sourceRoot":"","sources":["../../src/store/WSStore.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,SAAS,EAAE,MAAM,IAAI,CAAC;AAC/B,OAAO,EAAE,YAAY,EAAE,MAAM,iDAAiD,CAAC;AAC/E,OAAO,EAAa,eAAe,EAAE,MAAM,uCAAuC,CAAC;AAEnF,MAAM,WAAW,QAAQ;IACrB,aAAa;IACb,OAAO,EAAE,eAAe,CAAC,GAAG,CAAC,CAAC;CACjC;AAED,qBAAa,OAAQ,SAAQ,YAAY,CAAC,QAAQ,CAAC;IAC/C,OAAO,CAAC,MAAM,CAAC,UAAU,CAAuB;IAChD,WAAkB,QAAQ,YAEzB;IAED,OAAO,CAAC,kBAAkB,CAKjB;;IAmBT,UAAU,CAAC,EAAE,EAAE,SAAS;IAgCxB;;;OAGG;IACG,SAAS,CAAC,OAAO,EAAE,eAAe,CAAC,GAAG,CAAC;CAehD"}
@@ -0,0 +1,76 @@
1
+ import { getUUID } from "@mp-assistant/common/dist/utils/index.js";
2
+ import { WebSocket } from "ws";
3
+ import { EventEmitter } from "@mp-assistant/common/dist/event/EventEmitter.js";
4
+ import { WSMessage } from "@mp-assistant/common/dist/ws/index.js";
5
+ export class WSStore extends EventEmitter {
6
+ static __instance = null;
7
+ static get instance() {
8
+ return this.__instance ?? (this.__instance = new WSStore());
9
+ }
10
+ __connectionWsList = [];
11
+ constructor() {
12
+ super();
13
+ // 定时发送心跳消息
14
+ setInterval(() => {
15
+ this.broadcast(WSMessage.Heartbeat.createMessage());
16
+ }, WSMessage.Heartbeat.loopInterval);
17
+ // 定时检查连接状态,关闭超时的连接
18
+ setInterval(() => {
19
+ this.__connectionWsList.forEach(item => {
20
+ if (Date.now() - item.activeTime > WSMessage.Heartbeat.timeout) {
21
+ item.ws.close();
22
+ }
23
+ });
24
+ }, 500);
25
+ }
26
+ connection(ws) {
27
+ const key = getUUID();
28
+ this.__connectionWsList.push({
29
+ key,
30
+ ws,
31
+ activeTime: Date.now(),
32
+ });
33
+ // 监听消息
34
+ ws.on('message', (data) => {
35
+ try {
36
+ const message = JSON.parse(data.toString());
37
+ // 只处理非心跳消息。
38
+ if (message.type !== WSMessage.Heartbeat.type) {
39
+ this.emit('message', message);
40
+ }
41
+ // 更新活跃时间
42
+ const currentWs = this.__connectionWsList.find(item => item.key === key);
43
+ if (currentWs) {
44
+ currentWs.activeTime = Date.now();
45
+ }
46
+ }
47
+ catch (e) {
48
+ // 不是json格式的消息,忽略
49
+ return;
50
+ }
51
+ });
52
+ // 监听关闭
53
+ ws.on('close', () => {
54
+ this.__connectionWsList = this.__connectionWsList.filter(item => item.ws !== ws);
55
+ });
56
+ }
57
+ /**
58
+ * 广播消息
59
+ * @param message
60
+ */
61
+ async broadcast(message) {
62
+ await Promise.allSettled(this.__connectionWsList.map(item => {
63
+ return new Promise((res, rej) => {
64
+ if (item.ws.readyState === WebSocket.OPEN) {
65
+ item.ws.send(JSON.stringify(message), (error) => {
66
+ if (error) {
67
+ rej();
68
+ return;
69
+ }
70
+ res();
71
+ });
72
+ }
73
+ });
74
+ }));
75
+ }
76
+ }
@@ -0,0 +1,11 @@
1
+ import type { BaseWorker } from "@mp-assistant/core/dist/worker/BaseWorker.js";
2
+ export declare class WorkerStore {
3
+ private static __instance;
4
+ static get instance(): WorkerStore;
5
+ private __workerList;
6
+ get workerList(): BaseWorker[];
7
+ constructor();
8
+ addWorker(worker: BaseWorker): void;
9
+ removeWorker(worker: BaseWorker): void;
10
+ }
11
+ //# sourceMappingURL=WorkerStore.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"WorkerStore.d.ts","sourceRoot":"","sources":["../../src/store/WorkerStore.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,8CAA8C,CAAC;AAc/E,qBAAa,WAAW;IACpB,OAAO,CAAC,MAAM,CAAC,UAAU,CAA4B;IACrD,WAAkB,QAAQ,gBAEzB;IAED,OAAO,CAAC,YAAY,CAAoB;IAExC,IAAI,UAAU,iBAEb;;IAYD,SAAS,CAAC,MAAM,EAAE,UAAU;IAS5B,YAAY,CAAC,MAAM,EAAE,UAAU;CAIlC"}
@@ -0,0 +1,38 @@
1
+ import { getStoreDir } from "@mp-assistant/common/dist/pathManage.js";
2
+ import { useLocalStore } from "../hooks/useLocalStore.js";
3
+ import { createWorker } from "@mp-assistant/core/dist/worker/index.js";
4
+ import { WSMessageEvent } from "../event/WSMessageEvent.js";
5
+ const { get: getWorkerLocalStoreList, set: setWorkerLocalStoreList } = useLocalStore('workerList', [], {
6
+ storeDir: getStoreDir(),
7
+ });
8
+ export class WorkerStore {
9
+ static __instance = null;
10
+ static get instance() {
11
+ return this.__instance ?? (this.__instance = new WorkerStore());
12
+ }
13
+ __workerList = [];
14
+ get workerList() {
15
+ return [...this.__workerList];
16
+ }
17
+ constructor() {
18
+ this.__workerList = getWorkerLocalStoreList().map(item => {
19
+ return createWorker(item.type, {
20
+ key: item.key,
21
+ name: item.name,
22
+ wsMessageEventHandler: WSMessageEvent.instance,
23
+ });
24
+ });
25
+ }
26
+ addWorker(worker) {
27
+ this.__workerList.push(worker);
28
+ setWorkerLocalStoreList([...getWorkerLocalStoreList(), {
29
+ key: worker.key,
30
+ type: worker.type,
31
+ name: worker.name,
32
+ }]);
33
+ }
34
+ removeWorker(worker) {
35
+ this.__workerList = this.__workerList.filter(w => w.key !== worker.key);
36
+ setWorkerLocalStoreList(getWorkerLocalStoreList().filter(item => item.key !== worker.key));
37
+ }
38
+ }
package/package.json ADDED
@@ -0,0 +1,37 @@
1
+ {
2
+ "name": "@mp-assistant/cli",
3
+ "version": "0.0.1",
4
+ "description": "",
5
+ "type": "module",
6
+ "main": "index.js",
7
+ "keywords": [],
8
+ "author": "",
9
+ "license": "ISC",
10
+ "dependencies": {
11
+ "@fastify/cors": "^11.2.0",
12
+ "@fastify/multipart": "^9.4.0",
13
+ "@fastify/static": "^9.0.0",
14
+ "@fastify/websocket": "^11.2.0",
15
+ "commander": "^14.0.3",
16
+ "dayjs": "^1.11.13",
17
+ "fastify": "^5.7.4",
18
+ "ws": "^8.19.0",
19
+ "@mp-assistant/common": "0.0.1",
20
+ "@mp-assistant/dashboard": "0.0.1",
21
+ "@mp-assistant/core": "0.0.1"
22
+ },
23
+ "devDependencies": {
24
+ "@types/ws": "^8.18.1",
25
+ "@mp-assistant/scripts": "0.0.1",
26
+ "@mp-assistant/configuration": "0.0.1"
27
+ },
28
+ "repository": {
29
+ "type": "git",
30
+ "url": "https://github.com/taozijiankang/mp-assistant.git"
31
+ },
32
+ "scripts": {
33
+ "clear-build-product": "mp-c clear-build-product",
34
+ "dev": "tsc --watch",
35
+ "build": "tsc"
36
+ }
37
+ }