soma-kit 0.1.4 → 0.1.6

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "soma-kit",
3
- "version": "0.1.4",
3
+ "version": "0.1.6",
4
4
  "description": "SOMA 第三条 UI 路线:写死模板与规则,DSL 显式传入,基础组件 + 数据组件",
5
5
  "type": "module",
6
6
  "exports": {
@@ -45,11 +45,8 @@
45
45
  "dependencies": {
46
46
  "jiti": "1.21.7",
47
47
  "js-yaml": "4.3.2",
48
- "next": "16.4.1",
49
- "react": "18.3.1",
50
- "react-dom": "18.3.1",
51
- "soma-core": "^2.1.5",
52
- "soma-foundation": "^0.1.1",
48
+ "soma-core": "^2.2.0",
49
+ "soma-foundation": "^0.1.2",
53
50
  "tailwindcss": "^4.1.0"
54
51
  },
55
52
  "devDependencies": {
@@ -122,17 +122,40 @@ export function registerKitAppEnvelopeFromYaml(appYamlText: string): void {
122
122
  appEnvelope = env;
123
123
  }
124
124
 
125
- /** 把有效信封编进一份 core 数据声明(`data:` 段):写通道与取数来源各加 failWhen / messagePath,已自带的不覆盖 */
125
+ /**
126
+ * 拼装业务信封子路径(纯函数):
127
+ * - 若 dataPath === undefined || dataPath === '',返回 subPath;
128
+ * - 若 subPath === '',返回 dataPath;
129
+ * - 向后兼容守卫:若 subPath === dataPath || subPath.startsWith(`${dataPath}.`),直接返回 subPath(避免重复拼成 data.data.rows);
130
+ * - 否则返回 `${dataPath}.${subPath}`。
131
+ */
132
+ export function resolveEnvelopeSubPath(subPath: string, dataPath?: string): string {
133
+ if (dataPath === undefined || dataPath === '') return subPath;
134
+ if (subPath === '') return dataPath;
135
+ if (subPath === dataPath || subPath.startsWith(`${dataPath}.`)) return subPath;
136
+ return `${dataPath}.${subPath}`;
137
+ }
138
+
139
+ /** 把有效信封编进一份 core 数据声明(`data:` 段):写通道与取数来源各加 failWhen / messagePath,单对象取数来源补 dataPath,已自带的不覆盖 */
126
140
  export function applyEnvelopeToData(data: Record<string, unknown>, env: KitEnvelope | undefined): void {
127
- if (env?.failWhen === undefined) return;
141
+ if (env === undefined || (env.failWhen === undefined && env.dataPath === undefined)) return;
128
142
  for (const decl of Object.values(data)) {
129
143
  if (!isRec(decl)) continue;
130
144
  const stamp = (target: Rec): void => {
131
- if (target.failWhen !== undefined) return;
132
- target.failWhen = env.failWhen;
133
- if (env.messagePath !== undefined) target.messagePath = env.messagePath;
145
+ if (env.failWhen !== undefined && target.failWhen === undefined) {
146
+ target.failWhen = env.failWhen;
147
+ if (env.messagePath !== undefined) target.messagePath = env.messagePath;
148
+ }
134
149
  };
135
150
  if (isRec(decl.write)) stamp(decl.write);
136
- if (Array.isArray(decl.from)) for (const source of decl.from) if (isRec(source)) stamp(source);
151
+ if (Array.isArray(decl.from)) {
152
+ for (const source of decl.from) {
153
+ if (!isRec(source)) continue;
154
+ stamp(source);
155
+ if (env.dataPath !== undefined && source.into === undefined && source.dataPath === undefined) {
156
+ source.dataPath = env.dataPath;
157
+ }
158
+ }
159
+ }
137
160
  }
138
161
  }
@@ -54,8 +54,9 @@ export function createKitNotifyRenderer(): NotifyRenderer {
54
54
  show(entry) {
55
55
  const host = ensure();
56
56
  if (host === undefined) return { dismiss() {} };
57
+ const level: NotifyEntry['level'] = (entry.level as string) === 'danger' ? 'error' : entry.level;
57
58
  const item = document.createElement('div');
58
- item.className = `${ITEM_BASE} ${LEVEL_CLASS[entry.level] ?? LEVEL_CLASS.info}`;
59
+ item.className = `${ITEM_BASE} ${LEVEL_CLASS[level] ?? LEVEL_CLASS.info}`;
59
60
  const body = document.createElement('div');
60
61
  body.className = BODY_CLASS;
61
62
  if (entry.title !== undefined && entry.title !== '') {
@@ -67,7 +68,7 @@ export function createKitNotifyRenderer(): NotifyRenderer {
67
68
  const m = document.createElement('div');
68
69
  m.textContent = entry.message;
69
70
  body.appendChild(m);
70
- item.append(kitIcon(LEVEL_ICON[entry.level] ?? 'info', 'md', ICON_CLASS), body);
71
+ item.append(kitIcon(LEVEL_ICON[level] ?? 'info', 'md', ICON_CLASS), body);
71
72
  let timer: ReturnType<typeof setTimeout> | undefined;
72
73
  const dismiss = (): void => {
73
74
  if (timer !== undefined) clearTimeout(timer);
@@ -87,7 +88,7 @@ export function createKitNotifyRenderer(): NotifyRenderer {
87
88
  host.appendChild(item);
88
89
  // duration 为 0 = 常驻(手动关闭);NaN / 负数 / 非数字按级别默认时长
89
90
  const d = entry.duration;
90
- const ms = typeof d === 'number' && Number.isFinite(d) && d >= 0 ? d : (DEFAULT_DURATION_MS[entry.level] ?? 3000);
91
+ const ms = typeof d === 'number' && Number.isFinite(d) && d >= 0 ? d : (DEFAULT_DURATION_MS[level] ?? 3000);
91
92
  if (ms > 0) timer = setTimeout(dismiss, ms);
92
93
  return { dismiss };
93
94
  },
package/src/app/server.ts CHANGED
@@ -2,6 +2,7 @@
2
2
  // 只在服务端 / build 面可达;node 内置模块与 core 服务端子路径全部动态 import,并带 webpackIgnore,
3
3
  // 即便 defineKitApp 的惰性 import 被打进浏览器包图,也不会在解析期报错。
4
4
 
5
+ import { createHash } from 'node:crypto';
5
6
  import { KIT_BASE_COMPONENTS } from '../base/index';
6
7
  import { KIT_STATIC_BUILTIN_SPECS } from '../data/static-registry';
7
8
  import { compileKitPage } from '../compile/compile-page';
@@ -19,6 +20,64 @@ import { KIT_PAGE_OWNER, createKitServerPages } from './server-pages';
19
20
  import type { KitServerPages } from './submit.types';
20
21
 
21
22
  export const KIT_OWNER = KIT_PAGE_OWNER;
23
+ export const KIT_GRAMMAR_VERSION = '0.1.0';
24
+ export const MAX_KIT_PAGE_CACHE = 256;
25
+
26
+ const kitPageCompileCache = new Map<string, KitPageArtifact>();
27
+
28
+ /** 清空页面编译产物缓存(供测试或热重载) */
29
+ export function clearKitPageCompileCache(): void {
30
+ kitPageCompileCache.clear();
31
+ }
32
+
33
+ /** 获取当前页面编译产物缓存条目数(供测试断言) */
34
+ export function getKitPageCompileCacheSize(): number {
35
+ return kitPageCompileCache.size;
36
+ }
37
+
38
+ /** 计算确定性输入指纹 */
39
+ export function computeKitPageCacheKey(
40
+ yamlText: string,
41
+ declaredUrl: string,
42
+ appContext: KitAppContext,
43
+ ): string {
44
+ return createHash('sha256')
45
+ .update(KIT_GRAMMAR_VERSION)
46
+ .update('\0')
47
+ .update(appContext.themeTokensCss ?? '')
48
+ .update('\0')
49
+ .update(appContext.themeCss)
50
+ .update('\0')
51
+ .update(JSON.stringify(appContext.envelope ?? null))
52
+ .update('\0')
53
+ .update(JSON.stringify(appContext.locales ?? null))
54
+ .update('\0')
55
+ .update((appContext.appCandidates ?? []).join('\0'))
56
+ .update('\0')
57
+ .update(declaredUrl)
58
+ .update('\0')
59
+ .update(yamlText)
60
+ .digest('hex');
61
+ }
62
+
63
+ function cloneKitPageArtifact(artifact: KitPageArtifact): KitPageArtifact {
64
+ return {
65
+ url: artifact.url,
66
+ html: artifact.html,
67
+ uiYaml: artifact.uiYaml,
68
+ eventYaml: artifact.eventYaml,
69
+ styles: artifact.styles.map((s) => ({ ...s })),
70
+ version: artifact.version,
71
+ };
72
+ }
73
+
74
+ function deepFreezeKitPageArtifact(artifact: KitPageArtifact): KitPageArtifact {
75
+ for (const s of artifact.styles) {
76
+ Object.freeze(s);
77
+ }
78
+ Object.freeze(artifact.styles);
79
+ return Object.freeze(artifact);
80
+ }
22
81
 
23
82
  export class KitAppAssemblyError extends Error {
24
83
  readonly diagnostics: KitDiagnostic[];
@@ -142,6 +201,14 @@ export async function assembleKitServer(options: DefineKitAppOptions, registry:
142
201
  }
143
202
  }
144
203
 
204
+ // 共享样式引擎实例:未传 options.styleEngine 时持有一个共享实例挂在 appContext.styleEngine 上
205
+ const customStyleEngine = (options as { styleEngine?: import('soma-core/server/style-engine').SomaStyleEngine }).styleEngine;
206
+ let sharedStyleEngine = customStyleEngine;
207
+ if (sharedStyleEngine === undefined) {
208
+ const { createStyleEnginePort } = await import('soma-core/server/style-engine');
209
+ sharedStyleEngine = createStyleEnginePort();
210
+ }
211
+
145
212
  // 业务信封约定:编译期编进 core 数据声明,服务端薄壳(分页适配等)缺省读同一份
146
213
  setKitAppEnvelope(config.envelope);
147
214
  const appContext: KitAppContext = {
@@ -157,6 +224,7 @@ export async function assembleKitServer(options: DefineKitAppOptions, registry:
157
224
  bizComponents: registry.bizComponents,
158
225
  frames: registry.frames,
159
226
  appCandidates: registry.appCandidates,
227
+ styleEngine: sharedStyleEngine,
160
228
  componentDefinitions: {
161
229
  ...registry.baseComponents,
162
230
  ...Object.fromEntries(Object.entries(registry.staticComponents).map(([n, e]) => [n, e.definition])),
@@ -177,25 +245,56 @@ export async function assembleKitServer(options: DefineKitAppOptions, registry:
177
245
  }
178
246
  const artifacts = new Map<string, KitPageArtifact>();
179
247
  const failures: KitDiagnostic[] = [];
248
+ const isCustomStyleEngine = customStyleEngine !== undefined;
249
+
180
250
  for (const { dir, file: name } of pageFiles) {
181
251
  const file = dir === pageDirs[0] ? name : `${path.relative(root, path.join(dir, name)) || name}`;
182
252
  const text = await fs.readFile(path.join(dir, name), 'utf8');
183
- const res = await compileKitPage(text, appContext);
184
- if (res.artifact === undefined || res.diagnostics.length > 0) {
185
- const locate = createYamlLocator(text);
186
- failures.push(...res.diagnostics.map((d) => {
187
- const pos = locate(d.path);
188
- return { ...d, path: `${file}:${d.path}`, file, ...(pos ? { line: pos.line, column: pos.column } : {}) };
189
- }));
190
- // 没产物又没诊断也是失败:不许静默吞掉一页
191
- if (res.diagnostics.length === 0) failures.push({ code: 'KIT-PAGE-004', path: file, message: '页面没有产出产物,也没有给出诊断' });
192
- continue;
253
+
254
+ let artifact: KitPageArtifact | undefined;
255
+ const urlMatch = /^\s*url:\s*['"]?([^\s'"#]+)['"]?/m.exec(text);
256
+ const declaredUrl = urlMatch ? urlMatch[1] : '';
257
+ const cacheKey = !isCustomStyleEngine
258
+ ? computeKitPageCacheKey(text, declaredUrl, appContext)
259
+ : undefined;
260
+
261
+ if (cacheKey !== undefined) {
262
+ const cached = kitPageCompileCache.get(cacheKey);
263
+ if (cached !== undefined) {
264
+ kitPageCompileCache.delete(cacheKey);
265
+ kitPageCompileCache.set(cacheKey, cached);
266
+ artifact = deepFreezeKitPageArtifact(cloneKitPageArtifact(cached));
267
+ }
268
+ }
269
+
270
+ if (artifact === undefined) {
271
+ const res = await compileKitPage(text, appContext);
272
+ if (res.artifact === undefined || res.diagnostics.length > 0) {
273
+ const locate = createYamlLocator(text);
274
+ failures.push(...res.diagnostics.map((d) => {
275
+ const pos = locate(d.path);
276
+ return { ...d, path: `${file}:${d.path}`, file, ...(pos ? { line: pos.line, column: pos.column } : {}) };
277
+ }));
278
+ // 没产物又没诊断也是失败:不许静默吞掉一页
279
+ if (res.diagnostics.length === 0) failures.push({ code: 'KIT-PAGE-004', path: file, message: '页面没有产出产物,也没有给出诊断' });
280
+ continue;
281
+ }
282
+ artifact = res.artifact;
283
+ if (cacheKey !== undefined) {
284
+ while (kitPageCompileCache.size >= MAX_KIT_PAGE_CACHE) {
285
+ const oldest = kitPageCompileCache.keys().next().value;
286
+ if (oldest !== undefined) kitPageCompileCache.delete(oldest);
287
+ else break;
288
+ }
289
+ kitPageCompileCache.set(cacheKey, cloneKitPageArtifact(artifact));
290
+ }
193
291
  }
194
- if (artifacts.has(res.artifact.url)) {
195
- failures.push({ code: 'KIT-PAGE-004', path: file, message: `页面地址 ${res.artifact.url} 重复` });
292
+
293
+ if (artifacts.has(artifact.url)) {
294
+ failures.push({ code: 'KIT-PAGE-004', path: file, message: `页面地址 ${artifact.url} 重复` });
196
295
  continue;
197
296
  }
198
- artifacts.set(res.artifact.url, res.artifact);
297
+ artifacts.set(artifact.url, artifact);
199
298
  }
200
299
  if (failures.length > 0) throw new KitAppAssemblyError('页面编译失败,拒绝启动', failures);
201
300
 
@@ -23,7 +23,7 @@ import { safeHref } from '../../base/link';
23
23
  import { closeKitHub, hasKitHub, kitActionExtras } from './runtime-hub';
24
24
  import { readKitStepValues } from './step-values';
25
25
  import { askKitPrompt } from '../../data/prompt-dialog';
26
- import { setKitAppEnvelope, type KitEnvelope } from '../../app/envelope';
26
+ import { setKitAppEnvelope, getKitAppEnvelope, resolveEnvelopeSubPath, type KitEnvelope } from '../../app/envelope';
27
27
  import { draftFieldsOfBody, recordKitOutcomeDraft } from '../../object-renderer/outcome-draft';
28
28
  import { kitText } from '../../i18n/kit-text';
29
29
  import { KIT_GRAMMAR } from '../../object-renderer/defaults';
@@ -299,11 +299,14 @@ export function createKitActionHost(): SomaComponentDefinition {
299
299
  }
300
300
  // 拆分(into.keyBy):整次请求的状态落合成对象名(不可见),成功后由 core 把列表按项落成 <名字>#<键值> 的按行结果
301
301
  let split: Record<string, unknown> | undefined;
302
+ let splitPath = '';
302
303
  if (spec.splitBy !== undefined) {
303
304
  outcomeScope = spec.writeObject;
304
305
  const env = rec(props().envelope);
306
+ const dataPath = typeof env.dataPath === 'string' ? env.dataPath : getKitAppEnvelope()?.dataPath;
307
+ splitPath = resolveEnvelopeSubPath(spec.splitBy.path, dataPath);
305
308
  split = {
306
- path: spec.splitBy.path, key: spec.splitBy.key, prefix: spec.outcome, separator: OUTCOME_KEY_SEP,
309
+ path: splitPath, key: spec.splitBy.key, prefix: spec.outcome, separator: OUTCOME_KEY_SEP,
307
310
  ...(env.failWhen !== undefined ? { failWhen: env.failWhen } : {}),
308
311
  ...(typeof env.messagePath === 'string' ? { messagePath: env.messagePath } : {}),
309
312
  };
@@ -330,7 +333,7 @@ export function createKitActionHost(): SomaComponentDefinition {
330
333
  let message = view.message;
331
334
  let ok = view.status === 'saved';
332
335
  // 拆分:响应体里取不到列表(接口形状不对)按请求失败,不假装拆出了结果
333
- if (ok && spec.splitBy !== undefined && !Array.isArray(walk(rec(view.result).data, spec.splitBy.path.split('.')))) {
336
+ if (ok && spec.splitBy !== undefined && !Array.isArray(walk(rec(view.result).data, splitPath.split('.')))) {
334
337
  ok = false;
335
338
  message = kitText('soma.kit.request_failed', undefined, ctx.host);
336
339
  }
@@ -57,9 +57,11 @@ import { classesInHtml } from '../object-renderer/candidates';
57
57
  import { checkClasses } from '../object-renderer/merge-class';
58
58
  import { KIT_TABLE_ACTIONS_CLASS_CANDIDATES } from '../object-renderer/table-actions';
59
59
  import { KIT_COLLECTION_STATE_CLASS_CANDIDATES, KIT_TABLE_HEAD_CLASS_CANDIDATES } from '../object-renderer/collection-parts';
60
- import { KIT_TABLE_TOOLS_CLASS_CANDIDATES } from '../object-renderer/table-tools';import type { KitDiagnostic } from '../object-renderer/types';
60
+ import { KIT_TABLE_TOOLS_CLASS_CANDIDATES } from '../object-renderer/table-tools';
61
+ import type { KitDiagnostic } from '../object-renderer/types';
61
62
  import { wrappedCandidateSource } from '../data/wrapped-candidates';
62
63
  import type { SomaComponentDefinition } from 'soma-core';
64
+ import type { SomaStyleEngine } from 'soma-core/server/style-engine';
63
65
  import type { KitFragment } from './fragment';
64
66
  import type { KitAppContext } from './types';
65
67
 
@@ -218,6 +220,13 @@ const MARKER_CLASS = /^(group|peer)(\/[A-Za-z0-9_-]+)?$/;
218
220
  /** 块级主题的作用域类(theme/block-theme.ts 写在块根上):它是令牌变量块的选择器,不是工具类,不交样式引擎 */
219
221
  const SCOPE_CLASS = /^soma-scope-[a-z0-9]+(?:-[a-z0-9]+)*$/;
220
222
 
223
+ let defaultStyleEngine: SomaStyleEngine | undefined;
224
+
225
+ /** 清除默认样式引擎实例(供测试重置) */
226
+ export function clearDefaultStyleEngine(): void {
227
+ defaultStyleEngine = undefined;
228
+ }
229
+
221
230
  /** 候选类是否放行:方括号任意值与主题头里没有的键一律不放行(同对象渲染内核的 KIT-STYLE-001 口径) */
222
231
  export function allowCandidate(candidate: string): boolean {
223
232
  return checkClasses(candidate, '').length === 0;
@@ -227,8 +236,11 @@ export function allowCandidate(candidate: string): boolean {
227
236
  export async function compileStyles(candidates: readonly string[], app: KitAppContext, blockThemeCss = ''): Promise<KitStyleResult> {
228
237
  let engine = app.styleEngine;
229
238
  if (engine === undefined) {
230
- const mod = await import('soma-core/server/style-engine');
231
- engine = mod.createStyleEnginePort();
239
+ if (defaultStyleEngine === undefined) {
240
+ const mod = await import('soma-core/server/style-engine');
241
+ defaultStyleEngine = mod.createStyleEnginePort();
242
+ }
243
+ engine = defaultStyleEngine;
232
244
  }
233
245
  // group / peer(含具名 group/x、peer/x)只是变体锚点标记,本身不产生任何样式规则;
234
246
  // 它们留在 HTML 上给 group-hover: / peer-checked: 等变体用,不交样式引擎(否则按 no-rule 拒收)。
@@ -27,7 +27,7 @@ import { KIT_BUSY_PROP_DEFS, cancelKitAction, isKitActionBusy, isKitActionCancel
27
27
  import { holds } from '../object-renderer/linkage';
28
28
  import { adoptPlan, gateOutcomeNames, gateReason, sameValue, type KitAdoptDecl, type KitAdoptPlan, type KitGateDecl } from '../object-renderer/adopt-gate';
29
29
  import { watchKitOutcome, type KitOutcome } from './outcome-watch';
30
- import { fetchRemoteOptionRows } from './remote-options';
30
+ import { fetchRemoteOptionRows, rowsOfOptionsResponse } from './remote-options';
31
31
  import { clearStaleFlowSelections, clearStaleRowSelections, flowOptionSlots, flowOptionsOfRows, rowColumnSlots, ROW_COLUMN_SLOT_TYPE, withFlowOptions, withRowColumnOptions, type FlowOptionResolved, type FlowOptionSlot } from './flow-remote-options';
32
32
  import { evalActionGate, gateFrom, gateOutcomeNamesOf } from '../base/action-gate';
33
33
  import { asyncResultOf, outcomePanelData } from './async-result-panel';
@@ -1071,24 +1071,6 @@ function createController(
1071
1071
  };
1072
1072
 
1073
1073
  // ── 远程选项(options.from):经 services.http 取,依赖字段变化清值并重取 ──
1074
- const pickPath = (root: unknown, path: string): unknown => {
1075
- let cur: unknown = root;
1076
- for (const seg of path.split('.')) {
1077
- if (!isRec(cur)) return undefined;
1078
- cur = cur[seg];
1079
- }
1080
- return cur;
1081
- };
1082
- const rowsOfResponse = (res: unknown, rowsPath: string): Rec[] => {
1083
- if (Array.isArray(res)) return res.filter(isRec);
1084
- for (const p of rowsPath !== '' ? [rowsPath] : FL.optionsFrom.rowsPathCandidates) {
1085
- const direct = pickPath(res, p);
1086
- if (Array.isArray(direct)) return direct.filter(isRec);
1087
- const wrapped = pickPath(pickPath(res, 'data'), p);
1088
- if (Array.isArray(wrapped)) return wrapped.filter(isRec);
1089
- }
1090
- return [];
1091
- };
1092
1074
  /** 选项源请求计划;params 里的 { steps: 's0.字段' }(GB1)先换成该步已确认的值,值为空等同依赖字段为空(不发请求) */
1093
1075
  const planFor = (of: NonNullable<KitCell['optionsFrom']>, vals: Rec): ReturnType<typeof planOptionSourceRequest> => {
1094
1076
  if (hasStepParams(of.params)) {
@@ -1129,7 +1111,7 @@ function createController(
1129
1111
  const api = baseURL !== '' && baseURL !== '/' && of.from.startsWith(`${baseURL}/`) ? of.from.slice(baseURL.length) : of.from;
1130
1112
  void http.get<unknown>(api, { params }).then((res) => {
1131
1113
  if (!alive || st.seq !== mine) return;
1132
- st.rows = rowsOfResponse(res, of.rowsPath);
1114
+ st.rows = rowsOfOptionsResponse(res, of.rowsPath);
1133
1115
  repaint();
1134
1116
  }).catch(() => {
1135
1117
  if (!alive || st.seq !== mine) return;
@@ -1247,7 +1229,7 @@ function createController(
1247
1229
  (st.children ??= new Map<string, Rec[]>()).set(cascadeKey(path), rows);
1248
1230
  repaint();
1249
1231
  };
1250
- void http.get<unknown>(api, { params }).then((res) => store(rowsOfResponse(res, of.rowsPath))).catch(() => store([]));
1232
+ void http.get<unknown>(api, { params }).then((res) => store(rowsOfOptionsResponse(res, of.rowsPath))).catch(() => store([]));
1251
1233
  };
1252
1234
 
1253
1235
  const buildRows = (): KitFormRow[] => {
@@ -4,6 +4,7 @@
4
4
  // 失败照实 reject(调用方显示『选项加载失败』),不吞成空列表。
5
5
 
6
6
  import { KIT_FORM_LINKAGE } from '../object-renderer/defaults';
7
+ import { unwrapEnvelope, envelopeMessage, getKitAppEnvelope, type KitEnvelope } from '../app/envelope';
7
8
 
8
9
  type Rec = Record<string, unknown>;
9
10
  type Json = Record<string, any>;
@@ -21,15 +22,34 @@ function pickPath(root: unknown, path: string): unknown {
21
22
  return cur;
22
23
  }
23
24
 
24
- /** 响应体 -> 候选行数组(响应本身是数组、或在 rowsPath / 候选路径下、或再包一层 data) */
25
- export function rowsOfOptionsResponse(res: unknown, rowsPath: string): Rec[] {
26
- if (Array.isArray(res)) return res.filter(isRec);
27
- for (const p of rowsPath !== '' ? [rowsPath] : CANDIDATES) {
28
- const direct = pickPath(res, p);
25
+ /** 响应体 -> 候选行数组(拆信封,命中业务失败则抛错;成功在 unwrapped.data 或原响应上查找数组) */
26
+ export function rowsOfOptionsResponse(res: unknown, rowsPath: string, env: KitEnvelope | undefined = getKitAppEnvelope()): Rec[] {
27
+ const unwrapped = unwrapEnvelope(res, env);
28
+ if (!unwrapped.ok) {
29
+ const msg = envelopeMessage(res, env) || '选项加载失败';
30
+ throw new Error(msg);
31
+ }
32
+ const payload = unwrapped.data;
33
+ if (Array.isArray(payload)) return payload.filter(isRec);
34
+
35
+ const paths = rowsPath !== '' ? [rowsPath] : CANDIDATES;
36
+ for (const p of paths) {
37
+ const direct = pickPath(payload, p);
29
38
  if (Array.isArray(direct)) return direct.filter(isRec);
30
- const wrapped = pickPath(pickPath(res, 'data'), p);
39
+ const wrapped = pickPath(pickPath(payload, 'data'), p);
31
40
  if (Array.isArray(wrapped)) return wrapped.filter(isRec);
32
41
  }
42
+
43
+ // 兼容存量已写 rowsPath: 'data.rows' 的情况:在 unwrapped.data 找不到时再回退试原始 res
44
+ if (payload !== res) {
45
+ for (const p of paths) {
46
+ const direct = pickPath(res, p);
47
+ if (Array.isArray(direct)) return direct.filter(isRec);
48
+ const wrapped = pickPath(pickPath(res, 'data'), p);
49
+ if (Array.isArray(wrapped)) return wrapped.filter(isRec);
50
+ }
51
+ }
52
+
33
53
  return [];
34
54
  }
35
55
 
@@ -27,6 +27,7 @@ import { kitIcon } from '../base/icons';
27
27
  import { KIT_TREE_TABLE } from '../object-renderer/defaults';
28
28
  import { ACTION_BUTTON_CLASS } from '../object-renderer/table-actions';
29
29
  import { provideCtxRows } from './context-menu';
30
+ import { unwrapEnvelope, envelopeMessage, getKitAppEnvelope } from '../app/envelope';
30
31
 
31
32
  // ── 类串表(整串字面量;候选类汇总在底部) ──
32
33
 
@@ -395,8 +396,24 @@ export function createKitTreeTable(): SomaComponentDefinition {
395
396
  const baseURL = typeof rawBase === 'string' ? rawBase.replace(/\/+$/, '') : '/api';
396
397
  const apiPath = baseURL && baseURL !== '/' && from.api.startsWith(`${baseURL}/`) ? from.api.slice(baseURL.length) : from.api;
397
398
  const res = await http.get<unknown>(apiPath, { params: { [from.param]: node.key } });
398
- const direct = pickPath(res, from.rows);
399
- const list = Array.isArray(direct) ? direct : pickPath(pickPath(res, 'data'), from.rows);
399
+ const unwrapped = unwrapEnvelope(res, getKitAppEnvelope());
400
+ if (!unwrapped.ok) throw new Error(envelopeMessage(res, getKitAppEnvelope()) || '加载子行失败');
401
+ const payload = unwrapped.data;
402
+ let list: unknown;
403
+ if (Array.isArray(payload)) {
404
+ list = payload;
405
+ } else {
406
+ const p1 = pickPath(payload, from.rows);
407
+ if (Array.isArray(p1)) {
408
+ list = p1;
409
+ } else if (from.rows === 'result.rows' && Array.isArray(pickPath(payload, 'rows'))) {
410
+ list = pickPath(payload, 'rows');
411
+ } else if (Array.isArray(pickPath(res, from.rows))) {
412
+ list = pickPath(res, from.rows);
413
+ } else {
414
+ list = pickPath(pickPath(res, 'data'), from.rows);
415
+ }
416
+ }
400
417
  loaded.set(node.key, Array.isArray(list) ? list.filter(isRec) : []);
401
418
  rebuild();
402
419
  open.add(node.key);
@@ -12,6 +12,7 @@
12
12
 
13
13
  import { regionMirrorStatePath } from 'soma-core';
14
14
  import type { SomaScopeDecl, SomaScopeMirrorDecl, SomaScopeSliceDecl } from 'soma-core';
15
+ import { getCompileEnvelope, resolveEnvelopeSubPath } from '../app/envelope';
15
16
  import { KIT_CORE_MAPPING, KIT_FORM_LINKAGE, KIT_GRAMMAR } from './defaults';
16
17
  import { predicateToCore, staticOptionsOf } from './linkage';
17
18
  import type {
@@ -157,13 +158,42 @@ export const VIEW_MIRROR_SIZE = 'view_size';
157
158
 
158
159
  /** 对象级轮询的隐藏接线件实例 id */
159
160
 
160
- export function listShapeOf(behavior: KitBehavior): KitListShape {
161
- const { rowsPath, totalPath, ...rest } = behavior.list ?? {};
161
+ export function listShapeOf(behavior: KitBehavior, dataPath = getCompileEnvelope()?.dataPath): KitListShape {
162
+ const { rowsPath, totalPath, errorPath, ...rest } = behavior.list ?? {};
162
163
  const shape: KitListShape = { ...KIT_CORE_MAPPING.listShape, ...rest };
163
164
  // rowsPath / totalPath 相对响应体,补上 listInto 前缀;与存量的 rows / total(相对对象)同写时 rowsPath / totalPath 优先
164
165
  const base = KIT_CORE_MAPPING.fromWrap.listInto;
165
- if (typeof rowsPath === 'string' && rowsPath !== '') shape.rows = `${base}.${rowsPath}`;
166
- if (typeof totalPath === 'string' && totalPath !== '') shape.total = `${base}.${totalPath}`;
166
+ const hasDataPath = typeof dataPath === 'string' && dataPath !== '';
167
+
168
+ if (hasDataPath) {
169
+ if (typeof rowsPath === 'string' && rowsPath !== '') {
170
+ shape.rows = `${base}.${resolveEnvelopeSubPath(rowsPath, dataPath)}`;
171
+ } else if (behavior.list?.rows === undefined) {
172
+ shape.rows = `${base}.${resolveEnvelopeSubPath('rows', dataPath)}`;
173
+ }
174
+ if (typeof totalPath === 'string' && totalPath !== '') {
175
+ shape.total = `${base}.${resolveEnvelopeSubPath(totalPath, dataPath)}`;
176
+ } else if (behavior.list?.total === undefined) {
177
+ shape.total = `${base}.${resolveEnvelopeSubPath('total', dataPath)}`;
178
+ }
179
+ if (errorPath === undefined) {
180
+ shape.errorPath = `${base}.${resolveEnvelopeSubPath('error', dataPath)}`;
181
+ } else if (typeof errorPath === 'string') {
182
+ if (errorPath === '') {
183
+ shape.errorPath = '';
184
+ } else if (errorPath.startsWith(`${base}.`)) {
185
+ shape.errorPath = errorPath;
186
+ } else {
187
+ shape.errorPath = `${base}.${resolveEnvelopeSubPath(errorPath, dataPath)}`;
188
+ }
189
+ }
190
+ } else {
191
+ if (typeof rowsPath === 'string' && rowsPath !== '') shape.rows = `${base}.${rowsPath}`;
192
+ if (typeof totalPath === 'string' && totalPath !== '') shape.total = `${base}.${totalPath}`;
193
+ if (typeof errorPath === 'string') {
194
+ shape.errorPath = errorPath === '' || errorPath.startsWith(`${base}.`) ? errorPath : `${base}.${errorPath}`;
195
+ }
196
+ }
167
197
  return shape;
168
198
  }
169
199