@abraca/dabra 2.102.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.
- package/dist/abracadabra-provider.cjs +6673 -6543
- package/dist/abracadabra-provider.cjs.map +1 -1
- package/dist/esm/AbracadabraBaseProvider.js +558 -0
- package/dist/esm/AbracadabraBaseProvider.js.map +1 -0
- package/dist/esm/AbracadabraClient.js +1424 -0
- package/dist/esm/AbracadabraClient.js.map +1 -0
- package/dist/esm/AbracadabraProvider.js +547 -0
- package/dist/esm/AbracadabraProvider.js.map +1 -0
- package/dist/esm/AbracadabraWS.js +398 -0
- package/dist/esm/AbracadabraWS.js.map +1 -0
- package/dist/esm/BackgroundSyncManager.js +571 -0
- package/dist/esm/BackgroundSyncManager.js.map +1 -0
- package/dist/esm/BackgroundSyncPersistence.js +62 -0
- package/dist/esm/BackgroundSyncPersistence.js.map +1 -0
- package/dist/esm/ChatClient.js +176 -0
- package/dist/esm/ChatClient.js.map +1 -0
- package/dist/esm/CloseEvents.js +45 -0
- package/dist/esm/CloseEvents.js.map +1 -0
- package/dist/esm/ContentManager.js +153 -0
- package/dist/esm/ContentManager.js.map +1 -0
- package/dist/esm/CoverReconcile.js +124 -0
- package/dist/esm/CoverReconcile.js.map +1 -0
- package/dist/esm/CryptoIdentityKeystore.js +580 -0
- package/dist/esm/CryptoIdentityKeystore.js.map +1 -0
- package/dist/esm/DeviceRegistrationService.js +158 -0
- package/dist/esm/DeviceRegistrationService.js.map +1 -0
- package/dist/esm/DocConverters.js +1300 -0
- package/dist/esm/DocConverters.js.map +1 -0
- package/dist/esm/DocKeyManager.js +145 -0
- package/dist/esm/DocKeyManager.js.map +1 -0
- package/dist/esm/DocTypes.js +792 -0
- package/dist/esm/DocTypes.js.map +1 -0
- package/dist/esm/DocUtils.js +180 -0
- package/dist/esm/DocUtils.js.map +1 -0
- package/dist/esm/DocumentCache.js +131 -0
- package/dist/esm/DocumentCache.js.map +1 -0
- package/dist/esm/DocumentManager.js +240 -0
- package/dist/esm/DocumentManager.js.map +1 -0
- package/dist/esm/E2EAbracadabraProvider.js +273 -0
- package/dist/esm/E2EAbracadabraProvider.js.map +1 -0
- package/dist/esm/E2EOfflineStore.js +53 -0
- package/dist/esm/E2EOfflineStore.js.map +1 -0
- package/dist/esm/EncryptedChatClient.js +156 -0
- package/dist/esm/EncryptedChatClient.js.map +1 -0
- package/dist/esm/EncryptedY.js +115 -0
- package/dist/esm/EncryptedY.js.map +1 -0
- package/dist/esm/EventEmitter.js +40 -0
- package/dist/esm/EventEmitter.js.map +1 -0
- package/dist/esm/FileBlobStore.js +410 -0
- package/dist/esm/FileBlobStore.js.map +1 -0
- package/dist/esm/IdentityDoc.js +413 -0
- package/dist/esm/IdentityDoc.js.map +1 -0
- package/dist/esm/IncomingMessage.js +39 -0
- package/dist/esm/IncomingMessage.js.map +1 -0
- package/dist/esm/LifecycleGate.js +124 -0
- package/dist/esm/LifecycleGate.js.map +1 -0
- package/dist/esm/MessageReceiver.js +86 -0
- package/dist/esm/MessageReceiver.js.map +1 -0
- package/dist/esm/MessageSender.js +19 -0
- package/dist/esm/MessageSender.js.map +1 -0
- package/dist/esm/MetaManager.js +112 -0
- package/dist/esm/MetaManager.js.map +1 -0
- package/dist/esm/MnemonicKeyDerivation.js +137 -0
- package/dist/esm/MnemonicKeyDerivation.js.map +1 -0
- package/dist/esm/NodeConnect.js +63 -0
- package/dist/esm/NodeConnect.js.map +1 -0
- package/dist/esm/NodeIdentity.js +212 -0
- package/dist/esm/NodeIdentity.js.map +1 -0
- package/dist/esm/NotificationsClient.js +136 -0
- package/dist/esm/NotificationsClient.js.map +1 -0
- package/dist/esm/OfflineStore.js +291 -0
- package/dist/esm/OfflineStore.js.map +1 -0
- package/dist/esm/OutgoingMessage.js +18 -0
- package/dist/esm/OutgoingMessage.js.map +1 -0
- package/dist/esm/OutgoingMessages/AuthenticationMessage.js +24 -0
- package/dist/esm/OutgoingMessages/AuthenticationMessage.js.map +1 -0
- package/dist/esm/OutgoingMessages/AwarenessMessage.js +28 -0
- package/dist/esm/OutgoingMessages/AwarenessMessage.js.map +1 -0
- package/dist/esm/OutgoingMessages/CloseMessage.js +21 -0
- package/dist/esm/OutgoingMessages/CloseMessage.js.map +1 -0
- package/dist/esm/OutgoingMessages/QueryAwarenessMessage.js +21 -0
- package/dist/esm/OutgoingMessages/QueryAwarenessMessage.js.map +1 -0
- package/dist/esm/OutgoingMessages/StatelessMessage.js +22 -0
- package/dist/esm/OutgoingMessages/StatelessMessage.js.map +1 -0
- package/dist/esm/OutgoingMessages/SubdocMessage.js +34 -0
- package/dist/esm/OutgoingMessages/SubdocMessage.js.map +1 -0
- package/dist/esm/OutgoingMessages/SyncStepOneMessage.js +24 -0
- package/dist/esm/OutgoingMessages/SyncStepOneMessage.js.map +1 -0
- package/dist/esm/OutgoingMessages/UpdateMessage.js +23 -0
- package/dist/esm/OutgoingMessages/UpdateMessage.js.map +1 -0
- package/dist/esm/PerfCounters.js +336 -0
- package/dist/esm/PerfCounters.js.map +1 -0
- package/dist/esm/QueryClient.js +117 -0
- package/dist/esm/QueryClient.js.map +1 -0
- package/dist/esm/RpcClient.js +456 -0
- package/dist/esm/RpcClient.js.map +1 -0
- package/dist/esm/SchemaTypes.js +38 -0
- package/dist/esm/SchemaTypes.js.map +1 -0
- package/dist/esm/SearchIndex.js +167 -0
- package/dist/esm/SearchIndex.js.map +1 -0
- package/dist/esm/ServerRegistry.js +139 -0
- package/dist/esm/ServerRegistry.js.map +1 -0
- package/dist/esm/ServerReset.js +170 -0
- package/dist/esm/ServerReset.js.map +1 -0
- package/dist/esm/TokenManager.js +236 -0
- package/dist/esm/TokenManager.js.map +1 -0
- package/dist/esm/TreeManager.js +655 -0
- package/dist/esm/TreeManager.js.map +1 -0
- package/dist/esm/TreeTimestamps.js +61 -0
- package/dist/esm/TreeTimestamps.js.map +1 -0
- package/dist/esm/auth.js +43 -0
- package/dist/esm/auth.js.map +1 -0
- package/dist/esm/awarenessStatesToArray.js +13 -0
- package/dist/esm/awarenessStatesToArray.js.map +1 -0
- package/dist/esm/docIds.js +53 -0
- package/dist/esm/docIds.js.map +1 -0
- package/dist/esm/encryptedContent.js +21 -0
- package/dist/esm/encryptedContent.js.map +1 -0
- package/dist/esm/index.js +61 -0
- package/dist/esm/messageRecord.js +64 -0
- package/dist/esm/messageRecord.js.map +1 -0
- package/dist/esm/sync/BroadcastChannelSync.js +160 -0
- package/dist/esm/sync/BroadcastChannelSync.js.map +1 -0
- package/dist/esm/types.js +54 -0
- package/dist/esm/types.js.map +1 -0
- package/dist/esm/webrtc/AbracadabraWebRTC.js +483 -0
- package/dist/esm/webrtc/AbracadabraWebRTC.js.map +1 -0
- package/dist/esm/webrtc/DataChannelRouter.js +124 -0
- package/dist/esm/webrtc/DataChannelRouter.js.map +1 -0
- package/dist/esm/webrtc/DevicePairingChannel.js +335 -0
- package/dist/esm/webrtc/DevicePairingChannel.js.map +1 -0
- package/dist/esm/webrtc/E2EEChannel.js +137 -0
- package/dist/esm/webrtc/E2EEChannel.js.map +1 -0
- package/dist/esm/webrtc/FileTransferChannel.js +250 -0
- package/dist/esm/webrtc/FileTransferChannel.js.map +1 -0
- package/dist/esm/webrtc/ManualSignaling.js +161 -0
- package/dist/esm/webrtc/ManualSignaling.js.map +1 -0
- package/dist/esm/webrtc/PeerConnection.js +96 -0
- package/dist/esm/webrtc/PeerConnection.js.map +1 -0
- package/dist/esm/webrtc/SignalingSocket.js +274 -0
- package/dist/esm/webrtc/SignalingSocket.js.map +1 -0
- package/dist/esm/webrtc/YjsDataChannel.js +135 -0
- package/dist/esm/webrtc/YjsDataChannel.js.map +1 -0
- package/dist/esm/webrtc/types.js +29 -0
- package/dist/esm/webrtc/types.js.map +1 -0
- package/dist/esm/x25519Convert.js +69 -0
- package/dist/esm/x25519Convert.js.map +1 -0
- package/dist/index.d.ts +26 -11
- package/package.json +6 -4
- package/dist/abracadabra-provider.esm.js +0 -14860
- package/dist/abracadabra-provider.esm.js.map +0 -1
|
@@ -0,0 +1,547 @@
|
|
|
1
|
+
import { AuthenticationMessage } from "./OutgoingMessages/AuthenticationMessage.js";
|
|
2
|
+
import { UpdateMessage } from "./OutgoingMessages/UpdateMessage.js";
|
|
3
|
+
import { AbracadabraBaseProvider } from "./AbracadabraBaseProvider.js";
|
|
4
|
+
import { OfflineStore } from "./OfflineStore.js";
|
|
5
|
+
import { SubdocMessage } from "./OutgoingMessages/SubdocMessage.js";
|
|
6
|
+
import * as Y from "yjs";
|
|
7
|
+
|
|
8
|
+
//#region packages/provider/src/AbracadabraProvider.ts
|
|
9
|
+
/** Validate that a string is a UUID acceptable by the server's DocId parser. */
|
|
10
|
+
function isValidDocId(id) {
|
|
11
|
+
return /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(id);
|
|
12
|
+
}
|
|
13
|
+
/**
|
|
14
|
+
* AbracadabraProvider extends AbracadabraBaseProvider with:
|
|
15
|
+
*
|
|
16
|
+
* 1. Subdocument lifecycle – intercepts Y.Doc subdoc events and syncs them
|
|
17
|
+
* with the server via MSG_SUBDOC (4) frames. Child documents get their
|
|
18
|
+
* own AbracadabraProvider instances sharing the same WebSocket connection.
|
|
19
|
+
*
|
|
20
|
+
* 2. Offline-first – persists CRDT updates to IndexedDB so they survive
|
|
21
|
+
* page reloads and network outages. On startup, the last saved document
|
|
22
|
+
* snapshot is applied immediately so the UI is usable without a server
|
|
23
|
+
* connection. On reconnect, pending updates are flushed and a fresh
|
|
24
|
+
* snapshot is saved.
|
|
25
|
+
*
|
|
26
|
+
* 3. Server-scoped storage – the IndexedDB database is keyed by server
|
|
27
|
+
* hostname + docId, preventing cross-server data contamination when the
|
|
28
|
+
* same docId is used on multiple servers.
|
|
29
|
+
*
|
|
30
|
+
* 4. Permission snapshotting – stores the resolved role locally so the UI
|
|
31
|
+
* can gate write operations without a network round-trip. Role is
|
|
32
|
+
* refreshed from the server on every reconnect.
|
|
33
|
+
*/
|
|
34
|
+
var AbracadabraProvider = class AbracadabraProvider extends AbracadabraBaseProvider {
|
|
35
|
+
static {
|
|
36
|
+
this.DEFAULT_MAX_CHILDREN = 64;
|
|
37
|
+
}
|
|
38
|
+
constructor(configuration) {
|
|
39
|
+
const resolved = { ...configuration };
|
|
40
|
+
const client = configuration.client ?? null;
|
|
41
|
+
if (client) {
|
|
42
|
+
const r = resolved;
|
|
43
|
+
if (!r.url && !r.websocketProvider) r.url = client.wsUrl;
|
|
44
|
+
if (resolved.token === void 0 && !configuration.cryptoIdentity) resolved.token = async () => {
|
|
45
|
+
await client.ensureFreshToken().catch(() => false);
|
|
46
|
+
return client.token ?? "";
|
|
47
|
+
};
|
|
48
|
+
}
|
|
49
|
+
super(resolved);
|
|
50
|
+
this.effectiveRole = null;
|
|
51
|
+
this._writeDropWarned = false;
|
|
52
|
+
this.childProviders = /* @__PURE__ */ new Map();
|
|
53
|
+
this.pendingLoads = /* @__PURE__ */ new Map();
|
|
54
|
+
this.childAccessTimes = /* @__PURE__ */ new Map();
|
|
55
|
+
this.pinnedChildren = /* @__PURE__ */ new Set();
|
|
56
|
+
this.transientChildren = /* @__PURE__ */ new Set();
|
|
57
|
+
this.unsubscribeToken = null;
|
|
58
|
+
this.boundHandleYSubdocsChange = this.handleYSubdocsChange.bind(this);
|
|
59
|
+
this.hasCachedContent = false;
|
|
60
|
+
this._offlineSettled = false;
|
|
61
|
+
this._syncEpoch = 0;
|
|
62
|
+
this._client = client;
|
|
63
|
+
this.abracadabraConfig = configuration;
|
|
64
|
+
this.subdocLoading = configuration.subdocLoading ?? "lazy";
|
|
65
|
+
this.maxChildren = configuration.maxChildren ?? AbracadabraProvider.DEFAULT_MAX_CHILDREN;
|
|
66
|
+
const serverOrigin = configuration.serverAgnostic ? void 0 : AbracadabraProvider.deriveServerOrigin(configuration, client);
|
|
67
|
+
this.offlineStore = configuration.disableOfflineStore ? null : new OfflineStore(configuration.name, serverOrigin);
|
|
68
|
+
this.on("subdocRegistered", configuration.onSubdocRegistered ?? (() => null));
|
|
69
|
+
this.on("subdocLoaded", configuration.onSubdocLoaded ?? (() => null));
|
|
70
|
+
this.document.on("subdocs", this.boundHandleYSubdocsChange);
|
|
71
|
+
this.unsubscribeToken = client?.onTokenChanged?.((token) => {
|
|
72
|
+
try {
|
|
73
|
+
this.configuration.websocketProvider?.refreshAuth?.(token);
|
|
74
|
+
} catch {}
|
|
75
|
+
}) ?? null;
|
|
76
|
+
this.on("synced", () => this.flushPendingUpdates());
|
|
77
|
+
this.restorePermissionSnapshot();
|
|
78
|
+
let readyTimer = null;
|
|
79
|
+
this.ready = Promise.race([this._initFromOfflineStore(), new Promise((resolve) => {
|
|
80
|
+
readyTimer = setTimeout(resolve, 5e3);
|
|
81
|
+
})]).catch((err) => {
|
|
82
|
+
this.emit("error", { message: `Offline store init failed: ${err?.message ?? err}` });
|
|
83
|
+
}).finally(() => {
|
|
84
|
+
if (readyTimer !== null) clearTimeout(readyTimer);
|
|
85
|
+
this._offlineSettled = true;
|
|
86
|
+
});
|
|
87
|
+
}
|
|
88
|
+
/**
|
|
89
|
+
* Send SyncStep1 only once the local snapshot is in the document.
|
|
90
|
+
*
|
|
91
|
+
* SyncStep1 carries our state vector, and the server answers with
|
|
92
|
+
* everything we lack. A child provider attached to an already-open socket
|
|
93
|
+
* (every `loadChild`, i.e. every page a reader opens) reached this before
|
|
94
|
+
* `_initFromOfflineStore()` had read IndexedDB — so it announced an EMPTY
|
|
95
|
+
* state vector and the server re-sent the whole document, even when an
|
|
96
|
+
* identical copy was on disk; both copies were then applied. Waiting for
|
|
97
|
+
* `ready` (milliseconds, and bounded by its own 5 s timeout) turns that
|
|
98
|
+
* into a diff. Nothing else in `startSync` is time-critical enough to send
|
|
99
|
+
* ahead of it, so the whole method is deferred together.
|
|
100
|
+
*/
|
|
101
|
+
startSync() {
|
|
102
|
+
if (this._offlineSettled || !this.offlineStore) {
|
|
103
|
+
super.startSync();
|
|
104
|
+
return;
|
|
105
|
+
}
|
|
106
|
+
const epoch = ++this._syncEpoch;
|
|
107
|
+
this.ready.then(() => {
|
|
108
|
+
if (epoch !== this._syncEpoch || !this.isAttached) return;
|
|
109
|
+
super.startSync();
|
|
110
|
+
});
|
|
111
|
+
}
|
|
112
|
+
/**
|
|
113
|
+
* Extract the server hostname from the provider configuration.
|
|
114
|
+
* Used to namespace the IndexedDB key so docs from different servers
|
|
115
|
+
* never share the same database.
|
|
116
|
+
*/
|
|
117
|
+
static deriveServerOrigin(config, client) {
|
|
118
|
+
try {
|
|
119
|
+
const url = config.url ?? config.websocketProvider?.url ?? client?.wsUrl;
|
|
120
|
+
if (url) return new URL(url).host;
|
|
121
|
+
} catch {}
|
|
122
|
+
}
|
|
123
|
+
/**
|
|
124
|
+
* Load the stored document snapshot (and any pending local edits) from
|
|
125
|
+
* IndexedDB and apply them to the Y.Doc so the UI can render without a
|
|
126
|
+
* server connection.
|
|
127
|
+
*
|
|
128
|
+
* Uses `this.offlineStore` as the Y.js update origin so that
|
|
129
|
+
* `documentUpdateHandler` ignores these replayed updates and does not
|
|
130
|
+
* attempt to re-persist or re-send them.
|
|
131
|
+
*/
|
|
132
|
+
async _initFromOfflineStore() {
|
|
133
|
+
if (!this.offlineStore) return;
|
|
134
|
+
const [snapshot, pending] = await Promise.all([this.offlineStore.getDocSnapshot().catch(() => null), this.offlineStore.getPendingUpdates().catch(() => [])]);
|
|
135
|
+
if (snapshot) {
|
|
136
|
+
Y.applyUpdate(this.document, snapshot, this.offlineStore);
|
|
137
|
+
this.hasCachedContent = true;
|
|
138
|
+
}
|
|
139
|
+
for (const update of pending) {
|
|
140
|
+
Y.applyUpdate(this.document, update, this.offlineStore);
|
|
141
|
+
this.hasCachedContent = true;
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
authenticatedHandler(scope) {
|
|
145
|
+
super.authenticatedHandler(scope);
|
|
146
|
+
const roleMap = {
|
|
147
|
+
service: "service",
|
|
148
|
+
admin: "admin",
|
|
149
|
+
owner: "owner",
|
|
150
|
+
editor: "editor",
|
|
151
|
+
viewer: "viewer",
|
|
152
|
+
observer: "observer",
|
|
153
|
+
"read-write": "editor",
|
|
154
|
+
readonly: "viewer"
|
|
155
|
+
};
|
|
156
|
+
const couldWrite = this.canWrite;
|
|
157
|
+
this.effectiveRole = roleMap[scope] ?? "observer";
|
|
158
|
+
this.offlineStore?.savePermissionSnapshot(this.effectiveRole);
|
|
159
|
+
if (this.canWrite) this._writeDropWarned = false;
|
|
160
|
+
this.emit("roleChanged", {
|
|
161
|
+
role: this.effectiveRole,
|
|
162
|
+
canWrite: this.canWrite
|
|
163
|
+
});
|
|
164
|
+
if (!couldWrite && this.canWrite && this.isSynced) this.flushPendingUpdates().catch(() => null);
|
|
165
|
+
}
|
|
166
|
+
/**
|
|
167
|
+
* Override sendToken to send a pubkey-only identity declaration instead of a
|
|
168
|
+
* JWT when cryptoIdentity is configured.
|
|
169
|
+
*
|
|
170
|
+
* The public key is the sole identifier in the crypto auth handshake.
|
|
171
|
+
* Username is decoupled from auth; it lives on the server as an immutable
|
|
172
|
+
* internal field and is never sent in the challenge-response frames.
|
|
173
|
+
*/
|
|
174
|
+
async sendToken() {
|
|
175
|
+
const { cryptoIdentity } = this.abracadabraConfig;
|
|
176
|
+
if (cryptoIdentity) {
|
|
177
|
+
const id = typeof cryptoIdentity === "function" ? await cryptoIdentity() : cryptoIdentity;
|
|
178
|
+
const json = JSON.stringify({
|
|
179
|
+
type: "identity",
|
|
180
|
+
publicKey: id.publicKey
|
|
181
|
+
});
|
|
182
|
+
this.send(AuthenticationMessage, {
|
|
183
|
+
token: json,
|
|
184
|
+
documentName: this.configuration.name
|
|
185
|
+
});
|
|
186
|
+
} else await super.sendToken();
|
|
187
|
+
}
|
|
188
|
+
/** Handle an auth_challenge message from the server. */
|
|
189
|
+
async handleAuthChallenge(challenge, expiresAt) {
|
|
190
|
+
const { signChallenge, cryptoIdentity } = this.abracadabraConfig;
|
|
191
|
+
if (!signChallenge || !cryptoIdentity) {
|
|
192
|
+
this.permissionDeniedHandler("No signChallenge callback configured");
|
|
193
|
+
return;
|
|
194
|
+
}
|
|
195
|
+
if (Date.now() > expiresAt * 1e3) {
|
|
196
|
+
this.permissionDeniedHandler("Challenge expired");
|
|
197
|
+
return;
|
|
198
|
+
}
|
|
199
|
+
const id = typeof cryptoIdentity === "function" ? await cryptoIdentity() : cryptoIdentity;
|
|
200
|
+
const signature = await signChallenge(challenge);
|
|
201
|
+
const proof = JSON.stringify({
|
|
202
|
+
type: "proof",
|
|
203
|
+
publicKey: id.publicKey,
|
|
204
|
+
signature,
|
|
205
|
+
challenge
|
|
206
|
+
});
|
|
207
|
+
this.send(AuthenticationMessage, {
|
|
208
|
+
token: proof,
|
|
209
|
+
documentName: this.configuration.name
|
|
210
|
+
});
|
|
211
|
+
}
|
|
212
|
+
async restorePermissionSnapshot() {
|
|
213
|
+
if (!this.offlineStore) return;
|
|
214
|
+
const role = await this.offlineStore.getPermissionSnapshot();
|
|
215
|
+
if (role && !this.effectiveRole) {
|
|
216
|
+
this.effectiveRole = role;
|
|
217
|
+
this.emit("roleChanged", {
|
|
218
|
+
role: this.effectiveRole,
|
|
219
|
+
canWrite: this.canWrite
|
|
220
|
+
});
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
get canWrite() {
|
|
224
|
+
return this.effectiveRole != null && this.effectiveRole !== "viewer" && this.effectiveRole !== "observer";
|
|
225
|
+
}
|
|
226
|
+
get canAwareness() {
|
|
227
|
+
return this.effectiveRole != null && this.effectiveRole !== "observer";
|
|
228
|
+
}
|
|
229
|
+
/** The AbracadabraClient instance for REST API access, if configured. */
|
|
230
|
+
get client() {
|
|
231
|
+
return this._client;
|
|
232
|
+
}
|
|
233
|
+
/** The OfflineStore instance, or null if offline storage is disabled. */
|
|
234
|
+
get store() {
|
|
235
|
+
return this.offlineStore;
|
|
236
|
+
}
|
|
237
|
+
/**
|
|
238
|
+
* Called when a MSG_STATELESS frame arrives from the server.
|
|
239
|
+
* Abracadabra uses stateless frames to deliver subdoc confirmations
|
|
240
|
+
* ({ type: "subdoc_registered", child_id, parent_id }).
|
|
241
|
+
*/
|
|
242
|
+
receiveStateless(payload) {
|
|
243
|
+
if (!payload.includes("\"auth_challenge\"") && !payload.includes("\"subdoc_registered\"")) {
|
|
244
|
+
super.receiveStateless(payload);
|
|
245
|
+
return;
|
|
246
|
+
}
|
|
247
|
+
let parsed;
|
|
248
|
+
try {
|
|
249
|
+
parsed = JSON.parse(payload);
|
|
250
|
+
} catch {
|
|
251
|
+
super.receiveStateless(payload);
|
|
252
|
+
return;
|
|
253
|
+
}
|
|
254
|
+
const msg = parsed;
|
|
255
|
+
if (msg.type === "auth_challenge" && msg.challenge && msg.expiresAt) {
|
|
256
|
+
this.handleAuthChallenge(msg.challenge, msg.expiresAt).catch((err) => {
|
|
257
|
+
this.emit("authenticationFailed", { reason: `Auth challenge error: ${err?.message ?? err}` });
|
|
258
|
+
});
|
|
259
|
+
return;
|
|
260
|
+
}
|
|
261
|
+
if (msg.type === "subdoc_registered" && msg.child_id && msg.parent_id) {
|
|
262
|
+
const event = {
|
|
263
|
+
childId: msg.child_id,
|
|
264
|
+
parentId: msg.parent_id
|
|
265
|
+
};
|
|
266
|
+
this.emit("subdocRegistered", event);
|
|
267
|
+
this.offlineStore?.removeSubdocFromQueue(msg.child_id);
|
|
268
|
+
if (this.subdocLoading === "eager") this.loadChild(msg.child_id);
|
|
269
|
+
return;
|
|
270
|
+
}
|
|
271
|
+
super.receiveStateless(payload);
|
|
272
|
+
}
|
|
273
|
+
/**
|
|
274
|
+
* Y.Doc emits 'subdocs' whenever subdocuments are added, removed, or loaded.
|
|
275
|
+
* We intercept additions to register them with the Abracadabra server.
|
|
276
|
+
*/
|
|
277
|
+
handleYSubdocsChange({ added, removed }) {
|
|
278
|
+
for (const subdoc of added) {
|
|
279
|
+
if (!isValidDocId(subdoc.guid)) continue;
|
|
280
|
+
this.registerSubdoc(subdoc);
|
|
281
|
+
}
|
|
282
|
+
for (const subdoc of removed) this.unloadChild(subdoc.guid);
|
|
283
|
+
}
|
|
284
|
+
/**
|
|
285
|
+
* Send a subdoc registration frame to the server.
|
|
286
|
+
* If offline the event is queued in IndexedDB and replayed on reconnect.
|
|
287
|
+
*/
|
|
288
|
+
registerSubdoc(subdoc) {
|
|
289
|
+
const childId = subdoc.guid;
|
|
290
|
+
if (this.isConnected) this.send(SubdocMessage, {
|
|
291
|
+
documentName: this.configuration.name,
|
|
292
|
+
childDocumentName: childId
|
|
293
|
+
});
|
|
294
|
+
else this.offlineStore?.queueSubdoc({
|
|
295
|
+
childId,
|
|
296
|
+
parentId: this.configuration.name,
|
|
297
|
+
createdAt: Date.now()
|
|
298
|
+
});
|
|
299
|
+
}
|
|
300
|
+
/** Get a loaded child provider by ID, or null if not yet loaded. */
|
|
301
|
+
getChild(childId) {
|
|
302
|
+
return this.childProviders.get(childId) ?? null;
|
|
303
|
+
}
|
|
304
|
+
/** Check if a child provider is already loaded. */
|
|
305
|
+
hasChild(childId) {
|
|
306
|
+
return this.childProviders.has(childId);
|
|
307
|
+
}
|
|
308
|
+
/**
|
|
309
|
+
* Whether a loaded child is currently transient — loaded with
|
|
310
|
+
* `{ evictable: false }` (e.g. by a background indexer/sync) and not since
|
|
311
|
+
* promoted to a normal UI-held child. A later `loadChild(id)` with the
|
|
312
|
+
* default `evictable: true` clears this flag.
|
|
313
|
+
*
|
|
314
|
+
* Background loaders use this to decide whether they still own a child
|
|
315
|
+
* before unloading it: if the UI opened the same doc mid-sync, the child is
|
|
316
|
+
* no longer transient and must NOT be destroyed out from under the view.
|
|
317
|
+
*/
|
|
318
|
+
isChildTransient(childId) {
|
|
319
|
+
return this.transientChildren.has(childId);
|
|
320
|
+
}
|
|
321
|
+
/**
|
|
322
|
+
* Create (or return cached) a child AbracadabraProvider for a given
|
|
323
|
+
* child document id. Each child shares the parent's WebSocket via
|
|
324
|
+
* multiplexing.
|
|
325
|
+
*
|
|
326
|
+
* `evictable` (default `true`) controls whether the child enters the
|
|
327
|
+
* LRU pool. Pass `evictable: false` for transient loads — typically
|
|
328
|
+
* batch indexers (search, file extraction) that touch every doc in
|
|
329
|
+
* the tree and would otherwise blow out the cache, silently evicting
|
|
330
|
+
* subdocs the UI is actively using. Transient children are excluded
|
|
331
|
+
* from the LRU budget AND don't trigger eviction of other children.
|
|
332
|
+
* Callers MUST pair `loadChild(id, { evictable: false })` with an
|
|
333
|
+
* explicit `unloadChild(id)` once they're done.
|
|
334
|
+
*/
|
|
335
|
+
loadChild(childId, options = {}) {
|
|
336
|
+
if (!isValidDocId(childId)) return Promise.reject(/* @__PURE__ */ new Error(`loadChild: "${childId}" is not a valid document ID (must be a UUID). If this node was created with an older version of the app, delete it and recreate it.`));
|
|
337
|
+
if (childId === this.configuration.name) return Promise.resolve(this);
|
|
338
|
+
const evictable = options.evictable !== false;
|
|
339
|
+
if (this.childProviders.has(childId)) {
|
|
340
|
+
this.childAccessTimes.set(childId, Date.now());
|
|
341
|
+
if (evictable) this.transientChildren.delete(childId);
|
|
342
|
+
return Promise.resolve(this.childProviders.get(childId));
|
|
343
|
+
}
|
|
344
|
+
if (this.pendingLoads.has(childId)) return this.pendingLoads.get(childId);
|
|
345
|
+
const load = this._doLoadChild(childId, evictable);
|
|
346
|
+
this.pendingLoads.set(childId, load);
|
|
347
|
+
load.finally(() => this.pendingLoads.delete(childId));
|
|
348
|
+
return load;
|
|
349
|
+
}
|
|
350
|
+
async _doLoadChild(childId, evictable) {
|
|
351
|
+
const childDoc = new Y.Doc({ guid: childId });
|
|
352
|
+
this.registerSubdoc(childDoc);
|
|
353
|
+
const childProvider = new AbracadabraProvider({
|
|
354
|
+
name: childId,
|
|
355
|
+
document: childDoc,
|
|
356
|
+
websocketProvider: this.configuration.websocketProvider,
|
|
357
|
+
token: this.configuration.token,
|
|
358
|
+
lazyAwareness: true,
|
|
359
|
+
subdocLoading: this.subdocLoading,
|
|
360
|
+
disableOfflineStore: this.abracadabraConfig.disableOfflineStore,
|
|
361
|
+
client: this._client ?? void 0,
|
|
362
|
+
cryptoIdentity: this.abracadabraConfig.cryptoIdentity,
|
|
363
|
+
signChallenge: this.abracadabraConfig.signChallenge,
|
|
364
|
+
docKeyManager: this.abracadabraConfig.docKeyManager,
|
|
365
|
+
keystore: this.abracadabraConfig.keystore
|
|
366
|
+
});
|
|
367
|
+
childProvider.attach();
|
|
368
|
+
this.childProviders.set(childId, childProvider);
|
|
369
|
+
this.childAccessTimes.set(childId, Date.now());
|
|
370
|
+
if (!evictable) this.transientChildren.add(childId);
|
|
371
|
+
if (evictable) this.evictLRU();
|
|
372
|
+
this.emit("subdocLoaded", {
|
|
373
|
+
childId,
|
|
374
|
+
provider: childProvider
|
|
375
|
+
});
|
|
376
|
+
return childProvider;
|
|
377
|
+
}
|
|
378
|
+
unloadChild(childId) {
|
|
379
|
+
if (this.pinnedChildren.has(childId)) return;
|
|
380
|
+
const provider = this.childProviders.get(childId);
|
|
381
|
+
if (provider) {
|
|
382
|
+
provider.destroy();
|
|
383
|
+
this.childProviders.delete(childId);
|
|
384
|
+
this.childAccessTimes.delete(childId);
|
|
385
|
+
this.pinnedChildren.delete(childId);
|
|
386
|
+
this.transientChildren.delete(childId);
|
|
387
|
+
}
|
|
388
|
+
}
|
|
389
|
+
/**
|
|
390
|
+
* Mark a child as pinned so LRU eviction will not remove it.
|
|
391
|
+
* Use this when a document is actively being viewed by the user.
|
|
392
|
+
*/
|
|
393
|
+
pinChild(childId) {
|
|
394
|
+
this.pinnedChildren.add(childId);
|
|
395
|
+
this.transientChildren.delete(childId);
|
|
396
|
+
}
|
|
397
|
+
/**
|
|
398
|
+
* Unpin a child, allowing LRU eviction to reclaim it when capacity is exceeded.
|
|
399
|
+
*/
|
|
400
|
+
unpinChild(childId) {
|
|
401
|
+
this.pinnedChildren.delete(childId);
|
|
402
|
+
this.evictLRU();
|
|
403
|
+
}
|
|
404
|
+
/**
|
|
405
|
+
* Evict least-recently-used unpinned, non-transient child providers
|
|
406
|
+
* until the cache is at or below MAX_CHILDREN. Transient children
|
|
407
|
+
* (loaded with `{ evictable: false }`) are excluded from both the
|
|
408
|
+
* budget *and* the eviction list — they're invisible to the LRU and
|
|
409
|
+
* only go away when their loader explicitly calls `unloadChild`.
|
|
410
|
+
*/
|
|
411
|
+
evictLRU() {
|
|
412
|
+
let nonTransientCount = 0;
|
|
413
|
+
for (const id of this.childProviders.keys()) if (!this.transientChildren.has(id)) nonTransientCount++;
|
|
414
|
+
if (nonTransientCount <= this.maxChildren) return;
|
|
415
|
+
const evictable = [];
|
|
416
|
+
for (const [id] of this.childProviders) {
|
|
417
|
+
if (this.pinnedChildren.has(id)) continue;
|
|
418
|
+
if (this.transientChildren.has(id)) continue;
|
|
419
|
+
evictable.push({
|
|
420
|
+
id,
|
|
421
|
+
accessTime: this.childAccessTimes.get(id) ?? 0
|
|
422
|
+
});
|
|
423
|
+
}
|
|
424
|
+
evictable.sort((a, b) => a.accessTime - b.accessTime);
|
|
425
|
+
let toEvict = nonTransientCount - this.maxChildren;
|
|
426
|
+
for (const entry of evictable) {
|
|
427
|
+
if (toEvict <= 0) break;
|
|
428
|
+
this.unloadChild(entry.id);
|
|
429
|
+
toEvict--;
|
|
430
|
+
}
|
|
431
|
+
}
|
|
432
|
+
/** Return all currently-loaded child providers. */
|
|
433
|
+
get children() {
|
|
434
|
+
return this.childProviders;
|
|
435
|
+
}
|
|
436
|
+
/**
|
|
437
|
+
* Land buffered offline writes before the page goes away.
|
|
438
|
+
*
|
|
439
|
+
* `OfflineStore` coalesces local updates into one transaction per ~150 ms
|
|
440
|
+
* window (see WRITE_COALESCE_MS). That window is the only moment an edit
|
|
441
|
+
* exists in memory but not on disk, and a closing tab is exactly when it
|
|
442
|
+
* would be lost — so pagehide flushes it synchronously. `super.pageHide()`
|
|
443
|
+
* still clears our awareness state for peers.
|
|
444
|
+
*/
|
|
445
|
+
pageHide() {
|
|
446
|
+
super.pageHide();
|
|
447
|
+
this.offlineStore?.flushWritesSync();
|
|
448
|
+
}
|
|
449
|
+
/**
|
|
450
|
+
* Override to persist every local update to IndexedDB before sending it
|
|
451
|
+
* over the wire, ensuring no work is lost during connection outages.
|
|
452
|
+
*
|
|
453
|
+
* Updates applied by the server (origin === this) and updates replayed
|
|
454
|
+
* from the offline store (origin === this.offlineStore) are both skipped
|
|
455
|
+
* to avoid loops.
|
|
456
|
+
*/
|
|
457
|
+
documentUpdateHandler(update, origin) {
|
|
458
|
+
if (origin === this) return;
|
|
459
|
+
if (this.offlineStore !== null && origin === this.offlineStore) return;
|
|
460
|
+
this.offlineStore?.persistUpdate(update).catch(() => null);
|
|
461
|
+
if (!this.canWrite) {
|
|
462
|
+
if (!this._writeDropWarned) {
|
|
463
|
+
this._writeDropWarned = true;
|
|
464
|
+
try {
|
|
465
|
+
console.warn(`[abra:write-drop] dropping wire-send for doc "${this.configuration?.name}" — effectiveRole=${this.effectiveRole ?? "null"} (canWrite=false). Edits are persisted to IndexedDB only; the server will NOT receive them until this doc regains write access.`);
|
|
466
|
+
} catch {}
|
|
467
|
+
}
|
|
468
|
+
this.emit("writeDropped", {
|
|
469
|
+
name: this.configuration?.name,
|
|
470
|
+
role: this.effectiveRole ?? null
|
|
471
|
+
});
|
|
472
|
+
return;
|
|
473
|
+
}
|
|
474
|
+
super.documentUpdateHandler(update, origin);
|
|
475
|
+
}
|
|
476
|
+
/**
|
|
477
|
+
* After reconnect + sync:
|
|
478
|
+
* 1. Flush any updates that were generated while offline.
|
|
479
|
+
* 2. Flush any queued subdoc registrations.
|
|
480
|
+
* 3. Save a fresh full document snapshot for the next offline session.
|
|
481
|
+
*
|
|
482
|
+
* Uses a local `store` reference captured at the start so that a concurrent
|
|
483
|
+
* `destroy()` call setting `offlineStore = null` does not cause null-ref
|
|
484
|
+
* errors across async await boundaries.
|
|
485
|
+
*/
|
|
486
|
+
async flushPendingUpdates() {
|
|
487
|
+
const store = this.offlineStore;
|
|
488
|
+
if (!store) return;
|
|
489
|
+
await this.persistSnapshot();
|
|
490
|
+
if (this.canWrite) {
|
|
491
|
+
const updates = await store.getPendingUpdates();
|
|
492
|
+
if (updates.length > 0) {
|
|
493
|
+
for (const update of updates) this.send(UpdateMessage, {
|
|
494
|
+
update,
|
|
495
|
+
documentName: this.configuration.name
|
|
496
|
+
});
|
|
497
|
+
await this.persistSnapshot();
|
|
498
|
+
await store.clearPendingUpdates();
|
|
499
|
+
}
|
|
500
|
+
const pendingSubdocs = await store.getPendingSubdocs();
|
|
501
|
+
for (const { childId } of pendingSubdocs) this.send(SubdocMessage, {
|
|
502
|
+
documentName: this.configuration.name,
|
|
503
|
+
childDocumentName: childId
|
|
504
|
+
});
|
|
505
|
+
}
|
|
506
|
+
}
|
|
507
|
+
/**
|
|
508
|
+
* Persist the current merged document state to the offline store.
|
|
509
|
+
*
|
|
510
|
+
* This is the ONLY path that persists server-delivered content
|
|
511
|
+
* (`documentUpdateHandler` skips `origin === this`), so it MUST run for
|
|
512
|
+
* read-only roles too — otherwise observers/viewers get a permanently
|
|
513
|
+
* empty offline cache and every cold start waits for a full re-sync.
|
|
514
|
+
*
|
|
515
|
+
* Public so short-lived consumers that load a document, read it and
|
|
516
|
+
* immediately unload it (BackgroundSyncManager) can force the write to
|
|
517
|
+
* land before teardown instead of racing `destroy()`.
|
|
518
|
+
*/
|
|
519
|
+
async persistSnapshot() {
|
|
520
|
+
const store = this.offlineStore;
|
|
521
|
+
if (!store) return;
|
|
522
|
+
const snapshot = Y.encodeStateAsUpdate(this.document);
|
|
523
|
+
await store.saveDocSnapshot(snapshot).catch(() => null);
|
|
524
|
+
}
|
|
525
|
+
get isConnected() {
|
|
526
|
+
return this.configuration.websocketProvider.status === "connected";
|
|
527
|
+
}
|
|
528
|
+
destroy() {
|
|
529
|
+
this.unsubscribeToken?.();
|
|
530
|
+
this.unsubscribeToken = null;
|
|
531
|
+
this.document.off("subdocs", this.boundHandleYSubdocsChange);
|
|
532
|
+
const childIds = [...this.childProviders.keys()];
|
|
533
|
+
for (const provider of this.childProviders.values()) provider.destroy();
|
|
534
|
+
this.childProviders.clear();
|
|
535
|
+
this.childAccessTimes.clear();
|
|
536
|
+
this.pinnedChildren.clear();
|
|
537
|
+
const wsProviderMap = this.configuration.websocketProvider?.configuration?.providerMap;
|
|
538
|
+
if (wsProviderMap) for (const childId of childIds) wsProviderMap.delete(childId);
|
|
539
|
+
this.offlineStore?.destroy();
|
|
540
|
+
this.offlineStore = null;
|
|
541
|
+
super.destroy();
|
|
542
|
+
}
|
|
543
|
+
};
|
|
544
|
+
|
|
545
|
+
//#endregion
|
|
546
|
+
export { AbracadabraProvider };
|
|
547
|
+
//# sourceMappingURL=AbracadabraProvider.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"AbracadabraProvider.js","names":[],"sources":["../../src/AbracadabraProvider.ts"],"sourcesContent":["import * as Y from \"yjs\";\nimport { AbracadabraBaseProvider } from \"./AbracadabraBaseProvider.ts\";\nimport type { AbracadabraBaseProviderConfiguration } from \"./AbracadabraBaseProvider.ts\";\nimport type { AbracadabraWS } from \"./AbracadabraWS.ts\";\nimport { OfflineStore } from \"./OfflineStore.ts\";\nimport { SubdocMessage } from \"./OutgoingMessages/SubdocMessage.ts\";\nimport { UpdateMessage } from \"./OutgoingMessages/UpdateMessage.ts\";\nimport type {\n\tCryptoIdentity,\n\tEffectiveRole,\n\tonSubdocRegisteredParameters,\n\tonSubdocLoadedParameters,\n} from \"./types.ts\";\nimport { AuthenticationMessage } from \"./OutgoingMessages/AuthenticationMessage.ts\";\nimport type { AbracadabraClient } from \"./AbracadabraClient.ts\";\nimport type { DocKeyManager } from \"./DocKeyManager.ts\";\nimport type { CryptoIdentityKeystore } from \"./CryptoIdentityKeystore.ts\";\n\nexport interface AbracadabraProviderConfiguration\n\textends Omit<AbracadabraBaseProviderConfiguration, \"url\" | \"websocketProvider\"> {\n\t/**\n\t * Subdocument loading strategy.\n\t * - \"lazy\" (default) – child providers are created only when explicitly requested.\n\t * - \"eager\" – all children returned by the server on connect are loaded automatically.\n\t */\n\tsubdocLoading?: \"lazy\" | \"eager\";\n\n\t/** Called when the server confirms a subdoc registration. */\n\tonSubdocRegistered?: (data: onSubdocRegisteredParameters) => void;\n\n\t/** Called when a child AbracadabraProvider has been created and attached. */\n\tonSubdocLoaded?: (data: onSubdocLoadedParameters) => void;\n\n\t/**\n\t * Disable the IndexedDB offline store. Useful for server-side rendering\n\t * or testing environments that lack IndexedDB.\n\t */\n\tdisableOfflineStore?: boolean;\n\n\t/**\n\t * Identity for passwordless crypto auth (Model B multi-key).\n\t * Mutually exclusive with token.\n\t */\n\tcryptoIdentity?: CryptoIdentity | (() => Promise<CryptoIdentity>);\n\n\t/**\n\t * Signs a base64url challenge and returns a base64url signature.\n\t * Required when cryptoIdentity is set.\n\t */\n\tsignChallenge?: (challenge: string) => Promise<string>;\n\n\t/**\n\t * AbracadabraClient instance for REST API access.\n\t * When provided, the provider automatically derives the WebSocket URL\n\t * and token from the client (unless explicitly overridden).\n\t */\n\tclient?: AbracadabraClient;\n\n\t/** WebSocket URL. Derived from client.wsUrl if client is provided. */\n\turl?: string;\n\n\t/** DocKeyManager for E2E/CSE encryption key management. */\n\tdocKeyManager?: DocKeyManager;\n\t/** Keystore for X25519 key derivation. */\n\tkeystore?: CryptoIdentityKeystore;\n\n\t/** Shared WebSocket connection (use when multiplexing multiple root documents). */\n\twebsocketProvider?: AbracadabraWS;\n\n\t/**\n\t * When true, the IndexedDB offline store is NOT scoped by server origin.\n\t * This allows a single document to be synced across multiple servers while\n\t * sharing one local store. Used for the identity doc.\n\t */\n\tserverAgnostic?: boolean;\n\n\t/**\n\t * Maximum number of simultaneously cached child providers before LRU\n\t * eviction reclaims the least-recently-used unpinned ones. Default 20.\n\t * Apps that legitimately need more docs alive (e.g. background-sync of\n\t * a working set) should raise this; pin individual children with\n\t * `pinChild()` to make them eviction-immune regardless of cap.\n\t */\n\tmaxChildren?: number;\n}\n\n/** Validate that a string is a UUID acceptable by the server's DocId parser. */\nfunction isValidDocId(id: string): boolean {\n\treturn /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(id);\n}\n\n/**\n * AbracadabraProvider extends AbracadabraBaseProvider with:\n *\n * 1. Subdocument lifecycle – intercepts Y.Doc subdoc events and syncs them\n * with the server via MSG_SUBDOC (4) frames. Child documents get their\n * own AbracadabraProvider instances sharing the same WebSocket connection.\n *\n * 2. Offline-first – persists CRDT updates to IndexedDB so they survive\n * page reloads and network outages. On startup, the last saved document\n * snapshot is applied immediately so the UI is usable without a server\n * connection. On reconnect, pending updates are flushed and a fresh\n * snapshot is saved.\n *\n * 3. Server-scoped storage – the IndexedDB database is keyed by server\n * hostname + docId, preventing cross-server data contamination when the\n * same docId is used on multiple servers.\n *\n * 4. Permission snapshotting – stores the resolved role locally so the UI\n * can gate write operations without a network round-trip. Role is\n * refreshed from the server on every reconnect.\n */\nexport class AbracadabraProvider extends AbracadabraBaseProvider {\n\tpublic effectiveRole: EffectiveRole = null;\n\n\t// Throttle the \"write-drop\" warning/event to once per (role) transition so a\n\t// read-only editor session doesn't flood the console on every keystroke.\n\tprivate _writeDropWarned = false;\n\n\tprivate _client: AbracadabraClient | null;\n\tprivate offlineStore: OfflineStore | null;\n\tprivate childProviders = new Map<string, AbracadabraProvider>();\n\tprivate pendingLoads = new Map<string, Promise<AbracadabraProvider>>();\n\tprivate subdocLoading: \"lazy\" | \"eager\";\n\n\t/** LRU tracking: childId → last access timestamp */\n\tprivate childAccessTimes = new Map<string, number>();\n\t/** Pinned children that must not be evicted (e.g. actively viewed docs) */\n\tprivate pinnedChildren = new Set<string>();\n\t/**\n\t * Children explicitly marked as transient (e.g. by a background indexer\n\t * that scans the whole tree). They:\n\t * - never count toward the LRU `maxChildren` budget\n\t * - never cause eviction of OTHER children when they're added\n\t * - are eligible for LRU eviction themselves only after they get\n\t * unmarked or explicitly unloaded\n\t *\n\t * The motivating case: `useSearchIndex` / `useFileIndex` walk every doc\n\t * in the tree calling `loadChild`. With a default cap of 20 and a tree\n\t * of 76+ subdocs, the LRU silently evicted whichever subdoc the UI was\n\t * actually showing — a CLOSE storm and dead awareness for the user.\n\t * Transient loads sidestep that pool entirely.\n\t */\n\tprivate transientChildren = new Set<string>();\n\t/**\n\t * Default cap on simultaneously cached child providers (excluding\n\t * transient ones — see `transientChildren`). Configurable per-instance\n\t * via `maxChildren`. Bumped from 20 → 64 because real apps routinely\n\t * have trees with dozens of subdocs being touched and 20 caused silent\n\t * subdoc eviction (with awareness loss) on perfectly normal load.\n\t */\n\tprivate static readonly DEFAULT_MAX_CHILDREN = 64;\n\tprivate readonly maxChildren: number;\n\n\tprivate abracadabraConfig: AbracadabraProviderConfiguration;\n\n\t/** Detach from the client's token broadcasts. See the constructor. */\n\tprivate unsubscribeToken: (() => void) | null = null;\n\n\tprivate readonly boundHandleYSubdocsChange = this.handleYSubdocsChange.bind(this);\n\n\t/**\n\t * Resolves once the document has been pre-populated from the local\n\t * IndexedDB snapshot (if one exists). Await this before rendering UI\n\t * that depends on the document content — it resolves immediately when\n\t * the offline store is disabled or when no snapshot has been saved yet.\n\t */\n\tpublic readonly ready: Promise<void>;\n\n\t/**\n\t * True once `_initFromOfflineStore()` has applied a non-empty snapshot or\n\t * at least one pending update to the Y.Doc. Lets the UI decide to render\n\t * cached content immediately instead of waiting for a server round-trip.\n\t * Only meaningful after `await ready`.\n\t */\n\tpublic hasCachedContent = false;\n\n\t/** Set once `ready` has settled (snapshot applied, failed or timed out). */\n\tprivate _offlineSettled = false;\n\t/** Bumped per `startSync()`, so only the latest deferred one sends. */\n\tprivate _syncEpoch = 0;\n\n\tconstructor(configuration: AbracadabraProviderConfiguration) {\n\t\t// Derive URL and token from client when not explicitly set.\n\t\tconst resolved = { ...configuration } as AbracadabraBaseProviderConfiguration;\n\t\tconst client = configuration.client ?? null;\n\n\t\tif (client) {\n\t\t\t// `url` is no longer part of the base provider config — the URL\n\t\t\t// rides on `websocketProvider`. Keep the legacy field assignment\n\t\t\t// for downstream consumers that read it off the merged object,\n\t\t\t// but cast through `any` since `resolved` doesn't declare it.\n\t\t\tconst r = resolved as { url?: string; websocketProvider?: AbracadabraWS };\n\t\t\tif (!r.url && !r.websocketProvider) {\n\t\t\t\tr.url = client.wsUrl;\n\t\t\t}\n\t\t\tif (resolved.token === undefined && !configuration.cryptoIdentity) {\n\t\t\t\t// AWAITS a freshness check, and that await is the fix rather\n\t\t\t\t// than an optimisation. This closure is what `sendToken()`\n\t\t\t\t// resolves for the AUTH frame on every handshake — initial and\n\t\t\t\t// reconnect alike — and a handshake carrying a lapsed token is\n\t\t\t\t// refused outright (`auth rejected: JWT error:\n\t\t\t\t// ExpiredSignature`), after which the provider never syncs and\n\t\t\t\t// the only symptom anybody sees is `Sync timed out`. Four hours\n\t\t\t\t// into a deploy that is every new socket, forever.\n\t\t\t\t//\n\t\t\t\t// A no-op when the token is fresh, and single-flighted, so the\n\t\t\t\t// cost on the common path is one subtraction. On a client with\n\t\t\t\t// no session renewer installed it is a no-op entirely, which is\n\t\t\t\t// the pre-existing behaviour.\n\t\t\t\tresolved.token = async () => {\n\t\t\t\t\tawait client.ensureFreshToken().catch(() => false);\n\t\t\t\t\treturn client.token ?? \"\";\n\t\t\t\t};\n\t\t\t}\n\t\t}\n\n\t\tsuper(resolved);\n\t\tthis._client = client;\n\t\tthis.abracadabraConfig = configuration;\n\t\tthis.subdocLoading = configuration.subdocLoading ?? \"lazy\";\n\t\tthis.maxChildren = configuration.maxChildren ?? AbracadabraProvider.DEFAULT_MAX_CHILDREN;\n\n\t\tconst serverOrigin = configuration.serverAgnostic\n\t\t\t? undefined\n\t\t\t: AbracadabraProvider.deriveServerOrigin(configuration, client);\n\t\tthis.offlineStore = configuration.disableOfflineStore\n\t\t\t? null\n\t\t\t: new OfflineStore(configuration.name, serverOrigin);\n\n\t\tthis.on(\n\t\t\t\"subdocRegistered\",\n\t\t\tconfiguration.onSubdocRegistered ?? (() => null),\n\t\t);\n\t\tthis.on(\"subdocLoaded\", configuration.onSubdocLoaded ?? (() => null));\n\n\t\t// Intercept Y.Doc subdoc lifecycle events.\n\t\tthis.document.on(\"subdocs\", this.boundHandleYSubdocsChange);\n\n\t\t// Keep an ALREADY-OPEN socket armed when the session is renewed.\n\t\t//\n\t\t// The token closure above covers every new handshake; this covers the\n\t\t// connection that is already up. Without it an ordinary session's\n\t\t// socket is dropped by the server on the first sync or awareness frame\n\t\t// past `exp` and then reconnect-storms, and an elevated one keeps\n\t\t// running on a session the server will not extend. The dedupe lives on\n\t\t// the socket, so N providers multiplexed on one connection still send\n\t\t// exactly one frame.\n\t\tthis.unsubscribeToken =\n\t\t\tclient?.onTokenChanged?.((token) => {\n\t\t\t\ttry {\n\t\t\t\t\t(\n\t\t\t\t\t\tthis.configuration.websocketProvider as AbracadabraWS | undefined\n\t\t\t\t\t)?.refreshAuth?.(token);\n\t\t\t\t} catch {\n\t\t\t\t\t/* a torn-down socket has nothing to re-arm */\n\t\t\t\t}\n\t\t\t}) ?? null;\n\n\t\t// Flush offline updates once we're back online and synced.\n\t\tthis.on(\"synced\", () => this.flushPendingUpdates());\n\n\t\t// Restore permission snapshot while offline.\n\t\tthis.restorePermissionSnapshot();\n\n\t\t// Pre-populate the Y.Doc from the local snapshot so the UI works offline.\n\t\t//\n\t\t// The timeout is a bail-out for a wedged IndexedDB, and `Promise.race`\n\t\t// does not cancel the loser — so before this cleared it, every provider\n\t\t// held a live 5 s timer long after the offline load had finished in\n\t\t// milliseconds. A burst of children left dozens of them pending at once,\n\t\t// and in Node an uncleared timer also keeps the event loop alive, which\n\t\t// is why short-lived CLI/MCP processes lingered on exit.\n\t\tlet readyTimer: ReturnType<typeof setTimeout> | null = null;\n\t\tthis.ready = Promise.race([\n\t\t\tthis._initFromOfflineStore(),\n\t\t\tnew Promise<void>((resolve) => {\n\t\t\t\treadyTimer = setTimeout(resolve, 5_000);\n\t\t\t}),\n\t\t])\n\t\t\t.catch((err) => {\n\t\t\t\tthis.emit(\"error\", { message: `Offline store init failed: ${err?.message ?? err}` });\n\t\t\t})\n\t\t\t.finally(() => {\n\t\t\t\tif (readyTimer !== null) clearTimeout(readyTimer);\n\t\t\t\tthis._offlineSettled = true;\n\t\t\t});\n\t}\n\n\t/**\n\t * Send SyncStep1 only once the local snapshot is in the document.\n\t *\n\t * SyncStep1 carries our state vector, and the server answers with\n\t * everything we lack. A child provider attached to an already-open socket\n\t * (every `loadChild`, i.e. every page a reader opens) reached this before\n\t * `_initFromOfflineStore()` had read IndexedDB — so it announced an EMPTY\n\t * state vector and the server re-sent the whole document, even when an\n\t * identical copy was on disk; both copies were then applied. Waiting for\n\t * `ready` (milliseconds, and bounded by its own 5 s timeout) turns that\n\t * into a diff. Nothing else in `startSync` is time-critical enough to send\n\t * ahead of it, so the whole method is deferred together.\n\t */\n\toverride startSync() {\n\t\tif (this._offlineSettled || !this.offlineStore) {\n\t\t\tsuper.startSync();\n\t\t\treturn;\n\t\t}\n\t\tconst epoch = ++this._syncEpoch;\n\t\tvoid this.ready.then(() => {\n\t\t\tif (epoch !== this._syncEpoch || !this.isAttached) return;\n\t\t\tsuper.startSync();\n\t\t});\n\t}\n\n\t// ── Server origin derivation ──────────────────────────────────────────────\n\n\t/**\n\t * Extract the server hostname from the provider configuration.\n\t * Used to namespace the IndexedDB key so docs from different servers\n\t * never share the same database.\n\t */\n\tprotected static deriveServerOrigin(\n\t\tconfig: AbracadabraProviderConfiguration,\n\t\tclient: AbracadabraClient | null,\n\t): string | undefined {\n\t\ttry {\n\t\t\tconst url =\n\t\t\t\tconfig.url ??\n\t\t\t\t(config.websocketProvider as AbracadabraWS | undefined)?.url ??\n\t\t\t\tclient?.wsUrl;\n\t\t\t// `host` (NOT `hostname`): the port is part of a server's identity.\n\t\t\t// Two servers on the same host but different ports would otherwise\n\t\t\t// share one IDB namespace — and since default-config servers also\n\t\t\t// share the same root_doc_id, one server's cached doc state silently\n\t\t\t// hydrated into the other's Y.Doc (cross-server contamination that\n\t\t\t// can then sync back upstream).\n\t\t\tif (url) return new URL(url).host;\n\t\t} catch {\n\t\t\t// Malformed URL — fall back to no scoping\n\t\t}\n\t\treturn undefined;\n\t}\n\n\t// ── Offline-first initialisation ──────────────────────────────────────────\n\n\t/**\n\t * Load the stored document snapshot (and any pending local edits) from\n\t * IndexedDB and apply them to the Y.Doc so the UI can render without a\n\t * server connection.\n\t *\n\t * Uses `this.offlineStore` as the Y.js update origin so that\n\t * `documentUpdateHandler` ignores these replayed updates and does not\n\t * attempt to re-persist or re-send them.\n\t */\n\tprivate async _initFromOfflineStore(): Promise<void> {\n\t\tif (!this.offlineStore) return;\n\n\t\t// Fetch snapshot and pending updates in parallel — each call opens the\n\t\t// IDB database, so running them concurrently roughly halves the latency.\n\t\tconst [snapshot, pending] = await Promise.all([\n\t\t\tthis.offlineStore.getDocSnapshot().catch(() => null),\n\t\t\tthis.offlineStore.getPendingUpdates().catch(() => []),\n\t\t]);\n\n\t\tif (snapshot) {\n\t\t\tY.applyUpdate(this.document, snapshot, this.offlineStore);\n\t\t\tthis.hasCachedContent = true;\n\t\t}\n\t\tfor (const update of pending) {\n\t\t\tY.applyUpdate(this.document, update, this.offlineStore);\n\t\t\tthis.hasCachedContent = true;\n\t\t}\n\t}\n\n\t// ── Auth / permission snapshot ────────────────────────────────────────────\n\n\toverride authenticatedHandler(scope: string) {\n\t\t// NB: super.authenticatedHandler emits \"authenticated\" BEFORE we set\n\t\t// effectiveRole below, so listeners of \"authenticated\" must not read the\n\t\t// role from this provider — use the \"roleChanged\" event emitted at the end\n\t\t// of this method instead, which fires once effectiveRole reflects `scope`.\n\t\tsuper.authenticatedHandler(scope);\n\n\t\tconst roleMap: Record<string, import(\"./types.ts\").EffectiveRole> = {\n\t\t\tservice: \"service\",\n\t\t\tadmin: \"admin\",\n\t\t\towner: \"owner\",\n\t\t\teditor: \"editor\",\n\t\t\tviewer: \"viewer\",\n\t\t\tobserver: \"observer\",\n\t\t\t\"read-write\": \"editor\",\n\t\t\treadonly: \"viewer\",\n\t\t};\n\t\tconst couldWrite = this.canWrite;\n\t\tthis.effectiveRole = roleMap[scope] ?? \"observer\";\n\n\t\tthis.offlineStore?.savePermissionSnapshot(this.effectiveRole);\n\n\t\t// Regaining write access re-arms the one-shot write-drop warning so a later\n\t\t// downgrade to a read-only role surfaces again.\n\t\tif (this.canWrite) this._writeDropWarned = false;\n\n\t\t// Reactive role signal for consumers (e.g. the editor edit-gate). Fired\n\t\t// AFTER effectiveRole is set so `canWrite` reflects the new role.\n\t\tthis.emit(\"roleChanged\", { role: this.effectiveRole, canWrite: this.canWrite });\n\n\t\t// Self-heal: if the server's authentication frame arrived AFTER the initial\n\t\t// sync (so the \"synced\" flush ran while the role was still null/stale and\n\t\t// skipped, see flushPendingUpdates' canWrite guard), and we now have write\n\t\t// access, push any updates that were queued to IndexedDB while we couldn't\n\t\t// send. Without this, edits made before auth completed stay stuck in IDB\n\t\t// (visible locally, never on the server) until the next reconnect.\n\t\tif (!couldWrite && this.canWrite && this.isSynced) {\n\t\t\tthis.flushPendingUpdates().catch(() => null);\n\t\t}\n\t}\n\n\t/**\n\t * Override sendToken to send a pubkey-only identity declaration instead of a\n\t * JWT when cryptoIdentity is configured.\n\t *\n\t * The public key is the sole identifier in the crypto auth handshake.\n\t * Username is decoupled from auth; it lives on the server as an immutable\n\t * internal field and is never sent in the challenge-response frames.\n\t */\n\toverride async sendToken() {\n\t\tconst { cryptoIdentity } = this.abracadabraConfig;\n\t\tif (cryptoIdentity) {\n\t\t\tconst id =\n\t\t\t\ttypeof cryptoIdentity === \"function\"\n\t\t\t\t\t? await cryptoIdentity()\n\t\t\t\t\t: cryptoIdentity;\n\t\t\tconst json = JSON.stringify({\n\t\t\t\ttype: \"identity\",\n\t\t\t\tpublicKey: id.publicKey,\n\t\t\t});\n\t\t\tthis.send(AuthenticationMessage, {\n\t\t\t\ttoken: json,\n\t\t\t\tdocumentName: this.configuration.name,\n\t\t\t});\n\t\t} else {\n\t\t\tawait super.sendToken();\n\t\t}\n\t}\n\n\t/** Handle an auth_challenge message from the server. */\n\tprivate async handleAuthChallenge(\n\t\tchallenge: string,\n\t\texpiresAt: number,\n\t): Promise<void> {\n\t\tconst { signChallenge, cryptoIdentity } = this.abracadabraConfig;\n\t\tif (!signChallenge || !cryptoIdentity) {\n\t\t\tthis.permissionDeniedHandler(\"No signChallenge callback configured\");\n\t\t\treturn;\n\t\t}\n\t\tif (Date.now() > expiresAt * 1000) {\n\t\t\tthis.permissionDeniedHandler(\"Challenge expired\");\n\t\t\treturn;\n\t\t}\n\t\tconst id =\n\t\t\ttypeof cryptoIdentity === \"function\"\n\t\t\t\t? await cryptoIdentity()\n\t\t\t\t: cryptoIdentity;\n\t\tconst signature = await signChallenge(challenge);\n\t\t// Proof frame sends only publicKey — username is fully decoupled from auth.\n\t\tconst proof = JSON.stringify({\n\t\t\ttype: \"proof\",\n\t\t\tpublicKey: id.publicKey,\n\t\t\tsignature,\n\t\t\tchallenge,\n\t\t});\n\t\tthis.send(AuthenticationMessage, {\n\t\t\ttoken: proof,\n\t\t\tdocumentName: this.configuration.name,\n\t\t});\n\t}\n\n\tprivate async restorePermissionSnapshot() {\n\t\tif (!this.offlineStore) return;\n\t\tconst role = await this.offlineStore.getPermissionSnapshot();\n\t\tif (role && !this.effectiveRole) {\n\t\t\tthis.effectiveRole = role as EffectiveRole;\n\t\t\t// Surface the cached role reactively so the offline edit-gate can open\n\t\t\t// before any server round-trip. The server's authenticatedHandler will\n\t\t\t// later override this with ground truth (and re-emit).\n\t\t\tthis.emit(\"roleChanged\", { role: this.effectiveRole, canWrite: this.canWrite });\n\t\t}\n\t}\n\n\tget canWrite(): boolean {\n\t\treturn this.effectiveRole != null && this.effectiveRole !== \"viewer\" && this.effectiveRole !== \"observer\";\n\t}\n\n\tget canAwareness(): boolean {\n\t\treturn this.effectiveRole != null && this.effectiveRole !== \"observer\";\n\t}\n\n\t/** The AbracadabraClient instance for REST API access, if configured. */\n\tget client(): AbracadabraClient | null {\n\t\treturn this._client;\n\t}\n\n\t/** The OfflineStore instance, or null if offline storage is disabled. */\n\tget store(): OfflineStore | null {\n\t\treturn this.offlineStore;\n\t}\n\n\t// ── Stateless message interception ────────────────────────────────────────\n\n\t/**\n\t * Called when a MSG_STATELESS frame arrives from the server.\n\t * Abracadabra uses stateless frames to deliver subdoc confirmations\n\t * ({ type: \"subdoc_registered\", child_id, parent_id }).\n\t */\n\toverride receiveStateless(payload: string) {\n\t\t// Only two envelopes are intercepted here. Every other stateless frame —\n\t\t// RPC and query frames above all, which are prefixed and not JSON at all —\n\t\t// used to be JSON.parse'd (and throw) here and then again in the base\n\t\t// class. A substring test is enough to know neither envelope is present.\n\t\tif (\n\t\t\t!payload.includes('\"auth_challenge\"') &&\n\t\t\t!payload.includes('\"subdoc_registered\"')\n\t\t) {\n\t\t\tsuper.receiveStateless(payload);\n\t\t\treturn;\n\t\t}\n\n\t\tlet parsed: unknown;\n\t\ttry {\n\t\t\tparsed = JSON.parse(payload);\n\t\t} catch {\n\t\t\tsuper.receiveStateless(payload);\n\t\t\treturn;\n\t\t}\n\n\t\tconst msg = parsed as {\n\t\t\ttype?: string;\n\t\t\tchild_id?: string;\n\t\t\tparent_id?: string;\n\t\t\tchallenge?: string;\n\t\t\texpiresAt?: number;\n\t\t};\n\n\t\t// Intercept auth_challenge before subdoc handling.\n\t\tif (msg.type === \"auth_challenge\" && msg.challenge && msg.expiresAt) {\n\t\t\tthis.handleAuthChallenge(msg.challenge, msg.expiresAt).catch((err) => {\n\t\t\t\tthis.emit(\"authenticationFailed\", { reason: `Auth challenge error: ${err?.message ?? err}` });\n\t\t\t});\n\t\t\treturn;\n\t\t}\n\n\t\tif (msg.type === \"subdoc_registered\" && msg.child_id && msg.parent_id) {\n\t\t\tconst event: onSubdocRegisteredParameters = {\n\t\t\t\tchildId: msg.child_id,\n\t\t\t\tparentId: msg.parent_id,\n\t\t\t};\n\t\t\tthis.emit(\"subdocRegistered\", event);\n\n\t\t\t// Remove from the offline queue now the server confirmed.\n\t\t\tthis.offlineStore?.removeSubdocFromQueue(msg.child_id);\n\n\t\t\t// Eager mode: auto-load the confirmed child.\n\t\t\tif (this.subdocLoading === \"eager\") {\n\t\t\t\tthis.loadChild(msg.child_id);\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\n\t\t// Unknown stateless payload – pass through to base class.\n\t\tsuper.receiveStateless(payload);\n\t}\n\n\t// ── Subdocument support ───────────────────────────────────────────────────\n\n\t/**\n\t * Y.Doc emits 'subdocs' whenever subdocuments are added, removed, or loaded.\n\t * We intercept additions to register them with the Abracadabra server.\n\t */\n\tprivate handleYSubdocsChange({\n\t\tadded,\n\t\tremoved,\n\t}: {\n\t\tadded: Set<Y.Doc>;\n\t\tremoved: Set<Y.Doc>;\n\t\tloaded: Set<Y.Doc>;\n\t}) {\n\t\tfor (const subdoc of added) {\n\t\t\tif (!isValidDocId(subdoc.guid)) continue;\n\t\t\tthis.registerSubdoc(subdoc);\n\t\t}\n\t\tfor (const subdoc of removed) {\n\t\t\tthis.unloadChild(subdoc.guid);\n\t\t}\n\t}\n\n\t/**\n\t * Send a subdoc registration frame to the server.\n\t * If offline the event is queued in IndexedDB and replayed on reconnect.\n\t */\n\tprivate registerSubdoc(subdoc: Y.Doc) {\n\t\tconst childId = subdoc.guid;\n\n\t\tif (this.isConnected) {\n\t\t\tthis.send(SubdocMessage, {\n\t\t\t\tdocumentName: this.configuration.name,\n\t\t\t\tchildDocumentName: childId,\n\t\t\t} as any);\n\t\t} else {\n\t\t\t// Queue for later replay when we reconnect.\n\t\t\tthis.offlineStore?.queueSubdoc({\n\t\t\t\tchildId,\n\t\t\t\tparentId: this.configuration.name,\n\t\t\t\tcreatedAt: Date.now(),\n\t\t\t});\n\t\t}\n\t}\n\n\t/** Get a loaded child provider by ID, or null if not yet loaded. */\n\tgetChild(childId: string): AbracadabraProvider | null {\n\t\treturn this.childProviders.get(childId) ?? null;\n\t}\n\n\t/** Check if a child provider is already loaded. */\n\thasChild(childId: string): boolean {\n\t\treturn this.childProviders.has(childId);\n\t}\n\n\t/**\n\t * Whether a loaded child is currently transient — loaded with\n\t * `{ evictable: false }` (e.g. by a background indexer/sync) and not since\n\t * promoted to a normal UI-held child. A later `loadChild(id)` with the\n\t * default `evictable: true` clears this flag.\n\t *\n\t * Background loaders use this to decide whether they still own a child\n\t * before unloading it: if the UI opened the same doc mid-sync, the child is\n\t * no longer transient and must NOT be destroyed out from under the view.\n\t */\n\tisChildTransient(childId: string): boolean {\n\t\treturn this.transientChildren.has(childId);\n\t}\n\n\t/**\n\t * Create (or return cached) a child AbracadabraProvider for a given\n\t * child document id. Each child shares the parent's WebSocket via\n\t * multiplexing.\n\t *\n\t * `evictable` (default `true`) controls whether the child enters the\n\t * LRU pool. Pass `evictable: false` for transient loads — typically\n\t * batch indexers (search, file extraction) that touch every doc in\n\t * the tree and would otherwise blow out the cache, silently evicting\n\t * subdocs the UI is actively using. Transient children are excluded\n\t * from the LRU budget AND don't trigger eviction of other children.\n\t * Callers MUST pair `loadChild(id, { evictable: false })` with an\n\t * explicit `unloadChild(id)` once they're done.\n\t */\n\tloadChild(\n\t\tchildId: string,\n\t\toptions: { evictable?: boolean } = {},\n\t): Promise<AbracadabraProvider> {\n\t\tif (!isValidDocId(childId)) {\n\t\t\treturn Promise.reject(\n\t\t\t\tnew Error(\n\t\t\t\t\t`loadChild: \"${childId}\" is not a valid document ID (must be a UUID). ` +\n\t\t\t\t\t`If this node was created with an older version of the app, delete it and recreate it.`,\n\t\t\t\t),\n\t\t\t);\n\t\t}\n\n\t\t// Self-load: caller asked for the doc this provider already owns.\n\t\t// Return `this` directly. Without this guard we'd build a sibling\n\t\t// AbracadabraProvider with the same `name` and call attach() on the\n\t\t// shared AbracadabraWS. The wsp's providerMap is keyed by name, so\n\t\t// the sibling silently REPLACES the root in the routing table — its\n\t\t// outgoing messages still reach the wire (send doesn't read the\n\t\t// map), but inbound frames addressed to that doc go to the sibling.\n\t\t// When the borrow ends and the sibling detaches, providerMap is\n\t\t// wiped of that name and the root is left orphaned: the UI still\n\t\t// reports `connected` + `synced`, but no awareness/sync messages\n\t\t// are received. Returning `this` is intentionally not added to\n\t\t// `childProviders` so LRU eviction never destroys the root, and\n\t\t// `unloadChild(self)` becomes a safe no-op (see below).\n\t\tif (childId === this.configuration.name) {\n\t\t\treturn Promise.resolve(this);\n\t\t}\n\n\t\tconst evictable = options.evictable !== false;\n\n\t\tif (this.childProviders.has(childId)) {\n\t\t\tthis.childAccessTimes.set(childId, Date.now());\n\t\t\t// A second load call promotes a child *out* of transient mode —\n\t\t\t// once a UI surface wants it, it's no longer \"just for indexing\"\n\t\t\t// and should be governed by the normal LRU budget. We never go\n\t\t\t// the other way (UI-loaded → transient) implicitly.\n\t\t\tif (evictable) this.transientChildren.delete(childId);\n\t\t\treturn Promise.resolve(this.childProviders.get(childId)!);\n\t\t}\n\n\t\t// Deduplicate concurrent calls: return the same Promise so both callers\n\t\t// get the exact same AbracadabraProvider instance.\n\t\tif (this.pendingLoads.has(childId)) {\n\t\t\treturn this.pendingLoads.get(childId)!;\n\t\t}\n\n\t\tconst load = this._doLoadChild(childId, evictable);\n\t\tthis.pendingLoads.set(childId, load);\n\t\tload.finally(() => this.pendingLoads.delete(childId));\n\t\treturn load;\n\t}\n\n\tprivate async _doLoadChild(\n\t\tchildId: string,\n\t\tevictable: boolean,\n\t): Promise<AbracadabraProvider> {\n\t\tconst childDoc = new Y.Doc({ guid: childId });\n\n\t\t// Fire-and-forget: tell the server this child belongs to the parent.\n\t\tthis.registerSubdoc(childDoc);\n\n\t\t// Reuse the parent's WebSocket for multiplexing — all children share a\n\t\t// single TCP connection instead of each opening its own. The shared\n\t\t// AbracadabraWS demuxes frames by documentName, so each child provider\n\t\t// still syncs independently. Because we pass websocketProvider the\n\t\t// child's manageSocket will be false, meaning destroy() detaches\n\t\t// without tearing down the shared connection.\n\t\tconst childProvider = new AbracadabraProvider({\n\t\t\tname: childId,\n\t\t\tdocument: childDoc,\n\t\t\twebsocketProvider: this.configuration.websocketProvider,\n\t\t\ttoken: this.configuration.token,\n\t\t\t// Presence on demand, not on load.\n\t\t\t//\n\t\t\t// Most children are never looked at by a human: the background sync\n\t\t\t// manager, the search indexer and the blob prefetcher between them open\n\t\t\t// every document in the space. Building an Awareness for each one costs\n\t\t\t// a 3 s interval and a wire frame every 15 s for as long as it stays\n\t\t\t// loaded, and broadcasts the user as \"present\" in documents they have\n\t\t\t// never opened. Measured before this change: 10 loaded children = 11\n\t\t\t// Awareness instances = 66 heartbeat callbacks per 20 s idle.\n\t\t\t//\n\t\t\t// Deferring is invisible to consumers. Anything that actually wants\n\t\t\t// presence — TipTap's CollaborationCaret via `useEditor`, presence\n\t\t\t// avatars, follow mode — reads `provider.awareness`, and that read is\n\t\t\t// what builds it, announces us and queries the room. The parent stays\n\t\t\t// eager, so the shared socket always has a heartbeat on it.\n\t\t\tlazyAwareness: true,\n\t\t\tsubdocLoading: this.subdocLoading,\n\t\t\tdisableOfflineStore: this.abracadabraConfig.disableOfflineStore,\n\t\t\tclient: this._client ?? undefined,\n\t\t\tcryptoIdentity: this.abracadabraConfig.cryptoIdentity,\n\t\t\tsignChallenge: this.abracadabraConfig.signChallenge,\n\t\t\tdocKeyManager: this.abracadabraConfig.docKeyManager,\n\t\t\tkeystore: this.abracadabraConfig.keystore,\n\t\t});\n\n\t\t// Shared websocketProvider means manageSocket is false, so the base\n\t\t// class constructor skips auto-attach. Attach explicitly.\n\t\tchildProvider.attach();\n\n\t\tthis.childProviders.set(childId, childProvider);\n\t\tthis.childAccessTimes.set(childId, Date.now());\n\t\tif (!evictable) this.transientChildren.add(childId);\n\n\t\t// Evict least-recently-used children if over capacity. A transient\n\t\t// load doesn't count toward the budget AND shouldn't kick others\n\t\t// out — it's an indexer scanning the tree, not the UI subscribing\n\t\t// to a new doc.\n\t\tif (evictable) this.evictLRU();\n\n\t\tthis.emit(\"subdocLoaded\", { childId, provider: childProvider });\n\n\t\treturn childProvider;\n\t}\n\n\tunloadChild(childId: string) {\n\t\t// A PINNED child is actively bound to an open UI view (a TipTap editor or\n\t\t// a page-type renderer reading this exact Y.Doc). Destroying it detaches\n\t\t// the Y.Doc and wipes its WebSocket route, so the open view goes blank —\n\t\t// \"title + meta render, body never arrives, fixed only by a full reload\".\n\t\t// Pinning is the UI's ownership claim: ONLY `unpinChild` may release a\n\t\t// pinned doc, after which LRU eviction reclaims it normally. Background\n\t\t// indexers (search/file index + blob prefetch via BackgroundSyncManager)\n\t\t// and subdoc-removal cleanup must never tear a pinned doc out from under\n\t\t// the view — this guard is the hard invariant that makes that impossible.\n\t\t// (Full provider `destroy()` bypasses this: it tears children down\n\t\t// directly, which is correct for whole-provider teardown.)\n\t\tif (this.pinnedChildren.has(childId)) return;\n\n\t\tconst provider = this.childProviders.get(childId);\n\t\tif (provider) {\n\t\t\tprovider.destroy();\n\t\t\tthis.childProviders.delete(childId);\n\t\t\tthis.childAccessTimes.delete(childId);\n\t\t\tthis.pinnedChildren.delete(childId);\n\t\t\tthis.transientChildren.delete(childId);\n\t\t}\n\t}\n\n\t/**\n\t * Mark a child as pinned so LRU eviction will not remove it.\n\t * Use this when a document is actively being viewed by the user.\n\t */\n\tpinChild(childId: string) {\n\t\tthis.pinnedChildren.add(childId);\n\t\t// Pinning means the UI is actively using this doc, so it is no longer a\n\t\t// mere transient indexer scan. Promote it OUT of transient so that:\n\t\t// (a) the background indexer's \"still ours\" check (`isChildTransient`)\n\t\t// correctly leaves it alone even when the UI reused the provider\n\t\t// WITHOUT going back through `loadChild` (e.g. resolving it from an\n\t\t// already-open tree) — the gap that let the indexer's finally-unload\n\t\t// destroy the doc being viewed; and\n\t\t// (b) once unpinned it is a normal evictable child again, instead of\n\t\t// leaking forever as an unreclaimable transient (evictLRU skips\n\t\t// transient children).\n\t\tthis.transientChildren.delete(childId);\n\t}\n\n\t/**\n\t * Unpin a child, allowing LRU eviction to reclaim it when capacity is exceeded.\n\t */\n\tunpinChild(childId: string) {\n\t\tthis.pinnedChildren.delete(childId);\n\t\t// Run eviction now in case we're over capacity\n\t\tthis.evictLRU();\n\t}\n\n\t/**\n\t * Evict least-recently-used unpinned, non-transient child providers\n\t * until the cache is at or below MAX_CHILDREN. Transient children\n\t * (loaded with `{ evictable: false }`) are excluded from both the\n\t * budget *and* the eviction list — they're invisible to the LRU and\n\t * only go away when their loader explicitly calls `unloadChild`.\n\t */\n\tprivate evictLRU() {\n\t\t// Count only non-transient children toward the budget. A search\n\t\t// indexer that pinned 100 transient children must NOT cause the\n\t\t// LRU to evict the 1 doc the user's editor is actively viewing.\n\t\tlet nonTransientCount = 0;\n\t\tfor (const id of this.childProviders.keys()) {\n\t\t\tif (!this.transientChildren.has(id)) nonTransientCount++;\n\t\t}\n\t\tif (nonTransientCount <= this.maxChildren) return;\n\n\t\tconst evictable: Array<{ id: string; accessTime: number }> = [];\n\t\tfor (const [id] of this.childProviders) {\n\t\t\tif (this.pinnedChildren.has(id)) continue;\n\t\t\tif (this.transientChildren.has(id)) continue;\n\t\t\tevictable.push({ id, accessTime: this.childAccessTimes.get(id) ?? 0 });\n\t\t}\n\t\tevictable.sort((a, b) => a.accessTime - b.accessTime);\n\n\t\tlet toEvict = nonTransientCount - this.maxChildren;\n\t\tfor (const entry of evictable) {\n\t\t\tif (toEvict <= 0) break;\n\t\t\tthis.unloadChild(entry.id);\n\t\t\ttoEvict--;\n\t\t}\n\t}\n\n\t/** Return all currently-loaded child providers. */\n\tget children(): Map<string, AbracadabraProvider> {\n\t\treturn this.childProviders;\n\t}\n\n\t/**\n\t * Land buffered offline writes before the page goes away.\n\t *\n\t * `OfflineStore` coalesces local updates into one transaction per ~150 ms\n\t * window (see WRITE_COALESCE_MS). That window is the only moment an edit\n\t * exists in memory but not on disk, and a closing tab is exactly when it\n\t * would be lost — so pagehide flushes it synchronously. `super.pageHide()`\n\t * still clears our awareness state for peers.\n\t */\n\toverride pageHide() {\n\t\tsuper.pageHide();\n\t\tthis.offlineStore?.flushWritesSync();\n\t}\n\n\t// ── Offline-first update persistence ─────────────────────────────────────\n\n\t/**\n\t * Override to persist every local update to IndexedDB before sending it\n\t * over the wire, ensuring no work is lost during connection outages.\n\t *\n\t * Updates applied by the server (origin === this) and updates replayed\n\t * from the offline store (origin === this.offlineStore) are both skipped\n\t * to avoid loops.\n\t */\n\toverride documentUpdateHandler(update: Uint8Array, origin: unknown) {\n\t\tif (origin === this) return;\n\t\t// Only skip when the store exists AND origin matches it.\n\t\t// Without the null-guard, a null offlineStore would match any update\n\t\t// with origin=null (the default for user transactions), silently\n\t\t// dropping all local writes when disableOfflineStore is true.\n\t\tif (this.offlineStore !== null && origin === this.offlineStore) return;\n\n\t\t// Persist locally first (fire-and-forget; errors are non-fatal).\n\t\tthis.offlineStore?.persistUpdate(update).catch(() => null);\n\n\t\t// Don't send writes over the wire if we lack write permission.\n\t\tif (!this.canWrite) {\n\t\t\t// Make the otherwise-silent write-drop observable. A local edit was just\n\t\t\t// persisted to IndexedDB but will NOT be sent to the server because this\n\t\t\t// provider's effective role can't write. If the editor UI let the user\n\t\t\t// type here, the UI's write-gate diverged from this provider's — the edit\n\t\t\t// lives only in local IDB (looks fine locally, empty on the server). We\n\t\t\t// emit a \"writeDropped\" event so consumers can surface a read-only /\n\t\t\t// \"unsynced changes\" banner, and warn once per role-transition so a\n\t\t\t// read-only session doesn't flood the console on every keystroke.\n\t\t\tif (!this._writeDropWarned) {\n\t\t\t\tthis._writeDropWarned = true;\n\t\t\t\ttry {\n\t\t\t\t\tconsole.warn(\n\t\t\t\t\t\t`[abra:write-drop] dropping wire-send for doc \"${this.configuration?.name}\" ` +\n\t\t\t\t\t\t\t`— effectiveRole=${this.effectiveRole ?? \"null\"} (canWrite=false). ` +\n\t\t\t\t\t\t\t`Edits are persisted to IndexedDB only; the server will NOT receive them ` +\n\t\t\t\t\t\t\t`until this doc regains write access.`,\n\t\t\t\t\t);\n\t\t\t\t} catch { /* noop */ }\n\t\t\t}\n\t\t\tthis.emit(\"writeDropped\", {\n\t\t\t\tname: this.configuration?.name,\n\t\t\t\trole: this.effectiveRole ?? null,\n\t\t\t});\n\t\t\treturn;\n\t\t}\n\n\t\tsuper.documentUpdateHandler(update, origin);\n\t}\n\n\t/**\n\t * After reconnect + sync:\n\t * 1. Flush any updates that were generated while offline.\n\t * 2. Flush any queued subdoc registrations.\n\t * 3. Save a fresh full document snapshot for the next offline session.\n\t *\n\t * Uses a local `store` reference captured at the start so that a concurrent\n\t * `destroy()` call setting `offlineStore = null` does not cause null-ref\n\t * errors across async await boundaries.\n\t */\n\tprivate async flushPendingUpdates() {\n\t\tconst store = this.offlineStore;\n\t\tif (!store) return;\n\n\t\t// Snapshot FIRST, before any awaited IndexedDB round-trip below.\n\t\t//\n\t\t// This used to run last, and the delay lost the write outright for\n\t\t// short-lived providers: BackgroundSyncManager loads a child, awaits\n\t\t// \"synced\", then unloads it in a `finally` — and `unloadChild` →\n\t\t// `destroy()` closes the offline store. The `getPendingUpdates()` await\n\t\t// here was enough of a gap for the store to be gone by the time the\n\t\t// snapshot was written, and the failure is swallowed by `.catch()`.\n\t\t// Measured on a real profile: 126 documents marked \"synced\" by\n\t\t// background sync, 11 with a persisted snapshot. That is an empty\n\t\t// offline cache for the other 115 — no offline reading, and nothing on\n\t\t// disk for the client-side search/backlink index to walk.\n\t\tawait this.persistSnapshot();\n\n\t\t// Flushing queued *local* writes / subdoc registrations over the wire\n\t\t// is only meaningful for writers — a read-only session has none and\n\t\t// must not send.\n\t\tif (this.canWrite) {\n\t\t\tconst updates = await store.getPendingUpdates();\n\t\t\tif (updates.length > 0) {\n\t\t\t\tfor (const update of updates) {\n\t\t\t\t\tthis.send(UpdateMessage, {\n\t\t\t\t\t\tupdate,\n\t\t\t\t\t\tdocumentName: this.configuration.name,\n\t\t\t\t\t});\n\t\t\t\t}\n\n\t\t\t\t// Re-snapshot BEFORE clearing, or an edit can end up in neither\n\t\t\t\t// store and vanish from the local cache.\n\t\t\t\t//\n\t\t\t\t// The snapshot above was taken before `getPendingUpdates()`, so\n\t\t\t\t// anything written in between is present in `updates` and absent\n\t\t\t\t// from that snapshot. Clearing at this point erased it from disk\n\t\t\t\t// entirely: the document still looked right on screen and on the\n\t\t\t\t// server, while the offline cache silently went stale — a cold\n\t\t\t\t// start would replay a document missing its most recent edits,\n\t\t\t\t// and the client-side search/backlink index would walk the same\n\t\t\t\t// stale copy.\n\t\t\t\t//\n\t\t\t\t// The window is small but it is exactly the moment a local edit\n\t\t\t\t// is most likely to occur (right after sync completes), and\n\t\t\t\t// `OfflineStore`'s write coalescing widened it: `getPendingUpdates`\n\t\t\t\t// now flushes a buffer that previously would already have been\n\t\t\t\t// written. Caught by \"a local edit reaches IndexedDB and survives\n\t\t\t\t// provider teardown\" under full-suite load.\n\t\t\t\t//\n\t\t\t\t// Costs a second encode only on flushes that actually carried\n\t\t\t\t// pending updates, which is the offline-reconnect path, not the\n\t\t\t\t// common one. The first snapshot stays where it is — it is what\n\t\t\t\t// wins the race against a short-lived provider being torn down.\n\t\t\t\tawait this.persistSnapshot();\n\t\t\t\tawait store.clearPendingUpdates();\n\t\t\t}\n\n\t\t\tconst pendingSubdocs = await store.getPendingSubdocs();\n\t\t\tfor (const { childId } of pendingSubdocs) {\n\t\t\t\tthis.send(SubdocMessage, {\n\t\t\t\t\tdocumentName: this.configuration.name,\n\t\t\t\t\tchildDocumentName: childId,\n\t\t\t\t} as any);\n\t\t\t}\n\t\t}\n\n\t}\n\n\t/**\n\t * Persist the current merged document state to the offline store.\n\t *\n\t * This is the ONLY path that persists server-delivered content\n\t * (`documentUpdateHandler` skips `origin === this`), so it MUST run for\n\t * read-only roles too — otherwise observers/viewers get a permanently\n\t * empty offline cache and every cold start waits for a full re-sync.\n\t *\n\t * Public so short-lived consumers that load a document, read it and\n\t * immediately unload it (BackgroundSyncManager) can force the write to\n\t * land before teardown instead of racing `destroy()`.\n\t */\n\tasync persistSnapshot(): Promise<void> {\n\t\tconst store = this.offlineStore;\n\t\tif (!store) return;\n\t\tconst snapshot = Y.encodeStateAsUpdate(this.document);\n\t\tawait store.saveDocSnapshot(snapshot).catch(() => null);\n\t}\n\n\tget isConnected(): boolean {\n\t\treturn (\n\t\t\t(this.configuration.websocketProvider as AbracadabraWS)\n\t\t\t\t.status === \"connected\"\n\t\t);\n\t}\n\n\t// ── Lifecycle ─────────────────────────────────────────────────────────────\n\n\toverride destroy() {\n\t\tthis.unsubscribeToken?.();\n\t\tthis.unsubscribeToken = null;\n\t\tthis.document.off(\"subdocs\", this.boundHandleYSubdocsChange);\n\n\t\t// Collect child IDs before destroying — detach() may skip cleanup if\n\t\t// a new provider already overwrote the slot during teardown/re-init races.\n\t\tconst childIds = [...this.childProviders.keys()];\n\n\t\tfor (const provider of this.childProviders.values()) {\n\t\t\tprovider.destroy();\n\t\t}\n\t\tthis.childProviders.clear();\n\t\tthis.childAccessTimes.clear();\n\t\tthis.pinnedChildren.clear();\n\n\t\t// Force-clear any stale providerMap entries for our children.\n\t\t// detach() only removes if current === provider, so orphans can remain\n\t\t// when a new provider attached before the old one was destroyed.\n\t\tconst wsProviderMap = this.configuration.websocketProvider?.configuration?.providerMap;\n\t\tif (wsProviderMap) {\n\t\t\tfor (const childId of childIds) {\n\t\t\t\twsProviderMap.delete(childId);\n\t\t\t}\n\t\t}\n\n\t\tthis.offlineStore?.destroy();\n\t\tthis.offlineStore = null;\n\n\t\tsuper.destroy();\n\t}\n}\n"],"mappings":";;;;;;;;;AAuFA,SAAS,aAAa,IAAqB;AAC1C,QAAO,kEAAkE,KAAK,GAAG;;;;;;;;;;;;;;;;;;;;;;;AAwBlF,IAAa,sBAAb,MAAa,4BAA4B,wBAAwB;;8BAuCjB;;CA+B/C,YAAY,eAAiD;EAE5D,MAAM,WAAW,EAAE,GAAG,eAAe;EACrC,MAAM,SAAS,cAAc,UAAU;AAEvC,MAAI,QAAQ;GAKX,MAAM,IAAI;AACV,OAAI,CAAC,EAAE,OAAO,CAAC,EAAE,kBAChB,GAAE,MAAM,OAAO;AAEhB,OAAI,SAAS,UAAU,UAAa,CAAC,cAAc,eAclD,UAAS,QAAQ,Y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