nx-kv 0.45.1 → 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 +57 -0
- package/README.md +11 -5
- package/assets/kv-get/SKILL.md +1 -1
- package/assets/kv-get/references/timegoal-workflow.md +7 -7
- package/assets/kv-get/references/timegoal.md +6 -6
- 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/localtask/action-lifecycle.js +3 -6
- package/src/modules/localtask/repo/goals.js +5 -6
- package/src/modules/localtask/task-lifecycle.js +2 -2
- 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/index.js +4 -7
- package/src/modules/tasktool/panel-escort.js +1 -1
- package/src/modules/tasktool/plugins/goal-template.js +2 -2
- package/src/modules/tasktool/plugins/taskgoal-store.js +1 -1
- package/src/modules/tasktool/plugins/timegoal-cwd-store.js +8 -11
- package/src/modules/tasktool/plugins/timegoal-task-store.js +9 -12
- 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/shared/prompt-blocks.js +1 -1
- package/src/web/frontend/api/cli-tree.json +49 -0
- package/src/web/frontend/api/client.generated.ts +39 -0
- package/src/web/public/assets/{Introduction-EHroxF1H.js → Introduction-BI8Ohz1l.js} +1 -1
- package/src/web/public/assets/{bar-BvS_Jfi4.js → bar-Jfji2mz3.js} +1 -1
- package/src/web/public/assets/{cloud-DlWk0wnP.js → cloud-cFewR3CF.js} +1 -1
- package/src/web/public/assets/{composer-panel-D3w-CjhN.js → composer-panel-CcK0D4Gd.js} +1 -1
- package/src/web/public/assets/{deleted-panel-BMJEEBWD.js → deleted-panel-oN8YlGvq.js} +1 -1
- package/src/web/public/assets/{dir-BtjHgH4Q.js → dir-BuAtw08k.js} +1 -1
- package/src/web/public/assets/{group-Bxq8JamU.js → group-FRUv4mQ6.js} +1 -1
- package/src/web/public/assets/{index-ChlZPTea.js → index-CyF6nNWE.js} +2 -2
- package/src/web/public/assets/{md-history-CBqcR086.js → md-history-DErcpXhC.js} +1 -1
- package/src/web/public/assets/{overview-BP5sB1WX.js → overview-DZHcrz4u.js} +1 -1
- package/src/web/public/assets/{refs-Dt7DQIOo.js → refs-BXIwmL5W.js} +1 -1
- package/src/web/public/assets/{repos-Zl1_SfPX.js → repos-DYugJZpl.js} +1 -1
- package/src/web/public/assets/{route-crumb-PqhQSVWL.js → route-crumb-C3Ce0rzR.js} +1 -1
- package/src/web/public/assets/{settings-CXWFvvvv.js → settings-Bpazt87u.js} +2 -2
- package/src/web/public/assets/{status-tag-BK-45ld2.js → status-tag-CHCpOgMP.js} +1 -1
- package/src/web/public/assets/{task-COFIPegR.js → task-G58spmPC.js} +1 -1
- package/src/web/public/assets/{templates-CIxgTTt-.js → templates-Dr0CunY8.js} +1 -1
- package/src/web/public/assets/{tool-bar-TIqYxsQl.js → tool-bar-BSIlsHln.js} +1 -1
- package/src/web/public/index.html +1 -1
- package/src/modules/system/index.js +0 -96
- package/src/runtime/api.js +0 -101
- package/src/runtime/registry.js +0 -89
|
@@ -0,0 +1,243 @@
|
|
|
1
|
+
// codegen:从同一份 action 契约生成两样东西——
|
|
2
|
+
// 1. client.generated.ts:给前端用的类型安全 apiclient
|
|
3
|
+
// 2. cli-tree.json:CLI 命令树快照(面板 / 文档可消费的事实源)
|
|
4
|
+
//
|
|
5
|
+
// **「半自动化」的边界(模板 spike 的量化结论):**
|
|
6
|
+
// 自动:每个 action 一个方法(名字、入参/返回类型来自 zod schema)、路由模式、
|
|
7
|
+
// 路径参数抽取、query/body 分流。
|
|
8
|
+
// 手写:传输层(api/client.ts 的 api()——错误信封/超时已是现成的)、
|
|
9
|
+
// 页面接线(哪个按钮调哪个 action)。
|
|
10
|
+
//
|
|
11
|
+
// 刻意偏差:生成的 client **不在前端做 zod 运行时校验**(schema 只以 import type
|
|
12
|
+
// 出现,返回值 as 断言)——省掉浏览器包里整个 zod;服务端仍在 zod-bridge 双端守
|
|
13
|
+
// schema(CLI 与 HTTP 共用同一份)。
|
|
14
|
+
//
|
|
15
|
+
// 只生成 zod 通道(@action 装饰)的 action;legacy flags 通道的 action 继续由前端
|
|
16
|
+
// 手写 client.js 调用(迁移完成后删除)。
|
|
17
|
+
//
|
|
18
|
+
// 入参 schema 常量命名约定:<camelCase(actionId)>Input(如 system.bootstrap →
|
|
19
|
+
// systemBootstrapInput)。约定破了 codegen 会生成指向不存在符号的 import,
|
|
20
|
+
// tests/unit/api-client.test.mjs 的新鲜度对账会当场红。
|
|
21
|
+
//
|
|
22
|
+
// 出参没有 schema——**实现即契约**:返回类型直接从 action 类的方法签名推断,
|
|
23
|
+
// 同一信息只声明一次,「两份声明漂移」无从发生。
|
|
24
|
+
import { describeInput } from './zod-bridge.js';
|
|
25
|
+
import { routeParams, type ZodBoundAction } from './action-decorator.js';
|
|
26
|
+
|
|
27
|
+
/** actionId → 入参 schema 常量名:system.bootstrap → systemBootstrapInput */
|
|
28
|
+
export function schemaName(actionId: string): string {
|
|
29
|
+
const parts = actionId.split(/[.\-_]/).filter(Boolean);
|
|
30
|
+
const camel = parts
|
|
31
|
+
.map((seg, i) => (i === 0 ? seg : seg[0]!.toUpperCase() + seg.slice(1)))
|
|
32
|
+
.join('');
|
|
33
|
+
return camel + 'Input';
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/** 前端方法名:取 actionId 最后一段,撞名时加模块前缀(todo.get 与 repo.get → get / repoGet)。 */
|
|
37
|
+
export function clientMethodNames(actions: readonly ZodBoundAction[]): Map<string, string> {
|
|
38
|
+
const used = new Set<string>();
|
|
39
|
+
const names = new Map<string, string>();
|
|
40
|
+
for (const a of actions) {
|
|
41
|
+
const parts = a.id.split('.');
|
|
42
|
+
const base = parts[parts.length - 1]!;
|
|
43
|
+
let candidate = base;
|
|
44
|
+
if (used.has(candidate)) {
|
|
45
|
+
const module = parts.length > 1 ? parts[parts.length - 2]! : 'action';
|
|
46
|
+
candidate = module + base[0]!.toUpperCase() + base.slice(1);
|
|
47
|
+
let n = 2;
|
|
48
|
+
while (used.has(candidate)) candidate = `${module}${base[0]!.toUpperCase()}${base.slice(1)}${n++}`;
|
|
49
|
+
}
|
|
50
|
+
used.add(candidate);
|
|
51
|
+
names.set(a.id, candidate);
|
|
52
|
+
}
|
|
53
|
+
return names;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/**
|
|
57
|
+
* schema 常量按**模块**分组 import:一个模块一份 schemas.ts
|
|
58
|
+
* (src/modules/<域>/schemas.ts),生成物从 src/web/frontend/api/ 算起
|
|
59
|
+
* 的相对路径固定为 '../../../modules/<域>/schemas.js'。
|
|
60
|
+
*/
|
|
61
|
+
function schemaModuleOf(moduleId: string): string {
|
|
62
|
+
return `../../../modules/${moduleId}/schemas.js`;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/** 生成前端 apiclient 的 TS 源码(type-only 引 schema:zod 不进浏览器包)。 */
|
|
66
|
+
export function generateClientSource(actions: readonly ZodBoundAction[]): string {
|
|
67
|
+
const withHttp = actions.filter((a) => a.http);
|
|
68
|
+
const methodNames = clientMethodNames(withHttp);
|
|
69
|
+
|
|
70
|
+
// 按模块分组收集两类类型锚点:入参 schema 常量(schemas.ts)+ action 类(清单)。
|
|
71
|
+
// 返回类型不引 schema——**实现即契约**:从 action 类的方法签名直接推断。
|
|
72
|
+
const inputTypes = new Map<string, Set<string>>();
|
|
73
|
+
const actionClasses = new Map<string, Set<string>>();
|
|
74
|
+
for (const a of withHttp) {
|
|
75
|
+
if (describeInput(a.input, a.args ?? []).length) {
|
|
76
|
+
const set = inputTypes.get(a.module) || new Set<string>();
|
|
77
|
+
set.add(schemaName(a.id));
|
|
78
|
+
inputTypes.set(a.module, set);
|
|
79
|
+
}
|
|
80
|
+
const classes = actionClasses.get(a.module) || new Set<string>();
|
|
81
|
+
classes.add(a.className);
|
|
82
|
+
actionClasses.set(a.module, classes);
|
|
83
|
+
}
|
|
84
|
+
const imports = [...inputTypes.entries()]
|
|
85
|
+
.sort(([a], [b]) => a.localeCompare(b))
|
|
86
|
+
.map(([module, names]) => {
|
|
87
|
+
const list = [...names].sort().map((n) => ` ${n},`).join('\n');
|
|
88
|
+
return `import type {\n${list}\n} from '${schemaModuleOf(module)}';`;
|
|
89
|
+
})
|
|
90
|
+
.concat(
|
|
91
|
+
[...actionClasses.entries()]
|
|
92
|
+
.sort(([a], [b]) => a.localeCompare(b))
|
|
93
|
+
.map(([module, names]) => {
|
|
94
|
+
const list = [...names].sort().map((n) => ` ${n},`).join('\n');
|
|
95
|
+
return `import type {\n${list}\n} from '../../../modules/${module}/actions/_manifest.generated.js';`;
|
|
96
|
+
}),
|
|
97
|
+
)
|
|
98
|
+
.join('\n');
|
|
99
|
+
|
|
100
|
+
const iface = withHttp
|
|
101
|
+
.map((a) => {
|
|
102
|
+
const fields = describeInput(a.input, a.args ?? []);
|
|
103
|
+
const paramType = `z.input<typeof ${schemaName(a.id)}>`;
|
|
104
|
+
const required = fields.some((f) => f.required);
|
|
105
|
+
const sig = fields.length === 0 ? '' : required ? `input: ${paramType}` : `input?: ${paramType}`;
|
|
106
|
+
const doc = a.summary ? `/** ${a.summary} */\n ` : '';
|
|
107
|
+
return `${doc}${methodNames.get(a.id)}(${sig}): Promise<Awaited<ReturnType<InstanceType<typeof ${a.className}>['${a.method}']>>>;`;
|
|
108
|
+
})
|
|
109
|
+
.join('\n');
|
|
110
|
+
|
|
111
|
+
const impl = withHttp
|
|
112
|
+
.map((a) => {
|
|
113
|
+
const inName = schemaName(a.id);
|
|
114
|
+
const methodName = methodNames.get(a.id)!;
|
|
115
|
+
const [method, pattern] = a.http!;
|
|
116
|
+
const params = routeParams(pattern);
|
|
117
|
+
const fields = describeInput(a.input, a.args ?? []);
|
|
118
|
+
const bodyFields = fields.filter((f) => !params.includes(f.name));
|
|
119
|
+
const required = fields.some((f) => f.required);
|
|
120
|
+
const isGet = method === 'GET' || method === 'HEAD';
|
|
121
|
+
|
|
122
|
+
const lines: string[] = [];
|
|
123
|
+
lines.push(` // action: ${a.id}`);
|
|
124
|
+
const argSig =
|
|
125
|
+
fields.length === 0 ? '' : required ? `input: z.input<typeof ${inName}>` : `input?: z.input<typeof ${inName}>`;
|
|
126
|
+
lines.push(` async ${methodName}(${argSig}) {`);
|
|
127
|
+
if (fields.length) {
|
|
128
|
+
// 可选入参统一兜底成对象:后面的索引访问不用再判 undefined
|
|
129
|
+
lines.push(` const inp = input ?? ({} as z.input<typeof ${inName}>);`);
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
// 路径参数是位置参数(zodActionsOf 已校验 :param ⊆ args),编码后插进模板。
|
|
133
|
+
const pathTemplate = pattern.replace(
|
|
134
|
+
/:([\w-]+)/g,
|
|
135
|
+
(_m: string, k: string) => '${encodeURIComponent(String(inp[' + JSON.stringify(k) + ']))}',
|
|
136
|
+
);
|
|
137
|
+
lines.push(` ${isGet && bodyFields.length ? 'let' : 'const'} path = \`${pathTemplate}\`;`);
|
|
138
|
+
|
|
139
|
+
const ret = `return (await transport.request(${JSON.stringify(method)}, path${isGet ? '' : ', body'})) as Awaited<ReturnType<InstanceType<typeof ${a.className}>['${a.method}']>>;`;
|
|
140
|
+
|
|
141
|
+
if (isGet) {
|
|
142
|
+
if (bodyFields.length) {
|
|
143
|
+
lines.push(' const q = new URLSearchParams();');
|
|
144
|
+
for (const f of bodyFields) {
|
|
145
|
+
lines.push(
|
|
146
|
+
` if (inp[${JSON.stringify(f.name)}] !== undefined) q.set(${JSON.stringify(f.name)}, String(inp[${JSON.stringify(f.name)}]));`,
|
|
147
|
+
);
|
|
148
|
+
}
|
|
149
|
+
lines.push(' const query = q.toString();');
|
|
150
|
+
lines.push(" if (query) path += path.includes('?') ? '&' + query : '?' + query;");
|
|
151
|
+
}
|
|
152
|
+
lines.push(' ' + ret);
|
|
153
|
+
} else {
|
|
154
|
+
if (bodyFields.length) {
|
|
155
|
+
const body = bodyFields.map((f) => `${JSON.stringify(f.name)}: inp[${JSON.stringify(f.name)}]`);
|
|
156
|
+
lines.push(` const body = { ${body.join(', ')} };`);
|
|
157
|
+
}
|
|
158
|
+
lines.push(' ' + ret);
|
|
159
|
+
}
|
|
160
|
+
lines.push(' },');
|
|
161
|
+
return lines.join('\n');
|
|
162
|
+
})
|
|
163
|
+
.join('\n');
|
|
164
|
+
|
|
165
|
+
const needsZodType = withHttp.some((a) => describeInput(a.input, a.args ?? []).length > 0);
|
|
166
|
+
return `// AUTO-GENERATED —— 由 scripts/gen-api-client.mjs(runtime/codegen.ts)生成,勿手改。
|
|
167
|
+
//
|
|
168
|
+
// 类型来自 zod schema(import type,zod 运行时不进浏览器包);运行时校验在服务端
|
|
169
|
+
//(runtime/zod-bridge.ts,CLI 与 HTTP 共用同一份 schema)。传输层是手写的那一半:
|
|
170
|
+
// 调 createApiClient 时传入 api/client.ts 的 api() 即可。
|
|
171
|
+
// 重新生成:pnpm gen:api。新鲜度由 tests/unit/api-client.test.mjs 对账。
|
|
172
|
+
|
|
173
|
+
${needsZodType ? "import type { z } from 'zod';" : ''}
|
|
174
|
+
${imports}
|
|
175
|
+
|
|
176
|
+
/** 传输层契约(手写的那一半):返回 data(错误信封由 api() 拆好,失败即 throw)。 */
|
|
177
|
+
export interface Transport {
|
|
178
|
+
request(method: string, path: string, body?: unknown): Promise<unknown>;
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
export interface ApiClient {
|
|
182
|
+
${iface}
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
export function createApiClient(transport: Transport): ApiClient {
|
|
186
|
+
return {
|
|
187
|
+
${impl}
|
|
188
|
+
};
|
|
189
|
+
}
|
|
190
|
+
`;
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
/** CLI 树节点(序列化用)。 */
|
|
194
|
+
export interface TreeNodeJson {
|
|
195
|
+
name: string;
|
|
196
|
+
path: string[];
|
|
197
|
+
action: {
|
|
198
|
+
id: string;
|
|
199
|
+
module: string;
|
|
200
|
+
summary: string;
|
|
201
|
+
usage: string;
|
|
202
|
+
http: string | null;
|
|
203
|
+
} | null;
|
|
204
|
+
children: TreeNodeJson[];
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
/** 从 action 声明派生层级命令树(无第二份手写清单——树是声明的产物)。 */
|
|
208
|
+
export function buildTreeJson(actions: readonly ZodBoundAction[]): TreeNodeJson {
|
|
209
|
+
type Node = { name: string; path: string[]; children: Node[]; action?: ZodBoundAction };
|
|
210
|
+
const root: Node = { name: '', path: [], children: [] };
|
|
211
|
+
for (const action of actions) {
|
|
212
|
+
let node = root;
|
|
213
|
+
action.cli.forEach((seg, i) => {
|
|
214
|
+
let next = node.children.find((c) => c.name === seg);
|
|
215
|
+
if (!next) {
|
|
216
|
+
next = { name: seg, path: action.cli.slice(0, i + 1), children: [] };
|
|
217
|
+
node.children.push(next);
|
|
218
|
+
}
|
|
219
|
+
node = next;
|
|
220
|
+
});
|
|
221
|
+
node.action = action;
|
|
222
|
+
}
|
|
223
|
+
const toJson = (node: Node): TreeNodeJson => ({
|
|
224
|
+
name: node.name,
|
|
225
|
+
path: node.path,
|
|
226
|
+
action: node.action
|
|
227
|
+
? {
|
|
228
|
+
id: node.action.id,
|
|
229
|
+
module: node.action.module,
|
|
230
|
+
summary: node.action.summary ?? '',
|
|
231
|
+
usage: node.action.cli.join(' '),
|
|
232
|
+
http: node.action.http ? `${node.action.http[0]} ${node.action.http[1]}` : null,
|
|
233
|
+
}
|
|
234
|
+
: null,
|
|
235
|
+
children: node.children.map(toJson),
|
|
236
|
+
});
|
|
237
|
+
return toJson(root);
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
/** CLI 树快照 JSON(stable:字段序固定,适合入库对账)。 */
|
|
241
|
+
export function generateTreeJson(actions: readonly ZodBoundAction[]): string {
|
|
242
|
+
return JSON.stringify(buildTreeJson(actions), null, 2) + '\n';
|
|
243
|
+
}
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
// IoC 容器:依赖的**注册与解析**都在这里,业务代码只声明「我需要什么」。
|
|
2
|
+
//
|
|
3
|
+
// 为什么需要它(而不是模块手工 new 每个 action 类):
|
|
4
|
+
// - **加一条 action 零登记**——新文件 → gen:actions 收进 manifest → 模块自动装配;
|
|
5
|
+
// - 依赖不在 action 的构造函数里点名,而是运行时按 key 取(`this.deps.get('config')`)
|
|
6
|
+
// ——于是测试可以换一整个容器,而不是逐个改构造参数。
|
|
7
|
+
//
|
|
8
|
+
// 类型安全:key 与值类型由 **DependencyMap** 接口约束——
|
|
9
|
+
// - `get('config')` 的返回类型自动推导(不需要手写泛型);
|
|
10
|
+
// - key 拼错 / register 的值类型不匹配,**编译期红**;
|
|
11
|
+
// - 新依赖类型 = 给 DependencyMap 加字段。
|
|
12
|
+
//
|
|
13
|
+
// 容器是进程级单例(默认容器已注册 core 共享依赖);测试可 new 一个自己的容器。
|
|
14
|
+
import * as configModule from '../core/config.js';
|
|
15
|
+
import type * as configTypes from '../core/config.js';
|
|
16
|
+
import * as kvapiModule from '../core/kvapi.js';
|
|
17
|
+
import type * as kvapiTypes from '../core/kvapi.js';
|
|
18
|
+
|
|
19
|
+
/** 项目级依赖清单:key → 类型。新依赖在此加字段。 */
|
|
20
|
+
export interface DependencyMap {
|
|
21
|
+
/** 本机配置(core/config 的服务函数集;测试可注册临时实现)。 */
|
|
22
|
+
config: typeof configTypes;
|
|
23
|
+
/** 远程 KV 客户端(core/kvapi;测试可注册假实现)。 */
|
|
24
|
+
kvapi: typeof kvapiTypes;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export class Container {
|
|
28
|
+
private readonly providers = new Map<keyof DependencyMap, unknown>();
|
|
29
|
+
|
|
30
|
+
/** 注册一个依赖(后注册覆盖先注册)。链式返回自己,便于一行装配。 */
|
|
31
|
+
register<K extends keyof DependencyMap>(key: K, value: DependencyMap[K]): this {
|
|
32
|
+
this.providers.set(key, value);
|
|
33
|
+
return this;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/** 取依赖;key 拼错编译期即红,没注册就运行时报错并点名 key。 */
|
|
37
|
+
get<K extends keyof DependencyMap>(key: K): DependencyMap[K] {
|
|
38
|
+
if (!this.providers.has(key)) {
|
|
39
|
+
throw new Error(
|
|
40
|
+
`依赖未注册: ${String(key)}(已注册: ${[...this.providers.keys()].join(', ') || '无'})`,
|
|
41
|
+
);
|
|
42
|
+
}
|
|
43
|
+
return this.providers.get(key) as DependencyMap[K];
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/** 用容器建实例:action 类的构造函数统一只接容器本身。 */
|
|
47
|
+
create<T>(cls: new (deps: Container) => T): T {
|
|
48
|
+
return new cls(this);
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/** 进程级默认容器:共享依赖在这里注册一次,全项目可用。 */
|
|
53
|
+
export const container = new Container().register('config', configModule).register('kvapi', kvapiModule);
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// 跨域(CORS)策略:面板对外来请求的态度。
|
|
2
2
|
//
|
|
3
|
-
//
|
|
3
|
+
// 为什么不按 Origin 拒绝写请求(任务 #57):
|
|
4
4
|
// 浏览器对 POST/PUT/DELETE **一律带 Origin 头,哪怕请求与页面同源**。
|
|
5
5
|
// 面板原先那道校验是「Origin 的主机名必须是 127.0.0.1/localhost」——
|
|
6
6
|
// 走内网穿透(frp / cloudflared / ngrok)从手机或外网访问时,Origin 变成隧道
|
|
@@ -23,12 +23,31 @@ const DEFAULT_ALLOWED_METHODS = 'GET,HEAD,POST,PUT,PATCH,DELETE,OPTIONS';
|
|
|
23
23
|
const DEFAULT_ALLOWED_HEADERS = 'content-type,authorization,x-requested-with';
|
|
24
24
|
const PREFLIGHT_MAX_AGE = '600';
|
|
25
25
|
|
|
26
|
+
/** 请求头里我们关心的形状(Node 的 IncomingHttp.headers 是 (string|string[]|undefined))。 */
|
|
27
|
+
export type ReqHeaders = Record<string, string | string[] | undefined>;
|
|
28
|
+
|
|
29
|
+
/** 极简请求形状:cors 只看 method 与 headers。 */
|
|
30
|
+
export interface CorsRequest {
|
|
31
|
+
method?: string;
|
|
32
|
+
headers?: ReqHeaders;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/** 放行策略:all = 放行全部;否则精确/通配名单。 */
|
|
36
|
+
export interface AllowOrigin {
|
|
37
|
+
all: boolean;
|
|
38
|
+
list: string[];
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
function header(req: CorsRequest | undefined, name: string): string {
|
|
42
|
+
const v = req?.headers?.[name];
|
|
43
|
+
return Array.isArray(v) ? (v[0] ?? '') : String(v ?? '');
|
|
44
|
+
}
|
|
45
|
+
|
|
26
46
|
/**
|
|
27
47
|
* 解析 --allow-origin 规格。
|
|
28
|
-
* @param
|
|
29
|
-
* @returns {{all: boolean, list: string[]}} 放行策略
|
|
48
|
+
* @param spec 逗号分隔的来源列表;'*' 或缺省 = 放行全部
|
|
30
49
|
*/
|
|
31
|
-
export function parseAllowOrigin(spec) {
|
|
50
|
+
export function parseAllowOrigin(spec: string | undefined | null): AllowOrigin {
|
|
32
51
|
if (spec === undefined || spec === null) return { all: true, list: [] };
|
|
33
52
|
const raw = String(spec).trim();
|
|
34
53
|
if (!raw || raw === '*') return { all: true, list: [] };
|
|
@@ -44,33 +63,29 @@ export function parseAllowOrigin(spec) {
|
|
|
44
63
|
/**
|
|
45
64
|
* 名单项匹配:支持通配(https://*.example.com)。只有通配是「宽松」的语义,
|
|
46
65
|
* 其余字符按字面量比对。
|
|
47
|
-
* @param {string} pattern 名单项
|
|
48
|
-
* @param {string} origin 实际来源
|
|
49
|
-
* @returns {boolean} 是否命中
|
|
50
66
|
*/
|
|
51
|
-
function patternMatches(pattern, origin) {
|
|
67
|
+
function patternMatches(pattern: string, origin: string): boolean {
|
|
52
68
|
if (!pattern.includes('*')) return pattern === origin;
|
|
53
69
|
const parts = pattern.split('*');
|
|
54
70
|
let rest = origin;
|
|
55
71
|
for (let i = 0; i < parts.length; i++) {
|
|
56
|
-
const part = parts[i]
|
|
72
|
+
const part = parts[i]!;
|
|
57
73
|
if (!part) continue;
|
|
58
74
|
const idx = rest.indexOf(part);
|
|
59
75
|
if (idx === -1) return false;
|
|
60
76
|
if (i === 0 && idx !== 0) return false; // 首段必须贴在开头
|
|
61
77
|
rest = rest.slice(idx + part.length);
|
|
62
78
|
}
|
|
63
|
-
const tail = parts[parts.length - 1]
|
|
79
|
+
const tail = parts[parts.length - 1]!;
|
|
64
80
|
return !tail || origin.endsWith(tail);
|
|
65
81
|
}
|
|
66
82
|
|
|
67
83
|
/**
|
|
68
84
|
* 来源是否在放行名单里。
|
|
69
|
-
* @param
|
|
70
|
-
* @param
|
|
71
|
-
* @returns {boolean} 是否放行
|
|
85
|
+
* @param origin 请求的 Origin 头
|
|
86
|
+
* @param allow 放行策略
|
|
72
87
|
*/
|
|
73
|
-
export function originAllowed(origin, allow) {
|
|
88
|
+
export function originAllowed(origin: string, allow: AllowOrigin): boolean {
|
|
74
89
|
if (!origin) return false;
|
|
75
90
|
if (!allow || allow.all) return true;
|
|
76
91
|
const o = String(origin).replace(/\/+$/, '');
|
|
@@ -79,13 +94,11 @@ export function originAllowed(origin, allow) {
|
|
|
79
94
|
|
|
80
95
|
/**
|
|
81
96
|
* 是否是 CORS 预检请求(OPTIONS + Access-Control-Request-Method)。
|
|
82
|
-
* @param {{method?: string, headers: object}} req 原始请求
|
|
83
|
-
* @returns {boolean} 是否预检
|
|
84
97
|
*/
|
|
85
|
-
export function isPreflight(req) {
|
|
98
|
+
export function isPreflight(req: CorsRequest | undefined): boolean {
|
|
86
99
|
return (
|
|
87
100
|
String((req && req.method) || '').toUpperCase() === 'OPTIONS' &&
|
|
88
|
-
!!(req
|
|
101
|
+
!!header(req, 'access-control-request-method')
|
|
89
102
|
);
|
|
90
103
|
}
|
|
91
104
|
|
|
@@ -94,12 +107,9 @@ export function isPreflight(req) {
|
|
|
94
107
|
* 非浏览器客户端(无 Origin)不加头;来源不在名单里也**故意不加** allow-origin
|
|
95
108
|
* ——让浏览器自己拦下这次跨源请求(而不是服务端回 403,那会把「跨源不支持」
|
|
96
109
|
* 和「请求出错」混成一种状态码)。
|
|
97
|
-
* @param {{headers: object}} req 原始请求
|
|
98
|
-
* @param {{all: boolean, list: string[]}} allow 放行策略
|
|
99
|
-
* @returns {Record<string, string>} CORS 响应头
|
|
100
110
|
*/
|
|
101
|
-
export function corsHeaders(req, allow) {
|
|
102
|
-
const origin = req
|
|
111
|
+
export function corsHeaders(req: CorsRequest | undefined, allow: AllowOrigin): Record<string, string> {
|
|
112
|
+
const origin = header(req, 'origin');
|
|
103
113
|
if (!origin) return { vary: 'Origin' };
|
|
104
114
|
if (!originAllowed(origin, allow)) return { vary: 'Origin' };
|
|
105
115
|
return {
|
|
@@ -110,12 +120,9 @@ export function corsHeaders(req, allow) {
|
|
|
110
120
|
|
|
111
121
|
/**
|
|
112
122
|
* 预检响应头:回显浏览器这次请求的方法与请求头(只回该次预检涉及的)。
|
|
113
|
-
* @param {{headers: object}} req 原始请求
|
|
114
|
-
* @param {{all: boolean, list: string[]}} allow 放行策略
|
|
115
|
-
* @returns {Record<string, string>} 预检响应头
|
|
116
123
|
*/
|
|
117
|
-
export function preflightHeaders(req, allow) {
|
|
118
|
-
const requested = req
|
|
124
|
+
export function preflightHeaders(req: CorsRequest | undefined, allow: AllowOrigin): Record<string, string> {
|
|
125
|
+
const requested = header(req, 'access-control-request-headers');
|
|
119
126
|
return {
|
|
120
127
|
...corsHeaders(req, allow),
|
|
121
128
|
'access-control-allow-methods': DEFAULT_ALLOWED_METHODS,
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
// help:完全由命令表生成。
|
|
2
|
+
//
|
|
3
|
+
// 命令表的一行见 spec.ts 的 entryOf —— 纯「声明 → 文本」,runtime/spec 之外没有副本。
|
|
4
|
+
// 本文件是纯函数层:表由调用方(cli.ts)传入,不持有自己的状态,
|
|
5
|
+
// 因此 help 文本不可能与实际命令脱节。
|
|
6
|
+
import { APP_NAME } from '../core/paths.js';
|
|
7
|
+
import { configPathFromEnv } from '../core/config.js';
|
|
8
|
+
import { badInput } from '../core/errors.js';
|
|
9
|
+
import { MODULES } from './registry.js';
|
|
10
|
+
import { cliPathsOf, entryOf, usageOf, type AnyAction } from './spec.js';
|
|
11
|
+
|
|
12
|
+
export type HelpEntry = ReturnType<typeof entryOf>;
|
|
13
|
+
|
|
14
|
+
// 解析帮助主题。既接受模块 id(repos),也接受命令组(repo)——
|
|
15
|
+
// 用户脑子里想的是「repo 相关的东西」,不会去记内部模块名。
|
|
16
|
+
// 这条路径不能报错退出:`nx-kv help <随便什么>` 失败会让最需要帮助的人卡住。
|
|
17
|
+
export function helpEntries(commands: readonly AnyAction[], topic?: unknown): HelpEntry[] {
|
|
18
|
+
const all = commands.map(entryOf);
|
|
19
|
+
if (!topic) return all;
|
|
20
|
+
|
|
21
|
+
const t = String(topic);
|
|
22
|
+
if (MODULES.some((m) => m.id === t)) return all.filter((e) => e.module === t);
|
|
23
|
+
|
|
24
|
+
const byRoot = all.filter((e) => e.command.split(' ')[1] === t);
|
|
25
|
+
if (byRoot.length) return byRoot;
|
|
26
|
+
|
|
27
|
+
// 命令本身的 id 也认(如 `nx-kv help repo.add`)
|
|
28
|
+
const byId = all.filter((e) => e.id === t);
|
|
29
|
+
if (byId.length) return byId;
|
|
30
|
+
|
|
31
|
+
const topics = [...new Set(all.map((e) => e.module))].join(', ');
|
|
32
|
+
throw badInput(`未知帮助主题: ${t}(可用模块: ${topics};或命令组如 repo / skill / gh)`);
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export function renderHelp(entries: readonly HelpEntry[], topic: unknown, version: string): string {
|
|
36
|
+
const lines: string[] = [];
|
|
37
|
+
if (!topic) {
|
|
38
|
+
lines.push(`${APP_NAME} · nx-kv v${version}`);
|
|
39
|
+
lines.push('KV 清单管理中枢:serve 驱动 CLI 与 Web,同源同构。');
|
|
40
|
+
lines.push(`配置: ${configPathFromEnv()} (环境变量 NX_KV_CONFIG 或 --config 覆盖)`);
|
|
41
|
+
lines.push('');
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
const groups = new Map<string, HelpEntry[]>();
|
|
45
|
+
for (const e of entries) {
|
|
46
|
+
if (!groups.has(e.module)) groups.set(e.module, []);
|
|
47
|
+
groups.get(e.module)!.push(e);
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
for (const [mod, list] of groups) {
|
|
51
|
+
const title =
|
|
52
|
+
MODULES.find((m) => m.id === mod)?.title || (mod === 'platform' ? '平台命令' : mod);
|
|
53
|
+
lines.push(title + ':');
|
|
54
|
+
const width = Math.max(...list.map((e) => e.usage.length));
|
|
55
|
+
for (const e of list) lines.push(' ' + e.usage.padEnd(width + 2) + e.summary);
|
|
56
|
+
lines.push('');
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
lines.push('通用:');
|
|
60
|
+
lines.push(' --json 机器可读输出(agent 模式)');
|
|
61
|
+
lines.push(' --config 本次运行覆盖配置文件路径');
|
|
62
|
+
return lines.join('\n');
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
// `nx-kv <命令> --help`:只打印这一条,而不是整个模块——
|
|
66
|
+
// 之前这里传的是 cmd.cli[0],对别名 action(cli 是数组的数组)会拼出 "bundled,list"。
|
|
67
|
+
export function printCommandHelp(cmd: AnyAction): void {
|
|
68
|
+
const lines: string[] = [usageOf(cmd)];
|
|
69
|
+
if (cmd.summary) lines.push(' ' + cmd.summary);
|
|
70
|
+
lines.push('');
|
|
71
|
+
|
|
72
|
+
const aliases = cliPathsOf(cmd).slice(1).map((p) => APP_NAME + ' ' + p.join(' '));
|
|
73
|
+
if (aliases.length) lines.push('别名: ' + aliases.join(' · '));
|
|
74
|
+
if (cmd.http) lines.push('对应路由: ' + cmd.http[0] + ' ' + cmd.http[1]);
|
|
75
|
+
lines.push('所属模块: ' + (cmd.module || 'platform'));
|
|
76
|
+
console.log(lines.join('\n'));
|
|
77
|
+
}
|
|
@@ -0,0 +1,139 @@
|
|
|
1
|
+
// 模块注册表:全部功能域的 action 在此汇合。
|
|
2
|
+
//
|
|
3
|
+
// CLI 命令表、HTTP 路由表、help 文本三者全部由此派生 —— 这是
|
|
4
|
+
// 「Web 上每个操作都有等价 CLI 命令」得以成为**结构性保证**而非口头约定的原因:
|
|
5
|
+
// 一条 action 同时声明 cli 与 http,二者写在同一处,不可能分叉。
|
|
6
|
+
//
|
|
7
|
+
// 新增功能域:
|
|
8
|
+
// 1. 写 src/modules/<name>/(模板形态:index.ts 装配 ModuleBase 子类 + schemas.ts
|
|
9
|
+
// 契约 + actions/*.ts 一条 action 一个文件 + _manifest.generated.ts)
|
|
10
|
+
// 2. 在下面的 create 调用里加上它的实例
|
|
11
|
+
// 3. 需要面板的话,到 web/frontend/ 写视图并在前端 registry 登记——**不经过后端**
|
|
12
|
+
//
|
|
13
|
+
// 前端怎么呈现,后端不知道也不该知道:本文件里没有任何前端路径。
|
|
14
|
+
// 后端只提供 /api/*,前端只消费 /api/*,跨端的唯一例外是同构纯函数(src/shared/)。
|
|
15
|
+
// tests/unit/registry.test.mjs 会断言两侧的模块集合对齐,漏登记直接测试失败。
|
|
16
|
+
//
|
|
17
|
+
// **迁移期双通道**:system 已是模板形态(@action + zod);其余模块还是 legacy
|
|
18
|
+
// plain-object(flags 表契约)。两者都满足 AnyModule,Registry 对通道无感——
|
|
19
|
+
// load 期自检对两通道一视同仁(重复 id / 重复路由 / 缺 run 启动即红)。
|
|
20
|
+
import { ModuleBase, type AnyModule } from './types/module.js';
|
|
21
|
+
import { cliPathsOf, entryOf, type AnyAction } from './spec.js';
|
|
22
|
+
import { publishCommandTable } from '../core/command-table.js';
|
|
23
|
+
import systemModule from '../modules/system/index.js';
|
|
24
|
+
import setting from '../modules/setting/index.js';
|
|
25
|
+
import auth from '../modules/auth/index.js';
|
|
26
|
+
import localtask from '../modules/localtask/index.js';
|
|
27
|
+
import tasktool from '../modules/tasktool/index.js';
|
|
28
|
+
import todo from '../modules/todo/index.js';
|
|
29
|
+
import repos from '../modules/repos/index.js';
|
|
30
|
+
import docs from '../modules/docs/index.js';
|
|
31
|
+
import file from '../modules/file/index.js';
|
|
32
|
+
import templates from '../modules/templates/index.js';
|
|
33
|
+
import bundled from '../modules/bundled/index.js';
|
|
34
|
+
import db from '../modules/db/index.js';
|
|
35
|
+
|
|
36
|
+
// 工作空间(group)已于 2026-10-23 并入 todo 模块:它是**清单的设置**,
|
|
37
|
+
// 不该单独占一个模块/一个 tab。命令与路由一字未改。
|
|
38
|
+
const MODULE_LIST: readonly AnyModule[] = [
|
|
39
|
+
systemModule,
|
|
40
|
+
setting,
|
|
41
|
+
auth,
|
|
42
|
+
localtask,
|
|
43
|
+
tasktool,
|
|
44
|
+
todo,
|
|
45
|
+
repos,
|
|
46
|
+
docs,
|
|
47
|
+
file,
|
|
48
|
+
templates,
|
|
49
|
+
bundled,
|
|
50
|
+
db,
|
|
51
|
+
];
|
|
52
|
+
|
|
53
|
+
/** 模块元组:全部业务域(tests/unit/registry.test.mjs 对账模块目录一一对应)。 */
|
|
54
|
+
export const MODULES: readonly AnyModule[] = [...MODULE_LIST].sort(
|
|
55
|
+
(a, b) => (a.order ?? 100) - (b.order ?? 100),
|
|
56
|
+
);
|
|
57
|
+
|
|
58
|
+
export class Registry {
|
|
59
|
+
private constructor(
|
|
60
|
+
readonly modules: readonly AnyModule[],
|
|
61
|
+
readonly actions: readonly AnyAction[],
|
|
62
|
+
) {}
|
|
63
|
+
|
|
64
|
+
/**
|
|
65
|
+
* 唯一装载入口。装载正确性由这里的运行时自检负责
|
|
66
|
+
* (重复 id / 重复 CLI 路由 / 重复 HTTP 路由 / 缺 run / rest flag 置尾)。
|
|
67
|
+
* 运行时按 order 排序。
|
|
68
|
+
*/
|
|
69
|
+
static create(modules: readonly AnyModule[]): Registry {
|
|
70
|
+
const sorted = [...modules].sort((a, b) => (a.order ?? 100) - (b.order ?? 100));
|
|
71
|
+
const actions = sorted.flatMap((m) =>
|
|
72
|
+
(m.actions || []).map((a) => ({ ...(a as object), module: m.id }) as AnyAction),
|
|
73
|
+
);
|
|
74
|
+
|
|
75
|
+
// 装载期自检:把「两个模块声明了同名命令」这类问题暴露在启动瞬间,
|
|
76
|
+
// 而不是等某个用户敲到那条命令时才发现。
|
|
77
|
+
//
|
|
78
|
+
// 方向性约定(刻意的不对称):
|
|
79
|
+
// - 每条 action 都必须有 cli —— 保证「Web 上能做的,CLI 都能做」
|
|
80
|
+
// - http 允许为 null(纯 CLI 命令),但**不允许**声明 http 却没有 cli
|
|
81
|
+
const seenIds = new Set<string>();
|
|
82
|
+
const seenCli = new Set<string>();
|
|
83
|
+
const seenHttp = new Set<string>();
|
|
84
|
+
for (const a of actions) {
|
|
85
|
+
if (seenIds.has(a.id)) throw new Error('action id 重复: ' + a.id);
|
|
86
|
+
seenIds.add(a.id);
|
|
87
|
+
|
|
88
|
+
const paths = cliPathsOf(a);
|
|
89
|
+
if (!paths.length) throw new Error(`action 没有声明 CLI 命令(Web 操作必须有 CLI 等价): ${a.id}`);
|
|
90
|
+
for (const path of paths) {
|
|
91
|
+
const key = path.join(' ');
|
|
92
|
+
if (seenCli.has(key)) throw new Error(`CLI 命令重复: ${key}(action ${a.id})`);
|
|
93
|
+
seenCli.add(key);
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
if (a.http) {
|
|
97
|
+
const httpKey = a.http[0] + ' ' + a.http[1];
|
|
98
|
+
if (seenHttp.has(httpKey)) throw new Error(`HTTP 路由重复: ${httpKey}(action ${a.id})`);
|
|
99
|
+
seenHttp.add(httpKey);
|
|
100
|
+
} else if (a.http !== null) {
|
|
101
|
+
throw new Error(`action 的 http 必须是路由数组或显式 null: ${a.id}`);
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
if (!a.run) throw new Error(`action 缺少 run: ${a.id}`);
|
|
105
|
+
|
|
106
|
+
// rest flag(吃掉其后全部 token,见 spec.ts)必须在声明里排最后:
|
|
107
|
+
// CLI 是「谁的路径最长谁赢」,flag 的先后由声明顺序决定;一旦后面还跟着别的 flag,
|
|
108
|
+
// 它就会被当成值的一部分静默吞掉——命令照跑,参数却没了。
|
|
109
|
+
// (仅 legacy flags 通道有 rest flag;zod 通道用 restArg,无此约束。)
|
|
110
|
+
const flagNames = Object.keys(a.flags || {});
|
|
111
|
+
if (flagNames.length) {
|
|
112
|
+
const restAt = flagNames.findIndex((n) => (a.flags![n] as { rest?: boolean }).rest);
|
|
113
|
+
if (restAt >= 0 && restAt !== flagNames.length - 1) {
|
|
114
|
+
throw new Error(
|
|
115
|
+
`rest flag 必须声明在 flags 的最后(其后还有: ${flagNames.slice(restAt + 1).join(', ')}): ${a.id}`,
|
|
116
|
+
);
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
return new Registry(sorted, actions);
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
/** 全项目唯一注册表实例:CliApp / ApiRouter / 编程入口都从它取 action 与命令表。 */
|
|
126
|
+
export const registry = Registry.create(MODULES);
|
|
127
|
+
|
|
128
|
+
// 兼容别名:ACTIONS 是 registry.actions 的投影;tests 与文档沿用旧名。
|
|
129
|
+
export const ACTIONS = registry.actions;
|
|
130
|
+
|
|
131
|
+
// 命令表快照:模块(system.bootstrap 要给面板下发「CLI 等价」)只读这份,
|
|
132
|
+
// 不再 import runtime —— registry → modules → cli → registry 正是那条要避开的环。
|
|
133
|
+
// cli.ts 在装配出 ALL_COMMANDS 后会再覆盖一次(含 serve / help / version
|
|
134
|
+
// 这类平台命令),所以「从 CLI 跑」拿到的是完整表,纯 HTTP 场景拿到的是 action 表。
|
|
135
|
+
publishCommandTable(ACTIONS.map(entryOf));
|
|
136
|
+
|
|
137
|
+
// ModuleBase 仅为类型连贯在此重导出:模块作者从 types/module.js 拿基类,
|
|
138
|
+
// runtime 侧不主动扩散它。
|
|
139
|
+
export { ModuleBase };
|