@abraca/dabra 2.101.0 → 2.103.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 (151) hide show
  1. package/dist/abracadabra-provider.cjs +6673 -6543
  2. package/dist/abracadabra-provider.cjs.map +1 -1
  3. package/dist/esm/AbracadabraBaseProvider.js +558 -0
  4. package/dist/esm/AbracadabraBaseProvider.js.map +1 -0
  5. package/dist/esm/AbracadabraClient.js +1424 -0
  6. package/dist/esm/AbracadabraClient.js.map +1 -0
  7. package/dist/esm/AbracadabraProvider.js +547 -0
  8. package/dist/esm/AbracadabraProvider.js.map +1 -0
  9. package/dist/esm/AbracadabraWS.js +398 -0
  10. package/dist/esm/AbracadabraWS.js.map +1 -0
  11. package/dist/esm/BackgroundSyncManager.js +571 -0
  12. package/dist/esm/BackgroundSyncManager.js.map +1 -0
  13. package/dist/esm/BackgroundSyncPersistence.js +62 -0
  14. package/dist/esm/BackgroundSyncPersistence.js.map +1 -0
  15. package/dist/esm/ChatClient.js +176 -0
  16. package/dist/esm/ChatClient.js.map +1 -0
  17. package/dist/esm/CloseEvents.js +45 -0
  18. package/dist/esm/CloseEvents.js.map +1 -0
  19. package/dist/esm/ContentManager.js +153 -0
  20. package/dist/esm/ContentManager.js.map +1 -0
  21. package/dist/esm/CoverReconcile.js +124 -0
  22. package/dist/esm/CoverReconcile.js.map +1 -0
  23. package/dist/esm/CryptoIdentityKeystore.js +580 -0
  24. package/dist/esm/CryptoIdentityKeystore.js.map +1 -0
  25. package/dist/esm/DeviceRegistrationService.js +158 -0
  26. package/dist/esm/DeviceRegistrationService.js.map +1 -0
  27. package/dist/esm/DocConverters.js +1300 -0
  28. package/dist/esm/DocConverters.js.map +1 -0
  29. package/dist/esm/DocKeyManager.js +145 -0
  30. package/dist/esm/DocKeyManager.js.map +1 -0
  31. package/dist/esm/DocTypes.js +792 -0
  32. package/dist/esm/DocTypes.js.map +1 -0
  33. package/dist/esm/DocUtils.js +180 -0
  34. package/dist/esm/DocUtils.js.map +1 -0
  35. package/dist/esm/DocumentCache.js +131 -0
  36. package/dist/esm/DocumentCache.js.map +1 -0
  37. package/dist/esm/DocumentManager.js +240 -0
  38. package/dist/esm/DocumentManager.js.map +1 -0
  39. package/dist/esm/E2EAbracadabraProvider.js +273 -0
  40. package/dist/esm/E2EAbracadabraProvider.js.map +1 -0
  41. package/dist/esm/E2EOfflineStore.js +53 -0
  42. package/dist/esm/E2EOfflineStore.js.map +1 -0
  43. package/dist/esm/EncryptedChatClient.js +156 -0
  44. package/dist/esm/EncryptedChatClient.js.map +1 -0
  45. package/dist/esm/EncryptedY.js +115 -0
  46. package/dist/esm/EncryptedY.js.map +1 -0
  47. package/dist/esm/EventEmitter.js +40 -0
  48. package/dist/esm/EventEmitter.js.map +1 -0
  49. package/dist/esm/FileBlobStore.js +410 -0
  50. package/dist/esm/FileBlobStore.js.map +1 -0
  51. package/dist/esm/IdentityDoc.js +413 -0
  52. package/dist/esm/IdentityDoc.js.map +1 -0
  53. package/dist/esm/IncomingMessage.js +39 -0
  54. package/dist/esm/IncomingMessage.js.map +1 -0
  55. package/dist/esm/LifecycleGate.js +124 -0
  56. package/dist/esm/LifecycleGate.js.map +1 -0
  57. package/dist/esm/MessageReceiver.js +86 -0
  58. package/dist/esm/MessageReceiver.js.map +1 -0
  59. package/dist/esm/MessageSender.js +19 -0
  60. package/dist/esm/MessageSender.js.map +1 -0
  61. package/dist/esm/MetaManager.js +112 -0
  62. package/dist/esm/MetaManager.js.map +1 -0
  63. package/dist/esm/MnemonicKeyDerivation.js +137 -0
  64. package/dist/esm/MnemonicKeyDerivation.js.map +1 -0
  65. package/dist/esm/NodeConnect.js +63 -0
  66. package/dist/esm/NodeConnect.js.map +1 -0
  67. package/dist/esm/NodeIdentity.js +212 -0
  68. package/dist/esm/NodeIdentity.js.map +1 -0
  69. package/dist/esm/NotificationsClient.js +136 -0
  70. package/dist/esm/NotificationsClient.js.map +1 -0
  71. package/dist/esm/OfflineStore.js +291 -0
  72. package/dist/esm/OfflineStore.js.map +1 -0
  73. package/dist/esm/OutgoingMessage.js +18 -0
  74. package/dist/esm/OutgoingMessage.js.map +1 -0
  75. package/dist/esm/OutgoingMessages/AuthenticationMessage.js +24 -0
  76. package/dist/esm/OutgoingMessages/AuthenticationMessage.js.map +1 -0
  77. package/dist/esm/OutgoingMessages/AwarenessMessage.js +28 -0
  78. package/dist/esm/OutgoingMessages/AwarenessMessage.js.map +1 -0
  79. package/dist/esm/OutgoingMessages/CloseMessage.js +21 -0
  80. package/dist/esm/OutgoingMessages/CloseMessage.js.map +1 -0
  81. package/dist/esm/OutgoingMessages/QueryAwarenessMessage.js +21 -0
  82. package/dist/esm/OutgoingMessages/QueryAwarenessMessage.js.map +1 -0
  83. package/dist/esm/OutgoingMessages/StatelessMessage.js +22 -0
  84. package/dist/esm/OutgoingMessages/StatelessMessage.js.map +1 -0
  85. package/dist/esm/OutgoingMessages/SubdocMessage.js +34 -0
  86. package/dist/esm/OutgoingMessages/SubdocMessage.js.map +1 -0
  87. package/dist/esm/OutgoingMessages/SyncStepOneMessage.js +24 -0
  88. package/dist/esm/OutgoingMessages/SyncStepOneMessage.js.map +1 -0
  89. package/dist/esm/OutgoingMessages/UpdateMessage.js +23 -0
  90. package/dist/esm/OutgoingMessages/UpdateMessage.js.map +1 -0
  91. package/dist/esm/PerfCounters.js +336 -0
  92. package/dist/esm/PerfCounters.js.map +1 -0
  93. package/dist/esm/QueryClient.js +117 -0
  94. package/dist/esm/QueryClient.js.map +1 -0
  95. package/dist/esm/RpcClient.js +456 -0
  96. package/dist/esm/RpcClient.js.map +1 -0
  97. package/dist/esm/SchemaTypes.js +38 -0
  98. package/dist/esm/SchemaTypes.js.map +1 -0
  99. package/dist/esm/SearchIndex.js +167 -0
  100. package/dist/esm/SearchIndex.js.map +1 -0
  101. package/dist/esm/ServerRegistry.js +139 -0
  102. package/dist/esm/ServerRegistry.js.map +1 -0
  103. package/dist/esm/ServerReset.js +170 -0
  104. package/dist/esm/ServerReset.js.map +1 -0
  105. package/dist/esm/TokenManager.js +236 -0
  106. package/dist/esm/TokenManager.js.map +1 -0
  107. package/dist/esm/TreeManager.js +655 -0
  108. package/dist/esm/TreeManager.js.map +1 -0
  109. package/dist/esm/TreeTimestamps.js +61 -0
  110. package/dist/esm/TreeTimestamps.js.map +1 -0
  111. package/dist/esm/auth.js +43 -0
  112. package/dist/esm/auth.js.map +1 -0
  113. package/dist/esm/awarenessStatesToArray.js +13 -0
  114. package/dist/esm/awarenessStatesToArray.js.map +1 -0
  115. package/dist/esm/docIds.js +53 -0
  116. package/dist/esm/docIds.js.map +1 -0
  117. package/dist/esm/encryptedContent.js +21 -0
  118. package/dist/esm/encryptedContent.js.map +1 -0
  119. package/dist/esm/index.js +61 -0
  120. package/dist/esm/messageRecord.js +64 -0
  121. package/dist/esm/messageRecord.js.map +1 -0
  122. package/dist/esm/sync/BroadcastChannelSync.js +160 -0
  123. package/dist/esm/sync/BroadcastChannelSync.js.map +1 -0
  124. package/dist/esm/types.js +54 -0
  125. package/dist/esm/types.js.map +1 -0
  126. package/dist/esm/webrtc/AbracadabraWebRTC.js +483 -0
  127. package/dist/esm/webrtc/AbracadabraWebRTC.js.map +1 -0
  128. package/dist/esm/webrtc/DataChannelRouter.js +124 -0
  129. package/dist/esm/webrtc/DataChannelRouter.js.map +1 -0
  130. package/dist/esm/webrtc/DevicePairingChannel.js +335 -0
  131. package/dist/esm/webrtc/DevicePairingChannel.js.map +1 -0
  132. package/dist/esm/webrtc/E2EEChannel.js +137 -0
  133. package/dist/esm/webrtc/E2EEChannel.js.map +1 -0
  134. package/dist/esm/webrtc/FileTransferChannel.js +250 -0
  135. package/dist/esm/webrtc/FileTransferChannel.js.map +1 -0
  136. package/dist/esm/webrtc/ManualSignaling.js +161 -0
  137. package/dist/esm/webrtc/ManualSignaling.js.map +1 -0
  138. package/dist/esm/webrtc/PeerConnection.js +96 -0
  139. package/dist/esm/webrtc/PeerConnection.js.map +1 -0
  140. package/dist/esm/webrtc/SignalingSocket.js +274 -0
  141. package/dist/esm/webrtc/SignalingSocket.js.map +1 -0
  142. package/dist/esm/webrtc/YjsDataChannel.js +135 -0
  143. package/dist/esm/webrtc/YjsDataChannel.js.map +1 -0
  144. package/dist/esm/webrtc/types.js +29 -0
  145. package/dist/esm/webrtc/types.js.map +1 -0
  146. package/dist/esm/x25519Convert.js +69 -0
  147. package/dist/esm/x25519Convert.js.map +1 -0
  148. package/dist/index.d.ts +26 -11
  149. package/package.json +6 -4
  150. package/dist/abracadabra-provider.esm.js +0 -14860
  151. package/dist/abracadabra-provider.esm.js.map +0 -1
@@ -0,0 +1,398 @@
1
+ import EventEmitter from "./EventEmitter.js";
2
+ import { WebSocketStatus, WsReadyStates } from "./types.js";
3
+ import { getLifecycleGate } from "./LifecycleGate.js";
4
+ import { IncomingMessage } from "./IncomingMessage.js";
5
+ import { CloseMessage } from "./OutgoingMessages/CloseMessage.js";
6
+ import { retry } from "@lifeomic/attempt";
7
+ import * as time from "lib0/time";
8
+
9
+ //#region packages/provider/src/AbracadabraWS.ts
10
+ var AbracadabraWS = class extends EventEmitter {
11
+ constructor(configuration) {
12
+ super();
13
+ this.messageQueue = [];
14
+ this.configuration = {
15
+ url: "",
16
+ autoConnect: true,
17
+ preserveTrailingSlash: false,
18
+ document: void 0,
19
+ WebSocketPolyfill: void 0,
20
+ messageReconnectTimeout: 3e4,
21
+ delay: 1e3,
22
+ initialDelay: 0,
23
+ factor: 2,
24
+ maxAttempts: 0,
25
+ minDelay: 1e3,
26
+ maxDelay: 3e4,
27
+ jitter: true,
28
+ timeout: 0,
29
+ onOpen: () => null,
30
+ onConnect: () => null,
31
+ onMessage: () => null,
32
+ onOutgoingMessage: () => null,
33
+ onStatus: () => null,
34
+ onDisconnect: () => null,
35
+ onClose: () => null,
36
+ onDestroy: () => null,
37
+ onAwarenessUpdate: () => null,
38
+ onAwarenessChange: () => null,
39
+ handleTimeout: null,
40
+ providerMap: /* @__PURE__ */ new Map()
41
+ };
42
+ this.webSocket = null;
43
+ this.webSocketHandlers = {};
44
+ this.shouldConnect = true;
45
+ this.status = WebSocketStatus.Disconnected;
46
+ this.lastMessageReceived = 0;
47
+ this.identifier = 0;
48
+ this.intervals = { connectionChecker: null };
49
+ this.connectionAttempt = null;
50
+ this.onlineListener = null;
51
+ this.offlineListener = null;
52
+ this.unsubscribeLifecycle = null;
53
+ this.receivedOnOpenPayload = void 0;
54
+ this.closeTries = 0;
55
+ this.lastRefreshToken = null;
56
+ this.setConfiguration(configuration);
57
+ this.configuration.WebSocketPolyfill = configuration.WebSocketPolyfill ? configuration.WebSocketPolyfill : globalThis.WebSocket;
58
+ this.on("open", this.configuration.onOpen);
59
+ this.on("open", this.onOpen.bind(this));
60
+ this.on("connect", this.configuration.onConnect);
61
+ this.on("message", this.configuration.onMessage);
62
+ this.on("outgoingMessage", this.configuration.onOutgoingMessage);
63
+ this.on("status", this.configuration.onStatus);
64
+ this.on("disconnect", this.configuration.onDisconnect);
65
+ this.on("close", this.configuration.onClose);
66
+ this.on("destroy", this.configuration.onDestroy);
67
+ this.on("awarenessUpdate", this.configuration.onAwarenessUpdate);
68
+ this.on("awarenessChange", this.configuration.onAwarenessChange);
69
+ this.on("close", this.onClose.bind(this));
70
+ this.on("message", this.onMessage.bind(this));
71
+ this.intervals.connectionChecker = setInterval(this.checkConnection.bind(this), this.configuration.messageReconnectTimeout / 10);
72
+ this.unsubscribeLifecycle = getLifecycleGate().onChange((backgrounded) => {
73
+ if (!backgrounded) this.checkConnection();
74
+ });
75
+ if (typeof window !== "undefined" && typeof window.addEventListener === "function") {
76
+ this.onlineListener = this.handleOnline.bind(this);
77
+ this.offlineListener = this.handleOffline.bind(this);
78
+ window.addEventListener("online", this.onlineListener);
79
+ window.addEventListener("offline", this.offlineListener);
80
+ }
81
+ if (this.shouldConnect) this.connect();
82
+ }
83
+ /**
84
+ * Whether the device currently believes it has network connectivity.
85
+ *
86
+ * Treats "unknown" as online: in Node and other non-browser environments
87
+ * `navigator` (or `navigator.onLine`) is absent, and we must not gate
88
+ * reconnection there — only the browser exposes a trustworthy signal.
89
+ */
90
+ get isOnline() {
91
+ return typeof navigator === "undefined" || navigator.onLine !== false;
92
+ }
93
+ handleOnline() {
94
+ if (this.shouldConnect && this.status !== WebSocketStatus.Connected) this.connect();
95
+ }
96
+ handleOffline() {
97
+ if (this.cancelWebsocketRetry) {
98
+ this.cancelWebsocketRetry();
99
+ this.cancelWebsocketRetry = void 0;
100
+ }
101
+ try {
102
+ this.webSocket?.close();
103
+ this.messageQueue = [];
104
+ } catch (e) {
105
+ console.error(e);
106
+ }
107
+ }
108
+ async onOpen(event) {
109
+ this.status = WebSocketStatus.Connected;
110
+ this.emit("status", { status: WebSocketStatus.Connected });
111
+ this.cancelWebsocketRetry = void 0;
112
+ this.receivedOnOpenPayload = event;
113
+ }
114
+ attach(provider) {
115
+ const existing = this.configuration.providerMap.get(provider.configuration.name);
116
+ if (existing && existing !== provider) console.debug(`[AbracadabraWS] attach: replacing provider for "${provider.configuration.name}".`);
117
+ this.configuration.providerMap.set(provider.configuration.name, provider);
118
+ if (this.status === WebSocketStatus.Disconnected && this.shouldConnect) this.connect();
119
+ if (this.receivedOnOpenPayload && this.status === WebSocketStatus.Connected) provider.onOpen(this.receivedOnOpenPayload);
120
+ }
121
+ detach(provider) {
122
+ const name = provider.configuration.name;
123
+ if (this.configuration.providerMap.get(name) === provider) {
124
+ provider.send(CloseMessage, { documentName: name });
125
+ this.configuration.providerMap.delete(name);
126
+ }
127
+ }
128
+ setConfiguration(configuration = {}) {
129
+ this.configuration = {
130
+ ...this.configuration,
131
+ ...configuration
132
+ };
133
+ if (!this.configuration.autoConnect) this.shouldConnect = false;
134
+ }
135
+ async connect() {
136
+ if (this.status === WebSocketStatus.Connected) return;
137
+ if (!this.isOnline) {
138
+ this.shouldConnect = true;
139
+ return;
140
+ }
141
+ if (this.cancelWebsocketRetry) {
142
+ this.cancelWebsocketRetry();
143
+ this.cancelWebsocketRetry = void 0;
144
+ }
145
+ this.receivedOnOpenPayload = void 0;
146
+ this.shouldConnect = true;
147
+ const abortableRetry = () => {
148
+ let cancelAttempt = false;
149
+ return {
150
+ retryPromise: retry(this.createWebSocketConnection.bind(this), {
151
+ delay: this.configuration.delay,
152
+ initialDelay: this.configuration.initialDelay,
153
+ factor: this.configuration.factor,
154
+ maxAttempts: this.configuration.maxAttempts,
155
+ minDelay: this.configuration.minDelay,
156
+ maxDelay: this.configuration.maxDelay,
157
+ jitter: this.configuration.jitter,
158
+ timeout: this.configuration.timeout,
159
+ handleTimeout: this.configuration.handleTimeout,
160
+ beforeAttempt: (context) => {
161
+ if (!this.shouldConnect || cancelAttempt) context.abort();
162
+ }
163
+ }).catch((error) => {
164
+ if (error && error.code !== "ATTEMPT_ABORTED") throw error;
165
+ }),
166
+ cancelFunc: () => {
167
+ cancelAttempt = true;
168
+ }
169
+ };
170
+ };
171
+ const { retryPromise, cancelFunc } = abortableRetry();
172
+ this.cancelWebsocketRetry = cancelFunc;
173
+ return retryPromise;
174
+ }
175
+ attachWebSocketListeners(ws, reject) {
176
+ const { identifier } = ws;
177
+ const onMessageHandler = (payload) => this.emit("message", payload);
178
+ const onCloseHandler = (payload) => this.emit("close", { event: payload });
179
+ const onOpenHandler = (payload) => this.emit("open", payload);
180
+ const onErrorHandler = (err) => {
181
+ reject(err);
182
+ };
183
+ this.webSocketHandlers[identifier] = {
184
+ message: onMessageHandler,
185
+ close: onCloseHandler,
186
+ open: onOpenHandler,
187
+ error: onErrorHandler
188
+ };
189
+ const handlers = this.webSocketHandlers[ws.identifier];
190
+ Object.keys(handlers).forEach((name) => {
191
+ ws.addEventListener(name, handlers[name]);
192
+ });
193
+ }
194
+ cleanupWebSocket() {
195
+ if (!this.webSocket) return;
196
+ const { identifier } = this.webSocket;
197
+ const handlers = this.webSocketHandlers[identifier];
198
+ Object.keys(handlers).forEach((name) => {
199
+ this.webSocket?.removeEventListener(name, handlers[name]);
200
+ delete this.webSocketHandlers[identifier];
201
+ });
202
+ if (this.webSocket.readyState !== 3) this.webSocket.addEventListener("error", () => {});
203
+ try {
204
+ if (this.webSocket.readyState !== 0 && this.webSocket.readyState !== 3) this.webSocket.close();
205
+ } catch (e) {}
206
+ this.webSocket = null;
207
+ }
208
+ createWebSocketConnection() {
209
+ return new Promise((resolve, reject) => {
210
+ if (this.webSocket) {
211
+ this.messageQueue = [];
212
+ this.cleanupWebSocket();
213
+ }
214
+ this.lastMessageReceived = 0;
215
+ this.identifier += 1;
216
+ const ws = new this.configuration.WebSocketPolyfill(this.url);
217
+ ws.binaryType = "arraybuffer";
218
+ ws.identifier = this.identifier;
219
+ this.attachWebSocketListeners(ws, reject);
220
+ this.webSocket = ws;
221
+ this.status = WebSocketStatus.Connecting;
222
+ this.emit("status", { status: WebSocketStatus.Connecting });
223
+ this.connectionAttempt = {
224
+ resolve,
225
+ reject
226
+ };
227
+ });
228
+ }
229
+ onMessage(event) {
230
+ this.resolveConnectionAttempt();
231
+ this.lastMessageReceived = time.getUnixTime();
232
+ const documentName = new IncomingMessage(event.data).peekVarString();
233
+ try {
234
+ this.configuration.providerMap.get(documentName)?.onMessage(event);
235
+ } catch (err) {
236
+ console.error(`[AbracadabraWS] Provider onMessage error for "${documentName}":`, err);
237
+ }
238
+ }
239
+ resolveConnectionAttempt() {
240
+ if (this.connectionAttempt) {
241
+ this.connectionAttempt.resolve();
242
+ this.connectionAttempt = null;
243
+ this.status = WebSocketStatus.Connected;
244
+ this.emit("status", { status: WebSocketStatus.Connected });
245
+ this.emit("connect");
246
+ this.messageQueue.forEach((message) => this.send(message));
247
+ this.messageQueue = [];
248
+ }
249
+ }
250
+ stopConnectionAttempt() {
251
+ this.connectionAttempt = null;
252
+ }
253
+ rejectConnectionAttempt() {
254
+ this.connectionAttempt?.reject();
255
+ this.connectionAttempt = null;
256
+ }
257
+ checkConnection() {
258
+ if (getLifecycleGate().backgrounded) return;
259
+ if (this.status !== WebSocketStatus.Connected) return;
260
+ if (!this.lastMessageReceived) return;
261
+ if (this.configuration.messageReconnectTimeout >= time.getUnixTime() - this.lastMessageReceived) return;
262
+ this.closeTries += 1;
263
+ if (this.closeTries > 2) {
264
+ this.onClose({ event: {
265
+ code: 4408,
266
+ reason: "forced"
267
+ } });
268
+ this.closeTries = 0;
269
+ } else {
270
+ this.webSocket?.close();
271
+ this.messageQueue = [];
272
+ }
273
+ }
274
+ get serverUrl() {
275
+ if (this.configuration.preserveTrailingSlash) return this.configuration.url;
276
+ let url = this.configuration.url;
277
+ while (url[url.length - 1] === "/") url = url.slice(0, url.length - 1);
278
+ return url;
279
+ }
280
+ get url() {
281
+ return this.serverUrl;
282
+ }
283
+ disconnect() {
284
+ this.shouldConnect = false;
285
+ if (this.webSocket === null) return;
286
+ try {
287
+ this.webSocket.close();
288
+ this.messageQueue = [];
289
+ } catch (e) {
290
+ console.error(e);
291
+ }
292
+ }
293
+ /**
294
+ * Force a fresh socket on the SAME WS manager: drop the current connection
295
+ * (if any) and reconnect immediately.
296
+ *
297
+ * Unlike {@link disconnect} (which clears `shouldConnect` and gives up) this
298
+ * re-arms `shouldConnect`, so it also revives a socket that a permanent
299
+ * permission-denial turned off (see `AbracadabraBaseProvider.permissionDeniedHandler`).
300
+ * The WS manager and its `providerMap` are preserved, so every attached
301
+ * provider — and every Y.Doc + observer riding this socket — survives
302
+ * untouched; only the transport is recycled.
303
+ *
304
+ * The existing socket is torn down silently (handlers removed first), so no
305
+ * `close` event fires and no second reconnect is scheduled — `connect()`
306
+ * below is the single path that re-opens. Returns the `connect()` promise.
307
+ */
308
+ reconnect() {
309
+ this.shouldConnect = true;
310
+ if (this.cancelWebsocketRetry) {
311
+ this.cancelWebsocketRetry();
312
+ this.cancelWebsocketRetry = void 0;
313
+ }
314
+ if (this.webSocket) this.cleanupWebSocket();
315
+ this.status = WebSocketStatus.Disconnected;
316
+ this.emit("status", { status: WebSocketStatus.Disconnected });
317
+ return this.connect();
318
+ }
319
+ send(message) {
320
+ if (this.webSocket?.readyState === WsReadyStates.Open) this.webSocket.send(message);
321
+ else this.messageQueue.push(message);
322
+ }
323
+ /**
324
+ * Re-arm this CONNECTION with a freshly minted JWT, in place.
325
+ *
326
+ * The server tracks a connection's expiry as one shared value
327
+ * (`SyncSession`'s `jwt_exp`, an `Arc<AtomicI64>` every session on the socket
328
+ * points at) and rejects every non-stateless frame once it passes — dropping
329
+ * the whole socket for an ordinary session. `auth:refresh {"token":…}` moves
330
+ * that value, and it rides `MSG_STATELESS` precisely because stateless is the
331
+ * one frame kind an expired session may still send.
332
+ *
333
+ * So ONE frame, through any authenticated document, re-arms everything
334
+ * multiplexed here. Sending it per attached provider would be N identical
335
+ * frames on a shared socket carrying sixty documents; `lastRefreshToken` is
336
+ * what keeps it at one.
337
+ *
338
+ * Verified against a live server with a 45-second token TTL, on an ORDINARY
339
+ * (non-elevated) account, refreshing before the lapse so the socket is never
340
+ * dropped and never re-handshaken: without the frame the socket is closed
341
+ * past the original expiry, with it `close` never fires at all.
342
+ *
343
+ * Returns whether a frame actually went out. `false` means there was nobody
344
+ * to send it through — harmless, because the next handshake carries the new
345
+ * token anyway (see the provider's token closure).
346
+ */
347
+ refreshAuth(token) {
348
+ if (!token || token === this.lastRefreshToken) return false;
349
+ if (this.status !== WebSocketStatus.Connected) return false;
350
+ const payload = `auth:refresh ${JSON.stringify({ token })}`;
351
+ for (const provider of this.configuration.providerMap.values()) {
352
+ if (!provider.isAuthenticated) continue;
353
+ provider.sendStateless(payload);
354
+ this.lastRefreshToken = token;
355
+ return true;
356
+ }
357
+ return false;
358
+ }
359
+ onClose({ event }) {
360
+ this.closeTries = 0;
361
+ this.cleanupWebSocket();
362
+ if (this.connectionAttempt) this.rejectConnectionAttempt();
363
+ this.status = WebSocketStatus.Disconnected;
364
+ this.emit("status", { status: WebSocketStatus.Disconnected });
365
+ const isRateLimited = event?.code === 4429 || event === 4429;
366
+ this.emit("disconnect", { event });
367
+ if (isRateLimited) this.emit("rateLimited");
368
+ if (!this.cancelWebsocketRetry && this.shouldConnect && this.isOnline) {
369
+ const delay = isRateLimited ? 6e4 : this.configuration.delay;
370
+ setTimeout(() => {
371
+ this.connect();
372
+ }, delay);
373
+ }
374
+ }
375
+ destroy() {
376
+ this.shouldConnect = false;
377
+ this.emit("destroy");
378
+ if (typeof window !== "undefined" && typeof window.removeEventListener === "function") {
379
+ if (this.onlineListener) window.removeEventListener("online", this.onlineListener);
380
+ if (this.offlineListener) window.removeEventListener("offline", this.offlineListener);
381
+ }
382
+ this.onlineListener = null;
383
+ this.offlineListener = null;
384
+ this.unsubscribeLifecycle?.();
385
+ this.unsubscribeLifecycle = null;
386
+ clearInterval(this.intervals.connectionChecker);
387
+ this.stopConnectionAttempt();
388
+ this.disconnect();
389
+ this.removeAllListeners();
390
+ this.cleanupWebSocket();
391
+ }
392
+ };
393
+ /** @deprecated Use AbracadabraWS */
394
+ const HocuspocusProviderWebsocket = AbracadabraWS;
395
+
396
+ //#endregion
397
+ export { AbracadabraWS, HocuspocusProviderWebsocket };
398
+ //# sourceMappingURL=AbracadabraWS.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"AbracadabraWS.js","names":[],"sources":["../../src/AbracadabraWS.ts"],"sourcesContent":["import { WsReadyStates } from \"./types.ts\";\nimport { getLifecycleGate } from \"./LifecycleGate.ts\";\nimport { retry } from \"@lifeomic/attempt\";\nimport * as time from \"lib0/time\";\nimport type { Event, MessageEvent } from \"ws\";\nimport EventEmitter from \"./EventEmitter.ts\";\nimport type { AbracadabraBaseProvider } from \"./AbracadabraBaseProvider.ts\";\nimport { IncomingMessage } from \"./IncomingMessage.ts\";\nimport { CloseMessage } from \"./OutgoingMessages/CloseMessage.ts\";\nimport {\n WebSocketStatus,\n type onAwarenessChangeParameters,\n type onAwarenessUpdateParameters,\n type onCloseParameters,\n type onDisconnectParameters,\n type onMessageParameters,\n type onOpenParameters,\n type onOutgoingMessageParameters,\n type onStatusParameters,\n} from \"./types.ts\";\n\nexport type AbracadabraWebSocketConn = WebSocket & { identifier: string };\n/** @deprecated Use AbracadabraWebSocketConn */\nexport type HocuspocusWebSocket = AbracadabraWebSocketConn;\n/** @deprecated Use AbracadabraWebSocketConn */\nexport type HocusPocusWebSocket = AbracadabraWebSocketConn;\n\nexport type AbracadabraWSConfiguration = Required<\n Pick<CompleteAbracadabraWSConfiguration, \"url\">\n> &\n Partial<CompleteAbracadabraWSConfiguration>;\n\n/** @deprecated Use AbracadabraWSConfiguration */\nexport type HocuspocusProviderWebsocketConfiguration = AbracadabraWSConfiguration;\n\nexport interface CompleteAbracadabraWSConfiguration {\n /**\n * Whether to connect automatically when creating the provider instance. Default=true\n */\n autoConnect: boolean;\n\n /**\n * URL of your @hocuspocus/server instance\n */\n url: string;\n\n /**\n * By default, trailing slashes are removed from the URL. Set this to true\n * to preserve trailing slashes if your server configuration requires them.\n */\n preserveTrailingSlash: boolean;\n\n /**\n * An optional WebSocket polyfill, for example for Node.js\n */\n WebSocketPolyfill: any;\n\n /**\n * Disconnect and reconnect when no message is received for the defined amount\n * of milliseconds.\n *\n * Defaults to 30000 ms to match y-protocols/awareness `Awareness.outdatedTime`\n * (also 30 s). Awareness heartbeats are what normally keep this timer\n * resetting, so this value should be ≥ the largest `outdatedTime` of any\n * awareness instance attached to this socket. If you pass a custom awareness\n * with a non-default `outdatedTime`, pass the matching value here too.\n */\n messageReconnectTimeout: number;\n /**\n * The delay between each attempt in milliseconds. You can provide a factor to have the delay grow exponentially.\n */\n delay: number;\n /**\n * The initialDelay is the amount of time to wait before making the first attempt. This option should typically be 0 since you typically want the first attempt to happen immediately.\n */\n initialDelay: number;\n /**\n * The factor option is used to grow the delay exponentially.\n */\n factor: number;\n /**\n * The maximum number of attempts or 0 if there is no limit on number of attempts.\n */\n maxAttempts: number;\n /**\n * minDelay is used to set a lower bound of delay when jitter is enabled. This property has no effect if jitter is disabled.\n */\n minDelay: number;\n /**\n * The maxDelay option is used to set an upper bound for the delay when factor is enabled. A value of 0 can be provided if there should be no upper bound when calculating delay.\n */\n maxDelay: number;\n /**\n * If jitter is true then the calculated delay will be a random integer value between minDelay and the calculated delay for the current iteration.\n */\n jitter: boolean;\n /**\n * A timeout in milliseconds. If timeout is non-zero then a timer is set using setTimeout. If the timeout is triggered then future attempts will be aborted.\n */\n timeout: number;\n handleTimeout: (() => Promise<unknown>) | null;\n onOpen: (data: onOpenParameters) => void;\n onConnect: () => void;\n onMessage: (data: onMessageParameters) => void;\n onOutgoingMessage: (data: onOutgoingMessageParameters) => void;\n onStatus: (data: onStatusParameters) => void;\n onDisconnect: (data: onDisconnectParameters) => void;\n onClose: (data: onCloseParameters) => void;\n onDestroy: () => void;\n onAwarenessUpdate: (data: onAwarenessUpdateParameters) => void;\n onAwarenessChange: (data: onAwarenessChangeParameters) => void;\n\n /**\n * Map of attached providers keyed by documentName.\n */\n providerMap: Map<string, AbracadabraBaseProvider>;\n}\n\n/** @deprecated Use CompleteAbracadabraWSConfiguration */\nexport type CompleteHocuspocusProviderWebsocketConfiguration = CompleteAbracadabraWSConfiguration;\n\nexport class AbracadabraWS extends EventEmitter {\n private messageQueue: any[] = [];\n\n public configuration: CompleteAbracadabraWSConfiguration = {\n url: \"\",\n autoConnect: true,\n preserveTrailingSlash: false,\n // @ts-ignore\n document: undefined,\n WebSocketPolyfill: undefined,\n // Matches y-protocols/awareness Awareness.outdatedTime default (30 s).\n // See the `messageReconnectTimeout` JSDoc on CompleteAbracadabraWSConfiguration.\n messageReconnectTimeout: 30000,\n // 1 second\n delay: 1000,\n // instant\n initialDelay: 0,\n // double the delay each time\n factor: 2,\n // unlimited retries\n maxAttempts: 0,\n // wait at least 1 second\n minDelay: 1000,\n // at least every 30 seconds\n maxDelay: 30000,\n // randomize\n jitter: true,\n // retry forever\n timeout: 0,\n onOpen: () => null,\n onConnect: () => null,\n onMessage: () => null,\n onOutgoingMessage: () => null,\n onStatus: () => null,\n onDisconnect: () => null,\n onClose: () => null,\n onDestroy: () => null,\n onAwarenessUpdate: () => null,\n onAwarenessChange: () => null,\n handleTimeout: null,\n providerMap: new Map(),\n };\n\n webSocket: AbracadabraWebSocketConn | null = null;\n\n webSocketHandlers: { [key: string]: any } = {};\n\n shouldConnect = true;\n\n status = WebSocketStatus.Disconnected;\n\n lastMessageReceived = 0;\n\n identifier = 0;\n\n intervals: any = {\n connectionChecker: null,\n };\n\n connectionAttempt: {\n resolve: (value?: any) => void;\n reject: (reason?: any) => void;\n } | null = null;\n\n // Bound `online`/`offline` listeners, retained so we can detach them in\n // destroy(). Only registered in browser-like environments (see constructor).\n private onlineListener: (() => void) | null = null;\n\n private offlineListener: (() => void) | null = null;\n\n unsubscribeLifecycle: (() => void) | null = null;\n\n constructor(configuration: AbracadabraWSConfiguration) {\n super();\n this.setConfiguration(configuration);\n\n this.configuration.WebSocketPolyfill = configuration.WebSocketPolyfill\n ? configuration.WebSocketPolyfill\n : (globalThis as { WebSocket?: typeof WebSocket }).WebSocket;\n\n this.on(\"open\", this.configuration.onOpen);\n this.on(\"open\", this.onOpen.bind(this));\n this.on(\"connect\", this.configuration.onConnect);\n this.on(\"message\", this.configuration.onMessage);\n this.on(\"outgoingMessage\", this.configuration.onOutgoingMessage);\n this.on(\"status\", this.configuration.onStatus);\n this.on(\"disconnect\", this.configuration.onDisconnect);\n this.on(\"close\", this.configuration.onClose);\n this.on(\"destroy\", this.configuration.onDestroy);\n this.on(\"awarenessUpdate\", this.configuration.onAwarenessUpdate);\n this.on(\"awarenessChange\", this.configuration.onAwarenessChange);\n\n this.on(\"close\", this.onClose.bind(this));\n this.on(\"message\", this.onMessage.bind(this));\n\n this.intervals.connectionChecker = setInterval(\n this.checkConnection.bind(this),\n this.configuration.messageReconnectTimeout / 10,\n );\n\n // Returning to the foreground re-checks at once rather than waiting out the\n // next tick, so gating the checker while hidden costs no detection latency\n // at the only moment a stale socket is actually noticeable.\n this.unsubscribeLifecycle = getLifecycleGate().onChange((backgrounded) => {\n if (!backgrounded) this.checkConnection();\n });\n\n // Offline-first reconnect gating. When the device reports it is offline we\n // stop hammering the socket (failed attempts just flip status\n // disconnected↔connecting and light up every connection indicator) and\n // wait for the `online` event to resume immediately — no backoff wait.\n if (typeof window !== \"undefined\" && typeof window.addEventListener === \"function\") {\n this.onlineListener = this.handleOnline.bind(this);\n this.offlineListener = this.handleOffline.bind(this);\n window.addEventListener(\"online\", this.onlineListener);\n window.addEventListener(\"offline\", this.offlineListener);\n }\n\n if (this.shouldConnect) {\n this.connect();\n }\n }\n\n /**\n * Whether the device currently believes it has network connectivity.\n *\n * Treats \"unknown\" as online: in Node and other non-browser environments\n * `navigator` (or `navigator.onLine`) is absent, and we must not gate\n * reconnection there — only the browser exposes a trustworthy signal.\n */\n get isOnline(): boolean {\n return typeof navigator === \"undefined\" || navigator.onLine !== false;\n }\n\n handleOnline() {\n // Network came back — resume immediately if we still want a connection\n // and aren't already connected. Bypasses the backoff that a pending\n // retryer would otherwise wait out.\n if (this.shouldConnect && this.status !== WebSocketStatus.Connected) {\n this.connect();\n }\n }\n\n handleOffline() {\n // Stop attempting while offline, but preserve `shouldConnect` so intent\n // survives — `handleOnline`/attach will resume once connectivity returns.\n if (this.cancelWebsocketRetry) {\n this.cancelWebsocketRetry();\n this.cancelWebsocketRetry = undefined;\n }\n try {\n this.webSocket?.close();\n this.messageQueue = [];\n } catch (e) {\n console.error(e);\n }\n }\n\n receivedOnOpenPayload?: Event | undefined = undefined;\n\n async onOpen(event: Event) {\n this.status = WebSocketStatus.Connected;\n this.emit(\"status\", { status: WebSocketStatus.Connected });\n\n this.cancelWebsocketRetry = undefined;\n this.receivedOnOpenPayload = event;\n }\n\n attach(provider: AbracadabraBaseProvider) {\n const existing = this.configuration.providerMap.get(provider.configuration.name);\n if (existing && existing !== provider) {\n console.debug(\n `[AbracadabraWS] attach: replacing provider for \"${provider.configuration.name}\".`\n );\n }\n this.configuration.providerMap.set(provider.configuration.name, provider);\n\n if (this.status === WebSocketStatus.Disconnected && this.shouldConnect) {\n this.connect();\n }\n\n if (this.receivedOnOpenPayload && this.status === WebSocketStatus.Connected) {\n provider.onOpen(this.receivedOnOpenPayload);\n }\n }\n\n detach(provider: AbracadabraBaseProvider) {\n const name = provider.configuration.name;\n const current = this.configuration.providerMap.get(name);\n if (current === provider) {\n provider.send(CloseMessage, { documentName: name });\n this.configuration.providerMap.delete(name);\n }\n // If current !== provider, another provider owns this slot —\n // don't send CloseMessage or remove it from the map.\n }\n\n public setConfiguration(\n configuration: Partial<AbracadabraWSConfiguration> = {},\n ): void {\n this.configuration = { ...this.configuration, ...configuration };\n\n if (!this.configuration.autoConnect) {\n this.shouldConnect = false;\n }\n }\n\n cancelWebsocketRetry?: () => void;\n\n async connect() {\n if (this.status === WebSocketStatus.Connected) {\n return;\n }\n\n // Don't attempt while the device is offline — record the intent and let\n // the `online` event drive the resume. Avoids the reconnect storm of\n // instantly-failing socket attempts against a known-dead network.\n if (!this.isOnline) {\n this.shouldConnect = true;\n return;\n }\n\n // Always cancel any previously initiated connection retryer instances\n if (this.cancelWebsocketRetry) {\n this.cancelWebsocketRetry();\n this.cancelWebsocketRetry = undefined;\n }\n\n this.receivedOnOpenPayload = undefined;\n this.shouldConnect = true;\n\n const abortableRetry = () => {\n let cancelAttempt = false;\n\n const retryPromise = retry(this.createWebSocketConnection.bind(this), {\n delay: this.configuration.delay,\n initialDelay: this.configuration.initialDelay,\n factor: this.configuration.factor,\n maxAttempts: this.configuration.maxAttempts,\n minDelay: this.configuration.minDelay,\n maxDelay: this.configuration.maxDelay,\n jitter: this.configuration.jitter,\n timeout: this.configuration.timeout,\n handleTimeout: this.configuration.handleTimeout,\n beforeAttempt: (context) => {\n if (!this.shouldConnect || cancelAttempt) {\n context.abort();\n }\n },\n }).catch((error: any) => {\n // If we aborted the connection attempt then don't throw an error\n // ref: https://github.com/lifeomic/attempt/blob/master/src/index.ts#L136\n if (error && error.code !== \"ATTEMPT_ABORTED\") {\n throw error;\n }\n });\n\n return {\n retryPromise,\n cancelFunc: () => {\n cancelAttempt = true;\n },\n };\n };\n\n const { retryPromise, cancelFunc } = abortableRetry();\n this.cancelWebsocketRetry = cancelFunc;\n\n return retryPromise;\n }\n\n // eslint-disable-next-line @typescript-eslint/no-unsafe-function-type\n attachWebSocketListeners(ws: AbracadabraWebSocketConn, reject: Function) {\n const { identifier } = ws;\n const onMessageHandler = (payload: any) => this.emit(\"message\", payload);\n const onCloseHandler = (payload: any) => this.emit(\"close\", { event: payload });\n const onOpenHandler = (payload: any) => this.emit(\"open\", payload);\n const onErrorHandler = (err: any) => {\n reject(err);\n };\n\n this.webSocketHandlers[identifier] = {\n message: onMessageHandler,\n close: onCloseHandler,\n open: onOpenHandler,\n error: onErrorHandler,\n };\n\n const handlers = this.webSocketHandlers[ws.identifier];\n\n Object.keys(handlers).forEach((name) => {\n ws.addEventListener(name, handlers[name]);\n });\n }\n\n cleanupWebSocket() {\n if (!this.webSocket) {\n return;\n }\n const { identifier } = this.webSocket;\n const handlers = this.webSocketHandlers[identifier];\n\n Object.keys(handlers).forEach((name) => {\n this.webSocket?.removeEventListener(name, handlers[name]);\n delete this.webSocketHandlers[identifier];\n });\n\n // After removing our handlers, ensure there is always at least one error\n // listener on the socket. Without one, any asynchronously-fired error\n // (e.g. \"WebSocket was closed before the connection was established\" when\n // closing a CONNECTING socket) will propagate as an uncaught exception in\n // Node.js. The no-op listener absorbs these post-cleanup errors safely.\n if (this.webSocket.readyState !== 3 /* CLOSED */) {\n this.webSocket.addEventListener(\"error\", () => {});\n }\n\n try {\n if (this.webSocket.readyState !== 0 /* CONNECTING */ && this.webSocket.readyState !== 3 /* CLOSED */) {\n this.webSocket.close();\n }\n // CONNECTING (0): already being closed by disconnect(), or will be closed imminently.\n // CLOSED (3): nothing to do.\n } catch (e) {\n // Ignore errors during close\n }\n\n this.webSocket = null;\n }\n\n createWebSocketConnection() {\n return new Promise((resolve, reject) => {\n if (this.webSocket) {\n this.messageQueue = [];\n this.cleanupWebSocket();\n }\n this.lastMessageReceived = 0;\n this.identifier += 1;\n\n // Init the WebSocket connection\n const ws = new this.configuration.WebSocketPolyfill(this.url);\n ws.binaryType = \"arraybuffer\";\n ws.identifier = this.identifier;\n\n this.attachWebSocketListeners(ws, reject);\n\n this.webSocket = ws;\n\n // Reset the status\n this.status = WebSocketStatus.Connecting;\n this.emit(\"status\", { status: WebSocketStatus.Connecting });\n\n // Store resolve/reject for later use\n this.connectionAttempt = {\n resolve,\n reject,\n };\n });\n }\n\n onMessage(event: MessageEvent) {\n this.resolveConnectionAttempt();\n\n this.lastMessageReceived = time.getUnixTime();\n\n const message = new IncomingMessage(event.data);\n const documentName = message.peekVarString();\n\n try {\n this.configuration.providerMap.get(documentName)?.onMessage(event);\n } catch (err) {\n console.error(`[AbracadabraWS] Provider onMessage error for \"${documentName}\":`, err);\n }\n }\n\n resolveConnectionAttempt() {\n if (this.connectionAttempt) {\n this.connectionAttempt.resolve();\n this.connectionAttempt = null;\n\n this.status = WebSocketStatus.Connected;\n this.emit(\"status\", { status: WebSocketStatus.Connected });\n this.emit(\"connect\");\n this.messageQueue.forEach((message) => this.send(message));\n this.messageQueue = [];\n }\n }\n\n stopConnectionAttempt() {\n this.connectionAttempt = null;\n }\n\n rejectConnectionAttempt() {\n this.connectionAttempt?.reject();\n this.connectionAttempt = null;\n }\n\n closeTries = 0;\n\n checkConnection() {\n // Don't police a socket nobody is looking at.\n //\n // This check exists to notice a connection that has gone quiet and force a\n // reconnect. While the app is backgrounded there is no one to serve, and\n // running it anyway is actively harmful on mobile: the client is sending\n // nothing, so `lastMessageReceived` goes stale on its own schedule and the\n // checker tears down a perfectly good socket, then reconnects it, then does\n // it again — burning radio to maintain a connection for nobody. Coming back\n // into view re-runs this immediately, so a genuinely dead socket is still\n // caught the moment it matters to anyone.\n if (getLifecycleGate().backgrounded) {\n return;\n }\n\n // Don't check the connection when it's not even established\n if (this.status !== WebSocketStatus.Connected) {\n return;\n }\n\n // Don't close the connection while waiting for the first message\n if (!this.lastMessageReceived) {\n return;\n }\n\n // Don't close the connection when a message was received recently\n if (\n this.configuration.messageReconnectTimeout >=\n time.getUnixTime() - this.lastMessageReceived\n ) {\n return;\n }\n\n // No message received in a long time, not even your own\n // Awareness updates, which are updated every 15 seconds\n // if awareness is enabled.\n this.closeTries += 1;\n // https://bugs.webkit.org/show_bug.cgi?id=247943\n if (this.closeTries > 2) {\n this.onClose({\n event: {\n code: 4408,\n reason: \"forced\",\n },\n });\n this.closeTries = 0;\n } else {\n this.webSocket?.close();\n this.messageQueue = [];\n }\n }\n\n get serverUrl() {\n if (this.configuration.preserveTrailingSlash) {\n return this.configuration.url;\n }\n\n // By default, ensure that the URL never ends with /\n let url = this.configuration.url;\n while (url[url.length - 1] === \"/\") {\n url = url.slice(0, url.length - 1);\n }\n\n return url;\n }\n\n get url() {\n return this.serverUrl;\n }\n\n disconnect() {\n this.shouldConnect = false;\n\n if (this.webSocket === null) {\n return;\n }\n\n try {\n this.webSocket.close();\n this.messageQueue = [];\n } catch (e) {\n console.error(e);\n }\n }\n\n /**\n * Force a fresh socket on the SAME WS manager: drop the current connection\n * (if any) and reconnect immediately.\n *\n * Unlike {@link disconnect} (which clears `shouldConnect` and gives up) this\n * re-arms `shouldConnect`, so it also revives a socket that a permanent\n * permission-denial turned off (see `AbracadabraBaseProvider.permissionDeniedHandler`).\n * The WS manager and its `providerMap` are preserved, so every attached\n * provider — and every Y.Doc + observer riding this socket — survives\n * untouched; only the transport is recycled.\n *\n * The existing socket is torn down silently (handlers removed first), so no\n * `close` event fires and no second reconnect is scheduled — `connect()`\n * below is the single path that re-opens. Returns the `connect()` promise.\n */\n reconnect() {\n this.shouldConnect = true;\n\n // Cancel any in-flight retryer so we don't stack two connection attempts.\n if (this.cancelWebsocketRetry) {\n this.cancelWebsocketRetry();\n this.cancelWebsocketRetry = undefined;\n }\n\n // Silently drop the current socket (cleanupWebSocket removes our handlers\n // before closing, so onClose never runs → no auto-reschedule).\n if (this.webSocket) {\n this.cleanupWebSocket();\n }\n\n // connect() early-returns when status is Connected; force Disconnected so\n // it always builds a fresh socket. Surface the transition so status\n // listeners (and the providers' synced reset) see the drop.\n this.status = WebSocketStatus.Disconnected;\n this.emit(\"status\", { status: WebSocketStatus.Disconnected });\n\n return this.connect();\n }\n\n send(message: any) {\n if (this.webSocket?.readyState === WsReadyStates.Open) {\n this.webSocket.send(message);\n } else {\n this.messageQueue.push(message);\n }\n }\n\n /** The last token this socket was re-armed with — see {@link refreshAuth}. */\n private lastRefreshToken: string | null = null;\n\n /**\n * Re-arm this CONNECTION with a freshly minted JWT, in place.\n *\n * The server tracks a connection's expiry as one shared value\n * (`SyncSession`'s `jwt_exp`, an `Arc<AtomicI64>` every session on the socket\n * points at) and rejects every non-stateless frame once it passes — dropping\n * the whole socket for an ordinary session. `auth:refresh {\"token\":…}` moves\n * that value, and it rides `MSG_STATELESS` precisely because stateless is the\n * one frame kind an expired session may still send.\n *\n * So ONE frame, through any authenticated document, re-arms everything\n * multiplexed here. Sending it per attached provider would be N identical\n * frames on a shared socket carrying sixty documents; `lastRefreshToken` is\n * what keeps it at one.\n *\n * Verified against a live server with a 45-second token TTL, on an ORDINARY\n * (non-elevated) account, refreshing before the lapse so the socket is never\n * dropped and never re-handshaken: without the frame the socket is closed\n * past the original expiry, with it `close` never fires at all.\n *\n * Returns whether a frame actually went out. `false` means there was nobody\n * to send it through — harmless, because the next handshake carries the new\n * token anyway (see the provider's token closure).\n */\n refreshAuth(token: string): boolean {\n if (!token || token === this.lastRefreshToken) return false;\n if (this.status !== WebSocketStatus.Connected) return false;\n const payload = `auth:refresh ${JSON.stringify({ token })}`;\n for (const provider of this.configuration.providerMap.values()) {\n // An authenticated document is required: the frame is dispatched by\n // document name, and a name this connection has no session for has\n // nothing to re-arm.\n if (!provider.isAuthenticated) continue;\n provider.sendStateless(payload);\n this.lastRefreshToken = token;\n return true;\n }\n return false;\n }\n\n onClose({ event }: onCloseParameters) {\n this.closeTries = 0;\n this.cleanupWebSocket();\n\n if (this.connectionAttempt) {\n // That connection attempt failed.\n this.rejectConnectionAttempt();\n }\n\n // Let's update the connection status.\n this.status = WebSocketStatus.Disconnected;\n this.emit(\"status\", { status: WebSocketStatus.Disconnected });\n\n // Detect server-side rate-limit close (code 4429).\n // `event` may be a CloseEvent (browser) with `.code`, or a raw number (ws/Node.js).\n // `event` may be a CloseEvent (browser) with `.code`, or a raw number (ws/Node.js).\n const isRateLimited = (event as any)?.code === 4429 || (event as unknown) === 4429;\n this.emit(\"disconnect\", { event });\n if (isRateLimited) {\n this.emit(\"rateLimited\");\n }\n\n // trigger connect if no retry is running and we want to have a connection.\n // Skip scheduling entirely while offline — `handleOnline` resumes the\n // moment connectivity returns, so there's no point burning a timer (and a\n // failed attempt) against a dead network.\n if (!this.cancelWebsocketRetry && this.shouldConnect && this.isOnline) {\n // Apply a much longer delay for rate-limited closes to let the server window reset.\n const delay = isRateLimited ? 60_000 : this.configuration.delay;\n setTimeout(() => {\n this.connect();\n }, delay);\n }\n }\n\n destroy() {\n // Mark as not wanting a connection FIRST so that onClose (fired by disconnect()\n // below) does not schedule a new reconnect setTimeout after we've torn down.\n this.shouldConnect = false;\n\n this.emit(\"destroy\");\n\n if (typeof window !== \"undefined\" && typeof window.removeEventListener === \"function\") {\n if (this.onlineListener) window.removeEventListener(\"online\", this.onlineListener);\n if (this.offlineListener) window.removeEventListener(\"offline\", this.offlineListener);\n }\n this.onlineListener = null;\n this.offlineListener = null;\n\n // The lifecycle gate is process-wide and outlives this socket, so a missed\n // unsubscribe here leaks a closure holding the destroyed socket for the\n // lifetime of the tab.\n this.unsubscribeLifecycle?.();\n this.unsubscribeLifecycle = null;\n\n clearInterval(this.intervals.connectionChecker);\n\n // If there is still a connection attempt outstanding then we should stop\n // it before calling disconnect, otherwise it will be rejected in the onClose\n // handler and trigger a retry\n this.stopConnectionAttempt();\n\n this.disconnect();\n\n this.removeAllListeners();\n\n this.cleanupWebSocket();\n }\n}\n\n/** @deprecated Use AbracadabraWS */\nexport const HocuspocusProviderWebsocket = AbracadabraWS;\n/** @deprecated Use AbracadabraWS */\nexport type HocuspocusProviderWebsocket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