/** * rSplat Local-First Client * * Wraps the shared local-first stack into a splat gallery API. * 3D files stay on the filesystem — only metadata is in Automerge. */ import * as Automerge from '@automerge/automerge'; import { DocumentManager } from '../../shared/local-first/document'; import type { DocumentId } from '../../shared/local-first/document'; import { EncryptedDocStore } from '../../shared/local-first/storage'; import { DocSyncManager } from '../../shared/local-first/sync'; import { DocCrypto } from '../../shared/local-first/crypto'; import { splatScenesSchema, splatScenesDocId } from './schemas'; import type { SplatScenesDoc } from './schemas'; export class SplatLocalFirstClient { #space: string; #documents: DocumentManager; #store: EncryptedDocStore; #sync: DocSyncManager; #initialized = false; constructor(space: string, docCrypto?: DocCrypto) { this.#space = space; this.#documents = new DocumentManager(); this.#store = new EncryptedDocStore(space, docCrypto); this.#sync = new DocSyncManager({ documents: this.#documents, store: this.#store, }); this.#documents.registerSchema(splatScenesSchema); } get isConnected(): boolean { return this.#sync.isConnected; } async init(): Promise { if (this.#initialized) return; await this.#store.open(); const cachedIds = await this.#store.listByModule('splat', 'scenes'); for (const docId of cachedIds) { const binary = await this.#store.load(docId); if (binary) this.#documents.open(docId, splatScenesSchema, binary); } const proto = location.protocol === 'https:' ? 'wss:' : 'ws:'; const wsUrl = `${proto}//${location.host}/ws/${this.#space}`; try { await this.#sync.connect(wsUrl, this.#space); } catch { console.warn('[SplatClient] Working offline'); } this.#initialized = true; } async subscribe(): Promise { const docId = splatScenesDocId(this.#space) as DocumentId; let doc = this.#documents.get(docId); if (!doc) { const binary = await this.#store.load(docId); doc = binary ? this.#documents.open(docId, splatScenesSchema, binary) : this.#documents.open(docId, splatScenesSchema); } await this.#sync.subscribe([docId]); return doc ?? null; } getScenes(): SplatScenesDoc | undefined { return this.#documents.get(splatScenesDocId(this.#space) as DocumentId); } onChange(cb: (doc: SplatScenesDoc) => void): () => void { return this.#sync.onChange(splatScenesDocId(this.#space) as DocumentId, cb as (doc: any) => void); } onConnect(cb: () => void): () => void { return this.#sync.onConnect(cb); } onDisconnect(cb: () => void): () => void { return this.#sync.onDisconnect(cb); } async disconnect(): Promise { await this.#sync.flush(); this.#sync.disconnect(); } }