@cool-office/collaboration-client 0.0.0-stage → 1.2.2

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 (82) hide show
  1. package/LICENSE +176 -0
  2. package/README.md +2 -2
  3. package/lib/cjs/chunk-4MGIQFAJ.js +40 -0
  4. package/lib/cjs/chunk-JHTS3PZO.js +1882 -0
  5. package/lib/cjs/facade.js +98 -0
  6. package/lib/cjs/index.js +209 -0
  7. package/lib/cjs/locale/ar-SA.js +25 -0
  8. package/lib/cjs/locale/ca-ES.js +25 -0
  9. package/lib/cjs/locale/de-DE.js +25 -0
  10. package/lib/cjs/locale/en-US.js +25 -0
  11. package/lib/cjs/locale/es-ES.js +25 -0
  12. package/lib/cjs/locale/fa-IR.js +25 -0
  13. package/lib/cjs/locale/fr-FR.js +25 -0
  14. package/lib/cjs/locale/id-ID.js +25 -0
  15. package/lib/cjs/locale/it-IT.js +25 -0
  16. package/lib/cjs/locale/ja-JP.js +25 -0
  17. package/lib/cjs/locale/ko-KR.js +25 -0
  18. package/lib/cjs/locale/pl-PL.js +25 -0
  19. package/lib/cjs/locale/pt-BR.js +25 -0
  20. package/lib/cjs/locale/ru-RU.js +25 -0
  21. package/lib/cjs/locale/sk-SK.js +25 -0
  22. package/lib/cjs/locale/vi-VN.js +25 -0
  23. package/lib/cjs/locale/zh-CN.js +25 -0
  24. package/lib/cjs/locale/zh-HK.js +25 -0
  25. package/lib/cjs/locale/zh-TW.js +25 -0
  26. package/lib/cjs/package.json +1 -0
  27. package/lib/es/chunk-4MGIQFAJ.js +16 -0
  28. package/lib/es/chunk-JHTS3PZO.js +1832 -0
  29. package/lib/es/facade.js +80 -0
  30. package/lib/es/index.js +186 -0
  31. package/lib/es/locale/ar-SA.js +7 -0
  32. package/lib/es/locale/ca-ES.js +7 -0
  33. package/lib/es/locale/de-DE.js +7 -0
  34. package/lib/es/locale/en-US.js +7 -0
  35. package/lib/es/locale/es-ES.js +7 -0
  36. package/lib/es/locale/fa-IR.js +7 -0
  37. package/lib/es/locale/fr-FR.js +7 -0
  38. package/lib/es/locale/id-ID.js +7 -0
  39. package/lib/es/locale/it-IT.js +7 -0
  40. package/lib/es/locale/ja-JP.js +7 -0
  41. package/lib/es/locale/ko-KR.js +7 -0
  42. package/lib/es/locale/pl-PL.js +7 -0
  43. package/lib/es/locale/pt-BR.js +7 -0
  44. package/lib/es/locale/ru-RU.js +7 -0
  45. package/lib/es/locale/sk-SK.js +7 -0
  46. package/lib/es/locale/vi-VN.js +7 -0
  47. package/lib/es/locale/zh-CN.js +7 -0
  48. package/lib/es/locale/zh-HK.js +7 -0
  49. package/lib/es/locale/zh-TW.js +7 -0
  50. package/lib/types/src/assets.d.ts +41 -0
  51. package/lib/types/src/authorization.d.ts +31 -0
  52. package/lib/types/src/changeset-submitter.d.ts +80 -0
  53. package/lib/types/src/document-object-resources.d.ts +4 -0
  54. package/lib/types/src/document-recovery.d.ts +82 -0
  55. package/lib/types/src/document-undo.d.ts +9 -0
  56. package/lib/types/src/facade/index.d.ts +46 -0
  57. package/lib/types/src/index.d.ts +14 -0
  58. package/lib/types/src/locale/ar-SA.d.ts +20 -0
  59. package/lib/types/src/locale/ca-ES.d.ts +20 -0
  60. package/lib/types/src/locale/de-DE.d.ts +20 -0
  61. package/lib/types/src/locale/en-US.d.ts +20 -0
  62. package/lib/types/src/locale/es-ES.d.ts +20 -0
  63. package/lib/types/src/locale/fa-IR.d.ts +20 -0
  64. package/lib/types/src/locale/fr-FR.d.ts +20 -0
  65. package/lib/types/src/locale/id-ID.d.ts +20 -0
  66. package/lib/types/src/locale/it-IT.d.ts +20 -0
  67. package/lib/types/src/locale/ja-JP.d.ts +20 -0
  68. package/lib/types/src/locale/ko-KR.d.ts +20 -0
  69. package/lib/types/src/locale/pl-PL.d.ts +20 -0
  70. package/lib/types/src/locale/pt-BR.d.ts +20 -0
  71. package/lib/types/src/locale/ru-RU.d.ts +20 -0
  72. package/lib/types/src/locale/sk-SK.d.ts +20 -0
  73. package/lib/types/src/locale/vi-VN.d.ts +20 -0
  74. package/lib/types/src/locale/zh-CN.d.ts +20 -0
  75. package/lib/types/src/locale/zh-HK.d.ts +20 -0
  76. package/lib/types/src/locale/zh-TW.d.ts +20 -0
  77. package/lib/types/src/revision-recovery.d.ts +93 -0
  78. package/lib/types/src/session.d.ts +85 -0
  79. package/lib/types/src/snapshot-server.d.ts +25 -0
  80. package/lib/types/src/socket.d.ts +46 -0
  81. package/lib/types/src/workspace.d.ts +100 -0
  82. package/package.json +160 -4
@@ -0,0 +1,1832 @@
1
+ import {
2
+ __decorateClass,
3
+ __decorateParam
4
+ } from "./chunk-4MGIQFAJ.js";
5
+
6
+ // src/snapshot-server.ts
7
+ import { IConfigService, Inject } from "@cool-office/core";
8
+ import { HTTPService } from "@cool-office/network";
9
+ import { UniverType } from "@cool-office/protocol";
10
+ var DEFAULT_SNAPSHOT_SERVER_URL = "/universer-api/snapshot";
11
+ var SNAPSHOT_URL_KEY = "SNAPSHOT_URL_KEY";
12
+ var COLLABORATION_CLIENT_PLUGIN_CONFIG_KEY = "collaboration-client.config";
13
+ function asBytes(value) {
14
+ if (value instanceof Uint8Array) return value;
15
+ if (typeof value !== "string" || !/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(value)) throw new Error("Invalid base64 snapshot data");
16
+ const text = atob(value);
17
+ return Uint8Array.from(text, (character) => character.charCodeAt(0));
18
+ }
19
+ function decodeSnapshot(snapshot) {
20
+ if (!snapshot) return snapshot;
21
+ const result = { ...snapshot };
22
+ if ((snapshot.type === UniverType.UNIVER_SHEET || snapshot.type === UniverType.UNIVER_BASE) && snapshot.workbook) {
23
+ const sheets = Object.fromEntries(Object.entries(snapshot.workbook.sheets).map(([id, sheet]) => [id, { ...sheet, originalMeta: asBytes(sheet.originalMeta) }]));
24
+ result.workbook = { ...snapshot.workbook, sheets, originalMeta: asBytes(snapshot.workbook.originalMeta) };
25
+ }
26
+ const keys = snapshot.type === UniverType.UNIVER_SLIDE ? snapshot.slide?.originalMeta ? ["slide"] : ["doc"] : snapshot.type === UniverType.UNIVER_BOARD ? ["board"] : snapshot.type === UniverType.UNIVER_DOC ? ["doc"] : snapshot.type === UniverType.UNIVER_PDF ? ["pdf"] : [];
27
+ for (const key of keys) {
28
+ const meta = snapshot[key];
29
+ if (meta) result[key] = { ...meta, originalMeta: asBytes(meta.originalMeta) };
30
+ }
31
+ return result;
32
+ }
33
+ function segment(value) {
34
+ if (!value) throw new Error("Unit or block ID is required");
35
+ return encodeURIComponent(value);
36
+ }
37
+ var SnapshotServerOverHTTPService = class {
38
+ constructor(_configService, _httpService) {
39
+ this._configService = _configService;
40
+ this._httpService = _httpService;
41
+ }
42
+ _prefix() {
43
+ const config = this._configService.getConfig(COLLABORATION_CLIENT_PLUGIN_CONFIG_KEY);
44
+ return (config?.snapshotServerUrl ?? DEFAULT_SNAPSHOT_SERVER_URL).replace(/\/$/, "");
45
+ }
46
+ getSnapshotAPIPath() {
47
+ return (this._configService.getConfig(SNAPSHOT_URL_KEY) ?? this._prefix()).replace(/\/$/, "");
48
+ }
49
+ async getUnitOnRev(_context, params) {
50
+ const response = await this._httpService.get(`${this.getSnapshotAPIPath()}/${params.type}/unit/${segment(params.unitID)}/rev/${params.revision ?? 0}`);
51
+ return { ...response.body, snapshot: decodeSnapshot(response.body.snapshot) };
52
+ }
53
+ async getSheetBlock(_context, params) {
54
+ const response = await this._httpService.get(`${this._prefix()}/${params.type}/unit/${segment(params.unitID)}/block/${segment(params.blockID)}`);
55
+ return { ...response.body, block: response.body.block ? { ...response.body.block, data: asBytes(response.body.block.data) } : void 0 };
56
+ }
57
+ async getDeserializedSheetBlock(_context, params) {
58
+ return (await this._httpService.get(`${this._prefix()}/block/${params.type}/unit/${segment(params.unitID)}/block/${segment(params.blockID)}`)).body;
59
+ }
60
+ async fetchMissingChangesets(_context, params) {
61
+ const query = new URLSearchParams({ from: String(params.from), to: String(params.to) });
62
+ return (await this._httpService.get(`${this._prefix()}/${params.type}/unit/${segment(params.unitID)}/fetchmissing?${query}`)).body;
63
+ }
64
+ async getResourcesRequest(_context, params) {
65
+ return (await this._httpService.get(`${this._prefix()}/${params.type}/unit/${segment(params.unitID)}/resources`, { params: { resourceId: JSON.stringify(params.resourceIDs) } })).body;
66
+ }
67
+ saveSnapshot() {
68
+ throw new Error("This method should not be called on the client side!");
69
+ }
70
+ updateSnapshot() {
71
+ throw new Error("This method should not be called on the client side!");
72
+ }
73
+ saveSheetBlock() {
74
+ throw new Error("This method should not be called on the client side!");
75
+ }
76
+ saveChangeset() {
77
+ throw new Error("This method should not be called on the client side!");
78
+ }
79
+ copyFileMeta() {
80
+ throw new Error("This method should not be called on the client side!");
81
+ }
82
+ getLatestCsReqIdBySid() {
83
+ throw new Error("This method should not be called on the client side!");
84
+ }
85
+ };
86
+ SnapshotServerOverHTTPService = __decorateClass([
87
+ __decorateParam(0, IConfigService),
88
+ __decorateParam(1, Inject(HTTPService))
89
+ ], SnapshotServerOverHTTPService);
90
+
91
+ // src/socket.ts
92
+ import { createIdentifier, Disposable, IConfigService as IConfigService2, Inject as Inject2, Injector, ILogService } from "@cool-office/core";
93
+ import { HTTPEventType, HTTPService as HTTPService2, ISocketService } from "@cool-office/network";
94
+ import { CmdRspCode, CombCmd, ErrorCode } from "@cool-office/protocol";
95
+ import { filter, firstValueFrom, Subject, timeout } from "rxjs";
96
+ var ICollaborationSocketService = createIdentifier("univer-pro.collaboration-client-socket-service");
97
+ var outboundFields = { update_cursor: "updateCursorEvent", users_leave: "leaveEvent", users_enter: "joinEvent", "liveshare.new_host": "liveShareNewHost", "liveshare.operation": "liveShareOperation", "liveshare.terminate": "liveShareTerminate", "liveshare.request_host": "liveShareRequestHost" };
98
+ var inboundFields = { permission_rej: "permissionRejEvent", changeset_ack: "csAckEvent", new_changesets: "newCsEvent", changeset_rej: "csRejEvent", changeset_should_retry: "csShouldRetryEvent", update_cursor: "updateCursorEvent", users_enter: "joinEvent", users_leave: "leaveEvent", "liveshare.new_host": "liveShareNewHost", "liveshare.operation": "liveShareOperation", "liveshare.fetch_operations": "liveShareOperation", "liveshare.terminate": "liveShareNewHost", comment_update: "commentUpdateEvent", update_permission_obj: "updatePermissionObjEvent", should_close_conn: "shouldCloseConn", "uniscript.run": "uniscriptRunEvent" };
99
+ var changeEvents = /* @__PURE__ */ new Set(["permission_rej", "changeset_ack", "new_changesets", "changeset_rej", "changeset_should_retry"]);
100
+ function serializeCombRequest(event) {
101
+ const { cmd, routeKey, data } = event;
102
+ if (cmd === CombCmd.HELLO || cmd === CombCmd.HEARTBEAT) return JSON.stringify({ cmd, routeKey });
103
+ if (cmd === CombCmd.JOIN) return JSON.stringify({ cmd, routeKey, joinReq: data });
104
+ if (cmd === CombCmd.LEAVE) return JSON.stringify({ cmd, routeKey, leaveReq: data });
105
+ if (cmd === CombCmd.INGEST && data && typeof data.eventID === "string") {
106
+ const field = outboundFields[data.eventID];
107
+ return JSON.stringify({ cmd, routeKey, collaMsg: { eventID: data.eventID, ...field ? { [field]: data.data } : {} } });
108
+ }
109
+ throw new Error("Unsupported collaboration request");
110
+ }
111
+ function deserializeToCombResponse(event) {
112
+ if (typeof event.data !== "string") throw new Error("Collaboration response must be text");
113
+ const response = JSON.parse(event.data);
114
+ if (!response || typeof response !== "object" || !Number.isSafeInteger(response.cmd)) throw new Error("Invalid collaboration response");
115
+ if (response.cmd === CombCmd.HELLO || response.cmd === CombCmd.HEARTBEAT) return { ...response, data: response.infoRsp };
116
+ if (response.cmd === CombCmd.JOIN) return { ...response, data: response.joinRsp };
117
+ if (response.cmd !== CombCmd.RECV || !response.collaMsg || typeof response.collaMsg.eventID !== "string") return response;
118
+ const message = response.collaMsg, field = inboundFields[message.eventID];
119
+ if (!field) return response;
120
+ const value = message[field];
121
+ return { ...response, data: { ...message, data: changeEvents.has(message.eventID) ? value?.cs : value } };
122
+ }
123
+ var CollaborationSocketService = class extends Disposable {
124
+ constructor(_injector, _httpService, _configService, _logService, _snapshotServerService) {
125
+ super();
126
+ this._injector = _injector;
127
+ this._httpService = _httpService;
128
+ this._configService = _configService;
129
+ this._logService = _logService;
130
+ this._snapshotServerService = _snapshotServerService;
131
+ }
132
+ async createSocket(url) {
133
+ return this._doCreateSocket(url);
134
+ }
135
+ _doCreateSocket(url) {
136
+ const source = this._injector.get(ISocketService).createSocket(url);
137
+ if (!source) throw new Error("Could not create collaboration socket");
138
+ const messages = new Subject(), errors = new Subject(), closed = new Subject(), subscriptions = [];
139
+ let disposed = false;
140
+ const close = () => {
141
+ if (disposed) return;
142
+ disposed = true;
143
+ source.close();
144
+ subscriptions.forEach((subscription) => subscription.unsubscribe());
145
+ messages.complete();
146
+ errors.complete();
147
+ closed.complete();
148
+ };
149
+ subscriptions.push(source.close$.subscribe((event) => closed.next(event)), source.error$.subscribe((event) => errors.next(event)), source.message$.subscribe((event) => {
150
+ try {
151
+ messages.next(deserializeToCombResponse(event));
152
+ } catch {
153
+ errors.next(new Event("Invalid collaboration message"));
154
+ close();
155
+ }
156
+ }));
157
+ const socket = {
158
+ memberID: "",
159
+ open$: source.open$,
160
+ error$: errors.asObservable(),
161
+ close$: closed.asObservable(),
162
+ message$: messages.asObservable(),
163
+ close,
164
+ send: (event, options) => {
165
+ if (disposed) throw new Error("Collaboration socket is closed");
166
+ if (event.cmd === CombCmd.INGEST && event.data?.eventID === "submit_changeset") return this._submitChangeset(socket, event.data.data, options?.timeout ?? 12e4);
167
+ if (event.cmd === CombCmd.INGEST && event.data?.eventID === "fetch_missing") {
168
+ const request = event.data.data;
169
+ void this._snapshotServerService.fetchMissingChangesets({}, { unitID: request.unitID, type: request.unitType, from: request.from, to: request.to }).then((result) => {
170
+ if (result.error && result.error.code !== ErrorCode.OK) throw new Error(result.error.message || "Cannot fetch missing changes");
171
+ if (!disposed) messages.next({ cmd: CombCmd.RECV, code: CmdRspCode.OK, routeKey: request.unitID, routeType: "", data: { eventID: "pseudo_fetch_missing_result", data: { changesets: result.changesets } } });
172
+ }).catch((error) => {
173
+ this._logService.error(error);
174
+ if (!disposed) {
175
+ errors.next(new Event("connection error"));
176
+ closed.next(new Event("connection error"));
177
+ close();
178
+ }
179
+ });
180
+ return;
181
+ }
182
+ source.send(serializeCombRequest(event));
183
+ }
184
+ };
185
+ this.disposeWithMe({ dispose: close });
186
+ return socket;
187
+ }
188
+ async _submitChangeset(socket, request, timeoutMs) {
189
+ const config = this._configService.getConfig(COLLABORATION_CLIENT_PLUGIN_CONFIG_KEY);
190
+ const prefix = (config?.collabSubmitChangesetUrl ?? "/universer-api/comb").replace(/\/$/, "");
191
+ const changeset = { ...request.changeset, mutations: request.changeset.mutations.map((mutation) => ({ id: mutation.id, data: JSON.stringify(mutation.params ?? {}) })) };
192
+ const payload = { unitID: request.unitID, memberID: socket.memberID, type: request.unitType, changeset };
193
+ const result = await firstValueFrom(this._httpService.stream("POST", `${prefix}/${request.unitType}/unit/${encodeURIComponent(request.unitID)}/new_changes`, { body: payload }).pipe(filter((item) => item.type === HTTPEventType.Response), timeout(timeoutMs)));
194
+ if ("body" in result && result.body?.error?.code !== void 0 && result.body.error.code !== ErrorCode.OK) throw new Error(result.body.error.message || "Changeset submission failed");
195
+ }
196
+ };
197
+ CollaborationSocketService = __decorateClass([
198
+ __decorateParam(0, Inject2(Injector)),
199
+ __decorateParam(1, Inject2(HTTPService2)),
200
+ __decorateParam(2, IConfigService2),
201
+ __decorateParam(3, ILogService),
202
+ __decorateParam(4, Inject2(SnapshotServerOverHTTPService))
203
+ ], CollaborationSocketService);
204
+
205
+ // src/session.ts
206
+ import { Disposable as Disposable2, IConfigService as IConfigService3, Inject as Inject3 } from "@cool-office/core";
207
+ import { CmdRspCode as CmdRspCode2, CombCmd as CombCmd2 } from "@cool-office/protocol";
208
+ import { BehaviorSubject, Subject as Subject2, Subscription } from "rxjs";
209
+ var SessionStatus = /* @__PURE__ */ ((SessionStatus2) => {
210
+ SessionStatus2[SessionStatus2["IDLE"] = 0] = "IDLE";
211
+ SessionStatus2[SessionStatus2["JOINING"] = 1] = "JOINING";
212
+ SessionStatus2[SessionStatus2["OFFLINE"] = 2] = "OFFLINE";
213
+ SessionStatus2[SessionStatus2["ONLINE"] = 3] = "ONLINE";
214
+ return SessionStatus2;
215
+ })(SessionStatus || {});
216
+ var CollaborationSession = class {
217
+ constructor(unitID, _service) {
218
+ this.unitID = unitID;
219
+ this._service = _service;
220
+ this._status = new BehaviorSubject(0 /* IDLE */);
221
+ this._events = new Subject2();
222
+ this.sessionStatus$ = this._status.asObservable();
223
+ this.event$ = this._events.asObservable();
224
+ this._closed = false;
225
+ this._joinedBefore = false;
226
+ this._requiresResync = false;
227
+ }
228
+ get sessionStatus() {
229
+ return this._status.value;
230
+ }
231
+ get requiresResync() {
232
+ return this._requiresResync;
233
+ }
234
+ /** Call only after the consumer has reconciled the missed server revisions and pending edits. */
235
+ markResynced() {
236
+ if (this.sessionStatus !== 3 /* ONLINE */) throw new Error("Collaboration session is not online");
237
+ this._requiresResync = false;
238
+ }
239
+ getMemberID() {
240
+ return this._service.memberID;
241
+ }
242
+ async send(event, _unitID, options) {
243
+ if (this._closed || this.sessionStatus !== 3 /* ONLINE */) throw new Error("Collaboration session is not online");
244
+ if (_unitID !== this.unitID) throw new Error("Collaboration session unit mismatch");
245
+ if (this._requiresResync && event.eventID === "submit_changeset") throw new Error("Reconcile missed changes before submitting edits");
246
+ await this._service.send({ cmd: CombCmd2.INGEST, routeKey: this.unitID, data: event }, options);
247
+ }
248
+ close() {
249
+ if (!this._closed) this._service.closeSession(this.unitID);
250
+ }
251
+ dispose() {
252
+ this.close();
253
+ }
254
+ /** @internal */
255
+ setStatus(status) {
256
+ if (!this._closed && this._status.value !== status) this._status.next(status);
257
+ }
258
+ /** @internal */
259
+ emit(event) {
260
+ if (!this._closed) this._events.next(event);
261
+ }
262
+ /** @internal */
263
+ joined() {
264
+ if (this._joinedBefore) this._requiresResync = true;
265
+ this._joinedBefore = true;
266
+ this.setStatus(3 /* ONLINE */);
267
+ if (this._requiresResync) this.emit({ eventID: "requires_resync" });
268
+ }
269
+ /** @internal */
270
+ finish() {
271
+ if (this._closed) return;
272
+ this._closed = true;
273
+ this._events.complete();
274
+ this._status.complete();
275
+ }
276
+ };
277
+ var CollaborationSessionService = class extends Disposable2 {
278
+ constructor(_configService, _socketService) {
279
+ super();
280
+ this._configService = _configService;
281
+ this._socketService = _socketService;
282
+ this._sessions = /* @__PURE__ */ new Map();
283
+ this._status = new BehaviorSubject(0 /* IDLE */);
284
+ this._socketState = new BehaviorSubject(null);
285
+ this._roomEvents = new Subject2();
286
+ this.status$ = this._status.asObservable();
287
+ this.socket$ = this._socketState.asObservable();
288
+ this.roomEvents$ = this._roomEvents.asObservable();
289
+ this._socket = null;
290
+ this._subscriptions = new Subscription();
291
+ this._ready = false;
292
+ this._connecting = false;
293
+ this._online = true;
294
+ this._generation = 0;
295
+ this._retryCount = 0;
296
+ this._retryTimer = null;
297
+ this._handshakeTimer = null;
298
+ this._heartbeatTimer = null;
299
+ this._heartbeatTimeout = null;
300
+ }
301
+ get memberID() {
302
+ return this._ready ? this._socket?.memberID ?? null : null;
303
+ }
304
+ async requireSession(unitID) {
305
+ if (this._disposed) throw new Error("Collaboration session service is disposed");
306
+ if (!unitID) throw new Error("Unit ID is required");
307
+ let session = this._sessions.get(unitID);
308
+ if (!session) {
309
+ session = new CollaborationSession(unitID, this);
310
+ this._sessions.set(unitID, session);
311
+ if (this._ready) this._join(session);
312
+ else if (this._online && !this._retryTimer && !this._socket && !this._connecting) this._scheduleReconnect();
313
+ }
314
+ return session;
315
+ }
316
+ closeSession(unitID) {
317
+ const session = this._sessions.get(unitID);
318
+ if (!session) return;
319
+ this._sessions.delete(unitID);
320
+ if (this._ready) {
321
+ try {
322
+ void this._socket?.send({ cmd: CombCmd2.LEAVE, routeKey: unitID, data: { roomID: unitID } });
323
+ } catch {
324
+ }
325
+ }
326
+ session.finish();
327
+ if (!this._sessions.size) {
328
+ this._disconnect();
329
+ this._status.next(0 /* IDLE */);
330
+ }
331
+ }
332
+ reconnect() {
333
+ if (this._disposed) return;
334
+ this._retryCount = 0;
335
+ this._disconnect();
336
+ if (this._sessions.size && this._online) this._scheduleReconnect();
337
+ }
338
+ /** Browser network signals are hints only; reconnection still requires a successful handshake. */
339
+ setOnline(online) {
340
+ if (this._disposed || this._online === online) return;
341
+ this._online = online;
342
+ if (!online) this._disconnect();
343
+ else this.reconnect();
344
+ }
345
+ async send(event, options) {
346
+ if (!this._ready || !this._socket) throw new Error("Collaboration connection is not ready");
347
+ await this._socket.send(event, options);
348
+ }
349
+ dispose() {
350
+ if (this._disposed) return;
351
+ this._disconnect();
352
+ for (const session of this._sessions.values()) session.finish();
353
+ this._sessions.clear();
354
+ this._roomEvents.complete();
355
+ this._status.complete();
356
+ this._socketState.complete();
357
+ super.dispose();
358
+ }
359
+ _scheduleReconnect() {
360
+ if (this._disposed || !this._online || !this._sessions.size || this._retryTimer || this._connecting) return;
361
+ const max = this._configService.getConfig("RETRY_CONNECTING_MAX_COUNT") ?? 3;
362
+ if (this._retryCount >= max) return;
363
+ const config = this._configService.getConfig(COLLABORATION_CLIENT_PLUGIN_CONFIG_KEY);
364
+ const delay = this._retryCount === 0 ? 0 : Math.min(config?.maxReconnectInterval ?? 2147483647, (config?.retryConnectingInterval ?? 2e4) * 2 ** this._retryCount);
365
+ this._retryCount++;
366
+ this._retryTimer = setTimeout(() => {
367
+ this._retryTimer = null;
368
+ void this._connect();
369
+ }, delay);
370
+ }
371
+ async _connect() {
372
+ const generation = ++this._generation;
373
+ this._connecting = true;
374
+ const config = this._configService.getConfig(COLLABORATION_CLIENT_PLUGIN_CONFIG_KEY);
375
+ this._status.next(1 /* JOINING */);
376
+ try {
377
+ const socket = await this._socketService.createSocket(config?.collabWebSocketUrl ?? "ws://127.0.0.1:8000/universer-api/comb/connect");
378
+ if (generation !== this._generation || this._disposed || !this._sessions.size || !this._online) {
379
+ socket?.close();
380
+ return;
381
+ }
382
+ this._connecting = false;
383
+ if (!socket) throw new Error("Unable to create collaboration socket");
384
+ this._socket = socket;
385
+ this._subscriptions = new Subscription();
386
+ this._subscriptions.add(socket.open$.subscribe(() => {
387
+ try {
388
+ void socket.send({ cmd: CombCmd2.HELLO, routeKey: "" });
389
+ } catch {
390
+ this._failed(generation);
391
+ }
392
+ }));
393
+ this._subscriptions.add(socket.error$.subscribe(() => this._failed(generation)));
394
+ this._subscriptions.add(socket.close$.subscribe(() => this._failed(generation)));
395
+ this._subscriptions.add(socket.message$.subscribe((event) => this._onMessage(generation, event)));
396
+ this._handshakeTimer = setTimeout(() => this._failed(generation), 2e4);
397
+ } catch {
398
+ this._failed(generation);
399
+ }
400
+ }
401
+ _onMessage(generation, event) {
402
+ if (generation !== this._generation || !this._socket) return;
403
+ if (!this._ready && event.cmd === CombCmd2.HELLO) {
404
+ if ((event.code ?? CmdRspCode2.OK) !== CmdRspCode2.OK || typeof event.data?.memberID !== "string" || !event.data.memberID) {
405
+ this._failed(generation);
406
+ return;
407
+ }
408
+ this._clear("_handshakeTimer");
409
+ this._socket.memberID = event.data.memberID;
410
+ this._ready = true;
411
+ this._retryCount = 0;
412
+ this._socketState.next(this._socket);
413
+ this._status.next(3 /* ONLINE */);
414
+ for (const session2 of this._sessions.values()) this._join(session2);
415
+ this._scheduleHeartbeat(generation);
416
+ return;
417
+ }
418
+ if (!this._ready) return;
419
+ if (event.cmd === CombCmd2.HEARTBEAT) {
420
+ this._clear("_heartbeatTimeout");
421
+ this._scheduleHeartbeat(generation);
422
+ return;
423
+ }
424
+ const session = this._sessions.get(event.routeKey);
425
+ if (event.cmd === CombCmd2.JOIN && session) {
426
+ const room = event.data?.roomInfos?.[event.routeKey];
427
+ if ((event.code ?? CmdRspCode2.OK) === CmdRspCode2.OK && room) {
428
+ this._roomEvents.next({ unitID: event.routeKey, event: { eventID: "room_joined", data: room } });
429
+ session.joined();
430
+ } else session.setStatus(2 /* OFFLINE */);
431
+ } else if (event.cmd === CombCmd2.RECV && session && event.data && typeof event.data.eventID === "string") {
432
+ this._roomEvents.next({ unitID: event.routeKey, event: event.data });
433
+ session.emit(event.data);
434
+ }
435
+ }
436
+ _join(session) {
437
+ session.setStatus(1 /* JOINING */);
438
+ try {
439
+ void this._socket?.send({ cmd: CombCmd2.JOIN, routeKey: session.unitID, data: { rooms: [{ roomID: session.unitID }] } });
440
+ } catch {
441
+ this._failed(this._generation);
442
+ }
443
+ }
444
+ _scheduleHeartbeat(generation) {
445
+ this._clear("_heartbeatTimer");
446
+ this._heartbeatTimer = setTimeout(() => {
447
+ if (!this._ready || generation !== this._generation) return;
448
+ try {
449
+ void this._socket?.send({ cmd: CombCmd2.HEARTBEAT, routeKey: "" });
450
+ } catch {
451
+ this._failed(generation);
452
+ return;
453
+ }
454
+ this._heartbeatTimeout = setTimeout(() => this._failed(generation), this._configService.getConfig("HEARTBEAT_TIMEOUT") ?? 2e4);
455
+ }, this._configService.getConfig("HEARTBEAT_INTERVAL") ?? 3e4);
456
+ }
457
+ _failed(generation) {
458
+ if (generation !== this._generation || this._disposed) return;
459
+ this._disconnect();
460
+ this._scheduleReconnect();
461
+ }
462
+ _disconnect() {
463
+ this._generation++;
464
+ this._ready = false;
465
+ this._connecting = false;
466
+ this._subscriptions.unsubscribe();
467
+ this._subscriptions = new Subscription();
468
+ this._clear("_retryTimer");
469
+ this._clear("_handshakeTimer");
470
+ this._clear("_heartbeatTimer");
471
+ this._clear("_heartbeatTimeout");
472
+ const socket = this._socket;
473
+ this._socket = null;
474
+ socket?.close();
475
+ this._socketState.next(null);
476
+ if (this._sessions.size) {
477
+ this._status.next(2 /* OFFLINE */);
478
+ for (const session of this._sessions.values()) session.setStatus(2 /* OFFLINE */);
479
+ }
480
+ }
481
+ _clear(name) {
482
+ const timer = this[name];
483
+ if (timer !== null) clearTimeout(timer);
484
+ this[name] = null;
485
+ }
486
+ };
487
+ CollaborationSessionService = __decorateClass([
488
+ __decorateParam(0, IConfigService3),
489
+ __decorateParam(1, Inject3(ICollaborationSocketService))
490
+ ], CollaborationSessionService);
491
+
492
+ // src/document-recovery.ts
493
+ import { applyDocumentChange, DOCUMENT_EDIT, documentEdit, readDocumentChanges, replaceDocumentContents } from "@cool-office/collaboration/document";
494
+ import { Disposable as Disposable3, JSON1, JSONX as JSONX2, Tools } from "@cool-office/core";
495
+ import { ErrorCode as ErrorCode2 } from "@cool-office/protocol";
496
+ import { BehaviorSubject as BehaviorSubject2 } from "rxjs";
497
+
498
+ // src/document-object-resources.ts
499
+ import { JSONX } from "@cool-office/core";
500
+ var descriptors = [
501
+ { prefix: "docs-code.mutation.", set: "set-config", remove: "remove-config", name: "DOC_CODE_PLUGIN", collection: "codes", key: "blockId" },
502
+ { prefix: "docs-callout.mutation.", set: "set-config", remove: "remove-config", name: "DOC_CALLOUT_PLUGIN", collection: "callouts", key: "blockId" },
503
+ { prefix: "docs-latex.mutation.", set: "set-formula", remove: "remove-formula", name: "DOC_LATEX_PLUGIN", collection: "formulas", key: "rangeId" }
504
+ ];
505
+ function isDocumentObjectMutation(id) {
506
+ return descriptors.some((item) => id === item.prefix + item.set || id === item.prefix + item.remove);
507
+ }
508
+ function documentObjectEdit(before, id, params, resources) {
509
+ const descriptor = descriptors.find((item) => id === item.prefix + item.set || id === item.prefix + item.remove);
510
+ if (!descriptor) return void 0;
511
+ const hook = resources?.getAllResourceHooks().find((item) => item.pluginName === descriptor.name);
512
+ const key = params[descriptor.key];
513
+ if (!hook || typeof key !== "string" || !key) throw new Error("Document object resource is unavailable");
514
+ const entries = before.resources ?? [];
515
+ const index = entries.findIndex((item) => item.name === descriptor.name);
516
+ const entry = entries[index];
517
+ const saved = entry ? JSON.parse(entry.data) : {};
518
+ const oldItems = saved[descriptor.collection] ?? {};
519
+ const items = { ...oldItems };
520
+ const live = JSON.parse(hook.toJson(before.id))[descriptor.collection];
521
+ if (Object.hasOwn(live, key)) Object.defineProperty(items, key, { value: live[key], enumerable: true, configurable: true });
522
+ else if (Object.hasOwn(items, key)) delete items[key];
523
+ else return null;
524
+ const data = JSON.stringify({ ...saved, [descriptor.collection]: items });
525
+ if (entry?.data === data) return null;
526
+ const json = JSONX.getInstance();
527
+ if (entry) return json.replaceOp(["resources", index, "data"], true, data);
528
+ const resource = { name: descriptor.name, data };
529
+ return before.resources ? json.insertOp(["resources", entries.length], resource) : json.insertOp(["resources"], [resource]);
530
+ }
531
+ function refreshDocumentObjectResources(unitID, before, after, manager) {
532
+ if (!manager || before === after) return;
533
+ for (const { name, collection } of descriptors) {
534
+ const previous = before?.find((item) => item.name === name)?.data;
535
+ const current = after?.find((item) => item.name === name)?.data;
536
+ if (previous === current) continue;
537
+ const hook = manager.getAllResourceHooks().find((item) => item.pluginName === name);
538
+ if (hook) hook.onLoad(unitID, hook.parseJson(current ?? JSON.stringify({ [collection]: {} })));
539
+ }
540
+ }
541
+
542
+ // src/document-recovery.ts
543
+ var DocumentCollaborationRecovery = class extends Disposable3 {
544
+ constructor(options, _commands, _snapshots, _sessions, _model, _connection, _remove) {
545
+ super();
546
+ this.options = options;
547
+ this._commands = _commands;
548
+ this._snapshots = _snapshots;
549
+ this._sessions = _sessions;
550
+ this._model = _model;
551
+ this._connection = _connection;
552
+ this._remove = _remove;
553
+ this._state = new BehaviorSubject2("connecting");
554
+ this.status$ = this._state.asObservable();
555
+ this._queue = [];
556
+ this._sid = crypto.randomUUID();
557
+ this._next = 1;
558
+ this._reason = null;
559
+ this._conflictRemote = null;
560
+ this._closed = false;
561
+ this._ready = false;
562
+ this._pulling = false;
563
+ this._accessPending = false;
564
+ this._generation = 0;
565
+ this._sending = 0;
566
+ this._buffer = [];
567
+ this._storageError = false;
568
+ if (!options.userID || _model.getRev() !== options.revision) throw new Error("Authenticated document and loaded revision are required");
569
+ this._confirmed = structuredClone(_model.getSnapshot());
570
+ this._grant = _connection.initialAccess;
571
+ }
572
+ get status() {
573
+ return this._state.value;
574
+ }
575
+ get revision() {
576
+ return this._confirmed.rev;
577
+ }
578
+ get hasWritePending() {
579
+ return !!this._queue.length || !!this._reason;
580
+ }
581
+ get conflictReason() {
582
+ return this._reason;
583
+ }
584
+ get canPublishConflict() {
585
+ return this._grant === "write" && !this._storageError;
586
+ }
587
+ getUnrecoverableDraft() {
588
+ if (!this._storageError) return;
589
+ try {
590
+ const key = this._connection.recoveryKey;
591
+ return key && sessionStorage.getItem(key) || JSON.stringify(this.getLocalDocument(), null, 2);
592
+ } catch {
593
+ return JSON.stringify(this.getLocalDocument(), null, 2);
594
+ }
595
+ }
596
+ getPendingEdits() {
597
+ return { edits: this._queue.map((item) => ({ id: DOCUMENT_EDIT, params: { unitId: this.options.unitID, actions: structuredClone(item.op) } })), incomplete: !!this._reason, awaitingConfirmation: !!this._queue[0]?.sent };
598
+ }
599
+ getLocalDocument() {
600
+ return structuredClone(this._model.getSnapshot());
601
+ }
602
+ getConfirmedDocument() {
603
+ return structuredClone(this._confirmed);
604
+ }
605
+ getProposedDocument() {
606
+ const local = this.getLocalDocument();
607
+ if (!this._conflictBase) return local;
608
+ try {
609
+ const draft2 = this._queue.reduce((op, item) => JSONX2.compose(op, item.op), null);
610
+ if (!replaceDocumentContents(applyDocumentChange(this._conflictBase, draft2), local) && !replaceDocumentContents(applyDocumentChange(this._conflictBase, this._conflictRemote), this._confirmed)) {
611
+ return structuredClone(applyDocumentChange(this._confirmed, JSON1.type.transformNoConflict(draft2, this._conflictRemote, "left")));
612
+ }
613
+ } catch {
614
+ }
615
+ const proposed = this.getConfirmedDocument();
616
+ const base = this._conflictBase;
617
+ const draft = local;
618
+ for (const field of /* @__PURE__ */ new Set([...Object.keys(base), ...Object.keys(draft)])) {
619
+ if (field === "id" || field === "rev" || field === "disabled" || Tools.diffValue(base[field], draft[field])) continue;
620
+ if (draft[field] === void 0) delete proposed[field];
621
+ else proposed[field] = draft[field];
622
+ }
623
+ return proposed;
624
+ }
625
+ markUnitUnavailable() {
626
+ if (this.hasWritePending) this._conflict("The document was closed");
627
+ }
628
+ async start() {
629
+ this._restore();
630
+ this._connection.setAccess(this._reason ? "read" : this._grant);
631
+ this.disposeWithMe(this._commands.onCommandExecuted((command) => {
632
+ if (this._batch?.trigger === command.id) this._finishObjectCommand();
633
+ }));
634
+ this.disposeWithMe(this._commands.onMutationExecutedForCollab((command, execution) => {
635
+ const params = command.params;
636
+ if (execution?.fromCollab || execution?.onlyLocal || execution?.fromChangeset || params?.unitId !== this.options.unitID) return;
637
+ try {
638
+ if (this._reason || this._grant !== "write" || execution?.syncOnly) throw new Error("The pending document needs review");
639
+ const settings = isDocumentObjectMutation(command.id);
640
+ const trigger = params.trigger ?? command.id;
641
+ const compound = settings || /^(docs-(code|callout|latex)\.command\.|univer\.command\.(undo|redo)$)/.test(trigger);
642
+ if (!compound) {
643
+ this._enqueue(documentEdit(this.options.unitID, command.id, params));
644
+ return;
645
+ }
646
+ if (this._batch && this._batch.trigger !== trigger) this._finishObjectCommand();
647
+ if (!this._batch) {
648
+ const batch = this._batch = { trigger, body: null, settings: [] };
649
+ queueMicrotask(() => {
650
+ if (this._batch === batch) this._finishObjectCommand();
651
+ });
652
+ }
653
+ if (settings) this._batch.settings.push({ id: command.id, params });
654
+ else this._batch.body = JSONX2.compose(this._batch.body, documentEdit(this.options.unitID, command.id, params));
655
+ } catch (error) {
656
+ this._conflict(String(error));
657
+ }
658
+ }));
659
+ const session = await this._sessions.requireSession(this.options.unitID);
660
+ if (this._closed) return;
661
+ this._session = session;
662
+ const events = session.event$.subscribe((event) => {
663
+ const data = event.data;
664
+ if (event.eventID === "changeset_ack" || event.eventID === "new_changesets") {
665
+ this._buffer.push(...Array.isArray(data) ? data : [data]);
666
+ if (this._ready && !this._pulling) this._drain();
667
+ } else if (data?.sid === this._sid && data.reqId === this._queue[0]?.reqId) {
668
+ if (event.eventID === "changeset_should_retry") {
669
+ this._clearSend();
670
+ void this._pull();
671
+ }
672
+ if (event.eventID === "changeset_rej" || event.eventID === "permission_rej") {
673
+ this._clearSend();
674
+ this._conflict(event.eventID === "permission_rej" ? "Document permission changed" : "The document edits require review");
675
+ void this._refreshAccess();
676
+ }
677
+ }
678
+ });
679
+ const status = session.sessionStatus$.subscribe((state) => {
680
+ this._generation++;
681
+ this._pulling = false;
682
+ this._ready = false;
683
+ this._clearSend();
684
+ if (state === 3 /* ONLINE */) void this._pull();
685
+ else this._update();
686
+ });
687
+ const interval = setInterval(() => {
688
+ void this._refreshAccess();
689
+ }, 2e3);
690
+ this.disposeWithMe(() => {
691
+ events.unsubscribe();
692
+ status.unsubscribe();
693
+ clearInterval(interval);
694
+ });
695
+ }
696
+ /** The caller shows the two snapshots and supplies the revision the user actually reviewed. */
697
+ async resolveDocumentConflict(choice, reviewedRevision) {
698
+ if (!this._reason || this._session?.sessionStatus !== 3 /* ONLINE */ || this._pulling || this._storageError && choice === "local") return false;
699
+ await this._refreshAccess();
700
+ await this._pull();
701
+ if (!this._ready || reviewedRevision !== this.revision || this._closed || this._grant === "none" || choice === "local" && this._grant !== "write") return false;
702
+ const local = this.getLocalDocument();
703
+ try {
704
+ const target = choice === "remote" ? this._confirmed : this.getProposedDocument();
705
+ const op = replaceDocumentContents(this._confirmed, target);
706
+ applyDocumentChange(this._confirmed, op);
707
+ this._apply(replaceDocumentContents(local, target));
708
+ this._model.setRev(this.revision);
709
+ this._queue = choice === "local" && op ? [{ reqId: this._next++, op, reviewed: true }] : [];
710
+ if (choice === "remote") this._storageError = false;
711
+ this._reason = null;
712
+ this._conflictBase = void 0;
713
+ this._conflictRemote = null;
714
+ this._save();
715
+ this._connection.setAccess(this._grant);
716
+ this._update();
717
+ this._submit();
718
+ return true;
719
+ } catch (error) {
720
+ this._conflict(String(error));
721
+ return false;
722
+ }
723
+ }
724
+ async _refreshAccess() {
725
+ if (this._closed || this._accessPending) return;
726
+ this._accessPending = true;
727
+ try {
728
+ const grant = await this._connection.access();
729
+ if (this._closed || grant === this._grant) return;
730
+ const previous = this._grant;
731
+ this._grant = grant;
732
+ if (grant !== "write" && this._queue.length) this._conflict("Document permission changed");
733
+ this._connection.setAccess(this._reason && grant === "write" ? "read" : grant);
734
+ if (previous === "none" && grant !== "none") this._sessions.reconnect();
735
+ this._update(true);
736
+ } catch {
737
+ } finally {
738
+ this._accessPending = false;
739
+ }
740
+ }
741
+ async _pull() {
742
+ if (this._closed || this._pulling || this._session?.sessionStatus !== 3 /* ONLINE */ || this._grant === "none") return;
743
+ const generation = this._generation;
744
+ this._pulling = true;
745
+ this._update();
746
+ try {
747
+ const result = await this._snapshots.fetchMissingChangesets({}, { unitID: this.options.unitID, type: 1, from: this.revision, to: 0 });
748
+ if (this._closed || generation !== this._generation) return;
749
+ if (result.error && result.error.code !== ErrorCode2.OK || !Array.isArray(result.changesets)) throw new Error("Unable to read document revisions");
750
+ this._buffer.push(...result.changesets);
751
+ this._ready = true;
752
+ if (this._session.requiresResync) this._session.markResynced();
753
+ this._pulling = false;
754
+ this._drain();
755
+ } catch {
756
+ if (!this._closed && generation === this._generation) {
757
+ this._pulling = false;
758
+ this._ready = false;
759
+ this._sessions.reconnect();
760
+ }
761
+ }
762
+ }
763
+ _drain() {
764
+ this._buffer.sort((a, b) => a.revision - b.revision);
765
+ while (this._buffer.length) {
766
+ const change = this._buffer[0];
767
+ if (change.revision <= this.revision) {
768
+ this._buffer.shift();
769
+ continue;
770
+ }
771
+ if (change.revision > this.revision + 1) {
772
+ void this._pull();
773
+ return;
774
+ }
775
+ if (change.baseRev !== this.revision || change.type !== 1 || change.unitID !== this.options.unitID) {
776
+ this._conflict("Invalid document revision");
777
+ return;
778
+ }
779
+ this._buffer.shift();
780
+ const before = this._confirmed;
781
+ let op = null;
782
+ const paused = !!this._reason;
783
+ try {
784
+ op = readDocumentChanges(change.unitID, change.mutations);
785
+ const next = applyDocumentChange(before, op);
786
+ this._confirmed = { ...next, rev: change.revision };
787
+ if (paused) this._conflictRemote = JSONX2.compose(this._conflictRemote, op);
788
+ const first = this._queue[0];
789
+ if (change.userID === this.options.userID && change.sid === this._sid && change.reqId === first?.reqId && first) {
790
+ this._clearSend();
791
+ if (!this._reason && !Tools.diffValue(first.op, op) && !Tools.diffValue(applyDocumentChange(before, first.op), next)) {
792
+ throw new Error("The confirmed edit differs from the pending edit");
793
+ }
794
+ this._queue.shift();
795
+ } else if (!this._reason) {
796
+ let remote = op;
797
+ const queue = this._queue.map((item) => {
798
+ if (item.reviewed) throw new Error("The reviewed version changed");
799
+ const local = JSONX2.transform(item.op, remote, "right") ?? null;
800
+ remote = JSONX2.transform(remote, item.op, "left") ?? null;
801
+ return { ...item, op: local };
802
+ });
803
+ this._apply(remote);
804
+ this._queue = queue;
805
+ }
806
+ this._model.setRev(change.revision);
807
+ this._save();
808
+ } catch (error) {
809
+ if (!paused && this._confirmed !== before) this._conflictRemote = op;
810
+ this._conflict(String(error), before);
811
+ }
812
+ }
813
+ this._update();
814
+ this._submit();
815
+ }
816
+ _apply(op, localResource = false) {
817
+ if (!op) return;
818
+ if (!localResource) this._connection.beforeRemote?.(op, this._model.getSnapshot());
819
+ const previousResources = this._model.getSnapshot().resources;
820
+ const title = this._model.getSnapshot().title;
821
+ const result = this._commands.syncExecuteCommand(DOCUMENT_EDIT, {
822
+ unitId: this.options.unitID,
823
+ actions: structuredClone(op),
824
+ noHistory: true,
825
+ noNeedSetTextRange: true
826
+ }, { fromCollab: true, fromChangeset: true });
827
+ if (!result || !result.actions?.length) throw new Error("The editor could not apply this document revision");
828
+ if (!localResource) refreshDocumentObjectResources(this.options.unitID, previousResources, this._model.getSnapshot().resources, this._connection.resources);
829
+ const updated = this._model.getSnapshot().title;
830
+ if (typeof updated === "string" && updated !== title) this._model.setName(updated);
831
+ }
832
+ _finishObjectCommand() {
833
+ const batch = this._batch;
834
+ this._batch = void 0;
835
+ if (!batch || this._closed) return;
836
+ try {
837
+ let op = batch.body;
838
+ for (const item of batch.settings) {
839
+ const edit = documentObjectEdit(this._model.getSnapshot(), item.id, item.params, this._connection.resources);
840
+ if (!edit) continue;
841
+ const resource = documentEdit(this.options.unitID, DOCUMENT_EDIT, { unitId: this.options.unitID, actions: edit });
842
+ this._apply(resource, true);
843
+ op = JSONX2.compose(op, resource);
844
+ }
845
+ this._enqueue(op);
846
+ } catch (error) {
847
+ this._conflict(String(error));
848
+ }
849
+ }
850
+ _enqueue(op) {
851
+ if (!op) return;
852
+ this._queue.push({ reqId: this._next++, op: structuredClone(op) });
853
+ this._save();
854
+ this._update();
855
+ this._submit();
856
+ }
857
+ _submit() {
858
+ const first = this._queue[0];
859
+ const memberID = this._session?.getMemberID();
860
+ if (this._closed || !first || !memberID || !this._ready || this._pulling || this._sending || this._reason || this._grant !== "write") return;
861
+ first.sent ??= { base: this.revision, op: structuredClone(first.op) };
862
+ try {
863
+ this._save();
864
+ } catch (error) {
865
+ this._conflict(String(error));
866
+ return;
867
+ }
868
+ const request = first.reqId;
869
+ this._sending = request;
870
+ const changeset = { unitID: this.options.unitID, type: 1, baseRev: first.sent.base, revision: 0, userID: this.options.userID, memberID, sid: this._sid, reqId: request, mutations: [{ id: DOCUMENT_EDIT, params: { unitId: this.options.unitID, actions: first.sent.op, ...first.reviewed ? { requireCurrentRevision: true } : {} } }] };
871
+ const generation = this._generation;
872
+ const reconnect = () => {
873
+ if (!this._closed && this._sending === request && generation === this._generation) this._sessions.reconnect();
874
+ };
875
+ this._ackTimer = setTimeout(reconnect, 2e4);
876
+ void this._session.send({ eventID: "submit_changeset", data: { unitID: this.options.unitID, unitType: 1, changeset } }, this.options.unitID).catch(reconnect);
877
+ }
878
+ _clearSend() {
879
+ clearTimeout(this._ackTimer);
880
+ this._sending = 0;
881
+ }
882
+ _update(accessChanged = false) {
883
+ const next = this._grant === "none" ? "denied" : this._reason ? "conflict" : this._session?.sessionStatus === 2 /* OFFLINE */ ? "offline" : !this._ready ? "connecting" : this._pulling ? "recovering" : this._queue.length ? "pending" : this._grant === "read" ? "readonly" : "synced";
884
+ if (accessChanged || next !== this.status) this._state.next(next);
885
+ }
886
+ _conflict(reason, base = this._confirmed) {
887
+ this._reason ??= reason;
888
+ this._conflictBase ??= base;
889
+ if (!this._closed) this._connection.setAccess(this._grant === "none" ? "none" : "read");
890
+ try {
891
+ this._save();
892
+ } catch {
893
+ }
894
+ this._update();
895
+ }
896
+ _save() {
897
+ const key = this._connection.recoveryKey;
898
+ if (!key) return;
899
+ if (this._storageError) throw new Error("Cannot save the pending document");
900
+ try {
901
+ if (!this.hasWritePending) {
902
+ sessionStorage.removeItem(key);
903
+ return;
904
+ }
905
+ const checkpoint = { version: 1, sid: this._sid, next: this._next, confirmed: this._confirmed, queue: this._queue, conflict: this._reason, ...this._reason ? { local: this.getLocalDocument(), conflictBase: this._conflictBase, conflictRemote: this._conflictRemote } : {} };
906
+ sessionStorage.setItem(key, JSON.stringify(checkpoint));
907
+ } catch {
908
+ this._storageError = true;
909
+ throw new Error("Cannot save the pending document");
910
+ }
911
+ }
912
+ _restore() {
913
+ const key = this._connection.recoveryKey;
914
+ if (!key) return;
915
+ try {
916
+ const raw = sessionStorage.getItem(key);
917
+ if (!raw) return;
918
+ const checkpoint = JSON.parse(raw);
919
+ if (checkpoint.version !== 1 || checkpoint.confirmed.id !== this.options.unitID || !Number.isSafeInteger(checkpoint.confirmed.rev) || !Number.isSafeInteger(checkpoint.next) || !checkpoint.sid || !Array.isArray(checkpoint.queue)) {
920
+ throw new Error("Invalid pending document");
921
+ }
922
+ const local = checkpoint.local ?? checkpoint.queue.reduce((doc, item) => applyDocumentChange(doc, item.op), checkpoint.confirmed);
923
+ this._apply(replaceDocumentContents(this.getLocalDocument(), local));
924
+ this._model.setRev(checkpoint.confirmed.rev);
925
+ this._confirmed = checkpoint.confirmed;
926
+ this._queue = checkpoint.queue;
927
+ this._sid = checkpoint.sid;
928
+ this._next = checkpoint.next;
929
+ this._reason = checkpoint.conflict;
930
+ this._conflictBase = checkpoint.conflictBase;
931
+ this._conflictRemote = checkpoint.conflictRemote ?? null;
932
+ } catch {
933
+ this._storageError = true;
934
+ this._reason = "The saved edits could not be loaded";
935
+ }
936
+ }
937
+ dispose() {
938
+ if (this._closed) return;
939
+ this._closed = true;
940
+ this._generation++;
941
+ this._clearSend();
942
+ this._state.complete();
943
+ this._remove();
944
+ super.dispose();
945
+ }
946
+ };
947
+
948
+ // src/document-undo.ts
949
+ import { applyDocumentChange as applyDocumentChange2, DOCUMENT_EDIT as DOCUMENT_EDIT2, documentEdit as documentEdit2 } from "@cool-office/collaboration/document";
950
+ import { JSONX as JSONX3, LocalUndoRedoService } from "@cool-office/core";
951
+ var DocumentCollaborationUndoService = class extends LocalUndoRedoService {
952
+ /** A later write to the same cell belongs to its author and must survive local undo. */
953
+ transformSheetHistory(unitID, changes) {
954
+ const written = /* @__PURE__ */ new Map();
955
+ for (const change of changes) {
956
+ if (change.id !== "sheet.mutation.set-range-values") continue;
957
+ const p = change.params;
958
+ if (!p?.cellValue) continue;
959
+ const coordinates = written.get(p.subUnitId) ?? /* @__PURE__ */ new Set();
960
+ for (const [row, cells] of Object.entries(p.cellValue)) for (const column of Object.keys(cells)) coordinates.add(row + ":" + column);
961
+ written.set(p.subUnitId, coordinates);
962
+ }
963
+ if (!written.size) return;
964
+ const omitOverwrittenCells = (mutation) => {
965
+ if (mutation.id !== "sheet.mutation.set-range-values") return [mutation];
966
+ const p = mutation.params;
967
+ const coordinates = written.get(p?.subUnitId);
968
+ if (!p?.cellValue || !coordinates) return [mutation];
969
+ const value = Object.fromEntries(Object.entries(p.cellValue).map(
970
+ ([row, cells]) => [row, Object.fromEntries(Object.entries(cells).filter(([column]) => !coordinates.has(row + ":" + column)))]
971
+ ).filter(([, cells]) => Object.keys(cells).length));
972
+ return Object.keys(value).length ? [{ ...mutation, params: { ...p, cellValue: value } }] : [];
973
+ };
974
+ for (const stack of [this._getUndoStack(unitID), this._getRedoStack(unitID)]) {
975
+ if (!stack) continue;
976
+ for (let i = stack.length - 1; i >= 0; i--) {
977
+ const item = stack[i];
978
+ item.undoMutations = item.undoMutations.flatMap(omitOverwrittenCells);
979
+ item.redoMutations = item.redoMutations.flatMap(omitOverwrittenCells);
980
+ if (!item.undoMutations.length || !item.redoMutations.length) stack.splice(i, 1);
981
+ }
982
+ }
983
+ this._updateStatus();
984
+ }
985
+ transformDocumentHistory(unitID, remote, before) {
986
+ const after = applyDocumentChange2(before, remote);
987
+ this._transformStack(unitID, this._getUndoStack(unitID), "undoMutations", remote, after);
988
+ this._transformStack(unitID, this._getRedoStack(unitID), "redoMutations", remote, after);
989
+ this._updateStatus();
990
+ }
991
+ _transformStack(unitID, stack, forward, remote, document) {
992
+ const backward = forward === "undoMutations" ? "redoMutations" : "undoMutations";
993
+ const compose = (items) => items.reduce((op, item) => JSONX3.compose(op, documentEdit2(unitID, item.id, item.params)), null);
994
+ const mutation = (op, template) => [{ id: DOCUMENT_EDIT2, params: { unitId: unitID, actions: op, trigger: template?.params?.trigger, noNeedSetTextRange: true } }];
995
+ if (!stack) return;
996
+ for (let i = stack.length - 1; i >= 0 && remote; i--) {
997
+ const item = stack[i];
998
+ try {
999
+ const action = compose(item[forward]);
1000
+ const next = JSONX3.transform(action, remote, "right") ?? null;
1001
+ remote = JSONX3.transform(remote, action, "left") ?? null;
1002
+ if (!next) {
1003
+ stack.splice(i, 1);
1004
+ continue;
1005
+ }
1006
+ const inverse = JSONX3.invertWithDoc(structuredClone(next), structuredClone(document));
1007
+ document = applyDocumentChange2(document, next);
1008
+ item[forward] = mutation(next, item[forward][0]);
1009
+ item[backward] = mutation(inverse, item[backward][0]);
1010
+ } catch {
1011
+ stack.splice(0, i + 1);
1012
+ break;
1013
+ }
1014
+ }
1015
+ }
1016
+ };
1017
+
1018
+ // src/revision-recovery.ts
1019
+ import { acceptsSheetRevision } from "@cool-office/collaboration/sheet-objects";
1020
+ import { documentEdit as documentEdit3, DOCUMENT_EDIT as DOCUMENT_EDIT3, readDocumentChanges as readDocumentChanges2 } from "@cool-office/collaboration/document";
1021
+ import { Disposable as Disposable4, ICommandService, Inject as Inject4, IUniverInstanceService, JSONX as JSONX4 } from "@cool-office/core";
1022
+ import { ErrorCode as ErrorCode3 } from "@cool-office/protocol";
1023
+ import { BehaviorSubject as BehaviorSubject3, Subscription as Subscription2 } from "rxjs";
1024
+ var CollaborationRevisionRecovery = class extends Disposable4 {
1025
+ constructor(options, _commands, _snapshots, _sessions, _instances, _onDispose) {
1026
+ super();
1027
+ this.options = options;
1028
+ this._commands = _commands;
1029
+ this._snapshots = _snapshots;
1030
+ this._sessions = _sessions;
1031
+ this._instances = _instances;
1032
+ this._onDispose = _onDispose;
1033
+ this._status = new BehaviorSubject3("connecting");
1034
+ this.status$ = this._status.asObservable();
1035
+ this._subscriptions = new Subscription2();
1036
+ this._pending = [];
1037
+ this._session = null;
1038
+ this._generation = 0;
1039
+ this._localDirty = false;
1040
+ this._closed = false;
1041
+ this._reason = null;
1042
+ this._localEdits = [];
1043
+ this._inflight = null;
1044
+ this._ackTimer = null;
1045
+ this._nextRequest = 1;
1046
+ this._sid = globalThis.crypto?.randomUUID?.() ?? "";
1047
+ this._untrackedLocalEdit = false;
1048
+ if (!options.unitID || !Number.isSafeInteger(options.revision) || options.revision < 0) throw new Error("A unit and its loaded revision are required");
1049
+ const unit = this._instances.getUnit(options.unitID);
1050
+ if (!unit || unit.type !== options.unitType || unit.getRev() !== options.revision) throw new Error("Loaded unit does not match the supplied type and revision");
1051
+ this._revision = options.revision;
1052
+ this.disposeWithMe(this._commands.onMutationExecutedForCollab((command, execution) => this._localMutation(command, execution)));
1053
+ }
1054
+ get revision() {
1055
+ return this._revision;
1056
+ }
1057
+ get status() {
1058
+ return this._status.value;
1059
+ }
1060
+ get conflictReason() {
1061
+ return this._reason;
1062
+ }
1063
+ get hasWritePending() {
1064
+ return this._localEdits.length > 0 || this._untrackedLocalEdit;
1065
+ }
1066
+ /** Retains in-memory pending edits when the editor closes the bound unit. */
1067
+ markUnitUnavailable() {
1068
+ this._conflict("The bound unit was closed");
1069
+ }
1070
+ /** Memory-only copy for the caller to preserve or inspect before disposing the unit. */
1071
+ getPendingEdits() {
1072
+ return { edits: structuredClone(this._localEdits), incomplete: this._untrackedLocalEdit, awaitingConfirmation: this._inflight !== null };
1073
+ }
1074
+ async start() {
1075
+ if (this._closed || this._session) throw new Error("Recovery has already started or was disposed");
1076
+ const session = await this._sessions.requireSession(this.options.unitID);
1077
+ if (this._closed) return;
1078
+ this._session = session;
1079
+ this._subscriptions.add(session.event$.subscribe((event) => {
1080
+ if (event.eventID === "changeset_ack" && !this.options.nativeMutations) {
1081
+ this._ack(event.data);
1082
+ return;
1083
+ }
1084
+ if (event.eventID === "permission_rej" && this.options.nativeMutations) {
1085
+ this._clearAckTimer();
1086
+ this._reason = "Permission denied";
1087
+ this._status.next("denied");
1088
+ return;
1089
+ }
1090
+ if (event.eventID === "changeset_should_retry" && this.options.nativeMutations) {
1091
+ this._clearAckTimer();
1092
+ this._inflight = null;
1093
+ void this._recover();
1094
+ return;
1095
+ }
1096
+ if (event.eventID === "changeset_should_retry" || event.eventID === "changeset_rej" || event.eventID === "permission_rej") {
1097
+ this._conflict("Server rejected or could not safely apply the local edit");
1098
+ return;
1099
+ }
1100
+ if ((event.eventID === "new_changesets" || event.eventID === "changeset_ack") && event.data) {
1101
+ if (this.hasWritePending && !this.options.nativeMutations) {
1102
+ this._conflict("Remote changes arrived while local edits were pending");
1103
+ return;
1104
+ }
1105
+ const incoming = Array.isArray(event.data) ? event.data : [event.data];
1106
+ this._pending.push(...incoming);
1107
+ if (this.status === "synced" || this.status === "pending" && this.options.nativeMutations) {
1108
+ const revision = Math.min(...this._pending.map((item) => item.revision));
1109
+ if (Number.isSafeInteger(revision) && revision > this._revision + 1) void this._recover();
1110
+ else if (this._drain()) this._finishNative();
1111
+ }
1112
+ }
1113
+ }));
1114
+ this._subscriptions.add(session.sessionStatus$.subscribe((status) => {
1115
+ if (this.status === "conflict" || this.status === "denied") return;
1116
+ if (status === 3 /* ONLINE */) {
1117
+ void this._recover();
1118
+ } else if (status === 2 /* OFFLINE */) {
1119
+ this._generation++;
1120
+ this._clearAckTimer();
1121
+ if (this.hasWritePending && !this.options.nativeMutations) this._conflict("Connection lost before local edits were acknowledged");
1122
+ else this._status.next("offline");
1123
+ }
1124
+ }));
1125
+ }
1126
+ dispose() {
1127
+ if (this._closed) return;
1128
+ this._closed = true;
1129
+ this._generation++;
1130
+ this._clearAckTimer();
1131
+ this._subscriptions.unsubscribe();
1132
+ this._status.complete();
1133
+ this._onDispose?.();
1134
+ super.dispose();
1135
+ }
1136
+ _localMutation(command, execution) {
1137
+ if (this._closed || execution?.fromCollab || execution?.fromChangeset || execution?.onlyLocal) return;
1138
+ const params = command.params;
1139
+ const id = params?.unitId ?? params?.unitID ?? params?.target?.unitId;
1140
+ if (this.options.nativeMutations && id !== this.options.unitID) return;
1141
+ if (typeof id === "string" && id !== this.options.unitID) return;
1142
+ if (!params || typeof command.id !== "string") {
1143
+ this._untrackedLocalEdit = true;
1144
+ this._localDirty = true;
1145
+ this._conflict("Local mutation could not be recorded");
1146
+ return;
1147
+ }
1148
+ let edit;
1149
+ try {
1150
+ edit = { id: command.id, params: JSON.parse(JSON.stringify(command.params)) };
1151
+ } catch {
1152
+ this._untrackedLocalEdit = true;
1153
+ this._localDirty = true;
1154
+ this._conflict("Local mutation could not be recorded");
1155
+ return;
1156
+ }
1157
+ this._localEdits.push(edit);
1158
+ this._localDirty = true;
1159
+ const canQueue = this.options.nativeMutations && ["offline", "connecting", "recovering"].includes(this.status);
1160
+ if (!canQueue && this.status !== "synced" && this.status !== "pending" || !this.options.nativeMutations && execution?.syncOnly || id !== this.options.unitID || !this._acceptsLocal(edit) || !this.options.userID || !this._sid) {
1161
+ this._conflict("Local edit cannot be synchronized safely");
1162
+ return;
1163
+ }
1164
+ if (this.options.nativeMutations) {
1165
+ if (canQueue) return;
1166
+ this._status.next("pending");
1167
+ queueMicrotask(() => this._submitNext());
1168
+ } else this._submitNext();
1169
+ }
1170
+ _withinSheet(id, params) {
1171
+ const sheet = typeof params.subUnitId === "string" && this._instances.getUnit(this.options.unitID, 2)?.getSheetBySheetId(params.subUnitId);
1172
+ return !!sheet && acceptsSheetRevision(id, params, this.options.unitID, sheet.getSheetId(), { rowCount: sheet.getRowCount(), columnCount: sheet.getColumnCount() });
1173
+ }
1174
+ _acceptsLocal(edit) {
1175
+ if (this.options.nativeMutations) return /^[\w-]+\.mutation\.[\w-]+$/.test(edit.id) && this._commands.hasCommand(edit.id);
1176
+ if (this.options.sheetObjects && edit.id !== "sheet.mutation.set-range-values") return this._withinSheet(edit.id, edit.params);
1177
+ if (this.options.unitType !== 2 || edit.id !== "sheet.mutation.set-range-values") return false;
1178
+ const params = edit.params;
1179
+ if (Object.keys(params).some((key) => !["unitId", "subUnitId", "cellValue", "sourceFormulaData", "isOverrideStyle", "trigger", "__splitChunk__"].includes(key))) return false;
1180
+ if (params.unitId !== this.options.unitID || typeof params.subUnitId !== "string" || !params.cellValue || typeof params.cellValue !== "object" || params.sourceFormulaData || params.isOverrideStyle) return false;
1181
+ const workbook = this._instances.getUnit(this.options.unitID);
1182
+ const sheet = workbook?.getSheetBySheetId?.(params.subUnitId);
1183
+ if (!sheet) return false;
1184
+ let count = 0;
1185
+ for (const [rowText, columns] of Object.entries(params.cellValue)) {
1186
+ const row = Number(rowText);
1187
+ if (!Number.isSafeInteger(row) || row < 0 || !columns || typeof columns !== "object" || Array.isArray(columns)) return false;
1188
+ for (const [columnText, value] of Object.entries(columns)) {
1189
+ const column = Number(columnText);
1190
+ if (!Number.isSafeInteger(column) || column < 0 || !value || typeof value !== "object" || Array.isArray(value)) return false;
1191
+ const cell = value;
1192
+ if (Object.keys(cell).some((key) => key !== "v" && key !== "t") || !("v" in cell) || "t" in cell && cell.t !== null && ![1, 2, 3, 4].includes(cell.t)) return false;
1193
+ const v = cell.v;
1194
+ if (!(v === null || typeof v === "string" || typeof v === "number" && Number.isFinite(v))) return false;
1195
+ const actual = sheet.getCellRaw(row, column);
1196
+ if ((actual?.v ?? null) !== v || "t" in cell && (actual?.t ?? null) !== cell.t || actual?.f || actual?.si || actual?.p) return false;
1197
+ if (++count > 1e4) return false;
1198
+ }
1199
+ }
1200
+ return count > 0;
1201
+ }
1202
+ _submitNext() {
1203
+ const edit = this._localEdits[0];
1204
+ const session = this._session;
1205
+ const memberID = session?.getMemberID();
1206
+ if (!edit || this._inflight || this.status !== "synced" && this.status !== "pending") return;
1207
+ if (!session || !memberID || !this.options.userID) {
1208
+ this._conflict("Collaboration identity is unavailable");
1209
+ return;
1210
+ }
1211
+ const mutations = this.options.nativeMutations ? [...this._localEdits] : [edit];
1212
+ const inflight = { count: mutations.length, sid: this._sid, reqId: this._nextRequest++, baseRev: this._revision, memberID, mutations: structuredClone(mutations) };
1213
+ this._inflight = inflight;
1214
+ this._send(inflight, session, memberID);
1215
+ }
1216
+ _send(inflight, session, memberID) {
1217
+ this._status.next("pending");
1218
+ const changeset = { unitID: this.options.unitID, type: this.options.unitType, baseRev: inflight.baseRev, revision: 0, userID: this.options.userID, memberID, sid: inflight.sid, reqId: inflight.reqId, mutations: inflight.mutations };
1219
+ const reconnect = () => {
1220
+ if (this._closed || this._inflight !== inflight || this._isConflict() || this.status === "denied") return;
1221
+ if (this.options.nativeMutations) {
1222
+ this._clearAckTimer();
1223
+ this._sessions.reconnect();
1224
+ } else this._conflict("Local edit submission failed or its result is unknown");
1225
+ };
1226
+ this._ackTimer = setTimeout(() => {
1227
+ if (this.options.nativeMutations) reconnect();
1228
+ else if (this._inflight === inflight) this._conflict("Server acknowledgement timed out");
1229
+ }, 2e4);
1230
+ void session.send({ eventID: "submit_changeset", data: { unitID: this.options.unitID, unitType: this.options.unitType, changeset } }, this.options.unitID).catch((error) => {
1231
+ if (this._inflight !== inflight || this._closed || this.status === "denied") return;
1232
+ if (this.options.nativeMutations && (error?.status === 401 || error?.status === 403)) {
1233
+ this._clearAckTimer();
1234
+ this._reason = "Permission denied";
1235
+ this._status.next("denied");
1236
+ } else if (this.options.nativeMutations && error?.status && error.status >= 400 && error.status < 500 && error.status !== 429) {
1237
+ this._conflict("The server rejected the pending edit");
1238
+ } else reconnect();
1239
+ });
1240
+ }
1241
+ _ack(change) {
1242
+ const inflight = this._inflight;
1243
+ if (!inflight || this.status === "conflict") return;
1244
+ if (!change || change.unitID !== this.options.unitID || change.type !== this.options.unitType || change.sid !== inflight.sid || change.reqId !== inflight.reqId || change.memberID !== inflight.memberID || change.baseRev !== inflight.baseRev || change.revision !== inflight.baseRev + 1) {
1245
+ this._conflict("Unexpected acknowledgement");
1246
+ return;
1247
+ }
1248
+ const unit = this._instances.getUnit(this.options.unitID);
1249
+ if (!unit || unit.getRev() !== this._revision) {
1250
+ this._conflict("Local revision changed before acknowledgement");
1251
+ return;
1252
+ }
1253
+ try {
1254
+ unit.setRev(change.revision);
1255
+ } catch {
1256
+ this._conflict("Could not update the local revision");
1257
+ return;
1258
+ }
1259
+ this._clearAckTimer();
1260
+ this._revision = change.revision;
1261
+ this._localEdits.splice(0, inflight.count);
1262
+ this._inflight = null;
1263
+ this._localDirty = this._localEdits.length > 0;
1264
+ if (!this._localDirty) this._status.next("synced");
1265
+ this._submitNext();
1266
+ }
1267
+ _clearAckTimer() {
1268
+ if (this._ackTimer !== null) clearTimeout(this._ackTimer);
1269
+ this._ackTimer = null;
1270
+ }
1271
+ async _recover() {
1272
+ if (this._closed || this._localDirty && !this.options.nativeMutations || this.status === "conflict" || this.status === "denied") return;
1273
+ const generation = ++this._generation;
1274
+ this._status.next("recovering");
1275
+ try {
1276
+ const result = await this._snapshots.fetchMissingChangesets({}, { unitID: this.options.unitID, type: this.options.unitType, from: this._revision, to: 0 });
1277
+ if (generation !== this._generation || this._closed || this._isConflict()) return;
1278
+ if (result.error && result.error.code !== ErrorCode3.OK) throw new Error(result.error.message || "Could not fetch missing revisions");
1279
+ if (!Array.isArray(result.changesets)) throw new Error("Missing changeset list");
1280
+ this._pending.push(...result.changesets);
1281
+ if (!this._drain()) return;
1282
+ if (this._session?.sessionStatus !== 3 /* ONLINE */) return;
1283
+ if (this._session.requiresResync) this._session.markResynced();
1284
+ if (this.options.nativeMutations) {
1285
+ if (this._inflight && !this._ackTimer) {
1286
+ const memberID = this._session.getMemberID();
1287
+ if (memberID) this._send(this._inflight, this._session, memberID);
1288
+ }
1289
+ this._finishNative();
1290
+ } else this._status.next("synced");
1291
+ } catch (error) {
1292
+ if (generation === this._generation && !this._closed) this._conflict(error instanceof Error ? error.message : "Failed to recover revisions");
1293
+ }
1294
+ }
1295
+ _finishNative() {
1296
+ if (!this.options.nativeMutations || this._closed || this._isConflict()) return;
1297
+ this._status.next(this._localEdits.length ? "pending" : "synced");
1298
+ this._submitNext();
1299
+ }
1300
+ _applyNativeBatch(change, batch) {
1301
+ const first = this._inflight;
1302
+ if (first && change.userID === this.options.userID && change.sid === first.sid && change.reqId === first.reqId) {
1303
+ this._clearAckTimer();
1304
+ this._localEdits.splice(0, first.count);
1305
+ this._inflight = null;
1306
+ this._localDirty = this._localEdits.length > 0;
1307
+ return;
1308
+ }
1309
+ const apply = (edit) => {
1310
+ if (this._commands.syncExecuteCommand(edit.id, edit.params, { fromCollab: true, fromChangeset: true }) === false) throw new Error(`Mutation could not be applied: ${edit.id}`);
1311
+ };
1312
+ if (!this._localEdits.length) {
1313
+ if (this.options.unitType === 1 && batch.every((m) => m.id === DOCUMENT_EDIT3 || m.id === "doc.mutation.rename-doc")) {
1314
+ const doc = this._instances.getUnit(this.options.unitID, 1);
1315
+ if (doc) this.options.beforeRemoteDocument?.(readDocumentChanges2(this.options.unitID, change.mutations), doc.getSnapshot());
1316
+ }
1317
+ if (this.options.unitType === 2) this.options.beforeRemoteSheet?.(batch);
1318
+ batch.forEach(apply);
1319
+ if (batch.some((m) => m.id === "univer.mutation.revert-version")) this.options.onRemoteRestore?.();
1320
+ return;
1321
+ }
1322
+ const edits = [...batch, ...this._localEdits];
1323
+ if (edits.every((m) => m.id === "sheet.mutation.set-range-values")) {
1324
+ batch.forEach(apply);
1325
+ this._localEdits.forEach(apply);
1326
+ return;
1327
+ }
1328
+ if (edits.every((m) => m.id === DOCUMENT_EDIT3 || m.id === "doc.mutation.rename-doc")) {
1329
+ let remote = readDocumentChanges2(this.options.unitID, change.mutations);
1330
+ for (const edit of this._localEdits) {
1331
+ const local = documentEdit3(this.options.unitID, edit.id, edit.params);
1332
+ const actions = JSONX4.transform(local, remote, "right") ?? null;
1333
+ remote = JSONX4.transform(remote, local, "left") ?? null;
1334
+ edit.id = DOCUMENT_EDIT3;
1335
+ edit.params = { unitId: this.options.unitID, actions };
1336
+ }
1337
+ if (remote) {
1338
+ const doc = this._instances.getUnit(this.options.unitID, 1);
1339
+ if (doc) this.options.beforeRemoteDocument?.(remote, doc.getSnapshot());
1340
+ apply({ id: DOCUMENT_EDIT3, params: { unitId: this.options.unitID, actions: remote, noNeedSetTextRange: true } });
1341
+ }
1342
+ return;
1343
+ }
1344
+ throw new Error("Concurrent edits affect the same file structure");
1345
+ }
1346
+ _drain() {
1347
+ this._pending.sort((a, b) => a.revision - b.revision);
1348
+ while (this._pending.length && this.status !== "conflict") {
1349
+ const change = this._pending.shift();
1350
+ if (!Number.isSafeInteger(change.revision)) {
1351
+ this._conflict("Invalid revision");
1352
+ return false;
1353
+ }
1354
+ if (change.revision <= this._revision) continue;
1355
+ if (change.unitID !== this.options.unitID || change.type !== this.options.unitType || change.baseRev !== this._revision || change.revision !== this._revision + 1) {
1356
+ this._conflict("Missing or inconsistent revision");
1357
+ return false;
1358
+ }
1359
+ if (!Array.isArray(change.mutations) || !this.options.nativeMutations && change.mutations.length !== 1) {
1360
+ this._conflict("Unsupported multi-mutation revision");
1361
+ return false;
1362
+ }
1363
+ try {
1364
+ const unit = this._instances.getUnit(this.options.unitID);
1365
+ if (!unit || unit.getRev() !== this._revision) throw new Error("Local revision changed before remote mutation");
1366
+ const batch = change.mutations.map((mutation) => {
1367
+ if (!mutation || typeof mutation.id !== "string" || typeof mutation.data !== "string" || !this._commands.hasCommand(mutation.id)) throw new Error("Invalid mutation");
1368
+ const params = JSON.parse(mutation.data);
1369
+ if (!params || typeof params !== "object" || Array.isArray(params) || (params.unitId ?? params.unitID ?? params.target?.unitId) !== this.options.unitID) throw new Error("Invalid mutation target");
1370
+ if (this.options.sheetObjects && !this._withinSheet(mutation.id, params)) throw new Error("Unsupported workbook object revision");
1371
+ return { id: mutation.id, params };
1372
+ });
1373
+ if (this.options.nativeMutations) this._applyNativeBatch(change, batch);
1374
+ else for (const { id, params } of batch) if (this._commands.syncExecuteCommand(id, params, { fromCollab: true, fromChangeset: true }) === false) throw new Error(`Mutation could not be applied: ${id}`);
1375
+ if (this._localDirty && !this.options.nativeMutations || this._isConflict()) return false;
1376
+ if (unit.getRev() !== this._revision) throw new Error("Local revision changed during remote mutation");
1377
+ unit.setRev(change.revision);
1378
+ this._revision = change.revision;
1379
+ } catch (error) {
1380
+ this._conflict(error instanceof Error ? error.message : "Failed to apply mutation");
1381
+ return false;
1382
+ }
1383
+ }
1384
+ return this.status !== "conflict";
1385
+ }
1386
+ _conflict(reason) {
1387
+ if (this._closed || this.status === "conflict") return;
1388
+ this._generation++;
1389
+ this._clearAckTimer();
1390
+ this._reason = reason;
1391
+ this._status.next("conflict");
1392
+ }
1393
+ _isConflict() {
1394
+ return this._status.value === "conflict";
1395
+ }
1396
+ };
1397
+ var CollaborationRevisionRecoveryService = class {
1398
+ constructor(_commands, _snapshots, _sessions, _instances) {
1399
+ this._commands = _commands;
1400
+ this._snapshots = _snapshots;
1401
+ this._sessions = _sessions;
1402
+ this._instances = _instances;
1403
+ this._active = new BehaviorSubject3(/* @__PURE__ */ new Map());
1404
+ this.active$ = this._active.asObservable();
1405
+ }
1406
+ get(unitID) {
1407
+ return this._active.value.get(unitID);
1408
+ }
1409
+ async attach(options) {
1410
+ if (this._active.value.has(options.unitID)) throw new Error("A collaboration recovery is already attached to this unit");
1411
+ const remove = () => {
1412
+ if (this._active.value.get(options.unitID) !== recovery) return;
1413
+ const next2 = new Map(this._active.value);
1414
+ next2.delete(options.unitID);
1415
+ this._active.next(next2);
1416
+ };
1417
+ const model = this._instances.getUnit(options.unitID, 1);
1418
+ const recovery = options.unitType === 1 && options.document && model ? new DocumentCollaborationRecovery(options, this._commands, this._snapshots, this._sessions, model, options.document, remove) : new CollaborationRevisionRecovery(options, this._commands, this._snapshots, this._sessions, this._instances, remove);
1419
+ const next = new Map(this._active.value);
1420
+ next.set(options.unitID, recovery);
1421
+ this._active.next(next);
1422
+ try {
1423
+ await recovery.start();
1424
+ return recovery;
1425
+ } catch (error) {
1426
+ recovery.dispose();
1427
+ throw error;
1428
+ }
1429
+ }
1430
+ };
1431
+ CollaborationRevisionRecoveryService = __decorateClass([
1432
+ __decorateParam(0, Inject4(ICommandService)),
1433
+ __decorateParam(1, Inject4(SnapshotServerOverHTTPService)),
1434
+ __decorateParam(2, Inject4(CollaborationSessionService)),
1435
+ __decorateParam(3, IUniverInstanceService)
1436
+ ], CollaborationRevisionRecoveryService);
1437
+
1438
+ // src/assets.ts
1439
+ import { createIdentifier as createIdentifier2, Disposable as Disposable5, IConfigService as IConfigService4, ImageSourceType, ImageUploadStatusType, Inject as Inject5, IUniverInstanceService as IUniverInstanceService2 } from "@cool-office/core";
1440
+ import { FileSource } from "@cool-office/protocol";
1441
+ import { BehaviorSubject as BehaviorSubject4 } from "rxjs";
1442
+ var IAttachmentIoService = createIdentifier2("cool-office.collaboration.attachment-io");
1443
+ var CollaborationAttachmentIoService = class {
1444
+ constructor(settings, units) {
1445
+ this.settings = settings;
1446
+ this.units = units;
1447
+ }
1448
+ get config() {
1449
+ return this.settings.getConfig(COLLABORATION_CLIENT_PLUGIN_CONFIG_KEY) ?? {};
1450
+ }
1451
+ getUploadOptions() {
1452
+ return this.config.attachment ?? {};
1453
+ }
1454
+ async saveAttachment(file) {
1455
+ const options = this.getUploadOptions();
1456
+ if (options.maxSize && file.size > options.maxSize) throw new Error("File is too large");
1457
+ if (options.accept?.length && !options.accept.some((pattern) => pattern.startsWith(".") ? file.name.toLowerCase().endsWith(pattern.toLowerCase()) : pattern.endsWith("/*") ? file.type.startsWith(pattern.slice(0, -1)) : file.type === pattern)) throw new Error("File type is not supported");
1458
+ if (options.upload) return options.upload(file);
1459
+ const id = this.units.getFocusedUnit()?.getUnitId();
1460
+ if (!id) throw new Error("No active file");
1461
+ const url = new URL(this.config.uploadFileServerUrl ?? "/universer-api/stream/file/upload", location.origin);
1462
+ url.searchParams.set("source", String(FileSource.UnitEmbedded));
1463
+ url.searchParams.set("assign", id);
1464
+ url.searchParams.set("size", String(file.size));
1465
+ const form = new FormData();
1466
+ form.append("file", file, file.name);
1467
+ const response = await fetch(url, { method: "POST", headers: this.config.customHeaders, credentials: "same-origin", body: form });
1468
+ if (!response.ok) throw new Error(`File upload failed (${response.status})`);
1469
+ const { FileId: fileId } = await response.json();
1470
+ if (typeof fileId !== "string" || !fileId) throw new Error("File ID is missing");
1471
+ return { id: fileId, name: file.name, mimeType: file.type, size: file.size, source: fileId, sourceType: ImageSourceType.UUID };
1472
+ }
1473
+ async getAttachmentUrl(source, type) {
1474
+ if (type !== ImageSourceType.UUID) return source;
1475
+ const replaceID = (url2) => url2.replace("{fileID}", encodeURIComponent(source));
1476
+ if (this.config.downloadEndpointUrl) return replaceID(this.config.downloadEndpointUrl);
1477
+ const response = await fetch(replaceID(this.config.signUrlServerUrl ?? "/universer-api/file/{fileID}/sign-url"), { headers: this.config.customHeaders, credentials: "same-origin" });
1478
+ if (!response.ok) throw new Error(`File is unavailable (${response.status})`);
1479
+ const { url } = await response.json();
1480
+ if (typeof url !== "string" || !url) throw new Error("File URL is missing");
1481
+ return url;
1482
+ }
1483
+ };
1484
+ CollaborationAttachmentIoService = __decorateClass([
1485
+ __decorateParam(0, IConfigService4),
1486
+ __decorateParam(1, IUniverInstanceService2)
1487
+ ], CollaborationAttachmentIoService);
1488
+ var CollaborationImageIoService = class extends Disposable5 {
1489
+ constructor(assets) {
1490
+ super();
1491
+ this.assets = assets;
1492
+ this.waiting = new BehaviorSubject4(0);
1493
+ this.change$ = this.waiting.asObservable();
1494
+ this.cache = /* @__PURE__ */ new Map();
1495
+ }
1496
+ setWaitCount(count) {
1497
+ this.waiting.next(Math.max(0, count));
1498
+ }
1499
+ getImage(id) {
1500
+ return this.assets.getAttachmentUrl(id, ImageSourceType.UUID);
1501
+ }
1502
+ async saveImage(file) {
1503
+ try {
1504
+ if (!file.type.startsWith("image/")) return { imageId: "", source: "", base64Cache: "", imageSourceType: ImageSourceType.UUID, status: ImageUploadStatusType.ERROR_IMAGE_TYPE };
1505
+ const result = await this.assets.saveAttachment(file);
1506
+ return { imageId: result.id, source: result.source ?? result.id, base64Cache: "", imageSourceType: result.sourceType ?? ImageSourceType.UUID, status: ImageUploadStatusType.SUCCUSS };
1507
+ } finally {
1508
+ this.setWaitCount(this.waiting.value - 1);
1509
+ }
1510
+ }
1511
+ getImageSourceCache(source, type) {
1512
+ return this.cache.get(type + source);
1513
+ }
1514
+ addImageSourceCache(source, type, image) {
1515
+ if (image) this.cache.set(type + source, image);
1516
+ else this.cache.delete(type + source);
1517
+ }
1518
+ dispose() {
1519
+ this.cache.clear();
1520
+ this.waiting.complete();
1521
+ super.dispose();
1522
+ }
1523
+ };
1524
+ CollaborationImageIoService = __decorateClass([
1525
+ __decorateParam(0, Inject5(CollaborationAttachmentIoService))
1526
+ ], CollaborationImageIoService);
1527
+
1528
+ // src/workspace.ts
1529
+ import { DependentOn, Disposable as Disposable6, IConfigService as IConfigService6, IImageIoService, IMentionIOService as IMentionIOService2, Inject as Inject6, Injector as Injector2, IUndoRedoService, IUniverInstanceService as IUniverInstanceService4, mergeOverrideWithDependencies, Plugin, registerDependencies, UserManagerService } from "@cool-office/core";
1530
+ import { ISnapshotServerService, UniverCollaborationPlugin } from "@cool-office/collaboration";
1531
+ import { UniverNetworkPlugin } from "@cool-office/network";
1532
+ import { BehaviorSubject as BehaviorSubject5, filter as filter2, firstValueFrom as firstValueFrom2, map, Subject as Subject3, timeout as timeout2 } from "rxjs";
1533
+
1534
+ // src/authorization.ts
1535
+ import { IAuthzIoService, IConfigService as IConfigService5, IUniverInstanceService as IUniverInstanceService3, MentionType } from "@cool-office/core";
1536
+ import { ErrorCode as ErrorCode4 } from "@cool-office/protocol";
1537
+ var part = (value) => encodeURIComponent(value);
1538
+ var CollaborationMentionService = class {
1539
+ constructor(grants, units) {
1540
+ this.grants = grants;
1541
+ this.units = units;
1542
+ }
1543
+ async list(params) {
1544
+ const id = params.unitId ?? this.units.getFocusedUnit()?.getUnitId();
1545
+ if (!id || params.type !== void 0 && params.type !== MentionType.PERSON) return { list: [], total: 0 };
1546
+ const people = await this.grants.listCollaborators({ unitID: id, objectID: id });
1547
+ const query = params.search?.toLocaleLowerCase() ?? "";
1548
+ const mentions = people.flatMap(({ subject }) => subject && subject.name.toLocaleLowerCase().includes(query) ? [{ objectType: MentionType.PERSON, objectId: subject.userID, label: subject.name, metadata: { icon: subject.avatar } }] : []);
1549
+ const offset = Math.max(0, (params.page ?? 1) - 1) * (params.size ?? mentions.length);
1550
+ return { list: [{ type: MentionType.PERSON, title: "PEOPLE", metadata: {}, mentions: mentions.slice(offset, offset + (params.size ?? mentions.length)) }], total: mentions.length, page: params.page, size: params.size };
1551
+ }
1552
+ };
1553
+ CollaborationMentionService = __decorateClass([
1554
+ __decorateParam(0, IAuthzIoService),
1555
+ __decorateParam(1, IUniverInstanceService3)
1556
+ ], CollaborationMentionService);
1557
+ var RemoteAuthorizationService = class {
1558
+ constructor(config) {
1559
+ this.config = config;
1560
+ this.inherit = true;
1561
+ }
1562
+ async request(path, method, input) {
1563
+ const settings = this.config.getConfig(COLLABORATION_CLIENT_PLUGIN_CONFIG_KEY);
1564
+ const prefix = (settings?.authzUrl ?? "/universer-api/authz").replace(/\/$/, "");
1565
+ const result = await fetch(prefix + path, { method, credentials: "same-origin", headers: { "content-type": "application/json", ...settings?.customHeaders }, body: input && JSON.stringify(input) });
1566
+ const data = await result.json();
1567
+ if (!result.ok || data.error && data.error.code !== ErrorCode4.OK) throw new Error(data.error?.message || `Permission request failed (${result.status})`);
1568
+ return data;
1569
+ }
1570
+ async create(input) {
1571
+ return (await this.request(`/${part(input.objectType)}/object`, "POST", input)).objectID;
1572
+ }
1573
+ async allowed(input) {
1574
+ return (await this.request(`/${part(input.objectType)}/object/${part(input.objectID)}/allowed`, "POST", input)).actions;
1575
+ }
1576
+ async batchAllowed(requests) {
1577
+ return (await this.request("/-/object/-/batch_allowed", "POST", { requests })).objectActions;
1578
+ }
1579
+ async list(input) {
1580
+ return (await this.request("/-/object/list", "POST", input)).objects;
1581
+ }
1582
+ async listRoles(input) {
1583
+ const { roles, actions } = await this.request(`/${part(input.objectType)}/roles`, "GET");
1584
+ return { roles, actions };
1585
+ }
1586
+ async update(input) {
1587
+ await this.request(`/${part(input.objectType)}/object/${part(input.objectID)}`, "PUT", input);
1588
+ }
1589
+ async listCollaborators(input) {
1590
+ const query = new URLSearchParams(Object.entries(input).map(([key, val]) => [key, String(val)]));
1591
+ const data = await this.request(`/collaborator?${query}`, "GET");
1592
+ this.inherit = data.cfgEnableObjInherit;
1593
+ return data.collaborators;
1594
+ }
1595
+ async updateCollaborator(input) {
1596
+ await this.request("/collaborator", "PATCH", input);
1597
+ }
1598
+ async deleteCollaborator(input) {
1599
+ await this.request("/collaborator", "DELETE", input);
1600
+ }
1601
+ async createCollaborator(input) {
1602
+ await this.request("/collaborator", "POST", input);
1603
+ }
1604
+ async putCollaborators(input) {
1605
+ await this.request("/collaborator", "PUT", input);
1606
+ }
1607
+ setCfgEnableObjInherit(value) {
1608
+ this.inherit = value;
1609
+ }
1610
+ getCfgEnableObjInherit() {
1611
+ return this.inherit;
1612
+ }
1613
+ };
1614
+ RemoteAuthorizationService = __decorateClass([
1615
+ __decorateParam(0, IConfigService5)
1616
+ ], RemoteAuthorizationService);
1617
+
1618
+ // src/workspace.ts
1619
+ import { IAuthzIoService as IAuthzIoService2 } from "@cool-office/core";
1620
+ var CollaborationStatus = /* @__PURE__ */ ((CollaborationStatus2) => {
1621
+ CollaborationStatus2["NOT_COLLAB"] = "not_collab";
1622
+ CollaborationStatus2["SYNCED"] = "synced";
1623
+ CollaborationStatus2["PENDING"] = "pending";
1624
+ CollaborationStatus2["AWAITING"] = "awaiting";
1625
+ CollaborationStatus2["AWAITING_WITH_PENDING"] = "awaiting_with_pending";
1626
+ CollaborationStatus2["FETCH_MISS"] = "fetch_missing";
1627
+ CollaborationStatus2["CONFLICT"] = "conflict";
1628
+ CollaborationStatus2["OFFLINE"] = "offline";
1629
+ return CollaborationStatus2;
1630
+ })(CollaborationStatus || {});
1631
+ var CollaborationUIEventId = /* @__PURE__ */ ((CollaborationUIEventId2) => {
1632
+ CollaborationUIEventId2["PERMISSION_DENIED"] = "PERMISSION_DENIED";
1633
+ CollaborationUIEventId2["CONFLICT"] = "CONFLICT";
1634
+ CollaborationUIEventId2["CLOSE_ROOM"] = "CLOSE_ROOM";
1635
+ CollaborationUIEventId2["REVISION_RESTORED"] = "REVISION_RESTORED";
1636
+ return CollaborationUIEventId2;
1637
+ })(CollaborationUIEventId || {});
1638
+ var CollaborationUIEventService = class extends Disposable6 {
1639
+ constructor() {
1640
+ super(...arguments);
1641
+ this.event$ = new Subject3();
1642
+ }
1643
+ dispose() {
1644
+ this.event$.complete();
1645
+ super.dispose();
1646
+ }
1647
+ };
1648
+ var MemberService = class extends Disposable6 {
1649
+ constructor(sessions) {
1650
+ super();
1651
+ this.rooms = new BehaviorSubject5(/* @__PURE__ */ new Map());
1652
+ this.disposeWithMe(sessions.roomEvents$.subscribe(({ unitID, event }) => {
1653
+ if (!["room_joined", "users_enter", "users_leave"].includes(event.eventID)) return;
1654
+ const payload = event.data;
1655
+ let room = this.rooms.value.get(unitID);
1656
+ if (!room) {
1657
+ room = { members$: new BehaviorSubject5(/* @__PURE__ */ new Map()) };
1658
+ this.rooms.next(new Map(this.rooms.value).set(unitID, room));
1659
+ }
1660
+ const members = new Map(event.eventID === "room_joined" ? [] : room.members$.value);
1661
+ for (const person of payload?.members ?? (payload?.memberID ? [payload] : [])) {
1662
+ if (event.eventID === "users_leave") members.delete(person.memberID);
1663
+ else members.set(person.memberID, person);
1664
+ }
1665
+ room.members$.next(members);
1666
+ }));
1667
+ }
1668
+ getRoom(unitID) {
1669
+ return this.rooms.value.get(unitID);
1670
+ }
1671
+ waitForRoom$(unitID) {
1672
+ return this.rooms.pipe(map((rooms) => rooms.get(unitID)));
1673
+ }
1674
+ dispose() {
1675
+ for (const room of this.rooms.value.values()) room.members$.complete();
1676
+ this.rooms.complete();
1677
+ super.dispose();
1678
+ }
1679
+ };
1680
+ MemberService = __decorateClass([
1681
+ __decorateParam(0, Inject6(CollaborationSessionService))
1682
+ ], MemberService);
1683
+ var CommentService = class {
1684
+ constructor(sessions) {
1685
+ this.commentUpdate$ = sessions.roomEvents$.pipe(filter2((e) => e.event.eventID === "comment_update"), map((e) => e.event.data));
1686
+ }
1687
+ };
1688
+ CommentService = __decorateClass([
1689
+ __decorateParam(0, Inject6(CollaborationSessionService))
1690
+ ], CommentService);
1691
+ var CollaborationController = class extends Disposable6 {
1692
+ constructor(config, units, users, recoveries, events, _members, history) {
1693
+ super();
1694
+ this.config = config;
1695
+ this.units = units;
1696
+ this.users = users;
1697
+ this.recoveries = recoveries;
1698
+ this.events = events;
1699
+ this.history = history;
1700
+ this.statusChanged$ = new Subject3();
1701
+ this.ready = /* @__PURE__ */ new Map();
1702
+ this.statuses = /* @__PURE__ */ new Map();
1703
+ this.disposeWithMe(this.units.unitDisposed$.subscribe((unit) => {
1704
+ const id = unit.getUnitId();
1705
+ this.recoveries.get(id)?.dispose();
1706
+ this.ready.delete(id);
1707
+ this.statuses.delete(id);
1708
+ }));
1709
+ }
1710
+ getStatus(id) {
1711
+ return this.statuses.get(id) ?? "not_collab" /* NOT_COLLAB */;
1712
+ }
1713
+ readyForCollab(id) {
1714
+ if (this.config.getConfig(COLLABORATION_CLIENT_PLUGIN_CONFIG_KEY)?.enableCollaboration === false) return Promise.resolve();
1715
+ const pending = this.ready.get(id);
1716
+ if (pending) return pending;
1717
+ const starting = this.start(id).catch((error) => {
1718
+ this.ready.delete(id);
1719
+ throw error;
1720
+ });
1721
+ this.ready.set(id, starting);
1722
+ return starting;
1723
+ }
1724
+ async start(id) {
1725
+ const unit = this.units.getUnit(id);
1726
+ if (!unit) throw new Error("File is unavailable");
1727
+ const undo = this.history instanceof DocumentCollaborationUndoService ? this.history : void 0;
1728
+ const recovery = this.recoveries.get(id) ?? await this.recoveries.attach({
1729
+ unitID: id,
1730
+ unitType: unit.type,
1731
+ revision: unit.getRev(),
1732
+ userID: this.users.getCurrentUser().userID,
1733
+ nativeMutations: true,
1734
+ onRemoteRestore: () => this.events.event$.next({ id: "REVISION_RESTORED" /* REVISION_RESTORED */, unitID: id }),
1735
+ beforeRemoteDocument: (actions, before) => undo?.transformDocumentHistory(id, actions, before),
1736
+ beforeRemoteSheet: (changes) => undo?.transformSheetHistory(id, changes)
1737
+ });
1738
+ this.disposeWithMe(recovery.status$.subscribe((status) => {
1739
+ const mapped = status === "synced" || status === "readonly" ? "synced" /* SYNCED */ : status === "pending" ? "pending" /* PENDING */ : status === "offline" ? "offline" /* OFFLINE */ : status === "conflict" || status === "denied" ? "conflict" /* CONFLICT */ : "fetch_missing" /* FETCH_MISS */;
1740
+ this.statuses.set(id, mapped);
1741
+ this.statusChanged$.next({ unitId: id, status: mapped });
1742
+ if (status === "denied" || status === "conflict") this.events.event$.next({ id: status === "denied" ? "PERMISSION_DENIED" /* PERMISSION_DENIED */ : "CONFLICT" /* CONFLICT */, unitID: id });
1743
+ }));
1744
+ await this.flush(id);
1745
+ }
1746
+ async flush(id, options) {
1747
+ const recovery = this.recoveries.get(id);
1748
+ if (!recovery) return;
1749
+ const status = await firstValueFrom2(recovery.status$.pipe(filter2((s) => s === "synced" || s === "readonly" || s === "denied" || s === "conflict"), timeout2(options?.timeoutMs ?? 3e4)));
1750
+ if (status === "denied" || status === "conflict") throw new Error(recovery.conflictReason ?? "Edits could not be synchronized");
1751
+ }
1752
+ dispose() {
1753
+ for (const id of this.ready.keys()) this.recoveries.get(id)?.dispose();
1754
+ this.ready.clear();
1755
+ this.statusChanged$.complete();
1756
+ super.dispose();
1757
+ }
1758
+ };
1759
+ CollaborationController = __decorateClass([
1760
+ __decorateParam(0, IConfigService6),
1761
+ __decorateParam(1, IUniverInstanceService4),
1762
+ __decorateParam(2, Inject6(UserManagerService)),
1763
+ __decorateParam(3, Inject6(CollaborationRevisionRecoveryService)),
1764
+ __decorateParam(4, Inject6(CollaborationUIEventService)),
1765
+ __decorateParam(5, Inject6(MemberService)),
1766
+ __decorateParam(6, IUndoRedoService)
1767
+ ], CollaborationController);
1768
+ var UniverCollaborationClientPlugin = class extends Plugin {
1769
+ constructor(config = {}, _injector) {
1770
+ super();
1771
+ this.config = config;
1772
+ this._injector = _injector;
1773
+ }
1774
+ onStarting() {
1775
+ this._injector.get(IConfigService6).setConfig(COLLABORATION_CLIENT_PLUGIN_CONFIG_KEY, this.config);
1776
+ registerDependencies(this._injector, mergeOverrideWithDependencies([
1777
+ [SnapshotServerOverHTTPService],
1778
+ [ISnapshotServerService, { useExisting: SnapshotServerOverHTTPService }],
1779
+ [ICollaborationSocketService, { useClass: this.config.socketService ?? CollaborationSocketService }],
1780
+ [CollaborationSessionService],
1781
+ [CollaborationRevisionRecoveryService],
1782
+ [CollaborationUIEventService],
1783
+ [MemberService],
1784
+ [CommentService],
1785
+ [CollaborationController],
1786
+ [CollaborationAttachmentIoService],
1787
+ [IAttachmentIoService, { useExisting: CollaborationAttachmentIoService }],
1788
+ [IImageIoService, { useClass: CollaborationImageIoService }]
1789
+ ], this.config.override));
1790
+ if (!this._injector.has(IUndoRedoService)) this._injector.add([IUndoRedoService, { useClass: DocumentCollaborationUndoService }]);
1791
+ if (!this._injector.has(IMentionIOService2)) this._injector.add([IMentionIOService2, { useClass: CollaborationMentionService }]);
1792
+ if (this.config.enableAuthServer) {
1793
+ if (this._injector.has(IAuthzIoService2)) this._injector.replace([IAuthzIoService2, { useClass: RemoteAuthorizationService }]);
1794
+ else this._injector.add([IAuthzIoService2, { useClass: RemoteAuthorizationService }]);
1795
+ }
1796
+ }
1797
+ };
1798
+ UniverCollaborationClientPlugin.pluginName = "COOL_COLLABORATION_CLIENT_PLUGIN";
1799
+ UniverCollaborationClientPlugin.packageName = "@cool-office/collaboration-client";
1800
+ UniverCollaborationClientPlugin.version = "1.2.0";
1801
+ UniverCollaborationClientPlugin = __decorateClass([
1802
+ DependentOn(UniverCollaborationPlugin, UniverNetworkPlugin),
1803
+ __decorateParam(1, Inject6(Injector2))
1804
+ ], UniverCollaborationClientPlugin);
1805
+
1806
+ export {
1807
+ DEFAULT_SNAPSHOT_SERVER_URL,
1808
+ SNAPSHOT_URL_KEY,
1809
+ COLLABORATION_CLIENT_PLUGIN_CONFIG_KEY,
1810
+ SnapshotServerOverHTTPService,
1811
+ ICollaborationSocketService,
1812
+ serializeCombRequest,
1813
+ deserializeToCombResponse,
1814
+ CollaborationSocketService,
1815
+ SessionStatus,
1816
+ CollaborationSession,
1817
+ CollaborationSessionService,
1818
+ DocumentCollaborationRecovery,
1819
+ DocumentCollaborationUndoService,
1820
+ CollaborationRevisionRecovery,
1821
+ CollaborationRevisionRecoveryService,
1822
+ IAttachmentIoService,
1823
+ CollaborationAttachmentIoService,
1824
+ CollaborationImageIoService,
1825
+ CollaborationStatus,
1826
+ CollaborationUIEventId,
1827
+ CollaborationUIEventService,
1828
+ MemberService,
1829
+ CommentService,
1830
+ CollaborationController,
1831
+ UniverCollaborationClientPlugin
1832
+ };