@ai-matrx/office 0.5.2 → 0.6.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +23 -0
- package/dist/chunk-2UBGQUXW.cjs.map +1 -1
- package/dist/chunk-BWMAYLW4.cjs.map +1 -1
- package/dist/chunk-O6FTSXHE.cjs.map +1 -1
- package/dist/chunk-QZE7HBZB.cjs.map +1 -1
- package/dist/chunk-ZDZCCOUB.cjs.map +1 -1
- package/dist/docs-host.cjs +40 -0
- package/dist/docs-host.cjs.map +1 -0
- package/dist/docs-host.d.cts +28 -0
- package/dist/docs-host.d.ts +28 -0
- package/dist/docs-host.js +19 -0
- package/dist/docs-host.js.map +1 -0
- package/dist/docs-io.cjs.map +1 -1
- package/dist/docs-tools.cjs.map +1 -1
- package/dist/docs.cjs +62 -19
- package/dist/docs.cjs.map +1 -1
- package/dist/docs.d.cts +25 -2
- package/dist/docs.d.ts +25 -2
- package/dist/docs.js +51 -8
- package/dist/docs.js.map +1 -1
- package/dist/matrxImagePorts-JDFYE4QI.cjs.map +1 -1
- package/dist/sheets-xlsx.cjs.map +1 -1
- package/dist/sheets.cjs.map +1 -1
- package/dist/univer-collab.cjs +111 -24
- package/dist/univer-collab.cjs.map +1 -1
- package/dist/univer-collab.d.cts +64 -13
- package/dist/univer-collab.d.ts +64 -13
- package/dist/univer-collab.js +111 -24
- package/dist/univer-collab.js.map +1 -1
- package/dist/univer.cjs +19 -0
- package/dist/univer.cjs.map +1 -1
- package/dist/univer.d.cts +16 -1
- package/dist/univer.d.ts +16 -1
- package/dist/univer.js +19 -0
- package/dist/univer.js.map +1 -1
- package/dist/xlsx-to-univer-AQAXU3TC.cjs.map +1 -1
- package/package.json +14 -4
package/dist/univer-collab.cjs
CHANGED
|
@@ -31,8 +31,11 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
|
|
|
31
31
|
// src/univer/collab/index.ts
|
|
32
32
|
var collab_exports = {};
|
|
33
33
|
__export(collab_exports, {
|
|
34
|
+
COLLAB_COVERED_KEY: () => COLLAB_COVERED_KEY,
|
|
34
35
|
WorkbookCollabSession: () => WorkbookCollabSession,
|
|
35
|
-
isCellEditorScratch: () => isCellEditorScratch
|
|
36
|
+
isCellEditorScratch: () => isCellEditorScratch,
|
|
37
|
+
stampCovered: () => stampCovered,
|
|
38
|
+
takeCovered: () => takeCovered
|
|
36
39
|
});
|
|
37
40
|
module.exports = __toCommonJS(collab_exports);
|
|
38
41
|
|
|
@@ -40,9 +43,28 @@ module.exports = __toCommonJS(collab_exports);
|
|
|
40
43
|
var Y = __toESM(require("yjs"), 1);
|
|
41
44
|
var import_awareness = require("y-protocols/awareness");
|
|
42
45
|
var import_collab = require("@ai-matrx/data/realtime/collab");
|
|
46
|
+
|
|
47
|
+
// src/univer/collab/covered.ts
|
|
48
|
+
var COLLAB_COVERED_KEY = "__matrxCollabCovered";
|
|
49
|
+
function stampCovered(snapshot, covered) {
|
|
50
|
+
return { ...snapshot, [COLLAB_COVERED_KEY]: [...covered] };
|
|
51
|
+
}
|
|
52
|
+
function takeCovered(snapshot) {
|
|
53
|
+
if (!snapshot || typeof snapshot !== "object" || !(COLLAB_COVERED_KEY in snapshot)) {
|
|
54
|
+
return { snapshot, covered: /* @__PURE__ */ new Set() };
|
|
55
|
+
}
|
|
56
|
+
const { [COLLAB_COVERED_KEY]: list, ...rest } = snapshot;
|
|
57
|
+
return {
|
|
58
|
+
snapshot: rest,
|
|
59
|
+
covered: new Set(Array.isArray(list) ? list.filter((e) => typeof e === "string") : [])
|
|
60
|
+
};
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
// src/univer/collab/WorkbookCollabSession.ts
|
|
43
64
|
var MUTATIONS_ARRAY_KEY = "mutations";
|
|
44
65
|
var CONTROL_MAP_KEY = "control";
|
|
45
66
|
var REPLACED_KEY = "replaced";
|
|
67
|
+
var CHECKPOINT_KEY = "checkpoint";
|
|
46
68
|
var WorkbookCollabSession = class {
|
|
47
69
|
options;
|
|
48
70
|
doc = null;
|
|
@@ -56,6 +78,15 @@ var WorkbookCollabSession = class {
|
|
|
56
78
|
muted = 0;
|
|
57
79
|
started = false;
|
|
58
80
|
disposed = false;
|
|
81
|
+
/** Room entries this seat holds in its content: applied from a peer, or made here. */
|
|
82
|
+
applied = /* @__PURE__ */ new Set();
|
|
83
|
+
/** Entries without an id (a peer on an older build) are applied once, by identity. */
|
|
84
|
+
appliedRefs = /* @__PURE__ */ new WeakSet();
|
|
85
|
+
seq = 0;
|
|
86
|
+
/** False until this seat has seen the room's content once (the join-time check runs then). */
|
|
87
|
+
joined = false;
|
|
88
|
+
/** The base is being reloaded: entries wait in the log until it is shown. */
|
|
89
|
+
reloadingBase = false;
|
|
59
90
|
constructor(options) {
|
|
60
91
|
this.options = options;
|
|
61
92
|
}
|
|
@@ -86,12 +117,8 @@ var WorkbookCollabSession = class {
|
|
|
86
117
|
const yArray = this.doc.getArray(MUTATIONS_ARRAY_KEY);
|
|
87
118
|
this.yArrayObserver = (event) => {
|
|
88
119
|
if (event.transaction.local) return;
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
for (const op of change.insert) {
|
|
92
|
-
this.applyRemoteMutation(op);
|
|
93
|
-
}
|
|
94
|
-
}
|
|
120
|
+
if (!event.changes.delta.some((change) => Array.isArray(change.insert) && change.insert.length > 0)) return;
|
|
121
|
+
this.drain();
|
|
95
122
|
};
|
|
96
123
|
yArray.observe(this.yArrayObserver);
|
|
97
124
|
if (this.options.onAwarenessChange) {
|
|
@@ -106,6 +133,7 @@ var WorkbookCollabSession = class {
|
|
|
106
133
|
);
|
|
107
134
|
await this.provider.connect();
|
|
108
135
|
await this.provider.ready();
|
|
136
|
+
this.drain();
|
|
109
137
|
if (this.disposed || !this.doc) return;
|
|
110
138
|
const control = this.doc.getMap(CONTROL_MAP_KEY);
|
|
111
139
|
const seen = control.get(REPLACED_KEY)?.nonce ?? null;
|
|
@@ -148,28 +176,44 @@ var WorkbookCollabSession = class {
|
|
|
148
176
|
this.doc = null;
|
|
149
177
|
}
|
|
150
178
|
}
|
|
151
|
-
/**
|
|
152
|
-
* How many mutations the shared log holds right now. Read it BEFORE
|
|
153
|
-
* `workbook.save()`: that many entries are guaranteed to be inside the
|
|
154
|
-
* snapshot that save produces.
|
|
155
|
-
*/
|
|
179
|
+
/** How many mutations the shared log holds right now. */
|
|
156
180
|
logLength() {
|
|
157
181
|
return this.doc?.getArray(MUTATIONS_ARRAY_KEY).length ?? 0;
|
|
158
182
|
}
|
|
159
183
|
/**
|
|
160
|
-
*
|
|
161
|
-
*
|
|
162
|
-
*
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
184
|
+
* The room entries this seat's content holds RIGHT NOW. Read it in the same synchronous step as the
|
|
185
|
+
* content you are about to save, and save it with that content (`stampCovered`); after the save lands,
|
|
186
|
+
* pass it to `checkpoint`.
|
|
187
|
+
*/
|
|
188
|
+
coveredNow() {
|
|
189
|
+
if (!this.doc) return [];
|
|
190
|
+
const covered = this.options.base?.covered();
|
|
191
|
+
const out = [];
|
|
192
|
+
for (const op of this.doc.getArray(MUTATIONS_ARRAY_KEY).toArray()) {
|
|
193
|
+
if (op.eid && (this.applied.has(op.eid) || covered?.has(op.eid))) out.push(op.eid);
|
|
194
|
+
}
|
|
195
|
+
return out;
|
|
196
|
+
}
|
|
197
|
+
/**
|
|
198
|
+
* The snapshot `snapshotId` was SAVED holding `covered` (from `coveredNow`): those entries leave the
|
|
199
|
+
* shared log, and the room records the snapshot as its newest checkpoint. Removal is by entry id, never
|
|
200
|
+
* by position — an entry that arrived while the save was in flight is not in the snapshot and stays.
|
|
201
|
+
* Only the elected saver calls this; peers receive it as a delete (never replayed).
|
|
167
202
|
*/
|
|
168
|
-
|
|
169
|
-
if (!this.doc
|
|
203
|
+
checkpoint(snapshotId, covered) {
|
|
204
|
+
if (!this.doc) return;
|
|
170
205
|
const yArray = this.doc.getArray(MUTATIONS_ARRAY_KEY);
|
|
171
|
-
const
|
|
172
|
-
|
|
206
|
+
const control = this.doc.getMap(CONTROL_MAP_KEY);
|
|
207
|
+
const drop = new Set(covered);
|
|
208
|
+
const signal = { snapshotId, by: this.options.clientId };
|
|
209
|
+
this.doc.transact(() => {
|
|
210
|
+
const entries = yArray.toArray();
|
|
211
|
+
for (let i = entries.length - 1; i >= 0; i -= 1) {
|
|
212
|
+
const eid = entries[i]?.eid;
|
|
213
|
+
if (eid && drop.has(eid)) yArray.delete(i, 1);
|
|
214
|
+
}
|
|
215
|
+
control.set(CHECKPOINT_KEY, signal);
|
|
216
|
+
});
|
|
173
217
|
}
|
|
174
218
|
/**
|
|
175
219
|
* This client replaced the whole content and SAVED it as `snapshotId`.
|
|
@@ -189,6 +233,7 @@ var WorkbookCollabSession = class {
|
|
|
189
233
|
this.doc.transact(() => {
|
|
190
234
|
if (yArray.length > 0) yArray.delete(0, yArray.length);
|
|
191
235
|
control.set(REPLACED_KEY, signal);
|
|
236
|
+
control.set(CHECKPOINT_KEY, { snapshotId, by: this.options.clientId });
|
|
192
237
|
});
|
|
193
238
|
}
|
|
194
239
|
/**
|
|
@@ -250,7 +295,49 @@ var WorkbookCollabSession = class {
|
|
|
250
295
|
return;
|
|
251
296
|
}
|
|
252
297
|
const yArray = this.doc.getArray(MUTATIONS_ARRAY_KEY);
|
|
253
|
-
|
|
298
|
+
const eid = `${this.options.clientId}:${++this.seq}`;
|
|
299
|
+
this.applied.add(eid);
|
|
300
|
+
this.joined = true;
|
|
301
|
+
yArray.push([{ id: info.id, type: info.type, params: safeParams, uid: this.options.uid, eid }]);
|
|
302
|
+
}
|
|
303
|
+
/**
|
|
304
|
+
* Apply every log entry this seat's content does not hold yet, in the log's order. The first time the
|
|
305
|
+
* room shows content, the join-time check runs: a seat that booted from a snapshot OLDER than the
|
|
306
|
+
* room's newest checkpoint reloads first (the entries that checkpoint trimmed exist only in it).
|
|
307
|
+
*/
|
|
308
|
+
drain() {
|
|
309
|
+
if (!this.doc || this.disposed || this.reloadingBase) return;
|
|
310
|
+
const yArray = this.doc.getArray(MUTATIONS_ARRAY_KEY);
|
|
311
|
+
const entries = yArray.toArray();
|
|
312
|
+
const base = this.options.base;
|
|
313
|
+
if (!this.joined) {
|
|
314
|
+
const control = this.doc.getMap(CONTROL_MAP_KEY);
|
|
315
|
+
const checkpoint = control.get(CHECKPOINT_KEY);
|
|
316
|
+
if (entries.length === 0 && !checkpoint) return;
|
|
317
|
+
this.joined = true;
|
|
318
|
+
if (base && checkpoint?.snapshotId && checkpoint.snapshotId !== base.snapshotId()) {
|
|
319
|
+
this.reloadingBase = true;
|
|
320
|
+
void base.reload().catch((error) => {
|
|
321
|
+
console.warn("[collab] could not load the newest saved version on joining", error);
|
|
322
|
+
this.options.onApplyFailed?.("collab.join", error);
|
|
323
|
+
}).finally(() => {
|
|
324
|
+
this.reloadingBase = false;
|
|
325
|
+
this.drain();
|
|
326
|
+
});
|
|
327
|
+
return;
|
|
328
|
+
}
|
|
329
|
+
}
|
|
330
|
+
const covered = base?.covered();
|
|
331
|
+
for (const op of entries) {
|
|
332
|
+
if (op.eid) {
|
|
333
|
+
if (this.applied.has(op.eid) || covered?.has(op.eid)) continue;
|
|
334
|
+
this.applied.add(op.eid);
|
|
335
|
+
} else {
|
|
336
|
+
if (this.appliedRefs.has(op)) continue;
|
|
337
|
+
this.appliedRefs.add(op);
|
|
338
|
+
}
|
|
339
|
+
this.applyRemoteMutation(op);
|
|
340
|
+
}
|
|
254
341
|
}
|
|
255
342
|
applyRemoteMutation(op) {
|
|
256
343
|
const ownUnit = this.options.unitId?.() ?? null;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/univer/collab/index.ts","../src/univer/collab/WorkbookCollabSession.ts"],"sourcesContent":["/**\n * The collab session shared by `/sheets` and `/docs` (was matrx-frontend `features/workbooks/collab`): the\n * Univer <-> Yjs bridge. It owns the Yjs import, so it is loaded on demand (`import()` when a workbook\n * or document goes live). The snapshot-insert subscription hook is its own entry,\n * `@ai-matrx/office/univer/realtime`, so a static import of the hook never carries Yjs into the editor\n * chunk. A transitional subpath, like `./univer`: it goes internal when the editors move.\n */\nexport * from \"./WorkbookCollabSession\";\n","/**\n * WorkbookCollabSession — the Univer ↔ Yjs bridge.\n *\n * Subscribes to Univer's public `commandService.onMutationExecutedForCollab`\n * hook for local mutations and pushes them onto a `Y.Array<MutationOp>` shared\n * via `SupabaseYjsProvider`. Inbound Yjs updates produce `IMutationInfo` ops\n * that are applied through `commandService.syncExecuteCommand` with the\n * `fromCollab` execution option flagged so the outbound listener short-\n * circuits and we don't echo our own apply.\n *\n * See `FEATURE.md` in this directory for the architecture, the \"do NOT use\n * the Pro preset\" verdict, and the host-election rule. This class is the\n * runtime side of that plan.\n *\n * Lifecycle:\n * - constructor: wire references, no side effects\n * - start(): create Y.Doc + Awareness, instantiate provider, subscribe to\n * command stream, subscribe to Yjs Array observer\n * - stop(): detach all listeners, dispose provider\n *\n * The session is one-shot per workbook open. Reload = stop() + new instance.\n */\n\"use client\";\n\nimport * as Y from \"yjs\";\nimport { Awareness } from \"y-protocols/awareness\";\n\nimport { electCollabHost, remoteOriginOf, REMOTE_PARAM_TAG } from \"@ai-matrx/data/realtime/collab\";\n\n/**\n * Structural transport contract. `SupabaseYjsProvider` satisfies it in\n * production; the verification harness injects an in-memory loopback\n * transport through the same seam. Keeping this structural (not the concrete\n * class) is what makes the session testable without network.\n */\nexport type CollabProviderLike = {\n connect(): Promise<void>;\n disconnect(): void;\n ready(): Promise<void>;\n /**\n * True when this is the only holder of its room in this tab allowed to act as\n * host (autosave). Same-tab holders share one client id and one uid, so\n * awareness cannot tell them apart. Absent = a lone holder = leader.\n */\n isTabLeader?(): boolean;\n};\n\n// Univer types are loose at the public hook boundary; we narrow with a\n// structural interface so we don't have to import the full Univer surface.\ntype MutationParams = Record<string, unknown> | unknown[] | null;\n\nexport type CollabMutationInfo = {\n id: string;\n type: number; // CommandType.MUTATION = 2 in Univer's enum\n params: MutationParams;\n /** Who made it (the person's uid), so a peer can tell its own other tab's edit from a stranger's. */\n uid?: string;\n};\n\ntype ExecuteOptions = {\n /** Per-Univer convention: when true, the command runs locally only and is\n * NOT broadcast to other plugins. We set this on inbound-apply so the\n * subsequent onMutationExecutedForCollab does NOT re-fire on our peer. */\n onlyLocal?: boolean;\n fromCollab?: boolean;\n};\n\nexport type CommandServiceLike = {\n onMutationExecutedForCollab(\n listener: (info: CollabMutationInfo, options?: ExecuteOptions) => void,\n ): {\n dispose: () => void;\n };\n syncExecuteCommand(\n id: string,\n params: MutationParams,\n options?: ExecuteOptions,\n ): unknown;\n};\n\nexport type WorkbookCollabSessionOptions = {\n workbookId: string;\n uid: string;\n clientId: string;\n commandService: CommandServiceLike;\n /** Factory so this file does not statically depend on the provider. */\n makeProvider: (args: {\n workbookId: string;\n clientId: string;\n doc: Y.Doc;\n awareness: Awareness;\n /** Wire to the provider so a host handover re-runs the election. */\n onLeaderChange: () => void;\n }) => CollabProviderLike;\n /** Called when the awareness set changes (peers join / leave / move cursor). */\n onAwarenessChange?: (awareness: Awareness) => void;\n /**\n * A peer replaced the whole content (history restore, Google update): the\n * newest saved snapshot is the content now. Reload it in place; never\n * re-announce. See `announceReplaced`.\n */\n onReplaced?: (snapshotId: string) => void;\n /**\n * TRUE when the room is bound to a Univer DOCUMENT unit (the Docs editor): there the `doc.mutation.*`\n * stream IS the content, so it must travel. Leave unset for a workbook, where `doc.mutation.*` is the\n * in-cell editor's scratch document and never travels (see `isCellEditorScratch`).\n */\n forwardDocumentMutations?: boolean;\n /**\n * The Univer unit id this seat mounted. Each seat can mount its own unit, so a peer's mutation\n * (addressed to the SENDER's unit) is re-addressed to this one before it is applied.\n */\n unitId?: () => string | null;\n /** A peer's mutation could not be applied here: the seat says so and re-syncs; never only a console line. */\n onApplyFailed?: (mutationId: string, error: unknown) => void;\n};\n\n/** What `announceReplaced` writes into the room's control map. */\ntype ReplacedSignal = { snapshotId: string; by: string; nonce: string };\n\nconst MUTATIONS_ARRAY_KEY = \"mutations\";\nconst CONTROL_MAP_KEY = \"control\";\nconst REPLACED_KEY = \"replaced\";\n\nexport class WorkbookCollabSession {\n private readonly options: WorkbookCollabSessionOptions;\n private doc: Y.Doc | null = null;\n private awareness: Awareness | null = null;\n private provider: CollabProviderLike | null = null;\n private commandDisposer: { dispose: () => void } | null = null;\n private yArrayObserver:\n ((event: Y.YArrayEvent<CollabMutationInfo>) => void) | null = null;\n private awarenessObserver: (() => void) | null = null;\n private controlObserver: ((event: Y.YMapEvent<unknown>) => void) | null = null;\n /** >0 while this client swaps its own content: its mutations are not edits. */\n private muted = 0;\n private started = false;\n private disposed = false;\n\n constructor(options: WorkbookCollabSessionOptions) {\n this.options = options;\n }\n\n async start(): Promise<void> {\n if (this.started || this.disposed) return;\n this.started = true;\n\n this.doc = new Y.Doc();\n this.awareness = new Awareness(this.doc);\n\n // Seed local awareness with the user identity. Cursor (sheetId/row/col)\n // is set later via setCursor().\n this.awareness.setLocalState({\n uid: this.options.uid,\n clientId: this.options.clientId,\n name: this.options.uid.slice(0, 8),\n color: pickColor(this.options.uid),\n sheetId: null,\n row: null,\n col: null,\n ts: Date.now(),\n });\n\n this.provider = this.options.makeProvider({\n workbookId: this.options.workbookId,\n clientId: this.options.clientId,\n doc: this.doc,\n awareness: this.awareness,\n onLeaderChange: () => {\n if (this.awareness) this.options.onAwarenessChange?.(this.awareness);\n },\n });\n\n // Subscribe to inbound Yjs array changes BEFORE connecting the provider,\n // so the initial-state replay (if any) hits our observer.\n const yArray = this.doc.getArray<CollabMutationInfo>(MUTATIONS_ARRAY_KEY);\n this.yArrayObserver = (event) => {\n // Local transactions are OUR OWN pushes from handleLocalMutation —\n // Univer already executed those mutations. Re-applying them here would\n // double-apply every local edit on the originator. Only act on\n // transactions that arrived via Y.applyUpdate (origin 'remote').\n if (event.transaction.local) return;\n for (const change of event.changes.delta) {\n if (!change.insert || !Array.isArray(change.insert)) continue;\n for (const op of change.insert as CollabMutationInfo[]) {\n this.applyRemoteMutation(op);\n }\n }\n };\n yArray.observe(this.yArrayObserver as Parameters<typeof yArray.observe>[0]);\n\n // Awareness change passthrough.\n if (this.options.onAwarenessChange) {\n const cb = this.options.onAwarenessChange;\n this.awarenessObserver = () => {\n if (this.awareness) cb(this.awareness);\n };\n this.awareness.on(\"change\", this.awarenessObserver);\n }\n\n // Subscribe to Univer's collab-grain mutation stream.\n this.commandDisposer =\n this.options.commandService.onMutationExecutedForCollab((info) =>\n this.handleLocalMutation(info),\n );\n\n await this.provider.connect();\n await this.provider.ready();\n\n // Whole-content replacement from a peer. Bound AFTER the initial sync: a\n // joiner already loaded the newest snapshot, so the signal it finds in\n // the room's state is history, not news (the editor also skips a\n // snapshot it already shows).\n if (this.disposed || !this.doc) return;\n const control = this.doc.getMap<unknown>(CONTROL_MAP_KEY);\n const seen = (control.get(REPLACED_KEY) as ReplacedSignal | undefined)?.nonce ?? null;\n this.controlObserver = (event) => {\n if (event.transaction.local || !event.keysChanged.has(REPLACED_KEY)) return;\n const signal = control.get(REPLACED_KEY) as ReplacedSignal | undefined;\n if (!signal?.snapshotId || signal.nonce === seen) return;\n this.options.onReplaced?.(signal.snapshotId);\n };\n control.observe(this.controlObserver);\n }\n\n stop(): void {\n if (this.disposed) return;\n this.disposed = true;\n\n this.commandDisposer?.dispose();\n this.commandDisposer = null;\n\n if (this.doc && this.yArrayObserver) {\n const yArray = this.doc.getArray<CollabMutationInfo>(MUTATIONS_ARRAY_KEY);\n yArray.unobserve(\n this.yArrayObserver as Parameters<typeof yArray.unobserve>[0],\n );\n this.yArrayObserver = null;\n }\n\n if (this.doc && this.controlObserver) {\n this.doc.getMap<unknown>(CONTROL_MAP_KEY).unobserve(this.controlObserver);\n this.controlObserver = null;\n }\n\n if (this.awareness && this.awarenessObserver) {\n this.awareness.off(\"change\", this.awarenessObserver);\n this.awarenessObserver = null;\n }\n\n this.provider?.disconnect();\n this.provider = null;\n\n if (this.awareness) {\n this.awareness.destroy();\n this.awareness = null;\n }\n\n if (this.doc) {\n this.doc.destroy();\n this.doc = null;\n }\n }\n\n /**\n * How many mutations the shared log holds right now. Read it BEFORE\n * `workbook.save()`: that many entries are guaranteed to be inside the\n * snapshot that save produces.\n */\n logLength(): number {\n return this.doc?.getArray<CollabMutationInfo>(MUTATIONS_ARRAY_KEY).length ?? 0;\n }\n\n /**\n * Drop the first `upTo` mutations from the shared log once a snapshot that\n * contains them has been SAVED. Without this a joiner loads the saved\n * workbook (which already has every mutation baked in) and then catches up\n * the whole log on top of it, replaying edits into a workbook that already\n * holds them — Univer refuses with \"Trying to overwrite value at key\"\n * (feedback 88184e53). Only the host calls this; peers receive it as a\n * delete, which the inbound observer ignores (it acts on inserts only).\n */\n compactLog(upTo: number): void {\n if (!this.doc || upTo <= 0) return;\n const yArray = this.doc.getArray<CollabMutationInfo>(MUTATIONS_ARRAY_KEY);\n const n = Math.min(upTo, yArray.length);\n if (n > 0) this.doc.transact(() => yArray.delete(0, n));\n }\n\n /**\n * This client replaced the whole content and SAVED it as `snapshotId`.\n * One transaction empties the shared mutation log (every entry targets the\n * content that is gone — a joiner must never replay them onto the new\n * snapshot) and tells every peer to reload the newest snapshot.\n */\n announceReplaced(snapshotId: string): void {\n if (!this.doc) return;\n const yArray = this.doc.getArray<CollabMutationInfo>(MUTATIONS_ARRAY_KEY);\n const control = this.doc.getMap<unknown>(CONTROL_MAP_KEY);\n const signal: ReplacedSignal = {\n snapshotId,\n by: this.options.clientId,\n nonce: `${this.options.clientId}:${Date.now()}:${Math.random().toString(36).slice(2, 8)}`,\n };\n this.doc.transact(() => {\n if (yArray.length > 0) yArray.delete(0, yArray.length);\n control.set(REPLACED_KEY, signal);\n });\n }\n\n /**\n * Run `swap` (this client tearing its content down and mounting the new\n * one) without broadcasting what Univer emits while it does: those are not\n * edits, and peers reload the same snapshot themselves.\n */\n muteWhile<T>(swap: () => T): T {\n this.muted += 1;\n try {\n return swap();\n } finally {\n this.muted -= 1;\n }\n }\n\n /**\n * Update the local awareness cursor. Call this from Univer's selection\n * listener (`worksheet.onSelectionChange(...)`). Throttle at the call site\n * (~50ms is plenty); the provider broadcasts on its own debounced cycle.\n */\n setCursor(input: {\n sheetId: string | null;\n row: number | null;\n col: number | null;\n }): void {\n if (!this.awareness) return;\n const current = this.awareness.getLocalState() ?? {};\n this.awareness.setLocalState({\n ...current,\n sheetId: input.sheetId,\n row: input.row,\n col: input.col,\n ts: Date.now(),\n });\n }\n\n /**\n * Returns the deterministic host: the connected peer with the lowest uid\n * (lexicographic). Host is the only client that writes canonical snapshots.\n * No election protocol; recompute whenever awareness changes.\n */\n electHost(opts: { tabTieBreak?: boolean } = {}): { isHost: boolean; hostUid: string | null } {\n if (!this.awareness) return { isHost: false, hostUid: null };\n const states = Array.from(this.awareness.getStates().values()) as Array<\n Record<string, unknown>\n >;\n // Lowest uid wins ACROSS tabs; inside this tab only the room's tab leader\n // may be host, because every same-tab holder carries the same uid.\n const leader = this.provider?.isTabLeader?.() ?? true;\n return electCollabHost(states, this.options.uid, this.options.clientId, leader, opts.tabTieBreak ?? false);\n }\n\n // ─── internals ────────────────────────────────────────────────────────\n\n private handleLocalMutation(info: CollabMutationInfo): void {\n if (this.muted > 0) return;\n if (!this.options.forwardDocumentMutations && isCellEditorScratch(info)) return;\n // Inbound-applied mutations re-fire this listener because Univer's\n // syncExecuteCommand legitimately processes them through the full\n // pipeline. Skip by sniffing the sentinel we stamped on apply.\n if (\n info.params &&\n typeof info.params === \"object\" &&\n !Array.isArray(info.params) &&\n remoteOriginOf(info.params) !== null\n ) {\n return;\n }\n if (!this.doc) return;\n\n // Normalize params through a JSON round-trip BEFORE pushing into Yjs.\n // Yjs (and the Broadcast transport) only carry JSON-encodable values;\n // Univer types its mutation params as \"serializable\" but JS objects can\n // smuggle Date / Map / class instances through that promise. The\n // round-trip makes the failure mode deterministic: a non-encodable\n // mutation is skipped with a warning instead of corrupting the shared\n // doc or desyncing peers mid-session. What we push here is byte-for-byte\n // what remote peers will apply, so local-apply == remote-apply.\n let safeParams: MutationParams;\n try {\n safeParams =\n info.params === undefined || info.params === null\n ? null\n : (JSON.parse(JSON.stringify(info.params)) as MutationParams);\n } catch (err) {\n console.warn(\n `[collab] skipping non-serializable mutation \"${info.id}\" — peers will not receive it`,\n err,\n );\n return;\n }\n\n const yArray = this.doc.getArray<CollabMutationInfo>(MUTATIONS_ARRAY_KEY);\n yArray.push([{ id: info.id, type: info.type, params: safeParams, uid: this.options.uid }]);\n }\n\n private applyRemoteMutation(op: CollabMutationInfo): void {\n // Wrap params with the sentinel so handleLocalMutation knows not to\n // echo the apply back into Yjs.\n const ownUnit = this.options.unitId?.() ?? null;\n const taggedParams: MutationParams =\n op.params && typeof op.params === \"object\" && !Array.isArray(op.params)\n ? {\n ...(op.params as Record<string, unknown>),\n ...(ownUnit && typeof (op.params as { unitId?: unknown }).unitId === \"string\" ? { unitId: ownUnit } : {}),\n [REMOTE_PARAM_TAG]: op.uid ?? true,\n }\n : op.params;\n\n try {\n this.options.commandService.syncExecuteCommand(op.id, taggedParams, {\n onlyLocal: true,\n fromCollab: true,\n });\n } catch (err) {\n // One unappliable op (already baked into the loaded snapshot, or a\n // stale target) must not throw into the realtime channel handler and\n // abort the rest of the catch-up. Said, never swallowed.\n console.warn(\n `[collab] could not apply remote mutation \"${op.id}\" — skipped`,\n err,\n );\n this.options.onApplyFailed?.(op.id, err);\n }\n }\n}\n\n// ─── helpers ────────────────────────────────────────────────────────────\n\n/**\n * A workbook holds no Univer DOCUMENT units of its own: the `doc.mutation.*` stream a sheet emits is\n * the in-cell editor's scratch document (typing into a cell). The finished text reaches the sheet as\n * `sheet.mutation.set-range-values`, which does travel. Sending the scratch edits made a joiner replay\n * them against an editor unit it does not have (\"Trying to overwrite value at key\").\n */\nexport function isCellEditorScratch(info: Pick<CollabMutationInfo, \"id\">): boolean {\n return typeof info.id === \"string\" && info.id.startsWith(\"doc.mutation.\");\n}\n\nconst CURSOR_PALETTE = [\n \"#3b82f6\", // blue\n \"#10b981\", // emerald\n \"#f59e0b\", // amber\n \"#ef4444\", // red\n \"#8b5cf6\", // violet\n \"#06b6d4\", // cyan\n \"#ec4899\", // pink\n \"#84cc16\", // lime\n];\n\nfunction pickColor(uid: string): string {\n // Deterministic FNV-1a-ish hash so the same user is always the same color\n // across sessions and across other users' screens.\n let h = 2166136261;\n for (let i = 0; i < uid.length; i++) {\n h ^= uid.charCodeAt(i);\n h = Math.imul(h, 16777619);\n }\n return CURSOR_PALETTE[Math.abs(h) % CURSOR_PALETTE.length] ?? \"#ec4899\";\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACwBA,QAAmB;AACnB,uBAA0B;AAE1B,oBAAkE;AA6FlE,IAAM,sBAAsB;AAC5B,IAAM,kBAAkB;AACxB,IAAM,eAAe;AAEd,IAAM,wBAAN,MAA4B;AAAA,EAChB;AAAA,EACT,MAAoB;AAAA,EACpB,YAA8B;AAAA,EAC9B,WAAsC;AAAA,EACtC,kBAAkD;AAAA,EAClD,iBACwD;AAAA,EACxD,oBAAyC;AAAA,EACzC,kBAAkE;AAAA;AAAA,EAElE,QAAQ;AAAA,EACR,UAAU;AAAA,EACV,WAAW;AAAA,EAEnB,YAAY,SAAuC;AACjD,SAAK,UAAU;AAAA,EACjB;AAAA,EAEA,MAAM,QAAuB;AAC3B,QAAI,KAAK,WAAW,KAAK,SAAU;AACnC,SAAK,UAAU;AAEf,SAAK,MAAM,IAAM,MAAI;AACrB,SAAK,YAAY,IAAI,2BAAU,KAAK,GAAG;AAIvC,SAAK,UAAU,cAAc;AAAA,MAC3B,KAAK,KAAK,QAAQ;AAAA,MAClB,UAAU,KAAK,QAAQ;AAAA,MACvB,MAAM,KAAK,QAAQ,IAAI,MAAM,GAAG,CAAC;AAAA,MACjC,OAAO,UAAU,KAAK,QAAQ,GAAG;AAAA,MACjC,SAAS;AAAA,MACT,KAAK;AAAA,MACL,KAAK;AAAA,MACL,IAAI,KAAK,IA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G;AAET,QAAI;AACF,WAAK,QAAQ,eAAe,mBAAmB,GAAG,IAAI,cAAc;AAAA,QAClE,WAAW;AAAA,QACX,YAAY;AAAA,MACd,CAAC;AAAA,IACH,SAAS,KAAK;AAIZ,cAAQ;AAAA,QACN,6CAA6C,GAAG,EAAE;AAAA,QAClD;AAAA,MACF;AACA,WAAK,QAAQ,gBAAgB,GAAG,IAAI,GAAG;AAAA,IACzC;AAAA,EACF;AACF;AAUO,SAAS,oBAAoB,MAA+C;AACjF,SAAO,OAAO,KAAK,OAAO,YAAY,KAAK,GAAG,WAAW,eAAe;AAC1E;AAEA,IAAM,iBAAiB;AAAA,EACrB;AAAA;AAAA,EACA;AAAA;AAAA,EACA;AAAA;AAAA,EACA;AAAA;AAAA,EACA;AAAA;AAAA,EACA;AAAA;AAAA,EACA;AAAA;AAAA,EACA;AAAA;AACF;AAEA,SAAS,UAAU,KAAqB;AAGtC,MAAI,IAAI;AACR,WAAS,IAAI,GAAG,IAAI,IAAI,QAAQ,KAAK;AACnC,SAAK,IAAI,WAAW,CAAC;AACrB,QAAI,KAAK,KAAK,GAAG,QAAQ;AAAA,EAC3B;AACA,SAAO,eAAe,KAAK,IAAI,CAAC,IAAI,eAAe,MAAM,KAAK;AAChE;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../src/univer/collab/index.ts","../src/univer/collab/WorkbookCollabSession.ts","../src/univer/collab/covered.ts"],"sourcesContent":["/**\n * The collab session shared by `/sheets` and `/docs` (was matrx-frontend `features/workbooks/collab`): the\n * Univer <-> Yjs bridge. It owns the Yjs import, so it is loaded on demand (`import()` when a workbook\n * or document goes live). The snapshot-insert subscription hook is its own entry,\n * `@ai-matrx/office/univer/realtime`, so a static import of the hook never carries Yjs into the editor\n * chunk. A transitional subpath, like `./univer`: it goes internal when the editors move.\n */\nexport * from \"./WorkbookCollabSession\";\n","/**\n * WorkbookCollabSession — the Univer ↔ Yjs bridge.\n *\n * Subscribes to Univer's public `commandService.onMutationExecutedForCollab`\n * hook for local mutations and pushes them onto a `Y.Array<MutationOp>` shared\n * via `SupabaseYjsProvider`. Inbound Yjs updates produce `IMutationInfo` ops\n * that are applied through `commandService.syncExecuteCommand` with the\n * `fromCollab` execution option flagged so the outbound listener short-\n * circuits and we don't echo our own apply.\n *\n * See `FEATURE.md` in this directory for the architecture, the \"do NOT use\n * the Pro preset\" verdict, and the host-election rule. This class is the\n * runtime side of that plan.\n *\n * Lifecycle:\n * - constructor: wire references, no side effects\n * - start(): create Y.Doc + Awareness, instantiate provider, subscribe to\n * command stream, subscribe to Yjs Array observer\n * - stop(): detach all listeners, dispose provider\n *\n * The session is one-shot per workbook open. Reload = stop() + new instance.\n */\n\"use client\";\n\nimport * as Y from \"yjs\";\nimport { Awareness } from \"y-protocols/awareness\";\n\nimport { electCollabHost, remoteOriginOf, REMOTE_PARAM_TAG } from \"@ai-matrx/data/realtime/collab\";\n\nexport { COLLAB_COVERED_KEY, stampCovered, takeCovered } from \"./covered\";\n\n/**\n * Structural transport contract. `SupabaseYjsProvider` satisfies it in\n * production; the verification harness injects an in-memory loopback\n * transport through the same seam. Keeping this structural (not the concrete\n * class) is what makes the session testable without network.\n */\nexport type CollabProviderLike = {\n connect(): Promise<void>;\n disconnect(): void;\n ready(): Promise<void>;\n /**\n * True when this is the only holder of its room in this tab allowed to act as\n * host (autosave). Same-tab holders share one client id and one uid, so\n * awareness cannot tell them apart. Absent = a lone holder = leader.\n */\n isTabLeader?(): boolean;\n};\n\n// Univer types are loose at the public hook boundary; we narrow with a\n// structural interface so we don't have to import the full Univer surface.\ntype MutationParams = Record<string, unknown> | unknown[] | null;\n\nexport type CollabMutationInfo = {\n id: string;\n type: number; // CommandType.MUTATION = 2 in Univer's enum\n params: MutationParams;\n /** Who made it (the person's uid), so a peer can tell its own other tab's edit from a stranger's. */\n uid?: string;\n /**\n * The entry's identity in the room (`<clientId>:<seq>`). A saved snapshot names the entries it holds\n * (`stampCovered`), so a seat that boots from that snapshot never replays them a second time.\n */\n eid?: string;\n};\n\n/**\n * What a seat booted from: the saved snapshot's row id and the room entries that snapshot already holds.\n * The session never replays a covered entry, and a seat that booted from an OLDER snapshot than the\n * room's newest checkpoint first reloads (the entries that checkpoint trimmed are only in that snapshot).\n */\nexport type CollabBase = {\n snapshotId: () => string | null;\n covered: () => ReadonlySet<string>;\n /** Show the newest saved snapshot (and make it the base). */\n reload: () => Promise<void>;\n};\n\ntype ExecuteOptions = {\n /** Per-Univer convention: when true, the command runs locally only and is\n * NOT broadcast to other plugins. We set this on inbound-apply so the\n * subsequent onMutationExecutedForCollab does NOT re-fire on our peer. */\n onlyLocal?: boolean;\n fromCollab?: boolean;\n};\n\nexport type CommandServiceLike = {\n onMutationExecutedForCollab(\n listener: (info: CollabMutationInfo, options?: ExecuteOptions) => void,\n ): {\n dispose: () => void;\n };\n syncExecuteCommand(\n id: string,\n params: MutationParams,\n options?: ExecuteOptions,\n ): unknown;\n};\n\nexport type WorkbookCollabSessionOptions = {\n workbookId: string;\n uid: string;\n clientId: string;\n commandService: CommandServiceLike;\n /** Factory so this file does not statically depend on the provider. */\n makeProvider: (args: {\n workbookId: string;\n clientId: string;\n doc: Y.Doc;\n awareness: Awareness;\n /** Wire to the provider so a host handover re-runs the election. */\n onLeaderChange: () => void;\n }) => CollabProviderLike;\n /** Called when the awareness set changes (peers join / leave / move cursor). */\n onAwarenessChange?: (awareness: Awareness) => void;\n /**\n * A peer replaced the whole content (history restore, Google update): the\n * newest saved snapshot is the content now. Reload it in place; never\n * re-announce. See `announceReplaced`.\n */\n onReplaced?: (snapshotId: string) => void;\n /**\n * TRUE when the room is bound to a Univer DOCUMENT unit (the Docs editor): there the `doc.mutation.*`\n * stream IS the content, so it must travel. Leave unset for a workbook, where `doc.mutation.*` is the\n * in-cell editor's scratch document and never travels (see `isCellEditorScratch`).\n */\n forwardDocumentMutations?: boolean;\n /**\n * The Univer unit id this seat mounted. Each seat can mount its own unit, so a peer's mutation\n * (addressed to the SENDER's unit) is re-addressed to this one before it is applied.\n */\n unitId?: () => string | null;\n /** A peer's mutation could not be applied here: the seat says so and re-syncs; never only a console line. */\n onApplyFailed?: (mutationId: string, error: unknown) => void;\n /**\n * The saved snapshot this seat booted from. Without it a reloading seat replays every entry still in\n * the room's log on top of a snapshot that already holds them: the text shows twice, and the next save\n * stores it twice (2026-10-16).\n */\n base?: CollabBase;\n};\n\n/** What `checkpoint` writes into the room's control map: the newest saved snapshot whose entries left the log. */\ntype CheckpointSignal = { snapshotId: string; by: string };\n\n/** What `announceReplaced` writes into the room's control map. */\ntype ReplacedSignal = { snapshotId: string; by: string; nonce: string };\n\nconst MUTATIONS_ARRAY_KEY = \"mutations\";\nconst CONTROL_MAP_KEY = \"control\";\nconst REPLACED_KEY = \"replaced\";\nconst CHECKPOINT_KEY = \"checkpoint\";\n\nexport class WorkbookCollabSession {\n private readonly options: WorkbookCollabSessionOptions;\n private doc: Y.Doc | null = null;\n private awareness: Awareness | null = null;\n private provider: CollabProviderLike | null = null;\n private commandDisposer: { dispose: () => void } | null = null;\n private yArrayObserver:\n ((event: Y.YArrayEvent<CollabMutationInfo>) => void) | null = null;\n private awarenessObserver: (() => void) | null = null;\n private controlObserver: ((event: Y.YMapEvent<unknown>) => void) | null = null;\n /** >0 while this client swaps its own content: its mutations are not edits. */\n private muted = 0;\n private started = false;\n private disposed = false;\n /** Room entries this seat holds in its content: applied from a peer, or made here. */\n private readonly applied = new Set<string>();\n /** Entries without an id (a peer on an older build) are applied once, by identity. */\n private readonly appliedRefs = new WeakSet<object>();\n private seq = 0;\n /** False until this seat has seen the room's content once (the join-time check runs then). */\n private joined = false;\n /** The base is being reloaded: entries wait in the log until it is shown. */\n private reloadingBase = false;\n\n constructor(options: WorkbookCollabSessionOptions) {\n this.options = options;\n }\n\n async start(): Promise<void> {\n if (this.started || this.disposed) return;\n this.started = true;\n\n this.doc = new Y.Doc();\n this.awareness = new Awareness(this.doc);\n\n // Seed local awareness with the user identity. Cursor (sheetId/row/col)\n // is set later via setCursor().\n this.awareness.setLocalState({\n uid: this.options.uid,\n clientId: this.options.clientId,\n name: this.options.uid.slice(0, 8),\n color: pickColor(this.options.uid),\n sheetId: null,\n row: null,\n col: null,\n ts: Date.now(),\n });\n\n this.provider = this.options.makeProvider({\n workbookId: this.options.workbookId,\n clientId: this.options.clientId,\n doc: this.doc,\n awareness: this.awareness,\n onLeaderChange: () => {\n if (this.awareness) this.options.onAwarenessChange?.(this.awareness);\n },\n });\n\n // Subscribe to inbound Yjs array changes BEFORE connecting the provider,\n // so the initial-state replay (if any) hits our observer.\n const yArray = this.doc.getArray<CollabMutationInfo>(MUTATIONS_ARRAY_KEY);\n this.yArrayObserver = (event) => {\n // Local transactions are OUR OWN pushes from handleLocalMutation —\n // Univer already executed those mutations. Re-applying them here would\n // double-apply every local edit on the originator. Only act on\n // transactions that arrived via Y.applyUpdate (origin 'remote').\n if (event.transaction.local) return;\n if (!event.changes.delta.some((change) => Array.isArray(change.insert) && change.insert.length > 0)) return;\n this.drain();\n };\n yArray.observe(this.yArrayObserver as Parameters<typeof yArray.observe>[0]);\n\n // Awareness change passthrough.\n if (this.options.onAwarenessChange) {\n const cb = this.options.onAwarenessChange;\n this.awarenessObserver = () => {\n if (this.awareness) cb(this.awareness);\n };\n this.awareness.on(\"change\", this.awarenessObserver);\n }\n\n // Subscribe to Univer's collab-grain mutation stream.\n this.commandDisposer =\n this.options.commandService.onMutationExecutedForCollab((info) =>\n this.handleLocalMutation(info),\n );\n\n await this.provider.connect();\n await this.provider.ready();\n this.drain();\n\n // Whole-content replacement from a peer. Bound AFTER the initial sync: a\n // joiner already loaded the newest snapshot, so the signal it finds in\n // the room's state is history, not news (the editor also skips a\n // snapshot it already shows).\n if (this.disposed || !this.doc) return;\n const control = this.doc.getMap<unknown>(CONTROL_MAP_KEY);\n const seen = (control.get(REPLACED_KEY) as ReplacedSignal | undefined)?.nonce ?? null;\n this.controlObserver = (event) => {\n if (event.transaction.local || !event.keysChanged.has(REPLACED_KEY)) return;\n const signal = control.get(REPLACED_KEY) as ReplacedSignal | undefined;\n if (!signal?.snapshotId || signal.nonce === seen) return;\n this.options.onReplaced?.(signal.snapshotId);\n };\n control.observe(this.controlObserver);\n }\n\n stop(): void {\n if (this.disposed) return;\n this.disposed = true;\n\n this.commandDisposer?.dispose();\n this.commandDisposer = null;\n\n if (this.doc && this.yArrayObserver) {\n const yArray = this.doc.getArray<CollabMutationInfo>(MUTATIONS_ARRAY_KEY);\n yArray.unobserve(\n this.yArrayObserver as Parameters<typeof yArray.unobserve>[0],\n );\n this.yArrayObserver = null;\n }\n\n if (this.doc && this.controlObserver) {\n this.doc.getMap<unknown>(CONTROL_MAP_KEY).unobserve(this.controlObserver);\n this.controlObserver = null;\n }\n\n if (this.awareness && this.awarenessObserver) {\n this.awareness.off(\"change\", this.awarenessObserver);\n this.awarenessObserver = null;\n }\n\n this.provider?.disconnect();\n this.provider = null;\n\n if (this.awareness) {\n this.awareness.destroy();\n this.awareness = null;\n }\n\n if (this.doc) {\n this.doc.destroy();\n this.doc = null;\n }\n }\n\n /** How many mutations the shared log holds right now. */\n logLength(): number {\n return this.doc?.getArray<CollabMutationInfo>(MUTATIONS_ARRAY_KEY).length ?? 0;\n }\n\n /**\n * The room entries this seat's content holds RIGHT NOW. Read it in the same synchronous step as the\n * content you are about to save, and save it with that content (`stampCovered`); after the save lands,\n * pass it to `checkpoint`.\n */\n coveredNow(): string[] {\n if (!this.doc) return [];\n const covered = this.options.base?.covered();\n const out: string[] = [];\n for (const op of this.doc.getArray<CollabMutationInfo>(MUTATIONS_ARRAY_KEY).toArray()) {\n if (op.eid && (this.applied.has(op.eid) || covered?.has(op.eid))) out.push(op.eid);\n }\n return out;\n }\n\n /**\n * The snapshot `snapshotId` was SAVED holding `covered` (from `coveredNow`): those entries leave the\n * shared log, and the room records the snapshot as its newest checkpoint. Removal is by entry id, never\n * by position — an entry that arrived while the save was in flight is not in the snapshot and stays.\n * Only the elected saver calls this; peers receive it as a delete (never replayed).\n */\n checkpoint(snapshotId: string, covered: readonly string[]): void {\n if (!this.doc) return;\n const yArray = this.doc.getArray<CollabMutationInfo>(MUTATIONS_ARRAY_KEY);\n const control = this.doc.getMap<unknown>(CONTROL_MAP_KEY);\n const drop = new Set(covered);\n const signal: CheckpointSignal = { snapshotId, by: this.options.clientId };\n this.doc.transact(() => {\n const entries = yArray.toArray();\n for (let i = entries.length - 1; i >= 0; i -= 1) {\n const eid = entries[i]?.eid;\n if (eid && drop.has(eid)) yArray.delete(i, 1);\n }\n control.set(CHECKPOINT_KEY, signal);\n });\n }\n\n /**\n * This client replaced the whole content and SAVED it as `snapshotId`.\n * One transaction empties the shared mutation log (every entry targets the\n * content that is gone — a joiner must never replay them onto the new\n * snapshot) and tells every peer to reload the newest snapshot.\n */\n announceReplaced(snapshotId: string): void {\n if (!this.doc) return;\n const yArray = this.doc.getArray<CollabMutationInfo>(MUTATIONS_ARRAY_KEY);\n const control = this.doc.getMap<unknown>(CONTROL_MAP_KEY);\n const signal: ReplacedSignal = {\n snapshotId,\n by: this.options.clientId,\n nonce: `${this.options.clientId}:${Date.now()}:${Math.random().toString(36).slice(2, 8)}`,\n };\n this.doc.transact(() => {\n if (yArray.length > 0) yArray.delete(0, yArray.length);\n control.set(REPLACED_KEY, signal);\n control.set(CHECKPOINT_KEY, { snapshotId, by: this.options.clientId } satisfies CheckpointSignal);\n });\n }\n\n /**\n * Run `swap` (this client tearing its content down and mounting the new\n * one) without broadcasting what Univer emits while it does: those are not\n * edits, and peers reload the same snapshot themselves.\n */\n muteWhile<T>(swap: () => T): T {\n this.muted += 1;\n try {\n return swap();\n } finally {\n this.muted -= 1;\n }\n }\n\n /**\n * Update the local awareness cursor. Call this from Univer's selection\n * listener (`worksheet.onSelectionChange(...)`). Throttle at the call site\n * (~50ms is plenty); the provider broadcasts on its own debounced cycle.\n */\n setCursor(input: {\n sheetId: string | null;\n row: number | null;\n col: number | null;\n }): void {\n if (!this.awareness) return;\n const current = this.awareness.getLocalState() ?? {};\n this.awareness.setLocalState({\n ...current,\n sheetId: input.sheetId,\n row: input.row,\n col: input.col,\n ts: Date.now(),\n });\n }\n\n /**\n * Returns the deterministic host: the connected peer with the lowest uid\n * (lexicographic). Host is the only client that writes canonical snapshots.\n * No election protocol; recompute whenever awareness changes.\n */\n electHost(opts: { tabTieBreak?: boolean } = {}): { isHost: boolean; hostUid: string | null } {\n if (!this.awareness) return { isHost: false, hostUid: null };\n const states = Array.from(this.awareness.getStates().values()) as Array<\n Record<string, unknown>\n >;\n // Lowest uid wins ACROSS tabs; inside this tab only the room's tab leader\n // may be host, because every same-tab holder carries the same uid.\n const leader = this.provider?.isTabLeader?.() ?? true;\n return electCollabHost(states, this.options.uid, this.options.clientId, leader, opts.tabTieBreak ?? false);\n }\n\n // ─── internals ────────────────────────────────────────────────────────\n\n private handleLocalMutation(info: CollabMutationInfo): void {\n if (this.muted > 0) return;\n if (!this.options.forwardDocumentMutations && isCellEditorScratch(info)) return;\n // Inbound-applied mutations re-fire this listener because Univer's\n // syncExecuteCommand legitimately processes them through the full\n // pipeline. Skip by sniffing the sentinel we stamped on apply.\n if (\n info.params &&\n typeof info.params === \"object\" &&\n !Array.isArray(info.params) &&\n remoteOriginOf(info.params) !== null\n ) {\n return;\n }\n if (!this.doc) return;\n\n // Normalize params through a JSON round-trip BEFORE pushing into Yjs.\n // Yjs (and the Broadcast transport) only carry JSON-encodable values;\n // Univer types its mutation params as \"serializable\" but JS objects can\n // smuggle Date / Map / class instances through that promise. The\n // round-trip makes the failure mode deterministic: a non-encodable\n // mutation is skipped with a warning instead of corrupting the shared\n // doc or desyncing peers mid-session. What we push here is byte-for-byte\n // what remote peers will apply, so local-apply == remote-apply.\n let safeParams: MutationParams;\n try {\n safeParams =\n info.params === undefined || info.params === null\n ? null\n : (JSON.parse(JSON.stringify(info.params)) as MutationParams);\n } catch (err) {\n console.warn(\n `[collab] skipping non-serializable mutation \"${info.id}\" — peers will not receive it`,\n err,\n );\n return;\n }\n\n const yArray = this.doc.getArray<CollabMutationInfo>(MUTATIONS_ARRAY_KEY);\n const eid = `${this.options.clientId}:${++this.seq}`;\n this.applied.add(eid);\n // An edit made here is made on what this seat shows: the join-time check is over.\n this.joined = true;\n yArray.push([{ id: info.id, type: info.type, params: safeParams, uid: this.options.uid, eid }]);\n }\n\n /**\n * Apply every log entry this seat's content does not hold yet, in the log's order. The first time the\n * room shows content, the join-time check runs: a seat that booted from a snapshot OLDER than the\n * room's newest checkpoint reloads first (the entries that checkpoint trimmed exist only in it).\n */\n private drain(): void {\n if (!this.doc || this.disposed || this.reloadingBase) return;\n const yArray = this.doc.getArray<CollabMutationInfo>(MUTATIONS_ARRAY_KEY);\n const entries = yArray.toArray();\n const base = this.options.base;\n if (!this.joined) {\n const control = this.doc.getMap<unknown>(CONTROL_MAP_KEY);\n const checkpoint = control.get(CHECKPOINT_KEY) as CheckpointSignal | undefined;\n if (entries.length === 0 && !checkpoint) return;\n this.joined = true;\n if (base && checkpoint?.snapshotId && checkpoint.snapshotId !== base.snapshotId()) {\n this.reloadingBase = true;\n void base\n .reload()\n .catch((error: unknown) => {\n console.warn(\"[collab] could not load the newest saved version on joining\", error);\n this.options.onApplyFailed?.(\"collab.join\", error);\n })\n .finally(() => {\n this.reloadingBase = false;\n this.drain();\n });\n return;\n }\n }\n const covered = base?.covered();\n for (const op of entries) {\n if (op.eid) {\n if (this.applied.has(op.eid) || covered?.has(op.eid)) continue;\n this.applied.add(op.eid);\n } else {\n if (this.appliedRefs.has(op)) continue;\n this.appliedRefs.add(op);\n }\n this.applyRemoteMutation(op);\n }\n }\n\n private applyRemoteMutation(op: CollabMutationInfo): void {\n // Wrap params with the sentinel so handleLocalMutation knows not to\n // echo the apply back into Yjs.\n const ownUnit = this.options.unitId?.() ?? null;\n const taggedParams: MutationParams =\n op.params && typeof op.params === \"object\" && !Array.isArray(op.params)\n ? {\n ...(op.params as Record<string, unknown>),\n ...(ownUnit && typeof (op.params as { unitId?: unknown }).unitId === \"string\" ? { unitId: ownUnit } : {}),\n [REMOTE_PARAM_TAG]: op.uid ?? true,\n }\n : op.params;\n\n try {\n this.options.commandService.syncExecuteCommand(op.id, taggedParams, {\n onlyLocal: true,\n fromCollab: true,\n });\n } catch (err) {\n // One unappliable op (already baked into the loaded snapshot, or a\n // stale target) must not throw into the realtime channel handler and\n // abort the rest of the catch-up. Said, never swallowed.\n console.warn(\n `[collab] could not apply remote mutation \"${op.id}\" — skipped`,\n err,\n );\n this.options.onApplyFailed?.(op.id, err);\n }\n }\n}\n\n// ─── helpers ────────────────────────────────────────────────────────────\n\n/**\n * A workbook holds no Univer DOCUMENT units of its own: the `doc.mutation.*` stream a sheet emits is\n * the in-cell editor's scratch document (typing into a cell). The finished text reaches the sheet as\n * `sheet.mutation.set-range-values`, which does travel. Sending the scratch edits made a joiner replay\n * them against an editor unit it does not have (\"Trying to overwrite value at key\").\n */\nexport function isCellEditorScratch(info: Pick<CollabMutationInfo, \"id\">): boolean {\n return typeof info.id === \"string\" && info.id.startsWith(\"doc.mutation.\");\n}\n\nconst CURSOR_PALETTE = [\n \"#3b82f6\", // blue\n \"#10b981\", // emerald\n \"#f59e0b\", // amber\n \"#ef4444\", // red\n \"#8b5cf6\", // violet\n \"#06b6d4\", // cyan\n \"#ec4899\", // pink\n \"#84cc16\", // lime\n];\n\nfunction pickColor(uid: string): string {\n // Deterministic FNV-1a-ish hash so the same user is always the same color\n // across sessions and across other users' screens.\n let h = 2166136261;\n for (let i = 0; i < uid.length; i++) {\n h ^= uid.charCodeAt(i);\n h = Math.imul(h, 16777619);\n }\n return CURSOR_PALETTE[Math.abs(h) % CURSOR_PALETTE.length] ?? \"#ec4899\";\n}\n","/**\n * A saved snapshot names the collab-room entries it already holds, so a seat that boots from it never\n * replays them (2026-10-16: a reload showed the text twice). Pure — no Yjs — so the editors' model can\n * stamp and read it without loading the room.\n */\n\n/** The key a saved snapshot carries its covered room entries under (`stampCovered` / `takeCovered`). */\nexport const COLLAB_COVERED_KEY = \"__matrxCollabCovered\";\n\n/** The snapshot to SAVE: `snapshot` plus the room entries it holds (`WorkbookCollabSession.coveredNow`). */\nexport function stampCovered<T extends object>(snapshot: T, covered: readonly string[]): T {\n return { ...snapshot, [COLLAB_COVERED_KEY]: [...covered] };\n}\n\n/** A LOADED snapshot split into the content to mount and the room entries it already holds. */\nexport function takeCovered<T>(snapshot: T): { snapshot: T; covered: Set<string> } {\n if (!snapshot || typeof snapshot !== \"object\" || !(COLLAB_COVERED_KEY in (snapshot as object))) {\n return { snapshot, covered: new Set() };\n }\n const { [COLLAB_COVERED_KEY]: list, ...rest } = snapshot as Record<string, unknown>;\n return {\n snapshot: rest as T,\n covered: new Set(Array.isArray(list) ? list.filter((e): e is string => typeof e === \"string\") : []),\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACwBA,QAAmB;AACnB,uBAA0B;AAE1B,oBAAkE;;;ACpB3D,IAAM,qBAAqB;AAG3B,SAAS,aAA+B,UAAa,SAA+B;AACzF,SAAO,EAAE,GAAG,UAAU,CAAC,kBAAkB,GAAG,CAAC,GAAG,OAAO,EAAE;AAC3D;AAGO,SAAS,YAAe,UAAoD;AACjF,MAAI,CAAC,YAAY,OAAO,aAAa,YAAY,EAAE,sBAAuB,WAAsB;AAC9F,WAAO,EAAE,UAAU,SAAS,oBAAI,IAAI,EAAE;AAAA,EACxC;AACA,QAAM,EAAE,CAAC,kBAAkB,GAAG,MAAM,GAAG,KAAK,IAAI;AAChD,SAAO;AAAA,IACL,UAAU;AAAA,IACV,SAAS,IAAI,IAAI,MAAM,QAAQ,IAAI,IAAI,KAAK,OAAO,CAAC,MAAmB,OAAO,MAAM,QAAQ,IAAI,CAAC,CAAC;AAAA,EACpG;AACF;;;AD4HA,IAAM,sBAAsB;AAC5B,IAAM,kBAAkB;AACxB,IAAM,eAAe;AACrB,IAAM,iBAAiB;AAEhB,IAAM,wBAAN,MAA4B;AAAA,EAChB;AAAA,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,MAAM,IAClE;AAAA,MACE,GAAI,GAAG;AAAA,MACP,GAAI,WAAW,OAAQ,GAAG,OAAgC,WAAW,WAAW,EAAE,QAAQ,QAAQ,IAAI,CAAC;AAAA,MACvG,CAAC,8BAAgB,GAAG,GAAG,OAAO;AAAA,IAChC,IACA,GAAG;AAET,QAAI;AACF,WAAK,QAAQ,eAAe,mBAAmB,GAAG,IAAI,cAAc;AAAA,QAClE,WAAW;AAAA,QACX,YAAY;AAAA,MACd,CAAC;AAAA,IACH,SAAS,KAAK;AAIZ,cAAQ;AAAA,QACN,6CAA6C,GAAG,EAAE;AAAA,QAClD;AAAA,MACF;AACA,WAAK,QAAQ,gBAAgB,GAAG,IAAI,GAAG;AAAA,IACzC;AAAA,EACF;AACF;AAUO,SAAS,oBAAoB,MAA+C;AACjF,SAAO,OAAO,KAAK,OAAO,YAAY,KAAK,GAAG,WAAW,eAAe;AAC1E;AAEA,IAAM,iBAAiB;AAAA,EACrB;AAAA;AAAA,EACA;AAAA;AAAA,EACA;AAAA;AAAA,EACA;AAAA;AAAA,EACA;AAAA;AAAA,EACA;AAAA;AAAA,EACA;AAAA;AAAA,EACA;AAAA;AACF;AAEA,SAAS,UAAU,KAAqB;AAGtC,MAAI,IAAI;AACR,WAAS,IAAI,GAAG,IAAI,IAAI,QAAQ,KAAK;AACnC,SAAK,IAAI,WAAW,CAAC;AACrB,QAAI,KAAK,KAAK,GAAG,QAAQ;AAAA,EAC3B;AACA,SAAO,eAAe,KAAK,IAAI,CAAC,IAAI,eAAe,MAAM,KAAK;AAChE;","names":[]}
|
package/dist/univer-collab.d.cts
CHANGED
|
@@ -1,6 +1,21 @@
|
|
|
1
1
|
import * as Y from 'yjs';
|
|
2
2
|
import { Awareness } from 'y-protocols/awareness';
|
|
3
3
|
|
|
4
|
+
/**
|
|
5
|
+
* A saved snapshot names the collab-room entries it already holds, so a seat that boots from it never
|
|
6
|
+
* replays them (2026-10-16: a reload showed the text twice). Pure — no Yjs — so the editors' model can
|
|
7
|
+
* stamp and read it without loading the room.
|
|
8
|
+
*/
|
|
9
|
+
/** The key a saved snapshot carries its covered room entries under (`stampCovered` / `takeCovered`). */
|
|
10
|
+
declare const COLLAB_COVERED_KEY = "__matrxCollabCovered";
|
|
11
|
+
/** The snapshot to SAVE: `snapshot` plus the room entries it holds (`WorkbookCollabSession.coveredNow`). */
|
|
12
|
+
declare function stampCovered<T extends object>(snapshot: T, covered: readonly string[]): T;
|
|
13
|
+
/** A LOADED snapshot split into the content to mount and the room entries it already holds. */
|
|
14
|
+
declare function takeCovered<T>(snapshot: T): {
|
|
15
|
+
snapshot: T;
|
|
16
|
+
covered: Set<string>;
|
|
17
|
+
};
|
|
18
|
+
|
|
4
19
|
/**
|
|
5
20
|
* Structural transport contract. `SupabaseYjsProvider` satisfies it in
|
|
6
21
|
* production; the verification harness injects an in-memory loopback
|
|
@@ -25,6 +40,22 @@ type CollabMutationInfo = {
|
|
|
25
40
|
params: MutationParams;
|
|
26
41
|
/** Who made it (the person's uid), so a peer can tell its own other tab's edit from a stranger's. */
|
|
27
42
|
uid?: string;
|
|
43
|
+
/**
|
|
44
|
+
* The entry's identity in the room (`<clientId>:<seq>`). A saved snapshot names the entries it holds
|
|
45
|
+
* (`stampCovered`), so a seat that boots from that snapshot never replays them a second time.
|
|
46
|
+
*/
|
|
47
|
+
eid?: string;
|
|
48
|
+
};
|
|
49
|
+
/**
|
|
50
|
+
* What a seat booted from: the saved snapshot's row id and the room entries that snapshot already holds.
|
|
51
|
+
* The session never replays a covered entry, and a seat that booted from an OLDER snapshot than the
|
|
52
|
+
* room's newest checkpoint first reloads (the entries that checkpoint trimmed are only in that snapshot).
|
|
53
|
+
*/
|
|
54
|
+
type CollabBase = {
|
|
55
|
+
snapshotId: () => string | null;
|
|
56
|
+
covered: () => ReadonlySet<string>;
|
|
57
|
+
/** Show the newest saved snapshot (and make it the base). */
|
|
58
|
+
reload: () => Promise<void>;
|
|
28
59
|
};
|
|
29
60
|
type ExecuteOptions = {
|
|
30
61
|
/** Per-Univer convention: when true, the command runs locally only and is
|
|
@@ -74,6 +105,12 @@ type WorkbookCollabSessionOptions = {
|
|
|
74
105
|
unitId?: () => string | null;
|
|
75
106
|
/** A peer's mutation could not be applied here: the seat says so and re-syncs; never only a console line. */
|
|
76
107
|
onApplyFailed?: (mutationId: string, error: unknown) => void;
|
|
108
|
+
/**
|
|
109
|
+
* The saved snapshot this seat booted from. Without it a reloading seat replays every entry still in
|
|
110
|
+
* the room's log on top of a snapshot that already holds them: the text shows twice, and the next save
|
|
111
|
+
* stores it twice (2026-10-16).
|
|
112
|
+
*/
|
|
113
|
+
base?: CollabBase;
|
|
77
114
|
};
|
|
78
115
|
declare class WorkbookCollabSession {
|
|
79
116
|
private readonly options;
|
|
@@ -88,25 +125,33 @@ declare class WorkbookCollabSession {
|
|
|
88
125
|
private muted;
|
|
89
126
|
private started;
|
|
90
127
|
private disposed;
|
|
128
|
+
/** Room entries this seat holds in its content: applied from a peer, or made here. */
|
|
129
|
+
private readonly applied;
|
|
130
|
+
/** Entries without an id (a peer on an older build) are applied once, by identity. */
|
|
131
|
+
private readonly appliedRefs;
|
|
132
|
+
private seq;
|
|
133
|
+
/** False until this seat has seen the room's content once (the join-time check runs then). */
|
|
134
|
+
private joined;
|
|
135
|
+
/** The base is being reloaded: entries wait in the log until it is shown. */
|
|
136
|
+
private reloadingBase;
|
|
91
137
|
constructor(options: WorkbookCollabSessionOptions);
|
|
92
138
|
start(): Promise<void>;
|
|
93
139
|
stop(): void;
|
|
140
|
+
/** How many mutations the shared log holds right now. */
|
|
141
|
+
logLength(): number;
|
|
94
142
|
/**
|
|
95
|
-
*
|
|
96
|
-
*
|
|
97
|
-
*
|
|
143
|
+
* The room entries this seat's content holds RIGHT NOW. Read it in the same synchronous step as the
|
|
144
|
+
* content you are about to save, and save it with that content (`stampCovered`); after the save lands,
|
|
145
|
+
* pass it to `checkpoint`.
|
|
98
146
|
*/
|
|
99
|
-
|
|
147
|
+
coveredNow(): string[];
|
|
100
148
|
/**
|
|
101
|
-
*
|
|
102
|
-
*
|
|
103
|
-
*
|
|
104
|
-
* the
|
|
105
|
-
* holds them — Univer refuses with "Trying to overwrite value at key"
|
|
106
|
-
* (feedback 88184e53). Only the host calls this; peers receive it as a
|
|
107
|
-
* delete, which the inbound observer ignores (it acts on inserts only).
|
|
149
|
+
* The snapshot `snapshotId` was SAVED holding `covered` (from `coveredNow`): those entries leave the
|
|
150
|
+
* shared log, and the room records the snapshot as its newest checkpoint. Removal is by entry id, never
|
|
151
|
+
* by position — an entry that arrived while the save was in flight is not in the snapshot and stays.
|
|
152
|
+
* Only the elected saver calls this; peers receive it as a delete (never replayed).
|
|
108
153
|
*/
|
|
109
|
-
|
|
154
|
+
checkpoint(snapshotId: string, covered: readonly string[]): void;
|
|
110
155
|
/**
|
|
111
156
|
* This client replaced the whole content and SAVED it as `snapshotId`.
|
|
112
157
|
* One transaction empties the shared mutation log (every entry targets the
|
|
@@ -142,6 +187,12 @@ declare class WorkbookCollabSession {
|
|
|
142
187
|
hostUid: string | null;
|
|
143
188
|
};
|
|
144
189
|
private handleLocalMutation;
|
|
190
|
+
/**
|
|
191
|
+
* Apply every log entry this seat's content does not hold yet, in the log's order. The first time the
|
|
192
|
+
* room shows content, the join-time check runs: a seat that booted from a snapshot OLDER than the
|
|
193
|
+
* room's newest checkpoint reloads first (the entries that checkpoint trimmed exist only in it).
|
|
194
|
+
*/
|
|
195
|
+
private drain;
|
|
145
196
|
private applyRemoteMutation;
|
|
146
197
|
}
|
|
147
198
|
/**
|
|
@@ -152,4 +203,4 @@ declare class WorkbookCollabSession {
|
|
|
152
203
|
*/
|
|
153
204
|
declare function isCellEditorScratch(info: Pick<CollabMutationInfo, "id">): boolean;
|
|
154
205
|
|
|
155
|
-
export { type CollabMutationInfo, type CollabProviderLike, type CommandServiceLike, WorkbookCollabSession, type WorkbookCollabSessionOptions, isCellEditorScratch };
|
|
206
|
+
export { COLLAB_COVERED_KEY, type CollabBase, type CollabMutationInfo, type CollabProviderLike, type CommandServiceLike, WorkbookCollabSession, type WorkbookCollabSessionOptions, isCellEditorScratch, stampCovered, takeCovered };
|
package/dist/univer-collab.d.ts
CHANGED
|
@@ -1,6 +1,21 @@
|
|
|
1
1
|
import * as Y from 'yjs';
|
|
2
2
|
import { Awareness } from 'y-protocols/awareness';
|
|
3
3
|
|
|
4
|
+
/**
|
|
5
|
+
* A saved snapshot names the collab-room entries it already holds, so a seat that boots from it never
|
|
6
|
+
* replays them (2026-10-16: a reload showed the text twice). Pure — no Yjs — so the editors' model can
|
|
7
|
+
* stamp and read it without loading the room.
|
|
8
|
+
*/
|
|
9
|
+
/** The key a saved snapshot carries its covered room entries under (`stampCovered` / `takeCovered`). */
|
|
10
|
+
declare const COLLAB_COVERED_KEY = "__matrxCollabCovered";
|
|
11
|
+
/** The snapshot to SAVE: `snapshot` plus the room entries it holds (`WorkbookCollabSession.coveredNow`). */
|
|
12
|
+
declare function stampCovered<T extends object>(snapshot: T, covered: readonly string[]): T;
|
|
13
|
+
/** A LOADED snapshot split into the content to mount and the room entries it already holds. */
|
|
14
|
+
declare function takeCovered<T>(snapshot: T): {
|
|
15
|
+
snapshot: T;
|
|
16
|
+
covered: Set<string>;
|
|
17
|
+
};
|
|
18
|
+
|
|
4
19
|
/**
|
|
5
20
|
* Structural transport contract. `SupabaseYjsProvider` satisfies it in
|
|
6
21
|
* production; the verification harness injects an in-memory loopback
|
|
@@ -25,6 +40,22 @@ type CollabMutationInfo = {
|
|
|
25
40
|
params: MutationParams;
|
|
26
41
|
/** Who made it (the person's uid), so a peer can tell its own other tab's edit from a stranger's. */
|
|
27
42
|
uid?: string;
|
|
43
|
+
/**
|
|
44
|
+
* The entry's identity in the room (`<clientId>:<seq>`). A saved snapshot names the entries it holds
|
|
45
|
+
* (`stampCovered`), so a seat that boots from that snapshot never replays them a second time.
|
|
46
|
+
*/
|
|
47
|
+
eid?: string;
|
|
48
|
+
};
|
|
49
|
+
/**
|
|
50
|
+
* What a seat booted from: the saved snapshot's row id and the room entries that snapshot already holds.
|
|
51
|
+
* The session never replays a covered entry, and a seat that booted from an OLDER snapshot than the
|
|
52
|
+
* room's newest checkpoint first reloads (the entries that checkpoint trimmed are only in that snapshot).
|
|
53
|
+
*/
|
|
54
|
+
type CollabBase = {
|
|
55
|
+
snapshotId: () => string | null;
|
|
56
|
+
covered: () => ReadonlySet<string>;
|
|
57
|
+
/** Show the newest saved snapshot (and make it the base). */
|
|
58
|
+
reload: () => Promise<void>;
|
|
28
59
|
};
|
|
29
60
|
type ExecuteOptions = {
|
|
30
61
|
/** Per-Univer convention: when true, the command runs locally only and is
|
|
@@ -74,6 +105,12 @@ type WorkbookCollabSessionOptions = {
|
|
|
74
105
|
unitId?: () => string | null;
|
|
75
106
|
/** A peer's mutation could not be applied here: the seat says so and re-syncs; never only a console line. */
|
|
76
107
|
onApplyFailed?: (mutationId: string, error: unknown) => void;
|
|
108
|
+
/**
|
|
109
|
+
* The saved snapshot this seat booted from. Without it a reloading seat replays every entry still in
|
|
110
|
+
* the room's log on top of a snapshot that already holds them: the text shows twice, and the next save
|
|
111
|
+
* stores it twice (2026-10-16).
|
|
112
|
+
*/
|
|
113
|
+
base?: CollabBase;
|
|
77
114
|
};
|
|
78
115
|
declare class WorkbookCollabSession {
|
|
79
116
|
private readonly options;
|
|
@@ -88,25 +125,33 @@ declare class WorkbookCollabSession {
|
|
|
88
125
|
private muted;
|
|
89
126
|
private started;
|
|
90
127
|
private disposed;
|
|
128
|
+
/** Room entries this seat holds in its content: applied from a peer, or made here. */
|
|
129
|
+
private readonly applied;
|
|
130
|
+
/** Entries without an id (a peer on an older build) are applied once, by identity. */
|
|
131
|
+
private readonly appliedRefs;
|
|
132
|
+
private seq;
|
|
133
|
+
/** False until this seat has seen the room's content once (the join-time check runs then). */
|
|
134
|
+
private joined;
|
|
135
|
+
/** The base is being reloaded: entries wait in the log until it is shown. */
|
|
136
|
+
private reloadingBase;
|
|
91
137
|
constructor(options: WorkbookCollabSessionOptions);
|
|
92
138
|
start(): Promise<void>;
|
|
93
139
|
stop(): void;
|
|
140
|
+
/** How many mutations the shared log holds right now. */
|
|
141
|
+
logLength(): number;
|
|
94
142
|
/**
|
|
95
|
-
*
|
|
96
|
-
*
|
|
97
|
-
*
|
|
143
|
+
* The room entries this seat's content holds RIGHT NOW. Read it in the same synchronous step as the
|
|
144
|
+
* content you are about to save, and save it with that content (`stampCovered`); after the save lands,
|
|
145
|
+
* pass it to `checkpoint`.
|
|
98
146
|
*/
|
|
99
|
-
|
|
147
|
+
coveredNow(): string[];
|
|
100
148
|
/**
|
|
101
|
-
*
|
|
102
|
-
*
|
|
103
|
-
*
|
|
104
|
-
* the
|
|
105
|
-
* holds them — Univer refuses with "Trying to overwrite value at key"
|
|
106
|
-
* (feedback 88184e53). Only the host calls this; peers receive it as a
|
|
107
|
-
* delete, which the inbound observer ignores (it acts on inserts only).
|
|
149
|
+
* The snapshot `snapshotId` was SAVED holding `covered` (from `coveredNow`): those entries leave the
|
|
150
|
+
* shared log, and the room records the snapshot as its newest checkpoint. Removal is by entry id, never
|
|
151
|
+
* by position — an entry that arrived while the save was in flight is not in the snapshot and stays.
|
|
152
|
+
* Only the elected saver calls this; peers receive it as a delete (never replayed).
|
|
108
153
|
*/
|
|
109
|
-
|
|
154
|
+
checkpoint(snapshotId: string, covered: readonly string[]): void;
|
|
110
155
|
/**
|
|
111
156
|
* This client replaced the whole content and SAVED it as `snapshotId`.
|
|
112
157
|
* One transaction empties the shared mutation log (every entry targets the
|
|
@@ -142,6 +187,12 @@ declare class WorkbookCollabSession {
|
|
|
142
187
|
hostUid: string | null;
|
|
143
188
|
};
|
|
144
189
|
private handleLocalMutation;
|
|
190
|
+
/**
|
|
191
|
+
* Apply every log entry this seat's content does not hold yet, in the log's order. The first time the
|
|
192
|
+
* room shows content, the join-time check runs: a seat that booted from a snapshot OLDER than the
|
|
193
|
+
* room's newest checkpoint reloads first (the entries that checkpoint trimmed exist only in it).
|
|
194
|
+
*/
|
|
195
|
+
private drain;
|
|
145
196
|
private applyRemoteMutation;
|
|
146
197
|
}
|
|
147
198
|
/**
|
|
@@ -152,4 +203,4 @@ declare class WorkbookCollabSession {
|
|
|
152
203
|
*/
|
|
153
204
|
declare function isCellEditorScratch(info: Pick<CollabMutationInfo, "id">): boolean;
|
|
154
205
|
|
|
155
|
-
export { type CollabMutationInfo, type CollabProviderLike, type CommandServiceLike, WorkbookCollabSession, type WorkbookCollabSessionOptions, isCellEditorScratch };
|
|
206
|
+
export { COLLAB_COVERED_KEY, type CollabBase, type CollabMutationInfo, type CollabProviderLike, type CommandServiceLike, WorkbookCollabSession, type WorkbookCollabSessionOptions, isCellEditorScratch, stampCovered, takeCovered };
|