nx-kv 0.46.0 → 0.47.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +37 -0
- package/README.md +10 -4
- package/bin/{cli.mjs → kv.mjs} +13 -2
- package/package.json +23 -11
- package/src/core/{command-table.js → command-table.ts} +16 -5
- package/src/core/{config.js → config.ts} +46 -27
- package/src/core/db/quiet.js +4 -0
- package/src/core/{errors.js → errors.ts} +35 -18
- package/src/core/{open.js → open.ts} +3 -3
- package/src/core/{paths.js → paths.ts} +18 -9
- package/src/core/{serve-port.js → serve-port.ts} +43 -17
- package/src/index.js +11 -9
- package/src/index.ts +10 -0
- package/src/modules/system/actions/_manifest.generated.ts +23 -0
- package/src/modules/system/actions/bootstrap.ts +74 -0
- package/src/modules/system/actions/health.ts +57 -0
- package/src/modules/system/actions/routes.ts +26 -0
- package/src/modules/system/index.ts +29 -0
- package/src/modules/system/{routes.js → routes.ts} +22 -26
- package/src/modules/system/schemas.ts +29 -0
- package/src/modules/tasktool/panel-escort.js +1 -1
- package/src/runtime/action-base.ts +14 -0
- package/src/runtime/action-decorator.ts +176 -0
- package/src/runtime/api.ts +146 -0
- package/src/runtime/{cli.js → cli.ts} +241 -161
- package/src/runtime/codegen.ts +243 -0
- package/src/runtime/container.ts +53 -0
- package/src/runtime/{cors.js → cors.ts} +35 -28
- package/src/runtime/help.ts +77 -0
- package/src/runtime/registry.ts +139 -0
- package/src/runtime/{server.js → server.ts} +65 -24
- package/src/runtime/{spec.js → spec.ts} +122 -31
- package/src/runtime/types/module.ts +43 -0
- package/src/runtime/zod-bridge.ts +198 -0
- package/src/web/frontend/api/cli-tree.json +49 -0
- package/src/web/frontend/api/client.generated.ts +39 -0
- package/src/modules/system/index.js +0 -96
- package/src/runtime/api.js +0 -101
- package/src/runtime/registry.js +0 -89
|
@@ -25,7 +25,7 @@ export const NO_OPEN_ENV = 'NX_SERVE_NO_OPEN';
|
|
|
25
25
|
export const PROBE_TIMEOUT_MS = 1500;
|
|
26
26
|
|
|
27
27
|
/** 真值判定:1 / true / yes / on(大小写不敏感)算开,其他一律算关。 */
|
|
28
|
-
export function isEnvTruthy(value) {
|
|
28
|
+
export function isEnvTruthy(value: unknown): boolean {
|
|
29
29
|
if (value === undefined || value === null) return false;
|
|
30
30
|
const s = String(value).trim().toLowerCase();
|
|
31
31
|
return s === '1' || s === 'true' || s === 'yes' || s === 'on';
|
|
@@ -35,11 +35,24 @@ export function isEnvTruthy(value) {
|
|
|
35
35
|
* 是否允许自动打开浏览器。
|
|
36
36
|
* 优先级:`--no-open` 命令行开关 > NX_SERVE_NO_OPEN 环境变量 > 默认允许。
|
|
37
37
|
*/
|
|
38
|
-
export function autoOpenEnabled(flagNoOpen) {
|
|
38
|
+
export function autoOpenEnabled(flagNoOpen: unknown): boolean {
|
|
39
39
|
if (flagNoOpen) return false;
|
|
40
40
|
return !isEnvTruthy(process.env[NO_OPEN_ENV]);
|
|
41
41
|
}
|
|
42
42
|
|
|
43
|
+
/** /api/bootstrap 的探测结果(面板认领签名:app.name / app.version)。 */
|
|
44
|
+
export interface PanelBootstrap {
|
|
45
|
+
app?: { name?: string; version?: string };
|
|
46
|
+
[k: string]: unknown;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
interface ProbeResult {
|
|
50
|
+
data: PanelBootstrap | null;
|
|
51
|
+
timedOut: boolean;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
type FetchHeaders = Record<string, string>;
|
|
55
|
+
|
|
43
56
|
/**
|
|
44
57
|
* 探一次端口,返回 { data, timedOut }。
|
|
45
58
|
*
|
|
@@ -47,11 +60,11 @@ export function autoOpenEnabled(flagNoOpen) {
|
|
|
47
60
|
* 超时说明端口上可能正是一个应答慢的面板,值得再等一次;
|
|
48
61
|
* 明确不是面板就没有再等的必要。
|
|
49
62
|
*/
|
|
50
|
-
async function probePanelOnce(port, host, timeoutMs, headers) {
|
|
63
|
+
async function probePanelOnce(port: number, host: string, timeoutMs: number, headers: FetchHeaders | null): Promise<ProbeResult> {
|
|
51
64
|
try {
|
|
52
65
|
const controller = new AbortController();
|
|
53
66
|
const timer = setTimeout(() => controller.abort(), timeoutMs);
|
|
54
|
-
let res;
|
|
67
|
+
let res: Response;
|
|
55
68
|
try {
|
|
56
69
|
res = await fetch(`http://${host}:${port}/api/bootstrap`, {
|
|
57
70
|
signal: controller.signal,
|
|
@@ -61,10 +74,10 @@ async function probePanelOnce(port, host, timeoutMs, headers) {
|
|
|
61
74
|
clearTimeout(timer);
|
|
62
75
|
}
|
|
63
76
|
if (!res.ok) return { data: null, timedOut: false };
|
|
64
|
-
const body = await res.json();
|
|
77
|
+
const body = (await res.json()) as { data?: PanelBootstrap } | null;
|
|
65
78
|
return { data: (body && body.data) || null, timedOut: false };
|
|
66
79
|
} catch (err) {
|
|
67
|
-
return { data: null, timedOut: !!(err && err.name === 'AbortError') };
|
|
80
|
+
return { data: null, timedOut: !!(err && (err as { name?: string }).name === 'AbortError') };
|
|
68
81
|
}
|
|
69
82
|
}
|
|
70
83
|
|
|
@@ -78,7 +91,12 @@ async function probePanelOnce(port, host, timeoutMs, headers) {
|
|
|
78
91
|
* headers 形参给需要鉴权的项目用(nx-as 的管理面要 Bearer 密钥);
|
|
79
92
|
* 默认不传,匿名探测。
|
|
80
93
|
*/
|
|
81
|
-
export async function probePanel(
|
|
94
|
+
export async function probePanel(
|
|
95
|
+
port: number,
|
|
96
|
+
host = '127.0.0.1',
|
|
97
|
+
timeoutMs: number = PROBE_TIMEOUT_MS,
|
|
98
|
+
headers: FetchHeaders | null = null,
|
|
99
|
+
): Promise<PanelBootstrap | null> {
|
|
82
100
|
const { data } = await probePanelOnce(port, host, timeoutMs, headers);
|
|
83
101
|
return data;
|
|
84
102
|
}
|
|
@@ -87,16 +105,16 @@ export async function probePanel(port, host = '127.0.0.1', timeoutMs = PROBE_TIM
|
|
|
87
105
|
* 从 start 起逐个试,返回第一个能监听的端口(最多试 50 个)。
|
|
88
106
|
* 用临时 net.Server 探测、立刻关闭;与 startServer 走同一套 EADDRINUSE 判定。
|
|
89
107
|
*/
|
|
90
|
-
export function findFreePort(start, host = '127.0.0.1') {
|
|
108
|
+
export function findFreePort(start: number, host = '127.0.0.1'): Promise<number> {
|
|
91
109
|
return new Promise((resolve_, reject) => {
|
|
92
|
-
const tryPort = (p) => {
|
|
110
|
+
const tryPort = (p: number): void => {
|
|
93
111
|
if (p > start + 50) {
|
|
94
112
|
reject(new Error(`找不到空闲端口(从 ${start} 起连续 50 个被占)`));
|
|
95
113
|
return;
|
|
96
114
|
}
|
|
97
115
|
const probe = net.createServer();
|
|
98
116
|
probe.once('error', (err) => {
|
|
99
|
-
if (err && err.code === 'EADDRINUSE') tryPort(p + 1);
|
|
117
|
+
if (err && (err as NodeJS.ErrnoException).code === 'EADDRINUSE') tryPort(p + 1);
|
|
100
118
|
else reject(err);
|
|
101
119
|
});
|
|
102
120
|
probe.listen(p, host, () => probe.close(() => resolve_(p)));
|
|
@@ -105,19 +123,27 @@ export function findFreePort(start, host = '127.0.0.1') {
|
|
|
105
123
|
});
|
|
106
124
|
}
|
|
107
125
|
|
|
126
|
+
/** 端口冲突决策:reuse = 复用已有实例;shift = 顺延到空闲端口。 */
|
|
127
|
+
export interface PortDecision {
|
|
128
|
+
action: 'reuse' | 'shift';
|
|
129
|
+
port: number;
|
|
130
|
+
occupant: string | null;
|
|
131
|
+
existing: PanelBootstrap | null;
|
|
132
|
+
}
|
|
133
|
+
|
|
108
134
|
/**
|
|
109
135
|
* 端口冲突的统一决策。
|
|
110
136
|
*
|
|
111
137
|
* reuse —— 端口上跑的就是本项目的面板:复用它,不再起第二个进程。
|
|
112
138
|
* 起第二个会让「切项目」变成「切端口」,而用户想看的其实是已经开着的那一个。
|
|
113
139
|
* shift —— 端口被别的东西占着:顺延到下一个空闲端口,再起自己的面板。
|
|
114
|
-
*
|
|
115
|
-
* 返回 { action, port, occupant, existing }:
|
|
116
|
-
* action 'reuse' | 'shift'
|
|
117
|
-
* port reuse 时是原端口;shift 时是下一个空闲端口
|
|
118
|
-
* occupant 占用者的 app 名(探测不到就是 null)
|
|
119
140
|
*/
|
|
120
|
-
export async function resolvePortConflict(
|
|
141
|
+
export async function resolvePortConflict(
|
|
142
|
+
port: number,
|
|
143
|
+
appName: string,
|
|
144
|
+
host = '127.0.0.1',
|
|
145
|
+
headers: FetchHeaders | null = null,
|
|
146
|
+
): Promise<PortDecision> {
|
|
121
147
|
let probe = await probePanelOnce(port, host, PROBE_TIMEOUT_MS, headers);
|
|
122
148
|
if (probe.timedOut) {
|
|
123
149
|
// 慢应答的面板也认:再等一次。别把「自己的面板」误判成「别人的服务」,
|
|
@@ -134,6 +160,6 @@ export async function resolvePortConflict(port, appName, host = '127.0.0.1', hea
|
|
|
134
160
|
}
|
|
135
161
|
|
|
136
162
|
/** 占用者的一句话描述,用于终端提示。探测不到就是「未知服务」。 */
|
|
137
|
-
export function describeOccupant(occupant) {
|
|
163
|
+
export function describeOccupant(occupant: string | null): string {
|
|
138
164
|
return occupant || '未知服务';
|
|
139
165
|
}
|
package/src/index.js
CHANGED
|
@@ -1,10 +1,12 @@
|
|
|
1
|
-
//
|
|
2
|
-
//
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
1
|
+
// 编程入口的兼容垫片:注册 tsx loader 后转发到 TS 源码。
|
|
2
|
+
//
|
|
3
|
+
// 为什么存在:package.json 的 main/exports 面向「不带 tsx 的普通 Node import」。
|
|
4
|
+
// 真相源是 index.ts(与 CLI / dev / 测试同一条执行路径),这里只负责让
|
|
5
|
+
// `import('nx-kv')` 在任何 Node 进程里都能跑通——垫片先注册 loader 再转发,
|
|
6
|
+
// 转发发生在同一模块图里,不存在「第二份实现」。
|
|
7
|
+
// 库内代码请直接 import './index.ts';这个垫片只服务包外消费方。
|
|
8
|
+
import { register } from 'tsx/esm/api';
|
|
8
9
|
|
|
9
|
-
|
|
10
|
-
|
|
10
|
+
register();
|
|
11
|
+
|
|
12
|
+
export * from './index.ts';
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
// 编程入口:供其他工具 / agent 以库方式调用。
|
|
2
|
+
// 导出的是各模块的 service(业务真相源),不是 CLI/HTTP 壳。
|
|
3
|
+
export * as config from './core/config.js';
|
|
4
|
+
export * as kvapi from './core/kvapi.js';
|
|
5
|
+
export * as errors from './core/errors.js';
|
|
6
|
+
export * as todo from './modules/todo/service.js';
|
|
7
|
+
export * as localtask from './modules/localtask/service.js';
|
|
8
|
+
|
|
9
|
+
export { ACTIONS, MODULES } from './runtime/registry.js';
|
|
10
|
+
export { startServer } from './runtime/server.js';
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
// AUTO-GENERATED —— 由 scripts/gen-actions.mjs 生成,勿手改。
|
|
2
|
+
//
|
|
3
|
+
// 收录本目录下所有继承 ActionBase 的类。**加一条 action = 新建一个文件 +
|
|
4
|
+
// 跑 `pnpm gen`**;模块的 index.ts 不需要改。
|
|
5
|
+
// 新鲜度由 tests/unit/action-registry.test.mjs 对账。
|
|
6
|
+
|
|
7
|
+
import type { ActionBase } from '../../../runtime/action-base.js';
|
|
8
|
+
import type { Container } from '../../../runtime/container.js';
|
|
9
|
+
import { BootstrapAction } from './bootstrap.js';
|
|
10
|
+
import { HealthAction } from './health.js';
|
|
11
|
+
import { RoutesAction } from './routes.js';
|
|
12
|
+
|
|
13
|
+
/** 本模块的全部 action 类(容器按这个顺序建实例)。 */
|
|
14
|
+
export const ACTIONS: readonly (new (deps: Container) => ActionBase)[] = [
|
|
15
|
+
BootstrapAction,
|
|
16
|
+
HealthAction,
|
|
17
|
+
RoutesAction,
|
|
18
|
+
];
|
|
19
|
+
|
|
20
|
+
// 再导出类本身:前端 apiclient 的返回类型从这里 type-only 引用(实现即契约)。
|
|
21
|
+
export { BootstrapAction };
|
|
22
|
+
export { HealthAction };
|
|
23
|
+
export { RoutesAction };
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
// system.bootstrap —— 面板启动上下文:版本 / 登录态 / 工作空间 / 命令表。
|
|
2
|
+
//
|
|
3
|
+
// 「一条 action 一个文件」:声明(@action 元数据)与实现同文件;契约在 ../schemas.ts。
|
|
4
|
+
// 依赖经 IoC 容器取(this.deps.get('config'))——测试可换一整个容器,不必改构造参数。
|
|
5
|
+
import { z } from 'zod';
|
|
6
|
+
import { readFileSync } from 'node:fs';
|
|
7
|
+
import { action } from '../../../runtime/action-decorator.js';
|
|
8
|
+
import { ActionBase } from '../../../runtime/action-base.js';
|
|
9
|
+
import { commandTable, type CommandEntry } from '../../../core/command-table.js';
|
|
10
|
+
import { APP_NAME, DEFAULT_PORT } from '../../../core/paths.js';
|
|
11
|
+
import { systemBootstrapInput } from '../schemas.js';
|
|
12
|
+
|
|
13
|
+
/** package.json 的版本号(只读一次;与 cli.ts 各读各的,避免引入跨层依赖)。 */
|
|
14
|
+
const VERSION: string = JSON.parse(
|
|
15
|
+
readFileSync(new URL('../../../../package.json', import.meta.url), 'utf8'),
|
|
16
|
+
).version;
|
|
17
|
+
|
|
18
|
+
export class BootstrapAction extends ActionBase {
|
|
19
|
+
@action({
|
|
20
|
+
id: 'system.bootstrap',
|
|
21
|
+
cli: ['bootstrap'],
|
|
22
|
+
http: ['GET', '/api/bootstrap'],
|
|
23
|
+
summary: '聚合上下文:版本 / 登录态 / 工作空间 / 命令表',
|
|
24
|
+
input: systemBootstrapInput,
|
|
25
|
+
})
|
|
26
|
+
async bootstrap(_ctx: z.output<typeof systemBootstrapInput>): Promise<{
|
|
27
|
+
app: { name: string; version: string };
|
|
28
|
+
version: string;
|
|
29
|
+
configPath: string;
|
|
30
|
+
baseUrl: string;
|
|
31
|
+
loggedIn: boolean;
|
|
32
|
+
email: string;
|
|
33
|
+
userId: number;
|
|
34
|
+
groupId: number;
|
|
35
|
+
groups: unknown[];
|
|
36
|
+
groupsError: string;
|
|
37
|
+
defaultPort: number;
|
|
38
|
+
projectRoot: string;
|
|
39
|
+
commands: CommandEntry[];
|
|
40
|
+
}> {
|
|
41
|
+
const config = this.deps.get('config');
|
|
42
|
+
const kvapi = this.deps.get('kvapi');
|
|
43
|
+
const cfg = await config.loadConfig();
|
|
44
|
+
let groups: unknown[] = [];
|
|
45
|
+
let groupsError = '';
|
|
46
|
+
if (cfg.token) {
|
|
47
|
+
try {
|
|
48
|
+
groups = await kvapi.listGroups();
|
|
49
|
+
} catch (e) {
|
|
50
|
+
groupsError = String((e as { message?: string }).message || e);
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
return {
|
|
54
|
+
// app 段是跨项目的认领签名:serve 端口被占时靠 app.name 判断
|
|
55
|
+
// 「上面跑的是不是本项目的面板」——相同则复用,不同则顺延端口。
|
|
56
|
+
app: { name: APP_NAME, version: VERSION },
|
|
57
|
+
version: VERSION,
|
|
58
|
+
configPath: config.configPathFromEnv(),
|
|
59
|
+
baseUrl: cfg.baseUrl,
|
|
60
|
+
loggedIn: !!cfg.token,
|
|
61
|
+
email: cfg.email,
|
|
62
|
+
userId: cfg.userId,
|
|
63
|
+
groupId: cfg.groupId,
|
|
64
|
+
groups,
|
|
65
|
+
groupsError,
|
|
66
|
+
defaultPort: DEFAULT_PORT,
|
|
67
|
+
// serve 进程的工作目录:仓库页「扫描」的缺省根目录用它(面板进程 cwd 即宿主项目)
|
|
68
|
+
projectRoot: process.cwd(),
|
|
69
|
+
// 命令表由 runtime 写进 core 的快照格子(见 core/command-table.ts)。
|
|
70
|
+
// 没有快照时给空数组:面板照常打开,只是没有「CLI 等价」提示。
|
|
71
|
+
commands: commandTable(),
|
|
72
|
+
};
|
|
73
|
+
}
|
|
74
|
+
}
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
// system.health —— 健康检查:本机配置 + 远程后端可达性。
|
|
2
|
+
//
|
|
3
|
+
// 依赖经 IoC 容器取(config);后端探测是**只读**的 /api/v1/user/info,
|
|
4
|
+
// 失败不算错误(health 的语义是「如实报告」,错误文案进 backendError 字段)。
|
|
5
|
+
import { z } from 'zod';
|
|
6
|
+
import { readFileSync } from 'node:fs';
|
|
7
|
+
import { action } from '../../../runtime/action-decorator.js';
|
|
8
|
+
import { ActionBase } from '../../../runtime/action-base.js';
|
|
9
|
+
import { systemHealthInput } from '../schemas.js';
|
|
10
|
+
|
|
11
|
+
const VERSION: string = JSON.parse(
|
|
12
|
+
readFileSync(new URL('../../../../package.json', import.meta.url), 'utf8'),
|
|
13
|
+
).version;
|
|
14
|
+
|
|
15
|
+
export interface HealthReport {
|
|
16
|
+
status: 'ok';
|
|
17
|
+
version: string;
|
|
18
|
+
baseUrl: string;
|
|
19
|
+
configPath: string;
|
|
20
|
+
loggedIn: boolean;
|
|
21
|
+
backend: 'reachable' | 'unreachable' | string;
|
|
22
|
+
backendError: string;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export class HealthAction extends ActionBase {
|
|
26
|
+
@action({
|
|
27
|
+
id: 'system.health',
|
|
28
|
+
cli: ['health'],
|
|
29
|
+
http: ['GET', '/api/health'],
|
|
30
|
+
summary: '健康检查(本机配置 + 后端可达性)',
|
|
31
|
+
input: systemHealthInput,
|
|
32
|
+
})
|
|
33
|
+
async health(_ctx: z.output<typeof systemHealthInput>): Promise<HealthReport> {
|
|
34
|
+
const config = this.deps.get('config');
|
|
35
|
+
const cfg = await config.loadConfig();
|
|
36
|
+
let backend = 'unreachable';
|
|
37
|
+
let backendError = '';
|
|
38
|
+
try {
|
|
39
|
+
const res = await fetch(cfg.baseUrl.replace(/\/$/, '') + '/api/v1/user/info', {
|
|
40
|
+
headers: cfg.token ? { authorization: `Bearer ${cfg.token}` } : {},
|
|
41
|
+
signal: AbortSignal.timeout(6000),
|
|
42
|
+
});
|
|
43
|
+
backend = res.ok ? 'reachable' : `http ${res.status}`;
|
|
44
|
+
} catch (e) {
|
|
45
|
+
backendError = String((e as { message?: string }).message || e);
|
|
46
|
+
}
|
|
47
|
+
return {
|
|
48
|
+
status: 'ok',
|
|
49
|
+
version: VERSION,
|
|
50
|
+
baseUrl: cfg.baseUrl,
|
|
51
|
+
configPath: config.configPathFromEnv(),
|
|
52
|
+
loggedIn: !!cfg.token,
|
|
53
|
+
backend,
|
|
54
|
+
backendError,
|
|
55
|
+
};
|
|
56
|
+
}
|
|
57
|
+
}
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
// system.routes —— 命令表 ↔ HTTP 路由的对照与反查(纯 CLI,无 HTTP 路由)。
|
|
2
|
+
//
|
|
3
|
+
// 命令表来自 core/command-table 的快照格子:cli.ts 装配完 ALL_COMMANDS 后会覆盖
|
|
4
|
+
// 写入**含平台命令的完整版**(registry 先写过一次 action 版)。所以这条命令
|
|
5
|
+
// 看到的表与 `help --json` 看到的完全同源同长。过滤逻辑在 ../routes.ts(纯函数),
|
|
6
|
+
// 这里只做声明与装配。
|
|
7
|
+
import { z } from 'zod';
|
|
8
|
+
import { action } from '../../../runtime/action-decorator.js';
|
|
9
|
+
import { ActionBase } from '../../../runtime/action-base.js';
|
|
10
|
+
import { commandTable, type CommandEntry } from '../../../core/command-table.js';
|
|
11
|
+
import { filterRoutes, renderRoutes } from '../routes.js';
|
|
12
|
+
import { systemRoutesInput } from '../schemas.js';
|
|
13
|
+
|
|
14
|
+
export class RoutesAction extends ActionBase {
|
|
15
|
+
@action({
|
|
16
|
+
id: 'system.routes',
|
|
17
|
+
cli: ['routes'],
|
|
18
|
+
http: null, // 纯 CLI:对照表本身没有 HTTP 端点(面板从 /api/bootstrap 拿同一张表)
|
|
19
|
+
summary: '命令 ↔ 路由对照表(--module 过滤;--http 反查命令)',
|
|
20
|
+
input: systemRoutesInput,
|
|
21
|
+
render: (list) => renderRoutes(list as CommandEntry[]),
|
|
22
|
+
})
|
|
23
|
+
async routes(ctx: z.output<typeof systemRoutesInput>): Promise<CommandEntry[]> {
|
|
24
|
+
return filterRoutes(commandTable(), ctx);
|
|
25
|
+
}
|
|
26
|
+
}
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
// 系统模块:聚合与自检。没有业务状态,也没有面板视图。
|
|
2
|
+
//
|
|
3
|
+
// 分层例外:本模块是刻意的聚合器,允许 import 其他模块的 service(放开「模块互依」
|
|
4
|
+
// 的 eslint 规则——它是唯一豁免)。
|
|
5
|
+
//
|
|
6
|
+
// 模板形态:模块是 ModuleBase 子类,只做「元信息 + 装配」;业务 action 在
|
|
7
|
+
// actions/ 下一条一个文件(@action 装饰器 + zod 契约),清单由 gen:actions 收进
|
|
8
|
+
// _manifest.generated.ts——加一条 action = 新建一个文件 + 跑一次生成,本文件零改动。
|
|
9
|
+
import { ModuleBase } from '../../runtime/types/module.js';
|
|
10
|
+
import { zodActionsOf, type ZodBoundAction } from '../../runtime/action-decorator.js';
|
|
11
|
+
import { container, type Container } from '../../runtime/container.js';
|
|
12
|
+
import { ACTIONS } from './actions/_manifest.generated.js';
|
|
13
|
+
|
|
14
|
+
export class SystemModule extends ModuleBase {
|
|
15
|
+
override readonly id = 'system';
|
|
16
|
+
override readonly title = '系统';
|
|
17
|
+
override readonly order = 0;
|
|
18
|
+
|
|
19
|
+
// actions 在构造期组装(依赖要先就绪),故用确定赋值断言而非字段初始化器。
|
|
20
|
+
override readonly actions: readonly ZodBoundAction[];
|
|
21
|
+
|
|
22
|
+
constructor(c: Container = container) {
|
|
23
|
+
super();
|
|
24
|
+
this.actions = ACTIONS.flatMap((Cls) => zodActionsOf(c.create(Cls)));
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export const systemModule = new SystemModule();
|
|
29
|
+
export default systemModule;
|
|
@@ -1,34 +1,30 @@
|
|
|
1
|
-
// `routes`
|
|
1
|
+
// `routes` 命令的纯逻辑:命令表 ↔ HTTP 路由的对照与反查。
|
|
2
2
|
//
|
|
3
|
-
//
|
|
4
|
-
//
|
|
5
|
-
//
|
|
6
|
-
//
|
|
7
|
-
//
|
|
8
|
-
// 历史上这段逻辑直接写在 index.js 的 action 里,靠 `await import('../../runtime/cli.js')`
|
|
9
|
-
// 绕开环:命令能跑,但分层倒了,而且一旦 loader 处理顺序变化,就会静默拿到半初始化的模块。
|
|
3
|
+
// 它为什么只放纯函数、表由调用方传入:表的数据源是 runtime 装配的命令表
|
|
4
|
+
// (经 core/command-table 的快照格子),模块不能 import runtime
|
|
5
|
+
// (registry → modules → cli → registry 会成环)。
|
|
6
|
+
// 历史上这段逻辑靠 `await import('../../runtime/cli.js')` 绕开环:命令能跑,
|
|
7
|
+
// 但分层倒了,而且 loader 处理顺序一变就可能拿到半初始化的模块。
|
|
10
8
|
import { badInput, notFound } from '../../core/errors.js';
|
|
9
|
+
import type { CommandEntry } from '../../core/command-table.js';
|
|
11
10
|
|
|
12
|
-
/**
|
|
13
|
-
export
|
|
14
|
-
module
|
|
15
|
-
http
|
|
16
|
-
}
|
|
11
|
+
/** routes 的输入(--module / --http,schema 见 ../schemas.ts)。 */
|
|
12
|
+
export interface RoutesCtx {
|
|
13
|
+
module?: string;
|
|
14
|
+
http?: string;
|
|
15
|
+
}
|
|
17
16
|
|
|
18
|
-
/**
|
|
19
|
-
|
|
20
|
-
* @param {{ module?: string, http?: string }} ctx
|
|
21
|
-
*/
|
|
22
|
-
export function filterRoutes(table, ctx = {}) {
|
|
17
|
+
/** 对照表过滤:--http 反查(METHOD /api/path,:param 视为通配);--module 正查。 */
|
|
18
|
+
export function filterRoutes(table: readonly CommandEntry[], ctx: RoutesCtx = {}): CommandEntry[] {
|
|
23
19
|
if (ctx.http) {
|
|
24
20
|
const { method, path } = parseHttpQuery(ctx.http);
|
|
25
21
|
const hit = table.filter(
|
|
26
|
-
(c) => c.http && (!method || c.http.method === method) && routeMatches(c.http.path, path)
|
|
22
|
+
(c) => c.http && (!method || c.http.method === method) && routeMatches(c.http.path, path),
|
|
27
23
|
);
|
|
28
24
|
if (!hit.length) throw notFound(`没有路由匹配: ${ctx.http}(用 nx-kv routes 查看全部对照)`);
|
|
29
25
|
return hit;
|
|
30
26
|
}
|
|
31
|
-
if (!ctx.module) return table;
|
|
27
|
+
if (!ctx.module) return [...table];
|
|
32
28
|
|
|
33
29
|
const known = [...new Set(table.map((c) => c.module))];
|
|
34
30
|
if (!known.includes(ctx.module)) {
|
|
@@ -38,24 +34,24 @@ export function filterRoutes(table, ctx = {}) {
|
|
|
38
34
|
}
|
|
39
35
|
|
|
40
36
|
/** CLI 人读渲染:命令左对齐,右侧是它的 HTTP 等价(或「仅 CLI」) */
|
|
41
|
-
export function renderRoutes(list) {
|
|
37
|
+
export function renderRoutes(list: readonly CommandEntry[]): string {
|
|
42
38
|
if (!list.length) return '(无匹配)';
|
|
43
39
|
const w = Math.max(...list.map((c) => c.command.length));
|
|
44
40
|
return list
|
|
45
41
|
.map(
|
|
46
42
|
(c) =>
|
|
47
|
-
`${c.command.padEnd(w + 2)}${c.http ? `${c.http.method} ${c.http.path}` : '(仅 CLI,无 HTTP 路由)'}
|
|
43
|
+
`${c.command.padEnd(w + 2)}${c.http ? `${c.http.method} ${c.http.path}` : '(仅 CLI,无 HTTP 路由)'}`,
|
|
48
44
|
)
|
|
49
45
|
.join('\n');
|
|
50
46
|
}
|
|
51
47
|
|
|
52
48
|
// ---- 内部 ----
|
|
53
49
|
|
|
54
|
-
function parseHttpQuery(input) {
|
|
50
|
+
function parseHttpQuery(input: string): { method: string | null; path: string } {
|
|
55
51
|
const s = String(input || '').trim();
|
|
56
52
|
const m = /^([A-Za-z]+)\s+(.*)$/.exec(s);
|
|
57
|
-
const method = m ? m[1]
|
|
58
|
-
const path = (m ? m[2] : s).split('?')[0]
|
|
53
|
+
const method = m ? m[1]!.toUpperCase() : null;
|
|
54
|
+
const path = (m ? m[2]! : s).split('?')[0]!;
|
|
59
55
|
if (!path.startsWith('/')) {
|
|
60
56
|
throw badInput(`HTTP 查询需形如 "/api/todo" 或 "GET /api/todo",收到: ${input}`);
|
|
61
57
|
}
|
|
@@ -63,7 +59,7 @@ function parseHttpQuery(input) {
|
|
|
63
59
|
}
|
|
64
60
|
|
|
65
61
|
// 段对段比较:`:param` 视为通配
|
|
66
|
-
function routeMatches(pattern, path) {
|
|
62
|
+
function routeMatches(pattern: string, path: string): boolean {
|
|
67
63
|
const a = pattern.split('/').filter(Boolean);
|
|
68
64
|
const b = path.split('/').filter(Boolean);
|
|
69
65
|
if (a.length !== b.length) return false;
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
// system 模块的 zod 契约:每个 action 一对入参 schema。
|
|
2
|
+
//
|
|
3
|
+
// 这份文件是「半自动化」的关键证据:它同时被三处消费——
|
|
4
|
+
// 1. 服务端:@action 装饰器引用它做入参校验(CLI 与 HTTP 共用同一份)
|
|
5
|
+
// 2. codegen:生成前端 apiclient 的入参类型(import type,零运行时进浏览器包)
|
|
6
|
+
// 3. 未来:前端表单校验可按需 import 同一份 schema(zod 本身浏览器安全)
|
|
7
|
+
//
|
|
8
|
+
// 命名约定(codegen 靠它自动拼 import 名):<camelCase(actionId)>Input,
|
|
9
|
+
// 如 system.bootstrap → systemBootstrapInput。约定破了 codegen 会生成指向
|
|
10
|
+
// 不存在符号的代码,tests/unit/api-client.test.mjs 的新鲜度对账会当场红。
|
|
11
|
+
//
|
|
12
|
+
// 已知边界(模板 spike 结论,别踩):
|
|
13
|
+
// - z.coerce 不能用('false'→true、''→0)——归一化在 runtime/zod-bridge.ts 做;
|
|
14
|
+
// - handler 入参类型手写 z.output(解析后形状);前端 client 入参是 z.input。
|
|
15
|
+
import { z } from 'zod';
|
|
16
|
+
|
|
17
|
+
// ---- system.bootstrap ----
|
|
18
|
+
export const systemBootstrapInput = z.object({});
|
|
19
|
+
|
|
20
|
+
// ---- system.health ----
|
|
21
|
+
export const systemHealthInput = z.object({});
|
|
22
|
+
|
|
23
|
+
// ---- system.routes ----
|
|
24
|
+
export const systemRoutesInput = z.object({
|
|
25
|
+
// 模块 id 过滤(正查)
|
|
26
|
+
module: z.string().optional(),
|
|
27
|
+
// `METHOD /api/path`(反查,:param 视为通配)
|
|
28
|
+
http: z.string().optional(),
|
|
29
|
+
});
|
|
@@ -29,7 +29,7 @@ export function deepLinkUrl(key, port) {
|
|
|
29
29
|
|
|
30
30
|
// 本仓库/已安装包的 CLI 入口(src/modules/tasktool/ 上三级到包根)。
|
|
31
31
|
function binCliPath() {
|
|
32
|
-
return fileURLToPath(new URL('../../../bin/
|
|
32
|
+
return fileURLToPath(new URL('../../../bin/kv.mjs', import.meta.url));
|
|
33
33
|
}
|
|
34
34
|
|
|
35
35
|
// 确保常驻主面板可用:已在运行直接复用;否则后台 detached 拉起一个独立
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
// action 的抽象基类:所有 action 类继承它,依赖经容器拿(IoC)。
|
|
2
|
+
//
|
|
3
|
+
// 为什么要基类而不是各自构造函数直接收依赖:
|
|
4
|
+
// - 容器 create 的签名统一为 `new (deps: Container) => T`——基类把这条约定固定下来,
|
|
5
|
+
// gen-actions 收清单时也只需认这一个形状;
|
|
6
|
+
// - 「我需要什么」写在**用点**(`this.deps.get('config')`),而不是构造函数的参数表
|
|
7
|
+
// ——新增依赖不必改调用方;
|
|
8
|
+
// - action 类只负责「声明 + 实现」,装配(模块编排、依赖注入、注册表收集)
|
|
9
|
+
// 都在基类与容器这一层。
|
|
10
|
+
import type { Container } from './container.js';
|
|
11
|
+
|
|
12
|
+
export abstract class ActionBase {
|
|
13
|
+
constructor(protected readonly deps: Container) {}
|
|
14
|
+
}
|