@abraca/dabra 2.89.0 → 2.91.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.
Files changed (71) hide show
  1. package/package.json +5 -11
  2. package/src/AbracadabraBaseProvider.ts +0 -963
  3. package/src/AbracadabraClient.ts +0 -1960
  4. package/src/AbracadabraProvider.ts +0 -915
  5. package/src/AbracadabraWS.ts +0 -695
  6. package/src/BackgroundSyncManager.ts +0 -856
  7. package/src/BackgroundSyncPersistence.ts +0 -140
  8. package/src/ChatClient.ts +0 -314
  9. package/src/CloseEvents.ts +0 -49
  10. package/src/ContentManager.ts +0 -246
  11. package/src/CoverReconcile.ts +0 -168
  12. package/src/CryptoIdentityKeystore.ts +0 -754
  13. package/src/DeviceRegistrationService.ts +0 -257
  14. package/src/DocConverters.ts +0 -1859
  15. package/src/DocKeyManager.ts +0 -163
  16. package/src/DocTypes.ts +0 -628
  17. package/src/DocUtils.ts +0 -251
  18. package/src/DocumentCache.ts +0 -210
  19. package/src/DocumentManager.ts +0 -410
  20. package/src/E2EAbracadabraProvider.ts +0 -426
  21. package/src/E2EOfflineStore.ts +0 -55
  22. package/src/EncryptedChatClient.ts +0 -173
  23. package/src/EncryptedY.ts +0 -145
  24. package/src/EventEmitter.ts +0 -59
  25. package/src/FileBlobStore.ts +0 -569
  26. package/src/IdentityDoc.ts +0 -711
  27. package/src/IncomingMessage.ts +0 -63
  28. package/src/MessageReceiver.ts +0 -151
  29. package/src/MessageSender.ts +0 -22
  30. package/src/MetaManager.ts +0 -194
  31. package/src/MnemonicKeyDerivation.ts +0 -171
  32. package/src/NodeConnect.ts +0 -63
  33. package/src/NodeIdentity.ts +0 -378
  34. package/src/NotificationsClient.ts +0 -207
  35. package/src/OfflineStore.ts +0 -294
  36. package/src/OutgoingMessage.ts +0 -25
  37. package/src/OutgoingMessages/AuthenticationMessage.ts +0 -23
  38. package/src/OutgoingMessages/AwarenessMessage.ts +0 -41
  39. package/src/OutgoingMessages/CloseMessage.ts +0 -17
  40. package/src/OutgoingMessages/QueryAwarenessMessage.ts +0 -17
  41. package/src/OutgoingMessages/StatelessMessage.ts +0 -18
  42. package/src/OutgoingMessages/SubdocMessage.ts +0 -35
  43. package/src/OutgoingMessages/SyncStepOneMessage.ts +0 -25
  44. package/src/OutgoingMessages/SyncStepTwoMessage.ts +0 -25
  45. package/src/OutgoingMessages/UpdateMessage.ts +0 -20
  46. package/src/QueryClient.ts +0 -209
  47. package/src/RpcClient.ts +0 -659
  48. package/src/SchemaTypes.ts +0 -179
  49. package/src/SearchIndex.ts +0 -250
  50. package/src/ServerRegistry.ts +0 -220
  51. package/src/ServerReset.ts +0 -222
  52. package/src/TokenManager.ts +0 -337
  53. package/src/TreeManager.ts +0 -894
  54. package/src/TreeTimestamps.ts +0 -101
  55. package/src/auth.ts +0 -62
  56. package/src/awarenessStatesToArray.ts +0 -10
  57. package/src/index.ts +0 -219
  58. package/src/messageRecord.ts +0 -121
  59. package/src/sync/BroadcastChannelSync.ts +0 -235
  60. package/src/types.ts +0 -790
  61. package/src/webrtc/AbracadabraWebRTC.ts +0 -683
  62. package/src/webrtc/DataChannelRouter.ts +0 -179
  63. package/src/webrtc/DevicePairingChannel.ts +0 -496
  64. package/src/webrtc/E2EEChannel.ts +0 -195
  65. package/src/webrtc/FileTransferChannel.ts +0 -367
  66. package/src/webrtc/ManualSignaling.ts +0 -204
  67. package/src/webrtc/PeerConnection.ts +0 -133
  68. package/src/webrtc/SignalingSocket.ts +0 -378
  69. package/src/webrtc/YjsDataChannel.ts +0 -203
  70. package/src/webrtc/index.ts +0 -26
  71. package/src/webrtc/types.ts +0 -177
@@ -1,963 +0,0 @@
1
- import { awarenessStatesToArray } from "./awarenessStatesToArray.ts";
2
- import type { Event, MessageEvent } from "ws";
3
- import { Awareness, removeAwarenessStates } from "y-protocols/awareness";
4
- import * as Y from "yjs";
5
- import EventEmitter from "./EventEmitter.ts";
6
- import type { CompleteAbracadabraWSConfiguration } from "./AbracadabraWS.ts";
7
- import { AbracadabraWS } from "./AbracadabraWS.ts";
8
- import { IncomingMessage } from "./IncomingMessage.ts";
9
- import { MessageReceiver } from "./MessageReceiver.ts";
10
- import { MessageSender } from "./MessageSender.ts";
11
- import { AuthenticationMessage } from "./OutgoingMessages/AuthenticationMessage.ts";
12
- import { AwarenessMessage } from "./OutgoingMessages/AwarenessMessage.ts";
13
- import { StatelessMessage } from "./OutgoingMessages/StatelessMessage.ts";
14
- import { RpcClient } from "./RpcClient.ts";
15
- import { QueryClient } from "./QueryClient.ts";
16
- import type { QuerySpec, QuerySubscriptionHandlers, QuerySubscriptionHandle } from "./QueryClient.ts";
17
- import { QueryAwarenessMessage } from "./OutgoingMessages/QueryAwarenessMessage.ts";
18
- import { SyncStepOneMessage } from "./OutgoingMessages/SyncStepOneMessage.ts";
19
- import { UpdateMessage } from "./OutgoingMessages/UpdateMessage.ts";
20
- import type {
21
- AuthorizedScope,
22
- ConstructableOutgoingMessage,
23
- onAuthenticatedParameters,
24
- onAuthenticationFailedParameters,
25
- onWriteRejectedParameters,
26
- WriteRejectionKind,
27
- onAwarenessChangeParameters,
28
- onAwarenessUpdateParameters,
29
- onCloseParameters,
30
- onDisconnectParameters,
31
- onMessageParameters,
32
- onOpenParameters,
33
- onOutgoingMessageParameters,
34
- onReconnectedParameters,
35
- onServerErrorParameters,
36
- onStatelessParameters,
37
- onStatusParameters,
38
- onSyncedParameters,
39
- onUnsyncedChangesParameters,
40
- } from "./types.ts";
41
- // Value import (not `import type`): `WebSocketStatus` is a runtime string enum
42
- // read in scheduleResubscribe's connection check, not just a type annotation.
43
- import { WebSocketStatus } from "./types.ts";
44
-
45
- export type AbracadabraBaseProviderConfiguration = Required<
46
- Pick<CompleteAbracadabraBaseProviderConfiguration, "name">
47
- > &
48
- Partial<CompleteAbracadabraBaseProviderConfiguration> &
49
- (
50
- | (Required<Pick<CompleteAbracadabraWSConfiguration, "url">> &
51
- Partial<Pick<CompleteAbracadabraWSConfiguration, "preserveTrailingSlash">>)
52
- | Required<Pick<CompleteAbracadabraBaseProviderConfiguration, "websocketProvider">>
53
- );
54
-
55
- /** @deprecated Use AbracadabraBaseProviderConfiguration */
56
- export type HocuspocusProviderConfiguration = AbracadabraBaseProviderConfiguration;
57
-
58
- export interface CompleteAbracadabraBaseProviderConfiguration {
59
- /**
60
- * The identifier/name of your document
61
- */
62
- name: string;
63
- /**
64
- * The actual Y.js document
65
- */
66
- document: Y.Doc;
67
-
68
- /**
69
- * An Awareness instance to keep the presence state of all clients.
70
- *
71
- * You can disable sharing awareness information by passing `null`.
72
- * Note that having no awareness information shared across all connections will break our ping checks
73
- * and thus trigger reconnects. You should always have at least one Provider with enabled awareness per
74
- * socket connection, or ensure that the Provider receives messages before running into `AbracadabraWS.messageReconnectTimeout`.
75
- */
76
- awareness: Awareness | null;
77
-
78
- /**
79
- * A token that's sent to the backend for authentication purposes.
80
- */
81
- token: string | (() => string) | (() => Promise<string>) | null;
82
-
83
- /**
84
- * Abracadabra websocket provider
85
- */
86
- websocketProvider: AbracadabraWS;
87
-
88
- /**
89
- * Force syncing the document in the defined interval.
90
- */
91
- forceSyncInterval: false | number;
92
-
93
- onAuthenticated: (data: onAuthenticatedParameters) => void;
94
- onAuthenticationFailed: (data: onAuthenticationFailedParameters) => void;
95
- /**
96
- * The server refused a local change. See {@link onWriteRejectedParameters} —
97
- * the change is still queued, not lost.
98
- */
99
- onWriteRejected: (data: onWriteRejectedParameters) => void;
100
- onRateLimited: () => void;
101
- onOpen: (data: onOpenParameters) => void;
102
- onReconnected: (data: onReconnectedParameters) => void;
103
- onConnect: () => void;
104
- onStatus: (data: onStatusParameters) => void;
105
- onMessage: (data: onMessageParameters) => void;
106
- onOutgoingMessage: (data: onOutgoingMessageParameters) => void;
107
- onSynced: (data: onSyncedParameters) => void;
108
- onDisconnect: (data: onDisconnectParameters) => void;
109
- onClose: (data: onCloseParameters) => void;
110
- onDestroy: () => void;
111
- onAwarenessUpdate: (data: onAwarenessUpdateParameters) => void;
112
- onAwarenessChange: (data: onAwarenessChangeParameters) => void;
113
- onStateless: (data: onStatelessParameters) => void;
114
- onServerError: (data: onServerErrorParameters) => void;
115
- onUnsyncedChanges: (data: onUnsyncedChangesParameters) => void;
116
- }
117
-
118
- /** @deprecated Use CompleteAbracadabraBaseProviderConfiguration */
119
- export type CompleteHocuspocusProviderConfiguration = CompleteAbracadabraBaseProviderConfiguration;
120
-
121
- export class AwarenessError extends Error {
122
- code = 1001;
123
- }
124
-
125
- export class AbracadabraBaseProvider extends EventEmitter {
126
- public configuration: CompleteAbracadabraBaseProviderConfiguration = {
127
- name: "",
128
- // @ts-ignore
129
- document: undefined,
130
- // @ts-ignore
131
- awareness: undefined,
132
- token: null,
133
- forceSyncInterval: false,
134
- onAuthenticated: () => null,
135
- onAuthenticationFailed: () => null,
136
- onWriteRejected: () => null,
137
- onRateLimited: () => null,
138
- onOpen: () => null,
139
- onReconnected: () => null,
140
- onConnect: () => null,
141
- onMessage: () => null,
142
- onOutgoingMessage: () => null,
143
- onSynced: () => null,
144
- onStatus: () => null,
145
- onDisconnect: () => null,
146
- onClose: () => null,
147
- onDestroy: () => null,
148
- onAwarenessUpdate: () => null,
149
- onAwarenessChange: () => null,
150
- onStateless: () => null,
151
- onServerError: () => null,
152
- onUnsyncedChanges: () => null,
153
- };
154
-
155
- isSynced = false;
156
-
157
- unsyncedChanges = 0;
158
-
159
- isAuthenticated = false;
160
-
161
- /**
162
- * True once this provider has received at least one Authenticated frame
163
- * on the current socket lifetime. Used by `permissionDeniedHandler` to
164
- * tell apart "the entry doc is wrong / unreachable" (first frame is a
165
- * denial → config error, give up) from "a mid-session write was denied"
166
- * (server keeps the read subscription alive → don't kill the socket).
167
- * Reset on close.
168
- */
169
- private _hasEverAuthenticated = false;
170
-
171
- /**
172
- * True once this provider's socket has opened at least once. Used to fire
173
- * the `reconnected` event on every *subsequent* open (an actual reconnect)
174
- * but not the very first connect. Persists across closes — a reconnect is
175
- * still a reconnect even after the socket dropped.
176
- */
177
- private _hasOpenedBefore = false;
178
-
179
- /** Current WebSocket connection status. */
180
- get connectionStatus(): WebSocketStatus {
181
- return this.configuration.websocketProvider.status;
182
- }
183
-
184
- authorizedScope: AuthorizedScope | undefined = undefined;
185
-
186
- // @internal
187
- manageSocket = false;
188
-
189
- private _isAttached = false;
190
-
191
- /**
192
- * Bounded retry of a multiplexed child's INITIAL subscribe handshake after a
193
- * *transient* server denial. On a clustered server a just-created doc's row
194
- * (or its permission cascade) can be briefly invisible on the replica this
195
- * socket landed on; a dropped "send AUTH for this document first" ordering
196
- * yields the same denial. Before this, a child gave up permanently on the
197
- * first denial and was left with a blank body until a full reload re-ran the
198
- * handshake — exactly the "open a freshly-created doc, see only the title,
199
- * blinking dot, never syncs until reload" report. We instead replay the
200
- * subscribe a few times with backoff; the instant the server catches up the
201
- * child authenticates and syncs, no reconnect. Only ever fires for the
202
- * INITIAL subscribe (never a mid-session write denial) and is bounded, so a
203
- * genuinely forbidden/absent doc still settles into give-up, just later.
204
- */
205
- private static readonly MAX_RESUBSCRIBE_ATTEMPTS = 6;
206
- private _resubscribeAttempts = 0;
207
- private _resubscribeTimer: ReturnType<typeof setTimeout> | null = null;
208
-
209
- intervals: { forceSync: ReturnType<typeof setInterval> | null } = {
210
- forceSync: null,
211
- };
212
-
213
- /**
214
- * Lazily-constructed RPC v1 client. See `RpcClient`/`docs/rpc-v1.md`.
215
- * Bound to this provider's stateless transport, so calls and handlers
216
- * ride the doc this provider is subscribed to.
217
- */
218
- private _rpc: RpcClient | undefined;
219
- get rpc(): RpcClient {
220
- if (!this._rpc) {
221
- this._rpc = new RpcClient(this);
222
- }
223
- return this._rpc;
224
- }
225
-
226
- /**
227
- * Lazily-constructed V2 query subscription client. See
228
- * `QueryClient`. Each call to `subscribeQuery(...)` opens a
229
- * long-lived subscription that fires `onSnapshot` with the initial
230
- * result set and `onDelta` whenever the projection moves.
231
- */
232
- private _queryClient: QueryClient | undefined;
233
- private getQueryClient(): QueryClient {
234
- if (!this._queryClient) {
235
- this._queryClient = new QueryClient(this);
236
- }
237
- return this._queryClient;
238
- }
239
-
240
- /**
241
- * Open a live query subscription. Mirrors the v1 REST shape
242
- * (`POST /docs/query`) but pushes deltas as the server-side
243
- * projection drifts under the predicate.
244
- */
245
- subscribeQuery(
246
- spec: QuerySpec,
247
- handlers: QuerySubscriptionHandlers = {},
248
- ): QuerySubscriptionHandle {
249
- return this.getQueryClient().subscribeQuery(spec, handlers);
250
- }
251
-
252
- constructor(configuration: AbracadabraBaseProviderConfiguration) {
253
- super();
254
- this.setConfiguration(configuration);
255
-
256
- this.configuration.document = configuration.document ? configuration.document : new Y.Doc();
257
- this.configuration.awareness =
258
- configuration.awareness !== undefined
259
- ? configuration.awareness
260
- : new Awareness(this.document);
261
-
262
- // y-protocols' setLocalStateField silently no-ops when getLocalState() is null.
263
- // Seeding with {} once ensures the *first* setLocalStateField call from any
264
- // consumer (TipTap CollaborationCaret, DocumentManager, app code) actually
265
- // publishes — instead of vanishing without a trace. Idempotent for callers
266
- // that pass their own awareness instance with state already set.
267
- if (this.awareness && this.awareness.getLocalState() === null) {
268
- this.awareness.setLocalState({});
269
- }
270
-
271
- this.on("open", this.configuration.onOpen);
272
- this.on("reconnected", this.configuration.onReconnected);
273
- this.on("message", this.configuration.onMessage);
274
- this.on("outgoingMessage", this.configuration.onOutgoingMessage);
275
- this.on("synced", this.configuration.onSynced);
276
- this.on("destroy", this.configuration.onDestroy);
277
- this.on("awarenessUpdate", this.configuration.onAwarenessUpdate);
278
- this.on("awarenessChange", this.configuration.onAwarenessChange);
279
- this.on("stateless", this.configuration.onStateless);
280
- this.on("serverError", this.configuration.onServerError);
281
- this.on("unsyncedChanges", this.configuration.onUnsyncedChanges);
282
-
283
- this.on("authenticated", this.configuration.onAuthenticated);
284
- this.on("authenticationFailed", this.configuration.onAuthenticationFailed);
285
- this.on("writeRejected", this.configuration.onWriteRejected);
286
- this.on("rateLimited", this.configuration.onRateLimited);
287
-
288
- this.awareness?.on("update", () => {
289
- this.emit("awarenessUpdate", {
290
- states: awarenessStatesToArray(this.awareness!.getStates()),
291
- });
292
- });
293
-
294
- this.awareness?.on("change", () => {
295
- this.emit("awarenessChange", {
296
- states: awarenessStatesToArray(this.awareness!.getStates()),
297
- });
298
- });
299
-
300
- this.document.on("update", this.boundDocumentUpdateHandler);
301
- this.awareness?.on("update", this.boundAwarenessUpdateHandler);
302
-
303
- this.registerEventListeners();
304
-
305
- if (
306
- this.configuration.forceSyncInterval &&
307
- typeof this.configuration.forceSyncInterval === "number"
308
- ) {
309
- this.intervals.forceSync = setInterval(
310
- this.forceSync.bind(this),
311
- this.configuration.forceSyncInterval,
312
- );
313
- }
314
-
315
- if (this.manageSocket) {
316
- this.attach();
317
- }
318
- }
319
-
320
- boundDocumentUpdateHandler = this.documentUpdateHandler.bind(this);
321
-
322
- boundAwarenessUpdateHandler = this.awarenessUpdateHandler.bind(this);
323
-
324
- boundPageHide = this.pageHide.bind(this);
325
-
326
- boundOnOpen = this.onOpen.bind(this);
327
-
328
- boundOnClose = this.onClose.bind(this);
329
-
330
- forwardConnect = () => this.emit("connect");
331
-
332
- forwardStatus = (e: onStatusParameters) => this.emit("status", e);
333
-
334
- forwardClose = (e: onCloseParameters) => this.emit("close", e);
335
-
336
- forwardDisconnect = (e: onDisconnectParameters) => this.emit("disconnect", e);
337
-
338
- forwardDestroy = () => this.emit("destroy");
339
-
340
- forwardRateLimited = () => this.emit("rateLimited");
341
-
342
- public setConfiguration(configuration: Partial<AbracadabraBaseProviderConfiguration> = {}): void {
343
- if (!configuration.websocketProvider) {
344
- this.manageSocket = true;
345
- this.configuration.websocketProvider = new AbracadabraWS(
346
- configuration as CompleteAbracadabraWSConfiguration,
347
- );
348
- }
349
-
350
- this.configuration = { ...this.configuration, ...configuration };
351
- }
352
-
353
- get document() {
354
- return this.configuration.document;
355
- }
356
-
357
- public get isAttached() {
358
- return this._isAttached;
359
- }
360
-
361
- get awareness() {
362
- return this.configuration.awareness;
363
- }
364
-
365
- get hasUnsyncedChanges(): boolean {
366
- return this.unsyncedChanges > 0;
367
- }
368
-
369
- private resetUnsyncedChanges() {
370
- // The unsynced counter tracks pending UpdateMessage acks (decremented by
371
- // SyncStatusMessage). The handshake itself is a connection-level concern,
372
- // not a doc update — reflect that by resetting to 0. The synced flag and
373
- // status: 'connecting' already surface in-flight sync to the UI; bumping
374
- // this counter to 1 would leave it stuck (SyncStep2 doesn't decrement).
375
- this.unsyncedChanges = 0;
376
- this.emit("unsyncedChanges", { number: this.unsyncedChanges });
377
- }
378
-
379
- incrementUnsyncedChanges() {
380
- this.unsyncedChanges += 1;
381
- this.emit("unsyncedChanges", { number: this.unsyncedChanges });
382
- }
383
-
384
- decrementUnsyncedChanges() {
385
- if (this.unsyncedChanges > 0) {
386
- this.unsyncedChanges -= 1;
387
- }
388
-
389
- if (this.unsyncedChanges === 0) {
390
- this.synced = true;
391
- }
392
-
393
- this.emit("unsyncedChanges", { number: this.unsyncedChanges });
394
- }
395
-
396
- forceSync() {
397
- this.resetUnsyncedChanges();
398
-
399
- this.send(SyncStepOneMessage, {
400
- document: this.document,
401
- documentName: this.configuration.name,
402
- });
403
- }
404
-
405
- pageHide() {
406
- if (this.awareness) {
407
- removeAwarenessStates(this.awareness, [this.document.clientID], "page hide");
408
- }
409
- }
410
-
411
- registerEventListeners() {
412
- if (typeof window === "undefined" || !("addEventListener" in window)) {
413
- return;
414
- }
415
-
416
- window.addEventListener("pagehide", this.boundPageHide);
417
- }
418
-
419
- sendStateless(payload: string) {
420
- this.send(StatelessMessage, {
421
- documentName: this.configuration.name,
422
- payload,
423
- });
424
- }
425
-
426
- async sendToken() {
427
- let token: string | null;
428
- try {
429
- token = await this.getToken();
430
- } catch (error) {
431
- this.permissionDeniedHandler(`Failed to get token during sendToken(): ${error}`);
432
- return;
433
- }
434
-
435
- this.send(AuthenticationMessage, {
436
- token: token ?? "",
437
- documentName: this.configuration.name,
438
- });
439
- }
440
-
441
- documentUpdateHandler(update: Uint8Array, origin: any) {
442
- if (origin === this) {
443
- return;
444
- }
445
-
446
- // Don't push live updates over a connection that hasn't authenticated this
447
- // document yet. On the shared multiplexed socket, onOpen() does
448
- // `await sendToken()` before the doc's AUTH frame actually goes out; an edit
449
- // firing in that async window would race ahead of the AUTH frame and the
450
- // server rejects it with "not subscribed: send AUTH for this document
451
- // first". State is NOT lost: subclasses persist to the offline store before
452
- // calling super (and re-flush pending updates on `synced`), and the
453
- // post-AUTH SyncStep1/2 handshake conveys all local state regardless. So
454
- // skipping the live wire-send here is safe — it only closes the race.
455
- if (!this.isAuthenticated) {
456
- return;
457
- }
458
-
459
- this.incrementUnsyncedChanges();
460
- this.send(UpdateMessage, { update, documentName: this.configuration.name });
461
- }
462
-
463
- awarenessUpdateHandler({ added, updated, removed }: any, origin: any) {
464
- // Same AUTH-ordering guard as documentUpdateHandler. Awareness churn
465
- // (cursor / presence / focus) during the connect AUTH window must not race
466
- // ahead of the doc's AUTH frame. Awareness is ephemeral and re-sent in full
467
- // by startSync() immediately after AUTH plus on the next local change, so
468
- // dropping pre-auth awareness frames loses nothing.
469
- if (!this.isAuthenticated) {
470
- return;
471
- }
472
-
473
- const changedClients = added.concat(updated).concat(removed);
474
-
475
- this.send(AwarenessMessage, {
476
- awareness: this.awareness,
477
- clients: changedClients,
478
- documentName: this.configuration.name,
479
- });
480
- }
481
-
482
- /**
483
- * Indicates whether a first handshake with the server has been established
484
- *
485
- * Note: this does not mean all updates from the client have been persisted to the backend. For this,
486
- * use `hasUnsyncedChanges`.
487
- */
488
- get synced(): boolean {
489
- return this.isSynced;
490
- }
491
-
492
- set synced(state) {
493
- if (this.isSynced === state) {
494
- return;
495
- }
496
-
497
- this.isSynced = state;
498
-
499
- if (state) {
500
- // Defer the emit one microtask. Y.applyUpdate dispatches Y.Map /
501
- // Y.Array observer notifications via microtasks; emitting `synced`
502
- // synchronously would let listeners read `getArray("messages")` (or
503
- // any sub-type populated by the just-applied state) and see length
504
- // 0 even though the wire delivered the full state. Deferring one
505
- // microtask lets the observers run first so everyone reading after
506
- // the synced event sees the populated state.
507
- queueMicrotask(() => {
508
- // Re-check in case `synced` flipped back to false between the
509
- // mutation and this microtask (e.g. a reconnect aborted sync).
510
- if (this.isSynced) this.emit("synced", { state });
511
- });
512
- }
513
- }
514
-
515
- receiveStateless(payload: string) {
516
- try {
517
- const parsed = JSON.parse(payload);
518
- if (parsed?.type === "error" && parsed.source && parsed.code) {
519
- const { source, code, message, meta } = parsed;
520
- console.warn(`[Abracadabra] Server error: ${source} (${code}) — ${message}`, meta ?? "");
521
- this.emit("serverError", { source, code, message: message ?? "", meta });
522
- return;
523
- }
524
- } catch {
525
- // not JSON — fall through to generic stateless event
526
- }
527
- this.emit("stateless", { payload });
528
- }
529
-
530
- // not needed, but provides backward compatibility with e.g. lexical/yjs
531
- async connect() {
532
- if (this.manageSocket) {
533
- return this.configuration.websocketProvider.connect();
534
- }
535
-
536
- console.warn(
537
- "AbracadabraBaseProvider::connect() is deprecated and does not do anything. Please connect/disconnect on the websocketProvider, or attach/deattach providers.",
538
- );
539
- }
540
-
541
- disconnect() {
542
- if (this.manageSocket) {
543
- return this.configuration.websocketProvider.disconnect();
544
- }
545
-
546
- console.warn(
547
- "AbracadabraBaseProvider::disconnect() is deprecated and does not do anything. Please connect/disconnect on the websocketProvider, or attach/deattach providers.",
548
- );
549
- }
550
-
551
- /**
552
- * Force the underlying socket to drop and reconnect on the SAME Y.Doc.
553
- *
554
- * Unlike destroying and re-creating the provider, the document is never
555
- * replaced — so every `observe`/`observeDeep` listener attached to it (and
556
- * its subdocs) keeps firing once the socket comes back. This also revives a
557
- * socket that a permanent permission-denial gave up on (see
558
- * {@link permissionDeniedHandler}). Pair it with a freshly-minted token (the
559
- * `token` callback is re-invoked on every reconnect) when healing a drop that
560
- * was caused by an expired JWT.
561
- *
562
- * Every provider multiplexed onto this socket is marked unsynced so a
563
- * subsequent `waitForSync` actually waits for the post-reconnect handshake
564
- * instead of short-circuiting on the stale `isSynced` flag.
565
- *
566
- * No-op (with a warning) for a provider on a shared, externally-managed
567
- * socket — reconnect the owning `websocketProvider` directly in that case.
568
- */
569
- reconnect() {
570
- if (!this.manageSocket) {
571
- console.warn(
572
- "AbracadabraBaseProvider::reconnect() — this provider shares an externally-managed socket; call reconnect() on the websocketProvider instead.",
573
- );
574
- return;
575
- }
576
-
577
- // Reset the synced flag of every provider on this socket BEFORE recycling
578
- // it. `cleanupWebSocket` tears the socket down silently (no close event),
579
- // so the providers' own `onClose` won't run to flip `synced` — do it here.
580
- for (const provider of this.configuration.websocketProvider.configuration.providerMap.values()) {
581
- provider.synced = false;
582
- provider.isAuthenticated = false;
583
- }
584
-
585
- return this.configuration.websocketProvider.reconnect();
586
- }
587
-
588
- async onOpen(event: Event) {
589
- const isReopen = this._hasOpenedBefore;
590
- this._hasOpenedBefore = true;
591
- this.isAuthenticated = false;
592
-
593
- this.emit("open", { event });
594
- // A subsequent open means the socket dropped and came back — let consumers
595
- // re-reconcile. Observers on `document` survive regardless (the doc is
596
- // never replaced); this is the explicit signal for catch-up work.
597
- if (isReopen) {
598
- this.emit("reconnected", { event });
599
- }
600
- await this.sendToken();
601
- this.startSync();
602
- }
603
-
604
- async getToken() {
605
- if (typeof this.configuration.token === "function") {
606
- const token = await this.configuration.token();
607
- return token;
608
- }
609
-
610
- return this.configuration.token;
611
- }
612
-
613
- startSync() {
614
- this.resetUnsyncedChanges();
615
-
616
- this.send(SyncStepOneMessage, {
617
- document: this.document,
618
- documentName: this.configuration.name,
619
- });
620
-
621
- if (this.awareness && this.awareness.getLocalState() !== null) {
622
- this.send(AwarenessMessage, {
623
- awareness: this.awareness,
624
- clients: [this.document.clientID],
625
- documentName: this.configuration.name,
626
- });
627
- }
628
-
629
- // Pull existing peers' awareness on (re)connect. The server keeps no
630
- // awareness cache and never replays presence to a fresh joiner, so without
631
- // this a late-joining client only learns about a peer once that peer next
632
- // *changes* its own awareness — producing asymmetric presence ("A sees B
633
- // but B can't see A"). The server re-broadcasts this query to all peers,
634
- // who answer with their full state (MessageReceiver.applyQueryAwareness),
635
- // and those replies fan back to us. Matches stock y-websocket on-open
636
- // behaviour. Only meaningful when an awareness instance exists.
637
- if (this.awareness) {
638
- this.send(QueryAwarenessMessage, {
639
- documentName: this.configuration.name,
640
- });
641
- }
642
- }
643
-
644
- send(message: ConstructableOutgoingMessage, args: any) {
645
- if (!this._isAttached) return;
646
-
647
- const messageSender = new MessageSender(message, args);
648
-
649
- this.emit("outgoingMessage", { message: messageSender.message });
650
- messageSender.send(this.configuration.websocketProvider);
651
- }
652
-
653
- onMessage(event: MessageEvent) {
654
- const message = new IncomingMessage(event.data);
655
-
656
- const documentName = message.readVarString();
657
-
658
- message.writeVarString(documentName);
659
-
660
- this.emit("message", { event, message: new IncomingMessage(event.data) });
661
-
662
- new MessageReceiver(message).apply(this, true);
663
- }
664
-
665
- onClose() {
666
- this.isAuthenticated = false;
667
- this.synced = false;
668
- // Reset per-socket-lifetime auth flag so the next connection's
669
- // permissionDeniedHandler can correctly identify a fresh-connection
670
- // denial as a config error.
671
- this._hasEverAuthenticated = false;
672
- // The socket's own reconnect re-runs onOpen → subscribe for every doc, so
673
- // any in-flight initial-subscribe retry from this lifetime is moot.
674
- this.clearResubscribe();
675
-
676
- // update awareness (all users except local left)
677
- if (this.awareness) {
678
- removeAwarenessStates(
679
- this.awareness,
680
- Array.from(this.awareness.getStates().keys()).filter(
681
- (client) => client !== this.document.clientID,
682
- ),
683
- this,
684
- );
685
- }
686
- }
687
-
688
- destroy() {
689
- this.emit("destroy");
690
-
691
- if (this._rpc) {
692
- // Keep the (now-destroyed) RpcClient bound to `_rpc` rather than
693
- // setting it back to `undefined`. The lazy getter would otherwise
694
- // construct a fresh client wired against a provider whose listeners
695
- // are gone, leaving any subsequent `rpc.call(...)` to hang forever.
696
- // The client's own `destroyed` flag now turns `call()` into an
697
- // immediate `CANCELLED` rejection — the right terminal outcome.
698
- this._rpc.destroy();
699
- }
700
-
701
- if (this.intervals.forceSync) {
702
- clearInterval(this.intervals.forceSync);
703
- }
704
-
705
- if (this.awareness) {
706
- removeAwarenessStates(this.awareness, [this.document.clientID], "provider destroy");
707
- this.awareness.off("update", this.boundAwarenessUpdateHandler);
708
- this.awareness.destroy();
709
- }
710
-
711
- this.document.off("update", this.boundDocumentUpdateHandler);
712
-
713
- this.removeAllListeners();
714
-
715
- this.detach();
716
-
717
- if (this.manageSocket) {
718
- this.configuration.websocketProvider.destroy();
719
- }
720
-
721
- if (typeof window === "undefined" || !("removeEventListener" in window)) {
722
- return;
723
- }
724
-
725
- window.removeEventListener("pagehide", this.boundPageHide);
726
- }
727
-
728
- detach() {
729
- this.configuration.websocketProvider.off("connect", this.configuration.onConnect);
730
- this.configuration.websocketProvider.off("connect", this.forwardConnect);
731
-
732
- this.configuration.websocketProvider.off("status", this.forwardStatus);
733
- this.configuration.websocketProvider.off("status", this.configuration.onStatus);
734
-
735
- this.configuration.websocketProvider.off("open", this.boundOnOpen);
736
- this.configuration.websocketProvider.off("close", this.boundOnClose);
737
- this.configuration.websocketProvider.off("close", this.configuration.onClose);
738
- this.configuration.websocketProvider.off("close", this.forwardClose);
739
- this.configuration.websocketProvider.off("disconnect", this.configuration.onDisconnect);
740
- this.configuration.websocketProvider.off("disconnect", this.forwardDisconnect);
741
- this.configuration.websocketProvider.off("destroy", this.configuration.onDestroy);
742
- this.configuration.websocketProvider.off("destroy", this.forwardDestroy);
743
-
744
- this.configuration.websocketProvider.off("rateLimited", this.forwardRateLimited);
745
-
746
- this.configuration.websocketProvider.detach(this);
747
-
748
- this._isAttached = false;
749
- this.clearResubscribe();
750
- }
751
-
752
- attach() {
753
- if (this._isAttached) return;
754
-
755
- this.configuration.websocketProvider.on("connect", this.configuration.onConnect);
756
- this.configuration.websocketProvider.on("connect", this.forwardConnect);
757
-
758
- this.configuration.websocketProvider.on("status", this.configuration.onStatus);
759
- this.configuration.websocketProvider.on("status", this.forwardStatus);
760
-
761
- this.configuration.websocketProvider.on("open", this.boundOnOpen);
762
-
763
- this.configuration.websocketProvider.on("close", this.boundOnClose);
764
- this.configuration.websocketProvider.on("close", this.configuration.onClose);
765
- this.configuration.websocketProvider.on("close", this.forwardClose);
766
-
767
- this.configuration.websocketProvider.on("disconnect", this.configuration.onDisconnect);
768
- this.configuration.websocketProvider.on("disconnect", this.forwardDisconnect);
769
-
770
- this.configuration.websocketProvider.on("destroy", this.configuration.onDestroy);
771
- this.configuration.websocketProvider.on("destroy", this.forwardDestroy);
772
-
773
- this.configuration.websocketProvider.on("rateLimited", this.forwardRateLimited);
774
-
775
- // Mark attached BEFORE registering with the socket: when the shared
776
- // socket is already connected (the loadChild case), wsp.attach()
777
- // synchronously invokes onOpen() → sendToken(), and send() drops frames
778
- // while _isAttached is false. With a crypto identity OBJECT sendToken()
779
- // hits no await before send(), so the AUTH frame was silently swallowed
780
- // and the doc never authenticated on the connection — the server then
781
- // (correctly) ignored every subsequent frame for it: child providers
782
- // never synced and their writes were dropped. (JWT auth only survived
783
- // by accident: `await getToken()` defers send() past attach().)
784
- this._isAttached = true;
785
-
786
- this.configuration.websocketProvider.attach(this);
787
- }
788
-
789
- permissionDeniedHandler(reason: string) {
790
- // A denial that arrives on a socket which has already authenticated AND
791
- // synced this document is not an authentication problem — it is a write
792
- // that was refused (see the mid-session note below). Surface it as one so
793
- // app code has something to listen to that is not `authenticationFailed`,
794
- // which on a shared socket is usually about somebody else's document.
795
- if (this._hasEverAuthenticated && this.isSynced) {
796
- this.reportWriteRejected(reason, "permission");
797
- }
798
-
799
- this.emit("authenticationFailed", { reason });
800
- this.isAuthenticated = false;
801
-
802
- // Stop the reconnect loop on a permanent denial. Without this the WS
803
- // closes after every server-side rejection, AbracadabraWS schedules a
804
- // retry, the new connection sends the same Subscribe → server denies
805
- // again, ad infinitum (CPU/log/network spam, page looks "broken" to
806
- // the user). The dominant cases here:
807
- // * "document not found" — entry-doc-id pinned to something that
808
- // doesn't exist on this server
809
- // * initial "permission denied" — operator never granted access
810
- // Both are config issues; retrying won't fix them.
811
- //
812
- // BUT — once we've successfully authenticated at least once on this
813
- // socket, a permission_denied frame means a *mid-session* operation
814
- // was rejected (e.g. a write attempt on a doc the user only has read
815
- // on, or a Forbidden surfaced from defense-in-depth). The server
816
- // keeps the read subscription alive in that case (see ws.rs handling
817
- // of Error::Forbidden), so killing the socket would be a regression:
818
- // it tears down every other doc's sync just because one write was
819
- // denied. Skip the disconnect here and let the affected operation
820
- // surface its own error.
821
- //
822
- // We only stop the socket when this provider OWNS it (`manageSocket`);
823
- // shared sockets (e.g. multiplexed child providers) leave the parent's
824
- // lifecycle alone and just give up on this doc.
825
- if (this.manageSocket && !this._hasEverAuthenticated) {
826
- try {
827
- this.configuration.websocketProvider.disconnect();
828
- }
829
- catch { /* WS may already be torn down — best effort */ }
830
- }
831
-
832
- // Transient-denial recovery (see _resubscribeAttempts doc). Fires only for
833
- // a multiplexed child (shared socket; the root is handled above) that has
834
- // NOT yet completed its initial sync, and only for denials whose reason is
835
- // transient — "document not found" (a just-created doc whose row/permission
836
- // is briefly invisible on the replica this socket hit) or "not subscribed"
837
- // (a dropped AUTH-ordering). We deliberately do NOT key off
838
- // `_hasEverAuthenticated`: the server sends AUTHENTICATED *before* it runs
839
- // the initial sync, so a not-found denial lands after that flag is already
840
- // set. `!isSynced` is the true "never got my content" signal and also
841
- // excludes mid-session write denials (those docs are already synced).
842
- // Permanent denials ("permission denied"/"write permission denied") are
843
- // NOT matched, so a genuinely forbidden doc still gives up immediately.
844
- if (
845
- !this.manageSocket &&
846
- !this.isSynced &&
847
- this._isAttached &&
848
- this._resubscribeAttempts < AbracadabraBaseProvider.MAX_RESUBSCRIBE_ATTEMPTS &&
849
- AbracadabraBaseProvider.isTransientSubscribeDenial(reason)
850
- ) {
851
- this.scheduleResubscribe();
852
- }
853
- }
854
-
855
- /**
856
- * The most recent write the server refused, or `null` if it has never
857
- * refused one on this provider. Kept as state (not just an event) because
858
- * the common consumer question is "is my last edit actually saved?", which
859
- * an event fired before the component mounted cannot answer.
860
- */
861
- public lastWriteRejection: onWriteRejectedParameters | null = null;
862
-
863
- /** Count of refused writes over this provider's lifetime. */
864
- public writeRejectionCount = 0;
865
-
866
- /**
867
- * Record and announce a server-refused local change.
868
- *
869
- * Called from both nack paths: the permission-denied auth frame and
870
- * `SyncStatus(applied=0)`. Deliberately does NOT touch the unsynced counter
871
- * — the update stays queued so a retry can land it once the cause is fixed.
872
- */
873
- reportWriteRejected(reason: string, kind: WriteRejectionKind) {
874
- const data: onWriteRejectedParameters = {
875
- documentName: this.configuration.name,
876
- reason,
877
- kind,
878
- };
879
- this.lastWriteRejection = data;
880
- this.writeRejectionCount += 1;
881
- this.emit("writeRejected", data);
882
- }
883
-
884
- /**
885
- * Whether a permission-denied reason reflects a *transient* server condition
886
- * a retry can clear (a freshly-created doc not yet visible on this replica, or
887
- * a dropped subscribe-ordering) rather than a permanent authorization failure.
888
- */
889
- private static isTransientSubscribeDenial(reason: string): boolean {
890
- const r = reason.toLowerCase();
891
- return r.includes("not found") || r.includes("not subscribed");
892
- }
893
-
894
- /**
895
- * Schedule one backed-off replay of the initial subscribe handshake. A single
896
- * timer is in flight at a time; each denial that slips past the guard above
897
- * arms the next attempt until {@link MAX_RESUBSCRIBE_ATTEMPTS} is reached.
898
- */
899
- private scheduleResubscribe() {
900
- if (this._resubscribeTimer) return;
901
- const attempt = this._resubscribeAttempts++;
902
- // 250, 500, 1000, 2000, 4000, 4000 ms — recovers within ~750ms for a
903
- // typical sub-second replica lag, ~11s total before final give-up.
904
- const delay = Math.min(4000, 250 * 2 ** attempt);
905
- this._resubscribeTimer = setTimeout(() => {
906
- this._resubscribeTimer = null;
907
- // Bail if anything changed under us: detached, already recovered, or the
908
- // socket dropped (its reconnect re-runs onOpen for every doc anyway).
909
- // `isSynced` — not the auth flags — is the success signal: the server
910
- // sends AUTHENTICATED *before* the initial-sync attempt, so a not-found
911
- // denial leaves isAuthenticated/_hasEverAuthenticated set yet unsynced;
912
- // bailing on those would (and did) skip the very retry we scheduled.
913
- if (
914
- !this._isAttached ||
915
- this.isSynced ||
916
- this.connectionStatus !== WebSocketStatus.Connected
917
- ) {
918
- return;
919
- }
920
- // Replay onOpen's subscribe: re-send AUTH (server re-runs subscribe_doc,
921
- // now that the doc/permission may be visible) then SyncStep1.
922
- void this.sendToken()
923
- .then(() => {
924
- if (this._isAttached && !this.isAuthenticated) this.startSync();
925
- })
926
- .catch(() => { /* a fresh denial re-enters permissionDeniedHandler */ });
927
- }, delay);
928
- }
929
-
930
- /** Cancel any pending resubscribe and reset the attempt budget. */
931
- private clearResubscribe() {
932
- if (this._resubscribeTimer) {
933
- clearTimeout(this._resubscribeTimer);
934
- this._resubscribeTimer = null;
935
- }
936
- this._resubscribeAttempts = 0;
937
- }
938
-
939
- authenticatedHandler(scope: string) {
940
- this.isAuthenticated = true;
941
- this._hasEverAuthenticated = true;
942
- this.authorizedScope = scope as AuthorizedScope;
943
- // Initial subscribe succeeded (possibly via a resubscribe retry) — stop
944
- // retrying and restore the budget for a future socket lifetime.
945
- this.clearResubscribe();
946
-
947
- this.emit("authenticated", { scope });
948
- }
949
-
950
- setAwarenessField(key: string, value: any) {
951
- if (!this.awareness) {
952
- throw new AwarenessError(
953
- `Cannot set awareness field "${key}" to ${JSON.stringify(value)}. You have disabled Awareness for this provider by explicitly passing awareness: null in the provider configuration.`,
954
- );
955
- }
956
- this.awareness.setLocalStateField(key, value);
957
- }
958
- }
959
-
960
- /** @deprecated Use AbracadabraBaseProvider */
961
- export const HocuspocusProvider = AbracadabraBaseProvider;
962
- /** @deprecated Use AbracadabraBaseProvider */
963
- export type HocuspocusProvider = AbracadabraBaseProvider;