@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.
Files changed (44) hide show
  1. package/LICENSE +202 -0
  2. package/NOTICE +9 -0
  3. package/README.md +48 -2
  4. package/package.json +141 -4
  5. package/src/action-designer.ts +250 -0
  6. package/src/attachment-url.ts +195 -0
  7. package/src/auth/index.ts +6 -0
  8. package/src/auth/qrcode.ts +519 -0
  9. package/src/auth/types.ts +261 -0
  10. package/src/display-style.ts +250 -0
  11. package/src/editor-frame.ts +623 -0
  12. package/src/editor-session.ts +1214 -0
  13. package/src/editor-testing.ts +838 -0
  14. package/src/editor.ts +1641 -0
  15. package/src/frame-transport.ts +491 -0
  16. package/src/frontend-routes.ts +99 -0
  17. package/src/hooks.ts +48 -0
  18. package/src/host-caps.ts +93 -0
  19. package/src/i18n.ts +238 -0
  20. package/src/im-panel.ts +132 -0
  21. package/src/image-tools.ts +91 -0
  22. package/src/index.ts +118 -0
  23. package/src/interactive-session.ts +94 -0
  24. package/src/nahida-im.ts +391 -0
  25. package/src/nahida-ws.ts +23 -0
  26. package/src/org-directory.ts +78 -0
  27. package/src/oz-realtime.ts +144 -0
  28. package/src/page.ts +404 -0
  29. package/src/print.ts +393 -0
  30. package/src/surface.ts +281 -0
  31. package/src/theme-mocks.ts +140 -0
  32. package/src/theme.ts +125 -0
  33. package/src/ui-fixtures/confirm.ts +16 -0
  34. package/src/ui-fixtures/entity-picker.ts +24 -0
  35. package/src/ui-fixtures/expression-editor.ts +52 -0
  36. package/src/ui-fixtures/image-cropper.ts +23 -0
  37. package/src/ui-fixtures/index.ts +16 -0
  38. package/src/ui-fixtures/org-tri-picker.ts +19 -0
  39. package/src/ui-fixtures/prompt.ts +19 -0
  40. package/src/ui-fixtures/record-picker.ts +17 -0
  41. package/src/ui-fixtures/template-picker.ts +13 -0
  42. package/src/ui-mocks.ts +250 -0
  43. package/src/ui.ts +479 -0
  44. package/src/workflow-designer.ts +475 -0
@@ -0,0 +1,623 @@
1
+ /**
2
+ * editor-frame.ts —— 编辑器 surface(designer / runtime)的沙箱档入口与 host-mirror 帧协议 `editor-frame/1`
3
+ * (SDK 1.1.0-tp.14 起)。
4
+ *
5
+ * 链路:插件前端(编辑器)↔ 宿主前端(designer-host,持有 WS 与桥)↔ 宿主通用 editor transport ↔ 表单数据权威层 Mirror。
6
+ * 设计态用沙箱档入口与 typed 设计态桥;填报态另用帧协议。
7
+ *
8
+ * 一、沙箱档。第三方编辑器一律在宿主沙箱框架(iframe)里运行,不能再靠 Vue `defineExpose` 让宿主拿组件实例:
9
+ * - 插件写 `export const createSurface = defineEditorSurface(ctx => ({ component, props }))`,两种挂载档写法一致;
10
+ * - 宿主 → 编辑器只能调 {@link EDITOR_FRAME_EXPOSED_METHODS} 列出的组件方法(经框架 expose 消息转到组件实例,
11
+ * 组件照常 `defineExpose` 这些方法即可);
12
+ * - 编辑器 → 宿主只能用 {@link EDITOR_FRAME_BRIDGE_KEYS} 列出的桥键,每个键只开放 {@link EDITOR_FRAME_HOST_METHODS}
13
+ * 里的方法;白名单外的能力即使在 manifest host_caps 声明也不下发;方法一律异步(返回 Promise);
14
+ * - iframe 不持有编辑器会话 attach token:帧 WS 由宿主页持有,经桥键 `editorFrames` 转发({@link EditorFrameChannel})。
15
+ * 宿主侧白名单实现在宿主前端,与本文件同口径。
16
+ *
17
+ * 二、帧协议 editor-frame/1(host-mirror 模式):帧外形 `{v:1, type, seq?, ack?, body}`;宿主是唯一服务端;
18
+ * 浏览器帧 seq 由编辑器前端维护、宿主经 ack 确认;服务端帧 seq 由宿主按会话单调分配并等于 Mirror 写序。
19
+ * body 键名 snake_case,与 proto editor/v1 editor_session.proto 的 *Body 消息一致。
20
+ * - 用户编辑:`edit.fields` / `edit.rows` 投影进 Mirror(editor 自身内部事务豁免);
21
+ * - 业务写(动作 / 取数 / 联动 / 流程写回):宿主改 Mirror 后推 `mirror.patch`,编辑器**只渲染、不回投**,
22
+ * 与在途编辑冲突时以 patch 为准(Mirror 是权威);
23
+ * - 缺口:宿主保留最近一段 patch(建议 256 条或 30 秒),超出发 `resync.required`,编辑器重拉快照(`snapshot` 帧);
24
+ * 编辑器自己需要快照时经帧通道 `resync()` 请宿主页带 `?snapshot=1` 重新附着。
25
+ * 本文件只给类型与 frame transport 封装({@link createEditorFrameTransport}:发帧编号、ack 跟踪、服务端缺口检测);
26
+ * 快照应用、ack / 回滚、重拉快照与宿主驱动保存的完整客户端 helper 见 `@kimposoft/plugin-sdk/editor-session`
27
+ * (createHostMirrorSession,tp.15 起),测试替身与一致性套件见 `@kimposoft/plugin-sdk/editor-testing`。
28
+ * sidecar 模式(表格编辑器)不使用本协议。
29
+ */
30
+ import { definePluginSurface, type SurfaceCreateInput, type SurfaceMountResult } from './surface';
31
+ import type { InteractiveSessionHandle } from './interactive-session';
32
+ import type {
33
+ BoundEditorSessionSnapshot,
34
+ EditorEffectEnvelope,
35
+ EditorFormMode,
36
+ EditorPluginEntry,
37
+ EditorRecordSnapshot,
38
+ EditorScene,
39
+ EditorSessionMeta,
40
+ EditorSessionMode,
41
+ EditorTypedValue,
42
+ AssetClient,
43
+ EditorPrintClient,
44
+ HostNavigationClient
45
+ } from './editor';
46
+ import type { OrgDirectoryClient } from './org-directory';
47
+
48
+ // ════════════════════════════ 一、沙箱档入口 ════════════════════════════
49
+
50
+ /** 编辑器 surface 类型。 */
51
+ export const EDITOR_SURFACE_TYPES = ['designer', 'runtime'] as const;
52
+
53
+ /** 沙箱档宿主为编辑器 surface 组装的 bridge 白名单键(宿主再按 manifest host_caps 裁剪,未声明即不可见)。 */
54
+ export const EDITOR_FRAME_BRIDGE_KEYS = [
55
+ 'interactiveSession',
56
+ 'designData',
57
+ 'templateSchema',
58
+ 'recordData',
59
+ 'actions',
60
+ 'editorFrames',
61
+ 'assets',
62
+ 'navigation',
63
+ // 组织目录只读查询:成员 / 部门控件选择所需的搜索与按 ID 取名,宿主按授予与数据权限裁剪。
64
+ 'orgDirectory',
65
+ // 宿主代打印:只给声明档案 print.basic 的编辑器;编辑器交可打印内容,宿主在主文档打印。
66
+ 'print',
67
+ 'message',
68
+ 'log',
69
+ 'i18n',
70
+ 'timezone',
71
+ 'theme'
72
+ ] as const;
73
+
74
+ export type EditorFrameBridgeKey = (typeof EDITOR_FRAME_BRIDGE_KEYS)[number];
75
+
76
+ /**
77
+ * 沙箱档每个桥键开放的方法(其余方法即使宿主同源实现里有也不下发)。
78
+ * i18n / timezone / theme / interactiveSession 按框架既有规则下发(快照 + 订阅),不在此表。
79
+ */
80
+ export const EDITOR_FRAME_HOST_METHODS: Readonly<Record<string, readonly string[]>> = {
81
+ designData: [
82
+ 'open',
83
+ 'init',
84
+ 'save',
85
+ 'loadExpressionCatalog',
86
+ 'defineFields',
87
+ 'defineMainTableFields',
88
+ 'defineExtensionTable',
89
+ 'defineExtensionTableFields',
90
+ 'openActionDesigner',
91
+ // 读模板已有表与字段、写字段属性、删字段(宿主按字段模型与删除影响预检裁决)。
92
+ 'listTemplateModel',
93
+ 'updateFields',
94
+ 'deleteFields'
95
+ ],
96
+ templateSchema: ['defineFields'],
97
+ recordData: ['open', 'enterEdit', 'save', 'close', 'notifySaved', 'confirmBeforeSave', 'invokeHostAction', 'validate'],
98
+ actions: ['emit', 'listManualActions', 'listFieldClickFields', 'waitAsyncSettled', 'postContinuation', 'onChainActivity'],
99
+ // resync(支持编辑器重同步的宿主才下发):请宿主页带 ?snapshot=1 重新附着、补发快照帧(沙箱档补快照入口)。
100
+ editorFrames: ['send', 'subscribe', 'resync'],
101
+ // 沙箱档没有网络,资产一律经宿主代取——upload 上传、preview 取 Blob(框架内 URL.createObjectURL
102
+ // 显示)、download 由宿主在主文档触发下载;不再开放 getUrl(宿主地址带会话,框架里用不了)。
103
+ assets: ['upload', 'preview', 'download'],
104
+ // selectRecord:宿主代选记录——宿主弹出既有记录选择器,只返回用户选中的那一条引用。
105
+ navigation: ['openRecord', 'pickRecord', 'openRecordList', 'openFormFill', 'selectRecord'],
106
+ orgDirectory: ['listDepartments', 'listMembers', 'searchUsers', 'resolveUsers', 'resolveDepartments', 'me'],
107
+ print: ['printHtml', 'printPdf'],
108
+ message: ['success', 'error', 'warning', 'info'],
109
+ log: ['debug', 'info', 'warn', 'error']
110
+ };
111
+
112
+ /**
113
+ * 宿主可经框架 expose 调用的编辑器组件方法(替代同源档的 Vue defineExpose 契约;三个必需 + 可选任务方法)。
114
+ * 组件照常 defineExpose 这些方法;沙箱档里返回值须是可结构化克隆的纯数据(Blob 可以,函数 / 类实例会被剥离)。
115
+ */
116
+ export const EDITOR_FRAME_EXPOSED_METHODS = [
117
+ 'applyEffectEnvelope',
118
+ 'executeHostCommand',
119
+ 'getCapabilities',
120
+ 'exportPdfBlob',
121
+ 'getTaskDraftChanges',
122
+ 'applyTaskDraftChanges',
123
+ 'setTaskFieldPolicy',
124
+ 'validateTaskRequired',
125
+ // 任务工作台附件上传(File 可结构化克隆,宿主把文件交给编辑器、回执是纯数据)。
126
+ 'uploadTaskAttachment'
127
+ ] as const;
128
+
129
+ export type EditorFrameExposedMethod = (typeof EDITOR_FRAME_EXPOSED_METHODS)[number];
130
+
131
+ /** 判断某宿主桥方法在沙箱档是否开放。 */
132
+ export function isEditorFrameHostMethodAllowed(key: string, method: string): boolean {
133
+ return (EDITOR_FRAME_HOST_METHODS[key] ?? []).includes(method);
134
+ }
135
+
136
+ /** 判断宿主能否经 expose 调用某编辑器方法。 */
137
+ export function isEditorFrameExposedMethod(method: string): method is EditorFrameExposedMethod {
138
+ return (EDITOR_FRAME_EXPOSED_METHODS as readonly string[]).includes(method);
139
+ }
140
+
141
+ /**
142
+ * 帧通道(桥键 `editorFrames`):宿主页持有 WS,经 MessageChannel 把帧转给 iframe。
143
+ * 同源档 `subscribe` 返回 `() => void`,沙箱档返回 `Promise<() => void>`,用 `disposerOf()`(from './frame-transport')统一。
144
+ */
145
+ export interface EditorFrameChannel {
146
+ /** 发一帧给宿主(宿主校验后写入 WS)。 */
147
+ send(frame: EditorClientFrame): void | Promise<void>;
148
+ /** 订阅服务端帧。 */
149
+ subscribe(listener: (frame: unknown) => void): (() => void) | Promise<() => void>;
150
+ /**
151
+ * 请宿主页带 `?snapshot=1` 重新附着(宿主附着后先补发 snapshot 帧)。可选:旧宿主不下发该方法,
152
+ * createHostMirrorSession 据此退回「stale + resync-needed」。reason 只用于宿主日志。
153
+ */
154
+ resync?(reason?: string): void | Promise<void>;
155
+ }
156
+
157
+ /**
158
+ * 沙箱档资产桥:框架 CSP 没有网络(connect-src 'none',img-src 只放 data: blob:),
159
+ * 宿主代编辑器上传、取字节、触发下载;框架拿到的只有纯数据回执与 Blob。方法一律异步。
160
+ */
161
+ export type EditorFrameAssetsBridge = Required<Pick<AssetClient, 'upload' | 'preview' | 'download'>>;
162
+
163
+ /** 沙箱档导航桥:同源档 {@link HostNavigationClient} 的白名单方法(含宿主代选记录 selectRecord)。 */
164
+ export type EditorFrameNavigationBridge = Partial<
165
+ Pick<HostNavigationClient, 'openRecord' | 'pickRecord' | 'openRecordList' | 'openFormFill' | 'selectRecord'>
166
+ >;
167
+
168
+ /**
169
+ * 沙箱档组织目录桥:只读、按当前用户数据权限裁剪;成员结果不带头像地址、手机号、邮箱
170
+ * (框架里取不到受会话保护的头像,联系方式也不是选择控件所需)。
171
+ */
172
+ export type EditorFrameOrgDirectoryBridge = Partial<OrgDirectoryClient>;
173
+
174
+ /** 沙箱档编辑器拿到的宿主桥(全部可选:宿主按声明裁剪,读未声明的键可能抛错,请经 defineEditorSurface 取)。 */
175
+ export interface EditorFrameHostBridge {
176
+ interactiveSession?: InteractiveSessionHandle;
177
+ designData?: unknown;
178
+ templateSchema?: unknown;
179
+ recordData?: unknown;
180
+ actions?: unknown;
181
+ editorFrames?: EditorFrameChannel;
182
+ /** 资产桥(宿主代上传 / 代取 Blob / 代下载),见 {@link EditorFrameAssetsBridge}。 */
183
+ assets?: EditorFrameAssetsBridge;
184
+ /** 导航(含宿主代选记录 selectRecord),见 {@link EditorFrameNavigationBridge}。 */
185
+ navigation?: EditorFrameNavigationBridge;
186
+ /** 组织目录只读查询(声明 host_caps `editor.orgDirectory` 才下发)。 */
187
+ orgDirectory?: EditorFrameOrgDirectoryBridge;
188
+ /** 宿主代打印(声明档案 `print.basic` 才下发)。 */
189
+ print?: EditorPrintClient;
190
+ message?: unknown;
191
+ log?: { debug(m: string, c?: unknown): unknown; info(m: string, c?: unknown): unknown; warn(m: string, c?: unknown): unknown; error(m: string, c?: unknown): unknown };
192
+ i18n?: unknown;
193
+ timezone?: unknown;
194
+ theme?: unknown;
195
+ }
196
+
197
+ /** defineEditorSurface 交给工厂的上下文。 */
198
+ export interface EditorSurfaceContext {
199
+ input: SurfaceCreateInput;
200
+ /** designer(设计态)或 runtime(填报态)。 */
201
+ entry: EditorPluginEntry;
202
+ /** 只含白名单键的宿主桥(缺失的键为 undefined)。 */
203
+ hostBridge: EditorFrameHostBridge;
204
+ interactiveSession: InteractiveSessionHandle;
205
+ /** 填报态宿主已开的 bound session(设计态或宿主未下发时为 undefined)。 */
206
+ boundSession?: BoundEditorSessionSnapshot;
207
+ scene?: EditorScene;
208
+ formMode?: EditorFormMode;
209
+ }
210
+
211
+ /**
212
+ * defineEditorSurface —— 编辑器专用的 definePluginSurface(tp.14 起):两种挂载档写法一致,沙箱档自动启动框架运行时并做
213
+ * 前端域自检(designer / runtime 需 frontend.surface + frontend.interactive-session)。
214
+ * 只把白名单键交给工厂;缺交互会话即抛错(快速失败);非 designer / runtime 挂载点抛错。
215
+ *
216
+ * @example
217
+ * ```ts
218
+ * export const createSurface = defineEditorSurface(({ entry, hostBridge, boundSession }) => ({
219
+ * component: entry === 'designer' ? FormDesigner : FormRuntime,
220
+ * props: { hostBridge, boundSession }
221
+ * }));
222
+ * ```
223
+ */
224
+ export function defineEditorSurface(factory: (ctx: EditorSurfaceContext) => SurfaceMountResult): (input: SurfaceCreateInput) => SurfaceMountResult {
225
+ return definePluginSurface((input: SurfaceCreateInput) => {
226
+ const entry = String(input.surfaceType);
227
+ if (!(EDITOR_SURFACE_TYPES as readonly string[]).includes(entry)) {
228
+ throw new Error(`defineEditorSurface: unsupported surface ${entry}`);
229
+ }
230
+ const props = (input.props ?? {}) as Record<string, unknown>;
231
+ const raw = (input.hostBridge ?? props.hostBridge ?? {}) as Record<string, unknown>;
232
+ const read = (key: string): unknown => {
233
+ try {
234
+ return raw[key];
235
+ } catch {
236
+ // 宿主按 host_caps 裁剪的 Proxy 读未声明键会抛错:视为缺失。
237
+ return undefined;
238
+ }
239
+ };
240
+ const hostBridge: Record<string, unknown> = {};
241
+ for (const key of EDITOR_FRAME_BRIDGE_KEYS) {
242
+ const value = read(key);
243
+ if (value !== undefined) hostBridge[key] = value;
244
+ }
245
+ const interactiveSession = hostBridge.interactiveSession as InteractiveSessionHandle | undefined;
246
+ if (!interactiveSession) {
247
+ throw new Error('defineEditorSurface: host bridge must include platform.interactiveSession');
248
+ }
249
+ return factory({
250
+ input,
251
+ entry: entry as EditorPluginEntry,
252
+ hostBridge: hostBridge as EditorFrameHostBridge,
253
+ interactiveSession,
254
+ boundSession: props.boundSession as BoundEditorSessionSnapshot | undefined,
255
+ scene: props.scene as EditorScene | undefined,
256
+ formMode: props.formMode as EditorFormMode | undefined
257
+ });
258
+ });
259
+ }
260
+
261
+ // ════════════════════════════ 二、帧协议 editor-frame/1 ════════════════════════════
262
+
263
+ /** 协议标识(BoundEditorSessionSnapshot.frameProtocol)。 */
264
+ export const EDITOR_FRAME_PROTOCOL = 'editor-frame/1';
265
+ /** 帧外形 v 唯一取值。 */
266
+ export const EDITOR_FRAME_VERSION = 1;
267
+
268
+ /** 帧类型闭集(v1)。 */
269
+ export const EDITOR_FRAME_TYPES = [
270
+ 'attached',
271
+ 'ping',
272
+ 'pong',
273
+ 'edit.fields',
274
+ 'edit.rows',
275
+ 'ack',
276
+ 'mirror.patch',
277
+ 'calc.state',
278
+ 'effects',
279
+ 'session.meta',
280
+ 'error',
281
+ 'resync.required',
282
+ 'snapshot'
283
+ ] as const;
284
+
285
+ export type EditorFrameType = (typeof EDITOR_FRAME_TYPES)[number];
286
+
287
+ /** 编辑器前端可发出的帧类型(宿主收到其它类型报 EDITOR_FRAME_PROTOCOL)。 */
288
+ export const EDITOR_CLIENT_FRAME_TYPES = ['ping', 'pong', 'edit.fields', 'edit.rows', 'calc.state'] as const;
289
+ /** 宿主会发出的帧类型。 */
290
+ export const EDITOR_SERVER_FRAME_TYPES = [
291
+ 'attached',
292
+ 'ping',
293
+ 'pong',
294
+ 'ack',
295
+ 'mirror.patch',
296
+ 'calc.state',
297
+ 'effects',
298
+ 'session.meta',
299
+ 'error',
300
+ 'resync.required',
301
+ 'snapshot'
302
+ ] as const;
303
+
304
+ /** 宿主重放缓冲建议值。 */
305
+ export const EDITOR_FRAME_REPLAY_BUFFER = { frames: 256, seconds: 30 } as const;
306
+
307
+ /** 帧外形。 */
308
+ export interface EditorFrameV1<TType extends string = EditorFrameType, TBody = unknown> {
309
+ v: 1;
310
+ type: TType;
311
+ /** 浏览器帧:client seq;服务端帧:Mirror 写序(无写序的控制帧可省略)。 */
312
+ seq?: number;
313
+ /** 服务端帧确认的 client seq。 */
314
+ ack?: number;
315
+ body?: TBody;
316
+ }
317
+
318
+ // ---- 帧体(snake_case,与 proto editor/v1 editor_session.proto 一致)----
319
+
320
+ export interface EditorAttachedBody {
321
+ editor_session_id: string;
322
+ server_seq?: number;
323
+ client_ack?: number;
324
+ session_mode?: EditorSessionMode;
325
+ }
326
+
327
+ export interface EditorFieldDelta {
328
+ data_table_id: string;
329
+ /** 主表 'main:0',明细 'row:N'(Mirror 稳定行键)。 */
330
+ row_key: string;
331
+ field_id: string;
332
+ value?: EditorTypedValue;
333
+ }
334
+
335
+ export interface EditorEditFieldsBody {
336
+ deltas: EditorFieldDelta[];
337
+ /** computes=true 的编辑器带上本批对应的计算修订号。 */
338
+ calc_revision?: number;
339
+ }
340
+
341
+ export type EditorRowOp =
342
+ | { op: 'append'; data_table_id: string; client_row_keys: string[] }
343
+ | { op: 'remove'; data_table_id: string; row_keys: string[] }
344
+ | { op: 'reorder'; data_table_id: string; ordered_row_keys: string[] };
345
+
346
+ export interface EditorEditRowsBody {
347
+ ops: EditorRowOp[];
348
+ }
349
+
350
+ export interface EditorAckBody {
351
+ client_seq: number;
352
+ assigned_rows?: Array<{ data_table_id: string; client_row_key: string; row_key: string }>;
353
+ /** 被 Mirror 拒绝的写(权限、只读、类型):编辑器应把该处显示回滚到 Mirror 的值。 */
354
+ rejected?: Array<{ data_table_id: string; row_key: string; field_id: string; code: string; message?: string }>;
355
+ mirror_seq?: number;
356
+ }
357
+
358
+ export interface EditorRowChange {
359
+ kind: 'appended' | 'removed' | 'reordered';
360
+ data_table_id: string;
361
+ row_keys?: string[];
362
+ ordered_row_keys?: string[];
363
+ }
364
+
365
+ /** Mirror 业务写之后的渲染通知(编辑器只渲染、不回投;隐藏字段值已剔除)。 */
366
+ export interface EditorMirrorPatch {
367
+ seq: number;
368
+ cause?: 'action' | 'fetch' | 'linkage' | 'workflow' | 'prefill' | 'save' | 'host' | string;
369
+ fields?: EditorFieldDelta[];
370
+ rows?: EditorRowChange[];
371
+ mutation_id?: string;
372
+ }
373
+
374
+ /** 计算态(与 Mirror ReportCalcState 同语义)。 */
375
+ export type EditorCalcStatus = 'clean' | 'dirty' | 'calculating' | 'stale' | 'error';
376
+
377
+ export interface EditorFieldCalcState {
378
+ data_table_id: string;
379
+ row_key: string;
380
+ field_id: string;
381
+ status: EditorCalcStatus;
382
+ }
383
+
384
+ /** calc.state:编辑器 → 宿主为计算态上报(barrier 留空);宿主 → 编辑器为屏障结果。 */
385
+ export interface EditorCalcStateBody {
386
+ calc_revision: number;
387
+ states?: EditorFieldCalcState[];
388
+ barrier?: 'settled' | 'waiting';
389
+ }
390
+
391
+ export interface EditorEffectsBody {
392
+ envelope: EditorEffectEnvelope;
393
+ }
394
+
395
+ export interface EditorFrameErrorBody {
396
+ code: string;
397
+ message?: string;
398
+ ref_seq?: number;
399
+ }
400
+
401
+ export interface EditorResyncRequiredBody {
402
+ from_seq?: number;
403
+ latest_seq?: number;
404
+ reason?: string;
405
+ }
406
+
407
+ /** 编辑器前端发出的帧。 */
408
+ export type EditorClientFrame =
409
+ | EditorFrameV1<'ping' | 'pong', Record<string, never> | undefined>
410
+ | EditorFrameV1<'edit.fields', EditorEditFieldsBody>
411
+ | EditorFrameV1<'edit.rows', EditorEditRowsBody>
412
+ | EditorFrameV1<'calc.state', EditorCalcStateBody>;
413
+
414
+ /** 宿主发出的帧。 */
415
+ export type EditorServerFrame =
416
+ | EditorFrameV1<'attached', EditorAttachedBody>
417
+ | EditorFrameV1<'ping' | 'pong', Record<string, never> | undefined>
418
+ | EditorFrameV1<'ack', EditorAckBody>
419
+ | EditorFrameV1<'mirror.patch', EditorMirrorPatch>
420
+ | EditorFrameV1<'calc.state', EditorCalcStateBody>
421
+ | EditorFrameV1<'effects', EditorEffectsBody>
422
+ | EditorFrameV1<'session.meta', EditorSessionMeta>
423
+ | EditorFrameV1<'error', EditorFrameErrorBody>
424
+ | EditorFrameV1<'resync.required', EditorResyncRequiredBody>
425
+ | EditorFrameV1<'snapshot', EditorRecordSnapshot>;
426
+
427
+ /** 帧不合法(错误码 EDITOR_FRAME_PROTOCOL)。 */
428
+ export class EditorFrameProtocolError extends Error {
429
+ code = 'EDITOR_FRAME_PROTOCOL' as const;
430
+ constructor(message: string) {
431
+ super(`EDITOR_FRAME_PROTOCOL: ${message}`);
432
+ this.name = 'EditorFrameProtocolError';
433
+ }
434
+ }
435
+
436
+ function isRecord(value: unknown): value is Record<string, unknown> {
437
+ return value !== null && typeof value === 'object' && !Array.isArray(value);
438
+ }
439
+
440
+ function isSeq(value: unknown): boolean {
441
+ return value === undefined || (typeof value === 'number' && Number.isInteger(value) && value >= 0);
442
+ }
443
+
444
+ /** 判断是否为闭集内的帧类型。 */
445
+ export function isEditorFrameType(type: unknown): type is EditorFrameType {
446
+ return typeof type === 'string' && (EDITOR_FRAME_TYPES as readonly string[]).includes(type);
447
+ }
448
+
449
+ /**
450
+ * 解析宿主帧(接受 JSON 字符串或已解码对象):外形 / 版本 / 类型闭集 / 计数器 / 关键帧体字段不合法即抛 EditorFrameProtocolError。
451
+ * 未知的 body 键原样保留(读者须容忍未知键)。
452
+ */
453
+ export function parseEditorServerFrame(raw: unknown): EditorServerFrame {
454
+ let value = raw;
455
+ if (typeof raw === 'string') {
456
+ try {
457
+ value = JSON.parse(raw);
458
+ } catch {
459
+ throw new EditorFrameProtocolError('frame is not valid JSON');
460
+ }
461
+ }
462
+ if (!isRecord(value)) throw new EditorFrameProtocolError('frame must be an object');
463
+ if (value.v !== EDITOR_FRAME_VERSION) throw new EditorFrameProtocolError(`unsupported frame version ${String(value.v)}`);
464
+ if (!(EDITOR_SERVER_FRAME_TYPES as readonly string[]).includes(String(value.type))) {
465
+ throw new EditorFrameProtocolError(`unexpected server frame type ${String(value.type)}`);
466
+ }
467
+ if (!isSeq(value.seq) || !isSeq(value.ack)) throw new EditorFrameProtocolError('seq / ack must be non-negative integers');
468
+ const body = value.body;
469
+ if (body !== undefined && body !== null && !isRecord(body)) throw new EditorFrameProtocolError('body must be an object');
470
+ const b = (body ?? {}) as Record<string, unknown>;
471
+ switch (value.type) {
472
+ case 'mirror.patch':
473
+ if (!isSeq(b.seq) || b.seq === undefined) throw new EditorFrameProtocolError('mirror.patch requires body.seq');
474
+ break;
475
+ case 'ack':
476
+ if (!isSeq(b.client_seq) || b.client_seq === undefined) throw new EditorFrameProtocolError('ack requires body.client_seq');
477
+ break;
478
+ case 'error':
479
+ if (typeof b.code !== 'string' || !b.code) throw new EditorFrameProtocolError('error requires body.code');
480
+ break;
481
+ case 'attached':
482
+ if (typeof b.editor_session_id !== 'string' || !b.editor_session_id) throw new EditorFrameProtocolError('attached requires body.editor_session_id');
483
+ break;
484
+ default:
485
+ break;
486
+ }
487
+ return value as unknown as EditorServerFrame;
488
+ }
489
+
490
+ /** frame transport 事件。 */
491
+ export type EditorFrameTransportEvent =
492
+ | { kind: 'frame'; frame: EditorServerFrame }
493
+ /** 服务端 mirror.patch 序号出现缺口(expected 是期望的下一序号):等待宿主重放,超时或收到 resync.required 时重拉快照。 */
494
+ | { kind: 'gap'; expected: number; received: number }
495
+ /** 收到不合法帧(已丢弃)。 */
496
+ | { kind: 'protocol-error'; error: EditorFrameProtocolError };
497
+
498
+ /** createEditorFrameTransport 返回的封装。 */
499
+ export interface EditorFrameTransport {
500
+ /** 发 edit.fields,返回本帧 client seq。 */
501
+ sendEditFields(body: EditorEditFieldsBody): Promise<number>;
502
+ /** 发 edit.rows,返回本帧 client seq。 */
503
+ sendEditRows(body: EditorEditRowsBody): Promise<number>;
504
+ /** 发 calc.state(computes=true 的编辑器)。 */
505
+ sendCalcState(body: EditorCalcStateBody): Promise<number>;
506
+ /** 发 ping。 */
507
+ ping(): Promise<number>;
508
+ /** 订阅服务端帧与缺口 / 协议错误事件,返回同步退订函数。 */
509
+ onEvent(listener: (event: EditorFrameTransportEvent) => void): () => void;
510
+ /** 尚未被 ack 的 client seq(断线重连后据 attached.client_ack 决定重发哪些)。 */
511
+ pendingClientSeqs(): number[];
512
+ /** 已连续应用的最大 Mirror 写序。 */
513
+ lastServerSeq(): number;
514
+ /** 应用新快照后重置服务端写序基线(snapshot.mirror_seq)。 */
515
+ resetServerSeq(seq: number): void;
516
+ /** 关闭:退订通道,丢弃监听。 */
517
+ close(): void;
518
+ }
519
+
520
+ /**
521
+ * createEditorFrameTransport —— 在帧通道上封装 editor-frame/1 的编号与确认:
522
+ * - 发帧自动分配单调递增的 client seq,记入待确认集合,收到 ack(帧外形 ack 或 ack 帧体 client_seq)后移出;
523
+ * - 跟踪 mirror.patch 的服务端写序:连续则推进,出现缺口发 gap 事件(重复或更旧的 patch 丢弃不报);
524
+ * - 不合法帧丢弃并发 protocol-error 事件。
525
+ * 不负责快照应用与 patch 合并(那是编辑器自己的渲染逻辑),也不重连(WS 由宿主页持有)。
526
+ *
527
+ * @param channel 宿主桥 `editorFrames`
528
+ * @param options.initialServerSeq 打开应答 recordSnapshot.mirror_seq(缺省 0)
529
+ */
530
+ export function createEditorFrameTransport(channel: EditorFrameChannel, options: { initialServerSeq?: number } = {}): EditorFrameTransport {
531
+ let clientSeq = 0;
532
+ let serverSeq = Math.max(0, Math.trunc(options.initialServerSeq ?? 0));
533
+ let closed = false;
534
+ const pending = new Set<number>();
535
+ const listeners = new Set<(event: EditorFrameTransportEvent) => void>();
536
+ const emit = (event: EditorFrameTransportEvent) => {
537
+ listeners.forEach(listener => {
538
+ try {
539
+ listener(event);
540
+ } catch {
541
+ // 监听器异常不影响帧处理。
542
+ }
543
+ });
544
+ };
545
+ const acknowledge = (seq: unknown) => {
546
+ if (typeof seq !== 'number') return;
547
+ // ack 是累积确认:小于等于它的 client seq 都已处理。
548
+ for (const s of [...pending]) if (s <= seq) pending.delete(s);
549
+ };
550
+ const onRaw = (raw: unknown) => {
551
+ if (closed) return;
552
+ let frame: EditorServerFrame;
553
+ try {
554
+ frame = parseEditorServerFrame(raw);
555
+ } catch (error) {
556
+ emit({ kind: 'protocol-error', error: error instanceof EditorFrameProtocolError ? error : new EditorFrameProtocolError(String(error)) });
557
+ return;
558
+ }
559
+ acknowledge(frame.ack);
560
+ if (frame.type === 'ack') acknowledge((frame.body as EditorAckBody).client_seq);
561
+ if (frame.type === 'mirror.patch') {
562
+ const seq = (frame.body as EditorMirrorPatch).seq;
563
+ if (seq <= serverSeq) return; // 重放重复,丢弃
564
+ if (seq !== serverSeq + 1) {
565
+ emit({ kind: 'gap', expected: serverSeq + 1, received: seq });
566
+ return;
567
+ }
568
+ serverSeq = seq;
569
+ }
570
+ if (frame.type === 'snapshot') {
571
+ const seq = (frame.body as EditorRecordSnapshot | undefined)?.mirror_seq;
572
+ if (typeof seq === 'number') serverSeq = seq;
573
+ }
574
+ emit({ kind: 'frame', frame });
575
+ };
576
+ let unsubscribe: (() => void) | undefined;
577
+ let unsubscribed = false;
578
+ const sub = channel.subscribe(onRaw);
579
+ if (typeof sub === 'function') unsubscribe = sub;
580
+ else if (sub && typeof (sub as Promise<() => void>).then === 'function') {
581
+ (sub as Promise<() => void>).then(
582
+ fn => {
583
+ unsubscribe = fn;
584
+ if (unsubscribed) fn();
585
+ },
586
+ () => undefined
587
+ );
588
+ }
589
+ const send = async (type: EditorClientFrame['type'], body?: unknown): Promise<number> => {
590
+ if (closed) throw new Error('editor frame transport is closed');
591
+ clientSeq += 1;
592
+ const seq = clientSeq;
593
+ pending.add(seq);
594
+ await channel.send({ v: 1, type, seq, ...(body === undefined ? {} : { body }) } as EditorClientFrame);
595
+ return seq;
596
+ };
597
+ return {
598
+ sendEditFields: body => send('edit.fields', body),
599
+ sendEditRows: body => send('edit.rows', body),
600
+ sendCalcState: body => send('calc.state', body),
601
+ ping: () => send('ping', {}),
602
+ onEvent(listener) {
603
+ listeners.add(listener);
604
+ return () => listeners.delete(listener);
605
+ },
606
+ pendingClientSeqs: () => [...pending].sort((a, b) => a - b),
607
+ lastServerSeq: () => serverSeq,
608
+ resetServerSeq(seq) {
609
+ serverSeq = Math.max(0, Math.trunc(seq));
610
+ },
611
+ close() {
612
+ if (closed) return;
613
+ closed = true;
614
+ listeners.clear();
615
+ unsubscribed = true;
616
+ try {
617
+ unsubscribe?.();
618
+ } catch {
619
+ // 宿主侧退订失败不影响关闭。
620
+ }
621
+ }
622
+ };
623
+ }