@abraca/dabra 2.90.0 → 2.92.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,410 +0,0 @@
1
- /**
2
- * DocumentManager — high-level ORM entry point for Abracadabra CRDT documents.
3
- *
4
- * Consolidates the shared connection lifecycle, authentication, space discovery,
5
- * provider caching, and Y.Map access patterns that were previously duplicated
6
- * across `mcp/src/server.ts` and `cli/src/connection.ts`.
7
- *
8
- * Usage:
9
- * ```ts
10
- * const dm = new DocumentManager({
11
- * url: 'https://my-server.example.com',
12
- * name: 'My Agent',
13
- * })
14
- * // Authenticate before connecting (consumer handles crypto):
15
- * await dm.client.loginWithKey(publicKey, signFn)
16
- * await dm.connect()
17
- *
18
- * // Use the ORM:
19
- * const docs = dm.tree.childrenOf(null) // root-level docs
20
- * const content = await dm.content.read(docId) // markdown + children
21
- * dm.meta.update(docId, { color: '#ff0000' }) // update metadata
22
- * ```
23
- */
24
- import * as Y from "yjs";
25
- import { AbracadabraProvider } from "./AbracadabraProvider.ts";
26
- import { AbracadabraClient } from "./AbracadabraClient.ts";
27
- import type { AbracadabraWS } from "./AbracadabraWS.ts";
28
- import type { ServerInfo, DocumentMeta } from "./types.ts";
29
- import { Kind, SERVER_ROOT_ID } from "./types.ts";
30
- import { TreeManager } from "./TreeManager.ts";
31
- import { ContentManager } from "./ContentManager.ts";
32
- import { MetaManager } from "./MetaManager.ts";
33
- import { waitForSync } from "./DocUtils.ts";
34
- import type { TreeEntry, PageMeta } from "./DocTypes.ts";
35
- import {
36
- projectTreeEntry,
37
- TypedDocTypeMismatchError,
38
- type SchemaRegistryLike,
39
- type TypedDocsClient,
40
- } from "./SchemaTypes.ts";
41
-
42
- export interface DocumentManagerConfig {
43
- /** Server base URL (http or https). */
44
- url: string;
45
- /** Display name for awareness (cursor labels, presence). */
46
- name?: string;
47
- /** Cursor / awareness color. */
48
- color?: string;
49
- /** Invite code for first-time registration. */
50
- inviteCode?: string;
51
- /** Suppress stderr logging. */
52
- quiet?: boolean;
53
- /** Disable IndexedDB offline persistence. */
54
- disableOfflineStore?: boolean;
55
- /** Custom fetch for Node.js environments. */
56
- fetch?: typeof globalThis.fetch;
57
- /**
58
- * Pre-configured AbracadabraClient instance.
59
- * When provided, the `url` and `fetch` fields are ignored — the client's
60
- * configuration is used instead. This is useful when the consumer has
61
- * already authenticated or configured the client externally.
62
- */
63
- client?: AbracadabraClient;
64
- /**
65
- * Shared WebSocket connection. Required in Node.js environments — pass an
66
- * AbracadabraWS constructed with WebSocketPolyfill set to the `ws` package.
67
- * When omitted, each provider creates its own connection from client.wsUrl.
68
- * The caller owns this instance and must destroy it after dm.destroy().
69
- */
70
- websocketProvider?: AbracadabraWS;
71
- /**
72
- * Known root document ID. When provided, connect() skips server discovery
73
- * and connects directly to this document. Useful in tests or CLIs where
74
- * the entry-point docId is already known.
75
- */
76
- rootDocId?: string;
77
- /**
78
- * TreeManager's in-memory parent→children index. When `true` (the
79
- * default), tree WALKS resolve against a lazily-rebuilt adjacency index
80
- * (O(k) per lookup, O(result) traversal), kept fresh by an `observeDeep`
81
- * dirty bit and rebuilt at most once per mutation batch; `childrenOfPage()`
82
- * becomes usable with stable (order,id) sibling ordering. Set `false` to
83
- * force the legacy whole-map scan (O(n) per call, O(n²) recursive) — only
84
- * needed to reproduce the exact historical order-only sibling ordering.
85
- * Benchmarked at ~700× on deep walks. Index affects WALK reads only;
86
- * `readEntries`/`get` keep raw parentId either way. Lazy: no index or
87
- * observer is bound until the first walk read.
88
- */
89
- treeIndex?: boolean;
90
- }
91
-
92
- interface CachedProvider {
93
- provider: AbracadabraProvider;
94
- lastAccessed: number;
95
- }
96
-
97
- export class DocumentManager {
98
- readonly client: AbracadabraClient;
99
-
100
- /** Tree CRUD operations. */
101
- readonly tree: TreeManager;
102
- /** Document content read/write. */
103
- readonly content: ContentManager;
104
- /** Document metadata read/write. */
105
- readonly meta: MetaManager;
106
-
107
- private _config: DocumentManagerConfig;
108
- private _serverInfo: ServerInfo | null = null;
109
- private _rootDocId: string | null = null;
110
- private _spaces: DocumentMeta[] = [];
111
- private _rootDoc: Y.Doc | null = null;
112
- private _rootProvider: AbracadabraProvider | null = null;
113
- private childCache = new Map<string, CachedProvider>();
114
-
115
- constructor(config: DocumentManagerConfig) {
116
- this._config = config;
117
- this.client =
118
- config.client ??
119
- new AbracadabraClient({
120
- url: config.url,
121
- persistAuth: false,
122
- fetch: config.fetch,
123
- });
124
-
125
- this.tree = new TreeManager(this);
126
- this.content = new ContentManager(this);
127
- this.meta = new MetaManager(this);
128
- }
129
-
130
- /**
131
- * Bind a schema registry to a typed accessor surface. The returned
132
- * client offers `.get(type, id)` with the registry's meta types
133
- * inferred at the call site, removing the need to pass `schema`
134
- * to every lookup. The provider remains schema-free at runtime —
135
- * `schema` is only used to drive type inference (see
136
- * `SchemaRegistryLike` for the structural witness).
137
- *
138
- * @example
139
- * const docs = dm.docs(kanbanSchema);
140
- * const board = docs.get("kanban", id);
141
- * if (board) console.log(board.meta.kanbanColumnWidth); // typed
142
- */
143
- docs<TMap extends Record<string, unknown>>(
144
- _schema: SchemaRegistryLike<TMap>,
145
- ): TypedDocsClient<TMap> {
146
- const tree = this.tree;
147
- const meta = this.meta;
148
- const expectType = <N extends keyof TMap & string>(
149
- expected: N,
150
- id: string,
151
- ): void => {
152
- const entry = tree.get(id);
153
- const actual = entry?.type;
154
- if (actual !== expected) {
155
- throw new TypedDocTypeMismatchError(id, expected, actual);
156
- }
157
- };
158
- return {
159
- get: <N extends keyof TMap & string>(expectedType: N, id: string) =>
160
- projectTreeEntry<TMap, N>(tree.get(id), expectedType),
161
- getEntry: (id: string) => tree.get(id),
162
- narrow: <N extends keyof TMap & string>(
163
- expectedType: N,
164
- entry: TreeEntry | null | undefined,
165
- ) => projectTreeEntry<TMap, N>(entry ?? null, expectedType),
166
- update: <N extends keyof TMap & string>(
167
- expectedType: N,
168
- id: string,
169
- patch: Partial<TMap[N]>,
170
- ) => {
171
- expectType(expectedType, id);
172
- meta.update(id, patch as Partial<PageMeta>);
173
- },
174
- set: <N extends keyof TMap & string>(
175
- expectedType: N,
176
- id: string,
177
- value: TMap[N],
178
- ) => {
179
- expectType(expectedType, id);
180
- meta.set(id, value as unknown as PageMeta);
181
- },
182
- clear: <N extends keyof TMap & string>(
183
- expectedType: N,
184
- id: string,
185
- keys: ReadonlyArray<keyof TMap[N] & string>,
186
- ) => {
187
- expectType(expectedType, id);
188
- meta.clear(id, keys as ReadonlyArray<string> as string[]);
189
- },
190
- };
191
- }
192
-
193
- // ── Accessors ─────────────────────────────────────────────────────────────
194
-
195
- get displayName(): string {
196
- return this._config.name || "DocumentManager";
197
- }
198
-
199
- get displayColor(): string {
200
- return this._config.color || "hsl(45, 90%, 55%)";
201
- }
202
-
203
- get serverInfo(): ServerInfo | null {
204
- return this._serverInfo;
205
- }
206
-
207
- get rootDocId(): string | null {
208
- return this._rootDocId;
209
- }
210
-
211
- /**
212
- * Whether the TreeManager in-memory index is enabled.
213
- * On by default — see {@link DocumentManagerConfig.treeIndex}.
214
- */
215
- get treeIndexEnabled(): boolean {
216
- return this._config.treeIndex ?? true;
217
- }
218
-
219
- get rootDocument(): Y.Doc | null {
220
- return this._rootDoc;
221
- }
222
-
223
- get rootProvider(): AbracadabraProvider | null {
224
- return this._rootProvider;
225
- }
226
-
227
- /**
228
- * Spaces visible to the caller — direct children of the server root with
229
- * `kind === "space"`. Populated by {@link connect}.
230
- */
231
- get spaces(): DocumentMeta[] {
232
- return this._spaces;
233
- }
234
-
235
- get isConnected(): boolean {
236
- return this._rootProvider?.isConnected ?? false;
237
- }
238
-
239
- // ── Y.Map access ──────────────────────────────────────────────────────────
240
-
241
- /** Get the root doc-tree Y.Map. */
242
- getTreeMap(): Y.Map<any> | null {
243
- return this._rootDoc?.getMap("doc-tree") ?? null;
244
- }
245
-
246
- /** Get the root doc-trash Y.Map. */
247
- getTrashMap(): Y.Map<any> | null {
248
- return this._rootDoc?.getMap("doc-trash") ?? null;
249
- }
250
-
251
- /** Get the root space-plugins Y.Map. */
252
- getPluginsMap(): Y.Map<any> | null {
253
- return this._rootDoc?.getMap("space-plugins") ?? null;
254
- }
255
-
256
- // ── Lifecycle ─────────────────────────────────────────────────────────────
257
-
258
- /**
259
- * Connect to the server: discover the entry-point document, sync the root
260
- * Y.Doc, and set awareness.
261
- *
262
- * **Authentication must be done before calling connect().**
263
- * Call `dm.client.loginWithKey(publicKey, signFn)` or `dm.client.login()`
264
- * to authenticate first.
265
- *
266
- * When `rootDocId` is set in the config, server discovery is skipped and
267
- * the manager connects directly to that document.
268
- */
269
- async connect(): Promise<void> {
270
- // Step 1: Discover server info (used for awareness colour, name, etc.).
271
- this._serverInfo = await this.client.serverInfo();
272
-
273
- // Step 2: Pick an entry-point doc.
274
- //
275
- // In the new model the dashboard's notion of "open the hub" maps to
276
- // "open the first Space". A Space is a top-level doc with
277
- // `kind === "space"`. If the caller pinned a `rootDocId`, honour it
278
- // directly — useful in tests/CLIs where the entry doc is known.
279
- let initialDocId: string | null = this._config.rootDocId ?? null;
280
-
281
- if (!initialDocId) {
282
- const roots = await this.client.listChildren();
283
- this._spaces = roots.filter((d) => d.kind === Kind.Space);
284
- const first = this._spaces[0] ?? roots[0];
285
- if (first) {
286
- initialDocId = first.id;
287
- this.log(`Entry document: ${first.label ?? first.id} (${first.id})`);
288
- }
289
- }
290
-
291
- if (!initialDocId) {
292
- throw new Error(
293
- `No entry point found: server has no top-level documents under ${SERVER_ROOT_ID}. Create a Space first.`,
294
- );
295
- }
296
-
297
- this._rootDocId = initialDocId;
298
-
299
- // Step 3: Connect provider and sync
300
- await this._connectToRoot(initialDocId);
301
- this.log("Connected and synced");
302
- }
303
-
304
- /** Switch active space to a different root document. */
305
- async switchSpace(docId: string): Promise<void> {
306
- // Destroy existing child providers
307
- for (const [, cached] of this.childCache) {
308
- cached.provider.destroy();
309
- }
310
- this.childCache.clear();
311
-
312
- // Destroy current root provider (not the wsp — caller owns it)
313
- if (this._rootProvider) {
314
- this._rootProvider.destroy();
315
- this._rootProvider = null;
316
- }
317
- this._rootDoc = null;
318
-
319
- await this._connectToRoot(docId);
320
- this._rootDocId = docId;
321
- this.log(`Switched to space ${docId}`);
322
- }
323
-
324
- /** Create, sync, and set awareness on a root provider for the given docId. */
325
- private async _connectToRoot(docId: string): Promise<void> {
326
- const doc = new Y.Doc({ guid: docId });
327
- const wsp = this._config.websocketProvider;
328
- const provider = new AbracadabraProvider({
329
- name: docId,
330
- document: doc,
331
- client: this.client,
332
- disableOfflineStore: this._config.disableOfflineStore ?? true,
333
- subdocLoading: "lazy",
334
- ...(wsp ? { websocketProvider: wsp } : {}),
335
- });
336
-
337
- // When a shared websocketProvider is supplied, manageSocket=false so
338
- // the base constructor does NOT call attach(). We must do it ourselves.
339
- if (wsp) provider.attach();
340
-
341
- await waitForSync(provider);
342
-
343
- provider.awareness?.setLocalStateField("user", {
344
- name: this.displayName,
345
- color: this.displayColor,
346
- });
347
- provider.awareness?.setLocalStateField("status", null);
348
-
349
- this._rootDoc = doc;
350
- this._rootProvider = provider;
351
- }
352
-
353
- /** Graceful shutdown. */
354
- async destroy(): Promise<void> {
355
- for (const [, cached] of this.childCache) {
356
- cached.provider.destroy();
357
- }
358
- this.childCache.clear();
359
-
360
- if (this._rootProvider) {
361
- this._rootProvider.awareness?.setLocalStateField(
362
- "status",
363
- null,
364
- );
365
- this._rootProvider.destroy();
366
- this._rootProvider = null;
367
- }
368
- this._rootDoc = null;
369
-
370
- this.log("Disconnected");
371
- }
372
-
373
- // ── Provider cache ────────────────────────────────────────────────────────
374
-
375
- /** Get or create a child provider for a document (synced). */
376
- async getChildProvider(docId: string): Promise<AbracadabraProvider> {
377
- const cached = this.childCache.get(docId);
378
- if (cached) {
379
- cached.lastAccessed = Date.now();
380
- return cached.provider;
381
- }
382
-
383
- if (!this._rootProvider) {
384
- throw new Error("Not connected. Call connect() first.");
385
- }
386
-
387
- const childProvider = await this._rootProvider.loadChild(docId);
388
- await waitForSync(childProvider);
389
-
390
- childProvider.awareness?.setLocalStateField("user", {
391
- name: this.displayName,
392
- color: this.displayColor,
393
- });
394
-
395
- this.childCache.set(docId, {
396
- provider: childProvider,
397
- lastAccessed: Date.now(),
398
- });
399
-
400
- return childProvider;
401
- }
402
-
403
- // ── Internal ──────────────────────────────────────────────────────────────
404
-
405
- private log(msg: string): void {
406
- if (!this._config.quiet) {
407
- console.error(`[abracadabra] ${msg}`);
408
- }
409
- }
410
- }