@kimposoft/plugin-sdk 0.0.0-stage → 1.1.0-tp.20
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/LICENSE +202 -0
- package/NOTICE +9 -0
- package/README.md +48 -2
- package/package.json +141 -4
- package/src/action-designer.ts +250 -0
- package/src/attachment-url.ts +195 -0
- package/src/auth/index.ts +6 -0
- package/src/auth/qrcode.ts +519 -0
- package/src/auth/types.ts +261 -0
- package/src/display-style.ts +250 -0
- package/src/editor-frame.ts +623 -0
- package/src/editor-session.ts +1214 -0
- package/src/editor-testing.ts +838 -0
- package/src/editor.ts +1641 -0
- package/src/frame-transport.ts +491 -0
- package/src/frontend-routes.ts +99 -0
- package/src/hooks.ts +48 -0
- package/src/host-caps.ts +93 -0
- package/src/i18n.ts +238 -0
- package/src/im-panel.ts +132 -0
- package/src/image-tools.ts +91 -0
- package/src/index.ts +118 -0
- package/src/interactive-session.ts +94 -0
- package/src/nahida-im.ts +391 -0
- package/src/nahida-ws.ts +23 -0
- package/src/org-directory.ts +78 -0
- package/src/oz-realtime.ts +144 -0
- package/src/page.ts +404 -0
- package/src/print.ts +393 -0
- package/src/surface.ts +281 -0
- package/src/theme-mocks.ts +140 -0
- package/src/theme.ts +125 -0
- package/src/ui-fixtures/confirm.ts +16 -0
- package/src/ui-fixtures/entity-picker.ts +24 -0
- package/src/ui-fixtures/expression-editor.ts +52 -0
- package/src/ui-fixtures/image-cropper.ts +23 -0
- package/src/ui-fixtures/index.ts +16 -0
- package/src/ui-fixtures/org-tri-picker.ts +19 -0
- package/src/ui-fixtures/prompt.ts +19 -0
- package/src/ui-fixtures/record-picker.ts +17 -0
- package/src/ui-fixtures/template-picker.ts +13 -0
- package/src/ui-mocks.ts +250 -0
- package/src/ui.ts +479 -0
- package/src/workflow-designer.ts +475 -0
|
@@ -0,0 +1,838 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* editor-testing.ts —— 编辑器前端的宿主替身与一致性套件(SDK 1.1.0-tp.15 起)。只在测试里用,不要打进插件 bundle。
|
|
3
|
+
*
|
|
4
|
+
* 链路:模拟 kimpo 宿主前端(持有帧 WS 的宿主页 + 宿主桥 editorFrames / recordData)+ 宿主通用 editor transport +
|
|
5
|
+
* 表单数据权威层 Mirror(填报层)。口径与 Go 替身 plugin/plugintest/editorconformance.FakeFrameHost 一致:两边回放同一批
|
|
6
|
+
* SDK 黄金帧脚本(schema/editor/golden/frames/*.json)逐帧比对。
|
|
7
|
+
*
|
|
8
|
+
* - createFakeHostMirror:内存 Mirror + editor-frame/1 服务端(ack / rejected、重复帧、协议错误、Mirror 拒写、
|
|
9
|
+
* 业务写推 mirror.patch 且隐藏字段出口剔除、稠密序号、重放缓冲与 resync.required + snapshot、宿主驱动保存);
|
|
10
|
+
* bridge() 给出编辑器拿到的那几样:editorFrames(宿主页语义:断线自动带 last_seq 重连)、recordData.save
|
|
11
|
+
* (宿主按 Mirror 保存,带字段载荷即拒 EDITOR_DIRECT_SAVE_RETIRED)、boundSession(打开应答,驼峰顶层)。
|
|
12
|
+
* - runHostMirrorConformance:对任意编辑器前端(经一个小适配器)跑十一项检查:初始快照、隐藏字段不可见、用户编辑进 Mirror、
|
|
13
|
+
* 拒写回滚、业务写只渲染不回投、增行、新行上的编辑、业务增行、断线超出缓冲后重拉快照、宿主驱动保存、帧外形。
|
|
14
|
+
*
|
|
15
|
+
* @example
|
|
16
|
+
* ```ts
|
|
17
|
+
* const report = await runHostMirrorConformance(({ bridge, boundSession }) => {
|
|
18
|
+
* const model = createMyFormModel({ hostBridge: bridge, boundSession }); // 你的编辑器状态层
|
|
19
|
+
* return {
|
|
20
|
+
* setText: (t, r, f, v) => model.edit(t, r, f, v),
|
|
21
|
+
* getText: (t, r, f) => model.text(t, r, f),
|
|
22
|
+
* appendRow: t => model.addRow(t),
|
|
23
|
+
* rowKeys: t => model.rows(t),
|
|
24
|
+
* save: () => model.save()
|
|
25
|
+
* };
|
|
26
|
+
* });
|
|
27
|
+
* expect(report.failures).toEqual([]);
|
|
28
|
+
* ```
|
|
29
|
+
*/
|
|
30
|
+
import type { EditorTypedValue } from './editor';
|
|
31
|
+
|
|
32
|
+
// ════════════════════════════ 一、替身宿主 ════════════════════════════
|
|
33
|
+
|
|
34
|
+
export interface FakeHostMirrorTable {
|
|
35
|
+
data_table_id: string;
|
|
36
|
+
/** main | detail(主表恰好一张)。 */
|
|
37
|
+
role: 'main' | 'detail' | string;
|
|
38
|
+
fields: string[];
|
|
39
|
+
/** 只读表:不允许增删行 / 重排。 */
|
|
40
|
+
readonly?: boolean;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
export interface FakeHostMirrorOptions {
|
|
44
|
+
session_id?: string;
|
|
45
|
+
plugin_id?: string;
|
|
46
|
+
scene?: string;
|
|
47
|
+
form_mode?: 'create' | 'edit' | 'view' | string;
|
|
48
|
+
readonly?: boolean;
|
|
49
|
+
record_id?: string;
|
|
50
|
+
record_version_no?: number;
|
|
51
|
+
template_version_no?: string;
|
|
52
|
+
tables: FakeHostMirrorTable[];
|
|
53
|
+
hidden_field_ids?: string[];
|
|
54
|
+
readonly_field_ids?: string[];
|
|
55
|
+
derived_readonly_field_ids?: string[];
|
|
56
|
+
required_field_ids?: string[];
|
|
57
|
+
replay_frames?: number;
|
|
58
|
+
replay_seconds?: number;
|
|
59
|
+
now?: () => number;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/** 一条附着(等价一条 attach WS)。 */
|
|
63
|
+
export interface FakeFrameConn {
|
|
64
|
+
/** 附着握手帧(attached + 补发 / resync + snapshot)。 */
|
|
65
|
+
readonly initial: Record<string, unknown>[];
|
|
66
|
+
/** 处理一条浏览器帧(对象或 JSON 文本),返回直接应答帧。 */
|
|
67
|
+
send(frame: unknown): Record<string, unknown>[];
|
|
68
|
+
/** 取走服务端主动推送的帧。 */
|
|
69
|
+
receive(): Record<string, unknown>[];
|
|
70
|
+
close(): void;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
export interface FakeSavedRow {
|
|
74
|
+
data_table_id: string;
|
|
75
|
+
row_key: string;
|
|
76
|
+
fields: Record<string, EditorTypedValue>;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
export interface FakeSavedRecord {
|
|
80
|
+
mutation_id: string;
|
|
81
|
+
mode: string;
|
|
82
|
+
record_id: string;
|
|
83
|
+
version_no: number;
|
|
84
|
+
rows: FakeSavedRow[];
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/** 宿主驱动保存回执(snake_case,version_no 为数字)。 */
|
|
88
|
+
export interface FakeSaveResult {
|
|
89
|
+
record_id: string;
|
|
90
|
+
version_no: number;
|
|
91
|
+
status_code: string;
|
|
92
|
+
template_version_no?: string;
|
|
93
|
+
mirror_seq?: number;
|
|
94
|
+
field_errors?: Array<{ field_id: string; data_table_id?: string; row_key?: string; code: string; message?: string }>;
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/** 保存失败(status + code)。 */
|
|
98
|
+
export class FakeSaveError extends Error {
|
|
99
|
+
constructor(
|
|
100
|
+
public readonly status: number,
|
|
101
|
+
public readonly code: string
|
|
102
|
+
) {
|
|
103
|
+
super(`${code}: host-driven save failed (${status})`);
|
|
104
|
+
this.name = 'FakeSaveError';
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
interface Row {
|
|
109
|
+
key: string;
|
|
110
|
+
state: string;
|
|
111
|
+
order: number;
|
|
112
|
+
fields: Map<string, EditorTypedValue>;
|
|
113
|
+
deleted?: boolean;
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
interface Table {
|
|
117
|
+
def: FakeHostMirrorTable;
|
|
118
|
+
fields: Set<string>;
|
|
119
|
+
rows: Row[];
|
|
120
|
+
next: number;
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
/** 编辑器拿到的那几样(与宿主沙箱档下发同形)。 */
|
|
124
|
+
export interface FakeEditorBridge {
|
|
125
|
+
editorFrames: {
|
|
126
|
+
send(frame: unknown): void;
|
|
127
|
+
subscribe(listener: (frame: unknown) => void): () => void;
|
|
128
|
+
/** 宿主页语义:带 ?snapshot=1 重新附着(宿主先补发 snapshot 帧)。 */
|
|
129
|
+
resync(reason?: string): void;
|
|
130
|
+
};
|
|
131
|
+
recordData: { save(input: Record<string, unknown>): Promise<Record<string, unknown>> };
|
|
132
|
+
log: { debug(m: string, c?: unknown): void; info(m: string, c?: unknown): void; warn(m: string, c?: unknown): void; error(m: string, c?: unknown): void };
|
|
133
|
+
interactiveSession: { sessionId: string; markDirty(dirty: boolean): void };
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
export interface FakeHostMirror {
|
|
137
|
+
readonly sessionId: string;
|
|
138
|
+
seed(dataTableId: string, rowKey: string, fieldId: string, value: EditorTypedValue): void;
|
|
139
|
+
seedDetailRow(dataTableId: string): string;
|
|
140
|
+
attach(lastSeq?: number, wantSnapshot?: boolean): FakeFrameConn;
|
|
141
|
+
snapshot(): Record<string, unknown>;
|
|
142
|
+
meta(): Record<string, unknown>;
|
|
143
|
+
/** 宿主前端归一后交给编辑器的 boundSession(顶层驼峰,meta / recordSnapshot 为 snake_case)。 */
|
|
144
|
+
boundSession(): Record<string, unknown>;
|
|
145
|
+
businessWrite(cause: string, writes: Array<{ data_table_id: string; row_key: string; field_id: string; value: EditorTypedValue }>): number;
|
|
146
|
+
businessAppendRows(cause: string, dataTableId: string, count: number): string[];
|
|
147
|
+
businessRemoveRows(cause: string, dataTableId: string, rowKeys: string[]): number;
|
|
148
|
+
setFormMode(mode: string): void;
|
|
149
|
+
pushEffects(envelope: Record<string, unknown>): void;
|
|
150
|
+
save(request: Record<string, unknown>): FakeSaveResult;
|
|
151
|
+
value(dataTableId: string, rowKey: string, fieldId: string): EditorTypedValue | undefined;
|
|
152
|
+
rowKeys(dataTableId: string): string[];
|
|
153
|
+
currentSeq(): number;
|
|
154
|
+
saved(): FakeSavedRecord[];
|
|
155
|
+
calcReports(): Record<string, unknown>[];
|
|
156
|
+
/** 编辑器侧的桥(宿主页语义)。 */
|
|
157
|
+
bridge(): FakeEditorBridge;
|
|
158
|
+
/** 模拟宿主页的 WS 断开:bridge 通道在 reconnect() 时带 last_seq 重新附着。 */
|
|
159
|
+
disconnect(): void;
|
|
160
|
+
reconnect(): void;
|
|
161
|
+
/** bridge 上编辑器发出的全部浏览器帧(原样)。 */
|
|
162
|
+
clientFrames(): unknown[];
|
|
163
|
+
/** bridge 上编辑器请求过的重同步(editorFrames.resync 的 reason,按调用顺序)。 */
|
|
164
|
+
resyncs(): string[];
|
|
165
|
+
/** bridge 收到的上报日志。 */
|
|
166
|
+
logs(): Array<{ level: string; message: string }>;
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
const clone = <T>(v: T): T => (v === undefined ? v : (JSON.parse(JSON.stringify(v)) as T));
|
|
170
|
+
|
|
171
|
+
/** 去掉空值(protojson 省略零值的口径):undefined / null / '' / 0 / false / 空数组 / 空对象。 */
|
|
172
|
+
function compact(v: unknown): unknown {
|
|
173
|
+
if (Array.isArray(v)) return v.map(compact);
|
|
174
|
+
if (v && typeof v === 'object') {
|
|
175
|
+
const out: Record<string, unknown> = {};
|
|
176
|
+
for (const [k, val] of Object.entries(v as Record<string, unknown>)) {
|
|
177
|
+
if (k === 'raw') {
|
|
178
|
+
if (val !== undefined) out[k] = val;
|
|
179
|
+
continue;
|
|
180
|
+
}
|
|
181
|
+
const c = compact(val);
|
|
182
|
+
if (c === undefined || c === null || c === '' || c === 0 || c === false) continue;
|
|
183
|
+
if (Array.isArray(c) && c.length === 0) continue;
|
|
184
|
+
if (c && typeof c === 'object' && !Array.isArray(c) && Object.keys(c).length === 0 && k !== 'value') continue;
|
|
185
|
+
out[k] = c;
|
|
186
|
+
}
|
|
187
|
+
return out;
|
|
188
|
+
}
|
|
189
|
+
return v;
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
function frame(type: string, body?: unknown, seq = 0, ack = 0): Record<string, unknown> {
|
|
193
|
+
const out: Record<string, unknown> = { v: 1, type };
|
|
194
|
+
if (seq > 0) out.seq = seq;
|
|
195
|
+
if (ack > 0) out.ack = ack;
|
|
196
|
+
if (body !== undefined) out.body = compact(body);
|
|
197
|
+
return out;
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
const errorFrame = (code: string, message: string, refSeq = 0) => frame('error', { code, message, ref_seq: refSeq });
|
|
201
|
+
|
|
202
|
+
const CLIENT_TYPES = ['ping', 'pong', 'edit.fields', 'edit.rows', 'calc.state'];
|
|
203
|
+
|
|
204
|
+
/** createFakeHostMirror —— host-mirror 会话宿主替身(口径见文件头)。 */
|
|
205
|
+
export function createFakeHostMirror(options: FakeHostMirrorOptions): FakeHostMirror {
|
|
206
|
+
const o = {
|
|
207
|
+
session_id: 'es-fake-1',
|
|
208
|
+
scene: 'form-runtime',
|
|
209
|
+
form_mode: 'create',
|
|
210
|
+
replay_frames: 256,
|
|
211
|
+
replay_seconds: 30,
|
|
212
|
+
now: () => Date.now(),
|
|
213
|
+
...options
|
|
214
|
+
};
|
|
215
|
+
const hidden = new Set(o.hidden_field_ids ?? []);
|
|
216
|
+
const readonlyFields = new Set(o.readonly_field_ids ?? []);
|
|
217
|
+
const derived = new Set(o.derived_readonly_field_ids ?? []);
|
|
218
|
+
const required = [...new Set(o.required_field_ids ?? [])].sort();
|
|
219
|
+
let formMode = o.form_mode;
|
|
220
|
+
let recordId = o.record_id ?? '';
|
|
221
|
+
let versionNo = o.record_version_no ?? 0;
|
|
222
|
+
let patchSeq = 0;
|
|
223
|
+
let clientAck = 0;
|
|
224
|
+
let recordSeq = 0;
|
|
225
|
+
let ring: Array<{ seq: number; at: number; frame: Record<string, unknown> }> = [];
|
|
226
|
+
const conns = new Set<{ push(f: Record<string, unknown>): void }>();
|
|
227
|
+
const saves = new Map<string, FakeSaveResult>();
|
|
228
|
+
const savedRecords: FakeSavedRecord[] = [];
|
|
229
|
+
const calc: Record<string, unknown>[] = [];
|
|
230
|
+
const tables: Table[] = o.tables.map(def => ({
|
|
231
|
+
def,
|
|
232
|
+
fields: new Set(def.fields),
|
|
233
|
+
rows: def.role === 'main' ? [{ key: 'main:0', state: 'clean', order: 0, fields: new Map() }] : [],
|
|
234
|
+
next: 0
|
|
235
|
+
}));
|
|
236
|
+
const byId = new Map(tables.map(t => [t.def.data_table_id, t]));
|
|
237
|
+
const live = (t: Table) => t.rows.filter(r => !r.deleted).sort((a, b) => a.order - b.order);
|
|
238
|
+
const rowOf = (t: Table, key: string) => t.rows.find(r => r.key === key && !r.deleted);
|
|
239
|
+
const appendRow = (t: Table, key: string, state: string): Row => {
|
|
240
|
+
if (!key) {
|
|
241
|
+
t.next += 1;
|
|
242
|
+
key = `row:${t.next}`;
|
|
243
|
+
} else if (key.startsWith('row:')) {
|
|
244
|
+
const n = Number(key.slice(4));
|
|
245
|
+
if (Number.isInteger(n) && n > t.next) t.next = n;
|
|
246
|
+
}
|
|
247
|
+
const r: Row = { key, state, order: live(t).length + 1, fields: new Map() };
|
|
248
|
+
t.rows.push(r);
|
|
249
|
+
return r;
|
|
250
|
+
};
|
|
251
|
+
const renumber = (t: Table) => live(t).forEach((r, i) => (r.order = i + 1));
|
|
252
|
+
const readonlySession = () => o.scene !== 'form-runtime' || o.readonly === true || formMode === 'view';
|
|
253
|
+
const prune = () => {
|
|
254
|
+
const cutoff = o.now() - o.replay_seconds * 1000;
|
|
255
|
+
let drop = 0;
|
|
256
|
+
while (drop < ring.length && (ring.length - drop > o.replay_frames || ring[drop].at < cutoff)) drop++;
|
|
257
|
+
if (drop > 0) ring = ring.slice(drop);
|
|
258
|
+
};
|
|
259
|
+
|
|
260
|
+
const snapshot = (): Record<string, unknown> =>
|
|
261
|
+
compact({
|
|
262
|
+
record_id: recordId,
|
|
263
|
+
template_version_no: o.template_version_no,
|
|
264
|
+
record_version_no: versionNo,
|
|
265
|
+
mirror_seq: patchSeq,
|
|
266
|
+
tables: tables.map(t => ({
|
|
267
|
+
data_table_id: t.def.data_table_id,
|
|
268
|
+
role: t.def.role,
|
|
269
|
+
rows: live(t).map(r => ({
|
|
270
|
+
row_key: r.key,
|
|
271
|
+
row_state: r.state,
|
|
272
|
+
display_order: r.order,
|
|
273
|
+
fields: [...r.fields.keys()]
|
|
274
|
+
.filter(id => !hidden.has(id))
|
|
275
|
+
.sort()
|
|
276
|
+
.map(id => ({ field_id: id, value: clone(r.fields.get(id)) }))
|
|
277
|
+
}))
|
|
278
|
+
}))
|
|
279
|
+
}) as Record<string, unknown>;
|
|
280
|
+
const meta = (): Record<string, unknown> =>
|
|
281
|
+
compact({
|
|
282
|
+
readonly: readonlySession(),
|
|
283
|
+
form_mode: formMode,
|
|
284
|
+
scene: o.scene,
|
|
285
|
+
hidden_field_ids: [...hidden].sort(),
|
|
286
|
+
readonly_field_ids: [...readonlyFields].sort(),
|
|
287
|
+
derived_readonly_field_ids: [...derived].sort(),
|
|
288
|
+
readonly_table_ids: tables.filter(t => t.def.readonly).map(t => t.def.data_table_id),
|
|
289
|
+
// 宿主口径:meta 下发必填字段,已扣掉隐藏 / 只读 / 派生只读。
|
|
290
|
+
required_field_ids: required.filter(id => !hidden.has(id) && !readonlyFields.has(id) && !derived.has(id))
|
|
291
|
+
}) as Record<string, unknown>;
|
|
292
|
+
|
|
293
|
+
const publish = (patch: { cause: string; fields?: Array<Record<string, unknown>>; rows?: Array<Record<string, unknown>> }) => {
|
|
294
|
+
const fields = (patch.fields ?? []).filter(d => !hidden.has(String(d.field_id)));
|
|
295
|
+
if (fields.length === 0 && (patch.rows ?? []).length === 0) return 0;
|
|
296
|
+
patchSeq += 1;
|
|
297
|
+
const f = frame('mirror.patch', { seq: patchSeq, cause: patch.cause, fields, rows: patch.rows }, patchSeq);
|
|
298
|
+
ring.push({ seq: patchSeq, at: o.now(), frame: f });
|
|
299
|
+
prune();
|
|
300
|
+
for (const c of conns) c.push(clone(f));
|
|
301
|
+
return patchSeq;
|
|
302
|
+
};
|
|
303
|
+
|
|
304
|
+
const ackFrame = (seq: number, body: Record<string, unknown>) => frame('ack', { client_seq: seq, ...body }, 0, seq);
|
|
305
|
+
|
|
306
|
+
const applyEditFields = (body: Record<string, unknown>, rejected: unknown[]): string | { protocol: string } | undefined => {
|
|
307
|
+
const deltas = Array.isArray(body.deltas) ? (body.deltas as Array<Record<string, unknown>>) : [];
|
|
308
|
+
const writes: Array<{ row: Row; field: string; value: EditorTypedValue }> = [];
|
|
309
|
+
for (const d of deltas) {
|
|
310
|
+
const table = String(d.data_table_id ?? '').trim();
|
|
311
|
+
const rowKey = String(d.row_key ?? '').trim();
|
|
312
|
+
const field = String(d.field_id ?? '').trim();
|
|
313
|
+
if (!table || !rowKey || !field) return { protocol: 'edit.fields delta requires data_table_id, row_key and field_id' };
|
|
314
|
+
if (readonlySession()) {
|
|
315
|
+
rejected.push({ data_table_id: table, row_key: rowKey, field_id: field, code: 'EDITOR_SESSION_READONLY', message: 'form is read-only' });
|
|
316
|
+
continue;
|
|
317
|
+
}
|
|
318
|
+
if (hidden.has(field) || readonlyFields.has(field) || derived.has(field)) {
|
|
319
|
+
rejected.push({ data_table_id: table, row_key: rowKey, field_id: field, code: 'EDITOR_FIELD_NOT_EDITABLE', message: 'field is not editable' });
|
|
320
|
+
continue;
|
|
321
|
+
}
|
|
322
|
+
const t = byId.get(table);
|
|
323
|
+
if (!t) return `unknown data table ${table}`;
|
|
324
|
+
if (!t.fields.has(field)) return `unknown field ${field}`;
|
|
325
|
+
const row = rowOf(t, rowKey);
|
|
326
|
+
if (!row) return `unknown row ${rowKey}`;
|
|
327
|
+
writes.push({ row, field, value: clone((d.value as EditorTypedValue) ?? {}) });
|
|
328
|
+
}
|
|
329
|
+
for (const w of writes) {
|
|
330
|
+
w.row.fields.set(w.field, w.value);
|
|
331
|
+
if (w.row.state === 'clean') w.row.state = 'dirty';
|
|
332
|
+
}
|
|
333
|
+
return undefined;
|
|
334
|
+
};
|
|
335
|
+
|
|
336
|
+
const applyEditRows = (body: Record<string, unknown>, rejected: unknown[], assigned: unknown[]): string | { protocol: string } | undefined => {
|
|
337
|
+
const ops = Array.isArray(body.ops) ? (body.ops as Array<Record<string, unknown>>) : [];
|
|
338
|
+
for (const op of ops) {
|
|
339
|
+
const table = String(op.data_table_id ?? '').trim();
|
|
340
|
+
if (!table) return { protocol: 'edit.rows op requires data_table_id' };
|
|
341
|
+
if (readonlySession()) {
|
|
342
|
+
rejected.push({ data_table_id: table, code: 'EDITOR_SESSION_READONLY', message: 'form is read-only' });
|
|
343
|
+
continue;
|
|
344
|
+
}
|
|
345
|
+
const t = byId.get(table);
|
|
346
|
+
if (t?.def.readonly) {
|
|
347
|
+
rejected.push({ data_table_id: table, code: 'EDITOR_TABLE_READONLY', message: 'rows of this table cannot be added or removed' });
|
|
348
|
+
continue;
|
|
349
|
+
}
|
|
350
|
+
const kind = String(op.op ?? '').trim();
|
|
351
|
+
const list = (k: string) => (Array.isArray(op[k]) ? (op[k] as string[]) : []);
|
|
352
|
+
if (kind === 'append' && list('client_row_keys').length === 0) return { protocol: 'append requires client_row_keys' };
|
|
353
|
+
if (kind === 'remove' && list('row_keys').length === 0) return { protocol: 'remove requires row_keys' };
|
|
354
|
+
if (kind === 'reorder' && list('ordered_row_keys').length === 0) return { protocol: 'reorder requires ordered_row_keys' };
|
|
355
|
+
if (!['append', 'remove', 'reorder'].includes(kind)) return { protocol: `unknown row op ${String(op.op)}` };
|
|
356
|
+
if (!t || t.def.role !== 'detail') return `unknown detail table ${table}`;
|
|
357
|
+
if (kind === 'append') {
|
|
358
|
+
for (const ck of list('client_row_keys')) {
|
|
359
|
+
const r = appendRow(t, '', 'new');
|
|
360
|
+
assigned.push({ data_table_id: table, client_row_key: ck, row_key: r.key });
|
|
361
|
+
}
|
|
362
|
+
} else if (kind === 'remove') {
|
|
363
|
+
const keys = list('row_keys');
|
|
364
|
+
for (const k of keys) if (!rowOf(t, k)) return `unknown row ${k}`;
|
|
365
|
+
for (const k of keys) rowOf(t, k)!.deleted = true;
|
|
366
|
+
renumber(t);
|
|
367
|
+
} else {
|
|
368
|
+
const keys = list('ordered_row_keys');
|
|
369
|
+
const rows = live(t);
|
|
370
|
+
const seen = new Set<string>();
|
|
371
|
+
if (keys.length !== rows.length) return 'ordered_row_keys must list every live row exactly once';
|
|
372
|
+
for (const k of keys) {
|
|
373
|
+
if (!rowOf(t, k) || seen.has(k)) return 'ordered_row_keys must list every live row exactly once';
|
|
374
|
+
seen.add(k);
|
|
375
|
+
}
|
|
376
|
+
keys.forEach((k, i) => (rowOf(t, k)!.order = i + 1));
|
|
377
|
+
}
|
|
378
|
+
}
|
|
379
|
+
return undefined;
|
|
380
|
+
};
|
|
381
|
+
|
|
382
|
+
const handle = (raw: unknown): Record<string, unknown>[] => {
|
|
383
|
+
let f: Record<string, unknown>;
|
|
384
|
+
try {
|
|
385
|
+
const parsed = typeof raw === 'string' ? JSON.parse(raw) : clone(raw);
|
|
386
|
+
if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) throw new Error('not an object');
|
|
387
|
+
f = parsed as Record<string, unknown>;
|
|
388
|
+
} catch {
|
|
389
|
+
return [errorFrame('EDITOR_FRAME_PROTOCOL', 'invalid json')];
|
|
390
|
+
}
|
|
391
|
+
const seq = typeof f.seq === 'number' && f.seq > 0 ? Math.trunc(f.seq) : 0;
|
|
392
|
+
if (f.v !== 1) return [errorFrame('EDITOR_FRAME_PROTOCOL', 'unsupported frame version', seq)];
|
|
393
|
+
const type = String(f.type ?? '');
|
|
394
|
+
if (!CLIENT_TYPES.includes(type)) return [errorFrame('EDITOR_FRAME_PROTOCOL', `frame type not accepted from editor: ${type}`, seq)];
|
|
395
|
+
const body = (f.body ?? {}) as Record<string, unknown>;
|
|
396
|
+
if (type === 'ping') return [frame('pong')];
|
|
397
|
+
if (type === 'pong') return [];
|
|
398
|
+
if (f.body !== undefined && f.body !== null && (typeof f.body !== 'object' || Array.isArray(f.body))) {
|
|
399
|
+
return [errorFrame('EDITOR_FRAME_PROTOCOL', `${type} body`, seq)];
|
|
400
|
+
}
|
|
401
|
+
if (type === 'calc.state') {
|
|
402
|
+
const states = Array.isArray(body.states) ? (body.states as Array<Record<string, unknown>>) : [];
|
|
403
|
+
let barrier = 'settled';
|
|
404
|
+
for (const st of states) {
|
|
405
|
+
const s = String(st.status ?? '');
|
|
406
|
+
if (s === 'clean') continue;
|
|
407
|
+
if (['dirty', 'calculating', 'stale', 'error'].includes(s)) barrier = 'waiting';
|
|
408
|
+
else return [errorFrame('EDITOR_FRAME_PROTOCOL', `calc.state status ${s}`, seq)];
|
|
409
|
+
}
|
|
410
|
+
calc.push(clone(body));
|
|
411
|
+
return [frame('calc.state', { calc_revision: body.calc_revision, barrier })];
|
|
412
|
+
}
|
|
413
|
+
if (seq === 0) return [errorFrame('EDITOR_FRAME_PROTOCOL', 'edit frame requires seq')];
|
|
414
|
+
if (seq <= clientAck) return [ackFrame(seq, { mirror_seq: patchSeq })];
|
|
415
|
+
const rejected: unknown[] = [];
|
|
416
|
+
const assigned: unknown[] = [];
|
|
417
|
+
const err = type === 'edit.fields' ? applyEditFields(body, rejected) : applyEditRows(body, rejected, assigned);
|
|
418
|
+
const out: Record<string, unknown>[] = [];
|
|
419
|
+
if (err && typeof err === 'object') return [errorFrame('EDITOR_FRAME_PROTOCOL', err.protocol, seq)];
|
|
420
|
+
if (err) out.push(errorFrame('EDITOR_MIRROR_REJECTED', err, seq));
|
|
421
|
+
if (seq > clientAck) clientAck = seq;
|
|
422
|
+
out.push(ackFrame(seq, { assigned_rows: assigned, rejected, mirror_seq: patchSeq }));
|
|
423
|
+
return out;
|
|
424
|
+
};
|
|
425
|
+
|
|
426
|
+
const attach = (lastSeq = -1, wantSnapshot = false, sink?: (f: Record<string, unknown>) => void): FakeFrameConn => {
|
|
427
|
+
if (wantSnapshot) lastSeq = -1;
|
|
428
|
+
let inbox: Record<string, unknown>[] = [];
|
|
429
|
+
let closed = false;
|
|
430
|
+
const conn = {
|
|
431
|
+
push: (f: Record<string, unknown>) => {
|
|
432
|
+
if (closed) return;
|
|
433
|
+
if (sink) sink(f);
|
|
434
|
+
else inbox.push(f);
|
|
435
|
+
}
|
|
436
|
+
};
|
|
437
|
+
conns.add(conn);
|
|
438
|
+
const initial = [frame('attached', { editor_session_id: o.session_id, server_seq: patchSeq, client_ack: clientAck, session_mode: 'host-mirror' })];
|
|
439
|
+
prune();
|
|
440
|
+
if (wantSnapshot) initial.push(frame('snapshot', snapshot()));
|
|
441
|
+
else if (lastSeq >= 0 && lastSeq < patchSeq) {
|
|
442
|
+
const next = lastSeq + 1;
|
|
443
|
+
if (ring.length === 0 || ring[0].seq > next) {
|
|
444
|
+
initial.push(frame('resync.required', { from_seq: next, latest_seq: patchSeq, reason: 'replay-buffer-exceeded' }), frame('snapshot', snapshot()));
|
|
445
|
+
} else {
|
|
446
|
+
for (const r of ring) if (r.seq >= next) initial.push(clone(r.frame));
|
|
447
|
+
}
|
|
448
|
+
}
|
|
449
|
+
return {
|
|
450
|
+
initial,
|
|
451
|
+
send: f => handle(f),
|
|
452
|
+
receive() {
|
|
453
|
+
const out = inbox;
|
|
454
|
+
inbox = [];
|
|
455
|
+
return out;
|
|
456
|
+
},
|
|
457
|
+
close() {
|
|
458
|
+
closed = true;
|
|
459
|
+
conns.delete(conn);
|
|
460
|
+
}
|
|
461
|
+
};
|
|
462
|
+
};
|
|
463
|
+
|
|
464
|
+
const save = (req: Record<string, unknown>): FakeSaveResult => {
|
|
465
|
+
const get = (snake: string) => req[snake] ?? req[snake.replace(/_([a-z])/g, (_m, c: string) => c.toUpperCase())];
|
|
466
|
+
const sid = String(get('editor_session_id') ?? '').trim();
|
|
467
|
+
if (sid && sid !== o.session_id) throw new FakeSaveError(400, 'EDITOR_FRAME_PROTOCOL');
|
|
468
|
+
if (readonlySession()) throw new FakeSaveError(403, 'EDITOR_SESSION_READONLY');
|
|
469
|
+
const mutation = String(get('client_mutation_id') ?? '').trim() || `host-save-${o.now()}`;
|
|
470
|
+
const cached = saves.get(mutation);
|
|
471
|
+
if (cached) return clone(cached);
|
|
472
|
+
const mode = formMode === 'edit' || recordId ? 'edit' : 'create';
|
|
473
|
+
const expected = Number(get('expected_version_no') ?? 0);
|
|
474
|
+
if (mode === 'edit' && expected > 0 && expected !== versionNo) throw new FakeSaveError(409, 'VERSION_CONFLICT');
|
|
475
|
+
const rows: FakeSavedRow[] = [];
|
|
476
|
+
const fieldErrors: NonNullable<FakeSaveResult['field_errors']> = [];
|
|
477
|
+
for (const t of tables) {
|
|
478
|
+
for (const r of live(t)) {
|
|
479
|
+
const fields: Record<string, EditorTypedValue> = {};
|
|
480
|
+
for (const [id, v] of r.fields) if (!hidden.has(id) && !readonlyFields.has(id)) fields[id] = clone(v);
|
|
481
|
+
rows.push({ data_table_id: t.def.data_table_id, row_key: r.key, fields });
|
|
482
|
+
// 必填只核 meta.required_field_ids(已扣隐藏 / 只读 / 派生只读字段),与宿主同口径。
|
|
483
|
+
for (const id of required) {
|
|
484
|
+
if (!t.fields.has(id) || hidden.has(id) || readonlyFields.has(id) || derived.has(id)) continue;
|
|
485
|
+
const v = r.fields.get(id);
|
|
486
|
+
if (!v || ((v.text ?? '') === '' && (v.raw === undefined || v.raw === null))) {
|
|
487
|
+
fieldErrors.push({ field_id: id, data_table_id: t.def.data_table_id, row_key: r.key, code: 'REQUIRED_FIELD_MISSING', message: 'required field is empty' });
|
|
488
|
+
}
|
|
489
|
+
}
|
|
490
|
+
}
|
|
491
|
+
}
|
|
492
|
+
if (fieldErrors.length > 0) {
|
|
493
|
+
const res = compact({ record_id: recordId, version_no: versionNo, status_code: 'draft', template_version_no: o.template_version_no, field_errors: fieldErrors, mirror_seq: patchSeq }) as FakeSaveResult;
|
|
494
|
+
saves.set(mutation, clone(res));
|
|
495
|
+
return res;
|
|
496
|
+
}
|
|
497
|
+
if (mode === 'create') {
|
|
498
|
+
recordSeq += 1;
|
|
499
|
+
recordId = `rec-fake-${recordSeq}`;
|
|
500
|
+
}
|
|
501
|
+
versionNo += 1;
|
|
502
|
+
savedRecords.push({ mutation_id: mutation, mode, record_id: recordId, version_no: versionNo, rows });
|
|
503
|
+
for (const t of tables) for (const r of live(t)) r.state = 'clean';
|
|
504
|
+
formMode = 'edit';
|
|
505
|
+
const res = compact({ record_id: recordId, version_no: versionNo, status_code: 'draft', template_version_no: o.template_version_no, mirror_seq: patchSeq }) as FakeSaveResult;
|
|
506
|
+
saves.set(mutation, clone(res));
|
|
507
|
+
return res;
|
|
508
|
+
};
|
|
509
|
+
|
|
510
|
+
// ---- 宿主页语义的桥 ----
|
|
511
|
+
const sentFrames: unknown[] = [];
|
|
512
|
+
const logLines: Array<{ level: string; message: string }> = [];
|
|
513
|
+
const subscribers = new Set<(f: unknown) => void>();
|
|
514
|
+
let bridgeConn: FakeFrameConn | undefined;
|
|
515
|
+
let bridgeLastSeq = 0;
|
|
516
|
+
let connected = false;
|
|
517
|
+
const resyncReasons: string[] = [];
|
|
518
|
+
const deliver = (frames: Record<string, unknown>[]) => {
|
|
519
|
+
for (const f of frames) {
|
|
520
|
+
const body = f.body as { seq?: number; mirror_seq?: number } | undefined;
|
|
521
|
+
const s = f.type === 'mirror.patch' ? body?.seq : f.type === 'snapshot' ? body?.mirror_seq : undefined;
|
|
522
|
+
if (typeof s === 'number' && s > bridgeLastSeq) bridgeLastSeq = s;
|
|
523
|
+
for (const l of [...subscribers]) l(clone(f));
|
|
524
|
+
}
|
|
525
|
+
};
|
|
526
|
+
const ensureConnected = () => {
|
|
527
|
+
if (connected) return;
|
|
528
|
+
connected = true;
|
|
529
|
+
// 宿主页语义:首次附着只收新帧;断线后重连带 last_seq(缓冲不足时宿主回 resync.required + snapshot)。
|
|
530
|
+
const conn = attach(bridgeConn ? bridgeLastSeq : -1, false, f => deliver([f]));
|
|
531
|
+
bridgeConn = conn;
|
|
532
|
+
deliver(conn.initial);
|
|
533
|
+
};
|
|
534
|
+
|
|
535
|
+
const host: FakeHostMirror = {
|
|
536
|
+
sessionId: o.session_id,
|
|
537
|
+
seed(t, r, f, v) {
|
|
538
|
+
const table = byId.get(t);
|
|
539
|
+
if (!table) throw new Error(`seed: unknown table ${t}`);
|
|
540
|
+
const row = rowOf(table, r) ?? appendRow(table, r, 'clean');
|
|
541
|
+
row.fields.set(f, clone(v));
|
|
542
|
+
},
|
|
543
|
+
seedDetailRow(t) {
|
|
544
|
+
const table = byId.get(t);
|
|
545
|
+
if (!table) throw new Error(`seedDetailRow: unknown table ${t}`);
|
|
546
|
+
return appendRow(table, '', 'clean').key;
|
|
547
|
+
},
|
|
548
|
+
attach,
|
|
549
|
+
snapshot,
|
|
550
|
+
meta,
|
|
551
|
+
boundSession: () => ({
|
|
552
|
+
editorSessionId: o.session_id,
|
|
553
|
+
sheetSessionId: o.session_id,
|
|
554
|
+
pluginId: o.plugin_id ?? '',
|
|
555
|
+
sessionMode: 'host-mirror',
|
|
556
|
+
credentialRevision: 1,
|
|
557
|
+
expiresAt: new Date(o.now() + 30 * 60_000).toISOString(),
|
|
558
|
+
serverTime: new Date(o.now()).toISOString(),
|
|
559
|
+
attachPath: `/api/v1/apps/app-fake/interactive-sessions/is-fake/editor-sessions/${o.session_id}/attach`,
|
|
560
|
+
meta: meta(),
|
|
561
|
+
recordSnapshot: snapshot(),
|
|
562
|
+
frameProtocol: 'editor-frame/1'
|
|
563
|
+
}),
|
|
564
|
+
businessWrite(cause, writes) {
|
|
565
|
+
for (const w of writes) {
|
|
566
|
+
const t = byId.get(w.data_table_id);
|
|
567
|
+
if (!t || !t.fields.has(w.field_id)) throw new Error(`businessWrite: unknown ${w.data_table_id}/${w.field_id}`);
|
|
568
|
+
const r = rowOf(t, w.row_key);
|
|
569
|
+
if (!r) throw new Error(`businessWrite: unknown row ${w.row_key}`);
|
|
570
|
+
r.fields.set(w.field_id, clone(w.value));
|
|
571
|
+
}
|
|
572
|
+
return publish({ cause, fields: writes.map(w => ({ data_table_id: w.data_table_id, row_key: w.row_key, field_id: w.field_id, value: clone(w.value) })) });
|
|
573
|
+
},
|
|
574
|
+
businessAppendRows(cause, t, count) {
|
|
575
|
+
const table = byId.get(t);
|
|
576
|
+
if (!table) throw new Error(`businessAppendRows: unknown table ${t}`);
|
|
577
|
+
const keys = Array.from({ length: count }, () => appendRow(table, '', 'new').key);
|
|
578
|
+
publish({ cause, rows: [{ kind: 'appended', data_table_id: t, row_keys: keys }] });
|
|
579
|
+
return keys;
|
|
580
|
+
},
|
|
581
|
+
businessRemoveRows(cause, t, rowKeys) {
|
|
582
|
+
const table = byId.get(t);
|
|
583
|
+
if (!table) throw new Error(`businessRemoveRows: unknown table ${t}`);
|
|
584
|
+
for (const k of rowKeys) {
|
|
585
|
+
const r = rowOf(table, k);
|
|
586
|
+
if (r) r.deleted = true;
|
|
587
|
+
}
|
|
588
|
+
renumber(table);
|
|
589
|
+
return publish({ cause, rows: [{ kind: 'removed', data_table_id: t, row_keys: rowKeys }] });
|
|
590
|
+
},
|
|
591
|
+
setFormMode(mode) {
|
|
592
|
+
formMode = mode;
|
|
593
|
+
const f = frame('session.meta', meta());
|
|
594
|
+
for (const c of conns) c.push(clone(f));
|
|
595
|
+
},
|
|
596
|
+
pushEffects(envelope) {
|
|
597
|
+
const f = frame('effects', { envelope });
|
|
598
|
+
for (const c of conns) c.push(clone(f));
|
|
599
|
+
},
|
|
600
|
+
save,
|
|
601
|
+
value(t, r, f) {
|
|
602
|
+
const table = byId.get(t);
|
|
603
|
+
const row = table ? rowOf(table, r) : undefined;
|
|
604
|
+
const v = row?.fields.get(f);
|
|
605
|
+
return v ? clone(v) : undefined;
|
|
606
|
+
},
|
|
607
|
+
rowKeys(t) {
|
|
608
|
+
const table = byId.get(t);
|
|
609
|
+
return table ? live(table).map(r => r.key) : [];
|
|
610
|
+
},
|
|
611
|
+
currentSeq: () => patchSeq,
|
|
612
|
+
saved: () => clone(savedRecords),
|
|
613
|
+
calcReports: () => clone(calc),
|
|
614
|
+
bridge() {
|
|
615
|
+
return {
|
|
616
|
+
editorFrames: {
|
|
617
|
+
send(f: unknown) {
|
|
618
|
+
sentFrames.push(clone(f));
|
|
619
|
+
ensureConnected();
|
|
620
|
+
if (!connected || !bridgeConn) return;
|
|
621
|
+
deliver(bridgeConn.send(f));
|
|
622
|
+
},
|
|
623
|
+
subscribe(listener: (f: unknown) => void) {
|
|
624
|
+
subscribers.add(listener);
|
|
625
|
+
ensureConnected();
|
|
626
|
+
return () => subscribers.delete(listener);
|
|
627
|
+
},
|
|
628
|
+
resync(reason?: string) {
|
|
629
|
+
// 宿主页语义:换下当前连接,带 ?snapshot=1 重新附着,宿主附着后先补发 snapshot 帧。
|
|
630
|
+
resyncReasons.push(String(reason ?? ''));
|
|
631
|
+
bridgeConn?.close();
|
|
632
|
+
connected = true;
|
|
633
|
+
const conn = attach(bridgeLastSeq, true, f => deliver([f]));
|
|
634
|
+
bridgeConn = conn;
|
|
635
|
+
deliver(conn.initial);
|
|
636
|
+
}
|
|
637
|
+
},
|
|
638
|
+
recordData: {
|
|
639
|
+
async save(input: Record<string, unknown>) {
|
|
640
|
+
if ('dataTables' in input || 'data_tables' in input) {
|
|
641
|
+
throw Object.assign(new Error('EDITOR_DIRECT_SAVE_RETIRED: recordData.save no longer accepts field payloads'), { code: 'EDITOR_DIRECT_SAVE_RETIRED' });
|
|
642
|
+
}
|
|
643
|
+
try {
|
|
644
|
+
const res = save({ editor_session_id: o.session_id, ...input });
|
|
645
|
+
// 宿主前端把回执归一成 ReportSaveResult(驼峰、versionNo 为数字)交给编辑器。
|
|
646
|
+
return {
|
|
647
|
+
recordId: res.record_id,
|
|
648
|
+
templateVersionNo: res.template_version_no ?? '',
|
|
649
|
+
versionNo: res.version_no,
|
|
650
|
+
statusCode: res.status_code,
|
|
651
|
+
savedAt: new Date(o.now()).toISOString(),
|
|
652
|
+
...(res.field_errors ? { fieldErrors: res.field_errors.map(e => ({ fieldId: e.field_id, code: e.code, message: e.message ?? '' })) } : {})
|
|
653
|
+
};
|
|
654
|
+
} catch (error) {
|
|
655
|
+
if (error instanceof FakeSaveError) throw Object.assign(new Error(error.message), { code: error.code });
|
|
656
|
+
throw error;
|
|
657
|
+
}
|
|
658
|
+
}
|
|
659
|
+
},
|
|
660
|
+
log: {
|
|
661
|
+
debug: (m: string) => void logLines.push({ level: 'debug', message: m }),
|
|
662
|
+
info: (m: string) => void logLines.push({ level: 'info', message: m }),
|
|
663
|
+
warn: (m: string) => void logLines.push({ level: 'warn', message: m }),
|
|
664
|
+
error: (m: string) => void logLines.push({ level: 'error', message: m })
|
|
665
|
+
},
|
|
666
|
+
interactiveSession: { sessionId: 'is-fake', markDirty: () => undefined }
|
|
667
|
+
};
|
|
668
|
+
},
|
|
669
|
+
disconnect() {
|
|
670
|
+
connected = false;
|
|
671
|
+
bridgeConn?.close();
|
|
672
|
+
},
|
|
673
|
+
reconnect() {
|
|
674
|
+
ensureConnected();
|
|
675
|
+
},
|
|
676
|
+
clientFrames: () => clone(sentFrames),
|
|
677
|
+
resyncs: () => [...resyncReasons],
|
|
678
|
+
logs: () => [...logLines]
|
|
679
|
+
};
|
|
680
|
+
return host;
|
|
681
|
+
}
|
|
682
|
+
|
|
683
|
+
// ════════════════════════════ 二、一致性套件 ════════════════════════════
|
|
684
|
+
|
|
685
|
+
/** 编辑器前端适配器:把你的编辑器状态层接到套件上。行键一律用编辑器当前看到的键(新增行确认后会换成 Mirror 行键)。 */
|
|
686
|
+
export interface HostMirrorEditorAdapter {
|
|
687
|
+
setText(dataTableId: string, rowKey: string, fieldId: string, text: string): void | Promise<void>;
|
|
688
|
+
getText(dataTableId: string, rowKey: string, fieldId: string): string | undefined;
|
|
689
|
+
/** 追加一行明细,返回编辑器给它的行键。 */
|
|
690
|
+
appendRow(dataTableId: string): string | Promise<string>;
|
|
691
|
+
/** 编辑器当前显示的行键(显示顺序)。 */
|
|
692
|
+
rowKeys(dataTableId: string): string[];
|
|
693
|
+
/** 触发宿主驱动保存,返回记录 ID 等(任意包含 recordId / record_id 的对象)。 */
|
|
694
|
+
save(): Promise<unknown>;
|
|
695
|
+
dispose?(): void;
|
|
696
|
+
}
|
|
697
|
+
|
|
698
|
+
export interface HostMirrorConformanceContext {
|
|
699
|
+
host: FakeHostMirror;
|
|
700
|
+
bridge: FakeEditorBridge;
|
|
701
|
+
boundSession: Record<string, unknown>;
|
|
702
|
+
}
|
|
703
|
+
|
|
704
|
+
export interface HostMirrorConformanceReport {
|
|
705
|
+
checks: Array<{ name: string; ok: boolean; detail?: string }>;
|
|
706
|
+
failures: string[];
|
|
707
|
+
}
|
|
708
|
+
|
|
709
|
+
const settle = async (rounds = 4) => {
|
|
710
|
+
for (let i = 0; i < rounds; i++) await new Promise(r => setTimeout(r, 0));
|
|
711
|
+
};
|
|
712
|
+
|
|
713
|
+
/** 套件使用的表单:主表 t_main(f_name / f_amount / f_secret 隐藏 / f_ro 只读)+ 明细 t_items(f_item)。 */
|
|
714
|
+
export const CONFORMANCE_FORM: FakeHostMirrorOptions = {
|
|
715
|
+
session_id: 'es-conformance',
|
|
716
|
+
tables: [
|
|
717
|
+
{ data_table_id: 't_main', role: 'main', fields: ['f_name', 'f_amount', 'f_secret', 'f_ro'] },
|
|
718
|
+
{ data_table_id: 't_items', role: 'detail', fields: ['f_item'] }
|
|
719
|
+
],
|
|
720
|
+
hidden_field_ids: ['f_secret'],
|
|
721
|
+
readonly_field_ids: ['f_ro'],
|
|
722
|
+
replay_frames: 1
|
|
723
|
+
};
|
|
724
|
+
|
|
725
|
+
const text = (s: string): EditorTypedValue => ({ raw: s, text: s });
|
|
726
|
+
|
|
727
|
+
/**
|
|
728
|
+
* runHostMirrorConformance —— 对编辑器前端跑 host-mirror 一致性检查(十一项,任一失败进 failures)。
|
|
729
|
+
* factory 拿到替身宿主、编辑器桥与 boundSession,返回适配器。表单结构见 CONFORMANCE_FORM。
|
|
730
|
+
*/
|
|
731
|
+
export async function runHostMirrorConformance(
|
|
732
|
+
factory: (ctx: HostMirrorConformanceContext) => HostMirrorEditorAdapter | Promise<HostMirrorEditorAdapter>
|
|
733
|
+
): Promise<HostMirrorConformanceReport> {
|
|
734
|
+
const checks: HostMirrorConformanceReport['checks'] = [];
|
|
735
|
+
const check = (name: string, ok: boolean, detail?: string) => checks.push({ name, ok, ...(ok || !detail ? {} : { detail }) });
|
|
736
|
+
const host = createFakeHostMirror(CONFORMANCE_FORM);
|
|
737
|
+
host.seed('t_main', 'main:0', 'f_name', text('Anna'));
|
|
738
|
+
host.seed('t_main', 'main:0', 'f_secret', text('top-secret'));
|
|
739
|
+
host.seed('t_main', 'main:0', 'f_ro', text('fixed'));
|
|
740
|
+
host.seed('t_items', 'row:1', 'f_item', text('pen'));
|
|
741
|
+
const bridge = host.bridge();
|
|
742
|
+
const adapter = await factory({ host, bridge, boundSession: host.boundSession() });
|
|
743
|
+
try {
|
|
744
|
+
await settle();
|
|
745
|
+
check('initial-snapshot-rendered', adapter.getText('t_main', 'main:0', 'f_name') === 'Anna' && adapter.getText('t_items', 'row:1', 'f_item') === 'pen',
|
|
746
|
+
`got name=${adapter.getText('t_main', 'main:0', 'f_name')} item=${adapter.getText('t_items', 'row:1', 'f_item')}`);
|
|
747
|
+
check('hidden-field-not-visible', adapter.getText('t_main', 'main:0', 'f_secret') === undefined, 'hidden field value reached the editor');
|
|
748
|
+
|
|
749
|
+
await adapter.setText('t_main', 'main:0', 'f_name', 'Bob');
|
|
750
|
+
await settle();
|
|
751
|
+
check('user-edit-reaches-mirror', host.value('t_main', 'main:0', 'f_name')?.text === 'Bob', `mirror has ${host.value('t_main', 'main:0', 'f_name')?.text}`);
|
|
752
|
+
|
|
753
|
+
await adapter.setText('t_main', 'main:0', 'f_ro', 'hacked');
|
|
754
|
+
await settle();
|
|
755
|
+
check('readonly-edit-rolled-back',
|
|
756
|
+
host.value('t_main', 'main:0', 'f_ro')?.text === 'fixed' && adapter.getText('t_main', 'main:0', 'f_ro') === 'fixed',
|
|
757
|
+
`mirror=${host.value('t_main', 'main:0', 'f_ro')?.text} editor=${adapter.getText('t_main', 'main:0', 'f_ro')}`);
|
|
758
|
+
|
|
759
|
+
const before = host.clientFrames().length;
|
|
760
|
+
host.businessWrite('action', [{ data_table_id: 't_main', row_key: 'main:0', field_id: 'f_amount', value: { raw: 42, text: '42' } }]);
|
|
761
|
+
await settle();
|
|
762
|
+
const echoed = host
|
|
763
|
+
.clientFrames()
|
|
764
|
+
.slice(before)
|
|
765
|
+
.some(f => JSON.stringify(f).includes('"f_amount"'));
|
|
766
|
+
check('business-write-rendered-not-echoed', adapter.getText('t_main', 'main:0', 'f_amount') === '42' && !echoed,
|
|
767
|
+
`editor=${adapter.getText('t_main', 'main:0', 'f_amount')} echoed=${echoed}`);
|
|
768
|
+
|
|
769
|
+
const newKey = await adapter.appendRow('t_items');
|
|
770
|
+
await settle();
|
|
771
|
+
const rowsAfterAppend = host.rowKeys('t_items');
|
|
772
|
+
const editorRows = adapter.rowKeys('t_items');
|
|
773
|
+
const added = rowsAfterAppend.find(k => k !== 'row:1');
|
|
774
|
+
check('append-row-reaches-mirror', rowsAfterAppend.length === 2 && !!added && editorRows.includes(added),
|
|
775
|
+
`mirror rows=${rowsAfterAppend.join(',')} editor rows=${editorRows.join(',')} (appendRow returned ${newKey})`);
|
|
776
|
+
if (added) {
|
|
777
|
+
await adapter.setText('t_items', editorRows.includes(added) ? added : newKey, 'f_item', 'ink');
|
|
778
|
+
await settle();
|
|
779
|
+
check('edit-on-new-row-reaches-mirror', host.value('t_items', added, 'f_item')?.text === 'ink', `mirror has ${host.value('t_items', added, 'f_item')?.text}`);
|
|
780
|
+
} else {
|
|
781
|
+
check('edit-on-new-row-reaches-mirror', false, 'no new row in mirror');
|
|
782
|
+
}
|
|
783
|
+
|
|
784
|
+
const [bizRow] = host.businessAppendRows('fetch', 't_items', 1);
|
|
785
|
+
await settle();
|
|
786
|
+
check('business-append-rendered', adapter.rowKeys('t_items').includes(bizRow), `editor rows=${adapter.rowKeys('t_items').join(',')}`);
|
|
787
|
+
|
|
788
|
+
host.disconnect();
|
|
789
|
+
host.businessWrite('linkage', [{ data_table_id: 't_main', row_key: 'main:0', field_id: 'f_amount', value: { raw: 1, text: '1' } }]);
|
|
790
|
+
host.businessWrite('linkage', [{ data_table_id: 't_main', row_key: 'main:0', field_id: 'f_name', value: text('Carol') }]);
|
|
791
|
+
host.reconnect();
|
|
792
|
+
await settle();
|
|
793
|
+
check('resync-after-buffer-overflow', adapter.getText('t_main', 'main:0', 'f_name') === 'Carol' && adapter.getText('t_main', 'main:0', 'f_amount') === '1',
|
|
794
|
+
`editor name=${adapter.getText('t_main', 'main:0', 'f_name')} amount=${adapter.getText('t_main', 'main:0', 'f_amount')}`);
|
|
795
|
+
|
|
796
|
+
let saveDetail = '';
|
|
797
|
+
let saveOk = false;
|
|
798
|
+
try {
|
|
799
|
+
const res = (await adapter.save()) as Record<string, unknown> | undefined;
|
|
800
|
+
const rid = res?.recordId ?? res?.record_id;
|
|
801
|
+
const all = host.saved();
|
|
802
|
+
const rec = all[all.length - 1];
|
|
803
|
+
const main = rec?.rows.find(r => r.data_table_id === 't_main');
|
|
804
|
+
saveOk = !!rec && rid === rec.record_id && main?.fields.f_name?.text === 'Carol' && !('f_secret' in (main?.fields ?? {}));
|
|
805
|
+
saveDetail = `result=${JSON.stringify(res)} saved=${JSON.stringify(rec)}`;
|
|
806
|
+
} catch (error) {
|
|
807
|
+
saveDetail = String(error);
|
|
808
|
+
}
|
|
809
|
+
check('host-driven-save', saveOk, saveDetail);
|
|
810
|
+
|
|
811
|
+
const frames = host.clientFrames() as Array<Record<string, unknown>>;
|
|
812
|
+
let lastSeq = 0;
|
|
813
|
+
let shapeOk = true;
|
|
814
|
+
let shapeDetail = '';
|
|
815
|
+
for (const f of frames) {
|
|
816
|
+
const type = String(f.type);
|
|
817
|
+
if (f.v !== 1 || !CLIENT_TYPES.includes(type)) {
|
|
818
|
+
shapeOk = false;
|
|
819
|
+
shapeDetail = `bad frame ${JSON.stringify(f)}`;
|
|
820
|
+
break;
|
|
821
|
+
}
|
|
822
|
+
if (type === 'edit.fields' || type === 'edit.rows') {
|
|
823
|
+
const seq = Number(f.seq);
|
|
824
|
+
// 重发帧(重连后)可以等于已发过的序号,但不得倒退到更早之前未发过的序号之外。
|
|
825
|
+
if (!Number.isInteger(seq) || seq <= 0 || seq > lastSeq + 1) {
|
|
826
|
+
shapeOk = false;
|
|
827
|
+
shapeDetail = `edit frame seq ${String(f.seq)} after ${lastSeq}`;
|
|
828
|
+
break;
|
|
829
|
+
}
|
|
830
|
+
lastSeq = Math.max(lastSeq, seq);
|
|
831
|
+
}
|
|
832
|
+
}
|
|
833
|
+
check('client-frames-well-formed', shapeOk, shapeDetail);
|
|
834
|
+
} finally {
|
|
835
|
+
adapter.dispose?.();
|
|
836
|
+
}
|
|
837
|
+
return { checks, failures: checks.filter(c => !c.ok).map(c => `${c.name}${c.detail ? `: ${c.detail}` : ''}`) };
|
|
838
|
+
}
|