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.
Files changed (39) hide show
  1. package/CHANGELOG.md +37 -0
  2. package/README.md +10 -4
  3. package/bin/{cli.mjs → kv.mjs} +13 -2
  4. package/package.json +23 -11
  5. package/src/core/{command-table.js → command-table.ts} +16 -5
  6. package/src/core/{config.js → config.ts} +46 -27
  7. package/src/core/db/quiet.js +4 -0
  8. package/src/core/{errors.js → errors.ts} +35 -18
  9. package/src/core/{open.js → open.ts} +3 -3
  10. package/src/core/{paths.js → paths.ts} +18 -9
  11. package/src/core/{serve-port.js → serve-port.ts} +43 -17
  12. package/src/index.js +11 -9
  13. package/src/index.ts +10 -0
  14. package/src/modules/system/actions/_manifest.generated.ts +23 -0
  15. package/src/modules/system/actions/bootstrap.ts +74 -0
  16. package/src/modules/system/actions/health.ts +57 -0
  17. package/src/modules/system/actions/routes.ts +26 -0
  18. package/src/modules/system/index.ts +29 -0
  19. package/src/modules/system/{routes.js → routes.ts} +22 -26
  20. package/src/modules/system/schemas.ts +29 -0
  21. package/src/modules/tasktool/panel-escort.js +1 -1
  22. package/src/runtime/action-base.ts +14 -0
  23. package/src/runtime/action-decorator.ts +176 -0
  24. package/src/runtime/api.ts +146 -0
  25. package/src/runtime/{cli.js → cli.ts} +241 -161
  26. package/src/runtime/codegen.ts +243 -0
  27. package/src/runtime/container.ts +53 -0
  28. package/src/runtime/{cors.js → cors.ts} +35 -28
  29. package/src/runtime/help.ts +77 -0
  30. package/src/runtime/registry.ts +139 -0
  31. package/src/runtime/{server.js → server.ts} +65 -24
  32. package/src/runtime/{spec.js → spec.ts} +122 -31
  33. package/src/runtime/types/module.ts +43 -0
  34. package/src/runtime/zod-bridge.ts +198 -0
  35. package/src/web/frontend/api/cli-tree.json +49 -0
  36. package/src/web/frontend/api/client.generated.ts +39 -0
  37. package/src/modules/system/index.js +0 -96
  38. package/src/runtime/api.js +0 -101
  39. package/src/runtime/registry.js +0 -89
@@ -0,0 +1,176 @@
1
+ // action 装饰器:在 ModuleBase 子类的方法上声明 action(zod schema 即契约)。
2
+ //
3
+ // 单一通道:全部新业务 action 都走这里——声明(@action 元数据)与实现同文件,
4
+ // 契约常量放同域 schemas.ts;模块的 actions 字段由 zodActionsOf(instance) 收集。
5
+ // 迁移期 legacy plain-object action(flags 表契约)并存,Registry / CliApp /
6
+ // ApiRouter 对两通道无感;全部模块迁移后 legacy 删除。
7
+ //
8
+ // 三条实测结论(模板 spike 逼出来的,改前先读):
9
+ //
10
+ // (a) 元数据挂在**方法函数**上(WeakMap),不碰 `context.metadata`。
11
+ // tsx(esbuild)会给 context.metadata 传对象,但 `Symbol.metadata` 在 Node 22 里
12
+ // 是 undefined——tsc 编译后交给原生 Node 时 context.metadata 就是 undefined,
13
+ // 元数据会静默丢失。挂函数上与运行时无关,最稳。
14
+ //
15
+ // (b) 装饰器**不改方法签名**(TC39 要求返回类型与原方法兼容),handler 的入参类型
16
+ // 只能手写 `z.output<typeof schema>`。z.input(调用方形状,.default 字段可选)
17
+ // 与 z.output(解析后形状,.default 字段必填)别混:handler 拿的是 z.output。
18
+ //
19
+ // (c) 出参没有 schema——**实现即契约**:apiclient 的返回类型从 action 类的方法签名
20
+ // 直接推断(codegen type-only 引类),同一信息只声明一次。
21
+ import { describeInput, type FieldDesc } from './zod-bridge.js';
22
+ import type { ZodType } from 'zod';
23
+
24
+ /** 装饰式 action 绑定到实例后的公共形状(registry.actions 的元素类型之一)。 */
25
+ export interface BoundAction {
26
+ id: string;
27
+ module: string;
28
+ cli: readonly string[];
29
+ http?: readonly [string, string] | null;
30
+ summary?: string;
31
+ // meta 形参刻意与 legacy 的 run(ctx, { transport }) 同形(宽松 string 而非字面量联合):
32
+ // Registry / CliApp / ApiRouter 把两通道 action 装进同一个数组,run 必须可互相赋值。
33
+ run: (input: unknown, meta?: { transport?: string }) => unknown;
34
+ [k: string]: unknown;
35
+ }
36
+
37
+ export interface ActionMeta {
38
+ /** 全局唯一 id,编成 `模块.动作`(如 `system.bootstrap`) */
39
+ id: string;
40
+ /** CLI 命令路径的各段(如 ['bootstrap']) */
41
+ cli: readonly string[];
42
+ /** HTTP 路由:[METHOD, PATTERN]。纯 CLI 命令**显式写 null**(与 legacy 一致,测试断言两态) */
43
+ http?: readonly [string, string] | null;
44
+ /** 一句话说明,进 help 与面板 */
45
+ summary?: string;
46
+ /** 位置参数字段名(按声明顺序消费 argv) */
47
+ args?: readonly string[];
48
+ /** 尾部收参:剩余全部位置参数收进这个字段(z.array(z.string())) */
49
+ restArg?: string;
50
+ /** 输入 schema:CLI 与 HTTP 共用的真相源(运行时校验 + 归一化的依据)。 */
51
+ input: ZodType;
52
+ /** CLI 人读渲染(面板不用——面板拿 data 走 JSON)。 */
53
+ render?: (result: unknown, ctx?: unknown) => string | Promise<string>;
54
+ /** SSE 类动作:true 时 HTTP 侧把 req/res 透传给 run,action 自己接管响应 */
55
+ stream?: boolean;
56
+ }
57
+
58
+ /** 装饰器元数据表:方法函数 → 声明。WeakMap 不阻止方法被 GC。 */
59
+ const META = new WeakMap<object, ActionMeta>();
60
+
61
+ /**
62
+ * 标注一个 action 方法。用法:
63
+ *
64
+ * ```ts
65
+ * export class SystemModule extends ModuleBase {
66
+ * @action({ id: 'system.bootstrap', cli: ['bootstrap'], http: ['GET', '/api/bootstrap'],
67
+ * summary: '…', input: systemBootstrapInput })
68
+ * bootstrap(ctx: z.output<typeof systemBootstrapInput>) { return this.svc.bootstrap(); }
69
+ * }
70
+ * ```
71
+ */
72
+ export function action(meta: ActionMeta) {
73
+ return function <F extends (...args: never[]) => unknown>(value: F, context: { kind: string }): F {
74
+ if (context.kind !== 'method') {
75
+ throw new Error(`@action 只能标注方法(收到 kind=${context.kind})`);
76
+ }
77
+ META.set(value as unknown as object, meta);
78
+ return value;
79
+ };
80
+ }
81
+
82
+ /** 取某个方法上的 action 声明;没标注过返回 undefined */
83
+ export function metaOf(method: unknown): ActionMeta | undefined {
84
+ if (typeof method !== 'function') return undefined;
85
+ return META.get(method as object);
86
+ }
87
+
88
+ /**
89
+ * 装饰式 action 绑定到实例后的形状:在 BoundAction 之上多带 zod 契约。
90
+ * CliApp 与 ApiRouter 据此走 zod 解析通道;channel: 'zod' 是双通道判别的标记。
91
+ */
92
+ export interface ZodBoundAction extends BoundAction {
93
+ id: string;
94
+ cli: readonly string[];
95
+ /** 纯 CLI 命令显式为 null(与 legacy 的两态约定一致) */
96
+ http: readonly [string, string] | null;
97
+ summary?: string;
98
+ /** 位置参数字段名(describeInput 的排序依据) */
99
+ args?: readonly string[];
100
+ /** 尾部收参字段名(剩余位置参数全收进来) */
101
+ restArg?: string;
102
+ /** 逐字段说明(收集时用 describeInput 算好一次,CLI/HTTP/usage/codegen 共用) */
103
+ fields: FieldDesc[];
104
+ input: ZodType;
105
+ render?: (result: unknown, ctx?: unknown) => string | Promise<string>;
106
+ stream?: boolean;
107
+ channel: 'zod';
108
+ /** 绑定的 action 类名(codegen 按它从清单 type-only 引类);tsc 编译后类名不变形(无压缩)。 */
109
+ className: string;
110
+ /** 类上的方法名(= 装饰的属性名)。 */
111
+ method: string;
112
+ }
113
+
114
+ /** 路由模式里的 :param 列表 */
115
+ export function routeParams(pattern: string): string[] {
116
+ return [...pattern.matchAll(/:([\w-]+)/g)].map((m) => m[1]!);
117
+ }
118
+
119
+ /**
120
+ * 收集一个实例(ModuleBase 子类)里被 @action 标注的方法,绑定成 actions 数组。
121
+ *
122
+ * handler 以**实例**为 this 调用——装饰式的卖点就是「声明与实现写在一起、
123
+ * 类可以持有状态」(依赖经构造注入,handler 调 this.deps.get(...))。
124
+ * 收集时用 getOwnPropertyDescriptor 取值而不是 proto[name]——
125
+ * 后者会执行 getter,只为了看一眼它有没有被装饰器标过。
126
+ *
127
+ * 装载期自检:路由 :param 未在 args 里声明 → 当场报错(单通道下这是该一致性
128
+ * 的唯一防线——类型层无法校验运行期才拼出来的元数据)。
129
+ */
130
+ export function zodActionsOf(instance: object): ZodBoundAction[] {
131
+ const proto = Object.getPrototypeOf(instance);
132
+ const moduleId = String((instance as { id?: unknown }).id ?? '');
133
+ const out: ZodBoundAction[] = [];
134
+ for (const name of Object.getOwnPropertyNames(proto)) {
135
+ if (name === 'constructor') continue;
136
+ const descriptor = Object.getOwnPropertyDescriptor(proto, name);
137
+ const method = descriptor?.value;
138
+ if (typeof method !== 'function') continue;
139
+ const meta = metaOf(method);
140
+ if (!meta) continue;
141
+
142
+ const args = meta.args ?? [];
143
+ if (meta.http) {
144
+ const declared = new Set([...args, ...(meta.restArg ? [meta.restArg] : [])]);
145
+ for (const p of routeParams(meta.http[1])) {
146
+ if (!declared.has(p)) {
147
+ throw new Error(
148
+ `action ${meta.id} 的路由 ${meta.http[1]} 含 :${p},但 args 里没声明同名位置参数` +
149
+ '(运行时会是 undefined)',
150
+ );
151
+ }
152
+ }
153
+ }
154
+
155
+ const fields = describeInput(meta.input, args);
156
+ const bound = method as (this: typeof instance, input: unknown, meta?: { transport?: string }) => unknown;
157
+ out.push({
158
+ id: meta.id,
159
+ cli: meta.cli,
160
+ http: meta.http ?? null,
161
+ summary: meta.summary,
162
+ args,
163
+ restArg: meta.restArg,
164
+ fields,
165
+ input: meta.input,
166
+ render: meta.render,
167
+ stream: meta.stream,
168
+ channel: 'zod',
169
+ module: moduleId,
170
+ className: instance.constructor.name,
171
+ method: name,
172
+ run: (input: unknown, meta?: { transport?: string }) => bound.call(instance, input, meta),
173
+ });
174
+ }
175
+ return out;
176
+ }
@@ -0,0 +1,146 @@
1
+ // HTTP 路由层:路由表由 action.http 编译而来,与 CLI 同源。
2
+ //
3
+ // 这里没有手写路由 —— 每条路由都来自某个模块的 action 声明,
4
+ // 所以「面板上有按钮、CLI 里没命令」在结构上不可能发生。
5
+ // ApiRouter 在构造期把注册表的 actions 编译成排好序的路由表,
6
+ // handle() 是 server 的 /api/* 入口——一次编译,常驻复用。
7
+ //
8
+ // **迁移期双通道**:zod action 走 fields + normalizeCliValue + parseZodInput;
9
+ // legacy action 走 applySpec(flags 表契约)。路由匹配 / stream 透传 / 错误信封
10
+ // 两通道完全一致。
11
+ import type { IncomingMessage, ServerResponse } from 'node:http';
12
+ import { compileRoute, applySpec, usageOf, type AnyAction } from './spec.js';
13
+ import { normalizeCliValue, parseZodInput } from './zod-bridge.js';
14
+ import type { ZodBoundAction } from './action-decorator.js';
15
+ import { toErrorPayload, httpStatusOf } from '../core/errors.js';
16
+
17
+ interface RouteEntry {
18
+ action: AnyAction;
19
+ method: string;
20
+ keys: string[];
21
+ regex: RegExp;
22
+ }
23
+
24
+ // 逐段比较两条模式,决定谁该先匹配:**字面量段优先于参数段**,段数多的优先。
25
+ //
26
+ // 为什么要排序而不是按声明顺序:`GET /api/repos/status` 与 `GET /api/repos/:id`
27
+ // 都能匹配 `/api/repos/status`,谁先声明谁赢。一旦有人调整 actions 顺序,
28
+ // 前者就会被后者抢走——这种 bug 只在运行时、且只在特定路径上出现,极难排查。
29
+ // 排序后,声明顺序不再影响匹配结果。
30
+ function routeSpecificity([, pattern]: readonly [string, string]): string[] {
31
+ return pattern.split('/').filter(Boolean);
32
+ }
33
+
34
+ function compareRoutes(a: RouteEntry, b: RouteEntry): number {
35
+ const pa = routeSpecificity(a.action.http!);
36
+ const pb = routeSpecificity(b.action.http!);
37
+ for (let i = 0; i < Math.min(pa.length, pb.length); i++) {
38
+ const litA = !pa[i]!.startsWith(':');
39
+ const litB = !pb[i]!.startsWith(':');
40
+ if (litA !== litB) return litA ? -1 : 1; // 字面量在前
41
+ }
42
+ return pb.length - pa.length; // 更长的(更具体)在前
43
+ }
44
+
45
+ export function sendJson(res: ServerResponse, status: number, obj: unknown): void {
46
+ res.writeHead(status, {
47
+ 'content-type': 'application/json; charset=utf-8',
48
+ 'cache-control': 'no-store',
49
+ });
50
+ res.end(JSON.stringify(obj));
51
+ }
52
+
53
+ // 请求体上限。定得比较宽是因为**附件上传走 base64 JSON**(面板选图 → data URL →
54
+ // 这里),base64 有 ~33% 膨胀,10MB 的图片会变成 ~13MB 的 JSON。
55
+ // 仍然有上限:本机单用户工具,但没有上限就等于「一个请求能吃掉全部内存」。
56
+ const MAX_BODY_BYTES = 24 * 1024 * 1024;
57
+
58
+ async function readBody(req: IncomingMessage): Promise<Record<string, unknown>> {
59
+ const chunks: Buffer[] = [];
60
+ let size = 0;
61
+ for await (const c of req) {
62
+ size += (c as Buffer).length;
63
+ if (size > MAX_BODY_BYTES) throw new Error(`请求体过大(上限 ${MAX_BODY_BYTES / 1024 / 1024}MB)`);
64
+ chunks.push(c as Buffer);
65
+ }
66
+ if (!chunks.length) return {};
67
+ return JSON.parse(Buffer.concat(chunks).toString('utf8')) as Record<string, unknown>;
68
+ }
69
+
70
+ export class ApiRouter {
71
+ private readonly routes: RouteEntry[];
72
+
73
+ constructor(actions: readonly AnyAction[]) {
74
+ this.routes = actions
75
+ .filter((a) => a.http)
76
+ .map((action) => {
77
+ const compiled = compileRoute(action as { http: readonly [string, string] });
78
+ return { action, method: compiled.method, keys: compiled.keys, regex: compiled.regex };
79
+ })
80
+ .sort(compareRoutes);
81
+ }
82
+
83
+ /** server 的 /api/* 入口:逐条尝试路由表,命中即执行并回 JSON。 */
84
+ async handle(req: IncomingMessage, res: ServerResponse, url: URL): Promise<void> {
85
+ const method = (req.method || 'GET').toUpperCase();
86
+
87
+ for (const route of this.routes) {
88
+ if (route.method !== method) continue;
89
+ const m = route.regex.exec(url.pathname);
90
+ if (!m) continue;
91
+
92
+ try {
93
+ const action = route.action;
94
+ // 这里不再按 Origin 拒绝写请求(任务 #57)。
95
+ // 原先那道校验比对 Origin 主机名是不是 127.0.0.1——但浏览器对 POST 一律带
96
+ // Origin(哪怕同源),于是走内网穿透从手机访问时 Origin 是隧道域名,
97
+ // 自己面板的同源写请求被判成跨站 → 403,任务提交不了。
98
+ // 跨域改由标准 CORS 头处理(预检 + allow-origin),见 runtime/cors.ts。
99
+
100
+ const raw: Record<string, unknown> = {};
101
+ route.keys.forEach((k, i) => {
102
+ raw[k] = decodeURIComponent(m[i + 1]!);
103
+ });
104
+ if (method === 'GET' || method === 'HEAD') {
105
+ for (const [k, v] of url.searchParams) raw[k] = v;
106
+ } else {
107
+ Object.assign(raw, await readBody(req).catch(() => ({})));
108
+ }
109
+
110
+ // 双通道分叉点:zod 走 fields 归一化 + zod 校验;legacy 走 applySpec。
111
+ const input = action.channel === 'zod'
112
+ ? parseZodChannelInput(action as ZodBoundAction, raw)
113
+ : applySpec(action, raw);
114
+
115
+ // stream 模式:把 req/res/url 透传给 run,让 action 自己接管响应(SSE 等)
116
+ if (action.stream) {
117
+ await action.run!({ ...input, __raw: { req, res, url } }, { transport: 'http' });
118
+ return;
119
+ }
120
+ const data = await action.run!(input, { transport: 'http' });
121
+ sendJson(res, 200, { ok: true, data });
122
+ } catch (err) {
123
+ // 错误码 → HTTP 状态只在这一处映射(core/errors.ts 提供表)
124
+ const p = toErrorPayload(err);
125
+ const payload: Record<string, unknown> = { ok: false, error: p.message, code: p.code };
126
+ if (p.details !== undefined) payload.details = p.details;
127
+ sendJson(res, httpStatusOf(p.code), payload);
128
+ }
129
+ return;
130
+ }
131
+
132
+ sendJson(res, 404, { ok: false, error: '接口不存在: ' + method + ' ' + url.pathname });
133
+ }
134
+ }
135
+
136
+ /** zod 通道的 HTTP 输入解析:路由参数 / query / body 统一过 normalizeCliValue 再校验。 */
137
+ function parseZodChannelInput(cmd: ZodBoundAction, raw: Record<string, unknown>): Record<string, unknown> {
138
+ const fields = cmd.fields;
139
+ const usage = usageOf(cmd);
140
+ const out: Record<string, unknown> = { ...raw };
141
+ for (const [k, v] of Object.entries(raw)) {
142
+ const f = fields.find((x) => x.name === k);
143
+ if (f) out[k] = normalizeCliValue(f, v);
144
+ }
145
+ return parseZodInput(cmd.input, out, usage) as Record<string, unknown>;
146
+ }