@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
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"abracadabra-provider.esm.js","names":["DB_VERSION","idbAvailable","openDb","txPromise","isValidDocId","HKDF_INFO","nobleEd25519","fromBase64","toBase64url","_generateMnemonic","_validateMnemonic","nobleEd25519Curves","HKDF_INFO","toBase64url","fromBase64url","openDb","nobleEd25519Curves","DB_VERSION","idbAvailable","openDb","txPromise","DB_VERSION","idbAvailable","openDb","DB_VERSION","idbAvailable","openDb","fromBase64","fromBase64","toBase64","DEFAULT_TIMEOUT_MS"],"sources":["../src/awarenessStatesToArray.ts","../src/EventEmitter.ts","../src/types.ts","../src/LifecycleGate.ts","../src/IncomingMessage.ts","../src/OutgoingMessage.ts","../src/OutgoingMessages/CloseMessage.ts","../src/AbracadabraWS.ts","../src/auth.ts","../src/MessageReceiver.ts","../src/MessageSender.ts","../src/OutgoingMessages/AuthenticationMessage.ts","../src/OutgoingMessages/AwarenessMessage.ts","../src/OutgoingMessages/StatelessMessage.ts","../src/RpcClient.ts","../src/QueryClient.ts","../src/OutgoingMessages/QueryAwarenessMessage.ts","../src/OutgoingMessages/SyncStepOneMessage.ts","../src/OutgoingMessages/UpdateMessage.ts","../src/AbracadabraBaseProvider.ts","../src/OfflineStore.ts","../src/OutgoingMessages/SubdocMessage.ts","../src/AbracadabraProvider.ts","../src/ServerReset.ts","../src/webrtc/SignalingSocket.ts","../src/webrtc/types.ts","../src/webrtc/DataChannelRouter.ts","../src/webrtc/PeerConnection.ts","../src/webrtc/YjsDataChannel.ts","../src/webrtc/FileTransferChannel.ts","../src/webrtc/E2EEChannel.ts","../src/webrtc/AbracadabraWebRTC.ts","../src/IdentityDoc.ts","../src/AbracadabraClient.ts","../src/TokenManager.ts","../src/CloseEvents.ts","../src/MnemonicKeyDerivation.ts","../src/CryptoIdentityKeystore.ts","../src/NodeIdentity.ts","../src/DocUtils.ts","../src/NodeConnect.ts","../src/ServerRegistry.ts","../src/DocumentCache.ts","../src/SearchIndex.ts","../src/FileBlobStore.ts","../src/DocKeyManager.ts","../src/EncryptedY.ts","../src/E2EOfflineStore.ts","../src/E2EAbracadabraProvider.ts","../src/TreeTimestamps.ts","../src/BackgroundSyncPersistence.ts","../src/BackgroundSyncManager.ts","../src/webrtc/ManualSignaling.ts","../src/webrtc/DevicePairingChannel.ts","../src/sync/BroadcastChannelSync.ts","../src/DeviceRegistrationService.ts","../src/ChatClient.ts","../src/EncryptedChatClient.ts","../src/messageRecord.ts","../src/NotificationsClient.ts","../src/DocTypes.ts","../src/SchemaTypes.ts","../src/TreeManager.ts","../src/CoverReconcile.ts","../src/DocConverters.ts","../src/ContentManager.ts","../src/MetaManager.ts","../src/DocumentManager.ts","../src/PerfCounters.ts"],"sourcesContent":["export const awarenessStatesToArray = (\n\tstates: Map<number, Record<string, any>>,\n) => {\n\treturn Array.from(states.entries()).map(([key, value]) => {\n\t\treturn {\n\t\t\tclientId: key,\n\t\t\t...value,\n\t\t};\n\t});\n};\n","export default class EventEmitter {\n\t// eslint-disable-next-line @typescript-eslint/no-unsafe-function-type\n\tpublic callbacks: { [key: string]: Function[] } = {};\n\n\t// eslint-disable-next-line @typescript-eslint/no-unsafe-function-type\n\tpublic on(event: string, fn: Function): this {\n\t\tif (!this.callbacks[event]) {\n\t\t\tthis.callbacks[event] = [];\n\t\t}\n\n\t\tthis.callbacks[event].push(fn);\n\n\t\treturn this;\n\t}\n\n\t// eslint-disable-next-line @typescript-eslint/no-unsafe-function-type\n\tpublic once(event: string, fn: Function): this {\n\t\tconst wrapper = (...args: any[]) => {\n\t\t\tthis.off(event, wrapper);\n\t\t\tfn.apply(this, args);\n\t\t};\n\t\treturn this.on(event, wrapper);\n\t}\n\n\tprotected emit(event: string, ...args: any): this {\n\t\tconst callbacks = this.callbacks[event];\n\n\t\tif (callbacks) {\n\t\t\tfor (const callback of callbacks) {\n\t\t\t\ttry {\n\t\t\t\t\tcallback.apply(this, args);\n\t\t\t\t} catch (err) {\n\t\t\t\t\tconsole.error(`[EventEmitter] Error in \"${event}\" listener:`, err);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn this;\n\t}\n\n\t// eslint-disable-next-line @typescript-eslint/no-unsafe-function-type\n\tpublic off(event: string, fn?: Function): this {\n\t\tconst callbacks = this.callbacks[event];\n\n\t\tif (callbacks) {\n\t\t\tif (fn) {\n\t\t\t\tthis.callbacks[event] = callbacks.filter((callback) => callback !== fn);\n\t\t\t} else {\n\t\t\t\tdelete this.callbacks[event];\n\t\t\t}\n\t\t}\n\n\t\treturn this;\n\t}\n\n\tremoveAllListeners(): void {\n\t\tthis.callbacks = {};\n\t}\n}\n","import type { Encoder } from \"lib0/encoding\";\nimport type { Event, MessageEvent } from \"ws\";\nimport type { Awareness } from \"y-protocols/awareness\";\nimport type * as Y from \"yjs\";\nimport type { CloseEvent } from \"./CloseEvents.ts\";\nimport type { IncomingMessage } from \"./IncomingMessage.ts\";\nimport type { OutgoingMessage } from \"./OutgoingMessage.ts\";\nimport type { AuthenticationMessage } from \"./OutgoingMessages/AuthenticationMessage.ts\";\nimport type { AwarenessMessage } from \"./OutgoingMessages/AwarenessMessage.ts\";\nimport type { QueryAwarenessMessage } from \"./OutgoingMessages/QueryAwarenessMessage.ts\";\nimport type { SyncStepOneMessage } from \"./OutgoingMessages/SyncStepOneMessage.ts\";\nimport type { SyncStepTwoMessage } from \"./OutgoingMessages/SyncStepTwoMessage.ts\";\nimport type { UpdateMessage } from \"./OutgoingMessages/UpdateMessage.ts\";\n\n/**\n * State of the WebSocket connection.\n * https://developer.mozilla.org/de/docs/Web/API/WebSocket/readyState\n */\nexport enum WsReadyStates {\n Connecting = 0,\n Open = 1,\n Closing = 2,\n Closed = 3,\n}\n\nexport enum MessageType {\n Sync = 0,\n Awareness = 1,\n Auth = 2,\n QueryAwareness = 3,\n Subdoc = 4,\n Stateless = 5,\n CLOSE = 7,\n SyncStatus = 8,\n}\n\nexport enum WebSocketStatus {\n Connecting = \"connecting\",\n Connected = \"connected\",\n Disconnected = \"disconnected\",\n}\n\nexport type AuthorizedScope = \"service\" | \"admin\" | \"owner\" | \"editor\" | \"viewer\" | \"observer\" | \"read-write\" | \"readonly\";\n\nexport interface OutgoingMessageInterface {\n encoder: Encoder;\n type?: MessageType;\n}\n\nexport interface OutgoingMessageArguments {\n documentName: string;\n token: string;\n document: Y.Doc;\n awareness: Awareness;\n clients: number[];\n states: Map<number, { [key: string]: any }>;\n update: any;\n payload: string;\n encoder: Encoder;\n}\n\nexport interface Constructable<T> {\n new (...args: any): T;\n}\n\nexport type ConstructableOutgoingMessage =\n | Constructable<AuthenticationMessage>\n | Constructable<AwarenessMessage>\n | Constructable<QueryAwarenessMessage>\n | Constructable<SyncStepOneMessage>\n | Constructable<SyncStepTwoMessage>\n | Constructable<UpdateMessage>;\n\nexport type onAuthenticationFailedParameters = {\n reason: string;\n};\n\n/**\n * Why the server refused a local change.\n *\n * - `permission` — the resolved role on that document cannot write. The read\n * subscription stays alive; only the update was dropped.\n * - `validation` — the update was structurally accepted but rejected by a\n * server-side gate (schema validation, size/pattern guards). Deliberately\n * NOT an auth failure: the server sends `SyncStatus(applied=0)` rather than\n * a permission-denied frame so a transient data error can't bounce a legit\n * editor off sync.\n */\nexport type WriteRejectionKind = \"permission\" | \"validation\";\n\n/**\n * Fired when the server tells us a local change was NOT applied.\n *\n * This event exists because the refusal was previously unobservable from\n * application code. The server has always nacked — `AUTH_PERMISSION_DENIED`\n * for a role that cannot write, `SyncStatus(applied=0)` for a rejected\n * update — but the SDK folded the first into a generic\n * `authenticationFailed` (which apps do not listen to, since on a shared\n * socket it usually is not one) and dropped the second on the floor entirely.\n * The write stayed in the unsynced buffer and the UI showed an edit that had\n * already been refused, so \"it saved, then it wasn't there after reload\"\n * became the standard bug report for viewer-role clients.\n *\n * The change is NOT lost when this fires: `unsyncedChanges` deliberately does\n * not decrement, so the update remains queued for retry after whatever caused\n * the rejection is fixed. Treat this as \"surface it\", not \"discard it\".\n */\nexport type onWriteRejectedParameters = {\n /** Document name (id) whose update was refused. */\n documentName: string;\n /** Server-supplied reason where one exists, else a fixed description. */\n reason: string;\n kind: WriteRejectionKind;\n};\n\nexport type onAuthenticatedParameters = {\n scope: AuthorizedScope;\n};\n\nexport type onOpenParameters = {\n event: Event;\n};\n\n/**\n * Fired when a socket re-establishes after having previously been open at\n * least once on this provider — i.e. an actual reconnect, not the first\n * connect. Consumers use this to re-run a reconciliation pass (e.g. re-scan a\n * watched column) after a drop. The provider's Y.Doc is never replaced, so any\n * `observe`/`observeDeep` listeners are still attached and fire on their own as\n * the post-reconnect sync delivers updates — this event is a belt-and-braces\n * \"we're live again\" signal, not a requirement for observers to keep working.\n */\nexport type onReconnectedParameters = {\n event: Event;\n};\n\nexport type onMessageParameters = {\n event: MessageEvent;\n message: IncomingMessage;\n};\n\nexport type onOutgoingMessageParameters = {\n message: OutgoingMessage;\n};\n\nexport type onStatusParameters = {\n status: WebSocketStatus;\n};\n\nexport type onSyncedParameters = {\n state: boolean;\n};\n\nexport type onUnsyncedChangesParameters = {\n number: number;\n};\n\nexport type onDisconnectParameters = {\n event: CloseEvent;\n};\n\nexport type onCloseParameters = {\n event: CloseEvent;\n};\n\nexport type onAwarenessUpdateParameters = {\n states: StatesArray;\n};\n\nexport type onAwarenessChangeParameters = {\n states: StatesArray;\n};\n\nexport type onStatelessParameters = {\n payload: string;\n};\n\n/** Fired by E2EAbracadabraProvider when the server acknowledges an E2E\n * client-side compaction (via the `snapshot:compacted` stateless broadcast). */\nexport type onCompactedParameters = {\n docId: string;\n /** User id that performed the compaction; undefined if payload was malformed. */\n by: string | undefined;\n};\n\nexport type onServerErrorParameters = {\n source: string;\n code: string;\n message: string;\n meta?: Record<string, unknown>;\n};\n\nexport type StatesArray = { clientId: number; [key: string | number]: any }[];\n\n// ── Abracadabra extensions ────────────────────────────────────────────────────\n\nexport type EffectiveRole = \"service\" | \"admin\" | \"owner\" | \"editor\" | \"viewer\" | \"observer\" | null;\n\n/**\n * Ed25519 identity for passwordless crypto auth.\n *\n * The public key is the sole identifier sent to the server during the\n * challenge-response handshake. Username is decoupled from auth and is\n * managed separately as a mutable display name (see PATCH /users/me).\n */\nexport interface CryptoIdentity {\n /** base64url-encoded Ed25519 public key (32 bytes). Primary auth identifier. */\n publicKey: string;\n}\n\nexport interface SubdocRegisteredEvent {\n childId: string;\n parentId: string;\n}\n\nexport type onSubdocRegisteredParameters = SubdocRegisteredEvent;\n\nexport type onSubdocLoadedParameters = {\n childId: string;\n provider: import(\"./AbracadabraProvider.ts\").AbracadabraProvider;\n};\n\nexport interface AbracadabraOutgoingMessageArguments extends OutgoingMessageArguments {\n childDocumentName: string;\n}\n\n// ── REST API response types ──────────────────────────────────────────────────\n\nexport interface UserProfile {\n id: string;\n username: string;\n email: string | null;\n displayName: string | null;\n role: string;\n /** Account-level Ed25519 public key (base64url). Canonical user identity. */\n publicKey: string | null;\n /**\n * Whether the user has a password set. `false` for key-based soft\n * identities until they opt in via {@link AbracadabraClient.setPassword}.\n * Drives the UI's \"Set password\" vs \"Change password\" branching.\n */\n hasPassword?: boolean;\n}\n\nexport interface DocumentMeta {\n id: string;\n parent_id: string | null;\n /**\n * Renderer hint — `\"kanban\"`, `\"checklist\"`, `\"outline\"`, `\"graph\"`,\n * `\"sheet\"`, `\"mindmap\"`, `\"doc\"`, etc. Drives the dashboard's choice of\n * Vue component for this doc. Orthogonal to {@link kind}.\n */\n doc_type?: string | null;\n label?: string | null;\n description?: string | null;\n public_access?: string | null;\n owner_id?: string | null;\n /**\n * Structural role hint — `\"server\"` for the reserved server-root doc,\n * `\"space\"` for top-level workspace containers, `null`/absent otherwise.\n * Distinct from {@link doc_type}: a Space (`kind: \"space\"`) can contain\n * many Kanban boards (each `doc_type: \"kanban\"`).\n */\n kind?: string | null;\n updated_at?: number | null;\n}\n\n/**\n * Well-known structural roles for the {@link DocumentMeta.kind} field. These\n * are conventions only — the server treats `kind` as an opaque string. Use\n * these constants instead of string literals to avoid typos.\n */\nexport const Kind = {\n /** The reserved server root document. There is exactly one per server. */\n Server: \"server\",\n /** A top-level workspace container — what the dashboard calls a \"Space\". */\n Space: \"space\",\n /** A regular content page rendered by the editor. */\n Page: \"page\",\n /** A group chat container under a Space. */\n Channel: \"channel\",\n /** A direct-message container at the server root with two-member permissions. */\n Dm: \"dm\",\n /** A child of channel/dm holding the messages Y.Array. */\n ChannelPeriod: \"channel-period\",\n /** A per-user inbox doc holding inbox entries; child of server root. */\n Inbox: \"inbox\",\n} as const;\nexport type Kind = typeof Kind[keyof typeof Kind];\n\n/**\n * Hardcoded UUID of the reserved server root document. Every doc in the tree\n * chains up to this row, so a permission grant on this doc cascades into\n * every descendant. Mirrors the constant in the Rust crate\n * (`crate::types::SERVER_ROOT_ID_STR`).\n */\nexport const SERVER_ROOT_ID = \"00000000-0000-0000-0000-000000000000\";\n\nexport interface UploadMeta {\n id: string;\n doc_id: string;\n filename: string;\n}\n\nexport interface UploadInfo {\n id: string;\n filename: string;\n mime_type: string;\n size: number;\n /** Intrinsic pixel width of the image (captured server-side at upload).\n * Absent for non-images and older servers. */\n width?: number;\n /** Intrinsic pixel height of the image. */\n height?: number;\n /** True when the server can synthesise a thumbnail for this upload (a\n * supported raster image and the feature is enabled). Absent on older\n * servers — treat as `false`. */\n thumbnail?: boolean;\n}\n\n/** Query options for the on-demand thumbnail endpoint. `w`/`h` are the\n * bounding box (at least one required, each on the server's allowed_sizes);\n * `fit` defaults to `contain`, `format` to `auto`. */\nexport interface ThumbnailOptions {\n w?: number;\n h?: number;\n fit?: \"cover\" | \"contain\" | \"inside\";\n format?: \"auto\" | \"jpeg\" | \"png\";\n /** JPEG quality 1–100. */\n q?: number;\n}\n\n/** Response of `POST /docs/:docId/uploads/:uploadId/stream-token` — a\n * short-lived grant that reads exactly one upload and travels in the query\n * string, so a `<video src>` can Range-seek it without an Authorization\n * header. `url` is server-relative. */\nexport interface StreamTokenInfo {\n token: string;\n /** Lifetime in seconds, from the moment the server minted it. */\n expires_in: number;\n /** `/docs/<docId>/uploads/<uploadId>?token=…` */\n url: string;\n}\n\nexport interface PublicKeyInfo {\n id: string;\n publicKey: string;\n deviceName: string | null;\n revoked: boolean;\n createdAt?: number | null;\n pairedBy?: string | null;\n pairedVia?: string | null;\n}\n\nexport interface PermissionEntry {\n user_id: string;\n role: \"service\" | \"admin\" | \"owner\" | \"editor\" | \"viewer\" | \"observer\";\n username: string;\n display_name: string | null;\n}\n\nexport interface EffectivePermissionEntry {\n user_id: string;\n role: \"service\" | \"admin\" | \"owner\" | \"editor\" | \"viewer\" | \"observer\";\n username: string;\n display_name: string | null;\n source: \"direct\" | \"inherited\";\n inherited_from_doc_id?: string;\n}\n\nexport interface EffectivePermissionsResponse {\n permissions: EffectivePermissionEntry[];\n default_role: string;\n}\n\n// ── Snapshots ────────────────────────────────────────────────────────────────\n\nexport interface SnapshotMeta {\n version: number;\n size_bytes: number;\n trigger: string;\n label?: string | null;\n created_by?: string | null;\n created_at: number;\n /** Number of uploads referenced by this snapshot's CRDT state.\n * Always 0 on servers older than the `snapshot_files` migration, or for\n * snapshots created before that migration ran (until the operator runs\n * `POST /admin/snapshots/backfill-refs`). */\n file_count?: number;\n /** Signed byte delta vs. the previous-version snapshot for this doc.\n * `null` for the first snapshot of a doc (or when the previous version\n * has been pruned). Lets the UI render `+12 KB` / `−3 KB`. */\n delta_bytes?: number | null;\n}\n\nexport interface SnapshotFileEntry {\n id: string;\n doc_id: string;\n filename: string;\n mime_type?: string | null;\n size?: number | null;\n}\n\nexport interface SnapshotData extends SnapshotMeta {\n data: string;\n /** Populated only when fetched with `?include=files`. Each entry is an\n * upload referenced by this snapshot's CRDT state. */\n files?: SnapshotFileEntry[];\n}\n\nexport interface SnapshotCreateResult {\n version: number;\n size_bytes: number;\n label?: string | null;\n}\n\nexport interface SnapshotRestoreResult {\n restored_from: number;\n diff_bytes: number;\n}\n\nexport interface SnapshotForkResult {\n doc_id: string;\n forked_from: { doc_id: string; version: number };\n}\n\nexport interface HealthStatus {\n status: string;\n version: string;\n active_documents: number;\n}\n\nexport interface ServerInfo {\n /** Human-readable server name set by the operator. */\n name?: string;\n /**\n * Identity of this server's DATABASE, persisted beside it.\n *\n * Stable across restarts and upgrades; it changes only when the database is\n * replaced — a wipe, or a restore from backup. That makes it the one signal a\n * client can use to know its cached CRDT state belongs to a peer that no\n * longer exists, which a CRDT cannot work out for itself. See\n * {@link dropCachesIfServerReplaced}.\n */\n server_id?: string;\n /** Server version string. */\n version?: string;\n /** Hocuspocus wire protocol version (currently 2). */\n protocol_version?: number;\n /**\n * The reserved server root document id. Every doc in the tree chains up\n * to this row; granting Admin here cascades to every doc. Hardcoded by\n * the server — clients can also use {@link SERVER_ROOT_ID} directly.\n */\n root_doc_id?: string;\n /**\n * Server-wide access policy. Drives client-side decisions like \"show the\n * sign-up CTA?\" (anonymous mode) or \"warn before publishing?\" (anonymous\n * grants).\n */\n access?: {\n /** `\"none\"` rejects unauthenticated requests; `\"observer\"` allows public read. */\n anonymous?: \"none\" | \"observer\";\n /** Server-wide floor for authed users with no explicit grant. */\n authenticated?: \"none\" | \"observer\" | \"viewer\" | \"editor\";\n };\n /** Enabled auth methods (e.g. [\"crypto\", \"jwt\"]). */\n auth_methods?: string[];\n /** Whether open registration is enabled. */\n registration_allowed?: boolean;\n /** Whether an invite code is required to register. */\n invite_only?: boolean;\n /** Server encryption configuration. */\n encryption?: { default_mode?: string; minimum_mode?: string };\n /**\n * Ed25519 public key (base64url, no padding) the server uses to sign every\n * accepted `messages:*` record (`server_sig`). Clients can verify message\n * placement / ordering by checking each record's `server_sig` against this\n * key over the canonical `{ msg_id, period_id, ts, client_sig }` payload.\n */\n messages_signer_pubkey?: string;\n}\n\n// ── Search ───────────────────────────────────────────────────────────────────\n\nexport interface SearchResult {\n docId: string;\n /** Number of matching trigrams — higher is better. */\n score: number;\n}\n\n/**\n * A single hit returned by the server's full-text search endpoint\n * (`GET /docs/search`). Distinct from {@link SearchResult}, which is the\n * client-side trigram index in `SearchIndex.ts`.\n *\n * `snippet` is server-rendered HTML with `<mark>` wrappers around the\n * matched tokens — safe to inject after standard sanitization. `rank` is\n * a backend-specific score (SQLite bm25 vs Postgres ts_rank); the only\n * guarantee is that hits arrive in best-first order.\n */\n/**\n * One inbound link, as returned by `GET /docs/:id/backlinks`.\n *\n * Deliberately thin: identity plus enough to render a row. Anything richer\n * (icon, breadcrumb, the sentence the link sits in) lives in the client's own\n * tree/index — the server index only knows the edge.\n */\nexport interface DocBacklink {\n doc_id: string;\n label: string | null;\n /** Structural role tag (`space`/`page`/`channel`/…), when the doc has one. */\n kind: string | null;\n}\n\nexport interface DocSearchHit {\n doc_id: string;\n parent_id: string | null;\n /**\n * Structural role tag (`space`/`page`/`channel`/…) — what the doc *is*,\n * not how it renders. See {@link doc_type} for the renderer/page type.\n */\n kind: string | null;\n label: string | null;\n /**\n * Renderer / page type (`kanban`/`graph`/`calendar`/…), surfaced by the\n * server from `documents.doc_type` or the CRDT-derived\n * `doc_meta_index.kind`. Use this as the renderer hint when opening a hit.\n * Absent from older servers and for plain docs.\n */\n doc_type?: string | null;\n /**\n * The top-level space (`kind: \"space\"`) that contains this hit, resolved\n * server-side by walking the CRDT tree. Lets a client jump straight to the\n * space without a client-side parent walk. Absent from older servers or\n * when no `kind=\"space\"` ancestor was found.\n */\n space_id?: string | null;\n /** HTML-safe snippet with `<mark>` markers around the matched tokens. */\n snippet: string;\n rank: number;\n}\n\n// ── Audit log (admin) ────────────────────────────────────────────────────────\n\n/**\n * A single row from `GET /admin/audit`. Mirrors the server's audit log\n * row format (see `audit::AuditLogRow`). `metadata` is the parsed JSON\n * object the server stored, or `null` if the row had no metadata. Each\n * row carries an internal `prev_hash` / `row_hash` chain that admins\n * verify with {@link AuditVerifyResult}.\n */\nexport interface AuditLogEntry {\n id: string;\n ts: number;\n event_type: string;\n actor_user_id: string | null;\n actor_ip: string | null;\n request_id: string | null;\n target_type: string | null;\n target_id: string | null;\n metadata: Record<string, unknown> | null;\n outcome: string;\n}\n\n/** Filters for `GET /admin/audit`. All optional and AND-combined. */\nexport interface AuditQueryOpts {\n event_type?: string;\n actor_user_id?: string;\n target_type?: string;\n target_id?: string;\n since_ts?: number;\n until_ts?: number;\n limit?: number;\n offset?: number;\n}\n\n/** Response of `GET /admin/audit/verify`. `status: \"broken\"` carries `break`. */\nexport interface AuditVerifyResult {\n status: \"ok\" | \"broken\";\n message?: string;\n break?: { rows_checked: number; row_id: string; reason: string };\n}\n\n// ── Admin: runtime config store ───────────────────────────────────────────────\n\n/**\n * Where the current value of a config field came from.\n *\n * * `default` — compiled-in default; nobody touched it.\n * * `env` — set at startup by an `ABRA_*` env var.\n * * `global_override` — admin runtime override via `/admin/config`.\n * * `route_override` — per-route override (Phase 3).\n */\nexport type AdminConfigOriginKind =\n | \"default\"\n | \"env\"\n | \"global_override\"\n | \"route_override\";\n\n/** One entry returned by `GET /admin/config` and `GET /admin/config/fields/:path`. */\nexport interface AdminConfigField {\n path: string;\n section: string;\n description: string;\n env_var: string;\n runtime_mutable: boolean;\n value: unknown;\n origin_kind: AdminConfigOriginKind;\n /** Provenance — present only when origin_kind is a `*_override`. */\n set_at?: number;\n set_by?: string;\n route?: string;\n}\n\n/**\n * One row from `GET /admin/config/env-snapshot.items[]`. Reports whether\n * each registry-known `ABRA_*` env var was set in the running process at\n * boot, with secrets reported as `value: null` and `redacted: true`.\n */\nexport interface EnvSnapshotItem {\n env_var: string;\n path: string;\n section: string;\n present: boolean;\n /** Verbatim env value, or `null` for redacted (secrets) or unset. */\n value: string | null;\n redacted: boolean;\n}\n\n/**\n * One row from `GET /admin/config/env-snapshot.extensions[]`. Extension\n * overrides (`ABRA_EXT_<name>_<field>`) sit outside the registry and are\n * reported by name with values inline.\n */\nexport interface EnvSnapshotExtension {\n env_var: string;\n value: string;\n}\n\n/**\n * `GET /admin/config/env-snapshot` response.\n *\n * `unknown` lists `ABRA_*` env vars present in the process that don't map\n * to any registered field — i.e. typos. Operators that see their tweak\n * land here instead of in `items` know they misspelled the var.\n */\nexport interface EnvSnapshotResponse {\n items: EnvSnapshotItem[];\n extensions: EnvSnapshotExtension[];\n unknown: string[];\n}\n\n// ── Readiness ────────────────────────────────────────────────────────────────\n\n/** Response of `GET /readyz`. HTTP 200 when ready, 503 when not. */\nexport interface ReadyzStatus {\n status: \"ready\" | \"unready\";\n version: string;\n checks: { database: \"ok\" | \"error\" };\n}\n\n// ── Spaces ───────────────────────────────────────────────────────────────────\n//\n// Spaces are documents whose `parent_id` is the server root and whose `kind`\n// is `\"space\"`. Listing them is `client.listSpaces()`; they come back as\n// regular `DocumentMeta` objects. Visibility is encoded in `public_access`:\n// `null` (or `\"none\"`) = private, `\"observer\"` = public read-only.\n\n// ── Invites ──────────────────────────────────────────────────────────────────\n\nexport interface InviteRow {\n code: string;\n createdBy: string | null;\n role: string;\n maxUses: number;\n useCount: number;\n expiresAt: number | null;\n revoked: boolean;\n createdAt: number;\n}\n\n// ── Upload queue ─────────────────────────────────────────────────────────────\n\nexport type UploadQueueStatus = \"pending\" | \"uploading\" | \"done\" | \"error\";\n\nexport interface UploadQueueEntry {\n /** Client-generated UUID. */\n id: string;\n docId: string;\n /** File or Blob to upload. File extends Blob and survives IDB as Blob. */\n file: Blob;\n /** Eagerly captured filename (from File.name or explicit arg). */\n filename: string;\n status: UploadQueueStatus;\n createdAt: number;\n error?: string;\n}\n\nexport interface DocEncryptionInfo {\n mode: \"none\" | \"cse\" | \"e2e\";\n effective_mode: \"none\" | \"cse\" | \"e2e\";\n inherited_from?: string;\n}\n\n// ── Chat (stateless channel) ─────────────────────────────────────────────────\n\nexport interface ChatMessage {\n id: string;\n channel: string;\n sender_id: string;\n sender_name?: string | null;\n content: string;\n created_at: number;\n}\n\nexport interface ChatChannel {\n channel: string;\n label?: string | null;\n last_message: ChatMessage;\n unread_count: number;\n}\n\nexport interface ChatTypingEvent {\n channel: string;\n sender_id: string;\n sender_name?: string | null;\n}\n\nexport interface ChatReadReceipt {\n channel: string;\n user_id: string;\n last_read_at: number;\n}\n\nexport interface ChatReadCursor {\n user_id: string;\n last_read_at: number;\n}\n\nexport interface SendChatMessageInput {\n channel: string;\n content: string;\n sender_name?: string;\n}\n\nexport interface GetChatHistoryInput {\n channel: string;\n before?: number;\n limit?: number;\n}\n\n// ── Notifications (stateless channel) ────────────────────────────────────────\n\nexport interface NotificationRecord {\n id: string;\n recipient_id: string;\n notification_type: string;\n title: string;\n body: string;\n icon?: string | null;\n link?: string | null;\n source_id?: string | null;\n read: boolean;\n created_at: number;\n}\n\nexport interface NotificationReadUpdate {\n /** Present when a specific set of notifications was marked read. */\n ids?: string[];\n /** Present when mark_all_read was called. */\n all?: boolean;\n recipient_id: string;\n}\n\nexport interface CreateNotificationInput {\n recipient_id: string;\n notification_type?: string;\n title: string;\n body?: string;\n icon?: string;\n link?: string;\n source_id?: string;\n}\n\nexport interface FetchNotificationsInput {\n before?: number;\n limit?: number;\n unread_only?: boolean;\n}\n","/**\n * LifecycleGate — one place that knows whether the app is actually being looked at.\n *\n * Nothing in the provider used to ask. A grep for `visibilitychange` across the\n * package returned exactly one hit, in `TokenManager`, and it used the signal to\n * do MORE work on resume — nothing anywhere used it to do less. So a backgrounded\n * PWA kept its socket liveness checker running, kept re-running a full-tree\n * background sync every five minutes, and kept broadcasting presence, at exactly\n * the same rate as a phone held open in front of a person.\n *\n * Two design points that matter:\n *\n * 1. **The visibility source is injectable.** Hidden-state behaviour is the part\n * of this that most needs testing and is the hardest to reach from a test\n * runner, so `setSource()` lets a test drive it deterministically instead of\n * the tests having to fake a DOM.\n *\n * 2. **Hiding is debounced, revealing is not.** Alt-tabbing to look something up\n * is not \"the user has gone away\", and treating it as such would make presence\n * avatars flicker across everyone else's screen every time someone checked\n * their mail. Coming back is always immediate — a user who returns must never\n * wait on a timer to see live data.\n *\n * In Node, and anywhere else without a `document`, this is inert and reports\n * visible forever.\n */\n\nexport type VisibilityState = \"visible\" | \"hidden\";\n\n/** Something that can report visibility and notify on change. */\nexport interface VisibilitySource {\n\t/** Current state at the moment of the call. */\n\tget(): VisibilityState;\n\t/** Subscribe to changes. Returns an unsubscribe function. */\n\tsubscribe(onChange: () => void): () => void;\n}\n\n/** How long the app must stay hidden before we act on it. */\nexport const HIDE_GRACE_MS = 10_000;\n\n/** The browser's own visibility, or a permanently-visible stub off-DOM. */\nfunction defaultSource(): VisibilitySource {\n\tconst doc = (globalThis as { document?: Document }).document;\n\tif (!doc || typeof doc.addEventListener !== \"function\") {\n\t\treturn {\n\t\t\tget: () => \"visible\",\n\t\t\tsubscribe: () => () => {},\n\t\t};\n\t}\n\treturn {\n\t\tget: () => (doc.visibilityState === \"hidden\" ? \"hidden\" : \"visible\"),\n\t\tsubscribe: (onChange) => {\n\t\t\tdoc.addEventListener(\"visibilitychange\", onChange);\n\t\t\treturn () => doc.removeEventListener(\"visibilitychange\", onChange);\n\t\t},\n\t};\n}\n\nexport class LifecycleGate {\n\tprivate source: VisibilitySource;\n\tprivate unsubscribe: (() => void) | null = null;\n\tprivate hideTimer: ReturnType<typeof setTimeout> | null = null;\n\tprivate _backgrounded = false;\n\tprivate listeners = new Set<(backgrounded: boolean) => void>();\n\n\tconstructor(\n\t\tsource: VisibilitySource = defaultSource(),\n\t\tprivate readonly graceMs: number = HIDE_GRACE_MS,\n\t) {\n\t\tthis.source = source;\n\t\tthis.unsubscribe = this.source.subscribe(() => this.onVisibilityChange());\n\t}\n\n\t/**\n\t * True when the app has been hidden for longer than the grace period.\n\t *\n\t * Deliberately NOT the same as `document.hidden`: a tab that was hidden two\n\t * seconds ago is still, for our purposes, in use.\n\t */\n\tget backgrounded(): boolean {\n\t\treturn this._backgrounded;\n\t}\n\n\t/** Subscribe to background/foreground transitions. Returns an unsubscribe fn. */\n\tonChange(listener: (backgrounded: boolean) => void): () => void {\n\t\tthis.listeners.add(listener);\n\t\treturn () => this.listeners.delete(listener);\n\t}\n\n\t/** Swap the visibility source. Used by tests to drive state deterministically. */\n\tsetSource(source: VisibilitySource): void {\n\t\tthis.unsubscribe?.();\n\t\tthis.source = source;\n\t\tthis.unsubscribe = this.source.subscribe(() => this.onVisibilityChange());\n\t\tthis.onVisibilityChange();\n\t}\n\n\tprivate onVisibilityChange(): void {\n\t\tif (this.source.get() === \"hidden\") {\n\t\t\t// Debounce: only a sustained absence counts.\n\t\t\tif (this._backgrounded || this.hideTimer) return;\n\t\t\tthis.hideTimer = setTimeout(() => {\n\t\t\t\tthis.hideTimer = null;\n\t\t\t\tthis.setBackgrounded(true);\n\t\t\t}, this.graceMs);\n\t\t\treturn;\n\t\t}\n\n\t\t// Visible again — cancel any pending hide and resume immediately.\n\t\tif (this.hideTimer) {\n\t\t\tclearTimeout(this.hideTimer);\n\t\t\tthis.hideTimer = null;\n\t\t}\n\t\tthis.setBackgrounded(false);\n\t}\n\n\tprivate setBackgrounded(next: boolean): void {\n\t\tif (this._backgrounded === next) return;\n\t\tthis._backgrounded = next;\n\t\tfor (const listener of [...this.listeners]) {\n\t\t\ttry {\n\t\t\t\tlistener(next);\n\t\t\t} catch {\n\t\t\t\t// One bad subscriber must not stop the others from being told.\n\t\t\t}\n\t\t}\n\t}\n\n\tdestroy(): void {\n\t\tthis.unsubscribe?.();\n\t\tthis.unsubscribe = null;\n\t\tif (this.hideTimer) {\n\t\t\tclearTimeout(this.hideTimer);\n\t\t\tthis.hideTimer = null;\n\t\t}\n\t\tthis.listeners.clear();\n\t}\n}\n\n/**\n * The process-wide gate.\n *\n * Visibility is a property of the tab, not of any one provider or socket, so a\n * single shared instance is both correct and avoids paying for one\n * `visibilitychange` listener per document.\n */\nlet shared: LifecycleGate | null = null;\n\nexport function getLifecycleGate(): LifecycleGate {\n\tif (!shared) shared = new LifecycleGate();\n\treturn shared;\n}\n\n/**\n * Replace the shared gate. Tests use this to install a controllable source;\n * passing `null` restores the default browser-backed gate on next access.\n */\nexport function setLifecycleGate(gate: LifecycleGate | null): void {\n\tif (shared && shared !== gate) shared.destroy();\n\tshared = gate;\n}\n\n/** A visibility source a test (or an embedder) can drive by hand. */\nexport class ManualVisibilitySource implements VisibilitySource {\n\tprivate state: VisibilityState = \"visible\";\n\tprivate listeners = new Set<() => void>();\n\n\tget(): VisibilityState {\n\t\treturn this.state;\n\t}\n\n\tsubscribe(onChange: () => void): () => void {\n\t\tthis.listeners.add(onChange);\n\t\treturn () => this.listeners.delete(onChange);\n\t}\n\n\tset(state: VisibilityState): void {\n\t\tif (this.state === state) return;\n\t\tthis.state = state;\n\t\tfor (const listener of [...this.listeners]) listener();\n\t}\n}\n","import type { Decoder } from \"lib0/decoding\";\nimport {\n\tcreateDecoder,\n\tpeekVarString,\n\treadVarUint,\n\treadVarUint8Array,\n\treadVarString,\n} from \"lib0/decoding\";\nimport type { Encoder } from \"lib0/encoding\";\nimport {\n\tcreateEncoder,\n\twriteVarUint,\n\twriteVarUint8Array,\n\twriteVarString,\n\tlength,\n} from \"lib0/encoding\";\nimport type { MessageType } from \"./types.ts\";\n\nexport class IncomingMessage {\n\tdata: any;\n\n\tencoder: Encoder;\n\n\tdecoder: Decoder;\n\n\tconstructor(data: any) {\n\t\tthis.data = data;\n\t\tthis.encoder = createEncoder();\n\t\tthis.decoder = createDecoder(new Uint8Array(this.data));\n\t}\n\n\tpeekVarString(): string {\n\t\treturn peekVarString(this.decoder);\n\t}\n\n\treadVarUint(): MessageType {\n\t\treturn readVarUint(this.decoder);\n\t}\n\n\treadVarString(): string {\n\t\treturn readVarString(this.decoder);\n\t}\n\n\treadVarUint8Array() {\n\t\treturn readVarUint8Array(this.decoder);\n\t}\n\n\twriteVarUint(type: MessageType) {\n\t\treturn writeVarUint(this.encoder, type);\n\t}\n\n\twriteVarString(string: string) {\n\t\treturn writeVarString(this.encoder, string);\n\t}\n\n\twriteVarUint8Array(data: Uint8Array) {\n\t\treturn writeVarUint8Array(this.encoder, data);\n\t}\n\n\tlength() {\n\t\treturn length(this.encoder);\n\t}\n}\n","import type { Encoder } from \"lib0/encoding\";\nimport { createEncoder, toUint8Array } from \"lib0/encoding\";\nimport type {\n\tMessageType,\n\tOutgoingMessageArguments,\n\tOutgoingMessageInterface,\n} from \"./types.ts\";\n\nexport class OutgoingMessage implements OutgoingMessageInterface {\n\tencoder: Encoder;\n\n\ttype?: MessageType;\n\n\tconstructor() {\n\t\tthis.encoder = createEncoder();\n\t}\n\n\tget(args: Partial<OutgoingMessageArguments>) {\n\t\treturn args.encoder;\n\t}\n\n\ttoUint8Array() {\n\t\treturn toUint8Array(this.encoder);\n\t}\n}\n","import * as encoding from \"lib0/encoding\";\nimport type { OutgoingMessageArguments } from \"../types.ts\";\nimport { MessageType } from \"../types.ts\";\nimport { OutgoingMessage } from \"../OutgoingMessage.ts\";\n\nexport class CloseMessage extends OutgoingMessage {\n\ttype = MessageType.CLOSE;\n\n\tdescription = \"Ask the server to close the connection\";\n\n\tget(args: Partial<OutgoingMessageArguments>) {\n\t\tencoding.writeVarString(this.encoder, args.documentName!);\n\t\tencoding.writeVarUint(this.encoder, this.type);\n\n\t\treturn this.encoder;\n\t}\n}\n","import { WsReadyStates } from \"./types.ts\";\nimport { getLifecycleGate } from \"./LifecycleGate.ts\";\nimport { retry } from \"@lifeomic/attempt\";\nimport * as time from \"lib0/time\";\nimport type { Event, MessageEvent } from \"ws\";\nimport EventEmitter from \"./EventEmitter.ts\";\nimport type { AbracadabraBaseProvider } from \"./AbracadabraBaseProvider.ts\";\nimport { IncomingMessage } from \"./IncomingMessage.ts\";\nimport { CloseMessage } from \"./OutgoingMessages/CloseMessage.ts\";\nimport {\n WebSocketStatus,\n type onAwarenessChangeParameters,\n type onAwarenessUpdateParameters,\n type onCloseParameters,\n type onDisconnectParameters,\n type onMessageParameters,\n type onOpenParameters,\n type onOutgoingMessageParameters,\n type onStatusParameters,\n} from \"./types.ts\";\n\nexport type AbracadabraWebSocketConn = WebSocket & { identifier: string };\n/** @deprecated Use AbracadabraWebSocketConn */\nexport type HocuspocusWebSocket = AbracadabraWebSocketConn;\n/** @deprecated Use AbracadabraWebSocketConn */\nexport type HocusPocusWebSocket = AbracadabraWebSocketConn;\n\nexport type AbracadabraWSConfiguration = Required<\n Pick<CompleteAbracadabraWSConfiguration, \"url\">\n> &\n Partial<CompleteAbracadabraWSConfiguration>;\n\n/** @deprecated Use AbracadabraWSConfiguration */\nexport type HocuspocusProviderWebsocketConfiguration = AbracadabraWSConfiguration;\n\nexport interface CompleteAbracadabraWSConfiguration {\n /**\n * Whether to connect automatically when creating the provider instance. Default=true\n */\n autoConnect: boolean;\n\n /**\n * URL of your @hocuspocus/server instance\n */\n url: string;\n\n /**\n * By default, trailing slashes are removed from the URL. Set this to true\n * to preserve trailing slashes if your server configuration requires them.\n */\n preserveTrailingSlash: boolean;\n\n /**\n * An optional WebSocket polyfill, for example for Node.js\n */\n WebSocketPolyfill: any;\n\n /**\n * Disconnect and reconnect when no message is received for the defined amount\n * of milliseconds.\n *\n * Defaults to 30000 ms to match y-protocols/awareness `Awareness.outdatedTime`\n * (also 30 s). Awareness heartbeats are what normally keep this timer\n * resetting, so this value should be ≥ the largest `outdatedTime` of any\n * awareness instance attached to this socket. If you pass a custom awareness\n * with a non-default `outdatedTime`, pass the matching value here too.\n */\n messageReconnectTimeout: number;\n /**\n * The delay between each attempt in milliseconds. You can provide a factor to have the delay grow exponentially.\n */\n delay: number;\n /**\n * The initialDelay is the amount of time to wait before making the first attempt. This option should typically be 0 since you typically want the first attempt to happen immediately.\n */\n initialDelay: number;\n /**\n * The factor option is used to grow the delay exponentially.\n */\n factor: number;\n /**\n * The maximum number of attempts or 0 if there is no limit on number of attempts.\n */\n maxAttempts: number;\n /**\n * minDelay is used to set a lower bound of delay when jitter is enabled. This property has no effect if jitter is disabled.\n */\n minDelay: number;\n /**\n * The maxDelay option is used to set an upper bound for the delay when factor is enabled. A value of 0 can be provided if there should be no upper bound when calculating delay.\n */\n maxDelay: number;\n /**\n * If jitter is true then the calculated delay will be a random integer value between minDelay and the calculated delay for the current iteration.\n */\n jitter: boolean;\n /**\n * A timeout in milliseconds. If timeout is non-zero then a timer is set using setTimeout. If the timeout is triggered then future attempts will be aborted.\n */\n timeout: number;\n handleTimeout: (() => Promise<unknown>) | null;\n onOpen: (data: onOpenParameters) => void;\n onConnect: () => void;\n onMessage: (data: onMessageParameters) => void;\n onOutgoingMessage: (data: onOutgoingMessageParameters) => void;\n onStatus: (data: onStatusParameters) => void;\n onDisconnect: (data: onDisconnectParameters) => void;\n onClose: (data: onCloseParameters) => void;\n onDestroy: () => void;\n onAwarenessUpdate: (data: onAwarenessUpdateParameters) => void;\n onAwarenessChange: (data: onAwarenessChangeParameters) => void;\n\n /**\n * Map of attached providers keyed by documentName.\n */\n providerMap: Map<string, AbracadabraBaseProvider>;\n}\n\n/** @deprecated Use CompleteAbracadabraWSConfiguration */\nexport type CompleteHocuspocusProviderWebsocketConfiguration = CompleteAbracadabraWSConfiguration;\n\nexport class AbracadabraWS extends EventEmitter {\n private messageQueue: any[] = [];\n\n public configuration: CompleteAbracadabraWSConfiguration = {\n url: \"\",\n autoConnect: true,\n preserveTrailingSlash: false,\n // @ts-ignore\n document: undefined,\n WebSocketPolyfill: undefined,\n // Matches y-protocols/awareness Awareness.outdatedTime default (30 s).\n // See the `messageReconnectTimeout` JSDoc on CompleteAbracadabraWSConfiguration.\n messageReconnectTimeout: 30000,\n // 1 second\n delay: 1000,\n // instant\n initialDelay: 0,\n // double the delay each time\n factor: 2,\n // unlimited retries\n maxAttempts: 0,\n // wait at least 1 second\n minDelay: 1000,\n // at least every 30 seconds\n maxDelay: 30000,\n // randomize\n jitter: true,\n // retry forever\n timeout: 0,\n onOpen: () => null,\n onConnect: () => null,\n onMessage: () => null,\n onOutgoingMessage: () => null,\n onStatus: () => null,\n onDisconnect: () => null,\n onClose: () => null,\n onDestroy: () => null,\n onAwarenessUpdate: () => null,\n onAwarenessChange: () => null,\n handleTimeout: null,\n providerMap: new Map(),\n };\n\n webSocket: AbracadabraWebSocketConn | null = null;\n\n webSocketHandlers: { [key: string]: any } = {};\n\n shouldConnect = true;\n\n status = WebSocketStatus.Disconnected;\n\n lastMessageReceived = 0;\n\n identifier = 0;\n\n intervals: any = {\n connectionChecker: null,\n };\n\n connectionAttempt: {\n resolve: (value?: any) => void;\n reject: (reason?: any) => void;\n } | null = null;\n\n // Bound `online`/`offline` listeners, retained so we can detach them in\n // destroy(). Only registered in browser-like environments (see constructor).\n private onlineListener: (() => void) | null = null;\n\n private offlineListener: (() => void) | null = null;\n\n unsubscribeLifecycle: (() => void) | null = null;\n\n constructor(configuration: AbracadabraWSConfiguration) {\n super();\n this.setConfiguration(configuration);\n\n this.configuration.WebSocketPolyfill = configuration.WebSocketPolyfill\n ? configuration.WebSocketPolyfill\n : (globalThis as { WebSocket?: typeof WebSocket }).WebSocket;\n\n this.on(\"open\", this.configuration.onOpen);\n this.on(\"open\", this.onOpen.bind(this));\n this.on(\"connect\", this.configuration.onConnect);\n this.on(\"message\", this.configuration.onMessage);\n this.on(\"outgoingMessage\", this.configuration.onOutgoingMessage);\n this.on(\"status\", this.configuration.onStatus);\n this.on(\"disconnect\", this.configuration.onDisconnect);\n this.on(\"close\", this.configuration.onClose);\n this.on(\"destroy\", this.configuration.onDestroy);\n this.on(\"awarenessUpdate\", this.configuration.onAwarenessUpdate);\n this.on(\"awarenessChange\", this.configuration.onAwarenessChange);\n\n this.on(\"close\", this.onClose.bind(this));\n this.on(\"message\", this.onMessage.bind(this));\n\n this.intervals.connectionChecker = setInterval(\n this.checkConnection.bind(this),\n this.configuration.messageReconnectTimeout / 10,\n );\n\n // Returning to the foreground re-checks at once rather than waiting out the\n // next tick, so gating the checker while hidden costs no detection latency\n // at the only moment a stale socket is actually noticeable.\n this.unsubscribeLifecycle = getLifecycleGate().onChange((backgrounded) => {\n if (!backgrounded) this.checkConnection();\n });\n\n // Offline-first reconnect gating. When the device reports it is offline we\n // stop hammering the socket (failed attempts just flip status\n // disconnected↔connecting and light up every connection indicator) and\n // wait for the `online` event to resume immediately — no backoff wait.\n if (typeof window !== \"undefined\" && typeof window.addEventListener === \"function\") {\n this.onlineListener = this.handleOnline.bind(this);\n this.offlineListener = this.handleOffline.bind(this);\n window.addEventListener(\"online\", this.onlineListener);\n window.addEventListener(\"offline\", this.offlineListener);\n }\n\n if (this.shouldConnect) {\n this.connect();\n }\n }\n\n /**\n * Whether the device currently believes it has network connectivity.\n *\n * Treats \"unknown\" as online: in Node and other non-browser environments\n * `navigator` (or `navigator.onLine`) is absent, and we must not gate\n * reconnection there — only the browser exposes a trustworthy signal.\n */\n get isOnline(): boolean {\n return typeof navigator === \"undefined\" || navigator.onLine !== false;\n }\n\n handleOnline() {\n // Network came back — resume immediately if we still want a connection\n // and aren't already connected. Bypasses the backoff that a pending\n // retryer would otherwise wait out.\n if (this.shouldConnect && this.status !== WebSocketStatus.Connected) {\n this.connect();\n }\n }\n\n handleOffline() {\n // Stop attempting while offline, but preserve `shouldConnect` so intent\n // survives — `handleOnline`/attach will resume once connectivity returns.\n if (this.cancelWebsocketRetry) {\n this.cancelWebsocketRetry();\n this.cancelWebsocketRetry = undefined;\n }\n try {\n this.webSocket?.close();\n this.messageQueue = [];\n } catch (e) {\n console.error(e);\n }\n }\n\n receivedOnOpenPayload?: Event | undefined = undefined;\n\n async onOpen(event: Event) {\n this.status = WebSocketStatus.Connected;\n this.emit(\"status\", { status: WebSocketStatus.Connected });\n\n this.cancelWebsocketRetry = undefined;\n this.receivedOnOpenPayload = event;\n }\n\n attach(provider: AbracadabraBaseProvider) {\n const existing = this.configuration.providerMap.get(provider.configuration.name);\n if (existing && existing !== provider) {\n console.debug(\n `[AbracadabraWS] attach: replacing provider for \"${provider.configuration.name}\".`\n );\n }\n this.configuration.providerMap.set(provider.configuration.name, provider);\n\n if (this.status === WebSocketStatus.Disconnected && this.shouldConnect) {\n this.connect();\n }\n\n if (this.receivedOnOpenPayload && this.status === WebSocketStatus.Connected) {\n provider.onOpen(this.receivedOnOpenPayload);\n }\n }\n\n detach(provider: AbracadabraBaseProvider) {\n const name = provider.configuration.name;\n const current = this.configuration.providerMap.get(name);\n if (current === provider) {\n provider.send(CloseMessage, { documentName: name });\n this.configuration.providerMap.delete(name);\n }\n // If current !== provider, another provider owns this slot —\n // don't send CloseMessage or remove it from the map.\n }\n\n public setConfiguration(\n configuration: Partial<AbracadabraWSConfiguration> = {},\n ): void {\n this.configuration = { ...this.configuration, ...configuration };\n\n if (!this.configuration.autoConnect) {\n this.shouldConnect = false;\n }\n }\n\n cancelWebsocketRetry?: () => void;\n\n async connect() {\n if (this.status === WebSocketStatus.Connected) {\n return;\n }\n\n // Don't attempt while the device is offline — record the intent and let\n // the `online` event drive the resume. Avoids the reconnect storm of\n // instantly-failing socket attempts against a known-dead network.\n if (!this.isOnline) {\n this.shouldConnect = true;\n return;\n }\n\n // Always cancel any previously initiated connection retryer instances\n if (this.cancelWebsocketRetry) {\n this.cancelWebsocketRetry();\n this.cancelWebsocketRetry = undefined;\n }\n\n this.receivedOnOpenPayload = undefined;\n this.shouldConnect = true;\n\n const abortableRetry = () => {\n let cancelAttempt = false;\n\n const retryPromise = retry(this.createWebSocketConnection.bind(this), {\n delay: this.configuration.delay,\n initialDelay: this.configuration.initialDelay,\n factor: this.configuration.factor,\n maxAttempts: this.configuration.maxAttempts,\n minDelay: this.configuration.minDelay,\n maxDelay: this.configuration.maxDelay,\n jitter: this.configuration.jitter,\n timeout: this.configuration.timeout,\n handleTimeout: this.configuration.handleTimeout,\n beforeAttempt: (context) => {\n if (!this.shouldConnect || cancelAttempt) {\n context.abort();\n }\n },\n }).catch((error: any) => {\n // If we aborted the connection attempt then don't throw an error\n // ref: https://github.com/lifeomic/attempt/blob/master/src/index.ts#L136\n if (error && error.code !== \"ATTEMPT_ABORTED\") {\n throw error;\n }\n });\n\n return {\n retryPromise,\n cancelFunc: () => {\n cancelAttempt = true;\n },\n };\n };\n\n const { retryPromise, cancelFunc } = abortableRetry();\n this.cancelWebsocketRetry = cancelFunc;\n\n return retryPromise;\n }\n\n // eslint-disable-next-line @typescript-eslint/no-unsafe-function-type\n attachWebSocketListeners(ws: AbracadabraWebSocketConn, reject: Function) {\n const { identifier } = ws;\n const onMessageHandler = (payload: any) => this.emit(\"message\", payload);\n const onCloseHandler = (payload: any) => this.emit(\"close\", { event: payload });\n const onOpenHandler = (payload: any) => this.emit(\"open\", payload);\n const onErrorHandler = (err: any) => {\n reject(err);\n };\n\n this.webSocketHandlers[identifier] = {\n message: onMessageHandler,\n close: onCloseHandler,\n open: onOpenHandler,\n error: onErrorHandler,\n };\n\n const handlers = this.webSocketHandlers[ws.identifier];\n\n Object.keys(handlers).forEach((name) => {\n ws.addEventListener(name, handlers[name]);\n });\n }\n\n cleanupWebSocket() {\n if (!this.webSocket) {\n return;\n }\n const { identifier } = this.webSocket;\n const handlers = this.webSocketHandlers[identifier];\n\n Object.keys(handlers).forEach((name) => {\n this.webSocket?.removeEventListener(name, handlers[name]);\n delete this.webSocketHandlers[identifier];\n });\n\n // After removing our handlers, ensure there is always at least one error\n // listener on the socket. Without one, any asynchronously-fired error\n // (e.g. \"WebSocket was closed before the connection was established\" when\n // closing a CONNECTING socket) will propagate as an uncaught exception in\n // Node.js. The no-op listener absorbs these post-cleanup errors safely.\n if (this.webSocket.readyState !== 3 /* CLOSED */) {\n this.webSocket.addEventListener(\"error\", () => {});\n }\n\n try {\n if (this.webSocket.readyState !== 0 /* CONNECTING */ && this.webSocket.readyState !== 3 /* CLOSED */) {\n this.webSocket.close();\n }\n // CONNECTING (0): already being closed by disconnect(), or will be closed imminently.\n // CLOSED (3): nothing to do.\n } catch (e) {\n // Ignore errors during close\n }\n\n this.webSocket = null;\n }\n\n createWebSocketConnection() {\n return new Promise((resolve, reject) => {\n if (this.webSocket) {\n this.messageQueue = [];\n this.cleanupWebSocket();\n }\n this.lastMessageReceived = 0;\n this.identifier += 1;\n\n // Init the WebSocket connection\n const ws = new this.configuration.WebSocketPolyfill(this.url);\n ws.binaryType = \"arraybuffer\";\n ws.identifier = this.identifier;\n\n this.attachWebSocketListeners(ws, reject);\n\n this.webSocket = ws;\n\n // Reset the status\n this.status = WebSocketStatus.Connecting;\n this.emit(\"status\", { status: WebSocketStatus.Connecting });\n\n // Store resolve/reject for later use\n this.connectionAttempt = {\n resolve,\n reject,\n };\n });\n }\n\n onMessage(event: MessageEvent) {\n this.resolveConnectionAttempt();\n\n this.lastMessageReceived = time.getUnixTime();\n\n const message = new IncomingMessage(event.data);\n const documentName = message.peekVarString();\n\n try {\n this.configuration.providerMap.get(documentName)?.onMessage(event);\n } catch (err) {\n console.error(`[AbracadabraWS] Provider onMessage error for \"${documentName}\":`, err);\n }\n }\n\n resolveConnectionAttempt() {\n if (this.connectionAttempt) {\n this.connectionAttempt.resolve();\n this.connectionAttempt = null;\n\n this.status = WebSocketStatus.Connected;\n this.emit(\"status\", { status: WebSocketStatus.Connected });\n this.emit(\"connect\");\n this.messageQueue.forEach((message) => this.send(message));\n this.messageQueue = [];\n }\n }\n\n stopConnectionAttempt() {\n this.connectionAttempt = null;\n }\n\n rejectConnectionAttempt() {\n this.connectionAttempt?.reject();\n this.connectionAttempt = null;\n }\n\n closeTries = 0;\n\n checkConnection() {\n // Don't police a socket nobody is looking at.\n //\n // This check exists to notice a connection that has gone quiet and force a\n // reconnect. While the app is backgrounded there is no one to serve, and\n // running it anyway is actively harmful on mobile: the client is sending\n // nothing, so `lastMessageReceived` goes stale on its own schedule and the\n // checker tears down a perfectly good socket, then reconnects it, then does\n // it again — burning radio to maintain a connection for nobody. Coming back\n // into view re-runs this immediately, so a genuinely dead socket is still\n // caught the moment it matters to anyone.\n if (getLifecycleGate().backgrounded) {\n return;\n }\n\n // Don't check the connection when it's not even established\n if (this.status !== WebSocketStatus.Connected) {\n return;\n }\n\n // Don't close the connection while waiting for the first message\n if (!this.lastMessageReceived) {\n return;\n }\n\n // Don't close the connection when a message was received recently\n if (\n this.configuration.messageReconnectTimeout >=\n time.getUnixTime() - this.lastMessageReceived\n ) {\n return;\n }\n\n // No message received in a long time, not even your own\n // Awareness updates, which are updated every 15 seconds\n // if awareness is enabled.\n this.closeTries += 1;\n // https://bugs.webkit.org/show_bug.cgi?id=247943\n if (this.closeTries > 2) {\n this.onClose({\n event: {\n code: 4408,\n reason: \"forced\",\n },\n });\n this.closeTries = 0;\n } else {\n this.webSocket?.close();\n this.messageQueue = [];\n }\n }\n\n get serverUrl() {\n if (this.configuration.preserveTrailingSlash) {\n return this.configuration.url;\n }\n\n // By default, ensure that the URL never ends with /\n let url = this.configuration.url;\n while (url[url.length - 1] === \"/\") {\n url = url.slice(0, url.length - 1);\n }\n\n return url;\n }\n\n get url() {\n return this.serverUrl;\n }\n\n disconnect() {\n this.shouldConnect = false;\n\n if (this.webSocket === null) {\n return;\n }\n\n try {\n this.webSocket.close();\n this.messageQueue = [];\n } catch (e) {\n console.error(e);\n }\n }\n\n /**\n * Force a fresh socket on the SAME WS manager: drop the current connection\n * (if any) and reconnect immediately.\n *\n * Unlike {@link disconnect} (which clears `shouldConnect` and gives up) this\n * re-arms `shouldConnect`, so it also revives a socket that a permanent\n * permission-denial turned off (see `AbracadabraBaseProvider.permissionDeniedHandler`).\n * The WS manager and its `providerMap` are preserved, so every attached\n * provider — and every Y.Doc + observer riding this socket — survives\n * untouched; only the transport is recycled.\n *\n * The existing socket is torn down silently (handlers removed first), so no\n * `close` event fires and no second reconnect is scheduled — `connect()`\n * below is the single path that re-opens. Returns the `connect()` promise.\n */\n reconnect() {\n this.shouldConnect = true;\n\n // Cancel any in-flight retryer so we don't stack two connection attempts.\n if (this.cancelWebsocketRetry) {\n this.cancelWebsocketRetry();\n this.cancelWebsocketRetry = undefined;\n }\n\n // Silently drop the current socket (cleanupWebSocket removes our handlers\n // before closing, so onClose never runs → no auto-reschedule).\n if (this.webSocket) {\n this.cleanupWebSocket();\n }\n\n // connect() early-returns when status is Connected; force Disconnected so\n // it always builds a fresh socket. Surface the transition so status\n // listeners (and the providers' synced reset) see the drop.\n this.status = WebSocketStatus.Disconnected;\n this.emit(\"status\", { status: WebSocketStatus.Disconnected });\n\n return this.connect();\n }\n\n send(message: any) {\n if (this.webSocket?.readyState === WsReadyStates.Open) {\n this.webSocket.send(message);\n } else {\n this.messageQueue.push(message);\n }\n }\n\n /** The last token this socket was re-armed with — see {@link refreshAuth}. */\n private lastRefreshToken: string | null = null;\n\n /**\n * Re-arm this CONNECTION with a freshly minted JWT, in place.\n *\n * The server tracks a connection's expiry as one shared value\n * (`SyncSession`'s `jwt_exp`, an `Arc<AtomicI64>` every session on the socket\n * points at) and rejects every non-stateless frame once it passes — dropping\n * the whole socket for an ordinary session. `auth:refresh {\"token\":…}` moves\n * that value, and it rides `MSG_STATELESS` precisely because stateless is the\n * one frame kind an expired session may still send.\n *\n * So ONE frame, through any authenticated document, re-arms everything\n * multiplexed here. Sending it per attached provider would be N identical\n * frames on a shared socket carrying sixty documents; `lastRefreshToken` is\n * what keeps it at one.\n *\n * Verified against a live server with a 45-second token TTL, on an ORDINARY\n * (non-elevated) account, refreshing before the lapse so the socket is never\n * dropped and never re-handshaken: without the frame the socket is closed\n * past the original expiry, with it `close` never fires at all.\n *\n * Returns whether a frame actually went out. `false` means there was nobody\n * to send it through — harmless, because the next handshake carries the new\n * token anyway (see the provider's token closure).\n */\n refreshAuth(token: string): boolean {\n if (!token || token === this.lastRefreshToken) return false;\n if (this.status !== WebSocketStatus.Connected) return false;\n const payload = `auth:refresh ${JSON.stringify({ token })}`;\n for (const provider of this.configuration.providerMap.values()) {\n // An authenticated document is required: the frame is dispatched by\n // document name, and a name this connection has no session for has\n // nothing to re-arm.\n if (!provider.isAuthenticated) continue;\n provider.sendStateless(payload);\n this.lastRefreshToken = token;\n return true;\n }\n return false;\n }\n\n onClose({ event }: onCloseParameters) {\n this.closeTries = 0;\n this.cleanupWebSocket();\n\n if (this.connectionAttempt) {\n // That connection attempt failed.\n this.rejectConnectionAttempt();\n }\n\n // Let's update the connection status.\n this.status = WebSocketStatus.Disconnected;\n this.emit(\"status\", { status: WebSocketStatus.Disconnected });\n\n // Detect server-side rate-limit close (code 4429).\n // `event` may be a CloseEvent (browser) with `.code`, or a raw number (ws/Node.js).\n // `event` may be a CloseEvent (browser) with `.code`, or a raw number (ws/Node.js).\n const isRateLimited = (event as any)?.code === 4429 || (event as unknown) === 4429;\n this.emit(\"disconnect\", { event });\n if (isRateLimited) {\n this.emit(\"rateLimited\");\n }\n\n // trigger connect if no retry is running and we want to have a connection.\n // Skip scheduling entirely while offline — `handleOnline` resumes the\n // moment connectivity returns, so there's no point burning a timer (and a\n // failed attempt) against a dead network.\n if (!this.cancelWebsocketRetry && this.shouldConnect && this.isOnline) {\n // Apply a much longer delay for rate-limited closes to let the server window reset.\n const delay = isRateLimited ? 60_000 : this.configuration.delay;\n setTimeout(() => {\n this.connect();\n }, delay);\n }\n }\n\n destroy() {\n // Mark as not wanting a connection FIRST so that onClose (fired by disconnect()\n // below) does not schedule a new reconnect setTimeout after we've torn down.\n this.shouldConnect = false;\n\n this.emit(\"destroy\");\n\n if (typeof window !== \"undefined\" && typeof window.removeEventListener === \"function\") {\n if (this.onlineListener) window.removeEventListener(\"online\", this.onlineListener);\n if (this.offlineListener) window.removeEventListener(\"offline\", this.offlineListener);\n }\n this.onlineListener = null;\n this.offlineListener = null;\n\n // The lifecycle gate is process-wide and outlives this socket, so a missed\n // unsubscribe here leaks a closure holding the destroyed socket for the\n // lifetime of the tab.\n this.unsubscribeLifecycle?.();\n this.unsubscribeLifecycle = null;\n\n clearInterval(this.intervals.connectionChecker);\n\n // If there is still a connection attempt outstanding then we should stop\n // it before calling disconnect, otherwise it will be rejected in the onClose\n // handler and trigger a retry\n this.stopConnectionAttempt();\n\n this.disconnect();\n\n this.removeAllListeners();\n\n this.cleanupWebSocket();\n }\n}\n\n/** @deprecated Use AbracadabraWS */\nexport const HocuspocusProviderWebsocket = AbracadabraWS;\n/** @deprecated Use AbracadabraWS */\nexport type HocuspocusProviderWebsocket = AbracadabraWS;\n","import * as encoding from \"lib0/encoding\";\nimport * as decoding from \"lib0/decoding\";\nimport type { AuthorizedScope } from \"./types.ts\";\n\nexport enum AuthMessageType {\n\tToken = 0,\n\tPermissionDenied = 1,\n\tAuthenticated = 2,\n}\n\nexport const writeAuthentication = (\n\tencoder: encoding.Encoder,\n\tauth: string,\n) => {\n\tencoding.writeVarUint(encoder, AuthMessageType.Token);\n\tencoding.writeVarString(encoder, auth);\n};\n\nexport const writePermissionDenied = (\n\tencoder: encoding.Encoder,\n\treason: string,\n) => {\n\tencoding.writeVarUint(encoder, AuthMessageType.PermissionDenied);\n\tencoding.writeVarString(encoder, reason);\n};\n\nexport const writeAuthenticated = (\n\tencoder: encoding.Encoder,\n\tscope: AuthorizedScope,\n) => {\n\tencoding.writeVarUint(encoder, AuthMessageType.Authenticated);\n\tencoding.writeVarString(encoder, scope);\n};\n\nexport const writeTokenSyncRequest = (\n\tencoder: encoding.Encoder,\n) => {\n\tencoding.writeVarUint(encoder, AuthMessageType.Token);\n};\n\nexport const readAuthMessage = (\n\tdecoder: decoding.Decoder,\n\tsendToken: () => void,\n\tpermissionDeniedHandler: (reason: string) => void,\n\tauthenticatedHandler: (scope: string) => void,\n) => {\n\tswitch (decoding.readVarUint(decoder)) {\n\t\tcase AuthMessageType.Token: {\n\t\t\tsendToken();\n\t\t\tbreak;\n\t\t}\n\t\tcase AuthMessageType.PermissionDenied: {\n\t\t\tpermissionDeniedHandler(decoding.readVarString(decoder));\n\t\t\tbreak;\n\t\t}\n\t\tcase AuthMessageType.Authenticated: {\n\t\t\tauthenticatedHandler(decoding.readVarString(decoder));\n\t\t\tbreak;\n\t\t}\n\t\tdefault:\n\t}\n};\n","import { readAuthMessage } from \"./auth.ts\";\nimport { readVarInt, readVarString } from \"lib0/decoding\";\nimport type { CloseEvent } from \"ws\";\nimport * as awarenessProtocol from \"y-protocols/awareness\";\nimport { messageYjsSyncStep2, readSyncMessage } from \"y-protocols/sync\";\nimport type { AbracadabraBaseProvider } from \"./AbracadabraBaseProvider.ts\";\nimport type { IncomingMessage } from \"./IncomingMessage.ts\";\nimport { OutgoingMessage } from \"./OutgoingMessage.ts\";\nimport { MessageType } from \"./types.ts\";\n\nexport class MessageReceiver {\n message: IncomingMessage;\n\n constructor(message: IncomingMessage) {\n this.message = message;\n }\n\n public apply(provider: AbracadabraBaseProvider, emitSynced: boolean) {\n const { message } = this;\n const type = message.readVarUint();\n\n const emptyMessageLength = message.length();\n\n switch (type) {\n case MessageType.Sync:\n this.applySyncMessage(provider, emitSynced);\n break;\n\n case MessageType.Awareness:\n this.applyAwarenessMessage(provider);\n break;\n\n case MessageType.Auth:\n this.applyAuthMessage(provider);\n break;\n\n case MessageType.QueryAwareness:\n this.applyQueryAwarenessMessage(provider);\n break;\n\n case MessageType.Stateless:\n provider.receiveStateless(readVarString(message.decoder));\n break;\n\n case MessageType.SyncStatus:\n this.applySyncStatusMessage(provider, readVarInt(message.decoder) === 1);\n break;\n\n case MessageType.CLOSE:\n // eslint-disable-next-line no-case-declarations\n const event: CloseEvent = {\n code: 1000,\n reason: readVarString(message.decoder),\n // @ts-ignore\n target: provider.configuration.websocketProvider.webSocket!,\n type: \"close\",\n };\n provider.onClose();\n provider.configuration.onClose({ event });\n provider.forwardClose({ event });\n break;\n\n default:\n throw new Error(`Can’t apply message of unknown type: ${type}`);\n }\n\n // Reply\n if (message.length() > emptyMessageLength + 1) {\n // length of documentName (considered in emptyMessageLength plus length of yjs sync type, set in applySyncMessage)\n // @ts-ignore\n provider.send(OutgoingMessage, { encoder: message.encoder });\n }\n }\n\n private applySyncMessage(provider: AbracadabraBaseProvider, emitSynced: boolean) {\n const { message } = this;\n\n message.writeVarUint(MessageType.Sync);\n\n // Apply update\n const syncMessageType = readSyncMessage(\n message.decoder,\n message.encoder,\n provider.document,\n provider,\n );\n\n // Synced once we receive Step2\n if (emitSynced && syncMessageType === messageYjsSyncStep2) {\n provider.synced = true;\n }\n }\n\n applySyncStatusMessage(provider: AbracadabraBaseProvider, applied: boolean) {\n if (applied) {\n provider.decrementUnsyncedChanges();\n return;\n }\n\n // applied = 0 is the server saying \"I did not take that update\". It is\n // sent for a write the caller's role isn't allowed to make and for one a\n // server-side gate rejected (schema validation, size/pattern guards).\n //\n // This branch used to be empty. Not decrementing is correct — the change\n // must stay queued rather than be counted as landed — but silence is not:\n // nothing in the SDK, and therefore nothing in any app built on it, could\n // tell that the edit sitting on screen had already been refused. That is\n // the whole \"it saved, and then it wasn't there after reload\" class.\n provider.reportWriteRejected(\n \"server did not apply the update (permission or validation)\",\n \"validation\",\n );\n }\n\n private applyAwarenessMessage(provider: AbracadabraBaseProvider) {\n // `peekAwareness`, never `.awareness`: reading the public accessor here\n // would build an Awareness instance — with its 3 s heartbeat and its 15 s\n // wire renewal — for every background-loaded document the moment ANY peer\n // announced themselves in it. A document with no local presence has\n // nothing to render a peer's cursor into; if it later gains an editor,\n // materialization sends its own QueryAwareness and catches up then.\n const awareness = provider.peekAwareness();\n if (!awareness) return;\n\n const { message } = this;\n\n awarenessProtocol.applyAwarenessUpdate(\n awareness,\n message.readVarUint8Array(),\n provider,\n );\n }\n\n private applyAuthMessage(provider: AbracadabraBaseProvider) {\n const { message } = this;\n\n readAuthMessage(\n message.decoder,\n provider.sendToken.bind(provider),\n provider.permissionDeniedHandler.bind(provider),\n provider.authenticatedHandler.bind(provider),\n );\n }\n\n private applyQueryAwarenessMessage(provider: AbracadabraBaseProvider) {\n // Same reasoning as applyAwarenessMessage: a document with no local\n // presence has nothing to answer a peer's roll-call with, and answering\n // would mean creating the very instance the lazy path exists to avoid.\n const awareness = provider.peekAwareness();\n if (!awareness) return;\n\n const { message } = this;\n\n message.writeVarUint(MessageType.Awareness);\n message.writeVarUint8Array(\n awarenessProtocol.encodeAwarenessUpdate(\n awareness,\n Array.from(awareness.getStates().keys()),\n ),\n );\n }\n}\n","import type { Encoder } from \"lib0/encoding\";\nimport { toUint8Array } from \"lib0/encoding\";\nimport type { ConstructableOutgoingMessage } from \"./types.ts\";\n\nexport class MessageSender {\n\tencoder: Encoder;\n\n\tmessage: any;\n\n\tconstructor(Message: ConstructableOutgoingMessage, args: any = {}) {\n\t\tthis.message = new Message();\n\t\tthis.encoder = this.message.get(args);\n\t}\n\n\tcreate() {\n\t\treturn toUint8Array(this.encoder);\n\t}\n\n\tsend(webSocket: any) {\n\t\twebSocket?.send(this.create());\n\t}\n}\n","import { writeVarString, writeVarUint } from \"lib0/encoding\";\nimport { writeAuthentication } from \"../auth.ts\";\nimport type { OutgoingMessageArguments } from \"../types.ts\";\nimport { MessageType } from \"../types.ts\";\nimport { OutgoingMessage } from \"../OutgoingMessage.ts\";\n\nexport class AuthenticationMessage extends OutgoingMessage {\n type = MessageType.Auth;\n\n description = \"Authentication\";\n\n get(args: Partial<OutgoingMessageArguments>) {\n if (typeof args.token === \"undefined\") {\n throw new Error(\"The authentication message requires `token` as an argument.\");\n }\n\n writeVarString(this.encoder, args.documentName!);\n writeVarUint(this.encoder, this.type);\n writeAuthentication(this.encoder, args.token);\n\n return this.encoder;\n }\n}\n","import * as encoding from \"lib0/encoding\";\nimport { encodeAwarenessUpdate } from \"y-protocols/awareness\";\nimport type { OutgoingMessageArguments } from \"../types.ts\";\nimport { MessageType } from \"../types.ts\";\nimport { OutgoingMessage } from \"../OutgoingMessage.ts\";\n\nexport class AwarenessMessage extends OutgoingMessage {\n\ttype = MessageType.Awareness;\n\n\tdescription = \"Awareness states update\";\n\n\tget(args: Partial<OutgoingMessageArguments>) {\n\t\tif (typeof args.awareness === \"undefined\") {\n\t\t\tthrow new Error(\n\t\t\t\t\"The awareness message requires awareness as an argument\",\n\t\t\t);\n\t\t}\n\n\t\tif (typeof args.clients === \"undefined\") {\n\t\t\tthrow new Error(\"The awareness message requires clients as an argument\");\n\t\t}\n\n\t\tencoding.writeVarString(this.encoder, args.documentName!);\n\t\tencoding.writeVarUint(this.encoder, this.type);\n\n\t\tlet awarenessUpdate;\n\t\tif (args.states === undefined) {\n\t\t\tawarenessUpdate = encodeAwarenessUpdate(args.awareness, args.clients);\n\t\t} else {\n\t\t\tawarenessUpdate = encodeAwarenessUpdate(\n\t\t\t\targs.awareness,\n\t\t\t\targs.clients,\n\t\t\t\targs.states,\n\t\t\t);\n\t\t}\n\n\t\tencoding.writeVarUint8Array(this.encoder, awarenessUpdate);\n\n\t\treturn this.encoder;\n\t}\n}\n","import { writeVarString, writeVarUint } from \"lib0/encoding\";\nimport type { OutgoingMessageArguments } from \"../types.ts\";\nimport { MessageType } from \"../types.ts\";\nimport { OutgoingMessage } from \"../OutgoingMessage.ts\";\n\nexport class StatelessMessage extends OutgoingMessage {\n\ttype = MessageType.Stateless;\n\n\tdescription = \"A stateless message\";\n\n\tget(args: Partial<OutgoingMessageArguments>) {\n\t\twriteVarString(this.encoder, args.documentName!);\n\t\twriteVarUint(this.encoder, this.type);\n\t\twriteVarString(this.encoder, args.payload ?? \"\");\n\n\t\treturn this.encoder;\n\t}\n}\n","import EventEmitter from \"./EventEmitter.ts\";\n\n/**\n * RPC v1 — request/response over `MSG_STATELESS`.\n *\n * Mirrors `docs/rpc-v1.md` in the abracadabra-rs server. Frames travel as\n * `MSG_STATELESS` payloads with the literal prefix `rpc:v1:` followed by a\n * JSON envelope. The provider's existing `sendStateless` / `stateless` event\n * stream is the only transport surface this layer touches; everything else\n * (state machine, deadlines, handler registry, dedupe of self-replies) lives\n * here.\n */\n\nexport const RPC_PREFIX = \"rpc:v1:\";\n\nexport type RpcKind =\n | \"req\"\n | \"ack\"\n | \"nack\"\n | \"progress\"\n | \"result\"\n | \"cancel\"\n | \"hb\"\n | \"register\"\n | \"unregister\";\n\nexport interface RpcFrame {\n kind: RpcKind;\n id: string;\n ts?: number;\n from?: string;\n to?: string;\n method?: string;\n args?: unknown;\n deadline_ms?: number;\n data?: unknown;\n error?: RpcErrorPayload;\n by?: \"server\" | \"runner\";\n runner_id?: string;\n seq?: number;\n methods?: string[];\n}\n\nexport interface RpcErrorPayload {\n code: string;\n message: string;\n details?: unknown;\n}\n\nexport type RpcErrorCode =\n | \"NO_HANDLER\"\n | \"HANDLER_GONE\"\n | \"TIMEOUT\"\n | \"CANCELLED\"\n | \"RATE_LIMITED\"\n | \"UNAUTHORIZED\"\n | \"SCHEMA\"\n | \"INTERNAL\"\n | \"APP\"\n | string; // forward-compat for unknown codes from runners\n\n/** Thrown by `rpc.call(...)` on terminal nack / error / timeout. */\nexport class RpcError extends Error {\n code: RpcErrorCode;\n details?: unknown;\n constructor(code: RpcErrorCode, message: string, details?: unknown) {\n super(message);\n this.name = \"RpcError\";\n this.code = code;\n this.details = details;\n }\n}\n\n/**\n * Minimal provider surface RpcClient needs. The base provider already\n * satisfies it; the indirection is here so handlers can be tested against\n * a stub without booting a Y.Doc.\n */\nexport interface RpcTransport {\n sendStateless(payload: string): void;\n // eslint-disable-next-line @typescript-eslint/no-unsafe-function-type\n on(event: string, fn: Function): unknown;\n // eslint-disable-next-line @typescript-eslint/no-unsafe-function-type\n off(event: string, fn?: Function): unknown;\n}\n\nexport type RpcTarget =\n | { kind: \"role\"; role: \"service\" }\n | { kind: \"user\"; userId: string }\n | { kind: \"runner\"; sessionId: string };\n\nexport interface RpcCallOptions {\n /** Defaults to `{ kind: \"role\", role: \"service\" }`. */\n target?: RpcTarget;\n /** Wall-clock deadline in ms. Server clamps to its own ceiling. */\n deadline?: number;\n /** Abort the call (sends `rpc:cancel` to the runner). */\n signal?: AbortSignal;\n /** Fired when a runner claims the call (after the server ack). */\n onClaim?: (runnerId: string) => void;\n /** Fired for every `rpc:progress` frame the runner emits. */\n onProgress?: (data: unknown, seq: number) => void;\n}\n\nexport interface RpcCallHandle<T = unknown> extends Promise<T> {\n /** RPC id (UUID v7) — useful for log correlation. */\n readonly id: string;\n /** Runner session id, populated once a runner has claimed the call. */\n readonly claimedBy: string | undefined;\n /** Cancel the call. Equivalent to `signal.abort()` if a signal was passed. */\n cancel(reason?: string): void;\n}\n\ninterface PendingRpc {\n id: string;\n resolve: (value: unknown) => void;\n reject: (err: Error) => void;\n options: RpcCallOptions;\n state: \"pending\" | \"accepted\" | \"claimed\" | \"settled\";\n claimedBy: string | undefined;\n deadlineTimer: ReturnType<typeof setTimeout> | undefined;\n}\n\n/**\n * Handler signature for a runner-side RPC handler.\n *\n * Returning a value emits `rpc:result(ok)`. Throwing emits\n * `rpc:result(err)` — `RpcError` instances pass through their `code` and\n * `details`; any other thrown value becomes `INTERNAL`.\n *\n * Returning an async generator turns each `yield` into a `rpc:progress`\n * frame (with monotonic `seq`); the generator's return value is the final\n * `result.data`.\n */\nexport type RpcHandler = (\n args: unknown,\n ctx: RpcHandlerContext,\n) =>\n | unknown\n | Promise<unknown>\n | AsyncGenerator<unknown, unknown, void>;\n\nexport interface RpcHandlerContext {\n id: string;\n method: string;\n /** Server-stamped caller user id. Trusted. */\n from: string;\n /** Aborted when the caller cancels or the deadline is reached. */\n signal: AbortSignal;\n}\n\n// ── UUID v7 (small inline impl) ─────────────────────────────────────────────\n\nfunction uuidv7(): string {\n // Minimal UUID v7 — time-ordered, 122 random bits.\n const ts = Date.now();\n const tsHex = ts.toString(16).padStart(12, \"0\");\n const rand = new Uint8Array(10);\n if (typeof crypto !== \"undefined\" && crypto.getRandomValues) {\n crypto.getRandomValues(rand);\n } else {\n for (let i = 0; i < rand.length; i++) rand[i] = Math.floor(Math.random() * 256);\n }\n // version=7, variant=10\n rand[0] = (rand[0] & 0x0f) | 0x70;\n rand[2] = (rand[2] & 0x3f) | 0x80;\n const hex = Array.from(rand, (b) => b.toString(16).padStart(2, \"0\")).join(\"\");\n return (\n `${tsHex.slice(0, 8)}-${tsHex.slice(8, 12)}-` +\n `${hex.slice(0, 4)}-${hex.slice(4, 8)}-${hex.slice(8, 20)}`\n );\n}\n\n// ── Client ──────────────────────────────────────────────────────────────────\n\n/**\n * Per-provider RPC layer. Construct one and attach by passing the provider\n * (or any `RpcTransport`). Disposes on `destroy()`.\n *\n * Caller side: `rpc.call('ai.summarize@1', { docId }, { onProgress })`.\n *\n * Runner side: `rpc.handle('ai.summarize@1', async (args, ctx) => …)`.\n */\nexport class RpcClient extends EventEmitter {\n private readonly transport: RpcTransport;\n private readonly pending = new Map<string, PendingRpc>();\n private readonly handlers = new Map<string, RpcHandler>();\n /** Tracks live runner-side invocations so we can route `rpc:cancel`. */\n private readonly runningHandlers = new Map<string, AbortController>();\n /** Pending register frames awaiting server ack — resolved by id. */\n private readonly pendingRegistrations = new Map<string, () => void>();\n /** Grace timer armed on `disconnect`; cancelled on `connect`. Fires\n * `HANDLER_GONE` on every pending RPC if the WS is still down after\n * the grace window. v1 used to wait `deadline + 5s` which could be\n * 35s on default deadlines — way too long for a definitively-dead\n * connection. */\n private disconnectGrace: ReturnType<typeof setTimeout> | undefined;\n private static readonly DISCONNECT_GRACE_MS = 10_000;\n private readonly onStatelessBound: (data: { payload: string }) => void;\n /**\n * Replays all live `register` frames whenever the underlying provider\n * (re)syncs — covers WebSocket reconnects where the server allocated a\n * new session id and the old capability entries were freed.\n */\n private readonly onSyncedBound: (data: { state: boolean }) => void;\n private readonly onDisconnectBound: () => void;\n private readonly onConnectBound: () => void;\n private destroyed = false;\n\n constructor(transport: RpcTransport) {\n super();\n this.transport = transport;\n this.onStatelessBound = (data) => this.receive(data.payload);\n this.onSyncedBound = (data) => {\n if (data.state) this.replayRegistrations();\n };\n this.onDisconnectBound = () => this.armDisconnectGrace();\n this.onConnectBound = () => this.cancelDisconnectGrace();\n transport.on(\"stateless\", this.onStatelessBound);\n transport.on(\"synced\", this.onSyncedBound);\n transport.on(\"disconnect\", this.onDisconnectBound);\n transport.on(\"connect\", this.onConnectBound);\n }\n\n private armDisconnectGrace(): void {\n if (this.destroyed) return;\n if (this.disconnectGrace) return; // already armed\n this.disconnectGrace = setTimeout(\n () => this.failPendingOnDisconnect(),\n RpcClient.DISCONNECT_GRACE_MS,\n );\n }\n\n private cancelDisconnectGrace(): void {\n if (this.disconnectGrace) {\n clearTimeout(this.disconnectGrace);\n this.disconnectGrace = undefined;\n }\n }\n\n /**\n * Called when the WS has been down for the full grace window. Every\n * in-flight call is dead from the server's perspective (its `close_session`\n * already fired `HANDLER_GONE` to a now-disconnected caller; on reconnect\n * the server-side session is fresh, so any cached cancel/result frames\n * the server tried to deliver were lost). Fail pending immediately.\n */\n private failPendingOnDisconnect(): void {\n this.disconnectGrace = undefined;\n if (this.destroyed) return;\n for (const [, p] of this.pending) {\n if (p.deadlineTimer) clearTimeout(p.deadlineTimer);\n this.settle(p, () =>\n p.reject(new RpcError(\"HANDLER_GONE\", \"websocket disconnected\")),\n );\n }\n }\n\n /**\n * Re-emit a `register` frame for every locally-known handler. Called on\n * every `synced` event from the provider, since a reconnected WS gets a\n * fresh server-side session with empty capability state.\n */\n private replayRegistrations(): void {\n if (this.destroyed) return;\n // A fresh server-side session will never ack any register frame issued\n // before this `synced` event, so prior pending entries are dead. Resolve\n // them with the current map clear so any awaiting `ready()` doesn't\n // hang forever — the new register below is the source of truth now.\n if (this.pendingRegistrations.size > 0) {\n const stale = [...this.pendingRegistrations.values()];\n this.pendingRegistrations.clear();\n for (const r of stale) r();\n }\n if (this.handlers.size === 0) return;\n const methods = [...this.handlers.keys()];\n const id = uuidv7();\n // Track this re-register so `ready()` resolves once the server ack lands.\n this.pendingRegistrations.set(id, () => {});\n this.send({ kind: \"register\", id, methods });\n }\n\n destroy(): void {\n if (this.destroyed) return;\n this.destroyed = true;\n this.transport.off(\"stateless\", this.onStatelessBound);\n this.transport.off(\"synced\", this.onSyncedBound);\n this.transport.off(\"disconnect\", this.onDisconnectBound);\n this.transport.off(\"connect\", this.onConnectBound);\n this.cancelDisconnectGrace();\n // Abort every in-flight handler.\n for (const [, ac] of this.runningHandlers) {\n try { ac.abort(); } catch { /* noop */ }\n }\n this.runningHandlers.clear();\n // Reject every pending caller.\n for (const [, p] of this.pending) {\n if (p.deadlineTimer) clearTimeout(p.deadlineTimer);\n p.reject(new RpcError(\"CANCELLED\", \"RpcClient destroyed\"));\n }\n this.pending.clear();\n // Unblock any awaiters of `ready()` — the WS is gone and no register\n // ack will ever land. Resolving (vs rejecting) keeps `ready(): Promise<void>`\n // semantically clean; the call sites that follow `ready()` are typically\n // diagnostic/orchestration, not request hot paths.\n for (const [, resolve] of this.pendingRegistrations) {\n try { resolve(); } catch { /* noop */ }\n }\n this.pendingRegistrations.clear();\n this.handlers.clear();\n this.removeAllListeners();\n }\n\n // ── Caller side ───────────────────────────────────────────────────────────\n\n /**\n * Send an RPC and return a handle that resolves with the runner's result.\n * Throws `RpcError` on nack / handler error / timeout / cancellation.\n */\n call<T = unknown>(method: string, args?: unknown, options?: RpcCallOptions): RpcCallHandle<T> {\n const opts = options ?? {};\n const id = uuidv7();\n const target = opts.target ?? { kind: \"role\", role: \"service\" };\n\n let resolve!: (value: unknown) => void;\n let reject!: (err: Error) => void;\n const promise = new Promise<unknown>((res, rej) => {\n resolve = res;\n reject = rej;\n });\n\n // Calling on a destroyed client used to silently hang because `send()`\n // short-circuits but the pending entry was already created. Reject now\n // and skip the rest so consumers always get a terminal outcome.\n if (this.destroyed) {\n const handle = promise as RpcCallHandle<T>;\n Object.defineProperty(handle, \"id\", { value: id, enumerable: true });\n Object.defineProperty(handle, \"claimedBy\", { enumerable: true, get: () => undefined });\n handle.cancel = () => {};\n reject(new RpcError(\"CANCELLED\", \"rpc client destroyed\"));\n return handle;\n }\n\n // Pre-aborted signal: no point sending the `req` (the runner would do\n // wasted work for a caller that's already given up) and no point sending\n // a `cancel` for an id the server has never seen. Short-circuit cleanly.\n if (opts.signal?.aborted) {\n const reason = opts.signal.reason;\n const handle = promise as RpcCallHandle<T>;\n Object.defineProperty(handle, \"id\", { value: id, enumerable: true });\n Object.defineProperty(handle, \"claimedBy\", { enumerable: true, get: () => undefined });\n handle.cancel = () => {};\n reject(new RpcError(\"CANCELLED\", typeof reason === \"string\" ? reason : \"aborted\"));\n return handle;\n }\n\n const pending: PendingRpc = {\n id,\n resolve,\n reject,\n options: opts,\n state: \"pending\",\n claimedBy: undefined,\n deadlineTimer: undefined,\n };\n this.pending.set(id, pending);\n\n // Local fallback timeout so we don't wait past `deadline` if the server\n // somehow goes silent (it shouldn't — server enforces its own).\n const deadline = opts.deadline ?? 30_000;\n pending.deadlineTimer = setTimeout(() => {\n if (pending.state !== \"settled\") {\n this.settle(pending, () =>\n reject(new RpcError(\"TIMEOUT\", \"rpc deadline exceeded (client-side)\")),\n );\n }\n }, deadline + 5_000); // grace window so server-side TIMEOUT lands first\n\n // Pre-aborted signals were handled above (no req frame sent). For a live\n // signal, listen for abort and cancel mid-flight when it trips.\n if (opts.signal) {\n opts.signal.addEventListener(\n \"abort\",\n () => this.abortInFlight(pending, opts.signal?.reason),\n { once: true },\n );\n }\n\n const frame: RpcFrame = {\n kind: \"req\",\n id,\n ts: Date.now(),\n method,\n args,\n to: serializeTarget(target),\n deadline_ms: deadline,\n };\n this.send(frame);\n\n const handle = promise as RpcCallHandle<T>;\n Object.defineProperty(handle, \"id\", { value: id, enumerable: true });\n Object.defineProperty(handle, \"claimedBy\", {\n enumerable: true,\n get: () => pending.claimedBy,\n });\n handle.cancel = (reason?: string) => this.abortInFlight(pending, reason);\n return handle;\n }\n\n private abortInFlight(pending: PendingRpc, reason?: unknown): void {\n if (pending.state === \"settled\") return;\n // Tell the runner we're cancelling.\n this.send({ kind: \"cancel\", id: pending.id, ts: Date.now(), data: reason ? { reason: String(reason) } : undefined });\n // Reject locally; the server may still emit a CANCELLED result later\n // (we'll see it but the pending is gone, so it's a no-op).\n this.settle(pending, () =>\n pending.reject(new RpcError(\"CANCELLED\", typeof reason === \"string\" ? reason : \"cancelled\")),\n );\n }\n\n // ── Runner side ───────────────────────────────────────────────────────────\n\n /**\n * Register a handler for `method` and advertise it to the server so\n * incoming `to: role:service` calls resolve here. Returns an unsubscribe\n * function. Calling `register` twice for the same method replaces the\n * handler and re-advertises.\n *\n * The advertise is fire-and-forget; if you need to wait until the server\n * has acknowledged registration (typical in tests with a separate caller\n * connection), `await rpc.ready()` after registering all handlers.\n */\n handle(method: string, handler: RpcHandler): () => void {\n this.handlers.set(method, handler);\n const id = uuidv7();\n this.pendingRegistrations.set(id, () => {\n // Default no-op; overwritten when ready() is awaited.\n });\n this.send({ kind: \"register\", id, methods: [method] });\n return () => {\n if (this.handlers.get(method) === handler) {\n this.handlers.delete(method);\n this.send({ kind: \"unregister\", id: uuidv7(), methods: [method] });\n }\n };\n }\n\n /**\n * Resolve once every outstanding `register` frame has been acknowledged\n * by the server. Useful when a separate connection is about to issue\n * `rpc.call(...)` and you need the capability registry to be live first.\n * Resolves immediately if there's nothing pending.\n */\n ready(): Promise<void> {\n if (this.pendingRegistrations.size === 0) return Promise.resolve();\n const ids = [...this.pendingRegistrations.keys()];\n return Promise.all(\n ids.map(\n (id) =>\n new Promise<void>((resolve) => {\n this.pendingRegistrations.set(id, resolve);\n }),\n ),\n ).then(() => undefined);\n }\n\n // ── Wire ───────────────────────────────────────────────────────────────────\n\n private send(frame: Partial<RpcFrame> & Pick<RpcFrame, \"kind\" | \"id\">): void {\n if (this.destroyed) return;\n const payload = `${RPC_PREFIX}${JSON.stringify(frame)}`;\n this.transport.sendStateless(payload);\n }\n\n private receive(payload: string): void {\n if (!payload.startsWith(RPC_PREFIX)) return;\n const json = payload.slice(RPC_PREFIX.length);\n let frame: RpcFrame;\n try {\n frame = JSON.parse(json) as RpcFrame;\n } catch {\n return;\n }\n switch (frame.kind) {\n case \"ack\": return this.onAck(frame);\n case \"progress\": return this.onProgress(frame);\n case \"result\": return this.onResult(frame);\n case \"nack\": return this.onNack(frame);\n case \"req\": return void this.onReq(frame);\n case \"cancel\": return this.onCancel(frame);\n // hb / register / unregister never travel client-bound.\n default: return;\n }\n }\n\n private onAck(frame: RpcFrame): void {\n // Register-ack: server confirmed a `register` frame.\n const pendingReg = this.pendingRegistrations.get(frame.id);\n if (pendingReg) {\n this.pendingRegistrations.delete(frame.id);\n pendingReg();\n return;\n }\n const pending = this.pending.get(frame.id);\n if (!pending) return;\n if (frame.by === \"server\" && pending.state === \"pending\") {\n pending.state = \"accepted\";\n } else if (frame.by === \"runner\") {\n pending.state = \"claimed\";\n pending.claimedBy = frame.runner_id;\n pending.options.onClaim?.(frame.runner_id ?? \"\");\n }\n }\n\n private onProgress(frame: RpcFrame): void {\n const pending = this.pending.get(frame.id);\n if (!pending) return;\n pending.options.onProgress?.(frame.data, frame.seq ?? 0);\n }\n\n private onResult(frame: RpcFrame): void {\n const pending = this.pending.get(frame.id);\n if (!pending) return;\n if (frame.error) {\n const err = new RpcError(frame.error.code, frame.error.message, frame.error.details);\n this.settle(pending, () => pending.reject(err));\n } else {\n this.settle(pending, () => pending.resolve(frame.data));\n }\n }\n\n private onNack(frame: RpcFrame): void {\n const pending = this.pending.get(frame.id);\n if (!pending) return;\n const err = frame.error\n ? new RpcError(frame.error.code, frame.error.message, frame.error.details)\n : new RpcError(\"INTERNAL\", \"rpc nack\");\n this.settle(pending, () => pending.reject(err));\n }\n\n private settle(pending: PendingRpc, finalize: () => void): void {\n if (pending.state === \"settled\") return;\n pending.state = \"settled\";\n if (pending.deadlineTimer) clearTimeout(pending.deadlineTimer);\n this.pending.delete(pending.id);\n finalize();\n }\n\n // ── Inbound request (runner side) ─────────────────────────────────────────\n\n private async onReq(frame: RpcFrame): Promise<void> {\n const method = frame.method ?? \"\";\n const handler = this.handlers.get(method);\n if (!handler) {\n // Server should have nacked NO_HANDLER before we got here; ignore.\n return;\n }\n if (this.runningHandlers.has(frame.id)) {\n // Duplicate req — server retry path. Server will re-emit the cached\n // terminal frame on its own; we just don't double-invoke.\n return;\n }\n const ac = new AbortController();\n this.runningHandlers.set(frame.id, ac);\n\n // Send the runner-claim ack immediately.\n this.send({\n kind: \"ack\",\n id: frame.id,\n ts: Date.now(),\n by: \"runner\",\n });\n\n const ctx: RpcHandlerContext = {\n id: frame.id,\n method,\n from: frame.from ?? \"\",\n signal: ac.signal,\n };\n\n // Heartbeat while the handler runs. The server doesn't enforce\n // inactivity in v1 but we send these so tooling can observe liveness\n // and a v2 server can fail stalled calls.\n const hbInterval = setInterval(() => {\n if (!ac.signal.aborted) {\n this.send({ kind: \"hb\", id: frame.id, ts: Date.now() });\n }\n }, 5_000);\n\n try {\n const ret = handler(frame.args, ctx);\n if (ret && typeof (ret as AsyncGenerator).next === \"function\" && typeof (ret as AsyncGenerator)[Symbol.asyncIterator] === \"function\") {\n // Generator: stream progress, return final.\n const gen = ret as AsyncGenerator<unknown, unknown, void>;\n let seq = 0;\n let final: unknown = undefined;\n while (true) {\n const { value, done } = await gen.next();\n if (done) {\n final = value;\n break;\n }\n if (ac.signal.aborted) break;\n this.send({ kind: \"progress\", id: frame.id, ts: Date.now(), seq: seq++, data: value });\n }\n if (ac.signal.aborted) {\n this.send({\n kind: \"result\",\n id: frame.id,\n ts: Date.now(),\n error: { code: \"CANCELLED\", message: \"handler cancelled\" },\n });\n } else {\n this.send({ kind: \"result\", id: frame.id, ts: Date.now(), data: final ?? null });\n }\n } else {\n const value = await (ret as Promise<unknown>);\n if (ac.signal.aborted) {\n this.send({\n kind: \"result\",\n id: frame.id,\n ts: Date.now(),\n error: { code: \"CANCELLED\", message: \"handler cancelled\" },\n });\n } else {\n this.send({ kind: \"result\", id: frame.id, ts: Date.now(), data: value ?? null });\n }\n }\n } catch (err) {\n const error =\n err instanceof RpcError\n ? { code: err.code, message: err.message, details: err.details }\n : { code: \"INTERNAL\", message: err instanceof Error ? err.message : String(err) };\n this.send({ kind: \"result\", id: frame.id, ts: Date.now(), error });\n } finally {\n clearInterval(hbInterval);\n this.runningHandlers.delete(frame.id);\n }\n }\n\n private onCancel(frame: RpcFrame): void {\n // The runner only ever observes `cancel` for an id whose `req` it has\n // already seen — frame ordering on a single WS preserves the\n // (req, cancel) sequence the server emits. If `runningHandlers` has\n // no entry for this id, the handler has already completed (cancel\n // arrived after result), so the cancel is informational and can be\n // dropped silently.\n const ac = this.runningHandlers.get(frame.id);\n if (ac) ac.abort(frame.error?.message ?? \"cancelled by caller\");\n }\n}\n\nfunction serializeTarget(t: RpcTarget): string {\n switch (t.kind) {\n case \"role\": return `role:${t.role}`;\n case \"user\": return `user:${t.userId}`;\n case \"runner\": return `runner:${t.sessionId}`;\n }\n}\n","import EventEmitter from \"./EventEmitter.ts\";\n\n/**\n * V2 query layer — live subscription client.\n *\n * Mirrors the server in `crates/abracadabra/src/query_stream.rs`. Frames\n * travel as `MSG_STATELESS` payloads with the literal `query:v1:` prefix\n * followed by a JSON envelope.\n *\n * Each call to `subscribeQuery(...)` opens a long-lived subscription:\n * 1. The client sends `req` with a fresh correlation id.\n * 2. The server replies `ack` with an initial snapshot\n * (`DocumentMeta[]`).\n * 3. The server emits `delta` frames as the doc-tree projection\n * drifts under the predicate.\n * 4. The client sends `cancel` to tear it down (or relies on the\n * WebSocket close path to free server state).\n *\n * The shape of the `query` field mirrors the REST `POST /docs/query`\n * body — `type`, `parentId`, `labelContains`, `where`, `limit`.\n */\n\nexport const QUERY_PREFIX = \"query:v1:\";\n\nexport type QueryKind = \"req\" | \"ack\" | \"delta\" | \"cancel\" | \"err\";\n\n/** Mirrors `crate::query_stream::QuerySpec`. */\nexport interface QuerySpec {\n\t/** Match `documents.kind` exactly. */\n\ttype?: string;\n\t/** Narrow to children of this doc. */\n\tparentId?: string;\n\t/** Case-insensitive substring on `documents.label`. */\n\tlabelContains?: string;\n\t/** Maximum rows returned (default 50, hard cap 500 server-side). */\n\tlimit?: number;\n\t/** Predicate AST. See `@abraca/schema/src/query.ts` for the shape. */\n\twhere?: unknown;\n}\n\nexport interface DocumentMetaWire {\n\tid: string;\n\tparent_id?: string | null;\n\tlabel?: string | null;\n\tkind?: string | null;\n\tdoc_type?: string | null;\n\tpublic_access?: string | null;\n\tdescription?: string | null;\n\towner_id?: string | null;\n}\n\nexport interface QueryFrame {\n\tkind: QueryKind;\n\tid: string;\n\tquery?: QuerySpec;\n\tinitial?: DocumentMetaWire[];\n\tadded?: DocumentMetaWire[];\n\tupdated?: DocumentMetaWire[];\n\tremoved?: string[];\n\terror?: { code: string; message: string };\n}\n\nexport class QueryError extends Error {\n\tcode: string;\n\tconstructor(code: string, message: string) {\n\t\tsuper(message);\n\t\tthis.name = \"QueryError\";\n\t\tthis.code = code;\n\t}\n}\n\nexport interface QuerySubscriptionHandlers {\n\t/** Fired once with the initial snapshot from the server's `ack`. */\n\tonSnapshot?: (rows: DocumentMetaWire[]) => void;\n\t/**\n\t * Fired on every `delta` after the initial ack. `added` are rows\n\t * newly matching the predicate; `removed` are doc_ids that no\n\t * longer match (or are no longer readable). v2 does not emit\n\t * `updated` — clients see updates as remove + add today; that\n\t * gap closes in v3 when row-level updates are tracked.\n\t */\n\tonDelta?: (delta: {\n\t\tadded: DocumentMetaWire[];\n\t\tremoved: string[];\n\t}) => void;\n\t/** Fired on `err` frames from the server. */\n\tonError?: (err: QueryError) => void;\n}\n\nexport interface QuerySubscriptionHandle {\n\t/** Correlation id assigned when the request was sent. */\n\treadonly id: string;\n\t/** Send a `cancel` to the server and stop dispatching to handlers. */\n\tcancel(): void;\n}\n\n/**\n * Minimal transport surface — matches `RpcTransport` so the provider\n * can satisfy both without extra glue.\n */\nexport interface QueryTransport {\n\tsendStateless(payload: string): void;\n\t// eslint-disable-next-line @typescript-eslint/no-unsafe-function-type\n\ton(event: string, fn: Function): unknown;\n\t// eslint-disable-next-line @typescript-eslint/no-unsafe-function-type\n\toff(event: string, fn?: Function): unknown;\n}\n\ninterface ActiveSubscription {\n\tid: string;\n\thandlers: QuerySubscriptionHandlers;\n\tcancelled: boolean;\n}\n\nexport class QueryClient extends EventEmitter {\n\tprivate readonly transport: QueryTransport;\n\tprivate readonly subs = new Map<string, ActiveSubscription>();\n\tprivate readonly onStatelessBound: (data: { payload: string }) => void;\n\tprivate idCounter = 0;\n\n\tconstructor(transport: QueryTransport) {\n\t\tsuper();\n\t\tthis.transport = transport;\n\t\tthis.onStatelessBound = (data) => this.receive(data.payload);\n\t\tthis.transport.on(\"stateless\", this.onStatelessBound);\n\t}\n\n\tdestroy(): void {\n\t\t// Best-effort cancel of every open sub. The WebSocket close\n\t\t// path also frees server state, so this is belt-and-suspenders.\n\t\tfor (const sub of this.subs.values()) {\n\t\t\tif (!sub.cancelled) {\n\t\t\t\tthis.send({ kind: \"cancel\", id: sub.id });\n\t\t\t\tsub.cancelled = true;\n\t\t\t}\n\t\t}\n\t\tthis.subs.clear();\n\t\tthis.transport.off(\"stateless\", this.onStatelessBound);\n\t}\n\n\tsubscribeQuery(\n\t\tspec: QuerySpec,\n\t\thandlers: QuerySubscriptionHandlers = {},\n\t): QuerySubscriptionHandle {\n\t\tconst id = this.nextId();\n\t\tconst sub: ActiveSubscription = {\n\t\t\tid,\n\t\t\thandlers,\n\t\t\tcancelled: false,\n\t\t};\n\t\tthis.subs.set(id, sub);\n\t\tthis.send({ kind: \"req\", id, query: spec });\n\t\tconst self = this;\n\t\treturn {\n\t\t\tid,\n\t\t\tcancel(): void {\n\t\t\t\tif (sub.cancelled) return;\n\t\t\t\tsub.cancelled = true;\n\t\t\t\tself.subs.delete(id);\n\t\t\t\tself.send({ kind: \"cancel\", id });\n\t\t\t},\n\t\t};\n\t}\n\n\tprivate nextId(): string {\n\t\tthis.idCounter += 1;\n\t\treturn `q-${Date.now()}-${this.idCounter}`;\n\t}\n\n\tprivate send(frame: QueryFrame): void {\n\t\tthis.transport.sendStateless(`${QUERY_PREFIX}${JSON.stringify(frame)}`);\n\t}\n\n\tprivate receive(payload: string): void {\n\t\tif (!payload.startsWith(QUERY_PREFIX)) return;\n\t\tconst rest = payload.slice(QUERY_PREFIX.length);\n\t\tlet frame: QueryFrame;\n\t\ttry {\n\t\t\tframe = JSON.parse(rest) as QueryFrame;\n\t\t} catch {\n\t\t\treturn;\n\t\t}\n\t\tconst sub = this.subs.get(frame.id);\n\t\tif (!sub || sub.cancelled) return;\n\t\tswitch (frame.kind) {\n\t\t\tcase \"ack\":\n\t\t\t\tsub.handlers.onSnapshot?.(frame.initial ?? []);\n\t\t\t\tbreak;\n\t\t\tcase \"delta\":\n\t\t\t\tsub.handlers.onDelta?.({\n\t\t\t\t\tadded: frame.added ?? [],\n\t\t\t\t\tremoved: frame.removed ?? [],\n\t\t\t\t});\n\t\t\t\tbreak;\n\t\t\tcase \"err\":\n\t\t\t\tif (frame.error) {\n\t\t\t\t\tsub.handlers.onError?.(\n\t\t\t\t\t\tnew QueryError(frame.error.code, frame.error.message),\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\t// Server treats `err` as terminal — drop the sub.\n\t\t\t\tthis.subs.delete(frame.id);\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\t// `req` / `cancel` are client→server only. Ignore.\n\t\t\t\tbreak;\n\t\t}\n\t}\n}\n","import * as encoding from \"lib0/encoding\";\nimport type { OutgoingMessageArguments } from \"../types.ts\";\nimport { MessageType } from \"../types.ts\";\nimport { OutgoingMessage } from \"../OutgoingMessage.ts\";\n\nexport class QueryAwarenessMessage extends OutgoingMessage {\n\ttype = MessageType.QueryAwareness;\n\n\tdescription = \"Queries awareness states\";\n\n\tget(args: Partial<OutgoingMessageArguments>) {\n\t\tencoding.writeVarString(this.encoder, args.documentName!);\n\t\tencoding.writeVarUint(this.encoder, this.type);\n\n\t\treturn this.encoder;\n\t}\n}\n","import * as encoding from \"lib0/encoding\";\nimport * as syncProtocol from \"y-protocols/sync\";\nimport type { OutgoingMessageArguments } from \"../types.ts\";\nimport { MessageType } from \"../types.ts\";\nimport { OutgoingMessage } from \"../OutgoingMessage.ts\";\n\nexport class SyncStepOneMessage extends OutgoingMessage {\n\ttype = MessageType.Sync;\n\n\tdescription = \"First sync step\";\n\n\tget(args: Partial<OutgoingMessageArguments>) {\n\t\tif (typeof args.document === \"undefined\") {\n\t\t\tthrow new Error(\n\t\t\t\t\"The sync step one message requires document as an argument\",\n\t\t\t);\n\t\t}\n\n\t\tencoding.writeVarString(this.encoder, args.documentName!);\n\t\tencoding.writeVarUint(this.encoder, this.type);\n\t\tsyncProtocol.writeSyncStep1(this.encoder, args.document);\n\n\t\treturn this.encoder;\n\t}\n}\n","import { writeVarString, writeVarUint } from \"lib0/encoding\";\nimport { writeUpdate } from \"y-protocols/sync\";\nimport type { OutgoingMessageArguments } from \"../types.ts\";\nimport { MessageType } from \"../types.ts\";\nimport { OutgoingMessage } from \"../OutgoingMessage.ts\";\n\nexport class UpdateMessage extends OutgoingMessage {\n\ttype = MessageType.Sync;\n\n\tdescription = \"A document update\";\n\n\tget(args: Partial<OutgoingMessageArguments>) {\n\t\twriteVarString(this.encoder, args.documentName!);\n\t\twriteVarUint(this.encoder, this.type);\n\n\t\twriteUpdate(this.encoder, args.update);\n\n\t\treturn this.encoder;\n\t}\n}\n","import { awarenessStatesToArray } from \"./awarenessStatesToArray.ts\";\nimport type { Event, MessageEvent } from \"ws\";\nimport { Awareness, removeAwarenessStates } from \"y-protocols/awareness\";\nimport * as Y from \"yjs\";\nimport EventEmitter from \"./EventEmitter.ts\";\nimport type { CompleteAbracadabraWSConfiguration } from \"./AbracadabraWS.ts\";\nimport { AbracadabraWS } from \"./AbracadabraWS.ts\";\nimport { IncomingMessage } from \"./IncomingMessage.ts\";\nimport { MessageReceiver } from \"./MessageReceiver.ts\";\nimport { MessageSender } from \"./MessageSender.ts\";\nimport { AuthenticationMessage } from \"./OutgoingMessages/AuthenticationMessage.ts\";\nimport { AwarenessMessage } from \"./OutgoingMessages/AwarenessMessage.ts\";\nimport { StatelessMessage } from \"./OutgoingMessages/StatelessMessage.ts\";\nimport { RpcClient } from \"./RpcClient.ts\";\nimport { QueryClient } from \"./QueryClient.ts\";\nimport type { QuerySpec, QuerySubscriptionHandlers, QuerySubscriptionHandle } from \"./QueryClient.ts\";\nimport { QueryAwarenessMessage } from \"./OutgoingMessages/QueryAwarenessMessage.ts\";\nimport { SyncStepOneMessage } from \"./OutgoingMessages/SyncStepOneMessage.ts\";\nimport { UpdateMessage } from \"./OutgoingMessages/UpdateMessage.ts\";\nimport type {\n AuthorizedScope,\n ConstructableOutgoingMessage,\n onAuthenticatedParameters,\n onAuthenticationFailedParameters,\n onWriteRejectedParameters,\n WriteRejectionKind,\n onAwarenessChangeParameters,\n onAwarenessUpdateParameters,\n onCloseParameters,\n onDisconnectParameters,\n onMessageParameters,\n onOpenParameters,\n onOutgoingMessageParameters,\n onReconnectedParameters,\n onServerErrorParameters,\n onStatelessParameters,\n onStatusParameters,\n onSyncedParameters,\n onUnsyncedChangesParameters,\n} from \"./types.ts\";\n// Value import (not `import type`): `WebSocketStatus` is a runtime string enum\n// read in scheduleResubscribe's connection check, not just a type annotation.\nimport { WebSocketStatus } from \"./types.ts\";\nimport { getLifecycleGate } from \"./LifecycleGate.ts\";\n\nexport type AbracadabraBaseProviderConfiguration = Required<\n Pick<CompleteAbracadabraBaseProviderConfiguration, \"name\">\n> &\n Partial<CompleteAbracadabraBaseProviderConfiguration> &\n (\n | (Required<Pick<CompleteAbracadabraWSConfiguration, \"url\">> &\n Partial<Pick<CompleteAbracadabraWSConfiguration, \"preserveTrailingSlash\">>)\n | Required<Pick<CompleteAbracadabraBaseProviderConfiguration, \"websocketProvider\">>\n );\n\n/** @deprecated Use AbracadabraBaseProviderConfiguration */\nexport type HocuspocusProviderConfiguration = AbracadabraBaseProviderConfiguration;\n\nexport interface CompleteAbracadabraBaseProviderConfiguration {\n /**\n * The identifier/name of your document\n */\n name: string;\n /**\n * The actual Y.js document\n */\n document: Y.Doc;\n\n /**\n * An Awareness instance to keep the presence state of all clients.\n *\n * You can disable sharing awareness information by passing `null`.\n * Note that having no awareness information shared across all connections will break our ping checks\n * and thus trigger reconnects. You should always have at least one Provider with enabled awareness per\n * socket connection, or ensure that the Provider receives messages before running into `AbracadabraWS.messageReconnectTimeout`.\n */\n awareness: Awareness | null;\n\n /**\n * Defer building the Awareness instance until something actually reads\n * `provider.awareness`.\n *\n * Every Awareness costs a 3 s `setInterval` for as long as it lives, plus a\n * wire frame every 15 s to renew its clock — forever, whether or not a human\n * is looking at the document. That is the right price for a document someone\n * has open, and pure waste for the dozens a background indexer or a search\n * sweep opens and closes. Measured: 10 loaded children = 11 instances = 66\n * heartbeat callbacks per 20 s idle.\n *\n * When this is set, the instance is built on first access instead of in the\n * constructor, and building it also publishes local state and queries peers,\n * so a document that later gains an editor gets symmetric presence exactly as\n * if it had been eager all along. Consumers see no difference: the public\n * `awareness` accessor always returns a usable instance.\n *\n * `AbracadabraProvider.loadChild` sets this. Top-level providers stay eager,\n * so every socket keeps at least one heartbeat and the liveness assumption in\n * `AbracadabraWS.checkConnection` is untouched.\n *\n * Ignored when an explicit `awareness` (including `null`) is supplied.\n */\n lazyAwareness?: boolean;\n\n /**\n * A token that's sent to the backend for authentication purposes.\n */\n token: string | (() => string) | (() => Promise<string>) | null;\n\n /**\n * Abracadabra websocket provider\n */\n websocketProvider: AbracadabraWS;\n\n /**\n * Force syncing the document in the defined interval.\n */\n forceSyncInterval: false | number;\n\n onAuthenticated: (data: onAuthenticatedParameters) => void;\n onAuthenticationFailed: (data: onAuthenticationFailedParameters) => void;\n /**\n * The server refused a local change. See {@link onWriteRejectedParameters} —\n * the change is still queued, not lost.\n */\n onWriteRejected: (data: onWriteRejectedParameters) => void;\n onRateLimited: () => void;\n onOpen: (data: onOpenParameters) => void;\n onReconnected: (data: onReconnectedParameters) => void;\n onConnect: () => void;\n onStatus: (data: onStatusParameters) => void;\n onMessage: (data: onMessageParameters) => void;\n onOutgoingMessage: (data: onOutgoingMessageParameters) => void;\n onSynced: (data: onSyncedParameters) => void;\n onDisconnect: (data: onDisconnectParameters) => void;\n onClose: (data: onCloseParameters) => void;\n onDestroy: () => void;\n onAwarenessUpdate: (data: onAwarenessUpdateParameters) => void;\n onAwarenessChange: (data: onAwarenessChangeParameters) => void;\n onStateless: (data: onStatelessParameters) => void;\n onServerError: (data: onServerErrorParameters) => void;\n onUnsyncedChanges: (data: onUnsyncedChangesParameters) => void;\n}\n\n/** @deprecated Use CompleteAbracadabraBaseProviderConfiguration */\nexport type CompleteHocuspocusProviderConfiguration = CompleteAbracadabraBaseProviderConfiguration;\n\nexport class AwarenessError extends Error {\n code = 1001;\n}\n\nexport class AbracadabraBaseProvider extends EventEmitter {\n public configuration: CompleteAbracadabraBaseProviderConfiguration = {\n name: \"\",\n // @ts-ignore\n document: undefined,\n // @ts-ignore\n awareness: undefined,\n token: null,\n forceSyncInterval: false,\n onAuthenticated: () => null,\n onAuthenticationFailed: () => null,\n onWriteRejected: () => null,\n onRateLimited: () => null,\n onOpen: () => null,\n onReconnected: () => null,\n onConnect: () => null,\n onMessage: () => null,\n onOutgoingMessage: () => null,\n onSynced: () => null,\n onStatus: () => null,\n onDisconnect: () => null,\n onClose: () => null,\n onDestroy: () => null,\n onAwarenessUpdate: () => null,\n onAwarenessChange: () => null,\n onStateless: () => null,\n onServerError: () => null,\n onUnsyncedChanges: () => null,\n };\n\n isSynced = false;\n\n unsyncedChanges = 0;\n\n isAuthenticated = false;\n\n /**\n * True once this provider has received at least one Authenticated frame\n * on the current socket lifetime. Used by `permissionDeniedHandler` to\n * tell apart \"the entry doc is wrong / unreachable\" (first frame is a\n * denial → config error, give up) from \"a mid-session write was denied\"\n * (server keeps the read subscription alive → don't kill the socket).\n * Reset on close.\n */\n private _hasEverAuthenticated = false;\n\n /**\n * True once this provider's socket has opened at least once. Used to fire\n * the `reconnected` event on every *subsequent* open (an actual reconnect)\n * but not the very first connect. Persists across closes — a reconnect is\n * still a reconnect even after the socket dropped.\n */\n private _hasOpenedBefore = false;\n\n /** Current WebSocket connection status. */\n get connectionStatus(): WebSocketStatus {\n return this.configuration.websocketProvider.status;\n }\n\n authorizedScope: AuthorizedScope | undefined = undefined;\n\n // @internal\n manageSocket = false;\n\n private _isAttached = false;\n\n /**\n * Bounded retry of a multiplexed child's INITIAL subscribe handshake after a\n * *transient* server denial. On a clustered server a just-created doc's row\n * (or its permission cascade) can be briefly invisible on the replica this\n * socket landed on; a dropped \"send AUTH for this document first\" ordering\n * yields the same denial. Before this, a child gave up permanently on the\n * first denial and was left with a blank body until a full reload re-ran the\n * handshake — exactly the \"open a freshly-created doc, see only the title,\n * blinking dot, never syncs until reload\" report. We instead replay the\n * subscribe a few times with backoff; the instant the server catches up the\n * child authenticates and syncs, no reconnect. Only ever fires for the\n * INITIAL subscribe (never a mid-session write denial) and is bounded, so a\n * genuinely forbidden/absent doc still settles into give-up, just later.\n */\n private static readonly MAX_RESUBSCRIBE_ATTEMPTS = 6;\n private _resubscribeAttempts = 0;\n private _resubscribeTimer: ReturnType<typeof setTimeout> | null = null;\n\n intervals: { forceSync: ReturnType<typeof setInterval> | null } = {\n forceSync: null,\n };\n\n /**\n * Lazily-constructed RPC v1 client. See `RpcClient`/`docs/rpc-v1.md`.\n * Bound to this provider's stateless transport, so calls and handlers\n * ride the doc this provider is subscribed to.\n */\n private _rpc: RpcClient | undefined;\n get rpc(): RpcClient {\n if (!this._rpc) {\n this._rpc = new RpcClient(this);\n }\n return this._rpc;\n }\n\n /**\n * Lazily-constructed V2 query subscription client. See\n * `QueryClient`. Each call to `subscribeQuery(...)` opens a\n * long-lived subscription that fires `onSnapshot` with the initial\n * result set and `onDelta` whenever the projection moves.\n */\n private _queryClient: QueryClient | undefined;\n private getQueryClient(): QueryClient {\n if (!this._queryClient) {\n this._queryClient = new QueryClient(this);\n }\n return this._queryClient;\n }\n\n /**\n * Open a live query subscription. Mirrors the v1 REST shape\n * (`POST /docs/query`) but pushes deltas as the server-side\n * projection drifts under the predicate.\n */\n subscribeQuery(\n spec: QuerySpec,\n handlers: QuerySubscriptionHandlers = {},\n ): QuerySubscriptionHandle {\n return this.getQueryClient().subscribeQuery(spec, handlers);\n }\n\n constructor(configuration: AbracadabraBaseProviderConfiguration) {\n super();\n this.setConfiguration(configuration);\n\n this.configuration.document = configuration.document ? configuration.document : new Y.Doc();\n\n if (configuration.awareness !== undefined) {\n // Explicit instance, or an explicit `null` opt-out. Either way the caller\n // has decided, and `null` must STAY null rather than being lazily filled\n // in later — `setAwarenessField` still has to throw for it.\n this.configuration.awareness = configuration.awareness;\n this._awarenessExplicitlyNull = configuration.awareness === null;\n } else if (configuration.lazyAwareness) {\n // Deferred: built by `_materializeAwareness()` on first public access.\n this.configuration.awareness = null;\n this._awarenessDeferred = true;\n } else {\n this.configuration.awareness = new Awareness(this.document);\n }\n\n if (!this._awarenessDeferred) this._initAwareness();\n\n this.on(\"open\", this.configuration.onOpen);\n this.on(\"reconnected\", this.configuration.onReconnected);\n this.on(\"message\", this.configuration.onMessage);\n this.on(\"outgoingMessage\", this.configuration.onOutgoingMessage);\n this.on(\"synced\", this.configuration.onSynced);\n this.on(\"destroy\", this.configuration.onDestroy);\n this.on(\"awarenessUpdate\", this.configuration.onAwarenessUpdate);\n this.on(\"awarenessChange\", this.configuration.onAwarenessChange);\n this.on(\"stateless\", this.configuration.onStateless);\n this.on(\"serverError\", this.configuration.onServerError);\n this.on(\"unsyncedChanges\", this.configuration.onUnsyncedChanges);\n\n this.on(\"authenticated\", this.configuration.onAuthenticated);\n this.on(\"authenticationFailed\", this.configuration.onAuthenticationFailed);\n this.on(\"writeRejected\", this.configuration.onWriteRejected);\n this.on(\"rateLimited\", this.configuration.onRateLimited);\n\n this.document.on(\"update\", this.boundDocumentUpdateHandler);\n\n this.registerEventListeners();\n\n if (\n this.configuration.forceSyncInterval &&\n typeof this.configuration.forceSyncInterval === \"number\"\n ) {\n // A periodic full re-diff against the server, for the case a long-lived\n // provider on a stable socket would otherwise never re-issue sync-step-1\n // (so a doc-tree entry written by an MCP or sibling client stays invisible).\n //\n // It is gated the same way `checkConnection` is, and for the same reason:\n // while nobody is looking there is no stale view to correct, and the cost\n // is not one timer — @abraca/nuxt sets this on the root provider AND on\n // every per-space provider, so a hidden tab with five spaces was sending\n // six full state-vector diffs every 30 s, forever, waking the radio for\n // nobody. Returning to the foreground re-diffs immediately, which is what\n // makes standing down safe: the refresh still happens at the only moment\n // it can matter to anyone.\n this.intervals.forceSync = setInterval(() => {\n if (getLifecycleGate().backgrounded) {\n this.missedForceSync = true;\n return;\n }\n this.forceSync();\n }, this.configuration.forceSyncInterval);\n\n this.unsubscribeForceSyncLifecycle = getLifecycleGate().onChange(\n (backgrounded) => {\n // Catch up only if a tick was actually skipped, so a brief alt-tab\n // does not turn into an extra full diff on every return.\n if (backgrounded || !this.missedForceSync) return;\n this.missedForceSync = false;\n this.forceSync();\n },\n );\n }\n\n if (this.manageSocket) {\n this.attach();\n }\n }\n\n /** A periodic re-sync tick that was skipped because the app was hidden. */\n missedForceSync = false;\n\n /** Detaches the force-sync lifecycle subscription, when one was installed. */\n unsubscribeForceSyncLifecycle: (() => void) | null = null;\n\n boundDocumentUpdateHandler = this.documentUpdateHandler.bind(this);\n\n boundAwarenessUpdateHandler = this.awarenessUpdateHandler.bind(this);\n\n boundPageHide = this.pageHide.bind(this);\n\n boundOnOpen = this.onOpen.bind(this);\n\n boundOnClose = this.onClose.bind(this);\n\n forwardConnect = () => this.emit(\"connect\");\n\n forwardStatus = (e: onStatusParameters) => this.emit(\"status\", e);\n\n forwardClose = (e: onCloseParameters) => this.emit(\"close\", e);\n\n forwardDisconnect = (e: onDisconnectParameters) => this.emit(\"disconnect\", e);\n\n forwardDestroy = () => this.emit(\"destroy\");\n\n forwardRateLimited = () => this.emit(\"rateLimited\");\n\n public setConfiguration(configuration: Partial<AbracadabraBaseProviderConfiguration> = {}): void {\n if (!configuration.websocketProvider) {\n this.manageSocket = true;\n this.configuration.websocketProvider = new AbracadabraWS(\n configuration as CompleteAbracadabraWSConfiguration,\n );\n }\n\n this.configuration = { ...this.configuration, ...configuration };\n }\n\n get document() {\n return this.configuration.document;\n }\n\n public get isAttached() {\n return this._isAttached;\n }\n\n /** True while an Awareness instance is owed but has not been built yet. */\n private _awarenessDeferred = false;\n\n /** True when the caller passed `awareness: null` and meant it. */\n private _awarenessExplicitlyNull = false;\n\n /**\n * The presence instance for this document, built on demand.\n *\n * Reading this materializes a deferred instance (see `lazyAwareness`), which\n * is why every consumer — TipTap's CollaborationCaret, presence UI, app code\n * — keeps working unchanged: touching `.awareness` is itself the signal that\n * this document needs presence.\n *\n * Provider INTERNALS must use `peekAwareness()` instead, or the lazy path\n * materializes everything it was meant to avoid.\n */\n get awareness(): Awareness | null {\n // An explicit `awareness: null` is a decision, not an absence: it must\n // never be lazily filled in, or `setAwarenessField` would quietly start\n // succeeding for a caller who asked for presence to be off. Checking it\n // here rather than relying on `_awarenessDeferred` being false keeps the\n // two states independent instead of implicitly coupled.\n if (this._awarenessExplicitlyNull) return null;\n if (this._awarenessDeferred) this._materializeAwareness();\n return this.configuration.awareness;\n }\n\n /**\n * The Awareness instance if one exists, without ever creating one.\n *\n * @internal Used by provider internals and `MessageReceiver`. A deferred\n * document has no local presence, so there is nothing for an inbound\n * awareness frame to be applied to and nothing to answer a peer's query with\n * — and materializing on a peer's frame would hand every idle background\n * document a heartbeat as soon as anyone else joined the space.\n */\n peekAwareness(): Awareness | null {\n return this._awarenessDeferred ? null : this.configuration.awareness;\n }\n\n /**\n * Build the deferred Awareness instance and bring it fully up to date:\n * seeded, wired, published, and caught up with the peers already present.\n */\n private _materializeAwareness(): void {\n if (!this._awarenessDeferred) return;\n this._awarenessDeferred = false;\n this.configuration.awareness = new Awareness(this.document);\n this._initAwareness();\n\n // A document that materializes mid-session must still end up with\n // symmetric presence. The server keeps no awareness cache and never\n // replays presence to a late joiner, so announce ourselves and ask the\n // room who is here — the same pair `startSync()` sends on every open.\n //\n // Deliberately NOT gated on `isAuthenticated`, exactly as `startSync` is\n // not. This is a deliberate announce, not the incidental awareness churn\n // that `awarenessUpdateHandler` drops pre-auth: frames are ordered on the\n // wire behind the token, so the server authenticates before it reads them.\n // Gating on auth here would silently skip the announce for anything that\n // materializes in the window between `sendToken()` and the auth ack, and\n // nothing would re-send it until the next local change. Materialization\n // while disconnected is covered too — `startSync` re-announces on every\n // socket open, and `send()` is a no-op while detached.\n if (this._isAttached) {\n this.send(AwarenessMessage, {\n awareness: this.configuration.awareness,\n clients: [this.document.clientID],\n documentName: this.configuration.name,\n });\n this.send(QueryAwarenessMessage, {\n documentName: this.configuration.name,\n });\n }\n }\n\n /**\n * Seed and wire an Awareness instance. Shared by the eager constructor path\n * and the lazy materialization path so the two cannot drift.\n */\n private _initAwareness(): void {\n const awareness = this.configuration.awareness;\n if (!awareness) return;\n\n // y-protocols' setLocalStateField silently no-ops when getLocalState() is\n // null. Seeding with {} once ensures the *first* setLocalStateField call\n // from any consumer (TipTap CollaborationCaret, DocumentManager, app code)\n // actually publishes — instead of vanishing without a trace. Idempotent for\n // callers that pass their own awareness instance with state already set.\n if (awareness.getLocalState() === null) {\n awareness.setLocalState({});\n }\n\n awareness.on(\"update\", () => {\n this.emit(\"awarenessUpdate\", {\n states: awarenessStatesToArray(awareness.getStates()),\n });\n });\n\n awareness.on(\"change\", () => {\n this.emit(\"awarenessChange\", {\n states: awarenessStatesToArray(awareness.getStates()),\n });\n });\n\n awareness.on(\"update\", this.boundAwarenessUpdateHandler);\n }\n\n get hasUnsyncedChanges(): boolean {\n return this.unsyncedChanges > 0;\n }\n\n private resetUnsyncedChanges() {\n // The unsynced counter tracks pending UpdateMessage acks (decremented by\n // SyncStatusMessage). The handshake itself is a connection-level concern,\n // not a doc update — reflect that by resetting to 0. The synced flag and\n // status: 'connecting' already surface in-flight sync to the UI; bumping\n // this counter to 1 would leave it stuck (SyncStep2 doesn't decrement).\n this.unsyncedChanges = 0;\n this.emit(\"unsyncedChanges\", { number: this.unsyncedChanges });\n }\n\n incrementUnsyncedChanges() {\n this.unsyncedChanges += 1;\n this.emit(\"unsyncedChanges\", { number: this.unsyncedChanges });\n }\n\n decrementUnsyncedChanges() {\n if (this.unsyncedChanges > 0) {\n this.unsyncedChanges -= 1;\n }\n\n if (this.unsyncedChanges === 0) {\n this.synced = true;\n }\n\n this.emit(\"unsyncedChanges\", { number: this.unsyncedChanges });\n }\n\n forceSync() {\n this.resetUnsyncedChanges();\n\n this.send(SyncStepOneMessage, {\n document: this.document,\n documentName: this.configuration.name,\n });\n }\n\n pageHide() {\n const awareness = this.peekAwareness();\n if (awareness) {\n removeAwarenessStates(awareness, [this.document.clientID], \"page hide\");\n }\n }\n\n registerEventListeners() {\n if (typeof window === \"undefined\" || !(\"addEventListener\" in window)) {\n return;\n }\n\n window.addEventListener(\"pagehide\", this.boundPageHide);\n }\n\n sendStateless(payload: string) {\n this.send(StatelessMessage, {\n documentName: this.configuration.name,\n payload,\n });\n }\n\n async sendToken() {\n let token: string | null;\n try {\n token = await this.getToken();\n } catch (error) {\n this.permissionDeniedHandler(`Failed to get token during sendToken(): ${error}`);\n return;\n }\n\n this.send(AuthenticationMessage, {\n token: token ?? \"\",\n documentName: this.configuration.name,\n });\n }\n\n documentUpdateHandler(update: Uint8Array, origin: any) {\n if (origin === this) {\n return;\n }\n\n // Don't push live updates over a connection that hasn't authenticated this\n // document yet. On the shared multiplexed socket, onOpen() does\n // `await sendToken()` before the doc's AUTH frame actually goes out; an edit\n // firing in that async window would race ahead of the AUTH frame and the\n // server rejects it with \"not subscribed: send AUTH for this document\n // first\". State is NOT lost: subclasses persist to the offline store before\n // calling super (and re-flush pending updates on `synced`), and the\n // post-AUTH SyncStep1/2 handshake conveys all local state regardless. So\n // skipping the live wire-send here is safe — it only closes the race.\n if (!this.isAuthenticated) {\n return;\n }\n\n this.incrementUnsyncedChanges();\n this.send(UpdateMessage, { update, documentName: this.configuration.name });\n }\n\n awarenessUpdateHandler({ added, updated, removed }: any, origin: any) {\n // Same AUTH-ordering guard as documentUpdateHandler. Awareness churn\n // (cursor / presence / focus) during the connect AUTH window must not race\n // ahead of the doc's AUTH frame. Awareness is ephemeral and re-sent in full\n // by startSync() immediately after AUTH plus on the next local change, so\n // dropping pre-auth awareness frames loses nothing.\n if (!this.isAuthenticated) {\n return;\n }\n\n const changedClients = added.concat(updated).concat(removed);\n\n this.send(AwarenessMessage, {\n awareness: this.peekAwareness(),\n clients: changedClients,\n documentName: this.configuration.name,\n });\n }\n\n /**\n * Indicates whether a first handshake with the server has been established\n *\n * Note: this does not mean all updates from the client have been persisted to the backend. For this,\n * use `hasUnsyncedChanges`.\n */\n get synced(): boolean {\n return this.isSynced;\n }\n\n set synced(state) {\n if (this.isSynced === state) {\n return;\n }\n\n this.isSynced = state;\n\n if (state) {\n // Defer the emit one microtask. Y.applyUpdate dispatches Y.Map /\n // Y.Array observer notifications via microtasks; emitting `synced`\n // synchronously would let listeners read `getArray(\"messages\")` (or\n // any sub-type populated by the just-applied state) and see length\n // 0 even though the wire delivered the full state. Deferring one\n // microtask lets the observers run first so everyone reading after\n // the synced event sees the populated state.\n queueMicrotask(() => {\n // Re-check in case `synced` flipped back to false between the\n // mutation and this microtask (e.g. a reconnect aborted sync).\n if (this.isSynced) this.emit(\"synced\", { state });\n });\n }\n }\n\n receiveStateless(payload: string) {\n try {\n const parsed = JSON.parse(payload);\n if (parsed?.type === \"error\" && parsed.source && parsed.code) {\n const { source, code, message, meta } = parsed;\n console.warn(`[Abracadabra] Server error: ${source} (${code}) — ${message}`, meta ?? \"\");\n this.emit(\"serverError\", { source, code, message: message ?? \"\", meta });\n return;\n }\n } catch {\n // not JSON — fall through to generic stateless event\n }\n this.emit(\"stateless\", { payload });\n }\n\n // not needed, but provides backward compatibility with e.g. lexical/yjs\n async connect() {\n if (this.manageSocket) {\n return this.configuration.websocketProvider.connect();\n }\n\n console.warn(\n \"AbracadabraBaseProvider::connect() is deprecated and does not do anything. Please connect/disconnect on the websocketProvider, or attach/deattach providers.\",\n );\n }\n\n disconnect() {\n if (this.manageSocket) {\n return this.configuration.websocketProvider.disconnect();\n }\n\n console.warn(\n \"AbracadabraBaseProvider::disconnect() is deprecated and does not do anything. Please connect/disconnect on the websocketProvider, or attach/deattach providers.\",\n );\n }\n\n /**\n * Force the underlying socket to drop and reconnect on the SAME Y.Doc.\n *\n * Unlike destroying and re-creating the provider, the document is never\n * replaced — so every `observe`/`observeDeep` listener attached to it (and\n * its subdocs) keeps firing once the socket comes back. This also revives a\n * socket that a permanent permission-denial gave up on (see\n * {@link permissionDeniedHandler}). Pair it with a freshly-minted token (the\n * `token` callback is re-invoked on every reconnect) when healing a drop that\n * was caused by an expired JWT.\n *\n * Every provider multiplexed onto this socket is marked unsynced so a\n * subsequent `waitForSync` actually waits for the post-reconnect handshake\n * instead of short-circuiting on the stale `isSynced` flag.\n *\n * No-op (with a warning) for a provider on a shared, externally-managed\n * socket — reconnect the owning `websocketProvider` directly in that case.\n */\n reconnect() {\n if (!this.manageSocket) {\n console.warn(\n \"AbracadabraBaseProvider::reconnect() — this provider shares an externally-managed socket; call reconnect() on the websocketProvider instead.\",\n );\n return;\n }\n\n // Reset the synced flag of every provider on this socket BEFORE recycling\n // it. `cleanupWebSocket` tears the socket down silently (no close event),\n // so the providers' own `onClose` won't run to flip `synced` — do it here.\n for (const provider of this.configuration.websocketProvider.configuration.providerMap.values()) {\n provider.synced = false;\n provider.isAuthenticated = false;\n }\n\n return this.configuration.websocketProvider.reconnect();\n }\n\n async onOpen(event: Event) {\n const isReopen = this._hasOpenedBefore;\n this._hasOpenedBefore = true;\n this.isAuthenticated = false;\n\n this.emit(\"open\", { event });\n // A subsequent open means the socket dropped and came back — let consumers\n // re-reconcile. Observers on `document` survive regardless (the doc is\n // never replaced); this is the explicit signal for catch-up work.\n if (isReopen) {\n this.emit(\"reconnected\", { event });\n }\n await this.sendToken();\n this.startSync();\n }\n\n async getToken() {\n if (typeof this.configuration.token === \"function\") {\n const token = await this.configuration.token();\n return token;\n }\n\n return this.configuration.token;\n }\n\n startSync() {\n this.resetUnsyncedChanges();\n\n this.send(SyncStepOneMessage, {\n document: this.document,\n documentName: this.configuration.name,\n });\n\n const openAwareness = this.peekAwareness();\n if (openAwareness && openAwareness.getLocalState() !== null) {\n this.send(AwarenessMessage, {\n awareness: openAwareness,\n clients: [this.document.clientID],\n documentName: this.configuration.name,\n });\n }\n\n // Pull existing peers' awareness on (re)connect. The server keeps no\n // awareness cache and never replays presence to a fresh joiner, so without\n // this a late-joining client only learns about a peer once that peer next\n // *changes* its own awareness — producing asymmetric presence (\"A sees B\n // but B can't see A\"). The server re-broadcasts this query to all peers,\n // who answer with their full state (MessageReceiver.applyQueryAwareness),\n // and those replies fan back to us. Matches stock y-websocket on-open\n // behaviour. Only meaningful when an awareness instance exists.\n if (openAwareness) {\n this.send(QueryAwarenessMessage, {\n documentName: this.configuration.name,\n });\n }\n }\n\n send(message: ConstructableOutgoingMessage, args: any) {\n if (!this._isAttached) return;\n\n const messageSender = new MessageSender(message, args);\n\n this.emit(\"outgoingMessage\", { message: messageSender.message });\n messageSender.send(this.configuration.websocketProvider);\n }\n\n onMessage(event: MessageEvent) {\n const message = new IncomingMessage(event.data);\n\n const documentName = message.readVarString();\n\n message.writeVarString(documentName);\n\n this.emit(\"message\", { event, message: new IncomingMessage(event.data) });\n\n new MessageReceiver(message).apply(this, true);\n }\n\n onClose() {\n this.isAuthenticated = false;\n this.synced = false;\n // Reset per-socket-lifetime auth flag so the next connection's\n // permissionDeniedHandler can correctly identify a fresh-connection\n // denial as a config error.\n this._hasEverAuthenticated = false;\n // The socket's own reconnect re-runs onOpen → subscribe for every doc, so\n // any in-flight initial-subscribe retry from this lifetime is moot.\n this.clearResubscribe();\n\n // update awareness (all users except local left)\n const closeAwareness = this.peekAwareness();\n if (closeAwareness) {\n removeAwarenessStates(\n closeAwareness,\n Array.from(closeAwareness.getStates().keys()).filter(\n (client) => client !== this.document.clientID,\n ),\n this,\n );\n }\n }\n\n destroy() {\n this.emit(\"destroy\");\n\n if (this._rpc) {\n // Keep the (now-destroyed) RpcClient bound to `_rpc` rather than\n // setting it back to `undefined`. The lazy getter would otherwise\n // construct a fresh client wired against a provider whose listeners\n // are gone, leaving any subsequent `rpc.call(...)` to hang forever.\n // The client's own `destroyed` flag now turns `call()` into an\n // immediate `CANCELLED` rejection — the right terminal outcome.\n this._rpc.destroy();\n }\n\n if (this.unsubscribeForceSyncLifecycle) {\n this.unsubscribeForceSyncLifecycle();\n this.unsubscribeForceSyncLifecycle = null;\n }\n\n if (this.intervals.forceSync) {\n clearInterval(this.intervals.forceSync);\n }\n\n const ownAwareness = this.peekAwareness();\n if (ownAwareness) {\n removeAwarenessStates(ownAwareness, [this.document.clientID], \"provider destroy\");\n ownAwareness.off(\"update\", this.boundAwarenessUpdateHandler);\n ownAwareness.destroy();\n }\n\n this.document.off(\"update\", this.boundDocumentUpdateHandler);\n\n this.removeAllListeners();\n\n this.detach();\n\n if (this.manageSocket) {\n this.configuration.websocketProvider.destroy();\n }\n\n if (typeof window === \"undefined\" || !(\"removeEventListener\" in window)) {\n return;\n }\n\n window.removeEventListener(\"pagehide\", this.boundPageHide);\n }\n\n detach() {\n this.configuration.websocketProvider.off(\"connect\", this.configuration.onConnect);\n this.configuration.websocketProvider.off(\"connect\", this.forwardConnect);\n\n this.configuration.websocketProvider.off(\"status\", this.forwardStatus);\n this.configuration.websocketProvider.off(\"status\", this.configuration.onStatus);\n\n this.configuration.websocketProvider.off(\"open\", this.boundOnOpen);\n this.configuration.websocketProvider.off(\"close\", this.boundOnClose);\n this.configuration.websocketProvider.off(\"close\", this.configuration.onClose);\n this.configuration.websocketProvider.off(\"close\", this.forwardClose);\n this.configuration.websocketProvider.off(\"disconnect\", this.configuration.onDisconnect);\n this.configuration.websocketProvider.off(\"disconnect\", this.forwardDisconnect);\n this.configuration.websocketProvider.off(\"destroy\", this.configuration.onDestroy);\n this.configuration.websocketProvider.off(\"destroy\", this.forwardDestroy);\n\n this.configuration.websocketProvider.off(\"rateLimited\", this.forwardRateLimited);\n\n this.configuration.websocketProvider.detach(this);\n\n this._isAttached = false;\n this.clearResubscribe();\n }\n\n attach() {\n if (this._isAttached) return;\n\n this.configuration.websocketProvider.on(\"connect\", this.configuration.onConnect);\n this.configuration.websocketProvider.on(\"connect\", this.forwardConnect);\n\n this.configuration.websocketProvider.on(\"status\", this.configuration.onStatus);\n this.configuration.websocketProvider.on(\"status\", this.forwardStatus);\n\n this.configuration.websocketProvider.on(\"open\", this.boundOnOpen);\n\n this.configuration.websocketProvider.on(\"close\", this.boundOnClose);\n this.configuration.websocketProvider.on(\"close\", this.configuration.onClose);\n this.configuration.websocketProvider.on(\"close\", this.forwardClose);\n\n this.configuration.websocketProvider.on(\"disconnect\", this.configuration.onDisconnect);\n this.configuration.websocketProvider.on(\"disconnect\", this.forwardDisconnect);\n\n this.configuration.websocketProvider.on(\"destroy\", this.configuration.onDestroy);\n this.configuration.websocketProvider.on(\"destroy\", this.forwardDestroy);\n\n this.configuration.websocketProvider.on(\"rateLimited\", this.forwardRateLimited);\n\n // Mark attached BEFORE registering with the socket: when the shared\n // socket is already connected (the loadChild case), wsp.attach()\n // synchronously invokes onOpen() → sendToken(), and send() drops frames\n // while _isAttached is false. With a crypto identity OBJECT sendToken()\n // hits no await before send(), so the AUTH frame was silently swallowed\n // and the doc never authenticated on the connection — the server then\n // (correctly) ignored every subsequent frame for it: child providers\n // never synced and their writes were dropped. (JWT auth only survived\n // by accident: `await getToken()` defers send() past attach().)\n this._isAttached = true;\n\n this.configuration.websocketProvider.attach(this);\n }\n\n permissionDeniedHandler(reason: string) {\n // A denial that arrives on a socket which has already authenticated AND\n // synced this document is not an authentication problem — it is a write\n // that was refused (see the mid-session note below). Surface it as one so\n // app code has something to listen to that is not `authenticationFailed`,\n // which on a shared socket is usually about somebody else's document.\n if (this._hasEverAuthenticated && this.isSynced) {\n this.reportWriteRejected(reason, \"permission\");\n }\n\n this.emit(\"authenticationFailed\", { reason });\n this.isAuthenticated = false;\n\n // Stop the reconnect loop on a permanent denial. Without this the WS\n // closes after every server-side rejection, AbracadabraWS schedules a\n // retry, the new connection sends the same Subscribe → server denies\n // again, ad infinitum (CPU/log/network spam, page looks \"broken\" to\n // the user). The dominant cases here:\n // * \"document not found\" — entry-doc-id pinned to something that\n // doesn't exist on this server\n // * initial \"permission denied\" — operator never granted access\n // Both are config issues; retrying won't fix them.\n //\n // BUT — once we've successfully authenticated at least once on this\n // socket, a permission_denied frame means a *mid-session* operation\n // was rejected (e.g. a write attempt on a doc the user only has read\n // on, or a Forbidden surfaced from defense-in-depth). The server\n // keeps the read subscription alive in that case (see ws.rs handling\n // of Error::Forbidden), so killing the socket would be a regression:\n // it tears down every other doc's sync just because one write was\n // denied. Skip the disconnect here and let the affected operation\n // surface its own error.\n //\n // We only stop the socket when this provider OWNS it (`manageSocket`);\n // shared sockets (e.g. multiplexed child providers) leave the parent's\n // lifecycle alone and just give up on this doc.\n if (this.manageSocket && !this._hasEverAuthenticated) {\n try {\n this.configuration.websocketProvider.disconnect();\n }\n catch { /* WS may already be torn down — best effort */ }\n }\n\n // Transient-denial recovery (see _resubscribeAttempts doc). Fires only for\n // a multiplexed child (shared socket; the root is handled above) that has\n // NOT yet completed its initial sync, and only for denials whose reason is\n // transient — \"document not found\" (a just-created doc whose row/permission\n // is briefly invisible on the replica this socket hit) or \"not subscribed\"\n // (a dropped AUTH-ordering). We deliberately do NOT key off\n // `_hasEverAuthenticated`: the server sends AUTHENTICATED *before* it runs\n // the initial sync, so a not-found denial lands after that flag is already\n // set. `!isSynced` is the true \"never got my content\" signal and also\n // excludes mid-session write denials (those docs are already synced).\n // Permanent denials (\"permission denied\"/\"write permission denied\") are\n // NOT matched, so a genuinely forbidden doc still gives up immediately.\n if (\n !this.manageSocket &&\n !this.isSynced &&\n this._isAttached &&\n this._resubscribeAttempts < AbracadabraBaseProvider.MAX_RESUBSCRIBE_ATTEMPTS &&\n AbracadabraBaseProvider.isTransientSubscribeDenial(reason)\n ) {\n this.scheduleResubscribe();\n }\n }\n\n /**\n * The most recent write the server refused, or `null` if it has never\n * refused one on this provider. Kept as state (not just an event) because\n * the common consumer question is \"is my last edit actually saved?\", which\n * an event fired before the component mounted cannot answer.\n */\n public lastWriteRejection: onWriteRejectedParameters | null = null;\n\n /** Count of refused writes over this provider's lifetime. */\n public writeRejectionCount = 0;\n\n /**\n * Record and announce a server-refused local change.\n *\n * Called from both nack paths: the permission-denied auth frame and\n * `SyncStatus(applied=0)`. Deliberately does NOT touch the unsynced counter\n * — the update stays queued so a retry can land it once the cause is fixed.\n */\n reportWriteRejected(reason: string, kind: WriteRejectionKind) {\n const data: onWriteRejectedParameters = {\n documentName: this.configuration.name,\n reason,\n kind,\n };\n this.lastWriteRejection = data;\n this.writeRejectionCount += 1;\n this.emit(\"writeRejected\", data);\n }\n\n /**\n * Whether a permission-denied reason reflects a *transient* server condition\n * a retry can clear (a freshly-created doc not yet visible on this replica, or\n * a dropped subscribe-ordering) rather than a permanent authorization failure.\n */\n private static isTransientSubscribeDenial(reason: string): boolean {\n const r = reason.toLowerCase();\n return r.includes(\"not found\") || r.includes(\"not subscribed\");\n }\n\n /**\n * Schedule one backed-off replay of the initial subscribe handshake. A single\n * timer is in flight at a time; each denial that slips past the guard above\n * arms the next attempt until {@link MAX_RESUBSCRIBE_ATTEMPTS} is reached.\n */\n private scheduleResubscribe() {\n if (this._resubscribeTimer) return;\n const attempt = this._resubscribeAttempts++;\n // 250, 500, 1000, 2000, 4000, 4000 ms — recovers within ~750ms for a\n // typical sub-second replica lag, ~11s total before final give-up.\n const delay = Math.min(4000, 250 * 2 ** attempt);\n this._resubscribeTimer = setTimeout(() => {\n this._resubscribeTimer = null;\n // Bail if anything changed under us: detached, already recovered, or the\n // socket dropped (its reconnect re-runs onOpen for every doc anyway).\n // `isSynced` — not the auth flags — is the success signal: the server\n // sends AUTHENTICATED *before* the initial-sync attempt, so a not-found\n // denial leaves isAuthenticated/_hasEverAuthenticated set yet unsynced;\n // bailing on those would (and did) skip the very retry we scheduled.\n if (\n !this._isAttached ||\n this.isSynced ||\n this.connectionStatus !== WebSocketStatus.Connected\n ) {\n return;\n }\n // Replay onOpen's subscribe: re-send AUTH (server re-runs subscribe_doc,\n // now that the doc/permission may be visible) then SyncStep1.\n void this.sendToken()\n .then(() => {\n if (this._isAttached && !this.isAuthenticated) this.startSync();\n })\n .catch(() => { /* a fresh denial re-enters permissionDeniedHandler */ });\n }, delay);\n }\n\n /** Cancel any pending resubscribe and reset the attempt budget. */\n private clearResubscribe() {\n if (this._resubscribeTimer) {\n clearTimeout(this._resubscribeTimer);\n this._resubscribeTimer = null;\n }\n this._resubscribeAttempts = 0;\n }\n\n authenticatedHandler(scope: string) {\n this.isAuthenticated = true;\n this._hasEverAuthenticated = true;\n this.authorizedScope = scope as AuthorizedScope;\n // Initial subscribe succeeded (possibly via a resubscribe retry) — stop\n // retrying and restore the budget for a future socket lifetime.\n this.clearResubscribe();\n\n this.emit(\"authenticated\", { scope });\n }\n\n setAwarenessField(key: string, value: any) {\n if (!this.awareness) {\n throw new AwarenessError(\n `Cannot set awareness field \"${key}\" to ${JSON.stringify(value)}. You have disabled Awareness for this provider by explicitly passing awareness: null in the provider configuration.`,\n );\n }\n this.awareness.setLocalStateField(key, value);\n }\n}\n\n/** @deprecated Use AbracadabraBaseProvider */\nexport const HocuspocusProvider = AbracadabraBaseProvider;\n/** @deprecated Use AbracadabraBaseProvider */\nexport type HocuspocusProvider = AbracadabraBaseProvider;\n","/**\n * IndexedDB-backed offline store for a single Abracadabra document.\n *\n * Responsibilities:\n * - Persist CRDT updates locally so they survive page refreshes / network loss.\n * - Store the last-known state vector for fast reconnect diffs.\n * - Store a permission snapshot so the UI can gate writes without a network round-trip.\n * - Queue subdoc registration events created while offline.\n * - Store a full document snapshot so the app can load content without a server connection.\n *\n * Falls back to a silent no-op when IndexedDB is unavailable (e.g. SSR / Node.js).\n *\n * Database key is scoped by server origin to prevent cross-server data contamination\n * when the same docId is used on multiple servers.\n */\n\nexport interface PendingSubdoc {\n\tchildId: string;\n\tparentId: string;\n\tcreatedAt: number;\n}\n\nconst DB_VERSION = 2;\n\nfunction idbAvailable(): boolean {\n\treturn typeof globalThis !== \"undefined\" && \"indexedDB\" in globalThis;\n}\n\nfunction openDb(storeKey: string): Promise<IDBDatabase> {\n\treturn new Promise((resolve, reject) => {\n\t\tconst req = globalThis.indexedDB.open(`abracadabra:${storeKey}`, DB_VERSION);\n\n\t\treq.onupgradeneeded = (event) => {\n\t\t\tconst db = (event.target as IDBOpenDBRequest).result;\n\n\t\t\tif (!db.objectStoreNames.contains(\"updates\")) {\n\t\t\t\tdb.createObjectStore(\"updates\", { autoIncrement: true });\n\t\t\t}\n\t\t\tif (!db.objectStoreNames.contains(\"meta\")) {\n\t\t\t\tdb.createObjectStore(\"meta\");\n\t\t\t}\n\t\t\tif (!db.objectStoreNames.contains(\"subdoc_queue\")) {\n\t\t\t\tdb.createObjectStore(\"subdoc_queue\", { keyPath: \"childId\" });\n\t\t\t}\n\t\t\t// v2: full document snapshot store\n\t\t\tif (!db.objectStoreNames.contains(\"doc_state\")) {\n\t\t\t\tdb.createObjectStore(\"doc_state\");\n\t\t\t}\n\t\t};\n\n\t\treq.onsuccess = () => resolve(req.result);\n\t\treq.onerror = () => reject(req.error);\n\t});\n}\n\nfunction txPromise<T>(\n\tstore: IDBObjectStore,\n\trequest: IDBRequest<T>,\n): Promise<T> {\n\treturn new Promise((resolve, reject) => {\n\t\trequest.onsuccess = () => resolve(request.result);\n\t\trequest.onerror = () => reject(request.error);\n\t});\n}\n\n/**\n * Resolve when the whole transaction commits.\n *\n * `txPromise` waits on a single request, which is the wrong unit once a\n * transaction carries a batch: the last `add` succeeding does not mean the\n * transaction committed, and reporting durability before commit is exactly the\n * lie the offline store must not tell.\n */\nfunction txComplete(tx: IDBTransaction): Promise<void> {\n\treturn new Promise((resolve, reject) => {\n\t\ttx.oncomplete = () => resolve();\n\t\ttx.onerror = () => reject(tx.error);\n\t\ttx.onabort = () => reject(tx.error ?? new Error(\"transaction aborted\"));\n\t});\n}\n\n/**\n * How long local edits are held before being written as one transaction.\n *\n * Yjs emits one update per keystroke, and the store used to open one IndexedDB\n * transaction for each — measured at 1.02 transactions per keystroke over 200\n * keystrokes. Coalescing trades a bounded window of durability for roughly an\n * order of magnitude fewer transactions. The window is small on purpose: these\n * edits have already gone to the server on the wire (that send is NOT batched),\n * so the exposure is an offline client that dies within the window.\n */\nconst WRITE_COALESCE_MS = 150;\n\n/** Flush early once a burst reaches this many updates, regardless of the timer. */\nconst MAX_WRITE_BATCH = 128;\n\nexport class OfflineStore {\n\tprivate storeKey: string;\n\tprivate db: IDBDatabase | null = null;\n\n\t/**\n\t * @param docId The document UUID.\n\t * @param serverOrigin Host of the server, including a non-default port\n\t * (e.g. \"abra.cou.sh\", \"localhost:3001\"). When provided\n\t * the IndexedDB database is namespaced per-server,\n\t * preventing cross-server data contamination — the port\n\t * matters because two same-host servers sharing the\n\t * default root_doc_id would otherwise collide.\n\t */\n\tconstructor(docId: string, serverOrigin?: string) {\n\t\tthis.storeKey = serverOrigin ? `${serverOrigin}/${docId}` : docId;\n\t}\n\n\tprivate dbPromise: Promise<IDBDatabase | null> | null = null;\n\n\tprivate _destroyed = false;\n\n\tprivate getDb(): Promise<IDBDatabase | null> {\n\t\tif (this._destroyed || !idbAvailable()) return Promise.resolve(null);\n\t\tif (!this.dbPromise) {\n\t\t\t// Cache the promise so concurrent callers share a single open operation.\n\t\t\tthis.dbPromise = openDb(this.storeKey).catch(() => null).then(db => {\n\t\t\t\tthis.db = db;\n\t\t\t\treturn db;\n\t\t\t});\n\t\t}\n\t\treturn this.dbPromise;\n\t}\n\n\t// ── Pending (unsynced) updates ────────────────────────────────────────────\n\n\t/** Updates buffered for the next batched write. */\n\tprivate writeBuffer: Uint8Array[] = [];\n\n\t/** Callers of `persistUpdate` awaiting the batch that carries their update. */\n\tprivate writeWaiters: Array<{\n\t\tresolve: () => void;\n\t\treject: (err: unknown) => void;\n\t}> = [];\n\n\tprivate flushTimer: ReturnType<typeof setTimeout> | null = null;\n\n\t/**\n\t * Queue a local update for persistence.\n\t *\n\t * The returned promise settles when the update has actually been committed,\n\t * not when it was queued — so `await persistUpdate(u)` still means \"on disk\",\n\t * exactly as it did when every call opened its own transaction.\n\t */\n\tpersistUpdate(update: Uint8Array): Promise<void> {\n\t\tif (this._destroyed || !idbAvailable()) return Promise.resolve();\n\n\t\tthis.writeBuffer.push(update);\n\t\tconst settled = new Promise<void>((resolve, reject) => {\n\t\t\tthis.writeWaiters.push({ resolve, reject });\n\t\t});\n\n\t\tif (this.writeBuffer.length >= MAX_WRITE_BATCH) {\n\t\t\tvoid this.flushWrites();\n\t\t} else if (this.flushTimer === null) {\n\t\t\tthis.flushTimer = setTimeout(() => {\n\t\t\t\tvoid this.flushWrites();\n\t\t\t}, WRITE_COALESCE_MS);\n\t\t}\n\n\t\treturn settled;\n\t}\n\n\t/**\n\t * Commit every buffered update as ONE transaction.\n\t *\n\t * Safe to call at any time, including with an empty buffer — every read path\n\t * calls it first so a caller can never observe a store that is missing writes\n\t * still sitting in memory.\n\t */\n\tasync flushWrites(): Promise<void> {\n\t\tif (this.flushTimer !== null) {\n\t\t\tclearTimeout(this.flushTimer);\n\t\t\tthis.flushTimer = null;\n\t\t}\n\n\t\tconst batch = this.writeBuffer;\n\t\tconst waiters = this.writeWaiters;\n\t\tthis.writeBuffer = [];\n\t\tthis.writeWaiters = [];\n\t\tif (batch.length === 0) {\n\t\t\tfor (const w of waiters) w.resolve();\n\t\t\treturn;\n\t\t}\n\n\t\ttry {\n\t\t\tconst db = await this.getDb();\n\t\t\tif (db) {\n\t\t\t\tconst tx = db.transaction(\"updates\", \"readwrite\");\n\t\t\t\tconst store = tx.objectStore(\"updates\");\n\t\t\t\tfor (const update of batch) store.add(update);\n\t\t\t\tawait txComplete(tx);\n\t\t\t}\n\t\t\tfor (const w of waiters) w.resolve();\n\t\t} catch (err) {\n\t\t\t// Tell the waiters the truth. `documentUpdateHandler` catches, so a\n\t\t\t// rejection here surfaces to anyone who asked without becoming an\n\t\t\t// unhandled rejection for anyone who did not.\n\t\t\tfor (const w of waiters) w.reject(err);\n\t\t\tthrow err;\n\t\t}\n\t}\n\n\t/**\n\t * Issue the buffered writes synchronously, without awaiting them.\n\t *\n\t * For teardown paths that cannot await: `pagehide` (the page may not survive\n\t * a microtask) and `destroy()`. IndexedDB will not close a connection until\n\t * its running transactions finish, so writes issued here still land.\n\t */\n\tflushWritesSync(): void {\n\t\tif (this.flushTimer !== null) {\n\t\t\tclearTimeout(this.flushTimer);\n\t\t\tthis.flushTimer = null;\n\t\t}\n\t\tconst batch = this.writeBuffer;\n\t\tconst waiters = this.writeWaiters;\n\t\tthis.writeBuffer = [];\n\t\tthis.writeWaiters = [];\n\t\tif (batch.length === 0) {\n\t\t\tfor (const w of waiters) w.resolve();\n\t\t\treturn;\n\t\t}\n\t\t// Only possible against an already-open connection; there is no\n\t\t// synchronous way to open one.\n\t\tconst db = this.db;\n\t\tif (db) {\n\t\t\ttry {\n\t\t\t\tconst tx = db.transaction(\"updates\", \"readwrite\");\n\t\t\t\tconst store = tx.objectStore(\"updates\");\n\t\t\t\tfor (const update of batch) store.add(update);\n\t\t\t} catch {\n\t\t\t\t// Connection closing — nothing further we can do synchronously.\n\t\t\t}\n\t\t}\n\t\tfor (const w of waiters) w.resolve();\n\t}\n\n\tasync getPendingUpdates(): Promise<Uint8Array[]> {\n\t\t// Buffered writes are pending updates too. Reading around them would let\n\t\t// `flushPendingUpdates` miss edits made in the last coalescing window and\n\t\t// leave them queued forever.\n\t\tawait this.flushWrites().catch(() => null);\n\t\tconst db = await this.getDb();\n\t\tif (!db) return [];\n\t\treturn new Promise((resolve, reject) => {\n\t\t\tconst tx = db.transaction(\"updates\", \"readonly\");\n\t\t\tconst store = tx.objectStore(\"updates\");\n\t\t\tconst req = store.getAll();\n\t\t\treq.onsuccess = () => resolve(req.result as Uint8Array[]);\n\t\t\treq.onerror = () => reject(req.error);\n\t\t});\n\t}\n\n\tasync clearPendingUpdates(): Promise<void> {\n\t\t// Drop anything still buffered, or it would be written back moments after\n\t\t// the clear and replay on the next connect.\n\t\tif (this.flushTimer !== null) {\n\t\t\tclearTimeout(this.flushTimer);\n\t\t\tthis.flushTimer = null;\n\t\t}\n\t\tthis.writeBuffer = [];\n\t\tfor (const w of this.writeWaiters) w.resolve();\n\t\tthis.writeWaiters = [];\n\n\t\tconst db = await this.getDb();\n\t\tif (!db) return;\n\t\tconst tx = db.transaction(\"updates\", \"readwrite\");\n\t\tawait txPromise(tx.objectStore(\"updates\"), tx.objectStore(\"updates\").clear());\n\t}\n\n\t// ── Full document snapshot ────────────────────────────────────────────────\n\n\t/**\n\t * Persist a full Y.js state snapshot (Y.encodeStateAsUpdate output).\n\t * Replaces any previously stored snapshot.\n\t */\n\tasync saveDocSnapshot(snapshot: Uint8Array): Promise<void> {\n\t\tconst db = await this.getDb();\n\t\tif (!db) return;\n\t\tconst tx = db.transaction(\"doc_state\", \"readwrite\");\n\t\tawait txPromise(\n\t\t\ttx.objectStore(\"doc_state\"),\n\t\t\ttx.objectStore(\"doc_state\").put(snapshot, \"snapshot\"),\n\t\t);\n\t}\n\n\t/**\n\t * Retrieve the stored full document snapshot, or null if none exists.\n\t */\n\tasync getDocSnapshot(): Promise<Uint8Array | null> {\n\t\tconst db = await this.getDb();\n\t\tif (!db) return null;\n\t\tconst tx = db.transaction(\"doc_state\", \"readonly\");\n\t\tconst result = await txPromise<Uint8Array | undefined>(\n\t\t\ttx.objectStore(\"doc_state\"),\n\t\t\ttx.objectStore(\"doc_state\").get(\"snapshot\"),\n\t\t);\n\t\treturn result ?? null;\n\t}\n\n\t// ── State vector ─────────────────────────────────────────────────────────\n\n\tasync getStateVector(): Promise<Uint8Array | null> {\n\t\tconst db = await this.getDb();\n\t\tif (!db) return null;\n\t\tconst tx = db.transaction(\"meta\", \"readonly\");\n\t\tconst result = await txPromise<Uint8Array | undefined>(\n\t\t\ttx.objectStore(\"meta\"),\n\t\t\ttx.objectStore(\"meta\").get(\"sv\"),\n\t\t);\n\t\treturn result ?? null;\n\t}\n\n\tasync saveStateVector(sv: Uint8Array): Promise<void> {\n\t\tconst db = await this.getDb();\n\t\tif (!db) return;\n\t\tconst tx = db.transaction(\"meta\", \"readwrite\");\n\t\tawait txPromise(tx.objectStore(\"meta\"), tx.objectStore(\"meta\").put(sv, \"sv\"));\n\t}\n\n\t// ── Permission snapshot ──────────────────────────────────────────────────\n\n\tasync getPermissionSnapshot(): Promise<string | null> {\n\t\tconst db = await this.getDb();\n\t\tif (!db) return null;\n\t\tconst tx = db.transaction(\"meta\", \"readonly\");\n\t\tconst result = await txPromise<string | undefined>(\n\t\t\ttx.objectStore(\"meta\"),\n\t\t\ttx.objectStore(\"meta\").get(\"role\"),\n\t\t);\n\t\treturn result ?? null;\n\t}\n\n\tasync savePermissionSnapshot(role: string): Promise<void> {\n\t\tconst db = await this.getDb();\n\t\tif (!db) return;\n\t\tconst tx = db.transaction(\"meta\", \"readwrite\");\n\t\tawait txPromise(\n\t\t\ttx.objectStore(\"meta\"),\n\t\t\ttx.objectStore(\"meta\").put(role, \"role\"),\n\t\t);\n\t}\n\n\t// ── Subdoc registration queue ─────────────────────────────────────────────\n\n\tasync queueSubdoc(entry: PendingSubdoc): Promise<void> {\n\t\tconst db = await this.getDb();\n\t\tif (!db) return;\n\t\tconst tx = db.transaction(\"subdoc_queue\", \"readwrite\");\n\t\tawait txPromise(\n\t\t\ttx.objectStore(\"subdoc_queue\"),\n\t\t\ttx.objectStore(\"subdoc_queue\").put(entry),\n\t\t);\n\t}\n\n\tasync getPendingSubdocs(): Promise<PendingSubdoc[]> {\n\t\tconst db = await this.getDb();\n\t\tif (!db) return [];\n\t\treturn new Promise((resolve, reject) => {\n\t\t\tconst tx = db.transaction(\"subdoc_queue\", \"readonly\");\n\t\t\tconst req = tx.objectStore(\"subdoc_queue\").getAll();\n\t\t\treq.onsuccess = () => resolve(req.result as PendingSubdoc[]);\n\t\t\treq.onerror = () => reject(req.error);\n\t\t});\n\t}\n\n\tasync removeSubdocFromQueue(childId: string): Promise<void> {\n\t\tconst db = await this.getDb();\n\t\tif (!db) return;\n\t\tconst tx = db.transaction(\"subdoc_queue\", \"readwrite\");\n\t\tawait txPromise(\n\t\t\ttx.objectStore(\"subdoc_queue\"),\n\t\t\ttx.objectStore(\"subdoc_queue\").delete(childId),\n\t\t);\n\t}\n\n\t// ── Generic meta accessors ────────────────────────────────────────────────\n\n\tasync getMeta(key: string): Promise<string | null> {\n\t\tconst db = await this.getDb();\n\t\tif (!db) return null;\n\t\tconst tx = db.transaction(\"meta\", \"readonly\");\n\t\tconst result = await txPromise<string | undefined>(\n\t\t\ttx.objectStore(\"meta\"),\n\t\t\ttx.objectStore(\"meta\").get(`meta:${key}`),\n\t\t);\n\t\treturn result ?? null;\n\t}\n\n\tasync setMeta(key: string, value: string): Promise<void> {\n\t\tconst db = await this.getDb();\n\t\tif (!db) return;\n\t\tconst tx = db.transaction(\"meta\", \"readwrite\");\n\t\tawait txPromise(\n\t\t\ttx.objectStore(\"meta\"),\n\t\t\ttx.objectStore(\"meta\").put(value, `meta:${key}`),\n\t\t);\n\t}\n\n\t/**\n\t * Clear all stored data (updates, snapshots, state vectors, subdoc queue).\n\t * The database itself is kept but emptied.\n\t */\n\tasync clearAll(): Promise<void> {\n\t\tconst db = await this.getDb();\n\t\tif (!db) return;\n\t\tconst storeNames = Array.from(db.objectStoreNames);\n\t\tif (storeNames.length === 0) return;\n\t\tconst tx = db.transaction(storeNames, \"readwrite\");\n\t\tawait Promise.all(\n\t\t\tstoreNames.map(\n\t\t\t\t(name) =>\n\t\t\t\t\tnew Promise<void>((resolve, reject) => {\n\t\t\t\t\t\tconst req = tx.objectStore(name).clear();\n\t\t\t\t\t\treq.onsuccess = () => resolve();\n\t\t\t\t\t\treq.onerror = () => reject(req.error);\n\t\t\t\t\t}),\n\t\t\t),\n\t\t);\n\t}\n\n\t// ── Lifecycle ─────────────────────────────────────────────────────────────\n\n\tdestroy() {\n\t\t// Land buffered writes BEFORE the destroyed flag, which makes getDb()\n\t\t// return null and would strand them. Synchronous on purpose: destroy() has\n\t\t// no async contract, and IDB holds the connection open until the\n\t\t// transaction commits.\n\t\tthis.flushWritesSync();\n\n\t\t// Set the destroyed flag first so getDb() returns null for any new operations.\n\t\tthis._destroyed = true;\n\t\tconst db = this.db;\n\t\tthis.db = null;\n\t\tthis.dbPromise = null;\n\t\t// Close the IDB connection to free the file descriptor. Deferred to the\n\t\t// next microtask so any in-flight transaction callbacks settle first.\n\t\t// IDB spec: close() waits for running transactions to finish before closing.\n\t\tif (db) {\n\t\t\tPromise.resolve().then(() => db.close());\n\t\t}\n\t}\n}\n","import { writeVarString, writeVarUint } from \"lib0/encoding\";\nimport type { AbracadabraOutgoingMessageArguments } from \"../types.ts\";\nimport { MessageType } from \"../types.ts\";\nimport { OutgoingMessage } from \"../OutgoingMessage.ts\";\n\n/**\n * Registers a new subdocument with the Abracadabra server.\n *\n * Wire format (consumed by handle_subdoc in sync.rs):\n * [ParentDocName: VarString] [MSG_SUBDOC(4): VarUint] [childDocumentName: VarString]\n *\n * The server responds with a MSG_STATELESS JSON frame:\n * { type: \"subdoc_registered\", child_id, parent_id }\n * which AbracadabraProvider intercepts in receiveStateless().\n */\nexport class SubdocMessage extends OutgoingMessage {\n\ttype = MessageType.Subdoc;\n\n\tdescription = \"SubdocRegistration\";\n\n\tget(args: Partial<AbracadabraOutgoingMessageArguments>) {\n\t\tif (!args.documentName) {\n\t\t\tthrow new Error(\"SubdocMessage requires `documentName` (parent id).\");\n\t\t}\n\t\tif (!args.childDocumentName) {\n\t\t\tthrow new Error(\"SubdocMessage requires `childDocumentName`.\");\n\t\t}\n\n\t\twriteVarString(this.encoder, args.documentName);\n\t\twriteVarUint(this.encoder, this.type);\n\t\twriteVarString(this.encoder, args.childDocumentName);\n\n\t\treturn this.encoder;\n\t}\n}\n","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\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});\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\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","/**\n * Detect that a server's database has been REPLACED, and drop this browser's\n * caches for it before anything re-pushes them.\n *\n * ## The bug\n *\n * Deleting a backend's database does not give you a clean server. Every browser\n * that was connected still holds that space's CRDT state in IndexedDB, and on\n * reconnect it re-pushes the old tree into the fresh one. A seeder then adds its\n * own on top and you get every page twice — `/about` AND `/about-1`. Repeat the\n * cycle and it MULTIPLIES: `-2`, `-3`, `-4`.\n *\n * This is inherent to a CRDT and cannot be fixed downstream. A deleted database\n * is not a tombstone; it is a peer that lost its memory, and the client is the\n * one holding the newer state. No idempotency guard can see it — by the time one\n * runs, the re-pushed tree looks exactly like real content.\n *\n * It is not a development-only annoyance. The expensive case is a production\n * restore from backup, where the peers re-pushing stale trees are visitors who\n * will never read a release note.\n *\n * ## Why the server can be believed\n *\n * The server mints a `server_id` and persists it beside its database. It\n * survives restarts and changes when, and only when, that database is replaced.\n * So it states outright what a CRDT cannot work out for itself: *the peer you\n * are syncing with is not the one you have been talking to.*\n *\n * ## What gets dropped\n *\n * Everything this SDK scopes to a server, which is more than the document\n * caches:\n *\n * | store | written by |\n * |---|---|\n * | `abracadabra:<host>/<docId>` | {@link OfflineStore} |\n * | `abracadabra:meta-cache:<host>` | `DocumentCache` |\n * | `abracadabra:files:<host>` | `FileBlobStore` |\n * | `abracadabra:bgsync:<host>` | `BackgroundSyncPersistence` |\n * | `abracadabra:search:<host>` | `SearchIndex` |\n *\n * One ANCHORED rule covers all five shapes, so nothing here has to stay in step\n * with how each store builds its key. Anchored rather than a substring test on\n * purpose — see {@link isServerScopedStore}, where the naive version would have\n * cleared a different server's caches.\n *\n * `abracadabra:identity` is deliberately NOT dropped. It is this browser's\n * keypair across every server it talks to; clearing it would sign the user out\n * of all of them because one of them was reinstalled.\n */\n\n/** Where the last-seen id for a host is remembered. */\nconst STORAGE_PREFIX = \"abracadabra:server-id:\";\n\n/**\n * Stores that belong to no particular server and must survive a reset.\n *\n * `abracadabra:identity` is this browser's keypair for EVERY server it talks to,\n * so dropping it because one server was reinstalled would sign the user out of\n * all of them. Listed explicitly rather than relying on the anchored match, so\n * that a future store named after a host cannot take it by accident.\n */\nconst GLOBAL_STORES = new Set([\"abracadabra:identity\", \"abracadabra:softkey\"]);\n\nexport interface ServerResetOutcome {\n\t/** The id previously seen for this host, if any. */\n\tpreviousServerId: string | null;\n\t/** The id the server reports now. */\n\tserverId: string;\n\t/** Databases deleted because they belonged to the replaced server. */\n\tcleared: string[];\n\t/**\n\t * Databases whose deletion was BLOCKED by an open connection.\n\t *\n\t * This is a failure, not a warning to swallow: the stale state is still in\n\t * the tab and will be re-pushed. It happens when a provider opened the store\n\t * before this ran, which means the guard was called too late. Callers should\n\t * surface it rather than assume a clean result.\n\t */\n\tblocked: string[];\n}\n\nfunction storageAvailable(): boolean {\n\ttry {\n\t\treturn (\n\t\t\ttypeof globalThis !== \"undefined\" &&\n\t\t\t\"localStorage\" in globalThis &&\n\t\t\t\"indexedDB\" in globalThis\n\t\t);\n\t} catch {\n\t\treturn false;\n\t}\n}\n\n/**\n * Does this database belong to the given server?\n *\n * The match is ANCHORED, and it has to be. A plain `name.includes(host)` looks\n * right and is wrong in a way that destroys data: `other.example.com:3011`\n * contains `example.com:3011`, so clearing one server's caches would delete a\n * DIFFERENT server's — the exact \"too broad\" failure this guard exists to avoid.\n * A unit test covers that pair.\n *\n * Three anchored shapes are needed, because the stores are NOT consistently\n * scoped and pretending otherwise silently misses some:\n *\n * - `<host>/…` — {@link OfflineStore}, keyed `<host>/<docId>`\n * - `…:<host>` — a namespaced store handed a bare host\n * - `…://<host>` — a namespaced store handed a full URL. Real, not hypothetical:\n * `@abraca/nuxt` passes `serverUrl` to `FileBlobStore`, so the database is\n * named `abracadabra:files:http://example.com:3011`. Measured in a live\n * browser; a rule written only for the first two shapes left it behind, which\n * is a whole file cache surviving a wipe.\n */\nexport function isServerScopedStore(name: string, host: string): boolean {\n\tif (!name.startsWith(\"abracadabra:\")) return false;\n\tif (GLOBAL_STORES.has(name)) return false;\n\tconst rest = name.slice(\"abracadabra:\".length);\n\treturn (\n\t\trest === host ||\n\t\trest.startsWith(`${host}/`) ||\n\t\trest.endsWith(`:${host}`) ||\n\t\trest.endsWith(`://${host}`)\n\t);\n}\n\n/**\n * Compare the server's identity against the one this browser last saw, and drop\n * every cache belonging to it if the database has been replaced.\n *\n * **Call this before opening any provider.** Once a provider holds an IndexedDB\n * handle, `deleteDatabase` blocks instead of deleting and the stale tree is\n * already queued for re-push — the deletion completes later, having achieved\n * nothing. Any store in that position comes back in `blocked`.\n *\n * Conservative by design:\n *\n * - the FIRST time a host is seen, the id is recorded and nothing is deleted —\n * a new visitor must not have caches cleared for having no history;\n * - a browser with no `indexedDB`/`localStorage` is a no-op;\n * - it never throws. Failing to tidy a cache must not stop an app from starting.\n *\n * @param host The server's `host` (`example.com:3011`) — the same value\n * providers scope their stores by. Not the full origin: the\n * scheme is not part of a server's cache identity here.\n * @param serverId `server_id` from `GET /info`.\n */\nexport async function dropCachesIfServerReplaced(\n\thost: string,\n\tserverId: string,\n): Promise<ServerResetOutcome | null> {\n\tif (!storageAvailable() || !host || !serverId) return null;\n\n\tconst key = STORAGE_PREFIX + host;\n\tlet previousServerId: string | null = null;\n\ttry {\n\t\tpreviousServerId = globalThis.localStorage.getItem(key);\n\t} catch {\n\t\treturn null;\n\t}\n\n\t// First sighting, or the same server we have always been talking to.\n\tif (previousServerId === null) {\n\t\ttry {\n\t\t\tglobalThis.localStorage.setItem(key, serverId);\n\t\t} catch {\n\t\t\t/* private mode, quota — not worth failing over */\n\t\t}\n\t\treturn null;\n\t}\n\tif (previousServerId === serverId) return null;\n\n\tconst cleared: string[] = [];\n\tconst blocked: string[] = [];\n\ttry {\n\t\tconst databases = (await globalThis.indexedDB.databases?.()) ?? [];\n\t\tconst doomed = databases\n\t\t\t.map((d) => d.name)\n\t\t\t.filter((n): n is string => !!n && isServerScopedStore(n, host));\n\n\t\tawait Promise.all(\n\t\t\tdoomed.map(\n\t\t\t\t(name) =>\n\t\t\t\t\tnew Promise<void>((resolve) => {\n\t\t\t\t\t\tconst request = globalThis.indexedDB.deleteDatabase(name);\n\t\t\t\t\t\trequest.onsuccess = () => {\n\t\t\t\t\t\t\tcleared.push(name);\n\t\t\t\t\t\t\tresolve();\n\t\t\t\t\t\t};\n\t\t\t\t\t\trequest.onerror = () => resolve();\n\t\t\t\t\t\t// Still open somewhere. The delete stays pending and the stale\n\t\t\t\t\t\t// state is still live in this tab — report it, do not hang the\n\t\t\t\t\t\t// page waiting for a handle we do not own.\n\t\t\t\t\t\trequest.onblocked = () => {\n\t\t\t\t\t\t\tblocked.push(name);\n\t\t\t\t\t\t\tresolve();\n\t\t\t\t\t\t};\n\t\t\t\t\t}),\n\t\t\t),\n\t\t);\n\t} catch {\n\t\t/* enumeration unsupported or denied — nothing safely deletable */\n\t}\n\n\ttry {\n\t\tglobalThis.localStorage.setItem(key, serverId);\n\t} catch {\n\t\t/* see above */\n\t}\n\n\treturn { previousServerId, serverId, cleared, blocked };\n}\n\n/** Forget what we know about a host, so the next check treats it as new. */\nexport function forgetServerIdentity(host: string): void {\n\tif (!storageAvailable() || !host) return;\n\ttry {\n\t\tglobalThis.localStorage.removeItem(STORAGE_PREFIX + host);\n\t} catch {\n\t\t/* nothing to do */\n\t}\n}\n","import { retry } from \"@lifeomic/attempt\";\nimport EventEmitter from \"../EventEmitter.ts\";\nimport type {\n\tPeerInfo,\n\tSignalingIncoming,\n\tSignalingOutgoing,\n} from \"./types.ts\";\n\nexport interface SignalingSocketConfiguration {\n\t/** WebSocket URL for the signaling endpoint. */\n\turl: string;\n\n\t/** JWT token or async token factory for auth. */\n\ttoken: string | (() => string) | (() => Promise<string>);\n\n\t/** Auto-connect on construction. Default: true. */\n\tautoConnect?: boolean;\n\n\t/** WebSocket polyfill (e.g. for Node.js). */\n\tWebSocketPolyfill?: any;\n\n\t/** Retry delay in ms. Default: 1000. */\n\tdelay?: number;\n\t/** Retry factor. Default: 2. */\n\tfactor?: number;\n\t/** Min retry delay. Default: 1000. */\n\tminDelay?: number;\n\t/** Max retry delay. Default: 30000. */\n\tmaxDelay?: number;\n\t/** Randomize delay. Default: true. */\n\tjitter?: boolean;\n\t/** Max retry attempts (0 = unlimited). Default: 0. */\n\tmaxAttempts?: number;\n}\n\nexport class SignalingSocket extends EventEmitter {\n\tprivate ws: WebSocket | null = null;\n\tprivate wsHandlers: Record<string, (e: any) => void> = {};\n\tprivate shouldConnect = true;\n\tprivate cancelRetry?: () => void;\n\tprivate connectionAttempt: {\n\t\tresolve: (v?: any) => void;\n\t\treject: (r?: any) => void;\n\t} | null = null;\n\n\tprivate readonly config: Required<\n\t\tPick<\n\t\t\tSignalingSocketConfiguration,\n\t\t\t| \"url\"\n\t\t\t| \"token\"\n\t\t\t| \"delay\"\n\t\t\t| \"factor\"\n\t\t\t| \"minDelay\"\n\t\t\t| \"maxDelay\"\n\t\t\t| \"jitter\"\n\t\t\t| \"maxAttempts\"\n\t\t>\n\t> & { WebSocketPolyfill: any };\n\n\tpublic localPeerId: string | null = null;\n\tpublic isConnected = false;\n\n\tconstructor(configuration: SignalingSocketConfiguration) {\n\t\tsuper();\n\n\t\tthis.config = {\n\t\t\turl: configuration.url,\n\t\t\ttoken: configuration.token,\n\t\t\tdelay: configuration.delay ?? 1000,\n\t\t\tfactor: configuration.factor ?? 2,\n\t\t\tminDelay: configuration.minDelay ?? 1000,\n\t\t\tmaxDelay: configuration.maxDelay ?? 30000,\n\t\t\tjitter: configuration.jitter ?? true,\n\t\t\tmaxAttempts: configuration.maxAttempts ?? 0,\n\t\t\tWebSocketPolyfill: configuration.WebSocketPolyfill ?? WebSocket,\n\t\t};\n\n\t\tif (configuration.autoConnect !== false) {\n\t\t\tthis.connect();\n\t\t}\n\t}\n\n\tprivate async getToken(): Promise<string> {\n\t\tif (typeof this.config.token === \"function\") {\n\t\t\treturn await this.config.token();\n\t\t}\n\t\treturn this.config.token;\n\t}\n\n\tprivate _connectPromise: Promise<void> | null = null;\n\n\tasync connect(): Promise<void> {\n\t\tif (this.isConnected) return;\n\t\tif (this._connectPromise) return this._connectPromise;\n\n\t\tthis._connectPromise = this._doConnect();\n\t\ttry {\n\t\t\tawait this._connectPromise;\n\t\t} finally {\n\t\t\tthis._connectPromise = null;\n\t\t}\n\t}\n\n\tprivate async _doConnect(): Promise<void> {\n\t\tif (this.cancelRetry) {\n\t\t\tthis.cancelRetry();\n\t\t\tthis.cancelRetry = undefined;\n\t\t}\n\n\t\tthis.shouldConnect = true;\n\n\t\tlet cancelAttempt = false;\n\n\t\tconst retryPromise = retry(\n\t\t\t() => this.createConnection(),\n\t\t\t{\n\t\t\t\tdelay: this.config.delay,\n\t\t\t\tinitialDelay: 0,\n\t\t\t\tfactor: this.config.factor,\n\t\t\t\tmaxAttempts: this.config.maxAttempts,\n\t\t\t\tminDelay: this.config.minDelay,\n\t\t\t\tmaxDelay: this.config.maxDelay,\n\t\t\t\tjitter: this.config.jitter,\n\t\t\t\ttimeout: 0,\n\t\t\t\tbeforeAttempt: (context) => {\n\t\t\t\t\tif (!this.shouldConnect || cancelAttempt) {\n\t\t\t\t\t\tcontext.abort();\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t},\n\t\t).catch((error: any) => {\n\t\t\tif (error && error.code !== \"ATTEMPT_ABORTED\") {\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t});\n\n\t\tthis.cancelRetry = () => {\n\t\t\tcancelAttempt = true;\n\t\t};\n\n\t\treturn retryPromise;\n\t}\n\n\tprivate async createConnection(): Promise<void> {\n\t\tthis.cleanup();\n\n\t\tconst token = await this.getToken();\n\t\tconst separator = this.config.url.includes(\"?\") ? \"&\" : \"?\";\n\t\tconst url = `${this.config.url}${separator}token=${encodeURIComponent(token)}`;\n\n\t\tconst ws = new this.config.WebSocketPolyfill(url);\n\n\t\treturn new Promise((resolve, reject) => {\n\t\t\tconst onOpen = () => {\n\t\t\t\tthis.isConnected = true;\n\t\t\t\t// Server auto-sends Welcome on join; we send Join to register\n\t\t\t\tthis.sendRaw({ type: \"join\" });\n\t\t\t};\n\n\t\t\t// eslint-disable-next-line @typescript-eslint/no-unsafe-function-type\n\t\t\tconst onMessage = (event: MessageEvent | { data: string }) => {\n\t\t\t\tconst data =\n\t\t\t\t\ttypeof event === \"string\"\n\t\t\t\t\t\t? event\n\t\t\t\t\t\t: typeof (event as MessageEvent).data === \"string\"\n\t\t\t\t\t\t\t? (event as MessageEvent).data\n\t\t\t\t\t\t\t: null;\n\t\t\t\tif (!data) return;\n\n\t\t\t\tlet msg: SignalingOutgoing;\n\t\t\t\ttry {\n\t\t\t\t\tmsg = JSON.parse(data);\n\t\t\t\t} catch {\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tthis.handleMessage(msg, resolve);\n\t\t\t};\n\n\t\t\tconst onClose = (event: CloseEvent | { code?: number }) => {\n\t\t\t\tconst wasConnected = this.isConnected;\n\t\t\t\tthis.isConnected = false;\n\t\t\t\tthis.localPeerId = null;\n\n\t\t\t\tif (this.connectionAttempt) {\n\t\t\t\t\tthis.connectionAttempt = null;\n\t\t\t\t\treject(\n\t\t\t\t\t\tnew Error(`Signaling WebSocket closed: ${(event as CloseEvent)?.code}`),\n\t\t\t\t\t);\n\t\t\t\t}\n\n\t\t\t\tthis.emit(\"disconnected\");\n\n\t\t\t\tif (!wasConnected) return;\n\n\t\t\t\t// Auto-reconnect if desired\n\t\t\t\tif (this.shouldConnect && !this.cancelRetry) {\n\t\t\t\t\tsetTimeout(() => this.connect(), this.config.delay);\n\t\t\t\t}\n\t\t\t};\n\n\t\t\tconst onError = (err: Event) => {\n\t\t\t\tif (this.connectionAttempt) {\n\t\t\t\t\tthis.connectionAttempt = null;\n\t\t\t\t\treject(err);\n\t\t\t\t}\n\t\t\t};\n\n\t\t\tthis.wsHandlers = {\n\t\t\t\topen: onOpen,\n\t\t\t\tmessage: onMessage,\n\t\t\t\tclose: onClose,\n\t\t\t\terror: onError,\n\t\t\t};\n\n\t\t\tfor (const [name, handler] of Object.entries(this.wsHandlers)) {\n\t\t\t\tws.addEventListener(name, handler);\n\t\t\t}\n\n\t\t\tthis.ws = ws;\n\t\t\tthis.connectionAttempt = { resolve, reject };\n\t\t});\n\t}\n\n\tprivate handleMessage(msg: SignalingOutgoing, resolveConnection?: (v?: any) => void): void {\n\t\tswitch (msg.type) {\n\t\t\tcase \"welcome\":\n\t\t\t\tthis.localPeerId = msg.peer_id;\n\t\t\t\tif (this.connectionAttempt) {\n\t\t\t\t\tthis.connectionAttempt = null;\n\t\t\t\t\tresolveConnection?.();\n\t\t\t\t}\n\t\t\t\tthis.emit(\"welcome\", {\n\t\t\t\t\tpeerId: msg.peer_id,\n\t\t\t\t\tpeers: msg.peers,\n\t\t\t\t});\n\t\t\t\tbreak;\n\n\t\t\tcase \"joined\":\n\t\t\t\tthis.emit(\"joined\", {\n\t\t\t\t\tpeer_id: msg.peer_id,\n\t\t\t\t\tuser_id: msg.user_id,\n\t\t\t\t\tmuted: msg.muted,\n\t\t\t\t\tvideo: msg.video,\n\t\t\t\t\tscreen: msg.screen,\n\t\t\t\t\tname: msg.name,\n\t\t\t\t\tcolor: msg.color,\n\t\t\t\t} satisfies PeerInfo);\n\t\t\t\tbreak;\n\n\t\t\tcase \"left\":\n\t\t\t\tthis.emit(\"left\", { peerId: msg.peer_id });\n\t\t\t\tbreak;\n\n\t\t\tcase \"offer\":\n\t\t\t\tthis.emit(\"offer\", { from: msg.from, sdp: msg.sdp });\n\t\t\t\tbreak;\n\n\t\t\tcase \"answer\":\n\t\t\t\tthis.emit(\"answer\", { from: msg.from, sdp: msg.sdp });\n\t\t\t\tbreak;\n\n\t\t\tcase \"ice\":\n\t\t\t\tthis.emit(\"ice\", { from: msg.from, candidate: msg.candidate });\n\t\t\t\tbreak;\n\n\t\t\tcase \"mute\":\n\t\t\t\tthis.emit(\"mute\", {\n\t\t\t\t\tpeerId: msg.peer_id,\n\t\t\t\t\tmuted: msg.muted,\n\t\t\t\t});\n\t\t\t\tbreak;\n\n\t\t\tcase \"media-state\":\n\t\t\t\tthis.emit(\"media-state\", {\n\t\t\t\t\tpeerId: msg.peer_id,\n\t\t\t\t\tvideo: msg.video,\n\t\t\t\t\tscreen: msg.screen,\n\t\t\t\t});\n\t\t\t\tbreak;\n\n\t\t\tcase \"profile\":\n\t\t\t\tthis.emit(\"profile\", {\n\t\t\t\t\tpeerId: msg.peer_id,\n\t\t\t\t\tname: msg.name,\n\t\t\t\t\tcolor: msg.color,\n\t\t\t\t});\n\t\t\t\tbreak;\n\n\t\t\tcase \"ping\":\n\t\t\t\tthis.sendRaw({ type: \"pong\" });\n\t\t\t\tbreak;\n\n\t\t\tcase \"error\":\n\t\t\t\tthis.emit(\"error\", {\n\t\t\t\t\tcode: msg.code,\n\t\t\t\t\tmessage: msg.message,\n\t\t\t\t});\n\t\t\t\tbreak;\n\t\t}\n\t}\n\n\tprivate sendRaw(msg: SignalingIncoming): void {\n\t\tif (this.ws?.readyState === 1 /* OPEN */) {\n\t\t\tthis.ws.send(JSON.stringify(msg));\n\t\t}\n\t}\n\n\t// ── Public send methods ─────────────────────────────────────────────────\n\n\tsendOffer(to: string, sdp: string): void {\n\t\tthis.sendRaw({ type: \"offer\", to, sdp });\n\t}\n\n\tsendAnswer(to: string, sdp: string): void {\n\t\tthis.sendRaw({ type: \"answer\", to, sdp });\n\t}\n\n\tsendIce(to: string, candidate: string): void {\n\t\tthis.sendRaw({ type: \"ice\", to, candidate });\n\t}\n\n\tsendMute(muted: boolean): void {\n\t\tthis.sendRaw({ type: \"mute\", muted });\n\t}\n\n\tsendMediaState(video: boolean, screen: boolean): void {\n\t\tthis.sendRaw({ type: \"media-state\", video, screen });\n\t}\n\n\tsendProfile(name: string, color: string): void {\n\t\tthis.sendRaw({ type: \"profile\", name, color });\n\t}\n\n\tsendLeave(): void {\n\t\tthis.sendRaw({ type: \"leave\" });\n\t}\n\n\t// ── Lifecycle ───────────────────────────────────────────────────────────\n\n\tdisconnect(): void {\n\t\tthis.shouldConnect = false;\n\t\tthis.sendLeave();\n\n\t\tif (this.cancelRetry) {\n\t\t\tthis.cancelRetry();\n\t\t\tthis.cancelRetry = undefined;\n\t\t}\n\n\t\tthis.cleanup();\n\t}\n\n\tdestroy(): void {\n\t\tthis.disconnect();\n\t\tthis.removeAllListeners();\n\t}\n\n\tprivate cleanup(): void {\n\t\tif (!this.ws) return;\n\n\t\tfor (const [name, handler] of Object.entries(this.wsHandlers)) {\n\t\t\tthis.ws.removeEventListener(name, handler);\n\t\t}\n\t\tthis.wsHandlers = {};\n\n\t\ttry {\n\t\t\tif (this.ws.readyState !== 3 /* CLOSED */) {\n\t\t\t\tthis.ws.close();\n\t\t\t}\n\t\t} catch {\n\t\t\t// Ignore close errors\n\t\t}\n\n\t\tthis.ws = null;\n\t\tthis.isConnected = false;\n\t\tthis.localPeerId = null;\n\t}\n}\n","// ── Signaling Wire Protocol ─────────────────────────────────────────────────\n// Mirrors the Rust server's Incoming/Outgoing enums in signaling.rs exactly.\n// All messages are JSON text frames with a \"type\" discriminator.\n\nexport type SignalingIncoming =\n\t| { type: \"join\" }\n\t| { type: \"leave\" }\n\t| { type: \"offer\"; to: string; sdp: string }\n\t| { type: \"answer\"; to: string; sdp: string }\n\t| { type: \"ice\"; to: string; candidate: string }\n\t| { type: \"mute\"; muted: boolean }\n\t| { type: \"media-state\"; video: boolean; screen: boolean }\n\t| { type: \"profile\"; name: string; color: string }\n\t| { type: \"pong\" };\n\nexport type SignalingOutgoing =\n\t| { type: \"welcome\"; peer_id: string; peers: PeerInfo[] }\n\t| {\n\t\t\ttype: \"joined\";\n\t\t\tpeer_id: string;\n\t\t\tuser_id: string;\n\t\t\tmuted: boolean;\n\t\t\tvideo: boolean;\n\t\t\tscreen: boolean;\n\t\t\tname: string | null;\n\t\t\tcolor: string | null;\n\t }\n\t| { type: \"left\"; peer_id: string }\n\t| { type: \"offer\"; from: string; sdp: string }\n\t| { type: \"answer\"; from: string; sdp: string }\n\t| { type: \"ice\"; from: string; candidate: string }\n\t| { type: \"mute\"; peer_id: string; muted: boolean }\n\t| {\n\t\t\ttype: \"media-state\";\n\t\t\tpeer_id: string;\n\t\t\tvideo: boolean;\n\t\t\tscreen: boolean;\n\t }\n\t| { type: \"profile\"; peer_id: string; name: string; color: string }\n\t| { type: \"ping\" }\n\t| { type: \"error\"; code: string; message: string };\n\n// ── Peer State ──────────────────────────────────────────────────────────────\n\nexport interface PeerInfo {\n\tpeer_id: string;\n\tuser_id: string;\n\tmuted: boolean;\n\tvideo: boolean;\n\tscreen: boolean;\n\tname: string | null;\n\tcolor: string | null;\n}\n\nexport interface PeerState extends PeerInfo {\n\tconnectionState: RTCPeerConnectionState | \"new\";\n}\n\n// ── File Transfer ───────────────────────────────────────────────────────────\n\nexport interface FileTransferMeta {\n\ttransferId: string;\n\tfilename: string;\n\tmimeType: string;\n\ttotalSize: number;\n\tchunkSize: number;\n\ttotalChunks: number;\n}\n\nexport type FileTransferStatus =\n\t| \"pending\"\n\t| \"sending\"\n\t| \"receiving\"\n\t| \"complete\"\n\t| \"cancelled\"\n\t| \"error\";\n\n/** Data channel file transfer message type discriminators (first byte). */\nexport const FILE_MSG = {\n\tSTART: 0x01,\n\tCHUNK: 0x02,\n\tCOMPLETE: 0x03,\n\tCANCEL: 0x04,\n} as const;\n\n/** Data channel Y.js message type discriminators (first byte). */\nexport const YJS_MSG = {\n\tSYNC: 0x00,\n\tUPDATE: 0x01,\n} as const;\n\n// ── Data Channel Names ──────────────────────────────────────────────────────\n\nexport const CHANNEL_NAMES = {\n\tYJS_SYNC: \"yjs-sync\",\n\tAWARENESS: \"awareness\",\n\tFILE_TRANSFER: \"file-transfer\",\n\tCUSTOM: \"custom\",\n} as const;\n\n// ── E2EE ────────────────────────────────────────────────────────────────────\n\nexport type { E2EEIdentity } from \"./E2EEChannel.ts\";\n\n// ── Configuration ───────────────────────────────────────────────────────────\n\nexport interface AbracadabraWebRTCConfiguration {\n\t/** Document ID for the signaling room. */\n\tdocId: string;\n\n\t/** Server base URL (http/https). Signaling URL derived automatically. */\n\turl: string;\n\n\t/**\n\t * Override the signaling WebSocket URL. When set, signaling connects to\n\t * this server instead of deriving from `url`. Useful for local spaces that\n\t * piggyback a remote server's signaling endpoint.\n\t */\n\tsignalingUrl?: string;\n\n\t/** JWT token or async token factory. */\n\ttoken: string | (() => string) | (() => Promise<string>);\n\n\t/** Optional Y.Doc to sync over data channels (hybrid mode). */\n\tdocument?: InstanceType<typeof import(\"yjs\").Doc> | null;\n\n\t/** Optional Awareness instance for presence sync over data channels. */\n\tawareness?: InstanceType<\n\t\ttypeof import(\"y-protocols/awareness\").Awareness\n\t> | null;\n\n\t/** ICE server configuration. Defaults to Google STUN. */\n\ticeServers?: RTCIceServer[];\n\n\t/** Display name for this peer. */\n\tdisplayName?: string;\n\n\t/** Color identifier for this peer. */\n\tcolor?: string;\n\n\t/** Enable Y.js document sync over data channels. Default: true when document is provided. */\n\tenableDocSync?: boolean;\n\n\t/** Enable awareness sync over data channels. Default: true when awareness is provided. */\n\tenableAwarenessSync?: boolean;\n\n\t/** Enable file transfer channel. Default: false. */\n\tenableFileTransfer?: boolean;\n\n\t/** Max file chunk size in bytes. Default: 16384 (16KB). */\n\tfileChunkSize?: number;\n\n\t/** Auto-connect on construction. Default: true. */\n\tautoConnect?: boolean;\n\n\t/**\n\t * E2EE identity for application-level encryption on data channels.\n\t * When provided, all data channel messages (except key-exchange) are\n\t * encrypted with AES-256-GCM using X25519 ECDH-derived session keys.\n\t */\n\te2ee?: import(\"./E2EEChannel.ts\").E2EEIdentity | (() => Promise<import(\"./E2EEChannel.ts\").E2EEIdentity>);\n\n\t/** WebSocket polyfill for signaling (e.g. for Node.js). */\n\tWebSocketPolyfill?: any;\n}\n\nexport const DEFAULT_ICE_SERVERS: RTCIceServer[] = [\n\t{ urls: \"stun:stun.l.google.com:19302\" },\n];\n\nexport const DEFAULT_FILE_CHUNK_SIZE = 16384; // 16KB\n\n/** UUID v4 transfer ID length when encoded as raw bytes. */\nexport const TRANSFER_ID_BYTES = 16;\n\n/** SHA-256 hash length in bytes. */\nexport const SHA256_BYTES = 32;\n","import EventEmitter from \"../EventEmitter.ts\";\nimport type { E2EEChannel } from \"./E2EEChannel.ts\";\nimport { CHANNEL_NAMES } from \"./types.ts\";\n\n/** Name of the data channel used for E2EE key exchange. */\nexport const KEY_EXCHANGE_CHANNEL = \"key-exchange\";\n\nexport class DataChannelRouter extends EventEmitter {\n\tprivate channels = new Map<string, RTCDataChannel>();\n\tprivate encryptor: E2EEChannel | null = null;\n\t/** Channels excluded from encryption (key-exchange itself, awareness). */\n\tprivate plaintextChannels = new Set<string>([KEY_EXCHANGE_CHANNEL]);\n\n\tconstructor(private connection: RTCPeerConnection) {\n\t\tsuper();\n\n\t\t// Accept incoming data channels from the remote peer.\n\t\tthis.connection.ondatachannel = (event) => {\n\t\t\tthis.registerChannel(event.channel);\n\t\t};\n\t}\n\n\t/** Attach an E2EE encryptor. All channels (except key-exchange) will be encrypted. */\n\tsetEncryptor(encryptor: E2EEChannel): void {\n\t\tthis.encryptor = encryptor;\n\t}\n\n\t/** Create a named data channel (initiator side). */\n\tcreateChannel(\n\t\tname: string,\n\t\toptions?: RTCDataChannelInit,\n\t): RTCDataChannel {\n\t\tconst channel = this.connection.createDataChannel(name, options);\n\t\tthis.registerChannel(channel);\n\t\treturn channel;\n\t}\n\n\t/** Create the standard set of channels for Abracadabra WebRTC. */\n\tcreateDefaultChannels(opts: {\n\t\tenableDocSync: boolean;\n\t\tenableAwareness: boolean;\n\t\tenableFileTransfer: boolean;\n\t}): void {\n\t\tif (opts.enableDocSync) {\n\t\t\tthis.createChannel(CHANNEL_NAMES.YJS_SYNC, {\n\t\t\t\tordered: true,\n\t\t\t});\n\t\t}\n\n\t\tif (opts.enableAwareness) {\n\t\t\tthis.createChannel(CHANNEL_NAMES.AWARENESS, {\n\t\t\t\tordered: false,\n\t\t\t\tmaxRetransmits: 0,\n\t\t\t});\n\t\t}\n\n\t\tif (opts.enableFileTransfer) {\n\t\t\tthis.createChannel(CHANNEL_NAMES.FILE_TRANSFER, {\n\t\t\t\tordered: true,\n\t\t\t});\n\t\t}\n\t}\n\n\t/**\n\t * Create namespaced channels for a child/subdocument.\n\t * Channel names are prefixed with `{childId}:` to avoid collisions.\n\t */\n\tcreateSubdocChannels(childId: string, opts: {\n\t\tenableDocSync: boolean;\n\t\tenableAwareness: boolean;\n\t}): void {\n\t\tif (opts.enableDocSync) {\n\t\t\tthis.createChannel(`${childId}:${CHANNEL_NAMES.YJS_SYNC}`, {\n\t\t\t\tordered: true,\n\t\t\t});\n\t\t}\n\t\tif (opts.enableAwareness) {\n\t\t\tthis.createChannel(`${childId}:${CHANNEL_NAMES.AWARENESS}`, {\n\t\t\t\tordered: false,\n\t\t\t\tmaxRetransmits: 0,\n\t\t\t});\n\t\t}\n\t}\n\n\tgetChannel(name: string): RTCDataChannel | null {\n\t\treturn this.channels.get(name) ?? null;\n\t}\n\n\tisOpen(name: string): boolean {\n\t\treturn this.channels.get(name)?.readyState === \"open\";\n\t}\n\n\t/**\n\t * Send data on a named channel, encrypting if E2EE is active.\n\t * Falls back to plaintext if no encryptor is set or for exempt channels.\n\t */\n\tasync send(name: string, data: Uint8Array): Promise<boolean> {\n\t\tconst channel = this.channels.get(name);\n\t\tif (!channel || channel.readyState !== \"open\") return false;\n\n\t\tif (this.encryptor?.isEstablished && !this.plaintextChannels.has(name)) {\n\t\t\tconst encrypted = await this.encryptor.encrypt(data);\n\t\t\tchannel.send(encrypted as unknown as ArrayBuffer);\n\t\t} else {\n\t\t\tchannel.send(data as unknown as ArrayBuffer);\n\t\t}\n\t\treturn true;\n\t}\n\n\tprivate registerChannel(channel: RTCDataChannel): void {\n\t\tchannel.binaryType = \"arraybuffer\";\n\t\tthis.channels.set(channel.label, channel);\n\n\t\tchannel.onopen = () => {\n\t\t\tthis.emit(\"channelOpen\", { name: channel.label, channel });\n\t\t};\n\n\t\tchannel.onclose = () => {\n\t\t\tthis.emit(\"channelClose\", { name: channel.label });\n\t\t\tthis.channels.delete(channel.label);\n\t\t};\n\n\t\tchannel.onmessage = async (event) => {\n\t\t\tconst name = channel.label;\n\t\t\tlet data = event.data;\n\n\t\t\t// Decrypt incoming data if E2EE is active (skip plaintext channels).\n\t\t\tif (\n\t\t\t\tthis.encryptor?.isEstablished &&\n\t\t\t\t!this.plaintextChannels.has(name) &&\n\t\t\t\t(data instanceof ArrayBuffer || data instanceof Uint8Array)\n\t\t\t) {\n\t\t\t\ttry {\n\t\t\t\t\tconst buf =\n\t\t\t\t\t\tdata instanceof ArrayBuffer ? new Uint8Array(data) : data;\n\t\t\t\t\tdata = await this.encryptor.decrypt(buf);\n\t\t\t\t} catch (err) {\n\t\t\t\t\tthis.emit(\"channelError\", {\n\t\t\t\t\t\tname,\n\t\t\t\t\t\terror: err,\n\t\t\t\t\t});\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tthis.emit(\"channelMessage\", { name, data });\n\t\t};\n\n\t\tchannel.onerror = (event) => {\n\t\t\tthis.emit(\"channelError\", {\n\t\t\t\tname: channel.label,\n\t\t\t\terror: event,\n\t\t\t});\n\t\t};\n\n\t\t// If the channel is already open (can happen with ondatachannel),\n\t\t// emit immediately.\n\t\tif (channel.readyState === \"open\") {\n\t\t\tthis.emit(\"channelOpen\", { name: channel.label, channel });\n\t\t}\n\t}\n\n\tclose(): void {\n\t\tfor (const channel of this.channels.values()) {\n\t\t\ttry {\n\t\t\t\tchannel.close();\n\t\t\t} catch {\n\t\t\t\t// Ignore\n\t\t\t}\n\t\t}\n\t\tthis.channels.clear();\n\t}\n\n\tdestroy(): void {\n\t\tthis.close();\n\t\tthis.connection.ondatachannel = null;\n\t\tthis.removeAllListeners();\n\t}\n}\n","import EventEmitter from \"../EventEmitter.ts\";\nimport { DataChannelRouter } from \"./DataChannelRouter.ts\";\n\nexport class PeerConnection extends EventEmitter {\n\tpublic readonly connection: RTCPeerConnection;\n\tpublic readonly router: DataChannelRouter;\n\tpublic readonly peerId: string;\n\tprivate pendingCandidates: RTCIceCandidateInit[] = [];\n\tprivate hasRemoteDescription = false;\n\n\tconstructor(\n\t\tpeerId: string,\n\t\ticeServers: RTCIceServer[],\n\t) {\n\t\tsuper();\n\n\t\tthis.peerId = peerId;\n\n\t\tthis.connection = new RTCPeerConnection({ iceServers });\n\t\tthis.router = new DataChannelRouter(this.connection);\n\n\t\tthis.connection.onicecandidate = (event) => {\n\t\t\tif (event.candidate) {\n\t\t\t\tthis.emit(\"iceCandidate\", {\n\t\t\t\t\tpeerId: this.peerId,\n\t\t\t\t\tcandidate: JSON.stringify(event.candidate.toJSON()),\n\t\t\t\t});\n\t\t\t}\n\t\t};\n\n\t\tthis.connection.oniceconnectionstatechange = () => {\n\t\t\tconst state = this.connection.iceConnectionState;\n\t\t\tthis.emit(\"iceStateChange\", { peerId: this.peerId, state });\n\n\t\t\tif (state === \"failed\") {\n\t\t\t\tthis.emit(\"iceFailed\", { peerId: this.peerId });\n\t\t\t}\n\t\t};\n\n\t\tthis.connection.onconnectionstatechange = () => {\n\t\t\tthis.emit(\"connectionStateChange\", {\n\t\t\t\tpeerId: this.peerId,\n\t\t\t\tstate: this.connection.connectionState,\n\t\t\t});\n\t\t};\n\t}\n\n\tget connectionState(): RTCPeerConnectionState {\n\t\treturn this.connection.connectionState;\n\t}\n\n\tget iceConnectionState(): RTCIceConnectionState {\n\t\treturn this.connection.iceConnectionState;\n\t}\n\n\t/** Create an SDP offer (initiator side). */\n\tasync createOffer(iceRestart = false): Promise<string> {\n\t\tconst offer = await this.connection.createOffer(\n\t\t\ticeRestart ? { iceRestart: true } : undefined,\n\t\t);\n\t\tawait this.connection.setLocalDescription(offer);\n\t\treturn JSON.stringify(this.connection.localDescription?.toJSON());\n\t}\n\n\t/** Set a remote offer and create an answer (receiver side). Returns the SDP answer. */\n\tasync setRemoteOffer(sdp: string): Promise<string> {\n\t\tconst offer = JSON.parse(sdp) as RTCSessionDescriptionInit;\n\t\tawait this.connection.setRemoteDescription(\n\t\t\tnew RTCSessionDescription(offer),\n\t\t);\n\t\tthis.hasRemoteDescription = true;\n\t\tawait this.flushPendingCandidates();\n\n\t\tconst answer = await this.connection.createAnswer();\n\t\tawait this.connection.setLocalDescription(answer);\n\t\treturn JSON.stringify(this.connection.localDescription?.toJSON());\n\t}\n\n\t/** Set the remote answer (initiator side). */\n\tasync setRemoteAnswer(sdp: string): Promise<void> {\n\t\tconst answer = JSON.parse(sdp) as RTCSessionDescriptionInit;\n\t\tawait this.connection.setRemoteDescription(\n\t\t\tnew RTCSessionDescription(answer),\n\t\t);\n\t\tthis.hasRemoteDescription = true;\n\t\tawait this.flushPendingCandidates();\n\t}\n\n\t/** Add a remote ICE candidate. Queues if remote description not yet set. */\n\tasync addIceCandidate(candidateJson: string): Promise<void> {\n\t\tconst candidate = JSON.parse(candidateJson) as RTCIceCandidateInit;\n\n\t\tif (!this.hasRemoteDescription) {\n\t\t\tthis.pendingCandidates.push(candidate);\n\t\t\treturn;\n\t\t}\n\n\t\tawait this.connection.addIceCandidate(new RTCIceCandidate(candidate));\n\t}\n\n\tprivate async flushPendingCandidates(): Promise<void> {\n\t\tfor (const candidate of this.pendingCandidates) {\n\t\t\tawait this.connection.addIceCandidate(\n\t\t\t\tnew RTCIceCandidate(candidate),\n\t\t\t);\n\t\t}\n\t\tthis.pendingCandidates = [];\n\t}\n\n\tclose(): void {\n\t\tthis.router.close();\n\t\ttry {\n\t\t\tthis.connection.close();\n\t\t} catch {\n\t\t\t// Ignore\n\t\t}\n\t}\n\n\tdestroy(): void {\n\t\tthis.router.destroy();\n\t\tthis.connection.onicecandidate = null;\n\t\tthis.connection.oniceconnectionstatechange = null;\n\t\tthis.connection.onconnectionstatechange = null;\n\n\t\ttry {\n\t\t\tthis.connection.close();\n\t\t} catch {\n\t\t\t// Ignore\n\t\t}\n\n\t\tthis.removeAllListeners();\n\t}\n}\n","import * as Y from \"yjs\";\nimport * as syncProtocol from \"y-protocols/sync\";\nimport {\n\tencodeAwarenessUpdate,\n\tapplyAwarenessUpdate,\n\ttype Awareness,\n} from \"y-protocols/awareness\";\nimport * as encoding from \"lib0/encoding\";\nimport * as decoding from \"lib0/decoding\";\nimport type { DataChannelRouter } from \"./DataChannelRouter.ts\";\nimport { CHANNEL_NAMES, YJS_MSG } from \"./types.ts\";\n\n/**\n * Handles Y.js document sync and awareness over WebRTC data channels.\n *\n * Uses the same y-protocols/sync encoding as the WebSocket provider but\n * transported over RTCDataChannel instead. A unique origin is used to\n * prevent echo loops with the server-based provider.\n */\nexport class YjsDataChannel {\n\tpublic isSynced = false;\n\tprivate docUpdateHandler: ((update: Uint8Array, origin: any) => void) | null = null;\n\tprivate awarenessUpdateHandler: ((changes: { added: number[]; updated: number[]; removed: number[] }, origin: any) => void) | null = null;\n\tprivate channelOpenHandler: ((data: { name: string; channel: RTCDataChannel }) => void) | null = null;\n\tprivate channelMessageHandler: ((data: { name: string; data: any }) => void) | null = null;\n\n\t/** Channel names used for sync and awareness (supports namespaced subdoc channels). */\n\tprivate readonly syncChannelName: string;\n\tprivate readonly awarenessChannelName: string;\n\n\t/**\n\t * @param document - The Y.Doc to sync\n\t * @param awareness - Optional Awareness instance\n\t * @param router - DataChannelRouter for the peer connection\n\t * @param channelPrefix - Optional prefix for subdocument channels (e.g. `\"{childId}:\"`)\n\t */\n\tconstructor(\n\t\tprivate readonly document: Y.Doc,\n\t\tprivate readonly awareness: Awareness | null,\n\t\tprivate readonly router: DataChannelRouter,\n\t\tchannelPrefix?: string,\n\t) {\n\t\tconst prefix = channelPrefix ?? \"\";\n\t\tthis.syncChannelName = `${prefix}${CHANNEL_NAMES.YJS_SYNC}`;\n\t\tthis.awarenessChannelName = `${prefix}${CHANNEL_NAMES.AWARENESS}`;\n\t}\n\n\t/** Start listening for Y.js updates and data channel messages. */\n\tattach(): void {\n\t\t// Listen for local doc updates and send to peer.\n\t\tthis.docUpdateHandler = (update: Uint8Array, origin: any) => {\n\t\t\t// Don't echo updates we received from this data channel.\n\t\t\tif (origin === this) return;\n\n\t\t\tif (!this.router.isOpen(this.syncChannelName)) return;\n\n\t\t\tconst encoder = encoding.createEncoder();\n\t\t\tencoding.writeVarUint(encoder, YJS_MSG.UPDATE);\n\t\t\tencoding.writeVarUint8Array(encoder, update);\n\t\t\tthis.router.send(this.syncChannelName, encoding.toUint8Array(encoder));\n\t\t};\n\t\tthis.document.on(\"update\", this.docUpdateHandler);\n\n\t\t// Listen for local awareness updates and send to peer.\n\t\tif (this.awareness) {\n\t\t\tthis.awarenessUpdateHandler = (\n\t\t\t\t{ added, updated, removed }: { added: number[]; updated: number[]; removed: number[] },\n\t\t\t\t_origin: any,\n\t\t\t) => {\n\t\t\t\tif (!this.router.isOpen(this.awarenessChannelName)) return;\n\n\t\t\t\tconst changedClients = added.concat(updated).concat(removed);\n\t\t\t\tconst update = encodeAwarenessUpdate(this.awareness!, changedClients);\n\t\t\t\tthis.router.send(this.awarenessChannelName, update);\n\t\t\t};\n\t\t\tthis.awareness.on(\"update\", this.awarenessUpdateHandler);\n\t\t}\n\n\t\t// Handle incoming data channel messages.\n\t\tthis.channelMessageHandler = ({ name, data }: { name: string; data: any }) => {\n\t\t\tif (name === this.syncChannelName) {\n\t\t\t\tthis.handleSyncMessage(data);\n\t\t\t} else if (name === this.awarenessChannelName) {\n\t\t\t\tthis.handleAwarenessMessage(data);\n\t\t\t}\n\t\t};\n\t\tthis.router.on(\"channelMessage\", this.channelMessageHandler);\n\n\t\t// When sync channel opens, initiate sync handshake.\n\t\tthis.channelOpenHandler = ({ name }: { name: string; channel: RTCDataChannel }) => {\n\t\t\tif (name === this.syncChannelName) {\n\t\t\t\tthis.sendSyncStep1();\n\t\t\t} else if (name === this.awarenessChannelName && this.awareness) {\n\t\t\t\t// Send full awareness state on channel open.\n\t\t\t\tif (this.router.isOpen(this.awarenessChannelName)) {\n\t\t\t\t\tconst update = encodeAwarenessUpdate(\n\t\t\t\t\t\tthis.awareness,\n\t\t\t\t\t\tArray.from(this.awareness.getStates().keys()),\n\t\t\t\t\t);\n\t\t\t\t\tthis.router.send(this.awarenessChannelName, update);\n\t\t\t\t}\n\t\t\t}\n\t\t};\n\t\tthis.router.on(\"channelOpen\", this.channelOpenHandler);\n\n\t\t// If sync channel is already open, start sync immediately.\n\t\tif (this.router.isOpen(this.syncChannelName)) {\n\t\t\tthis.sendSyncStep1();\n\t\t}\n\n\t\t// If awareness channel is already open, send state immediately.\n\t\tif (this.awareness && this.router.isOpen(this.awarenessChannelName)) {\n\t\t\tconst update = encodeAwarenessUpdate(\n\t\t\t\tthis.awareness,\n\t\t\t\tArray.from(this.awareness.getStates().keys()),\n\t\t\t);\n\t\t\tthis.router.send(this.awarenessChannelName, update);\n\t\t}\n\t}\n\n\t/** Stop listening and clean up handlers. */\n\tdetach(): void {\n\t\tif (this.docUpdateHandler) {\n\t\t\tthis.document.off(\"update\", this.docUpdateHandler);\n\t\t\tthis.docUpdateHandler = null;\n\t\t}\n\n\t\tif (this.awarenessUpdateHandler && this.awareness) {\n\t\t\tthis.awareness.off(\"update\", this.awarenessUpdateHandler);\n\t\t\tthis.awarenessUpdateHandler = null;\n\t\t}\n\n\t\tif (this.channelMessageHandler) {\n\t\t\tthis.router.off(\"channelMessage\", this.channelMessageHandler);\n\t\t\tthis.channelMessageHandler = null;\n\t\t}\n\n\t\tif (this.channelOpenHandler) {\n\t\t\tthis.router.off(\"channelOpen\", this.channelOpenHandler);\n\t\t\tthis.channelOpenHandler = null;\n\t\t}\n\n\t\tthis.isSynced = false;\n\t}\n\n\tdestroy(): void {\n\t\tthis.detach();\n\t}\n\n\tprivate sendSyncStep1(): void {\n\t\tif (!this.router.isOpen(this.syncChannelName)) return;\n\n\t\tconst encoder = encoding.createEncoder();\n\t\tencoding.writeVarUint(encoder, YJS_MSG.SYNC);\n\t\tsyncProtocol.writeSyncStep1(encoder, this.document);\n\t\tthis.router.send(this.syncChannelName, encoding.toUint8Array(encoder));\n\t}\n\n\tprivate handleSyncMessage(data: ArrayBuffer | Uint8Array): void {\n\t\tconst buf = data instanceof ArrayBuffer ? new Uint8Array(data) : data;\n\t\tconst decoder = decoding.createDecoder(buf);\n\t\tconst msgType = decoding.readVarUint(decoder);\n\n\t\tif (msgType === YJS_MSG.SYNC) {\n\t\t\t// Standard y-protocols/sync message (SyncStep1, SyncStep2, or Update).\n\t\t\tconst encoder = encoding.createEncoder();\n\t\t\tconst syncMessageType = syncProtocol.readSyncMessage(\n\t\t\t\tdecoder,\n\t\t\t\tencoder,\n\t\t\t\tthis.document,\n\t\t\t\tthis,\n\t\t\t);\n\n\t\t\t// If the sync protocol generated a response (SyncStep2), send it.\n\t\t\tif (encoding.length(encoder) > 0) {\n\t\t\t\tconst responseEncoder = encoding.createEncoder();\n\t\t\t\tencoding.writeVarUint(responseEncoder, YJS_MSG.SYNC);\n\t\t\t\tencoding.writeUint8Array(\n\t\t\t\t\tresponseEncoder,\n\t\t\t\t\tencoding.toUint8Array(encoder),\n\t\t\t\t);\n\t\t\t\tif (this.router.isOpen(this.syncChannelName)) {\n\t\t\t\t\tthis.router.send(this.syncChannelName, encoding.toUint8Array(responseEncoder));\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// SyncStep2 means initial sync is complete.\n\t\t\tif (syncMessageType === syncProtocol.messageYjsSyncStep2) {\n\t\t\t\tthis.isSynced = true;\n\t\t\t}\n\t\t} else if (msgType === YJS_MSG.UPDATE) {\n\t\t\t// Raw incremental update.\n\t\t\tconst update = decoding.readVarUint8Array(decoder);\n\t\t\tY.applyUpdate(this.document, update, this);\n\t\t}\n\t}\n\n\tprivate handleAwarenessMessage(data: ArrayBuffer | Uint8Array): void {\n\t\tif (!this.awareness) return;\n\t\tconst buf = data instanceof ArrayBuffer ? new Uint8Array(data) : data;\n\t\tapplyAwarenessUpdate(this.awareness, buf, this);\n\t}\n}\n","import EventEmitter from \"../EventEmitter.ts\";\nimport { DataChannelRouter } from \"./DataChannelRouter.ts\";\nimport {\n\tCHANNEL_NAMES,\n\tFILE_MSG,\n\tDEFAULT_FILE_CHUNK_SIZE,\n\tTRANSFER_ID_BYTES,\n\tSHA256_BYTES,\n\ttype FileTransferMeta,\n\ttype FileTransferStatus,\n} from \"./types.ts\";\n\n/**\n * Handle for tracking a file transfer in progress.\n */\nexport class FileTransferHandle extends EventEmitter {\n\tpublic readonly transferId: string;\n\tpublic progress = 0;\n\tpublic status: FileTransferStatus = \"pending\";\n\n\tprivate abortController = new AbortController();\n\n\tconstructor(transferId: string) {\n\t\tsuper();\n\t\tthis.transferId = transferId;\n\t}\n\n\tcancel(): void {\n\t\tthis.status = \"cancelled\";\n\t\tthis.abortController.abort();\n\t\tthis.emit(\"cancelled\");\n\t}\n\n\tget signal(): AbortSignal {\n\t\treturn this.abortController.signal;\n\t}\n\n\t/** @internal */\n\t_setProgress(p: number): void {\n\t\tthis.progress = p;\n\t\tthis.emit(\"progress\", p);\n\t}\n\n\t/** @internal */\n\t_setStatus(s: FileTransferStatus): void {\n\t\tthis.status = s;\n\t}\n\n\t/** @internal — public alias for the protected emit so the parent\n\t * `FileTransferChannel` (a different class instance) can dispatch events\n\t * on this handle. Protected access is by-class, not by-hierarchy. */\n\t_emit(event: string, ...args: unknown[]): void {\n\t\tthis.emit(event, ...args);\n\t}\n}\n\ninterface ReceiveState {\n\tmeta: FileTransferMeta;\n\tchunks: (Uint8Array | null)[];\n\treceivedCount: number;\n}\n\n/**\n * Chunked binary file transfer over a dedicated WebRTC data channel.\n */\nexport class FileTransferChannel extends EventEmitter {\n\tprivate receives = new Map<string, ReceiveState>();\n\tprivate chunkSize: number;\n\tprivate channelMessageHandler: ((data: { name: string; data: any }) => void) | null = null;\n\n\tconstructor(\n\t\tprivate readonly router: DataChannelRouter,\n\t\tchunkSize?: number,\n\t) {\n\t\tsuper();\n\t\tthis.chunkSize = chunkSize ?? DEFAULT_FILE_CHUNK_SIZE;\n\n\t\tthis.channelMessageHandler = ({ name, data }: { name: string; data: any }) => {\n\t\t\tif (name === CHANNEL_NAMES.FILE_TRANSFER) {\n\t\t\t\tthis.handleMessage(data);\n\t\t\t}\n\t\t};\n\t\tthis.router.on(\"channelMessage\", this.channelMessageHandler);\n\t}\n\n\t/** Send a file to a peer. Returns a handle for tracking progress. */\n\tasync send(\n\t\tfile: File | Blob,\n\t\tfilename: string,\n\t): Promise<FileTransferHandle> {\n\t\tconst transferId = generateTransferId();\n\t\tconst handle = new FileTransferHandle(transferId);\n\t\tconst transferIdBytes = hexToBytes(transferId);\n\n\t\tconst totalSize = file.size;\n\t\tconst totalChunks = Math.ceil(totalSize / this.chunkSize);\n\t\tconst mimeType =\n\t\t\tfile instanceof File ? file.type : \"application/octet-stream\";\n\n\t\tconst meta: FileTransferMeta = {\n\t\t\ttransferId,\n\t\t\tfilename,\n\t\t\tmimeType,\n\t\t\ttotalSize,\n\t\t\tchunkSize: this.chunkSize,\n\t\t\ttotalChunks,\n\t\t};\n\n\t\tconst channel = this.router.getChannel(CHANNEL_NAMES.FILE_TRANSFER);\n\t\tif (!channel || channel.readyState !== \"open\") {\n\t\t\thandle._setStatus(\"error\");\n\t\t\thandle._emit(\"error\", new Error(\"File transfer channel not open\"));\n\t\t\treturn handle;\n\t\t}\n\n\t\t// Send start message.\n\t\tconst startMsg = new Uint8Array(\n\t\t\t1 + new TextEncoder().encode(JSON.stringify(meta)).length,\n\t\t);\n\t\tstartMsg[0] = FILE_MSG.START;\n\t\tstartMsg.set(new TextEncoder().encode(JSON.stringify(meta)), 1);\n\t\tchannel.send(startMsg);\n\n\t\thandle._setStatus(\"sending\");\n\n\t\t// Read and send chunks.\n\t\tconst arrayBuffer = await file.arrayBuffer();\n\t\tconst fileBytes = new Uint8Array(arrayBuffer);\n\n\t\t// SHA-256 for integrity check.\n\t\tconst hashBuffer = await crypto.subtle.digest(\"SHA-256\", fileBytes);\n\t\tconst hashBytes = new Uint8Array(hashBuffer);\n\n\t\tfor (let i = 0; i < totalChunks; i++) {\n\t\t\tif (handle.signal.aborted) {\n\t\t\t\t// Send cancel.\n\t\t\t\tconst cancelMsg = new Uint8Array(1 + TRANSFER_ID_BYTES);\n\t\t\t\tcancelMsg[0] = FILE_MSG.CANCEL;\n\t\t\t\tcancelMsg.set(transferIdBytes, 1);\n\t\t\t\tchannel.send(cancelMsg);\n\t\t\t\treturn handle;\n\t\t\t}\n\n\t\t\tconst offset = i * this.chunkSize;\n\t\t\tconst chunk = fileBytes.slice(\n\t\t\t\toffset,\n\t\t\t\tMath.min(offset + this.chunkSize, totalSize),\n\t\t\t);\n\n\t\t\t// [type(1)] [transferId(16)] [chunkIndex(4)] [chunk data]\n\t\t\tconst msg = new Uint8Array(\n\t\t\t\t1 + TRANSFER_ID_BYTES + 4 + chunk.length,\n\t\t\t);\n\t\t\tmsg[0] = FILE_MSG.CHUNK;\n\t\t\tmsg.set(transferIdBytes, 1);\n\t\t\tnew DataView(msg.buffer).setUint32(\n\t\t\t\t1 + TRANSFER_ID_BYTES,\n\t\t\t\ti,\n\t\t\t\tfalse,\n\t\t\t);\n\t\t\tmsg.set(chunk, 1 + TRANSFER_ID_BYTES + 4);\n\n\t\t\t// Wait for bufferedAmount to drop before sending more chunks\n\t\t\t// to avoid overwhelming the data channel.\n\t\t\twhile (channel.bufferedAmount > this.chunkSize * 4) {\n\t\t\t\tawait new Promise<void>((resolve) => setTimeout(resolve, 10));\n\t\t\t\tif (handle.signal.aborted) return handle;\n\t\t\t}\n\n\t\t\tchannel.send(msg);\n\t\t\thandle._setProgress((i + 1) / totalChunks);\n\t\t}\n\n\t\t// Send complete message.\n\t\tconst completeMsg = new Uint8Array(\n\t\t\t1 + TRANSFER_ID_BYTES + SHA256_BYTES,\n\t\t);\n\t\tcompleteMsg[0] = FILE_MSG.COMPLETE;\n\t\tcompleteMsg.set(transferIdBytes, 1);\n\t\tcompleteMsg.set(hashBytes, 1 + TRANSFER_ID_BYTES);\n\t\tchannel.send(completeMsg);\n\n\t\thandle._setStatus(\"complete\");\n\t\thandle._emit(\"complete\");\n\n\t\treturn handle;\n\t}\n\n\tprivate handleMessage(data: ArrayBuffer | Uint8Array): void {\n\t\tconst buf = data instanceof ArrayBuffer ? new Uint8Array(data) : data;\n\t\tif (buf.length < 1) return;\n\n\t\tconst type = buf[0];\n\n\t\tswitch (type) {\n\t\t\tcase FILE_MSG.START:\n\t\t\t\tthis.handleStart(buf);\n\t\t\t\tbreak;\n\t\t\tcase FILE_MSG.CHUNK:\n\t\t\t\tthis.handleChunk(buf);\n\t\t\t\tbreak;\n\t\t\tcase FILE_MSG.COMPLETE:\n\t\t\t\tthis.handleComplete(buf);\n\t\t\t\tbreak;\n\t\t\tcase FILE_MSG.CANCEL:\n\t\t\t\tthis.handleCancel(buf);\n\t\t\t\tbreak;\n\t\t}\n\t}\n\n\tprivate handleStart(buf: Uint8Array): void {\n\t\tconst json = new TextDecoder().decode(buf.slice(1));\n\t\tlet meta: FileTransferMeta;\n\t\ttry {\n\t\t\tmeta = JSON.parse(json);\n\t\t} catch {\n\t\t\tthis.emit(\"receiveError\", { transferId: \"unknown\", error: \"Malformed START message: invalid JSON\" });\n\t\t\treturn;\n\t\t}\n\n\t\tthis.receives.set(meta.transferId, {\n\t\t\tmeta,\n\t\t\tchunks: new Array(meta.totalChunks).fill(null),\n\t\t\treceivedCount: 0,\n\t\t});\n\n\t\tthis.emit(\"receiveStart\", meta);\n\t}\n\n\tprivate handleChunk(buf: Uint8Array): void {\n\t\tif (buf.length < 1 + TRANSFER_ID_BYTES + 4) return;\n\n\t\tconst transferId = bytesToHex(\n\t\t\tbuf.slice(1, 1 + TRANSFER_ID_BYTES),\n\t\t);\n\t\tconst chunkIndex = new DataView(buf.buffer, buf.byteOffset).getUint32(\n\t\t\t1 + TRANSFER_ID_BYTES,\n\t\t\tfalse,\n\t\t);\n\t\tconst chunkData = buf.slice(1 + TRANSFER_ID_BYTES + 4);\n\n\t\tconst state = this.receives.get(transferId);\n\t\tif (!state) return;\n\n\t\tif (chunkIndex < state.chunks.length && !state.chunks[chunkIndex]) {\n\t\t\tstate.chunks[chunkIndex] = chunkData;\n\t\t\tstate.receivedCount++;\n\n\t\t\tconst progress = state.receivedCount / state.meta.totalChunks;\n\t\t\tthis.emit(\"receiveProgress\", {\n\t\t\t\ttransferId,\n\t\t\t\treceived: state.receivedCount,\n\t\t\t\ttotal: state.meta.totalChunks,\n\t\t\t\tprogress,\n\t\t\t});\n\t\t}\n\t}\n\n\tprivate async handleComplete(buf: Uint8Array): Promise<void> {\n\t\tif (buf.length < 1 + TRANSFER_ID_BYTES + SHA256_BYTES) return;\n\n\t\tconst transferId = bytesToHex(\n\t\t\tbuf.slice(1, 1 + TRANSFER_ID_BYTES),\n\t\t);\n\t\tconst expectedHash = buf.slice(1 + TRANSFER_ID_BYTES, 1 + TRANSFER_ID_BYTES + SHA256_BYTES);\n\n\t\tconst state = this.receives.get(transferId);\n\t\tif (!state) return;\n\n\t\t// Assemble the file.\n\t\tconst totalSize = state.meta.totalSize;\n\t\tconst assembled = new Uint8Array(totalSize);\n\t\tlet offset = 0;\n\n\t\tfor (let i = 0; i < state.chunks.length; i++) {\n\t\t\tconst chunk = state.chunks[i];\n\t\t\tif (!chunk) {\n\t\t\t\tthis.emit(\"receiveError\", {\n\t\t\t\t\ttransferId,\n\t\t\t\t\terror: `Missing chunk ${i}`,\n\t\t\t\t});\n\t\t\t\tthis.receives.delete(transferId);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tassembled.set(chunk, offset);\n\t\t\toffset += chunk.length;\n\t\t}\n\n\t\t// Verify SHA-256 integrity.\n\t\tconst actualHashBuffer = await crypto.subtle.digest(\n\t\t\t\"SHA-256\",\n\t\t\tassembled,\n\t\t);\n\t\tconst actualHash = new Uint8Array(actualHashBuffer);\n\n\t\tif (!constantTimeEqual(expectedHash, actualHash)) {\n\t\t\tthis.emit(\"receiveError\", {\n\t\t\t\ttransferId,\n\t\t\t\terror: \"SHA-256 integrity check failed\",\n\t\t\t});\n\t\t\tthis.receives.delete(transferId);\n\t\t\treturn;\n\t\t}\n\n\t\tconst blob = new Blob([assembled], { type: state.meta.mimeType });\n\n\t\tthis.emit(\"receiveComplete\", {\n\t\t\ttransferId,\n\t\t\tblob,\n\t\t\tfilename: state.meta.filename,\n\t\t\tmimeType: state.meta.mimeType,\n\t\t\tsize: state.meta.totalSize,\n\t\t});\n\n\t\tthis.receives.delete(transferId);\n\t}\n\n\tprivate handleCancel(buf: Uint8Array): void {\n\t\tif (buf.length < 1 + TRANSFER_ID_BYTES) return;\n\n\t\tconst transferId = bytesToHex(\n\t\t\tbuf.slice(1, 1 + TRANSFER_ID_BYTES),\n\t\t);\n\t\tthis.receives.delete(transferId);\n\t\tthis.emit(\"receiveCancelled\", { transferId });\n\t}\n\n\tdestroy(): void {\n\t\tif (this.channelMessageHandler) {\n\t\t\tthis.router.off(\"channelMessage\", this.channelMessageHandler);\n\t\t\tthis.channelMessageHandler = null;\n\t\t}\n\t\tthis.receives.clear();\n\t\tthis.removeAllListeners();\n\t}\n}\n\n// ── Utilities ───────────────────────────────────────────────────────────────\n\nfunction generateTransferId(): string {\n\tconst bytes = new Uint8Array(TRANSFER_ID_BYTES);\n\tcrypto.getRandomValues(bytes);\n\treturn bytesToHex(bytes);\n}\n\nfunction bytesToHex(bytes: Uint8Array): string {\n\treturn Array.from(bytes)\n\t\t.map((b) => b.toString(16).padStart(2, \"0\"))\n\t\t.join(\"\");\n}\n\nfunction hexToBytes(hex: string): Uint8Array {\n\tconst bytes = new Uint8Array(hex.length / 2);\n\tfor (let i = 0; i < hex.length; i += 2) {\n\t\tbytes[i / 2] = parseInt(hex.slice(i, i + 2), 16);\n\t}\n\treturn bytes;\n}\n\nfunction constantTimeEqual(a: Uint8Array, b: Uint8Array): boolean {\n\tif (a.length !== b.length) return false;\n\tlet result = 0;\n\tfor (let i = 0; i < a.length; i++) {\n\t\tresult |= a[i] ^ b[i];\n\t}\n\treturn result === 0;\n}\n","/**\n * E2EEChannel\n *\n * Per-peer end-to-end encryption for WebRTC data channels using\n * X25519 ECDH key agreement + HKDF-SHA256 + AES-256-GCM.\n *\n * Leverages the same cryptographic primitives as `DocKeyManager` and\n * `CryptoIdentityKeystore` but applied to data channel messages rather\n * than stored document keys.\n *\n * Key agreement flow:\n * 1. Both peers exchange Ed25519 public keys via the `key-exchange` data channel\n * 2. Convert Ed25519 → X25519 (Montgomery form)\n * 3. Run X25519 ECDH to derive a shared secret\n * 4. HKDF-SHA256(sharedSecret, salt, info) → 32-byte AES-256-GCM session key\n * 5. All subsequent data channel messages are encrypted with this key\n *\n * Message wire format: [12-byte nonce || AES-256-GCM ciphertext]\n *\n * Dependencies: @noble/curves (already in the project for CryptoIdentityKeystore)\n */\n\nimport { x25519, ed25519 as nobleEd25519 } from \"@noble/curves/ed25519.js\";\nimport { hkdf } from \"@noble/hashes/hkdf.js\";\nimport { sha256 } from \"@noble/hashes/sha2.js\";\nimport EventEmitter from \"../EventEmitter.ts\";\n\nconst HKDF_INFO = new TextEncoder().encode(\"abracadabra-webrtc-e2ee-v1\");\nconst NONCE_BYTES = 12;\n\nexport interface E2EEIdentity {\n\t/** Raw 32-byte Ed25519 public key. */\n\tpublicKey: Uint8Array;\n\t/** Raw 32-byte X25519 private key. Caller must wipe after E2EEChannel.destroy(). */\n\tx25519PrivateKey: Uint8Array;\n}\n\nexport class E2EEChannel extends EventEmitter {\n\tprivate sessionKey: CryptoKey | null = null;\n\tprivate remotePublicKey: Uint8Array | null = null;\n\tprivate _isEstablished = false;\n\n\tconstructor(\n\t\tprivate readonly identity: E2EEIdentity,\n\t\tprivate readonly docId: string,\n\t) {\n\t\tsuper();\n\t}\n\n\tget isEstablished(): boolean {\n\t\treturn this._isEstablished;\n\t}\n\n\t/**\n\t * Process a key-exchange message from the remote peer.\n\t * Called when the `key-exchange` data channel receives a message.\n\t *\n\t * The message is the remote peer's raw 32-byte Ed25519 public key.\n\t * After receiving it, ECDH is computed and the session key derived.\n\t */\n\tasync handleKeyExchange(remoteEdPubKey: Uint8Array): Promise<void> {\n\t\tif (remoteEdPubKey.length !== 32) {\n\t\t\tthis.emit(\"error\", new Error(\"Invalid remote public key length\"));\n\t\t\treturn;\n\t\t}\n\n\t\tthis.remotePublicKey = remoteEdPubKey;\n\n\t\t// Convert remote Ed25519 public key to X25519 (Montgomery form).\n\t\tconst remoteX25519Pub = nobleEd25519.utils.toMontgomery(remoteEdPubKey);\n\n\t\t// X25519 ECDH: compute shared secret.\n\t\tconst sharedSecret = x25519.getSharedSecret(\n\t\t\tthis.identity.x25519PrivateKey,\n\t\t\tremoteX25519Pub,\n\t\t);\n\n\t\t// Deterministic salt: docId + sorted public keys (ensures both peers derive the same key).\n\t\tconst localPub = this.identity.publicKey;\n\t\tconst remotePub = remoteEdPubKey;\n\t\tconst [first, second] = this.sortKeys(localPub, remotePub);\n\t\tconst saltParts = [\n\t\t\tnew TextEncoder().encode(this.docId),\n\t\t\tfirst,\n\t\t\tsecond,\n\t\t];\n\t\tconst salt = new Uint8Array(\n\t\t\tsaltParts.reduce((acc, p) => acc + p.length, 0),\n\t\t);\n\t\tlet offset = 0;\n\t\tfor (const part of saltParts) {\n\t\t\tsalt.set(part, offset);\n\t\t\toffset += part.length;\n\t\t}\n\n\t\t// HKDF-SHA256 → 32-byte AES key.\n\t\tconst keyBytes = hkdf(sha256, sharedSecret, salt, HKDF_INFO, 32);\n\n\t\tthis.sessionKey = await crypto.subtle.importKey(\n\t\t\t\"raw\",\n\t\t\tkeyBytes as BufferSource,\n\t\t\t{ name: \"AES-GCM\" },\n\t\t\tfalse,\n\t\t\t[\"encrypt\", \"decrypt\"],\n\t\t);\n\n\t\tthis._isEstablished = true;\n\t\tthis.emit(\"established\", { remotePublicKey: remoteEdPubKey });\n\t}\n\n\t/**\n\t * Returns the local Ed25519 public key to send to the remote peer\n\t * via the `key-exchange` data channel.\n\t */\n\tgetKeyExchangeMessage(): Uint8Array {\n\t\treturn this.identity.publicKey;\n\t}\n\n\t/**\n\t * Encrypt a message for sending over a data channel.\n\t * Returns `[12-byte nonce || AES-256-GCM ciphertext]`.\n\t *\n\t * @throws if the session key has not been established yet.\n\t */\n\tasync encrypt(plaintext: Uint8Array): Promise<Uint8Array> {\n\t\tif (!this.sessionKey) {\n\t\t\tthrow new Error(\"E2EE session key not established\");\n\t\t}\n\n\t\tconst nonce = crypto.getRandomValues(new Uint8Array(NONCE_BYTES));\n\t\tconst ciphertext = new Uint8Array(\n\t\t\tawait crypto.subtle.encrypt(\n\t\t\t\t{ name: \"AES-GCM\", iv: nonce as BufferSource },\n\t\t\t\tthis.sessionKey,\n\t\t\t\tplaintext as BufferSource,\n\t\t\t),\n\t\t);\n\n\t\t// Wire format: [nonce(12) || ciphertext].\n\t\tconst result = new Uint8Array(NONCE_BYTES + ciphertext.length);\n\t\tresult.set(nonce, 0);\n\t\tresult.set(ciphertext, NONCE_BYTES);\n\t\treturn result;\n\t}\n\n\t/**\n\t * Decrypt a message received from a data channel.\n\t * Expects `[12-byte nonce || AES-256-GCM ciphertext]`.\n\t *\n\t * @throws if the session key has not been established or decryption fails.\n\t */\n\tasync decrypt(data: Uint8Array): Promise<Uint8Array> {\n\t\tif (!this.sessionKey) {\n\t\t\tthrow new Error(\"E2EE session key not established\");\n\t\t}\n\n\t\tif (data.length < NONCE_BYTES + 16) {\n\t\t\t// Minimum: nonce + AES-GCM tag (16 bytes).\n\t\t\tthrow new Error(\"E2EE ciphertext too short\");\n\t\t}\n\n\t\tconst nonce = data.slice(0, NONCE_BYTES);\n\t\tconst ciphertext = data.slice(NONCE_BYTES);\n\n\t\tconst plaintext = await crypto.subtle.decrypt(\n\t\t\t{ name: \"AES-GCM\", iv: nonce },\n\t\t\tthis.sessionKey,\n\t\t\tciphertext,\n\t\t);\n\n\t\treturn new Uint8Array(plaintext);\n\t}\n\n\t/** Destroy the session key and wipe sensitive material. */\n\tdestroy(): void {\n\t\tthis.sessionKey = null;\n\t\tthis.remotePublicKey = null;\n\t\tthis._isEstablished = false;\n\t\tthis.removeAllListeners();\n\t}\n\n\t// ── Private ──────────────────────────────────────────────────────────────\n\n\t/** Sort two keys lexicographically so both peers produce the same order. */\n\tprivate sortKeys(\n\t\ta: Uint8Array,\n\t\tb: Uint8Array,\n\t): [Uint8Array, Uint8Array] {\n\t\tfor (let i = 0; i < Math.min(a.length, b.length); i++) {\n\t\t\tif (a[i] < b[i]) return [a, b];\n\t\t\tif (a[i] > b[i]) return [b, a];\n\t\t}\n\t\treturn a.length <= b.length ? [a, b] : [b, a];\n\t}\n}\n","import type * as Y from \"yjs\";\nimport type { Awareness } from \"y-protocols/awareness\";\nimport EventEmitter from \"../EventEmitter.ts\";\nimport type { AbracadabraProvider } from \"../AbracadabraProvider.ts\";\nimport { SignalingSocket } from \"./SignalingSocket.ts\";\nimport { PeerConnection } from \"./PeerConnection.ts\";\nimport { YjsDataChannel } from \"./YjsDataChannel.ts\";\nimport { FileTransferChannel, FileTransferHandle } from \"./FileTransferChannel.ts\";\nimport { E2EEChannel, type E2EEIdentity } from \"./E2EEChannel.ts\";\nimport { KEY_EXCHANGE_CHANNEL } from \"./DataChannelRouter.ts\";\nimport {\n\tDEFAULT_ICE_SERVERS,\n\tCHANNEL_NAMES,\n\ttype AbracadabraWebRTCConfiguration,\n\ttype PeerInfo,\n\ttype PeerState,\n} from \"./types.ts\";\n\nconst HAS_RTC = typeof globalThis.RTCPeerConnection !== \"undefined\";\n\n/**\n * Optional WebRTC provider for peer-to-peer Y.js sync, awareness, and file transfer.\n *\n * Uses the server's signaling endpoint (`/ws/:doc_id/signaling`) for connection\n * negotiation, then establishes direct data channels between peers. Designed to\n * work alongside `AbracadabraProvider` — the server remains the persistence layer,\n * while WebRTC provides low-latency P2P sync.\n *\n * Falls back to a no-op when `RTCPeerConnection` is unavailable (e.g. Node.js).\n */\nexport class AbracadabraWebRTC extends EventEmitter {\n\tprivate signaling: SignalingSocket | null = null;\n\tprivate peerConnections = new Map<string, PeerConnection>();\n\tprivate yjsChannels = new Map<string, YjsDataChannel>();\n\tprivate fileChannels = new Map<string, FileTransferChannel>();\n\tprivate e2eeChannels = new Map<string, E2EEChannel>();\n\n\tprivate readonly config: {\n\t\tdocId: string;\n\t\turl: string;\n\t\tsignalingUrl: string | null;\n\t\ttoken: string | (() => string) | (() => Promise<string>);\n\t\tdocument: Y.Doc | null;\n\t\tawareness: Awareness | null;\n\t\ticeServers: RTCIceServer[];\n\t\tdisplayName: string | null;\n\t\tcolor: string | null;\n\t\tenableDocSync: boolean;\n\t\tenableAwarenessSync: boolean;\n\t\tenableFileTransfer: boolean;\n\t\tfileChunkSize: number;\n\t\te2ee: E2EEIdentity | (() => Promise<E2EEIdentity>) | null;\n\t\tWebSocketPolyfill: any;\n\t};\n\n\t/** Cached resolved E2EE identity (lazily resolved from factory on first peer connect). */\n\tprivate _resolvedE2ee: E2EEIdentity | null = null;\n\tprivate _resolveE2eePromise: Promise<E2EEIdentity> | null = null;\n\n\tpublic readonly peers = new Map<string, PeerState>();\n\tpublic localPeerId: string | null = null;\n\tpublic isConnected = false;\n\n\tconstructor(configuration: AbracadabraWebRTCConfiguration) {\n\t\tsuper();\n\n\t\tconst doc = configuration.document ?? null;\n\t\tconst awareness = configuration.awareness ?? null;\n\n\t\tthis.config = {\n\t\t\tdocId: configuration.docId,\n\t\t\turl: configuration.url,\n\t\t\tsignalingUrl: configuration.signalingUrl ?? null,\n\t\t\ttoken: configuration.token,\n\t\t\tdocument: doc,\n\t\t\tawareness,\n\t\t\ticeServers: configuration.iceServers ?? DEFAULT_ICE_SERVERS,\n\t\t\tdisplayName: configuration.displayName ?? null,\n\t\t\tcolor: configuration.color ?? null,\n\t\t\tenableDocSync: configuration.enableDocSync ?? !!doc,\n\t\t\tenableAwarenessSync: configuration.enableAwarenessSync ?? !!awareness,\n\t\t\tenableFileTransfer: configuration.enableFileTransfer ?? false,\n\t\t\tfileChunkSize: configuration.fileChunkSize ?? 16384,\n\t\t\te2ee: configuration.e2ee ?? null,\n\t\t\tWebSocketPolyfill: configuration.WebSocketPolyfill,\n\t\t};\n\n\t\tif (configuration.autoConnect !== false && HAS_RTC) {\n\t\t\tthis.connect();\n\t\t}\n\t}\n\n\t/**\n\t * Create an AbracadabraWebRTC instance from an existing provider,\n\t * reusing its document, awareness, URL, and token.\n\t */\n\tstatic fromProvider(\n\t\tprovider: AbracadabraProvider,\n\t\toptions?: Partial<AbracadabraWebRTCConfiguration>,\n\t): AbracadabraWebRTC {\n\t\t// Derive the HTTP URL from the provider's WebSocket URL.\n\t\tconst config = provider.configuration;\n\t\tconst wsUrl =\n\t\t\tconfig.websocketProvider?.url ??\n\t\t\t(config as { url?: string }).url ??\n\t\t\t\"\";\n\t\tconst httpUrl = wsUrl\n\t\t\t.replace(/^wss:/, \"https:\")\n\t\t\t.replace(/^ws:/, \"http:\")\n\t\t\t.replace(/\\/ws\\/?$/, \"\");\n\n\t\treturn new AbracadabraWebRTC({\n\t\t\tdocId: config.name,\n\t\t\turl: httpUrl,\n\t\t\ttoken: config.token as string | (() => string) | (() => Promise<string>),\n\t\t\tdocument: provider.document,\n\t\t\tawareness: provider.awareness,\n\t\t\t...options,\n\t\t});\n\t}\n\n\t// ── Connection Lifecycle ────────────────────────────────────────────────\n\n\tasync connect(): Promise<void> {\n\t\tif (!HAS_RTC) return;\n\t\tif (this.isConnected) return;\n\n\t\tconst signalingUrl = this.buildSignalingUrl();\n\n\t\tthis.signaling = new SignalingSocket({\n\t\t\turl: signalingUrl,\n\t\t\ttoken: this.config.token,\n\t\t\tautoConnect: false,\n\t\t\tWebSocketPolyfill: this.config.WebSocketPolyfill,\n\t\t});\n\n\t\tthis.signaling.on(\n\t\t\t\"welcome\",\n\t\t\t(data: { peerId: string; peers: PeerInfo[] }) => {\n\t\t\t\tthis.localPeerId = data.peerId;\n\t\t\t\tthis.isConnected = true;\n\t\t\t\tthis.emit(\"connected\");\n\n\t\t\t\t// Send profile if configured.\n\t\t\t\tif (this.config.displayName && this.config.color) {\n\t\t\t\t\tthis.signaling!.sendProfile(\n\t\t\t\t\t\tthis.config.displayName,\n\t\t\t\t\t\tthis.config.color,\n\t\t\t\t\t);\n\t\t\t\t}\n\n\t\t\t\t// Initiate connections to existing peers.\n\t\t\t\tfor (const peer of data.peers) {\n\t\t\t\t\tthis.addPeer(peer);\n\t\t\t\t\t// Deterministic initiator: lower peer_id sends offer.\n\t\t\t\t\tif (this.localPeerId! < peer.peer_id) {\n\t\t\t\t\t\tthis.initiateConnection(peer.peer_id);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t},\n\t\t);\n\n\t\tthis.signaling.on(\"joined\", (peer: PeerInfo) => {\n\t\t\tthis.addPeer(peer);\n\t\t\tthis.emit(\"peerJoined\", peer);\n\n\t\t\t// Deterministic initiator.\n\t\t\tif (this.localPeerId! < peer.peer_id) {\n\t\t\t\tthis.initiateConnection(peer.peer_id);\n\t\t\t}\n\t\t});\n\n\t\tthis.signaling.on(\"left\", ({ peerId }: { peerId: string }) => {\n\t\t\tthis.removePeer(peerId);\n\t\t\tthis.emit(\"peerLeft\", { peerId });\n\t\t});\n\n\t\tthis.signaling.on(\n\t\t\t\"offer\",\n\t\t\tasync ({ from, sdp }: { from: string; sdp: string }) => {\n\t\t\t\tawait this.handleOffer(from, sdp);\n\t\t\t},\n\t\t);\n\n\t\tthis.signaling.on(\n\t\t\t\"answer\",\n\t\t\tasync ({ from, sdp }: { from: string; sdp: string }) => {\n\t\t\t\tconst pc = this.peerConnections.get(from);\n\t\t\t\tif (pc) {\n\t\t\t\t\tawait pc.setRemoteAnswer(sdp);\n\t\t\t\t}\n\t\t\t},\n\t\t);\n\n\t\tthis.signaling.on(\n\t\t\t\"ice\",\n\t\t\tasync ({\n\t\t\t\tfrom,\n\t\t\t\tcandidate,\n\t\t\t}: { from: string; candidate: string }) => {\n\t\t\t\tconst pc = this.peerConnections.get(from);\n\t\t\t\tif (pc) {\n\t\t\t\t\tawait pc.addIceCandidate(candidate);\n\t\t\t\t}\n\t\t\t},\n\t\t);\n\n\t\tthis.signaling.on(\n\t\t\t\"mute\",\n\t\t\t({ peerId, muted }: { peerId: string; muted: boolean }) => {\n\t\t\t\tconst peer = this.peers.get(peerId);\n\t\t\t\tif (peer) {\n\t\t\t\t\tpeer.muted = muted;\n\t\t\t\t\tthis.emit(\"peerMuted\", { peerId, muted });\n\t\t\t\t}\n\t\t\t},\n\t\t);\n\n\t\tthis.signaling.on(\n\t\t\t\"media-state\",\n\t\t\t({\n\t\t\t\tpeerId,\n\t\t\t\tvideo,\n\t\t\t\tscreen,\n\t\t\t}: { peerId: string; video: boolean; screen: boolean }) => {\n\t\t\t\tconst peer = this.peers.get(peerId);\n\t\t\t\tif (peer) {\n\t\t\t\t\tpeer.video = video;\n\t\t\t\t\tpeer.screen = screen;\n\t\t\t\t\tthis.emit(\"peerMediaState\", { peerId, video, screen });\n\t\t\t\t}\n\t\t\t},\n\t\t);\n\n\t\tthis.signaling.on(\n\t\t\t\"profile\",\n\t\t\t({\n\t\t\t\tpeerId,\n\t\t\t\tname,\n\t\t\t\tcolor,\n\t\t\t}: { peerId: string; name: string; color: string }) => {\n\t\t\t\tconst peer = this.peers.get(peerId);\n\t\t\t\tif (peer) {\n\t\t\t\t\tpeer.name = name;\n\t\t\t\t\tpeer.color = color;\n\t\t\t\t\tthis.emit(\"peerProfile\", { peerId, name, color });\n\t\t\t\t}\n\t\t\t},\n\t\t);\n\n\t\tthis.signaling.on(\"disconnected\", () => {\n\t\t\tthis.isConnected = false;\n\t\t\tthis.localPeerId = null;\n\t\t\t// Clean up all peer connections — signaling will auto-reconnect.\n\t\t\tthis.removeAllPeers();\n\t\t\tthis.emit(\"disconnected\");\n\t\t});\n\n\t\tthis.signaling.on(\n\t\t\t\"error\",\n\t\t\t(err: { code: string; message: string }) => {\n\t\t\t\tthis.emit(\"signalingError\", err);\n\t\t\t},\n\t\t);\n\n\t\tawait this.signaling.connect();\n\t}\n\n\tdisconnect(): void {\n\t\tif (!HAS_RTC) return;\n\n\t\tthis.removeAllPeers();\n\n\t\tif (this.signaling) {\n\t\t\tthis.signaling.disconnect();\n\t\t\tthis.signaling = null;\n\t\t}\n\n\t\tthis.isConnected = false;\n\t\tthis.localPeerId = null;\n\t}\n\n\tdestroy(): void {\n\t\tthis.disconnect();\n\n\t\tif (this.signaling) {\n\t\t\tthis.signaling.destroy();\n\t\t\tthis.signaling = null;\n\t\t}\n\n\t\tthis._resolvedE2ee = null;\n\t\tthis._resolveE2eePromise = null;\n\n\t\tthis.removeAllListeners();\n\t}\n\n\t// ── Media State ─────────────────────────────────────────────────────────\n\n\tsetMuted(muted: boolean): void {\n\t\tthis.signaling?.sendMute(muted);\n\t}\n\n\tsetMediaState(video: boolean, screen: boolean): void {\n\t\tthis.signaling?.sendMediaState(video, screen);\n\t}\n\n\tsetProfile(name: string, color: string): void {\n\t\tthis.signaling?.sendProfile(name, color);\n\t}\n\n\t// ── File Transfer ───────────────────────────────────────────────────────\n\n\t/**\n\t * Send a file to a specific peer. Returns a handle for tracking progress.\n\t */\n\tasync sendFile(\n\t\tpeerId: string,\n\t\tfile: File | Blob,\n\t\tfilename: string,\n\t): Promise<FileTransferHandle | null> {\n\t\tconst fc = this.fileChannels.get(peerId);\n\t\tif (!fc) return null;\n\t\treturn fc.send(file, filename);\n\t}\n\n\t/**\n\t * Send a file to all connected peers. Returns an array of handles.\n\t */\n\tasync broadcastFile(\n\t\tfile: File | Blob,\n\t\tfilename: string,\n\t): Promise<FileTransferHandle[]> {\n\t\tconst handles: FileTransferHandle[] = [];\n\t\tfor (const [peerId, fc] of this.fileChannels) {\n\t\t\tconst handle = await fc.send(file, filename);\n\t\t\thandles.push(handle);\n\t\t}\n\t\treturn handles;\n\t}\n\n\t// ── Custom Messages ─────────────────────────────────────────────────────\n\n\t/**\n\t * Send a custom string message to a specific peer via a data channel.\n\t * When E2EE is active, the message is encrypted through the router.\n\t */\n\tsendCustomMessage(peerId: string, payload: string): void {\n\t\tconst pc = this.peerConnections.get(peerId);\n\t\tif (!pc) return;\n\n\t\tconst channelName = \"custom\";\n\t\tconst channel = pc.router.getChannel(channelName);\n\t\tif (channel && channel.readyState === \"open\") {\n\t\t\tconst data = new TextEncoder().encode(payload);\n\t\t\tpc.router.send(channelName, data).catch(() => {});\n\t\t\treturn;\n\t\t}\n\n\t\t// Channel not open yet — queue via the router's channelOpen event.\n\t\t// Do NOT create a new channel here. The \"custom\" channel must be\n\t\t// created during initiateConnection to be included in the SDP offer.\n\t\t// If it doesn't exist yet, the peer hasn't finished negotiation.\n\t\tconst onOpen = ({ name }: { name: string }) => {\n\t\t\tif (name === channelName) {\n\t\t\t\tpc.router.off(\"channelOpen\", onOpen);\n\t\t\t\tconst data = new TextEncoder().encode(payload);\n\t\t\t\tpc.router.send(channelName, data).catch(() => {});\n\t\t\t}\n\t\t};\n\t\tpc.router.on(\"channelOpen\", onOpen);\n\t}\n\n\t/**\n\t * Send a custom string message to all connected peers.\n\t */\n\tbroadcastCustomMessage(payload: string): void {\n\t\tfor (const peerId of this.peerConnections.keys()) {\n\t\t\tthis.sendCustomMessage(peerId, payload);\n\t\t}\n\t}\n\n\t// ── Private: Peer Management ────────────────────────────────────────────\n\n\tprivate addPeer(info: PeerInfo): void {\n\t\tthis.peers.set(info.peer_id, {\n\t\t\t...info,\n\t\t\tconnectionState: \"new\",\n\t\t});\n\t}\n\n\tprivate removePeer(peerId: string): void {\n\t\tthis.peers.delete(peerId);\n\n\t\tconst e2ee = this.e2eeChannels.get(peerId);\n\t\tif (e2ee) {\n\t\t\te2ee.destroy();\n\t\t\tthis.e2eeChannels.delete(peerId);\n\t\t}\n\n\t\tconst yjs = this.yjsChannels.get(peerId);\n\t\tif (yjs) {\n\t\t\tyjs.destroy();\n\t\t\tthis.yjsChannels.delete(peerId);\n\t\t}\n\n\t\tconst fc = this.fileChannels.get(peerId);\n\t\tif (fc) {\n\t\t\tfc.destroy();\n\t\t\tthis.fileChannels.delete(peerId);\n\t\t}\n\n\t\tconst pc = this.peerConnections.get(peerId);\n\t\tif (pc) {\n\t\t\tpc.destroy();\n\t\t\tthis.peerConnections.delete(peerId);\n\t\t}\n\t}\n\n\tprivate removeAllPeers(): void {\n\t\tfor (const peerId of [...this.peers.keys()]) {\n\t\t\tthis.removePeer(peerId);\n\t\t}\n\t}\n\n\t// ── Private: Connection Negotiation ─────────────────────────────────────\n\n\tprivate createPeerConnection(peerId: string): PeerConnection {\n\t\tconst pc = new PeerConnection(peerId, this.config.iceServers);\n\n\t\t// Forward ICE candidates to signaling.\n\t\tpc.on(\n\t\t\t\"iceCandidate\",\n\t\t\t({ peerId, candidate }: { peerId: string; candidate: string }) => {\n\t\t\t\tthis.signaling?.sendIce(peerId, candidate);\n\t\t\t},\n\t\t);\n\n\t\t// Handle ICE failure with restart.\n\t\tpc.on(\"iceFailed\", async ({ peerId }: { peerId: string }) => {\n\t\t\ttry {\n\t\t\t\tconst sdp = await pc.createOffer(true);\n\t\t\t\tthis.signaling?.sendOffer(peerId, sdp);\n\t\t\t} catch {\n\t\t\t\t// If ICE restart fails, remove peer.\n\t\t\t\tthis.removePeer(peerId);\n\t\t\t}\n\t\t});\n\n\t\t// Track connection state.\n\t\tpc.on(\n\t\t\t\"connectionStateChange\",\n\t\t\t({ peerId, state }: { peerId: string; state: RTCPeerConnectionState }) => {\n\t\t\t\tconst peer = this.peers.get(peerId);\n\t\t\t\tif (peer) {\n\t\t\t\t\tpeer.connectionState = state;\n\t\t\t\t}\n\n\t\t\t\tif (state === \"disconnected\" || state === \"closed\") {\n\t\t\t\t\t// Peer connection dropped. Don't remove yet — ICE may recover.\n\t\t\t\t\t// If \"failed\", the iceFailed handler will attempt restart.\n\t\t\t\t}\n\n\t\t\t\tthis.emit(\"peerConnectionState\", { peerId, state });\n\t\t\t},\n\t\t);\n\n\t\t// Listen for custom messages on the router.\n\t\tpc.router.on(\"channelMessage\", ({ name, data }: { name: string; data: any }) => {\n\t\t\tif (name === \"custom\") {\n\t\t\t\tconst payload = typeof data === \"string\" ? data : new TextDecoder().decode(data);\n\t\t\t\tthis.emit(\"customMessage\", { peerId, payload });\n\t\t\t}\n\t\t});\n\n\t\tthis.peerConnections.set(peerId, pc);\n\t\tthis.attachDataHandlers(peerId, pc);\n\n\t\treturn pc;\n\t}\n\n\t/** Resolve the E2EE identity, supporting both pre-resolved objects and lazy factories. */\n\tprivate async resolveE2ee(): Promise<E2EEIdentity | null> {\n\t\tif (this._resolvedE2ee) return this._resolvedE2ee;\n\t\tif (!this.config.e2ee) return null;\n\t\tif (typeof this.config.e2ee === \"function\") {\n\t\t\tif (!this._resolveE2eePromise) {\n\t\t\t\tthis._resolveE2eePromise = this.config.e2ee().then((id) => {\n\t\t\t\t\tthis._resolvedE2ee = id;\n\t\t\t\t\treturn id;\n\t\t\t\t});\n\t\t\t}\n\t\t\treturn this._resolveE2eePromise;\n\t\t}\n\t\tthis._resolvedE2ee = this.config.e2ee;\n\t\treturn this._resolvedE2ee;\n\t}\n\n\tprivate attachDataHandlers(peerId: string, pc: PeerConnection): void {\n\t\tif (!this.config.e2ee) {\n\t\t\tthis.startDataSync(peerId, pc);\n\t\t\treturn;\n\t\t}\n\n\t\t// E2EE identity may resolve asynchronously (e.g. lazy passkey-derived key).\n\t\t// Register handlers synchronously so no messages are lost during resolution.\n\t\tlet e2ee: E2EEChannel | null = null;\n\t\tconst pendingMessages: Uint8Array[] = [];\n\t\tlet pendingKeyExchangeChannel: RTCDataChannel | null = null;\n\n\t\tpc.router.on(\"channelMessage\", async ({ name, data }: { name: string; data: any }) => {\n\t\t\tif (name !== KEY_EXCHANGE_CHANNEL) return;\n\t\t\tconst buf = data instanceof ArrayBuffer ? new Uint8Array(data) : data;\n\t\t\tif (!e2ee) {\n\t\t\t\tpendingMessages.push(buf);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\ttry {\n\t\t\t\tawait e2ee.handleKeyExchange(buf);\n\t\t\t} catch (err) {\n\t\t\t\tthis.emit(\"e2eeFailed\", { peerId, error: err });\n\t\t\t}\n\t\t});\n\n\t\tpc.router.on(\"channelOpen\", ({ name, channel }: { name: string; channel: RTCDataChannel }) => {\n\t\t\tif (name !== KEY_EXCHANGE_CHANNEL) return;\n\t\t\tif (!e2ee) {\n\t\t\t\tpendingKeyExchangeChannel = channel;\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tchannel.send(e2ee.getKeyExchangeMessage() as unknown as ArrayBuffer);\n\t\t});\n\n\t\tthis.resolveE2ee().then(async (identity) => {\n\t\t\tif (!identity) {\n\t\t\t\tthis.startDataSync(peerId, pc);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\te2ee = new E2EEChannel(identity, this.config.docId);\n\t\t\tthis.e2eeChannels.set(peerId, e2ee);\n\t\t\tpc.router.setEncryptor(e2ee);\n\n\t\t\t// Drain buffered key-exchange channel open\n\t\t\tif (pendingKeyExchangeChannel) {\n\t\t\t\tpendingKeyExchangeChannel.send(e2ee.getKeyExchangeMessage() as unknown as ArrayBuffer);\n\t\t\t}\n\t\t\t// Drain buffered messages\n\t\t\tfor (const msg of pendingMessages) {\n\t\t\t\ttry {\n\t\t\t\t\tawait e2ee.handleKeyExchange(msg);\n\t\t\t\t} catch (err) {\n\t\t\t\t\tthis.emit(\"e2eeFailed\", { peerId, error: err });\n\t\t\t\t}\n\t\t\t}\n\n\t\t\te2ee.on(\"established\", () => {\n\t\t\t\tthis.emit(\"e2eeEstablished\", { peerId });\n\t\t\t\tthis.startDataSync(peerId, pc);\n\t\t\t});\n\n\t\t\te2ee.on(\"error\", (err: Error) => {\n\t\t\t\tthis.emit(\"e2eeFailed\", { peerId, error: err });\n\t\t\t});\n\t\t}).catch((err) => {\n\t\t\tthis.emit(\"e2eeFailed\", { peerId, error: err });\n\t\t\tthis.startDataSync(peerId, pc);\n\t\t});\n\t}\n\n\tprivate startDataSync(peerId: string, pc: PeerConnection): void {\n\t\t// Attach Y.js sync.\n\t\tif (this.config.document && this.config.enableDocSync) {\n\t\t\t// Don't double-attach if already set up.\n\t\t\tif (this.yjsChannels.has(peerId)) return;\n\n\t\t\tconst yjs = new YjsDataChannel(\n\t\t\t\tthis.config.document,\n\t\t\t\tthis.config.enableAwarenessSync ? this.config.awareness : null,\n\t\t\t\tpc.router,\n\t\t\t);\n\t\t\tyjs.attach();\n\t\t\tthis.yjsChannels.set(peerId, yjs);\n\t\t}\n\n\t\t// Attach file transfer.\n\t\tif (this.config.enableFileTransfer && !this.fileChannels.has(peerId)) {\n\t\t\tconst fc = new FileTransferChannel(pc.router, this.config.fileChunkSize);\n\n\t\t\tfc.on(\"receiveStart\", (meta: any) => {\n\t\t\t\tthis.emit(\"fileReceiveStart\", { peerId, ...meta });\n\t\t\t});\n\t\t\tfc.on(\"receiveProgress\", (data: any) => {\n\t\t\t\tthis.emit(\"fileReceiveProgress\", { peerId, ...data });\n\t\t\t});\n\t\t\tfc.on(\"receiveComplete\", (data: any) => {\n\t\t\t\tthis.emit(\"fileReceiveComplete\", { peerId, ...data });\n\t\t\t});\n\t\t\tfc.on(\"receiveError\", (data: any) => {\n\t\t\t\tthis.emit(\"fileReceiveError\", { peerId, ...data });\n\t\t\t});\n\t\t\tfc.on(\"receiveCancelled\", (data: any) => {\n\t\t\t\tthis.emit(\"fileReceiveCancelled\", { peerId, ...data });\n\t\t\t});\n\n\t\t\tthis.fileChannels.set(peerId, fc);\n\t\t}\n\t}\n\n\tprivate async initiateConnection(peerId: string): Promise<void> {\n\t\tconst pc = this.createPeerConnection(peerId);\n\n\t\t// Create key-exchange channel first if E2EE is enabled.\n\t\tif (this.config.e2ee) {\n\t\t\tpc.router.createChannel(KEY_EXCHANGE_CHANNEL, { ordered: true });\n\t\t}\n\n\t\t// Create data channels (initiator creates them).\n\t\tpc.router.createDefaultChannels({\n\t\t\tenableDocSync: this.config.enableDocSync,\n\t\t\tenableAwareness: this.config.enableAwarenessSync,\n\t\t\tenableFileTransfer: this.config.enableFileTransfer,\n\t\t});\n\n\t\t// Always create the \"custom\" channel for application messages\n\t\t// (e.g. device pairing). Must be in the initial offer so the\n\t\t// remote peer receives it via ondatachannel.\n\t\tpc.router.createChannel(\"custom\", { ordered: true });\n\n\t\ttry {\n\t\t\tconst sdp = await pc.createOffer();\n\t\t\tthis.signaling?.sendOffer(peerId, sdp);\n\t\t} catch (err) {\n\t\t\tthis.emit(\"error\", { type: \"offer-failed\", peerId, error: err });\n\t\t\tthis.removePeer(peerId);\n\t\t}\n\t}\n\n\tprivate async handleOffer(from: string, sdp: string): Promise<void> {\n\t\t// Clean up any existing connection to this peer.\n\t\tconst existing = this.peerConnections.get(from);\n\t\tif (existing) {\n\t\t\texisting.destroy();\n\t\t\tthis.yjsChannels.get(from)?.destroy();\n\t\t\tthis.yjsChannels.delete(from);\n\t\t\tthis.fileChannels.get(from)?.destroy();\n\t\t\tthis.fileChannels.delete(from);\n\t\t\tthis.peerConnections.delete(from);\n\t\t}\n\n\t\tconst pc = this.createPeerConnection(from);\n\n\t\ttry {\n\t\t\tconst answerSdp = await pc.setRemoteOffer(sdp);\n\t\t\tthis.signaling?.sendAnswer(from, answerSdp);\n\t\t} catch (err) {\n\t\t\tthis.emit(\"error\", { type: \"answer-failed\", peerId: from, error: err });\n\t\t\tthis.removePeer(from);\n\t\t}\n\t}\n\n\t// ── Private: URL Building ───────────────────────────────────────────────\n\n\tprivate buildSignalingUrl(): string {\n\t\t// Use explicit signalingUrl if provided.\n\t\tif (this.config.signalingUrl) {\n\t\t\tlet sigBase = this.config.signalingUrl;\n\t\t\twhile (sigBase.endsWith(\"/\")) sigBase = sigBase.slice(0, -1);\n\t\t\tsigBase = sigBase.replace(/^https:/, \"wss:\").replace(/^http:/, \"ws:\");\n\t\t\treturn `${sigBase}/ws/${encodeURIComponent(this.config.docId)}/signaling`;\n\t\t}\n\n\t\tlet base = this.config.url;\n\n\t\t// Remove trailing slashes.\n\t\twhile (base.endsWith(\"/\")) {\n\t\t\tbase = base.slice(0, -1);\n\t\t}\n\n\t\t// Convert http(s) to ws(s).\n\t\tbase = base.replace(/^https:/, \"wss:\").replace(/^http:/, \"ws:\");\n\n\t\treturn `${base}/ws/${encodeURIComponent(this.config.docId)}/signaling`;\n\t}\n}\n","import * as Y from \"yjs\";\nimport { sha256 } from \"@noble/hashes/sha2.js\";\nimport EventEmitter from \"./EventEmitter.ts\";\nimport { AbracadabraProvider } from \"./AbracadabraProvider.ts\";\nimport type { AbracadabraProviderConfiguration } from \"./AbracadabraProvider.ts\";\nimport { AbracadabraWS } from \"./AbracadabraWS.ts\";\nimport { AbracadabraWebRTC } from \"./webrtc/AbracadabraWebRTC.ts\";\nimport type { CryptoIdentity } from \"./types.ts\";\nimport type { E2EEIdentity } from \"./webrtc/E2EEChannel.ts\";\n\n// ── Identity Doc ID Derivation ─────────────────────────────────────────────\n\n/**\n * Derives a deterministic UUID from an Ed25519 account-level public key.\n *\n * The result is a valid UUID v5-style string that any device sharing the\n * same identity can independently compute. The `abracadabra:identity:`\n * prefix prevents collisions with randomly generated doc UUIDs.\n *\n * @param publicKeyB64 Base64url-encoded Ed25519 public key (32 bytes).\n */\nexport function deriveIdentityDocId(publicKeyB64: string): string {\n\tconst hash = sha256(\n\t\tnew TextEncoder().encode(`abracadabra:identity:${publicKeyB64}`),\n\t);\n\tconst bytes = new Uint8Array(hash.buffer, hash.byteOffset, 16);\n\t// Set UUID version 5 + variant 1 bits.\n\tbytes[6] = (bytes[6] & 0x0f) | 0x50;\n\tbytes[8] = (bytes[8] & 0x3f) | 0x80;\n\tconst hex = Array.from(bytes, (b) => b.toString(16).padStart(2, \"0\")).join(\n\t\t\"\",\n\t);\n\treturn `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20, 32)}`;\n}\n\n/**\n * Derives a deterministic UUID for the DM doc between two participants\n * (independent of which side computes it). The two pubkeys are sorted\n * lexicographically before hashing so both clients produce the same id —\n * this lets `findOrCreateDmDoc` race-tolerantly create-or-claim the doc\n * without coordinating; whichever client wins the create-with-id call\n * is fine, the other gets a Conflict and reuses the existing id.\n *\n * @param pubkeyA Base64url-encoded Ed25519 public key (32 bytes).\n * @param pubkeyB Base64url-encoded Ed25519 public key (32 bytes).\n */\nexport function deriveDmDocId(pubkeyA: string, pubkeyB: string): string {\n\tconst [first, second] = [pubkeyA, pubkeyB].sort();\n\tconst hash = sha256(\n\t\tnew TextEncoder().encode(`abracadabra:dm:${first}:${second}`),\n\t);\n\tconst bytes = new Uint8Array(hash.buffer, hash.byteOffset, 16);\n\tbytes[6] = (bytes[6] & 0x0f) | 0x50;\n\tbytes[8] = (bytes[8] & 0x3f) | 0x80;\n\tconst hex = Array.from(bytes, (b) => b.toString(16).padStart(2, \"0\")).join(\n\t\t\"\",\n\t);\n\treturn `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20, 32)}`;\n}\n\n// ── Types ──────────────────────────────────────────────────────────────────\n\nexport interface IdentityProfile {\n\tusername?: string;\n\tdisplayName?: string;\n\tcolorName?: string;\n\tneutralColorName?: string;\n\tlocale?: string;\n\tavatarUrl?: string;\n}\n\nexport interface IdentityServerEntry {\n\tlabel: string;\n\thubDocId?: string;\n\tentryDocId?: string;\n\tdefaultRole?: string;\n\tspacesEnabled?: boolean;\n\taddedAt: number;\n}\n\nexport type DeviceTier = \"master\" | \"paired\";\n\nexport interface DeviceServerStatus {\n\tregistered: boolean;\n\tregisteredAt: number | null;\n\tkeyId: string | null;\n\tlastVerifiedAt: number | null;\n\terror: string | null;\n}\n\nexport interface IdentityDeviceEntry {\n\tdeviceName: string;\n\ttier: DeviceTier;\n\tx25519Key: string | null;\n\taddedAt: number;\n\trevokedAt: number | null;\n\trevokedBy: string | null;\n\tservers: Map<string, DeviceServerStatus>;\n}\n\nexport interface IdentitySpaceEntry {\n\tid: string;\n\tname: string;\n\ttype: \"local\" | \"remote\";\n\tserverUrl: string | null;\n\tdocId: string;\n\tremoteSpaceId?: string;\n\tvisibility: \"public\" | \"private\" | \"invite\";\n\tisHub: boolean;\n\torder: number;\n\tlastSyncedAt?: number;\n\tcreatedAt: number;\n}\n\nexport interface IdentityDocConfiguration {\n\t/** Base64url-encoded Ed25519 account public key. */\n\tpublicKey: string;\n\n\t/**\n\t * Trusted server URL for identity doc sync.\n\t * Only this server (plus the local server) will receive the identity doc.\n\t */\n\tsyncServerUrl?: string;\n\n\t/** Local Tauri server URL for on-device persistence. */\n\tlocalServerUrl?: string;\n\n\t/**\n\t * JWT token or async factory for authenticating with sync servers.\n\t * When using multiple servers, provide a factory that returns the correct\n\t * token for each.\n\t */\n\ttoken?: string | (() => string) | (() => Promise<string>);\n\n\t/** Per-server token factories keyed by base URL. */\n\ttokens?: Record<string, string | (() => string) | (() => Promise<string>)>;\n\n\t/**\n\t * Crypto identity for Ed25519 challenge-response auth.\n\t * When provided, used instead of JWT tokens for authenticating with servers.\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 * WebRTC configuration for P2P identity sync.\n\t * When provided, enables E2EE peer-to-peer sync using signaling from\n\t * any connected server.\n\t */\n\twebrtc?: {\n\t\t/** Server URL to use for signaling (any connected server works). */\n\t\tsignalingServerUrl: string;\n\t\t/** Token for the signaling server. */\n\t\ttoken: string | (() => string) | (() => Promise<string>);\n\t\t/** E2EE identity for the data channel. Accepts a factory for lazy derivation. */\n\t\te2ee?: E2EEIdentity | (() => Promise<E2EEIdentity>);\n\t\t/** ICE servers. */\n\t\ticeServers?: RTCIceServer[];\n\t};\n\n\t/** Disable IndexedDB offline store. */\n\tdisableOfflineStore?: boolean;\n\n\t/** Auto-connect on construction. Default: true. */\n\tautoConnect?: boolean;\n\n\t/** Additional provider config passed through to each AbracadabraProvider. */\n\tproviderDefaults?: Partial<AbracadabraProviderConfiguration>;\n}\n\n// ── IdentityDocProvider ────────────────────────────────────────────────────\n\n/**\n * Manages a Y.Doc dedicated to user identity that syncs across trusted\n * targets only: a designated sync server, a local Tauri server, and/or\n * WebRTC P2P.\n *\n * The Y.Doc contains cross-device settings (profile, servers, spaces,\n * plugins, preferences). Each sync target gets its own\n * AbracadabraProvider sharing the same Y.Doc, with `serverAgnostic: true`\n * so they all use one IndexedDB store.\n */\nexport class IdentityDocProvider extends EventEmitter {\n\tpublic readonly docId: string;\n\tpublic readonly document: Y.Doc;\n\n\tprivate providers = new Map<string, AbracadabraProvider>();\n\tprivate websockets = new Map<string, AbracadabraWS>();\n\tprivate webrtc: AbracadabraWebRTC | null = null;\n\tprivate config: IdentityDocConfiguration;\n\tprivate _destroyed = false;\n\n\tconstructor(configuration: IdentityDocConfiguration) {\n\t\tsuper();\n\t\tthis.config = configuration;\n\t\tthis.docId = deriveIdentityDocId(configuration.publicKey);\n\t\tthis.document = new Y.Doc({ guid: this.docId });\n\n\t\tif (configuration.autoConnect !== false) {\n\t\t\tthis.connect();\n\t\t}\n\t}\n\n\t// ── Connection Management ────────────────────────────────────────────────\n\n\tconnect(): void {\n\t\tif (this._destroyed) return;\n\n\t\tconst targets: Array<{ url: string; key: string }> = [];\n\n\t\tif (this.config.localServerUrl) {\n\t\t\ttargets.push({ url: this.config.localServerUrl, key: \"local\" });\n\t\t}\n\t\tif (this.config.syncServerUrl) {\n\t\t\ttargets.push({ url: this.config.syncServerUrl, key: \"sync\" });\n\t\t}\n\n\t\tfor (const { url, key } of targets) {\n\t\t\tif (this.providers.has(key)) continue;\n\t\t\tthis.connectToServer(key, url);\n\t\t}\n\n\t\tif (this.config.webrtc && !this.webrtc) {\n\t\t\tthis._connectWebRTC();\n\t\t}\n\t}\n\n\tconnectToServer(key: string, serverUrl: string): void {\n\t\tif (this._destroyed) return;\n\n\t\t// Tear down existing connection for this key (idempotent reconnect)\n\t\tconst existingProvider = this.providers.get(key);\n\t\tif (existingProvider) {\n\t\t\texistingProvider.destroy();\n\t\t\tthis.providers.delete(key);\n\t\t}\n\t\tconst existingWs = this.websockets.get(key);\n\t\tif (existingWs) {\n\t\t\texistingWs.destroy();\n\t\t\tthis.websockets.delete(key);\n\t\t}\n\n\t\tconst token =\n\t\t\tthis.config.tokens?.[serverUrl] ?? this.config.token ?? \"\";\n\n\t\tconst wsUrl = serverUrl\n\t\t\t.replace(/^http/, \"ws\")\n\t\t\t.replace(/\\/$/, \"\")\n\t\t\t.concat(\"/ws\");\n\n\t\tconst ws = new AbracadabraWS({ url: wsUrl, WebSocketPolyfill: undefined as any });\n\t\tthis.websockets.set(key, ws);\n\n\t\tconst providerConfig: AbracadabraProviderConfiguration = {\n\t\t\tname: this.docId,\n\t\t\tdocument: this.document,\n\t\t\twebsocketProvider: ws,\n\t\t\tserverAgnostic: true,\n\t\t\tdisableOfflineStore: key !== \"local\" && key !== \"sync\"\n\t\t\t\t? true\n\t\t\t\t: this.config.disableOfflineStore ?? false,\n\t\t\t...this.config.providerDefaults,\n\t\t};\n\n\t\t// Use crypto identity auth if available, otherwise JWT token\n\t\tif (this.config.cryptoIdentity && this.config.signChallenge) {\n\t\t\tproviderConfig.cryptoIdentity = this.config.cryptoIdentity;\n\t\t\tproviderConfig.signChallenge = this.config.signChallenge;\n\t\t} else {\n\t\t\tproviderConfig.token = token;\n\t\t}\n\n\t\tconst provider = new AbracadabraProvider(providerConfig);\n\n\t\tprovider.on(\"synced\", () => this.emit(\"synced\", { server: key }));\n\t\tprovider.on(\"status\", (data: any) =>\n\t\t\tthis.emit(\"status\", { server: key, ...data }),\n\t\t);\n\n\t\tthis.providers.set(key, provider);\n\t}\n\n\tprivate _connectWebRTC(): void {\n\t\tconst rtcConfig = this.config.webrtc;\n\t\tif (!rtcConfig) return;\n\n\t\tthis.webrtc = new AbracadabraWebRTC({\n\t\t\tdocId: this.docId,\n\t\t\turl: rtcConfig.signalingServerUrl,\n\t\t\ttoken: rtcConfig.token,\n\t\t\tdocument: this.document,\n\t\t\tenableDocSync: true,\n\t\t\tenableAwarenessSync: false,\n\t\t\tenableFileTransfer: false,\n\t\t\te2ee: rtcConfig.e2ee,\n\t\t\ticeServers: rtcConfig.iceServers,\n\t\t});\n\t}\n\n\t// ── Y.Doc Schema Accessors ───────────────────────────────────────────────\n\n\tget profileMap(): Y.Map<string> {\n\t\treturn this.document.getMap(\"profile\");\n\t}\n\n\tget serversMap(): Y.Map<Y.Map<any>> {\n\t\treturn this.document.getMap(\"servers\");\n\t}\n\n\tget spacesArray(): Y.Array<Y.Map<any>> {\n\t\treturn this.document.getArray(\"spaces\");\n\t}\n\n\tget pluginsMap(): Y.Map<any> {\n\t\treturn this.document.getMap(\"plugins\");\n\t}\n\n\tget devicesMap(): Y.Map<Y.Map<any>> {\n\t\treturn this.document.getMap(\"devices\");\n\t}\n\n\tget preferencesMap(): Y.Map<any> {\n\t\treturn this.document.getMap(\"preferences\");\n\t}\n\n\t// ── Profile ──────────────────────────────────────────────────────────────\n\n\tgetProfile(): IdentityProfile {\n\t\tconst m = this.profileMap;\n\t\treturn {\n\t\t\tusername: m.get(\"username\"),\n\t\t\tdisplayName: m.get(\"displayName\"),\n\t\t\tcolorName: m.get(\"colorName\"),\n\t\t\tneutralColorName: m.get(\"neutralColorName\"),\n\t\t\tlocale: m.get(\"locale\"),\n\t\t\tavatarUrl: m.get(\"avatarUrl\"),\n\t\t};\n\t}\n\n\tsetProfile(profile: Partial<IdentityProfile>): void {\n\t\tconst m = this.profileMap;\n\t\tthis.document.transact(() => {\n\t\t\tfor (const [key, value] of Object.entries(profile)) {\n\t\t\t\tif (value !== undefined) {\n\t\t\t\t\tm.set(key, value);\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t}\n\n\t// ── Servers ──────────────────────────────────────────────────────────────\n\n\tgetServer(url: string): IdentityServerEntry | undefined {\n\t\tconst entry = this.serversMap.get(url);\n\t\tif (!entry) return undefined;\n\t\treturn {\n\t\t\tlabel: entry.get(\"label\") ?? url,\n\t\t\thubDocId: entry.get(\"hubDocId\"),\n\t\t\tentryDocId: entry.get(\"entryDocId\"),\n\t\t\tdefaultRole: entry.get(\"defaultRole\"),\n\t\t\tspacesEnabled: entry.get(\"spacesEnabled\"),\n\t\t\taddedAt: entry.get(\"addedAt\") ?? 0,\n\t\t};\n\t}\n\n\tsetServer(url: string, entry: IdentityServerEntry): void {\n\t\tconst m = this.serversMap;\n\t\tthis.document.transact(() => {\n\t\t\tlet yEntry = m.get(url);\n\t\t\tif (!yEntry) {\n\t\t\t\tyEntry = new Y.Map();\n\t\t\t\tm.set(url, yEntry);\n\t\t\t}\n\t\t\tfor (const [key, value] of Object.entries(entry)) {\n\t\t\t\tif (value !== undefined) {\n\t\t\t\t\tyEntry.set(key, value);\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t}\n\n\tremoveServer(url: string): void {\n\t\tthis.serversMap.delete(url);\n\t}\n\n\tgetServers(): Map<string, IdentityServerEntry> {\n\t\tconst result = new Map<string, IdentityServerEntry>();\n\t\tthis.serversMap.forEach((entry, url) => {\n\t\t\tresult.set(url, {\n\t\t\t\tlabel: entry.get(\"label\") ?? url,\n\t\t\t\thubDocId: entry.get(\"hubDocId\"),\n\t\t\t\tentryDocId: entry.get(\"entryDocId\"),\n\t\t\t\tdefaultRole: entry.get(\"defaultRole\"),\n\t\t\t\tspacesEnabled: entry.get(\"spacesEnabled\"),\n\t\t\t\taddedAt: entry.get(\"addedAt\") ?? 0,\n\t\t\t});\n\t\t});\n\t\treturn result;\n\t}\n\n\t// ── Spaces ───────────────────────────────────────────────────────────────\n\n\tgetSpaces(): IdentitySpaceEntry[] {\n\t\tconst result: IdentitySpaceEntry[] = [];\n\t\tthis.spacesArray.forEach((yMap) => {\n\t\t\tresult.push({\n\t\t\t\tid: yMap.get(\"id\"),\n\t\t\t\tname: yMap.get(\"name\"),\n\t\t\t\ttype: yMap.get(\"type\") ?? \"remote\",\n\t\t\t\tserverUrl: yMap.get(\"serverUrl\") ?? null,\n\t\t\t\tdocId: yMap.get(\"docId\"),\n\t\t\t\tremoteSpaceId: yMap.get(\"remoteSpaceId\"),\n\t\t\t\tvisibility: yMap.get(\"visibility\") ?? \"private\",\n\t\t\t\tisHub: yMap.get(\"isHub\") ?? false,\n\t\t\t\torder: yMap.get(\"order\") ?? 0,\n\t\t\t\tlastSyncedAt: yMap.get(\"lastSyncedAt\"),\n\t\t\t\tcreatedAt: yMap.get(\"createdAt\") ?? 0,\n\t\t\t});\n\t\t});\n\t\treturn result;\n\t}\n\n\taddSpace(space: IdentitySpaceEntry): void {\n\t\tconst yMap = new Y.Map();\n\t\tthis.document.transact(() => {\n\t\t\tfor (const [key, value] of Object.entries(space)) {\n\t\t\t\tif (value !== undefined) {\n\t\t\t\t\tyMap.set(key, value);\n\t\t\t\t}\n\t\t\t}\n\t\t\tthis.spacesArray.push([yMap]);\n\t\t});\n\t}\n\n\tremoveSpace(spaceId: string): void {\n\t\tconst arr = this.spacesArray;\n\t\tfor (let i = 0; i < arr.length; i++) {\n\t\t\tif (arr.get(i).get(\"id\") === spaceId) {\n\t\t\t\tarr.delete(i, 1);\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\t}\n\n\tupdateSpace(spaceId: string, updates: Partial<IdentitySpaceEntry>): void {\n\t\tconst arr = this.spacesArray;\n\t\tfor (let i = 0; i < arr.length; i++) {\n\t\t\tconst yMap = arr.get(i);\n\t\t\tif (yMap.get(\"id\") === spaceId) {\n\t\t\t\tthis.document.transact(() => {\n\t\t\t\t\tfor (const [key, value] of Object.entries(updates)) {\n\t\t\t\t\t\tif (value !== undefined) {\n\t\t\t\t\t\t\tyMap.set(key, value);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\t}\n\n\t// ── Plugins ──────────────────────────────────────────────────────────────\n\n\tgetExternalPlugins(): Y.Array<Y.Map<any>> {\n\t\tlet arr = this.pluginsMap.get(\"external\") as Y.Array<Y.Map<any>> | undefined;\n\t\tif (!arr) {\n\t\t\tarr = new Y.Array();\n\t\t\tthis.pluginsMap.set(\"external\", arr);\n\t\t}\n\t\treturn arr;\n\t}\n\n\tgetDisabledBuiltins(): Y.Array<string> {\n\t\tlet arr = this.pluginsMap.get(\"disabledBuiltins\") as Y.Array<string> | undefined;\n\t\tif (!arr) {\n\t\t\tarr = new Y.Array();\n\t\t\tthis.pluginsMap.set(\"disabledBuiltins\", arr);\n\t\t}\n\t\treturn arr;\n\t}\n\n\t// ── Preferences ──────────────────────────────────────────────────────────\n\n\tgetPreference<T = any>(key: string): T | undefined {\n\t\treturn this.preferencesMap.get(key);\n\t}\n\n\tsetPreference(key: string, value: any): void {\n\t\tthis.preferencesMap.set(key, value);\n\t}\n\n\t// ── Devices ─────────────────────────────────────────────────────────────\n\n\tgetDevice(publicKey: string): IdentityDeviceEntry | undefined {\n\t\tconst entry = this.devicesMap.get(publicKey);\n\t\tif (!entry) return undefined;\n\t\tconst servers = new Map<string, DeviceServerStatus>();\n\t\tconst serversYMap = entry.get(\"servers\") as Y.Map<Y.Map<any>> | undefined;\n\t\tif (serversYMap) {\n\t\t\tserversYMap.forEach((sEntry, url) => {\n\t\t\t\tservers.set(url, {\n\t\t\t\t\tregistered: sEntry.get(\"registered\") ?? false,\n\t\t\t\t\tregisteredAt: sEntry.get(\"registeredAt\") ?? null,\n\t\t\t\t\tkeyId: sEntry.get(\"keyId\") ?? null,\n\t\t\t\t\tlastVerifiedAt: sEntry.get(\"lastVerifiedAt\") ?? null,\n\t\t\t\t\terror: sEntry.get(\"error\") ?? null,\n\t\t\t\t});\n\t\t\t});\n\t\t}\n\t\treturn {\n\t\t\tdeviceName: entry.get(\"deviceName\") ?? \"Unknown\",\n\t\t\ttier: entry.get(\"tier\") ?? \"paired\",\n\t\t\tx25519Key: entry.get(\"x25519Key\") ?? null,\n\t\t\taddedAt: entry.get(\"addedAt\") ?? 0,\n\t\t\trevokedAt: entry.get(\"revokedAt\") ?? null,\n\t\t\trevokedBy: entry.get(\"revokedBy\") ?? null,\n\t\t\tservers,\n\t\t};\n\t}\n\n\tgetDevices(): Map<string, IdentityDeviceEntry> {\n\t\tconst result = new Map<string, IdentityDeviceEntry>();\n\t\tthis.devicesMap.forEach((_entry, pubKey) => {\n\t\t\tconst device = this.getDevice(pubKey);\n\t\t\tif (device) result.set(pubKey, device);\n\t\t});\n\t\treturn result;\n\t}\n\n\taddDevice(\n\t\tpublicKey: string,\n\t\topts: {\n\t\t\tdeviceName: string;\n\t\t\ttier: DeviceTier;\n\t\t\tx25519Key?: string;\n\t\t\tserverUrl?: string;\n\t\t\tkeyId?: string;\n\t\t},\n\t): void {\n\t\tthis.document.transact(() => {\n\t\t\tlet entry = this.devicesMap.get(publicKey);\n\t\t\tif (!entry) {\n\t\t\t\tentry = new Y.Map();\n\t\t\t\tthis.devicesMap.set(publicKey, entry);\n\t\t\t}\n\t\t\tentry.set(\"deviceName\", opts.deviceName);\n\t\t\tentry.set(\"tier\", opts.tier);\n\t\t\tif (opts.x25519Key) entry.set(\"x25519Key\", opts.x25519Key);\n\t\t\tentry.set(\"addedAt\", Date.now());\n\t\t\tentry.set(\"revokedAt\", null);\n\t\t\tentry.set(\"revokedBy\", null);\n\n\t\t\tif (opts.serverUrl) {\n\t\t\t\tlet servers = entry.get(\"servers\") as Y.Map<Y.Map<any>> | undefined;\n\t\t\t\tif (!servers) {\n\t\t\t\t\tservers = new Y.Map();\n\t\t\t\t\tentry.set(\"servers\", servers);\n\t\t\t\t}\n\t\t\t\tconst sEntry = new Y.Map();\n\t\t\t\tsEntry.set(\"registered\", true);\n\t\t\t\tsEntry.set(\"registeredAt\", Date.now());\n\t\t\t\tsEntry.set(\"keyId\", opts.keyId ?? null);\n\t\t\t\tsEntry.set(\"lastVerifiedAt\", Date.now());\n\t\t\t\tsEntry.set(\"error\", null);\n\t\t\t\tservers.set(opts.serverUrl, sEntry);\n\t\t\t}\n\t\t});\n\t}\n\n\trevokeDevice(publicKey: string, revokedBy: string): void {\n\t\tconst entry = this.devicesMap.get(publicKey);\n\t\tif (!entry) return;\n\t\tthis.document.transact(() => {\n\t\t\tentry.set(\"revokedAt\", Date.now());\n\t\t\tentry.set(\"revokedBy\", revokedBy);\n\t\t});\n\t}\n\n\tsetDeviceServerStatus(\n\t\tdevicePubKey: string,\n\t\tserverUrl: string,\n\t\tstatus: Partial<DeviceServerStatus>,\n\t): void {\n\t\tconst entry = this.devicesMap.get(devicePubKey);\n\t\tif (!entry) return;\n\t\tthis.document.transact(() => {\n\t\t\tlet servers = entry.get(\"servers\") as Y.Map<Y.Map<any>> | undefined;\n\t\t\tif (!servers) {\n\t\t\t\tservers = new Y.Map();\n\t\t\t\tentry.set(\"servers\", servers);\n\t\t\t}\n\t\t\tlet sEntry = servers.get(serverUrl);\n\t\t\tif (!sEntry) {\n\t\t\t\tsEntry = new Y.Map();\n\t\t\t\tsEntry.set(\"registered\", false);\n\t\t\t\tsEntry.set(\"registeredAt\", null);\n\t\t\t\tsEntry.set(\"keyId\", null);\n\t\t\t\tsEntry.set(\"lastVerifiedAt\", null);\n\t\t\t\tsEntry.set(\"error\", null);\n\t\t\t\tservers.set(serverUrl, sEntry);\n\t\t\t}\n\t\t\tfor (const [key, value] of Object.entries(status)) {\n\t\t\t\tif (value !== undefined) {\n\t\t\t\t\tsEntry.set(key, value);\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t}\n\n\t// ── Observation ──────────────────────────────────────────────────────────\n\n\t/**\n\t * Observe deep changes on a specific top-level map.\n\t * Returns an unsubscribe function.\n\t */\n\tobserve(\n\t\tmapName: \"profile\" | \"servers\" | \"plugins\" | \"preferences\" | \"devices\",\n\t\tcallback: (events: Y.YEvent<any>[], transaction: Y.Transaction) => void,\n\t): () => void {\n\t\tconst map = this.document.getMap(mapName);\n\t\tmap.observeDeep(callback);\n\t\treturn () => map.unobserveDeep(callback);\n\t}\n\n\t/**\n\t * Observe changes to the spaces array.\n\t * Returns an unsubscribe function.\n\t */\n\tobserveSpaces(\n\t\tcallback: (event: Y.YArrayEvent<Y.Map<any>>, transaction: Y.Transaction) => void,\n\t): () => void {\n\t\tconst arr = this.spacesArray;\n\t\tarr.observe(callback);\n\t\treturn () => arr.unobserve(callback);\n\t}\n\n\t// ── Migration ────────────────────────────────────────────────────────────\n\n\t/**\n\t * Returns true if the identity doc has no profile data yet (first use).\n\t * Call this to decide whether to run migration from localStorage.\n\t */\n\tisEmpty(): boolean {\n\t\treturn this.profileMap.size === 0 && this.serversMap.size === 0;\n\t}\n\n\t// ── Lifecycle ────────────────────────────────────────────────────────────\n\n\t/**\n\t * Enable WebRTC P2P sync at runtime.\n\t * Use this for claimed/passkey users where E2EE identity derivation\n\t * was deferred to avoid biometric prompts on page load.\n\t */\n\tenableWebRTC(webrtcConfig: NonNullable<IdentityDocConfiguration[\"webrtc\"]>): void {\n\t\tif (this._destroyed || this.webrtc) return;\n\t\tthis.config = { ...this.config, webrtc: webrtcConfig };\n\t\tthis._connectWebRTC();\n\t}\n\n\t/**\n\t * Update the sync server URL at runtime (e.g. when user changes their\n\t * designated sync server in settings).\n\t */\n\tsetSyncServer(url: string | null): void {\n\t\t// Tear down existing sync provider if any.\n\t\tconst existing = this.providers.get(\"sync\");\n\t\tif (existing) {\n\t\t\texisting.destroy();\n\t\t\tthis.providers.delete(\"sync\");\n\t\t}\n\t\tconst existingWs = this.websockets.get(\"sync\");\n\t\tif (existingWs) {\n\t\t\texistingWs.destroy();\n\t\t\tthis.websockets.delete(\"sync\");\n\t\t}\n\n\t\tif (url) {\n\t\t\tthis.config = { ...this.config, syncServerUrl: url };\n\t\t\tthis.connectToServer(\"sync\", url);\n\t\t}\n\t}\n\n\tgetProvider(key: string): AbracadabraProvider | undefined {\n\t\treturn this.providers.get(key);\n\t}\n\n\tdestroy(): void {\n\t\tif (this._destroyed) return;\n\t\tthis._destroyed = true;\n\n\t\tfor (const [, provider] of this.providers) {\n\t\t\tprovider.destroy();\n\t\t}\n\t\tfor (const [, ws] of this.websockets) {\n\t\t\tws.destroy();\n\t\t}\n\t\tif (this.webrtc) {\n\t\t\t(this.webrtc as any).disconnect?.();\n\t\t}\n\n\t\tthis.providers.clear();\n\t\tthis.websockets.clear();\n\t\tthis.webrtc = null;\n\t\tthis.document.destroy();\n\t}\n}\n","import type {\n\tUserProfile,\n\tDocumentMeta,\n\tUploadMeta,\n\tUploadInfo,\n\tThumbnailOptions,\n\tStreamTokenInfo,\n\tPublicKeyInfo,\n\tPermissionEntry,\n\tEffectivePermissionsResponse,\n\tHealthStatus,\n\tReadyzStatus,\n\tServerInfo,\n\tInviteRow,\n\tSnapshotMeta,\n\tSnapshotData,\n\tSnapshotCreateResult,\n\tSnapshotRestoreResult,\n\tSnapshotForkResult,\n\tDocBacklink,\n\tDocSearchHit,\n\tAuditLogEntry,\n\tAuditQueryOpts,\n\tAuditVerifyResult,\n\tAdminConfigField,\n\tEnvSnapshotResponse,\n} from \"./types.ts\";\nimport { Kind, SERVER_ROOT_ID } from \"./types.ts\";\nimport type { DocEncryptionInfo } from \"./types.ts\";\nimport type { DocumentCache } from \"./DocumentCache.ts\";\nimport type { ServerResetOutcome } from \"./ServerReset.ts\";\nimport { dropCachesIfServerReplaced } from \"./ServerReset.ts\";\nimport { deriveDmDocId } from \"./IdentityDoc.ts\";\n\nfunction fromBase64(b64: string): Uint8Array {\n\treturn Uint8Array.from(atob(b64), (c) => c.charCodeAt(0));\n}\n\n/**\n * Decode a base64url-encoded string (e.g. a JWT header/payload segment) to\n * UTF-8 text. `atob` only accepts standard base64, so we translate the\n * url-safe alphabet (`-`/`_`) and re-pad before decoding — otherwise a\n * perfectly valid token whose payload happens to contain `-` or `_` throws\n * and gets misclassified as invalid/expired.\n */\nfunction decodeBase64UrlToString(b64url: string): string {\n\tlet b64 = b64url.replace(/-/g, \"+\").replace(/_/g, \"/\");\n\tconst pad = b64.length % 4;\n\tif (pad) b64 += \"=\".repeat(4 - pad);\n\tconst bytes = Uint8Array.from(atob(b64), (c) => c.charCodeAt(0));\n\treturn new TextDecoder().decode(bytes);\n}\n\n/**\n * Reason classifications surfaced to `onAuthFailed`. Consumers can decide\n * whether to silently re-register the keypair (`user_not_found`) or\n * surface a hard block (`account_revoked`, `forbidden`).\n */\nexport type AuthFailureReason =\n\t| \"user_not_found\"\n\t| \"account_revoked\"\n\t| \"forbidden\"\n\t| \"unauthorized\";\n\nexport interface AuthFailureContext {\n\t/** HTTP status code from the failed request. */\n\tstatus: number;\n\t/** Server-provided error message verbatim. */\n\tmessage: string;\n\t/** Best-guess classification from the message text. */\n\treason: AuthFailureReason;\n\t/** Method + path of the failed request, useful for debugging. */\n\tmethod: string;\n\tpath: string;\n}\n\nexport interface AbracadabraClientConfig {\n\t/** Server base URL (http or https). WebSocket URL is derived automatically. */\n\turl: string;\n\t/** Initial JWT token. If omitted and persistAuth is true, loads from storage. */\n\ttoken?: string;\n\t/** Persist JWT to localStorage for stay-logged-in. Default: true in browser. */\n\tpersistAuth?: boolean;\n\t/** localStorage key for token persistence. Default: \"abracadabra:auth\". */\n\tstorageKey?: string;\n\t/** Custom fetch implementation (useful for Node.js or testing). */\n\tfetch?: typeof globalThis.fetch;\n\t/**\n\t * Optional metadata cache. When provided, read methods (getDoc, listChildren,\n\t * getMe, listPermissions, listUploads) check the cache before hitting the\n\t * network. Write methods (deleteDoc, upload, deleteUpload) invalidate affected\n\t * cache entries automatically.\n\t */\n\tcache?: DocumentCache;\n\t/**\n\t * Called whenever a REST call returns 401/403 with a recoverable reason\n\t * (typically \"user not found\" — server's DB was wiped or repointed).\n\t * Consumers wire this to their reauth path (in cou-sh: `_reauthFn`)\n\t * so silently-failing background fetches still trigger key re-registration\n\t * without waiting for the next WS action to surface the problem.\n\t *\n\t * The callback runs OUT-OF-BAND of the failing request — the original\n\t * Promise still rejects so callers handle their own error path.\n\t * Long-running auth handlers should debounce or short-circuit duplicate\n\t * concurrent invocations.\n\t */\n\tonAuthFailed?: (ctx: AuthFailureContext) => void;\n\t/**\n\t * How long before a token's `exp` the session is re-minted, in ms.\n\t *\n\t * Only meaningful once a session renewer is installed — which\n\t * {@link AbracadabraClient.loginWithKey} does for you. Capped at a third of\n\t * the token's own lifetime, so a server issuing short-lived tokens is not\n\t * re-authenticated on every check.\n\t *\n\t * Default 20 minutes: comfortably inside the server's 4-hour crypto-auth\n\t * TTL and wider than any polling interval a consumer is likely to run.\n\t */\n\ttokenRenewMarginMs?: number;\n\t/**\n\t * Fallback interval, in ms, for a token whose `exp` cannot be read.\n\t * Default 60s.\n\t *\n\t * Renewal is normally scheduled from the token's own expiry, so this is not\n\t * a poll. `0` disables the timer entirely — the session is then renewed\n\t * only on demand (before a socket handshake, or an explicit\n\t * {@link AbracadabraClient.ensureFreshToken}).\n\t */\n\ttokenRenewCheckMs?: number;\n}\n\n/**\n * Read a JWT's `exp` / `iat` claims, in ms. `0` for anything unreadable.\n *\n * Deliberately tolerant: a token this cannot parse is treated as expiring now,\n * which costs one extra handshake and never costs a dead session.\n */\nfunction readJwtTimes(token: string | null): { exp: number; iat: number } {\n\tif (!token) return { exp: 0, iat: 0 };\n\tconst payload = token.split(\".\")[1];\n\tif (!payload) return { exp: 0, iat: 0 };\n\ttry {\n\t\tconst claims = JSON.parse(decodeBase64UrlToString(payload)) as {\n\t\t\texp?: unknown;\n\t\t\tiat?: unknown;\n\t\t};\n\t\treturn {\n\t\t\texp: typeof claims.exp === \"number\" ? claims.exp * 1000 : 0,\n\t\t\tiat: typeof claims.iat === \"number\" ? claims.iat * 1000 : 0,\n\t\t};\n\t} catch {\n\t\treturn { exp: 0, iat: 0 };\n\t}\n}\n\nexport class AbracadabraClient {\n\tprivate _token: string | null;\n\tprivate readonly baseUrl: string;\n\tprivate readonly persistAuth: boolean;\n\tprivate readonly storageKey: string;\n\tprivate readonly _fetch: typeof globalThis.fetch;\n\treadonly cache: DocumentCache | null;\n\tprivate readonly _onAuthFailed: ((ctx: AuthFailureContext) => void) | null;\n\t/** Single-flight for root listings (`/docs?root=true`) — the per-row\n\t * permission cascade makes this a multi-second / hundreds-of-KB call on\n\t * a busy server, and a connect burst fires several identical ones.\n\t * Keyed by the kind filter; cleared when the request settles. */\n\tprivate readonly rootListInflight = new Map<\n\t\tstring,\n\t\tPromise<DocumentMeta[]>\n\t>();\n\t/** Cached media-stream grants (`getStreamUrl`), keyed `docId/uploadId`.\n\t * Re-minted just before expiry and dropped whenever the session token\n\t * changes — a stream token inherits the identity that minted it. */\n\tprivate readonly streamTokens = new Map<\n\t\tstring,\n\t\t{ url: string; expiresAt: number }\n\t>();\n\t/** In-flight mints, keyed like `streamTokens` — collapses the burst a page\n\t * of media blocks produces into one request per upload. */\n\tprivate readonly streamTokenInflight = new Map<string, Promise<string>>();\n\n\t// ── Session renewal ──────────────────────────────────────────────────────\n\t//\n\t// A crypto-auth JWT is SHORT-LIVED — the server mints it with\n\t// `auth.jwt_token_ttl_crypto_secs`, four hours by default, on the stated\n\t// reasoning that \"devices can silently re-authenticate\". Until this existed\n\t// nothing did: a client logged in once and held that token for as long as\n\t// the process (or the tab) lived.\n\t//\n\t// What that costs is worth stating, because the failure is split and neither\n\t// half looks like an auth problem:\n\t//\n\t// - An ALREADY-OPEN socket keeps working for an elevated (service/admin)\n\t// session, because `SyncSession::is_jwt_expired` waves those through, and\n\t// `MSG_STATELESS` is exempt for every session. So chat and presence carry\n\t// on and the client looks completely alive. For an ordinary session the\n\t// first sync or awareness frame past `exp` drops the socket, and it then\n\t// reconnect-storms with the same dead token.\n\t// - Every NEW socket is refused at the handshake — the server logs\n\t// `auth rejected: JWT error: ExpiredSignature` — and the provider simply\n\t// never syncs. Anything that opens a provider per document (an SSR doc\n\t// cache, a background indexer, a Node runner visiting a page) stops\n\t// working entirely, four hours in, with `Sync timed out` as its only\n\t// symptom.\n\t//\n\t// Two mechanisms, and both are needed. `ensureFreshToken()` re-mints before\n\t// `exp` and is awaited by the provider's own token closure, so no handshake\n\t// ever carries a stale token. And every token change is broadcast, so an\n\t// open socket can be re-armed in place with the server's `auth:refresh`\n\t// frame rather than being dropped and rebuilt.\n\tprivate _renew: (() => Promise<string>) | null = null;\n\tprivate _renewing: Promise<boolean> | null = null;\n\tprivate _renewTimer: ReturnType<typeof setTimeout> | null = null;\n\tprivate readonly _tokenListeners = new Set<(token: string) => void>();\n\tprivate readonly renewMarginMs: number;\n\tprivate readonly renewCheckMs: number;\n\n\tconstructor(config: AbracadabraClientConfig) {\n\t\tthis.baseUrl = config.url.replace(/\\/+$/, \"\");\n\t\tthis.persistAuth = config.persistAuth ?? typeof localStorage !== \"undefined\";\n\t\tthis.storageKey = config.storageKey ?? \"abracadabra:auth\";\n\t\tthis._fetch = config.fetch ?? globalThis.fetch.bind(globalThis);\n\t\tthis.cache = config.cache ?? null;\n\t\tthis._onAuthFailed = config.onAuthFailed ?? null;\n\t\tthis.renewMarginMs = config.tokenRenewMarginMs ?? 20 * 60_000;\n\t\tthis.renewCheckMs = config.tokenRenewCheckMs ?? 60_000;\n\n\t\t// Load token: explicit > persisted > null\n\t\tthis._token = config.token ?? this.loadPersistedToken() ?? null;\n\t}\n\n\t// ── Token management ─────────────────────────────────────────────────────\n\n\tget token(): string | null {\n\t\treturn this._token;\n\t}\n\n\tset token(value: string | null) {\n\t\tconst changed = value !== this._token;\n\t\tthis._token = value;\n\t\t// Stream grants carry the old identity (and die with it on\n\t\t// logout-all) — never serve one across a session change.\n\t\tthis.streamTokens.clear();\n\t\tthis.streamTokenInflight.clear();\n\t\tif (this.persistAuth) {\n\t\t\tif (value) {\n\t\t\t\tthis.persistToken(value);\n\t\t\t} else {\n\t\t\t\tthis.clearPersistedToken();\n\t\t\t}\n\t\t}\n\t\t// Every auth path in this class assigns through here — login, verify,\n\t\t// a device refresh, a key revocation, a renewal — so this is the one\n\t\t// place a provider needs to watch to keep an OPEN socket armed. A\n\t\t// listener that throws is its own problem and must not break the login\n\t\t// that produced the token.\n\t\tif (changed && value) {\n\t\t\t// A new token has a new deadline. Re-arming here rather than only\n\t\t\t// inside the renewal covers every other path that adopts one — a\n\t\t\t// password login, a device refresh, a key revocation.\n\t\t\tthis.scheduleSessionRenewal();\n\t\t\tfor (const listener of this._tokenListeners) {\n\t\t\t\ttry {\n\t\t\t\t\tlistener(value);\n\t\t\t\t} catch {\n\t\t\t\t\t/* a consumer's listener must not break authentication */\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tget isAuthenticated(): boolean {\n\t\treturn this._token !== null;\n\t}\n\n\t/** Check if the current JWT token is present and not expired. */\n\tisTokenValid(): boolean {\n\t\tif (!this._token) return false;\n\t\ttry {\n\t\t\tconst [, payload] = this._token.split(\".\");\n\t\t\t// JWT payloads are base64url — `atob` only handles standard base64,\n\t\t\t// so a payload containing `-` or `_` would throw and a valid token\n\t\t\t// would be misread as expired, forcing a spurious re-auth.\n\t\t\tconst { exp } = JSON.parse(decodeBase64UrlToString(payload));\n\t\t\treturn typeof exp === \"number\" && exp * 1000 > Date.now();\n\t\t} catch {\n\t\t\treturn false;\n\t\t}\n\t}\n\n\t/** When the current token stops validating, in ms. `0` when unknown. */\n\tget tokenExpiresAt(): number {\n\t\treturn readJwtTimes(this._token).exp;\n\t}\n\n\t/**\n\t * Install the way this client re-authenticates itself, or `null` to stop.\n\t *\n\t * {@link loginWithKey} installs one for you, so a key-authenticated client\n\t * — every Node runner, and every browser session on a crypto identity —\n\t * renews without its consumer doing anything. Install one by hand for a\n\t * password session or any other flow that can mint a fresh token.\n\t *\n\t * The function must return the new JWT; adopting it (and notifying open\n\t * sockets) is this client's job.\n\t */\n\tsetSessionRenewer(renew: (() => Promise<string>) | null): void {\n\t\tthis._renew = renew;\n\t\tif (renew) this.scheduleSessionRenewal();\n\t\telse this.stopSessionRenewal();\n\t}\n\n\t/** Whether this client knows how to re-authenticate itself. */\n\tget canRenewSession(): boolean {\n\t\treturn this._renew !== null;\n\t}\n\n\t/**\n\t * Called whenever the session token changes — a login, a renewal, a device\n\t * refresh, a key revocation. Providers use this to re-arm sockets that are\n\t * already open. Returns an unsubscribe function.\n\t */\n\tonTokenChanged(listener: (token: string) => void): () => void {\n\t\tthis._tokenListeners.add(listener);\n\t\treturn () => this._tokenListeners.delete(listener);\n\t}\n\n\t/**\n\t * Make sure the token has life left in it, re-minting if it does not.\n\t *\n\t * Cheap when the token is fresh — one subtraction — so callers need not\n\t * reason about when the last renewal was, and concurrent callers share one\n\t * handshake. Returns whether the session is believed good; `false` is not\n\t * fatal, and the caller's own failure is still the authority.\n\t */\n\tasync ensureFreshToken(marginMs?: number): Promise<boolean> {\n\t\tif (!this._renew) return this.isTokenValid();\n\t\tif (this._renewing) return this._renewing;\n\n\t\tconst { exp } = readJwtTimes(this._token);\n\t\tif (exp > 0 && exp - Date.now() > this.renewMargin(marginMs)) return true;\n\n\t\t// Captured before the closure: `setSessionRenewer(null)` may land while\n\t\t// this is in flight, and a renewal that read `this._renew` at await time\n\t\t// would then throw instead of finishing the handshake it started.\n\t\tconst mint = this._renew;\n\t\tconst renew = (async (): Promise<boolean> => {\n\t\t\ttry {\n\t\t\t\tconst token = await mint();\n\t\t\t\t// `verify()` (and therefore `loginWithKey`) already adopts the\n\t\t\t\t// token through the setter, which is what notifies listeners.\n\t\t\t\t// Assigning again would be a second, identical notification.\n\t\t\t\tif (token && token !== this._token) this.token = token;\n\t\t\t\treturn true;\n\t\t\t} catch {\n\t\t\t\t// Do NOT push the expiry out on failure: the next caller must\n\t\t\t\t// try again rather than believe a renewal that did not happen.\n\t\t\t\treturn false;\n\t\t\t} finally {\n\t\t\t\tthis._renewing = null;\n\t\t\t}\n\t\t})();\n\t\tthis._renewing = renew;\n\t\treturn renew;\n\t}\n\n\t/**\n\t * How long before `exp` this session is re-minted.\n\t *\n\t * Capped at a third of the token's own lifetime, so a server configured\n\t * with short-lived tokens is not re-authenticated on every check — without\n\t * the cap a 45-second token against a 20-minute margin would mint a new\n\t * session every time anything asked.\n\t */\n\tprivate renewMargin(marginMs?: number): number {\n\t\tconst { exp, iat } = readJwtTimes(this._token);\n\t\tconst lifetime = exp > iat && iat > 0 ? exp - iat : Number.POSITIVE_INFINITY;\n\t\treturn Math.min(marginMs ?? this.renewMarginMs, lifetime / 3);\n\t}\n\n\t/**\n\t * Arm a single timer for the moment this token needs replacing.\n\t *\n\t * Scheduled from the token's OWN expiry rather than on a fixed interval,\n\t * and that is not tidiness. A poll can outrun the margin: measured against\n\t * a server issuing 45-second tokens, a 60-second poll first fired fifteen\n\t * seconds AFTER the token had already lapsed — long enough for the\n\t * awareness heartbeat to hit an expired session and have the socket dropped\n\t * under it. A deadline cannot be outrun by the thing it is a deadline for.\n\t *\n\t * Re-armed on every token change, so a renewal schedules the next one.\n\t */\n\tprivate scheduleSessionRenewal(): void {\n\t\tthis.stopSessionRenewal();\n\t\tif (!this._renew || this.renewCheckMs <= 0) return;\n\t\tconst { exp } = readJwtTimes(this._token);\n\t\t// A token whose expiry cannot be read falls back to the poll interval —\n\t\t// unreadable means \"assume the worst\", not \"stop renewing\".\n\t\tconst delay =\n\t\t\texp > 0\n\t\t\t\t? Math.max(1_000, exp - Date.now() - this.renewMargin())\n\t\t\t\t: this.renewCheckMs;\n\t\t// `setTimeout` treats anything past 2^31-1 ms as zero and fires at once,\n\t\t// which would busy-loop on a long-lived token. Re-arm instead.\n\t\tthis._renewTimer = setTimeout(\n\t\t\t() => {\n\t\t\t\tvoid this.ensureFreshToken()\n\t\t\t\t\t.catch(() => false)\n\t\t\t\t\t// A FAILED renewal must still re-arm, or one flaky moment\n\t\t\t\t\t// costs the session for the life of the process — the exact\n\t\t\t\t\t// shape of failure this mechanism exists to end.\n\t\t\t\t\t.finally(() => this.scheduleSessionRenewal());\n\t\t\t},\n\t\t\tMath.min(delay, 12 * 60 * 60_000),\n\t\t);\n\t\t// Never hold a Node process open for a session nothing is using.\n\t\t(this._renewTimer as { unref?: () => void }).unref?.();\n\t}\n\n\tprivate stopSessionRenewal(): void {\n\t\tif (!this._renewTimer) return;\n\t\tclearTimeout(this._renewTimer);\n\t\tthis._renewTimer = null;\n\t}\n\n\t/**\n\t * Stop renewing and drop every listener. Call when a client is discarded —\n\t * a long-lived consumer that builds one client per connection would\n\t * otherwise leave a timer per discarded client.\n\t */\n\tdestroy(): void {\n\t\tthis.stopSessionRenewal();\n\t\tthis._renew = null;\n\t\tthis._tokenListeners.clear();\n\t}\n\n\t/** Derives ws:// or wss:// URL from the http(s) base URL. */\n\tget wsUrl(): string {\n\t\treturn this.baseUrl\n\t\t\t.replace(/^https:\\/\\//, \"wss://\")\n\t\t\t.replace(/^http:\\/\\//, \"ws://\") + \"/ws\";\n\t}\n\n\t// ── Auth ─────────────────────────────────────────────────────────────────\n\n\t/** Register a new user with password. */\n\tasync register(opts: {\n\t\tusername: string;\n\t\tpassword: string;\n\t\temail?: string;\n\t\tdisplayName?: string;\n\t\tinviteCode?: string;\n\t}): Promise<UserProfile> {\n\t\treturn this.request<UserProfile>(\"POST\", \"/auth/register\", {\n\t\t\tbody: opts,\n\t\t\tauth: false,\n\t\t});\n\t}\n\n\t/**\n\t * Register a new user with an Ed25519 public key (crypto auth).\n\t * Username is optional — if omitted, a short identifier is derived from the key.\n\t */\n\tasync registerWithKey(opts: {\n\t\tpublicKey: string;\n\t\tusername?: string;\n\t\tdeviceName?: string;\n\t\tdisplayName?: string;\n\t\temail?: string;\n\t\tinviteCode?: string;\n\t\t/** X25519 encryption public key paired with the Ed25519 identity key. Required for E2E channels. */\n\t\tx25519Key?: string;\n\t}): Promise<UserProfile> {\n\t\tconst username = opts.username ?? `user-${opts.publicKey.slice(0, 8)}`;\n\t\treturn this.request<UserProfile>(\"POST\", \"/auth/register\", {\n\t\t\tbody: {\n\t\t\t\tusername,\n\t\t\t\tidentityPublicKey: opts.publicKey,\n\t\t\t\tdeviceName: opts.deviceName,\n\t\t\t\tdisplayName: opts.displayName,\n\t\t\t\temail: opts.email,\n\t\t\t\tinviteCode: opts.inviteCode,\n\t\t\t\tx25519Key: opts.x25519Key,\n\t\t\t},\n\t\t\tauth: false,\n\t\t});\n\t}\n\n\t/** Login with username + password. Auto-persists returned token. */\n\tasync login(opts: { username: string; password: string }): Promise<string> {\n\t\tconst res = await this.request<{ token: string }>(\"POST\", \"/auth/login\", {\n\t\t\tbody: opts,\n\t\t\tauth: false,\n\t\t});\n\t\tthis.token = res.token;\n\t\treturn res.token;\n\t}\n\n\t/** Request an Ed25519 crypto auth challenge for the given public key. */\n\tasync challenge(publicKey: string): Promise<{ challenge: string; expiresAt: number }> {\n\t\treturn this.request(\"POST\", \"/auth/challenge\", {\n\t\t\tbody: { publicKey },\n\t\t\tauth: false,\n\t\t});\n\t}\n\n\t/** Verify an Ed25519 signature to complete crypto auth. Auto-persists token. */\n\tasync verify(opts: {\n\t\tpublicKey: string;\n\t\tsignature: string;\n\t\tchallenge: string;\n\t}): Promise<string> {\n\t\tconst res = await this.request<{ token: string }>(\"POST\", \"/auth/verify\", {\n\t\t\tbody: opts,\n\t\t\tauth: false,\n\t\t});\n\t\tthis.token = res.token;\n\t\treturn res.token;\n\t}\n\n\t/**\n\t * Full crypto auth flow: challenge → sign → verify.\n\t * Convenience method combining challenge() + external signing + verify().\n\t */\n\tasync loginWithKey(\n\t\tpublicKey: string,\n\t\tsignChallenge: (challenge: string) => Promise<string>,\n\t): Promise<string> {\n\t\tconst { challenge } = await this.challenge(publicKey);\n\t\tconst signature = await signChallenge(challenge);\n\t\tconst token = await this.verify({ publicKey, signature, challenge });\n\t\t// A key-authenticated session can always mint itself another one — the\n\t\t// signer is right here — so this client becomes self-renewing the\n\t\t// moment it logs in, and no consumer has to remember that the server's\n\t\t// crypto-auth tokens expire in four hours. Installed AFTER `verify`, so\n\t\t// a failed login leaves no renewer behind.\n\t\tthis.setSessionRenewer(() => this.loginWithKey(publicKey, signChallenge));\n\t\treturn token;\n\t}\n\n\t/** Add a new Ed25519 public key to the current user (multi-device). */\n\tasync addKey(opts: { publicKey: string; deviceName?: string; x25519Key?: string }): Promise<void> {\n\t\tawait this.request(\"POST\", \"/auth/keys\", { body: { publicKey: opts.publicKey, deviceName: opts.deviceName, x25519Key: opts.x25519Key } });\n\t}\n\n\t/** List all registered public keys for the current user. */\n\tasync listKeys(): Promise<PublicKeyInfo[]> {\n\t\tconst res = await this.request<{ keys: PublicKeyInfo[] }>(\"GET\", \"/auth/keys\");\n\t\treturn res.keys;\n\t}\n\n\t/** Rename a registered device key. */\n\tasync renameKey(keyId: string, deviceName: string): Promise<void> {\n\t\tawait this.request(\"PATCH\", `/auth/keys/${encodeURIComponent(keyId)}`, { body: { deviceName } });\n\t}\n\n\t/**\n\t * Revoke a public key by its ID. The server treats this as a panic\n\t * action: every outstanding JWT for the account is invalidated (a stolen\n\t * device's token must die immediately, and tokens carry no per-key\n\t * claim), and a fresh token for THIS session is returned and adopted\n\t * automatically — so the device performing the revocation stays\n\t * authenticated while every other device silently re-auths.\n\t */\n\tasync revokeKey(keyId: string): Promise<void> {\n\t\tconst res = await this.request<{ token?: string } | null>(\n\t\t\t\"DELETE\",\n\t\t\t`/auth/keys/${encodeURIComponent(keyId)}`,\n\t\t);\n\t\t// Older servers respond 204 with no body — keep working against them.\n\t\tif (res && typeof res === \"object\" && typeof res.token === \"string\") {\n\t\t\tthis.token = res.token;\n\t\t}\n\t}\n\n\t// ── Device Invites ───────────────────────────────────────────────────────\n\n\t/** Create a single-use device invite code for pairing a new device to this account. */\n\tasync createDeviceInvite(opts?: { expiresIn?: number }): Promise<{ code: string; expiresAt: number }> {\n\t\treturn this.request<{ code: string; expiresAt: number }>(\"POST\", \"/auth/device-invite\", {\n\t\t\tbody: opts?.expiresIn != null ? { expiresIn: opts.expiresIn } : {},\n\t\t});\n\t}\n\n\t/** Redeem a device invite code to register a new device key. Returns a JWT token. */\n\tasync redeemDeviceInvite(opts: {\n\t\tcode: string;\n\t\tpublicKey: string;\n\t\tx25519Key?: string;\n\t\tdeviceName?: string;\n\t}): Promise<{ token: string; user: { id: string; username: string; publicKey: string } }> {\n\t\treturn this.request(\"POST\", \"/auth/device-redeem\", {\n\t\t\tbody: { code: opts.code, publicKey: opts.publicKey, x25519Key: opts.x25519Key, deviceName: opts.deviceName },\n\t\t\tauth: false,\n\t\t});\n\t}\n\n\t// ── Device Sessions ────────────────────────────────────────────────────\n\n\t/** Request a device session token after successful crypto auth. Requires valid JWT. */\n\tasync requestDeviceSession(opts: {\n\t\tpublicKey: string;\n\t\tdeviceName?: string;\n\t}): Promise<{ sessionId: string; sessionToken: string; expiresAt: number }> {\n\t\treturn this.request(\"POST\", \"/auth/device-session\", {\n\t\t\tbody: { publicKey: opts.publicKey, deviceName: opts.deviceName },\n\t\t});\n\t}\n\n\t/** Exchange a device session token for a fresh JWT. No biometric/passkey needed. */\n\tasync refreshWithDeviceSession(sessionToken: string): Promise<string> {\n\t\tconst res = await this.request<{ token: string }>(\"POST\", \"/auth/refresh\", {\n\t\t\tbody: { sessionToken },\n\t\t\tauth: false,\n\t\t});\n\t\tthis.token = res.token;\n\t\treturn res.token;\n\t}\n\n\t/** List active device sessions for the authenticated user. */\n\tasync listDeviceSessions(): Promise<\n\t\tArray<{ id: string; keyId: string; deviceName?: string; issuedAt: number; expiresAt: number; lastUsedAt?: number }>\n\t> {\n\t\tconst res = await this.request<{\n\t\t\tsessions: Array<{ id: string; keyId: string; deviceName?: string; issuedAt: number; expiresAt: number; lastUsedAt?: number }>;\n\t\t}>(\"GET\", \"/auth/device-session\");\n\t\treturn res.sessions;\n\t}\n\n\t/** Revoke a device session by ID. */\n\tasync revokeDeviceSession(sessionId: string): Promise<void> {\n\t\tawait this.request(\"DELETE\", `/auth/device-session/${encodeURIComponent(sessionId)}`);\n\t}\n\n\t// ── Pairing ─────────────────────────────────────────────────────────────\n\n\t/**\n\t * Fetch a short-lived anonymous pairing token for WebRTC signaling.\n\t * No authentication required. The token only grants access to `__pairing_*` rooms.\n\t */\n\tstatic async getPairingToken(serverUrl: string): Promise<string> {\n\t\tlet base = serverUrl;\n\t\twhile (base.endsWith(\"/\")) base = base.slice(0, -1);\n\t\tconst resp = await fetch(`${base}/auth/pairing-token`, { method: \"POST\" });\n\t\tif (!resp.ok) {\n\t\t\tthrow new Error(`Failed to fetch pairing token: ${resp.status}`);\n\t\t}\n\t\tconst { token } = (await resp.json()) as { token: string };\n\t\treturn token;\n\t}\n\n\t// ── Encryption ───────────────────────────────────────────────────────────\n\n\t/** Get encryption info for a document. */\n\tasync getDocEncryption(docId: string): Promise<DocEncryptionInfo> {\n\t\treturn this.request<DocEncryptionInfo>(\"GET\", `/docs/${encodeURIComponent(docId)}/encryption`);\n\t}\n\n\t/** Set the encryption mode for a document (no downgrade). */\n\tasync setDocEncryption(docId: string, mode: \"none\" | \"cse\" | \"e2e\"): Promise<void> {\n\t\tawait this.request(\"PATCH\", `/docs/${encodeURIComponent(docId)}/encryption`, { body: { mode } });\n\t}\n\n\t/** Get the caller's key envelope for a document (for decrypting the DocKey). */\n\tasync getMyKeyEnvelope(docId: string): Promise<{ encrypted_key: string; key_epoch: number } | null> {\n\t\treturn this.requestOrNull<{ encrypted_key: string; key_epoch: number }>(\n\t\t\t\"GET\",\n\t\t\t`/docs/${encodeURIComponent(docId)}/key-envelope`,\n\t\t);\n\t}\n\n\t/** Upload key envelopes for a document (Owner only). */\n\tasync uploadKeyEnvelopes(\n\t\tdocId: string,\n\t\topts: { key_epoch: number; envelopes: { recipient_key_id: string; encrypted_key: string }[] },\n\t): Promise<void> {\n\t\tawait this.request(\"POST\", `/docs/${encodeURIComponent(docId)}/key-envelopes`, { body: opts });\n\t}\n\n\t/** Get the X25519 public key for a user. */\n\tasync getUserX25519Key(userId: string): Promise<string | null> {\n\t\tconst res = await this.requestOrNull<{ x25519_key: string }>(\n\t\t\t\"GET\",\n\t\t\t`/users/${encodeURIComponent(userId)}/x25519-key`,\n\t\t);\n\t\treturn res?.x25519_key ?? null;\n\t}\n\n\t/** List all non-revoked keys for a user (Owner/Admin or self). */\n\tasync listUserKeys(userId: string): Promise<{ id: string; publicKey: string; x25519Key: string | null }[]> {\n\t\tconst res = await this.request<{ keys: { id: string; publicKey: string; x25519Key: string | null }[] }>(\n\t\t\t\"GET\",\n\t\t\t`/users/${encodeURIComponent(userId)}/keys`,\n\t\t);\n\t\treturn res.keys;\n\t}\n\n\t/** Fetch encrypted E2E update blobs since a given sequence number. */\n\tasync getE2EUpdatesSince(docId: string, sinceSeq: number): Promise<{ seq: number; data: Uint8Array }[]> {\n\t\tconst res = await this.request<{ updates: { seq: number; data: string }[] }>(\n\t\t\t\"GET\",\n\t\t\t`/docs/${encodeURIComponent(docId)}/e2e-updates?since_seq=${sinceSeq}`,\n\t\t);\n\t\treturn res.updates.map((u) => ({\n\t\t\tseq: u.seq,\n\t\t\tdata: fromBase64(u.data),\n\t\t}));\n\t}\n\n\t/**\n\t * Clear token from memory and storage. Local-only; does NOT notify the\n\t * server. Use {@link logoutServer} or {@link logoutAll} when you also\n\t * want the JWT to land in the server's revocation cache.\n\t */\n\tlogout(): void {\n\t\tthis.token = null;\n\t}\n\n\t/**\n\t * Revoke the current JWT server-side and clear local state. Adds the\n\t * token's `jti` to the server's revocation cache so subsequent requests\n\t * with this token return 401, even if the JWT signature still verifies\n\t * and `exp` hasn't passed. Safe to call when no token is set — degrades\n\t * to a local clear.\n\t *\n\t * Network errors are swallowed (the local state is always cleared) so\n\t * a sign-out flow can't get stuck on a flaky connection. The endpoint\n\t * itself is idempotent.\n\t */\n\tasync logoutServer(): Promise<void> {\n\t\tif (this._token) {\n\t\t\ttry {\n\t\t\t\tawait this.request(\"POST\", \"/auth/logout\");\n\t\t\t} catch {\n\t\t\t\t// best-effort — local clear must always happen\n\t\t\t}\n\t\t}\n\t\tthis.token = null;\n\t}\n\n\t/**\n\t * Bump the user's `tokens_invalid_before` watermark, revoking every\n\t * outstanding JWT for this user — every device, every browser, every\n\t * pending background tab. The current token is required (this is the\n\t * user's \"I am who I say I am\" assertion). After the call returns,\n\t * future authenticated requests with any pre-existing token return 401.\n\t */\n\tasync logoutAll(): Promise<void> {\n\t\tawait this.request(\"POST\", \"/auth/logout-all\");\n\t\tthis.token = null;\n\t}\n\n\t// ── Email verification ──────────────────────────────────────────────────\n\n\t/**\n\t * Request an email verification message be sent to the current user's\n\t * registered email address. Requires authentication. Server enforces a\n\t * per-user rate limit (1/min, 10/day). Returns 404 if email\n\t * verification is disabled in `[auth.email_verification]`.\n\t */\n\tasync requestEmailVerification(): Promise<void> {\n\t\tawait this.request(\"POST\", \"/auth/verify-email/request\", { body: {} });\n\t}\n\n\t/**\n\t * Confirm an email verification token (typically opened from a link in\n\t * the verification email). On success the server sets\n\t * `users.email_verified_at`. No auth required — the token itself is\n\t * the proof.\n\t */\n\tasync confirmEmailVerification(token: string): Promise<void> {\n\t\tawait this.request(\"POST\", \"/auth/verify-email/confirm\", {\n\t\t\tbody: { token },\n\t\t\tauth: false,\n\t\t});\n\t}\n\n\t// ── Password lifecycle ──────────────────────────────────────────────────\n\n\t/**\n\t * Initiate a password reset for a user identified by username or\n\t * email. The server always returns 202 to avoid leaking whether the\n\t * identifier exists; a real reset email is only sent if the lookup\n\t * matched. Heavily rate-limited per-identifier and per-IP.\n\t */\n\tasync requestPasswordReset(opts: { identifier: string }): Promise<void> {\n\t\tawait this.request(\"POST\", \"/auth/password-reset/request\", {\n\t\t\tbody: opts,\n\t\t\tauth: false,\n\t\t});\n\t}\n\n\t/**\n\t * Complete a password reset using the token from the reset email.\n\t * On success the user's password is updated and every existing JWT for\n\t * the account is invalidated (the `tokens_invalid_before` watermark\n\t * bumps). The caller is NOT auto-logged-in — call {@link login} after.\n\t */\n\tasync confirmPasswordReset(opts: { token: string; newPassword: string }): Promise<void> {\n\t\tawait this.request(\"POST\", \"/auth/password-reset/confirm\", {\n\t\t\tbody: { token: opts.token, newPassword: opts.newPassword },\n\t\t\tauth: false,\n\t\t});\n\t}\n\n\t/**\n\t * Change the current user's password. Requires the current password —\n\t * a stolen JWT alone can't pivot to \"I now own this account forever\"\n\t * because the lockout counter (shared with `/auth/login`) trips after\n\t * a few wrong tries. The endpoint also bumps `tokens_invalid_before`,\n\t * so other sessions are forced to re-auth.\n\t */\n\tasync changePassword(opts: { currentPassword: string; newPassword: string }): Promise<void> {\n\t\tawait this.request(\"POST\", \"/auth/password-change\", {\n\t\t\tbody: { currentPassword: opts.currentPassword, newPassword: opts.newPassword },\n\t\t});\n\t}\n\n\t/**\n\t * Add a password to an account that doesn't have one yet — for example,\n\t * a key-based soft identity opting into a recovery credential. Requires\n\t * the caller to be authenticated. The server checks\n\t * `users.password_hash IS NULL` and returns 409 if a password is already\n\t * set — use {@link changePassword} in that case.\n\t *\n\t * Setting a password does not bump `tokens_invalid_before`: it adds an\n\t * orthogonal credential rather than rotating an existing one. Other\n\t * devices keep their sessions; this just unlocks the password-login\n\t * code path for future logins on new devices.\n\t */\n\tasync setPassword(newPassword: string): Promise<void> {\n\t\tawait this.request(\"POST\", \"/auth/set-password\", {\n\t\t\tbody: { newPassword },\n\t\t});\n\t}\n\n\t// ── User ─────────────────────────────────────────────────────────────────\n\n\t/** Get the current user's profile. */\n\tasync getMe(): Promise<UserProfile> {\n\t\tif (this.cache) {\n\t\t\tconst cached = await this.cache.getCurrentProfile();\n\t\t\tif (cached) return cached;\n\t\t}\n\t\tconst profile = await this.request<UserProfile>(\"GET\", \"/users/me\");\n\t\tif (this.cache) {\n\t\t\tawait this.cache.setCurrentProfile(profile).catch(() => null);\n\t\t}\n\t\treturn profile;\n\t}\n\n\t/** Update the current user's display name. */\n\tasync updateMe(opts: { displayName?: string }): Promise<void> {\n\t\tawait this.request(\"PATCH\", \"/users/me\", { body: opts });\n\t}\n\n\t// ── Documents ────────────────────────────────────────────────────────────\n\n\t/**\n\t * Create a new root (top-level) document. Returns its metadata.\n\t *\n\t * Requires Admin-or-above unless the server sets\n\t * `[access].allow_user_top_level = true` — subtree docs go through\n\t * {@link createChild} instead and inherit creation rights from the parent.\n\t *\n\t * The options mirror the server's `CreateDocRequest`. They used to be typed\n\t * as just `{ id?: string }`, which is why `findOrCreateDmDoc` below reaches\n\t * past this method with a raw `request()` to set `kind` / `public_access`.\n\t */\n\tasync createDoc(opts?: {\n\t\tid?: string;\n\t\tlabel?: string;\n\t\tdescription?: string;\n\t\tkind?: string;\n\t\t/** See {@link AbracadabraClient.setDocumentAccess} for what each value means. */\n\t\tpublic_access?: \"none\" | \"private\" | \"observer\" | \"viewer\" | \"editor\";\n\t}): Promise<DocumentMeta> {\n\t\treturn this.request<DocumentMeta>(\"POST\", \"/docs\", { body: opts ?? {} });\n\t}\n\n\t/** Get document metadata. */\n\tasync getDoc(docId: string): Promise<DocumentMeta> {\n\t\tif (this.cache) {\n\t\t\tconst cached = await this.cache.getDoc(docId);\n\t\t\tif (cached) return cached;\n\t\t}\n\t\tconst meta = await this.request<DocumentMeta>(\"GET\", `/docs/${encodeURIComponent(docId)}`);\n\t\tif (this.cache) {\n\t\t\tawait this.cache.setDoc(meta).catch(() => null);\n\t\t}\n\t\treturn meta;\n\t}\n\n\t/** Delete a document (requires Owner role). Cascades to children and uploads. */\n\tasync deleteDoc(docId: string): Promise<void> {\n\t\tawait this.request(\"DELETE\", `/docs/${encodeURIComponent(docId)}`);\n\t\tif (this.cache) {\n\t\t\tawait this.cache.invalidateDoc(docId).catch(() => null);\n\t\t}\n\t}\n\n\t/**\n\t * Restore a soft-deleted document (and its descendants). Requires the\n\t * same `manage` permission as {@link deleteDoc}, and works even when\n\t * the doc currently has `deleted_at` set — the cascade resolver walks\n\t * the ancestor chain regardless of soft-delete state. Returns the\n\t * number of restored rows in the audit log; the SDK call returns\n\t * `void` because the wire response is 204.\n\t */\n\tasync restoreDoc(docId: string): Promise<void> {\n\t\tawait this.request(\"POST\", `/docs/${encodeURIComponent(docId)}/restore`);\n\t\tif (this.cache) {\n\t\t\tawait this.cache.invalidateDoc(docId).catch(() => null);\n\t\t}\n\t}\n\n\t/**\n\t * Full-text search over document labels via `GET /docs/search`. The\n\t * server filters each candidate hit through the cascade resolver, so\n\t * results only include docs the caller can read at viewer or above.\n\t * Anonymous callers are permitted but only see public docs.\n\t *\n\t * `limit` is clamped to `[1, 50]` server-side; the default is 20.\n\t * Hits arrive in best-first order. `snippet` is HTML with `<mark>`\n\t * markers around matched tokens — sanitize before injecting.\n\t */\n\tasync searchDocs(query: string, opts?: { limit?: number }): Promise<DocSearchHit[]> {\n\t\tconst params = new URLSearchParams({ q: query });\n\t\tif (opts?.limit != null) params.set(\"limit\", String(opts.limit));\n\t\tconst res = await this.request<{ results: DocSearchHit[] }>(\n\t\t\t\"GET\",\n\t\t\t`/docs/search?${params.toString()}`,\n\t\t);\n\t\treturn res.results;\n\t}\n\n\t/**\n\t * Documents that link TO `docId`, via `GET /docs/:id/backlinks`.\n\t *\n\t * Served from the server's `doc_links` index, which is rebuilt from each\n\t * document's CRDT state whenever a snapshot is written. Prefer this over\n\t * inverting links from a local cache: a client can only invert what it has\n\t * downloaded, so on a large space a purely local backlink list is silently\n\t * incomplete rather than empty-and-obviously-wrong.\n\t *\n\t * The caller must be able to read the target document, and each hit is\n\t * cascade-filtered, so this never reveals a document the caller couldn't\n\t * otherwise see. `limit` is clamped to `[1, 200]` server-side (default 50).\n\t *\n\t * Throws on servers that predate the endpoint — callers that need to work\n\t * against older deployments should catch and fall back to a local index.\n\t */\n\tasync getBacklinks(\n\t\tdocId: string,\n\t\topts?: { limit?: number },\n\t): Promise<DocBacklink[]> {\n\t\tconst params = new URLSearchParams();\n\t\tif (opts?.limit != null) params.set(\"limit\", String(opts.limit));\n\t\tconst qs = params.toString();\n\t\tconst res = await this.request<{ results: DocBacklink[] }>(\n\t\t\t\"GET\",\n\t\t\t`/docs/${encodeURIComponent(docId)}/backlinks${qs ? `?${qs}` : \"\"}`,\n\t\t);\n\t\treturn res.results;\n\t}\n\n\t/**\n\t * Query for documents matching a structural predicate. v1 of the\n\t * indexed-query layer described in\n\t * `ARCHITECTURE/20-kickoff-phase3-queries.md`.\n\t *\n\t * The wire shape accepts a `where` field so v2 (meta-predicate\n\t * filtering on top of the `doc_meta_index` projection) can light up\n\t * without a compatibility break. Sending a non-empty `where` today\n\t * returns a 400 — callers should leave it absent.\n\t *\n\t * Returns docs the requester can read at viewer-or-above, filtered\n\t * through the cascading permission resolver server-side.\n\t */\n\tasync queryDocs(opts: {\n\t\ttype?: string;\n\t\tparentId?: string;\n\t\tlabelContains?: string;\n\t\tlimit?: number;\n\t}): Promise<DocumentMeta[]> {\n\t\tconst body: Record<string, unknown> = {};\n\t\tif (opts.type != null) body.type = opts.type;\n\t\tif (opts.parentId != null) body.parent_id = opts.parentId;\n\t\tif (opts.labelContains != null) body.label_contains = opts.labelContains;\n\t\tif (opts.limit != null) body.limit = opts.limit;\n\t\tconst res = await this.request<{ documents: DocumentMeta[]; v: number }>(\n\t\t\t\"POST\",\n\t\t\t\"/docs/query\",\n\t\t\t{ body },\n\t\t);\n\t\treturn res.documents;\n\t}\n\n\t/**\n\t * List the direct children of a document, returning full metadata. Pass\n\t * no argument to list the children of the server root — what the\n\t * dashboard renders as the Spaces sidebar.\n\t *\n\t * The cache (when configured) stores the bare `id[]` topology used by\n\t * recursive tree walks; callers that need it can read `meta.id` from\n\t * the returned metas.\n\t */\n\tasync listChildren(\n\t\tparentId?: string,\n\t\topts?: { kind?: string },\n\t): Promise<DocumentMeta[]> {\n\t\tconst kind = opts?.kind;\n\t\tif (parentId) {\n\t\t\tconst res = await this.request<{\n\t\t\t\tdocuments: DocumentMeta[];\n\t\t\t\tchildren?: string[];\n\t\t\t}>(\"GET\", `/docs/${encodeURIComponent(parentId)}/children`);\n\t\t\tif (this.cache && res.children) {\n\t\t\t\tawait this.cache.setChildren(parentId, res.children).catch(() => null);\n\t\t\t}\n\t\t\treturn kind\n\t\t\t\t? res.documents.filter((d) => d.kind === kind)\n\t\t\t\t: res.documents;\n\t\t}\n\t\t// Root listing. The server runs the per-row permission cascade for\n\t\t// every top-level doc, so this is the expensive call. Send the\n\t\t// optional server-side `kind` filter — a fixed server skips the\n\t\t// cascade for non-matching docs; an old server ignores the unknown\n\t\t// param and we still filter client-side below, so the result is\n\t\t// identical either way. Concurrent identical root listings (a\n\t\t// connect fans out several) share one in-flight request.\n\t\tconst key = kind ?? \"\";\n\t\tconst existing = this.rootListInflight.get(key);\n\t\tconst docs = existing\n\t\t\t? await existing\n\t\t\t: await (() => {\n\t\t\t\t\tconst p = this.request<{\n\t\t\t\t\t\tdocuments: DocumentMeta[];\n\t\t\t\t\t\tchildren?: string[];\n\t\t\t\t\t}>(\n\t\t\t\t\t\t\"GET\",\n\t\t\t\t\t\tkind\n\t\t\t\t\t\t\t? `/docs?root=true&kind=${encodeURIComponent(kind)}`\n\t\t\t\t\t\t\t: \"/docs?root=true\",\n\t\t\t\t\t)\n\t\t\t\t\t\t.then((res) => res.documents)\n\t\t\t\t\t\t.finally(() => this.rootListInflight.delete(key));\n\t\t\t\t\tthis.rootListInflight.set(key, p);\n\t\t\t\t\treturn p;\n\t\t\t\t})();\n\t\treturn kind ? docs.filter((d) => d.kind === kind) : docs;\n\t}\n\n\t/**\n\t * Create a child document under a parent (requires write permission).\n\t *\n\t * `kind` is the well-known tag (`Kind.Channel`, `Kind.Page`, etc.); the\n\t * server stores it in `documents.kind` but does not enforce semantics.\n\t * `description` is freeform metadata.\n\t */\n\tasync createChild(\n\t\tdocId: string,\n\t\topts?: {\n\t\t\tchild_id?: string;\n\t\t\tdoc_type?: string;\n\t\t\tlabel?: string;\n\t\t\tkind?: string;\n\t\t\tdescription?: string;\n\t\t},\n\t): Promise<DocumentMeta> {\n\t\treturn this.request<DocumentMeta>(\n\t\t\t\"POST\",\n\t\t\t`/docs/${encodeURIComponent(docId)}/children`,\n\t\t\t{ body: opts ?? {} },\n\t\t);\n\t}\n\n\t/** Broadcast a stateless message to all connected clients on a document (requires manage permission). */\n\tasync broadcast(docId: string, payload: string): Promise<void> {\n\t\tawait this.request(\"POST\", `/docs/${encodeURIComponent(docId)}/broadcast`, { body: { payload } });\n\t}\n\n\t// ── Permissions ──────────────────────────────────────────────────────────\n\n\t/** List all permissions for a document (requires read access). */\n\tasync listPermissions(docId: string): Promise<PermissionEntry[]> {\n\t\tif (this.cache) {\n\t\t\tconst cached = await this.cache.getPermissions(docId);\n\t\t\tif (cached) return cached;\n\t\t}\n\t\tconst res = await this.request<{ permissions: PermissionEntry[] }>(\n\t\t\t\"GET\",\n\t\t\t`/docs/${encodeURIComponent(docId)}/permissions`,\n\t\t);\n\t\tif (this.cache) {\n\t\t\tawait this.cache.setPermissions(docId, res.permissions).catch(() => null);\n\t\t}\n\t\treturn res.permissions;\n\t}\n\n\t/** List effective permissions including inherited ones from ancestor documents. */\n\tasync listEffectivePermissions(\n\t\tdocId: string,\n\t): Promise<EffectivePermissionsResponse> {\n\t\ttry {\n\t\t\treturn await this.request<EffectivePermissionsResponse>(\n\t\t\t\t\"GET\",\n\t\t\t\t`/docs/${encodeURIComponent(docId)}/effective-permissions`,\n\t\t\t);\n\t\t} catch (e: unknown) {\n\t\t\t// Fallback for older servers that don't support this endpoint (404 only)\n\t\t\tif (typeof e === \"object\" && e !== null && \"status\" in e && (e as { status: number }).status === 404) {\n\t\t\t\tconst perms = await this.listPermissions(docId);\n\t\t\t\treturn {\n\t\t\t\t\tpermissions: perms.map((p) => ({ ...p, source: \"direct\" as const })),\n\t\t\t\t\tdefault_role: \"viewer\",\n\t\t\t\t};\n\t\t\t}\n\t\t\tthrow e;\n\t\t}\n\t}\n\n\t/** Grant or change a user's role on a document (requires Owner). */\n\tasync setPermission(\n\t\tdocId: string,\n\t\topts: { user_id: string; role: \"owner\" | \"editor\" | \"viewer\" | \"observer\" },\n\t): Promise<void> {\n\t\tawait this.request(\n\t\t\t\"POST\",\n\t\t\t`/docs/${encodeURIComponent(docId)}/permissions`,\n\t\t\t{ body: opts },\n\t\t);\n\t}\n\n\t/** Revoke a user's permission on a document (requires Owner). */\n\tasync removePermission(docId: string, opts: { user_id: string }): Promise<void> {\n\t\tawait this.request(\n\t\t\t\"DELETE\",\n\t\t\t`/docs/${encodeURIComponent(docId)}/permissions`,\n\t\t\t{ body: opts },\n\t\t);\n\t}\n\n\t// ── Uploads ──────────────────────────────────────────────────────────────\n\n\t/** Upload a file to a document (requires write permission). */\n\tasync upload(\n\t\tdocId: string,\n\t\tfile: File | Blob,\n\t\tfilename?: string,\n\t): Promise<UploadMeta> {\n\t\tconst formData = new FormData();\n\t\tformData.append(\"file\", file, filename);\n\n\t\tconst headers: Record<string, string> = {};\n\t\tif (this._token) {\n\t\t\theaders[\"Authorization\"] = `Bearer ${this._token}`;\n\t\t}\n\n\t\tconst res = await this._fetch(\n\t\t\t`${this.baseUrl}/docs/${encodeURIComponent(docId)}/uploads`,\n\t\t\t{ method: \"POST\", headers, body: formData },\n\t\t);\n\t\tif (!res.ok) {\n\t\t\tthrow await this.toError(res);\n\t\t}\n\t\tconst meta = await res.json() as UploadMeta;\n\t\tif (this.cache) {\n\t\t\tawait this.cache.invalidateUploads(docId).catch(() => null);\n\t\t}\n\t\treturn meta;\n\t}\n\n\t/** List all uploads for a document. */\n\tasync listUploads(docId: string): Promise<UploadInfo[]> {\n\t\tif (this.cache) {\n\t\t\tconst cached = await this.cache.getUploads(docId);\n\t\t\tif (cached) return cached;\n\t\t}\n\t\tconst res = await this.request<{ uploads: UploadInfo[] }>(\n\t\t\t\"GET\",\n\t\t\t`/docs/${encodeURIComponent(docId)}/uploads`,\n\t\t);\n\t\tif (this.cache) {\n\t\t\tawait this.cache.setUploads(docId, res.uploads).catch(() => null);\n\t\t}\n\t\treturn res.uploads;\n\t}\n\n\t/** Download an upload as a Blob. */\n\tasync getUpload(docId: string, uploadId: string): Promise<Blob> {\n\t\tconst headers: Record<string, string> = {};\n\t\tif (this._token) {\n\t\t\theaders[\"Authorization\"] = `Bearer ${this._token}`;\n\t\t}\n\n\t\tconst res = await this._fetch(\n\t\t\t`${this.baseUrl}/docs/${encodeURIComponent(docId)}/uploads/${encodeURIComponent(uploadId)}`,\n\t\t\t{ method: \"GET\", headers },\n\t\t);\n\t\tif (!res.ok) {\n\t\t\tthrow await this.toError(res);\n\t\t}\n\t\treturn res.blob();\n\t}\n\n\t/**\n\t * Mint a short-lived, read-only token bound to this one upload.\n\t * Prefer `getStreamUrl`, which caches and reuses the grant.\n\t */\n\tasync createStreamToken(\n\t\tdocId: string,\n\t\tuploadId: string,\n\t): Promise<StreamTokenInfo> {\n\t\treturn this.request<StreamTokenInfo>(\n\t\t\t\"POST\",\n\t\t\t`/docs/${encodeURIComponent(docId)}/uploads/${encodeURIComponent(uploadId)}/stream-token`,\n\t\t);\n\t}\n\n\t/**\n\t * Absolute URL that streams an upload straight from the server, safe to\n\t * hand to `<video src>` / `<audio src>`.\n\t *\n\t * Unlike `FileBlobStore.getBlobUrl` (which downloads the whole blob into\n\t * IndexedDB and hands back an object URL), this keeps the bytes on the\n\t * server so the browser can seek natively over HTTP Range — the difference\n\t * between \"wait for 400 MB\" and \"scrub instantly\". It needs the network,\n\t * so callers should fall back to `getBlobUrl` when offline.\n\t *\n\t * Grants are cached per upload and re-minted shortly before they expire.\n\t * Throws on servers older than the `stream-token` endpoint (404).\n\t */\n\tasync getStreamUrl(docId: string, uploadId: string): Promise<string> {\n\t\tconst key = `${docId}/${uploadId}`;\n\t\tconst cached = this.streamTokens.get(key);\n\t\t// Re-mint a minute early so a URL handed to a media element doesn't\n\t\t// expire mid-request.\n\t\tif (cached && cached.expiresAt - 60_000 > Date.now()) return cached.url;\n\n\t\t// Single-flight: a page full of media blocks resolves the same upload\n\t\t// from several components at once, and each mint is a round trip.\n\t\tconst inflight = this.streamTokenInflight.get(key);\n\t\tif (inflight) return inflight;\n\n\t\tconst pending = this.createStreamToken(docId, uploadId)\n\t\t\t.then((info) => {\n\t\t\t\tconst url = `${this.baseUrl}${info.url}`;\n\t\t\t\tthis.streamTokens.set(key, {\n\t\t\t\t\turl,\n\t\t\t\t\texpiresAt: Date.now() + info.expires_in * 1000,\n\t\t\t\t});\n\t\t\t\treturn url;\n\t\t\t})\n\t\t\t.finally(() => {\n\t\t\t\tthis.streamTokenInflight.delete(key);\n\t\t\t});\n\t\tthis.streamTokenInflight.set(key, pending);\n\t\treturn pending;\n\t}\n\n\t/** Drop any cached stream grant for an upload (or all of them). */\n\tclearStreamUrl(docId?: string, uploadId?: string): void {\n\t\tif (docId && uploadId) {\n\t\t\tthis.streamTokens.delete(`${docId}/${uploadId}`);\n\t\t\tthis.streamTokenInflight.delete(`${docId}/${uploadId}`);\n\t\t\treturn;\n\t\t}\n\t\tthis.streamTokens.clear();\n\t\tthis.streamTokenInflight.clear();\n\t}\n\n\t/**\n\t * Build the request path (with query string) for an upload's thumbnail.\n\t * Also the canonical cache key suffix — the query string is deterministic\n\t * in insertion order, so identical options map to the same URL and the\n\t * same `FileBlobStore` cache entry.\n\t */\n\tthumbnailPath(docId: string, uploadId: string, opts: ThumbnailOptions = {}): string {\n\t\tconst p = new URLSearchParams();\n\t\tif (opts.w != null) p.set(\"w\", String(opts.w));\n\t\tif (opts.h != null) p.set(\"h\", String(opts.h));\n\t\tif (opts.fit) p.set(\"fit\", opts.fit);\n\t\tif (opts.format) p.set(\"format\", opts.format);\n\t\tif (opts.q != null) p.set(\"q\", String(opts.q));\n\t\tconst qs = p.toString();\n\t\treturn `/docs/${encodeURIComponent(docId)}/uploads/${encodeURIComponent(uploadId)}/thumbnail${qs ? `?${qs}` : \"\"}`;\n\t}\n\n\t/**\n\t * Download a generated thumbnail of an image upload as a Blob. The server\n\t * renders + caches it on first request. Because a browser `<img>` can't\n\t * send `Authorization`, callers render the returned Blob via an object URL\n\t * (see `FileBlobStore.getThumbUrl`, which also caches it locally).\n\t * Throws (with `.status = 415`) when the source isn't a thumbnailable\n\t * raster image, or `422` for an out-of-allowlist size/format.\n\t */\n\tasync getThumbnail(\n\t\tdocId: string,\n\t\tuploadId: string,\n\t\topts: ThumbnailOptions = {},\n\t): Promise<Blob> {\n\t\tconst headers: Record<string, string> = {};\n\t\tif (this._token) {\n\t\t\theaders[\"Authorization\"] = `Bearer ${this._token}`;\n\t\t}\n\n\t\tconst res = await this._fetch(\n\t\t\t`${this.baseUrl}${this.thumbnailPath(docId, uploadId, opts)}`,\n\t\t\t{ method: \"GET\", headers },\n\t\t);\n\t\tif (!res.ok) {\n\t\t\tthrow await this.toError(res);\n\t\t}\n\t\treturn res.blob();\n\t}\n\n\t/** Delete an upload (requires uploader or document Owner). */\n\tasync deleteUpload(docId: string, uploadId: string): Promise<void> {\n\t\tawait this.request(\n\t\t\t\"DELETE\",\n\t\t\t`/docs/${encodeURIComponent(docId)}/uploads/${encodeURIComponent(uploadId)}`,\n\t\t);\n\t\tif (this.cache) {\n\t\t\tawait this.cache.invalidateUploads(docId).catch(() => null);\n\t\t}\n\t}\n\n\t// ── Invites ──────────────────────────────────────────────────────────────\n\n\t/** Create an invite code (requires permission per server config). */\n\tasync createInvite(opts?: { role?: string; maxUses?: number; expiresIn?: number }): Promise<InviteRow> {\n\t\treturn this.request<InviteRow>(\"POST\", \"/invites\", { body: opts ?? {} });\n\t}\n\n\t/** List invite codes visible to the current user. */\n\tasync listInvites(): Promise<InviteRow[]> {\n\t\tconst res = await this.request<{ invites: InviteRow[] }>(\"GET\", \"/invites\");\n\t\treturn res.invites;\n\t}\n\n\t/** Revoke an invite by its code. */\n\tasync revokeInvite(code: string): Promise<void> {\n\t\tawait this.request(\"DELETE\", `/invites/${encodeURIComponent(code)}`);\n\t}\n\n\t/** Redeem an invite code for the currently authenticated user. */\n\tasync redeemInvite(code: string): Promise<void> {\n\t\tawait this.request(\"POST\", \"/invites/redeem\", { body: { code } });\n\t}\n\n\t// ── Document Access & Discovery ──────────────────────────────────────────\n\n\t/**\n\t * Set the public_access level for a document. Pass null to inherit from parent.\n\t *\n\t * The values, and the two that are easy to confuse:\n\t *\n\t * - `\"observer\"` / `\"viewer\"` / `\"editor\"` — a FLOOR. Raises whoever reaches\n\t * this document to at least that role, cascading to descendants.\n\t * - `\"none\"` — no floor from here. Blocks anonymous, but an authenticated\n\t * principal still falls through to the server's `[access].authenticated`\n\t * default, so on a server with a floor this does NOT make a document private.\n\t * - `\"private\"` — no floor AND no ambient default. Only explicit grants,\n\t * ownership, Admin and Service reach a sealed document. This is what makes\n\t * a document private without reconfiguring the whole server.\n\t *\n\t * The cascade takes the NEAREST ancestor that sets a value, not the strongest,\n\t * so a descendant can re-publish itself out of a private parent.\n\t *\n\t * `\"private\"` requires server ≥ the release that introduced it. An older\n\t * server rejects it with 400 rather than silently storing it.\n\t */\n\tasync setDocumentAccess(\n\t\tdocId: string,\n\t\tpublicAccess: \"none\" | \"private\" | \"observer\" | \"viewer\" | \"editor\" | null,\n\t): Promise<void> {\n\t\tawait this.request(\"PATCH\", `/docs/${encodeURIComponent(docId)}/access`, {\n\t\t\tbody: { public_access: publicAccess },\n\t\t});\n\t}\n\n\t/** Get the public_access info for a document. */\n\tasync getDocumentAccess(docId: string): Promise<{ public_access: string | null; effective_public_access: string | null }> {\n\t\treturn this.request(\"GET\", `/docs/${encodeURIComponent(docId)}/access`);\n\t}\n\n\t/**\n\t * Update document metadata (label, description, kind, doc_type, parent_id).\n\t * Requires manage permission on the doc; reparenting additionally requires\n\t * manage on the new parent (or admin if moving under the server root).\n\t *\n\t * `doc_type` is the renderer hint (`\"kanban\"`, `\"graph\"`, …) — orthogonal\n\t * to `kind` (the structural role). Use it for post-create type changes;\n\t * never write renderer strings into `kind`. Servers older than migration\n\t * 0014 ignore the field (unknown JSON fields are dropped server-side).\n\t */\n\tasync updateDocumentMeta(\n\t\tdocId: string,\n\t\topts: {\n\t\t\tlabel?: string | null;\n\t\t\tdescription?: string | null;\n\t\t\tkind?: string | null;\n\t\t\tdoc_type?: string | null;\n\t\t\tparent_id?: string | null;\n\t\t},\n\t): Promise<void> {\n\t\tawait this.request(\"PATCH\", `/docs/${encodeURIComponent(docId)}`, { body: opts });\n\t}\n\n\t// ── Spaces ───────────────────────────────────────────────────────────────\n\t//\n\t// \"Spaces\" are direct children of the server root with `kind: \"space\"`.\n\t// They live in the regular `documents` table — there's no dedicated\n\t// spaces resource on the server anymore. These helpers keep the familiar\n\t// names so callers don't have to think about the underlying tree.\n\n\t/**\n\t * List Spaces visible to the caller — top-level docs (children of the\n\t * server root) tagged with `kind: \"space\"`. Authenticated users see\n\t * spaces resolving to any role; anonymous users see public ones.\n\t */\n\tasync listSpaces(): Promise<DocumentMeta[]> {\n\t\treturn this.listChildren(undefined, { kind: Kind.Space });\n\t}\n\n\t/**\n\t * Create a new top-level Space. Equivalent to a `POST /docs` with\n\t * `kind: \"space\"` plus the supplied metadata in one round trip.\n\t *\n\t * `visibility: \"public\"` sets `public_access = \"observer\"` (anonymous\n\t * read, no awareness or writes). `\"private\"` (the default) leaves\n\t * `public_access` unset so only explicit grants apply.\n\t */\n\tasync createSpace(opts: {\n\t\tname: string;\n\t\tdescription?: string;\n\t\tvisibility?: \"public\" | \"private\";\n\t\tid?: string;\n\t}): Promise<DocumentMeta> {\n\t\tconst public_access = opts.visibility === \"public\" ? \"observer\" : \"none\";\n\t\treturn this.request<DocumentMeta>(\"POST\", \"/docs\", {\n\t\t\tbody: {\n\t\t\t\tid: opts.id,\n\t\t\t\tlabel: opts.name,\n\t\t\t\tdescription: opts.description,\n\t\t\t\tkind: Kind.Space,\n\t\t\t\tpublic_access,\n\t\t\t},\n\t\t});\n\t}\n\n\t/**\n\t * Update a Space's metadata. `visibility` flips `public_access` between\n\t * `\"observer\"` (public) and `\"none\"` (private). To leave visibility\n\t * untouched, omit it. Pass any property as `null` to clear it.\n\t */\n\tasync updateSpace(\n\t\tdocId: string,\n\t\topts: { name?: string | null; description?: string | null; visibility?: \"public\" | \"private\" },\n\t): Promise<void> {\n\t\tconst meta: { label?: string | null; description?: string | null } = {};\n\t\tif (opts.name !== undefined) meta.label = opts.name;\n\t\tif (opts.description !== undefined) meta.description = opts.description;\n\t\tif (Object.keys(meta).length > 0) {\n\t\t\tawait this.updateDocumentMeta(docId, meta);\n\t\t}\n\t\tif (opts.visibility !== undefined) {\n\t\t\tawait this.setDocumentAccess(docId, opts.visibility === \"public\" ? \"observer\" : \"none\");\n\t\t}\n\t}\n\n\t/** Delete a Space (and every doc nested under it). Requires manage permission. */\n\tasync deleteSpace(docId: string): Promise<void> {\n\t\tawait this.deleteDoc(docId);\n\t}\n\n\t/**\n\t * Look up the DM doc between the calling user and `otherUserPk`, or\n\t * create it if none exists. The doc id is deterministically derived from\n\t * the sorted pubkey pair (see {@link deriveDmDocId}) so both sides\n\t * compute the same target — race-tolerant by construction. The created\n\t * doc has `kind = \"dm\"`, `public_access = \"none\"`, and explicit Editor\n\t * permissions for both participants.\n\t *\n\t * The cascade resolver enforces that no other user can read the DM,\n\t * because:\n\t * - `public_access = \"none\"` blocks anonymous + falls through to the\n\t * server-wide `[access].authenticated` floor for everyone else;\n\t * - the explicit Editor rows only exist for the two participants, so\n\t * non-participants get only the (capped) authenticated floor;\n\t * - the doc lives at server root, so there's no ancestor that could\n\t * leak via a higher cascade grant.\n\t *\n\t * Note: when `[access].authenticated >= \"viewer\"` is set server-wide,\n\t * non-participants can still *read* the DM via the authenticated floor —\n\t * `public_access = \"none\"` removes the floor but not the ambient default.\n\t *\n\t * Servers that support `public_access = \"private\"` can seal it properly:\n\t * call `setDocumentAccess(dmId, \"private\")` after creating one. That is NOT\n\t * done here, deliberately — this SDK talks to older servers too, and they\n\t * reject the value with a 400. Callers that know their server version can\n\t * opt in; a future major may make it the default.\n\t *\n\t * @param otherUserPk Base64url-encoded Ed25519 public key of the other party.\n\t * @returns The DM doc's id (existing or newly created).\n\t */\n\tasync findOrCreateDmDoc(otherUserPk: string): Promise<string> {\n\t\tconst me = await this.getMe();\n\t\tif (!me.publicKey) {\n\t\t\tthrow new Error(\"findOrCreateDmDoc: caller has no public key\");\n\t\t}\n\t\tconst dmId = deriveDmDocId(me.publicKey, otherUserPk);\n\t\t// Try to fetch the doc first — if it exists, we're done.\n\t\ttry {\n\t\t\tconst existing = await this.getDoc(dmId);\n\t\t\tif (existing && existing.kind === Kind.Dm) {\n\t\t\t\treturn dmId;\n\t\t\t}\n\t\t} catch {\n\t\t\t// 404 is the expected miss; any other error we let bubble up\n\t\t\t// from createDoc below.\n\t\t}\n\t\t// Race-tolerant create: both clients hashing the same pubkey pair\n\t\t// generate the same id, so whoever loses the create gets Conflict\n\t\t// and the catch reuses the id.\n\t\ttry {\n\t\t\tawait this.request<DocumentMeta>(\"POST\", \"/docs\", {\n\t\t\t\tbody: {\n\t\t\t\t\tid: dmId,\n\t\t\t\t\tkind: Kind.Dm,\n\t\t\t\t\tpublic_access: \"none\",\n\t\t\t\t},\n\t\t\t});\n\t\t} catch (err: any) {\n\t\t\t// Conflict means the other side already created it; reuse.\n\t\t\tconst status = err?.status ?? err?.response?.status;\n\t\t\tif (status !== 409) throw err;\n\t\t}\n\t\t// Idempotent permission grants (server upserts on (doc_id, user_id)).\n\t\tawait this.setPermission(dmId, { user_id: me.publicKey, role: \"editor\" });\n\t\tawait this.setPermission(dmId, { user_id: otherUserPk, role: \"editor\" });\n\t\treturn dmId;\n\t}\n\n\t/**\n\t * The reserved server root document id. Convenience accessor for the\n\t * client; identical to {@link SERVER_ROOT_ID}. Use this as the parent for\n\t * top-level docs / Spaces.\n\t */\n\tget rootDocId(): string {\n\t\treturn SERVER_ROOT_ID;\n\t}\n\n\t// ── Admin ───────────────────────────────────────────────────────────────\n\n\t/** List all users (requires elevated role: admin or service). */\n\tasync adminListUsers(): Promise<{ users: (UserProfile & { revoked: boolean; deviceKeys: string[] })[] }> {\n\t\treturn this.request(\"GET\", \"/admin/users\");\n\t}\n\n\t/** Promote a user to admin (requires service role). */\n\tasync adminPromote(userId: string): Promise<void> {\n\t\tawait this.request(\"POST\", `/admin/users/${encodeURIComponent(userId)}/admin`);\n\t}\n\n\t/** Demote an admin user back to regular (requires service role). */\n\tasync adminDemote(userId: string): Promise<void> {\n\t\tawait this.request(\"DELETE\", `/admin/users/${encodeURIComponent(userId)}/admin`);\n\t}\n\n\t/** Sweep orphaned file blobs from storage (requires elevated role). */\n\tasync adminStorageSweep(): Promise<{ blobsDeleted: number }> {\n\t\treturn this.request(\"POST\", \"/admin/storage/sweep\");\n\t}\n\n\t/** Repair blob ref-counts and sweep orphans (requires elevated role). */\n\tasync adminStorageRepair(): Promise<{ refCountsRepaired: number; blobsSwept: number }> {\n\t\treturn this.request(\"POST\", \"/admin/storage/repair\");\n\t}\n\n\t/**\n\t * Admin one-shot: populate the `snapshot_files` table for snapshots\n\t * created before that migration ran, so `SnapshotMeta.file_count` and\n\t * upload-ref tracking become accurate. Idempotent (insert-or-ignore).\n\t * Requires elevated role.\n\t */\n\tasync adminSnapshotsBackfillRefs(): Promise<{\n\t\tsnapshotsScanned: number;\n\t\trefsWritten: number;\n\t}> {\n\t\treturn this.request(\"POST\", \"/admin/snapshots/backfill-refs\");\n\t}\n\n\t/**\n\t * Admin one-shot: migrate pre-dedup inline snapshot data into the\n\t * content-addressed `snapshot_blobs` store. Idempotent (only migrates\n\t * rows with `data_hash IS NULL`). Requires elevated role.\n\t */\n\tasync adminSnapshotsBackfillBlobs(): Promise<{\n\t\tsnapshotsMigrated: number;\n\t\tblobsAfter: number;\n\t\ttotalBytesAfter: number;\n\t}> {\n\t\treturn this.request(\"POST\", \"/admin/snapshots/backfill-blobs\");\n\t}\n\n\t/**\n\t * Admin: server-wide upload listing, joined with the owning document\n\t * (label is best-effort — labels live in the CRDT, not the SQL row)\n\t * and the content-addressed blob (`ref_count` exposes dedup).\n\t * Server-side paginated + filtered. Requires elevated role.\n\t */\n\tasync adminListUploads(\n\t\topts: { q?: string; docId?: string; limit?: number; offset?: number } = {},\n\t): Promise<{\n\t\tuploads: Array<{\n\t\t\tid: string;\n\t\t\tdoc_id: string;\n\t\t\tdoc_label: string | null;\n\t\t\tfilename: string;\n\t\t\tmime_type: string | null;\n\t\t\tsize: number | null;\n\t\t\tcontent_hash: string | null;\n\t\t\tref_count: number | null;\n\t\t\towner_id: string;\n\t\t\tcreated_at: number;\n\t\t}>;\n\t\ttotal: number;\n\t}> {\n\t\tconst p = new URLSearchParams();\n\t\tif (opts.q) p.set(\"q\", opts.q);\n\t\tif (opts.docId) p.set(\"doc_id\", opts.docId);\n\t\tif (opts.limit != null) p.set(\"limit\", String(opts.limit));\n\t\tif (opts.offset != null) p.set(\"offset\", String(opts.offset));\n\t\tconst qs = p.toString();\n\t\treturn this.request(\"GET\", `/admin/uploads${qs ? `?${qs}` : \"\"}`);\n\t}\n\n\t/**\n\t * Admin: aggregate storage figures. `logicalBytes` is what users\n\t * uploaded; `physicalBytes` is on-disk after content-addressed dedup;\n\t * `dedupSaved` is the difference. Requires elevated role.\n\t */\n\tasync adminStorageStats(): Promise<{\n\t\tuploadCount: number;\n\t\tblobCount: number;\n\t\tlogicalBytes: number;\n\t\tphysicalBytes: number;\n\t\tdedupSaved: number;\n\t}> {\n\t\treturn this.request(\"GET\", \"/admin/storage/stats\");\n\t}\n\n\t/**\n\t * Clear the lockout state on a user account: zeroes the failed-login\n\t * counter and `locked_until`. Requires elevated role (Admin or\n\t * Service). The action is recorded in the audit log under\n\t * `admin.user_unlock`.\n\t */\n\tasync adminUnlockUser(userId: string): Promise<void> {\n\t\tawait this.request(\"POST\", `/admin/users/${encodeURIComponent(userId)}/unlock`);\n\t}\n\n\t/**\n\t * Admin: every non-deleted document the user owns (`source: \"owner\"`)\n\t * or has an explicit permission grant on (`source: \"grant\"`, with\n\t * `role`). Answers \"what does this identity touch\" without an N+1\n\t * client tree walk. Labels are best-effort (they live in the CRDT).\n\t * Requires elevated role.\n\t */\n\tasync adminUserDocs(\n\t\tuserId: string,\n\t\topts: { limit?: number } = {},\n\t): Promise<{\n\t\tdocs: Array<{\n\t\t\tid: string;\n\t\t\tlabel: string | null;\n\t\t\tkind: string | null;\n\t\t\tdoc_type: string | null;\n\t\t\tparent_id: string | null;\n\t\t\tsource: \"owner\" | \"grant\";\n\t\t\trole: string | null;\n\t\t}>;\n\t}> {\n\t\tconst qs = opts.limit != null ? `?limit=${opts.limit}` : \"\";\n\t\treturn this.request(\n\t\t\t\"GET\",\n\t\t\t`/admin/users/${encodeURIComponent(userId)}/docs${qs}`,\n\t\t);\n\t}\n\n\t/**\n\t * List `service`-role users (runners, demo seeders, automation\n\t * identities). Requires Service role. Admins can see service users via\n\t * `/admin/users` too but cannot mint or rotate them.\n\t */\n\tasync adminListServiceAccounts(): Promise<{\n\t\titems: Array<{\n\t\t\tid: string;\n\t\t\tusername: string;\n\t\t\tpublic_key: string | null;\n\t\t\trevoked: boolean;\n\t\t\tdisplay_name: string | null;\n\t\t}>;\n\t}> {\n\t\treturn this.request(\"GET\", \"/admin/service-accounts\");\n\t}\n\n\t/**\n\t * Create a new `service`-role user. When `public_key` is omitted the\n\t * server generates a keypair and returns the private half in the\n\t * response — show it to the operator **once** and discard; the server\n\t * never persists it. Requires Service role.\n\t */\n\tasync adminCreateServiceAccount(body: {\n\t\tusername: string;\n\t\tpublic_key?: string;\n\t}): Promise<{\n\t\tid: string;\n\t\tusername: string;\n\t\tpublic_key: string;\n\t\trole: string;\n\t\tprivate_key?: string;\n\t}> {\n\t\treturn this.request(\"POST\", \"/admin/service-accounts\", { body });\n\t}\n\n\t/**\n\t * Rotate the active keypair on a service account. Old JWTs are\n\t * invalidated; old device keys are marked revoked; the canonical\n\t * `users.public_key` swaps to the new value. `users.id` stays put so\n\t * existing permission rows keep matching. Returns the new pubkey (and\n\t * private half when the server generated it). Requires Service role.\n\t */\n\tasync adminRotateServiceAccountKey(\n\t\tuserId: string,\n\t\tbody: { public_key?: string } = {},\n\t): Promise<{ id: string; public_key: string; private_key?: string }> {\n\t\treturn this.request(\n\t\t\t\"POST\",\n\t\t\t`/admin/service-accounts/${encodeURIComponent(userId)}/rotate-key`,\n\t\t\t{ body },\n\t\t);\n\t}\n\n\t/**\n\t * Lock a service account and revoke all of its device keys. Idempotent.\n\t * Refuses targets whose `users.role` isn't `\"service\"`. Requires\n\t * Service role.\n\t */\n\tasync adminRevokeServiceAccount(userId: string): Promise<void> {\n\t\tawait this.request(\n\t\t\t\"DELETE\",\n\t\t\t`/admin/service-accounts/${encodeURIComponent(userId)}`,\n\t\t);\n\t}\n\n\t/**\n\t * Revoke a single device key on a user (any role). Bumps\n\t * `tokens_invalid_before` so open WS sessions tied to the key must\n\t * re-auth. Requires elevated role (Service or Admin@root).\n\t */\n\tasync adminRevokeDeviceKey(userId: string, keyId: string): Promise<void> {\n\t\tawait this.request(\n\t\t\t\"POST\",\n\t\t\t`/admin/users/${encodeURIComponent(userId)}/device-keys/${encodeURIComponent(keyId)}/revoke`,\n\t\t);\n\t}\n\n\t/**\n\t * Page through the audit log. Filters AND-combine; `limit` defaults to\n\t * 100 server-side. Requires elevated role.\n\t */\n\tasync adminAuditList(opts?: AuditQueryOpts): Promise<AuditLogEntry[]> {\n\t\tconst params = new URLSearchParams();\n\t\tif (opts?.event_type) params.set(\"event_type\", opts.event_type);\n\t\tif (opts?.actor_user_id) params.set(\"actor_user_id\", opts.actor_user_id);\n\t\tif (opts?.target_type) params.set(\"target_type\", opts.target_type);\n\t\tif (opts?.target_id) params.set(\"target_id\", opts.target_id);\n\t\tif (opts?.since_ts != null) params.set(\"since_ts\", String(opts.since_ts));\n\t\tif (opts?.until_ts != null) params.set(\"until_ts\", String(opts.until_ts));\n\t\tif (opts?.limit != null) params.set(\"limit\", String(opts.limit));\n\t\tif (opts?.offset != null) params.set(\"offset\", String(opts.offset));\n\t\tconst qs = params.toString();\n\t\tconst res = await this.request<{ items: AuditLogEntry[] }>(\n\t\t\t\"GET\",\n\t\t\t`/admin/audit${qs ? `?${qs}` : \"\"}`,\n\t\t);\n\t\treturn res.items;\n\t}\n\n\t/**\n\t * Stream the audit log as NDJSON (one JSON object per line) for SIEM\n\t * ingestion. Filters mirror {@link adminAuditList} minus `limit`/`offset`.\n\t * The server pages internally so memory usage is bounded; this method\n\t * buffers the full response into a string and is therefore best for\n\t * moderate exports — large dumps should consume `/admin/audit/export`\n\t * directly with a streaming HTTP client.\n\t */\n\tasync adminAuditExport(opts?: Omit<AuditQueryOpts, \"limit\" | \"offset\">): Promise<string> {\n\t\tconst params = new URLSearchParams();\n\t\tif (opts?.event_type) params.set(\"event_type\", opts.event_type);\n\t\tif (opts?.actor_user_id) params.set(\"actor_user_id\", opts.actor_user_id);\n\t\tif (opts?.target_type) params.set(\"target_type\", opts.target_type);\n\t\tif (opts?.target_id) params.set(\"target_id\", opts.target_id);\n\t\tif (opts?.since_ts != null) params.set(\"since_ts\", String(opts.since_ts));\n\t\tif (opts?.until_ts != null) params.set(\"until_ts\", String(opts.until_ts));\n\t\tconst qs = params.toString();\n\t\tconst headers: Record<string, string> = {};\n\t\tif (this._token) headers[\"Authorization\"] = `Bearer ${this._token}`;\n\t\tconst res = await this._fetch(\n\t\t\t`${this.baseUrl}/admin/audit/export${qs ? `?${qs}` : \"\"}`,\n\t\t\t{ method: \"GET\", headers },\n\t\t);\n\t\tif (!res.ok) throw await this.toError(res, \"GET\", \"/admin/audit/export\");\n\t\treturn res.text();\n\t}\n\n\t/**\n\t * Verify the integrity of the audit-log hash chain. Returns the result\n\t * unchanged: `status: \"ok\"` when the chain is intact, `status: \"broken\"`\n\t * with a `break` payload identifying the first divergent row when\n\t * tampering is detected. Wraps `GET /admin/audit/verify`. Requires\n\t * elevated role.\n\t *\n\t * Note: the server returns HTTP 409 on a broken chain — this method\n\t * special-cases the 409 status and returns the body as a successful\n\t * result rather than throwing, because \"broken\" is a valid answer\n\t * from the verifier, not an error.\n\t */\n\tasync adminAuditVerify(): Promise<AuditVerifyResult> {\n\t\tconst headers: Record<string, string> = {};\n\t\tif (this._token) headers[\"Authorization\"] = `Bearer ${this._token}`;\n\t\tconst res = await this._fetch(`${this.baseUrl}/admin/audit/verify`, {\n\t\t\tmethod: \"GET\",\n\t\t\theaders,\n\t\t});\n\t\tif (res.status === 200 || res.status === 409) {\n\t\t\treturn res.json() as Promise<AuditVerifyResult>;\n\t\t}\n\t\tthrow await this.toError(res, \"GET\", \"/admin/audit/verify\");\n\t}\n\n\t/**\n\t * Download a tar archive of the schema-meaningful tables (users,\n\t * documents, permissions, invites, optionally audit log). Requires\n\t * elevated role. The server gzips the response when the client sends\n\t * `Accept-Encoding: gzip` — `fetch` handles that transparently, so\n\t * the returned Blob is the raw tar bytes.\n\t */\n\tasync adminBackupDump(opts?: { includeAudit?: boolean }): Promise<Blob> {\n\t\tconst params = new URLSearchParams();\n\t\tif (opts?.includeAudit) params.set(\"include_audit\", \"true\");\n\t\tconst qs = params.toString();\n\t\tconst headers: Record<string, string> = {};\n\t\tif (this._token) headers[\"Authorization\"] = `Bearer ${this._token}`;\n\t\tconst res = await this._fetch(\n\t\t\t`${this.baseUrl}/admin/backup/dump${qs ? `?${qs}` : \"\"}`,\n\t\t\t{ method: \"GET\", headers },\n\t\t);\n\t\tif (!res.ok) throw await this.toError(res, \"GET\", \"/admin/backup/dump\");\n\t\treturn res.blob();\n\t}\n\n\t// ── Admin: runtime config store ──────────────────────────────────────────\n\n\t/**\n\t * List every registered config field with current value + origin\n\t * (`default` / `env` / `global_override` / `route_override`). Requires\n\t * elevated role.\n\t */\n\tasync adminConfigList(): Promise<AdminConfigField[]> {\n\t\tconst res = await this.request<{ items: AdminConfigField[] }>(\n\t\t\t\"GET\", \"/admin/config\",\n\t\t);\n\t\treturn res.items;\n\t}\n\n\t/** Read a single config field by dotted path (e.g. `\"access.authenticated\"`). */\n\tasync adminConfigGet(path: string): Promise<AdminConfigField> {\n\t\treturn this.request<AdminConfigField>(\n\t\t\t\"GET\", `/admin/config/fields/${encodeURIComponent(path)}`,\n\t\t);\n\t}\n\n\t/**\n\t * Set a runtime override on a config field. The field must be marked\n\t * `runtime_mutable = true` in the registry; immutable fields return a\n\t * schema error. Persists to the `settings_overrides` table.\n\t */\n\tasync adminConfigSet(path: string, value: unknown): Promise<AdminConfigField> {\n\t\treturn this.request<AdminConfigField>(\n\t\t\t\"PUT\", `/admin/config/fields/${encodeURIComponent(path)}`,\n\t\t\t{ body: { value } },\n\t\t);\n\t}\n\n\t/**\n\t * Clear a runtime override and revert the field to its env/TOML/default\n\t * base value. Returns `true` when an override was actually removed.\n\t */\n\tasync adminConfigUnset(path: string): Promise<boolean> {\n\t\tconst res = await this.request<{ existed: boolean }>(\n\t\t\t\"DELETE\", `/admin/config/fields/${encodeURIComponent(path)}`,\n\t\t);\n\t\treturn res.existed;\n\t}\n\n\t/**\n\t * Diagnostic dump of every `ABRA_*` env var the running process saw at\n\t * boot, mapped to its config path. Use this to debug\n\t * \"I set this in `.env` but the server reports a different value\".\n\t * Secrets are redacted (`value: null`, `redacted: true`).\n\t */\n\tasync adminConfigEnvSnapshot(): Promise<EnvSnapshotResponse> {\n\t\treturn this.request<EnvSnapshotResponse>(\"GET\", \"/admin/config/env-snapshot\");\n\t}\n\n\t/**\n\t * List every route pattern that currently has at least one per-route\n\t * config override. Use {@link adminConfigGetRoute} to read individual\n\t * fields. Requires elevated role.\n\t */\n\tasync adminConfigListRoutes(): Promise<string[]> {\n\t\tconst res = await this.request<{ routes: string[] }>(\n\t\t\t\"GET\", \"/admin/config/routes\",\n\t\t);\n\t\treturn res.routes;\n\t}\n\n\t/**\n\t * Read a field's effective value scoped to `route`, falling back to\n\t * the global value when no per-route override exists. `origin_kind`\n\t * is `\"route_override\"` only when an override is actually set.\n\t */\n\tasync adminConfigGetRoute(route: string, path: string): Promise<AdminConfigField> {\n\t\treturn this.request<AdminConfigField>(\n\t\t\t\"GET\",\n\t\t\t`/admin/config/routes/${encodeURIComponent(route)}/fields/${encodeURIComponent(path)}`,\n\t\t);\n\t}\n\n\t/** Set or replace a per-route override. Mirrors {@link adminConfigSet}. */\n\tasync adminConfigSetRoute(route: string, path: string, value: unknown): Promise<AdminConfigField> {\n\t\treturn this.request<AdminConfigField>(\n\t\t\t\"PUT\",\n\t\t\t`/admin/config/routes/${encodeURIComponent(route)}/fields/${encodeURIComponent(path)}`,\n\t\t\t{ body: { value } },\n\t\t);\n\t}\n\n\t/** Clear a per-route override (falls back to global). True if one existed. */\n\tasync adminConfigUnsetRoute(route: string, path: string): Promise<boolean> {\n\t\tconst res = await this.request<{ existed: boolean }>(\n\t\t\t\"DELETE\",\n\t\t\t`/admin/config/routes/${encodeURIComponent(route)}/fields/${encodeURIComponent(path)}`,\n\t\t);\n\t\treturn res.existed;\n\t}\n\n\t// ── Snapshots ────────────────────────────────────────────────────────────\n\n\t/** List snapshot metadata for a document. */\n\tasync listSnapshots(docId: string, opts?: { limit?: number; offset?: number }): Promise<SnapshotMeta[]> {\n\t\tconst params = new URLSearchParams();\n\t\tif (opts?.limit != null) params.set(\"limit\", String(opts.limit));\n\t\tif (opts?.offset != null) params.set(\"offset\", String(opts.offset));\n\t\tconst qs = params.toString();\n\t\tconst res = await this.request<{ snapshots: SnapshotMeta[] }>(\n\t\t\t\"GET\", `/docs/${encodeURIComponent(docId)}/snapshots${qs ? `?${qs}` : \"\"}`,\n\t\t);\n\t\treturn res.snapshots;\n\t}\n\n\t/** Fetch a single snapshot including its base64-encoded data blob.\n\t * Pass `{ include: \"files\" }` to also receive the joined upload list\n\t * (each `fileBlock` / `coverUploadId` resolved against `uploads`). */\n\tasync getSnapshot(\n\t\tdocId: string,\n\t\tversion: number,\n\t\topts?: { include?: \"files\" | string },\n\t): Promise<SnapshotData> {\n\t\tconst qs = opts?.include ? `?include=${encodeURIComponent(opts.include)}` : \"\";\n\t\treturn this.request<SnapshotData>(\n\t\t\t\"GET\", `/docs/${encodeURIComponent(docId)}/snapshots/${version}${qs}`,\n\t\t);\n\t}\n\n\t/** Create a manual snapshot of the current document state. */\n\tasync createSnapshot(docId: string, opts?: { label?: string }): Promise<SnapshotCreateResult> {\n\t\treturn this.request<SnapshotCreateResult>(\n\t\t\t\"POST\", `/docs/${encodeURIComponent(docId)}/snapshots`,\n\t\t\t{ body: opts ?? {} },\n\t\t);\n\t}\n\n\t/** Delete a specific snapshot version. Requires manage permission. */\n\tasync deleteSnapshot(docId: string, version: number): Promise<void> {\n\t\tawait this.request(\"DELETE\", `/docs/${encodeURIComponent(docId)}/snapshots/${version}`);\n\t}\n\n\t/** Restore a snapshot by merging it forward into the current document state. */\n\tasync restoreSnapshot(docId: string, version: number): Promise<SnapshotRestoreResult> {\n\t\treturn this.request<SnapshotRestoreResult>(\n\t\t\t\"POST\", `/docs/${encodeURIComponent(docId)}/snapshots/${version}/restore`,\n\t\t\t{ body: {} },\n\t\t);\n\t}\n\n\t/** Fork a snapshot into a new document. */\n\tasync forkSnapshot(docId: string, version: number): Promise<SnapshotForkResult> {\n\t\treturn this.request<SnapshotForkResult>(\n\t\t\t\"POST\", `/docs/${encodeURIComponent(docId)}/snapshots/${version}/fork`,\n\t\t\t{ body: {} },\n\t\t);\n\t}\n\n\t// ── System ───────────────────────────────────────────────────────────────\n\n\t/** Health check — no auth required. */\n\tasync health(): Promise<HealthStatus> {\n\t\treturn this.request<HealthStatus>(\"GET\", \"/health\", { auth: false });\n\t}\n\n\t/**\n\t * Readiness probe — pings the database. Returns 200 with\n\t * `status: \"ready\"` only when the server can serve traffic, 503 with\n\t * `status: \"unready\"` otherwise (load balancers / Kubernetes probes\n\t * use the status code; the body is informational).\n\t *\n\t * The 503 case is special-cased here: instead of throwing, the method\n\t * returns the unready body so callers can react to the state without\n\t * try/catch boilerplate.\n\t */\n\tasync readyz(): Promise<ReadyzStatus> {\n\t\tconst res = await this._fetch(`${this.baseUrl}/readyz`, { method: \"GET\" });\n\t\tif (res.status === 200 || res.status === 503) {\n\t\t\treturn res.json() as Promise<ReadyzStatus>;\n\t\t}\n\t\tthrow await this.toError(res, \"GET\", \"/readyz\");\n\t}\n\n\t/**\n\t * Fetch server metadata including `root_doc_id` and the `[access]` policy.\n\t * No auth required.\n\t */\n\tasync serverInfo(): Promise<ServerInfo> {\n\t\treturn this.request<ServerInfo>(\"GET\", \"/info\", { auth: false });\n\t}\n\n\t/**\n\t * Drop this browser's caches for this server if its database has been\n\t * REPLACED since the last visit, and report what happened.\n\t *\n\t * **Call it before opening any provider**, and await it. A deleted database\n\t * is not a tombstone — it is a peer that lost its memory — so a tab that\n\t * reconnects with stale IndexedDB re-pushes the old tree into the fresh one\n\t * and a seeder adds its own on top: every page twice, then three times. Once\n\t * a provider holds a store open, `deleteDatabase` blocks instead of deleting\n\t * and the damage is already queued; those stores come back in `blocked`,\n\t * which is a signal that this ran too late rather than something to ignore.\n\t *\n\t * Returns `null` when there is nothing to do — no `server_id`, no browser\n\t * storage, a first visit, or the same database as last time. It never\n\t * throws: an app must not fail to start because a cache could not be tidied.\n\t *\n\t * @see dropCachesIfServerReplaced for what is dropped and what is kept.\n\t */\n\tasync ensureFreshServer(): Promise<ServerResetOutcome | null> {\n\t\ttry {\n\t\t\tconst info = await this.serverInfo();\n\t\t\tif (!info?.server_id) return null;\n\t\t\t// `host`, matching how providers scope their stores — the port is part\n\t\t\t// of a server's identity, so two servers on one machine do not share a\n\t\t\t// cache namespace.\n\t\t\tconst host = new URL(this.wsUrl).host;\n\t\t\treturn await dropCachesIfServerReplaced(host, info.server_id);\n\t\t} catch {\n\t\t\treturn null;\n\t\t}\n\t}\n\n\t/**\n\t * Fetch ICE server configuration for WebRTC peer connections.\n\t * Falls back to default Google STUN server if the endpoint is unavailable.\n\t * No auth required.\n\t */\n\tasync getIceServers(): Promise<RTCIceServer[]> {\n\t\ttry {\n\t\t\tconst res = await this.request<{ iceServers: RTCIceServer[] }>(\n\t\t\t\t\"GET\",\n\t\t\t\t\"/ice-servers\",\n\t\t\t\t{ auth: false },\n\t\t\t);\n\t\t\treturn res.iceServers;\n\t\t} catch {\n\t\t\treturn [{ urls: \"stun:stun.l.google.com:19302\" }];\n\t\t}\n\t}\n\n\t// ── Internals ────────────────────────────────────────────────────────────\n\n\tprivate async request<T = void>(\n\t\tmethod: string,\n\t\tpath: string,\n\t\topts?: { body?: unknown; auth?: boolean },\n\t): Promise<T> {\n\t\tconst auth = opts?.auth ?? true;\n\t\tconst headers: Record<string, string> = {};\n\n\t\tif (auth && this._token) {\n\t\t\theaders[\"Authorization\"] = `Bearer ${this._token}`;\n\t\t}\n\n\t\tconst init: RequestInit = { method, headers, signal: AbortSignal.timeout(30_000) };\n\n\t\tif (opts?.body !== undefined) {\n\t\t\theaders[\"Content-Type\"] = \"application/json\";\n\t\t\tinit.body = JSON.stringify(opts.body);\n\t\t}\n\n\t\tconst res = await this._fetch(`${this.baseUrl}${path}`, init);\n\n\t\tif (!res.ok) {\n\t\t\tthrow await this.toError(res, method, path);\n\t\t}\n\n\t\t// 204 No Content\n\t\tif (res.status === 204) {\n\t\t\treturn undefined as T;\n\t\t}\n\n\t\treturn res.json() as Promise<T>;\n\t}\n\n\tprivate async requestOrNull<T>(\n\t\tmethod: string,\n\t\tpath: string,\n\t\topts?: { body?: unknown; auth?: boolean },\n\t): Promise<T | null> {\n\t\ttry {\n\t\t\treturn await this.request<T>(method, path, opts);\n\t\t} catch (e: unknown) {\n\t\t\tif (typeof e === \"object\" && e !== null && \"status\" in e && (e as { status: number }).status === 404) {\n\t\t\t\treturn null;\n\t\t\t}\n\t\t\tthrow e;\n\t\t}\n\t}\n\n\tprivate async toError(res: Response, method?: string, path?: string): Promise<Error> {\n\t\tlet message: string;\n\t\ttry {\n\t\t\tconst body = await res.json() as { error?: string };\n\t\t\tmessage = body.error ?? res.statusText;\n\t\t} catch {\n\t\t\tmessage = res.statusText;\n\t\t}\n\t\tconst prefix = method && path ? `${method} ${path}: ` : \"\";\n\t\tconst err = new Error(`${prefix}${message} (${res.status})`);\n\t\t(err as any).status = res.status;\n\t\t// Surface 401/403 to the auth-failed handler so consumers can trigger\n\t\t// reauth without waiting for the next WS action. Fire-and-forget —\n\t\t// the original Promise still rejects so callers handle their own\n\t\t// error path. Wrap in setTimeout(0) so the callback runs out-of-band\n\t\t// of the current request's microtask queue.\n\t\tif ((res.status === 401 || res.status === 403) && this._onAuthFailed) {\n\t\t\tconst lower = message.toLowerCase();\n\t\t\tlet reason: AuthFailureReason = res.status === 401 ? \"unauthorized\" : \"forbidden\";\n\t\t\tif (/user not found|user_not_found|public key not registered|no such user/.test(lower)) {\n\t\t\t\treason = \"user_not_found\";\n\t\t\t} else if (/account revoked|user account revoked/.test(lower)) {\n\t\t\t\treason = \"account_revoked\";\n\t\t\t} else if (/forbidden|insufficient permissions/.test(lower)) {\n\t\t\t\treason = \"forbidden\";\n\t\t\t}\n\t\t\tconst ctx: AuthFailureContext = {\n\t\t\t\tstatus: res.status,\n\t\t\t\tmessage,\n\t\t\t\treason,\n\t\t\t\tmethod: method ?? \"\",\n\t\t\t\tpath: path ?? \"\",\n\t\t\t};\n\t\t\ttry {\n\t\t\t\tsetTimeout(() => { try { this._onAuthFailed!(ctx); } catch { /* swallow */ } }, 0);\n\t\t\t} catch { /* setTimeout unavailable in some sandboxes — drop the signal */ }\n\t\t}\n\t\treturn err;\n\t}\n\n\tprivate loadPersistedToken(): string | null {\n\t\ttry {\n\t\t\treturn localStorage.getItem(this.storageKey);\n\t\t} catch {\n\t\t\treturn null;\n\t\t}\n\t}\n\n\tprivate persistToken(token: string): void {\n\t\ttry {\n\t\t\tlocalStorage.setItem(this.storageKey, token);\n\t\t} catch {\n\t\t\t// localStorage unavailable (SSR / Node.js)\n\t\t}\n\t}\n\n\tprivate clearPersistedToken(): void {\n\t\ttry {\n\t\t\tlocalStorage.removeItem(this.storageKey);\n\t\t} catch {\n\t\t\t// localStorage unavailable\n\t\t}\n\t}\n}\n","import EventEmitter from \"./EventEmitter.ts\";\nimport type { AbracadabraClient } from \"./AbracadabraClient.ts\";\n\n/**\n * On-disk shape of a device session. The server returns these values from\n * `POST /auth/device-session`; persistence keeps them across reloads so a\n * warm boot can mint a fresh JWT without re-prompting for the passkey.\n */\nexport interface DeviceSessionRecord {\n\tsessionId: string;\n\tsessionToken: string;\n\t/** Unix seconds — matches what the server returns. */\n\texpiresAt: number;\n}\n\nexport interface DeviceSessionStorage {\n\tload(): DeviceSessionRecord | null;\n\tsave(record: DeviceSessionRecord): void;\n\tclear(): void;\n}\n\nconst DEFAULT_STORAGE_KEY = \"abracadabra:device-session\";\n\n/** localStorage-backed storage; safe in SSR/Node (no-ops without localStorage). */\nexport class LocalStorageDeviceSessionStorage implements DeviceSessionStorage {\n\tconstructor(private readonly key: string = DEFAULT_STORAGE_KEY) {}\n\n\tload(): DeviceSessionRecord | null {\n\t\ttry {\n\t\t\tconst raw = localStorage.getItem(this.key);\n\t\t\tif (!raw) return null;\n\t\t\tconst parsed = JSON.parse(raw) as DeviceSessionRecord;\n\t\t\tif (\n\t\t\t\ttypeof parsed?.sessionId === \"string\" &&\n\t\t\t\ttypeof parsed?.sessionToken === \"string\" &&\n\t\t\t\ttypeof parsed?.expiresAt === \"number\"\n\t\t\t) {\n\t\t\t\treturn parsed;\n\t\t\t}\n\t\t\treturn null;\n\t\t} catch {\n\t\t\treturn null;\n\t\t}\n\t}\n\n\tsave(record: DeviceSessionRecord): void {\n\t\ttry {\n\t\t\tlocalStorage.setItem(this.key, JSON.stringify(record));\n\t\t} catch {\n\t\t\t/* localStorage unavailable */\n\t\t}\n\t}\n\n\tclear(): void {\n\t\ttry {\n\t\t\tlocalStorage.removeItem(this.key);\n\t\t} catch {\n\t\t\t/* localStorage unavailable */\n\t\t}\n\t}\n}\n\nexport interface TokenManagerOptions {\n\tclient: AbracadabraClient;\n\t/**\n\t * Where the device session record lives. Defaults to a localStorage\n\t * adapter under \"abracadabra:device-session\".\n\t */\n\tstorage?: DeviceSessionStorage;\n\t/**\n\t * Refresh the JWT this many milliseconds before its `exp`. Defaults to\n\t * 5 minutes — well clear of clock skew without burning a refresh per\n\t * minute. Refreshes are also dedup'd via in-flight promise.\n\t */\n\trefreshLeadMs?: number;\n\t/**\n\t * Hook `document.visibilitychange` and `window.online` to opportunistically\n\t * refresh when the tab/network resumes. Default true. The proactive\n\t * `setTimeout` doesn't fire reliably while the tab is hidden or the\n\t * laptop is asleep, which is the actual breakage path being addressed —\n\t * the resume hook is what makes the system self-heal after a long sleep.\n\t */\n\tinstallResumeHandlers?: boolean;\n}\n\n/**\n * Manages the lifetime of the short-lived JWT against a long-lived device\n * session token.\n *\n * Flow:\n * - Bootstrap: if a stored device session exists, exchange it for a fresh\n * JWT immediately (`bootstrap()`). Otherwise the consumer must run a\n * full crypto-auth handshake and then call `attachSession(record)` once\n * the server returns a device-session token.\n * - Steady state: `getValidToken()` returns the JWT, refreshing if the\n * JWT is within `refreshLeadMs` of expiry. Concurrent callers share one\n * in-flight refresh.\n * - Background: a proactive timer fires `refreshLeadMs` before `exp`.\n * `visibilitychange` and `online` events trigger an opportunistic\n * refresh in case the timer was suppressed (hidden tab, sleeping\n * laptop). The combination is what restores the WS without a reload.\n * - Failure: refresh errors with status 401/403 mean the device session\n * itself is dead (revoked or 30 d expired). The record is cleared and\n * `session-expired` fires so the consumer can prompt re-auth. Other\n * errors (network) are transparent — the existing JWT is returned and\n * the caller's normal retry loop covers it.\n */\nexport class TokenManager extends EventEmitter {\n\tprivate readonly client: AbracadabraClient;\n\tprivate readonly storage: DeviceSessionStorage;\n\tprivate readonly refreshLeadMs: number;\n\tprivate session: DeviceSessionRecord | null;\n\tprivate refreshing: Promise<string> | null = null;\n\tprivate proactiveTimer: ReturnType<typeof setTimeout> | null = null;\n\tprivate resumeHandlersInstalled = false;\n\tprivate boundOnResume: (() => void) | null = null;\n\tprivate disposed = false;\n\n\tconstructor(options: TokenManagerOptions) {\n\t\tsuper();\n\t\tthis.client = options.client;\n\t\tthis.storage = options.storage ?? new LocalStorageDeviceSessionStorage();\n\t\tthis.refreshLeadMs = options.refreshLeadMs ?? 5 * 60 * 1000;\n\t\tthis.session = this.storage.load();\n\t\tif (options.installResumeHandlers !== false) {\n\t\t\tthis.installResumeHandlers();\n\t\t}\n\t\t// Schedule a refresh against the JWT the client may already be\n\t\t// holding (loaded from persistAuth localStorage) so warm boots\n\t\t// without an explicit bootstrap() still benefit from proactive\n\t\t// refresh on the existing token.\n\t\tthis.scheduleProactiveRefresh();\n\t}\n\n\tget hasSession(): boolean {\n\t\treturn this.session !== null;\n\t}\n\n\tget currentSession(): DeviceSessionRecord | null {\n\t\treturn this.session;\n\t}\n\n\t/**\n\t * Persist a freshly-issued device session and exchange it immediately\n\t * for a JWT. Call this once after a successful crypto-auth login when\n\t * the server returns a device-session token.\n\t */\n\tasync attachSession(record: DeviceSessionRecord): Promise<string> {\n\t\tthis.session = record;\n\t\tthis.storage.save(record);\n\t\tconst jwt = await this.runRefresh();\n\t\treturn jwt;\n\t}\n\n\t/**\n\t * Drop the local device session (no server call). Use after a logout\n\t * or when `session-expired` fires. To revoke server-side as well, call\n\t * `client.revokeDeviceSession(sessionId)` first.\n\t */\n\tclearSession(): void {\n\t\tthis.session = null;\n\t\tthis.storage.clear();\n\t\tif (this.proactiveTimer) {\n\t\t\tclearTimeout(this.proactiveTimer);\n\t\t\tthis.proactiveTimer = null;\n\t\t}\n\t}\n\n\t/**\n\t * Return a valid JWT, refreshing if it is missing or within\n\t * `refreshLeadMs` of expiry. Safe to call concurrently — one\n\t * refresh is in flight at a time.\n\t *\n\t * Transient refresh errors (network) fall back to the cached JWT so\n\t * the WS auth attempt can still proceed; the server will reject and\n\t * the next reconnect tries again. Only 401/403 from the refresh\n\t * endpoint surfaces as a thrown error here, since those mean the\n\t * device session itself is dead.\n\t */\n\tasync getValidToken(): Promise<string> {\n\t\tif (this.refreshing) return this.refreshing;\n\t\tconst current = this.client.token;\n\t\tif (current && this.tokenIsFresh(current)) return current;\n\t\tif (!this.session) return current ?? \"\";\n\t\ttry {\n\t\t\treturn await this.runRefresh();\n\t\t} catch (err) {\n\t\t\tconst status = (err as { status?: number })?.status;\n\t\t\tif (status === 401 || status === 403) throw err;\n\t\t\t// Transient — let the caller use the stale token; the server\n\t\t\t// will reject and the WS reconnect loop will retry the refresh.\n\t\t\treturn current ?? \"\";\n\t\t}\n\t}\n\n\t/**\n\t * If a stored device session exists, exchange it for a fresh JWT now.\n\t * Returns the JWT (or null if there is no session to bootstrap from).\n\t * Throws on 401/403 — the stored session is invalid and the caller\n\t * should fall through to a full crypto-auth flow.\n\t */\n\tasync bootstrap(): Promise<string | null> {\n\t\tif (!this.session) return null;\n\t\ttry {\n\t\t\treturn await this.runRefresh();\n\t\t} catch (err) {\n\t\t\tconst status = (err as { status?: number })?.status;\n\t\t\tif (status === 401 || status === 403) throw err;\n\t\t\t// Transient — caller decides what to do (e.g. fall back to\n\t\t\t// passkey login or proceed offline).\n\t\t\treturn null;\n\t\t}\n\t}\n\n\tdispose(): void {\n\t\tif (this.disposed) return;\n\t\tthis.disposed = true;\n\t\tif (this.proactiveTimer) {\n\t\t\tclearTimeout(this.proactiveTimer);\n\t\t\tthis.proactiveTimer = null;\n\t\t}\n\t\tif (this.boundOnResume) {\n\t\t\ttry {\n\t\t\t\tif (typeof document !== \"undefined\") {\n\t\t\t\t\tdocument.removeEventListener(\"visibilitychange\", this.boundOnResume);\n\t\t\t\t}\n\t\t\t\tif (typeof window !== \"undefined\") {\n\t\t\t\t\twindow.removeEventListener(\"online\", this.boundOnResume);\n\t\t\t\t}\n\t\t\t} catch { /* environment without listener APIs */ }\n\t\t\tthis.boundOnResume = null;\n\t\t}\n\t\tthis.removeAllListeners();\n\t}\n\n\t// ── internals ───────────────────────────────────────────────────────────\n\n\tprivate runRefresh(): Promise<string> {\n\t\tif (this.refreshing) return this.refreshing;\n\t\tif (!this.session) return Promise.reject(new Error(\"No device session\"));\n\t\tconst sessionToken = this.session.sessionToken;\n\t\tthis.refreshing = (async () => {\n\t\t\ttry {\n\t\t\t\tconst jwt = await this.client.refreshWithDeviceSession(sessionToken);\n\t\t\t\tthis.scheduleProactiveRefresh();\n\t\t\t\tthis.emit(\"refresh\", jwt);\n\t\t\t\treturn jwt;\n\t\t\t} catch (err) {\n\t\t\t\tconst status = (err as { status?: number })?.status;\n\t\t\t\tif (status === 401 || status === 403) {\n\t\t\t\t\tconst message = (err as Error)?.message ?? \"device session rejected\";\n\t\t\t\t\tthis.clearSession();\n\t\t\t\t\tthis.emit(\"session-expired\", { status, message });\n\t\t\t\t}\n\t\t\t\tthrow err;\n\t\t\t} finally {\n\t\t\t\tthis.refreshing = null;\n\t\t\t}\n\t\t})();\n\t\treturn this.refreshing;\n\t}\n\n\tprivate tokenIsFresh(jwt: string): boolean {\n\t\tconst exp = this.parseExp(jwt);\n\t\tif (exp == null) return false;\n\t\treturn exp * 1000 - Date.now() > this.refreshLeadMs;\n\t}\n\n\tprivate parseExp(jwt: string): number | null {\n\t\ttry {\n\t\t\tconst [, payload] = jwt.split(\".\");\n\t\t\tif (!payload) return null;\n\t\t\t// base64url-safe: `atob` alone throws on `-`/`_`, which would make\n\t\t\t// the proactive-refresh timer treat a valid token as unparseable.\n\t\t\tlet b64 = payload.replace(/-/g, \"+\").replace(/_/g, \"/\");\n\t\t\tconst pad = b64.length % 4;\n\t\t\tif (pad) b64 += \"=\".repeat(4 - pad);\n\t\t\tconst json = new TextDecoder().decode(\n\t\t\t\tUint8Array.from(atob(b64), (c) => c.charCodeAt(0)),\n\t\t\t);\n\t\t\tconst { exp } = JSON.parse(json);\n\t\t\treturn typeof exp === \"number\" ? exp : null;\n\t\t} catch {\n\t\t\treturn null;\n\t\t}\n\t}\n\n\tprivate scheduleProactiveRefresh(): void {\n\t\tif (this.proactiveTimer) {\n\t\t\tclearTimeout(this.proactiveTimer);\n\t\t\tthis.proactiveTimer = null;\n\t\t}\n\t\tif (!this.session || this.disposed) return;\n\t\tconst jwt = this.client.token;\n\t\tconst exp = jwt ? this.parseExp(jwt) : null;\n\t\tif (exp == null) {\n\t\t\t// No JWT yet — defer; whoever calls getValidToken() / bootstrap()\n\t\t\t// will reschedule once a JWT lands.\n\t\t\treturn;\n\t\t}\n\t\t// Floor at 30 s so a near-expired token doesn't trigger a busy\n\t\t// refresh-then-immediately-refresh-again loop on clock skew.\n\t\tconst delay = Math.max(30_000, exp * 1000 - Date.now() - this.refreshLeadMs);\n\t\tthis.proactiveTimer = setTimeout(() => {\n\t\t\tthis.runRefresh().catch(() => {\n\t\t\t\t// 401/403 already surfaced via session-expired event;\n\t\t\t\t// transient errors are no-ops — the resume handler or the\n\t\t\t\t// next getValidToken() call will retry.\n\t\t\t});\n\t\t}, delay);\n\t}\n\n\tprivate installResumeHandlers(): void {\n\t\tif (this.resumeHandlersInstalled) return;\n\t\tif (typeof document === \"undefined\" && typeof window === \"undefined\") return;\n\t\tconst onResume = () => {\n\t\t\tif (this.disposed) return;\n\t\t\tif (typeof document !== \"undefined\" && document.visibilityState === \"hidden\") return;\n\t\t\tif (!this.session) return;\n\t\t\tconst jwt = this.client.token;\n\t\t\tif (jwt && this.tokenIsFresh(jwt)) return;\n\t\t\tthis.runRefresh().catch(() => {\n\t\t\t\t/* same swallow as above */\n\t\t\t});\n\t\t};\n\t\tthis.boundOnResume = onResume;\n\t\ttry {\n\t\t\tif (typeof document !== \"undefined\") {\n\t\t\t\tdocument.addEventListener(\"visibilitychange\", onResume);\n\t\t\t}\n\t\t\tif (typeof window !== \"undefined\") {\n\t\t\t\twindow.addEventListener(\"online\", onResume);\n\t\t\t}\n\t\t\tthis.resumeHandlersInstalled = true;\n\t\t} catch { /* environment without listener APIs */ }\n\t}\n}\n","export interface CloseEvent {\n\tcode: number;\n\treason: string;\n}\n\n/**\n * The server is terminating the connection because a data frame was received\n * that is too large.\n * See: https://developer.mozilla.org/en-US/docs/Web/API/CloseEvent/code\n */\nexport const MessageTooBig: CloseEvent = {\n\tcode: 1009,\n\treason: \"Message Too Big\",\n};\n\n/**\n * The server successfully processed the request, asks that the requester reset\n * its document view, and is not returning any content.\n */\nexport const ResetConnection: CloseEvent = {\n\tcode: 4205,\n\treason: \"Reset Connection\",\n};\n\n/**\n * Similar to Forbidden, but specifically for use when authentication is required and has\n * failed or has not yet been provided.\n */\nexport const Unauthorized: CloseEvent = {\n\tcode: 4401,\n\treason: \"Unauthorized\",\n};\n\n/**\n * The request contained valid data and was understood by the server, but the server\n * is refusing action.\n */\nexport const Forbidden: CloseEvent = {\n\tcode: 4403,\n\treason: \"Forbidden\",\n};\n\n/**\n * The server timed out waiting for the request.\n */\nexport const ConnectionTimeout: CloseEvent = {\n\tcode: 4408,\n\treason: \"Connection Timeout\",\n};\n","/**\n * MnemonicKeyDerivation\n *\n * Pure, stateless functions for BIP-39 mnemonic-based Ed25519 identity\n * derivation and AES-256-GCM seed wrapping. No IndexedDB, no WebAuthn,\n * no DOM access — fully unit-testable.\n *\n * Derivation chain:\n * BIP-39 Mnemonic (+optional passphrase)\n * → PBKDF2-HMAC-SHA512 (2048 rounds, per BIP-39 spec)\n * → first 32 bytes as IKM\n * → HKDF-SHA256(salt=\"abracadabra-mnemonic-v1\", info=\"abracadabra-identity-v1\")\n * → Ed25519 seed (32 bytes)\n * → Ed25519 keypair + X25519 (Montgomery conversion)\n *\n * The HKDF salt differs from the passkey PRF path (which uses PRF_SALT),\n * providing domain separation: identical raw input bytes can never produce\n * the same Ed25519 seed across the two derivation methods.\n *\n * Dependencies: @scure/bip39, @noble/ed25519, @noble/hashes, @noble/curves\n */\n\nimport * as ed from \"@noble/ed25519\";\nimport { hkdf } from \"@noble/hashes/hkdf.js\";\nimport { sha256, sha512 } from \"@noble/hashes/sha2.js\";\nimport { ed25519 as nobleEd25519Curves } from \"@noble/curves/ed25519.js\";\nimport { generateMnemonic as _generateMnemonic, validateMnemonic as _validateMnemonic, mnemonicToSeedSync } from \"@scure/bip39\";\nimport { wordlist } from \"@scure/bip39/wordlists/english.js\";\n\n// @noble/ed25519 v3 hash hook (idempotent across modules).\ned.hashes.sha512 = sha512;\ned.hashes.sha512Async = (m: Uint8Array) => Promise.resolve(sha512(m));\n\n// ── Constants ───────────────────────────────────────────────────────────────\n\n/** HKDF salt for mnemonic → Ed25519 seed derivation. */\nconst MNEMONIC_HKDF_SALT = /* @__PURE__ */ new TextEncoder().encode(\"abracadabra-mnemonic-v1\");\n\n/** HKDF info string — intentionally matches the passkey path's HKDF_INFO. */\nconst MNEMONIC_HKDF_INFO = /* @__PURE__ */ new TextEncoder().encode(\"abracadabra-identity-v1\");\n\n/** HKDF info string for deriving the AES-GCM seed-wrapping key from PRF output. */\nexport const SEED_WRAP_INFO = /* @__PURE__ */ new TextEncoder().encode(\"abracadabra-seed-wrap-v1\");\n\n// ── Helpers ─────────────────────────────────────────────────────────────────\n\nfunction toBase64url(bytes: Uint8Array): string {\n\treturn btoa(String.fromCharCode(...bytes))\n\t\t.replace(/\\+/g, \"-\")\n\t\t.replace(/\\//g, \"_\")\n\t\t.replace(/=/g, \"\");\n}\n\n// ── Mnemonic generation & validation ────────────────────────────────────────\n\n/**\n * Generate a new BIP-39 mnemonic phrase.\n * @param strength 128 for 12 words (default), 256 for 24 words.\n */\nexport function generateMnemonic(strength: 128 | 256 = 128): string {\n\treturn _generateMnemonic(wordlist, strength);\n}\n\n/**\n * Validate a BIP-39 mnemonic (wordlist + checksum).\n */\nexport function validateMnemonic(mnemonic: string): boolean {\n\treturn _validateMnemonic(mnemonic, wordlist);\n}\n\n/**\n * Re-export the English wordlist for UI auto-complete.\n */\nexport { wordlist as bip39Wordlist };\n\n// ── Key derivation ──────────────────────────────────────────────────────────\n\n/**\n * Derive a 32-byte Ed25519 seed from a BIP-39 mnemonic.\n *\n * Chain: mnemonic → PBKDF2-HMAC-SHA512 (2048 rounds) → first 32 bytes →\n * HKDF-SHA256(salt, info) → 32-byte seed.\n *\n * @param mnemonic Valid BIP-39 mnemonic (12 or 24 words).\n * @param passphrase Optional BIP-39 passphrase (\"25th word\").\n * @returns 32-byte Ed25519 seed. Caller MUST wipe after use: `seed.fill(0)`.\n */\nexport function mnemonicToEd25519Seed(mnemonic: string, passphrase?: string): Uint8Array {\n\t// BIP-39: PBKDF2-HMAC-SHA512(mnemonic, \"mnemonic\" + passphrase, 2048) → 64 bytes\n\tconst bip39Seed = mnemonicToSeedSync(mnemonic, passphrase ?? \"\");\n\t// Take first 32 bytes as input key material\n\tconst ikm = bip39Seed.subarray(0, 32);\n\t// HKDF-SHA256 with our domain-specific salt\n\tconst seed = hkdf(sha256, ikm, MNEMONIC_HKDF_SALT, MNEMONIC_HKDF_INFO, 32);\n\t// Wipe intermediate material\n\tbip39Seed.fill(0);\n\treturn seed;\n}\n\n/**\n * Derive the full Ed25519 + X25519 keypair from a BIP-39 mnemonic.\n *\n * @param mnemonic Valid BIP-39 mnemonic.\n * @param passphrase Optional BIP-39 passphrase.\n * @returns Keys and seed. Caller MUST wipe `seed` after use.\n */\nexport async function mnemonicToKeyPair(\n\tmnemonic: string,\n\tpassphrase?: string,\n): Promise<{\n\tseed: Uint8Array;\n\tpublicKey: Uint8Array;\n\tpublicKeyB64: string;\n\tx25519PublicKey: Uint8Array;\n\tx25519PublicKeyB64: string;\n}> {\n\tconst seed = mnemonicToEd25519Seed(mnemonic, passphrase);\n\tconst publicKey = await ed.getPublicKeyAsync(seed);\n\tconst publicKeyB64 = toBase64url(publicKey);\n\tconst x25519PublicKey = nobleEd25519Curves.utils.toMontgomery(publicKey);\n\tconst x25519PublicKeyB64 = toBase64url(x25519PublicKey);\n\treturn { seed, publicKey, publicKeyB64, x25519PublicKey, x25519PublicKeyB64 };\n}\n\n// ── Seed wrapping (AES-256-GCM via WebCrypto) ──────────────────────────────\n\n/**\n * Derive a 32-byte AES-256-GCM key from WebAuthn PRF output for seed wrapping.\n *\n * @param prfOutput Raw PRF output from WebAuthn assertion (32 bytes typical).\n * @param wrapSalt Random 32-byte salt, stored alongside the ciphertext.\n */\nexport function deriveSeedWrappingKey(prfOutput: ArrayBuffer, wrapSalt: Uint8Array): Uint8Array {\n\treturn hkdf(sha256, new Uint8Array(prfOutput), wrapSalt, SEED_WRAP_INFO, 32);\n}\n\n/**\n * Encrypt an Ed25519 seed with AES-256-GCM.\n *\n * @param seed 32-byte Ed25519 seed to protect.\n * @param wrappingKeyBytes 32-byte AES key from `deriveSeedWrappingKey`.\n * @returns Ciphertext (48 bytes: 32 plaintext + 16 auth tag) and 12-byte IV.\n */\nexport async function wrapSeed(\n\tseed: Uint8Array,\n\twrappingKeyBytes: Uint8Array,\n): Promise<{ ciphertext: ArrayBuffer; iv: Uint8Array }> {\n\tconst iv = crypto.getRandomValues(new Uint8Array(12));\n\tconst key = await crypto.subtle.importKey(\"raw\", wrappingKeyBytes as BufferSource, \"AES-GCM\", false, [\"encrypt\"]);\n\tconst ciphertext = await crypto.subtle.encrypt({ name: \"AES-GCM\", iv: iv as BufferSource }, key, seed as BufferSource);\n\treturn { ciphertext, iv };\n}\n\n/**\n * Decrypt an Ed25519 seed from AES-256-GCM ciphertext.\n *\n * @param ciphertext Encrypted seed (48 bytes).\n * @param iv 12-byte GCM nonce.\n * @param wrappingKeyBytes 32-byte AES key from `deriveSeedWrappingKey`.\n * @returns 32-byte Ed25519 seed. Caller MUST wipe after use.\n * @throws If the auth tag is invalid (wrong key or tampered data).\n */\nexport async function unwrapSeed(\n\tciphertext: ArrayBuffer,\n\tiv: Uint8Array,\n\twrappingKeyBytes: Uint8Array,\n): Promise<Uint8Array> {\n\tconst key = await crypto.subtle.importKey(\"raw\", wrappingKeyBytes as BufferSource, \"AES-GCM\", false, [\"decrypt\"]);\n\tconst plaintext = await crypto.subtle.decrypt({ name: \"AES-GCM\", iv: iv as BufferSource }, key, ciphertext);\n\treturn new Uint8Array(plaintext);\n}\n","/**\n * CryptoIdentityKeystore\n *\n * Ed25519 identity management with two derivation modes:\n *\n * 1. **Passkey-only (legacy)**: PRF output → HKDF → Ed25519 seed.\n * The passkey IS the identity source.\n *\n * 2. **Mnemonic-rooted**: BIP-39 mnemonic → Ed25519 seed, encrypted by\n * passkey PRF for day-to-day convenience. The mnemonic IS the identity\n * source; the passkey is a convenience wrapper. Recovery via mnemonic\n * re-derives the exact same key.\n *\n * Both modes coexist. IndexedDB records with `encryptedSeed` use mode 2;\n * records without it use mode 1 (backward compatible).\n *\n * Dependencies: @noble/ed25519, @noble/hashes, @noble/curves, @scure/bip39\n */\n\nimport * as ed from \"@noble/ed25519\";\nimport { hkdf } from \"@noble/hashes/hkdf.js\";\nimport { sha256, sha512 } from \"@noble/hashes/sha2.js\";\nimport { ed25519 as nobleEd25519Curves } from \"@noble/curves/ed25519.js\";\n\n// @noble/ed25519 v3: wire sha512 for sync paths and define an async hook so\n// signAsync/verifyAsync don't require a Web Crypto fallback in Node.\ned.hashes.sha512 = sha512;\ned.hashes.sha512Async = (m: Uint8Array) => Promise.resolve(sha512(m));\nimport {\n\tmnemonicToKeyPair,\n\tmnemonicToEd25519Seed,\n\tderiveSeedWrappingKey,\n\twrapSeed,\n\tunwrapSeed,\n} from \"./MnemonicKeyDerivation.ts\";\n\n// ── Constants ───────────────────────────────────────────────────────────────\n\n/**\n * Fixed PRF eval salt. Must be constant across all devices so the same synced\n * passkey produces the same PRF output everywhere.\n *\n * Value: SHA-256(\"abracadabra-prf-salt-v1\"), precomputed.\n */\nconst PRF_SALT = new Uint8Array([\n\t0xb7, 0x79, 0x41, 0xa2, 0xe7, 0x85, 0x1d, 0xfa,\n\t0x5e, 0xc1, 0xab, 0xb6, 0x50, 0x1a, 0x5c, 0x85,\n\t0x75, 0xfd, 0x3e, 0x3f, 0x92, 0xc9, 0xe1, 0xa7,\n\t0x4e, 0xba, 0x71, 0xfc, 0xf2, 0xb1, 0x12, 0xcf,\n]);\n\nconst HKDF_INFO = new TextEncoder().encode(\"abracadabra-identity-v1\");\n\n// ── Types ────────────────────────────────────────────────────────────────────\n\n/** Lightweight cache record — no private key material stored in plaintext. */\ninterface StoredIdentity {\n\tusername: string;\n\t/** base64url-encoded Ed25519 public key (32 bytes). */\n\tpublicKey: string;\n\t/** WebAuthn credential ID for allowCredentials hint. */\n\tcredentialId: ArrayBuffer;\n\t// ── Mnemonic-rooted fields (absent = legacy passkey-only mode) ──\n\t/** AES-256-GCM ciphertext of the 32-byte Ed25519 seed (48 bytes with tag). */\n\tencryptedSeed?: ArrayBuffer;\n\t/** 12-byte AES-GCM nonce used for seed encryption. */\n\tseedIv?: Uint8Array;\n\t/** 32-byte random salt for HKDF(PRF → wrapping key). Per-credential. */\n\twrapSalt?: Uint8Array;\n\t/** How the identity was created. Absent = legacy passkey-only. */\n\tauthMethod?: \"passkey\" | \"mnemonic\";\n}\n\n// ── Helpers ──────────────────────────────────────────────────────────────────\n\nfunction toBase64url(bytes: Uint8Array): string {\n\treturn btoa(String.fromCharCode(...bytes))\n\t\t.replace(/\\+/g, \"-\")\n\t\t.replace(/\\//g, \"_\")\n\t\t.replace(/=/g, \"\");\n}\n\nfunction fromBase64url(b64: string): Uint8Array {\n\tconst padded = b64.replace(/-/g, \"+\").replace(/_/g, \"/\");\n\tconst padLen = (4 - (padded.length % 4)) % 4;\n\tconst padded2 = padded + \"=\".repeat(padLen);\n\treturn Uint8Array.from(atob(padded2), (c) => c.charCodeAt(0));\n}\n\nconst DB_NAME = \"abracadabra:identity\";\nconst STORE_NAME = \"identity\";\n\n// ── IndexedDB helpers ─────────────────────────────────────────────────────────\n\nfunction openDb(): Promise<IDBDatabase> {\n\treturn new Promise((resolve, reject) => {\n\t\tconst req = indexedDB.open(DB_NAME, 3);\n\t\treq.onupgradeneeded = () => {\n\t\t\tconst db = req.result;\n\t\t\t// v1: plain object store; v2: credentialId-keyed records\n\t\t\t// v3: optional encryptedSeed/seedIv/wrapSalt/authMethod fields on values\n\t\t\t// (no structural changes — same store, new optional value fields)\n\t\t\tif (!db.objectStoreNames.contains(STORE_NAME)) {\n\t\t\t\tdb.createObjectStore(STORE_NAME);\n\t\t\t}\n\t\t};\n\t\treq.onsuccess = () => resolve(req.result);\n\t\treq.onerror = () => reject(req.error);\n\t});\n}\n\nasync function dbGetAll(db: IDBDatabase): Promise<{ key: IDBValidKey; value: StoredIdentity }[]> {\n\treturn new Promise((resolve, reject) => {\n\t\tconst tx = db.transaction(STORE_NAME, \"readonly\");\n\t\tconst store = tx.objectStore(STORE_NAME);\n\t\tconst results: { key: IDBValidKey; value: StoredIdentity }[] = [];\n\t\tconst req = store.openCursor();\n\t\treq.onsuccess = () => {\n\t\t\tconst cursor = req.result;\n\t\t\tif (cursor) {\n\t\t\t\tresults.push({ key: cursor.key, value: cursor.value as StoredIdentity });\n\t\t\t\tcursor.continue();\n\t\t\t} else {\n\t\t\t\tresolve(results);\n\t\t\t}\n\t\t};\n\t\treq.onerror = () => reject(req.error);\n\t});\n}\n\nasync function dbGet(db: IDBDatabase, key: string): Promise<StoredIdentity | undefined> {\n\treturn new Promise((resolve, reject) => {\n\t\tconst tx = db.transaction(STORE_NAME, \"readonly\");\n\t\tconst req = tx.objectStore(STORE_NAME).get(key);\n\t\treq.onsuccess = () => resolve(req.result as StoredIdentity | undefined);\n\t\treq.onerror = () => reject(req.error);\n\t});\n}\n\nasync function dbPut(db: IDBDatabase, key: string, value: StoredIdentity): Promise<void> {\n\treturn new Promise((resolve, reject) => {\n\t\tconst tx = db.transaction(STORE_NAME, \"readwrite\");\n\t\tconst req = tx.objectStore(STORE_NAME).put(value, key);\n\t\treq.onsuccess = () => resolve();\n\t\treq.onerror = () => reject(req.error);\n\t});\n}\n\nasync function dbDelete(db: IDBDatabase, key: string): Promise<void> {\n\treturn new Promise((resolve, reject) => {\n\t\tconst tx = db.transaction(STORE_NAME, \"readwrite\");\n\t\tconst req = tx.objectStore(STORE_NAME).delete(key);\n\t\treq.onsuccess = () => resolve();\n\t\treq.onerror = () => reject(req.error);\n\t});\n}\n\nasync function dbClear(db: IDBDatabase): Promise<void> {\n\treturn new Promise((resolve, reject) => {\n\t\tconst tx = db.transaction(STORE_NAME, \"readwrite\");\n\t\tconst req = tx.objectStore(STORE_NAME).clear();\n\t\treq.onsuccess = () => resolve();\n\t\treq.onerror = () => reject(req.error);\n\t});\n}\n\n// ── Key derivation ────────────────────────────────────────────────────────────\n\n/** Derive a 32-byte Ed25519 seed from raw PRF output. */\nfunction deriveEd25519Seed(prfOutput: ArrayBuffer): Uint8Array {\n\treturn hkdf(sha256, new Uint8Array(prfOutput), PRF_SALT, HKDF_INFO, 32);\n}\n\n// ── PRF extraction helper ────────────────────────────────────────────────────\n\nfunction extractPrfOutput(\n\tcredential: PublicKeyCredential,\n): ArrayBuffer {\n\tconst extResults = credential.getClientExtensionResults() as {\n\t\tprf?: { results?: { first?: ArrayBuffer } };\n\t};\n\tconst prfOutput = extResults?.prf?.results?.first;\n\tif (!prfOutput) {\n\t\tthrow new Error(\n\t\t\t\"WebAuthn PRF extension not available on this authenticator. \" +\n\t\t\t\"A PRF-capable platform authenticator (e.g. iCloud Keychain) is required.\",\n\t\t);\n\t}\n\treturn prfOutput;\n}\n\n// ── Main class ───────────────────────────────────────────────────────────────\n\nexport class CryptoIdentityKeystore {\n\n\t/**\n\t * Check whether the platform supports WebAuthn with PRF extension.\n\t * Call this before offering the \"Secure with Passkey\" option.\n\t */\n\tstatic async isPrfAvailable(): Promise<boolean> {\n\t\tif (typeof window === \"undefined\" || !window.PublicKeyCredential) return false;\n\t\ttry {\n\t\t\t// Check for platform authenticator\n\t\t\tconst available = await PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable();\n\t\t\tif (!available) return false;\n\n\t\t\t// PRF is indicated by the presence of the extension in the client;\n\t\t\t// there's no direct feature-detection API. We check for the\n\t\t\t// AuthenticationExtensionsClientInputs type support as a proxy.\n\t\t\t// The definitive test happens at registration time.\n\t\t\treturn true;\n\t\t} catch {\n\t\t\treturn false;\n\t\t}\n\t}\n\n\t/**\n\t * Create a synced discoverable passkey and derive the Ed25519 identity from\n\t * its PRF output. The passkey is stored in the platform credential manager\n\t * (e.g. iCloud Keychain) and syncs across devices automatically.\n\t *\n\t * Returns the base64url-encoded public key, X25519 public key, and credential ID.\n\t * The caller must register the public key with the server.\n\t */\n\tasync register(\n\t\tusername: string,\n\t\trpId: string,\n\t\trpName: string,\n\t): Promise<{ publicKey: string; x25519PublicKey: string; credentialId: string }> {\n\t\t// 1. Create a discoverable WebAuthn credential with PRF\n\t\tconst credential = await navigator.credentials.create({\n\t\t\tpublicKey: {\n\t\t\t\tchallenge: crypto.getRandomValues(new Uint8Array(32)),\n\t\t\t\trp: { id: rpId, name: rpName },\n\t\t\t\tuser: {\n\t\t\t\t\tid: new TextEncoder().encode(username),\n\t\t\t\t\tname: username,\n\t\t\t\t\tdisplayName: username,\n\t\t\t\t},\n\t\t\t\tpubKeyCredParams: [\n\t\t\t\t\t{ alg: -7, type: \"public-key\" }, // ES256\n\t\t\t\t\t{ alg: -257, type: \"public-key\" }, // RS256\n\t\t\t\t],\n\t\t\t\tauthenticatorSelection: {\n\t\t\t\t\tresidentKey: \"required\",\n\t\t\t\t\trequireResidentKey: true,\n\t\t\t\t\tuserVerification: \"required\",\n\t\t\t\t},\n\t\t\t\textensions: {\n\t\t\t\t\tprf: { eval: { first: PRF_SALT.buffer } },\n\t\t\t\t} as AuthenticationExtensionsClientInputs,\n\t\t\t},\n\t\t}) as PublicKeyCredential | null;\n\n\t\tif (!credential) {\n\t\t\tthrow new Error(\"WebAuthn credential creation cancelled\");\n\t\t}\n\n\t\t// 2. Extract PRF output and derive Ed25519 keypair\n\t\tconst prfOutput = extractPrfOutput(credential);\n\t\tconst seed = deriveEd25519Seed(prfOutput);\n\t\tconst publicKey = await ed.getPublicKeyAsync(seed);\n\t\tconst publicKeyB64 = toBase64url(publicKey);\n\n\t\t// 3. Derive X25519 public key\n\t\tconst x25519Pub = nobleEd25519Curves.utils.toMontgomery(publicKey);\n\t\tconst x25519PubB64 = toBase64url(x25519Pub);\n\n\t\t// 4. Credential ID for future allowCredentials hints\n\t\tconst credentialIdB64 = toBase64url(new Uint8Array(credential.rawId));\n\n\t\t// 5. Cache in IndexedDB (lightweight — no private key material)\n\t\tconst db = await openDb();\n\t\tawait dbPut(db, credentialIdB64, {\n\t\t\tusername,\n\t\t\tpublicKey: publicKeyB64,\n\t\t\tcredentialId: credential.rawId,\n\t\t});\n\t\tdb.close();\n\n\t\t// 6. Wipe seed from memory\n\t\tseed.fill(0);\n\n\t\treturn {\n\t\t\tpublicKey: publicKeyB64,\n\t\t\tx25519PublicKey: x25519PubB64,\n\t\t\tcredentialId: credentialIdB64,\n\t\t};\n\t}\n\n\t/**\n\t * Sign a base64url-encoded challenge using the Ed25519 key derived from\n\t * a passkey assertion. Triggers a WebAuthn prompt (biometric / PIN).\n\t *\n\t * @param challengeB64 - base64url-encoded challenge bytes from the server.\n\t * @param credentialIdHint - optional credential ID to select a specific passkey.\n\t * @returns base64url-encoded Ed25519 signature (64 bytes).\n\t */\n\tasync sign(challengeB64: string, credentialIdHint?: string): Promise<string> {\n\t\tconst { seed } = await this._assertAndDerive(credentialIdHint);\n\n\t\ttry {\n\t\t\tconst challengeBytes = fromBase64url(challengeB64);\n\t\t\tconst signature = await ed.signAsync(challengeBytes, seed);\n\t\t\treturn toBase64url(signature);\n\t\t} finally {\n\t\t\tseed.fill(0);\n\t\t}\n\t}\n\n\t/**\n\t * Returns the cached base64url public key, or null if no identity is cached.\n\t *\n\t * Does NOT trigger a WebAuthn prompt. If the cache is empty (e.g. IndexedDB\n\t * cleared), returns null — the identity can be recovered via sign() or\n\t * a fresh register() with the same synced passkey.\n\t */\n\tasync getPublicKey(credentialIdHint?: string): Promise<string | null> {\n\t\tconst db = await openDb();\n\t\ttry {\n\t\t\tif (credentialIdHint) {\n\t\t\t\tconst stored = await dbGet(db, credentialIdHint);\n\t\t\t\treturn stored?.publicKey ?? null;\n\t\t\t}\n\t\t\t// Return the first cached identity\n\t\t\tconst all = await dbGetAll(db);\n\t\t\treturn all.length > 0 ? all[0].value.publicKey : null;\n\t\t} finally {\n\t\t\tdb.close();\n\t\t}\n\t}\n\n\t/**\n\t * Returns the locally-cached username label, or null if no identity is cached.\n\t */\n\tasync getUsername(credentialIdHint?: string): Promise<string | null> {\n\t\tconst db = await openDb();\n\t\ttry {\n\t\t\tif (credentialIdHint) {\n\t\t\t\tconst stored = await dbGet(db, credentialIdHint);\n\t\t\t\treturn stored?.username ?? null;\n\t\t\t}\n\t\t\tconst all = await dbGetAll(db);\n\t\t\treturn all.length > 0 ? all[0].value.username : null;\n\t\t} finally {\n\t\t\tdb.close();\n\t\t}\n\t}\n\n\t/**\n\t * Updates the cached username for a given credential (or the first cached identity).\n\t * Call this after the user sets/changes their display name so it persists across devices.\n\t */\n\tasync setUsername(username: string, credentialIdHint?: string): Promise<void> {\n\t\tconst db = await openDb();\n\t\ttry {\n\t\t\tif (credentialIdHint) {\n\t\t\t\tconst stored = await dbGet(db, credentialIdHint);\n\t\t\t\tif (stored) {\n\t\t\t\t\tawait dbPut(db, credentialIdHint, { ...stored, username });\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tconst all = await dbGetAll(db);\n\t\t\t\tif (all.length > 0) {\n\t\t\t\t\tawait dbPut(db, String(all[0].key), { ...all[0].value, username });\n\t\t\t\t}\n\t\t\t}\n\t\t} finally {\n\t\t\tdb.close();\n\t\t}\n\t}\n\n\t/** Returns true if an identity is cached in IndexedDB. */\n\tasync hasIdentity(): Promise<boolean> {\n\t\tconst db = await openDb();\n\t\ttry {\n\t\t\tconst all = await dbGetAll(db);\n\t\t\treturn all.length > 0;\n\t\t} finally {\n\t\t\tdb.close();\n\t\t}\n\t}\n\n\t/** Remove cached identity record(s) from IndexedDB. The passkey itself\n\t * remains in the platform credential store. */\n\tasync clear(): Promise<void> {\n\t\tconst db = await openDb();\n\t\tawait dbClear(db);\n\t\tdb.close();\n\t}\n\n\t/**\n\t * Returns the X25519 public key derived from the cached Ed25519 public key.\n\t * Does NOT require WebAuthn — computed from the cached public key only.\n\t * Returns null if no identity is cached.\n\t */\n\tasync getX25519PublicKey(): Promise<Uint8Array | null> {\n\t\tconst db = await openDb();\n\t\ttry {\n\t\t\tconst all = await dbGetAll(db);\n\t\t\tif (all.length === 0) return null;\n\t\t\tconst edPub = fromBase64url(all[0].value.publicKey);\n\t\t\treturn nobleEd25519Curves.utils.toMontgomery(edPub);\n\t\t} finally {\n\t\t\tdb.close();\n\t\t}\n\t}\n\n\t/**\n\t * Returns the X25519 private key derived from the Ed25519 seed.\n\t * Requires a WebAuthn assertion to get the PRF output.\n\t * The caller MUST wipe the returned Uint8Array after use.\n\t */\n\tasync getX25519PrivateKey(credentialIdHint?: string): Promise<Uint8Array> {\n\t\tconst { seed } = await this._assertAndDerive(credentialIdHint);\n\t\ttry {\n\t\t\treturn nobleEd25519Curves.utils.toMontgomerySecret(seed);\n\t\t} finally {\n\t\t\tseed.fill(0);\n\t\t}\n\t}\n\n\t/**\n\t * Trigger a WebAuthn assertion to derive (or re-derive) the identity and\n\t * update the IndexedDB cache. Returns the public key and credential ID.\n\t *\n\t * Use this when the cache is empty but you need the public key before\n\t * signing (e.g. to send it to the server for the challenge request).\n\t */\n\tasync deriveIdentity(credentialIdHint?: string): Promise<{ publicKey: string; credentialId: string }> {\n\t\tconst { seed, publicKeyB64, credentialIdB64 } = await this._assertAndDerive(credentialIdHint);\n\t\tseed.fill(0);\n\t\treturn { publicKey: publicKeyB64, credentialId: credentialIdB64 };\n\t}\n\n\t/**\n\t * List all cached credential IDs. Useful for account switching UI.\n\t */\n\tasync listCachedIdentities(): Promise<{ credentialId: string; publicKey: string; username: string }[]> {\n\t\tconst db = await openDb();\n\t\ttry {\n\t\t\tconst all = await dbGetAll(db);\n\t\t\treturn all.map(({ key, value }) => ({\n\t\t\t\tcredentialId: key as string,\n\t\t\t\tpublicKey: value.publicKey,\n\t\t\t\tusername: value.username,\n\t\t\t}));\n\t\t} finally {\n\t\t\tdb.close();\n\t\t}\n\t}\n\n\t// ── Mnemonic-based methods ───────────────────────────────────────────────\n\n\t/**\n\t * Register a new identity rooted in a BIP-39 mnemonic. Optionally wraps the\n\t * derived seed with a passkey for biometric day-to-day access.\n\t *\n\t * @param username - Display name for the identity.\n\t * @param mnemonic - Valid BIP-39 mnemonic (12 or 24 words).\n\t * @param passphrase - Optional BIP-39 passphrase (\"25th word\").\n\t * @param rpId - WebAuthn relying party ID (omit to skip passkey wrapping).\n\t * @param rpName - WebAuthn relying party display name.\n\t * @returns Public keys and optional credential ID.\n\t */\n\tasync registerWithMnemonic(\n\t\tusername: string,\n\t\tmnemonic: string,\n\t\tpassphrase?: string,\n\t\trpId?: string,\n\t\trpName?: string,\n\t): Promise<{ publicKey: string; x25519PublicKey: string; credentialId?: string }> {\n\t\tconst kp = await mnemonicToKeyPair(mnemonic, passphrase);\n\n\t\ttry {\n\t\t\tif (rpId && rpName) {\n\t\t\t\t// Create a passkey to wrap the mnemonic-derived seed\n\t\t\t\tconst credential = await navigator.credentials.create({\n\t\t\t\t\tpublicKey: {\n\t\t\t\t\t\tchallenge: crypto.getRandomValues(new Uint8Array(32)),\n\t\t\t\t\t\trp: { id: rpId, name: rpName },\n\t\t\t\t\t\tuser: {\n\t\t\t\t\t\t\tid: new TextEncoder().encode(username),\n\t\t\t\t\t\t\tname: username,\n\t\t\t\t\t\t\tdisplayName: username,\n\t\t\t\t\t\t},\n\t\t\t\t\t\tpubKeyCredParams: [\n\t\t\t\t\t\t\t{ alg: -7, type: \"public-key\" },\n\t\t\t\t\t\t\t{ alg: -257, type: \"public-key\" },\n\t\t\t\t\t\t],\n\t\t\t\t\t\tauthenticatorSelection: {\n\t\t\t\t\t\t\tresidentKey: \"required\",\n\t\t\t\t\t\t\trequireResidentKey: true,\n\t\t\t\t\t\t\tuserVerification: \"required\",\n\t\t\t\t\t\t},\n\t\t\t\t\t\textensions: {\n\t\t\t\t\t\t\tprf: { eval: { first: PRF_SALT.buffer } },\n\t\t\t\t\t\t} as AuthenticationExtensionsClientInputs,\n\t\t\t\t\t},\n\t\t\t\t}) as PublicKeyCredential | null;\n\n\t\t\t\tif (!credential) {\n\t\t\t\t\tthrow new Error(\"WebAuthn credential creation cancelled\");\n\t\t\t\t}\n\n\t\t\t\tconst prfOutput = extractPrfOutput(credential);\n\t\t\t\tconst wrapSalt = crypto.getRandomValues(new Uint8Array(32));\n\t\t\t\tconst wrapKey = deriveSeedWrappingKey(prfOutput, wrapSalt);\n\t\t\t\tconst { ciphertext, iv } = await wrapSeed(kp.seed, wrapKey);\n\t\t\t\twrapKey.fill(0);\n\n\t\t\t\tconst credentialIdB64 = toBase64url(new Uint8Array(credential.rawId));\n\t\t\t\tconst db = await openDb();\n\t\t\t\tawait dbPut(db, credentialIdB64, {\n\t\t\t\t\tusername,\n\t\t\t\t\tpublicKey: kp.publicKeyB64,\n\t\t\t\t\tcredentialId: credential.rawId,\n\t\t\t\t\tencryptedSeed: ciphertext,\n\t\t\t\t\tseedIv: iv,\n\t\t\t\t\twrapSalt,\n\t\t\t\t\tauthMethod: \"mnemonic\",\n\t\t\t\t});\n\t\t\t\tdb.close();\n\n\t\t\t\treturn {\n\t\t\t\t\tpublicKey: kp.publicKeyB64,\n\t\t\t\t\tx25519PublicKey: kp.x25519PublicKeyB64,\n\t\t\t\t\tcredentialId: credentialIdB64,\n\t\t\t\t};\n\t\t\t}\n\n\t\t\t// No passkey wrapping — ephemeral or mnemonic-only mode\n\t\t\treturn {\n\t\t\t\tpublicKey: kp.publicKeyB64,\n\t\t\t\tx25519PublicKey: kp.x25519PublicKeyB64,\n\t\t\t};\n\t\t} finally {\n\t\t\tkp.seed.fill(0);\n\t\t}\n\t}\n\n\t/**\n\t * Wrap an existing mnemonic-derived seed with a new passkey. Use this when\n\t * a user logged in via mnemonic and wants to add biometric convenience.\n\t *\n\t * @param mnemonic - The user's BIP-39 mnemonic.\n\t * @param passphrase - Optional BIP-39 passphrase.\n\t * @param rpId - WebAuthn relying party ID.\n\t * @param rpName - WebAuthn relying party display name.\n\t * @returns The new credential ID.\n\t */\n\tasync wrapSeedWithPasskey(\n\t\tmnemonic: string,\n\t\tpassphrase: string | undefined,\n\t\trpId: string,\n\t\trpName: string,\n\t): Promise<{ credentialId: string }> {\n\t\tconst kp = await mnemonicToKeyPair(mnemonic, passphrase);\n\t\ttry {\n\t\t\tconst credential = await navigator.credentials.create({\n\t\t\t\tpublicKey: {\n\t\t\t\t\tchallenge: crypto.getRandomValues(new Uint8Array(32)),\n\t\t\t\t\trp: { id: rpId, name: rpName },\n\t\t\t\t\tuser: {\n\t\t\t\t\t\tid: fromBase64url(kp.publicKeyB64) as BufferSource,\n\t\t\t\t\t\tname: kp.publicKeyB64.slice(0, 16),\n\t\t\t\t\t\tdisplayName: kp.publicKeyB64.slice(0, 16),\n\t\t\t\t\t},\n\t\t\t\t\tpubKeyCredParams: [\n\t\t\t\t\t\t{ alg: -7, type: \"public-key\" },\n\t\t\t\t\t\t{ alg: -257, type: \"public-key\" },\n\t\t\t\t\t],\n\t\t\t\t\tauthenticatorSelection: {\n\t\t\t\t\t\tresidentKey: \"required\",\n\t\t\t\t\t\trequireResidentKey: true,\n\t\t\t\t\t\tuserVerification: \"required\",\n\t\t\t\t\t},\n\t\t\t\t\textensions: {\n\t\t\t\t\t\tprf: { eval: { first: PRF_SALT.buffer } },\n\t\t\t\t\t} as AuthenticationExtensionsClientInputs,\n\t\t\t\t},\n\t\t\t}) as PublicKeyCredential | null;\n\n\t\t\tif (!credential) {\n\t\t\t\tthrow new Error(\"WebAuthn credential creation cancelled\");\n\t\t\t}\n\n\t\t\tconst prfOutput = extractPrfOutput(credential);\n\t\t\tconst wrapSalt = crypto.getRandomValues(new Uint8Array(32));\n\t\t\tconst wrapKey = deriveSeedWrappingKey(prfOutput, wrapSalt);\n\t\t\tconst { ciphertext, iv } = await wrapSeed(kp.seed, wrapKey);\n\t\t\twrapKey.fill(0);\n\n\t\t\tconst credentialIdB64 = toBase64url(new Uint8Array(credential.rawId));\n\n\t\t\t// Try to preserve username from an existing record with the same pubkey\n\t\t\tlet username = \"\";\n\t\t\ttry {\n\t\t\t\tconst db = await openDb();\n\t\t\t\tconst all = await dbGetAll(db);\n\t\t\t\tconst existing = all.find(e => e.value.publicKey === kp.publicKeyB64);\n\t\t\t\tif (existing) username = existing.value.username;\n\t\t\t\tdb.close();\n\t\t\t} catch { /* non-fatal */ }\n\n\t\t\tconst db = await openDb();\n\t\t\tawait dbPut(db, credentialIdB64, {\n\t\t\t\tusername,\n\t\t\t\tpublicKey: kp.publicKeyB64,\n\t\t\t\tcredentialId: credential.rawId,\n\t\t\t\tencryptedSeed: ciphertext,\n\t\t\t\tseedIv: iv,\n\t\t\t\twrapSalt,\n\t\t\t\tauthMethod: \"mnemonic\",\n\t\t\t});\n\t\t\tdb.close();\n\n\t\t\treturn { credentialId: credentialIdB64 };\n\t\t} finally {\n\t\t\tkp.seed.fill(0);\n\t\t}\n\t}\n\n\t/**\n\t * Sign a challenge directly with a provided seed. No WebAuthn prompt.\n\t * For ephemeral mnemonic sessions where the seed is held in memory.\n\t *\n\t * The caller manages the seed lifecycle (wiping on session end).\n\t */\n\tstatic async signWithSeed(challengeB64: string, seed: Uint8Array): Promise<string> {\n\t\tconst challengeBytes = fromBase64url(challengeB64);\n\t\tconst signature = await ed.signAsync(challengeBytes, seed);\n\t\treturn toBase64url(signature);\n\t}\n\n\t/**\n\t * Stateless mnemonic sign: derive seed, sign, wipe. No IndexedDB, no WebAuthn.\n\t * Useful for CLI or one-shot operations.\n\t */\n\tstatic async signWithMnemonic(\n\t\tmnemonic: string,\n\t\tchallengeB64: string,\n\t\tpassphrase?: string,\n\t): Promise<string> {\n\t\tconst seed = mnemonicToEd25519Seed(mnemonic, passphrase);\n\t\ttry {\n\t\t\tconst challengeBytes = fromBase64url(challengeB64);\n\t\t\tconst signature = await ed.signAsync(challengeBytes, seed);\n\t\t\treturn toBase64url(signature);\n\t\t} finally {\n\t\t\tseed.fill(0);\n\t\t}\n\t}\n\n\t// ── Internal ─────────────────────────────────────────────────────────────\n\n\t/**\n\t * Perform a WebAuthn assertion with PRF, derive the Ed25519 seed, and\n\t * update the IndexedDB cache. Returns the seed (caller MUST wipe it).\n\t */\n\tprivate async _assertAndDerive(credentialIdHint?: string): Promise<{\n\t\tseed: Uint8Array;\n\t\tpublicKeyB64: string;\n\t\tcredentialIdB64: string;\n\t}> {\n\t\t// Build allowCredentials from hint or cached records\n\t\tconst allowCredentials: PublicKeyCredentialDescriptor[] = [];\n\n\t\tif (credentialIdHint) {\n\t\t\tallowCredentials.push({\n\t\t\t\tid: fromBase64url(credentialIdHint) as BufferSource,\n\t\t\t\ttype: \"public-key\",\n\t\t\t});\n\t\t} else {\n\t\t\t// Try cached credential IDs for a targeted prompt\n\t\t\ttry {\n\t\t\t\tconst db = await openDb();\n\t\t\t\tconst all = await dbGetAll(db);\n\t\t\t\tdb.close();\n\t\t\t\tfor (const { value } of all) {\n\t\t\t\t\tallowCredentials.push({\n\t\t\t\t\t\tid: value.credentialId,\n\t\t\t\t\t\ttype: \"public-key\",\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t} catch {\n\t\t\t\t// IndexedDB unavailable — proceed with discoverable credentials\n\t\t\t}\n\t\t}\n\n\t\tconst assertion = await navigator.credentials.get({\n\t\t\tpublicKey: {\n\t\t\t\tchallenge: crypto.getRandomValues(new Uint8Array(32)),\n\t\t\t\t...(allowCredentials.length > 0 ? { allowCredentials } : {}),\n\t\t\t\tuserVerification: \"required\",\n\t\t\t\textensions: {\n\t\t\t\t\tprf: { eval: { first: PRF_SALT.buffer } },\n\t\t\t\t} as AuthenticationExtensionsClientInputs,\n\t\t\t},\n\t\t}) as PublicKeyCredential | null;\n\n\t\tif (!assertion) {\n\t\t\tthrow new Error(\"WebAuthn assertion cancelled\");\n\t\t}\n\n\t\tconst prfOutput = extractPrfOutput(assertion);\n\t\tconst credentialIdB64 = toBase64url(new Uint8Array(assertion.rawId));\n\n\t\t// Check if this credential has a wrapped mnemonic seed\n\t\tlet stored: StoredIdentity | undefined;\n\t\ttry {\n\t\t\tconst db = await openDb();\n\t\t\tstored = await dbGet(db, credentialIdB64);\n\t\t\tdb.close();\n\t\t} catch {\n\t\t\t// IndexedDB unavailable — fall through to legacy derivation\n\t\t}\n\n\t\tlet seed: Uint8Array;\n\t\tif (stored?.encryptedSeed && stored.seedIv && stored.wrapSalt) {\n\t\t\t// Mnemonic-rooted: decrypt the stored seed using PRF-derived wrap key\n\t\t\tconst wrapKey = deriveSeedWrappingKey(prfOutput, stored.wrapSalt);\n\t\t\tseed = await unwrapSeed(stored.encryptedSeed, stored.seedIv, wrapKey);\n\t\t\twrapKey.fill(0);\n\t\t} else {\n\t\t\t// Legacy passkey-only: derive seed directly from PRF via HKDF\n\t\t\tseed = deriveEd25519Seed(prfOutput);\n\t\t}\n\n\t\tconst publicKey = await ed.getPublicKeyAsync(seed);\n\t\tconst publicKeyB64 = toBase64url(publicKey);\n\n\t\t// Update cache (preserve mnemonic-rooted fields if present)\n\t\ttry {\n\t\t\tconst db = await openDb();\n\t\t\tconst existing = await dbGet(db, credentialIdB64);\n\t\t\tawait dbPut(db, credentialIdB64, {\n\t\t\t\tusername: existing?.username ?? \"\",\n\t\t\t\tpublicKey: publicKeyB64,\n\t\t\t\tcredentialId: assertion.rawId,\n\t\t\t\t// Preserve wrapped seed fields from existing record\n\t\t\t\tencryptedSeed: existing?.encryptedSeed,\n\t\t\t\tseedIv: existing?.seedIv,\n\t\t\t\twrapSalt: existing?.wrapSalt,\n\t\t\t\tauthMethod: existing?.authMethod,\n\t\t\t});\n\t\t\tdb.close();\n\t\t} catch {\n\t\t\t// Cache update failure is non-fatal\n\t\t}\n\n\t\treturn { seed, publicKeyB64, credentialIdB64 };\n\t}\n}\n","/**\n * NodeIdentity — Ed25519 identity helpers for Node-side consumers.\n *\n * The browser identity story lives in {@link CryptoIdentityKeystore} (WebAuthn\n * PRF + IndexedDB). Node CLIs and daemons (`@abraca/mcp`, `@abraca/cli`,\n * `@abraca/orchestrator`, `@abraca/resend`, `@abraca/wiki`) instead use a raw\n * 32-byte Ed25519 seed kept in a key file, and authenticate to the server with\n * the same challenge → sign → verify flow exposed by\n * {@link AbracadabraClient.loginWithKey}.\n *\n * Every one of those packages previously vendored a near-identical `crypto.ts`\n * (key-file load/create + `signChallenge`) plus a copy-pasted\n * \"login → register-on-404 → re-login\" block. These helpers are the single\n * shared home for both.\n *\n * The signing helpers are environment-agnostic. Only {@link loadOrCreateKeyFile}\n * touches the filesystem, and it does so via dynamic `import(\"node:…\")` so this\n * module stays importable from browser bundles (the fs path simply isn't\n * reachable there).\n */\n\nimport * as ed from \"@noble/ed25519\";\nimport { sha512 } from \"@noble/hashes/sha2.js\";\n\n// @noble/ed25519 v3: wire sha512 for the sync sign/getPublicKey paths and an\n// async hook for *Async variants. Idempotent with the same assignment in\n// CryptoIdentityKeystore / MnemonicKeyDerivation — whichever module loads first\n// wins, and the value is identical.\ned.hashes.sha512 = sha512;\ned.hashes.sha512Async = (m: Uint8Array) => Promise.resolve(sha512(m));\n\n// ── base64url (browser-safe; mirrors CryptoIdentityKeystore) ─────────────────\n\nfunction toBase64url(bytes: Uint8Array): string {\n\treturn btoa(String.fromCharCode(...bytes))\n\t\t.replace(/\\+/g, \"-\")\n\t\t.replace(/\\//g, \"_\")\n\t\t.replace(/=/g, \"\");\n}\n\nfunction fromBase64url(b64: string): Uint8Array {\n\tconst padded = b64.replace(/-/g, \"+\").replace(/_/g, \"/\");\n\tconst padLen = (4 - (padded.length % 4)) % 4;\n\treturn Uint8Array.from(atob(padded + \"=\".repeat(padLen)), (c) =>\n\t\tc.charCodeAt(0),\n\t);\n}\n\n// ── Types ────────────────────────────────────────────────────────────────────\n\n/** A raw Node Ed25519 identity: 32-byte seed + base64url public key. */\nexport interface NodeKeypair {\n\t/** 32-byte Ed25519 private-key seed. */\n\tprivateKey: Uint8Array;\n\t/** base64url-encoded 32-byte Ed25519 public key. */\n\tpublicKeyB64: string;\n}\n\n/** Options for {@link loadOrCreateKeyFile}. */\nexport interface LoadKeyFileOptions {\n\t/**\n\t * File name under `~/.abracadabra/` used when `keyPath` is not given.\n\t * Lets each consumer keep its own identity slot (e.g. `\"cli.key\"`,\n\t * `\"agent.key\"`). Defaults to `\"identity.key\"`.\n\t */\n\tdefaultFileName?: string;\n\t/** Invoked once when a brand-new key is generated (for logging). */\n\tonCreate?: (info: { path: string; publicKeyB64: string }) => void;\n}\n\n/** Minimal client surface needed by {@link loginOrRegisterWithKey}. */\nexport interface KeyAuthClient {\n\tloginWithKey(\n\t\tpublicKey: string,\n\t\tsignChallenge: (challenge: string) => Promise<string>,\n\t): Promise<string>;\n\tregisterWithKey(opts: {\n\t\tpublicKey: string;\n\t\tusername?: string;\n\t\tdisplayName?: string;\n\t\tdeviceName?: string;\n\t\tinviteCode?: string;\n\t}): Promise<unknown>;\n}\n\n/**\n * Wider client surface needed by {@link loginOrRegisterWithPolicy}: it probes\n * `serverInfo()` (unauthenticated) to decide the access policy and reads\n * `getMe()` after connecting to detect a read-only (un-promoted) role.\n */\nexport interface PolicyAuthClient extends KeyAuthClient {\n\tserverInfo(): Promise<{\n\t\tname?: string;\n\t\tregistration_allowed?: boolean;\n\t\tinvite_only?: boolean;\n\t\taccess?: { authenticated?: string };\n\t}>;\n\tgetMe(): Promise<{ role?: string }>;\n}\n\n/**\n * Outcome of {@link loginOrRegisterWithPolicy}. A discriminated union so callers\n * (MCP `connect_server`, CLI `server login`) can render an actionable message.\n *\n * - `connected` — logged in (existing account) or registered (open server / valid\n * invite). `needsPromotion` is set when the account is read-only (`observer`),\n * so the caller can suggest an admin grant a write role to `publicKey`.\n * - `needs_invite` — server is invite-only, the key isn't registered, and no\n * invite code was supplied. Surface `publicKey` so an admin can authorize it by\n * hand if no token is available.\n * - `registration_closed` — open registration is disabled; only an admin can\n * provision the account. Surface `publicKey`.\n */\nexport type ConnectPolicyResult =\n\t| {\n\t\t\tstatus: \"connected\";\n\t\t\ttoken: string;\n\t\t\tpublicKey: string;\n\t\t\tserverName?: string;\n\t\t\trole?: string;\n\t\t\tneedsPromotion: boolean;\n\t }\n\t| { status: \"needs_invite\"; publicKey: string; serverName?: string }\n\t| { status: \"registration_closed\"; publicKey: string; serverName?: string };\n\n/** Options for {@link loginOrRegisterWithKey}. */\nexport interface LoginOrRegisterOptions {\n\t/**\n\t * Account username. Defaults to a slug of `displayName`\n\t * (`/\\s+/g → \"-\"`, lowercased) when omitted.\n\t */\n\tusername?: string;\n\tdisplayName?: string;\n\tdeviceName?: string;\n\tinviteCode?: string;\n\t/** Invoked right before auto-registering on first run (for logging). */\n\tonRegister?: () => void;\n}\n\n// ── Signing ──────────────────────────────────────────────────────────────────\n\n/**\n * Sign a base64url server challenge with a 32-byte Ed25519 seed.\n * Returns a base64url signature suitable for\n * {@link AbracadabraClient.verify}. Synchronous (the sha512 hook is set above).\n */\nexport function signChallengeWithSeed(\n\tchallengeB64: string,\n\tseed: Uint8Array,\n): string {\n\treturn toBase64url(ed.sign(fromBase64url(challengeB64), seed));\n}\n\n/**\n * Build the async `signChallenge` callback that\n * {@link AbracadabraClient.loginWithKey} expects, bound to a keypair. Keep the\n * returned function around to re-authenticate after a JWT expires.\n */\nexport function makeChallengeSigner(\n\tkeypair: NodeKeypair,\n): (challenge: string) => Promise<string> {\n\treturn (challenge: string) =>\n\t\tPromise.resolve(signChallengeWithSeed(challenge, keypair.privateKey));\n}\n\n/**\n * Derive a deterministic keypair from a seed string: the same input always\n * yields the same on-server identity. Used by `@abraca/orchestrator` so a named\n * actor maps to one reproducible account across runs.\n *\n * @param salt domain-separation suffix (default `\"orchestrator-salt\"`, the\n * historical value — change only if you intend a different identity space).\n */\nexport function deterministicKeypair(\n\tseed: string,\n\tsalt = \"orchestrator-salt\",\n): NodeKeypair {\n\tconst privateKey = sha512(\n\t\tnew TextEncoder().encode(`${seed}:${salt}`),\n\t).slice(0, 32);\n\treturn { privateKey, publicKeyB64: toBase64url(ed.getPublicKey(privateKey)) };\n}\n\n// ── Key file (Node only) ─────────────────────────────────────────────────────\n\n/**\n * Load an existing 32-byte Ed25519 seed from `keyPath`, or generate one and\n * persist it with `0o600` (dir `0o700`). When `keyPath` is omitted the file is\n * `~/.abracadabra/<defaultFileName>`.\n *\n * Node-only: filesystem modules are loaded via dynamic import, so importing\n * this symbol in a browser bundle is safe — only *calling* it requires Node.\n */\nexport async function loadOrCreateKeyFile(\n\tkeyPath?: string,\n\topts: LoadKeyFileOptions = {},\n): Promise<NodeKeypair> {\n\tconst { existsSync } = await import(\"node:fs\");\n\tconst { readFile, writeFile, mkdir } = await import(\"node:fs/promises\");\n\tconst { homedir } = await import(\"node:os\");\n\tconst { join, dirname } = await import(\"node:path\");\n\n\tconst path =\n\t\tkeyPath ??\n\t\tjoin(homedir(), \".abracadabra\", opts.defaultFileName ?? \"identity.key\");\n\n\tif (existsSync(path)) {\n\t\tconst seed = await readFile(path);\n\t\tif (seed.length !== 32) {\n\t\t\tthrow new Error(\n\t\t\t\t`Invalid key file at ${path}: expected 32 bytes, got ${seed.length}`,\n\t\t\t);\n\t\t}\n\t\tconst privateKey = new Uint8Array(seed);\n\t\treturn {\n\t\t\tprivateKey,\n\t\t\tpublicKeyB64: toBase64url(ed.getPublicKey(privateKey)),\n\t\t};\n\t}\n\n\tconst privateKey = ed.utils.randomSecretKey();\n\tconst publicKeyB64 = toBase64url(ed.getPublicKey(privateKey));\n\n\tconst dir = dirname(path);\n\tif (!existsSync(dir)) await mkdir(dir, { recursive: true, mode: 0o700 });\n\tawait writeFile(path, privateKey, { mode: 0o600 });\n\n\topts.onCreate?.({ path, publicKeyB64 });\n\treturn { privateKey, publicKeyB64 };\n}\n\n// ── Login / register ─────────────────────────────────────────────────────────\n\n/**\n * Authenticate `keypair` against the server, auto-registering on first run.\n *\n * Tries {@link AbracadabraClient.loginWithKey}; if the key isn't registered yet\n * — signalled by HTTP 404/422, or 401 with a \"not registered / user not found\"\n * message — it calls {@link AbracadabraClient.registerWithKey} and re-logs in.\n * Any other error propagates. Returns the JWT.\n *\n * This is the one shared implementation of the \"login → register-on-404 →\n * re-login\" dance previously copy-pasted into every Node consumer's connect().\n */\nexport async function loginOrRegisterWithKey(\n\tclient: KeyAuthClient,\n\tkeypair: NodeKeypair,\n\topts: LoginOrRegisterOptions = {},\n): Promise<string> {\n\tconst sign = makeChallengeSigner(keypair);\n\ttry {\n\t\treturn await client.loginWithKey(keypair.publicKeyB64, sign);\n\t} catch (err: unknown) {\n\t\tconst e = err as { status?: number; response?: { status?: number }; message?: string };\n\t\tconst status = e?.status ?? e?.response?.status;\n\t\tconst msg = String(e?.message ?? \"\").toLowerCase();\n\t\tconst notRegistered =\n\t\t\tstatus === 404 ||\n\t\t\tstatus === 422 ||\n\t\t\t(status === 401 && /not registered|user not found|no such user/.test(msg));\n\t\tif (!notRegistered) throw err;\n\n\t\topts.onRegister?.();\n\t\tconst username =\n\t\t\topts.username ??\n\t\t\t(opts.displayName\n\t\t\t\t? opts.displayName.replace(/\\s+/g, \"-\").toLowerCase()\n\t\t\t\t: undefined);\n\t\tawait client.registerWithKey({\n\t\t\tpublicKey: keypair.publicKeyB64,\n\t\t\tusername,\n\t\t\tdisplayName: opts.displayName,\n\t\t\tdeviceName: opts.deviceName,\n\t\t\tinviteCode: opts.inviteCode,\n\t\t});\n\t\treturn await client.loginWithKey(keypair.publicKeyB64, sign);\n\t}\n}\n\n/**\n * Like {@link loginOrRegisterWithKey}, but probes the server's access policy\n * first so an un-registered key produces an *actionable* result instead of a raw\n * register error. This is what lets a running agent say \"this server is\n * invite-only — give me a token, or have an admin authorize my public key\"\n * rather than failing opaquely.\n *\n * Flow:\n * 1. `serverInfo()` (unauthenticated) for the access policy + server name.\n * 2. Try `loginWithKey`. Success → fetch `getMe()` for the role → `connected`.\n * 3. On a \"not registered\" error, branch on the policy:\n * - an `inviteCode` was supplied → register with it (works for invite-only\n * and open servers) → re-login → `connected`.\n * - no code + `invite_only` → `needs_invite`.\n * - no code + `registration_allowed === false` → `registration_closed`.\n * - otherwise (open registration) → register without a code → `connected`.\n * 4. Any other login error propagates.\n */\nexport async function loginOrRegisterWithPolicy(\n\tclient: PolicyAuthClient,\n\tkeypair: NodeKeypair,\n\topts: LoginOrRegisterOptions = {},\n): Promise<ConnectPolicyResult> {\n\tconst sign = makeChallengeSigner(keypair);\n\tconst publicKey = keypair.publicKeyB64;\n\n\t// Best-effort policy probe — never fatal (older servers may omit fields).\n\tlet info: Awaited<ReturnType<PolicyAuthClient[\"serverInfo\"]>> = {};\n\ttry {\n\t\tinfo = await client.serverInfo();\n\t} catch {\n\t\t/* fall through with empty policy → behave like open/unknown */\n\t}\n\tconst serverName = info.name;\n\n\tconst connected = async (token: string): Promise<ConnectPolicyResult> => {\n\t\tlet role: string | undefined;\n\t\ttry {\n\t\t\trole = (await client.getMe()).role;\n\t\t} catch {\n\t\t\t/* role unknown — don't block the connection on it */\n\t\t}\n\t\t// A bare `observer` is the read-only floor: connected, but can't write\n\t\t// until an admin promotes the key. `service`/`admin`/`owner`/`editor` are\n\t\t// write-capable; `viewer` is intentionally read-only by grant, not a\n\t\t// missing-promotion signal, so only flag `observer`.\n\t\tconst needsPromotion = role === \"observer\";\n\t\treturn {\n\t\t\tstatus: \"connected\",\n\t\t\ttoken,\n\t\t\tpublicKey,\n\t\t\tserverName,\n\t\t\trole,\n\t\t\tneedsPromotion,\n\t\t};\n\t};\n\n\ttry {\n\t\treturn await connected(await client.loginWithKey(publicKey, sign));\n\t} catch (err: unknown) {\n\t\tconst e = err as {\n\t\t\tstatus?: number;\n\t\t\tresponse?: { status?: number };\n\t\t\tmessage?: string;\n\t\t};\n\t\tconst status = e?.status ?? e?.response?.status;\n\t\tconst msg = String(e?.message ?? \"\").toLowerCase();\n\t\tconst notRegistered =\n\t\t\tstatus === 404 ||\n\t\t\tstatus === 422 ||\n\t\t\t(status === 401 && /not registered|user not found|no such user/.test(msg));\n\t\tif (!notRegistered) throw err;\n\n\t\t// Not registered — decide based on policy + whether we have a code.\n\t\tif (!opts.inviteCode) {\n\t\t\tif (info.invite_only === true) {\n\t\t\t\treturn { status: \"needs_invite\", publicKey, serverName };\n\t\t\t}\n\t\t\tif (info.registration_allowed === false) {\n\t\t\t\treturn { status: \"registration_closed\", publicKey, serverName };\n\t\t\t}\n\t\t}\n\n\t\topts.onRegister?.();\n\t\tconst username =\n\t\t\topts.username ??\n\t\t\t(opts.displayName\n\t\t\t\t? opts.displayName.replace(/\\s+/g, \"-\").toLowerCase()\n\t\t\t\t: undefined);\n\t\tawait client.registerWithKey({\n\t\t\tpublicKey,\n\t\t\tusername,\n\t\t\tdisplayName: opts.displayName,\n\t\t\tdeviceName: opts.deviceName,\n\t\t\tinviteCode: opts.inviteCode,\n\t\t});\n\t\treturn await connected(await client.loginWithKey(publicKey, sign));\n\t}\n}\n","/**\n * Shared utilities for the DocumentManager ORM layer.\n *\n * These functions were previously duplicated across `mcp/src/utils.ts`,\n * `mcp/src/server.ts`, `cli/src/connection.ts`, and `mcp/src/tools/tree.ts`.\n */\nimport * as Y from \"yjs\";\nimport type { PageMeta, TreeEntry } from \"./DocTypes.ts\";\n\n/**\n * Wait for a provider's `synced` event with a timeout.\n * Resolves immediately if the provider is already synced.\n */\nexport function waitForSync(\n\tprovider: {\n\t\tisSynced?: boolean;\n\t\ton(event: string, cb: () => void): void;\n\t\toff(event: string, cb: () => void): void;\n\t},\n\ttimeoutMs = 15000,\n): Promise<void> {\n\t// Already synced — resolve immediately.\n\tif (provider.isSynced) return Promise.resolve();\n\n\treturn new Promise<void>((resolve, reject) => {\n\t\tconst timer = setTimeout(() => {\n\t\t\tprovider.off(\"synced\", handler);\n\t\t\treject(new Error(`Sync timed out after ${timeoutMs}ms`));\n\t\t}, timeoutMs);\n\n\t\tfunction handler() {\n\t\t\tclearTimeout(timer);\n\t\t\t// Detach so a one-shot `waitForSync` never leaves a dangling\n\t\t\t// `synced` listener on a long-lived provider.\n\t\t\tprovider.off(\"synced\", handler);\n\t\t\tresolve();\n\t\t}\n\n\t\tprovider.on(\"synced\", handler);\n\t});\n}\n\n/**\n * Wrap a promise with a timeout.\n */\nexport function withTimeout<T>(\n\tpromise: Promise<T>,\n\ttimeoutMs: number,\n\tmessage?: string,\n): Promise<T> {\n\treturn new Promise<T>((resolve, reject) => {\n\t\tconst timer = setTimeout(\n\t\t\t() =>\n\t\t\t\treject(\n\t\t\t\t\tnew Error(\n\t\t\t\t\t\tmessage ?? `Operation timed out after ${timeoutMs}ms`,\n\t\t\t\t\t),\n\t\t\t\t),\n\t\t\ttimeoutMs,\n\t\t);\n\t\tpromise.then(\n\t\t\t(val) => {\n\t\t\t\tclearTimeout(timer);\n\t\t\t\tresolve(val);\n\t\t\t},\n\t\t\t(err) => {\n\t\t\t\tclearTimeout(timer);\n\t\t\t\treject(err);\n\t\t\t},\n\t\t);\n\t});\n}\n\n/**\n * Normalize a document ID so the hub/root doc ID is treated as the tree root\n * (null). This lets callers pass the hub doc_id from list_spaces as\n * parentId/rootId and get the expected root-level results instead of an empty\n * set.\n */\nexport function normalizeRootId(\n\tid: string | null | undefined,\n\trootDocId: string | null,\n): string | null {\n\tif (id == null) return null;\n\treturn id === rootDocId ? null : id;\n}\n\n/**\n * Safely read a tree map value, converting Y.Map to plain object if needed.\n */\nexport function toPlain(val: unknown): unknown {\n\treturn val instanceof Y.Map ? val.toJSON() : val;\n}\n\n/**\n * Read every entry of a `doc-tree` Y.Map into a flat {@link TreeEntry}[].\n *\n * Skips non-entry keys (e.g. `\":updatedAt\"` timestamps), and — when `selfId`\n * is given — the space root's own self-descriptor entry (keyed by the\n * connected root doc id, `parentId:null`, `order:-1`) so the space doesn't\n * render as a phantom first child of itself. Entry values are nested\n * `Y.Map`s, so each is resolved via {@link toPlain} (raw field access on a\n * Y.Map returns undefined).\n *\n * This is the single shared implementation; `@abraca/mcp`, `@abraca/cli`, and\n * `@abraca/resend` previously each carried a near-identical copy.\n */\nexport function readEntries(\n\ttreeMap: Y.Map<unknown>,\n\tselfId?: string | null,\n): TreeEntry[] {\n\tconst entries: TreeEntry[] = [];\n\ttreeMap.forEach((raw, id) => {\n\t\tif (selfId && id === selfId) return;\n\t\tconst value = toPlain(raw);\n\t\tif (typeof value !== \"object\" || value === null) return;\n\t\tconst v = value as Record<string, unknown>;\n\t\tentries.push({\n\t\t\tid,\n\t\t\tlabel: typeof v.label === \"string\" && v.label ? v.label : \"Untitled\",\n\t\t\tparentId: (v.parentId as string | null) ?? null,\n\t\t\torder: typeof v.order === \"number\" ? v.order : 0,\n\t\t\ttype: typeof v.type === \"string\" ? v.type : undefined,\n\t\t\tmeta: v.meta as PageMeta | undefined,\n\t\t\tcreatedAt: typeof v.createdAt === \"number\" ? v.createdAt : undefined,\n\t\t\tupdatedAt: typeof v.updatedAt === \"number\" ? v.updatedAt : undefined,\n\t\t});\n\t});\n\treturn entries;\n}\n\n/**\n * Build a tree/trash entry as a nested `Y.Map`. Use for a brand-new or\n * re-created key (create / duplicate / restore) where no concurrent\n * writer exists, so a whole-value write is safe. `undefined` fields are\n * omitted; `null` is kept (a real value, e.g. top-level `parentId`).\n */\nexport function makeEntryMap(\n\tfields: Record<string, unknown>,\n): Y.Map<unknown> {\n\tconst m = new Y.Map<unknown>();\n\tfor (const [k, v] of Object.entries(fields)) {\n\t\tif (v !== undefined) m.set(k, v);\n\t}\n\treturn m;\n}\n\n/**\n * A label is a \"placeholder\" — i.e. carries no real user title — when it is\n * empty/whitespace, null/undefined, or the literal `\"Untitled\"` sentinel\n * (case-insensitive, so `\"untitled\"` from a `labelToFilename` round-trip is\n * caught too). The whole tree-label corruption class boils down to a\n * placeholder being allowed to overwrite a real title; `patchEntry` refuses\n * exactly that. Mirrors cou-sh's `isEmptyTreeLabel`.\n */\nexport function isPlaceholderLabel(label: unknown): boolean {\n\tif (typeof label !== \"string\") return label == null;\n\tconst t = label.trim();\n\treturn t === \"\" || t.toLowerCase() === \"untitled\";\n}\n\n/**\n * Patch an EXISTING entry's fields per-key on its nested `Y.Map`, so a\n * concurrent edit to a *different* field by a peer is preserved instead\n * of being clobbered by a whole-entry write — the whole-entry-LWW fix\n * (audit ⑦), the mirror of the Rust provider's `with_entry_mut`.\n *\n * - nested `Y.Map` entry → set/delete only the touched keys in place;\n * - legacy opaque (plain-object) entry → migrated once to a `Y.Map`;\n * - missing entry → created from the patch (lenient; matches the prior\n * call-site behaviour of spreading `undefined`).\n *\n * A patch value of `undefined` deletes the key; `null` is written.\n * Self-transacting: it batches its writes in one `Y.Doc` transaction\n * (a safe reentrant no-op join when already inside one), so callers\n * don't need to pass or own a transaction.\n *\n * ── NO-DESTROY LABEL INVARIANT ──────────────────────────────────────────\n * A `label` patch that is a placeholder (empty/whitespace/\"Untitled\") is\n * DROPPED when the entry already holds a real (non-placeholder) label —\n * regardless of which consumer (cou-sh title-sync, fs-sync rename\n * detection, MCP, table renderers, a stale snapshot) tried it. This is the\n * source-of-truth guard against the \"card title silently becomes Untitled\n * / files renamed to untitled.md\" corruption: a placeholder must never win\n * over a real title. Creating a brand-new entry with an empty label (e.g.\n * a fresh kanban card) is still allowed — the guard only fires when a real\n * label already exists. Pass `{ allowLabelClear: true }` to override (the\n * single legitimate \"user explicitly cleared it\" path).\n */\nexport function patchEntry(\n\ttreeMap: Y.Map<unknown>,\n\tid: string,\n\tpatch: Record<string, unknown>,\n\tremoveKeys: string[] = [],\n\topts: { allowLabelClear?: boolean } = {},\n): void {\n\tconst apply = (): void => {\n\t\tconst raw = treeMap.get(id);\n\n\t\t// NO-DESTROY label guard: strip a placeholder `label` from the patch\n\t\t// when a real label already exists on the entry. The existing-label\n\t\t// read is DUCK-TYPED (not `instanceof Y.Map`): under a host that\n\t\t// resolves a second physical yjs (cou-sh's local file-link), a\n\t\t// foreign Y.Map fails `instanceof` and would read `undefined` —\n\t\t// disabling the guard in the very environment that needs it. `.get`\n\t\t// / `.toJSON` work regardless of which yjs constructed the map.\n\t\tlet effectivePatch = patch;\n\t\tif (\n\t\t\t!opts.allowLabelClear &&\n\t\t\tObject.hasOwn(patch, \"label\") &&\n\t\t\tisPlaceholderLabel(patch.label)\n\t\t) {\n\t\t\tlet existingLabel: unknown;\n\t\t\tif (raw != null && typeof (raw as { get?: unknown }).get === \"function\") {\n\t\t\t\texistingLabel = (raw as Y.Map<unknown>).get(\"label\");\n\t\t\t} else if (\n\t\t\t\traw != null &&\n\t\t\t\ttypeof (raw as { toJSON?: unknown }).toJSON === \"function\"\n\t\t\t) {\n\t\t\t\texistingLabel = ((raw as { toJSON: () => Record<string, unknown> }).toJSON())\n\t\t\t\t\t?.label;\n\t\t\t} else if (raw != null && typeof raw === \"object\") {\n\t\t\t\texistingLabel = (raw as Record<string, unknown>).label;\n\t\t\t}\n\t\t\tif (!isPlaceholderLabel(existingLabel)) {\n\t\t\t\tconst { label: _dropped, ...rest } = patch;\n\t\t\t\teffectivePatch = rest;\n\t\t\t}\n\t\t}\n\n\t\tif (raw instanceof Y.Map) {\n\t\t\tfor (const [k, v] of Object.entries(effectivePatch)) {\n\t\t\t\tif (v === undefined) raw.delete(k);\n\t\t\t\telse raw.set(k, v);\n\t\t\t}\n\t\t\tfor (const k of removeKeys) raw.delete(k);\n\t\t\treturn;\n\t\t}\n\t\tconst base =\n\t\t\traw == null ? {} : (toPlain(raw) as Record<string, unknown>);\n\t\tconst merged: Record<string, unknown> = { ...base, ...effectivePatch };\n\t\tfor (const [k, v] of Object.entries(effectivePatch)) {\n\t\t\tif (v === undefined) delete merged[k];\n\t\t}\n\t\tfor (const k of removeKeys) delete merged[k];\n\t\ttreeMap.set(id, makeEntryMap(merged));\n\t};\n\tconst doc = treeMap.doc;\n\tif (doc) doc.transact(apply);\n\telse apply();\n}\n","/**\n * Node connection helpers — shared bootstrap primitives for the Node consumers\n * (`@abraca/mcp`, `@abraca/cli`, `@abraca/orchestrator`, `@abraca/resend`).\n *\n * Each of those packages opened a synced root/space/inbox provider with the\n * exact same incantation (`new Y.Doc({ guid }) → new AbracadabraProvider({\n * disableOfflineStore, subdocLoading:'lazy' }) → waitForSync`) and selected the\n * entry space with the same \"first Kind.Space, else first top-level doc\" rule.\n * Both live here now so there is one implementation.\n *\n * These are deliberately small, faithful extractions — they do NOT own auth\n * (see {@link loginOrRegisterWithKey}), awareness, child-provider caching, or\n * the reconnect/heal loop. Those stay with each consumer.\n */\n\nimport * as Y from \"yjs\";\nimport { AbracadabraProvider } from \"./AbracadabraProvider.ts\";\nimport { AbracadabraClient } from \"./AbracadabraClient.ts\";\nimport { waitForSync } from \"./DocUtils.ts\";\nimport { Kind } from \"./types.ts\";\nimport type { DocumentMeta } from \"./types.ts\";\n\n/**\n * Open a fresh `AbracadabraProvider` bound to `docId` on `client` and wait for\n * its first sync. Returns the new `Y.Doc` + provider. Used for the root space\n * doc, child-space docs, and the inbox doc alike — every Node consumer opened\n * them with these exact options.\n *\n * Offline persistence is disabled (Node daemons/CLIs are online-only) and\n * subdocs load lazily.\n */\nexport async function openSyncedProvider(opts: {\n\tclient: AbracadabraClient;\n\tdocId: string;\n\tsyncTimeoutMs?: number;\n}): Promise<{ doc: Y.Doc; provider: AbracadabraProvider }> {\n\tconst doc = new Y.Doc({ guid: opts.docId });\n\tconst provider = new AbracadabraProvider({\n\t\tname: opts.docId,\n\t\tdocument: doc,\n\t\tclient: opts.client,\n\t\tdisableOfflineStore: true,\n\t\tsubdocLoading: \"lazy\",\n\t});\n\tawait waitForSync(provider, opts.syncTimeoutMs);\n\treturn { doc, provider };\n}\n\n/**\n * Pick the entry-point document from a server root's top-level children: the\n * first `Kind.Space`, falling back to the first top-level doc of any kind.\n * Returns `null` when the server has no top-level documents.\n *\n * `spaces` is returned alongside so callers that track the space list (most do)\n * don't have to re-filter.\n */\nexport function pickEntrySpace(roots: DocumentMeta[]): {\n\tentry: DocumentMeta | null;\n\tspaces: DocumentMeta[];\n} {\n\tconst spaces = roots.filter((d) => d.kind === Kind.Space);\n\treturn { entry: spaces[0] ?? roots[0] ?? null, spaces };\n}\n","/**\n * ServerRegistry — a tiny on-disk registry of Abracadabra servers shared by the\n * Node-side consumers (`@abraca/mcp`, `@abraca/cli`).\n *\n * Historically each daemon read a single `ABRA_URL` and a single key file, so it\n * could only ever talk to one server. The registry lets a user remember several\n * servers by alias, keep a per-server identity (key file), and switch between\n * them — both from the CLI (`server add/use/login`) and from a running MCP agent\n * (`connect_server`/`switch_server`).\n *\n * Format: JSON at `~/.abracadabra/servers.json` (override with `ABRA_SERVERS_FILE`):\n *\n * {\n * \"defaultAlias\": \"coop\",\n * \"servers\": {\n * \"coop\": { \"alias\": \"coop\", \"url\": \"https://coop.cou.sh\",\n * \"keyFile\": \"/home/me/.abracadabra/keys/coop.key\" }\n * }\n * }\n *\n * Node-only: filesystem access is via dynamic `import(\"node:…\")`, so importing\n * this module from a browser bundle is safe — only *calling* the load/save\n * helpers requires Node.\n */\n\n// ── Types ──────────────────────────────────────────────────────────────────\n\n/** A single remembered server. */\nexport interface ServerProfile {\n\t/** Short, unique handle used on the CLI / in MCP tools. */\n\talias: string;\n\t/** Base URL, e.g. `https://coop.cou.sh`. */\n\turl: string;\n\t/** Path to this server's Ed25519 key file (per-server identity). */\n\tkeyFile: string;\n\t/** Display name presented to the server (presence / registration). */\n\tdisplayName?: string;\n\t/** Presence color (HSL string). */\n\tcolor?: string;\n\t/** Invite/registration token, when the server is invite-only. */\n\tinviteCode?: string;\n}\n\n/** The whole registry: a map of profiles plus which alias is the default. */\nexport interface ServerRegistry {\n\t/** Alias used when no `--server` / `connect_server` target is given. */\n\tdefaultAlias?: string;\n\tservers: Record<string, ServerProfile>;\n}\n\n// ── Paths ──────────────────────────────────────────────────────────────────\n\n/** Resolve the registry path: `ABRA_SERVERS_FILE` env, else `~/.abracadabra/servers.json`. */\nexport async function serverRegistryPath(override?: string): Promise<string> {\n\tconst { homedir } = await import(\"node:os\");\n\tconst { join } = await import(\"node:path\");\n\treturn (\n\t\toverride ??\n\t\tprocess.env.ABRA_SERVERS_FILE ??\n\t\tjoin(homedir(), \".abracadabra\", \"servers.json\")\n\t);\n}\n\n/** Default per-server key-file path: `~/.abracadabra/keys/<alias>.key`. */\nexport async function defaultKeyFileFor(alias: string): Promise<string> {\n\tconst { homedir } = await import(\"node:os\");\n\tconst { join } = await import(\"node:path\");\n\tconst safe = alias.replace(/[^a-zA-Z0-9._-]/g, \"_\");\n\treturn join(homedir(), \".abracadabra\", \"keys\", `${safe}.key`);\n}\n\n// ── Load / save ────────────────────────────────────────────────────────────\n\n/**\n * Load the registry from disk. A missing file yields an empty registry (never\n * throws on absence). A malformed file throws so the caller can surface it.\n */\nexport async function loadServerRegistry(\n\tpath?: string,\n): Promise<ServerRegistry> {\n\tconst { existsSync } = await import(\"node:fs\");\n\tconst { readFile } = await import(\"node:fs/promises\");\n\tconst file = await serverRegistryPath(path);\n\n\tif (!existsSync(file)) return { servers: {} };\n\n\tconst raw = await readFile(file, \"utf8\");\n\tif (!raw.trim()) return { servers: {} };\n\tlet parsed: unknown;\n\ttry {\n\t\tparsed = JSON.parse(raw);\n\t} catch (err) {\n\t\tthrow new Error(\n\t\t\t`Malformed server registry at ${file}: ${(err as Error).message}`,\n\t\t);\n\t}\n\tconst reg = parsed as Partial<ServerRegistry>;\n\treturn {\n\t\tdefaultAlias: reg.defaultAlias,\n\t\tservers: reg.servers ?? {},\n\t};\n}\n\n/** Persist the registry, creating `~/.abracadabra/` with `0o700` if needed. */\nexport async function saveServerRegistry(\n\treg: ServerRegistry,\n\tpath?: string,\n): Promise<void> {\n\tconst { existsSync } = await import(\"node:fs\");\n\tconst { writeFile, mkdir } = await import(\"node:fs/promises\");\n\tconst { dirname } = await import(\"node:path\");\n\tconst file = await serverRegistryPath(path);\n\tconst dir = dirname(file);\n\tif (!existsSync(dir)) await mkdir(dir, { recursive: true, mode: 0o700 });\n\tawait writeFile(file, `${JSON.stringify(reg, null, 2)}\\n`, { mode: 0o600 });\n}\n\n// ── Resolution ─────────────────────────────────────────────────────────────\n\n/**\n * Resolve `aliasOrUrl` against the registry.\n *\n * - A known alias → its stored profile.\n * - A bare URL (starts with `http://` / `https://`) → an ephemeral profile with\n * a derived alias (the URL host) and a default per-host key file. This is NOT\n * persisted; the caller decides whether to `addServer` it.\n * - Anything else → `null` (unknown alias).\n */\nexport async function resolveServer(\n\treg: ServerRegistry,\n\taliasOrUrl: string,\n): Promise<ServerProfile | null> {\n\tconst direct = reg.servers[aliasOrUrl];\n\tif (direct) return direct;\n\n\tif (/^https?:\\/\\//i.test(aliasOrUrl)) {\n\t\tlet alias = aliasOrUrl;\n\t\ttry {\n\t\t\talias = new URL(aliasOrUrl).host || aliasOrUrl;\n\t\t} catch {\n\t\t\t/* keep the raw string as the alias */\n\t\t}\n\t\treturn {\n\t\t\talias,\n\t\t\turl: aliasOrUrl.replace(/\\/+$/, \"\"),\n\t\t\tkeyFile: await defaultKeyFileFor(alias),\n\t\t};\n\t}\n\n\treturn null;\n}\n\n// ── Mutators (return a new registry; caller persists) ────────────────────────\n\n/** Add or replace a profile. The first server added becomes the default. */\nexport function addServer(\n\treg: ServerRegistry,\n\tprofile: ServerProfile,\n): ServerRegistry {\n\tconst servers = { ...reg.servers, [profile.alias]: profile };\n\tconst defaultAlias =\n\t\treg.defaultAlias && reg.servers[reg.defaultAlias]\n\t\t\t? reg.defaultAlias\n\t\t\t: profile.alias;\n\treturn { defaultAlias, servers };\n}\n\n/** Remove a profile by alias. Clears `defaultAlias` if it pointed at it. */\nexport function removeServer(\n\treg: ServerRegistry,\n\talias: string,\n): ServerRegistry {\n\tif (!reg.servers[alias]) return reg;\n\tconst servers = { ...reg.servers };\n\tdelete servers[alias];\n\tlet defaultAlias = reg.defaultAlias;\n\tif (defaultAlias === alias) {\n\t\tdefaultAlias = Object.keys(servers)[0];\n\t}\n\treturn { defaultAlias, servers };\n}\n\n/** Mark `alias` as the default. Throws if the alias is unknown. */\nexport function setDefault(reg: ServerRegistry, alias: string): ServerRegistry {\n\tif (!reg.servers[alias]) {\n\t\tthrow new Error(`Unknown server alias: ${alias}`);\n\t}\n\treturn { ...reg, defaultAlias: alias };\n}\n\n// ── Migration ────────────────────────────────────────────────────────────────\n\n/**\n * Seed a `default` profile from a legacy single-key setup when the registry is\n * empty. Existing MCP/CLI users keep `~/.abracadabra/{agent,cli}.key` and an\n * `ABRA_URL`; without this they'd lose their identity the first time the\n * registry takes over. Returns the (possibly unchanged) registry; the caller\n * persists if `migrated` is true.\n *\n * @param url the legacy `ABRA_URL` (no migration without it).\n * @param legacyKeyFile path to the legacy key (e.g. `~/.abracadabra/agent.key`).\n */\nexport async function migrateLegacyDefault(\n\treg: ServerRegistry,\n\turl: string | undefined,\n\tlegacyKeyFile: string,\n): Promise<{ registry: ServerRegistry; migrated: boolean }> {\n\tif (!url || Object.keys(reg.servers).length > 0) {\n\t\treturn { registry: reg, migrated: false };\n\t}\n\tconst { existsSync } = await import(\"node:fs\");\n\tif (!existsSync(legacyKeyFile)) return { registry: reg, migrated: false };\n\n\tconst profile: ServerProfile = {\n\t\talias: \"default\",\n\t\turl: url.replace(/\\/+$/, \"\"),\n\t\tkeyFile: legacyKeyFile,\n\t};\n\treturn { registry: addServer(reg, profile), migrated: true };\n}\n","/**\n * IndexedDB-backed cache for REST API metadata (documents, children, profiles,\n * permissions, uploads). Provides offline-first read access to data fetched\n * from the server.\n *\n * Each entry carries a `cachedAt` timestamp; reads return null once the TTL\n * has elapsed. The cache is scoped by server origin so the same app can work\n * against multiple backends without cross-contamination.\n *\n * Designed to be passed to AbracadabraClientConfig.cache so the client\n * automatically checks the cache before hitting the network.\n */\n\nimport type {\n\tDocumentMeta,\n\tUserProfile,\n\tPermissionEntry,\n\tUploadInfo,\n} from \"./types.ts\";\n\nconst DB_VERSION = 1;\nconst DEFAULT_TTL_MS = 5 * 60 * 1000; // 5 minutes\n\nfunction idbAvailable(): boolean {\n\treturn typeof globalThis !== \"undefined\" && \"indexedDB\" in globalThis;\n}\n\nfunction openDb(origin: string): Promise<IDBDatabase> {\n\treturn new Promise((resolve, reject) => {\n\t\tconst req = globalThis.indexedDB.open(\n\t\t\t`abracadabra:meta-cache:${origin}`,\n\t\t\tDB_VERSION,\n\t\t);\n\n\t\treq.onupgradeneeded = (event) => {\n\t\t\tconst db = (event.target as IDBOpenDBRequest).result;\n\t\t\tfor (const name of [\"doc_meta\", \"children\", \"user_profile\", \"permissions\", \"uploads\"]) {\n\t\t\t\tif (!db.objectStoreNames.contains(name)) {\n\t\t\t\t\tdb.createObjectStore(name);\n\t\t\t\t}\n\t\t\t}\n\t\t};\n\n\t\treq.onsuccess = () => resolve(req.result);\n\t\treq.onerror = () => reject(req.error);\n\t});\n}\n\nfunction txPromise<T>(store: IDBObjectStore, request: IDBRequest<T>): Promise<T> {\n\treturn new Promise((resolve, reject) => {\n\t\trequest.onsuccess = () => resolve(request.result);\n\t\trequest.onerror = () => reject(request.error);\n\t});\n}\n\nexport interface DocumentCacheOptions {\n\t/** How long cached entries remain valid. Default: 5 minutes. */\n\tttlMs?: number;\n}\n\nexport class DocumentCache {\n\tprivate readonly origin: string;\n\tprivate readonly ttlMs: number;\n\tprivate dbPromise: Promise<IDBDatabase | null> | null = null;\n\tprivate db: IDBDatabase | null = null;\n\n\tconstructor(serverOrigin: string, opts?: DocumentCacheOptions) {\n\t\tthis.origin = serverOrigin;\n\t\tthis.ttlMs = opts?.ttlMs ?? DEFAULT_TTL_MS;\n\t}\n\n\tprivate getDb(): Promise<IDBDatabase | null> {\n\t\tif (!idbAvailable()) return Promise.resolve(null);\n\t\tif (!this.dbPromise) {\n\t\t\tthis.dbPromise = openDb(this.origin)\n\t\t\t\t.catch(() => null)\n\t\t\t\t.then((db) => {\n\t\t\t\t\tthis.db = db;\n\t\t\t\t\treturn db;\n\t\t\t\t});\n\t\t}\n\t\treturn this.dbPromise;\n\t}\n\n\tprivate isExpired(cachedAt: number): boolean {\n\t\treturn Date.now() - cachedAt > this.ttlMs;\n\t}\n\n\t// ── Generic TTL helpers ───────────────────────────────────────────────────\n\n\tprivate async getWithTtl<T>(\n\t\tstoreName: string,\n\t\tkey: string,\n\t): Promise<T | null> {\n\t\tconst db = await this.getDb();\n\t\tif (!db) return null;\n\t\tconst tx = db.transaction(storeName, \"readonly\");\n\t\tconst result = await txPromise<{ value: T; cachedAt: number } | undefined>(\n\t\t\ttx.objectStore(storeName),\n\t\t\ttx.objectStore(storeName).get(key),\n\t\t);\n\t\tif (!result) return null;\n\t\tif (this.isExpired(result.cachedAt)) {\n\t\t\t// Stale — evict asynchronously and signal miss\n\t\t\tthis.deleteKey(storeName, key).catch(() => null);\n\t\t\treturn null;\n\t\t}\n\t\treturn result.value;\n\t}\n\n\tprivate async setWithTtl<T>(storeName: string, key: string, value: T): Promise<void> {\n\t\tconst db = await this.getDb();\n\t\tif (!db) return;\n\t\tconst entry = { value, cachedAt: Date.now() };\n\t\tconst tx = db.transaction(storeName, \"readwrite\");\n\t\tawait txPromise(\n\t\t\ttx.objectStore(storeName),\n\t\t\ttx.objectStore(storeName).put(entry, key),\n\t\t);\n\t}\n\n\tprivate async deleteKey(storeName: string, key: string): Promise<void> {\n\t\tconst db = await this.getDb();\n\t\tif (!db) return;\n\t\tconst tx = db.transaction(storeName, \"readwrite\");\n\t\tawait txPromise(tx.objectStore(storeName), tx.objectStore(storeName).delete(key));\n\t}\n\n\t// ── Document metadata ─────────────────────────────────────────────────────\n\n\tasync getDoc(docId: string): Promise<DocumentMeta | null> {\n\t\treturn this.getWithTtl<DocumentMeta>(\"doc_meta\", docId);\n\t}\n\n\tasync setDoc(meta: DocumentMeta): Promise<void> {\n\t\treturn this.setWithTtl(\"doc_meta\", meta.id, meta);\n\t}\n\n\tasync invalidateDoc(docId: string): Promise<void> {\n\t\tawait this.deleteKey(\"doc_meta\", docId).catch(() => null);\n\t}\n\n\t// ── Children list ─────────────────────────────────────────────────────────\n\n\tasync getChildren(parentId: string): Promise<string[] | null> {\n\t\treturn this.getWithTtl<string[]>(\"children\", parentId);\n\t}\n\n\tasync setChildren(parentId: string, items: string[]): Promise<void> {\n\t\treturn this.setWithTtl(\"children\", parentId, items);\n\t}\n\n\tasync invalidateChildren(parentId: string): Promise<void> {\n\t\tawait this.deleteKey(\"children\", parentId).catch(() => null);\n\t}\n\n\t// ── User profile ──────────────────────────────────────────────────────────\n\n\tasync getProfile(userId: string): Promise<UserProfile | null> {\n\t\treturn this.getWithTtl<UserProfile>(\"user_profile\", userId);\n\t}\n\n\tasync setProfile(profile: UserProfile): Promise<void> {\n\t\treturn this.setWithTtl(\"user_profile\", profile.id, profile);\n\t}\n\n\t/** Get the cached profile for the currently authenticated user. */\n\tasync getCurrentProfile(): Promise<UserProfile | null> {\n\t\treturn this.getWithTtl<UserProfile>(\"user_profile\", \"__current__\");\n\t}\n\n\t/** Cache a profile both by its ID and as the current user. */\n\tasync setCurrentProfile(profile: UserProfile): Promise<void> {\n\t\tawait Promise.all([\n\t\t\tthis.setWithTtl(\"user_profile\", profile.id, profile),\n\t\t\tthis.setWithTtl(\"user_profile\", \"__current__\", profile),\n\t\t]);\n\t}\n\n\t// ── Permissions ───────────────────────────────────────────────────────────\n\n\tasync getPermissions(docId: string): Promise<PermissionEntry[] | null> {\n\t\treturn this.getWithTtl<PermissionEntry[]>(\"permissions\", docId);\n\t}\n\n\tasync setPermissions(docId: string, items: PermissionEntry[]): Promise<void> {\n\t\treturn this.setWithTtl(\"permissions\", docId, items);\n\t}\n\n\t// ── Uploads list ──────────────────────────────────────────────────────────\n\n\tasync getUploads(docId: string): Promise<UploadInfo[] | null> {\n\t\treturn this.getWithTtl<UploadInfo[]>(\"uploads\", docId);\n\t}\n\n\tasync setUploads(docId: string, items: UploadInfo[]): Promise<void> {\n\t\treturn this.setWithTtl(\"uploads\", docId, items);\n\t}\n\n\tasync invalidateUploads(docId: string): Promise<void> {\n\t\tawait this.deleteKey(\"uploads\", docId).catch(() => null);\n\t}\n\n\t// ── Lifecycle ─────────────────────────────────────────────────────────────\n\n\tdestroy(): void {\n\t\tthis.db?.close();\n\t\tthis.db = null;\n\t}\n}\n","/**\n * IndexedDB-backed trigram full-text search index.\n *\n * Generic: caller passes (docId, texts[]) — works for Y.Doc text content,\n * file names, document titles, or any other text. No Y.js coupling.\n *\n * Algorithm: trigram inverted index.\n * - Each document is decomposed into overlapping 3-character windows.\n * - The \"postings\" store maps trigram → [docId, ...].\n * - The \"doc_trigrams\" store maps docId → [trigram, ...] for efficient removal.\n * - search() scores by number of query trigrams that match.\n *\n * IDB transactions that touch multiple stores use the callback-only pattern\n * (not async/await inside a transaction) to avoid the transaction auto-commit\n * issue across microtask boundaries.\n */\n\nimport type { SearchResult } from \"./types.ts\";\n\nconst DB_VERSION = 1;\n\nfunction idbAvailable(): boolean {\n\treturn typeof globalThis !== \"undefined\" && \"indexedDB\" in globalThis;\n}\n\nfunction openDb(origin: string): Promise<IDBDatabase> {\n\treturn new Promise((resolve, reject) => {\n\t\tconst req = globalThis.indexedDB.open(`abracadabra:search:${origin}`, DB_VERSION);\n\n\t\treq.onupgradeneeded = (event) => {\n\t\t\tconst db = (event.target as IDBOpenDBRequest).result;\n\t\t\tif (!db.objectStoreNames.contains(\"postings\")) {\n\t\t\t\tdb.createObjectStore(\"postings\");\n\t\t\t}\n\t\t\tif (!db.objectStoreNames.contains(\"doc_trigrams\")) {\n\t\t\t\tdb.createObjectStore(\"doc_trigrams\");\n\t\t\t}\n\t\t};\n\n\t\treq.onsuccess = () => resolve(req.result);\n\t\treq.onerror = () => reject(req.error);\n\t});\n}\n\n/** Extract the set of trigrams for a piece of text. */\nfunction extractTrigrams(text: string): Set<string> {\n\tconst trigrams = new Set<string>();\n\tconst padded = ` ${text.toLowerCase()} `;\n\tfor (let i = 0; i <= padded.length - 3; i++) {\n\t\ttrigrams.add(padded.slice(i, i + 3));\n\t}\n\treturn trigrams;\n}\n\n/** Merge trigrams from multiple texts into a single set. */\nfunction extractAllTrigrams(texts: string[]): Set<string> {\n\tconst result = new Set<string>();\n\tfor (const t of texts) {\n\t\tfor (const trigram of extractTrigrams(t)) {\n\t\t\tresult.add(trigram);\n\t\t}\n\t}\n\treturn result;\n}\n\nexport class SearchIndex {\n\tprivate readonly origin: string;\n\tprivate dbPromise: Promise<IDBDatabase | null> | null = null;\n\tprivate db: IDBDatabase | null = null;\n\n\tconstructor(serverOrigin: string) {\n\t\tthis.origin = serverOrigin;\n\t}\n\n\tprivate getDb(): Promise<IDBDatabase | null> {\n\t\tif (!idbAvailable()) return Promise.resolve(null);\n\t\tif (!this.dbPromise) {\n\t\t\tthis.dbPromise = openDb(this.origin)\n\t\t\t\t.catch(() => null)\n\t\t\t\t.then((db) => {\n\t\t\t\t\tthis.db = db;\n\t\t\t\t\treturn db;\n\t\t\t\t});\n\t\t}\n\t\treturn this.dbPromise;\n\t}\n\n\t/**\n\t * Replace the index for docId with the given texts.\n\t * Old trigram associations are removed before new ones are added.\n\t */\n\tasync index(docId: string, texts: string[]): Promise<void> {\n\t\tconst db = await this.getDb();\n\t\tif (!db) return;\n\n\t\tconst newTrigrams = extractAllTrigrams(texts);\n\n\t\treturn new Promise<void>((resolve, reject) => {\n\t\t\tconst tx = db.transaction([\"postings\", \"doc_trigrams\"], \"readwrite\");\n\t\t\ttx.oncomplete = () => resolve();\n\t\t\ttx.onerror = () => reject(tx.error);\n\n\t\t\tconst postings = tx.objectStore(\"postings\");\n\t\t\tconst docTrigramsStore = tx.objectStore(\"doc_trigrams\");\n\n\t\t\t// Step 1: read old trigrams for this doc\n\t\t\tconst oldReq = docTrigramsStore.get(docId);\n\t\t\toldReq.onsuccess = () => {\n\t\t\t\tconst oldTrigrams: string[] = oldReq.result ?? [];\n\t\t\t\tlet pending = oldTrigrams.length + newTrigrams.size + 1; // +1 for doc_trigrams write\n\n\t\t\t\tfunction done() {\n\t\t\t\t\tpending--;\n\t\t\t\t\t// tx.oncomplete fires naturally once all requests settle\n\t\t\t\t}\n\n\t\t\t\t// Step 2: remove docId from each old trigram's posting list\n\t\t\t\tfor (const trigram of oldTrigrams) {\n\t\t\t\t\tconst req = postings.get(trigram);\n\t\t\t\t\treq.onsuccess = () => {\n\t\t\t\t\t\tconst list: string[] = req.result ?? [];\n\t\t\t\t\t\tconst updated = list.filter((id) => id !== docId);\n\t\t\t\t\t\tif (updated.length === 0) {\n\t\t\t\t\t\t\tpostings.delete(trigram);\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tpostings.put(updated, trigram);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tdone();\n\t\t\t\t\t};\n\t\t\t\t\treq.onerror = done;\n\t\t\t\t}\n\n\t\t\t\t// Step 3: add docId to each new trigram's posting list\n\t\t\t\tfor (const trigram of newTrigrams) {\n\t\t\t\t\tconst req = postings.get(trigram);\n\t\t\t\t\treq.onsuccess = () => {\n\t\t\t\t\t\tconst list: string[] = req.result ?? [];\n\t\t\t\t\t\tif (!list.includes(docId)) {\n\t\t\t\t\t\t\tlist.push(docId);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tpostings.put(list, trigram);\n\t\t\t\t\t\tdone();\n\t\t\t\t\t};\n\t\t\t\t\treq.onerror = done;\n\t\t\t\t}\n\n\t\t\t\t// Step 4: save new trigram set for this doc\n\t\t\t\tconst writeReq = docTrigramsStore.put([...newTrigrams], docId);\n\t\t\t\twriteReq.onsuccess = done;\n\t\t\t\twriteReq.onerror = done;\n\t\t\t};\n\t\t\toldReq.onerror = () => reject(oldReq.error);\n\t\t});\n\t}\n\n\t/** Remove all indexed content for a document. */\n\tasync remove(docId: string): Promise<void> {\n\t\tconst db = await this.getDb();\n\t\tif (!db) return;\n\n\t\treturn new Promise<void>((resolve, reject) => {\n\t\t\tconst tx = db.transaction([\"postings\", \"doc_trigrams\"], \"readwrite\");\n\t\t\ttx.oncomplete = () => resolve();\n\t\t\ttx.onerror = () => reject(tx.error);\n\n\t\t\tconst postings = tx.objectStore(\"postings\");\n\t\t\tconst docTrigramsStore = tx.objectStore(\"doc_trigrams\");\n\n\t\t\tconst oldReq = docTrigramsStore.get(docId);\n\t\t\toldReq.onsuccess = () => {\n\t\t\t\tconst oldTrigrams: string[] = oldReq.result ?? [];\n\n\t\t\t\tfor (const trigram of oldTrigrams) {\n\t\t\t\t\tconst req = postings.get(trigram);\n\t\t\t\t\treq.onsuccess = () => {\n\t\t\t\t\t\tconst list: string[] = req.result ?? [];\n\t\t\t\t\t\tconst updated = list.filter((id) => id !== docId);\n\t\t\t\t\t\tif (updated.length === 0) {\n\t\t\t\t\t\t\tpostings.delete(trigram);\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tpostings.put(updated, trigram);\n\t\t\t\t\t\t}\n\t\t\t\t\t};\n\t\t\t\t}\n\n\t\t\t\tdocTrigramsStore.delete(docId);\n\t\t\t};\n\t\t\toldReq.onerror = () => reject(oldReq.error);\n\t\t});\n\t}\n\n\t/**\n\t * Search for documents matching the query.\n\t * Returns results sorted by score (matching trigram count) descending.\n\t */\n\tasync search(query: string, limit = 20): Promise<SearchResult[]> {\n\t\tconst db = await this.getDb();\n\t\tif (!db) return [];\n\n\t\tconst queryTrigrams = [...extractTrigrams(query)];\n\t\tif (queryTrigrams.length === 0) return [];\n\n\t\tconst maxScoreEntries = limit * 10;\n\n\t\treturn new Promise<SearchResult[]>((resolve, reject) => {\n\t\t\tconst tx = db.transaction(\"postings\", \"readonly\");\n\t\t\tconst postings = tx.objectStore(\"postings\");\n\t\t\tconst scores = new Map<string, number>();\n\t\t\tlet remaining = queryTrigrams.length;\n\n\t\t\tfor (const trigram of queryTrigrams) {\n\t\t\t\tconst req = postings.get(trigram);\n\t\t\t\treq.onsuccess = () => {\n\t\t\t\t\tconst docIds: string[] = req.result ?? [];\n\t\t\t\t\tfor (const docId of docIds) {\n\t\t\t\t\t\tscores.set(docId, (scores.get(docId) ?? 0) + 1);\n\t\t\t\t\t\tif (scores.size >= maxScoreEntries) break;\n\t\t\t\t\t}\n\t\t\t\t\tremaining--;\n\t\t\t\t\tif (remaining === 0) {\n\t\t\t\t\t\tconst results: SearchResult[] = [...scores.entries()]\n\t\t\t\t\t\t\t.map(([docId, score]) => ({ docId, score }))\n\t\t\t\t\t\t\t.sort((a, b) => b.score - a.score)\n\t\t\t\t\t\t\t.slice(0, limit);\n\t\t\t\t\t\tresolve(results);\n\t\t\t\t\t}\n\t\t\t\t};\n\t\t\t\treq.onerror = () => {\n\t\t\t\t\tremaining--;\n\t\t\t\t\tif (remaining === 0) {\n\t\t\t\t\t\tconst results: SearchResult[] = [...scores.entries()]\n\t\t\t\t\t\t\t.map(([docId, score]) => ({ docId, score }))\n\t\t\t\t\t\t\t.sort((a, b) => b.score - a.score)\n\t\t\t\t\t\t\t.slice(0, limit);\n\t\t\t\t\t\tresolve(results);\n\t\t\t\t\t}\n\t\t\t\t};\n\t\t\t}\n\n\t\t\ttx.onerror = () => reject(tx.error);\n\t\t});\n\t}\n\n\t// ── Lifecycle ─────────────────────────────────────────────────────────────\n\n\tdestroy(): void {\n\t\tthis.db?.close();\n\t\tthis.db = null;\n\t}\n}\n","/**\n * IndexedDB-backed file blob cache with an offline-tolerant upload queue.\n *\n * Responsibilities:\n * - Cache downloaded file blobs locally so they can be served offline via\n * object URLs (URL.createObjectURL).\n * - Queue file uploads when the network is unavailable. The queue persists\n * across page reloads (IndexedDB-backed).\n * - Auto-flush the upload queue when the browser reports it is back online,\n * and expose flushQueue() for manual flushing.\n *\n * Events:\n * - \"upload:queued\" — entry added to queue\n * - \"upload:started\" — upload attempt started\n * - \"upload:done\" — upload succeeded\n * - \"upload:error\" — upload attempt failed\n *\n * Falls back to a silent no-op when IndexedDB is unavailable (SSR / Node.js).\n */\n\nimport type { UploadQueueEntry, ThumbnailOptions } from \"./types.ts\";\nimport type { AbracadabraClient } from \"./AbracadabraClient.ts\";\nimport EventEmitter from \"./EventEmitter.ts\";\n\nconst DB_VERSION = 1;\n\nfunction idbAvailable(): boolean {\n\treturn typeof globalThis !== \"undefined\" && \"indexedDB\" in globalThis;\n}\n\nfunction openDb(origin: string): Promise<IDBDatabase> {\n\treturn new Promise((resolve, reject) => {\n\t\tconst req = globalThis.indexedDB.open(`abracadabra:files:${origin}`, DB_VERSION);\n\n\t\treq.onupgradeneeded = (event) => {\n\t\t\tconst db = (event.target as IDBOpenDBRequest).result;\n\t\t\tif (!db.objectStoreNames.contains(\"blobs\")) {\n\t\t\t\tdb.createObjectStore(\"blobs\");\n\t\t\t}\n\t\t\tif (!db.objectStoreNames.contains(\"upload_queue\")) {\n\t\t\t\tdb.createObjectStore(\"upload_queue\", { keyPath: \"id\" });\n\t\t\t}\n\t\t};\n\n\t\treq.onsuccess = () => resolve(req.result);\n\t\treq.onerror = () => reject(req.error);\n\t});\n}\n\nfunction txPromise<T>(store: IDBObjectStore, request: IDBRequest<T>): Promise<T> {\n\treturn new Promise((resolve, reject) => {\n\t\trequest.onsuccess = () => resolve(request.result);\n\t\trequest.onerror = () => reject(request.error);\n\t});\n}\n\ninterface BlobCacheEntry {\n\tblob: Blob;\n\tmime_type: string;\n\tfilename: string;\n\tcachedAt: number;\n}\n\nexport class FileBlobStore extends EventEmitter {\n\tprivate readonly origin: string;\n\tprivate readonly client: AbracadabraClient | null;\n\tprivate dbPromise: Promise<IDBDatabase | null> | null = null;\n\tprivate db: IDBDatabase | null = null;\n\n\t/** Tracks active object URLs so we can revoke them on destroy. */\n\tprivate readonly objectUrls = new Map<string, string>();\n\n\t/** Keys that returned 404 from the server — avoids repeated requests. TTL: 5 min. */\n\tprivate readonly _notFound = new Map<string, number>();\n\tprivate static readonly NOT_FOUND_TTL = 5 * 60 * 1000;\n\n\t/** Prevents concurrent flush runs. */\n\tprivate _flushPromise: Promise<void> | null = null;\n\n\tprivate readonly _onlineHandler: () => void;\n\n\tconstructor(serverOrigin: string, client?: AbracadabraClient | null) {\n\t\tsuper();\n\t\tthis.origin = serverOrigin;\n\t\tthis.client = client ?? null;\n\n\t\tthis._onlineHandler = () => { this.flushQueue().catch(() => null); };\n\t\tif (typeof window !== \"undefined\") {\n\t\t\twindow.addEventListener(\"online\", this._onlineHandler);\n\t\t}\n\t}\n\n\tprivate getDb(): Promise<IDBDatabase | null> {\n\t\tif (!idbAvailable()) return Promise.resolve(null);\n\t\tif (!this.dbPromise) {\n\t\t\tthis.dbPromise = openDb(this.origin)\n\t\t\t\t.catch(() => null)\n\t\t\t\t.then((db) => {\n\t\t\t\t\tthis.db = db;\n\t\t\t\t\tif (db) {\n\t\t\t\t\t\t// A browser-initiated close (storage pressure, tab\n\t\t\t\t\t\t// eviction) leaves the cached handle unusable. Reset so\n\t\t\t\t\t\t// the next getDb() reopens instead of handing back a\n\t\t\t\t\t\t// connection that throws \"database connection is\n\t\t\t\t\t\t// closing\" on transaction().\n\t\t\t\t\t\tdb.onclose = () => {\n\t\t\t\t\t\t\tif (this.db === db) this.db = null;\n\t\t\t\t\t\t\tthis.dbPromise = null;\n\t\t\t\t\t\t};\n\t\t\t\t\t}\n\t\t\t\t\treturn db;\n\t\t\t\t});\n\t\t}\n\t\treturn this.dbPromise;\n\t}\n\n\tprivate blobKey(docId: string, uploadId: string): string {\n\t\treturn `${docId}/${uploadId}`;\n\t}\n\n\t/**\n\t * Cache key for a thumbnail. Lives in the SAME IDB `blobs` store as\n\t * originals (no schema bump — the frozen cross-SDK IDB contract stays\n\t * intact) under a distinct `thumb:` namespace. The spec suffix is\n\t * deterministic so identical options collapse to one entry.\n\t */\n\tprivate thumbKey(docId: string, uploadId: string, opts: ThumbnailOptions): string {\n\t\tconst spec = [\n\t\t\topts.w != null ? `w${opts.w}` : \"\",\n\t\t\topts.h != null ? `h${opts.h}` : \"\",\n\t\t\topts.fit ? `f${opts.fit}` : \"\",\n\t\t\topts.format ? `m${opts.format}` : \"\",\n\t\t\topts.q != null ? `q${opts.q}` : \"\",\n\t\t]\n\t\t\t.filter(Boolean)\n\t\t\t.join(\"-\");\n\t\treturn `thumb:${docId}/${uploadId}/${spec}`;\n\t}\n\n\t// ── Blob cache ────────────────────────────────────────────────────────────\n\n\t/**\n\t * Return a local object URL for a file.\n\t * On first call the blob is downloaded from the server and cached in IDB.\n\t * Returns null when offline and the blob is not yet cached, or when\n\t * URL.createObjectURL is unavailable (e.g. Node.js / SSR).\n\t */\n\tasync getBlobUrl(docId: string, uploadId: string): Promise<string | null> {\n\t\treturn this._objectUrlForKey(\n\t\t\tthis.blobKey(docId, uploadId),\n\t\t\tuploadId,\n\t\t\tthis.client ? () => this.client!.getUpload(docId, uploadId) : null,\n\t\t);\n\t}\n\n\t/**\n\t * Return a **server** URL that streams an upload with HTTP Range support —\n\t * for `<video src>` / `<audio src>`, where `getBlobUrl` would first pull\n\t * the entire file into IndexedDB and seeking would stall until it landed.\n\t *\n\t * Requires a client and the network (the URL points at the server, and\n\t * minting its token is a request). Returns `null` when either is missing,\n\t * when the server predates the `stream-token` endpoint, or when we're\n\t * already known to be offline — callers fall back to `getBlobUrl` for the\n\t * cached copy.\n\t */\n\tasync getStreamUrl(docId: string, uploadId: string): Promise<string | null> {\n\t\tif (!this.client) return null;\n\t\tif (typeof navigator !== \"undefined\" && navigator.onLine === false) {\n\t\t\treturn null;\n\t\t}\n\t\ttry {\n\t\t\treturn await this.client.getStreamUrl(docId, uploadId);\n\t\t} catch {\n\t\t\treturn null;\n\t\t}\n\t}\n\n\t/**\n\t * Return a local object URL for a **thumbnail** of an image upload.\n\t * On first call the server renders + caches it and this stores the bytes\n\t * in IDB (same offline-serving model as `getBlobUrl`). Returns null when\n\t * offline + uncached, on non-image sources (server 415 → treated like a\n\t * miss), or outside the browser. Options must match the server's\n\t * `allowed_sizes` / `allowed_formats` or the fetch 422s (→ null).\n\t */\n\tasync getThumbUrl(\n\t\tdocId: string,\n\t\tuploadId: string,\n\t\topts: ThumbnailOptions = {},\n\t): Promise<string | null> {\n\t\treturn this._objectUrlForKey(\n\t\t\tthis.thumbKey(docId, uploadId, opts),\n\t\t\tuploadId,\n\t\t\tthis.client ? () => this.client!.getThumbnail(docId, uploadId, opts) : null,\n\t\t);\n\t}\n\n\t/**\n\t * Shared read-through: in-memory object URL → IDB `blobs` cache (with a\n\t * one-shot reopen on `InvalidStateError`) → `download()` (when a client is\n\t * available), caching the result. `download === null` means \"no network\n\t * source\" (offline / no client) → cache-only. 404 is negative-cached.\n\t */\n\tprivate async _objectUrlForKey(\n\t\tkey: string,\n\t\tfilename: string,\n\t\tdownload: (() => Promise<Blob>) | null,\n\t): Promise<string | null> {\n\t\t// Object URLs are only meaningful in browser environments.\n\t\tif (typeof window === \"undefined\") return null;\n\n\t\t// Reuse existing in-memory object URL if available\n\t\tconst existing = this.objectUrls.get(key);\n\t\tif (existing) return existing;\n\n\t\tlet db = await this.getDb();\n\t\tif (db) {\n\t\t\tlet entry: BlobCacheEntry | undefined;\n\t\t\ttry {\n\t\t\t\tconst tx = db.transaction(\"blobs\", \"readonly\");\n\t\t\t\tentry = await txPromise<BlobCacheEntry | undefined>(\n\t\t\t\t\ttx.objectStore(\"blobs\"),\n\t\t\t\t\ttx.objectStore(\"blobs\").get(key),\n\t\t\t\t);\n\t\t\t} catch (err: unknown) {\n\t\t\t\t// The cached connection was closed underneath us (space\n\t\t\t\t// teardown / destroy() racing this async read). Reopen once\n\t\t\t\t// and retry — the blob is still persisted in IDB.\n\t\t\t\tif ((err as { name?: string })?.name === \"InvalidStateError\") {\n\t\t\t\t\tif (this.db === db) this.db = null;\n\t\t\t\t\tthis.dbPromise = null;\n\t\t\t\t\tdb = await this.getDb();\n\t\t\t\t\tif (db) {\n\t\t\t\t\t\tconst tx = db.transaction(\"blobs\", \"readonly\");\n\t\t\t\t\t\tentry = await txPromise<BlobCacheEntry | undefined>(\n\t\t\t\t\t\t\ttx.objectStore(\"blobs\"),\n\t\t\t\t\t\t\ttx.objectStore(\"blobs\").get(key),\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tthrow err;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (entry) {\n\t\t\t\tconst url = URL.createObjectURL(entry.blob);\n\t\t\t\tthis.objectUrls.set(key, url);\n\t\t\t\treturn url;\n\t\t\t}\n\t\t}\n\n\t\t// Not cached — try downloading from server (requires a client)\n\t\tif (!download) return null;\n\n\t\t// Skip if we recently got a 404 for this key\n\t\tconst nfTime = this._notFound.get(key);\n\t\tif (nfTime && Date.now() - nfTime < FileBlobStore.NOT_FOUND_TTL) {\n\t\t\treturn null;\n\t\t}\n\n\t\tlet blob: Blob;\n\t\ttry {\n\t\t\tblob = await download();\n\t\t} catch (err: unknown) {\n\t\t\tconst status = (err as any)?.status;\n\t\t\tif (status === 404) {\n\t\t\t\tthis._notFound.set(key, Date.now());\n\t\t\t}\n\t\t\treturn null;\n\t\t}\n\n\t\t// Cache the blob\n\t\tif (db) {\n\t\t\tconst entry: BlobCacheEntry = {\n\t\t\t\tblob,\n\t\t\t\tmime_type: blob.type,\n\t\t\t\tfilename,\n\t\t\t\tcachedAt: Date.now(),\n\t\t\t};\n\t\t\tconst tx = db.transaction(\"blobs\", \"readwrite\");\n\t\t\ttx.objectStore(\"blobs\").put(entry, key);\n\t\t}\n\n\t\tconst url = URL.createObjectURL(blob);\n\t\tthis.objectUrls.set(key, url);\n\t\treturn url;\n\t}\n\n\t/**\n\t * Store a blob directly into the cache under the given (docId, uploadId) key\n\t * and return its object URL. Use this to pre-populate the cache for files\n\t * that haven't been uploaded to the server yet (e.g. offline upload queue).\n\t */\n\tasync putBlob(\n\t\tdocId: string,\n\t\tuploadId: string,\n\t\tblob: Blob,\n\t\tfilename: string,\n\t): Promise<string> {\n\t\tif (typeof window === \"undefined\") return URL.createObjectURL(blob);\n\n\t\tconst key = this.blobKey(docId, uploadId);\n\t\tthis._notFound.delete(key);\n\n\t\t// Return existing URL if already cached in-memory\n\t\tconst existing = this.objectUrls.get(key);\n\t\tif (existing) return existing;\n\n\t\tconst db = await this.getDb();\n\t\tif (db) {\n\t\t\tconst entry: BlobCacheEntry = {\n\t\t\t\tblob,\n\t\t\t\tmime_type: blob.type || \"application/octet-stream\",\n\t\t\t\tfilename,\n\t\t\t\tcachedAt: Date.now(),\n\t\t\t};\n\t\t\tconst tx = db.transaction(\"blobs\", \"readwrite\");\n\t\t\ttx.objectStore(\"blobs\").put(entry, key);\n\t\t}\n\n\t\tconst url = URL.createObjectURL(blob);\n\t\tthis.objectUrls.set(key, url);\n\t\treturn url;\n\t}\n\n\t/**\n\t * Retrieve the raw Blob from IDB for a previously cached upload.\n\t * Returns null if the blob has been evicted or was never stored.\n\t * Use this to re-upload a file after a page reload.\n\t */\n\tasync getBlob(docId: string, uploadId: string): Promise<Blob | null> {\n\t\tconst db = await this.getDb();\n\t\tif (!db) return null;\n\n\t\tconst key = this.blobKey(docId, uploadId);\n\t\tconst tx = db.transaction(\"blobs\", \"readonly\");\n\t\tconst entry = await txPromise<BlobCacheEntry | undefined>(\n\t\t\ttx.objectStore(\"blobs\"),\n\t\t\ttx.objectStore(\"blobs\").get(key),\n\t\t);\n\t\treturn entry?.blob ?? null;\n\t}\n\n\t/** Return metadata for all cached blobs (for storage stats). */\n\tasync getAllCachedEntries(): Promise<Array<{\n\t\tdocId: string; uploadId: string; filename: string;\n\t\tmimeType: string; size: number; cachedAt: number;\n\t}>> {\n\t\tconst db = await this.getDb();\n\t\tif (!db) return [];\n\t\treturn new Promise((resolve, reject) => {\n\t\t\tconst tx = db.transaction(\"blobs\", \"readonly\");\n\t\t\tconst store = tx.objectStore(\"blobs\");\n\t\t\tconst keysReq = store.getAllKeys();\n\t\t\tconst valuesReq = store.getAll();\n\t\t\ttx.oncomplete = () => {\n\t\t\t\tconst keys = keysReq.result as string[];\n\t\t\t\tconst values = valuesReq.result as BlobCacheEntry[];\n\t\t\t\tresolve(keys.map((key, i) => {\n\t\t\t\t\tconst slashIdx = key.indexOf(\"/\");\n\t\t\t\t\tconst docId = key.slice(0, slashIdx);\n\t\t\t\t\tconst uploadId = key.slice(slashIdx + 1);\n\t\t\t\t\tconst e = values[i]!;\n\t\t\t\t\treturn { docId, uploadId, filename: e.filename, mimeType: e.mime_type, size: e.blob.size, cachedAt: e.cachedAt };\n\t\t\t\t}));\n\t\t\t};\n\t\t\ttx.onerror = () => reject(tx.error);\n\t\t});\n\t}\n\n\t/** Revoke all object URLs and clear the entire blob cache from IDB. */\n\tasync clearAllBlobs(): Promise<void> {\n\t\tfor (const url of this.objectUrls.values()) URL.revokeObjectURL(url);\n\t\tthis.objectUrls.clear();\n\t\tconst db = await this.getDb();\n\t\tif (!db) return;\n\t\treturn new Promise((resolve, reject) => {\n\t\t\tconst tx = db.transaction(\"blobs\", \"readwrite\");\n\t\t\tconst req = tx.objectStore(\"blobs\").clear();\n\t\t\treq.onsuccess = () => resolve();\n\t\t\treq.onerror = () => reject(req.error);\n\t\t});\n\t}\n\n\t/**\n\t * Revoke the in-memory object URL without touching the IDB cache.\n\t * The next call to getBlobUrl() will re-create a fresh URL from IDB.\n\t * Use this when an <img> @error fires — the blob data is fine, only\n\t * the object URL reference is stale.\n\t */\n\tinvalidateUrl(docId: string, uploadId: string): void {\n\t\tconst key = this.blobKey(docId, uploadId);\n\t\tconst url = this.objectUrls.get(key);\n\t\tif (url) {\n\t\t\tURL.revokeObjectURL(url);\n\t\t\tthis.objectUrls.delete(key);\n\t\t}\n\t}\n\n\t/**\n\t * Thumbnail counterpart of {@link invalidateUrl}: revoke the in-memory\n\t * object URL for a specific thumbnail spec without touching its IDB cache.\n\t */\n\tinvalidateThumbUrl(docId: string, uploadId: string, opts: ThumbnailOptions = {}): void {\n\t\tconst key = this.thumbKey(docId, uploadId, opts);\n\t\tconst url = this.objectUrls.get(key);\n\t\tif (url) {\n\t\t\tURL.revokeObjectURL(url);\n\t\t\tthis.objectUrls.delete(key);\n\t\t}\n\t}\n\n\t/**\n\t * Clear the 404 negative-cache entry for (docId, uploadId) so the next\n\t * getBlobUrl() re-fetches from the server instead of short-circuiting.\n\t * Use on explicit user retry or after reconnect, when the file may have\n\t * become available since the last 404.\n\t */\n\tclearNotFound(docId: string, uploadId: string): void {\n\t\tthis._notFound.delete(this.blobKey(docId, uploadId));\n\t}\n\n\t/** Revoke the object URL and remove the blob from cache. */\n\tasync evictBlob(docId: string, uploadId: string): Promise<void> {\n\t\tconst key = this.blobKey(docId, uploadId);\n\n\t\tconst url = this.objectUrls.get(key);\n\t\tif (url) {\n\t\t\tURL.revokeObjectURL(url);\n\t\t\tthis.objectUrls.delete(key);\n\t\t}\n\n\t\tconst db = await this.getDb();\n\t\tif (!db) return;\n\t\tconst tx = db.transaction(\"blobs\", \"readwrite\");\n\t\tawait txPromise(tx.objectStore(\"blobs\"), tx.objectStore(\"blobs\").delete(key));\n\t}\n\n\t// ── Upload queue ──────────────────────────────────────────────────────────\n\n\t/**\n\t * Queue a file for upload. Works offline — the entry is persisted to IDB\n\t * and flushed the next time the queue is flushed.\n\t * Returns the generated queue entry id.\n\t */\n\tasync queueUpload(\n\t\tdocId: string,\n\t\tfile: File | Blob,\n\t\tfilename?: string,\n\t): Promise<string> {\n\t\tconst id = crypto.randomUUID();\n\t\tconst resolvedFilename =\n\t\t\tfile instanceof File ? file.name : (filename ?? \"file\");\n\n\t\tconst entry: UploadQueueEntry = {\n\t\t\tid,\n\t\t\tdocId,\n\t\t\tfile,\n\t\t\tfilename: resolvedFilename,\n\t\t\tstatus: \"pending\",\n\t\t\tcreatedAt: Date.now(),\n\t\t};\n\n\t\tconst db = await this.getDb();\n\t\tif (db) {\n\t\t\tconst tx = db.transaction(\"upload_queue\", \"readwrite\");\n\t\t\tawait txPromise(\n\t\t\t\ttx.objectStore(\"upload_queue\"),\n\t\t\t\ttx.objectStore(\"upload_queue\").put(entry),\n\t\t\t);\n\t\t}\n\n\t\tthis.emit(\"upload:queued\", entry);\n\t\treturn id;\n\t}\n\n\t/** Return all upload queue entries. */\n\tasync getQueue(): Promise<UploadQueueEntry[]> {\n\t\tconst db = await this.getDb();\n\t\tif (!db) return [];\n\t\treturn new Promise((resolve, reject) => {\n\t\t\tconst tx = db.transaction(\"upload_queue\", \"readonly\");\n\t\t\tconst req = tx.objectStore(\"upload_queue\").getAll();\n\t\t\treq.onsuccess = () => resolve(req.result as UploadQueueEntry[]);\n\t\t\treq.onerror = () => reject(req.error);\n\t\t});\n\t}\n\n\t/**\n\t * Upload all pending queue entries via AbracadabraClient.\n\t * Safe to call repeatedly — a concurrent call is a no-op.\n\t * Entries that fail are marked with status \"error\" and left in the queue.\n\t */\n\tasync flushQueue(): Promise<void> {\n\t\tif (this._flushPromise || !this.client) return;\n\t\tthis._flushPromise = this._doFlush();\n\t\ttry {\n\t\t\tawait this._flushPromise;\n\t\t} finally {\n\t\t\tthis._flushPromise = null;\n\t\t}\n\t}\n\n\tprivate async _doFlush(): Promise<void> {\n\t\tif (!this.client) return;\n\t\tconst all = await this.getQueue();\n\t\tconst pending = all.filter((e) => e.status === \"pending\");\n\n\t\tfor (const entry of pending) {\n\t\t\tawait this._updateQueueEntry(entry.id, { status: \"uploading\" });\n\t\t\tthis.emit(\"upload:started\", { ...entry, status: \"uploading\" });\n\n\t\t\ttry {\n\t\t\t\tawait this.client.upload(entry.docId, entry.file, entry.filename);\n\t\t\t\tawait this._updateQueueEntry(entry.id, { status: \"done\" });\n\t\t\t\tthis.emit(\"upload:done\", { ...entry, status: \"done\" });\n\t\t\t} catch (err) {\n\t\t\t\tconst message = err instanceof Error ? err.message : String(err);\n\t\t\t\tawait this._updateQueueEntry(entry.id, { status: \"error\", error: message });\n\t\t\t\tthis.emit(\"upload:error\", { ...entry, status: \"error\", error: message });\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate async _updateQueueEntry(\n\t\tid: string,\n\t\tpatch: Partial<UploadQueueEntry>,\n\t): Promise<void> {\n\t\tconst db = await this.getDb();\n\t\tif (!db) return;\n\n\t\treturn new Promise<void>((resolve, reject) => {\n\t\t\tconst tx = db.transaction(\"upload_queue\", \"readwrite\");\n\t\t\tconst store = tx.objectStore(\"upload_queue\");\n\t\t\tconst req = store.get(id);\n\t\t\treq.onsuccess = () => {\n\t\t\t\tif (!req.result) { resolve(); return; }\n\t\t\t\tconst updated = { ...req.result, ...patch };\n\t\t\t\tstore.put(updated);\n\t\t\t\ttx.oncomplete = () => resolve();\n\t\t\t\ttx.onerror = () => reject(tx.error);\n\t\t\t};\n\t\t\treq.onerror = () => reject(req.error);\n\t\t});\n\t}\n\n\t// ── Lifecycle ─────────────────────────────────────────────────────────────\n\n\tdestroy(): void {\n\t\tif (typeof window !== \"undefined\") {\n\t\t\twindow.removeEventListener(\"online\", this._onlineHandler);\n\t\t}\n\n\t\t// Revoke all tracked object URLs\n\t\tfor (const url of this.objectUrls.values()) {\n\t\t\tURL.revokeObjectURL(url);\n\t\t}\n\t\tthis.objectUrls.clear();\n\n\t\tthis.db?.close();\n\t\tthis.db = null;\n\t\t// Drop the cached promise too — otherwise a still-mounted FileNodeView\n\t\t// that calls getBlobUrl() after teardown gets the just-closed handle\n\t\t// and throws InvalidStateError. Nulling it lets getDb() reopen a fresh\n\t\t// connection to read the (still-persisted) cached blob.\n\t\tthis.dbPromise = null;\n\t\tthis.removeAllListeners();\n\t}\n}\n","/**\n * DocKeyManager\n *\n * Manages AES-256-GCM document keys for CSE and E2E encrypted documents.\n * Keys are wrapped per-user using X25519 ECDH + HKDF-SHA256 + AES-256-GCM.\n */\n\nimport { x25519 } from \"@noble/curves/ed25519.js\";\nimport { hkdf } from \"@noble/hashes/hkdf.js\";\nimport { sha256 } from \"@noble/hashes/sha2.js\";\nimport type { AbracadabraClient } from \"./AbracadabraClient.ts\";\nimport type { CryptoIdentityKeystore } from \"./CryptoIdentityKeystore.ts\";\n\nconst HKDF_INFO = new TextEncoder().encode(\"abracadabra-dockey-v1\");\n\nfunction fromBase64(b64: string): Uint8Array {\n\t// Accept both standard base64 and base64url, padded or not — server\n\t// payloads mix the two alphabets depending on the field.\n\tlet normalized = b64.replace(/-/g, \"+\").replace(/_/g, \"/\");\n\tconst pad = normalized.length % 4;\n\tif (pad) normalized += \"=\".repeat(4 - pad);\n\treturn Uint8Array.from(atob(normalized), (c) => c.charCodeAt(0));\n}\n\nexport class DocKeyManager {\n\tprivate cache = new Map<string, { key: CryptoKey; epoch: number; fetchedAt: number }>();\n\tprivate static readonly CACHE_TTL = 10 * 60 * 1000; // 10 minutes\n\n\t/** Generate a new random AES-256-GCM document key. */\n\tstatic async generateDocKey(): Promise<CryptoKey> {\n\t\treturn crypto.subtle.generateKey(\n\t\t\t{ name: \"AES-GCM\", length: 256 },\n\t\t\ttrue,\n\t\t\t[\"encrypt\", \"decrypt\"],\n\t\t);\n\t}\n\n\t/**\n\t * Get (or fetch) the DocKey for a document.\n\t * Returns null if no envelope exists (user not provisioned).\n\t */\n\tasync getDocKey(\n\t\tdocId: string,\n\t\tclient: AbracadabraClient,\n\t\tkeystore: CryptoIdentityKeystore,\n\t): Promise<CryptoKey | null> {\n\t\tconst cached = this.cache.get(docId);\n\t\tif (cached && Date.now() - cached.fetchedAt < DocKeyManager.CACHE_TTL) {\n\t\t\treturn cached.key;\n\t\t}\n\n\t\tconst envelope = await client.getMyKeyEnvelope(docId);\n\t\tif (envelope) {\n\t\t\tconst x25519PrivKey = await keystore.getX25519PrivateKey();\n\t\t\ttry {\n\t\t\t\tconst wrapped = fromBase64(envelope.encrypted_key);\n\t\t\t\tconst docKey = await this._unwrapKey(wrapped, x25519PrivKey, docId);\n\t\t\t\tthis.cache.set(docId, { key: docKey, epoch: envelope.key_epoch, fetchedAt: Date.now() });\n\t\t\t\treturn docKey;\n\t\t\t} finally {\n\t\t\t\tx25519PrivKey.fill(0);\n\t\t\t}\n\t\t}\n\n\t\t// Inheritance fallback. The doc has no envelope of our own — but it\n\t\t// might inherit its encryption mode from an ancestor (e.g. a child\n\t\t// page under an E2E space). The ancestor IS provisioned for us\n\t\t// (otherwise we couldn't open the parent either). Resolve the\n\t\t// encryption-source via /docs/:id/encryption.inherited_from, fetch\n\t\t// OUR envelope on that source, unwrap with the source's salt,\n\t\t// re-wrap for the current docId with its own salt, upload the new\n\t\t// envelope so subsequent calls hit the direct-envelope path.\n\t\ttry {\n\t\t\tconst enc = await client.getDocEncryption(docId);\n\t\t\tif (enc.effective_mode !== \"e2e\" || !enc.inherited_from || enc.inherited_from === docId) {\n\t\t\t\treturn null;\n\t\t\t}\n\t\t\tconst sourceEnv = await client.getMyKeyEnvelope(enc.inherited_from);\n\t\t\tif (!sourceEnv) return null;\n\t\t\tconst x25519PrivKey = await keystore.getX25519PrivateKey();\n\t\t\ttry {\n\t\t\t\tconst wrappedSrc = fromBase64(sourceEnv.encrypted_key);\n\t\t\t\tconst docKey = await this._unwrapKey(wrappedSrc, x25519PrivKey, enc.inherited_from);\n\t\t\t\tthis.cache.set(docId, { key: docKey, epoch: sourceEnv.key_epoch, fetchedAt: Date.now() });\n\t\t\t\t// Re-wrap for the current doc + upload so future opens take\n\t\t\t\t// the direct path. Best-effort — caller already has the key.\n\t\t\t\tconst me = await client.getMe();\n\t\t\t\tif (me.publicKey) {\n\t\t\t\t\tconst myKeys = await client.listUserKeys(me.id);\n\t\t\t\t\tconst primaryKey = myKeys[0];\n\t\t\t\t\tif (primaryKey?.x25519Key) {\n\t\t\t\t\t\tconst x25519Pub = fromBase64(primaryKey.x25519Key);\n\t\t\t\t\t\tconst rewrapped = await this.wrapKeyForRecipient(docKey, x25519Pub, docId);\n\t\t\t\t\t\tconst b64 = (() => {\n\t\t\t\t\t\t\tlet s = \"\";\n\t\t\t\t\t\t\tfor (let i = 0; i < rewrapped.length; i++) s += String.fromCharCode(rewrapped[i]!);\n\t\t\t\t\t\t\treturn btoa(s);\n\t\t\t\t\t\t})();\n\t\t\t\t\t\tawait client.uploadKeyEnvelopes(docId, {\n\t\t\t\t\t\t\tkey_epoch: sourceEnv.key_epoch,\n\t\t\t\t\t\t\tenvelopes: [{ recipient_key_id: primaryKey.id, encrypted_key: b64 }],\n\t\t\t\t\t\t}).catch(() => null);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn docKey;\n\t\t\t} finally {\n\t\t\t\tx25519PrivKey.fill(0);\n\t\t\t}\n\t\t} catch {\n\t\t\treturn null;\n\t\t}\n\t}\n\n\t/**\n\t * Wrap a DocKey for a recipient.\n\t * Output: [ephemeralPub(32) || nonce(12) || ciphertext(~48)] bytes\n\t */\n\tasync wrapKeyForRecipient(\n\t\tdocKey: CryptoKey,\n\t\trecipientX25519PubKey: Uint8Array,\n\t\tdocId: string,\n\t): Promise<Uint8Array> {\n\t\tconst ephemeralPriv = crypto.getRandomValues(new Uint8Array(32));\n\t\tconst ephemeralPub = x25519.getPublicKey(ephemeralPriv);\n\t\tconst sharedSecret = x25519.getSharedSecret(ephemeralPriv, recipientX25519PubKey);\n\n\t\tconst salt = new TextEncoder().encode(docId);\n\t\tconst keyBytes = hkdf(sha256, sharedSecret, salt, HKDF_INFO, 32);\n\t\tconst wrapKey = await crypto.subtle.importKey(\"raw\", keyBytes as BufferSource, { name: \"AES-GCM\" }, false, [\"encrypt\"]);\n\n\t\tconst rawDocKey = await crypto.subtle.exportKey(\"raw\", docKey);\n\t\tconst nonce = crypto.getRandomValues(new Uint8Array(12));\n\t\tconst ciphertext = new Uint8Array(await crypto.subtle.encrypt({ name: \"AES-GCM\", iv: nonce as BufferSource }, wrapKey, rawDocKey));\n\n\t\tconst result = new Uint8Array(32 + 12 + ciphertext.length);\n\t\tresult.set(ephemeralPub, 0);\n\t\tresult.set(nonce, 32);\n\t\tresult.set(ciphertext, 44);\n\t\treturn result;\n\t}\n\n\tprivate async _unwrapKey(wrapped: Uint8Array, recipientX25519PrivKey: Uint8Array, docId: string): Promise<CryptoKey> {\n\t\tconst ephemeralPub = wrapped.slice(0, 32);\n\t\tconst nonce = wrapped.slice(32, 44);\n\t\tconst ciphertext = wrapped.slice(44);\n\n\t\tconst sharedSecret = x25519.getSharedSecret(recipientX25519PrivKey, ephemeralPub);\n\t\tconst salt = new TextEncoder().encode(docId);\n\t\tconst keyBytes = hkdf(sha256, sharedSecret, salt, HKDF_INFO, 32);\n\t\tconst wrapKey = await crypto.subtle.importKey(\"raw\", keyBytes as BufferSource, { name: \"AES-GCM\" }, false, [\"decrypt\"]);\n\t\tconst rawDocKey = await crypto.subtle.decrypt({ name: \"AES-GCM\", iv: nonce as BufferSource }, wrapKey, ciphertext as BufferSource);\n\t\treturn crypto.subtle.importKey(\"raw\", rawDocKey, { name: \"AES-GCM\" }, true, [\"encrypt\", \"decrypt\"]);\n\t}\n\n\t/** Clear the cached key for a document (or all if docId omitted). */\n\tclearCache(docId?: string): void {\n\t\tif (docId) {\n\t\t\tthis.cache.delete(docId);\n\t\t} else {\n\t\t\tthis.cache.clear();\n\t\t}\n\t}\n}\n","/**\n * EncryptedY - CSE (Client-Side Encryption) primitives for Yjs documents.\n *\n * Wire format for encrypted fields: [nonce(12) || AES-GCM ciphertext]\n *\n * Limitations (documented):\n * - Concurrent writes to the same Y.Map key produce last-write-wins semantics\n * (not character-level CRDT merge), because encrypted values are opaque to Yrs.\n */\n\nimport * as Y from \"yjs\";\n\n// ── Field-level encryption ─────────────────────────────────────────────────────\n\n/** Encrypt a field value with AES-256-GCM. Returns [nonce(12) || ciphertext]. */\nexport async function encryptField(value: Uint8Array, docKey: CryptoKey): Promise<Uint8Array> {\n\tconst nonce = crypto.getRandomValues(new Uint8Array(12));\n\tconst ciphertext = new Uint8Array(\n\t\tawait crypto.subtle.encrypt({ name: \"AES-GCM\", iv: nonce as BufferSource }, docKey, value as BufferSource),\n\t);\n\tconst result = new Uint8Array(12 + ciphertext.length);\n\tresult.set(nonce, 0);\n\tresult.set(ciphertext, 12);\n\treturn result;\n}\n\n/** Decrypt a field value from [nonce(12) || ciphertext] format. */\nexport async function decryptField(ciphertext: Uint8Array, docKey: CryptoKey): Promise<Uint8Array> {\n\tconst nonce = ciphertext.slice(0, 12);\n\tconst ct = ciphertext.slice(12);\n\treturn new Uint8Array(await crypto.subtle.decrypt({ name: \"AES-GCM\", iv: nonce as BufferSource }, docKey, ct as BufferSource));\n}\n\n// ── EncryptedYMap ─────────────────────────────────────────────────────────────\n\n/**\n * A proxy wrapper around a Y.Map<Uint8Array> that transparently encrypts\n * values on .set() and decrypts on .get().\n *\n * NOTE: Concurrent writes to the same key produce last-write-wins (LWW)\n * because encrypted values are opaque blobs from Yrs's perspective.\n */\nexport class EncryptedYMap {\n\tconstructor(\n\t\tprivate readonly ymap: Y.Map<Uint8Array>,\n\t\tprivate readonly docKey: CryptoKey,\n\t) {}\n\n\tasync set(key: string, value: Uint8Array): Promise<void> {\n\t\tconst encrypted = await encryptField(value, this.docKey);\n\t\tthis.ymap.set(key, encrypted);\n\t}\n\n\tasync get(key: string): Promise<Uint8Array | null> {\n\t\tconst encrypted = this.ymap.get(key);\n\t\tif (!encrypted) return null;\n\t\ttry {\n\t\t\treturn await decryptField(encrypted, this.docKey);\n\t\t} catch {\n\t\t\treturn null; // Decryption failed (wrong key or corrupted)\n\t\t}\n\t}\n\n\thas(key: string): boolean {\n\t\treturn this.ymap.has(key);\n\t}\n\n\tdelete(key: string): void {\n\t\tthis.ymap.delete(key);\n\t}\n\n\tget size(): number {\n\t\treturn this.ymap.size;\n\t}\n\n\t/** Get all keys (encrypted values remain opaque until .get() is called). */\n\tkeys(): string[] {\n\t\treturn Array.from(this.ymap.keys());\n\t}\n\n\t/** Observe changes on the underlying Y.Map. */\n\tobserve(f: (event: Y.YMapEvent<Uint8Array>) => void): void {\n\t\tthis.ymap.observe(f);\n\t}\n\n\tunobserve(f: (event: Y.YMapEvent<Uint8Array>) => void): void {\n\t\tthis.ymap.unobserve(f);\n\t}\n}\n\n/** Create an EncryptedYMap wrapping a Y.Map<Uint8Array>. */\nexport function makeEncryptedYMap(ymap: Y.Map<Uint8Array>, docKey: CryptoKey): EncryptedYMap {\n\treturn new EncryptedYMap(ymap, docKey);\n}\n\n// ── EncryptedYText ────────────────────────────────────────────────────────────\n\n/**\n * Stores full text as a single encrypted blob in a Y.Map<Uint8Array> under a\n * fixed field name. This is last-write-wins for the entire text field.\n *\n * NOTE: This does NOT preserve character-level CRDT merge for concurrent edits.\n * It trades CRDT merge for confidentiality.\n */\nexport class EncryptedYText {\n\tprivate readonly ymap: Y.Map<Uint8Array>;\n\n\tconstructor(\n\t\tydoc: Y.Doc,\n\t\tfieldName: string,\n\t\tprivate readonly docKey: CryptoKey,\n\t) {\n\t\tthis.ymap = ydoc.getMap(`_encrypted_${fieldName}`);\n\t}\n\n\tasync set(text: string): Promise<void> {\n\t\tconst encoded = new TextEncoder().encode(text);\n\t\tconst encrypted = await encryptField(encoded, this.docKey);\n\t\tthis.ymap.set(\"v\", encrypted);\n\t}\n\n\tasync get(): Promise<string | null> {\n\t\tconst encrypted = this.ymap.get(\"v\");\n\t\tif (!encrypted) return null;\n\t\ttry {\n\t\t\tconst decoded = await decryptField(encrypted, this.docKey);\n\t\t\treturn new TextDecoder().decode(decoded);\n\t\t} catch {\n\t\t\treturn null;\n\t\t}\n\t}\n\n\tobserve(f: (event: Y.YMapEvent<Uint8Array>) => void): void {\n\t\tthis.ymap.observe(f);\n\t}\n\n\tunobserve(f: (event: Y.YMapEvent<Uint8Array>) => void): void {\n\t\tthis.ymap.unobserve(f);\n\t}\n}\n\n/** Create an EncryptedYText for a field in a Y.Doc. */\nexport function makeEncryptedYText(ydoc: Y.Doc, fieldName: string, docKey: CryptoKey): EncryptedYText {\n\treturn new EncryptedYText(ydoc, fieldName, docKey);\n}\n","/**\n * E2EOfflineStore\n *\n * Extends OfflineStore with transparent AES-GCM encryption of the document\n * snapshot, ensuring that even if the device is compromised, the local\n * IndexedDB data cannot be read without the doc key.\n *\n * Only the snapshot is encrypted (not the meta store entries, which contain\n * non-sensitive data like sequence numbers).\n *\n * Key availability limitation: if the user's WebAuthn key is not in\n * DocKeyManager's in-memory cache and there is no network, E2E docs show\n * empty — this is expected Phase 2 behavior.\n */\n\nimport { OfflineStore } from \"./OfflineStore.ts\";\nimport { encryptField, decryptField } from \"./EncryptedY.ts\";\n\nexport class E2EOfflineStore extends OfflineStore {\n\tprivate readonly docKey: CryptoKey;\n\n\t/**\n\t * @param docId The document UUID.\n\t * @param serverOrigin Hostname of the server (namespaces the IDB key).\n\t * @param docKey AES-GCM CryptoKey used to encrypt/decrypt the snapshot.\n\t */\n\tconstructor(docId: string, serverOrigin: string | undefined, docKey: CryptoKey) {\n\t\tsuper(docId, serverOrigin);\n\t\tthis.docKey = docKey;\n\t}\n\n\t/**\n\t * Encrypt the snapshot before storing it.\n\t */\n\toverride async saveDocSnapshot(snapshot: Uint8Array): Promise<void> {\n\t\tconst encrypted = await encryptField(snapshot, this.docKey);\n\t\tawait super.saveDocSnapshot(encrypted);\n\t}\n\n\t/**\n\t * Decrypt the snapshot after loading it.\n\t * Returns null if decryption fails (e.g. key mismatch or corrupt data).\n\t */\n\toverride async getDocSnapshot(): Promise<Uint8Array | null> {\n\t\tconst encrypted = await super.getDocSnapshot();\n\t\tif (!encrypted) return null;\n\t\ttry {\n\t\t\treturn await decryptField(encrypted, this.docKey);\n\t\t} catch {\n\t\t\t// Key mismatch or tampered data — return null so the provider falls\n\t\t\t// back to fetching from the server.\n\t\t\treturn null;\n\t\t}\n\t}\n}\n","/**\n * E2EAbracadabraProvider\n *\n * Extends AbracadabraProvider with full E2E encryption support.\n *\n * Differences from standard provider:\n * - startSync() sends a stateless e2e_sync_request instead of SYNC_STEP1\n * - On receiving e2e_ready, fetches all blobs via REST, decrypts, applies to Y.Doc\n * - Local updates are AES-GCM encrypted before sending over WebSocket\n * - Incoming e2e_update stateless messages are decrypted and applied\n *\n * Phase 2 offline support:\n * - After the doc key is obtained, an E2EOfflineStore is created for this doc.\n * - The stored encrypted snapshot is applied before fetching server updates.\n * - The last-seen sequence number (e2e_seq) is persisted so only delta updates\n * are fetched on subsequent connects.\n * - After sync, a fresh encrypted snapshot is saved.\n *\n * Client-side compaction:\n * - After `compactionThreshold` encrypted updates have been applied in this\n * session (local + remote), and the doc has been quiescent for\n * `compactionQuiescenceMs`, the provider merges the whole Y.Doc, encrypts it,\n * and sends `snapshot:compact` — the server atomically replaces the per-doc\n * update log with that single compacted blob. The server acknowledges by\n * broadcasting `snapshot:compacted`, which emits the `\"compacted\"` event.\n * - Requires Owner or above (server silently drops non-Owner requests).\n * - Callers that want a final compaction before teardown should\n * `await provider.compactNow()` before `destroy()`. `destroy()` does not\n * compact (it'd race with the socket teardown) — any pending debounce is\n * cancelled.\n *\n * Key availability limitation: if the user's WebAuthn key is not in\n * DocKeyManager's in-memory cache and there is no network, E2E docs show\n * empty — the key fetch requires either a cached in-memory key or network.\n */\n\nimport * as Y from \"yjs\";\nimport { AbracadabraProvider } from \"./AbracadabraProvider.ts\";\nimport type { AbracadabraProviderConfiguration } from \"./AbracadabraProvider.ts\";\nimport type { DocKeyManager } from \"./DocKeyManager.ts\";\nimport type { CryptoIdentityKeystore } from \"./CryptoIdentityKeystore.ts\";\nimport type { AbracadabraClient } from \"./AbracadabraClient.ts\";\nimport { UpdateMessage } from \"./OutgoingMessages/UpdateMessage.ts\";\nimport { encryptField, decryptField } from \"./EncryptedY.ts\";\nimport { E2EOfflineStore } from \"./E2EOfflineStore.ts\";\nimport type { onCompactedParameters } from \"./types.ts\";\n\nfunction fromBase64(b64: string): Uint8Array {\n\treturn Uint8Array.from(atob(b64), (c) => c.charCodeAt(0));\n}\n\nfunction toBase64(bytes: Uint8Array): string {\n\tlet bin = \"\";\n\tfor (let i = 0; i < bytes.length; i += 0x8000) {\n\t\tbin += String.fromCharCode(...bytes.subarray(i, i + 0x8000));\n\t}\n\treturn btoa(bin);\n}\n\nexport interface E2EAbracadabraProviderConfiguration extends AbracadabraProviderConfiguration {\n\tdocKeyManager: DocKeyManager;\n\tkeystore: CryptoIdentityKeystore;\n\tclient: AbracadabraClient;\n\t/**\n\t * Enable client-side compaction: after `compactionThreshold` E2E updates,\n\t * the provider merges the whole doc, re-encrypts it, and asks the server to\n\t * atomically replace its update log via the `snapshot:compact` stateless\n\t * protocol. Requires the user to have a role that `can_manage` the doc\n\t * (Owner or above); otherwise the server silently rejects.\n\t *\n\t * Default: true.\n\t */\n\tcompactionEnabled?: boolean;\n\t/**\n\t * Number of E2E updates applied in this session before compaction fires.\n\t * Default: 50. Ignored when `compactionEnabled === false`.\n\t */\n\tcompactionThreshold?: number;\n\t/**\n\t * Quiescence delay: once the threshold is crossed, wait this many ms with\n\t * no further updates before firing compaction. Debounces active editing\n\t * and reduces the chance of racing an in-flight remote update that hasn't\n\t * reached us yet (the server does not currently validate state-vector\n\t * coverage, so a compaction fired mid-flight could drop an update).\n\t *\n\t * Default: 2000 ms.\n\t */\n\tcompactionQuiescenceMs?: number;\n}\n\nexport class E2EAbracadabraProvider extends AbracadabraProvider {\n\tprivate readonly docKeyManager: DocKeyManager;\n\tprivate readonly keystore: CryptoIdentityKeystore;\n\tprivate readonly e2eClient: AbracadabraClient;\n\tprivate docKey: CryptoKey | null = null;\n\tprivate lastSeq = -1;\n\n\t/** E2E-encrypted offline store; created after the doc key is available. */\n\tprivate e2eStore: E2EOfflineStore | null = null;\n\tprivate readonly e2eServerOrigin: string | undefined;\n\n\t// ── Client-side compaction ────────────────────────────────────────────────\n\tprivate readonly compactionEnabled: boolean;\n\tprivate readonly compactionThreshold: number;\n\tprivate readonly compactionQuiescenceMs: number;\n\tprivate updatesSinceCompaction = 0;\n\tprivate compactionInFlight = false;\n\t/** Cleared on `snapshot:compacted` or on 30s timeout. */\n\tprivate compactionInFlightTimeout: ReturnType<typeof setTimeout> | null = null;\n\t/** Quiescence debounce: reset on every update, fires the actual compaction. */\n\tprivate compactionDebounceTimer: ReturnType<typeof setTimeout> | null = null;\n\tprivate destroyed = false;\n\t/**\n\t * Plaintext local updates produced while this doc is not yet authenticated\n\t * on the connection. Unlike the plaintext provider, E2E does not convey\n\t * local state via SyncStep2 (it ships discrete encrypted update frames keyed\n\t * by server-assigned seq), so a pre-auth update that loses the AUTH race and\n\t * gets \"not subscribed\"-rejected would be lost. We queue them here and flush\n\t * (encrypt + send) once `authenticatedHandler` confirms the doc is\n\t * subscribed. Survives reconnects (only cleared on flush or destroy).\n\t */\n\tprivate _pendingPreAuthUpdates: Uint8Array[] = [];\n\n\tconstructor(configuration: E2EAbracadabraProviderConfiguration) {\n\t\t// Disable the parent's offline store — E2E uses its own encrypted store.\n\t\tsuper({ ...configuration, disableOfflineStore: true });\n\t\tthis.docKeyManager = configuration.docKeyManager;\n\t\tthis.keystore = configuration.keystore;\n\t\tthis.e2eClient = configuration.client;\n\n\t\tthis.compactionEnabled = configuration.compactionEnabled !== false;\n\t\tthis.compactionThreshold = Math.max(1, configuration.compactionThreshold ?? 50);\n\t\tthis.compactionQuiescenceMs = Math.max(0, configuration.compactionQuiescenceMs ?? 2000);\n\n\t\t// Derive server origin for E2EOfflineStore namespacing\n\t\tthis.e2eServerOrigin = E2EAbracadabraProvider.deriveServerOrigin(\n\t\t\tconfiguration,\n\t\t\tconfiguration.client,\n\t\t);\n\t}\n\n\t/** Fetch the doc key from the server (requires WebAuthn if not cached). */\n\tprivate async ensureDocKey(): Promise<CryptoKey | null> {\n\t\tif (this.docKey) return this.docKey;\n\t\tthis.docKey = await this.docKeyManager.getDocKey(\n\t\t\tthis.configuration.name,\n\t\t\tthis.e2eClient,\n\t\t\tthis.keystore,\n\t\t);\n\n\t\t// Create the encrypted offline store now that we have the key\n\t\tif (this.docKey && !this.e2eStore) {\n\t\t\tthis.e2eStore = new E2EOfflineStore(\n\t\t\t\tthis.configuration.name,\n\t\t\t\tthis.e2eServerOrigin,\n\t\t\t\tthis.docKey,\n\t\t\t);\n\t\t}\n\n\t\treturn this.docKey;\n\t}\n\n\t/** Handle stateless messages including e2e_ready and e2e_update. */\n\toverride receiveStateless(payload: string): void {\n\t\t// `snapshot:compacted {\"doc_id\":\"...\",\"by\":\"...\"}` is a space-separated\n\t\t// stateless frame — not valid JSON as a whole — so handle it before the\n\t\t// JSON.parse fallthrough.\n\t\tif (payload.startsWith(\"snapshot:compacted \")) {\n\t\t\tthis._handleCompactedBroadcast(payload.slice(\"snapshot:compacted \".length));\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 { type?: string; seq?: number; data?: string; doc_id?: string };\n\n\t\tif (msg.type === \"e2e_ready\") {\n\t\t\t// Fetch all blobs and hydrate doc\n\t\t\tthis._fetchAndApplyAllBlobs().catch((e) => {\n\t\t\t\tconsole.error(\"[E2EAbracadabraProvider] failed to fetch e2e blobs:\", e);\n\t\t\t});\n\t\t\treturn;\n\t\t}\n\n\t\tif (msg.type === \"e2e_update\" && msg.data !== undefined && msg.seq !== undefined) {\n\t\t\tif (msg.seq <= this.lastSeq) return; // Already applied\n\t\t\tthis._decryptAndApply(fromBase64(msg.data), msg.seq).catch((e) => {\n\t\t\t\tconsole.error(\"[E2EAbracadabraProvider] failed to apply e2e_update:\", e);\n\t\t\t});\n\t\t\treturn;\n\t\t}\n\n\t\tsuper.receiveStateless(payload);\n\t}\n\n\tprivate async _fetchAndApplyAllBlobs(): Promise<void> {\n\t\tconst key = await this.ensureDocKey();\n\t\tif (!key) {\n\t\t\tconsole.warn(\"[E2EAbracadabraProvider] no doc key available, cannot decrypt blobs\");\n\t\t\tthis.synced = true;\n\t\t\treturn;\n\t\t}\n\n\t\t// Phase 2: load stored snapshot + lastSeq before fetching from server\n\t\tif (this.e2eStore) {\n\t\t\tconst storedSeqStr = await this.e2eStore.getMeta(\"e2e_seq\").catch(() => null);\n\t\t\tif (storedSeqStr !== null) {\n\t\t\t\tthis.lastSeq = parseInt(storedSeqStr, 10);\n\t\t\t}\n\n\t\t\tconst snapshot = await this.e2eStore.getDocSnapshot().catch(() => null);\n\t\t\tif (snapshot) {\n\t\t\t\tY.applyUpdate(this.document, snapshot, this.e2eStore);\n\t\t\t}\n\t\t}\n\n\t\t// Only fetch updates newer than lastSeq\n\t\tconst updates = await this.e2eClient.getE2EUpdatesSince(\n\t\t\tthis.configuration.name,\n\t\t\tthis.lastSeq,\n\t\t);\n\t\tfor (const { seq, data } of updates) {\n\t\t\tawait this._decryptAndApply(data, seq);\n\t\t}\n\n\t\tthis.synced = true;\n\n\t\t// Phase 2: persist updated snapshot and lastSeq\n\t\tif (this.e2eStore) {\n\t\t\tconst snapshot = Y.encodeStateAsUpdate(this.document);\n\t\t\tawait this.e2eStore.saveDocSnapshot(snapshot).catch(() => null);\n\t\t\tawait this.e2eStore.setMeta(\"e2e_seq\", String(this.lastSeq)).catch(() => null);\n\t\t}\n\t}\n\n\tprivate async _decryptAndApply(encryptedData: Uint8Array, seq: number): Promise<void> {\n\t\tconst key = await this.ensureDocKey();\n\t\tif (!key) return;\n\t\ttry {\n\t\t\tconst plaintext = await decryptField(encryptedData, key);\n\t\t\tY.applyUpdate(this.document, plaintext, this);\n\t\t\tthis.lastSeq = Math.max(this.lastSeq, seq);\n\t\t\tthis._noteUpdateApplied();\n\t\t} catch (e) {\n\t\t\tconsole.error(\"[E2EAbracadabraProvider] decryption failed for seq\", seq, e);\n\t\t}\n\t}\n\n\t/** Encrypt local updates before sending over WebSocket. */\n\toverride documentUpdateHandler(update: Uint8Array, origin: unknown): void {\n\t\tif (origin === this) return;\n\n\t\t// AUTH-ordering guard (see _pendingPreAuthUpdates): until the doc is\n\t\t// authenticated on the connection, an encrypted update would race ahead\n\t\t// of the AUTH frame on the shared multiplexed socket and be rejected with\n\t\t// \"not subscribed\". Queue it and flush on authenticatedHandler instead of\n\t\t// racing (and losing) it.\n\t\tif (!this.isAuthenticated) {\n\t\t\tthis._pendingPreAuthUpdates.push(update);\n\t\t\treturn;\n\t\t}\n\n\t\t// Don't call super (which would send plaintext); encrypt first\n\t\tthis._encryptAndSend(update).catch((e) => {\n\t\t\tconsole.error(\"[E2EAbracadabraProvider] failed to encrypt update:\", e);\n\t\t});\n\t}\n\n\t/**\n\t * Flush updates buffered while unauthenticated once the server confirms the\n\t * doc is subscribed, then resume normal live sends.\n\t */\n\toverride authenticatedHandler(scope: string): void {\n\t\tsuper.authenticatedHandler(scope);\n\t\tif (this._pendingPreAuthUpdates.length === 0) return;\n\t\tconst pending = this._pendingPreAuthUpdates;\n\t\tthis._pendingPreAuthUpdates = [];\n\t\tfor (const update of pending) {\n\t\t\tthis._encryptAndSend(update).catch((e) => {\n\t\t\t\tconsole.error(\"[E2EAbracadabraProvider] failed to flush pre-auth update:\", e);\n\t\t\t});\n\t\t}\n\t}\n\n\tprivate async _encryptAndSend(update: Uint8Array): Promise<void> {\n\t\tconst key = await this.ensureDocKey();\n\t\tif (!key) {\n\t\t\tconsole.warn(\"[E2EAbracadabraProvider] no doc key, dropping update\");\n\t\t\treturn;\n\t\t}\n\t\tconst encrypted = await encryptField(update, key);\n\t\tthis.send(UpdateMessage, {\n\t\t\tupdate: encrypted,\n\t\t\tdocumentName: this.configuration.name,\n\t\t});\n\t\tthis._noteUpdateApplied();\n\t}\n\n\t// ── Compaction ────────────────────────────────────────────────────────────\n\n\t/**\n\t * Force an immediate compaction attempt, bypassing the threshold and\n\t * quiescence debounce. Resolves once the `snapshot:compact` frame has been\n\t * sent (or rejected locally for missing prerequisites — destroyed, no\n\t * doc key, or already in-flight). The server acknowledges via a\n\t * `snapshot:compacted` broadcast, which emits the `\"compacted\"` event.\n\t */\n\tasync compactNow(): Promise<void> {\n\t\tif (this.compactionDebounceTimer) {\n\t\t\tclearTimeout(this.compactionDebounceTimer);\n\t\t\tthis.compactionDebounceTimer = null;\n\t\t}\n\t\tawait this._performCompaction();\n\t}\n\n\tprivate _noteUpdateApplied(): void {\n\t\tif (!this.compactionEnabled || this.destroyed) return;\n\t\tthis.updatesSinceCompaction += 1;\n\t\tif (this.updatesSinceCompaction < this.compactionThreshold) return;\n\n\t\t// Debounce: reset on every update so compaction only fires after a\n\t\t// quiescent window. This avoids racing concurrent remote updates that\n\t\t// are still propagating through the server.\n\t\tif (this.compactionDebounceTimer) clearTimeout(this.compactionDebounceTimer);\n\t\tthis.compactionDebounceTimer = setTimeout(() => {\n\t\t\tthis.compactionDebounceTimer = null;\n\t\t\tthis._performCompaction().catch((e) => {\n\t\t\t\tconsole.error(\"[E2EAbracadabraProvider] compaction failed:\", e);\n\t\t\t});\n\t\t}, this.compactionQuiescenceMs);\n\t}\n\n\tprivate async _performCompaction(): Promise<void> {\n\t\tif (this.destroyed) return;\n\t\t// Single-flight: server handles concurrent compactions, but we don't\n\t\t// want to pile up outbound frames.\n\t\tif (this.compactionInFlight) return;\n\t\t// Nothing to compact — skip unless explicitly forced after threshold.\n\t\tif (this.updatesSinceCompaction === 0) return;\n\n\t\t// Compaction replaces the entire server-side update log with our state.\n\t\t// Only run after the initial sync — otherwise we'd overwrite the log\n\t\t// with a partial state.\n\t\tif (!this.synced) return;\n\n\t\tconst key = await this.ensureDocKey();\n\t\tif (!key) return;\n\t\tif (this.destroyed) return; // key fetch may be async\n\n\t\tthis.compactionInFlight = true;\n\t\ttry {\n\t\t\tconst stateVector = Y.encodeStateVector(this.document);\n\t\t\tconst fullState = Y.encodeStateAsUpdate(this.document);\n\t\t\tconst encrypted = await encryptField(fullState, key);\n\t\t\tif (this.destroyed) {\n\t\t\t\tthis.compactionInFlight = false;\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tconst payload = `snapshot:compact ${JSON.stringify({\n\t\t\t\tstate_vector: toBase64(stateVector),\n\t\t\t\tcompacted: toBase64(encrypted),\n\t\t\t})}`;\n\t\t\tthis.sendStateless(payload);\n\n\t\t\t// Release in-flight on server broadcast; if nothing arrives in 30s\n\t\t\t// (e.g. permissions rejected, connection dropped) release anyway.\n\t\t\tthis.compactionInFlightTimeout = setTimeout(() => {\n\t\t\t\tthis.compactionInFlight = false;\n\t\t\t\tthis.compactionInFlightTimeout = null;\n\t\t\t}, 30_000);\n\t\t} catch (e) {\n\t\t\tthis.compactionInFlight = false;\n\t\t\tthrow e;\n\t\t}\n\t}\n\n\tprivate _handleCompactedBroadcast(jsonStr: string): void {\n\t\tlet parsed: { doc_id?: string; by?: string } = {};\n\t\ttry {\n\t\t\tparsed = JSON.parse(jsonStr);\n\t\t} catch {\n\t\t\t/* malformed — still clear in-flight below */\n\t\t}\n\n\t\t// Only act on broadcasts for our own doc (server scopes this already,\n\t\t// but be defensive).\n\t\tif (parsed.doc_id && parsed.doc_id !== this.configuration.name) return;\n\n\t\tif (this.compactionInFlightTimeout) {\n\t\t\tclearTimeout(this.compactionInFlightTimeout);\n\t\t\tthis.compactionInFlightTimeout = null;\n\t\t}\n\t\tthis.compactionInFlight = false;\n\t\tthis.updatesSinceCompaction = 0;\n\n\t\tconst event: onCompactedParameters = {\n\t\t\tdocId: parsed.doc_id ?? this.configuration.name,\n\t\t\tby: parsed.by,\n\t\t};\n\t\tthis.emit(\"compacted\", event);\n\t}\n\n\toverride destroy(): void {\n\t\tif (this.destroyed) return;\n\t\tthis.destroyed = true;\n\n\t\tif (this.compactionDebounceTimer) {\n\t\t\tclearTimeout(this.compactionDebounceTimer);\n\t\t\tthis.compactionDebounceTimer = null;\n\t\t}\n\t\tif (this.compactionInFlightTimeout) {\n\t\t\tclearTimeout(this.compactionInFlightTimeout);\n\t\t\tthis.compactionInFlightTimeout = null;\n\t\t}\n\t\tthis.e2eStore?.destroy();\n\t\tthis.e2eStore = null;\n\t\tsuper.destroy();\n\t}\n}\n","/**\n * TreeTimestamps\n *\n * Attaches an afterTransaction observer on a child Y.Doc so that whenever a\n * LOCAL edit is made, the `updatedAt` timestamp on the corresponding entry\n * in the root doc's `doc-tree` map is written.\n *\n * This propagates \"last edited\" timestamps to all peers via the root CRDT,\n * without requiring any server-side changes.\n *\n * Leading-edge + trailing-edge throttle (default 5 s window): the first\n * update flushes immediately so the \"last edited\" badge updates instantly;\n * follow-up updates within the window are coalesced into one trailing flush.\n */\n\nimport * as Y from \"yjs\";\n\nimport { patchEntry } from \"./DocUtils.ts\";\nimport type { OfflineStore } from \"./OfflineStore.ts\";\n\n/**\n * Attach an observer that writes `updatedAt` to the root doc-tree entry for\n * `childDocId` whenever the child doc receives a local edit.\n *\n * @param treeMap The root doc's \"doc-tree\" Y.Map.\n * @param childDocId The child document's UUID (key in treeMap).\n * @param childDoc The child Y.Doc to observe.\n * @param offlineStore The child provider's OfflineStore (used to detect\n * offline-replay origins and skip them). Pass null when\n * the offline store is disabled.\n * @param options Optional config. `throttleMs` controls the throttle\n * window (default 5000).\n * @returns Cleanup function — call on provider destroy. Flushes\n * any pending write before detaching.\n */\nexport function attachUpdatedAtObserver(\n\ttreeMap: Y.Map<any>,\n\tchildDocId: string,\n\tchildDoc: Y.Doc,\n\tofflineStore: OfflineStore | null,\n\toptions?: { throttleMs?: number },\n): () => void {\n\tconst throttleMs = options?.throttleMs ?? 5000;\n\n\tlet lastFlushedAt = 0;\n\tlet pendingTs = 0;\n\tlet timer: ReturnType<typeof setTimeout> | null = null;\n\n\tfunction writeTs(ts: number): void {\n\t\tconst raw = treeMap.get(childDocId);\n\t\tif (!raw) return;\n\t\t// Per-key set on the entry's nested Y.Map: the 5 s `updatedAt`\n\t\t// write no longer clobbers a concurrent parentId/label edit\n\t\t// (whole-entry-LWW fix, audit ⑦).\n\t\tpatchEntry(treeMap, childDocId, { updatedAt: ts });\n\t\tlastFlushedAt = ts;\n\t}\n\n\tfunction flushPending(): void {\n\t\ttimer = null;\n\t\tif (pendingTs === 0) return;\n\t\tconst ts = pendingTs;\n\t\tpendingTs = 0;\n\t\twriteTs(ts);\n\t}\n\n\tfunction handler(tr: Y.Transaction): void {\n\t\t// Only LOCAL edits stamp updatedAt. Remote updates (tr.local === false:\n\t\t// initial sync replay, other peers' edits, offline-store replay,\n\t\t// cross-tab broadcast) are stamped by the client that made them and the\n\t\t// timestamp propagates through the root CRDT — counting them here\n\t\t// turned \"last edited\" into \"last synced on this client\": merely\n\t\t// opening a doc bumped its updatedAt to now.\n\t\tif (!tr.local) return;\n\t\tif (offlineStore !== null && tr.origin === offlineStore) return;\n\t\t// No-op transactions (nothing actually changed) don't count as edits.\n\t\tif (tr.changed.size === 0) return;\n\n\t\tconst now = Date.now();\n\t\tif (now - lastFlushedAt >= throttleMs) {\n\t\t\t// Leading edge — flush immediately.\n\t\t\twriteTs(now);\n\t\t\treturn;\n\t\t}\n\t\t// Inside the throttle window — coalesce into a trailing flush.\n\t\tpendingTs = now;\n\t\tif (timer === null) {\n\t\t\ttimer = setTimeout(flushPending, throttleMs - (now - lastFlushedAt));\n\t\t}\n\t}\n\n\tchildDoc.on(\"afterTransaction\", handler);\n\n\treturn () => {\n\t\tchildDoc.off(\"afterTransaction\", handler);\n\t\tif (timer !== null) {\n\t\t\tclearTimeout(timer);\n\t\t\tflushPending();\n\t\t}\n\t};\n}\n","/**\n * BackgroundSyncPersistence\n *\n * Minimal IndexedDB store (`abracadabra:bgsync:{serverOrigin}`) that persists\n * per-document sync state across page reloads. A single object store,\n * `sync_state`, is keyed by `docId`.\n *\n * Falls back to a no-op when IndexedDB is unavailable (SSR / Node.js).\n */\n\n/**\n * Background-sync lifecycle status.\n *\n * - `pending` — never synced; queued for first attempt.\n * - `syncing` — attempt in progress (transient, not persisted as terminal).\n * - `synced` — last attempt succeeded; `lastSynced` is set.\n * - `retrying` — a *transient* failure (timeout, network) that has NOT yet\n * crossed the failure threshold. Will be retried silently;\n * the UI should treat this calmly and NOT count it as an error.\n * - `error` — a transient failure that has recurred past the threshold\n * (`consecutiveFailures >= FAILURE_THRESHOLD`). Genuinely\n * needs attention; this is what the UI surfaces as red.\n * - `unavailable` — a *permanent* failure (doc deleted/forbidden/invalid id —\n * 404/403/410/422). Not retried, and not surfaced as an error.\n * - `skipped` — E2E doc we can't sync (no keystore). Benign.\n */\nexport type DocSyncStatus =\n\t| \"pending\"\n\t| \"syncing\"\n\t| \"synced\"\n\t| \"retrying\"\n\t| \"error\"\n\t| \"unavailable\"\n\t| \"skipped\";\n\nexport interface DocSyncState {\n\tdocId: string;\n\t/** Current lifecycle status of this document's background sync. */\n\tstatus: DocSyncStatus;\n\t/** Unix ms of the last successful sync, or null if never synced. */\n\tlastSynced: number | null;\n\t/**\n\t * Human-readable message for the most recent failure. Populated for\n\t * `retrying`, `error`, and `unavailable` — cleared on a successful sync.\n\t */\n\terror?: string;\n\t/**\n\t * Count of consecutive failed attempts. Reset to 0 on success. Drives the\n\t * `retrying` → `error` escalation so a single transient blip never nags.\n\t */\n\tconsecutiveFailures?: number;\n\t/** Whether the document uses E2E encryption. */\n\tisE2E: boolean;\n}\n\nconst DB_VERSION = 1;\n\nfunction idbAvailable(): boolean {\n\treturn typeof globalThis !== \"undefined\" && \"indexedDB\" in globalThis;\n}\n\nfunction openDb(serverOrigin: string): Promise<IDBDatabase> {\n\treturn new Promise((resolve, reject) => {\n\t\tconst req = globalThis.indexedDB.open(\n\t\t\t`abracadabra:bgsync:${serverOrigin}`,\n\t\t\tDB_VERSION,\n\t\t);\n\t\treq.onupgradeneeded = (event) => {\n\t\t\tconst db = (event.target as IDBOpenDBRequest).result;\n\t\t\tif (!db.objectStoreNames.contains(\"sync_state\")) {\n\t\t\t\tdb.createObjectStore(\"sync_state\", { keyPath: \"docId\" });\n\t\t\t}\n\t\t};\n\t\treq.onsuccess = () => resolve(req.result);\n\t\treq.onerror = () => reject(req.error);\n\t});\n}\n\nfunction idbPromise<T>(request: IDBRequest<T>): Promise<T> {\n\treturn new Promise((resolve, reject) => {\n\t\trequest.onsuccess = () => resolve(request.result);\n\t\trequest.onerror = () => reject(request.error);\n\t});\n}\n\nexport class BackgroundSyncPersistence {\n\tprivate dbPromise: Promise<IDBDatabase | null> | null = null;\n\tprivate readonly serverOrigin: string;\n\n\tconstructor(serverOrigin: string) {\n\t\tthis.serverOrigin = serverOrigin;\n\t}\n\n\tprivate getDb(): Promise<IDBDatabase | null> {\n\t\tif (!idbAvailable()) return Promise.resolve(null);\n\t\tif (!this.dbPromise) {\n\t\t\tthis.dbPromise = openDb(this.serverOrigin).catch(() => null);\n\t\t}\n\t\treturn this.dbPromise;\n\t}\n\n\tasync getState(docId: string): Promise<DocSyncState | null> {\n\t\tconst db = await this.getDb();\n\t\tif (!db) return null;\n\t\tconst tx = db.transaction(\"sync_state\", \"readonly\");\n\t\tconst result = await idbPromise<DocSyncState | undefined>(\n\t\t\ttx.objectStore(\"sync_state\").get(docId),\n\t\t);\n\t\treturn result ?? null;\n\t}\n\n\tasync getAllStates(): Promise<DocSyncState[]> {\n\t\tconst db = await this.getDb();\n\t\tif (!db) return [];\n\t\treturn new Promise((resolve, reject) => {\n\t\t\tconst tx = db.transaction(\"sync_state\", \"readonly\");\n\t\t\tconst req = tx.objectStore(\"sync_state\").getAll();\n\t\t\treq.onsuccess = () => resolve(req.result as DocSyncState[]);\n\t\t\treq.onerror = () => reject(req.error);\n\t\t});\n\t}\n\n\tasync setState(state: DocSyncState): Promise<void> {\n\t\tconst db = await this.getDb();\n\t\tif (!db) return;\n\t\tconst tx = db.transaction(\"sync_state\", \"readwrite\");\n\t\tawait idbPromise(tx.objectStore(\"sync_state\").put(state));\n\t}\n\n\tasync deleteState(docId: string): Promise<void> {\n\t\tconst db = await this.getDb();\n\t\tif (!db) return;\n\t\tconst tx = db.transaction(\"sync_state\", \"readwrite\");\n\t\tawait idbPromise(tx.objectStore(\"sync_state\").delete(docId));\n\t}\n\n\tdestroy(): void {\n\t\t// No cleanup needed — shared IDB connection managed by browser\n\t}\n}\n","/**\n * BackgroundSyncManager\n *\n * Proactively syncs all documents in the root tree map to IndexedDB so they\n * are available offline even if the user has never opened them directly.\n *\n * Key behaviours:\n * - Priority queue: sorted by updatedAt desc → never-synced first → errored last\n * - Concurrency: semaphore (default 2 parallel WS connections)\n * - Provider selection: non-E2E via rootProvider.loadChild(); E2E via\n * E2EAbracadabraProvider directly when docKeyManager + keystore are present\n * - File pre-caching: after sync, walks the Y.Doc for file refs and warms\n * the FileBlobStore cache (opt-in via prefetchFiles, default true)\n * - Cover images: at start of syncAll(), pre-caches all cover upload IDs\n * from the root tree map immediately (fire-and-forget)\n * - Periodic sync: startPeriodicSync() returns a cleanup function\n *\n * Note: This is in-page only (no Service Worker). The existing\n * flushPendingUpdates() handles offline → reconnect for open docs.\n */\n\nimport * as Y from \"yjs\";\nimport type { AbracadabraProvider } from \"./AbracadabraProvider.ts\";\nimport type { AbracadabraClient } from \"./AbracadabraClient.ts\";\nimport type { FileBlobStore } from \"./FileBlobStore.ts\";\nimport {\n\tBackgroundSyncPersistence,\n\ttype DocSyncState,\n} from \"./BackgroundSyncPersistence.ts\";\nimport { OfflineStore } from \"./OfflineStore.ts\";\nimport EventEmitter from \"./EventEmitter.ts\";\nimport { E2EAbracadabraProvider } from \"./E2EAbracadabraProvider.ts\";\nimport { getLifecycleGate } from \"./LifecycleGate.ts\";\n\nexport interface BackgroundSyncManagerOptions {\n\t/** Max parallel WS connections for background sync. Default: 2. */\n\tconcurrency?: number;\n\t/** Timeout (ms) waiting for a provider to sync. Default: 30 000. */\n\tsyncTimeout?: number;\n\t/** Pre-cache file blobs after syncing a doc. Default: true. */\n\tprefetchFiles?: boolean;\n\t/** Delay (ms) between starting each doc sync to avoid server pressure. Default: 200. */\n\tthrottleMs?: number;\n\t/** Max retries for failed docs within a single syncAll() run. Default: 2. */\n\tmaxRetries?: number;\n}\n\n/**\n * Simple semaphore for capping concurrency.\n */\nclass Semaphore {\n\tprivate slots: number;\n\tprivate queue: Array<() => void> = [];\n\n\tconstructor(limit: number) {\n\t\tthis.slots = limit;\n\t}\n\n\tacquire(): Promise<void> {\n\t\tif (this.slots > 0) {\n\t\t\tthis.slots--;\n\t\t\treturn Promise.resolve();\n\t\t}\n\t\treturn new Promise((resolve) => this.queue.push(resolve));\n\t}\n\n\trelease(): void {\n\t\tconst next = this.queue.shift();\n\t\tif (next) {\n\t\t\tnext();\n\t\t} else {\n\t\t\tthis.slots++;\n\t\t}\n\t}\n}\n\n/**\n * Server-accepted doc-id format. The Rust server's `DocId::from_string`\n * is a strict UUID parse; any other string returns 422. Stale entries in\n * the doc-tree map (legacy slug ids from earlier demos, manual experiments)\n * would otherwise emit one 422 per `syncAll()` forever — see the warn\n * below in `_buildQueue`.\n */\nconst UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;\n\nfunction isValidDocId(id: string): boolean {\n\treturn UUID_RE.test(id);\n}\n\n/**\n * Consecutive transient failures before a doc is promoted from the calm\n * `retrying` status to a genuine `error`. Keeps a single timeout/network blip\n * from flashing a red error badge — the doc only \"counts\" as broken once it\n * has failed this many passes in a row.\n */\nconst FAILURE_THRESHOLD = 3;\n\n/** Delay before a one-shot follow-up retry of stragglers after `syncAll()`. */\nconst STRAGGLER_RETRY_DELAY_MS = 60_000;\n\n/**\n * Decide whether a sync failure is permanent (the server will never accept\n * this doc — deleted, forbidden, or an unparseable id) or merely transient\n * (timeout, dropped socket, momentary 5xx). Permanent failures are parked as\n * `unavailable` and never retried; transient ones go through `retrying`.\n *\n * Best-effort: inspects a numeric `status`/`code` if the thrown value carries\n * one, otherwise falls back to message keywords. Defaults to transient so we\n * never give up on a doc we're unsure about.\n */\nfunction isPermanentSyncError(err: unknown): boolean {\n\tconst status =\n\t\ttypeof err === \"object\" && err !== null\n\t\t\t? Number(\n\t\t\t\t\t(err as { status?: unknown; statusCode?: unknown; code?: unknown })\n\t\t\t\t\t\t.status ??\n\t\t\t\t\t\t(err as { statusCode?: unknown }).statusCode ??\n\t\t\t\t\t\t(err as { code?: unknown }).code,\n\t\t\t\t)\n\t\t\t: NaN;\n\tif (status === 403 || status === 404 || status === 410 || status === 422) {\n\t\treturn true;\n\t}\n\tconst msg = (err instanceof Error ? err.message : String(err)).toLowerCase();\n\treturn (\n\t\t/\\b(403|404|410|422)\\b/.test(msg) ||\n\t\tmsg.includes(\"forbidden\") ||\n\t\tmsg.includes(\"not found\") ||\n\t\tmsg.includes(\"does not exist\") ||\n\t\tmsg.includes(\"unprocessable\")\n\t);\n}\n\nexport class BackgroundSyncManager extends EventEmitter {\n\tprivate readonly rootProvider: AbracadabraProvider;\n\tprivate readonly client: AbracadabraClient;\n\tprivate readonly fileBlobStore: FileBlobStore | null;\n\tprivate readonly opts: Required<BackgroundSyncManagerOptions>;\n\n\tprivate readonly persistence: BackgroundSyncPersistence;\n\tprivate readonly semaphore: Semaphore;\n\tprivate readonly syncStates = new Map<string, DocSyncState>();\n\t/** Doc ids we've already warned about; keeps the log to one line per id. */\n\tprivate readonly _warnedInvalidIds = new Set<string>();\n\n\tprivate _destroyed = false;\n\tprivate _initPromise: Promise<void> | null = null;\n\t/** One-shot timer for the post-syncAll straggler retry pass. */\n\tprivate _stragglerTimer: ReturnType<typeof setTimeout> | null = null;\n\n\tconstructor(\n\t\trootProvider: AbracadabraProvider,\n\t\tclient: AbracadabraClient,\n\t\tfileBlobStore?: FileBlobStore | null,\n\t\topts?: BackgroundSyncManagerOptions,\n\t) {\n\t\tsuper();\n\t\tthis.rootProvider = rootProvider;\n\t\tthis.client = client;\n\t\tthis.fileBlobStore = fileBlobStore ?? null;\n\t\tthis.opts = {\n\t\t\tconcurrency: opts?.concurrency ?? 2,\n\t\t\tsyncTimeout: opts?.syncTimeout ?? 30_000,\n\t\t\tprefetchFiles: opts?.prefetchFiles ?? true,\n\t\t\tthrottleMs: opts?.throttleMs ?? 200,\n\t\t\tmaxRetries: opts?.maxRetries ?? 2,\n\t\t};\n\n\t\t// Derive server origin from client URL for IDB namespacing.\n\t\t// `host` (not `hostname`): port-scoped so same-host servers on\n\t\t// different ports don't share a namespace.\n\t\tlet serverOrigin = \"default\";\n\t\ttry {\n\t\t\tserverOrigin = new URL((client as any).baseUrl ?? \"\").host;\n\t\t} catch {}\n\n\t\tthis.persistence = new BackgroundSyncPersistence(serverOrigin);\n\t\tthis.semaphore = new Semaphore(this.opts.concurrency);\n\t}\n\n\t// ── Public API ────────────────────────────────────────────────────────────\n\n\t/**\n\t * Load persisted sync states from IndexedDB into the in-memory map.\n\t * Called automatically by syncAll() / syncDoc(); safe to call concurrently.\n\t */\n\tasync init(): Promise<void> {\n\t\tif (!this._initPromise) {\n\t\t\tthis._initPromise = this._loadPersistedStates();\n\t\t}\n\t\treturn this._initPromise;\n\t}\n\n\tprivate async _loadPersistedStates(): Promise<void> {\n\t\ttry {\n\t\t\tconst states = await this.persistence.getAllStates();\n\t\t\tfor (const state of states) {\n\t\t\t\tthis.syncStates.set(state.docId, state);\n\t\t\t}\n\t\t} catch {\n\t\t\t// IDB unavailable — proceed with empty map (full sync fallback)\n\t\t}\n\t}\n\n\t/**\n\t * Re-read persisted sync states from IndexedDB, merging in any docs not\n\t * already tracked in memory. Unlike `init()` this is **not** cached behind\n\t * `_initPromise` — every call hits IDB afresh.\n\t *\n\t * Why this exists: `init()` only ever loads IDB once. If a manager was\n\t * created while IDB was empty/mid-population (or a UI singleton was left\n\t * pointing at a manager whose in-memory map is stale after a connection\n\t * swap), the only thing that recovered the real counts was a full page\n\t * reload (which spins up a brand-new manager → fresh `_loadPersistedStates`).\n\t * Calling this re-hydrates from the same source a reload reads, so the\n\t * offline-sync panel can self-heal from a spurious \"0/0\" without a reload.\n\t *\n\t * Merge-only by design: an in-memory entry (possibly a fresher in-flight\n\t * `syncing`/`synced`) is never clobbered by the persisted copy; we only add\n\t * docs IDB knows about that memory doesn't.\n\t */\n\tasync reloadPersistedStates(): Promise<void> {\n\t\ttry {\n\t\t\tconst states = await this.persistence.getAllStates();\n\t\t\tfor (const state of states) {\n\t\t\t\tif (!this.syncStates.has(state.docId)) {\n\t\t\t\t\tthis.syncStates.set(state.docId, state);\n\t\t\t\t}\n\t\t\t}\n\t\t} catch {\n\t\t\t// IDB unavailable — keep whatever is already in memory.\n\t\t}\n\t}\n\n\t/** Sync all documents in the root tree. */\n\tasync syncAll(): Promise<void> {\n\t\tif (this._destroyed) return;\n\n\t\tawait this.init();\n\n\t\tconst treeMap = this.rootProvider.document.getMap(\"doc-tree\") as Y.Map<any>;\n\t\tconst entries = Array.from(treeMap.entries()) as Array<[string, any]>;\n\n\t\tif (entries.length === 0) return;\n\n\t\t// Build updatedAt lookup for skip-unchanged logic\n\t\tconst updatedAtMap = new Map<string, number>();\n\t\tfor (const [docId, v] of entries) {\n\t\t\tupdatedAtMap.set(docId, v?.updatedAt ?? v?.createdAt ?? 0);\n\t\t}\n\n\t\t// Pre-cache cover images immediately (fire-and-forget)\n\t\tthis._prefetchCovers(entries).catch(() => null);\n\n\t\t// Build the priority queue\n\t\tconst queue = this._buildQueue(entries);\n\n\t\t// Sync all docs with throttling: stagger starts to avoid server pressure.\n\t\t// We use a feeding loop instead of Promise.all(queue.map(...)) so that\n\t\t// each new doc start is spaced by throttleMs.\n\t\tconst failed: string[] = [];\n\t\tlet idx = 0;\n\t\tconst next = async (): Promise<void> => {\n\t\t\twhile (idx < queue.length) {\n\t\t\t\tif (this._destroyed) return;\n\t\t\t\tconst docId = queue[idx++]!;\n\t\t\t\tconst updatedAt = updatedAtMap.get(docId) ?? 0;\n\t\t\t\tconst ok = await this._syncWithSemaphore(docId, updatedAt);\n\t\t\t\tif (!ok) failed.push(docId);\n\t\t\t\t// Throttle between starts\n\t\t\t\tif (this.opts.throttleMs > 0 && idx < queue.length) {\n\t\t\t\t\tawait new Promise((r) => setTimeout(r, this.opts.throttleMs));\n\t\t\t\t}\n\t\t\t}\n\t\t};\n\n\t\t// Launch `concurrency` parallel workers feeding from the shared index.\n\t\tconst workers = Array.from({ length: this.opts.concurrency }, () => next());\n\t\tawait Promise.all(workers);\n\n\t\t// Retry failed docs with increasing backoff.\n\t\tfor (let retry = 0; retry < this.opts.maxRetries && failed.length > 0; retry++) {\n\t\t\tif (this._destroyed) return;\n\t\t\tconst batch = failed.splice(0, failed.length);\n\t\t\t// Backoff: 2s, 4s, 8s...\n\t\t\tconst backoff = 2000 * 2 ** retry;\n\t\t\tawait new Promise((r) => setTimeout(r, backoff));\n\n\t\t\tidx = 0;\n\t\t\tconst retryQueue = batch;\n\t\t\tconst retryNext = async (): Promise<void> => {\n\t\t\t\twhile (idx < retryQueue.length) {\n\t\t\t\t\tif (this._destroyed) return;\n\t\t\t\t\tconst docId = retryQueue[idx++]!;\n\t\t\t\t\tconst updatedAt = updatedAtMap.get(docId) ?? 0;\n\t\t\t\t\tconst ok = await this._syncWithSemaphore(docId, updatedAt);\n\t\t\t\t\tif (!ok) failed.push(docId);\n\t\t\t\t\tif (this.opts.throttleMs > 0 && idx < retryQueue.length) {\n\t\t\t\t\t\tawait new Promise((r) => setTimeout(r, this.opts.throttleMs));\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t};\n\t\t\tconst retryWorkers = Array.from({ length: this.opts.concurrency }, () => retryNext());\n\t\t\tawait Promise.all(retryWorkers);\n\t\t}\n\n\t\t// Any docs still failing after the in-run retries are \"stragglers\" — the\n\t\t// usual 1-2 slow docs that just needed a moment. Rather than make the\n\t\t// user stare at them until the next periodic pass (which can be far off),\n\t\t// schedule one quiet follow-up attempt while the connection is still warm.\n\t\tif (failed.length > 0) {\n\t\t\tthis._scheduleStragglerRetry(failed.slice());\n\t\t}\n\t}\n\n\t/**\n\t * Schedule a single delayed retry of the given docs. Replaces any pending\n\t * straggler timer so repeated `syncAll()` calls don't stack timers.\n\t */\n\tprivate _scheduleStragglerRetry(docIds: string[]): void {\n\t\tif (this._destroyed || docIds.length === 0) return;\n\t\tif (this._stragglerTimer) clearTimeout(this._stragglerTimer);\n\t\tthis._stragglerTimer = setTimeout(() => {\n\t\t\tthis._stragglerTimer = null;\n\t\t\tif (this._destroyed) return;\n\t\t\tvoid (async () => {\n\t\t\t\tconst treeMap = this.rootProvider.document.getMap(\n\t\t\t\t\t\"doc-tree\",\n\t\t\t\t) as Y.Map<any>;\n\t\t\t\tfor (const docId of docIds) {\n\t\t\t\t\tif (this._destroyed) return;\n\t\t\t\t\tconst entry = treeMap.get(docId);\n\t\t\t\t\tconst updatedAt = entry?.updatedAt ?? entry?.createdAt ?? 0;\n\t\t\t\t\tawait this._syncWithSemaphore(docId, updatedAt);\n\t\t\t\t}\n\t\t\t})();\n\t\t}, STRAGGLER_RETRY_DELAY_MS);\n\t}\n\n\t/** Sync a single document by ID. */\n\tasync syncDoc(docId: string): Promise<DocSyncState> {\n\t\tawait this.init();\n\t\tconst state = await this._doSyncDoc(docId);\n\t\tthis.syncStates.set(docId, state);\n\t\tawait this.persistence.setState(state).catch(() => null);\n\t\tthis.emit(\"stateChanged\", { docId, state });\n\t\treturn state;\n\t}\n\n\t/** Return a snapshot of all known sync states. */\n\tgetSyncStatus(): Map<string, DocSyncState> {\n\t\treturn new Map(this.syncStates);\n\t}\n\n\t/**\n\t * Start periodic background sync.\n\t * @param intervalMs Interval between sync runs. Default: 5 minutes.\n\t * @returns Cleanup function to stop the periodic sync.\n\t */\n\tstartPeriodicSync(intervalMs = 5 * 60 * 1000): () => void {\n\t\tlet missedWhileHidden = false;\n\n\t\tconst handle = setInterval(() => {\n\t\t\tif (this._destroyed) return;\n\n\t\t\t// A full-tree pass is the single most expensive thing this client\n\t\t\t// does on its own initiative: every document in the space gets an\n\t\t\t// encryption lookup, a provider, a sync wait, a document encode, an\n\t\t\t// IndexedDB write and a blob prefetch. Running that on a phone in\n\t\t\t// someone's pocket, on cellular, every five minutes, for a UI nobody\n\t\t\t// is looking at, is the worst trade in the codebase. Defer it; the\n\t\t\t// data is still there when they come back.\n\t\t\tif (getLifecycleGate().backgrounded) {\n\t\t\t\tmissedWhileHidden = true;\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tthis.syncAll().catch(() => null);\n\t\t}, intervalMs);\n\n\t\t// Catch up on return, but only if a run was actually skipped — coming\n\t\t// back to a foreground app must not trigger a redundant full-tree pass\n\t\t// on top of the one the interval is about to do anyway.\n\t\tconst unsubscribe = getLifecycleGate().onChange((backgrounded) => {\n\t\t\tif (backgrounded || !missedWhileHidden || this._destroyed) return;\n\t\t\tmissedWhileHidden = false;\n\t\t\tthis.syncAll().catch(() => null);\n\t\t});\n\n\t\treturn () => {\n\t\t\tclearInterval(handle);\n\t\t\tunsubscribe();\n\t\t};\n\t}\n\n\t/**\n\t * Clear all offline document data and sync state.\n\t * Opens each document's OfflineStore and clears its contents, then\n\t * resets the background sync persistence. After calling this, all\n\t * documents will need to be re-synced.\n\t */\n\tasync clearAllSyncedData(): Promise<void> {\n\t\t// Collect doc IDs from both in-memory state and the tree\n\t\tconst docIds = new Set<string>(this.syncStates.keys());\n\t\tconst treeMap = this.rootProvider.document.getMap(\"doc-tree\") as Y.Map<any>;\n\t\tfor (const docId of treeMap.keys()) {\n\t\t\tdocIds.add(docId);\n\t\t}\n\n\t\t// Derive server origin the same way the provider does (`host`, port-scoped)\n\t\tlet serverOrigin: string | undefined;\n\t\ttry {\n\t\t\tserverOrigin = new URL((this.client as any).baseUrl ?? \"\").host;\n\t\t} catch {}\n\n\t\t// Clear each document's offline store contents\n\t\tconst clearPromises = Array.from(docIds).map(async (docId) => {\n\t\t\ttry {\n\t\t\t\tconst store = new OfflineStore(docId, serverOrigin);\n\t\t\t\tawait store.clearAll();\n\t\t\t\tstore.destroy();\n\t\t\t} catch {\n\t\t\t\t// Ignore per-doc failures\n\t\t\t}\n\t\t});\n\t\tawait Promise.all(clearPromises);\n\n\t\t// Clear background sync persistence\n\t\tfor (const docId of docIds) {\n\t\t\tawait this.persistence.deleteState(docId).catch(() => null);\n\t\t}\n\n\t\t// Reset in-memory state\n\t\tthis.syncStates.clear();\n\t\tthis._initPromise = null;\n\t}\n\n\tdestroy(): void {\n\t\tthis._destroyed = true;\n\t\tif (this._stragglerTimer) {\n\t\t\tclearTimeout(this._stragglerTimer);\n\t\t\tthis._stragglerTimer = null;\n\t\t}\n\t\tthis.removeAllListeners();\n\t}\n\n\t// ── Internal ──────────────────────────────────────────────────────────────\n\n\t/**\n\t * Build a priority-sorted list of doc IDs:\n\t * 1. Never-synced docs first (lastSynced === null, status !== \"error\")\n\t * 2. Synced docs sorted by updatedAt desc (most-recently-edited first)\n\t * 3. Errored docs last\n\t */\n\tprivate _buildQueue(entries: Array<[string, any]>): string[] {\n\t\ttype Sortable = { docId: string; priority: number };\n\n\t\t// Drop ids the server can't parse (non-UUID). One-time warn per id\n\t\t// so the operator can chase down where the stale entry is, but no\n\t\t// log storm on every sync run.\n\t\tconst filtered: Array<[string, any]> = [];\n\t\tfor (const entry of entries) {\n\t\t\tconst [docId] = entry;\n\t\t\tif (isValidDocId(docId)) {\n\t\t\t\tfiltered.push(entry);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (!this._warnedInvalidIds.has(docId)) {\n\t\t\t\tthis._warnedInvalidIds.add(docId);\n\t\t\t\tconsole.warn(\n\t\t\t\t\t`[BackgroundSyncManager] skipping non-UUID doc id \"${docId}\" in doc-tree — server would reject it (422). Likely a stale entry from an earlier seeder; remove it from the tree to silence this.`,\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\n\t\tconst items: Sortable[] = [];\n\t\tfor (const [docId, v] of filtered) {\n\t\t\tconst state = this.syncStates.get(docId);\n\n\t\t\t// Permanently unavailable docs are never queued — the server would\n\t\t\t// just reject them again. They stay parked until a resync clears them.\n\t\t\tif (state?.status === \"unavailable\") continue;\n\n\t\t\tconst updatedAt: number = v?.updatedAt ?? v?.createdAt ?? 0;\n\n\t\t\tlet priority: number;\n\t\t\tif (!state || state.status === \"pending\") {\n\t\t\t\t// Never synced — high priority (large number so it sorts first when DESC)\n\t\t\t\tpriority = Number.MAX_SAFE_INTEGER - updatedAt;\n\t\t\t} else if (state.status === \"error\" || state.status === \"retrying\") {\n\t\t\t\t// Failing — lowest priority (large negative offset)\n\t\t\t\tpriority = -1;\n\t\t\t} else {\n\t\t\t\t// Synced — sort by updatedAt desc (most recent = highest priority)\n\t\t\t\tpriority = updatedAt;\n\t\t\t}\n\t\t\titems.push({ docId, priority });\n\t\t}\n\n\t\t// Sort descending by priority\n\t\titems.sort((a, b) => b.priority - a.priority);\n\t\treturn items.map((i) => i.docId);\n\t}\n\n\t/** Returns true on success (or skip), false on error. */\n\tprivate async _syncWithSemaphore(\n\t\tdocId: string,\n\t\tupdatedAt: number,\n\t): Promise<boolean> {\n\t\tif (this._destroyed) return true;\n\n\t\tconst existing = this.syncStates.get(docId);\n\n\t\t// Permanently unavailable (deleted/forbidden) — don't keep hammering a\n\t\t// doc the server will never accept. Re-emit so the UI keeps the state.\n\t\tif (existing && existing.status === \"unavailable\") {\n\t\t\tthis.emit(\"stateChanged\", { docId, state: existing });\n\t\t\treturn true;\n\t\t}\n\n\t\t// Skip if already synced and doc hasn't changed since last sync.\n\t\t// The 200ms grace margin handles edge cases where the updatedAt\n\t\t// observer writes a timestamp milliseconds after lastSynced was recorded.\n\t\tif (\n\t\t\texisting &&\n\t\t\texisting.status === \"synced\" &&\n\t\t\texisting.lastSynced !== null &&\n\t\t\texisting.lastSynced + 200 >= updatedAt\n\t\t) {\n\t\t\tthis.emit(\"stateChanged\", { docId, state: existing });\n\t\t\treturn true;\n\t\t}\n\n\t\tawait this.semaphore.acquire();\n\t\ttry {\n\t\t\tconst state = await this._doSyncDoc(docId);\n\t\t\tthis.syncStates.set(docId, state);\n\t\t\tawait this.persistence.setState(state).catch(() => null);\n\t\t\tthis.emit(\"stateChanged\", { docId, state });\n\t\t\t// `retrying` and `error` are both failures that warrant another pass;\n\t\t\t// `unavailable` is permanent so we report it as done (no retry).\n\t\t\treturn state.status !== \"error\" && state.status !== \"retrying\";\n\t\t} finally {\n\t\t\tthis.semaphore.release();\n\t\t}\n\t}\n\n\tprivate async _doSyncDoc(docId: string): Promise<DocSyncState> {\n\t\t// Non-UUID ids the server can't parse (422) are permanently unsyncable —\n\t\t// park them as `unavailable` rather than churning through retries.\n\t\tif (!isValidDocId(docId)) {\n\t\t\treturn {\n\t\t\t\tdocId,\n\t\t\t\tstatus: \"unavailable\",\n\t\t\t\tlastSynced: this.syncStates.get(docId)?.lastSynced ?? null,\n\t\t\t\terror: \"Invalid document id (not a UUID)\",\n\t\t\t\tconsecutiveFailures: 0,\n\t\t\t\tisE2E: false,\n\t\t\t};\n\t\t}\n\n\t\t// Mark as syncing\n\t\tconst syncing: DocSyncState = {\n\t\t\tdocId,\n\t\t\tstatus: \"syncing\",\n\t\t\tlastSynced: this.syncStates.get(docId)?.lastSynced ?? null,\n\t\t\tisE2E: false,\n\t\t};\n\t\tthis.syncStates.set(docId, syncing);\n\t\tthis.emit(\"stateChanged\", { docId, state: syncing });\n\n\t\tlet isE2E = false;\n\t\ttry {\n\t\t\t// Check encryption type\n\t\t\ttry {\n\t\t\t\tconst enc = await this.client.getDocEncryption(docId);\n\t\t\t\tisE2E = enc.mode === \"e2e\";\n\t\t\t} catch {\n\t\t\t\t// If we can't check, treat as non-E2E\n\t\t\t}\n\n\t\t\tif (isE2E) {\n\t\t\t\treturn await this._syncE2EDoc(docId);\n\t\t\t} else {\n\t\t\t\treturn await this._syncNonE2EDoc(docId);\n\t\t\t}\n\t\t} catch (err) {\n\t\t\tconst error = err instanceof Error ? err.message : String(err);\n\t\t\tconst prev = this.syncStates.get(docId);\n\t\t\tconst lastSynced = prev?.lastSynced ?? null;\n\n\t\t\t// Permanent failure (deleted / forbidden / unparseable) — park it as\n\t\t\t// `unavailable` so we stop retrying and never surface it as an error.\n\t\t\tif (isPermanentSyncError(err)) {\n\t\t\t\treturn {\n\t\t\t\t\tdocId,\n\t\t\t\t\tstatus: \"unavailable\",\n\t\t\t\t\tlastSynced,\n\t\t\t\t\terror,\n\t\t\t\t\tconsecutiveFailures: 0,\n\t\t\t\t\tisE2E,\n\t\t\t\t};\n\t\t\t}\n\n\t\t\t// Transient failure — escalate to a genuine `error` only once it has\n\t\t\t// recurred past the threshold; otherwise keep it calm as `retrying`.\n\t\t\tconst consecutiveFailures = (prev?.consecutiveFailures ?? 0) + 1;\n\t\t\treturn {\n\t\t\t\tdocId,\n\t\t\t\tstatus:\n\t\t\t\t\tconsecutiveFailures >= FAILURE_THRESHOLD ? \"error\" : \"retrying\",\n\t\t\t\tlastSynced,\n\t\t\t\terror,\n\t\t\t\tconsecutiveFailures,\n\t\t\t\tisE2E,\n\t\t\t};\n\t\t}\n\t}\n\n\tprivate async _syncNonE2EDoc(docId: string): Promise<DocSyncState> {\n\t\tconst treeMap = this.rootProvider.document.getMap(\"doc-tree\") as Y.Map<any>;\n\n\t\t// Check if the provider already exists (user is viewing it) before loading.\n\t\tconst alreadyCached = this.rootProvider.children.has(docId);\n\n\t\t// Another provider (e.g. a nested renderer) may have already loaded\n\t\t// this doc through a different parent. The shared WS providerMap\n\t\t// tracks all attached providers; if one exists, the doc is already\n\t\t// syncing — skip to avoid creating a duplicate.\n\t\tif (!alreadyCached) {\n\t\t\tconst wsProviderMap = (this.rootProvider as any).configuration\n\t\t\t\t?.websocketProvider?.configuration?.providerMap as\n\t\t\t\t| Map<string, unknown>\n\t\t\t\t| undefined;\n\t\t\tif (wsProviderMap?.has(docId)) {\n\t\t\t\treturn {\n\t\t\t\t\tdocId,\n\t\t\t\t\tstatus: \"synced\",\n\t\t\t\t\tlastSynced: Date.now(),\n\t\t\t\t\tconsecutiveFailures: 0,\n\t\t\t\t\tisE2E: false,\n\t\t\t\t};\n\t\t\t}\n\t\t}\n\n\t\t// Load transiently: a background-sync child must neither count toward\n\t\t// the parent's LRU budget nor evict the user's open docs, and it must\n\t\t// not be evicted out from under its own in-flight sync. We clean it up\n\t\t// explicitly in `finally`.\n\t\tconst childProvider = await this.rootProvider.loadChild(docId, {\n\t\t\tevictable: false,\n\t\t});\n\n\t\ttry {\n\t\t\t// Wait for ready (offline snapshot loaded) then synced (server sync done)\n\t\t\tawait childProvider.ready;\n\t\t\tawait this._waitForSynced(childProvider);\n\n\t\t\t// Force the offline snapshot to disk BEFORE the `finally` below\n\t\t\t// unloads (and therefore destroys) this provider. The provider's own\n\t\t\t// \"synced\" handler also writes one, but that runs concurrently and\n\t\t\t// loses the race often enough that most background-synced documents\n\t\t\t// ended up with an empty offline cache — which is also why the\n\t\t\t// client-side search/backlink index had almost nothing to walk.\n\t\t\t// \"Synced\" must mean \"on disk\", or this manager is lying.\n\t\t\tif (typeof (childProvider as any).persistSnapshot === \"function\") {\n\t\t\t\tawait (childProvider as any).persistSnapshot();\n\t\t\t}\n\n\t\t\t// Emit docSynced while the child is still loaded so listeners can\n\t\t\t// extract data (search text, file refs) without opening a new IDB.\n\t\t\t{\n\t\t\t\tconst treeEntry = treeMap.get(docId);\n\t\t\t\tthis.emit(\"docSynced\", {\n\t\t\t\t\tdocId,\n\t\t\t\t\tdocument: childProvider.document,\n\t\t\t\t\tlabel: treeEntry?.label ?? \"\",\n\t\t\t\t\tmeta: treeEntry?.meta,\n\t\t\t\t});\n\t\t\t}\n\n\t\t\t// Prefetch file blobs\n\t\t\tif (this.opts.prefetchFiles && this.fileBlobStore) {\n\t\t\t\tthis._prefetchDocFiles(docId, childProvider.document).catch(() => null);\n\t\t\t}\n\n\t\t\t// Use the tree's updatedAt so lastSynced >= updatedAt, preventing\n\t\t\t// the observer's timestamp write from triggering a spurious re-sync.\n\t\t\tconst treeEntry = treeMap.get(docId);\n\t\t\tconst treeUpdatedAt = treeEntry?.updatedAt ?? treeEntry?.createdAt ?? 0;\n\t\t\treturn {\n\t\t\t\tdocId,\n\t\t\t\tstatus: \"synced\",\n\t\t\t\tlastSynced: Math.max(Date.now(), treeUpdatedAt),\n\t\t\t\tconsecutiveFailures: 0,\n\t\t\t\tisE2E: false,\n\t\t\t};\n\t\t} finally {\n\t\t\t// Release the provider only if we created it solely for background\n\t\t\t// sync. Two cases keep it alive:\n\t\t\t// - `alreadyCached`: it was loaded before we started — the UI owns it.\n\t\t\t// - the user OPENED it mid-sync: `loadChild` (default evictable)\n\t\t\t// promoted it out of transient, so it's no longer ours. Destroying\n\t\t\t// it here would detach the provider under a doc they're viewing,\n\t\t\t// leaving it stuck on a blue/\"retrying\" indicator until reload.\n\t\t\t// `isChildTransient` is a newer provider API; fall back to the old\n\t\t\t// unconditional unload if the parent predates it.\n\t\t\tif (!alreadyCached) {\n\t\t\t\tconst stillOurs =\n\t\t\t\t\ttypeof (this.rootProvider as any).isChildTransient === \"function\"\n\t\t\t\t\t\t? (this.rootProvider as any).isChildTransient(docId)\n\t\t\t\t\t\t: true;\n\t\t\t\tif (stillOurs) this.rootProvider.unloadChild(docId);\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate async _syncE2EDoc(docId: string): Promise<DocSyncState> {\n\t\tconst treeMap = this.rootProvider.document.getMap(\"doc-tree\") as Y.Map<any>;\n\n\t\t// Attempt E2E sync only when docKeyManager and keystore are available\n\t\tconst docKeyManager = (this.rootProvider as any).abracadabraConfig\n\t\t\t?.docKeyManager;\n\t\tconst keystore = (this.rootProvider as any).abracadabraConfig?.keystore;\n\n\t\tif (!docKeyManager || !keystore) {\n\t\t\t// No key management configured — skip silently\n\t\t\treturn {\n\t\t\t\tdocId,\n\t\t\t\tstatus: \"skipped\",\n\t\t\t\tlastSynced: null,\n\t\t\t\tconsecutiveFailures: 0,\n\t\t\t\tisE2E: true,\n\t\t\t};\n\t\t}\n\n\t\tconst childDoc = new Y.Doc({ guid: docId });\n\t\tconst childProvider = new E2EAbracadabraProvider({\n\t\t\tname: docId,\n\t\t\tdocument: childDoc,\n\t\t\tclient: this.client,\n\t\t\tdocKeyManager,\n\t\t\tkeystore,\n\t\t});\n\n\t\ttry {\n\t\t\tawait childProvider.ready;\n\t\t\tawait this._waitForSynced(childProvider);\n\n\t\t\t// Emit docSynced while the child is still alive so listeners can\n\t\t\t// extract data without opening a new IDB connection.\n\t\t\t{\n\t\t\t\tconst treeEntry = treeMap.get(docId);\n\t\t\t\tthis.emit(\"docSynced\", {\n\t\t\t\t\tdocId,\n\t\t\t\t\tdocument: childDoc,\n\t\t\t\t\tlabel: treeEntry?.label ?? \"\",\n\t\t\t\t\tmeta: treeEntry?.meta,\n\t\t\t\t});\n\t\t\t}\n\n\t\t\tif (this.opts.prefetchFiles && this.fileBlobStore) {\n\t\t\t\tthis._prefetchDocFiles(docId, childDoc).catch(() => null);\n\t\t\t}\n\n\t\t\t// Use the tree's updatedAt so lastSynced >= updatedAt, preventing\n\t\t\t// the observer's timestamp write from triggering a spurious re-sync.\n\t\t\tconst treeEntry = treeMap.get(docId);\n\t\t\tconst treeUpdatedAt = treeEntry?.updatedAt ?? treeEntry?.createdAt ?? 0;\n\t\t\treturn {\n\t\t\t\tdocId,\n\t\t\t\tstatus: \"synced\",\n\t\t\t\tlastSynced: Math.max(Date.now(), treeUpdatedAt),\n\t\t\t\tconsecutiveFailures: 0,\n\t\t\t\tisE2E: true,\n\t\t\t};\n\t\t} finally {\n\t\t\tchildProvider.destroy();\n\t\t}\n\t}\n\n\t/**\n\t * Wait for a provider to emit the \"synced\" event (with state=true),\n\t * timing out after opts.syncTimeout ms.\n\t */\n\tprivate _waitForSynced(provider: any): Promise<void> {\n\t\t// If already synced, resolve immediately\n\t\tif (provider.synced === true) return Promise.resolve();\n\n\t\treturn new Promise<void>((resolve, reject) => {\n\t\t\tconst timer = setTimeout(() => {\n\t\t\t\tprovider.off(\"synced\", onSynced);\n\t\t\t\treject(new Error(`Sync timeout after ${this.opts.syncTimeout}ms`));\n\t\t\t}, this.opts.syncTimeout);\n\n\t\t\tfunction onSynced(state: boolean | { state: boolean }) {\n\t\t\t\t// Hocuspocus passes `{ state }` or a boolean directly\n\t\t\t\tconst synced =\n\t\t\t\t\ttypeof state === \"boolean\" ? state : (state as any)?.state ?? state;\n\t\t\t\tif (synced) {\n\t\t\t\t\tclearTimeout(timer);\n\t\t\t\t\tprovider.off(\"synced\", onSynced);\n\t\t\t\t\tresolve();\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tprovider.on(\"synced\", onSynced);\n\t\t});\n\t}\n\n\t/**\n\t * Pre-cache all cover images referenced in the root tree map.\n\t */\n\tprivate async _prefetchCovers(entries: Array<[string, any]>): Promise<void> {\n\t\tif (!this.fileBlobStore) return;\n\t\tfor (const [docId, v] of entries) {\n\t\t\tconst coverUploadId = v?.meta?.coverUploadId;\n\t\t\tif (coverUploadId) {\n\t\t\t\tthis.fileBlobStore.getBlobUrl(docId, coverUploadId).catch(() => null);\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Pre-cache file blobs referenced in a synced Y.Doc.\n\t * Walks:\n\t * - ydoc.getXmlFragment('default') for `fileBlock` nodes (TipTap)\n\t * - ydoc.getMap('doc-tree') for meta.coverUploadId entries\n\t */\n\tprivate async _prefetchDocFiles(\n\t\tdocId: string,\n\t\tydoc: Y.Doc,\n\t): Promise<void> {\n\t\tif (!this.fileBlobStore) return;\n\n\t\tconst refs = this._extractFileRefs(ydoc);\n\t\tfor (const { refDocId, uploadId } of refs) {\n\t\t\tthis.fileBlobStore\n\t\t\t\t.getBlobUrl(refDocId ?? docId, uploadId)\n\t\t\t\t.catch(() => null);\n\t\t}\n\t}\n\n\tprivate _extractFileRefs(\n\t\tydoc: Y.Doc,\n\t): Array<{ refDocId: string | null; uploadId: string }> {\n\t\tconst refs: Array<{ refDocId: string | null; uploadId: string }> = [];\n\n\t\t// Walk XML fragment for fileBlock nodes\n\t\ttry {\n\t\t\tconst fragment = ydoc.getXmlFragment(\"default\");\n\t\t\tthis._walkXml(fragment, refs);\n\t\t} catch {}\n\n\t\t// Walk doc-tree meta for cover upload IDs\n\t\ttry {\n\t\t\tconst treeMap = ydoc.getMap(\"doc-tree\") as Y.Map<any>;\n\t\t\tfor (const [id, v] of treeMap.entries()) {\n\t\t\t\tconst coverUploadId = v?.meta?.coverUploadId;\n\t\t\t\tif (coverUploadId) {\n\t\t\t\t\trefs.push({ refDocId: id, uploadId: coverUploadId });\n\t\t\t\t}\n\t\t\t}\n\t\t} catch {}\n\n\t\treturn refs;\n\t}\n\n\tprivate _walkXml(\n\t\tnode: Y.XmlFragment | Y.XmlElement,\n\t\trefs: Array<{ refDocId: string | null; uploadId: string }>,\n\t): void {\n\t\tfor (const child of node.toArray()) {\n\t\t\tif (child instanceof Y.XmlElement) {\n\t\t\t\tif (child.nodeName === \"fileBlock\") {\n\t\t\t\t\tconst uploadId = child.getAttribute(\"uploadId\");\n\t\t\t\t\tconst refDocId = child.getAttribute(\"docId\") ?? null;\n\t\t\t\t\tif (uploadId) refs.push({ refDocId, uploadId });\n\t\t\t\t}\n\t\t\t\tthis._walkXml(child, refs);\n\t\t\t}\n\t\t}\n\t}\n}\n","/**\n * ManualSignaling\n *\n * Serverless signaling adapter for WebRTC peer-to-peer connections.\n * Instead of a WebSocket server relaying SDP/ICE, peers exchange\n * offer and answer \"blobs\" out-of-band (QR code, copy-paste, NFC, etc.).\n *\n * Designed as a drop-in replacement for `SignalingSocket` — emits the\n * same events (`welcome`, `joined`, `offer`, `answer`, `ice`) so\n * `AbracadabraWebRTC` can use it transparently.\n *\n * Flow:\n * Device A (initiator):\n * 1. `createOffer()` → gathers ICE candidates → returns offer blob\n * 2. Share blob via QR/paste\n * 3. Receive answer blob → `acceptAnswer(blob)`\n *\n * Device B (responder):\n * 1. Receive offer blob → `acceptOffer(blob)` → returns answer blob\n * 2. Share answer blob via QR/paste\n */\n\nimport EventEmitter from \"../EventEmitter.ts\";\n\nexport interface ManualSignalingBlob {\n\t/** SDP offer or answer. */\n\tsdp: string;\n\t/** Gathered ICE candidates. */\n\tcandidates: string[];\n\t/** Peer ID of the sender. */\n\tpeerId: string;\n}\n\nexport class ManualSignaling extends EventEmitter {\n\tpublic localPeerId: string;\n\tpublic isConnected = false;\n\n\tprivate pc: RTCPeerConnection | null = null;\n\tprivate iceServers: RTCIceServer[];\n\n\tconstructor(iceServers?: RTCIceServer[]) {\n\t\tsuper();\n\t\tthis.localPeerId = crypto.randomUUID();\n\t\tthis.iceServers = iceServers ?? [{ urls: \"stun:stun.l.google.com:19302\" }];\n\t}\n\n\t/**\n\t * Initiator: create an offer blob with gathered ICE candidates.\n\t * Returns a blob to share with the remote peer.\n\t */\n\tasync createOfferBlob(): Promise<ManualSignalingBlob> {\n\t\tthis.pc = new RTCPeerConnection({ iceServers: this.iceServers });\n\t\t// A data channel is required for ICE gathering to produce candidates.\n\t\tthis.pc.createDataChannel(\"manual-signaling\");\n\n\t\tconst candidates: string[] = [];\n\t\tconst gatheringComplete = new Promise<void>((resolve) => {\n\t\t\tthis.pc!.onicecandidate = (event) => {\n\t\t\t\tif (event.candidate) {\n\t\t\t\t\tcandidates.push(JSON.stringify(event.candidate.toJSON()));\n\t\t\t\t} else {\n\t\t\t\t\t// Null candidate = gathering complete.\n\t\t\t\t\tresolve();\n\t\t\t\t}\n\t\t\t};\n\t\t});\n\n\t\tconst offer = await this.pc.createOffer();\n\t\tawait this.pc.setLocalDescription(offer);\n\t\tawait gatheringComplete;\n\n\t\t// Emit welcome (as if we connected to signaling).\n\t\tthis.isConnected = true;\n\t\tthis.emit(\"welcome\", { peerId: this.localPeerId, peers: [] });\n\n\t\treturn {\n\t\t\tsdp: this.pc.localDescription!.sdp,\n\t\t\tcandidates,\n\t\t\tpeerId: this.localPeerId,\n\t\t};\n\t}\n\n\t/**\n\t * Responder: accept an offer blob and create an answer blob.\n\t * The answer blob should be shared back to the initiator.\n\t */\n\tasync acceptOffer(offerBlob: ManualSignalingBlob): Promise<ManualSignalingBlob> {\n\t\tthis.pc = new RTCPeerConnection({ iceServers: this.iceServers });\n\t\tthis.pc.createDataChannel(\"manual-signaling\");\n\n\t\tconst candidates: string[] = [];\n\t\tconst gatheringComplete = new Promise<void>((resolve) => {\n\t\t\tthis.pc!.onicecandidate = (event) => {\n\t\t\t\tif (event.candidate) {\n\t\t\t\t\tcandidates.push(JSON.stringify(event.candidate.toJSON()));\n\t\t\t\t} else {\n\t\t\t\t\tresolve();\n\t\t\t\t}\n\t\t\t};\n\t\t});\n\n\t\t// Set remote offer.\n\t\tawait this.pc.setRemoteDescription(\n\t\t\tnew RTCSessionDescription({ type: \"offer\", sdp: offerBlob.sdp }),\n\t\t);\n\n\t\t// Add remote ICE candidates.\n\t\tfor (const c of offerBlob.candidates) {\n\t\t\ttry {\n\t\t\t\tawait this.pc.addIceCandidate(new RTCIceCandidate(JSON.parse(c)));\n\t\t\t} catch {\n\t\t\t\t// Skip malformed ICE candidate\n\t\t\t}\n\t\t}\n\n\t\t// Create answer.\n\t\tconst answer = await this.pc.createAnswer();\n\t\tawait this.pc.setLocalDescription(answer);\n\t\tawait gatheringComplete;\n\n\t\t// Emit welcome + joined (remote peer from the offer).\n\t\tthis.isConnected = true;\n\t\tthis.emit(\"welcome\", { peerId: this.localPeerId, peers: [] });\n\t\tthis.emit(\"joined\", {\n\t\t\tpeer_id: offerBlob.peerId,\n\t\t\tuser_id: offerBlob.peerId,\n\t\t\tmuted: false,\n\t\t\tvideo: false,\n\t\t\tscreen: false,\n\t\t\tname: null,\n\t\t\tcolor: null,\n\t\t});\n\n\t\t// Emit the offer so AbracadabraWebRTC handles it.\n\t\tthis.emit(\"offer\", { from: offerBlob.peerId, sdp: offerBlob.sdp });\n\n\t\t// Feed ICE candidates.\n\t\tfor (const c of offerBlob.candidates) {\n\t\t\tthis.emit(\"ice\", { from: offerBlob.peerId, candidate: c });\n\t\t}\n\n\t\treturn {\n\t\t\tsdp: this.pc.localDescription!.sdp,\n\t\t\tcandidates,\n\t\t\tpeerId: this.localPeerId,\n\t\t};\n\t}\n\n\t/**\n\t * Initiator: accept the answer blob from the responder.\n\t * Completes the connection.\n\t */\n\tasync acceptAnswer(answerBlob: ManualSignalingBlob): Promise<void> {\n\t\tif (!this.pc) throw new Error(\"Call createOfferBlob() first\");\n\n\t\t// Emit joined for the remote peer.\n\t\tthis.emit(\"joined\", {\n\t\t\tpeer_id: answerBlob.peerId,\n\t\t\tuser_id: answerBlob.peerId,\n\t\t\tmuted: false,\n\t\t\tvideo: false,\n\t\t\tscreen: false,\n\t\t\tname: null,\n\t\t\tcolor: null,\n\t\t});\n\n\t\t// Emit the answer so AbracadabraWebRTC handles it.\n\t\tthis.emit(\"answer\", { from: answerBlob.peerId, sdp: answerBlob.sdp });\n\n\t\t// Feed ICE candidates.\n\t\tfor (const c of answerBlob.candidates) {\n\t\t\tthis.emit(\"ice\", { from: answerBlob.peerId, candidate: c });\n\t\t}\n\t}\n\n\t// ── SignalingSocket-compatible stubs ─────────────────────────────────────\n\t// These are no-ops since manual signaling doesn't relay through a server.\n\n\tsendOffer(_to: string, _sdp: string): void {}\n\tsendAnswer(_to: string, _sdp: string): void {}\n\tsendIce(_to: string, _candidate: string): void {}\n\tsendMute(_muted: boolean): void {}\n\tsendMediaState(_video: boolean, _screen: boolean): void {}\n\tsendProfile(_name: string, _color: string): void {}\n\tsendLeave(): void {}\n\n\tasync connect(): Promise<void> {\n\t\t// No-op — connection is initiated via createOfferBlob() or acceptOffer().\n\t}\n\n\tdisconnect(): void {\n\t\tthis.isConnected = false;\n\t\tif (this.pc) {\n\t\t\tthis.pc.close();\n\t\t\tthis.pc = null;\n\t\t}\n\t\tthis.emit(\"disconnected\");\n\t}\n\n\tdestroy(): void {\n\t\tthis.disconnect();\n\t\tthis.removeAllListeners();\n\t}\n}\n","/**\n * DevicePairingChannel\n *\n * Enables cross-device identity pairing over an E2EE WebRTC data channel.\n * Device A (approver) creates a pairing session with a short code. Device B\n * (requester) joins with the code. After E2EE is established, Device B sends\n * its public key and Device A registers it via `addKey()`.\n *\n * Reuses the existing WebRTC stack: SignalingSocket, PeerConnection,\n * DataChannelRouter, and E2EEChannel (X25519 ECDH + AES-256-GCM).\n */\n\nimport { sha256 } from \"@noble/hashes/sha2.js\";\nimport EventEmitter from \"../EventEmitter.ts\";\nimport { AbracadabraClient } from \"../AbracadabraClient.ts\";\nimport { AbracadabraWebRTC } from \"./AbracadabraWebRTC.ts\";\nimport type { E2EEIdentity } from \"./E2EEChannel.ts\";\n\n// ── Constants ───────────────────────────────────────────────────────────────\n\n/** Ambiguity-free charset (no 0/O/1/I). */\nconst CODE_CHARSET = \"ABCDEFGHJKLMNPQRSTUVWXYZ23456789\";\nconst CODE_LENGTH = 6;\nconst PAIRING_TIMEOUT_MS = 5 * 60 * 1000; // 5 minutes\nconst SIGNALING_CONNECT_TIMEOUT_MS = 5_000; // 5 seconds before trying fallback\nconst PAIRING_CHANNEL = \"device-pairing\";\n\n// ── Types ───────────────────────────────────────────────────────────────────\n\nexport interface DevicePairingConfig {\n\t/** Server base URL (http/https). */\n\tserverUrl: string;\n\t/**\n\t * JWT token or async token factory for signaling auth.\n\t * When omitted, a short-lived anonymous pairing token is fetched automatically\n\t * from `POST /auth/pairing-token`.\n\t */\n\ttoken?: string | (() => string) | (() => Promise<string>);\n\t/** E2EE identity (Ed25519 public key + X25519 private key). */\n\te2ee: E2EEIdentity;\n\t/** ICE servers. Defaults to Google STUN. */\n\ticeServers?: RTCIceServer[];\n\t/**\n\t * Fallback signaling server URL. If the primary server is unreachable,\n\t * signaling will retry through this server. The actual pairing data is\n\t * E2EE-encrypted, so the relay server cannot read it.\n\t */\n\tfallbackSignalingUrl?: string;\n\t/** WebSocket polyfill (for Node.js). */\n\tWebSocketPolyfill?: any;\n}\n\nexport interface PairingRequest {\n\t/** Device B's Ed25519 public key (base64url). */\n\tpublicKey: string;\n\t/** Device B's X25519 public key (base64url). */\n\tx25519Key: string;\n\t/** Human-readable device label. */\n\tdeviceName: string;\n}\n\nexport interface PairingResult {\n\tsuccess: boolean;\n\terror?: string;\n}\n\ntype PairingRole = \"approver\" | \"requester\";\n\n// ── Internal wire messages ──────────────────────────────────────────────────\n\ninterface PairRequestMsg {\n\ttype: \"pair-request\";\n\tpublicKey: string;\n\tx25519Key: string;\n\tdeviceName: string;\n}\n\ninterface PairApprovedMsg {\n\ttype: \"pair-approved\";\n\t/** Approver's account-level Ed25519 public key (base64url). */\n\tmasterPublicKey?: string;\n}\n\ninterface PairInviteCodeMsg {\n\ttype: \"pair-invite-code\";\n\tcode: string;\n\t/** Approver's account-level Ed25519 public key (base64url). */\n\tmasterPublicKey?: string;\n}\n\ninterface PairRejectedMsg {\n\ttype: \"pair-rejected\";\n\treason: string;\n}\n\ntype PairingMsg = PairRequestMsg | PairApprovedMsg | PairRejectedMsg | PairInviteCodeMsg;\n\n// ── Helpers ─────────────────────────────────────────────────────────────────\n\nfunction generatePairingCode(): string {\n\tconst bytes = crypto.getRandomValues(new Uint8Array(CODE_LENGTH));\n\treturn Array.from(bytes)\n\t\t.map((b) => CODE_CHARSET[b % CODE_CHARSET.length])\n\t\t.join(\"\");\n}\n\nfunction codeToRoomId(code: string): string {\n\tconst hash = sha256(new TextEncoder().encode(code.toUpperCase()));\n\t// Take first 16 hex chars for the room ID.\n\tconst hex = Array.from(hash.slice(0, 8))\n\t\t.map((b) => b.toString(16).padStart(2, \"0\"))\n\t\t.join(\"\");\n\treturn `__pairing_${hex}`;\n}\n\n// ── DevicePairingChannel ────────────────────────────────────────────────────\n\nexport class DevicePairingChannel extends EventEmitter {\n\tprivate webrtc: AbracadabraWebRTC | null = null;\n\tprivate timeoutHandle: ReturnType<typeof setTimeout> | null = null;\n\tprivate _destroyed = false;\n\tprivate _pendingRequest: PairingRequest | null = null;\n\tprivate _connectedPeerId: string | null = null;\n\tprivate _usingFallback = false;\n\tprivate _resolvedIceServers: RTCIceServer[] | undefined;\n\n\treadonly role: PairingRole;\n\treadonly pairingCode: string;\n\n\tprivate constructor(\n\t\trole: PairingRole,\n\t\tpairingCode: string,\n\t\tprivate readonly config: DevicePairingConfig,\n\t) {\n\t\tsuper();\n\t\tthis.role = role;\n\t\tthis.pairingCode = pairingCode;\n\t}\n\n\t// ── Factory Methods ───────────────────────────────────────────────────\n\n\t/**\n\t * Create an approver session (Device A). Returns the channel and a\n\t * 6-character pairing code to share with Device B.\n\t */\n\tstatic createApprover(config: DevicePairingConfig): {\n\t\tchannel: DevicePairingChannel;\n\t\tpairingCode: string;\n\t} {\n\t\tconst code = generatePairingCode();\n\t\tconst channel = new DevicePairingChannel(\"approver\", code, config);\n\t\tchannel.start();\n\t\treturn { channel, pairingCode: code };\n\t}\n\n\t/**\n\t * Create a requester session (Device B). Joins with a pairing code\n\t * obtained from Device A.\n\t */\n\tstatic createRequester(\n\t\tconfig: DevicePairingConfig,\n\t\tpairingCode: string,\n\t): DevicePairingChannel {\n\t\tconst channel = new DevicePairingChannel(\n\t\t\t\"requester\",\n\t\t\tpairingCode.toUpperCase().replace(/[^A-Z2-9]/g, \"\"),\n\t\t\tconfig,\n\t\t);\n\t\tchannel.start();\n\t\treturn channel;\n\t}\n\n\t// ── Approver API ──────────────────────────────────────────────────────\n\n\t/**\n\t * Approve the pending pairing request. Calls `client.addKey()` to\n\t * register Device B's public key, then notifies Device B.\n\t *\n\t * @param client Authenticated REST client.\n\t * @param masterPublicKey Approver's account-level Ed25519 public key (base64url).\n\t * Sent to Device B so it can adopt the master's identity doc.\n\t */\n\tasync approve(client: AbracadabraClient, masterPublicKey?: string): Promise<PairingResult> {\n\t\tif (this.role !== \"approver\") {\n\t\t\treturn { success: false, error: \"Only the approver can approve\" };\n\t\t}\n\t\tif (!this._pendingRequest) {\n\t\t\treturn { success: false, error: \"No pending pairing request\" };\n\t\t}\n\t\tif (!this._connectedPeerId) {\n\t\t\treturn { success: false, error: \"Peer not connected\" };\n\t\t}\n\n\t\tconst req = this._pendingRequest;\n\n\t\ttry {\n\t\t\tawait client.addKey({\n\t\t\t\tpublicKey: req.publicKey,\n\t\t\t\tdeviceName: req.deviceName,\n\t\t\t\tx25519Key: req.x25519Key,\n\t\t\t});\n\n\t\t\tthis.sendMessage({ type: \"pair-approved\", masterPublicKey });\n\t\t\tthis._pendingRequest = null;\n\t\t\tthis.emit(\"pairingComplete\", { success: true } as PairingResult);\n\t\t\treturn { success: true };\n\t\t} catch (err: any) {\n\t\t\tconst error = err?.message ?? \"Failed to register device key\";\n\t\t\tthis.sendMessage({ type: \"pair-rejected\", reason: error });\n\t\t\tthis._pendingRequest = null;\n\t\t\tconst result: PairingResult = { success: false, error };\n\t\t\tthis.emit(\"pairingComplete\", result);\n\t\t\treturn result;\n\t\t}\n\t}\n\n\t/**\n\t * Approve via server-side device invite. Creates a single-use invite code\n\t * and sends it to Device B over the E2EE channel. Device B redeems it\n\t * independently via HTTP — Device A can go offline after this.\n\t *\n\t * @param client Authenticated REST client.\n\t * @param masterPublicKey Approver's account-level Ed25519 public key (base64url).\n\t * Sent to Device B so it can adopt the master's identity doc.\n\t */\n\tasync approveWithInvite(client: AbracadabraClient, masterPublicKey?: string): Promise<PairingResult> {\n\t\tif (this.role !== \"approver\") {\n\t\t\treturn { success: false, error: \"Only the approver can approve\" };\n\t\t}\n\t\tif (!this._pendingRequest) {\n\t\t\treturn { success: false, error: \"No pending pairing request\" };\n\t\t}\n\t\tif (!this._connectedPeerId) {\n\t\t\treturn { success: false, error: \"Peer not connected\" };\n\t\t}\n\n\t\ttry {\n\t\t\tconst { code } = await client.createDeviceInvite();\n\t\t\tthis.sendMessage({ type: \"pair-invite-code\", code, masterPublicKey });\n\t\t\tthis._pendingRequest = null;\n\t\t\tthis.emit(\"pairingComplete\", { success: true } as PairingResult);\n\t\t\treturn { success: true };\n\t\t} catch (err: any) {\n\t\t\tconst error = err?.message ?? \"Failed to create device invite\";\n\t\t\tthis.sendMessage({ type: \"pair-rejected\", reason: error });\n\t\t\tthis._pendingRequest = null;\n\t\t\tconst result: PairingResult = { success: false, error };\n\t\t\tthis.emit(\"pairingComplete\", result);\n\t\t\treturn result;\n\t\t}\n\t}\n\n\t/**\n\t * Reject the pending pairing request.\n\t */\n\treject(reason = \"Rejected by user\"): void {\n\t\tif (this.role !== \"approver\" || !this._pendingRequest) return;\n\t\tthis.sendMessage({ type: \"pair-rejected\", reason });\n\t\tthis._pendingRequest = null;\n\t\tthis.emit(\"pairingComplete\", {\n\t\t\tsuccess: false,\n\t\t\terror: reason,\n\t\t} as PairingResult);\n\t}\n\n\t// ── Requester API ─────────────────────────────────────────────────────\n\n\t/**\n\t * Send a pairing request to Device A. Call this after the \"connected\"\n\t * event fires.\n\t */\n\trequestPairing(request: PairingRequest): void {\n\t\tif (this.role !== \"requester\") return;\n\t\tthis.sendMessage({\n\t\t\ttype: \"pair-request\",\n\t\t\tpublicKey: request.publicKey,\n\t\t\tx25519Key: request.x25519Key,\n\t\t\tdeviceName: request.deviceName,\n\t\t});\n\t}\n\n\t// ── Lifecycle ─────────────────────────────────────────────────────────\n\n\tget isDestroyed(): boolean {\n\t\treturn this._destroyed;\n\t}\n\n\tdestroy(): void {\n\t\tif (this._destroyed) return;\n\t\tthis._destroyed = true;\n\n\t\tif (this.timeoutHandle) {\n\t\t\tclearTimeout(this.timeoutHandle);\n\t\t\tthis.timeoutHandle = null;\n\t\t}\n\n\t\tif (this.webrtc) {\n\t\t\tthis.webrtc.destroy();\n\t\t\tthis.webrtc = null;\n\t\t}\n\n\t\tthis.removeAllListeners();\n\t}\n\n\t// ── Private ─────────────────────────────────────────────────────────\n\n\tprivate async resolveToken(\n\t\tserverUrl?: string,\n\t): Promise<string | (() => string) | (() => Promise<string>)> {\n\t\t// Use provided token if connecting to the primary server.\n\t\tif (this.config.token && serverUrl === this.config.serverUrl) {\n\t\t\treturn this.config.token;\n\t\t}\n\n\t\t// Fetch a short-lived anonymous pairing token from the target server.\n\t\tlet base = serverUrl ?? this.config.serverUrl;\n\t\twhile (base.endsWith(\"/\")) base = base.slice(0, -1);\n\t\tconst resp = await fetch(`${base}/auth/pairing-token`, {\n\t\t\tmethod: \"POST\",\n\t\t});\n\t\tif (!resp.ok) {\n\t\t\tthrow new Error(\n\t\t\t\t`Failed to fetch pairing token: ${resp.status} ${resp.statusText}`,\n\t\t\t);\n\t\t}\n\t\tconst { token } = (await resp.json()) as { token: string };\n\t\treturn token;\n\t}\n\n\tprivate start(): void {\n\t\tthis.connectToServer(this.config.serverUrl);\n\n\t\t// Auto-destroy after timeout.\n\t\tthis.timeoutHandle = setTimeout(() => {\n\t\t\tif (!this._destroyed) {\n\t\t\t\tthis.emit(\"error\", new Error(\"Pairing timed out\"));\n\t\t\t\tthis.destroy();\n\t\t\t}\n\t\t}, PAIRING_TIMEOUT_MS);\n\t}\n\n\tprivate connectToServer(serverUrl: string, signalingUrl?: string): void {\n\t\tconst roomId = codeToRoomId(this.pairingCode);\n\n\t\t// Resolve token (possibly async) — uses a factory so SignalingSocket can await it.\n\t\tconst tokenPromise = this.resolveToken(serverUrl);\n\t\tconst tokenFactory = async (): Promise<string> => {\n\t\t\tconst t = await tokenPromise;\n\t\t\tif (typeof t === \"function\") return await t();\n\t\t\treturn t;\n\t\t};\n\n\t\t// Fetch ICE servers from the target server if none configured.\n\t\tif (!this.config.iceServers) {\n\t\t\tconst client = new AbracadabraClient({ url: serverUrl });\n\t\t\tclient.getIceServers().then((servers) => {\n\t\t\t\tif (servers.length > 0) this._resolvedIceServers = servers;\n\t\t\t});\n\t\t}\n\n\t\tthis.webrtc = new AbracadabraWebRTC({\n\t\t\tdocId: roomId,\n\t\t\turl: serverUrl,\n\t\t\tsignalingUrl: signalingUrl ?? undefined,\n\t\t\ttoken: tokenFactory,\n\t\t\ticeServers: this.config.iceServers ?? this._resolvedIceServers,\n\t\t\te2ee: this.config.e2ee,\n\t\t\tenableDocSync: false,\n\t\t\tenableAwarenessSync: false,\n\t\t\tenableFileTransfer: false,\n\t\t\tautoConnect: false,\n\t\t\tWebSocketPolyfill: this.config.WebSocketPolyfill,\n\t\t});\n\n\t\tlet connected = false;\n\n\t\tthis.webrtc.on(\"connected\", () => {\n\t\t\tconnected = true;\n\t\t});\n\n\t\tthis.webrtc.on(\"e2eeEstablished\", ({ peerId }: { peerId: string }) => {\n\t\t\tthis._connectedPeerId = peerId;\n\t\t\tthis.emit(\"connected\");\n\t\t});\n\n\t\tthis.webrtc.on(\n\t\t\t\"customMessage\",\n\t\t\t({ peerId, payload }: { peerId: string; payload: string }) => {\n\t\t\t\tthis.handleMessage(peerId, payload);\n\t\t\t},\n\t\t);\n\n\t\tthis.webrtc.on(\"e2eeFailed\", ({ peerId, error }: { peerId: string; error: any }) => {\n\t\t\tif (!this._destroyed) {\n\t\t\t\tthis.emit(\"error\", new Error(`E2EE failed: ${error?.message ?? error}`));\n\t\t\t}\n\t\t});\n\n\t\tthis.webrtc.on(\"error\", (err: any) => {\n\t\t\tif (!this._destroyed) {\n\t\t\t\tthis.emit(\"error\", new Error(`WebRTC: ${err?.type ?? err?.message ?? \"unknown\"}`));\n\t\t\t}\n\t\t});\n\n\t\tthis.webrtc.on(\"peerLeft\", () => {\n\t\t\tif (!this._destroyed) {\n\t\t\t\tthis.emit(\"error\", new Error(\"Peer disconnected\"));\n\t\t\t}\n\t\t});\n\n\t\tthis.webrtc.on(\n\t\t\t\"signalingError\",\n\t\t\t(err: { code: string; message: string }) => {\n\t\t\t\tthis.emit(\"error\", new Error(`Signaling: ${err.message}`));\n\t\t\t},\n\t\t);\n\n\t\t// If a fallback signaling server is configured, try it after a timeout.\n\t\tif (this.config.fallbackSignalingUrl && !signalingUrl) {\n\t\t\tconst fallbackTimer = setTimeout(() => {\n\t\t\t\tif (this._destroyed || connected) return;\n\t\t\t\t// Primary server didn't connect in time — try fallback.\n\t\t\t\tif (this.webrtc) {\n\t\t\t\t\tthis.webrtc.destroy();\n\t\t\t\t\tthis.webrtc = null;\n\t\t\t\t}\n\t\t\t\tthis._usingFallback = true;\n\t\t\t\tthis.emit(\"fallback\", { url: this.config.fallbackSignalingUrl });\n\t\t\t\tthis.connectToServer(\n\t\t\t\t\tthis.config.fallbackSignalingUrl!,\n\t\t\t\t);\n\t\t\t}, SIGNALING_CONNECT_TIMEOUT_MS);\n\n\t\t\t// Clear fallback timer if primary succeeds.\n\t\t\tthis.webrtc.on(\"connected\", () => clearTimeout(fallbackTimer));\n\t\t}\n\n\t\tthis.webrtc.connect();\n\t}\n\n\t/** Whether the connection fell back to the fallback signaling server. */\n\tget usingFallback(): boolean {\n\t\treturn this._usingFallback;\n\t}\n\n\tprivate sendMessage(msg: PairingMsg): void {\n\t\tif (!this.webrtc || !this._connectedPeerId) return;\n\t\t// Send via the custom message path — the E2EE layer on the data channel\n\t\t// encrypts all non-key-exchange traffic via the DataChannelRouter.\n\t\tthis.webrtc.sendCustomMessage(\n\t\t\tthis._connectedPeerId,\n\t\t\tJSON.stringify(msg),\n\t\t);\n\t}\n\n\tprivate handleMessage(peerId: string, payload: string): void {\n\t\tlet msg: PairingMsg;\n\t\ttry {\n\t\t\tmsg = JSON.parse(payload);\n\t\t} catch {\n\t\t\treturn;\n\t\t}\n\n\t\tswitch (msg.type) {\n\t\t\tcase \"pair-request\":\n\t\t\t\tif (this.role !== \"approver\") return;\n\t\t\t\tthis._pendingRequest = {\n\t\t\t\t\tpublicKey: msg.publicKey,\n\t\t\t\t\tx25519Key: msg.x25519Key,\n\t\t\t\t\tdeviceName: msg.deviceName,\n\t\t\t\t};\n\t\t\t\tthis.emit(\"pairingRequest\", this._pendingRequest);\n\t\t\t\tbreak;\n\n\t\t\tcase \"pair-approved\":\n\t\t\t\tif (this.role !== \"requester\") return;\n\t\t\t\tthis.emit(\"approved\", { masterPublicKey: msg.masterPublicKey });\n\t\t\t\tthis.emit(\"pairingComplete\", { success: true } as PairingResult);\n\t\t\t\tbreak;\n\n\t\t\tcase \"pair-rejected\":\n\t\t\t\tif (this.role !== \"requester\") return;\n\t\t\t\tthis.emit(\"rejected\", msg.reason);\n\t\t\t\tthis.emit(\"pairingComplete\", {\n\t\t\t\t\tsuccess: false,\n\t\t\t\t\terror: msg.reason,\n\t\t\t\t} as PairingResult);\n\t\t\t\tbreak;\n\n\t\t\tcase \"pair-invite-code\":\n\t\t\t\tif (this.role !== \"requester\") return;\n\t\t\t\tthis.emit(\"inviteCode\", msg.code, msg.masterPublicKey);\n\t\t\t\tbreak;\n\t\t}\n\t}\n}\n","import * as Y from \"yjs\";\nimport * as syncProtocol from \"y-protocols/sync\";\nimport {\n\tencodeAwarenessUpdate,\n\tapplyAwarenessUpdate,\n\ttype Awareness,\n} from \"y-protocols/awareness\";\nimport * as encoding from \"lib0/encoding\";\nimport * as decoding from \"lib0/decoding\";\nimport EventEmitter from \"../EventEmitter.ts\";\n\n/**\n * Cross-tab Y.js document and awareness sync via the BroadcastChannel API.\n *\n * Opens a BroadcastChannel per document, relays Y.js updates and awareness\n * state between tabs on the same origin. No server, no WebRTC — just same-device\n * multi-tab sync. Same-origin means same trust boundary, so no encryption needed.\n *\n * Uses the same y-protocols/sync encoding as `YjsDataChannel` for consistency.\n */\n\nconst CHANNEL_PREFIX = \"abra:sync:\";\n\n/** Message type discriminators (first byte). */\nconst MSG = {\n\tSYNC: 0x00,\n\tUPDATE: 0x01,\n\tAWARENESS: 0x02,\n\t/** Request all tabs to respond with SyncStep1. */\n\tQUERY_PEERS: 0x03,\n} as const;\n\nexport class BroadcastChannelSync extends EventEmitter {\n\tprivate channel: BroadcastChannel | null = null;\n\tprivate docUpdateHandler: ((update: Uint8Array, origin: any) => void) | null =\n\t\tnull;\n\tprivate awarenessUpdateHandler:\n\t\t| ((\n\t\t\t\tchanges: { added: number[]; updated: number[]; removed: number[] },\n\t\t\t\torigin: any,\n\t\t\t) => void)\n\t\t| null = null;\n\tprivate destroyed = false;\n\n\tconstructor(\n\t\tprivate readonly document: Y.Doc,\n\t\tprivate readonly awareness: Awareness | null,\n\t\tprivate readonly channelName: string,\n\t) {\n\t\tsuper();\n\t}\n\n\t/** Convenience factory using standard channel naming. */\n\tstatic forDoc(\n\t\tdocument: Y.Doc,\n\t\tdocId: string,\n\t\tawareness?: Awareness | null,\n\t): BroadcastChannelSync {\n\t\treturn new BroadcastChannelSync(\n\t\t\tdocument,\n\t\t\tawareness ?? null,\n\t\t\t`${CHANNEL_PREFIX}${docId}`,\n\t\t);\n\t}\n\n\t/** Start syncing. Opens the BroadcastChannel and initiates a sync handshake. */\n\tconnect(): void {\n\t\tif (this.destroyed || this.channel) return;\n\n\t\tif (typeof globalThis.BroadcastChannel === \"undefined\") {\n\t\t\t// Environment doesn't support BroadcastChannel (e.g. some Node.js builds).\n\t\t\treturn;\n\t\t}\n\n\t\tthis.channel = new BroadcastChannel(this.channelName);\n\t\tthis.channel.onmessage = (event) => this.handleMessage(event.data);\n\n\t\t// Listen for local doc updates → broadcast to other tabs.\n\t\tthis.docUpdateHandler = (update: Uint8Array, origin: any) => {\n\t\t\tif (origin === this) return; // Don't echo.\n\t\t\tthis.broadcastUpdate(update);\n\t\t};\n\t\tthis.document.on(\"update\", this.docUpdateHandler);\n\n\t\t// Listen for local awareness changes → broadcast to other tabs.\n\t\tif (this.awareness) {\n\t\t\tthis.awarenessUpdateHandler = (\n\t\t\t\t{\n\t\t\t\t\tadded,\n\t\t\t\t\tupdated,\n\t\t\t\t\tremoved,\n\t\t\t\t}: { added: number[]; updated: number[]; removed: number[] },\n\t\t\t\t_origin: any,\n\t\t\t) => {\n\t\t\t\tconst changedClients = added.concat(updated).concat(removed);\n\t\t\t\tconst update = encodeAwarenessUpdate(this.awareness!, changedClients);\n\t\t\t\tthis.broadcastAwareness(update);\n\t\t\t};\n\t\t\tthis.awareness.on(\"update\", this.awarenessUpdateHandler);\n\t\t}\n\n\t\t// Announce presence — other tabs reply with SyncStep1.\n\t\tthis.broadcastQueryPeers();\n\n\t\t// Send our SyncStep1 to trigger state exchange.\n\t\tthis.sendSyncStep1();\n\n\t\tthis.emit(\"connected\");\n\t}\n\n\t/** Stop syncing and close the BroadcastChannel. */\n\tdisconnect(): void {\n\t\tif (this.docUpdateHandler) {\n\t\t\tthis.document.off(\"update\", this.docUpdateHandler);\n\t\t\tthis.docUpdateHandler = null;\n\t\t}\n\t\tif (this.awarenessUpdateHandler && this.awareness) {\n\t\t\tthis.awareness.off(\"update\", this.awarenessUpdateHandler);\n\t\t\tthis.awarenessUpdateHandler = null;\n\t\t}\n\t\tif (this.channel) {\n\t\t\tthis.channel.close();\n\t\t\tthis.channel = null;\n\t\t}\n\t\tthis.emit(\"disconnected\");\n\t}\n\n\t/** Disconnect and prevent reconnection. */\n\tdestroy(): void {\n\t\tthis.disconnect();\n\t\tthis.destroyed = true;\n\t\tthis.removeAllListeners();\n\t}\n\n\t// ── Outgoing ────────────────────────────────────────────────────────────\n\n\tprivate broadcastUpdate(update: Uint8Array): void {\n\t\tif (!this.channel) return;\n\t\tconst encoder = encoding.createEncoder();\n\t\tencoding.writeVarUint(encoder, MSG.UPDATE);\n\t\tencoding.writeVarUint8Array(encoder, update);\n\t\tthis.channel.postMessage(encoding.toUint8Array(encoder));\n\t}\n\n\tprivate broadcastAwareness(update: Uint8Array): void {\n\t\tif (!this.channel) return;\n\t\tconst encoder = encoding.createEncoder();\n\t\tencoding.writeVarUint(encoder, MSG.AWARENESS);\n\t\tencoding.writeVarUint8Array(encoder, update);\n\t\tthis.channel.postMessage(encoding.toUint8Array(encoder));\n\t}\n\n\tprivate sendSyncStep1(): void {\n\t\tif (!this.channel) return;\n\t\tconst encoder = encoding.createEncoder();\n\t\tencoding.writeVarUint(encoder, MSG.SYNC);\n\t\tsyncProtocol.writeSyncStep1(encoder, this.document);\n\t\tthis.channel.postMessage(encoding.toUint8Array(encoder));\n\t}\n\n\tprivate broadcastQueryPeers(): void {\n\t\tif (!this.channel) return;\n\t\tconst encoder = encoding.createEncoder();\n\t\tencoding.writeVarUint(encoder, MSG.QUERY_PEERS);\n\t\tthis.channel.postMessage(encoding.toUint8Array(encoder));\n\t}\n\n\t// ── Incoming ────────────────────────────────────────────────────────────\n\n\tprivate handleMessage(data: any): void {\n\t\tif (!(data instanceof ArrayBuffer || data instanceof Uint8Array)) return;\n\t\tconst buf = data instanceof ArrayBuffer ? new Uint8Array(data) : data;\n\t\tconst decoder = decoding.createDecoder(buf);\n\t\tconst msgType = decoding.readVarUint(decoder);\n\n\t\tswitch (msgType) {\n\t\t\tcase MSG.SYNC:\n\t\t\t\tthis.handleSyncMessage(decoder);\n\t\t\t\tbreak;\n\t\t\tcase MSG.UPDATE:\n\t\t\t\tthis.handleUpdateMessage(decoder);\n\t\t\t\tbreak;\n\t\t\tcase MSG.AWARENESS:\n\t\t\t\tthis.handleAwarenessMessage(decoder);\n\t\t\t\tbreak;\n\t\t\tcase MSG.QUERY_PEERS:\n\t\t\t\t// Another tab joined — respond with our SyncStep1.\n\t\t\t\tthis.sendSyncStep1();\n\t\t\t\tif (this.awareness) {\n\t\t\t\t\tconst update = encodeAwarenessUpdate(\n\t\t\t\t\t\tthis.awareness,\n\t\t\t\t\t\tArray.from(this.awareness.getStates().keys()),\n\t\t\t\t\t);\n\t\t\t\t\tthis.broadcastAwareness(update);\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t}\n\t}\n\n\tprivate handleSyncMessage(decoder: decoding.Decoder): void {\n\t\tconst encoder = encoding.createEncoder();\n\t\tconst syncMessageType = syncProtocol.readSyncMessage(\n\t\t\tdecoder,\n\t\t\tencoder,\n\t\t\tthis.document,\n\t\t\tthis,\n\t\t);\n\n\t\t// If the sync protocol generated a response (SyncStep2), broadcast it.\n\t\tif (encoding.length(encoder) > 0) {\n\t\t\tconst responseEncoder = encoding.createEncoder();\n\t\t\tencoding.writeVarUint(responseEncoder, MSG.SYNC);\n\t\t\tencoding.writeUint8Array(\n\t\t\t\tresponseEncoder,\n\t\t\t\tencoding.toUint8Array(encoder),\n\t\t\t);\n\t\t\tthis.channel?.postMessage(encoding.toUint8Array(responseEncoder));\n\t\t}\n\n\t\tif (syncMessageType === syncProtocol.messageYjsSyncStep2) {\n\t\t\tthis.emit(\"synced\");\n\t\t}\n\t}\n\n\tprivate handleUpdateMessage(decoder: decoding.Decoder): void {\n\t\tconst update = decoding.readVarUint8Array(decoder);\n\t\tY.applyUpdate(this.document, update, this);\n\t}\n\n\tprivate handleAwarenessMessage(decoder: decoding.Decoder): void {\n\t\tif (!this.awareness) return;\n\t\tconst update = decoding.readVarUint8Array(decoder);\n\t\tapplyAwarenessUpdate(this.awareness, update, this);\n\t}\n}\n","import type * as Y from \"yjs\";\nimport { AbracadabraClient } from \"./AbracadabraClient.ts\";\nimport type { IdentityDocProvider } from \"./IdentityDoc.ts\";\nimport type { PublicKeyInfo } from \"./types.ts\";\n\n// ── Types ────────────────────────────────────────────────────────────────────\n\nexport interface FanOutResult {\n\tserverUrl: string;\n\tsuccess: boolean;\n\terror?: string;\n}\n\n// ── DeviceRegistrationService ────────────────────────────────────────────────\n\n/**\n * Handles cross-server device key registration and revocation propagation.\n *\n * All methods operate on the identity Y.Doc's `devicesMap` and authenticate\n * independently on each server using the master key's `signChallenge`.\n */\nexport class DeviceRegistrationService {\n\t/**\n\t * Fan out a device key to all servers in `serversMap` where it isn't registered.\n\t *\n\t * Must be called from a master device that can sign challenges with the\n\t * account-level private key.\n\t */\n\tstatic async fanOutDeviceKey(opts: {\n\t\tdevicePubKey: string;\n\t\tx25519Key?: string;\n\t\tdeviceName?: string;\n\t\tidentityDoc: IdentityDocProvider;\n\t\tmasterPubKey: string;\n\t\tsignChallenge: (challenge: string) => Promise<string>;\n\t\tskipServerUrl?: string;\n\t}): Promise<FanOutResult[]> {\n\t\tconst {\n\t\t\tdevicePubKey,\n\t\t\tx25519Key,\n\t\t\tdeviceName,\n\t\t\tidentityDoc,\n\t\t\tmasterPubKey,\n\t\t\tsignChallenge,\n\t\t\tskipServerUrl,\n\t\t} = opts;\n\n\t\tconst servers = identityDoc.getServers();\n\t\tconst results: FanOutResult[] = [];\n\n\t\t// Ensure the device entry exists in devicesMap\n\t\tif (!identityDoc.getDevice(devicePubKey)) {\n\t\t\tidentityDoc.addDevice(devicePubKey, {\n\t\t\t\tdeviceName: deviceName ?? \"Unknown\",\n\t\t\t\ttier: \"paired\",\n\t\t\t\tx25519Key,\n\t\t\t});\n\t\t}\n\n\t\tfor (const [serverUrl] of servers) {\n\t\t\tif (skipServerUrl && serverUrl === skipServerUrl) continue;\n\n\t\t\t// Check if already registered on this server\n\t\t\tconst device = identityDoc.getDevice(devicePubKey);\n\t\t\tconst serverStatus = device?.servers.get(serverUrl);\n\t\t\tif (serverStatus?.registered) continue;\n\n\t\t\ttry {\n\t\t\t\tconst client = new AbracadabraClient({ url: serverUrl });\n\t\t\t\tawait client.loginWithKey(masterPubKey, signChallenge);\n\t\t\t\tawait client.addKey({\n\t\t\t\t\tpublicKey: devicePubKey,\n\t\t\t\t\tx25519Key,\n\t\t\t\t\tdeviceName,\n\t\t\t\t});\n\n\t\t\t\t// Get the keyId from the server for future revocation\n\t\t\t\tconst keys = await client.listKeys();\n\t\t\t\tconst match = keys.find(\n\t\t\t\t\t(k) => k.publicKey === devicePubKey && !k.revoked,\n\t\t\t\t);\n\n\t\t\t\tidentityDoc.setDeviceServerStatus(devicePubKey, serverUrl, {\n\t\t\t\t\tregistered: true,\n\t\t\t\t\tregisteredAt: Date.now(),\n\t\t\t\t\tkeyId: match?.id ?? null,\n\t\t\t\t\tlastVerifiedAt: Date.now(),\n\t\t\t\t\terror: null,\n\t\t\t\t});\n\n\t\t\t\tresults.push({ serverUrl, success: true });\n\t\t\t} catch (e: any) {\n\t\t\t\tidentityDoc.setDeviceServerStatus(devicePubKey, serverUrl, {\n\t\t\t\t\terror: e?.message ?? \"Registration failed\",\n\t\t\t\t});\n\t\t\t\tresults.push({\n\t\t\t\t\tserverUrl,\n\t\t\t\t\tsuccess: false,\n\t\t\t\t\terror: e?.message ?? \"Registration failed\",\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\n\t\treturn results;\n\t}\n\n\t/**\n\t * Propagate pending revocations from the identity Y.Doc to all servers.\n\t *\n\t * Scans `devicesMap` for entries with `revokedAt` set and revokes them\n\t * on every server where they're still registered. Must be called from\n\t * a master device.\n\t */\n\tstatic async propagateRevocations(opts: {\n\t\tidentityDoc: IdentityDocProvider;\n\t\tmasterPubKey: string;\n\t\tsignChallenge: (challenge: string) => Promise<string>;\n\t}): Promise<FanOutResult[]> {\n\t\tconst { identityDoc, masterPubKey, signChallenge } = opts;\n\t\tconst devices = identityDoc.getDevices();\n\t\tconst results: FanOutResult[] = [];\n\n\t\tfor (const [devicePubKey, device] of devices) {\n\t\t\tif (!device.revokedAt) continue;\n\n\t\t\tfor (const [serverUrl, serverStatus] of device.servers) {\n\t\t\t\tif (!serverStatus.registered || !serverStatus.keyId) continue;\n\n\t\t\t\ttry {\n\t\t\t\t\tconst client = new AbracadabraClient({ url: serverUrl });\n\t\t\t\t\tawait client.loginWithKey(masterPubKey, signChallenge);\n\t\t\t\t\tawait client.revokeKey(serverStatus.keyId);\n\n\t\t\t\t\tidentityDoc.setDeviceServerStatus(\n\t\t\t\t\t\tdevicePubKey,\n\t\t\t\t\t\tserverUrl,\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tregistered: false,\n\t\t\t\t\t\t\terror: null,\n\t\t\t\t\t\t},\n\t\t\t\t\t);\n\t\t\t\t\tresults.push({ serverUrl, success: true });\n\t\t\t\t} catch (e: any) {\n\t\t\t\t\tresults.push({\n\t\t\t\t\t\tserverUrl,\n\t\t\t\t\t\tsuccess: false,\n\t\t\t\t\t\terror: e?.message ?? \"Revocation failed\",\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn results;\n\t}\n\n\t/**\n\t * Reconcile the identity Y.Doc's `devicesMap` with a server's actual\n\t * device key list. Call this on every server connection.\n\t *\n\t * - Updates registration status in Y.Doc to match server reality\n\t * - Imports unknown server keys as legacy entries\n\t * - Executes pending revocations if the caller is a master device\n\t */\n\tstatic async reconcile(opts: {\n\t\tidentityDoc: IdentityDocProvider;\n\t\tserverUrl: string;\n\t\tclient: AbracadabraClient;\n\t\tisMaster: boolean;\n\t}): Promise<void> {\n\t\tconst { identityDoc, serverUrl, client, isMaster } = opts;\n\n\t\tlet serverKeys: PublicKeyInfo[];\n\t\ttry {\n\t\t\tserverKeys = await client.listKeys();\n\t\t} catch {\n\t\t\treturn; // Server unreachable or auth issue — skip reconciliation\n\t\t}\n\n\t\tconst devicesMap = identityDoc.devicesMap;\n\n\t\t// Pending revocations are collected during the (synchronous) scan and\n\t\t// executed AFTER it — never fire-and-forget inside the forEach. The old\n\t\t// code kicked off `client.revokeKey(...)` without awaiting, so reconcile\n\t\t// resolved before the revoke landed: the caller's next request then\n\t\t// raced the in-flight revoke and ran with a token the revoke had just\n\t\t// invalidated server-side (revoke re-mints + bumps tokens_invalid_before).\n\t\tconst pendingRevocations: { devicePub: string; keyId: string }[] = [];\n\n\t\t// 1. Verify Y.Doc matches server reality\n\t\tdevicesMap.forEach((yEntry, devicePub) => {\n\t\t\tconst serversYMap = yEntry.get(\"servers\") as\n\t\t\t\t| Y.Map<Y.Map<any>>\n\t\t\t\t| undefined;\n\t\t\tconst serverEntry = serversYMap?.get(serverUrl);\n\t\t\tconst serverKey = serverKeys.find((k) => k.publicKey === devicePub);\n\t\t\tconst revokedAt = yEntry.get(\"revokedAt\");\n\n\t\t\tif (serverEntry?.get(\"registered\") && !serverKey) {\n\t\t\t\t// Y.Doc thinks registered but server doesn't have it\n\t\t\t\tidentityDoc.setDeviceServerStatus(devicePub, serverUrl, {\n\t\t\t\t\tregistered: false,\n\t\t\t\t\tkeyId: null,\n\t\t\t\t});\n\t\t\t}\n\n\t\t\tif (serverKey && !serverKey.revoked) {\n\t\t\t\t// Server has it — update Y.Doc if needed\n\t\t\t\tif (!serverEntry?.get(\"registered\")) {\n\t\t\t\t\tidentityDoc.setDeviceServerStatus(devicePub, serverUrl, {\n\t\t\t\t\t\tregistered: true,\n\t\t\t\t\t\tkeyId: serverKey.id,\n\t\t\t\t\t\tlastVerifiedAt: Date.now(),\n\t\t\t\t\t});\n\t\t\t\t} else {\n\t\t\t\t\t// Just update verification timestamp + keyId\n\t\t\t\t\tidentityDoc.setDeviceServerStatus(devicePub, serverUrl, {\n\t\t\t\t\t\tlastVerifiedAt: Date.now(),\n\t\t\t\t\t\tkeyId: serverKey.id,\n\t\t\t\t\t});\n\t\t\t\t}\n\n\t\t\t\t// Queue revocation if we're a master device — executed (awaited)\n\t\t\t\t// after the scan, below.\n\t\t\t\tif (revokedAt && isMaster) {\n\t\t\t\t\tpendingRevocations.push({ devicePub, keyId: serverKey.id });\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\n\t\t// Execute queued revocations serially so each `revokeKey` captures the\n\t\t// re-minted token (revokeKey updates the client's token) before the next\n\t\t// call — and so reconcile only resolves once they have actually landed.\n\t\tfor (const { devicePub, keyId } of pendingRevocations) {\n\t\t\ttry {\n\t\t\t\tawait client.revokeKey(keyId);\n\t\t\t\tidentityDoc.setDeviceServerStatus(devicePub, serverUrl, {\n\t\t\t\t\tregistered: false,\n\t\t\t\t});\n\t\t\t} catch {\n\t\t\t\t// Leave Y.Doc as-is; the next reconcile retries.\n\t\t\t}\n\t\t}\n\n\t\t// 2. Import unknown server keys into Y.Doc (migration)\n\t\tfor (const key of serverKeys) {\n\t\t\tif (key.revoked) continue;\n\t\t\tif (!devicesMap.has(key.publicKey)) {\n\t\t\t\tidentityDoc.addDevice(key.publicKey, {\n\t\t\t\t\tdeviceName: key.deviceName ?? \"Unknown\",\n\t\t\t\t\ttier: \"paired\",\n\t\t\t\t\tserverUrl,\n\t\t\t\t\tkeyId: key.id,\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\t}\n}\n","import EventEmitter from \"./EventEmitter.ts\";\nimport type {\n ChatTypingEvent,\n SendChatMessageInput as _LegacySendInput,\n GetChatHistoryInput as _LegacyHistoryInput,\n} from \"./types.ts\";\n\n// Legacy alias re-exports kept for type-import compat with consumers that\n// import these names from `@abraca/dabra`. The old shapes still describe\n// the wire the dashboard's own reactive layer reads/writes; this client\n// itself no longer uses them as method inputs.\nexport type _ReExportedTypes = _LegacySendInput | _LegacyHistoryInput;\n\n/**\n * Minimal provider surface ChatClient needs. Matches `AbracadabraBaseProvider`.\n */\nexport interface ChatClientTransport {\n sendStateless(payload: string): void;\n // eslint-disable-next-line @typescript-eslint/no-unsafe-function-type\n on(event: string, fn: Function): unknown;\n // eslint-disable-next-line @typescript-eslint/no-unsafe-function-type\n off(event: string, fn?: Function): unknown;\n}\n\ntype PendingResolver<T> = {\n resolve: (value: T) => void;\n reject: (err: Error) => void;\n timer: ReturnType<typeof setTimeout>;\n};\n\nconst DEFAULT_TIMEOUT_MS = 10_000;\n\n/**\n * Send a chat message into a channel doc.\n *\n * `channel_doc_id` is the UUID of the channel/dm doc — `documents.id` for\n * a row with `kind = \"channel\"` or `kind = \"dm\"`. Group channels under a\n * Space pass the channel doc's id; DMs pass the DM doc's id (callers\n * resolve \"the DM doc between user A and user B\" via their own path —\n * typically `client.listChildren(serverRootId)` filtered by `kind === \"dm\"`\n * with both pubkeys in `permissions`).\n */\nexport interface SendMessageInput {\n channel_doc_id: string;\n content: string;\n /** Cleartext recipient pubkeys for server-side mention fan-out. */\n mentions?: string[];\n /** Message id this is a reply to. */\n reply_to?: string;\n /**\n * Optional Ed25519 signature over the canonical envelope, base64url. When\n * server config `[messages].require_client_sig = true`, sends without a\n * sig are rejected. Default-config servers accept unsigned sends — the\n * threat model relies on JWT-bound session auth + the server's own\n * `server_sig` over `(msg_id, period_id, ts, sig)`.\n */\n sig?: string;\n /** Client-side timestamp (ms) for skew-tolerance check. Optional. */\n ts_hint?: number;\n}\n\nexport interface SendMessageResult {\n message_id: string;\n period_id: string;\n ts: number;\n server_sig: string;\n}\n\nexport interface EditMessageInput {\n channel_doc_id: string;\n message_id: string;\n content: string;\n sig?: string;\n}\n\nexport interface DeleteMessageInput {\n channel_doc_id: string;\n message_id: string;\n}\n\nexport interface MarkReadInput {\n channel_doc_id: string;\n period_id: string;\n message_id: string;\n /** Unix milliseconds. Defaults to server time. */\n ts?: number;\n}\n\n/**\n * Thin façade over the `messages:*` stateless protocol.\n *\n * The unified messages model stores chat history as Y.Array entries on\n * `kind = \"channel-period\"` child docs of channel/dm docs (and notifications\n * as entries on a per-user `kind = \"inbox\"` doc). Reading history, listing\n * channels, observing real-time messages, and tracking read cursors are all\n * Y.Doc-shaped operations that the SDK consumer performs via\n * `AbracadabraClient` + `AbracadabraProvider` directly — not through this\n * façade. ChatClient handles only the *write-and-validate* path (sends,\n * edits, deletes, typing, mark-read), where the server is the sole authority\n * over the channel-period Y.Array.\n *\n * Events emitted:\n * - `typing` → ChatTypingEvent (typing broadcast on the channel doc)\n *\n * For incoming-message observation, the consumer opens an\n * `AbracadabraProvider` on the active period doc and observes its\n * `messages` Y.Array directly. The dashboard's `useChat` composable does\n * this; the integration tests do this; external consumers should mirror\n * the pattern.\n */\nexport class ChatClient extends EventEmitter {\n private readonly provider: ChatClientTransport;\n private readonly responseTimeoutMs: number;\n\n // FIFO of promises waiting on a typed `messages:ok` reply (keyed by source).\n private readonly pending: Map<string, PendingResolver<any>[]> = new Map();\n\n private readonly boundOnStateless: (data: { payload: string }) => void;\n private readonly boundOnServerError: (data: {\n source: string;\n code: string;\n message: string;\n meta?: unknown;\n }) => void;\n\n constructor(provider: ChatClientTransport, options?: { responseTimeoutMs?: number }) {\n super();\n this.provider = provider;\n this.responseTimeoutMs = options?.responseTimeoutMs ?? DEFAULT_TIMEOUT_MS;\n this.boundOnStateless = (data) => this.handleStateless(data.payload);\n this.boundOnServerError = (data) => this.handleServerError(data);\n this.provider.on(\"stateless\", this.boundOnStateless);\n // BaseProvider intercepts `{type:\"error\",source,code}` frames and emits\n // them as `serverError`, not `stateless` — so request/response code paths\n // must listen here to learn about rejections.\n this.provider.on(\"serverError\", this.boundOnServerError);\n }\n\n destroy(): void {\n this.provider.off(\"stateless\", this.boundOnStateless);\n this.provider.off(\"serverError\", this.boundOnServerError);\n for (const queue of this.pending.values()) {\n for (const p of queue) {\n clearTimeout(p.timer);\n p.reject(new Error(\"ChatClient destroyed\"));\n }\n }\n this.pending.clear();\n this.removeAllListeners();\n }\n\n // ── Outgoing requests ──────────────────────────────────────────────────────\n\n /** Send a chat message. Resolves with the server-assigned id, ts, and signatures. */\n send(input: SendMessageInput): Promise<SendMessageResult> {\n const promise = this.enqueue<SendMessageResult>(\"messages:send\");\n this.provider.sendStateless(\n JSON.stringify({\n type: \"messages:send\",\n channel_doc_id: input.channel_doc_id,\n content: input.content,\n mentions: input.mentions ?? [],\n ...(input.reply_to !== undefined ? { reply_to: input.reply_to } : {}),\n ...(input.sig !== undefined ? { sig: input.sig } : {}),\n ...(input.ts_hint !== undefined ? { ts_hint: input.ts_hint } : {}),\n }),\n );\n return promise;\n }\n\n /** Edit a previously-sent message. Append-only — server records an `edit` entry. */\n edit(input: EditMessageInput): Promise<void> {\n const promise = this.enqueue<void>(\"messages:edit\");\n this.provider.sendStateless(\n JSON.stringify({\n type: \"messages:edit\",\n channel_doc_id: input.channel_doc_id,\n message_id: input.message_id,\n content: input.content,\n ...(input.sig !== undefined ? { sig: input.sig } : {}),\n }),\n );\n return promise;\n }\n\n /** Delete a message. Append-only — server records a `tombstone` entry. */\n delete(input: DeleteMessageInput): Promise<void> {\n const promise = this.enqueue<void>(\"messages:delete\");\n this.provider.sendStateless(\n JSON.stringify({\n type: \"messages:delete\",\n channel_doc_id: input.channel_doc_id,\n message_id: input.message_id,\n }),\n );\n return promise;\n }\n\n /** Broadcast a typing indicator on a channel. Fire-and-forget. */\n typing(channel_doc_id: string): void {\n this.provider.sendStateless(\n JSON.stringify({ type: \"messages:typing\", channel_doc_id }),\n );\n }\n\n /** Mark a (period, message) position as read for the calling user. Fire-and-forget. */\n markRead(input: MarkReadInput): void {\n this.provider.sendStateless(\n JSON.stringify({\n type: \"messages:mark_read\",\n channel_doc_id: input.channel_doc_id,\n period_id: input.period_id,\n message_id: input.message_id,\n ...(input.ts !== undefined ? { ts: input.ts } : {}),\n }),\n );\n }\n\n // ── Typed event subscription helpers ──────────────────────────────────────\n\n /** Observe typing broadcasts. */\n onTyping(fn: (e: ChatTypingEvent) => void): this {\n return this.on(\"typing\", fn) as this;\n }\n\n // ── Internals ─────────────────────────────────────────────────────────────\n\n private enqueue<T>(source: string): Promise<T> {\n return new Promise<T>((resolve, reject) => {\n const timer = setTimeout(() => {\n this.removePending(source, entry);\n reject(new Error(`ChatClient: timeout waiting for ${source} ack`));\n }, this.responseTimeoutMs);\n const entry: PendingResolver<T> = { resolve, reject, timer };\n const queue = this.pending.get(source) ?? [];\n queue.push(entry);\n this.pending.set(source, queue);\n });\n }\n\n private removePending(source: string, entry: PendingResolver<any>): void {\n const queue = this.pending.get(source);\n if (!queue) return;\n const idx = queue.indexOf(entry);\n if (idx >= 0) queue.splice(idx, 1);\n if (queue.length === 0) this.pending.delete(source);\n }\n\n private resolveNext<T>(source: string, value: T): boolean {\n const queue = this.pending.get(source);\n if (!queue || queue.length === 0) return false;\n const next = queue.shift()!;\n if (queue.length === 0) this.pending.delete(source);\n clearTimeout(next.timer);\n next.resolve(value);\n return true;\n }\n\n private rejectNext(source: string, err: Error): boolean {\n const queue = this.pending.get(source);\n if (!queue || queue.length === 0) return false;\n const next = queue.shift()!;\n if (queue.length === 0) this.pending.delete(source);\n clearTimeout(next.timer);\n next.reject(err);\n return true;\n }\n\n private handleStateless(payload: string): void {\n let parsed: any;\n try {\n parsed = JSON.parse(payload);\n } catch {\n return;\n }\n const type: unknown = parsed?.type;\n if (typeof type !== \"string\") return;\n\n // Server emits `messages:ok` acks with a `source` matching the originating\n // request type. Use that to resolve the matching pending promise.\n if (type === \"messages:ok\" && typeof parsed.source === \"string\") {\n this.resolveNext(parsed.source, parsed.meta);\n return;\n }\n if (type === \"messages:typing\") {\n // The server includes channel_doc_id + user_id; the legacy\n // ChatTypingEvent shape has `channel`, so emit it as the new doc id —\n // consumers that want the old `group:<id>` form can prefix locally.\n this.emit(\"typing\", {\n channel: parsed.channel_doc_id,\n sender_id: parsed.user_id,\n sender_name: null,\n } as ChatTypingEvent);\n return;\n }\n }\n\n private handleServerError(data: {\n source: string;\n code: string;\n message: string;\n meta?: unknown;\n }): void {\n if (typeof data.source !== \"string\" || !data.source.startsWith(\"messages:\")) return;\n if (data.source === \"messages:inbox_fetch\" || data.source === \"messages:inbox_mark_read\") {\n // Inbox traffic belongs to NotificationsClient — let it handle its own errors.\n return;\n }\n this.rejectNext(\n data.source,\n new Error(`${data.code ?? \"error\"}: ${data.message ?? \"messages request failed\"}`),\n );\n }\n}\n","/**\n * EncryptedChatClient — `ChatClient` wrapper that transparently encrypts\n * message content for channels in `e2e` mode and decrypts entries read\n * back from the period doc's `messages` Y.Array.\n *\n * Threat model\n * - Server cannot read message bodies (the `content` field is opaque\n * ciphertext bytes, base64-encoded into the wire string).\n * - Server CAN see `sender_id`, `channel_doc_id`, `period_id`, `ts`,\n * `mentions[]` (kept cleartext for fan-out), `message_id`,\n * and the `server_sig` it stamps. That envelope is the only thing\n * the server inspects to do its job.\n *\n * Wire format\n * `content` for an e2e message is the literal string\n * `\"e2e:1:<base64>\"`\n * where the decoded blob is `[nonce(12) || AES-GCM-ciphertext]` and\n * the AES-256-GCM key is the channel's existing DocKey (the same one\n * used for `EncryptedY` doc-level encryption — same threat boundary,\n * no extra key derivation, identical envelope distribution).\n *\n * The `e2e:1:` sentinel is a strict prefix to disambiguate from\n * cleartext content that happens to start with \"{\". Never unwrap a\n * message whose content doesn't start with the sentinel — passing\n * ciphertext from a server you don't trust through `decrypt` would\n * open the door to malformed-input oracles.\n */\n\nimport { encryptField, decryptField } from \"./EncryptedY.ts\";\nimport { DocKeyManager } from \"./DocKeyManager.ts\";\nimport type { AbracadabraClient } from \"./AbracadabraClient.ts\";\nimport type { CryptoIdentityKeystore } from \"./CryptoIdentityKeystore.ts\";\nimport type {\n ChatClient,\n SendMessageInput,\n SendMessageResult,\n EditMessageInput,\n} from \"./ChatClient.ts\";\n\nconst SENTINEL = \"e2e:1:\";\n\nfunction toBase64(bytes: Uint8Array): string {\n let s = \"\";\n for (let i = 0; i < bytes.length; i++) s += String.fromCharCode(bytes[i]!);\n return btoa(s);\n}\n\nfunction fromBase64(b64: string): Uint8Array {\n const bin = atob(b64);\n const out = new Uint8Array(bin.length);\n for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i);\n return out;\n}\n\n/**\n * Returns true if `content` is wrapped by this module (i.e. an `e2e:1:`\n * envelope). Cleartext content always returns false.\n */\nexport function isEncryptedContent(content: string): boolean {\n return typeof content === \"string\" && content.startsWith(SENTINEL);\n}\n\n/**\n * Decrypt an `e2e:1:` envelope back to cleartext using the channel's\n * DocKey. Returns null if the envelope is malformed (don't surface\n * partial decryption — show the user a placeholder instead).\n */\nexport async function decryptChatContent(content: string, docKey: CryptoKey): Promise<string | null> {\n if (!isEncryptedContent(content)) return content; // already cleartext\n try {\n const blob = fromBase64(content.slice(SENTINEL.length));\n const plain = await decryptField(blob, docKey);\n return new TextDecoder().decode(plain);\n } catch {\n return null;\n }\n}\n\n/**\n * Encrypt cleartext into an `e2e:1:` envelope ready to send as the\n * stateless `messages:send` `content` field.\n */\nexport async function encryptChatContent(content: string, docKey: CryptoKey): Promise<string> {\n const blob = await encryptField(new TextEncoder().encode(content), docKey);\n return SENTINEL + toBase64(blob);\n}\n\n/**\n * Per-channel encryption-mode + DocKey resolver. Caches the encryption\n * mode lookup for `cacheTtlMs`; the DocKey itself is cached inside\n * `DocKeyManager`. Returns `null` for non-E2E channels.\n */\nexport class ChannelKeyResolver {\n private modeCache = new Map<string, { mode: \"none\" | \"cse\" | \"e2e\"; fetchedAt: number }>();\n private static readonly DEFAULT_TTL_MS = 5 * 60 * 1000;\n\n constructor(\n private readonly client: AbracadabraClient,\n private readonly docKeys: DocKeyManager,\n private readonly keystore: CryptoIdentityKeystore,\n private readonly options: { cacheTtlMs?: number } = {},\n ) {}\n\n async modeFor(channelDocId: string): Promise<\"none\" | \"cse\" | \"e2e\"> {\n const cached = this.modeCache.get(channelDocId);\n const ttl = this.options.cacheTtlMs ?? ChannelKeyResolver.DEFAULT_TTL_MS;\n if (cached && Date.now() - cached.fetchedAt < ttl) return cached.mode;\n const info = await this.client.getDocEncryption(channelDocId);\n const mode = info.effective_mode;\n this.modeCache.set(channelDocId, { mode, fetchedAt: Date.now() });\n return mode;\n }\n\n /**\n * Returns the DocKey for an E2E channel, or null for cleartext channels\n * (no envelope to fetch). Throws if the channel is E2E but no envelope\n * exists for the current user — the caller should let the send fail\n * loudly rather than fall back to cleartext, which would silently\n * downgrade the threat model.\n */\n async docKeyFor(channelDocId: string): Promise<CryptoKey | null> {\n const mode = await this.modeFor(channelDocId);\n if (mode !== \"e2e\") return null;\n const key = await this.docKeys.getDocKey(channelDocId, this.client, this.keystore);\n if (!key) {\n throw new Error(\n `EncryptedChatClient: no key envelope for channel ${channelDocId} — user is not provisioned for this E2E channel.`,\n );\n }\n return key;\n }\n\n /** Drop the cached encryption mode for `channelDocId` (or all). */\n clearCache(channelDocId?: string): void {\n if (channelDocId) this.modeCache.delete(channelDocId);\n else this.modeCache.clear();\n }\n}\n\n/**\n * Drop-in wrapper around an existing ChatClient that intercepts the\n * write side (`send` / `edit`) and encrypts content for E2E channels.\n * Reading is handled separately — the consumer pumps the period's Y.Array\n * directly and calls `decryptChatContent` per record.\n *\n * Channels in `none` or `cse` mode are passed through untouched.\n */\nexport class EncryptedChatClient {\n constructor(\n private readonly inner: ChatClient,\n private readonly resolver: ChannelKeyResolver,\n ) {}\n\n async send(input: SendMessageInput): Promise<SendMessageResult> {\n const docKey = await this.resolver.docKeyFor(input.channel_doc_id);\n if (!docKey) return this.inner.send(input);\n const ciphertext = await encryptChatContent(input.content, docKey);\n return this.inner.send({ ...input, content: ciphertext });\n }\n\n async edit(input: EditMessageInput): Promise<void> {\n const docKey = await this.resolver.docKeyFor(input.channel_doc_id);\n if (!docKey) return this.inner.edit(input);\n const ciphertext = await encryptChatContent(input.content, docKey);\n return this.inner.edit({ ...input, content: ciphertext });\n }\n\n // Pass-through methods that don't carry encryptable content.\n delete(...args: Parameters<ChatClient[\"delete\"]>) { return this.inner.delete(...args); }\n markRead(...args: Parameters<ChatClient[\"markRead\"]>) { return this.inner.markRead(...args); }\n typing(...args: Parameters<ChatClient[\"typing\"]>) { return this.inner.typing(...args); }\n destroy() { this.inner.destroy(); }\n}\n","/**\n * Decode + fold message records from a period doc's `messages` Y.Array\n * into the flat `ChatMessage[]` shape the dashboard renders.\n *\n * The server appends three kinds of records to the array (see\n * `abracadabra-rs/crates/abracadabra/src/messages.rs`):\n *\n * - `record_kind: \"message\"` — a real message (default kind).\n * - `record_kind: \"edit\"` — an updated version of `target_id`.\n * - `record_kind: \"tombstone\"` — `target_id` is deleted.\n *\n * Folding rules:\n * - For each `target_id`, apply edits in `ts` order; the *last* edit's\n * content wins. The original message's id, sender_id, and ts stay.\n * `editedAt` is the latest edit's ts.\n * - Any target_id with a tombstone is dropped from the output entirely.\n * - Records without record_kind default to \"message\" (back-compat).\n *\n * Cross-period folding: edits and tombstones can in principle target a\n * message in a *prior* period (e.g. user edits a message that lived on\n * the previous period after rollover). Callers that paginate across\n * periods should fold the joined list, not each period independently.\n */\n\nexport interface MessageRecord {\n record_kind?: 'message' | 'edit' | 'tombstone'\n id: string\n target_id?: string\n sender_id: string\n channel_doc_id: string\n period_id: string\n ts: number\n content: string\n mentions?: string[]\n reply_to?: string | null\n sig?: string\n server_sig?: string\n}\n\nexport interface FoldedMessage {\n id: string\n channel: string\n senderId: string\n senderName?: string\n content: string\n createdAt: number\n /** Set if the message has been edited at least once. */\n editedAt?: number\n /** Reply target message id, if any. */\n replyTo?: string\n}\n\n/**\n * Fold an ordered list of records (oldest-first) into the visible\n * messages a UI should render. Records may come from one period or\n * across multiple periods concatenated in time order.\n */\nexport function foldRecords(records: MessageRecord[]): FoldedMessage[] {\n const tombstoned = new Set<string>()\n for (const r of records) {\n if (r.record_kind === 'tombstone' && r.target_id) tombstoned.add(r.target_id)\n }\n\n const base = new Map<string, FoldedMessage>()\n for (const r of records) {\n const kind = r.record_kind ?? 'message'\n if (kind !== 'message') continue\n if (tombstoned.has(r.id)) continue\n base.set(r.id, {\n id: r.id,\n channel: r.channel_doc_id,\n senderId: r.sender_id,\n content: r.content,\n createdAt: r.ts,\n ...(r.reply_to ? { replyTo: r.reply_to } : {}),\n })\n }\n\n for (const r of records) {\n if (r.record_kind !== 'edit' || !r.target_id) continue\n if (tombstoned.has(r.target_id)) continue\n const original = base.get(r.target_id)\n if (!original) continue\n original.content = r.content\n original.editedAt = r.ts\n }\n\n return [...base.values()].sort((a, b) => a.createdAt - b.createdAt)\n}\n\n/**\n * Decode whatever the Y.Array stored for an entry into a MessageRecord.\n * Note: the server stamps `ts` server-side via `Any::BigInt(now_ts_ms())`,\n * so on the wire it round-trips as a JS BigInt — `typeof` is `'bigint'`,\n * not `'number'`. Accept both and coerce.\n */\nexport function recordFromYAny(any: unknown): MessageRecord | null {\n if (!any || typeof any !== 'object') return null\n const o = any as Record<string, unknown>\n const tsRaw = o.ts\n const tsIsValid = typeof tsRaw === 'number' || typeof tsRaw === 'bigint'\n if (typeof o.id !== 'string' || typeof o.sender_id !== 'string'\n || typeof o.channel_doc_id !== 'string' || !tsIsValid) {\n return null\n }\n const ts = typeof tsRaw === 'bigint' ? Number(tsRaw) : (tsRaw as number)\n return {\n record_kind: typeof o.record_kind === 'string' ? o.record_kind as MessageRecord['record_kind'] : 'message',\n id: o.id,\n target_id: typeof o.target_id === 'string' ? o.target_id : undefined,\n sender_id: o.sender_id,\n channel_doc_id: o.channel_doc_id,\n period_id: typeof o.period_id === 'string' ? o.period_id : '',\n ts,\n content: typeof o.content === 'string' ? o.content : '',\n mentions: Array.isArray(o.mentions) ? o.mentions as string[] : [],\n reply_to: typeof o.reply_to === 'string' ? o.reply_to : null,\n sig: typeof o.sig === 'string' ? o.sig : undefined,\n server_sig: typeof o.server_sig === 'string' ? o.server_sig : undefined,\n }\n}\n","import EventEmitter from \"./EventEmitter.ts\";\nimport type { ChatClientTransport } from \"./ChatClient.ts\";\n\ntype PendingResolver<T> = {\n resolve: (value: T) => void;\n reject: (err: Error) => void;\n timer: ReturnType<typeof setTimeout>;\n};\n\nconst DEFAULT_TIMEOUT_MS = 10_000;\n\n/** Per-user inbox doc entry. Mirrors `InboxEntry` on the server. */\nexport interface InboxEntry {\n id: string;\n /** \"mention\" | \"reply\" | \"dm\" | \"system\". */\n kind: string;\n channel_doc_id: string;\n message_id?: string | null;\n sender_id?: string | null;\n sender_name?: string | null;\n /** Empty for E2E channels (server can't read body). Filled otherwise. */\n preview?: string | null;\n ts: number;\n /** Synthesized client-side from the inbox doc's `read` Y.Map. */\n read: boolean;\n}\n\nexport interface FetchInboxInput {\n before?: number;\n limit?: number;\n unread_only?: boolean;\n}\n\nexport interface MarkReadInput {\n id?: string;\n ids?: string[];\n source_id?: string;\n all?: boolean;\n}\n\n/**\n * Thin façade over the `messages:inbox_*` stateless protocol.\n *\n * Per-user notifications live as Y.Array entries on the user's inbox doc\n * (`kind = \"inbox\"`, owned by the user, child of the server root, server-only\n * writer). Real-time observation of new entries is a Y.Array observer the\n * consumer attaches via `AbracadabraProvider` on the inbox doc.\n *\n * This client handles only the request/response layer:\n * - `fetch()` issues `messages:inbox_fetch`, returns the entry list.\n * - `markRead()` issues `messages:inbox_mark_read` (id / ids / source_id /\n * all variants).\n *\n * For incoming notification observation, open an AbracadabraProvider on the\n * inbox doc and observe its `entries` Y.Array directly. The dashboard's\n * `useNotifications` composable does this.\n */\nexport class NotificationsClient extends EventEmitter {\n private readonly provider: ChatClientTransport;\n private readonly responseTimeoutMs: number;\n private readonly pending: Map<string, PendingResolver<any>[]> = new Map();\n private readonly boundOnStateless: (data: { payload: string }) => void;\n private readonly boundOnServerError: (data: {\n source: string;\n code: string;\n message: string;\n meta?: unknown;\n }) => void;\n\n constructor(provider: ChatClientTransport, options?: { responseTimeoutMs?: number }) {\n super();\n this.provider = provider;\n this.responseTimeoutMs = options?.responseTimeoutMs ?? DEFAULT_TIMEOUT_MS;\n this.boundOnStateless = (data) => this.handleStateless(data.payload);\n this.boundOnServerError = (data) => this.handleServerError(data);\n this.provider.on(\"stateless\", this.boundOnStateless);\n // BaseProvider emits `serverError` for `{type:\"error\",source,code}` frames\n // instead of `stateless`. Subscribe so inbox request rejections surface.\n this.provider.on(\"serverError\", this.boundOnServerError);\n }\n\n destroy(): void {\n this.provider.off(\"stateless\", this.boundOnStateless);\n this.provider.off(\"serverError\", this.boundOnServerError);\n for (const queue of this.pending.values()) {\n for (const p of queue) {\n clearTimeout(p.timer);\n p.reject(new Error(\"NotificationsClient destroyed\"));\n }\n }\n this.pending.clear();\n this.removeAllListeners();\n }\n\n /** Fetch a slice of the calling user's inbox. Resolves with the entries. */\n fetch(input: FetchInboxInput = {}): Promise<{ entries: InboxEntry[] }> {\n const promise = this.enqueue<{ entries: InboxEntry[] }>(\"messages:inbox_history\");\n this.provider.sendStateless(\n JSON.stringify({\n type: \"messages:inbox_fetch\",\n ...(input.before !== undefined ? { before: input.before } : {}),\n ...(input.limit !== undefined ? { limit: input.limit } : {}),\n ...(input.unread_only !== undefined ? { unread_only: input.unread_only } : {}),\n }),\n );\n return promise;\n }\n\n /**\n * Mark inbox entries read. One of `id`, `ids`, `source_id`, or `all`.\n * Returns when the server has acked.\n */\n markRead(input: MarkReadInput): Promise<void> {\n const body: Record<string, unknown> = { type: \"messages:inbox_mark_read\" };\n if (input.all === true) body.all = true;\n else if (input.source_id !== undefined) body.source_id = input.source_id;\n else if (input.ids !== undefined) body.ids = input.ids;\n else if (input.id !== undefined) body.id = input.id;\n else return Promise.reject(new Error(\"markRead: one of id/ids/source_id/all required\"));\n\n const promise = this.enqueue<void>(\"messages:inbox_mark_read\");\n this.provider.sendStateless(JSON.stringify(body));\n return promise;\n }\n\n // ── Internals ─────────────────────────────────────────────────────────────\n\n private enqueue<T>(source: string): Promise<T> {\n return new Promise<T>((resolve, reject) => {\n const timer = setTimeout(() => {\n this.removePending(source, entry);\n reject(new Error(`NotificationsClient: timeout waiting for ${source}`));\n }, this.responseTimeoutMs);\n const entry: PendingResolver<T> = { resolve, reject, timer };\n const queue = this.pending.get(source) ?? [];\n queue.push(entry);\n this.pending.set(source, queue);\n });\n }\n\n private removePending(source: string, entry: PendingResolver<any>): void {\n const queue = this.pending.get(source);\n if (!queue) return;\n const idx = queue.indexOf(entry);\n if (idx >= 0) queue.splice(idx, 1);\n if (queue.length === 0) this.pending.delete(source);\n }\n\n private resolveNext<T>(source: string, value: T): boolean {\n const queue = this.pending.get(source);\n if (!queue || queue.length === 0) return false;\n const next = queue.shift()!;\n if (queue.length === 0) this.pending.delete(source);\n clearTimeout(next.timer);\n next.resolve(value);\n return true;\n }\n\n private rejectNext(source: string, err: Error): boolean {\n const queue = this.pending.get(source);\n if (!queue || queue.length === 0) return false;\n const next = queue.shift()!;\n if (queue.length === 0) this.pending.delete(source);\n clearTimeout(next.timer);\n next.reject(err);\n return true;\n }\n\n private handleStateless(payload: string): void {\n let parsed: any;\n try {\n parsed = JSON.parse(payload);\n } catch {\n return;\n }\n const type: unknown = parsed?.type;\n if (typeof type !== \"string\") return;\n\n if (type === \"messages:inbox_history\") {\n this.resolveNext(\"messages:inbox_history\", {\n entries: parsed.entries ?? [],\n });\n return;\n }\n if (type === \"messages:ok\" && parsed.source === \"messages:inbox_mark_read\") {\n this.resolveNext(\"messages:inbox_mark_read\", undefined);\n return;\n }\n }\n\n private handleServerError(data: {\n source: string;\n code: string;\n message: string;\n meta?: unknown;\n }): void {\n if (data.source !== \"messages:inbox_fetch\" && data.source !== \"messages:inbox_mark_read\") {\n return;\n }\n const key =\n data.source === \"messages:inbox_fetch\" ? \"messages:inbox_history\" : data.source;\n this.rejectNext(\n key,\n new Error(`${data.code ?? \"error\"}: ${data.message ?? \"inbox request failed\"}`),\n );\n }\n}\n","/**\n * Canonical type definitions for Abracadabra document tree entries, page\n * metadata, and the static page-type catalog.\n *\n * These types were previously scattered across `mcp/converters/types.ts` and\n * `mcp/converters/page-types.ts`. By living in the provider package they\n * become first-class SDK types that any consumer (`@abraca/dabra`) can import\n * directly, removing the need for fragile relative-path re-exports.\n */\n\n// ── Meta field primitives ────────────────────────────────────────────────────\n\nexport type MetaFieldType\n = | 'datetimerange'\n | 'daterange'\n | 'timerange'\n | 'datetime'\n | 'date'\n | 'time'\n | 'slider'\n | 'number'\n | 'toggle'\n | 'select'\n | 'multiselect'\n | 'colorPreset'\n | 'colorPicker'\n | 'location'\n | 'icon'\n | 'textarea'\n | 'url'\n | 'rating'\n | 'tags'\n | 'members'\n\nexport interface UserMetaField {\n id: string\n type: string\n label?: string\n key?: string\n latKey?: string\n lngKey?: string\n startKey?: string\n endKey?: string\n allDayKey?: string\n presets?: string[]\n options?: string[]\n min?: number\n max?: number\n step?: number\n unit?: string\n default?: boolean\n}\n\n// ── PageMeta — the full union of all metadata fields ─────────────────────────\n\nexport interface PageMeta extends Record<string, unknown> {\n // Universal display\n color?: string\n icon?: string\n subtitle?: string\n note?: string\n\n // Datetime\n datetimeStart?: string\n datetimeEnd?: string\n allDay?: boolean\n dateStart?: string\n dateEnd?: string\n timeStart?: string\n timeEnd?: string\n dateTaken?: string\n\n // Task/status\n checked?: boolean\n priority?: number\n status?: string\n taskProgress?: number\n rating?: number\n tags?: string[]\n members?: { id: string; label: string }[]\n\n // Contact/value\n url?: string\n email?: string\n phone?: string\n number?: number\n unit?: string\n\n // Cover image\n coverUploadId?: string\n coverDocId?: string\n coverMimeType?: string\n\n // Geo/Map\n geoType?: 'marker' | 'line' | 'measure'\n geoLat?: number\n geoLng?: number\n geoDescription?: string\n\n // Dashboard\n deskX?: number\n deskY?: number\n deskZ?: number\n deskMode?: string\n\n // Mindmap\n mmX?: number\n mmY?: number\n\n // Graph\n graphX?: number\n graphY?: number\n graphPinned?: boolean\n\n // Spatial (3D) — spatial uses the universal `color` key (no spColor)\n spShape?: string\n spOpacity?: number\n spX?: number\n spY?: number\n spZ?: number\n spRX?: number\n spRY?: number\n spRZ?: number\n spSX?: number\n spSY?: number\n spSZ?: number\n spModelUploadId?: string\n spModelDocId?: string\n\n // Slides\n slidesTransition?: string\n slidesTheme?: string\n\n // Media metadata (extracted on import)\n mediaDuration?: number\n mediaWidth?: number\n mediaHeight?: number\n mediaCamera?: string\n mediaLens?: string\n mediaIso?: number\n mediaFocalLength?: number\n mediaAperture?: number\n mediaShutterSpeed?: string\n mediaArtist?: string\n mediaAlbum?: string\n mediaGenre?: string\n mediaYear?: number\n\n // Sheets cell formatting\n bold?: boolean\n italic?: boolean\n textColor?: string\n bgColor?: string\n align?: string\n formula?: string\n\n // Coder plugin (per-file)\n fileType?: string\n entry?: boolean\n\n // Renderer config (set on the page doc itself, not children)\n kanbanColumnWidth?: string\n galleryColumns?: number\n galleryAspect?: string\n galleryCardStyle?: string\n galleryShowLabels?: boolean\n gallerySortBy?: string\n calendarView?: string\n calendarWeekStart?: string\n calendarShowWeekNumbers?: boolean\n tableMode?: string\n tableSortKey?: string\n tableSortDir?: string\n tableColumns?: any[]\n tableColumnWidths?: Record<string, number>\n tableColumnOrder?: string[]\n timelineZoom?: string\n timelinePixelsPerDay?: number\n timelineCenterDate?: string\n checklistFilter?: string\n checklistSort?: string\n mapShowLabels?: boolean\n spatialGridVisible?: boolean\n graphSpacing?: string\n graphShowLabels?: boolean\n graphEdgeThickness?: string\n mmSpacing?: string\n showRefEdges?: boolean\n chartType?: string\n chartMetric?: string\n chartColorScheme?: string\n chartLimit?: number\n chartShowLegend?: boolean\n chartShowValues?: boolean\n mediaRepeat?: string\n mediaShuffle?: boolean\n sheetsDefaultColWidth?: number\n sheetsDefaultRowHeight?: number\n sheetsShowGridlines?: boolean\n sheetsColumnWidths?: Record<string, number>\n sheetsRowHeights?: Record<string, number>\n sheetsFreezeRows?: number\n sheetsFreezeCols?: number\n\n // Internal\n _metaFields?: UserMetaField[]\n _metaInitialized?: boolean\n}\n\n// ── Tree entry (flat row in the doc-tree Y.Map) ──────────────────────────────\n\nexport interface TreeEntry {\n id: string\n label: string\n parentId: string | null\n order: number\n type?: string\n meta?: PageMeta\n createdAt?: number\n updatedAt?: number\n}\n\n// ── Tree node (nested, for buildTree output) ─────────────────────────────────\n\nexport interface TreeNode {\n id: string\n label: string\n type?: string\n meta?: PageMeta\n order: number\n children: TreeNode[]\n}\n\n// ── Search result (from TreeManager.find) ────────────────────────────────────\n\nexport interface TreeSearchResult {\n id: string\n label: string\n type?: string\n meta?: PageMeta\n /** Ancestor labels from root → parent. */\n path: string[]\n}\n\n// ── Page type catalog ────────────────────────────────────────────────────────\n\nexport interface PageTypeMetaField {\n type: MetaFieldType\n label?: string\n /** single-value fields */\n key?: string\n /** location */\n latKey?: string\n lngKey?: string\n /** ranges */\n startKey?: string\n endKey?: string\n allDayKey?: string\n /** color preset */\n presets?: string[]\n /** icon / select / tags */\n options?: string[]\n /** slider / number */\n min?: number\n max?: number\n step?: number\n unit?: string\n /** toggle default */\n default?: boolean\n}\n\nexport interface PageTypeInfo {\n key: string\n label: string\n icon: string\n description?: string\n /** true = core type (always available); false = requires plugin */\n core: boolean\n plugin?: string\n supportsChildren: boolean\n childLabel?: string\n grandchildLabel?: string\n /** -1 = unlimited depth */\n defaultDepth?: number\n /** Fields that apply to this doc's descendants (children, grandchildren, ...) */\n metaSchema?: PageTypeMetaField[]\n /** Fields written to this doc's own meta on first render (renderer config) */\n defaultMetaFields?: PageTypeMetaField[]\n}\n\n// ── Geo type meta schemas ────────────────────────────────────────────────────\n\nconst GEO_COLOR_PRESETS = ['#3b82f6', '#f97316', '#22c55e', '#ef4444', '#a855f7']\nconst GEO_ICON_OPTIONS = [\n 'map-pin', 'star', 'flag', 'home', 'building-2', 'coffee', 'utensils',\n 'camera', 'heart', 'zap', 'triangle-alert', 'car', 'plane', 'anchor',\n 'tree-pine', 'mountain', 'waves', 'shield', 'crosshair', 'circle-dot',\n 'bookmark', 'gem', 'radio', 'compass',\n]\n\nexport const GEO_TYPE_META_SCHEMAS: Record<string, PageTypeMetaField[]> = {\n marker: [\n { type: 'location', latKey: 'geoLat', lngKey: 'geoLng', label: 'Location' },\n { type: 'icon', key: 'icon', options: GEO_ICON_OPTIONS, label: 'Icon' },\n { type: 'colorPreset', key: 'color', presets: GEO_COLOR_PRESETS, label: 'Color' },\n ],\n line: [\n { type: 'colorPreset', key: 'color', presets: GEO_COLOR_PRESETS, label: 'Color' },\n ],\n measure: [],\n}\n\n// ── Static page type registry ────────────────────────────────────────────────\n\nexport const PAGE_TYPES: Record<string, PageTypeInfo> = {\n doc: {\n key: 'doc',\n label: 'Document',\n icon: 'file-text',\n description: 'Rich text document with real-time collaboration',\n core: true,\n supportsChildren: true,\n },\n prose: {\n key: 'prose',\n label: 'Prose',\n icon: 'pen-tool',\n description: 'Long-form prose with serif typography and a narrow readable measure',\n core: true,\n supportsChildren: true,\n childLabel: 'Item',\n defaultDepth: -1,\n },\n kanban: {\n key: 'kanban',\n label: 'Kanban',\n icon: 'kanban',\n description: 'Drag-and-drop task board with columns and cards',\n core: true,\n supportsChildren: true,\n childLabel: 'Column',\n grandchildLabel: 'Card',\n defaultMetaFields: [\n { type: 'select', key: 'kanbanColumnWidth', options: ['narrow', 'default', 'wide'], label: 'Column Width' },\n ],\n },\n gallery: {\n key: 'gallery',\n label: 'Gallery',\n icon: 'images',\n description: 'Visual grid of items with rich content',\n core: true,\n supportsChildren: true,\n childLabel: 'Item',\n metaSchema: [\n { type: 'location', latKey: 'geoLat', lngKey: 'geoLng', label: 'Location' },\n { type: 'datetime', key: 'datetimeStart', label: 'Date' },\n { type: 'tags', key: 'tags', label: 'Tags' },\n { type: 'rating', key: 'rating', max: 5, label: 'Rating' },\n { type: 'icon', key: 'icon', label: 'Icon' },\n { type: 'colorPreset', key: 'color', presets: ['#6366f1', '#ec4899', '#f97316', '#22c55e', '#3b82f6', '#a855f7'], label: 'Color' },\n ],\n defaultMetaFields: [\n { type: 'number', key: 'galleryColumns', min: 1, max: 6, step: 1, label: 'Columns' },\n { type: 'select', key: 'galleryAspect', options: ['square', '4:3', '3:2', '16:9', 'free'], label: 'Aspect Ratio' },\n { type: 'select', key: 'galleryCardStyle', options: ['default', 'compact', 'detailed'], label: 'Card Style' },\n { type: 'toggle', key: 'galleryShowLabels', label: 'Show Labels' },\n { type: 'select', key: 'gallerySortBy', options: ['manual', 'date', 'name', 'rating'], label: 'Sort' },\n ],\n },\n table: {\n key: 'table',\n label: 'Table',\n icon: 'table',\n description: 'Collaborative spreadsheet with custom fields',\n core: true,\n supportsChildren: true,\n childLabel: 'Column',\n grandchildLabel: 'Row',\n defaultMetaFields: [\n { type: 'select', key: 'tableMode', options: ['hierarchy', 'flat'], label: 'Mode' },\n { type: 'select', key: 'tableSortDir', options: ['asc', 'desc'], label: 'Sort Direction' },\n ],\n },\n outline: {\n key: 'outline',\n label: 'Outline',\n icon: 'list-tree',\n description: 'Hierarchical outline with keyboard navigation',\n core: true,\n supportsChildren: true,\n childLabel: 'Item',\n defaultDepth: -1,\n },\n checklist: {\n key: 'checklist',\n label: 'Checklist',\n icon: 'check-square',\n description: 'Collaborative checklist with sub-tasks, drag-and-drop, and due dates',\n core: true,\n supportsChildren: true,\n childLabel: 'Task',\n defaultDepth: -1,\n metaSchema: [\n { type: 'toggle', key: 'checked', label: 'Done' },\n { type: 'select', key: 'priority', options: ['none', 'low', 'medium', 'high'], label: 'Priority' },\n { type: 'date', key: 'dateEnd', label: 'Due date' },\n ],\n defaultMetaFields: [\n { type: 'select', key: 'checklistFilter', options: ['all', 'active', 'completed'], label: 'Filter' },\n { type: 'select', key: 'checklistSort', options: ['manual', 'priority', 'due'], label: 'Sort' },\n ],\n },\n graph: {\n key: 'graph',\n label: 'Graph',\n icon: 'git-fork',\n description: 'Force-directed knowledge graph — full document tree as nodes & edges',\n core: true,\n supportsChildren: true,\n childLabel: 'Node',\n defaultMetaFields: [\n { type: 'toggle', key: 'showRefEdges', label: 'Show Ref Edges', default: true },\n ],\n },\n timeline: {\n key: 'timeline',\n label: 'Timeline',\n icon: 'gantt-chart',\n description: 'Gantt-style project timeline with epics and tasks',\n core: true,\n supportsChildren: true,\n childLabel: 'Epic',\n grandchildLabel: 'Task',\n metaSchema: [\n { type: 'daterange', startKey: 'dateStart', endKey: 'dateEnd' },\n { type: 'slider', key: 'taskProgress', min: 0, max: 100, label: 'Progress' },\n { type: 'colorPreset', key: 'color', presets: ['#6366f1', '#818cf8', '#f97316', '#22c55e', '#3b82f6', '#a855f7'], label: 'Color' },\n ],\n },\n calendar: {\n key: 'calendar',\n label: 'Calendar',\n icon: 'calendar',\n description: 'Event calendar with month, week, and day views',\n core: true,\n supportsChildren: true,\n childLabel: 'Event',\n metaSchema: [\n { type: 'datetimerange', startKey: 'datetimeStart', endKey: 'datetimeEnd', allDayKey: 'allDay' },\n { type: 'colorPreset', key: 'color', presets: ['#6366f1', '#ec4899', '#f97316', '#22c55e', '#3b82f6', '#a855f7'], label: 'Color' },\n { type: 'icon', key: 'icon', label: 'Icon' },\n ],\n defaultMetaFields: [\n { type: 'select', key: 'calendarWeekStart', options: ['sun', 'mon'], label: 'Week Starts' },\n { type: 'select', key: 'calendarView', options: ['month', 'week', 'day'], label: 'Default View' },\n { type: 'toggle', key: 'calendarShowWeekNumbers', label: 'Show Week Numbers' },\n ],\n },\n map: {\n key: 'map',\n label: 'Map',\n icon: 'map',\n description: 'Collaborative world map with shared markers',\n core: true,\n supportsChildren: true,\n childLabel: 'Location',\n defaultMetaFields: [\n { type: 'toggle', key: 'mapShowLabels', label: 'Show Labels', default: true },\n ],\n },\n dashboard: {\n key: 'dashboard',\n label: 'Dashboard',\n icon: 'layout-dashboard',\n description: 'Arrange documents as draggable icons with optional widget views',\n core: true,\n supportsChildren: true,\n childLabel: 'Item',\n },\n call: {\n key: 'call',\n label: 'Call',\n icon: 'phone',\n description: 'Video call room with live audio and screen sharing',\n core: true,\n supportsChildren: false,\n },\n chart: {\n key: 'chart',\n label: 'Chart',\n icon: 'bar-chart-3',\n description: 'Charts — manual data points or aggregation over document trees',\n core: true,\n supportsChildren: true,\n childLabel: 'Data Point',\n grandchildLabel: 'Data Point',\n metaSchema: [\n { type: 'number', key: 'number', step: 0.01, label: 'Value' },\n { type: 'colorPreset', key: 'color', presets: ['#6366f1', '#ec4899', '#f97316', '#22c55e', '#3b82f6', '#a855f7', '#14b8a6', '#eab308'], label: 'Color' },\n { type: 'tags', key: 'tags', label: 'Tags' },\n ],\n defaultMetaFields: [\n { type: 'select', key: 'chartType', options: ['bar', 'stacked bar', 'line', 'donut', 'treemap'], label: 'Chart Type' },\n { type: 'select', key: 'chartMetric', options: ['value', 'type', 'tag', 'status', 'priority', 'activity', 'completion'], label: 'Metric' },\n { type: 'select', key: 'chartColorScheme', options: ['default', 'warm', 'cool', 'mono'], label: 'Colors' },\n { type: 'number', key: 'chartLimit', min: 3, max: 30, step: 1, label: 'Max Items' },\n { type: 'toggle', key: 'chartShowLegend', label: 'Show Legend', default: true },\n { type: 'toggle', key: 'chartShowValues', label: 'Show Values' },\n ],\n },\n sheets: {\n key: 'sheets',\n label: 'Sheets',\n icon: 'grid-3x3',\n description: 'Spreadsheet — cells, formulas, and formatting in a collaborative grid',\n core: true,\n supportsChildren: true,\n childLabel: 'Column',\n grandchildLabel: 'Cell',\n defaultMetaFields: [\n { type: 'number', key: 'sheetsDefaultColWidth', min: 40, max: 500, step: 10, label: 'Column Width' },\n { type: 'number', key: 'sheetsDefaultRowHeight', min: 20, max: 100, step: 2, label: 'Row Height' },\n { type: 'toggle', key: 'sheetsShowGridlines', label: 'Gridlines' },\n ],\n },\n slides: {\n key: 'slides',\n label: 'Slides',\n icon: 'presentation',\n description: 'Presentation slides with two-axis navigation',\n core: true,\n supportsChildren: true,\n childLabel: 'Slide',\n grandchildLabel: 'Sub-slide',\n metaSchema: [\n { type: 'select', key: 'slidesTransition', options: ['none', 'fade', 'slide'], label: 'Transition' },\n { type: 'colorPreset', key: 'color', presets: ['#6366f1', '#ec4899', '#f97316', '#22c55e', '#3b82f6', '#a855f7'], label: 'Accent' },\n ],\n defaultMetaFields: [\n { type: 'select', key: 'slidesTheme', options: ['dark', 'light'], label: 'Theme' },\n ],\n },\n overview: {\n key: 'overview',\n label: 'Overview',\n icon: 'radar',\n description: 'Space home — activity, people, stats, and health at a glance',\n core: true,\n supportsChildren: true,\n childLabel: 'Page',\n },\n\n // Plugin-contributed types — require the named plugin to be enabled server-side.\n\n spatial: {\n key: 'spatial',\n label: 'Spatial',\n icon: 'box',\n description: '3D scene with collaborative objects and real-time presence',\n core: false,\n plugin: 'spatial',\n supportsChildren: true,\n childLabel: 'Object',\n grandchildLabel: 'Part',\n defaultDepth: -1,\n metaSchema: [\n { type: 'select', key: 'spShape', options: ['box', 'sphere', 'cylinder', 'cone', 'plane', 'torus', 'glb'], label: 'Shape' },\n { type: 'colorPreset', key: 'color', presets: ['#6366f1', '#ef4444', '#22c55e', '#3b82f6', '#f97316', '#a855f7', '#ec4899', '#14b8a6'], label: 'Color' },\n { type: 'slider', key: 'spOpacity', min: 0, max: 100, label: 'Opacity' },\n { type: 'number', key: 'spX', step: 0.1, label: 'X' },\n { type: 'number', key: 'spY', step: 0.1, label: 'Y' },\n { type: 'number', key: 'spZ', step: 0.1, label: 'Z' },\n { type: 'number', key: 'spRX', min: -180, max: 180, step: 1, label: 'Rot X' },\n { type: 'number', key: 'spRY', min: -180, max: 180, step: 1, label: 'Rot Y' },\n { type: 'number', key: 'spRZ', min: -180, max: 180, step: 1, label: 'Rot Z' },\n { type: 'number', key: 'spSX', min: 0.01, max: 100, step: 0.1, label: 'Scale X' },\n { type: 'number', key: 'spSY', min: 0.01, max: 100, step: 0.1, label: 'Scale Y' },\n { type: 'number', key: 'spSZ', min: 0.01, max: 100, step: 0.1, label: 'Scale Z' },\n ],\n defaultMetaFields: [\n { type: 'toggle', key: 'spatialGridVisible', label: 'Show Grid', default: true },\n ],\n },\n media: {\n key: 'media',\n label: 'Media',\n icon: 'disc-3',\n description: 'Media player with synced listening and playlists',\n core: false,\n plugin: 'media',\n supportsChildren: true,\n childLabel: 'Track',\n defaultDepth: -1,\n metaSchema: [\n { type: 'tags', key: 'tags', label: 'Tags' },\n ],\n defaultMetaFields: [\n { type: 'select', key: 'mediaRepeat', options: ['off', 'all', 'one'], label: 'Repeat' },\n { type: 'toggle', key: 'mediaShuffle', label: 'Shuffle' },\n ],\n },\n coder: {\n key: 'coder',\n label: 'Coder',\n icon: 'code-2',\n description: 'Collaborative multi-file coding environment',\n core: false,\n plugin: 'coder',\n supportsChildren: true,\n childLabel: 'File',\n defaultDepth: -1,\n metaSchema: [\n { type: 'select', key: 'fileType', options: ['vue', 'ts', 'js', 'css', 'json', 'folder'], label: 'Type' },\n { type: 'toggle', key: 'entry', label: 'Entry Point' },\n ],\n },\n}\n\nexport const TYPE_ALIASES: Record<string, string> = {\n desktop: 'dashboard',\n}\n\nexport function resolvePageType(key: string | undefined): PageTypeInfo | undefined {\n if (!key) return undefined\n const resolved = TYPE_ALIASES[key] ?? key\n return PAGE_TYPES[resolved]\n}\n","/**\n * Phase 2 Day 1 — typed projection types for the provider.\n *\n * The provider package never imports `@abraca/schema` directly (Rule 1 —\n * core stays schema-free). Instead, it declares a structural witness that\n * any registry — including `@abraca/schema`'s `SchemaRegistry<TMap>` — can\n * satisfy.\n *\n * Consumers parameterise typed accessors with the registry value:\n *\n * const board = dm.tree.getTyped(kanbanSchema, \"kanban\", id);\n * // board.meta.kanbanColumnWidth is typed as the kanban enum | undefined\n *\n * The phantom `__metaMap` carries the per-doc-type meta map so the\n * generics below can extract it without a runtime dependency.\n */\nimport type { PageMeta, TreeEntry } from \"./DocTypes.ts\";\n\n/**\n * Structural shape of a typed schema registry. The `TMap` parameter is the\n * meta-type map keyed by doc-type name (e.g. `{ \"kanban\": KanbanMeta, ... }`).\n * `@abraca/schema`'s `SchemaRegistry<TMap>` satisfies this shape.\n */\nexport interface SchemaRegistryLike<\n\tTMap extends Record<string, unknown> = Record<string, unknown>,\n> {\n\treadonly types: ReadonlyMap<string, unknown>;\n\treadonly __metaMap?: TMap;\n}\n\n/** Extract the doc-type names from a registry. */\nexport type SchemaDocTypeName<S> =\n\tS extends SchemaRegistryLike<infer M> ? keyof M & string : never;\n\n/** Extract the meta type for a given doc-type name from a registry. */\nexport type SchemaMetaOf<S, N extends string> =\n\tS extends SchemaRegistryLike<infer M>\n\t\t? N extends keyof M\n\t\t\t? M[N]\n\t\t\t: never\n\t\t: never;\n\n/**\n * A tree entry projected against a typed registry. The `meta` field is\n * narrowed to `TMap[N] | undefined` so consumers get full type inference\n * without an explicit cast.\n *\n * Note: `meta` is optional even when the registry mandates fields — the\n * tree may contain entries written before the schema was authored, and\n * Rule 4 means we don't reject them at read time.\n */\nexport interface TypedTreeEntry<\n\tTMap extends Record<string, unknown>,\n\tN extends keyof TMap & string,\n> {\n\treadonly id: string;\n\treadonly type: N;\n\treadonly label: string;\n\treadonly parentId: string | null;\n\treadonly order: number;\n\treadonly meta: TMap[N] | undefined;\n\treadonly createdAt: number | undefined;\n\treadonly updatedAt: number | undefined;\n}\n\n/**\n * A typed surface bound to a schema. Returned by\n * `DocumentManager.docs(schema)` so the schema doesn't have to be repeated\n * at every call site.\n *\n * Read methods (`get`, `getEntry`, `narrow`) project the existing\n * untyped tree without performing schema validation. Write methods\n * (`update`, `set`, `clear`) delegate to `MetaManager` and are subject\n * to whatever validator was attached via `MetaManager.setSchema` —\n * they do NOT auto-attach the registry passed to `dm.docs()`.\n */\nexport interface TypedDocsClient<TMap extends Record<string, unknown>> {\n\t/**\n\t * Fetch a tree entry projected as the requested doc-type. Returns\n\t * `null` when the entry doesn't exist OR when its `type` field doesn't\n\t * match `expectedType`.\n\t */\n\tget<N extends keyof TMap & string>(\n\t\texpectedType: N,\n\t\tid: string,\n\t): TypedTreeEntry<TMap, N> | null;\n\t/**\n\t * Fetch the raw, untyped entry (no type-narrowing applied). Useful when\n\t * the caller wants the underlying record without the projection.\n\t */\n\tgetEntry(id: string): TreeEntry | null;\n\t/**\n\t * Discriminator helper: narrows an arbitrary `TreeEntry` to the\n\t * requested doc-type, returning a typed projection or `null` on mismatch.\n\t * No runtime read — pure type-guard helper.\n\t */\n\tnarrow<N extends keyof TMap & string>(\n\t\texpectedType: N,\n\t\tentry: TreeEntry | null | undefined,\n\t): TypedTreeEntry<TMap, N> | null;\n\t/**\n\t * Merge typed meta into a document's metadata. Throws\n\t * `TypedDocTypeMismatchError` when the stored entry's `type` doesn't\n\t * match `expectedType`; throws `MetaValidationError` when a validator\n\t * is attached and the merged meta fails validation.\n\t */\n\tupdate<N extends keyof TMap & string>(\n\t\texpectedType: N,\n\t\tid: string,\n\t\tmeta: Partial<TMap[N]>,\n\t): void;\n\t/**\n\t * Replace all metadata on a document with a fully-typed payload.\n\t * Same throw semantics as `update`.\n\t */\n\tset<N extends keyof TMap & string>(\n\t\texpectedType: N,\n\t\tid: string,\n\t\tmeta: TMap[N],\n\t): void;\n\t/**\n\t * Delete specific metadata keys. Constrained to the typed key-set of\n\t * `TMap[N]` so typos surface at compile time.\n\t */\n\tclear<N extends keyof TMap & string>(\n\t\texpectedType: N,\n\t\tid: string,\n\t\tkeys: ReadonlyArray<keyof TMap[N] & string>,\n\t): void;\n}\n\n/**\n * Thrown by typed write methods on `TypedDocsClient` when the stored\n * entry's `type` doesn't match the caller's `expectedType`. Distinct from\n * `MetaValidationError` (which signals schema-content mismatches).\n */\nexport class TypedDocTypeMismatchError extends Error {\n\treadonly docId: string;\n\treadonly expectedType: string;\n\treadonly actualType: string | undefined;\n\tconstructor(docId: string, expectedType: string, actualType: string | undefined) {\n\t\tsuper(\n\t\t\t`Typed write on document ${docId} expected type \"${expectedType}\" but stored type is ${\n\t\t\t\tactualType === undefined ? \"(none)\" : `\"${actualType}\"`\n\t\t\t}`,\n\t\t);\n\t\tthis.name = \"TypedDocTypeMismatchError\";\n\t\tthis.docId = docId;\n\t\tthis.expectedType = expectedType;\n\t\tthis.actualType = actualType;\n\t}\n}\n\n// ── Internal: shared projection helper ──────────────────────────────────────\n\n/**\n * Project a raw `TreeEntry` to a `TypedTreeEntry<TMap, N>` if its `type`\n * matches; otherwise return `null`. Used by both `TreeManager.getTyped`\n * and `TypedDocsClient.{get,narrow}` to keep semantics consistent.\n */\nexport function projectTreeEntry<\n\tTMap extends Record<string, unknown>,\n\tN extends keyof TMap & string,\n>(entry: TreeEntry | null | undefined, expectedType: N):\n\tTypedTreeEntry<TMap, N> | null\n{\n\tif (!entry) return null;\n\tif (entry.type !== expectedType) return null;\n\treturn {\n\t\tid: entry.id,\n\t\ttype: expectedType,\n\t\tlabel: entry.label,\n\t\tparentId: entry.parentId,\n\t\torder: entry.order,\n\t\tmeta: entry.meta as (TMap[N] & PageMeta) | undefined,\n\t\tcreatedAt: entry.createdAt,\n\t\tupdatedAt: entry.updatedAt,\n\t};\n}\n","/**\n * TreeManager — typed ORM layer over the root Y.Doc's \"doc-tree\" / \"doc-trash\"\n * Y.Maps.\n *\n * Extracted from `mcp/tools/tree.ts` and `cli/commands/documents.ts` logic.\n * All tree CRUD operations go through this class.\n */\nimport type * as Y from \"yjs\";\nimport type {\n\tPageMeta,\n\tTreeEntry,\n\tTreeNode,\n\tTreeSearchResult,\n} from \"./DocTypes.ts\";\nimport { resolvePageType } from \"./DocTypes.ts\";\nimport {\n\tmakeEntryMap,\n\tnormalizeRootId,\n\tpatchEntry,\n\ttoPlain,\n} from \"./DocUtils.ts\";\nimport type { DocumentManager } from \"./DocumentManager.ts\";\nimport {\n\tprojectTreeEntry,\n\ttype SchemaRegistryLike,\n\ttype TypedTreeEntry,\n} from \"./SchemaTypes.ts\";\n\n/**\n * Stable total order over tree siblings: `order` ascending, then `id`\n * ascending as a deterministic tiebreak. The legacy scan sorted by\n * `order` alone and left ties to insertion/iteration order — a superset\n * change that makes cursor pagination well-defined.\n */\nfunction cmpKey(oa: number, ia: string, ob: number, ib: string): number {\n\tif (oa !== ob) return oa < ob ? -1 : 1;\n\treturn ia < ib ? -1 : ia > ib ? 1 : 0;\n}\nfunction cmpEntry(a: TreeEntry, b: TreeEntry): number {\n\treturn cmpKey(a.order ?? 0, a.id, b.order ?? 0, b.id);\n}\n\n/**\n * Deterministic, convergent cycle break for the parent-pointer forest.\n *\n * Concurrent offline reparents converge (Yjs LWW on each entry's *own*\n * `parentId` key) to a state that can contain a directed cycle — e.g. peer A\n * moves X under Y while peer B moves Y under X yields `X.parent=Y` AND\n * `Y.parent=X`. Both writes touch different keys so both survive, and the\n * whole subtree then floats unreachable from root (the \"orphaned subtree\"\n * corruption — §3b of OFFLINE-FIRST-TREE-AUDIT). Yjs guarantees every replica\n * converges to the SAME cyclic map, so any repair that is a pure function of\n * that map is itself convergent: every replica picks the identical break and\n * agrees on the result with no coordinator (a lightweight stand-in for the\n * full Kleppmann fold — it loses one move's intent, but never corrupts).\n *\n * Rule: in each cycle, the node with the lexicographically-greatest id is\n * logically reparented to root. Returns the set of such break-node ids — empty\n * when the forest is already acyclic (the overwhelmingly common case, so the\n * hot path adds one O(n) walk and changes no behavior).\n *\n * `parentOf` returns the effective *normalized* parent (null = root); a parent\n * id absent from `ids` is a strand, not a cycle (Tier-0 does not auto-rescue\n * strands). Self-loops (`parentId === id`) are a degenerate one-node cycle and\n * are handled. The Rust provider mirrors this exactly (`cycle_break_ids`).\n */\nfunction cycleBreakIds(\n\tids: Iterable<string>,\n\tparentOf: (id: string) => string | null,\n): Set<string> {\n\tconst idSet = new Set(ids);\n\tconst done = new Set<string>();\n\tconst breaks = new Set<string>();\n\tfor (const start of idSet) {\n\t\tif (done.has(start)) continue;\n\t\tconst path: string[] = [];\n\t\tconst onPath = new Map<string, number>();\n\t\tlet cur: string | null = start;\n\t\twhile (cur !== null && idSet.has(cur) && !done.has(cur)) {\n\t\t\tconst seenAt = onPath.get(cur);\n\t\t\tif (seenAt !== undefined) {\n\t\t\t\t// path[seenAt..] is the cycle; break its greatest id.\n\t\t\t\tlet maxId = path[seenAt];\n\t\t\t\tfor (let i = seenAt + 1; i < path.length; i++) {\n\t\t\t\t\tif (path[i] > maxId) maxId = path[i];\n\t\t\t\t}\n\t\t\t\tbreaks.add(maxId);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tonPath.set(cur, path.length);\n\t\t\tpath.push(cur);\n\t\t\tcur = parentOf(cur);\n\t\t}\n\t\tfor (const id of path) done.add(id);\n\t}\n\treturn breaks;\n}\n\n/** Opaque, dependency-free cursor over the (order,id) sibling order. */\nfunction encodeCursor(order: number, id: string): string {\n\treturn encodeURIComponent(JSON.stringify([order ?? 0, id]));\n}\nfunction decodeCursor(c: string): { order: number; id: string } | null {\n\ttry {\n\t\tconst v = JSON.parse(decodeURIComponent(c)) as unknown;\n\t\tif (\n\t\t\tArray.isArray(v) &&\n\t\t\ttypeof v[0] === \"number\" &&\n\t\t\ttypeof v[1] === \"string\"\n\t\t) {\n\t\t\treturn { order: v[0], id: v[1] };\n\t\t}\n\t} catch {\n\t\t// Garbage / tampered cursor → treat as \"from the beginning\".\n\t}\n\treturn null;\n}\n\nexport interface ChildrenPage {\n\tentries: TreeEntry[];\n\t/** Pass back as `cursor` for the next page; `null` when exhausted. */\n\tnextCursor: string | null;\n}\n\nexport class TreeManager {\n\tconstructor(private dm: DocumentManager) {}\n\n\t// ── Path-1 prototype: lazy parent→children index ──────────────────────────\n\t//\n\t// Gated by `dm.treeIndexEnabled`. When off, every method below falls\n\t// through to the original whole-map scan (unchanged). When on, tree\n\t// WALKS resolve against a normalized adjacency index that is rebuilt\n\t// lazily: an `observeDeep` on the bound `doc-tree` Y.Map only flips a\n\t// dirty bit, so the O(n) rebuild happens at most once per mutation\n\t// batch instead of once per read, and reads between writes are\n\t// O(k)/O(result) instead of O(n)/O(n²). `readEntries`/`get` keep RAW\n\t// parentId for round-trip consumers and are intentionally NOT indexed.\n\tprivate _idxMap: Y.Map<unknown> | null = null;\n\tprivate _idxObserver: (() => void) | null = null;\n\tprivate _idxDirty = true;\n\tprivate _byId = new Map<string, TreeEntry>();\n\tprivate _childrenByParent = new Map<string | null, TreeEntry[]>();\n\n\t/**\n\t * Ensure the index is enabled, bound to the current root doc's tree\n\t * map, and fresh. Returns `false` when the index is disabled or there\n\t * is no tree map yet — callers then use the legacy scan path.\n\t */\n\tprivate ensureIndex(): boolean {\n\t\tif (!this.dm.treeIndexEnabled) return false;\n\t\tconst treeMap = this.dm.getTreeMap();\n\t\tif (!treeMap) {\n\t\t\tthis.unbindIndex();\n\t\t\treturn false;\n\t\t}\n\t\tif (treeMap !== this._idxMap) {\n\t\t\t// Root doc (space) swapped, or first use — rebind the observer.\n\t\t\tthis.unbindIndex();\n\t\t\tconst obs = () => {\n\t\t\t\tthis._idxDirty = true;\n\t\t\t};\n\t\t\ttreeMap.observeDeep(obs);\n\t\t\tthis._idxMap = treeMap;\n\t\t\tthis._idxObserver = obs;\n\t\t\tthis._idxDirty = true;\n\t\t}\n\t\tif (this._idxDirty) this.rebuildIndex(treeMap);\n\t\treturn true;\n\t}\n\n\tprivate unbindIndex(): void {\n\t\tif (this._idxMap && this._idxObserver) {\n\t\t\tthis._idxMap.unobserveDeep(this._idxObserver);\n\t\t}\n\t\tthis._idxMap = null;\n\t\tthis._idxObserver = null;\n\t\tthis._byId = new Map();\n\t\tthis._childrenByParent = new Map();\n\t\tthis._idxDirty = true;\n\t}\n\n\tprivate rebuildIndex(treeMap: Y.Map<unknown>): void {\n\t\tconst root = this.dm.rootDocId;\n\t\tconst byId = new Map<string, TreeEntry>();\n\t\ttreeMap.forEach((raw: unknown, id: string) => {\n\t\t\tconst value = toPlain(raw) as Record<string, unknown>;\n\t\t\tif (typeof value !== \"object\" || value === null) return;\n\t\t\tbyId.set(id, {\n\t\t\t\tid,\n\t\t\t\tlabel: (value.label as string) || \"Untitled\",\n\t\t\t\tparentId: normalizeRootId(\n\t\t\t\t\t(value.parentId as string | null) ?? null,\n\t\t\t\t\troot,\n\t\t\t\t),\n\t\t\t\torder: (value.order as number) ?? 0,\n\t\t\t\ttype: value.type as string | undefined,\n\t\t\t\tmeta: value.meta as PageMeta | undefined,\n\t\t\t\tcreatedAt: value.createdAt as number | undefined,\n\t\t\t\tupdatedAt: value.updatedAt as number | undefined,\n\t\t\t});\n\t\t});\n\t\t// Converge concurrent-move cycles: logically reparent each cycle's\n\t\t// break node to root so the materialized adjacency is acyclic and\n\t\t// fully reachable. Non-mutating — the CRDT is untouched; only this\n\t\t// read-side cache is corrected (`repairTree()` persists the fix when\n\t\t// a writer wants it). No-op for the common acyclic tree. See\n\t\t// {@link cycleBreakIds}.\n\t\tconst breaks = cycleBreakIds(\n\t\t\tbyId.keys(),\n\t\t\t(id) => byId.get(id)?.parentId ?? null,\n\t\t);\n\t\tfor (const id of breaks) {\n\t\t\tconst e = byId.get(id);\n\t\t\tif (e) e.parentId = null;\n\t\t}\n\t\tconst childrenByParent = new Map<string | null, TreeEntry[]>();\n\t\tfor (const entry of byId.values()) {\n\t\t\tlet bucket = childrenByParent.get(entry.parentId);\n\t\t\tif (!bucket) {\n\t\t\t\tbucket = [];\n\t\t\t\tchildrenByParent.set(entry.parentId, bucket);\n\t\t\t}\n\t\t\tbucket.push(entry);\n\t\t}\n\t\tfor (const bucket of childrenByParent.values()) bucket.sort(cmpEntry);\n\t\tthis._byId = byId;\n\t\tthis._childrenByParent = childrenByParent;\n\t\tthis._idxDirty = false;\n\t}\n\n\t/**\n\t * Release the deep observer. Optional — the observer is auto-rebound\n\t * on space switch and becomes moot when the root Y.Doc is GC'd — but\n\t * available for consumers that want deterministic teardown.\n\t */\n\tdispose(): void {\n\t\tthis.unbindIndex();\n\t}\n\n\t// ── Reading ───────────────────────────────────────────────────────────────\n\n\t/** Read all tree entries as plain objects. */\n\treadEntries(): TreeEntry[] {\n\t\tconst treeMap = this.dm.getTreeMap();\n\t\tif (!treeMap) return [];\n\n\t\tconst entries: TreeEntry[] = [];\n\t\ttreeMap.forEach((raw: unknown, id: string) => {\n\t\t\tconst value = toPlain(raw) as Record<string, unknown>;\n\t\t\tif (typeof value !== \"object\" || value === null) return;\n\t\t\tentries.push({\n\t\t\t\tid,\n\t\t\t\tlabel: (value.label as string) || \"Untitled\",\n\t\t\t\tparentId: (value.parentId as string | null) ?? null,\n\t\t\t\torder: (value.order as number) ?? 0,\n\t\t\t\ttype: value.type as string | undefined,\n\t\t\t\tmeta: value.meta as PageMeta | undefined,\n\t\t\t\tcreatedAt: value.createdAt as number | undefined,\n\t\t\t\tupdatedAt: value.updatedAt as number | undefined,\n\t\t\t});\n\t\t});\n\t\treturn entries;\n\t}\n\n\t/**\n\t * Like {@link readEntries} but with every entry's *stored* parentId\n\t * run through {@link normalizeRootId} (parentId === rootDocId → null),\n\t * so a cou-sh / orphan-rescue top-level doc (parentId === spaceRoot)\n\t * resolves to top-level identically to a provider-created one\n\t * (parentId: null). Without this, the raw `parentId === spaceRoot`\n\t * form never matches the normalized `null` query and such docs are\n\t * silently invisible cross-client. Mirrors the Rust provider's\n\t * `normalized_entries`. readEntries/get keep raw values for\n\t * round-trip consumers; only tree-walk reads use this.\n\t */\n\tprivate normalizedEntries(): TreeEntry[] {\n\t\tif (this.ensureIndex()) return Array.from(this._byId.values());\n\t\tconst root = this.dm.rootDocId;\n\t\tconst entries = this.readEntries().map((e) => ({\n\t\t\t...e,\n\t\t\tparentId: normalizeRootId(e.parentId, root),\n\t\t}));\n\t\t// Same read-side cycle break as the indexed path (see\n\t\t// {@link rebuildIndex} / {@link cycleBreakIds}) so the legacy scan\n\t\t// walks an acyclic, fully-reachable tree too. No-op when acyclic.\n\t\tconst byId = new Map(entries.map((e) => [e.id, e]));\n\t\tconst breaks = cycleBreakIds(\n\t\t\tbyId.keys(),\n\t\t\t(id) => byId.get(id)?.parentId ?? null,\n\t\t);\n\t\tfor (const id of breaks) {\n\t\t\tconst e = byId.get(id);\n\t\t\tif (e) e.parentId = null;\n\t\t}\n\t\treturn entries;\n\t}\n\n\t/** Get immediate children of a parent (sorted by order). */\n\tchildrenOf(parentId: string | null): TreeEntry[] {\n\t\tconst normalized = normalizeRootId(parentId, this.dm.rootDocId);\n\t\tif (this.ensureIndex()) {\n\t\t\t// Copy: callers (descendantsOf, find, consumers) must not\n\t\t\t// mutate the cached bucket.\n\t\t\tconst bucket = this._childrenByParent.get(normalized);\n\t\t\treturn bucket ? bucket.slice() : [];\n\t\t}\n\t\treturn this.normalizedEntries()\n\t\t\t.filter((e) => e.parentId === normalized)\n\t\t\t.sort((a, b) => (a.order ?? 0) - (b.order ?? 0));\n\t}\n\n\t/**\n\t * Paginated immediate children — the Path-1 surface for large fan-out\n\t * parents. Walks the same stable (order,id) sibling order as\n\t * {@link childrenOf}; `cursor` is opaque (round-trip `nextCursor`).\n\t * `limit` defaults to 100. A stale/garbage cursor restarts from the\n\t * head rather than throwing. Cursor stability is exact when the index\n\t * is enabled; on the legacy scan path siblings with equal `order`\n\t * may shift between calls.\n\t */\n\tchildrenOfPage(\n\t\tparentId: string | null,\n\t\topts: { limit?: number; cursor?: string | null } = {},\n\t): ChildrenPage {\n\t\tconst all = this.childrenOf(parentId);\n\t\tconst limit =\n\t\t\topts.limit != null && opts.limit > 0 ? Math.floor(opts.limit) : 100;\n\t\tlet start = 0;\n\t\tif (opts.cursor) {\n\t\t\tconst dec = decodeCursor(opts.cursor);\n\t\t\tif (dec) {\n\t\t\t\tconst at = all.findIndex(\n\t\t\t\t\t(e) => cmpKey(e.order ?? 0, e.id, dec.order, dec.id) > 0,\n\t\t\t\t);\n\t\t\t\tstart = at < 0 ? all.length : at;\n\t\t\t}\n\t\t}\n\t\tconst entries = all.slice(start, start + limit);\n\t\tconst last = entries[entries.length - 1];\n\t\tconst nextCursor =\n\t\t\tlast && start + limit < all.length\n\t\t\t\t? encodeCursor(last.order ?? 0, last.id)\n\t\t\t\t: null;\n\t\treturn { entries, nextCursor };\n\t}\n\n\t/** Get all descendants recursively. */\n\tdescendantsOf(parentId: string | null): TreeEntry[] {\n\t\tconst normalized = normalizeRootId(parentId, this.dm.rootDocId);\n\t\tif (this.ensureIndex()) {\n\t\t\tconst result: TreeEntry[] = [];\n\t\t\tconst visited = new Set<string>();\n\t\t\tconst walk = (pid: string | null) => {\n\t\t\t\tif (pid !== null) {\n\t\t\t\t\tif (visited.has(pid)) return;\n\t\t\t\t\tvisited.add(pid);\n\t\t\t\t}\n\t\t\t\tconst bucket = this._childrenByParent.get(pid);\n\t\t\t\tif (!bucket) return;\n\t\t\t\tfor (const child of bucket) {\n\t\t\t\t\tresult.push(child);\n\t\t\t\t\twalk(child.id);\n\t\t\t\t}\n\t\t\t};\n\t\t\twalk(normalized);\n\t\t\treturn result;\n\t\t}\n\t\tconst entries = this.normalizedEntries();\n\t\tconst result: TreeEntry[] = [];\n\t\tconst visited = new Set<string>();\n\n\t\tconst collect = (pid: string | null) => {\n\t\t\tif (pid !== null && visited.has(pid)) return;\n\t\t\tif (pid !== null) visited.add(pid);\n\t\t\tfor (const child of entries\n\t\t\t\t.filter((e) => e.parentId === pid)\n\t\t\t\t.sort((a, b) => (a.order ?? 0) - (b.order ?? 0))) {\n\t\t\t\tresult.push(child);\n\t\t\t\tcollect(child.id);\n\t\t\t}\n\t\t};\n\t\tcollect(normalized);\n\t\treturn result;\n\t}\n\n\t/** Build nested tree JSON. */\n\tbuildTree(rootId?: string | null, maxDepth = 3): TreeNode[] {\n\t\tconst normalized = normalizeRootId(rootId ?? null, this.dm.rootDocId);\n\t\tif (this.ensureIndex()) {\n\t\t\treturn this._buildTreeIndexed(normalized, maxDepth, 0, new Set());\n\t\t}\n\t\tconst entries = this.normalizedEntries();\n\t\treturn this._buildTree(entries, normalized, maxDepth, 0, new Set());\n\t}\n\n\tprivate _buildTreeIndexed(\n\t\trootId: string | null,\n\t\tmaxDepth: number,\n\t\tcurrentDepth: number,\n\t\tvisited: Set<string>,\n\t): TreeNode[] {\n\t\tif (maxDepth >= 0 && currentDepth >= maxDepth) return [];\n\t\tconst children = this._childrenByParent.get(rootId) ?? [];\n\t\treturn children\n\t\t\t.filter((e) => !visited.has(e.id))\n\t\t\t.map((entry) => {\n\t\t\t\tconst next = new Set(visited);\n\t\t\t\tnext.add(entry.id);\n\t\t\t\treturn {\n\t\t\t\t\tid: entry.id,\n\t\t\t\t\tlabel: entry.label,\n\t\t\t\t\ttype: entry.type,\n\t\t\t\t\tmeta: entry.meta,\n\t\t\t\t\torder: entry.order,\n\t\t\t\t\tchildren: this._buildTreeIndexed(\n\t\t\t\t\t\tentry.id,\n\t\t\t\t\t\tmaxDepth,\n\t\t\t\t\t\tcurrentDepth + 1,\n\t\t\t\t\t\tnext,\n\t\t\t\t\t),\n\t\t\t\t};\n\t\t\t});\n\t}\n\n\tprivate _buildTree(\n\t\tentries: TreeEntry[],\n\t\trootId: string | null,\n\t\tmaxDepth: number,\n\t\tcurrentDepth: number,\n\t\tvisited: Set<string>,\n\t): TreeNode[] {\n\t\tif (maxDepth >= 0 && currentDepth >= maxDepth) return [];\n\t\tconst children = entries\n\t\t\t.filter((e) => e.parentId === rootId)\n\t\t\t.sort((a, b) => (a.order ?? 0) - (b.order ?? 0));\n\n\t\treturn children\n\t\t\t.filter((e) => !visited.has(e.id))\n\t\t\t.map((entry) => {\n\t\t\t\tconst next = new Set(visited);\n\t\t\t\tnext.add(entry.id);\n\t\t\t\treturn {\n\t\t\t\t\tid: entry.id,\n\t\t\t\t\tlabel: entry.label,\n\t\t\t\t\ttype: entry.type,\n\t\t\t\t\tmeta: entry.meta,\n\t\t\t\t\torder: entry.order,\n\t\t\t\t\tchildren: this._buildTree(\n\t\t\t\t\t\tentries,\n\t\t\t\t\t\tentry.id,\n\t\t\t\t\t\tmaxDepth,\n\t\t\t\t\t\tcurrentDepth + 1,\n\t\t\t\t\t\tnext,\n\t\t\t\t\t),\n\t\t\t\t};\n\t\t\t});\n\t}\n\n\t/**\n\t * Schema-typed lookup. Returns a `TypedTreeEntry<TMap, N>` when the\n\t * entry's `type` matches `expectedType`, else `null`. Pure projection\n\t * over the existing untyped tree — no schema validation is performed\n\t * here (the entry's data is whatever was last synced; meta correctness\n\t * is the writer's responsibility, optionally enforced via\n\t * `MetaManager.setSchema`).\n\t *\n\t * Rule 4 alignment: when the entry's type doesn't match, returns null\n\t * rather than throwing — callers branch on the result.\n\t */\n\tgetTyped<TMap extends Record<string, unknown>, N extends keyof TMap & string>(\n\t\t_schema: SchemaRegistryLike<TMap>,\n\t\texpectedType: N,\n\t\tdocId: string,\n\t): TypedTreeEntry<TMap, N> | null {\n\t\treturn projectTreeEntry<TMap, N>(this.get(docId), expectedType);\n\t}\n\n\t/** Find a single entry by ID. */\n\tget(docId: string): TreeEntry | null {\n\t\tconst treeMap = this.dm.getTreeMap();\n\t\tif (!treeMap) return null;\n\t\tconst raw = treeMap.get(docId);\n\t\tif (!raw) return null;\n\t\tconst value = toPlain(raw) as Record<string, unknown>;\n\t\tif (typeof value !== \"object\" || value === null) return null;\n\t\treturn {\n\t\t\tid: docId,\n\t\t\tlabel: (value.label as string) || \"Untitled\",\n\t\t\tparentId: (value.parentId as string | null) ?? null,\n\t\t\torder: (value.order as number) ?? 0,\n\t\t\ttype: value.type as string | undefined,\n\t\t\tmeta: value.meta as PageMeta | undefined,\n\t\t\tcreatedAt: value.createdAt as number | undefined,\n\t\t\tupdatedAt: value.updatedAt as number | undefined,\n\t\t};\n\t}\n\n\t/** Search by label (case-insensitive substring match). */\n\tfind(query: string, rootId?: string | null): TreeSearchResult[] {\n\t\tconst entries = this.normalizedEntries();\n\t\tconst lowerQuery = query.toLowerCase();\n\n\t\tconst normalized = normalizeRootId(rootId ?? null, this.dm.rootDocId);\n\t\tconst searchSet = normalized ? this.descendantsOf(normalized) : entries;\n\n\t\tconst matches = searchSet.filter((e) =>\n\t\t\te.label.toLowerCase().includes(lowerQuery),\n\t\t);\n\n\t\tconst byId = new Map(entries.map((e) => [e.id, e]));\n\t\treturn matches.map((entry) => {\n\t\t\tconst path: string[] = [];\n\t\t\tlet current = entry.parentId;\n\t\t\tconst visited = new Set<string>();\n\t\t\twhile (current && !visited.has(current)) {\n\t\t\t\tvisited.add(current);\n\t\t\t\tconst parent = byId.get(current);\n\t\t\t\tif (!parent) break;\n\t\t\t\tpath.unshift(parent.label);\n\t\t\t\tcurrent = parent.parentId;\n\t\t\t}\n\t\t\treturn {\n\t\t\t\tid: entry.id,\n\t\t\t\tlabel: entry.label,\n\t\t\t\ttype: entry.type,\n\t\t\t\tmeta: entry.meta,\n\t\t\t\tpath,\n\t\t\t};\n\t\t});\n\t}\n\n\t// ── Writing ──────────────────────────────────────────────────────────────\n\n\t/** Create a new document in the tree. Returns the new entry. */\n\tcreate(opts: {\n\t\tparentId?: string | null;\n\t\tlabel: string;\n\t\ttype?: string;\n\t\tmeta?: Partial<PageMeta>;\n\t}): TreeEntry {\n\t\tconst treeMap = this.dm.getTreeMap();\n\t\tconst rootDoc = this.dm.rootDocument;\n\t\tif (!treeMap || !rootDoc) {\n\t\t\tthrow new Error(\"Not connected\");\n\t\t}\n\n\t\tconst id = crypto.randomUUID();\n\t\tconst normalizedParent = normalizeRootId(\n\t\t\topts.parentId ?? null,\n\t\t\tthis.dm.rootDocId,\n\t\t);\n\t\tconst now = Date.now();\n\n\t\trootDoc.transact(() => {\n\t\t\ttreeMap.set(\n\t\t\t\tid,\n\t\t\t\tmakeEntryMap({\n\t\t\t\t\tlabel: opts.label,\n\t\t\t\t\tparentId: normalizedParent,\n\t\t\t\t\torder: now,\n\t\t\t\t\ttype: opts.type,\n\t\t\t\t\tmeta: opts.meta as PageMeta,\n\t\t\t\t\tcreatedAt: now,\n\t\t\t\t\tupdatedAt: now,\n\t\t\t\t}),\n\t\t\t);\n\t\t});\n\n\t\treturn {\n\t\t\tid,\n\t\t\tlabel: opts.label,\n\t\t\tparentId: normalizedParent,\n\t\t\torder: now,\n\t\t\ttype: opts.type,\n\t\t\tmeta: opts.meta as PageMeta | undefined,\n\t\t\tcreatedAt: now,\n\t\t\tupdatedAt: now,\n\t\t};\n\t}\n\n\t/**\n\t * Create a document and auto-apply renderer defaults from the page type's\n\t * `defaultMetaFields` (toggle fields with `default` values).\n\t */\n\tcreateWithTypeDefaults(opts: {\n\t\tparentId?: string | null;\n\t\tlabel: string;\n\t\ttype: string;\n\t\textraMeta?: Partial<PageMeta>;\n\t}): TreeEntry {\n\t\tconst typeInfo = resolvePageType(opts.type);\n\t\tconst autoMeta: Record<string, unknown> = {};\n\t\tif (typeInfo?.defaultMetaFields) {\n\t\t\tfor (const field of typeInfo.defaultMetaFields) {\n\t\t\t\tif (\n\t\t\t\t\tfield.type === \"toggle\" &&\n\t\t\t\t\tfield.key &&\n\t\t\t\t\tfield.default !== undefined\n\t\t\t\t) {\n\t\t\t\t\tautoMeta[field.key] = field.default;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tconst mergedMeta =\n\t\t\tObject.keys(autoMeta).length > 0 || opts.extraMeta\n\t\t\t\t? { ...autoMeta, ...(opts.extraMeta ?? {}) }\n\t\t\t\t: undefined;\n\t\treturn this.create({\n\t\t\tparentId: opts.parentId,\n\t\t\tlabel: opts.label,\n\t\t\ttype: opts.type,\n\t\t\tmeta: mergedMeta,\n\t\t});\n\t}\n\n\t/** Rename a document. */\n\trename(docId: string, label: string): void {\n\t\tconst treeMap = this.dm.getTreeMap();\n\t\tconst rootDoc = this.dm.rootDocument;\n\t\tif (!treeMap || !rootDoc) throw new Error(\"Not connected\");\n\n\t\tconst raw = treeMap.get(docId);\n\t\tif (!raw) throw new Error(`Document ${docId} not found`);\n\n\t\trootDoc.transact(() => {\n\t\t\tpatchEntry(treeMap, docId, { label, updatedAt: Date.now() });\n\t\t});\n\t}\n\n\t/** Move a document to a new parent. */\n\tmove(docId: string, newParentId?: string | null, order?: number): void {\n\t\tconst treeMap = this.dm.getTreeMap();\n\t\tconst rootDoc = this.dm.rootDocument;\n\t\tif (!treeMap || !rootDoc) throw new Error(\"Not connected\");\n\n\t\tconst raw = treeMap.get(docId);\n\t\tif (!raw) throw new Error(`Document ${docId} not found`);\n\n\t\trootDoc.transact(() => {\n\t\t\tpatchEntry(treeMap, docId, {\n\t\t\t\tparentId: normalizeRootId(newParentId ?? null, this.dm.rootDocId),\n\t\t\t\torder: order ?? Date.now(),\n\t\t\t\tupdatedAt: Date.now(),\n\t\t\t});\n\t\t});\n\t}\n\n\t/**\n\t * Heal converged move-cycles in the stored tree itself.\n\t *\n\t * The read paths already present a cycle-free, fully-reachable tree\n\t * without writing (see {@link cycleBreakIds}); this *persists* that repair\n\t * into the CRDT so the stored structure is acyclic too — useful as a\n\t * one-shot on load, or behind a \"repair tree\" action. Deterministic and\n\t * convergent: every replica computes the identical break set, so even\n\t * concurrent calls from multiple peers write the same `parentId: null` and\n\t * converge. Returns the number of nodes reparented to root (0 when already\n\t * acyclic — the common case, where no transaction is opened). Optional —\n\t * the always-on read guard already makes the corruption invisible.\n\t */\n\trepairTree(): number {\n\t\tconst treeMap = this.dm.getTreeMap();\n\t\tconst rootDoc = this.dm.rootDocument;\n\t\tif (!treeMap || !rootDoc) throw new Error(\"Not connected\");\n\t\tconst root = this.dm.rootDocId;\n\t\tconst parentById = new Map<string, string | null>();\n\t\ttreeMap.forEach((raw: unknown, id: string) => {\n\t\t\tconst value = toPlain(raw) as Record<string, unknown>;\n\t\t\tif (typeof value !== \"object\" || value === null) return;\n\t\t\tparentById.set(\n\t\t\t\tid,\n\t\t\t\tnormalizeRootId((value.parentId as string | null) ?? null, root),\n\t\t\t);\n\t\t});\n\t\tconst breaks = cycleBreakIds(\n\t\t\tparentById.keys(),\n\t\t\t(id) => parentById.get(id) ?? null,\n\t\t);\n\t\tif (!breaks.size) return 0;\n\t\trootDoc.transact(() => {\n\t\t\tfor (const id of breaks) {\n\t\t\t\tif (treeMap.get(id)) {\n\t\t\t\t\tpatchEntry(treeMap, id, {\n\t\t\t\t\t\tparentId: null,\n\t\t\t\t\t\tupdatedAt: Date.now(),\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t\treturn breaks.size;\n\t}\n\n\t/** Change the page type of a document. */\n\tchangeType(docId: string, type: string): void {\n\t\tconst treeMap = this.dm.getTreeMap();\n\t\tconst rootDoc = this.dm.rootDocument;\n\t\tif (!treeMap || !rootDoc) throw new Error(\"Not connected\");\n\n\t\tconst raw = treeMap.get(docId);\n\t\tif (!raw) throw new Error(`Document ${docId} not found`);\n\n\t\trootDoc.transact(() => {\n\t\t\tpatchEntry(treeMap, docId, { type, updatedAt: Date.now() });\n\t\t});\n\t}\n\n\t/**\n\t * Soft-delete a document and descendants (move to trash).\n\t * @returns count of deleted documents\n\t */\n\tdelete(docId: string): number {\n\t\tconst treeMap = this.dm.getTreeMap();\n\t\tconst trashMap = this.dm.getTrashMap();\n\t\tconst rootDoc = this.dm.rootDocument;\n\t\tif (!treeMap || !trashMap || !rootDoc) {\n\t\t\tthrow new Error(\"Not connected\");\n\t\t}\n\n\t\tconst now = Date.now();\n\t\tlet deletedCount = 0;\n\t\t// Compute the descendant set and trash it inside ONE synchronous\n\t\t// Yjs transaction. transact() callbacks are atomic — no local or\n\t\t// remote update interleaves — so a child concurrently added under\n\t\t// this subtree cannot be stranded with a trashed parent the way a\n\t\t// read-then-separate-write delete allowed.\n\t\trootDoc.transact(() => {\n\t\t\tconst entries = this.readEntries();\n\t\t\tconst toDelete = [docId, ...this._descendantIds(entries, docId)];\n\t\t\tdeletedCount = toDelete.length;\n\t\t\tfor (const nid of toDelete) {\n\t\t\t\tconst raw = treeMap.get(nid);\n\t\t\t\tif (!raw) continue;\n\t\t\t\tconst entry = toPlain(raw) as Record<string, unknown>;\n\t\t\t\ttrashMap.set(nid, {\n\t\t\t\t\tlabel: entry.label || \"Untitled\",\n\t\t\t\t\tparentId: entry.parentId ?? null,\n\t\t\t\t\torder: entry.order ?? 0,\n\t\t\t\t\ttype: entry.type,\n\t\t\t\t\tmeta: entry.meta,\n\t\t\t\t\tdeletedAt: now,\n\t\t\t\t});\n\t\t\t\ttreeMap.delete(nid);\n\t\t\t}\n\t\t});\n\n\t\treturn deletedCount;\n\t}\n\n\t/** Duplicate a document (shallow clone). Returns the new entry. */\n\tduplicate(docId: string): TreeEntry {\n\t\tconst treeMap = this.dm.getTreeMap();\n\t\tif (!treeMap) throw new Error(\"Not connected\");\n\n\t\tconst raw = treeMap.get(docId);\n\t\tif (!raw) throw new Error(`Document ${docId} not found`);\n\n\t\tconst entry = toPlain(raw) as Record<string, unknown>;\n\t\tconst newId = crypto.randomUUID();\n\t\tconst now = Date.now();\n\t\tconst newLabel = ((entry.label as string) || \"Untitled\") + \" (copy)\";\n\t\ttreeMap.set(\n\t\t\tnewId,\n\t\t\tmakeEntryMap({\n\t\t\t\t...entry,\n\t\t\t\tlabel: newLabel,\n\t\t\t\torder: now,\n\t\t\t\tcreatedAt: now,\n\t\t\t\tupdatedAt: now,\n\t\t\t}),\n\t\t);\n\n\t\treturn {\n\t\t\tid: newId,\n\t\t\tlabel: newLabel,\n\t\t\tparentId: (entry.parentId as string | null) ?? null,\n\t\t\torder: now,\n\t\t\ttype: entry.type as string | undefined,\n\t\t\tmeta: entry.meta as PageMeta | undefined,\n\t\t\tcreatedAt: now,\n\t\t\tupdatedAt: now,\n\t\t};\n\t}\n\n\t/** Restore a document from trash back into the tree. */\n\trestore(docId: string): void {\n\t\tconst treeMap = this.dm.getTreeMap();\n\t\tconst trashMap = this.dm.getTrashMap();\n\t\tconst rootDoc = this.dm.rootDocument;\n\t\tif (!treeMap || !trashMap || !rootDoc) {\n\t\t\tthrow new Error(\"Not connected\");\n\t\t}\n\n\t\tif (!trashMap.get(docId)) {\n\t\t\tthrow new Error(`Document ${docId} not found in trash`);\n\t\t}\n\n\t\tconst now = Date.now();\n\t\t// Restore docId AND its whole trashed subtree. delete() trashes\n\t\t// the subtree as independent entries; restoring only the named id\n\t\t// stranded every descendant in trash forever (audit RISK 4). The\n\t\t// trash snapshot + descendant walk happen INSIDE the transaction,\n\t\t// the same atomicity discipline delete() uses.\n\t\trootDoc.transact(() => {\n\t\t\tconst trashed = new Map<string, Record<string, unknown>>();\n\t\t\ttrashMap.forEach((raw: unknown, id: string) => {\n\t\t\t\tconst v = toPlain(raw) as Record<string, unknown>;\n\t\t\t\tif (typeof v === \"object\" && v !== null) trashed.set(id, v);\n\t\t\t});\n\n\t\t\tconst toRestore: string[] = [];\n\t\t\tconst visited = new Set<string>();\n\t\t\tconst collect = (id: string) => {\n\t\t\t\tif (visited.has(id)) return;\n\t\t\t\tvisited.add(id);\n\t\t\t\tif (!trashed.has(id)) return;\n\t\t\t\ttoRestore.push(id);\n\t\t\t\tfor (const [cid, v] of trashed) {\n\t\t\t\t\tif ((v.parentId ?? null) === id) collect(cid);\n\t\t\t\t}\n\t\t\t};\n\t\t\tcollect(docId);\n\n\t\t\tfor (const id of toRestore) {\n\t\t\t\tconst entry = trashed.get(id) as Record<string, unknown>;\n\t\t\t\ttreeMap.set(\n\t\t\t\t\tid,\n\t\t\t\t\tmakeEntryMap({\n\t\t\t\t\t\tlabel: entry.label || \"Untitled\",\n\t\t\t\t\t\tparentId: entry.parentId ?? null,\n\t\t\t\t\t\torder: entry.order ?? now,\n\t\t\t\t\t\ttype: entry.type,\n\t\t\t\t\t\tmeta: entry.meta,\n\t\t\t\t\t\tcreatedAt: entry.createdAt ?? now,\n\t\t\t\t\t\tupdatedAt: now,\n\t\t\t\t\t}),\n\t\t\t\t);\n\t\t\t\ttrashMap.delete(id);\n\t\t\t}\n\t\t});\n\t}\n\n\t/** List trashed documents. */\n\tlistTrash(): TreeEntry[] {\n\t\tconst trashMap = this.dm.getTrashMap();\n\t\tif (!trashMap) return [];\n\n\t\tconst entries: TreeEntry[] = [];\n\t\ttrashMap.forEach((raw: unknown, id: string) => {\n\t\t\tconst value = toPlain(raw) as Record<string, unknown>;\n\t\t\tif (typeof value !== \"object\" || value === null) return;\n\t\t\tentries.push({\n\t\t\t\tid,\n\t\t\t\tlabel: (value.label as string) || \"Untitled\",\n\t\t\t\tparentId: (value.parentId as string | null) ?? null,\n\t\t\t\torder: (value.order as number) ?? 0,\n\t\t\t\ttype: value.type as string | undefined,\n\t\t\t\tmeta: value.meta as PageMeta | undefined,\n\t\t\t});\n\t\t});\n\t\treturn entries;\n\t}\n\n\t/** Get enabled plugin names from space-plugins map. */\n\tgetEnabledPlugins(): string[] {\n\t\tconst pluginsMap = this.dm.getPluginsMap();\n\t\tif (!pluginsMap) return [];\n\n\t\tconst plugins: string[] = [];\n\t\tpluginsMap.forEach((raw: unknown, key: string) => {\n\t\t\tconst value = toPlain(raw) as Record<string, unknown>;\n\t\t\tif (value && value.enabled) {\n\t\t\t\tplugins.push(key);\n\t\t\t}\n\t\t});\n\t\treturn plugins;\n\t}\n\n\t// ── Internal helpers ──────────────────────────────────────────────────────\n\n\tprivate _descendantIds(entries: TreeEntry[], parentId: string): string[] {\n\t\tconst result: string[] = [];\n\t\tconst visited = new Set<string>();\n\t\tconst collect = (pid: string) => {\n\t\t\tif (visited.has(pid)) return;\n\t\t\tvisited.add(pid);\n\t\t\tfor (const child of entries.filter((e) => e.parentId === pid)) {\n\t\t\t\tresult.push(child.id);\n\t\t\t\tcollect(child.id);\n\t\t\t}\n\t\t};\n\t\tcollect(parentId);\n\t\treturn result;\n\t}\n}\n","/**\n * CoverReconcile — keep a document's cover-image metadata in sync with the\n * image/video file blocks that actually live in its content.\n *\n * The cover (`meta.coverUploadId` / `coverDocId` / `coverMimeType` on the\n * doc's own tree entry) is *persisted* metadata, not derived live — the\n * kanban/gallery/table views read it without loading each card's content.\n * Historically the only thing that reconciled it was cou-sh's TipTap editor\n * (`reconcileCover` in DocRenderer.vue), so any write that did NOT go through\n * that editor — MCP `write_document`, `@abraca/convert`, the CLI, another SDK\n * — could leave an orphaned cover pointing at an image the body no longer\n * contains. This is the shared, write-path-level reconciliation so every\n * content write through the SDK keeps the cover honest.\n *\n * Semantics mirror cou-sh's editor reconciler exactly:\n * - cover set + still references a present image/video → leave it (a\n * user-chosen cover is preserved as long as its image is in the doc);\n * - cover set + its image is gone, others remain → swap to the first;\n * - cover set + no image/video remains → clear the three cover keys;\n * - no cover + at least one image/video → adopt the first as the cover.\n */\nimport * as Y from \"yjs\";\nimport { toPlain, patchEntry } from \"./DocUtils.ts\";\n\nexport interface MediaFileBlock {\n\tuploadId: string;\n\tdocId: string;\n\tmimeType: string;\n}\n\nconst EXT_MIME: Record<string, string> = {\n\tpng: \"image/png\",\n\tjpg: \"image/jpeg\",\n\tjpeg: \"image/jpeg\",\n\tgif: \"image/gif\",\n\twebp: \"image/webp\",\n\tavif: \"image/avif\",\n\tsvg: \"image/svg+xml\",\n\tbmp: \"image/bmp\",\n\theic: \"image/heic\",\n\theif: \"image/heif\",\n\tmp4: \"video/mp4\",\n\twebm: \"video/webm\",\n\tmov: \"video/quicktime\",\n\tm4v: \"video/x-m4v\",\n\togv: \"video/ogg\",\n\tmkv: \"video/x-matroska\",\n};\n\nfunction attr(node: Y.XmlElement, name: string): string | undefined {\n\tconst v = node.getAttribute(name);\n\treturn typeof v === \"string\" && v ? v : undefined;\n}\n\n/**\n * Resolve a file node's mime type. A `fileBlock` may carry the mime under\n * `mimeType` (cou-sh's TipTap/y-prosemirror node attr) or `mime` (the\n * `@abraca/convert` markdown path), and may carry neither — in which case we\n * infer it from the filename/src extension (the convert sidecar `src` is\n * `.abracadabra/files/<id>-<filename>`). Returns \"\" when it can't be\n * classified as image/video.\n */\nfunction resolveMime(node: Y.XmlElement): string {\n\tconst explicit = attr(node, \"mimeType\") ?? attr(node, \"mime\");\n\tif (explicit) return explicit;\n\tconst name = attr(node, \"filename\") ?? attr(node, \"src\") ?? \"\";\n\tconst ext = name.split(\".\").pop()?.toLowerCase() ?? \"\";\n\treturn EXT_MIME[ext] ?? \"\";\n}\n\n/**\n * Recursively collect image/video `fileBlock` nodes from a Y.XmlFragment (or\n * element subtree), in document order. Mirrors the TipTap\n * `doc.descendants()` walk used by cou-sh — fileBlocks may be nested inside\n * other block nodes, so this recurses rather than scanning only top level.\n */\nexport function collectMediaFileBlocks(\n\troot: Y.XmlFragment | Y.XmlElement,\n): MediaFileBlock[] {\n\tconst out: MediaFileBlock[] = [];\n\tconst visit = (node: Y.AbstractType<unknown>): void => {\n\t\tif (node instanceof Y.XmlElement && node.nodeName === \"fileBlock\") {\n\t\t\tconst uploadId = attr(node, \"uploadId\") ?? attr(node, \"upload-id\");\n\t\t\tif (uploadId) {\n\t\t\t\tconst mimeType = resolveMime(node);\n\t\t\t\tif (\n\t\t\t\t\tmimeType.startsWith(\"image/\") ||\n\t\t\t\t\tmimeType.startsWith(\"video/\")\n\t\t\t\t) {\n\t\t\t\t\tout.push({\n\t\t\t\t\t\tuploadId,\n\t\t\t\t\t\tdocId: attr(node, \"docId\") ?? \"\",\n\t\t\t\t\t\tmimeType,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif (node instanceof Y.XmlElement || node instanceof Y.XmlFragment) {\n\t\t\tfor (let i = 0; i < node.length; i++) {\n\t\t\t\tvisit(node.get(i) as Y.AbstractType<unknown>);\n\t\t\t}\n\t\t}\n\t};\n\tvisit(root as unknown as Y.AbstractType<unknown>);\n\treturn out;\n}\n\n/**\n * Reconcile the cover metadata of `docId`'s tree entry against the media file\n * blocks currently present in `fragment`. No-op when the entry is missing or\n * the cover is already valid, so it is safe (and cheap) to call after every\n * content write. The `treeMap` is the root doc-tree Y.Map; the cover lives on\n * the doc's OWN self-entry (`treeMap.get(docId).meta`).\n */\nexport function reconcileDocCover(\n\ttreeMap: Y.Map<unknown>,\n\tdocId: string,\n\tfragment: Y.XmlFragment | Y.XmlElement,\n): void {\n\tconst raw = treeMap.get(docId);\n\tif (!raw) return;\n\n\tconst entry = toPlain(raw) as Record<string, unknown>;\n\tconst meta = ((entry.meta as Record<string, unknown>) ?? {}) as Record<\n\t\tstring,\n\t\tunknown\n\t>;\n\tconst currentCoverId = meta.coverUploadId as string | undefined;\n\n\tconst media = collectMediaFileBlocks(fragment);\n\n\t// Cover already references a present image/video → nothing to do.\n\tif (currentCoverId && media.some((b) => b.uploadId === currentCoverId)) {\n\t\treturn;\n\t}\n\n\tif (media.length > 0) {\n\t\t// Adopt (no cover) or swap (stale cover) to the first media block.\n\t\tconst best = media[0]!;\n\t\tif (\n\t\t\tcurrentCoverId === best.uploadId &&\n\t\t\tmeta.coverDocId === (best.docId || docId) &&\n\t\t\tmeta.coverMimeType === best.mimeType\n\t\t) {\n\t\t\treturn;\n\t\t}\n\t\tpatchEntry(treeMap, docId, {\n\t\t\tmeta: {\n\t\t\t\t...meta,\n\t\t\t\tcoverUploadId: best.uploadId,\n\t\t\t\tcoverDocId: best.docId || docId,\n\t\t\t\tcoverMimeType: best.mimeType,\n\t\t\t},\n\t\t\tupdatedAt: Date.now(),\n\t\t});\n\t\treturn;\n\t}\n\n\t// No media remains. Clear the cover keys only if one was set.\n\tif (!currentCoverId && !meta.coverDocId && !meta.coverMimeType) return;\n\tconst {\n\t\tcoverUploadId: _cu,\n\t\tcoverDocId: _cd,\n\t\tcoverMimeType: _cm,\n\t\t...rest\n\t} = meta;\n\tpatchEntry(treeMap, docId, { meta: rest, updatedAt: Date.now() });\n}\n","/**\n * Document content converters — markdown ↔ Y.js.\n *\n * Canonical implementations for converting between Markdown text and TipTap-\n * compatible Y.XmlFragment structures. Previously lived in\n * `mcp/converters/` — now the authoritative home is the provider package so\n * any consumer of `@abraca/dabra` can use them without pulling in MCP deps.\n */\nimport * as Y from \"yjs\";\nimport type { PageMeta } from \"./DocTypes.ts\";\n\n// ══════════════════════════════════════════════════════════════════════════════\n// Y.XmlFragment → Markdown (yjsToMarkdown)\n// ══════════════════════════════════════════════════════════════════════════════\n\n// ── Inline text serialization ────────────────────────────────────────────────\n\nfunction deltaToMarkdown(\n\tdelta: { insert: string; attributes?: Record<string, any> }[],\n): string {\n\treturn delta\n\t\t.map((op) => {\n\t\t\tlet text = op.insert as string;\n\t\t\tif (!op.attributes) return text;\n\n\t\t\tconst a = op.attributes;\n\n\t\t\tif (a.code) text = `\\`${text}\\``;\n\t\t\tif (a.bold) text = `**${text}**`;\n\t\t\tif (a.italic) text = `*${text}*`;\n\t\t\tif (a.strike) text = `~~${text}~~`;\n\t\t\tif (a.link?.href) text = `[${text}](${a.link.href})`;\n\t\t\tif (a.badge) text = `:badge[${a.badge.label || text}]`;\n\t\t\tif (a.kbd) text = `:kbd{value=\"${a.kbd.value || text}\"}`;\n\t\t\tif (a.proseIcon) text = `:icon{name=\"${a.proseIcon.name}\"}`;\n\n\t\t\treturn text;\n\t\t})\n\t\t.join(\"\");\n}\n\nfunction xmlTextToMarkdown(xmlText: Y.XmlText): string {\n\tconst delta = xmlText.toDelta();\n\treturn deltaToMarkdown(delta);\n}\n\nfunction elementTextContent(el: Y.XmlElement | Y.XmlFragment): string {\n\tconst parts: string[] = [];\n\tfor (const child of el.toArray()) {\n\t\tif (child instanceof Y.XmlText) {\n\t\t\tparts.push(xmlTextToMarkdown(child));\n\t\t} else if (child instanceof Y.XmlElement) {\n\t\t\tif (child.nodeName === \"docLink\") {\n\t\t\t\tconst docId = child.getAttribute(\"docId\");\n\t\t\t\tif (docId) parts.push(`[[${docId}]]`);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tparts.push(elementTextContent(child));\n\t\t}\n\t}\n\treturn parts.join(\"\");\n}\n\n// ── Block serialization ──────────────────────────────────────────────────────\n\nfunction serializeElement(el: Y.XmlElement, indent = \"\"): string {\n\tconst name = el.nodeName;\n\n\tswitch (name) {\n\t\tcase \"documentHeader\":\n\t\tcase \"documentMeta\":\n\t\t\treturn \"\";\n\n\t\tcase \"heading\": {\n\t\t\tconst level = Number(el.getAttribute(\"level\")) || 1;\n\t\t\tconst prefix = \"#\".repeat(level);\n\t\t\treturn `${prefix} ${elementTextContent(el)}`;\n\t\t}\n\n\t\tcase \"paragraph\":\n\t\t\treturn elementTextContent(el);\n\n\t\tcase \"bulletList\":\n\t\t\treturn serializeList(el, \"bullet\", indent);\n\n\t\tcase \"orderedList\":\n\t\t\treturn serializeList(el, \"ordered\", indent);\n\n\t\tcase \"taskList\":\n\t\t\treturn serializeTaskList(el, indent);\n\n\t\tcase \"codeBlock\": {\n\t\t\tconst lang = el.getAttribute(\"language\") || \"\";\n\t\t\tconst code = elementTextContent(el);\n\t\t\treturn `\\`\\`\\`${lang}\\n${code}\\n\\`\\`\\``;\n\t\t}\n\n\t\tcase \"blockquote\": {\n\t\t\tconst lines: string[] = [];\n\t\t\tfor (let i = 0; i < el.length; i++) {\n\t\t\t\tconst child = el.get(i);\n\t\t\t\tif (child instanceof Y.XmlElement) {\n\t\t\t\t\tlines.push(serializeElement(child, indent));\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn lines.map((l) => `> ${l}`).join(\"\\n\");\n\t\t}\n\n\t\tcase \"horizontalRule\":\n\t\t\treturn \"---\";\n\n\t\tcase \"table\":\n\t\t\treturn serializeTable(el);\n\n\t\tcase \"docEmbed\": {\n\t\t\tconst docId = el.getAttribute(\"docId\");\n\t\t\tif (!docId) return \"\";\n\t\t\tconst seamlessAttr = el.getAttribute(\"seamless\");\n\t\t\tconst seamless =\n\t\t\t\t(seamlessAttr as unknown) === true || seamlessAttr === \"true\";\n\t\t\treturn seamless ? `![[${docId}]]{seamless}` : `![[${docId}]]`;\n\t\t}\n\n\t\tcase \"svgEmbed\": {\n\t\t\tconst svg = el.getAttribute(\"svg\") || \"\";\n\t\t\tconst svgTitle = el.getAttribute(\"title\") || \"\";\n\t\t\tif (!svg) return \"\";\n\t\t\treturn `\\`\\`\\`svg${svgTitle ? ` ${svgTitle}` : \"\"}\\n${svg}\\n\\`\\`\\``;\n\t\t}\n\n\t\tcase \"image\": {\n\t\t\tconst src = el.getAttribute(\"src\") || \"\";\n\t\t\tconst alt = el.getAttribute(\"alt\") || \"\";\n\t\t\tconst w = el.getAttribute(\"width\");\n\t\t\tconst h = el.getAttribute(\"height\");\n\t\t\tlet attrs = \"\";\n\t\t\tif (w || h) {\n\t\t\t\tconst imgParts: string[] = [];\n\t\t\t\tif (w) imgParts.push(`width=\"${w}\"`);\n\t\t\t\tif (h) imgParts.push(`height=\"${h}\"`);\n\t\t\t\tattrs = `{${imgParts.join(\" \")}}`;\n\t\t\t}\n\t\t\treturn `${attrs}`;\n\t\t}\n\n\t\tcase \"callout\": {\n\t\t\tconst type = el.getAttribute(\"type\") || \"note\";\n\t\t\tconst inner = serializeChildren(el, indent);\n\t\t\treturn `::${type}\\n${inner}\\n::`;\n\t\t}\n\n\t\tcase \"collapsible\": {\n\t\t\tconst label = el.getAttribute(\"label\") || \"Details\";\n\t\t\tconst open = el.getAttribute(\"open\");\n\t\t\tconst props: string[] = [`label=\"${label}\"`];\n\t\t\tif ((open as unknown) === true || open === \"true\") props.push('open=\"true\"');\n\t\t\tconst inner = serializeChildren(el, indent);\n\t\t\treturn `::collapsible{${props.join(\" \")}}\\n${inner}\\n::`;\n\t\t}\n\n\t\tcase \"steps\": {\n\t\t\tconst inner = serializeChildren(el, indent);\n\t\t\treturn `::steps\\n${inner}\\n::`;\n\t\t}\n\n\t\tcase \"card\": {\n\t\t\tconst title = el.getAttribute(\"title\") || \"\";\n\t\t\tconst icon = el.getAttribute(\"icon\") || \"\";\n\t\t\tconst to = el.getAttribute(\"to\") || \"\";\n\t\t\tconst props: string[] = [];\n\t\t\tif (title) props.push(`title=\"${title}\"`);\n\t\t\tif (icon) props.push(`icon=\"${icon}\"`);\n\t\t\tif (to) props.push(`to=\"${to}\"`);\n\t\t\tconst inner = serializeChildren(el, indent);\n\t\t\treturn `::card{${props.join(\" \")}}\\n${inner}\\n::`;\n\t\t}\n\n\t\tcase \"cardGroup\": {\n\t\t\tconst inner = serializeChildren(el, indent);\n\t\t\treturn `::card-group\\n${inner}\\n::`;\n\t\t}\n\n\t\tcase \"codeCollapse\": {\n\t\t\tconst inner = serializeChildren(el, indent);\n\t\t\treturn `::code-collapse\\n${inner}\\n::`;\n\t\t}\n\n\t\tcase \"codeGroup\": {\n\t\t\tconst inner = serializeChildren(el, indent);\n\t\t\treturn `::code-group\\n${inner}\\n::`;\n\t\t}\n\n\t\tcase \"codePreview\": {\n\t\t\tconst inner = serializeChildren(el, indent);\n\t\t\treturn `::code-preview\\n${inner}\\n::`;\n\t\t}\n\n\t\tcase \"codeTree\": {\n\t\t\tconst files = el.getAttribute(\"files\") || \"[]\";\n\t\t\treturn `::code-tree{files=\"${files}\"}\\n::`;\n\t\t}\n\n\t\tcase \"accordion\":\n\t\t\treturn serializeSlottedComponent(\n\t\t\t\tel,\n\t\t\t\t\"accordion\",\n\t\t\t\t\"accordionItem\",\n\t\t\t\t\"item\",\n\t\t\t);\n\n\t\tcase \"tabs\":\n\t\t\treturn serializeSlottedComponent(el, \"tabs\", \"tabsItem\", \"tab\");\n\n\t\tcase \"field\": {\n\t\t\tconst fieldName = el.getAttribute(\"name\") || \"\";\n\t\t\tconst fieldType = el.getAttribute(\"type\") || \"string\";\n\t\t\tconst required = el.getAttribute(\"required\");\n\t\t\tconst props: string[] = [];\n\t\t\tif (fieldName) props.push(`name=\"${fieldName}\"`);\n\t\t\tprops.push(`type=\"${fieldType}\"`);\n\t\t\tif ((required as unknown) === true || required === \"true\")\n\t\t\t\tprops.push('required=\"true\"');\n\t\t\tconst inner = serializeChildren(el, indent);\n\t\t\treturn `::field{${props.join(\" \")}}\\n${inner}\\n::`;\n\t\t}\n\n\t\tcase \"fieldGroup\": {\n\t\t\tconst inner = serializeChildren(el, indent);\n\t\t\treturn `::field-group\\n${inner}\\n::`;\n\t\t}\n\n\t\tdefault: {\n\t\t\treturn serializeChildren(el, indent);\n\t\t}\n\t}\n}\n\nfunction serializeList(\n\tel: Y.XmlElement,\n\ttype: \"bullet\" | \"ordered\",\n\tindent: string,\n): string {\n\tconst lines: string[] = [];\n\tconst items = el.toArray();\n\tfor (let i = 0; i < items.length; i++) {\n\t\tconst item = items[i];\n\t\tif (\n\t\t\titem instanceof Y.XmlElement &&\n\t\t\titem.nodeName === \"listItem\"\n\t\t) {\n\t\t\tconst prefix = type === \"bullet\" ? \"- \" : `${i + 1}. `;\n\t\t\tconst content = elementTextContent(item);\n\t\t\tlines.push(`${indent}${prefix}${content}`);\n\t\t}\n\t}\n\treturn lines.join(\"\\n\");\n}\n\nfunction serializeTaskList(el: Y.XmlElement, indent: string): string {\n\tconst lines: string[] = [];\n\tfor (const item of el.toArray()) {\n\t\tif (\n\t\t\titem instanceof Y.XmlElement &&\n\t\t\titem.nodeName === \"taskItem\"\n\t\t) {\n\t\t\tconst checked = item.getAttribute(\"checked\");\n\t\t\tconst marker =\n\t\t\t\t(checked as unknown) === true || checked === \"true\" ? \"[x]\" : \"[ ]\";\n\t\t\tconst content = elementTextContent(item);\n\t\t\tlines.push(`${indent}- ${marker} ${content}`);\n\t\t}\n\t}\n\treturn lines.join(\"\\n\");\n}\n\nfunction serializeTable(el: Y.XmlElement): string {\n\tconst rows: string[][] = [];\n\n\tfor (const row of el.toArray()) {\n\t\tif (\n\t\t\t!(row instanceof Y.XmlElement) ||\n\t\t\trow.nodeName !== \"tableRow\"\n\t\t)\n\t\t\tcontinue;\n\n\t\tconst cells: string[] = [];\n\t\tfor (const cell of row.toArray()) {\n\t\t\tif (cell instanceof Y.XmlElement) {\n\t\t\t\tcells.push(elementTextContent(cell));\n\t\t\t}\n\t\t}\n\t\trows.push(cells);\n\t}\n\n\tif (!rows.length) return \"\";\n\n\tconst headerRow = rows[0]!;\n\tconst lines = [`| ${headerRow.join(\" | \")} |`];\n\n\t// Separator\n\tlines.push(`| ${headerRow.map(() => \"---\").join(\" | \")} |`);\n\n\t// Data rows\n\tfor (let i = 1; i < rows.length; i++) {\n\t\tlines.push(`| ${rows[i]!.join(\" | \")} |`);\n\t}\n\n\treturn lines.join(\"\\n\");\n}\n\nfunction serializeSlottedComponent(\n\tel: Y.XmlElement,\n\tcomponentName: string,\n\tchildNodeName: string,\n\tslotName: string,\n): string {\n\tconst parts: string[] = [`::${componentName}`];\n\n\tfor (let i = 0; i < el.length; i++) {\n\t\tconst child = el.get(i);\n\t\tif (\n\t\t\t!(child instanceof Y.XmlElement) ||\n\t\t\tchild.nodeName !== childNodeName\n\t\t)\n\t\t\tcontinue;\n\n\t\tconst label = child.getAttribute(\"label\") || `Item ${i + 1}`;\n\t\tconst icon = child.getAttribute(\"icon\") || \"\";\n\t\tconst props: string[] = [`label=\"${label}\"`];\n\t\tif (icon) props.push(`icon=\"${icon}\"`);\n\t\tparts.push(`#${slotName}{${props.join(\" \")}}`);\n\n\t\tconst inner = serializeChildren(child, \"\");\n\t\tif (inner) parts.push(inner);\n\t}\n\n\tparts.push(\"::\");\n\treturn parts.join(\"\\n\");\n}\n\nfunction serializeChildren(\n\tel: Y.XmlElement | Y.XmlFragment,\n\tindent: string,\n): string {\n\tconst parts: string[] = [];\n\tfor (const child of el.toArray()) {\n\t\tif (child instanceof Y.XmlElement) {\n\t\t\tconst serialized = serializeElement(child, indent);\n\t\t\tif (serialized) parts.push(serialized);\n\t\t} else if (child instanceof Y.XmlText) {\n\t\t\tconst text = xmlTextToMarkdown(child);\n\t\t\tif (text) parts.push(text);\n\t\t}\n\t}\n\treturn parts.join(\"\\n\\n\");\n}\n\n// ── Public: Y.js → Markdown ─────────────────────────────────────────────────\n\n/**\n * Converts a Y.XmlFragment (TipTap document) to markdown.\n * Extracts the title from the documentHeader element.\n *\n * @returns `{ title, markdown }` where title is the H1/header text\n */\nexport function yjsToMarkdown(\n\tfragment: Y.XmlFragment,\n): { title: string; markdown: string } {\n\tlet title = \"Untitled\";\n\tconst bodyParts: string[] = [];\n\n\t// Iterate via toArray() (O(n)). Indexed fragment.get(i) is an O(i)\n\t// linked-list walk, which made this top-level loop O(n²) on large docs.\n\tfor (const child of fragment.toArray()) {\n\t\tif (!(child instanceof Y.XmlElement)) continue;\n\n\t\tif (child.nodeName === \"documentHeader\") {\n\t\t\ttitle = elementTextContent(child) || \"Untitled\";\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (child.nodeName === \"documentMeta\") {\n\t\t\tcontinue;\n\t\t}\n\n\t\tconst serialized = serializeElement(child);\n\t\tif (serialized !== \"\") {\n\t\t\tbodyParts.push(serialized);\n\t\t}\n\t}\n\n\treturn { title, markdown: bodyParts.join(\"\\n\\n\") };\n}\n\n// ══════════════════════════════════════════════════════════════════════════════\n// Markdown → Y.XmlFragment (populateYDocFromMarkdown)\n// ══════════════════════════════════════════════════════════════════════════════\n\n// ── Filename → readable label ────────────────────────────────────────────────\n\nexport function filenameToLabel(raw: string): string {\n\tconst base = raw.replace(/\\.[^.]+$/, \"\");\n\tconst spaced = base.replace(/([a-z])([A-Z])/g, \"$1 $2\");\n\tconst clean = spaced\n\t\t.replace(/[-_.]+/g, \" \")\n\t\t.replace(/\\s+/g, \" \")\n\t\t.trim();\n\treturn clean.charAt(0).toUpperCase() + clean.slice(1);\n}\n\n// ── YAML frontmatter parser ──────────────────────────────────────────────────\n\nexport interface FrontmatterResult {\n\ttitle?: string;\n\tmeta: Partial<PageMeta>;\n\tbody: string;\n}\n\nfunction parseInlineArray(raw: string): string[] {\n\treturn raw\n\t\t.slice(1, -1)\n\t\t.split(\",\")\n\t\t.map((s) => s.trim())\n\t\t.filter(Boolean);\n}\n\nexport function parseFrontmatter(markdown: string): FrontmatterResult {\n\tconst noResult: FrontmatterResult = { meta: {}, body: markdown };\n\n\tconst match = markdown.match(/^---\\r?\\n([\\s\\S]*?)\\r?\\n---\\r?\\n?/);\n\tif (!match) return noResult;\n\n\tconst yamlBlock = match[1]!;\n\tconst body = markdown.slice(match[0].length);\n\n\tconst raw: Record<string, string | string[]> = {};\n\tconst lines = yamlBlock.split(\"\\n\");\n\tlet i = 0;\n\twhile (i < lines.length) {\n\t\tconst line = lines[i]!;\n\t\tconst blockSeqKey = line.match(/^(\\w[\\w-]*):\\s*$/);\n\t\tif (\n\t\t\tblockSeqKey &&\n\t\t\ti + 1 < lines.length &&\n\t\t\t/^\\s+-\\s/.test(lines[i + 1]!)\n\t\t) {\n\t\t\tconst key = blockSeqKey[1]!;\n\t\t\tconst items: string[] = [];\n\t\t\ti++;\n\t\t\twhile (i < lines.length && /^\\s+-\\s/.test(lines[i]!)) {\n\t\t\t\titems.push(lines[i]!.replace(/^\\s+-\\s/, \"\").trim());\n\t\t\t\ti++;\n\t\t\t}\n\t\t\traw[key] = items;\n\t\t\tcontinue;\n\t\t}\n\t\tconst kvMatch = line.match(/^(\\w[\\w-]*):\\s*(.*)$/);\n\t\tif (kvMatch) {\n\t\t\tconst key = kvMatch[1]!;\n\t\t\tconst val = kvMatch[2]!.trim();\n\t\t\tif (val.startsWith(\"[\") && val.endsWith(\"]\")) {\n\t\t\t\traw[key] = parseInlineArray(val);\n\t\t\t} else {\n\t\t\t\traw[key] = val;\n\t\t\t}\n\t\t}\n\t\ti++;\n\t}\n\n\tconst meta: Partial<PageMeta> = {};\n\n\tconst getStr = (keys: string[]): string | undefined => {\n\t\tfor (const k of keys) {\n\t\t\tconst v = raw[k];\n\t\t\tif (typeof v === \"string\" && v) return v;\n\t\t}\n\t};\n\n\tif (raw[\"tags\"])\n\t\tmeta.tags = Array.isArray(raw[\"tags\"])\n\t\t\t? raw[\"tags\"]\n\t\t\t: [raw[\"tags\"] as string];\n\tconst color = getStr([\"color\"]);\n\tif (color) meta.color = color;\n\tconst icon = getStr([\"icon\"]);\n\tif (icon) meta.icon = icon;\n\tconst status = getStr([\"status\"]);\n\tif (status) meta.status = status;\n\n\tconst priorityRaw = getStr([\"priority\"]);\n\tif (priorityRaw !== undefined) {\n\t\tconst map: Record<string, number> = {\n\t\t\tlow: 1,\n\t\t\tmedium: 2,\n\t\t\thigh: 3,\n\t\t\turgent: 4,\n\t\t};\n\t\tmeta.priority =\n\t\t\tmap[priorityRaw.toLowerCase()] ?? (Number(priorityRaw) || 0);\n\t}\n\n\tconst checkedRaw = raw[\"checked\"] ?? raw[\"done\"];\n\tif (checkedRaw !== undefined)\n\t\tmeta.checked = checkedRaw === \"true\" || (checkedRaw as unknown) === true;\n\n\tconst dateStart = getStr([\"date\", \"created\"]);\n\tif (dateStart) meta.dateStart = dateStart;\n\tconst dateEnd = getStr([\"due\"]);\n\tif (dateEnd) meta.dateEnd = dateEnd;\n\n\tconst subtitle = getStr([\"description\", \"subtitle\"]);\n\tif (subtitle) meta.subtitle = subtitle;\n\tconst url = getStr([\"url\"]);\n\tif (url) meta.url = url;\n\tconst email = getStr([\"email\"]);\n\tif (email) meta.email = email;\n\tconst phone = getStr([\"phone\"]);\n\tif (phone) meta.phone = phone;\n\n\tconst ratingRaw = getStr([\"rating\"]);\n\tif (ratingRaw !== undefined) {\n\t\tconst n = Number(ratingRaw);\n\t\tif (!Number.isNaN(n)) meta.rating = Math.min(5, Math.max(0, n));\n\t}\n\n\t// Datetime fields\n\tconst datetimeStart = getStr([\"datetimeStart\"]);\n\tif (datetimeStart) meta.datetimeStart = datetimeStart;\n\tconst datetimeEnd = getStr([\"datetimeEnd\"]);\n\tif (datetimeEnd) meta.datetimeEnd = datetimeEnd;\n\tconst allDayRaw = raw[\"allDay\"];\n\tif (allDayRaw !== undefined)\n\t\tmeta.allDay = allDayRaw === \"true\" || (allDayRaw as unknown) === true;\n\n\t// Geo fields\n\tconst geoLatRaw = getStr([\"geoLat\"]);\n\tif (geoLatRaw !== undefined) {\n\t\tconst n = Number(geoLatRaw);\n\t\tif (!Number.isNaN(n)) meta.geoLat = n;\n\t}\n\tconst geoLngRaw = getStr([\"geoLng\"]);\n\tif (geoLngRaw !== undefined) {\n\t\tconst n = Number(geoLngRaw);\n\t\tif (!Number.isNaN(n)) meta.geoLng = n;\n\t}\n\tconst geoType = getStr([\"geoType\"]);\n\tif (\n\t\tgeoType &&\n\t\t(geoType === \"marker\" || geoType === \"line\" || geoType === \"measure\")\n\t) {\n\t\tmeta.geoType = geoType;\n\t}\n\tconst geoDescription = getStr([\"geoDescription\"]);\n\tif (geoDescription) meta.geoDescription = geoDescription;\n\n\t// Numeric fields\n\tconst numberRaw = getStr([\"number\"]);\n\tif (numberRaw !== undefined) {\n\t\tconst n = Number(numberRaw);\n\t\tif (!Number.isNaN(n)) meta.number = n;\n\t}\n\tconst unit = getStr([\"unit\"]);\n\tif (unit) meta.unit = unit;\n\n\t// Note\n\tconst note = getStr([\"note\"]);\n\tif (note) meta.note = note;\n\n\tconst title = typeof raw[\"title\"] === \"string\" ? raw[\"title\"] : undefined;\n\n\treturn { title, meta, body };\n}\n\n// ── Inline token parsing ─────────────────────────────────────────────────────\n\ninterface InlineToken {\n\ttext: string;\n\tattrs?: Record<string, unknown>;\n\t/** If set, emit an inline Y.XmlElement with this nodeName instead of text+marks. */\n\tnode?: string;\n\t/** Attributes for the inline node (when node is set). */\n\tnodeAttrs?: Record<string, string>;\n}\n\nfunction parseMdcProps(\n\tpropsStr: string | undefined,\n): Record<string, string> {\n\tif (!propsStr) return {};\n\tconst result: Record<string, string> = {};\n\tconst re = /(\\w[\\w-]*)=\"([^\"]*)\"/g;\n\tlet m: RegExpExecArray | null;\n\twhile ((m = re.exec(propsStr)) !== null) {\n\t\tresult[m[1]!] = m[2]!;\n\t}\n\treturn result;\n}\n\nfunction parseInline(text: string): InlineToken[] {\n\tconst stripped = text\n\t\t.replace(/\\{lang=\"[^\"]*\"\\}/g, \"\")\n\t\t.replace(\n\t\t\t/:(?!badge|icon|kbd)(\\w[\\w-]*)\\[([^\\]]*)\\](\\{[^}]*\\})?/g,\n\t\t\t\"$2\",\n\t\t)\n\t\t.replace(/:(?!badge|icon|kbd)(\\w[\\w-]*)(\\{[^}]*\\})/g, \"\");\n\n\tconst tokens: InlineToken[] = [];\n\tconst re =\n\t\t/:badge\\[([^\\]]*)\\](\\{[^}]*\\})?|:icon\\{([^}]*)\\}|:kbd\\{([^}]*)\\}|!?\\[\\[([^\\]|]+?)(?:\\|([^\\]]+?))?\\]\\]|~~(.+?)~~|\\*\\*(.+?)\\*\\*|\\*(.+?)\\*|_(.+?)_|`(.+?)`|\\[(.+?)\\]\\((.+?)\\)/g;\n\tlet lastIndex = 0;\n\tlet match: RegExpExecArray | null;\n\n\twhile ((match = re.exec(stripped)) !== null) {\n\t\tif (match.index > lastIndex) {\n\t\t\ttokens.push({ text: stripped.slice(lastIndex, match.index) });\n\t\t}\n\t\tif (match[1] !== undefined) {\n\t\t\tconst badgeProps = parseMdcProps(match[2]);\n\t\t\ttokens.push({\n\t\t\t\ttext: match[1] || \"Badge\",\n\t\t\t\tattrs: {\n\t\t\t\t\tbadge: {\n\t\t\t\t\t\tlabel: match[1] || \"Badge\",\n\t\t\t\t\t\tcolor: badgeProps[\"color\"] || \"neutral\",\n\t\t\t\t\t\tvariant: badgeProps[\"variant\"] || \"subtle\",\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t});\n\t\t} else if (match[3] !== undefined) {\n\t\t\tconst iconProps = parseMdcProps(`{${match[3]}}`);\n\t\t\ttokens.push({\n\t\t\t\ttext: \"\\u200B\",\n\t\t\t\tattrs: {\n\t\t\t\t\tproseIcon: {\n\t\t\t\t\t\tname: iconProps[\"name\"] || \"i-lucide-star\",\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t});\n\t\t} else if (match[4] !== undefined) {\n\t\t\tconst kbdProps = parseMdcProps(`{${match[4]}}`);\n\t\t\ttokens.push({\n\t\t\t\ttext: kbdProps[\"value\"] || \"\",\n\t\t\t\tattrs: { kbd: { value: kbdProps[\"value\"] || \"\" } },\n\t\t\t});\n\t\t} else if (match[5] !== undefined) {\n\t\t\ttokens.push({\n\t\t\t\ttext: \"\",\n\t\t\t\tnode: \"docLink\",\n\t\t\t\tnodeAttrs: { docId: match[5]! },\n\t\t\t});\n\t\t} else if (match[7] !== undefined) {\n\t\t\ttokens.push({ text: match[7], attrs: { strike: true } });\n\t\t} else if (match[8] !== undefined) {\n\t\t\ttokens.push({ text: match[8], attrs: { bold: true } });\n\t\t} else if (match[9] !== undefined) {\n\t\t\ttokens.push({ text: match[9], attrs: { italic: true } });\n\t\t} else if (match[10] !== undefined) {\n\t\t\ttokens.push({ text: match[10], attrs: { italic: true } });\n\t\t} else if (match[11] !== undefined) {\n\t\t\ttokens.push({ text: match[11], attrs: { code: true } });\n\t\t} else if (match[12] !== undefined && match[13] !== undefined) {\n\t\t\ttokens.push({\n\t\t\t\ttext: match[12],\n\t\t\t\tattrs: { link: { href: match[13] } },\n\t\t\t});\n\t\t}\n\t\tlastIndex = match.index + match[0].length;\n\t}\n\n\tif (lastIndex < stripped.length) {\n\t\ttokens.push({ text: stripped.slice(lastIndex) });\n\t}\n\treturn tokens.filter((t) => t.node || t.text.length > 0);\n}\n\n// ── Block-level parser ───────────────────────────────────────────────────────\n\ninterface TaskItem {\n\ttext: string;\n\tchecked: boolean;\n}\n\ntype Block =\n\t| { type: \"heading\"; level: number; text: string }\n\t| { type: \"paragraph\"; text: string }\n\t| { type: \"bulletList\"; items: string[] }\n\t| { type: \"orderedList\"; items: string[] }\n\t| { type: \"taskList\"; items: TaskItem[] }\n\t| { type: \"codeBlock\"; lang: string; code: string }\n\t| { type: \"blockquote\"; lines: string[] }\n\t| { type: \"table\"; headerRow: string[]; dataRows: string[][] }\n\t| { type: \"hr\" }\n\t| { type: \"callout\"; calloutType: string; innerBlocks: Block[] }\n\t| {\n\t\t\ttype: \"collapsible\";\n\t\t\tlabel: string;\n\t\t\topen: boolean;\n\t\t\tinnerBlocks: Block[];\n\t }\n\t| { type: \"steps\"; innerBlocks: Block[] }\n\t| {\n\t\t\ttype: \"card\";\n\t\t\ttitle: string;\n\t\t\ticon: string;\n\t\t\tto: string;\n\t\t\tinnerBlocks: Block[];\n\t }\n\t| { type: \"cardGroup\"; cards: Block[] }\n\t| { type: \"codeCollapse\"; codeBlocks: Block[] }\n\t| { type: \"codeGroup\"; codeBlocks: Block[] }\n\t| { type: \"codePreview\"; innerBlocks: Block[]; codeBlocks: Block[] }\n\t| { type: \"codeTree\"; files: string }\n\t| {\n\t\t\ttype: \"accordion\";\n\t\t\titems: { label: string; icon: string; innerBlocks: Block[] }[];\n\t }\n\t| {\n\t\t\ttype: \"tabs\";\n\t\t\titems: { label: string; icon: string; innerBlocks: Block[] }[];\n\t }\n\t| {\n\t\t\ttype: \"field\";\n\t\t\tname: string;\n\t\t\tfieldType: string;\n\t\t\trequired: boolean;\n\t\t\tinnerBlocks: Block[];\n\t }\n\t| { type: \"fieldGroup\"; fields: Block[] }\n\t| {\n\t\t\ttype: \"image\";\n\t\t\tsrc: string;\n\t\t\talt: string;\n\t\t\twidth?: string;\n\t\t\theight?: string;\n\t }\n\t| { type: \"docEmbed\"; docId: string; seamless?: boolean }\n\t| { type: \"svgEmbed\"; svg: string; title: string };\n\nfunction parseTableRow(line: string): string[] {\n\tconst parts = line.split(\"|\");\n\treturn parts.slice(1, parts.length - 1).map((c) => c.trim());\n}\n\nfunction isTableSeparator(line: string): boolean {\n\treturn /^\\|[\\s|:-]+\\|$/.test(line.trim());\n}\n\nfunction extractFencedCode(lines: string[]): Block[] {\n\tconst result: Block[] = [];\n\tlet i = 0;\n\twhile (i < lines.length) {\n\t\tconst line = lines[i]!;\n\t\tconst fenceMatch = line.match(/^(`{3,})(\\w*)/);\n\t\tif (fenceMatch) {\n\t\t\tconst fence = fenceMatch[1]!;\n\t\t\tconst lang = fenceMatch[2] ?? \"\";\n\t\t\tconst codeLines: string[] = [];\n\t\t\ti++;\n\t\t\twhile (i < lines.length && !lines[i]!.startsWith(fence)) {\n\t\t\t\tcodeLines.push(lines[i]!);\n\t\t\t\ti++;\n\t\t\t}\n\t\t\ti++;\n\t\t\tresult.push({\n\t\t\t\ttype: \"codeBlock\",\n\t\t\t\tlang,\n\t\t\t\tcode: codeLines.join(\"\\n\"),\n\t\t\t});\n\t\t\tcontinue;\n\t\t}\n\t\ti++;\n\t}\n\treturn result;\n}\n\nfunction parseMdcChildren(\n\tinnerLines: string[],\n\tslotPrefix: string,\n): { label: string; icon: string; innerBlocks: Block[] }[] {\n\tconst items: { label: string; icon: string; lines: string[] }[] = [];\n\tlet current: { label: string; icon: string; lines: string[] } | null =\n\t\tnull;\n\tconst slotRe = new RegExp(`^#${slotPrefix}(\\\\{[^}]*\\\\})?\\\\s*$`);\n\n\tfor (const line of innerLines) {\n\t\tconst slotMatch = line.match(slotRe);\n\t\tif (slotMatch) {\n\t\t\tif (current) items.push(current);\n\t\t\tconst props = parseMdcProps(slotMatch[1]);\n\t\t\tcurrent = {\n\t\t\t\tlabel:\n\t\t\t\t\tprops[\"label\"] ||\n\t\t\t\t\tprops[\"title\"] ||\n\t\t\t\t\t`Item ${items.length + 1}`,\n\t\t\t\ticon: props[\"icon\"] || \"\",\n\t\t\t\tlines: [],\n\t\t\t};\n\t\t\tcontinue;\n\t\t}\n\t\tif (current) {\n\t\t\tcurrent.lines.push(line);\n\t\t} else {\n\t\t\tif (!items.length && !current) {\n\t\t\t\tcurrent = { label: \"Item 1\", icon: \"\", lines: [line] };\n\t\t\t}\n\t\t}\n\t}\n\tif (current) items.push(current);\n\n\treturn items.map((item) => ({\n\t\tlabel: item.label,\n\t\ticon: item.icon,\n\t\tinnerBlocks: parseBlocks(item.lines.join(\"\\n\")),\n\t}));\n}\n\nconst TASK_RE = /^[-*+]\\s+\\[([ xX])\\]\\s+(.*)/;\n\nfunction parseBlocks(markdown: string): Block[] {\n\tconst rawLines = markdown.split(\"\\n\");\n\tlet firstContentLine = 0;\n\twhile (firstContentLine < rawLines.length) {\n\t\tconst l = rawLines[firstContentLine]!;\n\t\tif (l.trim() === \"\" || /^import\\s/.test(l) || /^export\\s/.test(l)) {\n\t\t\tfirstContentLine++;\n\t\t} else {\n\t\t\tbreak;\n\t\t}\n\t}\n\tconst stripped = rawLines.slice(firstContentLine).join(\"\\n\");\n\n\tconst blocks: Block[] = [];\n\tconst lines = stripped.split(\"\\n\");\n\tlet i = 0;\n\n\twhile (i < lines.length) {\n\t\tconst line = lines[i]!;\n\n\t\tconst fenceBlockMatch = line.match(/^(`{3,})(.*)$/);\n\t\tif (fenceBlockMatch) {\n\t\t\tconst fence = fenceBlockMatch[1]!;\n\t\t\tconst lang = fenceBlockMatch[2]!\n\t\t\t\t.trim()\n\t\t\t\t.replace(/\\{[^}]*\\}$/, \"\")\n\t\t\t\t.replace(/\\s*\\[.*\\]$/, \"\")\n\t\t\t\t.trim();\n\t\t\tconst codeLines: string[] = [];\n\t\t\ti++;\n\t\t\twhile (i < lines.length && !lines[i]!.startsWith(fence)) {\n\t\t\t\tcodeLines.push(lines[i]!);\n\t\t\t\ti++;\n\t\t\t}\n\t\t\ti++;\n\t\t\tif (lang === \"svg\" || lang.startsWith(\"svg \")) {\n\t\t\t\tconst svgTitle =\n\t\t\t\t\tlang === \"svg\" ? \"\" : lang.slice(4).trim();\n\t\t\t\tblocks.push({\n\t\t\t\t\ttype: \"svgEmbed\",\n\t\t\t\t\tsvg: codeLines.join(\"\\n\"),\n\t\t\t\t\ttitle: svgTitle,\n\t\t\t\t});\n\t\t\t} else {\n\t\t\t\tblocks.push({\n\t\t\t\t\ttype: \"codeBlock\",\n\t\t\t\t\tlang,\n\t\t\t\t\tcode: codeLines.join(\"\\n\"),\n\t\t\t\t});\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\n\t\tconst headingMatch = line.match(/^(#{1,6})\\s+(.*)/);\n\t\tif (headingMatch) {\n\t\t\tblocks.push({\n\t\t\t\ttype: \"heading\",\n\t\t\t\tlevel: headingMatch[1]!.length,\n\t\t\t\ttext: headingMatch[2]!.trim(),\n\t\t\t});\n\t\t\ti++;\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (/^[-*_]{3,}\\s*$/.test(line)) {\n\t\t\tblocks.push({ type: \"hr\" });\n\t\t\ti++;\n\t\t\tcontinue;\n\t\t}\n\n\t\tconst docEmbedMatch = line.match(\n\t\t\t/^!\\[\\[([^\\]|]+?)(?:\\|[^\\]]*?)?\\]\\](\\{[^}]*\\})?\\s*$/,\n\t\t);\n\t\tif (docEmbedMatch) {\n\t\t\tconst props = parseMdcProps(docEmbedMatch[2]);\n\t\t\tconst seamless =\n\t\t\t\t\"seamless\" in props ||\n\t\t\t\tprops[\"seamless\"] === \"true\" ||\n\t\t\t\t/\\{[^}]*\\bseamless\\b[^}]*\\}/.test(docEmbedMatch[2] ?? \"\");\n\t\t\tblocks.push({\n\t\t\t\ttype: \"docEmbed\",\n\t\t\t\tdocId: docEmbedMatch[1]!,\n\t\t\t\tseamless: seamless || undefined,\n\t\t\t});\n\t\t\ti++;\n\t\t\tcontinue;\n\t\t}\n\n\t\tconst imgMatch = line.match(\n\t\t\t/^!\\[([^\\]]*)\\]\\(([^)]+)\\)(\\{[^}]*\\})?\\s*$/,\n\t\t);\n\t\tif (imgMatch) {\n\t\t\tconst alt = imgMatch[1] ?? \"\";\n\t\t\tconst src = imgMatch[2] ?? \"\";\n\t\t\tconst attrs = parseMdcProps(imgMatch[3]);\n\t\t\tblocks.push({\n\t\t\t\ttype: \"image\",\n\t\t\t\tsrc,\n\t\t\t\talt,\n\t\t\t\twidth: attrs[\"width\"],\n\t\t\t\theight: attrs[\"height\"],\n\t\t\t});\n\t\t\ti++;\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (line.startsWith(\"> \") || line === \">\") {\n\t\t\tconst bqLines: string[] = [];\n\t\t\twhile (\n\t\t\t\ti < lines.length &&\n\t\t\t\t(lines[i]!.startsWith(\"> \") || lines[i] === \">\")\n\t\t\t) {\n\t\t\t\tbqLines.push(lines[i]!.replace(/^>\\s?/, \"\"));\n\t\t\t\ti++;\n\t\t\t}\n\t\t\tblocks.push({ type: \"blockquote\", lines: bqLines });\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (/^\\s*\\|/.test(line)) {\n\t\t\tconst tableLines: string[] = [];\n\t\t\twhile (i < lines.length && /^\\s*\\|/.test(lines[i]!)) {\n\t\t\t\ttableLines.push(lines[i]!);\n\t\t\t\ti++;\n\t\t\t}\n\t\t\tif (\n\t\t\t\ttableLines.length >= 2 &&\n\t\t\t\tisTableSeparator(tableLines[1]!)\n\t\t\t) {\n\t\t\t\tconst headerRow = parseTableRow(tableLines[0]!);\n\t\t\t\tconst dataRows = tableLines\n\t\t\t\t\t.slice(2)\n\t\t\t\t\t.filter((l) => !isTableSeparator(l))\n\t\t\t\t\t.map(parseTableRow);\n\t\t\t\tblocks.push({ type: \"table\", headerRow, dataRows });\n\t\t\t} else {\n\t\t\t\tfor (const l of tableLines)\n\t\t\t\t\tblocks.push({ type: \"paragraph\", text: l });\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\n\t\tconst MDC_OPEN = /^\\s*(:{2,})(\\w[\\w-]*)(\\{[^}]*\\})?\\s*$/;\n\t\tif (MDC_OPEN.test(line)) {\n\t\t\tconst colons =\n\t\t\t\tline.match(/^\\s*(:+)/)?.[1]?.length ?? 2;\n\t\t\tconst componentName =\n\t\t\t\tline.match(/^\\s*:{2,}(\\w[\\w-]*)/)?.[1] ?? \"\";\n\t\t\tconst innerLines: string[] = [];\n\t\t\ti++;\n\t\t\twhile (i < lines.length) {\n\t\t\t\tconst l = lines[i]!;\n\t\t\t\tif (\n\t\t\t\t\tnew RegExp(`^\\\\s*:{${colons}}\\\\s*$`).test(l)\n\t\t\t\t) {\n\t\t\t\t\ti++;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tconst innerFence = l.match(/^(\\s*`{3,})/);\n\t\t\t\tif (innerFence) {\n\t\t\t\t\tconst fenceStr = innerFence[1]!.trimStart();\n\t\t\t\t\tinnerLines.push(l);\n\t\t\t\t\ti++;\n\t\t\t\t\twhile (\n\t\t\t\t\t\ti < lines.length &&\n\t\t\t\t\t\t!lines[i]!.trimStart().startsWith(fenceStr)\n\t\t\t\t\t) {\n\t\t\t\t\t\tinnerLines.push(lines[i]!);\n\t\t\t\t\t\ti++;\n\t\t\t\t\t}\n\t\t\t\t\tif (i < lines.length) {\n\t\t\t\t\t\tinnerLines.push(lines[i]!);\n\t\t\t\t\t\ti++;\n\t\t\t\t\t}\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tinnerLines.push(l);\n\t\t\t\ti++;\n\t\t\t}\n\n\t\t\tconst nonBlank = innerLines.filter(\n\t\t\t\t(l) => l.trim().length > 0,\n\t\t\t);\n\t\t\tif (nonBlank.length) {\n\t\t\t\tconst minIndent = Math.min(\n\t\t\t\t\t...nonBlank.map(\n\t\t\t\t\t\t(l) => l.match(/^(\\s*)/)?.[1]?.length ?? 0,\n\t\t\t\t\t),\n\t\t\t\t);\n\t\t\t\tif (minIndent > 0) {\n\t\t\t\t\tfor (let j = 0; j < innerLines.length; j++) {\n\t\t\t\t\t\tinnerLines[j] = innerLines[j]!.slice(\n\t\t\t\t\t\t\tMath.min(minIndent, innerLines[j]!.length),\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tlet contentStart = 0;\n\t\t\tif (innerLines[0]?.trim() === \"---\") {\n\t\t\t\tconst fmEnd = innerLines.findIndex(\n\t\t\t\t\t(l, idx) => idx > 0 && l.trim() === \"---\",\n\t\t\t\t);\n\t\t\t\tif (fmEnd !== -1) contentStart = fmEnd + 1;\n\t\t\t}\n\t\t\tconst contentLines = innerLines.slice(contentStart);\n\n\t\t\tconst defaultSlotLines: string[] = [];\n\t\t\tconst codeSlotLines: string[] = [];\n\t\t\tlet currentSlot: \"default\" | \"code\" | \"other\" = \"default\";\n\t\t\tfor (const l of contentLines) {\n\t\t\t\tif (/^#code\\s*$/.test(l)) {\n\t\t\t\t\tcurrentSlot = \"code\";\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tif (/^#\\w+/.test(l) && !/^#{2,}\\s/.test(l)) {\n\t\t\t\t\tcurrentSlot = \"other\";\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tif (currentSlot === \"default\") defaultSlotLines.push(l);\n\t\t\t\telse if (currentSlot === \"code\") codeSlotLines.push(l);\n\t\t\t}\n\t\t\tconst innerBlocks = parseBlocks(defaultSlotLines.join(\"\\n\"));\n\n\t\t\tconst codeBlocks = extractFencedCode(codeSlotLines);\n\n\t\t\tconst CALLOUT_NAMES = new Set([\n\t\t\t\t\"tip\",\n\t\t\t\t\"note\",\n\t\t\t\t\"info\",\n\t\t\t\t\"warning\",\n\t\t\t\t\"caution\",\n\t\t\t\t\"danger\",\n\t\t\t\t\"callout\",\n\t\t\t\t\"alert\",\n\t\t\t]);\n\t\t\tif (CALLOUT_NAMES.has(componentName.toLowerCase())) {\n\t\t\t\tblocks.push({\n\t\t\t\t\ttype: \"callout\",\n\t\t\t\t\tcalloutType: componentName.toLowerCase(),\n\t\t\t\t\tinnerBlocks,\n\t\t\t\t});\n\t\t\t} else {\n\t\t\t\tconst mdcProps = parseMdcProps(\n\t\t\t\t\tline.match(MDC_OPEN)?.[3],\n\t\t\t\t);\n\t\t\t\tconst lc = componentName.toLowerCase();\n\n\t\t\t\tif (lc === \"collapsible\") {\n\t\t\t\t\tblocks.push({\n\t\t\t\t\t\ttype: \"collapsible\",\n\t\t\t\t\t\tlabel: mdcProps[\"label\"] || \"Details\",\n\t\t\t\t\t\topen: mdcProps[\"open\"] === \"true\",\n\t\t\t\t\t\tinnerBlocks,\n\t\t\t\t\t});\n\t\t\t\t} else if (lc === \"steps\") {\n\t\t\t\t\tblocks.push({ type: \"steps\", innerBlocks });\n\t\t\t\t} else if (lc === \"card\") {\n\t\t\t\t\tblocks.push({\n\t\t\t\t\t\ttype: \"card\",\n\t\t\t\t\t\ttitle: mdcProps[\"title\"] || \"\",\n\t\t\t\t\t\ticon: mdcProps[\"icon\"] || \"\",\n\t\t\t\t\t\tto: mdcProps[\"to\"] || \"\",\n\t\t\t\t\t\tinnerBlocks,\n\t\t\t\t\t});\n\t\t\t\t} else if (lc === \"card-group\") {\n\t\t\t\t\tconst cards = innerBlocks.filter(\n\t\t\t\t\t\t(b) => b.type === \"card\",\n\t\t\t\t\t);\n\t\t\t\t\tif (cards.length) {\n\t\t\t\t\t\tblocks.push({ type: \"cardGroup\", cards });\n\t\t\t\t\t} else {\n\t\t\t\t\t\tblocks.push(...innerBlocks);\n\t\t\t\t\t}\n\t\t\t\t} else if (lc === \"code-collapse\") {\n\t\t\t\t\tblocks.push({\n\t\t\t\t\t\ttype: \"codeCollapse\",\n\t\t\t\t\t\tcodeBlocks: codeBlocks.length\n\t\t\t\t\t\t\t? codeBlocks\n\t\t\t\t\t\t\t: innerBlocks.filter(\n\t\t\t\t\t\t\t\t\t(b) => b.type === \"codeBlock\",\n\t\t\t\t\t\t\t\t),\n\t\t\t\t\t});\n\t\t\t\t} else if (lc === \"code-group\") {\n\t\t\t\t\tconst allCode = [\n\t\t\t\t\t\t...innerBlocks.filter(\n\t\t\t\t\t\t\t(b) => b.type === \"codeBlock\",\n\t\t\t\t\t\t),\n\t\t\t\t\t\t...codeBlocks,\n\t\t\t\t\t];\n\t\t\t\t\tblocks.push({ type: \"codeGroup\", codeBlocks: allCode });\n\t\t\t\t} else if (lc === \"code-preview\") {\n\t\t\t\t\tblocks.push({\n\t\t\t\t\t\ttype: \"codePreview\",\n\t\t\t\t\t\tinnerBlocks,\n\t\t\t\t\t\tcodeBlocks,\n\t\t\t\t\t});\n\t\t\t\t} else if (lc === \"code-tree\") {\n\t\t\t\t\tblocks.push({\n\t\t\t\t\t\ttype: \"codeTree\",\n\t\t\t\t\t\tfiles: mdcProps[\"files\"] || \"[]\",\n\t\t\t\t\t});\n\t\t\t\t} else if (lc === \"accordion\") {\n\t\t\t\t\tconst items = parseMdcChildren(\n\t\t\t\t\t\tcontentLines,\n\t\t\t\t\t\t\"item\",\n\t\t\t\t\t);\n\t\t\t\t\tif (items.length) {\n\t\t\t\t\t\tblocks.push({ type: \"accordion\", items });\n\t\t\t\t\t} else {\n\t\t\t\t\t\tblocks.push({\n\t\t\t\t\t\t\ttype: \"accordion\",\n\t\t\t\t\t\t\titems: [\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tlabel: \"Item 1\",\n\t\t\t\t\t\t\t\t\ticon: \"\",\n\t\t\t\t\t\t\t\t\tinnerBlocks,\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t],\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t} else if (lc === \"tabs\") {\n\t\t\t\t\tconst items = parseMdcChildren(\n\t\t\t\t\t\tcontentLines,\n\t\t\t\t\t\t\"tab\",\n\t\t\t\t\t);\n\t\t\t\t\tif (items.length) {\n\t\t\t\t\t\tblocks.push({ type: \"tabs\", items });\n\t\t\t\t\t} else {\n\t\t\t\t\t\tblocks.push({\n\t\t\t\t\t\t\ttype: \"tabs\",\n\t\t\t\t\t\t\titems: [\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tlabel: \"Tab 1\",\n\t\t\t\t\t\t\t\t\ticon: \"\",\n\t\t\t\t\t\t\t\t\tinnerBlocks,\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t],\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t} else if (lc === \"field\") {\n\t\t\t\t\tblocks.push({\n\t\t\t\t\t\ttype: \"field\",\n\t\t\t\t\t\tname: mdcProps[\"name\"] || \"\",\n\t\t\t\t\t\tfieldType: mdcProps[\"type\"] || \"string\",\n\t\t\t\t\t\trequired: mdcProps[\"required\"] === \"true\",\n\t\t\t\t\t\tinnerBlocks,\n\t\t\t\t\t});\n\t\t\t\t} else if (lc === \"field-group\") {\n\t\t\t\t\tconst fields = innerBlocks.filter(\n\t\t\t\t\t\t(b) => b.type === \"field\",\n\t\t\t\t\t);\n\t\t\t\t\tif (fields.length) {\n\t\t\t\t\t\tblocks.push({ type: \"fieldGroup\", fields });\n\t\t\t\t\t} else {\n\t\t\t\t\t\tblocks.push(...innerBlocks);\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tblocks.push(...innerBlocks);\n\t\t\t\t\tblocks.push(...codeBlocks);\n\t\t\t\t}\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (TASK_RE.test(line)) {\n\t\t\tconst items: TaskItem[] = [];\n\t\t\twhile (i < lines.length && TASK_RE.test(lines[i]!)) {\n\t\t\t\tconst m = lines[i]!.match(TASK_RE)!;\n\t\t\t\titems.push({\n\t\t\t\t\tchecked: m[1]!.toLowerCase() === \"x\",\n\t\t\t\t\ttext: m[2]!,\n\t\t\t\t});\n\t\t\t\ti++;\n\t\t\t}\n\t\t\tblocks.push({ type: \"taskList\", items });\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (/^[-*+]\\s+/.test(line)) {\n\t\t\tconst items: string[] = [];\n\t\t\twhile (\n\t\t\t\ti < lines.length &&\n\t\t\t\t/^[-*+]\\s+/.test(lines[i]!) &&\n\t\t\t\t!TASK_RE.test(lines[i]!)\n\t\t\t) {\n\t\t\t\titems.push(lines[i]!.replace(/^[-*+]\\s+/, \"\"));\n\t\t\t\ti++;\n\t\t\t}\n\t\t\tif (items.length) {\n\t\t\t\tblocks.push({ type: \"bulletList\", items });\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t}\n\n\t\tif (/^\\d+\\.\\s+/.test(line)) {\n\t\t\tconst items: string[] = [];\n\t\t\twhile (i < lines.length && /^\\d+\\.\\s+/.test(lines[i]!)) {\n\t\t\t\titems.push(lines[i]!.replace(/^\\d+\\.\\s+/, \"\"));\n\t\t\t\ti++;\n\t\t\t}\n\t\t\tblocks.push({ type: \"orderedList\", items });\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (line.trim() === \"\") {\n\t\t\ti++;\n\t\t\tcontinue;\n\t\t}\n\n\t\tconst paraLines: string[] = [];\n\t\twhile (\n\t\t\ti < lines.length &&\n\t\t\tlines[i]!.trim() !== \"\" &&\n\t\t\t!/^(#{1,6}\\s|[-*+]\\s|\\d+\\.\\s|>|`{3,}|\\s*\\||[-*_]{3,}\\s*$|\\s*:{2,}\\w)/.test(\n\t\t\t\tlines[i]!,\n\t\t\t)\n\t\t) {\n\t\t\tparaLines.push(lines[i]!);\n\t\t\ti++;\n\t\t}\n\t\tif (paraLines.length) {\n\t\t\tblocks.push({ type: \"paragraph\", text: paraLines.join(\" \") });\n\t\t}\n\t}\n\n\treturn blocks;\n}\n\n// ── Y.js content population helpers ──────────────────────────────────────────\n\nfunction fillTextInto(\n\tel: Y.XmlElement,\n\ttokens: InlineToken[],\n): void {\n\tconst filtered = tokens.filter((t) => t.node || t.text.length > 0);\n\tif (!filtered.length) return;\n\n\tconst children: (Y.XmlText | Y.XmlElement)[] = filtered.map((tok) => {\n\t\tif (tok.node) {\n\t\t\tconst xe = new Y.XmlElement(tok.node);\n\t\t\tif (tok.nodeAttrs) {\n\t\t\t\tfor (const [k, v] of Object.entries(tok.nodeAttrs))\n\t\t\t\t\txe.setAttribute(k, v);\n\t\t\t}\n\t\t\treturn xe;\n\t\t}\n\t\treturn new Y.XmlText();\n\t});\n\tel.insert(0, children);\n\n\tfiltered.forEach((tok, i) => {\n\t\tif (tok.node) return;\n\t\tconst xt = children[i] as Y.XmlText;\n\t\tif (tok.attrs) {\n\t\t\txt.insert(\n\t\t\t\t0,\n\t\t\t\ttok.text,\n\t\t\t\ttok.attrs as Record<string, boolean | object>,\n\t\t\t);\n\t\t} else {\n\t\t\txt.insert(0, tok.text);\n\t\t}\n\t});\n}\n\nfunction blockElName(b: Block): string {\n\tswitch (b.type) {\n\t\tcase \"heading\":\n\t\t\treturn \"heading\";\n\t\tcase \"paragraph\":\n\t\t\treturn \"paragraph\";\n\t\tcase \"bulletList\":\n\t\t\treturn \"bulletList\";\n\t\tcase \"orderedList\":\n\t\t\treturn \"orderedList\";\n\t\tcase \"taskList\":\n\t\t\treturn \"taskList\";\n\t\tcase \"codeBlock\":\n\t\t\treturn \"codeBlock\";\n\t\tcase \"blockquote\":\n\t\t\treturn \"blockquote\";\n\t\tcase \"table\":\n\t\t\treturn \"table\";\n\t\tcase \"hr\":\n\t\t\treturn \"horizontalRule\";\n\t\tcase \"callout\":\n\t\t\treturn \"callout\";\n\t\tcase \"collapsible\":\n\t\t\treturn \"collapsible\";\n\t\tcase \"steps\":\n\t\t\treturn \"steps\";\n\t\tcase \"card\":\n\t\t\treturn \"card\";\n\t\tcase \"cardGroup\":\n\t\t\treturn \"cardGroup\";\n\t\tcase \"codeCollapse\":\n\t\t\treturn \"codeCollapse\";\n\t\tcase \"codeGroup\":\n\t\t\treturn \"codeGroup\";\n\t\tcase \"codePreview\":\n\t\t\treturn \"codePreview\";\n\t\tcase \"codeTree\":\n\t\t\treturn \"codeTree\";\n\t\tcase \"accordion\":\n\t\t\treturn \"accordion\";\n\t\tcase \"tabs\":\n\t\t\treturn \"tabs\";\n\t\tcase \"field\":\n\t\t\treturn \"field\";\n\t\tcase \"fieldGroup\":\n\t\t\treturn \"fieldGroup\";\n\t\tcase \"image\":\n\t\t\treturn \"image\";\n\t\tcase \"docEmbed\":\n\t\t\treturn \"docEmbed\";\n\t\tcase \"svgEmbed\":\n\t\t\treturn \"svgEmbed\";\n\t}\n}\n\nfunction fillBlock(el: Y.XmlElement, block: Block): void {\n\tswitch (block.type) {\n\t\tcase \"heading\": {\n\t\t\tel.setAttribute(\"level\", block.level as any);\n\t\t\tfillTextInto(el, parseInline(block.text));\n\t\t\tbreak;\n\t\t}\n\t\tcase \"paragraph\": {\n\t\t\tfillTextInto(el, parseInline(block.text));\n\t\t\tbreak;\n\t\t}\n\t\tcase \"bulletList\":\n\t\tcase \"orderedList\": {\n\t\t\tconst listItemEls = block.items.map(\n\t\t\t\t() => new Y.XmlElement(\"listItem\"),\n\t\t\t);\n\t\t\tel.insert(0, listItemEls);\n\t\t\tblock.items.forEach((text, i) => {\n\t\t\t\tconst paraEl = new Y.XmlElement(\"paragraph\");\n\t\t\t\tlistItemEls[i]!.insert(0, [paraEl]);\n\t\t\t\tfillTextInto(paraEl, parseInline(text));\n\t\t\t});\n\t\t\tbreak;\n\t\t}\n\t\tcase \"taskList\": {\n\t\t\tconst taskItemEls = block.items.map(\n\t\t\t\t() => new Y.XmlElement(\"taskItem\"),\n\t\t\t);\n\t\t\tel.insert(0, taskItemEls);\n\t\t\tblock.items.forEach((item, i) => {\n\t\t\t\ttaskItemEls[i]!.setAttribute(\n\t\t\t\t\t\"checked\",\n\t\t\t\t\titem.checked as any,\n\t\t\t\t);\n\t\t\t\tconst paraEl = new Y.XmlElement(\"paragraph\");\n\t\t\t\ttaskItemEls[i]!.insert(0, [paraEl]);\n\t\t\t\tfillTextInto(paraEl, parseInline(item.text));\n\t\t\t});\n\t\t\tbreak;\n\t\t}\n\t\tcase \"codeBlock\": {\n\t\t\tif (block.lang) el.setAttribute(\"language\", block.lang);\n\t\t\tconst xt = new Y.XmlText();\n\t\t\tel.insert(0, [xt]);\n\t\t\txt.insert(0, block.code);\n\t\t\tbreak;\n\t\t}\n\t\tcase \"blockquote\": {\n\t\t\tconst paraEls = block.lines.map(\n\t\t\t\t() => new Y.XmlElement(\"paragraph\"),\n\t\t\t);\n\t\t\tel.insert(0, paraEls);\n\t\t\tblock.lines.forEach((line, i) =>\n\t\t\t\tfillTextInto(paraEls[i]!, parseInline(line)),\n\t\t\t);\n\t\t\tbreak;\n\t\t}\n\t\tcase \"table\": {\n\t\t\tconst headerRowEl = new Y.XmlElement(\"tableRow\");\n\t\t\tconst dataRowEls = block.dataRows.map(\n\t\t\t\t() => new Y.XmlElement(\"tableRow\"),\n\t\t\t);\n\t\t\tel.insert(0, [headerRowEl, ...dataRowEls]);\n\n\t\t\tconst headerCellEls = block.headerRow.map(\n\t\t\t\t() => new Y.XmlElement(\"tableHeader\"),\n\t\t\t);\n\t\t\theaderRowEl.insert(0, headerCellEls);\n\t\t\tblock.headerRow.forEach((cellText, i) => {\n\t\t\t\tconst paraEl = new Y.XmlElement(\"paragraph\");\n\t\t\t\theaderCellEls[i]!.insert(0, [paraEl]);\n\t\t\t\tfillTextInto(paraEl, parseInline(cellText));\n\t\t\t});\n\n\t\t\tblock.dataRows.forEach((row, ri) => {\n\t\t\t\tconst cellEls = row.map(\n\t\t\t\t\t() => new Y.XmlElement(\"tableCell\"),\n\t\t\t\t);\n\t\t\t\tdataRowEls[ri]!.insert(0, cellEls);\n\t\t\t\trow.forEach((cellText, ci) => {\n\t\t\t\t\tconst paraEl = new Y.XmlElement(\"paragraph\");\n\t\t\t\t\tcellEls[ci]!.insert(0, [paraEl]);\n\t\t\t\t\tfillTextInto(paraEl, parseInline(cellText));\n\t\t\t\t});\n\t\t\t});\n\t\t\tbreak;\n\t\t}\n\t\tcase \"hr\":\n\t\t\tbreak;\n\t\tcase \"callout\": {\n\t\t\tel.setAttribute(\"type\", block.calloutType);\n\t\t\tif (!block.innerBlocks.length) {\n\t\t\t\tconst paraEl = new Y.XmlElement(\"paragraph\");\n\t\t\t\tel.insert(0, [paraEl]);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tconst innerEls = block.innerBlocks.map(\n\t\t\t\t(b) => new Y.XmlElement(blockElName(b)),\n\t\t\t);\n\t\t\tel.insert(0, innerEls);\n\t\t\tblock.innerBlocks.forEach((b, i) =>\n\t\t\t\tfillBlock(innerEls[i]!, b),\n\t\t\t);\n\t\t\tbreak;\n\t\t}\n\t\tcase \"collapsible\": {\n\t\t\tel.setAttribute(\"label\", block.label);\n\t\t\tel.setAttribute(\"open\", block.open as any);\n\t\t\tconst inner = block.innerBlocks.length\n\t\t\t\t? block.innerBlocks\n\t\t\t\t: [{ type: \"paragraph\" as const, text: \"\" }];\n\t\t\tconst innerEls = inner.map(\n\t\t\t\t(b) => new Y.XmlElement(blockElName(b)),\n\t\t\t);\n\t\t\tel.insert(0, innerEls);\n\t\t\tinner.forEach((b, i) => fillBlock(innerEls[i]!, b));\n\t\t\tbreak;\n\t\t}\n\t\tcase \"steps\": {\n\t\t\tconst inner = block.innerBlocks.length\n\t\t\t\t? block.innerBlocks\n\t\t\t\t: [{ type: \"paragraph\" as const, text: \"\" }];\n\t\t\tconst innerEls = inner.map(\n\t\t\t\t(b) => new Y.XmlElement(blockElName(b)),\n\t\t\t);\n\t\t\tel.insert(0, innerEls);\n\t\t\tinner.forEach((b, i) => fillBlock(innerEls[i]!, b));\n\t\t\tbreak;\n\t\t}\n\t\tcase \"card\": {\n\t\t\tif (block.title) el.setAttribute(\"title\", block.title);\n\t\t\tif (block.icon) el.setAttribute(\"icon\", block.icon);\n\t\t\tif (block.to) el.setAttribute(\"to\", block.to);\n\t\t\tconst inner = block.innerBlocks.length\n\t\t\t\t? block.innerBlocks\n\t\t\t\t: [{ type: \"paragraph\" as const, text: \"\" }];\n\t\t\tconst innerEls = inner.map(\n\t\t\t\t(b) => new Y.XmlElement(blockElName(b)),\n\t\t\t);\n\t\t\tel.insert(0, innerEls);\n\t\t\tinner.forEach((b, i) => fillBlock(innerEls[i]!, b));\n\t\t\tbreak;\n\t\t}\n\t\tcase \"cardGroup\": {\n\t\t\tconst cardEls = block.cards.map(\n\t\t\t\t(b) => new Y.XmlElement(blockElName(b)),\n\t\t\t);\n\t\t\tel.insert(0, cardEls);\n\t\t\tblock.cards.forEach((b, i) => fillBlock(cardEls[i]!, b));\n\t\t\tbreak;\n\t\t}\n\t\tcase \"codeCollapse\": {\n\t\t\tconst codes = block.codeBlocks.length\n\t\t\t\t? block.codeBlocks\n\t\t\t\t: [{ type: \"codeBlock\" as const, lang: \"\", code: \"\" }];\n\t\t\tconst codeEl = new Y.XmlElement(\"codeBlock\");\n\t\t\tel.insert(0, [codeEl]);\n\t\t\tfillBlock(codeEl, codes[0]!);\n\t\t\tbreak;\n\t\t}\n\t\tcase \"codeGroup\": {\n\t\t\tconst codes = block.codeBlocks.length\n\t\t\t\t? block.codeBlocks\n\t\t\t\t: [{ type: \"codeBlock\" as const, lang: \"\", code: \"\" }];\n\t\t\tconst codeEls = codes.map(() => new Y.XmlElement(\"codeBlock\"));\n\t\t\tel.insert(0, codeEls);\n\t\t\tcodes.forEach((b, i) => fillBlock(codeEls[i]!, b));\n\t\t\tbreak;\n\t\t}\n\t\tcase \"codePreview\": {\n\t\t\tconst all = [...block.innerBlocks, ...block.codeBlocks];\n\t\t\tconst inner = all.length\n\t\t\t\t? all\n\t\t\t\t: [{ type: \"paragraph\" as const, text: \"\" }];\n\t\t\tconst innerEls = inner.map(\n\t\t\t\t(b) => new Y.XmlElement(blockElName(b)),\n\t\t\t);\n\t\t\tel.insert(0, innerEls);\n\t\t\tinner.forEach((b, i) => fillBlock(innerEls[i]!, b));\n\t\t\tbreak;\n\t\t}\n\t\tcase \"codeTree\": {\n\t\t\tel.setAttribute(\"files\", block.files);\n\t\t\tbreak;\n\t\t}\n\t\tcase \"accordion\": {\n\t\t\tconst itemEls = block.items.map(\n\t\t\t\t() => new Y.XmlElement(\"accordionItem\"),\n\t\t\t);\n\t\t\tel.insert(0, itemEls);\n\t\t\tblock.items.forEach((item, i) => {\n\t\t\t\titemEls[i]!.setAttribute(\"label\", item.label);\n\t\t\t\tif (item.icon)\n\t\t\t\t\titemEls[i]!.setAttribute(\"icon\", item.icon);\n\t\t\t\tconst inner = item.innerBlocks.length\n\t\t\t\t\t? item.innerBlocks\n\t\t\t\t\t: [{ type: \"paragraph\" as const, text: \"\" }];\n\t\t\t\tconst childEls = inner.map(\n\t\t\t\t\t(b) => new Y.XmlElement(blockElName(b)),\n\t\t\t\t);\n\t\t\t\titemEls[i]!.insert(0, childEls);\n\t\t\t\tinner.forEach((b, ci) => fillBlock(childEls[ci]!, b));\n\t\t\t});\n\t\t\tbreak;\n\t\t}\n\t\tcase \"tabs\": {\n\t\t\tconst itemEls = block.items.map(\n\t\t\t\t() => new Y.XmlElement(\"tabsItem\"),\n\t\t\t);\n\t\t\tel.insert(0, itemEls);\n\t\t\tblock.items.forEach((item, i) => {\n\t\t\t\titemEls[i]!.setAttribute(\"label\", item.label);\n\t\t\t\tif (item.icon)\n\t\t\t\t\titemEls[i]!.setAttribute(\"icon\", item.icon);\n\t\t\t\tconst inner = item.innerBlocks.length\n\t\t\t\t\t? item.innerBlocks\n\t\t\t\t\t: [{ type: \"paragraph\" as const, text: \"\" }];\n\t\t\t\tconst childEls = inner.map(\n\t\t\t\t\t(b) => new Y.XmlElement(blockElName(b)),\n\t\t\t\t);\n\t\t\t\titemEls[i]!.insert(0, childEls);\n\t\t\t\tinner.forEach((b, ci) => fillBlock(childEls[ci]!, b));\n\t\t\t});\n\t\t\tbreak;\n\t\t}\n\t\tcase \"field\": {\n\t\t\tif (block.name) el.setAttribute(\"name\", block.name);\n\t\t\tel.setAttribute(\"type\", block.fieldType);\n\t\t\tel.setAttribute(\"required\", block.required as any);\n\t\t\tconst inner = block.innerBlocks.length\n\t\t\t\t? block.innerBlocks\n\t\t\t\t: [{ type: \"paragraph\" as const, text: \"\" }];\n\t\t\tconst innerEls = inner.map(\n\t\t\t\t(b) => new Y.XmlElement(blockElName(b)),\n\t\t\t);\n\t\t\tel.insert(0, innerEls);\n\t\t\tinner.forEach((b, i) => fillBlock(innerEls[i]!, b));\n\t\t\tbreak;\n\t\t}\n\t\tcase \"fieldGroup\": {\n\t\t\tconst fieldEls = block.fields.map(\n\t\t\t\t(b) => new Y.XmlElement(blockElName(b)),\n\t\t\t);\n\t\t\tel.insert(0, fieldEls);\n\t\t\tblock.fields.forEach((b, i) => fillBlock(fieldEls[i]!, b));\n\t\t\tbreak;\n\t\t}\n\t\tcase \"image\": {\n\t\t\tel.setAttribute(\"src\", block.src);\n\t\t\tif (block.alt) el.setAttribute(\"alt\", block.alt);\n\t\t\tif (block.width) el.setAttribute(\"width\", block.width);\n\t\t\tif (block.height) el.setAttribute(\"height\", block.height);\n\t\t\tbreak;\n\t\t}\n\t\tcase \"docEmbed\": {\n\t\t\tel.setAttribute(\"docId\", block.docId);\n\t\t\tif (block.seamless) el.setAttribute(\"seamless\", \"true\");\n\t\t\tbreak;\n\t\t}\n\t\tcase \"svgEmbed\": {\n\t\t\tel.setAttribute(\"svg\", block.svg);\n\t\t\tif (block.title) el.setAttribute(\"title\", block.title);\n\t\t\tbreak;\n\t\t}\n\t}\n}\n\n// ── Public: Markdown → Y.js ─────────────────────────────────────────────────\n\nexport function populateYDocFromMarkdown(\n\tfragment: Y.XmlFragment,\n\tmarkdown: string,\n\tfallbackTitle = \"Untitled\",\n): void {\n\tconst ydoc = fragment.doc;\n\tif (!ydoc) {\n\t\tconsole.warn(\n\t\t\t\"[markdownToYjs] fragment has no doc — skipping population\",\n\t\t);\n\t\treturn;\n\t}\n\n\tconst blocks = parseBlocks(markdown);\n\n\tlet title = fallbackTitle;\n\tlet contentBlocks = blocks;\n\tconst h1 = blocks.findIndex(\n\t\t(b) => b.type === \"heading\" && b.level === 1,\n\t);\n\tif (h1 !== -1) {\n\t\ttitle = (\n\t\t\tblocks[h1] as { type: \"heading\"; level: number; text: string }\n\t\t).text;\n\t\tcontentBlocks = blocks.filter((_, i) => i !== h1);\n\t}\n\tif (!contentBlocks.length)\n\t\tcontentBlocks = [{ type: \"paragraph\", text: \"\" }];\n\n\tydoc.transact(() => {\n\t\tconst headerEl = new Y.XmlElement(\"documentHeader\");\n\t\tconst metaEl = new Y.XmlElement(\"documentMeta\");\n\t\tconst bodyEls: Y.XmlElement[] = contentBlocks.map((b) => {\n\t\t\tswitch (b.type) {\n\t\t\t\tcase \"heading\":\n\t\t\t\t\treturn new Y.XmlElement(\"heading\");\n\t\t\t\tcase \"paragraph\":\n\t\t\t\t\treturn new Y.XmlElement(\"paragraph\");\n\t\t\t\tcase \"bulletList\":\n\t\t\t\t\treturn new Y.XmlElement(\"bulletList\");\n\t\t\t\tcase \"orderedList\":\n\t\t\t\t\treturn new Y.XmlElement(\"orderedList\");\n\t\t\t\tcase \"taskList\":\n\t\t\t\t\treturn new Y.XmlElement(\"taskList\");\n\t\t\t\tcase \"codeBlock\":\n\t\t\t\t\treturn new Y.XmlElement(\"codeBlock\");\n\t\t\t\tcase \"blockquote\":\n\t\t\t\t\treturn new Y.XmlElement(\"blockquote\");\n\t\t\t\tcase \"table\":\n\t\t\t\t\treturn new Y.XmlElement(\"table\");\n\t\t\t\tcase \"hr\":\n\t\t\t\t\treturn new Y.XmlElement(\"horizontalRule\");\n\t\t\t\tcase \"callout\":\n\t\t\t\t\treturn new Y.XmlElement(\"callout\");\n\t\t\t\tcase \"collapsible\":\n\t\t\t\t\treturn new Y.XmlElement(\"collapsible\");\n\t\t\t\tcase \"steps\":\n\t\t\t\t\treturn new Y.XmlElement(\"steps\");\n\t\t\t\tcase \"card\":\n\t\t\t\t\treturn new Y.XmlElement(\"card\");\n\t\t\t\tcase \"cardGroup\":\n\t\t\t\t\treturn new Y.XmlElement(\"cardGroup\");\n\t\t\t\tcase \"codeCollapse\":\n\t\t\t\t\treturn new Y.XmlElement(\"codeCollapse\");\n\t\t\t\tcase \"codeGroup\":\n\t\t\t\t\treturn new Y.XmlElement(\"codeGroup\");\n\t\t\t\tcase \"codePreview\":\n\t\t\t\t\treturn new Y.XmlElement(\"codePreview\");\n\t\t\t\tcase \"codeTree\":\n\t\t\t\t\treturn new Y.XmlElement(\"codeTree\");\n\t\t\t\tcase \"accordion\":\n\t\t\t\t\treturn new Y.XmlElement(\"accordion\");\n\t\t\t\tcase \"tabs\":\n\t\t\t\t\treturn new Y.XmlElement(\"tabs\");\n\t\t\t\tcase \"field\":\n\t\t\t\t\treturn new Y.XmlElement(\"field\");\n\t\t\t\tcase \"fieldGroup\":\n\t\t\t\t\treturn new Y.XmlElement(\"fieldGroup\");\n\t\t\t\tcase \"image\":\n\t\t\t\t\treturn new Y.XmlElement(\"image\");\n\t\t\t\tcase \"docEmbed\":\n\t\t\t\t\treturn new Y.XmlElement(\"docEmbed\");\n\t\t\t\tcase \"svgEmbed\":\n\t\t\t\t\treturn new Y.XmlElement(\"svgEmbed\");\n\t\t\t}\n\t\t});\n\n\t\tfragment.insert(0, [headerEl, metaEl, ...bodyEls]);\n\n\t\tconst headerXt = new Y.XmlText();\n\t\theaderEl.insert(0, [headerXt]);\n\t\theaderXt.insert(0, title);\n\n\t\tcontentBlocks.forEach((block, i) => fillBlock(bodyEls[i]!, block));\n\t});\n}\n\n// ── Block element builders (exported for ContentManager and SDK consumers) ────\n\nexport function buildHeadingElement(text: string, level: 1|2|3|4|5|6 = 1): Y.XmlElement {\n\tconst el = new Y.XmlElement(\"heading\");\n\tel.setAttribute(\"level\", level as any);\n\tfillTextInto(el, parseInline(text));\n\treturn el;\n}\n\nexport function buildParagraphElement(text: string): Y.XmlElement {\n\tconst el = new Y.XmlElement(\"paragraph\");\n\tfillTextInto(el, parseInline(text));\n\treturn el;\n}\n\nexport function buildBulletListElement(items: string[]): Y.XmlElement {\n\tconst el = new Y.XmlElement(\"bulletList\");\n\tconst itemEls = items.map(() => new Y.XmlElement(\"listItem\"));\n\tel.insert(0, itemEls);\n\titems.forEach((text, i) => {\n\t\tconst paraEl = new Y.XmlElement(\"paragraph\");\n\t\titemEls[i]!.insert(0, [paraEl]);\n\t\tfillTextInto(paraEl, parseInline(text));\n\t});\n\treturn el;\n}\n\nexport function buildOrderedListElement(items: string[]): Y.XmlElement {\n\tconst el = new Y.XmlElement(\"orderedList\");\n\tconst itemEls = items.map(() => new Y.XmlElement(\"listItem\"));\n\tel.insert(0, itemEls);\n\titems.forEach((text, i) => {\n\t\tconst paraEl = new Y.XmlElement(\"paragraph\");\n\t\titemEls[i]!.insert(0, [paraEl]);\n\t\tfillTextInto(paraEl, parseInline(text));\n\t});\n\treturn el;\n}\n\nexport function buildTaskListElement(\n\titems: Array<{ text: string; checked?: boolean }>,\n): Y.XmlElement {\n\tconst el = new Y.XmlElement(\"taskList\");\n\tconst itemEls = items.map(() => new Y.XmlElement(\"taskItem\"));\n\tel.insert(0, itemEls);\n\titems.forEach((item, i) => {\n\t\titemEls[i]!.setAttribute(\"checked\", (item.checked ?? false) as any);\n\t\tconst paraEl = new Y.XmlElement(\"paragraph\");\n\t\titemEls[i]!.insert(0, [paraEl]);\n\t\tfillTextInto(paraEl, parseInline(item.text));\n\t});\n\treturn el;\n}\n\nexport function buildCodeBlockElement(code: string, language?: string): Y.XmlElement {\n\tconst el = new Y.XmlElement(\"codeBlock\");\n\tif (language) el.setAttribute(\"language\", language);\n\tconst xt = new Y.XmlText();\n\tel.insert(0, [xt]);\n\txt.insert(0, code);\n\treturn el;\n}\n\nexport function buildBlockquoteElement(text: string): Y.XmlElement {\n\tconst el = new Y.XmlElement(\"blockquote\");\n\tconst paraEl = new Y.XmlElement(\"paragraph\");\n\tel.insert(0, [paraEl]);\n\tfillTextInto(paraEl, parseInline(text));\n\treturn el;\n}\n\nexport function buildHorizontalRuleElement(): Y.XmlElement {\n\treturn new Y.XmlElement(\"horizontalRule\");\n}\n\n/** Parse markdown into block Y.XmlElements (no header/meta). */\nexport function buildBlocksFromMarkdown(markdown: string): Y.XmlElement[] {\n\tconst blocks = parseBlocks(markdown);\n\treturn blocks\n\t\t.filter((b) => b.type !== \"heading\" || (b as any).level !== 1)\n\t\t.map((b) => {\n\t\t\tconst el = new Y.XmlElement(blockElName(b));\n\t\t\tfillBlock(el, b);\n\t\t\treturn el;\n\t\t});\n}\n\n// ── Block reader ──────────────────────────────────────────────────────────────\n\nexport interface DocumentBlock {\n\ttype: string;\n\tattrs: Record<string, unknown>;\n\ttext: string;\n\titems?: string[];\n\tchildren?: DocumentBlock[];\n}\n\nexport function readBlocksFromFragment(fragment: Y.XmlFragment): DocumentBlock[] {\n\tconst result: DocumentBlock[] = [];\n\t// toArray() is O(n); indexed fragment.get(i) would make this O(n²).\n\tfor (const child of fragment.toArray()) {\n\t\tif (!(child instanceof Y.XmlElement)) continue;\n\t\tconst name = child.nodeName;\n\t\tif (name === \"documentHeader\" || name === \"documentMeta\") continue;\n\t\tresult.push(_xmlElToBlock(child));\n\t}\n\treturn result;\n}\n\nfunction _xmlElToBlock(el: Y.XmlElement): DocumentBlock {\n\tconst name = el.nodeName;\n\tswitch (name) {\n\t\tcase \"heading\":\n\t\t\treturn { type: \"heading\", attrs: { level: el.getAttribute(\"level\") }, text: elementTextContent(el) };\n\t\tcase \"paragraph\":\n\t\tcase \"blockquote\":\n\t\tcase \"horizontalRule\":\n\t\t\treturn { type: name, attrs: {}, text: elementTextContent(el) };\n\t\tcase \"codeBlock\": {\n\t\t\tconst lang = el.getAttribute(\"language\");\n\t\t\treturn { type: \"codeBlock\", attrs: lang ? { language: lang } : {}, text: elementTextContent(el) };\n\t\t}\n\t\tcase \"bulletList\":\n\t\tcase \"orderedList\": {\n\t\t\tconst items: string[] = [];\n\t\t\tfor (let i = 0; i < el.length; i++) {\n\t\t\t\tconst item = el.get(i);\n\t\t\t\tif (item instanceof Y.XmlElement && item.nodeName === \"listItem\")\n\t\t\t\t\titems.push(elementTextContent(item));\n\t\t\t}\n\t\t\treturn { type: name, attrs: {}, text: \"\", items };\n\t\t}\n\t\tcase \"taskList\": {\n\t\t\tconst items: string[] = [];\n\t\t\tconst children: DocumentBlock[] = [];\n\t\t\tfor (let i = 0; i < el.length; i++) {\n\t\t\t\tconst item = el.get(i);\n\t\t\t\tif (item instanceof Y.XmlElement && item.nodeName === \"taskItem\") {\n\t\t\t\t\tconst checked = item.getAttribute(\"checked\");\n\t\t\t\t\tconst text = elementTextContent(item);\n\t\t\t\t\titems.push(text);\n\t\t\t\t\tchildren.push({\n\t\t\t\t\t\ttype: \"taskItem\",\n\t\t\t\t\t\tattrs: { checked: checked === \"true\" || (checked as unknown) === true },\n\t\t\t\t\t\ttext,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn { type: \"taskList\", attrs: {}, text: \"\", items, children };\n\t\t}\n\t\tdefault:\n\t\t\treturn { type: name, attrs: {}, text: elementTextContent(el) };\n\t}\n}\n","/**\n * ContentManager — read/write document content via markdown ↔ Y.js conversion.\n *\n * Extracted from `mcp/tools/content.ts` and `cli/commands/content.ts`.\n */\nimport * as Y from \"yjs\";\nimport type { PageMeta } from \"./DocTypes.ts\";\nimport { toPlain, patchEntry } from \"./DocUtils.ts\";\nimport { reconcileDocCover } from \"./CoverReconcile.ts\";\nimport {\n\tyjsToMarkdown,\n\tpopulateYDocFromMarkdown,\n\tparseFrontmatter,\n\tbuildHeadingElement,\n\tbuildParagraphElement,\n\tbuildBulletListElement,\n\tbuildOrderedListElement,\n\tbuildTaskListElement,\n\tbuildCodeBlockElement,\n\tbuildBlockquoteElement,\n\tbuildHorizontalRuleElement,\n\tbuildBlocksFromMarkdown,\n\treadBlocksFromFragment,\n\ttype DocumentBlock,\n} from \"./DocConverters.ts\";\nexport type { DocumentBlock } from \"./DocConverters.ts\";\nimport type { DocumentManager } from \"./DocumentManager.ts\";\n\nexport interface DocumentContent {\n\tlabel: string;\n\ttype?: string;\n\tmeta?: PageMeta;\n\ttitle: string;\n\tmarkdown: string;\n\tchildren: Array<{\n\t\tid: string;\n\t\tlabel: string;\n\t\ttype?: string;\n\t\tmeta?: PageMeta;\n\t}>;\n}\n\nexport class ContentManager {\n\tconstructor(private dm: DocumentManager) {}\n\n\t/**\n\t * Read document content as markdown.\n\t *\n\t * Returns the markdown body, tree-derived label/type/meta, and immediate\n\t * children. `title` mirrors `label` (the tree entry's display name) — it\n\t * is *not* derived from a TipTap `documentHeader`, and the markdown body\n\t * does NOT include YAML frontmatter. Callers that want frontmatter-style\n\t * round-tripping should serialise `meta`/`type` themselves on top of the\n\t * returned markdown.\n\t */\n\tasync read(docId: string): Promise<DocumentContent> {\n\t\tconst provider = await this.dm.getChildProvider(docId);\n\t\tconst fragment = provider.document.getXmlFragment(\"default\");\n\n\t\t// Get tree metadata + immediate children\n\t\tconst treeMap = this.dm.getTreeMap();\n\t\tlet label = \"Untitled\";\n\t\tlet type: string | undefined;\n\t\tlet meta: PageMeta | undefined;\n\t\tconst childrenWithOrder: Array<{\n\t\t\tid: string;\n\t\t\tlabel: string;\n\t\t\ttype?: string;\n\t\t\tmeta?: PageMeta;\n\t\t\torder: number;\n\t\t}> = [];\n\n\t\tif (treeMap) {\n\t\t\tconst raw = treeMap.get(docId);\n\t\t\tif (raw) {\n\t\t\t\tconst entry = toPlain(raw) as Record<string, unknown>;\n\t\t\t\tlabel = (entry.label as string) || label;\n\t\t\t\ttype = entry.type as string | undefined;\n\t\t\t\tmeta = entry.meta as PageMeta | undefined;\n\t\t\t}\n\t\t\t// Collect immediate children sorted by order\n\t\t\ttreeMap.forEach((rawChild: unknown, id: string) => {\n\t\t\t\tconst value = toPlain(rawChild) as Record<string, unknown>;\n\t\t\t\tif (value && value.parentId === docId) {\n\t\t\t\t\tchildrenWithOrder.push({\n\t\t\t\t\t\tid,\n\t\t\t\t\t\tlabel: (value.label as string) || \"Untitled\",\n\t\t\t\t\t\ttype: value.type as string | undefined,\n\t\t\t\t\t\tmeta: value.meta as PageMeta | undefined,\n\t\t\t\t\t\torder: (value.order as number) ?? 0,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t});\n\t\t\tchildrenWithOrder.sort((a, b) => a.order - b.order);\n\t\t}\n\n\t\tconst children = childrenWithOrder.map(({ id, label, type, meta }) => ({\n\t\t\tid,\n\t\t\tlabel,\n\t\t\ttype,\n\t\t\tmeta,\n\t\t}));\n\n\t\tconst { markdown } = yjsToMarkdown(fragment);\n\t\tconst title = label;\n\n\t\treturn { label, type, meta, title, markdown, children };\n\t}\n\n\t/**\n\t * Write markdown content to a document.\n\t * Supports optional YAML frontmatter for title and metadata.\n\t *\n\t * @param mode - \"replace\" clears existing content first (default),\n\t * \"append\" adds to the end.\n\t */\n\tasync write(\n\t\tdocId: string,\n\t\tmarkdown: string,\n\t\tmode: \"replace\" | \"append\" = \"replace\",\n\t): Promise<void> {\n\t\tconst provider = await this.dm.getChildProvider(docId);\n\t\tconst doc = provider.document;\n\t\tconst fragment = doc.getXmlFragment(\"default\");\n\n\t\t// Parse optional frontmatter\n\t\tconst { title, meta, body } = parseFrontmatter(markdown);\n\n\t\t// Update tree metadata if frontmatter provided title or meta\n\t\tif (title || Object.keys(meta).length > 0) {\n\t\t\tconst treeMap = this.dm.getTreeMap();\n\t\t\tconst rootDoc = this.dm.rootDocument;\n\t\t\tif (treeMap && rootDoc) {\n\t\t\t\tconst entry = treeMap.get(docId);\n\t\t\t\tif (entry) {\n\t\t\t\t\trootDoc.transact(() => {\n\t\t\t\t\t\tconst cur = toPlain(entry) as Record<\n\t\t\t\t\t\t\tstring,\n\t\t\t\t\t\t\tunknown\n\t\t\t\t\t\t>;\n\t\t\t\t\t\tconst patch: Record<string, unknown> = {\n\t\t\t\t\t\t\tupdatedAt: Date.now(),\n\t\t\t\t\t\t};\n\t\t\t\t\t\tif (title) patch.label = title;\n\t\t\t\t\t\tif (Object.keys(meta).length > 0) {\n\t\t\t\t\t\t\tpatch.meta = {\n\t\t\t\t\t\t\t\t...((cur.meta as Record<string, unknown>) ??\n\t\t\t\t\t\t\t\t\t{}),\n\t\t\t\t\t\t\t\t...meta,\n\t\t\t\t\t\t\t};\n\t\t\t\t\t\t}\n\t\t\t\t\t\tpatchEntry(treeMap, docId, patch);\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif (mode === \"replace\") {\n\t\t\t// Clear existing content\n\t\t\tdoc.transact(() => {\n\t\t\t\twhile (fragment.length > 0) {\n\t\t\t\t\tfragment.delete(0);\n\t\t\t\t}\n\t\t\t});\n\t\t}\n\n\t\t// Write new content\n\t\tconst contentToWrite = body || markdown;\n\t\tconst fallbackTitle = title || \"Untitled\";\n\t\tpopulateYDocFromMarkdown(fragment, contentToWrite, fallbackTitle);\n\n\t\t// Reconcile the cover against the media blocks now in the body, so a\n\t\t// write that removed (or added) the cover's image keeps the persisted\n\t\t// cover metadata honest — the editor is no longer the only path that\n\t\t// does this. Cheap no-op when the cover is already valid.\n\t\tconst reconcileTree = this.dm.getTreeMap();\n\t\tif (reconcileTree) reconcileDocCover(reconcileTree, docId, fragment);\n\t}\n\n\tprivate async _appendElements(docId: string, els: Y.XmlElement[]): Promise<void> {\n\t\tconst provider = await this.dm.getChildProvider(docId);\n\t\tconst doc = provider.document;\n\t\tconst fragment = doc.getXmlFragment(\"default\");\n\t\tdoc.transact(() => {\n\t\t\tfragment.insert(fragment.length, els);\n\t\t});\n\t}\n\n\tasync appendHeading(docId: string, text: string, opts?: { level?: 1|2|3|4|5|6 }): Promise<void> {\n\t\treturn this._appendElements(docId, [buildHeadingElement(text, opts?.level)]);\n\t}\n\n\tasync appendParagraph(docId: string, text: string): Promise<void> {\n\t\treturn this._appendElements(docId, [buildParagraphElement(text)]);\n\t}\n\n\tasync appendBulletList(docId: string, items: string[]): Promise<void> {\n\t\treturn this._appendElements(docId, [buildBulletListElement(items)]);\n\t}\n\n\tasync appendOrderedList(docId: string, items: string[]): Promise<void> {\n\t\treturn this._appendElements(docId, [buildOrderedListElement(items)]);\n\t}\n\n\tasync appendTaskList(docId: string, items: Array<{ text: string; checked?: boolean }>): Promise<void> {\n\t\treturn this._appendElements(docId, [buildTaskListElement(items)]);\n\t}\n\n\tasync appendCodeBlock(docId: string, code: string, opts?: { language?: string }): Promise<void> {\n\t\treturn this._appendElements(docId, [buildCodeBlockElement(code, opts?.language)]);\n\t}\n\n\tasync appendBlockquote(docId: string, text: string): Promise<void> {\n\t\treturn this._appendElements(docId, [buildBlockquoteElement(text)]);\n\t}\n\n\tasync appendHorizontalRule(docId: string): Promise<void> {\n\t\treturn this._appendElements(docId, [buildHorizontalRuleElement()]);\n\t}\n\n\tasync appendMarkdown(docId: string, markdown: string): Promise<void> {\n\t\treturn this._appendElements(docId, buildBlocksFromMarkdown(markdown));\n\t}\n\n\tasync getBlocks(docId: string): Promise<DocumentBlock[]> {\n\t\tconst provider = await this.dm.getChildProvider(docId);\n\t\treturn readBlocksFromFragment(provider.document.getXmlFragment(\"default\"));\n\t}\n\n\t/**\n\t * Get the raw Y.XmlFragment for a document (the 'default' fragment\n\t * that TipTap uses for document content).\n\t */\n\tasync getFragment(docId: string): Promise<Y.XmlFragment> {\n\t\tconst provider = await this.dm.getChildProvider(docId);\n\t\treturn provider.document.getXmlFragment(\"default\");\n\t}\n\n\t/**\n\t * Get the raw Y.Doc for a document (synced).\n\t */\n\tasync getDoc(docId: string): Promise<Y.Doc> {\n\t\tconst provider = await this.dm.getChildProvider(docId);\n\t\treturn provider.document;\n\t}\n}\n","/**\n * MetaManager — read/write PageMeta on tree entries.\n *\n * Extracted from `mcp/tools/meta.ts` and `cli/commands/meta.ts`.\n *\n * Optionally validates writes against a JSON-Schema-backed validator\n * (e.g. `@abraca/schema`'s `SchemaRegistry`). The validator is supplied\n * via {@link MetaManager.setSchema} as a structural value matching\n * {@link SchemaValidatorLike}; the provider package never imports\n * `@abraca/schema` directly so core stays schema-free\n * (`feedback_schema_free_core` Rule 1). When no schema is set,\n * `update`/`set` behave exactly as before (Rule 4).\n */\nimport type { PageMeta } from \"./DocTypes.ts\";\nimport { toPlain, patchEntry } from \"./DocUtils.ts\";\nimport type { DocumentManager } from \"./DocumentManager.ts\";\n\nexport interface DocumentMetaInfo {\n\tid: string;\n\tlabel: string;\n\ttype?: string;\n\tmeta: PageMeta;\n}\n\n/**\n * Structural shape of a schema validator MetaManager can consult before\n * writes. Compatible with `@abraca/schema`'s `SchemaRegistry`.\n *\n * Implementations MUST treat unknown doc-types as unconstrained\n * (return `{ ok: true }`) — Rule 4: existing-app traffic for doc-types\n * not in the validator's bundle is never rejected.\n */\nexport interface SchemaValidatorLike {\n\tvalidateMeta(\n\t\tdocType: string,\n\t\tmeta: unknown,\n\t): { ok: true; value?: unknown } | {\n\t\tok: false;\n\t\terrors: ReadonlyArray<{\n\t\t\tpath: ReadonlyArray<PropertyKey>;\n\t\t\tmessage: string;\n\t\t\tcode?: string;\n\t\t}>;\n\t};\n}\n\nexport class MetaValidationError extends Error {\n\treadonly docId: string;\n\treadonly docType: string;\n\treadonly errors: ReadonlyArray<{\n\t\tpath: ReadonlyArray<PropertyKey>;\n\t\tmessage: string;\n\t\tcode?: string;\n\t}>;\n\n\tconstructor(\n\t\tdocId: string,\n\t\tdocType: string,\n\t\terrors: ReadonlyArray<{\n\t\t\tpath: ReadonlyArray<PropertyKey>;\n\t\t\tmessage: string;\n\t\t\tcode?: string;\n\t\t}>,\n\t) {\n\t\tconst detail = errors\n\t\t\t.map((e) => `${e.path.join(\".\") || \"(root)\"}: ${e.message}`)\n\t\t\t.join(\"; \");\n\t\tsuper(\n\t\t\t`Meta validation failed for document ${docId} of type \"${docType}\": ${detail}`,\n\t\t);\n\t\tthis.name = \"MetaValidationError\";\n\t\tthis.docId = docId;\n\t\tthis.docType = docType;\n\t\tthis.errors = errors;\n\t}\n}\n\nexport class MetaManager {\n\tprivate schema: SchemaValidatorLike | null = null;\n\n\tconstructor(private dm: DocumentManager) {}\n\n\t/**\n\t * Attach (or detach with `null`) a schema validator. When set, every\n\t * `update` / `set` validates the post-write meta against the entry's\n\t * declared `type` before writing to the doc-tree. Entries without a\n\t * `type` field pass through unconditionally.\n\t */\n\tsetSchema(schema: SchemaValidatorLike | null): void {\n\t\tthis.schema = schema;\n\t}\n\n\t/** Read metadata for a document. Returns null if not found. */\n\tget(docId: string): DocumentMetaInfo | null {\n\t\tconst treeMap = this.dm.getTreeMap();\n\t\tif (!treeMap) return null;\n\n\t\tconst raw = treeMap.get(docId);\n\t\tif (!raw) return null;\n\n\t\tconst entry = toPlain(raw) as Record<string, unknown>;\n\t\treturn {\n\t\t\tid: docId,\n\t\t\tlabel: (entry.label as string) || \"Untitled\",\n\t\t\ttype: entry.type as string | undefined,\n\t\t\tmeta: (entry.meta as PageMeta) ?? {},\n\t\t};\n\t}\n\n\t/**\n\t * Merge fields into a document's metadata.\n\t * Existing keys not in the update are preserved.\n\t *\n\t * @throws {MetaValidationError} when a schema is attached and the\n\t * merged meta fails validation for the entry's declared type.\n\t */\n\tupdate(docId: string, meta: Partial<PageMeta>): void {\n\t\tconst treeMap = this.dm.getTreeMap();\n\t\tif (!treeMap) throw new Error(\"Not connected\");\n\n\t\tconst raw = treeMap.get(docId);\n\t\tif (!raw) throw new Error(`Document ${docId} not found`);\n\n\t\tconst entry = toPlain(raw) as Record<string, unknown>;\n\t\tconst mergedMeta = { ...((entry.meta as PageMeta) ?? {}), ...meta };\n\t\tthis.validateOrThrow(docId, entry, mergedMeta);\n\t\tpatchEntry(treeMap, docId, {\n\t\t\tmeta: mergedMeta,\n\t\t\tupdatedAt: Date.now(),\n\t\t});\n\t}\n\n\t/**\n\t * Replace all metadata on a document.\n\t * This overwrites the entire meta object.\n\t *\n\t * @throws {MetaValidationError} when a schema is attached and the\n\t * replacement meta fails validation for the entry's declared type.\n\t */\n\tset(docId: string, meta: PageMeta): void {\n\t\tconst treeMap = this.dm.getTreeMap();\n\t\tif (!treeMap) throw new Error(\"Not connected\");\n\n\t\tconst raw = treeMap.get(docId);\n\t\tif (!raw) throw new Error(`Document ${docId} not found`);\n\n\t\tconst entry = toPlain(raw) as Record<string, unknown>;\n\t\tthis.validateOrThrow(docId, entry, meta);\n\t\tpatchEntry(treeMap, docId, {\n\t\t\tmeta,\n\t\t\tupdatedAt: Date.now(),\n\t\t});\n\t}\n\n\t/**\n\t * Clear specific metadata keys (set them to null/undefined).\n\t */\n\tclear(docId: string, keys: string[]): void {\n\t\tconst treeMap = this.dm.getTreeMap();\n\t\tif (!treeMap) throw new Error(\"Not connected\");\n\n\t\tconst raw = treeMap.get(docId);\n\t\tif (!raw) throw new Error(`Document ${docId} not found`);\n\n\t\tconst entry = toPlain(raw) as Record<string, unknown>;\n\t\tconst existingMeta = ((entry.meta as PageMeta) ?? {}) as Record<\n\t\t\tstring,\n\t\t\tunknown\n\t\t>;\n\t\tconst updated = { ...existingMeta };\n\t\tfor (const key of keys) {\n\t\t\tdelete updated[key];\n\t\t}\n\t\tthis.validateOrThrow(docId, entry, updated as PageMeta);\n\t\tpatchEntry(treeMap, docId, {\n\t\t\tmeta: updated,\n\t\t\tupdatedAt: Date.now(),\n\t\t});\n\t}\n\n\tprivate validateOrThrow(\n\t\tdocId: string,\n\t\tentry: Record<string, unknown>,\n\t\tmeta: PageMeta,\n\t): void {\n\t\tif (!this.schema) return;\n\t\tconst docType = entry.type as string | undefined;\n\t\tif (!docType) return;\n\t\tconst result = this.schema.validateMeta(docType, meta);\n\t\tif (!result.ok) {\n\t\t\tthrow new MetaValidationError(docId, docType, result.errors);\n\t\t}\n\t}\n}\n","/**\n * DocumentManager — high-level ORM entry point for Abracadabra CRDT documents.\n *\n * Consolidates the shared connection lifecycle, authentication, space discovery,\n * provider caching, and Y.Map access patterns that were previously duplicated\n * across `mcp/src/server.ts` and `cli/src/connection.ts`.\n *\n * Usage:\n * ```ts\n * const dm = new DocumentManager({\n * url: 'https://my-server.example.com',\n * name: 'My Agent',\n * })\n * // Authenticate before connecting (consumer handles crypto):\n * await dm.client.loginWithKey(publicKey, signFn)\n * await dm.connect()\n *\n * // Use the ORM:\n * const docs = dm.tree.childrenOf(null) // root-level docs\n * const content = await dm.content.read(docId) // markdown + children\n * dm.meta.update(docId, { color: '#ff0000' }) // update metadata\n * ```\n */\nimport * as Y from \"yjs\";\nimport { AbracadabraProvider } from \"./AbracadabraProvider.ts\";\nimport { AbracadabraClient } from \"./AbracadabraClient.ts\";\nimport type { AbracadabraWS } from \"./AbracadabraWS.ts\";\nimport type { ServerInfo, DocumentMeta } from \"./types.ts\";\nimport { Kind, SERVER_ROOT_ID } from \"./types.ts\";\nimport { TreeManager } from \"./TreeManager.ts\";\nimport { ContentManager } from \"./ContentManager.ts\";\nimport { MetaManager } from \"./MetaManager.ts\";\nimport { waitForSync } from \"./DocUtils.ts\";\nimport type { TreeEntry, PageMeta } from \"./DocTypes.ts\";\nimport {\n\tprojectTreeEntry,\n\tTypedDocTypeMismatchError,\n\ttype SchemaRegistryLike,\n\ttype TypedDocsClient,\n} from \"./SchemaTypes.ts\";\n\nexport interface DocumentManagerConfig {\n\t/** Server base URL (http or https). */\n\turl: string;\n\t/** Display name for awareness (cursor labels, presence). */\n\tname?: string;\n\t/** Cursor / awareness color. */\n\tcolor?: string;\n\t/** Invite code for first-time registration. */\n\tinviteCode?: string;\n\t/** Suppress stderr logging. */\n\tquiet?: boolean;\n\t/** Disable IndexedDB offline persistence. */\n\tdisableOfflineStore?: boolean;\n\t/** Custom fetch for Node.js environments. */\n\tfetch?: typeof globalThis.fetch;\n\t/**\n\t * Pre-configured AbracadabraClient instance.\n\t * When provided, the `url` and `fetch` fields are ignored — the client's\n\t * configuration is used instead. This is useful when the consumer has\n\t * already authenticated or configured the client externally.\n\t */\n\tclient?: AbracadabraClient;\n\t/**\n\t * Shared WebSocket connection. Required in Node.js environments — pass an\n\t * AbracadabraWS constructed with WebSocketPolyfill set to the `ws` package.\n\t * When omitted, each provider creates its own connection from client.wsUrl.\n\t * The caller owns this instance and must destroy it after dm.destroy().\n\t */\n\twebsocketProvider?: AbracadabraWS;\n\t/**\n\t * Known root document ID. When provided, connect() skips server discovery\n\t * and connects directly to this document. Useful in tests or CLIs where\n\t * the entry-point docId is already known.\n\t */\n\trootDocId?: string;\n\t/**\n\t * TreeManager's in-memory parent→children index. When `true` (the\n\t * default), tree WALKS resolve against a lazily-rebuilt adjacency index\n\t * (O(k) per lookup, O(result) traversal), kept fresh by an `observeDeep`\n\t * dirty bit and rebuilt at most once per mutation batch; `childrenOfPage()`\n\t * becomes usable with stable (order,id) sibling ordering. Set `false` to\n\t * force the legacy whole-map scan (O(n) per call, O(n²) recursive) — only\n\t * needed to reproduce the exact historical order-only sibling ordering.\n\t * Benchmarked at ~700× on deep walks. Index affects WALK reads only;\n\t * `readEntries`/`get` keep raw parentId either way. Lazy: no index or\n\t * observer is bound until the first walk read.\n\t */\n\ttreeIndex?: boolean;\n}\n\ninterface CachedProvider {\n\tprovider: AbracadabraProvider;\n\tlastAccessed: number;\n}\n\nexport class DocumentManager {\n\treadonly client: AbracadabraClient;\n\n\t/** Tree CRUD operations. */\n\treadonly tree: TreeManager;\n\t/** Document content read/write. */\n\treadonly content: ContentManager;\n\t/** Document metadata read/write. */\n\treadonly meta: MetaManager;\n\n\tprivate _config: DocumentManagerConfig;\n\tprivate _serverInfo: ServerInfo | null = null;\n\tprivate _rootDocId: string | null = null;\n\tprivate _spaces: DocumentMeta[] = [];\n\tprivate _rootDoc: Y.Doc | null = null;\n\tprivate _rootProvider: AbracadabraProvider | null = null;\n\tprivate childCache = new Map<string, CachedProvider>();\n\n\tconstructor(config: DocumentManagerConfig) {\n\t\tthis._config = config;\n\t\tthis.client =\n\t\t\tconfig.client ??\n\t\t\tnew AbracadabraClient({\n\t\t\t\turl: config.url,\n\t\t\t\tpersistAuth: false,\n\t\t\t\tfetch: config.fetch,\n\t\t\t});\n\n\t\tthis.tree = new TreeManager(this);\n\t\tthis.content = new ContentManager(this);\n\t\tthis.meta = new MetaManager(this);\n\t}\n\n\t/**\n\t * Bind a schema registry to a typed accessor surface. The returned\n\t * client offers `.get(type, id)` with the registry's meta types\n\t * inferred at the call site, removing the need to pass `schema`\n\t * to every lookup. The provider remains schema-free at runtime —\n\t * `schema` is only used to drive type inference (see\n\t * `SchemaRegistryLike` for the structural witness).\n\t *\n\t * @example\n\t * const docs = dm.docs(kanbanSchema);\n\t * const board = docs.get(\"kanban\", id);\n\t * if (board) console.log(board.meta.kanbanColumnWidth); // typed\n\t */\n\tdocs<TMap extends Record<string, unknown>>(\n\t\t_schema: SchemaRegistryLike<TMap>,\n\t): TypedDocsClient<TMap> {\n\t\tconst tree = this.tree;\n\t\tconst meta = this.meta;\n\t\tconst expectType = <N extends keyof TMap & string>(\n\t\t\texpected: N,\n\t\t\tid: string,\n\t\t): void => {\n\t\t\tconst entry = tree.get(id);\n\t\t\tconst actual = entry?.type;\n\t\t\tif (actual !== expected) {\n\t\t\t\tthrow new TypedDocTypeMismatchError(id, expected, actual);\n\t\t\t}\n\t\t};\n\t\treturn {\n\t\t\tget: <N extends keyof TMap & string>(expectedType: N, id: string) =>\n\t\t\t\tprojectTreeEntry<TMap, N>(tree.get(id), expectedType),\n\t\t\tgetEntry: (id: string) => tree.get(id),\n\t\t\tnarrow: <N extends keyof TMap & string>(\n\t\t\t\texpectedType: N,\n\t\t\t\tentry: TreeEntry | null | undefined,\n\t\t\t) => projectTreeEntry<TMap, N>(entry ?? null, expectedType),\n\t\t\tupdate: <N extends keyof TMap & string>(\n\t\t\t\texpectedType: N,\n\t\t\t\tid: string,\n\t\t\t\tpatch: Partial<TMap[N]>,\n\t\t\t) => {\n\t\t\t\texpectType(expectedType, id);\n\t\t\t\tmeta.update(id, patch as Partial<PageMeta>);\n\t\t\t},\n\t\t\tset: <N extends keyof TMap & string>(\n\t\t\t\texpectedType: N,\n\t\t\t\tid: string,\n\t\t\t\tvalue: TMap[N],\n\t\t\t) => {\n\t\t\t\texpectType(expectedType, id);\n\t\t\t\tmeta.set(id, value as unknown as PageMeta);\n\t\t\t},\n\t\t\tclear: <N extends keyof TMap & string>(\n\t\t\t\texpectedType: N,\n\t\t\t\tid: string,\n\t\t\t\tkeys: ReadonlyArray<keyof TMap[N] & string>,\n\t\t\t) => {\n\t\t\t\texpectType(expectedType, id);\n\t\t\t\tmeta.clear(id, keys as ReadonlyArray<string> as string[]);\n\t\t\t},\n\t\t};\n\t}\n\n\t// ── Accessors ─────────────────────────────────────────────────────────────\n\n\tget displayName(): string {\n\t\treturn this._config.name || \"DocumentManager\";\n\t}\n\n\tget displayColor(): string {\n\t\treturn this._config.color || \"hsl(45, 90%, 55%)\";\n\t}\n\n\tget serverInfo(): ServerInfo | null {\n\t\treturn this._serverInfo;\n\t}\n\n\tget rootDocId(): string | null {\n\t\treturn this._rootDocId;\n\t}\n\n\t/**\n\t * Whether the TreeManager in-memory index is enabled.\n\t * On by default — see {@link DocumentManagerConfig.treeIndex}.\n\t */\n\tget treeIndexEnabled(): boolean {\n\t\treturn this._config.treeIndex ?? true;\n\t}\n\n\tget rootDocument(): Y.Doc | null {\n\t\treturn this._rootDoc;\n\t}\n\n\tget rootProvider(): AbracadabraProvider | null {\n\t\treturn this._rootProvider;\n\t}\n\n\t/**\n\t * Spaces visible to the caller — direct children of the server root with\n\t * `kind === \"space\"`. Populated by {@link connect}.\n\t */\n\tget spaces(): DocumentMeta[] {\n\t\treturn this._spaces;\n\t}\n\n\tget isConnected(): boolean {\n\t\treturn this._rootProvider?.isConnected ?? false;\n\t}\n\n\t// ── Y.Map access ──────────────────────────────────────────────────────────\n\n\t/** Get the root doc-tree Y.Map. */\n\tgetTreeMap(): Y.Map<any> | null {\n\t\treturn this._rootDoc?.getMap(\"doc-tree\") ?? null;\n\t}\n\n\t/** Get the root doc-trash Y.Map. */\n\tgetTrashMap(): Y.Map<any> | null {\n\t\treturn this._rootDoc?.getMap(\"doc-trash\") ?? null;\n\t}\n\n\t/** Get the root space-plugins Y.Map. */\n\tgetPluginsMap(): Y.Map<any> | null {\n\t\treturn this._rootDoc?.getMap(\"space-plugins\") ?? null;\n\t}\n\n\t// ── Lifecycle ─────────────────────────────────────────────────────────────\n\n\t/**\n\t * Connect to the server: discover the entry-point document, sync the root\n\t * Y.Doc, and set awareness.\n\t *\n\t * **Authentication must be done before calling connect().**\n\t * Call `dm.client.loginWithKey(publicKey, signFn)` or `dm.client.login()`\n\t * to authenticate first.\n\t *\n\t * When `rootDocId` is set in the config, server discovery is skipped and\n\t * the manager connects directly to that document.\n\t */\n\tasync connect(): Promise<void> {\n\t\t// Step 1: Discover server info (used for awareness colour, name, etc.).\n\t\tthis._serverInfo = await this.client.serverInfo();\n\n\t\t// Step 2: Pick an entry-point doc.\n\t\t//\n\t\t// In the new model the dashboard's notion of \"open the hub\" maps to\n\t\t// \"open the first Space\". A Space is a top-level doc with\n\t\t// `kind === \"space\"`. If the caller pinned a `rootDocId`, honour it\n\t\t// directly — useful in tests/CLIs where the entry doc is known.\n\t\tlet initialDocId: string | null = this._config.rootDocId ?? null;\n\n\t\tif (!initialDocId) {\n\t\t\tconst roots = await this.client.listChildren();\n\t\t\tthis._spaces = roots.filter((d) => d.kind === Kind.Space);\n\t\t\tconst first = this._spaces[0] ?? roots[0];\n\t\t\tif (first) {\n\t\t\t\tinitialDocId = first.id;\n\t\t\t\tthis.log(`Entry document: ${first.label ?? first.id} (${first.id})`);\n\t\t\t}\n\t\t}\n\n\t\tif (!initialDocId) {\n\t\t\tthrow new Error(\n\t\t\t\t`No entry point found: server has no top-level documents under ${SERVER_ROOT_ID}. Create a Space first.`,\n\t\t\t);\n\t\t}\n\n\t\tthis._rootDocId = initialDocId;\n\n\t\t// Step 3: Connect provider and sync\n\t\tawait this._connectToRoot(initialDocId);\n\t\tthis.log(\"Connected and synced\");\n\t}\n\n\t/** Switch active space to a different root document. */\n\tasync switchSpace(docId: string): Promise<void> {\n\t\t// Destroy existing child providers\n\t\tfor (const [, cached] of this.childCache) {\n\t\t\tcached.provider.destroy();\n\t\t}\n\t\tthis.childCache.clear();\n\n\t\t// Destroy current root provider (not the wsp — caller owns it)\n\t\tif (this._rootProvider) {\n\t\t\tthis._rootProvider.destroy();\n\t\t\tthis._rootProvider = null;\n\t\t}\n\t\tthis._rootDoc = null;\n\n\t\tawait this._connectToRoot(docId);\n\t\tthis._rootDocId = docId;\n\t\tthis.log(`Switched to space ${docId}`);\n\t}\n\n\t/** Create, sync, and set awareness on a root provider for the given docId. */\n\tprivate async _connectToRoot(docId: string): Promise<void> {\n\t\tconst doc = new Y.Doc({ guid: docId });\n\t\tconst wsp = this._config.websocketProvider;\n\t\tconst provider = new AbracadabraProvider({\n\t\t\tname: docId,\n\t\t\tdocument: doc,\n\t\t\tclient: this.client,\n\t\t\tdisableOfflineStore: this._config.disableOfflineStore ?? true,\n\t\t\tsubdocLoading: \"lazy\",\n\t\t\t...(wsp ? { websocketProvider: wsp } : {}),\n\t\t});\n\n\t\t// When a shared websocketProvider is supplied, manageSocket=false so\n\t\t// the base constructor does NOT call attach(). We must do it ourselves.\n\t\tif (wsp) provider.attach();\n\n\t\tawait waitForSync(provider);\n\n\t\tprovider.awareness?.setLocalStateField(\"user\", {\n\t\t\tname: this.displayName,\n\t\t\tcolor: this.displayColor,\n\t\t});\n\t\tprovider.awareness?.setLocalStateField(\"status\", null);\n\n\t\tthis._rootDoc = doc;\n\t\tthis._rootProvider = provider;\n\t}\n\n\t/** Graceful shutdown. */\n\tasync destroy(): Promise<void> {\n\t\tfor (const [, cached] of this.childCache) {\n\t\t\tcached.provider.destroy();\n\t\t}\n\t\tthis.childCache.clear();\n\n\t\tif (this._rootProvider) {\n\t\t\tthis._rootProvider.awareness?.setLocalStateField(\n\t\t\t\t\"status\",\n\t\t\t\tnull,\n\t\t\t);\n\t\t\tthis._rootProvider.destroy();\n\t\t\tthis._rootProvider = null;\n\t\t}\n\t\tthis._rootDoc = null;\n\n\t\tthis.log(\"Disconnected\");\n\t}\n\n\t// ── Provider cache ────────────────────────────────────────────────────────\n\n\t/** Get or create a child provider for a document (synced). */\n\tasync getChildProvider(docId: string): Promise<AbracadabraProvider> {\n\t\tconst cached = this.childCache.get(docId);\n\t\tif (cached) {\n\t\t\tcached.lastAccessed = Date.now();\n\t\t\treturn cached.provider;\n\t\t}\n\n\t\tif (!this._rootProvider) {\n\t\t\tthrow new Error(\"Not connected. Call connect() first.\");\n\t\t}\n\n\t\tconst childProvider = await this._rootProvider.loadChild(docId);\n\t\tawait waitForSync(childProvider);\n\n\t\tchildProvider.awareness?.setLocalStateField(\"user\", {\n\t\t\tname: this.displayName,\n\t\t\tcolor: this.displayColor,\n\t\t});\n\n\t\tthis.childCache.set(docId, {\n\t\t\tprovider: childProvider,\n\t\t\tlastAccessed: Date.now(),\n\t\t});\n\n\t\treturn childProvider;\n\t}\n\n\t// ── Internal ──────────────────────────────────────────────────────────────\n\n\tprivate log(msg: string): void {\n\t\tif (!this._config.quiet) {\n\t\t\tconsole.error(`[abracadabra] ${msg}`);\n\t\t}\n\t}\n}\n","/**\n * PerfCounters — opt-in resource accounting for the provider.\n *\n * WHY THIS EXISTS\n *\n * The provider's expensive behaviour is idle behaviour: timers that fire and\n * frames that go out when nobody is doing anything. That cost is invisible to\n * ordinary profiling of a busy app and invisible to the test suite, so it grew\n * unnoticed. This module makes it countable, so a budget can be asserted\n * instead of argued about.\n *\n * DESIGN CONSTRAINTS\n *\n * 1. **Inert until installed.** Importing this module patches nothing and\n * costs nothing. Only `installPerfCounters()` wraps anything, and\n * `uninstall()` restores the exact original references. Nothing in the\n * production path ever calls in here.\n *\n * 2. **Attribute by stack, don't instrument by hand.** Timers are the unit of\n * battery cost, and the ones that matter are created inside dependencies\n * (`y-protocols`' Awareness starts a 3 s interval per instance). Recording\n * a creation stack for every timer means we count the real cost wherever it\n * comes from — including timers added later by code that never heard of\n * this module — instead of sprinkling counter calls through the provider\n * and hoping they stay in sync with reality.\n *\n * 3. **No global socket patching.** In Node the provider runs on the `ws`\n * package, not `globalThis.WebSocket`, so a global patch would silently\n * measure nothing. `instrumentSocket()` takes an explicit AbracadabraWS\n * instead — the same approach `_perf_client.mts` already uses.\n *\n * Not covered here on purpose: `Y.encodeStateAsUpdate` cost. It cannot be\n * patched through an ES import binding, and the perf harness measures it\n * directly by calling it, which is more accurate anyway.\n */\n\n// ── Types ────────────────────────────────────────────────────────────────────\n\n/** One group of timers sharing an origin and a delay. */\nexport interface TimerGroup {\n\t/** Best-effort source attribution, e.g. \"y-protocols/awareness.js\". */\n\torigin: string;\n\t/** The delay the timer was created with, in ms. */\n\tdelayMs: number;\n\t/** Timers of this shape created since the last reset. */\n\tcreated: number;\n\t/** Timers of this shape still live right now. */\n\tlive: number;\n\t/** Callback invocations of this shape since the last reset. */\n\tfired: number;\n}\n\nexport interface PerfSnapshot {\n\t/** Wall-clock ms since the last `reset()` (or install). */\n\telapsedMs: number;\n\ttimers: {\n\t\tintervalsCreated: number;\n\t\tintervalsLive: number;\n\t\ttimeoutsCreated: number;\n\t\ttimeoutsLive: number;\n\t\t/** Every callback invocation from a wrapped timer. */\n\t\tfired: number;\n\t\t/** Fired per second over the elapsed window — the battery number. */\n\t\tfiredPerSecond: number;\n\t\t/** Grouped by origin + delay, largest `live` first. */\n\t\tgroups: TimerGroup[];\n\t};\n\tanimationFrames: {\n\t\trequested: number;\n\t\tfired: number;\n\t};\n\tawareness: {\n\t\t/**\n\t\t * Live `y-protocols` Awareness instances, derived from their\n\t\t * characteristic heartbeat interval (outdatedTimeout / 10 = 3000 ms\n\t\t * created inside awareness.js). This is the count the whole idle-cost\n\t\t * ledger hinges on.\n\t\t */\n\t\tliveInstances: number;\n\t\t/** Heartbeat callback invocations since the last reset. */\n\t\theartbeatFires: number;\n\t};\n\tindexedDb: {\n\t\ttransactions: number;\n\t\t/** Transactions by object-store name. */\n\t\tbyStore: Record<string, number>;\n\t\tdatabasesOpened: number;\n\t};\n\tsockets: {\n\t\tframesSent: number;\n\t\tbytesSent: number;\n\t\tframesReceived: number;\n\t\tbytesReceived: number;\n\t\t/** Frames sent grouped by the wire message type byte, when readable. */\n\t\tsentByType: Record<string, number>;\n\t};\n}\n\n/** An AbracadabraWS-shaped object. Kept structural to avoid an import cycle. */\ninterface SocketLike {\n\tsend(message: unknown): void;\n\ton(event: string, handler: (...args: any[]) => void): unknown;\n\toff(event: string, handler: (...args: any[]) => void): unknown;\n}\n\n// ── Module state ─────────────────────────────────────────────────────────────\n\ninterface TimerRecord {\n\torigin: string;\n\tdelayMs: number;\n\tkind: \"interval\" | \"timeout\";\n}\n\nlet installed = false;\nlet startedAt = 0;\n\nconst liveTimers = new Map<unknown, TimerRecord>();\nconst groupCreated = new Map<string, number>();\nconst groupFired = new Map<string, number>();\n\nlet intervalsCreated = 0;\nlet timeoutsCreated = 0;\nlet timersFired = 0;\nlet rafRequested = 0;\nlet rafFired = 0;\n\nlet idbTransactions = 0;\nlet idbDatabasesOpened = 0;\nconst idbByStore = new Map<string, number>();\n\nlet framesSent = 0;\nlet bytesSent = 0;\nlet framesReceived = 0;\nlet bytesReceived = 0;\nconst sentByType = new Map<string, number>();\n\n// Saved originals, restored verbatim by uninstall().\nlet origSetInterval: typeof setInterval | null = null;\nlet origClearInterval: typeof clearInterval | null = null;\nlet origSetTimeout: typeof setTimeout | null = null;\nlet origClearTimeout: typeof clearTimeout | null = null;\nlet origRaf: ((cb: FrameRequestCallback) => number) | null = null;\nlet origIdbTransaction: IDBDatabase[\"transaction\"] | null = null;\nlet origIdbOpen: IDBFactory[\"open\"] | null = null;\n\nconst socketRestores: Array<() => void> = [];\n\n/** The heartbeat every y-protocols Awareness instance starts: outdatedTimeout / 10. */\nconst AWARENESS_HEARTBEAT_MS = 3000;\n\n// ── Stack attribution ────────────────────────────────────────────────────────\n\n/**\n * Best-effort \"who created this timer\". Walks the stack past this module and\n * past the Node/browser internals, and reports the first frame that looks like\n * real code. Deliberately coarse: a file name is enough to tell an Awareness\n * heartbeat apart from a reconnect backoff, and anything finer would be noise.\n */\nfunction captureOrigin(): string {\n\tconst stack = new Error().stack;\n\tif (!stack) return \"unknown\";\n\tconst lines = stack.split(\"\\n\").slice(1);\n\tfor (const line of lines) {\n\t\tif (line.includes(\"PerfCounters\")) continue;\n\t\tif (line.includes(\"node:internal\")) continue;\n\t\t// node_modules paths are the interesting ones (y-protocols, ws, …) —\n\t\t// keep the package-relative tail so the label stays stable across\n\t\t// machines and pnpm's content-addressed store layout.\n\t\tconst nm = line.match(/node_modules\\/(?:\\.pnpm\\/[^/]+\\/node_modules\\/)?(.+?):\\d+:\\d+/);\n\t\tif (nm?.[1]) return nm[1];\n\t\tconst src = line.match(/([^/\\\\()]+\\.(?:ts|mts|js|mjs)):\\d+:\\d+/);\n\t\tif (src?.[1]) return src[1];\n\t}\n\treturn \"unknown\";\n}\n\nfunction groupKey(origin: string, delayMs: number): string {\n\treturn `${origin}@${delayMs}`;\n}\n\nfunction bump(map: Map<string, number>, key: string, by = 1): void {\n\tmap.set(key, (map.get(key) ?? 0) + by);\n}\n\n// ── Install / uninstall ──────────────────────────────────────────────────────\n\n/**\n * Begin counting. Idempotent — a second call is a no-op rather than a\n * double-wrap, which would double every number and be very hard to notice.\n */\nexport function installPerfCounters(): void {\n\tif (installed) return;\n\tinstalled = true;\n\tstartedAt = Date.now();\n\n\tconst g = globalThis as any;\n\n\t// ── timers ──\n\torigSetInterval = g.setInterval;\n\torigClearInterval = g.clearInterval;\n\torigSetTimeout = g.setTimeout;\n\torigClearTimeout = g.clearTimeout;\n\n\tg.setInterval = function patchedSetInterval(handler: any, delay?: number, ...args: any[]) {\n\t\tconst origin = captureOrigin();\n\t\tconst delayMs = delay ?? 0;\n\t\tconst key = groupKey(origin, delayMs);\n\t\tconst wrapped =\n\t\t\ttypeof handler === \"function\"\n\t\t\t\t? (...cbArgs: any[]) => {\n\t\t\t\t\t\ttimersFired++;\n\t\t\t\t\t\tbump(groupFired, key);\n\t\t\t\t\t\treturn handler(...cbArgs);\n\t\t\t\t\t}\n\t\t\t\t: handler;\n\t\tconst id = origSetInterval!.call(g, wrapped, delay as any, ...args);\n\t\tintervalsCreated++;\n\t\tbump(groupCreated, key);\n\t\tliveTimers.set(id, { origin, delayMs, kind: \"interval\" });\n\t\treturn id;\n\t};\n\n\tg.clearInterval = function patchedClearInterval(id: any) {\n\t\tliveTimers.delete(id);\n\t\treturn origClearInterval!.call(g, id);\n\t};\n\n\tg.setTimeout = function patchedSetTimeout(handler: any, delay?: number, ...args: any[]) {\n\t\tconst origin = captureOrigin();\n\t\tconst delayMs = delay ?? 0;\n\t\tconst key = groupKey(origin, delayMs);\n\t\tlet id: any;\n\t\tconst wrapped =\n\t\t\ttypeof handler === \"function\"\n\t\t\t\t? (...cbArgs: any[]) => {\n\t\t\t\t\t\ttimersFired++;\n\t\t\t\t\t\tbump(groupFired, key);\n\t\t\t\t\t\t// A timeout is done once it fires; stop counting it as live.\n\t\t\t\t\t\tliveTimers.delete(id);\n\t\t\t\t\t\treturn handler(...cbArgs);\n\t\t\t\t\t}\n\t\t\t\t: handler;\n\t\tid = origSetTimeout!.call(g, wrapped, delay as any, ...args);\n\t\ttimeoutsCreated++;\n\t\tbump(groupCreated, key);\n\t\tliveTimers.set(id, { origin, delayMs, kind: \"timeout\" });\n\t\treturn id;\n\t};\n\n\tg.clearTimeout = function patchedClearTimeout(id: any) {\n\t\tliveTimers.delete(id);\n\t\treturn origClearTimeout!.call(g, id);\n\t};\n\n\t// ── animation frames (browser only) ──\n\tif (typeof g.requestAnimationFrame === \"function\") {\n\t\torigRaf = g.requestAnimationFrame;\n\t\tg.requestAnimationFrame = function patchedRaf(cb: FrameRequestCallback) {\n\t\t\trafRequested++;\n\t\t\treturn origRaf!.call(g, (t: number) => {\n\t\t\t\trafFired++;\n\t\t\t\treturn cb(t);\n\t\t\t});\n\t\t};\n\t}\n\n\t// ── IndexedDB ──\n\tif (typeof g.IDBDatabase === \"function\") {\n\t\torigIdbTransaction = g.IDBDatabase.prototype.transaction;\n\t\tg.IDBDatabase.prototype.transaction = function patchedTransaction(\n\t\t\tthis: IDBDatabase,\n\t\t\tstoreNames: string | string[],\n\t\t\t...rest: any[]\n\t\t) {\n\t\t\tidbTransactions++;\n\t\t\tconst names = Array.isArray(storeNames) ? storeNames : [storeNames];\n\t\t\tfor (const n of names) bump(idbByStore, String(n));\n\t\t\treturn (origIdbTransaction as any).call(this, storeNames, ...rest);\n\t\t};\n\t}\n\tif (g.indexedDB && typeof g.indexedDB.open === \"function\") {\n\t\torigIdbOpen = g.indexedDB.open.bind(g.indexedDB);\n\t\tg.indexedDB.open = function patchedOpen(...args: any[]) {\n\t\t\tidbDatabasesOpened++;\n\t\t\treturn (origIdbOpen as any)(...args);\n\t\t};\n\t}\n}\n\n/** Restore every patched global. Safe to call when not installed. */\nexport function uninstall(): void {\n\tif (!installed) return;\n\tconst g = globalThis as any;\n\n\tif (origSetInterval) g.setInterval = origSetInterval;\n\tif (origClearInterval) g.clearInterval = origClearInterval;\n\tif (origSetTimeout) g.setTimeout = origSetTimeout;\n\tif (origClearTimeout) g.clearTimeout = origClearTimeout;\n\tif (origRaf) g.requestAnimationFrame = origRaf;\n\tif (origIdbTransaction && typeof g.IDBDatabase === \"function\") {\n\t\tg.IDBDatabase.prototype.transaction = origIdbTransaction;\n\t}\n\tif (origIdbOpen && g.indexedDB) g.indexedDB.open = origIdbOpen;\n\n\tfor (const restore of socketRestores.splice(0)) restore();\n\n\torigSetInterval = null;\n\torigClearInterval = null;\n\torigSetTimeout = null;\n\torigClearTimeout = null;\n\torigRaf = null;\n\torigIdbTransaction = null;\n\torigIdbOpen = null;\n\n\tinstalled = false;\n\treset();\n}\n\n/** Zero every counter. Live-timer bookkeeping is preserved — it is a census. */\nexport function reset(): void {\n\tstartedAt = Date.now();\n\tgroupCreated.clear();\n\tgroupFired.clear();\n\tintervalsCreated = 0;\n\ttimeoutsCreated = 0;\n\ttimersFired = 0;\n\trafRequested = 0;\n\trafFired = 0;\n\tidbTransactions = 0;\n\tidbDatabasesOpened = 0;\n\tidbByStore.clear();\n\tframesSent = 0;\n\tbytesSent = 0;\n\tframesReceived = 0;\n\tbytesReceived = 0;\n\tsentByType.clear();\n}\n\n// ── Socket instrumentation ───────────────────────────────────────────────────\n\n/**\n * Count frames on one AbracadabraWS. Returns a restore function; the restore is\n * also run by `uninstall()`.\n *\n * Wrapping the instance (rather than a global) is deliberate: in Node the\n * provider runs on the `ws` package, so patching `globalThis.WebSocket` would\n * silently measure nothing at all.\n */\nexport function instrumentSocket(socket: SocketLike): () => void {\n\tconst originalSend = socket.send.bind(socket);\n\n\t(socket as any).send = (message: any) => {\n\t\tframesSent++;\n\t\tconst bytes = byteLength(message);\n\t\tbytesSent += bytes;\n\t\tconst type = readMessageType(message);\n\t\tif (type !== null) bump(sentByType, type);\n\t\treturn originalSend(message);\n\t};\n\n\tconst onMessage = (payload: any) => {\n\t\tframesReceived++;\n\t\tbytesReceived += byteLength(payload?.event?.data ?? payload?.data ?? payload);\n\t};\n\tsocket.on(\"message\", onMessage);\n\n\tconst restore = () => {\n\t\t(socket as any).send = originalSend;\n\t\ttry {\n\t\t\tsocket.off(\"message\", onMessage);\n\t\t} catch {\n\t\t\t/* already torn down */\n\t\t}\n\t};\n\tsocketRestores.push(restore);\n\treturn restore;\n}\n\nfunction byteLength(value: unknown): number {\n\tif (!value) return 0;\n\tif (value instanceof Uint8Array) return value.byteLength;\n\tif (value instanceof ArrayBuffer) return value.byteLength;\n\tif (typeof value === \"string\") return value.length;\n\t// Outgoing frames are MessageSender wrappers; unwrap the encoded payload.\n\tconst encoded = (value as any)?.toUint8Array?.() ?? (value as any)?.message;\n\tif (encoded instanceof Uint8Array) return encoded.byteLength;\n\treturn 0;\n}\n\n/**\n * The Hocuspocus V2 frame puts a varstring document name first, then the\n * message type. We only need a stable label, so report the type byte as-is\n * rather than duplicating the wire decoder here.\n */\nfunction readMessageType(message: unknown): string | null {\n\tconst encoded =\n\t\t(message as any)?.toUint8Array?.() ??\n\t\t(message as any)?.message ??\n\t\t(message instanceof Uint8Array ? message : null);\n\tif (!(encoded instanceof Uint8Array) || encoded.length === 0) return null;\n\t// varstring length prefix, then that many bytes of name, then the type.\n\tlet offset = 0;\n\tlet nameLen = 0;\n\tlet shift = 0;\n\twhile (offset < encoded.length) {\n\t\tconst byte = encoded[offset++]!;\n\t\tnameLen |= (byte & 0x7f) << shift;\n\t\tif ((byte & 0x80) === 0) break;\n\t\tshift += 7;\n\t}\n\tconst typeIndex = offset + nameLen;\n\tif (typeIndex >= encoded.length) return null;\n\treturn `type:${encoded[typeIndex]}`;\n}\n\n// ── Reading the counters ─────────────────────────────────────────────────────\n\nexport function snapshot(): PerfSnapshot {\n\tconst elapsedMs = Math.max(1, Date.now() - startedAt);\n\n\tconst liveByKey = new Map<string, number>();\n\tlet intervalsLive = 0;\n\tlet timeoutsLive = 0;\n\tlet awarenessLive = 0;\n\n\tfor (const rec of liveTimers.values()) {\n\t\tconst key = groupKey(rec.origin, rec.delayMs);\n\t\tbump(liveByKey, key);\n\t\tif (rec.kind === \"interval\") {\n\t\t\tintervalsLive++;\n\t\t\tif (isAwarenessHeartbeat(rec)) awarenessLive++;\n\t\t} else {\n\t\t\ttimeoutsLive++;\n\t\t}\n\t}\n\n\tconst keys = new Set<string>([\n\t\t...groupCreated.keys(),\n\t\t...groupFired.keys(),\n\t\t...liveByKey.keys(),\n\t]);\n\tconst groups: TimerGroup[] = [...keys]\n\t\t.map((key) => {\n\t\t\tconst at = key.lastIndexOf(\"@\");\n\t\t\treturn {\n\t\t\t\torigin: key.slice(0, at),\n\t\t\t\tdelayMs: Number(key.slice(at + 1)),\n\t\t\t\tcreated: groupCreated.get(key) ?? 0,\n\t\t\t\tlive: liveByKey.get(key) ?? 0,\n\t\t\t\tfired: groupFired.get(key) ?? 0,\n\t\t\t};\n\t\t})\n\t\t.sort((a, b) => b.live - a.live || b.fired - a.fired);\n\n\tlet heartbeatFires = 0;\n\tfor (const group of groups) {\n\t\tif (group.delayMs === AWARENESS_HEARTBEAT_MS && isAwarenessOrigin(group.origin)) {\n\t\t\theartbeatFires += group.fired;\n\t\t}\n\t}\n\n\treturn {\n\t\telapsedMs,\n\t\ttimers: {\n\t\t\tintervalsCreated,\n\t\t\tintervalsLive,\n\t\t\ttimeoutsCreated,\n\t\t\ttimeoutsLive,\n\t\t\tfired: timersFired,\n\t\t\tfiredPerSecond: Number(((timersFired / elapsedMs) * 1000).toFixed(2)),\n\t\t\tgroups,\n\t\t},\n\t\tanimationFrames: { requested: rafRequested, fired: rafFired },\n\t\tawareness: { liveInstances: awarenessLive, heartbeatFires },\n\t\tindexedDb: {\n\t\t\ttransactions: idbTransactions,\n\t\t\tbyStore: Object.fromEntries(idbByStore),\n\t\t\tdatabasesOpened: idbDatabasesOpened,\n\t\t},\n\t\tsockets: {\n\t\t\tframesSent,\n\t\t\tbytesSent,\n\t\t\tframesReceived,\n\t\t\tbytesReceived,\n\t\t\tsentByType: Object.fromEntries(sentByType),\n\t\t},\n\t};\n}\n\nfunction isAwarenessOrigin(origin: string): boolean {\n\treturn origin.includes(\"awareness\");\n}\n\nfunction isAwarenessHeartbeat(rec: TimerRecord): boolean {\n\treturn rec.delayMs === AWARENESS_HEARTBEAT_MS && isAwarenessOrigin(rec.origin);\n}\n\n/** Field-by-field difference of two snapshots, for before/after comparisons. */\nexport function diff(before: PerfSnapshot, after: PerfSnapshot) {\n\treturn {\n\t\telapsedMs: after.elapsedMs - before.elapsedMs,\n\t\ttimersFired: after.timers.fired - before.timers.fired,\n\t\tintervalsCreated: after.timers.intervalsCreated - before.timers.intervalsCreated,\n\t\tintervalsLive: after.timers.intervalsLive - before.timers.intervalsLive,\n\t\tawarenessLive: after.awareness.liveInstances - before.awareness.liveInstances,\n\t\theartbeatFires: after.awareness.heartbeatFires - before.awareness.heartbeatFires,\n\t\tframesSent: after.sockets.framesSent - before.sockets.framesSent,\n\t\tbytesSent: after.sockets.bytesSent - before.sockets.bytesSent,\n\t\tidbTransactions: after.indexedDb.transactions - before.indexedDb.transactions,\n\t};\n}\n\n/** Whether counting is currently active. */\nexport function isInstalled(): boolean {\n\treturn installed;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAAA,MAAa,0BACZ,WACI;AACJ,QAAO,MAAM,KAAK,OAAO,SAAS,CAAC,CAAC,KAAK,CAAC,KAAK,WAAW;AACzD,SAAO;GACN,UAAU;GACV,GAAG;GACH;GACA;;;;;ACRH,IAAqB,eAArB,MAAkC;;mBAEiB,EAAE;;CAGpD,AAAO,GAAG,OAAe,IAAoB;AAC5C,MAAI,CAAC,KAAK,UAAU,OACnB,MAAK,UAAU,SAAS,EAAE;AAG3B,OAAK,UAAU,OAAO,KAAK,GAAG;AAE9B,SAAO;;CAIR,AAAO,KAAK,OAAe,IAAoB;EAC9C,MAAM,WAAW,GAAG,SAAgB;AACnC,QAAK,IAAI,OAAO,QAAQ;AACxB,MAAG,MAAM,MAAM,KAAK;;AAErB,SAAO,KAAK,GAAG,OAAO,QAAQ;;CAG/B,AAAU,KAAK,OAAe,GAAG,MAAiB;EACjD,MAAM,YAAY,KAAK,UAAU;AAEjC,MAAI,UACH,MAAK,MAAM,YAAY,UACtB,KAAI;AACH,YAAS,MAAM,MAAM,KAAK;WAClB,KAAK;AACb,WAAQ,MAAM,4BAA4B,MAAM,cAAc,IAAI;;AAKrE,SAAO;;CAIR,AAAO,IAAI,OAAe,IAAqB;EAC9C,MAAM,YAAY,KAAK,UAAU;AAEjC,MAAI,UACH,KAAI,GACH,MAAK,UAAU,SAAS,UAAU,QAAQ,aAAa,aAAa,GAAG;MAEvE,QAAO,KAAK,UAAU;AAIxB,SAAO;;CAGR,qBAA2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