nx-kv 0.51.0 → 0.52.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 (81) hide show
  1. package/CHANGELOG.md +29 -0
  2. package/package.json +2 -1
  3. package/src/core/contract-snapshot.ts +24 -0
  4. package/src/core/contract-types.ts +106 -0
  5. package/src/modules/localtask/actions/localtask-list.ts +39 -0
  6. package/src/modules/system/actions/_manifest.generated.ts +3 -0
  7. package/src/modules/system/actions/bootstrap.ts +25 -0
  8. package/src/modules/system/actions/contract.ts +58 -0
  9. package/src/runtime/action-decorator.ts +20 -2
  10. package/src/runtime/contract.ts +66 -0
  11. package/src/runtime/dartgen.ts +347 -0
  12. package/src/runtime/registry.ts +17 -0
  13. package/src/runtime/zod-bridge.ts +101 -17
  14. package/src/web/frontend/App.tsx +15 -12
  15. package/src/web/frontend/api/cli-tree.json +14 -0
  16. package/src/web/frontend/api/client.generated.ts +8 -0
  17. package/src/web/frontend/components/layout/breadcrumb.tsx +44 -35
  18. package/src/web/frontend/components/layout/crumbs.ts +60 -0
  19. package/src/web/frontend/components/md/doc-keys.ts +53 -0
  20. package/src/web/frontend/components/md/md-panes-root.tsx +9 -2
  21. package/src/web/frontend/components/sidebar/index.tsx +99 -9
  22. package/src/web/frontend/components/sidebar/model.ts +18 -4
  23. package/src/web/frontend/components/sidebar/row-menu.tsx +9 -40
  24. package/src/web/frontend/components/toast/index.tsx +46 -3
  25. package/src/web/frontend/page/dir/task-actions.ts +20 -2
  26. package/src/web/frontend/page/doc/index.tsx +36 -12
  27. package/src/web/frontend/repo-data.ts +49 -0
  28. package/src/web/frontend/styles/repos.css +9 -2
  29. package/src/web/frontend/styles-v2/dag.css +12 -5
  30. package/src/web/public/assets/app-context-B0QwHGOd.js +1 -0
  31. package/src/web/public/assets/{bar-DoW8R6oG.js → bar-Di7RK1fB.js} +1 -1
  32. package/src/web/public/assets/{board-view-aAIEbSQi.js → board-view-BJCwrtHc.js} +1 -1
  33. package/src/web/public/assets/{composer-launch-CAe2Kg7t.js → composer-launch-yGr4Ayzx.js} +1 -1
  34. package/src/web/public/assets/{composer-panel-BnzPY41l.js → composer-panel-U2jaQLVQ.js} +1 -1
  35. package/src/web/public/assets/{dag-Gm4RcvEg.js → dag-DISpxumr.js} +1 -1
  36. package/src/web/public/assets/dir-BY5ibEGY.js +3 -0
  37. package/src/web/public/assets/doc-DHi__8Em.js +6 -0
  38. package/src/web/public/assets/frontmatter-b044qTyx.js +2 -0
  39. package/src/web/public/assets/group-mIIARpRB.js +1 -0
  40. package/src/web/public/assets/index-DiOQ8kPZ.js +2 -0
  41. package/src/web/public/assets/index-j44oS8Y3.css +1 -0
  42. package/src/web/public/assets/md-history-wRTMWb12.js +39 -0
  43. package/src/web/public/assets/{md-parse-CLyUaUto.js → md-parse-Bqb35k5w.js} +1 -1
  44. package/src/web/public/assets/{member-picker-XT12VRe6.js → member-picker-CQksP35E.js} +1 -1
  45. package/src/web/public/assets/model-lEeblPg0.js +2 -0
  46. package/src/web/public/assets/overview-DPDbuE5d.js +1 -0
  47. package/src/web/public/assets/{progress-CNam3Wuj.js → progress-BRSLsiPg.js} +2 -2
  48. package/src/web/public/assets/refs-CZdjVlxE.js +2 -0
  49. package/src/web/public/assets/repo-form-modal-dO99i73A.js +1 -0
  50. package/src/web/public/assets/repos-BaE9B1it.js +14 -0
  51. package/src/web/public/assets/route-crumb-BHZU-2HE.js +1 -0
  52. package/src/web/public/assets/{settings-DcpAnoPP.js → settings-BX78BaLf.js} +2 -2
  53. package/src/web/public/assets/status-tag-DC7mdpkI.js +1 -0
  54. package/src/web/public/assets/task-Cxa641GX.js +11 -0
  55. package/src/web/public/assets/task-row-3OXcmAJb.js +1 -0
  56. package/src/web/public/assets/{task-utils-DabL4pWl.js → task-utils-DSZKkq5e.js} +1 -1
  57. package/src/web/public/assets/{templates-B5C-04px.js → templates-CExLUDs6.js} +1 -1
  58. package/src/web/public/assets/{use-rail-drag-DWh_6gVG.js → use-rail-drag-D-17tqYm.js} +1 -1
  59. package/src/web/public/assets/{workspace-D_G-B3TX.js → workspace-fCTiC3R4.js} +1 -1
  60. package/src/web/public/index.html +18 -10
  61. package/src/web/public/assets/Introduction-Cd1EVmLJ.js +0 -6
  62. package/src/web/public/assets/app-context-BgpTewyA.js +0 -1
  63. package/src/web/public/assets/button-xyR2UROd.js +0 -1
  64. package/src/web/public/assets/dir-DOmboUMw.js +0 -3
  65. package/src/web/public/assets/group-CRy-GSr6.js +0 -1
  66. package/src/web/public/assets/index-CUigrOD7.js +0 -2
  67. package/src/web/public/assets/index-DAz3Dlo_.css +0 -1
  68. package/src/web/public/assets/md-history-B7SCKnJP.js +0 -39
  69. package/src/web/public/assets/model-CWJ8_2dN.js +0 -2
  70. package/src/web/public/assets/overview-Y4aroMeW.js +0 -1
  71. package/src/web/public/assets/refs-BUfvLix6.js +0 -2
  72. package/src/web/public/assets/repos-B098Pmd4.js +0 -14
  73. package/src/web/public/assets/route-crumb-DynMISE4.js +0 -1
  74. package/src/web/public/assets/status-tag-nNyC3U7Q.js +0 -1
  75. package/src/web/public/assets/task-93mVhj0L.js +0 -11
  76. package/src/web/public/assets/task-row-Bsptt2zF.js +0 -1
  77. package/src/web/public/assets/task-status-BHF-y9Aq.js +0 -2
  78. package/src/web/public/assets/ui-Y0aL-bGk.js +0 -1
  79. /package/src/web/public/assets/{Introduction-Iuxssa-b.css → doc-Iuxssa-b.css} +0 -0
  80. /package/src/web/public/assets/{task-status-BZrdOH46.css → frontmatter-BZrdOH46.css} +0 -0
  81. /package/src/web/public/assets/{button-DA4lNJeC.css → repo-form-modal-DA4lNJeC.css} +0 -0
@@ -0,0 +1,347 @@
1
+ // Dart 发射器:契约快照 → 零依赖 Dart 包。
2
+ //
3
+ // 只认 IR(contract.ts 的 ContractSnapshot),不 import zod——这样 zod 内部结构
4
+ // 变化不会波及生成器,生成的产物也能靠 JSON 快照独立复现。
5
+ //
6
+ // 三条刻意的取舍:
7
+ // 1. **零依赖**:包只有 dart:core(+ 需要序列化数组入参时 dart:convert),
8
+ // 传输层由调用方注入(fr 侧塞 MnWsAppClient,自带应用前缀与设备令牌)。
9
+ // 2. **只做反序列化**:端侧是消费者,不需要 toJson。少一半代码、少一半漂移面。
10
+ // 3. **信封只拆一次**:`{ok,data}` / `{ok,error}` 的拆解写死在生成物里,
11
+ // 调用方永远拿强类型对象,也永远不需要知道 nx-kv 的信封长什么样。
12
+
13
+ import type { ContractSnapshot } from './contract.js';
14
+ import type { FieldDesc, TypeNode } from './zod-bridge.js';
15
+
16
+ /** Dart 保留字(参数名撞上就得加后缀)。 */
17
+ const DART_KEYWORDS = new Set([
18
+ 'abstract', 'as', 'assert', 'async', 'await', 'break', 'case', 'catch', 'class', 'const',
19
+ 'continue', 'covariant', 'default', 'deferred', 'do', 'dynamic', 'else', 'enum', 'export',
20
+ 'extends', 'extension', 'external', 'factory', 'false', 'final', 'finally', 'for', 'function',
21
+ 'get', 'hide', 'if', 'implements', 'import', 'in', 'interface', 'is', 'late', 'library',
22
+ 'mixin', 'new', 'null', 'on', 'operator', 'part', 'required', 'rethrow', 'return', 'set',
23
+ 'show', 'static', 'super', 'switch', 'sync', 'this', 'throw', 'true', 'try', 'typedef', 'var',
24
+ 'void', 'while', 'with', 'yield',
25
+ ]);
26
+
27
+ const camel = (s: string): string => s.replace(/[-_](\w)/g, (_m, c: string) => c.toUpperCase());
28
+ const lowerFirst = (s: string): string => s.charAt(0).toLowerCase() + s.slice(1);
29
+ const dartName = (s: string): string => {
30
+ const n = lowerFirst(camel(s));
31
+ return DART_KEYWORDS.has(n) ? n + 'Value' : n;
32
+ };
33
+ const docComment = (text: string | undefined, indent: string): string[] =>
34
+ text ? [`${indent}/// ${text.replace(/\s+/g, ' ')}`] : [];
35
+
36
+ /** 收集树里所有模型 / 枚举(同名同形只留一份;同名不同形在 describeOutput 已拦)。 */
37
+ function collect(output: TypeNode, models: Map<string, TypeNode & { k: 'model' }>, enums: Map<string, string[]>): void {
38
+ switch (output.k) {
39
+ case 'model':
40
+ if (models.has(output.name)) return;
41
+ models.set(output.name, output);
42
+ for (const f of output.fields) collect(f.type, models, enums);
43
+ return;
44
+ case 'enum':
45
+ enums.set(output.name, output.values);
46
+ return;
47
+ case 'list':
48
+ case 'map':
49
+ collect(output.of, models, enums);
50
+ return;
51
+ default:
52
+ return;
53
+ }
54
+ }
55
+
56
+ /** Dart 类型名 */
57
+ function dartType(t: TypeNode): string {
58
+ switch (t.k) {
59
+ case 'string':
60
+ return 'String';
61
+ case 'int':
62
+ return 'int';
63
+ case 'number':
64
+ return 'num';
65
+ case 'bool':
66
+ return 'bool';
67
+ case 'unknown':
68
+ return 'dynamic';
69
+ case 'enum':
70
+ case 'model':
71
+ return t.name;
72
+ case 'list':
73
+ return `List<${dartType(t.of)}>`;
74
+ case 'map':
75
+ return `Map<String, ${dartType(t.of)}>`;
76
+ }
77
+ }
78
+
79
+ /** 把 `src` 处的值读成目标类型(递归) */
80
+ function readExpr(t: TypeNode, src: string): string {
81
+ switch (t.k) {
82
+ case 'string':
83
+ return `${src} as String`;
84
+ case 'int':
85
+ return `(${src} as num).toInt()`;
86
+ case 'number':
87
+ return `${src} as num`;
88
+ case 'bool':
89
+ return `${src} as bool`;
90
+ case 'unknown':
91
+ return src;
92
+ case 'enum':
93
+ return `${t.name}.values.byName(${src} as String)`;
94
+ case 'model':
95
+ return `${t.name}.fromJson(${src} as Map<String, dynamic>)`;
96
+ case 'list':
97
+ return `(${src} as List).map<${dartType(t.of)}>((e) => ${readExpr(t.of, 'e')}).toList()`;
98
+ case 'map':
99
+ return `(${src} as Map).map<String, ${dartType(t.of)}>((k, v) => MapEntry(k as String, ${readExpr(t.of, 'v')}))`;
100
+ }
101
+ }
102
+
103
+ function emitEnums(enums: Map<string, string[]>): string {
104
+ const out: string[] = [];
105
+ for (const [name, values] of enums) {
106
+ for (const v of values) {
107
+ if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(v)) {
108
+ throw new Error(
109
+ `枚举 ${name} 的值 ${JSON.stringify(v)} 不是合法 Dart 标识符;` +
110
+ '要么改取值,要么给这个 action 换个出参(生成器不做改名映射,改名会静默漂移)',
111
+ );
112
+ }
113
+ }
114
+ out.push(`/// 取值:${values.join(' / ')}\nenum ${name} { ${values.join(', ')} }`);
115
+ }
116
+ return out.join('\n\n');
117
+ }
118
+
119
+ function emitModel(model: TypeNode & { k: 'model' }): string {
120
+ const fields = model.fields;
121
+ const lines: string[] = [];
122
+ lines.push(`class ${model.name} {`);
123
+ const ctorArgs = fields
124
+ .map((f) => `${f.required ? 'required ' : ''}this.${dartName(f.name)}`)
125
+ .join(', ');
126
+ lines.push(` const ${model.name}({${ctorArgs}});`);
127
+ lines.push('');
128
+ for (const f of fields) {
129
+ lines.push(...docComment(f.hint, ' '));
130
+ lines.push(` final ${dartType(f.type)}${f.required ? '' : '?'} ${dartName(f.name)};`);
131
+ }
132
+ lines.push('');
133
+ lines.push(` factory ${model.name}.fromJson(Map<String, dynamic> json) => ${model.name}(`);
134
+ for (const f of fields) {
135
+ const key = `json['${f.name}']`;
136
+ const expr = readExpr(f.type, key);
137
+ lines.push(` ${dartName(f.name)}: ${f.required ? expr : `${key} == null ? null : ${expr}`},`);
138
+ }
139
+ lines.push(' );');
140
+ lines.push('}');
141
+ return lines.join('\n');
142
+ }
143
+
144
+ /** 入参字段 → Dart 形参(GET 走 query,其余走 JSON body) */
145
+ function paramOf(f: FieldDesc): string {
146
+ const type =
147
+ f.kind === 'number'
148
+ ? 'num'
149
+ : f.kind === 'boolean'
150
+ ? 'bool'
151
+ : f.kind === 'array'
152
+ ? 'List<String>'
153
+ : f.kind === 'kv' || f.kind === 'raw'
154
+ ? 'Map<String, dynamic>'
155
+ : f.kind === 'enum'
156
+ ? 'String'
157
+ : 'String';
158
+ return `${f.required ? 'required ' : ''}${type}${f.required ? '' : '?'} ${dartName(f.name)}`;
159
+ }
160
+
161
+ function methodNameOf(id: string, used: Set<string>): string {
162
+ const parts = id.split('.');
163
+ // 用**整条 id** 取名(localtask.list → localtaskList):只取末段会让
164
+ // localtask.list 与 docs.list 都叫 list,端侧天天撞名(设计里已把这条写成硬规则)
165
+ const base = lowerFirst(camel(parts.join('-')));
166
+ let name = base;
167
+ if (used.has(name)) {
168
+ const module = parts.length > 1 ? lowerFirst(camel(parts[parts.length - 2]!)) : 'action';
169
+ name = `${module}${base.charAt(0).toUpperCase()}${base.slice(1)}`;
170
+ }
171
+ let n = 2;
172
+ while (used.has(name)) name = `${base}${n++}`;
173
+ used.add(name);
174
+ return name;
175
+ }
176
+
177
+ /** Dart 包的文件集合(相对 contract/dart/ 的路径 → 内容)。 */
178
+ export function emitDartPackage(snapshot: ContractSnapshot): Record<string, string> {
179
+ const models = new Map<string, TypeNode & { k: 'model' }>();
180
+ const enums = new Map<string, string[]>();
181
+ for (const a of snapshot.actions) collect(a.output, models, enums);
182
+
183
+ const pkg = snapshot.app.replace(/[^a-z0-9]+/gi, '_').toLowerCase() + '_client';
184
+ const rootModels = new Map(snapshot.actions.map((a) => [a.id, a.output] as const));
185
+
186
+ // ---- models.dart ----
187
+ const modelSrc = [
188
+ '// GENERATED by nx-kv scripts/gen-dart-client.mjs —— 勿手改。',
189
+ `// 契约指纹:${snapshot.hash}(nx-kv ${snapshot.version})`,
190
+ '',
191
+ '// ignore_for_file: unnecessary_cast',
192
+ '',
193
+ emitEnums(enums),
194
+ [...models.values()].map(emitModel).join('\n\n'),
195
+ ]
196
+ .filter((s) => s !== '')
197
+ .join('\n') + '\n';
198
+
199
+ // ---- api.dart ----
200
+ const used = new Set<string>();
201
+ const methodLines: string[] = [];
202
+ for (const a of snapshot.actions) {
203
+ const root = rootModels.get(a.id)!;
204
+ if (root.k !== 'model') throw new Error(`action ${a.id} 的出参不是模型`);
205
+ const [method, path] = (a.http ?? 'GET ').split(' ') as [string, string];
206
+ const params = a.input.map(paramOf).join(', ');
207
+ const isGet = method === 'GET' || method === 'HEAD';
208
+ const body = isGet ? 'null' : bodyMap(a.input);
209
+ const query = isGet ? queryMap(a.input) : 'const <String, String>{}';
210
+ methodLines.push(
211
+ [
212
+ ...docComment(a.summary, ' '),
213
+ ` /// action: ${a.id} · 认证/前缀由注入的 transport 负责`,
214
+ ` Future<${root.name}> ${methodNameOf(a.id, used)}(${params}) async {`,
215
+ ` final query = ${query};`,
216
+ ` final body = ${body};`,
217
+ ` final data = _unwrap(await _send('${method}', '${path}', query, body));`,
218
+ ` return ${root.name}.fromJson(data);`,
219
+ ' }',
220
+ ].join('\n'),
221
+ );
222
+ }
223
+
224
+ const needsConvert = snapshot.actions.some(
225
+ (a) => (a.http ?? 'GET').startsWith('GET') && a.input.some((f) => f.kind === 'array' || f.kind === 'kv'),
226
+ );
227
+
228
+ const apiSrc = [
229
+ '// GENERATED by nx-kv scripts/gen-dart-client.mjs —— 勿手改。',
230
+ `// 契约指纹:${snapshot.hash}(nx-kv ${snapshot.version})`,
231
+ '',
232
+ needsConvert ? "import 'dart:convert';" : '',
233
+ "import 'models.dart';",
234
+ '',
235
+ '// 指纹对不上就是「端侧跑在旧契约上」的硬信号:拿它跟 GET /api/contract 的 hash 比。',
236
+ `const String contractHash = '${snapshot.hash}';`,
237
+ `const String contractVersion = '${snapshot.version}';`,
238
+ '',
239
+ '/// 传输层契约(由调用方注入):返回**完整信封**(`{ok,data}` / `{ok,error}`)的 JSON。',
240
+ '///',
241
+ '/// fr 侧的实现只有一行:把 method/path/query/body 交给 MnWsAppClient,应用前缀与',
242
+ '/// 设备令牌都由它负责——生成物不知道 nx-kv 挂在哪、也不需要知道。',
243
+ 'typedef NxKvTransport = Future<dynamic> Function(',
244
+ ' String method,',
245
+ ' String path,',
246
+ ' Map<String, String> query,',
247
+ ' Object? body,',
248
+ ');',
249
+ '',
250
+ '/// 服务端信封里的业务错误。',
251
+ 'class NxKvApiException implements Exception {',
252
+ ' NxKvApiException(this.message);',
253
+ '',
254
+ ' final String message;',
255
+ '',
256
+ ' @override',
257
+ ' String toString() => \'NxKvApiException: $message\';',
258
+ '}',
259
+ '',
260
+ 'Map<String, dynamic> _unwrap(dynamic raw) {',
261
+ ' if (raw is! Map) throw NxKvApiException(\'响应不是 JSON 对象:$raw\');',
262
+ ' if (raw[\'ok\'] != true) throw NxKvApiException(\'\${raw["error"] ?? raw}\');',
263
+ ' final data = raw[\'data\'];',
264
+ ' if (data is! Map) throw NxKvApiException(\'data 不是对象:$data\');',
265
+ ' return data.cast<String, dynamic>();',
266
+ '}',
267
+ '',
268
+ `class ${pascalOf(pkg)}Api {`,
269
+ ` ${pascalOf(pkg)}Api(this._send);`,
270
+ '',
271
+ ' final NxKvTransport _send;',
272
+ '',
273
+ methodLines.join('\n\n'),
274
+ '}',
275
+ '',
276
+ ].join('\n');
277
+
278
+ const entry = [
279
+ '// GENERATED by nx-kv scripts/gen-dart-client.mjs —— 勿手改。',
280
+ "export 'src/api.dart';",
281
+ "export 'src/models.dart';",
282
+ '',
283
+ ].join('\n');
284
+
285
+ return {
286
+ // pubspec 的 description 只能是 ASCII —— 不是洁癖,是踩出来的:
287
+ // pub 读 **git 源**的 pubspec 时按系统 ANSI 码页解码(Windows 中文 = GBK),
288
+ // UTF-8 的多字节尾巴会把行尾 `\n` 一起吃进残缺的 GBK 字符里,于是
289
+ // description 与 version 被拼成一行,报「Mapping values are not allowed here」,
290
+ // 而错误信息指向的是 version 的冒号 —— 看着像缩进问题。
291
+ // 同一个包用 path 引入却完全正常(path 源走 UTF-8 读),所以这个坑只在
292
+ // 「锁 sha 的 git 依赖」这条真实消费路径上出现。
293
+ 'pubspec.yaml': [
294
+ `name: ${pkg}`,
295
+ `description: nx-kv contract client (${snapshot.hash}) - generated, zero deps.`,
296
+ `version: ${snapshot.version}`,
297
+ 'publish_to: none',
298
+ 'environment:',
299
+ " sdk: '>=3.0.0 <4.0.0'",
300
+ '',
301
+ ].join('\n'),
302
+ '.gitignore': [
303
+ '# 生成器不产这两样;它们属于消费者,入库只会打架',
304
+ '.dart_tool/',
305
+ 'pubspec.lock',
306
+ '',
307
+ ].join('\n'),
308
+ 'lib/nx_kv_client.dart': entry,
309
+ 'lib/src/models.dart': modelSrc,
310
+ 'lib/src/api.dart': apiSrc,
311
+ };
312
+ }
313
+
314
+ function queryMap(input: FieldDesc[]): string {
315
+ if (!input.length) return 'const <String, String>{}';
316
+ const lines = input.map((f) => {
317
+ const v = dartName(f.name);
318
+ if (f.kind === 'array') {
319
+ return ` if (${v} != null) '${f.name}': (${v} as List).join(','),`;
320
+ }
321
+ if (f.kind === 'kv' || f.kind === 'raw') {
322
+ return ` if (${v} != null) '${f.name}': jsonEncode(${v}),`;
323
+ }
324
+ // 生成 Dart 的 '${x}' 插值:这里用拼接写,避免在模板串里嵌套插值把自己绕晕
325
+ return ' if (' + v + " != null) '" + f.name + "': '${" + v + "}',";
326
+ });
327
+ return ['<String, String>{', ...lines, ' }'].join('\n');
328
+ }
329
+
330
+ function bodyMap(input: FieldDesc[]): string {
331
+ if (!input.length) return 'const <String, dynamic>{}';
332
+ const lines = input.map((f) => {
333
+ const v = dartName(f.name);
334
+ return f.required
335
+ ? ` '${f.name}': ${v},`
336
+ : ` if (${v} != null) '${f.name}': ${v},`;
337
+ });
338
+ return ['<String, dynamic>{', ...lines, ' }'].join('\n');
339
+ }
340
+
341
+ function pascalOf(s: string): string {
342
+ return s
343
+ .split(/[_\-]+/)
344
+ .filter(Boolean)
345
+ .map((p) => p.charAt(0).toUpperCase() + p.slice(1))
346
+ .join('');
347
+ }
@@ -21,6 +21,10 @@
21
21
  import { ModuleBase, type AnyModule } from './types/module.js';
22
22
  import { cliPathsOf, entryOf, type AnyAction } from './spec.js';
23
23
  import { publishCommandTable } from '../core/command-table.js';
24
+ import { publishContractSnapshot } from '../core/contract-snapshot.js';
25
+ import { buildContractSnapshot } from './contract.js';
26
+ import type { ZodBoundAction } from './action-decorator.js';
27
+ import { readFileSync } from 'node:fs';
24
28
  import systemModule from '../modules/system/index.js';
25
29
  import setting from '../modules/setting/index.js';
26
30
  import localtask from '../modules/localtask/index.js';
@@ -129,6 +133,19 @@ export const ACTIONS = registry.actions;
129
133
  // 这类平台命令),所以「从 CLI 跑」拿到的是完整表,纯 HTTP 场景拿到的是 action 表。
130
134
  publishCommandTable(ACTIONS.map(entryOf));
131
135
 
136
+ // 契约快照:只在启动期算一次,模块侧(system.contract)只读这份。
137
+ // 与命令表同理——registry → modules → 想读契约的 action → registry 会成环,
138
+ // 快照把环断开;契约在装配后不再变化,所以「读快照」没有时效问题。
139
+ const VERSION: string = JSON.parse(
140
+ readFileSync(new URL('../../package.json', import.meta.url), 'utf8'),
141
+ ).version;
142
+ publishContractSnapshot(
143
+ buildContractSnapshot(
144
+ ACTIONS.filter((a) => Array.isArray((a as Partial<ZodBoundAction>).fields)) as unknown as ZodBoundAction[],
145
+ { app: 'nx-kv', version: VERSION },
146
+ ),
147
+ );
148
+
132
149
  // ModuleBase 仅为类型连贯在此重导出:模块作者从 types/module.js 拿基类,
133
150
  // runtime 侧不主动扩散它。
134
151
  export { ModuleBase };
@@ -21,25 +21,15 @@
21
21
  // 「用法:」前缀是**对外契约**:assets 文档教 agent 用错误文本里的「用法:」判定
22
22
  // 参数错误,不得丢。
23
23
  import { badInput } from '../core/errors.js';
24
+ import type { FieldDesc, ModelField, TypeNode } from '../core/contract-types.js';
24
25
  import type { ZodType } from 'zod';
25
26
 
26
- export type FieldKind = 'string' | 'number' | 'boolean' | 'enum' | 'array' | 'kv' | 'raw';
27
-
28
- export interface FieldDesc {
29
- name: string;
30
- kind: FieldKind;
31
- /** 位置参数(按 args 顺序消费 argv),其余是 --flag */
32
- positional: boolean;
33
- /** 没有 default 且非 optional → 必填 */
34
- required: boolean;
35
- default?: unknown;
36
- enumValues?: string[];
37
- /**
38
- * 字段说明(zod 的 .describe(),迁移自 legacy flags 的 hint)。
39
- * 用法串里拿它当值占位符——help 因此仍然说人话,而不是 `--module <string>`。
40
- */
41
- hint?: string;
42
- }
27
+ // 契约的数据形状统一由 core 定义(模块要读快照,而模块够不着 runtime);
28
+ // 这里只负责「zod → 那些形状」的转换,并把类型再导出一次给 runtime 内部用。
29
+ export type { FieldDesc, ModelField, TypeNode };
30
+
31
+ /** 入参字段的 kind(形状定义在 core/contract-types.ts,这里只取别名)。 */
32
+ export type FieldKind = FieldDesc['kind'];
43
33
 
44
34
  interface Unwrapped {
45
35
  inner: unknown;
@@ -210,3 +200,97 @@ export function parseZodInput(input: ZodType, values: Record<string, unknown>, u
210
200
  .join(';');
211
201
  throw badInput(`用法: ${usage} —— 参数不合法: ${issues}`);
212
202
  }
203
+
204
+ // ─────────────────────────── 出参(跨语言契约) ───────────────────────────
205
+ //
206
+ // 入参只需要「字段 + kind」这张扁平的说明(CLI/HTTP 归一化够用);出参要生成别的
207
+ // 语言的**类型**,所以必须是**递归结构**:模型里嵌模型、数组里有模型。
208
+ //
209
+ // 这份 IR 是 JSON 安全的(就是 contract.json 里 output 字段的形状),
210
+ // 生成器只认它、不再碰 zod——契约快照因此可以入库对账、可以给端侧当版本号。
211
+
212
+ const pascal = (s: string): string => {
213
+ const camel = s.replace(/[-_](\w)/g, (_m, c: string) => c.toUpperCase());
214
+ return camel.charAt(0).toUpperCase() + camel.slice(1);
215
+ };
216
+
217
+ /** topics → Topic(数组元素命名用;短词不动,避免 'as' → 'a' 这种自伤) */
218
+ const singular = (s: string): string => (s.length > 3 && s.endsWith('s') ? s.slice(0, -1) : s);
219
+
220
+ /**
221
+ * 把出参 schema 拆成递归类型树。
222
+ *
223
+ * 命名规则(固化成规则表,不做「智能猜测」):
224
+ * - 根模型 = 调用方给的 rootName(如 `LocaltaskListOutput`)
225
+ * - 子模型 = 根名去掉 `Output` 后缀 + 字段名的 Pascal 形式
226
+ * (`LocaltaskListOutput` 的 `settings` → `LocaltaskListSettings`)
227
+ * - 数组元素 = 同上,但字段名取单数(`topics` → `LocaltaskListTopic`)
228
+ * - **同名不同形直接抛错**:生成器不猜、也不加数字后缀糊过去——
229
+ * 真发生了说明命名该改,静默改名只会让端侧类型漂移得莫名其妙。
230
+ */
231
+ export function describeOutput(output: ZodType, rootName: string): TypeNode {
232
+ const seen = new Map<string, string>();
233
+ const claim = (name: string, node: TypeNode): TypeNode => {
234
+ const sig = JSON.stringify(node);
235
+ const prev = seen.get(name);
236
+ if (prev !== undefined && prev !== sig) {
237
+ throw new Error(
238
+ `出参模型名冲突:${name} 有两种不同形状。改字段名或显式拆模型,别让生成器猜。`,
239
+ );
240
+ }
241
+ seen.set(name, sig);
242
+ return node;
243
+ };
244
+
245
+ const walk = (schema: unknown, name: string): TypeNode => {
246
+ const { inner } = unwrap(schema);
247
+ const def = (inner as { _zod?: { def?: Record<string, unknown> } })?._zod?.def;
248
+ const tag = def?.type as string | undefined;
249
+ switch (tag) {
250
+ case 'string':
251
+ return { k: 'string' };
252
+ case 'number':
253
+ // z.int() 与 z.number() 在 zod v4 里同 tag,靠 format 区分
254
+ return def?.format === 'safeint' ? { k: 'int' } : { k: 'number' };
255
+ case 'boolean':
256
+ return { k: 'bool' };
257
+ case 'enum': {
258
+ const values = Object.values((def?.entries ?? {}) as Record<string, string>);
259
+ return claim(name, { k: 'enum', name, values });
260
+ }
261
+ case 'literal': {
262
+ const values = ((def?.values ?? []) as unknown[]).map((v) => String(v));
263
+ return claim(name, { k: 'enum', name, values });
264
+ }
265
+ case 'array':
266
+ // 名字由调用方按「字段名单数化」算好(topics → LocaltaskListTopic),这里原样往下传
267
+ return { k: 'list', of: walk(def?.element, name) };
268
+ case 'record':
269
+ return { k: 'map', of: walk(def?.valueType, name + 'Value') };
270
+ case 'object': {
271
+ const base = name.replace(/Output$/, '');
272
+ const shape = (def?.shape ?? {}) as Record<string, unknown>;
273
+ const fields: ModelField[] = Object.entries(shape).map(([fname, fs]) => {
274
+ const u = unwrap(fs);
275
+ const required = !u.optional && u.defaultValue === undefined;
276
+ const hint = hintOf(fs) || hintOf(u.inner);
277
+ // 数组字段的元素名取单数:topics → LocaltaskListTopic(而不是 …TopicsItem)
278
+ const isList =
279
+ (u.inner as { _zod?: { def?: { type?: string } } })?._zod?.def?.type === 'array';
280
+ const childName = base + pascal(isList ? singular(fname) : fname);
281
+ return { name: fname, required, type: walk(fs, childName), ...(hint ? { hint } : {}) };
282
+ });
283
+ return claim(name, { k: 'model', name, fields });
284
+ }
285
+ default:
286
+ // date / union / unknown / any …:Dart 侧给 dynamic,不装作知道形状
287
+ return { k: 'unknown' };
288
+ }
289
+ };
290
+
291
+ const node = walk(output, rootName);
292
+ if (node.k !== 'model') {
293
+ throw new Error(`出参必须是 z.object({...}) 收口(收到 ${node.k})——端侧根类型得是个模型`);
294
+ }
295
+ return node;
296
+ }
@@ -43,6 +43,7 @@ import { useTemplates } from './modules/md/use-templates.js';
43
43
  import { findGroupTask } from './modules/board/board-view.js';
44
44
  import { installAttachmentPreview } from './modules/md/lightbox.js';
45
45
  import { loadPrefs, updatePrefs } from './prefs.js';
46
+ import { nextRepoData } from './repo-data.js';
46
47
  import SidebarRescueFab from './components/sidebar/rescue-fab.jsx';
47
48
  import { pushRoute } from './components/layout/route-history.js';
48
49
  import type { AppRoute, BoardRow, LocaltasksData, LocalTask, LocalTopic, Prefs, RepoData, RepoRow, SpecCtx } from './types.js';
@@ -218,20 +219,22 @@ export default function App() {
218
219
  }, [refreshLocal]);
219
220
 
220
221
  // ─── 仓库与看板:侧栏的**唯一数据源** ───
222
+ //
223
+ // 两份清单**各自成败**(#194):原先是 `Promise.all` + 一次 setState,任一份失败
224
+ // (某个仓库目录读盘报错让 /api/repos 500、慢盘上扫 31 个仓库的 git 超时……)
225
+ // 两半一起被丢弃,repoData 退回初始空值 → 侧栏树整块消失变空白;此后新建项目组
226
+ // 虽然建成功,刷新仍走这条注定失败的路径,树始终是空的。
227
+ // 现在成功的一半立刻生效,失败的一半保留旧值——树最少「不倒退」。
221
228
  const [repoData, setRepoData] = useState<RepoData>({ repos: [], boards: [] });
222
229
  const refreshRepos = useCallback(async () => {
223
- try {
224
- const [repos, boards] = await Promise.all([
225
- api<RepoRow[]>('/api/repos'),
226
- api<{ boards?: RepoData['boards'] }>('/api/boards'),
227
- ]);
228
- setRepoData({
229
- repos: (repos || []).filter((r) => (r.type || 'dev') !== 'ref'), // 参考仓库不进侧栏
230
- boards: (boards && boards.boards) || [],
231
- });
232
- } catch {
233
- /* 读失败:保留旧数据,侧栏仍可用 */
234
- }
230
+ const [rRes, bRes] = await Promise.allSettled([
231
+ api<RepoRow[]>('/api/repos'),
232
+ api<{ boards?: RepoData['boards'] }>('/api/boards'),
233
+ ]);
234
+ setRepoData((prev) => nextRepoData(prev, {
235
+ repos: rRes.status === 'fulfilled' ? rRes.value : undefined,
236
+ boards: bRes.status === 'fulfilled' ? bRes.value : undefined,
237
+ }));
235
238
  }, []);
236
239
  useEffect(() => {
237
240
  refreshRepos();
@@ -17,6 +17,20 @@
17
17
  },
18
18
  "children": []
19
19
  },
20
+ {
21
+ "name": "contract",
22
+ "path": [
23
+ "contract"
24
+ ],
25
+ "action": {
26
+ "id": "system.contract",
27
+ "module": "system",
28
+ "summary": "契约快照:带 output 的 action + 指纹(端侧据此对账自己是不是旧契约)",
29
+ "usage": "contract",
30
+ "http": "GET /api/contract"
31
+ },
32
+ "children": []
33
+ },
20
34
  {
21
35
  "name": "health",
22
36
  "path": [
@@ -120,6 +120,7 @@ import type {
120
120
  } from '../../../modules/setting/actions/_manifest.generated.js';
121
121
  import type {
122
122
  BootstrapAction,
123
+ ContractAction,
123
124
  HealthAction,
124
125
  } from '../../../modules/system/actions/_manifest.generated.js';
125
126
  import type {
@@ -148,6 +149,8 @@ export interface Transport {
148
149
  export interface ApiClient {
149
150
  /** 聚合上下文:版本 / 命令表 */
150
151
  bootstrap(): Promise<Awaited<ReturnType<InstanceType<typeof BootstrapAction>['run']>>>;
152
+ /** 契约快照:带 output 的 action + 指纹(端侧据此对账自己是不是旧契约) */
153
+ contract(): Promise<Awaited<ReturnType<InstanceType<typeof ContractAction>['run']>>>;
151
154
  /** 健康检查(纯本机) */
152
155
  health(): Promise<Awaited<ReturnType<InstanceType<typeof HealthAction>['run']>>>;
153
156
  /** 读本机设置(附件自动下载、附件目录、参考仓库存储根) */
@@ -385,6 +388,11 @@ export function createApiClient(transport: Transport): ApiClient {
385
388
  const path = `/api/bootstrap`;
386
389
  return (await transport.request("GET", path)) as Awaited<ReturnType<InstanceType<typeof BootstrapAction>['run']>>;
387
390
  },
391
+ // action: system.contract
392
+ async contract() {
393
+ const path = `/api/contract`;
394
+ return (await transport.request("GET", path)) as Awaited<ReturnType<InstanceType<typeof ContractAction>['run']>>;
395
+ },
388
396
  // action: system.health
389
397
  async health() {
390
398
  const path = `/api/health`;