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
package/CHANGELOG.md CHANGED
@@ -2,6 +2,43 @@
2
2
 
3
3
  本文件记录对外可见的变更。格式参考 [Keep a Changelog](https://keepachangelog.com/zh-CN/1.1.0/)。
4
4
 
5
+ ## [0.47.0] - 2026-11-11 按 server-cli-web 模板形态 TS 化(阶段一:骨架,#174)
6
+
7
+ ### Added
8
+
9
+ - **模板骨架(对齐 `nx-nx/templates/server-cli-web`)**:`src/runtime/` 全部改写为
10
+ strict TypeScript——`@action` 装饰器(zod schema 即契约)、IoC 容器(`Container` +
11
+ `DependencyMap`)、`Registry` 类、`CliApp` / `ApiRouter` / `PanelServer`、
12
+ `zod-bridge`(CLI/HTTP 共用的归一化 + 校验)、`codegen`(前端 typed client +
13
+ CLI 树快照)。
14
+ - **codegen 工具链**:`pnpm gen:actions` 扫 `modules/<域>/actions/*.ts` 生成
15
+ `_manifest.generated.ts`(加一条 action = 新建一个文件 + 跑一次生成,模块 index 零改动);
16
+ `pnpm gen:api` 生成前端 `api/client.generated.ts` + `api/cli-tree.json`;
17
+ 新鲜度由 `tests/unit/api-client.test.mjs` 对账。
18
+ - **`system` 模块按模板形态重写**:`ModuleBase` 子类 + `schemas.ts`(zod 契约)+
19
+ `actions/<名>.ts` 一条 action 一个文件(bootstrap / health / routes)。
20
+ - **工具链**:三份 tsconfig(`base` / `node` / `web`,strict + `noUncheckedIndexedAccess`)、
21
+ `vite.config.ts`、`pnpm typecheck`、`pnpm dev`(vite + 后端一条命令起,端口先谈定再起进程)。
22
+ - **双通道并存**:legacy flags 表 action 与 zod 通道 action 由同一个 Registry 装载,
23
+ CLI / HTTP / help / routes 对通道无感——存量 166 条 action 行为零回归。
24
+
25
+ ### Changed
26
+
27
+ - **CLI 入口 `bin/cli.mjs` → `bin/kv.mjs`**(模板形态);**直跑 TS 源码**(tsx 注册 loader),
28
+ 不再走 dist——避免「改了源码忘 build」导致全局命令静默跑旧逻辑。
29
+ - `serve` / `help` / `version` 暂留 runtime 内建(help / version 要看注册表全集,
30
+ serve 要挂 localtask 面板占位;迁入 platform 模块列入后续阶段)。
31
+ - `routes` 命令从 runtime 内建迁入 `system` 模块(命令表改由 core 快照格子提供,
32
+ 不再依赖 runtime,解除「模块 ↔ runtime」的历史耦合)。
33
+ - **跨域策略保持不变**(任务 #57 的裁决):HTTP 层不做「Origin 主机名必须是本机」的拒绝,
34
+ 仍走标准 CORS 头 + 预检——模板自带的跨站拒绝会把内网穿透场景的真实用户挡在门外。
35
+ - `src/core/` 的 errors / paths / config / command-table / serve-port / open 改写为 TS。
36
+
37
+ ### Docs
38
+
39
+ - `plan/174-template-ts-refactor-stage1.md`:本次范围、分期与偏离模板之处(含理由)。
40
+ - 项目级 skill `dev-nxkv` 同步新结构:分层树、action 双形态契约、验证命令(typecheck / gen)。
41
+
5
42
  ## [0.46.0] - 2026-11-10 progress 参数彻底退役(#92)
6
43
 
7
44
  ### Removed
package/README.md CHANGED
@@ -34,17 +34,23 @@
34
34
  ```bash
35
35
  pnpm install
36
36
 
37
- # 开发模式(需要两个终端)
38
- pnpm run dev:serve # 终端 1:后端 :7877
39
- pnpm run dev # 终端 2:Vite :5181,/api 代理到 7877
37
+ # 开发模式(一条命令:vite + 后端一起起,ctrl-c 一起退)
38
+ pnpm dev # vite :5181 + 后端 :7877,/api 自动代理到后端实际端口
39
+
40
+ # 只想跑其中一半时
41
+ pnpm run dev:serve # 只起后端 :7877
42
+ pnpm run vite # 只起 Vite :5181(等价于 npx vite)
40
43
 
41
44
  # 生产模式
42
45
  pnpm start # 构建 + 起面板
43
46
 
44
- # 校验:lint + 构建 + 94 项端到端冒烟 + 33 项单元/一致性测试
47
+ # 校验:lint + 类型检查 + 构建 + 194 项端到端冒烟 + 894 项单元/一致性测试
45
48
  pnpm test
46
49
  ```
47
50
 
51
+ > 代码是 TypeScript(strict):`pnpm typecheck` 跑 `tsc -b`,
52
+ > `pnpm gen` 重新生成 action 清单与前端 typed client(改了 action 声明就要跑)。
53
+
48
54
  冒烟测试**对着假后端跑**(`tests/fake-backend.mjs`),不会碰生产服务器上的真实数据。
49
55
 
50
56
  `nx-kv serve` 默认会打开浏览器;**端口被占时不会报错退出**:
@@ -1,7 +1,13 @@
1
1
  #!/usr/bin/env node
2
2
  // nx-kv 唯一入口。
3
3
  // 设计约定:Web 面板上每个按钮,都对应这里的一条 CLI 命令——二者由同一份 action
4
- // 声明派生(见 src/modules/*/index.js),不是靠人维护两份清单。
4
+ // 声明派生(见 src/modules/*/),不是靠人维护两份清单。
5
+ //
6
+ // 运行的是 TS 源码(tsx 注册 loader 后动态 import)——与 `pnpm dev`、smoke 测试
7
+ // 同一条执行路径,**没有第二个真相源**。刻意不走 dist:bin 跑构建产物的话,
8
+ // 「改了源码忘了 build」会让全局 `nx-kv` 静默跑旧逻辑,这类 bug 没有任何报错指向根因。
9
+ // tsx 在 devDependencies:本仓库以 pnpm link 方式安装(scripts/link-local.mjs),
10
+ // bin 从仓库自己的 node_modules 解析 tsx,不需要装进 dependencies。
5
11
 
6
12
  // ── Node 版本硬拦(必须在任何业务 import 之前)──────────────────────────
7
13
  //
@@ -19,7 +25,12 @@ if (!versionCheck.ok) {
19
25
  process.exit(1);
20
26
  }
21
27
 
22
- const { runCli } = await import('../src/runtime/cli.js');
28
+ import { register } from 'tsx/esm/api';
29
+
30
+ // 注册 tsx loader(返回 unregister,进程退出无需清理)
31
+ register();
32
+
33
+ const { runCli } = await import('../src/runtime/cli.ts');
23
34
 
24
35
  runCli(process.argv.slice(2)).catch((err) => {
25
36
  console.error(err && err.stack ? err.stack : String(err));
package/package.json CHANGED
@@ -1,28 +1,33 @@
1
1
  {
2
2
  "name": "nx-kv",
3
- "version": "0.46.0",
3
+ "version": "0.47.0",
4
4
  "description": "nx-kv — KV 清单管理中枢(远程)+ 本机本地任务队列(localtask):serve 驱动 CLI 与 Web 面板,同源同构,附带可安装 skill 供 agent 提交 / 领取 / 阻塞接收任务",
5
5
  "type": "module",
6
6
  "bin": {
7
- "nx-kv": "bin/cli.mjs"
7
+ "nx-kv": "bin/kv.mjs"
8
8
  },
9
9
  "main": "src/index.js",
10
10
  "exports": {
11
11
  ".": "./src/index.js"
12
12
  },
13
13
  "scripts": {
14
- "build": "vite build && node scripts/link-local.mjs --auto",
15
- "dev": "vite",
16
- "dev:serve": "node bin/cli.mjs serve --no-open",
17
- "start": "pnpm run build && node bin/cli.mjs serve",
14
+ "gen:actions": "node --import tsx scripts/gen-actions.mjs",
15
+ "gen:api": "node --import tsx scripts/gen-api-client.mjs",
16
+ "gen": "pnpm run gen:actions && pnpm run gen:api",
17
+ "typecheck": "pnpm run gen && tsc -b tsconfig.node.json tsconfig.web.json",
18
+ "build": "pnpm run gen && tsc -b tsconfig.node.json && vite build && node scripts/link-local.mjs --auto",
19
+ "dev": "node --import tsx scripts/dev.mjs",
20
+ "vite": "vite",
21
+ "dev:serve": "node --import tsx src/runtime/cli.ts serve --no-open",
22
+ "start": "pnpm run build && node --import tsx src/runtime/cli.ts serve",
18
23
  "link:local": "node scripts/link-local.mjs",
19
24
  "unlink:local": "node scripts/link-local.mjs --unlink",
20
25
  "lint": "eslint . && node scripts/check-tdz.mjs --all && node scripts/check-schema-decisions.mjs && node scripts/check-lines.mjs",
21
26
  "check:schema": "node scripts/check-schema-decisions.mjs",
22
- "test": "pnpm run lint && pnpm run build && pnpm run test:smoke && pnpm run test:unit",
23
- "test:smoke": "node tests/smoke.mjs",
24
- "test:unit": "node --test tests/unit/*.test.mjs",
25
- "test:db": "node --test tests/unit/db-*.test.mjs"
27
+ "test": "pnpm run lint && pnpm run typecheck && pnpm run build && pnpm run test:smoke && pnpm run test:unit",
28
+ "test:smoke": "node --import tsx tests/smoke.mjs",
29
+ "test:unit": "node --import tsx --test tests/unit/*.test.mjs",
30
+ "test:db": "node --import tsx --test tests/unit/db-*.test.mjs"
26
31
  },
27
32
  "packageManager": "pnpm@10.33.0",
28
33
  "engines": {
@@ -49,14 +54,21 @@
49
54
  },
50
55
  "license": "MIT",
51
56
  "devDependencies": {
57
+ "@types/node": "^26.6.6",
58
+ "@types/react": "^19.2.7",
59
+ "@types/react-dom": "^19.2.3",
52
60
  "@vitejs/plugin-react": "^6.1.1",
53
61
  "eslint": "^10.10.0",
62
+ "tsx": "^4.23.15",
63
+ "typescript": "^5.9.3",
64
+ "typescript-eslint": "^8.72.2",
54
65
  "vite": "^8.3.0"
55
66
  },
56
67
  "dependencies": {
57
68
  "flexlayout-react": "0.11.1",
58
69
  "handlebars": "^4.7.10",
59
70
  "react": "^19.3.0",
60
- "react-dom": "^19.3.0"
71
+ "react-dom": "^19.3.0",
72
+ "zod": "^4.6.7"
61
73
  }
62
74
  }
@@ -1,7 +1,7 @@
1
1
  // 命令表快照:runtime 装配后写一次,模块只读。
2
2
  //
3
3
  // 为什么需要这个格子:`/api/bootstrap` 要给面板下发「每个操作对应的 CLI 命令」,
4
- // 而这张表由 runtime 装配(cli.js / registry.js)。模块直接 import runtime 会成环
4
+ // 而这张表由 runtime 装配(cli.ts / registry.ts)。模块直接 import runtime 会成环
5
5
  // (registry → modules/system → cli → registry),历史写法是用 `await import(...)`
6
6
  // 绕开:命令能跑,但分层倒了,且 loader 顺序一变就可能拿到半初始化的模块。
7
7
  //
@@ -9,14 +9,25 @@
9
9
  // runtime → core(写快照) modules → core(读快照)
10
10
  // 谁都不再反过来依赖谁。没有快照时返回空数组——调用方(bootstrap)允许空表降级,
11
11
  // 面板仍能打开,只是没有 CLI 提示。
12
- let rows = [];
12
+
13
+ /** 命令表的一行:routes / help / bootstrap 共用,几张表因此必然同源同长。 */
14
+ export interface CommandEntry {
15
+ id: string;
16
+ module: string;
17
+ command: string;
18
+ usage: string;
19
+ http: { method: string; path: string } | null;
20
+ summary?: string;
21
+ }
22
+
23
+ let rows: CommandEntry[] = [];
13
24
 
14
25
  /** 由 runtime 在装配完成时调用。只保留最后一次写入(CLI 的表是注册表的超集)。 */
15
- export function publishCommandTable(list) {
16
- rows = Array.isArray(list) ? list : [];
26
+ export function publishCommandTable(list: readonly CommandEntry[]): void {
27
+ rows = Array.isArray(list) ? [...list] : [];
17
28
  }
18
29
 
19
30
  /** 当前命令表快照(每行 { id, module, command, usage, http, summary })。 */
20
- export function commandTable() {
31
+ export function commandTable(): CommandEntry[] {
21
32
  return rows;
22
33
  }
@@ -33,7 +33,7 @@ import { nowMs } from './db/time.js';
33
33
  export const CONFIG_PATH = join(homedir(), '.nx-kv', 'config.json');
34
34
 
35
35
  // 测试与多实例覆盖:NX_KV_CONFIG 环境变量优先,其次是 NX_KV_STORE 所在目录
36
- export function configPathFromEnv() {
36
+ export function configPathFromEnv(): string {
37
37
  return process.env.NX_KV_CONFIG || CONFIG_PATH;
38
38
  }
39
39
 
@@ -42,15 +42,33 @@ export const DEFAULT_BASE_URL = 'http://192.0.2.47:8988';
42
42
  // ── 显式白名单(#82 的教训:不列出的字段两边都不写)────────────────────
43
43
 
44
44
  /** 留在 config.json 的字段(凭据 + 会话身份)。config.json 的键集合精确等于它。 */
45
- export const CREDENTIAL_KEYS = Object.freeze(['baseUrl', 'token', 'email', 'userId', 'groupId']);
45
+ export const CREDENTIAL_KEYS = Object.freeze(['baseUrl', 'token', 'email', 'userId', 'groupId'] as const);
46
46
 
47
47
  /** 进 settings 表(`app.*` 前缀)的偏好字段。 */
48
- export const PREF_KEYS = Object.freeze(['autoSyncAttachments', 'attachmentsDir', 'gitRepoRoot', 'gitDevRoot']);
48
+ export const PREF_KEYS = Object.freeze([
49
+ 'autoSyncAttachments',
50
+ 'attachmentsDir',
51
+ 'gitRepoRoot',
52
+ 'gitDevRoot',
53
+ ] as const);
49
54
 
50
55
  /** settings 表里偏好字段的键名。 */
51
56
  export const APP_SETTING_KEYS = Object.freeze(PREF_KEYS.map((k) => 'app.' + k));
52
57
 
53
- const EMPTY = () => ({
58
+ /** 归一后的本机配置形状(文件 5 项 + settings 偏好)。 */
59
+ export interface AppConfig {
60
+ baseUrl: string;
61
+ token: string;
62
+ email: string;
63
+ userId: number;
64
+ groupId: number;
65
+ autoSyncAttachments: boolean;
66
+ attachmentsDir: string;
67
+ gitRepoRoot: string;
68
+ gitDevRoot: string;
69
+ }
70
+
71
+ const EMPTY = (): AppConfig => ({
54
72
  baseUrl: process.env.NX_KV_BASE_URL || DEFAULT_BASE_URL,
55
73
  token: '',
56
74
  email: '',
@@ -70,30 +88,31 @@ const EMPTY = () => ({
70
88
  gitDevRoot: '',
71
89
  });
72
90
 
73
- let cache = null;
91
+ let cache: AppConfig | null = null;
74
92
  let cacheMtime = -1;
75
93
 
76
94
  /** 全量归一(文件 5 项 + settings 偏好合并后跑一次,保证形状与类型稳定)。 */
77
- function normalize(data) {
95
+ function normalize(data: unknown): AppConfig {
78
96
  const base = EMPTY();
79
97
  if (!data || typeof data !== 'object') return base;
98
+ const d = data as Record<string, unknown>;
80
99
  return {
81
- baseUrl: String(data.baseUrl || base.baseUrl),
82
- token: String(data.token || ''),
83
- email: String(data.email || ''),
84
- userId: Number(data.userId) || 0,
85
- groupId: Number(data.groupId) || 0,
86
- autoSyncAttachments: data.autoSyncAttachments === true,
87
- attachmentsDir: String(data.attachmentsDir || ''),
88
- gitRepoRoot: String(data.gitRepoRoot || ''),
89
- gitDevRoot: String(data.gitDevRoot || ''),
100
+ baseUrl: String(d.baseUrl || base.baseUrl),
101
+ token: String(d.token || ''),
102
+ email: String(d.email || ''),
103
+ userId: Number(d.userId) || 0,
104
+ groupId: Number(d.groupId) || 0,
105
+ autoSyncAttachments: d.autoSyncAttachments === true,
106
+ attachmentsDir: String(d.attachmentsDir || ''),
107
+ gitRepoRoot: String(d.gitRepoRoot || ''),
108
+ gitDevRoot: String(d.gitDevRoot || ''),
90
109
  };
91
110
  }
92
111
 
93
112
  /** 从 settings 表读偏好(每次现读 —— 不缓存,跨进程改设置立刻可见)。 */
94
- function readPrefs() {
113
+ function readPrefs(): Record<string, unknown> {
95
114
  const db = openStore();
96
- const prefs = {};
115
+ const prefs: Record<string, unknown> = {};
97
116
  for (const key of APP_SETTING_KEYS) {
98
117
  const v = readSettingRaw(db, key);
99
118
  if (v !== undefined) prefs[key.slice('app.'.length)] = v;
@@ -102,7 +121,7 @@ function readPrefs() {
102
121
  }
103
122
 
104
123
  /** 把偏好写进 settings 表(一个事务;只写白名单里的字段)。 */
105
- function writePrefs(next) {
124
+ function writePrefs(next: AppConfig): void {
106
125
  const at = nowMs();
107
126
  tx(
108
127
  (conn) => {
@@ -111,13 +130,13 @@ function writePrefs(next) {
111
130
  writeSettingRaw(conn, 'app.' + k, next[k], at);
112
131
  }
113
132
  },
114
- { db: openStore(), mode: 'IMMEDIATE' }
133
+ { db: openStore(), mode: 'IMMEDIATE' },
115
134
  );
116
135
  }
117
136
 
118
- export async function loadConfig(explicitPath) {
137
+ export async function loadConfig(explicitPath?: string): Promise<AppConfig> {
119
138
  const p = explicitPath || configPathFromEnv();
120
- let filePart;
139
+ let filePart: AppConfig;
121
140
  try {
122
141
  const st = await fsp.stat(p);
123
142
  if (!(cache && cacheMtime === st.mtimeMs)) {
@@ -135,11 +154,11 @@ export async function loadConfig(explicitPath) {
135
154
  return normalize({ ...filePart, ...readPrefs() });
136
155
  }
137
156
 
138
- export async function saveConfig(next, explicitPath) {
157
+ export async function saveConfig(next: unknown, explicitPath?: string): Promise<AppConfig> {
139
158
  const full = normalize(next);
140
159
  // ① 文件:只写凭据白名单里的字段(**键集合精确等于 CREDENTIAL_KEYS** ——
141
160
  // 偏好进了 settings,再写回文件会让「凭据文件」再次长出业务配置)。
142
- const filePart = {};
161
+ const filePart: Record<string, unknown> = {};
143
162
  for (const k of CREDENTIAL_KEYS) filePart[k] = full[k];
144
163
  const p = explicitPath || configPathFromEnv();
145
164
  await fsp.mkdir(dirname(p), { recursive: true });
@@ -157,14 +176,14 @@ export async function saveConfig(next, explicitPath) {
157
176
  return full;
158
177
  }
159
178
 
160
- export async function updateConfig(patch) {
179
+ export async function updateConfig(patch: Partial<AppConfig>): Promise<AppConfig> {
161
180
  const cur = await loadConfig();
162
181
  return saveConfig({ ...cur, ...patch });
163
182
  }
164
183
 
165
184
  // 读配置并要求已登录。所有需要 token 的 action 都先过这里,
166
185
  // 报错文案里的「未登录」是 agent 的失败分类锚点(与 kvcli 保持一致)。
167
- export async function requireAuth() {
186
+ export async function requireAuth(): Promise<AppConfig> {
168
187
  const cfg = await loadConfig();
169
188
  if (!cfg.token) {
170
189
  throw badInput('未登录(先执行 nx-kv auth login <email>)');
@@ -173,7 +192,7 @@ export async function requireAuth() {
173
192
  }
174
193
 
175
194
  // groupId 归一:0 / 负数 / 空 → undefined(不传参,由后端回落默认组)
176
- export function normalizeGroupId(v) {
195
+ export function normalizeGroupId(v: unknown): number | undefined {
177
196
  const n = Number(v);
178
197
  return Number.isFinite(n) && n > 0 ? n : undefined;
179
198
  }
@@ -186,7 +205,7 @@ export function normalizeGroupId(v) {
186
205
  * file 拿它选后端分组与本地附件目录。两处各写一遍的话,一旦有人只改了一处,
187
206
  * 就会出现「从 A 组读任务、往 B 组同步附件」—— 这类错不报错,只是静默地对不上。
188
207
  */
189
- export async function resolveGroupId(groupId) {
208
+ export async function resolveGroupId(groupId: unknown): Promise<number | undefined> {
190
209
  if (groupId !== undefined && groupId !== null && groupId !== '') return normalizeGroupId(groupId);
191
210
  const cfg = await loadConfig();
192
211
  return normalizeGroupId(cfg.groupId);
@@ -17,3 +17,7 @@ process.on('warning', (w) => {
17
17
  const message = (w && w.message) || String(w);
18
18
  console.error(`${name}: ${message}`);
19
19
  });
20
+
21
+ // 让本文件成为 ES 模块(tsconfig 的 isolatedModules 要求每个文件都是模块;
22
+ // 副作用模块的标准写法——不导出任何值)。
23
+ export {};
@@ -26,10 +26,13 @@ export const CODES = {
26
26
  // 单独一个码的理由:迁移失败是"数据没进来、库已回滚"的可恢复状态,
27
27
  // 脚本要能把它与"参数错"区分开(迁移脚本会据此决定是重试还是报人)。
28
28
  STORE_MIGRATION_FAILED: 'STORE_MIGRATION_FAILED',
29
- };
29
+ } as const;
30
+
31
+ export type ErrorCode = (typeof CODES)[keyof typeof CODES];
30
32
 
31
- // code -> HTTP 状态。只在这里映射一次,api.js 不再自行判断。
32
- const HTTP_STATUS = {
33
+ // code -> HTTP 状态。只在这里映射一次,api.ts 不再自行判断。
34
+ // Record 穷尽性:新增错误码漏映射,编译期立即报错。
35
+ const HTTP_STATUS: Record<ErrorCode, number> = {
33
36
  [CODES.INVALID_INPUT]: 400,
34
37
  [CODES.NOT_FOUND]: 404,
35
38
  [CODES.CONFLICT]: 409,
@@ -41,7 +44,7 @@ const HTTP_STATUS = {
41
44
 
42
45
  // code -> 进程退出码。CLI 只区分「成功 / 失败」,保持 agent-workflow.md 声明的契约。
43
46
  // 例外:迁移失败 → 2(见上面的 CODES 注释)。
44
- const EXIT_CODE = {
47
+ const EXIT_CODE: Record<ErrorCode, number> = {
45
48
  [CODES.INVALID_INPUT]: 1,
46
49
  [CODES.NOT_FOUND]: 1,
47
50
  [CODES.CONFLICT]: 1,
@@ -51,38 +54,52 @@ const EXIT_CODE = {
51
54
  [CODES.STORE_MIGRATION_FAILED]: 2,
52
55
  };
53
56
 
57
+ export interface ErrorPayload {
58
+ code: ErrorCode;
59
+ message: string;
60
+ details?: unknown;
61
+ }
62
+
54
63
  export class AppError extends Error {
55
- constructor(code, message, details) {
64
+ code: ErrorCode;
65
+ details?: unknown;
66
+
67
+ constructor(code: ErrorCode, message: string, details?: unknown) {
56
68
  super(message);
57
69
  this.name = 'AppError';
58
- this.code = CODES[code] ? code : CODES.INTERNAL;
70
+ this.code = CODES[code as ErrorCode] ? (code as ErrorCode) : CODES.INTERNAL;
59
71
  if (details !== undefined) this.details = details;
60
72
  }
61
73
  }
62
74
 
63
- export function httpStatusOf(code) {
64
- return HTTP_STATUS[code] || 500;
75
+ export function httpStatusOf(code: ErrorCode): number {
76
+ return HTTP_STATUS[code] ?? 500;
65
77
  }
66
78
 
67
- export function exitCodeOf(code) {
68
- return EXIT_CODE[code] || 1;
79
+ export function exitCodeOf(code: ErrorCode): number {
80
+ return EXIT_CODE[code] ?? 1;
69
81
  }
70
82
 
71
83
  // 把任意抛出物归一成 { code, message, details },供 API / CLI 统一序列化。
72
84
  // 非 AppError 一律归为 INTERNAL——不把内部堆栈细节泄漏给 agent。
73
- export function toErrorPayload(err) {
85
+ export function toErrorPayload(err: unknown): ErrorPayload {
74
86
  if (err instanceof AppError) {
75
- const out = { code: err.code, message: err.message };
87
+ const out: ErrorPayload = { code: err.code, message: err.message };
76
88
  if (err.details !== undefined) out.details = err.details;
77
89
  return out;
78
90
  }
79
- return { code: CODES.INTERNAL, message: String((err && err.message) || err) };
91
+ return { code: CODES.INTERNAL, message: String((err as { message?: string } | null)?.message || err) };
80
92
  }
81
93
 
82
94
  // ---- 构造快捷方式:让 service 层读起来是「为什么失败」而不是「怎么构造」 ----
83
95
 
84
- export const badInput = (message, details) => new AppError(CODES.INVALID_INPUT, message, details);
85
- export const notFound = (message, details) => new AppError(CODES.NOT_FOUND, message, details);
86
- export const conflict = (message, details) => new AppError(CODES.CONFLICT, message, details);
87
- export const blocked = (message, details) => new AppError(CODES.BLOCKED, message, details);
88
- export const external = (message, details) => new AppError(CODES.EXTERNAL, message, details);
96
+ export const badInput = (message: string, details?: unknown): AppError =>
97
+ new AppError(CODES.INVALID_INPUT, message, details);
98
+ export const notFound = (message: string, details?: unknown): AppError =>
99
+ new AppError(CODES.NOT_FOUND, message, details);
100
+ export const conflict = (message: string, details?: unknown): AppError =>
101
+ new AppError(CODES.CONFLICT, message, details);
102
+ export const blocked = (message: string, details?: unknown): AppError =>
103
+ new AppError(CODES.BLOCKED, message, details);
104
+ export const external = (message: string, details?: unknown): AppError =>
105
+ new AppError(CODES.EXTERNAL, message, details);
@@ -2,7 +2,7 @@
2
2
  // 零业务语义,且刻意不抛错——打不开就算了,调用方已经打印了地址。
3
3
  import { spawn } from 'node:child_process';
4
4
 
5
- function open(target) {
5
+ function open(target: string): void {
6
6
  try {
7
7
  const plat = process.platform;
8
8
  if (plat === 'win32') {
@@ -17,10 +17,10 @@ function open(target) {
17
17
  }
18
18
  }
19
19
 
20
- export function openBrowser(url) {
20
+ export function openBrowser(url: string): void {
21
21
  open(url);
22
22
  }
23
23
 
24
- export function openPath(dir) {
24
+ export function openPath(dir: string): void {
25
25
  open(dir);
26
26
  }
@@ -15,12 +15,18 @@ export const STORE_PATH = join(APP_DIR, 'store.json');
15
15
  // 就是最典型的"静默读写错库"。
16
16
  export const DB_FILE_NAME = 'nxkv.db';
17
17
 
18
+ /** 库落点:path 是库文件,appDir 是 legacy JSON 导入的扫描根(跟着目录走)。 */
19
+ export interface StoreTarget {
20
+ path: string;
21
+ appDir: string;
22
+ }
23
+
18
24
  // 库路径解析(唯一权威)。除了显式 NX_KV_DB,还会回落到各域 legacy env 的
19
25
  // 目录(repos / localtask 的 JSON 时代隔离约定)—— T06 起 config 偏好与队列级
20
26
  // timegoal 都进同一份库,core 层的默认打开(getDb / openStore 无参)必须与
21
27
  // 域仓储的解析落在同一个文件上,否则就是「读路径静默换库」(T05 的教训)。
22
28
  // appDir 是 legacy JSON 导入的扫描根,跟着目录走。
23
- export function defaultStoreTarget() {
29
+ export function defaultStoreTarget(): StoreTarget {
24
30
  const explicit = process.env.NX_KV_DB;
25
31
  if (explicit) return { path: explicit, appDir: APP_DIR };
26
32
  // 只保留两个**活**的测试隔离 env(localtask / repos 的 open.js 映射机制);
@@ -35,11 +41,11 @@ export function defaultStoreTarget() {
35
41
  return { path: join(APP_DIR, DB_FILE_NAME), appDir: APP_DIR };
36
42
  }
37
43
 
38
- export function dbPathFromEnv() {
44
+ export function dbPathFromEnv(): string {
39
45
  return defaultStoreTarget().path;
40
46
  }
41
47
  // 备份目录(VACUUM INTO 落这里;保留最近 5 份)
42
- export function backupsDirFromEnv() {
48
+ export function backupsDirFromEnv(): string {
43
49
  return process.env.NX_KV_BACKUPS || join(APP_DIR, 'backups');
44
50
  }
45
51
 
@@ -50,24 +56,24 @@ export const DEFAULT_PORT = 7877;
50
56
  export const ATTACHMENTS_DIR = join(APP_DIR, 'attachments');
51
57
 
52
58
  // 允许测试与多实例覆盖存储位置:NX_KV_STORE 环境变量优先
53
- export function storePathFromEnv() {
59
+ export function storePathFromEnv(): string {
54
60
  return process.env.NX_KV_STORE || STORE_PATH;
55
61
  }
56
62
 
57
63
  // 允许测试与多实例覆盖附件目录:NX_KV_ATTACHMENTS 环境变量优先
58
- export function attachmentsRootFromEnv() {
64
+ export function attachmentsRootFromEnv(): string {
59
65
  return process.env.NX_KV_ATTACHMENTS || ATTACHMENTS_DIR;
60
66
  }
61
67
 
62
- // 名称安全校验:拒绝路径穿越(保留中文等合法命名,与 fileops.go 语义一致)。
68
+ // 名称安全校验:拒绝路径穿越(保留中文等合法命名)。
63
69
  //
64
70
  // 用于「这个字符串会被用作**目录名**」的场景:skill 名、内置包名、适配器 id。
65
71
  // 因此拒绝前导点——避免意外生成隐藏目录。
66
72
  // 注意:文件路径不要用这个,用下面的 assertSafeRelPath——像 .gitignore 这样的
67
73
  // 文件名是合法且常见的,用名称规则去卡它会把正常文件挡在门外。
68
- export function assertSafeName(name, label = 'skill 名称') {
74
+ export function assertSafeName(name: unknown, label = 'skill 名称'): string {
69
75
  if (!name || typeof name !== 'string' || /[\\/]/.test(name) || name.includes('..') || name.startsWith('.')) {
70
- throw badInput('非法 ' + label + ': ' + name);
76
+ throw badInput('非法 ' + label + ': ' + String(name));
71
77
  }
72
78
  return name;
73
79
  }
@@ -78,7 +84,10 @@ export function assertSafeName(name, label = 'skill 名称') {
78
84
  // 同一类输入校验强度不一致,本身就是可乘之口。
79
85
  //
80
86
  // 返回**归一化后**的路径(折叠重复分隔符、去掉 './' 段),调用方应使用返回值。
81
- export function assertSafeRelPath(input, { label = '文件路径', allowSubdir = true } = {}) {
87
+ export function assertSafeRelPath(
88
+ input: unknown,
89
+ { label = '文件路径', allowSubdir = true }: { label?: string; allowSubdir?: boolean } = {},
90
+ ): string {
82
91
  if (!input || typeof input !== 'string') throw badInput(label + '不能为空');
83
92
  if (/^([a-zA-Z]:|[\\/])/.test(input)) throw badInput(label + '必须是相对路径: ' + input);
84
93