@vite-hub/realtime 0.5.0 → 0.5.1

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 (43) hide show
  1. package/README.md +2 -2
  2. package/dist/agent.d.ts +1 -1
  3. package/dist/agent.js +1 -2
  4. package/dist/{bus-Bsdanf5O.js → bus-DJ3dOQAZ.js} +4 -6
  5. package/dist/{bus-protocol-wXkXW28q.d.ts → bus-protocol-juNrVJDF.d.ts} +0 -2
  6. package/dist/bus.d.ts +1 -3
  7. package/dist/bus.js +1 -2
  8. package/dist/client/browser.js +3 -3
  9. package/dist/client.d.ts +2 -4
  10. package/dist/client.js +5 -6
  11. package/dist/{conflict-DYC_qXzM.js → conflict-BqdKFrkE.js} +3 -5
  12. package/dist/{conflict-CmZizTYl.d.ts → conflict-C5KRv-J1.d.ts} +0 -2
  13. package/dist/{document-b1ShR2S1.d.ts → document-CbqgNO_0.d.ts} +2 -4
  14. package/dist/document-CfrQbB03.js +1736 -0
  15. package/dist/durability.d.ts +1 -3
  16. package/dist/durability.js +1 -2
  17. package/dist/{editor-IL2jHqn8.js → editor-DzhKM4Gt.js} +2 -4
  18. package/dist/{error-diagnostics-Cd-XWNf7.js → error-diagnostics-we8V1O-X.js} +1 -2
  19. package/dist/index.d.ts +3 -7
  20. package/dist/index.js +3 -3
  21. package/dist/internal/runtime/unavailable.d.ts +1 -3
  22. package/dist/internal/runtime/unavailable.js +1 -2
  23. package/dist/internal/server.d.ts +6 -6
  24. package/dist/internal/server.js +5 -5
  25. package/dist/{keepalive-B4ONG6AD.js → keepalive-BYkk6Ax8.js} +3 -5
  26. package/dist/{layout-DNaxppTZ.js → layout-BQwRLTH0.js} +1 -2
  27. package/dist/{layout-VHjYWa-M.d.ts → layout-BZtKNqiC.d.ts} +1 -3
  28. package/dist/{log-E-cH6xkd.js → log-NlQi6kow.js} +2 -4
  29. package/dist/{object-BgPPDLDE.js → object-DfrneieE.js} +2 -4
  30. package/dist/{presence-B6rvkHqd.js → presence-DZ21pPKm.js} +3 -4
  31. package/dist/{request-kM5epeSd.js → request-DM6xHTaU.js} +5 -9
  32. package/dist/{request-DAodIqZ8.d.ts → request-PrMHOYFK.d.ts} +1 -3
  33. package/dist/{server-Covbc24E.d.ts → server-CLdYV7Md.d.ts} +6 -20
  34. package/dist/{server-BSXJP45b.js → server-yQp02XNp.js} +17 -24
  35. package/dist/server.d.ts +3 -3
  36. package/dist/server.js +2 -2
  37. package/dist/{types-DdY7Vo1H.d.ts → types-oUyN-CJR.d.ts} +1 -5
  38. package/dist/vite.d.ts +2 -15
  39. package/dist/vite.js +20 -27
  40. package/dist/vue.d.ts +2 -6
  41. package/dist/vue.js +47 -26
  42. package/package.json +39 -39
  43. package/dist/document-U5rzg2vG.js +0 -2041
@@ -0,0 +1,1736 @@
1
+ import { n as isRecord } from "./object-DfrneieE.js";
2
+ import { n as realtimeDocumentLayout } from "./layout-BQwRLTH0.js";
3
+ import * as Y from "yjs";
4
+ import { AbstractType, ContentType, Item, Text, UndoManager, XmlElement, XmlFragment, XmlHook, XmlText } from "yjs";
5
+ import { getSchema } from "@tiptap/core";
6
+ import { Decoration, DecorationSet } from "prosemirror-view";
7
+ import { AllSelection, NodeSelection, Plugin, PluginKey, Selection, TextSelection } from "prosemirror-state";
8
+ import * as PModel from "prosemirror-model";
9
+ import { Node as Node$1, Slice } from "prosemirror-model";
10
+ import * as error from "lib0/error";
11
+ import { ReplaceStep, replaceStep } from "prosemirror-transform";
12
+ import * as eventloop from "lib0/eventloop";
13
+ import { timeout } from "lib0/eventloop";
14
+ import * as math from "lib0/math";
15
+ import { createMutex } from "lib0/mutex";
16
+ import * as environment from "lib0/environment";
17
+ import * as dom from "lib0/dom";
18
+ import * as set from "lib0/set";
19
+ import * as random from "lib0/random";
20
+ import * as map from "lib0/map";
21
+ import * as sha256 from "lib0/hash/sha256";
22
+ import * as buf from "lib0/buffer";
23
+ import * as object from "lib0/object";
24
+ import { simpleDiff } from "lib0/diff";
25
+ // ../../node_modules/.pnpm/@tiptap+y-tiptap@3.3.1_prosemirror-model@1.25.13_prosemirror-state@1.4.4_prosemirror-vi_b58d38912836a5f4eb85f414a3f51083/node_modules/@tiptap/y-tiptap/dist/index.js
26
+ function getYType(item) {
27
+ if (!item) return null;
28
+ if (!(item.content instanceof ContentType)) return null;
29
+ const type = item.content.type;
30
+ if (!(type instanceof XmlFragment || type instanceof Text || type instanceof XmlHook)) throw new Error("Expected a Yjs XML type");
31
+ return type;
32
+ }
33
+ function getYParent(item) {
34
+ if (item === null) return null;
35
+ if (!(item.parent instanceof AbstractType)) throw new Error("Expected an integrated Yjs parent");
36
+ const type = item.parent;
37
+ if (!(type instanceof XmlFragment || type instanceof Text || type instanceof XmlHook)) throw new Error("Expected a Yjs XML type");
38
+ return type;
39
+ }
40
+ const createRelativePosition = (type, item) => {
41
+ let typeid = null;
42
+ let tname = null;
43
+ if (type._item === null) tname = Y.findRootTypeKey(type);
44
+ else typeid = Y.createID(type._item.id.client, type._item.id.clock);
45
+ return new Y.RelativePosition(typeid, tname, item.id);
46
+ };
47
+ /** Converts a ProseMirror position to a Yjs relative position. */
48
+ const absolutePositionToRelativePosition = (pos, type, mapping) => {
49
+ if (pos === 0) return Y.createRelativePositionFromTypeIndex(type, 0, -1);
50
+ let n = getYType(type._first);
51
+ while (n !== null && type !== n) {
52
+ if (n instanceof Y.XmlText) {
53
+ if (n._length >= pos) return Y.createRelativePositionFromTypeIndex(n, pos, -1);
54
+ else pos -= n._length;
55
+ if (n._item !== null && n._item.next !== null) n = getYType(n._item.next);
56
+ else {
57
+ do {
58
+ n = getYParent(n._item);
59
+ pos--;
60
+ } while (n !== type && n !== null && n._item !== null && n._item.next === null);
61
+ if (n !== null && n !== type) n = n._item === null ? null : getYType(n._item.next);
62
+ }
63
+ } else {
64
+ const mapped = mapping.get(n);
65
+ const pNodeSize = mapped instanceof Node$1 ? mapped.nodeSize : 0;
66
+ if (n._first !== null && pos < pNodeSize) {
67
+ n = getYType(n._first);
68
+ pos--;
69
+ } else {
70
+ if (pos === 1 && n._length === 0 && pNodeSize > 1) return new Y.RelativePosition(n._item === null ? null : n._item.id, n._item === null ? Y.findRootTypeKey(n) : null, null);
71
+ pos -= pNodeSize;
72
+ if (n._item !== null && n._item.next !== null) n = getYType(n._item.next);
73
+ else {
74
+ var _n$_item;
75
+ if (pos === 0) {
76
+ n = n._item === null ? n : getYParent(n._item);
77
+ if (n === null) throw error.unexpectedCase();
78
+ return new Y.RelativePosition(n._item === null ? null : n._item.id, n._item === null ? Y.findRootTypeKey(n) : null, null);
79
+ }
80
+ do {
81
+ n = getYParent(n._item);
82
+ if (n === null) throw error.unexpectedCase();
83
+ pos--;
84
+ } while (n !== type && ((_n$_item = n._item) === null || _n$_item === void 0 ? void 0 : _n$_item.next) === null);
85
+ if (n !== type) {
86
+ var _n$_item2;
87
+ n = getYType((_n$_item2 = n._item) === null || _n$_item2 === void 0 ? void 0 : _n$_item2.next);
88
+ }
89
+ }
90
+ }
91
+ }
92
+ if (n === null) throw error.unexpectedCase();
93
+ if (pos === 0 && n.constructor !== Y.XmlText && n !== type) {
94
+ const item = n._item;
95
+ const parent = getYParent(item);
96
+ if (item === null || parent === null) throw error.unexpectedCase();
97
+ return createRelativePosition(parent, item);
98
+ }
99
+ }
100
+ return Y.createRelativePositionFromTypeIndex(type, type._length, -1);
101
+ };
102
+ /** Reports whether a transaction changes the document structure. */
103
+ const isStructuralTransaction = (tr, oldDoc) => {
104
+ if (!tr.docChanged) return false;
105
+ if (tr.doc.childCount !== oldDoc.childCount) return true;
106
+ for (const step of tr.steps) if (step instanceof ReplaceStep) {
107
+ if (step.from === 0 && step.to === oldDoc.content.size) return true;
108
+ if (step.slice.content.size > 0) {
109
+ let hasBlock = false;
110
+ step.slice.content.forEach((node) => {
111
+ if (node.isBlock) hasBlock = true;
112
+ });
113
+ if (hasBlock) return true;
114
+ } else if (step.to > step.from) {
115
+ const $from = oldDoc.resolve(step.from);
116
+ const $to = oldDoc.resolve(step.to);
117
+ if ($from.depth === 0 && $to.depth === 0 && $from.index() !== $to.index()) return true;
118
+ }
119
+ }
120
+ return false;
121
+ };
122
+ function getYTypeSize(type, mapping) {
123
+ if (type instanceof XmlText) return type._length;
124
+ const node = mapping.get(type);
125
+ return node instanceof Node$1 ? node.nodeSize : null;
126
+ }
127
+ function getParentOffset(parent, type, mapping) {
128
+ let offset = 0;
129
+ let item = parent._first;
130
+ while (item !== null) {
131
+ const child = getYType(item);
132
+ if (child === type) break;
133
+ const deleted = item.deleted;
134
+ item = item.right;
135
+ if (deleted) continue;
136
+ if (child === null) return null;
137
+ const size = getYTypeSize(child, mapping);
138
+ if (size === null) return null;
139
+ offset += size;
140
+ }
141
+ return offset;
142
+ }
143
+ function getYContentOffset(type, index, mapping) {
144
+ let offset = 0;
145
+ let childIndex = 0;
146
+ let item = type._first;
147
+ while (childIndex < type._length && childIndex < index && item !== null) {
148
+ const current = item;
149
+ item = item.right;
150
+ if (current.deleted) continue;
151
+ const child = getYType(current);
152
+ if (child === null) return null;
153
+ const size = getYTypeSize(child, mapping);
154
+ if (size === null) return null;
155
+ childIndex++;
156
+ offset += size;
157
+ }
158
+ return offset;
159
+ }
160
+ /** Detects a text position that resolved outside its original block. */
161
+ const isMisresolvedTextPosition = (y, relPos, absPos) => {
162
+ var _decoded$type$_item;
163
+ if (absPos === null) return false;
164
+ const decoded = Y.createAbsolutePositionFromRelativePosition(relPos, y);
165
+ return decoded !== null && decoded.type instanceof Y.XmlText && relPos.item !== null && ((_decoded$type$_item = decoded.type._item) === null || _decoded$type$_item === void 0 ? void 0 : _decoded$type$_item.deleted) === true;
166
+ };
167
+ /** Resolves a Yjs relative position, returning null when it cannot be mapped. */
168
+ const relativePositionToAbsolutePosition = (y, documentType, relPos, mapping) => {
169
+ var _type$_item;
170
+ const decodedPos = Y.createAbsolutePositionFromRelativePosition(relPos, y);
171
+ if (decodedPos === null || decodedPos.type !== documentType && !Y.isParentOf(documentType, decodedPos.type._item)) return null;
172
+ let type = decodedPos.type;
173
+ let pos = 0;
174
+ if (type.constructor === Y.XmlText) pos = decodedPos.index;
175
+ else if (!((_type$_item = type._item) === null || _type$_item === void 0 ? void 0 : _type$_item.deleted)) {
176
+ const offset = getYContentOffset(type, decodedPos.index, mapping);
177
+ if (offset === null) return null;
178
+ pos = offset + 1;
179
+ }
180
+ while (type !== documentType && type._item !== null) {
181
+ var _parent$_item;
182
+ const parent = getYParent(type._item);
183
+ if (parent === null) return null;
184
+ if ((_parent$_item = parent._item) === null || _parent$_item === void 0 ? void 0 : _parent$_item.deleted) {
185
+ type = parent;
186
+ continue;
187
+ }
188
+ const offset = getParentOffset(parent, type, mapping);
189
+ if (offset === null) return null;
190
+ pos += offset + 1;
191
+ type = parent;
192
+ }
193
+ const absPos = pos - 1;
194
+ if (isMisresolvedTextPosition(y, relPos, absPos)) return null;
195
+ return absPos;
196
+ };
197
+ const ySyncPluginKey = new PluginKey("y-sync");
198
+ const yUndoPluginKey = new PluginKey("y-undo");
199
+ const yCursorPluginKey = new PluginKey("yjs-cursor");
200
+ let viewsToUpdate = null;
201
+ function takePendingMetas() {
202
+ const pending = viewsToUpdate;
203
+ viewsToUpdate = null;
204
+ const entries = [];
205
+ pending === null || pending === void 0 || pending.forEach((metas, view) => {
206
+ metas.forEach((value, key) => entries.push({
207
+ view,
208
+ key,
209
+ value
210
+ }));
211
+ });
212
+ return entries;
213
+ }
214
+ function updateMetas(entries = takePendingMetas(), isRetry = false) {
215
+ let isFirst = true;
216
+ while (entries.length > 0) {
217
+ const { view, key, value } = entries[0];
218
+ try {
219
+ const syncState = ySyncPluginKey.getState(view.state);
220
+ if (syncState && syncState.binding.prosemirrorView !== null) view.dispatch(view.state.tr.setMeta(key, value));
221
+ } catch (error) {
222
+ if (!(error instanceof RangeError)) throw error;
223
+ if (isRetry && isFirst) entries.shift();
224
+ if (entries.length > 0) timeout(0, () => updateMetas(entries, true));
225
+ return;
226
+ }
227
+ isFirst = false;
228
+ entries.shift();
229
+ }
230
+ }
231
+ /** Queues plugin metadata and batches repeated updates for the same key. */
232
+ function setMeta(view, key, value) {
233
+ if (viewsToUpdate === null) {
234
+ viewsToUpdate = /* @__PURE__ */ new Map();
235
+ timeout(0, updateMetas);
236
+ }
237
+ let metas = viewsToUpdate.get(view);
238
+ if (!metas) {
239
+ metas = /* @__PURE__ */ new Map();
240
+ viewsToUpdate.set(view, metas);
241
+ }
242
+ metas.set(key, value);
243
+ }
244
+ const defaultAwarenessStateFilter = (currentClientId, userClientId, _user) => currentClientId !== userClientId;
245
+ /** Creates the default remote cursor element from awareness user details. */
246
+ const defaultCursorBuilder = (user) => {
247
+ const cursor = document.createElement("span");
248
+ cursor.classList.add("ProseMirror-yjs-cursor");
249
+ cursor.setAttribute("style", `border-color: ${user.color}`);
250
+ const userDiv = document.createElement("div");
251
+ userDiv.setAttribute("style", `background-color: ${user.color}`);
252
+ userDiv.insertBefore(document.createTextNode(user.name), null);
253
+ const nonbreakingSpace1 = document.createTextNode("⁠");
254
+ const nonbreakingSpace2 = document.createTextNode("⁠");
255
+ cursor.insertBefore(nonbreakingSpace1, null);
256
+ cursor.insertBefore(userDiv, null);
257
+ cursor.insertBefore(nonbreakingSpace2, null);
258
+ return cursor;
259
+ };
260
+ /** Creates the default decoration attributes for a remote selection. */
261
+ const defaultSelectionBuilder = (user) => {
262
+ return {
263
+ style: `background-color: ${user.color}70`,
264
+ class: "ProseMirror-yjs-selection"
265
+ };
266
+ };
267
+ const getMappableSyncState = (state) => {
268
+ const ystate = ySyncPluginKey.getState(state);
269
+ return (ystate === null || ystate === void 0 ? void 0 : ystate.binding) && ystate.binding.invalidContentError === null ? ystate : null;
270
+ };
271
+ const rxValidColor = /^#[0-9a-fA-F]{6}$/;
272
+ const hasCursorUser = (user) => typeof user.name === "string" && typeof user.color === "string";
273
+ const createDecorations = (state, awareness, awarenessFilter, createCursor, createSelection) => {
274
+ const ystate = getMappableSyncState(state);
275
+ if (ystate == null || ystate.doc == null) return DecorationSet.create(state.doc, []);
276
+ const y = ystate.doc;
277
+ const decorations = [];
278
+ if (ystate.snapshot != null || ystate.prevSnapshot != null || ystate.binding.mapping.size === 0) return DecorationSet.create(state.doc, []);
279
+ awareness.getStates().forEach((aw, clientId) => {
280
+ if (!awarenessFilter(y.clientID, clientId, aw)) return;
281
+ if (aw && aw.cursor != null) {
282
+ const user = { ...aw.user };
283
+ if (user.color == null) user.color = "#ffa500";
284
+ else if (!rxValidColor.test(user.color)) console.warn("A user uses an unsupported color format", user);
285
+ if (user.name == null) user.name = `User: ${clientId}`;
286
+ if (!hasCursorUser(user)) return;
287
+ let anchor = relativePositionToAbsolutePosition(y, ystate.type, Y.createRelativePositionFromJSON(aw.cursor.anchor), ystate.binding.mapping);
288
+ let head = relativePositionToAbsolutePosition(y, ystate.type, Y.createRelativePositionFromJSON(aw.cursor.head), ystate.binding.mapping);
289
+ if (anchor !== null && head !== null) {
290
+ const maxsize = math.max(state.doc.content.size - 1, 0);
291
+ anchor = math.min(anchor, maxsize);
292
+ head = math.min(head, maxsize);
293
+ decorations.push(Decoration.widget(head, () => createCursor(user, clientId), {
294
+ key: clientId + "",
295
+ side: 10
296
+ }));
297
+ const from = math.min(anchor, head);
298
+ const to = math.max(anchor, head);
299
+ decorations.push(Decoration.inline(from, to, createSelection(user, clientId), {
300
+ inclusiveEnd: true,
301
+ inclusiveStart: false
302
+ }));
303
+ }
304
+ }
305
+ });
306
+ return DecorationSet.create(state.doc, decorations);
307
+ };
308
+ const isSameSelection = (cursor, selection) => cursor != null && Y.compareRelativePositions(Y.createRelativePositionFromJSON(cursor.anchor), Y.createRelativePositionFromJSON(selection.anchor)) && Y.compareRelativePositions(Y.createRelativePositionFromJSON(cursor.head), Y.createRelativePositionFromJSON(selection.head));
309
+ /** Renders remote cursors and publishes the local selection through awareness. */
310
+ const yCursorPlugin = (awareness, { awarenessStateFilter = defaultAwarenessStateFilter, cursorBuilder = defaultCursorBuilder, selectionBuilder = defaultSelectionBuilder, getSelection = (state) => state.selection } = {}, cursorStateField = "cursor") => {
311
+ if (cursorStateField === "lastSelection") throw new Error("yCursorPlugin: \"lastSelection\" is reserved and cannot be the cursor field");
312
+ return new Plugin({
313
+ key: yCursorPluginKey,
314
+ state: {
315
+ init(_, state) {
316
+ return createDecorations(state, awareness, awarenessStateFilter, cursorBuilder, selectionBuilder);
317
+ },
318
+ apply(tr, prevState, oldState, newState) {
319
+ const ystate = ySyncPluginKey.getState(newState);
320
+ const yCursorState = tr.getMeta(yCursorPluginKey);
321
+ const isRemoteChange = ystate && ystate.isChangeOrigin;
322
+ if (tr.docChanged && !isRemoteChange && isStructuralTransaction(tr, oldState.doc)) return DecorationSet.empty;
323
+ if (isRemoteChange || yCursorState && yCursorState.awarenessUpdated) return createDecorations(newState, awareness, awarenessStateFilter, cursorBuilder, selectionBuilder);
324
+ if (tr.docChanged) return prevState.map(tr.mapping, tr.doc);
325
+ return prevState;
326
+ }
327
+ },
328
+ props: { decorations: (state) => {
329
+ var _yCursorPluginKey$get;
330
+ return (_yCursorPluginKey$get = yCursorPluginKey.getState(state)) !== null && _yCursorPluginKey$get !== void 0 ? _yCursorPluginKey$get : DecorationSet.empty;
331
+ } },
332
+ view: (view) => {
333
+ var _ySyncPluginKey$getSt;
334
+ const syncType = (_ySyncPluginKey$getSt = ySyncPluginKey.getState(view.state)) === null || _ySyncPluginKey$getSt === void 0 ? void 0 : _ySyncPluginKey$getSt.type;
335
+ const field = syncType && syncType._item === null ? Y.findRootTypeKey(syncType) : void 0;
336
+ let publishedCursor = null;
337
+ let publishedEntry = null;
338
+ const awarenessListener = () => {
339
+ if (!view.isDestroyed) setMeta(view, yCursorPluginKey, { awarenessUpdated: true });
340
+ };
341
+ const publish = (current, selection, focused, cursor) => {
342
+ if (field === void 0 || typeof awareness.setLocalState !== "function") {
343
+ if (cursor !== current[cursorStateField]) awareness.setLocalStateField(cursorStateField, cursor);
344
+ return;
345
+ }
346
+ publishedEntry = {
347
+ ...selection,
348
+ time: Date.now(),
349
+ focused
350
+ };
351
+ awareness.setLocalState({
352
+ ...current,
353
+ [cursorStateField]: cursor,
354
+ lastSelection: {
355
+ ...current.lastSelection,
356
+ [field]: publishedEntry
357
+ }
358
+ });
359
+ };
360
+ const releaseCursor = (current) => {
361
+ var _current$lastSelectio;
362
+ if (publishedCursor === null) return;
363
+ const cursor = current[cursorStateField];
364
+ const ownsCursor = cursor === publishedCursor;
365
+ if (field !== void 0 && ((_current$lastSelectio = current.lastSelection) === null || _current$lastSelectio === void 0 ? void 0 : _current$lastSelectio[field]) === publishedEntry) publish(current, publishedCursor, false, ownsCursor ? null : cursor);
366
+ else if (ownsCursor) awareness.setLocalStateField(cursorStateField, null);
367
+ publishedCursor = null;
368
+ publishedEntry = null;
369
+ };
370
+ const updateCursorInfo = (editorView) => {
371
+ const ystate = getMappableSyncState(editorView.state);
372
+ if (!ystate) {
373
+ const localState = awareness.getLocalState();
374
+ if (localState !== null) releaseCursor(localState);
375
+ return;
376
+ }
377
+ const localState = awareness.getLocalState();
378
+ if (localState === null) return;
379
+ const current = localState || {};
380
+ if (!editorView.hasFocus()) {
381
+ releaseCursor(current);
382
+ return;
383
+ }
384
+ const selection = getSelection(editorView.state);
385
+ const anchor = absolutePositionToRelativePosition(selection.anchor, ystate.type, ystate.binding.mapping);
386
+ const head = absolutePositionToRelativePosition(selection.head, ystate.type, ystate.binding.mapping);
387
+ const cursor = current[cursorStateField];
388
+ if (cursor === publishedCursor && isSameSelection(cursor, {
389
+ anchor,
390
+ head
391
+ })) return;
392
+ publishedCursor = {
393
+ anchor,
394
+ head
395
+ };
396
+ publish(current, publishedCursor, true, publishedCursor);
397
+ };
398
+ const onFocusChange = () => updateCursorInfo(view);
399
+ awareness.on("change", awarenessListener);
400
+ view.dom.addEventListener("focusin", onFocusChange);
401
+ view.dom.addEventListener("focusout", onFocusChange);
402
+ return {
403
+ update: updateCursorInfo,
404
+ destroy: () => {
405
+ view.dom.removeEventListener("focusin", onFocusChange);
406
+ view.dom.removeEventListener("focusout", onFocusChange);
407
+ awareness.off("change", awarenessListener);
408
+ if (publishedCursor === null) return;
409
+ const localState = awareness.getLocalState();
410
+ if (localState !== null) releaseCursor(localState);
411
+ }
412
+ };
413
+ }
414
+ });
415
+ };
416
+ function getSyncPluginState(state) {
417
+ const pluginState = ySyncPluginKey.getState(state);
418
+ if (!pluginState) throw new Error("The editor requires ySyncPlugin");
419
+ return pluginState;
420
+ }
421
+ /** Reports whether a Yjs item is visible in the current document or a snapshot. */
422
+ const isVisible = (item, snapshot) => {
423
+ var _snapshot$sv$get;
424
+ return snapshot === void 0 ? !item.deleted : snapshot.sv.has(item.id.client) && ((_snapshot$sv$get = snapshot.sv.get(item.id.client)) !== null && _snapshot$sv$get !== void 0 ? _snapshot$sv$get : 0) > item.id.clock && !Y.isDeleted(snapshot.ds, item.id);
425
+ };
426
+ const getUserColor = (colorMapping, colors, user) => {
427
+ if (!colorMapping.has(user)) {
428
+ if (colorMapping.size < colors.length) {
429
+ const usedColors = set.create();
430
+ colorMapping.forEach((color) => usedColors.add(color));
431
+ colors = colors.filter((color) => !usedColors.has(color));
432
+ }
433
+ colorMapping.set(user, random.oneOf(colors));
434
+ }
435
+ const color = colorMapping.get(user);
436
+ if (!color) throw new Error("At least one snapshot color is required");
437
+ return color;
438
+ };
439
+ const attrsEqual = (a, b) => {
440
+ if (a === b) return true;
441
+ const aKeys = Object.keys(a);
442
+ return aKeys.length === Object.keys(b).length && aKeys.every((k) => a[k] === b[k]);
443
+ };
444
+ const hasDistinctiveAttrs = (node) => {
445
+ const specAttrs = node.type.spec.attrs || {};
446
+ return Object.keys(node.attrs).some((key) => {
447
+ const spec = specAttrs[key];
448
+ return spec == null || !Object.prototype.hasOwnProperty.call(spec, "default") || spec.default !== node.attrs[key];
449
+ });
450
+ };
451
+ /** Recovers a position in a moved block, returning null when the match is ambiguous. */
452
+ const findAbsolutePositionAfterStructuralChange = (oldDoc, newDoc, absPos) => {
453
+ let pos = 0;
454
+ let targetIdx = 0;
455
+ for (; targetIdx < oldDoc.childCount; targetIdx++) {
456
+ const child = oldDoc.child(targetIdx);
457
+ if (pos + child.nodeSize > absPos) break;
458
+ pos += child.nodeSize;
459
+ }
460
+ if (targetIdx >= oldDoc.childCount) return null;
461
+ const targetChild = oldDoc.child(targetIdx);
462
+ const $oldPos = oldDoc.resolve(absPos);
463
+ const place = (newBlockStart, newBlock) => {
464
+ if ($oldPos.depth === 0) {
465
+ const remapped = newBlockStart + (absPos - pos);
466
+ const contentStart = newBlockStart + 1;
467
+ const contentEnd = newBlockStart + newBlock.nodeSize - 1;
468
+ return Math.max(contentStart, Math.min(remapped, contentEnd));
469
+ }
470
+ if ($oldPos.depth > 1) {
471
+ const innerPosition = findAbsolutePositionAfterStructuralChange($oldPos.node(1), newBlock, $oldPos.pos - $oldPos.start(1));
472
+ return innerPosition === null ? null : newBlockStart + 1 + innerPosition;
473
+ }
474
+ if (!newBlock.isTextblock) return null;
475
+ return newBlockStart + 1 + Math.min($oldPos.parentOffset, newBlock.content.size);
476
+ };
477
+ const findByPredicate = (pred, requireUnique = false) => {
478
+ let occurrence = 0;
479
+ for (let i = 0; i <= targetIdx; i++) if (pred(oldDoc.child(i))) occurrence++;
480
+ let matchCount = 0;
481
+ let matchStart = -1;
482
+ let matchBlock = null;
483
+ let newPos = 0;
484
+ for (let i = 0; i < newDoc.childCount; i++) {
485
+ const child = newDoc.child(i);
486
+ if (pred(child)) {
487
+ matchCount++;
488
+ if (matchCount === occurrence) {
489
+ matchStart = newPos;
490
+ matchBlock = child;
491
+ }
492
+ }
493
+ newPos += child.nodeSize;
494
+ }
495
+ if (matchBlock === null || requireUnique && (occurrence !== 1 || matchCount !== 1)) return null;
496
+ return place(matchStart, matchBlock);
497
+ };
498
+ const sameTypeAndAttrs = (child) => child.type === targetChild.type && attrsEqual(child.attrs, targetChild.attrs);
499
+ const oldText = targetChild.textContent;
500
+ const byAll = findByPredicate((child) => sameTypeAndAttrs(child) && child.textContent === oldText);
501
+ if (byAll !== null) return byAll;
502
+ const byText = findByPredicate((child) => child.type === targetChild.type && child.textContent === oldText);
503
+ if (byText !== null) return byText;
504
+ if (!targetChild.isTextblock || hasDistinctiveAttrs(targetChild)) {
505
+ const byAttrs = findByPredicate(sameTypeAndAttrs, true);
506
+ if (byAttrs !== null) return byAttrs;
507
+ }
508
+ return findByPredicate((child) => sameTypeAndAttrs(child) && oldText !== "" && child.textContent !== "" && (oldText.startsWith(child.textContent) || child.textContent.startsWith(oldText)), true);
509
+ };
510
+ /** Detects a position that moved into a different block. */
511
+ const isMisresolvedAfterStructuralChange = (oldDoc, newDoc, oldAbs, resolvedAbs) => {
512
+ if (resolvedAbs === null) return false;
513
+ const $old = oldDoc.resolve(oldAbs);
514
+ const $new = newDoc.resolve(resolvedAbs);
515
+ if (!$old.parent.isTextblock) return false;
516
+ if (!$new.parent.isTextblock) return true;
517
+ if ($old.parent.textContent !== $new.parent.textContent) return true;
518
+ if ($old.parentOffset !== 0 && $new.parentOffset === 0) return true;
519
+ const bothAtStart = $old.parentOffset === 0 && $new.parentOffset === 0;
520
+ const suspicious = $old.parentOffset !== $new.parentOffset || $old.parent.type !== $new.parent.type || !attrsEqual($old.parent.attrs, $new.parent.attrs);
521
+ if (bothAtStart || suspicious) {
522
+ const expected = findAbsolutePositionAfterStructuralChange(oldDoc, newDoc, oldAbs);
523
+ return expected !== null && expected !== resolvedAbs;
524
+ }
525
+ return false;
526
+ };
527
+ const recoverSelectionEndpoint = (newDoc, oldDoc, oldAbs, resolved) => {
528
+ if (oldAbs == null || oldAbs < 0 || oldAbs > oldDoc.content.size) return resolved;
529
+ if (!(resolved === null || oldAbs > 1 && resolved <= 1 || isMisresolvedAfterStructuralChange(oldDoc, newDoc, oldAbs, resolved))) return resolved;
530
+ const recovered = findAbsolutePositionAfterStructuralChange(oldDoc, newDoc, oldAbs);
531
+ return recovered !== null ? recovered : resolved;
532
+ };
533
+ const restoreRelativeSelection = (tr, relSel, binding, oldDoc) => {
534
+ if (relSel !== null && relSel.anchor !== null && relSel.head !== null) {
535
+ if (relSel.type === "all") tr.setSelection(new AllSelection(tr.doc));
536
+ else if (relSel.type === "node") {
537
+ const anchor = relativePositionToAbsolutePosition(binding.doc, binding.type, relSel.anchor, binding.mapping);
538
+ if (anchor !== null) tr.setSelection(createSafeNodeSelection(tr, anchor));
539
+ } else if (relSel.type === "nodeRange") {
540
+ const anchor = relativePositionToAbsolutePosition(binding.doc, binding.type, relSel.anchor, binding.mapping);
541
+ const head = relativePositionToAbsolutePosition(binding.doc, binding.type, relSel.head, binding.mapping);
542
+ const selection = createSafeNodeRangeSelection(tr, anchor, head, relSel.depth);
543
+ if (selection !== null) tr.setSelection(selection);
544
+ } else {
545
+ let anchor = relativePositionToAbsolutePosition(binding.doc, binding.type, relSel.anchor, binding.mapping);
546
+ let head = relativePositionToAbsolutePosition(binding.doc, binding.type, relSel.head, binding.mapping);
547
+ if (oldDoc != null) {
548
+ anchor = recoverSelectionEndpoint(tr.doc, oldDoc, relSel.absAnchor, anchor);
549
+ head = recoverSelectionEndpoint(tr.doc, oldDoc, relSel.absHead, head);
550
+ }
551
+ if (anchor === null) anchor = head;
552
+ if (head === null) head = anchor;
553
+ if (anchor !== null && head !== null) tr.setSelection(TextSelection.between(tr.doc.resolve(anchor), tr.doc.resolve(head)));
554
+ }
555
+ }
556
+ };
557
+ const createSafeNodeSelection = (tr, pos) => {
558
+ const $pos = tr.doc.resolve(pos);
559
+ if ($pos.nodeAfter) return NodeSelection.create(tr.doc, pos);
560
+ else return TextSelection.near($pos);
561
+ };
562
+ const createSafeNodeRangeSelection = (tr, anchor, head, depth) => {
563
+ if (anchor === null || head === null) return null;
564
+ const clampedAnchor = Math.min(Math.max(anchor, 0), tr.doc.content.size);
565
+ const clampedHead = Math.min(Math.max(head, 0), tr.doc.content.size);
566
+ try {
567
+ const selection = Selection.fromJSON(tr.doc, {
568
+ type: "nodeRange",
569
+ anchor: clampedAnchor,
570
+ head: clampedHead,
571
+ depth
572
+ });
573
+ if (!selection.ranges.length) return TextSelection.near(tr.doc.resolve(clampedAnchor));
574
+ return selection;
575
+ } catch {
576
+ return TextSelection.near(tr.doc.resolve(clampedAnchor));
577
+ }
578
+ };
579
+ /** Captures the current selection as Yjs relative positions and absolute fallback positions. */
580
+ const getRelativeSelection = (pmbinding, state) => {
581
+ const selection = state.selection;
582
+ const json = selection.toJSON();
583
+ const type = typeof json.type === "string" ? json.type : "text";
584
+ return {
585
+ type,
586
+ depth: type === "nodeRange" && "depth" in selection && typeof selection.depth === "number" ? selection.depth : void 0,
587
+ anchor: absolutePositionToRelativePosition(state.selection.anchor, pmbinding.type, pmbinding.mapping),
588
+ head: absolutePositionToRelativePosition(state.selection.head, pmbinding.type, pmbinding.mapping),
589
+ absAnchor: state.selection.anchor,
590
+ absHead: state.selection.head
591
+ };
592
+ };
593
+ const projectedMappings = /* @__PURE__ */ new WeakMap();
594
+ const deleteMapping = (mapping, type) => {
595
+ var _projectedMappings$ge;
596
+ if (!(type instanceof Y.XmlFragment || type instanceof Y.Text || type instanceof Y.XmlHook)) return;
597
+ mapping.delete(type);
598
+ (_projectedMappings$ge = projectedMappings.get(mapping)) === null || _projectedMappings$ge === void 0 || _projectedMappings$ge.delete(type);
599
+ };
600
+ const getContentSnapshot = (type, snapshot, prevSnapshot) => {
601
+ if (snapshot === void 0 || prevSnapshot === void 0 || type._item === null) return snapshot;
602
+ if (isVisible(type._item, snapshot)) return snapshot;
603
+ return isVisible(type._item, prevSnapshot) ? prevSnapshot : void 0;
604
+ };
605
+ const getRemovedTextDeltas = (text, snapshot, computeYChange) => {
606
+ const formatted = text.toDelta(snapshot);
607
+ if (formatted.some((delta) => typeof delta.insert !== "string")) return formatted;
608
+ const removed = text.toDelta(Y.emptySnapshot, snapshot, computeYChange);
609
+ const deltas = [];
610
+ let removedIndex = 0;
611
+ let removedOffset = 0;
612
+ for (const delta of formatted) {
613
+ let offset = 0;
614
+ while (offset < delta.insert.length) {
615
+ var _removal$attributes$y, _removal$attributes;
616
+ const removal = removed[removedIndex];
617
+ const length = Math.min(delta.insert.length - offset, removal.insert.length - removedOffset);
618
+ deltas.push({
619
+ insert: delta.insert.slice(offset, offset + length),
620
+ attributes: {
621
+ ...delta.attributes,
622
+ ychange: (_removal$attributes$y = (_removal$attributes = removal.attributes) === null || _removal$attributes === void 0 ? void 0 : _removal$attributes.ychange) !== null && _removal$attributes$y !== void 0 ? _removal$attributes$y : { type: "removed" }
623
+ }
624
+ });
625
+ offset += length;
626
+ removedOffset += length;
627
+ if (removedOffset === removal.insert.length) {
628
+ removedIndex += 1;
629
+ removedOffset = 0;
630
+ }
631
+ }
632
+ }
633
+ return deltas;
634
+ };
635
+ const hashedMarkNameRegex = /(.*)(--[a-zA-Z0-9+/=]{8})$/;
636
+ const yattr2markname = (attrName) => {
637
+ var _hashedMarkNameRegex$, _hashedMarkNameRegex$2;
638
+ return (_hashedMarkNameRegex$ = (_hashedMarkNameRegex$2 = hashedMarkNameRegex.exec(attrName)) === null || _hashedMarkNameRegex$2 === void 0 ? void 0 : _hashedMarkNameRegex$2[1]) !== null && _hashedMarkNameRegex$ !== void 0 ? _hashedMarkNameRegex$ : attrName;
639
+ };
640
+ const attributesToMarks = (attrs, schema) => {
641
+ const marks = [];
642
+ for (const markName in attrs) marks.push(schema.mark(yattr2markname(markName), attrs[markName]));
643
+ return marks;
644
+ };
645
+ /** Deletes shared content that the editor schema cannot display. */
646
+ const deleteYType = (type) => {
647
+ const doc = type.doc;
648
+ const item = type._item;
649
+ if (!doc || !item) throw error.unexpectedCase();
650
+ doc.transact((transaction) => {
651
+ item.delete(transaction);
652
+ }, ySyncPluginKey);
653
+ };
654
+ /** Wraps a thrown value in an `Error`. */
655
+ const toError = (value) => value instanceof Error ? value : new Error(String(value));
656
+ const createTextNodesFromYText = (text, schema, meta, snapshot, prevSnapshot, computeYChange) => {
657
+ const contentSnapshot = getContentSnapshot(text, snapshot, prevSnapshot);
658
+ const deltas = contentSnapshot !== snapshot && contentSnapshot !== void 0 ? getRemovedTextDeltas(text, contentSnapshot, computeYChange) : text.toDelta(snapshot, prevSnapshot, computeYChange);
659
+ try {
660
+ return deltas.map((delta) => {
661
+ if (typeof delta.insert !== "string") throw new Error("Cannot project a Yjs text embed");
662
+ return schema.text(delta.insert, attributesToMarks(delta.attributes, schema));
663
+ });
664
+ } catch (error) {
665
+ if (meta.reportInvalidContent) meta.reportInvalidContent(toError(error));
666
+ else deleteYType(text);
667
+ return null;
668
+ }
669
+ };
670
+ /** Moves the content of a following text type into this one to avoid duplicated characters. */
671
+ const mergeNextYText = (text) => {
672
+ var _text$_item;
673
+ const content = (_text$_item = text._item) === null || _text$_item === void 0 || (_text$_item = _text$_item.right) === null || _text$_item === void 0 ? void 0 : _text$_item.content;
674
+ const nextText = content instanceof Y.ContentType ? content.type : null;
675
+ if (!(nextText instanceof Y.Text)) return;
676
+ const nextItem = nextText._item;
677
+ const nextDoc = nextText.doc;
678
+ if (!nextItem || !nextDoc || nextItem.deleted || nextItem.id.client !== nextDoc.clientID) return;
679
+ text.applyDelta([{ retain: text.length }, ...nextText.toDelta()]);
680
+ nextDoc.transact((transaction) => {
681
+ nextItem.delete(transaction);
682
+ });
683
+ };
684
+ const isAbsentFromSnapshots = (type, snapshot, prevSnapshot) => snapshot !== void 0 && prevSnapshot !== void 0 && type._item !== null && !isVisible(type._item, snapshot) && !isVisible(type._item, prevSnapshot);
685
+ const getSnapshotChildren = (el, snapshot, prevSnapshot, contentSnapshot) => {
686
+ if (snapshot === void 0 || prevSnapshot === void 0) return el.toArray();
687
+ if (contentSnapshot !== snapshot) return contentSnapshot === void 0 ? el.toArray() : Y.typeListToArraySnapshot(el, contentSnapshot);
688
+ return Y.typeListToArraySnapshot(el, new Y.Snapshot(prevSnapshot.ds, snapshot.sv));
689
+ };
690
+ const getYChange = (el, snapshot, prevSnapshot, computeYChange) => {
691
+ if (!el._item) return void 0;
692
+ if (!isVisible(el._item, snapshot)) return computeYChange ? computeYChange("removed", el._item.id) : { type: "removed" };
693
+ if (!isVisible(el._item, prevSnapshot)) return computeYChange ? computeYChange("added", el._item.id) : { type: "added" };
694
+ };
695
+ const setProjectedNode = (meta, el, node) => {
696
+ meta.mapping.set(el, node);
697
+ let projectedNodes = projectedMappings.get(meta.mapping);
698
+ if (projectedNodes === void 0) {
699
+ projectedNodes = /* @__PURE__ */ new WeakMap();
700
+ projectedMappings.set(meta.mapping, projectedNodes);
701
+ }
702
+ projectedNodes.set(el, node);
703
+ };
704
+ const createNodeFromYElement = (el, schema, meta, snapshot, prevSnapshot, computeYChange) => {
705
+ var _projectedMappings$ge;
706
+ const cachedNode = meta.mapping.get(el);
707
+ const cachedSingleNode = Array.isArray(cachedNode) ? void 0 : cachedNode;
708
+ if (cachedSingleNode !== void 0 && ((_projectedMappings$ge = projectedMappings.get(meta.mapping)) === null || _projectedMappings$ge === void 0 ? void 0 : _projectedMappings$ge.get(el)) === cachedSingleNode) return cachedSingleNode;
709
+ const contentSnapshot = getContentSnapshot(el, snapshot, prevSnapshot);
710
+ const children = [];
711
+ let hasSkippedChild = false;
712
+ const createChildren = (type) => {
713
+ if (isAbsentFromSnapshots(type, snapshot, prevSnapshot)) return;
714
+ if (type instanceof Y.XmlElement) {
715
+ const node = createNodeFromYElement(type, schema, meta, snapshot, prevSnapshot, computeYChange);
716
+ if (node === null || meta.mapping.get(type) !== node) hasSkippedChild = true;
717
+ if (node !== null) children.push(node);
718
+ return;
719
+ }
720
+ if (!(type instanceof Y.XmlText)) return;
721
+ if (meta.deferTextMerge) meta.deferTextMerge(type);
722
+ else mergeNextYText(type);
723
+ const textNodes = createTextNodesFromYText(type, schema, meta, snapshot, prevSnapshot, computeYChange);
724
+ if (textNodes === null) hasSkippedChild = true;
725
+ textNodes === null || textNodes === void 0 || textNodes.forEach((textNode) => children.push(textNode));
726
+ };
727
+ getSnapshotChildren(el, snapshot, prevSnapshot, contentSnapshot).forEach(createChildren);
728
+ try {
729
+ const attrs = el.getAttributes(contentSnapshot);
730
+ const ychange = snapshot ? getYChange(el, snapshot, prevSnapshot, computeYChange) : void 0;
731
+ if (ychange !== void 0) attrs.ychange = ychange;
732
+ let node = schema.node(el.nodeName, attrs, children);
733
+ if (cachedSingleNode === null || cachedSingleNode === void 0 ? void 0 : cachedSingleNode.eq(node)) node = cachedSingleNode;
734
+ if (hasSkippedChild && meta.reportInvalidContent) {
735
+ deleteMapping(meta.mapping, el);
736
+ return node;
737
+ }
738
+ setProjectedNode(meta, el, node);
739
+ return node;
740
+ } catch (error) {
741
+ deleteMapping(meta.mapping, el);
742
+ if (meta.reportInvalidContent) {
743
+ meta.reportInvalidContent(toError(error));
744
+ return null;
745
+ }
746
+ deleteYType(el);
747
+ return null;
748
+ }
749
+ };
750
+ const foldDigest = (digest) => {
751
+ const hashBytes = 6;
752
+ for (let i = hashBytes; i < digest.length; i++) digest[i % hashBytes] = digest[i % hashBytes] ^ digest[i];
753
+ return digest.slice(0, hashBytes);
754
+ };
755
+ const hashOfJSON = (json) => buf.toBase64(foldDigest(sha256.digest(buf.encodeAny(json))));
756
+ const marksToAttributes = (marks, meta) => {
757
+ const pattrs = {};
758
+ marks.forEach((mark) => {
759
+ if (mark.type.name !== "ychange") {
760
+ const isOverlapping = map.setIfUndefined(meta.isOMark, mark.type, () => !mark.type.excludes(mark.type));
761
+ pattrs[isOverlapping ? `${mark.type.name}--${hashOfJSON(mark.toJSON())}` : mark.type.name] = mark.attrs;
762
+ }
763
+ });
764
+ return pattrs;
765
+ };
766
+ const createTypeFromTextNodes = (nodes, meta) => {
767
+ const type = new Y.XmlText();
768
+ const delta = nodes.map((node) => {
769
+ var _node$text;
770
+ return {
771
+ insert: (_node$text = node.text) !== null && _node$text !== void 0 ? _node$text : "",
772
+ attributes: marksToAttributes(node.marks, meta)
773
+ };
774
+ });
775
+ type.applyDelta(delta);
776
+ meta.mapping.set(type, nodes);
777
+ return type;
778
+ };
779
+ const normalizePNodeContent = (pnode) => {
780
+ const c = pnode.content.content;
781
+ const res = [];
782
+ for (let i = 0; i < c.length; i++) {
783
+ const n = c[i];
784
+ if (n.isText) {
785
+ const textNodes = [];
786
+ for (let tnode = c[i]; i < c.length && tnode.isText; tnode = c[++i]) textNodes.push(tnode);
787
+ i--;
788
+ res.push(textNodes);
789
+ } else res.push(n);
790
+ }
791
+ return res;
792
+ };
793
+ const createTypeFromTextOrElementNode = (node, meta) => node instanceof Array ? createTypeFromTextNodes(node, meta) : createTypeFromElementNode(node, meta);
794
+ const createTypeFromElementNode = (node, meta) => {
795
+ const type = new Y.XmlElement(node.type.name);
796
+ for (const key in node.attrs) {
797
+ const val = node.attrs[key];
798
+ if (val !== null && key !== "ychange") type.setAttribute(key, val);
799
+ }
800
+ type.insert(0, normalizePNodeContent(node).map((n) => createTypeFromTextOrElementNode(n, meta)));
801
+ meta.mapping.set(type, node);
802
+ return type;
803
+ };
804
+ const isObject = (val) => typeof val === "object" && val !== null;
805
+ const equalAttrs = (pattrs, yattrs) => {
806
+ const keys = Object.keys(pattrs).filter((key) => pattrs[key] !== null);
807
+ let eq = keys.length === Object.keys(yattrs).filter((key) => yattrs[key] !== null).length;
808
+ for (let i = 0; i < keys.length && eq; i++) {
809
+ const key = keys[i];
810
+ const l = pattrs[key];
811
+ const r = yattrs[key];
812
+ eq = key === "ychange" || l === r || isObject(l) && isObject(r) && equalAttrs(l, r);
813
+ }
814
+ return eq;
815
+ };
816
+ const equalYTextPText = (ytext, ptexts) => {
817
+ const delta = ytext.toDelta();
818
+ return delta.length === ptexts.length && delta.every((d, i) => {
819
+ var _d$attributes;
820
+ return d.insert === ptexts[i].text && object.keys(d.attributes || {}).length === ptexts[i].marks.length && Object.entries((_d$attributes = d.attributes) !== null && _d$attributes !== void 0 ? _d$attributes : {}).every(([yattrname, attr]) => {
821
+ const markname = yattr2markname(yattrname);
822
+ const pmark = ptexts[i].marks.find((mark) => mark.type.name === markname);
823
+ if (!pmark) return false;
824
+ return equalAttrs(attr, pmark.attrs);
825
+ });
826
+ });
827
+ };
828
+ const mappedIdentity = (mapped, pcontent) => mapped === pcontent || mapped instanceof Array && pcontent instanceof Array && mapped.length === pcontent.length && mapped.every((a, i) => pcontent[i] === a);
829
+ const matchNodeName = (yElement, pNode) => !(pNode instanceof Array) && yElement.nodeName === pNode.type.name;
830
+ const equalYTypePNode = (ytype, pnode, mapping) => {
831
+ if (ytype instanceof Y.XmlElement && !(pnode instanceof Array) && matchNodeName(ytype, pnode)) {
832
+ const normalizedContent = normalizePNodeContent(pnode);
833
+ return ytype._length === normalizedContent.length && equalAttrs(ytype.getAttributes(), pnode.attrs) && ytype.toArray().every((ychild, index) => mappedIdentity(mapping === null || mapping === void 0 ? void 0 : mapping.get(ychild), normalizedContent[index]) || equalYTypePNode(ychild, normalizedContent[index], mapping));
834
+ }
835
+ return ytype instanceof Y.XmlText && pnode instanceof Array && equalYTextPText(ytype, pnode);
836
+ };
837
+ const findMappedChildAnchors = (yChildren, pChildren, meta) => {
838
+ const pChildIndices = /* @__PURE__ */ new Map();
839
+ pChildren.forEach((pChild, index) => {
840
+ if (!pChildIndices.has(pChild)) pChildIndices.set(pChild, index);
841
+ });
842
+ const candidates = [];
843
+ yChildren.forEach((yChild, yIndex) => {
844
+ const mapped = meta.mapping.get(yChild);
845
+ const pIndex = mapped === void 0 ? void 0 : pChildIndices.get(mapped);
846
+ if (pIndex !== void 0 && mappedIdentity(mapped, pChildren[pIndex])) candidates.push({
847
+ yIndex,
848
+ pIndex,
849
+ yChild
850
+ });
851
+ });
852
+ if (candidates.length === 0) return [];
853
+ const predecessors = [];
854
+ const tails = [];
855
+ for (let index = 0; index < candidates.length; index++) {
856
+ let low = 0;
857
+ let high = tails.length;
858
+ while (low < high) {
859
+ const middle = low + high >> 1;
860
+ if (candidates[tails[middle]].pIndex < candidates[index].pIndex) low = middle + 1;
861
+ else high = middle;
862
+ }
863
+ predecessors[index] = low > 0 ? tails[low - 1] : -1;
864
+ tails[low] = index;
865
+ }
866
+ const anchors = [];
867
+ for (let index = tails[tails.length - 1]; index !== -1; index = predecessors[index]) anchors.push(candidates[index]);
868
+ return anchors.reverse();
869
+ };
870
+ const ytextTrans = (ytext) => {
871
+ let str = "";
872
+ let n = ytext._start;
873
+ const nAttrs = {};
874
+ while (n !== null) {
875
+ if (!n.deleted) {
876
+ if (n.countable && n.content instanceof Y.ContentString) str += n.content.str;
877
+ else if (n.content instanceof Y.ContentFormat) nAttrs[n.content.key] = null;
878
+ }
879
+ n = n.right;
880
+ }
881
+ return {
882
+ str,
883
+ nAttrs
884
+ };
885
+ };
886
+ const updateYText = (ytext, ptexts, meta) => {
887
+ meta.mapping.set(ytext, ptexts);
888
+ const { nAttrs, str } = ytextTrans(ytext);
889
+ const content = ptexts.map((p) => {
890
+ var _p$text;
891
+ return {
892
+ insert: (_p$text = p.text) !== null && _p$text !== void 0 ? _p$text : "",
893
+ attributes: Object.assign({}, nAttrs, marksToAttributes(p.marks, meta))
894
+ };
895
+ });
896
+ const { insert, remove, index } = simpleDiff(str, content.map((c) => c.insert).join(""));
897
+ ytext.delete(index, remove);
898
+ ytext.insert(index, insert);
899
+ ytext.applyDelta(content.map((c) => ({
900
+ retain: c.insert.length,
901
+ attributes: c.attributes
902
+ })));
903
+ };
904
+ const updateMatchingYChild = (y, yChild, pChild, meta, updateFragment) => {
905
+ if (yChild instanceof Y.XmlText && pChild instanceof Array) {
906
+ if (equalYTextPText(yChild, pChild)) meta.mapping.set(yChild, pChild);
907
+ else updateYText(yChild, pChild, meta);
908
+ return true;
909
+ }
910
+ if (yChild instanceof Y.XmlElement && !(pChild instanceof Array) && matchNodeName(yChild, pChild)) {
911
+ if (equalYTypePNode(yChild, pChild, meta.mapping)) meta.mapping.set(yChild, pChild);
912
+ else updateFragment(y, yChild, pChild, meta);
913
+ return true;
914
+ }
915
+ return false;
916
+ };
917
+ const deleteYChildren = (yDomFragment, index, length, meta) => {
918
+ if (length > 0) {
919
+ yDomFragment.slice(index, index + length).forEach((type) => deleteMapping(meta.mapping, type));
920
+ yDomFragment.delete(index, length);
921
+ }
922
+ };
923
+ const insertPChildren = (yDomFragment, index, pChildren, start, end, meta) => {
924
+ if (start < end) {
925
+ const children = [];
926
+ for (let childIndex = start; childIndex < end; childIndex++) children.push(createTypeFromTextOrElementNode(pChildren[childIndex], meta));
927
+ yDomFragment.insert(index, children);
928
+ }
929
+ };
930
+ const reconcileUnanchoredChildren = (y, yDomFragment, pChildren, yChildren, yStart, yEnd, pStart, pEnd, meta, updateFragment) => {
931
+ const matchingChildren = math.min(yEnd - yStart, pEnd - pStart);
932
+ for (let index = 0; index < matchingChildren; index++) {
933
+ const yChild = yChildren[yStart + index];
934
+ const pChild = pChildren[pStart + index];
935
+ if (!updateMatchingYChild(y, yChild, pChild, meta, updateFragment)) {
936
+ deleteYChildren(yDomFragment, pStart + index, 1, meta);
937
+ insertPChildren(yDomFragment, pStart + index, pChildren, pStart + index, pStart + index + 1, meta);
938
+ }
939
+ }
940
+ deleteYChildren(yDomFragment, pStart + matchingChildren, yEnd - yStart - matchingChildren, meta);
941
+ insertPChildren(yDomFragment, pStart + matchingChildren, pChildren, pStart + matchingChildren, pEnd, meta);
942
+ };
943
+ const reconcileMappedChildren = (y, yDomFragment, pChildren, yChildren, meta, updateFragment) => {
944
+ const anchors = findMappedChildAnchors(yChildren, pChildren, meta);
945
+ if (anchors.length < 2 || !anchors.some((anchor) => anchor.yIndex !== anchor.pIndex) || anchors.some((anchor) => {
946
+ const pChild = pChildren[anchor.pIndex];
947
+ return !(anchor.yChild instanceof Y.XmlText && pChild instanceof Array || anchor.yChild instanceof Y.XmlElement && !(pChild instanceof Array));
948
+ })) return false;
949
+ let yIndex = 0;
950
+ let pIndex = 0;
951
+ for (const anchor of anchors) {
952
+ reconcileUnanchoredChildren(y, yDomFragment, pChildren, yChildren, yIndex, anchor.yIndex, pIndex, anchor.pIndex, meta, updateFragment);
953
+ const pChild = pChildren[anchor.pIndex];
954
+ updateMatchingYChild(y, anchor.yChild, pChild, meta, updateFragment);
955
+ yIndex = anchor.yIndex + 1;
956
+ pIndex = anchor.pIndex + 1;
957
+ }
958
+ reconcileUnanchoredChildren(y, yDomFragment, pChildren, yChildren, yIndex, yChildren.length, pIndex, pChildren.length, meta, updateFragment);
959
+ return true;
960
+ };
961
+ const computeChildEqualityFactor = (ytype, pnode, meta) => {
962
+ const yChildren = ytype.toArray();
963
+ const pChildren = normalizePNodeContent(pnode);
964
+ const pChildCnt = pChildren.length;
965
+ const yChildCnt = yChildren.length;
966
+ const minCnt = math.min(yChildCnt, pChildCnt);
967
+ let left = 0;
968
+ let right = 0;
969
+ let foundMappedChild = false;
970
+ for (; left < minCnt; left++) {
971
+ const leftY = yChildren[left];
972
+ const leftP = pChildren[left];
973
+ if (mappedIdentity(meta.mapping.get(leftY), leftP)) foundMappedChild = true;
974
+ else if (!equalYTypePNode(leftY, leftP, meta.mapping)) break;
975
+ }
976
+ for (; left + right < minCnt; right++) {
977
+ const rightY = yChildren[yChildCnt - right - 1];
978
+ const rightP = pChildren[pChildCnt - right - 1];
979
+ if (mappedIdentity(meta.mapping.get(rightY), rightP)) foundMappedChild = true;
980
+ else if (!equalYTypePNode(rightY, rightP, meta.mapping)) break;
981
+ }
982
+ return {
983
+ equalityFactor: left + right,
984
+ foundMappedChild
985
+ };
986
+ };
987
+ /** Updates a Yjs XML fragment to match a ProseMirror node while preserving mapped children. */
988
+ const updateYFragment = (y, yDomFragment, pNode, meta) => {
989
+ if (yDomFragment instanceof Y.XmlElement && yDomFragment.nodeName !== pNode.type.name) throw new Error("node name mismatch!");
990
+ meta.mapping.set(yDomFragment, pNode);
991
+ if (yDomFragment instanceof Y.XmlElement) {
992
+ const yDomAttrs = yDomFragment.getAttributes();
993
+ const pAttrs = pNode.attrs;
994
+ for (const key in pAttrs) {
995
+ if (pAttrs[key] === null) {
996
+ yDomFragment.removeAttribute(key);
997
+ continue;
998
+ }
999
+ if (yDomAttrs[key] !== pAttrs[key] && key !== "ychange") yDomFragment.setAttribute(key, pAttrs[key]);
1000
+ }
1001
+ for (const key in yDomAttrs) if (pAttrs[key] === void 0) yDomFragment.removeAttribute(key);
1002
+ }
1003
+ const pChildren = normalizePNodeContent(pNode);
1004
+ const pChildCnt = pChildren.length;
1005
+ const yChildren = yDomFragment.toArray();
1006
+ const yChildCnt = yChildren.length;
1007
+ const minCnt = math.min(pChildCnt, yChildCnt);
1008
+ let reconciled = false;
1009
+ y.transact(() => {
1010
+ reconciled = reconcileMappedChildren(y, yDomFragment, pChildren, yChildren, meta, updateYFragment);
1011
+ }, ySyncPluginKey);
1012
+ if (reconciled) return;
1013
+ let left = 0;
1014
+ let right = 0;
1015
+ for (; left < minCnt; left++) {
1016
+ const leftY = yChildren[left];
1017
+ const leftP = pChildren[left];
1018
+ if (mappedIdentity(meta.mapping.get(leftY), leftP)) continue;
1019
+ if (!equalYTypePNode(leftY, leftP, meta.mapping)) break;
1020
+ meta.mapping.set(leftY, leftP);
1021
+ }
1022
+ for (; right + left + 1 < minCnt; right++) {
1023
+ const rightY = yChildren[yChildCnt - right - 1];
1024
+ const rightP = pChildren[pChildCnt - right - 1];
1025
+ if (mappedIdentity(meta.mapping.get(rightY), rightP)) continue;
1026
+ if (!equalYTypePNode(rightY, rightP, meta.mapping)) break;
1027
+ meta.mapping.set(rightY, rightP);
1028
+ }
1029
+ y.transact(() => {
1030
+ while (yChildCnt - left - right > 0 && pChildCnt - left - right > 0) {
1031
+ const leftY = yChildren[left];
1032
+ const leftP = pChildren[left];
1033
+ const rightY = yChildren[yChildCnt - right - 1];
1034
+ const rightP = pChildren[pChildCnt - right - 1];
1035
+ if (leftY instanceof Y.XmlText && leftP instanceof Array) {
1036
+ if (!equalYTextPText(leftY, leftP)) updateYText(leftY, leftP, meta);
1037
+ left += 1;
1038
+ continue;
1039
+ }
1040
+ let updateLeft = leftY instanceof Y.XmlElement && matchNodeName(leftY, leftP);
1041
+ let updateRight = rightY instanceof Y.XmlElement && matchNodeName(rightY, rightP);
1042
+ if (updateLeft && updateRight && leftY instanceof Y.XmlElement && rightY instanceof Y.XmlElement && !Array.isArray(leftP) && !Array.isArray(rightP)) {
1043
+ const equalityLeft = computeChildEqualityFactor(leftY, leftP, meta);
1044
+ const equalityRight = computeChildEqualityFactor(rightY, rightP, meta);
1045
+ if (equalityLeft.foundMappedChild && !equalityRight.foundMappedChild) updateRight = false;
1046
+ else if (!equalityLeft.foundMappedChild && equalityRight.foundMappedChild) updateLeft = false;
1047
+ else if (equalityLeft.equalityFactor < equalityRight.equalityFactor) updateLeft = false;
1048
+ else updateRight = false;
1049
+ }
1050
+ if (updateLeft && leftY instanceof Y.XmlElement && !Array.isArray(leftP)) {
1051
+ updateYFragment(y, leftY, leftP, meta);
1052
+ left += 1;
1053
+ continue;
1054
+ }
1055
+ if (updateRight && rightY instanceof Y.XmlElement && !Array.isArray(rightP)) {
1056
+ updateYFragment(y, rightY, rightP, meta);
1057
+ right += 1;
1058
+ continue;
1059
+ }
1060
+ deleteMapping(meta.mapping, yDomFragment.get(left));
1061
+ yDomFragment.delete(left, 1);
1062
+ yDomFragment.insert(left, [createTypeFromTextOrElementNode(leftP, meta)]);
1063
+ left += 1;
1064
+ }
1065
+ const yDelLen = yChildCnt - left - right;
1066
+ if (yChildCnt === 1 && pChildCnt === 0 && yChildren[0] instanceof Y.XmlText) {
1067
+ deleteMapping(meta.mapping, yChildren[0]);
1068
+ yChildren[0].delete(0, yChildren[0].length);
1069
+ } else if (yDelLen > 0) {
1070
+ yDomFragment.slice(left, left + yDelLen).forEach((type) => deleteMapping(meta.mapping, type));
1071
+ yDomFragment.delete(left, yDelLen);
1072
+ }
1073
+ if (left + right >= pChildCnt) return;
1074
+ const childrenToInsert = [];
1075
+ for (let index = left; index < pChildCnt - right; index++) childrenToInsert.push(createTypeFromTextOrElementNode(pChildren[index], meta));
1076
+ yDomFragment.insert(left, childrenToInsert);
1077
+ }, ySyncPluginKey);
1078
+ };
1079
+ const replaceChangedChildren = (tr, content) => {
1080
+ var _step$apply$doc;
1081
+ const oldContent = tr.doc.content;
1082
+ let start = 0;
1083
+ let from = 0;
1084
+ while (start < oldContent.childCount && start < content.childCount && oldContent.child(start) === content.child(start)) {
1085
+ from += oldContent.child(start).nodeSize;
1086
+ start++;
1087
+ }
1088
+ let oldEnd = oldContent.childCount;
1089
+ let newEnd = content.childCount;
1090
+ let suffixSize = 0;
1091
+ while (oldEnd > start && newEnd > start && oldContent.child(oldEnd - 1) === content.child(newEnd - 1)) {
1092
+ suffixSize += oldContent.child(oldEnd - 1).nodeSize;
1093
+ oldEnd--;
1094
+ newEnd--;
1095
+ }
1096
+ if (start === oldEnd && start === newEnd) return tr;
1097
+ const slice = new Slice(content.cut(from, content.size - suffixSize), 0, 0);
1098
+ const step = replaceStep(tr.doc, from, oldContent.size - suffixSize, slice);
1099
+ if (step !== null && ((_step$apply$doc = step.apply(tr.doc).doc) === null || _step$apply$doc === void 0 ? void 0 : _step$apply$doc.content.eq(content))) return tr.step(step);
1100
+ return tr.replace(0, oldContent.size, new Slice(content, 0, 0));
1101
+ };
1102
+ /** Synchronizes one integrated Yjs XML fragment with a ProseMirror editor view. */
1103
+ var ProsemirrorBinding = class {
1104
+ constructor(yXmlFragment, mapping = /* @__PURE__ */ new Map(), onInvalidContent) {
1105
+ this.prosemirrorView = null;
1106
+ this.mux = createMutex();
1107
+ this.isOMark = /* @__PURE__ */ new Map();
1108
+ this.beforeTransactionSelection = null;
1109
+ this._domSelectionInView = null;
1110
+ this._invalidContentError = null;
1111
+ this.projectionError = null;
1112
+ this.hasSharedContent = false;
1113
+ this.pendingTextMerges = [];
1114
+ this.type = yXmlFragment;
1115
+ this.mapping = mapping;
1116
+ this._observeFunction = this._typeChanged.bind(this);
1117
+ if (onInvalidContent) {
1118
+ this.onInvalidContent = onInvalidContent;
1119
+ this.reportInvalidContent = (error) => {
1120
+ var _this$projectionError;
1121
+ (_this$projectionError = this.projectionError) !== null && _this$projectionError !== void 0 || (this.projectionError = error);
1122
+ };
1123
+ this.deferTextMerge = (text) => {
1124
+ this.pendingTextMerges.push(text);
1125
+ };
1126
+ }
1127
+ if (yXmlFragment.doc === null) throw new Error("The Yjs fragment must belong to a document");
1128
+ this.doc = yXmlFragment.doc;
1129
+ this.beforeAllTransactions = () => {
1130
+ if (this._invalidContentError === null && this.beforeTransactionSelection === null && this.prosemirrorView != null) this.beforeTransactionSelection = getRelativeSelection(this, this.view.state);
1131
+ };
1132
+ this.afterAllTransactions = () => {
1133
+ this.beforeTransactionSelection = null;
1134
+ };
1135
+ }
1136
+ /**
1137
+ * Returns the schema error that pauses editing and shared writes.
1138
+ * Only set when the binding keeps invalid content.
1139
+ * @returns The error, or null when the shared content fits the editor schema.
1140
+ */
1141
+ get invalidContentError() {
1142
+ return this._invalidContentError;
1143
+ }
1144
+ get view() {
1145
+ if (!this.prosemirrorView) throw new Error("The binding has no editor view");
1146
+ return this.prosemirrorView;
1147
+ }
1148
+ get _tr() {
1149
+ return this.view.state.tr.setMeta("addToHistory", false);
1150
+ }
1151
+ _isLocalCursorInView() {
1152
+ if (!this.view.hasFocus()) return false;
1153
+ if (environment.isBrowser && this._domSelectionInView === null) {
1154
+ eventloop.timeout(0, () => {
1155
+ this._domSelectionInView = null;
1156
+ });
1157
+ this._domSelectionInView = this._isDomSelectionInView();
1158
+ }
1159
+ return this._domSelectionInView;
1160
+ }
1161
+ _isDomSelectionInView() {
1162
+ const root = this.view.root;
1163
+ const selection = "getSelection" in root && typeof root.getSelection === "function" ? root.getSelection() : this.view.dom.ownerDocument.getSelection();
1164
+ if (selection == null || selection.anchorNode == null || selection.focusNode == null) return false;
1165
+ const range = this.view.dom.ownerDocument.createRange();
1166
+ range.setStart(selection.anchorNode, selection.anchorOffset);
1167
+ range.setEnd(selection.focusNode, selection.focusOffset);
1168
+ if (range.getClientRects().length === 0) {
1169
+ if (range.startContainer && range.collapsed) range.selectNodeContents(range.startContainer);
1170
+ }
1171
+ const bounding = range.getBoundingClientRect();
1172
+ const documentElement = dom.doc.documentElement;
1173
+ return bounding.bottom >= 0 && bounding.right >= 0 && bounding.left <= (window.innerWidth || documentElement.clientWidth || 0) && bounding.top <= (window.innerHeight || documentElement.clientHeight || 0);
1174
+ }
1175
+ renderSnapshot(snapshot, prevSnapshot) {
1176
+ if (!prevSnapshot) prevSnapshot = Y.createSnapshot(Y.createDeleteSet(), /* @__PURE__ */ new Map());
1177
+ this.view.dispatch(this._tr.setMeta(ySyncPluginKey, {
1178
+ snapshot,
1179
+ prevSnapshot
1180
+ }));
1181
+ }
1182
+ createDocumentContent() {
1183
+ this.projectionError = null;
1184
+ this.pendingTextMerges = [];
1185
+ const fragmentContent = this.type.toArray().map((type) => {
1186
+ if (!(type instanceof Y.XmlElement)) throw error.methodUnimplemented();
1187
+ return createNodeFromYElement(type, this.view.state.schema, this);
1188
+ }).filter((node) => node !== null);
1189
+ const content = PModel.Fragment.from(fragmentContent);
1190
+ const { topNodeType } = this.view.state.schema;
1191
+ this.hasSharedContent || (this.hasSharedContent = this.type.length > 0);
1192
+ const isPlaceholder = content.childCount === 0 && !this.hasSharedContent;
1193
+ if (this.reportInvalidContent && !isPlaceholder && !topNodeType.validContent(content)) this.reportInvalidContent(/* @__PURE__ */ new RangeError("Shared content does not fit the document schema"));
1194
+ if (this.projectionError === null) this.pendingTextMerges.forEach(mergeNextYText);
1195
+ return content;
1196
+ }
1197
+ /** Returns the projection error only when the content just stopped fitting the schema. */
1198
+ updateInvalidContentError() {
1199
+ const error = this.projectionError;
1200
+ const isNewError = error !== null && this._invalidContentError === null;
1201
+ this._invalidContentError = error;
1202
+ return isNewError ? error : null;
1203
+ }
1204
+ notifyInvalidContent(error) {
1205
+ var _this$onInvalidConten;
1206
+ if (error) (_this$onInvalidConten = this.onInvalidContent) === null || _this$onInvalidConten === void 0 || _this$onInvalidConten.call(this, error);
1207
+ }
1208
+ createDocumentTransaction() {
1209
+ const content = this.createDocumentContent();
1210
+ return this._tr.replace(0, this.view.state.doc.content.size, new PModel.Slice(content, 0, 0));
1211
+ }
1212
+ unrenderSnapshot() {
1213
+ this.mapping.clear();
1214
+ projectedMappings.delete(this.mapping);
1215
+ let newError = null;
1216
+ this.mux(() => {
1217
+ const tr = this.createDocumentTransaction();
1218
+ newError = this.updateInvalidContentError();
1219
+ tr.setMeta(ySyncPluginKey, {
1220
+ snapshot: null,
1221
+ prevSnapshot: null
1222
+ });
1223
+ this.view.dispatch(tr);
1224
+ });
1225
+ this.notifyInvalidContent(newError);
1226
+ }
1227
+ _forceRerender() {
1228
+ this.mapping.clear();
1229
+ projectedMappings.delete(this.mapping);
1230
+ let newError = null;
1231
+ this.mux(() => {
1232
+ const sel = this.beforeTransactionSelection !== null ? null : this.view.state.selection;
1233
+ const tr = this.createDocumentTransaction();
1234
+ newError = this.updateInvalidContentError();
1235
+ if (sel) {
1236
+ const clampedAnchor = math.min(math.max(sel.anchor, 0), tr.doc.content.size);
1237
+ const clampedHead = math.min(math.max(sel.head, 0), tr.doc.content.size);
1238
+ tr.setSelection(TextSelection.create(tr.doc, clampedAnchor, clampedHead));
1239
+ }
1240
+ this.view.dispatch(tr.setMeta(ySyncPluginKey, {
1241
+ isChangeOrigin: true,
1242
+ binding: this
1243
+ }));
1244
+ });
1245
+ this.notifyInvalidContent(newError);
1246
+ }
1247
+ _renderSnapshot(snapshot, prevSnapshot, pluginState) {
1248
+ var _prevSnapshot;
1249
+ let historyDoc = this.doc;
1250
+ let historyType = this.type;
1251
+ if (!snapshot) snapshot = Y.snapshot(this.doc);
1252
+ if (snapshot instanceof Uint8Array || prevSnapshot instanceof Uint8Array) {
1253
+ if (!(snapshot instanceof Uint8Array) || !(prevSnapshot instanceof Uint8Array)) throw error.unexpectedCase();
1254
+ historyDoc = new Y.Doc({ gc: false });
1255
+ Y.applyUpdateV2(historyDoc, prevSnapshot);
1256
+ prevSnapshot = Y.snapshot(historyDoc);
1257
+ Y.applyUpdateV2(historyDoc, snapshot);
1258
+ snapshot = Y.snapshot(historyDoc);
1259
+ if (historyType._item === null) {
1260
+ const rootKey = Array.from(this.doc.share.keys()).find((key) => Object.is(this.doc.share.get(key), historyType));
1261
+ historyType = historyDoc.getXmlFragment(rootKey);
1262
+ } else {
1263
+ var _historyDoc$store$cli;
1264
+ const historyStructs = (_historyDoc$store$cli = historyDoc.store.clients.get(historyType._item.id.client)) !== null && _historyDoc$store$cli !== void 0 ? _historyDoc$store$cli : [];
1265
+ const item = historyStructs[Y.findIndexSS(historyStructs, historyType._item.id.clock)];
1266
+ if (!(item instanceof Y.Item && item.content instanceof Y.ContentType && item.content.type instanceof Y.XmlFragment)) throw error.unexpectedCase();
1267
+ historyType = item.content.type;
1268
+ }
1269
+ }
1270
+ const currentSnapshot = snapshot;
1271
+ const previousSnapshot = (_prevSnapshot = prevSnapshot) !== null && _prevSnapshot !== void 0 ? _prevSnapshot : Y.emptySnapshot;
1272
+ this.mapping.clear();
1273
+ projectedMappings.delete(this.mapping);
1274
+ this.mux(() => {
1275
+ historyDoc.transact((transaction) => {
1276
+ const pud = pluginState.permanentUserData;
1277
+ if (pud) pud.dss.forEach((ds) => {
1278
+ Y.iterateDeletedStructs(transaction, ds, (_item) => {});
1279
+ });
1280
+ const computeYChange = (type, id) => {
1281
+ const user = pud ? type === "added" ? pud.getUserByClientId(id.client) : pud.getUserByDeletedId(id) : null;
1282
+ return {
1283
+ user,
1284
+ type,
1285
+ color: getUserColor(pluginState.colorMapping, pluginState.colors, user)
1286
+ };
1287
+ };
1288
+ const fragmentContent = Y.typeListToArraySnapshot(historyType, new Y.Snapshot(previousSnapshot.ds, currentSnapshot.sv)).map((t) => {
1289
+ if (!(t instanceof Y.XmlElement) || !t._item) return null;
1290
+ if (!t._item.deleted || isVisible(t._item, currentSnapshot) || isVisible(t._item, previousSnapshot)) return createNodeFromYElement(t, this.view.state.schema, {
1291
+ mapping: /* @__PURE__ */ new Map(),
1292
+ isOMark: /* @__PURE__ */ new Map(),
1293
+ reportInvalidContent: this.reportInvalidContent ? () => {} : void 0,
1294
+ deferTextMerge: this.reportInvalidContent ? () => {} : void 0
1295
+ }, currentSnapshot, previousSnapshot, computeYChange);
1296
+ else return null;
1297
+ }).filter((n) => n !== null);
1298
+ const tr = this._tr.replace(0, this.view.state.doc.content.size, new PModel.Slice(PModel.Fragment.from(fragmentContent), 0, 0));
1299
+ this.view.dispatch(tr.setMeta(ySyncPluginKey, { isChangeOrigin: true }));
1300
+ }, ySyncPluginKey);
1301
+ });
1302
+ }
1303
+ _typeChanged(events, transaction) {
1304
+ var _transaction$origin$c;
1305
+ if (this.prosemirrorView == null) return;
1306
+ const syncState = getSyncPluginState(this.view.state);
1307
+ if (events.length === 0 || syncState.snapshot != null || syncState.prevSnapshot != null) {
1308
+ this.renderSnapshot(syncState.snapshot, syncState.prevSnapshot);
1309
+ return;
1310
+ }
1311
+ const isUndoRedoOperation = transaction.origin instanceof Y.UndoManager;
1312
+ const undoSelection = isUndoRedoOperation ? (_transaction$origin$c = transaction.origin.currStackItem) === null || _transaction$origin$c === void 0 ? void 0 : _transaction$origin$c.meta.get(this) : void 0;
1313
+ const selection = undoSelection || this.beforeTransactionSelection;
1314
+ const oldDoc = undoSelection ? void 0 : this.view.state.doc;
1315
+ let newError = null;
1316
+ this.mux(() => {
1317
+ const delType = (_, type) => deleteMapping(this.mapping, type);
1318
+ Y.iterateDeletedStructs(transaction, transaction.deleteSet, (struct) => {
1319
+ if (struct instanceof Y.Item && struct.content instanceof Y.ContentType) deleteMapping(this.mapping, struct.content.type);
1320
+ });
1321
+ transaction.changed.forEach(delType);
1322
+ transaction.changedParentTypes.forEach(delType);
1323
+ let tr = replaceChangedChildren(this._tr, this.createDocumentContent());
1324
+ newError = this.updateInvalidContentError();
1325
+ if (this._invalidContentError === null) restoreRelativeSelection(tr, selection, this, oldDoc);
1326
+ tr = tr.setMeta(ySyncPluginKey, {
1327
+ isChangeOrigin: true,
1328
+ isUndoRedoOperation
1329
+ });
1330
+ if (this.beforeTransactionSelection !== null && this._isLocalCursorInView()) tr.scrollIntoView();
1331
+ this.view.dispatch(tr);
1332
+ });
1333
+ this.notifyInvalidContent(newError);
1334
+ }
1335
+ _prosemirrorChanged(doc) {
1336
+ if (this._invalidContentError !== null) return;
1337
+ const syncState = getSyncPluginState(this.view.state);
1338
+ if (syncState.snapshot != null || syncState.prevSnapshot != null) return;
1339
+ this.doc.transact(() => {
1340
+ updateYFragment(this.doc, this.type, doc, this);
1341
+ this.hasSharedContent || (this.hasSharedContent = this.type.length > 0);
1342
+ this.beforeTransactionSelection = getRelativeSelection(this, this.view.state);
1343
+ }, ySyncPluginKey);
1344
+ }
1345
+ initView(prosemirrorView) {
1346
+ if (this.prosemirrorView != null) this.destroy();
1347
+ this.prosemirrorView = prosemirrorView;
1348
+ this.doc.on("beforeAllTransactions", this.beforeAllTransactions);
1349
+ this.doc.on("afterAllTransactions", this.afterAllTransactions);
1350
+ this.type.observeDeep(this._observeFunction);
1351
+ }
1352
+ destroy() {
1353
+ if (this.prosemirrorView == null) return;
1354
+ this.prosemirrorView = null;
1355
+ this.type.unobserveDeep(this._observeFunction);
1356
+ this.doc.off("beforeAllTransactions", this.beforeAllTransactions);
1357
+ this.doc.off("afterAllTransactions", this.afterAllTransactions);
1358
+ }
1359
+ };
1360
+ const migrationPrefix = "__tiptap_position_migrations:";
1361
+ const clearPositionMigrations = (document, transaction) => {
1362
+ const stores = [];
1363
+ document.share.forEach((type, name) => {
1364
+ if (!name.startsWith(migrationPrefix) || transaction && !transaction.changed.has(type)) return;
1365
+ const store = document.getMap(name);
1366
+ if (store.size > 0) stores.push(store);
1367
+ });
1368
+ if (stores.length === 0) return;
1369
+ document.transact((transaction) => {
1370
+ transaction.meta.set("addToHistory", false);
1371
+ stores.forEach((store) => store.clear());
1372
+ }, clearPositionMigrations);
1373
+ };
1374
+ const defaultColors = [{
1375
+ light: "#ecd44433",
1376
+ dark: "#ecd444"
1377
+ }];
1378
+ /** Binds a Yjs XML fragment to the editor document. The fragment must belong to a Yjs document. */
1379
+ const ySyncPlugin = (yXmlFragment, { colors = defaultColors, colorMapping = /* @__PURE__ */ new Map(), permanentUserData = null, onFirstRender = () => {}, mapping, onInvalidContent } = {}) => {
1380
+ let initialContentChanged = false;
1381
+ const binding = new ProsemirrorBinding(yXmlFragment, mapping, onInvalidContent);
1382
+ return new Plugin({
1383
+ filterTransaction: (transaction) => binding.invalidContentError === null || !transaction.docChanged || transaction.getMeta(ySyncPluginKey) !== void 0,
1384
+ props: { editable: (state) => {
1385
+ const syncState = getSyncPluginState(state);
1386
+ return binding.invalidContentError === null && syncState.snapshot == null && syncState.prevSnapshot == null;
1387
+ } },
1388
+ key: ySyncPluginKey,
1389
+ state: {
1390
+ init: (_initargs, _state) => {
1391
+ return {
1392
+ type: yXmlFragment,
1393
+ doc: binding.doc,
1394
+ binding,
1395
+ snapshot: null,
1396
+ prevSnapshot: null,
1397
+ isChangeOrigin: false,
1398
+ isUndoRedoOperation: false,
1399
+ addToHistory: true,
1400
+ colors,
1401
+ colorMapping,
1402
+ permanentUserData
1403
+ };
1404
+ },
1405
+ apply: (tr, pluginState) => {
1406
+ const change = tr.getMeta(ySyncPluginKey);
1407
+ if (change !== void 0) pluginState = Object.assign({}, pluginState, change);
1408
+ if (tr.docChanged) pluginState.addToHistory = tr.getMeta("addToHistory") !== false;
1409
+ pluginState.isChangeOrigin = change !== void 0 && !!change.isChangeOrigin;
1410
+ pluginState.isUndoRedoOperation = change !== void 0 && !!change.isChangeOrigin && !!change.isUndoRedoOperation;
1411
+ if (binding.prosemirrorView === null || change === void 0 || change.snapshot == null && change.prevSnapshot == null) return pluginState;
1412
+ eventloop.timeout(0, () => {
1413
+ if (binding.prosemirrorView == null) return;
1414
+ if (change.restore == null) {
1415
+ binding._renderSnapshot(change.snapshot, change.prevSnapshot, pluginState);
1416
+ return;
1417
+ }
1418
+ if (binding.invalidContentError !== null) {
1419
+ binding.unrenderSnapshot();
1420
+ return;
1421
+ }
1422
+ binding._renderSnapshot(change.snapshot, change.snapshot, pluginState);
1423
+ binding.mux(() => {
1424
+ const activeView = binding.prosemirrorView;
1425
+ if (!activeView) return;
1426
+ activeView.dispatch(binding._tr.setMeta(ySyncPluginKey, {
1427
+ restore: false,
1428
+ snapshot: null,
1429
+ prevSnapshot: null,
1430
+ isChangeOrigin: true
1431
+ }));
1432
+ binding._prosemirrorChanged(activeView.state.doc);
1433
+ });
1434
+ });
1435
+ return pluginState;
1436
+ }
1437
+ },
1438
+ view: (view) => {
1439
+ const clearMigrations = (transaction) => clearPositionMigrations(binding.doc, transaction);
1440
+ clearPositionMigrations(binding.doc);
1441
+ binding.doc.on("afterTransaction", clearMigrations);
1442
+ binding.initView(view);
1443
+ if (mapping == null) binding._forceRerender();
1444
+ onFirstRender();
1445
+ return {
1446
+ update: () => {
1447
+ const pluginState = getSyncPluginState(view.state);
1448
+ if (pluginState.snapshot == null && pluginState.prevSnapshot == null) {
1449
+ const emptyDocument = view.state.doc.type.createAndFill();
1450
+ if (!emptyDocument) throw new Error("The schema cannot create an empty document");
1451
+ if (initialContentChanged || view.state.doc.content.findDiffStart(emptyDocument.content) !== null) {
1452
+ initialContentChanged = true;
1453
+ if (pluginState.addToHistory === false && !pluginState.isChangeOrigin) {
1454
+ const yUndoPluginState = yUndoPluginKey.getState(view.state);
1455
+ const um = yUndoPluginState && yUndoPluginState.undoManager;
1456
+ if (um) um.stopCapturing();
1457
+ }
1458
+ binding.mux(() => {
1459
+ pluginState.doc.transact((tr) => {
1460
+ tr.meta.set("addToHistory", pluginState.addToHistory);
1461
+ binding._prosemirrorChanged(view.state.doc);
1462
+ }, ySyncPluginKey);
1463
+ });
1464
+ }
1465
+ }
1466
+ },
1467
+ destroy: () => {
1468
+ binding.doc.off("afterTransaction", clearMigrations);
1469
+ binding.destroy();
1470
+ }
1471
+ };
1472
+ }
1473
+ });
1474
+ };
1475
+ function getUndoPluginState(state) {
1476
+ const pluginState = yUndoPluginKey.getState(state);
1477
+ if (!pluginState) throw new Error("The editor requires yUndoPlugin");
1478
+ return pluginState;
1479
+ }
1480
+ const restoreHistory = (state, direction) => {
1481
+ const syncState = getSyncPluginState(state);
1482
+ if (syncState.binding.invalidContentError !== null || syncState.snapshot != null || syncState.prevSnapshot != null) return false;
1483
+ const undoManager = getUndoPluginState(state).undoManager;
1484
+ if (undoManager != null) {
1485
+ undoManager[direction]();
1486
+ return true;
1487
+ }
1488
+ };
1489
+ /** Undoes a local change through the editor's Yjs undo manager. */
1490
+ const undo = (state) => restoreHistory(state, "undo");
1491
+ /** Redoes a local change through the editor's Yjs undo manager. */
1492
+ const redo = (state) => restoreHistory(state, "redo");
1493
+ const defaultProtectedNodes = /* @__PURE__ */ new Set(["paragraph"]);
1494
+ /** Keeps protected structural nodes when an undo operation would delete them. */
1495
+ const defaultDeleteFilter = (item, protectedNodes) => !(item instanceof Item) || !(item.content instanceof ContentType) || !(item.content.type instanceof Text || item.content.type instanceof XmlElement && protectedNodes.has(item.content.type.nodeName)) || item.content.type._length === 0;
1496
+ /** Tracks local Yjs changes for undo and redo while preserving remote changes. */
1497
+ const yUndoPlugin = ({ protectedNodes = defaultProtectedNodes, trackedOrigins = [], undoManager = null } = {}) => new Plugin({
1498
+ key: yUndoPluginKey,
1499
+ state: {
1500
+ init: (_, state) => {
1501
+ const syncState = getSyncPluginState(state);
1502
+ const destroyListeners = /* @__PURE__ */ new Set();
1503
+ let manager = undoManager;
1504
+ if (!manager) {
1505
+ var _syncState$doc$_obser;
1506
+ const before = new Set(syncState.doc._observers.get("destroy"));
1507
+ manager = new UndoManager(syncState.type, {
1508
+ trackedOrigins: /* @__PURE__ */ new Set([ySyncPluginKey, ...trackedOrigins]),
1509
+ deleteFilter: (item) => defaultDeleteFilter(item, protectedNodes),
1510
+ captureTransaction: (transaction) => transaction.meta.get("addToHistory") !== false
1511
+ });
1512
+ ((_syncState$doc$_obser = syncState.doc._observers.get("destroy")) !== null && _syncState$doc$_obser !== void 0 ? _syncState$doc$_obser : /* @__PURE__ */ new Set()).forEach((listener) => {
1513
+ if (!before.has(listener)) destroyListeners.add(listener);
1514
+ });
1515
+ }
1516
+ return {
1517
+ undoManager: manager,
1518
+ prevSel: null,
1519
+ hasUndoOps: manager.undoStack.length > 0,
1520
+ hasRedoOps: manager.redoStack.length > 0,
1521
+ destroyListeners
1522
+ };
1523
+ },
1524
+ apply: (_, value, oldState, state) => {
1525
+ const binding = getSyncPluginState(state).binding;
1526
+ const canMapSelection = binding && binding.invalidContentError === null;
1527
+ return {
1528
+ ...value,
1529
+ prevSel: canMapSelection ? getRelativeSelection(binding, oldState) : value.prevSel,
1530
+ hasUndoOps: value.undoManager.undoStack.length > 0,
1531
+ hasRedoOps: value.undoManager.redoStack.length > 0
1532
+ };
1533
+ }
1534
+ },
1535
+ view: (view) => {
1536
+ const syncState = getSyncPluginState(view.state);
1537
+ const { undoManager: manager, destroyListeners } = getUndoPluginState(view.state);
1538
+ manager.on("stack-item-added", ({ stackItem }) => {
1539
+ const binding = syncState.binding;
1540
+ if (binding) {
1541
+ const selection = manager.undoing || manager.redoing ? binding.beforeTransactionSelection : getUndoPluginState(view.state).prevSel;
1542
+ stackItem.meta.set(binding, selection);
1543
+ }
1544
+ });
1545
+ return { destroy: () => {
1546
+ manager.destroy();
1547
+ destroyListeners.forEach((listener) => manager.doc.off("destroy", listener));
1548
+ destroyListeners.clear();
1549
+ } };
1550
+ }
1551
+ });
1552
+ /** Converts a ProseMirror document into a new or existing Yjs XML fragment. */
1553
+ function prosemirrorToYXmlFragment(doc, xmlFragment) {
1554
+ var _type$doc;
1555
+ const type = xmlFragment || new Y.XmlFragment();
1556
+ const ydoc = (_type$doc = type.doc) !== null && _type$doc !== void 0 ? _type$doc : { transact: (callback) => callback() };
1557
+ updateYFragment(ydoc, type, doc, {
1558
+ mapping: /* @__PURE__ */ new Map(),
1559
+ isOMark: /* @__PURE__ */ new Map()
1560
+ });
1561
+ return type;
1562
+ }
1563
+ /** Reads ProseMirror JSON from a Yjs XML fragment. */
1564
+ function yXmlFragmentToProsemirrorJSON(xmlFragment) {
1565
+ const items = xmlFragment.toArray();
1566
+ const serialize = (item) => {
1567
+ let response;
1568
+ if (item instanceof Y.XmlText) response = item.toDelta().map((d) => {
1569
+ const text = {
1570
+ type: "text",
1571
+ text: d.insert
1572
+ };
1573
+ const attributes = d.attributes;
1574
+ if (attributes) text.marks = Object.keys(attributes).map((type_) => {
1575
+ const attrs = attributes[type_];
1576
+ const mark = { type: yattr2markname(type_) };
1577
+ if (Object.keys(attrs).length) mark.attrs = attrs;
1578
+ return mark;
1579
+ });
1580
+ return text;
1581
+ });
1582
+ else if (item instanceof Y.XmlElement) {
1583
+ response = { type: item.nodeName };
1584
+ const attrs = item.getAttributes();
1585
+ if (Object.keys(attrs).length) response.attrs = attrs;
1586
+ const children = item.toArray();
1587
+ if (children.length) response.content = children.map(serialize).flat();
1588
+ } else error.unexpectedCase();
1589
+ return response;
1590
+ };
1591
+ return {
1592
+ type: "doc",
1593
+ content: items.map(serialize)
1594
+ };
1595
+ }
1596
+ /** Converts ProseMirror JSON into a new or existing Yjs XML fragment. */
1597
+ function prosemirrorJSONToYXmlFragment(schema, state, xmlFragment) {
1598
+ return prosemirrorToYXmlFragment(Node$1.fromJSON(schema, state), xmlFragment);
1599
+ }
1600
+ // src/document.ts
1601
+ const schemas = /* @__PURE__ */ new WeakMap();
1602
+ function realtimeEditorSchema(editor) {
1603
+ let schema = schemas.get(editor);
1604
+ if (!schema) {
1605
+ schema = getSchema(editor.extensions());
1606
+ schemas.set(editor, schema);
1607
+ }
1608
+ return schema;
1609
+ }
1610
+ function stableJson(value) {
1611
+ if (Array.isArray(value)) return `[${value.map(stableJson).join(",")}]`;
1612
+ if (isRecord(value)) {
1613
+ const record = value;
1614
+ return `{${Object.keys(record).sort().map((key) => `${JSON.stringify(key)}:${stableJson(record[key])}`).join(",")}}`;
1615
+ }
1616
+ return JSON.stringify(value ?? null);
1617
+ }
1618
+ function realtimeJsonEqual(left, right) {
1619
+ return stableJson(left) === stableJson(right);
1620
+ }
1621
+ /** Writes fields into a document's field map, inserting, replacing, and deleting only what differs. */
1622
+ function writeRealtimeFields(map, fields) {
1623
+ const next = fields ?? {};
1624
+ for (const key of map.keys()) if (!Object.hasOwn(next, key)) map.delete(key);
1625
+ for (const [key, value] of Object.entries(next)) {
1626
+ if (value === void 0) continue;
1627
+ if (!map.has(key) || !realtimeJsonEqual(map.get(key), value)) map.set(key, structuredClone(value));
1628
+ }
1629
+ }
1630
+ /** Builds a new room document from a stored snapshot. Only use it for rooms no client holds yet. */
1631
+ async function createRealtimeYDoc(editor, snapshot) {
1632
+ const content = await editor.fromMarkdown(snapshot.body);
1633
+ const document = new Y.Doc();
1634
+ try {
1635
+ document.transact(() => {
1636
+ prosemirrorJSONToYXmlFragment(realtimeEditorSchema(editor), content, document.getXmlFragment(realtimeDocumentLayout.body));
1637
+ writeRealtimeFields(document.getMap(realtimeDocumentLayout.fields), snapshot.fields);
1638
+ });
1639
+ return document;
1640
+ } catch (error) {
1641
+ document.destroy();
1642
+ throw error;
1643
+ }
1644
+ }
1645
+ function readRealtimeFields(document) {
1646
+ return document.getMap(realtimeDocumentLayout.fields).toJSON();
1647
+ }
1648
+ function readRealtimeBody(editor, document) {
1649
+ return {
1650
+ ...yXmlFragmentToProsemirrorJSON(document.getXmlFragment(realtimeDocumentLayout.body)),
1651
+ type: realtimeEditorSchema(editor).topNodeType.name
1652
+ };
1653
+ }
1654
+ async function readRealtimeYDoc(editor, document) {
1655
+ const content = readRealtimeBody(editor, document);
1656
+ const fields = readRealtimeFields(document);
1657
+ return {
1658
+ body: await editor.toMarkdown(content),
1659
+ fields
1660
+ };
1661
+ }
1662
+ /**
1663
+ * Throws when the body of `document` does not fit the editor schema, such as a node type the schema does not know.
1664
+ * A codec that builds an editor from such JSON writes an empty or partial document.
1665
+ */
1666
+ function checkRealtimeBody(editor, document) {
1667
+ realtimeEditorSchema(editor).nodeFromJSON(readRealtimeBody(editor, document)).check();
1668
+ }
1669
+ /** Whether `fromMarkdown(body)` gives back the body of `document`, where `body` is what `toMarkdown` wrote for it. */
1670
+ async function realtimeCodecReadsBack(editor, document, body) {
1671
+ const schema = realtimeEditorSchema(editor);
1672
+ try {
1673
+ return schema.nodeFromJSON(readRealtimeBody(editor, document)).eq(schema.nodeFromJSON(await editor.fromMarkdown(body)));
1674
+ } catch {
1675
+ return false;
1676
+ }
1677
+ }
1678
+ /** Adds the final newline that a codec dropped when the stored body ends with one. */
1679
+ function keepRealtimeFinalNewline(body, finalNewline) {
1680
+ return finalNewline && !body.endsWith("\n") ? `${body}\n` : body;
1681
+ }
1682
+ function sameBody(left, right) {
1683
+ return left === right || keepRealtimeFinalNewline(left, true) === keepRealtimeFinalNewline(right, true);
1684
+ }
1685
+ /**
1686
+ * Returns the Yjs update that turns `base` into `target` as a structural diff. Applying it to a
1687
+ * room that has moved on since `base` keeps concurrent edits instead of duplicating content.
1688
+ */
1689
+ async function diffRealtimeYDoc(editor, base, target) {
1690
+ const current = await readRealtimeYDoc(editor, base);
1691
+ const next = sameBody(target.body, current.body) ? void 0 : await editor.fromMarkdown(target.body);
1692
+ const fieldsChanged = target.fields !== void 0 && !realtimeJsonEqual(current.fields, target.fields);
1693
+ if (!next && !fieldsChanged) return /* @__PURE__ */ new Uint8Array();
1694
+ const clone = new Y.Doc({ gc: false });
1695
+ try {
1696
+ Y.applyUpdate(clone, Y.encodeStateAsUpdate(base));
1697
+ const state = Y.encodeStateVector(clone);
1698
+ clone.transact(() => {
1699
+ if (next) updateYFragment(clone, clone.getXmlFragment(realtimeDocumentLayout.body), realtimeEditorSchema(editor).nodeFromJSON(next), {
1700
+ isOMark: /* @__PURE__ */ new Map(),
1701
+ mapping: /* @__PURE__ */ new Map()
1702
+ });
1703
+ if (fieldsChanged) writeRealtimeFields(clone.getMap(realtimeDocumentLayout.fields), target.fields);
1704
+ });
1705
+ return Y.encodeStateAsUpdate(clone, state);
1706
+ } finally {
1707
+ clone.destroy();
1708
+ }
1709
+ }
1710
+ function writeRealtimeStatus(document, status, origin) {
1711
+ const map = document.getMap(realtimeDocumentLayout.status);
1712
+ document.transact(() => {
1713
+ for (const [key, value] of Object.entries(status)) {
1714
+ if (value === void 0) continue;
1715
+ if (!map.has(key) || !realtimeJsonEqual(map.get(key), value)) map.set(key, value === null ? null : structuredClone(value));
1716
+ }
1717
+ }, origin);
1718
+ }
1719
+ /** Compact fingerprint used to reject client updates that touch the server-written status. */
1720
+ function realtimeStatusFingerprint(document) {
1721
+ return stableJson(document.getMap(realtimeDocumentLayout.status).toJSON());
1722
+ }
1723
+ /** Whether `document` already contains every insertion and deletion in `state`. */
1724
+ function containsRealtimeState(document, state) {
1725
+ const candidate = new Y.Doc({ gc: false });
1726
+ try {
1727
+ Y.applyUpdate(candidate, Y.encodeStateAsUpdate(document));
1728
+ const before = Y.snapshot(candidate);
1729
+ Y.applyUpdate(candidate, state);
1730
+ if (candidate.store.pendingStructs || candidate.store.pendingDs) return false;
1731
+ return Y.equalSnapshots(before, Y.snapshot(candidate));
1732
+ } finally {
1733
+ candidate.destroy();
1734
+ }
1735
+ }
1736
+ export { yCursorPlugin as _, keepRealtimeFinalNewline as a, yUndoPlugin as b, realtimeJsonEqual as c, writeRealtimeStatus as d, absolutePositionToRelativePosition as f, undo as g, relativePositionToAbsolutePosition as h, diffRealtimeYDoc as i, realtimeStatusFingerprint as l, redo as m, containsRealtimeState as n, readRealtimeYDoc as o, defaultSelectionBuilder as p, createRealtimeYDoc as r, realtimeCodecReadsBack as s, checkRealtimeBody as t, writeRealtimeFields as u, ySyncPlugin as v, yUndoPluginKey as x, ySyncPluginKey as y };