@abraca/dabra 2.90.0 → 2.91.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (71) hide show
  1. package/package.json +5 -11
  2. package/src/AbracadabraBaseProvider.ts +0 -963
  3. package/src/AbracadabraClient.ts +0 -1960
  4. package/src/AbracadabraProvider.ts +0 -915
  5. package/src/AbracadabraWS.ts +0 -695
  6. package/src/BackgroundSyncManager.ts +0 -856
  7. package/src/BackgroundSyncPersistence.ts +0 -140
  8. package/src/ChatClient.ts +0 -314
  9. package/src/CloseEvents.ts +0 -49
  10. package/src/ContentManager.ts +0 -246
  11. package/src/CoverReconcile.ts +0 -168
  12. package/src/CryptoIdentityKeystore.ts +0 -754
  13. package/src/DeviceRegistrationService.ts +0 -257
  14. package/src/DocConverters.ts +0 -1859
  15. package/src/DocKeyManager.ts +0 -163
  16. package/src/DocTypes.ts +0 -628
  17. package/src/DocUtils.ts +0 -251
  18. package/src/DocumentCache.ts +0 -210
  19. package/src/DocumentManager.ts +0 -410
  20. package/src/E2EAbracadabraProvider.ts +0 -426
  21. package/src/E2EOfflineStore.ts +0 -55
  22. package/src/EncryptedChatClient.ts +0 -173
  23. package/src/EncryptedY.ts +0 -145
  24. package/src/EventEmitter.ts +0 -59
  25. package/src/FileBlobStore.ts +0 -569
  26. package/src/IdentityDoc.ts +0 -711
  27. package/src/IncomingMessage.ts +0 -63
  28. package/src/MessageReceiver.ts +0 -151
  29. package/src/MessageSender.ts +0 -22
  30. package/src/MetaManager.ts +0 -194
  31. package/src/MnemonicKeyDerivation.ts +0 -171
  32. package/src/NodeConnect.ts +0 -63
  33. package/src/NodeIdentity.ts +0 -378
  34. package/src/NotificationsClient.ts +0 -207
  35. package/src/OfflineStore.ts +0 -294
  36. package/src/OutgoingMessage.ts +0 -25
  37. package/src/OutgoingMessages/AuthenticationMessage.ts +0 -23
  38. package/src/OutgoingMessages/AwarenessMessage.ts +0 -41
  39. package/src/OutgoingMessages/CloseMessage.ts +0 -17
  40. package/src/OutgoingMessages/QueryAwarenessMessage.ts +0 -17
  41. package/src/OutgoingMessages/StatelessMessage.ts +0 -18
  42. package/src/OutgoingMessages/SubdocMessage.ts +0 -35
  43. package/src/OutgoingMessages/SyncStepOneMessage.ts +0 -25
  44. package/src/OutgoingMessages/SyncStepTwoMessage.ts +0 -25
  45. package/src/OutgoingMessages/UpdateMessage.ts +0 -20
  46. package/src/QueryClient.ts +0 -209
  47. package/src/RpcClient.ts +0 -659
  48. package/src/SchemaTypes.ts +0 -179
  49. package/src/SearchIndex.ts +0 -250
  50. package/src/ServerRegistry.ts +0 -220
  51. package/src/ServerReset.ts +0 -222
  52. package/src/TokenManager.ts +0 -337
  53. package/src/TreeManager.ts +0 -894
  54. package/src/TreeTimestamps.ts +0 -101
  55. package/src/auth.ts +0 -62
  56. package/src/awarenessStatesToArray.ts +0 -10
  57. package/src/index.ts +0 -219
  58. package/src/messageRecord.ts +0 -121
  59. package/src/sync/BroadcastChannelSync.ts +0 -235
  60. package/src/types.ts +0 -790
  61. package/src/webrtc/AbracadabraWebRTC.ts +0 -683
  62. package/src/webrtc/DataChannelRouter.ts +0 -179
  63. package/src/webrtc/DevicePairingChannel.ts +0 -496
  64. package/src/webrtc/E2EEChannel.ts +0 -195
  65. package/src/webrtc/FileTransferChannel.ts +0 -367
  66. package/src/webrtc/ManualSignaling.ts +0 -204
  67. package/src/webrtc/PeerConnection.ts +0 -133
  68. package/src/webrtc/SignalingSocket.ts +0 -378
  69. package/src/webrtc/YjsDataChannel.ts +0 -203
  70. package/src/webrtc/index.ts +0 -26
  71. package/src/webrtc/types.ts +0 -177
@@ -1,915 +0,0 @@
1
- import * as Y from "yjs";
2
- import { AbracadabraBaseProvider } from "./AbracadabraBaseProvider.ts";
3
- import type { AbracadabraBaseProviderConfiguration } from "./AbracadabraBaseProvider.ts";
4
- import type { AbracadabraWS } from "./AbracadabraWS.ts";
5
- import { OfflineStore } from "./OfflineStore.ts";
6
- import { SubdocMessage } from "./OutgoingMessages/SubdocMessage.ts";
7
- import { UpdateMessage } from "./OutgoingMessages/UpdateMessage.ts";
8
- import type {
9
- CryptoIdentity,
10
- EffectiveRole,
11
- onSubdocRegisteredParameters,
12
- onSubdocLoadedParameters,
13
- } from "./types.ts";
14
- import { AuthenticationMessage } from "./OutgoingMessages/AuthenticationMessage.ts";
15
- import type { AbracadabraClient } from "./AbracadabraClient.ts";
16
- import type { DocKeyManager } from "./DocKeyManager.ts";
17
- import type { CryptoIdentityKeystore } from "./CryptoIdentityKeystore.ts";
18
-
19
- export interface AbracadabraProviderConfiguration
20
- extends Omit<AbracadabraBaseProviderConfiguration, "url" | "websocketProvider"> {
21
- /**
22
- * Subdocument loading strategy.
23
- * - "lazy" (default) – child providers are created only when explicitly requested.
24
- * - "eager" – all children returned by the server on connect are loaded automatically.
25
- */
26
- subdocLoading?: "lazy" | "eager";
27
-
28
- /** Called when the server confirms a subdoc registration. */
29
- onSubdocRegistered?: (data: onSubdocRegisteredParameters) => void;
30
-
31
- /** Called when a child AbracadabraProvider has been created and attached. */
32
- onSubdocLoaded?: (data: onSubdocLoadedParameters) => void;
33
-
34
- /**
35
- * Disable the IndexedDB offline store. Useful for server-side rendering
36
- * or testing environments that lack IndexedDB.
37
- */
38
- disableOfflineStore?: boolean;
39
-
40
- /**
41
- * Identity for passwordless crypto auth (Model B multi-key).
42
- * Mutually exclusive with token.
43
- */
44
- cryptoIdentity?: CryptoIdentity | (() => Promise<CryptoIdentity>);
45
-
46
- /**
47
- * Signs a base64url challenge and returns a base64url signature.
48
- * Required when cryptoIdentity is set.
49
- */
50
- signChallenge?: (challenge: string) => Promise<string>;
51
-
52
- /**
53
- * AbracadabraClient instance for REST API access.
54
- * When provided, the provider automatically derives the WebSocket URL
55
- * and token from the client (unless explicitly overridden).
56
- */
57
- client?: AbracadabraClient;
58
-
59
- /** WebSocket URL. Derived from client.wsUrl if client is provided. */
60
- url?: string;
61
-
62
- /** DocKeyManager for E2E/CSE encryption key management. */
63
- docKeyManager?: DocKeyManager;
64
- /** Keystore for X25519 key derivation. */
65
- keystore?: CryptoIdentityKeystore;
66
-
67
- /** Shared WebSocket connection (use when multiplexing multiple root documents). */
68
- websocketProvider?: AbracadabraWS;
69
-
70
- /**
71
- * When true, the IndexedDB offline store is NOT scoped by server origin.
72
- * This allows a single document to be synced across multiple servers while
73
- * sharing one local store. Used for the identity doc.
74
- */
75
- serverAgnostic?: boolean;
76
-
77
- /**
78
- * Maximum number of simultaneously cached child providers before LRU
79
- * eviction reclaims the least-recently-used unpinned ones. Default 20.
80
- * Apps that legitimately need more docs alive (e.g. background-sync of
81
- * a working set) should raise this; pin individual children with
82
- * `pinChild()` to make them eviction-immune regardless of cap.
83
- */
84
- maxChildren?: number;
85
- }
86
-
87
- /** Validate that a string is a UUID acceptable by the server's DocId parser. */
88
- function isValidDocId(id: string): boolean {
89
- return /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(id);
90
- }
91
-
92
- /**
93
- * AbracadabraProvider extends AbracadabraBaseProvider with:
94
- *
95
- * 1. Subdocument lifecycle – intercepts Y.Doc subdoc events and syncs them
96
- * with the server via MSG_SUBDOC (4) frames. Child documents get their
97
- * own AbracadabraProvider instances sharing the same WebSocket connection.
98
- *
99
- * 2. Offline-first – persists CRDT updates to IndexedDB so they survive
100
- * page reloads and network outages. On startup, the last saved document
101
- * snapshot is applied immediately so the UI is usable without a server
102
- * connection. On reconnect, pending updates are flushed and a fresh
103
- * snapshot is saved.
104
- *
105
- * 3. Server-scoped storage – the IndexedDB database is keyed by server
106
- * hostname + docId, preventing cross-server data contamination when the
107
- * same docId is used on multiple servers.
108
- *
109
- * 4. Permission snapshotting – stores the resolved role locally so the UI
110
- * can gate write operations without a network round-trip. Role is
111
- * refreshed from the server on every reconnect.
112
- */
113
- export class AbracadabraProvider extends AbracadabraBaseProvider {
114
- public effectiveRole: EffectiveRole = null;
115
-
116
- // Throttle the "write-drop" warning/event to once per (role) transition so a
117
- // read-only editor session doesn't flood the console on every keystroke.
118
- private _writeDropWarned = false;
119
-
120
- private _client: AbracadabraClient | null;
121
- private offlineStore: OfflineStore | null;
122
- private childProviders = new Map<string, AbracadabraProvider>();
123
- private pendingLoads = new Map<string, Promise<AbracadabraProvider>>();
124
- private subdocLoading: "lazy" | "eager";
125
-
126
- /** LRU tracking: childId → last access timestamp */
127
- private childAccessTimes = new Map<string, number>();
128
- /** Pinned children that must not be evicted (e.g. actively viewed docs) */
129
- private pinnedChildren = new Set<string>();
130
- /**
131
- * Children explicitly marked as transient (e.g. by a background indexer
132
- * that scans the whole tree). They:
133
- * - never count toward the LRU `maxChildren` budget
134
- * - never cause eviction of OTHER children when they're added
135
- * - are eligible for LRU eviction themselves only after they get
136
- * unmarked or explicitly unloaded
137
- *
138
- * The motivating case: `useSearchIndex` / `useFileIndex` walk every doc
139
- * in the tree calling `loadChild`. With a default cap of 20 and a tree
140
- * of 76+ subdocs, the LRU silently evicted whichever subdoc the UI was
141
- * actually showing — a CLOSE storm and dead awareness for the user.
142
- * Transient loads sidestep that pool entirely.
143
- */
144
- private transientChildren = new Set<string>();
145
- /**
146
- * Default cap on simultaneously cached child providers (excluding
147
- * transient ones — see `transientChildren`). Configurable per-instance
148
- * via `maxChildren`. Bumped from 20 → 64 because real apps routinely
149
- * have trees with dozens of subdocs being touched and 20 caused silent
150
- * subdoc eviction (with awareness loss) on perfectly normal load.
151
- */
152
- private static readonly DEFAULT_MAX_CHILDREN = 64;
153
- private readonly maxChildren: number;
154
-
155
- private abracadabraConfig: AbracadabraProviderConfiguration;
156
-
157
- private readonly boundHandleYSubdocsChange = this.handleYSubdocsChange.bind(this);
158
-
159
- /**
160
- * Resolves once the document has been pre-populated from the local
161
- * IndexedDB snapshot (if one exists). Await this before rendering UI
162
- * that depends on the document content — it resolves immediately when
163
- * the offline store is disabled or when no snapshot has been saved yet.
164
- */
165
- public readonly ready: Promise<void>;
166
-
167
- /**
168
- * True once `_initFromOfflineStore()` has applied a non-empty snapshot or
169
- * at least one pending update to the Y.Doc. Lets the UI decide to render
170
- * cached content immediately instead of waiting for a server round-trip.
171
- * Only meaningful after `await ready`.
172
- */
173
- public hasCachedContent = false;
174
-
175
- constructor(configuration: AbracadabraProviderConfiguration) {
176
- // Derive URL and token from client when not explicitly set.
177
- const resolved = { ...configuration } as AbracadabraBaseProviderConfiguration;
178
- const client = configuration.client ?? null;
179
-
180
- if (client) {
181
- // `url` is no longer part of the base provider config — the URL
182
- // rides on `websocketProvider`. Keep the legacy field assignment
183
- // for downstream consumers that read it off the merged object,
184
- // but cast through `any` since `resolved` doesn't declare it.
185
- const r = resolved as { url?: string; websocketProvider?: AbracadabraWS };
186
- if (!r.url && !r.websocketProvider) {
187
- r.url = client.wsUrl;
188
- }
189
- if (resolved.token === undefined && !configuration.cryptoIdentity) {
190
- resolved.token = () => client.token ?? "";
191
- }
192
- }
193
-
194
- super(resolved);
195
- this._client = client;
196
- this.abracadabraConfig = configuration;
197
- this.subdocLoading = configuration.subdocLoading ?? "lazy";
198
- this.maxChildren = configuration.maxChildren ?? AbracadabraProvider.DEFAULT_MAX_CHILDREN;
199
-
200
- const serverOrigin = configuration.serverAgnostic
201
- ? undefined
202
- : AbracadabraProvider.deriveServerOrigin(configuration, client);
203
- this.offlineStore = configuration.disableOfflineStore
204
- ? null
205
- : new OfflineStore(configuration.name, serverOrigin);
206
-
207
- this.on(
208
- "subdocRegistered",
209
- configuration.onSubdocRegistered ?? (() => null),
210
- );
211
- this.on("subdocLoaded", configuration.onSubdocLoaded ?? (() => null));
212
-
213
- // Intercept Y.Doc subdoc lifecycle events.
214
- this.document.on("subdocs", this.boundHandleYSubdocsChange);
215
-
216
- // Flush offline updates once we're back online and synced.
217
- this.on("synced", () => this.flushPendingUpdates());
218
-
219
- // Restore permission snapshot while offline.
220
- this.restorePermissionSnapshot();
221
-
222
- // Pre-populate the Y.Doc from the local snapshot so the UI works offline.
223
- this.ready = Promise.race([
224
- this._initFromOfflineStore(),
225
- new Promise<void>((resolve) => setTimeout(resolve, 5_000)),
226
- ]).catch((err) => {
227
- this.emit("error", { message: `Offline store init failed: ${err?.message ?? err}` });
228
- });
229
- }
230
-
231
- // ── Server origin derivation ──────────────────────────────────────────────
232
-
233
- /**
234
- * Extract the server hostname from the provider configuration.
235
- * Used to namespace the IndexedDB key so docs from different servers
236
- * never share the same database.
237
- */
238
- protected static deriveServerOrigin(
239
- config: AbracadabraProviderConfiguration,
240
- client: AbracadabraClient | null,
241
- ): string | undefined {
242
- try {
243
- const url =
244
- config.url ??
245
- (config.websocketProvider as AbracadabraWS | undefined)?.url ??
246
- client?.wsUrl;
247
- // `host` (NOT `hostname`): the port is part of a server's identity.
248
- // Two servers on the same host but different ports would otherwise
249
- // share one IDB namespace — and since default-config servers also
250
- // share the same root_doc_id, one server's cached doc state silently
251
- // hydrated into the other's Y.Doc (cross-server contamination that
252
- // can then sync back upstream).
253
- if (url) return new URL(url).host;
254
- } catch {
255
- // Malformed URL — fall back to no scoping
256
- }
257
- return undefined;
258
- }
259
-
260
- // ── Offline-first initialisation ──────────────────────────────────────────
261
-
262
- /**
263
- * Load the stored document snapshot (and any pending local edits) from
264
- * IndexedDB and apply them to the Y.Doc so the UI can render without a
265
- * server connection.
266
- *
267
- * Uses `this.offlineStore` as the Y.js update origin so that
268
- * `documentUpdateHandler` ignores these replayed updates and does not
269
- * attempt to re-persist or re-send them.
270
- */
271
- private async _initFromOfflineStore(): Promise<void> {
272
- if (!this.offlineStore) return;
273
-
274
- // Fetch snapshot and pending updates in parallel — each call opens the
275
- // IDB database, so running them concurrently roughly halves the latency.
276
- const [snapshot, pending] = await Promise.all([
277
- this.offlineStore.getDocSnapshot().catch(() => null),
278
- this.offlineStore.getPendingUpdates().catch(() => []),
279
- ]);
280
-
281
- if (snapshot) {
282
- Y.applyUpdate(this.document, snapshot, this.offlineStore);
283
- this.hasCachedContent = true;
284
- }
285
- for (const update of pending) {
286
- Y.applyUpdate(this.document, update, this.offlineStore);
287
- this.hasCachedContent = true;
288
- }
289
- }
290
-
291
- // ── Auth / permission snapshot ────────────────────────────────────────────
292
-
293
- override authenticatedHandler(scope: string) {
294
- // NB: super.authenticatedHandler emits "authenticated" BEFORE we set
295
- // effectiveRole below, so listeners of "authenticated" must not read the
296
- // role from this provider — use the "roleChanged" event emitted at the end
297
- // of this method instead, which fires once effectiveRole reflects `scope`.
298
- super.authenticatedHandler(scope);
299
-
300
- const roleMap: Record<string, import("./types.ts").EffectiveRole> = {
301
- service: "service",
302
- admin: "admin",
303
- owner: "owner",
304
- editor: "editor",
305
- viewer: "viewer",
306
- observer: "observer",
307
- "read-write": "editor",
308
- readonly: "viewer",
309
- };
310
- const couldWrite = this.canWrite;
311
- this.effectiveRole = roleMap[scope] ?? "observer";
312
-
313
- this.offlineStore?.savePermissionSnapshot(this.effectiveRole);
314
-
315
- // Regaining write access re-arms the one-shot write-drop warning so a later
316
- // downgrade to a read-only role surfaces again.
317
- if (this.canWrite) this._writeDropWarned = false;
318
-
319
- // Reactive role signal for consumers (e.g. the editor edit-gate). Fired
320
- // AFTER effectiveRole is set so `canWrite` reflects the new role.
321
- this.emit("roleChanged", { role: this.effectiveRole, canWrite: this.canWrite });
322
-
323
- // Self-heal: if the server's authentication frame arrived AFTER the initial
324
- // sync (so the "synced" flush ran while the role was still null/stale and
325
- // skipped, see flushPendingUpdates' canWrite guard), and we now have write
326
- // access, push any updates that were queued to IndexedDB while we couldn't
327
- // send. Without this, edits made before auth completed stay stuck in IDB
328
- // (visible locally, never on the server) until the next reconnect.
329
- if (!couldWrite && this.canWrite && this.isSynced) {
330
- this.flushPendingUpdates().catch(() => null);
331
- }
332
- }
333
-
334
- /**
335
- * Override sendToken to send a pubkey-only identity declaration instead of a
336
- * JWT when cryptoIdentity is configured.
337
- *
338
- * The public key is the sole identifier in the crypto auth handshake.
339
- * Username is decoupled from auth; it lives on the server as an immutable
340
- * internal field and is never sent in the challenge-response frames.
341
- */
342
- override async sendToken() {
343
- const { cryptoIdentity } = this.abracadabraConfig;
344
- if (cryptoIdentity) {
345
- const id =
346
- typeof cryptoIdentity === "function"
347
- ? await cryptoIdentity()
348
- : cryptoIdentity;
349
- const json = JSON.stringify({
350
- type: "identity",
351
- publicKey: id.publicKey,
352
- });
353
- this.send(AuthenticationMessage, {
354
- token: json,
355
- documentName: this.configuration.name,
356
- });
357
- } else {
358
- await super.sendToken();
359
- }
360
- }
361
-
362
- /** Handle an auth_challenge message from the server. */
363
- private async handleAuthChallenge(
364
- challenge: string,
365
- expiresAt: number,
366
- ): Promise<void> {
367
- const { signChallenge, cryptoIdentity } = this.abracadabraConfig;
368
- if (!signChallenge || !cryptoIdentity) {
369
- this.permissionDeniedHandler("No signChallenge callback configured");
370
- return;
371
- }
372
- if (Date.now() > expiresAt * 1000) {
373
- this.permissionDeniedHandler("Challenge expired");
374
- return;
375
- }
376
- const id =
377
- typeof cryptoIdentity === "function"
378
- ? await cryptoIdentity()
379
- : cryptoIdentity;
380
- const signature = await signChallenge(challenge);
381
- // Proof frame sends only publicKey — username is fully decoupled from auth.
382
- const proof = JSON.stringify({
383
- type: "proof",
384
- publicKey: id.publicKey,
385
- signature,
386
- challenge,
387
- });
388
- this.send(AuthenticationMessage, {
389
- token: proof,
390
- documentName: this.configuration.name,
391
- });
392
- }
393
-
394
- private async restorePermissionSnapshot() {
395
- if (!this.offlineStore) return;
396
- const role = await this.offlineStore.getPermissionSnapshot();
397
- if (role && !this.effectiveRole) {
398
- this.effectiveRole = role as EffectiveRole;
399
- // Surface the cached role reactively so the offline edit-gate can open
400
- // before any server round-trip. The server's authenticatedHandler will
401
- // later override this with ground truth (and re-emit).
402
- this.emit("roleChanged", { role: this.effectiveRole, canWrite: this.canWrite });
403
- }
404
- }
405
-
406
- get canWrite(): boolean {
407
- return this.effectiveRole != null && this.effectiveRole !== "viewer" && this.effectiveRole !== "observer";
408
- }
409
-
410
- get canAwareness(): boolean {
411
- return this.effectiveRole != null && this.effectiveRole !== "observer";
412
- }
413
-
414
- /** The AbracadabraClient instance for REST API access, if configured. */
415
- get client(): AbracadabraClient | null {
416
- return this._client;
417
- }
418
-
419
- /** The OfflineStore instance, or null if offline storage is disabled. */
420
- get store(): OfflineStore | null {
421
- return this.offlineStore;
422
- }
423
-
424
- // ── Stateless message interception ────────────────────────────────────────
425
-
426
- /**
427
- * Called when a MSG_STATELESS frame arrives from the server.
428
- * Abracadabra uses stateless frames to deliver subdoc confirmations
429
- * ({ type: "subdoc_registered", child_id, parent_id }).
430
- */
431
- override receiveStateless(payload: string) {
432
- let parsed: unknown;
433
- try {
434
- parsed = JSON.parse(payload);
435
- } catch {
436
- super.receiveStateless(payload);
437
- return;
438
- }
439
-
440
- const msg = parsed as {
441
- type?: string;
442
- child_id?: string;
443
- parent_id?: string;
444
- challenge?: string;
445
- expiresAt?: number;
446
- };
447
-
448
- // Intercept auth_challenge before subdoc handling.
449
- if (msg.type === "auth_challenge" && msg.challenge && msg.expiresAt) {
450
- this.handleAuthChallenge(msg.challenge, msg.expiresAt).catch((err) => {
451
- this.emit("authenticationFailed", { reason: `Auth challenge error: ${err?.message ?? err}` });
452
- });
453
- return;
454
- }
455
-
456
- if (msg.type === "subdoc_registered" && msg.child_id && msg.parent_id) {
457
- const event: onSubdocRegisteredParameters = {
458
- childId: msg.child_id,
459
- parentId: msg.parent_id,
460
- };
461
- this.emit("subdocRegistered", event);
462
-
463
- // Remove from the offline queue now the server confirmed.
464
- this.offlineStore?.removeSubdocFromQueue(msg.child_id);
465
-
466
- // Eager mode: auto-load the confirmed child.
467
- if (this.subdocLoading === "eager") {
468
- this.loadChild(msg.child_id);
469
- }
470
- return;
471
- }
472
-
473
- // Unknown stateless payload – pass through to base class.
474
- super.receiveStateless(payload);
475
- }
476
-
477
- // ── Subdocument support ───────────────────────────────────────────────────
478
-
479
- /**
480
- * Y.Doc emits 'subdocs' whenever subdocuments are added, removed, or loaded.
481
- * We intercept additions to register them with the Abracadabra server.
482
- */
483
- private handleYSubdocsChange({
484
- added,
485
- removed,
486
- }: {
487
- added: Set<Y.Doc>;
488
- removed: Set<Y.Doc>;
489
- loaded: Set<Y.Doc>;
490
- }) {
491
- for (const subdoc of added) {
492
- if (!isValidDocId(subdoc.guid)) continue;
493
- this.registerSubdoc(subdoc);
494
- }
495
- for (const subdoc of removed) {
496
- this.unloadChild(subdoc.guid);
497
- }
498
- }
499
-
500
- /**
501
- * Send a subdoc registration frame to the server.
502
- * If offline the event is queued in IndexedDB and replayed on reconnect.
503
- */
504
- private registerSubdoc(subdoc: Y.Doc) {
505
- const childId = subdoc.guid;
506
-
507
- if (this.isConnected) {
508
- this.send(SubdocMessage, {
509
- documentName: this.configuration.name,
510
- childDocumentName: childId,
511
- } as any);
512
- } else {
513
- // Queue for later replay when we reconnect.
514
- this.offlineStore?.queueSubdoc({
515
- childId,
516
- parentId: this.configuration.name,
517
- createdAt: Date.now(),
518
- });
519
- }
520
- }
521
-
522
- /** Get a loaded child provider by ID, or null if not yet loaded. */
523
- getChild(childId: string): AbracadabraProvider | null {
524
- return this.childProviders.get(childId) ?? null;
525
- }
526
-
527
- /** Check if a child provider is already loaded. */
528
- hasChild(childId: string): boolean {
529
- return this.childProviders.has(childId);
530
- }
531
-
532
- /**
533
- * Whether a loaded child is currently transient — loaded with
534
- * `{ evictable: false }` (e.g. by a background indexer/sync) and not since
535
- * promoted to a normal UI-held child. A later `loadChild(id)` with the
536
- * default `evictable: true` clears this flag.
537
- *
538
- * Background loaders use this to decide whether they still own a child
539
- * before unloading it: if the UI opened the same doc mid-sync, the child is
540
- * no longer transient and must NOT be destroyed out from under the view.
541
- */
542
- isChildTransient(childId: string): boolean {
543
- return this.transientChildren.has(childId);
544
- }
545
-
546
- /**
547
- * Create (or return cached) a child AbracadabraProvider for a given
548
- * child document id. Each child shares the parent's WebSocket via
549
- * multiplexing.
550
- *
551
- * `evictable` (default `true`) controls whether the child enters the
552
- * LRU pool. Pass `evictable: false` for transient loads — typically
553
- * batch indexers (search, file extraction) that touch every doc in
554
- * the tree and would otherwise blow out the cache, silently evicting
555
- * subdocs the UI is actively using. Transient children are excluded
556
- * from the LRU budget AND don't trigger eviction of other children.
557
- * Callers MUST pair `loadChild(id, { evictable: false })` with an
558
- * explicit `unloadChild(id)` once they're done.
559
- */
560
- loadChild(
561
- childId: string,
562
- options: { evictable?: boolean } = {},
563
- ): Promise<AbracadabraProvider> {
564
- if (!isValidDocId(childId)) {
565
- return Promise.reject(
566
- new Error(
567
- `loadChild: "${childId}" is not a valid document ID (must be a UUID). ` +
568
- `If this node was created with an older version of the app, delete it and recreate it.`,
569
- ),
570
- );
571
- }
572
-
573
- // Self-load: caller asked for the doc this provider already owns.
574
- // Return `this` directly. Without this guard we'd build a sibling
575
- // AbracadabraProvider with the same `name` and call attach() on the
576
- // shared AbracadabraWS. The wsp's providerMap is keyed by name, so
577
- // the sibling silently REPLACES the root in the routing table — its
578
- // outgoing messages still reach the wire (send doesn't read the
579
- // map), but inbound frames addressed to that doc go to the sibling.
580
- // When the borrow ends and the sibling detaches, providerMap is
581
- // wiped of that name and the root is left orphaned: the UI still
582
- // reports `connected` + `synced`, but no awareness/sync messages
583
- // are received. Returning `this` is intentionally not added to
584
- // `childProviders` so LRU eviction never destroys the root, and
585
- // `unloadChild(self)` becomes a safe no-op (see below).
586
- if (childId === this.configuration.name) {
587
- return Promise.resolve(this);
588
- }
589
-
590
- const evictable = options.evictable !== false;
591
-
592
- if (this.childProviders.has(childId)) {
593
- this.childAccessTimes.set(childId, Date.now());
594
- // A second load call promotes a child *out* of transient mode —
595
- // once a UI surface wants it, it's no longer "just for indexing"
596
- // and should be governed by the normal LRU budget. We never go
597
- // the other way (UI-loaded → transient) implicitly.
598
- if (evictable) this.transientChildren.delete(childId);
599
- return Promise.resolve(this.childProviders.get(childId)!);
600
- }
601
-
602
- // Deduplicate concurrent calls: return the same Promise so both callers
603
- // get the exact same AbracadabraProvider instance.
604
- if (this.pendingLoads.has(childId)) {
605
- return this.pendingLoads.get(childId)!;
606
- }
607
-
608
- const load = this._doLoadChild(childId, evictable);
609
- this.pendingLoads.set(childId, load);
610
- load.finally(() => this.pendingLoads.delete(childId));
611
- return load;
612
- }
613
-
614
- private async _doLoadChild(
615
- childId: string,
616
- evictable: boolean,
617
- ): Promise<AbracadabraProvider> {
618
- const childDoc = new Y.Doc({ guid: childId });
619
-
620
- // Fire-and-forget: tell the server this child belongs to the parent.
621
- this.registerSubdoc(childDoc);
622
-
623
- // Reuse the parent's WebSocket for multiplexing — all children share a
624
- // single TCP connection instead of each opening its own. The shared
625
- // AbracadabraWS demuxes frames by documentName, so each child provider
626
- // still syncs independently. Because we pass websocketProvider the
627
- // child's manageSocket will be false, meaning destroy() detaches
628
- // without tearing down the shared connection.
629
- const childProvider = new AbracadabraProvider({
630
- name: childId,
631
- document: childDoc,
632
- websocketProvider: this.configuration.websocketProvider,
633
- token: this.configuration.token,
634
- subdocLoading: this.subdocLoading,
635
- disableOfflineStore: this.abracadabraConfig.disableOfflineStore,
636
- client: this._client ?? undefined,
637
- cryptoIdentity: this.abracadabraConfig.cryptoIdentity,
638
- signChallenge: this.abracadabraConfig.signChallenge,
639
- docKeyManager: this.abracadabraConfig.docKeyManager,
640
- keystore: this.abracadabraConfig.keystore,
641
- });
642
-
643
- // Shared websocketProvider means manageSocket is false, so the base
644
- // class constructor skips auto-attach. Attach explicitly.
645
- childProvider.attach();
646
-
647
- this.childProviders.set(childId, childProvider);
648
- this.childAccessTimes.set(childId, Date.now());
649
- if (!evictable) this.transientChildren.add(childId);
650
-
651
- // Evict least-recently-used children if over capacity. A transient
652
- // load doesn't count toward the budget AND shouldn't kick others
653
- // out — it's an indexer scanning the tree, not the UI subscribing
654
- // to a new doc.
655
- if (evictable) this.evictLRU();
656
-
657
- this.emit("subdocLoaded", { childId, provider: childProvider });
658
-
659
- return childProvider;
660
- }
661
-
662
- unloadChild(childId: string) {
663
- // A PINNED child is actively bound to an open UI view (a TipTap editor or
664
- // a page-type renderer reading this exact Y.Doc). Destroying it detaches
665
- // the Y.Doc and wipes its WebSocket route, so the open view goes blank —
666
- // "title + meta render, body never arrives, fixed only by a full reload".
667
- // Pinning is the UI's ownership claim: ONLY `unpinChild` may release a
668
- // pinned doc, after which LRU eviction reclaims it normally. Background
669
- // indexers (search/file index + blob prefetch via BackgroundSyncManager)
670
- // and subdoc-removal cleanup must never tear a pinned doc out from under
671
- // the view — this guard is the hard invariant that makes that impossible.
672
- // (Full provider `destroy()` bypasses this: it tears children down
673
- // directly, which is correct for whole-provider teardown.)
674
- if (this.pinnedChildren.has(childId)) return;
675
-
676
- const provider = this.childProviders.get(childId);
677
- if (provider) {
678
- provider.destroy();
679
- this.childProviders.delete(childId);
680
- this.childAccessTimes.delete(childId);
681
- this.pinnedChildren.delete(childId);
682
- this.transientChildren.delete(childId);
683
- }
684
- }
685
-
686
- /**
687
- * Mark a child as pinned so LRU eviction will not remove it.
688
- * Use this when a document is actively being viewed by the user.
689
- */
690
- pinChild(childId: string) {
691
- this.pinnedChildren.add(childId);
692
- // Pinning means the UI is actively using this doc, so it is no longer a
693
- // mere transient indexer scan. Promote it OUT of transient so that:
694
- // (a) the background indexer's "still ours" check (`isChildTransient`)
695
- // correctly leaves it alone even when the UI reused the provider
696
- // WITHOUT going back through `loadChild` (e.g. resolving it from an
697
- // already-open tree) — the gap that let the indexer's finally-unload
698
- // destroy the doc being viewed; and
699
- // (b) once unpinned it is a normal evictable child again, instead of
700
- // leaking forever as an unreclaimable transient (evictLRU skips
701
- // transient children).
702
- this.transientChildren.delete(childId);
703
- }
704
-
705
- /**
706
- * Unpin a child, allowing LRU eviction to reclaim it when capacity is exceeded.
707
- */
708
- unpinChild(childId: string) {
709
- this.pinnedChildren.delete(childId);
710
- // Run eviction now in case we're over capacity
711
- this.evictLRU();
712
- }
713
-
714
- /**
715
- * Evict least-recently-used unpinned, non-transient child providers
716
- * until the cache is at or below MAX_CHILDREN. Transient children
717
- * (loaded with `{ evictable: false }`) are excluded from both the
718
- * budget *and* the eviction list — they're invisible to the LRU and
719
- * only go away when their loader explicitly calls `unloadChild`.
720
- */
721
- private evictLRU() {
722
- // Count only non-transient children toward the budget. A search
723
- // indexer that pinned 100 transient children must NOT cause the
724
- // LRU to evict the 1 doc the user's editor is actively viewing.
725
- let nonTransientCount = 0;
726
- for (const id of this.childProviders.keys()) {
727
- if (!this.transientChildren.has(id)) nonTransientCount++;
728
- }
729
- if (nonTransientCount <= this.maxChildren) return;
730
-
731
- const evictable: Array<{ id: string; accessTime: number }> = [];
732
- for (const [id] of this.childProviders) {
733
- if (this.pinnedChildren.has(id)) continue;
734
- if (this.transientChildren.has(id)) continue;
735
- evictable.push({ id, accessTime: this.childAccessTimes.get(id) ?? 0 });
736
- }
737
- evictable.sort((a, b) => a.accessTime - b.accessTime);
738
-
739
- let toEvict = nonTransientCount - this.maxChildren;
740
- for (const entry of evictable) {
741
- if (toEvict <= 0) break;
742
- this.unloadChild(entry.id);
743
- toEvict--;
744
- }
745
- }
746
-
747
- /** Return all currently-loaded child providers. */
748
- get children(): Map<string, AbracadabraProvider> {
749
- return this.childProviders;
750
- }
751
-
752
- // ── Offline-first update persistence ─────────────────────────────────────
753
-
754
- /**
755
- * Override to persist every local update to IndexedDB before sending it
756
- * over the wire, ensuring no work is lost during connection outages.
757
- *
758
- * Updates applied by the server (origin === this) and updates replayed
759
- * from the offline store (origin === this.offlineStore) are both skipped
760
- * to avoid loops.
761
- */
762
- override documentUpdateHandler(update: Uint8Array, origin: unknown) {
763
- if (origin === this) return;
764
- // Only skip when the store exists AND origin matches it.
765
- // Without the null-guard, a null offlineStore would match any update
766
- // with origin=null (the default for user transactions), silently
767
- // dropping all local writes when disableOfflineStore is true.
768
- if (this.offlineStore !== null && origin === this.offlineStore) return;
769
-
770
- // Persist locally first (fire-and-forget; errors are non-fatal).
771
- this.offlineStore?.persistUpdate(update).catch(() => null);
772
-
773
- // Don't send writes over the wire if we lack write permission.
774
- if (!this.canWrite) {
775
- // Make the otherwise-silent write-drop observable. A local edit was just
776
- // persisted to IndexedDB but will NOT be sent to the server because this
777
- // provider's effective role can't write. If the editor UI let the user
778
- // type here, the UI's write-gate diverged from this provider's — the edit
779
- // lives only in local IDB (looks fine locally, empty on the server). We
780
- // emit a "writeDropped" event so consumers can surface a read-only /
781
- // "unsynced changes" banner, and warn once per role-transition so a
782
- // read-only session doesn't flood the console on every keystroke.
783
- if (!this._writeDropWarned) {
784
- this._writeDropWarned = true;
785
- try {
786
- console.warn(
787
- `[abra:write-drop] dropping wire-send for doc "${this.configuration?.name}" ` +
788
- `— effectiveRole=${this.effectiveRole ?? "null"} (canWrite=false). ` +
789
- `Edits are persisted to IndexedDB only; the server will NOT receive them ` +
790
- `until this doc regains write access.`,
791
- );
792
- } catch { /* noop */ }
793
- }
794
- this.emit("writeDropped", {
795
- name: this.configuration?.name,
796
- role: this.effectiveRole ?? null,
797
- });
798
- return;
799
- }
800
-
801
- super.documentUpdateHandler(update, origin);
802
- }
803
-
804
- /**
805
- * After reconnect + sync:
806
- * 1. Flush any updates that were generated while offline.
807
- * 2. Flush any queued subdoc registrations.
808
- * 3. Save a fresh full document snapshot for the next offline session.
809
- *
810
- * Uses a local `store` reference captured at the start so that a concurrent
811
- * `destroy()` call setting `offlineStore = null` does not cause null-ref
812
- * errors across async await boundaries.
813
- */
814
- private async flushPendingUpdates() {
815
- const store = this.offlineStore;
816
- if (!store) return;
817
-
818
- // Snapshot FIRST, before any awaited IndexedDB round-trip below.
819
- //
820
- // This used to run last, and the delay lost the write outright for
821
- // short-lived providers: BackgroundSyncManager loads a child, awaits
822
- // "synced", then unloads it in a `finally` — and `unloadChild` →
823
- // `destroy()` closes the offline store. The `getPendingUpdates()` await
824
- // here was enough of a gap for the store to be gone by the time the
825
- // snapshot was written, and the failure is swallowed by `.catch()`.
826
- // Measured on a real profile: 126 documents marked "synced" by
827
- // background sync, 11 with a persisted snapshot. That is an empty
828
- // offline cache for the other 115 — no offline reading, and nothing on
829
- // disk for the client-side search/backlink index to walk.
830
- await this.persistSnapshot();
831
-
832
- // Flushing queued *local* writes / subdoc registrations over the wire
833
- // is only meaningful for writers — a read-only session has none and
834
- // must not send.
835
- if (this.canWrite) {
836
- const updates = await store.getPendingUpdates();
837
- if (updates.length > 0) {
838
- for (const update of updates) {
839
- this.send(UpdateMessage, {
840
- update,
841
- documentName: this.configuration.name,
842
- });
843
- }
844
- await store.clearPendingUpdates();
845
- }
846
-
847
- const pendingSubdocs = await store.getPendingSubdocs();
848
- for (const { childId } of pendingSubdocs) {
849
- this.send(SubdocMessage, {
850
- documentName: this.configuration.name,
851
- childDocumentName: childId,
852
- } as any);
853
- }
854
- }
855
-
856
- }
857
-
858
- /**
859
- * Persist the current merged document state to the offline store.
860
- *
861
- * This is the ONLY path that persists server-delivered content
862
- * (`documentUpdateHandler` skips `origin === this`), so it MUST run for
863
- * read-only roles too — otherwise observers/viewers get a permanently
864
- * empty offline cache and every cold start waits for a full re-sync.
865
- *
866
- * Public so short-lived consumers that load a document, read it and
867
- * immediately unload it (BackgroundSyncManager) can force the write to
868
- * land before teardown instead of racing `destroy()`.
869
- */
870
- async persistSnapshot(): Promise<void> {
871
- const store = this.offlineStore;
872
- if (!store) return;
873
- const snapshot = Y.encodeStateAsUpdate(this.document);
874
- await store.saveDocSnapshot(snapshot).catch(() => null);
875
- }
876
-
877
- get isConnected(): boolean {
878
- return (
879
- (this.configuration.websocketProvider as AbracadabraWS)
880
- .status === "connected"
881
- );
882
- }
883
-
884
- // ── Lifecycle ─────────────────────────────────────────────────────────────
885
-
886
- override destroy() {
887
- this.document.off("subdocs", this.boundHandleYSubdocsChange);
888
-
889
- // Collect child IDs before destroying — detach() may skip cleanup if
890
- // a new provider already overwrote the slot during teardown/re-init races.
891
- const childIds = [...this.childProviders.keys()];
892
-
893
- for (const provider of this.childProviders.values()) {
894
- provider.destroy();
895
- }
896
- this.childProviders.clear();
897
- this.childAccessTimes.clear();
898
- this.pinnedChildren.clear();
899
-
900
- // Force-clear any stale providerMap entries for our children.
901
- // detach() only removes if current === provider, so orphans can remain
902
- // when a new provider attached before the old one was destroyed.
903
- const wsProviderMap = this.configuration.websocketProvider?.configuration?.providerMap;
904
- if (wsProviderMap) {
905
- for (const childId of childIds) {
906
- wsProviderMap.delete(childId);
907
- }
908
- }
909
-
910
- this.offlineStore?.destroy();
911
- this.offlineStore = null;
912
-
913
- super.destroy();
914
- }
915
- }