@vite-hub/realtime 0.0.4 → 0.3.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/dist/vue.js CHANGED
@@ -1,24 +1,50 @@
1
- import { S as yUndoPluginKey, b as ySyncPluginKey, d as getRealtimePeople, f as absolutePositionToRelativePosition, g as undo, h as relativePositionToAbsolutePosition, i as isRetryableRealtimeCheckpointCode, l as workspaceRoomId, m as redo, n as decodeWorkspaceChangePayload, r as encodeWorkspaceChange, t as createRealtimeEditorExtensions, u as createRealtimeIdentity, x as yUndoPlugin, y as ySyncPlugin } from "./editor-extensions-CZEzrJ-t.js";
2
- import { Extension, MappablePosition, getUpdatedPosition } from "@tiptap/core";
3
- import * as Y from "yjs";
1
+ import { t as realtimeErrorDiagnostics } from "./error-diagnostics-B_66irmt.js";
2
+ import { n as resolveRealtimeApplicationPath, t as keepRealtimeSocketAlive } from "./keepalive-BCs-uXp4.js";
3
+ import { i as decodeRealtimeControlPayload, l as encodeWorkspaceChange, n as isRecord, o as decodeWorkspaceChangePayload, u as isRetryableRealtimeRequestCode, x as workspaceRoomId } from "./object-CzKyK0hX.js";
4
+ import { n as realtimeDocumentLayout, t as readRealtimeStatus } from "./layout-DNaxppTZ.js";
5
+ import { n as getRealtimePeople, t as createRealtimeIdentity } from "./presence-Tuy1y_l9.js";
6
+ import { t as createRealtimeEditorExtensions } from "./editor-BM5-vHqf.js";
7
+ import { _ as yCursorPlugin, b as yUndoPlugin, f as absolutePositionToRelativePosition, g as undo, h as relativePositionToAbsolutePosition, m as redo, o as readRealtimeYDoc, p as defaultSelectionBuilder, v as ySyncPlugin, x as yUndoPluginKey, y as ySyncPluginKey } from "./document-DjBrcgpY.js";
4
8
  import "lib0/decoding";
9
+ import * as encoding from "lib0/encoding";
10
+ import * as awarenessProtocol from "y-protocols/awareness";
11
+ import { WebsocketProvider } from "y-websocket";
12
+ import * as Y from "yjs";
13
+ import { Extension, MappablePosition, getUpdatedPosition } from "@tiptap/core";
5
14
  import { Plugin, PluginKey } from "@tiptap/pm/state";
6
15
  import { useUserSession } from "@vite-hub/auth/vue";
7
- import { computed, markRaw, onScopeDispose, ref, shallowRef, toValue, watch } from "vue";
8
- import { WebsocketProvider } from "y-websocket";
9
- //#region ../../node_modules/.pnpm/@tiptap+extension-collaboration@3.29.2_@tiptap+core@3.29.2_@tiptap+pm@3.29.2__@tiptap+p_894d099a4ad840a9519abb2f14438fb9/node_modules/@tiptap/extension-collaboration/dist/index.js
16
+ import { computed, getCurrentInstance, markRaw, onMounted, onScopeDispose, ref, shallowRef, toValue, watch } from "vue";
17
+ //#region ../../node_modules/.pnpm/@tiptap+extension-collaboration@3.31.4_@tiptap+core@3.31.4_@tiptap+pm@3.31.4__@tiptap+p_85015a5a825a0d4859fbb90094e145d9/node_modules/@tiptap/extension-collaboration/dist/index.js
18
+ /**
19
+ * Checks if a transaction was originated from a Yjs change.
20
+ * @param {Transaction} transaction - The transaction to check.
21
+ * @returns {boolean} - True if the transaction was originated from a Yjs change, false otherwise.
22
+ * @example
23
+ * const transaction = new Transaction(doc)
24
+ * const isOrigin = isChangeOrigin(transaction) // returns false
25
+ */
10
26
  function isChangeOrigin(transaction) {
11
27
  return !!transaction.getMeta(ySyncPluginKey);
12
28
  }
29
+ /**
30
+ * Converts a Y.js relative position to a position in the Tiptap document.
31
+ */
13
32
  function getYAbsolutePosition(state, relativePos) {
14
33
  const ystate = ySyncPluginKey.getState(state);
15
34
  return relativePositionToAbsolutePosition(ystate.doc, ystate.type, relativePos, ystate.binding.mapping) || 0;
16
35
  }
36
+ /**
37
+ * Converts a position in the Tiptap document to a Y.js relative position.
38
+ */
17
39
  function getYRelativePosition(state, absolutePos) {
18
40
  const ystate = ySyncPluginKey.getState(state);
19
41
  return absolutePositionToRelativePosition(absolutePos, ystate.type, ystate.binding.mapping);
20
42
  }
21
- var CollaborationMappablePosition = class _CollaborationMappablePosition extends MappablePosition {
43
+ /**
44
+ * A MappablePosition subclass that includes Y.js relative position information
45
+ * to track positions in collaborative transactions.
46
+ */
47
+ var CollaborationMappablePosition = class CollaborationMappablePosition extends MappablePosition {
22
48
  constructor(position, yRelativePosition) {
23
49
  super(position);
24
50
  this.yRelativePosition = yRelativePosition;
@@ -27,7 +53,7 @@ var CollaborationMappablePosition = class _CollaborationMappablePosition extends
27
53
  * Creates a CollaborationMappablePosition from a JSON object.
28
54
  */
29
55
  static fromJSON(json) {
30
- return new _CollaborationMappablePosition(json.position, json.yRelativePosition);
56
+ return new CollaborationMappablePosition(json.position, json.yRelativePosition);
31
57
  }
32
58
  /**
33
59
  * Converts the CollaborationMappablePosition to a JSON object.
@@ -39,9 +65,17 @@ var CollaborationMappablePosition = class _CollaborationMappablePosition extends
39
65
  };
40
66
  }
41
67
  };
68
+ /**
69
+ * Creates a MappablePosition from a position number.
70
+ * This is the collaboration implementation that returns a CollaborationMappablePosition.
71
+ */
42
72
  function createMappablePosition(position, state) {
43
73
  return new CollaborationMappablePosition(position, getYRelativePosition(state, position));
44
74
  }
75
+ /**
76
+ * Returns the new position after applying a transaction. Handles both Y.js
77
+ * transactions and regular transactions.
78
+ */
45
79
  function getUpdatedPosition$1(position, transaction, state) {
46
80
  const yRelativePosition = position instanceof CollaborationMappablePosition ? position.yRelativePosition : null;
47
81
  if (isChangeOrigin(transaction) && yRelativePosition) return {
@@ -51,11 +85,11 @@ function getUpdatedPosition$1(position, transaction, state) {
51
85
  const result = getUpdatedPosition(position, transaction);
52
86
  const absolutePosition = result.position.position;
53
87
  return {
54
- position: new CollaborationMappablePosition(absolutePosition, yRelativePosition != null ? yRelativePosition : getYRelativePosition(state, absolutePosition)),
88
+ position: new CollaborationMappablePosition(absolutePosition, yRelativePosition !== null && yRelativePosition !== void 0 ? yRelativePosition : getYRelativePosition(state, absolutePosition)),
55
89
  mapResult: result.mapResult
56
90
  };
57
91
  }
58
- var index_default = Extension.create({
92
+ var src_default = Extension.create({
59
93
  name: "collaboration",
60
94
  priority: 1e3,
61
95
  addOptions() {
@@ -118,15 +152,20 @@ var index_default = Extension.create({
118
152
  undoManager.doc.on("afterTransaction", undoManager.afterTransactionHandler);
119
153
  undoManager._observers = observers;
120
154
  };
121
- if (viewRet == null ? void 0 : viewRet.destroy) viewRet.destroy();
155
+ if (viewRet === null || viewRet === void 0 ? void 0 : viewRet.destroy) viewRet.destroy();
122
156
  } };
123
157
  };
158
+ const ySyncPluginOptions = {
159
+ ...this.options.ySyncOptions,
160
+ onFirstRender: this.options.onFirstRender
161
+ };
124
162
  return [
125
- ySyncPlugin(fragment, {
126
- ...this.options.ySyncOptions,
127
- onFirstRender: this.options.onFirstRender
128
- }),
163
+ ySyncPlugin(fragment, ySyncPluginOptions),
129
164
  yUndoPluginInstance,
165
+ new Plugin({ filterTransaction: (transaction, state) => {
166
+ if (transaction.getMeta("inputRule")) yUndoPluginKey.getState(state).undoManager.stopCapturing();
167
+ return true;
168
+ } }),
130
169
  this.editor.options.enableContentCheck && new Plugin({
131
170
  key: new PluginKey("filterInvalidContent"),
132
171
  filterTransaction: (transaction) => {
@@ -142,8 +181,8 @@ var index_default = Extension.create({
142
181
  error,
143
182
  editor: this.editor,
144
183
  disableCollaboration: () => {
145
- var _a;
146
- (_a = fragment.doc) == null || _a.destroy();
184
+ var _fragment$doc;
185
+ (_fragment$doc = fragment.doc) === null || _fragment$doc === void 0 || _fragment$doc.destroy();
147
186
  }
148
187
  });
149
188
  return true;
@@ -154,39 +193,139 @@ var index_default = Extension.create({
154
193
  }
155
194
  });
156
195
  //#endregion
157
- //#region src/application-path.ts
158
- function resolveRealtimeApplicationPath(path) {
159
- const baseURL = typeof __VITEHUB_APP_BASE_URL__ === "undefined" ? "/" : __VITEHUB_APP_BASE_URL__;
160
- return baseURL === "/" ? path : `${baseURL.replace(/\/+$/, "")}${path}`;
161
- }
196
+ //#region src/caret.ts
197
+ const validColor = /^#[0-9a-f]{6}$/i;
198
+ /**
199
+ * Other people's carets and selections, drawn from the room's awareness. It renders what TipTap's CollaborationCaret
200
+ * renders, under the same extension name, but it uses Realtime's bundled y-tiptap: CollaborationCaret installed next to
201
+ * Realtime has its own copy, cannot find Realtime's sync plugin, and draws nothing. Presence identity stays Realtime's.
202
+ */
203
+ const RealtimeCaret = Extension.create({
204
+ name: "collaborationCaret",
205
+ priority: 999,
206
+ addOptions() {
207
+ return {
208
+ awareness: null,
209
+ render: (user) => {
210
+ const caret = document.createElement("span");
211
+ caret.classList.add("collaboration-carets__caret");
212
+ caret.style.borderColor = user.color;
213
+ const label = document.createElement("div");
214
+ label.classList.add("collaboration-carets__label");
215
+ label.style.backgroundColor = user.color;
216
+ label.append(document.createTextNode(user.name));
217
+ caret.append(label);
218
+ return caret;
219
+ },
220
+ selectionRender: (user) => defaultSelectionBuilder(user)
221
+ };
222
+ },
223
+ addProseMirrorPlugins() {
224
+ const { awareness, render, selectionRender } = this.options;
225
+ if (!awareness) return [];
226
+ const person = (user) => ({
227
+ ...user,
228
+ color: typeof user.color === "string" && validColor.test(user.color) ? user.color : "transparent",
229
+ name: typeof user.name === "string" ? user.name : ""
230
+ });
231
+ return [yCursorPlugin(awareness, {
232
+ cursorBuilder: (user) => render(person(user)),
233
+ selectionBuilder: (user) => {
234
+ const current = person(user);
235
+ return current.color === "transparent" ? {} : selectionRender(current);
236
+ }
237
+ })];
238
+ }
239
+ });
162
240
  //#endregion
163
241
  //#region src/vue.ts
164
242
  const workspaceChangeFlushIntervalMs = 11;
243
+ function isString(value) {
244
+ return typeof value === "string";
245
+ }
246
+ function isRealtimeSaved(value) {
247
+ if (!isRecord(value) || !isRecord(value.document) || !isString(value.document.body)) return false;
248
+ if (value.document.fields !== void 0 && !isRecord(value.document.fields)) return false;
249
+ if (value.digest !== null && !isString(value.digest)) return false;
250
+ if (value.savedAt !== null && !isString(value.savedAt)) return false;
251
+ if (value.error !== null && !isString(value.error)) return false;
252
+ return Array.isArray(value.issues) && (value.savedBy === null || isRecord(value.savedBy));
253
+ }
254
+ function isRealtimeCheckpoint(value) {
255
+ if (!isRealtimeSaved(value) || !isString(value.digest)) return false;
256
+ const snapshot = "snapshot" in value ? value.snapshot : void 0;
257
+ if (!isRecord(snapshot)) return false;
258
+ if (typeof snapshot.id !== "string" || typeof snapshot.createdAt !== "string") return false;
259
+ if (snapshot.name !== void 0 && !isString(snapshot.name)) return false;
260
+ if (!isRecord(snapshot.entries)) return false;
261
+ return Object.values(snapshot.entries).every((entry) => {
262
+ if (!isRecord(entry) || entry.type !== "file" && entry.type !== "directory") return false;
263
+ if (entry.digest !== void 0 && !isString(entry.digest)) return false;
264
+ if (entry.metadata !== void 0 && !isRecord(entry.metadata)) return false;
265
+ if (entry.size !== void 0) {
266
+ if (typeof entry.size !== "number" || !Number.isFinite(entry.size)) return false;
267
+ }
268
+ return true;
269
+ });
270
+ }
271
+ function isRefreshResult(value) {
272
+ return isRecord(value) && (value.digest === null || isString(value.digest)) && typeof value.reseeded === "boolean";
273
+ }
165
274
  function useRealtimeTiptap(definition, documentId, options = {}) {
166
- const { user } = useUserSession();
275
+ const sessionUser = options.identity === void 0 ? useUserSession().user : void 0;
276
+ const identity = () => options.identity === void 0 ? sessionUser?.value : toValue(options.identity);
277
+ const createExtensions = () => options.editor ? options.editor.extensions() : createRealtimeEditorExtensions({ collaborative: true });
278
+ const createCarets = (awareness) => {
279
+ if (options.carets === false) return [];
280
+ const { render, selectionRender } = typeof options.carets === "object" ? options.carets : {};
281
+ return [markRaw(RealtimeCaret.configure({
282
+ awareness: markRaw(awareness),
283
+ ...render ? { render } : {},
284
+ ...selectionRender ? { selectionRender } : {}
285
+ }))];
286
+ };
167
287
  const document = shallowRef();
168
288
  const provider = shallowRef();
169
289
  const workspaceProvider = shallowRef();
170
290
  const workspaceChange = shallowRef();
171
291
  const people = shallowRef([]);
292
+ const saveStatus = shallowRef();
172
293
  const status = ref("disconnected");
173
294
  const synced = ref(false);
295
+ const readOnlyReason = ref(null);
174
296
  const checkpointRequests = ref(0);
297
+ const saveRequests = ref(0);
175
298
  const pendingWorkspaceChanges = [];
299
+ const requestControllers = /* @__PURE__ */ new Set();
300
+ const refreshControllers = /* @__PURE__ */ new Set();
301
+ const resetListeners = /* @__PURE__ */ new Set();
302
+ if (options.onReset) resetListeners.add(options.onReset);
303
+ let connectedDocumentId;
176
304
  let workspaceChangeTimer;
177
305
  const enabled = () => options.enabled === void 0 || toValue(options.enabled);
178
- function destroyDocument() {
306
+ let canConnect = !getCurrentInstance();
307
+ function destroyDocument(keepDocument = false, preserveRefresh = false) {
308
+ for (const controller of requestControllers) if (!preserveRefresh || !refreshControllers.has(controller)) controller.abort();
309
+ if (preserveRefresh) {
310
+ for (const controller of requestControllers) if (!refreshControllers.has(controller)) requestControllers.delete(controller);
311
+ } else {
312
+ requestControllers.clear();
313
+ refreshControllers.clear();
314
+ }
315
+ connectedDocumentId = void 0;
179
316
  provider.value?.destroy();
180
- document.value?.destroy();
317
+ if (!keepDocument) document.value?.destroy();
181
318
  provider.value = void 0;
182
319
  document.value = void 0;
183
320
  people.value = [];
321
+ saveStatus.value = void 0;
184
322
  status.value = "disconnected";
185
323
  synced.value = false;
324
+ readOnlyReason.value = null;
186
325
  }
187
326
  function currentPerson(clientId) {
188
- const value = user.value;
189
- const id = value?.id || `guest:${clientId}`;
327
+ const value = identity();
328
+ const id = isString(value?.id) && value.id ? value.id : `guest:${clientId}`;
190
329
  return createRealtimeIdentity({
191
330
  ...value,
192
331
  id
@@ -223,15 +362,18 @@ function useRealtimeTiptap(definition, documentId, options = {}) {
223
362
  workspaceChangeTimer = void 0;
224
363
  pendingWorkspaceChanges.length = 0;
225
364
  }
365
+ function serverURL() {
366
+ return `${window.location.protocol === "https:" ? "wss:" : "ws:"}//${window.location.host}${resolveRealtimeApplicationPath(`/api/_vitehub/realtime/${encodeURIComponent(definition)}`)}`;
367
+ }
226
368
  if (typeof window !== "undefined") {
227
- const server = `${window.location.protocol === "https:" ? "wss:" : "ws:"}//${window.location.host}${resolveRealtimeApplicationPath(`/api/_vitehub/realtime/${encodeURIComponent(definition)}`)}`;
228
369
  const workspaceDocument = markRaw(new Y.Doc());
229
- const nextWorkspaceProvider = new WebsocketProvider(server, encodeURIComponent(workspaceRoomId), workspaceDocument, {
370
+ const nextWorkspaceProvider = new WebsocketProvider(serverURL(), encodeURIComponent(workspaceRoomId), workspaceDocument, {
230
371
  connect: false,
231
372
  disableBc: true,
232
373
  params: { workspace: "events" }
233
374
  });
234
375
  nextWorkspaceProvider.awareness.setLocalState(null);
376
+ keepRealtimeSocketAlive(nextWorkspaceProvider);
235
377
  nextWorkspaceProvider.messageHandlers[4] = (_encoder, decoder) => {
236
378
  const change = decodeWorkspaceChangePayload(decoder);
237
379
  if (change) workspaceChange.value = change;
@@ -241,55 +383,188 @@ function useRealtimeTiptap(definition, documentId, options = {}) {
241
383
  });
242
384
  workspaceProvider.value = nextWorkspaceProvider;
243
385
  }
244
- async function checkpoint() {
245
- if (!enabled()) throw new Error("Realtime is disabled.");
246
- checkpointRequests.value++;
386
+ function connect(id) {
387
+ const nextDocument = markRaw(new Y.Doc());
388
+ const room = id.split("/").map(encodeURIComponent).join("/");
389
+ const version = options.editor?.version;
390
+ const nextProvider = new WebsocketProvider(serverURL(), room, nextDocument, {
391
+ connect: canConnect,
392
+ disableBc: true,
393
+ params: {
394
+ clientId: String(nextDocument.clientID),
395
+ ...version === void 0 ? {} : { editor: version }
396
+ }
397
+ });
398
+ keepRealtimeSocketAlive(nextProvider);
399
+ nextProvider.messageHandlers[5] = (_encoder, decoder) => {
400
+ if (provider.value !== nextProvider) return;
401
+ const control = decodeRealtimeControlPayload(decoder);
402
+ if (!control) return;
403
+ if (control.type === "session") {
404
+ nextProvider.params.epoch = control.epoch;
405
+ readOnlyReason.value = control.access === "read" ? control.reason ?? "access" : null;
406
+ return;
407
+ }
408
+ reset(id, control.reason, control.epoch);
409
+ };
410
+ nextProvider.awareness.off("update", nextProvider._awarenessUpdateHandler);
411
+ nextProvider.awareness.on("update", ({ added, removed, updated }) => {
412
+ const own = [
413
+ ...added,
414
+ ...updated,
415
+ ...removed
416
+ ].filter((client) => client === nextDocument.clientID);
417
+ const socket = nextProvider.ws;
418
+ if (!own.length || !nextProvider.wsconnected || !socket || socket.readyState !== socket.OPEN) return;
419
+ const encoder = encoding.createEncoder();
420
+ encoding.writeVarUint(encoder, 1);
421
+ encoding.writeVarUint8Array(encoder, awarenessProtocol.encodeAwarenessUpdate(nextProvider.awareness, own));
422
+ socket.send(encoding.toUint8Array(encoder));
423
+ });
424
+ nextProvider.awareness.setLocalStateField("user", currentPerson(nextDocument.clientID));
425
+ nextProvider.awareness.on("change", () => {
426
+ if (provider.value === nextProvider) updatePeople(nextProvider);
427
+ });
428
+ updatePeople(nextProvider);
429
+ nextDocument.getMap(realtimeDocumentLayout.status).observe(() => {
430
+ if (document.value === nextDocument) saveStatus.value = readRealtimeStatus(nextDocument);
431
+ });
432
+ nextProvider.on("status", (event) => {
433
+ if (provider.value === nextProvider) status.value = event.status;
434
+ });
435
+ nextProvider.on("sync", (value) => {
436
+ if (provider.value !== nextProvider) return;
437
+ synced.value = value;
438
+ if (value) saveStatus.value = readRealtimeStatus(nextDocument);
439
+ });
440
+ connectedDocumentId = id;
441
+ document.value = nextDocument;
442
+ provider.value = nextProvider;
443
+ if (canConnect) status.value = "connecting";
444
+ }
445
+ function reset(id, reason, epoch) {
446
+ const previous = document.value;
447
+ destroyDocument(true, true);
448
+ if (previous) try {
449
+ for (const listener of resetListeners) listener({
450
+ epoch,
451
+ previous,
452
+ reason
453
+ });
454
+ } finally {
455
+ previous.destroy();
456
+ }
457
+ if (enabled() && toValue(documentId) === id) connect(id);
458
+ }
459
+ function onReset(listener) {
460
+ resetListeners.add(listener);
461
+ return () => resetListeners.delete(listener);
462
+ }
463
+ async function request(action) {
464
+ const disconnected = () => [realtimeErrorDiagnostics.REALTIME_DISCONNECTED({ action }), void 0];
465
+ const controller = new AbortController();
466
+ requestControllers.add(controller);
467
+ if (action === "refresh") refreshControllers.add(controller);
247
468
  try {
248
469
  const id = toValue(documentId);
249
- if (!id) throw new Error("A realtime document is required before creating a checkpoint.");
470
+ if (!id) return [realtimeErrorDiagnostics.REALTIME_MISSING_DOCUMENT({ action }), void 0];
250
471
  const room = id.split("/").map(encodeURIComponent).join("/");
472
+ const current = document.value;
473
+ const query = action === "checkpoint" ? "history=checkpoint" : `document=${action}`;
474
+ const stillCurrent = () => !controller.signal.aborted && !!current && connectedDocumentId === id && document.value === current && toValue(documentId) === id && enabled();
251
475
  for (let attempt = 0;; attempt++) {
252
- const current = document.value;
253
- if (!current) throw new Error("The realtime document is not connected.");
254
- const response = await fetch(resolveRealtimeApplicationPath(`/api/_vitehub/realtime/${encodeURIComponent(definition)}/${room}?history=checkpoint`), {
255
- body: Uint8Array.from(Y.encodeStateAsUpdate(current)).buffer,
256
- method: "POST"
257
- });
258
- if (response.ok) return await response.json();
259
- const data = await response.json().catch(() => void 0);
260
- if (response.status === 409 && isRetryableRealtimeCheckpointCode(data?.data?.code) && attempt < 20) {
476
+ if (action !== "refresh" && !stillCurrent()) return disconnected();
477
+ let response;
478
+ try {
479
+ response = await fetch(resolveRealtimeApplicationPath(`/api/_vitehub/realtime/${encodeURIComponent(definition)}/${room}?${query}`), {
480
+ body: action === "refresh" ? void 0 : Uint8Array.from(Y.encodeStateAsUpdate(current)).buffer,
481
+ method: "POST",
482
+ signal: controller.signal
483
+ });
484
+ } catch (cause) {
485
+ if (controller.signal.aborted) return disconnected();
486
+ return [realtimeErrorDiagnostics.REALTIME_REQUEST_FAILED({
487
+ action,
488
+ cause
489
+ }), void 0];
490
+ }
491
+ let data;
492
+ try {
493
+ data = await response.json();
494
+ } catch {
495
+ if (controller.signal.aborted) return disconnected();
496
+ }
497
+ if (action !== "refresh" && !stillCurrent()) return disconnected();
498
+ if (response.ok) return [void 0, data];
499
+ const errorData = isRecord(data) ? data : void 0;
500
+ const nestedData = isRecord(errorData?.data) ? errorData.data : void 0;
501
+ const message = isString(errorData?.statusMessage) && errorData.statusMessage ? errorData.statusMessage : isString(errorData?.message) ? errorData.message : void 0;
502
+ if (response.status === 409 && isRetryableRealtimeRequestCode(isString(nestedData?.code) ? nestedData.code : void 0) && attempt < 20) {
261
503
  await new Promise((resolve) => setTimeout(resolve, 50));
262
504
  continue;
263
505
  }
264
- throw Object.assign(new Error(data?.statusMessage || data?.message || "Could not create the realtime checkpoint."), {
265
- data,
266
- statusCode: response.status
267
- });
506
+ return [realtimeErrorDiagnostics.REALTIME_REQUEST_FAILED({
507
+ action,
508
+ message,
509
+ status: response.status
510
+ }), void 0];
268
511
  }
512
+ } finally {
513
+ requestControllers.delete(controller);
514
+ refreshControllers.delete(controller);
515
+ }
516
+ }
517
+ async function requestResult(action, accepts) {
518
+ if (!enabled()) return [realtimeErrorDiagnostics.REALTIME_DISABLED({ action }), void 0];
519
+ const [error, data] = await request(action);
520
+ if (error) return [error, void 0];
521
+ return accepts(data) ? [void 0, data] : [realtimeErrorDiagnostics.REALTIME_INVALID_RESPONSE({ action }), void 0];
522
+ }
523
+ /**
524
+ * Saves the room through its document adapter now, including every edit this client has sent.
525
+ * Returns `[error, saved]`; `error.code` is a `RealtimeRequestErrorCode`.
526
+ */
527
+ async function save() {
528
+ if (!enabled()) return [realtimeErrorDiagnostics.REALTIME_DISABLED({ action: "save" }), void 0];
529
+ saveRequests.value++;
530
+ try {
531
+ return await requestResult("save", isRealtimeSaved);
532
+ } finally {
533
+ saveRequests.value--;
534
+ }
535
+ }
536
+ /**
537
+ * Saves the room and records a durable history entry through the document adapter.
538
+ * Returns `[error, checkpoint]`; `error.code` is a `RealtimeRequestErrorCode`.
539
+ */
540
+ async function checkpoint() {
541
+ if (!enabled()) return [realtimeErrorDiagnostics.REALTIME_DISABLED({ action: "checkpoint" }), void 0];
542
+ checkpointRequests.value++;
543
+ try {
544
+ return await requestResult("checkpoint", isRealtimeCheckpoint);
269
545
  } finally {
270
546
  checkpointRequests.value--;
271
547
  }
272
548
  }
549
+ /**
550
+ * Asks the room to compare its seed with the stored document. A changed source resets every client.
551
+ * Returns `[error, result]`; `error.code` is a `RealtimeRequestErrorCode`.
552
+ */
553
+ async function refresh() {
554
+ return await requestResult("refresh", isRefreshResult);
555
+ }
273
556
  watch([() => toValue(documentId), enabled], ([id, active]) => {
274
557
  destroyDocument();
275
558
  if (!active || !id || typeof window === "undefined") return;
276
- const nextDocument = markRaw(new Y.Doc());
277
- const nextProvider = new WebsocketProvider(`${window.location.protocol === "https:" ? "wss:" : "ws:"}//${window.location.host}${resolveRealtimeApplicationPath(`/api/_vitehub/realtime/${encodeURIComponent(definition)}`)}`, id.split("/").map(encodeURIComponent).join("/"), nextDocument, { disableBc: true });
278
- nextProvider.awareness.setLocalStateField("user", currentPerson(nextDocument.clientID));
279
- nextProvider.awareness.on("change", () => {
280
- if (provider.value === nextProvider) updatePeople(nextProvider);
281
- });
282
- updatePeople(nextProvider);
283
- nextProvider.on("status", (event) => {
284
- if (provider.value === nextProvider) status.value = event.status;
285
- });
286
- nextProvider.on("sync", (value) => {
287
- if (provider.value === nextProvider) synced.value = value;
288
- });
289
- document.value = nextDocument;
290
- provider.value = nextProvider;
291
- status.value = "connecting";
559
+ connect(id);
292
560
  }, { immediate: true });
561
+ if (!canConnect) onMounted(() => {
562
+ canConnect = true;
563
+ const current = provider.value;
564
+ if (!current) return;
565
+ status.value = "connecting";
566
+ current.connect();
567
+ });
293
568
  watch(enabled, (active) => {
294
569
  const current = workspaceProvider.value;
295
570
  if (!current) return;
@@ -299,7 +574,7 @@ function useRealtimeTiptap(definition, documentId, options = {}) {
299
574
  pendingWorkspaceChanges.length = 0;
300
575
  }
301
576
  }, { immediate: true });
302
- watch(user, () => {
577
+ watch(identity, () => {
303
578
  const current = provider.value;
304
579
  if (!current) return;
305
580
  current.awareness.setLocalStateField("user", currentPerson(current.doc.clientID));
@@ -308,9 +583,22 @@ function useRealtimeTiptap(definition, documentId, options = {}) {
308
583
  onScopeDispose(destroy);
309
584
  return {
310
585
  document,
311
- extensions: computed(() => document.value && provider.value ? [...createRealtimeEditorExtensions(), markRaw(index_default.configure({ fragment: markRaw(document.value.getXmlFragment("default")) }))] : []),
586
+ extensions: computed(() => document.value && provider.value ? [
587
+ ...createExtensions(),
588
+ markRaw(src_default.configure({ fragment: markRaw(document.value.getXmlFragment(realtimeDocumentLayout.body)) })),
589
+ ...createCarets(provider.value.awareness)
590
+ ] : []),
591
+ fields: computed(() => document.value?.getMap(realtimeDocumentLayout.fields)),
312
592
  people,
313
593
  provider,
594
+ /** The server rejects edits from this connection. `readOnlyReason` tells why; `saveStatus` holds the details. */
595
+ readOnly: computed(() => readOnlyReason.value !== null),
596
+ readOnlyReason,
597
+ refresh,
598
+ onReset,
599
+ save,
600
+ saveStatus,
601
+ saving: computed(() => saveRequests.value > 0),
314
602
  status,
315
603
  synced,
316
604
  history: {
@@ -325,4 +613,4 @@ function useRealtimeTiptap(definition, documentId, options = {}) {
325
613
  };
326
614
  }
327
615
  //#endregion
328
- export { useRealtimeTiptap };
616
+ export { RealtimeCaret, readRealtimeYDoc, useRealtimeTiptap };